This is python.info, produced by makeinfo version 6.5 from python.texi.

     Python 3.8.12, 九月 08, 2021

     unknown

     Copyright © 2001-2021, Python Software Foundation

INFO-DIR-SECTION Miscellaneous
START-INFO-DIR-ENTRY
* python: (python.info). One line description of project
END-INFO-DIR-ENTRY


   Generated by Sphinx 2.4.4.


File: python.info,  Node: Top,  Next: Python的新变化,  Up: (dir)

Python
******

     Python 3.8.12, 九月 08, 2021

     unknown

     Copyright © 2001-2021, Python Software Foundation

* Menu:

* Python的新变化::
* Python 教程::
* Python安装和使用::
* Python语言参考::
* Python 标准库::
* 扩展和嵌入 Python 解释器::
* Python/C API 参考手册::
* 分发 Python 模块::
* 安装 Python 模块::
* Python 常用指引::
* Python 常见问题::
* 术语对照表::
* 文档说明::
* 处理错误::
* 版权所有::
* 历史和许可证::
* 分发 Python 模块（遗留版本）::
* 安装Python模块（旧版）::
* Python 模块索引::
* 索引::

 — The Detailed Node Listing —

Python的新变化

* Python 3.8 有什么新变化: Python 3 8 有什么新变化.
* Python 3.7 有什么新变化: Python 3 7 有什么新变化.
* Python 3.6 有什么新变化: Python 3 6 有什么新变化.
* Python 3.5 有什么新变化: Python 3 5 有什么新变化.
* Python 3.4 有什么新变化: Python 3 4 有什么新变化.
* Python 3.3 有什么新变化: Python 3 3 有什么新变化.
* Python 3.2 有什么新变化: Python 3 2 有什么新变化.
* Python 3.1 有什么新变化: Python 3 1 有什么新变化.
* Python 3.0 有什么新变化: Python 3 0 有什么新变化.
* Python 2.7 有什么新变化: Python 2 7 有什么新变化.
* Python 2.6 有什么新变化: Python 2 6 有什么新变化.
* Python 2.5 有什么新变化: Python 2 5 有什么新变化.
* Python 2.4 有什么新变化: Python 2 4 有什么新变化.
* Python 2.3 有什么新变化: Python 2 3 有什么新变化.
* Python 2.2 有什么新变化: Python 2 2 有什么新变化.
* Python 2.1 有什么新变化: Python 2 1 有什么新变化.
* Python 2.0 有什么新变化: Python 2 0 有什么新变化.
* 更新日志::

Python 3.8 有什么新变化

* 摘要 - 发布重点::
* 新的特性::
* 其他语言特性修改::
* 新增模块::
* 改进的模块::
* 性能优化::
* 构建和 C API 的改变::
* 弃用::
* API 与特性的移除::
* 移植到 Python 3.8: 移植到 Python 3 8.
* Python 3.8.1 中的重要变化: Python 3 8 1 中的重要变化.
* Python 3.8.2 中的重要变化: Python 3 8 2 中的重要变化.
* Python 3.8.3 中的重要变化: Python 3 8 3 中的重要变化.
* Python 3.8.8 中的重要变化: Python 3 8 8 中的重要变化.
* Python 3.8.9 中的重要变化: Python 3 8 9 中的重要变化.
* Python 3.8.10 中的重要变化: Python 3 8 10 中的重要变化.
* Python 3.8.10 中的重要变化: Python 3 8 10 中的重要变化<2>.
* Python 3.8.12 中的重要变化: Python 3 8 12 中的重要变化.

新的特性

* 赋值表达式::
* 仅限位置形参::
* 用于已编译字节码文件的并行文件系统缓存::
* 调试构建使用与发布构建相同的 ABI::
* f-字符串支持 = 用于自动记录表达式和调试文档::
* PEP 578; Python 运行时审核钩子: PEP 578 Python 运行时审核钩子.
* PEP 587; Python 初始化配置: PEP 587 Python 初始化配置.
* Vectorcall; 用于 CPython 的快速调用协议: Vectorcall 用于 CPython 的快速调用协议.
* 具有外部数据缓冲区的 pickle 协议 5::

改进的模块

* ast::
* asyncio::
* builtins::
* collections::
* cProfile::
* csv::
* curses::
* ctypes::
* datetime::
* functools::
* gc::
* gettext::
* gzip::
* IDLE 与 idlelib::
* inspect::
* io::
* itertools::
* json.tool: json tool.
* logging::
* math::
* mmap::
* multiprocessing::
* os::
* os.path: os path.
* pathlib::
* pickle::
* plistlib::
* pprint::
* py_compile::
* shlex::
* shutil::
* socket::
* ssl::
* statistics::
* sys::
* tarfile::
* threading::
* tokenize::
* tkinter::
* time::
* typing::
* unicodedata::
* unittest::
* venv::
* weakref::
* xml::
* xmlrpc::

移植到 Python 3.8

* Python 行为的改变::
* Python API 的变化::
* C API 的变化::
* CPython 字节码的改变::
* 演示和工具::

Python 3.8.10 中的重要变化

* macOS 11.0 (Big Sur) 与 Apple Silicon Mac 支持: macOS 11 0 Big Sur 与 Apple Silicon Mac 支持.

Python 3.8.10 中的重要变化

* urllib.parse: urllib parse.

Python 3.8.12 中的重要变化

* Python API 的变化: Python API 的变化<2>.

Python 3.7 有什么新变化

* 摘要 - 发布重点: 摘要 - 发布重点<2>.
* 新的特性: 新的特性<2>.
* 其他语言特性修改: 其他语言特性修改<2>.
* 新增模块: 新增模块<2>.
* 改进的模块: 改进的模块<2>.
* C API 的改变::
* 构建的改变::
* 性能优化: 性能优化<2>.
* 其他 CPython 实现的改变::
* 已弃用的 Python 行为::
* 已弃用的 Python 模块、函数和方法::
* 已弃用的 C API 函数和类型::
* 平台支持的移除::
* API 与特性的移除: API 与特性的移除<2>.
* 移除的模块::
* Windows 专属的改变::
* 移植到 Python 3.7: 移植到 Python 3 7.
* Python 3.7.1 中的重要变化: Python 3 7 1 中的重要变化.
* Python 3.7.2 中的重要变化: Python 3 7 2 中的重要变化.
* Python 3.7.6 中的重要变化: Python 3 7 6 中的重要变化.
* Python 3.7.10 中的重要变化: Python 3 7 10 中的重要变化.

新的特性

* PEP 563：延迟的标注求值::
* PEP 538; 传统 C 区域强制转换: PEP 538 传统 C 区域强制转换.
* PEP 540; 强制 UTF-8 运行时模式: PEP 540 强制 UTF-8 运行时模式.
* PEP 553; 内置的 breakpoint(): PEP 553 内置的 breakpoint.
* PEP 539; 用于线程局部存储的新 C API: PEP 539 用于线程局部存储的新 C API.
* PEP 562; 定制对模块属性的访问: PEP 562 定制对模块属性的访问.
* PEP 564; 具有纳秒级精度的新时间函数: PEP 564 具有纳秒级精度的新时间函数.
* PEP 565; 在 __main__ 中显示 DeprecationWarning: PEP 565 在 __main__ 中显示 DeprecationWarning.
* PEP 560; 对 typing 模块和泛型类型的核心支持: PEP 560 对 typing 模块和泛型类型的核心支持.
* PEP 552; 基于哈希值的 .pyc 文件: PEP 552 基于哈希值的 pyc 文件.
* PEP 545; Python 文档翻译: PEP 545 Python 文档翻译.
* 开发运行时模式; -X dev: 开发运行时模式 -X dev.

新增模块

* contextvars::
* dataclasses::
* importlib.resources: importlib resources.

改进的模块

* argparse::
* asyncio: asyncio<2>.
* binascii::
* calendar::
* collections: collections<2>.
* compileall::
* concurrent.futures: concurrent futures.
* contextlib::
* cProfile: cProfile<2>.
* crypt::
* datetime: datetime<2>.
* dbm::
* decimal::
* dis::
* distutils::
* enum::
* functools: functools<2>.
* gc: gc<2>.
* hmac::
* http.client: http client.
* http.server: http server.
* idlelib 与 IDLE::
* importlib::
* io: io<2>.
* ipaddress::
* itertools: itertools<2>.
* locale::
* logging: logging<2>.
* math: math<2>.
* mimetypes::
* msilib::
* multiprocessing: multiprocessing<2>.
* os: os<2>.
* pathlib: pathlib<2>.
* pdb::
* py_compile: py_compile<2>.
* pydoc::
* queue::
* re::
* signal::
* socket: socket<2>.
* socketserver::
* sqlite3::
* ssl: ssl<2>.
* string::
* subprocess::
* sys: sys<2>.
* time: time<2>.
* tkinter: tkinter<2>.
* tracemalloc::
* types::
* unicodedata: unicodedata<2>.
* unittest: unittest<2>.
* unittest.mock: unittest mock.
* urllib.parse: urllib parse<2>.
* uu::
* uuid::
* warnings::
* xml.etree: xml etree.
* xmlrpc.server: xmlrpc server.
* zipapp::
* zipfile::

已弃用的 Python 模块、函数和方法

* aifc::
* asyncio: asyncio<3>.
* collections: collections<3>.
* dbm: dbm<2>.
* enum: enum<2>.
* gettext: gettext<2>.
* importlib: importlib<2>.
* locale: locale<2>.
* macpath::
* threading: threading<2>.
* socket: socket<3>.
* ssl: ssl<3>.
* sunau::
* sys: sys<3>.
* wave::

移植到 Python 3.7

* Python 行为的更改::
* Python API 的变化: Python API 的变化<3>.
* C API 的变化: C API 的变化<2>.
* CPython 字节码的改变: CPython 字节码的改变<2>.
* Windows 专属的改变: Windows 专属的改变<2>.
* 其他 CPython 实现的改变: 其他 CPython 实现的改变<2>.

Python 3.6 有什么新变化

* 摘要 - 发布重点: 摘要 - 发布重点<3>.
* 新的特性: 新的特性<3>.
* 其他语言特性修改: 其他语言特性修改<3>.
* 新增模块: 新增模块<3>.
* 改进的模块: 改进的模块<3>.
* 性能优化: 性能优化<3>.
* 构建和 C API 的改变: 构建和 C API 的改变<2>.
* 其他改进::
* 弃用: 弃用<2>.
* 移除::
* 移植到Python 3.6: 移植到Python 3 6.
* Python 3.6.2 中的重要变化: Python 3 6 2 中的重要变化.
* Python 3.6.4 中的重要变化: Python 3 6 4 中的重要变化.
* Python 3.6.5 中的重要变化: Python 3 6 5 中的重要变化.
* Python 3.6.7 中的重要变化: Python 3 6 7 中的重要变化.
* Python 3.6.10 中的重要变化: Python 3 6 10 中的重要变化.
* Notable changes in Python 3.6.13: Notable changes in Python 3 6 13.

新的特性

* PEP 498; 格式化的字符串文字: PEP 498 格式化的字符串文字.
* PEP 526; 变量注释的语法: PEP 526 变量注释的语法.
* PEP 515; 数字文字中的下划线。: PEP 515 数字文字中的下划线。.
* PEP 525; 异步生成器: PEP 525 异步生成器.
* PEP 530; 异步推导: PEP 530 异步推导.
* PEP 487; 自定义类创建: PEP 487 自定义类创建.
* PEP 487; 描述器协议的增强: PEP 487 描述器协议的增强.
* PEP 519; 添加文件系统路径协议: PEP 519 添加文件系统路径协议.
* PEP 495; 消除本地时间的歧义: PEP 495 消除本地时间的歧义.
* PEP 529; 将Windows文件系统编码更改为UTF-8: PEP 529 将Windows文件系统编码更改为UTF-8.
* PEP 528; 将Windows控制台编码更改为UTF-8: PEP 528 将Windows控制台编码更改为UTF-8.
* PEP 520; 保留类属性定义顺序: PEP 520 保留类属性定义顺序.
* PEP 468; 保留关键字参数顺序: PEP 468 保留关键字参数顺序.
* 新的 dict 实现::
* PEP 523; 向CPython 添加框架评估API: PEP 523 向CPython 添加框架评估API.
* PYTHONMALLOC 环境变量::
* DTrace 和 SystemTap 探测支持::

新增模块

* secrets::

改进的模块

* array::
* ast: ast<2>.
* asyncio: asyncio<4>.
* binascii: binascii<2>.
* cmath::
* collections: collections<4>.
* concurrent.futures: concurrent futures<2>.
* contextlib: contextlib<2>.
* datetime: datetime<3>.
* decimal: decimal<2>.
* distutils: distutils<2>.
* email::
* encodings::
* enum: enum<3>.
* faulthandler::
* fileinput::
* hashlib::
* http.client: http client<2>.
* idlelib 与 IDLE: idlelib 与 IDLE<2>.
* importlib: importlib<3>.
* inspect: inspect<2>.
* json::
* logging: logging<3>.
* math: math<3>.
* multiprocessing: multiprocessing<3>.
* os: os<3>.
* pathlib: pathlib<3>.
* pdb: pdb<2>.
* pickle: pickle<2>.
* pickletools::
* pydoc: pydoc<2>.
* random::
* re: re<2>.
* readline::
* rlcompleter::
* shlex: shlex<2>.
* site::
* sqlite3: sqlite3<2>.
* socket: socket<4>.
* socketserver: socketserver<2>.
* ssl: ssl<4>.
* statistics: statistics<2>.
* struct::
* subprocess: subprocess<2>.
* sys: sys<4>.
* telnetlib::
* time: time<3>.
* timeit::
* tkinter: tkinter<3>.
* 回溯::
* tracemalloc: tracemalloc<2>.
* typing: typing<2>.
* unicodedata: unicodedata<3>.
* unittest.mock: unittest mock<2>.
* urllib.request: urllib request.
* urllib.robotparser: urllib robotparser.
* venv: venv<2>.
* warnings: warnings<2>.
* winreg::
* winsound::
* xmlrpc.client: xmlrpc client.
* zipfile: zipfile<2>.
* zlib::

弃用

* 新关键字::
* 已弃用的 Python 行为: 已弃用的 Python 行为<2>.
* 已弃用的 Python 模块、函数和方法: 已弃用的 Python 模块、函数和方法<2>.
* 已弃用的 C API 函数和类型: 已弃用的 C API 函数和类型<2>.
* 弃用的构建选项::

已弃用的 Python 模块、函数和方法

* asynchat::
* asyncore::
* dbm: dbm<3>.
* distutils: distutils<3>.
* grp::
* importlib: importlib<4>.
* os: os<4>.
* re: re<3>.
* ssl: ssl<5>.
* tkinter: tkinter<4>.
* venv: venv<3>.

移除

* API 与特性的移除: API 与特性的移除<3>.

移植到Python 3.6

* 'python' 命令行为的变化::
* Python API 的变化: Python API 的变化<4>.
* C API 的变化: C API 的变化<3>.
* CPython 字节码的改变: CPython 字节码的改变<3>.

Python 3.6.2 中的重要变化

* New make regen-all build target::
* Removal of make touch build target::

Python 3.5 有什么新变化

* 摘要 - 发布重点: 摘要 - 发布重点<4>.
* 新的特性: 新的特性<4>.
* 其他语言特性修改: 其他语言特性修改<4>.
* 新增模块: 新增模块<4>.
* 改进的模块: 改进的模块<4>.
* 其他模块级更改::
* 性能优化: 性能优化<4>.
* 构建和 C API 的改变: 构建和 C API 的改变<3>.
* 弃用: 弃用<3>.
* 移除: 移除<2>.
* 移植到Python 3.5: 移植到Python 3 5.
* Python 3.5.4 的显著变化: Python 3 5 4 的显著变化.

新的特性

* PEP 492 - 使用 async 和 await 语法实现协程::
* PEP 465 - 用于矩阵乘法的专用中缀运算符::
* PEP 448 - Additional Unpacking Generalizations::
* PEP 461 - percent formatting support for bytes and bytearray::
* PEP 484 - 类型提示::
* PEP 471 - os.scandir() function: PEP 471 - os scandir function -- a better and faster directory iterator. a better and faster directory iterator
* PEP 475; Retry system calls failing with EINTR: PEP 475 Retry system calls failing with EINTR.
* PEP 479; Change StopIteration handling inside generators: PEP 479 Change StopIteration handling inside generators.
* PEP 485; A function for testing approximate equality: PEP 485 A function for testing approximate equality.
* PEP 486; Make the Python Launcher aware of virtual environments: PEP 486 Make the Python Launcher aware of virtual environments.
* PEP 488; Elimination of PYO files: PEP 488 Elimination of PYO files.
* PEP 489; Multi-phase extension module initialization: PEP 489 Multi-phase extension module initialization.

新增模块

* typing: typing<3>.
* zipapp: zipapp<2>.

改进的模块

* argparse: argparse<2>.
* asyncio: asyncio<5>.
* bz2::
* cgi::
* cmath: cmath<2>.
* code::
* collections: collections<5>.
* collections.abc: collections abc.
* compileall: compileall<2>.
* concurrent.futures: concurrent futures<3>.
* configparser::
* contextlib: contextlib<3>.
* csv: csv<2>.
* curses: curses<2>.
* dbm: dbm<4>.
* difflib::
* distutils: distutils<4>.
* doctest::
* email: email<2>.
* enum: enum<4>.
* faulthandler: faulthandler<2>.
* functools: functools<3>.
* glob::
* gzip: gzip<2>.
* heapq::
* http::
* http.client: http client<3>.
* idlelib 与 IDLE: idlelib 与 IDLE<3>.
* imaplib::
* imghdr::
* importlib: importlib<5>.
* inspect: inspect<3>.
* io: io<3>.
* ipaddress: ipaddress<2>.
* json: json<2>.
* linecache::
* locale: locale<3>.
* logging: logging<4>.
* lzma::
* math: math<4>.
* multiprocessing: multiprocessing<4>.
* operator::
* os: os<5>.
* pathlib: pathlib<4>.
* pickle: pickle<3>.
* poplib::
* re: re<4>.
* readline: readline<2>.
* selectors::
* shutil: shutil<2>.
* signal: signal<2>.
* smtpd::
* smtplib::
* sndhdr::
* socket: socket<5>.
* ssl: ssl<6>.
* sqlite3: sqlite3<3>.
* subprocess: subprocess<3>.
* sys: sys<5>.
* sysconfig::
* tarfile: tarfile<2>.
* threading: threading<3>.
* time: time<4>.
* timeit: timeit<2>.
* tkinter: tkinter<5>.
* 回溯: 回溯<2>.
* types: types<2>.
* unicodedata: unicodedata<4>.
* unittest: unittest<3>.
* unittest.mock: unittest mock<3>.
* urllib::
* wsgiref::
* xmlrpc: xmlrpc<2>.
* xml.sax: xml sax.
* zipfile: zipfile<3>.

ssl

* 内存 BIO 支持::
* Application-Layer Protocol Negotiation Support::
* Other Changes::

弃用

* 新关键字: 新关键字<2>.
* 已弃用的 Python 行为: 已弃用的 Python 行为<3>.
* 不支持的操作系统::
* 已弃用的 Python 模块、函数和方法: 已弃用的 Python 模块、函数和方法<3>.

移除

* API 与特性的移除: API 与特性的移除<4>.

移植到Python 3.5

* Python 行为的改变: Python 行为的改变<2>.
* Python API 的变化: Python API 的变化<5>.
* C API 的变化: C API 的变化<4>.

Python 3.5.4 的显著变化

* New make regen-all build target: New make regen-all build target<2>.
* Removal of make touch build target: Removal of make touch build target<2>.

Python 3.4 有什么新变化

* 摘要 - 发布重点: 摘要 - 发布重点<5>.
* 新的特性: 新的特性<5>.
* 新增模块: 新增模块<5>.
* 改进的模块: 改进的模块<5>.
* CPython Implementation Changes::
* 弃用: 弃用<4>.
* 移除: 移除<3>.
* 移植到 Python 3.4: 移植到 Python 3 4.
* 3.4.3 的变化: 3 4 3 的变化.

新的特性

* PEP 453; Explicit Bootstrapping of PIP in Python Installations: PEP 453 Explicit Bootstrapping of PIP in Python Installations.
* PEP 446; Newly Created File Descriptors Are Non-Inheritable: PEP 446 Newly Created File Descriptors Are Non-Inheritable.
* Improvements to Codec Handling::
* PEP 451; A ModuleSpec Type for the Import System: PEP 451 A ModuleSpec Type for the Import System.
* 其他语言特性修改: 其他语言特性修改<5>.

PEP 453: Explicit Bootstrapping of PIP in Python Installations

* Bootstrapping pip By Default::
* 文档更改::

新增模块

* asyncio: asyncio<6>.
* ensurepip::
* enum: enum<5>.
* pathlib: pathlib<5>.
* selectors: selectors<2>.
* statistics: statistics<3>.
* tracemalloc: tracemalloc<3>.

改进的模块

* abc::
* aifc: aifc<2>.
* argparse: argparse<3>.
* audioop::
* base64::
* collections: collections<6>.
* colorsys::
* contextlib: contextlib<4>.
* dbm: dbm<5>.
* dis: dis<2>.
* doctest: doctest<2>.
* email: email<3>.
* filecmp::
* functools: functools<4>.
* gc: gc<3>.
* glob: glob<2>.
* hashlib: hashlib<2>.
* hmac: hmac<2>.
* html::
* http: http<2>.
* idlelib 与 IDLE: idlelib 与 IDLE<4>.
* importlib: importlib<6>.
* inspect: inspect<4>.
* ipaddress: ipaddress<3>.
* logging: logging<5>.
* marshal::
* mmap: mmap<2>.
* multiprocessing: multiprocessing<5>.
* operator: operator<2>.
* os: os<6>.
* pdb: pdb<3>.
* pickle: pickle<4>.
* plistlib: plistlib<2>.
* poplib: poplib<2>.
* pprint: pprint<2>.
* pty::
* pydoc: pydoc<3>.
* re: re<5>.
* resource::
* select::
* shelve::
* shutil: shutil<3>.
* smtpd: smtpd<2>.
* smtplib: smtplib<2>.
* socket: socket<6>.
* sqlite3: sqlite3<4>.
* ssl: ssl<7>.
* stat::
* struct: struct<2>.
* subprocess: subprocess<4>.
* sunau: sunau<2>.
* sys: sys<6>.
* tarfile: tarfile<3>.
* textwrap::
* threading: threading<4>.
* 回溯: 回溯<3>.
* types: types<3>.
* urllib: urllib<2>.
* unittest: unittest<4>.
* venv: venv<4>.
* wave: wave<2>.
* weakref: weakref<2>.
* xml.etree: xml etree<2>.
* zipfile: zipfile<4>.

CPython Implementation Changes

* PEP 445; Customization of CPython Memory Allocators: PEP 445 Customization of CPython Memory Allocators.
* PEP 442; Safe Object Finalization: PEP 442 Safe Object Finalization.
* PEP 456; Secure and Interchangeable Hash Algorithm: PEP 456 Secure and Interchangeable Hash Algorithm.
* PEP 436; Argument Clinic: PEP 436 Argument Clinic.
* Other Build and C API Changes::
* 其他改进: 其他改进<2>.
* Significant Optimizations::

弃用

* Deprecations in the Python API::
* Deprecated Features::

移除

* 不再支持的操作系统::
* API 与特性的移除: API 与特性的移除<5>.
* Code Cleanups::

移植到 Python 3.4

* ’python’ 命令行为的变化: 'python' 命令行为的变化<2>.
* Python API 的变化: Python API 的变化<6>.
* C API 的变化: C API 的变化<5>.

3.4.3 的变化

* PEP 476; Enabling certificate verification by default for stdlib http clients: PEP 476 Enabling certificate verification by default for stdlib http clients.

Python 3.3 有什么新变化

* 摘要 - 发布重点: 摘要 - 发布重点<6>.
* PEP 405; 虚拟环境: PEP 405 虚拟环境.
* PEP 420; 隐式命名空间包: PEP 420 隐式命名空间包.
* PEP 3118; 新的内存视图实现和缓冲协议文档: PEP 3118 新的内存视图实现和缓冲协议文档.
* PEP 393; 灵活的字符串表示: PEP 393 灵活的字符串表示.
* PEP 397; 适用于Windows的Python启动器: PEP 397 适用于Windows的Python启动器.
* PEP 3151; 重写 OS 和 IO 异常的层次结构: PEP 3151 重写 OS 和 IO 异常的层次结构.
* PEP 380; 委托给子生成器的语法: PEP 380 委托给子生成器的语法.
* PEP 409; 清除异常上下文: PEP 409 清除异常上下文.
* PEP 414; 显式的Unicode文本: PEP 414 显式的Unicode文本.
* PEP 3155; 类和函数的限定名称: PEP 3155 类和函数的限定名称.
* PEP 412; Key-Sharing Dictionary: PEP 412 Key-Sharing Dictionary.
* PEP 362; 函数签名对象: PEP 362 函数签名对象.
* PEP 421; 添加 sys.implementation: PEP 421 添加 sys implementation.
* Using importlib as the Implementation of Import::
* 其他语言特性修改: 其他语言特性修改<6>.
* A Finer-Grained Import Lock::
* Builtin functions and types::
* 新增模块: 新增模块<6>.
* 改进的模块: 改进的模块<6>.
* 性能优化: 性能优化<5>.
* 构建和 C API 的改变: 构建和 C API 的改变<4>.
* 弃用: 弃用<5>.
* 移植到 Python 3.3: 移植到 Python 3 3.

PEP 3118: 新的内存视图实现和缓冲协议文档

* 相关特性::
* API changes::

PEP 393: 灵活的字符串表示

* Functionality::
* Performance and resource usage::

PEP 421: 添加 sys.implementation

* SimpleNamespace::

Using importlib as the Implementation of Import

* New APIs::
* Visible Changes::

新增模块

* faulthandler: faulthandler<3>.
* ipaddress: ipaddress<4>.
* lzma: lzma<2>.

改进的模块

* abc: abc<2>.
* array: array<2>.
* base64: base64<2>.
* binascii: binascii<3>.
* bz2: bz2<2>.
* 编码器::
* collections: collections<7>.
* contextlib: contextlib<5>.
* crypt: crypt<2>.
* curses: curses<3>.
* datetime: datetime<4>.
* decimal: decimal<3>.
* email: email<4>.
* ftplib::
* functools: functools<5>.
* gc: gc<4>.
* hmac: hmac<3>.
* http: http<3>.
* html: html<2>.
* imaplib: imaplib<2>.
* inspect: inspect<5>.
* io: io<4>.
* itertools: itertools<3>.
* logging: logging<6>.
* math: math<5>.
* mmap: mmap<3>.
* multiprocessing: multiprocessing<6>.
* nntplib::
* os: os<7>.
* pdb: pdb<4>.
* pickle: pickle<5>.
* pydoc: pydoc<4>.
* re: re<6>.
* sched::
* select: select<2>.
* shlex: shlex<3>.
* shutil: shutil<4>.
* signal: signal<3>.
* smtpd: smtpd<3>.
* smtplib: smtplib<3>.
* socket: socket<7>.
* socketserver: socketserver<3>.
* sqlite3: sqlite3<5>.
* ssl: ssl<8>.
* stat: stat<2>.
* struct: struct<3>.
* subprocess: subprocess<5>.
* sys: sys<7>.
* tarfile: tarfile<4>.
* tempfile::
* textwrap: textwrap<2>.
* threading: threading<5>.
* time: time<5>.
* types: types<4>.
* unittest: unittest<5>.
* urllib: urllib<3>.
* webbrowser::
* xml.etree.ElementTree: xml etree ElementTree.
* zlib: zlib<2>.

decimal

* 相关特性: 相关特性<2>.
* API changes: API changes<2>.

email

* Policy Framework::
* Provisional Policy with New Header API::
* Other API Changes::

弃用

* 不支持的操作系统: 不支持的操作系统<2>.
* 已弃用的 Python 模块、函数和方法: 已弃用的 Python 模块、函数和方法<4>.
* 已弃用的 C API 函数和类型: 已弃用的 C API 函数和类型<3>.
* 弃用的功能::

移植到 Python 3.3

* Porting Python code::
* Porting C code::
* Building C extensions::
* Command Line Switch Changes::

Python 3.2 有什么新变化

* PEP 384; 定义稳定的ABI: PEP 384 定义稳定的ABI.
* PEP 389; Argparse 命令行解析模块: PEP 389 Argparse 命令行解析模块.
* PEP 391; 基于字典的日志配置: PEP 391 基于字典的日志配置.
* PEP 3148; concurrent.futures 模块: PEP 3148 concurrent futures 模块.
* PEP 3147; PYC 仓库目录: PEP 3147 PYC 仓库目录.
* PEP 3149; ABI Version Tagged .so Files: PEP 3149 ABI Version Tagged so Files.
* PEP 3333; Python Web服务器网关接口v1.0.1: PEP 3333 Python Web服务器网关接口v1 0 1.
* 其他语言特性修改: 其他语言特性修改<7>.
* 新增，改进和弃用的模块::
* 多线程::
* 性能优化: 性能优化<6>.
* Unicode::
* 编解码器::
* 文档::
* IDLE::
* 代码库::
* 构建和 C API 的改变: 构建和 C API 的改变<5>.
* 移植到 Python 3.2: 移植到 Python 3 2.

新增，改进和弃用的模块

* email: email<5>.
* elementtree::
* functools: functools<6>.
* itertools: itertools<4>.
* collections: collections<8>.
* threading: threading<6>.
* datetime 和 time::
* math: math<6>.
* abc: abc<3>.
* io: io<5>.
* reprlib::
* logging: logging<7>.
* csv: csv<3>.
* contextlib: contextlib<6>.
* decimal and fractions::
* ftp::
* popen::
* select: select<3>.
* gzip 和 zipfile::
* tarfile: tarfile<5>.
* hashlib: hashlib<3>.
* ast: ast<3>.
* os: os<8>.
* shutil: shutil<5>.
* sqlite3: sqlite3<6>.
* html: html<3>.
* socket: socket<8>.
* ssl: ssl<9>.
* nntp::
* certificates::
* imaplib: imaplib<3>.
* http.client: http client<4>.
* unittest: unittest<6>.
* random: random<2>.
* poplib: poplib<3>.
* asyncore: asyncore<2>.
* tempfile: tempfile<2>.
* inspect: inspect<6>.
* pydoc: pydoc<5>.
* dis: dis<3>.
* dbm: dbm<6>.
* ctypes: ctypes<2>.
* site: site<2>.
* sysconfig: sysconfig<2>.
* pdb: pdb<5>.
* configparser: configparser<2>.
* urllib.parse: urllib parse<3>.
* mailbox::
* turtledemo::

Python 3.1 有什么新变化

* PEP 372; 有序字典: PEP 372 有序字典.
* PEP 378; 千位分隔符的格式说明符: PEP 378 千位分隔符的格式说明符.
* 其他语言特性修改: 其他语言特性修改<8>.
* 新增，改进和弃用的模块: 新增，改进和弃用的模块<2>.
* 性能优化: 性能优化<7>.
* IDLE: IDLE<2>.
* 构建和 C API 的改变: 构建和 C API 的改变<6>.
* 移植到 Python 3.1: 移植到 Python 3 1.

Python 3.0 有什么新变化

* 常见的绊脚石::
* Overview Of Syntax Changes::
* Changes Already Present In Python 2.6: Changes Already Present In Python 2 6.
* Library Changes::
* PEP 3101; A New Approach To String Formatting: PEP 3101 A New Approach To String Formatting.
* Changes To Exceptions::
* Miscellaneous Other Changes::
* 构建和 C API 的改变: 构建和 C API 的改变<7>.
* 性能::
* 移植到 Python 3.0: 移植到 Python 3 0.

常见的绊脚石

* Print Is A Function::
* Views And Iterators Instead Of Lists::
* Ordering Comparisons::
* 整数::
* Text Vs. Data Instead Of Unicode Vs. 8-bit: Text Vs Data Instead Of Unicode Vs 8-bit.

Overview Of Syntax Changes

* 新语法::
* 修改的语法::
* 移除的语法::

Miscellaneous Other Changes

* Operators And Special Methods::
* Builtins::

Python 2.7 有什么新变化

* Python 2.x的未来: Python 2 x的未来.
* Changes to the Handling of Deprecation Warnings::
* Python 3.1 Features: Python 3 1 Features.
* PEP 372; Adding an Ordered Dictionary to collections: PEP 372 Adding an Ordered Dictionary to collections.
* PEP 378; 千位分隔符的格式说明符: PEP 378 千位分隔符的格式说明符<2>.
* PEP 389; The argparse Module for Parsing Command Lines: PEP 389 The argparse Module for Parsing Command Lines.
* PEP 391; Dictionary-Based Configuration For Logging: PEP 391 Dictionary-Based Configuration For Logging.
* PEP 3106; Dictionary Views: PEP 3106 Dictionary Views.
* PEP 3137; The memoryview Object: PEP 3137 The memoryview Object.
* 其他语言特性修改: 其他语言特性修改<9>.
* 新增和改进的模块::
* 构建和 C API 的改变: 构建和 C API 的改变<8>.
* Other Changes and Fixes::
* 移植到 Python 2.7: 移植到 Python 2 7.
* New Features Added to Python 2.7 Maintenance Releases: New Features Added to Python 2 7 Maintenance Releases.
* 致谢::

其他语言特性修改

* Interpreter Changes::
* 性能优化: 性能优化<8>.

新增和改进的模块

* 新模块：importlib::
* 新模块：sysconfig::
* ttk; Themed Widgets for Tk: ttk Themed Widgets for Tk.
* 更新的模块：unittest::
* 更新的模块：ElementTree 1.3: 更新的模块：ElementTree 1 3.

构建和 C API 的改变

* 胶囊::
* 特定于 Windows 的更改：::
* 特定于 Mac OS X 的更改：::
* 特定于 FreeBSD 的更改：::

New Features Added to Python 2.7 Maintenance Releases

* Two new environment variables for debug mode::
* PEP 434; IDLE Enhancement Exception for All Branches: PEP 434 IDLE Enhancement Exception for All Branches.
* PEP 466; Network Security Enhancements for Python 2.7: PEP 466 Network Security Enhancements for Python 2 7.
* PEP 477; Backport ensurepip (PEP 453) to Python 2.7: PEP 477 Backport ensurepip PEP 453 to Python 2 7.
* PEP 476; Enabling certificate verification by default for stdlib http clients: PEP 476 Enabling certificate verification by default for stdlib http clients<2>.
* PEP 493：适用于Python 2.7 的 HTTPS 验证迁移工具: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具.
* New make regen-all build target: New make regen-all build target<3>.
* Removal of make touch build target: Removal of make touch build target<3>.

PEP 477: Backport ensurepip (PEP 453) to Python 2.7

* Bootstrapping pip By Default: Bootstrapping pip By Default<2>.
* 文档更改: 文档更改<2>.

Python 2.6 有什么新变化

* Python 3.0: Python 3 0.
* 开发过程的变化::
* PEP 343; "with" 语句: PEP 343 "with" 语句.
* PEP 366; 从主模块显式相对导入: PEP 366 从主模块显式相对导入.
* PEP 370; 分用户的 site-packages 目录: PEP 370 分用户的 site-packages 目录.
* PEP 371; 多任务处理包: PEP 371 多任务处理包.
* PEP 3101; 高级字符串格式: PEP 3101 高级字符串格式.
* PEP 3105; print 改为函数: PEP 3105 print 改为函数.
* PEP 3110; 异常处理的变更: PEP 3110 异常处理的变更.
* PEP 3112; 字节字面值: PEP 3112 字节字面值.
* PEP 3116; 新 I/O 库: PEP 3116 新 I/O 库.
* PEP 3118; 修改缓冲区协议: PEP 3118 修改缓冲区协议.
* PEP 3119; 抽象基类: PEP 3119 抽象基类.
* PEP 3127; 整型文字支持和语法: PEP 3127 整型文字支持和语法.
* PEP 3129; 类装饰器: PEP 3129 类装饰器.
* PEP 3141; A Type Hierarchy for Numbers: PEP 3141 A Type Hierarchy for Numbers.
* 其他语言特性修改: 其他语言特性修改<10>.
* 新增和改进的模块: 新增和改进的模块<2>.
* Deprecations and Removals::
* 构建和 C API 的改变: 构建和 C API 的改变<9>.
* 移植到Python 2.6: 移植到Python 2 6.
* 致谢: 致谢<2>.

开发过程的变化

* New Issue Tracker; Roundup: New Issue Tracker Roundup.
* 新的文档格式：使用 Sphinx 的 reStructuredText::

PEP 343: "with" 语句

* Writing Context Managers::
* contextlib 模块::

PEP 3141: A Type Hierarchy for Numbers

* fractions 模块::

其他语言特性修改

* 性能优化: 性能优化<9>.
* Interpreter Changes: Interpreter Changes<2>.

新增和改进的模块

* ast 模块::
* future_builtins 模块::
* The json module; JavaScript Object Notation: The json module JavaScript Object Notation.
* plistlib 模块：属性列表解析器::
* ctypes Enhancements::
* Improved SSL Support::

构建和 C API 的改变

* 特定于 Windows 的更改：: 特定于 Windows 的更改：<2>.
* 特定于 Mac OS X 的更改：: 特定于 Mac OS X 的更改：<2>.
* 特定于 IRIX 的更改：::

Python 2.5 有什么新变化

* PEP 308; 条件表达式: PEP 308 条件表达式.
* PEP 309; 部分功能应用: PEP 309 部分功能应用.
* PEP 314; Python软件包的元数据 v1.1: PEP 314 Python软件包的元数据 v1 1.
* PEP 328; 绝对导入和相对导入: PEP 328 绝对导入和相对导入.
* PEP 338; 将模块作为脚本执行: PEP 338 将模块作为脚本执行.
* PEP 341; 统一 try/except/finally: PEP 341 统一 try/except/finally.
* PEP 342; 生成器的新特性: PEP 342 生成器的新特性.
* PEP 343; "with" 语句: PEP 343 "with" 语句<2>.
* PEP 352; 异常作为新型的类: PEP 352 异常作为新型的类.
* PEP 353; 使用ssize_t作为索引类型: PEP 353 使用ssize_t作为索引类型.
* PEP 357; ’__index__’ 方法: PEP 357 '__index__' 方法.
* 其他语言特性修改: 其他语言特性修改<11>.
* 新增，改进和删除的模块::
* 构建和 C API 的改变: 构建和 C API 的改变<10>.
* 移植到Python 2.5: 移植到Python 2 5.
* 致谢: 致谢<3>.

PEP 343: "with" 语句

* Writing Context Managers: Writing Context Managers<2>.
* contextlib 模块: contextlib 模块<2>.

其他语言特性修改

* 交互解释器变更::
* 性能优化: 性能优化<10>.

新增，改进和删除的模块

* ctypes 包::
* ElementTree 包::
* hashlib 包::
* sqlite3 包::
* wsgiref 包::

构建和 C API 的改变

* Port-Specific Changes::

Python 2.4 有什么新变化

* PEP 218; 内置集合对象: PEP 218 内置集合对象.
* PEP 237; 统一长整数和整数: PEP 237 统一长整数和整数.
* PEP 289; 生成器表达式: PEP 289 生成器表达式.
* PEP 292; Simpler String Substitutions: PEP 292 Simpler String Substitutions.
* PEP 318; Decorators for Functions and Methods: PEP 318 Decorators for Functions and Methods.
* PEP 322; 反向迭代: PEP 322 反向迭代.
* PEP 324; 新的子进程模块: PEP 324 新的子进程模块.
* PEP 327; 十进制数据类型: PEP 327 十进制数据类型.
* PEP 328; 多行导入: PEP 328 多行导入.
* PEP 331; Locale-Independent Float/String Conversions: PEP 331 Locale-Independent Float/String Conversions.
* 其他语言特性修改: 其他语言特性修改<12>.
* 新增，改进和弃用的模块: 新增，改进和弃用的模块<3>.
* 构建和 C API 的改变: 构建和 C API 的改变<11>.
* 移植到 Python 2.4: 移植到 Python 2 4.
* 致谢: 致谢<4>.

PEP 327: 十进制数据类型

* 为什么需要十进制？::
* Decimal 类型::
* Context 类型::

其他语言特性修改

* 性能优化: 性能优化<11>.

新增，改进和弃用的模块

* cookielib::
* doctest: doctest<3>.

构建和 C API 的改变

* Port-Specific Changes: Port-Specific Changes<2>.

Python 2.3 有什么新变化

* PEP 218; A Standard Set Datatype: PEP 218 A Standard Set Datatype.
* PEP 255; Simple Generators: PEP 255 Simple Generators.
* PEP 263; Source Code Encodings: PEP 263 Source Code Encodings.
* PEP 273; 从ZIP压缩包导入模块: PEP 273 从ZIP压缩包导入模块.
* PEP 277; Unicode file name support for Windows NT: PEP 277 Unicode file name support for Windows NT.
* PEP 278; 通用换行支持: PEP 278 通用换行支持.
* PEP 279; enumerate(): PEP 279 enumerate.
* PEP 282; logging 包: PEP 282 logging 包.
* PEP 285; 布尔类型: PEP 285 布尔类型.
* PEP 293; Codec Error Handling Callbacks: PEP 293 Codec Error Handling Callbacks.
* PEP 301; Distutils的软件包索引和元数据: PEP 301 Distutils的软件包索引和元数据.
* PEP 302; New Import Hooks: PEP 302 New Import Hooks.
* PEP 305; 逗号分隔文件: PEP 305 逗号分隔文件.
* PEP 307; Pickle Enhancements: PEP 307 Pickle Enhancements.
* 扩展切片::
* 其他语言特性修改: 其他语言特性修改<13>.
* 新增，改进和弃用的模块: 新增，改进和弃用的模块<4>.
* Pymalloc; A Specialized Object Allocator: Pymalloc A Specialized Object Allocator.
* 构建和 C API 的改变: 构建和 C API 的改变<12>.
* Other Changes and Fixes: Other Changes and Fixes<2>.
* 移植到 Python 2.3: 移植到 Python 2 3.
* 致谢: 致谢<5>.

其他语言特性修改

* String Changes::
* 性能优化: 性能优化<12>.

新增，改进和弃用的模块

* Date/Time 类型::
* optparse 模块::

构建和 C API 的改变

* Port-Specific Changes: Port-Specific Changes<3>.

Python 2.2 有什么新变化

* 概述::
* PEPs 252 and 253; Type and Class Changes: PEPs 252 and 253 Type and Class Changes.
* PEP 234; Iterators: PEP 234 Iterators.
* PEP 255; Simple Generators: PEP 255 Simple Generators<2>.
* PEP 237; 统一长整数和整数: PEP 237 统一长整数和整数<2>.
* PEP 238; Changing the Division Operator: PEP 238 Changing the Division Operator.
* Unicode Changes::
* PEP 227; Nested Scopes: PEP 227 Nested Scopes.
* 新增和改进的模块: 新增和改进的模块<3>.
* Interpreter Changes and Fixes::
* Other Changes and Fixes: Other Changes and Fixes<3>.
* 致谢: 致谢<6>.

PEPs 252 and 253: Type and Class Changes

* Old and New Classes::
* Descriptors::
* Multiple Inheritance; The Diamond Rule: Multiple Inheritance The Diamond Rule.
* Attribute Access::
* Related Links::

Python 2.1 有什么新变化

* 概述: 概述<2>.
* PEP 227; Nested Scopes: PEP 227 Nested Scopes<2>.
* PEP 236; __future__ Directives: PEP 236 __future__ Directives.
* PEP 207; Rich Comparisons: PEP 207 Rich Comparisons.
* PEP 230; Warning Framework: PEP 230 Warning Framework.
* PEP 229; New Build System: PEP 229 New Build System.
* PEP 205; Weak References: PEP 205 Weak References.
* PEP 232; Function Attributes: PEP 232 Function Attributes.
* PEP 235; Importing Modules on Case-Insensitive Platforms: PEP 235 Importing Modules on Case-Insensitive Platforms.
* PEP 217; Interactive Display Hook: PEP 217 Interactive Display Hook.
* PEP 208; New Coercion Model: PEP 208 New Coercion Model.
* PEP 241; Metadata in Python Packages: PEP 241 Metadata in Python Packages.
* 新增和改进的模块: 新增和改进的模块<4>.
* Other Changes and Fixes: Other Changes and Fixes<4>.
* 致谢: 致谢<7>.

Python 2.0 有什么新变化

* 概述: 概述<3>.
* What About Python 1.6?: What About Python 1 6?.
* 新开发流程::
* Unicode: Unicode<2>.
* 列表推导式::
* Augmented Assignment::
* 字符串的方法::
* Garbage Collection of Cycles::
* 其他核心变化::
* 移植 Python 2.0: 移植 Python 2 0.
* 扩展/嵌入更改::
* Distutils：使模块易于安装::
* XML 模块::
* 模块更改::
* 新增模块: 新增模块<7>.
* IDLE 改进::
* 删除和弃用的模块::
* 致谢: 致谢<8>.

其他核心变化

* Minor Language Changes::
* Changes to Built-in Functions::

XML 模块

* SAX2 Support::
* DOM Support::
* Relationship to PyXML::

更新日志

* Python 3.8.12 final: Python 3 8 12 final.
* 最终版本Python 3.8.11: 最终版本Python 3 8 11.
* Python 3.8.10 final: Python 3 8 10 final.
* Python 3.8.9 final: Python 3 8 9 final.
* Python 3.8.8 final: Python 3 8 8 final.
* Python 3.8.8 rc1: Python 3 8 8 rc1.
* Python 3.8.7 final: Python 3 8 7 final.
* Python 3.8.7 release candidate 1: Python 3 8 7 release candidate 1.
* Python 3.8.6 final: Python 3 8 6 final.
* Python 3.8.6 release candidate 1: Python 3 8 6 release candidate 1.
* Python 3.8.5 final: Python 3 8 5 final.
* Python 3.8.4 final: Python 3 8 4 final.
* Python 3.8.4 release candidate 1: Python 3 8 4 release candidate 1.
* Python 3.8.3 final: Python 3 8 3 final.
* Python 3.8.3 release candidate 1: Python 3 8 3 release candidate 1.
* Python 3.8.2 正式版: Python 3 8 2 正式版.
* Python 3.8.2 rc2: Python 3 8 2 rc2.
* Python 3.8.2 rc1: Python 3 8 2 rc1.
* Python 3.8.1 正式版: Python 3 8 1 正式版.
* Python 3.8.1 rc1: Python 3 8 1 rc1.
* Python 3.8.0 正式版: Python 3 8 0 正式版.
* Python 3.8.0 rc1: Python 3 8 0 rc1.
* Python 3.8.0 beta 4: Python 3 8 0 beta 4.
* Python 3.8.0 beta 3: Python 3 8 0 beta 3.
* Python 3.8.0 beta 2: Python 3 8 0 beta 2.
* Python 3.8.0 beta 1: Python 3 8 0 beta 1.
* Python 3.8.0 alpha 4: Python 3 8 0 alpha 4.
* Python 3.8.0 alpha 3: Python 3 8 0 alpha 3.
* Python 3.8.0 alpha 2: Python 3 8 0 alpha 2.
* Python 3.8.0 alpha 1: Python 3 8 0 alpha 1.
* Python 3.7.0 正式版: Python 3 7 0 正式版.
* Python 3.7.0 rc1: Python 3 7 0 rc1.
* Python 3.7.0 beta 5: Python 3 7 0 beta 5.
* Python 3.7.0 beta 4: Python 3 7 0 beta 4.
* Python 3.7.0 beta 3: Python 3 7 0 beta 3.
* Python 3.7.0 beta 2: Python 3 7 0 beta 2.
* Python 3.7.0 beta 1: Python 3 7 0 beta 1.
* Python 3.7.0 alpha 4: Python 3 7 0 alpha 4.
* Python 3.7.0 alpha 3: Python 3 7 0 alpha 3.
* Python 3.7.0 alpha 2: Python 3 7 0 alpha 2.
* Python 3.7.0 alpha 1: Python 3 7 0 alpha 1.
* Python 3.6.6 正式版: Python 3 6 6 正式版.
* Python 3.6.6 rc1: Python 3 6 6 rc1.
* Python 3.6.5 正式版: Python 3 6 5 正式版.
* Python 3.6.5 rc1: Python 3 6 5 rc1.
* Python 3.6.4 正式版: Python 3 6 4 正式版.
* Python 3.6.4 rc1: Python 3 6 4 rc1.
* Python 3.6.3 正式版: Python 3 6 3 正式版.
* Python 3.6.3 rc1: Python 3 6 3 rc1.
* Python 3.6.2 正式版: Python 3 6 2 正式版.
* Python 3.6.2 rc2: Python 3 6 2 rc2.
* Python 3.6.2 rc1: Python 3 6 2 rc1.
* Python 3.6.1 正式版: Python 3 6 1 正式版.
* Python 3.6.1 rc1: Python 3 6 1 rc1.
* Python 3.6.0 正式版: Python 3 6 0 正式版.
* Python 3.6.0 rc2: Python 3 6 0 rc2.
* Python 3.6.0 rc1: Python 3 6 0 rc1.
* Python 3.6.0 beta 4: Python 3 6 0 beta 4.
* Python 3.6.0 beta 3: Python 3 6 0 beta 3.
* Python 3.6.0 beta 2: Python 3 6 0 beta 2.
* Python 3.6.0 beta 1: Python 3 6 0 beta 1.
* Python 3.6.0 alpha 4: Python 3 6 0 alpha 4.
* Python 3.6.0 alpha 3: Python 3 6 0 alpha 3.
* Python 3.6.0 alpha 2: Python 3 6 0 alpha 2.
* Python 3.6.0 alpha 1: Python 3 6 0 alpha 1.
* Python 3.5.5 正式版: Python 3 5 5 正式版.
* Python 3.5.5 rc1: Python 3 5 5 rc1.
* Python 3.5.4 正式版: Python 3 5 4 正式版.
* Python 3.5.4 rc1: Python 3 5 4 rc1.
* Python 3.5.3 正式版: Python 3 5 3 正式版.
* Python 3.5.3 rc1: Python 3 5 3 rc1.
* Python 3.5.2 正式版: Python 3 5 2 正式版.
* Python 3.5.2 rc1: Python 3 5 2 rc1.
* Python 3.5.1 正式版: Python 3 5 1 正式版.
* Python 3.5.1 rc1: Python 3 5 1 rc1.
* Python 3.5.0 正式版: Python 3 5 0 正式版.
* Python 3.5.0 rc4: Python 3 5 0 rc4.
* Python 3.5.0 rc3: Python 3 5 0 rc3.
* Python 3.5.0 rc2: Python 3 5 0 rc2.
* Python 3.5.0 rc1: Python 3 5 0 rc1.
* Python 3.5.0 beta 4: Python 3 5 0 beta 4.
* Python 3.5.0 beta 3: Python 3 5 0 beta 3.
* Python 3.5.0 beta 2: Python 3 5 0 beta 2.
* Python 3.5.0 beta 1: Python 3 5 0 beta 1.
* Python 3.5.0 alpha 4: Python 3 5 0 alpha 4.
* Python 3.5.0 alpha 3: Python 3 5 0 alpha 3.
* Python 3.5.0 alpha 2: Python 3 5 0 alpha 2.
* Python 3.5.0 alpha 1: Python 3 5 0 alpha 1.

Python 3.8.12 final

* 安全::
* 核心与内置::
* 库::
* 文档: 文档<2>.
* Windows::
* macOS::

最终版本Python 3.8.11

* 安全: 安全<2>.
* 核心与内置: 核心与内置<2>.
* 库: 库<2>.

Python 3.8.10 final

* 安全: 安全<3>.
* 核心与内置: 核心与内置<3>.
* 库: 库<3>.
* 文档: 文档<3>.
* 测试::
* Windows: Windows<2>.
* macOS: macOS<2>.
* IDLE: IDLE<3>.
* C API::

Python 3.8.9 final

* 安全: 安全<4>.
* 核心与内置: 核心与内置<4>.
* 库: 库<4>.
* 文档: 文档<4>.
* 测试: 测试<2>.
* 构建::
* macOS: macOS<3>.
* IDLE: IDLE<4>.

Python 3.8.8 rc1

* 安全: 安全<5>.
* 核心与内置: 核心与内置<5>.
* 库: 库<5>.
* 文档: 文档<5>.
* 测试: 测试<3>.
* 构建: 构建<2>.
* Windows: Windows<3>.
* macOS: macOS<4>.
* IDLE: IDLE<5>.
* 工具/示例::
* C API: C API<2>.

Python 3.8.7 final

* 核心与内置: 核心与内置<6>.
* 库: 库<6>.
* 文档: 文档<6>.
* 构建: 构建<3>.
* 工具/示例: 工具/示例<2>.

Python 3.8.7 release candidate 1

* 安全: 安全<6>.
* 核心与内置: 核心与内置<7>.
* 库: 库<7>.
* 文档: 文档<7>.
* 测试: 测试<4>.
* 构建: 构建<4>.
* Windows: Windows<4>.
* macOS: macOS<5>.
* IDLE: IDLE<6>.
* C API: C API<3>.

Python 3.8.6 final

* 核心与内置: 核心与内置<8>.
* 库: 库<8>.
* 文档: 文档<8>.
* 测试: 测试<5>.
* Windows: Windows<5>.
* IDLE: IDLE<7>.

Python 3.8.6 release candidate 1

* 核心与内置: 核心与内置<9>.
* 库: 库<9>.
* 文档: 文档<9>.
* Windows: Windows<6>.
* IDLE: IDLE<8>.
* C API: C API<4>.

Python 3.8.5 final

* 安全: 安全<7>.
* 核心与内置: 核心与内置<10>.
* 库: 库<10>.
* 文档: 文档<10>.
* 构建: 构建<5>.
* macOS: macOS<6>.
* IDLE: IDLE<9>.

Python 3.8.4 final

* 安全: 安全<8>.
* 核心与内置: 核心与内置<11>.
* 库: 库<11>.
* IDLE: IDLE<10>.

Python 3.8.4 release candidate 1

* 安全: 安全<9>.
* 核心与内置: 核心与内置<12>.
* 库: 库<12>.
* 测试: 测试<6>.
* 构建: 构建<6>.
* Windows: Windows<7>.
* macOS: macOS<7>.
* IDLE: IDLE<11>.
* 工具/示例: 工具/示例<3>.

Python 3.8.3 final

* 核心与内置: 核心与内置<13>.
* 库: 库<13>.
* 文档: 文档<11>.
* Windows: Windows<8>.
* C API: C API<5>.

Python 3.8.3 release candidate 1

* 安全: 安全<10>.
* 核心与内置: 核心与内置<14>.
* 库: 库<14>.
* 文档: 文档<12>.
* 测试: 测试<7>.
* 构建: 构建<7>.
* Windows: Windows<9>.
* macOS: macOS<8>.
* IDLE: IDLE<12>.
* 工具/示例: 工具/示例<4>.
* C API: C API<6>.

Python 3.8.2 正式版

* 核心与内置: 核心与内置<15>.
* 库: 库<15>.
* 文档: 文档<13>.
* IDLE: IDLE<13>.

Python 3.8.2 rc2

* 安全: 安全<11>.
* 核心与内置: 核心与内置<16>.
* 库: 库<16>.
* IDLE: IDLE<14>.

Python 3.8.2 rc1

* 安全: 安全<12>.
* 核心与内置: 核心与内置<17>.
* 库: 库<17>.
* 文档: 文档<14>.
* 测试: 测试<8>.
* 构建: 构建<8>.
* Windows: Windows<10>.
* IDLE: IDLE<15>.

Python 3.8.1 正式版

* 核心与内置: 核心与内置<18>.
* 库: 库<18>.
* 测试: 测试<9>.
* Windows: Windows<11>.
* macOS: macOS<9>.
* IDLE: IDLE<16>.

Python 3.8.1 rc1

* 安全: 安全<13>.
* 核心与内置: 核心与内置<19>.
* 库: 库<19>.
* 文档: 文档<15>.
* 测试: 测试<10>.
* 构建: 构建<9>.
* Windows: Windows<12>.
* macOS: macOS<10>.
* IDLE: IDLE<17>.
* C API: C API<7>.

Python 3.8.0 正式版

* 核心与内置: 核心与内置<20>.
* 库: 库<20>.
* 文档: 文档<16>.
* 测试: 测试<11>.
* Windows: Windows<13>.
* IDLE: IDLE<18>.
* 工具/示例: 工具/示例<5>.
* C API: C API<8>.

Python 3.8.0 rc1

* 安全: 安全<14>.
* 核心与内置: 核心与内置<21>.
* 库: 库<21>.
* 文档: 文档<17>.
* 测试: 测试<12>.
* 构建: 构建<10>.
* Windows: Windows<14>.
* macOS: macOS<11>.
* IDLE: IDLE<19>.
* 工具/示例: 工具/示例<6>.
* C API: C API<9>.

Python 3.8.0 beta 4

* 安全: 安全<15>.
* 核心与内置: 核心与内置<22>.
* 库: 库<22>.
* 文档: 文档<18>.
* 测试: 测试<13>.
* 构建: 构建<11>.
* Windows: Windows<15>.
* macOS: macOS<12>.
* IDLE: IDLE<20>.
* 工具/示例: 工具/示例<7>.
* C API: C API<10>.

Python 3.8.0 beta 3

* 安全: 安全<16>.
* 核心与内置: 核心与内置<23>.
* 库: 库<23>.
* 文档: 文档<19>.
* 测试: 测试<14>.
* 构建: 构建<12>.
* Windows: Windows<16>.
* IDLE: IDLE<21>.
* 工具/示例: 工具/示例<8>.

Python 3.8.0 beta 2

* 安全: 安全<17>.
* 核心与内置: 核心与内置<24>.
* 库: 库<24>.
* 文档: 文档<20>.
* 测试: 测试<15>.
* 构建: 构建<13>.
* Windows: Windows<17>.
* macOS: macOS<13>.
* IDLE: IDLE<22>.
* C API: C API<11>.

Python 3.8.0 beta 1

* 安全: 安全<18>.
* 核心与内置: 核心与内置<25>.
* 库: 库<25>.
* 文档: 文档<21>.
* 测试: 测试<16>.
* 构建: 构建<14>.
* Windows: Windows<18>.
* macOS: macOS<14>.
* IDLE: IDLE<23>.
* 工具/示例: 工具/示例<9>.
* C API: C API<12>.

Python 3.8.0 alpha 4

* 安全: 安全<19>.
* 核心与内置: 核心与内置<26>.
* 库: 库<26>.
* 文档: 文档<22>.
* 测试: 测试<17>.
* 构建: 构建<15>.
* Windows: Windows<19>.
* macOS: macOS<15>.
* IDLE: IDLE<24>.
* 工具/示例: 工具/示例<10>.
* C API: C API<13>.

Python 3.8.0 alpha 3

* 安全: 安全<20>.
* 核心与内置: 核心与内置<27>.
* 库: 库<27>.
* 文档: 文档<23>.
* 测试: 测试<18>.
* 构建: 构建<16>.
* Windows: Windows<20>.
* IDLE: IDLE<25>.
* 工具/示例: 工具/示例<11>.
* C API: C API<14>.

Python 3.8.0 alpha 2

* 核心与内置: 核心与内置<28>.
* 库: 库<28>.
* 文档: 文档<24>.
* 测试: 测试<19>.
* Windows: Windows<21>.
* IDLE: IDLE<26>.

Python 3.8.0 alpha 1

* 安全: 安全<21>.
* 核心与内置: 核心与内置<29>.
* 库: 库<29>.
* 文档: 文档<25>.
* 测试: 测试<20>.
* 构建: 构建<17>.
* Windows: Windows<22>.
* macOS: macOS<16>.
* IDLE: IDLE<27>.
* 工具/示例: 工具/示例<12>.
* C API: C API<15>.

Python 3.7.0 正式版

* 库: 库<30>.
* C API: C API<16>.

Python 3.7.0 rc1

* 核心与内置: 核心与内置<30>.
* 库: 库<31>.
* 文档: 文档<26>.
* 构建: 构建<18>.
* Windows: Windows<23>.
* IDLE: IDLE<28>.

Python 3.7.0 beta 5

* 核心与内置: 核心与内置<31>.
* 库: 库<32>.
* 文档: 文档<27>.
* 测试: 测试<21>.
* 构建: 构建<19>.
* macOS: macOS<17>.
* IDLE: IDLE<29>.

Python 3.7.0 beta 4

* 核心与内置: 核心与内置<32>.
* 库: 库<33>.
* 文档: 文档<28>.
* 测试: 测试<22>.
* 构建: 构建<20>.
* Windows: Windows<24>.
* macOS: macOS<18>.
* IDLE: IDLE<30>.
* 工具/示例: 工具/示例<13>.

Python 3.7.0 beta 3

* 安全: 安全<22>.
* 核心与内置: 核心与内置<33>.
* 库: 库<34>.
* 文档: 文档<29>.
* 测试: 测试<23>.
* 构建: 构建<21>.
* Windows: Windows<25>.
* macOS: macOS<19>.
* IDLE: IDLE<31>.
* 工具/示例: 工具/示例<14>.
* C API: C API<17>.

Python 3.7.0 beta 2

* 安全: 安全<23>.
* 核心与内置: 核心与内置<34>.
* 库: 库<35>.
* 文档: 文档<30>.
* 测试: 测试<24>.
* 构建: 构建<22>.
* Windows: Windows<26>.
* macOS: macOS<20>.
* IDLE: IDLE<32>.
* 工具/示例: 工具/示例<15>.

Python 3.7.0 beta 1

* 核心与内置: 核心与内置<35>.
* 库: 库<36>.
* 文档: 文档<31>.
* 测试: 测试<25>.
* 构建: 构建<23>.
* Windows: Windows<27>.
* macOS: macOS<21>.
* C API: C API<18>.

Python 3.7.0 alpha 4

* 核心与内置: 核心与内置<36>.
* 库: 库<37>.
* 文档: 文档<32>.
* 测试: 测试<26>.
* Windows: Windows<28>.
* 工具/示例: 工具/示例<16>.
* C API: C API<19>.

Python 3.7.0 alpha 3

* 核心与内置: 核心与内置<37>.
* 库: 库<38>.
* 文档: 文档<33>.
* 测试: 测试<27>.
* 构建: 构建<24>.
* Windows: Windows<29>.
* macOS: macOS<22>.
* IDLE: IDLE<33>.
* 工具/示例: 工具/示例<17>.
* C API: C API<20>.

Python 3.7.0 alpha 2

* 核心与内置: 核心与内置<38>.
* 库: 库<39>.
* 文档: 文档<34>.
* 构建: 构建<25>.
* IDLE: IDLE<34>.
* C API: C API<21>.

Python 3.7.0 alpha 1

* 安全: 安全<24>.
* 核心与内置: 核心与内置<39>.
* 库: 库<40>.
* 文档: 文档<35>.
* 测试: 测试<28>.
* 构建: 构建<26>.
* Windows: Windows<30>.
* IDLE: IDLE<35>.
* 工具/示例: 工具/示例<18>.
* C API: C API<22>.

Python 3.6.6 rc1

* 核心与内置: 核心与内置<40>.
* 库: 库<41>.
* 文档: 文档<36>.
* 测试: 测试<29>.
* 构建: 构建<27>.
* Windows: Windows<31>.
* macOS: macOS<23>.
* IDLE: IDLE<36>.
* 工具/示例: 工具/示例<19>.
* C API: C API<23>.

Python 3.6.5 正式版

* 测试: 测试<30>.
* 构建: 构建<28>.

Python 3.6.5 rc1

* 安全: 安全<25>.
* 核心与内置: 核心与内置<41>.
* 库: 库<42>.
* 文档: 文档<37>.
* 测试: 测试<31>.
* 构建: 构建<29>.
* Windows: Windows<32>.
* macOS: macOS<24>.
* IDLE: IDLE<37>.
* 工具/示例: 工具/示例<20>.
* C API: C API<24>.

Python 3.6.4 rc1

* 核心与内置: 核心与内置<42>.
* 库: 库<43>.
* 文档: 文档<38>.
* 测试: 测试<32>.
* 构建: 构建<30>.
* Windows: Windows<33>.
* macOS: macOS<25>.
* IDLE: IDLE<38>.
* 工具/示例: 工具/示例<21>.
* C API: C API<25>.

Python 3.6.3 正式版

* 库: 库<44>.
* 构建: 构建<31>.

Python 3.6.3 rc1

* 安全: 安全<26>.
* 核心与内置: 核心与内置<43>.
* 库: 库<45>.
* 文档: 文档<39>.
* 测试: 测试<33>.
* 构建: 构建<32>.
* Windows: Windows<34>.
* IDLE: IDLE<39>.
* 工具/示例: 工具/示例<22>.

Python 3.6.2 rc2

* 安全: 安全<27>.

Python 3.6.2 rc1

* 核心与内置: 核心与内置<44>.
* 库: 库<46>.
* 安全: 安全<28>.
* 库: 库<47>.
* IDLE: IDLE<40>.
* C API: C API<26>.
* 构建: 构建<33>.
* 文档: 文档<40>.
* 工具/示例: 工具/示例<23>.
* 测试: 测试<34>.
* Windows: Windows<35>.

Python 3.6.1 正式版

* 核心与内置: 核心与内置<45>.
* 构建: 构建<34>.

Python 3.6.1 rc1

* 核心与内置: 核心与内置<46>.
* 库: 库<48>.
* IDLE: IDLE<41>.
* Windows: Windows<36>.
* C API: C API<27>.
* 文档: 文档<41>.
* 测试: 测试<35>.
* 构建: 构建<35>.

Python 3.6.0 rc2

* 核心与内置: 核心与内置<47>.
* 工具/示例: 工具/示例<24>.
* Windows: Windows<37>.
* 构建: 构建<36>.

Python 3.6.0 rc1

* 核心与内置: 核心与内置<48>.
* 库: 库<49>.
* C API: C API<28>.
* 文档: 文档<42>.
* 工具/示例: 工具/示例<25>.

Python 3.6.0 beta 4

* 核心与内置: 核心与内置<49>.
* 库: 库<50>.
* 文档: 文档<43>.
* 测试: 测试<36>.
* 构建: 构建<37>.

Python 3.6.0 beta 3

* 核心与内置: 核心与内置<50>.
* 库: 库<51>.
* Windows: Windows<38>.
* 构建: 构建<38>.
* 测试: 测试<37>.

Python 3.6.0 beta 2

* 核心与内置: 核心与内置<51>.
* 库: 库<52>.
* Windows: Windows<39>.
* C API: C API<29>.
* 构建: 构建<39>.
* 测试: 测试<38>.

Python 3.6.0 beta 1

* 核心与内置: 核心与内置<52>.
* 库: 库<53>.
* IDLE: IDLE<42>.
* C API: C API<30>.
* 测试: 测试<39>.
* 构建: 构建<40>.
* 工具/示例: 工具/示例<26>.
* Windows: Windows<40>.

Python 3.6.0 alpha 4

* 核心与内置: 核心与内置<53>.
* 库: 库<54>.
* IDLE: IDLE<43>.
* 测试: 测试<40>.
* Windows: Windows<41>.
* 构建: 构建<41>.

Python 3.6.0 alpha 3

* 核心与内置: 核心与内置<54>.
* 库: 库<55>.
* 安全: 安全<29>.
* 库: 库<56>.
* 安全: 安全<30>.
* 库: 库<57>.
* IDLE: IDLE<44>.
* C API: C API<31>.
* 构建: 构建<42>.
* 工具/示例: 工具/示例<27>.
* 文档: 文档<44>.
* 测试: 测试<41>.

Python 3.6.0 alpha 2

* 核心与内置: 核心与内置<55>.
* 库: 库<58>.
* 安全: 安全<31>.
* 库: 库<59>.
* 安全: 安全<32>.
* 库: 库<60>.
* IDLE: IDLE<45>.
* 文档: 文档<45>.
* 测试: 测试<42>.
* Windows: Windows<42>.
* 构建: 构建<43>.
* Windows: Windows<43>.
* C API: C API<32>.
* 工具/示例: 工具/示例<28>.

Python 3.6.0 alpha 1

* 核心与内置: 核心与内置<56>.
* 库: 库<61>.
* 安全: 安全<33>.
* 库: 库<62>.
* 安全: 安全<34>.
* 库: 库<63>.
* 安全: 安全<35>.
* 库: 库<64>.
* IDLE: IDLE<46>.
* 文档: 文档<46>.
* 测试: 测试<43>.
* 构建: 构建<44>.
* Windows: Windows<44>.
* 工具/示例: 工具/示例<29>.
* C API: C API<33>.

Python 3.5.5 rc1

* 安全: 安全<36>.
* 核心与内置: 核心与内置<57>.
* 库: 库<65>.

Python 3.5.4 正式版

* 库: 库<66>.

Python 3.5.4 rc1

* 安全: 安全<37>.
* 核心与内置: 核心与内置<58>.
* 库: 库<67>.
* 文档: 文档<47>.
* 测试: 测试<44>.
* 构建: 构建<45>.
* Windows: Windows<45>.
* C API: C API<34>.

Python 3.5.3 rc1

* 核心与内置: 核心与内置<59>.
* 库: 库<68>.
* 安全: 安全<38>.
* 库: 库<69>.
* 安全: 安全<39>.
* 库: 库<70>.
* IDLE: IDLE<47>.
* C API: C API<35>.
* 文档: 文档<48>.
* 测试: 测试<45>.
* 工具/示例: 工具/示例<30>.
* Windows: Windows<46>.
* 构建: 构建<46>.

Python 3.5.2 正式版

* 核心与内置: 核心与内置<60>.
* 测试: 测试<46>.
* IDLE: IDLE<48>.

Python 3.5.2 rc1

* 核心与内置: 核心与内置<61>.
* 安全: 安全<40>.
* 库: 库<71>.
* 安全: 安全<41>.
* 库: 库<72>.
* 安全: 安全<42>.
* 库: 库<73>.
* 安全: 安全<43>.
* 库: 库<74>.
* 安全: 安全<44>.
* 库: 库<75>.
* IDLE: IDLE<49>.
* 文档: 文档<49>.
* 测试: 测试<47>.
* 构建: 构建<47>.
* Windows: Windows<47>.
* 工具/示例: 工具/示例<31>.
* Windows: Windows<48>.

Python 3.5.1 正式版

* 核心与内置: 核心与内置<62>.
* Windows: Windows<49>.

Python 3.5.1 rc1

* 核心与内置: 核心与内置<63>.
* 库: 库<76>.
* IDLE: IDLE<50>.
* 文档: 文档<50>.
* 测试: 测试<48>.
* 构建: 构建<48>.
* Windows: Windows<50>.
* 工具/示例: 工具/示例<32>.

Python 3.5.0 正式版

* 构建: 构建<49>.

Python 3.5.0 rc4

* 库: 库<77>.
* 构建: 构建<50>.

Python 3.5.0 rc3

* 核心与内置: 核心与内置<64>.
* 库: 库<78>.

Python 3.5.0 rc2

* 核心与内置: 核心与内置<65>.
* 库: 库<79>.

Python 3.5.0 rc1

* 核心与内置: 核心与内置<66>.
* 库: 库<80>.
* IDLE: IDLE<51>.
* 文档: 文档<51>.
* 测试: 测试<49>.

Python 3.5.0 beta 4

* 核心与内置: 核心与内置<67>.
* 库: 库<81>.
* 构建: 构建<51>.

Python 3.5.0 beta 3

* 核心与内置: 核心与内置<68>.
* 库: 库<82>.
* 测试: 测试<50>.
* 文档: 文档<52>.
* 构建: 构建<52>.

Python 3.5.0 beta 2

* 核心与内置: 核心与内置<69>.
* 库: 库<83>.

Python 3.5.0 beta 1

* 核心与内置: 核心与内置<70>.
* 库: 库<84>.
* IDLE: IDLE<52>.
* 测试: 测试<51>.
* 文档: 文档<53>.
* 工具/示例: 工具/示例<33>.

Python 3.5.0 alpha 4

* 核心与内置: 核心与内置<71>.
* 库: 库<85>.
* 构建: 构建<53>.
* 测试: 测试<52>.
* 工具/示例: 工具/示例<34>.
* C API: C API<36>.

Python 3.5.0 alpha 3

* 核心与内置: 核心与内置<72>.
* 库: 库<86>.
* 构建: 构建<54>.
* 测试: 测试<53>.
* 工具/示例: 工具/示例<35>.

Python 3.5.0 alpha 2

* 核心与内置: 核心与内置<73>.
* 库: 库<87>.
* 构建: 构建<55>.
* C API: C API<37>.
* Windows: Windows<51>.

Python 3.5.0 alpha 1

* 核心与内置: 核心与内置<74>.
* 库: 库<88>.
* IDLE: IDLE<53>.
* 构建: 构建<56>.
* C API: C API<38>.
* 文档: 文档<54>.
* 测试: 测试<54>.
* 工具/示例: 工具/示例<36>.
* Windows: Windows<52>.

Python 教程

* 课前甜点::
* 使用 Python 解释器::
* Python 的非正式介绍::
* 其他流程控制工具::
* 数据结构::
* 模块::
* 输入输出::
* 错误和异常::
* 类::
* 标准库简介::
* 标准库简介 —— 第二部分::
* 虚拟环境和包::
* 接下来？::
* 交互式编辑和编辑历史::
* 浮点算术：争议和限制::
* 附录::

使用 Python 解释器

* 调用解释器::
* 解释器的运行环境::

调用解释器

* 传入参数::
* 交互模式::

解释器的运行环境

* 源文件的字符编码::

Python 的非正式介绍

* Python 作为计算器使用::
* 走向编程的第一步::

Python 作为计算器使用

* 数字::
* 字符串::
* 列表::

其他流程控制工具

* if 语句::
* for 语句::
* range() 函数: range 函数.
* break 和 continue 语句，以及循环中的 else 子句::
* pass 语句::
* 定义函数::
* 函数定义的更多形式::
* 小插曲：编码风格::

函数定义的更多形式

* 参数默认值::
* 关键字参数::
* 特殊参数::
* 任意的参数列表::
* 解包参数列表::
* Lambda 表达式::
* 文档字符串::
* 函数标注::

特殊参数

* 位置或关键字参数::
* 仅限位置参数::
* 仅限关键字参数::
* 函数示例::
* 概括::

数据结构

* 列表的更多特性::
* del 语句::
* 元组和序列::
* 集合::
* 字典::
* 循环的技巧::
* 深入条件控制::
* 比较序列和其他类型::

列表的更多特性

* 列表作为栈使用::
* 列表作为队列使用::
* 列表推导式: 列表推导式<2>.
* 嵌套的列表推导式::

模块

* 更多有关模块的信息::
* 标准模块::
* dir() 函数: dir 函数.
* 包::

更多有关模块的信息

* 以脚本的方式执行模块::
* 模块搜索路径::
* “编译过的”Python文件::

包

* 从包中导入 *::
* 子包参考::
* 多个目录中的包::

输入输出

* 更漂亮的输出格式::
* 读写文件::

更漂亮的输出格式

* 格式化字符串文字::
* 字符串的 format() 方法: 字符串的 format 方法.
* 手动格式化字符串::
* 旧的字符串格式化方法::

读写文件

* 文件对象的方法::
* 使用 json 保存结构化数据::

错误和异常

* 语法错误::
* 异常::
* 处理异常::
* 抛出异常::
* 用户自定义异常::
* 定义清理操作::
* 预定义的清理操作::

类

* 名称和对象::
* Python 作用域和命名空间::
* 初探类::
* 补充说明::
* 继承::
* 私有变量::
* 杂项说明::
* 迭代器::
* 生成器::
* 生成器表达式::

Python 作用域和命名空间

* 作用域和命名空间示例::

初探类

* 类定义语法::
* 类对象::
* 实例对象::
* 方法对象::
* 类和实例变量::

继承

* 多重继承::

标准库简介

* 操作系统接口::
* 文件通配符::
* 命令行参数::
* 错误输出重定向和程序终止::
* 字符串模式匹配::
* 数学::
* 互联网访问::
* 日期和时间::
* 数据压缩::
* 性能测量::
* 质量控制::
* 自带电池::

标准库简介 —— 第二部分

* 格式化输出::
* 模板::
* 使用二进制数据记录格式::
* 多线程: 多线程<2>.
* 日志记录::
* 弱引用::
* 用于操作列表的工具::
* 十进制浮点运算::

虚拟环境和包

* 概述: 概述<4>.
* 创建虚拟环境::
* 使用pip管理包::

交互式编辑和编辑历史

* Tab 补全和编辑历史::
* 默认交互式解释器的替代品::

浮点算术：争议和限制

* 表示性错误::

附录

* 交互模式: 交互模式<2>.

交互模式

* 错误处理::
* 可执行的Python脚本::
* 交互式启动文件::
* 定制模块::

Python安装和使用

* 命令行与环境::
* 在类Unix环境下使用Python::
* 在Windows上使用 Python::
* 在苹果系统上使用 Python::
* 编辑器和集成开发环境::

命令行与环境

* 命令行::
* 环境变量::

命令行

* 接口选项::
* 通用选项::
* 其他选项::
* 不应当使用的选项::

环境变量

* 调试模式变量::

在类Unix环境下使用Python

* 获得并安装Python的最新版本::
* 构建Python::
* 与Python相关的路径和文件::
* 杂项::

获得并安装Python的最新版本

* 在Linux中::
* 在FreeBSD和OpenBSD上::
* 在OpenSolaris系统上::

在Windows上使用 Python

* 完整安装程序::
* Microsoft Store包::
* nuget.org 安装包: nuget org 安装包.
* 可嵌入的包::
* 替代捆绑包::
* 配置Python::
* UTF-8 模式::
* 适用于Windows的Python启动器::
* 查找模块::
* 附加模块::
* 在Windows上编译Python::
* 其他平台::

完整安装程序

* 安装步骤::
* 删除 MAX_PATH 限制::
* 无UI 安装::
* 免下载安装::
* 修改安装::

Microsoft Store包

* 已知的问题::

可嵌入的包

* Python应用程序::
* 嵌入Python::

配置Python

* 附录：设置环境变量::
* 查找Python可执行文件::

适用于Windows的Python启动器

* 入门::
* Shebang Lines::
* shebang lines 的参数::
* 自定义::
* 诊断::

入门

* 从命令行::
* 从虚拟环境::
* 从脚本::
* 从文件关联::

自定义

* 通过INI文件自定义::
* 自定义默认的Python版本::

附加模块

* PyWin32::
* cx_Freeze::
* WConio::

在苹果系统上使用 Python

* 获取和安装 MacPython::
* IDE::
* 安装额外的 Python 包::
* Mac 上的图形界面编程::
* 在 Mac 上分发 Python 应用程序::
* 其他资源::

获取和安装 MacPython

* 如何运行 Python 脚本::
* 运行有图形界面的脚本::
* 配置::

Python语言参考

* 概述: 概述<5>.
* 词法分析::
* 数据模型::
* 执行模型::
* 导入系统::
* 表达式::
* 简单语句::
* 复合语句::
* 最高层级组件::
* 完整的语法规范::

概述

* 其他实现::
* 标注::

词法分析

* 行结构::
* 其他形符::
* 标识符和关键字::
* 字面值::
* 运算符::
* 分隔符::

行结构

* 逻辑行::
* 物理行::
* 注释::
* 编码声明::
* 显式的行拼接::
* 隐式的行拼接::
* 空白行::
* 缩进::
* 形符之间的空白::

标识符和关键字

* 关键字::
* 保留的标识符类::

字面值

* 字符串和字节串字面值::
* 字符串字面值拼接::
* 格式化字符串字面值::
* 数字字面值::
* 整型数字面值::
* 浮点数字面值::
* 虚数字面值::

数据模型

* 对象、值与类型::
* 标准类型层级结构::
* 特殊方法名称::
* 协程::

特殊方法名称

* 基本定制::
* 自定义属性访问::
* 自定义类创建::
* 自定义实例及子类检查::
* 模拟泛型类型::
* 模拟可调用对象::
* 模拟容器类型::
* 模拟数字类型::
* with 语句上下文管理器::
* 特殊方法查找::

自定义属性访问

* 自定义模块属性访问::
* 实现描述器::
* 调用描述器::
* __slots__::

__slots__

* 使用 __slots__ 的注意事项::

自定义类创建

* 元类::
* 解析 MRO 条目::
* 确定适当的元类::
* 准备类命名空间::
* 执行类主体::
* 创建类对象::
* 元类的作用::

协程

* 可等待对象::
* 协程对象::
* 异步迭代器::
* 异步上下文管理器::

执行模型

* 程序的结构::
* 命名与绑定::
* 异常: 异常<2>.

命名与绑定

* 名称的绑定::
* 名称的解析::
* 内置命名空间和受限的执行::
* 与动态特性的交互::

导入系统

* importlib: importlib<7>.
* 包: 包<2>.
* 搜索::
* 加载::
* 基于路径的查找器::
* 替换标准导入系统::
* 包相对导入::
* 有关 __main__ 的特殊事项::
* 开放问题项::
* 参考文献::

包

* 常规包::
* 命名空间包::

搜索

* 模块缓存::
* 查找器和加载器::
* 导入钩子::
* 元路径::

加载

* 加载器::
* 子模块::
* 模块规格说明::
* 导入相关的模块属性::
* module.__path__: module __path__.
* 模块的 repr::
* 已缓存字节码的失效::

基于路径的查找器

* 路径条目查找器::
* 路径条目查找器协议::

有关 __main__ 的特殊事项

* __main__.__spec__: __main__ __spec__.

表达式

* 算术转换::
* 原子::
* 原型::
* await 表达式::
* 幂运算符::
* 一元算术和位运算::
* 二元算术运算符::
* 移位运算::
* 二元位运算::
* 比较运算::
* 布尔运算::
* 赋值表达式: 赋值表达式<2>.
* 条件表达式::
* lambda 表达式::
* 表达式列表::
* 求值顺序::
* 运算符优先级::

原子

* 标识符（名称）::
* 字面值: 字面值<2>.
* 带圆括号的形式::
* 列表、集合与字典的显示::
* 列表显示::
* 集合显示::
* 字典显示::
* 生成器表达式: 生成器表达式<2>.
* yield 表达式::

yield 表达式

* 生成器-迭代器的方法::
* 例子::
* 异步生成器函数::
* 异步生成器-迭代器方法::

原型

* 属性引用::
* 抽取::
* 切片::
* 调用::

比较运算

* 值比较::
* 成员检测运算::
* 标识号比较::

简单语句

* 表达式语句::
* 赋值语句::
* assert 语句::
* pass 语句: pass 语句<2>.
* del 语句: del 语句<2>.
* return 语句::
* yield 语句::
* raise 语句::
* break 语句::
* continue 语句::
* import 语句::
* global 语句::
* nonlocal 语句::

赋值语句

* 增强赋值语句::
* 带标注的赋值语句::

import 语句

* future 语句::

复合语句

* if 语句: if 语句<2>.
* while 语句::
* for 语句: for 语句<2>.
* try 语句::
* with 语句::
* 函数定义::
* 类定义::
* 协程: 协程<2>.

协程

* 协程函数定义::
* async for 语句::
* async with 语句::

最高层级组件

* 完整的 Python 程序::
* 文件输入::
* 交互式输入::
* 表达式输入::

Python 标准库

* 概述: 概述<6>.
* 内置函数::
* 内置常量::
* 内置类型::
* 内置异常::
* 文本处理服务::
* 二进制数据服务::
* 数据类型::
* 数字和数学模块::
* 函数式编程模块::
* 文件和目录访问::
* 数据持久化::
* 数据压缩和存档::
* 文件格式::
* 加密服务::
* 通用操作系统服务::
* 并发执行::
* 网络和进程间通信::
* 互联网数据处理::
* 结构化标记处理工具::
* 互联网协议和支持::
* 多媒体服务::
* 国际化::
* 程序框架::
* Tk图形用户界面(GUI): Tk图形用户界面 GUI.
* 开发工具::
* 调试和分析::
* 软件打包和分发::
* Python运行时服务::
* 自定义 Python 解释器::
* 导入模块::
* Python 语言服务::
* 杂项服务::
* Windows系统相关模块::
* Unix 专有服务::
* 被取代的模块::
* 未创建文档的模块::

概述

* 可用性注释::

内置常量

* 由 site 模块添加的常量::

内置类型

* 逻辑值检测::
* 布尔运算: 布尔运算 --- and or not. and, or, not
* 比较运算: 比较运算<2>.
* 数字类型: 数字类型 --- int float complex. int, float, complex
* 迭代器类型::
* 序列类型: 序列类型 --- list tuple range. list, tuple, range
* 文本序列类型: 文本序列类型 --- str. str
* 二进制序列类型: 二进制序列类型 --- bytes bytearray memoryview. bytes, bytearray, memoryview
* 集合类型: 集合类型 --- set frozenset. set, frozenset
* 映射类型: 映射类型 --- dict. dict
* 上下文管理器类型::
* 其他内置类型::
* 特殊属性::

数字类型 — int, float, complex

* 整数类型的按位运算::
* 整数类型的附加方法::
* 浮点类型的附加方法::
* 数字类型的哈希运算::

迭代器类型

* 生成器类型::

序列类型 — list, tuple, range

* 通用序列操作::
* 不可变序列类型::
* 可变序列类型::
* 列表: 列表<2>.
* 元组::
* range 对象::

文本序列类型 — str

* 字符串的方法: 字符串的方法<2>.
* printf 风格的字符串格式化::

二进制序列类型 — bytes, bytearray, memoryview

* bytes 对象::
* bytearray 对象::
* bytes 和 bytearray 操作::
* printf 风格的字节串格式化::
* 内存视图::

映射类型 — dict

* 字典视图对象::

其他内置类型

* 模块: 模块<2>.
* 类与类实例::
* 函数::
* 方法::
* 代码对象::
* 类型对象::
* 空对象::
* 省略符对象::
* 未实现对象::
* 布尔值::
* 内部对象::

内置异常

* 基类::
* 具体异常::
* 警告::
* 异常层次结构::

具体异常

* OS 异常::

文本处理服务

* string: string --- 常见的字符串操作. 常见的字符串操作
* re: re --- 正则表达式操作. 正则表达式操作
* difflib: difflib --- 计算差异的辅助工具. 计算差异的辅助工具
* textwrap: textwrap --- 文本自动换行与填充. 文本自动换行与填充
* unicodedata: unicodedata --- Unicode 数据库. Unicode 数据库
* stringprep: stringprep --- 因特网字符串预备. 因特网字符串预备
* readline: readline --- GNU readline 接口. GNU readline 接口
* rlcompleter: rlcompleter --- GNU readline 的补全函数. GNU readline 的补全函数

string — 常见的字符串操作

* 字符串常量::
* 自定义字符串格式化::
* 格式字符串语法::
* 模板字符串::
* 辅助函数::

格式字符串语法

* 格式规格迷你语言::
* 格式示例::

re — 正则表达式操作

* 正则表达式语法::
* 模块内容::
* 正则表达式对象 （正则对象）::
* 匹配对象::
* 正则表达式例子::

正则表达式例子

* 检查对子::
* 模拟 scanf(): 模拟 scanf.
* search() vs. match(): search vs match.
* 制作一个电话本::
* 文字整理::
* 查找所有副词::
* 查找所有的副词及其位置::
* 原始字符串标记::
* 写一个词法分析器::

difflib — 计算差异的辅助工具

* SequenceMatcher 对象::
* SequenceMatcher 的示例::
* Differ 对象::
* Differ 示例::
* difflib 的命令行接口::

readline — GNU readline 接口

* 初始化文件::
* 行缓冲区::
* 历史文件::
* 历史列表::
* 启动钩子::
* Completion::
* 示例::

rlcompleter — GNU readline 的补全函数

* Completer 对象::

二进制数据服务

* struct: struct --- 将字节串解读为打包的二进制数据. 将字节串解读为打包的二进制数据
* codecs: codecs --- 编解码器注册和相关基类. 编解码器注册和相关基类

struct — 将字节串解读为打包的二进制数据

* 函数和异常::
* 格式字符串::
* 类: 类<2>.

格式字符串

* 字节顺序，大小和对齐方式::
* 格式字符::
* 例子: 例子<2>.

codecs — 编解码器注册和相关基类

* 编解码器基类::
* 编码格式与 Unicode::
* 标准编码::
* Python 专属的编码格式::
* encodings.idna: encodings idna --- 应用程序中的国际化域名. 应用程序中的国际化域名
* encodings.mbcs: encodings mbcs --- Windows ANSI代码页. Windows ANSI代码页
* encodings.utf_8_sig: encodings utf_8_sig --- 带BOM签名的UTF-8编解码器. 带BOM签名的UTF-8编解码器

编解码器基类

* 错误处理方案::
* 无状态的编码和解码::
* 增量式的编码和解码::
* 流式的编码和解码::

增量式的编码和解码

* IncrementalEncoder 对象::
* IncrementalDecoder 对象::

流式的编码和解码

* StreamWriter 对象::
* StreamReader 对象::
* StreamReaderWriter 对象::
* StreamRecoder 对象::

Python 专属的编码格式

* 文字编码::
* 二进制转换::
* 文字转换::

数据类型

* datetime: datetime --- 基本的日期和时间类型. 基本的日期和时间类型
* calendar: calendar --- 日历相关函数. 日历相关函数
* collections: collections --- 容器数据类型. 容器数据类型
* collections.abc: collections abc --- 容器的抽象基类. 容器的抽象基类
* heapq: heapq --- 堆队列算法. 堆队列算法
* bisect: bisect --- 数组二分查找算法. 数组二分查找算法
* array: array --- 高效的数值数组. 高效的数值数组
* weakref: weakref --- 弱引用. 弱引用
* types: types --- 动态类型创建和内置类型名称. 动态类型创建和内置类型名称
* copy: copy --- 浅层 shallow 和深层 deep 复制操作. 浅层 (shallow) 和深层 (deep) 复制操作
* pprint: pprint --- 数据美化输出. 数据美化输出
* reprlib: reprlib --- 另一种 repr 实现. 另一种 repr() 实现
* enum: enum --- 对枚举的支持. 对枚举的支持

datetime — 基本的日期和时间类型

* 感知型对象和简单型对象::
* 常量::
* 有效的类型::
* timedelta 类对象::
* date 对象::
* datetime 对象::
* time 对象::
* tzinfo 对象::
* timezone 对象::
* strftime() 和 strptime() 的行为: strftime 和 strptime 的行为.

有效的类型

* 通用的特征属性::
* 确定一个对象是感知型还是简单型::

timedelta 类对象

* class;timedelta 用法示例: class timedelta 用法示例.

date 对象

* class;date 用法示例: class date 用法示例.

datetime 对象

* 用法示例; datetime: 用法示例 datetime.

time 对象

* 用法示例; time: 用法示例 time.

strftime() 和 strptime() 的行为

* strftime() 和 strptime() Format Codes: strftime 和 strptime Format Codes.
* 技术细节::

collections — 容器数据类型

* ChainMap 对象::
* Counter 对象::
* deque 对象::
* defaultdict 对象::
* namedtuple() 命名元组的工厂函数: namedtuple 命名元组的工厂函数.
* OrderedDict 对象::
* UserDict 对象::
* UserList 对象::
* UserString 对象::

ChainMap 对象

* ChainMap 例子和方法::

deque 对象

* deque 用法::

defaultdict 对象

* defaultdict 例子::

OrderedDict 对象

* OrderedDict 例子和用法::

collections.abc — 容器的抽象基类

* 容器抽象基类::

heapq — 堆队列算法

* 基本示例::
* 优先队列实现说明::
* 理论::

bisect — 数组二分查找算法

* 搜索有序列表::
* 其他示例::

weakref — 弱引用

* 弱引用对象::
* 示例: 示例<2>.
* 终结器对象::
* 比较终结器与 __del__() 方法: 比较终结器与 __del__ 方法.

types — 动态类型创建和内置类型名称

* 动态类型创建::
* 标准解释器类型::
* 附加工具类和函数::
* 协程工具函数::

pprint — 数据美化输出

* PrettyPrinter 对象::
* 示例: 示例<3>.

reprlib — 另一种 repr() 实现

* Repr 对象::
* 子类化 Repr 对象::

enum — 对枚举的支持

* 模块内容: 模块内容<2>.
* 创建一个 Enum::
* 对枚举成员及其属性的程序化访问::
* 复制枚举成员和值::
* 确保唯一的枚举值::
* 使用自动设定的值::
* 迭代::
* 比较运算: 比较运算<3>.
* 允许的枚举成员和属性::
* 受限的 Enum 子类化::
* 封存::
* 功能性 API::
* 派生的枚举::
* 何时使用 __new__() 与 __init__(): 何时使用 __new__ 与 __init__.
* 有趣的示例::
* 各种枚举有何区别？::

派生的枚举

* IntEnum::
* IntFlag::
* Flag::
* 其他事项::

有趣的示例

* 省略值::
* OrderedEnum::
* DuplicateFreeEnum::
* Planet::
* TimePeriod::

省略值

* 使用 auto::
* 使用 object::
* 使用描述性字符串::
* 使用自定义的 __new__(): 使用自定义的 __new__.

各种枚举有何区别？

* 枚举类::
* 枚举成员（即实例）::
* 细节要点::

细节要点

* 支持的 __dunder__ 名称::
* 支持的 _sunder_ 名称::
* Enum 成员类型::
* Enum 类和成员的布尔值::
* 带有方法的 Enum 类::
* 组合 Flag 的成员::

数字和数学模块

* numbers: numbers --- 数字的抽象基类. 数字的抽象基类
* math: math --- 数学函数. 数学函数
* cmath: cmath --- 关于复数的数学函数. 关于复数的数学函数
* decimal: decimal --- 十进制定点和浮点运算. 十进制定点和浮点运算
* fractions: fractions --- 分数. 分数
* random: random --- 生成伪随机数. 生成伪随机数
* statistics: statistics --- 数学统计函数. 数学统计函数

numbers — 数字的抽象基类

* 数字的层次::
* 类型接口注释。::

类型接口注释。

* 加入更多数字的ABC::
* 实现算术运算::

math — 数学函数

* 数论与表示函数::
* 幂函数与对数函数::
* 三角函数::
* 角度转换::
* 双曲函数::
* 特殊函数::
* 常量: 常量<2>.

cmath — 关于复数的数学函数

* 到极坐标和从极坐标的转换::
* 幂函数与对数函数: 幂函数与对数函数<2>.
* 三角函数: 三角函数<2>.
* 双曲函数: 双曲函数<2>.
* 分类函数::
* 常量: 常量<3>.

decimal — 十进制定点和浮点运算

* 快速入门教程::
* Decimal 对象::
* 上下文对象::
* 常量: 常量<4>.
* 舍入模式::
* 信号::
* 浮点数说明::
* 使用线程::
* 例程::
* Decimal 常见问题::

Decimal 对象

* 逻辑操作数::

浮点数说明

* 通过提升精度来解决舍入错误::
* 特殊的值::

random — 生成伪随机数

* 簿记功能::
* 整数用函数::
* 序列用函数::
* 实值分布::
* 替代生成器::
* 关于再现性的说明::
* 例子和配方::

statistics — 数学统计函数

* 平均值以及对中心位置的评估::
* 对分散程度的评估::
* 函数细节::
* 异常: 异常<3>.
* NormalDist 对象::

NormalDist 对象

* NormalDist 示例和用法::

函数式编程模块

* itertools: itertools --- 为高效循环而创建迭代器的函数. 为高效循环而创建迭代器的函数
* functools: functools --- 高阶函数和可调用对象上的操作. 高阶函数和可调用对象上的操作
* operator: operator --- 标准运算符替代函数. 标准运算符替代函数

itertools — 为高效循环而创建迭代器的函数

* Itertool函数::
* itertools 配方::

functools — 高阶函数和可调用对象上的操作

* partial 对象::

operator — 标准运算符替代函数

* 将运算符映射到函数::
* 原地运算符::

文件和目录访问

* pathlib: pathlib --- 面向对象的文件系统路径. 面向对象的文件系统路径
* os.path: os path --- 常用路径操作. 常用路径操作
* fileinput: fileinput --- 迭代来自多个输入流的行. 迭代来自多个输入流的行
* stat: stat --- 解析 stat 结果. 解析 stat() 结果
* filecmp: filecmp --- 文件及目录的比较. 文件及目录的比较
* tempfile: tempfile --- 生成临时文件和目录. 生成临时文件和目录
* glob: glob --- Unix 风格路径名模式扩展. Unix 风格路径名模式扩展
* fnmatch: fnmatch --- Unix 文件名模式匹配. Unix 文件名模式匹配
* linecache: linecache --- 随机读写文本行. 随机读写文本行
* shutil: shutil --- 高阶文件操作. 高阶文件操作

pathlib — 面向对象的文件系统路径

* 基础使用::
* 纯路径::
* 具体路径::
* 对应的 os 模块的工具::

纯路径

* 通用性质::
* 运算符: 运算符<2>.
* 访问个别部分::
* 方法和特征属性::

具体路径

* 方法: 方法<2>.

filecmp — 文件及目录的比较

* dircmp 类::

tempfile — 生成临时文件和目录

* 例子: 例子<3>.
* 已弃用的函数和变量::

shutil — 高阶文件操作

* 目录和文件操作::
* 归档操作::
* 查询输出终端的尺寸::

目录和文件操作

* 依赖于具体平台的高效拷贝操作::
* copytree 示例::
* rmtree 示例::

归档操作

* 归档程序示例::
* 使用 base_dir 的归档程序示例::

数据持久化

* pickle: pickle --- Python 对象序列化. Python 对象序列化
* copyreg: copyreg --- 注册配合 pickle 模块使用的函数. 注册配合 pickle 模块使用的函数
* shelve: shelve --- Python 对象持久化. Python 对象持久化
* marshal: marshal --- 内部 Python 对象序列化. 内部 Python 对象序列化
* dbm: dbm --- Unix "数据库" 接口. Unix "数据库" 接口
* sqlite3: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块. SQLite 数据库 DB-API 2.0 接口模块

pickle — Python 对象序列化

* 与其他 Python 模块间的关系::
* 数据流格式::
* 模块接口::
* 可以被封存/解封的对象::
* 封存类实例::
* 类型，函数和其他对象的自定义归约::
* 外部缓冲区::
* 限制全局变量::
* 性能: 性能<2>.
* 例子: 例子<4>.

与其他 Python 模块间的关系

* 与 marshal 间的关系::
* 与 json 模块的比较::

封存类实例

* 持久化外部对象::
* Dispatch 表::
* 处理有状态的对象::

外部缓冲区

* 提供方 API::
* 使用方 API::
* 示例: 示例<4>.

copyreg — 注册配合 pickle 模块使用的函数

* 示例: 示例<5>.

shelve — Python 对象持久化

* 限制::
* 示例: 示例<6>.

dbm — Unix "数据库" 接口

* dbm.gnu: dbm gnu --- GNU 对 dbm 的重解析. GNU 对 dbm 的重解析
* dbm.ndbm: dbm ndbm --- 基于 ndbm 的接口. 基于 ndbm 的接口
* dbm.dumb: dbm dumb --- 便携式 DBM 实现. 便携式 DBM 实现

sqlite3 — SQLite 数据库 DB-API 2.0 接口模块

* 模块函数和常量::
* 连接对象（Connection）::
* Cursor 对象::
* 行对象::
* 异常: 异常<4>.
* SQLite 与 Python 类型::
* 控制事务::
* 有效使用 sqlite3::

SQLite 与 Python 类型

* 概述: 概述<7>.
* 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。::
* 将SQLite 值转换为自定义Python 类型::
* 默认适配器和转换器::

使用适配器将额外的 Python 类型保存在 SQLite 数据库中。

* 让对象自行适配::
* 注册可调用的适配器::

有效使用 sqlite3

* 使用快捷方式::
* 通过名称而不是索引访问索引::
* 使用连接作为上下文管理器::

数据压缩和存档

* zlib: zlib --- 与 gzip 兼容的压缩. 与 gzip 兼容的压缩
* gzip: gzip --- 对 gzip 格式的支持. 对 gzip 格式的支持
* bz2: bz2 --- 对 bzip2 压缩算法的支持. 对 bzip2 压缩算法的支持
* lzma: lzma --- 用 LZMA 算法压缩. 用 LZMA 算法压缩
* zipfile: zipfile --- 使用ZIP存档. 使用ZIP存档
* tarfile: tarfile --- 读写tar归档文件. 读写tar归档文件

gzip — 对 gzip 格式的支持

* 用法示例::
* 命令行界面::

命令行界面

* 命令行选项::

bz2 — 对 bzip2 压缩算法的支持

* 文件压缩和解压::
* 增量压缩和解压::
* 一次性压缩或解压缩::
* 用法示例: 用法示例<2>.

lzma — 用 LZMA 算法压缩

* 读写压缩文件::
* 在内存中压缩和解压缩数据::
* 杂项: 杂项<2>.
* 指定自定义的过滤器链::
* 例子: 例子<5>.

zipfile — 使用ZIP存档

* ZipFile 对象::
* Path 对象::
* PyZipFile 对象::
* ZipInfo 对象::
* 命令行界面: 命令行界面<2>.
* 解压缩的障碍::

命令行界面

* 命令行选项: 命令行选项<2>.

解压缩的障碍

* 由于文件本身::
* 文件系统限制::
* 资源限制::
* 中断::
* 提取的默认行为::

tarfile — 读写tar归档文件

* TarFile 对象::
* TarInfo 对象::
* 命令行界面: 命令行界面<3>.
* 例子: 例子<6>.
* 受支持的 tar 格式::
* Unicode 问题::

命令行界面

* 命令行选项: 命令行选项<3>.

文件格式

* csv: csv --- CSV 文件读写. CSV 文件读写
* configparser: configparser --- 配置文件解析器. 配置文件解析器
* netrc: netrc --- netrc 文件处理. netrc 文件处理
* xdrlib: xdrlib --- 编码与解码 XDR 数据. 编码与解码 XDR 数据
* plistlib: plistlib --- 生成与解析 Mac OS X plist 文件. 生成与解析 Mac OS X .plist 文件

csv — CSV 文件读写

* 模块内容: 模块内容<3>.
* 变种与格式参数::
* Reader 对象::
* Writer 对象::
* 例子: 例子<7>.

configparser — 配置文件解析器

* 快速起步::
* 支持的数据类型::
* 回退值::
* 受支持的 INI 文件结构::
* 值的插值::
* 映射协议访问::
* 定制解析器行为::
* 旧式 API 示例::
* ConfigParser 对象::
* RawConfigParser 对象::
* 异常: 异常<5>.

netrc — netrc 文件处理

* netrc 对象::

xdrlib — 编码与解码 XDR 数据

* Packer 对象::
* Unpacker 对象::
* 异常: 异常<6>.

plistlib — 生成与解析 Mac OS X .plist 文件

* 例子: 例子<8>.

加密服务

* hashlib: hashlib --- 安全哈希与消息摘要. 安全哈希与消息摘要
* hmac: hmac --- 基于密钥的消息验证. 基于密钥的消息验证
* secrets: secrets --- 生成安全随机数字用于管理密码. 生成安全随机数字用于管理密码

hashlib — 安全哈希与消息摘要

* 哈希算法::
* SHAKE 可变长度摘要::
* 密钥派生::
* BLAKE2::

BLAKE2

* 创建哈希对象::
* 常量: 常量<5>.
* 例子: 例子<9>.
* 开发人员::

例子

* 简单哈希::
* 使用不同的摘要大小::
* 密钥哈希::
* 随机哈希::
* 个性化::
* 树形模式::

secrets — 生成安全随机数字用于管理密码

* 随机数::
* 生成凭据::
* 其他功能::
* 应用技巧与最佳实践::

生成凭据

* 凭据应当使用多少个字节？::

通用操作系统服务

* os: os --- 多种操作系统接口. 多种操作系统接口
* io: io --- 处理流的核心工具. 处理流的核心工具
* time: time --- 时间的访问和转换. 时间的访问和转换
* argparse: argparse --- 命令行选项、参数和子命令解析器. 命令行选项、参数和子命令解析器
* getopt: getopt --- C 风格的命令行选项解析器. C 风格的命令行选项解析器
* logging: logging --- Python 的日志记录工具. Python 的日志记录工具
* logging.config: logging config --- 日志记录配置. 日志记录配置
* logging.handlers: logging handlers --- 日志处理. 日志处理
* getpass: getpass --- 便携式密码输入工具. 便携式密码输入工具
* curses: curses --- 终端字符单元显示的处理. 终端字符单元显示的处理
* curses.textpad: curses textpad --- 用于 curses 程序的文本输入控件. 用于 curses 程序的文本输入控件
* curses.ascii: curses ascii --- 用于 ASCII 字符的工具. 用于 ASCII 字符的工具
* curses.panel: curses panel --- curses 的 panel 栈扩展. curses 的 panel 栈扩展
* platform: platform --- 获取底层平台的标识数据. 获取底层平台的标识数据
* errno: errno --- 标准 errno 系统符号. 标准 errno 系统符号
* ctypes: ctypes --- Python 的外部函数库. Python 的外部函数库

os — 多种操作系统接口

* 文件名，命令行参数，以及环境变量。::
* 进程参数::
* 创建文件对象::
* 文件描述符操作::
* 文件和目录::
* 进程管理::
* 调度器接口::
* 其他系统信息::
* 随机数: 随机数<2>.

文件描述符操作

* 查询终端的尺寸::
* 文件描述符的继承::

文件和目录

* Linux 扩展属性::

io — 处理流的核心工具

* 概述: 概述<8>.
* 高阶模块接口::
* 类的层次结构::
* 性能: 性能<3>.

概述

* 文本 I/O::
* 二进制 I/O::
* 原始 I/O::

类的层次结构

* I/O 基类::
* 原始文件 I/O::
* 缓冲流::
* 文本 I/O: 文本 I/O<2>.

性能

* 二进制 I/O: 二进制 I/O<2>.
* 文本 I/O: 文本 I/O<3>.
* 多线程: 多线程<3>.
* 可重入性::

time — 时间的访问和转换

* 函数: 函数<2>.
* Clock ID 常量::
* 时区常量::

argparse — 命令行选项、参数和子命令解析器

* 示例: 示例<7>.
* ArgumentParser 对象::
* add_argument() 方法: add_argument 方法.
* parse_args() 方法: parse_args 方法.
* 其它实用工具::
* 升级 optparse 代码::

示例

* 创建一个解析器::
* 添加参数::
* 解析参数::

ArgumentParser 对象

* prog::
* usage::
* description::
* epilog::
* parents::
* formatter_class::
* prefix_chars::
* fromfile_prefix_chars::
* argument_default::
* allow_abbrev::
* conflict_handler::
* add_help::

add_argument() 方法

* name or flags::
* action::
* nargs::
* const::
* 默认值::
* type::
* choices::
* required::
* help::
* metavar::
* dest::
* Action 类::

parse_args() 方法

* 选项值语法::
* 无效的参数::
* 包含 - 的参数::
* 参数缩写（前缀匹配）::
* 在 sys.argv 以外: 在 sys argv 以外.
* 命名空间对象::

其它实用工具

* 子命令::
* FileType 对象::
* 参数组::
* 互斥::
* 解析器默认值::
* 打印帮助::
* 部分解析::
* 自定义文件解析::
* 退出方法::
* 混合解析::

logging — Python 的日志记录工具

* 记录器对象::
* 日志级别::
* 处理器对象::
* 格式器对象::
* Filter 对象::
* LogRecord 属性::
* LogRecord 属性: LogRecord 属性<2>.
* LoggerAdapter 对象::
* 线程安全::
* 模块级别函数::
* 模块级属性::
* 与警告模块集成::

logging.config — 日志记录配置

* 配置函数::
* 配置字典架构::
* 配置文件格式::

配置字典架构

* 字典架构细节::
* 增量配置::
* 对象连接::
* 用户定义对象::
* 访问外部对象::
* 访问内部对象::
* 导入解析与定制导入器::

logging.handlers — 日志处理

* StreamHandler::
* FileHandler::
* NullHandler::
* WatchedFileHandler::
* BaseRotatingHandler::
* RotatingFileHandler::
* TimedRotatingFileHandler::
* SocketHandler::
* DatagramHandler::
* SysLogHandler::
* NTEventLogHandler::
* SMTPHandler::
* MemoryHandler::
* HTTPHandler::
* QueueHandler::
* QueueListener::

curses — 终端字符单元显示的处理

* 函数: 函数<3>.
* Window 对象::
* 常量: 常量<6>.

curses.textpad — 用于 curses 程序的文本输入控件

* 文本框对象::

curses.panel — curses 的 panel 栈扩展

* 函数: 函数<4>.
* Panel 对象::

platform —  获取底层平台的标识数据

* 跨平台::
* Java平台::
* Windows平台::
* Mac OS平台::
* Unix 平台::

ctypes — Python 的外部函数库

* ctypes 教程::
* ctypes 参考手册::

ctypes 教程

* 载入动态连接库::
* 操作导入的动态链接库中的函数::
* 调用函数::
* 基础数据类型::
* 调用函数，继续::
* 使用自定义的数据类型调用函数::
* 指定必选参数的类型(函数原型): 指定必选参数的类型 函数原型.
* 返回类型::
* 传递指针(或者传递引用): 传递指针 或者传递引用.
* 结构体和联合::
* 结构体/联合 字段对齐及字节顺序::
* 结构体和联合中的位域::
* 数组::
* 指针::
* 类型强制转换::
* 不完整类型::
* 回调函数::
* 访问 dll 中导出的值::
* 意外::
* 变长数据类型::

ctypes 参考手册

* 寻找动态链接库::
* 加载动态链接库::
* 外部函数::
* 函数原型::
* 工具函数::
* 数据类型: 数据类型<2>.
* 基础数据类型: 基础数据类型<2>.
* 结构化数据类型::
* 数组与指针::

并发执行

* threading: threading --- 基于线程的并行. 基于线程的并行
* multiprocessing: multiprocessing --- 基于进程的并行. 基于进程的并行
* multiprocessing.shared_memory: multiprocessing shared_memory --- 可从进程直接访问的共享内存. 可从进程直接访问的共享内存
* concurrent 包::
* concurrent.futures: concurrent futures --- 启动并行任务. 启动并行任务
* subprocess: subprocess --- 子进程管理. 子进程管理
* sched: sched --- 事件调度器. 事件调度器
* queue: queue --- 一个同步的队列类. 一个同步的队列类
* contextvars 上下文变量::
* _thread: _thread --- 底层多线程 API. 底层多线程 API
* _dummy_thread: _dummy_thread --- _thread 的替代模块. _thread 的替代模块
* dummy_threading: dummy_threading --- 可直接替代 threading 模块。. 可直接替代 threading 模块。

threading — 基于线程的并行

* 线程本地数据::
* 线程对象::
* 锁对象::
* 递归锁对象::
* 条件对象::
* 信号量对象::
* 事件对象::
* 定时器对象::
* 栅栏对象::
* 在 with 语句中使用锁、条件和信号量::

信号量对象

* Semaphore 例子::

multiprocessing — 基于进程的并行

* 概述: 概述<9>.
* 参考::
* 编程指导::
* 例子: 例子<10>.

概述

* Process 类::
* 上下文和启动方法::
* 在进程之间交换对象::
* 进程间同步::
* 进程间共享状态::
* 使用工作进程::

参考

* Process 和异常::
* 管道和队列::
* 杂项: 杂项<3>.
* 连接对象（Connection）: 连接对象（Connection）<2>.
* 同步原语::
* 共享 ctypes 对象::
* 管理器::
* 代理对象::
* 进程池::
* 监听器及客户端::
* 认证密码::
* 日志记录: 日志记录<2>.
* multiprocessing.dummy 模块: multiprocessing dummy 模块.

共享 ctypes 对象

* multiprocessing.sharedctypes 模块: multiprocessing sharedctypes 模块.

管理器

* 自定义管理器::
* 使用远程管理器::

代理对象

* 清理::

监听器及客户端

* 地址格式::

编程指导

* 所有start方法::
* spawn 和 forkserver 启动方式::

concurrent.futures — 启动并行任务

* Executor 对象::
* ThreadPoolExecutor::
* ProcessPoolExecutor::
* Future 对象::
* 模块函数::
* Exception类::

ThreadPoolExecutor

* ThreadPoolExecutor 例子::

ProcessPoolExecutor

* ProcessPoolExecutor 例子::

subprocess — 子进程管理

* 使用 subprocess 模块::
* 安全考量::
* Popen 对象::
* Windows Popen 助手::
* 较旧的高阶 API::
* 使用 subprocess 模块替换旧函数::
* 旧式的 Shell 发起函数::
* 注释: 注释<2>.

使用 subprocess 模块

* 常用参数::
* Popen 构造函数::
* 异常: 异常<7>.

Windows Popen 助手

* Windows 常数::

使用 subprocess 模块替换旧函数

* 替代 /bin/sh shell 命令替换::
* 替代 shell 管道::
* 替代 os.system(): 替代 os system.
* 替代 os.spawn 函数族: 替代 os spawn 函数族.
* 替代 os.popen(), os.popen2(), os.popen3(): 替代 os popen os popen2 os popen3.
* 来自 popen2 模块的替代函数::

注释

* 在 Windows 上将参数列表转换为一个字符串::

sched — 事件调度器

* 调度器对象::

queue — 一个同步的队列类

* Queue对象::
* SimpleQueue 对象::

contextvars 上下文变量

* 上下文变量::
* 手动上下文管理::
* asyncio 支持::

网络和进程间通信

* asyncio: asyncio --- 异步 I/O. 异步 I/O
* socket: socket --- 底层网络接口. 底层网络接口
* ssl: ssl --- 套接字对象的TLS/SSL封装. 套接字对象的TLS/SSL封装
* select: select --- 等待 I/O 完成. 等待 I/O 完成
* selectors: selectors --- 高级 I/O 复用库. 高级 I/O 复用库
* asyncore: asyncore --- 异步socket处理器. 异步socket处理器
* asynchat: asynchat --- 异步 socket 指令/响应 处理器. 异步 socket 指令/响应 处理器
* signal: signal --- 设置异步事件处理程序. 设置异步事件处理程序
* mmap: mmap --- 内存映射文件支持. 内存映射文件支持

asyncio — 异步 I/O

* 协程与任务::
* 流::
* 同步原语: 同步原语<2>.
* 子进程集::
* 队列集::
* 异常: 异常<9>.
* 事件循环::
* Futures::
* 传输和协议::
* 策略::
* 平台支持::
* 高级API索引::
* 底层API目录::
* 用 asyncio 开发::

协程与任务

* 协程: 协程<3>.
* 可等待对象: 可等待对象<2>.
* 运行 asyncio 程序::
* 创建任务::
* 休眠::
* 并发运行任务::
* 屏蔽取消操作::
* 超时::
* 简单等待::
* 来自其他线程的日程安排::
* 内省::
* Task 对象::
* 基于生成器的协程::

流

* StreamReader::
* StreamWriter::
* 例子: 例子<11>.

例子

* 使用流的 TCP 回显客户端::
* 使用流的 TCP 回显服务器::
* 获取 HTTP 标头::
* 注册一个打开的套接字以等待使用流的数据::

同步原语

* Lock::
* Event::
* Condition::
* Semaphore::
* BoundedSemaphore::

子进程集

* 创建子进程::
* 常量: 常量<7>.
* 与子进程交互::

与子进程交互

* 子进程和线程::
* 例子: 例子<12>.

队列集

* Queue::
* 优先级队列::
* 后进先出队列::
* 异常: 异常<8>.
* 例子: 例子<13>.

事件循环

* 事件循环方法集::
* 回调处理::
* Server 对象::
* 事件循环实现::
* 例子: 例子<14>.

事件循环方法集

* 运行和停止循环::
* 调度回调::
* 调度延迟回调::
* 创建 Futures 和 Tasks::
* 打开网络连接::
* 创建网络服务::
* 传输文件::
* TLS 升级::
* 监控文件描述符::
* 直接使用 socket 对象::
* DNS::
* 使用管道::
* Unix 信号::
* 在线程或者进程池中执行代码。::
* 错误处理API::
* 开启调试模式::
* 运行子进程::

例子

* call_soon() 的 Hello World 示例。: call_soon 的 Hello World 示例。.
* 使用 call_later() 来展示当前的日期: 使用 call_later 来展示当前的日期.
* 监控一个文件描述符的读事件::
* 为SIGINT和SIGTERM设置信号处理器::

Futures

* Future 函数::
* Future 对象: Future 对象<2>.

传输和协议

* 传输::
* 协议::
* 例子: 例子<15>.

传输

* 传输层级::
* 基础传输::
* 只读传输::
* 只写传输::
* 数据报传输::
* 子进程传输::

协议

* 基础协议::
* 基础协议: 基础协议<2>.
* 流协议::
* 缓冲流协议::
* 数据报协议::
* 子进程协议::

例子

* TCP回应服务器::
* TCP回应客户端::
* UDP回应服务器::
* UDP回应客户端::
* 链接已存在的套接字::
* loop.subprocess_exec() 与 SubprocessProtocol: loop subprocess_exec 与 SubprocessProtocol.

策略

* 获取和设置策略::
* 策略对象::
* 进程监视器::
* 自定义策略::

平台支持

* 所有平台::
* Windows: Windows<53>.
* macOS: macOS<26>.

Windows

* Windows的子进程支持::

高级API索引

* 任务::
* 队列集: 队列集<2>.
* 子进程集: 子进程集<2>.
* 流: 流<2>.
* 同步::
* 异常: 异常<10>.

底层API目录

* 获取事件循环::
* 事件循环方法集: 事件循环方法集<2>.
* 传输: 传输<2>.
* 协议: 协议<2>.
* 事件循环策略::

用 asyncio 开发

* Debug 模式::
* 并发性和多线程::
* 运行阻塞的代码::
* 日志记录: 日志记录<3>.
* 检测 never-awaited 协同程序::
* 检测就再也没异常::

socket — 底层网络接口

* 套接字协议族::
* 模块内容: 模块内容<4>.
* 套接字对象::
* 关于套接字超时的说明::
* 示例: 示例<8>.

模块内容

* 异常: 异常<11>.
* 常量: 常量<8>.
* 函数: 函数<5>.

函数

* 创建套接字::
* 其他功能: 其他功能<2>.

关于套接字超时的说明

* 超时与 connect 方法::
* 超时与 accept 方法::

ssl — 套接字对象的TLS/SSL封装

* 方法、常量和异常处理::
* SSL 套接字::
* SSL 上下文::
* 证书::
* 例子: 例子<16>.
* 关于非阻塞套接字的说明::
* 内存 BIO 支持: 内存 BIO 支持<2>.
* SSL 会话::
* 安全考量: 安全考量<2>.
* TLS 1.3: TLS 1 3.
* LibreSSL 支持::

方法、常量和异常处理

* 套接字创建::
* 上下文创建::
* 异常: 异常<12>.
* 随机生成::
* 证书处理::
* 常量: 常量<9>.

证书

* 证书链::
* CA 证书::
* 合并的密钥和证书::
* 自签名证书::

例子

* 检测 SSL 支持::
* 客户端操作::
* 服务器端操作::

安全考量

* 最佳默认值::
* 手动设置::
* 多进程::

手动设置

* 验证证书::
* 协议版本::
* 密码选择::

select — 等待 I/O 完成

* /dev/poll 轮询对象::
* 边缘触发和水平触发的轮询 (epoll) 对象: 边缘触发和水平触发的轮询 epoll 对象.
* Poll 对象::
* Kqueue 对象::
* Kevent 对象::

selectors — 高级 I/O 复用库

* 概述: 概述<10>.
* 类: 类<3>.
* 例子: 例子<17>.

asyncore — 异步socket处理器

* asyncore 示例基本 HTTP 客户端::
* asyncore 示例基本回显服务器::

asynchat — 异步 socket 指令/响应 处理器

* asynchat 示例::

signal — 设置异步事件处理程序

* 一般规则::
* 模块内容: 模块内容<5>.
* 示例: 示例<9>.
* 对于 SIGPIPE 的说明::

一般规则

* 执行 Python 信号处理程序::
* 信号与线程::

mmap — 内存映射文件支持

* MADV_* 常量::

互联网数据处理

* email: email --- 电子邮件与 MIME 处理包. 电子邮件与 MIME 处理包
* json: json --- JSON 编码和解码器. JSON 编码和解码器
* mailcap: mailcap --- Mailcap 文件处理. Mailcap 文件处理
* mailbox: mailbox --- 操作多种格式的邮箱. 操作多种格式的邮箱
* mimetypes: mimetypes --- 映射文件夹到 MIME 类型. 映射文件夹到 MIME 类型
* base64: base64 --- Base16 Base32 Base64 Base85 数据编码. Base16, Base32, Base64, Base85 数据编码
* binhex: binhex --- 对binhex4文件进行编码和解码. 对binhex4文件进行编码和解码
* binascii: binascii --- 二进制和 ASCII 码互转. 二进制和 ASCII 码互转
* quopri: quopri --- 编码与解码经过 MIME 转码的可打印数据. 编码与解码经过 MIME 转码的可打印数据
* uu: uu --- 对 uuencode 文件进行编码与解码. 对 uuencode 文件进行编码与解码

email — 电子邮件与 MIME 处理包

* email.message; 表示一封电子邮件信息: email message 表示一封电子邮件信息.
* email.parser; 解析电子邮件信息: email parser 解析电子邮件信息.
* email.generator; 生成 MIME 文档: email generator 生成 MIME 文档.
* email.policy; 策略对象: email policy 策略对象.
* email.errors; 异常和缺陷类: email errors 异常和缺陷类.
* email.headerregistry; 自定义标头对象: email headerregistry 自定义标头对象.
* email.contentmanager; 管理 MIME 内容: email contentmanager 管理 MIME 内容.
* email; 示例: email 示例.
* email.message.Message; 使用 compat32 API 来表示电子邮件消息: email message Message 使用 compat32 API 来表示电子邮件消息.
* email.mime; 从头创建电子邮件和 MIME 对象: email mime 从头创建电子邮件和 MIME 对象.
* email.header; 国际化标头: email header 国际化标头.
* email.charset; 表示字符集: email charset 表示字符集.
* email.encoders; 编码器: email encoders 编码器.
* email.utils; 其他工具: email utils 其他工具.
* email.iterators; 迭代器: email iterators 迭代器.

email.parser: 解析电子邮件信息

* FeedParser API::
* Parser API::
* 附加说明::

email.contentmanager: 管理 MIME 内容

* 内容管理器实例::

json — JSON 编码和解码器

* 基本使用::
* 编码器和解码器::
* 异常: 异常<13>.
* 标准符合性和互操作性::
* 命令行界面: 命令行界面<4>.

标准符合性和互操作性

* 字符编码::
* Infinite 和 NaN 数值::
* 对象中的重复名称::
* 顶级非对象，非数组值::
* 实现限制::

命令行界面

* 命令行选项: 命令行选项<4>.

mailbox — 操作多种格式的邮箱

* Mailbox 对象::
* Message 对象::
* 异常: 异常<14>.
* 例子: 例子<18>.

Mailbox 对象

* Maildir::
* mbox::
* MH::
* Babyl::
* MMDF::

Message 对象

* MaildirMessage::
* mboxMessage::
* MHMessage::
* BabylMessage::
* MMDFMessage::

mimetypes — 映射文件夹到 MIME 类型

* MimeTypes 对象::

binhex — 对binhex4文件进行编码和解码

* 注释: 注释<3>.

结构化标记处理工具

* html: html --- 超文本标记语言支持. 超文本标记语言支持
* html.parser: html parser --- 简单的 HTML 和 XHTML 解析器. 简单的 HTML 和 XHTML 解析器
* html.entities: html entities --- HTML 一般实体的定义. HTML 一般实体的定义
* XML处理模块::
* xml.etree.ElementTree: xml etree ElementTree --- ElementTree XML API. ElementTree XML API
* xml.dom: xml dom --- 文档对象模型 API. 文档对象模型 API
* xml.dom.minidom: xml dom minidom --- 最小化的 DOM 实现. 最小化的 DOM 实现
* xml.dom.pulldom: xml dom pulldom --- 支持构建部分 DOM 树. 支持构建部分 DOM 树
* xml.sax: xml sax --- 支持 SAX2 解析器. 支持 SAX2 解析器
* xml.sax.handler: xml sax handler --- SAX 处理程序的基类. SAX 处理程序的基类
* xml.sax.saxutils: xml sax saxutils --- SAX 工具集. SAX 工具集
* xml.sax.xmlreader: xml sax xmlreader --- 用于 XML 解析器的接口. 用于 XML 解析器的接口
* xml.parsers.expat: xml parsers expat --- 使用 Expat 的快速 XML 解析. 使用 Expat 的快速 XML 解析

html.parser — 简单的 HTML 和 XHTML 解析器

* HTML 解析器的示例程序::
* HTMLParser 方法::
* 例子: 例子<19>.

XML处理模块

* XML 漏洞::
* defusedxml 包::

xml.etree.ElementTree —  ElementTree XML API

* 教程::
* XPath支持::
* 参考: 参考<2>.
* XInclude 支持::
* 参考: 参考<3>.

教程

* XML树和元素::
* 解析XML::
* Pull API进行非阻塞解析::
* 查找感兴趣的元素::
* 修改XML文件::
* 构建XML文档::
* 使用命名空间解析XML::
* 其他资源: 其他资源<2>.

XPath支持

* 示例: 示例<10>.
* 支持的XPath语法::

参考

* 函数: 函数<6>.

XInclude 支持

* 示例: 示例<11>.

参考

* 函数: 函数<7>.
* 元素对象::
* ElementTree 对象::
* QName 对象::
* TreeBuilder 对象::
* XMLParser对象::
* XMLPullParser对象::
* 异常: 异常<15>.

xml.dom — 文档对象模型 API

* 模块内容: 模块内容<6>.
* DOM 中的对象::
* 一致性::

DOM 中的对象

* DOMImplementation 对象::
* 节点对象::
* 节点列表对象::
* 文档类型对象::
* 文档对象::
* 元素对象: 元素对象<2>.
* Attr 对象::
* NamedNodeMap 对象::
* 注释对象::
* Text 和 CDATASection 对象::
* ProcessingInstruction 对象::
* 异常: 异常<16>.

一致性

* 类型映射::
* 访问器方法::

xml.dom.minidom — 最小化的 DOM 实现

* DOM 对象::
* DOM 示例::
* minidom 和 DOM 标准::

xml.dom.pulldom — 支持构建部分 DOM 树

* DOMEventStream 对象::

xml.sax — 支持 SAX2 解析器

* SAXException 对象::

xml.sax.handler — SAX 处理程序的基类

* ContentHandler 对象::
* DTDHandler 对象::
* EntityResolver 对象::
* ErrorHandler 对象::

xml.sax.xmlreader — 用于 XML 解析器的接口

* XMLReader 对象::
* IncrementalParser 对象::
* Locator 对象::
* InputSource 对象::
* Attributes 接口::
* AttributesNS 接口::

xml.parsers.expat —  使用 Expat 的快速 XML 解析

* XMLParser对象: XMLParser对象<2>.
* ExpatError 异常::
* 示例: 示例<12>.
* 内容模型描述::
* Expat 错误常量::

互联网协议和支持

* webbrowser: webbrowser --- 方便的Web浏览器控制器. 方便的Web浏览器控制器
* cgi: cgi --- 通用网关接口支持. 通用网关接口支持
* cgitb: cgitb --- 用于 CGI 脚本的回溯管理器. 用于 CGI 脚本的回溯管理器
* wsgiref: wsgiref --- WSGI Utilities and Reference Implementation. WSGI Utilities and Reference Implementation
* urllib: urllib --- URL 处理模块. URL 处理模块
* urllib.request: urllib request --- 用于打开 URL 的可扩展库. 用于打开 URL 的可扩展库
* urllib.response: urllib response --- urllib 使用的 Response 类. urllib 使用的 Response 类
* urllib.parse 用于解析 URL: urllib parse 用于解析 URL.
* urllib.error: urllib error --- urllib request 引发的异常类. urllib.request 引发的异常类
* urllib.robotparser: urllib robotparser --- robots txt 语法分析程序. robots.txt 语法分析程序
* http: http --- HTTP 模块. HTTP 模块
* http.client: http client --- HTTP 协议客户端. HTTP 协议客户端
* ftplib: ftplib --- FTP 协议客户端. FTP 协议客户端
* poplib: poplib --- POP3 协议客户端. POP3 协议客户端
* imaplib: imaplib --- IMAP4 协议客户端. IMAP4 协议客户端
* nntplib: nntplib --- NNTP protocol client. NNTP protocol client
* smtplib ---SMTP协议客户端::
* smtpd: smtpd --- SMTP 服务器. SMTP 服务器
* telnetlib: telnetlib -- Telnet 客户端. Telnet 客户端
* uuid: uuid --- UUID objects according to RFC 4122. UUID objects according to RFC 4122
* socketserver: socketserver --- A framework for network servers. A framework for network servers
* http.server: http server --- HTTP 服务器. HTTP 服务器
* http.cookies: http cookies --- HTTP状态管理. HTTP状态管理
* http.cookiejar —— HTTP 客户端的 Cookie 处理: http cookiejar —— HTTP 客户端的 Cookie 处理.
* xmlrpc: xmlrpc --- XMLRPC 服务端与客户端模块. XMLRPC 服务端与客户端模块
* xmlrpc.client: xmlrpc client --- XML-RPC 客户端访问. XML-RPC 客户端访问
* xmlrpc.server: xmlrpc server --- 基本 XML-RPC 服务器. 基本 XML-RPC 服务器
* ipaddress: ipaddress --- IPv4/IPv6 操作库. IPv4/IPv6 操作库

webbrowser — 方便的Web浏览器控制器

* 浏览器控制器对象::

cgi — 通用网关接口支持

* 概述: 概述<11>.
* 使用cgi模块。::
* 更高层级的接口::
* 函数: 函数<8>.
* Caring about security::
* Installing your CGI script on a Unix system::
* Testing your CGI script::
* Debugging CGI scripts::
* Common problems and solutions::

wsgiref — WSGI Utilities and Reference Implementation

* wsgiref.util: wsgiref util -- WSGI environment utilities. WSGI environment utilities
* wsgiref.headers: wsgiref headers -- WSGI response header tools. WSGI response header tools
* wsgiref.simple_server: wsgiref simple_server -- a simple WSGI HTTP server. a simple WSGI HTTP server
* wsgiref.validate: wsgiref validate --- WSGI conformance checker. WSGI conformance checker
* wsgiref.handlers: wsgiref handlers -- server/gateway base classes. server/gateway base classes
* 例子: 例子<20>.

urllib.request — 用于打开 URL 的可扩展库

* Request 对象::
* OpenerDirector 对象::
* BaseHandler 对象::
* HTTPRedirectHandler 对象::
* HTTPCookieProcessor 对象::
* ProxyHandler 对象::
* HTTPPasswordMgr 对象::
* HTTPPasswordMgrWithPriorAuth 对象::
* AbstractBasicAuthHandler 对象::
* HTTPBasicAuthHandler 对象::
* ProxyBasicAuthHandler 对象::
* AbstractDigestAuthHandler 对象::
* HTTPDigestAuthHandler 对象::
* ProxyDigestAuthHandler 对象::
* HTTPHandler 对象::
* HTTPSHandler 对象::
* FileHandler 对象::
* DataHandler 对象::
* FTPHandler 对象::
* CacheFTPHandler 对象::
* UnknownHandler 对象::
* HTTPErrorProcessor 对象::
* 例子: 例子<21>.
* 已停用的接口::
* urllib.request Restrictions: urllib request Restrictions.

urllib.parse  用于解析 URL

* URL 解析::
* 解析ASCII编码字节::
* 结构化解析结果::
* URL Quoting::

http — HTTP 模块

* HTTP 状态码::

http.client — HTTP 协议客户端

* HTTPConnection 对象::
* HTTPResponse 对象::
* 例子: 例子<22>.
* HTTPMessage Objects::

ftplib — FTP 协议客户端

* FTP 对象::
* FTP_TLS 对象::

poplib — POP3 协议客户端

* POP3 对象::
* POP3 示例::

imaplib — IMAP4 协议客户端

* IMAP4 Objects::
* IMAP4 Example::

nntplib — NNTP protocol client

* NNTP Objects::
* 工具函数: 工具函数<2>.

NNTP Objects

* Attributes::
* 方法: 方法<3>.

smtplib —SMTP协议客户端

* SMTP Objects::
* SMTP Example::

smtpd — SMTP 服务器

* SMTPServer 对象::
* DebuggingServer 对象::
* PureProxy对象::
* MailmanProxy 对象::
* SMTPChannel 对象::

telnetlib – Telnet 客户端

* Telnet 对象::
* Telnet 示例::

uuid — UUID objects according to RFC 4122

* 示例: 示例<13>.

socketserver — A framework for network servers

* Server Creation Notes::
* Server 对象: Server 对象<2>.
* Request Handler Objects::
* 例子: 例子<23>.

例子

* socketserver.TCPServer Example: socketserver TCPServer Example.
* socketserver.UDPServer Example: socketserver UDPServer Example.
* Asynchronous Mixins::

http.cookies — HTTP状态管理

* Cookie 对象::
* Morsel 对象::
* 示例: 示例<14>.

http.cookiejar —— HTTP 客户端的 Cookie 处理

* CookieJar 和 FileCookieJar 对象::
* FileCookieJar subclasses and co-operation with web browsers::
* CookiePolicy 对象::
* DefaultCookiePolicy 对象::
* Cookie 对象: Cookie 对象<2>.
* 例子: 例子<24>.

xmlrpc.client — XML-RPC 客户端访问

* ServerProxy 对象::
* DateTime 对象::
* Binary 对象::
* Fault 对象::
* ProtocolError 对象::
* MultiCall 对象::
* Convenience Functions::
* Example of Client Usage::
* Example of Client and Server Usage::

xmlrpc.server — 基本 XML-RPC 服务器

* SimpleXMLRPCServer Objects::
* CGIXMLRPCRequestHandler::
* Documenting XMLRPC server::
* DocXMLRPCServer Objects::
* DocCGIXMLRPCRequestHandler::

SimpleXMLRPCServer Objects

* SimpleXMLRPCServer Example::

ipaddress — IPv4/IPv6 操作库

* 方便的工厂函数::
* IP 地址::
* IP网络的定义::
* Interface objects::
* Other Module Level Functions::
* Custom Exceptions::

IP 地址

* 地址对象::
* Conversion to Strings and Integers::
* 运算符: 运算符<3>.

运算符

* 比较运算符::
* 算术运算符::

IP网络的定义

* Prefix, net mask and host mask: Prefix net mask and host mask.
* Network objects::
* 运算符: 运算符<4>.

运算符

* Logical operators::
* 迭代: 迭代<2>.
* Networks as containers of addresses::

Interface objects

* 运算符: 运算符<5>.

运算符

* Logical operators: Logical operators<2>.

多媒体服务

* audioop: audioop --- 处理原始音频数据. 处理原始音频数据
* aifc: aifc --- 读写 AIFF 和 AIFC 文件. 读写 AIFF 和 AIFC 文件
* sunau: sunau --- 读写 Sun AU 文件. 读写 Sun AU 文件
* wave: wave --- 读写WAV格式文件. 读写WAV格式文件
* chunk: chunk --- 读取 IFF 分块数据. 读取 IFF 分块数据
* colorsys: colorsys --- 颜色系统间的转换. 颜色系统间的转换
* imghdr: imghdr --- 推测图像类型. 推测图像类型
* sndhdr: sndhdr --- 推测声音文件的类型. 推测声音文件的类型
* ossaudiodev: ossaudiodev --- 访问兼容OSS的音频设备. 访问兼容OSS的音频设备

sunau — 读写 Sun AU 文件

* AU_read 对象::
* AU_write 对象::

wave — 读写WAV格式文件

* Wave_read对象::
* Wave_write 对象::

ossaudiodev  — 访问兼容OSS的音频设备

* Audio Device Objects::
* Mixer Device Objects::

国际化

* gettext: gettext --- 多语种国际化服务. 多语种国际化服务
* locale: locale --- 国际化服务. 国际化服务

gettext — 多语种国际化服务

* GNU gettext API::
* 基于类的 API::
* 国际化 (I18N) 你的程序和模块: 国际化 I18N 你的程序和模块.
* 致谢: 致谢<9>.

基于类的 API

* NullTranslations 类::
* GNUTranslations 类::
* Solaris 消息编目支持::
* 编目构造器::

国际化 (I18N) 你的程序和模块

* 本地化你的模块::
* 本地化你的应用程序::
* 即时更改语言::
* 延迟翻译::

locale — 国际化服务

* Background, details, hints, tips and caveats: Background details hints tips and caveats.
* For extension writers and programs that embed Python::
* Access to message catalogs::

程序框架

* turtle: turtle --- 海龟绘图. 海龟绘图
* cmd: cmd --- 支持面向行的命令解释器. 支持面向行的命令解释器
* shlex: shlex --- Simple lexical analysis. Simple lexical analysis

turtle — 海龟绘图

* 概述: 概述<12>.
* 可用的 Turtle 和 Screen 方法概览::
* RawTurtle/Turtle 方法和对应函数::
* TurtleScreen/Screen 方法及对应函数::
* 公共类::
* 帮助与配置::
* turtledemo: turtledemo --- 演示脚本集. 演示脚本集
* Python 2.6 之后的变化: Python 2 6 之后的变化.
* Python 3.0 之后的变化: Python 3 0 之后的变化.

可用的 Turtle 和 Screen 方法概览

* Turtle 方法::
* TurtleScreen/Screen 方法::

RawTurtle/Turtle 方法和对应函数

* 海龟动作::
* 获取海龟的状态::
* 度量单位设置::
* 画笔控制::
* 海龟状态::
* 使用事件::
* 特殊海龟方法::
* 复合形状::

画笔控制

* 绘图状态::
* 颜色控制::
* 填充::
* 更多绘图控制::

海龟状态

* 可见性::
* 外观::

TurtleScreen/Screen 方法及对应函数

* 窗口控制::
* 动画控制::
* 使用屏幕事件::
* 输入方法::
* 设置与特殊方法::
* Screen 专有方法, 而非继承自 TurtleScreen: Screen 专有方法 而非继承自 TurtleScreen.

帮助与配置

* 如何使用帮助::
* 文档字符串翻译为不同的语言::
* 如何配置 Screen 和 Turtle::

cmd — 支持面向行的命令解释器

* Cmd 对象::
* Cmd 例子::

shlex — Simple lexical analysis

* shlex Objects::
* Parsing Rules::
* Improved Compatibility with Shells::

Tk图形用户界面(GUI)

* tkinter: tkinter --- Tcl/Tk的Python接口. Tcl/Tk的Python接口
* tkinter.ttk: tkinter ttk --- Tk主题小部件. Tk主题小部件
* tkinter.tix: tkinter tix --- TK扩展包. TK扩展包
* tkinter.scrolledtext: tkinter scrolledtext --- 滚动文字控件. 滚动文字控件
* IDLE: IDLE<54>.
* 其他图形用户界面（GUI）包::

tkinter — Tcl/Tk的Python接口

* Tkinter 模块::
* Tkinter Life Preserver::
* A (Very) Quick Look at Tcl/Tk: A Very Quick Look at Tcl/Tk.
* Mapping Basic Tk into Tkinter::
* How Tk and Tkinter are Related::
* Handy Reference::
* File Handlers::

Tkinter Life Preserver

* How To Use This Section::
* A Simple Hello World Program::

Handy Reference

* Setting Options::
* The Packer::
* Packer Options::
* Coupling Widget Variables::
* The Window Manager::
* Tk Option Data Types::
* Bindings and Events::
* The index Parameter::
* Images::

tkinter.ttk — Tk主题小部件

* 使用 Ttk::
* Ttk 部件::
* 控件::
* 组合框::
* Spinbox::
* 笔记本::
* Progressbar::
* Separator::
* Sizegrip::
* Treeview::
* Ttk Styling::

控件

* 标准选项::
* 可滚动控件选项::
* 标签选项::
* 兼容性选项::
* 控件状态::
* ttk.Widget: ttk Widget.

组合框

* 选项::
* 虚拟事件::
* ttk.Combobox: ttk Combobox.

Spinbox

* 选项: 选项<2>.
* 虚拟事件: 虚拟事件<2>.
* ttk.Spinbox: ttk Spinbox.

笔记本

* 选项: 选项<3>.
* Tab 选项::
* Tab Identifiers::
* Virtual Events::
* ttk.Notebook: ttk Notebook.

Progressbar

* 选项: 选项<4>.
* ttk.Progressbar: ttk Progressbar.

Separator

* 选项: 选项<5>.

Sizegrip

* Platform-specific notes::
* Bugs::

Treeview

* 选项: 选项<6>.
* Item Options::
* Tag Options::
* Column Identifiers::
* Virtual Events: Virtual Events<2>.
* ttk.Treeview: ttk Treeview.

Ttk Styling

* Layouts::

tkinter.tix — TK扩展包

* Using Tix::
* Tix Widgets::
* Tix Commands::

Tix Widgets

* Basic Widgets::
* File Selectors::
* Hierarchical ListBox::
* Tabular ListBox::
* Manager Widgets::
* Image Types::
* Miscellaneous Widgets::
* Form Geometry Manager::

IDLE

* 目录::
* 编辑和导航::
* 启动和代码执行::
* 帮助和偏好::

目录

* 文件菜单 （命令行和编辑器）::
* 编辑菜单（命令行和编辑器）::
* 格式菜单（仅 window 编辑器）::
* 运行菜单（仅 window 编辑器）::
* Shell 菜单（仅 window 编辑器）::
* 调试菜单（仅 window 编辑器）::
* 选项菜单（命令行和编辑器）::
* Window 菜单（命令行和编辑器）::
* 帮助菜单（命令行和编辑器）::
* 上下文菜单::

编辑和导航

* 编辑窗口::
* 按键绑定::
* 自动缩进::
* 完成::
* 提示::
* 代码上下文::
* Python Shell 窗口::
* 文本颜色::

启动和代码执行

* 命令行语法::
* 启动失败::
* 运行用户代码::
* Shell中的用户输出::
* 开发 tkinter 应用程序::
* 在没有子进程的情况下运行::

帮助和偏好

* 帮助源::
* 首选项设置::
* macOS 上的IDLE::
* 扩展::

开发工具

* typing: typing --- 类型标注支持. 类型标注支持
* pydoc: pydoc --- 文档生成器和在线帮助系统. 文档生成器和在线帮助系统
* doctest: doctest --- 测试交互性的Python示例. 测试交互性的Python示例
* unittest: unittest --- 单元测试框架. 单元测试框架
* unittest.mock: unittest mock --- 模拟对象库. 模拟对象库
* unittest.mock 上手指南: unittest mock 上手指南.
* 2to3 - 自动将 Python 2 代码转为 Python 3 代码::
* test: test --- Python回归测试包. Python回归测试包
* test.support: test support --- Utilities for the Python test suite. Utilities for the Python test suite
* test.support.script_helper: test support script_helper --- Utilities for the Python execution tests. Utilities for the Python execution tests

typing — 类型标注支持

* 类型别名::
* NewType::
* Callable::
* 泛型(Generic): 泛型 Generic.
* 用户定义的泛型类型::
* Any 类型::
* 名义性子类型 区别于 结构性子类型::
* 类,函数和修饰器.: 类 函数和修饰器.

doctest — 测试交互性的Python示例

* 简单用法：检查Docstrings中的示例::
* Simple Usage; Checking Examples in a Text File: Simple Usage Checking Examples in a Text File.
* How It Works::
* Basic API::
* Unittest API::
* Advanced API::
* 调试::
* Soapbox::

How It Works

* Which Docstrings Are Examined?::
* How are Docstring Examples Recognized?::
* What's the Execution Context?::
* What About Exceptions?::
* Option Flags::
* Directives::
* 警告: 警告<2>.

Advanced API

* DocTest 对象::
* Example Objects::
* DocTestFinder 对象::
* DocTestParser 对象::
* DocTestRunner 对象::
* OutputChecker 对象::

unittest — 单元测试框架

* 基本实例::
* 命令行界面: 命令行界面<5>.
* 探索性测试::
* 组织你的测试代码::
* 复用已有的测试代码::
* 跳过测试与预计的失败::
* Distinguishing test iterations using subtests::
* 类与函数::
* Class and Module Fixtures::
* 信号处理::

命令行界面

* 命令行选项: 命令行选项<5>.

类与函数

* 测试用例::
* Grouping tests::
* Loading and running tests::

测试用例

* Deprecated aliases::

Loading and running tests

* load_tests Protocol::

Class and Module Fixtures

* setUpClass and tearDownClass::
* setUpModule and tearDownModule::

unittest.mock — 模拟对象库

* 快速上手::
* Mock 类::
* The patchers::
* MagicMock and magic method support::
* Helpers::

Mock 类

* Calling::
* Deleting Attributes::
* Mock names and the name attribute::
* Attaching Mocks as Attributes::

The patchers

* patch::
* patch.object: patch object.
* patch.dict: patch dict.
* patch.multiple: patch multiple.
* patch methods; start and stop: patch methods start and stop.
* patch builtins::
* TEST_PREFIX::
* Nesting Patch Decorators::
* Where to patch::
* Patching Descriptors and Proxy Objects::

MagicMock and magic method support

* Mocking Magic Methods::
* Magic Mock::

Helpers

* sentinel::
* DEFAULT::
* call::
* create_autospec::
* ANY::
* FILTER_DIR::
* mock_open::
* Autospeccing::
* Sealing mocks::

unittest.mock 上手指南

* 使用 mock::
* Patch Decorators::
* Further Examples::

使用 mock

* 模拟方法调用::
* 对象上的方法调用的 mock::
* Mocking Classes::
* Naming your mocks::
* Tracking all Calls::
* Setting Return Values and Attributes::
* Raising exceptions with mocks::
* Side effect functions and iterables::
* Mocking asynchronous iterators::
* Mocking asynchronous context manager::
* Creating a Mock from an Existing Object::

Further Examples

* Mocking chained calls::
* Partial mocking::
* Mocking a Generator Method::
* Applying the same patch to every test method::
* Mocking Unbound Methods::
* Checking multiple calls with mock::
* Coping with mutable arguments::
* Nesting Patches::
* Mocking a dictionary with MagicMock::
* Mock subclasses and their attributes::
* Mocking imports with patch.dict: Mocking imports with patch dict.
* Tracking order of calls and less verbose call assertions::
* More complex argument matching::

2to3 - 自动将 Python 2 代码转为 Python 3 代码

* 使用 2to3::
* 修复器::
* lib2to3 —— 2to3 支持库::

test —  Python回归测试包

* Writing Unit Tests for the test package::
* Running tests using the command-line interface::

调试和分析

* 审计事件表::
* bdb: bdb --- Debugger framework. Debugger framework
* faulthandler: faulthandler --- Dump the Python traceback. Dump the Python traceback
* pdb: pdb --- Python的调试器. Python的调试器
* Python Profilers 分析器::
* timeit: timeit --- 测量小代码片段的执行时间. 测量小代码片段的执行时间
* trace: trace --- 跟踪Python语句的执行. 跟踪Python语句的执行
* tracemalloc: tracemalloc --- 跟踪内存分配. 跟踪内存分配

faulthandler — Dump the Python traceback

* Dumping the traceback::
* Fault handler state::
* Dumping the tracebacks after a timeout::
* Dumping the traceback on a user signal::
* Issue with file descriptors::
* 示例: 示例<15>.

pdb — Python的调试器

* 调试器命令::

Python Profilers 分析器

* profile分析器简介::
* 实时用户手册::
* profile 和 cProfile 模块参考::
* Stats 类::
* 什么是确定性性能分析？::
* 局限性::
* 准确估量::
* 使用自定义计时器::

timeit — 测量小代码片段的执行时间

* 基本示例: 基本示例<2>.
* Python 接口::
* 命令行界面: 命令行界面<6>.
* 例子: 例子<25>.

trace — 跟踪Python语句的执行

* Command-Line Usage::
* 编程接口::

Command-Line Usage

* Main options::
* Modifiers::
* Filters::

tracemalloc — 跟踪内存分配

* 例子: 例子<26>.
* API::

例子

* 显示前10项::
* 计算差异::
* Get the traceback of a memory block::
* Pretty top::

API

* 函数: 函数<9>.
* 域过滤器::
* 过滤器::
* Frame::
* 快照::
* 统计::
* StatisticDiff::
* 跟踪::
* 回溯: 回溯<4>.

软件打包和分发

* distutils: distutils --- 构建和安装 Python 模块. 构建和安装 Python 模块
* ensurepip: ensurepip --- Bootstrapping the pip installer. Bootstrapping the pip installer
* venv: venv --- 创建虚拟环境. 创建虚拟环境
* zipapp: zipapp --- Manage executable Python zip archives. Manage executable Python zip archives

ensurepip — Bootstrapping the pip installer

* Command line interface::
* Module API::

venv — 创建虚拟环境

* 创建虚拟环境: 创建虚拟环境<2>.
* API: API<2>.
* 一个扩展 EnvBuilder 的例子::

zipapp — Manage executable Python zip archives

* Basic Example::
* 命令行界面: 命令行界面<7>.
* Python API::
* 例子: 例子<27>.
* Specifying the Interpreter::
* Creating Standalone Applications with zipapp::
* The Python Zip Application Archive Format::

Creating Standalone Applications with zipapp

* Making a Windows executable::
* Caveats::

Python运行时服务

* sys: sys --- 系统相关的参数和函数. 系统相关的参数和函数
* sysconfig: sysconfig --- Provide access to Python's configuration information. Provide access to Python’s configuration information
* builtins: builtins --- 内建对象. 内建对象
* __main__: __main__ --- 顶层脚本环境. 顶层脚本环境
* warnings: warnings --- Warning control. Warning control
* dataclasses: dataclasses --- 数据类. 数据类
* contextlib: contextlib --- 为 with语句上下文提供的工具. 为 with语句上下文提供的工具
* abc: abc --- 抽象基类. 抽象基类
* atexit: atexit --- 退出处理器. 退出处理器
* traceback: traceback --- 打印或检索堆栈回溯. 打印或检索堆栈回溯
* __future__: __future__ --- Future 语句定义. Future 语句定义
* gc: gc --- 垃圾回收器接口. 垃圾回收器接口
* inspect: inspect --- 检查对象. 检查对象
* site —— 站点专属的配置钩子::

sysconfig — Provide access to Python’s configuration information

* 配置变量::
* 安装路径::
* 其他功能: 其他功能<3>.
* Using sysconfig as a script::

warnings — Warning control

* 警告类别::
* The Warnings Filter::
* 暂时禁止警告::
* 测试警告::
* Updating Code For New Versions of Dependencies::
* Available Functions::
* Available Context Managers::

The Warnings Filter

* Describing Warning Filters::
* 默认警告过滤器::
* Overriding the default filter::

dataclasses — 数据类

* 模块级装饰器、类和函数::
* 初始化后处理::
* 类变量::
* 仅初始化变量::
* 冻结的实例::
* 继承: 继承<2>.
* 默认工厂函数::
* 可变的默认值::
* 异常: 异常<17>.

contextlib — 为 with语句上下文提供的工具

* 工具::
* 例子和配方: 例子和配方<2>.
* Single use, reusable and reentrant context managers: Single use reusable and reentrant context managers.

例子和配方

* Supporting a variable number of context managers::
* Catching exceptions from __enter__ methods::
* Cleaning up in an __enter__ implementation::
* Replacing any use of try-finally and flag variables::
* Using a context manager as a function decorator::

Single use, reusable and reentrant context managers

* Reentrant context managers::
* Reusable context managers::

atexit — 退出处理器

* atexit 示例::

traceback — 打印或检索堆栈回溯

* TracebackException Objects::
* StackSummary Objects::
* FrameSummary Objects::
* Traceback Examples::

inspect — 检查对象

* 类型和成员::
* Retrieving source code::
* Introspecting callables with the Signature object::
* 类与函数: 类与函数<2>.
* The interpreter stack::
* Fetching attributes statically::
* Current State of Generators and Coroutines::
* Code Objects Bit Flags::
* 命令行界面: 命令行界面<8>.

site —— 站点专属的配置钩子

* Readline（类库） 配置::
* 模块内容: 模块内容<7>.
* 命令行界面: 命令行界面<9>.

自定义 Python 解释器

* code: code --- 解释器基类. 解释器基类
* codeop: codeop --- 编译Python代码. 编译Python代码

code — 解释器基类

* 交互解释器对象::
* 交互式控制台对象::

导入模块

* zipimport: zipimport --- 从 Zip 存档中导入模块. 从 Zip 存档中导入模块
* pkgutil: pkgutil --- 包扩展工具. 包扩展工具
* modulefinder: modulefinder --- 查找脚本使用的模块. 查找脚本使用的模块
* runpy: runpy --- Locating and executing Python modules. Locating and executing Python modules
* importlib: importlib --- import 的实现. import 的实现
* Using importlib.metadata: Using importlib metadata.

zipimport — 从 Zip 存档中导入模块

* zipimporter 对象::
* 例子: 例子<28>.

modulefinder — 查找脚本使用的模块

* ModuleFinder 的示例用法::

importlib — import 的实现

* 概述: 概述<13>.
* 函数: 函数<10>.
* importlib.abc —— 关于导入的抽象基类: importlib abc —— 关于导入的抽象基类.
* importlib.resources: importlib resources -- 资源. 资源
* importlib.machinery: importlib machinery -- Importers and path hooks. Importers and path hooks
* importlib.util: importlib util -- Utility code for importers. Utility code for importers
* 例子: 例子<29>.

例子

* Importing programmatically::
* Checking if a module can be imported::
* Importing a source file directly::
* Setting up an importer::
* Approximating importlib.import_module(): Approximating importlib import_module.

Using importlib.metadata

* 概述: 概述<14>.
* 功能性 API: 功能性 API<2>.
* Distributions::
* Extending the search algorithm::

功能性 API

* Entry points::
* Distribution metadata::
* Distribution versions::
* Distribution files::
* Distribution requirements::

Python 语言服务

* parser: parser --- 访问 Python 解析树. 访问 Python 解析树
* ast: ast --- 抽象语法树. 抽象语法树
* symtable: symtable --- Access to the compiler's symbol tables. Access to the compiler’s symbol tables
* symbol: symbol --- 与 Python 解析树一起使用的常量. 与 Python 解析树一起使用的常量
* token: token --- 与Python解析树一起使用的常量. 与Python解析树一起使用的常量
* keyword: keyword --- 检验Python关键字. 检验Python关键字
* tokenize: tokenize --- 对 Python 代码使用的标记解析器. 对 Python 代码使用的标记解析器
* tabnanny: tabnanny --- 模糊缩进检测. 模糊缩进检测
* pyclbr: pyclbr --- Python 模块浏览器支持. Python 模块浏览器支持
* py_compile: py_compile --- 编译 Python 源文件. 编译 Python 源文件
* compileall: compileall --- Byte-compile Python libraries. Byte-compile Python libraries
* dis: dis --- Python 字节码反汇编器. Python 字节码反汇编器
* pickletools: pickletools --- pickle 开发者工具集. pickle 开发者工具集

parser — 访问 Python 解析树

* 创建 ST 对象::
* 转换 ST 对象::
* Queries on ST Objects::
* 异常和错误处理::
* ST 对象::
* 示例; compile() 的模拟: 示例 compile 的模拟.

ast — 抽象语法树

* 节点类::
* 抽象文法::
* ast 中的辅助函数::

symtable — Access to the compiler’s symbol tables

* Generating Symbol Tables::
* Examining Symbol Tables::

tokenize — 对 Python 代码使用的标记解析器

* 对输入进行解析标记::
* Command-Line Usage: Command-Line Usage<2>.
* 例子: 例子<30>.

pyclbr — Python 模块浏览器支持

* 函数对象::
* 类对象: 类对象<2>.

compileall — Byte-compile Python libraries

* Command-line use::
* Public functions::

dis — Python 字节码反汇编器

* 字节码分析::
* 分析函数::
* Python字节码说明::
* 操作码集合::

pickletools — pickle 开发者工具集

* 命令行语法: 命令行语法<2>.
* 编程接口: 编程接口<2>.

命令行语法

* 命令行选项: 命令行选项<6>.

杂项服务

* formatter: formatter --- 通用格式化输出. 通用格式化输出

formatter — 通用格式化输出

* The Formatter Interface::
* Formatter Implementations::
* The Writer Interface::
* Writer Implementations::

Windows系统相关模块

* msilib: msilib --- Read and write Microsoft Installer files. Read and write Microsoft Installer files
* msvcrt: msvcrt --- 来自 MS VC++ 运行时的有用例程. 来自 MS VC++ 运行时的有用例程
* winreg: winreg --- Windows 注册表访问. Windows 注册表访问
* winsound: winsound --- Sound-playing interface for Windows. Sound-playing interface for Windows

msilib — Read and write Microsoft Installer files

* Database Objects::
* View Objects::
* Summary Information Objects::
* Record Objects::
* Errors::
* CAB Objects::
* Directory Objects::
* 相关特性: 相关特性<3>.
* GUI classes::
* Precomputed tables::

msvcrt — 来自 MS VC++ 运行时的有用例程

* 文件操作::
* 控制台 I/O::
* 其他函数::

winreg — Windows 注册表访问

* 函数: 函数<11>.
* 常量: 常量<10>.
* Registry Handle Objects::

常量

* HKEY_* Constants::
* Access Rights::
* Value Types::

Access Rights

* 64-bit Specific::

Unix 专有服务

* posix: posix --- 最常见的 POSIX 系统调用. 最常见的 POSIX 系统调用
* pwd: pwd --- 用户密码数据库. 用户密码数据库
* spwd: spwd --- The shadow password database. The shadow password database
* grp: grp --- 组数据库. 组数据库
* crypt: crypt --- Function to check Unix passwords. Function to check Unix passwords
* termios: termios --- POSIX 风格的 tty 控制. POSIX 风格的 tty 控制
* tty: tty --- 终端控制功能. 终端控制功能
* pty: pty --- 伪终端工具. 伪终端工具
* fcntl: fcntl --- The fcntl and ioctl system calls. The fcntl and ioctl system calls
* pipes: pipes --- 终端管道接口. 终端管道接口
* resource: resource --- Resource usage information. Resource usage information
* nis: nis --- Sun 的 NIS 黄页 接口. Sun 的 NIS (黄页) 接口
* Unix syslog 库例程::

posix — 最常见的 POSIX 系统调用

* 大文件支持::
* 重要的模块内容::

crypt — Function to check Unix passwords

* Hashing Methods::
* Module Attributes::
* 模块函数: 模块函数<2>.
* 例子: 例子<31>.

termios — POSIX 风格的 tty 控制

* 示例: 示例<16>.

pty — 伪终端工具

* 示例: 示例<17>.

pipes — 终端管道接口

* 模板对象::

resource — Resource usage information

* Resource Limits::
* Resource Usage::

Unix syslog 库例程

* 例子: 例子<32>.

例子

* 简单示例::

被取代的模块

* optparse: optparse --- 解析器的命令行选项. 解析器的命令行选项
* imp: imp --- Access the import internals. Access the import internals

optparse — 解析器的命令行选项

* 背景::
* 教程: 教程<2>.
* 参考指南::
* Option Callbacks::
* Extending optparse::

背景

* 术语::
* What are options for?::
* 位置位置::

教程

* Understanding option actions::
* The store action::
* Handling boolean (flag) options: Handling boolean flag options.
* Other actions::
* 默认值: 默认值<2>.
* Generating help::
* Printing a version string::
* How optparse handles errors::
* Putting it all together::

Generating help

* Grouping Options::

参考指南

* 创建解析器::
* 填充解析器::
* 定义选项::
* Option attributes::
* Standard option actions::
* Standard option types::
* 解析参数: 解析参数<2>.
* Querying and manipulating your option parser::
* Conflicts between options::
* 清理: 清理<2>.
* Other methods::

Option Callbacks

* Defining a callback option::
* How callbacks are called::
* Raising errors in a callback::
* Callback example 1; trivial callback: Callback example 1 trivial callback.
* Callback example 2; check option order: Callback example 2 check option order.
* Callback example 3; check option order (generalized): Callback example 3 check option order generalized.
* Callback example 4; check arbitrary condition: Callback example 4 check arbitrary condition.
* Callback example 5; fixed arguments: Callback example 5 fixed arguments.
* Callback example 6; variable arguments: Callback example 6 variable arguments.

Extending optparse

* Adding new types::
* Adding new actions::

imp — Access the import internals

* 例子: 例子<33>.

未创建文档的模块

* 平台特定模块::

扩展和嵌入 Python 解释器

* 推荐的第三方工具::
* 不使用第三方工具创建扩展::
* 在更大的应用程序中嵌入 CPython 运行时::

不使用第三方工具创建扩展

* 使用 C 或 C++ 扩展 Python::
* 自定义扩展类型：教程::
* 定义扩展类型：已分类主题::
* 构建C/C++扩展::
* 在Windows平台编译C和C++扩展::

使用 C 或 C++ 扩展 Python

* 一个简单的例子::
* 关于错误和异常::
* 回到例子::
* 模块方法表和初始化函数::
* 编译和链接::
* 在C中调用Python函数::
* 提取扩展函数的参数::
* 给扩展函数的关键字参数::
* 构造任意值::
* 引用计数::
* 在C++中编写扩展::
* 给扩展模块提供C API::

引用计数

* Python中的引用计数::
* 拥有规则::
* 危险的薄冰::
* NULL指针::

自定义扩展类型：教程

* 基础::
* Adding data and methods to the Basic example::
* Providing finer control over data attributes::
* Supporting cyclic garbage collection::
* Subclassing other types::

定义扩展类型：已分类主题

* 终结和内存释放::
* 对象展示::
* 属性管理::
* Object Comparison::
* Abstract Protocol Support::
* Weak Reference Support::
* 更多建议::

属性管理

* 泛型属性管理::
* Type-specific Attribute Management::

构建C/C++扩展

* 使用distutils构建C和C++扩展::
* 发布你的扩展模块::

在Windows平台编译C和C++扩展

* 菜谱式说明::
* Unix 和 Windows 之间的差异::
* DLL 的实际使用::

在更大的应用程序中嵌入 CPython 运行时

* 在其它应用程序嵌入 Python::

在其它应用程序嵌入 Python

* Very High Level Embedding::
* Beyond Very High Level Embedding; An overview: Beyond Very High Level Embedding An overview.
* 纯嵌入::
* Extending Embedded Python::
* 在 C++ 中嵌入 Python::
* 在类 Unix 系统中编译和链接::

Python/C API 参考手册

* 概述: 概述<15>.
* 稳定的应用程序二进制接口::
* The Very High Level Layer::
* 引用计数: 引用计数<3>.
* 异常处理::
* 工具: 工具<2>.
* 抽象对象层::
* 具体的对象层::
* 初始化，终结和线程::
* Python初始化配置::
* 内存管理::
* 对象实现支持::
* API 和 ABI 版本管理::

概述

* 代码标准::
* 包含文件::
* 有用的宏::
* 对象、类型和引用计数::
* 异常: 异常<18>.
* 嵌入Python: 嵌入Python<2>.
* 调试构建::

对象、类型和引用计数

* 引用计数: 引用计数<2>.
* 类型::

引用计数

* 引用计数细节::

异常处理

* 打印和清理::
* 抛出异常: 抛出异常<2>.
* 警告: 警告<3>.
* 查询错误指示器::
* 信号处理: 信号处理<2>.
* 异常类::
* 异常对象::
* Unicode 异常对象::
* 递归控制::
* 标准异常::
* 标准警告类别::

工具

* 操作系统实用程序::
* 系统功能::
* 过程控制::
* 导入模块: 导入模块<2>.
* 数据 marshal 操作支持::
* 解析参数并构建值变量::
* 字符串转换与格式化::
* 反射::
* 编解码器注册与支持功能::

解析参数并构建值变量

* 解析参数: 解析参数<3>.
* 创建变量::

解析参数

* 字符串和缓存区::
* 数字: 数字<2>.
* 其他对象::
* API 函数::

编解码器注册与支持功能

* Codec 查找API::
* 用于Unicode编码错误处理程序的注册表API::

抽象对象层

* 对象协议::
* 数字协议::
* 序列协议::
* 映射协议::
* 迭代器协议::
* 缓冲协议::
* 旧缓冲协议::

缓冲协议

* 缓冲区结构::
* 缓冲区请求的类型::
* 复杂数组::
* 缓冲区相关函数::

缓冲区请求的类型

* 与请求无关的字段::
* 只读，格式::
* 形状，步幅，子偏移量::
* 连续性的请求::
* 复合请求::

复杂数组

* NumPy-风格：形状和步幅::
* PIL-风格：形状，步幅和子偏移量::

具体的对象层

* 基本对象::
* 数值对象::
* 序列对象::
* 容器对象::
* 函数对象: 函数对象<2>.
* 其他对象: 其他对象<2>.

基本对象

* 类型对象: 类型对象<2>.
* None 对象::

类型对象

* Creating Heap-Allocated Types::

数值对象

* 整数型对象::
* 布尔对象::
* 浮点数对象::
* 复数对象::

复数对象

* 表示复数的C结构体::
* 表示复数的Python对象::

序列对象

* bytes 对象: bytes 对象<2>.
* 字节数组对象::
* Unicode对象和编码解码器::
* 元组对象::
* 结构序列对象::
* 列表对象::

字节数组对象

* 类型检查宏::
* 直接 API 函数::
* 宏::

Unicode对象和编码解码器

* Unicode对象::
* Built-in Codecs::
* Methods and Slot Functions::

Unicode对象

* Unicode类型::
* Unicode字符属性::
* Creating and accessing Unicode strings::
* Deprecated Py_UNICODE APIs::
* Locale Encoding::
* File System Encoding::
* wchar_t Support::

Built-in Codecs

* Generic Codecs::
* UTF-8 Codecs::
* UTF-32 Codecs::
* UTF-16 Codecs::
* UTF-7 Codecs::
* Unicode-Escape Codecs::
* Raw-Unicode-Escape Codecs::
* Latin-1 Codecs::
* ASCII Codecs::
* Character Map Codecs::
* MBCS codecs for Windows::
* Methods & Slots::

容器对象

* 字典对象::
* 集合对象::

函数对象

* 函数对象: 函数对象<3>.
* 实例方法对象::
* 方法对象: 方法对象<2>.
* Cell 对象::
* 代码对象: 代码对象<2>.

其他对象

* 文件对象::
* 模块对象::
* 迭代器对象::
* 描述符对象::
* 切片对象::
* Ellipsis 对象::
* MemoryView 对象::
* 弱引用对象: 弱引用对象<2>.
* 胶囊: 胶囊<2>.
* 生成器对象::
* 协程对象: 协程对象<2>.
* 上下文变量对象::
* DateTime 对象: DateTime 对象<2>.

模块对象

* Initializing C modules::
* Module lookup::

Initializing C modules

* Single-phase initialization::
* Multi-phase initialization::
* Low-level module creation functions::
* Support functions::

初始化，终结和线程

* 在Python初始化之前::
* 全局配置变量::
* Initializing and finalizing the interpreter::
* Process-wide parameters::
* Thread State and the Global Interpreter Lock::
* Sub-interpreter support::
* 异步通知::
* 分析和跟踪::
* 高级调试器支持::
* Thread Local Storage Support::

Thread State and the Global Interpreter Lock

* Releasing the GIL from extension code::
* 非Python创建的线程::
* Cautions about fork(): Cautions about fork.
* 高阶 API::
* Low-level API::

Sub-interpreter support

* 错误和警告::

Thread Local Storage Support

* Thread Specific Storage (TSS) API: Thread Specific Storage TSS API.
* Thread Local Storage (TLS) API: Thread Local Storage TLS API.

Thread Specific Storage (TSS) API

* Dynamic Allocation::
* 方法: 方法<4>.

Python初始化配置

* PyWideStringList::
* PyStatus::
* PyPreConfig::
* Preinitialization with PyPreConfig::
* PyConfig::
* Initialization with PyConfig::
* Isolated Configuration::
* Python Configuration::
* 路径配置::
* Py_RunMain(): Py_RunMain.
* Multi-Phase Initialization Private Provisional API::

内存管理

* 概述: 概述<16>.
* 原始内存接口::
* 内存接口::
* 对象分配器::
* 默认内存分配器::
* 自定义内存分配器::
* pymalloc 分配器::
* tracemalloc C API::
* 例子: 例子<34>.

pymalloc 分配器

* 自定义 pymalloc Arena 分配器::

对象实现支持

* 在堆上分配对象::
* 公用对象的结构::
* 类型对象: 类型对象<3>.
* Number Object Structures::
* Mapping Object Structures::
* Sequence Object Structures::
* Buffer Object Structures::
* Async Object Structures::
* Slot Type typedefs::
* 例子: 例子<35>.
* 使对象类型支持循环垃圾回收::

类型对象

* 快速参考::
* PyTypeObject Definition::
* PyObject Slots::
* PyVarObject Slots::
* PyTypeObject Slots::
* Heap Types::

快速参考

* "tp 槽"::
* sub-slots::
* slot typedefs::

分发 Python 模块

* 关键术语::
* 开源许可与协作::
* 安装相关工具::
* 阅读 Python 打包用户指南::
* 我该如何...？: 我该如何 ？.

我该如何...？

* ...为我的项目选择一个名字？: 为我的项目选择一个名字？.
* ...创建和分发二进制扩展？: 创建和分发二进制扩展？.

安装 Python 模块

* 关键术语: 关键术语<2>.
* 基本使用: 基本使用<2>.
* 我应如何 ...？: 我应如何 ？.
* 常见的安装问题::

我应如何 ...？

* ... 在 Python 3.4 之前的 Python 版本中安装 pip ？: 在 Python 3 4 之前的 Python 版本中安装 pip ？.
* ... 只为当前用户安装软件包？: 只为当前用户安装软件包？.
* ... 安装科学计算类 Python 软件包？: 安装科学计算类 Python 软件包？.
* ... 使用并行安装的多个 Python 版本？: 使用并行安装的多个 Python 版本？.

常见的安装问题

* 在 Linux 的系统 Python 版本上安装::
* 未安装 pip::
* 安装二进制编译扩展::

Python 常用指引

* 将 Python 2 代码迁移到 Python 3::
* 将扩展模块移植到 Python 3::
* 用 Python 进行 Curses 编程::
* 描述器使用指南::
* 函数式编程指引::
* 日志常用指引::
* 日志操作手册::
* 正则表达式HOWTO::
* 套接字编程指南::
* 排序指南::
* Unicode 指南::
* HOWTO 使用 urllib 包获取网络资源::
* Argparse 教程::
* ipaddress模块介绍::
* Argument Clinic How-To::
* 使用 DTrace 和 SystemTap 检测CPython::

将 Python 2 代码迁移到 Python 3

* 简要说明::
* 详情::

详情

* 删除对Python 2.6及更早版本的支持: 删除对Python 2 6及更早版本的支持.
* Make sure you specify the proper version support in your setup.py file: Make sure you specify the proper version support in your setup py file.
* 良好的测试覆盖率::
* 了解Python 2 和 3之间的区别::
* 更新代码::
* Prevent compatibility regressions::
* Check which dependencies block your transition::
* Update your setup.py file to denote Python 3 compatibility: Update your setup py file to denote Python 3 compatibility.
* Use continuous integration to stay compatible::
* 考虑使用可选的静态类型检查::

更新代码

* 除法::
* 文本与二进制数据::
* Use feature detection instead of version detection::

用 Python 进行 Curses 编程

* curses 是什么？::
* 开始和结束curses应用程序::
* 窗口和面板::
* 显示文字::
* 用户输入::
* 更多的信息::

curses 是什么？

* Python 的 curses 模块::

显示文字

* 属性和颜色::

描述器使用指南

* 摘要::
* 定义和简介::
* 描述器协议::
* 调用描述器: 调用描述器<2>.
* 描述器示例::
* 属性::
* 函数和方法::
* 静态方法和类方法::

函数式编程指引

* 概述: 概述<17>.
* 迭代器: 迭代器<2>.
* 生成器表达式和列表推导式::
* 生成器: 生成器<2>.
* 内置函数: 内置函数<2>.
* itertools 模块::
* functools 模块::
* 小函数和 lambda 表达式::
* 修订记录和致谢::
* 参考文献: 参考文献<2>.

概述

* 形式证明::
* 模块化::
* 易于调试和测试::
* 组合性::

迭代器

* 支持迭代器的数据类型::

生成器

* 向生成器传递值::

itertools 模块

* 创建新的迭代器::
* 对元素使用函数::
* 选择元素::
* 组合函数::
* 为元素分组::

functools 模块

* operator 模块::

参考文献

* 通用文献::
* Python 相关::
* Python 文档::

日志常用指引

* 日志基础教程::
* 进阶日志教程::
* 日志级别: 日志级别<2>.
* 有用的处理程序::
* 记录日志中引发的异常::
* 使用任意对象作为消息::
* 优化::

日志基础教程

* 什么时候使用日志::
* 一个简单的例子: 一个简单的例子<2>.
* 记录日志到文件::
* 从多个模块记录日志::
* 记录变量数据::
* 更改显示消息的格式::
* 在消息中显示日期/时间::
* 后续步骤::

进阶日志教程

* 记录流程::
* 记录器::
* 处理程序::
* 格式化程序::
* 配置日志记录::
* 如果没有提供配置会发生什么::
* 配置库的日志记录::

日志级别

* 自定义级别::

日志操作手册

* 在多个模块中记录日志::
* 在多个线程中记录日志::
* 多个日志处理器以及多种格式化器::
* 在多个地方记录日志::
* 日志服务器配置示例::
* 处理日志处理器的阻塞::
* 通过网络发送和接收日志::
* 在日志记录中添加上下文信息::
* 从多个进程记录至单个文件::
* 轮换日志文件::
* 使用其他日志格式化方式::
* 自定义 LogRecord::
* 子类化 QueueHandler - ZeroMQ 示例::
* 子类化 QueueListener —— ZeroMQ 示例::
* 基于字典进行日志配置的示例::
* 利用 rotator 和 namer 自定义日志轮换操作::
* 更加详细的多道处理示例::
* 在发送给 SysLogHandler 的信息中插入一个 BOM。::
* 结构化日志的实现代码::
* 利用 dictConfig() 自定义 handler: 利用 dictConfig 自定义 handler.
* 生效于整个应用程序的格式化样式::
* 利用 dictConfig() 定义过滤器: 利用 dictConfig 定义过滤器.
* 异常信息的自定义格式化::
* 语音播报日志信息::
* 缓冲日志消息并有条件地输出它们::
* 通过配置使用UTC (GMT) 格式化时间: 通过配置使用UTC GMT 格式化时间.
* 使用上下文管理器的可选的日志记录::
* 命令行日志应用起步::
* Qt GUI 日志示例::

在日志记录中添加上下文信息

* 使用日志适配器传递上下文信息::
* 使用过滤器传递上下文信息::

使用日志适配器传递上下文信息

* 使用除字典之外的其它对象传递上下文信息::

从多个进程记录至单个文件

* concurrent.futures.ProcessPoolExecutor 的用法: concurrent futures ProcessPoolExecutor 的用法.

生效于整个应用程序的格式化样式

* LogRecord 工厂的用法::
* 自定义信息对象的使用::

正则表达式HOWTO

* 概述: 概述<18>.
* 简单模式::
* 使用正则表达式::
* 更多模式能力::
* 修改字符串::
* 常见问题::
* 反馈::

简单模式

* 匹配字符::
* 重复::

使用正则表达式

* 编译正则表达式::
* 反斜杠灾难::
* 应用匹配::
* 模块级别函数: 模块级别函数<2>.
* 编译标志::

更多模式能力

* 更多元字符::
* 分组::
* 非捕获和命名组::
* 前向断言::

修改字符串

* 分割字符串::
* 搜索和替换::

常见问题

* 使用字符串方法::
* match() 和 search(): match 和 search.
* 贪婪与非贪婪::
* 使用 re.VERBOSE: 使用 re VERBOSE.

套接字编程指南

* 套接字::
* 创建套接字: 创建套接字<2>.
* 使用一个套接字::
* 断开连接::
* 非阻塞的套接字::

套接字

* 历史::

创建套接字

* 进程间通信::

使用一个套接字

* 二进制数据::

断开连接

* 套接字何时销毁::

排序指南

* 基本排序::
* 关键函数::
* Operator 模块函数::
* 升序和降序::
* 排序稳定性和排序复杂度::
* 使用装饰-排序-去装饰的旧方法::
* 使用 cmp 参数的旧方法::
* 其它::

Unicode 指南

* Unicode 概述::
* Python对Unicode的支持::
* Unicode 数据的读写::
* 致谢: 致谢<10>.

Unicode 概述

* 定义::
* 编码::
* 参考文献: 参考文献<3>.

Python对Unicode的支持

* 字符串类型::
* 转换为字节::
* Python 源代码中的 Unicode 文字::
* Unicode属性::
* 字符串比较::
* Unicode 正则表达式::
* 参考文献: 参考文献<4>.

Unicode 数据的读写

* Unicode 文件名::
* 识别 Unicode 的编程技巧::
* 参考文献: 参考文献<5>.

识别 Unicode 的编程技巧

* 在文件编码格式之间进行转换::
* 编码格式未知的文件::

HOWTO 使用 urllib 包获取网络资源

* 概述: 概述<19>.
* 提取URL::
* 处理异常: 处理异常<2>.
* info and geturl::
* Opener 和 Handler::
* 基本认证::
* 代理::
* 套接字与分层::
* 备注::

提取URL

* 数据::
* HTTP 头部信息::

处理异常

* URLError::
* HTTPError::
* 包装起来::

HTTPError

* 错误代码::

包装起来

* 数字1::
* 第二种方案::

Argparse 教程

* 概念::
* 基础: 基础<2>.
* 位置参数介绍::
* 可选参数介绍::
* 结合位置参数和可选参数::
* 进行一些小小的改进::
* 后记::

可选参数介绍

* 短选项::

进行一些小小的改进

* 矛盾的选项::

ipaddress模块介绍

* 创建 Address/Network/Interface 对象::
* 审查 Address/Network/Interface 对象::
* Network 作为 Address 列表::
* 比较运算: 比较运算<4>.
* 将IP地址与其他模块一起使用::
* 实例创建失败时获取更多详细信息::

创建 Address/Network/Interface 对象

* 关于IP版本的说明::
* IP主机地址::
* 定义网络::
* 主机接口::

Argument Clinic How-To

* The Goals Of Argument Clinic::
* Basic Concepts And Usage::
* Converting Your First Function::
* Advanced Topics::

Advanced Topics

* Symbolic default values::
* Renaming the C functions and variables generated by Argument Clinic::
* Converting functions using PyArg_UnpackTuple::
* Optional Groups::
* Using real Argument Clinic converters, instead of "legacy converters": Using real Argument Clinic converters instead of "legacy converters".
* Py_buffer::
* Advanced converters::
* Parameter default values::
* The NULL default value::
* Expressions specified as default values::
* Using a return converter::
* Cloning existing functions::
* Calling Python code::
* Using a "self converter"::
* Writing a custom converter::
* Writing a custom return converter::
* METH_O and METH_NOARGS::
* tp_new and tp_init functions::
* Changing and redirecting Clinic's output::
* The #ifdef trick::
* Using Argument Clinic in Python files::

使用 DTrace 和 SystemTap 检测CPython

* 启用静态标记::
* 静态DTrace探针::
* 静态SystemTap标记::
* 可用的静态标记::
* SystemTap Tapsets::
* 例子: 例子<36>.

Python 常见问题

* Python常见问题::
* 编程常见问题::
* 设计和历史常见问题::
* 代码库和插件 FAQ::
* 扩展/嵌入常见问题::
* Python在Windows上的常见问题::
* 图形用户界面（GUI）常见问题::
* “为什么我的电脑上安装了 Python ？”::

Python常见问题

* 一般信息::
* 现实世界中的 Python::

一般信息

* 什么是 Python？::
* 什么是 Python 软件基金会？::
* 使用 Python 是否存在版权限制？::
* 创造 Python 的最初理由是什么？::
* Python 适合做什么？::
* Python 版本的编号形式是怎样的？::
* 我应如何获取一份 Python 源代码的副本？::
* 我应如何获取 Python 的文档？::
* 我之前从未接触过编程。 哪里有 Python 的教程？::
* 是否有专门针对 Python 的新闻组或邮件列表？::
* 我应如何获取 Python 的公开测试版本？::
* 我应如何为 Python 提交错误报告和补丁？::
* 是否有任何公开发表的 Python 相关文章可以供我参考引用？::
* 是否有任何 Python 相关的书籍？::
* www.python.org 具体位于世界上的哪个地点？: www python org 具体位于世界上的哪个地点？.
* 为何命名为 Python？::
* 我必须喜欢 "Monty Python 的飞行马戏团" 吗？::

现实世界中的 Python

* Python 有多稳定？::
* 有多少人在使用 Python？::
* 有哪些重要的项目是用 Python 开发的？::
* 在未来可以期待 Python 将有什么新进展？::
* 提议对 Python 加入不兼容的更改是否合理？::
* Python 是一种对编程初学者友好的语言吗？::

编程常见问题

* 一般问题::
* 核心语言::
* 数字和字符串::
* 性能: 性能<4>.
* 序列（元组/列表）::
* 对象::
* 模块: 模块<3>.

一般问题

* Python 有没有提供断点与单步调试等功能的，源码层次的调试器？::
* 是否有能帮助寻找漏洞或执行静态分析的工具？::
* 我如何能够通过一个 Python 脚本创建一个独立运行的二进制文件？::
* 是否有 Python 程序规范代码标准或风格指南？::

核心语言

* 当变量有值时，为什么会出现UnboundLocalError？::
* Python中的局部变量和全局变量有哪些规则？::
* 为什么在具有不同值的循环中定义的lambdas都返回相同的结果？::
* 如何跨模块共享全局变量？::
* 导入模块的“最佳实践”是什么？::
* 为什么对象之间会共享默认值？::
* 如何将可选参数或关键字参数从一个函数传递到另一个函数？::
* 形参和实参之间有什么区别？::
* 为什么更改列表 'y' 也会更改列表 'x'？::
* 如何编写带输出参数的函数（通过引用调用）？::
* 如何在Python中创建高阶函数？::
* 如何在Python中复制对象？::
* 如何找到对象的方法或属性？::
* 我的代码如何才能发现对象的名称？::
* 逗号运算符的优先级是什么？::
* 是否有与 C 的 "?;" 三目运算符等价的东西？: 是否有与 C 的 "? " 三目运算符等价的东西？.
* 是否可以用Python编写混淆的单行程序?::
* 函数参数列表中的斜杠（/）是什么意思？::

数字和字符串

* 如何指定十六进制和八进制整数？::
* 为什么-22 // 10返回-3？::
* 如何将字符串转换为数字？::
* 如何将数字转换为字符串？::
* 如何修改字符串？::
* 如何使用字符串调用函数/方法？::
* 是否有与Perl 的chomp() 等效的方法，用于从字符串中删除尾随换行符？: 是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？.
* 是否有 scanf() 或 sscanf() 的对应物？: 是否有 scanf 或 sscanf 的对应物？.
* 'UnicodeDecodeError' 或 'UnicodeEncodeError' 错误是什么意思？::

性能

* 我的程序太慢了。该如何加快速度？::
* 将多个字符串连接在一起的最有效方法是什么？::

序列（元组/列表）

* 如何在元组和列表之间进行转换？::
* 什么是负数序号？::
* 如何以相反的顺序迭代序列？::
* 如何从列表中删除重复项？::
* 如何从列表中删除多个项？::
* 如何在Python中创建数组？::
* 如何创建多维列表？::
* 如何将方法应用于一系列对象？::
* 为什么 a_tuple[i] += ['item'] 会在执行加法时引发异常？::
* 我想做一个复杂的排序：你能用Python做一个Schwartzian变换吗？::
* 如何按其他列表中的值对一个列表进行排序？::

对象

* 什么是类？::
* 什么是方法？::
* 什么是 self ？::
* 如何检查对象是否为给定类或其子类的一个实例？::
* 什么是委托？::
* 如何从覆盖基类的派生类调用基类中定义的方法?::
* 如何组织代码以便更改基类？::
* 如何创建静态类数据和静态类方法？::
* 如何在Python中重载构造函数（或方法）？::
* 我尝试使用 __spam ，但是得到一个关于 _SomeClassName__spam 的错误信息。::
* 类定义了 __del__ 方法，但是删除对象时没有调用它。::
* 如何获取给定类的所有实例的列表？::
* 为什么 id() 的结果看起来不是唯一的？: 为什么 id 的结果看起来不是唯一的？.

模块

* 如何创建 .pyc 文件？: 如何创建 pyc 文件？.
* 如何找到当前模块名称？::
* 如何让模块相互导入？::
* __import__(’x.y.z’) 返回 <module ’x’>; 如何获取z?: __import__ 'x y z' 返回 <module 'x'>; 如何获取z?.
* 当我编辑了导入过的模块并重新导入它时，这些变化没有显示出来。为什么会这样？::

设计和历史常见问题

* 为什么Python使用缩进来分组语句？::
* 为什么简单的算术运算得到奇怪的结果？::
* 为什么浮点计算不准确？::
* 为什么Python字符串是不可变的？::
* 为什么必须在方法定义和调用中显式使用“self”？::
* 为什么不能在表达式中赋值？::
* 为什么Python对某些功能（例如list.index()）使用方法来实现，而其他功能（例如len(List)）使用函数实现？: 为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？.
* 为什么 join()是一个字符串方法而不是列表或元组方法？: 为什么 join 是一个字符串方法而不是列表或元组方法？.
* 异常有多快？::
* 为什么Python中没有switch或case语句？::
* 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？::
* 为什么lambda表达式不能包含语句？::
* 可以将Python编译为机器代码，C或其他语言吗？::
* Python如何管理内存？::
* 为什么CPython不使用更传统的垃圾回收方案？::
* CPython退出时为什么不释放所有内存？::
* 为什么有单独的元组和列表数据类型？::
* 列表是如何在CPython中实现的？::
* 字典是如何在CPython中实现的？::
* 为什么字典key必须是不可变的？::
* 为什么 list.sort() 没有返回排序列表？: 为什么 list sort 没有返回排序列表？.
* 如何在Python中指定和实施接口规范？::
* 为什么没有goto？::
* 为什么原始字符串（r-strings）不能以反斜杠结尾？::
* 为什么Python没有属性赋值的“with”语句？::
* 为什么 if/while/def/class语句需要冒号？::
* 为什么Python在列表和元组的末尾允许使用逗号？::

代码库和插件 FAQ

* 通用的代码库问题::
* 通用任务::
* 线程相关::
* 输入输出: 输入输出<2>.
* 网络 / Internet 编程::
* 数据库::
* 数学和数字::

通用的代码库问题

* 如何找到可以用来做 XXX 的模块或应用？::
* math.py（socket.py，regex.py 等）的源文件在哪？: math py（socket py，regex py 等）的源文件在哪？.
* 在 Unix 中怎样让 Python 脚本可执行？::
* Python 中有 curses/termcap 包吗？::
* Python 中存在类似 C 的 onexit() 函数的东西吗？: Python 中存在类似 C 的 onexit 函数的东西吗？.
* 为什么我的信号处理函数不能工作？::

通用任务

* 怎样测试 Python 程序或组件？::
* 怎样用 docstring 创建文档？::
* 怎样一次只获取一个按键？::

线程相关

* 程序中怎样使用线程？::
* 我的线程都没有运行，为什么？::
* 如何将任务分配给多个工作线程？::
* 怎样修改全局变量是线程安全的？::
* 不能删除全局解释器锁吗？::

输入输出

* 怎样删除文件？（以及其他文件相关的问题……）::
* 怎样复制文件？::
* 怎样读取（或写入）二进制数据？::
* 似乎 os.popen() 创建的管道不能使用 os.read()，这是为什么？: 似乎 os popen 创建的管道不能使用 os read ，这是为什么？.
* 怎样访问（RS232）串口？::
* 为什么关闭 sys.stdout（stdin，stderr）并不会真正关掉它？: 为什么关闭 sys stdout（stdin，stderr）并不会真正关掉它？.

网络 / Internet 编程

* Python 中的 WWW 工具是什么？::
* 怎样模拟发送 CGI 表单（METHOD=POST）？::
* 生成 HTML 需要使用什么模块？::
* 怎样使用 Python 脚本发送邮件？::
* socket 的 connect() 方法怎样避免阻塞？: socket 的 connect 方法怎样避免阻塞？.

数据库

* Python 中有数据库包的接口吗？::
* 在 Python 中如何实现持久化对象？::

数学和数字

* Python 中怎样生成随机数？::

扩展/嵌入常见问题

* 可以使用 C 语言创建自己的函数吗？::
* 可以使用 C++ 语言创建自己的函数吗？::
* C很难写，有没有其他选择？::
* 如何在 C 中执行任意 Python 语句？::
* 如何在 C 中对任意 Python 表达式求值？::
* 如何从Python对象中提取C的值？::
* 如何使用Py_BuildValue()创建任意长度的元组？: 如何使用Py_BuildValue 创建任意长度的元组？.
* 如何从C调用对象的方法？::
* 如何捕获PyErr_Print()（或打印到stdout / stderr的任何内容）的输出？: 如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？.
* 如何从C访问用Python编写的模块？::
* 如何在 Python 中对接 C ++ 对象？::
* 我使用Setup文件添加了一个模块，为什么make失败了？::
* 如何调试扩展？::
* 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?::
* 如何区分“输入不完整”和“输入无效”？::
* 如何找到未定义的g++符号__builtin_new或__pure_virtual？::
* 能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？::

Python在Windows上的常见问题

* 我怎样在Windows下运行一个Python程序？::
* 我怎么让 Python 脚本可执行？::
* 为什么有时候 Python 程序会启动缓慢？::
* 我怎样使用 Python 脚本制作可执行文件？::
* *.pyd 文件和 DLL 文件相同吗？: * pyd 文件和 DLL 文件相同吗？.
* 我怎样将 Python 嵌入一个 Windows 程序？::
* 如何让编辑器不要在我的 Python 源代码中插入 tab ？::
* 如何在不阻塞的情况下检查按键？::

图形用户界面（GUI）常见问题

* 图形界面常见问题::
* Python 是否有平台无关的图形界面工具包？::
* 有哪些Python的GUI工具是某个平台专用的？::
* 有关Tkinter的问题::

Python 是否有平台无关的图形界面工具包？

* Tkinter::
* wxWidgets::
* Qt::
* Gtk+::
* Kivy::
* FLTK::
* OpenGL::

有关Tkinter的问题

* 我怎样“冻结”Tkinter程序？::
* 在等待 I/O 操作时能够处理 Tk 事件吗？::
* 在Tkinter中键绑定不工作：为什么？::

“为什么我的电脑上安装了 Python ？”

* 什么是 Python？: 什么是 Python？<2>.
* 为什么我的电脑上安装了 Python ？::
* 我能删除 Python 吗？::

文档说明

* Python 文档的贡献者::

处理错误

* 文档 Bug::
* 使用 Python 的问题追踪系统::
* 开始为 Python 贡献您的知识::

历史和许可证

* 该软件的历史::
* 获取或以其他方式使用 Python 的条款和条件::
* 收录软件的许可与鸣谢::

获取或以其他方式使用 Python 的条款和条件

* 用于 PYTHON 3.8.12 的 PSF 许可协议: 用于 PYTHON 3 8 12 的 PSF 许可协议.
* 用于 PYTHON 2.0 的 BEOPEN.COM 许可协议: 用于 PYTHON 2 0 的 BEOPEN COM 许可协议.
* 用于 PYTHON 1.6.1 的 CNRI 许可协议: 用于 PYTHON 1 6 1 的 CNRI 许可协议.
* 用于 PYTHON 0.9.0 至 1.2 的 CWI 许可协议: 用于 PYTHON 0 9 0 至 1 2 的 CWI 许可协议.
* ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3.8.12 DOCUMENTATION: ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3 8 12 DOCUMENTATION.

收录软件的许可与鸣谢

* Mersenne Twister::
* 套接字: 套接字<2>.
* 异步套接字服务::
* Cookie 管理::
* 执行追踪::
* UUencode 与 UUdecode 函数::
* XML 远程过程调用::
* test_epoll::
* Select kqueue::
* SipHash24::
* strtod 和 dtoa::
* OpenSSL::
* expat::
* libffi::
* zlib: zlib<3>.
* cfuhash::
* libmpdec::
* W3C C14N 测试套件::

分发 Python 模块（遗留版本）

* Distutils 模块介绍::
* 编写安装脚本::
* 编写设置脚本的配置文件::
* Creating a Source Distribution::
* 创建构建分布::
* Distutils 示例::
* 扩展 Distutils::
* 命令参考::
* API参考引用::

Distutils 模块介绍

* 概念和术语::
* 一个简单的例子: 一个简单的例子<3>.
* 通用的 Python 术语::
* Distutils 特定的术语::

编写安装脚本

* Listing whole packages::
* Listing individual modules::
* Describing extension modules::
* Relationships between Distributions and Packages::
* Installing Scripts::
* Installing Package Data::
* Installing Additional Files::
* Additional meta-data::
* Debugging the setup script::

Describing extension modules

* 扩展名和软件包::
* Extension source files::
* Preprocessor options::
* Library options::
* 其他选项: 其他选项<2>.

Creating a Source Distribution

* Specifying the files to distribute::
* Manifest-related options::

创建构建分布

* 创建RPM软件包::
* Creating Windows Installers::
* Cross-compiling on Windows::
* Vista User Access Control (UAC): Vista User Access Control UAC.

Cross-compiling on Windows

* The Postinstallation script::

Distutils 示例

* 纯 Python 分发（通过 module）::
* 纯 Python 分发（通过 包）::
* 单个扩展模块::
* 检查一个包::
* 读取元数据::

扩展 Distutils

* 集成新的命令::
* 添加新的发布类型::

命令参考

* 安装模块; install 命令族: 安装模块 install 命令族.
* 创建源码发行包; sdist 命令: 创建源码发行包 sdist 命令.

安装模块: install 命令族

* install_data::
* install_scripts::

API参考引用

* distutils.core: distutils core --- 分发包功能的核心. 分发包功能的核心
* distutils.ccompiler: distutils ccompiler --- CCompiler基类. CCompiler基类
* distutils.unixccompiler: distutils unixccompiler --- Unix C Compiler. Unix C Compiler
* distutils.msvccompiler: distutils msvccompiler --- Microsoft Compiler. Microsoft Compiler
* distutils.bcppcompiler: distutils bcppcompiler --- Borland Compiler. Borland Compiler
* distutils.cygwincompiler: distutils cygwincompiler --- Cygwin Compiler. Cygwin Compiler
* distutils.archive_util: distutils archive_util --- Archiving utilities. Archiving utilities
* distutils.dep_util: distutils dep_util --- Dependency checking. Dependency checking
* distutils.dir_util: distutils dir_util --- Directory tree operations. Directory tree operations
* distutils.file_util: distutils file_util --- Single file operations. Single file operations
* distutils.util: distutils util --- Miscellaneous other utility functions. Miscellaneous other utility functions
* distutils.dist: distutils dist --- The Distribution class. The Distribution class
* distutils.extension: distutils extension --- The Extension class. The Extension class
* distutils.debug: distutils debug --- Distutils debug mode. Distutils debug mode
* distutils.errors: distutils errors --- Distutils exceptions. Distutils exceptions
* distutils.fancy_getopt: distutils fancy_getopt --- Wrapper around the standard getopt module. Wrapper around the standard getopt module
* distutils.filelist: distutils filelist --- The FileList class. The FileList class
* distutils.log: distutils log --- Simple PEP 282-style logging. Simple PEP 282-style logging
* distutils.spawn: distutils spawn --- Spawn a sub-process. Spawn a sub-process
* distutils.sysconfig: distutils sysconfig --- System configuration information. System configuration information
* distutils.text_file: distutils text_file --- The TextFile class. The TextFile class
* distutils.version: distutils version --- Version number classes. Version number classes
* distutils.cmd: distutils cmd --- Abstract base class for Distutils commands. Abstract base class for Distutils commands
* Creating a new Distutils command::
* distutils.command: distutils command --- Individual Distutils commands. Individual Distutils commands
* distutils.command.bdist: distutils command bdist --- Build a binary installer. Build a binary installer
* distutils.command.bdist_packager: distutils command bdist_packager --- Abstract base class for packagers. Abstract base class for packagers
* distutils.command.bdist_dumb: distutils command bdist_dumb --- Build a "dumb" installer. Build a "dumb" installer
* distutils.command.bdist_msi: distutils command bdist_msi --- Build a Microsoft Installer binary package. Build a Microsoft Installer binary package
* distutils.command.bdist_rpm: distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM. Build a binary distribution as a Redhat RPM and
                               SRPM
* distutils.command.bdist_wininst: distutils command bdist_wininst --- Build a Windows installer. Build a Windows installer
* distutils.command.sdist: distutils command sdist --- Build a source distribution. Build a source distribution
* distutils.command.build: distutils command build --- Build all files of a package. Build all files of a package
* distutils.command.build_clib: distutils command build_clib --- Build any C libraries in a package. Build any C libraries in a package
* distutils.command.build_ext: distutils command build_ext --- Build any extensions in a package. Build any extensions in a package
* distutils.command.build_py: distutils command build_py --- Build the py/ pyc files of a package. Build the .py/.pyc files of a package
* distutils.command.build_scripts: distutils command build_scripts --- Build the scripts of a package. Build the scripts of a package
* distutils.command.clean: distutils command clean --- Clean a package build area. Clean a package build area
* distutils.command.config: distutils command config --- Perform package configuration. Perform package configuration
* distutils.command.install: distutils command install --- Install a package. Install a package
* distutils.command.install_data: distutils command install_data --- Install data files from a package. Install data files from a package
* distutils.command.install_headers: distutils command install_headers --- Install C/C++ header files from a package. Install C/C++ header files from a package
* distutils.command.install_lib: distutils command install_lib --- Install library files from a package. Install library files from a package
* distutils.command.install_scripts: distutils command install_scripts --- Install script files from a package. Install script files from a package
* distutils.command.register: distutils command register --- Register a module with the Python Package Index. Register a module with the Python Package Index
* distutils.command.check: distutils command check --- Check the meta-data of a package. Check the meta-data of a package

安装Python模块（旧版）

* 概述: 概述<20>.
* Standard Build and Install::
* Alternate Installation::
* 自定义安装::
* Distutils Configuration Files::
* Building Extensions; Tips and Tricks: Building Extensions Tips and Tricks.

概述

* 基于分布式系统的源代码分发::

Standard Build and Install

* Platform variations::
* Splitting the job up::
* How building works::
* How installation works::

Alternate Installation

* Alternate installation; the user scheme: Alternate installation the user scheme.
* Alternate installation; the home scheme: Alternate installation the home scheme.
* Alternate installation; Unix (the prefix scheme): Alternate installation Unix the prefix scheme.
* Alternate installation; Windows (the prefix scheme): Alternate installation Windows the prefix scheme.

自定义安装

* Modifying Python's Search Path::

Distutils Configuration Files

* Location and names of config files::
* Syntax of config files::

Building Extensions: Tips and Tricks

* Tweaking compiler/linker flags::
* Using non-Microsoft compilers on Windows::

Using non-Microsoft compilers on Windows

* Borland/CodeGear C++::
* GNU C / Cygwin / MinGW::

GNU C / Cygwin / MinGW

* Older Versions of Python and MinGW::



File: python.info,  Node: Python的新变化,  Next: Python 教程,  Prev: Top,  Up: Top

1 Python的新变化
****************

这个“Python 有什么新变化？”系列内容会带您浏览 Python 大版本之间重要的变
化。在新版发布后，如果您希望掌握最新变化，请务必阅读这些内容。

* Menu:

* Python 3.8 有什么新变化: Python 3 8 有什么新变化.
* Python 3.7 有什么新变化: Python 3 7 有什么新变化.
* Python 3.6 有什么新变化: Python 3 6 有什么新变化.
* Python 3.5 有什么新变化: Python 3 5 有什么新变化.
* Python 3.4 有什么新变化: Python 3 4 有什么新变化.
* Python 3.3 有什么新变化: Python 3 3 有什么新变化.
* Python 3.2 有什么新变化: Python 3 2 有什么新变化.
* Python 3.1 有什么新变化: Python 3 1 有什么新变化.
* Python 3.0 有什么新变化: Python 3 0 有什么新变化.
* Python 2.7 有什么新变化: Python 2 7 有什么新变化.
* Python 2.6 有什么新变化: Python 2 6 有什么新变化.
* Python 2.5 有什么新变化: Python 2 5 有什么新变化.
* Python 2.4 有什么新变化: Python 2 4 有什么新变化.
* Python 2.3 有什么新变化: Python 2 3 有什么新变化.
* Python 2.2 有什么新变化: Python 2 2 有什么新变化.
* Python 2.1 有什么新变化: Python 2 1 有什么新变化.
* Python 2.0 有什么新变化: Python 2 0 有什么新变化.
* 更新日志::


File: python.info,  Node: Python 3 8 有什么新变化,  Next: Python 3 7 有什么新变化,  Up: Python的新变化

1.1 Python 3.8 有什么新变化
===========================


编者: Raymond Hettinger

本文解释了 Python 3.8 相比 3.7 的新增特性。 完整的详情可参阅 *note
更新日志: 14d.。

Python 3.8已于2019年10月14日发布。

* Menu:

* 摘要 - 发布重点::
* 新的特性::
* 其他语言特性修改::
* 新增模块::
* 改进的模块::
* 性能优化::
* 构建和 C API 的改变::
* 弃用::
* API 与特性的移除::
* 移植到 Python 3.8: 移植到 Python 3 8.
* Python 3.8.1 中的重要变化: Python 3 8 1 中的重要变化.
* Python 3.8.2 中的重要变化: Python 3 8 2 中的重要变化.
* Python 3.8.3 中的重要变化: Python 3 8 3 中的重要变化.
* Python 3.8.8 中的重要变化: Python 3 8 8 中的重要变化.
* Python 3.8.9 中的重要变化: Python 3 8 9 中的重要变化.
* Python 3.8.10 中的重要变化: Python 3 8 10 中的重要变化.
* Python 3.8.10 中的重要变化: Python 3 8 10 中的重要变化<2>.
* Python 3.8.12 中的重要变化: Python 3 8 12 中的重要变化.


File: python.info,  Node: 摘要 - 发布重点,  Next: 新的特性,  Up: Python 3 8 有什么新变化

1.1.1 摘要 - 发布重点
---------------------


File: python.info,  Node: 新的特性,  Next: 其他语言特性修改,  Prev: 摘要 - 发布重点,  Up: Python 3 8 有什么新变化

1.1.2 新的特性
--------------

* Menu:

* 赋值表达式::
* 仅限位置形参::
* 用于已编译字节码文件的并行文件系统缓存::
* 调试构建使用与发布构建相同的 ABI::
* f-字符串支持 = 用于自动记录表达式和调试文档::
* PEP 578; Python 运行时审核钩子: PEP 578 Python 运行时审核钩子.
* PEP 587; Python 初始化配置: PEP 587 Python 初始化配置.
* Vectorcall; 用于 CPython 的快速调用协议: Vectorcall 用于 CPython 的快速调用协议.
* 具有外部数据缓冲区的 pickle 协议 5::


File: python.info,  Node: 赋值表达式,  Next: 仅限位置形参,  Up: 新的特性

1.1.2.1 赋值表达式
..................

新增的语法 ‘:=’ 可在表达式内部为变量赋值。 它被昵称为“海象运算符”因为它
很像是 海象的眼睛和长牙(1)。

在这个示例中，赋值表达式可以避免调用 *note len(): 151. 两次:

     if (n := len(a)) > 10:
         print(f"List is too long ({n} elements, expected <= 10)")

类似的益处还可出现在正则表达式匹配中需要使用两次匹配对象的情况中，一次检
测用于匹配是否发生，另一次用于提取子分组:

     discount = 0.0
     if (mo := re.search(r'(\d+)% discount', advertisement)):
         discount = float(mo.group(1)) / 100.0

此运算符也适用于配合 while 循环计算一个值来检测循环是否终止，而同一个值
又在循环体中再次被使用的情况:

     # Loop over fixed length blocks
     while (block := f.read(256)) != '':
         process(block)

另一个值得介绍的用例出现于列表推导式中，在筛选条件中计算一个值，而同一个
值又在表达式中需要被使用:

     [clean_name.title() for name in names
      if (clean_name := normalize('NFC', name)) in allowed_names]

请尽量将海象运算符的使用限制在清晰的场合中，以降低复杂性并提升可读性。

请参阅 PEP 572(2) 了解详情。

（由 Morehouse 在 bpo-35224(3) 中贡献。）

   ---------- Footnotes ----------

   (1) 
https://en.wikipedia.org/wiki/Walrus#/media/File:Pacific_Walrus_-_Bull_(8247646168).jpg

   (2) https://www.python.org/dev/peps/pep-0572

   (3) https://bugs.python.org/issue35224


File: python.info,  Node: 仅限位置形参,  Next: 用于已编译字节码文件的并行文件系统缓存,  Prev: 赋值表达式,  Up: 新的特性

1.1.2.2 仅限位置形参
....................

新增了一个函数形参语法 ‘/’ 用来指明某些函数形参必须使用仅限位置而非关键
字参数的形式。 这种标记语法与通过 ‘help()’ 所显示的使用 Larry Hastings 的
Argument Clinic(1) 工具标记的 C 函数相同。

在下面的例子中，形参 `a' 和 `b' 为仅限位置形参，`c' 或 `d' 可以是位置形
参或关键字形参，而 `e' 或 `f' 要求为关键字形参:

     def f(a, b, /, c, d, *, e, f):
         print(a, b, c, d, e, f)

以下均为合法的调用:

     f(10, 20, 30, d=40, e=50, f=60)

但是，以下均为不合法的调用:

     f(10, b=20, c=30, d=40, e=50, f=60)   # b cannot be a keyword argument
     f(10, 20, 30, 40, 50, f=60)           # e must be a keyword argument

这种标记形式的一个用例是它允许纯 Python 函数完整模拟现有的用 C 代码编写
的函数的行为。 例如，内置的 *note divmod(): 153. 函数不接受关键字参数:

     def divmod(a, b, /):
         "Emulate the built in divmod() function"
         return (a // b, a % b)

另一个用例是在不需要形参名称时排除关键字参数。 例如，内置的 *note len():
151. 函数的签名为 ‘len(obj, /)’。 这可以排除如下这种笨拙的调用形式:

     len(obj='hello')  # The "obj" keyword argument impairs readability

另一个益处是将形参标记为仅限位置形参将允许在未来修改形参名而不会破坏客户
的代码。 例如，在 *note statistics: f6. 模块中，形参名 `dist' 在未来可能
被修改。 这使得以下函数描述成为可能:

     def quantiles(dist, /, *, n=4, method='exclusive')
         ...

由于在 ‘/’ 左侧的形参不会被公开为可用关键字，其他形参名仍可在 ‘**kwargs’
中使用:

     >>> def f(a, b, /, **kwargs):
     ...     print(a, b, kwargs)
     ...
     >>> f(10, 20, a=1, b=2, c=3)         # a and b are used in two ways
     10 20 {'a': 1, 'b': 2, 'c': 3}

这极大地简化了需要接受任意关键字参数的函数和方法的实现。 例如，以下是一
段摘自 *note collections: 1e. 模块的代码:

     class Counter(dict):

         def __init__(self, iterable=None, /, **kwds):
             # Note "iterable" is a possible keyword argument

请参阅 PEP 570(2) 了解详情。

（由 Pablo Galindo 在 bpo-36540(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://docs.python.org/3/howto/clinic.html

   (2) https://www.python.org/dev/peps/pep-0570

   (3) https://bugs.python.org/issue36540


File: python.info,  Node: 用于已编译字节码文件的并行文件系统缓存,  Next: 调试构建使用与发布构建相同的 ABI,  Prev: 仅限位置形参,  Up: 新的特性

1.1.2.3 用于已编译字节码文件的并行文件系统缓存
..............................................

新增的 *note PYTHONPYCACHEPREFIX: 155. 设置 (也可使用 *note -X: 156.
‘pycache_prefix’) 可将隐式的字节码缓存配置为使用单独的并行文件系统树，而
不是默认的每个源代码目录下的 ‘__pycache__’ 子目录。

缓存的位置会在 *note sys.pycache_prefix: 157. 中报告 (*note None: 158. 表
示默认位置即 ‘__pycache__’ 子目录)。

（由 Carl Meyer 在 bpo-33499(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33499


File: python.info,  Node: 调试构建使用与发布构建相同的 ABI,  Next: f-字符串支持 = 用于自动记录表达式和调试文档,  Prev: 用于已编译字节码文件的并行文件系统缓存,  Up: 新的特性

1.1.2.4 调试构建使用与发布构建相同的 ABI
........................................

Python 现在不论是以发布模式还是调试模式进行构建都将使用相同的 ABI。 在
Unix 上，当 Python 以调试模式构建时，现在将可以加载以发布模式构建的 C 扩
展和使用稳定版 ABI 构建的 C 扩展。

发布构建和调试构建现在都是 ABI 兼容的：定义 ‘Py_DEBUG’ 宏不会再启用
‘Py_TRACE_REFS’ 宏，它引入了唯一的 ABI 不兼容性。 ‘Py_TRACE_REFS’ 宏添加
了 ‘sys.getobjects()’ 函数和 *note PYTHONDUMPREFS: 15a. 环境变量，它可以
使用新的 ‘./configure --with-trace-refs’ 构建选项来设置。 （由 Victor
Stinner 在 bpo-36465(1) 中贡献。）

在 Unix 上，C 扩展不会再被链接到 libpython，但 Android 和 Cygwin 例外。
现在静态链接的 Python 将可以加载使用共享库 Python 构建的 C 扩展。 （由
Victor Stinner 在 bpo-21536(2) 中贡献。）

在 Unix 上，当 Python 以调试模式构建时，导入操作现在也会查找在发布模式下
编译的 C 扩展以及使用稳定版 ABI 编译的 C 扩展。 （由 Victor Stinner 在
bpo-36722(3) 中贡献。）

要将 Python 嵌入到一个应用中，必须将新增的 ‘--embed’ 选项传给
‘python3-config --libs --embed’ 以获得 ‘-lpython3.8’ (将应用链接到
libpython)。 要同时支持 3.8 和旧版本，请先尝试 ‘python3-config --libs
--embed’ 并在此命令失败时回退到 ‘python3-config --libs’ (即不带
‘--embed’)。

增加一个 pkg-config ‘python-3.8-embed’ 模块用来将 Python 嵌入到一个应用
中: ‘pkg-config python-3.8-embed --libs’ 包含 ‘-lpython3.8’。 要同时支持
3.8 和旧版本，请先尝试 ‘pkg-config python-X.Y-embed --libs’ 并在此命令失
败时回退到 ‘pkg-config python-X.Y --libs’ (即不带 ‘--embed’) （请将
‘X.Y’ 替换为 Python 版本号）。

另一方面，‘pkg-config python3.8 --libs’ 不再包含 ‘-lpython3.8’。 C 扩展
不可被链接到 libpython (但 Android 和 Cygwin 例外，这两者的情况由脚本处
理)；此改变是故意被设为向下不兼容的。 （由 Victor Stinner 在
bpo-36721(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36465

   (2) https://bugs.python.org/issue21536

   (3) https://bugs.python.org/issue36722

   (4) https://bugs.python.org/issue36721


File: python.info,  Node: f-字符串支持 = 用于自动记录表达式和调试文档,  Next: PEP 578 Python 运行时审核钩子,  Prev: 调试构建使用与发布构建相同的 ABI,  Up: 新的特性

1.1.2.5 f-字符串支持 ‘=’ 用于自动记录表达式和调试文档
.....................................................

增加 ‘=’ 说明符用于 *note f-string: 15c.。 形式为 ‘f'{expr=}'’ 的 f-字符
串将扩展表示为表达式文本，加一个等于号，再加表达式的求值结果。 例如：

     >>> user = 'eric_idle'
     >>> member_since = date(1975, 7, 31)
     >>> f'{user=} {member_since=}'
     "user='eric_idle' member_since=datetime.date(1975, 7, 31)"

通常的 *note f-字符串格式说明符: 15d. 允许更细致地控制所要显示的表达式结
果:

     >>> delta = date.today() - member_since
     >>> f'{user=!s}  {delta.days=:,d}'
     'user=eric_idle  delta.days=16,075'

‘=’ 说明符将输出整个表达式，以便详细演示计算过程:

     >>> print(f'{theta=}  {cos(radians(theta))=:.3f}')
     theta=30  cos(radians(theta))=0.866

（由 Eric V. Smith 和 Larry Hastings 在 bpo-36817(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36817


File: python.info,  Node: PEP 578 Python 运行时审核钩子,  Next: PEP 587 Python 初始化配置,  Prev: f-字符串支持 = 用于自动记录表达式和调试文档,  Up: 新的特性

1.1.2.6 PEP 578: Python 运行时审核钩子
......................................

此 PEP 添加了审核钩子和已验证开放钩子。 两者在 Python 与本机代码中均可用
。允许以纯 Python 代码编写的应用和框架利用额外的通知，同时允许嵌入开发人
员或系统管理员部署始终启用审核的 Python 版本。

请参阅 PEP 578(1) 了解详情。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0578


File: python.info,  Node: PEP 587 Python 初始化配置,  Next: Vectorcall 用于 CPython 的快速调用协议,  Prev: PEP 578 Python 运行时审核钩子,  Up: 新的特性

1.1.2.7 PEP 587: Python 初始化配置
..................................

PEP 587(1) 增加了一个新的 C API 用来配置 Python 初始化，提供对整个配置过
程的更细致控制以及更好的错误报告。

新的结构：

   * *note PyConfig: 160.

   * *note PyPreConfig: 161.

   * *note PyStatus: 162.

   * *note PyWideStringList: 163.

新的函数：

   * *note PyConfig_Clear(): 164.

   * *note PyConfig_InitIsolatedConfig(): 165.

   * *note PyConfig_InitPythonConfig(): 166.

   * *note PyConfig_Read(): 167.

   * *note PyConfig_SetArgv(): 168.

   * *note PyConfig_SetBytesArgv(): 169.

   * *note PyConfig_SetBytesString(): 16a.

   * *note PyConfig_SetString(): 16b.

   * *note PyPreConfig_InitIsolatedConfig(): 16c.

   * *note PyPreConfig_InitPythonConfig(): 16d.

   * *note PyStatus_Error(): 16e.

   * *note PyStatus_Exception(): 16f.

   * *note PyStatus_Exit(): 170.

   * *note PyStatus_IsError(): 171.

   * *note PyStatus_IsExit(): 172.

   * *note PyStatus_NoMemory(): 173.

   * *note PyStatus_Ok(): 174.

   * *note PyWideStringList_Append(): 175.

   * *note PyWideStringList_Insert(): 176.

   * *note Py_BytesMain(): 177.

   * *note Py_ExitStatusException(): 178.

   * *note Py_InitializeFromConfig(): 179.

   * *note Py_PreInitialize(): 17a.

   * *note Py_PreInitializeFromArgs(): 17b.

   * *note Py_PreInitializeFromBytesArgs(): 17c.

   * *note Py_RunMain(): 17d.

此 PEP 还为这些内部结构添加了 ‘_PyRuntimeState.preconfig’ (*note
PyPreConfig: 161. 类型) 和 ‘PyInterpreterState.config’ (*note PyConfig:
160. 类型) 字段。 ‘PyInterpreterState.config’ 成为新的引用配置，替代全局
配置变量和其他私有变量。

请参阅 *note Python 初始化配置: 17e. 获取详细文档。

请参阅 PEP 587(2) 了解详情。

（由 Victor Stinner 在 bpo-36763(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0587

   (2) https://www.python.org/dev/peps/pep-0587

   (3) https://bugs.python.org/issue36763


File: python.info,  Node: Vectorcall 用于 CPython 的快速调用协议,  Next: 具有外部数据缓冲区的 pickle 协议 5,  Prev: PEP 587 Python 初始化配置,  Up: 新的特性

1.1.2.8 Vectorcall: 用于 CPython 的快速调用协议
...............................................

添加 "vectorcall" 协议到 Python/C API。 它的目标是对已被应用于许多类的现
有优化进行正式化。 任何实现可调用对象的扩展类型均可使用此协议。

此特性目前为暂定状态，计划在 Python 3.9 将其完全公开。

请参阅 PEP 590(1) 了解详情。

（由 Jeroen Demeyer 和 Mark Shannon 在 bpo-36974(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0590

   (2) https://bugs.python.org/issue36974


File: python.info,  Node: 具有外部数据缓冲区的 pickle 协议 5,  Prev: Vectorcall 用于 CPython 的快速调用协议,  Up: 新的特性

1.1.2.9 具有外部数据缓冲区的 pickle 协议 5
..........................................

当使用 *note pickle: cb. 在 Python 进程间传输大量数据以充分发挥多核或多
机处理的优势时，非常重要一点是通过减少内存拷贝来优化传输效率，并可能应用
一些定制技巧例如针对特定数据的压缩。

*note pickle: cb. 协议 5 引入了对于外部缓冲区的支持，这样 PEP 3118(1) 兼
容的数据可以与主 pickle 流分开进行传输，这是由通信层来确定的。

请参阅 PEP 574(2) 了解详情。

（由 Antoine Pitrou 在 bpo-36785(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3118

   (2) https://www.python.org/dev/peps/pep-0574

   (3) https://bugs.python.org/issue36785


File: python.info,  Node: 其他语言特性修改,  Next: 新增模块,  Prev: 新的特性,  Up: Python 3 8 有什么新变化

1.1.3 其他语言特性修改
----------------------

   * 在之前版本中 *note continue: 182. 语句不允许在 *note finally: 183.
     子句中使用，这是因为具体实现存在一个问题。 在 Python 3.8 中此限制已
     被取消。 （由 Serhiy Storchaka 在 bpo-32489(1) 中贡献。）

   * *note bool: 184, *note int: 185. 和 *note fractions.Fraction: 186.
     类型现在都有一个 *note as_integer_ratio(): 187. 方法，与 *note
     float: 188. 和 *note decimal.Decimal: 189. 中的已有方法类似。 这个
     微小的 API 扩展使得 ‘numerator, denominator = x.as_integer_ratio()’
     这样的写法在多种数字类型上通用成为可能。 （由 Lisa Roach 在
     bpo-33073(2) 和 Raymond Hettinger 在 bpo-37819(3) 中贡献。）

   * *note int: 185, *note float: 188. 和 *note complex: 18a. 的构造器现
     在会使用 *note __index__(): 18b. 特殊方法，如果该方法可用而对应的方
     法 method *note __int__(): 18c, *note __float__(): 18d. 或 *note
     __complex__(): 18e. 方法不可用的话。 （由 Serhiy Storchaka 在
     bpo-20092(4) 中贡献。）

   * 添加 ‘\N{name}’ 转义符在 *note 正则表达式: de. 中的支持:

          >>> notice = 'Copyright © 2019'
          >>> copyright_year_pattern = re.compile(r'\N{copyright sign}\s*(\d{4})')
          >>> int(copyright_year_pattern.search(notice).group(1))
          2019

     （由 Jonathan Eunice 和 Serhiy Storchaka 在 bpo-30688(5) 中贡献。）

   * 现在 dict 和 dictview 可以使用 *note reversed(): 18f. 按插入顺序反
     向迭代。 （由 Rémi Lapeyre 在 bpo-33462(6) 中贡献。）

   * 在函数调用中允许使用的关键字名称语法受到进一步的限制。 特别地，
     ‘f((keyword)=arg)’ 不再被允许。 关键字参数赋值形式的左侧绝不允许一
     般标识符以外的其他内容。 （由 Benjamin Peterson 在 bpo-34641(7) 中
     贡献。）

   * 在 *note yield: 190. 和 *note return: 191. 语句中的一般可迭代对象解
     包不再要求加圆括号。 这使得 `yield' 和 `return' 的语法与正常的赋值
     语法更为一致:

          >>> def parse(family):
                  lastname, *members = family.split()
                  return lastname.upper(), *members

          >>> parse('simpsons homer marge bart lisa sally')
          ('SIMPSONS', 'homer', 'marge', 'bart', 'lisa', 'sally')

     （由 David Cuthbert 和 Jordan Chapman 在 bpo-32117(8) 中贡献。）

   * 当类似 ‘[(10, 20) (30, 40)]’ 这样在代码中少了一个逗号时，编译器将显
     示 *note SyntaxWarning: 192. 并附带更有帮助的提示。 这相比原来用
     *note TypeError: 193. 来提示第一个元组是不可调用的更容易被理解。 （
     由 Serhiy Storchaka 在 bpo-15248(9) 中贡献。）

   * *note datetime.date: 194. 或 *note datetime.datetime: 195. 和 *note
     datetime.timedelta: 196. 对象之间的算术运算现在将返回相应子类的实例
     而不是基类的实例。 这也会影响到在具体实现中（直接或间接地）使用了
     *note datetime.timedelta: 196. 算术运算的返回类型，例如 *note
     astimezone(): 197.。 （由 Paul Ganssle 在 bpo-32417(10) 中贡献。）

   * 当 Python 解释器通过 Ctrl-C (SIGINT) 被中断并且所产生的 *note
     KeyboardInterrupt: 198. 异常未被捕获，Python 进程现在会通过一个
     SIGINT 信号或是使得发起调用的进程能检测到它是由 Ctrl-C 操作杀死的正
     确退出代码来退出。 POSIX 和 Windows 上的终端会相应地使用此代码在交
     互式会话中终止脚本。 （由 Google 的 Gregory P. Smith 在
     bpo-1054041(11) 中贡献。）

   * 某些高级编程风格要求为现有的函数更新 *note types.CodeType: 199. 对
     象。 由于代码对象是不可变的，需要基于现有代码对象模型创建一个新的代
     码对象。 使用 19 个形参将会相当繁琐。 现在，新的 ‘replace()’ 方法使
     得通过少量修改的形参创建克隆对象成为可能。

     下面是一个修改 *note statistics.mean(): 19a. 函数来防止 `data' 形参
     被用作关键字参数的例子:

          >>> from statistics import mean
          >>> mean(data=[10, 20, 90])
          40
          >>> mean.__code__ = mean.__code__.replace(co_posonlyargcount=1)
          >>> mean(data=[10, 20, 90])
          Traceback (most recent call last):
            ...
          TypeError: mean() got some positional-only arguments passed as keyword arguments: 'data'

     （由 Victor Stinner 在 bpo-37032(12) 中贡献。）

   * 对于整数，现在 *note pow(): 19b. 函数的三参数形式在底数与模数不可约
     的情况下允许指数为负值。 随后它会在指数为 ‘-1’ 时计算底数的模乘逆元
     ，并对其他负指数计算反模的适当幂次。 例如，要计算 38 模 137 的 模乘
     逆元(13) 则可写为:

          >>> pow(38, -1, 137)
          119
          >>> 119 * 38 % 137
          1

     模乘逆元在求解 线性丢番图方程(14) 会被用到。 例如，想要求出 ‘4258𝑥
     + 147𝑦 = 369’ 的整数解，首先应重写为 ‘4258𝑥 ≡ 369 (mod 147)’ 然后求
     解：

          >>> x = 369 * pow(4258, -1, 147) % 147
          >>> y = (4258 * x - 369) // -147
          >>> 4258 * x + 147 * y
          369

     （由 Mark Dickinson 在 bpo-36027(15) 中贡献。）

   * 字典推导式已与字典字面值实现同步，会先计算键再计算值:

          >>> # Dict comprehension
          >>> cast = {input('role? '): input('actor? ') for i in range(2)}
          role? King Arthur
          actor? Chapman
          role? Black Knight
          actor? Cleese

          >>> # Dict literal
          >>> cast = {input('role? '): input('actor? ')}
          role? Sir Robin
          actor? Eric Idle

     对执行顺序的保证对赋值表达式来说很有用，因为在键表达式中赋值的变量
     将可在值表达式中被使用:

          >>> names = ['Martin von Löwis', 'Łukasz Langa', 'Walter Dörwald']
          >>> {(n := normalize('NFC', name)).casefold() : n for name in names}
          {'martin von löwis': 'Martin von Löwis',
           'łukasz langa': 'Łukasz Langa',
           'walter dörwald': 'Walter Dörwald'}

     （由 Jörn Heissler 在 bpo-35224(16) 中贡献。）

   * *note object.__reduce__(): 19c. 方法现在可返回长度为二至六个元素的
     元组。 之前的上限为五个。 新增的第六个可选元素是签名为 ‘(obj,
     state)’ 的可调用对象。 这样就允许直接控制特定对象的状态更新。 如果
     元素值不为 `None'，该可调用对象将优先于对象的 *note __setstate__():
     19d. 方法。 （由 Pierre Glaser 和 Olivier Grisel 在 bpo-35900(17) 中
     贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32489

   (2) https://bugs.python.org/issue33073

   (3) https://bugs.python.org/issue37819

   (4) https://bugs.python.org/issue20092

   (5) https://bugs.python.org/issue30688

   (6) https://bugs.python.org/issue33462

   (7) https://bugs.python.org/issue34641

   (8) https://bugs.python.org/issue32117

   (9) https://bugs.python.org/issue15248

   (10) https://bugs.python.org/issue32417

   (11) https://bugs.python.org/issue1054041

   (12) https://bugs.python.org/issue37032

   (13) https://en.wikipedia.org/wiki/Modular_multiplicative_inverse

   (14) https://en.wikipedia.org/wiki/Diophantine_equation

   (15) https://bugs.python.org/issue36027

   (16) https://bugs.python.org/issue35224

   (17) https://bugs.python.org/issue35900


File: python.info,  Node: 新增模块,  Next: 改进的模块,  Prev: 其他语言特性修改,  Up: Python 3 8 有什么新变化

1.1.4 新增模块
--------------

   * 新增的 *note importlib.metadata: 9e. 模块提供了从第三方包读取元数据
     的（临时）支持。 例如，它可以提取一个已安装软件包的版本号、入口点列
     表等等:

          >>> # Note following example requires that the popular "requests"
          >>> # package has been installed.
          >>>
          >>> from importlib.metadata import version, requires, files
          >>> version('requests')
          '2.22.0'
          >>> list(requires('requests'))
          ['chardet (<3.1.0,>=3.0.2)']
          >>> list(files('requests'))[:5]
          [PackagePath('requests-2.22.0.dist-info/INSTALLER'),
           PackagePath('requests-2.22.0.dist-info/LICENSE'),
           PackagePath('requests-2.22.0.dist-info/METADATA'),
           PackagePath('requests-2.22.0.dist-info/RECORD'),
           PackagePath('requests-2.22.0.dist-info/WHEEL')]

     （由 Barry Warsaw 和 Jason R. Coombs 在 bpo-34632(1) 中贡献）。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34632


File: python.info,  Node: 改进的模块,  Next: 性能优化,  Prev: 新增模块,  Up: Python 3 8 有什么新变化

1.1.5 改进的模块
----------------

* Menu:

* ast::
* asyncio::
* builtins::
* collections::
* cProfile::
* csv::
* curses::
* ctypes::
* datetime::
* functools::
* gc::
* gettext::
* gzip::
* IDLE 与 idlelib::
* inspect::
* io::
* itertools::
* json.tool: json tool.
* logging::
* math::
* mmap::
* multiprocessing::
* os::
* os.path: os path.
* pathlib::
* pickle::
* plistlib::
* pprint::
* py_compile::
* shlex::
* shutil::
* socket::
* ssl::
* statistics::
* sys::
* tarfile::
* threading::
* tokenize::
* tkinter::
* time::
* typing::
* unicodedata::
* unittest::
* venv::
* weakref::
* xml::
* xmlrpc::


File: python.info,  Node: ast,  Next: asyncio,  Up: 改进的模块

1.1.5.1 ast
...........

AST 节点现在具有 ‘end_lineno’ 和 ‘end_col_offset’ 属性，它们给出节点结束
的精确位置。 （这只适用于具有 ‘lineno’ 和 ‘col_offset’ 属性的节点。）

新增函数 *note ast.get_source_segment(): 1a1. 返回指定 AST 节点的源代码
。

（由 Ivan Levkivskyi 在 bpo-33416(1) 中贡献。）

*note ast.parse(): 1a2. 函数具有一些新的旗标：

   * ‘type_comments=True’ 导致其返回与特定 AST 节点相关联的 PEP 484(2) 和
     PEP 526(3) 类型注释文本；

   * ‘mode='func_type'’ 可被用于解析 PEP 484(4) "签名类型注释" (为函数定
     义 AST 节点而返回)；

   * ‘feature_version=(3, N)’ 允许指定一个更早的 Python 3 版本。 例如，
     ‘feature_version=(3, 4)’ 将把 *note async: 1a3. 和 *note await:
     1a4. 视为非保留字。

（由 Guido van Rossum 在 bpo-35766(5) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33416

   (2) https://www.python.org/dev/peps/pep-0484

   (3) https://www.python.org/dev/peps/pep-0526

   (4) https://www.python.org/dev/peps/pep-0484

   (5) https://bugs.python.org/issue35766


File: python.info,  Node: asyncio,  Next: builtins,  Prev: ast,  Up: 改进的模块

1.1.5.2 asyncio
...............

*note asyncio.run(): 1a6. 已经从暂定状态晋级为稳定 API。 此函数可被用于
执行一个 *note coroutine: 1a7. 并返回结果，同时自动管理事件循环。 例如:

     import asyncio

     async def main():
         await asyncio.sleep(0)
         return 42

     asyncio.run(main())

这 `大致' 等价于:

     import asyncio

     async def main():
         await asyncio.sleep(0)
         return 42

     loop = asyncio.new_event_loop()
     asyncio.set_event_loop(loop)
     try:
         loop.run_until_complete(main())
     finally:
         asyncio.set_event_loop(None)
         loop.close()

实际的实现要更复杂许多。 因此 *note asyncio.run(): 1a6. 应该作为运行
asyncio 程序的首选方式。

（由 Yury Selivanov 在 bpo-32314(1) 中贡献。）

运行 ‘python -m asyncio’ 将启动一个原生异步 REPL。 这允许快速体验具有最
高层级 *note await: 1a4. 的代码。 这时不再需要直接调用 ‘asyncio.run()’，
因为此操作会在每次发起调用时产生一个新事件循环：

     $ python -m asyncio
     asyncio REPL 3.8.0
     Use "await" directly instead of "asyncio.run()".
     Type "help", "copyright", "credits" or "license" for more information.
     >>> import asyncio
     >>> await asyncio.sleep(10, result='hello')
     hello

（由 Yury Selivanov 在 bpo-37028(2) 中贡献。）

异常 *note asyncio.CancelledError: 1a8. 现在继承自 *note BaseException:
1a9. 而不是 *note Exception: 1aa. 并且不再继承自 *note
concurrent.futures.CancelledError: 1ab.。 （由 Yury Selivanov 在
bpo-32528(3) 中贡献。）

在 Windows 上，现在默认的事件循环为 *note ProactorEventLoop: 1ac.。 （由
Victor Stinner 在 bpo-34687(4) 中贡献。）

*note ProactorEventLoop: 1ac. 现在也支持 UDP。 （由 Adam Meily 和 Andrew
Svetlov 在 bpo-29883(5) 中贡献。）

*note ProactorEventLoop: 1ac. 现在可通过 *note KeyboardInterrupt: 198.
("CTRL+C") 来中断。 （由 Vladimir Matveev 在 bpo-23057(6) 中贡献。）

添加了 *note asyncio.Task.get_coro(): 1ad. 用来获取 *note asyncio.Task:
1ae. 中的已包装协程。 （由 Alex Grönholm 在 bpo-36999(7) 中贡献。）

asyncio 任务现在可以被命名，或者是通过将 ‘name’ 关键字参数传给 *note
asyncio.create_task(): 1af. 或 *note create_task(): 1b0. 事件循环方法，
或者是通过在任务对象上调用 *note set_name(): 1b1. 方法。 任务名称在
*note asyncio.Task: 1ae. 的 ‘repr()’ 输出中可见，并且还可以使用 *note
get_name(): 1b2. 方法来获取。 （由 Alex Grönholm 在 bpo-34270(8) 中贡献
。）

将对 Happy Eyeballs(9) 的支持添加到 *note
asyncio.loop.create_connection(): 1b3.。 要指定此行为，已增加了两个新的
形参: `happy_eyeballs_delay' 和 `interleave'。 Happy Eyeballs 算法可提升
支持 IPv4 和 IPv6 的应用的响应速度，具体做法是尝试同时使用两者进行连接。
（由 twisteroid ambassador 在 bpo-33530(10) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32314

   (2) https://bugs.python.org/issue37028

   (3) https://bugs.python.org/issue32528

   (4) https://bugs.python.org/issue34687

   (5) https://bugs.python.org/issue29883

   (6) https://bugs.python.org/issue23057

   (7) https://bugs.python.org/issue36999

   (8) https://bugs.python.org/issue34270

   (9) https://en.wikipedia.org/wiki/Happy_Eyeballs

   (10) https://bugs.python.org/issue33530


File: python.info,  Node: builtins,  Next: collections,  Prev: asyncio,  Up: 改进的模块

1.1.5.3 builtins
................

内置的 *note compile(): 1b5. 已改进为可接受
‘ast.PyCF_ALLOW_TOP_LEVEL_AWAIT’ 旗标。 当传入此新旗标时，*note
compile(): 1b5. 将允许通常被视为无效语法的最高层级 ‘await’, ‘async for’
和 ‘async with’ 构造。 此后将可返回带有 ‘CO_COROUTINE’ 旗标的异步代码对
象。 （由 Matthias Bussonnier 在 bpo-34616(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34616


File: python.info,  Node: collections,  Next: cProfile,  Prev: builtins,  Up: 改进的模块

1.1.5.4 collections
...................

*note collections.namedtuple(): 1b7. 的 *note _asdict(): 1b8. 方法现在将
返回 *note dict: 1b9. 而不是 *note collections.OrderedDict: 1ba.。 此项
更改是由于普通字典自 Python 3.7 起已保证具有确定的元素顺序。 如果还需要
‘OrderedDict’ 的额外特性，建议的解决方案是将结果转换为需要的类型:
‘OrderedDict(nt._asdict())’。 （由 Raymond Hettinger 在 bpo-35864(1) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35864


File: python.info,  Node: cProfile,  Next: csv,  Prev: collections,  Up: 改进的模块

1.1.5.5 cProfile
................

*note cProfile.Profile: 1bc. 类现在可被用作上下文管理器。 在运行时对一个
代码块实现性能分析:

     import cProfile

     with cProfile.Profile() as profiler:
           # code to be profiled
           ...

（由 Scott Sanderson 在 bpo-29235(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29235


File: python.info,  Node: csv,  Next: curses,  Prev: cProfile,  Up: 改进的模块

1.1.5.6 csv
...........

*note csv.DictReader: 1be. 现在将返回 *note dict: 1b9. 而不是 *note
collections.OrderedDict: 1ba.。 此工具现在会更快速且消耗更少内存同时仍然
保留字段顺序。 （由 Michael Selik 在 bpo-34003(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34003


File: python.info,  Node: curses,  Next: ctypes,  Prev: csv,  Up: 改进的模块

1.1.5.7 curses
..............

添加了一个新变量用于保存下层 ncurses 库的结构版信息: *note
ncurses_version: 1c0.。 （由 Serhiy Storchaka 在 bpo-31680(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31680


File: python.info,  Node: ctypes,  Next: datetime,  Prev: curses,  Up: 改进的模块

1.1.5.8 ctypes
..............

在 Windows 上，*note CDLL: 1c2. 及其子类现在接受 `winmode' 形参来指定用
于底层 ‘LoadLibraryEx’ 调用的旗标。 默认旗标被设为仅加载来自可信任位置的
DLL 依赖项，包括 DLL 的存放路径（如果加载初始 DLL 时使用了完整或部分路径
）以及通过 *note add_dll_directory(): 1c3. 添加的路径。 （由 Steve Dower
在 bpo-36085(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36085


File: python.info,  Node: datetime,  Next: functools,  Prev: ctypes,  Up: 改进的模块

1.1.5.9 datetime
................

添加了新的替代构造器 *note datetime.date.fromisocalendar(): 1c5. 和
*note datetime.datetime.fromisocalendar(): 1c6.，它们分别基于 ISO 年份、
周序号和周内日序号来构造 ‘date’ 和 *note datetime: 31. 对象；这两者分别
是其所对应类中 ‘isocalendar’ 方法的逆操作。 （由 Paul Ganssle 在
bpo-36004(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36004


File: python.info,  Node: functools,  Next: gc,  Prev: datetime,  Up: 改进的模块

1.1.5.10 functools
..................

*note functools.lru_cache(): 1c8. 现在可直接作为装饰器而不是作为返回装饰
器的函数。 因此这两种写法现在都被支持:

     @lru_cache
     def f(x):
         ...

     @lru_cache(maxsize=256)
     def f(x):
         ...

（由 Raymond Hettinger 在 bpo-36772(1) 中贡献。）

添加了新的 *note functools.cached_property(): 1c9. 装饰器，用于在实例生
命周期内缓存的已计算特征属性。

     import functools
     import statistics

     class Dataset:
        def __init__(self, sequence_of_numbers):
           self.data = sequence_of_numbers

        @functools.cached_property
        def variance(self):
           return statistics.variance(self.data)

（由 Carl Meyer 在 bpo-21145(2) 中贡献）

添加了新的 *note functools.singledispatchmethod(): 1ca. 装饰器可使用
*note single dispatch: 1cb. 将方法转换为 *note 泛型函数: 1cc.:

     from functools import singledispatchmethod
     from contextlib import suppress

     class TaskManager:

         def __init__(self, tasks):
             self.tasks = list(tasks)

         @singledispatchmethod
         def discard(self, value):
             with suppress(ValueError):
                 self.tasks.remove(value)

         @discard.register(list)
         def _(self, tasks):
             targets = set(tasks)
             self.tasks = [x for x in self.tasks if x not in targets]

（由 Ethan Smith 在 bpo-32380(3) 中贡献）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36772

   (2) https://bugs.python.org/issue21145

   (3) https://bugs.python.org/issue32380


File: python.info,  Node: gc,  Next: gettext,  Prev: functools,  Up: 改进的模块

1.1.5.11 gc
...........

*note get_objects(): 1ce. 现在能接受一个可选的 `generation' 形参来指定一
个用于获取对象的生成器。 （由 Pablo Galindo 在 bpo-36016(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36016


File: python.info,  Node: gettext,  Next: gzip,  Prev: gc,  Up: 改进的模块

1.1.5.12 gettext
................

添加了 *note pgettext(): 1d0. 及其变化形式。 （由 Franz Glasner, Éric
Araujo 和 Cheryl Sabella 在 bpo-2504(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2504


File: python.info,  Node: gzip,  Next: IDLE 与 idlelib,  Prev: gettext,  Up: 改进的模块

1.1.5.13 gzip
.............

添加 `mtime' 形参到 *note gzip.compress(): 1d2. 用于可重现的输出。 （由
Guo Ci Teo 在 bpo-34898(1) 中贡献。）

对于特定类型的无效或已损坏 gzip 文件现在将引发 *note BadGzipFile: 1d3. 而
不是 *note OSError: 1d4.。 （由 Filip Gruszczyński, Michele Orrù 和
Zackery Spytz 在 bpo-6584(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34898

   (2) https://bugs.python.org/issue6584


File: python.info,  Node: IDLE 与 idlelib,  Next: inspect,  Prev: gzip,  Up: 改进的模块

1.1.5.14 IDLE 与 idlelib
........................

超过 N 行（默认值为 50）的输出将被折叠为一个按钮。 N 可以在 Settings 对
话框的 General 页的 PyShell 部分中进行修改。 数量较少但是超长的行可以通
过在输出上右击来折叠。 被折叠的输出可通过双击按钮来展开，或是通过右击按
钮来放入剪贴板或是单独的窗口。 （由 Tal Einat 在 bpo-1529353(1) 中贡献。
）

在 Run 菜单中增加了 "Run Customized" 以使用自定义设置来运行模块。 输入的
任何命令行参数都会被加入 sys.argv。 它们在下次自定义运行时会再次显示在窗
体中。 用户也可以禁用通常的 Shell 主模块重启。 （由 Cheryl Sabella,
Terry Jan Reedy 等人在 bpo-5680(2) 和 bpo-37627(3) 中贡献。）

在 IDLE 编辑器窗口中增加了可选的行号。 窗口打开时默认不显示行号，除非在
配置对话框的 General 选项卡中特别设置。 已打开窗口中的行号可以在 Options
菜单中显示和隐藏。 （由 Tal Einat 和 Saimadhav Heblikar 在 bpo-17535(4)
中贡献。）

现在会使用 OS 本机编码格式在 Python 字符串和 Tcl 对象间进行转换。 这允许
在 IDLE 中处理 emoji 和其他非 BMP 字符。 这些字符将可被显示或是从剪贴板
复制和粘贴。 字符串从 Tcl 到 Python 的来回转换现在不会再发生失败。 （过
去八年有许多人都为此付出过努力，问题最终由 Serhiy Storchaka 在
bpo-13153(5) 中解决。）

在 3.8.1 中新增:

添加切换光标闪烁停止的选项。 （由 Zackery Spytz 在 bpo-4603(6) 中贡献。
）

Esc 键现在会关闭 IDLE 补全提示窗口。 （由 Johnny Najera 在 bpo-38944(7)
中贡献。）

上述修改已被反向移植到 3.7 维护发行版中。

添加关键字到模块名称补全列表。 （由 Terry J. Reedy 在 bpo-37765(8) 中贡
献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1529353

   (2) https://bugs.python.org/issue5680

   (3) https://bugs.python.org/issue37627

   (4) https://bugs.python.org/issue17535

   (5) https://bugs.python.org/issue13153

   (6) https://bugs.python.org/issue4603

   (7) https://bugs.python.org/issue38944

   (8) https://bugs.python.org/issue37765


File: python.info,  Node: inspect,  Next: io,  Prev: IDLE 与 idlelib,  Up: 改进的模块

1.1.5.15 inspect
................

*note inspect.getdoc(): 1d7. 函数现在可以找到 ‘__slots__’ 的文档字符串，
如果该属性是一个元素值为文档字符串的 *note dict: 1b9. 的话。 这提供了类
似于目前已有的 *note property(): 1d8, *note classmethod(): 1d9. 和 *note
staticmethod(): 1da. 等函数的文档选项:

     class AudioClip:
         __slots__ = {'bit_rate': 'expressed in kilohertz to one decimal place',
                      'duration': 'in seconds, rounded up to an integer'}
         def __init__(self, bit_rate, duration):
             self.bit_rate = round(bit_rate / 1000.0, 1)
             self.duration = ceil(duration)

（由 Raymond Hettinger 在 bpo-36326(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36326


File: python.info,  Node: io,  Next: itertools,  Prev: inspect,  Up: 改进的模块

1.1.5.16 io
...........

在开发模式 (*note -X: 156. ‘env’) 和调试构建中，*note io.IOBase: 1dc. 终
结器现在会在 ‘close()’ 方法失败时将异常写入日志。 发生的异常在发布构建中
默认会被静默忽略。 （由 Victor Stinner 在 bpo-18748(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18748


File: python.info,  Node: itertools,  Next: json tool,  Prev: io,  Up: 改进的模块

1.1.5.17 itertools
..................

*note itertools.accumulate(): 1de. 函数增加了可选的 `initial' 关键字参数
用来指定一个初始值:

     >>> from itertools import accumulate
     >>> list(accumulate([10, 5, 30, 15], initial=1000))
     [1000, 1010, 1015, 1045, 1060]

（由 Lisa Roach 在 bpo-34659(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34659


File: python.info,  Node: json tool,  Next: logging,  Prev: itertools,  Up: 改进的模块

1.1.5.18 json.tool
..................

添加选项 ‘--json-lines’ 用于将每个输入行解析为单独的 JSON 对象。 （由
Weipeng Hong 在 bpo-31553(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31553


File: python.info,  Node: logging,  Next: math,  Prev: json tool,  Up: 改进的模块

1.1.5.19 logging
................

为 *note logging.basicConfig(): 1e1. 添加了 `force' 关键字参数，当设为真
值时，关联到根日志记录器的任何现有处理程序都将在执行由其他参数所指定的配
置之前被移除并关闭。

这解决了一个长期存在的问题。 当一个日志处理器或 `basicConfig()' 被调用时
，对 `basicConfig()' 的后续调用会被静默地忽略。 这导致使用交互提示符或
Jupyter 笔记本更新、试验或讲解各种日志配置选项变得相当困难。

（由 Raymond Hettinger 提议，由 Dong-hee Na 实现，并由 Vinay Sajip 在
bpo-33897(1) 中完成审核。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33897


File: python.info,  Node: math,  Next: mmap,  Prev: logging,  Up: 改进的模块

1.1.5.20 math
.............

添加了新的函数 *note math.dist(): 1e3. 用于计算两点之间的欧几里得距离。
（由 Raymond Hettinger 在 bpo-33089(1) 中贡献。）

扩展了 *note math.hypot(): 1e4. 函数以便处理更多的维度。 之前它仅支持
2-D 的情况。 （由 Raymond Hettinger 在 bpo-33089(2) 中贡献。）

添加了新的函数 *note math.prod(): 1e5. 作为的 *note sum(): 1e6. 同类，该
函数返回 ’start’ 值 (默认值: 1) 乘以一个数字可迭代对象的积:

     >>> prior = 0.8
     >>> likelihoods = [0.625, 0.84, 0.30]
     >>> math.prod(likelihoods, start=prior)
     0.126

（由 Pablo Galindo 在 bpo-35606(3) 中贡献。）

添加了两个新的组合函数 *note math.perm(): 1e7. 和 *note math.comb():
1e8.:

     >>> math.perm(10, 3)    # Permutations of 10 things taken 3 at a time
     720
     >>> math.comb(10, 3)    # Combinations of 10 things taken 3 at a time
     120

（由 Yash Aggarwal, Keller Fuchs, Serhiy Storchaka 和 Raymond Hettinger
在 bpo-37128(4), bpo-37178(5) 和 bpo-35431(6) 中贡献。）

添加了一个新函数 *note math.isqrt(): 1e9. 用于计算精确整数平方根而无需转
换为浮点数。 该新函数支持任意大整数。 它的执行速度比 ‘floor(sqrt(n))’ 快
但是比 *note math.sqrt(): 1ea. 慢:

     >>> r = 650320427
     >>> s = r ** 2
     >>> isqrt(s - 1)         # correct
     650320426
     >>> floor(sqrt(s - 1))   # incorrect
     650320427

（由 Mark Dickinson 在 bpo-36887(7) 中贡献。）

函数 *note math.factorial(): 1eb. 不再接受非整数类参数。 （由 Pablo
Galindo 在 bpo-33083(8) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33089

   (2) https://bugs.python.org/issue33089

   (3) https://bugs.python.org/issue35606

   (4) https://bugs.python.org/issue37128

   (5) https://bugs.python.org/issue37178

   (6) https://bugs.python.org/issue35431

   (7) https://bugs.python.org/issue36887

   (8) https://bugs.python.org/issue33083


File: python.info,  Node: mmap,  Next: multiprocessing,  Prev: math,  Up: 改进的模块

1.1.5.21 mmap
.............

*note mmap.mmap: 1ed. 类现在具有一个 *note madvise(): 1ee. 方法用于访问
‘madvise()’ 系统调用。 （由 Zackery Spytz 在 bpo-32941(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32941


File: python.info,  Node: multiprocessing,  Next: os,  Prev: mmap,  Up: 改进的模块

1.1.5.22 multiprocessing
........................

添加了新的 *note multiprocessing.shared_memory: bd. 模块。 （由 Davin
Potts 在 bpo-35813(1) 中贡献。）

在macOS上，现在默认使用的启动方式是*spawn*启动方式。 （由 Victor Stinner
在 bpo-33725(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35813

   (2) https://bugs.python.org/issue33725


File: python.info,  Node: os,  Next: os path,  Prev: multiprocessing,  Up: 改进的模块

1.1.5.23 os
...........

在 Windows 上添加了新函数 *note add_dll_directory(): 1c3. 用于在导入扩展
模块或使用 *note ctypes: 2b. 加载 DLL 时为本机依赖提供额外搜索路径 。 （
由 Steve Dower 在 bpo-36085(1) 中贡献。）

添加了新的 *note os.memfd_create(): 1f1. 函数用于包装 ‘memfd_create()’ 系
统调用。 （由 Zackery Spytz 和 Christian Heimes 在 bpo-26836(2) 中贡献。
）

在 Windows 上，大部分用于处理重解析点,（包括符号链接和目录连接）的手动逻
辑已被委托给操作系统。 特别地，*note os.stat(): 1f2. 现在将会遍历操作系
统所支持的任何内容，而 *note os.lstat(): 1f3. 将只打开被标识为“名称代理
”的重解析点，而其要由 *note os.stat(): 1f2. 打开其他的重解析点。 在所有
情况下，‘stat_result.st_mode’ 将只为符号链接而非其他种类的重解析点设置
‘S_IFLNK’。 要标识其他种类的重解析点，请检查新的
‘stat_result.st_reparse_tag’ 属性。

在 Windows 上，*note os.readlink(): 1f4. 现在能够读取目录连接。 请注意
*note islink(): 1f5. 会对目录连接返回 ‘False’，因此首先检查 ‘islink’ 的
代码将连续把连接视为目录，而会处理 *note os.readlink(): 1f4. 所引发错误
的代码现在会把连接视为链接。

（由 Steve Dower 在 bpo-37834(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36085

   (2) https://bugs.python.org/issue26836

   (3) https://bugs.python.org/issue37834


File: python.info,  Node: os path,  Next: pathlib,  Prev: os,  Up: 改进的模块

1.1.5.24 os.path
................

返回布尔值结果的 *note os.path: c6. 函数例如 *note exists(): 1f7, *note
lexists(): 1f8, *note isdir(): 1f9, *note isfile(): 1fa, *note islink():
1f5, 以及 *note ismount(): 1fb. 现在对于包含在 OS 层级无法表示的字符或字
节的路径将会返回 ‘False’ 而不是引发 *note ValueError: 1fc. 或其子类
*note UnicodeEncodeError: 1fd. 和 *note UnicodeDecodeError: 1fe.。 （由
Serhiy Storchaka 在 bpo-33721(1) 中贡献。）

*note expanduser(): 1ff. 在 Windows 上现在改用 ‘USERPROFILE’ 环境变量而
不再使用 ‘HOME’，后者通常不会为一般用户账户设置。 （由 Anthony Sottile 在
bpo-36264(2) 中贡献。）

*note isdir(): 1f9. 在 Windows 上将不再为不存在的目录的链接返回 ‘True’。

*note realpath(): 200. 在 Windows 上现在会识别重解析点，包括符号链接和目
录连接。

（由 Steve Dower 在 bpo-37834(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33721

   (2) https://bugs.python.org/issue36264

   (3) https://bugs.python.org/issue37834


File: python.info,  Node: pathlib,  Next: pickle,  Prev: os path,  Up: 改进的模块

1.1.5.25 pathlib
................

返回布尔值结果的 *note pathlib.Path: 202. 方法例如 *note exists(): 203,
*note is_dir(): 204, *note is_file(): 205, *note is_mount(): 206, *note
is_symlink(): 207, *note is_block_device(): 208, *note is_char_device():
209, *note is_fifo(): 20a, *note is_socket(): 20b. 现在对于包含在 OS 层
级无法表示的字符或字节的路径将会返回 ‘False’ 而不是引发 *note
ValueError: 1fc. 或其子类 *note UnicodeEncodeError: 1fd.。 （由 Serhiy
Storchaka 在 bpo-33721(1) 中贡献。）

添加了 *note pathlib.Path.link_to(): 20c. 用于创建指向某个路径的硬链接。
（由 Joannah Nanjekye 在 bpo-26978(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33721

   (2) https://bugs.python.org/issue26978


File: python.info,  Node: pickle,  Next: plistlib,  Prev: pathlib,  Up: 改进的模块

1.1.5.26 pickle
...............

*note pickle: cb. 扩展子类化针对 C 优化的 *note Pickler: 20e. 现在可通过
定义特殊的 *note reducer_override(): 20f. 方法来重载函数和类的封存逻辑。
（由 Pierre Glaser 和 Olivier Grisel 在 bpo-35900(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35900


File: python.info,  Node: plistlib,  Next: pprint,  Prev: pickle,  Up: 改进的模块

1.1.5.27 plistlib
.................

添加了新的 *note plistlib.UID: 211. 并启动了对读取和写入经过
NSKeyedArchiver 编码的二进制 plists 的支持。 （由 Jon Janzen 在
bpo-26707(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26707


File: python.info,  Node: pprint,  Next: py_compile,  Prev: plistlib,  Up: 改进的模块

1.1.5.28 pprint
...............

*note pprint: d3. 模块为一些函数添加了 `sort_dicts' 形参。 默认情况下，
这些函数会继续在渲染或打印之前对字典进行排序。 但是，如果 `sort_dicts' 设
为假值，则字典将保持键插入时的顺序。 这在调试期间与 JSON 输入进行比较时
会很有用。

除此之外，还增加了一个方便的新函数 *note pprint.pp(): 213.，它类似于
*note pprint.pprint(): 214. 但它的 `sort_dicts' 默认为 ‘False’:

     >>> from pprint import pprint, pp
     >>> d = dict(source='input.txt', operation='filter', destination='output.txt')
     >>> pp(d, width=40)                  # Original order
     {'source': 'input.txt',
      'operation': 'filter',
      'destination': 'output.txt'}
     >>> pprint(d, width=40)              # Keys sorted alphabetically
     {'destination': 'output.txt',
      'operation': 'filter',
      'source': 'input.txt'}

（由 Rémi Lapeyre 在 bpo-30670(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30670


File: python.info,  Node: py_compile,  Next: shlex,  Prev: pprint,  Up: 改进的模块

1.1.5.29 py_compile
...................

*note py_compile.compile(): 216. 现在支持静默模式。 （由 Joannah
Nanjekye 在 bpo-22640(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22640


File: python.info,  Node: shlex,  Next: shutil,  Prev: py_compile,  Up: 改进的模块

1.1.5.30 shlex
..............

新增了 *note shlex.join(): 218. 函数作为 *note shlex.split(): 219. 的逆
操作。 （由 Bo Bayles 在 bpo-32102(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32102


File: python.info,  Node: shutil,  Next: socket,  Prev: shlex,  Up: 改进的模块

1.1.5.31 shutil
...............

*note shutil.copytree(): 21b. 现在接受新的 ‘dirs_exist_ok’ 关键字参数。
（由 Josh Bronson 在 bpo-20849(1) 中贡献。）

*note shutil.make_archive(): 21c. 现在对新的归档默认使用 modern pax
(POSIX.1-2001) 格式以提升可移植性和标准一致性，此特性继承自对 *note
tarfile: 102. 模块的相应更改。 （由 C.A.M. Gerlach 在 bpo-30661(2) 中贡
献。）

*note shutil.rmtree(): 21d. 在 Windows 上现在会移除目录连接而不会递归地
先移除其中的内容。 （由 Steve Dower 在 bpo-37834(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20849

   (2) https://bugs.python.org/issue30661

   (3) https://bugs.python.org/issue37834


File: python.info,  Node: socket,  Next: ssl,  Prev: shutil,  Up: 改进的模块

1.1.5.32 socket
...............

添加了便捷的 *note create_server(): 21f. 和 *note has_dualstack_ipv6():
220. 函数以自动化在创建服务器套接字时通常情况下所必须的任务，包括在同一
套接字中同时接受 IPv4 和 IPv6 连接。 （由 Giampaolo Rodolà 在
bpo-17561(1) 中贡献。）

*note socket.if_nameindex(): 221, *note socket.if_nametoindex(): 222. 和
*note socket.if_indextoname(): 223. 函数已经在 Windows 上实现。 （由
Zackery Spytz 在 bpo-37007(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17561

   (2) https://bugs.python.org/issue37007


File: python.info,  Node: ssl,  Next: statistics,  Prev: socket,  Up: 改进的模块

1.1.5.33 ssl
............

增加了 *note post_handshake_auth: 225. 和 *note
verify_client_post_handshake(): 226. 分别启用和初始化 TLS 1.3 握手后验证
。 （由 Christian Heimes 在 bpo-34670(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34670


File: python.info,  Node: statistics,  Next: sys,  Prev: ssl,  Up: 改进的模块

1.1.5.34 statistics
...................

添加了 *note statistics.fmean(): 228. 作为 *note statistics.mean(): 19a.
的更快速的浮点数版版本。 （由 Raymond Hettinger 和 Steven D’Aprano 在
bpo-35904(1) 中贡献。）

添加了 *note statistics.geometric_mean(): 229. （由 Raymond Hettinger 在
bpo-27181(2) 中贡献。）

添加了 *note statistics.multimode(): 22a. 用于返回最常见值的列表。 （由
Raymond Hettinger 在 bpo-35892(3) 中贡献。）

添加了 *note statistics.quantiles(): 22b. 用于将数据或分布划分为多个等概
率区间（例如四分位、十分位或百分位）。 （由 Raymond Hettinger 在
bpo-36546(4) 中贡献。）

添加了 *note statistics.NormalDist: 22c. 用于创建和操纵随机变量的正态分
布。 （由 Raymond Hettinger 在 bpo-36018(5) 中贡献。）

     >>> temperature_feb = NormalDist.from_samples([4, 12, -3, 2, 7, 14])
     >>> temperature_feb.mean
     6.0
     >>> temperature_feb.stdev
     6.356099432828281

     >>> temperature_feb.cdf(3)            # Chance of being under 3 degrees
     0.3184678262814532
     >>> # Relative chance of being 7 degrees versus 10 degrees
     >>> temperature_feb.pdf(7) / temperature_feb.pdf(10)
     1.2039930378537762

     >>> el_niño = NormalDist(4, 2.5)
     >>> temperature_feb += el_niño        # Add in a climate effect
     >>> temperature_feb
     NormalDist(mu=10.0, sigma=6.830080526611674)

     >>> temperature_feb * (9/5) + 32      # Convert to Fahrenheit
     NormalDist(mu=50.0, sigma=12.294144947901014)
     >>> temperature_feb.samples(3)        # Generate random samples
     [7.672102882379219, 12.000027119750287, 4.647488369766392]

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35904

   (2) https://bugs.python.org/issue27181

   (3) https://bugs.python.org/issue35892

   (4) https://bugs.python.org/issue36546

   (5) https://bugs.python.org/issue36018


File: python.info,  Node: sys,  Next: tarfile,  Prev: statistics,  Up: 改进的模块

1.1.5.35 sys
............

添加了新的 *note sys.unraisablehook(): 22e. 函数，可被重载以便控制如何处
理“不可引发的异常”。 它会在发生了一个异常但 Python 没有办法处理时被调用
。 例如，当一个析构器在垃圾回收时 (*note gc.collect(): 22f.) 所引发的异
常。 （由 Victor Stinner 在 bpo-36829(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36829


File: python.info,  Node: tarfile,  Next: threading,  Prev: sys,  Up: 改进的模块

1.1.5.36 tarfile
................

*note tarfile: 102. 模块现在对新的归档默认使用 modern pax (POSIX.1-2001)
格式而不再是之前的 GNU 专属格式。 这通过标准化和可扩展格式的统一编码
(UTF-8) 提升了跨平台可移植性，还提供了其他一些益处。 （由 C.A.M. Gerlach
在 bpo-36268(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36268


File: python.info,  Node: threading,  Next: tokenize,  Prev: tarfile,  Up: 改进的模块

1.1.5.37 threading
..................

添加了新的 *note threading.excepthook(): 232. 函数用来处理未捕获的 *note
threading.Thread.run(): 233. 异常。 它可被重载以便控制如何处理未捕获的
*note threading.Thread.run(): 233. 异常。 （由 Victor Stinner 在
bpo-1230540(1) 中贡献。）

添加了新的 *note threading.get_native_id(): 234. 函数以及 *note
threading.Thread: 235. 类的 *note native_id: 236. 属性。 它们会返回内核
所分配给当前线程的原生整数线程 ID。 此特性仅在特定平台上可用，参见 *note
get_native_id: 234. 了解详情。 （由 Jake Tesler 在 bpo-36084(2) 中贡献。
）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1230540

   (2) https://bugs.python.org/issue36084


File: python.info,  Node: tokenize,  Next: tkinter,  Prev: threading,  Up: 改进的模块

1.1.5.38 tokenize
.................

当提供不带末尾新行的输入时，*note tokenize: 112. 模块现在会隐式地添加
‘NEWLINE’ 形符。 此行为现在已与 C 词法分析器的内部行为相匹配。 （由
Ammar Askar 在 bpo-33899(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33899


File: python.info,  Node: tkinter,  Next: time,  Prev: tokenize,  Up: 改进的模块

1.1.5.39 tkinter
................

在 ‘tkinter.Spinbox’ 中添加了方法 ‘selection_from()’,
‘selection_present()’, ‘selection_range()’ 和 ‘selection_to()’。 （由
Juliette Monsel 在 bpo-34829(1) 中贡献。）

在 ‘tkinter.Canvas’ 类中添加了方法 ‘moveto()’。 （由 Juliette Monsel 在
bpo-23831(2) 中贡献。）

‘tkinter.PhotoImage’ 类现在具有 ‘transparency_get()’ 和
‘transparency_set()’ 方法。 （由 Zackery Spytz 在 bpo-25451(3) 中贡献。
）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34829

   (2) https://bugs.python.org/issue23831

   (3) https://bugs.python.org/issue25451


File: python.info,  Node: time,  Next: typing,  Prev: tkinter,  Up: 改进的模块

1.1.5.40 time
.............

为 macOS 10.12 添加了新的时钟 *note CLOCK_UPTIME_RAW: 23a.。 （由
Joannah Nanjekye 在 bpo-35702(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35702


File: python.info,  Node: typing,  Next: unicodedata,  Prev: time,  Up: 改进的模块

1.1.5.41 typing
...............

*note typing: 11a. 模块加入了一些新特性：

   * 一个带有键专属类型的字典类型。 参见 PEP 589(1) 和 *note
     typing.TypedDict: 23c.。 TypedDict 只使用字符串作为键。 默认情况下
     每个键都要求提供。 指定 "total=False" 以允许键作为可选项:

          class Location(TypedDict, total=False):
              lat_long: tuple
              grid_square: str
              xy_coordinate: tuple

   * Literal 类型。 参见 PEP 586(2) 和 *note typing.Literal: 23d.。
     Literal 类型指明一个形参或返回值被限定为一个或多个特定的字面值:

          def get_status(port: int) -> Literal['connected', 'disconnected']:
              ...

   * "Final" 变量、函数、方法和类。 参见 PEP 591(3), *note typing.Final:
     23e. 和 *note typing.final(): 23f.。 final 限定符会指示静态类型检查
     器限制进行子类化、重载或重新赋值:

          pi: Final[float] = 3.1415926536

   * 协议定义。 参见 PEP 544(4), *note typing.Protocol: 240. 和 *note
     typing.runtime_checkable(): 241.。 简单的 ABC 例如 *note
     typing.SupportsInt: 242. 现在是 ‘Protocol’ 的子类。

   * 新的协议类 *note typing.SupportsIndex: 243.。

   * 新的函数 *note typing.get_origin(): 244. 和 *note
     typing.get_args(): 245.。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0589

   (2) https://www.python.org/dev/peps/pep-0586

   (3) https://www.python.org/dev/peps/pep-0591

   (4) https://www.python.org/dev/peps/pep-0544


File: python.info,  Node: unicodedata,  Next: unittest,  Prev: typing,  Up: 改进的模块

1.1.5.42 unicodedata
....................

*note unicodedata: 11b. 模块现在已升级为使用 Unicode 12.1.0(1) 发布版。

新的函数 *note is_normalized(): 247. 可被用来验证字符串是否为特定正规形
式，通常会比实际进行字符串正规化要快得多。 （由 Max Belanger, David
Euresti 和 Greg Price 在 bpo-32285(2) 和 bpo-37966(3) 中贡献。）

   ---------- Footnotes ----------

   (1) http://blog.unicode.org/2019/05/unicode-12-1-en.html

   (2) https://bugs.python.org/issue32285

   (3) https://bugs.python.org/issue37966


File: python.info,  Node: unittest,  Next: venv,  Prev: unicodedata,  Up: 改进的模块

1.1.5.43 unittest
.................

添加了 *note AsyncMock: 249. 以支持异步版本的 *note Mock: 24a.。 同时也
添加了相应的断言函数用于测试。 （由 Lisa Roach 在 bpo-26467(1) 中贡献。
）

unittest 添加了 *note addModuleCleanup(): 24b. 和 *note
addClassCleanup(): 24c. 以支持对 ‘setUpModule()’ 和 *note setUpClass():
24d. 进行清理。 （由 Lisa Roach 在 bpo-24412(2) 中贡献。）

一些模拟断言函数现在也会在失败时打印一个实际调用列表。 （由 Petter
Strandmark 在 bpo-35047(3) 中贡献。）

*note unittest: 11c. 模块已支持通过 *note
unittest.IsolatedAsyncioTestCase: 24e. 来使用协程作为测试用例。 （由
Andrew Svetlov 在 bpo-32972(4) 中贡献。）

示例:

     import unittest


     class TestRequest(unittest.IsolatedAsyncioTestCase):

         async def asyncSetUp(self):
             self.connection = await AsyncConnection()

         async def test_get(self):
             response = await self.connection.get("https://example.com")
             self.assertEqual(response.status_code, 200)

         async def asyncTearDown(self):
             await self.connection.close()


     if __name__ == "__main__":
         unittest.main()

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26467

   (2) https://bugs.python.org/issue24412

   (3) https://bugs.python.org/issue35047

   (4) https://bugs.python.org/issue32972


File: python.info,  Node: venv,  Next: weakref,  Prev: unittest,  Up: 改进的模块

1.1.5.44 venv
.............

现在 *note venv: 126. 在所有平台上都会包含 ‘Activate.ps1’ 脚本用于在
PowerShell Core 6.1 下激活虚拟环境。 （由 Brett Cannon 在 bpo-32718(1) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32718


File: python.info,  Node: weakref,  Next: xml,  Prev: venv,  Up: 改进的模块

1.1.5.45 weakref
................

由 *note weakref.proxy(): 251. 返回的代理对象现在除其他算术运算符外也支
持矩阵乘法运算符 ‘@’ 和 ‘@=’。 （由 Mark Dickinson 在 bpo-36669(1) 中贡
献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36669


File: python.info,  Node: xml,  Next: xmlrpc,  Prev: weakref,  Up: 改进的模块

1.1.5.46 xml
............

作为对 DTD 和外部实体检索的缓解，在默认情况下 *note xml.dom.minidom:
136. 和 *note xml.sax: 13c. 模块不再处理外部实体。 （由 Christian Heimes
在 bpo-17239(1) 中贡献。）

*note xml.etree.ElementTree: 138. 模块中的 ‘.find*()’ 方法支持通配符搜索
例如 ‘{*}tag’，此搜索会忽略命名空间以及返回给定命名空间中所有标签的
‘{namespace}*’。 （由 Stefan Behnel 在 bpo-28238(2) 中贡献。）

*note xml.etree.ElementTree: 138. 模块提供了实现 C14N 2.0 的新函数
‘–xml.etree.ElementTree.canonicalize()’。 （由 Stefan Behnel 在
bpo-13611(3) 中贡献。）

*note xml.etree.ElementTree.XMLParser: 253. 的目标对象可通过新的回调方法
‘start_ns()’ 和 ‘end_ns()’ 来接受命名空间声明事件。 此外，*note
xml.etree.ElementTree.TreeBuilder: 254. 目标可被配置为处理有关注释和处理
指令事件以将它们包含在所生成的树当中。 （由 Stefan Behnel 在
bpo-36676(4) 和 bpo-36673(5) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17239

   (2) https://bugs.python.org/issue28238

   (3) https://bugs.python.org/issue13611

   (4) https://bugs.python.org/issue36676

   (5) https://bugs.python.org/issue36673


File: python.info,  Node: xmlrpc,  Prev: xml,  Up: 改进的模块

1.1.5.47 xmlrpc
...............

*note xmlrpc.client.ServerProxy: 256. 现在支持可选的 `headers' 关键字参
数作为随同每次请求发送的 HTTP 标头序列。 此特征的作用之一是使得从默认的
基础认证升级到更快速的会话认证成为可能。 （由 Cédric Krier 在
bpo-35153(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35153


File: python.info,  Node: 性能优化,  Next: 构建和 C API 的改变,  Prev: 改进的模块,  Up: Python 3 8 有什么新变化

1.1.6 性能优化
--------------

   * *note subprocess: fa. 模块现在能在某些情况下使用 *note
     os.posix_spawn(): 258. 函数以获得更好的性能。 目前，它的使用仅限
     macOS 和 Linux（使用 glibc 2.24 或更新版本），并要求满足以下条件：

        * `close_fds' 为假值；

        * `preexec_fn', `pass_fds', `cwd' 和 `start_new_session' 形参未
          设置；

        * `executable' 路径包含一个目录。

     （由 Joannah Nanjekye 和 Victor Stinner 在 bpo-35537(1) 中贡献。）

   * *note shutil.copyfile(): 259, *note shutil.copy(): 25a, *note
     shutil.copy2(): 25b, *note shutil.copytree(): 21b. 和 *note
     shutil.move(): 25c. 在 Linux 和 macOS 上会使用平台专属的
     "fast-copy" 系统调用以提高效率。 "fast-copy" 意味着拷贝操作发生于内
     核中，从而避免在进行 "‘outfd.write(infd.read())’" 等操作时使用
     Python 中的用户空间缓冲区。 在 Windows 上 *note shutil.copyfile():
     259. 会使用更大的默认缓冲区（1 MiB 而不是 16 KiB）并且使用基于
     *note memoryview(): 25d. 的 *note shutil.copyfileobj(): 25e. 版本。
     在同一分区内拷贝一个 512 MiB 文件的速度提升在 Linux 上约为 +26%，在
     macOS 上为 +50%，在 Windows 上为 +40%。 此外还将消耗更少的 CPU 周期
     。 参见 *note 依赖于具体平台的高效拷贝操作: 25f. 一节。 （由
     Giampaolo Rodolà 在 bpo-33671(2) 中贡献。）

   * *note shutil.copytree(): 21b. 会根据其所用缓存的 *note os.stat():
     1f2. 值使用 *note os.scandir(): 260. 函数及所有拷贝函数。 拷贝一个
     包含 8000 文件的目录的速度提升在 Linux 上约为 +9%，在 Windows 上为
     +20%，对于 Windows SMB 共享目录则为 +30%。 此外 *note os.stat():
     1f2. 系统调用的次数也减少了 38%，使得 *note shutil.copytree(): 21b.
     在网络文件系统上会特别快速。 （由Giampaolo Rodolà 在 bpo-33695(3) 中
     贡献。）

   * *note pickle: cb. 模块使用的默认协议现在为 Protocol 4，最早在
     Python 3.4 中被引入。 它提供了比自 Python 3.0 起可用的 Protocol 3 更
     好的性能和更小的数据尺寸。

   * 从 ‘PyGC_Head’ 移除了一个 ‘Py_ssize_t’ 成员。 所有跟踪 GC 的对象（
     例如 tuple, list, dict）大小减少了 4 或 8 字节。 （由 Inada Naoki 在
     bpo-33597(4) 中贡献。）

   * *note uuid.UUID: 261. 现在会使用 ‘__slots__’ 以减少内存足迹。 （由
     Wouter Bolsterlee 和 Tal Einat 在 bpo-30977(5) 中贡献。）

   * *note operator.itemgetter(): 262. 的性能提升了 33%。 优化了参数处理
     ，并为常见的在元组中单个非负整数索引的情况新增了一条快速路径（这是
     标准库中的典型用例）。 （由 Raymond Hettinger 在 bpo-35664(6) 中贡
     献。

   * 加快了在 *note collections.namedtuple(): 1b7. 中的字段查找。 它们现
     在的速度快了两倍以上，成为 Python 中最快的实例变量查找形式。 （由
     Raymond Hettinger, Pablo Galindo 和 Joe Jevnik, Serhiy Storchaka 在
     bpo-32492(7) 中贡献。）

   * 如果输入的可迭代对象的长度已知 (即输入对象实现了 ‘__len__’)，*note
     list: 263. 构造器不会过度分配内部项缓冲区。 这使得所创建的列表资源
     占用平均减少了 12%。 （由 Raymond Hettinger 和 Pablo Galindo 在
     bpo-33234(8) 中贡献。）

   * 类变量写入速度加倍。 当一个非冗余属性被更新时，之前存在一个更新
     slots 的非必要调用。 （由 Stefan Behnel, Pablo Galindo Salgado,
     Raymond Hettinger, Neil Schemenauer, 和 Serhiy Storchaka 在
     bpo-36012(9) 中贡献。）

   * 减少了传递给许多内置函数和方法的参数转换的开销。 这使得某些简单内置
     函数和方法的速度提升了 20–50%。 （由 Serhiy Storchaka 在
     bpo-23867(10), bpo-35582(11) 和 bpo-36127(12) 中贡献。）

   * ‘LOAD_GLOBAL’ 指令现在会使用新的 "per opcode cache" 机制。 它的速度
     现在提升了大约 40%。 （由 Yury Selivanov 和 Inada Naoki 在
     bpo-26219(13) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35537

   (2) https://bugs.python.org/issue33671

   (3) https://bugs.python.org/issue33695

   (4) https://bugs.python.org/issue33597

   (5) https://bugs.python.org/issue30977

   (6) https://bugs.python.org/issue35664

   (7) https://bugs.python.org/issue32492

   (8) https://bugs.python.org/issue33234

   (9) https://bugs.python.org/issue36012

   (10) https://bugs.python.org/issue23867

   (11) https://bugs.python.org/issue35582

   (12) https://bugs.python.org/issue36127

   (13) https://bugs.python.org/issue26219


File: python.info,  Node: 构建和 C API 的改变,  Next: 弃用,  Prev: 性能优化,  Up: Python 3 8 有什么新变化

1.1.7 构建和 C API 的改变
-------------------------

   * 默认的 *note sys.abiflags: 265. 成为一个空字符串：pymalloc 的 ‘m’ 旗
     标不再有意义（无论是否启用 pymalloc 构建都是兼容 ABI 的）因此已被移
     除。 （由 Victor Stinner 在 bpo-36707(1) 中贡献。）

     改变的例子：

        * 只会安装 ‘python3.8’ 程序，不再有 ‘python3.8m’ 程序。

        * 只会安装 ‘python3.8-config’ 脚本，不再有 ‘python3.8m-config’ 脚
          本。

        * ‘m’ 旗标已经从动态库文件名后缀中移除：包括标准库中的扩展模块以
          及第三方包所产生和安装的模块例如从 PyPI 下载的模块。 以 Linux
          为例，Python 3.7 的后缀 ‘.cpython-37m-x86_64-linux-gnu.so’ 在
          Python 3.8 中改为 ‘.cpython-38-x86_64-linux-gnu.so’。

   * 重新组织了所有头文件以更好地区分不同种类的 API：

        * ‘Include/*.h’ 应为可移植的公有稳定版 C API。

        * ‘Include/cpython/*.h’ 应为 CPython 专属的不稳定版 C API；公有
          API，部分私有 API 附加 ‘_Py’ or ‘_PY’ 前缀。

        * ‘Include/internal/*.h’ 应为 CPython 特别专属的私有内部 C API。
          此 API 不具备向下兼容保证并且不应在 CPython 以外被使用。 它们
          的公开仅适用于特别限定的需求例如调试器和性能分析等必须直接访问
          CPython 内部数据而不通过调用函数的应用。 此 API 现在是通过
          ‘make install’ 安装的。

     （由 Victor Stinner 在 bpo-35134(2) 和 bpo-35081(3) 中贡献，相关工
     作由 Eric Snow 在 Python 3.7 中发起。）

   * 某些宏已被转换为静态内联函数：形参类型和返回类型定义良好，它们不再
     会有与宏相关的问题，变量具有局部作用域。 例如：

        * *note Py_INCREF(): 266, *note Py_DECREF(): 267.

        * *note Py_XINCREF(): 268, *note Py_XDECREF(): 269.

        * ‘PyObject_INIT()’, ‘PyObject_INIT_VAR()’

        * 私有函数: ‘_PyObject_GC_TRACK()’, ‘_PyObject_GC_UNTRACK()’,
          ‘_Py_Dealloc()’

     （由 Victor Stinner 在 bpo-35059(4) 中贡献。）

   * ‘PyByteArray_Init()’ 和 ‘PyByteArray_Fini()’ 函数已被移除。 它们自
     Python 2.7.4 和 Python 3.2.0 起就没有任何用处，被排除在受限 API (稳
     定版 ABI) 之外，并且未被写入文档。 （由 Victor Stinner 在
     bpo-35713(5) 中贡献。）

   * ‘PyExceptionClass_Name()’ 的结果类型现在是 ‘const char *’ 而非
     ‘char *’。 （由 Serhiy Storchaka 在 bpo-33818(6) 中贡献。）

   * ‘Modules/Setup.dist’ 与 ‘Modules/Setup’ 两者的共存已被移除。 之前在
     更新 CPython 源码树时，开发者必须手动拷贝 ‘Modules/Setup.dist’ (在
     源码树内) 到 ‘Modules/Setup’ (在构建树内) 以反映上游的任何改变。 旧
     特性对打包者来说有一点益处，但代价是对追踪 CPython 开发进程的开发者
     造成经常性的麻烦，因为忘记拷贝该文件可能导致构建失败。

     现在构建系统总是会从源码树内的 ‘Modules/Setup’ 读取数据。 建议希望
     定制该文件的开发者在 CPython 的一个 git 分叉或补丁文件中维护他们的
     更改，就如他们对源码树做任何其他改变时一样。

     （由 Antoine Pitrou 在 bpo-32430(7) 中贡献。）

   * 将 Python 数字转换为 C 整型的函数例如 *note PyLong_AsLong(): 26a. 以
     及带有 ‘'i'’ 之类整型转换格式单元的参数解析函数例如 *note
     PyArg_ParseTuple(): 26b. 现在如果可能将会使用 *note __index__():
     18b. 特殊方法而不是 *note __int__(): 18c.。 对于带有 ‘__int__()’ 方
     法但没有 ‘__index__()’ 方法的对象 (例如 *note Decimal: 189. 和
     *note Fraction: 186.) 将会发出弃用警告。 对于实现了 ‘__index__()’ 的
     对象 *note PyNumber_Check(): 26c. 现在将返回 ‘1’。 *note
     PyNumber_Long(): 26d, *note PyNumber_Float(): 26e. 和 *note
     PyFloat_AsDouble(): 26f. 现在如果可能也将会使用 ‘__index__()’ 方法
     。 （由 Serhiy Storchaka 在 bpo-36048(8) 和 bpo-20092(9) 中贡献。）

   * 堆分配类型对象现在将增加它们在 *note PyObject_Init(): 270. (及其对
     应的宏 ‘PyObject_INIT’) 中的引用计数而不是在 *note
     PyType_GenericAlloc(): 271. 中。 修改实例分配或中止分配的类型可能需
     要进行调整。 （由 Elizondo 在 bpo-35810(10) 中贡献。）

   * 新增函数 *note PyCode_NewWithPosOnlyArgs(): 272. 允许创建代码对象例
     如 *note PyCode_New(): 273.，但带有一个额外的 `posonlyargcount' 形
     参以指明仅限位置参数的数量。 （由 Pablo Galindo 在 bpo-37221(11) 中
     贡献。）

   * *note Py_SetPath(): 274. 现在会将 *note sys.executable: 275. 设为程
     序完整路径 (*note Py_GetProgramFullPath(): 276.) 而不是程序名称
     (*note Py_GetProgramName(): 277.)。 （由 Victor Stinner 在
     bpo-38234(12) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36707

   (2) https://bugs.python.org/issue35134

   (3) https://bugs.python.org/issue35081

   (4) https://bugs.python.org/issue35059

   (5) https://bugs.python.org/issue35713

   (6) https://bugs.python.org/issue33818

   (7) https://bugs.python.org/issue32430

   (8) https://bugs.python.org/issue36048

   (9) https://bugs.python.org/issue20092

   (10) https://bugs.python.org/issue35810

   (11) https://bugs.python.org/issue37221

   (12) https://bugs.python.org/issue38234


File: python.info,  Node: 弃用,  Next: API 与特性的移除,  Prev: 构建和 C API 的改变,  Up: Python 3 8 有什么新变化

1.1.8 弃用
----------

   * distutils 的 ‘bdist_wininst’ 命令现在已弃用，请改用 ‘bdist_wheel’
     (wheel 包)。 （由 Victor Stinner 在 bpo-37481(1) 中贡献。）

   * *note ElementTree: 138. 模块中的已弃用方法 ‘getchildren()’ 和
     ‘getiterator()’ 现在会引发 *note DeprecationWarning: 279. 而不是
     *note PendingDeprecationWarning: 27a.。 它们将在 Python 3.9 中被移
     除。 （由 Serhiy Storchaka 在 bpo-29209(2) 中贡献。）

   * 将不是 *note concurrent.futures.ThreadPoolExecutor: 27b. 的实例的对
     象传给 *note loop.set_default_executor(): 27c. 已被弃用，并将在
     Python 3.9 中被禁止。 （由 Elvis Pranskevichus 在 bpo-34075(3) 中贡
     献。）

   * *note xml.dom.pulldom.DOMEventStream: 27d, *note
     wsgiref.util.FileWrapper: 27e. 和 *note fileinput.FileInput: 27f. 的
     *note __getitem__(): 280. 方法已被弃用。

     这些方法的实现会忽略它们的 `index' 形参，并改为返回下一条目。 （由
     Berker Peksag 在 bpo-9372(4) 中贡献。）

   * *note typing.NamedTuple: 281. 类已弃用了 ‘_field_types’ 属性而改用
     具有同样信息的 ‘__annotations__’ 属性。 （由 Raymond Hettinger 在
     bpo-36320(5) 中贡献。）

   * *note ast: 8. 类 ‘Num’, ‘Str’, ‘Bytes’, ‘NameConstant’ 和
     ‘Ellipsis’ 被视为已弃用并将在未来的 Python 版本中被移除。 应当改用
     ‘Constant’。 （由 Serhiy Storchaka 在 bpo-32892(6) 中贡献。）

   * *note ast.NodeVisitor: 282. 的方法 ‘visit_Num()’, ‘visit_Str()’,
     ‘visit_Bytes()’, ‘visit_NameConstant()’ 和 ‘visit_Ellipsis()’ 现在
     已被弃用，并且在未来的 Python 版本中将不再被调用。 添加
     ‘visit_Constant()’ 方法来处理所有常量节点。 （由 Serhiy Storchaka 在
     bpo-36917(7) 中贡献。）

   * *note asyncio.coroutine(): 283. *note decorator: 284. 已弃用并将在
     3.10 版中被移除。 原有的 ‘@asyncio.coroutine’ 请改用 *note async
     def: 285. 来替代。 （由 Andrew Svetlov 在 bpo-36921(8) 中贡献。）

   * 在 *note asyncio: a. 中，`loop' 参数的显式传递已被弃用并且到 3.10 版
     时将会在以下函数中被移除: *note asyncio.sleep(): 286, *note
     asyncio.gather(): 287, *note asyncio.shield(): 288, *note
     asyncio.wait_for(): 289, *note asyncio.wait(): 28a, *note
     asyncio.as_completed(): 28b, *note asyncio.Task: 1ae, *note
     asyncio.Lock: 28c, *note asyncio.Event: 28d, *note
     asyncio.Condition: 28e, *note asyncio.Semaphore: 28f, *note
     asyncio.BoundedSemaphore: 290, *note asyncio.Queue: 291, *note
     asyncio.create_subprocess_exec(): 292. 以及 *note
     asyncio.create_subprocess_shell(): 293.。

   * 将协程对象显式传递给 *note asyncio.wait(): 28a. 的做法已被弃用并且
     将在 3.11 版中被移除。 （由 Yury Selivanov 在 bpo-34790(9) 中贡献。
     ）

   * *note gettext: 89. 模块中的下列函数和方法已被弃用: *note
     lgettext(): 294, *note ldgettext(): 295, *note lngettext(): 296. 和
     *note ldngettext(): 297.。 它们返回已编码的字节串，如果转换后的字符
     串存在编码问题你将可能遭遇预期之外的异常。 更好的做法是使用 Python
     3 中返回 Unicode 字符串的操作作为替代。 前面的函数都早已不宜使用。

     函数 *note bind_textdomain_codeset(): 298.，方法 *note
     output_charset(): 299. 和 *note set_output_charset(): 29a.，以及函
     数 *note translation(): 29b. 和 *note install(): 29c. 的 `codeset'
     形参也已被弃用，因为它们仅适用于 ‘l*gettext()’ 函数。 （由 Serhiy
     Storchaka 在 bpo-33710(10) 中贡献。）

   * *note threading.Thread: 235. 的 ‘isAlive()’ 方法已弃用。 （由
     Dong-hee Na 在 bpo-35283(11) 中贡献。）

   * 许多接受整数参数的内置和扩展模块的函数现在将对传入 *note Decimal:
     189, *note Fraction: 186. 以及任何其他可被转换为整数但会丢失精度（
     即具有 *note __int__(): 18c. 方法但没有 *note __index__(): 18b. 方
     法）的对象发出弃用警告。 在未来的版本中则将报错。 （由 Serhiy
     Storchaka 在 bpo-36048(12) 中贡献。）

   * 以下参数作为关键字参数传递的方式已被弃用：

        - *note functools.partialmethod(): 29d, *note
          weakref.finalize(): 29e, *note profile.Profile.runcall(): 29f,
          ‘cProfile.Profile.runcall()’, *note bdb.Bdb.runcall(): 2a0,
          *note trace.Trace.runfunc(): 2a1. 与 *note curses.wrapper():
          2a2. 中的 `func'。

        - *note unittest.TestCase.addCleanup(): 2a3. 中的 `function'。

        - *note concurrent.futures.ThreadPoolExecutor: 27b. 和 *note
          concurrent.futures.ProcessPoolExecutor: 2a4. 的 *note
          submit(): 2a5. 方法中的 `fn'。

        - *note contextlib.ExitStack.callback(): 2a6,
          ‘contextlib.AsyncExitStack.callback()’ 和 *note
          contextlib.AsyncExitStack.push_async_callback(): 2a7. 中的
          `callback'。

        - ‘multiprocessing.managers.Server’ 和
          ‘multiprocessing.managers.SharedMemoryServer’ 的 ‘create()’ 方
          法中的 `c' 和 `typeid'。

        - *note weakref.finalize(): 29e. 中的 `obj'。

     在未来版本的 Python 中，它们将成为 *note 仅限位置参数: 2a8.。 （由
     Serhiy Storchaka 在 bpo-36492(13) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37481

   (2) https://bugs.python.org/issue29209

   (3) https://bugs.python.org/issue34075

   (4) https://bugs.python.org/issue9372

   (5) https://bugs.python.org/issue36320

   (6) https://bugs.python.org/issue32892

   (7) https://bugs.python.org/issue36917

   (8) https://bugs.python.org/issue36921

   (9) https://bugs.python.org/issue34790

   (10) https://bugs.python.org/issue33710

   (11) https://bugs.python.org/issue35283

   (12) https://bugs.python.org/issue36048

   (13) https://bugs.python.org/issue36492


File: python.info,  Node: API 与特性的移除,  Next: 移植到 Python 3 8,  Prev: 弃用,  Up: Python 3 8 有什么新变化

1.1.9 API 与特性的移除
----------------------

下列特性与 API 已从 Python 3.8 中移除：

   * 自 Python 3.3 起，从 *note collections: 1e. 导入 ABC 的做法已弃用，
     而应当从 *note collections.abc: 1f. 执行导入。 从 collections 导入
     的操作在 3.8 中已标记为被移除，但将推迟到 3.9 中实施。 （参见
     bpo-36952(1)。）

   * ‘macpath’ 模块，在 Python 3.7 中弃用，现已被移除。 （由 Victor
     Stinner 在 bpo-35471(2) 中贡献。）

   * 函数 ‘platform.popen()’ 已被移除，它自 Python 3.3 起就已被弃用：请
     改用 *note os.popen(): 2aa.。 （由 Victor Stinner 在 bpo-35345(3) 中
     贡献。）

   * 函数 ‘time.clock()’ 已被移除，它自 Python 3.3 起就已被弃用：请根据
     具体需求改用 *note time.perf_counter(): 2ab. 或 *note
     time.process_time(): 2ac. 以获得具有良好定义的行为。 （由 Matthias
     Bussonnier 在 bpo-36895(4) 中贡献。）

   * ‘pyvenv’ 脚本已被移除，推荐改用 ‘python3.8 -m venv’ 来帮助消除容易
     混淆 ‘pyvenv’ 脚本所关联的 Python 解释器这一问题。 （由 Brett
     Cannon 在 bpo-25427(5) 中贡献。）

   * ‘parse_qs’, ‘parse_qsl’ 和 ‘escape’ 已从 *note cgi: 16. 模块中被移
     除。 这些函数自 Python 3.2 或更早就已被弃用。 它们应改为从
     ‘urllib.parse’ 和 ‘html’ 模块导入。

   * ‘filemode’ 函数已从 *note tarfile: 102. 模块中被移除。 该函数未被写
     入文档，自 Python 3.3 起就已弃用。

   * *note XMLParser: 253. 构造器不再接受 `html' 参数。 它从来没有任何作
     用并在 Python 3.4 中已被弃用。 所有其他形参现在都是 *note
     仅限关键字参数: 2ad.。 （由 Serhiy Storchaka 在 bpo-29209(6) 中贡献
     。）

   * *note XMLParser: 253. 的 ‘doctype()’ 方法已被移除。 （由 Serhiy
     Storchaka 在 bpo-29209(7) 中贡献。）

   * "unicode_internal" 编解码器已被移除。 （由 Inada Naoki 在
     bpo-36297(8) 中贡献。）

   * *note sqlite3: f3. 模块的 ‘Cache’ 和 ‘Statement’ 对象已不再公开给用
     户。 （由 Aviv Palivoda 在 bpo-30262(9) 中贡献。）

   * *note fileinput.input(): 2ae. 和 *note fileinput.FileInput(): 27f.
     中自 Python 3.6 起就已被忽略并弃用的 ‘bufsize’ 关键字参数已被移除。
     由 Matthias Bussonnier 在 bpo-36952(10) 中贡献。）

   * 在 Python 3.7 中弃用的函数 ‘sys.set_coroutine_wrapper()’ 和
     ‘sys.get_coroutine_wrapper()’ 已被移除。 （由 Matthias Bussonnier 在
     bpo-36933(11) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36952

   (2) https://bugs.python.org/issue35471

   (3) https://bugs.python.org/issue35345

   (4) https://bugs.python.org/issue36895

   (5) https://bugs.python.org/issue25427

   (6) https://bugs.python.org/issue29209

   (7) https://bugs.python.org/issue29209

   (8) https://bugs.python.org/issue36297

   (9) https://bugs.python.org/issue30262

   (10) https://bugs.python.org/issue36952

   (11) https://bugs.python.org/issue36933


File: python.info,  Node: 移植到 Python 3 8,  Next: Python 3 8 1 中的重要变化,  Prev: API 与特性的移除,  Up: Python 3 8 有什么新变化

1.1.10 移植到 Python 3.8
------------------------

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

* Menu:

* Python 行为的改变::
* Python API 的变化::
* C API 的变化::
* CPython 字节码的改变::
* 演示和工具::


File: python.info,  Node: Python 行为的改变,  Next: Python API 的变化,  Up: 移植到 Python 3 8

1.1.10.1 Python 行为的改变
..........................

   * yield 表达式（包括 ‘yield’ 和 ‘yield from’ 子句）现在不允许在推导式
     和生成器表达式中使用（但 ‘for’ 子句最左边的可迭代对象表达式除外）。
     （由 Serhiy Storchaka 在 bpo-10544(1) 中贡献。）

   * 当标识号检测 (‘is’ 和 ‘is not’) 与特定类型的字面值 (例如字符串和数
     字) 一同使用时编译器现在会产生 *note SyntaxWarning: 192.。 这在
     CPython 中通常是可行的，但并不被语言定义所保证。 该警告会建议用户改
     用相等性检测 (‘==’ and ‘!=’)。 （由 Serhiy Storchaka 在
     bpo-34850(2) 中贡献。）

   * CPython 解释器在某些情况下可以忽略异常。 在 Python 3.8 中这种情况会
     更少发生。 特别地，从类型字典获取属性时引发的异常不会再被忽略。 （
     由 Serhiy Storchaka 在 bpo-35459(3) 中贡献。）

   * 从内置类型 *note bool: 184, *note int: 185, *note float: 188, *note
     complex: 18a. 和标准库的一些类中移除了 ‘__str__’ 实现。 它们现在会
     从 *note object: 2b1. 继承 ‘__str__()’。 作为结果，在这些类的子类中
     定义 ‘__repr__()’ 方法将会影响它们的字符串表示。 （由 Serhiy
     Storchaka 在 bpo-36793(4) 中贡献。）

   * 在 AIX 上，*note sys.platform: 2b2. 将不再包含主要版本号。 它将总是
     ‘'aix'’ 而不再是 ‘'aix3'’ ..  ‘'aix7'’。 由于较旧的 Python 版本会包
     含该版本号，因此推荐总是使用 ‘sys.platform.startswith('aix')’。 （
     由 M. Felt 在 bpo-36588(5) 中贡献。）

   * 现在 *note PyEval_AcquireLock(): 2b3. 和 *note
     PyEval_AcquireThread(): 2b4. 如果当解释器终结化时被调用将会终结当前
     线程，以使它们与 *note PyEval_RestoreThread(): 2b5, *note
     Py_END_ALLOW_THREADS(): 2b6. 以及 *note PyGILState_Ensure(): 2b7. 保
     持一致。 如果不想要这样的行为，请通过检测 ‘_Py_IsFinalizing()’ 或
     ‘sys.is_finalizing()’ 来保护该调用。 （由 Joannah Nanjekye 在
     bpo-36475(6) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10544

   (2) https://bugs.python.org/issue34850

   (3) https://bugs.python.org/issue35459

   (4) https://bugs.python.org/issue36793

   (5) https://bugs.python.org/issue36588

   (6) https://bugs.python.org/issue36475


File: python.info,  Node: Python API 的变化,  Next: C API 的变化,  Prev: Python 行为的改变,  Up: 移植到 Python 3 8

1.1.10.2 Python API 的变化
..........................

   * 在 Windows 上 *note os.getcwdb(): 2b9. 函数现在会使用 UTF-8 编码格
     式而不是 ANSI 代码页：请参看 PEP 529(1) 了解具体原因。 该函数在
     Windows 上不再被弃用。 （由 Victor Stinner 在 bpo-37412(2) 中贡献。
     ）

   * 现在 *note subprocess.Popen: 2ba. 在某些情况下会使用 *note
     os.posix_spawn(): 258. 以获得更好的性能。 在适用于 Linux 的 Windows
     子系统和 QEMU 用户模拟器上，使用 *note os.posix_spawn(): 258. 的
     ‘Popen’ 构造器不会再因为“找不到程序”这样的错误引发异常。 而是让子进
     程失败并返回一个非零的 ‘returncode’。 （由 Joannah Nanjekye 和
     Victor Stinner 在 bpo-35537(3) 中贡献。）

   * The `preexec_fn' argument of * *note subprocess.Popen: 2ba. is no
     longer compatible with subinterpreters.  The use of the parameter
     in a subinterpreter now raises *note RuntimeError: 2bb.
     (Contributed by Eric Snow in bpo-34651(4), modified by Christian
     Heimes in bpo-37951(5).)

   * ‘imap.IMAP4.logout()’ 方法不会再静默地忽略任意异常。 （由 Victor
     Stinner 在 bpo-36348(6) 中贡献。）

   * 函数 ‘platform.popen()’ 已被移除，它自 Python 3.3 起就已被弃用：请
     改用 *note os.popen(): 2aa.。 （由 Victor Stinner 在 bpo-35345(7) 中
     贡献。）

   * 当传入多模数据时 *note statistics.mode(): 2bc. 函数不会再引发异常。
     它将改为返回在输入数据中遇到的第一个模式。 （由 Raymond Hettinger 在
     bpo-35892(8) 中贡献。）

   * *note tkinter.ttk.Treeview: 2bd. 类的 *note selection(): 2be. 方法
     不再接受参数。 带参数调用该方法来改变选择在 Python 3.6 中已弃用。 请
     使用专门方法例如 *note selection_set(): 2bf. 来改变选择。 （由
     Serhiy Storchaka 在 bpo-31508(9) 中贡献。）

   * *note xml.dom.minidom: 136. 的 ‘writexml()’, ‘toxml()’ 和
     ‘toprettyxml()’ 方法以及 ‘xml.etree’ 的 ‘write()’ 方法现在会保留用
     户指定的属性顺序。 （由 Diego Rojas 和 Raymond Hettinger 在
     bpo-34160(10) 中贡献。）

   * 附带 ‘'r'’ 旗标打开的 *note dbm.dumb: 33. 数据库现在将是只读的。 如
     果数据库不存在，附带 ‘'r'’ 和 ‘'w'’ 旗标的 *note dbm.dumb.open():
     2c0. 不会再创建数据库。 （由 Serhiy Storchaka 在 bpo-32749(11) 中贡
     献。）

   * 在 *note XMLParser: 253. 的子类中定义的 ‘doctype()’ 方法将不会再被
     调用，并将导致发出 *note RuntimeWarning: 2c1. 而不是 *note
     DeprecationWarning: 279.。 请在目标上定义 *note doctype(): 2c2. 方
     法来处理 XML doctype 声明。 （由 Serhiy Storchaka 在 bpo-29209(12)
     中贡献。）

   * 现在当自定义元类未在传给 ‘type.__new__’ 的命名空间中提供
     ‘__classcell__’ 入口时将引发 *note RuntimeError: 2bb.。 在 Python
     3.6–3.7 中是则是引发 *note DeprecationWarning: 279.。 （由 Serhiy
     Storchaka 在 bpo-23722(13) 中贡献。）

   * ‘cProfile.Profile’ 类现在可被用作上下文管理器。 （由 Scott
     Sanderson 在 bpo-29235(14) 中贡献。）

   * *note shutil.copyfile(): 259, *note shutil.copy(): 25a, *note
     shutil.copy2(): 25b, *note shutil.copytree(): 21b. 和 *note
     shutil.move(): 25c. 会使用平台专属的 "fast-copy" 系统调用（参见
     *note 依赖于具体平台的高效拷贝操作: 25f. 一节）。

   * *note shutil.copyfile(): 259. 在 Windows 上的默认缓冲区大小从 16
     KiB 改为 1 MiB。

   * ‘PyGC_Head’ 结构已被完全改变。 所有接触到该结构的代码都应当被重写。
     （参见 bpo-33597(15)。）

   * *note PyInterpreterState: 2c3. 结构已被移入 "internal" 头文件（特别
     是 Include/internal/pycore_pystate.h）。 不透明的
     ‘PyInterpreterState’ 作为仅有 API（以及稳定版 ABI）的一部分仍然可用
     。 文档指明该结构的任何字段都不是公有的，因此我们希望没人在使用它们
     。 但是，如果你确实依赖其中某一个或更多个私有字段并且没有其他替代选
     项，则请开一个 BPO 问题。 我们将尽力帮助你进行调整（可能包括向公有
     API 添加访问器函数）。 （参见 bpo-35886(16)。）

   * 现在所有平台下的 *note mmap.flush(): 2c4. 方法都会在成功时返回
     ‘None’ 并在错误时引发异常。 之前它的行为取决于具体平台： Windows 下
     会在成功时返回非零值；在失败时返回零。 Unix 下会在成功时返回零；在
     失败时引发错误。 （由 Berker Peksag 在 bpo-2122(17) 中贡献。）

   * *note xml.dom.minidom: 136. 和 *note xml.sax: 13c. 模块默认将不再处
     理外部实体。 （由 Christian Heimes 在 bpo-17239(18) 中贡献。）

   * 从只读的 *note dbm: 32. 数据库 (*note dbm.dumb: 33, *note dbm.gnu:
     34. 或 *note dbm.ndbm: 35.) 删除键将会引发 ‘error’ (*note
     dbm.dumb.error: 2c5, *note dbm.gnu.error: 2c6. 或 *note
     dbm.ndbm.error: 2c7.) 而不是 *note KeyError: 2c8.。 （由 Xiang
     Zhang 在 bpo-33106(19) 中贡献。）

   * 简化了字面值的 AST。 所有常量将被表示为 ‘ast.Constant’ 的实例。 实
     例化旧类 ‘Num’, ‘Str’, ‘Bytes’, ‘NameConstant’ 和 ‘Ellipsis’ 都将返
     回 ‘Constant’ 的实例。 （由 Serhiy Storchaka 在 bpo-32892(20) 中贡
     献。）

   * *note expanduser(): 1ff. 在 Windows 上现在改用 ‘USERPROFILE’ 环境变
     量而不再使用 ‘HOME’，后者通常不会为一般用户账户设置。 （由 Anthony
     Sottile 在 bpo-36264(21) 中贡献。）

   * 异常 *note asyncio.CancelledError: 1a8. 现在继承自 *note
     BaseException: 1a9. 而不是 *note Exception: 1aa. 并且不再继承自
     *note concurrent.futures.CancelledError: 1ab.。 （由 Yury Selivanov
     在 bpo-32528(22) 中贡献。）

   * 当使用 *note asyncio.Task: 1ae. 的实例时，函数 *note
     asyncio.wait_for(): 289. 现在会正确地等待撤销。 在此之前当达到
     `timeout' 时，它会被撤销并立即返回。 （由 Elvis Pranskevichus 在
     bpo-32751(23) 中贡献。）

   * 当将 ’socket’ 作为 `name' 形参传入时，函数 *note
     asyncio.BaseTransport.get_extra_info(): 2c9. 现在会返回一个可安全使
     用的套接字对象。 （由 Yury Selivanov 在 bpo-37027(24) 中贡献。）

   * *note asyncio.BufferedProtocol: 2ca. 已经晋级为稳定 API。

   * 在 Windows 上对扩展模块的 DLL 依赖以及通过 *note ctypes: 2b. 加载的
     DLL 的解析现在将更为安全。 只有系统路径、包含相信 DLL 或 PYD 文件的
     路径以及通过 *note add_dll_directory(): 1c3. 添加的目录才会被作为加
     载时依赖的搜索位置。 特别地， ‘PATH’ 和当前工作目录将不再被使用，对
     它们的修改将不再对正常的 DLL 解析产生影响。 如果你的应用依赖于这些
     机制，你应当先检查 *note add_dll_directory(): 1c3.，如果它存在就用
     它在加载你的库时添加你的 DLL 目录。 请注意 Windows 7 用户还需要确保
     Windows 更新包 KB2533623 已安装（这一点也会由安装器进行验证）。 （
     由 Steve Dower 在 bpo-36085(25) 中贡献。）

   * 关联到 pgen 的头文件和函数在其被纯 Python 实现取代后已被移除。 （由
     Pablo Galindo 在 bpo-36623(26) 中贡献。）

   * *note types.CodeType: 199. 在构造器的第二个位置新增了一个形参
     (`posonlyargcount') 以支持在 PEP 570(27) 中定义的仅限位置参数。 第
     一个参数 (`argcount') 现在表示位置参数的总数量 (包括仅限位置参数)。
     *note types.CodeType: 199. 中新增的 ‘replace()’ 方法可用于让代码支
     持 future 特性。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0529

   (2) https://bugs.python.org/issue37412

   (3) https://bugs.python.org/issue35537

   (4) https://bugs.python.org/issue34651

   (5) https://bugs.python.org/issue37951

   (6) https://bugs.python.org/issue36348

   (7) https://bugs.python.org/issue35345

   (8) https://bugs.python.org/issue35892

   (9) https://bugs.python.org/issue31508

   (10) https://bugs.python.org/issue34160

   (11) https://bugs.python.org/issue32749

   (12) https://bugs.python.org/issue29209

   (13) https://bugs.python.org/issue23722

   (14) https://bugs.python.org/issue29235

   (15) https://bugs.python.org/issue33597

   (16) https://bugs.python.org/issue35886

   (17) https://bugs.python.org/issue2122

   (18) https://bugs.python.org/issue17239

   (19) https://bugs.python.org/issue33106

   (20) https://bugs.python.org/issue32892

   (21) https://bugs.python.org/issue36264

   (22) https://bugs.python.org/issue32528

   (23) https://bugs.python.org/issue32751

   (24) https://bugs.python.org/issue37027

   (25) https://bugs.python.org/issue36085

   (26) https://bugs.python.org/issue36623

   (27) https://www.python.org/dev/peps/pep-0570


File: python.info,  Node: C API 的变化,  Next: CPython 字节码的改变,  Prev: Python API 的变化,  Up: 移植到 Python 3 8

1.1.10.3 C API 的变化
.....................

   * *note PyCompilerFlags: 2cd. 结构体添加了一个新的
     `cf_feature_version' 字段。 它应当被初始化为 ‘PY_MINOR_VERSION’。 该
     字段默认会被忽略，当且仅当 ‘PyCF_ONLY_AST’ 在 `cf_flags' 中设置旗标
     时才会被使用。 （由 Guido van Rossum 在 bpo-35766(1) 中贡献。）

   * ‘PyEval_ReInitThreads()’ 函数已从 C API 中移除。 它不应当被显式地调
     用；请改用 *note PyOS_AfterFork_Child(): 2ce.。 （由 Victor Stinner
     在 bpo-36728(2) 中贡献。）

   * 在 Unix 上，C 扩展不会再被链接到 libpython，但 Android 和 Cygwin 例
     外。 当 Python 被嵌入时，‘libpython’ 不可使用 ‘RTLD_LOCAL’ 加载，而
     要改用 ‘RTLD_GLOBAL’。 之前使用 ‘RTLD_LOCAL’ 已经不可能加载未链接到
     ‘libpython’ 的 C 扩展了，例如通过 ‘Modules/Setup’ 的 ‘*shared*’ 部
     分构建的标准库 C 扩展。 （由 Victor Stinner 在 bpo-21536(3) 中贡献
     。）

   * 在解析或构建值时（例如 *note PyArg_ParseTuple(): 26b, *note
     Py_BuildValue(): 2cf, *note PyObject_CallFunction(): 2d0. 等等）使
     用形如 ‘#’ 的格式而不定义 ‘PY_SSIZE_T_CLEAN’ 现在将会引发
     ‘DeprecationWarning’。 它将在 3.10 或 4.0 中被移除。 请参阅 *note
     解析参数并构建值变量: 2d1. 了解详情。 （由 Inada Naoki 在
     bpo-36381(4) 中贡献。）

   * 堆分配类型的实例（例如使用 *note PyType_FromSpec(): 2d2. 创建的实例
     ）会保存一个对其类型对象的引用。 提升这些类型对象引用计数的操作已从
     *note PyType_GenericAlloc(): 271. 移至更低层级的函数 *note
     PyObject_Init(): 270. 和 ‘PyObject_INIT()’。 这使用通过This makes
     types created through *note PyType_FromSpec(): 2d2. 所创建类型的行
     为与管理代码中的其他类保持一致。

     静态分配类型将不受影响。

     在大部分情况下，这应该都不会有附带影响。 但是，在分配实例后手动提升
     引用计数的类型（也许是为了绕过漏洞）现在可能永远不会被销毁。 要避免
     这种情况，这些类需要在实例撤销分配期间在类型对象上调用 Py_DECREF。

     要正确地将这些类型移植到 3.8，请应用以下修改：

        * 在分配实例之后在类型对象上移除 *note Py_INCREF: 266. —— 如果有
          的话。 这可以发生在调用 *note PyObject_New(): 2d3, *note
          PyObject_NewVar(): 2d4, *note PyObject_GC_New(): 2d5, *note
          PyObject_GC_NewVar(): 2d6. 或任何其他使用 *note
          PyObject_Init(): 270. 或 ‘PyObject_INIT()’ 的自定义分配器之后
          。

          示例:

               static foo_struct *
               foo_new(PyObject *type) {
                   foo_struct *foo = PyObject_GC_New(foo_struct, (PyTypeObject *) type);
                   if (foo == NULL)
                       return NULL;
               #if PY_VERSION_HEX < 0x03080000
                   // Workaround for Python issue 35810; no longer necessary in Python 3.8
                   PY_INCREF(type)
               #endif
                   return foo;
               }

        * 确保所有堆分配类型的自定义 ‘tp_dealloc’ 函数会减少类型的引用计
          数。

          示例:

               static void
               foo_dealloc(foo_struct *instance) {
                   PyObject *type = Py_TYPE(instance);
                   PyObject_GC_Del(instance);
               #if PY_VERSION_HEX >= 0x03080000
                   // This was not needed before Python 3.8 (Python issue 35810)
                   Py_DECREF(type);
               #endif
               }

     （由 Eddie Elizondo 在 bpo-35810(5) 中贡献。）

   * ‘Py_DEPRECATED()’ 宏已经针对 MSVC 实现。 这个宏现在必须放在符号名称
     之前。

     示例:

          Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);

     （由 Zackery Spytz 在 bpo-33407(6) 中贡献。）

   * 解释器将不再假装支持跨发布版本的扩展类型二进制兼容性。 由第三方扩展
     模块所导出的 *note PyTypeObject: 2d7. 应该具有当前 Python 版本所要
     求的所有空位，包括 *note tp_finalize: 2d8. (*note
     Py_TPFLAGS_HAVE_FINALIZE: 2d9. 不会再在读取 *note tp_finalize: 2d8.
     之前被检查)。

     （由 Antoine Pitrou 在 bpo-32388(7) 中贡献。）

   * 函数 ‘PyNode_AddChild()’ 和 ‘PyParser_AddToken()’ 现在接受两个额外
     的 ‘int’ 参数 `end_lineno' 和 `end_col_offset'。

   * 允许 MinGW 工具直接链接到 ‘python38.dll’ 的 ‘libpython38.a’ 文件已
     不再包含于标准的 Windows 分发包中。 如果你需要此文件，可使用
     ‘gendef’ 和 ‘dlltool’ 工具来生成它，这些工具是 MinGW binutils 包的
     一部分：

          gendef - python38.dll > tmp.def
          dlltool --dllname python38.dll --def tmp.def --output-lib libpython38.a

     已安装的 ‘pythonXY.dll’ 所在位置将取决于安装选项以及 Windows 的版本
     和语言。 请参阅 *note 在Windows上使用 Python: 2da. 了解更多信息。 该
     结果库应当放在与 ‘pythonXY.lib’ 相同的目录下，这通常是你的 Python 安
     装路径下的 ‘libs’ 目录。

     （由 Steve Dower 在 bpo-37351(8) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35766

   (2) https://bugs.python.org/issue36728

   (3) https://bugs.python.org/issue21536

   (4) https://bugs.python.org/issue36381

   (5) https://bugs.python.org/issue35810

   (6) https://bugs.python.org/issue33407

   (7) https://bugs.python.org/issue32388

   (8) https://bugs.python.org/issue37351


File: python.info,  Node: CPython 字节码的改变,  Next: 演示和工具,  Prev: C API 的变化,  Up: 移植到 Python 3 8

1.1.10.4 CPython 字节码的改变
.............................

   * 解释器循环已通过将块堆栈展开逻辑移入编译器获得了简化。 编译器现在会
     发出显式指令来调整值堆栈并为 *note break: 2dc, *note continue: 182.
     和 *note return: 191. 调用清除代码。

     移除了操作码 ‘BREAK_LOOP’, ‘CONTINUE_LOOP’, ‘SETUP_LOOP’ 和
     ‘SETUP_EXCEPT’。 添加了新的操作码 *note ROT_FOUR: 2dd, *note
     BEGIN_FINALLY: 2de, *note CALL_FINALLY: 2df. 和 *note POP_FINALLY:
     2e0.。 修改了 *note END_FINALLY: 2e1. 和 *note WITH_CLEANUP_START:
     2e2. 的行为。

     （由 Mark Shannon, Antoine Pitrou 和 Serhiy Storchaka 在
     bpo-17611(1) 中贡献。）

   * 添加了新的操作码 *note END_ASYNC_FOR: 2e3. 用于处理当等待 *note
     async for: 2e4. 循环的下一项时引发的异常。 （由 Serhiy Storchaka 在
     bpo-33041(2) 中贡献。）

   * *note MAP_ADD: 2e5. 现在会预期值为栈的第一个元素而键为第二个元素。
     作出此改变以使得字典推导式能如 PEP 572(3) 所提议的那样，键总是会在
     值之前被求值。 （由 Jörn Heissler 在 bpo-35224(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17611

   (2) https://bugs.python.org/issue33041

   (3) https://www.python.org/dev/peps/pep-0572

   (4) https://bugs.python.org/issue35224


File: python.info,  Node: 演示和工具,  Prev: CPython 字节码的改变,  Up: 移植到 Python 3 8

1.1.10.5 演示和工具
...................

添加了一个检测脚本用于对访问变量的不同方式进行计时:
‘Tools/scripts/var_access_benchmark.py’。 （由 Raymond Hettinger 在
bpo-35884(1) 中贡献。）

以下是自 Python 3.3 以来性能提升情况的总结:

     Python version                       3.3     3.4     3.5     3.6     3.7     3.8
     --------------                       ---     ---     ---     ---     ---     ---

     Variable and attribute read access:
         read_local                       4.0     7.1     7.1     5.4     5.1     3.9
         read_nonlocal                    5.3     7.1     8.1     5.8     5.4     4.4
         read_global                     13.3    15.5    19.0    14.3    13.6     7.6
         read_builtin                    20.0    21.1    21.6    18.5    19.0     7.5
         read_classvar_from_class        20.5    25.6    26.5    20.7    19.5    18.4
         read_classvar_from_instance     18.5    22.8    23.5    18.8    17.1    16.4
         read_instancevar                26.8    32.4    33.1    28.0    26.3    25.4
         read_instancevar_slots          23.7    27.8    31.3    20.8    20.8    20.2
         read_namedtuple                 68.5    73.8    57.5    45.0    46.8    18.4
         read_boundmethod                29.8    37.6    37.9    29.6    26.9    27.7

     Variable and attribute write access:
         write_local                      4.6     8.7     9.3     5.5     5.3     4.3
         write_nonlocal                   7.3    10.5    11.1     5.6     5.5     4.7
         write_global                    15.9    19.7    21.2    18.0    18.0    15.8
         write_classvar                  81.9    92.9    96.0   104.6   102.1    39.2
         write_instancevar               36.4    44.6    45.8    40.0    38.9    35.5
         write_instancevar_slots         28.7    35.6    36.1    27.3    26.6    25.7

     Data structure read access:
         read_list                       19.2    24.2    24.5    20.8    20.8    19.0
         read_deque                      19.9    24.7    25.5    20.2    20.6    19.8
         read_dict                       19.7    24.3    25.7    22.3    23.0    21.0
         read_strdict                    17.9    22.6    24.3    19.5    21.2    18.9

     Data structure write access:
         write_list                      21.2    27.1    28.5    22.5    21.6    20.0
         write_deque                     23.8    28.7    30.1    22.7    21.8    23.5
         write_dict                      25.9    31.4    33.3    29.3    29.2    24.7
         write_strdict                   22.9    28.4    29.9    27.5    25.2    23.1

     Stack (or queue) operations:
         list_append_pop                144.2    93.4   112.7    75.4    74.2    50.8
         deque_append_pop                30.4    43.5    57.0    49.4    49.2    42.5
         deque_append_popleft            30.8    43.7    57.3    49.7    49.7    42.8

     Timing loop:
         loop_overhead                    0.3     0.5     0.6     0.4     0.3     0.3

基准测试是在 Intel® Core™ i7-4960HQ 处理器(2) 上运行从 python.org(3) 获
取的 macOS 64 位版得到的数据。 基准测试脚本显示时间以纳秒为单位。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35884

   (2) 
https://ark.intel.com/content/www/us/en/ark/products/76088/intel-core-i7-4960hq-processor-6m-cache-up-to-3-80-ghz.html

   (3) https://www.python.org/downloads/mac-osx/


File: python.info,  Node: Python 3 8 1 中的重要变化,  Next: Python 3 8 2 中的重要变化,  Prev: 移植到 Python 3 8,  Up: Python 3 8 有什么新变化

1.1.11 Python 3.8.1 中的重要变化
--------------------------------

出于重要的安全性考量，*note asyncio.loop.create_datagram_endpoint():
2e8. 的 `reuse_address' 形参不再被支持。 这是由 UDP 中的套接字选项
‘SO_REUSEADDR’ 的行为导致的。 更多细节请参阅
‘loop.create_datagram_endpoint()’ 的文档。 （由 Kyle Stanley, Antoine
Pitrou 和 Yury Selivanov 在 bpo-37228(1) 中贡献。。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37228


File: python.info,  Node: Python 3 8 2 中的重要变化,  Next: Python 3 8 3 中的重要变化,  Prev: Python 3 8 1 中的重要变化,  Up: Python 3 8 有什么新变化

1.1.12 Python 3.8.2 中的重要变化
--------------------------------

修复了 *note shutil.copytree(): 21b. 的 ‘ignore’ 回调中的回归问题。 现在
该参数的类型已改回 str 和 List[str]。 （由 Manuel Barkhau 和 Giampaolo
Rodola 在 bpo-39390(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39390


File: python.info,  Node: Python 3 8 3 中的重要变化,  Next: Python 3 8 8 中的重要变化,  Prev: Python 3 8 2 中的重要变化,  Up: Python 3 8 有什么新变化

1.1.13 Python 3.8.3 中的重要变化
--------------------------------

*note __future__: 0. 模块中的 future 旗标常量值已获得更新以防止与
compiler 旗标相冲突。 在之前版本中 ‘PyCF_ALLOW_TOP_LEVEL_AWAIT’ 与
‘CO_FUTURE_DIVISION’ 存在冲突。 （由 Batuhan Taskaya 在 bpo-39562(1) 中
贡献）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39562


File: python.info,  Node: Python 3 8 8 中的重要变化,  Next: Python 3 8 9 中的重要变化,  Prev: Python 3 8 3 中的重要变化,  Up: Python 3 8 有什么新变化

1.1.14 Python 3.8.8 中的重要变化
--------------------------------

早先的 Python 版本允许使用 ‘;’ 和 ‘&’ 作为 *note
urllib.parse.parse_qs(): 2ec. 和 *note urllib.parse.parse_qsl(): 2ed. 中
query 形参的分隔键。 出于安全考虑，也为了遵循更新的 W3C 推荐设置，这已被
改为只允许单个分隔键，默认为 ‘&’。 这一改变还会影响 *note cgi.parse():
2ee. 和 *note cgi.parse_multipart(): 2ef. 因为它们在内部使用了受影响的函
数。 要了解更多细节，请查看它们各自的文档。 （由 Adam Goldschmidt,
Senthil Kumaran 和 Ken Jin 在 bpo-42967(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42967


File: python.info,  Node: Python 3 8 9 中的重要变化,  Next: Python 3 8 10 中的重要变化,  Prev: Python 3 8 8 中的重要变化,  Up: Python 3 8 有什么新变化

1.1.15 Python 3.8.9 中的重要变化
--------------------------------

新的安全修正将A security fix alters the *note ftplib.FTP: 2f1. 的行为改
成当设置被动数据通道时不信任远程服务器所发送的 IPv4 地址。 我们会改为重
用 FTP 服务器的 IP 地址。 对于需要原先行为的不常见代码，请在你的 FTP 实
例上设置 ‘trust_server_pasv_ipv4_address’ 属性为 ‘True’。 (参见
bpo-43285(1))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43285


File: python.info,  Node: Python 3 8 10 中的重要变化,  Next: Python 3 8 10 中的重要变化<2>,  Prev: Python 3 8 9 中的重要变化,  Up: Python 3 8 有什么新变化

1.1.16 Python 3.8.10 中的重要变化
---------------------------------

* Menu:

* macOS 11.0 (Big Sur) 与 Apple Silicon Mac 支持: macOS 11 0 Big Sur 与 Apple Silicon Mac 支持.


File: python.info,  Node: macOS 11 0 Big Sur 与 Apple Silicon Mac 支持,  Up: Python 3 8 10 中的重要变化

1.1.16.1 macOS 11.0 (Big Sur) 与 Apple Silicon Mac 支持
.......................................................

As of 3.8.10, Python now supports building and running on macOS 11 (Big
Sur) and on Apple Silicon Macs (based on the ‘ARM64’ architecture).  A
new universal build variant, ‘universal2’, is now available to natively
support both ‘ARM64’ and ‘Intel 64’ in one set of executables.  Note
that support for "weaklinking", building binaries targeted for newer
versions of macOS that will also run correctly on older versions by
testing at runtime for missing features, is not included in this
backport from Python 3.9; to support a range of macOS versions, continue
to target for and build on the oldest version in the range.

(Originally contributed by Ronald Oussoren and Lawrence D’Anna in
bpo-41100(1), with fixes by FX Coudert and Eli Rykoff, and backported to
3.8 by Maxime Bélanger and Ned Deily)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41100


File: python.info,  Node: Python 3 8 10 中的重要变化<2>,  Next: Python 3 8 12 中的重要变化,  Prev: Python 3 8 10 中的重要变化,  Up: Python 3 8 有什么新变化

1.1.17 Python 3.8.10 中的重要变化
---------------------------------

* Menu:

* urllib.parse: urllib parse.


File: python.info,  Node: urllib parse,  Up: Python 3 8 10 中的重要变化<2>

1.1.17.1 urllib.parse
.....................

在 URL 部分中存在换行符或制表符可导致某些形式的攻击。 跟随更新了 RFC
3986(1) 的 WHATWG 规格描述，ASCII 换行 ‘\n’, ‘\r’ 和制表 ‘\t’ 等字符会被
*note urllib.parse: 120. 的解析器从 URL 中移除以防止此类攻击。 移除字符
操作是由新的模块级变量 ‘urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE’ 来控制
的。 (参见 bpo-43882(2))

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3986.html

   (2) https://bugs.python.org/issue43882


File: python.info,  Node: Python 3 8 12 中的重要变化,  Prev: Python 3 8 10 中的重要变化<2>,  Up: Python 3 8 有什么新变化

1.1.18 Python 3.8.12 中的重要变化
---------------------------------

* Menu:

* Python API 的变化: Python API 的变化<2>.


File: python.info,  Node: Python API 的变化<2>,  Up: Python 3 8 12 中的重要变化

1.1.18.1 Python API 的变化
..........................

Starting with Python 3.8.12 the *note ipaddress: a3. module no longer
accepts any leading zeros in IPv4 address strings.  Leading zeros are
ambiguous and interpreted as octal notation by some libraries.  For
example the legacy function *note socket.inet_aton(): 2f8. treats
leading zeros as octal notation.  glibc implementation of modern *note
inet_pton(): 2f9. does not accept any leading zeros.

(Originally contributed by Christian Heimes in bpo-36384(1), and
backported to 3.8 by Achraf Merzouki)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36384


File: python.info,  Node: Python 3 7 有什么新变化,  Next: Python 3 6 有什么新变化,  Prev: Python 3 8 有什么新变化,  Up: Python的新变化

1.2 Python 3.7 有什么新变化
===========================


编者: Elvis Pranskevichus <<elvis@magic.io>>

本文解释了 Python 3.7 相比 3.6 的新增特性。Python 3.7 于 2018 年 6 月 27
日发布。完整的详情可参阅 *note 更新日志: 14d.。

* Menu:

* 摘要 - 发布重点: 摘要 - 发布重点<2>.
* 新的特性: 新的特性<2>.
* 其他语言特性修改: 其他语言特性修改<2>.
* 新增模块: 新增模块<2>.
* 改进的模块: 改进的模块<2>.
* C API 的改变::
* 构建的改变::
* 性能优化: 性能优化<2>.
* 其他 CPython 实现的改变::
* 已弃用的 Python 行为::
* 已弃用的 Python 模块、函数和方法::
* 已弃用的 C API 函数和类型::
* 平台支持的移除::
* API 与特性的移除: API 与特性的移除<2>.
* 移除的模块::
* Windows 专属的改变::
* 移植到 Python 3.7: 移植到 Python 3 7.
* Python 3.7.1 中的重要变化: Python 3 7 1 中的重要变化.
* Python 3.7.2 中的重要变化: Python 3 7 2 中的重要变化.
* Python 3.7.6 中的重要变化: Python 3 7 6 中的重要变化.
* Python 3.7.10 中的重要变化: Python 3 7 10 中的重要变化.


File: python.info,  Node: 摘要 - 发布重点<2>,  Next: 新的特性<2>,  Up: Python 3 7 有什么新变化

1.2.1 摘要 - 发布重点
---------------------

新的语法特性：

   * *note PEP 563: 2fd.，类型标注延迟求值。

向后不兼容的语法更改：

   * *note async: 1a3. 和 *note await: 1a4. 现在是保留的关键字。

新的库模块：

   * *note contextvars: 25.: *note PEP 567 – 上下文变量: 2fe.

   * *note dataclasses: 30.: *note PEP 557 – 数据类: 2ff.

   * *note importlib.resources: 300.

新的内置特性：

   * *note PEP 553: 301, 新的 *note breakpoint(): 302. 函数。

对 Python 数据模型的改进：

   * *note PEP 562: 303, 自定义可访问的模块属性。

   * *note PEP 560: 304, typing模块和泛型类型的核心支持。

   * *note dict: 305. 对象会保持插入时的顺序这个特性 正式宣布(1) 成为
     Python 语言官方规范的一部分。

标准库中的重大改进：

   * *note asyncio: a. 模块添加了新的功能，重大改进请参阅 *note
     可用性与性能提升: 306.。

   * *note time: 10b. 模块现在提供 *note 纳秒级精度函数: 307. 的支持。

CPython 实现的改进：

   * 避免使用 ASCII 作为默认的文本编码：

        * *note PEP 538: 308.，传统 C 区域强制转换

        * *note PEP 540: 309.，强制 UTF-8 运行时模式

   * *note PEP 552: 30a.，确定性的 .pyc 文件

   * *note 新的开发运行时模式: 30b.

   * *note PEP 565: 30c.，改进的 *note DeprecationWarning: 279. 处理

C API 的改进：

   * *note PEP 539: 30d.，用于线程本地存储的新 C API

文档的改进：

   * *note PEP 545: 30e, Python 文档翻译

   * 新的文档翻译：Japanese(2)，French(3) 和 Korean(4)。

此版本在诸多方面有显著的性能改进。*note 性能优化: 30f. 章节详细列出了它
们。

和之前的 Python 版本存在兼容性的更改列表，请参阅 *note 移植到 Python
3.7: 310. 章节。

   ---------- Footnotes ----------

   (1) 
https://mail.python.org/pipermail/python-dev/2017-December/151283.html

   (2) https://docs.python.org/ja/

   (3) https://docs.python.org/fr/

   (4) https://docs.python.org/ko/


File: python.info,  Node: 新的特性<2>,  Next: 其他语言特性修改<2>,  Prev: 摘要 - 发布重点<2>,  Up: Python 3 7 有什么新变化

1.2.2 新的特性
--------------

* Menu:

* PEP 563：延迟的标注求值::
* PEP 538; 传统 C 区域强制转换: PEP 538 传统 C 区域强制转换.
* PEP 540; 强制 UTF-8 运行时模式: PEP 540 强制 UTF-8 运行时模式.
* PEP 553; 内置的 breakpoint(): PEP 553 内置的 breakpoint.
* PEP 539; 用于线程局部存储的新 C API: PEP 539 用于线程局部存储的新 C API.
* PEP 562; 定制对模块属性的访问: PEP 562 定制对模块属性的访问.
* PEP 564; 具有纳秒级精度的新时间函数: PEP 564 具有纳秒级精度的新时间函数.
* PEP 565; 在 __main__ 中显示 DeprecationWarning: PEP 565 在 __main__ 中显示 DeprecationWarning.
* PEP 560; 对 typing 模块和泛型类型的核心支持: PEP 560 对 typing 模块和泛型类型的核心支持.
* PEP 552; 基于哈希值的 .pyc 文件: PEP 552 基于哈希值的 pyc 文件.
* PEP 545; Python 文档翻译: PEP 545 Python 文档翻译.
* 开发运行时模式; -X dev: 开发运行时模式 -X dev.


File: python.info,  Node: PEP 563：延迟的标注求值,  Next: PEP 538 传统 C 区域强制转换,  Up: 新的特性<2>

1.2.2.1 PEP 563：延迟的标注求值
...............................

随着 PEP 3107(1) 加入标注功能并在 PEP 526(2) 进一步细化，Python 中类型提
示的出现揭示了两个明显的可用性问题：

   * 标注只能使用在当前作用域中已经存在的名称，也就是说，它们不支持任何
     形式的前向引用；而且——

   * 标注源码对 Python 程序的启动时间有不利的影响。

这两个问题都可以通过延迟标注求值来解决。在定义标注的时候，编译器并不会编
译执行相应表达式的代码，而是保存与相应表达式的 AST 等价的字符串形式。如
果有需要，标注可以在运行时使用 *note typing.get_type_hints(): 313. 进行
解析。在不需要这种解析的通常情况下，标注的存储成本更低（因为解析器只需处
理较短的字符串）且启动时间更短。

在可用性方面，标注现在支持向前引用，以使以下句法有效:

     class C:
         @classmethod
         def from_string(cls, source: str) -> C:
             ...

         def validate_b(self, obj: B) -> bool:
             ...

     class B:
         ...

由于此修改会破坏兼容性，在 Python 3.7 中此种新的行为需要在每个模块层级上
使用 *note __future__: 0. 导入来启用:

     from __future__ import annotations

它将在 Python 3.10 中成为默认行为。

参见
....

PEP 563(3) – 延迟的标注求值

     PEP 由 Łukasz Langa 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3107

   (2) https://www.python.org/dev/peps/pep-0526

   (3) https://www.python.org/dev/peps/pep-0563


File: python.info,  Node: PEP 538 传统 C 区域强制转换,  Next: PEP 540 强制 UTF-8 运行时模式,  Prev: PEP 563：延迟的标注求值,  Up: 新的特性<2>

1.2.2.2 PEP 538: 传统 C 区域强制转换
....................................

Python 3 系列有一个持续的挑战就是为处理 7 比特位 ASCII 文本的假定编码确
定合理的默认策略，目前的设定是在非 Windows 平台上使用默认的 C 或 POSIX 区
域设置。

PEP 538(1) 更新了默认的解释器命令行接口，以自动将上述区域强制转换为可用
的基于 UTF-8 的区域，具体描述可参见有关新增环境变量 *note
PYTHONCOERCECLOCALE: 315. 的文档。 以这种方式自动设置 ‘LC_CTYPE’ 意味着
核心解释器和能感知区域的 C 扩展 (例如 *note readline: df.) 都将会假定
UTF-8 已被用作默认的文本编码，而不再是 ASCII。

PEP 11(2) 中的平台支持定义也已被更新以限制完整文本处理支持适当配置的基于
非 ASCII 的语言区域。

作为此更改的一部分，当使用任何已定义的强制转换目标区域时 (目前为
‘C.UTF-8’, ‘C.utf8’ 和 ‘UTF-8’) *note stdin: 316. 和 *note stdout: 317.
默认的处理器现在将为 ‘surrogateescape’ (而不是 ‘strict’)。 而无论是什么
区域，*note stderr: 318. 默认的处理器仍为 ‘backslashreplace’。

默认情况下区域强制转换会静默进行，但为了辅助调试潜在的区域相关集成问题，
可以通过设置 ‘PYTHONCOERCECLOCALE=warn’ 来请求显式地启用警告信息（直接在
*note stderr: 318. 上发出）。 此设置还会使得 Python 运行时在核心解释器初
始化时如果传统 C 区域仍然处于激活状态时发出警告。

虽然 PEP 538(3) 的区域强制转换的好处在于它还会同时影响扩展模块 (例如 GNU
‘readline’) 以及子进程 (包括运行非 Python 应用和旧版本 Python 的子进程
)，但它也存在需要所运行系统必须存在适合的目标区域的缺点。 为了更好地处理
没有可用适合的目标区域的情况 (例如在 RHEL/CentOS 7 上就会出现此情况)，
Python 3.7 还实现了 *note PEP 540; 强制 UTF-8 运行时模式: 309.。

参见
....

PEP 538(4) – 强制转换传统 C 区域到基于 UTF-8 的区域

     PEP 由 Nick Coghlan 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0538

   (2) https://www.python.org/dev/peps/pep-0011

   (3) https://www.python.org/dev/peps/pep-0538

   (4) https://www.python.org/dev/peps/pep-0538


File: python.info,  Node: PEP 540 强制 UTF-8 运行时模式,  Next: PEP 553 内置的 breakpoint,  Prev: PEP 538 传统 C 区域强制转换,  Up: 新的特性<2>

1.2.2.3 PEP 540: 强制 UTF-8 运行时模式
......................................

新的 *note -X: 156. ‘utf8’ 命令行选项和 *note PYTHONUTF8: 31a. 环境变量
可被用来启用 CPython 的 `UTF-8 模式'。

当处于 UTF-8 模式时，CPython 会忽略区域设置，并默认使用 UTF-8 编码。 用
于 *note sys.stdin: 316. 和 *note sys.stdout: 317. 流的错误处理器将设置
为 ‘surrogateescape’。

强制 UTF-8 模式可被用来在嵌入的 Python 解释器中改变文本处理行为，而不会
改变嵌入方应用的区域设置。

PEP 540(1) 的 UTF-8 模式的好处是不必关心运行所在系统中有哪些可用区域即可
工作，但它也存在对扩展模块 (例如 GNU ‘readline’)、运行非 Python 应用的子
进程以及运行旧版本 Python 的子进程不起作用的缺点。 为了减小与这些组件通
信时破坏文本数据的风险，Python 3.7 还实现了 *note PEP 540; 强制 UTF-8
运行时模式: 309.)。

UTF-8 模式在语言区域为 ‘C’ 或 ‘POSIX’ 并且 PEP 538(2) 区域强制转换特性无
法将其修改为某种基于 UTF-8 的替代项时会被默认启用（无论修改失败是由于设
置了 ‘PYTHONCOERCECLOCALE=0’, ‘LC_ALL’ 还是由于缺少适合的目标区域）。

参见
....

PEP 540(3) – 增加了新的 UTF-8 模式

     PEP 由 Victor Stinner 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0540

   (2) https://www.python.org/dev/peps/pep-0538

   (3) https://www.python.org/dev/peps/pep-0540


File: python.info,  Node: PEP 553 内置的 breakpoint,  Next: PEP 539 用于线程局部存储的新 C API,  Prev: PEP 540 强制 UTF-8 运行时模式,  Up: 新的特性<2>

1.2.2.4 PEP 553: 内置的 ‘breakpoint()’
......................................

Python 3.7 包含了新的内置 *note breakpoint(): 302. 函数，作为一种简单方
便地进入 Python 调试器的方式。

内置 ‘breakpoint()’ 会调用 *note sys.breakpointhook(): 31c.。 在默认情况
下后者会导入 *note pdb: ca. 然后再调用 ‘pdb.set_trace()’，但是通过将
‘sys.breakpointhook()’ 绑定到你选定的函数，‘breakpoint()’ 可以进入任何调
试器。 此外，环境变量 *note PYTHONBREAKPOINT: 31d. 可被设置为你选定的调
试器的可调用对象。 设置 ‘PYTHONBREAKPOINT=0’ 会完全禁用内置
‘breakpoint()’。

参见
....

PEP 553(1) – 内置的 breakpoint()

     PEP 由 Barry Warsaw 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0553


File: python.info,  Node: PEP 539 用于线程局部存储的新 C API,  Next: PEP 562 定制对模块属性的访问,  Prev: PEP 553 内置的 breakpoint,  Up: 新的特性<2>

1.2.2.5 PEP 539: 用于线程局部存储的新 C API
...........................................

虽然 Python 已提供了用于线程局部存储支持的 C API；但原有的 *note
线程局部存储 (TLS) API: 31f. 使用 ‘int’ 来表示所有平台上的 TLS 密钥。 对
于官方支持的平台而言这通常不是问题，但这既不符合 POSIX 标准，也不具备任
何实际意义上的可移植性。

PEP 539(1) 通过向 CPython 提供了一个新的 *note 线程特定存储 (TSS) API:
320. 来改变这一点，它取代了原有的 CPython 内部 TLS API 的使用，并且原有
API 已弃用。 TSS API 使用一种新类型 *note Py_tss_t: 321. 而非 ‘int’ 来表
示 TSS 密钥 – 这是一种不透明类型，其定义可能依赖于下层的 TLS 实现。 因此
，这将允许在以无法安全地转换为 ‘int’ 的方式定义原生 TLS 密钥的平台上构建
CPython。

请注意在原生 TLS 密钥定义方式无法被安全地转换为 ‘int’ 的平台上，原有 TLS
API 中的全部函数将无法执行并会立即返回失败信息。 这样能清楚地表明原有
API 在无法可靠使用的平台上不受支持，并且不会再尝试添加此类支持。

参见
....

PEP 539(2) – 在 CPython 中用于线程局部存储的新 C-API

     PEP 由 Erik M. Bray 撰写；由 Masayuki Yamamoto 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0539

   (2) https://www.python.org/dev/peps/pep-0539


File: python.info,  Node: PEP 562 定制对模块属性的访问,  Next: PEP 564 具有纳秒级精度的新时间函数,  Prev: PEP 539 用于线程局部存储的新 C API,  Up: 新的特性<2>

1.2.2.6 PEP 562: 定制对模块属性的访问
.....................................

Python 3.7 允许在模块上定义 *note __getattr__(): 323. 并且当以其他方式找
不到某个模块属性时将会调用它。 在模块上定义 *note __dir__(): 324. 现在也
是允许的。

一个典型的可能有用的例子是已弃用模块属性和惰性加载。

参见
....

PEP 562(1) – 模块的 ‘__getattr__’ 和 ‘__dir__’

     PEP 由 Ivan Levkivskyi 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0562


File: python.info,  Node: PEP 564 具有纳秒级精度的新时间函数,  Next: PEP 565 在 __main__ 中显示 DeprecationWarning,  Prev: PEP 562 定制对模块属性的访问,  Up: 新的特性<2>

1.2.2.7 PEP 564: 具有纳秒级精度的新时间函数
...........................................

现代系统的时钟精度可以超过由 *note time.time(): 326. 函数及其变化形式所
返回的浮点数的有限精度。 为了避免精度损失， PEP 564(1) 在 *note time:
10b. 模块中增加了原有计时器函数的六个新“纳秒版”变化形式:

   * *note time.clock_gettime_ns(): 327.

   * *note time.clock_settime_ns(): 328.

   * *note time.monotonic_ns(): 329.

   * *note time.perf_counter_ns(): 32a.

   * *note time.process_time_ns(): 32b.

   * *note time.time_ns(): 32c.

这些新函数会以整数值的形式返回纳秒数。

测量(2) 表明在 Linux 和 Windows 上 *note time.time_ns(): 32c. 的精度大约
比 *note time.time(): 326. 要高 3 倍。

参见
....

PEP 564(3) – 增加具有纳秒级精度的新时间函数

     PEP 由 Victor Stinner 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0564

   (2) 
https://www.python.org/dev/peps/pep-0564/#annex-clocks-resolution-in-python

   (3) https://www.python.org/dev/peps/pep-0564


File: python.info,  Node: PEP 565 在 __main__ 中显示 DeprecationWarning,  Next: PEP 560 对 typing 模块和泛型类型的核心支持,  Prev: PEP 564 具有纳秒级精度的新时间函数,  Up: 新的特性<2>

1.2.2.8 PEP 565: 在 ‘__main__’ 中显示 DeprecationWarning
........................................................

*note DeprecationWarning: 279. 的默认处理方式已经被更改，这此警告默认只
显示一次，仅有当直接在 *note __main__: 1. 模块中运行的代码触发它们时才会
再次显示。 因此，单文件脚本开发者以及 Python 交互模式使用者应该会再次开
始看到针对他们所使用 API 的已弃用警告，但被导入应用、库和框架模块所触发
的已弃用警告默认将继续隐藏。

作为此项更改的结果，标准库现在允许开发者在三种不同的已弃用警告行为之间进
行选择:

   * *note FutureWarning: 32e.: 默认情况下总是会显示，建议用于应用程序最
     终用户应该看到的警告信息（例如对于已弃用的应用程序配置的设置选项）
     。

   * *note DeprecationWarning: 279.: 默认情况下仅在 *note __main__: 1. 中
     以及当运行测试时会显示，建议用于其他 Python 开发者应该看到的警告信
     息，提示版本升级可能导致行为改变或者错误。

   * *note PendingDeprecationWarning: 27a.: 默认情况下仅在运行测试时会显
     示，可用于提示未来版本升级将会改变警告类别为 *note
     DeprecationWarning: 279. 或 *note FutureWarning: 32e. 的情况。

在此之前 *note DeprecationWarning: 279. 和 *note
PendingDeprecationWarning: 27a. 都仅在运行测试时可见，这意味着主要编写单
文件脚本或使用 Python 交互模式的开发者可能会因他们所用 API 突然出现的改
变而感到惊讶。

参见
....

PEP 565(1) – 在 ‘__main__’ 中显示 DeprecationWarning

     PEP 由 Nick Coghlan 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0565


File: python.info,  Node: PEP 560 对 typing 模块和泛型类型的核心支持,  Next: PEP 552 基于哈希值的 pyc 文件,  Prev: PEP 565 在 __main__ 中显示 DeprecationWarning,  Up: 新的特性<2>

1.2.2.9 PEP 560: 对 ‘typing’ 模块和泛型类型的核心支持
.....................................................

PEP 484(1) 最初的设计方式使其不会向核心 CPython 解释器引入 `任何' 更改。
现在类型提示和 *note typing: 11a. 模块已被社区广泛使用，因此这个限制已被
取消。 这个 PEP 引入了两个特殊方法 *note __class_getitem__(): 330. 和
‘__mro_entries__’，这些方法现在被 *note typing: 11a. 中的大多数类和特殊
构造所使用。 结果就是与类型相关的各类操作的速度提升了 7 倍，泛型类型可以
在没有元类冲突的情况下被使用，而 *note typing: 11a. 模块中几个长期存在的
错误也已被修正。

参见
....

PEP 560(2) – 对 typing 模块和泛型类型的核心支持

     PEP 由 Ivan Levkivskyi 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0560


File: python.info,  Node: PEP 552 基于哈希值的 pyc 文件,  Next: PEP 545 Python 文档翻译,  Prev: PEP 560 对 typing 模块和泛型类型的核心支持,  Up: 新的特性<2>

1.2.2.10 PEP 552: 基于哈希值的 .pyc 文件
........................................

传统上 Python 检查字节码缓存文件 (即 ‘.pyc’ 文件) 是否最新的方式是通过对
源码元数据 (最后更改的时间戳和大小）和生成缓存时保存在其文件头中的源码元
数据进行比较。 这种检查方法虽然有效，但也存在缺点。 当文件系统的时间戳太
粗糙时，Python 有可能错过源码更新，导致用户感到困惑。 此外，在缓存文件中
存在时间戳对于 构建可再现(1) 并且基于内容的构建系统来说是有问题的。

PEP 552(2) 扩展了 pyc 格式以允许使用源文件的哈希值而非源文件的时间戳来检
查有效性。 这种 ‘.pyc’ 文件就称为“基于哈希值的”。 默认情况下，Python 仍
然使用基于时间戳的有效性检查，不会在运行时生成基于哈希值的 ‘.pyc’ 文件。
基于哈希值的 ‘.pyc’ 文件可以使用 *note py_compile: d8. 或 *note
compileall: 21. 来生成。

基于哈希值的 ‘.pyc’ 文件包含两种变体：已选定和未选定。 Python 会在运行时
针对相应源码文件验证已选定基于哈希值的 ‘.pyc’ 文件，但对未选定基于哈希值
的 pyc 文件则不会这样做。 未选定基于哈希值的 ‘.pyc’ 文件对于需要由
Python 外部的系统（例如构建系统）负责使 ‘.pyc’ 文件保持最新的环境来说是
一种有用的性能优化。

请参阅 *note 已缓存字节码的失效: 332. 了解更多信息。

参见
....

PEP 552(3) – 确定性的 pyc 文件

     PEP 由 Benjamin Peterson 撰写并实现

   ---------- Footnotes ----------

   (1) https://reproducible-builds.org/

   (2) https://www.python.org/dev/peps/pep-0552

   (3) https://www.python.org/dev/peps/pep-0552


File: python.info,  Node: PEP 545 Python 文档翻译,  Next: 开发运行时模式 -X dev,  Prev: PEP 552 基于哈希值的 pyc 文件,  Up: 新的特性<2>

1.2.2.11 PEP 545: Python 文档翻译
.................................

PEP 545(1) 描述了创建和维护 Python 文档翻译的整个过程。

新增了三个新的翻译版本:

   - 日语: ‘https://docs.python.org/ja/’

   - 法语: ‘https://docs.python.org/fr/’

   - 韩语: ‘https://docs.python.org/ko/’

参见
....

PEP 545(2) – Python 文档翻译

     PEP 由 Julien Palard, Inada Naoki 和 Victor Stinner 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0545

   (2) https://www.python.org/dev/peps/pep-0545


File: python.info,  Node: 开发运行时模式 -X dev,  Prev: PEP 545 Python 文档翻译,  Up: 新的特性<2>

1.2.2.12 开发运行时模式: -X dev
...............................

新的 *note -X: 156. ‘dev’ 命令行选项或新的 *note PYTHONDEVMODE: 335. 环
境变量可被用来启用 CPython 的 `开发模式'。 在开发模式下，CPython 会执行
额外的在默认情况下开销过大的运行时检查。 请参阅 *note -X: 156. ‘dev’ 文
档查看对于此模式效果的完整描述。


File: python.info,  Node: 其他语言特性修改<2>,  Next: 新增模块<2>,  Prev: 新的特性<2>,  Up: Python 3 7 有什么新变化

1.2.3 其他语言特性修改
----------------------

   * *note await: 1a4. 表达式和包含 *note async for: 2e4. 子句的推导式不
     允许在 *note 格式化字符串字面值: 15d. 的表达式中使用。 在 Python
     3.7 中此限制已被取消。

   * 现在可以将超过 255 个参数传递给一个函数，而现在一个函数也可以拥有超
     过 255 个形参。 （由 Serhiy Storchaka 在 bpo-12844(1) 和
     bpo-18896(2) 中贡献。）

   * 现在 *note bytes.fromhex(): 337. 和 *note bytearray.fromhex(): 338.
     会忽略所有 ASCII 空白符，而非仅是空格符. （由 Robert Xiao 在
     bpo-28927(3) 中贡献。）

   * *note str: 339, *note bytes: 33a. 和 *note bytearray: 33b. 获得了对
     新 *note isascii(): 33c. 方法的支持，该方法可被用来测试是个字符串或
     字节串是否仅包含 ASCII 字符。 （由 INADA Naoki 在 bpo-32677(4) 中贡
     献。）

   * 现在当 ‘from ... import ...’ 失败时 *note ImportError: 33d. 会显示
     模块名称和模块 ‘__file__’ 路径。 （由 Matthias Bussonnier 在
     bpo-29546(5) 中贡献。）

   * 现在已支持涉及将子模块绑定到一个名称的绝对导入的循环导入。 （由
     Serhiy Storchaka 在 bpo-30024(6) 中贡献。）

   * 现在 ‘object.__format__(x, '')’ 等价于 ‘str(x)’ 而非
     ‘format(str(self), '')’。 （由 Serhiy Storchaka d bpo-28974(7) 中贡
     献。）

   * 为更好地支持栈跟踪的动态创建，现在 *note types.TracebackType: 33e.
     可以从 Python 代码中被实例化，并且 *note 回溯对象: 33f. 的
     ‘tb_next’ 属性现在是可写的。 （由 Nathaniel J. Smith 在
     bpo-30579(8) 中贡献。）

   * 当使用 *note -m: 340. 开关时，现在 ‘sys.path[0]’ 会主动扩展为完整的
     起始目录路径，而不是保持为空目录（这将允许在发生导入时从 `当前' 工
     作目录导入） （由 Nick Coghlan 在 bpo-33053(9) 中贡献。）

   * 新的 *note -X: 156. ‘importtime’ 选项或 *note
     PYTHONPROFILEIMPORTTIME: 341. 环境变量可被用来显示每次模块导入的时
     间。 （由 Victor Stinner 在 bpo-31415(10) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12844

   (2) https://bugs.python.org/issue18896

   (3) https://bugs.python.org/issue28927

   (4) https://bugs.python.org/issue32677

   (5) https://bugs.python.org/issue29546

   (6) https://bugs.python.org/issue30024

   (7) https://bugs.python.org/issue28974

   (8) https://bugs.python.org/issue30579

   (9) https://bugs.python.org/issue33053

   (10) https://bugs.python.org/issue31415


File: python.info,  Node: 新增模块<2>,  Next: 改进的模块<2>,  Prev: 其他语言特性修改<2>,  Up: Python 3 7 有什么新变化

1.2.4 新增模块
--------------

* Menu:

* contextvars::
* dataclasses::
* importlib.resources: importlib resources.


File: python.info,  Node: contextvars,  Next: dataclasses,  Up: 新增模块<2>

1.2.4.1 contextvars
...................

新的 *note contextvars: 25. 模块和一组 *note 新的 C API: 344. 引入了对
`上下文变量' 的支持。 上下文变量在概念上类似于线程局部变量。 与 TLS 不同
，上下文变量能正确地支持异步代码。

*note asyncio: a. 和 *note decimal: 36. 已得到更新以使用和支持开箱即用的
上下文变量。 特别是激活的 decimal 上下文现在将存储在上下文变量中，它允许
十进制运算在异步代码中使用正确的上下文。

参见
....

PEP 567(1) – 上下文变量

     PEP 由 Yury Selivanov 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0567


File: python.info,  Node: dataclasses,  Next: importlib resources,  Prev: contextvars,  Up: 新增模块<2>

1.2.4.2 dataclasses
...................

新的 *note dataclass(): 346. 装饰器提供了一种声明 `数据类' 的方式。 数据
类使用变量标注来描述其属性。 它的构造器和其他魔术方法例如 *note
__repr__(): 347, *note __eq__(): 348. 以及 *note __hash__(): 349. 会自动
地生成。

示例:

     @dataclass
     class Point:
         x: float
         y: float
         z: float = 0.0

     p = Point(1.5, 2.5)
     print(p)   # produces "Point(x=1.5, y=2.5, z=0.0)"

参见
....

PEP 557(1) – 数据类

     PEP 由 Eric V. Smith 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0557


File: python.info,  Node: importlib resources,  Prev: dataclasses,  Up: 新增模块<2>

1.2.4.3 importlib.resources
...........................

新的 *note importlib.resources: 9f. 模块提供了一些新的 API 和一个新的
ABC 用于访问、打开和读取包内的 `资源'。 资源基本上类似于包内的文件，但它
们不一定是物理文件系统中实际的文件。 模块加载器可以提供
‘get_resource_reader()’ 函数，它会返回一个 *note
importlib.abc.ResourceReader: 34b. 实例来支持这个新 API。 内置的文件路径
加载器和 zip 文件加载器都支持此特性。

由 Barry Warsaw 和 Brett Cannon 在 bpo-32248(1) 中贡献。

参见
....

importlib_resources(2) – 用于先前 Python 版本的 PyPI 下层接口。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32248

   (2) http://importlib-resources.readthedocs.io/en/latest/


File: python.info,  Node: 改进的模块<2>,  Next: C API 的改变,  Prev: 新增模块<2>,  Up: Python 3 7 有什么新变化

1.2.5 改进的模块
----------------

* Menu:

* argparse::
* asyncio: asyncio<2>.
* binascii::
* calendar::
* collections: collections<2>.
* compileall::
* concurrent.futures: concurrent futures.
* contextlib::
* cProfile: cProfile<2>.
* crypt::
* datetime: datetime<2>.
* dbm::
* decimal::
* dis::
* distutils::
* enum::
* functools: functools<2>.
* gc: gc<2>.
* hmac::
* http.client: http client.
* http.server: http server.
* idlelib 与 IDLE::
* importlib::
* io: io<2>.
* ipaddress::
* itertools: itertools<2>.
* locale::
* logging: logging<2>.
* math: math<2>.
* mimetypes::
* msilib::
* multiprocessing: multiprocessing<2>.
* os: os<2>.
* pathlib: pathlib<2>.
* pdb::
* py_compile: py_compile<2>.
* pydoc::
* queue::
* re::
* signal::
* socket: socket<2>.
* socketserver::
* sqlite3::
* ssl: ssl<2>.
* string::
* subprocess::
* sys: sys<2>.
* time: time<2>.
* tkinter: tkinter<2>.
* tracemalloc::
* types::
* unicodedata: unicodedata<2>.
* unittest: unittest<2>.
* unittest.mock: unittest mock.
* urllib.parse: urllib parse<2>.
* uu::
* uuid::
* warnings::
* xml.etree: xml etree.
* xmlrpc.server: xmlrpc server.
* zipapp::
* zipfile::


File: python.info,  Node: argparse,  Next: asyncio<2>,  Up: 改进的模块<2>

1.2.5.1 argparse
................

新的 *note ArgumentParser.parse_intermixed_args(): 34e. 方法允许混合选项
与位置参数。 （由 paul.j3 在 bpo-14191(1) 中提供。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14191


File: python.info,  Node: asyncio<2>,  Next: binascii,  Prev: argparse,  Up: 改进的模块<2>

1.2.5.2 asyncio
...............

*note asyncio: a. 模块获得了许多新的特性、可用性和 *note 性能提升: 350.。
重要的改变包括:

   * 新的 *note 暂定: 351. *note asyncio.run(): 1a6. 函数可被用于通过自
     动创建和销毁事件循环来基于同步代码运行协程。 （由 Yury Selivanov 在
     bpo-32314(1) 中贡献。）

   * asyncio 增加支持 *note contextvars: 25.  *note loop.call_soon():
     352, *note loop.call_soon_threadsafe(): 353, *note
     loop.call_later(): 354, *note loop.call_at(): 355. 并且 *note
     Future.add_done_callback(): 356. 具有新的可选仅关键字参数
     `context'。 现在 *note Tasks: 1ae. 会自动跟踪其上下文。 详情参见
     PEP 567(2)。 （由 Yury Selivanov 在 bpo-32436(3) 中贡献。）

   * 增加了新的 *note asyncio.create_task(): 1af. 函数作为
     ‘asyncio.get_event_loop().create_task()’ 的快捷方式。 （由 Andrew
     Svetlov 在 bpo-32311(4) 中贡献。）

   * 新的 *note loop.start_tls(): 357. 方法可用于升级现有的 TLS 连接。 （
     由 Yury Selivanov 在 bpo-23749(5) 中贡献。）

   * 新的 *note loop.sock_recv_into(): 358. 方法允许直接从套接字读取数据
     放入所提供的缓冲区，从而可以减少数据复制。 （由 Antoine Pitrou 在
     bpo-31819(6) 中贡献。）

   * 新的 *note asyncio.current_task(): 359. 函数可返回当前运行的 *note
     Task: 1ae. 实例，以及新的 *note asyncio.all_tasks(): 35a. 函数可返
     回给定循环中所有现存 ‘Task’ 实例的集合。 *note Task.current_task():
     35b. 和 *note Task.all_tasks(): 35c. 方法已弃用。 （由 Andrew
     Svetlov 在 bpo-32250(7) 中贡献。）

   * 新的 `暂定' *note BufferedProtocol: 2ca. 类允许通过手动控制接收缓冲
     区来实现流式协议。 （由 Yury Selivanov 在 bpo-32251(8) 中贡献。）

   * 新的 *note asyncio.get_running_loop(): 35d. 函数可返回当前运行的循
     环，如果没有循环在运行则引发 *note RuntimeError: 2bb.。 这与 *note
     asyncio.get_event_loop(): 35e. 不同，后者在没有循环在运行时将 `创建
     ' 一个新的事件循环。 （由 Yury Selivanov 在 bpo-32269(9) 中提供。）

   * 新的 *note StreamWriter.wait_closed(): 35f. 协程方法允许执行等待直
     到流写入器被关闭。 新的 *note StreamWriter.is_closing(): 360. 方法
     可用于确定写入器是否被关闭。 （由 Andrew Svetlov 在 bpo-32391(10) 中
     贡献。）

   * 新的 *note loop.sock_sendfile(): 361. 协程方法允许在可能的情况下使
     用 *note os.sendfile: 362. 发送文件。 （由 Andrew Svetlov 在
     bpo-32410(11) 中贡献。）

   * 新的 *note Future.get_loop(): 363. 和 ‘Task.get_loop()’ 方法会返回
     创建 task 或 future 对象的事件循环的实例。 *note Server.get_loop():
     364. 允许为 *note asyncio.Server: 365. 对象执行同样操作。 （由 Yury
     Selivanov 在 bpo-32415(12) 中，以及由 Srinivas Reddy Thatiparthy 在
     bpo-32418(13) 中贡献。）

   * 现在可以控制 *note asyncio.Server: 365. 的实例如何开启服务。 之前，
     服务在创建后将立即开启服务。 新的 `start_serving' 关键字参数已添加
     到 *note loop.create_server(): 366. 和 *note
     loop.create_unix_server(): 367.，并且 *note Server.start_serving():
     368, 和 *note Server.serve_forever(): 369. 可被用来分离服务的实例化
     和服务的开启。 新的 *note Server.is_serving(): 36a. 方法会在服务开
     启时返回 ‘True’。 现在 *note Server: 365. 对象已是异步上下文管理器:

          srv = await loop.create_server(...)

          async with srv:
              # some code

          # At this point, srv is closed and no longer accepts new connections.

     （由 Yury Selivanov 在 bpo-32662(14) 中贡献。）

   * 由 *note loop.call_later(): 354. 所返回的回调对象已获得新的 *note
     when(): 36b. 方法，该方法会返回一个排入计划日程的绝对时间戳。 （由
     Andrew Svetlov 在 bpo-32741(15) 中贡献。）

   * *note loop.create_datagram_endpoint(): 2e8. 方法已获得对 Unix 套接
     字的支持。 （由 Quentin Dawans 在 bpo-31245(16) 中贡献。）

   * *note asyncio.open_connection(): 36c, *note asyncio.start_server():
     36d. functions, *note loop.create_connection(): 1b3, *note
     loop.create_server(): 366, *note loop.create_accepted_socket():
     36e. 方法及其对应的 UNIX 套接字变体现在接受 `ssl_handshake_timeout'
     关键字参数。 （由 Neil Aspinall 在 bpo-29970(17) 中贡献。）

   * 新的 *note Handle.cancelled(): 36f. 方法会在回调被取消时返回
     ‘True’。 （由 Marat Sharafutdinov 在 bpo-31943(18) 中贡献。）

   * asyncio 源已被转换为使用 *note async: 1a3./*note await: 1a4. 语法。
     （由 Andrew Svetlov 在 bpo-32193(19) 中贡献。）

   * 新的 *note ReadTransport.is_reading(): 370. 方法可用于确定传输的读
     取状态。 此外，对 *note ReadTransport.resume_reading(): 371. 和
     *note ReadTransport.pause_reading(): 372. 的调用现在是幂等的。 （由
     Yury Selivanov 在 bpo-32356(20) 中贡献。）

   * 接受套接字路径的循环方法现在支持传入 *note 路径类对象: 373.。 （由
     Yury Selivanov 在 bpo-32066(21) 中贡献。）

   * 在 *note asyncio: a. 中，Linux 上的 TCP 套接字现在创建时默认带有
     ‘TCP_NODELAY’ 旗标设置。 （由 Yury Selivanov 和 Victor Stinner 在
     bpo-27456(22) 中贡献。）

   * 在被取消任务中发生的异常不会再被记录。 （由 Yury Selivanov 在
     bpo-30508(23) 中贡献。）

   * 新的 ‘WindowsSelectorEventLoopPolicy’ 和
     ‘WindowsProactorEventLoopPolicy’ 类。 （由 Yury Selivanov 在
     bpo-33792(24) 中贡献。）

部分 ‘asyncio’ API 改为 *note 已弃用: 374.。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32314

   (2) https://www.python.org/dev/peps/pep-0567

   (3) https://bugs.python.org/issue32436

   (4) https://bugs.python.org/issue32311

   (5) https://bugs.python.org/issue23749

   (6) https://bugs.python.org/issue31819

   (7) https://bugs.python.org/issue32250

   (8) https://bugs.python.org/issue32251

   (9) https://bugs.python.org/issue32269

   (10) https://bugs.python.org/issue32391

   (11) https://bugs.python.org/issue32410

   (12) https://bugs.python.org/issue32415

   (13) https://bugs.python.org/issue32418

   (14) https://bugs.python.org/issue32662

   (15) https://bugs.python.org/issue32741

   (16) https://bugs.python.org/issue31245

   (17) https://bugs.python.org/issue29970

   (18) https://bugs.python.org/issue31943

   (19) https://bugs.python.org/issue32193

   (20) https://bugs.python.org/issue32356

   (21) https://bugs.python.org/issue32066

   (22) https://bugs.python.org/issue27456

   (23) https://bugs.python.org/issue30508

   (24) https://bugs.python.org/issue33792


File: python.info,  Node: binascii,  Next: calendar,  Prev: asyncio<2>,  Up: 改进的模块<2>

1.2.5.3 binascii
................

*note b2a_uu(): 376. 函数现在接受可选的 `backtick' 关键字参数。 当其为真
值时，零会以 ‘'`'’ 而非空格来表示。 （由 Xiang Zhang 在 bpo-30103(1) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30103


File: python.info,  Node: calendar,  Next: collections<2>,  Prev: binascii,  Up: 改进的模块<2>

1.2.5.4 calendar
................

*note HTMLCalendar: 378. 类具有新的类属性，可以简化所生成 HTML 日历中
CSS 类的自定义。 （由 Oz Tiram 在 bpo-30095(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30095


File: python.info,  Node: collections<2>,  Next: compileall,  Prev: calendar,  Up: 改进的模块<2>

1.2.5.5 collections
...................

‘collections.namedtuple()’ 现在支持默认值。 （由 Raymond Hettinger 在
bpo-32320(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32320


File: python.info,  Node: compileall,  Next: concurrent futures,  Prev: collections<2>,  Up: 改进的模块<2>

1.2.5.6 compileall
..................

*note compileall.compile_dir(): 37b. 增加了新的 `invalidation_mode' 形参
，可用于启用 *note 基于哈希值的 .pyc 有效性检测: 30a.。 失效模式也可以在
命令行中使用新的 ‘--invalidation-mode’ 参数来指定。 （由 Benjamin
Peterson 在 bpo-31650(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31650


File: python.info,  Node: concurrent futures,  Next: contextlib,  Prev: compileall,  Up: 改进的模块<2>

1.2.5.7 concurrent.futures
..........................

*note ProcessPoolExecutor: 2a4. 和 *note ThreadPoolExecutor: 27b. 现在支
持新的 `初始化器' 以及 `initargs' 构造器参数。 （由 Antoine Pitrou 在
bpo-21423(1) 中贡献。）

*note ProcessPoolExecutor: 2a4. 现在能通过新的 `mp_context' 参数来接受多
进程上下文。 （由 Thomas Moreau 在 bpo-31540(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21423

   (2) https://bugs.python.org/issue31540


File: python.info,  Node: contextlib,  Next: cProfile<2>,  Prev: concurrent futures,  Up: 改进的模块<2>

1.2.5.8 contextlib
..................

新的 *note nullcontext(): 37e. 是一个比 *note ExitStack: 37f. 更简单和快
速的无操作上下文管理器。 （由 Jesse-Bakker 在 bpo-10049(1) 中贡献。）

增加了新的 *note asynccontextmanager(): 380, *note
AbstractAsyncContextManager: 381. 和 *note AsyncExitStack: 382. 以补充它
们所对应的同步项。 （由 Jelle Zijlstra 在 bpo-29679(2) 和 bpo-30241(3) 中
，以及由 Alexander Mohr 和 Ilya Kulakov 在 bpo-29302(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10049

   (2) https://bugs.python.org/issue29679

   (3) https://bugs.python.org/issue30241

   (4) https://bugs.python.org/issue29302


File: python.info,  Node: cProfile<2>,  Next: crypt,  Prev: contextlib,  Up: 改进的模块<2>

1.2.5.9 cProfile
................

*note cProfile: 28. 命令行现在接受 ‘-m module_name’ 作为脚本路径的替代。
（由 Sanyam Khurana 在 bpo-21862(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21862


File: python.info,  Node: crypt,  Next: datetime<2>,  Prev: cProfile<2>,  Up: 改进的模块<2>

1.2.5.10 crypt
..............

*note crypt: 29. 模块现在支持 Blowfish 哈希方法。 （由 Serhiy Storchaka
在 bpo-31664(1) 中贡献。）

*note mksalt(): 385. 函数现在允许指定哈希操作的轮数。 （由 Serhiy
Storchaka 在 bpo-31702(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31664

   (2) https://bugs.python.org/issue31702


File: python.info,  Node: datetime<2>,  Next: dbm,  Prev: crypt,  Up: 改进的模块<2>

1.2.5.11 datetime
.................

新的 *note datetime.fromisoformat(): 387. 方法会基于由
‘datetime.isoformat()’ 所输出的某一特定格式字符串构建 *note datetime:
195. 对象。 （由 Paul Ganssle 在 bpo-15873(1) 中贡献。）

*note tzinfo: 388. 类现在支持小于一分钟的偏移量。 （由 Alexander
Belopolsky 在 bpo-5288(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15873

   (2) https://bugs.python.org/issue5288


File: python.info,  Node: dbm,  Next: decimal,  Prev: datetime<2>,  Up: 改进的模块<2>

1.2.5.12 dbm
............

*note dbm.dumb: 33. 现在支持读取只读文件，并且在其未改变时不再写入索引文
件。


File: python.info,  Node: decimal,  Next: dis,  Prev: dbm,  Up: 改进的模块<2>

1.2.5.13 decimal
................

*note decimal: 36. 模块现在使用 *note 上下文变量: 2fe. 来储存十进制值上
下文。 （由 Yury Selivanov 在 bpo-32630(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32630


File: python.info,  Node: dis,  Next: distutils,  Prev: decimal,  Up: 改进的模块<2>

1.2.5.14 dis
............

*note dis(): 38c. 函数现在能够反汇编嵌套的代码对象（推导式、生成器表达式
和嵌套函数的代码，以及用于构建嵌套类的代码）。 反汇编递归的最大深度由新
的 `depth' 形参来控制。 （由 Serhiy Storchaka 在 bpo-11822(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11822


File: python.info,  Node: distutils,  Next: enum,  Prev: dis,  Up: 改进的模块<2>

1.2.5.15 distutils
..................

‘README.rst’ 现在包含在 distutils 的标准 README 列表之中，因而也包含在源
码发布之中。 （由 Ryan Gonzalez 在 bpo-11913(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11913


File: python.info,  Node: enum,  Next: functools<2>,  Prev: distutils,  Up: 改进的模块<2>

1.2.5.16 enum
.............

*note Enum: 38f. 增加了新的 ‘_ignore_’ 类特征属性，该属性允许列出不应当
成为枚举成员的特征属性名称。 （由 Ethan Furman 在 bpo-31801(1) 中贡献。
）

在 Python 3.8 中，尝试在 ‘Enum’ 类中检查非 Enum 对象将引发 *note
TypeError: 193. (例如 ‘1 in Color’)；类似地，尝试在 ‘Flag’ 成员中检查非
Flag 对象也将引发 *note TypeError: 193. (例如 ‘1 in Perm.RW’)；目前，两
种操作均会返回 *note False: 390. 并且已弃用。 （由 Ethan Furman 在
bpo-33217(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31801

   (2) https://bugs.python.org/issue33217


File: python.info,  Node: functools<2>,  Next: gc<2>,  Prev: enum,  Up: 改进的模块<2>

1.2.5.17 functools
..................

*note functools.singledispatch(): 392. 现在支持使用类型标注来注册实现。
（由 Łukasz Langa 在 bpo-32227(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32227


File: python.info,  Node: gc<2>,  Next: hmac,  Prev: functools<2>,  Up: 改进的模块<2>

1.2.5.18 gc
...........

新的 *note gc.freeze(): 394. 函数允许冻结由垃圾回收器所跟踪的所有对象，
并将它们从未来的集合中排除。 这可以在 POSIX ‘fork()’ 调用之前使用以令 GC
友好地进行写入时复制或加速收集。 新的 *note gc.unfreeze(): 395. 函数会反
转此操作。 此外，*note gc.get_freeze_count(): 396. 可被用于获取冻结对象
的数量。 （由 Li Zekun 在 bpo-31558(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31558


File: python.info,  Node: hmac,  Next: http client,  Prev: gc<2>,  Up: 改进的模块<2>

1.2.5.19 hmac
.............

*note hmac: 8f. 现在具有经优化的一次性 *note digest(): 398. 函数，其速度
比 ‘HMAC()’ 要快三倍。 （由 Christian Heimes 在 bpo-32433(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32433


File: python.info,  Node: http client,  Next: http server,  Prev: hmac,  Up: 改进的模块<2>

1.2.5.20 http.client
....................

*note HTTPConnection: 39a. 和 *note HTTPSConnection: 39b. 现在支持新的
`blocksize' 参数以提升上传吞吐量。 （由 Nir Soffer 在 bpo-31945(1) 中贡
献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31945


File: python.info,  Node: http server,  Next: idlelib 与 IDLE,  Prev: http client,  Up: 改进的模块<2>

1.2.5.21 http.server
....................

*note SimpleHTTPRequestHandler: 39d. 现在支持 HTTP ‘If-Modified-Since’ 标
头。 如果目标文件在该标点指定的时间之后未被修改则服务器会返回 304 响应状
态。 （由 Pierre Quentel 在 bpo-29654(1) 中贡献。）

*note SimpleHTTPRequestHandler: 39d. 接受新的 `directory' 参数并增加了新
的 ‘--directory’ 命令行参数。 通过此形参，服务器可以对服务指定目录，默认
情况下它使用当前工作目录。 （由 Stéphane Wirtel 和 Julien Palard 在
bpo-28707(2) 中贡献。）

新的 *note ThreadingHTTPServer: 39e. 类使用线程来处理使用
‘ThreadingMixin’ 的请求。 它会在 ‘http.server’ 附带 ‘-m’ 运行时被使用。
（由 Julien Palard 在 bpo-31639(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29654

   (2) https://bugs.python.org/issue28707

   (3) https://bugs.python.org/issue31639


File: python.info,  Node: idlelib 与 IDLE,  Next: importlib,  Prev: http server,  Up: 改进的模块<2>

1.2.5.22 idlelib 与 IDLE
........................

多个对自动补全的修正。 （由 Louie Lu 在 bpo-15786(1) 中贡献。）

Module Browser (在 File 菜单中，之前称为 Class Browser) 现在会在最高层级
函数和类之外显示嵌套的函数和类。 （由 Guilherme Polo, Cheryl Sabella 和
Terry Jan Reedy 在 bpo-1612262(2) 中贡献。）

Settings 对话框 (Options 中的 Configure IDLE) 已经被部分重写以改进外观和
功能。 （由 Cheryl Sabella 和 Terry Jan Reedy 在多个问题项中贡献。）

字体样本现在包括一组非拉丁字符以便用户能更好地查看所选特定字体的效果。 （
由 Terry Jan Reedy 在 bpo-13802(3) 中贡献。） 样本可以被修改以包括其他字
符。 （由 Serhiy Storchaka 在 bpo-31860(4) 中贡献。）

之前以扩展形式实现的 IDLE 特性已作为正常特性重新实现。 它们的设置已从
Extensions 选项卡移至其他对话框选项卡。 （由 Charles Wohlganger 和 Terry
Jan Reedy 在 bpo-27099(5) 中实现。）

编辑器代码上下文选项已经过修改。 Box 会显示所有上下文行直到最大行数。 点
击一个上下文行会使编辑器跳转到该行。 自定义主题的上下文颜色已添加到
Settings 对话框的 Highlights 选项卡。 （由 Cheryl Sabella 和 Terry Jan
Reedy 在 bpo-33642(6), bpo-33768(7) 和 bpo-33679(8) 中贡献。）

在 Windows 上，会有新的 API 调用将 tk 对 DPI 的调整告知 Windows。 在
Windows 8.1+ 或 10 上，如果 Python 二进制码的 DPI 兼容属性未改变，并且监
视器分辨率大于 96 DPI，这应该会令文本和线条更清晰。 否则的话它应该不造成
影响。 （由 Terry Jan Reedy 在 bpo-33656(9) 中贡献。）

在 3.7.1 中新增:

超过 N 行（默认值为 50）的输出将被折叠为一个按钮。 N 可以在 Settings 对
话框的 General 页的 PyShell 部分中进行修改。 数量较少但是超长的行可以通
过在输出上右击来折叠。 被折叠的输出可通过双击按钮来展开，或是通过右击按
钮来放入剪贴板或是单独的窗口。 （由 Tal Einat 在 bpo-1529353(10) 中贡献
。）

上述修改已被反向移植到 3.6 维护发行版中。

在 3.7.4 中新增:

在 Run 菜单中增加了 "Run Customized" 以使用自定义设置来运行模块。 输入的
任何命令行参数都会被加入 sys.argv。 它们在下次自定义运行时会再次显示在窗
体中。 用户也可以禁用通常的 Shell 主模块重启。 （由 Cheryl Sabella,
Terry Jan Reedy 等人在 bpo-5680(11) 和 bpo-37627(12) 中贡献。）

在 3.7.5 中新增:

在 IDLE 编辑器窗口中增加了可选的行序号。 窗口打开时默认不带行序号，除非
在配置对话框的 General 选项卡中进行设置。 已打开窗口中的行序号可以在
Options 菜单中显示和隐藏。 （由 Tal Einat 和 Saimadhav Heblikar 在
bpo-17535(13) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15786

   (2) https://bugs.python.org/issue1612262

   (3) https://bugs.python.org/issue13802

   (4) https://bugs.python.org/issue31860

   (5) https://bugs.python.org/issue27099

   (6) https://bugs.python.org/issue33642

   (7) https://bugs.python.org/issue33768

   (8) https://bugs.python.org/issue33679

   (9) https://bugs.python.org/issue33656

   (10) https://bugs.python.org/issue1529353

   (11) https://bugs.python.org/issue5680

   (12) https://bugs.python.org/issue37627

   (13) https://bugs.python.org/issue17535


File: python.info,  Node: importlib,  Next: io<2>,  Prev: idlelib 与 IDLE,  Up: 改进的模块<2>

1.2.5.23 importlib
..................

引入了 *note importlib.abc.ResourceReader: 34b. ABC 以支持从包中加载资源
。 另请参阅 *note importlib.resources: 300.。 （由 Barry Warsaw, Brett
Cannon 在 bpo-32248(1) 中贡献。）

如果模块缺少规格描述 *note importlib.reload(): 3a1. 现在会引发 *note
ModuleNotFoundError: 3a2.。 （由 Garvit Khatri 在 bpo-29851(2) 中贡献。
）

如果指定的父模块不是一个包 (即缺少 ‘__path__’ 属性)
‘importlib.find_spec()’ 现在会引发 *note ModuleNotFoundError: 3a2. 而非
*note AttributeError: 3a3.。 （由 Milan Oberkirch 在 bpo-30436(3) 中贡献
。）

新的 ‘importlib.source_hash()’ 可被用来计算传入源的哈希值。 *note
基于哈希值的 .pyc 文件: 30a. 会嵌入此函数所返回的值。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32248

   (2) https://bugs.python.org/issue29851

   (3) https://bugs.python.org/issue30436


File: python.info,  Node: io<2>,  Next: ipaddress,  Prev: importlib,  Up: 改进的模块<2>

1.2.5.24 io
...........

新的 *note TextIOWrapper.reconfigure(): 3a5. 方法可用于根据新的设置重新
配置文本流。 （由 Antoine Pitrou 在 bpo-30526(1) 以及 INADA Naoki 在
bpo-15216(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30526

   (2) https://bugs.python.org/issue15216


File: python.info,  Node: ipaddress,  Next: itertools<2>,  Prev: io<2>,  Up: 改进的模块<2>

1.2.5.25 ipaddress
..................

methods of *note ipaddress.IPv6Network: 3a7. 和 *note
ipaddress.IPv4Network: 3a8. 中新的 ‘subnet_of()’ 以及 ‘supernet_of()’ 方
法可用于网络包含测试。 （由 Michel Albert 和 Cheryl Sabella 在
bpo-20825(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20825


File: python.info,  Node: itertools<2>,  Next: locale,  Prev: ipaddress,  Up: 改进的模块<2>

1.2.5.26 itertools
..................

*note itertools.islice(): 3aa. 现在接受 *note 类整数对象: 18b. 作为
start, stop 和 slice 参数。 （由 Will Roberts 在 bpo-30537(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30537


File: python.info,  Node: locale,  Next: logging<2>,  Prev: itertools<2>,  Up: 改进的模块<2>

1.2.5.27 locale
...............

*note locale.format_string(): 3ac. 中新的 `monetary' 参数可用于转换所使
用的千位分隔符和分组字符串。 （由 Garvit 在 bpo-10379(1) 中贡献。）

现在 *note locale.getpreferredencoding(): 3ad. 函数在 Android 上或是在
*note 强制 UTF-8 模式: 309. 下总是返回 ‘'UTF-8'’ 。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10379


File: python.info,  Node: logging<2>,  Next: math<2>,  Prev: locale,  Up: 改进的模块<2>

1.2.5.28 logging
................

*note Logger: 3af. 实例现在可以被 pickle。 （由 Vinay Sajip 在
bpo-30520(1) 中贡献。）

新的 *note StreamHandler.setStream(): 3b0. 方法可用于在句柄创建之后替换
日志流。 （由 Vinay Sajip 在 bpo-30522(2) 中创建。）

现在可以在传递给 *note logging.config.fileConfig(): 3b1. 的配置信息中对
句柄构造器指定关键字参数。 （由 Preston Landers 在 bpo-31080(3) 中贡献。
)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30520

   (2) https://bugs.python.org/issue30522

   (3) https://bugs.python.org/issue31080


File: python.info,  Node: math<2>,  Next: mimetypes,  Prev: logging<2>,  Up: 改进的模块<2>

1.2.5.29 math
.............

新的 *note math.remainder(): 3b3. 函数实现了 IEEE 754 风格的余数运算。 （
由 Mark Dickinson 在 bpo-29962(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29962


File: python.info,  Node: mimetypes,  Next: msilib,  Prev: math<2>,  Up: 改进的模块<2>

1.2.5.30 mimetypes
..................

.bmp 的 MIME type 从 ‘'image/x-ms-bmp'’ 改为 ‘'image/bmp'’。 （由 Nitish
Chandra 在 bpo-22589(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22589


File: python.info,  Node: msilib,  Next: multiprocessing<2>,  Prev: mimetypes,  Up: 改进的模块<2>

1.2.5.31 msilib
...............

新的 *note Database.Close(): 3b6. 方法可用于关闭 MSI (last-in,
first-out) 数据库。 （由 Berker Peksag 在 bpo-20486(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20486


File: python.info,  Node: multiprocessing<2>,  Next: os<2>,  Prev: msilib,  Up: 改进的模块<2>

1.2.5.32 multiprocessing
........................

新的 *note Process.close(): 3b8. 方法会显式地关闭进程对象并释放与其关联
的所有资源。 如果底层进程仍在运行则将引发 *note ValueError: 1fc.。 （由
Antoine Pitrou 在 bpo-30596(1) 中贡献。）

新的 *note Process.kill(): 3b9. 方法可用于在 Unix 上使用 ‘SIGKILL’ 信号
来终止进程。 （由 Vitor Pereira 在 bpo-30794(2) 中贡献。）

由 *note Process: 3ba. 所创建的非守护线程现在会在进程退出时被合并。 （由
Antoine Pitrou 在 bpo-18966(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30596

   (2) https://bugs.python.org/issue30794

   (3) https://bugs.python.org/issue18966


File: python.info,  Node: os<2>,  Next: pathlib<2>,  Prev: multiprocessing<2>,  Up: 改进的模块<2>

1.2.5.33 os
...........

*note os.fwalk(): 3bc. 现在接受 *note bytes: 33a. 类型的 `path' 参数。 （
由 Serhiy Storchaka 在 bpo-28682(1) 中贡献。）

*note os.scandir(): 260. 已获得对 *note 文件描述器: 3bd. 的支持。 （由
Serhiy Storchaka 在 bpo-25996(2) 中贡献。）

新的 *note register_at_fork(): 3be. 函数允许注册 Python 回调以便在进程分
叉中执行。 （由 Antoine Pitrou 在 bpo-16500(3) 中贡献。）

增加了 *note os.preadv(): 3bf. (结合了 *note os.readv(): 3c0. 与 *note
os.pread(): 3c1. 的功能) 以及 *note os.pwritev(): 3c2. 函数 (结合了
*note os.writev(): 3c3. 和 *note os.pwrite(): 3c4. 的功能)。 （由 Pablo
Galindo 在 bpo-31368(4) 中贡献。）

*note os.makedirs(): 3c5. 的 mode 参数不再影响新创建的中间层级目录的文件
权限。 （由 Serhiy Storchaka 在 bpo-19930(5) 中贡献。）

*note os.dup2(): 3c6. 现在会返回新的文件描述器。 之前，返回的总是
‘None’。 （由 Benjamin Peterson 在 bpo-32441(6) 中贡献。）

在 Solaris 及其派生系统上 *note os.stat(): 1f2. 所返回的结构现在会包含
*note st_fstype: 3c7. 属性。 （由 Jesús Cea Avión 在 bpo-32659(7) 中贡献
。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28682

   (2) https://bugs.python.org/issue25996

   (3) https://bugs.python.org/issue16500

   (4) https://bugs.python.org/issue31368

   (5) https://bugs.python.org/issue19930

   (6) https://bugs.python.org/issue32441

   (7) https://bugs.python.org/issue32659


File: python.info,  Node: pathlib<2>,  Next: pdb,  Prev: os<2>,  Up: 改进的模块<2>

1.2.5.34 pathlib
................

在 POSIX 类系统上新的 *note Path.is_mount(): 206. 方法现在可用于确定一个
路径是否为挂载点。 （由 Cooper Ry Lees 在 bpo-30897(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30897


File: python.info,  Node: pdb,  Next: py_compile<2>,  Prev: pathlib<2>,  Up: 改进的模块<2>

1.2.5.35 pdb
............

*note pdb.set_trace(): 3ca. 现在接受一个可选的限关键字参数 `header'。 如
果给出，它会在调试开始之前被打印到控制台。 （由 Barry Warsaw 在
bpo-31389(1) 中贡献。）

*note pdb: ca. 命令行现在接受 ‘-m module_name’ 作为对脚本文件的替代。 （
由 Mario Corchero 在 bpo-32206(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31389

   (2) https://bugs.python.org/issue32206


File: python.info,  Node: py_compile<2>,  Next: pydoc,  Prev: pdb,  Up: 改进的模块<2>

1.2.5.36 py_compile
...................

*note py_compile.compile(): 216. – 及其扩展形式 *note compileall: 21. –
现在会通过无条件地为基于哈希值的有效性验证创建 ‘.pyc’ 文件来支持
‘SOURCE_DATE_EPOCH’ 环境变量。 这样可以确保当 ‘.pyc’ 文件被主动创建时 可
重现的生成(1)。 （由 Bernhard M. Wiedemann 在 bpo-29708(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://reproducible-builds.org/

   (2) https://bugs.python.org/issue29708


File: python.info,  Node: pydoc,  Next: queue,  Prev: py_compile<2>,  Up: 改进的模块<2>

1.2.5.37 pydoc
..............

pydoc 服务器现在可以绑定到由新的 ‘-n’ 命令行参数所指定的任意主机名。 （
由 Feanil Patel 在 bpo-31128(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31128


File: python.info,  Node: queue,  Next: re,  Prev: pydoc,  Up: 改进的模块<2>

1.2.5.38 queue
..............

新的 *note SimpleQueue: 3ce. 类是一个无界的 FIFO (last-in, first-out) 队
列。 （由 Antoine Pitrou 在 bpo-14976(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14976


File: python.info,  Node: re,  Next: signal,  Prev: queue,  Up: 改进的模块<2>

1.2.5.39 re
...........

旗标 *note re.ASCII: 3d0, *note re.LOCALE: 3d1. 和 ‘re.UNICODE’ 可以在组
的范围内设置。 （由 Serhiy Storchaka 在 bpo-31690(1) 中贡献。）

*note re.split(): 3d2. 现在支持基于匹配一个空字符串的模式例如 ‘r'\b'’,
‘'^$'’ 或 ‘(?=-)’ 进行拆分。 （由 Serhiy Storchaka 在 bpo-25054(2) 中贡
献。）

使用 *note re.LOCALE: 3d1. 旗标编译的正则表达式不再依赖于编译时的区域设
置。 区域设置仅在已编译正则表达式被使用时才被应用。 （由 Serhiy
Storchaka 在 bpo-30215(3) 中贡献。）

现在如果一个正则表达式包含语义将在未来发生改变的字符集构造，则会引发
*note FutureWarning: 32e.，例如嵌套集与集合操作等。 （由 Serhiy
Storchaka 在 bpo-30349(4) 中贡献。）

已编译正则表达式和匹配对象现在可以使用 *note copy.copy(): 3d3. 和 *note
copy.deepcopy(): 3d4. 进行拷贝。 （由 Serhiy Storchaka 在 bpo-10076(5) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31690

   (2) https://bugs.python.org/issue25054

   (3) https://bugs.python.org/issue30215

   (4) https://bugs.python.org/issue30349

   (5) https://bugs.python.org/issue10076


File: python.info,  Node: signal,  Next: socket<2>,  Prev: re,  Up: 改进的模块<2>

1.2.5.40 signal
...............

*note signal.set_wakeup_fd(): 3d6. 函数新增的 `warn_on_full_buffer' 参数
可以指定当唤醒缓冲区溢出时 Python 是否要在 stderr 上打印警告信息。 （由
Nathaniel J. Smith 在 bpo-30050(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30050


File: python.info,  Node: socket<2>,  Next: socketserver,  Prev: signal,  Up: 改进的模块<2>

1.2.5.41 socket
...............

新增的 *note socket.getblocking(): 3d8. 方法会在套接字处于阻塞模式时返回
‘True’，否则返回 ‘False’。 （由 Yury Selivanov 在 bpo-32373(1) 中贡献。
）

新的 *note socket.close(): 3d9. 函数可关闭所传入的套接字文件描述符。 应
该用此函数来代替 *note os.close(): 3da. 以获得更好的跨平台兼容性。 （由
Christian Heimes 在 bpo-32454(2) 中贡献。）

*note socket: f0. 模块现在会公开 ‘socket.TCP_CONGESTION’ (Linux 2.6.13),
‘socket.TCP_USER_TIMEOUT’ (Linux 2.6.37) 以及 ‘socket.TCP_NOTSENT_LOWAT’
(Linux 3.12) 常量。 （由 Omar Sandoval 在 bpo-26273(3) 以及 Nathaniel J.
Smith 在 bpo-29728(4) 中贡献。）

已加入对 *note socket.AF_VSOCK: 3db. 套接字的支持以允许在虚拟机及其宿主
机之间进行通讯。 （由 Cathy Avery 在 bpo-27584(5) 中贡献。）

套接字现在默认会根据文件描述符自动检测所属族、类型和协议。 （由
Christian Heimes 在 bpo-28134(6) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32373

   (2) https://bugs.python.org/issue32454

   (3) https://bugs.python.org/issue26273

   (4) https://bugs.python.org/issue29728

   (5) https://bugs.python.org/issue27584

   (6) https://bugs.python.org/issue28134


File: python.info,  Node: socketserver,  Next: sqlite3,  Prev: socket<2>,  Up: 改进的模块<2>

1.2.5.42 socketserver
.....................

‘socketserver.ThreadingMixIn.server_close()’ 现在会等待所有非守护线程完
成。 ‘socketserver.ForkingMixIn.server_close()’ 现在会等待所有子进程完成
。

为 *note socketserver.ForkingMixIn: 3dd. 和 *note
socketserver.ThreadingMixIn: 3de. 类增加了新的
‘socketserver.ForkingMixIn.block_on_close’ 类属性。 该类属性值设为
‘False’ 以保持 3.7 之前的行为。


File: python.info,  Node: sqlite3,  Next: ssl<2>,  Prev: socketserver,  Up: 改进的模块<2>

1.2.5.43 sqlite3
................

现在当下层的 SQLite 库版本为 3.6.11 及以上时 *note sqlite3.Connection:
3e0. 会开放 *note backup(): 3e1. 方法。 （由 Lele Gaifax 在 bpo-27645(1)
中贡献。）

*note sqlite3.connect(): 3e2. 的 `database' 参数现在接受任何 *note
path-like object: 373.，而不是只接受字符串。 （由 Anders Lorentsen 在
bpo-31843(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27645

   (2) https://bugs.python.org/issue31843


File: python.info,  Node: ssl<2>,  Next: string,  Prev: sqlite3,  Up: 改进的模块<2>

1.2.5.44 ssl
............

*note ssl: f4. 模块现在使用 OpenSSL 的内置 API 代替 *note
match_hostname(): 3e4. 来检查主机名或 IP 地址。 值的验证会在 TLS 握手期
间进行。 任何证书验证错误包括主机名检查失败现在将引发 *note
SSLCertVerificationError: 3e5. 并使用正确的 TLS Alert 消息中止握手过程。
这个新异常包含有额外的信息。 主机名验证可通过 *note
SSLContext.hostname_checks_common_name: 3e6. 进行自定义。 （由 Christian
Heimes 在 bpo-31399(1) 中贡献。）

     注解: 改进的主机名检测需要有兼容 OpenSSL 1.0.2 或 1.1 的 `libssl' 实
     现。 因此，OpenSSL 0.9.8 和 1.0.1 不再被支持（请参阅 *note
     平台支持的移除: 3e7. 了解详情）。 目前 ssl 模块主要兼容 LibreSSL
     2.7.2 及更高版本。

‘ssl’ 模块不再以 SNI TLS 扩展发送 IP 地址。 （由 Christian Heimes 在
bpo-32185(2) 中贡献。）

*note match_hostname(): 3e4. 不再支持部分通配符例如 ‘www*.example.org’。
（由 Mandeep Singh 在 bpo-23033(3) 以及 Christian Heimes 在 bpo-31399(4)
中贡献。）

‘ssl’ 模块默认的加密套件选择现在是使用黑名单方式而非硬编码的白名单。
Python 不会再重新启用已经被 OpenSSL 安全更新所阻止的加密。 默认的加密套
件选择可以在编译时进行配置。 （由 Christian Heimes 在 bpo-31429(5) 中贡
献。）

现在已支持包含国际化域名 (IDN) 的服务器证书验证。 作为此更改的一部分，
*note SSLSocket.server_hostname: 3e8. 属性现在会以预期的 A 标签形式
(‘"xn--pythn-mua.org"’) 而不是以 U 标签形式 (‘"pythön.org"’) 存储。 （由
Nathaniel J. Smith 与 Christian Heimes 在 bpo-28414(6) 中贡献。）

‘ssl’ 模块对 TLS 1.3 和 OpenSSL 1.1.1 具有初步和实验性的支持。 在 Python
3.7.0 发布的时刻，OpenSSL 1.1.1 仍在开发中，而 TLS 1.3 尚未最终确定。
TLS 1.3 握手和协议行为与 TLS 1.2 及更早的版本略有差异，请参阅 *note TLS
1.3: 3e9.。 （由 Christian Heimes 在 bpo-32947(7), bpo-20995(8),
bpo-29136(9), bpo-30622(10) 以及 bpo-33618(11) 中贡献。）

*note SSLSocket: 3ea. 和 *note SSLObject: 3eb. 不再具有公共构造器。 直接
实例化从未成为有文档和受支持的特性。 实际必须通过 *note SSLContext: 3ec.
的方法 *note wrap_socket(): 3ed. 和 *note wrap_bio(): 3ee. 来创建。 （由
Christian Heimes 在 bpo-32951(12) 中贡献。）

用于设置最小和最大 TLS 协议版本的 OpenSSL 1.1 API 现已可用，名称分别为
*note SSLContext.minimum_version: 3ef. 和 *note
SSLContext.maximum_version: 3f0.。 受支持的协议由几个新增旗标指定，例如
*note HAS_TLSv1_1: 3f1.。 （由 Christian Heimes 在 bpo-32609(13) 中贡献
。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31399

   (2) https://bugs.python.org/issue32185

   (3) https://bugs.python.org/issue23033

   (4) https://bugs.python.org/issue31399

   (5) https://bugs.python.org/issue31429

   (6) https://bugs.python.org/issue28414

   (7) https://bugs.python.org/issue32947

   (8) https://bugs.python.org/issue20995

   (9) https://bugs.python.org/issue29136

   (10) https://bugs.python.org/issue30622

   (11) https://bugs.python.org/issue33618

   (12) https://bugs.python.org/issue32951

   (13) https://bugs.python.org/issue32609


File: python.info,  Node: string,  Next: subprocess,  Prev: ssl<2>,  Up: 改进的模块<2>

1.2.5.45 string
...............

*note string.Template: 3f3. 现在允许你有选择地分别修改带大括号的占位符和
不带大括号的占位符所对应的正则表达式模式。 （由 Barry Warsaw 在
bpo-1198569(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1198569


File: python.info,  Node: subprocess,  Next: sys<2>,  Prev: string,  Up: 改进的模块<2>

1.2.5.46 subprocess
...................

*note subprocess.run(): 3f5. 函数接受新的 `capture_output' 关键字参数。
当其为真值时，将会捕获 stdout 和 stderr。 这相当于将 *note
subprocess.PIPE: 3f6. 作为 `stdout' 和 `stderr' 参数传入。 （由 Bo
Bayles 在 bpo-32102(1) 中贡献。）

‘subprocess.run’ 函数和 *note subprocess.Popen: 2ba. 构造器现在接受
`text' 关键字参数作为 `universal_newlines' 的别名。 （由 Andrew Clegg 在
bpo-31756(2) 中贡献。）

在 Windows 中当重定向标准句柄时 `close_fds' 的默认值由 ‘False’ 改为
‘True’。 现在可以在重定向标准句柄时将 `close_fds' 设为真值。 参阅 *note
subprocess.Popen: 2ba.。 这意味着现在 `close_fds' 在所有受支持的平台上默
认值均为 ‘True’。 （由 Segev Finer 在 bpo-19764(3) 中贡献。）

在 *note subprocess.call(): 3f7, *note subprocess.run(): 3f5. 期间或在
*note Popen: 2ba. 上下文管理器中，subprocess 模块现在能更优雅地处理
*note KeyboardInterrupt: 198.。 它现在会等待一小段时间以便子进程退出，然
后再继续处理 ‘KeyboardInterrupt’ 异常。 （由 Gregory P. Smith 在
bpo-25942(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32102

   (2) https://bugs.python.org/issue31756

   (3) https://bugs.python.org/issue19764

   (4) https://bugs.python.org/issue25942


File: python.info,  Node: sys<2>,  Next: time<2>,  Prev: subprocess,  Up: 改进的模块<2>

1.2.5.47 sys
............

新增 *note sys.breakpointhook(): 31c. 钩子函数，供内置的 *note
breakpoint(): 302. 进行调用。 （由 Barry Warsaw 在 bpo-31353(1) 中贡献。
）

在 Android 中新增的 *note sys.getandroidapilevel(): 3f9. 会返回构建时的
Android API 版本。 （由 Victor Stinner 在 bpo-28740(2) 中贡献。）

新的 *note sys.get_coroutine_origin_tracking_depth(): 3fa. 函数会返回当
前协程的由新的 *note sys.set_coroutine_origin_tracking_depth(): 3fb. 所
设定的原始跟踪深度。 *note asyncio: a. 已转换为使用这个新 API 代替已弃用
的 ‘sys.set_coroutine_wrapper()’。 （由 Nathaniel J. Smith 在
bpo-32591(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31353

   (2) https://bugs.python.org/issue28740

   (3) https://bugs.python.org/issue32591


File: python.info,  Node: time<2>,  Next: tkinter<2>,  Prev: sys<2>,  Up: 改进的模块<2>

1.2.5.48 time
.............

PEP 564(1) 向 *note time: 10b. 模块增加六个具有纳秒级精度的新函数:

   * *note time.clock_gettime_ns(): 327.

   * *note time.clock_settime_ns(): 328.

   * *note time.monotonic_ns(): 329.

   * *note time.perf_counter_ns(): 32a.

   * *note time.process_time_ns(): 32b.

   * *note time.time_ns(): 32c.

增加了新的时钟标识符:

   * *note time.CLOCK_BOOTTIME: 3fd. (Linux): 与 *note
     time.CLOCK_MONOTONIC: 3fe. 相似，不同点在于它还包括任何系统挂起的时
     间。

   * *note time.CLOCK_PROF: 3ff. (FreeBSD, NetBSD 和 OpenBSD): 高精度的
     分进程 CPU 计时器。

   * *note time.CLOCK_UPTIME: 400. (FreeBSD, OpenBSD): 该时间的绝对值是
     系统运行且未挂起的时间，提供准确的正常运行时间度量。

新的 *note time.thread_time(): 401. 和 *note time.thread_time_ns(): 402.
函数可用于获取每线程的 CPU 时间度量。 （由 Antoine Pitrou 在
bpo-32025(2) 中贡献。）

新的 *note time.pthread_getcpuclockid(): 403. 函数会返回特定线程中 CPU 时
钟的时钟 ID。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0564

   (2) https://bugs.python.org/issue32025


File: python.info,  Node: tkinter<2>,  Next: tracemalloc,  Prev: time<2>,  Up: 改进的模块<2>

1.2.5.49 tkinter
................

新的 *note tkinter.ttk.Spinbox: 405. 类现已可用。 （由 Alan Moore 在
bpo-32585(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32585


File: python.info,  Node: tracemalloc,  Next: types,  Prev: tkinter<2>,  Up: 改进的模块<2>

1.2.5.50 tracemalloc
....................

*note tracemalloc.Traceback: 407. 的行为更接近正规的回溯，会对所有帧按从
最旧到最新来排序。 *note Traceback.format(): 408. 现在接受负的 `limit'，
并会将结果截短至排在第 ‘abs(limit)’ 位的旧帧。 如果要获得旧的行为，请在
‘Traceback.format()’ 中使用新的 `most_recent_first' 参数。 （由 Jesse
Bakker 在 bpo-32121(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32121


File: python.info,  Node: types,  Next: unicodedata<2>,  Prev: tracemalloc,  Up: 改进的模块<2>

1.2.5.51 types
..............

新的 *note WrapperDescriptorType: 40a, *note MethodWrapperType: 40b,
*note MethodDescriptorType: 40c. 和 *note ClassMethodDescriptorType:
40d. 类现已可用。 （由 Manuel Krebber 和 Guido van Rossum 在
bpo-29377(1) 以及 Serhiy Storchaka 在 bpo-32265(2) 中贡献。）

新的 *note types.resolve_bases(): 40e. 函数会以 PEP 560(3) 所规定的方式
动态解析 MRO 条目。 （由 Ivan Levkivskyi 在 bpo-32717(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29377

   (2) https://bugs.python.org/issue32265

   (3) https://www.python.org/dev/peps/pep-0560

   (4) https://bugs.python.org/issue32717


File: python.info,  Node: unicodedata<2>,  Next: unittest<2>,  Prev: types,  Up: 改进的模块<2>

1.2.5.52 unicodedata
....................

内部的 *note unicodedata: 11b. 数据库已升级为使用 Unicode 11(1)。 （由
Benjamin Peterson 贡献。）

   ---------- Footnotes ----------

   (1) http://www.unicode.org/versions/Unicode11.0.0/


File: python.info,  Node: unittest<2>,  Next: unittest mock,  Prev: unicodedata<2>,  Up: 改进的模块<2>

1.2.5.53 unittest
.................

新的 ‘-k’ 命令行选项允许通过名称子字符串或类似于 Unix shell 的模式来筛选
测试项。 例如，‘python -m unittest -k foo’ 将运行
‘foo_tests.SomeTest.test_something’, ‘bar_tests.SomeTest.test_foo’，但不
会运行 ‘bar_tests.FooTest.test_something’。 （由 Jonas Haag 在
bpo-32071(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32071


File: python.info,  Node: unittest mock,  Next: urllib parse<2>,  Prev: unittest<2>,  Up: 改进的模块<2>

1.2.5.54 unittest.mock
......................

现在 *note sentinel: 412. 属性会在它们被 *note 复制: 26. 或 *note 封存:
cb. 时保存其标识。 （由 Serhiy Storchaka 在 bpo-20804(1) 中贡献。）

新的 *note seal(): 413. 函数允许 *note Mock: 24a. 对实例进行密封，这将禁
止进一步创建属性模拟。 密封会以递归方式应用于自身模拟的所有属性。 （由
Mario Corchero 在 bpo-30541(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20804

   (2) https://bugs.python.org/issue30541


File: python.info,  Node: urllib parse<2>,  Next: uu,  Prev: unittest mock,  Up: 改进的模块<2>

1.2.5.55 urllib.parse
.....................

*note urllib.parse.quote(): 415. 已经从 RFC 2396(1) 更新为 RFC 3986(2)，
将 ‘~’ 添加到默认情况下从未引用的字符集。 （由 Christian Theune 和
Ratnadeep Debnath 在 bpo-16285(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2396.html

   (2) https://tools.ietf.org/html/rfc3986.html

   (3) https://bugs.python.org/issue16285


File: python.info,  Node: uu,  Next: uuid,  Prev: urllib parse<2>,  Up: 改进的模块<2>

1.2.5.56 uu
...........

*note uu.encode(): 417. 函数现在接受可选的 `backtick' 关键字参数。 当其
为真时，零会以 ‘'`'’ 而非空格来表示。 （由 Xiang Zhang 在 bpo-30103(1) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30103


File: python.info,  Node: uuid,  Next: warnings,  Prev: uu,  Up: 改进的模块<2>

1.2.5.57 uuid
.............

新的 *note UUID.is_safe: 419. 属性会从平台中继有关是否使用多进程安全模式
来生成所需 UUID 的信息。 （由 Barry Warsaw 在 bpo-22807(1) 中贡献。）

*note uuid.getnode(): 41a. 现在更倾向于统一管理的 MAC 地址而不是本地管理
的 MAC 地址。 这样可以更好地保证从 *note uuid.uuid1(): 41b. 返回的 UUID
的全局唯一性。 如果只有本地管理的 MAC 地址可用，则返回首个找到的此类地址
。 （由 Barry Warsaw 在 bpo-32107(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22807

   (2) https://bugs.python.org/issue32107


File: python.info,  Node: warnings,  Next: xml etree,  Prev: uuid,  Up: 改进的模块<2>

1.2.5.58 warnings
.................

默认警告过滤器的初始化已进行以下更改:

   * 通过命令行选项（包括 *note -b: 41d. 以及新的 CPython 专属的 *note
     -X: 156. ‘dev’ 选项）启用的警告总是会通过 *note sys.warnoptions:
     41e. 属性被传递给警告机制。

   * 通过命令行或环境变量启用的警告过滤器现在具有以下优先顺序:

             * 用于 *note -b: 41d. (或 ‘-bb’) 的 ‘BytesWarning’ 过滤器

             * 通过 *note -W: 41f. 选项指定的任何过滤器

             * 通过 *note PYTHONWARNINGS: 420. 环境变量指定的任何过滤器

             * 任何其他 CPython 专属过滤器（例如 ‘-X dev’ 模式中新增的
               ‘default’ 过滤器）

             * 由警告机制所定义的任何隐式过滤器

   * 在 CPython 调试版本中，现在默认情况下会显示所有警告（隐式过滤器列表
     为空）

（由 Nick Coghlan 和 Victor Stinner 在 bpo-20361(1), bpo-32043(2) 以及
bpo-32230(3) 中贡献。）

在单文件脚本和交互式提示符中，默认情况下会再次显示已弃用警告。 详情参见
*note PEP 565; 在 __main__ 中显示 DeprecationWarning: 30c.。 （由 Nick
Coghlan 在 bpo-31975(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20361

   (2) https://bugs.python.org/issue32043

   (3) https://bugs.python.org/issue32230

   (4) https://bugs.python.org/issue31975


File: python.info,  Node: xml etree,  Next: xmlrpc server,  Prev: warnings,  Up: 改进的模块<2>

1.2.5.59 xml.etree
..................

‘find()’ 方法中的 *note ElementPath: 422. 描述词现在可以将当前节点文本与
‘[. = "text"]’ 进行比较，而不仅是子节点中的文本。 描述词还允许添加空格以
提高可读性。 （由 Stefan Behnel 在 bpo-31648(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31648


File: python.info,  Node: xmlrpc server,  Next: zipapp,  Prev: xml etree,  Up: 改进的模块<2>

1.2.5.60 xmlrpc.server
......................

‘SimpleXMLRPCDispatcher.register_function’ 现在可以被用作装饰器。 （由
Xiang Zhang 在 bpo-7769(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7769


File: python.info,  Node: zipapp,  Next: zipfile,  Prev: xmlrpc server,  Up: 改进的模块<2>

1.2.5.61 zipapp
...............

函数 *note create_archive(): 425. 现在接受可选的 `filter' 参数，以允许用
户选择哪些文件应被加入归档包。 （由 Irmen de Jong 在 bpo-31072(1) 中贡献
。）

函数 *note create_archive(): 425. 现在接受可选的 `compressed' 参数，以生
成压缩归档包。 另外也加入了命令行选项 ‘--compress’ 以支持压缩。 （由
Zhiming Wang 在 bpo-31638(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31072

   (2) https://bugs.python.org/issue31638


File: python.info,  Node: zipfile,  Prev: zipapp,  Up: 改进的模块<2>

1.2.5.62 zipfile
................

*note ZipFile: 427. 现在接受新的 `compresslevel' 形参，以控制压缩级别。
（由 Bo Bayles 在 bpo-21417(1) 中贡献。）

‘ZipFile’ 所创建的归档包中的子目录现在会按字母表顺序保存。 （由 Bernhard
M. Wiedemann 在 bpo-30693(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21417

   (2) https://bugs.python.org/issue30693


File: python.info,  Node: C API 的改变,  Next: 构建的改变,  Prev: 改进的模块<2>,  Up: Python 3 7 有什么新变化

1.2.6 C API 的改变
------------------

已实现了用于线程本地存储的新 API。 相关概述请参阅 *note PEP 539;
用于线程局部存储的新 C API: 30d.，完整参考文档请查看 *note Thread
Specific Storage (TSS) API: 320.。 （由 Masayuki Yamamoto 在
bpo-25658(1) 中贡献。)

新的 *note 上下文变量: 2fe. 功能开放了许多 *note 新的 C API: 344.。

新的 *note PyImport_GetModule(): 429. 函数会返回之前所导入的具有给定名称
的模块。 （由 Eric Snow 在 bpo-28411(2) 中贡献。）

新的 *note Py_RETURN_RICHCOMPARE: 42a. 宏可以简化丰富比较函数的编写。 （
由 Petr Victorin 在 bpo-23699(3) 中贡献。）

新的 *note Py_UNREACHABLE: 42b. 宏可用于标记不可到达的代码路径。 （由
Barry Warsaw 在 bpo-31338(4) 中贡献。）

*note tracemalloc: 115. 现在通过新的 *note PyTraceMalloc_Track(): 42c. 和
*note PyTraceMalloc_Untrack(): 42d. 函数公开了一个 C API。 （由 Victor
Stinner 在 bpo-30054(5) 中贡献。）

新的 ‘import__find__load__start()’ 和 ‘import__find__load__done()’ 静态
标记可用于跟踪模块导入。 （由 Christian Heimes 在 bpo-31574(6) 中贡献。
）

结构体 *note PyMemberDef: 42e, *note PyGetSetDef: 42f, *note
PyStructSequence_Field: 430, *note PyStructSequence_Desc: 431. 和
‘wrapperbase’ 的字段 ‘name’ 和 ‘doc’ 现在的类型为 ‘const char *’ 而不是
‘char *’。 （由 Serhiy Storchaka 在 bpo-28761(7) 中贡献。）

*note PyUnicode_AsUTF8AndSize(): 432. 和 *note PyUnicode_AsUTF8(): 433.
的结果类型现在是 ‘const char *’ 而非 ‘char *’。 （由 Serhiy Storchaka 在
bpo-28769(8) 中贡献。）

*note PyMapping_Keys(): 434, *note PyMapping_Values(): 435. 和 *note
PyMapping_Items(): 436. 的结果现在肯定是列表，而非可能是列表也可能是元组
。 （由 Oren Milman 在 bpo-28280(9) 中贡献。）

添加了函数 *note PySlice_Unpack(): 437. 和 *note
PySlice_AdjustIndices(): 438.。 （由 Serhiy Storchaka 在 bpo-27867(10) 中
贡献。）

*note PyOS_AfterFork(): 439. 已弃用，建议改用新的 functions *note
PyOS_BeforeFork(): 43a, *note PyOS_AfterFork_Parent(): 43b. 和 *note
PyOS_AfterFork_Child(): 2ce.。 （由 Antoine Pitrou 在 bpo-16500(11) 中贡
献。）

曾经作为公共 API 一部分的 ‘PyExc_RecursionErrorInst’ 单例已被移除，因为
它的成员永远不会被清理，可能在解释器的最终化过程中导致段错误。 由 Xavier
de Gaye 在 bpo-22898(12) 和 bpo-30697(13) 中贡献。

添加 C API 对使用 timezone 的构造器 *note PyTimeZone_FromOffset(): 43c.
和 *note PyTimeZone_FromOffsetAndName(): 43d. 的时区的支持，以及通常
*note PyDateTime_TimeZone_UTC: 43e. 使用 UTC 单例。 由 Paul Ganssle 在
bpo-10381(14) 中贡献。

‘PyThread_start_new_thread()’ 和 ‘PyThread_get_thread_ident()’ 的结果类
型以及 *note PyThreadState_SetAsyncExc(): 43f. 的 `id' 参数类型由 ‘long’
改为 ‘unsigned long’。 （由 Serhiy Storchaka 在 bpo-6532(15) 中贡献。）

现在 *note PyUnicode_AsWideCharString(): 440. 如果第二个参数为 ‘NULL’ 并
且 ‘wchar_t*’ 字符串包含空字符则会引发 *note ValueError: 1fc.。 （由
Serhiy Storchaka 在 bpo-30708(16) 中贡献。）

对启动顺序以及动态内存分配器管理的更改意味着早已记录在案的，对在调用大多
数 C API 函数之前调用 *note Py_Initialize(): 441. 的要求的依赖现在变得更
加强烈，未遵循此要求可能导致嵌入式应用程序中的段错误。 请参阅此文档的
*note 移植到 Python 3.7: 310. 一节以及 C API 文档的 *note
在Python初始化之前: 442. 一节了解更多细节。

新的 *note PyInterpreterState_GetID(): 443. 会返回给定解释器的唯一 ID。
（由 Eric Snow 在 bpo-29102(17) 中贡献。）

现在当启用 *note UTF-8 模式: 309. 时 *note Py_DecodeLocale(): 444, *note
Py_EncodeLocale(): 445. 会使用 UTF-8 编码。 （由 Victor Stinner 在
bpo-29240(18) 中贡献。）

*note PyUnicode_DecodeLocaleAndSize(): 446. 和 *note
PyUnicode_EncodeLocale(): 447. 现在会为 ‘surrogateescape’ 错误句柄使用当
前区域编码。 （由 Victor Stinner 在 bpo-29240(19) 中贡献。）

*note PyUnicode_FindChar(): 448. 的 `start' 和 `end' 形参的行为现在调整
为与字符串切片类似。 （由 Xiang Zhang 在 bpo-28822(20) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25658

   (2) https://bugs.python.org/issue28411

   (3) https://bugs.python.org/issue23699

   (4) https://bugs.python.org/issue31338

   (5) https://bugs.python.org/issue30054

   (6) https://bugs.python.org/issue31574

   (7) https://bugs.python.org/issue28761

   (8) https://bugs.python.org/issue28769

   (9) https://bugs.python.org/issue28280

   (10) https://bugs.python.org/issue27867

   (11) https://bugs.python.org/issue16500

   (12) https://bugs.python.org/issue22898

   (13) https://bugs.python.org/issue30697

   (14) https://bugs.python.org/issue10381

   (15) https://bugs.python.org/issue6532

   (16) https://bugs.python.org/issue30708

   (17) https://bugs.python.org/issue29102

   (18) https://bugs.python.org/issue29240

   (19) https://bugs.python.org/issue29240

   (20) https://bugs.python.org/issue28822


File: python.info,  Node: 构建的改变,  Next: 性能优化<2>,  Prev: C API 的改变,  Up: Python 3 7 有什么新变化

1.2.7 构建的改变
----------------

对于 ‘--without-threads’ 构建的支持已被移除。 *note threading: 10a. 模块
现在将总是可用。 （由 Antoine Pitrou 在 bpo-31370(1) 中贡献。）

在非 OSX UNIX 平台上已不再包含用于构建 *note _ctypes: 2b. 模块的完整
libffi 副本。 现在当在此类平台上构建 ‘_ctypes’ 时需要事先装有 libffi 的
副本。 （由 Zachary Ware 在 bpo-27979(2) 中贡献。）

Windows 构建过程不再依赖 Subversion 来拉取外部源码，而是改用一段 Python
脚本从 GitHub 下载 zip 文件。 如果未在系统中找到 Python 3.6 (通过 ‘py
-3.6’)，则会使用 NuGet 下载一份 32 位的 Python 副本用于此目的。 （由
Zachary Ware 在 bpo-30450(3) 中贡献。）

*note ssl: f4. 模块需要兼容 OpenSSL 1.0.2 或 1.1 的 libssl。 OpenSSL
1.0.1 的生命期已于 2016-12-31 终止且不再受支持。 LibreSSL 暂时也不受支持
。 LibreSSL 发布版直到 2.6.4 版还缺少所需的 OpenSSL 1.0.2 API。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31370

   (2) https://bugs.python.org/issue27979

   (3) https://bugs.python.org/issue30450


File: python.info,  Node: 性能优化<2>,  Next: 其他 CPython 实现的改变,  Prev: 构建的改变,  Up: Python 3 7 有什么新变化

1.2.8 性能优化
--------------

通过移植更多代码来使用 ‘METH_FASTCALL’ 的约定，可以显著地减少调用 C 代码
中实现的各类标准库的很多方法的开销。 （由 Victor Stinner 在
bpo-29300(1)、bpo-29507(2)、bpo-29452(3) 以及 bpo-29286(4) 中贡献。）

通过各种优化方式，使 Python 在 Linux 上的启动时间缩短了 10%，在 macOS 上
缩短了 30%。 （由 Victor Stinner, INADA Naoki 在 bpo-29585(5) 中，以及
Ivan Levkivskyi 在 bpo-31333(6) 中贡献。）

由于避免创建绑定方法案例的字节码更改，方法调用速度现在加快了 20%。 （由
Yury Selivanov 和 INADA Naoki 在 bpo-26110(7) 中贡献。） 对 *note
asyncio: a. 模块里面的一些常用函数做了显著的性能优化。

   * *note asyncio.get_event_loop(): 35e. 函数已经改用 C 重新实现，使其
     执行速度加快了 15 倍。 （由 Yury Selivanov 在 bpo-32296(8) 中贡献。
     ）

   * *note asyncio.Future: 44b. 回调管理已经过优化。 （由 Yury Selivanov
     在 bpo-32348(9) 中贡献。）

   * *note asyncio.gather(): 287. 的执行速度现在加快了 15%。 （由 Yury
     Selivanov 在 bpo-32355(10) 中贡献。）

   * 当 `delay' 参数为零或负值时 *note asyncio.sleep(): 286. 的执行速度
     现在加快了 2 倍。 （由 Andrew Svetlov 在 bpo-32351(11) 中贡献。）

   * asyncio 调试模式的执行开销已获减轻。 （由 Antoine Pitrou 在
     bpo-31970(12) 中贡献。）

作为 *note PEP 560 工作: 304. 的结果，*note typing: 11a. 的导入时间已减
少了 7 倍，许多与类型相关的操作现在会执行得更快。 （由 Ivan Levkivskyi 在
bpo-32226(13) 中贡献。）

*note sorted(): 44c. 和 *note list.sort(): 44d. 已经过优化，在通常情况下
执行速度可提升 40-75%。 （由 Elliot Gorokhovsky 在 bpo-28685(14) 中贡献
。）

*note dict.copy(): 44e. 的执行速度现在加快了 5.5 倍。 （由 Yury
Selivanov 在 bpo-31179(15) 中贡献。）

当 `name' 未找到并且 `obj' 未重载 *note object.__getattr__(): 323. 或
*note object.__getattribute__(): 44f. 时 *note hasattr(): 450. 和 *note
getattr(): 451. 现在会比原来快大约 4 倍。 （由 INADA Naoki 在
bpo-32544(16) 中贡献。）

在字符串中搜索特定的 Unicode 字符（例如乌克兰语字母“Є”）会比搜索其他字符
慢上 25 倍。 而现在最坏情况下也只会慢上 3 倍。 （由 Serhiy Storchaka 在
bpo-24821(17) 中贡献。）

*note collections.namedtuple(): 1b7. 工厂对象已经重写实现，使得创建具名
元组的速度加快了 4 到 6 倍。 （由 Jelle Zijlstra 在 bpo-28638(18) 中贡献
，进一步的改进由 INADA Naoki, Serhiy Storchaka 和 Raymond Hettinger 贡献
。）

现在 ‘date.fromordinal()’ 和 ‘date.fromtimestamp()’ 在通常情况下执行速度
可提升 30%。 （由 Paul Ganssle 在 bpo-32403(19) 中贡献。）

由于使用了 *note os.scandir(): 260.，现在 *note os.fwalk(): 3bc. 函数执
行速度提升了 2 倍。 （由 Serhiy Storchaka 在 bpo-25996(20) 中贡献。）

由于使用了 *note os.scandir(): 260. 函数，*note shutil.rmtree(): 21d. 函
数的执行速度已经提升了 20–40%。 （由 Serhiy Storchaka 在 bpo-28564(21) 中
贡献。）

*note 正则表达式: de. 忽略大小写的匹配和搜索已获得优化。 现在搜索某些模
式的速度提升了 20 倍。 （由 Serhiy Storchaka 在 bpo-30285(22) 中贡献。）

*note re.compile(): 452. 现在会将 ‘flags’ 形参转换为 int 对象，如果它是
‘RegexFlag’ 的话。 它现在会和 Python 3.5 一样快，而比 Python 3.6 快大约
10%，实际速度取决于具体的模式。 （由 INADA Naoki 在 bpo-31671(23) 中贡献
。）

*note selectors.EpollSelector: 453, *note selectors.PollSelector: 454. 和
*note selectors.DevpollSelector: 455. 这几个类的 *note modify(): 456. 方
法在重负载下可以加快 10% 左右。 （由 Giampaolo Rodola’ 在 bpo-30014(24)
中贡献。）

常量折叠已经从窥孔优化器迁移至新的 AST 优化器，后者可以以更高的一致性来
执行优化。 （由 Eugene Toder 和 INADA Naoki 在 bpo-29469(25) 和
bpo-11549(26) 中贡献。）

*note abc: 4. 中的大部分函数和方法已经用 C 重写。 这使得创建抽像基类以及
调用其 *note isinstance(): 457. 和 *note issubclass(): 458. 的速度加快了
1.5 倍。 这也使得 Python 启动耗时减少了 10%。 （由 Ivan Levkivskyi 和
INADA Naoki 在 bpo-31333(27) 中贡献。）

在不构造子类时，通过使用快速路径构造器使得 *note datetime.date: 194. 和
*note datetime.datetime: 195. 的替代构造器获得了显著的速度提升。 （由
Paul Ganssle 在 bpo-32403(28) 中贡献。）

在特定情况下 *note array.array: 459. 实例的比较速度已获得很大提升。 现在
当比较存放相同的整数类型的值的数组时会比原来快 10 到 70 倍。 （由 Adrian
Wielgosik 在 bpo-24700(29) 中贡献。）

在大多数平台上 *note math.erf(): 45a. 和 *note math.erfc(): 45b. 函数现
在使用（更快的）C 库实现。 （由 Serhiy Storchaka 在 bpo-26121(30) 中贡献
。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29300

   (2) https://bugs.python.org/issue29507

   (3) https://bugs.python.org/issue29452

   (4) https://bugs.python.org/issue29286

   (5) https://bugs.python.org/issue29585

   (6) https://bugs.python.org/issue31333

   (7) https://bugs.python.org/issue26110

   (8) https://bugs.python.org/issue32296

   (9) https://bugs.python.org/issue32348

   (10) https://bugs.python.org/issue32355

   (11) https://bugs.python.org/issue32351

   (12) https://bugs.python.org/issue31970

   (13) https://bugs.python.org/issue32226

   (14) https://bugs.python.org/issue28685

   (15) https://bugs.python.org/issue31179

   (16) https://bugs.python.org/issue32544

   (17) https://bugs.python.org/issue24821

   (18) https://bugs.python.org/issue28638

   (19) https://bugs.python.org/issue32403

   (20) https://bugs.python.org/issue25996

   (21) https://bugs.python.org/issue28564

   (22) https://bugs.python.org/issue30285

   (23) https://bugs.python.org/issue31671

   (24) https://bugs.python.org/issue30014

   (25) https://bugs.python.org/issue29469

   (26) https://bugs.python.org/issue11549

   (27) https://bugs.python.org/issue31333

   (28) https://bugs.python.org/issue32403

   (29) https://bugs.python.org/issue24700

   (30) https://bugs.python.org/issue26121


File: python.info,  Node: 其他 CPython 实现的改变,  Next: 已弃用的 Python 行为,  Prev: 性能优化<2>,  Up: Python 3 7 有什么新变化

1.2.9 其他 CPython 实现的改变
-----------------------------

   * 跟踪钩子现在可以选择不接收 ‘line’ 而是选择从解释器接收 ‘opcode’ 事
     件，具体做法是在被跟踪的帧上相应地设置新的 ‘f_trace_lines’ 和
     ‘f_trace_opcodes’ 属性。 （由 Nick Coghlan 在 bpo-31344(1) 中贡献。
     ）

   * 修复了一些命名空间包模块属性的一致性问题。 命名空间模块对象的
     ‘__file__’ 被设置为 ‘None’ (原先未设置)，对象的 ‘__spec__.origin’ 也
     被设置为 ‘None’ (之前为字符串 ‘"namespace"’)。 参见 bpo-32305(2)。
     而且，命名空间模块对象的 ‘__spec__.loader’ 被设置的值与
     ‘__loader__’ 相同 (原先前者被设置为 ‘None’)。 参见 bpo-32303(3)。

   * *note locals(): 45d. 字典现在以变量定义的词法顺序显示。 原先未定义
     顺序。 （由 Raymond Hettinger 在 bpo-32690(4) 中贡献。）

   * *note distutils: 39. ‘upload’ 命令不会再试图将行结束字符 CR 改为
     CRLF。 这修复了 sdists 的一个以与 CR 等价的字节结束的数据损坏问题。
     （由 Bo Bayles 在 bpo-32304(5) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31344

   (2) https://bugs.python.org/issue32305

   (3) https://bugs.python.org/issue32303

   (4) https://bugs.python.org/issue32690

   (5) https://bugs.python.org/issue32304


File: python.info,  Node: 已弃用的 Python 行为,  Next: 已弃用的 Python 模块、函数和方法,  Prev: 其他 CPython 实现的改变,  Up: Python 3 7 有什么新变化

1.2.10 已弃用的 Python 行为
---------------------------

在推导式和生成器表达式中的 yield 语句（包括 ‘yield’ 和 ‘yield from’ 子句
）现在已弃用（最左端的 ‘for’ 子句中的可迭代对象表达式除外）。 这确保了推
导式总是立即返回适当类型的容器（而不是有可能返回 *note generator
iterator: 45f. 对象），这样生成器表达式不会试图将它们的隐式输出与任何来
自显式 yield 表达式的输出交错起来。 在 Python 3.7 中，这样的表达式会在编
译时引发 *note DeprecationWarning: 279.，在 Python 3.8 中则将引发 *note
SyntaxError: 460.。 （由 Serhiy Storchaka 在 bpo-10544(1) 中贡献。）

从 *note object.__complex__(): 18e. 返回一个 *note complex: 18a. 的子类
的行为已弃用并将在未来的 Python 版本中引发错误。 这使得 ‘__complex__()’
的行为与 *note object.__int__(): 18c. 和 *note object.__float__(): 18d.
保持一致。 （由 Serhiy Storchaka 在 bpo-28894(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10544

   (2) https://bugs.python.org/issue28894


File: python.info,  Node: 已弃用的 Python 模块、函数和方法,  Next: 已弃用的 C API 函数和类型,  Prev: 已弃用的 Python 行为,  Up: Python 3 7 有什么新变化

1.2.11 已弃用的 Python 模块、函数和方法
---------------------------------------

* Menu:

* aifc::
* asyncio: asyncio<3>.
* collections: collections<3>.
* dbm: dbm<2>.
* enum: enum<2>.
* gettext: gettext<2>.
* importlib: importlib<2>.
* locale: locale<2>.
* macpath::
* threading: threading<2>.
* socket: socket<3>.
* ssl: ssl<3>.
* sunau::
* sys: sys<3>.
* wave::


File: python.info,  Node: aifc,  Next: asyncio<3>,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.1 aifc
.............

‘aifc.openfp()’ 已弃用并将在 Python 3.9 中被移除。 请改用 *note
aifc.open(): 463.。 （由 Brian Curtin 在 bpo-31985(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31985


File: python.info,  Node: asyncio<3>,  Next: collections<3>,  Prev: aifc,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.2 asyncio
................

对 *note asyncio.Lock: 28c. 和其他 asyncio 同步原语的 ‘await’ 实例的直接
支持已弃用。 想要获取并释放同步资源必须使用异步上下文管理器。 （由
Andrew Svetlov 在 bpo-32253(1) 中贡献。）

*note asyncio.Task.current_task(): 35b. 和 *note
asyncio.Task.all_tasks(): 35c. 方法已弃用。 （由 Andrew Svetlov 在
bpo-32250(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32253

   (2) https://bugs.python.org/issue32250


File: python.info,  Node: collections<3>,  Next: dbm<2>,  Prev: asyncio<3>,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.3 collections
....................

在 Python 3.8 中，*note collections.abc: 1f. 内的抽象基类将不会再通过常
规的 *note collections: 1e. 模块公开。 这有助于更清晰地区别具体类与抽象
基类。 （由 Serhiy Storchaka 在 bpo-25988(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25988


File: python.info,  Node: dbm<2>,  Next: enum<2>,  Prev: collections<3>,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.4 dbm
............

*note dbm.dumb: 33. 现在支持读取只读文件，且当其未被更改时不会再写入索引
文件。 现在如果索引文件丢失并在 ‘'r'’ 与 ‘'w'’ 模式下被重新创建，则会发
出已弃用警告（在未来的 Python 发布版中将改为错误）。 （由 Serhiy
Storchaka 在 bpo-28847(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28847


File: python.info,  Node: enum<2>,  Next: gettext<2>,  Prev: dbm<2>,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.5 enum
.............

在 Python 3.8 中，尝试在 ‘Enum’ 类中检查非 Enum 对象将引发 *note
TypeError: 193. (例如 ‘1 in Color’)；类似地，尝试在 ‘Flag’ 成员中检查非
Flag 对象也将引发 *note TypeError: 193. (例如 ‘1 in Perm.RW’)；目前，两
种操作均会返回 *note False: 390.。 （由 Ethan Furman 在 bpo-33217(1) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33217


File: python.info,  Node: gettext<2>,  Next: importlib<2>,  Prev: enum<2>,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.6 gettext
................

使用非整数值在 *note gettext: 89. 中选择复数形式现在已弃用。 它从未正确
地发挥作用。 （由 Serhiy Storchaka 在 bpo-28692(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28692


File: python.info,  Node: importlib<2>,  Next: locale<2>,  Prev: gettext<2>,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.7 importlib
..................

下列方法 *note MetaPathFinder.find_module(): 46a. (被 *note
MetaPathFinder.find_spec() 替代: 46b.) 和 *note
PathEntryFinder.find_loader(): 46c. (被 *note
PathEntryFinder.find_spec() 替代: 46d.) 都在 Python 3.4 中已弃用，现在会
引发 *note DeprecationWarning: 279.。 （由 Matthias Bussonnier 在
bpo-29576(1) 中贡献）

*note importlib.abc.ResourceLoader: 46e. ABC 已弃用，推荐改用 *note
importlib.abc.ResourceReader: 34b.。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29576


File: python.info,  Node: locale<2>,  Next: macpath,  Prev: importlib<2>,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.8 locale
...............

*note locale.format(): 470. 已弃用，请改用 *note locale.format_string():
3ac.。 （由 Garvit 在 bpo-10379(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10379


File: python.info,  Node: macpath,  Next: threading<2>,  Prev: locale<2>,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.9 macpath
................

‘macpath’ 现在已弃用，将在 Python 3.8 中被移除。 （由 Chi Hsuan Yen 在
bpo-9850(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9850


File: python.info,  Node: threading<2>,  Next: socket<3>,  Prev: macpath,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.10 threading
...................

*note dummy_threading: 68. 和 *note _dummy_thread: 2. 已弃用。 构建禁用
线程的 Python 已不再可能。 请改用 *note threading: 10a.。 （由 Antoine
Pitrou 在 bpo-31370(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31370


File: python.info,  Node: socket<3>,  Next: ssl<3>,  Prev: threading<2>,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.11 socket
................

*note socket.htons(): 474. 和 *note socket.ntohs(): 475. 中的静默参数截
断已弃用。 在未来的 Python 版本中，如果传入的参数长度大于 16 比特位，将
会引发异常。 （由 Oren Milman 在 bpo-28332(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28332


File: python.info,  Node: ssl<3>,  Next: sunau,  Prev: socket<3>,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.12 ssl
.............

*note ssl.wrap_socket(): 477. 已弃用。 请改用 *note
ssl.SSLContext.wrap_socket(): 3ed.。 （由 Christian Heimes 在
bpo-28124(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28124


File: python.info,  Node: sunau,  Next: sys<3>,  Prev: ssl<3>,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.13 sunau
...............

*note sunau.openfp(): 479. 已弃用并将在 Python 3.9 中被移除。 请改用
*note sunau.open(): 47a.。 （由 Brian Curtin 在 bpo-31985(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31985


File: python.info,  Node: sys<3>,  Next: wave,  Prev: sunau,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.14 sys
.............

已弃用 ‘sys.set_coroutine_wrapper()’ 和 ‘sys.get_coroutine_wrapper()’。

未写入文档的 ‘sys.callstats()’ 函数已弃用并将在未来的 Python 版本中被移
除。 （由 Victor Stinner 在 bpo-28799(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28799


File: python.info,  Node: wave,  Prev: sys<3>,  Up: 已弃用的 Python 模块、函数和方法

1.2.11.15 wave
..............

*note wave.openfp(): 47d. 已弃用并将在 Python 3.9 中被移除。 请改用
*note wave.open(): 47e.。 （由 Brian Curtin 在 bpo-31985(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31985


File: python.info,  Node: 已弃用的 C API 函数和类型,  Next: 平台支持的移除,  Prev: 已弃用的 Python 模块、函数和方法,  Up: Python 3 7 有什么新变化

1.2.12 已弃用的 C API 函数和类型
--------------------------------

如果 ‘Py_LIMITED_API’ 未设定或设定为范围在 ‘0x03050400’ 和 ‘0x03060000’
(不含) 之间，或为 ‘0x03060100’ 或更高的值，函数 *note
PySlice_GetIndicesEx(): 480. 已弃用并被一个宏所替代。 （由 Serhiy
Storchaka 在 bpo-27867(1) 中贡献。）

*note PyOS_AfterFork(): 439. 已弃用。 请改用 *note PyOS_BeforeFork():
43a, *note PyOS_AfterFork_Parent(): 43b. 或 *note
PyOS_AfterFork_Child(): 2ce.。 （由 Antoine Pitrou 在 bpo-16500(2) 中贡
献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27867

   (2) https://bugs.python.org/issue16500


File: python.info,  Node: 平台支持的移除,  Next: API 与特性的移除<2>,  Prev: 已弃用的 C API 函数和类型,  Up: Python 3 7 有什么新变化

1.2.13 平台支持的移除
---------------------

   * 官方已不再支持 FreeBSD 9 及更旧的版本。

   * 为了完整的 Unicode 支持，包括在扩展模块之内，*nix 平台现在至少应当
     提供 ‘C.UTF-8’ (完整区域), ‘C.utf8’ (完整区域) 或 ‘UTF-8’
     (‘LC_CTYPE’ 专属区域) 中的一个作为基于 ‘ASCII’ 的传统 ‘C’ 区域的替
     代。

   * OpenSSL 0.9.8 和 1.0.1 已不再受支持，这意味着在仍然使用这些版本的旧
     平台上构建带有 SSL/TLS 支持的 CPython 3.7 时，需要自定义构建选项以
     链接到更新的 OpenSSL 版本。

     注意，此问题会影响到 Debian 8 (代号“jessie”) 和 Ubuntu 14.04 (代号
     “Trusty”) 等长期支持 Linux 发行版，因为它们默认仍然使用 OpenSSL
     1.0.1。

     Debian 9 (“stretch”) 和 Ubuntu 16.04 (“xenial”) 以及其他最新的长期
     支持 Linux 发行版 (例如 RHEL/CentOS 7.5, SLES 12-SP3) 都使用
     OpenSSL 1.0.2 或更新的版本，因此继续在默认的构建配置中受到支持。

     CPython 自己的 CI 配置文件(1) 提供了一个使用 CPython 测试套件中的
     SSL 兼容性测试架构(2) 基于 OpenSSL 1.1.0 进行构建和链接的例子，而不
     是使用过时的系统所提供的 OpenSSL。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/.travis.yml

   (2) 
https://github.com/python/cpython/tree/3.8/Tools/ssl/multissltests.py


File: python.info,  Node: API 与特性的移除<2>,  Next: 移除的模块,  Prev: 平台支持的移除,  Up: Python 3 7 有什么新变化

1.2.14 API 与特性的移除
-----------------------

下列特性与 API 已从 Python 3.7 中移除:

   * ‘os.stat_float_times()’ 函数已被移除。 它在 Python 2.3 中被引入用于
     向下兼容 Python 2.2，并自 Python 3.1 起就已弃用。

   * 在 *note re.sub(): 483. 的替换模块中由 ‘'\'’ 与一个 ASCII 字母构成
     的未知转义在 Python 3.5 中已弃用，现在将会引发错误。

   * 在 *note tarfile.TarFile.add(): 484. 中移除了对 `exclude' 参数的支
     持。 它在 Python 2.7 和 3.2 中已弃用。 请改用 `filter' 参数。

   * ‘ntpath’ 模块中的 ‘splitunc()’ 函数在 Python 3.1 中已弃用，现在已被
     移除。 请改用 *note splitdrive(): 485. 函数。

   * *note collections.namedtuple(): 1b7. 不再支持 `verbose' 形参或
     ‘_source’ 属性，该属性会显示为具名元组类所生成的源代码。 这是加速类
     创建的设计优化的一部分。 （由 Jelle Zijlstra 在 bpo-28638(1) 中贡献
     ，进一步的改进由 INADA Naoki, Serhiy Storchaka 和 Raymond Hettinger
     贡献。）

   * 函数 *note bool(): 184, *note float(): 188, *note list(): 263. 和
     *note tuple(): 486. 不再接受关键字参数。 *note int(): 185. 的第一个
     参数现在只能作为位置参数传入。

   * 移除了之前在 Python 2.4 中已弃用的 *note plistlib: d0. 模块的类
     ‘Plist’, ‘Dict’ 和 ‘_InternalDict’。 作为函数 *note readPlist():
     487. 和 *note readPlistFromBytes(): 488. 返回结果的 Dict 值现在为普
     通 dict。 你不能再使用属性访问来获取这些字典的项。

   * ‘asyncio.windows_utils.socketpair()’ 函数已被移除。 请改用 *note
     socket.socketpair(): 489. 函数，它自 Python 3.5 起就在所有平台上可
     用。 ‘asyncio.windows_utils.socketpair’ 在 Python 3.5 及更新版本上
     只是 ‘socket.socketpair’ 的别名。

   * *note asyncio: a. 不再将 *note selectors: e7. 和 ‘_overlapped’ 模块
     导出为 ‘asyncio.selectors’ 和 ‘asyncio._overlapped’。 请将 ‘from
     asyncio import selectors’ 替换为 ‘import selectors’。

   * 现在已禁止直接实例化 *note ssl.SSLSocket: 3ea. 和 *note
     ssl.SSLObject: 3eb. 对象。 相应构造器从未写入文档、也从未作为公有构
     造器进行测试或设计。 用户应当使用 *note ssl.wrap_socket(): 477. 或
     *note ssl.SSLContext: 3ec.。 （由 Christian Heimes 在 bpo-32951(2)
     中贡献。）

   * 未被使用的 *note distutils: 39. ‘install_misc’ 命令已被移除。 （由
     Eric N. Vander Weele 在 bpo-29218(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28638

   (2) https://bugs.python.org/issue32951

   (3) https://bugs.python.org/issue29218


File: python.info,  Node: 移除的模块,  Next: Windows 专属的改变,  Prev: API 与特性的移除<2>,  Up: Python 3 7 有什么新变化

1.2.15 移除的模块
-----------------

‘fpectl’ 模块已被移除。 它从未被默认启用，从未在 x86-64 上正确发挥效果，
并且它对 Python ABI 的改变会导致 C 扩展的意外损坏。 （由 Nathaniel J.
Smith 在 bpo-29137(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29137


File: python.info,  Node: Windows 专属的改变,  Next: 移植到 Python 3 7,  Prev: 移除的模块,  Up: Python 3 7 有什么新变化

1.2.16 Windows 专属的改变
-------------------------

Python 启动器（py.exe）可以接受 32 位或 64 位标记而 `不必' 同时指定一个
小版本。 因此 ‘py -3-32’ 和 ‘py -3-64’ 与 ‘py -3.7-32’ 均为有效，并且现
在还接受 -`m'-64 和 -`m.n'-64 来强制使用 64 位 python 命令，即使是本应使
用 32 位的时候。 如果指定版本不可用则 py.exe 将报错退出。 （由 Steve
Barnes 在 bpo-30291(1) 中贡献。）

启动器可以运行 ‘py -0’ 来列出已安装的所有 python，`默认版本会以星号标出
'。 运行 ‘py -0p’ 将同时列出相应的路径。 如果运行 py 时指定了无法匹配的
版本，它将显示 `简短形式' 的可用版本列表。 （由 Steve Barnes 在
bpo-30362(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30291

   (2) https://bugs.python.org/issue30362


File: python.info,  Node: 移植到 Python 3 7,  Next: Python 3 7 1 中的重要变化,  Prev: Windows 专属的改变,  Up: Python 3 7 有什么新变化

1.2.17 移植到 Python 3.7
------------------------

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

* Menu:

* Python 行为的更改::
* Python API 的变化: Python API 的变化<3>.
* C API 的变化: C API 的变化<2>.
* CPython 字节码的改变: CPython 字节码的改变<2>.
* Windows 专属的改变: Windows 专属的改变<2>.
* 其他 CPython 实现的改变: 其他 CPython 实现的改变<2>.


File: python.info,  Node: Python 行为的更改,  Next: Python API 的变化<3>,  Up: 移植到 Python 3 7

1.2.17.1 Python 行为的更改
..........................

   * *note async: 1a3. 和 *note await: 1a4. 现在是保留关键字。 使用了这
     些名称作为标识符的代码现在将引发 *note SyntaxError: 460.。 （由
     Jelle Zijlstra 在 bpo-30406(1) 中贡献。）

   * PEP 479(2) 在 Python 3.7 中对所有代码启用，在协程和生成器中直接或间
     接引发的 *note StopIteration: 48e. 异常会被转换为 *note
     RuntimeError: 2bb. 异常。 （由 Yury Selivanov 在 bpo-32670(3) 中贡
     献。）

   * *note object.__aiter__(): 48f. 方法不再能被声明为异步的。 （由 Yury
     Selivanov 在 bpo-31709(4) 中贡献。）

   * 由于一个疏忽，之前的 Python 版本会错误地接受以下语法:

          f(1 for x in [1],)

          class C(1 for x in [1]):
              pass

     现在 Python 3.7 会正确地引发 *note SyntaxError: 460.，因为生成器表
     达式总是必须直接包含于一对括号之内， 且前后都不能有逗号，仅在调用时
     可以忽略重复的括号。 （由 Serhiy Storchaka 在 bpo-32012(5) 和
     bpo-32023(6) 中贡献。）

   * 现在当使用 *note -m: 340. 开关时，会将初始工作目录添加到 *note
     sys.path: 490.，而不再是一个空字符串（即在每次导入时动态地指明当前
     工作目录）。 任何会检测该空字符串，或是以其他方式依赖之前行为的的程
     序将需要进行相应的更新（例如改为还要检测 ‘os.getcwd()’ 或
     ‘os.path.dirname(__main__.__file__)’，具体做法首先要取决于为何要对
     代码执行空字符串检测）。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30406

   (2) https://www.python.org/dev/peps/pep-0479

   (3) https://bugs.python.org/issue32670

   (4) https://bugs.python.org/issue31709

   (5) https://bugs.python.org/issue32012

   (6) https://bugs.python.org/issue32023


File: python.info,  Node: Python API 的变化<3>,  Next: C API 的变化<2>,  Prev: Python 行为的更改,  Up: 移植到 Python 3 7

1.2.17.2 Python API 的变化
..........................

   * ‘socketserver.ThreadingMixIn.server_close()’ 现在会等待所有非守护线
     程完成。 将新增的 ‘socketserver.ThreadingMixIn.block_on_close’ 类属
     性设为 ‘False’ 可获得 3.7 之前版本的行为。 （由 Victor Stinner 在
     bpo-31233(1) 和 bpo-33540(2) 中贡献。）

   * ‘socketserver.ForkingMixIn.server_close()’ 现在会等等所有子进程完成
     。 将新增的 ‘socketserver.ForkingMixIn.block_on_close’ 类属性设为
     ‘False’ 可获得 3.7 之前版本的行为。 （由 Victor Stinner 在
     bpo-31151(3) 和 bpo-33540(4) 中贡献。）

   * 某些情况下 *note locale.localeconv(): 492. 函数现在会临时将
     ‘LC_CTYPE’ 区域设置为 ‘LC_NUMERIC’ 的值。 （由 Victor Stinner 在
     bpo-31900(5) 中贡献。）

   * 如果 `path' 为字符串 *note pkgutil.walk_packages(): 493. 现在会引发
     *note ValueError: 1fc.。 之前则是返回一个空列表。 （由 Sanyam
     Khurana 在 bpo-24744(6) 中贡献。）

   * *note string.Formatter.format(): 494. 的格式字符串参数现在为 *note
     仅限位置: 2a8. 参数。 将其作为关键字参数传入的方式自 Python 3.5 起
     已弃用。 （由 Serhiy Storchaka 在 bpo-29193(7) 中贡献。）

   * 类 *note http.cookies.Morsel: 495. 的属性 *note key: 496, *note
     value: 497. 和 *note coded_value: 498. 现在均为只读。 对其赋值的操
     作自 Python 3.5 起已弃用。 要设置它们的值请使用 *note set(): 499. 方
     法。 （由 Serhiy Storchaka 在 bpo-29192(8) 中贡献。）

   * *note os.makedirs(): 3c5. 的 `mode' 参数不会再影响新建中间层级目录
     的文件权限位。 要设置它们的文件权限位你可以在发起调用 ‘makedirs()’
     之前设置 umask。 （由 Serhiy Storchaka 在 bpo-19930(9) 中贡献。）

   * *note struct.Struct.format: 49a. 的类型现在是 *note str: 339. 而非
     *note bytes: 33a.。 （由 Victor Stinner 在 bpo-21071(10) 中贡献。）

   * *note parse_multipart(): 2ef. 现在接受 `encoding' 和 `errors' 参数
     并返回与 ‘FieldStorage’ 同样的结果：对于非文件字段，与键相关联的值
     是一个字符串列表，而非字节串。 （由 Pierre Quentel 在 bpo-29979(11)
     中贡献。）

   * 由于 *note socket: f0. 中的内部更改，在由旧版 Python 中的 *note
     socket.share: 49b. 所创建的套接字上调用 *note socket.fromshare():
     49c. 已不受支持。

   * *note BaseException: 1a9. 的 ‘repr’ 已更改为不包含末尾的逗号。 大多
     数异常都会受此更改影响。 （由 Serhiy Storchaka 在 bpo-30399(12) 中
     贡献。）

   * *note datetime.timedelta: 196. 的 ‘repr’ 已更改为在输出中包含关键字
     参数。 （由 Utkarsh Upadhyay 在 bpo-30302(13) 中贡献。）

   * 因为 *note shutil.rmtree(): 21d. 现在是使用 *note os.scandir():
     260. 函数实现的，用户指定的句柄 `onerror' 现在被调用时如果列目录失
     败会附带第一个参数 ‘os.scandir’ 而不是 ‘os.listdir’。

   * 未来可能加入在正则表达式中对 Unicode 技术标准 #18(14) 中嵌套集合与
     集合操作的支持。 这会改变现有语法。 为了推动这项未来的改变，目前在
     有歧义的情况下会引发 *note FutureWarning: 32e.。 这包括以字面值
     ‘'['’ 开头或包含字面值字符序列 ‘'--'’, ‘'&&'’, ‘'~~'’ 以及 ‘'||'’ 的
     集合。 要避免警告，请用反斜杠对其进行转义。 （由 Serhiy Storchaka 在
     bpo-30349(15) 中贡献。）

   * 基于可以匹配空字符串的 *note 正则表达式: de. 对字符串进行拆分的结果
     已被更改。 例如基于 ‘r'\s*'’ 的拆分现在不仅会像原先那样拆分空格符，
     而且会拆分所有非空格字符之前和字符串结尾处的空字符串。 通过将模式修
     改为 ‘r'\s+'’ 可以恢复原先的行为。 自 Python 3.5 开始此类模式将会引
     发 *note FutureWarning: 32e.。

     对于同时匹配空字符串和非空字符串的模式，在其他情况下搜索所有匹配的
     结果也可能会被更改。 例如在字符串 ‘'a\n\n'’ 中，模式
     ‘r'(?m)^\s*?$'’ 将不仅会匹配位置 2 和 3 上的空字符串，还会匹配位置
     2–3 上的字符串 ‘'\n'’。 想要只匹配空行，模式应当改写为
     ‘r'(?m)^[^\S\n]*$'’。

     *note re.sub(): 483. 现在会替换与前一个的非空匹配相邻的空匹配。 例
     如 ‘re.sub('x*', '-', 'abxd')’ 现在会返回 ‘'-a-b--d-'’ 而不是
     ‘'-a-b-d-'’ (’b’ 和 ’d’ 之间的第一个减号是替换 ’x’，而第二个减号则
     是替换 ’x’ 和 ’d’ 之间的空字符串)。

     （由 Serhiy Storchaka 在 bpo-25054(16) 和 bpo-32308(17) 中贡献。）

   * *note re.escape(): 49d. 更改为只转义正则表达式特殊字符，而不转义
     ASCII 字母、数字和 ‘'_'’ 以外的所有字符。 （由 Serhiy Storchaka 在
     bpo-29995(18) 中贡献。）

   * *note tracemalloc.Traceback: 407. 帧现在是按从最旧到最新排序，以便
     与 *note traceback: 114. 更为一致。 （由 Jesse Bakker 在
     bpo-32121(19) 中贡献。）

   * 在支持 *note socket.SOCK_NONBLOCK: 49e. 或 *note
     socket.SOCK_CLOEXEC: 49f. 标志位的操作系统上，*note socket.type:
     4a0. 不再应用它们。 因此，像 ‘if sock.type == socket.SOCK_STREAM’ 之
     类的检测会在所有平台上按预期的方式工作。 （由 Yury Selivanov 在
     bpo-32331(20) 中贡献。）

   * 在 Windows 上当重定向标准句柄时，*note subprocess.Popen: 2ba. 的
     `close_fds' 参数的默认值从 *note False: 390. 更改为 *note True:
     4a1.。 如果你以前依赖于在使用带有标准 io 重定向的 *note
     subprocess.Popen: 2ba. 时所继承的句柄，则必须传入 ‘close_fds=False’
     以保留原先的行为，或是使用 *note STARTUPINFO.lpAttributeList: 4a2.。

   * *note importlib.machinery.PathFinder.invalidate_caches(): 4a3. – 此
     方法隐式地影响 *note importlib.invalidate_caches(): 4a4. – 现在会删
     除 *note sys.path_importer_cache: 4a5. 中被设为 ‘None’ 的条目。 （
     由 Brett Cannon 在 bpo-33169(21) 中贡献。）

   * 在 *note asyncio: a. 中，*note loop.sock_recv(): 4a6, *note
     loop.sock_sendall(): 4a7, *note loop.sock_accept(): 4a8, *note
     loop.getaddrinfo(): 4a9, *note loop.getnameinfo(): 4aa. 已被更改为
     正确的协程方法以与培训五日文档相匹配。 之前，这些方法会返回 *note
     asyncio.Future: 44b. 实例。 （由 Yury Selivanov 在 bpo-32327(22) 中
     贡献。）

   * *note asyncio.Server.sockets: 4ab. 现在会返回服务器套接字列表的副本
     ，而不是直接地返回它。 （由 Yury Selivanov 在 bpo-32662(23) 中贡献
     。）

   * *note Struct.format: 49a. 现在是一个 *note str: 339. 实例而非 *note
     bytes: 33a. 实例。 （由 Victor Stinner 在 bpo-21071(24) 中贡献。）

   * 现在可以通过将 ‘required=True’ 传给 *note
     ArgumentParser.add_subparsers(): 4ac. 使得 *note argparse: 6. 子解
     析器成为必需的。 （由 Anthony Sottile 在 bpo-26510(25) 中贡献。）

   * *note ast.literal_eval(): 4ad. 现在更为严格。 任意地加减数字已不再
     被允许。 （由 Serhiy Storchaka 在 bpo-31778(26) 中贡献。）

   * 当一个日期超出 ‘0001-01-01’ 到 ‘9999-12-31’ 范围时 *note
     Calendar.itermonthdates: 4ae. 现在将始终如一地引发异常，以便支持不
     能容忍此类异常的应用程序，可以使用新增的 *note
     Calendar.itermonthdays3: 4af. 和 *note Calendar.itermonthdays4:
     4b0.。 这些新方法返回元组，并且其不受 *note datetime.date: 194. 所
     支持的范围限制。 （由 Alexander Belopolsky 在 bpo-28292(27) 中贡献
     。）

   * *note collections.ChainMap: 4b1. 现在会保留底层映射的顺序。 （由
     Raymond Hettinger 在 bpo-32792(28) 中贡献。）

   * 如果在解释器关闭期间被调用，*note
     concurrent.futures.ThreadPoolExecutor: 27b. 和 *note
     concurrent.futures.ProcessPoolExecutor: 2a4. 的 ‘submit()’ 方法现在
     会引发 *note RuntimeError: 2bb.。 （由 Mark Nemec 在 bpo-33097(29)
     中贡献。）

   * *note configparser.ConfigParser: 4b2. 构造器现在使用 ‘read_dict()’
     来处理默认值，以使其行为与解析器的其余部分保持致。 在默认字典中的非
     字符串键和值现在会被隐式地转换为字符串。 （由 James Tocknell 在
     bpo-23835(30) 中贡献。）

   * 一些未写入文档的内部导入已被移除。 一个例子是 ‘os.errno’ 已不再可用
     ；应改为直接使用 ‘import errno’。 请注意此类未写入文档的内部导入可
     能未经通知地随时被移除，甚至是在微版本号发行版中移除。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31233

   (2) https://bugs.python.org/issue33540

   (3) https://bugs.python.org/issue31151

   (4) https://bugs.python.org/issue33540

   (5) https://bugs.python.org/issue31900

   (6) https://bugs.python.org/issue24744

   (7) https://bugs.python.org/issue29193

   (8) https://bugs.python.org/issue29192

   (9) https://bugs.python.org/issue19930

   (10) https://bugs.python.org/issue21071

   (11) https://bugs.python.org/issue29979

   (12) https://bugs.python.org/issue30399

   (13) https://bugs.python.org/issue30302

   (14) https://unicode.org/reports/tr18/

   (15) https://bugs.python.org/issue30349

   (16) https://bugs.python.org/issue25054

   (17) https://bugs.python.org/issue32308

   (18) https://bugs.python.org/issue29995

   (19) https://bugs.python.org/issue32121

   (20) https://bugs.python.org/issue32331

   (21) https://bugs.python.org/issue33169

   (22) https://bugs.python.org/issue32327

   (23) https://bugs.python.org/issue32662

   (24) https://bugs.python.org/issue21071

   (25) https://bugs.python.org/issue26510

   (26) https://bugs.python.org/issue31778

   (27) https://bugs.python.org/issue28292

   (28) https://bugs.python.org/issue32792

   (29) https://bugs.python.org/issue33097

   (30) https://bugs.python.org/issue23835


File: python.info,  Node: C API 的变化<2>,  Next: CPython 字节码的改变<2>,  Prev: Python API 的变化<3>,  Up: 移植到 Python 3 7

1.2.17.3 C API 的变化
.....................

函数 *note PySlice_GetIndicesEx(): 480. 被认为对于大小可变的序列来说并不
安全。 如果切片索引不是 *note int: 185. 的实例，而是实现了 ‘__index__()’
方法的对象，则序列可以在其长度被传给 ‘PySlice_GetIndicesEx()’ 之后调整大
小。 这可能导致返回超出序列长度的索引号。 为了避免可能的问题，请使用新增
的函数 *note PySlice_Unpack(): 437. 和 *note PySlice_AdjustIndices():
438.。 （由 Serhiy Storchaka 在 bpo-27867(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27867


File: python.info,  Node: CPython 字节码的改变<2>,  Next: Windows 专属的改变<2>,  Prev: C API 的变化<2>,  Up: 移植到 Python 3 7

1.2.17.4 CPython 字节码的改变
.............................

新增了两个操作码: *note LOAD_METHOD: 4b5. 和 *note CALL_METHOD: 4b6.。 （
由 Yury Selivanov 和 INADA Naoki 在 bpo-26110(1) 中贡献。）

‘STORE_ANNOTATION’ 操作码已被移除。 （由 Mark Shannon 在 bpo-32550(2) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26110

   (2) https://bugs.python.org/issue32550


File: python.info,  Node: Windows 专属的改变<2>,  Next: 其他 CPython 实现的改变<2>,  Prev: CPython 字节码的改变<2>,  Up: 移植到 Python 3 7

1.2.17.5 Windows 专属的改变
...........................

用于重载 *note sys.path: 490. 的文件现在命名为
‘<python-executable>._pth’ 而不是 ‘'sys.path'’。 请参阅 *note 查找模块:
4b8. 了解更多信息。 （由 Steve Dower 在 bpo-28137(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28137


File: python.info,  Node: 其他 CPython 实现的改变<2>,  Prev: Windows 专属的改变<2>,  Up: 移植到 Python 3 7

1.2.17.6 其他 CPython 实现的改变
................................

为了准备在未来对公开的 CPython 运行时初始化 API 进行潜在更改（请参阅 PEP
432(1) 获取最初但略为过时的文稿），CPython 内部的启动和配置管理逻辑已经
过大幅重构。 虽然这些更新旨在对嵌入式应用程序和常规的 CPython CLI 用户都
完全透明，但它们在这里被提及是因为重构会改变解释器启动期间许多操作的内部
顺序，因此可能提示出原先隐藏的缺陷，这可能存在于嵌入式应用程序中，或是在
CPython 自身内部。 （最初由 Nick Coghlan 和 Eric Snow 作为 bpo-22257(2)
的一部分贡献，并由 Nick, Eric 和 Victor Stinner 在一系列其他问题报告中进
一步更新）。 已知会受到影响的一些细节：

   * *note PySys_AddWarnOptionUnicode(): 4ba. 目前对嵌入式应用程序不可用
     ，因为在调用 ‘Py_Initialize’ 之前需要创建 Unicode 对象。 请改用
     *note PySys_AddWarnOption(): 4bb.。

   * 嵌入式应用程序通过 *note PySys_AddWarnOption(): 4bb. 所添加的警告过
     滤器现在应该以更高的一致性优先于由解释器所设置的默认过滤器

由于默认警告过滤器的配置方式发生了变化，将 *note Py_BytesWarningFlag:
4bc. 设置为大于一的值不再足以在发出 *note BytesWarning: 4bd. 消息的同时
将其转换为异常。 而是改为必须设置旗标（以便首先发出警告），以及添加显式
的 ‘error::BytesWarning’ 警告过滤器来将其转换为异常。

由于编译器处理文档字符串的方式发生了变化，一个仅由文档字符串构成的函数体
中隐式的 ‘return None’ 现在被标记为在与文档字符串相同的行，而不是在函数
的标题行。

当前异常状态已从帧对象移到协程对象。 这会简化解释器并修正由于在进入或退
出生成器时具有交换异常状态而导致的一些模糊错误。 （由 Mark Shannon 在
bpo-25612(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0432

   (2) https://bugs.python.org/issue22257

   (3) https://bugs.python.org/issue25612


File: python.info,  Node: Python 3 7 1 中的重要变化,  Next: Python 3 7 2 中的重要变化,  Prev: 移植到 Python 3 7,  Up: Python 3 7 有什么新变化

1.2.18 Python 3.7.1 中的重要变化
--------------------------------

从 3.7.1 开始，*note Py_Initialize(): 441. 现在始终会读取并遵循与 *note
Py_Main(): 4bf. 相同的环境设置（在更早的 Python 版本中，它会遵循一个错误
定义的环境变量子集，而在 Python 3.7.0 中则会由于 bpo-34247(1) 而完全不读
取它们）。 如果不想要此行为，请在调用 *note Py_Initialize(): 441. 之前将
*note Py_IgnoreEnvironmentFlag: 4c0. 设为 1。

在 3.7.1 中，上下文变量的 C API 已 *note 获得更新: 4c1. 以使用 *note
PyObject: 4c2. 指针。 另请参阅 bpo-34762(2)。

在 3.7.1 中，当提供不带末尾新行的输入时 *note tokenize: 112. 模块现在会
隐式地添加 ‘NEWLINE’ 形符。 此行为现在已与 C 词法分析器的内部行为相匹配
。 （由 Ammar Askar 在 bpo-33899(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34247

   (2) https://bugs.python.org/issue34762

   (3) https://bugs.python.org/issue33899


File: python.info,  Node: Python 3 7 2 中的重要变化,  Next: Python 3 7 6 中的重要变化,  Prev: Python 3 7 1 中的重要变化,  Up: Python 3 7 有什么新变化

1.2.19 Python 3.7.2 中的重要变化
--------------------------------

在 3.7.2 中，Windows 下的 *note venv: 126. 不再复制原来的二进制文件，而
是改为创建名为 ‘python.exe’ 和 ‘pythonw.exe’ 的重定向脚本。 这解决了一个
长期存在的问题，即所有虚拟环境在每次 Python 升级后都必须进行升级或是重新
创建。 然而，要注意此发布版仍然要求重新创建虚拟环境以获得新的脚本。


File: python.info,  Node: Python 3 7 6 中的重要变化,  Next: Python 3 7 10 中的重要变化,  Prev: Python 3 7 2 中的重要变化,  Up: Python 3 7 有什么新变化

1.2.20 Python 3.7.6 中的重要变化
--------------------------------

出于重要的安全性考量，*note asyncio.loop.create_datagram_endpoint():
2e8. 的 `reuse_address' 形参不再被支持。 这是由 UDP 中的套接字选项
‘SO_REUSEADDR’ 的行为导致的。 更多细节请参阅
‘loop.create_datagram_endpoint()’ 的文档。 （由 Kyle Stanley, Antoine
Pitrou 和 Yury Selivanov 在 bpo-37228(1) 中贡献。。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37228


File: python.info,  Node: Python 3 7 10 中的重要变化,  Prev: Python 3 7 6 中的重要变化,  Up: Python 3 7 有什么新变化

1.2.21 Python 3.7.10 中的重要变化
---------------------------------

早先的 Python 版本允许使用 ‘;’ 和 ‘&’ 作为 *note
urllib.parse.parse_qs(): 2ec. 和 *note urllib.parse.parse_qsl(): 2ed. 中
query 形参的分隔键。 出于安全考虑，也为了遵循更新的 W3C 推荐设置，这已被
改为只允许单个分隔键，默认为 ‘&’。 这一改变还会影响 *note cgi.parse():
2ee. 和 *note cgi.parse_multipart(): 2ef. 因为它们在内部使用了受影响的函
数。 要了解更多细节，请查看它们各自的文档。 （由 Adam Goldschmidt,
Senthil Kumaran 和 Ken Jin 在 bpo-42967(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42967


File: python.info,  Node: Python 3 6 有什么新变化,  Next: Python 3 5 有什么新变化,  Prev: Python 3 7 有什么新变化,  Up: Python的新变化

1.3 Python 3.6 有什么新变化
===========================


编者: Elvis Pranskevichus <<elvis@magic.io>>, Yury Selivanov
<<yury@magic.io>>

本文解释了与3.5相比，Python 3.6中的新功能。 Python 3.6于2016年12月23日发
布。请参阅 changelog(1) 以获取完整的更改列表。

参见
....

PEP 494(2) - Python 3.6发布计划

* Menu:

* 摘要 - 发布重点: 摘要 - 发布重点<3>.
* 新的特性: 新的特性<3>.
* 其他语言特性修改: 其他语言特性修改<3>.
* 新增模块: 新增模块<3>.
* 改进的模块: 改进的模块<3>.
* 性能优化: 性能优化<3>.
* 构建和 C API 的改变: 构建和 C API 的改变<2>.
* 其他改进::
* 弃用: 弃用<2>.
* 移除::
* 移植到Python 3.6: 移植到Python 3 6.
* Python 3.6.2 中的重要变化: Python 3 6 2 中的重要变化.
* Python 3.6.4 中的重要变化: Python 3 6 4 中的重要变化.
* Python 3.6.5 中的重要变化: Python 3 6 5 中的重要变化.
* Python 3.6.7 中的重要变化: Python 3 6 7 中的重要变化.
* Python 3.6.10 中的重要变化: Python 3 6 10 中的重要变化.
* Notable changes in Python 3.6.13: Notable changes in Python 3 6 13.

   ---------- Footnotes ----------

   (1) https://docs.python.org/3.6/whatsnew/changelog.html

   (2) https://www.python.org/dev/peps/pep-0494


File: python.info,  Node: 摘要 - 发布重点<3>,  Next: 新的特性<3>,  Up: Python 3 6 有什么新变化

1.3.1 摘要 - 发布重点
---------------------

新的语法特性：

   * *note PEP 498: 4c9, 格式化的字符串文字

   * *note PEP 515: 4ca, 数字文字中的下划线。

   * *note PEP 526: 4cb. , 变量注释的语法。

   * *note PEP 525: 4cc, 异步生成器。

   * *note PEP 530: 4cd.: 异步推导。

新的库模块：

   * *note secrets: e5.: *note PEP 506 – Secrets模块被加入Python标准库:
     4ce.。

CPython 实现的改进：

   * 根据 Raymond Hettinger 的提议(1) 已将 *note dict: 305. 类型重新实现
     为使用 *note 更紧凑的表示形式: 4cf. 并类似于 PyPy dict
     implementation(2)。 这使得字典所使用的内存相对于 Python 3.5 版减少
     了 20% 到 25%。

   * 类创建的定制过程通过 *note 新协议: 4d0. 得到了简化。

   * 类属性的定义顺序 *note 现在会被保留: 4d1.。

   * 现在 ‘**kwargs’ 中的元素会与传给函数的关键字参数 *note
     保持对应顺序: 4d2.。

   * 添加了 DTrace 和 SystemTap *note 探测支持: 4d3.

   * 新的 *note PYTHONMALLOC: 4d4. 环境变量可被用来调试解释器的内存分配
     和访问错误。

标准库中的重大改进：

   * *note asyncio: a. 模块获得了许多新特性，显著的可用性和性能提升，以
     及大量的问题修正。 从 Python 3.6 开始 ‘asyncio’ 模块不再处于待定状
     态，它已被视为稳定 API。

   * 实现了新的 *note 文件系统路径协议: 4d5. 以支持 *note 路径类对象:
     373.。 所有操作路径的标准库函数已被更新为使用新的协议。

   * *note datetime: 31. 模块已获得对 *note 本地时间消歧义: 4d6. 的支持
     。

   * *note typing: 11a. 模块获得了大量的 *note 改进: 4d7.。

   * *note tracemalloc: 115. 模块已被大幅重写，现在将被用于为 *note
     ResourceWarning: 4d8. 提供更好的输出，并为内存分配错误提供更好的诊
     断。 请参阅 *note PYTHONMALLOC 一节: 4d4. 来了解详情。

安全改进：

   * 添加了 *note secrets: e5. 模块以简化适用于密码管理的高加密强度伪随
     机数的生成，例如账户验证、安全凭据等场景。

   * 在 Linux 上，现在 *note os.urandom(): 4d9. 会阻塞直到系统的 urandom
     熵池被初始化以提升安全性。 其理由参见 PEP 524(3)。

   * *note hashlib: 8d. 和 *note ssl: f4. 模块现在支持 OpenSSL 1.1.0。

   * *note ssl: f4. 模块的默认设置和特性集已得到改进。

   * *note hashlib: 8d. 模块获得了对 BLAKE2, SHA-3 和 SHAKE 哈希算法以及
     *note scrypt(): 4da. 密钥派生函数的支持。

Windows改进：

   * *note PEP 528: 4db. 和 *note PEP 529: 4dc, 将Windows文件系统和控制
     台的编码更改为UTF-8

   * 在交互式地使用 ‘py.exe’ 启动器时，当用户未（通过命令行参数或配置文
     件）指定版本时不再优先选择 Python 2 而是选择 Python 3。 对声明行的
     处理则保持不变 —— 在这种情况下 "python" 还是指 Python 2。

   * ‘python.exe’ 和 ‘pythonw.exe’ 已被标记为支持长路径，这意味着不再有
     260 个字符的路径长度限制。 详情参见 *note 移除 MAX_PATH 限制: 4dd.。

   * 可以添加一个 ‘._pth’ 文件来强制使用隔离模式和完整指定所有搜索路径来
     避免注册表和环境查找。 更多信息请参阅 *note 相关文档: 4b8.。

   * 现在 ‘python36.zip’ 文件可以作为推断 *note PYTHONHOME: 4de. 的标志
     。 更多信息请参阅 *note 相关文档: 4b8.。

   ---------- Footnotes ----------

   (1) 
https://mail.python.org/pipermail/python-dev/2012-December/123028.html

   (2) 
https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html

   (3) https://www.python.org/dev/peps/pep-0524


File: python.info,  Node: 新的特性<3>,  Next: 其他语言特性修改<3>,  Prev: 摘要 - 发布重点<3>,  Up: Python 3 6 有什么新变化

1.3.2 新的特性
--------------

* Menu:

* PEP 498; 格式化的字符串文字: PEP 498 格式化的字符串文字.
* PEP 526; 变量注释的语法: PEP 526 变量注释的语法.
* PEP 515; 数字文字中的下划线。: PEP 515 数字文字中的下划线。.
* PEP 525; 异步生成器: PEP 525 异步生成器.
* PEP 530; 异步推导: PEP 530 异步推导.
* PEP 487; 自定义类创建: PEP 487 自定义类创建.
* PEP 487; 描述器协议的增强: PEP 487 描述器协议的增强.
* PEP 519; 添加文件系统路径协议: PEP 519 添加文件系统路径协议.
* PEP 495; 消除本地时间的歧义: PEP 495 消除本地时间的歧义.
* PEP 529; 将Windows文件系统编码更改为UTF-8: PEP 529 将Windows文件系统编码更改为UTF-8.
* PEP 528; 将Windows控制台编码更改为UTF-8: PEP 528 将Windows控制台编码更改为UTF-8.
* PEP 520; 保留类属性定义顺序: PEP 520 保留类属性定义顺序.
* PEP 468; 保留关键字参数顺序: PEP 468 保留关键字参数顺序.
* 新的 dict 实现::
* PEP 523; 向CPython 添加框架评估API: PEP 523 向CPython 添加框架评估API.
* PYTHONMALLOC 环境变量::
* DTrace 和 SystemTap 探测支持::


File: python.info,  Node: PEP 498 格式化的字符串文字,  Next: PEP 526 变量注释的语法,  Up: 新的特性<3>

1.3.2.1 PEP 498: 格式化的字符串文字
...................................

PEP 498(1) 引入了一种新型的字符串字面值: `f-字符串'，或称 *note
格式化字符串字面值: 15d.。

格式化字符串字面值带有 ‘'f'’ 前缀并且类似于 *note str.format(): 4e2. 所
接受的格式字符串。 其中包含由花括号包围的替换字段。 替换字段属于表达式，
它们会在运行时被求值，然后使用 *note format(): 4e3. 协议进行格式化:

     >>> name = "Fred"
     >>> f"He said his name is {name}."
     'He said his name is Fred.'
     >>> width = 10
     >>> precision = 4
     >>> value = decimal.Decimal("12.34567")
     >>> f"result: {value:{width}.{precision}}"  # nested fields
     'result:      12.35'

参见
....

PEP 498(2) – 文字字符串插值。

     PEP 由 Eric V. Smith 撰写并实现

*note Feature documentation: 15d.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0498

   (2) https://www.python.org/dev/peps/pep-0498


File: python.info,  Node: PEP 526 变量注释的语法,  Next: PEP 515 数字文字中的下划线。,  Prev: PEP 498 格式化的字符串文字,  Up: 新的特性<3>

1.3.2.2 PEP 526: 变量注释的语法
...............................

PEP 484(1) 引入了函数形参类型标注即类型提示的标准。 这个 PEP 为 Python 添
加了标注变量类型的语法，包括类变量和实例变量:

     primes: List[int] = []

     captain: str  # Note: no initial value!

     class Starship:
         stats: Dict[str, int] = {}

与函数标注一样，Python 解释器不会为变量标注附加任何特殊含义，仅会将其保
存在类或模块的 ‘__annotations__’ 属性中。

与静态类型语法的变量声明不同，标注语法的目的是通过抽象语法树和
‘__annotations__’ 属性提供一个简单方式来为第三方工具和库指定结构化类型元
数据。

参见
....

PEP 526(2) – 变量注释的语法。

     PEP 由 Ryan Gonzalez, Philip House, Ivan Levkivskyi, Lisa Roach, 和
     Guido van Rossum 撰写，由 Ivan Levkivskyi 实现。

使用或将要使用此新语法的工具有: mypy(3), pytype(4), PyCharm 等等。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0526

   (3) http://www.mypy-lang.org/

   (4) https://github.com/google/pytype


File: python.info,  Node: PEP 515 数字文字中的下划线。,  Next: PEP 525 异步生成器,  Prev: PEP 526 变量注释的语法,  Up: 新的特性<3>

1.3.2.3 PEP 515: 数字文字中的下划线。
.....................................

PEP 515(1) 增加了在数字字面值中使用下划线的能力以改善可读性。 例如:

     >>> 1_000_000_000_000_000
     1000000000000000
     >>> 0x_FF_FF_FF_FF
     4294967295

单个下划线允许用在数码之间和任何数制指示符之后。 一行内不允许有开头、末
尾或多个下划线。

*note 字符串格式化: 4e6. 微语言现在也支持以 ‘'_'’ 选项来表示用下划线作为
浮点表示类型和整数表示类型 ‘'d'’ 的千位分隔符。 对于整数表示类型 ‘'b'’,
‘'o'’, ‘'x'’ 和 ‘'X'’，将每隔 4 个数码插入一个下划线:

     >>> '{:_}'.format(1000000)
     '1_000_000'
     >>> '{:_x}'.format(0xFFFFFFFF)
     'ffff_ffff'

参见
....

PEP 515(2) – 数字文字中的下划线。

     PEP 由 Georg Brandl 和 Serhiy Storchaka 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0515

   (2) https://www.python.org/dev/peps/pep-0515


File: python.info,  Node: PEP 525 异步生成器,  Next: PEP 530 异步推导,  Prev: PEP 515 数字文字中的下划线。,  Up: 新的特性<3>

1.3.2.4 PEP 525: 异步生成器
...........................

PEP 492(1) 将对原生协程和 ‘async’ / ‘await’ 语法的支持引入到 Python 3.5
中。 但 Python 3.5 实现的一个明显限制是不可能在同一函数体中同时使用
‘await’ 和 ‘yield’。 在 Python 3.6 中此限制已被解除，这样就就能够定义 `异
步生成器':

     async def ticker(delay, to):
         """Yield numbers from 0 to *to* every *delay* seconds."""
         for i in range(to):
             yield i
             await asyncio.sleep(delay)

这个新语法允许更快速且更精简的代码。

参见
....

PEP 525(2) – 异步生成器

     PEP 由 Yury Selivanov 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0492

   (2) https://www.python.org/dev/peps/pep-0525


File: python.info,  Node: PEP 530 异步推导,  Next: PEP 487 自定义类创建,  Prev: PEP 525 异步生成器,  Up: 新的特性<3>

1.3.2.5 PEP 530: 异步推导
.........................

PEP 530(1) 添加了对在列表、集合与字典推导式和生成器表达式中使用 ‘async
for’ 的支持:

     result = [i async for i in aiter() if i % 2]

此外，‘await’ 表达式也在所有种类的推导式中得到支持:

     result = [await fun() for fun in funcs if await condition()]

参见
....

PEP 530(2) – 异步推导

     PEP 由 Yury Selivanov 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0530

   (2) https://www.python.org/dev/peps/pep-0530


File: python.info,  Node: PEP 487 自定义类创建,  Next: PEP 487 描述器协议的增强,  Prev: PEP 530 异步推导,  Up: 新的特性<3>

1.3.2.6 PEP 487: 自定义类创建
.............................

现在可以在不使用元类的情况下自定义子类的创建。 当一个新的子类被创建时将
在基类上调用新的 ‘__init_subclass__’ 类方法:

     class PluginBase:
         subclasses = []

         def __init_subclass__(cls, **kwargs):
             super().__init_subclass__(**kwargs)
             cls.subclasses.append(cls)

     class Plugin1(PluginBase):
         pass

     class Plugin2(PluginBase):
         pass

为了让来自 *note __init_subclass__(): 4ea. 实现的零参数 *note super():
4eb. 调用能正确工作，自定义元类必须保证新的 ‘__classcell__’ 命名空间入口
被传播到 ‘type.__new__’ (如 *note 创建类对象: 4ec. 中所描述)。

参见
....

PEP 487(1) – 自定义类创建

     PEP 由 Martin Teichmann 撰写并实现。

*note 特性文档: 4ed.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0487


File: python.info,  Node: PEP 487 描述器协议的增强,  Next: PEP 519 添加文件系统路径协议,  Prev: PEP 487 自定义类创建,  Up: 新的特性<3>

1.3.2.7 PEP 487: 描述器协议的增强
.................................

PEP 487(1) 扩展了描述器协议以包括新的可选方法 *note __set_name__():
4f0.。 当创建一个新类时，这个新方法将在定义中包括的所有描述器上被调用，
为它们提供对所定义类的引用以及在类命名中间中给予描述器的名称。 换句话说
，描述器的实例现在能知道描述器在所有者类中的属性名称:

     class IntField:
         def __get__(self, instance, owner):
             return instance.__dict__[self.name]

         def __set__(self, instance, value):
             if not isinstance(value, int):
                 raise ValueError(f'expecting integer in {self.name}')
             instance.__dict__[self.name] = value

         # this is the new initializer:
         def __set_name__(self, owner, name):
             self.name = name

     class Model:
         int_field = IntField()

参见
....

PEP 487(2) – 自定义类创建

     PEP 由 Martin Teichmann 撰写并实现。

*note 特性文档: 4f1.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0487

   (2) https://www.python.org/dev/peps/pep-0487


File: python.info,  Node: PEP 519 添加文件系统路径协议,  Next: PEP 495 消除本地时间的歧义,  Prev: PEP 487 描述器协议的增强,  Up: 新的特性<3>

1.3.2.8 PEP 519: 添加文件系统路径协议
.....................................

File system paths have historically been represented as *note str: 339.
or *note bytes: 33a. objects.  This has led to people who write code
which operate on file system paths to assume that such objects are only
one of those two types (an *note int: 185. representing a file
descriptor does not count as that is not a file path).  Unfortunately
that assumption prevents alternative object representations of file
system paths like *note pathlib: c9. from working with pre-existing
code, including Python’s standard library.

To fix this situation, a new interface represented by *note os.PathLike:
4f3. has been defined.  By implementing the *note __fspath__(): 4f4.
method, an object signals that it represents a path.  An object can then
provide a low-level representation of a file system path as a *note str:
339. or *note bytes: 33a. object.  This means an object is considered
*note path-like: 373. if it implements *note os.PathLike: 4f3. or is a
*note str: 339. or *note bytes: 33a. object which represents a file
system path.  Code can use *note os.fspath(): 4f5, *note os.fsdecode():
4f6, or *note os.fsencode(): 4f7. to explicitly get a *note str: 339.
and/or *note bytes: 33a. representation of a path-like object.

The built-in *note open(): 4f8. function has been updated to accept
*note os.PathLike: 4f3. objects, as have all relevant functions in the
*note os: c5. and *note os.path: c6. modules, and most other functions
and classes in the standard library.  The *note os.DirEntry: 4f9. class
and relevant classes in *note pathlib: c9. have also been updated to
implement *note os.PathLike: 4f3.

The hope is that updating the fundamental functions for operating on
file system paths will lead to third-party code to implicitly support
all *note path-like objects: 373. without any code changes, or at least
very minimal ones (e.g.  calling *note os.fspath(): 4f5. at the
beginning of code before operating on a path-like object).

Here are some examples of how the new interface allows for *note
pathlib.Path: 202. to be used more easily and transparently with
pre-existing code:

     >>> import pathlib
     >>> with open(pathlib.Path("README")) as f:
     ...     contents = f.read()
     ...
     >>> import os.path
     >>> os.path.splitext(pathlib.Path("some_file.txt"))
     ('some_file', '.txt')
     >>> os.path.join("/a/b", pathlib.Path("c"))
     '/a/b/c'
     >>> import os
     >>> os.fspath(pathlib.Path("some_file.txt"))
     'some_file.txt'

（由 Brett Cannon, Ethan Furman, Dusty Phillips 和 Jelle Zijlstra 实现。
）

参见
....

PEP 519(1) – 添加文件系统路径协议

     PEP 由 Brett Cannon 和 Koos Zevenhoven 撰写。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0519


File: python.info,  Node: PEP 495 消除本地时间的歧义,  Next: PEP 529 将Windows文件系统编码更改为UTF-8,  Prev: PEP 519 添加文件系统路径协议,  Up: 新的特性<3>

1.3.2.9 PEP 495: 消除本地时间的歧义
...................................

In most world locations, there have been and will be times when local
clocks are moved back.  In those times, intervals are introduced in
which local clocks show the same time twice in the same day.  In these
situations, the information displayed on a local clock (or stored in a
Python datetime instance) is insufficient to identify a particular
moment in time.

PEP 495(1) adds the new `fold' attribute to instances of *note
datetime.datetime: 195. and *note datetime.time: 4fb. classes to
differentiate between two moments in time for which local times are the
same:

     >>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
     >>> for i in range(4):
     ...     u = u0 + i*HOUR
     ...     t = u.astimezone(Eastern)
     ...     print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
     ...
     04:00:00 UTC = 00:00:00 EDT 0
     05:00:00 UTC = 01:00:00 EDT 0
     06:00:00 UTC = 01:00:00 EST 1
     07:00:00 UTC = 02:00:00 EST 0

The values of the *note fold: 4fc. attribute have the value ‘0’ for all
instances except those that represent the second (chronologically)
moment in time in an ambiguous case.

参见
....

PEP 495(2) – 消除本地时间的歧义

     PEP 由 Alexander Belopolsky 和 Tim Peters 撰写，由 Alexander
     Belopolsky 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0495

   (2) https://www.python.org/dev/peps/pep-0495


File: python.info,  Node: PEP 529 将Windows文件系统编码更改为UTF-8,  Next: PEP 528 将Windows控制台编码更改为UTF-8,  Prev: PEP 495 消除本地时间的歧义,  Up: 新的特性<3>

1.3.2.10 PEP 529: 将Windows文件系统编码更改为UTF-8
..................................................

Representing filesystem paths is best performed with str (Unicode)
rather than bytes.  However, there are some situations where using bytes
is sufficient and correct.

Prior to Python 3.6, data loss could result when using bytes paths on
Windows.  With this change, using bytes to represent paths is now
supported on Windows, provided those bytes are encoded with the encoding
returned by *note sys.getfilesystemencoding(): 4fe, which now defaults
to ‘'utf-8'’.

Applications that do not use str to represent paths should use *note
os.fsencode(): 4f7. and *note os.fsdecode(): 4f6. to ensure their bytes
are correctly encoded.  To revert to the previous behaviour, set *note
PYTHONLEGACYWINDOWSFSENCODING: 4ff. or call *note
sys._enablelegacywindowsfsencoding(): 500.

有关详细信息和可能需要的代码修改的讨论，请参见 PEP 529(1) 。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0529


File: python.info,  Node: PEP 528 将Windows控制台编码更改为UTF-8,  Next: PEP 520 保留类属性定义顺序,  Prev: PEP 529 将Windows文件系统编码更改为UTF-8,  Up: 新的特性<3>

1.3.2.11 PEP 528: 将Windows控制台编码更改为UTF-8
................................................

The default console on Windows will now accept all Unicode characters
and provide correctly read str objects to Python code.  ‘sys.stdin’,
‘sys.stdout’ and ‘sys.stderr’ now default to utf-8 encoding.

This change only applies when using an interactive console, and not when
redirecting files or pipes.  To revert to the previous behaviour for
interactive console use, set *note PYTHONLEGACYWINDOWSSTDIO: 502.

参见
....

PEP 528(1) – 将Windows控制台编码更改为UTF-8

     PEP 由 Steve Dower 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0528


File: python.info,  Node: PEP 520 保留类属性定义顺序,  Next: PEP 468 保留关键字参数顺序,  Prev: PEP 528 将Windows控制台编码更改为UTF-8,  Up: 新的特性<3>

1.3.2.12 PEP 520: 保留类属性定义顺序
....................................

Attributes in a class definition body have a natural ordering: the same
order in which the names appear in the source.  This order is now
preserved in the new class’s *note __dict__: 504. attribute.

Also, the effective default class `execution' namespace (returned from
*note type.__prepare__(): 505.) is now an insertion-order-preserving
mapping.

参见
....

PEP 520(1) – 保留类属性定义顺序

     PEP 由 Eric Snow 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0520


File: python.info,  Node: PEP 468 保留关键字参数顺序,  Next: 新的 dict 实现,  Prev: PEP 520 保留类属性定义顺序,  Up: 新的特性<3>

1.3.2.13 PEP 468: 保留关键字参数顺序
....................................

‘**kwargs’ in a function signature is now guaranteed to be an
insertion-order-preserving mapping.

参见
....

PEP 468(1) – 保留关键字参数顺序

     PEP 由 Eric Snow 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0468


File: python.info,  Node: 新的 dict 实现,  Next: PEP 523 向CPython 添加框架评估API,  Prev: PEP 468 保留关键字参数顺序,  Up: 新的特性<3>

1.3.2.14 新的 dict 实现
.......................

The *note dict: 305. type now uses a "compact" representation based on a
proposal by Raymond Hettinger(1) which was first implemented by PyPy(2).
The memory usage of the new *note dict(): 1b9. is between 20% and 25%
smaller compared to Python 3.5.

The order-preserving aspect of this new implementation is considered an
implementation detail and should not be relied upon (this may change in
the future, but it is desired to have this new dict implementation in
the language for a few releases before changing the language spec to
mandate order-preserving semantics for all current and future Python
implementations; this also helps preserve backwards-compatibility with
older versions of the language where random iteration order is still in
effect, e.g.  Python 3.5).

(Contributed by INADA Naoki in bpo-27350(3).  Idea originally suggested
by Raymond Hettinger(4).)

   ---------- Footnotes ----------

   (1) 
https://mail.python.org/pipermail/python-dev/2012-December/123028.html

   (2) 
https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html

   (3) https://bugs.python.org/issue27350

   (4) 
https://mail.python.org/pipermail/python-dev/2012-December/123028.html


File: python.info,  Node: PEP 523 向CPython 添加框架评估API,  Next: PYTHONMALLOC 环境变量,  Prev: 新的 dict 实现,  Up: 新的特性<3>

1.3.2.15 PEP 523: 向CPython 添加框架评估API
...........................................

While Python provides extensive support to customize how code executes,
one place it has not done so is in the evaluation of frame objects.  If
you wanted some way to intercept frame evaluation in Python there really
wasn’t any way without directly manipulating function pointers for
defined functions.

PEP 523(1) changes this by providing an API to make frame evaluation
pluggable at the C level.  This will allow for tools such as debuggers
and JITs to intercept frame evaluation before the execution of Python
code begins.  This enables the use of alternative evaluation
implementations for Python code, tracking frame evaluation, etc.

This API is not part of the limited C API and is marked as private to
signal that usage of this API is expected to be limited and only
applicable to very select, low-level use-cases.  Semantics of the API
will change with Python as necessary.

参见
....

PEP 523(2) – 向CPython 添加框架评估API

     PEP 由 Brett Cannon 和 Dino Viehland 撰写。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0523

   (2) https://www.python.org/dev/peps/pep-0523


File: python.info,  Node: PYTHONMALLOC 环境变量,  Next: DTrace 和 SystemTap 探测支持,  Prev: PEP 523 向CPython 添加框架评估API,  Up: 新的特性<3>

1.3.2.16 PYTHONMALLOC 环境变量
..............................

The new *note PYTHONMALLOC: 50b. environment variable allows setting the
Python memory allocators and installing debug hooks.

It is now possible to install debug hooks on Python memory allocators on
Python compiled in release mode using ‘PYTHONMALLOC=debug’.  Effects of
debug hooks:

   * 新分配的内存中填充字节 ‘0xCB’

   * 释放的内存中填充了字节 ‘0xDB’

   * Detect violations of the Python memory allocator API. For example,
     *note PyObject_Free(): 50c. called on a memory block allocated by
     *note PyMem_Malloc(): 50d.

   * 在缓冲区开始之前检测写操作（缓冲区下溢）

   * 在缓冲区结束后检测写操作（缓冲区溢出）

   * Check that the *note GIL: 50e. is held when allocator functions of
     *note PYMEM_DOMAIN_OBJ: 50f. (ex: *note PyObject_Malloc(): 510.)
     and *note PYMEM_DOMAIN_MEM: 511. (ex: *note PyMem_Malloc(): 50d.)
     domains are called.

检查是否保留了 GIL 也是Python 3.6 的新特性。

See the *note PyMem_SetupDebugHooks(): 512. function for debug hooks on
Python memory allocators.

It is now also possible to force the usage of the ‘malloc()’ allocator
of the C library for all Python memory allocations using
‘PYTHONMALLOC=malloc’.  This is helpful when using external memory
debuggers like Valgrind on a Python compiled in release mode.

On error, the debug hooks on Python memory allocators now use the *note
tracemalloc: 115. module to get the traceback where a memory block was
allocated.

Example of fatal error on buffer overflow using ‘python3.6 -X
tracemalloc=5’ (store 5 frames in traces):

     Debug memory block at address p=0x7fbcd41666f8: API 'o'
         4 bytes originally requested
         The 7 pad bytes at p-7 are FORBIDDENBYTE, as expected.
         The 8 pad bytes at tail=0x7fbcd41666fc are not all FORBIDDENBYTE (0xfb):
             at tail+0: 0x02 *** OUCH
             at tail+1: 0xfb
             at tail+2: 0xfb
             at tail+3: 0xfb
             at tail+4: 0xfb
             at tail+5: 0xfb
             at tail+6: 0xfb
             at tail+7: 0xfb
         The block was made by call #1233329 to debug malloc/realloc.
         Data at p: 1a 2b 30 00

     Memory block allocated at (most recent call first):
       File "test/test_bytes.py", line 323
       File "unittest/case.py", line 600
       File "unittest/case.py", line 648
       File "unittest/suite.py", line 122
       File "unittest/suite.py", line 84

     Fatal Python error: bad trailing pad byte

     Current thread 0x00007fbcdbd32700 (most recent call first):
       File "test/test_bytes.py", line 323 in test_hex
       File "unittest/case.py", line 600 in run
       File "unittest/case.py", line 648 in __call__
       File "unittest/suite.py", line 122 in run
       File "unittest/suite.py", line 84 in __call__
       File "unittest/suite.py", line 122 in run
       File "unittest/suite.py", line 84 in __call__
       ...

（由 Victor Stinner 在 bpo-26516(1) 和 bpo-26564(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26516

   (2) https://bugs.python.org/issue26564


File: python.info,  Node: DTrace 和 SystemTap 探测支持,  Prev: PYTHONMALLOC 环境变量,  Up: 新的特性<3>

1.3.2.17 DTrace 和 SystemTap 探测支持
.....................................

Python can now be built ‘--with-dtrace’ which enables static markers for
the following events in the interpreter:

   * 函数调用/返回

   * 垃圾收集开始/完成

   * 执行的代码行。

This can be used to instrument running interpreters in production,
without the need to recompile specific debug builds or providing
application-specific profiling/debugging code.

更多信息，请参见 *note 使用 DTrace 和 SystemTap 检测CPython: 514. 。

当前的实现已在 Linux 和 macOS 上进行了测试。将来可能会添加其他标记。

(Contributed by Łukasz Langa in bpo-21590(1), based on patches by Jesús
Cea Avión, David Malcolm, and Nikhil Benesch.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21590


File: python.info,  Node: 其他语言特性修改<3>,  Next: 新增模块<3>,  Prev: 新的特性<3>,  Up: Python 3 6 有什么新变化

1.3.3 其他语言特性修改
----------------------

对Python 语言核心进行的小改动：

   * A ‘global’ or ‘nonlocal’ statement must now textually appear before
     the first use of the affected name in the same scope.  Previously
     this was a *note SyntaxWarning: 192.

   * It is now possible to set a *note special method: 516. to ‘None’ to
     indicate that the corresponding operation is not available.  For
     example, if a class sets *note __iter__(): 517. to ‘None’, the
     class is not iterable.  (Contributed by Andrew Barnert and Ivan
     Levkivskyi in bpo-25958(1).)

   * Long sequences of repeated traceback lines are now abbreviated as
     ‘"[Previous line repeated {count} more times]"’ (see *note 回溯:
     518. for an example).  (Contributed by Emanuel Barry in
     bpo-26823(2).)

   * Import now raises the new exception *note ModuleNotFoundError: 3a2.
     (subclass of *note ImportError: 33d.) when it cannot find a module.
     Code that currently checks for ImportError (in try-except) will
     still work.  (Contributed by Eric Snow in bpo-15767(3).)

   * Class methods relying on zero-argument ‘super()’ will now work
     correctly when called from metaclass methods during class creation.
     (Contributed by Martin Teichmann in bpo-23722(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25958

   (2) https://bugs.python.org/issue26823

   (3) https://bugs.python.org/issue15767

   (4) https://bugs.python.org/issue23722


File: python.info,  Node: 新增模块<3>,  Next: 改进的模块<3>,  Prev: 其他语言特性修改<3>,  Up: Python 3 6 有什么新变化

1.3.4 新增模块
--------------

* Menu:

* secrets::


File: python.info,  Node: secrets,  Up: 新增模块<3>

1.3.4.1 secrets
...............

The main purpose of the new *note secrets: e5. module is to provide an
obvious way to reliably generate cryptographically strong pseudo-random
values suitable for managing secrets, such as account authentication,
tokens, and similar.

     警告: Note that the pseudo-random generators in the *note random:
     dd. module should `NOT' be used for security purposes.  Use *note
     secrets: e5. on Python 3.6+ and *note os.urandom(): 4d9. on Python
     3.5 and earlier.

参见
....

PEP 506(1) – Secrets模块被加入Python标准库

     PEP 由 Steven D’Aprano 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0506


File: python.info,  Node: 改进的模块<3>,  Next: 性能优化<3>,  Prev: 新增模块<3>,  Up: Python 3 6 有什么新变化

1.3.5 改进的模块
----------------

* Menu:

* array::
* ast: ast<2>.
* asyncio: asyncio<4>.
* binascii: binascii<2>.
* cmath::
* collections: collections<4>.
* concurrent.futures: concurrent futures<2>.
* contextlib: contextlib<2>.
* datetime: datetime<3>.
* decimal: decimal<2>.
* distutils: distutils<2>.
* email::
* encodings::
* enum: enum<3>.
* faulthandler::
* fileinput::
* hashlib::
* http.client: http client<2>.
* idlelib 与 IDLE: idlelib 与 IDLE<2>.
* importlib: importlib<3>.
* inspect: inspect<2>.
* json::
* logging: logging<3>.
* math: math<3>.
* multiprocessing: multiprocessing<3>.
* os: os<3>.
* pathlib: pathlib<3>.
* pdb: pdb<2>.
* pickle: pickle<2>.
* pickletools::
* pydoc: pydoc<2>.
* random::
* re: re<2>.
* readline::
* rlcompleter::
* shlex: shlex<2>.
* site::
* sqlite3: sqlite3<2>.
* socket: socket<4>.
* socketserver: socketserver<2>.
* ssl: ssl<4>.
* statistics: statistics<2>.
* struct::
* subprocess: subprocess<2>.
* sys: sys<4>.
* telnetlib::
* time: time<3>.
* timeit::
* tkinter: tkinter<3>.
* 回溯::
* tracemalloc: tracemalloc<2>.
* typing: typing<2>.
* unicodedata: unicodedata<3>.
* unittest.mock: unittest mock<2>.
* urllib.request: urllib request.
* urllib.robotparser: urllib robotparser.
* venv: venv<2>.
* warnings: warnings<2>.
* winreg::
* winsound::
* xmlrpc.client: xmlrpc client.
* zipfile: zipfile<2>.
* zlib::


File: python.info,  Node: array,  Next: ast<2>,  Up: 改进的模块<3>

1.3.5.1 array
.............

Exhausted iterators of *note array.array: 459. will now stay exhausted
even if the iterated array is extended.  This is consistent with the
behavior of other mutable sequences.

由 Serhiy Storchaka 在 bpo-26492(1) 中贡献。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26492


File: python.info,  Node: ast<2>,  Next: asyncio<4>,  Prev: array,  Up: 改进的模块<3>

1.3.5.2 ast
...........

The new ‘ast.Constant’ AST node has been added.  It can be used by
external AST optimizers for the purposes of constant folding.

由 Victor Stinner 在 bpo-26146(1) 中贡献。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26146


File: python.info,  Node: asyncio<4>,  Next: binascii<2>,  Prev: ast<2>,  Up: 改进的模块<3>

1.3.5.3 asyncio
...............

Starting with Python 3.6 the ‘asyncio’ module is no longer provisional
and its API is considered stable.

Notable changes in the *note asyncio: a. module since Python 3.5.0 (all
backported to 3.5.x due to the provisional status):

   * The *note get_event_loop(): 35e. function has been changed to
     always return the currently running loop when called from
     coroutines and callbacks.  (Contributed by Yury Selivanov in
     bpo-28613(1).)

   * The *note ensure_future(): 51f. function and all functions that use
     it, such as *note loop.run_until_complete(): 520, now accept all
     kinds of *note awaitable objects: 521.  (Contributed by Yury
     Selivanov.)

   * New *note run_coroutine_threadsafe(): 522. function to submit
     coroutines to event loops from other threads.  (Contributed by
     Vincent Michel.)

   * New *note Transport.is_closing(): 523. method to check if the
     transport is closing or closed.  (Contributed by Yury Selivanov.)

   * The *note loop.create_server(): 366. method can now accept a list
     of hosts.  (Contributed by Yann Sionneau.)

   * New *note loop.create_future(): 524. method to create Future
     objects.  This allows alternative event loop implementations, such
     as uvloop(2), to provide a faster *note asyncio.Future: 44b.
     implementation.  (Contributed by Yury Selivanov in bpo-27041(3).)

   * New *note loop.get_exception_handler(): 525. method to get the
     current exception handler.  (Contributed by Yury Selivanov in
     bpo-27040(4).)

   * New *note StreamReader.readuntil(): 526. method to read data from
     the stream until a separator bytes sequence appears.  (Contributed
     by Mark Korenberg.)

   * The performance of *note StreamReader.readexactly(): 527. has been
     improved.  (Contributed by Mark Korenberg in bpo-28370(5).)

   * The *note loop.getaddrinfo(): 4a9. method is optimized to avoid
     calling the system ‘getaddrinfo’ function if the address is already
     resolved.  (Contributed by A. Jesse Jiryu Davis.)

   * The *note loop.stop(): 528. method has been changed to stop the
     loop immediately after the current iteration.  Any new callbacks
     scheduled as a result of the last iteration will be discarded.
     (Contributed by Guido van Rossum in bpo-25593(6).)

   * ‘Future.set_exception’ will now raise *note TypeError: 193. when
     passed an instance of the *note StopIteration: 48e. exception.
     (Contributed by Chris Angelico in bpo-26221(7).)

   * New *note loop.connect_accepted_socket(): 36e. method to be used by
     servers that accept connections outside of asyncio, but that use
     asyncio to handle them.  (Contributed by Jim Fulton in
     bpo-27392(8).)

   * ‘TCP_NODELAY’ flag is now set for all TCP transports by default.
     (Contributed by Yury Selivanov in bpo-27456(9).)

   * New *note loop.shutdown_asyncgens(): 529. to properly close pending
     asynchronous generators before closing the loop.  (Contributed by
     Yury Selivanov in bpo-28003(10).)

   * *note Future: 44b. and *note Task: 1ae. classes now have an
     optimized C implementation which makes asyncio code up to 30%
     faster.  (Contributed by Yury Selivanov and INADA Naoki in
     bpo-26081(11) and bpo-28544(12).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28613

   (2) https://github.com/MagicStack/uvloop

   (3) https://bugs.python.org/issue27041

   (4) https://bugs.python.org/issue27040

   (5) https://bugs.python.org/issue28370

   (6) https://bugs.python.org/issue25593

   (7) https://bugs.python.org/issue26221

   (8) https://bugs.python.org/issue27392

   (9) https://bugs.python.org/issue27456

   (10) https://bugs.python.org/issue28003

   (11) https://bugs.python.org/issue26081

   (12) https://bugs.python.org/issue28544


File: python.info,  Node: binascii<2>,  Next: cmath,  Prev: asyncio<4>,  Up: 改进的模块<3>

1.3.5.4 binascii
................

The *note b2a_base64(): 52b. function now accepts an optional `newline'
keyword argument to control whether the newline character is appended to
the return value.  (Contributed by Victor Stinner in bpo-25357(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25357


File: python.info,  Node: cmath,  Next: collections<4>,  Prev: binascii<2>,  Up: 改进的模块<3>

1.3.5.5 cmath
.............

The new *note cmath.tau: 52d. (`τ') constant has been added.
(Contributed by Lisa Roach in bpo-12345(1), see PEP 628(2) for details.)

New constants: *note cmath.inf: 52e. and *note cmath.nan: 52f. to match
*note math.inf: 530. and *note math.nan: 531, and also *note cmath.infj:
532. and *note cmath.nanj: 533. to match the format used by complex
repr.  (Contributed by Mark Dickinson in bpo-23229(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12345

   (2) https://www.python.org/dev/peps/pep-0628

   (3) https://bugs.python.org/issue23229


File: python.info,  Node: collections<4>,  Next: concurrent futures<2>,  Prev: cmath,  Up: 改进的模块<3>

1.3.5.6 collections
...................

The new *note Collection: 535. abstract base class has been added to
represent sized iterable container classes.  (Contributed by Ivan
Levkivskyi, docs by Neil Girdhar in bpo-27598(1).)

The new *note Reversible: 536. abstract base class represents iterable
classes that also provide the *note __reversed__(): 537. method.
(Contributed by Ivan Levkivskyi in bpo-25987(2).)

The new *note AsyncGenerator: 538. abstract base class represents
asynchronous generators.  (Contributed by Yury Selivanov in
bpo-28720(3).)

The *note namedtuple(): 1b7. function now accepts an optional keyword
argument `module', which, when specified, is used for the ‘__module__’
attribute of the returned named tuple class.  (Contributed by Raymond
Hettinger in bpo-17941(4).)

The `verbose' and `rename' arguments for *note namedtuple(): 1b7. are
now keyword-only.  (Contributed by Raymond Hettinger in bpo-25628(5).)

Recursive *note collections.deque: 539. instances can now be pickled.
(Contributed by Serhiy Storchaka in bpo-26482(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27598

   (2) https://bugs.python.org/issue25987

   (3) https://bugs.python.org/issue28720

   (4) https://bugs.python.org/issue17941

   (5) https://bugs.python.org/issue25628

   (6) https://bugs.python.org/issue26482


File: python.info,  Node: concurrent futures<2>,  Next: contextlib<2>,  Prev: collections<4>,  Up: 改进的模块<3>

1.3.5.7 concurrent.futures
..........................

The *note ThreadPoolExecutor: 27b. class constructor now accepts an
optional `thread_name_prefix' argument to make it possible to customize
the names of the threads created by the pool.  (Contributed by Gregory
P. Smith in bpo-27664(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27664


File: python.info,  Node: contextlib<2>,  Next: datetime<3>,  Prev: concurrent futures<2>,  Up: 改进的模块<3>

1.3.5.8 contextlib
..................

The *note contextlib.AbstractContextManager: 53c. class has been added
to provide an abstract base class for context managers.  It provides a
sensible default implementation for ‘__enter__()’ which returns ‘self’
and leaves ‘__exit__()’ an abstract method.  A matching class has been
added to the *note typing: 11a. module as *note typing.ContextManager:
53d.  (Contributed by Brett Cannon in bpo-25609(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25609


File: python.info,  Node: datetime<3>,  Next: decimal<2>,  Prev: contextlib<2>,  Up: 改进的模块<3>

1.3.5.9 datetime
................

The *note datetime: 195. and *note time: 4fb. classes have the new
‘fold’ attribute used to disambiguate local time when necessary.  Many
functions in the *note datetime: 31. have been updated to support local
time disambiguation.  See *note Local Time Disambiguation: 4d6. section
for more information.  (Contributed by Alexander Belopolsky in
bpo-24773(1).)

The *note datetime.strftime(): 53f. and *note date.strftime(): 540.
methods now support ISO 8601 date directives ‘%G’, ‘%u’ and ‘%V’.
(Contributed by Ashley Anderson in bpo-12006(2).)

The *note datetime.isoformat(): 541. function now accepts an optional
`timespec' argument that specifies the number of additional components
of the time value to include.  (Contributed by Alessandro Cucci and
Alexander Belopolsky in bpo-19475(3).)

The *note datetime.combine(): 542. now accepts an optional `tzinfo'
argument.  (Contributed by Alexander Belopolsky in bpo-27661(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24773

   (2) https://bugs.python.org/issue12006

   (3) https://bugs.python.org/issue19475

   (4) https://bugs.python.org/issue27661


File: python.info,  Node: decimal<2>,  Next: distutils<2>,  Prev: datetime<3>,  Up: 改进的模块<3>

1.3.5.10 decimal
................

New *note Decimal.as_integer_ratio(): 544. method that returns a pair
‘(n, d)’ of integers that represent the given *note Decimal: 189.
instance as a fraction, in lowest terms and with a positive denominator:

     >>> Decimal('-3.14').as_integer_ratio()
     (-157, 50)

（由 Stefan Krah 和 Mark Dickinson 在 bpo-25928(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25928


File: python.info,  Node: distutils<2>,  Next: email,  Prev: decimal<2>,  Up: 改进的模块<3>

1.3.5.11 distutils
..................

The ‘default_format’ attribute has been removed from
‘distutils.command.sdist.sdist’ and the ‘formats’ attribute defaults to
‘['gztar']’.  Although not anticipated, any code relying on the presence
of ‘default_format’ may need to be adapted.  See bpo-27819(1) for more
details.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27819


File: python.info,  Node: email,  Next: encodings,  Prev: distutils<2>,  Up: 改进的模块<3>

1.3.5.12 email
..............

The new email API, enabled via the `policy' keyword to various
constructors, is no longer provisional.  The *note email: 69.
documentation has been reorganized and rewritten to focus on the new
API, while retaining the old documentation for the legacy API.
(Contributed by R. David Murray in bpo-24277(1).)

The *note email.mime: 73. classes now all accept an optional `policy'
keyword.  (Contributed by Berker Peksag in bpo-27331(2).)

The *note DecodedGenerator: 547. now supports the `policy' keyword.

There is a new *note policy: 75. attribute, *note message_factory: 548,
that controls what class is used by default when the parser creates new
message objects.  For the *note email.policy.compat32: 549. policy this
is *note Message: 54a, for the new policies it is *note EmailMessage:
54b.  (Contributed by R. David Murray in bpo-20476(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24277

   (2) https://bugs.python.org/issue27331

   (3) https://bugs.python.org/issue20476


File: python.info,  Node: encodings,  Next: enum<3>,  Prev: email,  Up: 改进的模块<3>

1.3.5.13 encodings
..................

On Windows, added the ‘'oem'’ encoding to use ‘CP_OEMCP’, and the
‘'ansi'’ alias for the existing ‘'mbcs'’ encoding, which uses the
‘CP_ACP’ code page.  (Contributed by Steve Dower in bpo-27959(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27959


File: python.info,  Node: enum<3>,  Next: faulthandler,  Prev: encodings,  Up: 改进的模块<3>

1.3.5.14 enum
.............

Two new enumeration base classes have been added to the *note enum: 7b.
module: *note Flag: 54e. and ‘IntFlags’.  Both are used to define
constants that can be combined using the bitwise operators.
(Contributed by Ethan Furman in bpo-23591(1).)

Many standard library modules have been updated to use the ‘IntFlags’
class for their constants.

The new *note enum.auto: 54f. value can be used to assign values to enum
members automatically:

     >>> from enum import Enum, auto
     >>> class Color(Enum):
     ...     red = auto()
     ...     blue = auto()
     ...     green = auto()
     ...
     >>> list(Color)
     [<Color.red: 1>, <Color.blue: 2>, <Color.green: 3>]

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23591


File: python.info,  Node: faulthandler,  Next: fileinput,  Prev: enum<3>,  Up: 改进的模块<3>

1.3.5.15 faulthandler
.....................

On Windows, the *note faulthandler: 7d. module now installs a handler
for Windows exceptions: see *note faulthandler.enable(): 551.
(Contributed by Victor Stinner in bpo-23848(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23848


File: python.info,  Node: fileinput,  Next: hashlib,  Prev: faulthandler,  Up: 改进的模块<3>

1.3.5.16 fileinput
..................

*note hook_encoded(): 553. now supports the `errors' argument.
(Contributed by Joseph Hackman in bpo-25788(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25788


File: python.info,  Node: hashlib,  Next: http client<2>,  Prev: fileinput,  Up: 改进的模块<3>

1.3.5.17 hashlib
................

*note hashlib: 8d. supports OpenSSL 1.1.0.  The minimum recommend
version is 1.0.2.  (Contributed by Christian Heimes in bpo-26470(1).)

BLAKE2 hash functions were added to the module.  *note blake2b(): 555.
and *note blake2s(): 556. are always available and support the full
feature set of BLAKE2.  (Contributed by Christian Heimes in bpo-26798(2)
based on code by Dmitry Chestnykh and Samuel Neves.  Documentation
written by Dmitry Chestnykh.)

The SHA-3 hash functions ‘sha3_224()’, ‘sha3_256()’, ‘sha3_384()’,
‘sha3_512()’, and SHAKE hash functions ‘shake_128()’ and ‘shake_256()’
were added.  (Contributed by Christian Heimes in bpo-16113(3).  Keccak
Code Package by Guido Bertoni, Joan Daemen, Michaël Peeters, Gilles Van
Assche, and Ronny Van Keer.)

The password-based key derivation function *note scrypt(): 4da. is now
available with OpenSSL 1.1.0 and newer.  (Contributed by Christian
Heimes in bpo-27928(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26470

   (2) https://bugs.python.org/issue26798

   (3) https://bugs.python.org/issue16113

   (4) https://bugs.python.org/issue27928


File: python.info,  Node: http client<2>,  Next: idlelib 与 IDLE<2>,  Prev: hashlib,  Up: 改进的模块<3>

1.3.5.18 http.client
....................

*note HTTPConnection.request(): 558. and *note endheaders(): 559. both
now support chunked encoding request bodies.  (Contributed by Demian
Brecht and Rolf Krahl in bpo-12319(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12319


File: python.info,  Node: idlelib 与 IDLE<2>,  Next: importlib<3>,  Prev: http client<2>,  Up: 改进的模块<3>

1.3.5.19 idlelib 与 IDLE
........................

The idlelib package is being modernized and refactored to make IDLE look
and work better and to make the code easier to understand, test, and
improve.  Part of making IDLE look better, especially on Linux and Mac,
is using ttk widgets, mostly in the dialogs.  As a result, IDLE no
longer runs with tcl/tk 8.4.  It now requires tcl/tk 8.5 or 8.6.  We
recommend running the latest release of either.

’Modernizing’ includes renaming and consolidation of idlelib modules.
The renaming of files with partial uppercase names is similar to the
renaming of, for instance, Tkinter and TkFont to tkinter and
tkinter.font in 3.0.  As a result, imports of idlelib files that worked
in 3.5 will usually not work in 3.6.  At least a module name change will
be needed (see idlelib/README.txt), sometimes more.  (Name changes
contributed by Al Swiegart and Terry Reedy in bpo-24225(1).  Most
idlelib patches since have been and will be part of the process.)

In compensation, the eventual result with be that some idlelib classes
will be easier to use, with better APIs and docstrings explaining them.
Additional useful information will be added to idlelib when available.

在 3.6.2 中新增:

多个对自动补全的修正。 （由 Louie Lu 在 bpo-15786(2) 中贡献。）

在 3.6.3 中新增:

Module Browser (在 File 菜单中，之前称为 Class Browser) 现在会在最高层级
函数和类之外显示嵌套的函数和类。 （由 Guilherme Polo, Cheryl Sabella 和
Terry Jan Reedy 在 bpo-1612262(3) 中贡献。）

之前以扩展形式实现的 IDLE 特性已作为正常特性重新实现。 它们的设置已从
Extensions 选项卡移至其他对话框选项卡。 （由 Charles Wohlganger 和 Terry
Jan Reedy 在 bpo-27099(4) 中实现。）

Settings 对话框 (Options 中的 Configure IDLE) 已经被部分重写以改进外观和
功能。 （由 Cheryl Sabella 和 Terry Jan Reedy 在多个问题项中贡献。）

在 3.6.4 中新增:

字体样本现在包括一组非拉丁字符以便用户能更好地查看所选特定字体的效果。 （
由 Terry Jan Reedy 在 bpo-13802(5) 中贡献。） 样本可以被修改以包括其他字
符。 （由 Serhiy Storchaka 在 bpo-31860(6) 中贡献。）

在 3.6.6 中新增:

编辑器代码上下文选项已经过修改。 Box 会显示所有上下文行直到最大行数。 点
击一个上下文行会使编辑器跳转到该行。 自定义主题的上下文颜色已添加到
Settings 对话框的 Highlights 选项卡。 （由 Cheryl Sabella 和 Terry Jan
Reedy 在 bpo-33642(7), bpo-33768(8) 和 bpo-33679(9) 中贡献。）

在 Windows 上，会有新的 API 调用将 tk 对 DPI 的调整告知 Windows。 在
Windows 8.1+ 或 10 上，如果 Python 二进制码的 DPI 兼容属性未改变，并且监
视器分辨率大于 96 DPI，这应该会令文本和线条更清晰。 否则的话它应该不造成
影响。 （由 Terry Jan Reedy 在 bpo-33656(10) 中贡献。）

在 3.6.7 中新增:

超过 N 行（默认值为 50）的输出将被折叠为一个按钮。 N 可以在 Settings 对
话框的 General 页的 PyShell 部分中进行修改。 数量较少但是超长的行可以通
过在输出上右击来折叠。 被折叠的输出可通过双击按钮来展开，或是通过右击按
钮来放入剪贴板或是单独的窗口。 （由 Tal Einat 在 bpo-1529353(11) 中贡献
。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24225

   (2) https://bugs.python.org/issue15786

   (3) https://bugs.python.org/issue1612262

   (4) https://bugs.python.org/issue27099

   (5) https://bugs.python.org/issue13802

   (6) https://bugs.python.org/issue31860

   (7) https://bugs.python.org/issue33642

   (8) https://bugs.python.org/issue33768

   (9) https://bugs.python.org/issue33679

   (10) https://bugs.python.org/issue33656

   (11) https://bugs.python.org/issue1529353


File: python.info,  Node: importlib<3>,  Next: inspect<2>,  Prev: idlelib 与 IDLE<2>,  Up: 改进的模块<3>

1.3.5.20 importlib
..................

Import now raises the new exception *note ModuleNotFoundError: 3a2.
(subclass of *note ImportError: 33d.) when it cannot find a module.
Code that current checks for ‘ImportError’ (in try-except) will still
work.  (Contributed by Eric Snow in bpo-15767(1).)

*note importlib.util.LazyLoader: 55c. now calls *note create_module():
55d. on the wrapped loader, removing the restriction that *note
importlib.machinery.BuiltinImporter: 55e. and *note
importlib.machinery.ExtensionFileLoader: 55f. couldn’t be used with
*note importlib.util.LazyLoader: 55c.

*note importlib.util.cache_from_source(): 560, *note
importlib.util.source_from_cache(): 561, and *note
importlib.util.spec_from_file_location(): 562. now accept a *note
path-like object: 373.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15767


File: python.info,  Node: inspect<2>,  Next: json,  Prev: importlib<3>,  Up: 改进的模块<3>

1.3.5.21 inspect
................

The *note inspect.signature(): 564. function now reports the implicit
‘.0’ parameters generated by the compiler for comprehension and
generator expression scopes as if they were positional-only parameters
called ‘implicit0’.  (Contributed by Jelle Zijlstra in bpo-19611(1).)

To reduce code churn when upgrading from Python 2.7 and the legacy *note
inspect.getargspec(): 565. API, the previously documented deprecation of
*note inspect.getfullargspec(): 566. has been reversed.  While this
function is convenient for single/source Python 2/3 code bases, the
richer *note inspect.signature(): 564. interface remains the recommended
approach for new code.  (Contributed by Nick Coghlan in bpo-27172(2))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19611

   (2) https://bugs.python.org/issue27172


File: python.info,  Node: json,  Next: logging<3>,  Prev: inspect<2>,  Up: 改进的模块<3>

1.3.5.22 json
.............

*note json.load(): 568. and *note json.loads(): 569. now support binary
input.  Encoded JSON should be represented using either UTF-8, UTF-16,
or UTF-32.  (Contributed by Serhiy Storchaka in bpo-17909(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17909


File: python.info,  Node: logging<3>,  Next: math<3>,  Prev: json,  Up: 改进的模块<3>

1.3.5.23 logging
................

The new *note WatchedFileHandler.reopenIfNeeded(): 56b. method has been
added to add the ability to check if the log file needs to be reopened.
(Contributed by Marian Horban in bpo-24884(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24884


File: python.info,  Node: math<3>,  Next: multiprocessing<3>,  Prev: logging<3>,  Up: 改进的模块<3>

1.3.5.24 math
.............

The tau (`τ') constant has been added to the *note math: b2. and *note
cmath: 19. modules.  (Contributed by Lisa Roach in bpo-12345(1), see PEP
628(2) for details.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12345

   (2) https://www.python.org/dev/peps/pep-0628


File: python.info,  Node: multiprocessing<3>,  Next: os<3>,  Prev: math<3>,  Up: 改进的模块<3>

1.3.5.25 multiprocessing
........................

*note Proxy Objects: 56e. returned by ‘multiprocessing.Manager()’ can
now be nested.  (Contributed by Davin Potts in bpo-6766(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6766


File: python.info,  Node: os<3>,  Next: pathlib<3>,  Prev: multiprocessing<3>,  Up: 改进的模块<3>

1.3.5.26 os
...........

See the summary of *note PEP 519: 4d5. for details on how the *note os:
c5. and *note os.path: c6. modules now support *note path-like objects:
373.

*note scandir(): 260. now supports *note bytes: 33a. paths on Windows.

A new *note close(): 570. method allows explicitly closing a *note
scandir(): 260. iterator.  The *note scandir(): 260. iterator now
supports the *note context manager: 571. protocol.  If a ‘scandir()’
iterator is neither exhausted nor explicitly closed a *note
ResourceWarning: 4d8. will be emitted in its destructor.  (Contributed
by Serhiy Storchaka in bpo-25994(1).)

在 Linux 上，现在 *note os.urandom(): 4d9. 会阻塞直到系统的 urandom 熵池
被初始化以提升安全性。 其理由参见 PEP 524(2)。

The Linux ‘getrandom()’ syscall (get random bytes) is now exposed as the
new *note os.getrandom(): 572. function.  (Contributed by Victor
Stinner, part of the PEP 524(3))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25994

   (2) https://www.python.org/dev/peps/pep-0524

   (3) https://www.python.org/dev/peps/pep-0524


File: python.info,  Node: pathlib<3>,  Next: pdb<2>,  Prev: os<3>,  Up: 改进的模块<3>

1.3.5.27 pathlib
................

*note pathlib: c9. now supports *note path-like objects: 373.
(Contributed by Brett Cannon in bpo-27186(1).)

See the summary of *note PEP 519: 4d5. for details.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27186


File: python.info,  Node: pdb<2>,  Next: pickle<2>,  Prev: pathlib<3>,  Up: 改进的模块<3>

1.3.5.28 pdb
............

The *note Pdb: 575. class constructor has a new optional `readrc'
argument to control whether ‘.pdbrc’ files should be read.


File: python.info,  Node: pickle<2>,  Next: pickletools,  Prev: pdb<2>,  Up: 改进的模块<3>

1.3.5.29 pickle
...............

Objects that need ‘__new__’ called with keyword arguments can now be
pickled using *note pickle protocols: 577. older than protocol version
4.  Protocol version 4 already supports this case.  (Contributed by
Serhiy Storchaka in bpo-24164(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24164


File: python.info,  Node: pickletools,  Next: pydoc<2>,  Prev: pickle<2>,  Up: 改进的模块<3>

1.3.5.30 pickletools
....................

*note pickletools.dis(): 579. now outputs the implicit memo index for
the ‘MEMOIZE’ opcode.  (Contributed by Serhiy Storchaka in
bpo-25382(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25382


File: python.info,  Node: pydoc<2>,  Next: random,  Prev: pickletools,  Up: 改进的模块<3>

1.3.5.31 pydoc
..............

The *note pydoc: da. module has learned to respect the ‘MANPAGER’
environment variable.  (Contributed by Matthias Klose in bpo-8637(1).)

*note help(): 57b. and *note pydoc: da. can now list named tuple fields
in the order they were defined rather than alphabetically.  (Contributed
by Raymond Hettinger in bpo-24879(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8637

   (2) https://bugs.python.org/issue24879


File: python.info,  Node: random,  Next: re<2>,  Prev: pydoc<2>,  Up: 改进的模块<3>

1.3.5.32 random
...............

The new *note choices(): 57d. function returns a list of elements of
specified size from the given population with optional weights.
(Contributed by Raymond Hettinger in bpo-18844(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18844


File: python.info,  Node: re<2>,  Next: readline,  Prev: random,  Up: 改进的模块<3>

1.3.5.33 re
...........

Added support of modifier spans in regular expressions.  Examples:
‘'(?i:p)ython'’ matches ‘'python'’ and ‘'Python'’, but not ‘'PYTHON'’;
‘'(?i)g(?-i:v)r'’ matches ‘'GvR'’ and ‘'gvr'’, but not ‘'GVR'’.
(Contributed by Serhiy Storchaka in bpo-433028(1).)

Match object groups can be accessed by ‘__getitem__’, which is
equivalent to ‘group()’.  So ‘mo['name']’ is now equivalent to
‘mo.group('name')’.  (Contributed by Eric Smith in bpo-24454(2).)

‘Match’ objects now support *note index-like objects: 18b. as group
indices.  (Contributed by Jeroen Demeyer and Xiang Zhang in
bpo-27177(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue433028

   (2) https://bugs.python.org/issue24454

   (3) https://bugs.python.org/issue27177


File: python.info,  Node: readline,  Next: rlcompleter,  Prev: re<2>,  Up: 改进的模块<3>

1.3.5.34 readline
.................

Added *note set_auto_history(): 580. to enable or disable automatic
addition of input to the history list.  (Contributed by Tyler Crompton
in bpo-26870(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26870


File: python.info,  Node: rlcompleter,  Next: shlex<2>,  Prev: readline,  Up: 改进的模块<3>

1.3.5.35 rlcompleter
....................

Private and special attribute names now are omitted unless the prefix
starts with underscores.  A space or a colon is added after some
completed keywords.  (Contributed by Serhiy Storchaka in bpo-25011(1)
and bpo-25209(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25011

   (2) https://bugs.python.org/issue25209


File: python.info,  Node: shlex<2>,  Next: site,  Prev: rlcompleter,  Up: 改进的模块<3>

1.3.5.36 shlex
..............

The *note shlex: 583. has much *note improved shell compatibility: 584.
through the new `punctuation_chars' argument to control which characters
are treated as punctuation.  (Contributed by Vinay Sajip in
bpo-1521950(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1521950


File: python.info,  Node: site,  Next: sqlite3<2>,  Prev: shlex<2>,  Up: 改进的模块<3>

1.3.5.37 site
.............

When specifying paths to add to *note sys.path: 490. in a ‘.pth’ file,
you may now specify file paths on top of directories (e.g.  zip files).
(Contributed by Wolfgang Langner in bpo-26587(1)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26587


File: python.info,  Node: sqlite3<2>,  Next: socket<4>,  Prev: site,  Up: 改进的模块<3>

1.3.5.38 sqlite3
................

*note sqlite3.Cursor.lastrowid: 587. now supports the ‘REPLACE’
statement.  (Contributed by Alex LordThorsen in bpo-16864(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16864


File: python.info,  Node: socket<4>,  Next: socketserver<2>,  Prev: sqlite3<2>,  Up: 改进的模块<3>

1.3.5.39 socket
...............

The *note ioctl(): 589. function now supports the *note
SIO_LOOPBACK_FAST_PATH: 58a. control code.  (Contributed by Daniel
Stokes in bpo-26536(1).)

The *note getsockopt(): 58b. constants ‘SO_DOMAIN’, ‘SO_PROTOCOL’,
‘SO_PEERSEC’, and ‘SO_PASSSEC’ are now supported.  (Contributed by
Christian Heimes in bpo-26907(2).)

The *note setsockopt(): 58c. now supports the ‘setsockopt(level,
optname, None, optlen: int)’ form.  (Contributed by Christian Heimes in
bpo-27744(3).)

The socket module now supports the address family *note AF_ALG: 58d. to
interface with Linux Kernel crypto API. ‘ALG_*’, ‘SOL_ALG’ and *note
sendmsg_afalg(): 58e. were added.  (Contributed by Christian Heimes in
bpo-27744(4) with support from Victor Stinner.)

New Linux constants ‘TCP_USER_TIMEOUT’ and ‘TCP_CONGESTION’ were added.
(Contributed by Omar Sandoval, issue:‘26273’).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26536

   (2) https://bugs.python.org/issue26907

   (3) https://bugs.python.org/issue27744

   (4) https://bugs.python.org/issue27744


File: python.info,  Node: socketserver<2>,  Next: ssl<4>,  Prev: socket<4>,  Up: 改进的模块<3>

1.3.5.40 socketserver
.....................

Servers based on the *note socketserver: f1. module, including those
defined in *note http.server: 97, *note xmlrpc.server: 141. and *note
wsgiref.simple_server: 130, now support the *note context manager: 571.
protocol.  (Contributed by Aviv Palivoda in bpo-26404(1).)

The ‘wfile’ attribute of *note StreamRequestHandler: 590. classes now
implements the *note io.BufferedIOBase: 591. writable interface.  In
particular, calling *note write(): 592. is now guaranteed to send the
data in full.  (Contributed by Martin Panter in bpo-26721(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26404

   (2) https://bugs.python.org/issue26721


File: python.info,  Node: ssl<4>,  Next: statistics<2>,  Prev: socketserver<2>,  Up: 改进的模块<3>

1.3.5.41 ssl
............

*note ssl: f4. supports OpenSSL 1.1.0.  The minimum recommend version is
1.0.2.  (Contributed by Christian Heimes in bpo-26470(1).)

3DES has been removed from the default cipher suites and ChaCha20
Poly1305 cipher suites have been added.  (Contributed by Christian
Heimes in bpo-27850(2) and bpo-27766(3).)

*note SSLContext: 3ec. has better default configuration for options and
ciphers.  (Contributed by Christian Heimes in bpo-28043(4).)

SSL session can be copied from one client-side connection to another
with the new *note SSLSession: 594. class.  TLS session resumption can
speed up the initial handshake, reduce latency and improve performance
(Contributed by Christian Heimes in bpo-19500(5) based on a draft by
Alex Warhawk.)

The new *note get_ciphers(): 595. method can be used to get a list of
enabled ciphers in order of cipher priority.

All constants and flags have been converted to *note IntEnum: 596. and
‘IntFlags’.  (Contributed by Christian Heimes in bpo-28025(6).)

Server and client-side specific TLS protocols for *note SSLContext: 3ec.
were added.  (Contributed by Christian Heimes in bpo-28085(7).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26470

   (2) https://bugs.python.org/issue27850

   (3) https://bugs.python.org/issue27766

   (4) https://bugs.python.org/issue28043

   (5) https://bugs.python.org/issue19500

   (6) https://bugs.python.org/issue28025

   (7) https://bugs.python.org/issue28085


File: python.info,  Node: statistics<2>,  Next: struct,  Prev: ssl<4>,  Up: 改进的模块<3>

1.3.5.42 statistics
...................

A new *note harmonic_mean(): 598. function has been added.  (Contributed
by Steven D’Aprano in bpo-27181(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27181


File: python.info,  Node: struct,  Next: subprocess<2>,  Prev: statistics<2>,  Up: 改进的模块<3>

1.3.5.43 struct
...............

*note struct: f9. now supports IEEE 754 half-precision floats via the
‘'e'’ format specifier.  (Contributed by Eli Stevens, Mark Dickinson in
bpo-11734(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11734


File: python.info,  Node: subprocess<2>,  Next: sys<4>,  Prev: struct,  Up: 改进的模块<3>

1.3.5.44 subprocess
...................

*note subprocess.Popen: 2ba. destructor now emits a *note
ResourceWarning: 4d8. warning if the child process is still running.
Use the context manager protocol (‘with proc: ...’) or explicitly call
the *note wait(): 59b. method to read the exit status of the child
process.  (Contributed by Victor Stinner in bpo-26741(1).)

The *note subprocess.Popen: 2ba. constructor and all functions that pass
arguments through to it now accept `encoding' and `errors' arguments.
Specifying either of these will enable text mode for the `stdin',
`stdout' and `stderr' streams.  (Contributed by Steve Dower in
bpo-6135(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26741

   (2) https://bugs.python.org/issue6135


File: python.info,  Node: sys<4>,  Next: telnetlib,  Prev: subprocess<2>,  Up: 改进的模块<3>

1.3.5.45 sys
............

The new *note getfilesystemencodeerrors(): 59d. function returns the
name of the error mode used to convert between Unicode filenames and
bytes filenames.  (Contributed by Steve Dower in bpo-27781(1).)

On Windows the return value of the *note getwindowsversion(): 59e.
function now includes the `platform_version' field which contains the
accurate major version, minor version and build number of the current
operating system, rather than the version that is being emulated for the
process (Contributed by Steve Dower in bpo-27932(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27781

   (2) https://bugs.python.org/issue27932


File: python.info,  Node: telnetlib,  Next: time<3>,  Prev: sys<4>,  Up: 改进的模块<3>

1.3.5.46 telnetlib
..................

*note Telnet: 5a0. is now a context manager (contributed by Stéphane
Wirtel in bpo-25485(1)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25485


File: python.info,  Node: time<3>,  Next: timeit,  Prev: telnetlib,  Up: 改进的模块<3>

1.3.5.47 time
.............

The *note struct_time: 5a2. attributes ‘tm_gmtoff’ and ‘tm_zone’ are now
available on all platforms.


File: python.info,  Node: timeit,  Next: tkinter<3>,  Prev: time<3>,  Up: 改进的模块<3>

1.3.5.48 timeit
...............

The new *note Timer.autorange(): 5a4. convenience method has been added
to call *note Timer.timeit(): 5a5. repeatedly so that the total run time
is greater or equal to 200 milliseconds.  (Contributed by Steven
D’Aprano in bpo-6422(1).)

*note timeit: 10c. now warns when there is substantial (4x) variance
between best and worst times.  (Contributed by Serhiy Storchaka in
bpo-23552(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6422

   (2) https://bugs.python.org/issue23552


File: python.info,  Node: tkinter<3>,  Next: 回溯,  Prev: timeit,  Up: 改进的模块<3>

1.3.5.49 tkinter
................

Added methods ‘trace_add()’, ‘trace_remove()’ and ‘trace_info()’ in the
‘tkinter.Variable’ class.  They replace old methods ‘trace_variable()’,
‘trace()’, ‘trace_vdelete()’ and ‘trace_vinfo()’ that use obsolete Tcl
commands and might not work in future versions of Tcl.  (Contributed by
Serhiy Storchaka in bpo-22115(1)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22115


File: python.info,  Node: 回溯,  Next: tracemalloc<2>,  Prev: tkinter<3>,  Up: 改进的模块<3>

1.3.5.50 回溯
.............

Both the traceback module and the interpreter’s builtin exception
display now abbreviate long sequences of repeated lines in tracebacks as
shown in the following example:

     >>> def f(): f()
     ...
     >>> f()
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
       File "<stdin>", line 1, in f
       File "<stdin>", line 1, in f
       File "<stdin>", line 1, in f
       [Previous line repeated 995 more times]
     RecursionError: maximum recursion depth exceeded

（由 Emanuel Barry在 bpo-26823(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26823


File: python.info,  Node: tracemalloc<2>,  Next: typing<2>,  Prev: 回溯,  Up: 改进的模块<3>

1.3.5.51 tracemalloc
....................

The *note tracemalloc: 115. module now supports tracing memory
allocations in multiple different address spaces.

The new *note DomainFilter: 5a9. filter class has been added to filter
block traces by their address space (domain).

（由 Victor Stinner 在 bpo-26588(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26588


File: python.info,  Node: typing<2>,  Next: unicodedata<3>,  Prev: tracemalloc<2>,  Up: 改进的模块<3>

1.3.5.52 typing
...............

Since the *note typing: 11a. module is *note provisional: 351, all
changes introduced in Python 3.6 have also been backported to Python
3.5.x.

The *note typing: 11a. module has a much improved support for generic
type aliases.  For example ‘Dict[str, Tuple[S, T]]’ is now a valid type
annotation.  (Contributed by Guido van Rossum in Github #195(1).)

The *note typing.ContextManager: 53d. class has been added for
representing *note contextlib.AbstractContextManager: 53c.  (Contributed
by Brett Cannon in bpo-25609(2).)

The *note typing.Collection: 5ab. class has been added for representing
*note collections.abc.Collection: 535.  (Contributed by Ivan Levkivskyi
in bpo-27598(3).)

The *note typing.ClassVar: 5ac. type construct has been added to mark
class variables.  As introduced in PEP 526(4), a variable annotation
wrapped in ClassVar indicates that a given attribute is intended to be
used as a class variable and should not be set on instances of that
class.  (Contributed by Ivan Levkivskyi in Github #280(5).)

A new *note TYPE_CHECKING: 5ad. constant that is assumed to be ‘True’ by
the static type checkers, but is ‘False’ at runtime.  (Contributed by
Guido van Rossum in Github #230(6).)

A new *note NewType(): 5ae. helper function has been added to create
lightweight distinct types for annotations:

     from typing import NewType

     UserId = NewType('UserId', int)
     some_id = UserId(524313)

The static type checker will treat the new type as if it were a subclass
of the original type.  (Contributed by Ivan Levkivskyi in Github
#189(7).)

   ---------- Footnotes ----------

   (1) https://github.com/python/typing/pull/195

   (2) https://bugs.python.org/issue25609

   (3) https://bugs.python.org/issue27598

   (4) https://www.python.org/dev/peps/pep-0526

   (5) https://github.com/python/typing/pull/280

   (6) https://github.com/python/typing/issues/230

   (7) https://github.com/python/typing/issues/189


File: python.info,  Node: unicodedata<3>,  Next: unittest mock<2>,  Prev: typing<2>,  Up: 改进的模块<3>

1.3.5.53 unicodedata
....................

The *note unicodedata: 11b. module now uses data from Unicode 9.0.0(1).
(Contributed by Benjamin Peterson.)

   ---------- Footnotes ----------

   (1) http://unicode.org/versions/Unicode9.0.0/


File: python.info,  Node: unittest mock<2>,  Next: urllib request,  Prev: unicodedata<3>,  Up: 改进的模块<3>

1.3.5.54 unittest.mock
......................

The *note Mock: 24a. class has the following improvements:

   * Two new methods, *note Mock.assert_called(): 5b1. and *note
     Mock.assert_called_once(): 5b2. to check if the mock object was
     called.  (Contributed by Amit Saha in bpo-26323(1).)

   * The *note Mock.reset_mock(): 5b3. method now has two optional
     keyword only arguments: `return_value' and `side_effect'.
     (Contributed by Kushal Das in bpo-21271(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26323

   (2) https://bugs.python.org/issue21271


File: python.info,  Node: urllib request,  Next: urllib robotparser,  Prev: unittest mock<2>,  Up: 改进的模块<3>

1.3.5.55 urllib.request
.......................

If a HTTP request has a file or iterable body (other than a bytes
object) but no ‘Content-Length’ header, rather than throwing an error,
‘AbstractHTTPHandler’ now falls back to use chunked transfer encoding.
(Contributed by Demian Brecht and Rolf Krahl in bpo-12319(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12319


File: python.info,  Node: urllib robotparser,  Next: venv<2>,  Prev: urllib request,  Up: 改进的模块<3>

1.3.5.56 urllib.robotparser
...........................

*note RobotFileParser: 5b6. now supports the ‘Crawl-delay’ and
‘Request-rate’ extensions.  (Contributed by Nikolay Bogoychev in
bpo-16099(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16099


File: python.info,  Node: venv<2>,  Next: warnings<2>,  Prev: urllib robotparser,  Up: 改进的模块<3>

1.3.5.57 venv
.............

*note venv: 126. accepts a new parameter ‘--prompt’.  This parameter
provides an alternative prefix for the virtual environment.  (Proposed
by Łukasz Balcerzak and ported to 3.6 by Stéphane Wirtel in
bpo-22829(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22829


File: python.info,  Node: warnings<2>,  Next: winreg,  Prev: venv<2>,  Up: 改进的模块<3>

1.3.5.58 warnings
.................

A new optional `source' parameter has been added to the *note
warnings.warn_explicit(): 5b9. function: the destroyed object which
emitted a *note ResourceWarning: 4d8.  A `source' attribute has also
been added to ‘warnings.WarningMessage’ (contributed by Victor Stinner
in bpo-26568(1) and bpo-26567(2)).

When a *note ResourceWarning: 4d8. warning is logged, the *note
tracemalloc: 115. module is now used to try to retrieve the traceback
where the destroyed object was allocated.

Example with the script ‘example.py’:

     import warnings

     def func():
         return open(__file__)

     f = func()
     f = None

Output of the command ‘python3.6 -Wd -X tracemalloc=5 example.py’:

     example.py:7: ResourceWarning: unclosed file <_io.TextIOWrapper name='example.py' mode='r' encoding='UTF-8'>
       f = None
     Object allocated at (most recent call first):
       File "example.py", lineno 4
         return open(__file__)
       File "example.py", lineno 6
         f = func()

The "Object allocated at" traceback is new and is only displayed if
*note tracemalloc: 115. is tracing Python memory allocations and if the
*note warnings: 127. module was already imported.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26568

   (2) https://bugs.python.org/issue26567


File: python.info,  Node: winreg,  Next: winsound,  Prev: warnings<2>,  Up: 改进的模块<3>

1.3.5.59 winreg
...............

Added the 64-bit integer type *note REG_QWORD: 5bb.  (Contributed by
Clement Rouault in bpo-23026(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23026


File: python.info,  Node: winsound,  Next: xmlrpc client,  Prev: winreg,  Up: 改进的模块<3>

1.3.5.60 winsound
.................

Allowed keyword arguments to be passed to *note Beep: 5bd, *note
MessageBeep: 5be, and *note PlaySound: 5bf. (bpo-27982(1)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27982


File: python.info,  Node: xmlrpc client,  Next: zipfile<2>,  Prev: winsound,  Up: 改进的模块<3>

1.3.5.61 xmlrpc.client
......................

The *note xmlrpc.client: 140. module now supports unmarshalling
additional data types used by the Apache XML-RPC implementation for
numerics and ‘None’.  (Contributed by Serhiy Storchaka in bpo-26885(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26885


File: python.info,  Node: zipfile<2>,  Next: zlib,  Prev: xmlrpc client,  Up: 改进的模块<3>

1.3.5.62 zipfile
................

A new *note ZipInfo.from_file(): 5c2. class method allows making a *note
ZipInfo: 5c3. instance from a filesystem file.  A new *note
ZipInfo.is_dir(): 5c4. method can be used to check if the *note ZipInfo:
5c3. instance represents a directory.  (Contributed by Thomas Kluyver in
bpo-26039(1).)

The *note ZipFile.open(): 5c5. method can now be used to write data into
a ZIP file, as well as for extracting data.  (Contributed by Thomas
Kluyver in bpo-26039(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26039

   (2) https://bugs.python.org/issue26039


File: python.info,  Node: zlib,  Prev: zipfile<2>,  Up: 改进的模块<3>

1.3.5.63 zlib
.............

The *note compress(): 5c7. and *note decompress(): 5c8. functions now
accept keyword arguments.  (Contributed by Aviv Palivoda in bpo-26243(1)
and Xiang Zhang in bpo-16764(2) respectively.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26243

   (2) https://bugs.python.org/issue16764


File: python.info,  Node: 性能优化<3>,  Next: 构建和 C API 的改变<2>,  Prev: 改进的模块<3>,  Up: Python 3 6 有什么新变化

1.3.6 性能优化
--------------

   * The Python interpreter now uses a 16-bit wordcode instead of
     bytecode which made a number of opcode optimizations possible.
     (Contributed by Demur Rumed with input and reviews from Serhiy
     Storchaka and Victor Stinner in bpo-26647(1) and bpo-28050(2).)

   * The *note asyncio.Future: 44b. class now has an optimized C
     implementation.  (Contributed by Yury Selivanov and INADA Naoki in
     bpo-26081(3).)

   * The *note asyncio.Task: 1ae. class now has an optimized C
     implementation.  (Contributed by Yury Selivanov in bpo-28544(4).)

   * Various implementation improvements in the *note typing: 11a.
     module (such as caching of generic types) allow up to 30 times
     performance improvements and reduced memory footprint.

   * The ASCII decoder is now up to 60 times as fast for error handlers
     ‘surrogateescape’, ‘ignore’ and ‘replace’ (Contributed by Victor
     Stinner in bpo-24870(5)).

   * The ASCII and the Latin1 encoders are now up to 3 times as fast for
     the error handler ‘surrogateescape’ (Contributed by Victor Stinner
     in bpo-25227(6)).

   * The UTF-8 encoder is now up to 75 times as fast for error handlers
     ‘ignore’, ‘replace’, ‘surrogateescape’, ‘surrogatepass’
     (Contributed by Victor Stinner in bpo-25267(7)).

   * The UTF-8 decoder is now up to 15 times as fast for error handlers
     ‘ignore’, ‘replace’ and ‘surrogateescape’ (Contributed by Victor
     Stinner in bpo-25301(8)).

   * ‘bytes % args’ is now up to 2 times faster.  (Contributed by Victor
     Stinner in bpo-25349(9)).

   * ‘bytearray % args’ is now between 2.5 and 5 times faster.
     (Contributed by Victor Stinner in bpo-25399(10)).

   * Optimize *note bytes.fromhex(): 337. and *note bytearray.fromhex():
     338.: they are now between 2x and 3.5x faster.  (Contributed by
     Victor Stinner in bpo-25401(11)).

   * Optimize ‘bytes.replace(b'', b'.')’ and ‘bytearray.replace(b'',
     b'.')’: up to 80% faster.  (Contributed by Josh Snider in
     bpo-26574(12)).

   * Allocator functions of the *note PyMem_Malloc(): 50d. domain (*note
     PYMEM_DOMAIN_MEM: 511.) now use the *note pymalloc memory
     allocator: 5ca. instead of ‘malloc()’ function of the C library.
     The pymalloc allocator is optimized for objects smaller or equal to
     512 bytes with a short lifetime, and use ‘malloc()’ for larger
     memory blocks.  (Contributed by Victor Stinner in bpo-26249(13)).

   * *note pickle.load(): 5cb. and *note pickle.loads(): 5cc. are now up
     to 10% faster when deserializing many small objects (Contributed by
     Victor Stinner in bpo-27056(14)).

   * Passing *note keyword arguments: 5cd. to a function has an overhead
     in comparison with passing *note positional arguments: 5ce.  Now in
     extension functions implemented with using Argument Clinic this
     overhead is significantly decreased.  (Contributed by Serhiy
     Storchaka in bpo-27574(15)).

   * Optimized *note glob(): 5cf. and *note iglob(): 5d0. functions in
     the *note glob: 8a. module; they are now about 3–6 times faster.
     (Contributed by Serhiy Storchaka in bpo-25596(16)).

   * Optimized globbing in *note pathlib: c9. by using *note
     os.scandir(): 260.; it is now about 1.5–4 times faster.
     (Contributed by Serhiy Storchaka in bpo-26032(17)).

   * *note xml.etree.ElementTree: 138. parsing, iteration and deepcopy
     performance has been significantly improved.  (Contributed by
     Serhiy Storchaka in bpo-25638(18), bpo-25873(19), and
     bpo-25869(20).)

   * Creation of *note fractions.Fraction: 186. instances from floats
     and decimals is now 2 to 3 times faster.  (Contributed by Serhiy
     Storchaka in bpo-25971(21).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26647

   (2) https://bugs.python.org/issue28050

   (3) https://bugs.python.org/issue26081

   (4) https://bugs.python.org/issue28544

   (5) https://bugs.python.org/issue24870

   (6) https://bugs.python.org/issue25227

   (7) https://bugs.python.org/issue25267

   (8) https://bugs.python.org/issue25301

   (9) https://bugs.python.org/issue25349

   (10) https://bugs.python.org/issue25399

   (11) https://bugs.python.org/issue25401

   (12) https://bugs.python.org/issue26574

   (13) https://bugs.python.org/issue26249

   (14) https://bugs.python.org/issue27056

   (15) https://bugs.python.org/issue27574

   (16) https://bugs.python.org/issue25596

   (17) https://bugs.python.org/issue26032

   (18) https://bugs.python.org/issue25638

   (19) https://bugs.python.org/issue25873

   (20) https://bugs.python.org/issue25869

   (21) https://bugs.python.org/issue25971


File: python.info,  Node: 构建和 C API 的改变<2>,  Next: 其他改进,  Prev: 性能优化<3>,  Up: Python 3 6 有什么新变化

1.3.7 构建和 C API 的改变
-------------------------

   * Python now requires some C99 support in the toolchain to build.
     Most notably, Python now uses standard integer types and macros in
     place of custom macros like ‘PY_LONG_LONG’.  For more information,
     see PEP 7(1) and bpo-17884(2).

   * Cross-compiling CPython with the Android NDK and the Android API
     level set to 21 (Android 5.0 Lollipop) or greater runs
     successfully.  While Android is not yet a supported platform, the
     Python test suite runs on the Android emulator with only about 16
     tests failures.  See the Android meta-issue bpo-26865(3).

   * The ‘--enable-optimizations’ configure flag has been added.
     Turning it on will activate expensive optimizations like PGO.
     (Original patch by Alecsandru Patrascu of Intel in bpo-26359(4).)

   * The *note GIL: 50e. must now be held when allocator functions of
     *note PYMEM_DOMAIN_OBJ: 50f. (ex: *note PyObject_Malloc(): 510.)
     and *note PYMEM_DOMAIN_MEM: 511. (ex: *note PyMem_Malloc(): 50d.)
     domains are called.

   * New *note Py_FinalizeEx(): 5d2. API which indicates if flushing
     buffered data failed.  (Contributed by Martin Panter in
     bpo-5319(5).)

   * *note PyArg_ParseTupleAndKeywords(): 5d3. now supports *note
     positional-only parameters: 2a8.  Positional-only parameters are
     defined by empty names.  (Contributed by Serhiy Storchaka in
     bpo-26282(6)).

   * ‘PyTraceback_Print’ method now abbreviates long sequences of
     repeated lines as ‘"[Previous line repeated {count} more times]"’.
     (Contributed by Emanuel Barry in bpo-26823(7).)

   * The new *note PyErr_SetImportErrorSubclass(): 5d4. function allows
     for specifying a subclass of *note ImportError: 33d. to raise.
     (Contributed by Eric Snow in bpo-15767(8).)

   * The new *note PyErr_ResourceWarning(): 5d5. function can be used to
     generate a *note ResourceWarning: 4d8. providing the source of the
     resource allocation.  (Contributed by Victor Stinner in
     bpo-26567(9).)

   * The new *note PyOS_FSPath(): 5d6. function returns the file system
     representation of a *note path-like object: 373.  (Contributed by
     Brett Cannon in bpo-27186(10).)

   * The *note PyUnicode_FSConverter(): 5d7. and *note
     PyUnicode_FSDecoder(): 5d8. functions will now accept *note
     path-like objects: 373.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0007

   (2) https://bugs.python.org/issue17884

   (3) https://bugs.python.org/issue26865

   (4) https://bugs.python.org/issue26359

   (5) https://bugs.python.org/issue5319

   (6) https://bugs.python.org/issue26282

   (7) https://bugs.python.org/issue26823

   (8) https://bugs.python.org/issue15767

   (9) https://bugs.python.org/issue26567

   (10) https://bugs.python.org/issue27186


File: python.info,  Node: 其他改进,  Next: 弃用<2>,  Prev: 构建和 C API 的改变<2>,  Up: Python 3 6 有什么新变化

1.3.8 其他改进
--------------

   * When *note –version: 5da. (short form: *note -V: 5db.) is supplied
     twice, Python prints *note sys.version: 5dc. for detailed
     information.

          $ ./python -VV
          Python 3.6.0b4+ (3.6:223967b49e49+, Nov 21 2016, 20:55:04)
          [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]


File: python.info,  Node: 弃用<2>,  Next: 移除,  Prev: 其他改进,  Up: Python 3 6 有什么新变化

1.3.9 弃用
----------

* Menu:

* 新关键字::
* 已弃用的 Python 行为: 已弃用的 Python 行为<2>.
* 已弃用的 Python 模块、函数和方法: 已弃用的 Python 模块、函数和方法<2>.
* 已弃用的 C API 函数和类型: 已弃用的 C API 函数和类型<2>.
* 弃用的构建选项::


File: python.info,  Node: 新关键字,  Next: 已弃用的 Python 行为<2>,  Up: 弃用<2>

1.3.9.1 新关键字
................

‘async’ and ‘await’ are not recommended to be used as variable, class,
function or module names.  Introduced by PEP 492(1) in Python 3.5, they
will become proper keywords in Python 3.7.  Starting in Python 3.6, the
use of ‘async’ or ‘await’ as names will generate a *note
DeprecationWarning: 279.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: 已弃用的 Python 行为<2>,  Next: 已弃用的 Python 模块、函数和方法<2>,  Prev: 新关键字,  Up: 弃用<2>

1.3.9.2 已弃用的 Python 行为
............................

Raising the *note StopIteration: 48e. exception inside a generator will
now generate a *note DeprecationWarning: 279, and will trigger a *note
RuntimeError: 2bb. in Python 3.7.  See *note PEP 479; Change
StopIteration handling inside generators: 5e0. for details.

The *note __aiter__(): 48f. method is now expected to return an
asynchronous iterator directly instead of returning an awaitable as
previously.  Doing the former will trigger a *note DeprecationWarning:
279.  Backward compatibility will be removed in Python 3.7.
(Contributed by Yury Selivanov in bpo-27243(1).)

A backslash-character pair that is not a valid escape sequence now
generates a *note DeprecationWarning: 279.  Although this will
eventually become a *note SyntaxError: 460, that will not be for several
Python releases.  (Contributed by Emanuel Barry in bpo-27364(2).)

When performing a relative import, falling back on ‘__name__’ and
‘__path__’ from the calling module when ‘__spec__’ or ‘__package__’ are
not defined now raises an *note ImportWarning: 5e1.  (Contributed by
Rose Ames in bpo-25791(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27243

   (2) https://bugs.python.org/issue27364

   (3) https://bugs.python.org/issue25791


File: python.info,  Node: 已弃用的 Python 模块、函数和方法<2>,  Next: 已弃用的 C API 函数和类型<2>,  Prev: 已弃用的 Python 行为<2>,  Up: 弃用<2>

1.3.9.3 已弃用的 Python 模块、函数和方法
........................................

* Menu:

* asynchat::
* asyncore::
* dbm: dbm<3>.
* distutils: distutils<3>.
* grp::
* importlib: importlib<4>.
* os: os<4>.
* re: re<3>.
* ssl: ssl<5>.
* tkinter: tkinter<4>.
* venv: venv<3>.


File: python.info,  Node: asynchat,  Next: asyncore,  Up: 已弃用的 Python 模块、函数和方法<2>

1.3.9.4 asynchat
................

The *note asynchat: 9. has been deprecated in favor of *note asyncio: a.
(Contributed by Mariatta in bpo-25002(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25002


File: python.info,  Node: asyncore,  Next: dbm<3>,  Prev: asynchat,  Up: 已弃用的 Python 模块、函数和方法<2>

1.3.9.5 asyncore
................

The *note asyncore: b. has been deprecated in favor of *note asyncio: a.
(Contributed by Mariatta in bpo-25002(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25002


File: python.info,  Node: dbm<3>,  Next: distutils<3>,  Prev: asyncore,  Up: 已弃用的 Python 模块、函数和方法<2>

1.3.9.6 dbm
...........

Unlike other *note dbm: 32. implementations, the *note dbm.dumb: 33.
module creates databases with the ‘'rw'’ mode and allows modifying the
database opened with the ‘'r'’ mode.  This behavior is now deprecated
and will be removed in 3.8.  (Contributed by Serhiy Storchaka in
bpo-21708(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21708


File: python.info,  Node: distutils<3>,  Next: grp,  Prev: dbm<3>,  Up: 已弃用的 Python 模块、函数和方法<2>

1.3.9.7 distutils
.................

The undocumented ‘extra_path’ argument to the ‘Distribution’ constructor
is now considered deprecated and will raise a warning if set.  Support
for this parameter will be removed in a future Python release.  See
bpo-27919(1) for details.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27919


File: python.info,  Node: grp,  Next: importlib<4>,  Prev: distutils<3>,  Up: 已弃用的 Python 模块、函数和方法<2>

1.3.9.8 grp
...........

The support of non-integer arguments in *note getgrgid(): 5e8. has been
deprecated.  (Contributed by Serhiy Storchaka in bpo-26129(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26129


File: python.info,  Node: importlib<4>,  Next: os<4>,  Prev: grp,  Up: 已弃用的 Python 模块、函数和方法<2>

1.3.9.9 importlib
.................

The *note importlib.machinery.SourceFileLoader.load_module(): 5ea. and
*note importlib.machinery.SourcelessFileLoader.load_module(): 5eb.
methods are now deprecated.  They were the only remaining
implementations of *note importlib.abc.Loader.load_module(): 5ec. in
*note importlib: 9b. that had not been deprecated in previous versions
of Python in favour of *note importlib.abc.Loader.exec_module(): 5ed.

The *note importlib.machinery.WindowsRegistryFinder: 5ee. class is now
deprecated.  As of 3.6.0, it is still added to *note sys.meta_path: 5ef.
by default (on Windows), but this may change in future releases.


File: python.info,  Node: os<4>,  Next: re<3>,  Prev: importlib<4>,  Up: 已弃用的 Python 模块、函数和方法<2>

1.3.9.10 os
...........

Undocumented support of general *note bytes-like objects: 5f1. as paths
in *note os: c5. functions, *note compile(): 1b5. and similar functions
is now deprecated.  (Contributed by Serhiy Storchaka in bpo-25791(1) and
bpo-26754(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25791

   (2) https://bugs.python.org/issue26754


File: python.info,  Node: re<3>,  Next: ssl<5>,  Prev: os<4>,  Up: 已弃用的 Python 模块、函数和方法<2>

1.3.9.11 re
...........

Support for inline flags ‘(?letters)’ in the middle of the regular
expression has been deprecated and will be removed in a future Python
version.  Flags at the start of a regular expression are still allowed.
(Contributed by Serhiy Storchaka in bpo-22493(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22493


File: python.info,  Node: ssl<5>,  Next: tkinter<4>,  Prev: re<3>,  Up: 已弃用的 Python 模块、函数和方法<2>

1.3.9.12 ssl
............

OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported.
In the future the *note ssl: f4. module will require at least OpenSSL
1.0.2 or 1.1.0.

SSL-related arguments like ‘certfile’, ‘keyfile’ and ‘check_hostname’ in
*note ftplib: 84, *note http.client: 94, *note imaplib: 98, *note
poplib: d1, and *note smtplib: ee. have been deprecated in favor of
‘context’.  (Contributed by Christian Heimes in bpo-28022(1).)

A couple of protocols and functions of the *note ssl: f4. module are now
deprecated.  Some features will no longer be available in future
versions of OpenSSL. Other features are deprecated in favor of a
different API. (Contributed by Christian Heimes in bpo-28022(2) and
bpo-26470(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28022

   (2) https://bugs.python.org/issue28022

   (3) https://bugs.python.org/issue26470


File: python.info,  Node: tkinter<4>,  Next: venv<3>,  Prev: ssl<5>,  Up: 已弃用的 Python 模块、函数和方法<2>

1.3.9.13 tkinter
................

The *note tkinter.tix: 10f. module is now deprecated.  *note tkinter:
10d. users should use *note tkinter.ttk: 110. instead.


File: python.info,  Node: venv<3>,  Prev: tkinter<4>,  Up: 已弃用的 Python 模块、函数和方法<2>

1.3.9.14 venv
.............

The ‘pyvenv’ script has been deprecated in favour of ‘python3 -m venv’.
This prevents confusion as to what Python interpreter ‘pyvenv’ is
connected to and thus what Python interpreter will be used by the
virtual environment.  (Contributed by Brett Cannon in bpo-25154(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25154


File: python.info,  Node: 已弃用的 C API 函数和类型<2>,  Next: 弃用的构建选项,  Prev: 已弃用的 Python 模块、函数和方法<2>,  Up: 弃用<2>

1.3.9.15 已弃用的 C API 函数和类型
..................................

Undocumented functions ‘PyUnicode_AsEncodedObject()’,
‘PyUnicode_AsDecodedObject()’, ‘PyUnicode_AsEncodedUnicode()’ and
‘PyUnicode_AsDecodedUnicode()’ are deprecated now.  Use the *note
generic codec based API: 5f7. instead.


File: python.info,  Node: 弃用的构建选项,  Prev: 已弃用的 C API 函数和类型<2>,  Up: 弃用<2>

1.3.9.16 弃用的构建选项
.......................

The ‘--with-system-ffi’ configure flag is now on by default on non-macOS
UNIX platforms.  It may be disabled by using ‘--without-system-ffi’, but
using the flag is deprecated and will not be accepted in Python 3.7.
macOS is unaffected by this change.  Note that many OS distributors
already use the ‘--with-system-ffi’ flag when building their system
Python.


File: python.info,  Node: 移除,  Next: 移植到Python 3 6,  Prev: 弃用<2>,  Up: Python 3 6 有什么新变化

1.3.10 移除
-----------

* Menu:

* API 与特性的移除: API 与特性的移除<3>.


File: python.info,  Node: API 与特性的移除<3>,  Up: 移除

1.3.10.1 API 与特性的移除
.........................

   * Unknown escapes consisting of ‘'\'’ and an ASCII letter in regular
     expressions will now cause an error.  In replacement templates for
     *note re.sub(): 483. they are still allowed, but deprecated.  The
     *note re.LOCALE: 3d1. flag can now only be used with binary
     patterns.

   * ‘inspect.getmoduleinfo()’ was removed (was deprecated since CPython
     3.3).  *note inspect.getmodulename(): 5fb. should be used for
     obtaining the module name for a given path.  (Contributed by Yury
     Selivanov in bpo-13248(1).)

   * ‘traceback.Ignore’ class and ‘traceback.usage’,
     ‘traceback.modname’, ‘traceback.fullmodname’,
     ‘traceback.find_lines_from_code’, ‘traceback.find_lines’,
     ‘traceback.find_strings’, ‘traceback.find_executable_lines’ methods
     were removed from the *note traceback: 114. module.  They were
     undocumented methods deprecated since Python 3.2 and equivalent
     functionality is available from private methods.

   * The ‘tk_menuBar()’ and ‘tk_bindForTraversal()’ dummy methods in
     *note tkinter: 10d. widget classes were removed (corresponding Tk
     commands were obsolete since Tk 4.0).

   * The *note open(): 5c5. method of the *note zipfile.ZipFile: 427.
     class no longer supports the ‘'U'’ mode (was deprecated since
     Python 3.4).  Use *note io.TextIOWrapper: 5fc. for reading
     compressed text files in *note universal newlines: 5fd. mode.

   * The undocumented ‘IN’, ‘CDROM’, ‘DLFCN’, ‘TYPES’, ‘CDIO’, and
     ‘STROPTS’ modules have been removed.  They had been available in
     the platform specific ‘Lib/plat-*/’ directories, but were
     chronically out of date, inconsistently available across platforms,
     and unmaintained.  The script that created these modules is still
     available in the source distribution at Tools/scripts/h2py.py(2).

   * The deprecated ‘asynchat.fifo’ class has been removed.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13248

   (2) https://github.com/python/cpython/tree/3.8/Tools/scripts/h2py.py


File: python.info,  Node: 移植到Python 3 6,  Next: Python 3 6 2 中的重要变化,  Prev: 移除,  Up: Python 3 6 有什么新变化

1.3.11 移植到Python 3.6
-----------------------

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

* Menu:

* 'python' 命令行为的变化::
* Python API 的变化: Python API 的变化<4>.
* C API 的变化: C API 的变化<3>.
* CPython 字节码的改变: CPython 字节码的改变<3>.


File: python.info,  Node: 'python' 命令行为的变化,  Next: Python API 的变化<4>,  Up: 移植到Python 3 6

1.3.11.1 ’python’ 命令行为的变化
................................

   * The output of a special Python build with defined ‘COUNT_ALLOCS’,
     ‘SHOW_ALLOC_COUNT’ or ‘SHOW_TRACK_COUNT’ macros is now off by
     default.  It can be re-enabled using the ‘-X showalloccount’
     option.  It now outputs to ‘stderr’ instead of ‘stdout’.
     (Contributed by Serhiy Storchaka in bpo-23034(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23034


File: python.info,  Node: Python API 的变化<4>,  Next: C API 的变化<3>,  Prev: 'python' 命令行为的变化,  Up: 移植到Python 3 6

1.3.11.2 Python API 的变化
..........................

   * *note open(): 4f8. will no longer allow combining the ‘'U'’ mode
     flag with ‘'+'’.  (Contributed by Jeff Balogh and John O’Connor in
     bpo-2091(1).)

   * *note sqlite3: f3. no longer implicitly commits an open transaction
     before DDL statements.

   * On Linux, *note os.urandom(): 4d9. now blocks until the system
     urandom entropy pool is initialized to increase the security.

   * When *note importlib.abc.Loader.exec_module(): 5ed. is defined,
     *note importlib.abc.Loader.create_module(): 55d. must also be
     defined.

   * *note PyErr_SetImportError(): 601. now sets *note TypeError: 193.
     when its `msg' argument is not set.  Previously only ‘NULL’ was
     returned.

   * The format of the ‘co_lnotab’ attribute of code objects changed to
     support a negative line number delta.  By default, Python does not
     emit bytecode with a negative line number delta.  Functions using
     ‘frame.f_lineno’, ‘PyFrame_GetLineNumber()’ or ‘PyCode_Addr2Line()’
     are not affected.  Functions directly decoding ‘co_lnotab’ should
     be updated to use a signed 8-bit integer type for the line number
     delta, but this is only required to support applications using a
     negative line number delta.  See ‘Objects/lnotab_notes.txt’ for the
     ‘co_lnotab’ format and how to decode it, and see the PEP 511(2) for
     the rationale.

   * The functions in the *note compileall: 21. module now return
     booleans instead of ‘1’ or ‘0’ to represent success or failure,
     respectively.  Thanks to booleans being a subclass of integers,
     this should only be an issue if you were doing identity checks for
     ‘1’ or ‘0’.  See bpo-25768(3).

   * Reading the ‘port’ attribute of *note urllib.parse.urlsplit(): 602.
     and *note urlparse(): 603. results now raises *note ValueError:
     1fc. for out-of-range values, rather than returning *note None:
     158.  See bpo-20059(4).

   * The *note imp: 9a. module now raises a *note DeprecationWarning:
     279. instead of *note PendingDeprecationWarning: 27a.

   * The following modules have had missing APIs added to their
     ‘__all__’ attributes to match the documented APIs: *note calendar:
     15, *note cgi: 16, *note csv: 2a, *note ElementTree: 138, *note
     enum: 7b, *note fileinput: 80, *note ftplib: 84, *note logging: ab,
     *note mailbox: af, *note mimetypes: b3, *note optparse: c4, *note
     plistlib: d0, *note smtpd: ed, *note subprocess: fa, *note tarfile:
     102, *note threading: 10a. and *note wave: 128.  This means they
     will export new symbols when ‘import *’ is used.  (Contributed by
     Joel Taddei and Jacek Kołodziej in bpo-23883(5).)

   * When performing a relative import, if ‘__package__’ does not
     compare equal to ‘__spec__.parent’ then *note ImportWarning: 5e1.
     is raised.  (Contributed by Brett Cannon in bpo-25791(6).)

   * When a relative import is performed and no parent package is known,
     then *note ImportError: 33d. will be raised.  Previously, *note
     SystemError: 604. could be raised.  (Contributed by Brett Cannon in
     bpo-18018(7).)

   * Servers based on the *note socketserver: f1. module, including
     those defined in *note http.server: 97, *note xmlrpc.server: 141.
     and *note wsgiref.simple_server: 130, now only catch exceptions
     derived from *note Exception: 1aa.  Therefore if a request handler
     raises an exception like *note SystemExit: 605. or *note
     KeyboardInterrupt: 198, *note handle_error(): 606. is no longer
     called, and the exception will stop a single-threaded server.
     (Contributed by Martin Panter in bpo-23430(8).)

   * *note spwd.getspnam(): 607. now raises a *note PermissionError:
     608. instead of *note KeyError: 2c8. if the user doesn’t have
     privileges.

   * The *note socket.socket.close(): 609. method now raises an
     exception if an error (e.g.  ‘EBADF’) was reported by the
     underlying system call.  (Contributed by Martin Panter in
     bpo-26685(9).)

   * The `decode_data' argument for the *note smtpd.SMTPChannel: 60a.
     and *note smtpd.SMTPServer: 60b. constructors is now ‘False’ by
     default.  This means that the argument passed to *note
     process_message(): 60c. is now a bytes object by default, and
     ‘process_message()’ will be passed keyword arguments.  Code that
     has already been updated in accordance with the deprecation warning
     generated by 3.5 will not be affected.

   * All optional arguments of the *note dump(): 60d, *note dumps():
     60e, *note load(): 568. and *note loads(): 569. functions and *note
     JSONEncoder: 60f. and *note JSONDecoder: 610. class constructors in
     the *note json: a5. module are now *note keyword-only: 2ad.
     (Contributed by Serhiy Storchaka in bpo-18726(10).)

   * *note type: 611. 的子类如果未重载 ‘type.__new__’，将不再能使用一个
     参数的形式来获取对象的类型。

   * As part of PEP 487(11), the handling of keyword arguments passed to
     *note type: 611. (other than the metaclass hint, ‘metaclass’) is
     now consistently delegated to *note object.__init_subclass__():
     4ea.  This means that ‘type.__new__()’ and ‘type.__init__()’ both
     now accept arbitrary keyword arguments, but *note
     object.__init_subclass__(): 4ea. (which is called from
     ‘type.__new__()’) will reject them by default.  Custom metaclasses
     accepting additional keyword arguments will need to adjust their
     calls to ‘type.__new__()’ (whether direct or via *note super: 4eb.)
     accordingly.

   * In ‘distutils.command.sdist.sdist’, the ‘default_format’ attribute
     has been removed and is no longer honored.  Instead, the gzipped
     tarfile format is the default on all platforms and no
     platform-specific selection is made.  In environments where
     distributions are built on Windows and zip distributions are
     required, configure the project with a ‘setup.cfg’ file containing
     the following:

          [sdist]
          formats=zip

     This behavior has also been backported to earlier Python versions
     by Setuptools 26.0.0.

   * In the *note urllib.request: 121. module and the *note
     http.client.HTTPConnection.request(): 558. method, if no
     Content-Length header field has been specified and the request body
     is a file object, it is now sent with HTTP 1.1 chunked encoding.
     If a file object has to be sent to a HTTP 1.0 server, the
     Content-Length value now has to be specified by the caller.
     (Contributed by Demian Brecht and Rolf Krahl with tweaks from
     Martin Panter in bpo-12319(12).)

   * The *note DictReader: 1be. now returns rows of type *note
     OrderedDict: 1ba.  (Contributed by Steve Holden in bpo-27842(13).)

   * The *note crypt.METHOD_CRYPT: 612. will no longer be added to
     ‘crypt.methods’ if unsupported by the platform.  (Contributed by
     Victor Stinner in bpo-25287(14).)

   * The `verbose' and `rename' arguments for *note namedtuple(): 1b7.
     are now keyword-only.  (Contributed by Raymond Hettinger in
     bpo-25628(15).)

   * On Linux, *note ctypes.util.find_library(): 613. now looks in
     ‘LD_LIBRARY_PATH’ for shared libraries.  (Contributed by Vinay
     Sajip in bpo-9998(16).)

   * The *note imaplib.IMAP4: 614. class now handles flags containing
     the ‘']'’ character in messages sent from the server to improve
     real-world compatibility.  (Contributed by Lita Cho in
     bpo-21815(17).)

   * The ‘mmap.write()’ function now returns the number of bytes written
     like other write methods.  (Contributed by Jakub Stasiak in
     bpo-26335(18).)

   * The *note pkgutil.iter_modules(): 615. and *note
     pkgutil.walk_packages(): 493. functions now return *note
     ModuleInfo: 616. named tuples.  (Contributed by Ramchandra Apte in
     bpo-17211(19).)

   * *note re.sub(): 483. now raises an error for invalid numerical
     group references in replacement templates even if the pattern is
     not found in the string.  The error message for invalid group
     references now includes the group index and the position of the
     reference.  (Contributed by SilentGhost, Serhiy Storchaka in
     bpo-25953(20).)

   * *note zipfile.ZipFile: 427. will now raise *note
     NotImplementedError: 617. for unrecognized compression values.
     Previously a plain *note RuntimeError: 2bb. was raised.
     Additionally, calling *note ZipFile: 427. methods on a closed
     ZipFile or calling the *note write(): 618. method on a ZipFile
     created with mode ‘'r'’ will raise a *note ValueError: 1fc.
     Previously, a *note RuntimeError: 2bb. was raised in those
     scenarios.

   * when custom metaclasses are combined with zero-argument *note
     super(): 4eb. or direct references from methods to the implicit
     ‘__class__’ closure variable, the implicit ‘__classcell__’
     namespace entry must now be passed up to ‘type.__new__’ for
     initialisation.  Failing to do so will result in a *note
     DeprecationWarning: 279. in Python 3.6 and a *note RuntimeError:
     2bb. in Python 3.8.

   * With the introduction of *note ModuleNotFoundError: 3a2, import
     system consumers may start expecting import system replacements to
     raise that more specific exception when appropriate, rather than
     the less-specific *note ImportError: 33d.  To provide future
     compatibility with such consumers, implementors of alternative
     import systems that completely replace *note __import__(): 619.
     will need to update their implementations to raise the new subclass
     when a module can’t be found at all.  Implementors of compliant
     plugins to the default import system shouldn’t need to make any
     changes, as the default import system will raise the new subclass
     when appropriate.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2091

   (2) https://www.python.org/dev/peps/pep-0511

   (3) https://bugs.python.org/issue25768

   (4) https://bugs.python.org/issue20059

   (5) https://bugs.python.org/issue23883

   (6) https://bugs.python.org/issue25791

   (7) https://bugs.python.org/issue18018

   (8) https://bugs.python.org/issue23430

   (9) https://bugs.python.org/issue26685

   (10) https://bugs.python.org/issue18726

   (11) https://www.python.org/dev/peps/pep-0487

   (12) https://bugs.python.org/issue12319

   (13) https://bugs.python.org/issue27842

   (14) https://bugs.python.org/issue25287

   (15) https://bugs.python.org/issue25628

   (16) https://bugs.python.org/issue9998

   (17) https://bugs.python.org/issue21815

   (18) https://bugs.python.org/issue26335

   (19) https://bugs.python.org/issue17211

   (20) https://bugs.python.org/issue25953


File: python.info,  Node: C API 的变化<3>,  Next: CPython 字节码的改变<3>,  Prev: Python API 的变化<4>,  Up: 移植到Python 3 6

1.3.11.3 C API 的变化
.....................

   * The *note PyMem_Malloc(): 50d. allocator family now uses the *note
     pymalloc allocator: 5ca. rather than the system ‘malloc()’.
     Applications calling *note PyMem_Malloc(): 50d. without holding the
     GIL can now crash.  Set the *note PYTHONMALLOC: 50b. environment
     variable to ‘debug’ to validate the usage of memory allocators in
     your application.  See bpo-26249(1).

   * *note Py_Exit(): 61b. (and the main interpreter) now override the
     exit status with 120 if flushing buffered data failed.  See
     bpo-5319(2).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26249

   (2) https://bugs.python.org/issue5319


File: python.info,  Node: CPython 字节码的改变<3>,  Prev: C API 的变化<3>,  Up: 移植到Python 3 6

1.3.11.4 CPython 字节码的改变
.............................

There have been several major changes to the *note bytecode: 61d. in
Python 3.6.

   * The Python interpreter now uses a 16-bit wordcode instead of
     bytecode.  (Contributed by Demur Rumed with input and reviews from
     Serhiy Storchaka and Victor Stinner in bpo-26647(1) and
     bpo-28050(2).)

   * The new *note FORMAT_VALUE: 61e. and *note BUILD_STRING: 61f.
     opcodes as part of the *note formatted string literal: 4c9.
     implementation.  (Contributed by Eric Smith in bpo-25483(3) and
     Serhiy Storchaka in bpo-27078(4).)

   * The new *note BUILD_CONST_KEY_MAP: 620. opcode to optimize the
     creation of dictionaries with constant keys.  (Contributed by
     Serhiy Storchaka in bpo-27140(5).)

   * The function call opcodes have been heavily reworked for better
     performance and simpler implementation.  The *note MAKE_FUNCTION:
     621, *note CALL_FUNCTION: 622, *note CALL_FUNCTION_KW: 623. and
     *note BUILD_MAP_UNPACK_WITH_CALL: 624. opcodes have been modified,
     the new *note CALL_FUNCTION_EX: 625. and *note
     BUILD_TUPLE_UNPACK_WITH_CALL: 626. have been added, and
     ‘CALL_FUNCTION_VAR’, ‘CALL_FUNCTION_VAR_KW’ and ‘MAKE_CLOSURE’
     opcodes have been removed.  (Contributed by Demur Rumed in
     bpo-27095(6), and Serhiy Storchaka in bpo-27213(7), bpo-28257(8).)

   * The new *note SETUP_ANNOTATIONS: 627. and ‘STORE_ANNOTATION’
     opcodes have been added to support the new *note variable
     annotation: 628. syntax.  (Contributed by Ivan Levkivskyi in
     bpo-27985(9).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26647

   (2) https://bugs.python.org/issue28050

   (3) https://bugs.python.org/issue25483

   (4) https://bugs.python.org/issue27078

   (5) https://bugs.python.org/issue27140

   (6) https://bugs.python.org/issue27095

   (7) https://bugs.python.org/issue27213

   (8) https://bugs.python.org/issue28257

   (9) https://bugs.python.org/issue27985


File: python.info,  Node: Python 3 6 2 中的重要变化,  Next: Python 3 6 4 中的重要变化,  Prev: 移植到Python 3 6,  Up: Python 3 6 有什么新变化

1.3.12 Python 3.6.2 中的重要变化
--------------------------------

* Menu:

* New make regen-all build target::
* Removal of make touch build target::


File: python.info,  Node: New make regen-all build target,  Next: Removal of make touch build target,  Up: Python 3 6 2 中的重要变化

1.3.12.1 New ‘make regen-all’ build target
..........................................

To simplify cross-compilation, and to ensure that CPython can reliably
be compiled without requiring an existing version of Python to already
be available, the autotools-based build system no longer attempts to
implicitly recompile generated files based on file modification times.

Instead, a new ‘make regen-all’ command has been added to force
regeneration of these files when desired (e.g.  after an initial version
of Python has already been built based on the pregenerated versions).

More selective regeneration targets are also defined - see
Makefile.pre.in(1) for details.

（由 Victor Stinner 在 bpo-23404(2) 中贡献。）

3.6.2 新版功能.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Makefile.pre.in

   (2) https://bugs.python.org/issue23404


File: python.info,  Node: Removal of make touch build target,  Prev: New make regen-all build target,  Up: Python 3 6 2 中的重要变化

1.3.12.2 Removal of ‘make touch’ build target
.............................................

The ‘make touch’ build target previously used to request implicit
regeneration of generated files by updating their modification times has
been removed.

It has been replaced by the new ‘make regen-all’ target.

（由 Victor Stinner 在 bpo-23404(1) 中贡献。）

在 3.6.2 版更改.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23404


File: python.info,  Node: Python 3 6 4 中的重要变化,  Next: Python 3 6 5 中的重要变化,  Prev: Python 3 6 2 中的重要变化,  Up: Python 3 6 有什么新变化

1.3.13 Python 3.6.4 中的重要变化
--------------------------------

The ‘PyExc_RecursionErrorInst’ singleton that was part of the public API
has been removed as its members being never cleared may cause a segfault
during finalization of the interpreter.  (Contributed by Xavier de Gaye
in bpo-22898(1) and bpo-30697(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22898

   (2) https://bugs.python.org/issue30697


File: python.info,  Node: Python 3 6 5 中的重要变化,  Next: Python 3 6 7 中的重要变化,  Prev: Python 3 6 4 中的重要变化,  Up: Python 3 6 有什么新变化

1.3.14 Python 3.6.5 中的重要变化
--------------------------------

The *note locale.localeconv(): 492. function now sets temporarily the
‘LC_CTYPE’ locale to the ‘LC_NUMERIC’ locale in some cases.
(Contributed by Victor Stinner in bpo-31900(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31900


File: python.info,  Node: Python 3 6 7 中的重要变化,  Next: Python 3 6 10 中的重要变化,  Prev: Python 3 6 5 中的重要变化,  Up: Python 3 6 有什么新变化

1.3.15 Python 3.6.7 中的重要变化
--------------------------------

In 3.6.7 the *note tokenize: 112. module now implicitly emits a
‘NEWLINE’ token when provided with input that does not have a trailing
new line.  This behavior now matches what the C tokenizer does
internally.  (Contributed by Ammar Askar in bpo-33899(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33899


File: python.info,  Node: Python 3 6 10 中的重要变化,  Next: Notable changes in Python 3 6 13,  Prev: Python 3 6 7 中的重要变化,  Up: Python 3 6 有什么新变化

1.3.16 Python 3.6.10 中的重要变化
---------------------------------

出于重要的安全性考量，*note asyncio.loop.create_datagram_endpoint():
2e8. 的 `reuse_address' 形参不再被支持。 这是由 UDP 中的套接字选项
‘SO_REUSEADDR’ 的行为导致的。 更多细节请参阅
‘loop.create_datagram_endpoint()’ 的文档。 （由 Kyle Stanley, Antoine
Pitrou 和 Yury Selivanov 在 bpo-37228(1) 中贡献。。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37228


File: python.info,  Node: Notable changes in Python 3 6 13,  Prev: Python 3 6 10 中的重要变化,  Up: Python 3 6 有什么新变化

1.3.17 Notable changes in Python 3.6.13
---------------------------------------

早先的 Python 版本允许使用 ‘;’ 和 ‘&’ 作为 *note
urllib.parse.parse_qs(): 2ec. 和 *note urllib.parse.parse_qsl(): 2ed. 中
query 形参的分隔键。 出于安全考虑，也为了遵循更新的 W3C 推荐设置，这已被
改为只允许单个分隔键，默认为 ‘&’。 这一改变还会影响 *note cgi.parse():
2ee. 和 *note cgi.parse_multipart(): 2ef. 因为它们在内部使用了受影响的函
数。 要了解更多细节，请查看它们各自的文档。 （由 Adam Goldschmidt,
Senthil Kumaran 和 Ken Jin 在 bpo-42967(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42967


File: python.info,  Node: Python 3 5 有什么新变化,  Next: Python 3 4 有什么新变化,  Prev: Python 3 6 有什么新变化,  Up: Python的新变化

1.4 Python 3.5 有什么新变化
===========================


编者: Elvis Pranskevichus <<elvis@magic.io>>, Yury Selivanov
<<yury@magic.io>>

This article explains the new features in Python 3.5, compared to 3.4.
Python 3.5 was released on September 13, 2015.   See the changelog(1)
for a full list of changes.

参见
....

PEP 478(2) - Python 3.5 发布计划

* Menu:

* 摘要 - 发布重点: 摘要 - 发布重点<4>.
* 新的特性: 新的特性<4>.
* 其他语言特性修改: 其他语言特性修改<4>.
* 新增模块: 新增模块<4>.
* 改进的模块: 改进的模块<4>.
* 其他模块级更改::
* 性能优化: 性能优化<4>.
* 构建和 C API 的改变: 构建和 C API 的改变<3>.
* 弃用: 弃用<3>.
* 移除: 移除<2>.
* 移植到Python 3.5: 移植到Python 3 5.
* Python 3.5.4 的显著变化: Python 3 5 4 的显著变化.

   ---------- Footnotes ----------

   (1) https://docs.python.org/3.5/whatsnew/changelog.html

   (2) https://www.python.org/dev/peps/pep-0478


File: python.info,  Node: 摘要 - 发布重点<4>,  Next: 新的特性<4>,  Up: Python 3 5 有什么新变化

1.4.1 摘要 - 发布重点
---------------------

新的语法特性：

   * *note PEP 492: 634, 使用 async 和 await 语法实现协程。

   * *note PEP 465: 635, 新的矩阵乘法运算符: ‘a @ b’.

   * *note PEP 448: 636, additional unpacking generalizations.

新的库模块：

   * *note typing: 11a.: *note PEP 484 – 类型提示: 637.

   * *note zipapp: 142.: *note PEP 441 改进Python ZIP应用程序支持: 638.

新的内置特性：

   * ‘bytes % args’, ‘bytearray % args’: *note PEP 461: 639. – Adding
     ‘%’ formatting to bytes and bytearray.

   * New *note bytes.hex(): 63a, *note bytearray.hex(): 63b. and *note
     memoryview.hex(): 63c. methods.  (Contributed by Arnon Yaari in
     bpo-9951(1).)

   * *note memoryview: 25d. now supports tuple indexing (including
     multi-dimensional).  (Contributed by Antoine Pitrou in
     bpo-23632(2).)

   * Generators have a new ‘gi_yieldfrom’ attribute, which returns the
     object being iterated by ‘yield from’ expressions.  (Contributed by
     Benno Leslie and Yury Selivanov in bpo-24450(3).)

   * A new *note RecursionError: 63d. exception is now raised when
     maximum recursion depth is reached.  (Contributed by Georg Brandl
     in bpo-19235(4).)

CPython 实现的改进：

   * When the ‘LC_TYPE’ locale is the POSIX locale (‘C’ locale), *note
     sys.stdin: 316. and *note sys.stdout: 317. now use the
     ‘surrogateescape’ error handler, instead of the ‘strict’ error
     handler.  (Contributed by Victor Stinner in bpo-19977(5).)

   * ‘.pyo’ files are no longer used and have been replaced by a more
     flexible scheme that includes the optimization level explicitly in
     ‘.pyc’ name.  (See *note PEP 488 overview: 63e.)

   * Builtin and extension modules are now initialized in a multi-phase
     process, which is similar to how Python modules are loaded.  (See
     *note PEP 489 overview: 63f.)

标准库中的重大改进：

   * *note collections.OrderedDict: 1ba. is now *note implemented in C:
     640, which makes it 4 to 100 times faster.

   * The *note ssl: f4. module gained *note support for Memory BIO: 641,
     which decouples SSL protocol handling from network IO.

   * The new *note os.scandir(): 260. function provides a *note better
     and significantly faster way: 642. of directory traversal.

   * *note functools.lru_cache(): 1c8. has been mostly *note
     reimplemented in C: 643, yielding much better performance.

   * The new *note subprocess.run(): 3f5. function provides a *note
     streamlined way to run subprocesses: 644.

   * The *note traceback: 114. module has been significantly *note
     enhanced: 645. for improved performance and developer convenience.

安全改进：

   * SSLv3 is now disabled throughout the standard library.  It can
     still be enabled by instantiating a *note ssl.SSLContext: 3ec.
     manually.  (See bpo-22638(6) for more details; this change was
     backported to CPython 3.4 and 2.7.)

   * HTTP cookie parsing is now stricter, in order to protect against
     potential injection attacks.  (Contributed by Antoine Pitrou in
     bpo-22796(7).)

Windows改进：

   * A new installer for Windows has replaced the old MSI. See *note
     在Windows上使用 Python: 2da. for more information.

   * Windows builds now use Microsoft Visual C++ 14.0, and extension
     modules should use the same.

Please read on for a comprehensive list of user-facing changes,
including many other smaller improvements, CPython optimizations,
deprecations, and potential porting issues.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9951

   (2) https://bugs.python.org/issue23632

   (3) https://bugs.python.org/issue24450

   (4) https://bugs.python.org/issue19235

   (5) https://bugs.python.org/issue19977

   (6) https://bugs.python.org/issue22638

   (7) https://bugs.python.org/issue22796


File: python.info,  Node: 新的特性<4>,  Next: 其他语言特性修改<4>,  Prev: 摘要 - 发布重点<4>,  Up: Python 3 5 有什么新变化

1.4.2 新的特性
--------------

* Menu:

* PEP 492 - 使用 async 和 await 语法实现协程::
* PEP 465 - 用于矩阵乘法的专用中缀运算符::
* PEP 448 - Additional Unpacking Generalizations::
* PEP 461 - percent formatting support for bytes and bytearray::
* PEP 484 - 类型提示::
* PEP 471 - os.scandir() function: PEP 471 - os scandir function -- a better and faster directory iterator. a better and faster directory iterator
* PEP 475; Retry system calls failing with EINTR: PEP 475 Retry system calls failing with EINTR.
* PEP 479; Change StopIteration handling inside generators: PEP 479 Change StopIteration handling inside generators.
* PEP 485; A function for testing approximate equality: PEP 485 A function for testing approximate equality.
* PEP 486; Make the Python Launcher aware of virtual environments: PEP 486 Make the Python Launcher aware of virtual environments.
* PEP 488; Elimination of PYO files: PEP 488 Elimination of PYO files.
* PEP 489; Multi-phase extension module initialization: PEP 489 Multi-phase extension module initialization.


File: python.info,  Node: PEP 492 - 使用 async 和 await 语法实现协程,  Next: PEP 465 - 用于矩阵乘法的专用中缀运算符,  Up: 新的特性<4>

1.4.2.1 PEP 492 - 使用 async 和 await 语法实现协程
..................................................

PEP 492(1) greatly improves support for asynchronous programming in
Python by adding *note awaitable objects: 521, *note coroutine
functions: 648, *note asynchronous iteration: 649, and *note
asynchronous context managers: 64a.

Coroutine functions are declared using the new *note async def: 285.
syntax:

     >>> async def coro():
     ...     return 'spam'

Inside a coroutine function, the new *note await: 1a4. expression can be
used to suspend coroutine execution until the result is available.  Any
object can be `awaited', as long as it implements the *note awaitable:
521. protocol by defining the *note __await__(): 64b. method.

PEP 492 also adds *note async for: 2e4. statement for convenient
iteration over asynchronous iterables.

An example of a rudimentary HTTP client written using the new syntax:

     import asyncio

     async def http_get(domain):
         reader, writer = await asyncio.open_connection(domain, 80)

         writer.write(b'\r\n'.join([
             b'GET / HTTP/1.1',
             b'Host: %b' % domain.encode('latin-1'),
             b'Connection: close',
             b'', b''
         ]))

         async for line in reader:
             print('>>>', line)

         writer.close()

     loop = asyncio.get_event_loop()
     try:
         loop.run_until_complete(http_get('example.com'))
     finally:
         loop.close()

Similarly to asynchronous iteration, there is a new syntax for
asynchronous context managers.  The following script:

     import asyncio

     async def coro(name, lock):
         print('coro {}: waiting for lock'.format(name))
         async with lock:
             print('coro {}: holding the lock'.format(name))
             await asyncio.sleep(1)
             print('coro {}: releasing the lock'.format(name))

     loop = asyncio.get_event_loop()
     lock = asyncio.Lock()
     coros = asyncio.gather(coro(1, lock), coro(2, lock))
     try:
         loop.run_until_complete(coros)
     finally:
         loop.close()

将输出：

     coro 2: waiting for lock
     coro 2: holding the lock
     coro 1: waiting for lock
     coro 2: releasing the lock
     coro 1: holding the lock
     coro 1: releasing the lock

Note that both *note async for: 2e4. and *note async with: 64c. can only
be used inside a coroutine function declared with *note async def: 285.

Coroutine functions are intended to be run inside a compatible event
loop, such as the *note asyncio loop: 64d.

     注解: 
     在 3.5.2 版更改: Starting with CPython 3.5.2, ‘__aiter__’ can
     directly return *note asynchronous iterators: 64e.  Returning an
     *note awaitable: 521. object will result in a *note
     PendingDeprecationWarning: 27a.

     See more details in the *note 异步迭代器: 64f. documentation
     section.

参见
....

PEP 492(2) – 使用 async 和 await 语法实现协程

     PEP 由 Yury Selivanov 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0492

   (2) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: PEP 465 - 用于矩阵乘法的专用中缀运算符,  Next: PEP 448 - Additional Unpacking Generalizations,  Prev: PEP 492 - 使用 async 和 await 语法实现协程,  Up: 新的特性<4>

1.4.2.2 PEP 465 - 用于矩阵乘法的专用中缀运算符
..............................................

PEP 465(1) adds the ‘@’ infix operator for matrix multiplication.
Currently, no builtin Python types implement the new operator, however,
it can be implemented by defining *note __matmul__(): 651, *note
__rmatmul__(): 652, and *note __imatmul__(): 653. for regular,
reflected, and in-place matrix multiplication.  The semantics of these
methods is similar to that of methods defining other infix arithmetic
operators.

矩阵乘法在数学，科学，工程学的许多领域中是一种常见的操作，使用 ‘@’ 运算
符可以编写更简洁的代码：

     S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)

代替：

     S = dot((dot(H, beta) - r).T,
             dot(inv(dot(dot(H, V), H.T)), dot(H, beta) - r))

NumPy 1.10 支持新的运算符：

     >>> import numpy

     >>> x = numpy.ones(3)
     >>> x
     array([ 1., 1., 1.])

     >>> m = numpy.eye(3)
     >>> m
     array([[ 1., 0., 0.],
            [ 0., 1., 0.],
            [ 0., 0., 1.]])

     >>> x @ m
     array([ 1., 1., 1.])

参见
....

PEP 465(2) – 用于矩阵乘法的专用中缀运算符

     PEP 由 Nathaniel J. Smith 撰写，由 Benjamin Peterson 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0465

   (2) https://www.python.org/dev/peps/pep-0465


File: python.info,  Node: PEP 448 - Additional Unpacking Generalizations,  Next: PEP 461 - percent formatting support for bytes and bytearray,  Prev: PEP 465 - 用于矩阵乘法的专用中缀运算符,  Up: 新的特性<4>

1.4.2.3 PEP 448 - Additional Unpacking Generalizations
......................................................

PEP 448(1) extends the allowed uses of the ‘*’ iterable unpacking
operator and ‘**’ dictionary unpacking operator.  It is now possible to
use an arbitrary number of unpackings in *note function calls: 655.:

     >>> print(*[1], *[2], 3, *[4, 5])
     1 2 3 4 5

     >>> def fn(a, b, c, d):
     ...     print(a, b, c, d)
     ...

     >>> fn(**{'a': 1, 'c': 3}, **{'b': 2, 'd': 4})
     1 2 3 4

Similarly, tuple, list, set, and dictionary displays allow multiple
unpackings (see *note 表达式列表: 656. and *note 字典显示: 657.):

     >>> *range(4), 4
     (0, 1, 2, 3, 4)

     >>> [*range(4), 4]
     [0, 1, 2, 3, 4]

     >>> {*range(4), 4, *(5, 6, 7)}
     {0, 1, 2, 3, 4, 5, 6, 7}

     >>> {'x': 1, **{'y': 2}}
     {'x': 1, 'y': 2}

参见
....

PEP 448(2) – Additional Unpacking Generalizations

     PEP 由 Joshua Landau 撰写 ，由 Neil Girdhar，Thomas Wouters 和
     Joshua Landau 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0448

   (2) https://www.python.org/dev/peps/pep-0448


File: python.info,  Node: PEP 461 - percent formatting support for bytes and bytearray,  Next: PEP 484 - 类型提示,  Prev: PEP 448 - Additional Unpacking Generalizations,  Up: 新的特性<4>

1.4.2.4 PEP 461 - percent formatting support for bytes and bytearray
....................................................................

PEP 461(1) adds support for the ‘%’ *note interpolation operator: 659.
to *note bytes: 33a. and *note bytearray: 33b.

While interpolation is usually thought of as a string operation, there
are cases where interpolation on ‘bytes’ or ‘bytearrays’ makes sense,
and the work needed to make up for this missing functionality detracts
from the overall readability of the code.  This issue is particularly
important when dealing with wire format protocols, which are often a
mixture of binary and ASCII compatible text.

示例:

     >>> b'Hello %b!' % b'World'
     b'Hello World!'

     >>> b'x=%i y=%f' % (1, 2.5)
     b'x=1 y=2.500000'

Unicode is not allowed for ‘%b’, but it is accepted by ‘%a’ (equivalent
of ‘repr(obj).encode('ascii', 'backslashreplace')’):

     >>> b'Hello %b!' % 'World'
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: %b requires bytes, or an object that implements __bytes__, not 'str'

     >>> b'price: %a' % '10€'
     b"price: '10\\u20ac'"

Note that ‘%s’ and ‘%r’ conversion types, although supported, should
only be used in codebases that need compatibility with Python 2.

参见
....

PEP 461(2) – Adding % formatting to bytes and bytearray

     PEP 由 Ethan Furman 撰写 ，由 Neil Schemenauer 和 Ethan Furman 实现
     。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0461

   (2) https://www.python.org/dev/peps/pep-0461


File: python.info,  Node: PEP 484 - 类型提示,  Next: PEP 471 - os scandir function -- a better and faster directory iterator,  Prev: PEP 461 - percent formatting support for bytes and bytearray,  Up: 新的特性<4>

1.4.2.5 PEP 484 - 类型提示
..........................

Function annotation syntax has been a Python feature since version 3.0 (
PEP 3107(1)), however the semantics of annotations has been left
undefined.

Experience has shown that the majority of function annotation uses were
to provide type hints to function parameters and return values.  It
became evident that it would be beneficial for Python users, if the
standard library included the base definitions and tools for type
annotations.

PEP 484(2) introduces a *note provisional module: 351. to provide these
standard definitions and tools, along with some conventions for
situations where annotations are not available.

For example, here is a simple function whose argument and return type
are declared in the annotations:

     def greeting(name: str) -> str:
         return 'Hello ' + name

While these annotations are available at runtime through the usual
‘__annotations__’ attribute, `no automatic type checking happens at
runtime'.  Instead, it is assumed that a separate off-line type checker
(e.g.  mypy(3)) will be used for on-demand source code analysis.

The type system supports unions, generic types, and a special type named
*note Any: 65b. which is consistent with (i.e.  assignable to and from)
all types.

参见
....

   * *note typing: 11a. 模块文档

   * 
     PEP 484(4) – 类型提示

          PEP 由 Guido van Rossum，Jukka Lehtosalo 和 Łukasz Langa 撰写
          ，由 Guido van Rossum 实现。

   * 
     PEP 483(5) – 类型提示理论

          PEP 由 Yury Selivanov 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3107

   (2) https://www.python.org/dev/peps/pep-0484

   (3) http://mypy-lang.org

   (4) https://www.python.org/dev/peps/pep-0484

   (5) https://www.python.org/dev/peps/pep-0483


File: python.info,  Node: PEP 471 - os scandir function -- a better and faster directory iterator,  Next: PEP 475 Retry system calls failing with EINTR,  Prev: PEP 484 - 类型提示,  Up: 新的特性<4>

1.4.2.6 PEP 471 - os.scandir() function – a better and faster directory iterator
................................................................................

PEP 471(1) adds a new directory iteration function, *note os.scandir():
260, to the standard library.  Additionally, *note os.walk(): 65d. is
now implemented using ‘scandir’, which makes it 3 to 5 times faster on
POSIX systems and 7 to 20 times faster on Windows systems.  This is
largely achieved by greatly reducing the number of calls to *note
os.stat(): 1f2. required to walk a directory tree.

Additionally, ‘scandir’ returns an iterator, as opposed to returning a
list of file names, which improves memory efficiency when iterating over
very large directories.

The following example shows a simple use of *note os.scandir(): 260. to
display all the files (excluding directories) in the given `path' that
don’t start with ‘'.'’.  The *note entry.is_file(): 65e. call will
generally not make an additional system call:

     for entry in os.scandir(path):
         if not entry.name.startswith('.') and entry.is_file():
             print(entry.name)

参见
....

PEP 471(2) – os.scandir() function – a better and faster directory iterator

     PEP 由 Ben Hoyt 在 Victor Stinner 的帮助下撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0471

   (2) https://www.python.org/dev/peps/pep-0471


File: python.info,  Node: PEP 475 Retry system calls failing with EINTR,  Next: PEP 479 Change StopIteration handling inside generators,  Prev: PEP 471 - os scandir function -- a better and faster directory iterator,  Up: 新的特性<4>

1.4.2.7 PEP 475: Retry system calls failing with EINTR
......................................................

An *note errno.EINTR: 661. error code is returned whenever a system
call, that is waiting for I/O, is interrupted by a signal.  Previously,
Python would raise *note InterruptedError: 662. in such cases.  This
meant that, when writing a Python application, the developer had two
choices:

  1. Ignore the ‘InterruptedError’.

  2. Handle the ‘InterruptedError’ and attempt to restart the
     interrupted system call at every call site.

The first option makes an application fail intermittently.  The second
option adds a large amount of boilerplate that makes the code nearly
unreadable.  Compare:

     print("Hello World")

和:

     while True:
         try:
             print("Hello World")
             break
         except InterruptedError:
             continue

PEP 475(1) implements automatic retry of system calls on ‘EINTR’.  This
removes the burden of dealing with ‘EINTR’ or *note InterruptedError:
662. in user code in most situations and makes Python programs,
including the standard library, more robust.  Note that the system call
is only retried if the signal handler does not raise an exception.

Below is a list of functions which are now retried when interrupted by a
signal:

   * *note open(): 4f8. 和 *note io.open(): 663.;

   * *note faulthandler: 7d. 模块的功能

   * *note os: c5. 函数: *note fchdir(): 664, *note fchmod(): 665, *note
     fchown(): 666, *note fdatasync(): 667, *note fstat(): 668, *note
     fstatvfs(): 669, *note fsync(): 66a, *note ftruncate(): 66b, *note
     mkfifo(): 66c, *note mknod(): 66d, *note open(): 66e, *note
     posix_fadvise(): 66f, *note posix_fallocate(): 670, *note pread():
     3c1, *note pwrite(): 3c4, *note read(): 671, *note readv(): 3c0,
     *note sendfile(): 362, *note wait3(): 672, *note wait4(): 673,
     *note wait(): 674, *note waitid(): 675, *note waitpid(): 676, *note
     write(): 677, *note writev(): 3c3.;

   * 特例: *note os.close(): 3da. 和 *note os.dup2(): 3c6. 现在会忽略
     *note EINTR: 661. 错误; 不重试系统调用（请参阅PEP了解基本原理）

   * *note select: e6. 函数: *note devpoll.poll(): 678, *note
     epoll.poll(): 679, *note kqueue.control(): 67a, *note poll.poll():
     67b, *note select(): 67c.;

   * *note socket: 67d. 类的方法: *note accept(): 67e, *note connect():
     67f. （除了非阻塞套接字）, *note recv(): 680, *note recvfrom():
     681, *note recvmsg(): 682, *note send(): 683, *note sendall(): 684,
     *note sendmsg(): 685, *note sendto(): 686.;

   * *note signal.sigtimedwait(): 687. 和 *note signal.sigwaitinfo():
     688.;

   * *note time.sleep(): 689.

参见
....

PEP 475(2) – Retry system calls failing with EINTR

     PEP and implementation written by Charles-François Natali and
     Victor Stinner, with the help of Antoine Pitrou (the French
     connection).

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475

   (2) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: PEP 479 Change StopIteration handling inside generators,  Next: PEP 485 A function for testing approximate equality,  Prev: PEP 475 Retry system calls failing with EINTR,  Up: 新的特性<4>

1.4.2.8 PEP 479: Change StopIteration handling inside generators
................................................................

The interaction of generators and *note StopIteration: 48e. in Python
3.4 and earlier was sometimes surprising, and could conceal obscure
bugs.  Previously, ‘StopIteration’ raised accidentally inside a
generator function was interpreted as the end of the iteration by the
loop construct driving the generator.

PEP 479(1) changes the behavior of generators: when a ‘StopIteration’
exception is raised inside a generator, it is replaced with a *note
RuntimeError: 2bb. before it exits the generator frame.  The main goal
of this change is to ease debugging in the situation where an unguarded
*note next(): 68b. call raises ‘StopIteration’ and causes the iteration
controlled by the generator to terminate silently.  This is particularly
pernicious in combination with the ‘yield from’ construct.

This is a backwards incompatible change, so to enable the new behavior,
a *note __future__: 68c. import is necessary:

     >>> from __future__ import generator_stop

     >>> def gen():
     ...     next(iter([]))
     ...     yield
     ...
     >>> next(gen())
     Traceback (most recent call last):
       File "<stdin>", line 2, in gen
     StopIteration

     The above exception was the direct cause of the following exception:

     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     RuntimeError: generator raised StopIteration

Without a ‘__future__’ import, a *note PendingDeprecationWarning: 27a.
will be raised whenever a *note StopIteration: 48e. exception is raised
inside a generator.

参见
....

PEP 479(2) – Change StopIteration handling inside generators

     PEP 由 Chris Angelico 和 Guido van Rossum 撰写，由 Chris Angelico，
     Yury Selivanov 和 Nick Coghlan 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0479

   (2) https://www.python.org/dev/peps/pep-0479


File: python.info,  Node: PEP 485 A function for testing approximate equality,  Next: PEP 486 Make the Python Launcher aware of virtual environments,  Prev: PEP 479 Change StopIteration handling inside generators,  Up: 新的特性<4>

1.4.2.9 PEP 485: A function for testing approximate equality
............................................................

PEP 485(1) adds the *note math.isclose(): 68f. and *note
cmath.isclose(): 690. functions which tell whether two values are
approximately equal or "close" to each other.  Whether or not two values
are considered close is determined according to given absolute and
relative tolerances.  Relative tolerance is the maximum allowed
difference between ‘isclose’ arguments, relative to the larger absolute
value:

     >>> import math
     >>> a = 5.0
     >>> b = 4.99998
     >>> math.isclose(a, b, rel_tol=1e-5)
     True
     >>> math.isclose(a, b, rel_tol=1e-6)
     False

It is also possible to compare two values using absolute tolerance,
which must be a non-negative value:

     >>> import math
     >>> a = 5.0
     >>> b = 4.99998
     >>> math.isclose(a, b, abs_tol=0.00003)
     True
     >>> math.isclose(a, b, abs_tol=0.00001)
     False

参见
....

PEP 485(2) —— 用于测试近似相等的函数

     PEP 由 Christopher Barker 撰写，由 Chris Barker 和 Tal Einat 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0485

   (2) https://www.python.org/dev/peps/pep-0485


File: python.info,  Node: PEP 486 Make the Python Launcher aware of virtual environments,  Next: PEP 488 Elimination of PYO files,  Prev: PEP 485 A function for testing approximate equality,  Up: 新的特性<4>

1.4.2.10 PEP 486: Make the Python Launcher aware of virtual environments
........................................................................

PEP 486(1) makes the Windows launcher (see PEP 397(2)) aware of an
active virtual environment.  When the default interpreter would be used
and the ‘VIRTUAL_ENV’ environment variable is set, the interpreter in
the virtual environment will be used.

参见
....

PEP 486(3) – Make the Python Launcher aware of virtual environments

     PEP 由 Paul Moore 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0486

   (2) https://www.python.org/dev/peps/pep-0397

   (3) https://www.python.org/dev/peps/pep-0486


File: python.info,  Node: PEP 488 Elimination of PYO files,  Next: PEP 489 Multi-phase extension module initialization,  Prev: PEP 486 Make the Python Launcher aware of virtual environments,  Up: 新的特性<4>

1.4.2.11 PEP 488: Elimination of PYO files
..........................................

PEP 488(1) does away with the concept of ‘.pyo’ files.  This means that
‘.pyc’ files represent both unoptimized and optimized bytecode.  To
prevent the need to constantly regenerate bytecode files, ‘.pyc’ files
now have an optional ‘opt-’ tag in their name when the bytecode is
optimized.  This has the side-effect of no more bytecode file name
clashes when running under either *note -O: 694. or *note -OO: 695.
Consequently, bytecode files generated from *note -O: 694, and *note
-OO: 695. may now exist simultaneously.  *note
importlib.util.cache_from_source(): 560. has an updated API to help with
this change.

参见
....

PEP 488(2) – Elimination of PYO files

     PEP 由 Brett Cannon 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0488

   (2) https://www.python.org/dev/peps/pep-0488


File: python.info,  Node: PEP 489 Multi-phase extension module initialization,  Prev: PEP 488 Elimination of PYO files,  Up: 新的特性<4>

1.4.2.12 PEP 489: Multi-phase extension module initialization
.............................................................

PEP 489(1) updates extension module initialization to take advantage of
the two step module loading mechanism introduced by PEP 451(2) in Python
3.4.

This change brings the import semantics of extension modules that opt-in
to using the new mechanism much closer to those of Python source and
bytecode modules, including the ability to use any valid identifier as a
module name, rather than being restricted to ASCII.

参见
....

PEP 489(3) – Multi-phase extension module initialization

     PEP 由 Petr Viktorin , Stefan Behnel 和 Nick Coghlan 撰写，由 Petr
     Viktorin 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0489

   (2) https://www.python.org/dev/peps/pep-0451

   (3) https://www.python.org/dev/peps/pep-0489


File: python.info,  Node: 其他语言特性修改<4>,  Next: 新增模块<4>,  Prev: 新的特性<4>,  Up: Python 3 5 有什么新变化

1.4.3 其他语言特性修改
----------------------

对Python 语言核心进行的小改动：

   * Added the ‘"namereplace"’ error handlers.  The ‘"backslashreplace"’
     error handlers now work with decoding and translating.
     (Contributed by Serhiy Storchaka in bpo-19676(1) and bpo-22286(2).)

   * The *note -b: 41d. option now affects comparisons of *note bytes:
     33a. with *note int: 185.  (Contributed by Serhiy Storchaka in
     bpo-23681(3).)

   * New Kazakh ‘kz1048’ and Tajik ‘koi8_t’ *note codecs: 698.
     (Contributed by Serhiy Storchaka in bpo-22682(4) and bpo-22681(5).)

   * Property docstrings are now writable.  This is especially useful
     for *note collections.namedtuple(): 1b7. docstrings.  (Contributed
     by Berker Peksag in bpo-24064(6).)

   * Circular imports involving relative imports are now supported.
     (Contributed by Brett Cannon and Antoine Pitrou in bpo-17636(7).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19676

   (2) https://bugs.python.org/issue22286

   (3) https://bugs.python.org/issue23681

   (4) https://bugs.python.org/issue22682

   (5) https://bugs.python.org/issue22681

   (6) https://bugs.python.org/issue24064

   (7) https://bugs.python.org/issue17636


File: python.info,  Node: 新增模块<4>,  Next: 改进的模块<4>,  Prev: 其他语言特性修改<4>,  Up: Python 3 5 有什么新变化

1.4.4 新增模块
--------------

* Menu:

* typing: typing<3>.
* zipapp: zipapp<2>.


File: python.info,  Node: typing<3>,  Next: zipapp<2>,  Up: 新增模块<4>

1.4.4.1 typing
..............

The new *note typing: 11a. *note provisional: 351. module provides
standard definitions and tools for function type annotations.  See *note
Type Hints: 637. for more information.


File: python.info,  Node: zipapp<2>,  Prev: typing<3>,  Up: 新增模块<4>

1.4.4.2 zipapp
..............

The new *note zipapp: 142. module (specified in PEP 441(1)) provides an
API and command line tool for creating executable Python Zip
Applications, which were introduced in Python 2.6 in bpo-1739468(2), but
which were not well publicized, either at the time or since.

With the new module, bundling your application is as simple as putting
all the files, including a ‘__main__.py’ file, into a directory ‘myapp’
and running:

     $ python -m zipapp myapp
     $ python myapp.pyz

The module implementation has been contributed by Paul Moore in
bpo-23491(3).

参见
....

PEP 441(4) – Improving Python ZIP Application Support

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0441

   (2) https://bugs.python.org/issue1739468

   (3) https://bugs.python.org/issue23491

   (4) https://www.python.org/dev/peps/pep-0441


File: python.info,  Node: 改进的模块<4>,  Next: 其他模块级更改,  Prev: 新增模块<4>,  Up: Python 3 5 有什么新变化

1.4.5 改进的模块
----------------

* Menu:

* argparse: argparse<2>.
* asyncio: asyncio<5>.
* bz2::
* cgi::
* cmath: cmath<2>.
* code::
* collections: collections<5>.
* collections.abc: collections abc.
* compileall: compileall<2>.
* concurrent.futures: concurrent futures<3>.
* configparser::
* contextlib: contextlib<3>.
* csv: csv<2>.
* curses: curses<2>.
* dbm: dbm<4>.
* difflib::
* distutils: distutils<4>.
* doctest::
* email: email<2>.
* enum: enum<4>.
* faulthandler: faulthandler<2>.
* functools: functools<3>.
* glob::
* gzip: gzip<2>.
* heapq::
* http::
* http.client: http client<3>.
* idlelib 与 IDLE: idlelib 与 IDLE<3>.
* imaplib::
* imghdr::
* importlib: importlib<5>.
* inspect: inspect<3>.
* io: io<3>.
* ipaddress: ipaddress<2>.
* json: json<2>.
* linecache::
* locale: locale<3>.
* logging: logging<4>.
* lzma::
* math: math<4>.
* multiprocessing: multiprocessing<4>.
* operator::
* os: os<5>.
* pathlib: pathlib<4>.
* pickle: pickle<3>.
* poplib::
* re: re<4>.
* readline: readline<2>.
* selectors::
* shutil: shutil<2>.
* signal: signal<2>.
* smtpd::
* smtplib::
* sndhdr::
* socket: socket<5>.
* ssl: ssl<6>.
* sqlite3: sqlite3<3>.
* subprocess: subprocess<3>.
* sys: sys<5>.
* sysconfig::
* tarfile: tarfile<2>.
* threading: threading<3>.
* time: time<4>.
* timeit: timeit<2>.
* tkinter: tkinter<5>.
* 回溯: 回溯<2>.
* types: types<2>.
* unicodedata: unicodedata<4>.
* unittest: unittest<3>.
* unittest.mock: unittest mock<3>.
* urllib::
* wsgiref::
* xmlrpc: xmlrpc<2>.
* xml.sax: xml sax.
* zipfile: zipfile<3>.


File: python.info,  Node: argparse<2>,  Next: asyncio<5>,  Up: 改进的模块<4>

1.4.5.1 argparse
................

The *note ArgumentParser: 69e. class now allows disabling *note
abbreviated usage: 69f. of long options by setting *note allow_abbrev:
6a0. to ‘False’.  (Contributed by Jonathan Paugh, Steven Bethard, paul
j3 and Daniel Eriksson in bpo-14910(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14910


File: python.info,  Node: asyncio<5>,  Next: bz2,  Prev: argparse<2>,  Up: 改进的模块<4>

1.4.5.2 asyncio
...............

Since the *note asyncio: a. module is *note provisional: 351, all
changes introduced in Python 3.5 have also been backported to Python
3.4.x.

Notable changes in the *note asyncio: a. module since Python 3.4.0:

   * New debugging APIs: *note loop.set_debug(): 6a2. and *note
     loop.get_debug(): 6a3. methods.  (Contributed by Victor Stinner.)

   * The proactor event loop now supports SSL. (Contributed by Antoine
     Pitrou and Victor Stinner in bpo-22560(1).)

   * A new *note loop.is_closed(): 6a4. method to check if the event
     loop is closed.  (Contributed by Victor Stinner in bpo-21326(2).)

   * A new *note loop.create_task(): 1b0. to conveniently create and
     schedule a new *note Task: 1ae. for a coroutine.  The ‘create_task’
     method is also used by all asyncio functions that wrap coroutines
     into tasks, such as *note asyncio.wait(): 28a, *note
     asyncio.gather(): 287, etc.  (Contributed by Victor Stinner.)

   * A new *note transport.get_write_buffer_limits(): 6a5. method to
     inquire for `high-' and `low-' water limits of the flow control.
     (Contributed by Victor Stinner.)

   * The ‘async()’ function is deprecated in favor of *note
     ensure_future(): 51f.  (Contributed by Yury Selivanov.)

   * New *note loop.set_task_factory(): 6a6. and *note
     loop.get_task_factory(): 6a7. methods to customize the task factory
     that *note loop.create_task(): 1b0. method uses.  (Contributed by
     Yury Selivanov.)

   * New *note Queue.join(): 6a8. and *note Queue.task_done(): 6a9.
     queue methods.  (Contributed by Victor Stinner.)

   * The ‘JoinableQueue’ class was removed, in favor of the *note
     asyncio.Queue: 291. class.  (Contributed by Victor Stinner.)

3.5.1 中的更新：

   * The *note ensure_future(): 51f. function and all functions that use
     it, such as *note loop.run_until_complete(): 520, now accept all
     kinds of *note awaitable objects: 521.  (Contributed by Yury
     Selivanov.)

   * New *note run_coroutine_threadsafe(): 522. function to submit
     coroutines to event loops from other threads.  (Contributed by
     Vincent Michel.)

   * New *note Transport.is_closing(): 523. method to check if the
     transport is closing or closed.  (Contributed by Yury Selivanov.)

   * The *note loop.create_server(): 366. method can now accept a list
     of hosts.  (Contributed by Yann Sionneau.)

3.5.2 中的更新：

   * New *note loop.create_future(): 524. method to create Future
     objects.  This allows alternative event loop implementations, such
     as uvloop(3), to provide a faster *note asyncio.Future: 44b.
     implementation.  (Contributed by Yury Selivanov.)

   * New *note loop.get_exception_handler(): 525. method to get the
     current exception handler.  (Contributed by Yury Selivanov.)

   * New *note StreamReader.readuntil(): 526. method to read data from
     the stream until a separator bytes sequence appears.  (Contributed
     by Mark Korenberg.)

   * The *note loop.create_connection(): 1b3. and *note
     loop.create_server(): 366. methods are optimized to avoid calling
     the system ‘getaddrinfo’ function if the address is already
     resolved.  (Contributed by A. Jesse Jiryu Davis.)

   * The *note loop.sock_connect(sock, address): 6aa. no longer requires
     the `address' to be resolved prior to the call.  (Contributed by A.
     Jesse Jiryu Davis.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22560

   (2) https://bugs.python.org/issue21326

   (3) https://github.com/MagicStack/uvloop


File: python.info,  Node: bz2,  Next: cgi,  Prev: asyncio<5>,  Up: 改进的模块<4>

1.4.5.3 bz2
...........

The *note BZ2Decompressor.decompress: 6ac. method now accepts an
optional `max_length' argument to limit the maximum size of decompressed
data.  (Contributed by Nikolaus Rath in bpo-15955(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15955


File: python.info,  Node: cgi,  Next: cmath<2>,  Prev: bz2,  Up: 改进的模块<4>

1.4.5.4 cgi
...........

The ‘FieldStorage’ class now supports the *note context manager: 571.
protocol.  (Contributed by Berker Peksag in bpo-20289(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20289


File: python.info,  Node: cmath<2>,  Next: code,  Prev: cgi,  Up: 改进的模块<4>

1.4.5.5 cmath
.............

A new function *note isclose(): 690. provides a way to test for
approximate equality.  (Contributed by Chris Barker and Tal Einat in
bpo-24270(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24270


File: python.info,  Node: code,  Next: collections<5>,  Prev: cmath<2>,  Up: 改进的模块<4>

1.4.5.6 code
............

The *note InteractiveInterpreter.showtraceback(): 6b0. method now prints
the full chained traceback, just like the interactive interpreter.
(Contributed by Claudiu Popa in bpo-17442(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17442


File: python.info,  Node: collections<5>,  Next: collections abc,  Prev: code,  Up: 改进的模块<4>

1.4.5.7 collections
...................

The *note OrderedDict: 1ba. class is now implemented in C, which makes
it 4 to 100 times faster.  (Contributed by Eric Snow in bpo-16991(1).)

‘OrderedDict.items()’, ‘OrderedDict.keys()’, ‘OrderedDict.values()’
views now support *note reversed(): 18f. iteration.  (Contributed by
Serhiy Storchaka in bpo-19505(2).)

The *note deque: 539. class now defines *note index(): 6b2, *note
insert(): 6b3, and *note copy(): 6b4, and supports the ‘+’ and ‘*’
operators.  This allows deques to be recognized as a *note
MutableSequence: 6b5. and improves their substitutability for lists.
(Contributed by Raymond Hettinger in bpo-23704(3).)

Docstrings produced by *note namedtuple(): 1b7. can now be updated:

     Point = namedtuple('Point', ['x', 'y'])
     Point.__doc__ += ': Cartesian coodinate'
     Point.x.__doc__ = 'abscissa'
     Point.y.__doc__ = 'ordinate'

（由 Berker Peksag 在 bpo-24064(4) 中贡献。）

The *note UserString: 6b6. class now implements the *note
__getnewargs__(): 6b7, *note __rmod__(): 6b8, *note casefold(): 6b9,
*note format_map(): 6ba, *note isprintable(): 6bb, and *note
maketrans(): 6bc. methods to match the corresponding methods of *note
str: 339.  (Contributed by Joe Jevnik in bpo-22189(5).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16991

   (2) https://bugs.python.org/issue19505

   (3) https://bugs.python.org/issue23704

   (4) https://bugs.python.org/issue24064

   (5) https://bugs.python.org/issue22189


File: python.info,  Node: collections abc,  Next: compileall<2>,  Prev: collections<5>,  Up: 改进的模块<4>

1.4.5.8 collections.abc
.......................

The ‘Sequence.index()’ method now accepts `start' and `stop' arguments
to match the corresponding methods of *note tuple: 486, *note list: 263,
etc.  (Contributed by Devin Jeanpierre in bpo-23086(1).)

A new *note Generator: 6be. abstract base class.  (Contributed by Stefan
Behnel in bpo-24018(2).)

New *note Awaitable: 6bf, *note Coroutine: 6c0, *note AsyncIterator:
6c1, and *note AsyncIterable: 6c2. abstract base classes.  (Contributed
by Yury Selivanov in bpo-24184(3).)

For earlier Python versions, a backport of the new ABCs is available in
an external PyPI package(4).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23086

   (2) https://bugs.python.org/issue24018

   (3) https://bugs.python.org/issue24184

   (4) https://pypi.org/project/backports_abc


File: python.info,  Node: compileall<2>,  Next: concurrent futures<3>,  Prev: collections abc,  Up: 改进的模块<4>

1.4.5.9 compileall
..................

A new *note compileall: 21. option, ‘-j `N'’, allows running `N' workers
simultaneously to perform parallel bytecode compilation.  The *note
compile_dir(): 37b. function has a corresponding ‘workers’ parameter.
(Contributed by Claudiu Popa in bpo-16104(1).)

Another new option, ‘-r’, allows controlling the maximum recursion level
for subdirectories.  (Contributed by Claudiu Popa in bpo-19628(2).)

The ‘-q’ command line option can now be specified more than once, in
which case all output, including errors, will be suppressed.  The
corresponding ‘quiet’ parameter in *note compile_dir(): 37b, *note
compile_file(): 6c4, and *note compile_path(): 6c5. can now accept an
integer value indicating the level of output suppression.  (Contributed
by Thomas Kluyver in bpo-21338(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16104

   (2) https://bugs.python.org/issue19628

   (3) https://bugs.python.org/issue21338


File: python.info,  Node: concurrent futures<3>,  Next: configparser,  Prev: compileall<2>,  Up: 改进的模块<4>

1.4.5.10 concurrent.futures
...........................

The *note Executor.map(): 6c7. method now accepts a `chunksize' argument
to allow batching of tasks to improve performance when *note
ProcessPoolExecutor(): 2a4. is used.  (Contributed by Dan O’Reilly in
bpo-11271(1).)

The number of workers in the *note ThreadPoolExecutor: 27b. constructor
is optional now.  The default value is 5 times the number of CPUs.
(Contributed by Claudiu Popa in bpo-21527(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11271

   (2) https://bugs.python.org/issue21527


File: python.info,  Node: configparser,  Next: contextlib<3>,  Prev: concurrent futures<3>,  Up: 改进的模块<4>

1.4.5.11 configparser
.....................

*note configparser: 23. now provides a way to customize the conversion
of values by specifying a dictionary of converters in the *note
ConfigParser: 4b2. constructor, or by defining them as methods in
‘ConfigParser’ subclasses.  Converters defined in a parser instance are
inherited by its section proxies.

示例:

     >>> import configparser
     >>> conv = {}
     >>> conv['list'] = lambda v: [e.strip() for e in v.split() if e.strip()]
     >>> cfg = configparser.ConfigParser(converters=conv)
     >>> cfg.read_string("""
     ... [s]
     ... list = a b c d e f g
     ... """)
     >>> cfg.get('s', 'list')
     'a b c d e f g'
     >>> cfg.getlist('s', 'list')
     ['a', 'b', 'c', 'd', 'e', 'f', 'g']
     >>> section = cfg['s']
     >>> section.getlist('list')
     ['a', 'b', 'c', 'd', 'e', 'f', 'g']

（由 Łukasz Langa 在 bpo-18159(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18159


File: python.info,  Node: contextlib<3>,  Next: csv<2>,  Prev: configparser,  Up: 改进的模块<4>

1.4.5.12 contextlib
...................

The new *note redirect_stderr(): 6ca. *note context manager: 571.
(similar to *note redirect_stdout(): 6cb.) makes it easier for utility
scripts to handle inflexible APIs that write their output to *note
sys.stderr: 318. and don’t provide any options to redirect it:

     >>> import contextlib, io, logging
     >>> f = io.StringIO()
     >>> with contextlib.redirect_stderr(f):
     ...     logging.warning('warning')
     ...
     >>> f.getvalue()
     'WARNING:root:warning\n'

（由 Berker Peksag 在 bpo-22389(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22389


File: python.info,  Node: csv<2>,  Next: curses<2>,  Prev: contextlib<3>,  Up: 改进的模块<4>

1.4.5.13 csv
............

The *note writerow(): 6cd. method now supports arbitrary iterables, not
just sequences.  (Contributed by Serhiy Storchaka in bpo-23171(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23171


File: python.info,  Node: curses<2>,  Next: dbm<4>,  Prev: csv<2>,  Up: 改进的模块<4>

1.4.5.14 curses
...............

The new *note update_lines_cols(): 6cf. function updates the ‘LINES’ and
‘COLS’ environment variables.  This is useful for detecting manual
screen resizing.  (Contributed by Arnon Yaari in bpo-4254(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4254


File: python.info,  Node: dbm<4>,  Next: difflib,  Prev: curses<2>,  Up: 改进的模块<4>

1.4.5.15 dbm
............

*note dumb.open: 2c0. always creates a new database when the flag has
the value ‘"n"’.  (Contributed by Claudiu Popa in bpo-18039(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18039


File: python.info,  Node: difflib,  Next: distutils<4>,  Prev: dbm<4>,  Up: 改进的模块<4>

1.4.5.16 difflib
................

The charset of HTML documents generated by *note HtmlDiff.make_file():
6d2. can now be customized by using a new `charset' keyword-only
argument.  The default charset of HTML document changed from
‘"ISO-8859-1"’ to ‘"utf-8"’.  (Contributed by Berker Peksag in
bpo-2052(1).)

The *note diff_bytes(): 6d3. function can now compare lists of byte
strings.  This fixes a regression from Python 2.  (Contributed by Terry
J. Reedy and Greg Ward in bpo-17445(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2052

   (2) https://bugs.python.org/issue17445


File: python.info,  Node: distutils<4>,  Next: doctest,  Prev: difflib,  Up: 改进的模块<4>

1.4.5.17 distutils
..................

Both the ‘build’ and ‘build_ext’ commands now accept a ‘-j’ option to
enable parallel building of extension modules.  (Contributed by Antoine
Pitrou in bpo-5309(1).)

The *note distutils: 39. module now supports ‘xz’ compression, and can
be enabled by passing ‘xztar’ as an argument to ‘bdist --format’.
(Contributed by Serhiy Storchaka in bpo-16314(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5309

   (2) https://bugs.python.org/issue16314


File: python.info,  Node: doctest,  Next: email<2>,  Prev: distutils<4>,  Up: 改进的模块<4>

1.4.5.18 doctest
................

The *note DocTestSuite(): 6d6. function returns an empty *note
unittest.TestSuite: 6d7. if `module' contains no docstrings, instead of
raising *note ValueError: 1fc.  (Contributed by Glenn Jones in
bpo-15916(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15916


File: python.info,  Node: email<2>,  Next: enum<4>,  Prev: doctest,  Up: 改进的模块<4>

1.4.5.19 email
..............

A new policy option *note Policy.mangle_from_: 6d9. controls whether or
not lines that start with ‘"From "’ in email bodies are prefixed with a
‘">"’ character by generators.  The default is ‘True’ for *note
compat32: 549. and ‘False’ for all other policies.  (Contributed by
Milan Oberkirch in bpo-20098(1).)

A new *note Message.get_content_disposition(): 6da. method provides easy
access to a canonical value for the ‘Content-Disposition’ header.
(Contributed by Abhilash Raj in bpo-21083(2).)

A new policy option *note EmailPolicy.utf8: 6db. can be set to ‘True’ to
encode email headers using the UTF-8 charset instead of using encoded
words.  This allows ‘Messages’ to be formatted according to RFC 6532(3)
and used with an SMTP server that supports the RFC 6531(4) ‘SMTPUTF8’
extension.  (Contributed by R. David Murray in bpo-24211(5).)

The *note mime.text.MIMEText: 6dc. constructor now accepts a *note
charset.Charset: 6dd. instance.  (Contributed by Claude Paroz and Berker
Peksag in bpo-16324(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20098

   (2) https://bugs.python.org/issue21083

   (3) https://tools.ietf.org/html/rfc6532.html

   (4) https://tools.ietf.org/html/rfc6531.html

   (5) https://bugs.python.org/issue24211

   (6) https://bugs.python.org/issue16324


File: python.info,  Node: enum<4>,  Next: faulthandler<2>,  Prev: email<2>,  Up: 改进的模块<4>

1.4.5.20 enum
.............

The *note Enum: 38f. callable has a new parameter `start' to specify the
initial number of enum values if only `names' are provided:

     >>> Animal = enum.Enum('Animal', 'cat dog', start=10)
     >>> Animal.cat
     <Animal.cat: 10>
     >>> Animal.dog
     <Animal.dog: 11>

（由 Ethan Furman 在 bpo-21706(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21706


File: python.info,  Node: faulthandler<2>,  Next: functools<3>,  Prev: enum<4>,  Up: 改进的模块<4>

1.4.5.21 faulthandler
.....................

The *note enable(): 551, *note register(): 6e0, *note dump_traceback():
6e1. and *note dump_traceback_later(): 6e2. functions now accept file
descriptors in addition to file-like objects.  (Contributed by Wei Wu in
bpo-23566(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23566


File: python.info,  Node: functools<3>,  Next: glob,  Prev: faulthandler<2>,  Up: 改进的模块<4>

1.4.5.22 functools
..................

Most of the *note lru_cache(): 1c8. machinery is now implemented in C,
making it significantly faster.  (Contributed by Matt Joiner, Alexey
Kachayev, and Serhiy Storchaka in bpo-14373(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14373


File: python.info,  Node: glob,  Next: gzip<2>,  Prev: functools<3>,  Up: 改进的模块<4>

1.4.5.23 glob
.............

The *note iglob(): 5d0. and *note glob(): 5cf. functions now support
recursive search in subdirectories, using the ‘"**"’ pattern.
(Contributed by Serhiy Storchaka in bpo-13968(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13968


File: python.info,  Node: gzip<2>,  Next: heapq,  Prev: glob,  Up: 改进的模块<4>

1.4.5.24 gzip
.............

The `mode' argument of the *note GzipFile: 6e6. constructor now accepts
‘"x"’ to request exclusive creation.  (Contributed by Tim Heaney in
bpo-19222(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19222


File: python.info,  Node: heapq,  Next: http,  Prev: gzip<2>,  Up: 改进的模块<4>

1.4.5.25 heapq
..............

Element comparison in *note merge(): 6e8. can now be customized by
passing a *note key function: 6e9. in a new optional `key' keyword
argument, and a new optional `reverse' keyword argument can be used to
reverse element comparison:

     >>> import heapq
     >>> a = ['9', '777', '55555']
     >>> b = ['88', '6666']
     >>> list(heapq.merge(a, b, key=len))
     ['9', '88', '777', '6666', '55555']
     >>> list(heapq.merge(reversed(a), reversed(b), key=len, reverse=True))
     ['55555', '6666', '777', '88', '9']

（由 Raymond Hettinger 在 bpo-13742(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13742


File: python.info,  Node: http,  Next: http client<3>,  Prev: heapq,  Up: 改进的模块<4>

1.4.5.26 http
.............

A new *note HTTPStatus: 6eb. enum that defines a set of HTTP status
codes, reason phrases and long descriptions written in English.
(Contributed by Demian Brecht in bpo-21793(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21793


File: python.info,  Node: http client<3>,  Next: idlelib 与 IDLE<3>,  Prev: http,  Up: 改进的模块<4>

1.4.5.27 http.client
....................

*note HTTPConnection.getresponse(): 6ed. now raises a *note
RemoteDisconnected: 6ee. exception when a remote server connection is
closed unexpectedly.  Additionally, if a *note ConnectionError: 6ef. (of
which ‘RemoteDisconnected’ is a subclass) is raised, the client socket
is now closed automatically, and will reconnect on the next request:

     import http.client
     conn = http.client.HTTPConnection('www.python.org')
     for retries in range(3):
         try:
             conn.request('GET', '/')
             resp = conn.getresponse()
         except http.client.RemoteDisconnected:
             pass

（由 Martin Panter 在 bpo-3566(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3566


File: python.info,  Node: idlelib 与 IDLE<3>,  Next: imaplib,  Prev: http client<3>,  Up: 改进的模块<4>

1.4.5.28 idlelib 与 IDLE
........................

Since idlelib implements the IDLE shell and editor and is not intended
for import by other programs, it gets improvements with every release.
See ‘Lib/idlelib/NEWS.txt’ for a cumulative list of changes since 3.4.0,
as well as changes made in future 3.5.x releases.  This file is also
available from the IDLE Help ‣ About IDLE dialog.


File: python.info,  Node: imaplib,  Next: imghdr,  Prev: idlelib 与 IDLE<3>,  Up: 改进的模块<4>

1.4.5.29 imaplib
................

The *note IMAP4: 614. class now supports the *note context manager: 571.
protocol.  When used in a *note with: 6f2. statement, the IMAP4 ‘LOGOUT’
command will be called automatically at the end of the block.
(Contributed by Tarek Ziadé and Serhiy Storchaka in bpo-4972(1).)

The *note imaplib: 98. module now supports RFC 5161(2) (ENABLE
Extension) and RFC 6855(3) (UTF-8 Support) via the *note IMAP4.enable():
6f3. method.  A new *note IMAP4.utf8_enabled: 6f4. attribute tracks
whether or not RFC 6855(4) support is enabled.  (Contributed by Milan
Oberkirch, R. David Murray, and Maciej Szulik in bpo-21800(5).)

The *note imaplib: 98. module now automatically encodes non-ASCII string
usernames and passwords using UTF-8, as recommended by the RFCs.
(Contributed by Milan Oberkirch in bpo-21800(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4972

   (2) https://tools.ietf.org/html/rfc5161.html

   (3) https://tools.ietf.org/html/rfc6855.html

   (4) https://tools.ietf.org/html/rfc6855.html

   (5) https://bugs.python.org/issue21800

   (6) https://bugs.python.org/issue21800


File: python.info,  Node: imghdr,  Next: importlib<5>,  Prev: imaplib,  Up: 改进的模块<4>

1.4.5.30 imghdr
...............

The *note what(): 6f6. function now recognizes the OpenEXR(1) format
(contributed by Martin Vignali and Claudiu Popa in bpo-20295(2)), and
the WebP(3) format (contributed by Fabrice Aneche and Claudiu Popa in
bpo-20197(4).)

   ---------- Footnotes ----------

   (1) http://www.openexr.com

   (2) https://bugs.python.org/issue20295

   (3) https://en.wikipedia.org/wiki/WebP

   (4) https://bugs.python.org/issue20197


File: python.info,  Node: importlib<5>,  Next: inspect<3>,  Prev: imghdr,  Up: 改进的模块<4>

1.4.5.31 importlib
..................

The *note util.LazyLoader: 55c. class allows for lazy loading of modules
in applications where startup time is important.  (Contributed by Brett
Cannon in bpo-17621(1).)

The *note abc.InspectLoader.source_to_code(): 6f8. method is now a
static method.  This makes it easier to initialize a module object with
code compiled from a string by running ‘exec(code, module.__dict__)’.
(Contributed by Brett Cannon in bpo-21156(2).)

The new *note util.module_from_spec(): 6f9. function is now the
preferred way to create a new module.  As opposed to creating a *note
types.ModuleType: 6fa. instance directly, this new function will set the
various import-controlled attributes based on the passed-in spec object.
(Contributed by Brett Cannon in bpo-20383(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17621

   (2) https://bugs.python.org/issue21156

   (3) https://bugs.python.org/issue20383


File: python.info,  Node: inspect<3>,  Next: io<3>,  Prev: importlib<5>,  Up: 改进的模块<4>

1.4.5.32 inspect
................

Both the *note Signature: 6fc. and *note Parameter: 6fd. classes are now
picklable and hashable.  (Contributed by Yury Selivanov in bpo-20726(1)
and bpo-20334(2).)

A new *note BoundArguments.apply_defaults(): 6fe. method provides a way
to set default values for missing arguments:

     >>> def foo(a, b='ham', *args): pass
     >>> ba = inspect.signature(foo).bind('spam')
     >>> ba.apply_defaults()
     >>> ba.arguments
     OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])

（由 Yury Selivanov 在 bpo-24190(3) 中贡献。）

A new class method *note Signature.from_callable(): 6ff. makes
subclassing of *note Signature: 6fc. easier.  (Contributed by Yury
Selivanov and Eric Snow in bpo-17373(4).)

The *note signature(): 564. function now accepts a `follow_wrapped'
optional keyword argument, which, when set to ‘False’, disables
automatic following of ‘__wrapped__’ links.  (Contributed by Yury
Selivanov in bpo-20691(5).)

A set of new functions to inspect *note coroutine functions: 648. and
*note coroutine objects: 1a7. has been added: *note iscoroutine(): 700,
*note iscoroutinefunction(): 701, *note isawaitable(): 702, *note
getcoroutinelocals(): 703, and *note getcoroutinestate(): 704.
(Contributed by Yury Selivanov in bpo-24017(6) and bpo-24400(7).)

The *note stack(): 705, *note trace(): 706, *note getouterframes(): 707,
and *note getinnerframes(): 708. functions now return a list of named
tuples.  (Contributed by Daniel Shahaf in bpo-16808(8).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20726

   (2) https://bugs.python.org/issue20334

   (3) https://bugs.python.org/issue24190

   (4) https://bugs.python.org/issue17373

   (5) https://bugs.python.org/issue20691

   (6) https://bugs.python.org/issue24017

   (7) https://bugs.python.org/issue24400

   (8) https://bugs.python.org/issue16808


File: python.info,  Node: io<3>,  Next: ipaddress<2>,  Prev: inspect<3>,  Up: 改进的模块<4>

1.4.5.33 io
...........

A new *note BufferedIOBase.readinto1(): 70a. method, that uses at most
one call to the underlying raw stream’s *note RawIOBase.read(): 70b. or
*note RawIOBase.readinto(): 70c. methods.  (Contributed by Nikolaus Rath
in bpo-20578(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20578


File: python.info,  Node: ipaddress<2>,  Next: json<2>,  Prev: io<3>,  Up: 改进的模块<4>

1.4.5.34 ipaddress
..................

Both the *note IPv4Network: 3a8. and *note IPv6Network: 3a7. classes now
accept an ‘(address, netmask)’ tuple argument, so as to easily construct
network objects from existing addresses:

     >>> import ipaddress
     >>> ipaddress.IPv4Network(('127.0.0.0', 8))
     IPv4Network('127.0.0.0/8')
     >>> ipaddress.IPv4Network(('127.0.0.0', '255.0.0.0'))
     IPv4Network('127.0.0.0/8')

（由 Peter Moody 和 Antoine Pitrou 在 bpo-16531(1) 中贡献。）

A new ‘reverse_pointer’ attribute for the *note IPv4Network: 3a8. and
*note IPv6Network: 3a7. classes returns the name of the reverse DNS PTR
record:

     >>> import ipaddress
     >>> addr = ipaddress.IPv4Address('127.0.0.1')
     >>> addr.reverse_pointer
     '1.0.0.127.in-addr.arpa'
     >>> addr6 = ipaddress.IPv6Address('::1')
     >>> addr6.reverse_pointer
     '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa'

（由 Leon Weber 在 bpo-20480(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16531

   (2) https://bugs.python.org/issue20480


File: python.info,  Node: json<2>,  Next: linecache,  Prev: ipaddress<2>,  Up: 改进的模块<4>

1.4.5.35 json
.............

The *note json.tool: a6. command line interface now preserves the order
of keys in JSON objects passed in input.  The new ‘--sort-keys’ option
can be used to sort the keys alphabetically.  (Contributed by Berker
Peksag in bpo-21650(1).)

JSON decoder now raises *note JSONDecodeError: 70f. instead of *note
ValueError: 1fc. to provide better context information about the error.
(Contributed by Serhiy Storchaka in bpo-19361(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21650

   (2) https://bugs.python.org/issue19361


File: python.info,  Node: linecache,  Next: locale<3>,  Prev: json<2>,  Up: 改进的模块<4>

1.4.5.36 linecache
..................

A new *note lazycache(): 711. function can be used to capture
information about a non-file-based module to permit getting its lines
later via *note getline(): 712.  This avoids doing I/O until a line is
actually needed, without having to carry the module globals around
indefinitely.  (Contributed by Robert Collins in bpo-17911(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17911


File: python.info,  Node: locale<3>,  Next: logging<4>,  Prev: linecache,  Up: 改进的模块<4>

1.4.5.37 locale
...............

A new *note delocalize(): 714. function can be used to convert a string
into a normalized number string, taking the ‘LC_NUMERIC’ settings into
account:

     >>> import locale
     >>> locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')
     'de_DE.UTF-8'
     >>> locale.delocalize('1.234,56')
     '1234.56'
     >>> locale.setlocale(locale.LC_NUMERIC, 'en_US.UTF-8')
     'en_US.UTF-8'
     >>> locale.delocalize('1,234.56')
     '1234.56'

（由 Cédric Krier 在 bpo-13918(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13918


File: python.info,  Node: logging<4>,  Next: lzma,  Prev: locale<3>,  Up: 改进的模块<4>

1.4.5.38 logging
................

All logging methods (*note Logger: 3af. *note log(): 716, *note
exception(): 717, *note critical(): 718, *note debug(): 719, etc.), now
accept exception instances as an `exc_info' argument, in addition to
boolean values and exception tuples:

     >>> import logging
     >>> try:
     ...     1/0
     ... except ZeroDivisionError as ex:
     ...     logging.error('exception', exc_info=ex)
     ERROR:root:exception

（由 Yury Selivanov 在 bpo-20537(1) 中贡献。）

The *note handlers.HTTPHandler: 71a. class now accepts an optional *note
ssl.SSLContext: 3ec. instance to configure SSL settings used in an HTTP
connection.  (Contributed by Alex Gaynor in bpo-22788(2).)

The *note handlers.QueueListener: 71b. class now takes a
`respect_handler_level' keyword argument which, if set to ‘True’, will
pass messages to handlers taking handler levels into account.
(Contributed by Vinay Sajip.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20537

   (2) https://bugs.python.org/issue22788


File: python.info,  Node: lzma,  Next: math<4>,  Prev: logging<4>,  Up: 改进的模块<4>

1.4.5.39 lzma
.............

The *note LZMADecompressor.decompress(): 71d. method now accepts an
optional `max_length' argument to limit the maximum size of decompressed
data.  (Contributed by Martin Panter in bpo-15955(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15955


File: python.info,  Node: math<4>,  Next: multiprocessing<4>,  Prev: lzma,  Up: 改进的模块<4>

1.4.5.40 math
.............

Two new constants have been added to the *note math: b2. module: *note
inf: 530. and *note nan: 531.  (Contributed by Mark Dickinson in
bpo-23185(1).)

A new function *note isclose(): 68f. provides a way to test for
approximate equality.  (Contributed by Chris Barker and Tal Einat in
bpo-24270(2).)

A new *note gcd(): 71f. function has been added.  The *note
fractions.gcd(): 720. function is now deprecated.  (Contributed by Mark
Dickinson and Serhiy Storchaka in bpo-22486(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23185

   (2) https://bugs.python.org/issue24270

   (3) https://bugs.python.org/issue22486


File: python.info,  Node: multiprocessing<4>,  Next: operator,  Prev: math<4>,  Up: 改进的模块<4>

1.4.5.41 multiprocessing
........................

*note sharedctypes.synchronized(): 722. objects now support the *note
context manager: 571. protocol.  (Contributed by Charles-François Natali
in bpo-21565(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21565


File: python.info,  Node: operator,  Next: os<5>,  Prev: multiprocessing<4>,  Up: 改进的模块<4>

1.4.5.42 operator
.................

*note attrgetter(): 724, *note itemgetter(): 262, and *note
methodcaller(): 725. objects now support pickling.  (Contributed by Josh
Rosenberg and Serhiy Storchaka in bpo-22955(1).)

New *note matmul(): 726. and *note imatmul(): 727. functions to perform
matrix multiplication.  (Contributed by Benjamin Peterson in
bpo-21176(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22955

   (2) https://bugs.python.org/issue21176


File: python.info,  Node: os<5>,  Next: pathlib<4>,  Prev: operator,  Up: 改进的模块<4>

1.4.5.43 os
...........

The new *note scandir(): 260. function returning an iterator of *note
DirEntry: 4f9. objects has been added.  If possible, *note scandir():
260. extracts file attributes while scanning a directory, removing the
need to perform subsequent system calls to determine file type or
attributes, which may significantly improve performance.  (Contributed
by Ben Hoyt with the help of Victor Stinner in bpo-22524(1).)

On Windows, a new *note stat_result.st_file_attributes: 729. attribute
is now available.  It corresponds to the ‘dwFileAttributes’ member of
the ‘BY_HANDLE_FILE_INFORMATION’ structure returned by
‘GetFileInformationByHandle()’.  (Contributed by Ben Hoyt in
bpo-21719(2).)

The *note urandom(): 4d9. function now uses the ‘getrandom()’ syscall on
Linux 3.17 or newer, and ‘getentropy()’ on OpenBSD 5.6 and newer,
removing the need to use ‘/dev/urandom’ and avoiding failures due to
potential file descriptor exhaustion.  (Contributed by Victor Stinner in
bpo-22181(3).)

New *note get_blocking(): 72a. and *note set_blocking(): 72b. functions
allow getting and setting a file descriptor’s blocking mode (*note
O_NONBLOCK: 72c.)  (Contributed by Victor Stinner in bpo-22054(4).)

The *note truncate(): 72d. and *note ftruncate(): 66b. functions are now
supported on Windows.  (Contributed by Steve Dower in bpo-23668(5).)

There is a new *note os.path.commonpath(): 72e. function returning the
longest common sub-path of each passed pathname.  Unlike the *note
os.path.commonprefix(): 72f. function, it always returns a valid path:

     >>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
     '/usr/l'

     >>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
     '/usr'

（由 Rafik Draoui 和 Serhiy Storchaka 在 bpo-10395(6) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22524

   (2) https://bugs.python.org/issue21719

   (3) https://bugs.python.org/issue22181

   (4) https://bugs.python.org/issue22054

   (5) https://bugs.python.org/issue23668

   (6) https://bugs.python.org/issue10395


File: python.info,  Node: pathlib<4>,  Next: pickle<3>,  Prev: os<5>,  Up: 改进的模块<4>

1.4.5.44 pathlib
................

The new *note Path.samefile(): 731. method can be used to check whether
the path points to the same file as another path, which can be either
another *note Path: 202. object, or a string:

     >>> import pathlib
     >>> p1 = pathlib.Path('/etc/hosts')
     >>> p2 = pathlib.Path('/etc/../etc/hosts')
     >>> p1.samefile(p2)
     True

（由 Vajrasky Kok 和 Antoine Pitrou 在 bpo-19775(1) 中贡献。）

The *note Path.mkdir(): 732. method now accepts a new optional
`exist_ok' argument to match ‘mkdir -p’ and *note os.makedirs(): 3c5.
functionality.  (Contributed by Berker Peksag in bpo-21539(2).)

There is a new *note Path.expanduser(): 733. method to expand ‘~’ and
‘~user’ prefixes.  (Contributed by Serhiy Storchaka and Claudiu Popa in
bpo-19776(3).)

A new *note Path.home(): 734. class method can be used to get a *note
Path: 202. instance representing the user’s home directory.
(Contributed by Victor Salgado and Mayank Tripathi in bpo-19777(4).)

New *note Path.write_text(): 735, *note Path.read_text(): 736, *note
Path.write_bytes(): 737, *note Path.read_bytes(): 738. methods to
simplify read/write operations on files.

The following code snippet will create or rewrite existing file
‘~/spam42’:

     >>> import pathlib
     >>> p = pathlib.Path('~/spam42')
     >>> p.expanduser().write_text('ham')
     3

（由 Christopher Welborn 在 bpo-20218(5) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19775

   (2) https://bugs.python.org/issue21539

   (3) https://bugs.python.org/issue19776

   (4) https://bugs.python.org/issue19777

   (5) https://bugs.python.org/issue20218


File: python.info,  Node: pickle<3>,  Next: poplib,  Prev: pathlib<4>,  Up: 改进的模块<4>

1.4.5.45 pickle
...............

Nested objects, such as unbound methods or nested classes, can now be
pickled using *note pickle protocols: 577. older than protocol version
4.  Protocol version 4 already supports these cases.  (Contributed by
Serhiy Storchaka in bpo-23611(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23611


File: python.info,  Node: poplib,  Next: re<4>,  Prev: pickle<3>,  Up: 改进的模块<4>

1.4.5.46 poplib
...............

A new *note POP3.utf8(): 73b. command enables RFC 6856(1)
(Internationalized Email) support, if a POP server supports it.
(Contributed by Milan OberKirch in bpo-21804(2).)

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc6856.html

   (2) https://bugs.python.org/issue21804


File: python.info,  Node: re<4>,  Next: readline<2>,  Prev: poplib,  Up: 改进的模块<4>

1.4.5.47 re
...........

References and conditional references to groups with fixed length are
now allowed in lookbehind assertions:

     >>> import re
     >>> pat = re.compile(r'(a|b).(?<=\1)c')
     >>> pat.match('aac')
     <_sre.SRE_Match object; span=(0, 3), match='aac'>
     >>> pat.match('bbc')
     <_sre.SRE_Match object; span=(0, 3), match='bbc'>

（由 Serhiy Storchaka 在 bpo-9179(1) 中贡献。）

The number of capturing groups in regular expressions is no longer
limited to 100.  (Contributed by Serhiy Storchaka in bpo-22437(2).)

The *note sub(): 483. and *note subn(): 73d. functions now replace
unmatched groups with empty strings instead of raising an exception.
(Contributed by Serhiy Storchaka in bpo-1519638(3).)

The *note re.error: 73e. exceptions have new attributes, *note msg: 73f,
*note pattern: 740, *note pos: 741, *note lineno: 742, and *note colno:
743, that provide better context information about the error:

     >>> re.compile("""
     ...     (?x)
     ...     .++
     ... """)
     Traceback (most recent call last):
        ...
     sre_constants.error: multiple repeat at position 16 (line 3, column 7)

（由 Serhiy Storchaka 在 bpo-22578(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9179

   (2) https://bugs.python.org/issue22437

   (3) https://bugs.python.org/issue1519638

   (4) https://bugs.python.org/issue22578


File: python.info,  Node: readline<2>,  Next: selectors,  Prev: re<4>,  Up: 改进的模块<4>

1.4.5.48 readline
.................

A new *note append_history_file(): 745. function can be used to append
the specified number of trailing elements in history to the given file.
(Contributed by Bruno Cauet in bpo-22940(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22940


File: python.info,  Node: selectors,  Next: shutil<2>,  Prev: readline<2>,  Up: 改进的模块<4>

1.4.5.49 selectors
..................

The new *note DevpollSelector: 455. supports efficient ‘/dev/poll’
polling on Solaris.  (Contributed by Giampaolo Rodola’ in bpo-18931(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18931


File: python.info,  Node: shutil<2>,  Next: signal<2>,  Prev: selectors,  Up: 改进的模块<4>

1.4.5.50 shutil
...............

The *note move(): 25c. function now accepts a `copy_function' argument,
allowing, for example, the *note copy(): 25a. function to be used
instead of the default *note copy2(): 25b. if there is a need to ignore
file metadata when moving.  (Contributed by Claudiu Popa in
bpo-19840(1).)

The *note make_archive(): 21c. function now supports the `xztar' format.
(Contributed by Serhiy Storchaka in bpo-5411(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19840

   (2) https://bugs.python.org/issue5411


File: python.info,  Node: signal<2>,  Next: smtpd,  Prev: shutil<2>,  Up: 改进的模块<4>

1.4.5.51 signal
...............

On Windows, the *note set_wakeup_fd(): 3d6. function now also supports
socket handles.  (Contributed by Victor Stinner in bpo-22018(1).)

Various ‘SIG*’ constants in the *note signal: eb. module have been
converted into *note Enums: 7b.  This allows meaningful names to be
printed during debugging, instead of integer "magic numbers".
(Contributed by Giampaolo Rodola’ in bpo-21076(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22018

   (2) https://bugs.python.org/issue21076


File: python.info,  Node: smtpd,  Next: smtplib,  Prev: signal<2>,  Up: 改进的模块<4>

1.4.5.52 smtpd
..............

Both the *note SMTPServer: 60b. and *note SMTPChannel: 60a. classes now
accept a `decode_data' keyword argument to determine if the ‘DATA’
portion of the SMTP transaction is decoded using the ‘"utf-8"’ codec or
is instead provided to the *note SMTPServer.process_message(): 60c.
method as a byte string.  The default is ‘True’ for backward
compatibility reasons, but will change to ‘False’ in Python 3.6.  If
`decode_data' is set to ‘False’, the ‘process_message’ method must be
prepared to accept keyword arguments.  (Contributed by Maciej Szulik in
bpo-19662(1).)

The *note SMTPServer: 60b. class now advertises the ‘8BITMIME’ extension
( RFC 6152(2)) if `decode_data' has been set ‘True’.  If the client
specifies ‘BODY=8BITMIME’ on the ‘MAIL’ command, it is passed to *note
SMTPServer.process_message(): 60c. via the `mail_options' keyword.
(Contributed by Milan Oberkirch and R. David Murray in bpo-21795(3).)

The *note SMTPServer: 60b. class now also supports the ‘SMTPUTF8’
extension ( RFC 6531(4): Internationalized Email).  If the client
specified ‘SMTPUTF8 BODY=8BITMIME’ on the ‘MAIL’ command, they are
passed to *note SMTPServer.process_message(): 60c. via the
`mail_options' keyword.  It is the responsibility of the
‘process_message’ method to correctly handle the ‘SMTPUTF8’ data.
(Contributed by Milan Oberkirch in bpo-21725(5).)

It is now possible to provide, directly or via name resolution, IPv6
addresses in the *note SMTPServer: 60b. constructor, and have it
successfully connect.  (Contributed by Milan Oberkirch in bpo-14758(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19662

   (2) https://tools.ietf.org/html/rfc6152.html

   (3) https://bugs.python.org/issue21795

   (4) https://tools.ietf.org/html/rfc6531.html

   (5) https://bugs.python.org/issue21725

   (6) https://bugs.python.org/issue14758


File: python.info,  Node: smtplib,  Next: sndhdr,  Prev: smtpd,  Up: 改进的模块<4>

1.4.5.53 smtplib
................

A new *note SMTP.auth(): 74b. method provides a convenient way to
implement custom authentication mechanisms.  (Contributed by Milan
Oberkirch in bpo-15014(1).)

The *note SMTP.set_debuglevel(): 74c. method now accepts an additional
debuglevel (2), which enables timestamps in debug messages.
(Contributed by Gavin Chappell and Maciej Szulik in bpo-16914(2).)

Both the *note SMTP.sendmail(): 74d. and *note SMTP.send_message(): 74e.
methods now support RFC 6531(3) (SMTPUTF8).  (Contributed by Milan
Oberkirch and R. David Murray in bpo-22027(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15014

   (2) https://bugs.python.org/issue16914

   (3) https://tools.ietf.org/html/rfc6531.html

   (4) https://bugs.python.org/issue22027


File: python.info,  Node: sndhdr,  Next: socket<5>,  Prev: smtplib,  Up: 改进的模块<4>

1.4.5.54 sndhdr
...............

The *note what(): 750. and *note whathdr(): 751. functions now return a
*note namedtuple(): 1b7.  (Contributed by Claudiu Popa in bpo-18615(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18615


File: python.info,  Node: socket<5>,  Next: ssl<6>,  Prev: sndhdr,  Up: 改进的模块<4>

1.4.5.55 socket
...............

Functions with timeouts now use a monotonic clock, instead of a system
clock.  (Contributed by Victor Stinner in bpo-22043(1).)

A new *note socket.sendfile(): 753. method allows sending a file over a
socket by using the high-performance *note os.sendfile(): 362. function
on UNIX, resulting in uploads being from 2 to 3 times faster than when
using plain *note socket.send(): 683.  (Contributed by Giampaolo Rodola’
in bpo-17552(2).)

The *note socket.sendall(): 684. method no longer resets the socket
timeout every time bytes are received or sent.  The socket timeout is
now the maximum total duration to send all data.  (Contributed by Victor
Stinner in bpo-23853(3).)

The `backlog' argument of the *note socket.listen(): 754. method is now
optional.  By default it is set to *note SOMAXCONN: 755. or to ‘128’,
whichever is less.  (Contributed by Charles-François Natali in
bpo-21455(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22043

   (2) https://bugs.python.org/issue17552

   (3) https://bugs.python.org/issue23853

   (4) https://bugs.python.org/issue21455


File: python.info,  Node: ssl<6>,  Next: sqlite3<3>,  Prev: socket<5>,  Up: 改进的模块<4>

1.4.5.56 ssl
............

* Menu:

* 内存 BIO 支持::
* Application-Layer Protocol Negotiation Support::
* Other Changes::


File: python.info,  Node: 内存 BIO 支持,  Next: Application-Layer Protocol Negotiation Support,  Up: ssl<6>

1.4.5.57 内存 BIO 支持
......................

（由 Geert Jansen 在 bpo-21965(1) 中贡献。）

The new *note SSLObject: 3eb. class has been added to provide SSL
protocol support for cases when the network I/O capabilities of *note
SSLSocket: 3ea. are not necessary or are suboptimal.  ‘SSLObject’
represents an SSL protocol instance, but does not implement any network
I/O methods, and instead provides a memory buffer interface.  The new
*note MemoryBIO: 758. class can be used to pass data between Python and
an SSL protocol instance.

The memory BIO SSL support is primarily intended to be used in
frameworks implementing asynchronous I/O for which *note SSLSocket:
3ea.’s readiness model ("select/poll") is inefficient.

A new *note SSLContext.wrap_bio(): 3ee. method can be used to create a
new ‘SSLObject’ instance.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21965


File: python.info,  Node: Application-Layer Protocol Negotiation Support,  Next: Other Changes,  Prev: 内存 BIO 支持,  Up: ssl<6>

1.4.5.58 Application-Layer Protocol Negotiation Support
.......................................................

（由 Benjamin Peterson 在 bpo-20188(1) 中贡献。）

Where OpenSSL support is present, the *note ssl: f4. module now
implements the `Application-Layer Protocol Negotiation' TLS extension as
described in RFC 7301(2).

The new *note SSLContext.set_alpn_protocols(): 75a. can be used to
specify which protocols a socket should advertise during the TLS
handshake.

The new *note SSLSocket.selected_alpn_protocol(): 75b. returns the
protocol that was selected during the TLS handshake.  The *note
HAS_ALPN: 75c. flag indicates whether ALPN support is present.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20188

   (2) https://tools.ietf.org/html/rfc7301.html


File: python.info,  Node: Other Changes,  Prev: Application-Layer Protocol Negotiation Support,  Up: ssl<6>

1.4.5.59 Other Changes
......................

There is a new *note SSLSocket.version(): 75e. method to query the
actual protocol version in use.  (Contributed by Antoine Pitrou in
bpo-20421(1).)

The *note SSLSocket: 3ea. class now implements a ‘SSLSocket.sendfile()’
method.  (Contributed by Giampaolo Rodola’ in bpo-17552(2).)

The ‘SSLSocket.send()’ method now raises either the *note
ssl.SSLWantReadError: 75f. or *note ssl.SSLWantWriteError: 760.
exception on a non-blocking socket if the operation would block.
Previously, it would return ‘0’.  (Contributed by Nikolaus Rath in
bpo-20951(3).)

The *note cert_time_to_seconds(): 761. function now interprets the input
time as UTC and not as local time, per RFC 5280(4).  Additionally, the
return value is always an *note int: 185.  (Contributed by Akira Li in
bpo-19940(5).)

New ‘SSLObject.shared_ciphers()’ and *note SSLSocket.shared_ciphers():
762. methods return the list of ciphers sent by the client during the
handshake.  (Contributed by Benjamin Peterson in bpo-23186(6).)

The *note SSLSocket.do_handshake(): 763, *note SSLSocket.read(): 764,
‘SSLSocket.shutdown()’, and *note SSLSocket.write(): 765. methods of the
*note SSLSocket: 3ea. class no longer reset the socket timeout every
time bytes are received or sent.  The socket timeout is now the maximum
total duration of the method.  (Contributed by Victor Stinner in
bpo-23853(7).)

The *note match_hostname(): 3e4. function now supports matching of IP
addresses.  (Contributed by Antoine Pitrou in bpo-23239(8).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20421

   (2) https://bugs.python.org/issue17552

   (3) https://bugs.python.org/issue20951

   (4) https://tools.ietf.org/html/rfc5280.html

   (5) https://bugs.python.org/issue19940

   (6) https://bugs.python.org/issue23186

   (7) https://bugs.python.org/issue23853

   (8) https://bugs.python.org/issue23239


File: python.info,  Node: sqlite3<3>,  Next: subprocess<3>,  Prev: ssl<6>,  Up: 改进的模块<4>

1.4.5.60 sqlite3
................

The *note Row: 767. class now fully supports the sequence protocol, in
particular *note reversed(): 18f. iteration and slice indexing.
(Contributed by Claudiu Popa in bpo-10203(1); by Lucas Sinclair, Jessica
McKellar, and Serhiy Storchaka in bpo-13583(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10203

   (2) https://bugs.python.org/issue13583


File: python.info,  Node: subprocess<3>,  Next: sys<5>,  Prev: sqlite3<3>,  Up: 改进的模块<4>

1.4.5.61 subprocess
...................

The new *note run(): 3f5. function has been added.  It runs the
specified command and returns a *note CompletedProcess: 769. object,
which describes a finished process.  The new API is more consistent and
is the recommended approach to invoking subprocesses in Python code that
does not need to maintain compatibility with earlier Python versions.
(Contributed by Thomas Kluyver in bpo-23342(1).)

示例:

     >>> subprocess.run(["ls", "-l"])  # doesn't capture output
     CompletedProcess(args=['ls', '-l'], returncode=0)

     >>> subprocess.run("exit 1", shell=True, check=True)
     Traceback (most recent call last):
       ...
     subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

     >>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
     CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
     stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23342


File: python.info,  Node: sys<5>,  Next: sysconfig,  Prev: subprocess<3>,  Up: 改进的模块<4>

1.4.5.62 sys
............

A new ‘set_coroutine_wrapper()’ function allows setting a global hook
that will be called whenever a *note coroutine object: 1a7. is created
by an *note async def: 285. function.  A corresponding
‘get_coroutine_wrapper()’ can be used to obtain a currently set wrapper.
Both functions are *note provisional: 351, and are intended for
debugging purposes only.  (Contributed by Yury Selivanov in
bpo-24017(1).)

A new *note is_finalizing(): 76b. function can be used to check if the
Python interpreter is *note shutting down: 76c.  (Contributed by Antoine
Pitrou in bpo-22696(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24017

   (2) https://bugs.python.org/issue22696


File: python.info,  Node: sysconfig,  Next: tarfile<2>,  Prev: sys<5>,  Up: 改进的模块<4>

1.4.5.63 sysconfig
..................

The name of the user scripts directory on Windows now includes the first
two components of the Python version.  (Contributed by Paul Moore in
bpo-23437(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23437


File: python.info,  Node: tarfile<2>,  Next: threading<3>,  Prev: sysconfig,  Up: 改进的模块<4>

1.4.5.64 tarfile
................

The `mode' argument of the *note open(): 76f. function now accepts ‘"x"’
to request exclusive creation.  (Contributed by Berker Peksag in
bpo-21717(1).)

The *note TarFile.extractall(): 770. and *note TarFile.extract(): 771.
methods now take a keyword argument `numeric_owner'.  If set to ‘True’,
the extracted files and directories will be owned by the numeric ‘uid’
and ‘gid’ from the tarfile.  If set to ‘False’ (the default, and the
behavior in versions prior to 3.5), they will be owned by the named user
and group in the tarfile.  (Contributed by Michael Vogt and Eric Smith
in bpo-23193(2).)

The *note TarFile.list(): 772. now accepts an optional `members' keyword
argument that can be set to a subset of the list returned by *note
TarFile.getmembers(): 773.  (Contributed by Serhiy Storchaka in
bpo-21549(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21717

   (2) https://bugs.python.org/issue23193

   (3) https://bugs.python.org/issue21549


File: python.info,  Node: threading<3>,  Next: time<4>,  Prev: tarfile<2>,  Up: 改进的模块<4>

1.4.5.65 threading
..................

Both the *note Lock.acquire(): 775. and *note RLock.acquire(): 776.
methods now use a monotonic clock for timeout management.  (Contributed
by Victor Stinner in bpo-22043(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22043


File: python.info,  Node: time<4>,  Next: timeit<2>,  Prev: threading<3>,  Up: 改进的模块<4>

1.4.5.66 time
.............

The *note monotonic(): 778. function is now always available.
(Contributed by Victor Stinner in bpo-22043(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22043


File: python.info,  Node: timeit<2>,  Next: tkinter<5>,  Prev: time<4>,  Up: 改进的模块<4>

1.4.5.67 timeit
...............

A new command line option ‘-u’ or ‘--unit=`U'’ can be used to specify
the time unit for the timer output.  Supported options are ‘usec’,
‘msec’, or ‘sec’.  (Contributed by Julian Gindi in bpo-18983(1).)

The *note timeit(): 77a. function has a new `globals' parameter for
specifying the namespace in which the code will be running.
(Contributed by Ben Roberts in bpo-2527(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18983

   (2) https://bugs.python.org/issue2527


File: python.info,  Node: tkinter<5>,  Next: 回溯<2>,  Prev: timeit<2>,  Up: 改进的模块<4>

1.4.5.68 tkinter
................

The ‘tkinter._fix’ module used for setting up the Tcl/Tk environment on
Windows has been replaced by a private function in the ‘_tkinter’ module
which makes no permanent changes to environment variables.  (Contributed
by Zachary Ware in bpo-20035(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20035


File: python.info,  Node: 回溯<2>,  Next: types<2>,  Prev: tkinter<5>,  Up: 改进的模块<4>

1.4.5.69 回溯
.............

New *note walk_stack(): 77d. and *note walk_tb(): 77e. functions to
conveniently traverse frame and traceback objects.  (Contributed by
Robert Collins in bpo-17911(1).)

New lightweight classes: *note TracebackException: 77f, *note
StackSummary: 780, and *note FrameSummary: 781.  (Contributed by Robert
Collins in bpo-17911(2).)

Both the *note print_tb(): 782. and *note print_stack(): 783. functions
now support negative values for the `limit' argument.  (Contributed by
Dmitry Kazakov in bpo-22619(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17911

   (2) https://bugs.python.org/issue17911

   (3) https://bugs.python.org/issue22619


File: python.info,  Node: types<2>,  Next: unicodedata<4>,  Prev: 回溯<2>,  Up: 改进的模块<4>

1.4.5.70 types
..............

A new *note coroutine(): 785. function to transform *note generator:
45f. and *note generator-like: 6be. objects into *note awaitables: 521.
(Contributed by Yury Selivanov in bpo-24017(1).)

A new type called *note CoroutineType: 786, which is used for *note
coroutine: 1a7. objects created by *note async def: 285. functions.
(Contributed by Yury Selivanov in bpo-24400(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24017

   (2) https://bugs.python.org/issue24400


File: python.info,  Node: unicodedata<4>,  Next: unittest<3>,  Prev: types<2>,  Up: 改进的模块<4>

1.4.5.71 unicodedata
....................

The *note unicodedata: 11b. module now uses data from Unicode 8.0.0(1).

   ---------- Footnotes ----------

   (1) http://unicode.org/versions/Unicode8.0.0/


File: python.info,  Node: unittest<3>,  Next: unittest mock<3>,  Prev: unicodedata<4>,  Up: 改进的模块<4>

1.4.5.72 unittest
.................

The *note TestLoader.loadTestsFromModule(): 789. method now accepts a
keyword-only argument `pattern' which is passed to ‘load_tests’ as the
third argument.  Found packages are now checked for ‘load_tests’
regardless of whether their path matches `pattern', because it is
impossible for a package name to match the default pattern.
(Contributed by Robert Collins and Barry A. Warsaw in bpo-16662(1).)

Unittest discovery errors now are exposed in the *note
TestLoader.errors: 78a. attribute of the *note TestLoader: 78b.
instance.  (Contributed by Robert Collins in bpo-19746(2).)

A new command line option ‘--locals’ to show local variables in
tracebacks.  (Contributed by Robert Collins in bpo-22936(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16662

   (2) https://bugs.python.org/issue19746

   (3) https://bugs.python.org/issue22936


File: python.info,  Node: unittest mock<3>,  Next: urllib,  Prev: unittest<3>,  Up: 改进的模块<4>

1.4.5.73 unittest.mock
......................

The *note Mock: 24a. class has the following improvements:

   * The class constructor has a new `unsafe' parameter, which causes
     mock objects to raise *note AttributeError: 3a3. on attribute names
     starting with ‘"assert"’.  (Contributed by Kushal Das in
     bpo-21238(1).)

   * A new *note Mock.assert_not_called(): 78d. method to check if the
     mock object was called.  (Contributed by Kushal Das in
     bpo-21262(2).)

The *note MagicMock: 78e. class now supports *note __truediv__(): 78f,
*note __divmod__(): 790. and *note __matmul__(): 651. operators.
(Contributed by Johannes Baiter in bpo-20968(3), and Håkan Lövdahl in
bpo-23581(4) and bpo-23568(5).)

It is no longer necessary to explicitly pass ‘create=True’ to the *note
patch(): 791. function when patching builtin names.  (Contributed by
Kushal Das in bpo-17660(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21238

   (2) https://bugs.python.org/issue21262

   (3) https://bugs.python.org/issue20968

   (4) https://bugs.python.org/issue23581

   (5) https://bugs.python.org/issue23568

   (6) https://bugs.python.org/issue17660


File: python.info,  Node: urllib,  Next: wsgiref,  Prev: unittest mock<3>,  Up: 改进的模块<4>

1.4.5.74 urllib
...............

A new *note request.HTTPPasswordMgrWithPriorAuth: 793. class allows HTTP
Basic Authentication credentials to be managed so as to eliminate
unnecessary ‘401’ response handling, or to unconditionally send
credentials on the first request in order to communicate with servers
that return a ‘404’ response instead of a ‘401’ if the ‘Authorization’
header is not sent.  (Contributed by Matej Cepl in bpo-19494(1) and
Akshit Khurana in bpo-7159(2).)

A new `quote_via' argument for the *note parse.urlencode(): 794.
function provides a way to control the encoding of query parts if
needed.  (Contributed by Samwyse and Arnon Yaari in bpo-13866(3).)

The *note request.urlopen(): 795. function accepts an *note
ssl.SSLContext: 3ec. object as a `context' argument, which will be used
for the HTTPS connection.  (Contributed by Alex Gaynor in bpo-22366(4).)

The *note parse.urljoin(): 796. was updated to use the RFC 3986(5)
semantics for the resolution of relative URLs, rather than RFC 1808(6)
and RFC 2396(7).  (Contributed by Demian Brecht and Senthil Kumaran in
bpo-22118(8).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19494

   (2) https://bugs.python.org/issue7159

   (3) https://bugs.python.org/issue13866

   (4) https://bugs.python.org/issue22366

   (5) https://tools.ietf.org/html/rfc3986.html

   (6) https://tools.ietf.org/html/rfc1808.html

   (7) https://tools.ietf.org/html/rfc2396.html

   (8) https://bugs.python.org/issue22118


File: python.info,  Node: wsgiref,  Next: xmlrpc<2>,  Prev: urllib,  Up: 改进的模块<4>

1.4.5.75 wsgiref
................

The `headers' argument of the *note headers.Headers: 798. class
constructor is now optional.  (Contributed by Pablo Torres Navarrete and
SilentGhost in bpo-5800(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5800


File: python.info,  Node: xmlrpc<2>,  Next: xml sax,  Prev: wsgiref,  Up: 改进的模块<4>

1.4.5.76 xmlrpc
...............

The *note client.ServerProxy: 256. class now supports the *note context
manager: 571. protocol.  (Contributed by Claudiu Popa in bpo-20627(1).)

The *note client.ServerProxy: 256. constructor now accepts an optional
*note ssl.SSLContext: 3ec. instance.  (Contributed by Alex Gaynor in
bpo-22960(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20627

   (2) https://bugs.python.org/issue22960


File: python.info,  Node: xml sax,  Next: zipfile<3>,  Prev: xmlrpc<2>,  Up: 改进的模块<4>

1.4.5.77 xml.sax
................

SAX parsers now support a character stream of the *note
xmlreader.InputSource: 79b. object.  (Contributed by Serhiy Storchaka in
bpo-2175(1).)

*note parseString(): 79c. now accepts a *note str: 339. instance.
(Contributed by Serhiy Storchaka in bpo-10590(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2175

   (2) https://bugs.python.org/issue10590


File: python.info,  Node: zipfile<3>,  Prev: xml sax,  Up: 改进的模块<4>

1.4.5.78 zipfile
................

ZIP output can now be written to unseekable streams.  (Contributed by
Serhiy Storchaka in bpo-23252(1).)

The `mode' argument of *note ZipFile.open(): 5c5. method now accepts
‘"x"’ to request exclusive creation.  (Contributed by Serhiy Storchaka
in bpo-21717(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23252

   (2) https://bugs.python.org/issue21717


File: python.info,  Node: 其他模块级更改,  Next: 性能优化<4>,  Prev: 改进的模块<4>,  Up: Python 3 5 有什么新变化

1.4.6 其他模块级更改
--------------------

Many functions in the *note mmap: b4, *note ossaudiodev: c7, *note
socket: f0, *note ssl: f4, and *note codecs: 1c. modules now accept
writable *note bytes-like objects: 5f1.  (Contributed by Serhiy
Storchaka in bpo-23001(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23001


File: python.info,  Node: 性能优化<4>,  Next: 构建和 C API 的改变<3>,  Prev: 其他模块级更改,  Up: Python 3 5 有什么新变化

1.4.7 性能优化
--------------

The *note os.walk(): 65d. function has been sped up by 3 to 5 times on
POSIX systems, and by 7 to 20 times on Windows.  This was done using the
new *note os.scandir(): 260. function, which exposes file information
from the underlying ‘readdir’ or ‘FindFirstFile’/‘FindNextFile’ system
calls.  (Contributed by Ben Hoyt with help from Victor Stinner in
bpo-23605(1).)

Construction of ‘bytes(int)’ (filled by zero bytes) is faster and uses
less memory for large objects.  ‘calloc()’ is used instead of ‘malloc()’
to allocate memory for these objects.  (Contributed by Victor Stinner in
bpo-21233(2).)

Some operations on *note ipaddress: a3. *note IPv4Network: 3a8. and
*note IPv6Network: 3a7. have been massively sped up, such as *note
subnets(): 7a0, *note supernet(): 7a1, *note summarize_address_range():
7a2, *note collapse_addresses(): 7a3.  The speed up can range from 3 to
15 times.  (Contributed by Antoine Pitrou, Michel Albert, and Markus in
bpo-21486(3), bpo-21487(4), bpo-20826(5), bpo-23266(6).)

Pickling of *note ipaddress: a3. objects was optimized to produce
significantly smaller output.  (Contributed by Serhiy Storchaka in
bpo-23133(7).)

Many operations on *note io.BytesIO: 7a4. are now 50% to 100% faster.
(Contributed by Serhiy Storchaka in bpo-15381(8) and David Wilson in
bpo-22003(9).)

The *note marshal.dumps(): 7a5. function is now faster: 65–85% with
versions 3 and 4, 20–25% with versions 0 to 2 on typical data, and up to
5 times in best cases.  (Contributed by Serhiy Storchaka in
bpo-20416(10) and bpo-23344(11).)

The UTF-32 encoder is now 3 to 7 times faster.  (Contributed by Serhiy
Storchaka in bpo-15027(12).)

Regular expressions are now parsed up to 10% faster.  (Contributed by
Serhiy Storchaka in bpo-19380(13).)

The *note json.dumps(): 60e. function was optimized to run with
‘ensure_ascii=False’ as fast as with ‘ensure_ascii=True’.  (Contributed
by Naoki Inada in bpo-23206(14).)

The *note PyObject_IsInstance(): 7a6. and *note PyObject_IsSubclass():
7a7. functions have been sped up in the common case that the second
argument has *note type: 611. as its metaclass.  (Contributed Georg
Brandl by in bpo-22540(15).)

Method caching was slightly improved, yielding up to 5% performance
improvement in some benchmarks.  (Contributed by Antoine Pitrou in
bpo-22847(16).)

Objects from the *note random: dd. module now use 50% less memory on
64-bit builds.  (Contributed by Serhiy Storchaka in bpo-23488(17).)

The *note property(): 1d8. getter calls are up to 25% faster.
(Contributed by Joe Jevnik in bpo-23910(18).)

Instantiation of *note fractions.Fraction: 186. is now up to 30% faster.
(Contributed by Stefan Behnel in bpo-22464(19).)

String methods *note find(): 7a8, *note rfind(): 7a9, *note split():
7aa, *note partition(): 7ab. and the *note in: 7ac. string operator are
now significantly faster for searching 1-character substrings.
(Contributed by Serhiy Storchaka in bpo-23573(20).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23605

   (2) https://bugs.python.org/issue21233

   (3) https://bugs.python.org/issue21486

   (4) https://bugs.python.org/issue21487

   (5) https://bugs.python.org/issue20826

   (6) https://bugs.python.org/issue23266

   (7) https://bugs.python.org/issue23133

   (8) https://bugs.python.org/issue15381

   (9) https://bugs.python.org/issue22003

   (10) https://bugs.python.org/issue20416

   (11) https://bugs.python.org/issue23344

   (12) https://bugs.python.org/issue15027

   (13) https://bugs.python.org/issue19380

   (14) https://bugs.python.org/issue23206

   (15) https://bugs.python.org/issue22540

   (16) https://bugs.python.org/issue22847

   (17) https://bugs.python.org/issue23488

   (18) https://bugs.python.org/issue23910

   (19) https://bugs.python.org/issue22464

   (20) https://bugs.python.org/issue23573


File: python.info,  Node: 构建和 C API 的改变<3>,  Next: 弃用<3>,  Prev: 性能优化<4>,  Up: Python 3 5 有什么新变化

1.4.8 构建和 C API 的改变
-------------------------

增加了 ‘calloc’ 函数

   * *note PyMem_RawCalloc(): 7ae,

   * *note PyMem_Calloc(): 7af,

   * *note PyObject_Calloc(): 7b0.

(Victor Stinner 贡献于 bpo-21233(1).)

新的 encoding/decoding 帮助函数:

   * *note Py_DecodeLocale(): 444. (替代 ‘_Py_char2wchar()’),

   * *note Py_EncodeLocale(): 445. (替代 ‘_Py_wchar2char()’).

（由 Victor Stinner 在 bpo-18395(2) 中贡献。）

A new *note PyCodec_NameReplaceErrors(): 7b1. function to replace the
unicode encode error with ‘\N{...}’ escapes.  (Contributed by Serhiy
Storchaka in bpo-19676(3).)

A new *note PyErr_FormatV(): 7b2. function similar to *note
PyErr_Format(): 7b3, but accepts a ‘va_list’ argument.  (Contributed by
Antoine Pitrou in bpo-18711(4).)

A new ‘PyExc_RecursionError’ exception.  (Contributed by Georg Brandl in
bpo-19235(5).)

New *note PyModule_FromDefAndSpec(): 7b4, *note
PyModule_FromDefAndSpec2(): 7b5, and *note PyModule_ExecDef(): 7b6.
functions introduced by PEP 489(6) – multi-phase extension module
initialization.  (Contributed by Petr Viktorin in bpo-24268(7).)

New *note PyNumber_MatrixMultiply(): 7b7. and *note
PyNumber_InPlaceMatrixMultiply(): 7b8. functions to perform matrix
multiplication.  (Contributed by Benjamin Peterson in bpo-21176(8).  See
also PEP 465(9) for details.)

The *note PyTypeObject.tp_finalize: 2d8. slot is now part of the stable
ABI.

Windows builds now require Microsoft Visual C++ 14.0, which is available
as part of Visual Studio 2015(10).

Extension modules now include a platform information tag in their
filename on some platforms (the tag is optional, and CPython will import
extensions without it, although if the tag is present and mismatched,
the extension won’t be loaded):

   * On Linux, extension module filenames end with
     ‘.cpython-<major><minor>m-<architecture>-<os>.pyd’:

        * ‘<major>’ is the major number of the Python version; for
          Python 3.5 this is ‘3’.

        * ‘<minor>’ is the minor number of the Python version; for
          Python 3.5 this is ‘5’.

        * ‘<architecture>’ is the hardware architecture the extension
          module was built to run on.  It’s most commonly either ‘i386’
          for 32-bit Intel platforms or ‘x86_64’ for 64-bit Intel (and
          AMD) platforms.

        * ‘<os>’ is always ‘linux-gnu’, except for extensions built to
          talk to the 32-bit ABI on 64-bit platforms, in which case it
          is ‘linux-gnu32’ (and ‘<architecture>’ will be ‘x86_64’).

   * On Windows, extension module filenames end with
     ‘<debug>.cp<major><minor>-<platform>.pyd’:

        * ‘<major>’ is the major number of the Python version; for
          Python 3.5 this is ‘3’.

        * ‘<minor>’ is the minor number of the Python version; for
          Python 3.5 this is ‘5’.

        * ‘<platform>’ is the platform the extension module was built
          for, either ‘win32’ for Win32, ‘win_amd64’ for Win64,
          ‘win_ia64’ for Windows Itanium 64, and ‘win_arm’ for Windows
          on ARM.

        * If built in debug mode, ‘<debug>’ will be ‘_d’, otherwise it
          will be blank.

   * On OS X platforms, extension module filenames now end with
     ‘-darwin.so’.

   * On all other platforms, extension module filenames are the same as
     they were with Python 3.4.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21233

   (2) https://bugs.python.org/issue18395

   (3) https://bugs.python.org/issue19676

   (4) https://bugs.python.org/issue18711

   (5) https://bugs.python.org/issue19235

   (6) https://www.python.org/dev/peps/pep-0489

   (7) https://bugs.python.org/issue24268

   (8) https://bugs.python.org/issue21176

   (9) https://www.python.org/dev/peps/pep-0465

   (10) https://www.visualstudio.com/


File: python.info,  Node: 弃用<3>,  Next: 移除<2>,  Prev: 构建和 C API 的改变<3>,  Up: Python 3 5 有什么新变化

1.4.9 弃用
----------

* Menu:

* 新关键字: 新关键字<2>.
* 已弃用的 Python 行为: 已弃用的 Python 行为<3>.
* 不支持的操作系统::
* 已弃用的 Python 模块、函数和方法: 已弃用的 Python 模块、函数和方法<3>.


File: python.info,  Node: 新关键字<2>,  Next: 已弃用的 Python 行为<3>,  Up: 弃用<3>

1.4.9.1 新关键字
................

‘async’ and ‘await’ are not recommended to be used as variable, class,
function or module names.  Introduced by PEP 492(1) in Python 3.5, they
will become proper keywords in Python 3.7.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: 已弃用的 Python 行为<3>,  Next: 不支持的操作系统,  Prev: 新关键字<2>,  Up: 弃用<3>

1.4.9.2 已弃用的 Python 行为
............................

Raising the *note StopIteration: 48e. exception inside a generator will
now generate a silent *note PendingDeprecationWarning: 27a, which will
become a non-silent deprecation warning in Python 3.6 and will trigger a
*note RuntimeError: 2bb. in Python 3.7.  See *note PEP 479; Change
StopIteration handling inside generators: 5e0. for details.


File: python.info,  Node: 不支持的操作系统,  Next: 已弃用的 Python 模块、函数和方法<3>,  Prev: 已弃用的 Python 行为<3>,  Up: 弃用<3>

1.4.9.3 不支持的操作系统
........................

Windows XP is no longer supported by Microsoft, thus, per PEP 11(1),
CPython 3.5 is no longer officially supported on this OS.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0011


File: python.info,  Node: 已弃用的 Python 模块、函数和方法<3>,  Prev: 不支持的操作系统,  Up: 弃用<3>

1.4.9.4 已弃用的 Python 模块、函数和方法
........................................

The *note formatter: 82. module has now graduated to full deprecation
and is still slated for removal in Python 3.6.

The ‘asyncio.async()’ function is deprecated in favor of *note
ensure_future(): 51f.

The *note smtpd: ed. module has in the past always decoded the DATA
portion of email messages using the ‘utf-8’ codec.  This can now be
controlled by the new `decode_data' keyword to *note SMTPServer: 60b.
The default value is ‘True’, but this default is deprecated.  Specify
the `decode_data' keyword with an appropriate value to avoid the
deprecation warning.

Directly assigning values to the *note key: 496, *note value: 497. and
*note coded_value: 498. of *note http.cookies.Morsel: 495. objects is
deprecated.  Use the *note set(): 499. method instead.  In addition, the
undocumented `LegalChars' parameter of *note set(): 499. is deprecated,
and is now ignored.

Passing a format string as keyword argument `format_string' to the *note
format(): 494. method of the *note string.Formatter: 7be. class has been
deprecated.  (Contributed by Serhiy Storchaka in bpo-23671(1).)

The ‘platform.dist()’ and ‘platform.linux_distribution()’ functions are
now deprecated.  Linux distributions use too many different ways of
describing themselves, so the functionality is left to a package.
(Contributed by Vajrasky Kok and Berker Peksag in bpo-1322(2).)

The previously undocumented ‘from_function’ and ‘from_builtin’ methods
of *note inspect.Signature: 6fc. are deprecated.  Use the new *note
Signature.from_callable(): 6ff. method instead.  (Contributed by Yury
Selivanov in bpo-24248(3).)

The *note inspect.getargspec(): 565. function is deprecated and
scheduled to be removed in Python 3.6.  (See bpo-20438(4) for details.)

The *note inspect: a1. *note getfullargspec(): 566, *note getcallargs():
7bf, and *note formatargspec(): 7c0. functions are deprecated in favor
of the *note inspect.signature(): 564. API. (Contributed by Yury
Selivanov in bpo-20438(5).)

*note getargvalues(): 7c1. and *note formatargvalues(): 7c2. functions
were inadvertently marked as deprecated with the release of Python
3.5.0.

Use of *note re.LOCALE: 3d1. flag with str patterns or *note re.ASCII:
3d0. is now deprecated.  (Contributed by Serhiy Storchaka in
bpo-22407(6).)

Use of unrecognized special sequences consisting of ‘'\'’ and an ASCII
letter in regular expression patterns and replacement patterns now
raises a deprecation warning and will be forbidden in Python 3.6.
(Contributed by Serhiy Storchaka in bpo-23622(7).)

The undocumented and unofficial `use_load_tests' default argument of the
*note unittest.TestLoader.loadTestsFromModule(): 789. method now is
deprecated and ignored.  (Contributed by Robert Collins and Barry A.
Warsaw in bpo-16662(8).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23671

   (2) https://bugs.python.org/issue1322

   (3) https://bugs.python.org/issue24248

   (4) https://bugs.python.org/issue20438

   (5) https://bugs.python.org/issue20438

   (6) https://bugs.python.org/issue22407

   (7) https://bugs.python.org/issue23622

   (8) https://bugs.python.org/issue16662


File: python.info,  Node: 移除<2>,  Next: 移植到Python 3 5,  Prev: 弃用<3>,  Up: Python 3 5 有什么新变化

1.4.10 移除
-----------

* Menu:

* API 与特性的移除: API 与特性的移除<4>.


File: python.info,  Node: API 与特性的移除<4>,  Up: 移除<2>

1.4.10.1 API 与特性的移除
.........................

The following obsolete and previously deprecated APIs and features have
been removed:

   * The ‘__version__’ attribute has been dropped from the email
     package.  The email code hasn’t been shipped separately from the
     stdlib for a long time, and the ‘__version__’ string was not
     updated in the last few releases.

   * The internal ‘Netrc’ class in the *note ftplib: 84. module was
     deprecated in 3.4, and has now been removed.  (Contributed by Matt
     Chaput in bpo-6623(1).)

   * The concept of ‘.pyo’ files has been removed.

   * The JoinableQueue class in the provisional *note asyncio: a. module
     was deprecated in 3.4.4 and is now removed.  (Contributed by A.
     Jesse Jiryu Davis in bpo-23464(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6623

   (2) https://bugs.python.org/issue23464


File: python.info,  Node: 移植到Python 3 5,  Next: Python 3 5 4 的显著变化,  Prev: 移除<2>,  Up: Python 3 5 有什么新变化

1.4.11 移植到Python 3.5
-----------------------

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

* Menu:

* Python 行为的改变: Python 行为的改变<2>.
* Python API 的变化: Python API 的变化<5>.
* C API 的变化: C API 的变化<4>.


File: python.info,  Node: Python 行为的改变<2>,  Next: Python API 的变化<5>,  Up: 移植到Python 3 5

1.4.11.1 Python 行为的改变
..........................

   * 由于一个疏忽，之前的 Python 版本会错误地接受以下语法:

          f(1 for x in [1], *args)
          f(1 for x in [1], **kwargs)

     Python 3.5 now correctly raises a *note SyntaxError: 460, as
     generator expressions must be put in parentheses if not a sole
     argument to a function.


File: python.info,  Node: Python API 的变化<5>,  Next: C API 的变化<4>,  Prev: Python 行为的改变<2>,  Up: 移植到Python 3 5

1.4.11.2 Python API 的变化
..........................

   * PEP 475(1): System calls are now retried when interrupted by a
     signal instead of raising *note InterruptedError: 662. if the
     Python signal handler does not raise an exception.

   * Before Python 3.5, a *note datetime.time: 4fb. object was
     considered to be false if it represented midnight in UTC. This
     behavior was considered obscure and error-prone and has been
     removed in Python 3.5.  See bpo-13936(2) for full details.

   * The ‘ssl.SSLSocket.send()’ method now raises either *note
     ssl.SSLWantReadError: 75f. or *note ssl.SSLWantWriteError: 760. on
     a non-blocking socket if the operation would block.  Previously, it
     would return ‘0’.  (Contributed by Nikolaus Rath in bpo-20951(3).)

   * The ‘__name__’ attribute of generators is now set from the function
     name, instead of being set from the code name.  Use
     ‘gen.gi_code.co_name’ to retrieve the code name.  Generators also
     have a new ‘__qualname__’ attribute, the qualified name, which is
     now used for the representation of a generator (‘repr(gen)’).
     (Contributed by Victor Stinner in bpo-21205(4).)

   * The deprecated "strict" mode and argument of *note HTMLParser: 7c8,
     ‘HTMLParser.error()’, and the ‘HTMLParserError’ exception have been
     removed.  (Contributed by Ezio Melotti in bpo-15114(5).)  The
     `convert_charrefs' argument of *note HTMLParser: 7c8. is now ‘True’
     by default.  (Contributed by Berker Peksag in bpo-21047(6).)

   * Although it is not formally part of the API, it is worth noting for
     porting purposes (ie: fixing tests) that error messages that were
     previously of the form "’sometype’ does not support the buffer
     protocol" are now of the form "a *note bytes-like object: 5f1. is
     required, not ’sometype’".  (Contributed by Ezio Melotti in
     bpo-16518(7).)

   * If the current directory is set to a directory that no longer
     exists then *note FileNotFoundError: 7c9. will no longer be raised
     and instead *note find_spec(): 7ca. will return ‘None’ `without'
     caching ‘None’ in *note sys.path_importer_cache: 4a5, which is
     different than the typical case (bpo-22834(8)).

   * HTTP status code and messages from *note http.client: 94. and *note
     http.server: 97. were refactored into a common *note HTTPStatus:
     6eb. enum.  The values in *note http.client: 94. and *note
     http.server: 97. remain available for backwards compatibility.
     (Contributed by Demian Brecht in bpo-21793(9).)

   * When an import loader defines
     ‘importlib.machinery.Loader.exec_module()’ it is now expected to
     also define ‘create_module()’ (raises a *note DeprecationWarning:
     279. now, will be an error in Python 3.6).  If the loader inherits
     from *note importlib.abc.Loader: 7cb. then there is nothing to do,
     else simply define ‘create_module()’ to return ‘None’.
     (Contributed by Brett Cannon in bpo-23014(10).)

   * The *note re.split(): 3d2. function always ignored empty pattern
     matches, so the ‘"x*"’ pattern worked the same as ‘"x+"’, and the
     ‘"\b"’ pattern never worked.  Now *note re.split(): 3d2. raises a
     warning if the pattern could match an empty string.  For
     compatibility, use patterns that never match an empty string (e.g.
     ‘"x+"’ instead of ‘"x*"’).  Patterns that could only match an empty
     string (such as ‘"\b"’) now raise an error.  (Contributed by Serhiy
     Storchaka in bpo-22818(11).)

   * The *note http.cookies.Morsel: 495. dict-like interface has been
     made self consistent: morsel comparison now takes the *note key:
     496. and *note value: 497. into account, *note copy(): 7cc. now
     results in a *note Morsel: 495. instance rather than a *note dict:
     1b9, and *note update(): 7cd. will now raise an exception if any of
     the keys in the update dictionary are invalid.  In addition, the
     undocumented `LegalChars' parameter of *note set(): 499. is
     deprecated and is now ignored.  (Contributed by Demian Brecht in
     bpo-2211(12).)

   * PEP 488(13) has removed ‘.pyo’ files from Python and introduced the
     optional ‘opt-’ tag in ‘.pyc’ file names.  The *note
     importlib.util.cache_from_source(): 560. has gained an
     `optimization' parameter to help control the ‘opt-’ tag.  Because
     of this, the `debug_override' parameter of the function is now
     deprecated.  ‘.pyo’ files are also no longer supported as a file
     argument to the Python interpreter and thus serve no purpose when
     distributed on their own (i.e.  sourceless code distribution).  Due
     to the fact that the magic number for bytecode has changed in
     Python 3.5, all old ‘.pyo’ files from previous versions of Python
     are invalid regardless of this PEP.

   * The *note socket: f0. module now exports the *note
     CAN_RAW_FD_FRAMES: 7ce. constant on linux 3.6 and greater.

   * The *note ssl.cert_time_to_seconds(): 761. function now interprets
     the input time as UTC and not as local time, per RFC 5280(14).
     Additionally, the return value is always an *note int: 185.
     (Contributed by Akira Li in bpo-19940(15).)

   * The ‘pygettext.py’ Tool now uses the standard +NNNN format for
     timezones in the POT-Creation-Date header.

   * The *note smtplib: ee. module now uses *note sys.stderr: 318.
     instead of the previous module-level ‘stderr’ variable for debug
     output.  If your (test) program depends on patching the
     module-level variable to capture the debug output, you will need to
     update it to capture sys.stderr instead.

   * The *note str.startswith(): 7cf. and *note str.endswith(): 7d0.
     methods no longer return ‘True’ when finding the empty string and
     the indexes are completely out of range.  (Contributed by Serhiy
     Storchaka in bpo-24284(16).)

   * The *note inspect.getdoc(): 1d7. function now returns documentation
     strings inherited from base classes.  Documentation strings no
     longer need to be duplicated if the inherited documentation is
     appropriate.  To suppress an inherited string, an empty string must
     be specified (or the documentation may be filled in).  This change
     affects the output of the *note pydoc: da. module and the *note
     help(): 57b. function.  (Contributed by Serhiy Storchaka in
     bpo-15582(17).)

   * Nested *note functools.partial(): 7d1. calls are now flattened.  If
     you were relying on the previous behavior, you can now either add
     an attribute to a *note functools.partial(): 7d1. object or you can
     create a subclass of *note functools.partial(): 7d1.  (Contributed
     by Alexander Belopolsky in bpo-7830(18).)

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475

   (2) https://bugs.python.org/issue13936

   (3) https://bugs.python.org/issue20951

   (4) https://bugs.python.org/issue21205

   (5) https://bugs.python.org/issue15114

   (6) https://bugs.python.org/issue21047

   (7) https://bugs.python.org/issue16518

   (8) https://bugs.python.org/issue22834

   (9) https://bugs.python.org/issue21793

   (10) https://bugs.python.org/issue23014

   (11) https://bugs.python.org/issue22818

   (12) https://bugs.python.org/issue2211

   (13) https://www.python.org/dev/peps/pep-0488

   (14) https://tools.ietf.org/html/rfc5280.html

   (15) https://bugs.python.org/issue19940

   (16) https://bugs.python.org/issue24284

   (17) https://bugs.python.org/issue15582

   (18) https://bugs.python.org/issue7830


File: python.info,  Node: C API 的变化<4>,  Prev: Python API 的变化<5>,  Up: 移植到Python 3 5

1.4.11.3 C API 的变化
.....................

   * The undocumented ‘format’ member of the (non-public)
     ‘PyMemoryViewObject’ structure has been removed.  All extensions
     relying on the relevant parts in ‘memoryobject.h’ must be rebuilt.

   * The ‘PyMemAllocator’ structure was renamed to *note
     PyMemAllocatorEx: 7d3. and a new ‘calloc’ field was added.

   * Removed non-documented macro ‘PyObject_REPR’ which leaked
     references.  Use format character ‘%R’ in *note
     PyUnicode_FromFormat(): 7d4.-like functions to format the *note
     repr(): 7d5. of the object.  (Contributed by Serhiy Storchaka in
     bpo-22453(1).)

   * Because the lack of the ‘__module__’ attribute breaks pickling and
     introspection, a deprecation warning is now raised for builtin
     types without the ‘__module__’ attribute.  This would be an
     AttributeError in the future.  (Contributed by Serhiy Storchaka in
     bpo-20204(2).)

   * As part of the PEP 492(3) implementation, the ‘tp_reserved’ slot of
     *note PyTypeObject: 2d7. was replaced with a ‘tp_as_async’ slot.
     Refer to *note 协程对象: 7d6. for new types, structures and
     functions.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22453

   (2) https://bugs.python.org/issue20204

   (3) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: Python 3 5 4 的显著变化,  Prev: 移植到Python 3 5,  Up: Python 3 5 有什么新变化

1.4.12 Python 3.5.4 的显著变化
------------------------------

* Menu:

* New make regen-all build target: New make regen-all build target<2>.
* Removal of make touch build target: Removal of make touch build target<2>.


File: python.info,  Node: New make regen-all build target<2>,  Next: Removal of make touch build target<2>,  Up: Python 3 5 4 的显著变化

1.4.12.1 New ‘make regen-all’ build target
..........................................

To simplify cross-compilation, and to ensure that CPython can reliably
be compiled without requiring an existing version of Python to already
be available, the autotools-based build system no longer attempts to
implicitly recompile generated files based on file modification times.

Instead, a new ‘make regen-all’ command has been added to force
regeneration of these files when desired (e.g.  after an initial version
of Python has already been built based on the pregenerated versions).

More selective regeneration targets are also defined - see
Makefile.pre.in(1) for details.

（由 Victor Stinner 在 bpo-23404(2) 中贡献。）

3.5.4 新版功能.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Makefile.pre.in

   (2) https://bugs.python.org/issue23404


File: python.info,  Node: Removal of make touch build target<2>,  Prev: New make regen-all build target<2>,  Up: Python 3 5 4 的显著变化

1.4.12.2 Removal of ‘make touch’ build target
.............................................

The ‘make touch’ build target previously used to request implicit
regeneration of generated files by updating their modification times has
been removed.

It has been replaced by the new ‘make regen-all’ target.

（由 Victor Stinner 在 bpo-23404(1) 中贡献。）

在 3.5.4 版更改.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23404


File: python.info,  Node: Python 3 4 有什么新变化,  Next: Python 3 3 有什么新变化,  Prev: Python 3 5 有什么新变化,  Up: Python的新变化

1.5 Python 3.4 有什么新变化
===========================


作者: R. David Murray <<rdmurray@bitdance.com>> (Editor)

This article explains the new features in Python 3.4, compared to 3.3.
Python 3.4 was released on March 16, 2014.  For full details, see the
changelog(1).

参见
....

PEP 429(2) – Python 3.4 发布计划

* Menu:

* 摘要 - 发布重点: 摘要 - 发布重点<5>.
* 新的特性: 新的特性<5>.
* 新增模块: 新增模块<5>.
* 改进的模块: 改进的模块<5>.
* CPython Implementation Changes::
* 弃用: 弃用<4>.
* 移除: 移除<3>.
* 移植到 Python 3.4: 移植到 Python 3 4.
* 3.4.3 的变化: 3 4 3 的变化.

   ---------- Footnotes ----------

   (1) https://docs.python.org/3.4/whatsnew/changelog.html

   (2) https://www.python.org/dev/peps/pep-0429


File: python.info,  Node: 摘要 - 发布重点<5>,  Next: 新的特性<5>,  Up: Python 3 4 有什么新变化

1.5.1 摘要 - 发布重点
---------------------

新的语法特性：

   * No new syntax features were added in Python 3.4.

其他的新特性

   * *note pip 能够随时可用: 7dd. ( PEP 453(1)).

   * *note Newly created file descriptors are non-inheritable: 7de. (
     PEP 446(2)).

   * command line option for *note isolated mode: 7df. (bpo-16499(3)).

   * *note improvements in the handling of codecs: 7e0. that are not
     text encodings (multiple issues).

   * *note A ModuleSpec Type: 7e1. for the Import System ( PEP 451(4)).
     (Affects importer authors.)

   * The *note marshal: b1. format has been made *note more compact and
     efficient: 7e2. (bpo-16475(5)).

新的库模块：

   * *note asyncio: a.: *note New provisional API for asynchronous IO:
     7e3. ( PEP 3156(6)).

   * *note ensurepip: 7a.: *note Bootstrapping the pip installer: 7e4. (
     PEP 453(7)).

   * *note enum: 7b.: *note Support for enumeration types: 7e5. ( PEP
     435(8)).

   * *note pathlib: c9.: *note Object-oriented filesystem paths: 7e6. (
     PEP 428(9)).

   * *note selectors: e7.: *note High-level and efficient I/O
     multiplexing: 7e7, built upon the *note select: e6. module
     primitives (part of PEP 3156(10)).

   * *note statistics: f6.: A basic *note numerically stable statistics
     library: 7e8. ( PEP 450(11)).

   * *note tracemalloc: 115.: *note Trace Python memory allocations:
     7e9. ( PEP 454(12)).

Significantly improved library modules:

   * *note Single-dispatch generic functions: 7ea. in *note functools:
     85. ( PEP 443(13)).

   * New *note pickle: cb. *note protocol 4: 7eb. ( PEP 3154(14)).

   * *note multiprocessing: b8. now has *note an option to avoid using
     os.fork on Unix: 7ec. (bpo-8713(15)).

   * *note email: 69. has a new submodule, *note contentmanager: 6b, and
     a new *note Message: 54a. subclass (‘EmailMessage’) that *note
     simplify MIME handling: 7ed. (bpo-18891(16)).

   * The *note inspect: a1. and *note pydoc: da. modules are now capable
     of correct introspection of a much wider variety of callable
     objects, which improves the output of the Python *note help(): 57b.
     system.

   * The *note ipaddress: a3. module API has been declared stable

安全改进：

   * *note Secure and interchangeable hash algorithm: 7ee. ( PEP
     456(17)).

   * *note Make newly created file descriptors non-inheritable: 7de. (
     PEP 446(18)) to avoid leaking file descriptors to child processes.

   * New command line option for *note isolated mode: 7df,
     (bpo-16499(19)).

   * *note multiprocessing: b8. now has *note an option to avoid using
     os.fork on Unix: 7ec.  `spawn' and `forkserver' are more secure
     because they avoid sharing data with child processes.

   * *note multiprocessing: b8. child processes on Windows no longer
     inherit all of the parent’s inheritable handles, only the necessary
     ones.

   * A new *note hashlib.pbkdf2_hmac(): 7ef. function provides the
     PKCS#5 password-based key derivation function 2(20).

   * *note TLSv1.1 and TLSv1.2 support: 7f0. for *note ssl: f4.

   * *note Retrieving certificates from the Windows system cert store
     support: 7f1. for *note ssl: f4.

   * *note Server-side SNI (Server Name Indication) support: 7f2. for
     *note ssl: f4.

   * The *note ssl.SSLContext: 3ec. class has a *note lot of
     improvements: 7f3.

   * All modules in the standard library that support SSL now support
     server certificate verification, including hostname matching (*note
     ssl.match_hostname(): 3e4.) and CRLs (Certificate Revocation lists,
     see *note ssl.SSLContext.load_verify_locations(): 7f4.).

CPython 实现的改进：

   * *note Safe object finalization: 7f5. ( PEP 442(21)).

   * Leveraging PEP 442(22), in most cases *note module globals are no
     longer set to None during finalization: 7f5. (bpo-18214(23)).

   * *note Configurable memory allocators: 7f6. ( PEP 445(24)).

   * *note Argument Clinic: 7f7. ( PEP 436(25)).

Please read on for a comprehensive list of user-facing changes,
including many other smaller improvements, CPython optimizations,
deprecations, and potential porting issues.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0453

   (2) https://www.python.org/dev/peps/pep-0446

   (3) https://bugs.python.org/issue16499

   (4) https://www.python.org/dev/peps/pep-0451

   (5) https://bugs.python.org/issue16475

   (6) https://www.python.org/dev/peps/pep-3156

   (7) https://www.python.org/dev/peps/pep-0453

   (8) https://www.python.org/dev/peps/pep-0435

   (9) https://www.python.org/dev/peps/pep-0428

   (10) https://www.python.org/dev/peps/pep-3156

   (11) https://www.python.org/dev/peps/pep-0450

   (12) https://www.python.org/dev/peps/pep-0454

   (13) https://www.python.org/dev/peps/pep-0443

   (14) https://www.python.org/dev/peps/pep-3154

   (15) https://bugs.python.org/issue8713

   (16) https://bugs.python.org/issue18891

   (17) https://www.python.org/dev/peps/pep-0456

   (18) https://www.python.org/dev/peps/pep-0446

   (19) https://bugs.python.org/issue16499

   (20) https://en.wikipedia.org/wiki/PBKDF2

   (21) https://www.python.org/dev/peps/pep-0442

   (22) https://www.python.org/dev/peps/pep-0442

   (23) https://bugs.python.org/issue18214

   (24) https://www.python.org/dev/peps/pep-0445

   (25) https://www.python.org/dev/peps/pep-0436


File: python.info,  Node: 新的特性<5>,  Next: 新增模块<5>,  Prev: 摘要 - 发布重点<5>,  Up: Python 3 4 有什么新变化

1.5.2 新的特性
--------------

* Menu:

* PEP 453; Explicit Bootstrapping of PIP in Python Installations: PEP 453 Explicit Bootstrapping of PIP in Python Installations.
* PEP 446; Newly Created File Descriptors Are Non-Inheritable: PEP 446 Newly Created File Descriptors Are Non-Inheritable.
* Improvements to Codec Handling::
* PEP 451; A ModuleSpec Type for the Import System: PEP 451 A ModuleSpec Type for the Import System.
* 其他语言特性修改: 其他语言特性修改<5>.


File: python.info,  Node: PEP 453 Explicit Bootstrapping of PIP in Python Installations,  Next: PEP 446 Newly Created File Descriptors Are Non-Inheritable,  Up: 新的特性<5>

1.5.2.1 PEP 453: Explicit Bootstrapping of PIP in Python Installations
......................................................................

* Menu:

* Bootstrapping pip By Default::
* 文档更改::


File: python.info,  Node: Bootstrapping pip By Default,  Next: 文档更改,  Up: PEP 453 Explicit Bootstrapping of PIP in Python Installations

1.5.2.2 Bootstrapping pip By Default
....................................

The new *note ensurepip: 7a. module (defined in PEP 453(1)) provides a
standard cross-platform mechanism to bootstrap the pip installer into
Python installations and virtual environments.  The version of ‘pip’
included with Python 3.4.0 is ‘pip’ 1.5.4, and future 3.4.x maintenance
releases will update the bundled version to the latest version of ‘pip’
that is available at the time of creating the release candidate.

By default, the commands ‘pipX’ and ‘pipX.Y’ will be installed on all
platforms (where X.Y stands for the version of the Python installation),
along with the ‘pip’ Python package and its dependencies.  On Windows
and in virtual environments on all platforms, the unversioned ‘pip’
command will also be installed.  On other platforms, the system wide
unversioned ‘pip’ command typically refers to the separately installed
Python 2 version.

The ‘pyvenv’ command line utility and the *note venv: 126. module make
use of the *note ensurepip: 7a. module to make ‘pip’ readily available
in virtual environments.  When using the command line utility, ‘pip’ is
installed by default, while when using the *note venv: 126. module *note
API: 7fb. installation of ‘pip’ must be requested explicitly.

For CPython *note source builds on POSIX systems: 7fc, the ‘make
install’ and ‘make altinstall’ commands bootstrap ‘pip’ by default.
This behaviour can be controlled through configure options, and
overridden through Makefile options.

On Windows and Mac OS X, the CPython installers now default to
installing ‘pip’ along with CPython itself (users may opt out of
installing it during the installation process).  Window users will need
to opt in to the automatic ‘PATH’ modifications to have ‘pip’ available
from the command line by default, otherwise it can still be accessed
through the Python launcher for Windows as ‘py -m pip’.

As discussed in the PEP(2), platform packagers may choose not to install
these commands by default, as long as, when invoked, they provide clear
and simple directions on how to install them on that platform (usually
using the system package manager).

     注解: To avoid conflicts between parallel Python 2 and Python 3
     installations, only the versioned ‘pip3’ and ‘pip3.4’ commands are
     bootstrapped by default when ‘ensurepip’ is invoked directly - the
     ‘--default-pip’ option is needed to also request the unversioned
     ‘pip’ command.  ‘pyvenv’ and the Windows installer ensure that the
     unqualified ‘pip’ command is made available in those environments,
     and ‘pip’ can always be invoked via the ‘-m’ switch rather than
     directly to avoid ambiguity on systems with multiple Python
     installations.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0453

   (2) 
https://www.python.org/dev/peps/pep-0453/#recommendations-for-downstream-distributors


File: python.info,  Node: 文档更改,  Prev: Bootstrapping pip By Default,  Up: PEP 453 Explicit Bootstrapping of PIP in Python Installations

1.5.2.3 文档更改
................

As part of this change, the *note 安装 Python 模块: 7fe. and *note 分发
Python 模块: 7ff. sections of the documentation have been completely
redesigned as short getting started and FAQ documents.  Most packaging
documentation has now been moved out to the Python Packaging Authority
maintained Python Packaging User Guide(1) and the documentation of the
individual projects.

However, as this migration is currently still incomplete, the legacy
versions of those guides remaining available as *note
安装Python模块（旧版）: 800. and *note 分发 Python 模块（遗留版本）:
801.

参见
....

PEP 453(2) – Python安装中pip的显式引导

     PEP 由Donald Stufft 和 Nick Coghlan 撰写，由 Donald Stufft，Nick
     Coghlan，Martin von Löwis 和 Ned Deily 实现。

   ---------- Footnotes ----------

   (1) https://packaging.python.org

   (2) https://www.python.org/dev/peps/pep-0453


File: python.info,  Node: PEP 446 Newly Created File Descriptors Are Non-Inheritable,  Next: Improvements to Codec Handling,  Prev: PEP 453 Explicit Bootstrapping of PIP in Python Installations,  Up: 新的特性<5>

1.5.2.4 PEP 446: Newly Created File Descriptors Are Non-Inheritable
...................................................................

PEP 446(1) makes newly created file descriptors *note non-inheritable:
803.  In general, this is the behavior an application will want: when
launching a new process, having currently open files also open in the
new process can lead to all sorts of hard to find bugs, and potentially
to security issues.

However, there are occasions when inheritance is desired.  To support
these cases, the following new functions and methods are available:

   * *note os.get_inheritable(): 804, *note os.set_inheritable(): 805.

   * *note os.get_handle_inheritable(): 806, *note
     os.set_handle_inheritable(): 807.

   * *note socket.socket.get_inheritable(): 808, *note
     socket.socket.set_inheritable(): 809.

参见
....

PEP 446(2) – Make newly created file descriptors non-inheritable

     PEP 由 Victor Stinner 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0446

   (2) https://www.python.org/dev/peps/pep-0446


File: python.info,  Node: Improvements to Codec Handling,  Next: PEP 451 A ModuleSpec Type for the Import System,  Prev: PEP 446 Newly Created File Descriptors Are Non-Inheritable,  Up: 新的特性<5>

1.5.2.5 Improvements to Codec Handling
......................................

Since it was first introduced, the *note codecs: 1c. module has always
been intended to operate as a type-neutral dynamic encoding and decoding
system.  However, its close coupling with the Python text model,
especially the type restricted convenience methods on the builtin *note
str: 339, *note bytes: 33a. and *note bytearray: 33b. types, has
historically obscured that fact.

As a key step in clarifying the situation, the *note codecs.encode():
80b. and *note codecs.decode(): 80c. convenience functions are now
properly documented in Python 2.7, 3.3 and 3.4.  These functions have
existed in the *note codecs: 1c. module (and have been covered by the
regression test suite) since Python 2.4, but were previously only
discoverable through runtime introspection.

Unlike the convenience methods on *note str: 339, *note bytes: 33a. and
*note bytearray: 33b, the *note codecs: 1c. convenience functions
support arbitrary codecs in both Python 2 and Python 3, rather than
being limited to Unicode text encodings (in Python 3) or ‘basestring’
<-> ‘basestring’ conversions (in Python 2).

In Python 3.4, the interpreter is able to identify the known non-text
encodings provided in the standard library and direct users towards
these general purpose convenience functions when appropriate:

     >>> b"abcdef".decode("hex")
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs

     >>> "hello".encode("rot13")
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     LookupError: 'rot13' is not a text encoding; use codecs.encode() to handle arbitrary codecs

     >>> open("foo.txt", encoding="hex")
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     LookupError: 'hex' is not a text encoding; use codecs.open() to handle arbitrary codecs

In a related change, whenever it is feasible without breaking backwards
compatibility, exceptions raised during encoding and decoding operations
are wrapped in a chained exception of the same type that mentions the
name of the codec responsible for producing the error:

     >>> import codecs

     >>> codecs.decode(b"abcdefgh", "hex")
     Traceback (most recent call last):
       File "/usr/lib/python3.4/encodings/hex_codec.py", line 20, in hex_decode
         return (binascii.a2b_hex(input), len(input))
     binascii.Error: Non-hexadecimal digit found

     The above exception was the direct cause of the following exception:

     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     binascii.Error: decoding with 'hex' codec failed (Error: Non-hexadecimal digit found)

     >>> codecs.encode("hello", "bz2")
     Traceback (most recent call last):
       File "/usr/lib/python3.4/encodings/bz2_codec.py", line 17, in bz2_encode
         return (bz2.compress(input), len(input))
       File "/usr/lib/python3.4/bz2.py", line 498, in compress
         return comp.compress(data) + comp.flush()
     TypeError: 'str' does not support the buffer interface

     The above exception was the direct cause of the following exception:

     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: encoding with 'bz2' codec failed (TypeError: 'str' does not support the buffer interface)

Finally, as the examples above show, these improvements have permitted
the restoration of the convenience aliases for the non-Unicode codecs
that were themselves restored in Python 3.2.  This means that encoding
binary data to and from its hexadecimal representation (for example) can
now be written as:

     >>> from codecs import encode, decode
     >>> encode(b"hello", "hex")
     b'68656c6c6f'
     >>> decode(b"68656c6c6f", "hex")
     b'hello'

The binary and text transforms provided in the standard library are
detailed in *note 二进制转换: 80d. and *note 文字转换: 80e.

(Contributed by Nick Coghlan in bpo-7475(1), bpo-17827(2), bpo-17828(3)
and bpo-19619(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7475

   (2) https://bugs.python.org/issue17827

   (3) https://bugs.python.org/issue17828

   (4) https://bugs.python.org/issue19619


File: python.info,  Node: PEP 451 A ModuleSpec Type for the Import System,  Next: 其他语言特性修改<5>,  Prev: Improvements to Codec Handling,  Up: 新的特性<5>

1.5.2.6 PEP 451: A ModuleSpec Type for the Import System
........................................................

PEP 451(1) provides an encapsulation of the information about a module
that the import machinery will use to load it (that is, a module
specification).  This helps simplify both the import implementation and
several import-related APIs.  The change is also a stepping stone for
several future import-related improvements(2).

The public-facing changes from the PEP are entirely backward-compatible.
Furthermore, they should be transparent to everyone but importer
authors.  Key finder and loader methods have been deprecated, but they
will continue working.  New importers should use the new methods
described in the PEP. Existing importers should be updated to implement
the new methods.  See the *note 弃用: 810. section for a list of methods
that should be replaced and their replacements.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0451

   (2) 
https://mail.python.org/pipermail/python-dev/2013-November/130111.html


File: python.info,  Node: 其他语言特性修改<5>,  Prev: PEP 451 A ModuleSpec Type for the Import System,  Up: 新的特性<5>

1.5.2.7 其他语言特性修改
........................

对Python 语言核心进行的小改动：

   * Unicode database updated to UCD version 6.3.

   * *note min(): 812. and *note max(): 813. now accept a `default'
     keyword-only argument that can be used to specify the value they
     return if the iterable they are evaluating has no elements.
     (Contributed by Julian Berman in bpo-18111(1).)

   * Module objects are now *note weakref: 129.’able.

   * Module ‘__file__’ attributes (and related values) should now always
     contain absolute paths by default, with the sole exception of
     ‘__main__.__file__’ when a script has been executed directly using
     a relative path.  (Contributed by Brett Cannon in bpo-18416(2).)

   * All the UTF-* codecs (except UTF-7) now reject surrogates during
     both encoding and decoding unless the ‘surrogatepass’ error handler
     is used, with the exception of the UTF-16 decoder (which accepts
     valid surrogate pairs) and the UTF-16 encoder (which produces them
     while encoding non-BMP characters).  (Contributed by Victor
     Stinner, Kang-Hao (Kenny) Lu and Serhiy Storchaka in bpo-12892(3).)

   * New German EBCDIC *note codec: 698. ‘cp273’.  (Contributed by
     Michael Bierenfeld and Andrew Kuchling in bpo-1097797(4).)

   * New Ukrainian *note codec: 698. ‘cp1125’.  (Contributed by Serhiy
     Storchaka in bpo-19668(5).)

   * *note bytes: 33a.join() and *note bytearray: 33b.join() now accept
     arbitrary buffer objects as arguments.  (Contributed by Antoine
     Pitrou in bpo-15958(6).)

   * The *note int: 185. constructor now accepts any object that has an
     ‘__index__’ method for its `base' argument.  (Contributed by Mark
     Dickinson in bpo-16772(7).)

   * Frame objects now have a *note clear(): 814. method that clears all
     references to local variables from the frame.  (Contributed by
     Antoine Pitrou in bpo-17934(8).)

   * *note memoryview: 25d. is now registered as a *note Sequence: 1f,
     and supports the *note reversed(): 18f. builtin.  (Contributed by
     Nick Coghlan and Claudiu Popa in bpo-18690(9) and bpo-19078(10).)

   * Signatures reported by *note help(): 57b. have been modified and
     improved in several cases as a result of the introduction of
     Argument Clinic and other changes to the *note inspect: a1. and
     *note pydoc: da. modules.

   * *note __length_hint__(): 815. is now part of the formal language
     specification (see PEP 424(11)).  (Contributed by Armin Ronacher in
     bpo-16148(12).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18111

   (2) https://bugs.python.org/issue18416

   (3) https://bugs.python.org/issue12892

   (4) https://bugs.python.org/issue1097797

   (5) https://bugs.python.org/issue19668

   (6) https://bugs.python.org/issue15958

   (7) https://bugs.python.org/issue16772

   (8) https://bugs.python.org/issue17934

   (9) https://bugs.python.org/issue18690

   (10) https://bugs.python.org/issue19078

   (11) https://www.python.org/dev/peps/pep-0424

   (12) https://bugs.python.org/issue16148


File: python.info,  Node: 新增模块<5>,  Next: 改进的模块<5>,  Prev: 新的特性<5>,  Up: Python 3 4 有什么新变化

1.5.3 新增模块
--------------

* Menu:

* asyncio: asyncio<6>.
* ensurepip::
* enum: enum<5>.
* pathlib: pathlib<5>.
* selectors: selectors<2>.
* statistics: statistics<3>.
* tracemalloc: tracemalloc<3>.


File: python.info,  Node: asyncio<6>,  Next: ensurepip,  Up: 新增模块<5>

1.5.3.1 asyncio
...............

The new *note asyncio: a. module (defined in PEP 3156(1)) provides a
standard pluggable event loop model for Python, providing solid
asynchronous IO support in the standard library, and making it easier
for other event loop implementations to interoperate with the standard
library and each other.

For Python 3.4, this module is considered a *note provisional API: 351.

参见
....

PEP 3156(2) – Asynchronous IO Support Rebooted: the "asyncio" Module

     PEP 由 Guido van Rossum 领导编写和实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3156

   (2) https://www.python.org/dev/peps/pep-3156


File: python.info,  Node: ensurepip,  Next: enum<5>,  Prev: asyncio<6>,  Up: 新增模块<5>

1.5.3.2 ensurepip
.................

The new *note ensurepip: 7a. module is the primary infrastructure for
the PEP 453(1) implementation.  In the normal course of events end users
will not need to interact with this module, but it can be used to
manually bootstrap ‘pip’ if the automated bootstrapping into an
installation or virtual environment was declined.

*note ensurepip: 7a. includes a bundled copy of ‘pip’, up-to-date as of
the first release candidate of the release of CPython with which it
ships (this applies to both maintenance releases and feature releases).
‘ensurepip’ does not access the internet.  If the installation has
Internet access, after ‘ensurepip’ is run the bundled ‘pip’ can be used
to upgrade ‘pip’ to a more recent release than the bundled one.  (Note
that such an upgraded version of ‘pip’ is considered to be a separately
installed package and will not be removed if Python is uninstalled.)

The module is named `ensure'pip because if called when ‘pip’ is already
installed, it does nothing.  It also has an ‘--upgrade’ option that will
cause it to install the bundled copy of ‘pip’ if the existing installed
version of ‘pip’ is older than the bundled copy.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0453


File: python.info,  Node: enum<5>,  Next: pathlib<5>,  Prev: ensurepip,  Up: 新增模块<5>

1.5.3.3 enum
............

The new *note enum: 7b. module (defined in PEP 435(1)) provides a
standard implementation of enumeration types, allowing other modules
(such as *note socket: f0.) to provide more informative error messages
and better debugging support by replacing opaque integer constants with
backwards compatible enumeration values.

参见
....

PEP 435(2) – Adding an Enum type to the Python standard library

     PEP 由 Barry Warsaw，Eli Bendersky 和 Ethan Furman 撰写 ，由 Ethan
     Furman 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0435

   (2) https://www.python.org/dev/peps/pep-0435


File: python.info,  Node: pathlib<5>,  Next: selectors<2>,  Prev: enum<5>,  Up: 新增模块<5>

1.5.3.4 pathlib
...............

The new *note pathlib: c9. module offers classes representing filesystem
paths with semantics appropriate for different operating systems.  Path
classes are divided between `pure paths', which provide purely
computational operations without I/O, and `concrete paths', which
inherit from pure paths but also provide I/O operations.

For Python 3.4, this module is considered a *note provisional API: 351.

参见
....

PEP 428(1) – The pathlib module – object-oriented filesystem paths

     PEP 由 Antoine Pitrou 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0428


File: python.info,  Node: selectors<2>,  Next: statistics<3>,  Prev: pathlib<5>,  Up: 新增模块<5>

1.5.3.5 selectors
.................

The new *note selectors: e7. module (created as part of implementing PEP
3156(1)) allows high-level and efficient I/O multiplexing, built upon
the *note select: e6. module primitives.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3156


File: python.info,  Node: statistics<3>,  Next: tracemalloc<3>,  Prev: selectors<2>,  Up: 新增模块<5>

1.5.3.6 statistics
..................

The new *note statistics: f6. module (defined in PEP 450(1)) offers some
core statistics functionality directly in the standard library.  This
module supports calculation of the mean, median, mode, variance and
standard deviation of a data series.

参见
....

PEP 450(2) – Adding A Statistics Module To The Standard Library

     PEP 由 Steven D’Aprano 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0450

   (2) https://www.python.org/dev/peps/pep-0450


File: python.info,  Node: tracemalloc<3>,  Prev: statistics<3>,  Up: 新增模块<5>

1.5.3.7 tracemalloc
...................

The new *note tracemalloc: 115. module (defined in PEP 454(1)) is a
debug tool to trace memory blocks allocated by Python.  It provides the
following information:

   * Trace where an object was allocated

   * Statistics on allocated memory blocks per filename and per line
     number: total size, number and average size of allocated memory
     blocks

   * Compute the differences between two snapshots to detect memory
     leaks

参见
....

PEP 454(2) – Add a new tracemalloc module to trace Python memory allocations

     PEP 由 Victor Stinner 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0454

   (2) https://www.python.org/dev/peps/pep-0454


File: python.info,  Node: 改进的模块<5>,  Next: CPython Implementation Changes,  Prev: 新增模块<5>,  Up: Python 3 4 有什么新变化

1.5.4 改进的模块
----------------

* Menu:

* abc::
* aifc: aifc<2>.
* argparse: argparse<3>.
* audioop::
* base64::
* collections: collections<6>.
* colorsys::
* contextlib: contextlib<4>.
* dbm: dbm<5>.
* dis: dis<2>.
* doctest: doctest<2>.
* email: email<3>.
* filecmp::
* functools: functools<4>.
* gc: gc<3>.
* glob: glob<2>.
* hashlib: hashlib<2>.
* hmac: hmac<2>.
* html::
* http: http<2>.
* idlelib 与 IDLE: idlelib 与 IDLE<4>.
* importlib: importlib<6>.
* inspect: inspect<4>.
* ipaddress: ipaddress<3>.
* logging: logging<5>.
* marshal::
* mmap: mmap<2>.
* multiprocessing: multiprocessing<5>.
* operator: operator<2>.
* os: os<6>.
* pdb: pdb<3>.
* pickle: pickle<4>.
* plistlib: plistlib<2>.
* poplib: poplib<2>.
* pprint: pprint<2>.
* pty::
* pydoc: pydoc<3>.
* re: re<5>.
* resource::
* select::
* shelve::
* shutil: shutil<3>.
* smtpd: smtpd<2>.
* smtplib: smtplib<2>.
* socket: socket<6>.
* sqlite3: sqlite3<4>.
* ssl: ssl<7>.
* stat::
* struct: struct<2>.
* subprocess: subprocess<4>.
* sunau: sunau<2>.
* sys: sys<6>.
* tarfile: tarfile<3>.
* textwrap::
* threading: threading<4>.
* 回溯: 回溯<3>.
* types: types<3>.
* urllib: urllib<2>.
* unittest: unittest<4>.
* venv: venv<4>.
* wave: wave<2>.
* weakref: weakref<2>.
* xml.etree: xml etree<2>.
* zipfile: zipfile<4>.


File: python.info,  Node: abc,  Next: aifc<2>,  Up: 改进的模块<5>

1.5.4.1 abc
...........

New function *note abc.get_cache_token(): 820. can be used to know when
to invalidate caches that are affected by changes in the object graph.
(Contributed by Łukasz Langa in bpo-16832(1).)

New class *note ABC: 821. has *note ABCMeta: 822. as its meta class.
Using ‘ABC’ as a base class has essentially the same effect as
specifying ‘metaclass=abc.ABCMeta’, but is simpler to type and easier to
read.  (Contributed by Bruno Dupuis in bpo-16049(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16832

   (2) https://bugs.python.org/issue16049


File: python.info,  Node: aifc<2>,  Next: argparse<3>,  Prev: abc,  Up: 改进的模块<5>

1.5.4.2 aifc
............

The *note getparams(): 824. method now returns a namedtuple rather than
a plain tuple.  (Contributed by Claudiu Popa in bpo-17818(1).)

*note aifc.open(): 463. now supports the context management protocol:
when used in a *note with: 6f2. block, the *note close(): 825. method of
the returned object will be called automatically at the end of the
block.  (Contributed by Serhiy Storchacha in bpo-16486(2).)

The *note writeframesraw(): 826. and *note writeframes(): 827. methods
now accept any *note bytes-like object: 5f1.  (Contributed by Serhiy
Storchaka in bpo-8311(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17818

   (2) https://bugs.python.org/issue16486

   (3) https://bugs.python.org/issue8311


File: python.info,  Node: argparse<3>,  Next: audioop,  Prev: aifc<2>,  Up: 改进的模块<5>

1.5.4.3 argparse
................

The *note FileType: 829. class now accepts `encoding' and `errors'
arguments, which are passed through to *note open(): 4f8.  (Contributed
by Lucas Maystre in bpo-11175(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11175


File: python.info,  Node: audioop,  Next: base64,  Prev: argparse<3>,  Up: 改进的模块<5>

1.5.4.4 audioop
...............

*note audioop: d. now supports 24-bit samples.  (Contributed by Serhiy
Storchaka in bpo-12866(1).)

New *note byteswap(): 82b. function converts big-endian samples to
little-endian and vice versa.  (Contributed by Serhiy Storchaka in
bpo-19641(2).)

All *note audioop: d. functions now accept any *note bytes-like object:
5f1.  Strings are not accepted: they didn’t work before, now they raise
an error right away.  (Contributed by Serhiy Storchaka in bpo-16685(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12866

   (2) https://bugs.python.org/issue19641

   (3) https://bugs.python.org/issue16685


File: python.info,  Node: base64,  Next: collections<6>,  Prev: audioop,  Up: 改进的模块<5>

1.5.4.5 base64
..............

The encoding and decoding functions in *note base64: e. now accept any
*note bytes-like object: 5f1. in cases where it previously required a
*note bytes: 33a. or *note bytearray: 33b. instance.  (Contributed by
Nick Coghlan in bpo-17839(1).)

New functions *note a85encode(): 82d, *note a85decode(): 82e, *note
b85encode(): 82f, and *note b85decode(): 830. provide the ability to
encode and decode binary data from and to ‘Ascii85’ and the
git/mercurial ‘Base85’ formats, respectively.  The ‘a85’ functions have
options that can be used to make them compatible with the variants of
the ‘Ascii85’ encoding, including the Adobe variant.  (Contributed by
Martin Morrison, the Mercurial project, Serhiy Storchaka, and Antoine
Pitrou in bpo-17618(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17839

   (2) https://bugs.python.org/issue17618


File: python.info,  Node: collections<6>,  Next: colorsys,  Prev: base64,  Up: 改进的模块<5>

1.5.4.6 collections
...................

The *note ChainMap.new_child(): 832. method now accepts an `m' argument
specifying the child map to add to the chain.  This allows an existing
mapping and/or a custom mapping type to be used for the child.
(Contributed by Vinay Sajip in bpo-16613(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16613


File: python.info,  Node: colorsys,  Next: contextlib<4>,  Prev: collections<6>,  Up: 改进的模块<5>

1.5.4.7 colorsys
................

The number of digits in the coefficients for the RGB — YIQ conversions
have been expanded so that they match the FCC NTSC versions.  The change
in results should be less than 1% and may better match results found
elsewhere.  (Contributed by Brian Landers and Serhiy Storchaka in
bpo-14323(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14323


File: python.info,  Node: contextlib<4>,  Next: dbm<5>,  Prev: colorsys,  Up: 改进的模块<5>

1.5.4.8 contextlib
..................

The new *note contextlib.suppress: 835. context manager helps to clarify
the intent of code that deliberately suppresses exceptions from a single
statement.  (Contributed by Raymond Hettinger in bpo-15806(1) and Zero
Piraeus in bpo-19266(2).)

The new *note contextlib.redirect_stdout(): 6cb. context manager makes
it easier for utility scripts to handle inflexible APIs that write their
output to *note sys.stdout: 317. and don’t provide any options to
redirect it.  Using the context manager, the *note sys.stdout: 317.
output can be redirected to any other stream or, in conjunction with
*note io.StringIO: 836, to a string.  The latter can be especially
useful, for example, to capture output from a function that was written
to implement a command line interface.  It is recommended only for
utility scripts because it affects the global state of *note sys.stdout:
317.  (Contributed by Raymond Hettinger in bpo-15805(3).)

The *note contextlib: 24. documentation has also been updated to include
a *note discussion: 837. of the differences between single use, reusable
and reentrant context managers.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15806

   (2) https://bugs.python.org/issue19266

   (3) https://bugs.python.org/issue15805


File: python.info,  Node: dbm<5>,  Next: dis<2>,  Prev: contextlib<4>,  Up: 改进的模块<5>

1.5.4.9 dbm
...........

*note dbm.open(): 839. objects now support the context management
protocol.  When used in a *note with: 6f2. statement, the ‘close’ method
of the database object will be called automatically at the end of the
block.  (Contributed by Claudiu Popa and Nick Coghlan in bpo-19282(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19282


File: python.info,  Node: dis<2>,  Next: doctest<2>,  Prev: dbm<5>,  Up: 改进的模块<5>

1.5.4.10 dis
............

Functions *note show_code(): 83b, *note dis(): 38c, *note distb(): 83c,
and *note disassemble(): 83d. now accept a keyword-only `file' argument
that controls where they write their output.

The *note dis: 38. module is now built around an *note Instruction: 83e.
class that provides object oriented access to the details of each
individual bytecode operation.

A new method, *note get_instructions(): 83f, provides an iterator that
emits the Instruction stream for a given piece of Python code.  Thus it
is now possible to write a program that inspects and manipulates a
bytecode object in ways different from those provided by the *note dis:
38. module itself.  For example:

     >>> import dis
     >>> for instr in dis.get_instructions(lambda x: x + 1):
     ...     print(instr.opname)
     LOAD_FAST
     LOAD_CONST
     BINARY_ADD
     RETURN_VALUE

The various display tools in the *note dis: 38. module have been
rewritten to use these new components.

In addition, a new application-friendly class *note Bytecode: 840.
provides an object-oriented API for inspecting bytecode in both in
human-readable form and for iterating over instructions.  The *note
Bytecode: 840. constructor takes the same arguments that
‘get_instruction()’ does (plus an optional `current_offset'), and the
resulting object can be iterated to produce *note Instruction: 83e.
objects.  But it also has a *note dis: 841. method, equivalent to
calling *note dis: 38c. on the constructor argument, but returned as a
multi-line string:

     >>> bytecode = dis.Bytecode(lambda x: x + 1, current_offset=3)
     >>> for instr in bytecode:
     ...     print('{} ({})'.format(instr.opname, instr.opcode))
     LOAD_FAST (124)
     LOAD_CONST (100)
     BINARY_ADD (23)
     RETURN_VALUE (83)
     >>> bytecode.dis().splitlines()
     ['  1           0 LOAD_FAST                0 (x)',
      '      -->     3 LOAD_CONST               1 (1)',
      '              6 BINARY_ADD',
      '              7 RETURN_VALUE']

*note Bytecode: 840. also has a class method, *note from_traceback():
842, that provides the ability to manipulate a traceback (that is,
‘print(Bytecode.from_traceback(tb).dis())’ is equivalent to
‘distb(tb)’).

(Contributed by Nick Coghlan, Ryan Kelly and Thomas Kluyver in
bpo-11816(1) and Claudiu Popa in bpo-17916(2).)

New function *note stack_effect(): 843. computes the effect on the
Python stack of a given opcode and argument, information that is not
otherwise available.  (Contributed by Larry Hastings in bpo-19722(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11816

   (2) https://bugs.python.org/issue17916

   (3) https://bugs.python.org/issue19722


File: python.info,  Node: doctest<2>,  Next: email<3>,  Prev: dis<2>,  Up: 改进的模块<5>

1.5.4.11 doctest
................

A new *note option flag: 845, *note FAIL_FAST: 846, halts test running
as soon as the first failure is detected.  (Contributed by R. David
Murray and Daniel Urban in bpo-16522(1).)

The *note doctest: 67. command line interface now uses *note argparse:
6, and has two new options, ‘-o’ and ‘-f’.  ‘-o’ allows *note doctest
options: 845. to be specified on the command line, and ‘-f’ is a
shorthand for ‘-o FAIL_FAST’ (to parallel the similar option supported
by the *note unittest: 11c. CLI). (Contributed by R. David Murray in
bpo-11390(2).)

*note doctest: 67. will now find doctests in extension module ‘__doc__’
strings.  (Contributed by Zachary Ware in bpo-3158(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16522

   (2) https://bugs.python.org/issue11390

   (3) https://bugs.python.org/issue3158


File: python.info,  Node: email<3>,  Next: filecmp,  Prev: doctest<2>,  Up: 改进的模块<5>

1.5.4.12 email
..............

*note as_string(): 848. now accepts a `policy' argument to override the
default policy of the message when generating a string representation of
it.  This means that ‘as_string’ can now be used in more circumstances,
instead of having to create and use a *note generator: 6e. in order to
pass formatting parameters to its ‘flatten’ method.  (Contributed by R.
David Murray in bpo-18600(1).)

New method *note as_bytes(): 849. added to produce a bytes
representation of the message in a fashion similar to how ‘as_string’
produces a string representation.  It does not accept the `maxheaderlen'
argument, but does accept the `unixfrom' and `policy' arguments.  The
*note Message: 54a. *note __bytes__(): 84a. method calls it, meaning
that ‘bytes(mymsg)’ will now produce the intuitive result: a bytes
object containing the fully formatted message.  (Contributed by R. David
Murray in bpo-18600(2).)

The *note Message.set_param(): 84b. message now accepts a `replace'
keyword argument.  When specified, the associated header will be updated
without changing its location in the list of headers.  For backward
compatibility, the default is ‘False’.  (Contributed by R. David Murray
in bpo-18891(3).)  A pair of new subclasses of *note Message: 54a. have
been added (*note EmailMessage: 54b. and *note MIMEPart: 84c.), along
with a new sub-module, *note contentmanager: 6b. and a new *note policy:
75. attribute *note content_manager: 84d.  All documentation is
currently in the new module, which is being added as part of email’s new
*note provisional API: 351.  These classes provide a number of new
methods that make extracting content from and inserting content into
email messages much easier.  For details, see the *note contentmanager:
6b. documentation and the *note email; 示例: 84e.  These API additions
complete the bulk of the work that was planned as part of the email6
project.  The currently provisional API is scheduled to become final in
Python 3.5 (possibly with a few minor additions in the area of error
handling).  (Contributed by R. David Murray in bpo-18891(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18600

   (2) https://bugs.python.org/issue18600

   (3) https://bugs.python.org/issue18891

   (4) https://bugs.python.org/issue18891


File: python.info,  Node: filecmp,  Next: functools<4>,  Prev: email<3>,  Up: 改进的模块<5>

1.5.4.13 filecmp
................

A new *note clear_cache(): 850. function provides the ability to clear
the *note filecmp: 7f. comparison cache, which uses *note os.stat():
1f2. information to determine if the file has changed since the last
compare.  This can be used, for example, if the file might have been
changed and re-checked in less time than the resolution of a particular
filesystem’s file modification time field.  (Contributed by Mark Levitt
in bpo-18149(1).)

New module attribute *note DEFAULT_IGNORES: 851. provides the list of
directories that are used as the default value for the `ignore'
parameter of the *note dircmp(): 852. function.  (Contributed by Eli
Bendersky in bpo-15442(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18149

   (2) https://bugs.python.org/issue15442


File: python.info,  Node: functools<4>,  Next: gc<3>,  Prev: filecmp,  Up: 改进的模块<5>

1.5.4.14 functools
..................

The new *note partialmethod(): 29d. descriptor brings partial argument
application to descriptors, just as *note partial(): 7d1. provides for
normal callables.  The new descriptor also makes it easier to get
arbitrary callables (including *note partial(): 7d1. instances) to
behave like normal instance methods when included in a class definition.
(Contributed by Alon Horev and Nick Coghlan in bpo-4331(1).)  The new
*note singledispatch(): 392. decorator brings support for
single-dispatch generic functions to the Python standard library.  Where
object oriented programming focuses on grouping multiple operations on a
common set of data into a class, a generic function focuses on grouping
multiple implementations of an operation that allows it to work with
`different' kinds of data.

参见
....

PEP 443(2) – Single-dispatch generic functions

     PEP 由 Łukasz Langa 撰写并实现。

*note total_ordering(): 854. now supports a return value of *note
NotImplemented: 855. from the underlying comparison function.
(Contributed by Katie Miller in bpo-10042(3).)

A pure-python version of the *note partial(): 7d1. function is now in
the stdlib; in CPython it is overridden by the C accelerated version,
but it is available for other implementations to use.  (Contributed by
Brian Thorne in bpo-12428(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4331

   (2) https://www.python.org/dev/peps/pep-0443

   (3) https://bugs.python.org/issue10042

   (4) https://bugs.python.org/issue12428


File: python.info,  Node: gc<3>,  Next: glob<2>,  Prev: functools<4>,  Up: 改进的模块<5>

1.5.4.15 gc
...........

New function *note get_stats(): 857. returns a list of three
per-generation dictionaries containing the collections statistics since
interpreter startup.  (Contributed by Antoine Pitrou in bpo-16351(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16351


File: python.info,  Node: glob<2>,  Next: hashlib<2>,  Prev: gc<3>,  Up: 改进的模块<5>

1.5.4.16 glob
.............

A new function *note escape(): 859. provides a way to escape special
characters in a filename so that they do not become part of the globbing
expansion but are instead matched literally.  (Contributed by Serhiy
Storchaka in bpo-8402(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8402


File: python.info,  Node: hashlib<2>,  Next: hmac<2>,  Prev: glob<2>,  Up: 改进的模块<5>

1.5.4.17 hashlib
................

A new *note hashlib.pbkdf2_hmac(): 7ef. function provides the PKCS#5
password-based key derivation function 2(1).  (Contributed by Christian
Heimes in bpo-18582(2).)

The *note name: 85b. attribute of *note hashlib: 8d. hash objects is now
a formally supported interface.  It has always existed in CPython’s
*note hashlib: 8d. (although it did not return lower case names for all
supported hashes), but it was not a public interface and so some other
Python implementations have not previously supported it.  (Contributed
by Jason R. Coombs in bpo-18532(3).)

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/PBKDF2

   (2) https://bugs.python.org/issue18582

   (3) https://bugs.python.org/issue18532


File: python.info,  Node: hmac<2>,  Next: html,  Prev: hashlib<2>,  Up: 改进的模块<5>

1.5.4.18 hmac
.............

*note hmac: 8f. now accepts ‘bytearray’ as well as ‘bytes’ for the `key'
argument to the *note new(): 85d. function, and the `msg' parameter to
both the *note new(): 85d. function and the *note update(): 85e. method
now accepts any type supported by the *note hashlib: 8d. module.
(Contributed by Jonas Borgström in bpo-18240(1).)

The `digestmod' argument to the *note hmac.new(): 85d. function may now
be any hash digest name recognized by *note hashlib: 8d.  In addition,
the current behavior in which the value of `digestmod' defaults to ‘MD5’
is deprecated: in a future version of Python there will be no default
value.  (Contributed by Christian Heimes in bpo-17276(2).)

With the addition of *note block_size: 85f. and *note name: 860.
attributes (and the formal documentation of the *note digest_size: 861.
attribute), the *note hmac: 8f. module now conforms fully to the PEP
247(3) API. (Contributed by Christian Heimes in bpo-18775(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18240

   (2) https://bugs.python.org/issue17276

   (3) https://www.python.org/dev/peps/pep-0247

   (4) https://bugs.python.org/issue18775


File: python.info,  Node: html,  Next: http<2>,  Prev: hmac<2>,  Up: 改进的模块<5>

1.5.4.19 html
.............

New function *note unescape(): 863. function converts HTML5 character
references to the corresponding Unicode characters.  (Contributed by
Ezio Melotti in bpo-2927(1).)

*note HTMLParser: 7c8. accepts a new keyword argument `convert_charrefs'
that, when ‘True’, automatically converts all character references.  For
backward-compatibility, its value defaults to ‘False’, but it will
change to ‘True’ in a future version of Python, so you are invited to
set it explicitly and update your code to use this new feature.
(Contributed by Ezio Melotti in bpo-13633(2).)

The `strict' argument of *note HTMLParser: 7c8. is now deprecated.
(Contributed by Ezio Melotti in bpo-15114(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2927

   (2) https://bugs.python.org/issue13633

   (3) https://bugs.python.org/issue15114


File: python.info,  Node: http<2>,  Next: idlelib 与 IDLE<4>,  Prev: html,  Up: 改进的模块<5>

1.5.4.20 http
.............

*note send_error(): 865. now accepts an optional additional `explain'
parameter which can be used to provide an extended error description,
overriding the hardcoded default if there is one.  This extended error
description will be formatted using the ‘error_message_format’ attribute
and sent as the body of the error response.  (Contributed by Karl Cow in
bpo-12921(1).)

The *note http.server: 97. *note command line interface: 866. now has a
‘-b/--bind’ option that causes the server to listen on a specific
address.  (Contributed by Malte Swart in bpo-17764(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12921

   (2) https://bugs.python.org/issue17764


File: python.info,  Node: idlelib 与 IDLE<4>,  Next: importlib<6>,  Prev: http<2>,  Up: 改进的模块<5>

1.5.4.21 idlelib 与 IDLE
........................

Since idlelib implements the IDLE shell and editor and is not intended
for import by other programs, it gets improvements with every release.
See ‘Lib/idlelib/NEWS.txt’ for a cumulative list of changes since 3.3.0,
as well as changes made in future 3.4.x releases.  This file is also
available from the IDLE Help ‣ About IDLE dialog.


File: python.info,  Node: importlib<6>,  Next: inspect<4>,  Prev: idlelib 与 IDLE<4>,  Up: 改进的模块<5>

1.5.4.22 importlib
..................

The *note InspectLoader: 869. ABC defines a new method, *note
source_to_code(): 6f8. that accepts source data and a path and returns a
code object.  The default implementation is equivalent to ‘compile(data,
path, 'exec', dont_inherit=True)’.  (Contributed by Eric Snow and Brett
Cannon in bpo-15627(1).)

*note InspectLoader: 869. also now has a default implementation for the
*note get_code(): 86a. method.  However, it will normally be desirable
to override the default implementation for performance reasons.
(Contributed by Brett Cannon in bpo-18072(2).)

The *note reload(): 3a1. function has been moved from *note imp: 9a. to
*note importlib: 9b. as part of the *note imp: 9a. module deprecation.
(Contributed by Berker Peksag in bpo-18193(3).)

*note importlib.util: a0. now has a *note MAGIC_NUMBER: 86b. attribute
providing access to the bytecode version number.  This replaces the
*note get_magic(): 86c. function in the deprecated *note imp: 9a.
module.  (Contributed by Brett Cannon in bpo-18192(4).)

New *note importlib.util: a0. functions *note cache_from_source(): 560.
and *note source_from_cache(): 561. replace the same-named functions in
the deprecated *note imp: 9a. module.  (Contributed by Brett Cannon in
bpo-18194(5).)

The *note importlib: 9b. bootstrap ‘NamespaceLoader’ now conforms to the
*note InspectLoader: 869. ABC, which means that ‘runpy’ and ‘python -m’
can now be used with namespace packages.  (Contributed by Brett Cannon
in bpo-18058(6).)

*note importlib.util: a0. has a new function *note decode_source(): 86d.
that decodes source from bytes using universal newline processing.  This
is useful for implementing *note InspectLoader.get_source(): 86e.
methods.

*note importlib.machinery.ExtensionFileLoader: 55f. now has a *note
get_filename(): 86f. method.  This was inadvertently omitted in the
original implementation.  (Contributed by Eric Snow in bpo-19152(7).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15627

   (2) https://bugs.python.org/issue18072

   (3) https://bugs.python.org/issue18193

   (4) https://bugs.python.org/issue18192

   (5) https://bugs.python.org/issue18194

   (6) https://bugs.python.org/issue18058

   (7) https://bugs.python.org/issue19152


File: python.info,  Node: inspect<4>,  Next: ipaddress<3>,  Prev: importlib<6>,  Up: 改进的模块<5>

1.5.4.23 inspect
................

The *note inspect: a1. module now offers a basic *note command line
interface: 871. to quickly display source code and other information for
modules, classes and functions.  (Contributed by Claudiu Popa and Nick
Coghlan in bpo-18626(1).)

*note unwrap(): 872. makes it easy to unravel wrapper function chains
created by *note functools.wraps(): 873. (and any other API that sets
the ‘__wrapped__’ attribute on a wrapper function).  (Contributed by
Daniel Urban, Aaron Iles and Nick Coghlan in bpo-13266(2).)

As part of the implementation of the new *note enum: 7b. module, the
*note inspect: a1. module now has substantially better support for
custom ‘__dir__’ methods and dynamic class attributes provided through
metaclasses.  (Contributed by Ethan Furman in bpo-18929(3) and
bpo-19030(4).)

*note getfullargspec(): 566. and *note getargspec(): 565. now use the
*note signature(): 564. API. This allows them to support a much broader
range of callables, including those with ‘__signature__’ attributes,
those with metadata provided by argument clinic, *note
functools.partial(): 7d1. objects and more.  Note that, unlike *note
signature(): 564, these functions still ignore ‘__wrapped__’ attributes,
and report the already bound first argument for bound methods, so it is
still necessary to update your code to use *note signature(): 564.
directly if those features are desired.  (Contributed by Yury Selivanov
in bpo-17481(5).)

*note signature(): 564. now supports duck types of CPython functions,
which adds support for functions compiled with Cython.  (Contributed by
Stefan Behnel and Yury Selivanov in bpo-17159(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18626

   (2) https://bugs.python.org/issue13266

   (3) https://bugs.python.org/issue18929

   (4) https://bugs.python.org/issue19030

   (5) https://bugs.python.org/issue17481

   (6) https://bugs.python.org/issue17159


File: python.info,  Node: ipaddress<3>,  Next: logging<5>,  Prev: inspect<4>,  Up: 改进的模块<5>

1.5.4.24 ipaddress
..................

*note ipaddress: a3. was added to the standard library in Python 3.3 as
a *note provisional API: 351.  With the release of Python 3.4, this
qualification has been removed: *note ipaddress: a3. is now considered a
stable API, covered by the normal standard library requirements to
maintain backwards compatibility.

A new *note is_global: 875. property is ‘True’ if an address is globally
routeable.  (Contributed by Peter Moody in bpo-17400(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17400


File: python.info,  Node: logging<5>,  Next: marshal,  Prev: ipaddress<3>,  Up: 改进的模块<5>

1.5.4.25 logging
................

The *note TimedRotatingFileHandler: 877. has a new `atTime' parameter
that can be used to specify the time of day when rollover should happen.
(Contributed by Ronald Oussoren in bpo-9556(1).)

*note SocketHandler: 878. and *note DatagramHandler: 879. now support
Unix domain sockets (by setting `port' to ‘None’).  (Contributed by
Vinay Sajip in commit ce46195b56a9.)

*note fileConfig(): 3b1. now accepts a *note
configparser.RawConfigParser: 87a. subclass instance for the `fname'
parameter.  This facilitates using a configuration file when logging
configuration is just a part of the overall application configuration,
or where the application modifies the configuration before passing it to
*note fileConfig(): 3b1.  (Contributed by Vinay Sajip in bpo-16110(2).)

Logging configuration data received from a socket via the *note
logging.config.listen(): 87b. function can now be validated before being
processed by supplying a verification function as the argument to the
new `verify' keyword argument.  (Contributed by Vinay Sajip in
bpo-15452(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9556

   (2) https://bugs.python.org/issue16110

   (3) https://bugs.python.org/issue15452


File: python.info,  Node: marshal,  Next: mmap<2>,  Prev: logging<5>,  Up: 改进的模块<5>

1.5.4.26 marshal
................

The default *note marshal: b1. version has been bumped to 3.  The code
implementing the new version restores the Python2 behavior of recording
only one copy of interned strings and preserving the interning on
deserialization, and extends this "one copy" ability to any object type
(including handling recursive references).  This reduces both the size
of ‘.pyc’ files and the amount of memory a module occupies in memory
when it is loaded from a ‘.pyc’ (or ‘.pyo’) file.  (Contributed by
Kristján Valur Jónsson in bpo-16475(1), with additional speedups by
Antoine Pitrou in bpo-19219(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16475

   (2) https://bugs.python.org/issue19219


File: python.info,  Node: mmap<2>,  Next: multiprocessing<5>,  Prev: marshal,  Up: 改进的模块<5>

1.5.4.27 mmap
.............

mmap objects can now be *note weakref: 129.ed.  (Contributed by Valerie
Lambert in bpo-4885(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4885


File: python.info,  Node: multiprocessing<5>,  Next: operator<2>,  Prev: mmap<2>,  Up: 改进的模块<5>

1.5.4.28 multiprocessing
........................

On Unix two new *note start methods: 87f, ‘spawn’ and ‘forkserver’, have
been added for starting processes using *note multiprocessing: b8.
These make the mixing of processes with threads more robust, and the
‘spawn’ method matches the semantics that multiprocessing has always
used on Windows.  New function *note get_all_start_methods(): 880.
reports all start methods available on the platform, *note
get_start_method(): 881. reports the current start method, and *note
set_start_method(): 882. sets the start method.  (Contributed by Richard
Oudkerk in bpo-8713(1).)

*note multiprocessing: b8. also now has the concept of a ‘context’,
which determines how child processes are created.  New function *note
get_context(): 883. returns a context that uses a specified start
method.  It has the same API as the *note multiprocessing: b8. module
itself, so you can use it to create *note Pool: 884.s and other objects
that will operate within that context.  This allows a framework and an
application or different parts of the same application to use
multiprocessing without interfering with each other.  (Contributed by
Richard Oudkerk in bpo-18999(2).)

Except when using the old `fork' start method, child processes no longer
inherit unneeded handles/file descriptors from their parents (part of
bpo-8713(3)).

*note multiprocessing: b8. now relies on *note runpy: e3. (which
implements the ‘-m’ switch) to initialise ‘__main__’ appropriately in
child processes when using the ‘spawn’ or ‘forkserver’ start methods.
This resolves some edge cases where combining multiprocessing, the ‘-m’
command line switch, and explicit relative imports could cause obscure
failures in child processes.  (Contributed by Nick Coghlan in
bpo-19946(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8713

   (2) https://bugs.python.org/issue18999

   (3) https://bugs.python.org/issue8713

   (4) https://bugs.python.org/issue19946


File: python.info,  Node: operator<2>,  Next: os<6>,  Prev: multiprocessing<5>,  Up: 改进的模块<5>

1.5.4.29 operator
.................

New function *note length_hint(): 886. provides an implementation of the
specification for how the *note __length_hint__(): 815. special method
should be used, as part of the PEP 424(1) formal specification of this
language feature.  (Contributed by Armin Ronacher in bpo-16148(2).)

There is now a pure-python version of the *note operator: c3. module
available for reference and for use by alternate implementations of
Python.  (Contributed by Zachary Ware in bpo-16694(3).)

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0424

   (2) https://bugs.python.org/issue16148

   (3) https://bugs.python.org/issue16694


File: python.info,  Node: os<6>,  Next: pdb<3>,  Prev: operator<2>,  Up: 改进的模块<5>

1.5.4.30 os
...........

There are new functions to get and set the *note inheritable flag: 803.
of a file descriptor (*note os.get_inheritable(): 804, *note
os.set_inheritable(): 805.) or a Windows handle (*note
os.get_handle_inheritable(): 806, *note os.set_handle_inheritable():
807.).

New function *note cpu_count(): 888. reports the number of CPUs
available on the platform on which Python is running (or ‘None’ if the
count can’t be determined).  The *note multiprocessing.cpu_count(): 889.
function is now implemented in terms of this function).  (Contributed by
Trent Nelson, Yogesh Chaudhari, Victor Stinner, and Charles-François
Natali in bpo-17914(1).)

*note os.path.samestat(): 88a. is now available on the Windows platform
(and the *note os.path.samefile(): 88b. implementation is now shared
between Unix and Windows).  (Contributed by Brian Curtin in
bpo-11939(2).)

*note os.path.ismount(): 1fb. now recognizes volumes mounted below a
drive root on Windows.  (Contributed by Tim Golden in bpo-9035(3).)

*note os.open(): 66e. supports two new flags on platforms that provide
them, *note O_PATH: 88c. (un-opened file descriptor), and *note
O_TMPFILE: 88d. (unnamed temporary file; as of 3.4.0 release available
only on Linux systems with a kernel version of 3.11 or newer that have
uapi headers).  (Contributed by Christian Heimes in bpo-18673(4) and
Benjamin Peterson, respectively.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17914

   (2) https://bugs.python.org/issue11939

   (3) https://bugs.python.org/issue9035

   (4) https://bugs.python.org/issue18673


File: python.info,  Node: pdb<3>,  Next: pickle<4>,  Prev: os<6>,  Up: 改进的模块<5>

1.5.4.31 pdb
............

*note pdb: ca. has been enhanced to handle generators, *note yield: 190,
and ‘yield from’ in a more useful fashion.  This is especially helpful
when debugging *note asyncio: a. based programs.  (Contributed by Andrew
Svetlov and Xavier de Gaye in bpo-16596(1).)

The ‘print’ command has been removed from *note pdb: ca, restoring
access to the Python *note print(): 88f. function from the pdb command
line.  Python2’s ‘pdb’ did not have a ‘print’ command; instead, entering
‘print’ executed the ‘print’ statement.  In Python3 ‘print’ was
mistakenly made an alias for the pdb *note p: 890. command.  ‘p’,
however, prints the ‘repr’ of its argument, not the ‘str’ like the
Python2 ‘print’ command did.  Worse, the Python3 ‘pdb print’ command
shadowed the Python3 ‘print’ function, making it inaccessible at the
‘pdb’ prompt.  (Contributed by Connor Osborn in bpo-18764(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16596

   (2) https://bugs.python.org/issue18764


File: python.info,  Node: pickle<4>,  Next: plistlib<2>,  Prev: pdb<3>,  Up: 改进的模块<5>

1.5.4.32 pickle
...............

*note pickle: cb. now supports (but does not use by default) a new
pickle protocol, protocol 4.  This new protocol addresses a number of
issues that were present in previous protocols, such as the
serialization of nested classes, very large strings and containers, and
classes whose *note __new__(): 892. method takes keyword-only arguments.
It also provides some efficiency improvements.

参见
....

PEP 3154(1) – Pickle protocol 4

     PEP 由 Antoine Pitrou 撰写，并由 Alexandre Vassalotti 实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3154


File: python.info,  Node: plistlib<2>,  Next: poplib<2>,  Prev: pickle<4>,  Up: 改进的模块<5>

1.5.4.33 plistlib
.................

*note plistlib: d0. now has an API that is similar to the standard
pattern for stdlib serialization protocols, with new *note load(): 894,
*note dump(): 895, *note loads(): 896, and *note dumps(): 897.
functions.  (The older API is now deprecated.)  In addition to the
already supported XML plist format (*note FMT_XML: 898.), it also now
supports the binary plist format (*note FMT_BINARY: 899.).  (Contributed
by Ronald Oussoren and others in bpo-14455(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14455


File: python.info,  Node: poplib<2>,  Next: pprint<2>,  Prev: plistlib<2>,  Up: 改进的模块<5>

1.5.4.34 poplib
...............

Two new methods have been added to *note poplib: d1.: *note capa(): 89b,
which returns the list of capabilities advertised by the POP server, and
*note stls(): 89c, which switches a clear-text POP3 session into an
encrypted POP3 session if the POP server supports it.  (Contributed by
Lorenzo Catucci in bpo-4473(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4473


File: python.info,  Node: pprint<2>,  Next: pty,  Prev: poplib<2>,  Up: 改进的模块<5>

1.5.4.35 pprint
...............

The *note pprint: d3. module’s *note PrettyPrinter: 89e. class and its
*note pformat(): 89f, and *note pprint(): 214. functions have a new
option, `compact', that controls how the output is formatted.  Currently
setting `compact' to ‘True’ means that sequences will be printed with as
many sequence elements as will fit within `width' on each (indented)
line.  (Contributed by Serhiy Storchaka in bpo-19132(1).)

Long strings are now wrapped using Python’s normal line continuation
syntax.  (Contributed by Antoine Pitrou in bpo-17150(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19132

   (2) https://bugs.python.org/issue17150


File: python.info,  Node: pty,  Next: pydoc<3>,  Prev: pprint<2>,  Up: 改进的模块<5>

1.5.4.36 pty
............

*note pty.spawn(): 8a1. now returns the status value from *note
os.waitpid(): 676. on the child process, instead of ‘None’.
(Contributed by Gregory P. Smith.)


File: python.info,  Node: pydoc<3>,  Next: re<5>,  Prev: pty,  Up: 改进的模块<5>

1.5.4.37 pydoc
..............

The *note pydoc: da. module is now based directly on the *note
inspect.signature(): 564. introspection API, allowing it to provide
signature information for a wider variety of callable objects.  This
change also means that ‘__wrapped__’ attributes are now taken into
account when displaying help information.  (Contributed by Larry
Hastings in bpo-19674(1).)

The *note pydoc: da. module no longer displays the ‘self’ parameter for
already bound methods.  Instead, it aims to always display the exact
current signature of the supplied callable.  (Contributed by Larry
Hastings in bpo-20710(2).)

In addition to the changes that have been made to *note pydoc: da.
directly, its handling of custom ‘__dir__’ methods and various
descriptor behaviours has also been improved substantially by the
underlying changes in the *note inspect: a1. module.

As the *note help(): 57b. builtin is based on *note pydoc: da, the above
changes also affect the behaviour of *note help(): 57b.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19674

   (2) https://bugs.python.org/issue20710


File: python.info,  Node: re<5>,  Next: resource,  Prev: pydoc<3>,  Up: 改进的模块<5>

1.5.4.38 re
...........

New *note fullmatch(): 8a4. function and ‘regex.fullmatch()’ method
anchor the pattern at both ends of the string to match.  This provides a
way to be explicit about the goal of the match, which avoids a class of
subtle bugs where ‘$’ characters get lost during code changes or the
addition of alternatives to an existing regular expression.
(Contributed by Matthew Barnett in bpo-16203(1).)

The repr of *note regex objects: 8a5. now includes the pattern and the
flags; the repr of *note match objects: 8a6. now includes the start,
end, and the part of the string that matched.  (Contributed by Hugo
Lopes Tavares and Serhiy Storchaka in bpo-13592(2) and bpo-17087(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16203

   (2) https://bugs.python.org/issue13592

   (3) https://bugs.python.org/issue17087


File: python.info,  Node: resource,  Next: select,  Prev: re<5>,  Up: 改进的模块<5>

1.5.4.39 resource
.................

New *note prlimit(): 8a8. function, available on Linux platforms with a
kernel version of 2.6.36 or later and glibc of 2.13 or later, provides
the ability to query or set the resource limits for processes other than
the one making the call.  (Contributed by Christian Heimes in
bpo-16595(1).)

On Linux kernel version 2.6.36 or later, there are also some new Linux
specific constants: *note RLIMIT_MSGQUEUE: 8a9, *note RLIMIT_NICE: 8aa,
*note RLIMIT_RTPRIO: 8ab, *note RLIMIT_RTTIME: 8ac, and *note
RLIMIT_SIGPENDING: 8ad.  (Contributed by Christian Heimes in
bpo-19324(2).)

On FreeBSD version 9 and later, there some new FreeBSD specific
constants: *note RLIMIT_SBSIZE: 8ae, *note RLIMIT_SWAP: 8af, and *note
RLIMIT_NPTS: 8b0.  (Contributed by Claudiu Popa in bpo-19343(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16595

   (2) https://bugs.python.org/issue19324

   (3) https://bugs.python.org/issue19343


File: python.info,  Node: select,  Next: shelve,  Prev: resource,  Up: 改进的模块<5>

1.5.4.40 select
...............

*note epoll: 8b2. objects now support the context management protocol.
When used in a *note with: 6f2. statement, the *note close(): 8b3.
method will be called automatically at the end of the block.
(Contributed by Serhiy Storchaka in bpo-16488(1).)

*note devpoll: 8b4. objects now have *note fileno(): 8b5. and *note
close(): 8b6. methods, as well as a new attribute *note closed: 8b7.
(Contributed by Victor Stinner in bpo-18794(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16488

   (2) https://bugs.python.org/issue18794


File: python.info,  Node: shelve,  Next: shutil<3>,  Prev: select,  Up: 改进的模块<5>

1.5.4.41 shelve
...............

*note Shelf: 8b9. instances may now be used in *note with: 6f2.
statements, and will be automatically closed at the end of the ‘with’
block.  (Contributed by Filip Gruszczyński in bpo-13896(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13896


File: python.info,  Node: shutil<3>,  Next: smtpd<2>,  Prev: shelve,  Up: 改进的模块<5>

1.5.4.42 shutil
...............

*note copyfile(): 259. now raises a specific *note Error: 8bb. subclass,
*note SameFileError: 8bc, when the source and destination are the same
file, which allows an application to take appropriate action on this
specific error.  (Contributed by Atsuo Ishimoto and Hynek Schlawack in
bpo-1492704(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1492704


File: python.info,  Node: smtpd<2>,  Next: smtplib<2>,  Prev: shutil<3>,  Up: 改进的模块<5>

1.5.4.43 smtpd
..............

The *note SMTPServer: 60b. and *note SMTPChannel: 60a. classes now
accept a `map' keyword argument which, if specified, is passed in to
*note asynchat.async_chat: 8be. as its `map' argument.  This allows an
application to avoid affecting the global socket map.  (Contributed by
Vinay Sajip in bpo-11959(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11959


File: python.info,  Node: smtplib<2>,  Next: socket<6>,  Prev: smtpd<2>,  Up: 改进的模块<5>

1.5.4.44 smtplib
................

*note SMTPException: 8c0. is now a subclass of *note OSError: 1d4, which
allows both socket level errors and SMTP protocol level errors to be
caught in one try/except statement by code that only cares whether or
not an error occurred.  (Contributed by Ned Jackson Lovely in
bpo-2118(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2118


File: python.info,  Node: socket<6>,  Next: sqlite3<4>,  Prev: smtplib<2>,  Up: 改进的模块<5>

1.5.4.45 socket
...............

The socket module now supports the *note CAN_BCM: 8c2. protocol on
platforms that support it.  (Contributed by Brian Thorne in
bpo-15359(1).)

Socket objects have new methods to get or set their *note inheritable
flag: 803, *note get_inheritable(): 808. and *note set_inheritable():
809.

The ‘socket.AF_*’ and ‘socket.SOCK_*’ constants are now enumeration
values using the new *note enum: 7b. module.  This allows meaningful
names to be printed during debugging, instead of integer "magic
numbers".

The *note AF_LINK: 8c3. constant is now available on BSD and OSX.

*note inet_pton(): 2f9. and *note inet_ntop(): 8c4. are now supported on
Windows.  (Contributed by Atsuo Ishimoto in bpo-7171(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15359

   (2) https://bugs.python.org/issue7171


File: python.info,  Node: sqlite3<4>,  Next: ssl<7>,  Prev: socket<6>,  Up: 改进的模块<5>

1.5.4.46 sqlite3
................

A new boolean parameter to the *note connect(): 3e2. function, `uri',
can be used to indicate that the `database' parameter is a ‘uri’ (see
the SQLite URI documentation(1)).  (Contributed by poq in bpo-13773(2).)

   ---------- Footnotes ----------

   (1) https://www.sqlite.org/uri.html

   (2) https://bugs.python.org/issue13773


File: python.info,  Node: ssl<7>,  Next: stat,  Prev: sqlite3<4>,  Up: 改进的模块<5>

1.5.4.47 ssl
............

*note PROTOCOL_TLSv1_1: 8c7. and *note PROTOCOL_TLSv1_2: 8c8. (TLSv1.1
and TLSv1.2 support) have been added; support for these protocols is
only available if Python is linked with OpenSSL 1.0.1 or later.
(Contributed by Michele Orrù and Antoine Pitrou in bpo-16692(1).)  New
function *note create_default_context(): 8c9. provides a standard way to
obtain an *note SSLContext: 3ec. whose settings are intended to be a
reasonable balance between compatibility and security.  These settings
are more stringent than the defaults provided by the *note SSLContext:
3ec. constructor, and may be adjusted in the future, without prior
deprecation, if best-practice security requirements change.  The new
recommended best practice for using stdlib libraries that support SSL is
to use *note create_default_context(): 8c9. to obtain an *note
SSLContext: 3ec. object, modify it if needed, and then pass it as the
`context' argument of the appropriate stdlib API. (Contributed by
Christian Heimes in bpo-19689(2).)

*note SSLContext: 3ec. method *note load_verify_locations(): 7f4.
accepts a new optional argument `cadata', which can be used to provide
PEM or DER encoded certificates directly via strings or bytes,
respectively.  (Contributed by Christian Heimes in bpo-18138(3).)

New function *note get_default_verify_paths(): 8ca. returns a named
tuple of the paths and environment variables that the *note
set_default_verify_paths(): 8cb. method uses to set OpenSSL’s default
‘cafile’ and ‘capath’.  This can be an aid in debugging default
verification issues.  (Contributed by Christian Heimes in bpo-18143(4).)

*note SSLContext: 3ec. has a new method, *note cert_store_stats(): 8cc,
that reports the number of loaded ‘X.509’ certs, ‘X.509 CA’ certs, and
certificate revocation lists (‘crl’s), as well as a *note
get_ca_certs(): 8cd. method that returns a list of the loaded ‘CA’
certificates.  (Contributed by Christian Heimes in bpo-18147(5).)

If OpenSSL 0.9.8 or later is available, *note SSLContext: 3ec. has a new
attribute *note verify_flags: 8ce. that can be used to control the
certificate verification process by setting it to some combination of
the new constants *note VERIFY_DEFAULT: 8cf, *note
VERIFY_CRL_CHECK_LEAF: 8d0, *note VERIFY_CRL_CHECK_CHAIN: 8d1, or *note
VERIFY_X509_STRICT: 8d2.  OpenSSL does not do any CRL verification by
default.  (Contributed by Christien Heimes in bpo-8813(6).)

New *note SSLContext: 3ec. method *note load_default_certs(): 8d3. loads
a set of default "certificate authority" (CA) certificates from default
locations, which vary according to the platform.  It can be used to load
both TLS web server authentication certificates (‘purpose=’*note
SERVER_AUTH: 8d4.) for a client to use to verify a server, and
certificates for a server to use in verifying client certificates
(‘purpose=’*note CLIENT_AUTH: 8d5.).  (Contributed by Christian Heimes
in bpo-19292(7).)  Two new windows-only functions, *note
enum_certificates(): 8d6. and *note enum_crls(): 8d7. provide the
ability to retrieve certificates, certificate information, and CRLs from
the Windows cert store.  (Contributed by Christian Heimes in
bpo-17134(8).)  Support for server-side SNI (Server Name Indication)
using the new *note ssl.SSLContext.set_servername_callback(): 8d8.
method.  (Contributed by Daniel Black in bpo-8109(9).)

The dictionary returned by *note SSLSocket.getpeercert(): 8d9. contains
additional ‘X509v3’ extension items: ‘crlDistributionPoints’,
‘calIssuers’, and ‘OCSP’ URIs.  (Contributed by Christian Heimes in
bpo-18379(10).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16692

   (2) https://bugs.python.org/issue19689

   (3) https://bugs.python.org/issue18138

   (4) https://bugs.python.org/issue18143

   (5) https://bugs.python.org/issue18147

   (6) https://bugs.python.org/issue8813

   (7) https://bugs.python.org/issue19292

   (8) https://bugs.python.org/issue17134

   (9) https://bugs.python.org/issue8109

   (10) https://bugs.python.org/issue18379


File: python.info,  Node: stat,  Next: struct<2>,  Prev: ssl<7>,  Up: 改进的模块<5>

1.5.4.48 stat
.............

The *note stat: f5. module is now backed by a C implementation in
‘_stat’.  A C implementation is required as most of the values aren’t
standardized and are platform-dependent.  (Contributed by Christian
Heimes in bpo-11016(1).)

The module supports new *note ST_MODE: 8db. flags, *note S_IFDOOR: 8dc,
*note S_IFPORT: 8dd, and *note S_IFWHT: 8de.  (Contributed by Christian
Hiemes in bpo-11016(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11016

   (2) https://bugs.python.org/issue11016


File: python.info,  Node: struct<2>,  Next: subprocess<4>,  Prev: stat,  Up: 改进的模块<5>

1.5.4.49 struct
...............

New function *note iter_unpack: 8e0. and a new *note
struct.Struct.iter_unpack(): 8e1. method on compiled formats provide
streamed unpacking of a buffer containing repeated instances of a given
format of data.  (Contributed by Antoine Pitrou in bpo-17804(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17804


File: python.info,  Node: subprocess<4>,  Next: sunau<2>,  Prev: struct<2>,  Up: 改进的模块<5>

1.5.4.50 subprocess
...................

*note check_output(): 8e3. now accepts an `input' argument that can be
used to provide the contents of ‘stdin’ for the command that is run.
(Contributed by Zack Weinberg in bpo-16624(1).)

‘getstatus()’ and *note getstatusoutput(): 8e4. now work on Windows.
This change was actually inadvertently made in 3.3.4.  (Contributed by
Tim Golden in bpo-10197(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16624

   (2) https://bugs.python.org/issue10197


File: python.info,  Node: sunau<2>,  Next: sys<6>,  Prev: subprocess<4>,  Up: 改进的模块<5>

1.5.4.51 sunau
..............

The ‘getparams()’ method now returns a namedtuple rather than a plain
tuple.  (Contributed by Claudiu Popa in bpo-18901(1).)

*note sunau.open(): 47a. now supports the context management protocol:
when used in a *note with: 6f2. block, the ‘close’ method of the
returned object will be called automatically at the end of the block.
(Contributed by Serhiy Storchaka in bpo-18878(2).)

*note AU_write.setsampwidth(): 8e6. now supports 24 bit samples, thus
adding support for writing 24 sample using the module.  (Contributed by
Serhiy Storchaka in bpo-19261(3).)

The *note writeframesraw(): 8e7. and *note writeframes(): 8e8. methods
now accept any *note bytes-like object: 5f1.  (Contributed by Serhiy
Storchaka in bpo-8311(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18901

   (2) https://bugs.python.org/issue18878

   (3) https://bugs.python.org/issue19261

   (4) https://bugs.python.org/issue8311


File: python.info,  Node: sys<6>,  Next: tarfile<3>,  Prev: sunau<2>,  Up: 改进的模块<5>

1.5.4.52 sys
............

New function *note sys.getallocatedblocks(): 8ea. returns the current
number of blocks allocated by the interpreter.  (In CPython with the
default ‘--with-pymalloc’ setting, this is allocations made through the
*note PyObject_Malloc(): 510. API.) This can be useful for tracking
memory leaks, especially if automated via a test suite.  (Contributed by
Antoine Pitrou in bpo-13390(1).)

When the Python interpreter starts in *note interactive mode: 8eb, it
checks for an *note __interactivehook__: 8ec. attribute on the *note
sys: fe. module.  If the attribute exists, its value is called with no
arguments just before interactive mode is started.  The check is made
after the *note PYTHONSTARTUP: 8ed. file is read, so it can be set
there.  The *note site: ec. module *note sets it: 8ee. to a function
that enables tab completion and history saving (in ‘~/.python-history’)
if the platform supports *note readline: df.  If you do not want this
(new) behavior, you can override it in *note PYTHONSTARTUP: 8ed,
‘sitecustomize’, or ‘usercustomize’ by deleting this attribute from
*note sys: fe. (or setting it to some other callable).  (Contributed by
Éric Araujo and Antoine Pitrou in bpo-5845(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13390

   (2) https://bugs.python.org/issue5845


File: python.info,  Node: tarfile<3>,  Next: textwrap,  Prev: sys<6>,  Up: 改进的模块<5>

1.5.4.53 tarfile
................

The *note tarfile: 102. module now supports a simple *note 命令行界面:
8f0. when called as a script directly or via ‘-m’.  This can be used to
create and extract tarfile archives.  (Contributed by Berker Peksag in
bpo-13477(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13477


File: python.info,  Node: textwrap,  Next: threading<4>,  Prev: tarfile<3>,  Up: 改进的模块<5>

1.5.4.54 textwrap
.................

The *note TextWrapper: 8f2. class has two new attributes/constructor
arguments: *note max_lines: 8f3, which limits the number of lines in the
output, and *note placeholder: 8f4, which is a string that will appear
at the end of the output if it has been truncated because of
`max_lines'.  Building on these capabilities, a new convenience function
*note shorten(): 8f5. collapses all of the whitespace in the input to
single spaces and produces a single line of a given `width' that ends
with the `placeholder' (by default, ‘[...]’).  (Contributed by Antoine
Pitrou and Serhiy Storchaka in bpo-18585(1) and bpo-18725(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18585

   (2) https://bugs.python.org/issue18725


File: python.info,  Node: threading<4>,  Next: 回溯<3>,  Prev: textwrap,  Up: 改进的模块<5>

1.5.4.55 threading
..................

The *note Thread: 235. object representing the main thread can be
obtained from the new *note main_thread(): 8f7. function.  In normal
conditions this will be the thread from which the Python interpreter was
started.  (Contributed by Andrew Svetlov in bpo-18882(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18882


File: python.info,  Node: 回溯<3>,  Next: types<3>,  Prev: threading<4>,  Up: 改进的模块<5>

1.5.4.56 回溯
.............

A new *note traceback.clear_frames(): 8f9. function takes a traceback
object and clears the local variables in all of the frames it
references, reducing the amount of memory consumed.  (Contributed by
Andrew Kuchling in bpo-1565525(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1565525


File: python.info,  Node: types<3>,  Next: urllib<2>,  Prev: 回溯<3>,  Up: 改进的模块<5>

1.5.4.57 types
..............

A new *note DynamicClassAttribute(): 8fb. descriptor provides a way to
define an attribute that acts normally when looked up through an
instance object, but which is routed to the `class' ‘__getattr__’ when
looked up through the class.  This allows one to have properties active
on a class, and have virtual attributes on the class with the same name
(see ‘Enum’ for an example).  (Contributed by Ethan Furman in
bpo-19030(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19030


File: python.info,  Node: urllib<2>,  Next: unittest<4>,  Prev: types<3>,  Up: 改进的模块<5>

1.5.4.58 urllib
...............

*note urllib.request: 121. now supports ‘data:’ URLs via the *note
DataHandler: 8fd. class.  (Contributed by Mathias Panzenböck in
bpo-16423(1).)

The http method that will be used by a *note Request: 8fe. class can now
be specified by setting a *note method: 8ff. class attribute on the
subclass.  (Contributed by Jason R Coombs in bpo-18978(2).)

*note Request: 8fe. objects are now reusable: if the *note full_url:
900. or *note data: 901. attributes are modified, all relevant internal
properties are updated.  This means, for example, that it is now
possible to use the same *note Request: 8fe. object in more than one
*note OpenerDirector.open(): 902. call with different `data' arguments,
or to modify a *note Request: 8fe.’s ‘url’ rather than recomputing it
from scratch.  There is also a new *note remove_header(): 903. method
that can be used to remove headers from a *note Request: 8fe.
(Contributed by Alexey Kachayev in bpo-16464(3), Daniel Wozniak in
bpo-17485(4), and Damien Brecht and Senthil Kumaran in bpo-17272(5).)

*note HTTPError: 904. objects now have a *note headers: 905. attribute
that provides access to the HTTP response headers associated with the
error.  (Contributed by Berker Peksag in bpo-15701(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16423

   (2) https://bugs.python.org/issue18978

   (3) https://bugs.python.org/issue16464

   (4) https://bugs.python.org/issue17485

   (5) https://bugs.python.org/issue17272

   (6) https://bugs.python.org/issue15701


File: python.info,  Node: unittest<4>,  Next: venv<4>,  Prev: urllib<2>,  Up: 改进的模块<5>

1.5.4.59 unittest
.................

The *note TestCase: 907. class has a new method, *note subTest(): 908,
that produces a context manager whose *note with: 6f2. block becomes a
"sub-test".  This context manager allows a test method to dynamically
generate subtests by, say, calling the ‘subTest’ context manager inside
a loop.  A single test method can thereby produce an indefinite number
of separately-identified and separately-counted tests, all of which will
run even if one or more of them fail.  For example:

     class NumbersTest(unittest.TestCase):
         def test_even(self):
             for i in range(6):
                 with self.subTest(i=i):
                     self.assertEqual(i % 2, 0)

will result in six subtests, each identified in the unittest verbose
output with a label consisting of the variable name ‘i’ and a particular
value for that variable (‘i=0’, ‘i=1’, etc).  See *note Distinguishing
test iterations using subtests: 909. for the full version of this
example.  (Contributed by Antoine Pitrou in bpo-16997(1).)

*note unittest.main(): 90a. now accepts an iterable of test names for
`defaultTest', where previously it only accepted a single test name as a
string.  (Contributed by Jyrki Pulliainen in bpo-15132(2).)

If *note SkipTest: 90b. is raised during test discovery (that is, at the
module level in the test file), it is now reported as a skip instead of
an error.  (Contributed by Zach Ware in bpo-16935(3).)

*note discover(): 90c. now sorts the discovered files to provide
consistent test ordering.  (Contributed by Martin Melin and Jeff Ramnani
in bpo-16709(4).)

*note TestSuite: 6d7. now drops references to tests as soon as the test
has been run, if the test is successful.  On Python interpreters that do
garbage collection, this allows the tests to be garbage collected if
nothing else is holding a reference to the test.  It is possible to
override this behavior by creating a *note TestSuite: 6d7. subclass that
defines a custom ‘_removeTestAtIndex’ method.  (Contributed by Tom
Wardill, Matt McClure, and Andrew Svetlov in bpo-11798(5).)

A new test assertion context-manager, *note assertLogs(): 90d, will
ensure that a given block of code emits a log message using the *note
logging: ab. module.  By default the message can come from any logger
and have a priority of ‘INFO’ or higher, but both the logger name and an
alternative minimum logging level may be specified.  The object returned
by the context manager can be queried for the *note LogRecord: 90e.s
and/or formatted messages that were logged.  (Contributed by Antoine
Pitrou in bpo-18937(6).)

Test discovery now works with namespace packages (Contributed by Claudiu
Popa in bpo-17457(7).)

*note unittest.mock: 11d. objects now inspect their specification
signatures when matching calls, which means an argument can now be
matched by either position or name, instead of only by position.
(Contributed by Antoine Pitrou in bpo-17015(8).)

‘mock_open()’ objects now have ‘readline’ and ‘readlines’ methods.
(Contributed by Toshio Kuratomi in bpo-17467(9).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16997

   (2) https://bugs.python.org/issue15132

   (3) https://bugs.python.org/issue16935

   (4) https://bugs.python.org/issue16709

   (5) https://bugs.python.org/issue11798

   (6) https://bugs.python.org/issue18937

   (7) https://bugs.python.org/issue17457

   (8) https://bugs.python.org/issue17015

   (9) https://bugs.python.org/issue17467


File: python.info,  Node: venv<4>,  Next: wave<2>,  Prev: unittest<4>,  Up: 改进的模块<5>

1.5.4.60 venv
.............

*note venv: 126. now includes activation scripts for the ‘csh’ and
‘fish’ shells.  (Contributed by Andrew Svetlov in bpo-15417(1).)

*note EnvBuilder: 910. and the *note create(): 911. convenience function
take a new keyword argument `with_pip', which defaults to ‘False’, that
controls whether or not *note EnvBuilder: 910. ensures that ‘pip’ is
installed in the virtual environment.  (Contributed by Nick Coghlan in
bpo-19552(2) as part of the PEP 453(3) implementation.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15417

   (2) https://bugs.python.org/issue19552

   (3) https://www.python.org/dev/peps/pep-0453


File: python.info,  Node: wave<2>,  Next: weakref<2>,  Prev: venv<4>,  Up: 改进的模块<5>

1.5.4.61 wave
.............

The ‘getparams()’ method now returns a namedtuple rather than a plain
tuple.  (Contributed by Claudiu Popa in bpo-17487(1).)

*note wave.open(): 47e. now supports the context management protocol.
(Contributed by Claudiu Popa in bpo-17616(2).)

*note wave: 128. can now *note write output to unseekable files: 913.
(Contributed by David Jones, Guilherme Polo, and Serhiy Storchaka in
bpo-5202(3).)

The *note writeframesraw(): 914. and *note writeframes(): 915. methods
now accept any *note bytes-like object: 5f1.  (Contributed by Serhiy
Storchaka in bpo-8311(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17487

   (2) https://bugs.python.org/issue17616

   (3) https://bugs.python.org/issue5202

   (4) https://bugs.python.org/issue8311


File: python.info,  Node: weakref<2>,  Next: xml etree<2>,  Prev: wave<2>,  Up: 改进的模块<5>

1.5.4.62 weakref
................

New *note WeakMethod: 917. class simulates weak references to bound
methods.  (Contributed by Antoine Pitrou in bpo-14631(1).)

New *note finalize: 29e. class makes it possible to register a callback
to be invoked when an object is garbage collected, without needing to
carefully manage the lifecycle of the weak reference itself.
(Contributed by Richard Oudkerk in bpo-15528(2).)

The callback, if any, associated with a *note ref: 918. is now exposed
via the *note __callback__: 919. attribute.  (Contributed by Mark
Dickinson in bpo-17643(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14631

   (2) https://bugs.python.org/issue15528

   (3) https://bugs.python.org/issue17643


File: python.info,  Node: xml etree<2>,  Next: zipfile<4>,  Prev: weakref<2>,  Up: 改进的模块<5>

1.5.4.63 xml.etree
..................

A new parser, *note XMLPullParser: 91b, allows a non-blocking
applications to parse XML documents.  An example can be seen at *note
Pull API进行非阻塞解析: 91c.  (Contributed by Antoine Pitrou in
bpo-17741(1).)

The *note xml.etree.ElementTree: 138. *note tostring(): 91d. and *note
tostringlist(): 91e. functions, and the *note ElementTree: 91f. *note
write(): 920. method, now have a `short_empty_elements' *note
keyword-only parameter: 2ad. providing control over whether elements
with no content are written in abbreviated (‘<tag />’) or expanded
(‘<tag></tag>’) form.  (Contributed by Ariel Poliak and Serhiy Storchaka
in bpo-14377(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17741

   (2) https://bugs.python.org/issue14377


File: python.info,  Node: zipfile<4>,  Prev: xml etree<2>,  Up: 改进的模块<5>

1.5.4.64 zipfile
................

The *note writepy(): 922. method of the *note PyZipFile: 923. class has
a new `filterfunc' option that can be used to control which directories
and files are added to the archive.  For example, this could be used to
exclude test files from the archive.  (Contributed by Christian Tismer
in bpo-19274(1).)

The `allowZip64' parameter to *note ZipFile: 427. and ‘PyZipfile’ is now
‘True’ by default.  (Contributed by William Mallard in bpo-17201(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19274

   (2) https://bugs.python.org/issue17201


File: python.info,  Node: CPython Implementation Changes,  Next: 弃用<4>,  Prev: 改进的模块<5>,  Up: Python 3 4 有什么新变化

1.5.5 CPython Implementation Changes
------------------------------------

* Menu:

* PEP 445; Customization of CPython Memory Allocators: PEP 445 Customization of CPython Memory Allocators.
* PEP 442; Safe Object Finalization: PEP 442 Safe Object Finalization.
* PEP 456; Secure and Interchangeable Hash Algorithm: PEP 456 Secure and Interchangeable Hash Algorithm.
* PEP 436; Argument Clinic: PEP 436 Argument Clinic.
* Other Build and C API Changes::
* 其他改进: 其他改进<2>.
* Significant Optimizations::


File: python.info,  Node: PEP 445 Customization of CPython Memory Allocators,  Next: PEP 442 Safe Object Finalization,  Up: CPython Implementation Changes

1.5.5.1 PEP 445: Customization of CPython Memory Allocators
...........................................................

PEP 445(1) adds new C level interfaces to customize memory allocation in
the CPython interpreter.

参见
....

PEP 445(2) – Add new APIs to customize Python memory allocators

     PEP 由 Victor Stinner 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0445

   (2) https://www.python.org/dev/peps/pep-0445


File: python.info,  Node: PEP 442 Safe Object Finalization,  Next: PEP 456 Secure and Interchangeable Hash Algorithm,  Prev: PEP 445 Customization of CPython Memory Allocators,  Up: CPython Implementation Changes

1.5.5.2 PEP 442: Safe Object Finalization
.........................................

PEP 442(1) removes the current limitations and quirks of object
finalization in CPython.  With it, objects with *note __del__(): 927.
methods, as well as generators with *note finally: 183. clauses, can be
finalized when they are part of a reference cycle.

As part of this change, module globals are no longer forcibly set to
*note None: 158. during interpreter shutdown in most cases, instead
relying on the normal operation of the cyclic garbage collector.  This
avoids a whole class of interpreter-shutdown-time errors, usually
involving ‘__del__’ methods, that have plagued Python since the cyclic
GC was first introduced.

参见
....

PEP 442(2) – Safe object finalization

     PEP 由 Antoine Pitrou 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0442

   (2) https://www.python.org/dev/peps/pep-0442


File: python.info,  Node: PEP 456 Secure and Interchangeable Hash Algorithm,  Next: PEP 436 Argument Clinic,  Prev: PEP 442 Safe Object Finalization,  Up: CPython Implementation Changes

1.5.5.3 PEP 456: Secure and Interchangeable Hash Algorithm
..........................................................

PEP 456(1) follows up on earlier security fix work done on Python’s hash
algorithm to address certain DOS attacks to which public facing APIs
backed by dictionary lookups may be subject.  (See bpo-14621(2) for the
start of the current round of improvements.)  The PEP unifies CPython’s
hash code to make it easier for a packager to substitute a different
hash algorithm, and switches Python’s default implementation to a
SipHash implementation on platforms that have a 64 bit data type.  Any
performance differences in comparison with the older FNV algorithm are
trivial.

The PEP adds additional fields to the *note sys.hash_info: 929. named
tuple to describe the hash algorithm in use by the currently executing
binary.  Otherwise, the PEP does not alter any existing CPython APIs.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0456

   (2) https://bugs.python.org/issue14621


File: python.info,  Node: PEP 436 Argument Clinic,  Next: Other Build and C API Changes,  Prev: PEP 456 Secure and Interchangeable Hash Algorithm,  Up: CPython Implementation Changes

1.5.5.4 PEP 436: Argument Clinic
................................

"Argument Clinic" ( PEP 436(1)) is now part of the CPython build process
and can be used to simplify the process of defining and maintaining
accurate signatures for builtins and standard library extension modules
implemented in C.

Some standard library extension modules have been converted to use
Argument Clinic in Python 3.4, and *note pydoc: da. and *note inspect:
a1. have been updated accordingly.

It is expected that signature metadata for programmatic introspection
will be added to additional callables implemented in C as part of Python
3.4 maintenance releases.

     注解: The Argument Clinic PEP is not fully up to date with the
     state of the implementation.  This has been deemed acceptable by
     the release manager and core development team in this case, as
     Argument Clinic will not be made available as a public API for
     third party use in Python 3.4.

参见
....

PEP 436(2) – The Argument Clinic DSL

     PEP 由 Larry Hastings 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0436

   (2) https://www.python.org/dev/peps/pep-0436


File: python.info,  Node: Other Build and C API Changes,  Next: 其他改进<2>,  Prev: PEP 436 Argument Clinic,  Up: CPython Implementation Changes

1.5.5.5 Other Build and C API Changes
.....................................

   * The new *note PyType_GetSlot(): 92c. function has been added to the
     stable ABI, allowing retrieval of function pointers from named type
     slots when using the limited API. (Contributed by Martin von Löwis
     in bpo-17162(1).)

   * The new *note Py_SetStandardStreamEncoding(): 92d.
     pre-initialization API allows applications embedding the CPython
     interpreter to reliably force a particular encoding and error
     handler for the standard streams.  (Contributed by Bastien Montagne
     and Nick Coghlan in bpo-16129(2).)

   * Most Python C APIs that don’t mutate string arguments are now
     correctly marked as accepting ‘const char *’ rather than ‘char *’.
     (Contributed by Serhiy Storchaka in bpo-1772673(3).)

   * A new shell version of ‘python-config’ can be used even when a
     python interpreter is not available (for example, in cross
     compilation scenarios).

   * *note PyUnicode_FromFormat(): 7d4. now supports width and precision
     specifications for ‘%s’, ‘%A’, ‘%U’, ‘%V’, ‘%S’, and ‘%R’.
     (Contributed by Ysj Ray and Victor Stinner in bpo-7330(4).)

   * New function *note PyStructSequence_InitType2(): 92e. supplements
     the existing *note PyStructSequence_InitType(): 92f. function.  The
     difference is that it returns ‘0’ on success and ‘-1’ on failure.

   * The CPython source can now be compiled using the address sanity
     checking features of recent versions of GCC and clang: the false
     alarms in the small object allocator have been silenced.
     (Contributed by Dhiru Kholia in bpo-18596(5).)

   * The Windows build now uses Address Space Layout Randomization(6)
     and Data Execution Prevention(7).  (Contributed by Christian Heimes
     in bpo-16632(8).)

   * New function *note PyObject_LengthHint(): 930. is the C API
     equivalent of *note operator.length_hint(): 886.  (Contributed by
     Armin Ronacher in bpo-16148(9).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17162

   (2) https://bugs.python.org/issue16129

   (3) https://bugs.python.org/issue1772673

   (4) https://bugs.python.org/issue7330

   (5) https://bugs.python.org/issue18596

   (6) https://en.wikipedia.org/wiki/Address_space_layout_randomization

   (7) https://en.wikipedia.org/wiki/Data_Execution_Prevention

   (8) https://bugs.python.org/issue16632

   (9) https://bugs.python.org/issue16148


File: python.info,  Node: 其他改进<2>,  Next: Significant Optimizations,  Prev: Other Build and C API Changes,  Up: CPython Implementation Changes

1.5.5.6 其他改进
................

   * The *note python: 933. command has a new *note option: 934, ‘-I’,
     which causes it to run in "isolated mode", which means that *note
     sys.path: 490. contains neither the script’s directory nor the
     user’s ‘site-packages’ directory, and all ‘PYTHON*’ environment
     variables are ignored (it implies both ‘-s’ and ‘-E’).  Other
     restrictions may also be applied in the future, with the goal being
     to isolate the execution of a script from the user’s environment.
     This is appropriate, for example, when Python is used to run a
     system script.  On most POSIX systems it can and should be used in
     the ‘#!’ line of system scripts.  (Contributed by Christian Heimes
     in bpo-16499(1).)

   * Tab-completion is now enabled by default in the interactive
     interpreter on systems that support *note readline: df.  History is
     also enabled by default, and is written to (and read from) the file
     ‘~/.python-history’.  (Contributed by Antoine Pitrou and Éric
     Araujo in bpo-5845(2).)

   * Invoking the Python interpreter with ‘--version’ now outputs the
     version to standard output instead of standard error
     (bpo-18338(3)).  Similar changes were made to *note argparse: 6.
     (bpo-18920(4)) and other modules that have script-like invocation
     capabilities (bpo-18922(5)).

   * The CPython Windows installer now adds ‘.py’ to the ‘PATHEXT’
     variable when extensions are registered, allowing users to run a
     python script at the windows command prompt by just typing its name
     without the ‘.py’ extension.  (Contributed by Paul Moore in
     bpo-18569(6).)

   * A new ‘make’ target coverage-report(7) will build python, run the
     test suite, and generate an HTML coverage report for the C codebase
     using ‘gcov’ and lcov(8).

   * The ‘-R’ option to the *note python regression test suite: 935. now
     also checks for memory allocation leaks, using *note
     sys.getallocatedblocks(): 8ea.  (Contributed by Antoine Pitrou in
     bpo-13390(9).)

   * ‘python -m’ now works with namespace packages.

   * The *note stat: f5. module is now implemented in C, which means it
     gets the values for its constants from the C header files, instead
     of having the values hard-coded in the python module as was
     previously the case.

   * Loading multiple python modules from a single OS module (‘.so’,
     ‘.dll’) now works correctly (previously it silently returned the
     first python module in the file).  (Contributed by Václav Šmilauer
     in bpo-16421(10).)

   * A new opcode, *note LOAD_CLASSDEREF: 936, has been added to fix a
     bug in the loading of free variables in class bodies that could be
     triggered by certain uses of *note __prepare__: 505.  (Contributed
     by Benjamin Peterson in bpo-17853(11).)

   * A number of MemoryError-related crashes were identified and fixed
     by Victor Stinner using his PEP 445(12)-based ‘pyfailmalloc’ tool
     (bpo-18408(13), bpo-18520(14)).

   * The ‘pyvenv’ command now accepts a ‘--copies’ option to use copies
     rather than symlinks even on systems where symlinks are the
     default.  (Contributed by Vinay Sajip in bpo-18807(15).)

   * The ‘pyvenv’ command also accepts a ‘--without-pip’ option to
     suppress the otherwise-automatic bootstrapping of pip into the
     virtual environment.  (Contributed by Nick Coghlan in bpo-19552(16)
     as part of the PEP 453(17) implementation.)

   * The encoding name is now optional in the value set for the *note
     PYTHONIOENCODING: 937. environment variable.  This makes it
     possible to set just the error handler, without changing the
     default encoding.  (Contributed by Serhiy Storchaka in
     bpo-18818(18).)

   * The *note bz2: 14, *note lzma: ae, and *note gzip: 8c. module
     ‘open’ functions now support ‘x’ (exclusive creation) mode.
     (Contributed by Tim Heaney and Vajrasky Kok in bpo-19201(19),
     bpo-19222(20), and bpo-19223(21).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16499

   (2) https://bugs.python.org/issue5845

   (3) https://bugs.python.org/issue18338

   (4) https://bugs.python.org/issue18920

   (5) https://bugs.python.org/issue18922

   (6) https://bugs.python.org/issue18569

   (7) 
https://devguide.python.org/coverage/#measuring-coverage-of-c-code-with-gcov-and-lcov

   (8) http://ltp.sourceforge.net/coverage/lcov.php

   (9) https://bugs.python.org/issue13390

   (10) https://bugs.python.org/issue16421

   (11) https://bugs.python.org/issue17853

   (12) https://www.python.org/dev/peps/pep-0445

   (13) https://bugs.python.org/issue18408

   (14) https://bugs.python.org/issue18520

   (15) https://bugs.python.org/issue18807

   (16) https://bugs.python.org/issue19552

   (17) https://www.python.org/dev/peps/pep-0453

   (18) https://bugs.python.org/issue18818

   (19) https://bugs.python.org/issue19201

   (20) https://bugs.python.org/issue19222

   (21) https://bugs.python.org/issue19223


File: python.info,  Node: Significant Optimizations,  Prev: 其他改进<2>,  Up: CPython Implementation Changes

1.5.5.7 Significant Optimizations
.................................

   * The UTF-32 decoder is now 3x to 4x faster.  (Contributed by Serhiy
     Storchaka in bpo-14625(1).)

   * The cost of hash collisions for sets is now reduced.  Each hash
     table probe now checks a series of consecutive, adjacent key/hash
     pairs before continuing to make random probes through the hash
     table.  This exploits cache locality to make collision resolution
     less expensive.  The collision resolution scheme can be described
     as a hybrid of linear probing and open addressing.  The number of
     additional linear probes defaults to nine.  This can be changed at
     compile-time by defining LINEAR_PROBES to be any value.  Set
     LINEAR_PROBES=0 to turn-off linear probing entirely.  (Contributed
     by Raymond Hettinger in bpo-18771(2).)

   * The interpreter starts about 30% faster.  A couple of measures lead
     to the speedup.  The interpreter loads fewer modules on startup,
     e.g.  the *note re: de, *note collections: 1e. and *note locale:
     aa. modules and their dependencies are no longer imported by
     default.  The marshal module has been improved to load compiled
     Python code faster.  (Contributed by Antoine Pitrou, Christian
     Heimes and Victor Stinner in bpo-19219(3), bpo-19218(4),
     bpo-19209(5), bpo-19205(6) and bpo-9548(7).)

   * *note bz2.BZ2File: 939. is now as fast or faster than the Python2
     version for most cases.  *note lzma.LZMAFile: 93a. has also been
     optimized.  (Contributed by Serhiy Storchaka and Nadeem Vawda in
     bpo-16034(8).)

   * *note random.getrandbits(): 93b. is 20%-40% faster for small
     integers (the most common use case).  (Contributed by Serhiy
     Storchaka in bpo-16674(9).)

   * By taking advantage of the new storage format for strings, pickling
     of strings is now significantly faster.  (Contributed by Victor
     Stinner and Antoine Pitrou in bpo-15596(10).)

   * A performance issue in ‘io.FileIO.readall()’ has been solved.  This
     particularly affects Windows, and significantly speeds up the case
     of piping significant amounts of data through *note subprocess: fa.
     (Contributed by Richard Oudkerk in bpo-15758(11).)

   * *note html.escape(): 93c. is now 10x faster.  (Contributed by Matt
     Bryant in bpo-18020(12).)

   * On Windows, the native ‘VirtualAlloc’ is now used instead of the
     CRT ‘malloc’ in ‘obmalloc’.  Artificial benchmarks show about a 3%
     memory savings.

   * *note os.urandom(): 4d9. now uses a lazily-opened persistent file
     descriptor so as to avoid using many file descriptors when run in
     parallel from multiple threads.  (Contributed by Antoine Pitrou in
     bpo-18756(13).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14625

   (2) https://bugs.python.org/issue18771

   (3) https://bugs.python.org/issue19219

   (4) https://bugs.python.org/issue19218

   (5) https://bugs.python.org/issue19209

   (6) https://bugs.python.org/issue19205

   (7) https://bugs.python.org/issue9548

   (8) https://bugs.python.org/issue16034

   (9) https://bugs.python.org/issue16674

   (10) https://bugs.python.org/issue15596

   (11) https://bugs.python.org/issue15758

   (12) https://bugs.python.org/issue18020

   (13) https://bugs.python.org/issue18756


File: python.info,  Node: 弃用<4>,  Next: 移除<3>,  Prev: CPython Implementation Changes,  Up: Python 3 4 有什么新变化

1.5.6 弃用
----------

This section covers various APIs and other features that have been
deprecated in Python 3.4, and will be removed in Python 3.5 or later.
In most (but not all) cases, using the deprecated APIs will produce a
*note DeprecationWarning: 279. when the interpreter is run with
deprecation warnings enabled (for example, by using ‘-Wd’).

* Menu:

* Deprecations in the Python API::
* Deprecated Features::


File: python.info,  Node: Deprecations in the Python API,  Next: Deprecated Features,  Up: 弃用<4>

1.5.6.1 Deprecations in the Python API
......................................

   * As mentioned in *note PEP 451; A ModuleSpec Type for the Import
     System: 7e1, a number of *note importlib: 9b. methods and functions
     are deprecated: *note importlib.find_loader(): 93f. is replaced by
     *note importlib.util.find_spec(): 940.; *note
     importlib.machinery.PathFinder.find_module(): 941. is replaced by
     *note importlib.machinery.PathFinder.find_spec(): 942.; *note
     importlib.abc.MetaPathFinder.find_module(): 46a. is replaced by
     *note importlib.abc.MetaPathFinder.find_spec(): 46b.; *note
     importlib.abc.PathEntryFinder.find_loader(): 46c. and *note
     find_module(): 943. are replaced by *note
     importlib.abc.PathEntryFinder.find_spec(): 46d.; all of the
     ‘xxxLoader’ ABC ‘load_module’ methods (*note
     importlib.abc.Loader.load_module(): 5ec, *note
     importlib.abc.InspectLoader.load_module(): 944, *note
     importlib.abc.FileLoader.load_module(): 945, *note
     importlib.abc.SourceLoader.load_module(): 946.) should no longer be
     implemented, instead loaders should implement an ‘exec_module’
     method (*note importlib.abc.Loader.exec_module(): 5ed, *note
     importlib.abc.InspectLoader.exec_module(): 947. *note
     importlib.abc.SourceLoader.exec_module(): 948.) and let the import
     system take care of the rest; and *note
     importlib.abc.Loader.module_repr(): 949, *note
     importlib.util.module_for_loader(): 94a, *note
     importlib.util.set_loader(): 94b, and *note
     importlib.util.set_package(): 94c. are no longer needed because
     their functions are now handled automatically by the import system.

   * The *note imp: 9a. module is pending deprecation.  To keep
     compatibility with Python 2/3 code bases, the module’s removal is
     currently not scheduled.

   * The *note formatter: 82. module is pending deprecation and is
     slated for removal in Python 3.6.

   * ‘MD5’ as the default `digestmod' for the *note hmac.new(): 85d.
     function is deprecated.  Python 3.6 will require an explicit digest
     name or constructor as `digestmod' argument.

   * The internal ‘Netrc’ class in the *note ftplib: 84. module has been
     documented as deprecated in its docstring for quite some time.  It
     now emits a *note DeprecationWarning: 279. and will be removed
     completely in Python 3.5.

   * The undocumented `endtime' argument to *note
     subprocess.Popen.wait(): 59b. should not have been exposed and is
     hopefully not in use; it is deprecated and will mostly likely be
     removed in Python 3.5.

   * The `strict' argument of *note HTMLParser: 7c8. is deprecated.

   * The *note plistlib: d0. *note readPlist(): 487, *note writePlist():
     94d, *note readPlistFromBytes(): 488, and *note
     writePlistToBytes(): 94e. functions are deprecated in favor of the
     corresponding new functions *note load(): 894, *note dump(): 895,
     *note loads(): 896, and *note dumps(): 897.  *note Data(): 94f. is
     deprecated in favor of just using the *note bytes: 33a.
     constructor.

   * The *note sysconfig: ff. key ‘SO’ is deprecated, it has been
     replaced by ‘EXT_SUFFIX’.

   * The ‘U’ mode accepted by various ‘open’ functions is deprecated.
     In Python3 it does not do anything useful, and should be replaced
     by appropriate uses of *note io.TextIOWrapper: 5fc. (if needed) and
     its `newline' argument.

   * The `parser' argument of *note xml.etree.ElementTree.iterparse():
     950. has been deprecated, as has the `html' argument of *note
     XMLParser(): 253.  To prepare for the removal of the latter, all
     arguments to ‘XMLParser’ should be passed by keyword.


File: python.info,  Node: Deprecated Features,  Prev: Deprecations in the Python API,  Up: 弃用<4>

1.5.6.2 Deprecated Features
...........................

   * Running *note IDLE: 952. with the ‘-n’ flag (no subprocess) is
     deprecated.  However, the feature will not be removed until
     bpo-18823(1) is resolved.

   * The site module adding a "site-python" directory to sys.path, if it
     exists, is deprecated (bpo-19375(2)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18823

   (2) https://bugs.python.org/issue19375


File: python.info,  Node: 移除<3>,  Next: 移植到 Python 3 4,  Prev: 弃用<4>,  Up: Python 3 4 有什么新变化

1.5.7 移除
----------

* Menu:

* 不再支持的操作系统::
* API 与特性的移除: API 与特性的移除<5>.
* Code Cleanups::


File: python.info,  Node: 不再支持的操作系统,  Next: API 与特性的移除<5>,  Up: 移除<3>

1.5.7.1 不再支持的操作系统
..........................

从源代码和构建工具中删除了对以下操作系统的支持：

   * OS/2 (bpo-16135(1)).

   * Windows 2000（变更集e52df05b496a）。

   * Windows系统中 ‘COMSPEC’ 指向 ‘command.com’ 的版本（ bpo-14470(2) ）
     。

   * VMS (bpo-16136(3)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16135

   (2) https://bugs.python.org/issue14470

   (3) https://bugs.python.org/issue16136


File: python.info,  Node: API 与特性的移除<5>,  Next: Code Cleanups,  Prev: 不再支持的操作系统,  Up: 移除<3>

1.5.7.2 API 与特性的移除
........................

The following obsolete and previously deprecated APIs and features have
been removed:

   * The unmaintained ‘Misc/TextMate’ and ‘Misc/vim’ directories have
     been removed (see the devguide(1) for suggestions on what to use
     instead).

   * The ‘SO’ makefile macro is removed (it was replaced by the
     ‘SHLIB_SUFFIX’ and ‘EXT_SUFFIX’ macros) (bpo-16754(2)).

   * The ‘PyThreadState.tick_counter’ field has been removed; its value
     has been meaningless since Python 3.2, when the "new GIL" was
     introduced (bpo-19199(3)).

   * ‘PyLoader’ and ‘PyPycLoader’ have been removed from *note
     importlib: 9b.  (Contributed by Taras Lyapun in bpo-15641(4).)

   * The `strict' argument to *note HTTPConnection: 39a. and *note
     HTTPSConnection: 39b. has been removed.  HTTP 0.9-style "Simple
     Responses" are no longer supported.

   * The deprecated *note urllib.request.Request: 8fe. getter and setter
     methods ‘add_data’, ‘has_data’, ‘get_data’, ‘get_type’, ‘get_host’,
     ‘get_selector’, ‘set_proxy’, ‘get_origin_req_host’, and
     ‘is_unverifiable’ have been removed (use direct attribute access
     instead).

   * Support for loading the deprecated ‘TYPE_INT64’ has been removed
     from *note marshal: b1.  (Contributed by Dan Riti in bpo-15480(5).)

   * *note inspect.Signature: 6fc.: positional-only parameters are now
     required to have a valid name.

   * *note object.__format__(): 956. no longer accepts non-empty format
     strings, it now raises a *note TypeError: 193. instead.  Using a
     non-empty string has been deprecated since Python 3.2.  This change
     has been made to prevent a situation where previously working (but
     incorrect) code would start failing if an object gained a
     __format__ method, which means that your code may now raise a *note
     TypeError: 193. if you are using an ‘'s'’ format code with objects
     that do not have a __format__ method that handles it.  See
     bpo-7994(6) for background.

   * ‘difflib.SequenceMatcher.isbjunk()’ and
     ‘difflib.SequenceMatcher.isbpopular()’ were deprecated in 3.2, and
     have now been removed: use ‘x in sm.bjunk’ and ‘x in sm.bpopular’,
     where `sm' is a *note SequenceMatcher: 957. object (bpo-13248(7)).

   ---------- Footnotes ----------

   (1) https://devguide.python.org

   (2) https://bugs.python.org/issue16754

   (3) https://bugs.python.org/issue19199

   (4) https://bugs.python.org/issue15641

   (5) https://bugs.python.org/issue15480

   (6) https://bugs.python.org/issue7994

   (7) https://bugs.python.org/issue13248


File: python.info,  Node: Code Cleanups,  Prev: API 与特性的移除<5>,  Up: 移除<3>

1.5.7.3 Code Cleanups
.....................

   * The unused and undocumented internal ‘Scanner’ class has been
     removed from the *note pydoc: da. module.

   * The private and effectively unused ‘_gestalt’ module has been
     removed, along with the private *note platform: cf. functions
     ‘_mac_ver_lookup’, ‘_mac_ver_gstalt’, and ‘_bcd2str’, which would
     only have ever been called on badly broken OSX systems (see
     bpo-18393(1)).

   * The hardcoded copies of certain *note stat: f5. constants that were
     included in the *note tarfile: 102. module namespace have been
     removed.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18393


File: python.info,  Node: 移植到 Python 3 4,  Next: 3 4 3 的变化,  Prev: 移除<3>,  Up: Python 3 4 有什么新变化

1.5.8 移植到 Python 3.4
-----------------------

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

* Menu:

* ’python’ 命令行为的变化: 'python' 命令行为的变化<2>.
* Python API 的变化: Python API 的变化<6>.
* C API 的变化: C API 的变化<5>.


File: python.info,  Node: 'python' 命令行为的变化<2>,  Next: Python API 的变化<6>,  Up: 移植到 Python 3 4

1.5.8.1 ’python’ 命令行为的变化
...............................

   * In a posix shell, setting the ‘PATH’ environment variable to an
     empty value is equivalent to not setting it at all.  However,
     setting *note PYTHONPATH: 95b. to an empty value was `not'
     equivalent to not setting it at all: setting *note PYTHONPATH: 95b.
     to an empty value was equivalent to setting it to ‘.’, which leads
     to confusion when reasoning by analogy to how ‘PATH’ works.  The
     behavior now conforms to the posix convention for ‘PATH’.

   * The [X refs, Y blocks] output of a debug (‘--with-pydebug’) build
     of the CPython interpreter is now off by default.  It can be
     re-enabled using the ‘-X showrefcount’ option.  (Contributed by
     Ezio Melotti in bpo-17323(1).)

   * The python command and most stdlib scripts (as well as *note
     argparse: 6.) now output ‘--version’ information to ‘stdout’
     instead of ‘stderr’ (for issue list see *note 其他改进: 932.
     above).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17323


File: python.info,  Node: Python API 的变化<6>,  Next: C API 的变化<5>,  Prev: 'python' 命令行为的变化<2>,  Up: 移植到 Python 3 4

1.5.8.2 Python API 的变化
.........................

   * The ABCs defined in *note importlib.abc: 9c. now either raise the
     appropriate exception or return a default value instead of raising
     *note NotImplementedError: 617. blindly.  This will only affect
     code calling *note super(): 4eb. and falling through all the way to
     the ABCs.  For compatibility, catch both *note NotImplementedError:
     617. or the appropriate exception as needed.

   * The module type now initializes the *note __package__: 95d. and
     *note __loader__: 95e. attributes to ‘None’ by default.  To
     determine if these attributes were set in a backwards-compatible
     fashion, use e.g.  ‘getattr(module, '__loader__', None) is not
     None’.  (bpo-17115(1).)

   * *note importlib.util.module_for_loader(): 94a. now sets
     ‘__loader__’ and ‘__package__’ unconditionally to properly support
     reloading.  If this is not desired then you will need to set these
     attributes manually.  You can use ‘importlib.util.module_to_load()’
     for module management.

   * Import now resets relevant attributes (e.g.  ‘__name__’,
     ‘__loader__’, ‘__package__’, ‘__file__’, ‘__cached__’)
     unconditionally when reloading.  Note that this restores a pre-3.3
     behavior in that it means a module is re-found when re-loaded
     (bpo-19413(2)).

   * Frozen packages no longer set ‘__path__’ to a list containing the
     package name, they now set it to an empty list.  The previous
     behavior could cause the import system to do the wrong thing on
     submodule imports if there was also a directory with the same name
     as the frozen package.  The correct way to determine if a module is
     a package or not is to use ‘hasattr(module, '__path__')’
     (bpo-18065(3)).

   * Frozen modules no longer define a ‘__file__’ attribute.  It’s
     semantically incorrect for frozen modules to set the attribute as
     they are not loaded from any explicit location.  If you must know
     that a module comes from frozen code then you can see if the
     module’s ‘__spec__.location’ is set to ‘'frozen'’, check if the
     loader is a subclass of *note importlib.machinery.FrozenImporter:
     95f, or if Python 2 compatibility is necessary you can use
     ‘imp.is_frozen()’.

   * *note py_compile.compile(): 216. now raises *note FileExistsError:
     960. if the file path it would write to is a symlink or a
     non-regular file.  This is to act as a warning that import will
     overwrite those files with a regular file regardless of what type
     of file path they were originally.

   * *note importlib.abc.SourceLoader.get_source(): 961. no longer
     raises *note ImportError: 33d. when the source code being loaded
     triggers a *note SyntaxError: 460. or *note UnicodeDecodeError:
     1fe.  As *note ImportError: 33d. is meant to be raised only when
     source code cannot be found but it should, it was felt to be
     over-reaching/overloading of that meaning when the source code is
     found but improperly structured.  If you were catching ImportError
     before and wish to continue to ignore syntax or decoding issues,
     catch all three exceptions now.

   * *note functools.update_wrapper(): 962. and *note functools.wraps():
     873. now correctly set the ‘__wrapped__’ attribute to the function
     being wrapped, even if that function also had its ‘__wrapped__’
     attribute set.  This means ‘__wrapped__’ attributes now correctly
     link a stack of decorated functions rather than every ‘__wrapped__’
     attribute in the chain referring to the innermost function.
     Introspection libraries that assumed the previous behaviour was
     intentional can use *note inspect.unwrap(): 872. to access the
     first function in the chain that has no ‘__wrapped__’ attribute.

   * *note inspect.getfullargspec(): 566. has been reimplemented on top
     of *note inspect.signature(): 564. and hence handles a much wider
     variety of callable objects than it did in the past.  It is
     expected that additional builtin and extension module callables
     will gain signature metadata over the course of the Python 3.4
     series.  Code that assumes that *note inspect.getfullargspec():
     566. will fail on non-Python callables may need to be adjusted
     accordingly.

   * *note importlib.machinery.PathFinder: 963. now passes on the
     current working directory to objects in *note sys.path_hooks: 964.
     for the empty string.  This results in *note
     sys.path_importer_cache: 4a5. never containing ‘''’, thus iterating
     through *note sys.path_importer_cache: 4a5. based on *note
     sys.path: 490. will not find all keys.  A module’s ‘__file__’ when
     imported in the current working directory will also now have an
     absolute path, including when using ‘-m’ with the interpreter
     (except for ‘__main__.__file__’ when a script has been executed
     directly using a relative path) (Contributed by Brett Cannon in
     bpo-18416(4)).  is specified on the command-line) (bpo-18416(5)).

   * The removal of the `strict' argument to *note HTTPConnection: 39a.
     and *note HTTPSConnection: 39b. changes the meaning of the
     remaining arguments if you are specifying them positionally rather
     than by keyword.  If you’ve been paying attention to deprecation
     warnings your code should already be specifying any additional
     arguments via keywords.

   * Strings between ‘from __future__ import ...’ statements now
     `always' raise a *note SyntaxError: 460.  Previously if there was
     no leading docstring, an interstitial string would sometimes be
     ignored.  This brings CPython into compliance with the language
     spec; Jython and PyPy already were.  (bpo-17434(6)).

   * *note ssl.SSLSocket.getpeercert(): 8d9. and *note
     ssl.SSLSocket.do_handshake(): 763. now raise an *note OSError: 1d4.
     with ‘ENOTCONN’ when the ‘SSLSocket’ is not connected, instead of
     the previous behavior of raising an *note AttributeError: 3a3.  In
     addition, *note getpeercert(): 8d9. will raise a *note ValueError:
     1fc. if the handshake has not yet been done.

   * *note base64.b32decode(): 965. now raises a *note binascii.Error:
     966. when the input string contains non-b32-alphabet characters,
     instead of a *note TypeError: 193.  This particular *note
     TypeError: 193. was missed when the other *note TypeError: 193.s
     were converted.  (Contributed by Serhiy Storchaka in bpo-18011(7).)
     Note: this change was also inadvertently applied in Python 3.3.3.

   * The ‘file’ attribute is now automatically closed when the creating
     ‘cgi.FieldStorage’ instance is garbage collected.  If you were
     pulling the file object out separately from the ‘cgi.FieldStorage’
     instance and not keeping the instance alive, then you should either
     store the entire ‘cgi.FieldStorage’ instance or read the contents
     of the file before the ‘cgi.FieldStorage’ instance is garbage
     collected.

   * Calling ‘read’ or ‘write’ on a closed SSL socket now raises an
     informative *note ValueError: 1fc. rather than the previous more
     mysterious *note AttributeError: 3a3. (bpo-9177(8)).

   * *note slice.indices(): 967. no longer produces an *note
     OverflowError: 968. for huge values.  As a consequence of this fix,
     *note slice.indices(): 967. now raises a *note ValueError: 1fc. if
     given a negative length; previously it returned nonsense values
     (bpo-14794(9)).

   * The *note complex: 18a. constructor, unlike the *note cmath: 19.
     functions, was incorrectly accepting *note float: 188. values if an
     object’s ‘__complex__’ special method returned one.  This now
     raises a *note TypeError: 193.  (bpo-16290(10).)

   * The *note int: 185. constructor in 3.2 and 3.3 erroneously accepts
     *note float: 188. values for the `base' parameter.  It is unlikely
     anyone was doing this, but if so, it will now raise a *note
     TypeError: 193. (bpo-16772(11)).

   * Defaults for keyword-only arguments are now evaluated `after'
     defaults for regular keyword arguments, instead of before.
     Hopefully no one wrote any code that depends on the previous buggy
     behavior (bpo-16967(12)).

   * Stale thread states are now cleared after *note fork(): 969.  This
     may cause some system resources to be released that previously were
     incorrectly kept perpetually alive (for example, database
     connections kept in thread-local storage).  (bpo-17094(13).)

   * Parameter names in ‘__annotations__’ dicts are now mangled
     properly, similarly to ‘__kwdefaults__’.  (Contributed by Yury
     Selivanov in bpo-20625(14).)

   * *note hashlib.hash.name: 85b. now always returns the identifier in
     lower case.  Previously some builtin hashes had uppercase names,
     but now that it is a formal public interface the naming has been
     made consistent (bpo-18532(15)).

   * Because *note unittest.TestSuite: 6d7. now drops references to
     tests after they are run, test harnesses that re-use a *note
     TestSuite: 6d7. to re-run a set of tests may fail.  Test suites
     should not be re-used in this fashion since it means state is
     retained between test runs, breaking the test isolation that *note
     unittest: 11c. is designed to provide.  However, if the lack of
     isolation is considered acceptable, the old behavior can be
     restored by creating a *note TestSuite: 6d7. subclass that defines
     a ‘_removeTestAtIndex’ method that does nothing (see *note
     TestSuite.__iter__(): 96a.) (bpo-11798(16)).

   * *note unittest: 11c. now uses *note argparse: 6. for command line
     parsing.  There are certain invalid command forms that used to work
     that are no longer allowed; in theory this should not cause
     backward compatibility issues since the disallowed command forms
     didn’t make any sense and are unlikely to be in use.

   * The *note re.split(): 3d2, *note re.findall(): 96b, and *note
     re.sub(): 483. functions, and the ‘group()’ and ‘groups()’ methods
     of ‘match’ objects now always return a `bytes' object when the
     string to be matched is a *note bytes-like object: 5f1.  Previously
     the return type matched the input type, so if your code was
     depending on the return value being, say, a ‘bytearray’, you will
     need to change your code.

   * *note audioop: d. functions now raise an error immediately if
     passed string input, instead of failing randomly later on
     (bpo-16685(17)).

   * The new `convert_charrefs' argument to *note HTMLParser: 7c8.
     currently defaults to ‘False’ for backward compatibility, but will
     eventually be changed to default to ‘True’.  It is recommended that
     you add this keyword, with the appropriate value, to any *note
     HTMLParser: 7c8. calls in your code (bpo-13633(18)).

   * Since the `digestmod' argument to the *note hmac.new(): 85d.
     function will in the future have no default, all calls to *note
     hmac.new(): 85d. should be changed to explicitly specify a
     `digestmod' (bpo-17276(19)).

   * Calling *note sysconfig.get_config_var(): 96c. with the ‘SO’ key,
     or looking ‘SO’ up in the results of a call to *note
     sysconfig.get_config_vars(): 96d. is deprecated.  This key should
     be replaced by ‘EXT_SUFFIX’ or ‘SHLIB_SUFFIX’, depending on the
     context (bpo-19555(20)).

   * Any calls to ‘open’ functions that specify ‘U’ should be modified.
     ‘U’ is ineffective in Python3 and will eventually raise an error if
     used.  Depending on the function, the equivalent of its old Python2
     behavior can be achieved using either a `newline' argument, or if
     necessary by wrapping the stream in *note TextIOWrapper: 5fc. to
     use its `newline' argument (bpo-15204(21)).

   * If you use ‘pyvenv’ in a script and desire that pip `not' be
     installed, you must add ‘--without-pip’ to your command invocation.

   * The default behavior of *note json.dump(): 60d. and *note
     json.dumps(): 60e. when an indent is specified has changed: it no
     longer produces trailing spaces after the item separating commas at
     the ends of lines.  This will matter only if you have tests that
     are doing white-space-sensitive comparisons of such output
     (bpo-16333(22)).

   * *note doctest: 67. now looks for doctests in extension module
     ‘__doc__’ strings, so if your doctest test discovery includes
     extension modules that have things that look like doctests in them
     you may see test failures you’ve never seen before when running
     your tests (bpo-3158(23)).

   * The *note collections.abc: 1f. module has been slightly refactored
     as part of the Python startup improvements.  As a consequence of
     this, it is no longer the case that importing *note collections:
     1e. automatically imports *note collections.abc: 1f.  If your
     program depended on the (undocumented) implicit import, you will
     need to add an explicit ‘import collections.abc’ (bpo-20784(24)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17115

   (2) https://bugs.python.org/issue19413

   (3) https://bugs.python.org/issue18065

   (4) https://bugs.python.org/issue18416

   (5) https://bugs.python.org/issue18416

   (6) https://bugs.python.org/issue17434

   (7) https://bugs.python.org/issue18011

   (8) https://bugs.python.org/issue9177

   (9) https://bugs.python.org/issue14794

   (10) https://bugs.python.org/issue16290

   (11) https://bugs.python.org/issue16772

   (12) https://bugs.python.org/issue16967

   (13) https://bugs.python.org/issue17094

   (14) https://bugs.python.org/issue20625

   (15) https://bugs.python.org/issue18532

   (16) https://bugs.python.org/issue11798

   (17) https://bugs.python.org/issue16685

   (18) https://bugs.python.org/issue13633

   (19) https://bugs.python.org/issue17276

   (20) https://bugs.python.org/issue19555

   (21) https://bugs.python.org/issue15204

   (22) https://bugs.python.org/issue16333

   (23) https://bugs.python.org/issue3158

   (24) https://bugs.python.org/issue20784


File: python.info,  Node: C API 的变化<5>,  Prev: Python API 的变化<6>,  Up: 移植到 Python 3 4

1.5.8.3 C API 的变化
....................

   * *note PyEval_EvalFrameEx(): 96f, *note PyObject_Repr(): 970, and
     *note PyObject_Str(): 971, along with some other internal C APIs,
     now include a debugging assertion that ensures they are not used in
     situations where they may silently discard a currently active
     exception.  In cases where discarding the active exception is
     expected and desired (for example, because it has already been
     saved locally with *note PyErr_Fetch(): 972. or is being
     deliberately replaced with a different exception), an explicit
     *note PyErr_Clear(): 973. call will be needed to avoid triggering
     the assertion when invoking these operations (directly or
     indirectly) and running against a version of Python that is
     compiled with assertions enabled.

   * *note PyErr_SetImportError(): 601. now sets *note TypeError: 193.
     when its `msg' argument is not set.  Previously only ‘NULL’ was
     returned with no exception set.

   * The result of the *note PyOS_ReadlineFunctionPointer: 974. callback
     must now be a string allocated by *note PyMem_RawMalloc(): 975. or
     *note PyMem_RawRealloc(): 976, or ‘NULL’ if an error occurred,
     instead of a string allocated by *note PyMem_Malloc(): 50d. or
     *note PyMem_Realloc(): 977. (bpo-16742(1))

   * *note PyThread_set_key_value(): 978. now always set the value.  In
     Python 3.3, the function did nothing if the key already exists (if
     the current value is a non-‘NULL’ pointer).

   * The ‘f_tstate’ (thread state) field of the *note PyFrameObject:
     979. structure has been removed to fix a bug: see bpo-14432(2) for
     the rationale.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16742

   (2) https://bugs.python.org/issue14432


File: python.info,  Node: 3 4 3 的变化,  Prev: 移植到 Python 3 4,  Up: Python 3 4 有什么新变化

1.5.9 3.4.3 的变化
------------------

* Menu:

* PEP 476; Enabling certificate verification by default for stdlib http clients: PEP 476 Enabling certificate verification by default for stdlib http clients.


File: python.info,  Node: PEP 476 Enabling certificate verification by default for stdlib http clients,  Up: 3 4 3 的变化

1.5.9.1 PEP 476: Enabling certificate verification by default for stdlib http clients
.....................................................................................

*note http.client: 94. and modules which use it, such as *note
urllib.request: 121. and *note xmlrpc.client: 140, will now verify that
the server presents a certificate which is signed by a CA in the
platform trust store and whose hostname matches the hostname being
requested by default, significantly improving security for many
applications.

For applications which require the old previous behavior, they can pass
an alternate context:

     import urllib.request
     import ssl

     # This disables all verification
     context = ssl._create_unverified_context()

     # This allows using a specific certificate for the host, which doesn't need
     # to be in the trust store
     context = ssl.create_default_context(cafile="/path/to/file.crt")

     urllib.request.urlopen("https://invalid-cert", context=context)


File: python.info,  Node: Python 3 3 有什么新变化,  Next: Python 3 2 有什么新变化,  Prev: Python 3 4 有什么新变化,  Up: Python的新变化

1.6 Python 3.3 有什么新变化
===========================

本文介绍了Python 3.3相比 3.2 的新增特性。Python 3.3于2012年9月29日发布。
有关完整详细信息，请参见 changelog(1)。

参见
....

PEP 398(2) - Python 3.3 发布计划

* Menu:

* 摘要 - 发布重点: 摘要 - 发布重点<6>.
* PEP 405; 虚拟环境: PEP 405 虚拟环境.
* PEP 420; 隐式命名空间包: PEP 420 隐式命名空间包.
* PEP 3118; 新的内存视图实现和缓冲协议文档: PEP 3118 新的内存视图实现和缓冲协议文档.
* PEP 393; 灵活的字符串表示: PEP 393 灵活的字符串表示.
* PEP 397; 适用于Windows的Python启动器: PEP 397 适用于Windows的Python启动器.
* PEP 3151; 重写 OS 和 IO 异常的层次结构: PEP 3151 重写 OS 和 IO 异常的层次结构.
* PEP 380; 委托给子生成器的语法: PEP 380 委托给子生成器的语法.
* PEP 409; 清除异常上下文: PEP 409 清除异常上下文.
* PEP 414; 显式的Unicode文本: PEP 414 显式的Unicode文本.
* PEP 3155; 类和函数的限定名称: PEP 3155 类和函数的限定名称.
* PEP 412; Key-Sharing Dictionary: PEP 412 Key-Sharing Dictionary.
* PEP 362; 函数签名对象: PEP 362 函数签名对象.
* PEP 421; 添加 sys.implementation: PEP 421 添加 sys implementation.
* Using importlib as the Implementation of Import::
* 其他语言特性修改: 其他语言特性修改<6>.
* A Finer-Grained Import Lock::
* Builtin functions and types::
* 新增模块: 新增模块<6>.
* 改进的模块: 改进的模块<6>.
* 性能优化: 性能优化<5>.
* 构建和 C API 的改变: 构建和 C API 的改变<4>.
* 弃用: 弃用<5>.
* 移植到 Python 3.3: 移植到 Python 3 3.

   ---------- Footnotes ----------

   (1) https://docs.python.org/3.3/whatsnew/changelog.html

   (2) https://www.python.org/dev/peps/pep-0398


File: python.info,  Node: 摘要 - 发布重点<6>,  Next: PEP 405 虚拟环境,  Up: Python 3 3 有什么新变化

1.6.1 摘要 - 发布重点
---------------------

新的语法特性：

   * New ‘yield from’ expression for *note generator delegation: 980.

   * The ‘u'unicode'’ syntax is accepted again for *note str: 339.
     objects.

新的库模块：

   * *note faulthandler: 7d. （帮助调试低级崩溃）

   * *note ipaddress: a3. (high-level objects representing IP addresses
     and masks)

   * *note lzma: ae. (compress data using the XZ / LZMA algorithm)

   * *note unittest.mock: 11d. (replace parts of your system under test
     with mock objects)

   * *note venv: 126. (Python *note virtual environments: 981, as in the
     popular ‘virtualenv’ package)

新的内置特性：

   * 重写 *note I/O 异常的层次结构: 982.

实现的改进：

   * 基于 *note importlib: 9b. 重写 *note import machinery: 983.

   * More compact *note unicode strings: 984.

   * More compact *note attribute dictionaries: 985.

显着改进的库模块：

   * C Accelerator for the *note decimal: 986. module.

   * Better unicode handling in the *note email: 987. module (*note
     provisional: 988.).

安全改进：

   * Hash randomization is switched on by default.

Please read on for a comprehensive list of user-facing changes.


File: python.info,  Node: PEP 405 虚拟环境,  Next: PEP 420 隐式命名空间包,  Prev: 摘要 - 发布重点<6>,  Up: Python 3 3 有什么新变化

1.6.2 PEP 405: 虚拟环境
-----------------------

Virtual environments help create separate Python setups while sharing a
system-wide base install, for ease of maintenance.  Virtual environments
have their own set of private site packages (i.e.  locally-installed
libraries), and are optionally segregated from the system-wide site
packages.  Their concept and implementation are inspired by the popular
‘virtualenv’ third-party package, but benefit from tighter integration
with the interpreter core.

This PEP adds the *note venv: 126. module for programmatic access, and
the ‘pyvenv’ script for command-line access and administration.  The
Python interpreter checks for a ‘pyvenv.cfg’, file whose existence
signals the base of a virtual environment’s directory tree.

参见
....

PEP 405(1) - Python虚拟环境

     PEP 由 Carl Meyer 撰写 ; 由 Carl Meyer 和 Vinay Sajip 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0405


File: python.info,  Node: PEP 420 隐式命名空间包,  Next: PEP 3118 新的内存视图实现和缓冲协议文档,  Prev: PEP 405 虚拟环境,  Up: Python 3 3 有什么新变化

1.6.3 PEP 420: 隐式命名空间包
-----------------------------

Native support for package directories that don’t require ‘__init__.py’
marker files and can automatically span multiple path segments (inspired
by various third party approaches to namespace packages, as described in
PEP 420(1))

参见
....

PEP 420(2) - 隐式命名空间包

     PEP 由 Eric V. Smith 撰写，由 Eric V. Smith 和 Barry Warsaw 实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0420

   (2) https://www.python.org/dev/peps/pep-0420


File: python.info,  Node: PEP 3118 新的内存视图实现和缓冲协议文档,  Next: PEP 393 灵活的字符串表示,  Prev: PEP 420 隐式命名空间包,  Up: Python 3 3 有什么新变化

1.6.4 PEP 3118: 新的内存视图实现和缓冲协议文档
----------------------------------------------

The implementation of PEP 3118(1) has been significantly improved.

The new memoryview implementation comprehensively fixes all ownership
and lifetime issues of dynamically allocated fields in the Py_buffer
struct that led to multiple crash reports.  Additionally, several
functions that crashed or returned incorrect results for non-contiguous
or multi-dimensional input have been fixed.

The memoryview object now has a PEP-3118 compliant getbufferproc() that
checks the consumer’s request type.  Many new features have been added,
most of them work in full generality for non-contiguous arrays and
arrays with suboffsets.

The documentation has been updated, clearly spelling out
responsibilities for both exporters and consumers.  Buffer request flags
are grouped into basic and compound flags.  The memory layout of
non-contiguous and multi-dimensional NumPy-style arrays is explained.

* Menu:

* 相关特性::
* API changes::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3118


File: python.info,  Node: 相关特性,  Next: API changes,  Up: PEP 3118 新的内存视图实现和缓冲协议文档

1.6.4.1 相关特性
................

   * All native single character format specifiers in struct module
     syntax (optionally prefixed with ’@’) are now supported.

   * With some restrictions, the cast() method allows changing of format
     and shape of C-contiguous arrays.

   * Multi-dimensional list representations are supported for any array
     type.

   * Multi-dimensional comparisons are supported for any array type.

   * One-dimensional memoryviews of hashable (read-only) types with
     formats B, b or c are now hashable.  (Contributed by Antoine Pitrou
     in bpo-13411(1).)

   * Arbitrary slicing of any 1-D arrays type is supported.  For
     example, it is now possible to reverse a memoryview in O(1) by
     using a negative step.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13411


File: python.info,  Node: API changes,  Prev: 相关特性,  Up: PEP 3118 新的内存视图实现和缓冲协议文档

1.6.4.2 API changes
...................

   * The maximum number of dimensions is officially limited to 64.

   * The representation of empty shape, strides and suboffsets is now an
     empty tuple instead of ‘None’.

   * Accessing a memoryview element with format ’B’ (unsigned bytes) now
     returns an integer (in accordance with the struct module syntax).
     For returning a bytes object the view must be cast to ’c’ first.

   * memoryview comparisons now use the logical structure of the
     operands and compare all array elements by value.  All format
     strings in struct module syntax are supported.  Views with
     unrecognised format strings are still permitted, but will always
     compare as unequal, regardless of view contents.

   * For further changes see *note Build and C API Changes: 98f. and
     *note Porting C code: 990.

（由 Stefan Krah 在 bpo-10181(1) 中贡献。）

参见
....

PEP 3118(2) - 修改缓冲区协议

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10181

   (2) https://www.python.org/dev/peps/pep-3118


File: python.info,  Node: PEP 393 灵活的字符串表示,  Next: PEP 397 适用于Windows的Python启动器,  Prev: PEP 3118 新的内存视图实现和缓冲协议文档,  Up: Python 3 3 有什么新变化

1.6.5 PEP 393: 灵活的字符串表示
-------------------------------

The Unicode string type is changed to support multiple internal
representations, depending on the character with the largest Unicode
ordinal (1, 2, or 4 bytes) in the represented string.  This allows a
space-efficient representation in common cases, but gives access to full
UCS-4 on all systems.  For compatibility with existing APIs, several
representations may exist in parallel; over time, this compatibility
should be phased out.

On the Python side, there should be no downside to this change.

On the C API side, PEP 393(1) is fully backward compatible.  The legacy
API should remain available at least five years.  Applications using the
legacy API will not fully benefit of the memory reduction, or - worse -
may use a bit more memory, because Python may have to maintain two
versions of each string (in the legacy format and in the new efficient
storage).

* Menu:

* Functionality::
* Performance and resource usage::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393


File: python.info,  Node: Functionality,  Next: Performance and resource usage,  Up: PEP 393 灵活的字符串表示

1.6.5.1 Functionality
.....................

Changes introduced by PEP 393(1) are the following:

   * Python now always supports the full range of Unicode code points,
     including non-BMP ones (i.e.  from ‘U+0000’ to ‘U+10FFFF’).  The
     distinction between narrow and wide builds no longer exists and
     Python now behaves like a wide build, even under Windows.

   * With the death of narrow builds, the problems specific to narrow
     builds have also been fixed, for example:

        * *note len(): 151. now always returns 1 for non-BMP characters,
          so ‘len('\U0010FFFF') == 1’;

        * surrogate pairs are not recombined in string literals, so
          ‘'\uDBFF\uDFFF' != '\U0010FFFF'’;

        * indexing or slicing non-BMP characters returns the expected
          value, so ‘'\U0010FFFF'[0]’ now returns ‘'\U0010FFFF'’ and not
          ‘'\uDBFF'’;

        * all other functions in the standard library now correctly
          handle non-BMP code points.

   * The value of *note sys.maxunicode: 993. is now always ‘1114111’
     (‘0x10FFFF’ in hexadecimal).  The ‘PyUnicode_GetMax()’ function
     still returns either ‘0xFFFF’ or ‘0x10FFFF’ for backward
     compatibility, and it should not be used with the new Unicode API
     (see bpo-13054(2)).

   * The ‘./configure’ flag ‘--with-wide-unicode’ has been removed.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393

   (2) https://bugs.python.org/issue13054


File: python.info,  Node: Performance and resource usage,  Prev: Functionality,  Up: PEP 393 灵活的字符串表示

1.6.5.2 Performance and resource usage
......................................

The storage of Unicode strings now depends on the highest code point in
the string:

   * pure ASCII and Latin1 strings (‘U+0000-U+00FF’) use 1 byte per code
     point;

   * BMP strings (‘U+0000-U+FFFF’) use 2 bytes per code point;

   * non-BMP strings (‘U+10000-U+10FFFF’) use 4 bytes per code point.

The net effect is that for most applications, memory usage of string
storage should decrease significantly - especially compared to former
wide unicode builds - as, in many cases, strings will be pure ASCII even
in international contexts (because many strings store non-human language
data, such as XML fragments, HTTP headers, JSON-encoded data, etc.).  We
also hope that it will, for the same reasons, increase CPU cache
efficiency on non-trivial applications.  The memory usage of Python 3.3
is two to three times smaller than Python 3.2, and a little bit better
than Python 2.7, on a Django benchmark (see the PEP for details).

参见
....

PEP 393(1) - 灵活的字符串表示

     PEP 由 Martin von Löwis 撰写 ; 由 Torsten Becker 和 Martin von
     Löwis 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393


File: python.info,  Node: PEP 397 适用于Windows的Python启动器,  Next: PEP 3151 重写 OS 和 IO 异常的层次结构,  Prev: PEP 393 灵活的字符串表示,  Up: Python 3 3 有什么新变化

1.6.6 PEP 397: 适用于Windows的Python启动器
------------------------------------------

The Python 3.3 Windows installer now includes a ‘py’ launcher
application that can be used to launch Python applications in a version
independent fashion.

This launcher is invoked implicitly when double-clicking ‘*.py’ files.
If only a single Python version is installed on the system, that version
will be used to run the file.  If multiple versions are installed, the
most recent version is used by default, but this can be overridden by
including a Unix-style "shebang line" in the Python script.

The launcher can also be used explicitly from the command line as the
‘py’ application.  Running ‘py’ follows the same version selection rules
as implicitly launching scripts, but a more specific version can be
selected by passing appropriate arguments (such as ‘-3’ to request
Python 3 when Python 2 is also installed, or ‘-2.6’ to specifically
request an earlier Python version when a more recent version is
installed).

In addition to the launcher, the Windows installer now includes an
option to add the newly installed Python to the system PATH.
(Contributed by Brian Curtin in bpo-3561(1).)

参见
....

PEP 397(2) - 适用于Windows的Python启动器

     PEP 由 Mark Hammond 和 Martin v.  Löwis 撰写 ; 由 Vinay Sajip实现。

Launcher documentation: *note 适用于Windows的Python启动器: 997.

Installer PATH modification: *note 查找Python可执行文件: 998.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3561

   (2) https://www.python.org/dev/peps/pep-0397


File: python.info,  Node: PEP 3151 重写 OS 和 IO 异常的层次结构,  Next: PEP 380 委托给子生成器的语法,  Prev: PEP 397 适用于Windows的Python启动器,  Up: Python 3 3 有什么新变化

1.6.7 PEP 3151: 重写 OS 和 IO 异常的层次结构
--------------------------------------------

The hierarchy of exceptions raised by operating system errors is now
both simplified and finer-grained.

You don’t have to worry anymore about choosing the appropriate exception
type between *note OSError: 1d4, *note IOError: 99a, *note
EnvironmentError: 99b, *note WindowsError: 99c, ‘mmap.error’, *note
socket.error: 99d. or *note select.error: 99e.  All these exception
types are now only one: *note OSError: 1d4.  The other names are kept as
aliases for compatibility reasons.

Also, it is now easier to catch a specific error condition.  Instead of
inspecting the ‘errno’ attribute (or ‘args[0]’) for a particular
constant from the *note errno: 7c. module, you can catch the adequate
*note OSError: 1d4. subclass.  The available subclasses are the
following:

   * *note BlockingIOError: 99f.

   * *note ChildProcessError: 9a0.

   * *note ConnectionError: 6ef.

   * *note FileExistsError: 960.

   * *note FileNotFoundError: 7c9.

   * *note InterruptedError: 662.

   * *note IsADirectoryError: 9a1.

   * *note NotADirectoryError: 9a2.

   * *note PermissionError: 608.

   * *note ProcessLookupError: 9a3.

   * *note TimeoutError: 9a4.

And the *note ConnectionError: 6ef. itself has finer-grained subclasses:

   * *note BrokenPipeError: 9a5.

   * *note ConnectionAbortedError: 9a6.

   * *note ConnectionRefusedError: 9a7.

   * *note ConnectionResetError: 9a8.

Thanks to the new exceptions, common usages of the *note errno: 7c. can
now be avoided.  For example, the following code written for Python 3.2:

     from errno import ENOENT, EACCES, EPERM

     try:
         with open("document.txt") as f:
             content = f.read()
     except IOError as err:
         if err.errno == ENOENT:
             print("document.txt file is missing")
         elif err.errno in (EACCES, EPERM):
             print("You are not allowed to read document.txt")
         else:
             raise

can now be written without the *note errno: 7c. import and without
manual inspection of exception attributes:

     try:
         with open("document.txt") as f:
             content = f.read()
     except FileNotFoundError:
         print("document.txt file is missing")
     except PermissionError:
         print("You are not allowed to read document.txt")

参见
....

PEP 3151(1) - 重写 OS 和 IO 异常的层次结构

     PEP 由 Antoine Pitrou 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3151


File: python.info,  Node: PEP 380 委托给子生成器的语法,  Next: PEP 409 清除异常上下文,  Prev: PEP 3151 重写 OS 和 IO 异常的层次结构,  Up: Python 3 3 有什么新变化

1.6.8 PEP 380: 委托给子生成器的语法
-----------------------------------

PEP 380 adds the ‘yield from’ expression, allowing a *note generator:
9aa. to delegate part of its operations to another generator.  This
allows a section of code containing *note yield: 190. to be factored out
and placed in another generator.  Additionally, the subgenerator is
allowed to return with a value, and the value is made available to the
delegating generator.

While designed primarily for use in delegating to a subgenerator, the
‘yield from’ expression actually allows delegation to arbitrary
subiterators.

For simple iterators, ‘yield from iterable’ is essentially just a
shortened form of ‘for item in iterable: yield item’:

     >>> def g(x):
     ...     yield from range(x, 0, -1)
     ...     yield from range(x)
     ...
     >>> list(g(5))
     [5, 4, 3, 2, 1, 0, 1, 2, 3, 4]

However, unlike an ordinary loop, ‘yield from’ allows subgenerators to
receive sent and thrown values directly from the calling scope, and
return a final value to the outer generator:

     >>> def accumulate():
     ...     tally = 0
     ...     while 1:
     ...         next = yield
     ...         if next is None:
     ...             return tally
     ...         tally += next
     ...
     >>> def gather_tallies(tallies):
     ...     while 1:
     ...         tally = yield from accumulate()
     ...         tallies.append(tally)
     ...
     >>> tallies = []
     >>> acc = gather_tallies(tallies)
     >>> next(acc)  # Ensure the accumulator is ready to accept values
     >>> for i in range(4):
     ...     acc.send(i)
     ...
     >>> acc.send(None)  # Finish the first tally
     >>> for i in range(5):
     ...     acc.send(i)
     ...
     >>> acc.send(None)  # Finish the second tally
     >>> tallies
     [6, 10]

The main principle driving this change is to allow even generators that
are designed to be used with the ‘send’ and ‘throw’ methods to be split
into multiple subgenerators as easily as a single large function can be
split into multiple subfunctions.

参见
....

PEP 380(1) - 委托给子生成器的语法

     PEP 由 Greg Ewing 撰写，由 Greg Ewing 实现。由 Renaud Blanch，Ryan
     Kelly 和 Nick Coghlan 集成到3.3，由 Zbigniew Jędrzejewski-Szmek 和
     Nick Coghlan 编写文档

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0380


File: python.info,  Node: PEP 409 清除异常上下文,  Next: PEP 414 显式的Unicode文本,  Prev: PEP 380 委托给子生成器的语法,  Up: Python 3 3 有什么新变化

1.6.9 PEP 409: 清除异常上下文
-----------------------------

PEP 409 introduces new syntax that allows the display of the chained
exception context to be disabled.  This allows cleaner error messages in
applications that convert between exception types:

     >>> class D:
     ...     def __init__(self, extra):
     ...         self._extra_attributes = extra
     ...     def __getattr__(self, attr):
     ...         try:
     ...             return self._extra_attributes[attr]
     ...         except KeyError:
     ...             raise AttributeError(attr) from None
     ...
     >>> D({}).x
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
       File "<stdin>", line 8, in __getattr__
     AttributeError: x

Without the ‘from None’ suffix to suppress the cause, the original
exception would be displayed by default:

     >>> class C:
     ...     def __init__(self, extra):
     ...         self._extra_attributes = extra
     ...     def __getattr__(self, attr):
     ...         try:
     ...             return self._extra_attributes[attr]
     ...         except KeyError:
     ...             raise AttributeError(attr)
     ...
     >>> C({}).x
     Traceback (most recent call last):
       File "<stdin>", line 6, in __getattr__
     KeyError: 'x'

     During handling of the above exception, another exception occurred:

     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
       File "<stdin>", line 8, in __getattr__
     AttributeError: x

No debugging capability is lost, as the original exception context
remains available if needed (for example, if an intervening library has
incorrectly suppressed valuable underlying details):

     >>> try:
     ...     D({}).x
     ... except AttributeError as exc:
     ...     print(repr(exc.__context__))
     ...
     KeyError('x',)

参见
....

PEP 409(1) - 清除异常上下文

     PEP 由 Ethan Furman 撰写 ，由 Ethan Furman 和 Nick Coghlan 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0409


File: python.info,  Node: PEP 414 显式的Unicode文本,  Next: PEP 3155 类和函数的限定名称,  Prev: PEP 409 清除异常上下文,  Up: Python 3 3 有什么新变化

1.6.10 PEP 414: 显式的Unicode文本
---------------------------------

To ease the transition from Python 2 for Unicode aware Python
applications that make heavy use of Unicode literals, Python 3.3 once
again supports the "‘u’" prefix for string literals.  This prefix has no
semantic significance in Python 3, it is provided solely to reduce the
number of purely mechanical changes in migrating to Python 3, making it
easier for developers to focus on the more significant semantic changes
(such as the stricter default separation of binary and text data).

参见
....

PEP 414(1) - 显式的Unicode文本

     PEP 由 Armin Ronacher 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0414


File: python.info,  Node: PEP 3155 类和函数的限定名称,  Next: PEP 412 Key-Sharing Dictionary,  Prev: PEP 414 显式的Unicode文本,  Up: Python 3 3 有什么新变化

1.6.11 PEP 3155: 类和函数的限定名称
-----------------------------------

Functions and class objects have a new ‘__qualname__’ attribute
representing the "path" from the module top-level to their definition.
For global functions and classes, this is the same as ‘__name__’.  For
other functions and classes, it provides better information about where
they were actually defined, and how they might be accessible from the
global scope.

Example with (non-bound) methods:

     >>> class C:
     ...     def meth(self):
     ...         pass
     >>> C.meth.__name__
     'meth'
     >>> C.meth.__qualname__
     'C.meth'

Example with nested classes:

     >>> class C:
     ...     class D:
     ...         def meth(self):
     ...             pass
     ...
     >>> C.D.__name__
     'D'
     >>> C.D.__qualname__
     'C.D'
     >>> C.D.meth.__name__
     'meth'
     >>> C.D.meth.__qualname__
     'C.D.meth'

Example with nested functions:

     >>> def outer():
     ...     def inner():
     ...         pass
     ...     return inner
     ...
     >>> outer().__name__
     'inner'
     >>> outer().__qualname__
     'outer.<locals>.inner'

The string representation of those objects is also changed to include
the new, more precise information:

     >>> str(C.D)
     "<class '__main__.C.D'>"
     >>> str(C.D.meth)
     '<function C.D.meth at 0x7f46b9fe31e0>'

参见
....

PEP 3155(1) - 类和函数的限定名称

     PEP 由 Antoine Pitrou 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3155


File: python.info,  Node: PEP 412 Key-Sharing Dictionary,  Next: PEP 362 函数签名对象,  Prev: PEP 3155 类和函数的限定名称,  Up: Python 3 3 有什么新变化

1.6.12 PEP 412: Key-Sharing Dictionary
--------------------------------------

Dictionaries used for the storage of objects’ attributes are now able to
share part of their internal storage between each other (namely, the
part which stores the keys and their respective hashes).  This reduces
the memory consumption of programs creating many instances of
non-builtin types.

参见
....

PEP 412(1) - Key-Sharing Dictionary

     PEP 由 Mark Shannon 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0412


File: python.info,  Node: PEP 362 函数签名对象,  Next: PEP 421 添加 sys implementation,  Prev: PEP 412 Key-Sharing Dictionary,  Up: Python 3 3 有什么新变化

1.6.13 PEP 362: 函数签名对象
----------------------------

A new function *note inspect.signature(): 564. makes introspection of
python callables easy and straightforward.  A broad range of callables
is supported: python functions, decorated or not, classes, and *note
functools.partial(): 7d1. objects.  New classes *note inspect.Signature:
6fc, *note inspect.Parameter: 6fd. and *note inspect.BoundArguments:
9b0. hold information about the call signatures, such as, annotations,
default values, parameters kinds, and bound arguments, which
considerably simplifies writing decorators and any code that validates
or amends calling signatures or arguments.

参见
....

PEP 362(1): - 函数签名对象

     PEP 由 Brett Cannon，Yury Selivanov，Larry Hastings，Jiwon Seo 撰写
     ，由 Yury Selivanov 实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0362


File: python.info,  Node: PEP 421 添加 sys implementation,  Next: Using importlib as the Implementation of Import,  Prev: PEP 362 函数签名对象,  Up: Python 3 3 有什么新变化

1.6.14 PEP 421: 添加 sys.implementation
---------------------------------------

A new attribute on the *note sys: fe. module exposes details specific to
the implementation of the currently running interpreter.  The initial
set of attributes on *note sys.implementation: 9b2. are ‘name’,
‘version’, ‘hexversion’, and ‘cache_tag’.

The intention of ‘sys.implementation’ is to consolidate into one
namespace the implementation-specific data used by the standard library.
This allows different Python implementations to share a single standard
library code base much more easily.  In its initial state,
‘sys.implementation’ holds only a small portion of the
implementation-specific data.  Over time that ratio will shift in order
to make the standard library more portable.

One example of improved standard library portability is ‘cache_tag’.  As
of Python 3.3, ‘sys.implementation.cache_tag’ is used by *note
importlib: 9b. to support PEP 3147(1) compliance.  Any Python
implementation that uses ‘importlib’ for its built-in import system may
use ‘cache_tag’ to control the caching behavior for modules.

* Menu:

* SimpleNamespace::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: SimpleNamespace,  Up: PEP 421 添加 sys implementation

1.6.14.1 SimpleNamespace
........................

The implementation of ‘sys.implementation’ also introduces a new type to
Python: *note types.SimpleNamespace: 9b4.  In contrast to a
mapping-based namespace, like *note dict: 1b9, ‘SimpleNamespace’ is
attribute-based, like *note object: 2b1.  However, unlike ‘object’,
‘SimpleNamespace’ instances are writable.  This means that you can add,
remove, and modify the namespace through normal attribute access.

参见
....

PEP 421(1) - 添加 sys.implementation

     PEP 由 Eric Snow 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0421


File: python.info,  Node: Using importlib as the Implementation of Import,  Next: 其他语言特性修改<6>,  Prev: PEP 421 添加 sys implementation,  Up: Python 3 3 有什么新变化

1.6.15 Using importlib as the Implementation of Import
------------------------------------------------------

bpo-2377(1) - Replace __import__ w/ importlib.__import__ bpo-13959(2) -
Re-implement parts of *note imp: 9a. in pure Python bpo-14605(3) - Make
import machinery explicit bpo-14646(4) - Require loaders set __loader__
and __package__

The *note __import__(): 619. function is now powered by *note
importlib.__import__(): 9b6.  This work leads to the completion of
"phase 2" of PEP 302(5).  There are multiple benefits to this change.
First, it has allowed for more of the machinery powering import to be
exposed instead of being implicit and hidden within the C code.  It also
provides a single implementation for all Python VMs supporting Python
3.3 to use, helping to end any VM-specific deviations in import
semantics.  And finally it eases the maintenance of import, allowing for
future growth to occur.

For the common user, there should be no visible change in semantics.
For those whose code currently manipulates import or calls import
programmatically, the code changes that might possibly be required are
covered in the *note Porting Python code: 9b7. section of this document.

* Menu:

* New APIs::
* Visible Changes::

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2377

   (2) https://bugs.python.org/issue13959

   (3) https://bugs.python.org/issue14605

   (4) https://bugs.python.org/issue14646

   (5) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: New APIs,  Next: Visible Changes,  Up: Using importlib as the Implementation of Import

1.6.15.1 New APIs
.................

One of the large benefits of this work is the exposure of what goes into
making the import statement work.  That means the various importers that
were once implicit are now fully exposed as part of the *note importlib:
9b. package.

The abstract base classes defined in *note importlib.abc: 9c. have been
expanded to properly delineate between *note meta path finders: 9b9. and
*note path entry finders: 9ba. by introducing *note
importlib.abc.MetaPathFinder: 9bb. and *note
importlib.abc.PathEntryFinder: 9bc, respectively.  The old ABC of *note
importlib.abc.Finder: 9bd. is now only provided for
backwards-compatibility and does not enforce any method requirements.

In terms of finders, *note importlib.machinery.FileFinder: 9be. exposes
the mechanism used to search for source and bytecode files of a module.
Previously this class was an implicit member of *note sys.path_hooks:
964.

For loaders, the new abstract base class *note importlib.abc.FileLoader:
9bf. helps write a loader that uses the file system as the storage
mechanism for a module’s code.  The loader for source files (*note
importlib.machinery.SourceFileLoader: 9c0.), sourceless bytecode files
(*note importlib.machinery.SourcelessFileLoader: 9c1.), and extension
modules (*note importlib.machinery.ExtensionFileLoader: 55f.) are now
available for direct use.

*note ImportError: 33d. now has ‘name’ and ‘path’ attributes which are
set when there is relevant data to provide.  The message for failed
imports will also provide the full name of the module now instead of
just the tail end of the module’s name.

The *note importlib.invalidate_caches(): 4a4. function will now call the
method with the same name on all finders cached in *note
sys.path_importer_cache: 4a5. to help clean up any stored state as
necessary.


File: python.info,  Node: Visible Changes,  Prev: New APIs,  Up: Using importlib as the Implementation of Import

1.6.15.2 Visible Changes
........................

For potential required changes to code, see the *note Porting Python
code: 9b7. section.

Beyond the expanse of what *note importlib: 9b. now exposes, there are
other visible changes to import.  The biggest is that *note
sys.meta_path: 5ef. and *note sys.path_hooks: 964. now store all of the
meta path finders and path entry hooks used by import.  Previously the
finders were implicit and hidden within the C code of import instead of
being directly exposed.  This means that one can now easily remove or
change the order of the various finders to fit one’s needs.

Another change is that all modules have a ‘__loader__’ attribute,
storing the loader used to create the module.  PEP 302(1) has been
updated to make this attribute mandatory for loaders to implement, so in
the future once 3rd-party loaders have been updated people will be able
to rely on the existence of the attribute.  Until such time, though,
import is setting the module post-load.

Loaders are also now expected to set the ‘__package__’ attribute from
PEP 366(2).  Once again, import itself is already setting this on all
loaders from *note importlib: 9b. and import itself is setting the
attribute post-load.

‘None’ is now inserted into *note sys.path_importer_cache: 4a5. when no
finder can be found on *note sys.path_hooks: 964.  Since *note
imp.NullImporter: 9c3. is not directly exposed on *note sys.path_hooks:
964. it could no longer be relied upon to always be available to use as
a value representing no finder found.

All other changes relate to semantic changes which should be taken into
consideration when updating code for Python 3.3, and thus should be read
about in the *note Porting Python code: 9b7. section of this document.

(Implementation by Brett Cannon)

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0302

   (2) https://www.python.org/dev/peps/pep-0366


File: python.info,  Node: 其他语言特性修改<6>,  Next: A Finer-Grained Import Lock,  Prev: Using importlib as the Implementation of Import,  Up: Python 3 3 有什么新变化

1.6.16 其他语言特性修改
-----------------------

对Python 语言核心进行的小改动：

   * Added support for Unicode name aliases and named sequences.  Both
     *note unicodedata.lookup(): 9c5. and ‘'\N{...}'’ now resolve name
     aliases, and *note unicodedata.lookup(): 9c5. resolves named
     sequences too.

     （由 Ezio Melotti 在 bpo-12753(1) 中贡献。）

   * Unicode database updated to UCD version 6.1.0

   * Equality comparisons on *note range(): 9c6. objects now return a
     result reflecting the equality of the underlying sequences
     generated by those range objects.  (bpo-13201(2))

   * The ‘count()’, ‘find()’, ‘rfind()’, ‘index()’ and ‘rindex()’
     methods of *note bytes: 33a. and *note bytearray: 33b. objects now
     accept an integer between 0 and 255 as their first argument.

     （由 Petri Lehtinen 在 bpo-12170(3) 中贡献。）

   * The ‘rjust()’, ‘ljust()’, and ‘center()’ methods of *note bytes:
     33a. and *note bytearray: 33b. now accept a *note bytearray: 33b.
     for the ‘fill’ argument.  (Contributed by Petri Lehtinen in
     bpo-12380(4).)

   * New methods have been added to *note list: 263. and *note
     bytearray: 33b.: ‘copy()’ and ‘clear()’ (bpo-10516(5)).
     Consequently, *note MutableSequence: 6b5. now also defines a
     ‘clear()’ method (bpo-11388(6)).

   * Raw bytes literals can now be written ‘rb"..."’ as well as
     ‘br"..."’.

     （由 Antoine Pitrou 在 bpo-13748(7) 中贡献。）

   * *note dict.setdefault(): 9c7. now does only one lookup for the
     given key, making it atomic when used with built-in types.

     （由 Filip Gruszczyński 在 bpo-13521(8) 中贡献。）

   * The error messages produced when a function call does not match the
     function signature have been significantly improved.

     （由 Benjamin Peterson 贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12753

   (2) https://bugs.python.org/issue13201

   (3) https://bugs.python.org/issue12170

   (4) https://bugs.python.org/issue12380

   (5) https://bugs.python.org/issue10516

   (6) https://bugs.python.org/issue11388

   (7) https://bugs.python.org/issue13748

   (8) https://bugs.python.org/issue13521


File: python.info,  Node: A Finer-Grained Import Lock,  Next: Builtin functions and types,  Prev: 其他语言特性修改<6>,  Up: Python 3 3 有什么新变化

1.6.17 A Finer-Grained Import Lock
----------------------------------

Previous versions of CPython have always relied on a global import lock.
This led to unexpected annoyances, such as deadlocks when importing a
module would trigger code execution in a different thread as a
side-effect.  Clumsy workarounds were sometimes employed, such as the
*note PyImport_ImportModuleNoBlock(): 9c9. C API function.

In Python 3.3, importing a module takes a per-module lock.  This
correctly serializes importation of a given module from multiple threads
(preventing the exposure of incompletely initialized modules), while
eliminating the aforementioned annoyances.

（由 Antoine Pitrou 在 bpo-9260(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9260


File: python.info,  Node: Builtin functions and types,  Next: 新增模块<6>,  Prev: A Finer-Grained Import Lock,  Up: Python 3 3 有什么新变化

1.6.18 Builtin functions and types
----------------------------------

   * *note open(): 4f8. gets a new `opener' parameter: the underlying
     file descriptor for the file object is then obtained by calling
     `opener' with (`file', `flags').  It can be used to use custom
     flags like *note os.O_CLOEXEC: 9cb. for example.  The ‘'x'’ mode
     was added: open for exclusive creation, failing if the file already
     exists.

   * *note print(): 88f.: added the `flush' keyword argument.  If the
     `flush' keyword argument is true, the stream is forcibly flushed.

   * *note hash(): 9cc.: hash randomization is enabled by default, see
     *note object.__hash__(): 349. and *note PYTHONHASHSEED: 9cd.

   * The *note str: 339. type gets a new *note casefold(): 6b9. method:
     return a casefolded copy of the string, casefolded strings may be
     used for caseless matching.  For example, ‘'ß'.casefold()’ returns
     ‘'ss'’.

   * The sequence documentation has been substantially rewritten to
     better explain the binary/text sequence distinction and to provide
     specific documentation sections for the individual builtin sequence
     types (bpo-4966(1)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4966


File: python.info,  Node: 新增模块<6>,  Next: 改进的模块<6>,  Prev: Builtin functions and types,  Up: Python 3 3 有什么新变化

1.6.19 新增模块
---------------

* Menu:

* faulthandler: faulthandler<3>.
* ipaddress: ipaddress<4>.
* lzma: lzma<2>.


File: python.info,  Node: faulthandler<3>,  Next: ipaddress<4>,  Up: 新增模块<6>

1.6.19.1 faulthandler
.....................

This new debug module *note faulthandler: 7d. contains functions to dump
Python tracebacks explicitly, on a fault (a crash like a segmentation
fault), after a timeout, or on a user signal.  Call *note
faulthandler.enable(): 551. to install fault handlers for the ‘SIGSEGV’,
‘SIGFPE’, ‘SIGABRT’, ‘SIGBUS’, and ‘SIGILL’ signals.  You can also
enable them at startup by setting the *note PYTHONFAULTHANDLER: 9d0.
environment variable or by using *note -X: 156. ‘faulthandler’ command
line option.

Example of a segmentation fault on Linux:

     $ python -q -X faulthandler
     >>> import ctypes
     >>> ctypes.string_at(0)
     Fatal Python error: Segmentation fault

     Current thread 0x00007fb899f39700:
       File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at
       File "<stdin>", line 1 in <module>
     Segmentation fault


File: python.info,  Node: ipaddress<4>,  Next: lzma<2>,  Prev: faulthandler<3>,  Up: 新增模块<6>

1.6.19.2 ipaddress
..................

The new *note ipaddress: a3. module provides tools for creating and
manipulating objects representing IPv4 and IPv6 addresses, networks and
interfaces (i.e.  an IP address associated with a specific IP subnet).

（由 Google 和 Peter Moody 在 bpo-3144(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3144


File: python.info,  Node: lzma<2>,  Prev: ipaddress<4>,  Up: 新增模块<6>

1.6.19.3 lzma
.............

The newly-added *note lzma: ae. module provides data compression and
decompression using the LZMA algorithm, including support for the ‘.xz’
and ‘.lzma’ file formats.

（由 Nadeem Vawda 和 Per Øyvind Karlsen 在 bpo-6715(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6715


File: python.info,  Node: 改进的模块<6>,  Next: 性能优化<5>,  Prev: 新增模块<6>,  Up: Python 3 3 有什么新变化

1.6.20 改进的模块
-----------------

* Menu:

* abc: abc<2>.
* array: array<2>.
* base64: base64<2>.
* binascii: binascii<3>.
* bz2: bz2<2>.
* 编码器::
* collections: collections<7>.
* contextlib: contextlib<5>.
* crypt: crypt<2>.
* curses: curses<3>.
* datetime: datetime<4>.
* decimal: decimal<3>.
* email: email<4>.
* ftplib::
* functools: functools<5>.
* gc: gc<4>.
* hmac: hmac<3>.
* http: http<3>.
* html: html<2>.
* imaplib: imaplib<2>.
* inspect: inspect<5>.
* io: io<4>.
* itertools: itertools<3>.
* logging: logging<6>.
* math: math<5>.
* mmap: mmap<3>.
* multiprocessing: multiprocessing<6>.
* nntplib::
* os: os<7>.
* pdb: pdb<4>.
* pickle: pickle<5>.
* pydoc: pydoc<4>.
* re: re<6>.
* sched::
* select: select<2>.
* shlex: shlex<3>.
* shutil: shutil<4>.
* signal: signal<3>.
* smtpd: smtpd<3>.
* smtplib: smtplib<3>.
* socket: socket<7>.
* socketserver: socketserver<3>.
* sqlite3: sqlite3<5>.
* ssl: ssl<8>.
* stat: stat<2>.
* struct: struct<3>.
* subprocess: subprocess<5>.
* sys: sys<7>.
* tarfile: tarfile<4>.
* tempfile::
* textwrap: textwrap<2>.
* threading: threading<5>.
* time: time<5>.
* types: types<4>.
* unittest: unittest<5>.
* urllib: urllib<3>.
* webbrowser::
* xml.etree.ElementTree: xml etree ElementTree.
* zlib: zlib<2>.


File: python.info,  Node: abc<2>,  Next: array<2>,  Up: 改进的模块<6>

1.6.20.1 abc
............

Improved support for abstract base classes containing descriptors
composed with abstract methods.  The recommended approach to declaring
abstract descriptors is now to provide ‘__isabstractmethod__’ as a
dynamically updated property.  The built-in descriptors have been
updated accordingly.

        * *note abc.abstractproperty: 9d5. has been deprecated, use
          *note property: 1d8. with *note abc.abstractmethod(): 9d6.
          instead.

        * *note abc.abstractclassmethod: 9d7. has been deprecated, use
          *note classmethod: 1d9. with *note abc.abstractmethod(): 9d6.
          instead.

        * *note abc.abstractstaticmethod: 9d8. has been deprecated, use
          *note staticmethod: 1da. with *note abc.abstractmethod(): 9d6.
          instead.

（由 Pablo Galindo 在 bpo-11610(1) 中贡献。）

*note abc.ABCMeta.register(): 9d9. now returns the registered subclass,
which means it can now be used as a class decorator (bpo-10868(2)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11610

   (2) https://bugs.python.org/issue10868


File: python.info,  Node: array<2>,  Next: base64<2>,  Prev: abc<2>,  Up: 改进的模块<6>

1.6.20.2 array
..............

The *note array: 7. module supports the ‘long long’ type using ‘q’ and
‘Q’ type codes.

（由 Oren Tirosh 和 Hirokazu Yamamoto 在 bpo-1172711(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1172711


File: python.info,  Node: base64<2>,  Next: binascii<3>,  Prev: array<2>,  Up: 改进的模块<6>

1.6.20.3 base64
...............

ASCII-only Unicode strings are now accepted by the decoding functions of
the *note base64: e. modern interface.  For example,
‘base64.b64decode('YWJj')’ returns ‘b'abc'’.  (Contributed by Catalin
Iacob in bpo-13641(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13641


File: python.info,  Node: binascii<3>,  Next: bz2<2>,  Prev: base64<2>,  Up: 改进的模块<6>

1.6.20.4 binascii
.................

In addition to the binary objects they normally accept, the ‘a2b_’
functions now all also accept ASCII-only strings as input.  (Contributed
by Antoine Pitrou in bpo-13637(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13637


File: python.info,  Node: bz2<2>,  Next: 编码器,  Prev: binascii<3>,  Up: 改进的模块<6>

1.6.20.5 bz2
............

The *note bz2: 14. module has been rewritten from scratch.  In the
process, several new features have been added:

   * New *note bz2.open(): 9de. function: open a bzip2-compressed file
     in binary or text mode.

   * *note bz2.BZ2File: 939. can now read from and write to arbitrary
     file-like objects, by means of its constructor’s `fileobj'
     argument.

     （由 Nadeem Vawda 在 bpo-5863(1) 中贡献。）

   * *note bz2.BZ2File: 939. and *note bz2.decompress(): 9df. can now
     decompress multi-stream inputs (such as those produced by the
     ‘pbzip2’ tool).  *note bz2.BZ2File: 939. can now also be used to
     create this type of file, using the ‘'a'’ (append) mode.

     （由 Nir Aides 在 bpo-1625(2) 中贡献。）

   * *note bz2.BZ2File: 939. now implements all of the *note
     io.BufferedIOBase: 591. API, except for the ‘detach()’ and
     ‘truncate()’ methods.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5863

   (2) https://bugs.python.org/issue1625


File: python.info,  Node: 编码器,  Next: collections<7>,  Prev: bz2<2>,  Up: 改进的模块<6>

1.6.20.6 编码器
...............

The *note mbcs: 78. codec has been rewritten to handle correctly
‘replace’ and ‘ignore’ error handlers on all Windows versions.  The
*note mbcs: 78. codec now supports all error handlers, instead of only
‘replace’ to encode and ‘ignore’ to decode.

A new Windows-only codec has been added: ‘cp65001’ (bpo-13216(1)).  It
is the Windows code page 65001 (Windows UTF-8, ‘CP_UTF8’).  For example,
it is used by ‘sys.stdout’ if the console output code page is set to
cp65001 (e.g., using ‘chcp 65001’ command).

Multibyte CJK decoders now resynchronize faster.  They only ignore the
first byte of an invalid byte sequence.  For example,
‘b'\xff\n'.decode('gb2312', 'replace')’ now returns a ‘\n’ after the
replacement character.

(bpo-12016(2))

Incremental CJK codec encoders are no longer reset at each call to their
encode() methods.  For example:

     >>> import codecs
     >>> encoder = codecs.getincrementalencoder('hz')('strict')
     >>> b''.join(encoder.encode(x) for x in '\u52ff\u65bd\u65bc\u4eba\u3002 Bye.')
     b'~{NpJ)l6HK!#~} Bye.'

This example gives ‘b'~{Np~}~{J)~}~{l6~}~{HK~}~{!#~} Bye.'’ with older
Python versions.

(bpo-12100(3))

The ‘unicode_internal’ codec has been deprecated.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13216

   (2) https://bugs.python.org/issue12016

   (3) https://bugs.python.org/issue12100


File: python.info,  Node: collections<7>,  Next: contextlib<5>,  Prev: 编码器,  Up: 改进的模块<6>

1.6.20.7 collections
....................

Addition of a new *note ChainMap: 4b1. class to allow treating a number
of mappings as a single unit.  (Written by Raymond Hettinger for
bpo-11089(1), made public in bpo-11297(2).)

The abstract base classes have been moved in a new *note
collections.abc: 1f. module, to better differentiate between the
abstract and the concrete collections classes.  Aliases for ABCs are
still present in the *note collections: 1e. module to preserve existing
imports.  (bpo-11085(3))

The *note Counter: 9e2. class now supports the unary ‘+’ and ‘-’
operators, as well as the in-place operators ‘+=’, ‘-=’, ‘|=’, and ‘&=’.
(Contributed by Raymond Hettinger in bpo-13121(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11089

   (2) https://bugs.python.org/issue11297

   (3) https://bugs.python.org/issue11085

   (4) https://bugs.python.org/issue13121


File: python.info,  Node: contextlib<5>,  Next: crypt<2>,  Prev: collections<7>,  Up: 改进的模块<6>

1.6.20.8 contextlib
...................

*note ExitStack: 37f. now provides a solid foundation for programmatic
manipulation of context managers and similar cleanup functionality.
Unlike the previous ‘contextlib.nested’ API (which was deprecated and
removed), the new API is designed to work correctly regardless of
whether context managers acquire their resources in their ‘__init__’
method (for example, file objects) or in their ‘__enter__’ method (for
example, synchronisation objects from the *note threading: 10a. module).

(bpo-13585(1))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13585


File: python.info,  Node: crypt<2>,  Next: curses<3>,  Prev: contextlib<5>,  Up: 改进的模块<6>

1.6.20.9 crypt
..............

Addition of salt and modular crypt format (hashing method) and the *note
mksalt(): 385. function to the *note crypt: 29. module.

(bpo-10924(1))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10924


File: python.info,  Node: curses<3>,  Next: datetime<4>,  Prev: crypt<2>,  Up: 改进的模块<6>

1.6.20.10 curses
................

        * If the *note curses: 2c. module is linked to the ncursesw
          library, use Unicode functions when Unicode strings or
          characters are passed (e.g.  ‘waddwstr()’), and bytes
          functions otherwise (e.g.  ‘waddstr()’).

        * Use the locale encoding instead of ‘utf-8’ to encode Unicode
          strings.

        * ‘curses.window’ has a new *note curses.window.encoding: 9e6.
          attribute.

        * The ‘curses.window’ class has a new *note get_wch(): 9e7.
          method to get a wide character

        * The *note curses: 2c. module has a new *note unget_wch(): 9e8.
          function to push a wide character so the next *note get_wch():
          9e7. will return it

（由 Iñigo Serna 在 bpo-6755(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6755


File: python.info,  Node: datetime<4>,  Next: decimal<3>,  Prev: curses<3>,  Up: 改进的模块<6>

1.6.20.11 datetime
..................

        * Equality comparisons between naive and aware *note datetime:
          195. instances now return *note False: 390. instead of raising
          *note TypeError: 193. (bpo-15006(1)).

        * New *note datetime.datetime.timestamp(): 9ea. method: Return
          POSIX timestamp corresponding to the *note datetime: 195.
          instance.

        * The *note datetime.datetime.strftime(): 53f. method supports
          formatting years older than 1000.

        * The *note datetime.datetime.astimezone(): 197. method can now
          be called without arguments to convert datetime instance to
          the system timezone.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15006


File: python.info,  Node: decimal<3>,  Next: email<4>,  Prev: datetime<4>,  Up: 改进的模块<6>

1.6.20.12 decimal
.................

bpo-7652(1) - integrate fast native decimal arithmetic.

     C-module and libmpdec written by Stefan Krah.

The new C version of the decimal module integrates the high speed
libmpdec library for arbitrary precision correctly-rounded decimal
floating point arithmetic.  libmpdec conforms to IBM’s General Decimal
Arithmetic Specification.

Performance gains range from 10x for database applications to 100x for
numerically intensive applications.  These numbers are expected gains
for standard precisions used in decimal floating point arithmetic.
Since the precision is user configurable, the exact figures may vary.
For example, in integer bignum arithmetic the differences can be
significantly higher.

The following table is meant as an illustration.  Benchmarks are
available at ‘http://www.bytereef.org/mpdecimal/quickstart.html’.

                   decimal.py        _decimal           加速
                                                        
     ---------------------------------------------------------------------
                                                        
     pi            42.02秒           0.345秒            120倍
                                                        
                                                        
     telco         172.19秒          5.68秒             30倍
                                                        
                                                        
     psycopg       3.57秒            0.29秒             12倍
                                                        

* Menu:

* 相关特性: 相关特性<2>.
* API changes: API changes<2>.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7652


File: python.info,  Node: 相关特性<2>,  Next: API changes<2>,  Up: decimal<3>

1.6.20.13 相关特性
..................

   * The *note FloatOperation: 9ed. signal optionally enables stricter
     semantics for mixing floats and Decimals.

   * If Python is compiled without threads, the C version automatically
     disables the expensive thread local context machinery.  In this
     case, the variable *note HAVE_THREADS: 9ee. is set to ‘False’.


File: python.info,  Node: API changes<2>,  Prev: 相关特性<2>,  Up: decimal<3>

1.6.20.14 API changes
.....................

   * C模块上下文限制（如下表），具体取决于计算机体系结构：

                                  32位                      64位
                                                            
          -------------------------------------------------------------------------------------
                                                            
          ‘MAX_PREC’              ‘425000000’               ‘999999999999999999’
                                                            
                                                            
          ‘MAX_EMAX’              ‘425000000’               ‘999999999999999999’
                                                            
                                                            
          ‘MIN_EMIN’              ‘-425000000’              ‘-999999999999999999’
                                                            

   * In the context templates (*note DefaultContext: 9f0, *note
     BasicContext: 9f1. and *note ExtendedContext: 9f2.) the magnitude
     of ‘Emax’ and ‘Emin’ has changed to ‘999999’.

   * The *note Decimal: 189. constructor in decimal.py does not observe
     the context limits and converts values with arbitrary exponents or
     precision exactly.  Since the C version has internal limits, the
     following scheme is used: If possible, values are converted
     exactly, otherwise *note InvalidOperation: 9f3. is raised and the
     result is NaN. In the latter case it is always possible to use
     *note create_decimal(): 9f4. in order to obtain a rounded or
     inexact value.

   * The power function in decimal.py is always correctly-rounded.  In
     the C version, it is defined in terms of the correctly-rounded
     *note exp(): 9f5. and *note ln(): 9f6. functions, but the final
     result is only "almost always correctly rounded".

   * In the C version, the context dictionary containing the signals is
     a *note MutableMapping: 9f7.  For speed reasons, ‘flags’ and
     ‘traps’ always refer to the same *note MutableMapping: 9f7. that
     the context was initialized with.  If a new signal dictionary is
     assigned, ‘flags’ and ‘traps’ are updated with the new values, but
     they do not reference the RHS dictionary.

   * Pickling a *note Context: 9f8. produces a different output in order
     to have a common interchange format for the Python and C versions.

   * The order of arguments in the *note Context: 9f8. constructor has
     been changed to match the order displayed by *note repr(): 7d5.

   * The ‘watchexp’ parameter in the *note quantize(): 9f9. method is
     deprecated.


File: python.info,  Node: email<4>,  Next: ftplib,  Prev: decimal<3>,  Up: 改进的模块<6>

1.6.20.15 email
...............

* Menu:

* Policy Framework::
* Provisional Policy with New Header API::
* Other API Changes::


File: python.info,  Node: Policy Framework,  Next: Provisional Policy with New Header API,  Up: email<4>

1.6.20.16 Policy Framework
..........................

The email package now has a *note policy: 75. framework.  A *note
Policy: 9fc. is an object with several methods and properties that
control how the email package behaves.  The primary policy for Python
3.3 is the *note Compat32: 9fd. policy, which provides backward
compatibility with the email package in Python 3.2.  A ‘policy’ can be
specified when an email message is parsed by a *note parser: 74, or when
a *note Message: 54a. object is created, or when an email is serialized
using a *note generator: 6e.  Unless overridden, a policy passed to a
‘parser’ is inherited by all the ‘Message’ object and sub-objects
created by the ‘parser’.  By default a ‘generator’ will use the policy
of the ‘Message’ object it is serializing.  The default policy is *note
compat32: 549.

The minimum set of controls implemented by all ‘policy’ objects are:

     max_line_length     The maximum length, excluding the linesep character(s),
                         individual lines may have when a ‘Message’ is serialized.
                         Defaults to 78.
                         
                         
     linesep             The character used to separate individual lines when a
                         ‘Message’ is serialized.  Defaults to ‘\n’.
                         
                         
     cte_type            ‘7bit’ or ‘8bit’.  ‘8bit’ applies only to a ‘Bytes’
                         ‘generator’, and means that non-ASCII may be used where
                         allowed by the protocol (or where it exists in the
                         original input).
                         
                         
     raise_on_defect     Causes a ‘parser’ to raise error when defects are
                         encountered instead of adding them to the ‘Message’
                         object’s ‘defects’ list.
                         

A new policy instance, with new settings, is created using the *note
clone(): 9fe. method of policy objects.  ‘clone’ takes any of the above
controls as keyword arguments.  Any control not specified in the call
retains its default value.  Thus you can create a policy that uses
‘\r\n’ linesep characters like this:

     mypolicy = compat32.clone(linesep='\r\n')

Policies can be used to make the generation of messages in the format
needed by your application simpler.  Instead of having to remember to
specify ‘linesep='\r\n'’ in all the places you call a ‘generator’, you
can specify it once, when you set the policy used by the ‘parser’ or the
‘Message’, whichever your program uses to create ‘Message’ objects.  On
the other hand, if you need to generate messages in multiple forms, you
can still specify the parameters in the appropriate ‘generator’ call.
Or you can have custom policy instances for your different cases, and
pass those in when you create the ‘generator’.


File: python.info,  Node: Provisional Policy with New Header API,  Next: Other API Changes,  Prev: Policy Framework,  Up: email<4>

1.6.20.17 Provisional Policy with New Header API
................................................

While the policy framework is worthwhile all by itself, the main
motivation for introducing it is to allow the creation of new policies
that implement new features for the email package in a way that
maintains backward compatibility for those who do not use the new
policies.  Because the new policies introduce a new API, we are
releasing them in Python 3.3 as a *note provisional policy: 988.
Backwards incompatible changes (up to and including removal of the code)
may occur if deemed necessary by the core developers.

The new policies are instances of *note EmailPolicy: a00, and add the
following additional controls:

     refold_source       Controls whether or not headers parsed by a
                         *note parser: 74. are refolded by the
                         *note generator: 6e.  It can be ‘none’, ‘long’, or ‘all’.
                         The default is ‘long’, which means that source headers
                         with a line longer than ‘max_line_length’ get refolded.
                         ‘none’ means no line get refolded, and ‘all’ means that
                         all lines get refolded.
                         
                         
     header_factory      A callable that take a ‘name’ and ‘value’ and produces a
                         custom header object.
                         

The ‘header_factory’ is the key to the new features provided by the new
policies.  When one of the new policies is used, any header retrieved
from a ‘Message’ object is an object produced by the ‘header_factory’,
and any time you set a header on a ‘Message’ it becomes an object
produced by ‘header_factory’.  All such header objects have a ‘name’
attribute equal to the header name.  Address and Date headers have
additional attributes that give you access to the parsed data of the
header.  This means you can now do things like this:

     >>> m = Message(policy=SMTP)
     >>> m['To'] = 'Éric <foo@example.com>'
     >>> m['to']
     'Éric <foo@example.com>'
     >>> m['to'].addresses
     (Address(display_name='Éric', username='foo', domain='example.com'),)
     >>> m['to'].addresses[0].username
     'foo'
     >>> m['to'].addresses[0].display_name
     'Éric'
     >>> m['Date'] = email.utils.localtime()
     >>> m['Date'].datetime
     datetime.datetime(2012, 5, 25, 21, 39, 24, 465484, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000), 'EDT'))
     >>> m['Date']
     'Fri, 25 May 2012 21:44:27 -0400'
     >>> print(m)
     To: =?utf-8?q?=C3=89ric?= <foo@example.com>
     Date: Fri, 25 May 2012 21:44:27 -0400

You will note that the unicode display name is automatically encoded as
‘utf-8’ when the message is serialized, but that when the header is
accessed directly, you get the unicode version.  This eliminates any
need to deal with the *note email.header: 6f. *note decode_header():
a01. or *note make_header(): a02. functions.

You can also create addresses from parts:

     >>> m['cc'] = [Group('pals', [Address('Bob', 'bob', 'example.com'),
     ...                           Address('Sally', 'sally', 'example.com')]),
     ...            Address('Bonzo', addr_spec='bonz@laugh.com')]
     >>> print(m)
     To: =?utf-8?q?=C3=89ric?= <foo@example.com>
     Date: Fri, 25 May 2012 21:44:27 -0400
     cc: pals: Bob <bob@example.com>, Sally <sally@example.com>;, Bonzo <bonz@laugh.com>

Decoding to unicode is done automatically:

     >>> m2 = message_from_string(str(m))
     >>> m2['to']
     'Éric <foo@example.com>'

When you parse a message, you can use the ‘addresses’ and ‘groups’
attributes of the header objects to access the groups and individual
addresses:

     >>> m2['cc'].addresses
     (Address(display_name='Bob', username='bob', domain='example.com'), Address(display_name='Sally', username='sally', domain='example.com'), Address(display_name='Bonzo', username='bonz', domain='laugh.com'))
     >>> m2['cc'].groups
     (Group(display_name='pals', addresses=(Address(display_name='Bob', username='bob', domain='example.com'), Address(display_name='Sally', username='sally', domain='example.com')), Group(display_name=None, addresses=(Address(display_name='Bonzo', username='bonz', domain='laugh.com'),))

In summary, if you use one of the new policies, header manipulation
works the way it ought to: your application works with unicode strings,
and the email package transparently encodes and decodes the unicode to
and from the RFC standard Content Transfer Encodings.


File: python.info,  Node: Other API Changes,  Prev: Provisional Policy with New Header API,  Up: email<4>

1.6.20.18 Other API Changes
...........................

New *note BytesHeaderParser: a04, added to the *note parser: 74. module
to complement *note HeaderParser: a05. and complete the Bytes API.

New utility functions:

        * *note format_datetime(): a06.: given a *note datetime: 195,
          produce a string formatted for use in an email header.

        * *note parsedate_to_datetime(): a07.: given a date string from
          an email header, convert it into an aware *note datetime: 195,
          or a naive *note datetime: 195. if the offset is ‘-0000’.

        * *note localtime(): a08.: With no argument, returns the current
          local time as an aware *note datetime: 195. using the local
          *note timezone: a09.  Given an aware *note datetime: 195,
          converts it into an aware *note datetime: 195. using the local
          *note timezone: a09.


File: python.info,  Node: ftplib,  Next: functools<5>,  Prev: email<4>,  Up: 改进的模块<6>

1.6.20.19 ftplib
................

   * *note ftplib.FTP: 2f1. now accepts a ‘source_address’ keyword
     argument to specify the ‘(host, port)’ to use as the source address
     in the bind call when creating the outgoing socket.  (Contributed
     by Giampaolo Rodolà in bpo-8594(1).)

   * The *note FTP_TLS: a0b. class now provides a new *note ccc(): a0c.
     function to revert control channel back to plaintext.  This can be
     useful to take advantage of firewalls that know how to handle NAT
     with non-secure FTP without opening fixed ports.  (Contributed by
     Giampaolo Rodolà in bpo-12139(2).)

   * Added *note ftplib.FTP.mlsd(): a0d. method which provides a
     parsable directory listing format and deprecates *note
     ftplib.FTP.nlst(): a0e. and *note ftplib.FTP.dir(): a0f.
     (Contributed by Giampaolo Rodolà in bpo-11072(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8594

   (2) https://bugs.python.org/issue12139

   (3) https://bugs.python.org/issue11072


File: python.info,  Node: functools<5>,  Next: gc<4>,  Prev: ftplib,  Up: 改进的模块<6>

1.6.20.20 functools
...................

The *note functools.lru_cache(): 1c8. decorator now accepts a ‘typed’
keyword argument (that defaults to ‘False’ to ensure that it caches
values of different types that compare equal in separate cache slots.
(Contributed by Raymond Hettinger in bpo-13227(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13227


File: python.info,  Node: gc<4>,  Next: hmac<3>,  Prev: functools<5>,  Up: 改进的模块<6>

1.6.20.21 gc
............

It is now possible to register callbacks invoked by the garbage
collector before and after collection using the new *note callbacks:
a12. list.


File: python.info,  Node: hmac<3>,  Next: http<3>,  Prev: gc<4>,  Up: 改进的模块<6>

1.6.20.22 hmac
..............

A new *note compare_digest(): a14. function has been added to prevent
side channel attacks on digests through timing analysis.  (Contributed
by Nick Coghlan and Christian Heimes in bpo-15061(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15061


File: python.info,  Node: http<3>,  Next: html<2>,  Prev: hmac<3>,  Up: 改进的模块<6>

1.6.20.23 http
..............

*note http.server.BaseHTTPRequestHandler: a16. now buffers the headers
and writes them all at once when *note end_headers(): a17. is called.  A
new method *note flush_headers(): a18. can be used to directly manage
when the accumulated headers are sent.  (Contributed by Andrew Schaaf in
bpo-3709(1).)

*note http.server: 97. now produces valid ‘HTML 4.01 strict’ output.
(Contributed by Ezio Melotti in bpo-13295(2).)

*note http.client.HTTPResponse: a19. now has a *note readinto(): a1a.
method, which means it can be used as an *note io.RawIOBase: a1b. class.
(Contributed by John Kuhn in bpo-13464(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3709

   (2) https://bugs.python.org/issue13295

   (3) https://bugs.python.org/issue13464


File: python.info,  Node: html<2>,  Next: imaplib<2>,  Prev: http<3>,  Up: 改进的模块<6>

1.6.20.24 html
..............

*note html.parser.HTMLParser: 7c8. is now able to parse broken markup
without raising errors, therefore the `strict' argument of the
constructor and the ‘HTMLParseError’ exception are now deprecated.  The
ability to parse broken markup is the result of a number of bug fixes
that are also available on the latest bug fix releases of Python
2.7/3.2.  (Contributed by Ezio Melotti in bpo-15114(1), and
bpo-14538(2), bpo-13993(3), bpo-13960(4), bpo-13358(5), bpo-1745761(6),
bpo-755670(7), bpo-13357(8), bpo-12629(9), bpo-1200313(10),
bpo-670664(11), bpo-13273(12), bpo-12888(13), bpo-7311(14).)

A new *note html5: a1d. dictionary that maps HTML5 named character
references to the equivalent Unicode character(s) (e.g.  ‘html5['gt;']
== '>'’) has been added to the *note html.entities: 91. module.  The
dictionary is now also used by *note HTMLParser: 7c8.  (Contributed by
Ezio Melotti in bpo-11113(15) and bpo-15156(16).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15114

   (2) https://bugs.python.org/issue14538

   (3) https://bugs.python.org/issue13993

   (4) https://bugs.python.org/issue13960

   (5) https://bugs.python.org/issue13358

   (6) https://bugs.python.org/issue1745761

   (7) https://bugs.python.org/issue755670

   (8) https://bugs.python.org/issue13357

   (9) https://bugs.python.org/issue12629

   (10) https://bugs.python.org/issue1200313

   (11) https://bugs.python.org/issue670664

   (12) https://bugs.python.org/issue13273

   (13) https://bugs.python.org/issue12888

   (14) https://bugs.python.org/issue7311

   (15) https://bugs.python.org/issue11113

   (16) https://bugs.python.org/issue15156


File: python.info,  Node: imaplib<2>,  Next: inspect<5>,  Prev: html<2>,  Up: 改进的模块<6>

1.6.20.25 imaplib
.................

The *note IMAP4_SSL: a1f. constructor now accepts an SSLContext
parameter to control parameters of the secure channel.

（由 Sijin Joseph 在 bpo-8808(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8808


File: python.info,  Node: inspect<5>,  Next: io<4>,  Prev: imaplib<2>,  Up: 改进的模块<6>

1.6.20.26 inspect
.................

A new *note getclosurevars(): a21. function has been added.  This
function reports the current binding of all names referenced from the
function body and where those names were resolved, making it easier to
verify correct internal state when testing code that relies on stateful
closures.

（由 Meador Inge 和 Nick Coghlan 在 bpo-13062(1) 中贡献。）

A new *note getgeneratorlocals(): a22. function has been added.  This
function reports the current binding of local variables in the
generator’s stack frame, making it easier to verify correct internal
state when testing generators.

（由 Meador Inge 在 bpo-15153(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13062

   (2) https://bugs.python.org/issue15153


File: python.info,  Node: io<4>,  Next: itertools<3>,  Prev: inspect<5>,  Up: 改进的模块<6>

1.6.20.27 io
............

The *note open(): 663. function has a new ‘'x'’ mode that can be used to
exclusively create a new file, and raise a *note FileExistsError: 960.
if the file already exists.  It is based on the C11 ’x’ mode to fopen().

（由 David Townshend 在 bpo-12760(1) 中贡献。）

The constructor of the *note TextIOWrapper: 5fc. class has a new
`write_through' optional argument.  If `write_through' is ‘True’, calls
to ‘write()’ are guaranteed not to be buffered: any data written on the
*note TextIOWrapper: 5fc. object is immediately handled to its
underlying binary buffer.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12760


File: python.info,  Node: itertools<3>,  Next: logging<6>,  Prev: io<4>,  Up: 改进的模块<6>

1.6.20.28 itertools
...................

*note accumulate(): 1de. now takes an optional ‘func’ argument for
providing a user-supplied binary function.


File: python.info,  Node: logging<6>,  Next: math<5>,  Prev: itertools<3>,  Up: 改进的模块<6>

1.6.20.29 logging
.................

The *note basicConfig(): 1e1. function now supports an optional
‘handlers’ argument taking an iterable of handlers to be added to the
root logger.

A class level attribute ‘append_nul’ has been added to *note
SysLogHandler: a26. to allow control of the appending of the ‘NUL’
(‘\000’) byte to syslog records, since for some daemons it is required
while for others it is passed through to the log.


File: python.info,  Node: math<5>,  Next: mmap<3>,  Prev: logging<6>,  Up: 改进的模块<6>

1.6.20.30 math
..............

The *note math: b2. module has a new function, *note log2(): a28, which
returns the base-2 logarithm of `x'.

(Written by Mark Dickinson in bpo-11888(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11888


File: python.info,  Node: mmap<3>,  Next: multiprocessing<6>,  Prev: math<5>,  Up: 改进的模块<6>

1.6.20.31 mmap
..............

The *note read(): a2a. method is now more compatible with other
file-like objects: if the argument is omitted or specified as ‘None’, it
returns the bytes from the current file position to the end of the
mapping.  (Contributed by Petri Lehtinen in bpo-12021(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12021


File: python.info,  Node: multiprocessing<6>,  Next: nntplib,  Prev: mmap<3>,  Up: 改进的模块<6>

1.6.20.32 multiprocessing
.........................

The new *note multiprocessing.connection.wait(): a2c. function allows
polling multiple objects (such as connections, sockets and pipes) with a
timeout.  (Contributed by Richard Oudkerk in bpo-12328(1).)

‘multiprocessing.Connection’ objects can now be transferred over
multiprocessing connections.  (Contributed by Richard Oudkerk in
bpo-4892(2).)

*note multiprocessing.Process: 3ba. now accepts a ‘daemon’ keyword
argument to override the default behavior of inheriting the ‘daemon’
flag from the parent process (bpo-6064(3)).

New attribute *note multiprocessing.Process.sentinel: a2d. allows a
program to wait on multiple *note Process: 3ba. objects at one time
using the appropriate OS primitives (for example, *note select: e6. on
posix systems).

New methods *note multiprocessing.pool.Pool.starmap(): a2e. and *note
starmap_async(): a2f. provide *note itertools.starmap(): a30.
equivalents to the existing *note multiprocessing.pool.Pool.map(): a31.
and *note map_async(): a32. functions.  (Contributed by Hynek Schlawack
in bpo-12708(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12328

   (2) https://bugs.python.org/issue4892

   (3) https://bugs.python.org/issue6064

   (4) https://bugs.python.org/issue12708


File: python.info,  Node: nntplib,  Next: os<7>,  Prev: multiprocessing<6>,  Up: 改进的模块<6>

1.6.20.33 nntplib
.................

The *note nntplib.NNTP: a34. class now supports the context management
protocol to unconditionally consume *note socket.error: 99d. exceptions
and to close the NNTP connection when done:

     >>> from nntplib import NNTP
     >>> with NNTP('news.gmane.org') as n:
     ...     n.group('gmane.comp.python.committers')
     ...
     ('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp.python.committers')
     >>>

（由 Giampaolo Rodolà 在 bpo-9795(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9795


File: python.info,  Node: os<7>,  Next: pdb<4>,  Prev: nntplib,  Up: 改进的模块<6>

1.6.20.34 os
............

   * The *note os: c5. module has a new *note pipe2(): a36. function
     that makes it possible to create a pipe with *note O_CLOEXEC: 9cb.
     or *note O_NONBLOCK: 72c. flags set atomically.  This is especially
     useful to avoid race conditions in multi-threaded programs.

   * The *note os: c5. module has a new *note sendfile(): 362. function
     which provides an efficient "zero-copy" way for copying data from
     one file (or socket) descriptor to another.  The phrase "zero-copy"
     refers to the fact that all of the copying of data between the two
     descriptors is done entirely by the kernel, with no copying of data
     into userspace buffers.  *note sendfile(): 362. can be used to
     efficiently copy data from a file on disk to a network socket, e.g.
     for downloading a file.

     (Patch submitted by Ross Lagerwall and Giampaolo Rodolà in
     bpo-10882(1).)

   * To avoid race conditions like symlink attacks and issues with
     temporary files and directories, it is more reliable (and also
     faster) to manipulate file descriptors instead of file names.
     Python 3.3 enhances existing functions and introduces new functions
     to work on file descriptors (bpo-4761(2), bpo-10755(3) and
     bpo-14626(4)).

        - The *note os: c5. module has a new *note fwalk(): 3bc.
          function similar to *note walk(): 65d. except that it also
          yields file descriptors referring to the directories visited.
          This is especially useful to avoid symlink races.

        - The following functions get new optional `dir_fd' (*note paths
          relative to directory descriptors: a37.) and/or
          `follow_symlinks' (*note not following symlinks: a38.): *note
          access(): a39, *note chflags(): a3a, *note chmod(): a3b, *note
          chown(): a3c, *note link(): a3d, *note lstat(): 1f3, *note
          mkdir(): a3e, *note mkfifo(): 66c, *note mknod(): 66d, *note
          open(): 66e, *note readlink(): 1f4, *note remove(): a3f, *note
          rename(): a40, *note replace(): a41, *note rmdir(): a42, *note
          stat(): 1f2, *note symlink(): a43, *note unlink(): a44, *note
          utime(): a45.  Platform support for using these parameters can
          be checked via the sets *note os.supports_dir_fd: a46. and
          ‘os.supports_follows_symlinks’.

        - The following functions now support a file descriptor for
          their path argument: *note chdir(): a47, *note chmod(): a3b,
          *note chown(): a3c, *note execve(): a48, *note listdir(): a49,
          *note pathconf(): a4a, *note exists(): 1f7, *note stat(): 1f2,
          *note statvfs(): a4b, *note utime(): a45.  Platform support
          for this can be checked via the *note os.supports_fd: a4c.
          set.

   * *note access(): a39. accepts an ‘effective_ids’ keyword argument to
     turn on using the effective uid/gid rather than the real uid/gid in
     the access check.  Platform support for this can be checked via the
     *note supports_effective_ids: a4d. set.

   * The *note os: c5. module has two new functions: *note
     getpriority(): a4e. and *note setpriority(): a4f.  They can be used
     to get or set process niceness/priority in a fashion similar to
     *note os.nice(): a50. but extended to all processes instead of just
     the current one.

     (Patch submitted by Giampaolo Rodolà in bpo-10784(5).)

   * The new *note os.replace(): a41. function allows cross-platform
     renaming of a file with overwriting the destination.  With *note
     os.rename(): a40, an existing destination file is overwritten under
     POSIX, but raises an error under Windows.  (Contributed by Antoine
     Pitrou in bpo-8828(6).)

   * The stat family of functions (*note stat(): 1f2, *note fstat():
     668, and *note lstat(): 1f3.) now support reading a file’s
     timestamps with nanosecond precision.  Symmetrically, *note
     utime(): a45. can now write file timestamps with nanosecond
     precision.  (Contributed by Larry Hastings in bpo-14127(7).)

   * The new *note os.get_terminal_size(): a51. function queries the
     size of the terminal attached to a file descriptor.  See also *note
     shutil.get_terminal_size(): a52.  (Contributed by Zbigniew
     Jędrzejewski-Szmek in bpo-13609(8).)

   * New functions to support Linux extended attributes (bpo-12720(9)):
     *note getxattr(): a53, *note listxattr(): a54, *note removexattr():
     a55, *note setxattr(): a56.

   * New interface to the scheduler.  These functions control how a
     process is allocated CPU time by the operating system.  New
     functions: *note sched_get_priority_max(): a57, *note
     sched_get_priority_min(): a58, *note sched_getaffinity(): a59,
     *note sched_getparam(): a5a, *note sched_getscheduler(): a5b, *note
     sched_rr_get_interval(): a5c, *note sched_setaffinity(): a5d, *note
     sched_setparam(): a5e, *note sched_setscheduler(): a5f, *note
     sched_yield(): a60,

   * New functions to control the file system:

        * *note posix_fadvise(): 66f.: Announces an intention to access
          data in a specific pattern thus allowing the kernel to make
          optimizations.

        * *note posix_fallocate(): 670.: Ensures that enough disk space
          is allocated for a file.

        * *note sync(): a61.: Force write of everything to disk.

   * Additional new posix functions:

        * *note lockf(): a62.: Apply, test or remove a POSIX lock on an
          open file descriptor.

        * *note pread(): 3c1.: Read from a file descriptor at an offset,
          the file offset remains unchanged.

        * *note pwrite(): 3c4.: Write to a file descriptor from an
          offset, leaving the file offset unchanged.

        * *note readv(): 3c0.: Read from a file descriptor into a number
          of writable buffers.

        * *note truncate(): 72d.: Truncate the file corresponding to
          `path', so that it is at most `length' bytes in size.

        * *note waitid(): 675.: Wait for the completion of one or more
          child processes.

        * *note writev(): 3c3.: Write the contents of `buffers' to a
          file descriptor, where `buffers' is an arbitrary sequence of
          buffers.

        * *note getgrouplist(): a63. (bpo-9344(10)): Return list of
          group ids that specified user belongs to.

   * *note times(): a64. and *note uname(): a65.: Return type changed
     from a tuple to a tuple-like object with named attributes.

   * Some platforms now support additional constants for the *note
     lseek(): a66. function, such as ‘os.SEEK_HOLE’ and ‘os.SEEK_DATA’.

   * New constants *note RTLD_LAZY: a67, *note RTLD_NOW: a68, *note
     RTLD_GLOBAL: a69, *note RTLD_LOCAL: a6a, *note RTLD_NODELETE: a6b,
     *note RTLD_NOLOAD: a6c, and *note RTLD_DEEPBIND: a6d. are available
     on platforms that support them.  These are for use with the *note
     sys.setdlopenflags(): a6e. function, and supersede the similar
     constants defined in *note ctypes: 2b. and ‘DLFCN’.  (Contributed
     by Victor Stinner in bpo-13226(11).)

   * *note os.symlink(): a43. now accepts (and ignores) the
     ‘target_is_directory’ keyword argument on non-Windows platforms, to
     ease cross-platform support.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10882

   (2) https://bugs.python.org/issue4761

   (3) https://bugs.python.org/issue10755

   (4) https://bugs.python.org/issue14626

   (5) https://bugs.python.org/issue10784

   (6) https://bugs.python.org/issue8828

   (7) https://bugs.python.org/issue14127

   (8) https://bugs.python.org/issue13609

   (9) https://bugs.python.org/issue12720

   (10) https://bugs.python.org/issue9344

   (11) https://bugs.python.org/issue13226


File: python.info,  Node: pdb<4>,  Next: pickle<5>,  Prev: os<7>,  Up: 改进的模块<6>

1.6.20.35 pdb
.............

Tab-completion is now available not only for command names, but also
their arguments.  For example, for the ‘break’ command, function and
file names are completed.

（由 Georg Brandl 在 bpo-14210(1) 中贡献）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14210


File: python.info,  Node: pickle<5>,  Next: pydoc<4>,  Prev: pdb<4>,  Up: 改进的模块<6>

1.6.20.36 pickle
................

*note pickle.Pickler: 20e. objects now have an optional *note
dispatch_table: a71. attribute allowing per-pickler reduction functions
to be set.

（由 Richard Oudkerk 在 bpo-14166(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14166


File: python.info,  Node: pydoc<4>,  Next: re<6>,  Prev: pickle<5>,  Up: 改进的模块<6>

1.6.20.37 pydoc
...............

The Tk GUI and the ‘serve()’ function have been removed from the *note
pydoc: da. module: ‘pydoc -g’ and ‘serve()’ have been deprecated in
Python 3.2.


File: python.info,  Node: re<6>,  Next: sched,  Prev: pydoc<4>,  Up: 改进的模块<6>

1.6.20.38 re
............

*note str: 339. regular expressions now support ‘\u’ and ‘\U’ escapes.

（由 Serhiy Storchaka 在 bpo-3665(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3665


File: python.info,  Node: sched,  Next: select<2>,  Prev: re<6>,  Up: 改进的模块<6>

1.6.20.39 sched
...............

   * *note run(): a75. now accepts a `blocking' parameter which when set
     to false makes the method execute the scheduled events due to
     expire soonest (if any) and then return immediately.  This is
     useful in case you want to use the *note scheduler: a76. in
     non-blocking applications.  (Contributed by Giampaolo Rodolà in
     bpo-13449(1).)

   * *note scheduler: a76. class can now be safely used in
     multi-threaded environments.  (Contributed by Josiah Carlson and
     Giampaolo Rodolà in bpo-8684(2).)

   * `timefunc' and `delayfunct' parameters of *note scheduler: a76.
     class constructor are now optional and defaults to *note
     time.time(): 326. and *note time.sleep(): 689. respectively.
     (Contributed by Chris Clark in bpo-13245(3).)

   * *note enter(): a77. and *note enterabs(): a78. `argument' parameter
     is now optional.  (Contributed by Chris Clark in bpo-13245(4).)

   * *note enter(): a77. and *note enterabs(): a78. now accept a
     `kwargs' parameter.  (Contributed by Chris Clark in bpo-13245(5).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13449

   (2) https://bugs.python.org/issue8684

   (3) https://bugs.python.org/issue13245

   (4) https://bugs.python.org/issue13245

   (5) https://bugs.python.org/issue13245


File: python.info,  Node: select<2>,  Next: shlex<3>,  Prev: sched,  Up: 改进的模块<6>

1.6.20.40 select
................

Solaris and derivative platforms have a new class *note select.devpoll:
8b4. for high performance asynchronous sockets via ‘/dev/poll’.
(Contributed by Jesús Cea Avión in bpo-6397(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6397


File: python.info,  Node: shlex<3>,  Next: shutil<4>,  Prev: select<2>,  Up: 改进的模块<6>

1.6.20.41 shlex
...............

The previously undocumented helper function ‘quote’ from the *note
pipes: cd. modules has been moved to the *note shlex: e9. module and
documented.  *note quote(): a7b. properly escapes all characters in a
string that might be otherwise given special meaning by the shell.


File: python.info,  Node: shutil<4>,  Next: signal<3>,  Prev: shlex<3>,  Up: 改进的模块<6>

1.6.20.42 shutil
................

   * 新的函数：

        * *note disk_usage(): a7d.: provides total, used and free disk
          space statistics.  (Contributed by Giampaolo Rodolà in
          bpo-12442(1).)

        * *note chown(): a7e.: allows one to change user and/or group of
          the given path also specifying the user/group names and not
          only their numeric ids.  (Contributed by Sandro Tosi in
          bpo-12191(2).)

        * *note shutil.get_terminal_size(): a52.: returns the size of
          the terminal window to which the interpreter is attached.
          (Contributed by Zbigniew Jędrzejewski-Szmek in bpo-13609(3).)

   * *note copy2(): 25b. and *note copystat(): a7f. now preserve file
     timestamps with nanosecond precision on platforms that support it.
     They also preserve file "extended attributes" on Linux.
     (Contributed by Larry Hastings in bpo-14127(4) and bpo-15238(5).)

   * Several functions now take an optional ‘symlinks’ argument: when
     that parameter is true, symlinks aren’t dereferenced and the
     operation instead acts on the symlink itself (or creates one, if
     relevant).  (Contributed by Hynek Schlawack in bpo-12715(6).)

   * When copying files to a different file system, *note move(): 25c.
     now handles symlinks the way the posix ‘mv’ command does,
     recreating the symlink rather than copying the target file
     contents.  (Contributed by Jonathan Niehof in bpo-9993(7).)  *note
     move(): 25c. now also returns the ‘dst’ argument as its result.

   * *note rmtree(): 21d. is now resistant to symlink attacks on
     platforms which support the new ‘dir_fd’ parameter in *note
     os.open(): 66e. and *note os.unlink(): a44.  (Contributed by Martin
     von Löwis and Hynek Schlawack in bpo-4489(8).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12442

   (2) https://bugs.python.org/issue12191

   (3) https://bugs.python.org/issue13609

   (4) https://bugs.python.org/issue14127

   (5) https://bugs.python.org/issue15238

   (6) https://bugs.python.org/issue12715

   (7) https://bugs.python.org/issue9993

   (8) https://bugs.python.org/issue4489


File: python.info,  Node: signal<3>,  Next: smtpd<3>,  Prev: shutil<4>,  Up: 改进的模块<6>

1.6.20.43 signal
................

   * The *note signal: eb. module has new functions:

        * *note pthread_sigmask(): a81.: fetch and/or change the signal
          mask of the calling thread (Contributed by Jean-Paul Calderone
          in bpo-8407(1));

        * *note pthread_kill(): a82.: send a signal to a thread;

        * *note sigpending(): a83.: examine pending functions;

        * *note sigwait(): a84.: wait a signal;

        * *note sigwaitinfo(): 688.: wait for a signal, returning
          detailed information about it;

        * *note sigtimedwait(): 687.: like *note sigwaitinfo(): 688. but
          with a timeout.

   * The signal handler writes the signal number as a single byte
     instead of a nul byte into the wakeup file descriptor.  So it is
     possible to wait more than one signal and know which signals were
     raised.

   * *note signal.signal(): a85. and *note signal.siginterrupt(): a86.
     raise an OSError, instead of a RuntimeError: OSError has an errno
     attribute.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8407


File: python.info,  Node: smtpd<3>,  Next: smtplib<3>,  Prev: signal<3>,  Up: 改进的模块<6>

1.6.20.44 smtpd
...............

The *note smtpd: ed. module now supports RFC 5321(1) (extended SMTP) and
RFC 1870(2) (size extension).  Per the standard, these extensions are
enabled if and only if the client initiates the session with an ‘EHLO’
command.

(Initial ‘ELHO’ support by Alberto Trevino.  Size extension by Juhana
Jauhiainen.  Substantial additional work on the patch contributed by
Michele Orrù and Dan Boswell.  bpo-8739(3))

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc5321.html

   (2) https://tools.ietf.org/html/rfc1870.html

   (3) https://bugs.python.org/issue8739


File: python.info,  Node: smtplib<3>,  Next: socket<7>,  Prev: smtpd<3>,  Up: 改进的模块<6>

1.6.20.45 smtplib
.................

The *note SMTP: a89, *note SMTP_SSL: a8a, and *note LMTP: a8b. classes
now accept a ‘source_address’ keyword argument to specify the ‘(host,
port)’ to use as the source address in the bind call when creating the
outgoing socket.  (Contributed by Paulo Scardine in bpo-11281(1).)

*note SMTP: a89. now supports the context management protocol, allowing
an ‘SMTP’ instance to be used in a ‘with’ statement.  (Contributed by
Giampaolo Rodolà in bpo-11289(2).)

The *note SMTP_SSL: a8a. constructor and the *note starttls(): a8c.
method now accept an SSLContext parameter to control parameters of the
secure channel.  (Contributed by Kasun Herath in bpo-8809(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11281

   (2) https://bugs.python.org/issue11289

   (3) https://bugs.python.org/issue8809


File: python.info,  Node: socket<7>,  Next: socketserver<3>,  Prev: smtplib<3>,  Up: 改进的模块<6>

1.6.20.46 socket
................

   * The *note socket: 67d. class now exposes additional methods to
     process ancillary data when supported by the underlying platform:

        * *note sendmsg(): 685.

        * *note recvmsg(): 682.

        * *note recvmsg_into(): a8e.

     (Contributed by David Watson in bpo-6560(1), based on an earlier
     patch by Heiko Wundram)

   * The *note socket: 67d. class now supports the PF_CAN protocol
     family (‘https://en.wikipedia.org/wiki/Socketcan’), on Linux
     (‘https://lwn.net/Articles/253425’).

     (Contributed by Matthias Fuchs, updated by Tiago Gonçalves in
     bpo-10141(2).)

   * The *note socket: 67d. class now supports the PF_RDS protocol
     family (‘https://en.wikipedia.org/wiki/Reliable_Datagram_Sockets’
     and ‘https://oss.oracle.com/projects/rds/’).

   * The *note socket: 67d. class now supports the ‘PF_SYSTEM’ protocol
     family on OS X. (Contributed by Michael Goderbauer in
     bpo-13777(3).)

   * New function *note sethostname(): a8f. allows the hostname to be
     set on unix systems if the calling process has sufficient
     privileges.  (Contributed by Ross Lagerwall in bpo-10866(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6560

   (2) https://bugs.python.org/issue10141

   (3) https://bugs.python.org/issue13777

   (4) https://bugs.python.org/issue10866


File: python.info,  Node: socketserver<3>,  Next: sqlite3<5>,  Prev: socket<7>,  Up: 改进的模块<6>

1.6.20.47 socketserver
......................

*note BaseServer: a91. now has an overridable method *note
service_actions(): a92. that is called by the *note serve_forever():
a93. method in the service loop.  *note ForkingMixIn: 3dd. now uses this
to clean up zombie child processes.  (Contributed by Justin Warkentin in
bpo-11109(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11109


File: python.info,  Node: sqlite3<5>,  Next: ssl<8>,  Prev: socketserver<3>,  Up: 改进的模块<6>

1.6.20.48 sqlite3
.................

New *note sqlite3.Connection: 3e0. method *note set_trace_callback():
a95. can be used to capture a trace of all sql commands processed by
sqlite.  (Contributed by Torsten Landschoff in bpo-11688(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11688


File: python.info,  Node: ssl<8>,  Next: stat<2>,  Prev: sqlite3<5>,  Up: 改进的模块<6>

1.6.20.49 ssl
.............

   * The *note ssl: f4. module has two new random generation functions:

        * *note RAND_bytes(): a97.: generate cryptographically strong
          pseudo-random bytes.

        * *note RAND_pseudo_bytes(): a98.: generate pseudo-random bytes.

     （由 Victor Stinner 在 bpo-12049(1) 中贡献。）

   * The *note ssl: f4. module now exposes a finer-grained exception
     hierarchy in order to make it easier to inspect the various kinds
     of errors.  (Contributed by Antoine Pitrou in bpo-11183(2).)

   * *note load_cert_chain(): a99. now accepts a `password' argument to
     be used if the private key is encrypted.  (Contributed by Adam
     Simpkins in bpo-12803(3).)

   * Diffie-Hellman key exchange, both regular and Elliptic Curve-based,
     is now supported through the *note load_dh_params(): a9a. and *note
     set_ecdh_curve(): a9b. methods.  (Contributed by Antoine Pitrou in
     bpo-13626(4) and bpo-13627(5).)

   * SSL sockets have a new *note get_channel_binding(): a9c. method
     allowing the implementation of certain authentication mechanisms
     such as SCRAM-SHA-1-PLUS. (Contributed by Jacek Konieczny in
     bpo-12551(6).)

   * You can query the SSL compression algorithm used by an SSL socket,
     thanks to its new *note compression(): a9d. method.  The new
     attribute *note OP_NO_COMPRESSION: a9e. can be used to disable
     compression.  (Contributed by Antoine Pitrou in bpo-13634(7).)

   * Support has been added for the Next Protocol Negotiation extension
     using the *note ssl.SSLContext.set_npn_protocols(): a9f. method.
     (Contributed by Colin Marc in bpo-14204(8).)

   * SSL errors can now be introspected more easily thanks to *note
     library: aa0. and *note reason: aa1. attributes.  (Contributed by
     Antoine Pitrou in bpo-14837(9).)

   * The *note get_server_certificate(): aa2. function now supports
     IPv6.  (Contributed by Charles-François Natali in bpo-11811(10).)

   * New attribute *note OP_CIPHER_SERVER_PREFERENCE: aa3. allows
     setting SSLv3 server sockets to use the server’s cipher ordering
     preference rather than the client’s (bpo-13635(11)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12049

   (2) https://bugs.python.org/issue11183

   (3) https://bugs.python.org/issue12803

   (4) https://bugs.python.org/issue13626

   (5) https://bugs.python.org/issue13627

   (6) https://bugs.python.org/issue12551

   (7) https://bugs.python.org/issue13634

   (8) https://bugs.python.org/issue14204

   (9) https://bugs.python.org/issue14837

   (10) https://bugs.python.org/issue11811

   (11) https://bugs.python.org/issue13635


File: python.info,  Node: stat<2>,  Next: struct<3>,  Prev: ssl<8>,  Up: 改进的模块<6>

1.6.20.50 stat
..............

The undocumented tarfile.filemode function has been moved to *note
stat.filemode(): aa5.  It can be used to convert a file’s mode to a
string of the form ’-rwxrwxrwx’.

（由 Giampaolo Rodolà 在 bpo-14807(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14807


File: python.info,  Node: struct<3>,  Next: subprocess<5>,  Prev: stat<2>,  Up: 改进的模块<6>

1.6.20.51 struct
................

The *note struct: f9. module now supports ‘ssize_t’ and ‘size_t’ via the
new codes ‘n’ and ‘N’, respectively.  (Contributed by Antoine Pitrou in
bpo-3163(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3163


File: python.info,  Node: subprocess<5>,  Next: sys<7>,  Prev: struct<3>,  Up: 改进的模块<6>

1.6.20.52 subprocess
....................

Command strings can now be bytes objects on posix platforms.
(Contributed by Victor Stinner in bpo-8513(1).)

A new constant *note DEVNULL: aa8. allows suppressing output in a
platform-independent fashion.  (Contributed by Ross Lagerwall in
bpo-5870(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8513

   (2) https://bugs.python.org/issue5870


File: python.info,  Node: sys<7>,  Next: tarfile<4>,  Prev: subprocess<5>,  Up: 改进的模块<6>

1.6.20.53 sys
.............

The *note sys: fe. module has a new *note thread_info: aaa. *note named
tuple: aab. holding information about the thread implementation
(bpo-11223(1)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11223


File: python.info,  Node: tarfile<4>,  Next: tempfile,  Prev: sys<7>,  Up: 改进的模块<6>

1.6.20.54 tarfile
.................

*note tarfile: 102. now supports ‘lzma’ encoding via the *note lzma: ae.
module.  (Contributed by Lars Gustäbel in bpo-5689(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5689


File: python.info,  Node: tempfile,  Next: textwrap<2>,  Prev: tarfile<4>,  Up: 改进的模块<6>

1.6.20.55 tempfile
..................

*note tempfile.SpooledTemporaryFile: aae.’s ‘truncate()’ method now
accepts a ‘size’ parameter.  (Contributed by Ryan Kelly in bpo-9957(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9957


File: python.info,  Node: textwrap<2>,  Next: threading<5>,  Prev: tempfile,  Up: 改进的模块<6>

1.6.20.56 textwrap
..................

The *note textwrap: 109. module has a new *note indent(): ab0. that
makes it straightforward to add a common prefix to selected lines in a
block of text (bpo-13857(1)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13857


File: python.info,  Node: threading<5>,  Next: time<5>,  Prev: textwrap<2>,  Up: 改进的模块<6>

1.6.20.57 threading
...................

*note threading.Condition: ab2, *note threading.Semaphore: ab3, *note
threading.BoundedSemaphore: ab4, *note threading.Event: ab5, and *note
threading.Timer: ab6, all of which used to be factory functions
returning a class instance, are now classes and may be subclassed.
(Contributed by Éric Araujo in bpo-10968(1).)

The *note threading.Thread: 235. constructor now accepts a ‘daemon’
keyword argument to override the default behavior of inheriting the
‘daemon’ flag value from the parent thread (bpo-6064(2)).

The formerly private function ‘_thread.get_ident’ is now available as
the public function *note threading.get_ident(): ab7.  This eliminates
several cases of direct access to the ‘_thread’ module in the stdlib.
Third party code that used ‘_thread.get_ident’ should likewise be
changed to use the new public interface.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10968

   (2) https://bugs.python.org/issue6064


File: python.info,  Node: time<5>,  Next: types<4>,  Prev: threading<5>,  Up: 改进的模块<6>

1.6.20.58 time
..............

The PEP 418(1) added new functions to the *note time: 10b. module:

   * *note get_clock_info(): ab9.: Get information on a clock.

   * *note monotonic(): 778.: Monotonic clock (cannot go backward), not
     affected by system clock updates.

   * *note perf_counter(): 2ab.: Performance counter with the highest
     available resolution to measure a short duration.

   * *note process_time(): 2ac.: Sum of the system and user CPU time of
     the current process.

Other new functions:

   * *note clock_getres(): aba, *note clock_gettime(): abb. and *note
     clock_settime(): abc. functions with ‘CLOCK_xxx’ constants.
     (Contributed by Victor Stinner in bpo-10278(2).)

To improve cross platform consistency, *note sleep(): 689. now raises a
*note ValueError: 1fc. when passed a negative sleep value.  Previously
this was an error on posix, but produced an infinite sleep on Windows.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0418

   (2) https://bugs.python.org/issue10278


File: python.info,  Node: types<4>,  Next: unittest<5>,  Prev: time<5>,  Up: 改进的模块<6>

1.6.20.59 types
...............

Add a new *note types.MappingProxyType: abe. class: Read-only proxy of a
mapping.  (bpo-14386(1))

The new functions *note types.new_class(): abf. and *note
types.prepare_class(): ac0. provide support for PEP 3115(2) compliant
dynamic type creation.  (bpo-14588(3))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14386

   (2) https://www.python.org/dev/peps/pep-3115

   (3) https://bugs.python.org/issue14588


File: python.info,  Node: unittest<5>,  Next: urllib<3>,  Prev: types<4>,  Up: 改进的模块<6>

1.6.20.60 unittest
..................

*note assertRaises(): ac2, *note assertRaisesRegex(): ac3, *note
assertWarns(): ac4, and *note assertWarnsRegex(): ac5. now accept a
keyword argument `msg' when used as context managers.  (Contributed by
Ezio Melotti and Winston Ewert in bpo-10775(1).)

*note unittest.TestCase.run(): ac6. now returns the *note TestResult:
ac7. object.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10775


File: python.info,  Node: urllib<3>,  Next: webbrowser,  Prev: unittest<5>,  Up: 改进的模块<6>

1.6.20.61 urllib
................

The *note Request: 8fe. class, now accepts a `method' argument used by
*note get_method(): ac9. to determine what HTTP method should be used.
For example, this will send a ‘'HEAD'’ request:

     >>> urlopen(Request('https://www.python.org', method='HEAD'))

(bpo-1673007(1))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1673007


File: python.info,  Node: webbrowser,  Next: xml etree ElementTree,  Prev: urllib<3>,  Up: 改进的模块<6>

1.6.20.62 webbrowser
....................

The *note webbrowser: 12a. module supports more "browsers": Google
Chrome (named ‘chrome’, ‘chromium’, ‘chrome-browser’ or
‘chromium-browser’ depending on the version and operating system), and
the generic launchers ‘xdg-open’, from the FreeDesktop.org project, and
‘gvfs-open’, which is the default URI handler for GNOME 3.  (The former
contributed by Arnaud Calmettes in bpo-13620(1), the latter by Matthias
Klose in bpo-14493(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13620

   (2) https://bugs.python.org/issue14493


File: python.info,  Node: xml etree ElementTree,  Next: zlib<2>,  Prev: webbrowser,  Up: 改进的模块<6>

1.6.20.63 xml.etree.ElementTree
...............................

The *note xml.etree.ElementTree: 138. module now imports its C
accelerator by default; there is no longer a need to explicitly import
‘xml.etree.cElementTree’ (this module stays for backwards compatibility,
but is now deprecated).  In addition, the ‘iter’ family of methods of
*note Element: acc. has been optimized (rewritten in C). The module’s
documentation has also been greatly improved with added examples and a
more detailed reference.


File: python.info,  Node: zlib<2>,  Prev: xml etree ElementTree,  Up: 改进的模块<6>

1.6.20.64 zlib
..............

New attribute *note zlib.Decompress.eof: ace. makes it possible to
distinguish between a properly-formed compressed stream and an
incomplete or truncated one.  (Contributed by Nadeem Vawda in
bpo-12646(1).)

New attribute *note zlib.ZLIB_RUNTIME_VERSION: acf. reports the version
string of the underlying ‘zlib’ library that is loaded at runtime.
(Contributed by Torsten Landschoff in bpo-12306(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12646

   (2) https://bugs.python.org/issue12306


File: python.info,  Node: 性能优化<5>,  Next: 构建和 C API 的改变<4>,  Prev: 改进的模块<6>,  Up: Python 3 3 有什么新变化

1.6.21 性能优化
---------------

Major performance enhancements have been added:

   * Thanks to PEP 393(1), some operations on Unicode strings have been
     optimized:

        * the memory footprint is divided by 2 to 4 depending on the
          text

        * encode an ASCII string to UTF-8 doesn’t need to encode
          characters anymore, the UTF-8 representation is shared with
          the ASCII representation

        * the UTF-8 encoder has been optimized

        * repeating a single ASCII letter and getting a substring of an
          ASCII string is 4 times faster

   * UTF-8 is now 2x to 4x faster.  UTF-16 encoding is now up to 10x
     faster.

     (Contributed by Serhiy Storchaka, bpo-14624(2), bpo-14738(3) and
     bpo-15026(4).)

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393

   (2) https://bugs.python.org/issue14624

   (3) https://bugs.python.org/issue14738

   (4) https://bugs.python.org/issue15026


File: python.info,  Node: 构建和 C API 的改变<4>,  Next: 弃用<5>,  Prev: 性能优化<5>,  Up: Python 3 3 有什么新变化

1.6.22 构建和 C API 的改变
--------------------------

Changes to Python’s build process and to the C API include:

   * 新的 PEP 3118(1) 相关功能：

        * *note PyMemoryView_FromMemory(): ad1.

   * PEP 393(2) 添加了新的 Unicode 类型，宏和函数

        * 高阶 API

             * *note PyUnicode_CopyCharacters(): ad2.

             * *note PyUnicode_FindChar(): 448.

             * *note PyUnicode_GetLength(): ad3, *note
               PyUnicode_GET_LENGTH: ad4.

             * *note PyUnicode_New(): ad5.

             * *note PyUnicode_Substring(): ad6.

             * *note PyUnicode_ReadChar(): ad7, *note
               PyUnicode_WriteChar(): ad8.

        * 低阶 API:

             * *note Py_UCS1: ad9, *note Py_UCS2: ada, *note Py_UCS4:
               adb. 类型

             * *note PyASCIIObject: adc. 和 *note
               PyCompactUnicodeObject: add. 结构

             * *note PyUnicode_READY: ade.

             * *note PyUnicode_FromKindAndData(): adf.

             * *note PyUnicode_AsUCS4(): ae0, *note
               PyUnicode_AsUCS4Copy(): ae1.

             * *note PyUnicode_DATA: ae2, *note PyUnicode_1BYTE_DATA:
               ae3, *note PyUnicode_2BYTE_DATA: ae4, *note
               PyUnicode_4BYTE_DATA: ae5.

             * *note PyUnicode_KIND: ae6. 使用 ‘PyUnicode_Kind’ 枚举:
               *note PyUnicode_WCHAR_KIND: ae7, *note
               PyUnicode_1BYTE_KIND: ae8, *note PyUnicode_2BYTE_KIND:
               ae9, *note PyUnicode_4BYTE_KIND: aea.

             * *note PyUnicode_READ: aeb, *note PyUnicode_READ_CHAR:
               aec, *note PyUnicode_WRITE: aed.

             * *note PyUnicode_MAX_CHAR_VALUE: aee.

   * *note PyArg_ParseTuple: 26b. 现在接受 ‘c’ 格式的 *note bytearray:
     33b. (bpo-12380(3))。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3118

   (2) https://www.python.org/dev/peps/pep-0393

   (3) https://bugs.python.org/issue12380


File: python.info,  Node: 弃用<5>,  Next: 移植到 Python 3 3,  Prev: 构建和 C API 的改变<4>,  Up: Python 3 3 有什么新变化

1.6.23 弃用
-----------

* Menu:

* 不支持的操作系统: 不支持的操作系统<2>.
* 已弃用的 Python 模块、函数和方法: 已弃用的 Python 模块、函数和方法<4>.
* 已弃用的 C API 函数和类型: 已弃用的 C API 函数和类型<3>.
* 弃用的功能::


File: python.info,  Node: 不支持的操作系统<2>,  Next: 已弃用的 Python 模块、函数和方法<4>,  Up: 弃用<5>

1.6.23.1 不支持的操作系统
.........................

由于缺少维护人员，不再支持 OS/2 和 VMS 系统 。

由于维护负担，将 ‘COMSPEC’ 设置为 ‘command.com’ 的 Windows平台（含
Windows 2000）不再受支持。

OSF支持在3.2中被弃用，现在已经被完全删除。


File: python.info,  Node: 已弃用的 Python 模块、函数和方法<4>,  Next: 已弃用的 C API 函数和类型<3>,  Prev: 不支持的操作系统<2>,  Up: 弃用<5>

1.6.23.2 已弃用的 Python 模块、函数和方法
.........................................

   * Passing a non-empty string to ‘object.__format__()’ is deprecated,
     and will produce a *note TypeError: 193. in Python 3.4
     (bpo-9856(1)).

   * The ‘unicode_internal’ codec has been deprecated because of the PEP
     393(2), use UTF-8, UTF-16 (‘utf-16-le’ or ‘utf-16-be’), or UTF-32
     (‘utf-32-le’ or ‘utf-32-be’)

   * *note ftplib.FTP.nlst(): a0e. and *note ftplib.FTP.dir(): a0f.: use
     *note ftplib.FTP.mlsd(): a0d.

   * ‘platform.popen()’: use the *note subprocess: fa. module.  Check
     especially the *note 使用 subprocess 模块替换旧函数: af2. section
     (bpo-11377(3)).

   * bpo-13374(4): The Windows bytes API has been deprecated in the
     *note os: c5. module.  Use Unicode filenames, instead of bytes
     filenames, to not depend on the ANSI code page anymore and to
     support any filename.

   * bpo-13988(5): The ‘xml.etree.cElementTree’ module is deprecated.
     The accelerator is used automatically whenever available.

   * The behaviour of ‘time.clock()’ depends on the platform: use the
     new *note time.perf_counter(): 2ab. or *note time.process_time():
     2ac. function instead, depending on your requirements, to have a
     well defined behaviour.

   * The ‘os.stat_float_times()’ function is deprecated.

   * *note abc: 4. module:

        * *note abc.abstractproperty: 9d5. has been deprecated, use
          *note property: 1d8. with *note abc.abstractmethod(): 9d6.
          instead.

        * *note abc.abstractclassmethod: 9d7. has been deprecated, use
          *note classmethod: 1d9. with *note abc.abstractmethod(): 9d6.
          instead.

        * *note abc.abstractstaticmethod: 9d8. has been deprecated, use
          *note staticmethod: 1da. with *note abc.abstractmethod(): 9d6.
          instead.

   * *note importlib: 9b. package:

        * *note importlib.abc.SourceLoader.path_mtime(): af3. is now
          deprecated in favour of *note
          importlib.abc.SourceLoader.path_stats(): af4. as bytecode
          files now store both the modification time and size of the
          source file the bytecode file was compiled from.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9856

   (2) https://www.python.org/dev/peps/pep-0393

   (3) https://bugs.python.org/issue11377

   (4) https://bugs.python.org/issue13374

   (5) https://bugs.python.org/issue13988


File: python.info,  Node: 已弃用的 C API 函数和类型<3>,  Next: 弃用的功能,  Prev: 已弃用的 Python 模块、函数和方法<4>,  Up: 弃用<5>

1.6.23.3 已弃用的 C API 函数和类型
..................................

*note Py_UNICODE: af6. 已经在 PEP 393(1) 弃用，并将于 Python 4 中移除。
所有使用此类型的函数都已弃用：

Unicode functions and methods using *note Py_UNICODE: af6. and *note
Py_UNICODE*: af6. types:

   * *note PyUnicode_FromUnicode: af7.: 使用 *note
     PyUnicode_FromWideChar(): af8. 或 *note
     PyUnicode_FromKindAndData(): adf.

   * *note PyUnicode_AS_UNICODE: af9, *note PyUnicode_AsUnicode(): afa,
     *note PyUnicode_AsUnicodeAndSize(): afb.: 使用 *note
     PyUnicode_AsWideCharString(): 440.

   * *note PyUnicode_AS_DATA: afc.: 使用 *note PyUnicode_DATA: ae2. 以及
     *note PyUnicode_READ: aeb. 和 *note PyUnicode_WRITE: aed.

   * *note PyUnicode_GET_SIZE: afd, *note PyUnicode_GetSize(): afe.: 使
     用 *note PyUnicode_GET_LENGTH: ad4. 或 *note PyUnicode_GetLength():
     ad3.

   * *note PyUnicode_GET_DATA_SIZE: aff.: 使用
     ‘PyUnicode_GET_LENGTH(str) * PyUnicode_KIND(str)’ (仅适用于现成的字
     符串)

   * *note PyUnicode_AsUnicodeCopy(): b00.: 使用 *note
     PyUnicode_AsUCS4Copy(): ae1. 或 *note PyUnicode_AsWideCharString():
     440.

   * ‘PyUnicode_GetMax()’

Functions and macros manipulating Py_UNICODE* strings:

   * ‘Py_UNICODE_strlen’: 使用 *note PyUnicode_GetLength(): ad3. 或
     *note PyUnicode_GET_LENGTH: ad4.

   * ‘Py_UNICODE_strcat’: 使用 *note PyUnicode_CopyCharacters(): ad2. 或
     *note PyUnicode_FromFormat(): 7d4.

   * ‘Py_UNICODE_strcpy’, ‘Py_UNICODE_strncpy’, ‘Py_UNICODE_COPY’: 使用
     *note PyUnicode_CopyCharacters(): ad2. 或 *note
     PyUnicode_Substring(): ad6.

   * ‘Py_UNICODE_strcmp’: 使用 *note PyUnicode_Compare(): b01.

   * ‘Py_UNICODE_strncmp’: 使用 *note PyUnicode_Tailmatch(): b02.

   * ‘Py_UNICODE_strchr’, ‘Py_UNICODE_strrchr’: 使用 *note
     PyUnicode_FindChar(): 448.

   * ‘Py_UNICODE_FILL’: 使用 *note PyUnicode_Fill(): b03.

   * ‘Py_UNICODE_MATCH’

编码器:

   * *note PyUnicode_Encode(): b04.: 使用 ‘PyUnicode_AsEncodedObject()’

   * *note PyUnicode_EncodeUTF7(): b05.

   * *note PyUnicode_EncodeUTF8(): b06.: 使用 *note PyUnicode_AsUTF8():
     433. 或 *note PyUnicode_AsUTF8String(): b07.

   * *note PyUnicode_EncodeUTF32(): b08.

   * *note PyUnicode_EncodeUTF16(): b09.

   * *note PyUnicode_EncodeUnicodeEscape(): b0a. use *note
     PyUnicode_AsUnicodeEscapeString(): b0b.

   * *note PyUnicode_EncodeRawUnicodeEscape(): b0c. use *note
     PyUnicode_AsRawUnicodeEscapeString(): b0d.

   * *note PyUnicode_EncodeLatin1(): b0e.: 使用 *note
     PyUnicode_AsLatin1String(): b0f.

   * *note PyUnicode_EncodeASCII(): b10.: 使用 *note
     PyUnicode_AsASCIIString(): b11.

   * *note PyUnicode_EncodeCharmap(): b12.

   * *note PyUnicode_TranslateCharmap(): b13.

   * *note PyUnicode_EncodeMBCS(): b14.: 使用 *note
     PyUnicode_AsMBCSString(): b15. 或 *note PyUnicode_EncodeCodePage():
     b16. (和 ‘CP_ACP’ code_page)

   * ‘PyUnicode_EncodeDecimal()’, *note
     PyUnicode_TransformDecimalToASCII(): b17.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393


File: python.info,  Node: 弃用的功能,  Prev: 已弃用的 C API 函数和类型<3>,  Up: 弃用<5>

1.6.23.4 弃用的功能
...................

The *note array: 7. module’s ‘'u'’ format code is now deprecated and
will be removed in Python 4 together with the rest of the (*note
Py_UNICODE: af6.) API.


File: python.info,  Node: 移植到 Python 3 3,  Prev: 弃用<5>,  Up: Python 3 3 有什么新变化

1.6.24 移植到 Python 3.3
------------------------

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

* Menu:

* Porting Python code::
* Porting C code::
* Building C extensions::
* Command Line Switch Changes::


File: python.info,  Node: Porting Python code,  Next: Porting C code,  Up: 移植到 Python 3 3

1.6.24.1 Porting Python code
............................

   * Hash randomization is enabled by default.  Set the *note
     PYTHONHASHSEED: 9cd. environment variable to ‘0’ to disable hash
     randomization.  See also the *note object.__hash__(): 349. method.

   * bpo-12326(1): On Linux, sys.platform doesn’t contain the major
     version anymore.  It is now always ’linux’, instead of ’linux2’ or
     ’linux3’ depending on the Linux version used to build Python.
     Replace sys.platform == ’linux2’ with
     sys.platform.startswith(’linux’), or directly sys.platform ==
     ’linux’ if you don’t need to support older Python versions.

   * bpo-13847(2), bpo-14180(3): *note time: 10b. and *note datetime:
     31.: *note OverflowError: 968. is now raised instead of *note
     ValueError: 1fc. if a timestamp is out of range.  *note OSError:
     1d4. is now raised if C functions ‘gmtime()’ or ‘localtime()’
     failed.

   * The default finders used by import now utilize a cache of what is
     contained within a specific directory.  If you create a Python
     source file or sourceless bytecode file, make sure to call *note
     importlib.invalidate_caches(): 4a4. to clear out the cache for the
     finders to notice the new file.

   * *note ImportError: 33d. now uses the full name of the module that
     was attempted to be imported.  Doctests that check ImportErrors’
     message will need to be updated to use the full name of the module
     instead of just the tail of the name.

   * The `index' argument to *note __import__(): 619. now defaults to 0
     instead of -1 and no longer support negative values.  It was an
     oversight when PEP 328(4) was implemented that the default value
     remained -1.  If you need to continue to perform a relative import
     followed by an absolute import, then perform the relative import
     using an index of 1, followed by another import using an index of
     0.  It is preferred, though, that you use *note
     importlib.import_module(): b1b. rather than call *note
     __import__(): 619. directly.

   * *note __import__(): 619. no longer allows one to use an index value
     other than 0 for top-level modules.  E.g.  ‘__import__('sys',
     level=1)’ is now an error.

   * Because *note sys.meta_path: 5ef. and *note sys.path_hooks: 964.
     now have finders on them by default, you will most likely want to
     use ‘list.insert()’ instead of ‘list.append()’ to add to those
     lists.

   * Because ‘None’ is now inserted into *note sys.path_importer_cache:
     4a5, if you are clearing out entries in the dictionary of paths
     that do not have a finder, you will need to remove keys paired with
     values of ‘None’ `and' *note imp.NullImporter: 9c3. to be
     backwards-compatible.  This will lead to extra overhead on older
     versions of Python that re-insert ‘None’ into *note
     sys.path_importer_cache: 4a5. where it represents the use of
     implicit finders, but semantically it should not change anything.

   * *note importlib.abc.Finder: 9bd. no longer specifies a
     ‘find_module()’ abstract method that must be implemented.  If you
     were relying on subclasses to implement that method, make sure to
     check for the method’s existence first.  You will probably want to
     check for ‘find_loader()’ first, though, in the case of working
     with *note path entry finders: 9ba.

   * *note pkgutil: ce. has been converted to use *note importlib: 9b.
     internally.  This eliminates many edge cases where the old
     behaviour of the PEP 302(5) import emulation failed to match the
     behaviour of the real import system.  The import emulation itself
     is still present, but is now deprecated.  The *note
     pkgutil.iter_importers(): b1c. and *note pkgutil.walk_packages():
     493. functions special case the standard import hooks so they are
     still supported even though they do not provide the non-standard
     ‘iter_modules()’ method.

   * A longstanding RFC-compliance bug (bpo-1079(6)) in the parsing done
     by *note email.header.decode_header(): a01. has been fixed.  Code
     that uses the standard idiom to convert encoded headers into
     unicode (‘str(make_header(decode_header(h))’) will see no change,
     but code that looks at the individual tuples returned by
     decode_header will see that whitespace that precedes or follows
     ‘ASCII’ sections is now included in the ‘ASCII’ section.  Code that
     builds headers using ‘make_header’ should also continue to work
     without change, since ‘make_header’ continues to add whitespace
     between ‘ASCII’ and non-‘ASCII’ sections if it is not already
     present in the input strings.

   * *note email.utils.formataddr(): b1d. now does the correct content
     transfer encoding when passed non-‘ASCII’ display names.  Any code
     that depended on the previous buggy behavior that preserved the
     non-‘ASCII’ unicode in the formatted output string will need to be
     changed (bpo-1690608(7)).

   * *note poplib.POP3.quit(): b1e. may now raise protocol errors like
     all other ‘poplib’ methods.  Code that assumes ‘quit’ does not
     raise *note poplib.error_proto: b1f. errors may need to be changed
     if errors on ‘quit’ are encountered by a particular application
     (bpo-11291(8)).

   * The ‘strict’ argument to *note email.parser.Parser: b20, deprecated
     since Python 2.4, has finally been removed.

   * The deprecated method ‘unittest.TestCase.assertSameElements’ has
     been removed.

   * The deprecated variable ‘time.accept2dyear’ has been removed.

   * The deprecated ‘Context._clamp’ attribute has been removed from the
     *note decimal: 36. module.  It was previously replaced by the
     public attribute ‘clamp’.  (See bpo-8540(9).)

   * The undocumented internal helper class ‘SSLFakeFile’ has been
     removed from *note smtplib: ee, since its functionality has long
     been provided directly by *note socket.socket.makefile(): b21.

   * Passing a negative value to *note time.sleep(): 689. on Windows now
     raises an error instead of sleeping forever.  It has always raised
     an error on posix.

   * The ‘ast.__version__’ constant has been removed.  If you need to
     make decisions affected by the AST version, use *note
     sys.version_info: b22. to make the decision.

   * Code that used to work around the fact that the *note threading:
     10a. module used factory functions by subclassing the private
     classes will need to change to subclass the now-public classes.

   * The undocumented debugging machinery in the threading module has
     been removed, simplifying the code.  This should have no effect on
     production code, but is mentioned here in case any application
     debug frameworks were interacting with it (bpo-13550(10)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12326

   (2) https://bugs.python.org/issue13847

   (3) https://bugs.python.org/issue14180

   (4) https://www.python.org/dev/peps/pep-0328

   (5) https://www.python.org/dev/peps/pep-0302

   (6) https://bugs.python.org/issue1079

   (7) https://bugs.python.org/issue1690608

   (8) https://bugs.python.org/issue11291

   (9) https://bugs.python.org/issue8540

   (10) https://bugs.python.org/issue13550


File: python.info,  Node: Porting C code,  Next: Building C extensions,  Prev: Porting Python code,  Up: 移植到 Python 3 3

1.6.24.2 Porting C code
.......................

   * In the course of changes to the buffer API the undocumented
     ‘smalltable’ member of the *note Py_buffer: b23. structure has been
     removed and the layout of the ‘PyMemoryViewObject’ has changed.

     All extensions relying on the relevant parts in ‘memoryobject.h’ or
     ‘object.h’ must be rebuilt.

   * Due to *note PEP 393: 984, the *note Py_UNICODE: af6. type and all
     functions using this type are deprecated (but will stay available
     for at least five years).  If you were using low-level Unicode APIs
     to construct and access unicode objects and you want to benefit of
     the memory footprint reduction provided by PEP 393(1), you have to
     convert your code to the new *note Unicode API: b24.

     However, if you only have been using high-level functions such as
     *note PyUnicode_Concat(): b25, *note PyUnicode_Join(): b26. or
     *note PyUnicode_FromFormat(): 7d4, your code will automatically
     take advantage of the new unicode representations.

   * *note PyImport_GetMagicNumber(): b27. now returns ‘-1’ upon
     failure.

   * As a negative value for the `level' argument to *note __import__():
     619. is no longer valid, the same now holds for *note
     PyImport_ImportModuleLevel(): b28.  This also means that the value
     of `level' used by *note PyImport_ImportModuleEx(): b29. is now ‘0’
     instead of ‘-1’.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393


File: python.info,  Node: Building C extensions,  Next: Command Line Switch Changes,  Prev: Porting C code,  Up: 移植到 Python 3 3

1.6.24.3 Building C extensions
..............................

   * The range of possible file names for C extensions has been
     narrowed.  Very rarely used spellings have been suppressed: under
     POSIX, files named ‘xxxmodule.so’, ‘xxxmodule.abi3.so’ and
     ‘xxxmodule.cpython-*.so’ are no longer recognized as implementing
     the ‘xxx’ module.  If you had been generating such files, you have
     to switch to the other spellings (i.e., remove the ‘module’ string
     from the file names).

     (implemented in bpo-14040(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14040


File: python.info,  Node: Command Line Switch Changes,  Prev: Building C extensions,  Up: 移植到 Python 3 3

1.6.24.4 Command Line Switch Changes
....................................

   * The -Q command-line flag and related artifacts have been removed.
     Code checking sys.flags.division_warning will need updating.

     （bpo-10998(1)，由 Éric Araujo 贡献。）

   * When ‘python’ is started with *note -S: b2c, ‘import site’ will no
     longer add site-specific paths to the module search paths.  In
     previous versions, it did.

     (bpo-11591(2), contributed by Carl Meyer with editions by Éric
     Araujo.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10998

   (2) https://bugs.python.org/issue11591


File: python.info,  Node: Python 3 2 有什么新变化,  Next: Python 3 1 有什么新变化,  Prev: Python 3 3 有什么新变化,  Up: Python的新变化

1.7 Python 3.2 有什么新变化
===========================


作者: Raymond Hettinger

This article explains the new features in Python 3.2 as compared to 3.1.
It focuses on a few highlights and gives a few examples.  For full
details, see the Misc/NEWS(1) file.

参见
....

PEP 392(2) - Python 3.2 发布计划

* Menu:

* PEP 384; 定义稳定的ABI: PEP 384 定义稳定的ABI.
* PEP 389; Argparse 命令行解析模块: PEP 389 Argparse 命令行解析模块.
* PEP 391; 基于字典的日志配置: PEP 391 基于字典的日志配置.
* PEP 3148; concurrent.futures 模块: PEP 3148 concurrent futures 模块.
* PEP 3147; PYC 仓库目录: PEP 3147 PYC 仓库目录.
* PEP 3149; ABI Version Tagged .so Files: PEP 3149 ABI Version Tagged so Files.
* PEP 3333; Python Web服务器网关接口v1.0.1: PEP 3333 Python Web服务器网关接口v1 0 1.
* 其他语言特性修改: 其他语言特性修改<7>.
* 新增，改进和弃用的模块::
* 多线程::
* 性能优化: 性能优化<6>.
* Unicode::
* 编解码器::
* 文档::
* IDLE::
* 代码库::
* 构建和 C API 的改变: 构建和 C API 的改变<5>.
* 移植到 Python 3.2: 移植到 Python 3 2.

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/blob/076ca6c3c8df3030307e548d9be792ce3c1c6eea/Misc/NEWS

   (2) https://www.python.org/dev/peps/pep-0392


File: python.info,  Node: PEP 384 定义稳定的ABI,  Next: PEP 389 Argparse 命令行解析模块,  Up: Python 3 2 有什么新变化

1.7.1 PEP 384: 定义稳定的ABI
----------------------------

In the past, extension modules built for one Python version were often
not usable with other Python versions.  Particularly on Windows, every
feature release of Python required rebuilding all extension modules that
one wanted to use.  This requirement was the result of the free access
to Python interpreter internals that extension modules could use.

With Python 3.2, an alternative approach becomes available: extension
modules which restrict themselves to a limited API (by defining
Py_LIMITED_API) cannot use many of the internals, but are constrained to
a set of API functions that are promised to be stable for several
releases.  As a consequence, extension modules built for 3.2 in that
mode will also work with 3.3, 3.4, and so on.  Extension modules that
make use of details of memory structures can still be built, but will
need to be recompiled for every feature release.

参见
....

PEP 384(1) - 定义稳定的ABI

     PEP 由 Martin von Löwis 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0384


File: python.info,  Node: PEP 389 Argparse 命令行解析模块,  Next: PEP 391 基于字典的日志配置,  Prev: PEP 384 定义稳定的ABI,  Up: Python 3 2 有什么新变化

1.7.2 PEP 389: Argparse 命令行解析模块
--------------------------------------

A new module for command line parsing, *note argparse: 6, was introduced
to overcome the limitations of *note optparse: c4. which did not provide
support for positional arguments (not just options), subcommands,
required options and other common patterns of specifying and validating
options.

This module has already had widespread success in the community as a
third-party module.  Being more fully featured than its predecessor, the
*note argparse: 6. module is now the preferred module for command-line
processing.  The older module is still being kept available because of
the substantial amount of legacy code that depends on it.

Here’s an annotated example parser showing features like limiting
results to a set of choices, specifying a `metavar' in the help screen,
validating that one or more positional arguments is present, and making
a required option:

     import argparse
     parser = argparse.ArgumentParser(
                 description = 'Manage servers',         # main description for help
                 epilog = 'Tested on Solaris and Linux') # displayed after help
     parser.add_argument('action',                       # argument name
                 choices = ['deploy', 'start', 'stop'],  # three allowed values
                 help = 'action on each target')         # help msg
     parser.add_argument('targets',
                 metavar = 'HOSTNAME',                   # var name used in help msg
                 nargs = '+',                            # require one or more targets
                 help = 'url for target machines')       # help msg explanation
     parser.add_argument('-u', '--user',                 # -u or --user option
                 required = True,                        # make it a required argument
                 help = 'login as user')

Example of calling the parser on a command string:

     >>> cmd = 'deploy sneezy.example.com sleepy.example.com -u skycaptain'
     >>> result = parser.parse_args(cmd.split())
     >>> result.action
     'deploy'
     >>> result.targets
     ['sneezy.example.com', 'sleepy.example.com']
     >>> result.user
     'skycaptain'

Example of the parser’s automatically generated help:

     >>> parser.parse_args('-h'.split())

     usage: manage_cloud.py [-h] -u USER
                            {deploy,start,stop} HOSTNAME [HOSTNAME ...]

     Manage servers

     positional arguments:
       {deploy,start,stop}   action on each target
       HOSTNAME              url for target machines

     optional arguments:
       -h, --help            show this help message and exit
       -u USER, --user USER  login as user

     Tested on Solaris and Linux

An especially nice *note argparse: 6. feature is the ability to define
subparsers, each with their own argument patterns and help displays:

     import argparse
     parser = argparse.ArgumentParser(prog='HELM')
     subparsers = parser.add_subparsers()

     parser_l = subparsers.add_parser('launch', help='Launch Control')   # first subgroup
     parser_l.add_argument('-m', '--missiles', action='store_true')
     parser_l.add_argument('-t', '--torpedos', action='store_true')

     parser_m = subparsers.add_parser('move', help='Move Vessel',        # second subgroup
                                      aliases=('steer', 'turn'))         # equivalent names
     parser_m.add_argument('-c', '--course', type=int, required=True)
     parser_m.add_argument('-s', '--speed', type=int, default=0)

     $ ./helm.py --help                         # top level help (launch and move)
     $ ./helm.py launch --help                  # help for launch options
     $ ./helm.py launch --missiles              # set missiles=True and torpedos=False
     $ ./helm.py steer --course 180 --speed 5   # set movement parameters

参见
....

PEP 389(1) - 新的命令行解析模块

     PEP 由 Steven Bethard 撰写

*note 升级 optparse 代码: b31. for details on the differences from *note
optparse: c4.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0389


File: python.info,  Node: PEP 391 基于字典的日志配置,  Next: PEP 3148 concurrent futures 模块,  Prev: PEP 389 Argparse 命令行解析模块,  Up: Python 3 2 有什么新变化

1.7.3 PEP 391: 基于字典的日志配置
---------------------------------

The *note logging: ab. module provided two kinds of configuration, one
style with function calls for each option or another style driven by an
external file saved in a ‘ConfigParser’ format.  Those options did not
provide the flexibility to create configurations from JSON or YAML
files, nor did they support incremental configuration, which is needed
for specifying logger options from a command line.

To support a more flexible style, the module now offers *note
logging.config.dictConfig(): b33. for specifying logging configuration
with plain Python dictionaries.  The configuration options include
formatters, handlers, filters, and loggers.  Here’s a working example of
a configuration dictionary:

     {"version": 1,
      "formatters": {"brief": {"format": "%(levelname)-8s: %(name)-15s: %(message)s"},
                     "full": {"format": "%(asctime)s %(name)-15s %(levelname)-8s %(message)s"}
                     },
      "handlers": {"console": {
                        "class": "logging.StreamHandler",
                        "formatter": "brief",
                        "level": "INFO",
                        "stream": "ext://sys.stdout"},
                   "console_priority": {
                        "class": "logging.StreamHandler",
                        "formatter": "full",
                        "level": "ERROR",
                        "stream": "ext://sys.stderr"}
                   },
      "root": {"level": "DEBUG", "handlers": ["console", "console_priority"]}}

If that dictionary is stored in a file called ‘conf.json’, it can be
loaded and called with code like this:

     >>> import json, logging.config
     >>> with open('conf.json') as f:
     ...     conf = json.load(f)
     ...
     >>> logging.config.dictConfig(conf)
     >>> logging.info("Transaction completed normally")
     INFO    : root           : Transaction completed normally
     >>> logging.critical("Abnormal termination")
     2011-02-17 11:14:36,694 root            CRITICAL Abnormal termination

参见
....

PEP 391(1) - 基于字典的日志配置

     PEP 由 Vinay Sajip 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0391


File: python.info,  Node: PEP 3148 concurrent futures 模块,  Next: PEP 3147 PYC 仓库目录,  Prev: PEP 391 基于字典的日志配置,  Up: Python 3 2 有什么新变化

1.7.4 PEP 3148: ‘concurrent.futures’ 模块
-----------------------------------------

Code for creating and managing concurrency is being collected in a new
top-level namespace, `concurrent'.  Its first member is a `futures'
package which provides a uniform high-level interface for managing
threads and processes.

The design for *note concurrent.futures: 22. was inspired by the
`java.util.concurrent' package.  In that model, a running call and its
result are represented by a *note Future: b35. object that abstracts
features common to threads, processes, and remote procedure calls.  That
object supports status checks (running or done), timeouts,
cancellations, adding callbacks, and access to results or exceptions.

The primary offering of the new module is a pair of executor classes for
launching and managing calls.  The goal of the executors is to make it
easier to use existing tools for making parallel calls.  They save the
effort needed to setup a pool of resources, launch the calls, create a
results queue, add time-out handling, and limit the total number of
threads, processes, or remote procedure calls.

Ideally, each application should share a single executor across multiple
components so that process and thread limits can be centrally managed.
This solves the design challenge that arises when each component has its
own competing strategy for resource management.

Both classes share a common interface with three methods: *note
submit(): 2a5. for scheduling a callable and returning a *note Future:
b35. object; *note map(): 6c7. for scheduling many asynchronous calls at
a time, and *note shutdown(): b36. for freeing resources.  The class is
a *note context manager: 571. and can be used in a *note with: 6f2.
statement to assure that resources are automatically released when
currently pending futures are done executing.

A simple of example of *note ThreadPoolExecutor: 27b. is a launch of
four parallel threads for copying files:

     import concurrent.futures, shutil
     with concurrent.futures.ThreadPoolExecutor(max_workers=4) as e:
         e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
         e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
         e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
         e.submit(shutil.copy, 'src3.txt', 'dest4.txt')

参见
....

PEP 3148(1) – futures - 异步执行指令

     PEP 由 Brian Quinlan 撰写

*note Code for Threaded Parallel URL reads: b37, an example using
threads to fetch multiple web pages in parallel.

*note Code for computing prime numbers in parallel: b38, an example
demonstrating *note ProcessPoolExecutor: 2a4.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3148


File: python.info,  Node: PEP 3147 PYC 仓库目录,  Next: PEP 3149 ABI Version Tagged so Files,  Prev: PEP 3148 concurrent futures 模块,  Up: Python 3 2 有什么新变化

1.7.5 PEP 3147: PYC 仓库目录
----------------------------

Python’s scheme for caching bytecode in `.pyc' files did not work well
in environments with multiple Python interpreters.  If one interpreter
encountered a cached file created by another interpreter, it would
recompile the source and overwrite the cached file, thus losing the
benefits of caching.

The issue of "pyc fights" has become more pronounced as it has become
commonplace for Linux distributions to ship with multiple versions of
Python.  These conflicts also arise with CPython alternatives such as
Unladen Swallow.

To solve this problem, Python’s import machinery has been extended to
use distinct filenames for each interpreter.  Instead of Python 3.2 and
Python 3.3 and Unladen Swallow each competing for a file called
"mymodule.pyc", they will now look for "mymodule.cpython-32.pyc",
"mymodule.cpython-33.pyc", and "mymodule.unladen10.pyc".  And to prevent
all of these new files from cluttering source directories, the `pyc'
files are now collected in a "__pycache__" directory stored under the
package directory.

Aside from the filenames and target directories, the new scheme has a
few aspects that are visible to the programmer:

   * Imported modules now have a *note __cached__: b3a. attribute which
     stores the name of the actual file that was imported:

          >>> import collections
          >>> collections.__cached__
          'c:/py32/lib/__pycache__/collections.cpython-32.pyc'

   * The tag that is unique to each interpreter is accessible from the
     *note imp: 9a. module:

          >>> import imp
          >>> imp.get_tag()
          'cpython-32'

   * Scripts that try to deduce source filename from the imported file
     now need to be smarter.  It is no longer sufficient to simply strip
     the "c" from a ".pyc" filename.  Instead, use the new functions in
     the *note imp: 9a. module:

          >>> imp.source_from_cache('c:/py32/lib/__pycache__/collections.cpython-32.pyc')
          'c:/py32/lib/collections.py'
          >>> imp.cache_from_source('c:/py32/lib/collections.py')
          'c:/py32/lib/__pycache__/collections.cpython-32.pyc'

   * The *note py_compile: d8. and *note compileall: 21. modules have
     been updated to reflect the new naming convention and target
     directory.  The command-line invocation of `compileall' has new
     options: ‘-i’ for specifying a list of files and directories to
     compile and ‘-b’ which causes bytecode files to be written to their
     legacy location rather than `__pycache__'.

   * The *note importlib.abc: 9c. module has been updated with new *note
     abstract base classes: b3b. for loading bytecode files.  The
     obsolete ABCs, ‘PyLoader’ and ‘PyPycLoader’, have been deprecated
     (instructions on how to stay Python 3.1 compatible are included
     with the documentation).

参见
....

PEP 3147(1) - PYC 仓库目录

     PEP 由 Barry Warsaw 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: PEP 3149 ABI Version Tagged so Files,  Next: PEP 3333 Python Web服务器网关接口v1 0 1,  Prev: PEP 3147 PYC 仓库目录,  Up: Python 3 2 有什么新变化

1.7.6 PEP 3149: ABI Version Tagged .so Files
--------------------------------------------

The PYC repository directory allows multiple bytecode cache files to be
co-located.  This PEP implements a similar mechanism for shared object
files by giving them a common directory and distinct names for each
version.

The common directory is "pyshared" and the file names are made distinct
by identifying the Python implementation (such as CPython, PyPy, Jython,
etc.), the major and minor version numbers, and optional build flags
(such as "d" for debug, "m" for pymalloc, "u" for wide-unicode).  For an
arbitrary package "foo", you may see these files when the distribution
package is installed:

     /usr/share/pyshared/foo.cpython-32m.so
     /usr/share/pyshared/foo.cpython-33md.so

In Python itself, the tags are accessible from functions in the *note
sysconfig: ff. module:

     >>> import sysconfig
     >>> sysconfig.get_config_var('SOABI')       # find the version tag
     'cpython-32mu'
     >>> sysconfig.get_config_var('EXT_SUFFIX')  # find the full filename extension
     '.cpython-32mu.so'

参见
....

PEP 3149(1) - ABI Version Tagged .so Files

     PEP 由 Barry Warsaw 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3149


File: python.info,  Node: PEP 3333 Python Web服务器网关接口v1 0 1,  Next: 其他语言特性修改<7>,  Prev: PEP 3149 ABI Version Tagged so Files,  Up: Python 3 2 有什么新变化

1.7.7 PEP 3333: Python Web服务器网关接口v1.0.1
----------------------------------------------

This informational PEP clarifies how bytes/text issues are to be handled
by the WSGI protocol.  The challenge is that string handling in Python 3
is most conveniently handled with the *note str: 339. type even though
the HTTP protocol is itself bytes oriented.

The PEP differentiates so-called `native strings' that are used for
request/response headers and metadata versus `byte strings' which are
used for the bodies of requests and responses.

The `native strings' are always of type *note str: 339. but are
restricted to code points between `U+0000' through `U+00FF' which are
translatable to bytes using `Latin-1' encoding.  These strings are used
for the keys and values in the environment dictionary and for response
headers and statuses in the ‘start_response()’ function.  They must
follow RFC 2616(1) with respect to encoding.  That is, they must either
be `ISO-8859-1' characters or use RFC 2047(2) MIME encoding.

For developers porting WSGI applications from Python 2, here are the
salient points:

   * If the app already used strings for headers in Python 2, no change
     is needed.

   * If instead, the app encoded output headers or decoded input
     headers, then the headers will need to be re-encoded to Latin-1.
     For example, an output header encoded in utf-8 was using
     ‘h.encode('utf-8')’ now needs to convert from bytes to native
     strings using ‘h.encode('utf-8').decode('latin-1')’.

   * Values yielded by an application or sent using the ‘write()’ method
     must be byte strings.  The ‘start_response()’ function and environ
     must use native strings.  The two cannot be mixed.

For server implementers writing CGI-to-WSGI pathways or other CGI-style
protocols, the users must to be able access the environment using native
strings even though the underlying platform may have a different
convention.  To bridge this gap, the *note wsgiref: 12d. module has a
new function, *note wsgiref.handlers.read_environ(): b3e. for
transcoding CGI variables from *note os.environ: b3f. into native
strings and returning a new dictionary.

参见
....

PEP 3333(3) - Python Web服务器网关接口v1.0.1

     PEP 由 Phillip Eby 撰写

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2616.html

   (2) https://tools.ietf.org/html/rfc2047.html

   (3) https://www.python.org/dev/peps/pep-3333


File: python.info,  Node: 其他语言特性修改<7>,  Next: 新增，改进和弃用的模块,  Prev: PEP 3333 Python Web服务器网关接口v1 0 1,  Up: Python 3 2 有什么新变化

1.7.8 其他语言特性修改
----------------------

对Python 语言核心进行的小改动：

   * String formatting for *note format(): 4e3. and *note str.format():
     4e2. gained new capabilities for the format character `#'.
     Previously, for integers in binary, octal, or hexadecimal, it
     caused the output to be prefixed with ’0b’, ’0o’, or ’0x’
     respectively.  Now it can also handle floats, complex, and Decimal,
     causing the output to always have a decimal point even when no
     digits follow it.

          >>> format(20, '#o')
          '0o24'
          >>> format(12.34, '#5.0f')
          '  12.'

     (Suggested by Mark Dickinson and implemented by Eric Smith in
     bpo-7094(1).)

   * There is also a new *note str.format_map(): 6ba. method that
     extends the capabilities of the existing *note str.format(): 4e2.
     method by accepting arbitrary *note mapping: b41. objects.  This
     new method makes it possible to use string formatting with any of
     Python’s many dictionary-like objects such as *note defaultdict:
     b42, *note Shelf: 8b9, *note ConfigParser: 4b2, or *note dbm: 32.
     It is also useful with custom *note dict: 1b9. subclasses that
     normalize keys before look-up or that supply a *note __missing__():
     b43. method for unknown keys:

          >>> import shelve
          >>> d = shelve.open('tmp.shl')
          >>> 'The {project_name} status is {status} as of {date}'.format_map(d)
          'The testing project status is green as of February 15, 2011'

          >>> class LowerCasedDict(dict):
          ...     def __getitem__(self, key):
          ...         return dict.__getitem__(self, key.lower())
          >>> lcd = LowerCasedDict(part='widgets', quantity=10)
          >>> 'There are {QUANTITY} {Part} in stock'.format_map(lcd)
          'There are 10 widgets in stock'

          >>> class PlaceholderDict(dict):
          ...     def __missing__(self, key):
          ...         return '<{}>'.format(key)
          >>> 'Hello {name}, welcome to {location}'.format_map(PlaceholderDict())
          'Hello <name>, welcome to <location>'

     (Suggested by Raymond Hettinger and implemented by Eric Smith in
     bpo-6081(2).)

   * The interpreter can now be started with a quiet option, ‘-q’, to
     prevent the copyright and version information from being displayed
     in the interactive mode.  The option can be introspected using the
     *note sys.flags: b44. attribute:

          $ python -q
          >>> sys.flags
          sys.flags(debug=0, division_warning=0, inspect=0, interactive=0,
          optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0,
          ignore_environment=0, verbose=0, bytes_warning=0, quiet=1)

     （由 Marcin Wojdyr 在 bpo-1772833(3) 中贡献。）

   * The *note hasattr(): 450. function works by calling *note
     getattr(): 451. and detecting whether an exception is raised.  This
     technique allows it to detect methods created dynamically by *note
     __getattr__(): 323. or *note __getattribute__(): 44f. which would
     otherwise be absent from the class dictionary.  Formerly, `hasattr'
     would catch any exception, possibly masking genuine errors.  Now,
     `hasattr' has been tightened to only catch *note AttributeError:
     3a3. and let other exceptions pass through:

          >>> class A:
          ...     @property
          ...     def f(self):
          ...         return 1 // 0
          ...
          >>> a = A()
          >>> hasattr(a, 'f')
          Traceback (most recent call last):
            ...
          ZeroDivisionError: integer division or modulo by zero

     (Discovered by Yury Selivanov and fixed by Benjamin Peterson;
     bpo-9666(4).)

   * The *note str(): 339. of a float or complex number is now the same
     as its *note repr(): 7d5.  Previously, the *note str(): 339. form
     was shorter but that just caused confusion and is no longer needed
     now that the shortest possible *note repr(): 7d5. is displayed by
     default:

          >>> import math
          >>> repr(math.pi)
          '3.141592653589793'
          >>> str(math.pi)
          '3.141592653589793'

     (Proposed and implemented by Mark Dickinson; bpo-9337(5).)

   * *note memoryview: 25d. objects now have a *note release(): b45.
     method and they also now support the context management protocol.
     This allows timely release of any resources that were acquired when
     requesting a buffer from the original object.

          >>> with memoryview(b'abcdefgh') as v:
          ...     print(v.tolist())
          [97, 98, 99, 100, 101, 102, 103, 104]

     (Added by Antoine Pitrou; bpo-9757(6).)

   * Previously it was illegal to delete a name from the local namespace
     if it occurs as a free variable in a nested block:

          def outer(x):
              def inner():
                  return x
              inner()
              del x

     This is now allowed.  Remember that the target of an *note except:
     b46. clause is cleared, so this code which used to work with Python
     2.6, raised a *note SyntaxError: 460. with Python 3.1 and now works
     again:

          def f():
              def print_error():
                  print(e)
              try:
                  something
              except Exception as e:
                  print_error()
                  # implicit "del e" here

     (See bpo-4617(7).)

   * The internal ‘structsequence’ tool now creates subclasses of tuple.
     This means that C structures like those returned by *note
     os.stat(): 1f2, *note time.gmtime(): b47, and *note
     sys.version_info: b22. now work like a *note named tuple: aab. and
     now work with functions and methods that expect a tuple as an
     argument.  This is a big step forward in making the C structures as
     flexible as their pure Python counterparts:

          >>> import sys
          >>> isinstance(sys.version_info, tuple)
          True
          >>> 'Version %d.%d.%d %s(%d)' % sys.version_info
          'Version 3.2.0 final(0)'

     (Suggested by Arfrever Frehtes Taifersar Arahesis and implemented
     by Benjamin Peterson in bpo-8413(8).)

   * Warnings are now easier to control using the *note PYTHONWARNINGS:
     420. environment variable as an alternative to using ‘-W’ at the
     command line:

          $ export PYTHONWARNINGS='ignore::RuntimeWarning::,once::UnicodeWarning::'

     (Suggested by Barry Warsaw and implemented by Philip Jenvey in
     bpo-7301(9).)

   * A new warning category, *note ResourceWarning: 4d8, has been added.
     It is emitted when potential issues with resource consumption or
     cleanup are detected.  It is silenced by default in normal release
     builds but can be enabled through the means provided by the *note
     warnings: 127. module, or on the command line.

     A *note ResourceWarning: 4d8. is issued at interpreter shutdown if
     the *note gc.garbage: b48. list isn’t empty, and if *note
     gc.DEBUG_UNCOLLECTABLE: b49. is set, all uncollectable objects are
     printed.  This is meant to make the programmer aware that their
     code contains object finalization issues.

     A *note ResourceWarning: 4d8. is also issued when a *note file
     object: b4a. is destroyed without having been explicitly closed.
     While the deallocator for such object ensures it closes the
     underlying operating system resource (usually, a file descriptor),
     the delay in deallocating the object could produce various issues,
     especially under Windows.  Here is an example of enabling the
     warning from the command line:

          $ python -q -Wdefault
          >>> f = open("foo", "wb")
          >>> del f
          __main__:1: ResourceWarning: unclosed file <_io.BufferedWriter name='foo'>

     (Added by Antoine Pitrou and Georg Brandl in bpo-10093(10) and
     bpo-477863(11).)

   * *note range: 9c6. objects now support `index' and `count' methods.
     This is part of an effort to make more objects fully implement the
     ‘collections.Sequence’ *note abstract base class: b3b.  As a
     result, the language will have a more uniform API. In addition,
     *note range: 9c6. objects now support slicing and negative indices,
     even with values larger than *note sys.maxsize: b4b.  This makes
     `range' more interoperable with lists:

          >>> range(0, 100, 2).count(10)
          1
          >>> range(0, 100, 2).index(10)
          5
          >>> range(0, 100, 2)[5]
          10
          >>> range(0, 100, 2)[0:5]
          range(0, 10, 2)

     （由 Daniel Stutzbach 在 bpo-9213(12) 中贡献，由 Alexander
     Belopolsky 在 bpo-2690(13) 中贡献，由 Nick Coghlan 在 bpo-10889(14)
     中贡献。）

   * The *note callable(): b4c. builtin function from Py2.x was
     resurrected.  It provides a concise, readable alternative to using
     an *note abstract base class: b3b. in an expression like
     ‘isinstance(x, collections.Callable)’:

          >>> callable(max)
          True
          >>> callable(20)
          False

     （见 bpo-10518(15) ）

   * Python’s import mechanism can now load modules installed in
     directories with non-ASCII characters in the path name.  This
     solved an aggravating problem with home directories for users with
     non-ASCII characters in their usernames.

     (Required extensive work by Victor Stinner in bpo-9425(16).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7094

   (2) https://bugs.python.org/issue6081

   (3) https://bugs.python.org/issue1772833

   (4) https://bugs.python.org/issue9666

   (5) https://bugs.python.org/issue9337

   (6) https://bugs.python.org/issue9757

   (7) https://bugs.python.org/issue4617

   (8) https://bugs.python.org/issue8413

   (9) https://bugs.python.org/issue7301

   (10) https://bugs.python.org/issue10093

   (11) https://bugs.python.org/issue477863

   (12) https://bugs.python.org/issue9213

   (13) https://bugs.python.org/issue2690

   (14) https://bugs.python.org/issue10889

   (15) https://bugs.python.org/issue10518

   (16) https://bugs.python.org/issue9425


File: python.info,  Node: 新增，改进和弃用的模块,  Next: 多线程,  Prev: 其他语言特性修改<7>,  Up: Python 3 2 有什么新变化

1.7.9 新增，改进和弃用的模块
----------------------------

Python’s standard library has undergone significant maintenance efforts
and quality improvements.

The biggest news for Python 3.2 is that the *note email: 69. package,
*note mailbox: af. module, and *note nntplib: c1. modules now work
correctly with the bytes/text model in Python 3.  For the first time,
there is correct handling of messages with mixed encodings.

Throughout the standard library, there has been more careful attention
to encodings and text versus bytes issues.  In particular, interactions
with the operating system are now better able to exchange non-ASCII data
using the Windows MBCS encoding, locale-aware encodings, or UTF-8.

Another significant win is the addition of substantially better support
for `SSL' connections and security certificates.

In addition, more classes now implement a *note context manager: 571. to
support convenient and reliable resource clean-up using a *note with:
6f2. statement.

* Menu:

* email: email<5>.
* elementtree::
* functools: functools<6>.
* itertools: itertools<4>.
* collections: collections<8>.
* threading: threading<6>.
* datetime 和 time::
* math: math<6>.
* abc: abc<3>.
* io: io<5>.
* reprlib::
* logging: logging<7>.
* csv: csv<3>.
* contextlib: contextlib<6>.
* decimal and fractions::
* ftp::
* popen::
* select: select<3>.
* gzip 和 zipfile::
* tarfile: tarfile<5>.
* hashlib: hashlib<3>.
* ast: ast<3>.
* os: os<8>.
* shutil: shutil<5>.
* sqlite3: sqlite3<6>.
* html: html<3>.
* socket: socket<8>.
* ssl: ssl<9>.
* nntp::
* certificates::
* imaplib: imaplib<3>.
* http.client: http client<4>.
* unittest: unittest<6>.
* random: random<2>.
* poplib: poplib<3>.
* asyncore: asyncore<2>.
* tempfile: tempfile<2>.
* inspect: inspect<6>.
* pydoc: pydoc<5>.
* dis: dis<3>.
* dbm: dbm<6>.
* ctypes: ctypes<2>.
* site: site<2>.
* sysconfig: sysconfig<2>.
* pdb: pdb<5>.
* configparser: configparser<2>.
* urllib.parse: urllib parse<3>.
* mailbox::
* turtledemo::


File: python.info,  Node: email<5>,  Next: elementtree,  Up: 新增，改进和弃用的模块

1.7.9.1 email
.............

The usability of the *note email: 69. package in Python 3 has been
mostly fixed by the extensive efforts of R. David Murray.  The problem
was that emails are typically read and stored in the form of *note
bytes: 33a. rather than *note str: 339. text, and they may contain
multiple encodings within a single email.  So, the email package had to
be extended to parse and generate email messages in bytes format.

   * New functions *note message_from_bytes(): b4f. and *note
     message_from_binary_file(): b50, and new classes *note
     BytesFeedParser: b51. and *note BytesParser: b52. allow binary
     message data to be parsed into model objects.

   * Given bytes input to the model, *note get_payload(): b53. will by
     default decode a message body that has a
     ‘Content-Transfer-Encoding’ of `8bit' using the charset specified
     in the MIME headers and return the resulting string.

   * Given bytes input to the model, *note Generator: b54. will convert
     message bodies that have a ‘Content-Transfer-Encoding’ of `8bit' to
     instead have a `7bit' ‘Content-Transfer-Encoding’.

     Headers with unencoded non-ASCII bytes are deemed to be RFC
     2047(1)-encoded using the `unknown-8bit' character set.

   * A new class *note BytesGenerator: b55. produces bytes as output,
     preserving any unchanged non-ASCII data that was present in the
     input used to build the model, including message bodies with a
     ‘Content-Transfer-Encoding’ of `8bit'.

   * The *note smtplib: ee. *note SMTP: a89. class now accepts a byte
     string for the `msg' argument to the *note sendmail(): 74d. method,
     and a new method, *note send_message(): 74e. accepts a *note
     Message: 54a. object and can optionally obtain the `from_addr' and
     `to_addrs' addresses directly from the object.

(Proposed and implemented by R. David Murray, bpo-4661(2) and
bpo-10321(3).)

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2047.html

   (2) https://bugs.python.org/issue4661

   (3) https://bugs.python.org/issue10321


File: python.info,  Node: elementtree,  Next: functools<6>,  Prev: email<5>,  Up: 新增，改进和弃用的模块

1.7.9.2 elementtree
...................

The *note xml.etree.ElementTree: 138. package and its
‘xml.etree.cElementTree’ counterpart have been updated to version 1.3.

Several new and useful functions and methods have been added:

   * *note xml.etree.ElementTree.fromstringlist(): b57. which builds an
     XML document from a sequence of fragments

   * *note xml.etree.ElementTree.register_namespace(): b58. for
     registering a global namespace prefix

   * *note xml.etree.ElementTree.tostringlist(): 91e. for string
     representation including all sublists

   * *note xml.etree.ElementTree.Element.extend(): b59. for appending a
     sequence of zero or more elements

   * *note xml.etree.ElementTree.Element.iterfind(): b5a. searches an
     element and subelements

   * *note xml.etree.ElementTree.Element.itertext(): b5b. creates a text
     iterator over an element and its subelements

   * *note xml.etree.ElementTree.TreeBuilder.end(): b5c. closes the
     current element

   * *note xml.etree.ElementTree.TreeBuilder.doctype(): 2c2. handles a
     doctype declaration

两个方法被弃用：

   * ‘xml.etree.ElementTree.getchildren()’ 被 ‘list(elem)’ 替代。

   * ‘xml.etree.ElementTree.getiterator()’ 被 ‘Element.iter’ 替代。

For details of the update, see Introducing ElementTree(1) on Fredrik
Lundh’s website.

（由 Florent Xicluna 和 Fredrik Lundh 在 bpo-6472(2) 中贡献。）

   ---------- Footnotes ----------

   (1) http://effbot.org/zone/elementtree-13-intro.htm

   (2) https://bugs.python.org/issue6472


File: python.info,  Node: functools<6>,  Next: itertools<4>,  Prev: elementtree,  Up: 新增，改进和弃用的模块

1.7.9.3 functools
.................

   * The *note functools: 85. module includes a new decorator for
     caching function calls.  *note functools.lru_cache(): 1c8. can save
     repeated queries to an external resource whenever the results are
     expected to be the same.

     For example, adding a caching decorator to a database query
     function can save database accesses for popular searches:

          >>> import functools
          >>> @functools.lru_cache(maxsize=300)
          ... def get_phone_number(name):
          ...     c = conn.cursor()
          ...     c.execute('SELECT phonenumber FROM phonelist WHERE name=?', (name,))
          ...     return c.fetchone()[0]

          >>> for name in user_requests:
          ...     get_phone_number(name)        # cached lookup

     To help with choosing an effective cache size, the wrapped function
     is instrumented for tracking cache statistics:

          >>> get_phone_number.cache_info()
          CacheInfo(hits=4805, misses=980, maxsize=300, currsize=300)

     If the phonelist table gets updated, the outdated contents of the
     cache can be cleared with:

          >>> get_phone_number.cache_clear()

     (Contributed by Raymond Hettinger and incorporating design ideas
     from Jim Baker, Miki Tebeka, and Nick Coghlan; see recipe
     498245(1), recipe 577479(2), bpo-10586(3), and bpo-10593(4).)

   * The *note functools.wraps(): 873. decorator now adds a
     ‘__wrapped__’ attribute pointing to the original callable function.
     This allows wrapped functions to be introspected.  It also copies
     ‘__annotations__’ if defined.  And now it also gracefully skips
     over missing attributes such as ‘__doc__’ which might not be
     defined for the wrapped callable.

     In the above example, the cache can be removed by recovering the
     original function:

          >>> get_phone_number = get_phone_number.__wrapped__    # uncached function

     (By Nick Coghlan and Terrence Cole; bpo-9567(5), bpo-3445(6), and
     bpo-8814(7).)

   * To help write classes with rich comparison methods, a new decorator
     *note functools.total_ordering(): 854. will use existing equality
     and inequality methods to fill in the remaining methods.

     For example, supplying `__eq__' and `__lt__' will enable *note
     total_ordering(): 854. to fill-in `__le__', `__gt__' and `__ge__':

          @total_ordering
          class Student:
              def __eq__(self, other):
                  return ((self.lastname.lower(), self.firstname.lower()) ==
                          (other.lastname.lower(), other.firstname.lower()))

              def __lt__(self, other):
                  return ((self.lastname.lower(), self.firstname.lower()) <
                          (other.lastname.lower(), other.firstname.lower()))

     With the `total_ordering' decorator, the remaining comparison
     methods are filled in automatically.

     （由 Raymond Hettinger 贡献。）

   * To aid in porting programs from Python 2, the *note
     functools.cmp_to_key(): b5e. function converts an old-style
     comparison function to modern *note key function: 6e9.:

          >>> # locale-aware sort order
          >>> sorted(iterable, key=cmp_to_key(locale.strcoll))

     For sorting examples and a brief sorting tutorial, see the Sorting
     HowTo(8) tutorial.

     （由 Raymond Hettinger 贡献。）

   ---------- Footnotes ----------

   (1) https://code.activestate.com/recipes/498245

   (2) https://code.activestate.com/recipes/577479

   (3) https://bugs.python.org/issue10586

   (4) https://bugs.python.org/issue10593

   (5) https://bugs.python.org/issue9567

   (6) https://bugs.python.org/issue3445

   (7) https://bugs.python.org/issue8814

   (8) https://wiki.python.org/moin/HowTo/Sorting/


File: python.info,  Node: itertools<4>,  Next: collections<8>,  Prev: functools<6>,  Up: 新增，改进和弃用的模块

1.7.9.4 itertools
.................

   * The *note itertools: a4. module has a new *note accumulate(): 1de.
     function modeled on APL’s `scan' operator and Numpy’s `accumulate'
     function:

          >>> from itertools import accumulate
          >>> list(accumulate([8, 2, 50]))
          [8, 10, 60]

          >>> prob_dist = [0.1, 0.4, 0.2, 0.3]
          >>> list(accumulate(prob_dist))      # cumulative probability distribution
          [0.1, 0.5, 0.7, 1.0]

     For an example using *note accumulate(): 1de, see the *note
     examples for the random module: b60.

     (Contributed by Raymond Hettinger and incorporating design
     suggestions from Mark Dickinson.)


File: python.info,  Node: collections<8>,  Next: threading<6>,  Prev: itertools<4>,  Up: 新增，改进和弃用的模块

1.7.9.5 collections
...................

   * The *note collections.Counter: 9e2. class now has two forms of
     in-place subtraction, the existing `-=' operator for saturating
     subtraction(1) and the new *note subtract(): b62. method for
     regular subtraction.  The former is suitable for multisets(2) which
     only have positive counts, and the latter is more suitable for use
     cases that allow negative counts:

          >>> from collections import Counter
          >>> tally = Counter(dogs=5, cats=3)
          >>> tally -= Counter(dogs=2, cats=8)    # saturating subtraction
          >>> tally
          Counter({'dogs': 3})

          >>> tally = Counter(dogs=5, cats=3)
          >>> tally.subtract(dogs=2, cats=8)      # regular subtraction
          >>> tally
          Counter({'dogs': 3, 'cats': -5})

     （由 Raymond Hettinger 贡献。）

   * The *note collections.OrderedDict: 1ba. class has a new method
     *note move_to_end(): b63. which takes an existing key and moves it
     to either the first or last position in the ordered sequence.

     The default is to move an item to the last position.  This is
     equivalent of renewing an entry with ‘od[k] = od.pop(k)’.

     A fast move-to-end operation is useful for resequencing entries.
     For example, an ordered dictionary can be used to track order of
     access by aging entries from the oldest to the most recently
     accessed.

          >>> from collections import OrderedDict
          >>> d = OrderedDict.fromkeys(['a', 'b', 'X', 'd', 'e'])
          >>> list(d)
          ['a', 'b', 'X', 'd', 'e']
          >>> d.move_to_end('X')
          >>> list(d)
          ['a', 'b', 'd', 'e', 'X']

     （由 Raymond Hettinger 贡献。）

   * The *note collections.deque: 539. class grew two new methods *note
     count(): b64. and *note reverse(): b65. that make them more
     substitutable for *note list: 263. objects:

          >>> from collections import deque
          >>> d = deque('simsalabim')
          >>> d.count('s')
          2
          >>> d.reverse()
          >>> d
          deque(['m', 'i', 'b', 'a', 'l', 'a', 's', 'm', 'i', 's'])

     （由 Raymond Hettinger 贡献。）

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Saturation_arithmetic

   (2) https://en.wikipedia.org/wiki/Multiset


File: python.info,  Node: threading<6>,  Next: datetime 和 time,  Prev: collections<8>,  Up: 新增，改进和弃用的模块

1.7.9.6 threading
.................

The *note threading: 10a. module has a new *note Barrier: b67.
synchronization class for making multiple threads wait until all of them
have reached a common barrier point.  Barriers are useful for making
sure that a task with multiple preconditions does not run until all of
the predecessor tasks are complete.

Barriers can work with an arbitrary number of threads.  This is a
generalization of a Rendezvous(1) which is defined for only two threads.

Implemented as a two-phase cyclic barrier, *note Barrier: b67. objects
are suitable for use in loops.  The separate `filling' and `draining'
phases assure that all threads get released (drained) before any one of
them can loop back and re-enter the barrier.  The barrier fully resets
after each cycle.

Example of using barriers:

     from threading import Barrier, Thread

     def get_votes(site):
         ballots = conduct_election(site)
         all_polls_closed.wait()        # do not count until all polls are closed
         totals = summarize(ballots)
         publish(site, totals)

     all_polls_closed = Barrier(len(sites))
     for site in sites:
         Thread(target=get_votes, args=(site,)).start()

In this example, the barrier enforces a rule that votes cannot be
counted at any polling site until all polls are closed.  Notice how a
solution with a barrier is similar to one with *note
threading.Thread.join(): b68, but the threads stay alive and continue to
do work (summarizing ballots) after the barrier point is crossed.

If any of the predecessor tasks can hang or be delayed, a barrier can be
created with an optional `timeout' parameter.  Then if the timeout
period elapses before all the predecessor tasks reach the barrier point,
all waiting threads are released and a *note BrokenBarrierError: b69.
exception is raised:

     def get_votes(site):
         ballots = conduct_election(site)
         try:
             all_polls_closed.wait(timeout=midnight - time.now())
         except BrokenBarrierError:
             lockbox = seal_ballots(ballots)
             queue.put(lockbox)
         else:
             totals = summarize(ballots)
             publish(site, totals)

In this example, the barrier enforces a more robust rule.  If some
election sites do not finish before midnight, the barrier times-out and
the ballots are sealed and deposited in a queue for later handling.

See Barrier Synchronization Patterns(2) for more examples of how
barriers can be used in parallel computing.  Also, there is a simple but
thorough explanation of barriers in The Little Book of Semaphores(3),
`section 3.6'.

(Contributed by Kristján Valur Jónsson with an API review by Jeffrey
Yasskin in bpo-8777(4).)

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Synchronous_rendezvous

   (2) 
http://osl.cs.illinois.edu/media/papers/karmani-2009-barrier_synchronization_pattern.pdf

   (3) https://greenteapress.com/semaphores/LittleBookOfSemaphores.pdf

   (4) https://bugs.python.org/issue8777


File: python.info,  Node: datetime 和 time,  Next: math<6>,  Prev: threading<6>,  Up: 新增，改进和弃用的模块

1.7.9.7 datetime 和 time
........................

   * The *note datetime: 31. module has a new type *note timezone: a09.
     that implements the *note tzinfo: 388. interface by returning a
     fixed UTC offset and timezone name.  This makes it easier to create
     timezone-aware datetime objects:

          >>> from datetime import datetime, timezone

          >>> datetime.now(timezone.utc)
          datetime.datetime(2010, 12, 8, 21, 4, 2, 923754, tzinfo=datetime.timezone.utc)

          >>> datetime.strptime("01/01/2000 12:00 +0000", "%m/%d/%Y %H:%M %z")
          datetime.datetime(2000, 1, 1, 12, 0, tzinfo=datetime.timezone.utc)

   * Also, *note timedelta: 196. objects can now be multiplied by *note
     float: 188. and divided by *note float: 188. and *note int: 185.
     objects.  And *note timedelta: 196. objects can now divide one
     another.

   * The *note datetime.date.strftime(): 540. method is no longer
     restricted to years after 1900.  The new supported year range is
     from 1000 to 9999 inclusive.

   * Whenever a two-digit year is used in a time tuple, the
     interpretation has been governed by ‘time.accept2dyear’.  The
     default is ‘True’ which means that for a two-digit year, the
     century is guessed according to the POSIX rules governing the ‘%y’
     strptime format.

     Starting with Py3.2, use of the century guessing heuristic will
     emit a *note DeprecationWarning: 279.  Instead, it is recommended
     that ‘time.accept2dyear’ be set to ‘False’ so that large date
     ranges can be used without guesswork:

          >>> import time, warnings
          >>> warnings.resetwarnings()      # remove the default warning filters

          >>> time.accept2dyear = True      # guess whether 11 means 11 or 2011
          >>> time.asctime((11, 1, 1, 12, 34, 56, 4, 1, 0))
          Warning (from warnings module):
            ...
          DeprecationWarning: Century info guessed for a 2-digit year.
          'Fri Jan  1 12:34:56 2011'

          >>> time.accept2dyear = False     # use the full range of allowable dates
          >>> time.asctime((11, 1, 1, 12, 34, 56, 4, 1, 0))
          'Fri Jan  1 12:34:56 11'

     Several functions now have significantly expanded date ranges.
     When ‘time.accept2dyear’ is false, the *note time.asctime(): b6b.
     function will accept any year that fits in a C int, while the *note
     time.mktime(): b6c. and *note time.strftime(): b6d. functions will
     accept the full range supported by the corresponding operating
     system functions.

(Contributed by Alexander Belopolsky and Victor Stinner in
bpo-1289118(1), bpo-5094(2), bpo-6641(3), bpo-2706(4), bpo-1777412(5),
bpo-8013(6), and bpo-10827(7).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1289118

   (2) https://bugs.python.org/issue5094

   (3) https://bugs.python.org/issue6641

   (4) https://bugs.python.org/issue2706

   (5) https://bugs.python.org/issue1777412

   (6) https://bugs.python.org/issue8013

   (7) https://bugs.python.org/issue10827


File: python.info,  Node: math<6>,  Next: abc<3>,  Prev: datetime 和 time,  Up: 新增，改进和弃用的模块

1.7.9.8 math
............

The *note math: b2. module has been updated with six new functions
inspired by the C99 standard.

The *note isfinite(): b6f. function provides a reliable and fast way to
detect special values.  It returns ‘True’ for regular numbers and
‘False’ for `Nan' or `Infinity':

     >>> from math import isfinite
     >>> [isfinite(x) for x in (123, 4.56, float('Nan'), float('Inf'))]
     [True, True, False, False]

The *note expm1(): b70. function computes ‘e**x-1’ for small values of
`x' without incurring the loss of precision that usually accompanies the
subtraction of nearly equal quantities:

     >>> from math import expm1
     >>> expm1(0.013671875)   # more accurate way to compute e**x-1 for a small x
     0.013765762467652909

The *note erf(): 45a. function computes a probability integral or
Gaussian error function(1).  The complementary error function, *note
erfc(): 45b, is ‘1 - erf(x)’:

     >>> from math import erf, erfc, sqrt
     >>> erf(1.0/sqrt(2.0))   # portion of normal distribution within 1 standard deviation
     0.682689492137086
     >>> erfc(1.0/sqrt(2.0))  # portion of normal distribution outside 1 standard deviation
     0.31731050786291404
     >>> erf(1.0/sqrt(2.0)) + erfc(1.0/sqrt(2.0))
     1.0

The *note gamma(): b71. function is a continuous extension of the
factorial function.  See ‘https://en.wikipedia.org/wiki/Gamma_function’
for details.  Because the function is related to factorials, it grows
large even for small values of `x', so there is also a *note lgamma():
b72. function for computing the natural logarithm of the gamma function:

     >>> from math import gamma, lgamma
     >>> gamma(7.0)           # six factorial
     720.0
     >>> lgamma(801.0)        # log(800 factorial)
     4551.950730698041

（由 Mark Dickinson 贡献）

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Error_function


File: python.info,  Node: abc<3>,  Next: io<5>,  Prev: math<6>,  Up: 新增，改进和弃用的模块

1.7.9.9 abc
...........

The *note abc: 4. module now supports *note abstractclassmethod(): 9d7.
and *note abstractstaticmethod(): 9d8.

These tools make it possible to define an *note abstract base class:
b3b. that requires a particular *note classmethod(): 1d9. or *note
staticmethod(): 1da. to be implemented:

     class Temperature(metaclass=abc.ABCMeta):
         @abc.abstractclassmethod
         def from_fahrenheit(cls, t):
             ...
         @abc.abstractclassmethod
         def from_celsius(cls, t):
             ...

(Patch submitted by Daniel Urban; bpo-5867(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5867


File: python.info,  Node: io<5>,  Next: reprlib,  Prev: abc<3>,  Up: 新增，改进和弃用的模块

1.7.9.10 io
...........

The *note io.BytesIO: 7a4. has a new method, *note getbuffer(): b75,
which provides functionality similar to *note memoryview(): 25d.  It
creates an editable view of the data without making a copy.  The
buffer’s random access and support for slice notation are well-suited to
in-place editing:

     >>> REC_LEN, LOC_START, LOC_LEN = 34, 7, 11

     >>> def change_location(buffer, record_number, location):
     ...     start = record_number * REC_LEN + LOC_START
     ...     buffer[start: start+LOC_LEN] = location

     >>> import io

     >>> byte_stream = io.BytesIO(
     ...     b'G3805  storeroom  Main chassis    '
     ...     b'X7899  shipping   Reserve cog     '
     ...     b'L6988  receiving  Primary sprocket'
     ... )
     >>> buffer = byte_stream.getbuffer()
     >>> change_location(buffer, 1, b'warehouse  ')
     >>> change_location(buffer, 0, b'showroom   ')
     >>> print(byte_stream.getvalue())
     b'G3805  showroom   Main chassis    '
     b'X7899  warehouse  Reserve cog     '
     b'L6988  receiving  Primary sprocket'

（由 Antoine Pitrou 在 bpo-5506(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5506


File: python.info,  Node: reprlib,  Next: logging<7>,  Prev: io<5>,  Up: 新增，改进和弃用的模块

1.7.9.11 reprlib
................

When writing a *note __repr__(): 347. method for a custom container, it
is easy to forget to handle the case where a member refers back to the
container itself.  Python’s builtin objects such as *note list: 263. and
*note set: b77. handle self-reference by displaying "..."  in the
recursive part of the representation string.

To help write such *note __repr__(): 347. methods, the *note reprlib:
e0. module has a new decorator, *note recursive_repr(): b78, for
detecting recursive calls to *note __repr__(): 347. and substituting a
placeholder string instead:

     >>> class MyList(list):
     ...     @recursive_repr()
     ...     def __repr__(self):
     ...         return '<' + '|'.join(map(repr, self)) + '>'
     ...
     >>> m = MyList('abc')
     >>> m.append(m)
     >>> m.append('x')
     >>> print(m)
     <'a'|'b'|'c'|...|'x'>

（由 Raymond Hettinger 在 bpo-9826(1) 和 bpo-9840(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9826

   (2) https://bugs.python.org/issue9840


File: python.info,  Node: logging<7>,  Next: csv<3>,  Prev: reprlib,  Up: 新增，改进和弃用的模块

1.7.9.12 logging
................

In addition to dictionary-based configuration described above, the *note
logging: ab. package has many other improvements.

The logging documentation has been augmented by a *note basic tutorial:
b7a, an *note advanced tutorial: b7b, and a *note cookbook: b7c. of
logging recipes.  These documents are the fastest way to learn about
logging.

The *note logging.basicConfig(): 1e1. set-up function gained a `style'
argument to support three different types of string formatting.  It
defaults to "%" for traditional %-formatting, can be set to "{" for the
new *note str.format(): 4e2. style, or can be set to "$" for the
shell-style formatting provided by *note string.Template: 3f3.  The
following three configurations are equivalent:

     >>> from logging import basicConfig
     >>> basicConfig(style='%', format="%(name)s -> %(levelname)s: %(message)s")
     >>> basicConfig(style='{', format="{name} -> {levelname} {message}")
     >>> basicConfig(style='$', format="$name -> $levelname: $message")

If no configuration is set-up before a logging event occurs, there is
now a default configuration using a *note StreamHandler: b7d. directed
to *note sys.stderr: 318. for events of ‘WARNING’ level or higher.
Formerly, an event occurring before a configuration was set-up would
either raise an exception or silently drop the event depending on the
value of ‘logging.raiseExceptions’.  The new default handler is stored
in *note logging.lastResort: b7e.

The use of filters has been simplified.  Instead of creating a *note
Filter: b7f. object, the predicate can be any Python callable that
returns ‘True’ or ‘False’.

There were a number of other improvements that add flexibility and
simplify configuration.  See the module documentation for a full listing
of changes in Python 3.2.


File: python.info,  Node: csv<3>,  Next: contextlib<6>,  Prev: logging<7>,  Up: 新增，改进和弃用的模块

1.7.9.13 csv
............

The *note csv: 2a. module now supports a new dialect, *note
unix_dialect: b81, which applies quoting for all fields and a
traditional Unix style with ‘'\n'’ as the line terminator.  The
registered dialect name is ‘unix’.

The *note csv.DictWriter: b82. has a new method, *note writeheader():
b83. for writing-out an initial row to document the field names:

     >>> import csv, sys
     >>> w = csv.DictWriter(sys.stdout, ['name', 'dept'], dialect='unix')
     >>> w.writeheader()
     "name","dept"
     >>> w.writerows([
     ...     {'name': 'tom', 'dept': 'accounting'},
     ...     {'name': 'susan', 'dept': 'Salesl'}])
     "tom","accounting"
     "susan","sales"

(New dialect suggested by Jay Talbot in bpo-5975(1), and the new method
suggested by Ed Abraham in bpo-1537721(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5975

   (2) https://bugs.python.org/issue1537721


File: python.info,  Node: contextlib<6>,  Next: decimal and fractions,  Prev: csv<3>,  Up: 新增，改进和弃用的模块

1.7.9.14 contextlib
...................

There is a new and slightly mind-blowing tool *note ContextDecorator:
b85. that is helpful for creating a *note context manager: 571. that
does double duty as a function decorator.

As a convenience, this new functionality is used by *note
contextmanager(): b86. so that no extra effort is needed to support both
roles.

The basic idea is that both context managers and function decorators can
be used for pre-action and post-action wrappers.  Context managers wrap
a group of statements using a *note with: 6f2. statement, and function
decorators wrap a group of statements enclosed in a function.  So,
occasionally there is a need to write a pre-action or post-action
wrapper that can be used in either role.

For example, it is sometimes useful to wrap functions or groups of
statements with a logger that can track the time of entry and time of
exit.  Rather than writing both a function decorator and a context
manager for the task, the *note contextmanager(): b86. provides both
capabilities in a single definition:

     from contextlib import contextmanager
     import logging

     logging.basicConfig(level=logging.INFO)

     @contextmanager
     def track_entry_and_exit(name):
         logging.info('Entering: %s', name)
         yield
         logging.info('Exiting: %s', name)

Formerly, this would have only been usable as a context manager:

     with track_entry_and_exit('widget loader'):
         print('Some time consuming activity goes here')
         load_widget()

Now, it can be used as a decorator as well:

     @track_entry_and_exit('widget loader')
     def activity():
         print('Some time consuming activity goes here')
         load_widget()

Trying to fulfill two roles at once places some limitations on the
technique.  Context managers normally have the flexibility to return an
argument usable by a *note with: 6f2. statement, but there is no
parallel for function decorators.

In the above example, there is not a clean way for the
`track_entry_and_exit' context manager to return a logging instance for
use in the body of enclosed statements.

（由 Michael Foord 在 bpo-9110(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9110


File: python.info,  Node: decimal and fractions,  Next: ftp,  Prev: contextlib<6>,  Up: 新增，改进和弃用的模块

1.7.9.15 decimal and fractions
..............................

Mark Dickinson crafted an elegant and efficient scheme for assuring that
different numeric datatypes will have the same hash value whenever their
actual values are equal (bpo-8188(1)):

     assert hash(Fraction(3, 2)) == hash(1.5) == \
            hash(Decimal("1.5")) == hash(complex(1.5, 0))

Some of the hashing details are exposed through a new attribute, *note
sys.hash_info: 929, which describes the bit width of the hash value, the
prime modulus, the hash values for `infinity' and `nan', and the
multiplier used for the imaginary part of a number:

     >>> sys.hash_info
     sys.hash_info(width=64, modulus=2305843009213693951, inf=314159, nan=0, imag=1000003)

An early decision to limit the inter-operability of various numeric
types has been relaxed.  It is still unsupported (and ill-advised) to
have implicit mixing in arithmetic expressions such as ‘Decimal('1.1') +
float('1.1')’ because the latter loses information in the process of
constructing the binary float.  However, since existing floating point
value can be converted losslessly to either a decimal or rational
representation, it makes sense to add them to the constructor and to
support mixed-type comparisons.

   * The *note decimal.Decimal: 189. constructor now accepts *note
     float: 188. objects directly so there in no longer a need to use
     the *note from_float(): b88. method (bpo-8257(2)).

   * Mixed type comparisons are now fully supported so that *note
     Decimal: 189. objects can be directly compared with *note float:
     188. and *note fractions.Fraction: 186. (bpo-2531(3) and
     bpo-8188(4)).

Similar changes were made to *note fractions.Fraction: 186. so that the
*note from_float(): b89. and *note from_decimal(): b8a. methods are no
longer needed (bpo-8294(5)):

     >>> from decimal import Decimal
     >>> from fractions import Fraction
     >>> Decimal(1.1)
     Decimal('1.100000000000000088817841970012523233890533447265625')
     >>> Fraction(1.1)
     Fraction(2476979795053773, 2251799813685248)

Another useful change for the *note decimal: 36. module is that the
‘Context.clamp’ attribute is now public.  This is useful in creating
contexts that correspond to the decimal interchange formats specified in
IEEE 754 (see bpo-8540(6)).

（由 Mark Dickinson 和 Raymond Hettinger贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8188

   (2) https://bugs.python.org/issue8257

   (3) https://bugs.python.org/issue2531

   (4) https://bugs.python.org/issue8188

   (5) https://bugs.python.org/issue8294

   (6) https://bugs.python.org/issue8540


File: python.info,  Node: ftp,  Next: popen,  Prev: decimal and fractions,  Up: 新增，改进和弃用的模块

1.7.9.16 ftp
............

The *note ftplib.FTP: 2f1. class now supports the context management
protocol to unconditionally consume *note socket.error: 99d. exceptions
and to close the FTP connection when done:

     >>> from ftplib import FTP
     >>> with FTP("ftp1.at.proftpd.org") as ftp:
             ftp.login()
             ftp.dir()

     '230 Anonymous login ok, restrictions apply.'
     dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 .
     dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 ..
     dr-xr-xr-x   5 ftp      ftp          4096 May  6 10:43 CentOS
     dr-xr-xr-x   3 ftp      ftp            18 Jul 10  2008 Fedora

Other file-like objects such as *note mmap.mmap: 1ed. and *note
fileinput.input(): 2ae. also grew auto-closing context managers:

     with fileinput.input(files=('log1.txt', 'log2.txt')) as f:
         for line in f:
             process(line)

（由 Tarek Ziadé 和 Giampaolo Rodolà 在 bpo-4972‘贡献，由 Georg Brandl 在
:issue:‘8046(1) 和 bpo-1286(2) 贡献。）

The *note FTP_TLS: a0b. class now accepts a `context' parameter, which
is a *note ssl.SSLContext: 3ec. object allowing bundling SSL
configuration options, certificates and private keys into a single
(potentially long-lived) structure.

（由 Giampaolo Rodolà 在 bpo-8806(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4972‘贡献，由 Georg Brandl 在
:issue:‘8046

   (2) https://bugs.python.org/issue1286

   (3) https://bugs.python.org/issue8806


File: python.info,  Node: popen,  Next: select<3>,  Prev: ftp,  Up: 新增，改进和弃用的模块

1.7.9.17 popen
..............

The *note os.popen(): 2aa. and *note subprocess.Popen(): 2ba. functions
now support *note with: 6f2. statements for auto-closing of the file
descriptors.

（由 Antoine Pitrou 和 Brian Curtin 在 bpo-7461(1) 和 bpo-10554(2) 中贡
献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7461

   (2) https://bugs.python.org/issue10554


File: python.info,  Node: select<3>,  Next: gzip 和 zipfile,  Prev: popen,  Up: 新增，改进和弃用的模块

1.7.9.18 select
...............

The *note select: e6. module now exposes a new, constant attribute,
*note PIPE_BUF: b8e, which gives the minimum number of bytes which are
guaranteed not to block when *note select.select(): 67c. says a pipe is
ready for writing.

     >>> import select
     >>> select.PIPE_BUF
     512

(Available on Unix systems.  Patch by Sébastien Sablé in bpo-9862(1))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9862


File: python.info,  Node: gzip 和 zipfile,  Next: tarfile<5>,  Prev: select<3>,  Up: 新增，改进和弃用的模块

1.7.9.19 gzip 和 zipfile
........................

*note gzip.GzipFile: 6e6. now implements the *note io.BufferedIOBase:
591. *note abstract base class: b3b. (except for ‘truncate()’).  It also
has a *note peek(): b90. method and supports unseekable as well as
zero-padded file objects.

The *note gzip: 8c. module also gains the *note compress(): 1d2. and
*note decompress(): b91. functions for easier in-memory compression and
decompression.  Keep in mind that text needs to be encoded as *note
bytes: 33a. before compressing and decompressing:

     >>> import gzip
     >>> s = 'Three shall be the number thou shalt count, '
     >>> s += 'and the number of the counting shall be three'
     >>> b = s.encode()                        # convert to utf-8
     >>> len(b)
     89
     >>> c = gzip.compress(b)
     >>> len(c)
     77
     >>> gzip.decompress(c).decode()[:42]      # decompress and convert to text
     'Three shall be the number thou shalt count'

（由 Anand B. Pillai 在 bpo-3488(1) 中贡献，由Antoine Pitrou, Nir Aides
和 Brian Curtin 在 bpo-9962(2)，bpo-1675951(3) ，bpo-7471(4) 和
bpo-2846(5) 中贡献。）

Also, the ‘zipfile.ZipExtFile’ class was reworked internally to
represent files stored inside an archive.  The new implementation is
significantly faster and can be wrapped in an *note io.BufferedReader:
b92. object for more speedups.  It also solves an issue where
interleaved calls to `read' and `readline' gave the wrong results.

(Patch submitted by Nir Aides in bpo-7610(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3488

   (2) https://bugs.python.org/issue9962

   (3) https://bugs.python.org/issue1675951

   (4) https://bugs.python.org/issue7471

   (5) https://bugs.python.org/issue2846

   (6) https://bugs.python.org/issue7610


File: python.info,  Node: tarfile<5>,  Next: hashlib<3>,  Prev: gzip 和 zipfile,  Up: 新增，改进和弃用的模块

1.7.9.20 tarfile
................

The *note TarFile: b94. class can now be used as a context manager.  In
addition, its *note add(): 484. method has a new option, `filter', that
controls which files are added to the archive and allows the file
metadata to be edited.

The new `filter' option replaces the older, less flexible `exclude'
parameter which is now deprecated.  If specified, the optional `filter'
parameter needs to be a *note keyword argument: 5cd.  The user-supplied
filter function accepts a *note TarInfo: b95. object and returns an
updated *note TarInfo: b95. object, or if it wants the file to be
excluded, the function can return ‘None’:

     >>> import tarfile, glob

     >>> def myfilter(tarinfo):
     ...     if tarinfo.isfile():             # only save real files
     ...         tarinfo.uname = 'monty'      # redact the user name
     ...         return tarinfo

     >>> with tarfile.open(name='myarchive.tar.gz', mode='w:gz') as tf:
     ...     for filename in glob.glob('*.txt'):
     ...         tf.add(filename, filter=myfilter)
     ...     tf.list()
     -rw-r--r-- monty/501        902 2011-01-26 17:59:11 annotations.txt
     -rw-r--r-- monty/501        123 2011-01-26 17:59:11 general_questions.txt
     -rw-r--r-- monty/501       3514 2011-01-26 17:59:11 prion.txt
     -rw-r--r-- monty/501        124 2011-01-26 17:59:11 py_todo.txt
     -rw-r--r-- monty/501       1399 2011-01-26 17:59:11 semaphore_notes.txt

(Proposed by Tarek Ziadé and implemented by Lars Gustäbel in
bpo-6856(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6856


File: python.info,  Node: hashlib<3>,  Next: ast<3>,  Prev: tarfile<5>,  Up: 新增，改进和弃用的模块

1.7.9.21 hashlib
................

The *note hashlib: 8d. module has two new constant attributes listing
the hashing algorithms guaranteed to be present in all implementations
and those available on the current implementation:

     >>> import hashlib

     >>> hashlib.algorithms_guaranteed
     {'sha1', 'sha224', 'sha384', 'sha256', 'sha512', 'md5'}

     >>> hashlib.algorithms_available
     {'md2', 'SHA256', 'SHA512', 'dsaWithSHA', 'mdc2', 'SHA224', 'MD4', 'sha256',
     'sha512', 'ripemd160', 'SHA1', 'MDC2', 'SHA', 'SHA384', 'MD2',
     'ecdsa-with-SHA1','md4', 'md5', 'sha1', 'DSA-SHA', 'sha224',
     'dsaEncryption', 'DSA', 'RIPEMD160', 'sha', 'MD5', 'sha384'}

（由 Carl Chenet 在 bpo-7418(1) 中建议。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7418


File: python.info,  Node: ast<3>,  Next: os<8>,  Prev: hashlib<3>,  Up: 新增，改进和弃用的模块

1.7.9.22 ast
............

The *note ast: 8. module has a wonderful a general-purpose tool for
safely evaluating expression strings using the Python literal syntax.
The *note ast.literal_eval(): 4ad. function serves as a secure
alternative to the builtin *note eval(): b98. function which is easily
abused.  Python 3.2 adds *note bytes: 33a. and *note set: b77. literals
to the list of supported types: strings, bytes, numbers, tuples, lists,
dicts, sets, booleans, and ‘None’.

     >>> from ast import literal_eval

     >>> request = "{'req': 3, 'func': 'pow', 'args': (2, 0.5)}"
     >>> literal_eval(request)
     {'args': (2, 0.5), 'req': 3, 'func': 'pow'}

     >>> request = "os.system('do something harmful')"
     >>> literal_eval(request)
     Traceback (most recent call last):
       ...
     ValueError: malformed node or string: <_ast.Call object at 0x101739a10>

（由Benjamin Peterson 和 Georg Brandl 实现。）


File: python.info,  Node: os<8>,  Next: shutil<5>,  Prev: ast<3>,  Up: 新增，改进和弃用的模块

1.7.9.23 os
...........

Different operating systems use various encodings for filenames and
environment variables.  The *note os: c5. module provides two new
functions, *note fsencode(): 4f7. and *note fsdecode(): 4f6, for
encoding and decoding filenames:

     >>> import os
     >>> filename = 'Sehenswürdigkeiten'
     >>> os.fsencode(filename)
     b'Sehensw\xc3\xbcrdigkeiten'

Some operating systems allow direct access to encoded bytes in the
environment.  If so, the *note os.supports_bytes_environ: b9a. constant
will be true.

For direct access to encoded environment variables (if available), use
the new *note os.getenvb(): b9b. function or use *note os.environb: b9c.
which is a bytes version of *note os.environ: b3f.

（由 Victor Stinner 贡献。）


File: python.info,  Node: shutil<5>,  Next: sqlite3<6>,  Prev: os<8>,  Up: 新增，改进和弃用的模块

1.7.9.24 shutil
...............

The *note shutil.copytree(): 21b. function has two new options:

   * `ignore_dangling_symlinks': when ‘symlinks=False’ so that the
     function copies a file pointed to by a symlink, not the symlink
     itself.  This option will silence the error raised if the file
     doesn’t exist.

   * `copy_function': is a callable that will be used to copy files.
     *note shutil.copy2(): 25b. is used by default.

（由 Tarek Ziadé 贡献。）

In addition, the *note shutil: ea. module now supports *note archiving
operations: b9e. for zipfiles, uncompressed tarfiles, gzipped tarfiles,
and bzipped tarfiles.  And there are functions for registering
additional archiving file formats (such as xz compressed tarfiles or
custom formats).

The principal functions are *note make_archive(): 21c. and *note
unpack_archive(): b9f.  By default, both operate on the current
directory (which can be set by *note os.chdir(): a47.) and on any
sub-directories.  The archive filename needs to be specified with a full
pathname.  The archiving step is non-destructive (the original files are
left unchanged).

     >>> import shutil, pprint

     >>> os.chdir('mydata')  # change to the source directory
     >>> f = shutil.make_archive('/var/backup/mydata',
     ...                         'zip')      # archive the current directory
     >>> f                                   # show the name of archive
     '/var/backup/mydata.zip'
     >>> os.chdir('tmp')                     # change to an unpacking
     >>> shutil.unpack_archive('/var/backup/mydata.zip')  # recover the data

     >>> pprint.pprint(shutil.get_archive_formats())  # display known formats
     [('bztar', "bzip2'ed tar-file"),
      ('gztar', "gzip'ed tar-file"),
      ('tar', 'uncompressed tar file'),
      ('zip', 'ZIP file')]

     >>> shutil.register_archive_format(     # register a new archive format
     ...     name='xz',
     ...     function=xz.compress,           # callable archiving function
     ...     extra_args=[('level', 8)],      # arguments to the function
     ...     description='xz compression'
     ... )

（由 Tarek Ziadé 贡献。）


File: python.info,  Node: sqlite3<6>,  Next: html<3>,  Prev: shutil<5>,  Up: 新增，改进和弃用的模块

1.7.9.25 sqlite3
................

The *note sqlite3: f3. module was updated to pysqlite version 2.6.0.  It
has two new capabilities.

   * The ‘sqlite3.Connection.in_transit’ attribute is true if there is
     an active transaction for uncommitted changes.

   * The *note sqlite3.Connection.enable_load_extension(): ba1. and
     *note sqlite3.Connection.load_extension(): ba2. methods allows you
     to load SQLite extensions from ".so" files.  One well-known
     extension is the fulltext-search extension distributed with SQLite.

（由 R. David Murray 和 Shashwat Anand 在 bpo-8845(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8845


File: python.info,  Node: html<3>,  Next: socket<8>,  Prev: sqlite3<6>,  Up: 新增，改进和弃用的模块

1.7.9.26 html
.............

A new *note html: 90. module was introduced with only a single function,
*note escape(): 93c, which is used for escaping reserved characters from
HTML markup:

     >>> import html
     >>> html.escape('x > 2 && x < 7')
     'x &gt; 2 &amp;&amp; x &lt; 7'


File: python.info,  Node: socket<8>,  Next: ssl<9>,  Prev: html<3>,  Up: 新增，改进和弃用的模块

1.7.9.27 socket
...............

The *note socket: f0. module has two new improvements.

   * Socket objects now have a *note detach(): ba5. method which puts
     the socket into closed state without actually closing the
     underlying file descriptor.  The latter can then be reused for
     other purposes.  (Added by Antoine Pitrou; bpo-8524(1).)

   * *note socket.create_connection(): ba6. now supports the context
     management protocol to unconditionally consume *note socket.error:
     99d. exceptions and to close the socket when done.  (Contributed by
     Giampaolo Rodolà; bpo-9794(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8524

   (2) https://bugs.python.org/issue9794


File: python.info,  Node: ssl<9>,  Next: nntp,  Prev: socket<8>,  Up: 新增，改进和弃用的模块

1.7.9.28 ssl
............

The *note ssl: f4. module added a number of features to satisfy common
requirements for secure (encrypted, authenticated) internet connections:

   * A new class, *note SSLContext: 3ec, serves as a container for
     persistent SSL data, such as protocol settings, certificates,
     private keys, and various other options.  It includes a *note
     wrap_socket(): 3ed. for creating an SSL socket from an SSL context.

   * A new function, *note ssl.match_hostname(): 3e4, supports server
     identity verification for higher-level protocols by implementing
     the rules of HTTPS (from RFC 2818(1)) which are also suitable for
     other protocols.

   * The *note ssl.wrap_socket(): 477. constructor function now takes a
     `ciphers' argument.  The `ciphers' string lists the allowed
     encryption algorithms using the format described in the OpenSSL
     documentation(2).

   * When linked against recent versions of OpenSSL, the *note ssl: f4.
     module now supports the Server Name Indication extension to the TLS
     protocol, allowing multiple "virtual hosts" using different
     certificates on a single IP port.  This extension is only supported
     in client mode, and is activated by passing the `server_hostname'
     argument to *note ssl.SSLContext.wrap_socket(): 3ed.

   * Various options have been added to the *note ssl: f4. module, such
     as *note OP_NO_SSLv2: ba8. which disables the insecure and obsolete
     SSLv2 protocol.

   * The extension now loads all the OpenSSL ciphers and digest
     algorithms.  If some SSL certificates cannot be verified, they are
     reported as an "unknown algorithm" error.

   * The version of OpenSSL being used is now accessible using the
     module attributes *note ssl.OPENSSL_VERSION: ba9. (a string), *note
     ssl.OPENSSL_VERSION_INFO: baa. (a 5-tuple), and *note
     ssl.OPENSSL_VERSION_NUMBER: bab. (an integer).

（由 Antoine Pitrou 在 bpo-8850(3), bpo-1589(4), bpo-8322(5),
bpo-5639(6), bpo-4870(7), bpo-8484(8) 和 bpo-8321(9) 中贡献。）

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2818.html

   (2) 
https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT

   (3) https://bugs.python.org/issue8850

   (4) https://bugs.python.org/issue1589

   (5) https://bugs.python.org/issue8322

   (6) https://bugs.python.org/issue5639

   (7) https://bugs.python.org/issue4870

   (8) https://bugs.python.org/issue8484

   (9) https://bugs.python.org/issue8321


File: python.info,  Node: nntp,  Next: certificates,  Prev: ssl<9>,  Up: 新增，改进和弃用的模块

1.7.9.29 nntp
.............

The *note nntplib: c1. module has a revamped implementation with better
bytes and text semantics as well as more practical APIs.  These
improvements break compatibility with the nntplib version in Python 3.1,
which was partly dysfunctional in itself.

Support for secure connections through both implicit (using *note
nntplib.NNTP_SSL: bad.) and explicit (using *note
nntplib.NNTP.starttls(): bae.) TLS has also been added.

（由 Antoine Pitrou 在 bpo-9360(1) 中贡献，由 Andrew Vant 在 bpo-1926(2)
中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9360

   (2) https://bugs.python.org/issue1926


File: python.info,  Node: certificates,  Next: imaplib<3>,  Prev: nntp,  Up: 新增，改进和弃用的模块

1.7.9.30 certificates
.....................

*note http.client.HTTPSConnection: 39b, *note
urllib.request.HTTPSHandler: bb0. and *note urllib.request.urlopen():
795. now take optional arguments to allow for server certificate
checking against a set of Certificate Authorities, as recommended in
public uses of HTTPS.

(Added by Antoine Pitrou, bpo-9003(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9003


File: python.info,  Node: imaplib<3>,  Next: http client<4>,  Prev: certificates,  Up: 新增，改进和弃用的模块

1.7.9.31 imaplib
................

Support for explicit TLS on standard IMAP4 connections has been added
through the new *note imaplib.IMAP4.starttls: bb2. method.

（由 Lorenzo M. Catucci 和 Antoine Pitrou 在 bpo-4471(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4471


File: python.info,  Node: http client<4>,  Next: unittest<6>,  Prev: imaplib<3>,  Up: 新增，改进和弃用的模块

1.7.9.32 http.client
....................

There were a number of small API improvements in the *note http.client:
94. module.  The old-style HTTP 0.9 simple responses are no longer
supported and the `strict' parameter is deprecated in all classes.

The *note HTTPConnection: 39a. and *note HTTPSConnection: 39b. classes
now have a `source_address' parameter for a (host, port) tuple
indicating where the HTTP connection is made from.

Support for certificate checking and HTTPS virtual hosts were added to
*note HTTPSConnection: 39b.

The *note request(): 558. method on connection objects allowed an
optional `body' argument so that a *note file object: b4a. could be used
to supply the content of the request.  Conveniently, the `body' argument
now also accepts an *note iterable: bb4. object so long as it includes
an explicit ‘Content-Length’ header.  This extended interface is much
more flexible than before.

To establish an HTTPS connection through a proxy server, there is a new
*note set_tunnel(): bb5. method that sets the host and port for HTTP
Connect tunneling.

To match the behavior of *note http.server: 97, the HTTP client library
now also encodes headers with ISO-8859-1 (Latin-1) encoding.  It was
already doing that for incoming headers, so now the behavior is
consistent for both incoming and outgoing traffic.  (See work by Armin
Ronacher in bpo-10980(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10980


File: python.info,  Node: unittest<6>,  Next: random<2>,  Prev: http client<4>,  Up: 新增，改进和弃用的模块

1.7.9.33 unittest
.................

The unittest module has a number of improvements supporting test
discovery for packages, easier experimentation at the interactive
prompt, new testcase methods, improved diagnostic messages for test
failures, and better method names.

   * The command-line call ‘python -m unittest’ can now accept file
     paths instead of module names for running specific tests
     (bpo-10620(1)).  The new test discovery can find tests within
     packages, locating any test importable from the top-level
     directory.  The top-level directory can be specified with the ‘-t’
     option, a pattern for matching files with ‘-p’, and a directory to
     start discovery with ‘-s’:

          $ python -m unittest discover -s my_proj_dir -p _test.py

     （由 Michael Foord 贡献）

   * Experimentation at the interactive prompt is now easier because the
     ‘unittest.case.TestCase’ class can now be instantiated without
     arguments:

          >>> from unittest import TestCase
          >>> TestCase().assertEqual(pow(2, 3), 8)

     （由 Michael Foord 贡献）

   * The *note unittest: 11c. module has two new methods, *note
     assertWarns(): ac4. and *note assertWarnsRegex(): ac5. to verify
     that a given warning type is triggered by the code under test:

          with self.assertWarns(DeprecationWarning):
              legacy_function('XYZ')

     （由 Antoine Pitrou 在 bpo-9754(2) 中贡献。）

     Another new method, *note assertCountEqual(): bb7. is used to
     compare two iterables to determine if their element counts are
     equal (whether the same elements are present with the same number
     of occurrences regardless of order):

          def test_anagram(self):
              self.assertCountEqual('algorithm', 'logarithm')

     （由 Raymond Hettinger 贡献。）

   * A principal feature of the unittest module is an effort to produce
     meaningful diagnostics when a test fails.  When possible, the
     failure is recorded along with a diff of the output.  This is
     especially helpful for analyzing log files of failed test runs.
     However, since diffs can sometime be voluminous, there is a new
     *note maxDiff: bb8. attribute that sets maximum length of diffs
     displayed.

   * In addition, the method names in the module have undergone a number
     of clean-ups.

     For example, *note assertRegex(): bb9. is the new name for
     ‘assertRegexpMatches()’ which was misnamed because the test uses
     *note re.search(): bba, not *note re.match(): bbb.  Other methods
     using regular expressions are now named using short form "Regex" in
     preference to "Regexp" – this matches the names used in other
     unittest implementations, matches Python’s old name for the *note
     re: de. module, and it has unambiguous camel-casing.

     （由 Raymond Hettinger 贡献并由 Ezio Melotti 实现。）

   * To improve consistency, some long-standing method aliases are being
     deprecated in favor of the preferred names:

          旧名称                              首选名称
                                              
          -----------------------------------------------------------------------
                                              
          ‘assert_()’                         *note assertTrue(): bbc.
                                              
                                              
          ‘assertEquals()’                    *note assertEqual(): bbd.
                                              
                                              
          ‘assertNotEquals()’                 *note assertNotEqual(): bbe.
                                              
                                              
          ‘assertAlmostEquals()’              *note assertAlmostEqual(): bbf.
                                              
                                              
          ‘assertNotAlmostEquals()’           *note assertNotAlmostEqual(): bc0.
                                              

     Likewise, the ‘TestCase.fail*’ methods deprecated in Python 3.1 are
     expected to be removed in Python 3.3.  Also see the *note
     Deprecated aliases: bc1. section in the *note unittest: 11c.
     documentation.

     （由 Ezio Melotti 在 bpo-9424(3) 中贡献。）

   * The ‘assertDictContainsSubset()’ method was deprecated because it
     was misimplemented with the arguments in the wrong order.  This
     created hard-to-debug optical illusions where tests like
     ‘TestCase().assertDictContainsSubset({'a':1, 'b':2}, {'a':1})’
     would fail.

     （由 Raymond Hettinger 贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10620

   (2) https://bugs.python.org/issue9754

   (3) https://bugs.python.org/issue9424


File: python.info,  Node: random<2>,  Next: poplib<3>,  Prev: unittest<6>,  Up: 新增，改进和弃用的模块

1.7.9.34 random
...............

The integer methods in the *note random: dd. module now do a better job
of producing uniform distributions.  Previously, they computed
selections with ‘int(n*random())’ which had a slight bias whenever `n'
was not a power of two.  Now, multiple selections are made from a range
up to the next power of two and a selection is kept only when it falls
within the range ‘0 <= x < n’.  The functions and methods affected are
*note randrange(): bc3, *note randint(): bc4, *note choice(): bc5, *note
shuffle(): bc6. and *note sample(): bc7.

（由 Raymond Hettinger 在 bpo-9025(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9025


File: python.info,  Node: poplib<3>,  Next: asyncore<2>,  Prev: random<2>,  Up: 新增，改进和弃用的模块

1.7.9.35 poplib
...............

*note POP3_SSL: bc9. class now accepts a `context' parameter, which is a
*note ssl.SSLContext: 3ec. object allowing bundling SSL configuration
options, certificates and private keys into a single (potentially
long-lived) structure.

（由 Giampaolo Rodolà 在 bpo-8807(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8807


File: python.info,  Node: asyncore<2>,  Next: tempfile<2>,  Prev: poplib<3>,  Up: 新增，改进和弃用的模块

1.7.9.36 asyncore
.................

*note asyncore.dispatcher: bcb. now provides a *note handle_accepted():
bcc. method returning a ‘(sock, addr)’ pair which is called when a
connection has actually been established with a new remote endpoint.
This is supposed to be used as a replacement for old *note
handle_accept(): bcd. and avoids the user to call *note accept(): bce.
directly.

（由 Giampaolo Rodolà 在 bpo-6706(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6706


File: python.info,  Node: tempfile<2>,  Next: inspect<6>,  Prev: asyncore<2>,  Up: 新增，改进和弃用的模块

1.7.9.37 tempfile
.................

The *note tempfile: 104. module has a new context manager, *note
TemporaryDirectory: bd0. which provides easy deterministic cleanup of
temporary directories:

     with tempfile.TemporaryDirectory() as tmpdirname:
         print('created temporary dir:', tmpdirname)

（由 Neil Schemenauer 和 Nick Coghlan 在 bpo-5178(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5178


File: python.info,  Node: inspect<6>,  Next: pydoc<5>,  Prev: tempfile<2>,  Up: 新增，改进和弃用的模块

1.7.9.38 inspect
................

   * The *note inspect: a1. module has a new function *note
     getgeneratorstate(): bd2. to easily identify the current state of a
     generator-iterator:

          >>> from inspect import getgeneratorstate
          >>> def gen():
          ...     yield 'demo'
          >>> g = gen()
          >>> getgeneratorstate(g)
          'GEN_CREATED'
          >>> next(g)
          'demo'
          >>> getgeneratorstate(g)
          'GEN_SUSPENDED'
          >>> next(g, None)
          >>> getgeneratorstate(g)
          'GEN_CLOSED'

     （由 Rodolpho Eckhardt 和 Nick Coghlan 在 bpo-10220(1) 中贡献。）

   * To support lookups without the possibility of activating a dynamic
     attribute, the *note inspect: a1. module has a new function, *note
     getattr_static(): bd3.  Unlike *note hasattr(): 450, this is a true
     read-only search, guaranteed not to change state while it is
     searching:

          >>> class A:
          ...     @property
          ...     def f(self):
          ...         print('Running')
          ...         return 10
          ...
          >>> a = A()
          >>> getattr(a, 'f')
          Running
          10
          >>> inspect.getattr_static(a, 'f')
          <property object at 0x1022bd788>

     （由 Michael Foord 贡献）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10220


File: python.info,  Node: pydoc<5>,  Next: dis<3>,  Prev: inspect<6>,  Up: 新增，改进和弃用的模块

1.7.9.39 pydoc
..............

The *note pydoc: da. module now provides a much-improved Web server
interface, as well as a new command-line option ‘-b’ to automatically
open a browser window to display that server:

     $ pydoc3.2 -b

（由 Ron Adam 在 bpo-2001(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2001


File: python.info,  Node: dis<3>,  Next: dbm<6>,  Prev: pydoc<5>,  Up: 新增，改进和弃用的模块

1.7.9.40 dis
............

The *note dis: 38. module gained two new functions for inspecting code,
*note code_info(): bd6. and *note show_code(): 83b.  Both provide
detailed code object information for the supplied function, method,
source code string or code object.  The former returns a string and the
latter prints it:

     >>> import dis, random
     >>> dis.show_code(random.choice)
     Name:              choice
     Filename:          /Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/random.py
     Argument count:    2
     Kw-only arguments: 0
     Number of locals:  3
     Stack size:        11
     Flags:             OPTIMIZED, NEWLOCALS, NOFREE
     Constants:
        0: 'Choose a random element from a non-empty sequence.'
        1: 'Cannot choose from an empty sequence'
     Names:
        0: _randbelow
        1: len
        2: ValueError
        3: IndexError
     Variable names:
        0: self
        1: seq
        2: i

In addition, the *note dis(): 38c. function now accepts string arguments
so that the common idiom ‘dis(compile(s, '', 'eval'))’ can be shortened
to ‘dis(s)’:

     >>> dis('3*x+1 if x%2==1 else x//2')
       1           0 LOAD_NAME                0 (x)
                   3 LOAD_CONST               0 (2)
                   6 BINARY_MODULO
                   7 LOAD_CONST               1 (1)
                  10 COMPARE_OP               2 (==)
                  13 POP_JUMP_IF_FALSE       28
                  16 LOAD_CONST               2 (3)
                  19 LOAD_NAME                0 (x)
                  22 BINARY_MULTIPLY
                  23 LOAD_CONST               1 (1)
                  26 BINARY_ADD
                  27 RETURN_VALUE
             >>   28 LOAD_NAME                0 (x)
                  31 LOAD_CONST               0 (2)
                  34 BINARY_FLOOR_DIVIDE
                  35 RETURN_VALUE

Taken together, these improvements make it easier to explore how CPython
is implemented and to see for yourself what the language syntax does
under-the-hood.

（由 Nick Coghlan 在 bpo-9147(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9147


File: python.info,  Node: dbm<6>,  Next: ctypes<2>,  Prev: dis<3>,  Up: 新增，改进和弃用的模块

1.7.9.41 dbm
............

All database modules now support the ‘get()’ and ‘setdefault()’ methods.

（由 Ray Allen 在 bpo-9523(1) 中建议。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9523


File: python.info,  Node: ctypes<2>,  Next: site<2>,  Prev: dbm<6>,  Up: 新增，改进和弃用的模块

1.7.9.42 ctypes
...............

A new type, *note ctypes.c_ssize_t: bd9. represents the C ‘ssize_t’
datatype.


File: python.info,  Node: site<2>,  Next: sysconfig<2>,  Prev: ctypes<2>,  Up: 新增，改进和弃用的模块

1.7.9.43 site
.............

The *note site: ec. module has three new functions useful for reporting
on the details of a given Python installation.

   * *note getsitepackages(): bdb. lists all global site-packages
     directories.

   * *note getuserbase(): bdc. reports on the user’s base directory
     where data can be stored.

   * *note getusersitepackages(): bdd. reveals the user-specific
     site-packages directory path.

     >>> import site
     >>> site.getsitepackages()
     ['/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages',
      '/Library/Frameworks/Python.framework/Versions/3.2/lib/site-python',
      '/Library/Python/3.2/site-packages']
     >>> site.getuserbase()
     '/Users/raymondhettinger/Library/Python/3.2'
     >>> site.getusersitepackages()
     '/Users/raymondhettinger/Library/Python/3.2/lib/python/site-packages'

Conveniently, some of site’s functionality is accessible directly from
the command-line:

     $ python -m site --user-base
     /Users/raymondhettinger/.local
     $ python -m site --user-site
     /Users/raymondhettinger/.local/lib/python3.2/site-packages

（由 Tarek Ziadé 在 bpo-6693(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6693


File: python.info,  Node: sysconfig<2>,  Next: pdb<5>,  Prev: site<2>,  Up: 新增，改进和弃用的模块

1.7.9.44 sysconfig
..................

The new *note sysconfig: ff. module makes it straightforward to discover
installation paths and configuration variables that vary across
platforms and installations.

The module offers access simple access functions for platform and
version information:

   * *note get_platform(): bdf. returning values like `linux-i586' or
     `macosx-10.6-ppc'.

   * *note get_python_version(): be0. returns a Python version string
     such as "3.2".

It also provides access to the paths and variables corresponding to one
of seven named schemes used by *note distutils: 39.  Those include
`posix_prefix', `posix_home', `posix_user', `nt', `nt_user', `os2',
`os2_home':

   * *note get_paths(): be1. makes a dictionary containing installation
     paths for the current installation scheme.

   * *note get_config_vars(): 96d. returns a dictionary of platform
     specific variables.

还有一个方便的命令行界面：

     C:\Python32>python -m sysconfig
     Platform: "win32"
     Python version: "3.2"
     Current installation scheme: "nt"

     Paths:
             data = "C:\Python32"
             include = "C:\Python32\Include"
             platinclude = "C:\Python32\Include"
             platlib = "C:\Python32\Lib\site-packages"
             platstdlib = "C:\Python32\Lib"
             purelib = "C:\Python32\Lib\site-packages"
             scripts = "C:\Python32\Scripts"
             stdlib = "C:\Python32\Lib"

     Variables:
             BINDIR = "C:\Python32"
             BINLIBDEST = "C:\Python32\Lib"
             EXE = ".exe"
             INCLUDEPY = "C:\Python32\Include"
             LIBDEST = "C:\Python32\Lib"
             SO = ".pyd"
             VERSION = "32"
             abiflags = ""
             base = "C:\Python32"
             exec_prefix = "C:\Python32"
             platbase = "C:\Python32"
             prefix = "C:\Python32"
             projectbase = "C:\Python32"
             py_version = "3.2"
             py_version_nodot = "32"
             py_version_short = "3.2"
             srcdir = "C:\Python32"
             userbase = "C:\Documents and Settings\Raymond\Application Data\Python"

（由TarekZiadé 移出Distutils。）


File: python.info,  Node: pdb<5>,  Next: configparser<2>,  Prev: sysconfig<2>,  Up: 新增，改进和弃用的模块

1.7.9.45 pdb
............

The *note pdb: ca. debugger module gained a number of usability
improvements:

   * ‘pdb.py’ now has a ‘-c’ option that executes commands as given in a
     ‘.pdbrc’ script file.

   * A ‘.pdbrc’ script file can contain ‘continue’ and ‘next’ commands
     that continue debugging.

   * The ‘Pdb’ class constructor now accepts a `nosigint' argument.

   * New commands: ‘l(list)’, ‘ll(long list)’ and ‘source’ for listing
     source code.

   * New commands: ‘display’ and ‘undisplay’ for showing or hiding the
     value of an expression if it has changed.

   * New command: ‘interact’ for starting an interactive interpreter
     containing the global and local names found in the current scope.

   * Breakpoints can be cleared by breakpoint number.

（由Georg Brandl, Antonio Cuni 和 Ilya Sandler 贡献。）


File: python.info,  Node: configparser<2>,  Next: urllib parse<3>,  Prev: pdb<5>,  Up: 新增，改进和弃用的模块

1.7.9.46 configparser
.....................

The *note configparser: 23. module was modified to improve usability and
predictability of the default parser and its supported INI syntax.  The
old ‘ConfigParser’ class was removed in favor of ‘SafeConfigParser’
which has in turn been renamed to *note ConfigParser: 4b2.  Support for
inline comments is now turned off by default and section or option
duplicates are not allowed in a single configuration source.

Config parsers gained a new API based on the mapping protocol:

     >>> parser = ConfigParser()
     >>> parser.read_string("""
     ... [DEFAULT]
     ... location = upper left
     ... visible = yes
     ... editable = no
     ... color = blue
     ...
     ... [main]
     ... title = Main Menu
     ... color = green
     ...
     ... [options]
     ... title = Options
     ... """)
     >>> parser['main']['color']
     'green'
     >>> parser['main']['editable']
     'no'
     >>> section = parser['options']
     >>> section['title']
     'Options'
     >>> section['title'] = 'Options (editable: %(editable)s)'
     >>> section['title']
     'Options (editable: no)'

The new API is implemented on top of the classical API, so custom parser
subclasses should be able to use it without modifications.

The INI file structure accepted by config parsers can now be customized.
Users can specify alternative option/value delimiters and comment
prefixes, change the name of the `DEFAULT' section or switch the
interpolation syntax.

There is support for pluggable interpolation including an additional
interpolation handler *note ExtendedInterpolation: be4.:

     >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
     >>> parser.read_dict({'buildout': {'directory': '/home/ambv/zope9'},
     ...                   'custom': {'prefix': '/usr/local'}})
     >>> parser.read_string("""
     ... [buildout]
     ... parts =
     ...   zope9
     ...   instance
     ... find-links =
     ...   ${buildout:directory}/downloads/dist
     ...
     ... [zope9]
     ... recipe = plone.recipe.zope9install
     ... location = /opt/zope
     ...
     ... [instance]
     ... recipe = plone.recipe.zope9instance
     ... zope9-location = ${zope9:location}
     ... zope-conf = ${custom:prefix}/etc/zope.conf
     ... """)
     >>> parser['buildout']['find-links']
     '\n/home/ambv/zope9/downloads/dist'
     >>> parser['instance']['zope-conf']
     '/usr/local/etc/zope.conf'
     >>> instance = parser['instance']
     >>> instance['zope-conf']
     '/usr/local/etc/zope.conf'
     >>> instance['zope9-location']
     '/opt/zope'

A number of smaller features were also introduced, like support for
specifying encoding in read operations, specifying fallback values for
get-functions, or reading directly from dictionaries and strings.

(All changes contributed by Łukasz Langa.)


File: python.info,  Node: urllib parse<3>,  Next: mailbox,  Prev: configparser<2>,  Up: 新增，改进和弃用的模块

1.7.9.47 urllib.parse
.....................

A number of usability improvements were made for the *note urllib.parse:
120. module.

The *note urlparse(): 603. function now supports IPv6(1) addresses as
described in RFC 2732(2):

     >>> import urllib.parse
     >>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/')
     ParseResult(scheme='http',
                 netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]',
                 path='/foo/',
                 params='',
                 query='',
                 fragment='')

The *note urldefrag(): be6. function now returns a *note named tuple:
aab.:

     >>> r = urllib.parse.urldefrag('http://python.org/about/#target')
     >>> r
     DefragResult(url='http://python.org/about/', fragment='target')
     >>> r[0]
     'http://python.org/about/'
     >>> r.fragment
     'target'

And, the *note urlencode(): 794. function is now much more flexible,
accepting either a string or bytes type for the `query' argument.  If it
is a string, then the `safe', `encoding', and `error' parameters are
sent to *note quote_plus(): be7. for encoding:

     >>> urllib.parse.urlencode([
     ...      ('type', 'telenovela'),
     ...      ('name', '¿Dónde Está Elisa?')],
     ...      encoding='latin-1')
     'type=telenovela&name=%BFD%F3nde+Est%E1+Elisa%3F'

As detailed in *note 解析ASCII编码字节: be8, all the *note urllib.parse:
120. functions now accept ASCII-encoded byte strings as input, so long
as they are not mixed with regular strings.  If ASCII-encoded byte
strings are given as parameters, the return types will also be an
ASCII-encoded byte strings:

     >>> urllib.parse.urlparse(b'http://www.python.org:80/about/')
     ParseResultBytes(scheme=b'http', netloc=b'www.python.org:80',
                      path=b'/about/', params=b'', query=b'', fragment=b'')

(Work by Nick Coghlan, Dan Mahn, and Senthil Kumaran in bpo-2987(3),
bpo-5468(4), and bpo-9873(5).)

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/IPv6

   (2) https://tools.ietf.org/html/rfc2732.html

   (3) https://bugs.python.org/issue2987

   (4) https://bugs.python.org/issue5468

   (5) https://bugs.python.org/issue9873


File: python.info,  Node: mailbox,  Next: turtledemo,  Prev: urllib parse<3>,  Up: 新增，改进和弃用的模块

1.7.9.48 mailbox
................

Thanks to a concerted effort by R. David Murray, the *note mailbox: af.
module has been fixed for Python 3.2.  The challenge was that mailbox
had been originally designed with a text interface, but email messages
are best represented with *note bytes: 33a. because various parts of a
message may have different encodings.

The solution harnessed the *note email: 69. package’s binary support for
parsing arbitrary email messages.  In addition, the solution required a
number of API changes.

As expected, the *note add(): bea. method for *note mailbox.Mailbox:
beb. objects now accepts binary input.

*note StringIO: 836. and text file input are deprecated.  Also, string
input will fail early if non-ASCII characters are used.  Previously it
would fail when the email was processed in a later step.

There is also support for binary output.  The *note get_file(): bec.
method now returns a file in the binary mode (where it used to
incorrectly set the file to text-mode).  There is also a new *note
get_bytes(): bed. method that returns a *note bytes: 33a. representation
of a message corresponding to a given `key'.

It is still possible to get non-binary output using the old API’s *note
get_string(): bee. method, but that approach is not very useful.
Instead, it is best to extract messages from a *note Message: bef.
object or to load them from binary input.

(Contributed by R. David Murray, with efforts from Steffen Daode
Nurpmeso and an initial patch by Victor Stinner in bpo-9124(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9124


File: python.info,  Node: turtledemo,  Prev: mailbox,  Up: 新增，改进和弃用的模块

1.7.9.49 turtledemo
...................

The demonstration code for the *note turtle: 117. module was moved from
the `Demo' directory to main library.  It includes over a dozen sample
scripts with lively displays.  Being on *note sys.path: 490, it can now
be run directly from the command-line:

     $ python -m turtledemo

(Moved from the Demo directory by Alexander Belopolsky in bpo-10199(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10199


File: python.info,  Node: 多线程,  Next: 性能优化<6>,  Prev: 新增，改进和弃用的模块,  Up: Python 3 2 有什么新变化

1.7.10 多线程
-------------

   * The mechanism for serializing execution of concurrently running
     Python threads (generally known as the *note GIL: bf2. or Global
     Interpreter Lock) has been rewritten.  Among the objectives were
     more predictable switching intervals and reduced overhead due to
     lock contention and the number of ensuing system calls.  The notion
     of a "check interval" to allow thread switches has been abandoned
     and replaced by an absolute duration expressed in seconds.  This
     parameter is tunable through *note sys.setswitchinterval(): bf3.
     It currently defaults to 5 milliseconds.

     Additional details about the implementation can be read from a
     python-dev mailing-list message(1) (however, "priority requests" as
     exposed in this message have not been kept for inclusion).

     （由 Antoine Pitrou 贡献。）

   * Regular and recursive locks now accept an optional `timeout'
     argument to their *note acquire(): 775. method.  (Contributed by
     Antoine Pitrou; bpo-7316(2).)

   * Similarly, *note threading.Semaphore.acquire(): bf4. also gained a
     `timeout' argument.  (Contributed by Torsten Landschoff;
     bpo-850728(3).)

   * Regular and recursive lock acquisitions can now be interrupted by
     signals on platforms using Pthreads.  This means that Python
     programs that deadlock while acquiring locks can be successfully
     killed by repeatedly sending SIGINT to the process (by pressing
     ‘Ctrl+C’ in most shells).  (Contributed by Reid Kleckner;
     bpo-8844(4).)

   ---------- Footnotes ----------

   (1) 
https://mail.python.org/pipermail/python-dev/2009-October/093321.html

   (2) https://bugs.python.org/issue7316

   (3) https://bugs.python.org/issue850728

   (4) https://bugs.python.org/issue8844


File: python.info,  Node: 性能优化<6>,  Next: Unicode,  Prev: 多线程,  Up: Python 3 2 有什么新变化

1.7.11 性能优化
---------------

A number of small performance enhancements have been added:

   * Python’s peephole optimizer now recognizes patterns such ‘x in {1,
     2, 3}’ as being a test for membership in a set of constants.  The
     optimizer recasts the *note set: b77. as a *note frozenset: bf6.
     and stores the pre-built constant.

     Now that the speed penalty is gone, it is practical to start
     writing membership tests using set-notation.  This style is both
     semantically clear and operationally fast:

          extension = name.rpartition('.')[2]
          if extension in {'xml', 'html', 'xhtml', 'css'}:
              handle(name)

     (Patch and additional tests contributed by Dave Malcolm;
     bpo-6690(1)).

   * Serializing and unserializing data using the *note pickle: cb.
     module is now several times faster.

     （由 Alexandre Vassalotti, Antoine Pitrou 和 Unladen Swallow 团队在
     bpo-9410(2) 和 bpo-3873(3) 中贡献。）

   * The Timsort algorithm(4) used in *note list.sort(): 44d. and *note
     sorted(): 44c. now runs faster and uses less memory when called
     with a *note key function: 6e9.  Previously, every element of a
     list was wrapped with a temporary object that remembered the key
     value associated with each element.  Now, two arrays of keys and
     values are sorted in parallel.  This saves the memory consumed by
     the sort wrappers, and it saves time lost to delegating
     comparisons.

     (Patch by Daniel Stutzbach in bpo-9915(5).)

   * JSON decoding performance is improved and memory consumption is
     reduced whenever the same string is repeated for multiple keys.
     Also, JSON encoding now uses the C speedups when the ‘sort_keys’
     argument is true.

     （由Antoine Pitrou 在 bpo-7451(6) 中贡献，由 Raymond Hettinger 和
     Antoine Pitrou 在 bpo-10314(7) 中贡献。）

   * Recursive locks (created with the *note threading.RLock(): bf7.
     API) now benefit from a C implementation which makes them as fast
     as regular locks, and between 10x and 15x faster than their
     previous pure Python implementation.

     （由 Antoine Pitrou 在 bpo-3001(8) 中贡献。）

   * The fast-search algorithm in stringlib is now used by the
     ‘split()’, ‘rsplit()’, ‘splitlines()’ and ‘replace()’ methods on
     *note bytes: 33a, *note bytearray: 33b. and *note str: 339.
     objects.  Likewise, the algorithm is also used by ‘rfind()’,
     ‘rindex()’, ‘rsplit()’ and ‘rpartition()’.

     (Patch by Florent Xicluna in bpo-7622(9) and bpo-7462(10).)

   * Integer to string conversions now work two "digits" at a time,
     reducing the number of division and modulo operations.

     (bpo-6713(11) by Gawain Bolton, Mark Dickinson, and Victor
     Stinner.)

There were several other minor optimizations.  Set differencing now runs
faster when one operand is much larger than the other (patch by Andress
Bennetts in bpo-8685(12)).  The ‘array.repeat()’ method has a faster
implementation (bpo-1569291(13) by Alexander Belopolsky).  The
‘BaseHTTPRequestHandler’ has more efficient buffering (bpo-3709(14) by
Andrew Schaaf).  The *note operator.attrgetter(): 724. function has been
sped-up (bpo-10160(15) by Christos Georgiou).  And ‘ConfigParser’ loads
multi-line arguments a bit faster (bpo-7113(16) by Łukasz Langa).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6690

   (2) https://bugs.python.org/issue9410

   (3) https://bugs.python.org/issue3873

   (4) https://en.wikipedia.org/wiki/Timsort

   (5) https://bugs.python.org/issue9915

   (6) https://bugs.python.org/issue7451

   (7) https://bugs.python.org/issue10314

   (8) https://bugs.python.org/issue3001

   (9) https://bugs.python.org/issue7622

   (10) https://bugs.python.org/issue7462

   (11) https://bugs.python.org/issue6713

   (12) https://bugs.python.org/issue8685

   (13) https://bugs.python.org/issue1569291

   (14) https://bugs.python.org/issue3709

   (15) https://bugs.python.org/issue10160

   (16) https://bugs.python.org/issue7113


File: python.info,  Node: Unicode,  Next: 编解码器,  Prev: 性能优化<6>,  Up: Python 3 2 有什么新变化

1.7.12 Unicode
--------------

Python has been updated to Unicode 6.0.0(1).  The update to the standard
adds over 2,000 new characters including emoji(2) symbols which are
important for mobile phones.

In addition, the updated standard has altered the character properties
for two Kannada characters (U+0CF1, U+0CF2) and one New Tai Lue numeric
character (U+19DA), making the former eligible for use in identifiers
while disqualifying the latter.  For more information, see Unicode
Character Database Changes(3).

   ---------- Footnotes ----------

   (1) http://unicode.org/versions/Unicode6.0.0/

   (2) https://en.wikipedia.org/wiki/Emoji

   (3) http://www.unicode.org/versions/Unicode6.0.0/#Database_Changes


File: python.info,  Node: 编解码器,  Next: 文档,  Prev: Unicode,  Up: Python 3 2 有什么新变化

1.7.13 编解码器
---------------

Support was added for `cp720' Arabic DOS encoding (bpo-1616979(1)).

MBCS encoding no longer ignores the error handler argument.  In the
default strict mode, it raises an *note UnicodeDecodeError: 1fe. when it
encounters an undecodable byte sequence and an *note UnicodeEncodeError:
1fd. for an unencodable character.

The MBCS codec supports ‘'strict'’ and ‘'ignore'’ error handlers for
decoding, and ‘'strict'’ and ‘'replace'’ for encoding.

To emulate Python3.1 MBCS encoding, select the ‘'ignore'’ handler for
decoding and the ‘'replace'’ handler for encoding.

On Mac OS X, Python decodes command line arguments with ‘'utf-8'’ rather
than the locale encoding.

By default, *note tarfile: 102. uses ‘'utf-8'’ encoding on Windows
(instead of ‘'mbcs'’) and the ‘'surrogateescape'’ error handler on all
operating systems.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1616979


File: python.info,  Node: 文档,  Next: IDLE,  Prev: 编解码器,  Up: Python 3 2 有什么新变化

1.7.14 文档
-----------

The documentation continues to be improved.

   * A table of quick links has been added to the top of lengthy
     sections such as *note 内置函数: bfb.  In the case of *note
     itertools: a4, the links are accompanied by tables of
     cheatsheet-style summaries to provide an overview and memory jog
     without having to read all of the docs.

   * In some cases, the pure Python source code can be a helpful adjunct
     to the documentation, so now many modules now feature quick links
     to the latest version of the source code.  For example, the *note
     functools: 85. module documentation has a quick link at the top
     labeled:

          `源代码' Lib/functools.py(1).

     （由 Raymond Hettinger 贡献，参见 rationale(2)。）

   * The docs now contain more examples and recipes.  In particular,
     *note re: de. module has an extensive section, *note
     正则表达式例子: bfc.  Likewise, the *note itertools: a4. module
     continues to be updated with new *note itertools 配方: bfd.

   * The *note datetime: 31. module now has an auxiliary implementation
     in pure Python.  No functionality was changed.  This just provides
     an easier-to-read alternate implementation.

     （由 Alexander Belopolsky 在 bpo-9528(3) 中贡献。）

   * The unmaintained ‘Demo’ directory has been removed.  Some demos
     were integrated into the documentation, some were moved to the
     ‘Tools/demo’ directory, and others were removed altogether.

     （由 Georg Brandl 在 bpo-7962(4) 中贡献）

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/functools.py

   (2) 
https://rhettinger.wordpress.com/2011/01/28/open-your-source-more/

   (3) https://bugs.python.org/issue9528

   (4) https://bugs.python.org/issue7962


File: python.info,  Node: IDLE,  Next: 代码库,  Prev: 文档,  Up: Python 3 2 有什么新变化

1.7.15 IDLE
-----------

   * The format menu now has an option to clean source files by
     stripping trailing whitespace.

     （由 Raymond Hettinger 在 bpo-5150(1) 中贡献。）

   * IDLE on Mac OS X now works with both Carbon AquaTk and Cocoa
     AquaTk.

     （由 Kevin Walzer, Ned Deily 和 Ronald Oussoren 在 bpo-6075(2) 中贡
     献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5150

   (2) https://bugs.python.org/issue6075


File: python.info,  Node: 代码库,  Next: 构建和 C API 的改变<5>,  Prev: IDLE,  Up: Python 3 2 有什么新变化

1.7.16 代码库
-------------

In addition to the existing Subversion code repository at
‘http://svn.python.org’ there is now a Mercurial(1) repository at
‘https://hg.python.org/’.

After the 3.2 release, there are plans to switch to Mercurial as the
primary repository.  This distributed version control system should make
it easier for members of the community to create and share external
changesets.  See PEP 385(2) for details.

To learn to use the new version control system, see the Quick Start(3)
or the Guide to Mercurial Workflows(4).

   ---------- Footnotes ----------

   (1) https://www.mercurial-scm.org/

   (2) https://www.python.org/dev/peps/pep-0385

   (3) https://www.mercurial-scm.org/wiki/QuickStart

   (4) https://www.mercurial-scm.org/guide


File: python.info,  Node: 构建和 C API 的改变<5>,  Next: 移植到 Python 3 2,  Prev: 代码库,  Up: Python 3 2 有什么新变化

1.7.17 构建和 C API 的改变
--------------------------

Changes to Python’s build process and to the C API include:

   * The `idle', `pydoc' and `2to3' scripts are now installed with a
     version-specific suffix on ‘make altinstall’ (bpo-10679(1)).

   * The C functions that access the Unicode Database now accept and
     return characters from the full Unicode range, even on narrow
     unicode builds (Py_UNICODE_TOLOWER, Py_UNICODE_ISDECIMAL, and
     others).  A visible difference in Python is that *note
     unicodedata.numeric(): c01. now returns the correct value for large
     code points, and *note repr(): 7d5. may consider more characters as
     printable.

     (Reported by Bupjoe Lee and fixed by Amaury Forgeot D’Arc;
     bpo-5127(2).)

   * Computed gotos are now enabled by default on supported compilers
     (which are detected by the configure script).  They can still be
     disabled selectively by specifying ‘--without-computed-gotos’.

     （由 Antoine Pitrou 在 bpo-9203(3) 中贡献。）

   * The option ‘--with-wctype-functions’ was removed.  The built-in
     unicode database is now used for all functions.

     （由 Amaury Forgeot d’Arc 在 bpo-9210(4) 中贡献。）

   * Hash values are now values of a new type, ‘Py_hash_t’, which is
     defined to be the same size as a pointer.  Previously they were of
     type long, which on some 64-bit operating systems is still only 32
     bits long.  As a result of this fix, *note set: b77. and *note
     dict: 1b9. can now hold more than ‘2**32’ entries on builds with
     64-bit pointers (previously, they could grow to that size but their
     performance degraded catastrophically).

     (Suggested by Raymond Hettinger and implemented by Benjamin
     Peterson; bpo-9778(5).)

   * A new macro ‘Py_VA_COPY’ copies the state of the variable argument
     list.  It is equivalent to C99 `va_copy' but available on all
     Python platforms (bpo-2443(6)).

   * A new C API function *note PySys_SetArgvEx(): c02. allows an
     embedded interpreter to set *note sys.argv: c03. without also
     modifying *note sys.path: 490. (bpo-5753(7)).

   * ‘PyEval_CallObject’ is now only available in macro form.  The
     function declaration, which was kept for backwards compatibility
     reasons, is now removed – the macro was introduced in 1997
     (bpo-8276(8)).

   * There is a new function *note PyLong_AsLongLongAndOverflow(): c04.
     which is analogous to *note PyLong_AsLongAndOverflow(): c05.  They
     both serve to convert Python *note int: 185. into a native
     fixed-width type while providing detection of cases where the
     conversion won’t fit (bpo-7767(9)).

   * The *note PyUnicode_CompareWithASCIIString(): c06. function now
     returns `not equal' if the Python string is `NUL' terminated.

   * There is a new function *note PyErr_NewExceptionWithDoc(): c07.
     that is like *note PyErr_NewException(): c08. but allows a
     docstring to be specified.  This lets C exceptions have the same
     self-documenting capabilities as their pure Python counterparts
     (bpo-7033(10)).

   * When compiled with the ‘--with-valgrind’ option, the pymalloc
     allocator will be automatically disabled when running under
     Valgrind.  This gives improved memory leak detection when running
     under Valgrind, while taking advantage of pymalloc at other times
     (bpo-2422(11)).

   * Removed the ‘O?’ format from the `PyArg_Parse' functions.  The
     format is no longer used and it had never been documented
     (bpo-8837(12)).

There were a number of other small changes to the C-API. See the
Misc/NEWS(13) file for a complete list.

Also, there were a number of updates to the Mac OS X build, see
Mac/BuildScript/README.txt(14) for details.  For users running a
32/64-bit build, there is a known problem with the default Tcl/Tk on Mac
OS X 10.6.  Accordingly, we recommend installing an updated alternative
such as ActiveState Tcl/Tk 8.5.9(15).  See
‘https://www.python.org/download/mac/tcltk/’ for additional details.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10679

   (2) https://bugs.python.org/issue5127

   (3) https://bugs.python.org/issue9203

   (4) https://bugs.python.org/issue9210

   (5) https://bugs.python.org/issue9778

   (6) https://bugs.python.org/issue2443

   (7) https://bugs.python.org/issue5753

   (8) https://bugs.python.org/issue8276

   (9) https://bugs.python.org/issue7767

   (10) https://bugs.python.org/issue7033

   (11) https://bugs.python.org/issue2422

   (12) https://bugs.python.org/issue8837

   (13) https://github.com/python/cpython/tree/3.8/Misc/NEWS

   (14) 
https://github.com/python/cpython/tree/3.8/Mac/BuildScript/README.txt

   (15) https://www.activestate.com/activetcl/downloads


File: python.info,  Node: 移植到 Python 3 2,  Prev: 构建和 C API 的改变<5>,  Up: Python 3 2 有什么新变化

1.7.18 移植到 Python 3.2
------------------------

This section lists previously described changes and other bugfixes that
may require changes to your code:

   * The *note configparser: 23. module has a number of clean-ups.  The
     major change is to replace the old ‘ConfigParser’ class with
     long-standing preferred alternative ‘SafeConfigParser’.  In
     addition there are a number of smaller incompatibilities:

        * The interpolation syntax is now validated on *note get(): c0a.
          and *note set(): c0b. operations.  In the default
          interpolation scheme, only two tokens with percent signs are
          valid: ‘%(name)s’ and ‘%%’, the latter being an escaped
          percent sign.

        * The *note set(): c0b. and *note add_section(): c0c. methods
          now verify that values are actual strings.  Formerly,
          unsupported types could be introduced unintentionally.

        * Duplicate sections or options from a single source now raise
          either *note DuplicateSectionError: c0d. or *note
          DuplicateOptionError: c0e.  Formerly, duplicates would
          silently overwrite a previous entry.

        * Inline comments are now disabled by default so now the `;'
          character can be safely used in values.

        * Comments now can be indented.  Consequently, for `;' or `#' to
          appear at the start of a line in multiline values, it has to
          be interpolated.  This keeps comment prefix characters in
          values from being mistaken as comments.

        * ‘""’ is now a valid value and is no longer automatically
          converted to an empty string.  For empty strings, use ‘"option
          ="’ in a line.

   * The *note nntplib: c1. module was reworked extensively, meaning
     that its APIs are often incompatible with the 3.1 APIs.

   * *note bytearray: 33b. objects can no longer be used as filenames;
     instead, they should be converted to *note bytes: 33a.

   * The ‘array.tostring()’ and ‘array.fromstring()’ have been renamed
     to ‘array.tobytes()’ and ‘array.frombytes()’ for clarity.  The old
     names have been deprecated.  (See bpo-8990(1).)

   * ‘PyArg_Parse*()’ 函数:

        * "t#" format has been removed: use "s#" or "s*" instead

        * "w" and "w#" formats has been removed: use "w*" instead

   * The ‘PyCObject’ type, deprecated in 3.1, has been removed.  To wrap
     opaque C pointers in Python objects, the *note PyCapsule: c0f. API
     should be used instead; the new type has a well-defined interface
     for passing typing safety information and a less complicated
     signature for calling a destructor.

   * The ‘sys.setfilesystemencoding()’ function was removed because it
     had a flawed design.

   * The *note random.seed(): c10. function and method now salt string
     seeds with an sha512 hash function.  To access the previous version
     of `seed' in order to reproduce Python 3.1 sequences, set the
     `version' argument to `1', ‘random.seed(s, version=1)’.

   * The previously deprecated ‘string.maketrans()’ function has been
     removed in favor of the static methods *note bytes.maketrans():
     c11. and *note bytearray.maketrans(): c12.  This change solves the
     confusion around which types were supported by the *note string:
     f7. module.  Now, *note str: 339, *note bytes: 33a, and *note
     bytearray: 33b. each have their own `maketrans' and `translate'
     methods with intermediate translation tables of the appropriate
     type.

     （由Georg Brandl在 bpo-5675(2) 中贡献）

   * The previously deprecated ‘contextlib.nested()’ function has been
     removed in favor of a plain *note with: 6f2. statement which can
     accept multiple context managers.  The latter technique is faster
     (because it is built-in), and it does a better job finalizing
     multiple context managers when one of them raises an exception:

          with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
              for line in infile:
                  if '<critical>' in line:
                      outfile.write(line)

     (Contributed by Georg Brandl and Mattias Brändström; appspot issue
     53094(3).)

   * *note struct.pack(): c13. now only allows bytes for the ‘s’ string
     pack code.  Formerly, it would accept text arguments and implicitly
     encode them to bytes using UTF-8.  This was problematic because it
     made assumptions about the correct encoding and because a
     variable-length encoding can fail when writing to fixed length
     segment of a structure.

     Code such as ‘struct.pack('<6sHHBBB', 'GIF87a', x, y)’ should be
     rewritten with to use bytes instead of text,
     ‘struct.pack('<6sHHBBB', b'GIF87a', x, y)’.

     (Discovered by David Beazley and fixed by Victor Stinner;
     bpo-10783(4).)

   * The *note xml.etree.ElementTree: 138. class now raises an *note
     xml.etree.ElementTree.ParseError: c14. when a parse fails.
     Previously it raised an *note xml.parsers.expat.ExpatError: c15.

   * The new, longer *note str(): 339. value on floats may break
     doctests which rely on the old output format.

   * In *note subprocess.Popen: 2ba, the default value for `close_fds'
     is now ‘True’ under Unix; under Windows, it is ‘True’ if the three
     standard streams are set to ‘None’, ‘False’ otherwise.  Previously,
     `close_fds' was always ‘False’ by default, which produced difficult
     to solve bugs or race conditions when open file descriptors would
     leak into the child process.

   * Support for legacy HTTP 0.9 has been removed from *note
     urllib.request: 121. and *note http.client: 94.  Such support is
     still present on the server side (in *note http.server: 97.).

     （由 Antoine Pitrou 在 bpo-10711(5) 中贡献。）

   * SSL sockets in timeout mode now raise *note socket.timeout: c16.
     when a timeout occurs, rather than a generic *note SSLError: c17.

     （由 Antoine Pitrou 在 bpo-10272(6) 中贡献。）

   * The misleading functions *note PyEval_AcquireLock(): 2b3. and *note
     PyEval_ReleaseLock(): c18. have been officially deprecated.  The
     thread-state aware APIs (such as *note PyEval_SaveThread(): c19.
     and *note PyEval_RestoreThread(): 2b5.) should be used instead.

   * Due to security risks, ‘asyncore.handle_accept()’ has been
     deprecated, and a new function, ‘asyncore.handle_accepted()’, was
     added to replace it.

     （由 Giampaolo Rodola 在 bpo-6706(7) 中贡献。）

   * Due to the new *note GIL: bf2. implementation, *note
     PyEval_InitThreads(): c1a. cannot be called before *note
     Py_Initialize(): 441. anymore.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8990

   (2) https://bugs.python.org/issue5675

   (3) https://codereview.appspot.com/53094

   (4) https://bugs.python.org/issue10783

   (5) https://bugs.python.org/issue10711

   (6) https://bugs.python.org/issue10272

   (7) https://bugs.python.org/issue6706


File: python.info,  Node: Python 3 1 有什么新变化,  Next: Python 3 0 有什么新变化,  Prev: Python 3 2 有什么新变化,  Up: Python的新变化

1.8 Python 3.1 有什么新变化
===========================


作者: Raymond Hettinger

This article explains the new features in Python 3.1, compared to 3.0.

* Menu:

* PEP 372; 有序字典: PEP 372 有序字典.
* PEP 378; 千位分隔符的格式说明符: PEP 378 千位分隔符的格式说明符.
* 其他语言特性修改: 其他语言特性修改<8>.
* 新增，改进和弃用的模块: 新增，改进和弃用的模块<2>.
* 性能优化: 性能优化<7>.
* IDLE: IDLE<2>.
* 构建和 C API 的改变: 构建和 C API 的改变<6>.
* 移植到 Python 3.1: 移植到 Python 3 1.


File: python.info,  Node: PEP 372 有序字典,  Next: PEP 378 千位分隔符的格式说明符,  Up: Python 3 1 有什么新变化

1.8.1 PEP 372: 有序字典
-----------------------

Regular Python dictionaries iterate over key/value pairs in arbitrary
order.  Over the years, a number of authors have written alternative
implementations that remember the order that the keys were originally
inserted.  Based on the experiences from those implementations, a new
*note collections.OrderedDict: 1ba. class has been introduced.

The OrderedDict API is substantially the same as regular dictionaries
but will iterate over keys and values in a guaranteed order depending on
when a key was first inserted.  If a new entry overwrites an existing
entry, the original insertion position is left unchanged.  Deleting an
entry and reinserting it will move it to the end.

The standard library now supports use of ordered dictionaries in several
modules.  The *note configparser: 23. module uses them by default.  This
lets configuration files be read, modified, and then written back in
their original order.  The `_asdict()' method for *note
collections.namedtuple(): 1b7. now returns an ordered dictionary with
the values appearing in the same order as the underlying tuple indices.
The *note json: a5. module is being built-out with an
`object_pairs_hook' to allow OrderedDicts to be built by the decoder.
Support was also added for third-party tools like PyYAML(1).

参见
....

PEP 372(2) - 有序字典

     PEP 由 Armin Ronacher 和 Raymond Hettinger 撰写，由 Raymond
     Hettinger 实现。

   ---------- Footnotes ----------

   (1) http://pyyaml.org/

   (2) https://www.python.org/dev/peps/pep-0372


File: python.info,  Node: PEP 378 千位分隔符的格式说明符,  Next: 其他语言特性修改<8>,  Prev: PEP 372 有序字典,  Up: Python 3 1 有什么新变化

1.8.2 PEP 378: 千位分隔符的格式说明符
-------------------------------------

The built-in *note format(): 4e3. function and the *note str.format():
4e2. method use a mini-language that now includes a simple, non-locale
aware way to format a number with a thousands separator.  That provides
a way to humanize a program’s output, improving its professional
appearance and readability:

     >>> format(1234567, ',d')
     '1,234,567'
     >>> format(1234567.89, ',.2f')
     '1,234,567.89'
     >>> format(12345.6 + 8901234.12j, ',f')
     '12,345.600000+8,901,234.120000j'
     >>> format(Decimal('1234567.89'), ',f')
     '1,234,567.89'

The supported types are *note int: 185, *note float: 188, *note complex:
18a. and *note decimal.Decimal: 189.

Discussions are underway about how to specify alternative separators
like dots, spaces, apostrophes, or underscores.  Locale-aware
applications should use the existing `n' format specifier which already
has some support for thousands separators.

参见
....

PEP 378(1) - 千位分隔符的格式说明符

     PEP 由 Raymond Hettinger 撰写，并由 Eric Smith 和 Mark Dickinson 实
     现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0378


File: python.info,  Node: 其他语言特性修改<8>,  Next: 新增，改进和弃用的模块<2>,  Prev: PEP 378 千位分隔符的格式说明符,  Up: Python 3 1 有什么新变化

1.8.3 其他语言特性修改
----------------------

对Python 语言核心进行的小改动：

   * Directories and zip archives containing a ‘__main__.py’ file can
     now be executed directly by passing their name to the interpreter.
     The directory/zipfile is automatically inserted as the first entry
     in sys.path.  (Suggestion and initial patch by Andy Chu; revised
     patch by Phillip J. Eby and Nick Coghlan; bpo-1739468(1).)

   * The *note int(): 185. type gained a ‘bit_length’ method that
     returns the number of bits necessary to represent its argument in
     binary:

          >>> n = 37
          >>> bin(37)
          '0b100101'
          >>> n.bit_length()
          6
          >>> n = 2**123-1
          >>> n.bit_length()
          123
          >>> (n+1).bit_length()
          124

     （由 Fredrik Johansson, Victor Stinner, Raymond Hettinger 和 Mark
     Dickinson 在 bpo-3439(2) 中贡献。）

   * The fields in *note format(): 4e3. strings can now be automatically
     numbered:

          >>> 'Sir {} of {}'.format('Gallahad', 'Camelot')
          'Sir Gallahad of Camelot'

     Formerly, the string would have required numbered fields such as:
     ‘'Sir {0} of {1}'’.

     （由 Eric Smith在 bpo-5237(3) 中贡献）

   * The ‘string.maketrans()’ function is deprecated and is replaced by
     new static methods, *note bytes.maketrans(): c11. and *note
     bytearray.maketrans(): c12.  This change solves the confusion
     around which types were supported by the *note string: f7. module.
     Now, *note str: 339, *note bytes: 33a, and *note bytearray: 33b.
     each have their own `maketrans' and `translate' methods with
     intermediate translation tables of the appropriate type.

     （由Georg Brandl在 bpo-5675(4) 中贡献）

   * The syntax of the *note with: 6f2. statement now allows multiple
     context managers in a single statement:

          >>> with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
          ...     for line in infile:
          ...         if '<critical>' in line:
          ...             outfile.write(line)

     With the new syntax, the ‘contextlib.nested()’ function is no
     longer needed and is now deprecated.

     (Contributed by Georg Brandl and Mattias Brändström; appspot issue
     53094(5).)

   * ‘round(x, n)’ now returns an integer if `x' is an integer.
     Previously it returned a float:

          >>> round(1123, -2)
          1100

     （由 Mark Dickinson在 bpo-4707(6) 贡献）

   * Python now uses David Gay’s algorithm for finding the shortest
     floating point representation that doesn’t change its value.  This
     should help mitigate some of the confusion surrounding binary
     floating point numbers.

     The significance is easily seen with a number like ‘1.1’ which does
     not have an exact equivalent in binary floating point.  Since there
     is no exact equivalent, an expression like ‘float('1.1')’ evaluates
     to the nearest representable value which is ‘0x1.199999999999ap+0’
     in hex or ‘1.100000000000000088817841970012523233890533447265625’
     in decimal.  That nearest value was and still is used in subsequent
     floating point calculations.

     What is new is how the number gets displayed.  Formerly, Python
     used a simple approach.  The value of ‘repr(1.1)’ was computed as
     ‘format(1.1, '.17g')’ which evaluated to ‘'1.1000000000000001'’.
     The advantage of using 17 digits was that it relied on IEEE-754
     guarantees to assure that ‘eval(repr(1.1))’ would round-trip
     exactly to its original value.  The disadvantage is that many
     people found the output to be confusing (mistaking intrinsic
     limitations of binary floating point representation as being a
     problem with Python itself).

     The new algorithm for ‘repr(1.1)’ is smarter and returns ‘'1.1'’.
     Effectively, it searches all equivalent string representations
     (ones that get stored with the same underlying float value) and
     returns the shortest representation.

     The new algorithm tends to emit cleaner representations when
     possible, but it does not change the underlying values.  So, it is
     still the case that ‘1.1 + 2.2 != 3.3’ even though the
     representations may suggest otherwise.

     The new algorithm depends on certain features in the underlying
     floating point implementation.  If the required features are not
     found, the old algorithm will continue to be used.  Also, the text
     pickle protocols assure cross-platform portability by using the old
     algorithm.

     （由 Eric Smith 和 Mark Dickinson 在 bpo-1580(7) 贡献）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1739468

   (2) https://bugs.python.org/issue3439

   (3) https://bugs.python.org/issue5237

   (4) https://bugs.python.org/issue5675

   (5) https://codereview.appspot.com/53094

   (6) https://bugs.python.org/issue4707

   (7) https://bugs.python.org/issue1580


File: python.info,  Node: 新增，改进和弃用的模块<2>,  Next: 性能优化<7>,  Prev: 其他语言特性修改<8>,  Up: Python 3 1 有什么新变化

1.8.4 新增，改进和弃用的模块
----------------------------

   * Added a *note collections.Counter: 9e2. class to support convenient
     counting of unique items in a sequence or iterable:

          >>> Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
          Counter({'blue': 3, 'red': 2, 'green': 1})

     （由 Raymond Hettinger 在 bpo-1696199(1) 中贡献。）

   * Added a new module, *note tkinter.ttk: 110. for access to the Tk
     themed widget set.  The basic idea of ttk is to separate, to the
     extent possible, the code implementing a widget’s behavior from the
     code implementing its appearance.

     （由 Guilherme Polo 在 bpo-2983(2) 中贡献。）

   * The *note gzip.GzipFile: 6e6. and *note bz2.BZ2File: 939. classes
     now support the context management protocol:

          >>> # Automatically close file after writing
          >>> with gzip.GzipFile(filename, "wb") as f:
          ...     f.write(b"xxx")

     （由 Antoine Pitrou 贡献。）

   * The *note decimal: 36. module now supports methods for creating a
     decimal object from a binary *note float: 188.  The conversion is
     exact but can sometimes be surprising:

          >>> Decimal.from_float(1.1)
          Decimal('1.100000000000000088817841970012523233890533447265625')

     The long decimal result shows the actual binary fraction being
     stored for `1.1'.  The fraction has many digits because `1.1'
     cannot be exactly represented in binary.

     （由Raymond Hettinger 和 Mark Dickinson贡献。）

   * The *note itertools: a4. module grew two new functions.  The *note
     itertools.combinations_with_replacement(): c21. function is one of
     four for generating combinatorics including permutations and
     Cartesian products.  The *note itertools.compress(): c22. function
     mimics its namesake from APL. Also, the existing *note
     itertools.count(): c23. function now has an optional `step'
     argument and can accept any type of counting sequence including
     *note fractions.Fraction: 186. and *note decimal.Decimal: 189.:

          >>> [p+q for p,q in combinations_with_replacement('LOVE', 2)]
          ['LL', 'LO', 'LV', 'LE', 'OO', 'OV', 'OE', 'VV', 'VE', 'EE']

          >>> list(compress(data=range(10), selectors=[0,0,1,1,0,1,0,1,0,0]))
          [2, 3, 5, 7]

          >>> c = count(start=Fraction(1,2), step=Fraction(1,6))
          >>> [next(c), next(c), next(c), next(c)]
          [Fraction(1, 2), Fraction(2, 3), Fraction(5, 6), Fraction(1, 1)]

     （由 Raymond Hettinger 贡献。）

   * *note collections.namedtuple(): 1b7. now supports a keyword
     argument `rename' which lets invalid fieldnames be automatically
     converted to positional names in the form _0, _1, etc.  This is
     useful when the field names are being created by an external source
     such as a CSV header, SQL field list, or user input:

          >>> query = input()
          SELECT region, dept, count(*) FROM main GROUPBY region, dept

          >>> cursor.execute(query)
          >>> query_fields = [desc[0] for desc in cursor.description]
          >>> UserQuery = namedtuple('UserQuery', query_fields, rename=True)
          >>> pprint.pprint([UserQuery(*row) for row in cursor])
          [UserQuery(region='South', dept='Shipping', _2=185),
           UserQuery(region='North', dept='Accounting', _2=37),
           UserQuery(region='West', dept='Sales', _2=419)]

     （由 Raymond Hettinger 在 bpo-1818(3) 中贡献。）

   * The *note re.sub(): 483, *note re.subn(): 73d. and *note
     re.split(): 3d2. functions now accept a flags parameter.

     （由 Gregory Smith 贡献）

   * The *note logging: ab. module now implements a simple *note
     logging.NullHandler: c24. class for applications that are not using
     logging but are calling library code that does.  Setting-up a null
     handler will suppress spurious warnings such as "No handlers could
     be found for logger foo":

          >>> h = logging.NullHandler()
          >>> logging.getLogger("foo").addHandler(h)

     （由 Vinay Sajip 在 bpo-4384(4) 中贡献。）

   * The *note runpy: e3. module which supports the ‘-m’ command line
     switch now supports the execution of packages by looking for and
     executing a ‘__main__’ submodule when a package name is supplied.

     （由 Andi Vajda 在 bpo-4195(5) 中贡献。）

   * The *note pdb: ca. module can now access and display source code
     loaded via *note zipimport: 144. (or any other conformant PEP
     302(6) loader).

     （由 Alexander Belopolsky 在 bpo-4201(7) 中贡献。）

   * *note functools.partial: 7d1. objects can now be pickled.

     (Suggested by Antoine Pitrou and Jesse Noller.  Implemented by Jack
     Diederich; bpo-5228(8).)

   * Add *note pydoc: da. help topics for symbols so that ‘help('@')’
     works as expected in the interactive environment.

     （由 David Laban 在 bpo-4739(9) 中贡献。）

   * The *note unittest: 11c. module now supports skipping individual
     tests or classes of tests.  And it supports marking a test as an
     expected failure, a test that is known to be broken, but shouldn’t
     be counted as a failure on a TestResult:

          class TestGizmo(unittest.TestCase):

              @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
              def test_gizmo_on_windows(self):
                  ...

              @unittest.expectedFailure
              def test_gimzo_without_required_library(self):
                  ...

     Also, tests for exceptions have been builtout to work with context
     managers using the *note with: 6f2. statement:

          def test_division_by_zero(self):
              with self.assertRaises(ZeroDivisionError):
                  x / 0

     In addition, several new assertion methods were added including
     ‘assertSetEqual()’, ‘assertDictEqual()’,
     ‘assertDictContainsSubset()’, ‘assertListEqual()’,
     ‘assertTupleEqual()’, ‘assertSequenceEqual()’,
     ‘assertRaisesRegexp()’, ‘assertIsNone()’, and ‘assertIsNotNone()’.

     （由Benjamin Peterson 和 Antoine Pitrou 贡献。）

   * The *note io: a2. module has three new constants for the ‘seek()’
     method ‘SEEK_SET’, ‘SEEK_CUR’, and ‘SEEK_END’.

   * The *note sys.version_info: b22. tuple is now a named tuple:

          >>> sys.version_info
          sys.version_info(major=3, minor=1, micro=0, releaselevel='alpha', serial=2)

     （由 Ross Light 在 bpo-4285(10) 中贡献。）

   * The *note nntplib: c1. and *note imaplib: 98. modules now support
     IPv6.

     （由 Derek Morr 在 bpo-1655(11) 和 bpo-1664(12) 中贡献。）

   * The *note pickle: cb. module has been adapted for better
     interoperability with Python 2.x when used with protocol 2 or
     lower.  The reorganization of the standard library changed the
     formal reference for many objects.  For example, ‘__builtin__.set’
     in Python 2 is called ‘builtins.set’ in Python 3.  This change
     confounded efforts to share data between different versions of
     Python.  But now when protocol 2 or lower is selected, the pickler
     will automatically use the old Python 2 names for both loading and
     dumping.  This remapping is turned-on by default but can be
     disabled with the `fix_imports' option:

          >>> s = {1, 2, 3}
          >>> pickle.dumps(s, protocol=0)
          b'c__builtin__\nset\np0\n((lp1\nL1L\naL2L\naL3L\natp2\nRp3\n.'
          >>> pickle.dumps(s, protocol=0, fix_imports=False)
          b'cbuiltins\nset\np0\n((lp1\nL1L\naL2L\naL3L\natp2\nRp3\n.'

     An unfortunate but unavoidable side-effect of this change is that
     protocol 2 pickles produced by Python 3.1 won’t be readable with
     Python 3.0.  The latest pickle protocol, protocol 3, should be used
     when migrating data between Python 3.x implementations, as it
     doesn’t attempt to remain compatible with Python 2.x.

     （由 Alexandre Vassalotti 和 Antoine Pitrou 在 bpo-6137(13) 中贡献
     。）

   * A new module, *note importlib: 9b. was added.  It provides a
     complete, portable, pure Python reference implementation of the
     *note import: c25. statement and its counterpart, the *note
     __import__(): 619. function.  It represents a substantial step
     forward in documenting and defining the actions that take place
     during imports.

     （由 Brett Cannon 贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1696199

   (2) https://bugs.python.org/issue2983

   (3) https://bugs.python.org/issue1818

   (4) https://bugs.python.org/issue4384

   (5) https://bugs.python.org/issue4195

   (6) https://www.python.org/dev/peps/pep-0302

   (7) https://bugs.python.org/issue4201

   (8) https://bugs.python.org/issue5228

   (9) https://bugs.python.org/issue4739

   (10) https://bugs.python.org/issue4285

   (11) https://bugs.python.org/issue1655

   (12) https://bugs.python.org/issue1664

   (13) https://bugs.python.org/issue6137


File: python.info,  Node: 性能优化<7>,  Next: IDLE<2>,  Prev: 新增，改进和弃用的模块<2>,  Up: Python 3 1 有什么新变化

1.8.5 性能优化
--------------

Major performance enhancements have been added:

   * The new I/O library (as defined in PEP 3116(1)) was mostly written
     in Python and quickly proved to be a problematic bottleneck in
     Python 3.0.  In Python 3.1, the I/O library has been entirely
     rewritten in C and is 2 to 20 times faster depending on the task at
     hand.  The pure Python version is still available for
     experimentation purposes through the ‘_pyio’ module.

     （由 Amaury Forgeot d’Arc 和 Antoine Pitrou 贡献。）

   * Added a heuristic so that tuples and dicts containing only
     untrackable objects are not tracked by the garbage collector.  This
     can reduce the size of collections and therefore the garbage
     collection overhead on long-running programs, depending on their
     particular use of datatypes.

     （由 Antoine Pitrou 在 bpo-4688(2) 中贡献。）

   * Enabling a configure option named ‘--with-computed-gotos’ on
     compilers that support it (notably: gcc, SunPro, icc), the bytecode
     evaluation loop is compiled with a new dispatch mechanism which
     gives speedups of up to 20%, depending on the system, the compiler,
     and the benchmark.

     （由 Antoine Pitrou 以及其他一些参与者在 bpo-4753(3) 中贡献。）

   * The decoding of UTF-8, UTF-16 and LATIN-1 is now two to four times
     faster.

     （由 Antoine Pitrou 和 Amaury Forgeot d’Arc 在 bpo-4868(4) 中贡献。
     ）

   * The *note json: a5. module now has a C extension to substantially
     improve its performance.  In addition, the API was modified so that
     json works only with *note str: 339, not with *note bytes: 33a.
     That change makes the module closely match the JSON
     specification(5) which is defined in terms of Unicode.

     （由 Bob Ippolito 在 bpo-4136(6) 中贡献。并由 Antoine Pitrou 和
     Benjamin Peterson 转换为Py3.1）

   * Unpickling now interns the attribute names of pickled objects.
     This saves memory and allows pickles to be smaller.

     （由 Jake McGuire 和 Antoine Pitrou 在 bpo-5084(7) 中贡献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3116

   (2) https://bugs.python.org/issue4688

   (3) https://bugs.python.org/issue4753

   (4) https://bugs.python.org/issue4868

   (5) http://json.org/

   (6) https://bugs.python.org/issue4136

   (7) https://bugs.python.org/issue5084


File: python.info,  Node: IDLE<2>,  Next: 构建和 C API 的改变<6>,  Prev: 性能优化<7>,  Up: Python 3 1 有什么新变化

1.8.6 IDLE
----------

   * IDLE’s format menu now provides an option to strip trailing
     whitespace from a source file.

     （由 Roger D. Serwy 在 bpo-5150(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5150


File: python.info,  Node: 构建和 C API 的改变<6>,  Next: 移植到 Python 3 1,  Prev: IDLE<2>,  Up: Python 3 1 有什么新变化

1.8.7 构建和 C API 的改变
-------------------------

Changes to Python’s build process and to the C API include:

   * Integers are now stored internally either in base 2**15 or in base
     2**30, the base being determined at build time.  Previously, they
     were always stored in base 2**15.  Using base 2**30 gives
     significant performance improvements on 64-bit machines, but
     benchmark results on 32-bit machines have been mixed.  Therefore,
     the default is to use base 2**30 on 64-bit machines and base 2**15
     on 32-bit machines; on Unix, there’s a new configure option
     ‘--enable-big-digits’ that can be used to override this default.

     Apart from the performance improvements this change should be
     invisible to end users, with one exception: for testing and
     debugging purposes there’s a new *note sys.int_info: c29. that
     provides information about the internal format, giving the number
     of bits per digit and the size in bytes of the C type used to store
     each digit:

          >>> import sys
          >>> sys.int_info
          sys.int_info(bits_per_digit=30, sizeof_digit=4)

     （由 Mark Dickinson在 bpo-4258(1) 贡献）

   * The *note PyLong_AsUnsignedLongLong(): c2a. function now handles a
     negative `pylong' by raising *note OverflowError: 968. instead of
     *note TypeError: 193.

     （由 Mark Dickinson 和 Lisandro Dalcrin 在 bpo-5175(2) 中贡献。）

   * Deprecated ‘PyNumber_Int()’.  Use *note PyNumber_Long(): 26d.
     instead.

     （由 Mark Dickinson在 bpo-4910(3) 贡献）

   * Added a new *note PyOS_string_to_double(): c2b. function to replace
     the deprecated functions ‘PyOS_ascii_strtod()’ and
     ‘PyOS_ascii_atof()’.

     （由 Mark Dickinson 在 bpo-5914(4) 贡献）

   * Added *note PyCapsule: c0f. as a replacement for the ‘PyCObject’
     API. The principal difference is that the new type has a well
     defined interface for passing typing safety information and a less
     complicated signature for calling a destructor.  The old type had a
     problematic API and is now deprecated.

     （由 Larry Hastings 在 bpo-5630(5) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4258

   (2) https://bugs.python.org/issue5175

   (3) https://bugs.python.org/issue4910

   (4) https://bugs.python.org/issue5914

   (5) https://bugs.python.org/issue5630


File: python.info,  Node: 移植到 Python 3 1,  Prev: 构建和 C API 的改变<6>,  Up: Python 3 1 有什么新变化

1.8.8 移植到 Python 3.1
-----------------------

This section lists previously described changes and other bugfixes that
may require changes to your code:

   * The new floating point string representations can break existing
     doctests.  For example:

          def e():
              '''Compute the base of natural logarithms.

              >>> e()
              2.7182818284590451

              '''
              return sum(1/math.factorial(x) for x in reversed(range(30)))

          doctest.testmod()

          **********************************************************************
          Failed example:
              e()
          Expected:
              2.7182818284590451
          Got:
              2.718281828459045
          **********************************************************************

   * The automatic name remapping in the pickle module for protocol 2 or
     lower can make Python 3.1 pickles unreadable in Python 3.0.  One
     solution is to use protocol 3.  Another solution is to set the
     `fix_imports' option to ‘False’.  See the discussion above for more
     details.


File: python.info,  Node: Python 3 0 有什么新变化,  Next: Python 2 7 有什么新变化,  Prev: Python 3 1 有什么新变化,  Up: Python的新变化

1.9 Python 3.0 有什么新变化
===========================


作者: Guido van Rossum

This article explains the new features in Python 3.0, compared to 2.6.
Python 3.0, also known as "Python 3000" or "Py3K", is the first ever
`intentionally backwards incompatible' Python release.  There are more
changes than in a typical release, and more that are important for all
Python users.  Nevertheless, after digesting the changes, you’ll find
that Python really hasn’t changed all that much – by and large, we’re
mostly fixing well-known annoyances and warts, and removing a lot of old
cruft.

This article doesn’t attempt to provide a complete specification of all
new features, but instead tries to give a convenient overview.  For full
details, you should refer to the documentation for Python 3.0, and/or
the many PEPs referenced in the text.  If you want to understand the
complete implementation and design rationale for a particular feature,
PEPs usually have more details than the regular documentation; but note
that PEPs usually are not kept up-to-date once a feature has been fully
implemented.

Due to time constraints this document is not as complete as it should
have been.  As always for a new release, the ‘Misc/NEWS’ file in the
source distribution contains a wealth of detailed information about
every small thing that was changed.

* Menu:

* 常见的绊脚石::
* Overview Of Syntax Changes::
* Changes Already Present In Python 2.6: Changes Already Present In Python 2 6.
* Library Changes::
* PEP 3101; A New Approach To String Formatting: PEP 3101 A New Approach To String Formatting.
* Changes To Exceptions::
* Miscellaneous Other Changes::
* 构建和 C API 的改变: 构建和 C API 的改变<7>.
* 性能::
* 移植到 Python 3.0: 移植到 Python 3 0.


File: python.info,  Node: 常见的绊脚石,  Next: Overview Of Syntax Changes,  Up: Python 3 0 有什么新变化

1.9.1 常见的绊脚石
------------------

This section lists those few changes that are most likely to trip you up
if you’re used to Python 2.5.

* Menu:

* Print Is A Function::
* Views And Iterators Instead Of Lists::
* Ordering Comparisons::
* 整数::
* Text Vs. Data Instead Of Unicode Vs. 8-bit: Text Vs Data Instead Of Unicode Vs 8-bit.


File: python.info,  Node: Print Is A Function,  Next: Views And Iterators Instead Of Lists,  Up: 常见的绊脚石

1.9.1.1 Print Is A Function
...........................

The ‘print’ statement has been replaced with a *note print(): 88f.
function, with keyword arguments to replace most of the special syntax
of the old ‘print’ statement ( PEP 3105(1)).  Examples:

     Old: print "The answer is", 2*2
     New: print("The answer is", 2*2)

     Old: print x,           # Trailing comma suppresses newline
     New: print(x, end=" ")  # Appends a space instead of a newline

     Old: print              # Prints a newline
     New: print()            # You must call the function!

     Old: print >>sys.stderr, "fatal error"
     New: print("fatal error", file=sys.stderr)

     Old: print (x, y)       # prints repr((x, y))
     New: print((x, y))      # Not the same as print(x, y)!

You can also customize the separator between items, e.g.:

     print("There are <", 2**32, "> possibilities!", sep="")

which produces:

     There are <4294967296> possibilities!

注意

   * The *note print(): 88f. function doesn’t support the "softspace"
     feature of the old ‘print’ statement.  For example, in Python 2.x,
     ‘print "A\n", "B"’ would write ‘"A\nB\n"’; but in Python 3.0,
     ‘print("A\n", "B")’ writes ‘"A\n B\n"’.

   * Initially, you’ll be finding yourself typing the old ‘print x’ a
     lot in interactive mode.  Time to retrain your fingers to type
     ‘print(x)’ instead!

   * When using the ‘2to3’ source-to-source conversion tool, all ‘print’
     statements are automatically converted to *note print(): 88f.
     function calls, so this is mostly a non-issue for larger projects.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3105


File: python.info,  Node: Views And Iterators Instead Of Lists,  Next: Ordering Comparisons,  Prev: Print Is A Function,  Up: 常见的绊脚石

1.9.1.2 Views And Iterators Instead Of Lists
............................................

Some well-known APIs no longer return lists:

   * *note dict: 1b9. methods *note dict.keys(): c32, *note
     dict.items(): c33. and *note dict.values(): c34. return "views"
     instead of lists.  For example, this no longer works: ‘k =
     d.keys(); k.sort()’.  Use ‘k = sorted(d)’ instead (this works in
     Python 2.5 too and is just as efficient).

   * Also, the ‘dict.iterkeys()’, ‘dict.iteritems()’ and
     ‘dict.itervalues()’ methods are no longer supported.

   * *note map(): c35. and *note filter(): c36. return iterators.  If
     you really need a list and the input sequences are all of equal
     length, a quick fix is to wrap *note map(): c35. in *note list():
     263, e.g.  ‘list(map(...))’, but a better fix is often to use a
     list comprehension (especially when the original code uses *note
     lambda: c37.), or rewriting the code so it doesn’t need a list at
     all.  Particularly tricky is *note map(): c35. invoked for the side
     effects of the function; the correct transformation is to use a
     regular *note for: c38. loop (since creating a list would just be
     wasteful).

     If the input sequences are not of equal length, *note map(): c35.
     will stop at the termination of the shortest of the sequences.  For
     full compatibility with *note map(): c35. from Python 2.x, also
     wrap the sequences in *note itertools.zip_longest(): c39, e.g.
     ‘map(func, *sequences)’ becomes ‘list(map(func,
     itertools.zip_longest(*sequences)))’.

   * *note range(): 9c6. now behaves like ‘xrange()’ used to behave,
     except it works with values of arbitrary size.  The latter no
     longer exists.

   * *note zip(): c3a. now returns an iterator.


File: python.info,  Node: Ordering Comparisons,  Next: 整数,  Prev: Views And Iterators Instead Of Lists,  Up: 常见的绊脚石

1.9.1.3 Ordering Comparisons
............................

Python 3.0 has simplified the rules for ordering comparisons:

   * The ordering comparison operators (‘<’, ‘<=’, ‘>=’, ‘>’) raise a
     TypeError exception when the operands don’t have a meaningful
     natural ordering.  Thus, expressions like ‘1 < ''’, ‘0 > None’ or
     ‘len <= len’ are no longer valid, and e.g.  ‘None < None’ raises
     *note TypeError: 193. instead of returning ‘False’.  A corollary is
     that sorting a heterogeneous list no longer makes sense – all the
     elements must be comparable to each other.  Note that this does not
     apply to the ‘==’ and ‘!=’ operators: objects of different
     incomparable types always compare unequal to each other.

   * ‘builtin.sorted()’ and *note list.sort(): 44d. no longer accept the
     `cmp' argument providing a comparison function.  Use the `key'
     argument instead.  N.B. the `key' and `reverse' arguments are now
     "keyword-only".

   * The ‘cmp()’ function should be treated as gone, and the ‘__cmp__()’
     special method is no longer supported.  Use *note __lt__(): c3c.
     for sorting, *note __eq__(): 348. with *note __hash__(): 349, and
     other rich comparisons as needed.  (If you really need the ‘cmp()’
     functionality, you could use the expression ‘(a > b) - (a < b)’ as
     the equivalent for ‘cmp(a, b)’.)


File: python.info,  Node: 整数,  Next: Text Vs Data Instead Of Unicode Vs 8-bit,  Prev: Ordering Comparisons,  Up: 常见的绊脚石

1.9.1.4 整数
............

   * PEP 237(1): Essentially, ‘long’ renamed to *note int: 185.  That
     is, there is only one built-in integral type, named *note int:
     185.; but it behaves mostly like the old ‘long’ type.

   * PEP 238(2): An expression like ‘1/2’ returns a float.  Use ‘1//2’
     to get the truncating behavior.  (The latter syntax has existed for
     years, at least since Python 2.2.)

   * The ‘sys.maxint’ constant was removed, since there is no longer a
     limit to the value of integers.  However, *note sys.maxsize: b4b.
     can be used as an integer larger than any practical list or string
     index.  It conforms to the implementation’s "natural" integer size
     and is typically the same as ‘sys.maxint’ in previous releases on
     the same platform (assuming the same build options).

   * The *note repr(): 7d5. of a long integer doesn’t include the
     trailing ‘L’ anymore, so code that unconditionally strips that
     character will chop off the last digit instead.  (Use *note str():
     339. instead.)

   * Octal literals are no longer of the form ‘0720’; use ‘0o720’
     instead.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0237

   (2) https://www.python.org/dev/peps/pep-0238


File: python.info,  Node: Text Vs Data Instead Of Unicode Vs 8-bit,  Prev: 整数,  Up: 常见的绊脚石

1.9.1.5 Text Vs. Data Instead Of Unicode Vs. 8-bit
..................................................

Everything you thought you knew about binary data and Unicode has
changed.

   * Python 3.0 uses the concepts of `text' and (binary) `data' instead
     of Unicode strings and 8-bit strings.  All text is Unicode; however
     `encoded' Unicode is represented as binary data.  The type used to
     hold text is *note str: 339, the type used to hold data is *note
     bytes: 33a.  The biggest difference with the 2.x situation is that
     any attempt to mix text and data in Python 3.0 raises *note
     TypeError: 193, whereas if you were to mix Unicode and 8-bit
     strings in Python 2.x, it would work if the 8-bit string happened
     to contain only 7-bit (ASCII) bytes, but you would get *note
     UnicodeDecodeError: 1fe. if it contained non-ASCII values.  This
     value-specific behavior has caused numerous sad faces over the
     years.

   * As a consequence of this change in philosophy, pretty much all code
     that uses Unicode, encodings or binary data most likely has to
     change.  The change is for the better, as in the 2.x world there
     were numerous bugs having to do with mixing encoded and unencoded
     text.  To be prepared in Python 2.x, start using ‘unicode’ for all
     unencoded text, and *note str: 339. for binary or encoded data
     only.  Then the ‘2to3’ tool will do most of the work for you.

   * You can no longer use ‘u"..."’ literals for Unicode text.  However,
     you must use ‘b"..."’ literals for binary data.

   * As the *note str: 339. and *note bytes: 33a. types cannot be mixed,
     you must always explicitly convert between them.  Use *note
     str.encode(): c3f. to go from *note str: 339. to *note bytes: 33a,
     and *note bytes.decode(): c40. to go from *note bytes: 33a. to
     *note str: 339.  You can also use ‘bytes(s, encoding=...)’ and
     ‘str(b, encoding=...)’, respectively.

   * Like *note str: 339, the *note bytes: 33a. type is immutable.
     There is a separate `mutable' type to hold buffered binary data,
     *note bytearray: 33b.  Nearly all APIs that accept *note bytes:
     33a. also accept *note bytearray: 33b.  The mutable API is based on
     ‘collections.MutableSequence’.

   * All backslashes in raw string literals are interpreted literally.
     This means that ‘'\U'’ and ‘'\u'’ escapes in raw strings are not
     treated specially.  For example, ‘r'\u20ac'’ is a string of 6
     characters in Python 3.0, whereas in 2.6, ‘ur'\u20ac'’ was the
     single "euro" character.  (Of course, this change only affects raw
     string literals; the euro character is ‘'\u20ac'’ in Python 3.0.)

   * The built-in ‘basestring’ abstract type was removed.  Use *note
     str: 339. instead.  The *note str: 339. and *note bytes: 33a. types
     don’t have functionality enough in common to warrant a shared base
     class.  The ‘2to3’ tool (see below) replaces every occurrence of
     ‘basestring’ with *note str: 339.

   * Files opened as text files (still the default mode for *note
     open(): 4f8.) always use an encoding to map between strings (in
     memory) and bytes (on disk).  Binary files (opened with a ‘b’ in
     the mode argument) always use bytes in memory.  This means that if
     a file is opened using an incorrect mode or encoding, I/O will
     likely fail loudly, instead of silently producing incorrect data.
     It also means that even Unix users will have to specify the correct
     mode (text or binary) when opening a file.  There is a
     platform-dependent default encoding, which on Unixy platforms can
     be set with the ‘LANG’ environment variable (and sometimes also
     with some other platform-specific locale-related environment
     variables).  In many cases, but not all, the system default is
     UTF-8; you should never count on this default.  Any application
     reading or writing more than pure ASCII text should probably have a
     way to override the encoding.  There is no longer any need for
     using the encoding-aware streams in the *note codecs: 1c. module.

   * The initial values of *note sys.stdin: 316, *note sys.stdout: 317.
     and *note sys.stderr: 318. are now unicode-only text files (i.e.,
     they are instances of *note io.TextIOBase: c41.).  To read and
     write bytes data with these streams, you need to use their *note
     io.TextIOBase.buffer: c42. attribute.

   * Filenames are passed to and returned from APIs as (Unicode)
     strings.  This can present platform-specific problems because on
     some platforms filenames are arbitrary byte strings.  (On the other
     hand, on Windows filenames are natively stored as Unicode.)  As a
     work-around, most APIs (e.g.  *note open(): 4f8. and many functions
     in the *note os: c5. module) that take filenames accept *note
     bytes: 33a. objects as well as strings, and a few APIs have a way
     to ask for a *note bytes: 33a. return value.  Thus, *note
     os.listdir(): a49. returns a list of *note bytes: 33a. instances if
     the argument is a *note bytes: 33a. instance, and *note
     os.getcwdb(): 2b9. returns the current working directory as a *note
     bytes: 33a. instance.  Note that when *note os.listdir(): a49.
     returns a list of strings, filenames that cannot be decoded
     properly are omitted rather than raising *note UnicodeError: c43.

   * Some system APIs like *note os.environ: b3f. and *note sys.argv:
     c03. can also present problems when the bytes made available by the
     system is not interpretable using the default encoding.  Setting
     the ‘LANG’ variable and rerunning the program is probably the best
     approach.

   * PEP 3138(1): The *note repr(): 7d5. of a string no longer escapes
     non-ASCII characters.  It still escapes control characters and code
     points with non-printable status in the Unicode standard, however.

   * PEP 3120(2): The default source encoding is now UTF-8.

   * PEP 3131(3): Non-ASCII letters are now allowed in identifiers.
     (However, the standard library remains ASCII-only with the
     exception of contributor names in comments.)

   * The ‘StringIO’ and ‘cStringIO’ modules are gone.  Instead, import
     the *note io: a2. module and use *note io.StringIO: 836. or *note
     io.BytesIO: 7a4. for text and data respectively.

   * See also the *note Unicode 指南: c44, which was updated for Python
     3.0.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3138

   (2) https://www.python.org/dev/peps/pep-3120

   (3) https://www.python.org/dev/peps/pep-3131


File: python.info,  Node: Overview Of Syntax Changes,  Next: Changes Already Present In Python 2 6,  Prev: 常见的绊脚石,  Up: Python 3 0 有什么新变化

1.9.2 Overview Of Syntax Changes
--------------------------------

This section gives a brief overview of every `syntactic' change in
Python 3.0.

* Menu:

* 新语法::
* 修改的语法::
* 移除的语法::


File: python.info,  Node: 新语法,  Next: 修改的语法,  Up: Overview Of Syntax Changes

1.9.2.1 新语法
..............

   * PEP 3107(1): Function argument and return value annotations.  This
     provides a standardized way of annotating a function’s parameters
     and return value.  There are no semantics attached to such
     annotations except that they can be introspected at runtime using
     the ‘__annotations__’ attribute.  The intent is to encourage
     experimentation through metaclasses, decorators or frameworks.

   * PEP 3102(2): Keyword-only arguments.  Named parameters occurring
     after ‘*args’ in the parameter list `must' be specified using
     keyword syntax in the call.  You can also use a bare ‘*’ in the
     parameter list to indicate that you don’t accept a variable-length
     argument list, but you do have keyword-only arguments.

   * Keyword arguments are allowed after the list of base classes in a
     class definition.  This is used by the new convention for
     specifying a metaclass (see next section), but can be used for
     other purposes as well, as long as the metaclass supports it.

   * PEP 3104(3): *note nonlocal: c47. statement.  Using ‘nonlocal x’
     you can now assign directly to a variable in an outer (but
     non-global) scope.  ‘nonlocal’ is a new reserved word.

   * PEP 3132(4): Extended Iterable Unpacking.  You can now write things
     like ‘a, b, *rest = some_sequence’.  And even ‘*rest, a = stuff’.
     The ‘rest’ object is always a (possibly empty) list; the right-hand
     side may be any iterable.  Example:

          (a, *rest, b) = range(5)

     This sets `a' to ‘0’, `b' to ‘4’, and `rest' to ‘[1, 2, 3]’.

   * Dictionary comprehensions: ‘{k: v for k, v in stuff}’ means the
     same thing as ‘dict(stuff)’ but is more flexible.  (This is PEP
     274(5) vindicated.  :-)

   * Set literals, e.g.  ‘{1, 2}’.  Note that ‘{}’ is an empty
     dictionary; use ‘set()’ for an empty set.  Set comprehensions are
     also supported; e.g., ‘{x for x in stuff}’ means the same thing as
     ‘set(stuff)’ but is more flexible.

   * New octal literals, e.g.  ‘0o720’ (already in 2.6).  The old octal
     literals (‘0720’) are gone.

   * New binary literals, e.g.  ‘0b1010’ (already in 2.6), and there is
     a new corresponding built-in function, *note bin(): c48.

   * Bytes literals are introduced with a leading ‘b’ or ‘B’, and there
     is a new corresponding built-in function, *note bytes(): 33a.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3107

   (2) https://www.python.org/dev/peps/pep-3102

   (3) https://www.python.org/dev/peps/pep-3104

   (4) https://www.python.org/dev/peps/pep-3132

   (5) https://www.python.org/dev/peps/pep-0274


File: python.info,  Node: 修改的语法,  Next: 移除的语法,  Prev: 新语法,  Up: Overview Of Syntax Changes

1.9.2.2 修改的语法
..................

   * PEP 3109(1) and PEP 3134(2): new *note raise: c4a. statement
     syntax: ‘raise [`expr' [from `expr']]’.  See below.

   * ‘as’ and *note with: 6f2. are now reserved words.  (Since 2.6,
     actually.)

   * ‘True’, ‘False’, and ‘None’ are reserved words.  (2.6 partially
     enforced the restrictions on ‘None’ already.)

   * Change from *note except: b46. `exc', `var' to ‘except’ `exc' ‘as’
     `var'.  See PEP 3110(3).

   * PEP 3115(4): New Metaclass Syntax.  Instead of:

          class C:
              __metaclass__ = M
              ...

     you must now use:

          class C(metaclass=M):
              ...

     The module-global ‘__metaclass__’ variable is no longer supported.
     (It was a crutch to make it easier to default to new-style classes
     without deriving every class from *note object: 2b1.)

   * List comprehensions no longer support the syntactic form ‘[... for
     `var' in `item1', `item2', ...]’.  Use ‘[... for `var' in (`item1',
     `item2', ...)]’ instead.  Also note that list comprehensions have
     different semantics: they are closer to syntactic sugar for a
     generator expression inside a *note list(): 263. constructor, and
     in particular the loop control variables are no longer leaked into
     the surrounding scope.

   * The `ellipsis' (‘...’) can be used as an atomic expression
     anywhere.  (Previously it was only allowed in slices.)  Also, it
     `must' now be spelled as ‘...’.  (Previously it could also be
     spelled as ‘. . .’, by a mere accident of the grammar.)

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3109

   (2) https://www.python.org/dev/peps/pep-3134

   (3) https://www.python.org/dev/peps/pep-3110

   (4) https://www.python.org/dev/peps/pep-3115


File: python.info,  Node: 移除的语法,  Prev: 修改的语法,  Up: Overview Of Syntax Changes

1.9.2.3 移除的语法
..................

   * PEP 3113(1): Tuple parameter unpacking removed.  You can no longer
     write ‘def foo(a, (b, c)): ...’.  Use ‘def foo(a, b_c): b, c = b_c’
     instead.

   * Removed backticks (use *note repr(): 7d5. instead).

   * Removed ‘<>’ (use ‘!=’ instead).

   * Removed keyword: *note exec(): c4c. is no longer a keyword; it
     remains as a function.  (Fortunately the function syntax was also
     accepted in 2.x.)  Also note that *note exec(): c4c. no longer
     takes a stream argument; instead of ‘exec(f)’ you can use
     ‘exec(f.read())’.

   * Integer literals no longer support a trailing ‘l’ or ‘L’.

   * String literals no longer support a leading ‘u’ or ‘U’.

   * The *note from: c4d. `module' *note import: c25. ‘*’ syntax is only
     allowed at the module level, no longer inside functions.

   * The only acceptable syntax for relative imports is ‘from
     .[`module'] import `name'’.  All *note import: c25. forms not
     starting with ‘.’ are interpreted as absolute imports.  ( PEP
     328(2))

   * Classic classes are gone.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3113

   (2) https://www.python.org/dev/peps/pep-0328


File: python.info,  Node: Changes Already Present In Python 2 6,  Next: Library Changes,  Prev: Overview Of Syntax Changes,  Up: Python 3 0 有什么新变化

1.9.3 Changes Already Present In Python 2.6
-------------------------------------------

Since many users presumably make the jump straight from Python 2.5 to
Python 3.0, this section reminds the reader of new features that were
originally designed for Python 3.0 but that were back-ported to Python
2.6.  The corresponding sections in *note Python 2.6 有什么新变化: c4f.
should be consulted for longer descriptions.

   * *note PEP 343; "with" 语句: c50.  The *note with: 6f2. statement is
     now a standard feature and no longer needs to be imported from the
     *note __future__: 0.  Also check out *note Writing Context
     Managers: c51. and *note contextlib 模块: c52.

   * *note PEP 366; 从主模块显式相对导入: c53.  This enhances the
     usefulness of the *note -m: 340. option when the referenced module
     lives in a package.

   * *note PEP 370; 分用户的 site-packages 目录: c54.

   * *note PEP 371; 多任务处理包: c55.

   * *note PEP 3101; 高级字符串格式: c56.  Note: the 2.6 description
     mentions the *note format(): 4e3. method for both 8-bit and Unicode
     strings.  In 3.0, only the *note str: 339. type (text strings with
     Unicode support) supports this method; the *note bytes: 33a. type
     does not.  The plan is to eventually make this the only API for
     string formatting, and to start deprecating the ‘%’ operator in
     Python 3.1.

   * *note PEP 3105; print 改为函数: c57.  This is now a standard
     feature and no longer needs to be imported from *note __future__:
     0.  More details were given above.

   * *note PEP 3110; 异常处理的变更: c58.  The *note except: b46. `exc'
     ‘as’ `var' syntax is now standard and ‘except’ `exc', `var' is no
     longer supported.  (Of course, the ‘as’ `var' part is still
     optional.)

   * *note PEP 3112; 字节字面值: c59.  The ‘b"..."’ string literal
     notation (and its variants like ‘b'...'’, ‘b"""..."""’, and
     ‘br"..."’) now produces a literal of type *note bytes: 33a.

   * *note PEP 3116; 新 I/O 库: c5a.  The *note io: a2. module is now
     the standard way of doing file I/O. The built-in *note open(): 4f8.
     function is now an alias for *note io.open(): 663. and has
     additional keyword arguments `encoding', `errors', `newline' and
     `closefd'.  Also note that an invalid `mode' argument now raises
     *note ValueError: 1fc, not *note IOError: 99a.  The binary file
     object underlying a text file object can be accessed as ‘f.buffer’
     (but beware that the text object maintains a buffer of itself in
     order to speed up the encoding and decoding operations).

   * *note PEP 3118; 修改缓冲区协议: c5b.  The old builtin ‘buffer()’ is
     now really gone; the new builtin *note memoryview(): 25d. provides
     (mostly) similar functionality.

   * *note PEP 3119; 抽象基类: c5c.  The *note abc: 4. module and the
     ABCs defined in the *note collections: 1e. module plays a somewhat
     more prominent role in the language now, and built-in collection
     types like *note dict: 1b9. and *note list: 263. conform to the
     ‘collections.MutableMapping’ and ‘collections.MutableSequence’
     ABCs, respectively.

   * *note PEP 3127; 整型文字支持和语法: c5d.  As mentioned above, the
     new octal literal notation is the only one supported, and binary
     literals have been added.

   * *note PEP 3129; 类装饰器: c5e.

   * *note PEP 3141; A Type Hierarchy for Numbers: c5f.  The *note
     numbers: c2. module is another new use of ABCs, defining Python’s
     "numeric tower".  Also note the new *note fractions: 83. module
     which implements *note numbers.Rational: c60.


File: python.info,  Node: Library Changes,  Next: PEP 3101 A New Approach To String Formatting,  Prev: Changes Already Present In Python 2 6,  Up: Python 3 0 有什么新变化

1.9.4 Library Changes
---------------------

Due to time constraints, this document does not exhaustively cover the
very extensive changes to the standard library.  PEP 3108(1) is the
reference for the major changes to the library.  Here’s a capsule
review:

   * Many old modules were removed.  Some, like ‘gopherlib’ (no longer
     used) and ‘md5’ (replaced by *note hashlib: 8d.), were already
     deprecated by PEP 4(2).  Others were removed as a result of the
     removal of support for various platforms such as Irix, BeOS and Mac
     OS 9 (see PEP 11(3)).  Some modules were also selected for removal
     in Python 3.0 due to lack of use or because a better replacement
     exists.  See PEP 3108(4) for an exhaustive list.

   * The ‘bsddb3’ package was removed because its presence in the core
     standard library has proved over time to be a particular burden for
     the core developers due to testing instability and Berkeley DB’s
     release schedule.  However, the package is alive and well,
     externally maintained at
     ‘https://www.jcea.es/programacion/pybsddb.htm’.

   * Some modules were renamed because their old name disobeyed PEP
     8(5), or for various other reasons.  Here’s the list:

     旧名称                      新名称
                                 
     --------------------------------------------------------
                                 
     _winreg                     winreg
                                 
                                 
     ConfigParser                configparser
                                 
                                 
     copy_reg                    copyreg
                                 
                                 
     Queue                       queue
                                 
                                 
     SocketServer                socketserver
                                 
                                 
     markupbase                  _markupbase
                                 
                                 
     repr                        reprlib
                                 
                                 
     test.test_support           test.support
                                 

   * A common pattern in Python 2.x is to have one version of a module
     implemented in pure Python, with an optional accelerated version
     implemented as a C extension; for example, *note pickle: cb. and
     ‘cPickle’.  This places the burden of importing the accelerated
     version and falling back on the pure Python version on each user of
     these modules.  In Python 3.0, the accelerated versions are
     considered implementation details of the pure Python versions.
     Users should always import the standard version, which attempts to
     import the accelerated version and falls back to the pure Python
     version.  The *note pickle: cb. / ‘cPickle’ pair received this
     treatment.  The *note profile: d4. module is on the list for 3.1.
     The ‘StringIO’ module has been turned into a class in the *note io:
     a2. module.

   * Some related modules have been grouped into packages, and usually
     the submodule names have been simplified.  The resulting new
     packages are:

        * *note dbm: 32. (‘anydbm’, ‘dbhash’, *note dbm: 32, ‘dumbdbm’,
          ‘gdbm’, ‘whichdb’).

        * *note html: 90. (‘HTMLParser’, ‘htmlentitydefs’).

        * *note http: 93. (‘httplib’, ‘BaseHTTPServer’, ‘CGIHTTPServer’,
          ‘SimpleHTTPServer’, ‘Cookie’, ‘cookielib’).

        * *note tkinter: 10d. (all ‘Tkinter’-related modules except
          *note turtle: 117.).  The target audience of *note turtle:
          117. doesn’t really care about *note tkinter: 10d.  Also note
          that as of Python 2.6, the functionality of *note turtle: 117.
          has been greatly enhanced.

        * *note urllib: 11e. (*note urllib: 11e, ‘urllib2’, ‘urlparse’,
          ‘robotparse’).

        * ‘xmlrpc’ (‘xmlrpclib’, ‘DocXMLRPCServer’,
          ‘SimpleXMLRPCServer’).

Some other changes to standard library modules, not covered by PEP
3108(6):

   * Killed ‘sets’.  Use the built-in *note set(): b77. class.

   * Cleanup of the *note sys: fe. module: removed ‘sys.exitfunc()’,
     ‘sys.exc_clear()’, ‘sys.exc_type’, ‘sys.exc_value’,
     ‘sys.exc_traceback’.  (Note that *note sys.last_type: c62. etc.
     remain.)

   * Cleanup of the *note array.array: 459. type: the ‘read()’ and
     ‘write()’ methods are gone; use ‘fromfile()’ and ‘tofile()’
     instead.  Also, the ‘'c'’ typecode for array is gone – use either
     ‘'b'’ for bytes or ‘'u'’ for Unicode characters.

   * Cleanup of the *note operator: c3. module: removed
     ‘sequenceIncludes()’ and ‘isCallable()’.

   * Cleanup of the ‘thread’ module: ‘acquire_lock()’ and
     ‘release_lock()’ are gone; use ‘acquire()’ and ‘release()’ instead.

   * Cleanup of the *note random: dd. module: removed the ‘jumpahead()’
     API.

   * The ‘new’ module is gone.

   * The functions ‘os.tmpnam()’, ‘os.tempnam()’ and ‘os.tmpfile()’ have
     been removed in favor of the *note tempfile: 104. module.

   * The *note tokenize: 112. module has been changed to work with
     bytes.  The main entry point is now *note tokenize.tokenize(): c63,
     instead of generate_tokens.

   * ‘string.letters’ and its friends (‘string.lowercase’ and
     ‘string.uppercase’) are gone.  Use *note string.ascii_letters: c64.
     etc.  instead.  (The reason for the removal is that
     ‘string.letters’ and friends had locale-specific behavior, which is
     a bad idea for such attractively-named global "constants".)

   * Renamed module ‘__builtin__’ to *note builtins: 13. (removing the
     underscores, adding an ’s’).  The ‘__builtins__’ variable found in
     most global namespaces is unchanged.  To modify a builtin, you
     should use *note builtins: 13, not ‘__builtins__’!

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3108

   (2) https://www.python.org/dev/peps/pep-0004

   (3) https://www.python.org/dev/peps/pep-0011

   (4) https://www.python.org/dev/peps/pep-3108

   (5) https://www.python.org/dev/peps/pep-0008

   (6) https://www.python.org/dev/peps/pep-3108


File: python.info,  Node: PEP 3101 A New Approach To String Formatting,  Next: Changes To Exceptions,  Prev: Library Changes,  Up: Python 3 0 有什么新变化

1.9.5 `PEP 3101': A New Approach To String Formatting
-----------------------------------------------------

   * A new system for built-in string formatting operations replaces the
     ‘%’ string formatting operator.  (However, the ‘%’ operator is
     still supported; it will be deprecated in Python 3.1 and removed
     from the language at some later time.)  Read PEP 3101(1) for the
     full scoop.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3101


File: python.info,  Node: Changes To Exceptions,  Next: Miscellaneous Other Changes,  Prev: PEP 3101 A New Approach To String Formatting,  Up: Python 3 0 有什么新变化

1.9.6 Changes To Exceptions
---------------------------

The APIs for raising and catching exception have been cleaned up and new
powerful features added:

   * PEP 352(1): All exceptions must be derived (directly or indirectly)
     from *note BaseException: 1a9.  This is the root of the exception
     hierarchy.  This is not new as a recommendation, but the
     `requirement' to inherit from *note BaseException: 1a9. is new.
     (Python 2.6 still allowed classic classes to be raised, and placed
     no restriction on what you can catch.)  As a consequence, string
     exceptions are finally truly and utterly dead.

   * Almost all exceptions should actually derive from *note Exception:
     1aa.; *note BaseException: 1a9. should only be used as a base class
     for exceptions that should only be handled at the top level, such
     as *note SystemExit: 605. or *note KeyboardInterrupt: 198.  The
     recommended idiom for handling all exceptions except for this
     latter category is to use *note except: b46. *note Exception: 1aa.

   * ‘StandardError’ was removed.

   * Exceptions no longer behave as sequences.  Use the ‘args’ attribute
     instead.

   * PEP 3109(2): Raising exceptions.  You must now use ‘raise
     `Exception'(`args')’ instead of ‘raise `Exception', `args'’.
     Additionally, you can no longer explicitly specify a traceback;
     instead, if you `have' to do this, you can assign directly to the
     ‘__traceback__’ attribute (see below).

   * PEP 3110(3): Catching exceptions.  You must now use ‘except
     `SomeException' as `variable'’ instead of ‘except `SomeException',
     `variable'’.  Moreover, the `variable' is explicitly deleted when
     the *note except: b46. block is left.

   * PEP 3134(4): Exception chaining.  There are two cases: implicit
     chaining and explicit chaining.  Implicit chaining happens when an
     exception is raised in an *note except: b46. or *note finally: 183.
     handler block.  This usually happens due to a bug in the handler
     block; we call this a `secondary' exception.  In this case, the
     original exception (that was being handled) is saved as the
     ‘__context__’ attribute of the secondary exception.  Explicit
     chaining is invoked with this syntax:

          raise SecondaryException() from primary_exception

     (where `primary_exception' is any expression that produces an
     exception object, probably an exception that was previously
     caught).  In this case, the primary exception is stored on the
     ‘__cause__’ attribute of the secondary exception.  The traceback
     printed when an unhandled exception occurs walks the chain of
     ‘__cause__’ and ‘__context__’ attributes and prints a separate
     traceback for each component of the chain, with the primary
     exception at the top.  (Java users may recognize this behavior.)

   * PEP 3134(5): Exception objects now store their traceback as the
     ‘__traceback__’ attribute.  This means that an exception object now
     contains all the information pertaining to an exception, and there
     are fewer reasons to use *note sys.exc_info(): c67. (though the
     latter is not removed).

   * A few exception messages are improved when Windows fails to load an
     extension module.  For example, ‘error code 193’ is now ‘%1 is not
     a valid Win32 application’.  Strings now deal with non-English
     locales.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0352

   (2) https://www.python.org/dev/peps/pep-3109

   (3) https://www.python.org/dev/peps/pep-3110

   (4) https://www.python.org/dev/peps/pep-3134

   (5) https://www.python.org/dev/peps/pep-3134


File: python.info,  Node: Miscellaneous Other Changes,  Next: 构建和 C API 的改变<7>,  Prev: Changes To Exceptions,  Up: Python 3 0 有什么新变化

1.9.7 Miscellaneous Other Changes
---------------------------------

* Menu:

* Operators And Special Methods::
* Builtins::


File: python.info,  Node: Operators And Special Methods,  Next: Builtins,  Up: Miscellaneous Other Changes

1.9.7.1 Operators And Special Methods
.....................................

   * ‘!=’ now returns the opposite of ‘==’, unless ‘==’ returns *note
     NotImplemented: 855.

   * The concept of "unbound methods" has been removed from the
     language.  When referencing a method as a class attribute, you now
     get a plain function object.

   * ‘__getslice__()’, ‘__setslice__()’ and ‘__delslice__()’ were
     killed.  The syntax ‘a[i:j]’ now translates to
     ‘a.__getitem__(slice(i, j))’ (or *note __setitem__(): c6a. or *note
     __delitem__(): c6b, when used as an assignment or deletion target,
     respectively).

   * PEP 3114(1): the standard *note next(): 68b. method has been
     renamed to *note __next__(): c6c.

   * The ‘__oct__()’ and ‘__hex__()’ special methods are removed – *note
     oct(): c6d. and *note hex(): c6e. use *note __index__(): 18b. now
     to convert the argument to an integer.

   * Removed support for ‘__members__’ and ‘__methods__’.

   * The function attributes named ‘func_X’ have been renamed to use the
     ‘__X__’ form, freeing up these names in the function attribute
     namespace for user-defined attributes.  To wit, ‘func_closure’,
     ‘func_code’, ‘func_defaults’, ‘func_dict’, ‘func_doc’,
     ‘func_globals’, ‘func_name’ were renamed to ‘__closure__’,
     ‘__code__’, ‘__defaults__’, *note __dict__: 504, ‘__doc__’,
     ‘__globals__’, *note __name__: c6f, respectively.

   * ‘__nonzero__()’ is now *note __bool__(): c70.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3114


File: python.info,  Node: Builtins,  Prev: Operators And Special Methods,  Up: Miscellaneous Other Changes

1.9.7.2 Builtins
................

   * PEP 3135(1): New *note super(): 4eb.  You can now invoke *note
     super(): 4eb. without arguments and (assuming this is in a regular
     instance method defined inside a *note class: c72. statement) the
     right class and instance will automatically be chosen.  With
     arguments, the behavior of *note super(): 4eb. is unchanged.

   * PEP 3111(2): ‘raw_input()’ was renamed to *note input(): c73.  That
     is, the new *note input(): c73. function reads a line from *note
     sys.stdin: 316. and returns it with the trailing newline stripped.
     It raises *note EOFError: c74. if the input is terminated
     prematurely.  To get the old behavior of *note input(): c73, use
     ‘eval(input())’.

   * A new built-in function *note next(): 68b. was added to call the
     *note __next__(): c6c. method on an object.

   * The *note round(): c75. function rounding strategy and return type
     have changed.  Exact halfway cases are now rounded to the nearest
     even result instead of away from zero.  (For example, ‘round(2.5)’
     now returns ‘2’ rather than ‘3’.)  ‘round(x[, n])’ now delegates to
     ‘x.__round__([n])’ instead of always returning a float.  It
     generally returns an integer when called with a single argument and
     a value of the same type as ‘x’ when called with two arguments.

   * Moved ‘intern()’ to *note sys.intern(): c76.

   * Removed: ‘apply()’.  Instead of ‘apply(f, args)’ use ‘f(*args)’.

   * Removed *note callable(): b4c.  Instead of ‘callable(f)’ you can
     use ‘isinstance(f, collections.Callable)’.  The
     ‘operator.isCallable()’ function is also gone.

   * Removed ‘coerce()’.  This function no longer serves a purpose now
     that classic classes are gone.

   * Removed ‘execfile()’.  Instead of ‘execfile(fn)’ use
     ‘exec(open(fn).read())’.

   * Removed the ‘file’ type.  Use *note open(): 4f8.  There are now
     several different kinds of streams that open can return in the
     *note io: a2. module.

   * Removed ‘reduce()’.  Use *note functools.reduce(): c77. if you
     really need it; however, 99 percent of the time an explicit *note
     for: c38. loop is more readable.

   * Removed ‘reload()’.  Use *note imp.reload(): c78.

   * Removed.  ‘dict.has_key()’ – use the *note in: 7ac. operator
     instead.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3135

   (2) https://www.python.org/dev/peps/pep-3111


File: python.info,  Node: 构建和 C API 的改变<7>,  Next: 性能,  Prev: Miscellaneous Other Changes,  Up: Python 3 0 有什么新变化

1.9.8 构建和 C API 的改变
-------------------------

Due to time constraints, here is a `very' incomplete list of changes to
the C API.

   * Support for several platforms was dropped, including but not
     limited to Mac OS 9, BeOS, RISCOS, Irix, and Tru64.

   * PEP 3118(1): New Buffer API.

   * PEP 3121(2): Extension Module Initialization & Finalization.

   * PEP 3123(3): Making *note PyObject_HEAD: c7a. conform to standard
     C.

   * No more C API support for restricted execution.

   * ‘PyNumber_Coerce()’, ‘PyNumber_CoerceEx()’, ‘PyMember_Get()’, and
     ‘PyMember_Set()’ C APIs are removed.

   * New C API *note PyImport_ImportModuleNoBlock(): 9c9, works like
     *note PyImport_ImportModule(): c7b. but won’t block on the import
     lock (returning an error instead).

   * Renamed the boolean conversion C-level slot and method:
     ‘nb_nonzero’ is now ‘nb_bool’.

   * Removed ‘METH_OLDARGS’ and ‘WITH_CYCLE_GC’ from the C API.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3118

   (2) https://www.python.org/dev/peps/pep-3121

   (3) https://www.python.org/dev/peps/pep-3123


File: python.info,  Node: 性能,  Next: 移植到 Python 3 0,  Prev: 构建和 C API 的改变<7>,  Up: Python 3 0 有什么新变化

1.9.9 性能
----------

The net result of the 3.0 generalizations is that Python 3.0 runs the
pystone benchmark around 10% slower than Python 2.5.  Most likely the
biggest cause is the removal of special-casing for small integers.
There’s room for improvement, but it will happen after 3.0 is released!


File: python.info,  Node: 移植到 Python 3 0,  Prev: 性能,  Up: Python 3 0 有什么新变化

1.9.10 移植到 Python 3.0
------------------------

For porting existing Python 2.5 or 2.6 source code to Python 3.0, the
best strategy is the following:

  0. (Prerequisite:) Start with excellent test coverage.

  1. Port to Python 2.6.  This should be no more work than the average
     port from Python 2.x to Python 2.(x+1).  Make sure all your tests
     pass.

  2. (Still using 2.6:) Turn on the ‘-3’ command line switch.  This
     enables warnings about features that will be removed (or change) in
     3.0.  Run your test suite again, and fix code that you get warnings
     about until there are no warnings left, and all your tests still
     pass.

  3. Run the ‘2to3’ source-to-source translator over your source code
     tree.  (See *note 2to3 - 自动将 Python 2 代码转为 Python 3 代码:
     c7e. for more on this tool.)  Run the result of the translation
     under Python 3.0.  Manually fix up any remaining issues, fixing
     problems until all tests pass again.

It is not recommended to try to write source code that runs unchanged
under both Python 2.6 and 3.0; you’d have to use a very contorted coding
style, e.g.  avoiding ‘print’ statements, metaclasses, and much more.
If you are maintaining a library that needs to support both Python 2.6
and Python 3.0, the best approach is to modify step 3 above by editing
the 2.6 version of the source code and running the ‘2to3’ translator
again, rather than editing the 3.0 version of the source code.

For porting C extensions to Python 3.0, please see *note 将扩展模块移植到
Python 3: c7f.


File: python.info,  Node: Python 2 7 有什么新变化,  Next: Python 2 6 有什么新变化,  Prev: Python 3 0 有什么新变化,  Up: Python的新变化

1.10 Python 2.7 有什么新变化
============================


作者: A.M. Kuchling (amk at amk.ca)

本文介绍了Python 2.7 的新功能。 Python 2.7 于2010年7月3日发布。

Numeric handling has been improved in many ways, for both floating-point
numbers and for the *note Decimal: 189. class.  There are some useful
additions to the standard library, such as a greatly enhanced *note
unittest: 11c. module, the *note argparse: 6. module for parsing
command-line options, convenient *note OrderedDict: 1ba. and *note
Counter: 9e2. classes in the *note collections: 1e. module, and many
other improvements.

Python 2.7 is planned to be the last of the 2.x releases, so we worked
on making it a good release for the long term.  To help with porting to
Python 3, several new features from the Python 3.x series have been
included in 2.7.

This article doesn’t attempt to provide a complete specification of the
new features, but instead provides a convenient overview.  For full
details, you should refer to the documentation for Python 2.7 at
‘https://docs.python.org’.  If you want to understand the rationale for
the design and implementation, refer to the PEP for a particular new
feature or the issue on ‘https://bugs.python.org’ in which a change was
discussed.  Whenever possible, "What’s New in Python" links to the
bug/patch item for each change.

* Menu:

* Python 2.x的未来: Python 2 x的未来.
* Changes to the Handling of Deprecation Warnings::
* Python 3.1 Features: Python 3 1 Features.
* PEP 372; Adding an Ordered Dictionary to collections: PEP 372 Adding an Ordered Dictionary to collections.
* PEP 378; 千位分隔符的格式说明符: PEP 378 千位分隔符的格式说明符<2>.
* PEP 389; The argparse Module for Parsing Command Lines: PEP 389 The argparse Module for Parsing Command Lines.
* PEP 391; Dictionary-Based Configuration For Logging: PEP 391 Dictionary-Based Configuration For Logging.
* PEP 3106; Dictionary Views: PEP 3106 Dictionary Views.
* PEP 3137; The memoryview Object: PEP 3137 The memoryview Object.
* 其他语言特性修改: 其他语言特性修改<9>.
* 新增和改进的模块::
* 构建和 C API 的改变: 构建和 C API 的改变<8>.
* Other Changes and Fixes::
* 移植到 Python 2.7: 移植到 Python 2 7.
* New Features Added to Python 2.7 Maintenance Releases: New Features Added to Python 2 7 Maintenance Releases.
* 致谢::


File: python.info,  Node: Python 2 x的未来,  Next: Changes to the Handling of Deprecation Warnings,  Up: Python 2 7 有什么新变化

1.10.1 Python 2.x的未来
-----------------------

Python 2.7 是 2.x 系列中的最后一个主版本，因为Python 维护人员已将新功能
开发工作的重点转移到了 Python 3.x 系列中。这意味着，尽管 Python 2 会继续
修复bug并更新，以便在新的硬件和支持操作系统版本上正确构建，但不会有新的
功能发布。

然而，尽管在 Python 2.7 和 Python 3 之间有一个很大的公共子集，并且迁移到
该公共子集或直接迁移到 Python 3 所涉及的许多更改可以安全地自动化完成。但
是一些其他更改（特别是那些与Unicode处理相关的更改）可能需要仔细考虑，并
且最好用自动化回归测试套件进行健壮性测试，以便有效地迁移。

这意味着 Python2.7 将长期保留，为尚未移植到 Python 3 的生产系统提供一个
稳定且受支持的基础平台。Python 2.7系列的预期完整生命周期在 PEP 373(1) 中
有详细介绍。

长期保留 2.7 版的的一些关键后果：

   * 如上所述，与早期的2.x版本相比，2.7版本的维护时间更长。目前，预计核
     心开发团队将继续支持Python 2.7（接收安全更新和其他错误修复），直到
     至少2020年（首次发布后10年，相比之下，通常的支持期为18–24个月）。

   * 随着 Python 2.7 标准库的老化，有效地利用 Python 包索引（直接或通过
     重新分发者）对 Python 2 用户来说变得更加重要。除了各种任务的第三方
     包之外，可用的包还包括与 Python 2 兼容的 Python 3 标准库中的新模块
     和功能的后端移植，以及各种工具和库，这些工具和库可以让用户更容易迁
     移到 Python 3。 Python 包用户指南(2) 提供了从 Python 包索引的下载和
     安装软件的指导。

   * 虽然现在增强 Python 2 的首选方法是在Python包索引上发布新包，但这种
     方法不一定适用于所有情况，尤其是与网络安全相关的情况。在一些特殊情
     况下，如果在PyPI上发布新的或更新的包无法得到充分的处理，则可以使用
     Python增强建议过程来提出直接在Python 2标准库中添加新功能。任何此类
     添加及其添加的维护版本将在下面的 *note New Features Added to Python
     2.7 Maintenance Releases: c84. 部分中注明。

对于希望从 Python2 迁移到 Python3 的项目，或者对于希望同时支持 Python2 和
Python3 用户的库和框架开发人员，可以使用各种工具和指南来帮助决定合适的方
法并管理所涉及的一些技术细节。建议从 *note 将 Python 2 代码迁移到 Python
3: c85. 操作指南开始。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0373

   (2) https://packaging.python.org


File: python.info,  Node: Changes to the Handling of Deprecation Warnings,  Next: Python 3 1 Features,  Prev: Python 2 x的未来,  Up: Python 2 7 有什么新变化

1.10.2 Changes to the Handling of Deprecation Warnings
------------------------------------------------------

For Python 2.7, a policy decision was made to silence warnings only of
interest to developers by default.  *note DeprecationWarning: 279. and
its descendants are now ignored unless otherwise requested, preventing
users from seeing warnings triggered by an application.  This change was
also made in the branch that became Python 3.2.  (Discussed on
stdlib-sig and carried out in bpo-7319(1).)

In previous releases, *note DeprecationWarning: 279. messages were
enabled by default, providing Python developers with a clear indication
of where their code may break in a future major version of Python.

However, there are increasingly many users of Python-based applications
who are not directly involved in the development of those applications.
*note DeprecationWarning: 279. messages are irrelevant to such users,
making them worry about an application that’s actually working correctly
and burdening application developers with responding to these concerns.

You can re-enable display of *note DeprecationWarning: 279. messages by
running Python with the *note -Wdefault: 41f. (short form: *note -Wd:
41f.) switch, or by setting the *note PYTHONWARNINGS: 420. environment
variable to ‘"default"’ (or ‘"d"’) before running Python.  Python code
can also re-enable them by calling ‘warnings.simplefilter('default')’.

The ‘unittest’ module also automatically reenables deprecation warnings
when running tests.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7319


File: python.info,  Node: Python 3 1 Features,  Next: PEP 372 Adding an Ordered Dictionary to collections,  Prev: Changes to the Handling of Deprecation Warnings,  Up: Python 2 7 有什么新变化

1.10.3 Python 3.1 Features
--------------------------

就像 Python2.6 集成了 Python3.0 的特性一样，2.7版也集成了 Python3.1 中的
一些新特性。2.x 系列继续提供迁移到3.x系列的工具。

3.1 功能的部分列表，这些功能已反向移植到 2.7：

   * The syntax for set literals (‘{1,2,3}’ is a mutable set).

   * Dictionary and set comprehensions (‘{i: i*2 for i in range(3)}’).

   * Multiple context managers in a single *note with: 6f2. statement.

   * A new version of the *note io: a2. library, rewritten in C for
     performance.

   * The ordered-dictionary type described in *note PEP 372; Adding an
     Ordered Dictionary to collections: c88.

   * The new ‘","’ format specifier described in *note PEP 378;
     千位分隔符的格式说明符: c89.

   * The *note memoryview: 25d. object.

   * A small subset of the *note importlib: 9b. module, *note described
     below: c8a.

   * The *note repr(): 7d5. of a float ‘x’ is shorter in many cases:
     it’s now based on the shortest decimal string that’s guaranteed to
     round back to ‘x’.  As in previous versions of Python, it’s
     guaranteed that ‘float(repr(x))’ recovers ‘x’.

   * Float-to-string and string-to-float conversions are correctly
     rounded.  The *note round(): c75. function is also now correctly
     rounded.

   * The *note PyCapsule: c0f. type, used to provide a C API for
     extension modules.

   * The *note PyLong_AsLongAndOverflow(): c05. C API function.

Other new Python3-mode warnings include:

   * ‘operator.isCallable()’ and ‘operator.sequenceIncludes()’, which
     are not supported in 3.x, now trigger warnings.

   * The ‘-3’ switch now automatically enables the ‘-Qwarn’ switch that
     causes warnings about using classic division with integers and long
     integers.


File: python.info,  Node: PEP 372 Adding an Ordered Dictionary to collections,  Next: PEP 378 千位分隔符的格式说明符<2>,  Prev: Python 3 1 Features,  Up: Python 2 7 有什么新变化

1.10.4 PEP 372: Adding an Ordered Dictionary to collections
-----------------------------------------------------------

Regular Python dictionaries iterate over key/value pairs in arbitrary
order.  Over the years, a number of authors have written alternative
implementations that remember the order that the keys were originally
inserted.  Based on the experiences from those implementations, 2.7
introduces a new *note OrderedDict: 1ba. class in the *note collections:
1e. module.

The *note OrderedDict: 1ba. API provides the same interface as regular
dictionaries but iterates over keys and values in a guaranteed order
depending on when a key was first inserted:

     >>> from collections import OrderedDict
     >>> d = OrderedDict([('first', 1),
     ...                  ('second', 2),
     ...                  ('third', 3)])
     >>> d.items()
     [('first', 1), ('second', 2), ('third', 3)]

If a new entry overwrites an existing entry, the original insertion
position is left unchanged:

     >>> d['second'] = 4
     >>> d.items()
     [('first', 1), ('second', 4), ('third', 3)]

Deleting an entry and reinserting it will move it to the end:

     >>> del d['second']
     >>> d['second'] = 5
     >>> d.items()
     [('first', 1), ('third', 3), ('second', 5)]

The *note popitem(): c8c. method has an optional `last' argument that
defaults to ‘True’.  If `last' is true, the most recently added key is
returned and removed; if it’s false, the oldest key is selected:

     >>> od = OrderedDict([(x,0) for x in range(20)])
     >>> od.popitem()
     (19, 0)
     >>> od.popitem()
     (18, 0)
     >>> od.popitem(last=False)
     (0, 0)
     >>> od.popitem(last=False)
     (1, 0)

Comparing two ordered dictionaries checks both the keys and values, and
requires that the insertion order was the same:

     >>> od1 = OrderedDict([('first', 1),
     ...                    ('second', 2),
     ...                    ('third', 3)])
     >>> od2 = OrderedDict([('third', 3),
     ...                    ('first', 1),
     ...                    ('second', 2)])
     >>> od1 == od2
     False
     >>> # Move 'third' key to the end
     >>> del od2['third']; od2['third'] = 3
     >>> od1 == od2
     True

Comparing an *note OrderedDict: 1ba. with a regular dictionary ignores
the insertion order and just compares the keys and values.

How does the *note OrderedDict: 1ba. work?  It maintains a doubly-linked
list of keys, appending new keys to the list as they’re inserted.  A
secondary dictionary maps keys to their corresponding list node, so
deletion doesn’t have to traverse the entire linked list and therefore
remains O(1).

The standard library now supports use of ordered dictionaries in several
modules.

   * The ‘ConfigParser’ module uses them by default, meaning that
     configuration files can now be read, modified, and then written
     back in their original order.

   * The *note _asdict(): 1b8. method for *note
     collections.namedtuple(): 1b7. now returns an ordered dictionary
     with the values appearing in the same order as the underlying tuple
     indices.

   * The *note json: a5. module’s *note JSONDecoder: 610. class
     constructor was extended with an `object_pairs_hook' parameter to
     allow ‘OrderedDict’ instances to be built by the decoder.  Support
     was also added for third-party tools like PyYAML(1).

参见
....

PEP 372(2) - 将有序词典添加到集合中

     PEP 由 Armin Ronacher 和 Raymond Hettinger 撰写，由 Raymond
     Hettinger 实现。

   ---------- Footnotes ----------

   (1) http://pyyaml.org/

   (2) https://www.python.org/dev/peps/pep-0372


File: python.info,  Node: PEP 378 千位分隔符的格式说明符<2>,  Next: PEP 389 The argparse Module for Parsing Command Lines,  Prev: PEP 372 Adding an Ordered Dictionary to collections,  Up: Python 2 7 有什么新变化

1.10.5 PEP 378: 千位分隔符的格式说明符
--------------------------------------

To make program output more readable, it can be useful to add separators
to large numbers, rendering them as 18,446,744,073,709,551,616 instead
of 18446744073709551616.

The fully general solution for doing this is the *note locale: aa.
module, which can use different separators ("," in North America, "."
in Europe) and different grouping sizes, but *note locale: aa. is
complicated to use and unsuitable for multi-threaded applications where
different threads are producing output for different locales.

Therefore, a simple comma-grouping mechanism has been added to the
mini-language used by the *note str.format(): 4e2. method.  When
formatting a floating-point number, simply include a comma between the
width and the precision:

     >>> '{:20,.2f}'.format(18446744073709551616.0)
     '18,446,744,073,709,551,616.00'

When formatting an integer, include the comma after the width:

     >>> '{:20,d}'.format(18446744073709551616)
     '18,446,744,073,709,551,616'

This mechanism is not adaptable at all; commas are always used as the
separator and the grouping is always into three-digit groups.  The
comma-formatting mechanism isn’t as general as the *note locale: aa.
module, but it’s easier to use.

参见
....

PEP 378(1) - 千位分隔符的格式说明符

     PEP 由 Raymond Hettinger 撰写，由 Eric Smith 实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0378


File: python.info,  Node: PEP 389 The argparse Module for Parsing Command Lines,  Next: PEP 391 Dictionary-Based Configuration For Logging,  Prev: PEP 378 千位分隔符的格式说明符<2>,  Up: Python 2 7 有什么新变化

1.10.6 PEP 389: The argparse Module for Parsing Command Lines
-------------------------------------------------------------

The *note argparse: 6. module for parsing command-line arguments was
added as a more powerful replacement for the *note optparse: c4. module.

This means Python now supports three different modules for parsing
command-line arguments: *note getopt: 87, *note optparse: c4, and *note
argparse: 6.  The *note getopt: 87. module closely resembles the C
library’s ‘getopt()’ function, so it remains useful if you’re writing a
Python prototype that will eventually be rewritten in C. *note optparse:
c4. becomes redundant, but there are no plans to remove it because there
are many scripts still using it, and there’s no automated way to update
these scripts.  (Making the *note argparse: 6. API consistent with *note
optparse: c4.’s interface was discussed but rejected as too messy and
difficult.)

In short, if you’re writing a new script and don’t need to worry about
compatibility with earlier versions of Python, use *note argparse: 6.
instead of *note optparse: c4.

以下是为示例代码:

     import argparse

     parser = argparse.ArgumentParser(description='Command-line example.')

     # Add optional switches
     parser.add_argument('-v', action='store_true', dest='is_verbose',
                         help='produce verbose output')
     parser.add_argument('-o', action='store', dest='output',
                         metavar='FILE',
                         help='direct output to FILE instead of stdout')
     parser.add_argument('-C', action='store', type=int, dest='context',
                         metavar='NUM', default=0,
                         help='display NUM lines of added context')

     # Allow any number of additional arguments.
     parser.add_argument(nargs='*', action='store', dest='inputs',
                         help='input filenames (default is stdin)')

     args = parser.parse_args()
     print args.__dict__

Unless you override it, ‘-h’ and ‘--help’ switches are automatically
added, and produce neatly formatted output:

     -> ./python.exe argparse-example.py --help
     usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]

     Command-line example.

     positional arguments:
       inputs      input filenames (default is stdin)

     optional arguments:
       -h, --help  show this help message and exit
       -v          produce verbose output
       -o FILE     direct output to FILE instead of stdout
       -C NUM      display NUM lines of added context

As with *note optparse: c4, the command-line switches and arguments are
returned as an object with attributes named by the `dest' parameters:

     -> ./python.exe argparse-example.py -v
     {'output': None,
      'is_verbose': True,
      'context': 0,
      'inputs': []}

     -> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
     {'output': '/tmp/output',
      'is_verbose': True,
      'context': 4,
      'inputs': ['file1', 'file2']}

*note argparse: 6. has much fancier validation than *note optparse: c4.;
you can specify an exact number of arguments as an integer, 0 or more
arguments by passing ‘'*'’, 1 or more by passing ‘'+'’, or an optional
argument with ‘'?'’.  A top-level parser can contain sub-parsers to
define subcommands that have different sets of switches, as in ‘svn
commit’, ‘svn checkout’, etc.  You can specify an argument’s type as
*note FileType: 829, which will automatically open files for you and
understands that ‘'-'’ means standard input or output.

参见
....

*note argparse: 6. documentation

     argparse 模块的文档页面。

*note 升级 optparse 代码: b31.

     Part of the Python documentation, describing how to convert code
     that uses *note optparse: c4.

PEP 389(1) - argparse - 新的命令行解析模块

     PEP 由 Steven Bethard 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0389


File: python.info,  Node: PEP 391 Dictionary-Based Configuration For Logging,  Next: PEP 3106 Dictionary Views,  Prev: PEP 389 The argparse Module for Parsing Command Lines,  Up: Python 2 7 有什么新变化

1.10.7 PEP 391: Dictionary-Based Configuration For Logging
----------------------------------------------------------

The *note logging: ab. module is very flexible; applications can define
a tree of logging subsystems, and each logger in this tree can filter
out certain messages, format them differently, and direct messages to a
varying number of handlers.

All this flexibility can require a lot of configuration.  You can write
Python statements to create objects and set their properties, but a
complex set-up requires verbose but boring code.  *note logging: ab.
also supports a ‘fileConfig()’ function that parses a file, but the file
format doesn’t support configuring filters, and it’s messier to generate
programmatically.

Python 2.7 adds a ‘dictConfig()’ function that uses a dictionary to
configure logging.  There are many ways to produce a dictionary from
different sources: construct one with code; parse a file containing
JSON; or use a YAML parsing library if one is installed.  For more
information see *note 配置函数: c90.

The following example configures two loggers, the root logger and a
logger named "network".  Messages sent to the root logger will be sent
to the system log using the syslog protocol, and messages to the
"network" logger will be written to a ‘network.log’ file that will be
rotated once the log reaches 1MB.

     import logging
     import logging.config

     configdict = {
      'version': 1,    # Configuration schema in use; must be 1 for now
      'formatters': {
          'standard': {
              'format': ('%(asctime)s %(name)-15s '
                         '%(levelname)-8s %(message)s')}},

      'handlers': {'netlog': {'backupCount': 10,
                          'class': 'logging.handlers.RotatingFileHandler',
                          'filename': '/logs/network.log',
                          'formatter': 'standard',
                          'level': 'INFO',
                          'maxBytes': 1000000},
                   'syslog': {'class': 'logging.handlers.SysLogHandler',
                              'formatter': 'standard',
                              'level': 'ERROR'}},

      # Specify all the subordinate loggers
      'loggers': {
                  'network': {
                              'handlers': ['netlog']
                  }
      },
      # Specify properties of the root logger
      'root': {
               'handlers': ['syslog']
      },
     }

     # Set up configuration
     logging.config.dictConfig(configdict)

     # As an example, log two error messages
     logger = logging.getLogger('/')
     logger.error('Database not found')

     netlogger = logging.getLogger('network')
     netlogger.error('Connection failed')

Three smaller enhancements to the *note logging: ab. module, all
implemented by Vinay Sajip, are:

   * The *note SysLogHandler: a26. class now supports syslogging over
     TCP. The constructor has a `socktype' parameter giving the type of
     socket to use, either *note socket.SOCK_DGRAM: c91. for UDP or
     *note socket.SOCK_STREAM: c92. for TCP. The default protocol
     remains UDP.

   * *note Logger: 3af. instances gained a *note getChild(): c93. method
     that retrieves a descendant logger using a relative path.  For
     example, once you retrieve a logger by doing ‘log =
     getLogger('app')’, calling ‘log.getChild('network.listen')’ is
     equivalent to ‘getLogger('app.network.listen')’.

   * The *note LoggerAdapter: c94. class gained an ‘isEnabledFor()’
     method that takes a `level' and returns whether the underlying
     logger would process a message of that level of importance.

参见
....

PEP 391(1) - 基于字典的日志配置

     PEP 由 Vinay Sajip 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0391


File: python.info,  Node: PEP 3106 Dictionary Views,  Next: PEP 3137 The memoryview Object,  Prev: PEP 391 Dictionary-Based Configuration For Logging,  Up: Python 2 7 有什么新变化

1.10.8 PEP 3106: Dictionary Views
---------------------------------

The dictionary methods *note keys(): c32, *note values(): c34, and *note
items(): c33. are different in Python 3.x.  They return an object called
a `view' instead of a fully materialized list.

It’s not possible to change the return values of *note keys(): c32,
*note values(): c34, and *note items(): c33. in Python 2.7 because too
much code would break.  Instead the 3.x versions were added under the
new names ‘viewkeys()’, ‘viewvalues()’, and ‘viewitems()’.

     >>> d = dict((i*10, chr(65+i)) for i in range(26))
     >>> d
     {0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'}
     >>> d.viewkeys()
     dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])

Views can be iterated over, but the key and item views also behave like
sets.  The ‘&’ operator performs intersection, and ‘|’ performs a union:

     >>> d1 = dict((i*10, chr(65+i)) for i in range(26))
     >>> d2 = dict((i**.5, i) for i in range(1000))
     >>> d1.viewkeys() & d2.viewkeys()
     set([0.0, 10.0, 20.0, 30.0])
     >>> d1.viewkeys() | range(0, 30)
     set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])

The view keeps track of the dictionary and its contents change as the
dictionary is modified:

     >>> vk = d.viewkeys()
     >>> vk
     dict_keys([0, 130, 10, ..., 250])
     >>> d[260] = '&'
     >>> vk
     dict_keys([0, 130, 260, 10, ..., 250])

However, note that you can’t add or remove keys while you’re iterating
over the view:

     >>> for k in vk:
     ...     d[k*2] = k
     ...
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     RuntimeError: dictionary changed size during iteration

You can use the view methods in Python 2.x code, and the 2to3 converter
will change them to the standard *note keys(): c32, *note values(): c34,
and *note items(): c33. methods.

参见
....

PEP 3106(1) - 改造 dict.keys(), .values() 和 .items()

     PEP written by Guido van Rossum.  Backported to 2.7 by Alexandre
     Vassalotti; bpo-1967(2).

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3106

   (2) https://bugs.python.org/issue1967


File: python.info,  Node: PEP 3137 The memoryview Object,  Next: 其他语言特性修改<9>,  Prev: PEP 3106 Dictionary Views,  Up: Python 2 7 有什么新变化

1.10.9 PEP 3137: The memoryview Object
--------------------------------------

The *note memoryview: 25d. object provides a view of another object’s
memory content that matches the *note bytes: 33a. type’s interface.

     >>> import string
     >>> m = memoryview(string.letters)
     >>> m
     <memory at 0x37f850>
     >>> len(m)           # Returns length of underlying object
     52
     >>> m[0], m[25], m[26]   # Indexing returns one byte
     ('a', 'z', 'A')
     >>> m2 = m[0:26]         # Slicing returns another memoryview
     >>> m2
     <memory at 0x37f080>

The content of the view can be converted to a string of bytes or a list
of integers:

     >>> m2.tobytes()
     'abcdefghijklmnopqrstuvwxyz'
     >>> m2.tolist()
     [97, 98, 99, 100, 101, 102, 103, ... 121, 122]
     >>>

*note memoryview: 25d. objects allow modifying the underlying object if
it’s a mutable object.

     >>> m2[0] = 75
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: cannot modify read-only memory
     >>> b = bytearray(string.letters)  # Creating a mutable object
     >>> b
     bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
     >>> mb = memoryview(b)
     >>> mb[0] = '*'         # Assign to view, changing the bytearray.
     >>> b[0:5]              # The bytearray has been changed.
     bytearray(b'*bcde')
     >>>

参见
....

PEP 3137(1) - 不变字节和可变缓冲区

     PEP written by Guido van Rossum.  Implemented by Travis Oliphant,
     Antoine Pitrou and others.  Backported to 2.7 by Antoine Pitrou;
     bpo-2396(2).

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3137

   (2) https://bugs.python.org/issue2396


File: python.info,  Node: 其他语言特性修改<9>,  Next: 新增和改进的模块,  Prev: PEP 3137 The memoryview Object,  Up: Python 2 7 有什么新变化

1.10.10 其他语言特性修改
------------------------

对Python 语言核心进行的小改动：

   * The syntax for set literals has been backported from Python 3.x.
     Curly brackets are used to surround the contents of the resulting
     mutable set; set literals are distinguished from dictionaries by
     not containing colons and values.  ‘{}’ continues to represent an
     empty dictionary; use ‘set()’ for an empty set.

          >>> {1, 2, 3, 4, 5}
          set([1, 2, 3, 4, 5])
          >>> set() # empty set
          set([])
          >>> {}    # empty dict
          {}

     Backported by Alexandre Vassalotti; bpo-2335(1).

   * Dictionary and set comprehensions are another feature backported
     from 3.x, generalizing list/generator comprehensions to use the
     literal syntax for sets and dictionaries.

          >>> {x: x*x for x in range(6)}
          {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
          >>> {('a'*x) for x in range(6)}
          set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])

     Backported by Alexandre Vassalotti; bpo-2333(2).

   * The *note with: 6f2. statement can now use multiple context
     managers in one statement.  Context managers are processed from
     left to right and each one is treated as beginning a new ‘with’
     statement.  This means that:

          with A() as a, B() as b:
              ... suite of statements ...

     相当于:

          with A() as a:
              with B() as b:
                  ... suite of statements ...

     The ‘contextlib.nested()’ function provides a very similar
     function, so it’s no longer necessary and has been deprecated.

     (Proposed in ‘https://codereview.appspot.com/53094’; implemented by
     Georg Brandl.)

   * Conversions between floating-point numbers and strings are now
     correctly rounded on most platforms.  These conversions occur in
     many different places: *note str(): 339. on floats and complex
     numbers; the *note float: 188. and *note complex: 18a.
     constructors; numeric formatting; serializing and deserializing
     floats and complex numbers using the *note marshal: b1, *note
     pickle: cb. and *note json: a5. modules; parsing of float and
     imaginary literals in Python code; and *note Decimal: 189.-to-float
     conversion.

     Related to this, the *note repr(): 7d5. of a floating-point number
     `x' now returns a result based on the shortest decimal string
     that’s guaranteed to round back to `x' under correct rounding (with
     round-half-to-even rounding mode).  Previously it gave a string
     based on rounding x to 17 decimal digits.

     The rounding library responsible for this improvement works on
     Windows and on Unix platforms using the gcc, icc, or suncc
     compilers.  There may be a small number of platforms where correct
     operation of this code cannot be guaranteed, so the code is not
     used on such systems.  You can find out which code is being used by
     checking *note sys.float_repr_style: c98, which will be ‘short’ if
     the new code is in use and ‘legacy’ if it isn’t.

     Implemented by Eric Smith and Mark Dickinson, using David Gay’s
     ‘dtoa.c’ library; bpo-7117(3).

   * Conversions from long integers and regular integers to floating
     point now round differently, returning the floating-point number
     closest to the number.  This doesn’t matter for small integers that
     can be converted exactly, but for large numbers that will
     unavoidably lose precision, Python 2.7 now approximates more
     closely.  For example, Python 2.6 computed the following:

          >>> n = 295147905179352891391
          >>> float(n)
          2.9514790517935283e+20
          >>> n - long(float(n))
          65535L

     Python 2.7’s floating-point result is larger, but much closer to
     the true value:

          >>> n = 295147905179352891391
          >>> float(n)
          2.9514790517935289e+20
          >>> n - long(float(n))
          -1L

     (Implemented by Mark Dickinson; bpo-3166(4).)

     Integer division is also more accurate in its rounding behaviours.
     (Also implemented by Mark Dickinson; bpo-1811(5).)

   * Implicit coercion for complex numbers has been removed; the
     interpreter will no longer ever attempt to call a ‘__coerce__()’
     method on complex objects.  (Removed by Meador Inge and Mark
     Dickinson; bpo-5211(6).)

   * The *note str.format(): 4e2. method now supports automatic
     numbering of the replacement fields.  This makes using *note
     str.format(): 4e2. more closely resemble using ‘%s’ formatting:

          >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
          '2009:4:Sunday'
          >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
          '2009:4:Sunday'

     The auto-numbering takes the fields from left to right, so the
     first ‘{...}’ specifier will use the first argument to *note
     str.format(): 4e2, the next specifier will use the next argument,
     and so on.  You can’t mix auto-numbering and explicit numbering –
     either number all of your specifier fields or none of them – but
     you can mix auto-numbering and named fields, as in the second
     example above.  (Contributed by Eric Smith; bpo-5237(7).)

     Complex numbers now correctly support usage with *note format():
     4e3, and default to being right-aligned.  Specifying a precision or
     comma-separation applies to both the real and imaginary parts of
     the number, but a specified field width and alignment is applied to
     the whole of the resulting ‘1.5+3j’ output.  (Contributed by Eric
     Smith; bpo-1588(8) and bpo-7988(9).)

     The ’F’ format code now always formats its output using uppercase
     characters, so it will now produce ’INF’ and ’NAN’.  (Contributed
     by Eric Smith; bpo-3382(10).)

     A low-level change: the *note object.__format__(): 956. method now
     triggers a *note PendingDeprecationWarning: 27a. if it’s passed a
     format string, because the *note __format__(): 956. method for
     *note object: 2b1. converts the object to a string representation
     and formats that.  Previously the method silently applied the
     format string to the string representation, but that could hide
     mistakes in Python code.  If you’re supplying formatting
     information such as an alignment or precision, presumably you’re
     expecting the formatting to be applied in some object-specific way.
     (Fixed by Eric Smith; bpo-7994(11).)

   * The *note int(): 185. and ‘long()’ types gained a ‘bit_length’
     method that returns the number of bits necessary to represent its
     argument in binary:

          >>> n = 37
          >>> bin(n)
          '0b100101'
          >>> n.bit_length()
          6
          >>> n = 2**123-1
          >>> n.bit_length()
          123
          >>> (n+1).bit_length()
          124

     (Contributed by Fredrik Johansson and Victor Stinner;
     bpo-3439(12).)

   * The *note import: c25. statement will no longer try an absolute
     import if a relative import (e.g.  ‘from .os import sep’) fails.
     This fixes a bug, but could possibly break certain ‘import’
     statements that were only working by accident.  (Fixed by Meador
     Inge; bpo-7902(13).)

   * It’s now possible for a subclass of the built-in ‘unicode’ type to
     override the ‘__unicode__()’ method.  (Implemented by Victor
     Stinner; bpo-1583863(14).)

   * The *note bytearray: 33b. type’s *note translate(): c99. method now
     accepts ‘None’ as its first argument.  (Fixed by Georg Brandl;
     bpo-4759(15).)

   * When using ‘@classmethod’ and ‘@staticmethod’ to wrap methods as
     class or static methods, the wrapper object now exposes the wrapped
     function as their ‘__func__’ attribute.  (Contributed by Amaury
     Forgeot d’Arc, after a suggestion by George Sakkis; bpo-5982(16).)

   * When a restricted set of attributes were set using ‘__slots__’,
     deleting an unset attribute would not raise *note AttributeError:
     3a3. as you would expect.  Fixed by Benjamin Peterson;
     bpo-7604(17).)

   * Two new encodings are now supported: "cp720", used primarily for
     Arabic text; and "cp858", a variant of CP 850 that adds the euro
     symbol.  (CP720 contributed by Alexander Belchenko and Amaury
     Forgeot d’Arc in bpo-1616979(18); CP858 contributed by Tim Hatch in
     bpo-8016(19).)

   * The ‘file’ object will now set the ‘filename’ attribute on the
     *note IOError: 99a. exception when trying to open a directory on
     POSIX platforms (noted by Jan Kaliszewski; bpo-4764(20)), and now
     explicitly checks for and forbids writing to read-only file objects
     instead of trusting the C library to catch and report the error
     (fixed by Stefan Krah; bpo-5677(21)).

   * The Python tokenizer now translates line endings itself, so the
     *note compile(): 1b5. built-in function now accepts code using any
     line-ending convention.  Additionally, it no longer requires that
     the code end in a newline.

   * Extra parentheses in function definitions are illegal in Python
     3.x, meaning that you get a syntax error from ‘def f((x)): pass’.
     In Python3-warning mode, Python 2.7 will now warn about this odd
     usage.  (Noted by James Lingard; bpo-7362(22).)

   * It’s now possible to create weak references to old-style class
     objects.  New-style classes were always weak-referenceable.  (Fixed
     by Antoine Pitrou; bpo-8268(23).)

   * When a module object is garbage-collected, the module’s dictionary
     is now only cleared if no one else is holding a reference to the
     dictionary (bpo-7140(24)).

* Menu:

* Interpreter Changes::
* 性能优化: 性能优化<8>.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2335

   (2) https://bugs.python.org/issue2333

   (3) https://bugs.python.org/issue7117

   (4) https://bugs.python.org/issue3166

   (5) https://bugs.python.org/issue1811

   (6) https://bugs.python.org/issue5211

   (7) https://bugs.python.org/issue5237

   (8) https://bugs.python.org/issue1588

   (9) https://bugs.python.org/issue7988

   (10) https://bugs.python.org/issue3382

   (11) https://bugs.python.org/issue7994

   (12) https://bugs.python.org/issue3439

   (13) https://bugs.python.org/issue7902

   (14) https://bugs.python.org/issue1583863

   (15) https://bugs.python.org/issue4759

   (16) https://bugs.python.org/issue5982

   (17) https://bugs.python.org/issue7604

   (18) https://bugs.python.org/issue1616979

   (19) https://bugs.python.org/issue8016

   (20) https://bugs.python.org/issue4764

   (21) https://bugs.python.org/issue5677

   (22) https://bugs.python.org/issue7362

   (23) https://bugs.python.org/issue8268

   (24) https://bugs.python.org/issue7140


File: python.info,  Node: Interpreter Changes,  Next: 性能优化<8>,  Up: 其他语言特性修改<9>

1.10.10.1 Interpreter Changes
.............................

A new environment variable, *note PYTHONWARNINGS: 420, allows
controlling warnings.  It should be set to a string containing warning
settings, equivalent to those used with the *note -W: 41f. switch,
separated by commas.  (Contributed by Brian Curtin; bpo-7301(1).)

For example, the following setting will print warnings every time they
occur, but turn warnings from the ‘Cookie’ module into an error.  (The
exact syntax for setting an environment variable varies across operating
systems and shells.)

     export PYTHONWARNINGS=all,error:::Cookie:0

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7301


File: python.info,  Node: 性能优化<8>,  Prev: Interpreter Changes,  Up: 其他语言特性修改<9>

1.10.10.2 性能优化
..................

Several performance enhancements have been added:

   * A new opcode was added to perform the initial setup for *note with:
     6f2. statements, looking up the *note __enter__(): c9d. and *note
     __exit__(): c9e. methods.  (Contributed by Benjamin Peterson.)

   * The garbage collector now performs better for one common usage
     pattern: when many objects are being allocated without deallocating
     any of them.  This would previously take quadratic time for garbage
     collection, but now the number of full garbage collections is
     reduced as the number of objects on the heap grows.  The new logic
     only performs a full garbage collection pass when the middle
     generation has been collected 10 times and when the number of
     survivor objects from the middle generation exceeds 10% of the
     number of objects in the oldest generation.  (Suggested by Martin
     von Löwis and implemented by Antoine Pitrou; bpo-4074(1).)

   * The garbage collector tries to avoid tracking simple containers
     which can’t be part of a cycle.  In Python 2.7, this is now true
     for tuples and dicts containing atomic types (such as ints,
     strings, etc.).  Transitively, a dict containing tuples of atomic
     types won’t be tracked either.  This helps reduce the cost of each
     garbage collection by decreasing the number of objects to be
     considered and traversed by the collector.  (Contributed by Antoine
     Pitrou; bpo-4688(2).)

   * Long integers are now stored internally either in base 2**15 or in
     base 2**30, the base being determined at build time.  Previously,
     they were always stored in base 2**15.  Using base 2**30 gives
     significant performance improvements on 64-bit machines, but
     benchmark results on 32-bit machines have been mixed.  Therefore,
     the default is to use base 2**30 on 64-bit machines and base 2**15
     on 32-bit machines; on Unix, there’s a new configure option
     ‘--enable-big-digits’ that can be used to override this default.

     Apart from the performance improvements this change should be
     invisible to end users, with one exception: for testing and
     debugging purposes there’s a new structseq ‘sys.long_info’ that
     provides information about the internal format, giving the number
     of bits per digit and the size in bytes of the C type used to store
     each digit:

          >>> import sys
          >>> sys.long_info
          sys.long_info(bits_per_digit=30, sizeof_digit=4)

     （由 Mark Dickinson在 bpo-4258(3) 贡献）

     Another set of changes made long objects a few bytes smaller: 2
     bytes smaller on 32-bit systems and 6 bytes on 64-bit.
     (Contributed by Mark Dickinson; bpo-5260(4).)

   * The division algorithm for long integers has been made faster by
     tightening the inner loop, doing shifts instead of multiplications,
     and fixing an unnecessary extra iteration.  Various benchmarks show
     speedups of between 50% and 150% for long integer divisions and
     modulo operations.  (Contributed by Mark Dickinson; bpo-5512(5).)
     Bitwise operations are also significantly faster (initial patch by
     Gregory Smith; bpo-1087418(6)).

   * The implementation of ‘%’ checks for the left-side operand being a
     Python string and special-cases it; this results in a 1–3%
     performance increase for applications that frequently use ‘%’ with
     strings, such as templating libraries.  (Implemented by Collin
     Winter; bpo-5176(7).)

   * List comprehensions with an ‘if’ condition are compiled into faster
     bytecode.  (Patch by Antoine Pitrou, back-ported to 2.7 by Jeffrey
     Yasskin; bpo-4715(8).)

   * Converting an integer or long integer to a decimal string was made
     faster by special-casing base 10 instead of using a generalized
     conversion function that supports arbitrary bases.  (Patch by
     Gawain Bolton; bpo-6713(9).)

   * The ‘split()’, ‘replace()’, ‘rindex()’, ‘rpartition()’, and
     ‘rsplit()’ methods of string-like types (strings, Unicode strings,
     and *note bytearray: 33b. objects) now use a fast reverse-search
     algorithm instead of a character-by-character scan.  This is
     sometimes faster by a factor of 10.  (Added by Florent Xicluna;
     bpo-7462(10) and bpo-7622(11).)

   * The *note pickle: cb. and ‘cPickle’ modules now automatically
     intern the strings used for attribute names, reducing memory usage
     of the objects resulting from unpickling.  (Contributed by Jake
     McGuire; bpo-5084(12).)

   * The ‘cPickle’ module now special-cases dictionaries, nearly halving
     the time required to pickle them.  (Contributed by Collin Winter;
     bpo-5670(13).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4074

   (2) https://bugs.python.org/issue4688

   (3) https://bugs.python.org/issue4258

   (4) https://bugs.python.org/issue5260

   (5) https://bugs.python.org/issue5512

   (6) https://bugs.python.org/issue1087418

   (7) https://bugs.python.org/issue5176

   (8) https://bugs.python.org/issue4715

   (9) https://bugs.python.org/issue6713

   (10) https://bugs.python.org/issue7462

   (11) https://bugs.python.org/issue7622

   (12) https://bugs.python.org/issue5084

   (13) https://bugs.python.org/issue5670


File: python.info,  Node: 新增和改进的模块,  Next: 构建和 C API 的改变<8>,  Prev: 其他语言特性修改<9>,  Up: Python 2 7 有什么新变化

1.10.11 新增和改进的模块
------------------------

As in every release, Python’s standard library received a number of
enhancements and bug fixes.  Here’s a partial list of the most notable
changes, sorted alphabetically by module name.  Consult the ‘Misc/NEWS’
file in the source tree for a more complete list of changes, or look
through the Subversion logs for all the details.

   * The *note bdb: f. module’s base debugging class *note Bdb: ca0.
     gained a feature for skipping modules.  The constructor now takes
     an iterable containing glob-style patterns such as ‘django.*’; the
     debugger will not step into stack frames from a module that matches
     one of these patterns.  (Contributed by Maru Newby after a
     suggestion by Senthil Kumaran; bpo-5142(1).)

   * The *note binascii: 10. module now supports the buffer API, so it
     can be used with *note memoryview: 25d. instances and other similar
     buffer objects.  (Backported from 3.x by Florent Xicluna;
     bpo-7703(2).)

   * Updated module: the ‘bsddb’ module has been updated from
     4.7.2devel9 to version 4.8.4 of the pybsddb package(3).  The new
     version features better Python 3.x compatibility, various bug
     fixes, and adds several new BerkeleyDB flags and methods.  (Updated
     by Jesús Cea Avión; bpo-8156(4).  The pybsddb changelog can be read
     at ‘http://hg.jcea.es/pybsddb/file/tip/ChangeLog’.)

   * The *note bz2: 14. module’s *note BZ2File: 939. now supports the
     context management protocol, so you can write ‘with
     bz2.BZ2File(...) as f:’.  (Contributed by Hagen Fürstenau;
     bpo-3860(5).)

   * New class: the *note Counter: 9e2. class in the *note collections:
     1e. module is useful for tallying data.  *note Counter: 9e2.
     instances behave mostly like dictionaries but return zero for
     missing keys instead of raising a *note KeyError: 2c8.:

          >>> from collections import Counter
          >>> c = Counter()
          >>> for letter in 'here is a sample of english text':
          ...   c[letter] += 1
          ...
          >>> c
          Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
          'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
          'p': 1, 'r': 1, 'x': 1})
          >>> c['e']
          5
          >>> c['z']
          0

     There are three additional *note Counter: 9e2. methods.  *note
     most_common(): ca1. returns the N most common elements and their
     counts.  *note elements(): ca2. returns an iterator over the
     contained elements, repeating each element as many times as its
     count.  *note subtract(): b62. takes an iterable and subtracts one
     for each element instead of adding; if the argument is a dictionary
     or another ‘Counter’, the counts are subtracted.

          >>> c.most_common(5)
          [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
          >>> c.elements() ->
             'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
             'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
             'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
             's', 's', 'r', 't', 't', 'x'
          >>> c['e']
          5
          >>> c.subtract('very heavy on the letter e')
          >>> c['e']    # Count is now lower
          -1

     Contributed by Raymond Hettinger; bpo-1696199(6).

     New class: *note OrderedDict: 1ba. is described in the earlier
     section *note PEP 372; Adding an Ordered Dictionary to collections:
     c88.

     New method: The *note deque: 539. data type now has a *note
     count(): b64. method that returns the number of contained elements
     equal to the supplied argument `x', and a *note reverse(): b65.
     method that reverses the elements of the deque in-place.  *note
     deque: 539. also exposes its maximum length as the read-only *note
     maxlen: ca3. attribute.  (Both features added by Raymond
     Hettinger.)

     The *note namedtuple: 1b7. class now has an optional `rename'
     parameter.  If `rename' is true, field names that are invalid
     because they’ve been repeated or aren’t legal Python identifiers
     will be renamed to legal names that are derived from the field’s
     position within the list of fields:

          >>> from collections import namedtuple
          >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
          >>> T._fields
          ('field1', '_1', '_2', 'field2')

     (Added by Raymond Hettinger; bpo-1818(7).)

     Finally, the ‘Mapping’ abstract base class now returns *note
     NotImplemented: 855. if a mapping is compared to another type that
     isn’t a ‘Mapping’.  (Fixed by Daniel Stutzbach; bpo-8729(8).)

   * Constructors for the parsing classes in the ‘ConfigParser’ module
     now take an `allow_no_value' parameter, defaulting to false; if
     true, options without values will be allowed.  For example:

          >>> import ConfigParser, StringIO
          >>> sample_config = """
          ... [mysqld]
          ... user = mysql
          ... pid-file = /var/run/mysqld/mysqld.pid
          ... skip-bdb
          ... """
          >>> config = ConfigParser.RawConfigParser(allow_no_value=True)
          >>> config.readfp(StringIO.StringIO(sample_config))
          >>> config.get('mysqld', 'user')
          'mysql'
          >>> print config.get('mysqld', 'skip-bdb')
          None
          >>> print config.get('mysqld', 'unknown')
          Traceback (most recent call last):
            ...
          NoOptionError: No option 'unknown' in section: 'mysqld'

     (Contributed by Mats Kindahl; bpo-7005(9).)

   * Deprecated function: ‘contextlib.nested()’, which allows handling
     more than one context manager with a single *note with: 6f2.
     statement, has been deprecated, because the ‘with’ statement now
     supports multiple context managers.

   * The ‘cookielib’ module now ignores cookies that have an invalid
     version field, one that doesn’t contain an integer value.  (Fixed
     by John J. Lee; bpo-3924(10).)

   * The *note copy: 26. module’s *note deepcopy(): 3d4. function will
     now correctly copy bound instance methods.  (Implemented by Robert
     Collins; bpo-1515(11).)

   * The *note ctypes: 2b. module now always converts ‘None’ to a C
     ‘NULL’ pointer for arguments declared as pointers.  (Changed by
     Thomas Heller; bpo-4606(12).)  The underlying libffi library(13)
     has been updated to version 3.0.9, containing various fixes for
     different platforms.  (Updated by Matthias Klose; bpo-8142(14).)

   * New method: the *note datetime: 31. module’s *note timedelta: 196.
     class gained a *note total_seconds(): ca4. method that returns the
     number of seconds in the duration.  (Contributed by Brian Quinlan;
     bpo-5788(15).)

   * New method: the *note Decimal: 189. class gained a *note
     from_float(): b88. class method that performs an exact conversion
     of a floating-point number to a *note Decimal: 189.  This exact
     conversion strives for the closest decimal approximation to the
     floating-point representation’s value; the resulting decimal value
     will therefore still include the inaccuracy, if any.  For example,
     ‘Decimal.from_float(0.1)’ returns
     ‘Decimal('0.1000000000000000055511151231257827021181583404541015625')’.
     (Implemented by Raymond Hettinger; bpo-4796(16).)

     Comparing instances of *note Decimal: 189. with floating-point
     numbers now produces sensible results based on the numeric values
     of the operands.  Previously such comparisons would fall back to
     Python’s default rules for comparing objects, which produced
     arbitrary results based on their type.  Note that you still cannot
     combine ‘Decimal’ and floating-point in other operations such as
     addition, since you should be explicitly choosing how to convert
     between float and *note Decimal: 189.  (Fixed by Mark Dickinson;
     bpo-2531(17).)

     The constructor for *note Decimal: 189. now accepts floating-point
     numbers (added by Raymond Hettinger; bpo-8257(18)) and non-European
     Unicode characters such as Arabic-Indic digits (contributed by Mark
     Dickinson; bpo-6595(19)).

     Most of the methods of the *note Context: 9f8. class now accept
     integers as well as *note Decimal: 189. instances; the only
     exceptions are the *note canonical(): ca5. and *note
     is_canonical(): ca6. methods.  (Patch by Juan José Conti;
     bpo-7633(20).)

     When using *note Decimal: 189. instances with a string’s *note
     format(): 4e2. method, the default alignment was previously
     left-alignment.  This has been changed to right-alignment, which is
     more sensible for numeric types.  (Changed by Mark Dickinson;
     bpo-6857(21).)

     Comparisons involving a signaling NaN value (or ‘sNAN’) now signal
     ‘InvalidOperation’ instead of silently returning a true or false
     value depending on the comparison operator.  Quiet NaN values (or
     ‘NaN’) are now hashable.  (Fixed by Mark Dickinson; bpo-7279(22).)

   * The *note difflib: 37. module now produces output that is more
     compatible with modern ‘diff’/‘patch’ tools through one small
     change, using a tab character instead of spaces as a separator in
     the header giving the filename.  (Fixed by Anatoly Techtonik;
     bpo-7585(23).)

   * The Distutils ‘sdist’ command now always regenerates the ‘MANIFEST’
     file, since even if the ‘MANIFEST.in’ or ‘setup.py’ files haven’t
     been modified, the user might have created some new files that
     should be included.  (Fixed by Tarek Ziadé; bpo-8688(24).)

   * The *note doctest: 67. module’s ‘IGNORE_EXCEPTION_DETAIL’ flag will
     now ignore the name of the module containing the exception being
     tested.  (Patch by Lennart Regebro; bpo-7490(25).)

   * The *note email: 69. module’s *note Message: 54a. class will now
     accept a Unicode-valued payload, automatically converting the
     payload to the encoding specified by ‘output_charset’.  (Added by
     R. David Murray; bpo-1368247(26).)

   * The *note Fraction: 186. class now accepts a single float or *note
     Decimal: 189. instance, or two rational numbers, as arguments to
     its constructor.  (Implemented by Mark Dickinson; rationals added
     in bpo-5812(27), and float/decimal in bpo-8294(28).)

     Ordering comparisons (‘<’, ‘<=’, ‘>’, ‘>=’) between fractions and
     complex numbers now raise a *note TypeError: 193.  This fixes an
     oversight, making the *note Fraction: 186. match the other numeric
     types.

   * New class: *note FTP_TLS: a0b. in the *note ftplib: 84. module
     provides secure FTP connections using TLS encapsulation of
     authentication as well as subsequent control and data transfers.
     (Contributed by Giampaolo Rodola; bpo-2054(29).)

     The *note storbinary(): ca7. method for binary uploads can now
     restart uploads thanks to an added `rest' parameter (patch by Pablo
     Mouzo; bpo-6845(30).)

   * New class decorator: *note total_ordering(): 854. in the *note
     functools: 85. module takes a class that defines an *note __eq__():
     348. method and one of *note __lt__(): c3c, *note __le__(): ca8,
     *note __gt__(): ca9, or *note __ge__(): caa, and generates the
     missing comparison methods.  Since the ‘__cmp__()’ method is being
     deprecated in Python 3.x, this decorator makes it easier to define
     ordered classes.  (Added by Raymond Hettinger; bpo-5479(31).)

     New function: *note cmp_to_key(): b5e. will take an old-style
     comparison function that expects two arguments and return a new
     callable that can be used as the `key' parameter to functions such
     as *note sorted(): 44c, *note min(): 812. and *note max(): 813,
     etc.  The primary intended use is to help with making code
     compatible with Python 3.x.  (Added by Raymond Hettinger.)

   * New function: the *note gc: 86. module’s *note is_tracked(): cab.
     returns true if a given instance is tracked by the garbage
     collector, false otherwise.  (Contributed by Antoine Pitrou;
     bpo-4688(32).)

   * The *note gzip: 8c. module’s *note GzipFile: 6e6. now supports the
     context management protocol, so you can write ‘with
     gzip.GzipFile(...) as f:’ (contributed by Hagen Fürstenau;
     bpo-3860(33)), and it now implements the *note io.BufferedIOBase:
     591. ABC, so you can wrap it with *note io.BufferedReader: b92. for
     faster processing (contributed by Nir Aides; bpo-7471(34)).  It’s
     also now possible to override the modification time recorded in a
     gzipped file by providing an optional timestamp to the constructor.
     (Contributed by Jacques Frechet; bpo-4272(35).)

     Files in gzip format can be padded with trailing zero bytes; the
     *note gzip: 8c. module will now consume these trailing bytes.
     (Fixed by Tadek Pietraszek and Brian Curtin; bpo-2846(36).)

   * New attribute: the *note hashlib: 8d. module now has an
     ‘algorithms’ attribute containing a tuple naming the supported
     algorithms.  In Python 2.7, ‘hashlib.algorithms’ contains ‘('md5',
     'sha1', 'sha224', 'sha256', 'sha384', 'sha512')’.  (Contributed by
     Carl Chenet; bpo-7418(37).)

   * The default ‘HTTPResponse’ class used by the ‘httplib’ module now
     supports buffering, resulting in much faster reading of HTTP
     responses.  (Contributed by Kristján Valur Jónsson; bpo-4879(38).)

     The ‘HTTPConnection’ and ‘HTTPSConnection’ classes now support a
     `source_address' parameter, a ‘(host, port)’ 2-tuple giving the
     source address that will be used for the connection.  (Contributed
     by Eldon Ziegler; bpo-3972(39).)

   * The ‘ihooks’ module now supports relative imports.  Note that
     ‘ihooks’ is an older module for customizing imports, superseded by
     the ‘imputil’ module added in Python 2.0.  (Relative import support
     added by Neil Schemenauer.)

   * The *note imaplib: 98. module now supports IPv6 addresses.
     (Contributed by Derek Morr; bpo-1655(40).)

   * New function: the *note inspect: a1. module’s *note getcallargs():
     7bf. takes a callable and its positional and keyword arguments, and
     figures out which of the callable’s parameters will receive each
     argument, returning a dictionary mapping argument names to their
     values.  For example:

          >>> from inspect import getcallargs
          >>> def f(a, b=1, *pos, **named):
          ...     pass
          >>> getcallargs(f, 1, 2, 3)
          {'a': 1, 'b': 2, 'pos': (3,), 'named': {}}
          >>> getcallargs(f, a=2, x=4)
          {'a': 2, 'b': 1, 'pos': (), 'named': {'x': 4}}
          >>> getcallargs(f)
          Traceback (most recent call last):
          ...
          TypeError: f() takes at least 1 argument (0 given)

     由 Georg Sakkis 在 bpo-3135(41) 中贡献。

   * Updated module: The *note io: a2. library has been upgraded to the
     version shipped with Python 3.1.  For 3.1, the I/O library was
     entirely rewritten in C and is 2 to 20 times faster depending on
     the task being performed.  The original Python version was renamed
     to the ‘_pyio’ module.

     One minor resulting change: the *note io.TextIOBase: c41. class now
     has an ‘errors’ attribute giving the error setting used for
     encoding and decoding errors (one of ‘'strict'’, ‘'replace'’,
     ‘'ignore'’).

     The *note io.FileIO: cac. class now raises an *note OSError: 1d4.
     when passed an invalid file descriptor.  (Implemented by Benjamin
     Peterson; bpo-4991(42).)  The *note truncate(): cad. method now
     preserves the file position; previously it would change the file
     position to the end of the new file.  (Fixed by Pascal Chambon;
     bpo-6939(43).)

   * New function: ‘itertools.compress(data, selectors)’ takes two
     iterators.  Elements of `data' are returned if the corresponding
     value in `selectors' is true:

          itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
            A, C, E, F

     New function: ‘itertools.combinations_with_replacement(iter, r)’
     returns all the possible `r'-length combinations of elements from
     the iterable `iter'.  Unlike *note combinations(): cae, individual
     elements can be repeated in the generated combinations:

          itertools.combinations_with_replacement('abc', 2) =>
            ('a', 'a'), ('a', 'b'), ('a', 'c'),
            ('b', 'b'), ('b', 'c'), ('c', 'c')

     Note that elements are treated as unique depending on their
     position in the input, not their actual values.

     The *note itertools.count(): c23. function now has a `step'
     argument that allows incrementing by values other than 1.  *note
     count(): c23. also now allows keyword arguments, and using
     non-integer values such as floats or *note Decimal: 189. instances.
     (Implemented by Raymond Hettinger; bpo-5032(44).)

     *note itertools.combinations(): cae. and *note itertools.product():
     caf. previously raised *note ValueError: 1fc. for values of `r'
     larger than the input iterable.  This was deemed a specification
     error, so they now return an empty iterator.  (Fixed by Raymond
     Hettinger; bpo-4816(45).)

   * Updated module: The *note json: a5. module was upgraded to version
     2.0.9 of the simplejson package, which includes a C extension that
     makes encoding and decoding faster.  (Contributed by Bob Ippolito;
     bpo-4136(46).)

     To support the new *note collections.OrderedDict: 1ba. type, *note
     json.load(): 568. now has an optional `object_pairs_hook' parameter
     that will be called with any object literal that decodes to a list
     of pairs.  (Contributed by Raymond Hettinger; bpo-5381(47).)

   * The *note mailbox: af. module’s *note Maildir: cb0. class now
     records the timestamp on the directories it reads, and only
     re-reads them if the modification time has subsequently changed.
     This improves performance by avoiding unneeded directory scans.
     (Fixed by A.M. Kuchling and Antoine Pitrou; bpo-1607951(48),
     bpo-6896(49).)

   * New functions: the *note math: b2. module gained *note erf(): 45a.
     and *note erfc(): 45b. for the error function and the complementary
     error function, *note expm1(): b70. which computes ‘e**x - 1’ with
     more precision than using *note exp(): cb1. and subtracting 1,
     *note gamma(): b71. for the Gamma function, and *note lgamma():
     b72. for the natural log of the Gamma function.  (Contributed by
     Mark Dickinson and nirinA raseliarison; bpo-3366(50).)

   * The *note multiprocessing: b8. module’s ‘Manager*’ classes can now
     be passed a callable that will be called whenever a subprocess is
     started, along with a set of arguments that will be passed to the
     callable.  (Contributed by lekma; bpo-5585(51).)

     The ‘Pool’ class, which controls a pool of worker processes, now
     has an optional `maxtasksperchild' parameter.  Worker processes
     will perform the specified number of tasks and then exit, causing
     the ‘Pool’ to start a new worker.  This is useful if tasks may leak
     memory or other resources, or if some tasks will cause the worker
     to become very large.  (Contributed by Charles Cazabon;
     bpo-6963(52).)

   * The *note nntplib: c1. module now supports IPv6 addresses.
     (Contributed by Derek Morr; bpo-1664(53).)

   * New functions: the *note os: c5. module wraps the following POSIX
     system calls: *note getresgid(): cb2. and *note getresuid(): cb3,
     which return the real, effective, and saved GIDs and UIDs; *note
     setresgid(): cb4. and *note setresuid(): cb5, which set real,
     effective, and saved GIDs and UIDs to new values; *note
     initgroups(): cb6, which initialize the group access list for the
     current process.  (GID/UID functions contributed by Travis H.;
     bpo-6508(54).  Support for initgroups added by Jean-Paul Calderone;
     bpo-7333(55).)

     The *note os.fork(): 969. function now re-initializes the import
     lock in the child process; this fixes problems on Solaris when
     *note fork(): 969. is called from a thread.  (Fixed by Zsolt
     Cserna; bpo-7242(56).)

   * In the *note os.path: c6. module, the *note normpath(): cb7. and
     *note abspath(): cb8. functions now preserve Unicode; if their
     input path is a Unicode string, the return value is also a Unicode
     string.  (*note normpath(): cb7. fixed by Matt Giuca in
     bpo-5827(57); *note abspath(): cb8. fixed by Ezio Melotti in
     bpo-3426(58).)

   * The *note pydoc: da. module now has help for the various symbols
     that Python uses.  You can now do ‘help('<<')’ or ‘help('@')’, for
     example.  (Contributed by David Laban; bpo-4739(59).)

   * The *note re: de. module’s *note split(): 3d2, *note sub(): 483,
     and *note subn(): 73d. now accept an optional `flags' argument, for
     consistency with the other functions in the module.  (Added by
     Gregory P. Smith.)

   * New function: *note run_path(): cb9. in the *note runpy: e3. module
     will execute the code at a provided `path' argument.  `path' can be
     the path of a Python source file (‘example.py’), a compiled
     bytecode file (‘example.pyc’), a directory (‘./package/’), or a zip
     archive (‘example.zip’).  If a directory or zip path is provided,
     it will be added to the front of ‘sys.path’ and the module *note
     __main__: 1. will be imported.  It’s expected that the directory or
     zip contains a ‘__main__.py’; if it doesn’t, some other
     ‘__main__.py’ might be imported from a location later in
     ‘sys.path’.  This makes more of the machinery of *note runpy: e3.
     available to scripts that want to mimic the way Python’s command
     line processes an explicit path name.  (Added by Nick Coghlan;
     bpo-6816(60).)

   * New function: in the *note shutil: ea. module, *note
     make_archive(): 21c. takes a filename, archive type (zip or
     tar-format), and a directory path, and creates an archive
     containing the directory’s contents.  (Added by Tarek Ziadé.)

     *note shutil: ea.’s *note copyfile(): 259. and *note copytree():
     21b. functions now raise a ‘SpecialFileError’ exception when asked
     to copy a named pipe.  Previously the code would treat named pipes
     like a regular file by opening them for reading, and this would
     block indefinitely.  (Fixed by Antoine Pitrou; bpo-3002(61).)

   * The *note signal: eb. module no longer re-installs the signal
     handler unless this is truly necessary, which fixes a bug that
     could make it impossible to catch the EINTR signal robustly.
     (Fixed by Charles-Francois Natali; bpo-8354(62).)

   * New functions: in the *note site: ec. module, three new functions
     return various site- and user-specific paths.  *note
     getsitepackages(): bdb. returns a list containing all global
     site-packages directories, *note getusersitepackages(): bdd.
     returns the path of the user’s site-packages directory, and *note
     getuserbase(): bdc. returns the value of the ‘USER_BASE’
     environment variable, giving the path to a directory that can be
     used to store data.  (Contributed by Tarek Ziadé; bpo-6693(63).)

     The *note site: ec. module now reports exceptions occurring when
     the ‘sitecustomize’ module is imported, and will no longer catch
     and swallow the *note KeyboardInterrupt: 198. exception.  (Fixed by
     Victor Stinner; bpo-3137(64).)

   * The *note create_connection(): ba6. function gained a
     `source_address' parameter, a ‘(host, port)’ 2-tuple giving the
     source address that will be used for the connection.  (Contributed
     by Eldon Ziegler; bpo-3972(65).)

     The *note recv_into(): cba. and *note recvfrom_into(): cbb. methods
     will now write into objects that support the buffer API, most
     usefully the *note bytearray: 33b. and *note memoryview: 25d.
     objects.  (Implemented by Antoine Pitrou; bpo-8104(66).)

   * The ‘SocketServer’ module’s ‘TCPServer’ class now supports socket
     timeouts and disabling the Nagle algorithm.  The
     ‘disable_nagle_algorithm’ class attribute defaults to ‘False’; if
     overridden to be true, new request connections will have the
     TCP_NODELAY option set to prevent buffering many small sends into a
     single TCP packet.  The ‘timeout’ class attribute can hold a
     timeout in seconds that will be applied to the request socket; if
     no request is received within that time, ‘handle_timeout()’ will be
     called and ‘handle_request()’ will return.  (Contributed by
     Kristján Valur Jónsson; bpo-6192(67) and bpo-6267(68).)

   * Updated module: the *note sqlite3: f3. module has been updated to
     version 2.6.0 of the pysqlite package(69).  Version 2.6.0 includes
     a number of bugfixes, and adds the ability to load SQLite
     extensions from shared libraries.  Call the
     ‘enable_load_extension(True)’ method to enable extensions, and then
     call *note load_extension(): ba2. to load a particular shared
     library.  (Updated by Gerhard Häring.)

   * The *note ssl: f4. module’s *note SSLSocket: 3ea. objects now
     support the buffer API, which fixed a test suite failure (fix by
     Antoine Pitrou; bpo-7133(70)) and automatically set OpenSSL’s
     ‘SSL_MODE_AUTO_RETRY’, which will prevent an error code being
     returned from ‘recv()’ operations that trigger an SSL renegotiation
     (fix by Antoine Pitrou; bpo-8222(71)).

     The *note ssl.wrap_socket(): 477. constructor function now takes a
     `ciphers' argument that’s a string listing the encryption
     algorithms to be allowed; the format of the string is described in
     the OpenSSL documentation(72).  (Added by Antoine Pitrou;
     bpo-8322(73).)

     Another change makes the extension load all of OpenSSL’s ciphers
     and digest algorithms so that they’re all available.  Some SSL
     certificates couldn’t be verified, reporting an "unknown algorithm"
     error.  (Reported by Beda Kosata, and fixed by Antoine Pitrou;
     bpo-8484(74).)

     The version of OpenSSL being used is now available as the module
     attributes *note ssl.OPENSSL_VERSION: ba9. (a string), *note
     ssl.OPENSSL_VERSION_INFO: baa. (a 5-tuple), and *note
     ssl.OPENSSL_VERSION_NUMBER: bab. (an integer).  (Added by Antoine
     Pitrou; bpo-8321(75).)

   * The *note struct: f9. module will no longer silently ignore
     overflow errors when a value is too large for a particular integer
     format code (one of ‘bBhHiIlLqQ’); it now always raises a *note
     struct.error: cbc. exception.  (Changed by Mark Dickinson;
     bpo-1523(76).)  The *note pack(): c13. function will also attempt
     to use *note __index__(): 18b. to convert and pack non-integers
     before trying the *note __int__(): 18c. method or reporting an
     error.  (Changed by Mark Dickinson; bpo-8300(77).)

   * New function: the *note subprocess: fa. module’s *note
     check_output(): 8e3. runs a command with a specified set of
     arguments and returns the command’s output as a string when the
     command runs without error, or raises a *note CalledProcessError:
     cbd. exception otherwise.

          >>> subprocess.check_output(['df', '-h', '.'])
          'Filesystem     Size   Used  Avail Capacity  Mounted on\n
          /dev/disk0s2    52G    49G   3.0G    94%    /\n'

          >>> subprocess.check_output(['df', '-h', '/bogus'])
            ...
          subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1

     （由 Gregory P. Smith 贡献）

     The *note subprocess: fa. module will now retry its internal system
     calls on receiving an ‘EINTR’ signal.  (Reported by several people;
     final patch by Gregory P. Smith in bpo-1068268(78).)

   * New function: *note is_declared_global(): cbe. in the *note
     symtable: fd. module returns true for variables that are explicitly
     declared to be global, false for ones that are implicitly global.
     (Contributed by Jeremy Hylton.)

   * The *note syslog: 100. module will now use the value of
     ‘sys.argv[0]’ as the identifier instead of the previous default
     value of ‘'python'’.  (Changed by Sean Reifschneider;
     bpo-8451(79).)

   * The ‘sys.version_info’ value is now a named tuple, with attributes
     named ‘major’, ‘minor’, ‘micro’, ‘releaselevel’, and ‘serial’.
     (Contributed by Ross Light; bpo-4285(80).)

     *note sys.getwindowsversion(): 59e. also returns a named tuple,
     with attributes named ‘major’, ‘minor’, ‘build’, *note platform:
     cf, ‘service_pack’, ‘service_pack_major’, ‘service_pack_minor’,
     ‘suite_mask’, and ‘product_type’.  (Contributed by Brian Curtin;
     bpo-7766(81).)

   * The *note tarfile: 102. module’s default error handling has
     changed, to no longer suppress fatal errors.  The default error
     level was previously 0, which meant that errors would only result
     in a message being written to the debug log, but because the debug
     log is not activated by default, these errors go unnoticed.  The
     default error level is now 1, which raises an exception if there’s
     an error.  (Changed by Lars Gustäbel; bpo-7357(82).)

     *note tarfile: 102. now supports filtering the *note TarInfo: b95.
     objects being added to a tar file.  When you call *note add(): 484,
     you may supply an optional `filter' argument that’s a callable.
     The `filter' callable will be passed the *note TarInfo: b95. for
     every file being added, and can modify and return it.  If the
     callable returns ‘None’, the file will be excluded from the
     resulting archive.  This is more powerful than the existing
     `exclude' argument, which has therefore been deprecated.  (Added by
     Lars Gustäbel; bpo-6856(83).)  The *note TarFile: b94. class also
     now supports the context management protocol.  (Added by Lars
     Gustäbel; bpo-7232(84).)

   * The *note wait(): cbf. method of the *note threading.Event: ab5.
     class now returns the internal flag on exit.  This means the method
     will usually return true because *note wait(): cbf. is supposed to
     block until the internal flag becomes true.  The return value will
     only be false if a timeout was provided and the operation timed
     out.  (Contributed by Tim Lesher; bpo-1674032(85).)

   * The Unicode database provided by the *note unicodedata: 11b. module
     is now used internally to determine which characters are numeric,
     whitespace, or represent line breaks.  The database also includes
     information from the ‘Unihan.txt’ data file (patch by Anders
     Chrigström and Amaury Forgeot d’Arc; bpo-1571184(86)) and has been
     updated to version 5.2.0 (updated by Florent Xicluna;
     bpo-8024(87)).

   * The ‘urlparse’ module’s ‘urlsplit()’ now handles unknown URL
     schemes in a fashion compliant with RFC 3986(88): if the URL is of
     the form ‘"<something>://..."’, the text before the ‘://’ is
     treated as the scheme, even if it’s a made-up scheme that the
     module doesn’t know about.  This change may break code that worked
     around the old behaviour.  For example, Python 2.6.4 or 2.5 will
     return the following:

          >>> import urlparse
          >>> urlparse.urlsplit('invented://host/filename?query')
          ('invented', '', '//host/filename?query', '', '')

     Python 2.7 (and Python 2.6.5) will return:

          >>> import urlparse
          >>> urlparse.urlsplit('invented://host/filename?query')
          ('invented', 'host', '/filename?query', '', '')

     (Python 2.7 actually produces slightly different output, since it
     returns a named tuple instead of a standard tuple.)

     The ‘urlparse’ module also supports IPv6 literal addresses as
     defined by RFC 2732(89) (contributed by Senthil Kumaran;
     bpo-2987(90)).

          >>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
          ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
                      path='/foo', params='', query='', fragment='')

   * New class: the *note WeakSet: cc0. class in the *note weakref: 129.
     module is a set that only holds weak references to its elements;
     elements will be removed once there are no references pointing to
     them.  (Originally implemented in Python 3.x by Raymond Hettinger,
     and backported to 2.7 by Michael Foord.)

   * The ElementTree library, ‘xml.etree’, no longer escapes ampersands
     and angle brackets when outputting an XML processing instruction
     (which looks like ‘<?xml-stylesheet href="#style1"?>’) or comment
     (which looks like ‘<!-- comment -->’).  (Patch by Neil Muller;
     bpo-2746(91).)

   * The XML-RPC client and server, provided by the ‘xmlrpclib’ and
     ‘SimpleXMLRPCServer’ modules, have improved performance by
     supporting HTTP/1.1 keep-alive and by optionally using gzip
     encoding to compress the XML being exchanged.  The gzip compression
     is controlled by the ‘encode_threshold’ attribute of
     ‘SimpleXMLRPCRequestHandler’, which contains a size in bytes;
     responses larger than this will be compressed.  (Contributed by
     Kristján Valur Jónsson; bpo-6267(92).)

   * The *note zipfile: 143. module’s *note ZipFile: 427. now supports
     the context management protocol, so you can write ‘with
     zipfile.ZipFile(...) as f:’.  (Contributed by Brian Curtin;
     bpo-5511(93).)

     *note zipfile: 143. now also supports archiving empty directories
     and extracts them correctly.  (Fixed by Kuba Wieczorek;
     bpo-4710(94).)  Reading files out of an archive is faster, and
     interleaving *note read(): cc1. and ‘readline()’ now works
     correctly.  (Contributed by Nir Aides; bpo-7610(95).)

     The *note is_zipfile(): cc2. function now accepts a file object, in
     addition to the path names accepted in earlier versions.
     (Contributed by Gabriel Genellina; bpo-4756(96).)

     The *note writestr(): cc3. method now has an optional
     `compress_type' parameter that lets you override the default
     compression method specified in the *note ZipFile: 427.
     constructor.  (Contributed by Ronald Oussoren; bpo-6003(97).)

* Menu:

* 新模块：importlib::
* 新模块：sysconfig::
* ttk; Themed Widgets for Tk: ttk Themed Widgets for Tk.
* 更新的模块：unittest::
* 更新的模块：ElementTree 1.3: 更新的模块：ElementTree 1 3.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5142

   (2) https://bugs.python.org/issue7703

   (3) https://www.jcea.es/programacion/pybsddb.htm

   (4) https://bugs.python.org/issue8156

   (5) https://bugs.python.org/issue3860

   (6) https://bugs.python.org/issue1696199

   (7) https://bugs.python.org/issue1818

   (8) https://bugs.python.org/issue8729

   (9) https://bugs.python.org/issue7005

   (10) https://bugs.python.org/issue3924

   (11) https://bugs.python.org/issue1515

   (12) https://bugs.python.org/issue4606

   (13) https://sourceware.org/libffi/

   (14) https://bugs.python.org/issue8142

   (15) https://bugs.python.org/issue5788

   (16) https://bugs.python.org/issue4796

   (17) https://bugs.python.org/issue2531

   (18) https://bugs.python.org/issue8257

   (19) https://bugs.python.org/issue6595

   (20) https://bugs.python.org/issue7633

   (21) https://bugs.python.org/issue6857

   (22) https://bugs.python.org/issue7279

   (23) https://bugs.python.org/issue7585

   (24) https://bugs.python.org/issue8688

   (25) https://bugs.python.org/issue7490

   (26) https://bugs.python.org/issue1368247

   (27) https://bugs.python.org/issue5812

   (28) https://bugs.python.org/issue8294

   (29) https://bugs.python.org/issue2054

   (30) https://bugs.python.org/issue6845

   (31) https://bugs.python.org/issue5479

   (32) https://bugs.python.org/issue4688

   (33) https://bugs.python.org/issue3860

   (34) https://bugs.python.org/issue7471

   (35) https://bugs.python.org/issue4272

   (36) https://bugs.python.org/issue2846

   (37) https://bugs.python.org/issue7418

   (38) https://bugs.python.org/issue4879

   (39) https://bugs.python.org/issue3972

   (40) https://bugs.python.org/issue1655

   (41) https://bugs.python.org/issue3135

   (42) https://bugs.python.org/issue4991

   (43) https://bugs.python.org/issue6939

   (44) https://bugs.python.org/issue5032

   (45) https://bugs.python.org/issue4816

   (46) https://bugs.python.org/issue4136

   (47) https://bugs.python.org/issue5381

   (48) https://bugs.python.org/issue1607951

   (49) https://bugs.python.org/issue6896

   (50) https://bugs.python.org/issue3366

   (51) https://bugs.python.org/issue5585

   (52) https://bugs.python.org/issue6963

   (53) https://bugs.python.org/issue1664

   (54) https://bugs.python.org/issue6508

   (55) https://bugs.python.org/issue7333

   (56) https://bugs.python.org/issue7242

   (57) https://bugs.python.org/issue5827

   (58) https://bugs.python.org/issue3426

   (59) https://bugs.python.org/issue4739

   (60) https://bugs.python.org/issue6816

   (61) https://bugs.python.org/issue3002

   (62) https://bugs.python.org/issue8354

   (63) https://bugs.python.org/issue6693

   (64) https://bugs.python.org/issue3137

   (65) https://bugs.python.org/issue3972

   (66) https://bugs.python.org/issue8104

   (67) https://bugs.python.org/issue6192

   (68) https://bugs.python.org/issue6267

   (69) https://github.com/ghaering/pysqlite

   (70) https://bugs.python.org/issue7133

   (71) https://bugs.python.org/issue8222

   (72) 
https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT

   (73) https://bugs.python.org/issue8322

   (74) https://bugs.python.org/issue8484

   (75) https://bugs.python.org/issue8321

   (76) https://bugs.python.org/issue1523

   (77) https://bugs.python.org/issue8300

   (78) https://bugs.python.org/issue1068268

   (79) https://bugs.python.org/issue8451

   (80) https://bugs.python.org/issue4285

   (81) https://bugs.python.org/issue7766

   (82) https://bugs.python.org/issue7357

   (83) https://bugs.python.org/issue6856

   (84) https://bugs.python.org/issue7232

   (85) https://bugs.python.org/issue1674032

   (86) https://bugs.python.org/issue1571184

   (87) https://bugs.python.org/issue8024

   (88) https://tools.ietf.org/html/rfc3986.html

   (89) https://tools.ietf.org/html/rfc2732.html

   (90) https://bugs.python.org/issue2987

   (91) https://bugs.python.org/issue2746

   (92) https://bugs.python.org/issue6267

   (93) https://bugs.python.org/issue5511

   (94) https://bugs.python.org/issue4710

   (95) https://bugs.python.org/issue7610

   (96) https://bugs.python.org/issue4756

   (97) https://bugs.python.org/issue6003


File: python.info,  Node: 新模块：importlib,  Next: 新模块：sysconfig,  Up: 新增和改进的模块

1.10.11.1 新模块：importlib
...........................

Python 3.1 includes the *note importlib: 9b. package, a
re-implementation of the logic underlying Python’s *note import: c25.
statement.  *note importlib: 9b. is useful for implementors of Python
interpreters and to users who wish to write new importers that can
participate in the import process.  Python 2.7 doesn’t contain the
complete *note importlib: 9b. package, but instead has a tiny subset
that contains a single function, *note import_module(): b1b.

‘import_module(name, package=None)’ imports a module.  `name' is a
string containing the module or package’s name.  It’s possible to do
relative imports by providing a string that begins with a ‘.’ character,
such as ‘..utils.errors’.  For relative imports, the `package' argument
must be provided and is the name of the package that will be used as the
anchor for the relative import.  *note import_module(): b1b. both
inserts the imported module into ‘sys.modules’ and returns the module
object.

这是一些例子:

     >>> from importlib import import_module
     >>> anydbm = import_module('anydbm')  # Standard absolute import
     >>> anydbm
     <module 'anydbm' from '/p/python/Lib/anydbm.py'>
     >>> # Relative import
     >>> file_util = import_module('..file_util', 'distutils.command')
     >>> file_util
     <module 'distutils.file_util' from '/python/Lib/distutils/file_util.pyc'>

*note importlib: 9b. was implemented by Brett Cannon and introduced in
Python 3.1.


File: python.info,  Node: 新模块：sysconfig,  Next: ttk Themed Widgets for Tk,  Prev: 新模块：importlib,  Up: 新增和改进的模块

1.10.11.2 新模块：sysconfig
...........................

The *note sysconfig: ff. module has been pulled out of the Distutils
package, becoming a new top-level module in its own right.  *note
sysconfig: ff. provides functions for getting information about Python’s
build process: compiler switches, installation paths, the platform name,
and whether Python is running from its source directory.

Some of the functions in the module are:

   * *note get_config_var(): 96c. returns variables from Python’s
     Makefile and the ‘pyconfig.h’ file.

   * *note get_config_vars(): 96d. returns a dictionary containing all
     of the configuration variables.

   * *note get_path(): cc6. returns the configured path for a particular
     type of module: the standard library, site-specific modules,
     platform-specific modules, etc.

   * *note is_python_build(): cc7. returns true if you’re running a
     binary from a Python source tree, and false otherwise.

Consult the *note sysconfig: ff. documentation for more details and for
a complete list of functions.

The Distutils package and *note sysconfig: ff. are now maintained by
Tarek Ziadé, who has also started a Distutils2 package (source
repository at ‘https://hg.python.org/distutils2/’) for developing a
next-generation version of Distutils.


File: python.info,  Node: ttk Themed Widgets for Tk,  Next: 更新的模块：unittest,  Prev: 新模块：sysconfig,  Up: 新增和改进的模块

1.10.11.3 ttk: Themed Widgets for Tk
....................................

Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
widgets but have a more customizable appearance and can therefore more
closely resemble the native platform’s widgets.  This widget set was
originally called Tile, but was renamed to Ttk (for "themed Tk") on
being added to Tcl/Tck release 8.5.

To learn more, read the ‘ttk’ module documentation.  You may also wish
to read the Tcl/Tk manual page describing the Ttk theme engine,
available at ‘https://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm’.  Some
screenshots of the Python/Ttk code in use are at
‘https://code.google.com/archive/p/python-ttk/wikis/Screenshots.wiki’.

The ‘ttk’ module was written by Guilherme Polo and added in bpo-2983(1).
An alternate version called ‘Tile.py’, written by Martin Franklin and
maintained by Kevin Walzer, was proposed for inclusion in bpo-2618(2),
but the authors argued that Guilherme Polo’s work was more
comprehensive.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2983

   (2) https://bugs.python.org/issue2618


File: python.info,  Node: 更新的模块：unittest,  Next: 更新的模块：ElementTree 1 3,  Prev: ttk Themed Widgets for Tk,  Up: 新增和改进的模块

1.10.11.4 更新的模块：unittest
..............................

The *note unittest: 11c. module was greatly enhanced; many new features
were added.  Most of these features were implemented by Michael Foord,
unless otherwise noted.  The enhanced version of the module is
downloadable separately for use with Python versions 2.4 to 2.6,
packaged as the ‘unittest2’ package, from
‘https://pypi.org/project/unittest2’.

When used from the command line, the module can automatically discover
tests.  It’s not as fancy as py.test(1) or nose(2), but provides a
simple way to run tests kept within a set of package directories.  For
example, the following command will search the ‘test/’ subdirectory for
any importable test files named ‘test*.py’:

     python -m unittest discover -s test

Consult the *note unittest: 11c. module documentation for more details.
(Developed in bpo-6001(3).)

The *note main(): 90a. function supports some other new options:

   * *note -b: ccb. or ‘--buffer’ will buffer the standard output and
     standard error streams during each test.  If the test passes, any
     resulting output will be discarded; on failure, the buffered output
     will be displayed.

   * *note -c: ccc. or ‘--catch’ will cause the control-C interrupt to
     be handled more gracefully.  Instead of interrupting the test
     process immediately, the currently running test will be completed
     and then the partial results up to the interruption will be
     reported.  If you’re impatient, a second press of control-C will
     cause an immediate interruption.

     This control-C handler tries to avoid causing problems when the
     code being tested or the tests being run have defined a signal
     handler of their own, by noticing that a signal handler was already
     set and calling it.  If this doesn’t work for you, there’s a *note
     removeHandler(): ccd. decorator that can be used to mark tests that
     should have the control-C handling disabled.

   * *note -f: cce. or ‘--failfast’ makes test execution stop
     immediately when a test fails instead of continuing to execute
     further tests.  (Suggested by Cliff Dyer and implemented by Michael
     Foord; bpo-8074(4).)

The progress messages now show ’x’ for expected failures and ’u’ for
unexpected successes when run in verbose mode.  (Contributed by Benjamin
Peterson.)

Test cases can raise the *note SkipTest: 90b. exception to skip a test
(bpo-1034053(5)).

The error messages for *note assertEqual(): bbd, *note assertTrue():
bbc, and *note assertFalse(): ccf. failures now provide more
information.  If you set the *note longMessage: cd0. attribute of your
*note TestCase: 907. classes to true, both the standard error message
and any additional message you provide will be printed for failures.
(Added by Michael Foord; bpo-5663(6).)

The *note assertRaises(): ac2. method now returns a context handler when
called without providing a callable object to run.  For example, you can
write this:

     with self.assertRaises(KeyError):
         {}['foo']

(Implemented by Antoine Pitrou; bpo-4444(7).)

Module- and class-level setup and teardown fixtures are now supported.
Modules can contain ‘setUpModule()’ and ‘tearDownModule()’ functions.
Classes can have *note setUpClass(): 24d. and *note tearDownClass():
cd1. methods that must be defined as class methods (using ‘@classmethod’
or equivalent).  These functions and methods are invoked when the test
runner switches to a test case in a different module or class.

The methods *note addCleanup(): 2a3. and *note doCleanups(): cd2. were
added.  *note addCleanup(): 2a3. lets you add cleanup functions that
will be called unconditionally (after *note setUp(): cd3. if *note
setUp(): cd3. fails, otherwise after *note tearDown(): cd4.).  This
allows for much simpler resource allocation and deallocation during
tests (bpo-5679(8)).

A number of new methods were added that provide more specialized tests.
Many of these methods were written by Google engineers for use in their
test suites; Gregory P. Smith, Michael Foord, and GvR worked on merging
them into Python’s version of *note unittest: 11c.

   * *note assertIsNone(): cd5. and *note assertIsNotNone(): cd6. take
     one expression and verify that the result is or is not ‘None’.

   * *note assertIs(): cd7. and *note assertIsNot(): cd8. take two
     values and check whether the two values evaluate to the same object
     or not.  (Added by Michael Foord; bpo-2578(9).)

   * *note assertIsInstance(): cd9. and *note assertNotIsInstance():
     cda. check whether the resulting object is an instance of a
     particular class, or of one of a tuple of classes.  (Added by Georg
     Brandl; bpo-7031(10).)

   * *note assertGreater(): cdb, *note assertGreaterEqual(): cdc, *note
     assertLess(): cdd, and *note assertLessEqual(): cde. compare two
     quantities.

   * *note assertMultiLineEqual(): cdf. compares two strings, and if
     they’re not equal, displays a helpful comparison that highlights
     the differences in the two strings.  This comparison is now used by
     default when Unicode strings are compared with *note assertEqual():
     bbd.

   * ‘assertRegexpMatches()’ and ‘assertNotRegexpMatches()’ checks
     whether the first argument is a string matching or not matching the
     regular expression provided as the second argument (bpo-8038(11)).

   * ‘assertRaisesRegexp()’ checks whether a particular exception is
     raised, and then also checks that the string representation of the
     exception matches the provided regular expression.

   * *note assertIn(): ce0. and *note assertNotIn(): ce1. tests whether
     `first' is or is not in `second'.

   * ‘assertItemsEqual()’ tests whether two provided sequences contain
     the same elements.

   * *note assertSetEqual(): ce2. compares whether two sets are equal,
     and only reports the differences between the sets in case of error.

   * Similarly, *note assertListEqual(): ce3. and *note
     assertTupleEqual(): ce4. compare the specified types and explain
     any differences without necessarily printing their full values;
     these methods are now used by default when comparing lists and
     tuples using *note assertEqual(): bbd.  More generally, *note
     assertSequenceEqual(): ce5. compares two sequences and can
     optionally check whether both sequences are of a particular type.

   * *note assertDictEqual(): ce6. compares two dictionaries and reports
     the differences; it’s now used by default when you compare two
     dictionaries using *note assertEqual(): bbd.
     ‘assertDictContainsSubset()’ checks whether all of the key/value
     pairs in `first' are found in `second'.

   * *note assertAlmostEqual(): bbf. and *note assertNotAlmostEqual():
     bc0. test whether `first' and `second' are approximately equal.
     This method can either round their difference to an
     optionally-specified number of `places' (the default is 7) and
     compare it to zero, or require the difference to be smaller than a
     supplied `delta' value.

   * *note loadTestsFromName(): ce7. properly honors the *note
     suiteClass: ce8. attribute of the *note TestLoader: 78b.  (Fixed by
     Mark Roddy; bpo-6866(12).)

   * A new hook lets you extend the *note assertEqual(): bbd. method to
     handle new data types.  The *note addTypeEqualityFunc(): ce9.
     method takes a type object and a function.  The function will be
     used when both of the objects being compared are of the specified
     type.  This function should compare the two objects and raise an
     exception if they don’t match; it’s a good idea for the function to
     provide additional information about why the two objects aren’t
     matching, much as the new sequence comparison methods do.

*note unittest.main(): 90a. now takes an optional ‘exit’ argument.  If
false, *note main(): 90a. doesn’t call *note sys.exit(): cea, allowing
*note main(): 90a. to be used from the interactive interpreter.
(Contributed by J. Pablo Fernández; bpo-3379(13).)

*note TestResult: ac7. has new *note startTestRun(): ceb. and *note
stopTestRun(): cec. methods that are called immediately before and after
a test run.  (Contributed by Robert Collins; bpo-5728(14).)

With all these changes, the ‘unittest.py’ was becoming awkwardly large,
so the module was turned into a package and the code split into several
files (by Benjamin Peterson).  This doesn’t affect how the module is
imported or used.

参见
....

‘http://www.voidspace.org.uk/python/articles/unittest2.shtml’

     Describes the new features, how to use them, and the rationale for
     various design decisions.  (By Michael Foord.)

   ---------- Footnotes ----------

   (1) http://pytest.org

   (2) https://nose.readthedocs.io/

   (3) https://bugs.python.org/issue6001

   (4) https://bugs.python.org/issue8074

   (5) https://bugs.python.org/issue1034053

   (6) https://bugs.python.org/issue5663

   (7) https://bugs.python.org/issue4444

   (8) https://bugs.python.org/issue5679

   (9) https://bugs.python.org/issue2578

   (10) https://bugs.python.org/issue7031

   (11) https://bugs.python.org/issue8038

   (12) https://bugs.python.org/issue6866

   (13) https://bugs.python.org/issue3379

   (14) https://bugs.python.org/issue5728


File: python.info,  Node: 更新的模块：ElementTree 1 3,  Prev: 更新的模块：unittest,  Up: 新增和改进的模块

1.10.11.5 更新的模块：ElementTree 1.3
.....................................

The version of the ElementTree library included with Python was updated
to version 1.3.  Some of the new features are:

   * The various parsing functions now take a `parser' keyword argument
     giving an *note XMLParser: 253. instance that will be used.  This
     makes it possible to override the file’s internal encoding:

          p = ET.XMLParser(encoding='utf-8')
          t = ET.XML("""<root/>""", parser=p)

     Errors in parsing XML now raise a ‘ParseError’ exception, whose
     instances have a ‘position’ attribute containing a (`line',
     `column') tuple giving the location of the problem.

   * ElementTree’s code for converting trees to a string has been
     significantly reworked, making it roughly twice as fast in many
     cases.  The *note ElementTree.write(): 920. and ‘Element.write()’
     methods now have a `method' parameter that can be "xml" (the
     default), "html", or "text".  HTML mode will output empty elements
     as ‘<empty></empty>’ instead of ‘<empty/>’, and text mode will skip
     over elements and only output the text chunks.  If you set the
     ‘tag’ attribute of an element to ‘None’ but leave its children in
     place, the element will be omitted when the tree is written out, so
     you don’t need to do more extensive rearrangement to remove a
     single element.

     Namespace handling has also been improved.  All ‘xmlns:<whatever>’
     declarations are now output on the root element, not scattered
     throughout the resulting XML. You can set the default namespace for
     a tree by setting the ‘default_namespace’ attribute and can
     register new prefixes with *note register_namespace(): b58.  In XML
     mode, you can use the true/false `xml_declaration' parameter to
     suppress the XML declaration.

   * New *note Element: acc. method: *note extend(): b59. appends the
     items from a sequence to the element’s children.  Elements
     themselves behave like sequences, so it’s easy to move children
     from one element to another:

          from xml.etree import ElementTree as ET

          t = ET.XML("""<list>
            <item>1</item> <item>2</item>  <item>3</item>
          </list>""")
          new = ET.XML('<root/>')
          new.extend(t)

          # Outputs <root><item>1</item>...</root>
          print ET.tostring(new)

   * New ‘Element’ method: *note iter(): cef. yields the children of the
     element as a generator.  It’s also possible to write ‘for child in
     elem:’ to loop over an element’s children.  The existing method
     ‘getiterator()’ is now deprecated, as is ‘getchildren()’ which
     constructs and returns a list of children.

   * New ‘Element’ method: *note itertext(): b5b. yields all chunks of
     text that are descendants of the element.  For example:

          t = ET.XML("""<list>
            <item>1</item> <item>2</item>  <item>3</item>
          </list>""")

          # Outputs ['\n  ', '1', ' ', '2', '  ', '3', '\n']
          print list(t.itertext())

   * Deprecated: using an element as a Boolean (i.e., ‘if elem:’) would
     return true if the element had any children, or false if there were
     no children.  This behaviour is confusing – ‘None’ is false, but so
     is a childless element?  – so it will now trigger a *note
     FutureWarning: 32e.  In your code, you should be explicit: write
     ‘len(elem) != 0’ if you’re interested in the number of children, or
     ‘elem is not None’.

Fredrik Lundh develops ElementTree and produced the 1.3 version; you can
read his article describing 1.3 at
‘http://effbot.org/zone/elementtree-13-intro.htm’.  Florent Xicluna
updated the version included with Python, after discussions on
python-dev and in bpo-6472(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6472


File: python.info,  Node: 构建和 C API 的改变<8>,  Next: Other Changes and Fixes,  Prev: 新增和改进的模块,  Up: Python 2 7 有什么新变化

1.10.12 构建和 C API 的改变
---------------------------

Changes to Python’s build process and to the C API include:

   * The latest release of the GNU Debugger, GDB 7, can be scripted
     using Python(1).  When you begin debugging an executable program P,
     GDB will look for a file named ‘P-gdb.py’ and automatically read
     it.  Dave Malcolm contributed a ‘python-gdb.py’ that adds a number
     of commands useful when debugging Python itself.  For example,
     ‘py-up’ and ‘py-down’ go up or down one Python stack frame, which
     usually corresponds to several C stack frames.  ‘py-print’ prints
     the value of a Python variable, and ‘py-bt’ prints the Python stack
     trace.  (Added as a result of bpo-8032(2).)

   * If you use the ‘.gdbinit’ file provided with Python, the "pyo"
     macro in the 2.7 version now works correctly when the thread being
     debugged doesn’t hold the GIL; the macro now acquires it before
     printing.  (Contributed by Victor Stinner; bpo-3632(3).)

   * *note Py_AddPendingCall(): cf1. is now thread-safe, letting any
     worker thread submit notifications to the main Python thread.  This
     is particularly useful for asynchronous IO operations.
     (Contributed by Kristján Valur Jónsson; bpo-4293(4).)

   * New function: *note PyCode_NewEmpty(): cf2. creates an empty code
     object; only the filename, function name, and first line number are
     required.  This is useful for extension modules that are attempting
     to construct a more useful traceback stack.  Previously such
     extensions needed to call *note PyCode_New(): 273, which had many
     more arguments.  (Added by Jeffrey Yasskin.)

   * New function: *note PyErr_NewExceptionWithDoc(): c07. creates a new
     exception class, just as the existing *note PyErr_NewException():
     c08. does, but takes an extra ‘char *’ argument containing the
     docstring for the new exception class.  (Added by ’lekma’ on the
     Python bug tracker; bpo-7033(5).)

   * New function: *note PyFrame_GetLineNumber(): cf3. takes a frame
     object and returns the line number that the frame is currently
     executing.  Previously code would need to get the index of the
     bytecode instruction currently executing, and then look up the line
     number corresponding to that address.  (Added by Jeffrey Yasskin.)

   * New functions: *note PyLong_AsLongAndOverflow(): c05. and *note
     PyLong_AsLongLongAndOverflow(): c04. approximates a Python long
     integer as a C ‘long’ or ‘long long’.  If the number is too large
     to fit into the output type, an `overflow' flag is set and returned
     to the caller.  (Contributed by Case Van Horsen; bpo-7528(6) and
     bpo-7767(7).)

   * New function: stemming from the rewrite of string-to-float
     conversion, a new *note PyOS_string_to_double(): c2b. function was
     added.  The old ‘PyOS_ascii_strtod()’ and ‘PyOS_ascii_atof()’
     functions are now deprecated.

   * New function: *note PySys_SetArgvEx(): c02. sets the value of
     ‘sys.argv’ and can optionally update ‘sys.path’ to include the
     directory containing the script named by ‘sys.argv[0]’ depending on
     the value of an `updatepath' parameter.

     This function was added to close a security hole for applications
     that embed Python.  The old function, *note PySys_SetArgv(): cf4,
     would always update ‘sys.path’, and sometimes it would add the
     current directory.  This meant that, if you ran an application
     embedding Python in a directory controlled by someone else,
     attackers could put a Trojan-horse module in the directory (say, a
     file named ‘os.py’) that your application would then import and
     run.

     If you maintain a C/C++ application that embeds Python, check
     whether you’re calling *note PySys_SetArgv(): cf4. and carefully
     consider whether the application should be using *note
     PySys_SetArgvEx(): c02. with `updatepath' set to false.

     Security issue reported as CVE-2008-5983(8); discussed in
     bpo-5753(9), and fixed by Antoine Pitrou.

   * New macros: the Python header files now define the following
     macros: ‘Py_ISALNUM’, ‘Py_ISALPHA’, ‘Py_ISDIGIT’, ‘Py_ISLOWER’,
     ‘Py_ISSPACE’, ‘Py_ISUPPER’, ‘Py_ISXDIGIT’, ‘Py_TOLOWER’, and
     ‘Py_TOUPPER’.  All of these functions are analogous to the C
     standard macros for classifying characters, but ignore the current
     locale setting, because in several places Python needs to analyze
     characters in a locale-independent way.  (Added by Eric Smith;
     bpo-5793(10).)

   * Removed function: ‘PyEval_CallObject’ is now only available as a
     macro.  A function version was being kept around to preserve ABI
     linking compatibility, but that was in 1997; it can certainly be
     deleted by now.  (Removed by Antoine Pitrou; bpo-8276(11).)

   * New format codes: the ‘PyFormat_FromString()’,
     ‘PyFormat_FromStringV()’, and *note PyErr_Format(): 7b3. functions
     now accept ‘%lld’ and ‘%llu’ format codes for displaying C’s ‘long
     long’ types.  (Contributed by Mark Dickinson; bpo-7228(12).)

   * The complicated interaction between threads and process forking has
     been changed.  Previously, the child process created by *note
     os.fork(): 969. might fail because the child is created with only a
     single thread running, the thread performing the *note os.fork():
     969.  If other threads were holding a lock, such as Python’s import
     lock, when the fork was performed, the lock would still be marked
     as "held" in the new process.  But in the child process nothing
     would ever release the lock, since the other threads weren’t
     replicated, and the child process would no longer be able to
     perform imports.

     Python 2.7 acquires the import lock before performing an *note
     os.fork(): 969, and will also clean up any locks created using the
     *note threading: 10a. module.  C extension modules that have
     internal locks, or that call ‘fork()’ themselves, will not benefit
     from this clean-up.

     (Fixed by Thomas Wouters; bpo-1590864(13).)

   * The *note Py_Finalize(): cf5. function now calls the internal
     ‘threading._shutdown()’ function; this prevents some exceptions
     from being raised when an interpreter shuts down.  (Patch by Adam
     Olsen; bpo-1722344(14).)

   * When using the *note PyMemberDef: 42e. structure to define
     attributes of a type, Python will no longer let you try to delete
     or set a ‘T_STRING_INPLACE’ attribute.

   * Global symbols defined by the *note ctypes: 2b. module are now
     prefixed with ‘Py’, or with ‘_ctypes’.  (Implemented by Thomas
     Heller; bpo-3102(15).)

   * New configure option: the ‘--with-system-expat’ switch allows
     building the ‘pyexpat’ module to use the system Expat library.
     (Contributed by Arfrever Frehtes Taifersar Arahesis; bpo-7609(16).)

   * New configure option: the ‘--with-valgrind’ option will now disable
     the pymalloc allocator, which is difficult for the Valgrind
     memory-error detector to analyze correctly.  Valgrind will
     therefore be better at detecting memory leaks and overruns.
     (Contributed by James Henstridge; bpo-2422(17).)

   * New configure option: you can now supply an empty string to
     ‘--with-dbmliborder=’ in order to disable all of the various DBM
     modules.  (Added by Arfrever Frehtes Taifersar Arahesis;
     bpo-6491(18).)

   * The ‘configure’ script now checks for floating-point rounding bugs
     on certain 32-bit Intel chips and defines a ‘X87_DOUBLE_ROUNDING’
     preprocessor definition.  No code currently uses this definition,
     but it’s available if anyone wishes to use it.  (Added by Mark
     Dickinson; bpo-2937(19).)

     ‘configure’ also now sets a ‘LDCXXSHARED’ Makefile variable for
     supporting C++ linking.  (Contributed by Arfrever Frehtes Taifersar
     Arahesis; bpo-1222585(20).)

   * The build process now creates the necessary files for pkg-config
     support.  (Contributed by Clinton Roy; bpo-3585(21).)

   * The build process now supports Subversion 1.7.  (Contributed by
     Arfrever Frehtes Taifersar Arahesis; bpo-6094(22).)

* Menu:

* 胶囊::
* 特定于 Windows 的更改：::
* 特定于 Mac OS X 的更改：::
* 特定于 FreeBSD 的更改：::

   ---------- Footnotes ----------

   (1) https://sourceware.org/gdb/current/onlinedocs/gdb/Python.html

   (2) https://bugs.python.org/issue8032

   (3) https://bugs.python.org/issue3632

   (4) https://bugs.python.org/issue4293

   (5) https://bugs.python.org/issue7033

   (6) https://bugs.python.org/issue7528

   (7) https://bugs.python.org/issue7767

   (8) https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983

   (9) https://bugs.python.org/issue5753

   (10) https://bugs.python.org/issue5793

   (11) https://bugs.python.org/issue8276

   (12) https://bugs.python.org/issue7228

   (13) https://bugs.python.org/issue1590864

   (14) https://bugs.python.org/issue1722344

   (15) https://bugs.python.org/issue3102

   (16) https://bugs.python.org/issue7609

   (17) https://bugs.python.org/issue2422

   (18) https://bugs.python.org/issue6491

   (19) https://bugs.python.org/issue2937

   (20) https://bugs.python.org/issue1222585

   (21) https://bugs.python.org/issue3585

   (22) https://bugs.python.org/issue6094


File: python.info,  Node: 胶囊,  Next: 特定于 Windows 的更改：,  Up: 构建和 C API 的改变<8>

1.10.12.1 胶囊
..............

Python 3.1 adds a new C datatype, *note PyCapsule: c0f, for providing a
C API to an extension module.  A capsule is essentially the holder of a
C ‘void *’ pointer, and is made available as a module attribute; for
example, the *note socket: f0. module’s API is exposed as ‘socket.CAPI’,
and *note unicodedata: 11b. exposes ‘ucnhash_CAPI’.  Other extensions
can import the module, access its dictionary to get the capsule object,
and then get the ‘void *’ pointer, which will usually point to an array
of pointers to the module’s various API functions.

There is an existing data type already used for this, ‘PyCObject’, but
it doesn’t provide type safety.  Evil code written in pure Python could
cause a segmentation fault by taking a ‘PyCObject’ from module A and
somehow substituting it for the ‘PyCObject’ in module B. Capsules know
their own name, and getting the pointer requires providing the name:

     void *vtable;

     if (!PyCapsule_IsValid(capsule, "mymodule.CAPI") {
             PyErr_SetString(PyExc_ValueError, "argument type invalid");
             return NULL;
     }

     vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI");

You are assured that ‘vtable’ points to whatever you’re expecting.  If a
different capsule was passed in, *note PyCapsule_IsValid(): cf8. would
detect the mismatched name and return false.  Refer to *note
给扩展模块提供C API: cf9. for more information on using these objects.

Python 2.7 now uses capsules internally to provide various
extension-module APIs, but the ‘PyCObject_AsVoidPtr()’ was modified to
handle capsules, preserving compile-time compatibility with the
‘CObject’ interface.  Use of ‘PyCObject_AsVoidPtr()’ will signal a *note
PendingDeprecationWarning: 27a, which is silent by default.

Implemented in Python 3.1 and backported to 2.7 by Larry Hastings;
discussed in bpo-5630(1).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5630


File: python.info,  Node: 特定于 Windows 的更改：,  Next: 特定于 Mac OS X 的更改：,  Prev: 胶囊,  Up: 构建和 C API 的改变<8>

1.10.12.2 特定于 Windows 的更改：
.................................

   * The *note msvcrt: b7. module now contains some constants from the
     ‘crtassem.h’ header file: ‘CRT_ASSEMBLY_VERSION’,
     ‘VC_ASSEMBLY_PUBLICKEYTOKEN’, and ‘LIBRARIES_ASSEMBLY_NAME_PREFIX’.
     (Contributed by David Cournapeau; bpo-4365(1).)

   * The ‘_winreg’ module for accessing the registry now implements the
     ‘CreateKeyEx()’ and ‘DeleteKeyEx()’ functions, extended versions of
     previously-supported functions that take several extra arguments.
     The ‘DisableReflectionKey()’, ‘EnableReflectionKey()’, and
     ‘QueryReflectionKey()’ were also tested and documented.
     (Implemented by Brian Curtin: bpo-7347(2).)

   * The new ‘_beginthreadex()’ API is used to start threads, and the
     native thread-local storage functions are now used.  (Contributed
     by Kristján Valur Jónsson; bpo-3582(3).)

   * The *note os.kill(): cfb. function now works on Windows.  The
     signal value can be the constants ‘CTRL_C_EVENT’,
     ‘CTRL_BREAK_EVENT’, or any integer.  The first two constants will
     send ‘Control-C’ and ‘Control-Break’ keystroke events to
     subprocesses; any other value will use the ‘TerminateProcess()’
     API. (Contributed by Miki Tebeka; bpo-1220212(4).)

   * The *note os.listdir(): a49. function now correctly fails for an
     empty path.  (Fixed by Hirokazu Yamamoto; bpo-5913(5).)

   * The ‘mimelib’ module will now read the MIME database from the
     Windows registry when initializing.  (Patch by Gabriel Genellina;
     bpo-4969(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4365

   (2) https://bugs.python.org/issue7347

   (3) https://bugs.python.org/issue3582

   (4) https://bugs.python.org/issue1220212

   (5) https://bugs.python.org/issue5913

   (6) https://bugs.python.org/issue4969


File: python.info,  Node: 特定于 Mac OS X 的更改：,  Next: 特定于 FreeBSD 的更改：,  Prev: 特定于 Windows 的更改：,  Up: 构建和 C API 的改变<8>

1.10.12.3 特定于 Mac OS X 的更改：
..................................

   * The path ‘/Library/Python/2.7/site-packages’ is now appended to
     ‘sys.path’, in order to share added packages between the system
     installation and a user-installed copy of the same version.
     (Changed by Ronald Oussoren; bpo-4865(1).)

          在 2.7.13 版更改: As of 2.7.13, this change was removed.
          ‘/Library/Python/2.7/site-packages’, the site-packages
          directory used by the Apple-supplied system Python 2.7 is no
          longer appended to ‘sys.path’ for user-installed Pythons such
          as from the python.org installers.  As of macOS 10.12, Apple
          changed how the system site-packages directory is configured,
          which could cause installation of pip components, like
          setuptools, to fail.  Packages installed for the system Python
          will no longer be shared with user-installed Pythons.
          (bpo-28440(2))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4865

   (2) https://bugs.python.org/issue28440


File: python.info,  Node: 特定于 FreeBSD 的更改：,  Prev: 特定于 Mac OS X 的更改：,  Up: 构建和 C API 的改变<8>

1.10.12.4 特定于 FreeBSD 的更改：
.................................

   * FreeBSD 7.1’s ‘SO_SETFIB’ constant, used with
     ‘getsockopt()’/‘setsockopt()’ to select an alternate routing table,
     is now available in the *note socket: f0. module.  (Added by Kyle
     VanderBeek; bpo-8235(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8235


File: python.info,  Node: Other Changes and Fixes,  Next: 移植到 Python 2 7,  Prev: 构建和 C API 的改变<8>,  Up: Python 2 7 有什么新变化

1.10.13 Other Changes and Fixes
-------------------------------

   * Two benchmark scripts, ‘iobench’ and ‘ccbench’, were added to the
     ‘Tools’ directory.  ‘iobench’ measures the speed of the built-in
     file I/O objects returned by *note open(): 4f8. while performing
     various operations, and ‘ccbench’ is a concurrency benchmark that
     tries to measure computing throughput, thread switching latency,
     and IO processing bandwidth when performing several tasks using a
     varying number of threads.

   * The ‘Tools/i18n/msgfmt.py’ script now understands plural forms in
     ‘.po’ files.  (Fixed by Martin von Löwis; bpo-5464(1).)

   * When importing a module from a ‘.pyc’ or ‘.pyo’ file with an
     existing ‘.py’ counterpart, the ‘co_filename’ attributes of the
     resulting code objects are overwritten when the original filename
     is obsolete.  This can happen if the file has been renamed, moved,
     or is accessed through different paths.  (Patch by Ziga Seilnacht
     and Jean-Paul Calderone; bpo-1180193(2).)

   * The ‘regrtest.py’ script now takes a ‘--randseed=’ switch that
     takes an integer that will be used as the random seed for the ‘-r’
     option that executes tests in random order.  The ‘-r’ option also
     reports the seed that was used (Added by Collin Winter.)

   * Another ‘regrtest.py’ switch is ‘-j’, which takes an integer
     specifying how many tests run in parallel.  This allows reducing
     the total runtime on multi-core machines.  This option is
     compatible with several other options, including the ‘-R’ switch
     which is known to produce long runtimes.  (Added by Antoine Pitrou,
     bpo-6152(3).)  This can also be used with a new ‘-F’ switch that
     runs selected tests in a loop until they fail.  (Added by Antoine
     Pitrou; bpo-7312(4).)

   * When executed as a script, the ‘py_compile.py’ module now accepts
     ‘'-'’ as an argument, which will read standard input for the list
     of filenames to be compiled.  (Contributed by Piotr Ożarowski;
     bpo-8233(5).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5464

   (2) https://bugs.python.org/issue1180193

   (3) https://bugs.python.org/issue6152

   (4) https://bugs.python.org/issue7312

   (5) https://bugs.python.org/issue8233


File: python.info,  Node: 移植到 Python 2 7,  Next: New Features Added to Python 2 7 Maintenance Releases,  Prev: Other Changes and Fixes,  Up: Python 2 7 有什么新变化

1.10.14 移植到 Python 2.7
-------------------------

This section lists previously described changes and other bugfixes that
may require changes to your code:

   * The *note range(): 9c6. function processes its arguments more
     consistently; it will now call *note __int__(): 18c. on non-float,
     non-integer arguments that are supplied to it.  (Fixed by Alexander
     Belopolsky; bpo-1533(1).)

   * The string *note format(): 4e3. method changed the default
     precision used for floating-point and complex numbers from 6
     decimal places to 12, which matches the precision used by *note
     str(): 339.  (Changed by Eric Smith; bpo-5920(2).)

   * Because of an optimization for the *note with: 6f2. statement, the
     special methods *note __enter__(): c9d. and *note __exit__(): c9e.
     must belong to the object’s type, and cannot be directly attached
     to the object’s instance.  This affects new-style classes (derived
     from *note object: 2b1.) and C extension types.  (bpo-6101(3).)

   * Due to a bug in Python 2.6, the `exc_value' parameter to *note
     __exit__(): c9e. methods was often the string representation of the
     exception, not an instance.  This was fixed in 2.7, so `exc_value'
     will be an instance as expected.  (Fixed by Florent Xicluna;
     bpo-7853(4).)

   * When a restricted set of attributes were set using ‘__slots__’,
     deleting an unset attribute would not raise *note AttributeError:
     3a3. as you would expect.  Fixed by Benjamin Peterson;
     bpo-7604(5).)

In the standard library:

   * Operations with *note datetime: 195. instances that resulted in a
     year falling outside the supported range didn’t always raise *note
     OverflowError: 968.  Such errors are now checked more carefully and
     will now raise the exception.  (Reported by Mark Leander, patch by
     Anand B. Pillai and Alexander Belopolsky; bpo-7150(6).)

   * When using *note Decimal: 189. instances with a string’s *note
     format(): 4e3. method, the default alignment was previously
     left-alignment.  This has been changed to right-alignment, which
     might change the output of your programs.  (Changed by Mark
     Dickinson; bpo-6857(7).)

     Comparisons involving a signaling NaN value (or ‘sNAN’) now signal
     *note InvalidOperation: 9f3. instead of silently returning a true
     or false value depending on the comparison operator.  Quiet NaN
     values (or ‘NaN’) are now hashable.  (Fixed by Mark Dickinson;
     bpo-7279(8).)

   * The ElementTree library, ‘xml.etree’, no longer escapes ampersands
     and angle brackets when outputting an XML processing instruction
     (which looks like ‘<?xml-stylesheet href="#style1"?>’) or comment
     (which looks like ‘<!– comment –>’).  (Patch by Neil Muller;
     bpo-2746(9).)

   * The ‘readline()’ method of ‘StringIO’ objects now does nothing when
     a negative length is requested, as other file-like objects do.
     (bpo-7348(10)).

   * The *note syslog: 100. module will now use the value of
     ‘sys.argv[0]’ as the identifier instead of the previous default
     value of ‘'python'’.  (Changed by Sean Reifschneider;
     bpo-8451(11).)

   * The *note tarfile: 102. module’s default error handling has
     changed, to no longer suppress fatal errors.  The default error
     level was previously 0, which meant that errors would only result
     in a message being written to the debug log, but because the debug
     log is not activated by default, these errors go unnoticed.  The
     default error level is now 1, which raises an exception if there’s
     an error.  (Changed by Lars Gustäbel; bpo-7357(12).)

   * The ‘urlparse’ module’s ‘urlsplit()’ now handles unknown URL
     schemes in a fashion compliant with RFC 3986(13): if the URL is of
     the form ‘"<something>://..."’, the text before the ‘://’ is
     treated as the scheme, even if it’s a made-up scheme that the
     module doesn’t know about.  This change may break code that worked
     around the old behaviour.  For example, Python 2.6.4 or 2.5 will
     return the following:

          >>> import urlparse
          >>> urlparse.urlsplit('invented://host/filename?query')
          ('invented', '', '//host/filename?query', '', '')

     Python 2.7 (and Python 2.6.5) will return:

          >>> import urlparse
          >>> urlparse.urlsplit('invented://host/filename?query')
          ('invented', 'host', '/filename?query', '', '')

     (Python 2.7 actually produces slightly different output, since it
     returns a named tuple instead of a standard tuple.)

对于C 扩展模块：

   * C extensions that use integer format codes with the ‘PyArg_Parse*’
     family of functions will now raise a *note TypeError: 193.
     exception instead of triggering a *note DeprecationWarning: 279.
     (bpo-5080(14)).

   * Use the new *note PyOS_string_to_double(): c2b. function instead of
     the old ‘PyOS_ascii_strtod()’ and ‘PyOS_ascii_atof()’ functions,
     which are now deprecated.

对于嵌入Python的应用程序：

   * The *note PySys_SetArgvEx(): c02. function was added, letting
     applications close a security hole when the existing *note
     PySys_SetArgv(): cf4. function was used.  Check whether you’re
     calling *note PySys_SetArgv(): cf4. and carefully consider whether
     the application should be using *note PySys_SetArgvEx(): c02. with
     `updatepath' set to false.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1533

   (2) https://bugs.python.org/issue5920

   (3) https://bugs.python.org/issue6101

   (4) https://bugs.python.org/issue7853

   (5) https://bugs.python.org/issue7604

   (6) https://bugs.python.org/issue7150

   (7) https://bugs.python.org/issue6857

   (8) https://bugs.python.org/issue7279

   (9) https://bugs.python.org/issue2746

   (10) https://bugs.python.org/issue7348

   (11) https://bugs.python.org/issue8451

   (12) https://bugs.python.org/issue7357

   (13) https://tools.ietf.org/html/rfc3986.html

   (14) https://bugs.python.org/issue5080


File: python.info,  Node: New Features Added to Python 2 7 Maintenance Releases,  Next: 致谢,  Prev: 移植到 Python 2 7,  Up: Python 2 7 有什么新变化

1.10.15 New Features Added to Python 2.7 Maintenance Releases
-------------------------------------------------------------

New features may be added to Python 2.7 maintenance releases when the
situation genuinely calls for it.  Any such additions must go through
the Python Enhancement Proposal process, and make a compelling case for
why they can’t be adequately addressed by either adding the new feature
solely to Python 3, or else by publishing it on the Python Package
Index.

In addition to the specific proposals listed below, there is a general
exemption allowing new ‘-3’ warnings to be added in any Python 2.7
maintenance release.

* Menu:

* Two new environment variables for debug mode::
* PEP 434; IDLE Enhancement Exception for All Branches: PEP 434 IDLE Enhancement Exception for All Branches.
* PEP 466; Network Security Enhancements for Python 2.7: PEP 466 Network Security Enhancements for Python 2 7.
* PEP 477; Backport ensurepip (PEP 453) to Python 2.7: PEP 477 Backport ensurepip PEP 453 to Python 2 7.
* PEP 476; Enabling certificate verification by default for stdlib http clients: PEP 476 Enabling certificate verification by default for stdlib http clients<2>.
* PEP 493：适用于Python 2.7 的 HTTPS 验证迁移工具: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具.
* New make regen-all build target: New make regen-all build target<3>.
* Removal of make touch build target: Removal of make touch build target<3>.


File: python.info,  Node: Two new environment variables for debug mode,  Next: PEP 434 IDLE Enhancement Exception for All Branches,  Up: New Features Added to Python 2 7 Maintenance Releases

1.10.15.1 Two new environment variables for debug mode
......................................................

In debug mode, the ‘[xxx refs]’ statistic is not written by default, the
‘PYTHONSHOWREFCOUNT’ environment variable now must also be set.
(Contributed by Victor Stinner; bpo-31733(1).)

When Python is compiled with ‘COUNT_ALLOC’ defined, allocation counts
are no longer dumped by default anymore: the ‘PYTHONSHOWALLOCCOUNT’
environment variable must now also be set.  Moreover, allocation counts
are now dumped into stderr, rather than stdout.  (Contributed by Victor
Stinner; bpo-31692(2).)

2.7.15 新版功能.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31733

   (2) https://bugs.python.org/issue31692


File: python.info,  Node: PEP 434 IDLE Enhancement Exception for All Branches,  Next: PEP 466 Network Security Enhancements for Python 2 7,  Prev: Two new environment variables for debug mode,  Up: New Features Added to Python 2 7 Maintenance Releases

1.10.15.2 PEP 434: IDLE Enhancement Exception for All Branches
..............................................................

PEP 434(1) describes a general exemption for changes made to the IDLE
development environment shipped along with Python.  This exemption makes
it possible for the IDLE developers to provide a more consistent user
experience across all supported versions of Python 2 and 3.

For details of any IDLE changes, refer to the NEWS file for the specific
release.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0434


File: python.info,  Node: PEP 466 Network Security Enhancements for Python 2 7,  Next: PEP 477 Backport ensurepip PEP 453 to Python 2 7,  Prev: PEP 434 IDLE Enhancement Exception for All Branches,  Up: New Features Added to Python 2 7 Maintenance Releases

1.10.15.3 PEP 466: Network Security Enhancements for Python 2.7
...............................................................

PEP 466(1) describes a number of network security enhancement proposals
that have been approved for inclusion in Python 2.7 maintenance
releases, with the first of those changes appearing in the Python 2.7.7
release.

PEP 466(2) Python 2.7.7 中添加的相关功能：

   * *note hmac.compare_digest(): a14. was backported from Python 3 to
     make a timing attack resistant comparison operation available to
     Python 2 applications.  (Contributed by Alex Gaynor; bpo-21306(3).)

   * OpenSSL 1.0.1g was upgraded in the official Windows installers
     published on python.org.  (Contributed by Zachary Ware;
     bpo-21462(4).)

PEP 466(5) Python 2.7.8 中添加的相关功能：

   * *note hashlib.pbkdf2_hmac(): 7ef. was backported from Python 3 to
     make a hashing algorithm suitable for secure password storage
     broadly available to Python 2 applications.  (Contributed by Alex
     Gaynor; bpo-21304(6).)

   * OpenSSL 1.0.1h was upgraded for the official Windows installers
     published on python.org.  (contributed by Zachary Ware in
     bpo-21671(7) for CVE-2014-0224)

PEP 466(8) Python 2.7.9 中添加的相关功能：

   * Most of Python 3.4’s *note ssl: f4. module was backported.  This
     means *note ssl: f4. now supports Server Name Indication, TLS1.x
     settings, access to the platform certificate store, the *note
     SSLContext: 3ec. class, and other features.  (Contributed by Alex
     Gaynor and David Reid; bpo-21308(9).)

     Refer to the "Version added: 2.7.9" notes in the module
     documentation for specific details.

   * *note os.urandom(): 4d9. was changed to cache a file descriptor to
     ‘/dev/urandom’ instead of reopening ‘/dev/urandom’ on every call.
     (Contributed by Alex Gaynor; bpo-21305(10).)

   * *note hashlib.algorithms_guaranteed: d04. and *note
     hashlib.algorithms_available: d05. were backported from Python 3 to
     make it easier for Python 2 applications to select the strongest
     available hash algorithm.  (Contributed by Alex Gaynor in
     bpo-21307(11))

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0466

   (2) https://www.python.org/dev/peps/pep-0466

   (3) https://bugs.python.org/issue21306

   (4) https://bugs.python.org/issue21462

   (5) https://www.python.org/dev/peps/pep-0466

   (6) https://bugs.python.org/issue21304

   (7) https://bugs.python.org/issue21671

   (8) https://www.python.org/dev/peps/pep-0466

   (9) https://bugs.python.org/issue21308

   (10) https://bugs.python.org/issue21305

   (11) https://bugs.python.org/issue21307


File: python.info,  Node: PEP 477 Backport ensurepip PEP 453 to Python 2 7,  Next: PEP 476 Enabling certificate verification by default for stdlib http clients<2>,  Prev: PEP 466 Network Security Enhancements for Python 2 7,  Up: New Features Added to Python 2 7 Maintenance Releases

1.10.15.4 PEP 477: Backport ensurepip (PEP 453) to Python 2.7
.............................................................

PEP 477(1) approves the inclusion of the PEP 453(2) ensurepip module and
the improved documentation that was enabled by it in the Python 2.7
maintenance releases, appearing first in the Python 2.7.9 release.

* Menu:

* Bootstrapping pip By Default: Bootstrapping pip By Default<2>.
* 文档更改: 文档更改<2>.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0477

   (2) https://www.python.org/dev/peps/pep-0453


File: python.info,  Node: Bootstrapping pip By Default<2>,  Next: 文档更改<2>,  Up: PEP 477 Backport ensurepip PEP 453 to Python 2 7

1.10.15.5 Bootstrapping pip By Default
......................................

The new *note ensurepip: 7a. module (defined in PEP 453(1)) provides a
standard cross-platform mechanism to bootstrap the pip installer into
Python installations.  The version of ‘pip’ included with Python 2.7.9
is ‘pip’ 1.5.6, and future 2.7.x maintenance releases will update the
bundled version to the latest version of ‘pip’ that is available at the
time of creating the release candidate.

By default, the commands ‘pip’, ‘pipX’ and ‘pipX.Y’ will be installed on
all platforms (where X.Y stands for the version of the Python
installation), along with the ‘pip’ Python package and its dependencies.

For CPython *note source builds on POSIX systems: 7fc, the ‘make
install’ and ‘make altinstall’ commands do not bootstrap ‘pip’ by
default.  This behaviour can be controlled through configure options,
and overridden through Makefile options.

On Windows and Mac OS X, the CPython installers now default to
installing ‘pip’ along with CPython itself (users may opt out of
installing it during the installation process).  Window users will need
to opt in to the automatic ‘PATH’ modifications to have ‘pip’ available
from the command line by default, otherwise it can still be accessed
through the Python launcher for Windows as ‘py -m pip’.

As discussed in the PEP(2), platform packagers may choose not to install
these commands by default, as long as, when invoked, they provide clear
and simple directions on how to install them on that platform (usually
using the system package manager).

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0453

   (2) 
https://www.python.org/dev/peps/pep-0477/#disabling-ensurepip-by-downstream-distributors


File: python.info,  Node: 文档更改<2>,  Prev: Bootstrapping pip By Default<2>,  Up: PEP 477 Backport ensurepip PEP 453 to Python 2 7

1.10.15.6 文档更改
..................

As part of this change, the *note 安装 Python 模块: 7fe. and *note 分发
Python 模块: 7ff. sections of the documentation have been completely
redesigned as short getting started and FAQ documents.  Most packaging
documentation has now been moved out to the Python Packaging Authority
maintained Python Packaging User Guide(1) and the documentation of the
individual projects.

However, as this migration is currently still incomplete, the legacy
versions of those guides remaining available as *note
安装Python模块（旧版）: 800. and *note 分发 Python 模块（遗留版本）:
801.

参见
....

PEP 453(2) – Python安装中pip的显式引导

     PEP 由Donald Stufft 和 Nick Coghlan 撰写，由 Donald Stufft，Nick
     Coghlan，Martin von Löwis 和 Ned Deily 实现。

   ---------- Footnotes ----------

   (1) http://packaging.python.org

   (2) https://www.python.org/dev/peps/pep-0453


File: python.info,  Node: PEP 476 Enabling certificate verification by default for stdlib http clients<2>,  Next: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具,  Prev: PEP 477 Backport ensurepip PEP 453 to Python 2 7,  Up: New Features Added to Python 2 7 Maintenance Releases

1.10.15.7 PEP 476: Enabling certificate verification by default for stdlib http clients
.......................................................................................

PEP 476(1) updated ‘httplib’ and modules which use it, such as ‘urllib2’
and ‘xmlrpclib’, to now verify that the server presents a certificate
which is signed by a Certificate Authority in the platform trust store
and whose hostname matches the hostname being requested by default,
significantly improving security for many applications.  This change was
made in the Python 2.7.9 release.

For applications which require the old previous behavior, they can pass
an alternate context:

     import urllib2
     import ssl

     # This disables all verification
     context = ssl._create_unverified_context()

     # This allows using a specific certificate for the host, which doesn't need
     # to be in the trust store
     context = ssl.create_default_context(cafile="/path/to/file.crt")

     urllib2.urlopen("https://invalid-cert", context=context)

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0476


File: python.info,  Node: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具,  Next: New make regen-all build target<3>,  Prev: PEP 476 Enabling certificate verification by default for stdlib http clients<2>,  Up: New Features Added to Python 2 7 Maintenance Releases

1.10.15.8 PEP 493：适用于Python 2.7 的 HTTPS 验证迁移工具
.........................................................

PEP 493(1) provides additional migration tools to support a more
incremental infrastructure upgrade process for environments containing
applications and services relying on the historically permissive
processing of server certificates when establishing client HTTPS
connections.  These additions were made in the Python 2.7.12 release.

These tools are intended for use in cases where affected applications
and services can’t be modified to explicitly pass a more permissive SSL
context when establishing the connection.

For applications and services which can’t be modified at all, the new
‘PYTHONHTTPSVERIFY’ environment variable may be set to ‘0’ to revert an
entire Python process back to the default permissive behaviour of Python
2.7.8 and earlier.

For cases where the connection establishment code can’t be modified, but
the overall application can be, the new
‘ssl._https_verify_certificates()’ function can be used to adjust the
default behaviour at runtime.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0493


File: python.info,  Node: New make regen-all build target<3>,  Next: Removal of make touch build target<3>,  Prev: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具,  Up: New Features Added to Python 2 7 Maintenance Releases

1.10.15.9 New ‘make regen-all’ build target
...........................................

To simplify cross-compilation, and to ensure that CPython can reliably
be compiled without requiring an existing version of Python to already
be available, the autotools-based build system no longer attempts to
implicitly recompile generated files based on file modification times.

Instead, a new ‘make regen-all’ command has been added to force
regeneration of these files when desired (e.g.  after an initial version
of Python has already been built based on the pregenerated versions).

More selective regeneration targets are also defined - see
Makefile.pre.in(1) for details.

（由 Victor Stinner 在 bpo-23404(2) 中贡献。）

2.7.14 新版功能.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Makefile.pre.in

   (2) https://bugs.python.org/issue23404


File: python.info,  Node: Removal of make touch build target<3>,  Prev: New make regen-all build target<3>,  Up: New Features Added to Python 2 7 Maintenance Releases

1.10.15.10 Removal of ‘make touch’ build target
...............................................

The ‘make touch’ build target previously used to request implicit
regeneration of generated files by updating their modification times has
been removed.

It has been replaced by the new ‘make regen-all’ target.

（由 Victor Stinner 在 bpo-23404(1) 中贡献。）

在 2.7.14 版更改.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23404


File: python.info,  Node: 致谢,  Prev: New Features Added to Python 2 7 Maintenance Releases,  Up: Python 2 7 有什么新变化

1.10.16 致谢
------------

作者要感谢以下人员为本文的各种草案提供建议，更正和帮助： Nick Coghlan,
Philip Jenvey, Ryan Lovett, R. David Murray, Hugh Secker-Walker.


File: python.info,  Node: Python 2 6 有什么新变化,  Next: Python 2 5 有什么新变化,  Prev: Python 2 7 有什么新变化,  Up: Python的新变化

1.11 Python 2.6 有什么新变化
============================


作者: A.M. Kuchling (amk at amk.ca)

本文介绍了 Python 2.6 的新特性，它发布于 2008 年 10 月 1 日。 发布日程说
明见 PEP 361(1)。

The major theme of Python 2.6 is preparing the migration path to Python
3.0, a major redesign of the language.  Whenever possible, Python 2.6
incorporates new features and syntax from 3.0 while remaining compatible
with existing code by not removing older features or syntax.  When it’s
not possible to do that, Python 2.6 tries to do what it can, adding
compatibility functions in a ‘future_builtins’ module and a ‘-3’ switch
to warn about usages that will become unsupported in 3.0.

Some significant new packages have been added to the standard library,
such as the *note multiprocessing: b8. and *note json: a5. modules, but
there aren’t many new features that aren’t related to Python 3.0 in some
way.

Python 2.6 also sees a number of improvements and bugfixes throughout
the source.  A search through the change logs finds there were 259
patches applied and 612 bugs fixed between Python 2.5 and 2.6.  Both
figures are likely to be underestimates.

This article doesn’t attempt to provide a complete specification of the
new features, but instead provides a convenient overview.  For full
details, you should refer to the documentation for Python 2.6.  If you
want to understand the rationale for the design and implementation,
refer to the PEP for a particular new feature.  Whenever possible,
"What’s New in Python" links to the bug/patch item for each change.

* Menu:

* Python 3.0: Python 3 0.
* 开发过程的变化::
* PEP 343; "with" 语句: PEP 343 "with" 语句.
* PEP 366; 从主模块显式相对导入: PEP 366 从主模块显式相对导入.
* PEP 370; 分用户的 site-packages 目录: PEP 370 分用户的 site-packages 目录.
* PEP 371; 多任务处理包: PEP 371 多任务处理包.
* PEP 3101; 高级字符串格式: PEP 3101 高级字符串格式.
* PEP 3105; print 改为函数: PEP 3105 print 改为函数.
* PEP 3110; 异常处理的变更: PEP 3110 异常处理的变更.
* PEP 3112; 字节字面值: PEP 3112 字节字面值.
* PEP 3116; 新 I/O 库: PEP 3116 新 I/O 库.
* PEP 3118; 修改缓冲区协议: PEP 3118 修改缓冲区协议.
* PEP 3119; 抽象基类: PEP 3119 抽象基类.
* PEP 3127; 整型文字支持和语法: PEP 3127 整型文字支持和语法.
* PEP 3129; 类装饰器: PEP 3129 类装饰器.
* PEP 3141; A Type Hierarchy for Numbers: PEP 3141 A Type Hierarchy for Numbers.
* 其他语言特性修改: 其他语言特性修改<10>.
* 新增和改进的模块: 新增和改进的模块<2>.
* Deprecations and Removals::
* 构建和 C API 的改变: 构建和 C API 的改变<9>.
* 移植到Python 2.6: 移植到Python 2 6.
* 致谢: 致谢<2>.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0361


File: python.info,  Node: Python 3 0,  Next: 开发过程的变化,  Up: Python 2 6 有什么新变化

1.11.1 Python 3.0
-----------------

The development cycle for Python versions 2.6 and 3.0 was synchronized,
with the alpha and beta releases for both versions being made on the
same days.  The development of 3.0 has influenced many features in 2.6.

Python 3.0 is a far-ranging redesign of Python that breaks compatibility
with the 2.x series.  This means that existing Python code will need
some conversion in order to run on Python 3.0.  However, not all the
changes in 3.0 necessarily break compatibility.  In cases where new
features won’t cause existing code to break, they’ve been backported to
2.6 and are described in this document in the appropriate place.  Some
of the 3.0-derived features are:

   * A *note __complex__(): 18e. method for converting objects to a
     complex number.

   * Alternate syntax for catching exceptions: ‘except TypeError as
     exc’.

   * The addition of *note functools.reduce(): c77. as a synonym for the
     built-in ‘reduce()’ function.

Python 3.0 adds several new built-in functions and changes the semantics
of some existing builtins.  Functions that are new in 3.0 such as *note
bin(): c48. have simply been added to Python 2.6, but existing builtins
haven’t been changed; instead, the ‘future_builtins’ module has versions
with the new 3.0 semantics.  Code written to be compatible with 3.0 can
do ‘from future_builtins import hex, map’ as necessary.

A new command-line switch, ‘-3’, enables warnings about features that
will be removed in Python 3.0.  You can run code with this switch to see
how much work will be necessary to port code to 3.0.  The value of this
switch is available to Python code as the boolean variable
‘sys.py3kwarning’, and to C extension code as ‘Py_Py3kWarningFlag’.

参见
....

The 3xxx series of PEPs, which contains proposals for Python 3.0.  PEP
3000(1) describes the development process for Python 3.0.  Start with
PEP 3100(2) that describes the general goals for Python 3.0, and then
explore the higher-numbered PEPS that propose specific features.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3000

   (2) https://www.python.org/dev/peps/pep-3100


File: python.info,  Node: 开发过程的变化,  Next: PEP 343 "with" 语句,  Prev: Python 3 0,  Up: Python 2 6 有什么新变化

1.11.2 开发过程的变化
---------------------

While 2.6 was being developed, the Python development process underwent
two significant changes: we switched from SourceForge’s issue tracker to
a customized Roundup installation, and the documentation was converted
from LaTeX to reStructuredText.

* Menu:

* New Issue Tracker; Roundup: New Issue Tracker Roundup.
* 新的文档格式：使用 Sphinx 的 reStructuredText::


File: python.info,  Node: New Issue Tracker Roundup,  Next: 新的文档格式：使用 Sphinx 的 reStructuredText,  Up: 开发过程的变化

1.11.2.1 New Issue Tracker: Roundup
...................................

For a long time, the Python developers had been growing increasingly
annoyed by SourceForge’s bug tracker.  SourceForge’s hosted solution
doesn’t permit much customization; for example, it wasn’t possible to
customize the life cycle of issues.

The infrastructure committee of the Python Software Foundation therefore
posted a call for issue trackers, asking volunteers to set up different
products and import some of the bugs and patches from SourceForge.  Four
different trackers were examined: Jira(1), Launchpad(2), Roundup(3), and
Trac(4).  The committee eventually settled on Jira and Roundup as the
two candidates.  Jira is a commercial product that offers no-cost hosted
instances to free-software projects; Roundup is an open-source project
that requires volunteers to administer it and a server to host it.

After posting a call for volunteers, a new Roundup installation was set
up at ‘https://bugs.python.org’.  One installation of Roundup can host
multiple trackers, and this server now also hosts issue trackers for
Jython and for the Python web site.  It will surely find other uses in
the future.  Where possible, this edition of "What’s New in Python"
links to the bug/patch item for each change.

Hosting of the Python bug tracker is kindly provided by Upfront
Systems(5) of Stellenbosch, South Africa.  Martin von Löwis put a lot of
effort into importing existing bugs and patches from SourceForge; his
scripts for this import operation are at
‘http://svn.python.org/view/tracker/importer/’ and may be useful to
other projects wishing to move from SourceForge to Roundup.

参见
....

‘https://bugs.python.org’

     Python 的错误追踪器

‘http://bugs.jython.org’:

     Jython 的错误追踪器

‘http://roundup.sourceforge.net/’

     Roundup 下载和文档。

‘http://svn.python.org/view/tracker/importer/’

     Martin von Löwis 的转换脚本。

   ---------- Footnotes ----------

   (1) https://www.atlassian.com/software/jira/

   (2) https://launchpad.net/

   (3) http://roundup.sourceforge.net/

   (4) https://trac.edgewall.org/

   (5) http://www.upfrontsoftware.co.za


File: python.info,  Node: 新的文档格式：使用 Sphinx 的 reStructuredText,  Prev: New Issue Tracker Roundup,  Up: 开发过程的变化

1.11.2.2 新的文档格式：使用 Sphinx 的 reStructuredText
......................................................

The Python documentation was written using LaTeX since the project
started around 1989.  In the 1980s and early 1990s, most documentation
was printed out for later study, not viewed online.  LaTeX was widely
used because it provided attractive printed output while remaining
straightforward to write once the basic rules of the markup were
learned.

Today LaTeX is still used for writing publications destined for
printing, but the landscape for programming tools has shifted.  We no
longer print out reams of documentation; instead, we browse through it
online and HTML has become the most important format to support.
Unfortunately, converting LaTeX to HTML is fairly complicated and Fred
L. Drake Jr., the long-time Python documentation editor, spent a lot of
time maintaining the conversion process.  Occasionally people would
suggest converting the documentation into SGML and later XML, but
performing a good conversion is a major task and no one ever committed
the time required to finish the job.

During the 2.6 development cycle, Georg Brandl put a lot of effort into
building a new toolchain for processing the documentation.  The
resulting package is called Sphinx, and is available from
‘http://sphinx-doc.org/’.

Sphinx concentrates on HTML output, producing attractively styled and
modern HTML; printed output is still supported through conversion to
LaTeX. The input format is reStructuredText, a markup syntax supporting
custom extensions and directives that is commonly used in the Python
community.

Sphinx is a standalone package that can be used for writing, and almost
two dozen other projects (listed on the Sphinx web site(1)) have adopted
Sphinx as their documentation tool.

参见
....

Documenting Python(2)

     描述如何编写Python文档。

Sphinx(3)

     Sphinx工具链的文档和代码。

Docutils(4)

     reStructuredText 的基础解析器和工具集。

   ---------- Footnotes ----------

   (1) https://www.sphinx-doc.org/en/master/examples.html

   (2) https://devguide.python.org/documenting/

   (3) http://sphinx-doc.org/

   (4) http://docutils.sourceforge.net


File: python.info,  Node: PEP 343 "with" 语句,  Next: PEP 366 从主模块显式相对导入,  Prev: 开发过程的变化,  Up: Python 2 6 有什么新变化

1.11.3 PEP 343: "with" 语句
---------------------------

The previous version, Python 2.5, added the ’*note with: 6f2.’ statement
as an optional feature, to be enabled by a ‘from __future__ import
with_statement’ directive.  In 2.6 the statement no longer needs to be
specially enabled; this means that ‘with’ is now always a keyword.  The
rest of this section is a copy of the corresponding section from the
"What’s New in Python 2.5" document; if you’re familiar with the
’‘with’’ statement from Python 2.5, you can skip this section.

The ’*note with: 6f2.’ statement clarifies code that previously would
use ‘try...finally’ blocks to ensure that clean-up code is executed.  In
this section, I’ll discuss the statement as it will commonly be used.
In the next section, I’ll examine the implementation details and show
how to write objects for use with this statement.

The ’*note with: 6f2.’ statement is a control-flow structure whose basic
structure is:

     with expression [as variable]:
         with-block

The expression is evaluated, and it should result in an object that
supports the context management protocol (that is, has *note
__enter__(): c9d. and *note __exit__(): c9e. methods).

The object’s *note __enter__(): c9d. is called before `with-block' is
executed and therefore can run set-up code.  It also may return a value
that is bound to the name `variable', if given.  (Note carefully that
`variable' is `not' assigned the result of `expression'.)

After execution of the `with-block' is finished, the object’s *note
__exit__(): c9e. method is called, even if the block raised an
exception, and can therefore run clean-up code.

Some standard Python objects now support the context management protocol
and can be used with the ’*note with: 6f2.’ statement.  File objects are
one example:

     with open('/etc/passwd', 'r') as f:
         for line in f:
             print line
             ... more processing code ...

After this statement has executed, the file object in `f' will have been
automatically closed, even if the *note for: c38. loop raised an
exception part-way through the block.

     注解: In this case, `f' is the same object created by *note open():
     4f8, because ‘file.__enter__()’ returns `self'.

The *note threading: 10a. module’s locks and condition variables also
support the ’*note with: 6f2.’ statement:

     lock = threading.Lock()
     with lock:
         # Critical section of code
         ...

The lock is acquired before the block is executed and always released
once the block is complete.

The ‘localcontext()’ function in the *note decimal: 36. module makes it
easy to save and restore the current decimal context, which encapsulates
the desired precision and rounding characteristics for computations:

     from decimal import Decimal, Context, localcontext

     # Displays with default precision of 28 digits
     v = Decimal('578')
     print v.sqrt()

     with localcontext(Context(prec=16)):
         # All code in this block uses a precision of 16 digits.
         # The original context is restored on exiting the block.
         print v.sqrt()

* Menu:

* Writing Context Managers::
* contextlib 模块::


File: python.info,  Node: Writing Context Managers,  Next: contextlib 模块,  Up: PEP 343 "with" 语句

1.11.3.1 Writing Context Managers
.................................

Under the hood, the ’*note with: 6f2.’ statement is fairly complicated.
Most people will only use ’‘with’’ in company with existing objects and
don’t need to know these details, so you can skip the rest of this
section if you like.  Authors of new objects will need to understand the
details of the underlying implementation and should keep reading.

A high-level explanation of the context management protocol is:

   * The expression is evaluated and should result in an object called a
     "context manager".  The context manager must have *note
     __enter__(): c9d. and *note __exit__(): c9e. methods.

   * The context manager’s *note __enter__(): c9d. method is called.
     The value returned is assigned to `VAR'. If no ‘as VAR’ clause is
     present, the value is simply discarded.

   * The code in `BLOCK' is executed.

   * If `BLOCK' raises an exception, the context manager’s *note
     __exit__(): c9e. method is called with three arguments, the
     exception details (‘type, value, traceback’, the same values
     returned by *note sys.exc_info(): c67, which can also be ‘None’ if
     no exception occurred).  The method’s return value controls whether
     an exception is re-raised: any false value re-raises the exception,
     and ‘True’ will result in suppressing it.  You’ll only rarely want
     to suppress the exception, because if you do the author of the code
     containing the ’*note with: 6f2.’ statement will never realize
     anything went wrong.

   * If `BLOCK' didn’t raise an exception, the *note __exit__(): c9e.
     method is still called, but `type', `value', and `traceback' are
     all ‘None’.

Let’s think through an example.  I won’t present detailed code but will
only sketch the methods necessary for a database that supports
transactions.

(For people unfamiliar with database terminology: a set of changes to
the database are grouped into a transaction.  Transactions can be either
committed, meaning that all the changes are written into the database,
or rolled back, meaning that the changes are all discarded and the
database is unchanged.  See any database textbook for more information.)

Let’s assume there’s an object representing a database connection.  Our
goal will be to let the user write code like this:

     db_connection = DatabaseConnection()
     with db_connection as cursor:
         cursor.execute('insert into ...')
         cursor.execute('delete from ...')
         # ... more operations ...

The transaction should be committed if the code in the block runs
flawlessly or rolled back if there’s an exception.  Here’s the basic
interface for ‘DatabaseConnection’ that I’ll assume:

     class DatabaseConnection:
         # Database interface
         def cursor(self):
             "Returns a cursor object and starts a new transaction"
         def commit(self):
             "Commits current transaction"
         def rollback(self):
             "Rolls back current transaction"

The *note __enter__(): c9d. method is pretty easy, having only to start
a new transaction.  For this application the resulting cursor object
would be a useful result, so the method will return it.  The user can
then add ‘as cursor’ to their ’*note with: 6f2.’ statement to bind the
cursor to a variable name.

     class DatabaseConnection:
         ...
         def __enter__(self):
             # Code to start a new transaction
             cursor = self.cursor()
             return cursor

The *note __exit__(): c9e. method is the most complicated because it’s
where most of the work has to be done.  The method has to check if an
exception occurred.  If there was no exception, the transaction is
committed.  The transaction is rolled back if there was an exception.

In the code below, execution will just fall off the end of the function,
returning the default value of ‘None’.  ‘None’ is false, so the
exception will be re-raised automatically.  If you wished, you could be
more explicit and add a *note return: 191. statement at the marked
location.

     class DatabaseConnection:
         ...
         def __exit__(self, type, value, tb):
             if tb is None:
                 # No exception, so commit
                 self.commit()
             else:
                 # Exception occurred, so rollback.
                 self.rollback()
                 # return False


File: python.info,  Node: contextlib 模块,  Prev: Writing Context Managers,  Up: PEP 343 "with" 语句

1.11.3.2 contextlib 模块
........................

The *note contextlib: 24. module provides some functions and a decorator
that are useful when writing objects for use with the ’*note with: 6f2.’
statement.

The decorator is called ‘contextmanager()’, and lets you write a single
generator function instead of defining a new class.  The generator
should yield exactly one value.  The code up to the *note yield: 190.
will be executed as the *note __enter__(): c9d. method, and the value
yielded will be the method’s return value that will get bound to the
variable in the ’*note with: 6f2.’ statement’s ‘as’ clause, if any.  The
code after the ‘yield’ will be executed in the *note __exit__(): c9e.
method.  Any exception raised in the block will be raised by the ‘yield’
statement.

Using this decorator, our database example from the previous section
could be written as:

     from contextlib import contextmanager

     @contextmanager
     def db_transaction(connection):
         cursor = connection.cursor()
         try:
             yield cursor
         except:
             connection.rollback()
             raise
         else:
             connection.commit()

     db = DatabaseConnection()
     with db_transaction(db) as cursor:
         ...

The *note contextlib: 24. module also has a ‘nested(mgr1, mgr2, ...)’
function that combines a number of context managers so you don’t need to
write nested ’*note with: 6f2.’ statements.  In this example, the single
’‘with’’ statement both starts a database transaction and acquires a
thread lock:

     lock = threading.Lock()
     with nested (db_transaction(db), lock) as (cursor, locked):
         ...

Finally, the ‘closing()’ function returns its argument so that it can be
bound to a variable, and calls the argument’s ‘.close()’ method at the
end of the block.

     import urllib, sys
     from contextlib import closing

     with closing(urllib.urlopen('http://www.yahoo.com')) as f:
         for line in f:
             sys.stdout.write(line)

参见
....

PEP 343(1) - "with" 语句

     PEP written by Guido van Rossum and Nick Coghlan; implemented by
     Mike Bland, Guido van Rossum, and Neal Norwitz.  The PEP shows the
     code generated for a ’*note with: 6f2.’ statement, which can be
     helpful in learning how the statement works.

*note contextlib: 24. 模块的文档。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0343


File: python.info,  Node: PEP 366 从主模块显式相对导入,  Next: PEP 370 分用户的 site-packages 目录,  Prev: PEP 343 "with" 语句,  Up: Python 2 6 有什么新变化

1.11.4 PEP 366: 从主模块显式相对导入
------------------------------------

Python’s *note -m: 340. switch allows running a module as a script.
When you ran a module that was located inside a package, relative
imports didn’t work correctly.

The fix for Python 2.6 adds a *note __package__: 95d. attribute to
modules.  When this attribute is present, relative imports will be
relative to the value of this attribute instead of the *note __name__:
d1a. attribute.

PEP 302-style importers can then set *note __package__: 95d. as
necessary.  The *note runpy: e3. module that implements the *note -m:
340. switch now does this, so relative imports will now work correctly
in scripts running from inside a package.


File: python.info,  Node: PEP 370 分用户的 site-packages 目录,  Next: PEP 371 多任务处理包,  Prev: PEP 366 从主模块显式相对导入,  Up: Python 2 6 有什么新变化

1.11.5 PEP 370: 分用户的 site-packages 目录
-------------------------------------------

When you run Python, the module search path ‘sys.path’ usually includes
a directory whose path ends in ‘"site-packages"’.  This directory is
intended to hold locally-installed packages available to all users using
a machine or a particular site installation.

Python 2.6 introduces a convention for user-specific site directories.
The directory varies depending on the platform:

   * Unix and Mac OS X: ‘~/.local/’

   * Windows: ‘%APPDATA%/Python’

Within this directory, there will be version-specific subdirectories,
such as ‘lib/python2.6/site-packages’ on Unix/Mac OS and
‘Python26/site-packages’ on Windows.

If you don’t like the default directory, it can be overridden by an
environment variable.  *note PYTHONUSERBASE: d1c. sets the root
directory used for all Python versions supporting this feature.  On
Windows, the directory for application-specific data can be changed by
setting the ‘APPDATA’ environment variable.  You can also modify the
‘site.py’ file for your Python installation.

The feature can be disabled entirely by running Python with the *note
-s: d1d. option or setting the *note PYTHONNOUSERSITE: d1e. environment
variable.

参见
....

PEP 370(1) - 分用户的 site-packages 目录

     PEP 由 Christian Heimes 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0370


File: python.info,  Node: PEP 371 多任务处理包,  Next: PEP 3101 高级字符串格式,  Prev: PEP 370 分用户的 site-packages 目录,  Up: Python 2 6 有什么新变化

1.11.6 PEP 371: 多任务处理包
----------------------------

The new *note multiprocessing: b8. package lets Python programs create
new processes that will perform a computation and return a result to the
parent.  The parent and child processes can communicate using queues and
pipes, synchronize their operations using locks and semaphores, and can
share simple arrays of data.

The *note multiprocessing: b8. module started out as an exact emulation
of the *note threading: 10a. module using processes instead of threads.
That goal was discarded along the path to Python 2.6, but the general
approach of the module is still similar.  The fundamental class is the
‘Process’, which is passed a callable object and a collection of
arguments.  The ‘start()’ method sets the callable running in a
subprocess, after which you can call the ‘is_alive()’ method to check
whether the subprocess is still running and the ‘join()’ method to wait
for the process to exit.

Here’s a simple example where the subprocess will calculate a factorial.
The function doing the calculation is written strangely so that it takes
significantly longer when the input argument is a multiple of 4.

     import time
     from multiprocessing import Process, Queue


     def factorial(queue, N):
         "Compute a factorial."
         # If N is a multiple of 4, this function will take much longer.
         if (N % 4) == 0:
             time.sleep(.05 * N/4)

         # Calculate the result
         fact = 1L
         for i in range(1, N+1):
             fact = fact * i

         # Put the result on the queue
         queue.put(fact)

     if __name__ == '__main__':
         queue = Queue()

         N = 5

         p = Process(target=factorial, args=(queue, N))
         p.start()
         p.join()

         result = queue.get()
         print 'Factorial', N, '=', result

A *note Queue: d20. is used to communicate the result of the factorial.
The *note Queue: d20. object is stored in a global variable.  The child
process will use the value of the variable when the child was created;
because it’s a *note Queue: d20, parent and child can use the object to
communicate.  (If the parent were to change the value of the global
variable, the child’s value would be unaffected, and vice versa.)

Two other classes, ‘Pool’ and ‘Manager’, provide higher-level
interfaces.  ‘Pool’ will create a fixed number of worker processes, and
requests can then be distributed to the workers by calling ‘apply()’ or
‘apply_async()’ to add a single request, and *note map(): c35. or
‘map_async()’ to add a number of requests.  The following code uses a
‘Pool’ to spread requests across 5 worker processes and retrieve a list
of results:

     from multiprocessing import Pool

     def factorial(N, dictionary):
         "Compute a factorial."
         ...
     p = Pool(5)
     result = p.map(factorial, range(1, 1000, 10))
     for v in result:
         print v

This produces the following output:

     1
     39916800
     51090942171709440000
     8222838654177922817725562880000000
     33452526613163807108170062053440751665152000000000
     ...

The other high-level interface, the ‘Manager’ class, creates a separate
server process that can hold master copies of Python data structures.
Other processes can then access and modify these data structures using
proxy objects.  The following example creates a shared dictionary by
calling the *note dict(): 1b9. method; the worker processes then insert
values into the dictionary.  (Locking is not done for you automatically,
which doesn’t matter in this example.  ‘Manager’’s methods also include
‘Lock()’, ‘RLock()’, and ‘Semaphore()’ to create shared locks.)

     import time
     from multiprocessing import Pool, Manager

     def factorial(N, dictionary):
         "Compute a factorial."
         # Calculate the result
         fact = 1L
         for i in range(1, N+1):
             fact = fact * i

         # Store result in dictionary
         dictionary[N] = fact

     if __name__ == '__main__':
         p = Pool(5)
         mgr = Manager()
         d = mgr.dict()         # Create shared dictionary

         # Run tasks using the pool
         for N in range(1, 1000, 10):
             p.apply_async(factorial, (N, d))

         # Mark pool as closed -- no more tasks can be added.
         p.close()

         # Wait for tasks to exit
         p.join()

         # Output results
         for k, v in sorted(d.items()):
             print k, v

This will produce the output:

     1 1
     11 39916800
     21 51090942171709440000
     31 8222838654177922817725562880000000
     41 33452526613163807108170062053440751665152000000000
     51 15511187532873822802242430164693032110632597200169861120000...

参见
....

*note multiprocessing: b8. 模块的文档。

PEP 371(1) - 添加多任务处理包

     PEP 由 Jesse Noller 和 Richard Oudkerk 撰写，由 Richard Oudkerk 和
     Jesse Noller 实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0371


File: python.info,  Node: PEP 3101 高级字符串格式,  Next: PEP 3105 print 改为函数,  Prev: PEP 371 多任务处理包,  Up: Python 2 6 有什么新变化

1.11.7 PEP 3101: 高级字符串格式
-------------------------------

In Python 3.0, the ‘%’ operator is supplemented by a more powerful
string formatting method, *note format(): 4e3.  Support for the *note
str.format(): 4e2. method has been backported to Python 2.6.

In 2.6, both 8-bit and Unicode strings have a ‘.format()’ method that
treats the string as a template and takes the arguments to be formatted.
The formatting template uses curly brackets (‘{’, ‘}’) as special
characters:

     >>> # Substitute positional argument 0 into the string.
     >>> "User ID: {0}".format("root")
     'User ID: root'
     >>> # Use the named keyword arguments
     >>> "User ID: {uid}   Last seen: {last_login}".format(
     ...    uid="root",
     ...    last_login = "5 Mar 2008 07:20")
     'User ID: root   Last seen: 5 Mar 2008 07:20'

Curly brackets can be escaped by doubling them:

     >>> "Empty dict: {{}}".format()
     "Empty dict: {}"

Field names can be integers indicating positional arguments, such as
‘{0}’, ‘{1}’, etc.  or names of keyword arguments.  You can also supply
compound field names that read attributes or access dictionary keys:

     >>> import sys
     >>> print 'Platform: {0.platform}\nPython version: {0.version}'.format(sys)
     Platform: darwin
     Python version: 2.6a1+ (trunk:61261M, Mar  5 2008, 20:29:41)
     [GCC 4.0.1 (Apple Computer, Inc. build 5367)]'

     >>> import mimetypes
     >>> 'Content-type: {0[.mp4]}'.format(mimetypes.types_map)
     'Content-type: video/mp4'

Note that when using dictionary-style notation such as ‘[.mp4]’, you
don’t need to put any quotation marks around the string; it will look up
the value using ‘.mp4’ as the key.  Strings beginning with a number will
be converted to an integer.  You can’t write more complicated
expressions inside a format string.

So far we’ve shown how to specify which field to substitute into the
resulting string.  The precise formatting used is also controllable by
adding a colon followed by a format specifier.  For example:

     >>> # Field 0: left justify, pad to 15 characters
     >>> # Field 1: right justify, pad to 6 characters
     >>> fmt = '{0:15} ${1:>6}'
     >>> fmt.format('Registration', 35)
     'Registration    $    35'
     >>> fmt.format('Tutorial', 50)
     'Tutorial        $    50'
     >>> fmt.format('Banquet', 125)
     'Banquet         $   125'

Format specifiers can reference other fields through nesting:

     >>> fmt = '{0:{1}}'
     >>> width = 15
     >>> fmt.format('Invoice #1234', width)
     'Invoice #1234  '
     >>> width = 35
     >>> fmt.format('Invoice #1234', width)
     'Invoice #1234                      '

可以指定所需宽度内的字段对齐方式：

字符                 效果
                     
----------------------------------------------------------------------
                     
< (默认)             左对齐
                     
                     
>                    右对齐
                     
                     
^                    居中对齐
                     
                     
=                    （仅适用于数字类型）在符号后加空格。
                     

Format specifiers can also include a presentation type, which controls
how the value is formatted.  For example, floating-point numbers can be
formatted as a general number or in exponential notation:

     >>> '{0:g}'.format(3.75)
     '3.75'
     >>> '{0:e}'.format(3.75)
     '3.750000e+00'

A variety of presentation types are available.  Consult the 2.6
documentation for a *note complete list: d22.; here’s a sample:

‘b’       二进制。输出以2为底的数字。
          
          
‘c’       字符。在打印之前将整数转换为相应的Unicode字符。
          
          
‘d’       十进制整数。 输出以 10 为基数的数字。
          
          
‘o’       八进制格式。 输出以 8 为基数的数字。
          
          
‘x’       十六进制格式。 输出以 16 为基数的数字，使用小写字母表示 9 以上的数码。
          
          
‘e’       指数表示法。用字母 ’e’ 以科学计数法打印数字以表示指数。
          
          
‘g’       General format.  This prints the number as a fixed-point number, unless
          the number is too large, in which case it switches to ’e’ exponent
          notation.
          
          
‘n’       Number.  This is the same as ’g’ (for floats) or ’d’ (for integers),
          except that it uses the current locale setting to insert the appropriate
          number separator characters.
          
          
‘%’       Percentage.  Multiplies the number by 100 and displays in fixed (’f’)
          format, followed by a percent sign.
          

Classes and types can define a *note __format__(): 956. method to
control how they’re formatted.  It receives a single argument, the
format specifier:

     def __format__(self, format_spec):
         if isinstance(format_spec, unicode):
             return unicode(str(self))
         else:
             return str(self)

There’s also a *note format(): 4e3. builtin that will format a single
value.  It calls the type’s *note __format__(): 956. method with the
provided specifier:

     >>> format(75.6564, '.2f')
     '75.66'

参见
....

*note 格式字符串语法: d22.

     格式字段的参考文档。

PEP 3101(1) - 高级字符串格式

     PEP 由 Eric V. Smith 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3101


File: python.info,  Node: PEP 3105 print 改为函数,  Next: PEP 3110 异常处理的变更,  Prev: PEP 3101 高级字符串格式,  Up: Python 2 6 有什么新变化

1.11.8 PEP 3105: ‘print’ 改为函数
---------------------------------

The ‘print’ statement becomes the *note print(): 88f. function in Python
3.0.  Making *note print(): 88f. a function makes it possible to replace
the function by doing ‘def print(...)’ or importing a new function from
somewhere else.

Python 2.6 has a ‘__future__’ import that removes ‘print’ as language
syntax, letting you use the functional form instead.  For example:

     >>> from __future__ import print_function
     >>> print('# of entries', len(dictionary), file=sys.stderr)

The signature of the new function is:

     def print(*args, sep=' ', end='\n', file=None)

The parameters are:

        * `args': positional arguments whose values will be printed out.

        * `sep': the separator, which will be printed between arguments.

        * `end': the ending text, which will be printed after all of the
          arguments have been output.

        * `file': the file object to which the output will be sent.

参见
....

PEP 3105(1) - print 改为函数

     PEP 由 Georg Brandl 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3105


File: python.info,  Node: PEP 3110 异常处理的变更,  Next: PEP 3112 字节字面值,  Prev: PEP 3105 print 改为函数,  Up: Python 2 6 有什么新变化

1.11.9 PEP 3110: 异常处理的变更
-------------------------------

One error that Python programmers occasionally make is writing the
following code:

     try:
         ...
     except TypeError, ValueError:  # Wrong!
         ...

The author is probably trying to catch both *note TypeError: 193. and
*note ValueError: 1fc. exceptions, but this code actually does something
different: it will catch *note TypeError: 193. and bind the resulting
exception object to the local name ‘"ValueError"’.  The *note
ValueError: 1fc. exception will not be caught at all.  The correct code
specifies a tuple of exceptions:

     try:
         ...
     except (TypeError, ValueError):
         ...

This error happens because the use of the comma here is ambiguous: does
it indicate two different nodes in the parse tree, or a single node
that’s a tuple?

Python 3.0 makes this unambiguous by replacing the comma with the word
"as".  To catch an exception and store the exception object in the
variable ‘exc’, you must write:

     try:
         ...
     except TypeError as exc:
         ...

Python 3.0 will only support the use of "as", and therefore interprets
the first example as catching two different exceptions.  Python 2.6
supports both the comma and "as", so existing code will continue to
work.  We therefore suggest using "as" when writing new Python code that
will only be executed with 2.6.

参见
....

PEP 3110(1) - 在 Python 3000 中捕获异常

     PEP 由 Collin Winter 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3110


File: python.info,  Node: PEP 3112 字节字面值,  Next: PEP 3116 新 I/O 库,  Prev: PEP 3110 异常处理的变更,  Up: Python 2 6 有什么新变化

1.11.10 PEP 3112: 字节字面值
----------------------------

Python 3.0 adopts Unicode as the language’s fundamental string type and
denotes 8-bit literals differently, either as ‘b'string'’ or using a
*note bytes: 33a. constructor.  For future compatibility, Python 2.6
adds *note bytes: 33a. as a synonym for the *note str: 339. type, and it
also supports the ‘b''’ notation.

The 2.6 *note str: 339. differs from 3.0’s *note bytes: 33a. type in
various ways; most notably, the constructor is completely different.  In
3.0, ‘bytes([65, 66, 67])’ is 3 elements long, containing the bytes
representing ‘ABC’; in 2.6, ‘bytes([65, 66, 67])’ returns the 12-byte
string representing the *note str(): 339. of the list.

The primary use of *note bytes: 33a. in 2.6 will be to write tests of
object type such as ‘isinstance(x, bytes)’.  This will help the 2to3
converter, which can’t tell whether 2.x code intends strings to contain
either characters or 8-bit bytes; you can now use either *note bytes:
33a. or *note str: 339. to represent your intention exactly, and the
resulting code will also be correct in Python 3.0.

There’s also a ‘__future__’ import that causes all string literals to
become Unicode strings.  This means that ‘\u’ escape sequences can be
used to include Unicode characters:

     from __future__ import unicode_literals

     s = ('\u751f\u3080\u304e\u3000\u751f\u3054'
          '\u3081\u3000\u751f\u305f\u307e\u3054')

     print len(s)               # 12 Unicode characters

At the C level, Python 3.0 will rename the existing 8-bit string type,
called ‘PyStringObject’ in Python 2.x, to *note PyBytesObject: d26.
Python 2.6 uses ‘#define’ to support using the names *note
PyBytesObject(): d26, *note PyBytes_Check(): d27, *note
PyBytes_FromStringAndSize(): d28, and all the other functions and macros
used with strings.

Instances of the *note bytes: 33a. type are immutable just as strings
are.  A new *note bytearray: 33b. type stores a mutable sequence of
bytes:

     >>> bytearray([65, 66, 67])
     bytearray(b'ABC')
     >>> b = bytearray(u'\u21ef\u3244', 'utf-8')
     >>> b
     bytearray(b'\xe2\x87\xaf\xe3\x89\x84')
     >>> b[0] = '\xe3'
     >>> b
     bytearray(b'\xe3\x87\xaf\xe3\x89\x84')
     >>> unicode(str(b), 'utf-8')
     u'\u31ef \u3244'

Byte arrays support most of the methods of string types, such as
‘startswith()’/‘endswith()’, ‘find()’/‘rfind()’, and some of the methods
of lists, such as ‘append()’, ‘pop()’, and ‘reverse()’.

     >>> b = bytearray('ABC')
     >>> b.append('d')
     >>> b.append(ord('e'))
     >>> b
     bytearray(b'ABCde')

There’s also a corresponding C API, with *note PyByteArray_FromObject():
d29, *note PyByteArray_FromStringAndSize(): d2a, and various other
functions.

参见
....

PEP 3112(1) - Python 3000 中的字节字面值

     PEP 由 Jason Orendorff 撰写， 补丁2.6 由 Christian Heimes 撰写。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3112


File: python.info,  Node: PEP 3116 新 I/O 库,  Next: PEP 3118 修改缓冲区协议,  Prev: PEP 3112 字节字面值,  Up: Python 2 6 有什么新变化

1.11.11 PEP 3116: 新 I/O 库
---------------------------

Python’s built-in file objects support a number of methods, but
file-like objects don’t necessarily support all of them.  Objects that
imitate files usually support ‘read()’ and ‘write()’, but they may not
support *note readline(): df, for example.  Python 3.0 introduces a
layered I/O library in the *note io: a2. module that separates buffering
and text-handling features from the fundamental read and write
operations.

There are three levels of abstract base classes provided by the *note
io: a2. module:

   * ‘RawIOBase’ defines raw I/O operations: ‘read()’, ‘readinto()’,
     ‘write()’, ‘seek()’, ‘tell()’, ‘truncate()’, and ‘close()’.  Most
     of the methods of this class will often map to a single system
     call.  There are also ‘readable()’, ‘writable()’, and ‘seekable()’
     methods for determining what operations a given object will allow.

     Python 3.0 has concrete implementations of this class for files and
     sockets, but Python 2.6 hasn’t restructured its file and socket
     objects in this way.

   * ‘BufferedIOBase’ is an abstract base class that buffers data in
     memory to reduce the number of system calls used, making I/O
     processing more efficient.  It supports all of the methods of
     ‘RawIOBase’, and adds a ‘raw’ attribute holding the underlying raw
     object.

     There are five concrete classes implementing this ABC.
     ‘BufferedWriter’ and ‘BufferedReader’ are for objects that support
     write-only or read-only usage that have a ‘seek()’ method for
     random access.  ‘BufferedRandom’ objects support read and write
     access upon the same underlying stream, and ‘BufferedRWPair’ is for
     objects such as TTYs that have both read and write operations
     acting upon unconnected streams of data.  The ‘BytesIO’ class
     supports reading, writing, and seeking over an in-memory buffer.

   * ‘TextIOBase’: Provides functions for reading and writing strings
     (remember, strings will be Unicode in Python 3.0), and supporting
     *note universal newlines: 5fd.  ‘TextIOBase’ defines the *note
     readline(): df. method and supports iteration upon objects.

     There are two concrete implementations.  ‘TextIOWrapper’ wraps a
     buffered I/O object, supporting all of the methods for text I/O and
     adding a ‘buffer’ attribute for access to the underlying object.
     ‘StringIO’ simply buffers everything in memory without ever writing
     anything to disk.

     (In Python 2.6, *note io.StringIO: 836. is implemented in pure
     Python, so it’s pretty slow.  You should therefore stick with the
     existing ‘StringIO’ module or ‘cStringIO’ for now.  At some point
     Python 3.0’s *note io: a2. module will be rewritten into C for
     speed, and perhaps the C implementation will be backported to the
     2.x releases.)

In Python 2.6, the underlying implementations haven’t been restructured
to build on top of the *note io: a2. module’s classes.  The module is
being provided to make it easier to write code that’s forward-compatible
with 3.0, and to save developers the effort of writing their own
implementations of buffering and text I/O.

参见
....

PEP 3116(1) - 新 I/O

     PEP written by Daniel Stutzbach, Mike Verdone, and Guido van
     Rossum.  Code by Guido van Rossum, Georg Brandl, Walter Doerwald,
     Jeremy Hylton, Martin von Löwis, Tony Lownds, and others.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3116


File: python.info,  Node: PEP 3118 修改缓冲区协议,  Next: PEP 3119 抽象基类,  Prev: PEP 3116 新 I/O 库,  Up: Python 2 6 有什么新变化

1.11.12 PEP 3118: 修改缓冲区协议
--------------------------------

The buffer protocol is a C-level API that lets Python types exchange
pointers into their internal representations.  A memory-mapped file can
be viewed as a buffer of characters, for example, and this lets another
module such as *note re: de. treat memory-mapped files as a string of
characters to be searched.

The primary users of the buffer protocol are numeric-processing packages
such as NumPy, which expose the internal representation of arrays so
that callers can write data directly into an array instead of going
through a slower API. This PEP updates the buffer protocol in light of
experience from NumPy development, adding a number of new features such
as indicating the shape of an array or locking a memory region.

The most important new C API function is ‘PyObject_GetBuffer(PyObject
*obj, Py_buffer *view, int flags)’, which takes an object and a set of
flags, and fills in the ‘Py_buffer’ structure with information about the
object’s memory representation.  Objects can use this operation to lock
memory in place while an external caller could be modifying the
contents, so there’s a corresponding ‘PyBuffer_Release(Py_buffer *view)’
to indicate that the external caller is done.

The `flags' argument to *note PyObject_GetBuffer(): d2d. specifies
constraints upon the memory returned.  Some examples are:

        * ‘PyBUF_WRITABLE’ indicates that the memory must be writable.

        * ‘PyBUF_LOCK’ requests a read-only or exclusive lock on the
          memory.

        * ‘PyBUF_C_CONTIGUOUS’ and ‘PyBUF_F_CONTIGUOUS’ requests a
          C-contiguous (last dimension varies the fastest) or
          Fortran-contiguous (first dimension varies the fastest) array
          layout.

Two new argument codes for *note PyArg_ParseTuple(): 26b, ‘s*’ and ‘z*’,
return locked buffer objects for a parameter.

参见
....

PEP 3118(1) - 修改缓冲区协议

     PEP 由 Travis Oliphant 和 Carl Banks 撰写，由 Travis Oliphant 实现
     。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3118


File: python.info,  Node: PEP 3119 抽象基类,  Next: PEP 3127 整型文字支持和语法,  Prev: PEP 3118 修改缓冲区协议,  Up: Python 2 6 有什么新变化

1.11.13 PEP 3119: 抽象基类
--------------------------

Some object-oriented languages such as Java support interfaces,
declaring that a class has a given set of methods or supports a given
access protocol.  Abstract Base Classes (or ABCs) are an equivalent
feature for Python.  The ABC support consists of an *note abc: 4. module
containing a metaclass called ‘ABCMeta’, special handling of this
metaclass by the *note isinstance(): 457. and *note issubclass(): 458.
builtins, and a collection of basic ABCs that the Python developers
think will be widely useful.  Future versions of Python will probably
add more ABCs.

Let’s say you have a particular class and wish to know whether it
supports dictionary-style access.  The phrase "dictionary-style" is
vague, however.  It probably means that accessing items with ‘obj[1]’
works.  Does it imply that setting items with ‘obj[2] = value’ works?
Or that the object will have ‘keys()’, ‘values()’, and ‘items()’
methods?  What about the iterative variants such as ‘iterkeys()’?  *note
copy(): 26. and ‘update()’?  Iterating over the object with *note
iter(): d2f.?

The Python 2.6 *note collections: 1e. module includes a number of
different ABCs that represent these distinctions.  ‘Iterable’ indicates
that a class defines *note __iter__(): 517, and ‘Container’ means the
class defines a *note __contains__(): d30. method and therefore supports
‘x in y’ expressions.  The basic dictionary interface of getting items,
setting items, and ‘keys()’, ‘values()’, and ‘items()’, is defined by
the ‘MutableMapping’ ABC.

You can derive your own classes from a particular ABC to indicate they
support that ABC’s interface:

     import collections

     class Storage(collections.MutableMapping):
         ...

Alternatively, you could write the class without deriving from the
desired ABC and instead register the class by calling the ABC’s
‘register()’ method:

     import collections

     class Storage:
         ...

     collections.MutableMapping.register(Storage)

For classes that you write, deriving from the ABC is probably clearer.
The ‘register()’ method is useful when you’ve written a new ABC that can
describe an existing type or class, or if you want to declare that some
third-party class implements an ABC. For example, if you defined a
‘PrintableType’ ABC, it’s legal to do:

     # Register Python's types
     PrintableType.register(int)
     PrintableType.register(float)
     PrintableType.register(str)

Classes should obey the semantics specified by an ABC, but Python can’t
check this; it’s up to the class author to understand the ABC’s
requirements and to implement the code accordingly.

To check whether an object supports a particular interface, you can now
write:

     def func(d):
         if not isinstance(d, collections.MutableMapping):
             raise ValueError("Mapping object expected, not %r" % d)

Don’t feel that you must now begin writing lots of checks as in the
above example.  Python has a strong tradition of duck-typing, where
explicit type-checking is never done and code simply calls methods on an
object, trusting that those methods will be there and raising an
exception if they aren’t.  Be judicious in checking for ABCs and only do
it where it’s absolutely necessary.

You can write your own ABCs by using ‘abc.ABCMeta’ as the metaclass in a
class definition:

     from abc import ABCMeta, abstractmethod

     class Drawable():
         __metaclass__ = ABCMeta

         @abstractmethod
         def draw(self, x, y, scale=1.0):
             pass

         def draw_doubled(self, x, y):
             self.draw(x, y, scale=2.0)


     class Square(Drawable):
         def draw(self, x, y, scale):
             ...

In the ‘Drawable’ ABC above, the ‘draw_doubled()’ method renders the
object at twice its size and can be implemented in terms of other
methods described in ‘Drawable’.  Classes implementing this ABC
therefore don’t need to provide their own implementation of
‘draw_doubled()’, though they can do so.  An implementation of ‘draw()’
is necessary, though; the ABC can’t provide a useful generic
implementation.

You can apply the ‘@abstractmethod’ decorator to methods such as
‘draw()’ that must be implemented; Python will then raise an exception
for classes that don’t define the method.  Note that the exception is
only raised when you actually try to create an instance of a subclass
lacking the method:

     >>> class Circle(Drawable):
     ...     pass
     ...
     >>> c = Circle()
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: Can't instantiate abstract class Circle with abstract methods draw
     >>>

Abstract data attributes can be declared using the ‘@abstractproperty’
decorator:

     from abc import abstractproperty
     ...

     @abstractproperty
     def readonly(self):
        return self._x

Subclasses must then define a ‘readonly()’ property.

参见
....

PEP 3119(1) - 引入抽象基类

     PEP written by Guido van Rossum and Talin.  Implemented by Guido
     van Rossum.  Backported to 2.6 by Benjamin Aranguren, with Alex
     Martelli.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3119


File: python.info,  Node: PEP 3127 整型文字支持和语法,  Next: PEP 3129 类装饰器,  Prev: PEP 3119 抽象基类,  Up: Python 2 6 有什么新变化

1.11.14 PEP 3127: 整型文字支持和语法
------------------------------------

Python 3.0 changes the syntax for octal (base-8) integer literals,
prefixing them with "0o" or "0O" instead of a leading zero, and adds
support for binary (base-2) integer literals, signalled by a "0b" or
"0B" prefix.

Python 2.6 doesn’t drop support for a leading 0 signalling an octal
number, but it does add support for "0o" and "0b":

     >>> 0o21, 2*8 + 1
     (17, 17)
     >>> 0b101111
     47

The *note oct(): c6d. builtin still returns numbers prefixed with a
leading zero, and a new *note bin(): c48. builtin returns the binary
representation for a number:

     >>> oct(42)
     '052'
     >>> future_builtins.oct(42)
     '0o52'
     >>> bin(173)
     '0b10101101'

The *note int(): 185. and ‘long()’ builtins will now accept the "0o" and
"0b" prefixes when base-8 or base-2 are requested, or when the `base'
argument is zero (signalling that the base used should be determined
from the string):

     >>> int ('0o52', 0)
     42
     >>> int('1101', 2)
     13
     >>> int('0b1101', 2)
     13
     >>> int('0b1101', 0)
     13

参见
....

PEP 3127(1) - 整型文字支持和语法

     PEP written by Patrick Maupin; backported to 2.6 by Eric Smith.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3127


File: python.info,  Node: PEP 3129 类装饰器,  Next: PEP 3141 A Type Hierarchy for Numbers,  Prev: PEP 3127 整型文字支持和语法,  Up: Python 2 6 有什么新变化

1.11.15 PEP 3129: 类装饰器
--------------------------

Decorators have been extended from functions to classes.  It’s now legal
to write:

     @foo
     @bar
     class A:
       pass

这相当于:

     class A:
       pass

     A = foo(bar(A))

参见
....

PEP 3129(1) - 类装饰器

     PEP 由 Collin Winter 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3129


File: python.info,  Node: PEP 3141 A Type Hierarchy for Numbers,  Next: 其他语言特性修改<10>,  Prev: PEP 3129 类装饰器,  Up: Python 2 6 有什么新变化

1.11.16 PEP 3141: A Type Hierarchy for Numbers
----------------------------------------------

Python 3.0 adds several abstract base classes for numeric types inspired
by Scheme’s numeric tower.  These classes were backported to 2.6 as the
*note numbers: c2. module.

The most general ABC is ‘Number’.  It defines no operations at all, and
only exists to allow checking if an object is a number by doing
‘isinstance(obj, Number)’.

‘Complex’ is a subclass of ‘Number’.  Complex numbers can undergo the
basic operations of addition, subtraction, multiplication, division, and
exponentiation, and you can retrieve the real and imaginary parts and
obtain a number’s conjugate.  Python’s built-in complex type is an
implementation of ‘Complex’.

‘Real’ further derives from ‘Complex’, and adds operations that only
work on real numbers: ‘floor()’, ‘trunc()’, rounding, taking the
remainder mod N, floor division, and comparisons.

‘Rational’ numbers derive from ‘Real’, have ‘numerator’ and
‘denominator’ properties, and can be converted to floats.  Python 2.6
adds a simple rational-number class, ‘Fraction’, in the *note fractions:
83. module.  (It’s called ‘Fraction’ instead of ‘Rational’ to avoid a
name clash with *note numbers.Rational: c60.)

‘Integral’ numbers derive from ‘Rational’, and can be shifted left and
right with ‘<<’ and ‘>>’, combined using bitwise operations such as ‘&’
and ‘|’, and can be used as array indexes and slice boundaries.

In Python 3.0, the PEP slightly redefines the existing builtins *note
round(): c75, *note math.floor(): d34, *note math.ceil(): d35, and adds
a new one, *note math.trunc(): d36, that’s been backported to Python
2.6.  *note math.trunc(): d36. rounds toward zero, returning the closest
‘Integral’ that’s between the function’s argument and zero.

参见
....

PEP 3141(1) - A Type Hierarchy for Numbers

     PEP 由 Jeffrey Yasskin 撰写

Scheme’s numerical tower(2), from the Guile manual.

Scheme’s number datatypes(3) from the R5RS Scheme specification.

* Menu:

* fractions 模块::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3141

   (2) 
https://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower

   (3) 
http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2


File: python.info,  Node: fractions 模块,  Up: PEP 3141 A Type Hierarchy for Numbers

1.11.16.1 ‘fractions’ 模块
..........................

To fill out the hierarchy of numeric types, the *note fractions: 83.
module provides a rational-number class.  Rational numbers store their
values as a numerator and denominator forming a fraction, and can
exactly represent numbers such as ‘2/3’ that floating-point numbers can
only approximate.

The ‘Fraction’ constructor takes two ‘Integral’ values that will be the
numerator and denominator of the resulting fraction.

     >>> from fractions import Fraction
     >>> a = Fraction(2, 3)
     >>> b = Fraction(2, 5)
     >>> float(a), float(b)
     (0.66666666666666663, 0.40000000000000002)
     >>> a+b
     Fraction(16, 15)
     >>> a/b
     Fraction(5, 3)

For converting floating-point numbers to rationals, the float type now
has an ‘as_integer_ratio()’ method that returns the numerator and
denominator for a fraction that evaluates to the same floating-point
value:

     >>> (2.5) .as_integer_ratio()
     (5, 2)
     >>> (3.1415) .as_integer_ratio()
     (7074029114692207L, 2251799813685248L)
     >>> (1./3) .as_integer_ratio()
     (6004799503160661L, 18014398509481984L)

Note that values that can only be approximated by floating-point
numbers, such as 1./3, are not simplified to the number being
approximated; the fraction attempts to match the floating-point value
`exactly'.

The *note fractions: 83. module is based upon an implementation by
Sjoerd Mullender that was in Python’s ‘Demo/classes/’ directory for a
long time.  This implementation was significantly updated by Jeffrey
Yasskin.


File: python.info,  Node: 其他语言特性修改<10>,  Next: 新增和改进的模块<2>,  Prev: PEP 3141 A Type Hierarchy for Numbers,  Up: Python 2 6 有什么新变化

1.11.17 其他语言特性修改
------------------------

对Python 语言核心进行的小改动：

   * Directories and zip archives containing a ‘__main__.py’ file can
     now be executed directly by passing their name to the interpreter.
     The directory or zip archive is automatically inserted as the first
     entry in sys.path.  (Suggestion and initial patch by Andy Chu,
     subsequently revised by Phillip J. Eby and Nick Coghlan;
     bpo-1739468(1).)

   * The *note hasattr(): 450. function was catching and ignoring all
     errors, under the assumption that they meant a *note __getattr__():
     323. method was failing somehow and the return value of *note
     hasattr(): 450. would therefore be ‘False’.  This logic shouldn’t
     be applied to *note KeyboardInterrupt: 198. and *note SystemExit:
     605, however; Python 2.6 will no longer discard such exceptions
     when *note hasattr(): 450. encounters them.  (Fixed by Benjamin
     Peterson; bpo-2196(2).)

   * When calling a function using the ‘**’ syntax to provide keyword
     arguments, you are no longer required to use a Python dictionary;
     any mapping will now work:

          >>> def f(**kw):
          ...    print sorted(kw)
          ...
          >>> ud=UserDict.UserDict()
          >>> ud['a'] = 1
          >>> ud['b'] = 'string'
          >>> f(**ud)
          ['a', 'b']

     （由 Alexander Belopolsky 在 bpo-1686487(3) 中贡献。）

     It’s also become legal to provide keyword arguments after a ‘*args’
     argument to a function call.

          >>> def f(*args, **kw):
          ...     print args, kw
          ...
          >>> f(1,2,3, *(4,5,6), keyword=13)
          (1, 2, 3, 4, 5, 6) {'keyword': 13}

     Previously this would have been a syntax error.  (Contributed by
     Amaury Forgeot d’Arc; bpo-3473(4).)

   * A new builtin, ‘next(iterator, [default])’ returns the next item
     from the specified iterator.  If the `default' argument is
     supplied, it will be returned if `iterator' has been exhausted;
     otherwise, the *note StopIteration: 48e. exception will be raised.
     (Backported in bpo-2719(5).)

   * Tuples now have ‘index()’ and ‘count()’ methods matching the list
     type’s ‘index()’ and ‘count()’ methods:

          >>> t = (0,1,2,3,4,0,1,2)
          >>> t.index(3)
          3
          >>> t.count(0)
          2

     （由 Raymond Hettinger 贡献）

   * The built-in types now have improved support for extended slicing
     syntax, accepting various combinations of ‘(start, stop, step)’.
     Previously, the support was partial and certain corner cases
     wouldn’t work.  (Implemented by Thomas Wouters.)

   * Properties now have three attributes, ‘getter’, ‘setter’ and
     ‘deleter’, that are decorators providing useful shortcuts for
     adding a getter, setter or deleter function to an existing
     property.  You would use them like this:

          class C(object):
              @property
              def x(self):
                  return self._x

              @x.setter
              def x(self, value):
                  self._x = value

              @x.deleter
              def x(self):
                  del self._x

          class D(C):
              @C.x.getter
              def x(self):
                  return self._x * 2

              @x.setter
              def x(self, value):
                  self._x = value / 2

   * Several methods of the built-in set types now accept multiple
     iterables: ‘intersection()’, ‘intersection_update()’, ‘union()’,
     ‘update()’, ‘difference()’ and ‘difference_update()’.

          >>> s=set('1234567890')
          >>> s.intersection('abc123', 'cdf246')  # Intersection between all inputs
          set(['2'])
          >>> s.difference('246', '789')
          set(['1', '0', '3', '5'])

     （由 Raymond Hettinger 贡献。）

   * Many floating-point features were added.  The *note float(): 188.
     function will now turn the string ‘nan’ into an IEEE 754 Not A
     Number value, and ‘+inf’ and ‘-inf’ into positive or negative
     infinity.  This works on any platform with IEEE 754 semantics.
     (Contributed by Christian Heimes; bpo-1635(6).)

     Other functions in the *note math: b2. module, ‘isinf()’ and
     ‘isnan()’, return true if their floating-point argument is infinite
     or Not A Number.  (bpo-1640(7))

     Conversion functions were added to convert floating-point numbers
     into hexadecimal strings (bpo-3008(8)).  These functions convert
     floats to and from a string representation without introducing
     rounding errors from the conversion between decimal and binary.
     Floats have a *note hex(): c6e. method that returns a string
     representation, and the ‘float.fromhex()’ method converts a string
     back into a number:

          >>> a = 3.75
          >>> a.hex()
          '0x1.e000000000000p+1'
          >>> float.fromhex('0x1.e000000000000p+1')
          3.75
          >>> b=1./3
          >>> b.hex()
          '0x1.5555555555555p-2'

   * A numerical nicety: when creating a complex number from two floats
     on systems that support signed zeros (-0 and +0), the *note
     complex(): 18a. constructor will now preserve the sign of the zero.
     (Fixed by Mark T. Dickinson; bpo-1507(9).)

   * Classes that inherit a *note __hash__(): 349. method from a parent
     class can set ‘__hash__ = None’ to indicate that the class isn’t
     hashable.  This will make ‘hash(obj)’ raise a *note TypeError: 193.
     and the class will not be indicated as implementing the ‘Hashable’
     ABC.

     You should do this when you’ve defined a ‘__cmp__()’ or *note
     __eq__(): 348. method that compares objects by their value rather
     than by identity.  All objects have a default hash method that uses
     ‘id(obj)’ as the hash value.  There’s no tidy way to remove the
     *note __hash__(): 349. method inherited from a parent class, so
     assigning ‘None’ was implemented as an override.  At the C level,
     extensions can set ‘tp_hash’ to *note
     PyObject_HashNotImplemented(): d39.  (Fixed by Nick Coghlan and
     Amaury Forgeot d’Arc; bpo-2235(10).)

   * The *note GeneratorExit: d3a. exception now subclasses *note
     BaseException: 1a9. instead of *note Exception: 1aa.  This means
     that an exception handler that does ‘except Exception:’ will not
     inadvertently catch *note GeneratorExit: d3a.  (Contributed by Chad
     Austin; bpo-1537(11).)

   * Generator objects now have a ‘gi_code’ attribute that refers to the
     original code object backing the generator.  (Contributed by Collin
     Winter; bpo-1473257(12).)

   * The *note compile(): 1b5. built-in function now accepts keyword
     arguments as well as positional parameters.  (Contributed by Thomas
     Wouters; bpo-1444529(13).)

   * The *note complex(): 18a. constructor now accepts strings
     containing parenthesized complex numbers, meaning that
     ‘complex(repr(cplx))’ will now round-trip values.  For example,
     ‘complex('(3+4j)')’ now returns the value (3+4j).
     (bpo-1491866(14))

   * The string ‘translate()’ method now accepts ‘None’ as the
     translation table parameter, which is treated as the identity
     transformation.  This makes it easier to carry out operations that
     only delete characters.  (Contributed by Bengt Richter and
     implemented by Raymond Hettinger; bpo-1193128(15).)

   * The built-in *note dir(): d3b. function now checks for a *note
     __dir__(): 324. method on the objects it receives.  This method
     must return a list of strings containing the names of valid
     attributes for the object, and lets the object control the value
     that *note dir(): d3b. produces.  Objects that have *note
     __getattr__(): 323. or *note __getattribute__(): 44f. methods can
     use this to advertise pseudo-attributes they will honor.
     (bpo-1591665(16))

   * Instance method objects have new attributes for the object and
     function comprising the method; the new synonym for ‘im_self’ is
     ‘__self__’, and ‘im_func’ is also available as ‘__func__’.  The old
     names are still supported in Python 2.6, but are gone in 3.0.

   * An obscure change: when you use the *note locals(): 45d. function
     inside a *note class: c72. statement, the resulting dictionary no
     longer returns free variables.  (Free variables, in this case, are
     variables referenced in the ‘class’ statement that aren’t
     attributes of the class.)

* Menu:

* 性能优化: 性能优化<9>.
* Interpreter Changes: Interpreter Changes<2>.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1739468

   (2) https://bugs.python.org/issue2196

   (3) https://bugs.python.org/issue1686487

   (4) https://bugs.python.org/issue3473

   (5) https://bugs.python.org/issue2719

   (6) https://bugs.python.org/issue1635

   (7) https://bugs.python.org/issue1640

   (8) https://bugs.python.org/issue3008

   (9) https://bugs.python.org/issue1507

   (10) https://bugs.python.org/issue2235

   (11) https://bugs.python.org/issue1537

   (12) https://bugs.python.org/issue1473257

   (13) https://bugs.python.org/issue1444529

   (14) https://bugs.python.org/issue1491866

   (15) https://bugs.python.org/issue1193128

   (16) https://bugs.python.org/issue1591665


File: python.info,  Node: 性能优化<9>,  Next: Interpreter Changes<2>,  Up: 其他语言特性修改<10>

1.11.17.1 性能优化
..................

   * The *note warnings: 127. module has been rewritten in C. This makes
     it possible to invoke warnings from the parser, and may also make
     the interpreter’s startup faster.  (Contributed by Neal Norwitz and
     Brett Cannon; bpo-1631171(1).)

   * Type objects now have a cache of methods that can reduce the work
     required to find the correct method implementation for a particular
     class; once cached, the interpreter doesn’t need to traverse base
     classes to figure out the right method to call.  The cache is
     cleared if a base class or the class itself is modified, so the
     cache should remain correct even in the face of Python’s dynamic
     nature.  (Original optimization implemented by Armin Rigo, updated
     for Python 2.6 by Kevin Jacobs; bpo-1700288(2).)

     By default, this change is only applied to types that are included
     with the Python core.  Extension modules may not necessarily be
     compatible with this cache, so they must explicitly add
     ‘Py_TPFLAGS_HAVE_VERSION_TAG’ to the module’s ‘tp_flags’ field to
     enable the method cache.  (To be compatible with the method cache,
     the extension module’s code must not directly access and modify the
     ‘tp_dict’ member of any of the types it implements.  Most modules
     don’t do this, but it’s impossible for the Python interpreter to
     determine that.  See bpo-1878(3) for some discussion.)

   * Function calls that use keyword arguments are significantly faster
     by doing a quick pointer comparison, usually saving the time of a
     full string comparison.  (Contributed by Raymond Hettinger, after
     an initial implementation by Antoine Pitrou; bpo-1819(4).)

   * All of the functions in the *note struct: f9. module have been
     rewritten in C, thanks to work at the Need For Speed sprint.
     (Contributed by Raymond Hettinger.)

   * Some of the standard built-in types now set a bit in their type
     objects.  This speeds up checking whether an object is a subclass
     of one of these types.  (Contributed by Neal Norwitz.)

   * Unicode strings now use faster code for detecting whitespace and
     line breaks; this speeds up the ‘split()’ method by about 25% and
     ‘splitlines()’ by 35%.  (Contributed by Antoine Pitrou.)  Memory
     usage is reduced by using pymalloc for the Unicode string’s data.

   * The ‘with’ statement now stores the *note __exit__(): c9e. method
     on the stack, producing a small speedup.  (Implemented by Jeffrey
     Yasskin.)

   * To reduce memory usage, the garbage collector will now clear
     internal free lists when garbage-collecting the highest generation
     of objects.  This may return memory to the operating system sooner.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1631171

   (2) https://bugs.python.org/issue1700288

   (3) https://bugs.python.org/issue1878

   (4) https://bugs.python.org/issue1819


File: python.info,  Node: Interpreter Changes<2>,  Prev: 性能优化<9>,  Up: 其他语言特性修改<10>

1.11.17.2 Interpreter Changes
.............................

Two command-line options have been reserved for use by other Python
implementations.  The *note -J: d3f. switch has been reserved for use by
Jython for Jython-specific options, such as switches that are passed to
the underlying JVM. *note -X: 156. has been reserved for options
specific to a particular implementation of Python such as CPython,
Jython, or IronPython.  If either option is used with Python 2.6, the
interpreter will report that the option isn’t currently used.

Python can now be prevented from writing ‘.pyc’ or ‘.pyo’ files by
supplying the *note -B: d40. switch to the Python interpreter, or by
setting the *note PYTHONDONTWRITEBYTECODE: d41. environment variable
before running the interpreter.  This setting is available to Python
programs as the ‘sys.dont_write_bytecode’ variable, and Python code can
change the value to modify the interpreter’s behaviour.  (Contributed by
Neal Norwitz and Georg Brandl.)

The encoding used for standard input, output, and standard error can be
specified by setting the *note PYTHONIOENCODING: 937. environment
variable before running the interpreter.  The value should be a string
in the form ‘<encoding>’ or ‘<encoding>:<errorhandler>’.  The `encoding'
part specifies the encoding’s name, e.g.  ‘utf-8’ or ‘latin-1’; the
optional `errorhandler' part specifies what to do with characters that
can’t be handled by the encoding, and should be one of "error",
"ignore", or "replace".  (Contributed by Martin von Löwis.)


File: python.info,  Node: 新增和改进的模块<2>,  Next: Deprecations and Removals,  Prev: 其他语言特性修改<10>,  Up: Python 2 6 有什么新变化

1.11.18 新增和改进的模块
------------------------

As in every release, Python’s standard library received a number of
enhancements and bug fixes.  Here’s a partial list of the most notable
changes, sorted alphabetically by module name.  Consult the ‘Misc/NEWS’
file in the source tree for a more complete list of changes, or look
through the Subversion logs for all the details.

   * The *note asyncore: b. and *note asynchat: 9. modules are being
     actively maintained again, and a number of patches and bugfixes
     were applied.  (Maintained by Josiah Carlson; see bpo-1736190(1)
     for one patch.)

   * The ‘bsddb’ module also has a new maintainer, Jesús Cea Avión, and
     the package is now available as a standalone package.  The web page
     for the package is www.jcea.es/programacion/pybsddb.htm(2).  The
     plan is to remove the package from the standard library in Python
     3.0, because its pace of releases is much more frequent than
     Python’s.

     The ‘bsddb.dbshelve’ module now uses the highest pickling protocol
     available, instead of restricting itself to protocol 1.
     (Contributed by W. Barnes.)

   * The *note cgi: 16. module will now read variables from the query
     string of an HTTP POST request.  This makes it possible to use form
     actions with URLs that include query strings such as
     "/cgi-bin/add.py?category=1".  (Contributed by Alexandre Fiori and
     Nubis; bpo-1817(3).)

     The ‘parse_qs()’ and ‘parse_qsl()’ functions have been relocated
     from the *note cgi: 16. module to the ‘urlparse’ module.  The
     versions still available in the *note cgi: 16. module will trigger
     *note PendingDeprecationWarning: 27a. messages in 2.6
     (bpo-600362(4)).

   * The *note cmath: 19. module underwent extensive revision,
     contributed by Mark Dickinson and Christian Heimes.  Five new
     functions were added:

        * ‘polar()’ converts a complex number to polar form, returning
          the modulus and argument of the complex number.

        * ‘rect()’ does the opposite, turning a modulus, argument pair
          back into the corresponding complex number.

        * ‘phase()’ returns the argument (also called the angle) of a
          complex number.

        * ‘isnan()’ returns True if either the real or imaginary part of
          its argument is a NaN.

        * ‘isinf()’ returns True if either the real or imaginary part of
          its argument is infinite.

     The revisions also improved the numerical soundness of the *note
     cmath: 19. module.  For all functions, the real and imaginary parts
     of the results are accurate to within a few units of least
     precision (ulps) whenever possible.  See bpo-1381(5) for the
     details.  The branch cuts for ‘asinh()’, ‘atanh()’: and ‘atan()’
     have also been corrected.

     The tests for the module have been greatly expanded; nearly 2000
     new test cases exercise the algebraic functions.

     On IEEE 754 platforms, the *note cmath: 19. module now handles IEEE
     754 special values and floating-point exceptions in a manner
     consistent with Annex ’G’ of the C99 standard.

   * A new data type in the *note collections: 1e. module:
     ‘namedtuple(typename, fieldnames)’ is a factory function that
     creates subclasses of the standard tuple whose fields are
     accessible by name as well as index.  For example:

          >>> var_type = collections.namedtuple('variable',
          ...             'id name type size')
          >>> # Names are separated by spaces or commas.
          >>> # 'id, name, type, size' would also work.
          >>> var_type._fields
          ('id', 'name', 'type', 'size')

          >>> var = var_type(1, 'frequency', 'int', 4)
          >>> print var[0], var.id    # Equivalent
          1 1
          >>> print var[2], var.type  # Equivalent
          int int
          >>> var._asdict()
          {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
          >>> v2 = var._replace(name='amplitude')
          >>> v2
          variable(id=1, name='amplitude', type='int', size=4)

     Several places in the standard library that returned tuples have
     been modified to return ‘namedtuple’ instances.  For example, the
     ‘Decimal.as_tuple()’ method now returns a named tuple with ‘sign’,
     ‘digits’, and ‘exponent’ fields.

     （由 Raymond Hettinger 贡献。）

   * Another change to the *note collections: 1e. module is that the
     ‘deque’ type now supports an optional `maxlen' parameter; if
     supplied, the deque’s size will be restricted to no more than
     `maxlen' items.  Adding more items to a full deque causes old items
     to be discarded.

          >>> from collections import deque
          >>> dq=deque(maxlen=3)
          >>> dq
          deque([], maxlen=3)
          >>> dq.append(1); dq.append(2); dq.append(3)
          >>> dq
          deque([1, 2, 3], maxlen=3)
          >>> dq.append(4)
          >>> dq
          deque([2, 3, 4], maxlen=3)

     （由 Raymond Hettinger 贡献。）

   * The ‘Cookie’ module’s ‘Morsel’ objects now support an ‘httponly’
     attribute.  In some browsers.  cookies with this attribute set
     cannot be accessed or manipulated by JavaScript code.  (Contributed
     by Arvin Schnell; bpo-1638033(6).)

   * A new window method in the *note curses: 2c. module, ‘chgat()’,
     changes the display attributes for a certain number of characters
     on a single line.  (Contributed by Fabian Kreutz.)

          # Boldface text starting at y=0,x=21
          # and affecting the rest of the line.
          stdscr.chgat(0, 21, curses.A_BOLD)

     The ‘Textbox’ class in the *note curses.textpad: 2f. module now
     supports editing in insert mode as well as overwrite mode.  Insert
     mode is enabled by supplying a true value for the `insert_mode'
     parameter when creating the ‘Textbox’ instance.

   * The *note datetime: 31. module’s ‘strftime()’ methods now support a
     ‘%f’ format code that expands to the number of microseconds in the
     object, zero-padded on the left to six places.  (Contributed by
     Skip Montanaro; bpo-1158(7).)

   * The *note decimal: 36. module was updated to version 1.66 of the
     General Decimal Specification(8).  New features include some
     methods for some basic mathematical functions such as ‘exp()’ and
     ‘log10()’:

          >>> Decimal(1).exp()
          Decimal("2.718281828459045235360287471")
          >>> Decimal("2.7182818").ln()
          Decimal("0.9999999895305022877376682436")
          >>> Decimal(1000).log10()
          Decimal("3")

     The ‘as_tuple()’ method of ‘Decimal’ objects now returns a named
     tuple with ‘sign’, ‘digits’, and ‘exponent’ fields.

     (Implemented by Facundo Batista and Mark Dickinson.  Named tuple
     support added by Raymond Hettinger.)

   * The *note difflib: 37. module’s ‘SequenceMatcher’ class now returns
     named tuples representing matches, with ‘a’, ‘b’, and ‘size’
     attributes.  (Contributed by Raymond Hettinger.)

   * An optional ‘timeout’ parameter, specifying a timeout measured in
     seconds, was added to the *note ftplib.FTP: 2f1. class constructor
     as well as the ‘connect()’ method.  (Added by Facundo Batista.)
     Also, the ‘FTP’ class’s ‘storbinary()’ and ‘storlines()’ now take
     an optional `callback' parameter that will be called with each
     block of data after the data has been sent.  (Contributed by Phil
     Schwartz; bpo-1221598(9).)

   * The ‘reduce()’ built-in function is also available in the *note
     functools: 85. module.  In Python 3.0, the builtin has been dropped
     and ‘reduce()’ is only available from *note functools: 85.;
     currently there are no plans to drop the builtin in the 2.x series.
     (Patched by Christian Heimes; bpo-1739906(10).)

   * When possible, the *note getpass: 88. module will now use
     ‘/dev/tty’ to print a prompt message and read the password, falling
     back to standard error and standard input.  If the password may be
     echoed to the terminal, a warning is printed before the prompt is
     displayed.  (Contributed by Gregory P. Smith.)

   * The *note glob.glob(): 5cf. function can now return Unicode
     filenames if a Unicode path was used and Unicode filenames are
     matched within the directory.  (bpo-1001604(11))

   * A new function in the *note heapq: 8e. module, ‘merge(iter1, iter2,
     ...)’, takes any number of iterables returning data in sorted
     order, and returns a new generator that returns the contents of all
     the iterators, also in sorted order.  For example:

          >>> list(heapq.merge([1, 3, 5, 9], [2, 8, 16]))
          [1, 2, 3, 5, 8, 9, 16]

     Another new function, ‘heappushpop(heap, item)’, pushes `item' onto
     `heap', then pops off and returns the smallest item.  This is more
     efficient than making a call to ‘heappush()’ and then ‘heappop()’.

     *note heapq: 8e. is now implemented to only use less-than
     comparison, instead of the less-than-or-equal comparison it
     previously used.  This makes *note heapq: 8e.’s usage of a type
     match the *note list.sort(): 44d. method.  (Contributed by Raymond
     Hettinger.)

   * An optional ‘timeout’ parameter, specifying a timeout measured in
     seconds, was added to the ‘httplib.HTTPConnection’ and
     ‘HTTPSConnection’ class constructors.  (Added by Facundo Batista.)

   * Most of the *note inspect: a1. module’s functions, such as
     ‘getmoduleinfo()’ and ‘getargs()’, now return named tuples.  In
     addition to behaving like tuples, the elements of the return value
     can also be accessed as attributes.  (Contributed by Raymond
     Hettinger.)

     Some new functions in the module include ‘isgenerator()’,
     ‘isgeneratorfunction()’, and ‘isabstract()’.

   * The *note itertools: a4. module gained several new functions.

     ‘izip_longest(iter1, iter2, ...[, fillvalue])’ makes tuples from
     each of the elements; if some of the iterables are shorter than
     others, the missing values are set to `fillvalue'.  For example:

          >>> tuple(itertools.izip_longest([1,2,3], [1,2,3,4,5]))
          ((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))

     ‘product(iter1, iter2, ..., [repeat=N])’ returns the Cartesian
     product of the supplied iterables, a set of tuples containing every
     possible combination of the elements returned from each iterable.

          >>> list(itertools.product([1,2,3], [4,5,6]))
          [(1, 4), (1, 5), (1, 6),
           (2, 4), (2, 5), (2, 6),
           (3, 4), (3, 5), (3, 6)]

     The optional `repeat' keyword argument is used for taking the
     product of an iterable or a set of iterables with themselves,
     repeated `N' times.  With a single iterable argument, `N'-tuples
     are returned:

          >>> list(itertools.product([1,2], repeat=3))
          [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
           (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]

     With two iterables, `2N'-tuples are returned.

          >>> list(itertools.product([1,2], [3,4], repeat=2))
          [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
           (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
           (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
           (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]

     ‘combinations(iterable, r)’ returns sub-sequences of length `r'
     from the elements of `iterable'.

          >>> list(itertools.combinations('123', 2))
          [('1', '2'), ('1', '3'), ('2', '3')]
          >>> list(itertools.combinations('123', 3))
          [('1', '2', '3')]
          >>> list(itertools.combinations('1234', 3))
          [('1', '2', '3'), ('1', '2', '4'),
           ('1', '3', '4'), ('2', '3', '4')]

     ‘permutations(iter[, r])’ returns all the permutations of length
     `r' of the iterable’s elements.  If `r' is not specified, it will
     default to the number of elements produced by the iterable.

          >>> list(itertools.permutations([1,2,3,4], 2))
          [(1, 2), (1, 3), (1, 4),
           (2, 1), (2, 3), (2, 4),
           (3, 1), (3, 2), (3, 4),
           (4, 1), (4, 2), (4, 3)]

     ‘itertools.chain(*iterables)’ is an existing function in *note
     itertools: a4. that gained a new constructor in Python 2.6.
     ‘itertools.chain.from_iterable(iterable)’ takes a single iterable
     that should return other iterables.  ‘chain()’ will then return all
     the elements of the first iterable, then all the elements of the
     second, and so on.

          >>> list(itertools.chain.from_iterable([[1,2,3], [4,5,6]]))
          [1, 2, 3, 4, 5, 6]

     (All contributed by Raymond Hettinger.)

   * The *note logging: ab. module’s ‘FileHandler’ class and its
     subclasses ‘WatchedFileHandler’, ‘RotatingFileHandler’, and
     ‘TimedRotatingFileHandler’ now have an optional `delay' parameter
     to their constructors.  If `delay' is true, opening of the log file
     is deferred until the first ‘emit()’ call is made.  (Contributed by
     Vinay Sajip.)

     ‘TimedRotatingFileHandler’ also has a `utc' constructor parameter.
     If the argument is true, UTC time will be used in determining when
     midnight occurs and in generating filenames; otherwise local time
     will be used.

   * Several new functions were added to the *note math: b2. module:

        * *note isinf(): d43. and *note isnan(): d44. determine whether
          a given float is a (positive or negative) infinity or a NaN
          (Not a Number), respectively.

        * *note copysign(): d45. copies the sign bit of an IEEE 754
          number, returning the absolute value of `x' combined with the
          sign bit of `y'.  For example, ‘math.copysign(1, -0.0)’
          returns -1.0.  (Contributed by Christian Heimes.)

        * *note factorial(): 1eb. computes the factorial of a number.
          (Contributed by Raymond Hettinger; bpo-2138(12).)

        * *note fsum(): d46. adds up the stream of numbers from an
          iterable, and is careful to avoid loss of precision through
          using partial sums.  (Contributed by Jean Brouwers, Raymond
          Hettinger, and Mark Dickinson; bpo-2819(13).)

        * *note acosh(): d47, *note asinh(): d48. and *note atanh():
          d49. compute the inverse hyperbolic functions.

        * *note log1p(): d4a. returns the natural logarithm of `1+x'
          (base `e').

        * ‘trunc()’ rounds a number toward zero, returning the closest
          ‘Integral’ that’s between the function’s argument and zero.
          Added as part of the backport of *note PEP 3141’s type
          hierarchy for numbers: c5f.

   * The *note math: b2. module has been improved to give more
     consistent behaviour across platforms, especially with respect to
     handling of floating-point exceptions and IEEE 754 special values.

     Whenever possible, the module follows the recommendations of the
     C99 standard about 754’s special values.  For example, ‘sqrt(-1.)’
     should now give a *note ValueError: 1fc. across almost all
     platforms, while ‘sqrt(float('NaN'))’ should return a NaN on all
     IEEE 754 platforms.  Where Annex ’F’ of the C99 standard recommends
     signaling ’divide-by-zero’ or ’invalid’, Python will raise *note
     ValueError: 1fc.  Where Annex ’F’ of the C99 standard recommends
     signaling ’overflow’, Python will raise *note OverflowError: 968.
     (See bpo-711019(14) and bpo-1640(15).)

     （由 Christian Heimes 和 Mark Dickinson 贡献。）

   * *note mmap: 1ed. objects now have a ‘rfind()’ method that searches
     for a substring beginning at the end of the string and searching
     backwards.  The ‘find()’ method also gained an `end' parameter
     giving an index at which to stop searching.  (Contributed by John
     Lenton.)

   * The *note operator: c3. module gained a ‘methodcaller()’ function
     that takes a name and an optional set of arguments, returning a
     callable that will call the named function on any arguments passed
     to it.  For example:

          >>> # Equivalent to lambda s: s.replace('old', 'new')
          >>> replacer = operator.methodcaller('replace', 'old', 'new')
          >>> replacer('old wine in old bottles')
          'new wine in new bottles'

     （由 Gregory Petrosyan 提供建议，之后由 Georg Brandl 贡献。）

     The ‘attrgetter()’ function now accepts dotted names and performs
     the corresponding attribute lookups:

          >>> inst_name = operator.attrgetter(
          ...        '__class__.__name__')
          >>> inst_name('')
          'str'
          >>> inst_name(help)
          '_Helper'

     （由 Barry Warsaw 提供建议，之后由 Georg Brandl 贡献。）

   * The *note os: c5. module now wraps several new system calls.
     ‘fchmod(fd, mode)’ and ‘fchown(fd, uid, gid)’ change the mode and
     ownership of an opened file, and ‘lchmod(path, mode)’ changes the
     mode of a symlink.  (Contributed by Georg Brandl and Christian
     Heimes.)

     ‘chflags()’ and ‘lchflags()’ are wrappers for the corresponding
     system calls (where they’re available), changing the flags set on a
     file.  Constants for the flag values are defined in the *note stat:
     f5. module; some possible values include ‘UF_IMMUTABLE’ to signal
     the file may not be changed and ‘UF_APPEND’ to indicate that data
     can only be appended to the file.  (Contributed by M. Levinson.)

     ‘os.closerange(low, high)’ efficiently closes all file descriptors
     from `low' to `high', ignoring any errors and not including `high'
     itself.  This function is now used by the *note subprocess: fa.
     module to make starting processes faster.  (Contributed by Georg
     Brandl; bpo-1663329(16).)

   * The ‘os.environ’ object’s ‘clear()’ method will now unset the
     environment variables using *note os.unsetenv(): d4b. in addition
     to clearing the object’s keys.  (Contributed by Martin Horcicka;
     bpo-1181(17).)

   * The *note os.walk(): 65d. function now has a ‘followlinks’
     parameter.  If set to True, it will follow symlinks pointing to
     directories and visit the directory’s contents.  For backward
     compatibility, the parameter’s default value is false.  Note that
     the function can fall into an infinite recursion if there’s a
     symlink that points to a parent directory.  (bpo-1273829(18))

   * In the *note os.path: c6. module, the ‘splitext()’ function has
     been changed to not split on leading period characters.  This
     produces better results when operating on Unix’s dot-files.  For
     example, ‘os.path.splitext('.ipython')’ now returns ‘('.ipython',
     '')’ instead of ‘('', '.ipython')’.  (bpo-1115886(19))

     A new function, ‘os.path.relpath(path, start='.')’, returns a
     relative path from the ‘start’ path, if it’s supplied, or from the
     current working directory to the destination ‘path’.  (Contributed
     by Richard Barran; bpo-1339796(20).)

     On Windows, *note os.path.expandvars(): d4c. will now expand
     environment variables given in the form "%var%", and "~user" will
     be expanded into the user’s home directory path.  (Contributed by
     Josiah Carlson; bpo-957650(21).)

   * The Python debugger provided by the *note pdb: ca. module gained a
     new command: "run" restarts the Python program being debugged and
     can optionally take new command-line arguments for the program.
     (Contributed by Rocky Bernstein; bpo-1393667(22).)

   * The *note pdb.post_mortem(): d4d. function, used to begin debugging
     a traceback, will now use the traceback returned by *note
     sys.exc_info(): c67. if no traceback is supplied.  (Contributed by
     Facundo Batista; bpo-1106316(23).)

   * The *note pickletools: cc. module now has an ‘optimize()’ function
     that takes a string containing a pickle and removes some unused
     opcodes, returning a shorter pickle that contains the same data
     structure.  (Contributed by Raymond Hettinger.)

   * A ‘get_data()’ function was added to the *note pkgutil: ce. module
     that returns the contents of resource files included with an
     installed Python package.  For example:

          >>> import pkgutil
          >>> print pkgutil.get_data('test', 'exception_hierarchy.txt')
          BaseException
           +-- SystemExit
           +-- KeyboardInterrupt
           +-- GeneratorExit
           +-- Exception
                +-- StopIteration
                +-- StandardError
           ...

     （由 Paul Moore 在 bpo-2439(24) 中贡献。）

   * The ‘pyexpat’ module’s ‘Parser’ objects now allow setting their
     ‘buffer_size’ attribute to change the size of the buffer used to
     hold character data.  (Contributed by Achim Gaedke; bpo-1137(25).)

   * The ‘Queue’ module now provides queue variants that retrieve
     entries in different orders.  The ‘PriorityQueue’ class stores
     queued items in a heap and retrieves them in priority order, and
     ‘LifoQueue’ retrieves the most recently added entries first,
     meaning that it behaves like a stack.  (Contributed by Raymond
     Hettinger.)

   * The *note random: dd. module’s ‘Random’ objects can now be pickled
     on a 32-bit system and unpickled on a 64-bit system, and vice
     versa.  Unfortunately, this change also means that Python 2.6’s
     ‘Random’ objects can’t be unpickled correctly on earlier versions
     of Python.  (Contributed by Shawn Ligocki; bpo-1727780(26).)

     The new ‘triangular(low, high, mode)’ function returns random
     numbers following a triangular distribution.  The returned values
     are between `low' and `high', not including `high' itself, and with
     `mode' as the most frequently occurring value in the distribution.
     (Contributed by Wladmir van der Laan and Raymond Hettinger;
     bpo-1681432(27).)

   * Long regular expression searches carried out by the *note re: de.
     module will check for signals being delivered, so time-consuming
     searches can now be interrupted.  (Contributed by Josh Hoyt and
     Ralf Schmitt; bpo-846388(28).)

     The regular expression module is implemented by compiling bytecodes
     for a tiny regex-specific virtual machine.  Untrusted code could
     create malicious strings of bytecode directly and cause crashes, so
     Python 2.6 includes a verifier for the regex bytecode.
     (Contributed by Guido van Rossum from work for Google App Engine;
     bpo-3487(29).)

   * The *note rlcompleter: e2. module’s ‘Completer.complete()’ method
     will now ignore exceptions triggered while evaluating a name.
     (Fixed by Lorenz Quack; bpo-2250(30).)

   * The *note sched: e4. module’s ‘scheduler’ instances now have a
     read-only *note queue: db. attribute that returns the contents of
     the scheduler’s queue, represented as a list of named tuples with
     the fields ‘(time, priority, action, argument)’.  (Contributed by
     Raymond Hettinger; bpo-1861(31).)

   * The *note select: e6. module now has wrapper functions for the
     Linux ‘epoll()’ and BSD ‘kqueue()’ system calls.  ‘modify()’ method
     was added to the existing ‘poll’ objects; ‘pollobj.modify(fd,
     eventmask)’ takes a file descriptor or file object and an event
     mask, modifying the recorded event mask for that file.
     (Contributed by Christian Heimes; bpo-1657(32).)

   * The *note shutil.copytree(): 21b. function now has an optional
     `ignore' argument that takes a callable object.  This callable will
     receive each directory path and a list of the directory’s contents,
     and returns a list of names that will be ignored, not copied.

     The *note shutil: ea. module also provides an ‘ignore_patterns()’
     function for use with this new parameter.  ‘ignore_patterns()’
     takes an arbitrary number of glob-style patterns and returns a
     callable that will ignore any files and directories that match any
     of these patterns.  The following example copies a directory tree,
     but skips both ‘.svn’ directories and Emacs backup files, which
     have names ending with ’~’:

          shutil.copytree('Doc/library', '/tmp/library',
                          ignore=shutil.ignore_patterns('*~', '.svn'))

     （由 Tarek Ziadé 在 bpo-2663(33) 中贡献。）

   * Integrating signal handling with GUI handling event loops like
     those used by Tkinter or GTk+ has long been a problem; most
     software ends up polling, waking up every fraction of a second to
     check if any GUI events have occurred.  The *note signal: eb.
     module can now make this more efficient.  Calling
     ‘signal.set_wakeup_fd(fd)’ sets a file descriptor to be used; when
     a signal is received, a byte is written to that file descriptor.
     There’s also a C-level function, *note PySignal_SetWakeupFd(): d4e,
     for setting the descriptor.

     Event loops will use this by opening a pipe to create two
     descriptors, one for reading and one for writing.  The writable
     descriptor will be passed to ‘set_wakeup_fd()’, and the readable
     descriptor will be added to the list of descriptors monitored by
     the event loop via ‘select()’ or ‘poll()’.  On receiving a signal,
     a byte will be written and the main event loop will be woken up,
     avoiding the need to poll.

     （由 Adam Olsen 在 bpo-1583(34) 中贡献。）

     The ‘siginterrupt()’ function is now available from Python code,
     and allows changing whether signals can interrupt system calls or
     not.  (Contributed by Ralf Schmitt.)

     The ‘setitimer()’ and ‘getitimer()’ functions have also been added
     (where they’re available).  ‘setitimer()’ allows setting interval
     timers that will cause a signal to be delivered to the process
     after a specified time, measured in wall-clock time, consumed
     process time, or combined process+system time.  (Contributed by
     Guilherme Polo; bpo-2240(35).)

   * The *note smtplib: ee. module now supports SMTP over SSL thanks to
     the addition of the ‘SMTP_SSL’ class.  This class supports an
     interface identical to the existing ‘SMTP’ class.  (Contributed by
     Monty Taylor.)  Both class constructors also have an optional
     ‘timeout’ parameter that specifies a timeout for the initial
     connection attempt, measured in seconds.  (Contributed by Facundo
     Batista.)

     An implementation of the LMTP protocol ( RFC 2033(36)) was also
     added to the module.  LMTP is used in place of SMTP when
     transferring e-mail between agents that don’t manage a mail queue.
     (LMTP implemented by Leif Hedstrom; bpo-957003(37).)

     ‘SMTP.starttls()’ now complies with RFC 3207(38) and forgets any
     knowledge obtained from the server not obtained from the TLS
     negotiation itself.  (Patch contributed by Bill Fenner;
     bpo-829951(39).)

   * The *note socket: f0. module now supports TIPC
     (‘http://tipc.sourceforge.net/’), a high-performance non-IP-based
     protocol designed for use in clustered environments.  TIPC
     addresses are 4- or 5-tuples.  (Contributed by Alberto Bertogli;
     bpo-1646(40).)

     A new function, ‘create_connection()’, takes an address and
     connects to it using an optional timeout value, returning the
     connected socket object.  This function also looks up the address’s
     type and connects to it using IPv4 or IPv6 as appropriate.
     Changing your code to use ‘create_connection()’ instead of
     ‘socket(socket.AF_INET, ...)’ may be all that’s required to make
     your code work with IPv6.

   * The base classes in the ‘SocketServer’ module now support calling a
     ‘handle_timeout()’ method after a span of inactivity specified by
     the server’s ‘timeout’ attribute.  (Contributed by Michael
     Pomraning.)  The ‘serve_forever()’ method now takes an optional
     poll interval measured in seconds, controlling how often the server
     will check for a shutdown request.  (Contributed by Pedro Werneck
     and Jeffrey Yasskin; bpo-742598(41), bpo-1193577(42).)

   * The *note sqlite3: f3. module, maintained by Gerhard Häring, has
     been updated from version 2.3.2 in Python 2.5 to version 2.4.1.

   * The *note struct: f9. module now supports the C99 ‘_Bool’ type,
     using the format character ‘'?'’.  (Contributed by David Remahl.)

   * The ‘Popen’ objects provided by the *note subprocess: fa. module
     now have ‘terminate()’, ‘kill()’, and ‘send_signal()’ methods.  On
     Windows, ‘send_signal()’ only supports the ‘SIGTERM’ signal, and
     all these methods are aliases for the Win32 API function
     ‘TerminateProcess()’.  (Contributed by Christian Heimes.)

   * A new variable in the *note sys: fe. module, ‘float_info’, is an
     object containing information derived from the ‘float.h’ file about
     the platform’s floating-point support.  Attributes of this object
     include ‘mant_dig’ (number of digits in the mantissa), ‘epsilon’
     (smallest difference between 1.0 and the next largest value
     representable), and several others.  (Contributed by Christian
     Heimes; bpo-1534(43).)

     Another new variable, ‘dont_write_bytecode’, controls whether
     Python writes any ‘.pyc’ or ‘.pyo’ files on importing a module.  If
     this variable is true, the compiled files are not written.  The
     variable is initially set on start-up by supplying the *note -B:
     d40. switch to the Python interpreter, or by setting the *note
     PYTHONDONTWRITEBYTECODE: d41. environment variable before running
     the interpreter.  Python code can subsequently change the value of
     this variable to control whether bytecode files are written or not.
     (Contributed by Neal Norwitz and Georg Brandl.)

     Information about the command-line arguments supplied to the Python
     interpreter is available by reading attributes of a named tuple
     available as ‘sys.flags’.  For example, the ‘verbose’ attribute is
     true if Python was executed in verbose mode, ‘debug’ is true in
     debugging mode, etc.  These attributes are all read-only.
     (Contributed by Christian Heimes.)

     A new function, ‘getsizeof()’, takes a Python object and returns
     the amount of memory used by the object, measured in bytes.
     Built-in objects return correct results; third-party extensions may
     not, but can define a ‘__sizeof__()’ method to return the object’s
     size.  (Contributed by Robert Schuppenies; bpo-2898(44).)

     It’s now possible to determine the current profiler and tracer
     functions by calling *note sys.getprofile(): d4f. and *note
     sys.gettrace(): d50.  (Contributed by Georg Brandl; bpo-1648(45).)

   * The *note tarfile: 102. module now supports POSIX.1-2001 (pax)
     tarfiles in addition to the POSIX.1-1988 (ustar) and GNU tar
     formats that were already supported.  The default format is GNU
     tar; specify the ‘format’ parameter to open a file using a
     different format:

          tar = tarfile.open("output.tar", "w",
                             format=tarfile.PAX_FORMAT)

     The new ‘encoding’ and ‘errors’ parameters specify an encoding and
     an error handling scheme for character conversions.  ‘'strict'’,
     ‘'ignore'’, and ‘'replace'’ are the three standard ways Python can
     handle errors,; ‘'utf-8'’ is a special value that replaces bad
     characters with their UTF-8 representation.  (Character conversions
     occur because the PAX format supports Unicode filenames, defaulting
     to UTF-8 encoding.)

     The ‘TarFile.add()’ method now accepts an ‘exclude’ argument that’s
     a function that can be used to exclude certain filenames from an
     archive.  The function must take a filename and return true if the
     file should be excluded or false if it should be archived.  The
     function is applied to both the name initially passed to ‘add()’
     and to the names of files in recursively-added directories.

     (All changes contributed by Lars Gustäbel).

   * An optional ‘timeout’ parameter was added to the *note
     telnetlib.Telnet: 5a0. class constructor, specifying a timeout
     measured in seconds.  (Added by Facundo Batista.)

   * The *note tempfile.NamedTemporaryFile: d51. class usually deletes
     the temporary file it created when the file is closed.  This
     behaviour can now be changed by passing ‘delete=False’ to the
     constructor.  (Contributed by Damien Miller; bpo-1537850(46).)

     A new class, ‘SpooledTemporaryFile’, behaves like a temporary file
     but stores its data in memory until a maximum size is exceeded.  On
     reaching that limit, the contents will be written to an on-disk
     temporary file.  (Contributed by Dustin J. Mitchell.)

     The ‘NamedTemporaryFile’ and ‘SpooledTemporaryFile’ classes both
     work as context managers, so you can write ‘with
     tempfile.NamedTemporaryFile() as tmp: ...’.  (Contributed by
     Alexander Belopolsky; bpo-2021(47).)

   * The ‘test.test_support’ module gained a number of context managers
     useful for writing tests.  ‘EnvironmentVarGuard()’ is a context
     manager that temporarily changes environment variables and
     automatically restores them to their old values.

     Another context manager, ‘TransientResource’, can surround calls to
     resources that may or may not be available; it will catch and
     ignore a specified list of exceptions.  For example, a network test
     may ignore certain failures when connecting to an external web
     site:

          with test_support.TransientResource(IOError,
                                          errno=errno.ETIMEDOUT):
              f = urllib.urlopen('https://sf.net')
              ...

     Finally, ‘check_warnings()’ resets the ‘warning’ module’s warning
     filters and returns an object that will record all warning messages
     triggered (bpo-3781(48)):

          with test_support.check_warnings() as wrec:
              warnings.simplefilter("always")
              # ... code that triggers a warning ...
              assert str(wrec.message) == "function is outdated"
              assert len(wrec.warnings) == 1, "Multiple warnings raised"

     （由 Brett Cannon 贡献。）

   * The *note textwrap: 109. module can now preserve existing
     whitespace at the beginnings and ends of the newly-created lines by
     specifying ‘drop_whitespace=False’ as an argument:

          >>> S = """This  sentence  has a bunch   of
          ...   extra   whitespace."""
          >>> print textwrap.fill(S, width=15)
          This  sentence
          has a bunch
          of    extra
          whitespace.
          >>> print textwrap.fill(S, drop_whitespace=False, width=15)
          This  sentence
            has a bunch
             of    extra
             whitespace.
          >>>

     （由 Dwayne Bailey 在 bpo-1581073(49) 中贡献。）

   * The *note threading: 10a. module API is being changed to use
     properties such as ‘daemon’ instead of ‘setDaemon()’ and
     ‘isDaemon()’ methods, and some methods have been renamed to use
     underscores instead of camel-case; for example, the ‘activeCount()’
     method is renamed to ‘active_count()’.  Both the 2.6 and 3.0
     versions of the module support the same properties and renamed
     methods, but don’t remove the old methods.  No date has been set
     for the deprecation of the old APIs in Python 3.x; the old APIs
     won’t be removed in any 2.x version.  (Carried out by several
     people, most notably Benjamin Peterson.)

     The *note threading: 10a. module’s ‘Thread’ objects gained an
     ‘ident’ property that returns the thread’s identifier, a nonzero
     integer.  (Contributed by Gregory P. Smith; bpo-2871(50).)

   * The *note timeit: 10c. module now accepts callables as well as
     strings for the statement being timed and for the setup code.  Two
     convenience functions were added for creating ‘Timer’ instances:
     ‘repeat(stmt, setup, time, repeat, number)’ and ‘timeit(stmt,
     setup, time, number)’ create an instance and call the corresponding
     method.  (Contributed by Erik Demaine; bpo-1533909(51).)

   * The ‘Tkinter’ module now accepts lists and tuples for options,
     separating the elements by spaces before passing the resulting
     value to Tcl/Tk.  (Contributed by Guilherme Polo; bpo-2906(52).)

   * The *note turtle: 117. module for turtle graphics was greatly
     enhanced by Gregor Lingl.  New features in the module include:

        * Better animation of turtle movement and rotation.

        * Control over turtle movement using the new ‘delay()’,
          ‘tracer()’, and ‘speed()’ methods.

        * The ability to set new shapes for the turtle, and to define a
          new coordinate system.

        * Turtles now have an ‘undo()’ method that can roll back
          actions.

        * Simple support for reacting to input events such as mouse and
          keyboard activity, making it possible to write simple games.

        * A ‘turtle.cfg’ file can be used to customize the starting
          appearance of the turtle’s screen.

        * The module’s docstrings can be replaced by new docstrings that
          have been translated into another language.

     (bpo-1513695(53))

   * An optional ‘timeout’ parameter was added to the ‘urllib.urlopen()’
     function and the ‘urllib.ftpwrapper’ class constructor, as well as
     the ‘urllib2.urlopen()’ function.  The parameter specifies a
     timeout measured in seconds.  For example:

          >>> u = urllib2.urlopen("http://slow.example.com",
                                  timeout=3)
          Traceback (most recent call last):
            ...
          urllib2.URLError: <urlopen error timed out>
          >>>

     (Added by Facundo Batista.)

   * The Unicode database provided by the *note unicodedata: 11b. module
     has been updated to version 5.1.0.  (Updated by Martin von Löwis;
     bpo-3811(54).)

   * The *note warnings: 127. module’s ‘formatwarning()’ and
     ‘showwarning()’ gained an optional `line' argument that can be used
     to supply the line of source code.  (Added as part of
     bpo-1631171(55), which re-implemented part of the *note warnings:
     127. module in C code.)

     A new function, ‘catch_warnings()’, is a context manager intended
     for testing purposes that lets you temporarily modify the warning
     filters and then restore their original values (bpo-3781(56)).

   * The XML-RPC ‘SimpleXMLRPCServer’ and ‘DocXMLRPCServer’ classes can
     now be prevented from immediately opening and binding to their
     socket by passing ‘False’ as the `bind_and_activate' constructor
     parameter.  This can be used to modify the instance’s
     ‘allow_reuse_address’ attribute before calling the ‘server_bind()’
     and ‘server_activate()’ methods to open the socket and begin
     listening for connections.  (Contributed by Peter Parente;
     bpo-1599845(57).)

     ‘SimpleXMLRPCServer’ also has a ‘_send_traceback_header’ attribute;
     if true, the exception and formatted traceback are returned as HTTP
     headers "X-Exception" and "X-Traceback".  This feature is for
     debugging purposes only and should not be used on production
     servers because the tracebacks might reveal passwords or other
     sensitive information.  (Contributed by Alan McIntyre as part of
     his project for Google’s Summer of Code 2007.)

   * The ‘xmlrpclib’ module no longer automatically converts *note
     datetime.date: 194. and *note datetime.time: 4fb. to the
     ‘xmlrpclib.DateTime’ type; the conversion semantics were not
     necessarily correct for all applications.  Code using ‘xmlrpclib’
     should convert ‘date’ and *note time: 4fb. instances.
     (bpo-1330538(58)) The code can also handle dates before 1900
     (contributed by Ralf Schmitt; bpo-2014(59)) and 64-bit integers
     represented by using ‘<i8>’ in XML-RPC responses (contributed by
     Riku Lindblad; bpo-2985(60)).

   * The *note zipfile: 143. module’s ‘ZipFile’ class now has
     ‘extract()’ and ‘extractall()’ methods that will unpack a single
     file or all the files in the archive to the current directory, or
     to a specified directory:

          z = zipfile.ZipFile('python-251.zip')

          # Unpack a single file, writing it relative
          # to the /tmp directory.
          z.extract('Python/sysmodule.c', '/tmp')

          # Unpack all the files in the archive.
          z.extractall()

     （由 Alan McIntyre 在 bpo-467924(61) 中贡献。）

     The *note open(): 4f8, ‘read()’ and ‘extract()’ methods can now
     take either a filename or a ‘ZipInfo’ object.  This is useful when
     an archive accidentally contains a duplicated filename.
     (Contributed by Graham Horler; bpo-1775025(62).)

     Finally, *note zipfile: 143. now supports using Unicode filenames
     for archived files.  (Contributed by Alexey Borzenkov;
     bpo-1734346(63).)

* Menu:

* ast 模块::
* future_builtins 模块::
* The json module; JavaScript Object Notation: The json module JavaScript Object Notation.
* plistlib 模块：属性列表解析器::
* ctypes Enhancements::
* Improved SSL Support::

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1736190

   (2) https://www.jcea.es/programacion/pybsddb.htm

   (3) https://bugs.python.org/issue1817

   (4) https://bugs.python.org/issue600362

   (5) https://bugs.python.org/issue1381

   (6) https://bugs.python.org/issue1638033

   (7) https://bugs.python.org/issue1158

   (8) http://speleotrove.com/decimal/decarith.html

   (9) https://bugs.python.org/issue1221598

   (10) https://bugs.python.org/issue1739906

   (11) https://bugs.python.org/issue1001604

   (12) https://bugs.python.org/issue2138

   (13) https://bugs.python.org/issue2819

   (14) https://bugs.python.org/issue711019

   (15) https://bugs.python.org/issue1640

   (16) https://bugs.python.org/issue1663329

   (17) https://bugs.python.org/issue1181

   (18) https://bugs.python.org/issue1273829

   (19) https://bugs.python.org/issue1115886

   (20) https://bugs.python.org/issue1339796

   (21) https://bugs.python.org/issue957650

   (22) https://bugs.python.org/issue1393667

   (23) https://bugs.python.org/issue1106316

   (24) https://bugs.python.org/issue2439

   (25) https://bugs.python.org/issue1137

   (26) https://bugs.python.org/issue1727780

   (27) https://bugs.python.org/issue1681432

   (28) https://bugs.python.org/issue846388

   (29) https://bugs.python.org/issue3487

   (30) https://bugs.python.org/issue2250

   (31) https://bugs.python.org/issue1861

   (32) https://bugs.python.org/issue1657

   (33) https://bugs.python.org/issue2663

   (34) https://bugs.python.org/issue1583

   (35) https://bugs.python.org/issue2240

   (36) https://tools.ietf.org/html/rfc2033.html

   (37) https://bugs.python.org/issue957003

   (38) https://tools.ietf.org/html/rfc3207.html

   (39) https://bugs.python.org/issue829951

   (40) https://bugs.python.org/issue1646

   (41) https://bugs.python.org/issue742598

   (42) https://bugs.python.org/issue1193577

   (43) https://bugs.python.org/issue1534

   (44) https://bugs.python.org/issue2898

   (45) https://bugs.python.org/issue1648

   (46) https://bugs.python.org/issue1537850

   (47) https://bugs.python.org/issue2021

   (48) https://bugs.python.org/issue3781

   (49) https://bugs.python.org/issue1581073

   (50) https://bugs.python.org/issue2871

   (51) https://bugs.python.org/issue1533909

   (52) https://bugs.python.org/issue2906

   (53) https://bugs.python.org/issue1513695

   (54) https://bugs.python.org/issue3811

   (55) https://bugs.python.org/issue1631171

   (56) https://bugs.python.org/issue3781

   (57) https://bugs.python.org/issue1599845

   (58) https://bugs.python.org/issue1330538

   (59) https://bugs.python.org/issue2014

   (60) https://bugs.python.org/issue2985

   (61) https://bugs.python.org/issue467924

   (62) https://bugs.python.org/issue1775025

   (63) https://bugs.python.org/issue1734346


File: python.info,  Node: ast 模块,  Next: future_builtins 模块,  Up: 新增和改进的模块<2>

1.11.18.1 ‘ast’ 模块
....................

The *note ast: 8. module provides an Abstract Syntax Tree representation
of Python code, and Armin Ronacher contributed a set of helper functions
that perform a variety of common tasks.  These will be useful for HTML
templating packages, code analyzers, and similar tools that process
Python code.

The ‘parse()’ function takes an expression and returns an AST. The
‘dump()’ function outputs a representation of a tree, suitable for
debugging:

     import ast

     t = ast.parse("""
     d = {}
     for i in 'abcdefghijklm':
         d[i + i] = ord(i) - ord('a') + 1
     print d
     """)
     print ast.dump(t)

This outputs a deeply nested tree:

     Module(body=[
       Assign(targets=[
         Name(id='d', ctx=Store())
        ], value=Dict(keys=[], values=[]))
       For(target=Name(id='i', ctx=Store()),
           iter=Str(s='abcdefghijklm'), body=[
         Assign(targets=[
           Subscript(value=
             Name(id='d', ctx=Load()),
               slice=
               Index(value=
                 BinOp(left=Name(id='i', ctx=Load()), op=Add(),
                  right=Name(id='i', ctx=Load()))), ctx=Store())
          ], value=
          BinOp(left=
           BinOp(left=
            Call(func=
             Name(id='ord', ctx=Load()), args=[
               Name(id='i', ctx=Load())
              ], keywords=[], starargs=None, kwargs=None),
            op=Sub(), right=Call(func=
             Name(id='ord', ctx=Load()), args=[
               Str(s='a')
              ], keywords=[], starargs=None, kwargs=None)),
            op=Add(), right=Num(n=1)))
         ], orelse=[])
        Print(dest=None, values=[
          Name(id='d', ctx=Load())
        ], nl=True)
      ])

The ‘literal_eval()’ method takes a string or an AST representing a
literal expression, parses and evaluates it, and returns the resulting
value.  A literal expression is a Python expression containing only
strings, numbers, dictionaries, etc.  but no statements or function
calls.  If you need to evaluate an expression but cannot accept the
security risk of using an *note eval(): b98. call, ‘literal_eval()’ will
handle it safely:

     >>> literal = '("a", "b", {2:4, 3:8, 1:2})'
     >>> print ast.literal_eval(literal)
     ('a', 'b', {1: 2, 2: 4, 3: 8})
     >>> print ast.literal_eval('"a" + "b"')
     Traceback (most recent call last):
       ...
     ValueError: malformed string

The module also includes ‘NodeVisitor’ and ‘NodeTransformer’ classes for
traversing and modifying an AST, and functions for common
transformations such as changing line numbers.


File: python.info,  Node: future_builtins 模块,  Next: The json module JavaScript Object Notation,  Prev: ast 模块,  Up: 新增和改进的模块<2>

1.11.18.2 ‘future_builtins’ 模块
................................

Python 3.0 makes many changes to the repertoire of built-in functions,
and most of the changes can’t be introduced in the Python 2.x series
because they would break compatibility.  The ‘future_builtins’ module
provides versions of these built-in functions that can be imported when
writing 3.0-compatible code.

The functions in this module currently include:

   * ‘ascii(obj)’: equivalent to *note repr(): 7d5.  In Python 3.0,
     *note repr(): 7d5. will return a Unicode string, while *note
     ascii(): d54. will return a pure ASCII bytestring.

   * ‘filter(predicate, iterable)’, ‘map(func, iterable1, ...)’: the 3.0
     versions return iterators, unlike the 2.x builtins which return
     lists.

   * ‘hex(value)’, ‘oct(value)’: instead of calling the ‘__hex__()’ or
     ‘__oct__()’ methods, these versions will call the *note
     __index__(): 18b. method and convert the result to hexadecimal or
     octal.  *note oct(): c6d. will use the new ‘0o’ notation for its
     result.


File: python.info,  Node: The json module JavaScript Object Notation,  Next: plistlib 模块：属性列表解析器,  Prev: future_builtins 模块,  Up: 新增和改进的模块<2>

1.11.18.3 The ‘json’ module: JavaScript Object Notation
.......................................................

The new *note json: a5. module supports the encoding and decoding of
Python types in JSON (Javascript Object Notation).  JSON is a
lightweight interchange format often used in web applications.  For more
information about JSON, see ‘http://www.json.org’.

*note json: a5. comes with support for decoding and encoding most
built-in Python types.  The following example encodes and decodes a
dictionary:

     >>> import json
     >>> data = {"spam": "foo", "parrot": 42}
     >>> in_json = json.dumps(data) # Encode the data
     >>> in_json
     '{"parrot": 42, "spam": "foo"}'
     >>> json.loads(in_json) # Decode into a Python object
     {"spam": "foo", "parrot": 42}

It’s also possible to write your own decoders and encoders to support
more types.  Pretty-printing of the JSON strings is also supported.

*note json: a5. (originally called simplejson) was written by Bob
Ippolito.


File: python.info,  Node: plistlib 模块：属性列表解析器,  Next: ctypes Enhancements,  Prev: The json module JavaScript Object Notation,  Up: 新增和改进的模块<2>

1.11.18.4 ‘plistlib’ 模块：属性列表解析器
.........................................

The ‘.plist’ format is commonly used on Mac OS X to store basic data
types (numbers, strings, lists, and dictionaries) by serializing them
into an XML-based format.  It resembles the XML-RPC serialization of
data types.

Despite being primarily used on Mac OS X, the format has nothing
Mac-specific about it and the Python implementation works on any
platform that Python supports, so the *note plistlib: d0. module has
been promoted to the standard library.

Using the module is simple:

     import sys
     import plistlib
     import datetime

     # Create data structure
     data_struct = dict(lastAccessed=datetime.datetime.now(),
                        version=1,
                        categories=('Personal','Shared','Private'))

     # Create string containing XML.
     plist_str = plistlib.writePlistToString(data_struct)
     new_struct = plistlib.readPlistFromString(plist_str)
     print data_struct
     print new_struct

     # Write data structure to a file and read it back.
     plistlib.writePlist(data_struct, '/tmp/customizations.plist')
     new_struct = plistlib.readPlist('/tmp/customizations.plist')

     # read/writePlist accepts file-like objects as well as paths.
     plistlib.writePlist(data_struct, sys.stdout)


File: python.info,  Node: ctypes Enhancements,  Next: Improved SSL Support,  Prev: plistlib 模块：属性列表解析器,  Up: 新增和改进的模块<2>

1.11.18.5 ctypes Enhancements
.............................

Thomas Heller continued to maintain and enhance the *note ctypes: 2b.
module.

*note ctypes: 2b. now supports a ‘c_bool’ datatype that represents the
C99 ‘bool’ type.  (Contributed by David Remahl; bpo-1649190(1).)

The *note ctypes: 2b. string, buffer and array types have improved
support for extended slicing syntax, where various combinations of
‘(start, stop, step)’ are supplied.  (Implemented by Thomas Wouters.)

All *note ctypes: 2b. data types now support ‘from_buffer()’ and
‘from_buffer_copy()’ methods that create a ctypes instance based on a
provided buffer object.  ‘from_buffer_copy()’ copies the contents of the
object, while ‘from_buffer()’ will share the same memory area.

A new calling convention tells *note ctypes: 2b. to clear the ‘errno’ or
Win32 LastError variables at the outset of each wrapped call.
(Implemented by Thomas Heller; bpo-1798(2).)

You can now retrieve the Unix ‘errno’ variable after a function call.
When creating a wrapped function, you can supply ‘use_errno=True’ as a
keyword parameter to the ‘DLL()’ function and then call the module-level
methods ‘set_errno()’ and ‘get_errno()’ to set and retrieve the error
value.

The Win32 LastError variable is similarly supported by the ‘DLL()’,
‘OleDLL()’, and ‘WinDLL()’ functions.  You supply ‘use_last_error=True’
as a keyword parameter and then call the module-level methods
‘set_last_error()’ and ‘get_last_error()’.

The ‘byref()’ function, used to retrieve a pointer to a ctypes instance,
now has an optional `offset' parameter that is a byte count that will be
added to the returned pointer.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1649190

   (2) https://bugs.python.org/issue1798


File: python.info,  Node: Improved SSL Support,  Prev: ctypes Enhancements,  Up: 新增和改进的模块<2>

1.11.18.6 Improved SSL Support
..............................

Bill Janssen made extensive improvements to Python 2.6’s support for the
Secure Sockets Layer by adding a new module, *note ssl: f4, that’s built
atop the OpenSSL(1) library.  This new module provides more control over
the protocol negotiated, the X.509 certificates used, and has better
support for writing SSL servers (as opposed to clients) in Python.  The
existing SSL support in the *note socket: f0. module hasn’t been removed
and continues to work, though it will be removed in Python 3.0.

To use the new module, you must first create a TCP connection in the
usual way and then pass it to the *note ssl.wrap_socket(): 477.
function.  It’s possible to specify whether a certificate is required,
and to obtain certificate info by calling the ‘getpeercert()’ method.

参见
....

*note ssl: f4. 模块的文档。

   ---------- Footnotes ----------

   (1) https://www.openssl.org/


File: python.info,  Node: Deprecations and Removals,  Next: 构建和 C API 的改变<9>,  Prev: 新增和改进的模块<2>,  Up: Python 2 6 有什么新变化

1.11.19 Deprecations and Removals
---------------------------------

   * String exceptions have been removed.  Attempting to use them raises
     a *note TypeError: 193.

   * Changes to the *note Exception: 1aa. interface as dictated by PEP
     352(1) continue to be made.  For 2.6, the ‘message’ attribute is
     being deprecated in favor of the ‘args’ attribute.

   * (3.0-warning mode) Python 3.0 will feature a reorganized standard
     library that will drop many outdated modules and rename others.
     Python 2.6 running in 3.0-warning mode will warn about these
     modules when they are imported.

     The list of deprecated modules is: ‘audiodev’, ‘bgenlocations’,
     ‘buildtools’, ‘bundlebuilder’, ‘Canvas’, ‘compiler’, ‘dircache’,
     ‘dl’, ‘fpformat’, ‘gensuitemodule’, ‘ihooks’, ‘imageop’, ‘imgfile’,
     ‘linuxaudiodev’, ‘mhlib’, ‘mimetools’, ‘multifile’, ‘new’, ‘pure’,
     ‘statvfs’, ‘sunaudiodev’, ‘test.testall’, and ‘toaiff’.

   * ‘gopherlib’ 模块已被移除。

   * The ‘MimeWriter’ module and ‘mimify’ module have been deprecated;
     use the *note email: 69. package instead.

   * The ‘md5’ module has been deprecated; use the *note hashlib: 8d.
     module instead.

   * The ‘posixfile’ module has been deprecated; *note fcntl.lockf():
     d5a. provides better locking.

   * The ‘popen2’ module has been deprecated; use the *note subprocess:
     fa. module.

   * ‘rgbimg’ 模块已被移除。

   * The ‘sets’ module has been deprecated; it’s better to use the
     built-in *note set: b77. and *note frozenset: bf6. types.

   * The ‘sha’ module has been deprecated; use the *note hashlib: 8d.
     module instead.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0352


File: python.info,  Node: 构建和 C API 的改变<9>,  Next: 移植到Python 2 6,  Prev: Deprecations and Removals,  Up: Python 2 6 有什么新变化

1.11.20 构建和 C API 的改变
---------------------------

Changes to Python’s build process and to the C API include:

   * Python now must be compiled with C89 compilers (after 19 years!).
     This means that the Python source tree has dropped its own
     implementations of ‘memmove()’ and ‘strerror()’, which are in the
     C89 standard library.

   * Python 2.6 can be built with Microsoft Visual Studio 2008 (version
     9.0), and this is the new default compiler.  See the ‘PCbuild’
     directory for the build files.  (Implemented by Christian Heimes.)

   * On Mac OS X, Python 2.6 can be compiled as a 4-way universal build.
     The ‘configure’ script can take a
     ‘--with-universal-archs=[32-bit|64-bit|all]’ switch, controlling
     whether the binaries are built for 32-bit architectures (x86,
     PowerPC), 64-bit (x86-64 and PPC-64), or both.  (Contributed by
     Ronald Oussoren.)

   * The BerkeleyDB module now has a C API object, available as
     ‘bsddb.db.api’.  This object can be used by other C extensions that
     wish to use the ‘bsddb’ module for their own purposes.
     (Contributed by Duncan Grisby.)

   * The new buffer interface, previously described in *note the PEP
     3118 section: d2c, adds *note PyObject_GetBuffer(): d2d. and *note
     PyBuffer_Release(): d5c, as well as a few other functions.

   * Python’s use of the C stdio library is now thread-safe, or at least
     as thread-safe as the underlying library is.  A long-standing
     potential bug occurred if one thread closed a file object while
     another thread was reading from or writing to the object.  In 2.6
     file objects have a reference count, manipulated by the
     ‘PyFile_IncUseCount()’ and ‘PyFile_DecUseCount()’ functions.  File
     objects can’t be closed unless the reference count is zero.
     ‘PyFile_IncUseCount()’ should be called while the GIL is still
     held, before carrying out an I/O operation using the ‘FILE *’
     pointer, and ‘PyFile_DecUseCount()’ should be called immediately
     after the GIL is re-acquired.  (Contributed by Antoine Pitrou and
     Gregory P. Smith.)

   * Importing modules simultaneously in two different threads no longer
     deadlocks; it will now raise an *note ImportError: 33d.  A new API
     function, *note PyImport_ImportModuleNoBlock(): 9c9, will look for
     a module in ‘sys.modules’ first, then try to import it after
     acquiring an import lock.  If the import lock is held by another
     thread, an *note ImportError: 33d. is raised.  (Contributed by
     Christian Heimes.)

   * Several functions return information about the platform’s
     floating-point support.  *note PyFloat_GetMax(): d5d. returns the
     maximum representable floating point value, and *note
     PyFloat_GetMin(): d5e. returns the minimum positive value.  *note
     PyFloat_GetInfo(): d5f. returns an object containing more
     information from the ‘float.h’ file, such as ‘"mant_dig"’ (number
     of digits in the mantissa), ‘"epsilon"’ (smallest difference
     between 1.0 and the next largest value representable), and several
     others.  (Contributed by Christian Heimes; bpo-1534(1).)

   * C functions and methods that use *note PyComplex_AsCComplex(): d60.
     will now accept arguments that have a *note __complex__(): 18e.
     method.  In particular, the functions in the *note cmath: 19.
     module will now accept objects with this method.  This is a
     backport of a Python 3.0 change.  (Contributed by Mark Dickinson;
     bpo-1675423(2).)

   * Python’s C API now includes two functions for case-insensitive
     string comparisons, ‘PyOS_stricmp(char*, char*)’ and
     ‘PyOS_strnicmp(char*, char*, Py_ssize_t)’.  (Contributed by
     Christian Heimes; bpo-1635(3).)

   * Many C extensions define their own little macro for adding integers
     and strings to the module’s dictionary in the ‘init*’ function.
     Python 2.6 finally defines standard macros for adding values to a
     module, *note PyModule_AddStringMacro: d61. and
     ‘PyModule_AddIntMacro()’.  (Contributed by Christian Heimes.)

   * Some macros were renamed in both 3.0 and 2.6 to make it clearer
     that they are macros, not functions.  ‘Py_Size()’ became
     ‘Py_SIZE()’, ‘Py_Type()’ became ‘Py_TYPE()’, and ‘Py_Refcnt()’
     became ‘Py_REFCNT()’.  The mixed-case macros are still available in
     Python 2.6 for backward compatibility.  (bpo-1629(4))

   * Distutils now places C extensions it builds in a different
     directory when running on a debug version of Python.  (Contributed
     by Collin Winter; bpo-1530959(5).)

   * Several basic data types, such as integers and strings, maintain
     internal free lists of objects that can be re-used.  The data
     structures for these free lists now follow a naming convention: the
     variable is always named ‘free_list’, the counter is always named
     ‘numfree’, and a macro ‘Py<typename>_MAXFREELIST’ is always
     defined.

   * A new Makefile target, "make patchcheck", prepares the Python
     source tree for making a patch: it fixes trailing whitespace in all
     modified ‘.py’ files, checks whether the documentation has been
     changed, and reports whether the ‘Misc/ACKS’ and ‘Misc/NEWS’ files
     have been updated.  (Contributed by Brett Cannon.)

     Another new target, "make profile-opt", compiles a Python binary
     using GCC’s profile-guided optimization.  It compiles Python with
     profiling enabled, runs the test suite to obtain a set of profiling
     results, and then compiles using these results for optimization.
     (Contributed by Gregory P. Smith.)

* Menu:

* 特定于 Windows 的更改：: 特定于 Windows 的更改：<2>.
* 特定于 Mac OS X 的更改：: 特定于 Mac OS X 的更改：<2>.
* 特定于 IRIX 的更改：::

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1534

   (2) https://bugs.python.org/issue1675423

   (3) https://bugs.python.org/issue1635

   (4) https://bugs.python.org/issue1629

   (5) https://bugs.python.org/issue1530959


File: python.info,  Node: 特定于 Windows 的更改：<2>,  Next: 特定于 Mac OS X 的更改：<2>,  Up: 构建和 C API 的改变<9>

1.11.20.1 特定于 Windows 的更改：
.................................

   * The support for Windows 95, 98, ME and NT4 has been dropped.
     Python 2.6 requires at least Windows 2000 SP4.

   * The new default compiler on Windows is Visual Studio 2008 (version
     9.0).  The build directories for Visual Studio 2003 (version 7.1)
     and 2005 (version 8.0) were moved into the PC/ directory.  The new
     ‘PCbuild’ directory supports cross compilation for X64, debug
     builds and Profile Guided Optimization (PGO). PGO builds are
     roughly 10% faster than normal builds.  (Contributed by Christian
     Heimes with help from Amaury Forgeot d’Arc and Martin von Löwis.)

   * The *note msvcrt: b7. module now supports both the normal and wide
     char variants of the console I/O API. The ‘getwch()’ function reads
     a keypress and returns a Unicode value, as does the ‘getwche()’
     function.  The ‘putwch()’ function takes a Unicode character and
     writes it to the console.  (Contributed by Christian Heimes.)

   * *note os.path.expandvars(): d4c. will now expand environment
     variables in the form "%var%", and "~user" will be expanded into
     the user’s home directory path.  (Contributed by Josiah Carlson;
     bpo-957650(1).)

   * The *note socket: f0. module’s socket objects now have an ‘ioctl()’
     method that provides a limited interface to the ‘WSAIoctl()’ system
     interface.

   * The ‘_winreg’ module now has a function,
     ‘ExpandEnvironmentStrings()’, that expands environment variable
     references such as ‘%NAME%’ in an input string.  The handle objects
     provided by this module now support the context protocol, so they
     can be used in *note with: 6f2. statements.  (Contributed by
     Christian Heimes.)

     ‘_winreg’ also has better support for x64 systems, exposing the
     ‘DisableReflectionKey()’, ‘EnableReflectionKey()’, and
     ‘QueryReflectionKey()’ functions, which enable and disable registry
     reflection for 32-bit processes running on 64-bit systems.
     (bpo-1753245(2))

   * The *note msilib: b6. module’s ‘Record’ object gained
     ‘GetInteger()’ and ‘GetString()’ methods that return field values
     as an integer or a string.  (Contributed by Floris Bruynooghe;
     bpo-2125(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue957650

   (2) https://bugs.python.org/issue1753245

   (3) https://bugs.python.org/issue2125


File: python.info,  Node: 特定于 Mac OS X 的更改：<2>,  Next: 特定于 IRIX 的更改：,  Prev: 特定于 Windows 的更改：<2>,  Up: 构建和 C API 的改变<9>

1.11.20.2 特定于 Mac OS X 的更改：
..................................

   * 现在，在编译Python的框架版本时，可以为 ‘configure’ 脚本添加
     ‘--with-framework-name=’ 选项来指定要使用的框架名称。

   * ‘macfs’ 模块已被删除。这反过来要求删除 ‘macostools.touched()’ 函数
     ，因为它依赖于 ‘macfs’ 模块。 (bpo-1490190(1))

   * 许多其他 Mac OS 模块已弃用并将在 Python 3.0 中被删除:
     ‘_builtinSuites’, ‘aepack’, ‘aetools’, ‘aetypes’, ‘applesingle’,
     ‘appletrawmain’, ‘appletrunner’, ‘argvemulator’, ‘Audio_mac’,
     ‘autoGIL’, ‘Carbon’, ‘cfmfile’, ‘CodeWarrior’, ‘ColorPicker’,
     ‘EasyDialogs’, ‘Explorer’, ‘Finder’, ‘FrameWork’, ‘findertools’,
     ‘ic’, ‘icglue’, ‘icopen’, ‘macerrors’, ‘MacOS’, ‘macfs’,
     ‘macostools’, ‘macresource’, ‘MiniAEFrame’, ‘Nav’, ‘Netscape’,
     ‘OSATerminology’, ‘pimp’, ‘PixMapWrapper’, ‘StdSuites’,
     ‘SystemEvents’, ‘Terminal’ 和 ‘terminalcommand’。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1490190


File: python.info,  Node: 特定于 IRIX 的更改：,  Prev: 特定于 Mac OS X 的更改：<2>,  Up: 构建和 C API 的改变<9>

1.11.20.3 特定于 IRIX 的更改：
..............................

许多旧的 IRIX 专用模块已被弃用，并将在Python 3.0中删除： ‘al’ 和 ‘AL’,
‘cd’, ‘cddb’, ‘cdplayer’, ‘CL’ 和 ‘cl’, ‘DEVICE’, ‘ERRNO’, ‘FILE’, ‘FL’
和 ‘fl’, ‘flp’, ‘fm’, ‘GET’, ‘GLWS’, ‘GL’ 和 ‘gl’, ‘IN’, ‘IOCTL’,
‘jpeg’, ‘panelparser’, ‘readcd’, ‘SV’ 和 ‘sv’, ‘torgb’, ‘videoreader’, 和
‘WAIT’.


File: python.info,  Node: 移植到Python 2 6,  Next: 致谢<2>,  Prev: 构建和 C API 的改变<9>,  Up: Python 2 6 有什么新变化

1.11.21 移植到Python 2.6
------------------------

This section lists previously described changes and other bugfixes that
may require changes to your code:

   * Classes that aren’t supposed to be hashable should set ‘__hash__ =
     None’ in their definitions to indicate the fact.

   * String exceptions have been removed.  Attempting to use them raises
     a *note TypeError: 193.

   * The *note __init__(): d66. method of *note collections.deque: 539.
     now clears any existing contents of the deque before adding
     elements from the iterable.  This change makes the behavior match
     ‘list.__init__()’.

   * *note object.__init__(): d66. previously accepted arbitrary
     arguments and keyword arguments, ignoring them.  In Python 2.6,
     this is no longer allowed and will result in a *note TypeError:
     193.  This will affect *note __init__(): d66. methods that end up
     calling the corresponding method on *note object: 2b1. (perhaps
     through using *note super(): 4eb.).  See bpo-1683368(1) for
     discussion.

   * The ‘Decimal’ constructor now accepts leading and trailing
     whitespace when passed a string.  Previously it would raise an
     ‘InvalidOperation’ exception.  On the other hand, the
     ‘create_decimal()’ method of ‘Context’ objects now explicitly
     disallows extra whitespace, raising a ‘ConversionSyntax’ exception.

   * Due to an implementation accident, if you passed a file path to the
     built-in *note __import__(): 619. function, it would actually
     import the specified file.  This was never intended to work,
     however, and the implementation now explicitly checks for this case
     and raises an *note ImportError: 33d.

   * C API: the *note PyImport_Import(): d67. and *note
     PyImport_ImportModule(): c7b. functions now default to absolute
     imports, not relative imports.  This will affect C extensions that
     import other modules.

   * C API: extension data types that shouldn’t be hashable should
     define their ‘tp_hash’ slot to *note PyObject_HashNotImplemented():
     d39.

   * The *note socket: f0. module exception *note socket.error: 99d. now
     inherits from *note IOError: 99a.  Previously it wasn’t a subclass
     of ‘StandardError’ but now it is, through *note IOError: 99a.
     (Implemented by Gregory P. Smith; bpo-1706815(2).)

   * The ‘xmlrpclib’ module no longer automatically converts *note
     datetime.date: 194. and *note datetime.time: 4fb. to the
     ‘xmlrpclib.DateTime’ type; the conversion semantics were not
     necessarily correct for all applications.  Code using ‘xmlrpclib’
     should convert ‘date’ and *note time: 4fb. instances.
     (bpo-1330538(3))

   * (3.0-warning mode) The *note Exception: 1aa. class now warns when
     accessed using slicing or index access; having *note Exception:
     1aa. behave like a tuple is being phased out.

   * (3.0-warning mode) inequality comparisons between two dictionaries
     or two objects that don’t implement comparison methods are reported
     as warnings.  ‘dict1 == dict2’ still works, but ‘dict1 < dict2’ is
     being phased out.

     Comparisons between cells, which are an implementation detail of
     Python’s scoping rules, also cause warnings because such
     comparisons are forbidden entirely in 3.0.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1683368

   (2) https://bugs.python.org/issue1706815

   (3) https://bugs.python.org/issue1330538


File: python.info,  Node: 致谢<2>,  Prev: 移植到Python 2 6,  Up: Python 2 6 有什么新变化

1.11.22 致谢
------------

作者感谢以下人员对本文各种草稿给予的建议，更正和协助： Georg Brandl,
Steve Brown, Nick Coghlan, Ralph Corderoy, Jim Jewett, Kent Johnson,
Chris Lambacher, Martin Michlmayr, Antoine Pitrou, Brian Warner.


File: python.info,  Node: Python 2 5 有什么新变化,  Next: Python 2 4 有什么新变化,  Prev: Python 2 6 有什么新变化,  Up: Python的新变化

1.12 Python 2.5 有什么新变化
============================


作者: A.M. Kuchling

This article explains the new features in Python 2.5.  The final release
of Python 2.5 is scheduled for August 2006; PEP 356(1) describes the
planned release schedule.

The changes in Python 2.5 are an interesting mix of language and library
improvements.  The library enhancements will be more important to
Python’s user community, I think, because several widely-useful packages
were added.  New modules include ElementTree for XML processing
(‘xml.etree’), the SQLite database module (‘sqlite’), and the *note
ctypes: 2b. module for calling C functions.

The language changes are of middling significance.  Some pleasant new
features were added, but most of them aren’t features that you’ll use
every day.  Conditional expressions were finally added to the language
using a novel syntax; see section *note PEP 308; 条件表达式: d6c.  The
new ’*note with: 6f2.’ statement will make writing cleanup code easier
(section *note PEP 343; "with" 语句: d6d.).  Values can now be passed
into generators (section *note PEP 342; 生成器的新特性: d6e.).  Imports
are now visible as either absolute or relative (section *note PEP 328;
绝对导入和相对导入: d6f.).  Some corner cases of exception handling are
handled better (section *note PEP 341; 统一 try/except/finally: d70.).
All these improvements are worthwhile, but they’re improvements to one
specific language feature or another; none of them are broad
modifications to Python’s semantics.

As well as the language and library additions, other improvements and
bugfixes were made throughout the source tree.  A search through the SVN
change logs finds there were 353 patches applied and 458 bugs fixed
between Python 2.4 and 2.5.  (Both figures are likely to be
underestimates.)

This article doesn’t try to be a complete specification of the new
features; instead changes are briefly introduced using helpful examples.
For full details, you should always refer to the documentation for
Python 2.5 at ‘https://docs.python.org’.  If you want to understand the
complete implementation and design rationale, refer to the PEP for a
particular new feature.

Comments, suggestions, and error reports for this document are welcome;
please e-mail them to the author or open a bug in the Python bug
tracker.

* Menu:

* PEP 308; 条件表达式: PEP 308 条件表达式.
* PEP 309; 部分功能应用: PEP 309 部分功能应用.
* PEP 314; Python软件包的元数据 v1.1: PEP 314 Python软件包的元数据 v1 1.
* PEP 328; 绝对导入和相对导入: PEP 328 绝对导入和相对导入.
* PEP 338; 将模块作为脚本执行: PEP 338 将模块作为脚本执行.
* PEP 341; 统一 try/except/finally: PEP 341 统一 try/except/finally.
* PEP 342; 生成器的新特性: PEP 342 生成器的新特性.
* PEP 343; "with" 语句: PEP 343 "with" 语句<2>.
* PEP 352; 异常作为新型的类: PEP 352 异常作为新型的类.
* PEP 353; 使用ssize_t作为索引类型: PEP 353 使用ssize_t作为索引类型.
* PEP 357; ’__index__’ 方法: PEP 357 '__index__' 方法.
* 其他语言特性修改: 其他语言特性修改<11>.
* 新增，改进和删除的模块::
* 构建和 C API 的改变: 构建和 C API 的改变<10>.
* 移植到Python 2.5: 移植到Python 2 5.
* 致谢: 致谢<3>.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0356


File: python.info,  Node: PEP 308 条件表达式,  Next: PEP 309 部分功能应用,  Up: Python 2 5 有什么新变化

1.12.1 PEP 308: 条件表达式
--------------------------

For a long time, people have been requesting a way to write conditional
expressions, which are expressions that return value A or value B
depending on whether a Boolean value is true or false.  A conditional
expression lets you write a single assignment statement that has the
same effect as the following:

     if condition:
         x = true_value
     else:
         x = false_value

There have been endless tedious discussions of syntax on both python-dev
and comp.lang.python.  A vote was even held that found the majority of
voters wanted conditional expressions in some form, but there was no
syntax that was preferred by a clear majority.  Candidates included C’s
‘cond ? true_v : false_v’, ‘if cond then true_v else false_v’, and 16
other variations.

Guido van Rossum 最终选择了一种令人惊讶的语法：

     x = true_value if condition else false_value

Evaluation is still lazy as in existing Boolean expressions, so the
order of evaluation jumps around a bit.  The `condition' expression in
the middle is evaluated first, and the `true_value' expression is
evaluated only if the condition was true.  Similarly, the `false_value'
expression is only evaluated when the condition is false.

This syntax may seem strange and backwards; why does the condition go in
the `middle' of the expression, and not in the front as in C’s ‘c ? x :
y’?  The decision was checked by applying the new syntax to the modules
in the standard library and seeing how the resulting code read.  In many
cases where a conditional expression is used, one value seems to be the
’common case’ and one value is an ’exceptional case’, used only on rarer
occasions when the condition isn’t met.  The conditional syntax makes
this pattern a bit more obvious:

     contents = ((doc + '\n') if doc else '')

I read the above statement as meaning "here `contents' is usually
assigned a value of ‘doc+'\n'’; sometimes `doc' is empty, in which
special case an empty string is returned."  I doubt I will use
conditional expressions very often where there isn’t a clear common and
uncommon case.

There was some discussion of whether the language should require
surrounding conditional expressions with parentheses.  The decision was
made to `not' require parentheses in the Python language’s grammar, but
as a matter of style I think you should always use them.  Consider these
two statements:

     # First version -- no parens
     level = 1 if logging else 0

     # Second version -- with parens
     level = (1 if logging else 0)

In the first version, I think a reader’s eye might group the statement
into ’level = 1’, ’if logging’, ’else 0’, and think that the condition
decides whether the assignment to `level' is performed.  The second
version reads better, in my opinion, because it makes it clear that the
assignment is always performed and the choice is being made between two
values.

Another reason for including the brackets: a few odd combinations of
list comprehensions and lambdas could look like incorrect conditional
expressions.  See PEP 308(1) for some examples.  If you put parentheses
around your conditional expressions, you won’t run into this case.

参见
....

PEP 308(2) - 条件表达式

     PEP 由 Guido van Rossum 和 Raymond D 撰写，由 Thomas Wouters 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0308

   (2) https://www.python.org/dev/peps/pep-0308


File: python.info,  Node: PEP 309 部分功能应用,  Next: PEP 314 Python软件包的元数据 v1 1,  Prev: PEP 308 条件表达式,  Up: Python 2 5 有什么新变化

1.12.2 PEP 309: 部分功能应用
----------------------------

The *note functools: 85. module is intended to contain tools for
functional-style programming.

One useful tool in this module is the ‘partial()’ function.  For
programs written in a functional style, you’ll sometimes want to
construct variants of existing functions that have some of the
parameters filled in.  Consider a Python function ‘f(a, b, c)’; you
could create a new function ‘g(b, c)’ that was equivalent to ‘f(1, b,
c)’.  This is called "partial function application".

‘partial()’ takes the arguments ‘(function, arg1, arg2, ...
kwarg1=value1, kwarg2=value2)’.  The resulting object is callable, so
you can just call it to invoke `function' with the filled-in arguments.

这里有一个很小但很现实的例子:

     import functools

     def log (message, subsystem):
         "Write the contents of 'message' to the specified subsystem."
         print '%s: %s' % (subsystem, message)
         ...

     server_log = functools.partial(log, subsystem='server')
     server_log('Unable to open socket')

Here’s another example, from a program that uses PyGTK. Here a
context-sensitive pop-up menu is being constructed dynamically.  The
callback provided for the menu option is a partially applied version of
the ‘open_item()’ method, where the first argument has been provided.

     ...
     class Application:
         def open_item(self, path):
            ...
         def init (self):
             open_func = functools.partial(self.open_item, item_path)
             popup_menu.append( ("Open", open_func, 1) )

Another function in the *note functools: 85. module is the
‘update_wrapper(wrapper, wrapped)’ function that helps you write
well-behaved decorators.  ‘update_wrapper()’ copies the name, module,
and docstring attribute to a wrapper function so that tracebacks inside
the wrapped function are easier to understand.  For example, you might
write:

     def my_decorator(f):
         def wrapper(*args, **kwds):
             print 'Calling decorated function'
             return f(*args, **kwds)
         functools.update_wrapper(wrapper, f)
         return wrapper

‘wraps()’ is a decorator that can be used inside your own decorators to
copy the wrapped function’s information.  An alternate version of the
previous example would be:

     def my_decorator(f):
         @functools.wraps(f)
         def wrapper(*args, **kwds):
             print 'Calling decorated function'
             return f(*args, **kwds)
         return wrapper

参见
....

PEP 309(1) - Partial Function Application

     PEP由 Peter Harris 提出并撰写；由 Hye-Shik Chang 和 Nick Coghlan 实
     现，并由 Raymond Hettinger 适配。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0309


File: python.info,  Node: PEP 314 Python软件包的元数据 v1 1,  Next: PEP 328 绝对导入和相对导入,  Prev: PEP 309 部分功能应用,  Up: Python 2 5 有什么新变化

1.12.3 PEP 314: Python软件包的元数据 v1.1
-----------------------------------------

Some simple dependency support was added to Distutils.  The ‘setup()’
function now has ‘requires’, ‘provides’, and ‘obsoletes’ keyword
parameters.  When you build a source distribution using the ‘sdist’
command, the dependency information will be recorded in the ‘PKG-INFO’
file.

Another new keyword parameter is ‘download_url’, which should be set to
a URL for the package’s source code.  This means it’s now possible to
look up an entry in the package index, determine the dependencies for a
package, and download the required packages.

     VERSION = '1.0'
     setup(name='PyPackage',
           version=VERSION,
           requires=['numarray', 'zlib (>=1.1.4)'],
           obsoletes=['OldPackage']
           download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
                         % VERSION),
          )

Another new enhancement to the Python package index at
‘https://pypi.org’ is storing source and binary archives for a package.
The new ‘upload’ Distutils command will upload a package to the
repository.

Before a package can be uploaded, you must be able to build a
distribution using the ‘sdist’ Distutils command.  Once that works, you
can run ‘python setup.py upload’ to add your package to the PyPI
archive.  Optionally you can GPG-sign the package by supplying the
‘--sign’ and ‘--identity’ options.

Package uploading was implemented by Martin von Löwis and Richard Jones.

参见
....

PEP 314(1) - Python软件包的元数据 v1.1

     PEP 由 A.M. Kuchling, Richard Jones 和 Fred Drake 提出并撰写，由
     Richard Jones 和 Fred Drake 实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0314


File: python.info,  Node: PEP 328 绝对导入和相对导入,  Next: PEP 338 将模块作为脚本执行,  Prev: PEP 314 Python软件包的元数据 v1 1,  Up: Python 2 5 有什么新变化

1.12.4 PEP 328: 绝对导入和相对导入
----------------------------------

The simpler part of PEP 328(1) was implemented in Python 2.4:
parentheses could now be used to enclose the names imported from a
module using the ‘from ... import ...’ statement, making it easier to
import many different names.

The more complicated part has been implemented in Python 2.5: importing
a module can be specified to use absolute or package-relative imports.
The plan is to move toward making absolute imports the default in future
versions of Python.

Let’s say you have a package directory like this:

     pkg/
     pkg/__init__.py
     pkg/main.py
     pkg/string.py

This defines a package named ‘pkg’ containing the ‘pkg.main’ and
‘pkg.string’ submodules.

Consider the code in the ‘main.py’ module.  What happens if it executes
the statement ‘import string’?  In Python 2.4 and earlier, it will first
look in the package’s directory to perform a relative import, finds
‘pkg/string.py’, imports the contents of that file as the ‘pkg.string’
module, and that module is bound to the name ‘string’ in the ‘pkg.main’
module’s namespace.

That’s fine if ‘pkg.string’ was what you wanted.  But what if you wanted
Python’s standard *note string: f7. module?  There’s no clean way to
ignore ‘pkg.string’ and look for the standard module; generally you had
to look at the contents of ‘sys.modules’, which is slightly unclean.
Holger Krekel’s ‘py.std’ package provides a tidier way to perform
imports from the standard library, ‘import py; py.std.string.join()’,
but that package isn’t available on all Python installations.

Reading code which relies on relative imports is also less clear,
because a reader may be confused about which module, *note string: f7.
or ‘pkg.string’, is intended to be used.  Python users soon learned not
to duplicate the names of standard library modules in the names of their
packages’ submodules, but you can’t protect against having your
submodule’s name being used for a new module added in a future version
of Python.

In Python 2.5, you can switch *note import: c25.’s behaviour to absolute
imports using a ‘from __future__ import absolute_import’ directive.
This absolute-import behaviour will become the default in a future
version (probably Python 2.7).  Once absolute imports are the default,
‘import string’ will always find the standard library’s version.  It’s
suggested that users should begin using absolute imports as much as
possible, so it’s preferable to begin writing ‘from pkg import string’
in your code.

Relative imports are still possible by adding a leading period to the
module name when using the ‘from ... import’ form:

     # Import names from pkg.string
     from .string import name1, name2
     # Import pkg.string
     from . import string

This imports the *note string: f7. module relative to the current
package, so in ‘pkg.main’ this will import `name1' and `name2' from
‘pkg.string’.  Additional leading periods perform the relative import
starting from the parent of the current package.  For example, code in
the ‘A.B.C’ module can do:

     from . import D                 # Imports A.B.D
     from .. import E                # Imports A.E
     from ..F import G               # Imports A.F.G

Leading periods cannot be used with the ‘import modname’ form of the
import statement, only the ‘from ... import’ form.

参见
....

PEP 328(2) - 导入：多行和绝对/相对导入

     PEP 由 Aahz 撰写，由 Thomas Wouters 实现。

‘https://pylib.readthedocs.io/’

     The py library by Holger Krekel, which contains the ‘py.std’
     package.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0328

   (2) https://www.python.org/dev/peps/pep-0328


File: python.info,  Node: PEP 338 将模块作为脚本执行,  Next: PEP 341 统一 try/except/finally,  Prev: PEP 328 绝对导入和相对导入,  Up: Python 2 5 有什么新变化

1.12.5 PEP 338: 将模块作为脚本执行
----------------------------------

The *note -m: 340. switch added in Python 2.4 to execute a module as a
script gained a few more abilities.  Instead of being implemented in C
code inside the Python interpreter, the switch now uses an
implementation in a new module, *note runpy: e3.

The *note runpy: e3. module implements a more sophisticated import
mechanism so that it’s now possible to run modules in a package such as
‘pychecker.checker’.  The module also supports alternative import
mechanisms such as the *note zipimport: 144. module.  This means you can
add a .zip archive’s path to ‘sys.path’ and then use the *note -m: 340.
switch to execute code from the archive.

参见
....

PEP 338(1) - 将模块作为脚本执行

     PEP 由 Nick Coghlan 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0338


File: python.info,  Node: PEP 341 统一 try/except/finally,  Next: PEP 342 生成器的新特性,  Prev: PEP 338 将模块作为脚本执行,  Up: Python 2 5 有什么新变化

1.12.6 PEP 341: 统一 try/except/finally
---------------------------------------

Until Python 2.5, the *note try: d7a. statement came in two flavours.
You could use a *note finally: 183. block to ensure that code is always
executed, or one or more *note except: b46. blocks to catch specific
exceptions.  You couldn’t combine both ‘except’ blocks and a ‘finally’
block, because generating the right bytecode for the combined version
was complicated and it wasn’t clear what the semantics of the combined
statement should be.

Guido van Rossum spent some time working with Java, which does support
the equivalent of combining *note except: b46. blocks and a *note
finally: 183. block, and this clarified what the statement should mean.
In Python 2.5, you can now write:

     try:
         block-1 ...
     except Exception1:
         handler-1 ...
     except Exception2:
         handler-2 ...
     else:
         else-block
     finally:
         final-block

The code in `block-1' is executed.  If the code raises an exception, the
various *note except: b46. blocks are tested: if the exception is of
class ‘Exception1’, `handler-1' is executed; otherwise if it’s of class
‘Exception2’, `handler-2' is executed, and so forth.  If no exception is
raised, the `else-block' is executed.

No matter what happened previously, the `final-block' is executed once
the code block is complete and any raised exceptions handled.  Even if
there’s an error in an exception handler or the `else-block' and a new
exception is raised, the code in the `final-block' is still run.

参见
....

PEP 341(1) - 统一 try-except 和 try-finally

     PEP 由 Georg Brandl 撰写，由 Thomas Lee 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0341


File: python.info,  Node: PEP 342 生成器的新特性,  Next: PEP 343 "with" 语句<2>,  Prev: PEP 341 统一 try/except/finally,  Up: Python 2 5 有什么新变化

1.12.7 PEP 342: 生成器的新特性
------------------------------

Python 2.5 adds a simple way to pass values `into' a generator.  As
introduced in Python 2.3, generators only produce output; once a
generator’s code was invoked to create an iterator, there was no way to
pass any new information into the function when its execution is
resumed.  Sometimes the ability to pass in some information would be
useful.  Hackish solutions to this include making the generator’s code
look at a global variable and then changing the global variable’s value,
or passing in some mutable object that callers then modify.

To refresh your memory of basic generators, here’s a simple example:

     def counter (maximum):
         i = 0
         while i < maximum:
             yield i
             i += 1

When you call ‘counter(10)’, the result is an iterator that returns the
values from 0 up to 9.  On encountering the *note yield: 190. statement,
the iterator returns the provided value and suspends the function’s
execution, preserving the local variables.  Execution resumes on the
following call to the iterator’s *note next(): 68b. method, picking up
after the ‘yield’ statement.

In Python 2.3, *note yield: 190. was a statement; it didn’t return any
value.  In 2.5, ‘yield’ is now an expression, returning a value that can
be assigned to a variable or otherwise operated on:

     val = (yield i)

I recommend that you always put parentheses around a *note yield: 190.
expression when you’re doing something with the returned value, as in
the above example.  The parentheses aren’t always necessary, but it’s
easier to always add them instead of having to remember when they’re
needed.

( PEP 342(1) explains the exact rules, which are that a *note yield:
190.-expression must always be parenthesized except when it occurs at
the top-level expression on the right-hand side of an assignment.  This
means you can write ‘val = yield i’ but have to use parentheses when
there’s an operation, as in ‘val = (yield i) + 12’.)

Values are sent into a generator by calling its ‘send(value)’ method.
The generator’s code is then resumed and the *note yield: 190.
expression returns the specified `value'.  If the regular *note next():
68b. method is called, the ‘yield’ returns *note None: 158.

Here’s the previous example, modified to allow changing the value of the
internal counter.

     def counter (maximum):
         i = 0
         while i < maximum:
             val = (yield i)
             # If value provided, change counter
             if val is not None:
                 i = val
             else:
                 i += 1

And here’s an example of changing the counter:

     >>> it = counter(10)
     >>> print it.next()
     0
     >>> print it.next()
     1
     >>> print it.send(8)
     8
     >>> print it.next()
     9
     >>> print it.next()
     Traceback (most recent call last):
       File "t.py", line 15, in ?
         print it.next()
     StopIteration

*note yield: 190. will usually return *note None: 158, so you should
always check for this case.  Don’t just use its value in expressions
unless you’re sure that the ‘send()’ method will be the only method used
to resume your generator function.

In addition to ‘send()’, there are two other new methods on generators:

   * ‘throw(type, value=None, traceback=None)’ is used to raise an
     exception inside the generator; the exception is raised by the
     *note yield: 190. expression where the generator’s execution is
     paused.

   * ‘close()’ raises a new *note GeneratorExit: d3a. exception inside
     the generator to terminate the iteration.  On receiving this
     exception, the generator’s code must either raise *note
     GeneratorExit: d3a. or *note StopIteration: 48e.  Catching the
     *note GeneratorExit: d3a. exception and returning a value is
     illegal and will trigger a *note RuntimeError: 2bb.; if the
     function raises some other exception, that exception is propagated
     to the caller.  ‘close()’ will also be called by Python’s garbage
     collector when the generator is garbage-collected.

     If you need to run cleanup code when a *note GeneratorExit: d3a.
     occurs, I suggest using a ‘try: ... finally:’ suite instead of
     catching *note GeneratorExit: d3a.

这些改变的累积效应是，让生成器从单向的信息生产者变成了既是生产者，又是消
费者。

Generators also become `coroutines', a more generalized form of
subroutines.  Subroutines are entered at one point and exited at another
point (the top of the function, and a *note return: 191. statement), but
coroutines can be entered, exited, and resumed at many different points
(the *note yield: 190. statements).  We’ll have to figure out patterns
for using coroutines effectively in Python.

The addition of the ‘close()’ method has one side effect that isn’t
obvious.  ‘close()’ is called when a generator is garbage-collected, so
this means the generator’s code gets one last chance to run before the
generator is destroyed.  This last chance means that ‘try...finally’
statements in generators can now be guaranteed to work; the *note
finally: 183. clause will now always get a chance to run.  The syntactic
restriction that you couldn’t mix *note yield: 190. statements with a
‘try...finally’ suite has therefore been removed.  This seems like a
minor bit of language trivia, but using generators and ‘try...finally’
is actually necessary in order to implement the *note with: 6f2.
statement described by PEP 343(2).  I’ll look at this new statement in
the following section.

Another even more esoteric effect of this change: previously, the
‘gi_frame’ attribute of a generator was always a frame object.  It’s now
possible for ‘gi_frame’ to be ‘None’ once the generator has been
exhausted.

参见
....

PEP 342(3) - 通过增强型生成器实现协程

     PEP 由 Guido van Rossum 和 Phillip J. Eby 撰写，由 Phillip J. Eby 实
     现。包括一些更高级的使用生成器作为协程的示例。

     这些功能的早期版本在 PEP 288(4) （由 Raymond Hettinger 撰写） 和
     PEP 325(5) （由 Samuele Pedroni 撰写）中提出。

‘https://en.wikipedia.org/wiki/Coroutine’

     协程的Wikipedia条目。

‘http://www.sidhe.org/~dan/blog/archives/000178.html’

     An explanation of coroutines from a Perl point of view, written by
     Dan Sugalski.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0342

   (2) https://www.python.org/dev/peps/pep-0343

   (3) https://www.python.org/dev/peps/pep-0342

   (4) https://www.python.org/dev/peps/pep-0288

   (5) https://www.python.org/dev/peps/pep-0325


File: python.info,  Node: PEP 343 "with" 语句<2>,  Next: PEP 352 异常作为新型的类,  Prev: PEP 342 生成器的新特性,  Up: Python 2 5 有什么新变化

1.12.8 PEP 343: "with" 语句
---------------------------

The ’*note with: 6f2.’ statement clarifies code that previously would
use ‘try...finally’ blocks to ensure that clean-up code is executed.  In
this section, I’ll discuss the statement as it will commonly be used.
In the next section, I’ll examine the implementation details and show
how to write objects for use with this statement.

The ’*note with: 6f2.’ statement is a new control-flow structure whose
basic structure is:

     with expression [as variable]:
         with-block

The expression is evaluated, and it should result in an object that
supports the context management protocol (that is, has *note
__enter__(): c9d. and *note __exit__(): c9e. methods.

The object’s *note __enter__(): c9d. is called before `with-block' is
executed and therefore can run set-up code.  It also may return a value
that is bound to the name `variable', if given.  (Note carefully that
`variable' is `not' assigned the result of `expression'.)

After execution of the `with-block' is finished, the object’s *note
__exit__(): c9e. method is called, even if the block raised an
exception, and can therefore run clean-up code.

To enable the statement in Python 2.5, you need to add the following
directive to your module:

     from __future__ import with_statement

该语句在Python 2.6 中始终启用。

Some standard Python objects now support the context management protocol
and can be used with the ’*note with: 6f2.’ statement.  File objects are
one example:

     with open('/etc/passwd', 'r') as f:
         for line in f:
             print line
             ... more processing code ...

After this statement has executed, the file object in `f' will have been
automatically closed, even if the *note for: c38. loop raised an
exception part-way through the block.

     注解: In this case, `f' is the same object created by *note open():
     4f8, because ‘file.__enter__()’ returns `self'.

The *note threading: 10a. module’s locks and condition variables also
support the ’*note with: 6f2.’ statement:

     lock = threading.Lock()
     with lock:
         # Critical section of code
         ...

The lock is acquired before the block is executed and always released
once the block is complete.

The new ‘localcontext()’ function in the *note decimal: 36. module makes
it easy to save and restore the current decimal context, which
encapsulates the desired precision and rounding characteristics for
computations:

     from decimal import Decimal, Context, localcontext

     # Displays with default precision of 28 digits
     v = Decimal('578')
     print v.sqrt()

     with localcontext(Context(prec=16)):
         # All code in this block uses a precision of 16 digits.
         # The original context is restored on exiting the block.
         print v.sqrt()

* Menu:

* Writing Context Managers: Writing Context Managers<2>.
* contextlib 模块: contextlib 模块<2>.


File: python.info,  Node: Writing Context Managers<2>,  Next: contextlib 模块<2>,  Up: PEP 343 "with" 语句<2>

1.12.8.1 Writing Context Managers
.................................

Under the hood, the ’*note with: 6f2.’ statement is fairly complicated.
Most people will only use ’‘with’’ in company with existing objects and
don’t need to know these details, so you can skip the rest of this
section if you like.  Authors of new objects will need to understand the
details of the underlying implementation and should keep reading.

A high-level explanation of the context management protocol is:

   * The expression is evaluated and should result in an object called a
     "context manager".  The context manager must have *note
     __enter__(): c9d. and *note __exit__(): c9e. methods.

   * The context manager’s *note __enter__(): c9d. method is called.
     The value returned is assigned to `VAR'. If no ‘'as VAR'’ clause is
     present, the value is simply discarded.

   * The code in `BLOCK' is executed.

   * If `BLOCK' raises an exception, the ‘__exit__(type, value,
     traceback)’ is called with the exception details, the same values
     returned by *note sys.exc_info(): c67.  The method’s return value
     controls whether the exception is re-raised: any false value
     re-raises the exception, and ‘True’ will result in suppressing it.
     You’ll only rarely want to suppress the exception, because if you
     do the author of the code containing the ’*note with: 6f2.’
     statement will never realize anything went wrong.

   * If `BLOCK' didn’t raise an exception, the *note __exit__(): c9e.
     method is still called, but `type', `value', and `traceback' are
     all ‘None’.

Let’s think through an example.  I won’t present detailed code but will
only sketch the methods necessary for a database that supports
transactions.

(For people unfamiliar with database terminology: a set of changes to
the database are grouped into a transaction.  Transactions can be either
committed, meaning that all the changes are written into the database,
or rolled back, meaning that the changes are all discarded and the
database is unchanged.  See any database textbook for more information.)

Let’s assume there’s an object representing a database connection.  Our
goal will be to let the user write code like this:

     db_connection = DatabaseConnection()
     with db_connection as cursor:
         cursor.execute('insert into ...')
         cursor.execute('delete from ...')
         # ... more operations ...

The transaction should be committed if the code in the block runs
flawlessly or rolled back if there’s an exception.  Here’s the basic
interface for ‘DatabaseConnection’ that I’ll assume:

     class DatabaseConnection:
         # Database interface
         def cursor (self):
             "Returns a cursor object and starts a new transaction"
         def commit (self):
             "Commits current transaction"
         def rollback (self):
             "Rolls back current transaction"

The *note __enter__(): c9d. method is pretty easy, having only to start
a new transaction.  For this application the resulting cursor object
would be a useful result, so the method will return it.  The user can
then add ‘as cursor’ to their ’*note with: 6f2.’ statement to bind the
cursor to a variable name.

     class DatabaseConnection:
         ...
         def __enter__ (self):
             # Code to start a new transaction
             cursor = self.cursor()
             return cursor

The *note __exit__(): c9e. method is the most complicated because it’s
where most of the work has to be done.  The method has to check if an
exception occurred.  If there was no exception, the transaction is
committed.  The transaction is rolled back if there was an exception.

In the code below, execution will just fall off the end of the function,
returning the default value of ‘None’.  ‘None’ is false, so the
exception will be re-raised automatically.  If you wished, you could be
more explicit and add a *note return: 191. statement at the marked
location.

     class DatabaseConnection:
         ...
         def __exit__ (self, type, value, tb):
             if tb is None:
                 # No exception, so commit
                 self.commit()
             else:
                 # Exception occurred, so rollback.
                 self.rollback()
                 # return False


File: python.info,  Node: contextlib 模块<2>,  Prev: Writing Context Managers<2>,  Up: PEP 343 "with" 语句<2>

1.12.8.2 contextlib 模块
........................

The new *note contextlib: 24. module provides some functions and a
decorator that are useful for writing objects for use with the ’*note
with: 6f2.’ statement.

The decorator is called ‘contextmanager()’, and lets you write a single
generator function instead of defining a new class.  The generator
should yield exactly one value.  The code up to the *note yield: 190.
will be executed as the *note __enter__(): c9d. method, and the value
yielded will be the method’s return value that will get bound to the
variable in the ’*note with: 6f2.’ statement’s ‘as’ clause, if any.  The
code after the *note yield: 190. will be executed in the *note
__exit__(): c9e. method.  Any exception raised in the block will be
raised by the ‘yield’ statement.

Our database example from the previous section could be written using
this decorator as:

     from contextlib import contextmanager

     @contextmanager
     def db_transaction (connection):
         cursor = connection.cursor()
         try:
             yield cursor
         except:
             connection.rollback()
             raise
         else:
             connection.commit()

     db = DatabaseConnection()
     with db_transaction(db) as cursor:
         ...

The *note contextlib: 24. module also has a ‘nested(mgr1, mgr2, ...)’
function that combines a number of context managers so you don’t need to
write nested ’*note with: 6f2.’ statements.  In this example, the single
’‘with’’ statement both starts a database transaction and acquires a
thread lock:

     lock = threading.Lock()
     with nested (db_transaction(db), lock) as (cursor, locked):
         ...

Finally, the ‘closing(object)’ function returns `object' so that it can
be bound to a variable, and calls ‘object.close’ at the end of the
block.

     import urllib, sys
     from contextlib import closing

     with closing(urllib.urlopen('http://www.yahoo.com')) as f:
         for line in f:
             sys.stdout.write(line)

参见
....

PEP 343(1) - "with" 语句

     PEP written by Guido van Rossum and Nick Coghlan; implemented by
     Mike Bland, Guido van Rossum, and Neal Norwitz.  The PEP shows the
     code generated for a ’*note with: 6f2.’ statement, which can be
     helpful in learning how the statement works.

*note contextlib: 24. 模块的文档。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0343


File: python.info,  Node: PEP 352 异常作为新型的类,  Next: PEP 353 使用ssize_t作为索引类型,  Prev: PEP 343 "with" 语句<2>,  Up: Python 2 5 有什么新变化

1.12.9 PEP 352: 异常作为新型的类
--------------------------------

Exception classes can now be new-style classes, not just classic
classes, and the built-in *note Exception: 1aa. class and all the
standard built-in exceptions (*note NameError: d83, *note ValueError:
1fc, etc.)  are now new-style classes.

The inheritance hierarchy for exceptions has been rearranged a bit.  In
2.5, the inheritance relationships are:

     BaseException       # New in Python 2.5
     |- KeyboardInterrupt
     |- SystemExit
     |- Exception
        |- (all other current built-in exceptions)

This rearrangement was done because people often want to catch all
exceptions that indicate program errors.  *note KeyboardInterrupt: 198.
and *note SystemExit: 605. aren’t errors, though, and usually represent
an explicit action such as the user hitting ‘Control-C’ or code calling
*note sys.exit(): cea.  A bare ‘except:’ will catch all exceptions, so
you commonly need to list *note KeyboardInterrupt: 198. and *note
SystemExit: 605. in order to re-raise them.  The usual pattern is:

     try:
         ...
     except (KeyboardInterrupt, SystemExit):
         raise
     except:
         # Log error...
         # Continue running program...

In Python 2.5, you can now write ‘except Exception’ to achieve the same
result, catching all the exceptions that usually indicate errors but
leaving *note KeyboardInterrupt: 198. and *note SystemExit: 605. alone.
As in previous versions, a bare ‘except:’ still catches all exceptions.

The goal for Python 3.0 is to require any class raised as an exception
to derive from *note BaseException: 1a9. or some descendant of *note
BaseException: 1a9, and future releases in the Python 2.x series may
begin to enforce this constraint.  Therefore, I suggest you begin making
all your exception classes derive from *note Exception: 1aa. now.  It’s
been suggested that the bare ‘except:’ form should be removed in Python
3.0, but Guido van Rossum hasn’t decided whether to do this or not.

Raising of strings as exceptions, as in the statement ‘raise "Error
occurred"’, is deprecated in Python 2.5 and will trigger a warning.  The
aim is to be able to remove the string-exception feature in a few
releases.

参见
....

PEP 352(1) - 异常所需的超类

     PEP 由 Brett Cannon 和 Guido van Rossum 撰写，由 Brett Cannon 实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0352


File: python.info,  Node: PEP 353 使用ssize_t作为索引类型,  Next: PEP 357 '__index__' 方法,  Prev: PEP 352 异常作为新型的类,  Up: Python 2 5 有什么新变化

1.12.10 PEP 353: 使用ssize_t作为索引类型
----------------------------------------

A wide-ranging change to Python’s C API, using a new ‘Py_ssize_t’ type
definition instead of ‘int’, will permit the interpreter to handle more
data on 64-bit platforms.  This change doesn’t affect Python’s capacity
on 32-bit platforms.

Various pieces of the Python interpreter used C’s ‘int’ type to store
sizes or counts; for example, the number of items in a list or tuple
were stored in an ‘int’.  The C compilers for most 64-bit platforms
still define ‘int’ as a 32-bit type, so that meant that lists could only
hold up to ‘2**31 - 1’ = 2147483647 items.  (There are actually a few
different programming models that 64-bit C compilers can use – see
‘http://www.unix.org/version2/whatsnew/lp64_wp.html’ for a discussion –
but the most commonly available model leaves ‘int’ as 32 bits.)

A limit of 2147483647 items doesn’t really matter on a 32-bit platform
because you’ll run out of memory before hitting the length limit.  Each
list item requires space for a pointer, which is 4 bytes, plus space for
a *note PyObject: 4c2. representing the item.  2147483647*4 is already
more bytes than a 32-bit address space can contain.

It’s possible to address that much memory on a 64-bit platform, however.
The pointers for a list that size would only require 16 GiB of space, so
it’s not unreasonable that Python programmers might construct lists that
large.  Therefore, the Python interpreter had to be changed to use some
type other than ‘int’, and this will be a 64-bit type on 64-bit
platforms.  The change will cause incompatibilities on 64-bit machines,
so it was deemed worth making the transition now, while the number of
64-bit users is still relatively small.  (In 5 or 10 years, we may `all'
be on 64-bit machines, and the transition would be more painful then.)

This change most strongly affects authors of C extension modules.
Python strings and container types such as lists and tuples now use
‘Py_ssize_t’ to store their size.  Functions such as *note
PyList_Size(): d86. now return ‘Py_ssize_t’.  Code in extension modules
may therefore need to have some variables changed to ‘Py_ssize_t’.

The *note PyArg_ParseTuple(): 26b. and *note Py_BuildValue(): 2cf.
functions have a new conversion code, ‘n’, for ‘Py_ssize_t’.  *note
PyArg_ParseTuple(): 26b.’s ‘s#’ and ‘t#’ still output ‘int’ by default,
but you can define the macro ‘PY_SSIZE_T_CLEAN’ before including
‘Python.h’ to make them return ‘Py_ssize_t’.

PEP 353(1) has a section on conversion guidelines that extension authors
should read to learn about supporting 64-bit platforms.

参见
....

PEP 353(2) - 使用ssize_t作为索引类型

     PEP 由 Martin von Löwis 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0353

   (2) https://www.python.org/dev/peps/pep-0353


File: python.info,  Node: PEP 357 '__index__' 方法,  Next: 其他语言特性修改<11>,  Prev: PEP 353 使用ssize_t作为索引类型,  Up: Python 2 5 有什么新变化

1.12.11 PEP 357: ’__index__’ 方法
---------------------------------

The NumPy developers had a problem that could only be solved by adding a
new special method, *note __index__(): 18b.  When using slice notation,
as in ‘[start:stop:step]’, the values of the `start', `stop', and `step'
indexes must all be either integers or long integers.  NumPy defines a
variety of specialized integer types corresponding to unsigned and
signed integers of 8, 16, 32, and 64 bits, but there was no way to
signal that these types could be used as slice indexes.

Slicing can’t just use the existing *note __int__(): 18c. method because
that method is also used to implement coercion to integers.  If slicing
used *note __int__(): 18c, floating-point numbers would also become
legal slice indexes and that’s clearly an undesirable behaviour.

Instead, a new special method called *note __index__(): 18b. was added.
It takes no arguments and returns an integer giving the slice index to
use.  For example:

     class C:
         def __index__ (self):
             return self.value

The return value must be either a Python integer or long integer.  The
interpreter will check that the type returned is correct, and raises a
*note TypeError: 193. if this requirement isn’t met.

A corresponding ‘nb_index’ slot was added to the C-level *note
PyNumberMethods: d89. structure to let C extensions implement this
protocol.  ‘PyNumber_Index(obj)’ can be used in extension code to call
the *note __index__(): 18b. function and retrieve its result.

参见
....

PEP 357(1) - 允许将任何对象用于切片

     PEP 由 Travis Oliphant 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0357


File: python.info,  Node: 其他语言特性修改<11>,  Next: 新增，改进和删除的模块,  Prev: PEP 357 '__index__' 方法,  Up: Python 2 5 有什么新变化

1.12.12 其他语言特性修改
------------------------

Here are all of the changes that Python 2.5 makes to the core Python
language.

   * The *note dict: 1b9. type has a new hook for letting subclasses
     provide a default value when a key isn’t contained in the
     dictionary.  When a key isn’t found, the dictionary’s
     ‘__missing__(key)’ method will be called.  This hook is used to
     implement the new ‘defaultdict’ class in the *note collections: 1e.
     module.  The following example defines a dictionary that returns
     zero for any missing key:

          class zerodict (dict):
              def __missing__ (self, key):
                  return 0

          d = zerodict({1:1, 2:2})
          print d[1], d[2]   # Prints 1, 2
          print d[3], d[4]   # Prints 0, 0

   * Both 8-bit and Unicode strings have new ‘partition(sep)’ and
     ‘rpartition(sep)’ methods that simplify a common use case.

     The ‘find(S)’ method is often used to get an index which is then
     used to slice the string and obtain the pieces that are before and
     after the separator.  ‘partition(sep)’ condenses this pattern into
     a single method call that returns a 3-tuple containing the
     substring before the separator, the separator itself, and the
     substring after the separator.  If the separator isn’t found, the
     first element of the tuple is the entire string and the other two
     elements are empty.  ‘rpartition(sep)’ also returns a 3-tuple but
     starts searching from the end of the string; the ‘r’ stands for
     ’reverse’.

     几个例子:

          >>> ('http://www.python.org').partition('://')
          ('http', '://', 'www.python.org')
          >>> ('file:/usr/share/doc/index.html').partition('://')
          ('file:/usr/share/doc/index.html', '', '')
          >>> (u'Subject: a quick question').partition(':')
          (u'Subject', u':', u' a quick question')
          >>> 'www.python.org'.rpartition('.')
          ('www.python', '.', 'org')
          >>> 'www.python.org'.rpartition(':')
          ('', '', 'www.python.org')

     (Implemented by Fredrik Lundh following a suggestion by Raymond
     Hettinger.)

   * The ‘startswith()’ and ‘endswith()’ methods of string types now
     accept tuples of strings to check for.

          def is_image_file (filename):
              return filename.endswith(('.gif', '.jpg', '.tiff'))

     (Implemented by Georg Brandl following a suggestion by Tom Lynn.)

   * The *note min(): 812. and *note max(): 813. built-in functions
     gained a ‘key’ keyword parameter analogous to the ‘key’ argument
     for ‘sort()’.  This parameter supplies a function that takes a
     single argument and is called for every value in the list; *note
     min(): 812./*note max(): 813. will return the element with the
     smallest/largest return value from this function.  For example, to
     find the longest string in a list, you can do:

          L = ['medium', 'longest', 'short']
          # Prints 'longest'
          print max(L, key=len)
          # Prints 'short', because lexicographically 'short' has the largest value
          print max(L)

     （由 Steven Bethard 和 Raymond Hettinger 贡献。）

   * Two new built-in functions, *note any(): d8c. and *note all(): d8d,
     evaluate whether an iterator contains any true or false values.
     *note any(): d8c. returns *note True: 4a1. if any value returned by
     the iterator is true; otherwise it will return *note False: 390.
     *note all(): d8d. returns *note True: 4a1. only if all of the
     values returned by the iterator evaluate as true.  (Suggested by
     Guido van Rossum, and implemented by Raymond Hettinger.)

   * The result of a class’s *note __hash__(): 349. method can now be
     either a long integer or a regular integer.  If a long integer is
     returned, the hash of that value is taken.  In earlier versions the
     hash value was required to be a regular integer, but in 2.5 the
     *note id(): d8e. built-in was changed to always return non-negative
     numbers, and users often seem to use ‘id(self)’ in *note
     __hash__(): 349. methods (though this is discouraged).

   * ASCII is now the default encoding for modules.  It’s now a syntax
     error if a module contains string literals with 8-bit characters
     but doesn’t have an encoding declaration.  In Python 2.4 this
     triggered a warning, not a syntax error.  See PEP 263(1) for how to
     declare a module’s encoding; for example, you might add a line like
     this near the top of the source file:

          # -*- coding: latin1 -*-

   * A new warning, *note UnicodeWarning: d8f, is triggered when you
     attempt to compare a Unicode string and an 8-bit string that can’t
     be converted to Unicode using the default ASCII encoding.  The
     result of the comparison is false:

          >>> chr(128) == unichr(128)   # Can't convert chr(128) to Unicode
          __main__:1: UnicodeWarning: Unicode equal comparison failed
            to convert both arguments to Unicode - interpreting them
            as being unequal
          False
          >>> chr(127) == unichr(127)   # chr(127) can be converted
          True

     Previously this would raise a *note UnicodeDecodeError: 1fe.
     exception, but in 2.5 this could result in puzzling problems when
     accessing a dictionary.  If you looked up ‘unichr(128)’ and
     ‘chr(128)’ was being used as a key, you’d get a *note
     UnicodeDecodeError: 1fe. exception.  Other changes in 2.5 resulted
     in this exception being raised instead of suppressed by the code in
     ‘dictobject.c’ that implements dictionaries.

     Raising an exception for such a comparison is strictly correct, but
     the change might have broken code, so instead *note UnicodeWarning:
     d8f. was introduced.

     （由 Marc-André Lemburg 实现。）

   * One error that Python programmers sometimes make is forgetting to
     include an ‘__init__.py’ module in a package directory.  Debugging
     this mistake can be confusing, and usually requires running Python
     with the *note -v: d90. switch to log all the paths searched.  In
     Python 2.5, a new *note ImportWarning: 5e1. warning is triggered
     when an import would have picked up a directory as a package but no
     ‘__init__.py’ was found.  This warning is silently ignored by
     default; provide the *note -Wd: 41f. option when running the Python
     executable to display the warning message.  (Implemented by Thomas
     Wouters.)

   * The list of base classes in a class definition can now be empty.
     As an example, this is now legal:

          class C():
              pass

     （由 Brett Cannon 实现。）

* Menu:

* 交互解释器变更::
* 性能优化: 性能优化<10>.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0263


File: python.info,  Node: 交互解释器变更,  Next: 性能优化<10>,  Up: 其他语言特性修改<11>

1.12.12.1 交互解释器变更
........................

In the interactive interpreter, ‘quit’ and ‘exit’ have long been strings
so that new users get a somewhat helpful message when they try to quit:

     >>> quit
     'Use Ctrl-D (i.e. EOF) to exit.'

In Python 2.5, ‘quit’ and ‘exit’ are now objects that still produce
string representations of themselves, but are also callable.  Newbies
who try ‘quit()’ or ‘exit()’ will now exit the interpreter as they
expect.  (Implemented by Georg Brandl.)

The Python executable now accepts the standard long options *note –help:
d93. and *note –version: 5da.; on Windows, it also accepts the *note /?:
d94. option for displaying a help message.  (Implemented by Georg
Brandl.)


File: python.info,  Node: 性能优化<10>,  Prev: 交互解释器变更,  Up: 其他语言特性修改<11>

1.12.12.2 性能优化
..................

Several of the optimizations were developed at the NeedForSpeed sprint,
an event held in Reykjavik, Iceland, from May 21–28 2006.  The sprint
focused on speed enhancements to the CPython implementation and was
funded by EWT LLC with local support from CCP Games.  Those
optimizations added at this sprint are specially marked in the following
list.

   * When they were introduced in Python 2.4, the built-in *note set:
     b77. and *note frozenset: bf6. types were built on top of Python’s
     dictionary type.  In 2.5 the internal data structure has been
     customized for implementing sets, and as a result sets will use a
     third less memory and are somewhat faster.  (Implemented by Raymond
     Hettinger.)

   * The speed of some Unicode operations, such as finding substrings,
     string splitting, and character map encoding and decoding, has been
     improved.  (Substring search and splitting improvements were added
     by Fredrik Lundh and Andrew Dalke at the NeedForSpeed sprint.
     Character maps were improved by Walter Dörwald and Martin von
     Löwis.)

   * The ‘long(str, base)’ function is now faster on long digit strings
     because fewer intermediate results are calculated.  The peak is for
     strings of around 800–1000 digits where the function is 6 times
     faster.  (Contributed by Alan McIntyre and committed at the
     NeedForSpeed sprint.)

   * It’s now illegal to mix iterating over a file with ‘for line in
     file’ and calling the file object’s ‘read()’/*note readline():
     df./‘readlines()’ methods.  Iteration uses an internal buffer and
     the ‘read*()’ methods don’t use that buffer.  Instead they would
     return the data following the buffer, causing the data to appear
     out of order.  Mixing iteration and these methods will now trigger
     a *note ValueError: 1fc. from the ‘read*()’ method.  (Implemented
     by Thomas Wouters.)

   * The *note struct: f9. module now compiles structure format strings
     into an internal representation and caches this representation,
     yielding a 20% speedup.  (Contributed by Bob Ippolito at the
     NeedForSpeed sprint.)

   * The *note re: de. module got a 1 or 2% speedup by switching to
     Python’s allocator functions instead of the system’s ‘malloc()’ and
     ‘free()’.  (Contributed by Jack Diederich at the NeedForSpeed
     sprint.)

   * The code generator’s peephole optimizer now performs simple
     constant folding in expressions.  If you write something like ‘a =
     2+3’, the code generator will do the arithmetic and produce code
     corresponding to ‘a = 5’.  (Proposed and implemented by Raymond
     Hettinger.)

   * Function calls are now faster because code objects now keep the
     most recently finished frame (a "zombie frame") in an internal
     field of the code object, reusing it the next time the code object
     is invoked.  (Original patch by Michael Hudson, modified by Armin
     Rigo and Richard Jones; committed at the NeedForSpeed sprint.)
     Frame objects are also slightly smaller, which may improve cache
     locality and reduce memory usage a bit.  (Contributed by Neal
     Norwitz.)

   * Python’s built-in exceptions are now new-style classes, a change
     that speeds up instantiation considerably.  Exception handling in
     Python 2.5 is therefore about 30% faster than in 2.4.  (Contributed
     by Richard Jones, Georg Brandl and Sean Reifschneider at the
     NeedForSpeed sprint.)

   * Importing now caches the paths tried, recording whether they exist
     or not so that the interpreter makes fewer ‘open()’ and ‘stat()’
     calls on startup.  (Contributed by Martin von Löwis and Georg
     Brandl.)


File: python.info,  Node: 新增，改进和删除的模块,  Next: 构建和 C API 的改变<10>,  Prev: 其他语言特性修改<11>,  Up: Python 2 5 有什么新变化

1.12.13 新增，改进和删除的模块
------------------------------

The standard library received many enhancements and bug fixes in Python
2.5.  Here’s a partial list of the most notable changes, sorted
alphabetically by module name.  Consult the ‘Misc/NEWS’ file in the
source tree for a more complete list of changes, or look through the SVN
logs for all the details.

   * The *note audioop: d. module now supports the a-LAW encoding, and
     the code for u-LAW encoding has been improved.  (Contributed by
     Lars Immisch.)

   * The *note codecs: 1c. module gained support for incremental codecs.
     The ‘codec.lookup()’ function now returns a ‘CodecInfo’ instance
     instead of a tuple.  ‘CodecInfo’ instances behave like a 4-tuple to
     preserve backward compatibility but also have the attributes
     ‘encode’, ‘decode’, ‘incrementalencoder’, ‘incrementaldecoder’,
     ‘streamwriter’, and ‘streamreader’.  Incremental codecs can receive
     input and produce output in multiple chunks; the output is the same
     as if the entire input was fed to the non-incremental codec.  See
     the *note codecs: 1c. module documentation for details.  (Designed
     and implemented by Walter Dörwald.)

   * The *note collections: 1e. module gained a new type, ‘defaultdict’,
     that subclasses the standard *note dict: 1b9. type.  The new type
     mostly behaves like a dictionary but constructs a default value
     when a key isn’t present, automatically adding it to the dictionary
     for the requested key value.

     The first argument to ‘defaultdict’’s constructor is a factory
     function that gets called whenever a key is requested but not
     found.  This factory function receives no arguments, so you can use
     built-in type constructors such as *note list(): 263. or *note
     int(): 185.  For example, you can make an index of words based on
     their initial letter like this:

          words = """Nel mezzo del cammin di nostra vita
          mi ritrovai per una selva oscura
          che la diritta via era smarrita""".lower().split()

          index = defaultdict(list)

          for w in words:
              init_letter = w[0]
              index[init_letter].append(w)

     打印 ‘index’ 导致以下输出:

          defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
                  'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
                  'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
                  'p': ['per'], 's': ['selva', 'smarrita'],
                  'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}

     （由 Guido van Rossum 贡献。）

   * The ‘deque’ double-ended queue type supplied by the *note
     collections: 1e. module now has a ‘remove(value)’ method that
     removes the first occurrence of `value' in the queue, raising *note
     ValueError: 1fc. if the value isn’t found.  (Contributed by Raymond
     Hettinger.)

   * New module: The *note contextlib: 24. module contains helper
     functions for use with the new ’*note with: 6f2.’ statement.  See
     section *note contextlib 模块: d7f. for more about this module.

   * New module: The *note cProfile: 28. module is a C implementation of
     the existing *note profile: d4. module that has much lower
     overhead.  The module’s interface is the same as *note profile:
     d4.: you run ‘cProfile.run('main()')’ to profile a function, can
     save profile data to a file, etc.  It’s not yet known if the
     Hotshot profiler, which is also written in C but doesn’t match the
     *note profile: d4. module’s interface, will continue to be
     maintained in future versions of Python.  (Contributed by Armin
     Rigo.)

     Also, the *note pstats: d5. module for analyzing the data measured
     by the profiler now supports directing the output to any file
     object by supplying a `stream' argument to the ‘Stats’ constructor.
     (Contributed by Skip Montanaro.)

   * The *note csv: 2a. module, which parses files in comma-separated
     value format, received several enhancements and a number of
     bugfixes.  You can now set the maximum size in bytes of a field by
     calling the ‘csv.field_size_limit(new_limit)’ function; omitting
     the `new_limit' argument will return the currently-set limit.  The
     ‘reader’ class now has a ‘line_num’ attribute that counts the
     number of physical lines read from the source; records can span
     multiple physical lines, so ‘line_num’ is not the same as the
     number of records read.

     The CSV parser is now stricter about multi-line quoted fields.
     Previously, if a line ended within a quoted field without a
     terminating newline character, a newline would be inserted into the
     returned field.  This behavior caused problems when reading files
     that contained carriage return characters within fields, so the
     code was changed to return the field without inserting newlines.
     As a consequence, if newlines embedded within fields are important,
     the input should be split into lines in a manner that preserves the
     newline characters.

     （由Skip Montanaro 和 Andrew McNamara 贡献。）

   * The *note datetime: 195. class in the *note datetime: 31. module
     now has a ‘strptime(string, format)’ method for parsing date
     strings, contributed by Josh Spoerri.  It uses the same format
     characters as *note time.strptime(): d99. and *note
     time.strftime(): b6d.:

          from datetime import datetime

          ts = datetime.strptime('10:13:15 2006-03-07',
                                 '%H:%M:%S %Y-%m-%d')

   * The ‘SequenceMatcher.get_matching_blocks()’ method in the *note
     difflib: 37. module now guarantees to return a minimal list of
     blocks describing matching subsequences.  Previously, the algorithm
     would occasionally break a block of matching elements into two list
     entries.  (Enhancement by Tim Peters.)

   * The *note doctest: 67. module gained a ‘SKIP’ option that keeps an
     example from being executed at all.  This is intended for code
     snippets that are usage examples intended for the reader and aren’t
     actually test cases.

     An `encoding' parameter was added to the ‘testfile()’ function and
     the ‘DocFileSuite’ class to specify the file’s encoding.  This
     makes it easier to use non-ASCII characters in tests contained
     within a docstring.  (Contributed by Bjorn Tillenius.)

   * *note email: 69. 包已经升级到 4.0版 （由 Barry Warsaw 贡献）

   * The *note fileinput: 80. module was made more flexible.  Unicode
     filenames are now supported, and a `mode' parameter that defaults
     to ‘"r"’ was added to the *note input(): c73. function to allow
     opening files in binary or *note universal newlines: 5fd. mode.
     Another new parameter, `openhook', lets you use a function other
     than *note open(): 4f8. to open the input files.  Once you’re
     iterating over the set of files, the ‘FileInput’ object’s new
     ‘fileno()’ returns the file descriptor for the currently opened
     file.  (Contributed by Georg Brandl.)

   * In the *note gc: 86. module, the new ‘get_count()’ function returns
     a 3-tuple containing the current collection counts for the three GC
     generations.  This is accounting information for the garbage
     collector; when these counts reach a specified threshold, a garbage
     collection sweep will be made.  The existing *note gc.collect():
     22f. function now takes an optional `generation' argument of 0, 1,
     or 2 to specify which generation to collect.  (Contributed by Barry
     Warsaw.)

   * The ‘nsmallest()’ and ‘nlargest()’ functions in the *note heapq:
     8e. module now support a ‘key’ keyword parameter similar to the one
     provided by the *note min(): 812./*note max(): 813. functions and
     the ‘sort()’ methods.  For example:

          >>> import heapq
          >>> L = ["short", 'medium', 'longest', 'longer still']
          >>> heapq.nsmallest(2, L)  # Return two lowest elements, lexicographically
          ['longer still', 'longest']
          >>> heapq.nsmallest(2, L, key=len)   # Return two shortest elements
          ['short', 'medium']

     （由 Raymond Hettinger 贡献。）

   * The *note itertools.islice(): 3aa. function now accepts ‘None’ for
     the start and step arguments.  This makes it more compatible with
     the attributes of slice objects, so that you can now write the
     following:

          s = slice(5)     # Create slice object
          itertools.islice(iterable, s.start, s.stop, s.step)

     （由 Raymond Hettinger 贡献。）

   * The *note format(): 4e3. function in the *note locale: aa. module
     has been modified and two new functions were added,
     ‘format_string()’ and ‘currency()’.

     The *note format(): 4e3. function’s `val' parameter could
     previously be a string as long as no more than one %char specifier
     appeared; now the parameter must be exactly one %char specifier
     with no surrounding text.  An optional `monetary' parameter was
     also added which, if ‘True’, will use the locale’s rules for
     formatting currency in placing a separator between groups of three
     digits.

     To format strings with multiple %char specifiers, use the new
     ‘format_string()’ function that works like *note format(): 4e3. but
     also supports mixing %char specifiers with arbitrary text.

     A new ‘currency()’ function was also added that formats a number
     according to the current locale’s settings.

     （由Georg Brandl 贡献。）

   * The *note mailbox: af. module underwent a massive rewrite to add
     the capability to modify mailboxes in addition to reading them.  A
     new set of classes that include ‘mbox’, ‘MH’, and ‘Maildir’ are
     used to read mailboxes, and have an ‘add(message)’ method to add
     messages, ‘remove(key)’ to remove messages, and ‘lock()’/‘unlock()’
     to lock/unlock the mailbox.  The following example converts a
     maildir-format mailbox into an mbox-format one:

          import mailbox

          # 'factory=None' uses email.Message.Message as the class representing
          # individual messages.
          src = mailbox.Maildir('maildir', factory=None)
          dest = mailbox.mbox('/tmp/mbox')

          for msg in src:
              dest.add(msg)

     (Contributed by Gregory K. Johnson.  Funding was provided by
     Google’s 2005 Summer of Code.)

   * New module: the *note msilib: b6. module allows creating Microsoft
     Installer ‘.msi’ files and CAB files.  Some support for reading the
     ‘.msi’ database is also included.  (Contributed by Martin von
     Löwis.)

   * The *note nis: c0. module now supports accessing domains other than
     the system default domain by supplying a `domain' argument to the
     *note nis.match(): d9a. and *note nis.maps(): d9b. functions.
     (Contributed by Ben Bell.)

   * The *note operator: c3. module’s ‘itemgetter()’ and ‘attrgetter()’
     functions now support multiple fields.  A call such as
     ‘operator.attrgetter('a', 'b')’ will return a function that
     retrieves the ‘a’ and ‘b’ attributes.  Combining this new feature
     with the ‘sort()’ method’s ‘key’ parameter lets you easily sort
     lists using multiple fields.  (Contributed by Raymond Hettinger.)

   * The *note optparse: c4. module was updated to version 1.5.1 of the
     Optik library.  The ‘OptionParser’ class gained an ‘epilog’
     attribute, a string that will be printed after the help message,
     and a ‘destroy()’ method to break reference cycles created by the
     object.  (Contributed by Greg Ward.)

   * The *note os: c5. module underwent several changes.  The
     ‘stat_float_times’ variable now defaults to true, meaning that
     *note os.stat(): 1f2. will now return time values as floats.  (This
     doesn’t necessarily mean that *note os.stat(): 1f2. will return
     times that are precise to fractions of a second; not all systems
     support such precision.)

     Constants named *note os.SEEK_SET: d9c, *note os.SEEK_CUR: d9d, and
     *note os.SEEK_END: d9e. have been added; these are the parameters
     to the *note os.lseek(): a66. function.  Two new constants for
     locking are *note os.O_SHLOCK: d9f. and *note os.O_EXLOCK: da0.

     Two new functions, ‘wait3()’ and ‘wait4()’, were added.  They’re
     similar the ‘waitpid()’ function which waits for a child process to
     exit and returns a tuple of the process ID and its exit status, but
     ‘wait3()’ and ‘wait4()’ return additional information.  ‘wait3()’
     doesn’t take a process ID as input, so it waits for any child
     process to exit and returns a 3-tuple of `process-id',
     `exit-status', `resource-usage' as returned from the *note
     resource.getrusage(): da1. function.  ‘wait4(pid)’ does take a
     process ID. (Contributed by Chad J. Schroeder.)

     On FreeBSD, the *note os.stat(): 1f2. function now returns times
     with nanosecond resolution, and the returned object now has
     ‘st_gen’ and ‘st_birthtime’.  The ‘st_flags’ attribute is also
     available, if the platform supports it.  (Contributed by Antti
     Louko and Diego Pettenò.)

   * The Python debugger provided by the *note pdb: ca. module can now
     store lists of commands to execute when a breakpoint is reached and
     execution stops.  Once breakpoint #1 has been created, enter
     ‘commands 1’ and enter a series of commands to be executed,
     finishing the list with ‘end’.  The command list can include
     commands that resume execution, such as ‘continue’ or ‘next’.
     (Contributed by Grégoire Dooms.)

   * The *note pickle: cb. and ‘cPickle’ modules no longer accept a
     return value of ‘None’ from the *note __reduce__(): 19c. method;
     the method must return a tuple of arguments instead.  The ability
     to return ‘None’ was deprecated in Python 2.4, so this completes
     the removal of the feature.

   * The *note pkgutil: ce. module, containing various utility functions
     for finding packages, was enhanced to support PEP 302(1)’s import
     hooks and now also works for packages stored in ZIP-format
     archives.  (Contributed by Phillip J. Eby.)

   * The pybench benchmark suite by Marc-André Lemburg is now included
     in the ‘Tools/pybench’ directory.  The pybench suite is an
     improvement on the commonly used ‘pystone.py’ program because
     pybench provides a more detailed measurement of the interpreter’s
     speed.  It times particular operations such as function calls,
     tuple slicing, method lookups, and numeric operations, instead of
     performing many different operations and reducing the result to a
     single number as ‘pystone.py’ does.

   * The ‘pyexpat’ module now uses version 2.0 of the Expat parser.
     (Contributed by Trent Mick.)

   * The *note Queue: d20. class provided by the ‘Queue’ module gained
     two new methods.  ‘join()’ blocks until all items in the queue have
     been retrieved and all processing work on the items have been
     completed.  Worker threads call the other new method,
     ‘task_done()’, to signal that processing for an item has been
     completed.  (Contributed by Raymond Hettinger.)

   * The old ‘regex’ and ‘regsub’ modules, which have been deprecated
     ever since Python 2.0, have finally been deleted.  Other deleted
     modules: ‘statcache’, ‘tzparse’, ‘whrandom’.

   * Also deleted: the ‘lib-old’ directory, which includes ancient
     modules such as ‘dircmp’ and ‘ni’, was removed.  ‘lib-old’ wasn’t
     on the default ‘sys.path’, so unless your programs explicitly added
     the directory to ‘sys.path’, this removal shouldn’t affect your
     code.

   * The *note rlcompleter: e2. module is no longer dependent on
     importing the *note readline: df. module and therefore now works on
     non-Unix platforms.  (Patch from Robert Kiendl.)

   * The ‘SimpleXMLRPCServer’ and ‘DocXMLRPCServer’ classes now have a
     ‘rpc_paths’ attribute that constrains XML-RPC operations to a
     limited set of URL paths; the default is to allow only ‘'/'’ and
     ‘'/RPC2'’.  Setting ‘rpc_paths’ to ‘None’ or an empty tuple
     disables this path checking.

   * The *note socket: f0. module now supports ‘AF_NETLINK’ sockets on
     Linux, thanks to a patch from Philippe Biondi.  Netlink sockets are
     a Linux-specific mechanism for communications between a user-space
     process and kernel code; an introductory article about them is at
     ‘https://www.linuxjournal.com/article/7356’.  In Python code,
     netlink addresses are represented as a tuple of 2 integers, ‘(pid,
     group_mask)’.

     Two new methods on socket objects, ‘recv_into(buffer)’ and
     ‘recvfrom_into(buffer)’, store the received data in an object that
     supports the buffer protocol instead of returning the data as a
     string.  This means you can put the data directly into an array or
     a memory-mapped file.

     Socket objects also gained ‘getfamily()’, ‘gettype()’, and
     ‘getproto()’ accessor methods to retrieve the family, type, and
     protocol values for the socket.

   * New module: the *note spwd: f2. module provides functions for
     accessing the shadow password database on systems that support
     shadow passwords.

   * The *note struct: f9. is now faster because it compiles format
     strings into ‘Struct’ objects with ‘pack()’ and ‘unpack()’ methods.
     This is similar to how the *note re: de. module lets you create
     compiled regular expression objects.  You can still use the
     module-level ‘pack()’ and ‘unpack()’ functions; they’ll create
     ‘Struct’ objects and cache them.  Or you can use ‘Struct’ instances
     directly:

          s = struct.Struct('ih3s')

          data = s.pack(1972, 187, 'abc')
          year, number, name = s.unpack(data)

     You can also pack and unpack data to and from buffer objects
     directly using the ‘pack_into(buffer, offset, v1, v2, ...)’ and
     ‘unpack_from(buffer, offset)’ methods.  This lets you store data
     directly into an array or a memory-mapped file.

     (‘Struct’ objects were implemented by Bob Ippolito at the
     NeedForSpeed sprint.  Support for buffer objects was added by
     Martin Blais, also at the NeedForSpeed sprint.)

   * The Python developers switched from CVS to Subversion during the
     2.5 development process.  Information about the exact build version
     is available as the ‘sys.subversion’ variable, a 3-tuple of
     ‘(interpreter-name, branch-name, revision-range)’.  For example, at
     the time of writing my copy of 2.5 was reporting ‘('CPython',
     'trunk', '45313:45315')’.

     This information is also available to C extensions via the *note
     Py_GetBuildInfo(): da2. function that returns a string of build
     information like this: ‘"trunk:45355:45356M, Apr 13 2006,
     07:42:19"’.  (Contributed by Barry Warsaw.)

   * Another new function, *note sys._current_frames(): da3, returns the
     current stack frames for all running threads as a dictionary
     mapping thread identifiers to the topmost stack frame currently
     active in that thread at the time the function is called.
     (Contributed by Tim Peters.)

   * The ‘TarFile’ class in the *note tarfile: 102. module now has an
     ‘extractall()’ method that extracts all members from the archive
     into the current working directory.  It’s also possible to set a
     different directory as the extraction target, and to unpack only a
     subset of the archive’s members.

     The compression used for a tarfile opened in stream mode can now be
     autodetected using the mode ‘'r|*'’.  (Contributed by Lars
     Gustäbel.)

   * The *note threading: 10a. module now lets you set the stack size
     used when new threads are created.  The ‘stack_size([*size*])’
     function returns the currently configured stack size, and supplying
     the optional `size' parameter sets a new value.  Not all platforms
     support changing the stack size, but Windows, POSIX threading, and
     OS/2 all do.  (Contributed by Andrew MacIntyre.)

   * The *note unicodedata: 11b. module has been updated to use version
     4.1.0 of the Unicode character database.  Version 3.2.0 is required
     by some specifications, so it’s still available as *note
     unicodedata.ucd_3_2_0: da4.

   * New module: the *note uuid: 125. module generates universally
     unique identifiers (UUIDs) according to RFC 4122(2).  The RFC
     defines several different UUID versions that are generated from a
     starting string, from system properties, or purely randomly.  This
     module contains a ‘UUID’ class and functions named ‘uuid1()’,
     ‘uuid3()’, ‘uuid4()’, and ‘uuid5()’ to generate different versions
     of UUID. (Version 2 UUIDs are not specified in RFC 4122(3) and are
     not supported by this module.)

          >>> import uuid
          >>> # make a UUID based on the host ID and current time
          >>> uuid.uuid1()
          UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

          >>> # make a UUID using an MD5 hash of a namespace UUID and a name
          >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
          UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

          >>> # make a random UUID
          >>> uuid.uuid4()
          UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

          >>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
          >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
          UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

     （由 Ka-Ping Yee 贡献。）

   * The *note weakref: 129. module’s ‘WeakKeyDictionary’ and
     ‘WeakValueDictionary’ types gained new methods for iterating over
     the weak references contained in the dictionary.  ‘iterkeyrefs()’
     and ‘keyrefs()’ methods were added to ‘WeakKeyDictionary’, and
     ‘itervaluerefs()’ and ‘valuerefs()’ were added to
     ‘WeakValueDictionary’.  (Contributed by Fred L. Drake, Jr.)

   * The *note webbrowser: 12a. module received a number of
     enhancements.  It’s now usable as a script with ‘python -m
     webbrowser’, taking a URL as the argument; there are a number of
     switches to control the behaviour (‘-n’ for a new browser window,
     ‘-t’ for a new tab).  New module-level functions, ‘open_new()’ and
     ‘open_new_tab()’, were added to support this.  The module’s *note
     open(): 4f8. function supports an additional feature, an
     `autoraise' parameter that signals whether to raise the open window
     when possible.  A number of additional browsers were added to the
     supported list such as Firefox, Opera, Konqueror, and elinks.
     (Contributed by Oleg Broytmann and Georg Brandl.)

   * The ‘xmlrpclib’ module now supports returning *note datetime: 195.
     objects for the XML-RPC date type.  Supply ‘use_datetime=True’ to
     the ‘loads()’ function or the ‘Unmarshaller’ class to enable this
     feature.  (Contributed by Skip Montanaro.)

   * The *note zipfile: 143. module now supports the ZIP64 version of
     the format, meaning that a .zip archive can now be larger than 4
     GiB and can contain individual files larger than 4 GiB.
     (Contributed by Ronald Oussoren.)

   * The *note zlib: 145. module’s ‘Compress’ and ‘Decompress’ objects
     now support a *note copy(): 26. method that makes a copy of the
     object’s internal state and returns a new ‘Compress’ or
     ‘Decompress’ object.  (Contributed by Chris AtLee.)

* Menu:

* ctypes 包::
* ElementTree 包::
* hashlib 包::
* sqlite3 包::
* wsgiref 包::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0302

   (2) https://tools.ietf.org/html/rfc4122.html

   (3) https://tools.ietf.org/html/rfc4122.html


File: python.info,  Node: ctypes 包,  Next: ElementTree 包,  Up: 新增，改进和删除的模块

1.12.13.1 ctypes 包
...................

The *note ctypes: 2b. package, written by Thomas Heller, has been added
to the standard library.  *note ctypes: 2b. lets you call arbitrary
functions in shared libraries or DLLs.  Long-time users may remember the
‘dl’ module, which provides functions for loading shared libraries and
calling functions in them.  The *note ctypes: 2b. package is much
fancier.

To load a shared library or DLL, you must create an instance of the
‘CDLL’ class and provide the name or path of the shared library or DLL.
Once that’s done, you can call arbitrary functions by accessing them as
attributes of the ‘CDLL’ object.

     import ctypes

     libc = ctypes.CDLL('libc.so.6')
     result = libc.printf("Line of output\n")

Type constructors for the various C types are provided: ‘c_int()’,
‘c_float()’, ‘c_double()’, ‘c_char_p()’ (equivalent to ‘char *’), and so
forth.  Unlike Python’s types, the C versions are all mutable; you can
assign to their ‘value’ attribute to change the wrapped value.  Python
integers and strings will be automatically converted to the
corresponding C types, but for other types you must call the correct
type constructor.  (And I mean `must'; getting it wrong will often
result in the interpreter crashing with a segmentation fault.)

You shouldn’t use ‘c_char_p()’ with a Python string when the C function
will be modifying the memory area, because Python strings are supposed
to be immutable; breaking this rule will cause puzzling bugs.  When you
need a modifiable memory area, use ‘create_string_buffer()’:

     s = "this is a string"
     buf = ctypes.create_string_buffer(s)
     libc.strfry(buf)

C functions are assumed to return integers, but you can set the
‘restype’ attribute of the function object to change this:

     >>> libc.atof('2.71828')
     -1783957616
     >>> libc.atof.restype = ctypes.c_double
     >>> libc.atof('2.71828')
     2.71828

*note ctypes: 2b. also provides a wrapper for Python’s C API as the
‘ctypes.pythonapi’ object.  This object does `not' release the global
interpreter lock before calling a function, because the lock must be
held when calling into the interpreter’s code.  There’s a ‘py_object()’
type constructor that will create a *note PyObject *: 4c2. pointer.  A
simple usage:

     import ctypes

     d = {}
     ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
               ctypes.py_object("abc"),  ctypes.py_object(1))
     # d is now {'abc', 1}.

Don’t forget to use ‘py_object()’; if it’s omitted you end up with a
segmentation fault.

*note ctypes: 2b. has been around for a while, but people still write
and distribution hand-coded extension modules because you can’t rely on
*note ctypes: 2b. being present.  Perhaps developers will begin to write
Python wrappers atop a library accessed through *note ctypes: 2b.
instead of extension modules, now that *note ctypes: 2b. is included
with core Python.

参见
....

‘http://starship.python.net/crew/theller/ctypes/’

     ctypes的主页，含教程， 参考和常见问题解答。

*note ctypes: 2b. 模块的文档。


File: python.info,  Node: ElementTree 包,  Next: hashlib 包,  Prev: ctypes 包,  Up: 新增，改进和删除的模块

1.12.13.2 ElementTree 包
........................

A subset of Fredrik Lundh’s ElementTree library for processing XML has
been added to the standard library as ‘xml.etree’.  The available
modules are ‘ElementTree’, ‘ElementPath’, and ‘ElementInclude’ from
ElementTree 1.2.6.  The ‘cElementTree’ accelerator module is also
included.

The rest of this section will provide a brief overview of using
ElementTree.  Full documentation for ElementTree is available at
‘http://effbot.org/zone/element-index.htm’.

ElementTree represents an XML document as a tree of element nodes.  The
text content of the document is stored as the ‘text’ and ‘tail’
attributes of (This is one of the major differences between ElementTree
and the Document Object Model; in the DOM there are many different types
of node, including ‘TextNode’.)

The most commonly used parsing function is ‘parse()’, that takes either
a string (assumed to contain a filename) or a file-like object and
returns an ‘ElementTree’ instance:

     from xml.etree import ElementTree as ET

     tree = ET.parse('ex-1.xml')

     feed = urllib.urlopen(
               'http://planet.python.org/rss10.xml')
     tree = ET.parse(feed)

Once you have an ‘ElementTree’ instance, you can call its ‘getroot()’
method to get the root ‘Element’ node.

There’s also an ‘XML()’ function that takes a string literal and returns
an ‘Element’ node (not an ‘ElementTree’).  This function provides a tidy
way to incorporate XML fragments, approaching the convenience of an XML
literal:

     svg = ET.XML("""<svg width="10px" version="1.0">
                  </svg>""")
     svg.set('height', '320px')
     svg.append(elem1)

Each XML element supports some dictionary-like and some list-like access
methods.  Dictionary-like operations are used to access attribute
values, and list-like operations are used to access child nodes.

运算                                结果：
                                    
-------------------------------------------------------------------------------------
                                    
‘elem[n]’                           返回第n个子元素
                                    
                                    
‘elem[m:n]’                         返回第m至第n个子元素的列表。
                                    
                                    
‘len(elem)’                         返回子元素的个数
                                    
                                    
‘list(elem)’                        返回子元素的列表
                                    
                                    
‘elem.append(elem2)’                将 `elem2' 添加为子级。
                                    
                                    
‘elem.insert(index, elem2)’         在指定位置插入 `elem2' 。
                                    
                                    
‘del elem[n]’                       删除第n个子元素
                                    
                                    
‘elem.keys()’                       返回属性名称的列表。
                                    
                                    
‘elem.get(name)’                    返回 `name' 属性的值。
                                    
                                    
‘elem.set(name, value)’             为 `name' 属性设置新值
                                    
                                    
‘elem.attrib’                       检索包含属性的字典。
                                    
                                    
‘del elem.attrib[name]’             删除 元素 `name' 的属性
                                    

Comments and processing instructions are also represented as ‘Element’
nodes.  To check if a node is a comment or processing instructions:

     if elem.tag is ET.Comment:
         ...
     elif elem.tag is ET.ProcessingInstruction:
         ...

To generate XML output, you should call the ‘ElementTree.write()’
method.  Like ‘parse()’, it can take either a string or a file-like
object:

     # Encoding is US-ASCII
     tree.write('output.xml')

     # Encoding is UTF-8
     f = open('output.xml', 'w')
     tree.write(f, encoding='utf-8')

(Caution: the default encoding used for output is ASCII. For general XML
work, where an element’s name may contain arbitrary Unicode characters,
ASCII isn’t a very useful encoding because it will raise an exception if
an element’s name contains any characters with values greater than 127.
Therefore, it’s best to specify a different encoding such as UTF-8 that
can handle any Unicode character.)

This section is only a partial description of the ElementTree
interfaces.  Please read the package’s official documentation for more
details.

参见
....

‘http://effbot.org/zone/element-index.htm’

     ElementTree 的官方文档


File: python.info,  Node: hashlib 包,  Next: sqlite3 包,  Prev: ElementTree 包,  Up: 新增，改进和删除的模块

1.12.13.3 hashlib 包
....................

A new *note hashlib: 8d. module, written by Gregory P. Smith, has been
added to replace the ‘md5’ and ‘sha’ modules.  *note hashlib: 8d. adds
support for additional secure hashes (SHA-224, SHA-256, SHA-384, and
SHA-512).  When available, the module uses OpenSSL for fast platform
optimized implementations of algorithms.

The old ‘md5’ and ‘sha’ modules still exist as wrappers around hashlib
to preserve backwards compatibility.  The new module’s interface is very
close to that of the old modules, but not identical.  The most
significant difference is that the constructor functions for creating
new hashing objects are named differently.

     # Old versions
     h = md5.md5()
     h = md5.new()

     # New version
     h = hashlib.md5()

     # Old versions
     h = sha.sha()
     h = sha.new()

     # New version
     h = hashlib.sha1()

     # Hash that weren't previously available
     h = hashlib.sha224()
     h = hashlib.sha256()
     h = hashlib.sha384()
     h = hashlib.sha512()

     # Alternative form
     h = hashlib.new('md5')          # Provide algorithm as a string

Once a hash object has been created, its methods are the same as before:
‘update(string)’ hashes the specified string into the current digest
state, ‘digest()’ and ‘hexdigest()’ return the digest value as a binary
string or a string of hex digits, and *note copy(): 26. returns a new
hashing object with the same digest state.

参见
....

*note hashlib: 8d. 模块的文档。


File: python.info,  Node: sqlite3 包,  Next: wsgiref 包,  Prev: hashlib 包,  Up: 新增，改进和删除的模块

1.12.13.4 sqlite3 包
....................

The pysqlite module (‘http://www.pysqlite.org’), a wrapper for the
SQLite embedded database, has been added to the standard library under
the package name *note sqlite3: f3.

SQLite 是一个C语言库，它可以提供一种轻量级的基于磁盘的数据库，这种数据库
不需要独立的服务器进程，也允许需要使用一种非标准的 SQL 查询语言来访问它
。一些应用程序可以使用 SQLite 作为内部数据存储。可以用它来创建一个应用程
序原型，然后再迁移到更大的数据库，比如 PostgreSQL 或 Oracle。

pysqlite was written by Gerhard Häring and provides a SQL interface
compliant with the DB-API 2.0 specification described by PEP 249(1).

If you’re compiling the Python source yourself, note that the source
tree doesn’t include the SQLite code, only the wrapper module.  You’ll
need to have the SQLite libraries and headers installed before compiling
Python, and the build process will compile the module when the necessary
headers are available.

To use the module, you must first create a ‘Connection’ object that
represents the database.  Here the data will be stored in the
‘/tmp/example’ file:

     conn = sqlite3.connect('/tmp/example')

你也可以使用 ‘:memory:’ 来创建一个内存中的数据库

Once you have a ‘Connection’, you can create a ‘Cursor’ object and call
its ‘execute()’ method to perform SQL commands:

     c = conn.cursor()

     # Create table
     c.execute('''create table stocks
     (date text, trans text, symbol text,
      qty real, price real)''')

     # Insert a row of data
     c.execute("""insert into stocks
               values ('2006-01-05','BUY','RHAT',100,35.14)""")

Usually your SQL operations will need to use values from Python
variables.  You shouldn’t assemble your query using Python’s string
operations because doing so is insecure; it makes your program
vulnerable to an SQL injection attack.

Instead, use the DB-API’s parameter substitution.  Put ‘?’ as a
placeholder wherever you want to use a value, and then provide a tuple
of values as the second argument to the cursor’s ‘execute()’ method.
(Other database modules may use a different placeholder, such as ‘%s’ or
‘:1’.)  For example:

     # Never do this -- insecure!
     symbol = 'IBM'
     c.execute("... where symbol = '%s'" % symbol)

     # Do this instead
     t = (symbol,)
     c.execute('select * from stocks where symbol=?', t)

     # Larger example
     for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
               ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
               ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
              ):
         c.execute('insert into stocks values (?,?,?,?,?)', t)

To retrieve data after executing a SELECT statement, you can either
treat the cursor as an iterator, call the cursor’s ‘fetchone()’ method
to retrieve a single matching row, or call ‘fetchall()’ to get a list of
the matching rows.

下面是一个使用迭代器形式的例子：

     >>> c = conn.cursor()
     >>> c.execute('select * from stocks order by price')
     >>> for row in c:
     ...    print row
     ...
     (u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
     (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
     (u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
     (u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
     >>>

For more information about the SQL dialect supported by SQLite, see
‘https://www.sqlite.org’.

参见
....

‘http://www.pysqlite.org’

     pysqlite 的主页

‘https://www.sqlite.org’

     SQLite的主页；它的文档详细描述了它所支持的 SQL 方言的语法和可用的数
     据类型。

*note sqlite3: f3. 模块的文档。

PEP 249(2) - DB-API 2.0 规范

     PEP 由 Marc-André Lemburg 撰写。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0249

   (2) https://www.python.org/dev/peps/pep-0249


File: python.info,  Node: wsgiref 包,  Prev: sqlite3 包,  Up: 新增，改进和删除的模块

1.12.13.5 wsgiref 包
....................

The Web Server Gateway Interface (WSGI) v1.0 defines a standard
interface between web servers and Python web applications and is
described in PEP 333(1).  The *note wsgiref: 12d. package is a reference
implementation of the WSGI specification.

The package includes a basic HTTP server that will run a WSGI
application; this server is useful for debugging but isn’t intended for
production use.  Setting up a server takes only a few lines of code:

     from wsgiref import simple_server

     wsgi_app = ...

     host = ''
     port = 8000
     httpd = simple_server.make_server(host, port, wsgi_app)
     httpd.serve_forever()

参见
....

‘http://www.wsgi.org’

     WSGI相关资源的核心网站。

PEP 333(2) - Python Web服务器网关接口 v1.0

     PEP 由 Phillip J. Eby 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0333

   (2) https://www.python.org/dev/peps/pep-0333


File: python.info,  Node: 构建和 C API 的改变<10>,  Next: 移植到Python 2 5,  Prev: 新增，改进和删除的模块,  Up: Python 2 5 有什么新变化

1.12.14 构建和 C API 的改变
---------------------------

Changes to Python’s build process and to the C API include:

   * The Python source tree was converted from CVS to Subversion, in a
     complex migration procedure that was supervised and flawlessly
     carried out by Martin von Löwis.  The procedure was developed as
     PEP 347(1).

   * Coverity, a company that markets a source code analysis tool called
     Prevent, provided the results of their examination of the Python
     source code.  The analysis found about 60 bugs that were quickly
     fixed.  Many of the bugs were refcounting problems, often occurring
     in error-handling code.  See ‘https://scan.coverity.com’ for the
     statistics.

   * The largest change to the C API came from PEP 353(2), which
     modifies the interpreter to use a ‘Py_ssize_t’ type definition
     instead of ‘int’.  See the earlier section *note PEP 353;
     使用ssize_t作为索引类型: d84. for a discussion of this change.

   * The design of the bytecode compiler has changed a great deal, no
     longer generating bytecode by traversing the parse tree.  Instead
     the parse tree is converted to an abstract syntax tree (or AST),
     and it is the abstract syntax tree that’s traversed to produce the
     bytecode.

     It’s possible for Python code to obtain AST objects by using the
     *note compile(): 1b5. built-in and specifying ‘_ast.PyCF_ONLY_AST’
     as the value of the `flags' parameter:

          from _ast import PyCF_ONLY_AST
          ast = compile("""a=0
          for i in range(10):
              a += i
          """, "<string>", 'exec', PyCF_ONLY_AST)

          assignment = ast.body[0]
          for_loop = ast.body[1]

     No official documentation has been written for the AST code yet,
     but PEP 339(3) discusses the design.  To start learning about the
     code, read the definition of the various AST nodes in
     ‘Parser/Python.asdl’.  A Python script reads this file and
     generates a set of C structure definitions in
     ‘Include/Python-ast.h’.  The ‘PyParser_ASTFromString()’ and
     ‘PyParser_ASTFromFile()’, defined in ‘Include/pythonrun.h’, take
     Python source as input and return the root of an AST representing
     the contents.  This AST can then be turned into a code object by
     ‘PyAST_Compile()’.  For more information, read the source code, and
     then ask questions on python-dev.

     The AST code was developed under Jeremy Hylton’s management, and
     implemented by (in alphabetical order) Brett Cannon, Nick Coghlan,
     Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim
     Peters, Armin Rigo, and Neil Schemenauer, plus the participants in
     a number of AST sprints at conferences such as PyCon.

   * Evan Jones’s patch to obmalloc, first described in a talk at PyCon
     DC 2005, was applied.  Python 2.4 allocated small objects in
     256K-sized arenas, but never freed arenas.  With this patch, Python
     will free arenas when they’re empty.  The net effect is that on
     some platforms, when you allocate many objects, Python’s memory
     usage may actually drop when you delete them and the memory may be
     returned to the operating system.  (Implemented by Evan Jones, and
     reworked by Tim Peters.)

     Note that this change means extension modules must be more careful
     when allocating memory.  Python’s API has many different functions
     for allocating memory that are grouped into families.  For example,
     *note PyMem_Malloc(): 50d, *note PyMem_Realloc(): 977, and *note
     PyMem_Free(): db1. are one family that allocates raw memory, while
     *note PyObject_Malloc(): 510, *note PyObject_Realloc(): db2, and
     *note PyObject_Free(): 50c. are another family that’s supposed to
     be used for creating Python objects.

     Previously these different families all reduced to the platform’s
     ‘malloc()’ and ‘free()’ functions.  This meant it didn’t matter if
     you got things wrong and allocated memory with the ‘PyMem()’
     function but freed it with the *note PyObject(): 4c2. function.
     With 2.5’s changes to obmalloc, these families now do different
     things and mismatches will probably result in a segfault.  You
     should carefully test your C extension modules with Python 2.5.

   * The built-in set types now have an official C API. Call *note
     PySet_New(): db3. and *note PyFrozenSet_New(): db4. to create a new
     set, *note PySet_Add(): db5. and *note PySet_Discard(): db6. to add
     and remove elements, and *note PySet_Contains(): db7. and *note
     PySet_Size(): db8. to examine the set’s state.  (Contributed by
     Raymond Hettinger.)

   * C code can now obtain information about the exact revision of the
     Python interpreter by calling the *note Py_GetBuildInfo(): da2.
     function that returns a string of build information like this:
     ‘"trunk:45355:45356M, Apr 13 2006, 07:42:19"’.  (Contributed by
     Barry Warsaw.)

   * Two new macros can be used to indicate C functions that are local
     to the current file so that a faster calling convention can be
     used.  ‘Py_LOCAL(type)’ declares the function as returning a value
     of the specified `type' and uses a fast-calling qualifier.
     ‘Py_LOCAL_INLINE(type)’ does the same thing and also requests the
     function be inlined.  If ‘PY_LOCAL_AGGRESSIVE()’ is defined before
     ‘python.h’ is included, a set of more aggressive optimizations are
     enabled for the module; you should benchmark the results to find
     out if these optimizations actually make the code faster.
     (Contributed by Fredrik Lundh at the NeedForSpeed sprint.)

   * ‘PyErr_NewException(name, base, dict)’ can now accept a tuple of
     base classes as its `base' argument.  (Contributed by Georg
     Brandl.)

   * The ‘PyErr_Warn()’ function for issuing warnings is now deprecated
     in favour of ‘PyErr_WarnEx(category, message, stacklevel)’ which
     lets you specify the number of stack frames separating this
     function and the caller.  A `stacklevel' of 1 is the function
     calling *note PyErr_WarnEx(): db9, 2 is the function above that,
     and so forth.  (Added by Neal Norwitz.)

   * The CPython interpreter is still written in C, but the code can now
     be compiled with a C++ compiler without errors.  (Implemented by
     Anthony Baxter, Martin von Löwis, Skip Montanaro.)

   * The ‘PyRange_New()’ function was removed.  It was never documented,
     never used in the core code, and had dangerously lax error
     checking.  In the unlikely case that your extensions were using it,
     you can replace it by something like the following:

          range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll",
                                        start, stop, step);

* Menu:

* Port-Specific Changes::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0347

   (2) https://www.python.org/dev/peps/pep-0353

   (3) https://www.python.org/dev/peps/pep-0339


File: python.info,  Node: Port-Specific Changes,  Up: 构建和 C API 的改变<10>

1.12.14.1 Port-Specific Changes
...............................

   * MacOS X (10.3 and higher): dynamic loading of modules now uses the
     ‘dlopen()’ function instead of MacOS-specific functions.

   * MacOS X: an ‘--enable-universalsdk’ switch was added to the
     ‘configure’ script that compiles the interpreter as a universal
     binary able to run on both PowerPC and Intel processors.
     (Contributed by Ronald Oussoren; bpo-2573(1).)

   * Windows: ‘.dll’ is no longer supported as a filename extension for
     extension modules.  ‘.pyd’ is now the only filename extension that
     will be searched for.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2573


File: python.info,  Node: 移植到Python 2 5,  Next: 致谢<3>,  Prev: 构建和 C API 的改变<10>,  Up: Python 2 5 有什么新变化

1.12.15 移植到Python 2.5
------------------------

This section lists previously described changes that may require changes
to your code:

   * ASCII is now the default encoding for modules.  It’s now a syntax
     error if a module contains string literals with 8-bit characters
     but doesn’t have an encoding declaration.  In Python 2.4 this
     triggered a warning, not a syntax error.

   * Previously, the ‘gi_frame’ attribute of a generator was always a
     frame object.  Because of the PEP 342(1) changes described in
     section *note PEP 342; 生成器的新特性: d6e, it’s now possible for
     ‘gi_frame’ to be ‘None’.

   * A new warning, *note UnicodeWarning: d8f, is triggered when you
     attempt to compare a Unicode string and an 8-bit string that can’t
     be converted to Unicode using the default ASCII encoding.
     Previously such comparisons would raise a *note UnicodeDecodeError:
     1fe. exception.

   * Library: the *note csv: 2a. module is now stricter about multi-line
     quoted fields.  If your files contain newlines embedded within
     fields, the input should be split into lines in a manner which
     preserves the newline characters.

   * Library: the *note locale: aa. module’s *note format(): 4e3.
     function’s would previously accept any string as long as no more
     than one %char specifier appeared.  In Python 2.5, the argument
     must be exactly one %char specifier with no surrounding text.

   * Library: The *note pickle: cb. and ‘cPickle’ modules no longer
     accept a return value of ‘None’ from the *note __reduce__(): 19c.
     method; the method must return a tuple of arguments instead.  The
     modules also no longer accept the deprecated `bin' keyword
     parameter.

   * Library: The ‘SimpleXMLRPCServer’ and ‘DocXMLRPCServer’ classes now
     have a ‘rpc_paths’ attribute that constrains XML-RPC operations to
     a limited set of URL paths; the default is to allow only ‘'/'’ and
     ‘'/RPC2'’.  Setting ‘rpc_paths’ to ‘None’ or an empty tuple
     disables this path checking.

   * C API: Many functions now use ‘Py_ssize_t’ instead of ‘int’ to
     allow processing more data on 64-bit machines.  Extension code may
     need to make the same change to avoid warnings and to support
     64-bit machines.  See the earlier section *note PEP 353;
     使用ssize_t作为索引类型: d84. for a discussion of this change.

   * C API: The obmalloc changes mean that you must be careful to not
     mix usage of the ‘PyMem_*()’ and ‘PyObject_*()’ families of
     functions.  Memory allocated with one family’s ‘*_Malloc()’ must be
     freed with the corresponding family’s ‘*_Free()’ function.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0342


File: python.info,  Node: 致谢<3>,  Prev: 移植到Python 2 5,  Up: Python 2 5 有什么新变化

1.12.16 致谢
------------

作者感谢以下人员对本文各种草稿给予的建议，更正和协助： Georg Brandl,
Nick Coghlan, Phillip J. Eby, Lars Gustäbel, Raymond Hettinger, Ralf W.
Grosse-Kunstleve, Kent Johnson, Iain Lowe, Martin von Löwis, Fredrik
Lundh, Andrew McNamara, Skip Montanaro, Gustavo Niemeyer, Paul Prescod,
James Pryor, Mike Rovner, Scott Weikart, Barry Warsaw, Thomas Wouters.


File: python.info,  Node: Python 2 4 有什么新变化,  Next: Python 2 3 有什么新变化,  Prev: Python 2 5 有什么新变化,  Up: Python的新变化

1.13 Python 2.4 有什么新变化
============================


作者: A.M. Kuchling

本文介绍了2005年3月30日发布的 Python 2.4.1 的新功能。

Python 2.4 is a medium-sized release.  It doesn’t introduce as many
changes as the radical Python 2.2, but introduces more features than the
conservative 2.3 release.  The most significant new language features
are function decorators and generator expressions; most other changes
are to the standard library.

According to the CVS change logs, there were 481 patches applied and 502
bugs fixed between Python 2.3 and 2.4.  Both figures are likely to be
underestimates.

This article doesn’t attempt to provide a complete specification of
every single new feature, but instead provides a brief introduction to
each feature.  For full details, you should refer to the documentation
for Python 2.4, such as the Python Library Reference and the Python
Reference Manual.  Often you will be referred to the PEP for a
particular new feature for explanations of the implementation and design
rationale.

* Menu:

* PEP 218; 内置集合对象: PEP 218 内置集合对象.
* PEP 237; 统一长整数和整数: PEP 237 统一长整数和整数.
* PEP 289; 生成器表达式: PEP 289 生成器表达式.
* PEP 292; Simpler String Substitutions: PEP 292 Simpler String Substitutions.
* PEP 318; Decorators for Functions and Methods: PEP 318 Decorators for Functions and Methods.
* PEP 322; 反向迭代: PEP 322 反向迭代.
* PEP 324; 新的子进程模块: PEP 324 新的子进程模块.
* PEP 327; 十进制数据类型: PEP 327 十进制数据类型.
* PEP 328; 多行导入: PEP 328 多行导入.
* PEP 331; Locale-Independent Float/String Conversions: PEP 331 Locale-Independent Float/String Conversions.
* 其他语言特性修改: 其他语言特性修改<12>.
* 新增，改进和弃用的模块: 新增，改进和弃用的模块<3>.
* 构建和 C API 的改变: 构建和 C API 的改变<11>.
* 移植到 Python 2.4: 移植到 Python 2 4.
* 致谢: 致谢<4>.


File: python.info,  Node: PEP 218 内置集合对象,  Next: PEP 237 统一长整数和整数,  Up: Python 2 4 有什么新变化

1.13.1 PEP 218: 内置集合对象
----------------------------

Python 2.3 introduced the ‘sets’ module.  C implementations of set data
types have now been added to the Python core as two new built-in types,
‘set(iterable)’ and ‘frozenset(iterable)’.  They provide high speed
operations for membership testing, for eliminating duplicates from
sequences, and for mathematical operations like unions, intersections,
differences, and symmetric differences.

     >>> a = set('abracadabra')              # form a set from a string
     >>> 'z' in a                            # fast membership testing
     False
     >>> a                                   # unique letters in a
     set(['a', 'r', 'b', 'c', 'd'])
     >>> ''.join(a)                          # convert back into a string
     'arbcd'

     >>> b = set('alacazam')                 # form a second set
     >>> a - b                               # letters in a but not in b
     set(['r', 'd', 'b'])
     >>> a | b                               # letters in either a or b
     set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
     >>> a & b                               # letters in both a and b
     set(['a', 'c'])
     >>> a ^ b                               # letters in a or b but not both
     set(['r', 'd', 'b', 'm', 'z', 'l'])

     >>> a.add('z')                          # add a new element
     >>> a.update('wxy')                     # add multiple new elements
     >>> a
     set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
     >>> a.remove('x')                       # take one element out
     >>> a
     set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])

The *note frozenset(): bf6. type is an immutable version of *note set():
b77.  Since it is immutable and hashable, it may be used as a dictionary
key or as a member of another set.

The ‘sets’ module remains in the standard library, and may be useful if
you wish to subclass the ‘Set’ or ‘ImmutableSet’ classes.  There are
currently no plans to deprecate the module.

参见
....

PEP 218(1) - 添加内置Set对象类型

     最初由 Greg Wilson 提出，由 Raymond Hettinger 最终实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0218


File: python.info,  Node: PEP 237 统一长整数和整数,  Next: PEP 289 生成器表达式,  Prev: PEP 218 内置集合对象,  Up: Python 2 4 有什么新变化

1.13.2 PEP 237: 统一长整数和整数
--------------------------------

The lengthy transition process for this PEP, begun in Python 2.2, takes
another step forward in Python 2.4.  In 2.3, certain integer operations
that would behave differently after int/long unification triggered *note
FutureWarning: 32e. warnings and returned values limited to 32 or 64
bits (depending on your platform).  In 2.4, these expressions no longer
produce a warning and instead produce a different result that’s usually
a long integer.

The problematic expressions are primarily left shifts and lengthy
hexadecimal and octal constants.  For example, ‘2 << 32’ results in a
warning in 2.3, evaluating to 0 on 32-bit platforms.  In Python 2.4,
this expression now returns the correct answer, 8589934592.

参见
....

PEP 237(1) - 统一长整数和整数

     原始PEP由 Moshe Zadka 和 GvR 撰写，2.4 的变更由 Kalle Svensson 实现
     。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0237


File: python.info,  Node: PEP 289 生成器表达式,  Next: PEP 292 Simpler String Substitutions,  Prev: PEP 237 统一长整数和整数,  Up: Python 2 4 有什么新变化

1.13.3 PEP 289: 生成器表达式
----------------------------

The iterator feature introduced in Python 2.2 and the *note itertools:
a4. module make it easier to write programs that loop through large data
sets without having the entire data set in memory at one time.  List
comprehensions don’t fit into this picture very well because they
produce a Python list object containing all of the items.  This
unavoidably pulls all of the objects into memory, which can be a problem
if your data set is very large.  When trying to write a
functionally-styled program, it would be natural to write something
like:

     links = [link for link in get_all_links() if not link.followed]
     for link in links:
         ...

代替：

     for link in get_all_links():
         if link.followed:
             continue
         ...

The first form is more concise and perhaps more readable, but if you’re
dealing with a large number of link objects you’d have to write the
second form to avoid having all link objects in memory at the same time.

Generator expressions work similarly to list comprehensions but don’t
materialize the entire list; instead they create a generator that will
return elements one by one.  The above example could be written as:

     links = (link for link in get_all_links() if not link.followed)
     for link in links:
         ...

Generator expressions always have to be written inside parentheses, as
in the above example.  The parentheses signalling a function call also
count, so if you want to create an iterator that will be immediately
passed to a function you could write:

     print sum(obj.count for obj in list_all_objects())

Generator expressions differ from list comprehensions in various small
ways.  Most notably, the loop variable (`obj' in the above example) is
not accessible outside of the generator expression.  List comprehensions
leave the variable assigned to its last value; future versions of Python
will change this, making list comprehensions match generator expressions
in this respect.

参见
....

PEP 289(1) - 生成器表达式

     Proposed by Raymond Hettinger and implemented by Jiwon Seo with
     early efforts steered by Hye-Shik Chang.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0289


File: python.info,  Node: PEP 292 Simpler String Substitutions,  Next: PEP 318 Decorators for Functions and Methods,  Prev: PEP 289 生成器表达式,  Up: Python 2 4 有什么新变化

1.13.4 PEP 292: Simpler String Substitutions
--------------------------------------------

Some new classes in the standard library provide an alternative
mechanism for substituting variables into strings; this style of
substitution may be better for applications where untrained users need
to edit templates.

The usual way of substituting variables by name is the ‘%’ operator:

     >>> '%(page)i: %(title)s' % {'page':2, 'title': 'The Best of Times'}
     '2: The Best of Times'

When writing the template string, it can be easy to forget the ‘i’ or
‘s’ after the closing parenthesis.  This isn’t a big problem if the
template is in a Python module, because you run the code, get an
"Unsupported format character" *note ValueError: 1fc, and fix the
problem.  However, consider an application such as Mailman where
template strings or translations are being edited by users who aren’t
aware of the Python language.  The format string’s syntax is complicated
to explain to such users, and if they make a mistake, it’s difficult to
provide helpful feedback to them.

PEP 292 adds a ‘Template’ class to the *note string: f7. module that
uses ‘$’ to indicate a substitution:

     >>> import string
     >>> t = string.Template('$page: $title')
     >>> t.substitute({'page':2, 'title': 'The Best of Times'})
     '2: The Best of Times'

If a key is missing from the dictionary, the ‘substitute()’ method will
raise a *note KeyError: 2c8.  There’s also a ‘safe_substitute()’ method
that ignores missing keys:

     >>> t = string.Template('$page: $title')
     >>> t.safe_substitute({'page':3})
     '3: $title'

参见
....

PEP 292(1) - Simpler String Substitutions

     由 Barry Warsaw 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0292


File: python.info,  Node: PEP 318 Decorators for Functions and Methods,  Next: PEP 322 反向迭代,  Prev: PEP 292 Simpler String Substitutions,  Up: Python 2 4 有什么新变化

1.13.5 PEP 318: Decorators for Functions and Methods
----------------------------------------------------

Python 2.2 extended Python’s object model by adding static methods and
class methods, but it didn’t extend Python’s syntax to provide any new
way of defining static or class methods.  Instead, you had to write a
*note def: dc6. statement in the usual way, and pass the resulting
method to a *note staticmethod(): 1da. or *note classmethod(): 1d9.
function that would wrap up the function as a method of the new type.
Your code would look like this:

     class C:
        def meth (cls):
            ...

        meth = classmethod(meth)   # Rebind name to wrapped-up class method

If the method was very long, it would be easy to miss or forget the
*note classmethod(): 1d9. invocation after the function body.

The intention was always to add some syntax to make such definitions
more readable, but at the time of 2.2’s release a good syntax was not
obvious.  Today a good syntax `still' isn’t obvious but users are asking
for easier access to the feature; a new syntactic feature has been added
to meet this need.

The new feature is called "function decorators".  The name comes from
the idea that *note classmethod(): 1d9, *note staticmethod(): 1da, and
friends are storing additional information on a function object; they’re
`decorating' functions with more details.

The notation borrows from Java and uses the ‘'@'’ character as an
indicator.  Using the new syntax, the example above would be written:

     class C:

        @classmethod
        def meth (cls):
            ...

The ‘@classmethod’ is shorthand for the ‘meth=classmethod(meth)’
assignment.  More generally, if you have the following:

     @A
     @B
     @C
     def f ():
         ...

It’s equivalent to the following pre-decorator code:

     def f(): ...
     f = A(B(C(f)))

Decorators must come on the line before a function definition, one
decorator per line, and can’t be on the same line as the def statement,
meaning that ‘@A def f(): ...’ is illegal.  You can only decorate
function definitions, either at the module level or inside a class; you
can’t decorate class definitions.

A decorator is just a function that takes the function to be decorated
as an argument and returns either the same function or some new object.
The return value of the decorator need not be callable (though it
typically is), unless further decorators will be applied to the result.
It’s easy to write your own decorators.  The following simple example
just sets an attribute on the function object:

     >>> def deco(func):
     ...    func.attr = 'decorated'
     ...    return func
     ...
     >>> @deco
     ... def f(): pass
     ...
     >>> f
     <function f at 0x402ef0d4>
     >>> f.attr
     'decorated'
     >>>

As a slightly more realistic example, the following decorator checks
that the supplied argument is an integer:

     def require_int (func):
         def wrapper (arg):
             assert isinstance(arg, int)
             return func(arg)

         return wrapper

     @require_int
     def p1 (arg):
         print arg

     @require_int
     def p2(arg):
         print arg*2

An example in PEP 318(1) contains a fancier version of this idea that
lets you both specify the required type and check the returned type.

Decorator functions can take arguments.  If arguments are supplied, your
decorator function is called with only those arguments and must return a
new decorator function; this function must take a single function and
return a function, as previously described.  In other words, ‘@A @B
@C(args)’ becomes:

     def f(): ...
     _deco = C(args)
     f = A(B(_deco(f)))

Getting this right can be slightly brain-bending, but it’s not too
difficult.

A small related change makes the ‘func_name’ attribute of functions
writable.  This attribute is used to display function names in
tracebacks, so decorators should change the name of any new function
that’s constructed and returned.

参见
....

PEP 318(2) - Decorators for Functions, Methods and Classes

     Written by Kevin D. Smith, Jim Jewett, and Skip Montanaro.  Several
     people wrote patches implementing function decorators, but the one
     that was actually checked in was patch #979728, written by Mark
     Russell.

‘https://wiki.python.org/moin/PythonDecoratorLibrary’

     该Wiki页面包含几个装饰器示例。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0318

   (2) https://www.python.org/dev/peps/pep-0318


File: python.info,  Node: PEP 322 反向迭代,  Next: PEP 324 新的子进程模块,  Prev: PEP 318 Decorators for Functions and Methods,  Up: Python 2 4 有什么新变化

1.13.6 PEP 322: 反向迭代
------------------------

A new built-in function, ‘reversed(seq)’, takes a sequence and returns
an iterator that loops over the elements of the sequence in reverse
order.

     >>> for i in reversed(xrange(1,4)):
     ...    print i
     ...
     3
     2
     1

Compared to extended slicing, such as ‘range(1,4)[::-1]’, *note
reversed(): 18f. is easier to read, runs faster, and uses substantially
less memory.

Note that *note reversed(): 18f. only accepts sequences, not arbitrary
iterators.  If you want to reverse an iterator, first convert it to a
list with *note list(): 263.

     >>> input = open('/etc/passwd', 'r')
     >>> for line in reversed(list(input)):
     ...   print line
     ...
     root:*:0:0:System Administrator:/var/root:/bin/tcsh
       ...

参见
....

PEP 322(1) - 反向迭代

     由 Raymond Hettinger 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0322


File: python.info,  Node: PEP 324 新的子进程模块,  Next: PEP 327 十进制数据类型,  Prev: PEP 322 反向迭代,  Up: Python 2 4 有什么新变化

1.13.7 PEP 324: 新的子进程模块
------------------------------

The standard library provides a number of ways to execute a subprocess,
offering different features and different levels of complexity.
‘os.system(command)’ is easy to use, but slow (it runs a shell process
which executes the command) and dangerous (you have to be careful about
escaping the shell’s metacharacters).  The ‘popen2’ module offers
classes that can capture standard output and standard error from the
subprocess, but the naming is confusing.  The *note subprocess: fa.
module cleans this up, providing a unified interface that offers all the
features you might need.

Instead of ‘popen2’’s collection of classes, *note subprocess: fa.
contains a single class called ‘Popen’ whose constructor supports a
number of different keyword arguments.

     class Popen(args, bufsize=0, executable=None,
                 stdin=None, stdout=None, stderr=None,
                 preexec_fn=None, close_fds=False, shell=False,
                 cwd=None, env=None, universal_newlines=False,
                 startupinfo=None, creationflags=0):

`args' is commonly a sequence of strings that will be the arguments to
the program executed as the subprocess.  (If the `shell' argument is
true, `args' can be a string which will then be passed on to the shell
for interpretation, just as *note os.system(): dc9. does.)

`stdin', `stdout', and `stderr' specify what the subprocess’s input,
output, and error streams will be.  You can provide a file object or a
file descriptor, or you can use the constant ‘subprocess.PIPE’ to create
a pipe between the subprocess and the parent.

The constructor has a number of handy options:

   * `close_fds' requests that all file descriptors be closed before
     running the subprocess.

   * `cwd' specifies the working directory in which the subprocess will
     be executed (defaulting to whatever the parent’s working directory
     is).

   * `env' is a dictionary specifying environment variables.

   * `preexec_fn' is a function that gets called before the child is
     started.

   * `universal_newlines' opens the child’s input and output using
     Python’s *note universal newlines: 5fd. feature.

Once you’ve created the ‘Popen’ instance, you can call its ‘wait()’
method to pause until the subprocess has exited, ‘poll()’ to check if
it’s exited without pausing, or ‘communicate(data)’ to send the string
`data' to the subprocess’s standard input.  ‘communicate(data)’ then
reads any data that the subprocess has sent to its standard output or
standard error, returning a tuple ‘(stdout_data, stderr_data)’.

‘call()’ is a shortcut that passes its arguments along to the ‘Popen’
constructor, waits for the command to complete, and returns the status
code of the subprocess.  It can serve as a safer analog to *note
os.system(): dc9.:

     sts = subprocess.call(['dpkg', '-i', '/tmp/new-package.deb'])
     if sts == 0:
         # Success
         ...
     else:
         # dpkg returned an error
         ...

The command is invoked without use of the shell.  If you really do want
to use the shell, you can add ‘shell=True’ as a keyword argument and
provide a string instead of a sequence:

     sts = subprocess.call('dpkg -i /tmp/new-package.deb', shell=True)

The PEP takes various examples of shell and Python code and shows how
they’d be translated into Python code that uses *note subprocess: fa.
Reading this section of the PEP is highly recommended.

参见
....

PEP 324(1) - 子进程 - 新的进程模块

     由 Peter Åstrand 在 Fredrik Lundh 等人的协助下撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0324


File: python.info,  Node: PEP 327 十进制数据类型,  Next: PEP 328 多行导入,  Prev: PEP 324 新的子进程模块,  Up: Python 2 4 有什么新变化

1.13.8 PEP 327: 十进制数据类型
------------------------------

Python has always supported floating-point (FP) numbers, based on the
underlying C ‘double’ type, as a data type.  However, while most
programming languages provide a floating-point type, many people (even
programmers) are unaware that floating-point numbers don’t represent
certain decimal fractions accurately.  The new ‘Decimal’ type can
represent these fractions accurately, up to a user-specified precision
limit.

* Menu:

* 为什么需要十进制？::
* Decimal 类型::
* Context 类型::


File: python.info,  Node: 为什么需要十进制？,  Next: Decimal 类型,  Up: PEP 327 十进制数据类型

1.13.8.1 为什么需要十进制？
...........................

The limitations arise from the representation used for floating-point
numbers.  FP numbers are made up of three components:

   * The sign, which is positive or negative.

   * The mantissa, which is a single-digit binary number followed by a
     fractional part.  For example, ‘1.01’ in base-2 notation is ‘1 +
     0/2 + 1/4’, or 1.25 in decimal notation.

   * The exponent, which tells where the decimal point is located in the
     number represented.

For example, the number 1.25 has positive sign, a mantissa value of 1.01
(in binary), and an exponent of 0 (the decimal point doesn’t need to be
shifted).  The number 5 has the same sign and mantissa, but the exponent
is 2 because the mantissa is multiplied by 4 (2 to the power of the
exponent 2); 1.25 * 4 equals 5.

Modern systems usually provide floating-point support that conforms to a
standard called IEEE 754.  C’s ‘double’ type is usually implemented as a
64-bit IEEE 754 number, which uses 52 bits of space for the mantissa.
This means that numbers can only be specified to 52 bits of precision.
If you’re trying to represent numbers whose expansion repeats endlessly,
the expansion is cut off after 52 bits.  Unfortunately, most software
needs to produce output in base 10, and common fractions in base 10 are
often repeating decimals in binary.  For example, 1.1 decimal is binary
‘1.0001100110011 ...’; .1 = 1/16 + 1/32 + 1/256 plus an infinite number
of additional terms.  IEEE 754 has to chop off that infinitely repeated
decimal after 52 digits, so the representation is slightly inaccurate.

Sometimes you can see this inaccuracy when the number is printed:

     >>> 1.1
     1.1000000000000001

The inaccuracy isn’t always visible when you print the number because
the FP-to-decimal-string conversion is provided by the C library, and
most C libraries try to produce sensible output.  Even if it’s not
displayed, however, the inaccuracy is still there and subsequent
operations can magnify the error.

For many applications this doesn’t matter.  If I’m plotting points and
displaying them on my monitor, the difference between 1.1 and
1.1000000000000001 is too small to be visible.  Reports often limit
output to a certain number of decimal places, and if you round the
number to two or three or even eight decimal places, the error is never
apparent.  However, for applications where it does matter, it’s a lot of
work to implement your own custom arithmetic routines.

因此，创建了 ‘Decimal’ 类型。


File: python.info,  Node: Decimal 类型,  Next: Context 类型,  Prev: 为什么需要十进制？,  Up: PEP 327 十进制数据类型

1.13.8.2 ‘Decimal’ 类型
.......................

A new module, *note decimal: 36, was added to Python’s standard library.
It contains two classes, ‘Decimal’ and ‘Context’.  ‘Decimal’ instances
represent numbers, and ‘Context’ instances are used to wrap up various
settings such as the precision and default rounding mode.

‘Decimal’ instances are immutable, like regular Python integers and FP
numbers; once it’s been created, you can’t change the value an instance
represents.  ‘Decimal’ instances can be created from integers or
strings:

     >>> import decimal
     >>> decimal.Decimal(1972)
     Decimal("1972")
     >>> decimal.Decimal("1.1")
     Decimal("1.1")

You can also provide tuples containing the sign, the mantissa
represented as a tuple of decimal digits, and the exponent:

     >>> decimal.Decimal((1, (1, 4, 7, 5), -2))
     Decimal("-14.75")

Cautionary note: the sign bit is a Boolean value, so 0 is positive and 1
is negative.

Converting from floating-point numbers poses a bit of a problem: should
the FP number representing 1.1 turn into the decimal number for exactly
1.1, or for 1.1 plus whatever inaccuracies are introduced?  The decision
was to dodge the issue and leave such a conversion out of the API.
Instead, you should convert the floating-point number into a string
using the desired precision and pass the string to the ‘Decimal’
constructor:

     >>> f = 1.1
     >>> decimal.Decimal(str(f))
     Decimal("1.1")
     >>> decimal.Decimal('%.12f' % f)
     Decimal("1.100000000000")

Once you have ‘Decimal’ instances, you can perform the usual
mathematical operations on them.  One limitation: exponentiation
requires an integer exponent:

     >>> a = decimal.Decimal('35.72')
     >>> b = decimal.Decimal('1.73')
     >>> a+b
     Decimal("37.45")
     >>> a-b
     Decimal("33.99")
     >>> a*b
     Decimal("61.7956")
     >>> a/b
     Decimal("20.64739884393063583815028902")
     >>> a ** 2
     Decimal("1275.9184")
     >>> a**b
     Traceback (most recent call last):
       ...
     decimal.InvalidOperation: x ** (non-integer)

You can combine ‘Decimal’ instances with integers, but not with
floating-point numbers:

     >>> a + 4
     Decimal("39.72")
     >>> a + 4.5
     Traceback (most recent call last):
       ...
     TypeError: You can interact Decimal only with int, long or Decimal data types.
     >>>

‘Decimal’ numbers can be used with the *note math: b2. and *note cmath:
19. modules, but note that they’ll be immediately converted to
floating-point numbers before the operation is performed, resulting in a
possible loss of precision and accuracy.  You’ll also get back a regular
floating-point number and not a ‘Decimal’.

     >>> import math, cmath
     >>> d = decimal.Decimal('123456789012.345')
     >>> math.sqrt(d)
     351364.18288201344
     >>> cmath.sqrt(-d)
     351364.18288201344j

‘Decimal’ instances have a ‘sqrt()’ method that returns a ‘Decimal’, but
if you need other things such as trigonometric functions you’ll have to
implement them.

     >>> d.sqrt()
     Decimal("351364.1828820134592177245001")


File: python.info,  Node: Context 类型,  Prev: Decimal 类型,  Up: PEP 327 十进制数据类型

1.13.8.3 ‘Context’ 类型
.......................

Instances of the ‘Context’ class encapsulate several settings for
decimal operations:

   * ‘prec’ is the precision, the number of decimal places.

   * ‘rounding’ specifies the rounding mode.  The *note decimal: 36.
     module has constants for the various possibilities: ‘ROUND_DOWN’,
     ‘ROUND_CEILING’, ‘ROUND_HALF_EVEN’, and various others.

   * ‘traps’ is a dictionary specifying what happens on encountering
     certain error conditions: either an exception is raised or a value
     is returned.  Some examples of error conditions are division by
     zero, loss of precision, and overflow.

There’s a thread-local default context available by calling
‘getcontext()’; you can change the properties of this context to alter
the default precision, rounding, or trap handling.  The following
example shows the effect of changing the precision of the default
context:

     >>> decimal.getcontext().prec
     28
     >>> decimal.Decimal(1) / decimal.Decimal(7)
     Decimal("0.1428571428571428571428571429")
     >>> decimal.getcontext().prec = 9
     >>> decimal.Decimal(1) / decimal.Decimal(7)
     Decimal("0.142857143")

The default action for error conditions is selectable; the module can
either return a special value such as infinity or not-a-number, or
exceptions can be raised:

     >>> decimal.Decimal(1) / decimal.Decimal(0)
     Traceback (most recent call last):
       ...
     decimal.DivisionByZero: x / 0
     >>> decimal.getcontext().traps[decimal.DivisionByZero] = False
     >>> decimal.Decimal(1) / decimal.Decimal(0)
     Decimal("Infinity")
     >>>

The ‘Context’ instance also has various methods for formatting numbers
such as ‘to_eng_string()’ and ‘to_sci_string()’.

For more information, see the documentation for the *note decimal: 36.
module, which includes a quick-start tutorial and a reference.

参见
....

PEP 327(1) - 十进数据类型

     由 Facundo Batista 撰写，由Facundo Batista, Eric Price, Raymond
     Hettinger, Aahz 和 Tim Peters 实现。

‘http://www.lahey.com/float.htm’

     The article uses Fortran code to illustrate many of the problems
     that floating-point inaccuracy can cause.

‘http://speleotrove.com/decimal/’

     A description of a decimal-based representation.  This
     representation is being proposed as a standard, and underlies the
     new Python decimal type.  Much of this material was written by Mike
     Cowlishaw, designer of the Rexx language.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0327


File: python.info,  Node: PEP 328 多行导入,  Next: PEP 331 Locale-Independent Float/String Conversions,  Prev: PEP 327 十进制数据类型,  Up: Python 2 4 有什么新变化

1.13.9 PEP 328: 多行导入
------------------------

One language change is a small syntactic tweak aimed at making it easier
to import many names from a module.  In a ‘from module import names’
statement, `names' is a sequence of names separated by commas.  If the
sequence is very long, you can either write multiple imports from the
same module, or you can use backslashes to escape the line endings like
this:

     from SimpleXMLRPCServer import SimpleXMLRPCServer,\
                 SimpleXMLRPCRequestHandler,\
                 CGIXMLRPCRequestHandler,\
                 resolve_dotted_attribute

The syntactic change in Python 2.4 simply allows putting the names
within parentheses.  Python ignores newlines within a parenthesized
expression, so the backslashes are no longer needed:

     from SimpleXMLRPCServer import (SimpleXMLRPCServer,
                                     SimpleXMLRPCRequestHandler,
                                     CGIXMLRPCRequestHandler,
                                     resolve_dotted_attribute)

The PEP also proposes that all *note import: c25. statements be absolute
imports, with a leading ‘.’ character to indicate a relative import.
This part of the PEP was not implemented for Python 2.4, but was
completed for Python 2.5.

参见
....

PEP 328(1) - 导入：多行和绝对/相对导入

     由 Aahz 撰写，多行导入由 Dima Dorfman 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0328


File: python.info,  Node: PEP 331 Locale-Independent Float/String Conversions,  Next: 其他语言特性修改<12>,  Prev: PEP 328 多行导入,  Up: Python 2 4 有什么新变化

1.13.10 PEP 331: Locale-Independent Float/String Conversions
------------------------------------------------------------

The *note locale: aa. modules lets Python software select various
conversions and display conventions that are localized to a particular
country or language.  However, the module was careful to not change the
numeric locale because various functions in Python’s implementation
required that the numeric locale remain set to the ‘'C'’ locale.  Often
this was because the code was using the C library’s ‘atof()’ function.

Not setting the numeric locale caused trouble for extensions that used
third-party C libraries, however, because they wouldn’t have the correct
locale set.  The motivating example was GTK+, whose user interface
widgets weren’t displaying numbers in the current locale.

The solution described in the PEP is to add three new functions to the
Python API that perform ASCII-only conversions, ignoring the locale
setting:

   * ‘PyOS_ascii_strtod(str, ptr)’ and ‘PyOS_ascii_atof(str, ptr)’ both
     convert a string to a C ‘double’.

   * ‘PyOS_ascii_formatd(buffer, buf_len, format, d)’ converts a
     ‘double’ to an ASCII string.

The code for these functions came from the GLib library
(‘https://developer.gnome.org/glib/stable/’), whose developers kindly
relicensed the relevant functions and donated them to the Python
Software Foundation.  The *note locale: aa. module can now change the
numeric locale, letting extensions such as GTK+ produce the correct
results.

参见
....

PEP 331(1) - Locale-Independent Float/String Conversions

     由Christian R. Reis撰写，由 Gustavo Carneiro 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0331


File: python.info,  Node: 其他语言特性修改<12>,  Next: 新增，改进和弃用的模块<3>,  Prev: PEP 331 Locale-Independent Float/String Conversions,  Up: Python 2 4 有什么新变化

1.13.11 其他语言特性修改
------------------------

Here are all of the changes that Python 2.4 makes to the core Python
language.

   * Decorators for functions and methods were added ( PEP 318(1)).

   * Built-in *note set(): b77. and *note frozenset(): bf6. types were
     added ( PEP 218(2)).  Other new built-ins include the
     ‘reversed(seq)’ function ( PEP 322(3)).

   * Generator expressions were added ( PEP 289(4)).

   * Certain numeric expressions no longer return values restricted to
     32 or 64 bits ( PEP 237(5)).

   * You can now put parentheses around the list of names in a ‘from
     module import names’ statement ( PEP 328(6)).

   * The *note dict.update(): dd1. method now accepts the same argument
     forms as the *note dict: 1b9. constructor.  This includes any
     mapping, any iterable of key/value pairs, and keyword arguments.
     (Contributed by Raymond Hettinger.)

   * The string methods ‘ljust()’, ‘rjust()’, and ‘center()’ now take an
     optional argument for specifying a fill character other than a
     space.  (Contributed by Raymond Hettinger.)

   * Strings also gained an ‘rsplit()’ method that works like the
     ‘split()’ method but splits from the end of the string.
     (Contributed by Sean Reifschneider.)

          >>> 'www.python.org'.split('.', 1)
          ['www', 'python.org']
          'www.python.org'.rsplit('.', 1)
          ['www.python', 'org']

   * Three keyword parameters, `cmp', `key', and `reverse', were added
     to the ‘sort()’ method of lists.  These parameters make some common
     usages of ‘sort()’ simpler.  All of these parameters are optional.

     For the `cmp' parameter, the value should be a comparison function
     that takes two parameters and returns -1, 0, or +1 depending on how
     the parameters compare.  This function will then be used to sort
     the list.  Previously this was the only parameter that could be
     provided to ‘sort()’.

     `key' should be a single-parameter function that takes a list
     element and returns a comparison key for the element.  The list is
     then sorted using the comparison keys.  The following example sorts
     a list case-insensitively:

          >>> L = ['A', 'b', 'c', 'D']
          >>> L.sort()                 # Case-sensitive sort
          >>> L
          ['A', 'D', 'b', 'c']
          >>> # Using 'key' parameter to sort list
          >>> L.sort(key=lambda x: x.lower())
          >>> L
          ['A', 'b', 'c', 'D']
          >>> # Old-fashioned way
          >>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
          >>> L
          ['A', 'b', 'c', 'D']

     The last example, which uses the `cmp' parameter, is the old way to
     perform a case-insensitive sort.  It works but is slower than using
     a `key' parameter.  Using `key' calls ‘lower()’ method once for
     each element in the list while using `cmp' will call it twice for
     each comparison, so using `key' saves on invocations of the
     ‘lower()’ method.

     For simple key functions and comparison functions, it is often
     possible to avoid a *note lambda: c37. expression by using an
     unbound method instead.  For example, the above case-insensitive
     sort is best written as:

          >>> L.sort(key=str.lower)
          >>> L
          ['A', 'b', 'c', 'D']

     Finally, the `reverse' parameter takes a Boolean value.  If the
     value is true, the list will be sorted into reverse order.  Instead
     of ‘L.sort(); L.reverse()’, you can now write
     ‘L.sort(reverse=True)’.

     The results of sorting are now guaranteed to be stable.  This means
     that two entries with equal keys will be returned in the same order
     as they were input.  For example, you can sort a list of people by
     name, and then sort the list by age, resulting in a list sorted by
     age where people with the same age are in name-sorted order.

     (All changes to ‘sort()’ contributed by Raymond Hettinger.)

   * There is a new built-in function ‘sorted(iterable)’ that works like
     the in-place *note list.sort(): 44d. method but can be used in
     expressions.  The differences are:

   * the input may be any iterable;

   * a newly formed copy is sorted, leaving the original intact; and

   * the expression returns the new sorted copy

          >>> L = [9,7,8,3,2,4,1,6,5]
          >>> [10+i for i in sorted(L)]       # usable in a list comprehension
          [11, 12, 13, 14, 15, 16, 17, 18, 19]
          >>> L                               # original is left unchanged
          [9,7,8,3,2,4,1,6,5]
          >>> sorted('Monty Python')          # any iterable may be an input
          [' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']

          >>> # List the contents of a dict sorted by key values
          >>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
          >>> for k, v in sorted(colormap.iteritems()):
          ...     print k, v
          ...
          black 4
          blue 2
          green 3
          red 1
          yellow 5

     （由 Raymond Hettinger 贡献。）

   * Integer operations will no longer trigger an ‘OverflowWarning’.
     The ‘OverflowWarning’ warning will disappear in Python 2.5.

   * The interpreter gained a new switch, *note -m: 340, that takes a
     name, searches for the corresponding module on ‘sys.path’, and runs
     the module as a script.  For example, you can now run the Python
     profiler with ‘python -m profile’.  (Contributed by Nick Coghlan.)

   * The ‘eval(expr, globals, locals)’ and ‘execfile(filename, globals,
     locals)’ functions and the ‘exec’ statement now accept any mapping
     type for the `locals' parameter.  Previously this had to be a
     regular Python dictionary.  (Contributed by Raymond Hettinger.)

   * The *note zip(): c3a. built-in function and ‘itertools.izip()’ now
     return an empty list if called with no arguments.  Previously they
     raised a *note TypeError: 193. exception.  This makes them more
     suitable for use with variable length argument lists:

          >>> def transpose(array):
          ...    return zip(*array)
          ...
          >>> transpose([(1,2,3), (4,5,6)])
          [(1, 4), (2, 5), (3, 6)]
          >>> transpose([])
          []

     （由 Raymond Hettinger 贡献。）

   * Encountering a failure while importing a module no longer leaves a
     partially-initialized module object in ‘sys.modules’.  The
     incomplete module object left behind would fool further imports of
     the same module into succeeding, leading to confusing errors.
     (Fixed by Tim Peters.)

   * *note None: 158. is now a constant; code that binds a new value to
     the name ‘None’ is now a syntax error.  (Contributed by Raymond
     Hettinger.)

* Menu:

* 性能优化: 性能优化<11>.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0318

   (2) https://www.python.org/dev/peps/pep-0218

   (3) https://www.python.org/dev/peps/pep-0322

   (4) https://www.python.org/dev/peps/pep-0289

   (5) https://www.python.org/dev/peps/pep-0237

   (6) https://www.python.org/dev/peps/pep-0328


File: python.info,  Node: 性能优化<11>,  Up: 其他语言特性修改<12>

1.13.11.1 性能优化
..................

   * The inner loops for list and tuple slicing were optimized and now
     run about one-third faster.  The inner loops for dictionaries were
     also optimized, resulting in performance boosts for ‘keys()’,
     ‘values()’, ‘items()’, ‘iterkeys()’, ‘itervalues()’, and
     ‘iteritems()’.  (Contributed by Raymond Hettinger.)

   * The machinery for growing and shrinking lists was optimized for
     speed and for space efficiency.  Appending and popping from lists
     now runs faster due to more efficient code paths and less frequent
     use of the underlying system ‘realloc()’.  List comprehensions also
     benefit.  ‘list.extend()’ was also optimized and no longer converts
     its argument into a temporary list before extending the base list.
     (Contributed by Raymond Hettinger.)

   * *note list(): 263, *note tuple(): 486, *note map(): c35, *note
     filter(): c36, and *note zip(): c3a. now run several times faster
     with non-sequence arguments that supply a *note __len__(): dd3.
     method.  (Contributed by Raymond Hettinger.)

   * The methods ‘list.__getitem__()’, ‘dict.__getitem__()’, and
     ‘dict.__contains__()’ are now implemented as ‘method_descriptor’
     objects rather than ‘wrapper_descriptor’ objects.  This form of
     access doubles their performance and makes them more suitable for
     use as arguments to functionals: ‘map(mydict.__getitem__,
     keylist)’.  (Contributed by Raymond Hettinger.)

   * Added a new opcode, ‘LIST_APPEND’, that simplifies the generated
     bytecode for list comprehensions and speeds them up by about a
     third.  (Contributed by Raymond Hettinger.)

   * The peephole bytecode optimizer has been improved to produce
     shorter, faster bytecode; remarkably, the resulting bytecode is
     more readable.  (Enhanced by Raymond Hettinger.)

   * String concatenations in statements of the form ‘s = s + "abc"’ and
     ‘s += "abc"’ are now performed more efficiently in certain
     circumstances.  This optimization won’t be present in other Python
     implementations such as Jython, so you shouldn’t rely on it; using
     the ‘join()’ method of strings is still recommended when you want
     to efficiently glue a large number of strings together.
     (Contributed by Armin Rigo.)

The net result of the 2.4 optimizations is that Python 2.4 runs the
pystone benchmark around 5% faster than Python 2.3 and 35% faster than
Python 2.2.  (pystone is not a particularly good benchmark, but it’s the
most commonly used measurement of Python’s performance.  Your own
applications may show greater or smaller benefits from Python 2.4.)


File: python.info,  Node: 新增，改进和弃用的模块<3>,  Next: 构建和 C API 的改变<11>,  Prev: 其他语言特性修改<12>,  Up: Python 2 4 有什么新变化

1.13.12 新增，改进和弃用的模块
------------------------------

As usual, Python’s standard library received a number of enhancements
and bug fixes.  Here’s a partial list of the most notable changes,
sorted alphabetically by module name.  Consult the ‘Misc/NEWS’ file in
the source tree for a more complete list of changes, or look through the
CVS logs for all the details.

   * The *note asyncore: b. module’s ‘loop()’ function now has a `count'
     parameter that lets you perform a limited number of passes through
     the polling loop.  The default is still to loop forever.

   * The *note base64: e. module now has more complete RFC 3548(1)
     support for Base64, Base32, and Base16 encoding and decoding,
     including optional case folding and optional alternative alphabets.
     (Contributed by Barry Warsaw.)

   * The *note bisect: 12. module now has an underlying C implementation
     for improved performance.  (Contributed by Dmitry Vasiliev.)

   * 由 Hye-Shik Chang 维护的东亚编解码器的 CJKCodecs 集合已集成到 2.4 中
     。新的编码为：

   * 汉语（大陆）: gb2312, gbk, gb18030, big5hkscs, hz

   * 汉语（台湾）: big5, cp950

   * 
     日语: cp932, euc-jis-2004, euc-jp, euc-jisx0213, iso-2022-jp,

          iso-2022-jp-1, iso-2022-jp-2, iso-2022-jp-3, iso-2022-jp-ext,
          iso-2022-jp-2004, shift-jis, shift-jisx0213, shift-jis-2004

   * 韩语: cp949, euc-kr, johab, iso-2022-kr

   * 添加了其他一些新的编码：HP Roman8, ISO_8859-11, ISO_8859-16,
     PCTP-154 和 TIS-620

   * The UTF-8 and UTF-16 codecs now cope better with receiving partial
     input.  Previously the ‘StreamReader’ class would try to read more
     data, making it impossible to resume decoding from the stream.  The
     ‘read()’ method will now return as much data as it can and future
     calls will resume decoding where previous ones left off.
     (Implemented by Walter Dörwald.)

   * There is a new *note collections: 1e. module for various
     specialized collection datatypes.  Currently it contains just one
     type, ‘deque’, a double-ended queue that supports efficiently
     adding and removing elements from either end:

          >>> from collections import deque
          >>> d = deque('ghi')        # make a new deque with three items
          >>> d.append('j')           # add a new entry to the right side
          >>> d.appendleft('f')       # add a new entry to the left side
          >>> d                       # show the representation of the deque
          deque(['f', 'g', 'h', 'i', 'j'])
          >>> d.pop()                 # return and remove the rightmost item
          'j'
          >>> d.popleft()             # return and remove the leftmost item
          'f'
          >>> list(d)                 # list the contents of the deque
          ['g', 'h', 'i']
          >>> 'h' in d                # search the deque
          True

     Several modules, such as the ‘Queue’ and *note threading: 10a.
     modules, now take advantage of *note collections.deque: 539. for
     improved performance.  (Contributed by Raymond Hettinger.)

   * The ‘ConfigParser’ classes have been enhanced slightly.  The
     ‘read()’ method now returns a list of the files that were
     successfully parsed, and the *note set(): b77. method raises *note
     TypeError: 193. if passed a `value' argument that isn’t a string.
     (Contributed by John Belmonte and David Goodger.)

   * The *note curses: 2c. module now supports the ncurses extension
     ‘use_default_colors()’.  On platforms where the terminal supports
     transparency, this makes it possible to use a transparent
     background.  (Contributed by Jörg Lehmann.)

   * The *note difflib: 37. module now includes an ‘HtmlDiff’ class that
     creates an HTML table showing a side by side comparison of two
     versions of a text.  (Contributed by Dan Gass.)

   * The *note email: 69. package was updated to version 3.0, which
     dropped various deprecated APIs and removes support for Python
     versions earlier than 2.3.  The 3.0 version of the package uses a
     new incremental parser for MIME messages, available in the
     ‘email.FeedParser’ module.  The new parser doesn’t require reading
     the entire message into memory, and doesn’t raise exceptions if a
     message is malformed; instead it records any problems in the
     ‘defect’ attribute of the message.  (Developed by Anthony Baxter,
     Barry Warsaw, Thomas Wouters, and others.)

   * The *note heapq: 8e. module has been converted to C. The resulting
     tenfold improvement in speed makes the module suitable for handling
     high volumes of data.  In addition, the module has two new
     functions ‘nlargest()’ and ‘nsmallest()’ that use heaps to find the
     N largest or smallest values in a dataset without the expense of a
     full sort.  (Contributed by Raymond Hettinger.)

   * The ‘httplib’ module now contains constants for HTTP status codes
     defined in various HTTP-related RFC documents.  Constants have
     names such as ‘OK’, ‘CREATED’, ‘CONTINUE’, and ‘MOVED_PERMANENTLY’;
     use pydoc to get a full list.  (Contributed by Andrew Eland.)

   * The *note imaplib: 98. module now supports IMAP’s THREAD command
     (contributed by Yves Dionne) and new ‘deleteacl()’ and ‘myrights()’
     methods (contributed by Arnaud Mazin).

   * The *note itertools: a4. module gained a ‘groupby(iterable[,
     *func*])’ function.  `iterable' is something that can be iterated
     over to return a stream of elements, and the optional `func'
     parameter is a function that takes an element and returns a key
     value; if omitted, the key is simply the element itself.
     ‘groupby()’ then groups the elements into subsequences which have
     matching values of the key, and returns a series of 2-tuples
     containing the key value and an iterator over the subsequence.

     Here’s an example to make this clearer.  The `key' function simply
     returns whether a number is even or odd, so the result of
     ‘groupby()’ is to return consecutive runs of odd or even numbers.

          >>> import itertools
          >>> L = [2, 4, 6, 7, 8, 9, 11, 12, 14]
          >>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
          ...    print key_val, list(it)
          ...
          0 [2, 4, 6]
          1 [7]
          0 [8]
          1 [9, 11]
          0 [12, 14]
          >>>

     ‘groupby()’ is typically used with sorted input.  The logic for
     ‘groupby()’ is similar to the Unix ‘uniq’ filter which makes it
     handy for eliminating, counting, or identifying duplicate elements:

          >>> word = 'abracadabra'
          >>> letters = sorted(word)   # Turn string into a sorted list of letters
          >>> letters
          ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
          >>> for k, g in itertools.groupby(letters):
          ...    print k, list(g)
          ...
          a ['a', 'a', 'a', 'a', 'a']
          b ['b', 'b']
          c ['c']
          d ['d']
          r ['r', 'r']
          >>> # List unique letters
          >>> [k for k, g in groupby(letters)]
          ['a', 'b', 'c', 'd', 'r']
          >>> # Count letter occurrences
          >>> [(k, len(list(g))) for k, g in groupby(letters)]
          [('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]

     （由 Hye-Shik Chang 贡献。）

   * *note itertools: a4. also gained a function named ‘tee(iterator,
     N)’ that returns `N' independent iterators that replicate
     `iterator'.  If `N' is omitted, the default is 2.

          >>> L = [1,2,3]
          >>> i1, i2 = itertools.tee(L)
          >>> i1,i2
          (<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
          >>> list(i1)               # Run the first iterator to exhaustion
          [1, 2, 3]
          >>> list(i2)               # Run the second iterator to exhaustion
          [1, 2, 3]

     Note that ‘tee()’ has to keep copies of the values returned by the
     iterator; in the worst case, it may need to keep all of them.  This
     should therefore be used carefully if the leading iterator can run
     far ahead of the trailing iterator in a long stream of inputs.  If
     the separation is large, then you might as well use *note list():
     263. instead.  When the iterators track closely with one another,
     ‘tee()’ is ideal.  Possible applications include bookmarking,
     windowing, or lookahead iterators.  (Contributed by Raymond
     Hettinger.)

   * A number of functions were added to the *note locale: aa. module,
     such as ‘bind_textdomain_codeset()’ to specify a particular
     encoding and a family of ‘l*gettext()’ functions that return
     messages in the chosen encoding.  (Contributed by Gustavo
     Niemeyer.)

   * Some keyword arguments were added to the *note logging: ab.
     package’s ‘basicConfig()’ function to simplify log configuration.
     The default behavior is to log messages to standard error, but
     various keyword arguments can be specified to log to a particular
     file, change the logging format, or set the logging level.  For
     example:

          import logging
          logging.basicConfig(filename='/var/log/application.log',
              level=0,  # Log all messages
              format='%(levelname):%(process):%(thread):%(message)')

     Other additions to the *note logging: ab. package include a
     ‘log(level, msg)’ convenience method, as well as a
     ‘TimedRotatingFileHandler’ class that rotates its log files at a
     timed interval.  The module already had ‘RotatingFileHandler’,
     which rotated logs once the file exceeded a certain size.  Both
     classes derive from a new ‘BaseRotatingHandler’ class that can be
     used to implement other rotating handlers.

     （更改由 Vinay Sajip 实现。）

   * The *note marshal: b1. module now shares interned strings on
     unpacking a data structure.  This may shrink the size of certain
     pickle strings, but the primary effect is to make ‘.pyc’ files
     significantly smaller.  (Contributed by Martin von Löwis.)

   * The *note nntplib: c1. module’s ‘NNTP’ class gained ‘description()’
     and ‘descriptions()’ methods to retrieve newsgroup descriptions for
     a single group or for a range of groups.  (Contributed by Jürgen A.
     Erhard.)

   * Two new functions were added to the *note operator: c3. module,
     ‘attrgetter(attr)’ and ‘itemgetter(index)’.  Both functions return
     callables that take a single argument and return the corresponding
     attribute or item; these callables make excellent data extractors
     when used with *note map(): c35. or *note sorted(): 44c.  For
     example:

          >>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
          >>> map(operator.itemgetter(0), L)
          ['c', 'd', 'a', 'b']
          >>> map(operator.itemgetter(1), L)
          [2, 1, 4, 3]
          >>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
          [('d', 1), ('c', 2), ('b', 3), ('a', 4)]

     （由 Raymond Hettinger 贡献。）

   * The *note optparse: c4. module was updated in various ways.  The
     module now passes its messages through *note gettext.gettext():
     dd5, making it possible to internationalize Optik’s help and error
     messages.  Help messages for options can now include the string
     ‘'%default'’, which will be replaced by the option’s default value.
     (Contributed by Greg Ward.)

   * The long-term plan is to deprecate the ‘rfc822’ module in some
     future Python release in favor of the *note email: 69. package.  To
     this end, the ‘email.Utils.formatdate()’ function has been changed
     to make it usable as a replacement for ‘rfc822.formatdate()’.  You
     may want to write new e-mail processing code with this in mind.
     (Change implemented by Anthony Baxter.)

   * A new ‘urandom(n)’ function was added to the *note os: c5. module,
     returning a string containing `n' bytes of random data.  This
     function provides access to platform-specific sources of randomness
     such as ‘/dev/urandom’ on Linux or the Windows CryptoAPI.
     (Contributed by Trevor Perrin.)

   * Another new function: ‘os.path.lexists(path)’ returns true if the
     file specified by `path' exists, whether or not it’s a symbolic
     link.  This differs from the existing ‘os.path.exists(path)’
     function, which returns false if `path' is a symlink that points to
     a destination that doesn’t exist.  (Contributed by Beni
     Cherniavsky.)

   * A new ‘getsid()’ function was added to the *note posix: d2. module
     that underlies the *note os: c5. module.  (Contributed by J.
     Raynor.)

   * The *note poplib: d1. module now supports POP over SSL.
     (Contributed by Hector Urtubia.)

   * The *note profile: d4. module can now profile C extension
     functions.  (Contributed by Nick Bastin.)

   * The *note random: dd. module has a new method called
     ‘getrandbits(N)’ that returns a long integer `N' bits in length.
     The existing ‘randrange()’ method now uses ‘getrandbits()’ where
     appropriate, making generation of arbitrarily large random numbers
     more efficient.  (Contributed by Raymond Hettinger.)

   * The regular expression language accepted by the *note re: de.
     module was extended with simple conditional expressions, written as
     ‘(?(group)A|B)’.  `group' is either a numeric group ID or a group
     name defined with ‘(?P<group>...)’ earlier in the expression.  If
     the specified group matched, the regular expression pattern `A'
     will be tested against the string; if the group didn’t match, the
     pattern `B' will be used instead.  (Contributed by Gustavo
     Niemeyer.)

   * The *note re: de. module is also no longer recursive, thanks to a
     massive amount of work by Gustavo Niemeyer.  In a recursive regular
     expression engine, certain patterns result in a large amount of C
     stack space being consumed, and it was possible to overflow the
     stack.  For example, if you matched a 30000-byte string of ‘a’
     characters against the expression ‘(a|b)+’, one stack frame was
     consumed per character.  Python 2.3 tried to check for stack
     overflow and raise a *note RuntimeError: 2bb. exception, but
     certain patterns could sidestep the checking and if you were
     unlucky Python could segfault.  Python 2.4’s regular expression
     engine can match this pattern without problems.

   * The *note signal: eb. module now performs tighter error-checking on
     the parameters to the *note signal.signal(): a85. function.  For
     example, you can’t set a handler on the ‘SIGKILL’ signal; previous
     versions of Python would quietly accept this, but 2.4 will raise a
     *note RuntimeError: 2bb. exception.

   * Two new functions were added to the *note socket: f0. module.
     ‘socketpair()’ returns a pair of connected sockets and
     ‘getservbyport(port)’ looks up the service name for a given port
     number.  (Contributed by Dave Cole and Barry Warsaw.)

   * The ‘sys.exitfunc()’ function has been deprecated.  Code should be
     using the existing *note atexit: c. module, which correctly handles
     calling multiple exit functions.  Eventually ‘sys.exitfunc()’ will
     become a purely internal interface, accessed only by *note atexit:
     c.

   * The *note tarfile: 102. module now generates GNU-format tar files
     by default.  (Contributed by Lars Gustäbel.)

   * The *note threading: 10a. module now has an elegantly simple way to
     support thread-local data.  The module contains a ‘local’ class
     whose attribute values are local to different threads.

          import threading

          data = threading.local()
          data.number = 42
          data.url = ('www.python.org', 80)

     Other threads can assign and retrieve their own values for the
     ‘number’ and ‘url’ attributes.  You can subclass ‘local’ to
     initialize attributes or to add methods.  (Contributed by Jim
     Fulton.)

   * The *note timeit: 10c. module now automatically disables periodic
     garbage collection during the timing loop.  This change makes
     consecutive timings more comparable.  (Contributed by Raymond
     Hettinger.)

   * The *note weakref: 129. module now supports a wider variety of
     objects including Python functions, class instances, sets,
     frozensets, deques, arrays, files, sockets, and regular expression
     pattern objects.  (Contributed by Raymond Hettinger.)

   * The ‘xmlrpclib’ module now supports a multi-call extension for
     transmitting multiple XML-RPC calls in a single HTTP operation.
     (Contributed by Brian Quinlan.)

   * ‘mpz’, ‘rotor’ 和 ‘xreadlines’ 模块已被移除。

* Menu:

* cookielib::
* doctest: doctest<3>.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3548.html


File: python.info,  Node: cookielib,  Next: doctest<3>,  Up: 新增，改进和弃用的模块<3>

1.13.12.1 cookielib
...................

The ‘cookielib’ library supports client-side handling for HTTP cookies,
mirroring the ‘Cookie’ module’s server-side cookie support.  Cookies are
stored in cookie jars; the library transparently stores cookies offered
by the web server in the cookie jar, and fetches the cookie from the jar
when connecting to the server.  As in web browsers, policy objects
control whether cookies are accepted or not.

In order to store cookies across sessions, two implementations of cookie
jars are provided: one that stores cookies in the Netscape format so
applications can use the Mozilla or Lynx cookie files, and one that
stores cookies in the same format as the Perl libwww library.

‘urllib2’ has been changed to interact with ‘cookielib’:
‘HTTPCookieProcessor’ manages a cookie jar that is used when accessing
URLs.

该模块由 John J. Lee 贡献。


File: python.info,  Node: doctest<3>,  Prev: cookielib,  Up: 新增，改进和弃用的模块<3>

1.13.12.2 doctest
.................

The *note doctest: 67. module underwent considerable refactoring thanks
to Edward Loper and Tim Peters.  Testing can still be as simple as
running *note doctest.testmod(): dd8, but the refactorings allow
customizing the module’s operation in various ways

The new ‘DocTestFinder’ class extracts the tests from a given object’s
docstrings:

     def f (x, y):
         """>>> f(2,2)
     4
     >>> f(3,2)
     6
         """
         return x*y

     finder = doctest.DocTestFinder()

     # Get list of DocTest instances
     tests = finder.find(f)

The new ‘DocTestRunner’ class then runs individual tests and can produce
a summary of the results:

     runner = doctest.DocTestRunner()
     for t in tests:
         tried, failed = runner.run(t)

     runner.summarize(verbose=1)

The above example produces the following output:

     1 items passed all tests:
        2 tests in f
     2 tests in 1 items.
     2 passed and 0 failed.
     Test passed.

‘DocTestRunner’ uses an instance of the ‘OutputChecker’ class to compare
the expected output with the actual output.  This class takes a number
of different flags that customize its behaviour; ambitious users can
also write a completely new subclass of ‘OutputChecker’.

The default output checker provides a number of handy features.  For
example, with the *note doctest.ELLIPSIS: dd9. option flag, an ellipsis
(‘...’) in the expected output matches any substring, making it easier
to accommodate outputs that vary in minor ways:

     def o (n):
         """>>> o(1)
     <__main__.C instance at 0x...>
     >>>
     """

Another special string, ‘<BLANKLINE>’, matches a blank line:

     def p (n):
         """>>> p(1)
     <BLANKLINE>
     >>>
     """

Another new capability is producing a diff-style display of the output
by specifying the *note doctest.REPORT_UDIFF: dda. (unified diffs),
*note doctest.REPORT_CDIFF: ddb. (context diffs), or *note
doctest.REPORT_NDIFF: ddc. (delta-style) option flags.  For example:

     def g (n):
         """>>> g(4)
     here
     is
     a
     lengthy
     >>>"""
         L = 'here is a rather lengthy list of words'.split()
         for word in L[:n]:
             print word

Running the above function’s tests with *note doctest.REPORT_UDIFF: dda.
specified, you get the following output:

     **********************************************************************
     File "t.py", line 15, in g
     Failed example:
         g(4)
     Differences (unified diff with -expected +actual):
         @@ -2,3 +2,3 @@
          is
          a
         -lengthy
         +rather
     **********************************************************************


File: python.info,  Node: 构建和 C API 的改变<11>,  Next: 移植到 Python 2 4,  Prev: 新增，改进和弃用的模块<3>,  Up: Python 2 4 有什么新变化

1.13.13 构建和 C API 的改变
---------------------------

Some of the changes to Python’s build process and to the C API are:

   * Three new convenience macros were added for common return values
     from extension functions: *note Py_RETURN_NONE: dde, *note
     Py_RETURN_TRUE: ddf, and *note Py_RETURN_FALSE: de0.  (Contributed
     by Brett Cannon.)

   * Another new macro, ‘Py_CLEAR(obj)’, decreases the reference count
     of `obj' and sets `obj' to the null pointer.  (Contributed by Jim
     Fulton.)

   * A new function, ‘PyTuple_Pack(N, obj1, obj2, ..., objN)’,
     constructs tuples from a variable length argument list of Python
     objects.  (Contributed by Raymond Hettinger.)

   * A new function, ‘PyDict_Contains(d, k)’, implements fast dictionary
     lookups without masking exceptions raised during the look-up
     process.  (Contributed by Raymond Hettinger.)

   * The ‘Py_IS_NAN(X)’ macro returns 1 if its float or double argument
     `X' is a NaN. (Contributed by Tim Peters.)

   * C code can avoid unnecessary locking by using the new *note
     PyEval_ThreadsInitialized(): de1. function to tell if any thread
     operations have been performed.  If this function returns false, no
     lock operations are needed.  (Contributed by Nick Coghlan.)

   * A new function, *note PyArg_VaParseTupleAndKeywords(): de2, is the
     same as *note PyArg_ParseTupleAndKeywords(): 5d3. but takes a
     ‘va_list’ instead of a number of arguments.  (Contributed by Greg
     Chapman.)

   * A new method flag, ‘METH_COEXISTS’, allows a function defined in
     slots to co-exist with a *note PyCFunction: de3. having the same
     name.  This can halve the access time for a method such as
     ‘set.__contains__()’.  (Contributed by Raymond Hettinger.)

   * Python can now be built with additional profiling for the
     interpreter itself, intended as an aid to people developing the
     Python core.  Providing ‘--enable-profiling’ to the ‘configure’
     script will let you profile the interpreter with ‘gprof’, and
     providing the ‘--with-tsc’ switch enables profiling using the
     Pentium’s Time-Stamp-Counter register.  Note that the ‘--with-tsc’
     switch is slightly misnamed, because the profiling feature also
     works on the PowerPC platform, though that processor architecture
     doesn’t call that register "the TSC register".  (Contributed by
     Jeremy Hylton.)

   * The ‘tracebackobject’ type has been renamed to ‘PyTracebackObject’.

* Menu:

* Port-Specific Changes: Port-Specific Changes<2>.


File: python.info,  Node: Port-Specific Changes<2>,  Up: 构建和 C API 的改变<11>

1.13.13.1 Port-Specific Changes
...............................

   * The Windows port now builds under MSVC++ 7.1 as well as version 6.
     (Contributed by Martin von Löwis.)


File: python.info,  Node: 移植到 Python 2 4,  Next: 致谢<4>,  Prev: 构建和 C API 的改变<11>,  Up: Python 2 4 有什么新变化

1.13.14 移植到 Python 2.4
-------------------------

This section lists previously described changes that may require changes
to your code:

   * Left shifts and hexadecimal/octal constants that are too large no
     longer trigger a *note FutureWarning: 32e. and return a value
     limited to 32 or 64 bits; instead they return a long integer.

   * Integer operations will no longer trigger an ‘OverflowWarning’.
     The ‘OverflowWarning’ warning will disappear in Python 2.5.

   * The *note zip(): c3a. built-in function and ‘itertools.izip()’ now
     return an empty list instead of raising a *note TypeError: 193.
     exception if called with no arguments.

   * You can no longer compare the ‘date’ and *note datetime: 195.
     instances provided by the *note datetime: 31. module.  Two
     instances of different classes will now always be unequal, and
     relative comparisons (‘<’, ‘>’) will raise a *note TypeError: 193.

   * ‘dircache.listdir()’ now passes exceptions to the caller instead of
     returning empty lists.

   * ‘LexicalHandler.startDTD()’ used to receive the public and system
     IDs in the wrong order.  This has been corrected; applications
     relying on the wrong order need to be fixed.

   * *note fcntl.ioctl(): de6. now warns if the `mutate' argument is
     omitted and relevant.

   * The *note tarfile: 102. module now generates GNU-format tar files
     by default.

   * Encountering a failure while importing a module no longer leaves a
     partially-initialized module object in ‘sys.modules’.

   * *note None: 158. is now a constant; code that binds a new value to
     the name ‘None’ is now a syntax error.

   * The ‘signals.signal()’ function now raises a *note RuntimeError:
     2bb. exception for certain illegal values; previously these errors
     would pass silently.  For example, you can no longer set a handler
     on the ‘SIGKILL’ signal.


File: python.info,  Node: 致谢<4>,  Prev: 移植到 Python 2 4,  Up: Python 2 4 有什么新变化

1.13.15 致谢
------------

作者感谢以下人员对本文各种草稿给予的建议，更正和协助：Koray Can,
Hye-Shik Chang, Michael Dyck, Raymond Hettinger, Brian Hurt, Hamish
Lawson, Fredrik Lundh, Sean Reifschneider, Sadruddin Rejeb.


File: python.info,  Node: Python 2 3 有什么新变化,  Next: Python 2 2 有什么新变化,  Prev: Python 2 4 有什么新变化,  Up: Python的新变化

1.14 Python 2.3 有什么新变化
============================


作者: A.M. Kuchling

本文介绍了 Python 2.3 的新特性。 Python 2.3 发布于 2003 年 7 月 29 日。

The main themes for Python 2.3 are polishing some of the features added
in 2.2, adding various small but useful enhancements to the core
language, and expanding the standard library.  The new object model
introduced in the previous version has benefited from 18 months of
bugfixes and from optimization efforts that have improved the
performance of new-style classes.  A few new built-in functions have
been added such as *note sum(): 1e6. and *note enumerate(): deb.  The
*note in: 7ac. operator can now be used for substring searches (e.g.
‘"ab" in "abc"’ returns *note True: 4a1.).

Some of the many new library features include Boolean, set, heap, and
date/time data types, the ability to import modules from ZIP-format
archives, metadata support for the long-awaited Python catalog, an
updated version of IDLE, and modules for logging messages, wrapping
text, parsing CSV files, processing command-line options, using
BerkeleyDB databases...  the list of new and enhanced modules is
lengthy.

This article doesn’t attempt to provide a complete specification of the
new features, but instead provides a convenient overview.  For full
details, you should refer to the documentation for Python 2.3, such as
the Python Library Reference and the Python Reference Manual.  If you
want to understand the complete implementation and design rationale,
refer to the PEP for a particular new feature.

* Menu:

* PEP 218; A Standard Set Datatype: PEP 218 A Standard Set Datatype.
* PEP 255; Simple Generators: PEP 255 Simple Generators.
* PEP 263; Source Code Encodings: PEP 263 Source Code Encodings.
* PEP 273; 从ZIP压缩包导入模块: PEP 273 从ZIP压缩包导入模块.
* PEP 277; Unicode file name support for Windows NT: PEP 277 Unicode file name support for Windows NT.
* PEP 278; 通用换行支持: PEP 278 通用换行支持.
* PEP 279; enumerate(): PEP 279 enumerate.
* PEP 282; logging 包: PEP 282 logging 包.
* PEP 285; 布尔类型: PEP 285 布尔类型.
* PEP 293; Codec Error Handling Callbacks: PEP 293 Codec Error Handling Callbacks.
* PEP 301; Distutils的软件包索引和元数据: PEP 301 Distutils的软件包索引和元数据.
* PEP 302; New Import Hooks: PEP 302 New Import Hooks.
* PEP 305; 逗号分隔文件: PEP 305 逗号分隔文件.
* PEP 307; Pickle Enhancements: PEP 307 Pickle Enhancements.
* 扩展切片::
* 其他语言特性修改: 其他语言特性修改<13>.
* 新增，改进和弃用的模块: 新增，改进和弃用的模块<4>.
* Pymalloc; A Specialized Object Allocator: Pymalloc A Specialized Object Allocator.
* 构建和 C API 的改变: 构建和 C API 的改变<12>.
* Other Changes and Fixes: Other Changes and Fixes<2>.
* 移植到 Python 2.3: 移植到 Python 2 3.
* 致谢: 致谢<5>.


File: python.info,  Node: PEP 218 A Standard Set Datatype,  Next: PEP 255 Simple Generators,  Up: Python 2 3 有什么新变化

1.14.1 PEP 218: A Standard Set Datatype
---------------------------------------

The new ‘sets’ module contains an implementation of a set datatype.  The
‘Set’ class is for mutable sets, sets that can have members added and
removed.  The ‘ImmutableSet’ class is for sets that can’t be modified,
and instances of ‘ImmutableSet’ can therefore be used as dictionary
keys.  Sets are built on top of dictionaries, so the elements within a
set must be hashable.

这是一个简单的示例：

     >>> import sets
     >>> S = sets.Set([1,2,3])
     >>> S
     Set([1, 2, 3])
     >>> 1 in S
     True
     >>> 0 in S
     False
     >>> S.add(5)
     >>> S.remove(3)
     >>> S
     Set([1, 2, 5])
     >>>

The union and intersection of sets can be computed with the ‘union()’
and ‘intersection()’ methods; an alternative notation uses the bitwise
operators ‘&’ and ‘|’.  Mutable sets also have in-place versions of
these methods, ‘union_update()’ and ‘intersection_update()’.

     >>> S1 = sets.Set([1,2,3])
     >>> S2 = sets.Set([4,5,6])
     >>> S1.union(S2)
     Set([1, 2, 3, 4, 5, 6])
     >>> S1 | S2                  # Alternative notation
     Set([1, 2, 3, 4, 5, 6])
     >>> S1.intersection(S2)
     Set([])
     >>> S1 & S2                  # Alternative notation
     Set([])
     >>> S1.union_update(S2)
     >>> S1
     Set([1, 2, 3, 4, 5, 6])
     >>>

It’s also possible to take the symmetric difference of two sets.  This
is the set of all elements in the union that aren’t in the intersection.
Another way of putting it is that the symmetric difference contains all
elements that are in exactly one set.  Again, there’s an alternative
notation (‘^’), and an in-place version with the ungainly name
‘symmetric_difference_update()’.

     >>> S1 = sets.Set([1,2,3,4])
     >>> S2 = sets.Set([3,4,5,6])
     >>> S1.symmetric_difference(S2)
     Set([1, 2, 5, 6])
     >>> S1 ^ S2
     Set([1, 2, 5, 6])
     >>>

There are also ‘issubset()’ and ‘issuperset()’ methods for checking
whether one set is a subset or superset of another:

     >>> S1 = sets.Set([1,2,3])
     >>> S2 = sets.Set([2,3])
     >>> S2.issubset(S1)
     True
     >>> S1.issubset(S2)
     False
     >>> S1.issuperset(S2)
     True
     >>>

参见
....

PEP 218(1) - 添加内置Set对象类型

     PEP 由 Greg V. Wilson 撰写 ; 由 Greg V. Wilson, Alex Martelli 和
     GvR 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0218


File: python.info,  Node: PEP 255 Simple Generators,  Next: PEP 263 Source Code Encodings,  Prev: PEP 218 A Standard Set Datatype,  Up: Python 2 3 有什么新变化

1.14.2 PEP 255: Simple Generators
---------------------------------

In Python 2.2, generators were added as an optional feature, to be
enabled by a ‘from __future__ import generators’ directive.  In 2.3
generators no longer need to be specially enabled, and are now always
present; this means that *note yield: 190. is now always a keyword.  The
rest of this section is a copy of the description of generators from the
"What’s New in Python 2.2" document; if you read it back when Python 2.2
came out, you can skip the rest of this section.

You’re doubtless familiar with how function calls work in Python or C.
When you call a function, it gets a private namespace where its local
variables are created.  When the function reaches a *note return: 191.
statement, the local variables are destroyed and the resulting value is
returned to the caller.  A later call to the same function will get a
fresh new set of local variables.  But, what if the local variables
weren’t thrown away on exiting a function?  What if you could later
resume the function where it left off?  This is what generators provide;
they can be thought of as resumable functions.

Here’s the simplest example of a generator function:

     def generate_ints(N):
         for i in range(N):
             yield i

A new keyword, *note yield: 190, was introduced for generators.  Any
function containing a ‘yield’ statement is a generator function; this is
detected by Python’s bytecode compiler which compiles the function
specially as a result.

When you call a generator function, it doesn’t return a single value;
instead it returns a generator object that supports the iterator
protocol.  On executing the *note yield: 190. statement, the generator
outputs the value of ‘i’, similar to a *note return: 191. statement.
The big difference between ‘yield’ and a ‘return’ statement is that on
reaching a ‘yield’ the generator’s state of execution is suspended and
local variables are preserved.  On the next call to the generator’s
‘.next()’ method, the function will resume executing immediately after
the ‘yield’ statement.  (For complicated reasons, the ‘yield’ statement
isn’t allowed inside the *note try: d7a. block of a ‘try’...‘finally’
statement; read PEP 255(1) for a full explanation of the interaction
between ‘yield’ and exceptions.)

Here’s a sample usage of the ‘generate_ints()’ generator:

     >>> gen = generate_ints(3)
     >>> gen
     <generator object at 0x8117f90>
     >>> gen.next()
     0
     >>> gen.next()
     1
     >>> gen.next()
     2
     >>> gen.next()
     Traceback (most recent call last):
       File "stdin", line 1, in ?
       File "stdin", line 2, in generate_ints
     StopIteration

You could equally write ‘for i in generate_ints(5)’, or ‘a,b,c =
generate_ints(3)’.

Inside a generator function, the *note return: 191. statement can only
be used without a value, and signals the end of the procession of
values; afterwards the generator cannot return any further values.
‘return’ with a value, such as ‘return 5’, is a syntax error inside a
generator function.  The end of the generator’s results can also be
indicated by raising *note StopIteration: 48e. manually, or by just
letting the flow of execution fall off the bottom of the function.

You could achieve the effect of generators manually by writing your own
class and storing all the local variables of the generator as instance
variables.  For example, returning a list of integers could be done by
setting ‘self.count’ to 0, and having the *note next(): 68b. method
increment ‘self.count’ and return it.  However, for a moderately
complicated generator, writing a corresponding class would be much
messier.  ‘Lib/test/test_generators.py’ contains a number of more
interesting examples.  The simplest one implements an in-order traversal
of a tree using generators recursively.

     # A recursive generator that generates Tree leaves in in-order.
     def inorder(t):
         if t:
             for x in inorder(t.left):
                 yield x
             yield t.label
             for x in inorder(t.right):
                 yield x

Two other examples in ‘Lib/test/test_generators.py’ produce solutions
for the N-Queens problem (placing $N$ queens on an $NxN$ chess board so
that no queen threatens another) and the Knight’s Tour (a route that
takes a knight to every square of an $NxN$ chessboard without visiting
any square twice).

The idea of generators comes from other programming languages,
especially Icon (‘https://www.cs.arizona.edu/icon/’), where the idea of
generators is central.  In Icon, every expression and function call
behaves like a generator.  One example from "An Overview of the Icon
Programming Language" at
‘https://www.cs.arizona.edu/icon/docs/ipd266.htm’ gives an idea of what
this looks like:

     sentence := "Store it in the neighboring harbor"
     if (i := find("or", sentence)) > 5 then write(i)

In Icon the ‘find()’ function returns the indexes at which the substring
"or" is found: 3, 23, 33.  In the *note if: def. statement, ‘i’ is first
assigned a value of 3, but 3 is less than 5, so the comparison fails,
and Icon retries it with the second value of 23.  23 is greater than 5,
so the comparison now succeeds, and the code prints the value 23 to the
screen.

Python doesn’t go nearly as far as Icon in adopting generators as a
central concept.  Generators are considered part of the core Python
language, but learning or using them isn’t compulsory; if they don’t
solve any problems that you have, feel free to ignore them.  One novel
feature of Python’s interface as compared to Icon’s is that a
generator’s state is represented as a concrete object (the iterator)
that can be passed around to other functions or stored in a data
structure.

参见
....

PEP 255(2) - 简单生成器

     Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland.
     Implemented mostly by Neil Schemenauer and Tim Peters, with other
     fixes from the Python Labs crew.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0255

   (2) https://www.python.org/dev/peps/pep-0255


File: python.info,  Node: PEP 263 Source Code Encodings,  Next: PEP 273 从ZIP压缩包导入模块,  Prev: PEP 255 Simple Generators,  Up: Python 2 3 有什么新变化

1.14.3 PEP 263: Source Code Encodings
-------------------------------------

Python source files can now be declared as being in different character
set encodings.  Encodings are declared by including a specially
formatted comment in the first or second line of the source file.  For
example, a UTF-8 file can be declared with:

     #!/usr/bin/env python
     # -*- coding: UTF-8 -*-

Without such an encoding declaration, the default encoding used is 7-bit
ASCII. Executing or importing modules that contain string literals with
8-bit characters and have no encoding declaration will result in a *note
DeprecationWarning: 279. being signalled by Python 2.3; in 2.4 this will
be a syntax error.

The encoding declaration only affects Unicode string literals, which
will be converted to Unicode using the specified encoding.  Note that
Python identifiers are still restricted to ASCII characters, so you
can’t have variable names that use characters outside of the usual
alphanumerics.

参见
....

PEP 263(1) - Defining Python Source Code Encodings

     由 Marc-André Lemburg 和 Martin von Löwis 撰写 ; 由 Suzuki Hisao 和
     Martin von Löwis 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0263


File: python.info,  Node: PEP 273 从ZIP压缩包导入模块,  Next: PEP 277 Unicode file name support for Windows NT,  Prev: PEP 263 Source Code Encodings,  Up: Python 2 3 有什么新变化

1.14.4 PEP 273: 从ZIP压缩包导入模块
-----------------------------------

The new *note zipimport: 144. module adds support for importing modules
from a ZIP-format archive.  You don’t need to import the module
explicitly; it will be automatically imported if a ZIP archive’s
filename is added to ‘sys.path’.  For example:

     amk@nyman:~/src/python$ unzip -l /tmp/example.zip
     Archive:  /tmp/example.zip
       Length     Date   Time    Name
      --------    ----   ----    ----
          8467  11-26-02 22:30   jwzthreading.py
      --------                   -------
          8467                   1 file
     amk@nyman:~/src/python$ ./python
     Python 2.3 (#1, Aug 1 2003, 19:54:32)
     >>> import sys
     >>> sys.path.insert(0, '/tmp/example.zip')  # Add .zip file to front of path
     >>> import jwzthreading
     >>> jwzthreading.__file__
     '/tmp/example.zip/jwzthreading.py'
     >>>

An entry in ‘sys.path’ can now be the filename of a ZIP archive.  The
ZIP archive can contain any kind of files, but only files named ‘*.py’,
‘*.pyc’, or ‘*.pyo’ can be imported.  If an archive only contains ‘*.py’
files, Python will not attempt to modify the archive by adding the
corresponding ‘*.pyc’ file, meaning that if a ZIP archive doesn’t
contain ‘*.pyc’ files, importing may be rather slow.

A path within the archive can also be specified to only import from a
subdirectory; for example, the path ‘/tmp/example.zip/lib/’ would only
import from the ‘lib/’ subdirectory within the archive.

参见
....

PEP 273(1) -  从ZIP压缩包导入模块

     Written by James C. Ahlstrom, who also provided an implementation.
     Python 2.3 follows the specification in PEP 273(2), but uses an
     implementation written by Just van Rossum that uses the import
     hooks described in PEP 302(3).  See section *note PEP 302; New
     Import Hooks: df3. for a description of the new import hooks.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0273

   (2) https://www.python.org/dev/peps/pep-0273

   (3) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: PEP 277 Unicode file name support for Windows NT,  Next: PEP 278 通用换行支持,  Prev: PEP 273 从ZIP压缩包导入模块,  Up: Python 2 3 有什么新变化

1.14.5 PEP 277: Unicode file name support for Windows NT
--------------------------------------------------------

On Windows NT, 2000, and XP, the system stores file names as Unicode
strings.  Traditionally, Python has represented file names as byte
strings, which is inadequate because it renders some file names
inaccessible.

Python now allows using arbitrary Unicode strings (within the
limitations of the file system) for all functions that expect file
names, most notably the *note open(): 4f8. built-in function.  If a
Unicode string is passed to *note os.listdir(): a49, Python now returns
a list of Unicode strings.  A new function, ‘os.getcwdu()’, returns the
current directory as a Unicode string.

Byte strings still work as file names, and on Windows Python will
transparently convert them to Unicode using the ‘mbcs’ encoding.

Other systems also allow Unicode strings as file names but convert them
to byte strings before passing them to the system, which can cause a
*note UnicodeError: c43. to be raised.  Applications can test whether
arbitrary Unicode strings are supported as file names by checking *note
os.path.supports_unicode_filenames: df5, a Boolean value.

Under MacOS, *note os.listdir(): a49. may now return Unicode filenames.

参见
....

PEP 277(1) - Unicode file name support for Windows NT

     由 Neil Hodgson 撰写 ; 由 Neil Hodgson, Martin von Löwis 和 Mark
     Hammond 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0277


File: python.info,  Node: PEP 278 通用换行支持,  Next: PEP 279 enumerate,  Prev: PEP 277 Unicode file name support for Windows NT,  Up: Python 2 3 有什么新变化

1.14.6 PEP 278: 通用换行支持
----------------------------

The three major operating systems used today are Microsoft Windows,
Apple’s Macintosh OS, and the various Unix derivatives.  A minor
irritation of cross-platform work is that these three platforms all use
different characters to mark the ends of lines in text files.  Unix uses
the linefeed (ASCII character 10), MacOS uses the carriage return (ASCII
character 13), and Windows uses a two-character sequence of a carriage
return plus a newline.

Python’s file objects can now support end of line conventions other than
the one followed by the platform on which Python is running.  Opening a
file with the mode ‘'U'’ or ‘'rU'’ will open a file for reading in *note
universal newlines: 5fd. mode.  All three line ending conventions will
be translated to a ‘'\n'’ in the strings returned by the various file
methods such as ‘read()’ and *note readline(): df.

Universal newline support is also used when importing modules and when
executing a file with the ‘execfile()’ function.  This means that Python
modules can be shared between all three operating systems without
needing to convert the line-endings.

This feature can be disabled when compiling Python by specifying the
‘--without-universal-newlines’ switch when running Python’s ‘configure’
script.

参见
....

PEP 278(1) - 通用换行支持

     由 Jack Jansen 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0278


File: python.info,  Node: PEP 279 enumerate,  Next: PEP 282 logging 包,  Prev: PEP 278 通用换行支持,  Up: Python 2 3 有什么新变化

1.14.7 PEP 279: enumerate()
---------------------------

A new built-in function, *note enumerate(): deb, will make certain loops
a bit clearer.  ‘enumerate(thing)’, where `thing' is either an iterator
or a sequence, returns an iterator that will return ‘(0, thing[0])’,
‘(1, thing[1])’, ‘(2, thing[2])’, and so forth.

A common idiom to change every element of a list looks like this:

     for i in range(len(L)):
         item = L[i]
         # ... compute some result based on item ...
         L[i] = result

可以使用 *note enumerate(): deb. 重写为：

     for i, item in enumerate(L):
         # ... compute some result based on item ...
         L[i] = result

参见
....

PEP 279(1) - 内置函数 enumerate()

     由 Raymond D. Hettinger 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0279


File: python.info,  Node: PEP 282 logging 包,  Next: PEP 285 布尔类型,  Prev: PEP 279 enumerate,  Up: Python 2 3 有什么新变化

1.14.8 PEP 282: logging 包
--------------------------

A standard package for writing logs, *note logging: ab, has been added
to Python 2.3.  It provides a powerful and flexible mechanism for
generating logging output which can then be filtered and processed in
various ways.  A configuration file written in a standard format can be
used to control the logging behavior of a program.  Python includes
handlers that will write log records to standard error or to a file or
socket, send them to the system log, or even e-mail them to a particular
address; of course, it’s also possible to write your own handler
classes.

The ‘Logger’ class is the primary class.  Most application code will
deal with one or more ‘Logger’ objects, each one used by a particular
subsystem of the application.  Each ‘Logger’ is identified by a name,
and names are organized into a hierarchy using ‘.’ as the component
separator.  For example, you might have ‘Logger’ instances named
‘server’, ‘server.auth’ and ‘server.network’.  The latter two instances
are below ‘server’ in the hierarchy.  This means that if you turn up the
verbosity for ‘server’ or direct ‘server’ messages to a different
handler, the changes will also apply to records logged to ‘server.auth’
and ‘server.network’.  There’s also a root ‘Logger’ that’s the parent of
all other loggers.

For simple uses, the *note logging: ab. package contains some
convenience functions that always use the root log:

     import logging

     logging.debug('Debugging information')
     logging.info('Informational message')
     logging.warning('Warning:config file %s not found', 'server.conf')
     logging.error('Error occurred')
     logging.critical('Critical error -- shutting down')

This produces the following output:

     WARNING:root:Warning:config file server.conf not found
     ERROR:root:Error occurred
     CRITICAL:root:Critical error -- shutting down

In the default configuration, informational and debugging messages are
suppressed and the output is sent to standard error.  You can enable the
display of informational and debugging messages by calling the
‘setLevel()’ method on the root logger.

Notice the ‘warning()’ call’s use of string formatting operators; all of
the functions for logging messages take the arguments ‘(msg, arg1, arg2,
...)’ and log the string resulting from ‘msg % (arg1, arg2, ...)’.

There’s also an ‘exception()’ function that records the most recent
traceback.  Any of the other functions will also record the traceback if
you specify a true value for the keyword argument `exc_info'.

     def f():
         try:    1/0
         except: logging.exception('Problem recorded')

     f()

This produces the following output:

     ERROR:root:Problem recorded
     Traceback (most recent call last):
       File "t.py", line 6, in f
         1/0
     ZeroDivisionError: integer division or modulo by zero

Slightly more advanced programs will use a logger other than the root
logger.  The ‘getLogger(name)’ function is used to get a particular log,
creating it if it doesn’t exist yet.  ‘getLogger(None)’ returns the root
logger.

     log = logging.getLogger('server')
      ...
     log.info('Listening on port %i', port)
      ...
     log.critical('Disk full')
      ...

Log records are usually propagated up the hierarchy, so a message logged
to ‘server.auth’ is also seen by ‘server’ and ‘root’, but a ‘Logger’ can
prevent this by setting its ‘propagate’ attribute to *note False: 390.

There are more classes provided by the *note logging: ab. package that
can be customized.  When a ‘Logger’ instance is told to log a message,
it creates a ‘LogRecord’ instance that is sent to any number of
different ‘Handler’ instances.  Loggers and handlers can also have an
attached list of filters, and each filter can cause the ‘LogRecord’ to
be ignored or can modify the record before passing it along.  When
they’re finally output, ‘LogRecord’ instances are converted to text by a
‘Formatter’ class.  All of these classes can be replaced by your own
specially-written classes.

With all of these features the *note logging: ab. package should provide
enough flexibility for even the most complicated applications.  This is
only an incomplete overview of its features, so please see the package’s
reference documentation for all of the details.  Reading PEP 282(1) will
also be helpful.

参见
....

PEP 282(2) - Logging 系统

     由 Vinay Sajip 和 Trent Mick 撰写 ; 由 Vinay Sajip 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0282

   (2) https://www.python.org/dev/peps/pep-0282


File: python.info,  Node: PEP 285 布尔类型,  Next: PEP 293 Codec Error Handling Callbacks,  Prev: PEP 282 logging 包,  Up: Python 2 3 有什么新变化

1.14.9 PEP 285: 布尔类型
------------------------

A Boolean type was added to Python 2.3.  Two new constants were added to
the ‘__builtin__’ module, *note True: 4a1. and *note False: 390.  (*note
True: 4a1. and *note False: 390. constants were added to the built-ins
in Python 2.2.1, but the 2.2.1 versions are simply set to integer values
of 1 and 0 and aren’t a different type.)

The type object for this new type is named *note bool: 184.; the
constructor for it takes any Python value and converts it to *note True:
4a1. or *note False: 390.

     >>> bool(1)
     True
     >>> bool(0)
     False
     >>> bool([])
     False
     >>> bool( (1,) )
     True

Most of the standard library modules and built-in functions have been
changed to return Booleans.

     >>> obj = []
     >>> hasattr(obj, 'append')
     True
     >>> isinstance(obj, list)
     True
     >>> isinstance(obj, tuple)
     False

Python’s Booleans were added with the primary goal of making code
clearer.  For example, if you’re reading a function and encounter the
statement ‘return 1’, you might wonder whether the ‘1’ represents a
Boolean truth value, an index, or a coefficient that multiplies some
other quantity.  If the statement is ‘return True’, however, the meaning
of the return value is quite clear.

Python’s Booleans were `not' added for the sake of strict type-checking.
A very strict language such as Pascal would also prevent you performing
arithmetic with Booleans, and would require that the expression in an
*note if: def. statement always evaluate to a Boolean result.  Python is
not this strict and never will be, as PEP 285(1) explicitly says.  This
means you can still use any expression in an ‘if’ statement, even ones
that evaluate to a list or tuple or some random object.  The Boolean
type is a subclass of the *note int: 185. class so that arithmetic using
a Boolean still works.

     >>> True + 1
     2
     >>> False + 1
     1
     >>> False * 75
     0
     >>> True * 75
     75

To sum up *note True: 4a1. and *note False: 390. in a sentence: they’re
alternative ways to spell the integer values 1 and 0, with the single
difference that *note str(): 339. and *note repr(): 7d5. return the
strings ‘'True'’ and ‘'False'’ instead of ‘'1'’ and ‘'0'’.

参见
....

PEP 285(2) - 添加布尔类型

     由 GvR 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0285

   (2) https://www.python.org/dev/peps/pep-0285


File: python.info,  Node: PEP 293 Codec Error Handling Callbacks,  Next: PEP 301 Distutils的软件包索引和元数据,  Prev: PEP 285 布尔类型,  Up: Python 2 3 有什么新变化

1.14.10 PEP 293: Codec Error Handling Callbacks
-----------------------------------------------

When encoding a Unicode string into a byte string, unencodable
characters may be encountered.  So far, Python has allowed specifying
the error processing as either "strict" (raising *note UnicodeError:
c43.), "ignore" (skipping the character), or "replace" (using a question
mark in the output string), with "strict" being the default behavior.
It may be desirable to specify alternative processing of such errors,
such as inserting an XML character reference or HTML entity reference
into the converted string.

Python now has a flexible framework to add different processing
strategies.  New error handlers can be added with *note
codecs.register_error(): dfd, and codecs then can access the error
handler with *note codecs.lookup_error(): dfe.  An equivalent C API has
been added for codecs written in C. The error handler gets the necessary
state information such as the string being converted, the position in
the string where the error was detected, and the target encoding.  The
handler can then either raise an exception or return a replacement
string.

Two additional error handlers have been implemented using this
framework: "backslashreplace" uses Python backslash quoting to represent
unencodable characters and "xmlcharrefreplace" emits XML character
references.

参见
....

PEP 293(1) - Codec Error Handling Callbacks

     由 Walter Dörwald 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0293


File: python.info,  Node: PEP 301 Distutils的软件包索引和元数据,  Next: PEP 302 New Import Hooks,  Prev: PEP 293 Codec Error Handling Callbacks,  Up: Python 2 3 有什么新变化

1.14.11 PEP 301: Distutils的软件包索引和元数据
----------------------------------------------

Support for the long-requested Python catalog makes its first appearance
in 2.3.

The heart of the catalog is the new Distutils ‘register’ command.
Running ‘python setup.py register’ will collect the metadata describing
a package, such as its name, version, maintainer, description, &c., and
send it to a central catalog server.  The resulting catalog is available
from ‘https://pypi.org’.

To make the catalog a bit more useful, a new optional `classifiers'
keyword argument has been added to the Distutils ‘setup()’ function.  A
list of Trove(1)-style strings can be supplied to help classify the
software.

Here’s an example ‘setup.py’ with classifiers, written to be compatible
with older versions of the Distutils:

     from distutils import core
     kw = {'name': "Quixote",
           'version': "0.5.1",
           'description': "A highly Pythonic Web application framework",
           # ...
           }

     if (hasattr(core, 'setup_keywords') and
         'classifiers' in core.setup_keywords):
         kw['classifiers'] = \
             ['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
              'Environment :: No Input/Output (Daemon)',
              'Intended Audience :: Developers'],

     core.setup(**kw)

The full list of classifiers can be obtained by running ‘python setup.py
register --list-classifiers’.

参见
....

PEP 301(2) - Distutils 的软件包索引和元数据

     由 Richard Jones 撰写并实现。

   ---------- Footnotes ----------

   (1) http://catb.org/~esr/trove/

   (2) https://www.python.org/dev/peps/pep-0301


File: python.info,  Node: PEP 302 New Import Hooks,  Next: PEP 305 逗号分隔文件,  Prev: PEP 301 Distutils的软件包索引和元数据,  Up: Python 2 3 有什么新变化

1.14.12 PEP 302: New Import Hooks
---------------------------------

While it’s been possible to write custom import hooks ever since the
‘ihooks’ module was introduced in Python 1.3, no one has ever been
really happy with it because writing new import hooks is difficult and
messy.  There have been various proposed alternatives such as the
‘imputil’ and ‘iu’ modules, but none of them has ever gained much
acceptance, and none of them were easily usable from C code.

PEP 302(1) borrows ideas from its predecessors, especially from Gordon
McMillan’s ‘iu’ module.  Three new items are added to the *note sys: fe.
module:

   * ‘sys.path_hooks’ is a list of callable objects; most often they’ll
     be classes.  Each callable takes a string containing a path and
     either returns an importer object that will handle imports from
     this path or raises an *note ImportError: 33d. exception if it
     can’t handle this path.

   * ‘sys.path_importer_cache’ caches importer objects for each path, so
     ‘sys.path_hooks’ will only need to be traversed once for each path.

   * ‘sys.meta_path’ is a list of importer objects that will be
     traversed before ‘sys.path’ is checked.  This list is initially
     empty, but user code can add objects to it.  Additional built-in
     and frozen modules can be imported by an object added to this list.

Importer objects must have a single method, ‘find_module(fullname,
path=None)’.  `fullname' will be a module or package name, e.g.
‘string’ or ‘distutils.core’.  ‘find_module()’ must return a loader
object that has a single method, ‘load_module(fullname)’, that creates
and returns the corresponding module object.

Pseudo-code for Python’s new import logic, therefore, looks something
like this (simplified a bit; see PEP 302(2) for the full details):

     for mp in sys.meta_path:
         loader = mp(fullname)
         if loader is not None:
             <module> = loader.load_module(fullname)

     for path in sys.path:
         for hook in sys.path_hooks:
             try:
                 importer = hook(path)
             except ImportError:
                 # ImportError, so try the other path hooks
                 pass
             else:
                 loader = importer.find_module(fullname)
                 <module> = loader.load_module(fullname)

     # Not found!
     raise ImportError

参见
....

PEP 302(3) - 新导入钩

     由 Just van Rossum 和 Paul Moore 撰写 ; 由 Just van Rossum 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0302

   (2) https://www.python.org/dev/peps/pep-0302

   (3) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: PEP 305 逗号分隔文件,  Next: PEP 307 Pickle Enhancements,  Prev: PEP 302 New Import Hooks,  Up: Python 2 3 有什么新变化

1.14.13 PEP 305: 逗号分隔文件
-----------------------------

Comma-separated files are a format frequently used for exporting data
from databases and spreadsheets.  Python 2.3 adds a parser for
comma-separated files.

Comma-separated format is deceptively simple at first glance:

     Costs,150,200,3.95

Read a line and call ‘line.split(',')’: what could be simpler?  But toss
in string data that can contain commas, and things get more complicated:

     "Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"

A big ugly regular expression can parse this, but using the new *note
csv: 2a. package is much simpler:

     import csv

     input = open('datafile', 'rb')
     reader = csv.reader(input)
     for line in reader:
         print line

The ‘reader()’ function takes a number of different options.  The field
separator isn’t limited to the comma and can be changed to any
character, and so can the quoting and line-ending characters.

Different dialects of comma-separated files can be defined and
registered; currently there are two dialects, both used by Microsoft
Excel.  A separate *note csv.writer: e04. class will generate
comma-separated files from a succession of tuples or lists, quoting
strings that contain the delimiter.

参见
....

该实现在“Python 增强提议” - PEP ‘305’ (CSV 文件 API) 中被提出

     由 Kevin Altis, Dave Cole, Andrew McNamara, Skip Montanaro, Cliff
     Wells 撰写并实现。


File: python.info,  Node: PEP 307 Pickle Enhancements,  Next: 扩展切片,  Prev: PEP 305 逗号分隔文件,  Up: Python 2 3 有什么新变化

1.14.14 PEP 307: Pickle Enhancements
------------------------------------

The *note pickle: cb. and ‘cPickle’ modules received some attention
during the 2.3 development cycle.  In 2.2, new-style classes could be
pickled without difficulty, but they weren’t pickled very compactly; PEP
307(1) quotes a trivial example where a new-style class results in a
pickled string three times longer than that for a classic class.

The solution was to invent a new pickle protocol.  The *note
pickle.dumps(): e07. function has supported a text-or-binary flag for a
long time.  In 2.3, this flag is redefined from a Boolean to an integer:
0 is the old text-mode pickle format, 1 is the old binary format, and
now 2 is a new 2.3-specific format.  A new constant, *note
pickle.HIGHEST_PROTOCOL: e08, can be used to select the fanciest
protocol available.

Unpickling is no longer considered a safe operation.  2.2’s *note
pickle: cb. provided hooks for trying to prevent unsafe classes from
being unpickled (specifically, a ‘__safe_for_unpickling__’ attribute),
but none of this code was ever audited and therefore it’s all been
ripped out in 2.3.  You should not unpickle untrusted data in any
version of Python.

To reduce the pickling overhead for new-style classes, a new interface
for customizing pickling was added using three special methods: *note
__getstate__(): e09, *note __setstate__(): 19d, and *note
__getnewargs__(): 6b7.  Consult PEP 307(2) for the full semantics of
these methods.

As a way to compress pickles yet further, it’s now possible to use
integer codes instead of long strings to identify pickled classes.  The
Python Software Foundation will maintain a list of standardized codes;
there’s also a range of codes for private use.  Currently no codes have
been specified.

参见
....

PEP 307(3) - Extensions to the pickle protocol

     PEP 由 Guido van Rossum 和 Tim Peters 撰写和实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0307

   (2) https://www.python.org/dev/peps/pep-0307

   (3) https://www.python.org/dev/peps/pep-0307


File: python.info,  Node: 扩展切片,  Next: 其他语言特性修改<13>,  Prev: PEP 307 Pickle Enhancements,  Up: Python 2 3 有什么新变化

1.14.15 扩展切片
----------------

Ever since Python 1.4, the slicing syntax has supported an optional
third "step" or "stride" argument.  For example, these are all legal
Python syntax: ‘L[1:10:2]’, ‘L[:-1:1]’, ‘L[::-1]’.  This was added to
Python at the request of the developers of Numerical Python, which uses
the third argument extensively.  However, Python’s built-in list, tuple,
and string sequence types have never supported this feature, raising a
*note TypeError: 193. if you tried it.  Michael Hudson contributed a
patch to fix this shortcoming.

For example, you can now easily extract the elements of a list that have
even indexes:

     >>> L = range(10)
     >>> L[::2]
     [0, 2, 4, 6, 8]

Negative values also work to make a copy of the same list in reverse
order:

     >>> L[::-1]
     [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

This also works for tuples, arrays, and strings:

     >>> s='abcd'
     >>> s[::2]
     'ac'
     >>> s[::-1]
     'dcba'

If you have a mutable sequence such as a list or an array you can assign
to or delete an extended slice, but there are some differences between
assignment to extended and regular slices.  Assignment to a regular
slice can be used to change the length of the sequence:

     >>> a = range(3)
     >>> a
     [0, 1, 2]
     >>> a[1:3] = [4, 5, 6]
     >>> a
     [0, 4, 5, 6]

Extended slices aren’t this flexible.  When assigning to an extended
slice, the list on the right hand side of the statement must contain the
same number of items as the slice it is replacing:

     >>> a = range(4)
     >>> a
     [0, 1, 2, 3]
     >>> a[::2]
     [0, 2]
     >>> a[::2] = [0, -1]
     >>> a
     [0, 1, -1, 3]
     >>> a[::2] = [0,1,2]
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
     ValueError: attempt to assign sequence of size 3 to extended slice of size 2

Deletion is more straightforward:

     >>> a = range(4)
     >>> a
     [0, 1, 2, 3]
     >>> a[::2]
     [0, 2]
     >>> del a[::2]
     >>> a
     [1, 3]

One can also now pass slice objects to the *note __getitem__(): 280.
methods of the built-in sequences:

     >>> range(10).__getitem__(slice(0, 5, 2))
     [0, 2, 4]

Or use slice objects directly in subscripts:

     >>> range(10)[slice(0, 5, 2)]
     [0, 2, 4]

To simplify implementing sequences that support extended slicing, slice
objects now have a method ‘indices(length)’ which, given the length of a
sequence, returns a ‘(start, stop, step)’ tuple that can be passed
directly to *note range(): 9c6.  ‘indices()’ handles omitted and
out-of-bounds indices in a manner consistent with regular slices (and
this innocuous phrase hides a welter of confusing details!).  The method
is intended to be used like this:

     class FakeSeq:
         ...
         def calc_item(self, i):
             ...
         def __getitem__(self, item):
             if isinstance(item, slice):
                 indices = item.indices(len(self))
                 return FakeSeq([self.calc_item(i) for i in range(*indices)])
             else:
                 return self.calc_item(i)

From this example you can also see that the built-in *note slice: e0c.
object is now the type object for the slice type, and is no longer a
function.  This is consistent with Python 2.2, where *note int: 185,
*note str: 339, etc., underwent the same change.


File: python.info,  Node: 其他语言特性修改<13>,  Next: 新增，改进和弃用的模块<4>,  Prev: 扩展切片,  Up: Python 2 3 有什么新变化

1.14.16 其他语言特性修改
------------------------

Here are all of the changes that Python 2.3 makes to the core Python
language.

   * The *note yield: 190. statement is now always a keyword, as
     described in section *note PEP 255; Simple Generators: dee. of this
     document.

   * A new built-in function *note enumerate(): deb. was added, as
     described in section *note PEP 279; enumerate(): df8. of this
     document.

   * Two new constants, *note True: 4a1. and *note False: 390. were
     added along with the built-in *note bool: 184. type, as described
     in section *note PEP 285; 布尔类型: dfb. of this document.

   * The *note int(): 185. type constructor will now return a long
     integer instead of raising an *note OverflowError: 968. when a
     string or floating-point number is too large to fit into an
     integer.  This can lead to the paradoxical result that
     ‘isinstance(int(expression), int)’ is false, but that seems
     unlikely to cause problems in practice.

   * Built-in types now support the extended slicing syntax, as
     described in section *note 扩展切片: e0b. of this document.

   * A new built-in function, ‘sum(iterable, start=0)’, adds up the
     numeric items in the iterable object and returns their sum.  *note
     sum(): 1e6. only accepts numbers, meaning that you can’t use it to
     concatenate a bunch of strings.  (Contributed by Alex Martelli.)

   * ‘list.insert(pos, value)’ used to insert `value' at the front of
     the list when `pos' was negative.  The behaviour has now been
     changed to be consistent with slice indexing, so when `pos' is -1
     the value will be inserted before the last element, and so forth.

   * ‘list.index(value)’, which searches for `value' within the list and
     returns its index, now takes optional `start' and `stop' arguments
     to limit the search to only part of the list.

   * Dictionaries have a new method, ‘pop(key[, *default*])’, that
     returns the value corresponding to `key' and removes that key/value
     pair from the dictionary.  If the requested key isn’t present in
     the dictionary, `default' is returned if it’s specified and *note
     KeyError: 2c8. raised if it isn’t.

          >>> d = {1:2}
          >>> d
          {1: 2}
          >>> d.pop(4)
          Traceback (most recent call last):
            File "stdin", line 1, in ?
          KeyError: 4
          >>> d.pop(1)
          2
          >>> d.pop(1)
          Traceback (most recent call last):
            File "stdin", line 1, in ?
          KeyError: 'pop(): dictionary is empty'
          >>> d
          {}
          >>>

     There’s also a new class method, ‘dict.fromkeys(iterable, value)’,
     that creates a dictionary with keys taken from the supplied
     iterator `iterable' and all values set to `value', defaulting to
     ‘None’.

     (Patches contributed by Raymond Hettinger.)

     Also, the *note dict(): 1b9. constructor now accepts keyword
     arguments to simplify creating small dictionaries:

          >>> dict(red=1, blue=2, green=3, black=4)
          {'blue': 2, 'black': 4, 'green': 3, 'red': 1}

     （由 Just van Rossum 贡献。）

   * The *note assert: e0e. statement no longer checks the ‘__debug__’
     flag, so you can no longer disable assertions by assigning to
     ‘__debug__’.  Running Python with the *note -O: 694. switch will
     still generate code that doesn’t execute any assertions.

   * Most type objects are now callable, so you can use them to create
     new objects such as functions, classes, and modules.  (This means
     that the ‘new’ module can be deprecated in a future Python version,
     because you can now use the type objects available in the *note
     types: 119. module.)  For example, you can create a new module
     object with the following code:

          >>> import types
          >>> m = types.ModuleType('abc','docstring')
          >>> m
          <module 'abc' (built-in)>
          >>> m.__doc__
          'docstring'

   * A new warning, *note PendingDeprecationWarning: 27a. was added to
     indicate features which are in the process of being deprecated.
     The warning will `not' be printed by default.  To check for use of
     features that will be deprecated in the future, supply *note
     -Walways;;PendingDeprecationWarning;;: 41f. on the command line or
     use *note warnings.filterwarnings(): e0f.

   * The process of deprecating string-based exceptions, as in ‘raise
     "Error occurred"’, has begun.  Raising a string will now trigger
     *note PendingDeprecationWarning: 27a.

   * Using ‘None’ as a variable name will now result in a *note
     SyntaxWarning: 192. warning.  In a future version of Python, ‘None’
     may finally become a keyword.

   * The ‘xreadlines()’ method of file objects, introduced in Python
     2.1, is no longer necessary because files now behave as their own
     iterator.  ‘xreadlines()’ was originally introduced as a faster way
     to loop over all the lines in a file, but now you can simply write
     ‘for line in file_obj’.  File objects also have a new read-only
     ‘encoding’ attribute that gives the encoding used by the file;
     Unicode strings written to the file will be automatically converted
     to bytes using the given encoding.

   * The method resolution order used by new-style classes has changed,
     though you’ll only notice the difference if you have a really
     complicated inheritance hierarchy.  Classic classes are unaffected
     by this change.  Python 2.2 originally used a topological sort of a
     class’s ancestors, but 2.3 now uses the C3 algorithm as described
     in the paper "A Monotonic Superclass Linearization for Dylan"(1).
     To understand the motivation for this change, read Michele
     Simionato’s article "Python 2.3 Method Resolution Order"(2), or
     read the thread on python-dev starting with the message at
     ‘https://mail.python.org/pipermail/python-dev/2002-October/029035.html’.
     Samuele Pedroni first pointed out the problem and also implemented
     the fix by coding the C3 algorithm.

   * Python runs multithreaded programs by switching between threads
     after executing N bytecodes.  The default value for N has been
     increased from 10 to 100 bytecodes, speeding up single-threaded
     applications by reducing the switching overhead.  Some
     multithreaded applications may suffer slower response time, but
     that’s easily fixed by setting the limit back to a lower number
     using ‘sys.setcheckinterval(N)’.  The limit can be retrieved with
     the new *note sys.getcheckinterval(): e10. function.

   * One minor but far-reaching change is that the names of extension
     types defined by the modules included with Python now contain the
     module and a ‘'.'’ in front of the type name.  For example, in
     Python 2.2, if you created a socket and printed its ‘__class__’,
     you’d get this output:

          >>> s = socket.socket()
          >>> s.__class__
          <type 'socket'>

     In 2.3, you get this:

          >>> s.__class__
          <type '_socket.socket'>

   * One of the noted incompatibilities between old- and new-style
     classes has been removed: you can now assign to the *note __name__:
     c6f. and *note __bases__: e11. attributes of new-style classes.
     There are some restrictions on what can be assigned to *note
     __bases__: e11. along the lines of those relating to assigning to
     an instance’s *note __class__: e12. attribute.

* Menu:

* String Changes::
* 性能优化: 性能优化<12>.

   ---------- Footnotes ----------

   (1) http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.3910

   (2) http://www.phyast.pitt.edu/~micheles/mro.html


File: python.info,  Node: String Changes,  Next: 性能优化<12>,  Up: 其他语言特性修改<13>

1.14.16.1 String Changes
........................

   * The *note in: 7ac. operator now works differently for strings.
     Previously, when evaluating ‘X in Y’ where `X' and `Y' are strings,
     `X' could only be a single character.  That’s now changed; `X' can
     be a string of any length, and ‘X in Y’ will return *note True:
     4a1. if `X' is a substring of `Y'. If `X' is the empty string, the
     result is always *note True: 4a1.

          >>> 'ab' in 'abcd'
          True
          >>> 'ad' in 'abcd'
          False
          >>> '' in 'abcd'
          True

     Note that this doesn’t tell you where the substring starts; if you
     need that information, use the ‘find()’ string method.

   * The ‘strip()’, ‘lstrip()’, and ‘rstrip()’ string methods now have
     an optional argument for specifying the characters to strip.  The
     default is still to remove all whitespace characters:

          >>> '   abc '.strip()
          'abc'
          >>> '><><abc<><><>'.strip('<>')
          'abc'
          >>> '><><abc<><><>\n'.strip('<>')
          'abc<><><>\n'
          >>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
          u'\u4001abc'
          >>>

     (Suggested by Simon Brunning and implemented by Walter Dörwald.)

   * The ‘startswith()’ and ‘endswith()’ string methods now accept
     negative numbers for the `start' and `end' parameters.

   * Another new string method is ‘zfill()’, originally a function in
     the *note string: f7. module.  ‘zfill()’ pads a numeric string with
     zeros on the left until it’s the specified width.  Note that the
     ‘%’ operator is still more flexible and powerful than ‘zfill()’.

          >>> '45'.zfill(4)
          '0045'
          >>> '12345'.zfill(4)
          '12345'
          >>> 'goofy'.zfill(6)
          '0goofy'

     （由 Walter Dörwald 贡献。）

   * A new type object, ‘basestring’, has been added.  Both 8-bit
     strings and Unicode strings inherit from this type, so
     ‘isinstance(obj, basestring)’ will return *note True: 4a1. for
     either kind of string.  It’s a completely abstract type, so you
     can’t create ‘basestring’ instances.

   * Interned strings are no longer immortal and will now be
     garbage-collected in the usual way when the only reference to them
     is from the internal dictionary of interned strings.  (Implemented
     by Oren Tirosh.)


File: python.info,  Node: 性能优化<12>,  Prev: String Changes,  Up: 其他语言特性修改<13>

1.14.16.2 性能优化
..................

   * The creation of new-style class instances has been made much
     faster; they’re now faster than classic classes!

   * The ‘sort()’ method of list objects has been extensively rewritten
     by Tim Peters, and the implementation is significantly faster.

   * Multiplication of large long integers is now much faster thanks to
     an implementation of Karatsuba multiplication, an algorithm that
     scales better than the O(n*n) required for the grade-school
     multiplication algorithm.  (Original patch by Christopher A. Craig,
     and significantly reworked by Tim Peters.)

   * The ‘SET_LINENO’ opcode is now gone.  This may provide a small
     speed increase, depending on your compiler’s idiosyncrasies.  See
     section *note Other Changes and Fixes: e15. for a longer
     explanation.  (Removed by Michael Hudson.)

   * ‘xrange()’ objects now have their own iterator, making ‘for i in
     xrange(n)’ slightly faster than ‘for i in range(n)’.  (Patch by
     Raymond Hettinger.)

   * A number of small rearrangements have been made in various hotspots
     to improve performance, such as inlining a function or removing
     some code.  (Implemented mostly by GvR, but lots of people have
     contributed single changes.)

The net result of the 2.3 optimizations is that Python 2.3 runs the
pystone benchmark around 25% faster than Python 2.2.


File: python.info,  Node: 新增，改进和弃用的模块<4>,  Next: Pymalloc A Specialized Object Allocator,  Prev: 其他语言特性修改<13>,  Up: Python 2 3 有什么新变化

1.14.17 新增，改进和弃用的模块
------------------------------

As usual, Python’s standard library received a number of enhancements
and bug fixes.  Here’s a partial list of the most notable changes,
sorted alphabetically by module name.  Consult the ‘Misc/NEWS’ file in
the source tree for a more complete list of changes, or look through the
CVS logs for all the details.

   * The *note array: 7. module now supports arrays of Unicode
     characters using the ‘'u'’ format character.  Arrays also now
     support using the ‘+=’ assignment operator to add another array’s
     contents, and the ‘*=’ assignment operator to repeat an array.
     (Contributed by Jason Orendorff.)

   * The ‘bsddb’ module has been replaced by version 4.1.6 of the
     PyBSDDB(1) package, providing a more complete interface to the
     transactional features of the BerkeleyDB library.

     The old version of the module has been renamed to ‘bsddb185’ and is
     no longer built automatically; you’ll have to edit ‘Modules/Setup’
     to enable it.  Note that the new ‘bsddb’ package is intended to be
     compatible with the old module, so be sure to file bugs if you
     discover any incompatibilities.  When upgrading to Python 2.3, if
     the new interpreter is compiled with a new version of the
     underlying BerkeleyDB library, you will almost certainly have to
     convert your database files to the new version.  You can do this
     fairly easily with the new scripts ‘db2pickle.py’ and
     ‘pickle2db.py’ which you will find in the distribution’s
     ‘Tools/scripts’ directory.  If you’ve already been using the
     PyBSDDB package and importing it as ‘bsddb3’, you will have to
     change your ‘import’ statements to import it as ‘bsddb’.

   * The new *note bz2: 14. module is an interface to the bz2 data
     compression library.  bz2-compressed data is usually smaller than
     corresponding *note zlib: 145.-compressed data.  (Contributed by
     Gustavo Niemeyer.)

   * A set of standard date/time types has been added in the new *note
     datetime: 31. module.  See the following section for more details.

   * The Distutils ‘Extension’ class now supports an extra constructor
     argument named `depends' for listing additional source files that
     an extension depends on.  This lets Distutils recompile the module
     if any of the dependency files are modified.  For example, if
     ‘sampmodule.c’ includes the header file ‘sample.h’, you would
     create the ‘Extension’ object like this:

          ext = Extension("samp",
                          sources=["sampmodule.c"],
                          depends=["sample.h"])

     Modifying ‘sample.h’ would then cause the module to be recompiled.
     (Contributed by Jeremy Hylton.)

   * Other minor changes to Distutils: it now checks for the ‘CC’,
     ‘CFLAGS’, ‘CPP’, ‘LDFLAGS’, and ‘CPPFLAGS’ environment variables,
     using them to override the settings in Python’s configuration
     (contributed by Robert Weber).

   * Previously the *note doctest: 67. module would only search the
     docstrings of public methods and functions for test cases, but it
     now also examines private ones as well.  The ‘DocTestSuite()’
     function creates a *note unittest.TestSuite: 6d7. object from a set
     of *note doctest: 67. tests.

   * The new ‘gc.get_referents(object)’ function returns a list of all
     the objects referenced by `object'.

   * The *note getopt: 87. module gained a new function, ‘gnu_getopt()’,
     that supports the same arguments as the existing *note getopt():
     87. function but uses GNU-style scanning mode.  The existing *note
     getopt(): 87. stops processing options as soon as a non-option
     argument is encountered, but in GNU-style mode processing
     continues, meaning that options and arguments can be mixed.  For
     example:

          >>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
          ([('-f', 'filename')], ['output', '-v'])
          >>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
          ([('-f', 'filename'), ('-v', '')], ['output'])

     （由 Peter Åstrand 贡献。）

   * The *note grp: 8b, *note pwd: d7, and *note resource: e1. modules
     now return enhanced tuples:

          >>> import grp
          >>> g = grp.getgrnam('amk')
          >>> g.gr_name, g.gr_gid
          ('amk', 500)

   * The *note gzip: 8c. module can now handle files exceeding 2 GiB.

   * The new *note heapq: 8e. module contains an implementation of a
     heap queue algorithm.  A heap is an array-like data structure that
     keeps items in a partially sorted order such that, for every index
     `k', ‘heap[k] <= heap[2*k+1]’ and ‘heap[k] <= heap[2*k+2]’.  This
     makes it quick to remove the smallest item, and inserting a new
     item while maintaining the heap property is O(lg n).  (See
     ‘https://xlinux.nist.gov/dads//HTML/priorityque.html’ for more
     information about the priority queue data structure.)

     The *note heapq: 8e. module provides ‘heappush()’ and ‘heappop()’
     functions for adding and removing items while maintaining the heap
     property on top of some other mutable Python sequence type.  Here’s
     an example that uses a Python list:

          >>> import heapq
          >>> heap = []
          >>> for item in [3, 7, 5, 11, 1]:
          ...    heapq.heappush(heap, item)
          ...
          >>> heap
          [1, 3, 5, 11, 7]
          >>> heapq.heappop(heap)
          1
          >>> heapq.heappop(heap)
          3
          >>> heap
          [5, 7, 11]

     （由 Kevin O’Connor 贡献。）

   * The IDLE integrated development environment has been updated using
     the code from the IDLEfork project
     (‘http://idlefork.sourceforge.net’).  The most notable feature is
     that the code being developed is now executed in a subprocess,
     meaning that there’s no longer any need for manual ‘reload()’
     operations.  IDLE’s core code has been incorporated into the
     standard library as the ‘idlelib’ package.

   * The *note imaplib: 98. module now supports IMAP over SSL.
     (Contributed by Piers Lauder and Tino Lange.)

   * The *note itertools: a4. contains a number of useful functions for
     use with iterators, inspired by various functions provided by the
     ML and Haskell languages.  For example,
     ‘itertools.ifilter(predicate, iterator)’ returns all elements in
     the iterator for which the function ‘predicate()’ returns *note
     True: 4a1, and ‘itertools.repeat(obj, N)’ returns ‘obj’ `N' times.
     There are a number of other functions in the module; see the
     package’s reference documentation for details.  (Contributed by
     Raymond Hettinger.)

   * Two new functions in the *note math: b2. module, ‘degrees(rads)’
     and ‘radians(degs)’, convert between radians and degrees.  Other
     functions in the *note math: b2. module such as *note math.sin():
     e17. and *note math.cos(): e18. have always required input values
     measured in radians.  Also, an optional `base' argument was added
     to *note math.log(): e19. to make it easier to compute logarithms
     for bases other than ‘e’ and ‘10’.  (Contributed by Raymond
     Hettinger.)

   * Several new POSIX functions (‘getpgid()’, ‘killpg()’, ‘lchown()’,
     ‘loadavg()’, ‘major()’, ‘makedev()’, ‘minor()’, and ‘mknod()’) were
     added to the *note posix: d2. module that underlies the *note os:
     c5. module.  (Contributed by Gustavo Niemeyer, Geert Jansen, and
     Denis S. Otkidach.)

   * In the *note os: c5. module, the ‘*stat()’ family of functions can
     now report fractions of a second in a timestamp.  Such time stamps
     are represented as floats, similar to the value returned by *note
     time.time(): 326.

     During testing, it was found that some applications will break if
     time stamps are floats.  For compatibility, when using the tuple
     interface of the ‘stat_result’ time stamps will be represented as
     integers.  When using named fields (a feature first introduced in
     Python 2.2), time stamps are still represented as integers, unless
     ‘os.stat_float_times()’ is invoked to enable float return values:

          >>> os.stat("/tmp").st_mtime
          1034791200
          >>> os.stat_float_times(True)
          >>> os.stat("/tmp").st_mtime
          1034791200.6335014

     In Python 2.4, the default will change to always returning floats.

     Application developers should enable this feature only if all their
     libraries work properly when confronted with floating point time
     stamps, or if they use the tuple API. If used, the feature should
     be activated on an application level instead of trying to enable it
     on a per-use basis.

   * The *note optparse: c4. module contains a new parser for
     command-line arguments that can convert option values to a
     particular Python type and will automatically generate a usage
     message.  See the following section for more details.

   * The old and never-documented ‘linuxaudiodev’ module has been
     deprecated, and a new version named *note ossaudiodev: c7. has been
     added.  The module was renamed because the OSS sound drivers can be
     used on platforms other than Linux, and the interface has also been
     tidied and brought up to date in various ways.  (Contributed by
     Greg Ward and Nicholas FitzRoy-Dale.)

   * The new *note platform: cf. module contains a number of functions
     that try to determine various properties of the platform you’re
     running on.  There are functions for getting the architecture, CPU
     type, the Windows OS version, and even the Linux distribution
     version.  (Contributed by Marc-André Lemburg.)

   * The parser objects provided by the ‘pyexpat’ module can now
     optionally buffer character data, resulting in fewer calls to your
     character data handler and therefore faster performance.  Setting
     the parser object’s ‘buffer_text’ attribute to *note True: 4a1.
     will enable buffering.

   * The ‘sample(population, k)’ function was added to the *note random:
     dd. module.  `population' is a sequence or ‘xrange’ object
     containing the elements of a population, and ‘sample()’ chooses `k'
     elements from the population without replacing chosen elements.
     `k' can be any value up to ‘len(population)’.  For example:

          >>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
          >>> random.sample(days, 3)      # Choose 3 elements
          ['St', 'Sn', 'Th']
          >>> random.sample(days, 7)      # Choose 7 elements
          ['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
          >>> random.sample(days, 7)      # Choose 7 again
          ['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
          >>> random.sample(days, 8)      # Can't choose eight
          Traceback (most recent call last):
            File "<stdin>", line 1, in ?
            File "random.py", line 414, in sample
                raise ValueError, "sample larger than population"
          ValueError: sample larger than population
          >>> random.sample(xrange(1,10000,2), 10)   # Choose ten odd nos. under 10000
          [3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]

     The *note random: dd. module now uses a new algorithm, the Mersenne
     Twister, implemented in C. It’s faster and more extensively studied
     than the previous algorithm.

     (All changes contributed by Raymond Hettinger.)

   * The *note readline: df. module also gained a number of new
     functions: ‘get_history_item()’, ‘get_current_history_length()’,
     and ‘redisplay()’.

   * The ‘rexec’ and ‘Bastion’ modules have been declared dead, and
     attempts to import them will fail with a *note RuntimeError: 2bb.
     New-style classes provide new ways to break out of the restricted
     execution environment provided by ‘rexec’, and no one has interest
     in fixing them or time to do so.  If you have applications using
     ‘rexec’, rewrite them to use something else.

     (Sticking with Python 2.2 or 2.1 will not make your applications
     any safer because there are known bugs in the ‘rexec’ module in
     those versions.  To repeat: if you’re using ‘rexec’, stop using it
     immediately.)

   * The ‘rotor’ module has been deprecated because the algorithm it
     uses for encryption is not believed to be secure.  If you need
     encryption, use one of the several AES Python modules that are
     available separately.

   * The *note shutil: ea. module gained a ‘move(src, dest)’ function
     that recursively moves a file or directory to a new location.

   * Support for more advanced POSIX signal handling was added to the
     *note signal: eb. but then removed again as it proved impossible to
     make it work reliably across platforms.

   * The *note socket: f0. module now supports timeouts.  You can call
     the ‘settimeout(t)’ method on a socket object to set a timeout of
     `t' seconds.  Subsequent socket operations that take longer than
     `t' seconds to complete will abort and raise a *note
     socket.timeout: c16. exception.

     The original timeout implementation was by Tim O’Malley.  Michael
     Gilfix integrated it into the Python *note socket: f0. module and
     shepherded it through a lengthy review.  After the code was checked
     in, Guido van Rossum rewrote parts of it.  (This is a good example
     of a collaborative development process in action.)

   * On Windows, the *note socket: f0. module now ships with Secure
     Sockets Layer (SSL) support.

   * The value of the C ‘PYTHON_API_VERSION’ macro is now exposed at the
     Python level as ‘sys.api_version’.  The current exception can be
     cleared by calling the new ‘sys.exc_clear()’ function.

   * The new *note tarfile: 102. module allows reading from and writing
     to ‘tar’-format archive files.  (Contributed by Lars Gustäbel.)

   * The new *note textwrap: 109. module contains functions for wrapping
     strings containing paragraphs of text.  The ‘wrap(text, width)’
     function takes a string and returns a list containing the text
     split into lines of no more than the chosen width.  The ‘fill(text,
     width)’ function returns a single string, reformatted to fit into
     lines no longer than the chosen width.  (As you can guess, ‘fill()’
     is built on top of ‘wrap()’.  For example:

          >>> import textwrap
          >>> paragraph = "Not a whit, we defy augury: ... more text ..."
          >>> textwrap.wrap(paragraph, 60)
          ["Not a whit, we defy augury: there's a special providence in",
           "the fall of a sparrow. If it be now, 'tis not to come; if it",
           ...]
          >>> print textwrap.fill(paragraph, 35)
          Not a whit, we defy augury: there's
          a special providence in the fall of
          a sparrow. If it be now, 'tis not
          to come; if it be not to come, it
          will be now; if it be not now, yet
          it will come: the readiness is all.
          >>>

     The module also contains a ‘TextWrapper’ class that actually
     implements the text wrapping strategy.  Both the ‘TextWrapper’
     class and the ‘wrap()’ and ‘fill()’ functions support a number of
     additional keyword arguments for fine-tuning the formatting;
     consult the module’s documentation for details.  (Contributed by
     Greg Ward.)

   * The ‘thread’ and *note threading: 10a. modules now have companion
     modules, ‘dummy_thread’ and *note dummy_threading: 68, that provide
     a do-nothing implementation of the ‘thread’ module’s interface for
     platforms where threads are not supported.  The intention is to
     simplify thread-aware modules (ones that `don’t' rely on threads to
     run) by putting the following code at the top:

          try:
              import threading as _threading
          except ImportError:
              import dummy_threading as _threading

     In this example, ‘_threading’ is used as the module name to make it
     clear that the module being used is not necessarily the actual
     *note threading: 10a. module.  Code can call functions and use
     classes in ‘_threading’ whether or not threads are supported,
     avoiding an *note if: def. statement and making the code slightly
     clearer.  This module will not magically make multithreaded code
     run without threads; code that waits for another thread to return
     or to do something will simply hang forever.

   * The *note time: 10b. module’s ‘strptime()’ function has long been
     an annoyance because it uses the platform C library’s ‘strptime()’
     implementation, and different platforms sometimes have odd bugs.
     Brett Cannon contributed a portable implementation that’s written
     in pure Python and should behave identically on all platforms.

   * The new *note timeit: 10c. module helps measure how long snippets
     of Python code take to execute.  The ‘timeit.py’ file can be run
     directly from the command line, or the module’s ‘Timer’ class can
     be imported and used directly.  Here’s a short example that figures
     out whether it’s faster to convert an 8-bit string to Unicode by
     appending an empty Unicode string to it or by using the ‘unicode()’
     function:

          import timeit

          timer1 = timeit.Timer('unicode("abc")')
          timer2 = timeit.Timer('"abc" + u""')

          # Run three trials
          print timer1.repeat(repeat=3, number=100000)
          print timer2.repeat(repeat=3, number=100000)

          # On my laptop this outputs:
          # [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]
          # [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]

   * The ‘Tix’ module has received various bug fixes and updates for the
     current version of the Tix package.

   * The ‘Tkinter’ module now works with a thread-enabled version of
     Tcl.  Tcl’s threading model requires that widgets only be accessed
     from the thread in which they’re created; accesses from another
     thread can cause Tcl to panic.  For certain Tcl interfaces,
     ‘Tkinter’ will now automatically avoid this when a widget is
     accessed from a different thread by marshalling a command, passing
     it to the correct thread, and waiting for the results.  Other
     interfaces can’t be handled automatically but ‘Tkinter’ will now
     raise an exception on such an access so that you can at least find
     out about the problem.  See
     ‘https://mail.python.org/pipermail/python-dev/2002-December/031107.html’
     for a more detailed explanation of this change.  (Implemented by
     Martin von Löwis.)

   * Calling Tcl methods through ‘_tkinter’ no longer returns only
     strings.  Instead, if Tcl returns other objects those objects are
     converted to their Python equivalent, if one exists, or wrapped
     with a ‘_tkinter.Tcl_Obj’ object if no Python equivalent exists.
     This behavior can be controlled through the ‘wantobjects()’ method
     of ‘tkapp’ objects.

     When using ‘_tkinter’ through the ‘Tkinter’ module (as most Tkinter
     applications will), this feature is always activated.  It should
     not cause compatibility problems, since Tkinter would always
     convert string results to Python types where possible.

     If any incompatibilities are found, the old behavior can be
     restored by setting the ‘wantobjects’ variable in the ‘Tkinter’
     module to false before creating the first ‘tkapp’ object.

          import Tkinter
          Tkinter.wantobjects = 0

     Any breakage caused by this change should be reported as a bug.

   * The ‘UserDict’ module has a new ‘DictMixin’ class which defines all
     dictionary methods for classes that already have a minimum mapping
     interface.  This greatly simplifies writing classes that need to be
     substitutable for dictionaries, such as the classes in the *note
     shelve: e8. module.

     Adding the mix-in as a superclass provides the full dictionary
     interface whenever the class defines *note __getitem__(): 280,
     *note __setitem__(): c6a, *note __delitem__(): c6b, and ‘keys()’.
     For example:

          >>> import UserDict
          >>> class SeqDict(UserDict.DictMixin):
          ...     """Dictionary lookalike implemented with lists."""
          ...     def __init__(self):
          ...         self.keylist = []
          ...         self.valuelist = []
          ...     def __getitem__(self, key):
          ...         try:
          ...             i = self.keylist.index(key)
          ...         except ValueError:
          ...             raise KeyError
          ...         return self.valuelist[i]
          ...     def __setitem__(self, key, value):
          ...         try:
          ...             i = self.keylist.index(key)
          ...             self.valuelist[i] = value
          ...         except ValueError:
          ...             self.keylist.append(key)
          ...             self.valuelist.append(value)
          ...     def __delitem__(self, key):
          ...         try:
          ...             i = self.keylist.index(key)
          ...         except ValueError:
          ...             raise KeyError
          ...         self.keylist.pop(i)
          ...         self.valuelist.pop(i)
          ...     def keys(self):
          ...         return list(self.keylist)
          ...
          >>> s = SeqDict()
          >>> dir(s)      # See that other dictionary methods are implemented
          ['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
           '__init__', '__iter__', '__len__', '__module__', '__repr__',
           '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
           'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
           'setdefault', 'update', 'valuelist', 'values']

     （由 Raymond Hettinger 贡献。）

   * The DOM implementation in *note xml.dom.minidom: 136. can now
     generate XML output in a particular encoding by providing an
     optional encoding argument to the ‘toxml()’ and ‘toprettyxml()’
     methods of DOM nodes.

   * The ‘xmlrpclib’ module now supports an XML-RPC extension for
     handling nil data values such as Python’s ‘None’.  Nil values are
     always supported on unmarshalling an XML-RPC response.  To generate
     requests containing ‘None’, you must supply a true value for the
     `allow_none' parameter when creating a ‘Marshaller’ instance.

   * The new ‘DocXMLRPCServer’ module allows writing self-documenting
     XML-RPC servers.  Run it in demo mode (as a program) to see it in
     action.  Pointing the Web browser to the RPC server produces
     pydoc-style documentation; pointing xmlrpclib to the server allows
     invoking the actual methods.  (Contributed by Brian Quinlan.)

   * Support for internationalized domain names (RFCs 3454, 3490, 3491,
     and 3492) has been added.  The "idna" encoding can be used to
     convert between a Unicode domain name and the ASCII-compatible
     encoding (ACE) of that name.

          >{}>{}> u"www.Alliancefrançaise.nu".encode("idna")
          'www.xn--alliancefranaise-npb.nu'

     The *note socket: f0. module has also been extended to
     transparently convert Unicode hostnames to the ACE version before
     passing them to the C library.  Modules that deal with hostnames
     such as ‘httplib’ and *note ftplib: 84.) also support Unicode host
     names; ‘httplib’ also sends HTTP ‘Host’ headers using the ACE
     version of the domain name.  *note urllib: 11e. supports Unicode
     URLs with non-ASCII host names as long as the ‘path’ part of the
     URL is ASCII only.

     To implement this change, the *note stringprep: f8. module, the
     ‘mkstringprep’ tool and the ‘punycode’ encoding have been added.

* Menu:

* Date/Time 类型::
* optparse 模块::

   ---------- Footnotes ----------

   (1) http://pybsddb.sourceforge.net


File: python.info,  Node: Date/Time 类型,  Next: optparse 模块,  Up: 新增，改进和弃用的模块<4>

1.14.17.1 Date/Time 类型
........................

Date and time types suitable for expressing timestamps were added as the
*note datetime: 31. module.  The types don’t support different calendars
or many fancy features, and just stick to the basics of representing
time.

The three primary types are: ‘date’, representing a day, month, and
year; *note time: 4fb, consisting of hour, minute, and second; and *note
datetime: 195, which contains all the attributes of both ‘date’ and
*note time: 4fb.  There’s also a ‘timedelta’ class representing
differences between two points in time, and time zone logic is
implemented by classes inheriting from the abstract ‘tzinfo’ class.

You can create instances of ‘date’ and *note time: 4fb. by either
supplying keyword arguments to the appropriate constructor, e.g.
‘datetime.date(year=1972, month=10, day=15)’, or by using one of a
number of class methods.  For example, the ‘date.today()’ class method
returns the current local date.

Once created, instances of the date/time classes are all immutable.
There are a number of methods for producing formatted strings from
objects:

     >>> import datetime
     >>> now = datetime.datetime.now()
     >>> now.isoformat()
     '2002-12-30T21:27:03.994956'
     >>> now.ctime()  # Only available on date, datetime
     'Mon Dec 30 21:27:03 2002'
     >>> now.strftime('%Y %d %b')
     '2002 30 Dec'

The ‘replace()’ method allows modifying one or more fields of a ‘date’
or *note datetime: 195. instance, returning a new instance:

     >>> d = datetime.datetime.now()
     >>> d
     datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
     >>> d.replace(year=2001, hour = 12)
     datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
     >>>

Instances can be compared, hashed, and converted to strings (the result
is the same as that of ‘isoformat()’).  ‘date’ and *note datetime: 195.
instances can be subtracted from each other, and added to ‘timedelta’
instances.  The largest missing feature is that there’s no standard
library support for parsing strings and getting back a ‘date’ or *note
datetime: 195.

For more information, refer to the module’s reference documentation.
(Contributed by Tim Peters.)


File: python.info,  Node: optparse 模块,  Prev: Date/Time 类型,  Up: 新增，改进和弃用的模块<4>

1.14.17.2 optparse 模块
.......................

The *note getopt: 87. module provides simple parsing of command-line
arguments.  The new *note optparse: c4. module (originally named Optik)
provides more elaborate command-line parsing that follows the Unix
conventions, automatically creates the output for ‘--help’, and can
perform different actions for different options.

You start by creating an instance of ‘OptionParser’ and telling it what
your program’s options are.

     import sys
     from optparse import OptionParser

     op = OptionParser()
     op.add_option('-i', '--input',
                   action='store', type='string', dest='input',
                   help='set input filename')
     op.add_option('-l', '--length',
                   action='store', type='int', dest='length',
                   help='set maximum length of output')

Parsing a command line is then done by calling the ‘parse_args()’
method.

     options, args = op.parse_args(sys.argv[1:])
     print options
     print args

This returns an object containing all of the option values, and a list
of strings containing the remaining arguments.

Invoking the script with the various arguments now works as you’d expect
it to.  Note that the length argument is automatically converted to an
integer.

     $ ./python opt.py -i data arg1
     <Values at 0x400cad4c: {'input': 'data', 'length': None}>
     ['arg1']
     $ ./python opt.py --input=data --length=4
     <Values at 0x400cad2c: {'input': 'data', 'length': 4}>
     []
     $

The help message is automatically generated for you:

     $ ./python opt.py --help
     usage: opt.py [options]

     options:
       -h, --help            show this help message and exit
       -iINPUT, --input=INPUT
                             set input filename
       -lLENGTH, --length=LENGTH
                             set maximum length of output
     $

有关更多详细信息，请参见模块的文档。

Optik was written by Greg Ward, with suggestions from the readers of the
Getopt SIG.


File: python.info,  Node: Pymalloc A Specialized Object Allocator,  Next: 构建和 C API 的改变<12>,  Prev: 新增，改进和弃用的模块<4>,  Up: Python 2 3 有什么新变化

1.14.18 Pymalloc: A Specialized Object Allocator
------------------------------------------------

Pymalloc, a specialized object allocator written by Vladimir Marangozov,
was a feature added to Python 2.1.  Pymalloc is intended to be faster
than the system ‘malloc()’ and to have less memory overhead for
allocation patterns typical of Python programs.  The allocator uses C’s
‘malloc()’ function to get large pools of memory and then fulfills
smaller memory requests from these pools.

In 2.1 and 2.2, pymalloc was an experimental feature and wasn’t enabled
by default; you had to explicitly enable it when compiling Python by
providing the ‘--with-pymalloc’ option to the ‘configure’ script.  In
2.3, pymalloc has had further enhancements and is now enabled by
default; you’ll have to supply ‘--without-pymalloc’ to disable it.

This change is transparent to code written in Python; however, pymalloc
may expose bugs in C extensions.  Authors of C extension modules should
test their code with pymalloc enabled, because some incorrect code may
cause core dumps at runtime.

There’s one particularly common error that causes problems.  There are a
number of memory allocation functions in Python’s C API that have
previously just been aliases for the C library’s ‘malloc()’ and
‘free()’, meaning that if you accidentally called mismatched functions
the error wouldn’t be noticeable.  When the object allocator is enabled,
these functions aren’t aliases of ‘malloc()’ and ‘free()’ any more, and
calling the wrong function to free memory may get you a core dump.  For
example, if memory was allocated using *note PyObject_Malloc(): 510, it
has to be freed using *note PyObject_Free(): 50c, not ‘free()’.  A few
modules included with Python fell afoul of this and had to be fixed;
doubtless there are more third-party modules that will have the same
problem.

As part of this change, the confusing multiple interfaces for allocating
memory have been consolidated down into two API families.  Memory
allocated with one family must not be manipulated with functions from
the other family.  There is one family for allocating chunks of memory
and another family of functions specifically for allocating Python
objects.

   * To allocate and free an undistinguished chunk of memory use the
     "raw memory" family: *note PyMem_Malloc(): 50d, *note
     PyMem_Realloc(): 977, and *note PyMem_Free(): db1.

   * The "object memory" family is the interface to the pymalloc
     facility described above and is biased towards a large number of
     "small" allocations: *note PyObject_Malloc(): 510, *note
     PyObject_Realloc(): db2, and *note PyObject_Free(): 50c.

   * To allocate and free Python objects, use the "object" family *note
     PyObject_New(): 2d3, *note PyObject_NewVar(): 2d4, and *note
     PyObject_Del(): e1e.

Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides
debugging features to catch memory overwrites and doubled frees in both
extension modules and in the interpreter itself.  To enable this
support, compile a debugging version of the Python interpreter by
running ‘configure’ with ‘--with-pydebug’.

To aid extension writers, a header file ‘Misc/pymemcompat.h’ is
distributed with the source to Python 2.3 that allows Python extensions
to use the 2.3 interfaces to memory allocation while compiling against
any version of Python since 1.5.2.  You would copy the file from
Python’s source distribution and bundle it with the source of your
extension.

参见
....

‘https://hg.python.org/cpython/file/default/Objects/obmalloc.c’

     For the full details of the pymalloc implementation, see the
     comments at the top of the file ‘Objects/obmalloc.c’ in the Python
     source code.  The above link points to the file within the
     python.org SVN browser.


File: python.info,  Node: 构建和 C API 的改变<12>,  Next: Other Changes and Fixes<2>,  Prev: Pymalloc A Specialized Object Allocator,  Up: Python 2 3 有什么新变化

1.14.19 构建和 C API 的改变
---------------------------

Changes to Python’s build process and to the C API include:

   * The cycle detection implementation used by the garbage collection
     has proven to be stable, so it’s now been made mandatory.  You can
     no longer compile Python without it, and the ‘--with-cycle-gc’
     switch to ‘configure’ has been removed.

   * Python can now optionally be built as a shared library
     (‘libpython2.3.so’) by supplying ‘--enable-shared’ when running
     Python’s ‘configure’ script.  (Contributed by Ondrej Palkovsky.)

   * The ‘DL_EXPORT’ and ‘DL_IMPORT’ macros are now deprecated.
     Initialization functions for Python extension modules should now be
     declared using the new macro ‘PyMODINIT_FUNC’, while the Python
     core will generally use the ‘PyAPI_FUNC’ and ‘PyAPI_DATA’ macros.

   * The interpreter can be compiled without any docstrings for the
     built-in functions and modules by supplying ‘--without-doc-strings’
     to the ‘configure’ script.  This makes the Python executable about
     10% smaller, but will also mean that you can’t get help for
     Python’s built-ins.  (Contributed by Gustavo Niemeyer.)

   * The ‘PyArg_NoArgs()’ macro is now deprecated, and code that uses it
     should be changed.  For Python 2.2 and later, the method definition
     table can specify the *note METH_NOARGS: e20. flag, signalling that
     there are no arguments, and the argument checking can then be
     removed.  If compatibility with pre-2.2 versions of Python is
     important, the code could use ‘PyArg_ParseTuple(args, "")’ instead,
     but this will be slower than using *note METH_NOARGS: e20.

   * *note PyArg_ParseTuple(): 26b. accepts new format characters for
     various sizes of unsigned integers: ‘B’ for ‘unsigned char’, ‘H’
     for ‘unsigned short int’, ‘I’ for ‘unsigned int’, and ‘K’ for
     ‘unsigned long long’.

   * A new function, ‘PyObject_DelItemString(mapping, char *key)’ was
     added as shorthand for ‘PyObject_DelItem(mapping,
     PyString_New(key))’.

   * File objects now manage their internal string buffer differently,
     increasing it exponentially when needed.  This results in the
     benchmark tests in ‘Lib/test/test_bufio.py’ speeding up
     considerably (from 57 seconds to 1.7 seconds, according to one
     measurement).

   * It’s now possible to define class and static methods for a C
     extension type by setting either the *note METH_CLASS: e21. or
     *note METH_STATIC: e22. flags in a method’s *note PyMethodDef: e23.
     structure.

   * Python now includes a copy of the Expat XML parser’s source code,
     removing any dependence on a system version or local installation
     of Expat.

   * If you dynamically allocate type objects in your extension, you
     should be aware of a change in the rules relating to the
     ‘__module__’ and *note __name__: c6f. attributes.  In summary, you
     will want to ensure the type’s dictionary contains a ‘'__module__'’
     key; making the module name the part of the type name leading up to
     the final period will no longer have the desired effect.  For more
     detail, read the API reference documentation or the source.

* Menu:

* Port-Specific Changes: Port-Specific Changes<3>.


File: python.info,  Node: Port-Specific Changes<3>,  Up: 构建和 C API 的改变<12>

1.14.19.1 Port-Specific Changes
...............................

Support for a port to IBM’s OS/2 using the EMX runtime environment was
merged into the main Python source tree.  EMX is a POSIX emulation layer
over the OS/2 system APIs.  The Python port for EMX tries to support all
the POSIX-like capability exposed by the EMX runtime, and mostly
succeeds; ‘fork()’ and *note fcntl(): 7e. are restricted by the
limitations of the underlying emulation layer.  The standard OS/2 port,
which uses IBM’s Visual Age compiler, also gained support for
case-sensitive import semantics as part of the integration of the EMX
port into CVS. (Contributed by Andrew MacIntyre.)

On MacOS, most toolbox modules have been weaklinked to improve backward
compatibility.  This means that modules will no longer fail to load if a
single routine is missing on the current OS version.  Instead calling
the missing routine will raise an exception.  (Contributed by Jack
Jansen.)

The RPM spec files, found in the ‘Misc/RPM/’ directory in the Python
source distribution, were updated for 2.3.  (Contributed by Sean
Reifschneider.)

Other new platforms now supported by Python include AtheOS
(‘http://www.atheos.cx/’), GNU/Hurd, and OpenVMS.


File: python.info,  Node: Other Changes and Fixes<2>,  Next: 移植到 Python 2 3,  Prev: 构建和 C API 的改变<12>,  Up: Python 2 3 有什么新变化

1.14.20 Other Changes and Fixes
-------------------------------

As usual, there were a bunch of other improvements and bugfixes
scattered throughout the source tree.  A search through the CVS change
logs finds there were 523 patches applied and 514 bugs fixed between
Python 2.2 and 2.3.  Both figures are likely to be underestimates.

Some of the more notable changes are:

   * If the *note PYTHONINSPECT: e26. environment variable is set, the
     Python interpreter will enter the interactive prompt after running
     a Python program, as if Python had been invoked with the *note -i:
     e27. option.  The environment variable can be set before running
     the Python interpreter, or it can be set by the Python program as
     part of its execution.

   * The ‘regrtest.py’ script now provides a way to allow "all resources
     except `foo'."  A resource name passed to the ‘-u’ option can now
     be prefixed with a hyphen (‘'-'’) to mean "remove this resource."
     For example, the option ’‘-uall,-bsddb’’ could be used to enable
     the use of all resources except ‘bsddb’.

   * The tools used to build the documentation now work under Cygwin as
     well as Unix.

   * The ‘SET_LINENO’ opcode has been removed.  Back in the mists of
     time, this opcode was needed to produce line numbers in tracebacks
     and support trace functions (for, e.g., *note pdb: ca.).  Since
     Python 1.5, the line numbers in tracebacks have been computed using
     a different mechanism that works with "python -O". For Python 2.3
     Michael Hudson implemented a similar scheme to determine when to
     call the trace function, removing the need for ‘SET_LINENO’
     entirely.

     It would be difficult to detect any resulting difference from
     Python code, apart from a slight speed up when Python is run
     without *note -O: 694.

     C extensions that access the ‘f_lineno’ field of frame objects
     should instead call ‘PyCode_Addr2Line(f->f_code, f->f_lasti)’.
     This will have the added effect of making the code work as desired
     under "python -O" in earlier versions of Python.

     A nifty new feature is that trace functions can now assign to the
     ‘f_lineno’ attribute of frame objects, changing the line that will
     be executed next.  A ‘jump’ command has been added to the *note
     pdb: ca. debugger taking advantage of this new feature.
     (Implemented by Richie Hindle.)


File: python.info,  Node: 移植到 Python 2 3,  Next: 致谢<5>,  Prev: Other Changes and Fixes<2>,  Up: Python 2 3 有什么新变化

1.14.21 移植到 Python 2.3
-------------------------

This section lists previously described changes that may require changes
to your code:

   * *note yield: 190. is now always a keyword; if it’s used as a
     variable name in your code, a different name must be chosen.

   * For strings `X' and `Y', ‘X in Y’ now works if `X' is more than one
     character long.

   * The *note int(): 185. type constructor will now return a long
     integer instead of raising an *note OverflowError: 968. when a
     string or floating-point number is too large to fit into an
     integer.

   * If you have Unicode strings that contain 8-bit characters, you must
     declare the file’s encoding (UTF-8, Latin-1, or whatever) by adding
     a comment to the top of the file.  See section *note PEP 263;
     Source Code Encodings: df1. for more information.

   * Calling Tcl methods through ‘_tkinter’ no longer returns only
     strings.  Instead, if Tcl returns other objects those objects are
     converted to their Python equivalent, if one exists, or wrapped
     with a ‘_tkinter.Tcl_Obj’ object if no Python equivalent exists.

   * Large octal and hex literals such as ‘0xffffffff’ now trigger a
     *note FutureWarning: 32e.  Currently they’re stored as 32-bit
     numbers and result in a negative value, but in Python 2.4 they’ll
     become positive long integers.

     There are a few ways to fix this warning.  If you really need a
     positive number, just add an ‘L’ to the end of the literal.  If
     you’re trying to get a 32-bit integer with low bits set and have
     previously used an expression such as ‘~(1 << 31)’, it’s probably
     clearest to start with all bits set and clear the desired upper
     bits.  For example, to clear just the top bit (bit 31), you could
     write ‘0xffffffffL &~(1L<<31)’.

   * You can no longer disable assertions by assigning to ‘__debug__’.

   * The Distutils ‘setup()’ function has gained various new keyword
     arguments such as `depends'.  Old versions of the Distutils will
     abort if passed unknown keywords.  A solution is to check for the
     presence of the new ‘get_distutil_options()’ function in your
     ‘setup.py’ and only uses the new keywords with a version of the
     Distutils that supports them:

          from distutils import core

          kw = {'sources': 'foo.c', ...}
          if hasattr(core, 'get_distutil_options'):
              kw['depends'] = ['foo.h']
          ext = Extension(**kw)

   * Using ‘None’ as a variable name will now result in a *note
     SyntaxWarning: 192. warning.

   * Names of extension types defined by the modules included with
     Python now contain the module and a ‘'.'’ in front of the type
     name.


File: python.info,  Node: 致谢<5>,  Prev: 移植到 Python 2 3,  Up: Python 2 3 有什么新变化

1.14.22 致谢
------------

作者感谢以下人员为本文的各种草案提供建议，更正和帮助： Jeff Bauer, Simon
Brunning, Brett Cannon, Michael Chermside, Andrew Dalke, Scott David
Daniels, Fred L. Drake, Jr., David Fraser, Kelly Gerber, Raymond
Hettinger, Michael Hudson, Chris Lambert, Detlef Lannert, Martin von
Löwis, Andrew MacIntyre, Lalo Martins, Chad Netzer, Gustavo Niemeyer,
Neal Norwitz, Hans Nowak, Chris Reedy, Francesco Ricciardi, Vinay Sajip,
Neil Schemenauer, Roman Suzi, Jason Tishler, Just van Rossum.


File: python.info,  Node: Python 2 2 有什么新变化,  Next: Python 2 1 有什么新变化,  Prev: Python 2 3 有什么新变化,  Up: Python的新变化

1.15 Python 2.2 有什么新变化
============================


作者: A.M. Kuchling

* Menu:

* 概述::
* PEPs 252 and 253; Type and Class Changes: PEPs 252 and 253 Type and Class Changes.
* PEP 234; Iterators: PEP 234 Iterators.
* PEP 255; Simple Generators: PEP 255 Simple Generators<2>.
* PEP 237; 统一长整数和整数: PEP 237 统一长整数和整数<2>.
* PEP 238; Changing the Division Operator: PEP 238 Changing the Division Operator.
* Unicode Changes::
* PEP 227; Nested Scopes: PEP 227 Nested Scopes.
* 新增和改进的模块: 新增和改进的模块<3>.
* Interpreter Changes and Fixes::
* Other Changes and Fixes: Other Changes and Fixes<3>.
* 致谢: 致谢<6>.


File: python.info,  Node: 概述,  Next: PEPs 252 and 253 Type and Class Changes,  Up: Python 2 2 有什么新变化

1.15.1 概述
-----------

This article explains the new features in Python 2.2.2, released on
October 14, 2002.  Python 2.2.2 is a bugfix release of Python 2.2,
originally released on December 21, 2001.

Python 2.2 can be thought of as the "cleanup release".  There are some
features such as generators and iterators that are completely new, but
most of the changes, significant and far-reaching though they may be,
are aimed at cleaning up irregularities and dark corners of the language
design.

This article doesn’t attempt to provide a complete specification of the
new features, but instead provides a convenient overview.  For full
details, you should refer to the documentation for Python 2.2, such as
the Python Library Reference(1) and the Python Reference Manual(2).  If
you want to understand the complete implementation and design rationale
for a change, refer to the PEP for a particular new feature.

   ---------- Footnotes ----------

   (1) https://docs.python.org/2.2/lib/lib.html

   (2) https://docs.python.org/2.2/ref/ref.html


File: python.info,  Node: PEPs 252 and 253 Type and Class Changes,  Next: PEP 234 Iterators,  Prev: 概述,  Up: Python 2 2 有什么新变化

1.15.2 PEPs 252 and 253: Type and Class Changes
-----------------------------------------------

The largest and most far-reaching changes in Python 2.2 are to Python’s
model of objects and classes.  The changes should be backward
compatible, so it’s likely that your code will continue to run
unchanged, but the changes provide some amazing new capabilities.
Before beginning this, the longest and most complicated section of this
article, I’ll provide an overview of the changes and offer some
comments.

A long time ago I wrote a Web page listing flaws in Python’s design.
One of the most significant flaws was that it’s impossible to subclass
Python types implemented in C. In particular, it’s not possible to
subclass built-in types, so you can’t just subclass, say, lists in order
to add a single useful method to them.  The ‘UserList’ module provides a
class that supports all of the methods of lists and that can be
subclassed further, but there’s lots of C code that expects a regular
Python list and won’t accept a ‘UserList’ instance.

Python 2.2 fixes this, and in the process adds some exciting new
capabilities.  A brief summary:

   * You can subclass built-in types such as lists and even integers,
     and your subclasses should work in every place that requires the
     original type.

   * It’s now possible to define static and class methods, in addition
     to the instance methods available in previous versions of Python.

   * It’s also possible to automatically call methods on accessing or
     setting an instance attribute by using a new mechanism called
     `properties'.  Many uses of *note __getattr__(): 323. can be
     rewritten to use properties instead, making the resulting code
     simpler and faster.  As a small side benefit, attributes can now
     have docstrings, too.

   * The list of legal attributes for an instance can be limited to a
     particular set using `slots', making it possible to safeguard
     against typos and perhaps make more optimizations possible in
     future versions of Python.

Some users have voiced concern about all these changes.  Sure, they say,
the new features are neat and lend themselves to all sorts of tricks
that weren’t possible in previous versions of Python, but they also make
the language more complicated.  Some people have said that they’ve
always recommended Python for its simplicity, and feel that its
simplicity is being lost.

Personally, I think there’s no need to worry.  Many of the new features
are quite esoteric, and you can write a lot of Python code without ever
needed to be aware of them.  Writing a simple class is no more difficult
than it ever was, so you don’t need to bother learning or teaching them
unless they’re actually needed.  Some very complicated tasks that were
previously only possible from C will now be possible in pure Python, and
to my mind that’s all for the better.

I’m not going to attempt to cover every single corner case and small
change that were required to make the new features work.  Instead this
section will paint only the broad strokes.  See section *note Related
Links: e2f, "Related Links", for further sources of information about
Python 2.2’s new object model.

* Menu:

* Old and New Classes::
* Descriptors::
* Multiple Inheritance; The Diamond Rule: Multiple Inheritance The Diamond Rule.
* Attribute Access::
* Related Links::


File: python.info,  Node: Old and New Classes,  Next: Descriptors,  Up: PEPs 252 and 253 Type and Class Changes

1.15.2.1 Old and New Classes
............................

First, you should know that Python 2.2 really has two kinds of classes:
classic or old-style classes, and new-style classes.  The old-style
class model is exactly the same as the class model in earlier versions
of Python.  All the new features described in this section apply only to
new-style classes.  This divergence isn’t intended to last forever;
eventually old-style classes will be dropped, possibly in Python 3.0.

So how do you define a new-style class?  You do it by subclassing an
existing new-style class.  Most of Python’s built-in types, such as
integers, lists, dictionaries, and even files, are new-style classes
now.  A new-style class named *note object: 2b1, the base class for all
built-in types, has also been added so if no built-in type is suitable,
you can just subclass *note object: 2b1.:

     class C(object):
         def __init__ (self):
             ...
         ...

This means that *note class: c72. statements that don’t have any base
classes are always classic classes in Python 2.2.  (Actually you can
also change this by setting a module-level variable named
‘__metaclass__’ — see PEP 253(1) for the details — but it’s easier to
just subclass *note object: 2b1.)

The type objects for the built-in types are available as built-ins,
named using a clever trick.  Python has always had built-in functions
named *note int(): 185, *note float(): 188, and *note str(): 339.  In
2.2, they aren’t functions any more, but type objects that behave as
factories when called.

     >>> int
     <type 'int'>
     >>> int('123')
     123

To make the set of types complete, new type objects such as *note
dict(): 1b9. and ‘file()’ have been added.  Here’s a more interesting
example, adding a ‘lock()’ method to file objects:

     class LockableFile(file):
         def lock (self, operation, length=0, start=0, whence=0):
             import fcntl
             return fcntl.lockf(self.fileno(), operation,
                                length, start, whence)

The now-obsolete ‘posixfile’ module contained a class that emulated all
of a file object’s methods and also added a ‘lock()’ method, but this
class couldn’t be passed to internal functions that expected a built-in
file, something which is possible with our new ‘LockableFile’.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0253


File: python.info,  Node: Descriptors,  Next: Multiple Inheritance The Diamond Rule,  Prev: Old and New Classes,  Up: PEPs 252 and 253 Type and Class Changes

1.15.2.2 Descriptors
....................

In previous versions of Python, there was no consistent way to discover
what attributes and methods were supported by an object.  There were
some informal conventions, such as defining ‘__members__’ and
‘__methods__’ attributes that were lists of names, but often the author
of an extension type or a class wouldn’t bother to define them.  You
could fall back on inspecting the *note __dict__: 504. of an object, but
when class inheritance or an arbitrary *note __getattr__(): 323. hook
were in use this could still be inaccurate.

The one big idea underlying the new class model is that an API for
describing the attributes of an object using `descriptors' has been
formalized.  Descriptors specify the value of an attribute, stating
whether it’s a method or a field.  With the descriptor API, static
methods and class methods become possible, as well as more exotic
constructs.

Attribute descriptors are objects that live inside class objects, and
have a few attributes of their own:

   * *note __name__: c6f. is the attribute’s name.

   * ‘__doc__’ is the attribute’s docstring.

   * ‘__get__(object)’ is a method that retrieves the attribute value
     from `object'.

   * ‘__set__(object, value)’ sets the attribute on `object' to `value'.

   * ‘__delete__(object, value)’ deletes the `value' attribute of
     `object'.

For example, when you write ‘obj.x’, the steps that Python actually
performs are:

     descriptor = obj.__class__.x
     descriptor.__get__(obj)

For methods, ‘descriptor.__get__()’ returns a temporary object that’s
callable, and wraps up the instance and the method to be called on it.
This is also why static methods and class methods are now possible; they
have descriptors that wrap up just the method, or the method and the
class.  As a brief explanation of these new kinds of methods, static
methods aren’t passed the instance, and therefore resemble regular
functions.  Class methods are passed the class of the object, but not
the object itself.  Static and class methods are defined like this:

     class C(object):
         def f(arg1, arg2):
             ...
         f = staticmethod(f)

         def g(cls, arg1, arg2):
             ...
         g = classmethod(g)

The *note staticmethod(): 1da. function takes the function ‘f()’, and
returns it wrapped up in a descriptor so it can be stored in the class
object.  You might expect there to be special syntax for creating such
methods (‘def static f’, ‘defstatic f()’, or something like that) but no
such syntax has been defined yet; that’s been left for future versions
of Python.

More new features, such as slots and properties, are also implemented as
new kinds of descriptors, and it’s not difficult to write a descriptor
class that does something novel.  For example, it would be possible to
write a descriptor class that made it possible to write Eiffel-style
preconditions and postconditions for a method.  A class that used this
feature might be defined like this:

     from eiffel import eiffelmethod

     class C(object):
         def f(self, arg1, arg2):
             # The actual function
             ...
         def pre_f(self):
             # Check preconditions
             ...
         def post_f(self):
             # Check postconditions
             ...

         f = eiffelmethod(f, pre_f, post_f)

Note that a person using the new ‘eiffelmethod()’ doesn’t have to
understand anything about descriptors.  This is why I think the new
features don’t increase the basic complexity of the language.  There
will be a few wizards who need to know about it in order to write
‘eiffelmethod()’ or the ZODB or whatever, but most users will just write
code on top of the resulting libraries and ignore the implementation
details.


File: python.info,  Node: Multiple Inheritance The Diamond Rule,  Next: Attribute Access,  Prev: Descriptors,  Up: PEPs 252 and 253 Type and Class Changes

1.15.2.3 Multiple Inheritance: The Diamond Rule
...............................................

Multiple inheritance has also been made more useful through changing the
rules under which names are resolved.  Consider this set of classes
(diagram taken from PEP 253(1) by Guido van Rossum):

           class A:
             ^ ^  def save(self): ...
            /   \
           /     \
          /       \
         /         \
     class B     class C:
         ^         ^  def save(self): ...
          \       /
           \     /
            \   /
             \ /
           class D

The lookup rule for classic classes is simple but not very smart; the
base classes are searched depth-first, going from left to right.  A
reference to ‘D.save()’ will search the classes ‘D’, ‘B’, and then ‘A’,
where ‘save()’ would be found and returned.  ‘C.save()’ would never be
found at all.  This is bad, because if ‘C’’s ‘save()’ method is saving
some internal state specific to ‘C’, not calling it will result in that
state never getting saved.

New-style classes follow a different algorithm that’s a bit more
complicated to explain, but does the right thing in this situation.
(Note that Python 2.3 changes this algorithm to one that produces the
same results in most cases, but produces more useful results for really
complicated inheritance graphs.)

  1. List all the base classes, following the classic lookup rule and
     include a class multiple times if it’s visited repeatedly.  In the
     above example, the list of visited classes is [‘D’, ‘B’, ‘A’, ‘C’,
     ‘A’].

  2. Scan the list for duplicated classes.  If any are found, remove all
     but one occurrence, leaving the `last' one in the list.  In the
     above example, the list becomes [‘D’, ‘B’, ‘C’, ‘A’] after dropping
     duplicates.

Following this rule, referring to ‘D.save()’ will return ‘C.save()’,
which is the behaviour we’re after.  This lookup rule is the same as the
one followed by Common Lisp.  A new built-in function, *note super():
4eb, provides a way to get at a class’s superclasses without having to
reimplement Python’s algorithm.  The most commonly used form will be
‘super(class, obj)’, which returns a bound superclass object (not the
actual class object).  This form will be used in methods to call a
method in the superclass; for example, ‘D’’s ‘save()’ method would look
like this:

     class D (B,C):
         def save (self):
             # Call superclass .save()
             super(D, self).save()
             # Save D's private information here
             ...

*note super(): 4eb. can also return unbound superclass objects when
called as ‘super(class)’ or ‘super(class1, class2)’, but this probably
won’t often be useful.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0253


File: python.info,  Node: Attribute Access,  Next: Related Links,  Prev: Multiple Inheritance The Diamond Rule,  Up: PEPs 252 and 253 Type and Class Changes

1.15.2.4 Attribute Access
.........................

A fair number of sophisticated Python classes define hooks for attribute
access using *note __getattr__(): 323.; most commonly this is done for
convenience, to make code more readable by automatically mapping an
attribute access such as ‘obj.parent’ into a method call such as
‘obj.get_parent’.  Python 2.2 adds some new ways of controlling
attribute access.

First, ‘__getattr__(attr_name)’ is still supported by new-style classes,
and nothing about it has changed.  As before, it will be called when an
attempt is made to access ‘obj.foo’ and no attribute named ‘foo’ is
found in the instance’s dictionary.

New-style classes also support a new method,
‘__getattribute__(attr_name)’.  The difference between the two methods
is that *note __getattribute__(): 44f. is `always' called whenever any
attribute is accessed, while the old *note __getattr__(): 323. is only
called if ‘foo’ isn’t found in the instance’s dictionary.

However, Python 2.2’s support for `properties' will often be a simpler
way to trap attribute references.  Writing a *note __getattr__(): 323.
method is complicated because to avoid recursion you can’t use regular
attribute accesses inside them, and instead have to mess around with the
contents of *note __dict__: 504.  *note __getattr__(): 323. methods also
end up being called by Python when it checks for other methods such as
*note __repr__(): 347. or ‘__coerce__()’, and so have to be written with
this in mind.  Finally, calling a function on every attribute access
results in a sizable performance loss.

*note property: 1d8. is a new built-in type that packages up three
functions that get, set, or delete an attribute, and a docstring.  For
example, if you want to define a ‘size’ attribute that’s computed, but
also settable, you could write:

     class C(object):
         def get_size (self):
             result = ... computation ...
             return result
         def set_size (self, size):
             ... compute something based on the size
             and set internal state appropriately ...

         # Define a property.  The 'delete this attribute'
         # method is defined as None, so the attribute
         # can't be deleted.
         size = property(get_size, set_size,
                         None,
                         "Storage size of this instance")

That is certainly clearer and easier to write than a pair of *note
__getattr__(): 323./*note __setattr__(): e34. methods that check for the
‘size’ attribute and handle it specially while retrieving all other
attributes from the instance’s *note __dict__: 504.  Accesses to ‘size’
are also the only ones which have to perform the work of calling a
function, so references to other attributes run at their usual speed.

Finally, it’s possible to constrain the list of attributes that can be
referenced on an object using the new *note __slots__: e35. class
attribute.  Python objects are usually very dynamic; at any time it’s
possible to define a new attribute on an instance by just doing
‘obj.new_attr=1’.  A new-style class can define a class attribute named
*note __slots__: e35. to limit the legal attributes to a particular set
of names.  An example will make this clear:

     >>> class C(object):
     ...     __slots__ = ('template', 'name')
     ...
     >>> obj = C()
     >>> print obj.template
     None
     >>> obj.template = 'Test'
     >>> print obj.template
     Test
     >>> obj.newattr = None
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
     AttributeError: 'C' object has no attribute 'newattr'

Note how you get an *note AttributeError: 3a3. on the attempt to assign
to an attribute not listed in *note __slots__: e35.


File: python.info,  Node: Related Links,  Prev: Attribute Access,  Up: PEPs 252 and 253 Type and Class Changes

1.15.2.5 Related Links
......................

This section has just been a quick overview of the new features, giving
enough of an explanation to start you programming, but many details have
been simplified or ignored.  Where should you go to get a more complete
picture?

‘https://docs.python.org/dev/howto/descriptor.html’ is a lengthy
tutorial introduction to the descriptor features, written by Guido van
Rossum.  If my description has whetted your appetite, go read this
tutorial next, because it goes into much more detail about the new
features while still remaining quite easy to read.

Next, there are two relevant PEPs, PEP 252(1) and PEP 253(2).  PEP
252(3) is titled "Making Types Look More Like Classes", and covers the
descriptor API. PEP 253(4) is titled "Subtyping Built-in Types", and
describes the changes to type objects that make it possible to subtype
built-in objects.  PEP 253(5) is the more complicated PEP of the two,
and at a few points the necessary explanations of types and meta-types
may cause your head to explode.  Both PEPs were written and implemented
by Guido van Rossum, with substantial assistance from the rest of the
Zope Corp.  team.

Finally, there’s the ultimate authority: the source code.  Most of the
machinery for the type handling is in ‘Objects/typeobject.c’, but you
should only resort to it after all other avenues have been exhausted,
including posting a question to python-list or python-dev.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0252

   (2) https://www.python.org/dev/peps/pep-0253

   (3) https://www.python.org/dev/peps/pep-0252

   (4) https://www.python.org/dev/peps/pep-0253

   (5) https://www.python.org/dev/peps/pep-0253


File: python.info,  Node: PEP 234 Iterators,  Next: PEP 255 Simple Generators<2>,  Prev: PEPs 252 and 253 Type and Class Changes,  Up: Python 2 2 有什么新变化

1.15.3 PEP 234: Iterators
-------------------------

Another significant addition to 2.2 is an iteration interface at both
the C and Python levels.  Objects can define how they can be looped over
by callers.

In Python versions up to 2.1, the usual way to make ‘for item in obj’
work is to define a *note __getitem__(): 280. method that looks
something like this:

     def __getitem__(self, index):
         return <next item>

*note __getitem__(): 280. is more properly used to define an indexing
operation on an object so that you can write ‘obj[5]’ to retrieve the
sixth element.  It’s a bit misleading when you’re using this only to
support *note for: c38. loops.  Consider some file-like object that
wants to be looped over; the `index' parameter is essentially
meaningless, as the class probably assumes that a series of *note
__getitem__(): 280. calls will be made with `index' incrementing by one
each time.  In other words, the presence of the *note __getitem__():
280. method doesn’t mean that using ‘file[5]’ to randomly access the
sixth element will work, though it really should.

In Python 2.2, iteration can be implemented separately, and *note
__getitem__(): 280. methods can be limited to classes that really do
support random access.  The basic idea of iterators is simple.  A new
built-in function, ‘iter(obj)’ or ‘iter(C, sentinel)’, is used to get an
iterator.  ‘iter(obj)’ returns an iterator for the object `obj', while
‘iter(C, sentinel)’ returns an iterator that will invoke the callable
object `C' until it returns `sentinel' to signal that the iterator is
done.

Python classes can define an *note __iter__(): 517. method, which should
create and return a new iterator for the object; if the object is its
own iterator, this method can just return ‘self’.  In particular,
iterators will usually be their own iterators.  Extension types
implemented in C can implement a *note tp_iter: e38. function in order
to return an iterator, and extension types that want to behave as
iterators can define a *note tp_iternext: e39. function.

So, after all this, what do iterators actually do?  They have one
required method, *note next(): 68b, which takes no arguments and returns
the next value.  When there are no more values to be returned, calling
*note next(): 68b. should raise the *note StopIteration: 48e. exception.

     >>> L = [1,2,3]
     >>> i = iter(L)
     >>> print i
     <iterator object at 0x8116870>
     >>> i.next()
     1
     >>> i.next()
     2
     >>> i.next()
     3
     >>> i.next()
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
     StopIteration
     >>>

In 2.2, Python’s *note for: c38. statement no longer expects a sequence;
it expects something for which *note iter(): d2f. will return an
iterator.  For backward compatibility and convenience, an iterator is
automatically constructed for sequences that don’t implement *note
__iter__(): 517. or a *note tp_iter: e38. slot, so ‘for i in [1,2,3]’
will still work.  Wherever the Python interpreter loops over a sequence,
it’s been changed to use the iterator protocol.  This means you can do
things like this:

     >>> L = [1,2,3]
     >>> i = iter(L)
     >>> a,b,c = i
     >>> a,b,c
     (1, 2, 3)

Iterator support has been added to some of Python’s basic types.
Calling *note iter(): d2f. on a dictionary will return an iterator which
loops over its keys:

     >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
     ...      'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
     >>> for key in m: print key, m[key]
     ...
     Mar 3
     Feb 2
     Aug 8
     Sep 9
     May 5
     Jun 6
     Jul 7
     Jan 1
     Apr 4
     Nov 11
     Dec 12
     Oct 10

That’s just the default behaviour.  If you want to iterate over keys,
values, or key/value pairs, you can explicitly call the ‘iterkeys()’,
‘itervalues()’, or ‘iteritems()’ methods to get an appropriate iterator.
In a minor related change, the *note in: 7ac. operator now works on
dictionaries, so ‘key in dict’ is now equivalent to ‘dict.has_key(key)’.

Files also provide an iterator, which calls the *note readline(): df.
method until there are no more lines in the file.  This means you can
now read each line of a file using code like this:

     for line in file:
         # do something for each line
         ...

Note that you can only go forward in an iterator; there’s no way to get
the previous element, reset the iterator, or make a copy of it.  An
iterator object could provide such additional capabilities, but the
iterator protocol only requires a *note next(): 68b. method.

参见
....

PEP 234(1) - Iterators

     由 Ka-Ping Yee 和 GvR 撰写；由 Python Labs 小组（主要由 GvR 和 Tim
     Peters）实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0234


File: python.info,  Node: PEP 255 Simple Generators<2>,  Next: PEP 237 统一长整数和整数<2>,  Prev: PEP 234 Iterators,  Up: Python 2 2 有什么新变化

1.15.4 PEP 255: Simple Generators
---------------------------------

Generators are another new feature, one that interacts with the
introduction of iterators.

You’re doubtless familiar with how function calls work in Python or C.
When you call a function, it gets a private namespace where its local
variables are created.  When the function reaches a *note return: 191.
statement, the local variables are destroyed and the resulting value is
returned to the caller.  A later call to the same function will get a
fresh new set of local variables.  But, what if the local variables
weren’t thrown away on exiting a function?  What if you could later
resume the function where it left off?  This is what generators provide;
they can be thought of as resumable functions.

Here’s the simplest example of a generator function:

     def generate_ints(N):
         for i in range(N):
             yield i

A new keyword, *note yield: 190, was introduced for generators.  Any
function containing a ‘yield’ statement is a generator function; this is
detected by Python’s bytecode compiler which compiles the function
specially as a result.  Because a new keyword was introduced, generators
must be explicitly enabled in a module by including a ‘from __future__
import generators’ statement near the top of the module’s source code.
In Python 2.3 this statement will become unnecessary.

When you call a generator function, it doesn’t return a single value;
instead it returns a generator object that supports the iterator
protocol.  On executing the *note yield: 190. statement, the generator
outputs the value of ‘i’, similar to a *note return: 191. statement.
The big difference between ‘yield’ and a ‘return’ statement is that on
reaching a ‘yield’ the generator’s state of execution is suspended and
local variables are preserved.  On the next call to the generator’s
‘next()’ method, the function will resume executing immediately after
the ‘yield’ statement.  (For complicated reasons, the ‘yield’ statement
isn’t allowed inside the ‘try’ block of a *note try: d7a...*note
finally: 183. statement; read PEP 255(1) for a full explanation of the
interaction between ‘yield’ and exceptions.)

Here’s a sample usage of the ‘generate_ints()’ generator:

     >>> gen = generate_ints(3)
     >>> gen
     <generator object at 0x8117f90>
     >>> gen.next()
     0
     >>> gen.next()
     1
     >>> gen.next()
     2
     >>> gen.next()
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
       File "<stdin>", line 2, in generate_ints
     StopIteration

You could equally write ‘for i in generate_ints(5)’, or ‘a,b,c =
generate_ints(3)’.

Inside a generator function, the *note return: 191. statement can only
be used without a value, and signals the end of the procession of
values; afterwards the generator cannot return any further values.
‘return’ with a value, such as ‘return 5’, is a syntax error inside a
generator function.  The end of the generator’s results can also be
indicated by raising *note StopIteration: 48e. manually, or by just
letting the flow of execution fall off the bottom of the function.

You could achieve the effect of generators manually by writing your own
class and storing all the local variables of the generator as instance
variables.  For example, returning a list of integers could be done by
setting ‘self.count’ to 0, and having the *note next(): 68b. method
increment ‘self.count’ and return it.  However, for a moderately
complicated generator, writing a corresponding class would be much
messier.  ‘Lib/test/test_generators.py’ contains a number of more
interesting examples.  The simplest one implements an in-order traversal
of a tree using generators recursively.

     # A recursive generator that generates Tree leaves in in-order.
     def inorder(t):
         if t:
             for x in inorder(t.left):
                 yield x
             yield t.label
             for x in inorder(t.right):
                 yield x

Two other examples in ‘Lib/test/test_generators.py’ produce solutions
for the N-Queens problem (placing $N$ queens on an $NxN$ chess board so
that no queen threatens another) and the Knight’s Tour (a route that
takes a knight to every square of an $NxN$ chessboard without visiting
any square twice).

The idea of generators comes from other programming languages,
especially Icon (‘https://www.cs.arizona.edu/icon/’), where the idea of
generators is central.  In Icon, every expression and function call
behaves like a generator.  One example from "An Overview of the Icon
Programming Language" at
‘https://www.cs.arizona.edu/icon/docs/ipd266.htm’ gives an idea of what
this looks like:

     sentence := "Store it in the neighboring harbor"
     if (i := find("or", sentence)) > 5 then write(i)

In Icon the ‘find()’ function returns the indexes at which the substring
"or" is found: 3, 23, 33.  In the *note if: def. statement, ‘i’ is first
assigned a value of 3, but 3 is less than 5, so the comparison fails,
and Icon retries it with the second value of 23.  23 is greater than 5,
so the comparison now succeeds, and the code prints the value 23 to the
screen.

Python doesn’t go nearly as far as Icon in adopting generators as a
central concept.  Generators are considered a new part of the core
Python language, but learning or using them isn’t compulsory; if they
don’t solve any problems that you have, feel free to ignore them.  One
novel feature of Python’s interface as compared to Icon’s is that a
generator’s state is represented as a concrete object (the iterator)
that can be passed around to other functions or stored in a data
structure.

参见
....

PEP 255(2) - 简单生成器

     Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland.
     Implemented mostly by Neil Schemenauer and Tim Peters, with other
     fixes from the Python Labs crew.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0255

   (2) https://www.python.org/dev/peps/pep-0255


File: python.info,  Node: PEP 237 统一长整数和整数<2>,  Next: PEP 238 Changing the Division Operator,  Prev: PEP 255 Simple Generators<2>,  Up: Python 2 2 有什么新变化

1.15.5 PEP 237: 统一长整数和整数
--------------------------------

In recent versions, the distinction between regular integers, which are
32-bit values on most machines, and long integers, which can be of
arbitrary size, was becoming an annoyance.  For example, on platforms
that support files larger than ‘2**32’ bytes, the ‘tell()’ method of
file objects has to return a long integer.  However, there were various
bits of Python that expected plain integers and would raise an error if
a long integer was provided instead.  For example, in Python 1.5, only
regular integers could be used as a slice index, and ‘'abc'[1L:]’ would
raise a *note TypeError: 193. exception with the message ’slice index
must be int’.

Python 2.2 will shift values from short to long integers as required.
The ’L’ suffix is no longer needed to indicate a long integer literal,
as now the compiler will choose the appropriate type.  (Using the ’L’
suffix will be discouraged in future 2.x versions of Python, triggering
a warning in Python 2.4, and probably dropped in Python 3.0.)  Many
operations that used to raise an *note OverflowError: 968. will now
return a long integer as their result.  For example:

     >>> 1234567890123
     1234567890123L
     >>> 2 ** 64
     18446744073709551616L

In most cases, integers and long integers will now be treated
identically.  You can still distinguish them with the *note type(): 611.
built-in function, but that’s rarely needed.

参见
....

PEP 237(1) - 统一长整数和整数

     由 Moshe Zadka 和 Guido van Rossum 撰写 ; 大部分由 Guido van Rossum
     实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0237


File: python.info,  Node: PEP 238 Changing the Division Operator,  Next: Unicode Changes,  Prev: PEP 237 统一长整数和整数<2>,  Up: Python 2 2 有什么新变化

1.15.6 PEP 238: Changing the Division Operator
----------------------------------------------

The most controversial change in Python 2.2 heralds the start of an
effort to fix an old design flaw that’s been in Python from the
beginning.  Currently Python’s division operator, ‘/’, behaves like C’s
division operator when presented with two integer arguments: it returns
an integer result that’s truncated down when there would be a fractional
part.  For example, ‘3/2’ is 1, not 1.5, and ‘(-1)/2’ is -1, not -0.5.
This means that the results of division can vary unexpectedly depending
on the type of the two operands and because Python is dynamically typed,
it can be difficult to determine the possible types of the operands.

(The controversy is over whether this is `really' a design flaw, and
whether it’s worth breaking existing code to fix this.  It’s caused
endless discussions on python-dev, and in July 2001 erupted into a storm
of acidly sarcastic postings on ‘comp.lang.python’.  I won’t argue for
either side here and will stick to describing what’s implemented in 2.2.
Read PEP 238(1) for a summary of arguments and counter-arguments.)

Because this change might break code, it’s being introduced very
gradually.  Python 2.2 begins the transition, but the switch won’t be
complete until Python 3.0.

First, I’ll borrow some terminology from PEP 238(2).  "True division" is
the division that most non-programmers are familiar with: 3/2 is 1.5,
1/4 is 0.25, and so forth.  "Floor division" is what Python’s ‘/’
operator currently does when given integer operands; the result is the
floor of the value returned by true division.  "Classic division" is the
current mixed behaviour of ‘/’; it returns the result of floor division
when the operands are integers, and returns the result of true division
when one of the operands is a floating-point number.

Here are the changes 2.2 introduces:

   * A new operator, ‘//’, is the floor division operator.  (Yes, we
     know it looks like C++’s comment symbol.)  ‘//’ `always' performs
     floor division no matter what the types of its operands are, so ‘1
     // 2’ is 0 and ‘1.0 // 2.0’ is also 0.0.

     ‘//’ is always available in Python 2.2; you don’t need to enable it
     using a ‘__future__’ statement.

   * By including a ‘from __future__ import division’ in a module, the
     ‘/’ operator will be changed to return the result of true division,
     so ‘1/2’ is 0.5.  Without the ‘__future__’ statement, ‘/’ still
     means classic division.  The default meaning of ‘/’ will not change
     until Python 3.0.

   * Classes can define methods called *note __truediv__(): 78f. and
     *note __floordiv__(): e3d. to overload the two division operators.
     At the C level, there are also slots in the *note PyNumberMethods:
     d89. structure so extension types can define the two operators.

   * Python 2.2 supports some command-line arguments for testing whether
     code will work with the changed division semantics.  Running python
     with ‘-Q warn’ will cause a warning to be issued whenever division
     is applied to two integers.  You can use this to find code that’s
     affected by the change and fix it.  By default, Python 2.2 will
     simply perform classic division without a warning; the warning will
     be turned on by default in Python 2.3.

参见
....

PEP 238(3) - Changing the Division Operator

     由 Moshe Zadka 和 Guido van Rossum 撰写 ; 由 Guido van Rossum 实现
     。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0238

   (2) https://www.python.org/dev/peps/pep-0238

   (3) https://www.python.org/dev/peps/pep-0238


File: python.info,  Node: Unicode Changes,  Next: PEP 227 Nested Scopes,  Prev: PEP 238 Changing the Division Operator,  Up: Python 2 2 有什么新变化

1.15.7 Unicode Changes
----------------------

Python’s Unicode support has been enhanced a bit in 2.2.  Unicode
strings are usually stored as UCS-2, as 16-bit unsigned integers.
Python 2.2 can also be compiled to use UCS-4, 32-bit unsigned integers,
as its internal encoding by supplying ‘--enable-unicode=ucs4’ to the
configure script.  (It’s also possible to specify ‘--disable-unicode’ to
completely disable Unicode support.)

When built to use UCS-4 (a "wide Python"), the interpreter can natively
handle Unicode characters from U+000000 to U+110000, so the range of
legal values for the ‘unichr()’ function is expanded accordingly.  Using
an interpreter compiled to use UCS-2 (a "narrow Python"), values greater
than 65535 will still cause ‘unichr()’ to raise a *note ValueError: 1fc.
exception.  This is all described in PEP 261(1), "Support for ’wide’
Unicode characters"; consult it for further details.

Another change is simpler to explain.  Since their introduction, Unicode
strings have supported an ‘encode()’ method to convert the string to a
selected encoding such as UTF-8 or Latin-1.  A symmetric
‘decode([*encoding*])’ method has been added to 8-bit strings (though
not to Unicode strings) in 2.2.  ‘decode()’ assumes that the string is
in the specified encoding and decodes it, returning whatever is returned
by the codec.

Using this new feature, codecs have been added for tasks not directly
related to Unicode.  For example, codecs have been added for
uu-encoding, MIME’s base64 encoding, and compression with the *note
zlib: 145. module:

     >>> s = """Here is a lengthy piece of redundant, overly verbose,
     ... and repetitive text.
     ... """
     >>> data = s.encode('zlib')
     >>> data
     'x\x9c\r\xc9\xc1\r\x80 \x10\x04\xc0?Ul...'
     >>> data.decode('zlib')
     'Here is a lengthy piece of redundant, overly verbose,\nand repetitive text.\n'
     >>> print s.encode('uu')
     begin 666 <data>
     M2&5R92!I<R!A(&QE;F=T:'D@<&EE8V4@;V8@<F5D=6YD86YT+"!O=F5R;'D@
     >=F5R8F]S92P*86YD(')E<&5T:71I=F4@=&5X="X*

     end
     >>> "sheesh".encode('rot-13')
     'furrfu'

To convert a class instance to Unicode, a ‘__unicode__()’ method can be
defined by a class, analogous to *note __str__(): e3f.

‘encode()’, ‘decode()’, and ‘__unicode__()’ were implemented by
Marc-André Lemburg.  The changes to support using UCS-4 internally were
implemented by Fredrik Lundh and Martin von Löwis.

参见
....

PEP 261(2) - Support for ’wide’ Unicode characters

     Written by Paul Prescod.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0261

   (2) https://www.python.org/dev/peps/pep-0261


File: python.info,  Node: PEP 227 Nested Scopes,  Next: 新增和改进的模块<3>,  Prev: Unicode Changes,  Up: Python 2 2 有什么新变化

1.15.8 PEP 227: Nested Scopes
-----------------------------

In Python 2.1, statically nested scopes were added as an optional
feature, to be enabled by a ‘from __future__ import nested_scopes’
directive.  In 2.2 nested scopes no longer need to be specially enabled,
and are now always present.  The rest of this section is a copy of the
description of nested scopes from my "What’s New in Python 2.1"
document; if you read it when 2.1 came out, you can skip the rest of
this section.

The largest change introduced in Python 2.1, and made complete in 2.2,
is to Python’s scoping rules.  In Python 2.0, at any given time there
are at most three namespaces used to look up variable names: local,
module-level, and the built-in namespace.  This often surprised people
because it didn’t match their intuitive expectations.  For example, a
nested recursive function definition doesn’t work:

     def f():
         ...
         def g(value):
             ...
             return g(value-1) + 1
         ...

The function ‘g()’ will always raise a *note NameError: d83. exception,
because the binding of the name ‘g’ isn’t in either its local namespace
or in the module-level namespace.  This isn’t much of a problem in
practice (how often do you recursively define interior functions like
this?), but this also made using the *note lambda: c37. expression
clumsier, and this was a problem in practice.  In code which uses
‘lambda’ you can often find local variables being copied by passing them
as the default values of arguments.

     def find(self, name):
         "Return list of any entries equal to 'name'"
         L = filter(lambda x, name=name: x == name,
                    self.list_attribute)
         return L

The readability of Python code written in a strongly functional style
suffers greatly as a result.

The most significant change to Python 2.2 is that static scoping has
been added to the language to fix this problem.  As a first effect, the
‘name=name’ default argument is now unnecessary in the above example.
Put simply, when a given variable name is not assigned a value within a
function (by an assignment, or the *note def: dc6, *note class: c72, or
*note import: c25. statements), references to the variable will be
looked up in the local namespace of the enclosing scope.  A more
detailed explanation of the rules, and a dissection of the
implementation, can be found in the PEP.

This change may cause some compatibility problems for code where the
same variable name is used both at the module level and as a local
variable within a function that contains further function definitions.
This seems rather unlikely though, since such code would have been
pretty confusing to read in the first place.

One side effect of the change is that the ‘from module import *’ and
‘exec’ statements have been made illegal inside a function scope under
certain conditions.  The Python reference manual has said all along that
‘from module import *’ is only legal at the top level of a module, but
the CPython interpreter has never enforced this before.  As part of the
implementation of nested scopes, the compiler which turns Python source
into bytecodes has to generate different code to access variables in a
containing scope.  ‘from module import *’ and ‘exec’ make it impossible
for the compiler to figure this out, because they add names to the local
namespace that are unknowable at compile time.  Therefore, if a function
contains function definitions or *note lambda: c37. expressions with
free variables, the compiler will flag this by raising a *note
SyntaxError: 460. exception.

To make the preceding explanation a bit clearer, here’s an example:

     x = 1
     def f():
         # The next line is a syntax error
         exec 'x=2'
         def g():
             return x

Line 4 containing the ‘exec’ statement is a syntax error, since ‘exec’
would define a new local variable named ‘x’ whose value should be
accessed by ‘g()’.

This shouldn’t be much of a limitation, since ‘exec’ is rarely used in
most Python code (and when it is used, it’s often a sign of a poor
design anyway).

参见
....

PEP 227(1) - Statically Nested Scopes

     由 Jeremy Hylton 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0227


File: python.info,  Node: 新增和改进的模块<3>,  Next: Interpreter Changes and Fixes,  Prev: PEP 227 Nested Scopes,  Up: Python 2 2 有什么新变化

1.15.9 新增和改进的模块
-----------------------

   * The ‘xmlrpclib’ module was contributed to the standard library by
     Fredrik Lundh, providing support for writing XML-RPC clients.
     XML-RPC is a simple remote procedure call protocol built on top of
     HTTP and XML. For example, the following snippet retrieves a list
     of RSS channels from the O’Reilly Network, and then lists the
     recent headlines for one channel:

          import xmlrpclib
          s = xmlrpclib.Server(
                'http://www.oreillynet.com/meerkat/xml-rpc/server.php')
          channels = s.meerkat.getChannels()
          # channels is a list of dictionaries, like this:
          # [{'id': 4, 'title': 'Freshmeat Daily News'}
          #  {'id': 190, 'title': '32Bits Online'},
          #  {'id': 4549, 'title': '3DGamers'}, ... ]

          # Get the items for one channel
          items = s.meerkat.getItems( {'channel': 4} )

          # 'items' is another list of dictionaries, like this:
          # [{'link': 'http://freshmeat.net/releases/52719/',
          #   'description': 'A utility which converts HTML to XSL FO.',
          #   'title': 'html2fo 0.3 (Default)'}, ... ]

     The ‘SimpleXMLRPCServer’ module makes it easy to create
     straightforward XML-RPC servers.  See
     ‘http://xmlrpc.scripting.com/’ for more information about XML-RPC.

   * The new *note hmac: 8f. module implements the HMAC algorithm
     described by RFC 2104(1).  (Contributed by Gerhard Häring.)

   * Several functions that originally returned lengthy tuples now
     return pseudo-sequences that still behave like tuples but also have
     mnemonic attributes such as memberst_mtime or ‘tm_year’.  The
     enhanced functions include *note stat(): f5, ‘fstat()’,
     ‘statvfs()’, and ‘fstatvfs()’ in the *note os: c5. module, and
     ‘localtime()’, ‘gmtime()’, and ‘strptime()’ in the *note time: 10b.
     module.

     For example, to obtain a file’s size using the old tuples, you’d
     end up writing something like ‘file_size =
     os.stat(filename)[stat.ST_SIZE]’, but now this can be written more
     clearly as ‘file_size = os.stat(filename).st_size’.

     The original patch for this feature was contributed by Nick
     Mathewson.

   * The Python profiler has been extensively reworked and various
     errors in its output have been corrected.  (Contributed by Fred L.
     Drake, Jr.  and Tim Peters.)

   * The *note socket: f0. module can be compiled to support IPv6;
     specify the ‘--enable-ipv6’ option to Python’s configure script.
     (Contributed by Jun-ichiro "itojun" Hagino.)

   * Two new format characters were added to the *note struct: f9.
     module for 64-bit integers on platforms that support the C ‘long
     long’ type.  ‘q’ is for a signed 64-bit integer, and ‘Q’ is for an
     unsigned one.  The value is returned in Python’s long integer type.
     (Contributed by Tim Peters.)

   * In the interpreter’s interactive mode, there’s a new built-in
     function *note help(): 57b. that uses the *note pydoc: da. module
     introduced in Python 2.1 to provide interactive help.
     ‘help(object)’ displays any available help text about `object'.
     *note help(): 57b. with no argument puts you in an online help
     utility, where you can enter the names of functions, classes, or
     modules to read their help text.  (Contributed by Guido van Rossum,
     using Ka-Ping Yee’s *note pydoc: da. module.)

   * Various bugfixes and performance improvements have been made to the
     SRE engine underlying the *note re: de. module.  For example, the
     *note re.sub(): 483. and *note re.split(): 3d2. functions have been
     rewritten in C. Another contributed patch speeds up certain Unicode
     character ranges by a factor of two, and a new ‘finditer()’ method
     that returns an iterator over all the non-overlapping matches in a
     given string.  (SRE is maintained by Fredrik Lundh.  The BIGCHARSET
     patch was contributed by Martin von Löwis.)

   * The *note smtplib: ee. module now supports RFC 2487(2), "Secure
     SMTP over TLS", so it’s now possible to encrypt the SMTP traffic
     between a Python program and the mail transport agent being handed
     a message.  *note smtplib: ee. also supports SMTP authentication.
     (Contributed by Gerhard Häring.)

   * The *note imaplib: 98. module, maintained by Piers Lauder, has
     support for several new extensions: the NAMESPACE extension defined
     in RFC 2342(3), SORT, GETACL and SETACL. (Contributed by Anthony
     Baxter and Michel Pelletier.)

   * The ‘rfc822’ module’s parsing of email addresses is now compliant
     with RFC 2822(4), an update to RFC 822(5).  (The module’s name is
     `not' going to be changed to ‘rfc2822’.)  A new package, *note
     email: 69, has also been added for parsing and generating e-mail
     messages.  (Contributed by Barry Warsaw, and arising out of his
     work on Mailman.)

   * The *note difflib: 37. module now contains a new ‘Differ’ class for
     producing human-readable lists of changes (a "delta") between two
     sequences of lines of text.  There are also two generator
     functions, ‘ndiff()’ and ‘restore()’, which respectively return a
     delta from two sequences, or one of the original sequences from a
     delta.  (Grunt work contributed by David Goodger, from ndiff.py
     code by Tim Peters who then did the generatorization.)

   * New constants ‘ascii_letters’, ‘ascii_lowercase’, and
     ‘ascii_uppercase’ were added to the *note string: f7. module.
     There were several modules in the standard library that used
     ‘string.letters’ to mean the ranges A-Za-z, but that assumption is
     incorrect when locales are in use, because ‘string.letters’ varies
     depending on the set of legal characters defined by the current
     locale.  The buggy modules have all been fixed to use
     ‘ascii_letters’ instead.  (Reported by an unknown person; fixed by
     Fred L. Drake, Jr.)

   * The *note mimetypes: b3. module now makes it easier to use
     alternative MIME-type databases by the addition of a ‘MimeTypes’
     class, which takes a list of filenames to be parsed.  (Contributed
     by Fred L. Drake, Jr.)

   * A ‘Timer’ class was added to the *note threading: 10a. module that
     allows scheduling an activity to happen at some future time.
     (Contributed by Itamar Shtull-Trauring.)

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2104.html

   (2) https://tools.ietf.org/html/rfc2487.html

   (3) https://tools.ietf.org/html/rfc2342.html

   (4) https://tools.ietf.org/html/rfc2822.html

   (5) https://tools.ietf.org/html/rfc822.html


File: python.info,  Node: Interpreter Changes and Fixes,  Next: Other Changes and Fixes<3>,  Prev: 新增和改进的模块<3>,  Up: Python 2 2 有什么新变化

1.15.10 Interpreter Changes and Fixes
-------------------------------------

Some of the changes only affect people who deal with the Python
interpreter at the C level because they’re writing Python extension
modules, embedding the interpreter, or just hacking on the interpreter
itself.  If you only write Python code, none of the changes described
here will affect you very much.

   * Profiling and tracing functions can now be implemented in C, which
     can operate at much higher speeds than Python-based functions and
     should reduce the overhead of profiling and tracing.  This will be
     of interest to authors of development environments for Python.  Two
     new C functions were added to Python’s API, *note
     PyEval_SetProfile(): e43. and *note PyEval_SetTrace(): e44.  The
     existing *note sys.setprofile(): e45. and *note sys.settrace():
     e46. functions still exist, and have simply been changed to use the
     new C-level interface.  (Contributed by Fred L. Drake, Jr.)

   * Another low-level API, primarily of interest to implementors of
     Python debuggers and development tools, was added.  *note
     PyInterpreterState_Head(): e47. and *note
     PyInterpreterState_Next(): e48. let a caller walk through all the
     existing interpreter objects; *note
     PyInterpreterState_ThreadHead(): e49. and *note
     PyThreadState_Next(): e4a. allow looping over all the thread states
     for a given interpreter.  (Contributed by David Beazley.)

   * The C-level interface to the garbage collector has been changed to
     make it easier to write extension types that support garbage
     collection and to debug misuses of the functions.  Various
     functions have slightly different semantics, so a bunch of
     functions had to be renamed.  Extensions that use the old API will
     still compile but will `not' participate in garbage collection, so
     updating them for 2.2 should be considered fairly high priority.

     To upgrade an extension module to the new API, perform the
     following steps:

   * Rename ‘Py_TPFLAGS_GC()’ to ‘PyTPFLAGS_HAVE_GC()’.

   * 
     Use *note PyObject_GC_New(): 2d5. or *note PyObject_GC_NewVar(): 2d6. to allocate

          objects, and *note PyObject_GC_Del(): e4b. to deallocate them.

   * 
     Rename ‘PyObject_GC_Init()’ to *note PyObject_GC_Track(): e4c. and

          ‘PyObject_GC_Fini()’ to *note PyObject_GC_UnTrack(): e4d.

   * Remove ‘PyGC_HEAD_SIZE()’ from object size calculations.

   * Remove calls to ‘PyObject_AS_GC()’ and ‘PyObject_FROM_GC()’.

   * A new ‘et’ format sequence was added to *note PyArg_ParseTuple():
     26b.; ‘et’ takes both a parameter and an encoding name, and
     converts the parameter to the given encoding if the parameter turns
     out to be a Unicode string, or leaves it alone if it’s an 8-bit
     string, assuming it to already be in the desired encoding.  This
     differs from the ‘es’ format character, which assumes that 8-bit
     strings are in Python’s default ASCII encoding and converts them to
     the specified new encoding.  (Contributed by M.-A. Lemburg, and
     used for the MBCS support on Windows described in the following
     section.)

   * A different argument parsing function, *note PyArg_UnpackTuple():
     e4e, has been added that’s simpler and presumably faster.  Instead
     of specifying a format string, the caller simply gives the minimum
     and maximum number of arguments expected, and a set of pointers to
     *note PyObject*: 4c2. variables that will be filled in with
     argument values.

   * Two new flags *note METH_NOARGS: e20. and *note METH_O: e4f. are
     available in method definition tables to simplify implementation of
     methods with no arguments or a single untyped argument.  Calling
     such methods is more efficient than calling a corresponding method
     that uses *note METH_VARARGS: e50.  Also, the old ‘METH_OLDARGS’
     style of writing C methods is now officially deprecated.

   * Two new wrapper functions, *note PyOS_snprintf(): e51. and *note
     PyOS_vsnprintf(): e52. were added to provide cross-platform
     implementations for the relatively new ‘snprintf()’ and
     ‘vsnprintf()’ C lib APIs.  In contrast to the standard ‘sprintf()’
     and ‘vsprintf()’ functions, the Python versions check the bounds of
     the buffer used to protect against buffer overruns.  (Contributed
     by M.-A. Lemburg.)

   * The *note _PyTuple_Resize(): e53. function has lost an unused
     parameter, so now it takes 2 parameters instead of 3.  The third
     argument was never used, and can simply be discarded when porting
     code from earlier versions to Python 2.2.


File: python.info,  Node: Other Changes and Fixes<3>,  Next: 致谢<6>,  Prev: Interpreter Changes and Fixes,  Up: Python 2 2 有什么新变化

1.15.11 Other Changes and Fixes
-------------------------------

As usual there were a bunch of other improvements and bugfixes scattered
throughout the source tree.  A search through the CVS change logs finds
there were 527 patches applied and 683 bugs fixed between Python 2.1 and
2.2; 2.2.1 applied 139 patches and fixed 143 bugs; 2.2.2 applied 106
patches and fixed 82 bugs.  These figures are likely to be
underestimates.

Some of the more notable changes are:

   * The code for the MacOS port for Python, maintained by Jack Jansen,
     is now kept in the main Python CVS tree, and many changes have been
     made to support MacOS X.

     The most significant change is the ability to build Python as a
     framework, enabled by supplying the ‘--enable-framework’ option to
     the configure script when compiling Python.  According to Jack
     Jansen, "This installs a self-contained Python installation plus
     the OS X framework "glue" into
     ‘/Library/Frameworks/Python.framework’ (or another location of
     choice).  For now there is little immediate added benefit to this
     (actually, there is the disadvantage that you have to change your
     PATH to be able to find Python), but it is the basis for creating a
     full-blown Python application, porting the MacPython IDE, possibly
     using Python as a standard OSA scripting language and much more."

     Most of the MacPython toolbox modules, which interface to MacOS
     APIs such as windowing, QuickTime, scripting, etc.  have been
     ported to OS X, but they’ve been left commented out in ‘setup.py’.
     People who want to experiment with these modules can uncomment them
     manually.

   * Keyword arguments passed to built-in functions that don’t take them
     now cause a *note TypeError: 193. exception to be raised, with the
     message "`function' takes no keyword arguments".

   * Weak references, added in Python 2.1 as an extension module, are
     now part of the core because they’re used in the implementation of
     new-style classes.  The *note ReferenceError: e55. exception has
     therefore moved from the *note weakref: 129. module to become a
     built-in exception.

   * A new script, ‘Tools/scripts/cleanfuture.py’ by Tim Peters,
     automatically removes obsolete ‘__future__’ statements from Python
     source code.

   * An additional `flags' argument has been added to the built-in
     function *note compile(): 1b5, so the behaviour of ‘__future__’
     statements can now be correctly observed in simulated shells, such
     as those presented by IDLE and other development environments.
     This is described in PEP 264(1).  (Contributed by Michael Hudson.)

   * The new license introduced with Python 1.6 wasn’t GPL-compatible.
     This is fixed by some minor textual changes to the 2.2 license, so
     it’s now legal to embed Python inside a GPLed program again.  Note
     that Python itself is not GPLed, but instead is under a license
     that’s essentially equivalent to the BSD license, same as it always
     was.  The license changes were also applied to the Python 2.0.1 and
     2.1.1 releases.

   * When presented with a Unicode filename on Windows, Python will now
     convert it to an MBCS encoded string, as used by the Microsoft file
     APIs.  As MBCS is explicitly used by the file APIs, Python’s choice
     of ASCII as the default encoding turns out to be an annoyance.  On
     Unix, the locale’s character set is used if
     ‘locale.nl_langinfo(CODESET)’ is available.  (Windows support was
     contributed by Mark Hammond with assistance from Marc-André
     Lemburg.  Unix support was added by Martin von Löwis.)

   * Large file support is now enabled on Windows.  (Contributed by Tim
     Peters.)

   * The ‘Tools/scripts/ftpmirror.py’ script now parses a ‘.netrc’ file,
     if you have one.  (Contributed by Mike Romberg.)

   * Some features of the object returned by the ‘xrange()’ function are
     now deprecated, and trigger warnings when they’re accessed; they’ll
     disappear in Python 2.3.  ‘xrange’ objects tried to pretend they
     were full sequence types by supporting slicing, sequence
     multiplication, and the *note in: 7ac. operator, but these features
     were rarely used and therefore buggy.  The ‘tolist()’ method and
     the ‘start’, ‘stop’, and ‘step’ attributes are also being
     deprecated.  At the C level, the fourth argument to the
     ‘PyRange_New()’ function, ‘repeat’, has also been deprecated.

   * There were a bunch of patches to the dictionary implementation,
     mostly to fix potential core dumps if a dictionary contains objects
     that sneakily changed their hash value, or mutated the dictionary
     they were contained in.  For a while python-dev fell into a gentle
     rhythm of Michael Hudson finding a case that dumped core, Tim
     Peters fixing the bug, Michael finding another case, and round and
     round it went.

   * On Windows, Python can now be compiled with Borland C thanks to a
     number of patches contributed by Stephen Hansen, though the result
     isn’t fully functional yet.  (But this `is' progress...)

   * Another Windows enhancement: Wise Solutions generously offered
     PythonLabs use of their InstallerMaster 8.1 system.  Earlier
     PythonLabs Windows installers used Wise 5.0a, which was beginning
     to show its age.  (Packaged up by Tim Peters.)

   * Files ending in ‘.pyw’ can now be imported on Windows.  ‘.pyw’ is a
     Windows-only thing, used to indicate that a script needs to be run
     using PYTHONW.EXE instead of PYTHON.EXE in order to prevent a DOS
     console from popping up to display the output.  This patch makes it
     possible to import such scripts, in case they’re also usable as
     modules.  (Implemented by David Bolen.)

   * On platforms where Python uses the C ‘dlopen()’ function to load
     extension modules, it’s now possible to set the flags used by
     ‘dlopen()’ using the *note sys.getdlopenflags(): e56. and *note
     sys.setdlopenflags(): a6e. functions.  (Contributed by Bram Stolk.)

   * The *note pow(): 19b. built-in function no longer supports 3
     arguments when floating-point numbers are supplied.  ‘pow(x, y, z)’
     returns ‘(x**y) % z’, but this is never useful for floating point
     numbers, and the final result varies unpredictably depending on the
     platform.  A call such as ‘pow(2.0, 8.0, 7.0)’ will now raise a
     *note TypeError: 193. exception.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0264


File: python.info,  Node: 致谢<6>,  Prev: Other Changes and Fixes<3>,  Up: Python 2 2 有什么新变化

1.15.12 致谢
------------

作者感谢以下人员为本文的各种草案提供建议，更正和帮助： Fred Bremmer,
Keith Briggs, Andrew Dalke, Fred L. Drake, Jr., Carel Fellinger, David
Goodger, Mark Hammond, Stephen Hansen, Michael Hudson, Jack Jansen,
Marc-André Lemburg, Martin von Löwis, Fredrik Lundh, Michael McLay, Nick
Mathewson, Paul Moore, Gustavo Niemeyer, Don O’Donnell, Joonas Paalasma,
Tim Peters, Jens Quade, Tom Reinhardt, Neil Schemenauer, Guido van
Rossum, Greg Ward, Edward Welbourne.


File: python.info,  Node: Python 2 1 有什么新变化,  Next: Python 2 0 有什么新变化,  Prev: Python 2 2 有什么新变化,  Up: Python的新变化

1.16 Python 2.1 有什么新变化
============================


作者: A.M. Kuchling

* Menu:

* 概述: 概述<2>.
* PEP 227; Nested Scopes: PEP 227 Nested Scopes<2>.
* PEP 236; __future__ Directives: PEP 236 __future__ Directives.
* PEP 207; Rich Comparisons: PEP 207 Rich Comparisons.
* PEP 230; Warning Framework: PEP 230 Warning Framework.
* PEP 229; New Build System: PEP 229 New Build System.
* PEP 205; Weak References: PEP 205 Weak References.
* PEP 232; Function Attributes: PEP 232 Function Attributes.
* PEP 235; Importing Modules on Case-Insensitive Platforms: PEP 235 Importing Modules on Case-Insensitive Platforms.
* PEP 217; Interactive Display Hook: PEP 217 Interactive Display Hook.
* PEP 208; New Coercion Model: PEP 208 New Coercion Model.
* PEP 241; Metadata in Python Packages: PEP 241 Metadata in Python Packages.
* 新增和改进的模块: 新增和改进的模块<4>.
* Other Changes and Fixes: Other Changes and Fixes<4>.
* 致谢: 致谢<7>.


File: python.info,  Node: 概述<2>,  Next: PEP 227 Nested Scopes<2>,  Up: Python 2 1 有什么新变化

1.16.1 概述
-----------

This article explains the new features in Python 2.1.  While there
aren’t as many changes in 2.1 as there were in Python 2.0, there are
still some pleasant surprises in store.  2.1 is the first release to be
steered through the use of Python Enhancement Proposals, or PEPs, so
most of the sizable changes have accompanying PEPs that provide more
complete documentation and a design rationale for the change.  This
article doesn’t attempt to document the new features completely, but
simply provides an overview of the new features for Python programmers.
Refer to the Python 2.1 documentation, or to the specific PEP, for more
details about any new feature that particularly interests you.

One recent goal of the Python development team has been to accelerate
the pace of new releases, with a new release coming every 6 to 9 months.
2.1 is the first release to come out at this faster pace, with the first
alpha appearing in January, 3 months after the final version of 2.0 was
released.

Python 2.1 的最终版本于2001年4月17日发布。


File: python.info,  Node: PEP 227 Nested Scopes<2>,  Next: PEP 236 __future__ Directives,  Prev: 概述<2>,  Up: Python 2 1 有什么新变化

1.16.2 PEP 227: Nested Scopes
-----------------------------

The largest change in Python 2.1 is to Python’s scoping rules.  In
Python 2.0, at any given time there are at most three namespaces used to
look up variable names: local, module-level, and the built-in namespace.
This often surprised people because it didn’t match their intuitive
expectations.  For example, a nested recursive function definition
doesn’t work:

     def f():
         ...
         def g(value):
             ...
             return g(value-1) + 1
         ...

The function ‘g()’ will always raise a *note NameError: d83. exception,
because the binding of the name ‘g’ isn’t in either its local namespace
or in the module-level namespace.  This isn’t much of a problem in
practice (how often do you recursively define interior functions like
this?), but this also made using the *note lambda: c37. expression
clumsier, and this was a problem in practice.  In code which uses *note
lambda: c37. you can often find local variables being copied by passing
them as the default values of arguments.

     def find(self, name):
         "Return list of any entries equal to 'name'"
         L = filter(lambda x, name=name: x == name,
                    self.list_attribute)
         return L

The readability of Python code written in a strongly functional style
suffers greatly as a result.

The most significant change to Python 2.1 is that static scoping has
been added to the language to fix this problem.  As a first effect, the
‘name=name’ default argument is now unnecessary in the above example.
Put simply, when a given variable name is not assigned a value within a
function (by an assignment, or the *note def: dc6, *note class: c72, or
*note import: c25. statements), references to the variable will be
looked up in the local namespace of the enclosing scope.  A more
detailed explanation of the rules, and a dissection of the
implementation, can be found in the PEP.

This change may cause some compatibility problems for code where the
same variable name is used both at the module level and as a local
variable within a function that contains further function definitions.
This seems rather unlikely though, since such code would have been
pretty confusing to read in the first place.

One side effect of the change is that the ‘from module import *’ and
‘exec’ statements have been made illegal inside a function scope under
certain conditions.  The Python reference manual has said all along that
‘from module import *’ is only legal at the top level of a module, but
the CPython interpreter has never enforced this before.  As part of the
implementation of nested scopes, the compiler which turns Python source
into bytecodes has to generate different code to access variables in a
containing scope.  ‘from module import *’ and ‘exec’ make it impossible
for the compiler to figure this out, because they add names to the local
namespace that are unknowable at compile time.  Therefore, if a function
contains function definitions or *note lambda: c37. expressions with
free variables, the compiler will flag this by raising a *note
SyntaxError: 460. exception.

To make the preceding explanation a bit clearer, here’s an example:

     x = 1
     def f():
         # The next line is a syntax error
         exec 'x=2'
         def g():
             return x

Line 4 containing the ‘exec’ statement is a syntax error, since ‘exec’
would define a new local variable named ‘x’ whose value should be
accessed by ‘g()’.

This shouldn’t be much of a limitation, since ‘exec’ is rarely used in
most Python code (and when it is used, it’s often a sign of a poor
design anyway).

Compatibility concerns have led to nested scopes being introduced
gradually; in Python 2.1, they aren’t enabled by default, but can be
turned on within a module by using a future statement as described in
PEP 236(1).  (See the following section for further discussion of PEP
236(2).)  In Python 2.2, nested scopes will become the default and there
will be no way to turn them off, but users will have had all of 2.1’s
lifetime to fix any breakage resulting from their introduction.

参见
....

PEP 227(3) - Statically Nested Scopes

     由 Jeremy Hylton 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0236

   (2) https://www.python.org/dev/peps/pep-0236

   (3) https://www.python.org/dev/peps/pep-0227


File: python.info,  Node: PEP 236 __future__ Directives,  Next: PEP 207 Rich Comparisons,  Prev: PEP 227 Nested Scopes<2>,  Up: Python 2 1 有什么新变化

1.16.3 PEP 236: __future__ Directives
-------------------------------------

The reaction to nested scopes was widespread concern about the dangers
of breaking code with the 2.1 release, and it was strong enough to make
the Pythoneers take a more conservative approach.  This approach
consists of introducing a convention for enabling optional functionality
in release N that will become compulsory in release N+1.

The syntax uses a ‘from...import’ statement using the reserved module
name *note __future__: 0.  Nested scopes can be enabled by the following
statement:

     from __future__ import nested_scopes

While it looks like a normal *note import: c25. statement, it’s not;
there are strict rules on where such a future statement can be put.
They can only be at the top of a module, and must precede any Python
code or regular ‘import’ statements.  This is because such statements
can affect how the Python bytecode compiler parses code and generates
bytecode, so they must precede any statement that will result in
bytecodes being produced.

参见
....

PEP 236(1) - Back to the *note __future__: 0.

     由 Tim Peters 撰写，主要由 Jeremy Hylton 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0236


File: python.info,  Node: PEP 207 Rich Comparisons,  Next: PEP 230 Warning Framework,  Prev: PEP 236 __future__ Directives,  Up: Python 2 1 有什么新变化

1.16.4 PEP 207: Rich Comparisons
--------------------------------

In earlier versions, Python’s support for implementing comparisons on
user-defined classes and extension types was quite simple.  Classes
could implement a ‘__cmp__()’ method that was given two instances of a
class, and could only return 0 if they were equal or +1 or -1 if they
weren’t; the method couldn’t raise an exception or return anything other
than a Boolean value.  Users of Numeric Python often found this model
too weak and restrictive, because in the number-crunching programs that
numeric Python is used for, it would be more useful to be able to
perform elementwise comparisons of two matrices, returning a matrix
containing the results of a given comparison for each element.  If the
two matrices are of different sizes, then the compare has to be able to
raise an exception to signal the error.

In Python 2.1, rich comparisons were added in order to support this
need.  Python classes can now individually overload each of the ‘<’,
‘<=’, ‘>’, ‘>=’, ‘==’, and ‘!=’ operations.  The new magic method names
are:

运算            方法名称
                
-------------------------------------
                
‘<’             *note __lt__(): c3c.
                
                
‘<=’            *note __le__(): ca8.
                
                
‘>’             *note __gt__(): ca9.
                
                
‘>=’            *note __ge__(): caa.
                
                
‘==’            *note __eq__(): 348.
                
                
‘!=’            *note __ne__(): e5e.
                

(The magic methods are named after the corresponding Fortran operators
‘.LT.’.  ‘.LE.’, &c.  Numeric programmers are almost certainly quite
familiar with these names and will find them easy to remember.)

Each of these magic methods is of the form ‘method(self, other)’, where
‘self’ will be the object on the left-hand side of the operator, while
‘other’ will be the object on the right-hand side.  For example, the
expression ‘A < B’ will cause ‘A.__lt__(B)’ to be called.

Each of these magic methods can return anything at all: a Boolean, a
matrix, a list, or any other Python object.  Alternatively they can
raise an exception if the comparison is impossible, inconsistent, or
otherwise meaningless.

The built-in ‘cmp(A,B)’ function can use the rich comparison machinery,
and now accepts an optional argument specifying which comparison
operation to use; this is given as one of the strings ‘"<"’, ‘"<="’,
‘">"’, ‘">="’, ‘"=="’, or ‘"!="’.  If called without the optional third
argument, ‘cmp()’ will only return -1, 0, or +1 as in previous versions
of Python; otherwise it will call the appropriate method and can return
any Python object.

There are also corresponding changes of interest to C programmers;
there’s a new slot ‘tp_richcmp’ in type objects and an API for
performing a given rich comparison.  I won’t cover the C API here, but
will refer you to PEP 207(1), or to 2.1’s C API documentation, for the
full list of related functions.

参见
....

PEP 207(2) - Rich Comparisons

     Written by Guido van Rossum, heavily based on earlier work by David
     Ascher, and implemented by Guido van Rossum.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0207

   (2) https://www.python.org/dev/peps/pep-0207


File: python.info,  Node: PEP 230 Warning Framework,  Next: PEP 229 New Build System,  Prev: PEP 207 Rich Comparisons,  Up: Python 2 1 有什么新变化

1.16.5 PEP 230: Warning Framework
---------------------------------

Over its 10 years of existence, Python has accumulated a certain number
of obsolete modules and features along the way.  It’s difficult to know
when a feature is safe to remove, since there’s no way of knowing how
much code uses it — perhaps no programs depend on the feature, or
perhaps many do.  To enable removing old features in a more structured
way, a warning framework was added.  When the Python developers want to
get rid of a feature, it will first trigger a warning in the next
version of Python.  The following Python version can then drop the
feature, and users will have had a full release cycle to remove uses of
the old feature.

Python 2.1 adds the warning framework to be used in this scheme.  It
adds a *note warnings: 127. module that provide functions to issue
warnings, and to filter out warnings that you don’t want to be
displayed.  Third-party modules can also use this framework to deprecate
old features that they no longer wish to support.

For example, in Python 2.1 the ‘regex’ module is deprecated, so
importing it causes a warning to be printed:

     >>> import regex
     __main__:1: DeprecationWarning: the regex module
              is deprecated; please use the re module
     >>>

Warnings can be issued by calling the *note warnings.warn(): e60.
function:

     warnings.warn("feature X no longer supported")

The first parameter is the warning message; an additional optional
parameters can be used to specify a particular warning category.

Filters can be added to disable certain warnings; a regular expression
pattern can be applied to the message or to the module name in order to
suppress a warning.  For example, you may have a program that uses the
‘regex’ module and not want to spare the time to convert it to use the
*note re: de. module right now.  The warning can be suppressed by
calling

     import warnings
     warnings.filterwarnings(action = 'ignore',
                             message='.*regex module is deprecated',
                             category=DeprecationWarning,
                             module = '__main__')

This adds a filter that will apply only to warnings of the class *note
DeprecationWarning: 279. triggered in the *note __main__: 1. module, and
applies a regular expression to only match the message about the ‘regex’
module being deprecated, and will cause such warnings to be ignored.
Warnings can also be printed only once, printed every time the offending
code is executed, or turned into exceptions that will cause the program
to stop (unless the exceptions are caught in the usual way, of course).

Functions were also added to Python’s C API for issuing warnings; refer
to PEP 230 or to Python’s API documentation for the details.

参见
....

PEP 5(1) - Guidelines for Language Evolution

     Written by Paul Prescod, to specify procedures to be followed when
     removing old features from Python.  The policy described in this
     PEP hasn’t been officially adopted, but the eventual policy
     probably won’t be too different from Prescod’s proposal.

PEP 230(2) - Warning Framework

     由 Guido van Rossum 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0005

   (2) https://www.python.org/dev/peps/pep-0230


File: python.info,  Node: PEP 229 New Build System,  Next: PEP 205 Weak References,  Prev: PEP 230 Warning Framework,  Up: Python 2 1 有什么新变化

1.16.6 PEP 229: New Build System
--------------------------------

When compiling Python, the user had to go in and edit the
‘Modules/Setup’ file in order to enable various additional modules; the
default set is relatively small and limited to modules that compile on
most Unix platforms.  This means that on Unix platforms with many more
features, most notably Linux, Python installations often don’t contain
all useful modules they could.

Python 2.0 added the Distutils, a set of modules for distributing and
installing extensions.  In Python 2.1, the Distutils are used to compile
much of the standard library of extension modules, autodetecting which
ones are supported on the current machine.  It’s hoped that this will
make Python installations easier and more featureful.

Instead of having to edit the ‘Modules/Setup’ file in order to enable
modules, a ‘setup.py’ script in the top directory of the Python source
distribution is run at build time, and attempts to discover which
modules can be enabled by examining the modules and header files on the
system.  If a module is configured in ‘Modules/Setup’, the ‘setup.py’
script won’t attempt to compile that module and will defer to the
‘Modules/Setup’ file’s contents.  This provides a way to specific any
strange command-line flags or libraries that are required for a specific
platform.

In another far-reaching change to the build mechanism, Neil Schemenauer
restructured things so Python now uses a single makefile that isn’t
recursive, instead of makefiles in the top directory and in each of the
‘Python/’, ‘Parser/’, ‘Objects/’, and ‘Modules/’ subdirectories.  This
makes building Python faster and also makes hacking the Makefiles
clearer and simpler.

参见
....

PEP 229(1) - Using Distutils to Build Python

     由 A.M. Kuchling 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0229


File: python.info,  Node: PEP 205 Weak References,  Next: PEP 232 Function Attributes,  Prev: PEP 229 New Build System,  Up: Python 2 1 有什么新变化

1.16.7 PEP 205: Weak References
-------------------------------

Weak references, available through the *note weakref: 129. module, are a
minor but useful new data type in the Python programmer’s toolbox.

Storing a reference to an object (say, in a dictionary or a list) has
the side effect of keeping that object alive forever.  There are a few
specific cases where this behaviour is undesirable, object caches being
the most common one, and another being circular references in data
structures such as trees.

For example, consider a memoizing function that caches the results of
another function ‘f(x)’ by storing the function’s argument and its
result in a dictionary:

     _cache = {}
     def memoize(x):
         if _cache.has_key(x):
             return _cache[x]

         retval = f(x)

         # Cache the returned object
         _cache[x] = retval

         return retval

This version works for simple things such as integers, but it has a side
effect; the ‘_cache’ dictionary holds a reference to the return values,
so they’ll never be deallocated until the Python process exits and
cleans up.  This isn’t very noticeable for integers, but if ‘f()’
returns an object, or a data structure that takes up a lot of memory,
this can be a problem.

Weak references provide a way to implement a cache that won’t keep
objects alive beyond their time.  If an object is only accessible
through weak references, the object will be deallocated and the weak
references will now indicate that the object it referred to no longer
exists.  A weak reference to an object `obj' is created by calling ‘wr =
weakref.ref(obj)’.  The object being referred to is returned by calling
the weak reference as if it were a function: ‘wr()’.  It will return the
referenced object, or ‘None’ if the object no longer exists.

This makes it possible to write a ‘memoize()’ function whose cache
doesn’t keep objects alive, by storing weak references in the cache.

     _cache = {}
     def memoize(x):
         if _cache.has_key(x):
             obj = _cache[x]()
             # If weak reference object still exists,
             # return it
             if obj is not None: return obj

         retval = f(x)

         # Cache a weak reference
         _cache[x] = weakref.ref(retval)

         return retval

The *note weakref: 129. module also allows creating proxy objects which
behave like weak references — an object referenced only by proxy objects
is deallocated – but instead of requiring an explicit call to retrieve
the object, the proxy transparently forwards all operations to the
object as long as the object still exists.  If the object is
deallocated, attempting to use a proxy will cause a
‘weakref.ReferenceError’ exception to be raised.

     proxy = weakref.proxy(obj)
     proxy.attr   # Equivalent to obj.attr
     proxy.meth() # Equivalent to obj.meth()
     del obj
     proxy.attr   # raises weakref.ReferenceError

参见
....

PEP 205(1) - 弱引用

     由 Fred L. Drake, Jr 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0205


File: python.info,  Node: PEP 232 Function Attributes,  Next: PEP 235 Importing Modules on Case-Insensitive Platforms,  Prev: PEP 205 Weak References,  Up: Python 2 1 有什么新变化

1.16.8 PEP 232: Function Attributes
-----------------------------------

In Python 2.1, functions can now have arbitrary information attached to
them.  People were often using docstrings to hold information about
functions and methods, because the ‘__doc__’ attribute was the only way
of attaching any information to a function.  For example, in the Zope
Web application server, functions are marked as safe for public access
by having a docstring, and in John Aycock’s SPARK parsing framework,
docstrings hold parts of the BNF grammar to be parsed.  This overloading
is unfortunate, since docstrings are really intended to hold a
function’s documentation; for example, it means you can’t properly
document functions intended for private use in Zope.

Arbitrary attributes can now be set and retrieved on functions using the
regular Python syntax:

     def f(): pass

     f.publish = 1
     f.secure = 1
     f.grammar = "A ::= B (C D)*"

The dictionary containing attributes can be accessed as the function’s
*note __dict__: 504.  Unlike the *note __dict__: 504. attribute of class
instances, in functions you can actually assign a new dictionary to
*note __dict__: 504, though the new value is restricted to a regular
Python dictionary; you `can’t' be tricky and set it to a ‘UserDict’
instance, or any other random object that behaves like a mapping.

参见
....

PEP 232(1) - Function Attributes

     由 Barry Warsaw 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0232


File: python.info,  Node: PEP 235 Importing Modules on Case-Insensitive Platforms,  Next: PEP 217 Interactive Display Hook,  Prev: PEP 232 Function Attributes,  Up: Python 2 1 有什么新变化

1.16.9 PEP 235: Importing Modules on Case-Insensitive Platforms
---------------------------------------------------------------

Some operating systems have filesystems that are case-insensitive, MacOS
and Windows being the primary examples; on these systems, it’s
impossible to distinguish the filenames ‘FILE.PY’ and ‘file.py’, even
though they do store the file’s name in its original case (they’re
case-preserving, too).

In Python 2.1, the *note import: c25. statement will work to simulate
case-sensitivity on case-insensitive platforms.  Python will now search
for the first case-sensitive match by default, raising an *note
ImportError: 33d. if no such file is found, so ‘import file’ will not
import a module named ‘FILE.PY’.  Case-insensitive matching can be
requested by setting the *note PYTHONCASEOK: e65. environment variable
before starting the Python interpreter.


File: python.info,  Node: PEP 217 Interactive Display Hook,  Next: PEP 208 New Coercion Model,  Prev: PEP 235 Importing Modules on Case-Insensitive Platforms,  Up: Python 2 1 有什么新变化

1.16.10 PEP 217: Interactive Display Hook
-----------------------------------------

When using the Python interpreter interactively, the output of commands
is displayed using the built-in *note repr(): 7d5. function.  In Python
2.1, the variable *note sys.displayhook(): e67. can be set to a callable
object which will be called instead of *note repr(): 7d5.  For example,
you can set it to a special pretty-printing function:

     >>> # Create a recursive data structure
     ... L = [1,2,3]
     >>> L.append(L)
     >>> L # Show Python's default output
     [1, 2, 3, [...]]
     >>> # Use pprint.pprint() as the display function
     ... import sys, pprint
     >>> sys.displayhook = pprint.pprint
     >>> L
     [1, 2, 3,  <Recursion on list with id=135143996>]
     >>>

参见
....

PEP 217(1) - Display Hook for Interactive Use

     由 Moshe Zadka 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0217


File: python.info,  Node: PEP 208 New Coercion Model,  Next: PEP 241 Metadata in Python Packages,  Prev: PEP 217 Interactive Display Hook,  Up: Python 2 1 有什么新变化

1.16.11 PEP 208: New Coercion Model
-----------------------------------

How numeric coercion is done at the C level was significantly modified.
This will only affect the authors of C extensions to Python, allowing
them more flexibility in writing extension types that support numeric
operations.

Extension types can now set the type flag ‘Py_TPFLAGS_CHECKTYPES’ in
their ‘PyTypeObject’ structure to indicate that they support the new
coercion model.  In such extension types, the numeric slot functions can
no longer assume that they’ll be passed two arguments of the same type;
instead they may be passed two arguments of differing types, and can
then perform their own internal coercion.  If the slot function is
passed a type it can’t handle, it can indicate the failure by returning
a reference to the ‘Py_NotImplemented’ singleton value.  The numeric
functions of the other type will then be tried, and perhaps they can
handle the operation; if the other type also returns
‘Py_NotImplemented’, then a *note TypeError: 193. will be raised.
Numeric methods written in Python can also return ‘Py_NotImplemented’,
causing the interpreter to act as if the method did not exist (perhaps
raising a *note TypeError: 193, perhaps trying another object’s numeric
methods).

参见
....

PEP 208(1) - Reworking the Coercion Model

     Written and implemented by Neil Schemenauer, heavily based upon
     earlier work by Marc-André Lemburg.  Read this to understand the
     fine points of how numeric operations will now be processed at the
     C level.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0208


File: python.info,  Node: PEP 241 Metadata in Python Packages,  Next: 新增和改进的模块<4>,  Prev: PEP 208 New Coercion Model,  Up: Python 2 1 有什么新变化

1.16.12 PEP 241: Metadata in Python Packages
--------------------------------------------

A common complaint from Python users is that there’s no single catalog
of all the Python modules in existence.  T. Middleton’s Vaults of
Parnassus at ‘http://www.vex.net/parnassus/’ are the largest catalog of
Python modules, but registering software at the Vaults is optional, and
many people don’t bother.

As a first small step toward fixing the problem, Python software
packaged using the Distutils ‘sdist’ command will include a file named
‘PKG-INFO’ containing information about the package such as its name,
version, and author (metadata, in cataloguing terminology).  PEP 241(1)
contains the full list of fields that can be present in the ‘PKG-INFO’
file.  As people began to package their software using Python 2.1, more
and more packages will include metadata, making it possible to build
automated cataloguing systems and experiment with them.  With the result
experience, perhaps it’ll be possible to design a really good catalog
and then build support for it into Python 2.2.  For example, the
Distutils ‘sdist’ and ‘bdist_*’ commands could support an ‘upload’
option that would automatically upload your package to a catalog server.

You can start creating packages containing ‘PKG-INFO’ even if you’re not
using Python 2.1, since a new release of the Distutils will be made for
users of earlier Python versions.  Version 1.0.2 of the Distutils
includes the changes described in PEP 241(2), as well as various
bugfixes and enhancements.  It will be available from the Distutils SIG
at ‘https://www.python.org/community/sigs/current/distutils-sig/’.

参见
....

PEP 241(3) - Metadata for Python Software Packages

     由 A.M. Kuchling 撰写并实现。

PEP 243(4) - Module Repository Upload Mechanism

     Written by Sean Reifschneider, this draft PEP describes a proposed
     mechanism for uploading Python packages to a central server.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0241

   (2) https://www.python.org/dev/peps/pep-0241

   (3) https://www.python.org/dev/peps/pep-0241

   (4) https://www.python.org/dev/peps/pep-0243


File: python.info,  Node: 新增和改进的模块<4>,  Next: Other Changes and Fixes<4>,  Prev: PEP 241 Metadata in Python Packages,  Up: Python 2 1 有什么新变化

1.16.13 新增和改进的模块
------------------------

   * Ka-Ping Yee contributed two new modules: ‘inspect.py’, a module for
     getting information about live Python code, and ‘pydoc.py’, a
     module for interactively converting docstrings to HTML or text.  As
     a bonus, ‘Tools/scripts/pydoc’, which is now automatically
     installed, uses ‘pydoc.py’ to display documentation given a Python
     module, package, or class name.  For example, ‘pydoc xml.dom’
     displays the following:

          Python Library Documentation: package xml.dom in xml

          NAME
              xml.dom - W3C Document Object Model implementation for Python.

          FILE
              /usr/local/lib/python2.1/xml/dom/__init__.pyc

          DESCRIPTION
              The Python mapping of the Document Object Model is documented in the
              Python Library Reference in the section on the xml.dom package.

              This package contains the following modules:
                ...

     ‘pydoc’ also includes a Tk-based interactive help browser.  ‘pydoc’
     quickly becomes addictive; try it out!

   * Two different modules for unit testing were added to the standard
     library.  The *note doctest: 67. module, contributed by Tim Peters,
     provides a testing framework based on running embedded examples in
     docstrings and comparing the results against the expected output.
     PyUnit, contributed by Steve Purcell, is a unit testing framework
     inspired by JUnit, which was in turn an adaptation of Kent Beck’s
     Smalltalk testing framework.  See ‘http://pyunit.sourceforge.net/’
     for more information about PyUnit.

   * The *note difflib: 37. module contains a class, ‘SequenceMatcher’,
     which compares two sequences and computes the changes required to
     transform one sequence into the other.  For example, this module
     can be used to write a tool similar to the Unix ‘diff’ program, and
     in fact the sample program ‘Tools/scripts/ndiff.py’ demonstrates
     how to write such a script.

   * *note curses.panel: 2e, a wrapper for the panel library, part of
     ncurses and of SYSV curses, was contributed by Thomas Gellekum.
     The panel library provides windows with the additional feature of
     depth.  Windows can be moved higher or lower in the depth ordering,
     and the panel library figures out where panels overlap and which
     sections are visible.

   * The PyXML package has gone through a few releases since Python 2.0,
     and Python 2.1 includes an updated version of the *note xml: 134.
     package.  Some of the noteworthy changes include support for Expat
     1.2 and later versions, the ability for Expat parsers to handle
     files in any encoding supported by Python, and various bugfixes for
     SAX, DOM, and the ‘minidom’ module.

   * Ping also contributed another hook for handling uncaught
     exceptions.  *note sys.excepthook(): e6b. can be set to a callable
     object.  When an exception isn’t caught by any *note try:
     d7a...*note except: b46. blocks, the exception will be passed to
     *note sys.excepthook(): e6b, which can then do whatever it likes.
     At the Ninth Python Conference, Ping demonstrated an application
     for this hook: printing an extended traceback that not only lists
     the stack frames, but also lists the function arguments and the
     local variables for each frame.

   * Various functions in the *note time: 10b. module, such as
     ‘asctime()’ and ‘localtime()’, require a floating point argument
     containing the time in seconds since the epoch.  The most common
     use of these functions is to work with the current time, so the
     floating point argument has been made optional; when a value isn’t
     provided, the current time will be used.  For example, log file
     entries usually need a string containing the current time; in
     Python 2.1, ‘time.asctime()’ can be used, instead of the lengthier
     ‘time.asctime(time.localtime(time.time()))’ that was previously
     required.

     This change was proposed and implemented by Thomas Wouters.

   * The *note ftplib: 84. module now defaults to retrieving files in
     passive mode, because passive mode is more likely to work from
     behind a firewall.  This request came from the Debian bug tracking
     system, since other Debian packages use *note ftplib: 84. to
     retrieve files and then don’t work from behind a firewall.  It’s
     deemed unlikely that this will cause problems for anyone, because
     Netscape defaults to passive mode and few people complain, but if
     passive mode is unsuitable for your application or network setup,
     call ‘set_pasv(0)’ on FTP objects to disable passive mode.

   * Support for raw socket access has been added to the *note socket:
     f0. module, contributed by Grant Edwards.

   * The *note pstats: d5. module now contains a simple interactive
     statistics browser for displaying timing profiles for Python
     programs, invoked when the module is run as a script.  Contributed
     by Eric S. Raymond.

   * A new implementation-dependent function, ‘sys._getframe([depth])’,
     has been added to return a given frame object from the current call
     stack.  *note sys._getframe(): e6c. returns the frame at the top of
     the call stack; if the optional integer argument `depth' is
     supplied, the function returns the frame that is `depth' calls
     below the top of the stack.  For example, ‘sys._getframe(1)’
     returns the caller’s frame object.

     This function is only present in CPython, not in Jython or the .NET
     implementation.  Use it for debugging, and resist the temptation to
     put it into production code.


File: python.info,  Node: Other Changes and Fixes<4>,  Next: 致谢<7>,  Prev: 新增和改进的模块<4>,  Up: Python 2 1 有什么新变化

1.16.14 Other Changes and Fixes
-------------------------------

There were relatively few smaller changes made in Python 2.1 due to the
shorter release cycle.  A search through the CVS change logs turns up
117 patches applied, and 136 bugs fixed; both figures are likely to be
underestimates.  Some of the more notable changes are:

   * A specialized object allocator is now optionally available, that
     should be faster than the system ‘malloc()’ and have less memory
     overhead.  The allocator uses C’s ‘malloc()’ function to get large
     pools of memory, and then fulfills smaller memory requests from
     these pools.  It can be enabled by providing the ‘--with-pymalloc’
     option to the ‘configure’ script; see ‘Objects/obmalloc.c’ for the
     implementation details.

     Authors of C extension modules should test their code with the
     object allocator enabled, because some incorrect code may break,
     causing core dumps at runtime.  There are a bunch of memory
     allocation functions in Python’s C API that have previously been
     just aliases for the C library’s ‘malloc()’ and ‘free()’, meaning
     that if you accidentally called mismatched functions, the error
     wouldn’t be noticeable.  When the object allocator is enabled,
     these functions aren’t aliases of ‘malloc()’ and ‘free()’ any more,
     and calling the wrong function to free memory will get you a core
     dump.  For example, if memory was allocated using ‘PyMem_New()’, it
     has to be freed using ‘PyMem_Del()’, not ‘free()’.  A few modules
     included with Python fell afoul of this and had to be fixed;
     doubtless there are more third-party modules that will have the
     same problem.

     The object allocator was contributed by Vladimir Marangozov.

   * The speed of line-oriented file I/O has been improved because
     people often complain about its lack of speed, and because it’s
     often been used as a naïve benchmark.  The *note readline(): df.
     method of file objects has therefore been rewritten to be much
     faster.  The exact amount of the speedup will vary from platform to
     platform depending on how slow the C library’s ‘getc()’ was, but is
     around 66%, and potentially much faster on some particular
     operating systems.  Tim Peters did much of the benchmarking and
     coding for this change, motivated by a discussion in
     comp.lang.python.

     A new module and method for file objects was also added,
     contributed by Jeff Epler.  The new method, ‘xreadlines()’, is
     similar to the existing ‘xrange()’ built-in.  ‘xreadlines()’
     returns an opaque sequence object that only supports being iterated
     over, reading a line on every iteration but not reading the entire
     file into memory as the existing ‘readlines()’ method does.  You’d
     use it like this:

          for line in sys.stdin.xreadlines():
              # ... do something for each line ...
              ...

     For a fuller discussion of the line I/O changes, see the python-dev
     summary for January 1–15, 2001 at
     ‘https://mail.python.org/pipermail/python-dev/2001-January/’.

   * A new method, ‘popitem()’, was added to dictionaries to enable
     destructively iterating through the contents of a dictionary; this
     can be faster for large dictionaries because there’s no need to
     construct a list containing all the keys or values.  ‘D.popitem()’
     removes a random ‘(key, value)’ pair from the dictionary ‘D’ and
     returns it as a 2-tuple.  This was implemented mostly by Tim Peters
     and Guido van Rossum, after a suggestion and preliminary patch by
     Moshe Zadka.

   * Modules can now control which names are imported when ‘from module
     import *’ is used, by defining an ‘__all__’ attribute containing a
     list of names that will be imported.  One common complaint is that
     if the module imports other modules such as *note sys: fe. or *note
     string: f7, ‘from module import *’ will add them to the importing
     module’s namespace.  To fix this, simply list the public names in
     ‘__all__’:

          # List public names
          __all__ = ['Database', 'open']

     A stricter version of this patch was first suggested and
     implemented by Ben Wolfson, but after some python-dev discussion, a
     weaker final version was checked in.

   * Applying *note repr(): 7d5. to strings previously used octal
     escapes for non-printable characters; for example, a newline was
     ‘'\012'’.  This was a vestigial trace of Python’s C ancestry, but
     today octal is of very little practical use.  Ka-Ping Yee suggested
     using hex escapes instead of octal ones, and using the ‘\n’, ‘\t’,
     ‘\r’ escapes for the appropriate characters, and implemented this
     new formatting.

   * Syntax errors detected at compile-time can now raise exceptions
     containing the filename and line number of the error, a pleasant
     side effect of the compiler reorganization done by Jeremy Hylton.

   * C extensions which import other modules have been changed to use
     ‘PyImport_ImportModule()’, which means that they will use any
     import hooks that have been installed.  This is also encouraged for
     third-party extensions that need to import some other module from C
     code.

   * The size of the Unicode character database was shrunk by another
     340K thanks to Fredrik Lundh.

   * Some new ports were contributed: MacOS X (by Steven Majewski),
     Cygwin (by Jason Tishler); RISCOS (by Dietmar Schwertberger);
     Unixware 7 (by Billy G. Allie).

And there’s the usual list of minor bugfixes, minor memory leaks,
docstring edits, and other tweaks, too lengthy to be worth itemizing;
see the CVS logs for the full details if you want them.


File: python.info,  Node: 致谢<7>,  Prev: Other Changes and Fixes<4>,  Up: Python 2 1 有什么新变化

1.16.15 致谢
------------

作者感谢以下人员对本文的各种草案提出建议： Graeme Cross, David Goodger,
Jay Graves, Michael Hudson, Marc-André Lemburg, Fredrik Lundh, Neil
Schemenauer, Thomas Wouters.


File: python.info,  Node: Python 2 0 有什么新变化,  Next: 更新日志,  Prev: Python 2 1 有什么新变化,  Up: Python的新变化

1.17 Python 2.0 有什么新变化
============================


作者: A.M. Kuchling 和 Moshe Zadka

* Menu:

* 概述: 概述<3>.
* What About Python 1.6?: What About Python 1 6?.
* 新开发流程::
* Unicode: Unicode<2>.
* 列表推导式::
* Augmented Assignment::
* 字符串的方法::
* Garbage Collection of Cycles::
* 其他核心变化::
* 移植 Python 2.0: 移植 Python 2 0.
* 扩展/嵌入更改::
* Distutils：使模块易于安装::
* XML 模块::
* 模块更改::
* 新增模块: 新增模块<7>.
* IDLE 改进::
* 删除和弃用的模块::
* 致谢: 致谢<8>.


File: python.info,  Node: 概述<3>,  Next: What About Python 1 6?,  Up: Python 2 0 有什么新变化

1.17.1 概述
-----------

A new release of Python, version 2.0, was released on October 16, 2000.
This article covers the exciting new features in 2.0, highlights some
other useful changes, and points out a few incompatible changes that may
require rewriting code.

Python’s development never completely stops between releases, and a
steady flow of bug fixes and improvements are always being submitted.  A
host of minor fixes, a few optimizations, additional docstrings, and
better error messages went into 2.0; to list them all would be
impossible, but they’re certainly significant.  Consult the
publicly-available CVS logs if you want to see the full list.  This
progress is due to the five developers working for PythonLabs are now
getting paid to spend their days fixing bugs, and also due to the
improved communication resulting from moving to SourceForge.


File: python.info,  Node: What About Python 1 6?,  Next: 新开发流程,  Prev: 概述<3>,  Up: Python 2 0 有什么新变化

1.17.2 What About Python 1.6?
-----------------------------

Python 1.6 can be thought of as the Contractual Obligations Python
release.  After the core development team left CNRI in May 2000, CNRI
requested that a 1.6 release be created, containing all the work on
Python that had been performed at CNRI. Python 1.6 therefore represents
the state of the CVS tree as of May 2000, with the most significant new
feature being Unicode support.  Development continued after May, of
course, so the 1.6 tree received a few fixes to ensure that it’s
forward-compatible with Python 2.0.  1.6 is therefore part of Python’s
evolution, and not a side branch.

So, should you take much interest in Python 1.6?  Probably not.  The
1.6final and 2.0beta1 releases were made on the same day (September 5,
2000), the plan being to finalize Python 2.0 within a month or so.  If
you have applications to maintain, there seems little point in breaking
things by moving to 1.6, fixing them, and then having another round of
breakage within a month by moving to 2.0; you’re better off just going
straight to 2.0.  Most of the really interesting features described in
this document are only in 2.0, because a lot of work was done between
May and September.


File: python.info,  Node: 新开发流程,  Next: Unicode<2>,  Prev: What About Python 1 6?,  Up: Python 2 0 有什么新变化

1.17.3 新开发流程
-----------------

The most important change in Python 2.0 may not be to the code at all,
but to how Python is developed: in May 2000 the Python developers began
using the tools made available by SourceForge for storing source code,
tracking bug reports, and managing the queue of patch submissions.  To
report bugs or submit patches for Python 2.0, use the bug tracking and
patch manager tools available from Python’s project page, located at
‘https://sourceforge.net/projects/python/’.

The most important of the services now hosted at SourceForge is the
Python CVS tree, the version-controlled repository containing the source
code for Python.  Previously, there were roughly 7 or so people who had
write access to the CVS tree, and all patches had to be inspected and
checked in by one of the people on this short list.  Obviously, this
wasn’t very scalable.  By moving the CVS tree to SourceForge, it became
possible to grant write access to more people; as of September 2000
there were 27 people able to check in changes, a fourfold increase.
This makes possible large-scale changes that wouldn’t be attempted if
they’d have to be filtered through the small group of core developers.
For example, one day Peter Schneider-Kamp took it into his head to drop
K&R C compatibility and convert the C source for Python to ANSI C. After
getting approval on the python-dev mailing list, he launched into a
flurry of checkins that lasted about a week, other developers joined in
to help, and the job was done.  If there were only 5 people with write
access, probably that task would have been viewed as "nice, but not
worth the time and effort needed" and it would never have gotten done.

The shift to using SourceForge’s services has resulted in a remarkable
increase in the speed of development.  Patches now get submitted,
commented on, revised by people other than the original submitter, and
bounced back and forth between people until the patch is deemed worth
checking in.  Bugs are tracked in one central location and can be
assigned to a specific person for fixing, and we can count the number of
open bugs to measure progress.  This didn’t come without a cost:
developers now have more e-mail to deal with, more mailing lists to
follow, and special tools had to be written for the new environment.
For example, SourceForge sends default patch and bug notification e-mail
messages that are completely unhelpful, so Ka-Ping Yee wrote an HTML
screen-scraper that sends more useful messages.

The ease of adding code caused a few initial growing pains, such as code
was checked in before it was ready or without getting clear agreement
from the developer group.  The approval process that has emerged is
somewhat similar to that used by the Apache group.  Developers can vote
+1, +0, -0, or -1 on a patch; +1 and -1 denote acceptance or rejection,
while +0 and -0 mean the developer is mostly indifferent to the change,
though with a slight positive or negative slant.  The most significant
change from the Apache model is that the voting is essentially advisory,
letting Guido van Rossum, who has Benevolent Dictator For Life status,
know what the general opinion is.  He can still ignore the result of a
vote, and approve or reject a change even if the community disagrees
with him.

Producing an actual patch is the last step in adding a new feature, and
is usually easy compared to the earlier task of coming up with a good
design.  Discussions of new features can often explode into lengthy
mailing list threads, making the discussion hard to follow, and no one
can read every posting to python-dev.  Therefore, a relatively formal
process has been set up to write Python Enhancement Proposals (PEPs),
modelled on the Internet RFC process.  PEPs are draft documents that
describe a proposed new feature, and are continually revised until the
community reaches a consensus, either accepting or rejecting the
proposal.  Quoting from the introduction to PEP 1(1), "PEP Purpose and
Guidelines":

     PEP stands for Python Enhancement Proposal.  A PEP is a design
     document providing information to the Python community, or
     describing a new feature for Python.  The PEP should provide a
     concise technical specification of the feature and a rationale for
     the feature.

     We intend PEPs to be the primary mechanisms for proposing new
     features, for collecting community input on an issue, and for
     documenting the design decisions that have gone into Python.  The
     PEP author is responsible for building consensus within the
     community and documenting dissenting opinions.

Read the rest of PEP 1(2) for the details of the PEP editorial process,
style, and format.  PEPs are kept in the Python CVS tree on SourceForge,
though they’re not part of the Python 2.0 distribution, and are also
available in HTML form from ‘https://www.python.org/dev/peps/’.  As of
September 2000, there are 25 PEPS, ranging from PEP 201(3), "Lockstep
Iteration", to PEP 225, "Elementwise/Objectwise Operators".

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0001

   (2) https://www.python.org/dev/peps/pep-0001

   (3) https://www.python.org/dev/peps/pep-0201


File: python.info,  Node: Unicode<2>,  Next: 列表推导式,  Prev: 新开发流程,  Up: Python 2 0 有什么新变化

1.17.4 Unicode
--------------

The largest new feature in Python 2.0 is a new fundamental data type:
Unicode strings.  Unicode uses 16-bit numbers to represent characters
instead of the 8-bit number used by ASCII, meaning that 65,536 distinct
characters can be supported.

The final interface for Unicode support was arrived at through countless
often-stormy discussions on the python-dev mailing list, and mostly
implemented by Marc-André Lemburg, based on a Unicode string type
implementation by Fredrik Lundh.  A detailed explanation of the
interface was written up as PEP 100(1), "Python Unicode Integration".
This article will simply cover the most significant points about the
Unicode interfaces.

In Python source code, Unicode strings are written as ‘u"string"’.
Arbitrary Unicode characters can be written using a new escape sequence,
‘\uHHHH’, where `HHHH' is a 4-digit hexadecimal number from 0000 to
FFFF. The existing ‘\xHHHH’ escape sequence can also be used, and octal
escapes can be used for characters up to U+01FF, which is represented by
‘\777’.

Unicode strings, just like regular strings, are an immutable sequence
type.  They can be indexed and sliced, but not modified in place.
Unicode strings have an ‘encode( [encoding] )’ method that returns an
8-bit string in the desired encoding.  Encodings are named by strings,
such as ‘'ascii'’, ‘'utf-8'’, ‘'iso-8859-1'’, or whatever.  A codec API
is defined for implementing and registering new encodings that are then
available throughout a Python program.  If an encoding isn’t specified,
the default encoding is usually 7-bit ASCII, though it can be changed
for your Python installation by calling the
‘sys.setdefaultencoding(encoding)’ function in a customized version of
‘site.py’.

Combining 8-bit and Unicode strings always coerces to Unicode, using the
default ASCII encoding; the result of ‘'a' + u'bc'’ is ‘u'abc'’.

New built-in functions have been added, and existing built-ins modified
to support Unicode:

   * ‘unichr(ch)’ returns a Unicode string 1 character long, containing
     the character `ch'.

   * ‘ord(u)’, where `u' is a 1-character regular or Unicode string,
     returns the number of the character as an integer.

   * ‘unicode(string [, encoding] [, errors] )’ creates a Unicode string
     from an 8-bit string.  ‘encoding’ is a string naming the encoding
     to use.  The ‘errors’ parameter specifies the treatment of
     characters that are invalid for the current encoding; passing
     ‘'strict'’ as the value causes an exception to be raised on any
     encoding error, while ‘'ignore'’ causes errors to be silently
     ignored and ‘'replace'’ uses U+FFFD, the official replacement
     character, in case of any problems.

   * The ‘exec’ statement, and various built-ins such as ‘eval()’,
     ‘getattr()’, and ‘setattr()’ will also accept Unicode strings as
     well as regular strings.  (It’s possible that the process of fixing
     this missed some built-ins; if you find a built-in function that
     accepts strings but doesn’t accept Unicode strings at all, please
     report it as a bug.)

A new module, *note unicodedata: 11b, provides an interface to Unicode
character properties.  For example, ‘unicodedata.category(u'A')’ returns
the 2-character string ’Lu’, the ’L’ denoting it’s a letter, and ’u’
meaning that it’s uppercase.  ‘unicodedata.bidirectional(u'\u0660')’
returns ’AN’, meaning that U+0660 is an Arabic number.

The *note codecs: 1c. module contains functions to look up existing
encodings and register new ones.  Unless you want to implement a new
encoding, you’ll most often use the ‘codecs.lookup(encoding)’ function,
which returns a 4-element tuple: ‘(encode_func, decode_func,
stream_reader, stream_writer)’.

   * `encode_func' is a function that takes a Unicode string, and
     returns a 2-tuple ‘(string, length)’.  `string' is an 8-bit string
     containing a portion (perhaps all) of the Unicode string converted
     into the given encoding, and `length' tells you how much of the
     Unicode string was converted.

   * `decode_func' is the opposite of `encode_func', taking an 8-bit
     string and returning a 2-tuple ‘(ustring, length)’, consisting of
     the resulting Unicode string `ustring' and the integer `length'
     telling how much of the 8-bit string was consumed.

   * `stream_reader' is a class that supports decoding input from a
     stream.  `stream_reader(file_obj)' returns an object that supports
     the ‘read()’, *note readline(): df, and ‘readlines()’ methods.
     These methods will all translate from the given encoding and return
     Unicode strings.

   * `stream_writer', similarly, is a class that supports encoding
     output to a stream.  `stream_writer(file_obj)' returns an object
     that supports the ‘write()’ and ‘writelines()’ methods.  These
     methods expect Unicode strings, translating them to the given
     encoding on output.

For example, the following code writes a Unicode string into a file,
encoding it as UTF-8:

     import codecs

     unistr = u'\u0660\u2000ab ...'

     (UTF8_encode, UTF8_decode,
      UTF8_streamreader, UTF8_streamwriter) = codecs.lookup('UTF-8')

     output = UTF8_streamwriter( open( '/tmp/output', 'wb') )
     output.write( unistr )
     output.close()

The following code would then read UTF-8 input from the file:

     input = UTF8_streamreader( open( '/tmp/output', 'rb') )
     print repr(input.read())
     input.close()

Unicode-aware regular expressions are available through the *note re:
de. module, which has a new underlying implementation called SRE written
by Fredrik Lundh of Secret Labs AB.

A ‘-U’ command line option was added which causes the Python compiler to
interpret all string literals as Unicode string literals.  This is
intended to be used in testing and future-proofing your Python code,
since some future version of Python may drop support for 8-bit strings
and provide only Unicode strings.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0100


File: python.info,  Node: 列表推导式,  Next: Augmented Assignment,  Prev: Unicode<2>,  Up: Python 2 0 有什么新变化

1.17.5 列表推导式
-----------------

Lists are a workhorse data type in Python, and many programs manipulate
a list at some point.  Two common operations on lists are to loop over
them, and either pick out the elements that meet a certain criterion, or
apply some function to each element.  For example, given a list of
strings, you might want to pull out all the strings containing a given
substring, or strip off trailing whitespace from each line.

The existing *note map(): c35. and *note filter(): c36. functions can be
used for this purpose, but they require a function as one of their
arguments.  This is fine if there’s an existing built-in function that
can be passed directly, but if there isn’t, you have to create a little
function to do the required work, and Python’s scoping rules make the
result ugly if the little function needs additional information.  Take
the first example in the previous paragraph, finding all the strings in
the list containing a given substring.  You could write the following to
do it:

     # Given the list L, make a list of all strings
     # containing the substring S.
     sublist = filter( lambda s, substring=S:
                          string.find(s, substring) != -1,
                       L)

Because of Python’s scoping rules, a default argument is used so that
the anonymous function created by the *note lambda: c37. expression
knows what substring is being searched for.  List comprehensions make
this cleaner:

     sublist = [ s for s in L if string.find(s, S) != -1 ]

List comprehensions have the form:

     [ expression for expr in sequence1
                  for expr2 in sequence2 ...
                  for exprN in sequenceN
                  if condition ]

The ‘for’...‘in’ clauses contain the sequences to be iterated over.  The
sequences do not have to be the same length, because they are `not'
iterated over in parallel, but from left to right; this is explained
more clearly in the following paragraphs.  The elements of the generated
list will be the successive values of `expression'.  The final ‘if’
clause is optional; if present, `expression' is only evaluated and added
to the result if `condition' is true.

To make the semantics very clear, a list comprehension is equivalent to
the following Python code:

     for expr1 in sequence1:
         for expr2 in sequence2:
         ...
             for exprN in sequenceN:
                  if (condition):
                       # Append the value of
                       # the expression to the
                       # resulting list.

This means that when there are multiple ‘for’...‘in’ clauses, the
resulting list will be equal to the product of the lengths of all the
sequences.  If you have two lists of length 3, the output list is 9
elements long:

     seq1 = 'abc'
     seq2 = (1,2,3)
     >>> [ (x,y) for x in seq1 for y in seq2]
     [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1),
     ('c', 2), ('c', 3)]

To avoid introducing an ambiguity into Python’s grammar, if `expression'
is creating a tuple, it must be surrounded with parentheses.  The first
list comprehension below is a syntax error, while the second one is
correct:

     # Syntax error
     [ x,y for x in seq1 for y in seq2]
     # Correct
     [ (x,y) for x in seq1 for y in seq2]

The idea of list comprehensions originally comes from the functional
programming language Haskell (‘https://www.haskell.org’).  Greg Ewing
argued most effectively for adding them to Python and wrote the initial
list comprehension patch, which was then discussed for a seemingly
endless time on the python-dev mailing list and kept up-to-date by Skip
Montanaro.


File: python.info,  Node: Augmented Assignment,  Next: 字符串的方法,  Prev: 列表推导式,  Up: Python 2 0 有什么新变化

1.17.6 Augmented Assignment
---------------------------

Augmented assignment operators, another long-requested feature, have
been added to Python 2.0.  Augmented assignment operators include ‘+=’,
‘-=’, ‘*=’, and so forth.  For example, the statement ‘a += 2’
increments the value of the variable ‘a’ by 2, equivalent to the
slightly lengthier ‘a = a + 2’.

The full list of supported assignment operators is ‘+=’, ‘-=’, ‘*=’,
‘/=’, ‘%=’, ‘**=’, ‘&=’, ‘|=’, ‘^=’, ‘>>=’, and ‘<<=’.  Python classes
can override the augmented assignment operators by defining methods
named *note __iadd__(): e77, *note __isub__(): e78, etc.  For example,
the following ‘Number’ class stores a number and supports using += to
create a new instance with an incremented value.

     class Number:
         def __init__(self, value):
             self.value = value
         def __iadd__(self, increment):
             return Number( self.value + increment)

     n = Number(5)
     n += 3
     print n.value

The *note __iadd__(): e77. special method is called with the value of
the increment, and should return a new instance with an appropriately
modified value; this return value is bound as the new value of the
variable on the left-hand side.

Augmented assignment operators were first introduced in the C
programming language, and most C-derived languages, such as ‘awk’, C++,
Java, Perl, and PHP also support them.  The augmented assignment patch
was implemented by Thomas Wouters.


File: python.info,  Node: 字符串的方法,  Next: Garbage Collection of Cycles,  Prev: Augmented Assignment,  Up: Python 2 0 有什么新变化

1.17.7 字符串的方法
-------------------

Until now string-manipulation functionality was in the *note string: f7.
module, which was usually a front-end for the ‘strop’ module written in
C. The addition of Unicode posed a difficulty for the ‘strop’ module,
because the functions would all need to be rewritten in order to accept
either 8-bit or Unicode strings.  For functions such as
‘string.replace()’, which takes 3 string arguments, that means eight
possible permutations, and correspondingly complicated code.

Instead, Python 2.0 pushes the problem onto the string type, making
string manipulation functionality available through methods on both
8-bit strings and Unicode strings.

     >>> 'andrew'.capitalize()
     'Andrew'
     >>> 'hostname'.replace('os', 'linux')
     'hlinuxtname'
     >>> 'moshe'.find('sh')
     2

One thing that hasn’t changed, a noteworthy April Fools’ joke
notwithstanding, is that Python strings are immutable.  Thus, the string
methods return new strings, and do not modify the string on which they
operate.

The old *note string: f7. module is still around for backwards
compatibility, but it mostly acts as a front-end to the new string
methods.

Two methods which have no parallel in pre-2.0 versions, although they
did exist in JPython for quite some time, are ‘startswith()’ and
‘endswith()’.  ‘s.startswith(t)’ is equivalent to ‘s[:len(t)] == t’,
while ‘s.endswith(t)’ is equivalent to ‘s[-len(t):] == t’.

One other method which deserves special mention is ‘join()’.  The
‘join()’ method of a string receives one parameter, a sequence of
strings, and is equivalent to the ‘string.join()’ function from the old
*note string: f7. module, with the arguments reversed.  In other words,
‘s.join(seq)’ is equivalent to the old ‘string.join(seq, s)’.


File: python.info,  Node: Garbage Collection of Cycles,  Next: 其他核心变化,  Prev: 字符串的方法,  Up: Python 2 0 有什么新变化

1.17.8 Garbage Collection of Cycles
-----------------------------------

The C implementation of Python uses reference counting to implement
garbage collection.  Every Python object maintains a count of the number
of references pointing to itself, and adjusts the count as references
are created or destroyed.  Once the reference count reaches zero, the
object is no longer accessible, since you need to have a reference to an
object to access it, and if the count is zero, no references exist any
longer.

Reference counting has some pleasant properties: it’s easy to understand
and implement, and the resulting implementation is portable, fairly
fast, and reacts well with other libraries that implement their own
memory handling schemes.  The major problem with reference counting is
that it sometimes doesn’t realise that objects are no longer accessible,
resulting in a memory leak.  This happens when there are cycles of
references.

Consider the simplest possible cycle, a class instance which has a
reference to itself:

     instance = SomeClass()
     instance.myself = instance

After the above two lines of code have been executed, the reference
count of ‘instance’ is 2; one reference is from the variable named
‘'instance'’, and the other is from the ‘myself’ attribute of the
instance.

If the next line of code is ‘del instance’, what happens?  The reference
count of ‘instance’ is decreased by 1, so it has a reference count of 1;
the reference in the ‘myself’ attribute still exists.  Yet the instance
is no longer accessible through Python code, and it could be deleted.
Several objects can participate in a cycle if they have references to
each other, causing all of the objects to be leaked.

Python 2.0 fixes this problem by periodically executing a cycle
detection algorithm which looks for inaccessible cycles and deletes the
objects involved.  A new *note gc: 86. module provides functions to
perform a garbage collection, obtain debugging statistics, and tuning
the collector’s parameters.

Running the cycle detection algorithm takes some time, and therefore
will result in some additional overhead.  It is hoped that after we’ve
gotten experience with the cycle collection from using 2.0, Python 2.1
will be able to minimize the overhead with careful tuning.  It’s not yet
obvious how much performance is lost, because benchmarking this is
tricky and depends crucially on how often the program creates and
destroys objects.  The detection of cycles can be disabled when Python
is compiled, if you can’t afford even a tiny speed penalty or suspect
that the cycle collection is buggy, by specifying the
‘--without-cycle-gc’ switch when running the ‘configure’ script.

Several people tackled this problem and contributed to a solution.  An
early implementation of the cycle detection approach was written by Toby
Kelsey.  The current algorithm was suggested by Eric Tiedemann during a
visit to CNRI, and Guido van Rossum and Neil Schemenauer wrote two
different implementations, which were later integrated by Neil.  Lots of
other people offered suggestions along the way; the March 2000 archives
of the python-dev mailing list contain most of the relevant discussion,
especially in the threads titled "Reference cycle collection for Python"
and "Finalization again".


File: python.info,  Node: 其他核心变化,  Next: 移植 Python 2 0,  Prev: Garbage Collection of Cycles,  Up: Python 2 0 有什么新变化

1.17.9 其他核心变化
-------------------

Various minor changes have been made to Python’s syntax and built-in
functions.  None of the changes are very far-reaching, but they’re handy
conveniences.

* Menu:

* Minor Language Changes::
* Changes to Built-in Functions::


File: python.info,  Node: Minor Language Changes,  Next: Changes to Built-in Functions,  Up: 其他核心变化

1.17.9.1 Minor Language Changes
...............................

A new syntax makes it more convenient to call a given function with a
tuple of arguments and/or a dictionary of keyword arguments.  In Python
1.5 and earlier, you’d use the ‘apply()’ built-in function: ‘apply(f,
args, kw)’ calls the function ‘f()’ with the argument tuple `args' and
the keyword arguments in the dictionary `kw'.  ‘apply()’ is the same in
2.0, but thanks to a patch from Greg Ewing, ‘f(*args, **kw)’ is a
shorter and clearer way to achieve the same effect.  This syntax is
symmetrical with the syntax for defining functions:

     def f(*args, **kw):
         # args is a tuple of positional args,
         # kw is a dictionary of keyword args
         ...

The ‘print’ statement can now have its output directed to a file-like
object by following the ‘print’ with ‘>> file’, similar to the
redirection operator in Unix shells.  Previously you’d either have to
use the ‘write()’ method of the file-like object, which lacks the
convenience and simplicity of ‘print’, or you could assign a new value
to ‘sys.stdout’ and then restore the old value.  For sending output to
standard error, it’s much easier to write this:

     print >> sys.stderr, "Warning: action field not supplied"

Modules can now be renamed on importing them, using the syntax ‘import
module as name’ or ‘from module import name as othername’.  The patch
was submitted by Thomas Wouters.

A new format style is available when using the ‘%’ operator; ’%r’ will
insert the *note repr(): 7d5. of its argument.  This was also added from
symmetry considerations, this time for symmetry with the existing ’%s’
format style, which inserts the *note str(): 339. of its argument.  For
example, ‘'%r %s' % ('abc', 'abc')’ returns a string containing ‘'abc'
abc’.

Previously there was no way to implement a class that overrode Python’s
built-in *note in: 7ac. operator and implemented a custom version.  ‘obj
in seq’ returns true if `obj' is present in the sequence `seq'; Python
computes this by simply trying every index of the sequence until either
`obj' is found or an *note IndexError: e7d. is encountered.  Moshe Zadka
contributed a patch which adds a *note __contains__(): d30. magic method
for providing a custom implementation for ‘in’.  Additionally, new
built-in objects written in C can define what ‘in’ means for them via a
new slot in the sequence protocol.

Earlier versions of Python used a recursive algorithm for deleting
objects.  Deeply nested data structures could cause the interpreter to
fill up the C stack and crash; Christian Tismer rewrote the deletion
logic to fix this problem.  On a related note, comparing recursive
objects recursed infinitely and crashed; Jeremy Hylton rewrote the code
to no longer crash, producing a useful result instead.  For example,
after this code:

     a = []
     b = []
     a.append(a)
     b.append(b)

The comparison ‘a==b’ returns true, because the two recursive data
structures are isomorphic.  See the thread "trashcan and PR#7" in the
April 2000 archives of the python-dev mailing list for the discussion
leading up to this implementation, and some useful relevant links.  Note
that comparisons can now also raise exceptions.  In earlier versions of
Python, a comparison operation such as ‘cmp(a,b)’ would always produce
an answer, even if a user-defined ‘__cmp__()’ method encountered an
error, since the resulting exception would simply be silently swallowed.

Work has been done on porting Python to 64-bit Windows on the Itanium
processor, mostly by Trent Mick of ActiveState.  (Confusingly,
‘sys.platform’ is still ‘'win32'’ on Win64 because it seems that for
ease of porting, MS Visual C++ treats code as 32 bit on Itanium.)
PythonWin also supports Windows CE; see the Python CE page at
‘http://pythonce.sourceforge.net/’ for more information.

Another new platform is Darwin/MacOS X; initial support for it is in
Python 2.0.  Dynamic loading works, if you specify "configure –with-dyld
–with-suffix=.x".  Consult the README in the Python source distribution
for more instructions.

An attempt has been made to alleviate one of Python’s warts, the
often-confusing *note NameError: d83. exception when code refers to a
local variable before the variable has been assigned a value.  For
example, the following code raises an exception on the ‘print’ statement
in both 1.5.2 and 2.0; in 1.5.2 a *note NameError: d83. exception is
raised, while 2.0 raises a new *note UnboundLocalError: e7e. exception.
*note UnboundLocalError: e7e. is a subclass of *note NameError: d83, so
any existing code that expects *note NameError: d83. to be raised should
still work.

     def f():
         print "i=",i
         i = i + 1
     f()

Two new exceptions, *note TabError: e7f. and *note IndentationError:
e80, have been introduced.  They’re both subclasses of *note
SyntaxError: 460, and are raised when Python code is found to be
improperly indented.


File: python.info,  Node: Changes to Built-in Functions,  Prev: Minor Language Changes,  Up: 其他核心变化

1.17.9.2 Changes to Built-in Functions
......................................

A new built-in, ‘zip(seq1, seq2, ...)’, has been added.  *note zip():
c3a. returns a list of tuples where each tuple contains the i-th element
from each of the argument sequences.  The difference between *note
zip(): c3a. and ‘map(None, seq1, seq2)’ is that *note map(): c35. pads
the sequences with ‘None’ if the sequences aren’t all of the same
length, while *note zip(): c3a. truncates the returned list to the
length of the shortest argument sequence.

The *note int(): 185. and ‘long()’ functions now accept an optional
"base" parameter when the first argument is a string.  ‘int('123', 10)’
returns 123, while ‘int('123', 16)’ returns 291.  ‘int(123, 16)’ raises
a *note TypeError: 193. exception with the message "can’t convert
non-string with explicit base".

A new variable holding more detailed version information has been added
to the *note sys: fe. module.  ‘sys.version_info’ is a tuple ‘(major,
minor, micro, level, serial)’ For example, in a hypothetical 2.0.1beta1,
‘sys.version_info’ would be ‘(2, 0, 1, 'beta', 1)’.  `level' is a string
such as ‘"alpha"’, ‘"beta"’, or ‘"final"’ for a final release.

Dictionaries have an odd new method, ‘setdefault(key, default)’, which
behaves similarly to the existing ‘get()’ method.  However, if the key
is missing, ‘setdefault()’ both returns the value of `default' as
‘get()’ would do, and also inserts it into the dictionary as the value
for `key'.  Thus, the following lines of code:

     if dict.has_key( key ): return dict[key]
     else:
         dict[key] = []
         return dict[key]

can be reduced to a single ‘return dict.setdefault(key, [])’ statement.

The interpreter sets a maximum recursion depth in order to catch runaway
recursion before filling the C stack and causing a core dump or GPF..
Previously this limit was fixed when you compiled Python, but in 2.0 the
maximum recursion depth can be read and modified using *note
sys.getrecursionlimit(): e82. and *note sys.setrecursionlimit(): e83.
The default value is 1000, and a rough maximum value for a given
platform can be found by running a new script,
‘Misc/find_recursionlimit.py’.


File: python.info,  Node: 移植 Python 2 0,  Next: 扩展/嵌入更改,  Prev: 其他核心变化,  Up: Python 2 0 有什么新变化

1.17.10 移植 Python 2.0
-----------------------

New Python releases try hard to be compatible with previous releases,
and the record has been pretty good.  However, some changes are
considered useful enough, usually because they fix initial design
decisions that turned out to be actively mistaken, that breaking
backward compatibility can’t always be avoided.  This section lists the
changes in Python 2.0 that may cause old Python code to break.

The change which will probably break the most code is tightening up the
arguments accepted by some methods.  Some methods would take multiple
arguments and treat them as a tuple, particularly various list methods
such as ‘append()’ and ‘insert()’.  In earlier versions of Python, if
‘L’ is a list, ‘L.append( 1,2 )’ appends the tuple ‘(1,2)’ to the list.
In Python 2.0 this causes a *note TypeError: 193. exception to be
raised, with the message: ’append requires exactly 1 argument; 2 given’.
The fix is to simply add an extra set of parentheses to pass both values
as a tuple: ‘L.append( (1,2) )’.

The earlier versions of these methods were more forgiving because they
used an old function in Python’s C interface to parse their arguments;
2.0 modernizes them to use ‘PyArg_ParseTuple()’, the current argument
parsing function, which provides more helpful error messages and treats
multi-argument calls as errors.  If you absolutely must use 2.0 but
can’t fix your code, you can edit ‘Objects/listobject.c’ and define the
preprocessor symbol ‘NO_STRICT_LIST_APPEND’ to preserve the old
behaviour; this isn’t recommended.

Some of the functions in the *note socket: f0. module are still
forgiving in this way.  For example, ‘socket.connect( ('hostname', 25)
)()’ is the correct form, passing a tuple representing an IP address,
but ‘socket.connect( 'hostname', 25 )()’ also works.
‘socket.connect_ex()’ and ‘socket.bind()’ are similarly easy-going.
2.0alpha1 tightened these functions up, but because the documentation
actually used the erroneous multiple argument form, many people wrote
code which would break with the stricter checking.  GvR backed out the
changes in the face of public reaction, so for the *note socket: f0.
module, the documentation was fixed and the multiple argument form is
simply marked as deprecated; it `will' be tightened up again in a future
Python version.

The ‘\x’ escape in string literals now takes exactly 2 hex digits.
Previously it would consume all the hex digits following the ’x’ and
take the lowest 8 bits of the result, so ‘\x123456’ was equivalent to
‘\x56’.

The *note AttributeError: 3a3. and *note NameError: d83. exceptions have
a more friendly error message, whose text will be something like ‘'Spam'
instance has no attribute 'eggs'’ or ‘name 'eggs' is not defined’.
Previously the error message was just the missing attribute name ‘eggs’,
and code written to take advantage of this fact will break in 2.0.

Some work has been done to make integers and long integers a bit more
interchangeable.  In 1.5.2, large-file support was added for Solaris, to
allow reading files larger than 2 GiB; this made the ‘tell()’ method of
file objects return a long integer instead of a regular integer.  Some
code would subtract two file offsets and attempt to use the result to
multiply a sequence or slice a string, but this raised a *note
TypeError: 193.  In 2.0, long integers can be used to multiply or slice
a sequence, and it’ll behave as you’d intuitively expect it to; ‘3L *
'abc'’ produces ’abcabcabc’, and ‘(0,1,2,3)[2L:4L]’ produces (2,3).
Long integers can also be used in various contexts where previously only
integers were accepted, such as in the ‘seek()’ method of file objects,
and in the formats supported by the ‘%’ operator (‘%d’, ‘%i’, ‘%x’,
etc.).  For example, ‘"%d" % 2L**64’ will produce the string
‘18446744073709551616’.

The subtlest long integer change of all is that the *note str(): 339. of
a long integer no longer has a trailing ’L’ character, though *note
repr(): 7d5. still includes it.  The ’L’ annoyed many people who wanted
to print long integers that looked just like regular integers, since
they had to go out of their way to chop off the character.  This is no
longer a problem in 2.0, but code which does ‘str(longval)[:-1]’ and
assumes the ’L’ is there, will now lose the final digit.

Taking the *note repr(): 7d5. of a float now uses a different formatting
precision than *note str(): 339.  *note repr(): 7d5. uses ‘%.17g’ format
string for C’s ‘sprintf()’, while *note str(): 339. uses ‘%.12g’ as
before.  The effect is that *note repr(): 7d5. may occasionally show
more decimal places than *note str(): 339, for certain numbers.  For
example, the number 8.1 can’t be represented exactly in binary, so
‘repr(8.1)’ is ‘'8.0999999999999996'’, while str(8.1) is ‘'8.1'’.

The ‘-X’ command-line option, which turned all standard exceptions into
strings instead of classes, has been removed; the standard exceptions
will now always be classes.  The ‘exceptions’ module containing the
standard exceptions was translated from Python to a built-in C module,
written by Barry Warsaw and Fredrik Lundh.


File: python.info,  Node: 扩展/嵌入更改,  Next: Distutils：使模块易于安装,  Prev: 移植 Python 2 0,  Up: Python 2 0 有什么新变化

1.17.11 扩展/嵌入更改
---------------------

Some of the changes are under the covers, and will only be apparent to
people writing C extension modules or embedding a Python interpreter in
a larger application.  If you aren’t dealing with Python’s C API, you
can safely skip this section.

The version number of the Python C API was incremented, so C extensions
compiled for 1.5.2 must be recompiled in order to work with 2.0.  On
Windows, it’s not possible for Python 2.0 to import a third party
extension built for Python 1.5.x due to how Windows DLLs work, so Python
will raise an exception and the import will fail.

Users of Jim Fulton’s ExtensionClass module will be pleased to find out
that hooks have been added so that ExtensionClasses are now supported by
*note isinstance(): 457. and *note issubclass(): 458.  This means you no
longer have to remember to write code such as ‘if type(obj) ==
myExtensionClass’, but can use the more natural ‘if isinstance(obj,
myExtensionClass)’.

The ‘Python/importdl.c’ file, which was a mass of #ifdefs to support
dynamic loading on many different platforms, was cleaned up and
reorganised by Greg Stein.  ‘importdl.c’ is now quite small, and
platform-specific code has been moved into a bunch of
‘Python/dynload_*.c’ files.  Another cleanup: there were also a number
of ‘my*.h’ files in the Include/ directory that held various portability
hacks; they’ve been merged into a single file, ‘Include/pyport.h’.

Vladimir Marangozov’s long-awaited malloc restructuring was completed,
to make it easy to have the Python interpreter use a custom allocator
instead of C’s standard ‘malloc()’.  For documentation, read the
comments in ‘Include/pymem.h’ and ‘Include/objimpl.h’.  For the lengthy
discussions during which the interface was hammered out, see the Web
archives of the ’patches’ and ’python-dev’ lists at python.org.

Recent versions of the GUSI development environment for MacOS support
POSIX threads.  Therefore, Python’s POSIX threading support now works on
the Macintosh.  Threading support using the user-space GNU ‘pth’ library
was also contributed.

Threading support on Windows was enhanced, too.  Windows supports thread
locks that use kernel objects only in case of contention; in the common
case when there’s no contention, they use simpler functions which are an
order of magnitude faster.  A threaded version of Python 1.5.2 on NT is
twice as slow as an unthreaded version; with the 2.0 changes, the
difference is only 10%.  These improvements were contributed by Yakov
Markovitch.

Python 2.0’s source now uses only ANSI C prototypes, so compiling Python
now requires an ANSI C compiler, and can no longer be done using a
compiler that only supports K&R C.

Previously the Python virtual machine used 16-bit numbers in its
bytecode, limiting the size of source files.  In particular, this
affected the maximum size of literal lists and dictionaries in Python
source; occasionally people who are generating Python code would run
into this limit.  A patch by Charles G. Waldman raises the limit from
‘2^16’ to ‘2^{32}’.

Three new convenience functions intended for adding constants to a
module’s dictionary at module initialization time were added:
‘PyModule_AddObject()’, ‘PyModule_AddIntConstant()’, and
‘PyModule_AddStringConstant()’.  Each of these functions takes a module
object, a null-terminated C string containing the name to be added, and
a third argument for the value to be assigned to the name.  This third
argument is, respectively, a Python object, a C long, or a C string.

A wrapper API was added for Unix-style signal handlers.  ‘PyOS_getsig()’
gets a signal handler and ‘PyOS_setsig()’ will set a new handler.


File: python.info,  Node: Distutils：使模块易于安装,  Next: XML 模块,  Prev: 扩展/嵌入更改,  Up: Python 2 0 有什么新变化

1.17.12 Distutils：使模块易于安装
---------------------------------

Before Python 2.0, installing modules was a tedious affair – there was
no way to figure out automatically where Python is installed, or what
compiler options to use for extension modules.  Software authors had to
go through an arduous ritual of editing Makefiles and configuration
files, which only really work on Unix and leave Windows and MacOS
unsupported.  Python users faced wildly differing installation
instructions which varied between different extension packages, which
made administering a Python installation something of a chore.

The SIG for distribution utilities, shepherded by Greg Ward, has created
the Distutils, a system to make package installation much easier.  They
form the *note distutils: 39. package, a new part of Python’s standard
library.  In the best case, installing a Python module from source will
require the same steps: first you simply mean unpack the tarball or zip
archive, and the run "‘python setup.py install’".  The platform will be
automatically detected, the compiler will be recognized, C extension
modules will be compiled, and the distribution installed into the proper
directory.  Optional command-line arguments provide more control over
the installation process, the distutils package offers many places to
override defaults – separating the build from the install, building or
installing in non-default directories, and more.

In order to use the Distutils, you need to write a ‘setup.py’ script.
For the simple case, when the software contains only .py files, a
minimal ‘setup.py’ can be just a few lines long:

     from distutils.core import setup
     setup (name = "foo", version = "1.0",
            py_modules = ["module1", "module2"])

The ‘setup.py’ file isn’t much more complicated if the software consists
of a few packages:

     from distutils.core import setup
     setup (name = "foo", version = "1.0",
            packages = ["package", "package.subpackage"])

A C extension can be the most complicated case; here’s an example taken
from the PyXML package:

     from distutils.core import setup, Extension

     expat_extension = Extension('xml.parsers.pyexpat',
          define_macros = [('XML_NS', None)],
          include_dirs = [ 'extensions/expat/xmltok',
                           'extensions/expat/xmlparse' ],
          sources = [ 'extensions/pyexpat.c',
                      'extensions/expat/xmltok/xmltok.c',
                      'extensions/expat/xmltok/xmlrole.c', ]
            )
     setup (name = "PyXML", version = "0.5.4",
            ext_modules =[ expat_extension ] )

The Distutils can also take care of creating source and binary
distributions.  The "sdist" command, run by "‘python setup.py sdist’’,
builds a source distribution such as ‘foo-1.0.tar.gz’.  Adding new
commands isn’t difficult, "bdist_rpm" and "bdist_wininst" commands have
already been contributed to create an RPM distribution and a Windows
installer for the software, respectively.  Commands to create other
distribution formats such as Debian packages and Solaris ‘.pkg’ files
are in various stages of development.

All this is documented in a new manual, `Distributing Python Modules',
that joins the basic set of Python documentation.


File: python.info,  Node: XML 模块,  Next: 模块更改,  Prev: Distutils：使模块易于安装,  Up: Python 2 0 有什么新变化

1.17.13 XML 模块
----------------

Python 1.5.2 included a simple XML parser in the form of the ‘xmllib’
module, contributed by Sjoerd Mullender.  Since 1.5.2’s release, two
different interfaces for processing XML have become common: SAX2
(version 2 of the Simple API for XML) provides an event-driven interface
with some similarities to ‘xmllib’, and the DOM (Document Object Model)
provides a tree-based interface, transforming an XML document into a
tree of nodes that can be traversed and modified.  Python 2.0 includes a
SAX2 interface and a stripped-down DOM interface as part of the *note
xml: 134. package.  Here we will give a brief overview of these new
interfaces; consult the Python documentation or the source code for
complete details.  The Python XML SIG is also working on improved
documentation.

* Menu:

* SAX2 Support::
* DOM Support::
* Relationship to PyXML::


File: python.info,  Node: SAX2 Support,  Next: DOM Support,  Up: XML 模块

1.17.13.1 SAX2 Support
......................

SAX defines an event-driven interface for parsing XML. To use SAX, you
must write a SAX handler class.  Handler classes inherit from various
classes provided by SAX, and override various methods that will then be
called by the XML parser.  For example, the ‘startElement()’ and
‘endElement()’ methods are called for every starting and end tag
encountered by the parser, the ‘characters()’ method is called for every
chunk of character data, and so forth.

The advantage of the event-driven approach is that the whole document
doesn’t have to be resident in memory at any one time, which matters if
you are processing really huge documents.  However, writing the SAX
handler class can get very complicated if you’re trying to modify the
document structure in some elaborate way.

For example, this little example program defines a handler that prints a
message for every starting and ending tag, and then parses the file
‘hamlet.xml’ using it:

     from xml import sax

     class SimpleHandler(sax.ContentHandler):
         def startElement(self, name, attrs):
             print 'Start of element:', name, attrs.keys()

         def endElement(self, name):
             print 'End of element:', name

     # Create a parser object
     parser = sax.make_parser()

     # Tell it what handler to use
     handler = SimpleHandler()
     parser.setContentHandler( handler )

     # Parse a file!
     parser.parse( 'hamlet.xml' )

For more information, consult the Python documentation, or the XML HOWTO
at ‘http://pyxml.sourceforge.net/topics/howto/xml-howto.html’.


File: python.info,  Node: DOM Support,  Next: Relationship to PyXML,  Prev: SAX2 Support,  Up: XML 模块

1.17.13.2 DOM Support
.....................

The Document Object Model is a tree-based representation for an XML
document.  A top-level ‘Document’ instance is the root of the tree, and
has a single child which is the top-level ‘Element’ instance.  This
‘Element’ has children nodes representing character data and any
sub-elements, which may have further children of their own, and so
forth.  Using the DOM you can traverse the resulting tree any way you
like, access element and attribute values, insert and delete nodes, and
convert the tree back into XML.

The DOM is useful for modifying XML documents, because you can create a
DOM tree, modify it by adding new nodes or rearranging subtrees, and
then produce a new XML document as output.  You can also construct a DOM
tree manually and convert it to XML, which can be a more flexible way of
producing XML output than simply writing ‘<tag1>’...‘</tag1>’ to a file.

The DOM implementation included with Python lives in the *note
xml.dom.minidom: 136. module.  It’s a lightweight implementation of the
Level 1 DOM with support for XML namespaces.  The ‘parse()’ and
‘parseString()’ convenience functions are provided for generating a DOM
tree:

     from xml.dom import minidom
     doc = minidom.parse('hamlet.xml')

‘doc’ is a ‘Document’ instance.  ‘Document’, like all the other DOM
classes such as ‘Element’ and ‘Text’, is a subclass of the ‘Node’ base
class.  All the nodes in a DOM tree therefore support certain common
methods, such as ‘toxml()’ which returns a string containing the XML
representation of the node and its children.  Each class also has
special methods of its own; for example, ‘Element’ and ‘Document’
instances have a method to find all child elements with a given tag
name.  Continuing from the previous 2-line example:

     perslist = doc.getElementsByTagName( 'PERSONA' )
     print perslist[0].toxml()
     print perslist[1].toxml()

For the `Hamlet' XML file, the above few lines output:

     <PERSONA>CLAUDIUS, king of Denmark. </PERSONA>
     <PERSONA>HAMLET, son to the late, and nephew to the present king.</PERSONA>

The root element of the document is available as ‘doc.documentElement’,
and its children can be easily modified by deleting, adding, or removing
nodes:

     root = doc.documentElement

     # Remove the first child
     root.removeChild( root.childNodes[0] )

     # Move the new first child to the end
     root.appendChild( root.childNodes[0] )

     # Insert the new first child (originally,
     # the third child) before the 20th child.
     root.insertBefore( root.childNodes[0], root.childNodes[20] )

Again, I will refer you to the Python documentation for a complete
listing of the different ‘Node’ classes and their various methods.


File: python.info,  Node: Relationship to PyXML,  Prev: DOM Support,  Up: XML 模块

1.17.13.3 Relationship to PyXML
...............................

The XML Special Interest Group has been working on XML-related Python
code for a while.  Its code distribution, called PyXML, is available
from the SIG’s Web pages at
‘https://www.python.org/community/sigs/current/xml-sig’.  The PyXML
distribution also used the package name ‘xml’.  If you’ve written
programs that used PyXML, you’re probably wondering about its
compatibility with the 2.0 *note xml: 134. package.

The answer is that Python 2.0’s *note xml: 134. package isn’t compatible
with PyXML, but can be made compatible by installing a recent version
PyXML. Many applications can get by with the XML support that is
included with Python 2.0, but more complicated applications will require
that the full PyXML package will be installed.  When installed, PyXML
versions 0.6.0 or greater will replace the *note xml: 134. package
shipped with Python, and will be a strict superset of the standard
package, adding a bunch of additional features.  Some of the additional
features in PyXML include:

   * 4DOM, a full DOM implementation from FourThought, Inc.

   * The xmlproc validating parser, written by Lars Marius Garshol.

   * The ‘sgmlop’ parser accelerator module, written by Fredrik Lundh.


File: python.info,  Node: 模块更改,  Next: 新增模块<7>,  Prev: XML 模块,  Up: Python 2 0 有什么新变化

1.17.14 模块更改
----------------

Lots of improvements and bugfixes were made to Python’s extensive
standard library; some of the affected modules include *note readline:
df, ‘ConfigParser’, *note cgi: 16, *note calendar: 15, *note posix: d2,
*note readline: df, ‘xmllib’, *note aifc: 5, ‘chunk, wave’, *note
random: dd, *note shelve: e8, and *note nntplib: c1.  Consult the CVS
logs for the exact patch-by-patch details.

Brian Gallew contributed OpenSSL support for the *note socket: f0.
module.  OpenSSL is an implementation of the Secure Socket Layer, which
encrypts the data being sent over a socket.  When compiling Python, you
can edit ‘Modules/Setup’ to include SSL support, which adds an
additional function to the *note socket: f0. module: ‘socket.ssl(socket,
keyfile, certfile)’, which takes a socket object and returns an SSL
socket.  The ‘httplib’ and *note urllib: 11e. modules were also changed
to support ‘https://’ URLs, though no one has implemented FTP or SMTP
over SSL.

The ‘httplib’ module has been rewritten by Greg Stein to support
HTTP/1.1.  Backward compatibility with the 1.5 version of ‘httplib’ is
provided, though using HTTP/1.1 features such as pipelining will require
rewriting code to use a different set of interfaces.

The ‘Tkinter’ module now supports Tcl/Tk version 8.1, 8.2, or 8.3, and
support for the older 7.x versions has been dropped.  The Tkinter module
now supports displaying Unicode strings in Tk widgets.  Also, Fredrik
Lundh contributed an optimization which makes operations like
‘create_line’ and ‘create_polygon’ much faster, especially when using
lots of coordinates.

The *note curses: 2c. module has been greatly extended, starting from
Oliver Andrich’s enhanced version, to provide many additional functions
from ncurses and SYSV curses, such as colour, alternative character set
support, pads, and mouse support.  This means the module is no longer
compatible with operating systems that only have BSD curses, but there
don’t seem to be any currently maintained OSes that fall into this
category.

As mentioned in the earlier discussion of 2.0’s Unicode support, the
underlying implementation of the regular expressions provided by the
*note re: de. module has been changed.  SRE, a new regular expression
engine written by Fredrik Lundh and partially funded by Hewlett Packard,
supports matching against both 8-bit strings and Unicode strings.


File: python.info,  Node: 新增模块<7>,  Next: IDLE 改进,  Prev: 模块更改,  Up: Python 2 0 有什么新变化

1.17.15 新增模块
----------------

A number of new modules were added.  We’ll simply list them with brief
descriptions; consult the 2.0 documentation for the details of a
particular module.

   * *note atexit: c.: For registering functions to be called before the
     Python interpreter exits.  Code that currently sets ‘sys.exitfunc’
     directly should be changed to use the *note atexit: c. module
     instead, importing *note atexit: c. and calling *note
     atexit.register(): e8d. with the function to be called on exit.
     (Contributed by Skip Montanaro.)

   * *note codecs: 1c, ‘encodings’, *note unicodedata: 11b.: Added as
     part of the new Unicode support.

   * *note filecmp: 7f.: Supersedes the old ‘cmp’, ‘cmpcache’ and
     ‘dircmp’ modules, which have now become deprecated.  (Contributed
     by Gordon MacMillan and Moshe Zadka.)

   * *note gettext: 89.: This module provides internationalization
     (I18N) and localization (L10N) support for Python programs by
     providing an interface to the GNU gettext message catalog library.
     (Integrated by Barry Warsaw, from separate contributions by Martin
     von Löwis, Peter Funk, and James Henstridge.)

   * ‘linuxaudiodev’: Support for the ‘/dev/audio’ device on Linux, a
     twin to the existing ‘sunaudiodev’ module.  (Contributed by Peter
     Bosch, with fixes by Jeremy Hylton.)

   * *note mmap: b4.: An interface to memory-mapped files on both
     Windows and Unix.  A file’s contents can be mapped directly into
     memory, at which point it behaves like a mutable string, so its
     contents can be read and modified.  They can even be passed to
     functions that expect ordinary strings, such as the *note re: de.
     module.  (Contributed by Sam Rushing, with some extensions by A.M.
     Kuchling.)

   * ‘pyexpat’: An interface to the Expat XML parser.  (Contributed by
     Paul Prescod.)

   * ‘robotparser’: Parse a ‘robots.txt’ file, which is used for writing
     Web spiders that politely avoid certain areas of a Web site.  The
     parser accepts the contents of a ‘robots.txt’ file, builds a set of
     rules from it, and can then answer questions about the fetchability
     of a given URL. (Contributed by Skip Montanaro.)

   * *note tabnanny: 101.: A module/script to check Python source code
     for ambiguous indentation.  (Contributed by Tim Peters.)

   * ‘UserString’: A base class useful for deriving objects that behave
     like strings.

   * *note webbrowser: 12a.: A module that provides a platform
     independent way to launch a web browser on a specific URL. For each
     platform, various browsers are tried in a specific order.  The user
     can alter which browser is launched by setting the `BROWSER'
     environment variable.  (Originally inspired by Eric S. Raymond’s
     patch to *note urllib: 11e. which added similar functionality, but
     the final module comes from code originally implemented by Fred
     Drake as ‘Tools/idle/BrowserControl.py’, and adapted for the
     standard library by Fred.)

   * ‘_winreg’: An interface to the Windows registry.  ‘_winreg’ is an
     adaptation of functions that have been part of PythonWin since
     1995, but has now been added to the core distribution, and enhanced
     to support Unicode.  ‘_winreg’ was written by Bill Tutt and Mark
     Hammond.

   * *note zipfile: 143.: A module for reading and writing ZIP-format
     archives.  These are archives produced by ‘PKZIP’ on DOS/Windows or
     ‘zip’ on Unix, not to be confused with ‘gzip’-format files (which
     are supported by the *note gzip: 8c. module) (Contributed by James
     C. Ahlstrom.)

   * ‘imputil’: A module that provides a simpler way for writing
     customized import hooks, in comparison to the existing ‘ihooks’
     module.  (Implemented by Greg Stein, with much discussion on
     python-dev along the way.)


File: python.info,  Node: IDLE 改进,  Next: 删除和弃用的模块,  Prev: 新增模块<7>,  Up: Python 2 0 有什么新变化

1.17.16 IDLE 改进
-----------------

IDLE is the official Python cross-platform IDE, written using Tkinter.
Python 2.0 includes IDLE 0.6, which adds a number of new features and
improvements.  A partial list:

   * UI improvements and optimizations, especially in the area of syntax
     highlighting and auto-indentation.

   * The class browser now shows more information, such as the top level
     functions in a module.

   * Tab width is now a user settable option.  When opening an existing
     Python file, IDLE automatically detects the indentation
     conventions, and adapts.

   * There is now support for calling browsers on various platforms,
     used to open the Python documentation in a browser.

   * IDLE now has a command line, which is largely similar to the
     vanilla Python interpreter.

   * Call tips were added in many places.

   * IDLE can now be installed as a package.

   * In the editor window, there is now a line/column bar at the bottom.

   * Three new keystroke commands: Check module (‘Alt-F5’), Import
     module (‘F5’) and Run script (‘Ctrl-F5’).


File: python.info,  Node: 删除和弃用的模块,  Next: 致谢<8>,  Prev: IDLE 改进,  Up: Python 2 0 有什么新变化

1.17.17 删除和弃用的模块
------------------------

A few modules have been dropped because they’re obsolete, or because
there are now better ways to do the same thing.  The ‘stdwin’ module is
gone; it was for a platform-independent windowing toolkit that’s no
longer developed.

A number of modules have been moved to the ‘lib-old’ subdirectory:
‘cmp’, ‘cmpcache’, ‘dircmp’, ‘dump’, ‘find’, ‘grep’, ‘packmail’, ‘poly’,
‘util’, ‘whatsound’, ‘zmod’.  If you have code which relies on a module
that’s been moved to ‘lib-old’, you can simply add that directory to
‘sys.path’ to get them back, but you’re encouraged to update any code
that uses these modules.


File: python.info,  Node: 致谢<8>,  Prev: 删除和弃用的模块,  Up: Python 2 0 有什么新变化

1.17.18 致谢
------------

作者感谢以下人士对本文的各种草稿提出建议： David Bolen, Mark Hammond,
Gregg Hauser, Jeremy Hylton, Fredrik Lundh, Detlef Lannert, Aahz Maruch,
Skip Montanaro, Vladimir Marangozov, Tobias Polzin, Guido van Rossum,
Neil Schemenauer, and Russ Schmidt.

这个“更新日志”是 Misc/NEWS.d(1) 目录下文件 构建(2) 的 HTML 版本，它包含
了对当前 Python 版本进行的 `所有' 重要的更改。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Misc/NEWS.d

   (2) https://pypi.org/project/blurb


File: python.info,  Node: 更新日志,  Prev: Python 2 0 有什么新变化,  Up: Python的新变化

1.18 更新日志
=============

* Menu:

* Python 3.8.12 final: Python 3 8 12 final.
* 最终版本Python 3.8.11: 最终版本Python 3 8 11.
* Python 3.8.10 final: Python 3 8 10 final.
* Python 3.8.9 final: Python 3 8 9 final.
* Python 3.8.8 final: Python 3 8 8 final.
* Python 3.8.8 rc1: Python 3 8 8 rc1.
* Python 3.8.7 final: Python 3 8 7 final.
* Python 3.8.7 release candidate 1: Python 3 8 7 release candidate 1.
* Python 3.8.6 final: Python 3 8 6 final.
* Python 3.8.6 release candidate 1: Python 3 8 6 release candidate 1.
* Python 3.8.5 final: Python 3 8 5 final.
* Python 3.8.4 final: Python 3 8 4 final.
* Python 3.8.4 release candidate 1: Python 3 8 4 release candidate 1.
* Python 3.8.3 final: Python 3 8 3 final.
* Python 3.8.3 release candidate 1: Python 3 8 3 release candidate 1.
* Python 3.8.2 正式版: Python 3 8 2 正式版.
* Python 3.8.2 rc2: Python 3 8 2 rc2.
* Python 3.8.2 rc1: Python 3 8 2 rc1.
* Python 3.8.1 正式版: Python 3 8 1 正式版.
* Python 3.8.1 rc1: Python 3 8 1 rc1.
* Python 3.8.0 正式版: Python 3 8 0 正式版.
* Python 3.8.0 rc1: Python 3 8 0 rc1.
* Python 3.8.0 beta 4: Python 3 8 0 beta 4.
* Python 3.8.0 beta 3: Python 3 8 0 beta 3.
* Python 3.8.0 beta 2: Python 3 8 0 beta 2.
* Python 3.8.0 beta 1: Python 3 8 0 beta 1.
* Python 3.8.0 alpha 4: Python 3 8 0 alpha 4.
* Python 3.8.0 alpha 3: Python 3 8 0 alpha 3.
* Python 3.8.0 alpha 2: Python 3 8 0 alpha 2.
* Python 3.8.0 alpha 1: Python 3 8 0 alpha 1.
* Python 3.7.0 正式版: Python 3 7 0 正式版.
* Python 3.7.0 rc1: Python 3 7 0 rc1.
* Python 3.7.0 beta 5: Python 3 7 0 beta 5.
* Python 3.7.0 beta 4: Python 3 7 0 beta 4.
* Python 3.7.0 beta 3: Python 3 7 0 beta 3.
* Python 3.7.0 beta 2: Python 3 7 0 beta 2.
* Python 3.7.0 beta 1: Python 3 7 0 beta 1.
* Python 3.7.0 alpha 4: Python 3 7 0 alpha 4.
* Python 3.7.0 alpha 3: Python 3 7 0 alpha 3.
* Python 3.7.0 alpha 2: Python 3 7 0 alpha 2.
* Python 3.7.0 alpha 1: Python 3 7 0 alpha 1.
* Python 3.6.6 正式版: Python 3 6 6 正式版.
* Python 3.6.6 rc1: Python 3 6 6 rc1.
* Python 3.6.5 正式版: Python 3 6 5 正式版.
* Python 3.6.5 rc1: Python 3 6 5 rc1.
* Python 3.6.4 正式版: Python 3 6 4 正式版.
* Python 3.6.4 rc1: Python 3 6 4 rc1.
* Python 3.6.3 正式版: Python 3 6 3 正式版.
* Python 3.6.3 rc1: Python 3 6 3 rc1.
* Python 3.6.2 正式版: Python 3 6 2 正式版.
* Python 3.6.2 rc2: Python 3 6 2 rc2.
* Python 3.6.2 rc1: Python 3 6 2 rc1.
* Python 3.6.1 正式版: Python 3 6 1 正式版.
* Python 3.6.1 rc1: Python 3 6 1 rc1.
* Python 3.6.0 正式版: Python 3 6 0 正式版.
* Python 3.6.0 rc2: Python 3 6 0 rc2.
* Python 3.6.0 rc1: Python 3 6 0 rc1.
* Python 3.6.0 beta 4: Python 3 6 0 beta 4.
* Python 3.6.0 beta 3: Python 3 6 0 beta 3.
* Python 3.6.0 beta 2: Python 3 6 0 beta 2.
* Python 3.6.0 beta 1: Python 3 6 0 beta 1.
* Python 3.6.0 alpha 4: Python 3 6 0 alpha 4.
* Python 3.6.0 alpha 3: Python 3 6 0 alpha 3.
* Python 3.6.0 alpha 2: Python 3 6 0 alpha 2.
* Python 3.6.0 alpha 1: Python 3 6 0 alpha 1.
* Python 3.5.5 正式版: Python 3 5 5 正式版.
* Python 3.5.5 rc1: Python 3 5 5 rc1.
* Python 3.5.4 正式版: Python 3 5 4 正式版.
* Python 3.5.4 rc1: Python 3 5 4 rc1.
* Python 3.5.3 正式版: Python 3 5 3 正式版.
* Python 3.5.3 rc1: Python 3 5 3 rc1.
* Python 3.5.2 正式版: Python 3 5 2 正式版.
* Python 3.5.2 rc1: Python 3 5 2 rc1.
* Python 3.5.1 正式版: Python 3 5 1 正式版.
* Python 3.5.1 rc1: Python 3 5 1 rc1.
* Python 3.5.0 正式版: Python 3 5 0 正式版.
* Python 3.5.0 rc4: Python 3 5 0 rc4.
* Python 3.5.0 rc3: Python 3 5 0 rc3.
* Python 3.5.0 rc2: Python 3 5 0 rc2.
* Python 3.5.0 rc1: Python 3 5 0 rc1.
* Python 3.5.0 beta 4: Python 3 5 0 beta 4.
* Python 3.5.0 beta 3: Python 3 5 0 beta 3.
* Python 3.5.0 beta 2: Python 3 5 0 beta 2.
* Python 3.5.0 beta 1: Python 3 5 0 beta 1.
* Python 3.5.0 alpha 4: Python 3 5 0 alpha 4.
* Python 3.5.0 alpha 3: Python 3 5 0 alpha 3.
* Python 3.5.0 alpha 2: Python 3 5 0 alpha 2.
* Python 3.5.0 alpha 1: Python 3 5 0 alpha 1.


File: python.info,  Node: Python 3 8 12 final,  Next: 最终版本Python 3 8 11,  Up: 更新日志

1.18.1 Python 3.8.12 final
--------------------------

`Release date: 2021-08-30'

* Menu:

* 安全::
* 核心与内置::
* 库::
* 文档: 文档<2>.
* Windows::
* macOS::


File: python.info,  Node: 安全,  Next: 核心与内置,  Up: Python 3 8 12 final

1.18.1.1 安全
.............

   - bpo-42278(1): Replaced usage of *note tempfile.mktemp(): e95. with
     *note TemporaryDirectory: bd0. to avoid a potential race condition.

   - bpo-44394(2): Update the vendored copy of libexpat to 2.4.1 (from
     2.2.8) to get the fix for the CVE-2013-0340 "Billion Laughs"
     vulnerability.  This copy is most used on Windows and macOS.

   - bpo-43124(3): Made the internal ‘putcmd’ function in *note smtplib:
     ee. sanitize input for presence of ‘\r’ and ‘\n’ characters to
     avoid (unlikely) command injection.

   - bpo-36384(4): *note ipaddress: a3. module no longer accepts any
     leading zeros in IPv4 address strings.  Leading zeros are ambiguous
     and interpreted as octal notation by some libraries.  For example
     the legacy function *note socket.inet_aton(): 2f8. treats leading
     zeros as octal notation.  glibc implementation of modern *note
     inet_pton(): 2f9. does not accept any leading zeros.  For a while
     the *note ipaddress: a3. module used to accept ambiguous leading
     zeros.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42278

   (2) https://bugs.python.org/issue44394

   (3) https://bugs.python.org/issue43124

   (4) https://bugs.python.org/issue36384


File: python.info,  Node: 核心与内置,  Next: 库,  Prev: 安全,  Up: Python 3 8 12 final

1.18.1.2 核心与内置
...................

   - bpo-44872(1): Use new trashcan macros (Py_TRASHCAN_BEGIN/END) in
     frameobject.c instead of the old ones (Py_TRASHCAN_SAFE_BEGIN/END).

   - bpo-33930(2): Fix segmentation fault with deep recursion when
     cleaning method objects.  Patch by Augusto Goulart and Pablo
     Galindo.

   - bpo-44856(3): Fix reference leaks in the error paths of
     ‘update_bases()’ and ‘__build_class__’.  Patch by Pablo Galindo.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44872

   (2) https://bugs.python.org/issue33930

   (3) https://bugs.python.org/issue44856


File: python.info,  Node: 库,  Next: 文档<2>,  Prev: 核心与内置,  Up: Python 3 8 12 final

1.18.1.3 库
...........

   - bpo-45001(1): Made email date parsing more robust against malformed
     input, namely a whitespace-only ‘Date:’ header.  Patch by Wouter
     Bolsterlee.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45001


File: python.info,  Node: 文档<2>,  Next: Windows,  Prev: 库,  Up: Python 3 8 12 final

1.18.1.4 文档
.............

   - bpo-30511(1): Clarify that *note shutil.make_archive(): 21c. is not
     thread-safe due to reliance on changing the current working
     directory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30511


File: python.info,  Node: Windows,  Next: macOS,  Prev: 文档<2>,  Up: Python 3 8 12 final

1.18.1.5 Windows
................

   - bpo-45007(1): Update to OpenSSL 1.1.1l in Windows build

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45007


File: python.info,  Node: macOS,  Prev: Windows,  Up: Python 3 8 12 final

1.18.1.6 macOS
..............

   - bpo-45007(1): Update macOS installer builds to use OpenSSL 1.1.1l.

   - bpo-44689(2): *note ctypes.util.find_library(): 613. now works
     correctly on macOS 11 Big Sur even if Python is built on an older
     version of macOS. Previously, when built on older macOS systems,
     ‘find_library’ was not able to find macOS system libraries when
     running on Big Sur due to changes in how system libraries are
     stored.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45007

   (2) https://bugs.python.org/issue44689


File: python.info,  Node: 最终版本Python 3 8 11,  Next: Python 3 8 10 final,  Prev: Python 3 8 12 final,  Up: 更新日志

1.18.2 最终版本Python 3.8.11
----------------------------

`发布日期: 2021-06-28'

* Menu:

* 安全: 安全<2>.
* 核心与内置: 核心与内置<2>.
* 库: 库<2>.


File: python.info,  Node: 安全<2>,  Next: 核心与内置<2>,  Up: 最终版本Python 3 8 11

1.18.2.1 安全
.............

   - bpo-44022(1): 现在 mod:*note http.client: 94. 当从服务器获得 ‘100
     Continue’ 状态响应后会避免无限读取潜在的 HTTP 标头。

   - bpo-43882(2): URL部分出现的换行或制表符可能会应许某些形式的攻击。

     Following the controlling specification for URLs defined by WHATWG
     *note urllib.parse(): 120. now removes ASCII newlines and tabs from
     URLs, preventing such attacks.

   - bpo-42800(3): Audit hooks are now fired for frame.f_code,
     traceback.tb_frame, and generator code/frame attribute access.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44022

   (2) https://bugs.python.org/issue43882

   (3) https://bugs.python.org/issue42800


File: python.info,  Node: 核心与内置<2>,  Next: 库<2>,  Prev: 安全<2>,  Up: 最终版本Python 3 8 11

1.18.2.2 核心与内置
...................

   - bpo-44070(1): No longer eagerly makes import filenames absolute,
     except for extension modules, which was introduced in 3.8.10.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44070


File: python.info,  Node: 库<2>,  Prev: 核心与内置<2>,  Up: 最终版本Python 3 8 11

1.18.2.3 库
...........

   - ‘bpo-44061 `__: 在用 :class:`pathlib.Path’ 对象列表为参数调用 *note
     pkgutil.iter_modules(): 615. 时，修复了先前版本的回归（regression）
     问题。


File: python.info,  Node: Python 3 8 10 final,  Next: Python 3 8 9 final,  Prev: 最终版本Python 3 8 11,  Up: 更新日志

1.18.3 Python 3.8.10 final
--------------------------

`发布日期: 2021-05-03'

* Menu:

* 安全: 安全<3>.
* 核心与内置: 核心与内置<3>.
* 库: 库<3>.
* 文档: 文档<3>.
* 测试::
* Windows: Windows<2>.
* macOS: macOS<2>.
* IDLE: IDLE<3>.
* C API::


File: python.info,  Node: 安全<3>,  Next: 核心与内置<3>,  Up: Python 3 8 10 final

1.18.3.1 安全
.............

   - bpo-43434(1): Creating a *note sqlite3.Connection: 3e0. object now
     also produces a ‘sqlite3.connect’ *note auditing event: ea1.
     Previously this event was only produced by *note sqlite3.connect():
     3e2. calls.  Patch by Erlend E. Aasland.

   - bpo-43472(2): Ensures interpreter-level audit hooks receive the
     ‘cpython.PyInterpreterState_New’ event when called through the
     ‘_xxsubinterpreters’ module.

   - bpo-43075(3)： 修复了 *note
     urllib.request.AbstractBasicAuthHandler: ea2. 中的正则表达式拒绝服
     务（ReDoS）漏洞。易受 ReDoS 攻击的正则表达式在最坏情况下具有二次复
     杂度，并且在验证一个精心制作的无效 RFCs 时它会导致拒绝服务。这个
     ReDoS 问题发生在客户端，需要远程攻击者控制 HTTP 服务器。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43434

   (2) https://bugs.python.org/issue43472

   (3) https://bugs.python.org/issue43075


File: python.info,  Node: 核心与内置<3>,  Next: 库<3>,  Prev: 安全<3>,  Up: Python 3 8 10 final

1.18.3.2 核心与内置
...................

   - bpo-43105(1): Importlib now resolves relative paths when creating
     module spec objects from file locations.

   - bpo-42924(2): Fix ‘bytearray’ repetition incorrectly copying data
     from the start of the buffer, even if the data is offset within the
     buffer (e.g.  after reassigning a slice at the start of the
     ‘bytearray’ to a shorter byte string).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43105

   (2) https://bugs.python.org/issue42924


File: python.info,  Node: 库<3>,  Next: 文档<3>,  Prev: 核心与内置<3>,  Up: Python 3 8 10 final

1.18.3.3 库
...........

   - bpo-43993(1): Update bundled pip to 21.1.1.

   - bpo-43937(2): Fixed the *note turtle: 117. module working with
     non-default root window.

   - bpo-43930(3): Update bundled pip to 21.1 and setuptools to 56.0.0

   - bpo-43920(4): OpenSSL 3.0.0: *note load_verify_locations(): 7f4.
     now returns a consistent error message when cadata contains no
     valid certificate.

   - bpo-43607(5): *note urllib: 11e. can now convert Windows paths with
     ‘\\?\’ prefixes into URL paths.

   - bpo-43284(6): platform.win32_ver derives the windows version from
     sys.getwindowsversion().platform_version which in turn derives the
     version from kernel32.dll (which can be of a different version than
     Windows itself).  Therefore change the platform.win32_ver to
     determine the version using the platform module’s _syscmd_ver
     private function to return an accurate version.

   - bpo-42248(7): [Enum] ensure exceptions raised in ‘_missing__’ are
     released

   - bpo-43799(8): OpenSSL 3.0.0: define ‘OPENSSL_API_COMPAT’ 1.1.1 to
     suppress deprecation warnings.  Python requires OpenSSL 1.1.1 APIs.

   - bpo-43794(9): Add *note ssl.OP_IGNORE_UNEXPECTED_EOF: ea5.
     constants (OpenSSL 3.0.0)

   - bpo-43789(10): OpenSSL 3.0.0: Don’t call the password callback
     function a second time when first call has signaled an error
     condition.

   - bpo-43788(11): The header files for *note ssl: f4. error codes are
     now OpenSSL version-specific.  Exceptions will now show correct
     reason and library codes.  The ‘make_ssl_data.py’ script has been
     rewritten to use OpenSSL’s text file with error codes.

   - bpo-43655(12): *note tkinter: 10d. dialog windows are now
     recognized as dialogs by window managers on macOS and X Window.

   - bpo-43534(13): *note turtle.textinput(): ea6. and *note
     turtle.numinput(): ea7. create now a transient window working on
     behalf of the canvas window.

   - bpo-43522(14): Fix problem with *note hostname_checks_common_name:
     3e6.  OpenSSL does not copy hostflags from `struct SSL_CTX' to
     `struct SSL'.

   - bpo-42967(15): Allow *note bytes: 33a. ‘separator’ argument in
     ‘urllib.parse.parse_qs’ and ‘urllib.parse.parse_qsl’ when parsing
     *note str: 339. query strings.  Previously, this raised a
     ‘TypeError’.

   - bpo-43176(16): Fixed processing of a dataclass that inherits from a
     frozen dataclass with no fields.  It is now correctly detected as
     an error.

   - bpo-34463(17): Fixed discrepancy between *note traceback: 114. and
     the interpreter in formatting of SyntaxError with lineno not set
     (*note traceback: 114. was changed to match interpreter).

   - bpo-41735(18): Fix thread locks in zlib module may go wrong in rare
     case.  Patch by Ma Lin.

   - bpo-26053(19): Fixed bug where the *note pdb: ca. interactive run
     command echoed the args from the shell command line, even if those
     have been overridden at the pdb prompt.

   - bpo-36470(20): Fix dataclasses with ‘InitVar’s and *note replace():
     ea8.  Patch by Claudiu Popa.

   - bpo-28577(21): The hosts method on 32-bit prefix length
     IPv4Networks and 128-bit prefix IPv6Networks now returns a list
     containing the single Address instead of an empty list.

   - bpo-32745(22): Fix a regression in the handling of ctypes’ *note
     ctypes.c_wchar_p: ea9. type: embedded null characters would cause a
     *note ValueError: 1fc. to be raised.  Patch by Zackery Spytz.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43993

   (2) https://bugs.python.org/issue43937

   (3) https://bugs.python.org/issue43930

   (4) https://bugs.python.org/issue43920

   (5) https://bugs.python.org/issue43607

   (6) https://bugs.python.org/issue43284

   (7) https://bugs.python.org/issue42248

   (8) https://bugs.python.org/issue43799

   (9) https://bugs.python.org/issue43794

   (10) https://bugs.python.org/issue43789

   (11) https://bugs.python.org/issue43788

   (12) https://bugs.python.org/issue43655

   (13) https://bugs.python.org/issue43534

   (14) https://bugs.python.org/issue43522

   (15) https://bugs.python.org/issue42967

   (16) https://bugs.python.org/issue43176

   (17) https://bugs.python.org/issue34463

   (18) https://bugs.python.org/issue41735

   (19) https://bugs.python.org/issue26053

   (20) https://bugs.python.org/issue36470

   (21) https://bugs.python.org/issue28577

   (22) https://bugs.python.org/issue32745


File: python.info,  Node: 文档<3>,  Next: 测试,  Prev: 库<3>,  Up: Python 3 8 10 final

1.18.3.4 文档
.............

   - bpo-43959(1): The documentation on the PyContextVar C-API was
     clarified.

   - bpo-43938(2): Update dataclasses documentation to express that
     FrozenInstanceError is derived from AttributeError.

   - bpo-43739(3): Fixing the example code in
     Doc/extending/extending.rst to declare and initialize the pmodule
     variable to be of the right type.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43959

   (2) https://bugs.python.org/issue43938

   (3) https://bugs.python.org/issue43739


File: python.info,  Node: 测试,  Next: Windows<2>,  Prev: 文档<3>,  Up: Python 3 8 10 final

1.18.3.5 测试
.............

   - bpo-43842(1): Fix a race condition in the SMTP test of
     test_logging.  Don’t close a file descriptor (socket) from a
     different thread while asyncore.loop() is polling the file
     descriptor.  Patch by Victor Stinner.

   - bpo-43811(2): Tests multiple OpenSSL versions on GitHub Actions.
     Use ccache to speed up testing.

   - bpo-43791(3): OpenSSL 3.0.0: Disable testing of legacy protocols
     TLS 1.0 and 1.1.  Tests are failing with
     TLSV1_ALERT_INTERNAL_ERROR.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43842

   (2) https://bugs.python.org/issue43811

   (3) https://bugs.python.org/issue43791


File: python.info,  Node: Windows<2>,  Next: macOS<2>,  Prev: 测试,  Up: Python 3 8 10 final

1.18.3.6 Windows
................

   - bpo-35306(1): Avoid raising errors from *note
     pathlib.Path.exists(): 203. when passed an invalid filename.

   - bpo-38822(2): Fixed *note os.stat(): 1f2. failing on inaccessible
     directories with a trailing slash, rather than falling back to the
     parent directory’s metadata.  This implicitly affected *note
     os.path.exists(): 1f7. and *note os.path.isdir(): 1f9.

   - bpo-26227(3): Fixed decoding of host names in *note
     socket.gethostbyaddr(): ead. and *note socket.gethostbyname_ex():
     eae.

   - bpo-43745(4): Actually updates Windows release to OpenSSL 1.1.1k.
     Earlier releases were mislabelled and actually included 1.1.1i
     again.

   - bpo-43492(5): Upgrade Windows installer to use SQLite 3.35.5.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35306

   (2) https://bugs.python.org/issue38822

   (3) https://bugs.python.org/issue26227

   (4) https://bugs.python.org/issue43745

   (5) https://bugs.python.org/issue43492


File: python.info,  Node: macOS<2>,  Next: IDLE<3>,  Prev: Windows<2>,  Up: Python 3 8 10 final

1.18.3.7 macOS
..............

   - bpo-44009(1): Provide "python3.x-intel64" executable to allow
     reliably forcing macOS universal2 framework builds to run under
     Rosetta 2 Intel-64 emulation on Apple Silicon Macs.  This can be
     useful for testing or when universal2 wheels are not yet available.

   - bpo-41100(2): As of 3.8.10, Python now supports building and
     running on macOS 11 (Big Sur) and on Apple Silicon Macs (based on
     the ‘ARM64’ architecture).  A new universal build variant,
     ‘universal2’, is also available to natively support both ‘ARM64’
     and ‘Intel 64’ in one set of executables.  This backport from
     Python 3.9 does not include support for "weaklinking"; to support a
     range of macOS versions, continue to target for and build on the
     oldest version in the range; for 3.8.x, the ‘universal2’ variant is
     only useful on macOS 11 or later.

   - bpo-43492(3): Update macOS installer to use SQLite 3.35.4.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44009

   (2) https://bugs.python.org/issue41100

   (3) https://bugs.python.org/issue43492


File: python.info,  Node: IDLE<3>,  Next: C API,  Prev: macOS<2>,  Up: Python 3 8 10 final

1.18.3.8 IDLE
.............

   - bpo-43655(1): IDLE dialog windows are now recognized as dialogs by
     window managers on macOS and X Window.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43655


File: python.info,  Node: C API,  Prev: IDLE<3>,  Up: Python 3 8 10 final

1.18.3.9 C API
..............

   - bpo-43962(1): _PyInterpreterState_IDIncref() now calls
     _PyInterpreterState_IDInitref() and always increments id_refcount.
     Previously, calling _xxsubinterpreters.get_current() could create
     an id_refcount inconsistency when a
     _xxsubinterpreters.InterpreterID object was deallocated.  Patch by
     Victor Stinner.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43962


File: python.info,  Node: Python 3 8 9 final,  Next: Python 3 8 8 final,  Prev: Python 3 8 10 final,  Up: 更新日志

1.18.4 Python 3.8.9 final
-------------------------

`Release date: 2021-04-02'

* Menu:

* 安全: 安全<4>.
* 核心与内置: 核心与内置<4>.
* 库: 库<4>.
* 文档: 文档<4>.
* 测试: 测试<2>.
* 构建::
* macOS: macOS<3>.
* IDLE: IDLE<4>.


File: python.info,  Node: 安全<4>,  Next: 核心与内置<4>,  Up: Python 3 8 9 final

1.18.4.1 安全
.............

   - bpo-42988(1): CVE-2021-3426: Remove the ‘getfile’ feature of the
     *note pydoc: da. module which could be abused to read arbitrary
     files on the disk (directory traversal vulnerability).  Moreover,
     even source code of Python modules can contain sensitive data like
     passwords.  Vulnerability reported by David Schwörer.

   - bpo-43285(2): *note ftplib: 84. no longer trusts the IP address
     value returned from the server in response to the PASV command by
     default.  This prevents a malicious FTP server from using the
     response to probe IPv4 address and port combinations on the client
     network.

     Code that requires the former vulnerable behavior may set a
     ‘trust_server_pasv_ipv4_address’ attribute on their *note
     ftplib.FTP: 2f1. instances to ‘True’ to re-enable it.

   - bpo-43439(3): Add audit hooks for *note gc.get_objects(): 1ce,
     *note gc.get_referrers(): eb4. and *note gc.get_referents(): eb5.
     Patch by Pablo Galindo.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42988

   (2) https://bugs.python.org/issue43285

   (3) https://bugs.python.org/issue43439


File: python.info,  Node: 核心与内置<4>,  Next: 库<4>,  Prev: 安全<4>,  Up: Python 3 8 9 final

1.18.4.2 核心与内置
...................

   - bpo-43660(1): Fix crash that happens when replacing ‘sys.stderr’
     with a callable that can remove the object while an exception is
     being printed.  Patch by Pablo Galindo.

   - bpo-35883(2): Python no longer fails at startup with a fatal error
     if a command line argument contains an invalid Unicode character.
     The *note Py_DecodeLocale(): 444. function now escapes byte
     sequences which would be decoded as Unicode characters outside the
     [U+0000; U+10ffff] range.

   - bpo-43406(3): Fix a possible race condition where
     ‘PyErr_CheckSignals’ tries to execute a non-Python signal handler.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43660

   (2) https://bugs.python.org/issue35883

   (3) https://bugs.python.org/issue43406


File: python.info,  Node: 库<4>,  Next: 文档<4>,  Prev: 核心与内置<4>,  Up: Python 3 8 9 final

1.18.4.3 库
...........

   - bpo-35930(1): Raising an exception raised in a "future" instance
     will create reference cycles.

   - bpo-43577(2): Fix deadlock when using *note ssl.SSLContext: 3ec.
     debug callback with *note ssl.SSLContext.sni_callback(): eb8.

   - bpo-43423(3): ‘subprocess.communicate()’ no longer raises an
     IndexError when there is an empty stdout or stderr IO buffer during
     a timeout on Windows.

   - bpo-27820(4): Fixed long-standing bug of smtplib.SMTP where doing
     AUTH LOGIN with initial_response_ok=False will fail.

     The cause is that SMTP.auth_login _always_ returns a password if
     provided with a challenge string, thus non-compliant with the
     standard for AUTH LOGIN.

     Also fixes bug with the test for smtpd.

   - bpo-43399(5): Fix ‘ElementTree.extend’ not working on iterators
     when using the Python implementation

   - bpo-43316(6): The ‘python -m gzip’ command line application now
     properly fails when detecting an unsupported extension.  It exits
     with a non-zero exit code and prints an error message to stderr.

   - bpo-43260(7): Fix TextIOWrapper can not flush internal buffer
     forever after very large text is written.

   - bpo-42782(8): Fail fast in *note shutil.move(): 25c. to avoid
     creating destination directories on failure.

   - bpo-37193(9): Fixed memory leak in ‘socketserver.ThreadingMixIn’
     introduced in Python 3.7.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35930

   (2) https://bugs.python.org/issue43577

   (3) https://bugs.python.org/issue43423

   (4) https://bugs.python.org/issue27820

   (5) https://bugs.python.org/issue43399

   (6) https://bugs.python.org/issue43316

   (7) https://bugs.python.org/issue43260

   (8) https://bugs.python.org/issue42782

   (9) https://bugs.python.org/issue37193


File: python.info,  Node: 文档<4>,  Next: 测试<2>,  Prev: 库<4>,  Up: Python 3 8 9 final

1.18.4.4 文档
.............

   - bpo-43199(1): Answer "Why is there no goto?"  in the Design and
     History FAQ.

   - bpo-43407(2): Clarified that a result from *note time.monotonic():
     778, *note time.perf_counter(): 2ab, *note time.process_time():
     2ac, or *note time.thread_time(): 401. can be compared with the
     result from any following call to the same function - not just the
     next immediate call.

   - bpo-27646(3): Clarify that ’yield from <expr>’ works with any
     iterable, not just iterators.

   - bpo-36346(4): Update some deprecated unicode APIs which are
     documented as "will be removed in 4.0" to "3.12".  See PEP 623(5)
     for detail.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43199

   (2) https://bugs.python.org/issue43407

   (3) https://bugs.python.org/issue27646

   (4) https://bugs.python.org/issue36346

   (5) https://www.python.org/dev/peps/pep-0623


File: python.info,  Node: 测试<2>,  Next: 构建,  Prev: 文档<4>,  Up: Python 3 8 9 final

1.18.4.5 测试
.............

   - bpo-37945(1): Fix test_getsetlocale_issue1813() of test_locale:
     skip the test if ‘setlocale()’ fails.  Patch by Victor Stinner.

   - bpo-41561(2): Add workaround for Ubuntu’s custom OpenSSL security
     level policy.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37945

   (2) https://bugs.python.org/issue41561


File: python.info,  Node: 构建,  Next: macOS<3>,  Prev: 测试<2>,  Up: Python 3 8 9 final

1.18.4.6 构建
.............

   - bpo-43631(1): Update macOS, Windows, and CI to OpenSSL 1.1.1k.

   - bpo-43617(2): Improve configure.ac: Check for presence of
     autoconf-archive package and remove our copies of M4 macros.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43631

   (2) https://bugs.python.org/issue43617


File: python.info,  Node: macOS<3>,  Next: IDLE<4>,  Prev: 构建,  Up: Python 3 8 9 final

1.18.4.7 macOS
..............

   - bpo-41837(1): Update macOS installer build to use OpenSSL 1.1.1j.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41837


File: python.info,  Node: IDLE<4>,  Prev: macOS<3>,  Up: Python 3 8 9 final

1.18.4.8 IDLE
.............

   - bpo-42225(1): Document that IDLE can fail on Unix either from
     misconfigured IP masquerage rules or failure displaying complex
     colored (non-ascii) characters.

   - bpo-43283(2): Document why printing to IDLE’s Shell is often slower
     than printing to a system terminal and that it can be made faster
     by pre-formatting a single string before printing.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42225

   (2) https://bugs.python.org/issue43283


File: python.info,  Node: Python 3 8 8 final,  Next: Python 3 8 8 rc1,  Prev: Python 3 8 9 final,  Up: 更新日志

1.18.5 Python 3.8.8 final
-------------------------

`发布日期: 2021-02-19'

在 3.8.8 版本中没有新的更改。


File: python.info,  Node: Python 3 8 8 rc1,  Next: Python 3 8 7 final,  Prev: Python 3 8 8 final,  Up: 更新日志

1.18.6 Python 3.8.8 rc1
-----------------------

`发布日期: 2021-02-16'

* Menu:

* 安全: 安全<5>.
* 核心与内置: 核心与内置<5>.
* 库: 库<5>.
* 文档: 文档<5>.
* 测试: 测试<3>.
* 构建: 构建<2>.
* Windows: Windows<3>.
* macOS: macOS<4>.
* IDLE: IDLE<5>.
* 工具/示例::
* C API: C API<2>.


File: python.info,  Node: 安全<5>,  Next: 核心与内置<5>,  Up: Python 3 8 8 rc1

1.18.6.1 安全
.............

   - bpo-42967(1): Fix web cache poisoning vulnerability by defaulting
     the query args separator to ‘&’, and allowing the user to choose a
     custom separator.

   - bpo-42938(2): 在计算 *note ctypes.c_double: ec1. 和 *note
     ctypes.c_longdouble: ec2. 值的表示形式时避免静态缓冲区。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42967

   (2) https://bugs.python.org/issue42938


File: python.info,  Node: 核心与内置<5>,  Next: 库<5>,  Prev: 安全<5>,  Up: Python 3 8 8 rc1

1.18.6.2 核心与内置
...................

   - bpo-42819(1): *note readline: df.: Explicitly disable bracketed
     paste in the interactive interpreter, even if it’s set in the
     inputrc, is enabled by default (eg GNU Readline 8.1), or a user
     calls ‘readline.read_init_file()’.  The Python REPL has not
     implemented bracketed paste support.  Also, bracketed mode writes
     the ‘"\x1b[?2004h"’ escape sequence into stdout which causes test
     failures in applications that don’t support it.  It can still be
     explicitly enabled by calling ‘readline.parse_and_bind("set
     enable-bracketed-paste on")’.  Patch by Dustin Rodrigues.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42819


File: python.info,  Node: 库<5>,  Next: 文档<5>,  Prev: 核心与内置<5>,  Up: Python 3 8 8 rc1

1.18.6.3 库
...........

   - bpo-43108(1): 修复 *note curses: 2c. 模块中的引用泄漏。由Pablo
     Galindo修正。

   - bpo-42780(2): Fix os.set_inheritable() for O_PATH file descriptors
     on Linux.

   - bpo-41748(3): Fix HTMLParser parsing rules for element attributes
     containing commas with spaces.  Patch by Karl Dubost.

   - bpo-42759(4): Fixed equality comparison of ‘tkinter.Variable’ and
     ‘tkinter.font.Font’.  Objects which belong to different Tcl
     interpreters are now always different, even if they have the same
     name.

   - bpo-23328(5): Allow / character in username, password fields on
     _PROXY envars.

   - bpo-42681(6): Fixed range checks for color and pair numbers in
     *note curses: 2c.

   - bpo-42531(7): *note importlib.resources.path(): ec5. now works for
     *note package: ec6.s missing the optional *note __file__: ec7.
     attribute (more specifically, packages whose *note __spec__:
     ec8.‘.’*note origin: ec9. *note is: eca. *note None: 158.).

   - bpo-42388(8): Fix subprocess.check_output(..., input=None) behavior
     when text=True to be consistent with that of the documentation and
     universal_newlines=True.

   - bpo-42384(9): Make pdb populate sys.path[0] exactly the same as
     regular python execution.

   - bpo-42383(10): pdb修复: 之前的 pdb 在指定路径时如果使用了相对路径，
     并且当前路径发生改变后重启调试目标会失败的问题。

   - bpo-42318(11): Fixed support of non-BMP characters in *note
     tkinter: 10d. on macOS.

   - bpo-42005(12): Fix CLI of *note cProfile: 28. and *note profile:
     d4. to catch *note BrokenPipeError: 9a5.

   - bpo-41604(13): Don’t decrement the reference count of the previous
     user_ptr when set_panel_userptr fails.

   - bpo-26407(14): Unexpected errors in calling the ‘__iter__’ method
     are no longer masked by ‘TypeError’ in *note csv.reader(): ecb,
     ‘csv.writer.writerow()’ and ‘csv.writer.writerows()’.

   - bpo-39068(15): Fix initialization race condition in ‘a85encode()’
     and ‘b85encode()’ in *note base64: e.  Patch by Brandon Stansbury.

   - bpo-36589(16): The *note curses.update_lines_cols(): 6cf. function
     now returns ‘None’ instead of ‘1’ on success.

   - bpo-33289(17): Correct call to ‘tkinter.colorchooser’ to return RGB
     triplet of ints instead of floats.  Patch by Cheryl Sabella.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43108

   (2) https://bugs.python.org/issue42780

   (3) https://bugs.python.org/issue41748

   (4) https://bugs.python.org/issue42759

   (5) https://bugs.python.org/issue23328

   (6) https://bugs.python.org/issue42681

   (7) https://bugs.python.org/issue42531

   (8) https://bugs.python.org/issue42388

   (9) https://bugs.python.org/issue42384

   (10) https://bugs.python.org/issue42383

   (11) https://bugs.python.org/issue42318

   (12) https://bugs.python.org/issue42005

   (13) https://bugs.python.org/issue41604

   (14) https://bugs.python.org/issue26407

   (15) https://bugs.python.org/issue39068

   (16) https://bugs.python.org/issue36589

   (17) https://bugs.python.org/issue33289


File: python.info,  Node: 文档<5>,  Next: 测试<3>,  Prev: 库<5>,  Up: Python 3 8 8 rc1

1.18.6.4 文档
.............

   - bpo-40304(1): Fix doc for type(name, bases, dict).  Patch by Boris
     Verkhovskiy and Éric Araujo.

   - bpo-42811(2): Updated importlib.utils.resolve_name() doc to use
     __spec__.parent instead of __package__.  (Thanks Yair Frid.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40304

   (2) https://bugs.python.org/issue42811


File: python.info,  Node: 测试<3>,  Next: 构建<2>,  Prev: 文档<5>,  Up: Python 3 8 8 rc1

1.18.6.5 测试
.............

   - bpo-42794(1): Update test_nntplib to use offical group name of
     news.aioe.org for testing.  Patch by Dong-hee Na.

   - bpo-40810(2): In *note sqlite3: f3, fix ‘CheckTraceCallbackContent’
     for SQLite pre 3.7.15.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42794

   (2) https://bugs.python.org/issue40810


File: python.info,  Node: 构建<2>,  Next: Windows<3>,  Prev: 测试<3>,  Up: Python 3 8 8 rc1

1.18.6.6 构建
.............

   - bpo-29076(1): Add fish shell support to macOS installer.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29076


File: python.info,  Node: Windows<3>,  Next: macOS<4>,  Prev: 构建<2>,  Up: Python 3 8 8 rc1

1.18.6.7 Windows
................

   - bpo-41837(1): Updated Windows installer to include OpenSSL 1.1.1i

   - bpo-42584(2): Upgrade Windows installer to use SQLite 3.34.0.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41837

   (2) https://bugs.python.org/issue42584


File: python.info,  Node: macOS<4>,  Next: IDLE<5>,  Prev: Windows<3>,  Up: Python 3 8 8 rc1

1.18.6.8 macOS
..............

   - bpo-41837(1): Update macOS installer build to use OpenSSL 1.1.1i.

   - bpo-42584(2): Update macOS installer to use SQLite 3.34.0.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41837

   (2) https://bugs.python.org/issue42584


File: python.info,  Node: IDLE<5>,  Next: 工具/示例,  Prev: macOS<4>,  Up: Python 3 8 8 rc1

1.18.6.9 IDLE
.............

   - bpo-43008(1): Make IDLE invoke *note sys.excepthook(): e6b. in
     normal, 2-process mode.  Patch by Ken Hilton.

   - bpo-33065(2): Fix problem debugging user classes with __repr__
     method.

   - bpo-42508(3): Keep IDLE running on macOS. Remove obsolete
     workaround that prevented running files with shortcuts when using
     new universal2 installers built on macOS 11.

   - bpo-23544(4): Disable Debug=>Stack Viewer when user code is running
     or Debugger is active, to prevent hang or crash.  Patch by Zackery
     Spytz.

   - bpo-32631(5): Finish zzdummy example extension module: make menu
     entries work; add docstrings and tests with 100% coverage.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43008

   (2) https://bugs.python.org/issue33065

   (3) https://bugs.python.org/issue42508

   (4) https://bugs.python.org/issue23544

   (5) https://bugs.python.org/issue32631


File: python.info,  Node: 工具/示例,  Next: C API<2>,  Prev: IDLE<5>,  Up: Python 3 8 8 rc1

1.18.6.10 工具/示例
...................

   - bpo-42726(1): Fixed Python 3 compatibility issue with
     gdb/libpython.py handling of attribute dictionaries.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42726


File: python.info,  Node: C API<2>,  Prev: 工具/示例,  Up: Python 3 8 8 rc1

1.18.6.11 C API
...............

   - bpo-43030(1): Fixed a compiler warning in *note
     Py_UNICODE_ISSPACE(): ed4. on platforms with signed ‘wchar_t’.

   - bpo-40052(2): Fix an alignment build warning/error in function
     ‘PyVectorcall_Function()’.  Patch by Andreas Schneider, Antoine
     Pitrou and Petr Viktorin.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43030

   (2) https://bugs.python.org/issue40052


File: python.info,  Node: Python 3 8 7 final,  Next: Python 3 8 7 release candidate 1,  Prev: Python 3 8 8 rc1,  Up: 更新日志

1.18.7 Python 3.8.7 final
-------------------------

`Release date: 2020-12-21'

* Menu:

* 核心与内置: 核心与内置<6>.
* 库: 库<6>.
* 文档: 文档<6>.
* 构建: 构建<3>.
* 工具/示例: 工具/示例<2>.


File: python.info,  Node: 核心与内置<6>,  Next: 库<6>,  Up: Python 3 8 7 final

1.18.7.1 核心与内置
...................

   - bpo-32381(1): 修复了在 Windows 上运行 ‘.pyc’ 文件时的编码格式名称，
     现在 *note PyRun_SimpleFileExFlags(): ed7. 会使用正确的编码格式来编
     码文件名。

   - bpo-42536(2): g一些内置和标准库类型现在会确保其内部结果元组总是会被
     *note 垃圾回收器: ed8. 所追踪:

        - *note collections.OrderedDict.items(): 1ba.

        - *note dict.items(): c33.

        - *note enumerate(): deb.

        - *note functools.reduce(): c77.

        - *note itertools.combinations(): cae.

        - *note itertools.combinations_with_replacement(): c21.

        - *note itertools.permutations(): ed9.

        - *note itertools.product(): caf.

        - *note itertools.zip_longest(): c39.

        - *note zip(): c3a.

     之前，它们可能会被前一次垃圾回收取消追踪。 由 Brandt Bucher 提供补
     丁。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32381

   (2) https://bugs.python.org/issue42536


File: python.info,  Node: 库<6>,  Next: 文档<6>,  Prev: 核心与内置<6>,  Up: Python 3 8 7 final

1.18.7.2 库
...........

   - bpo-42630(1): *note tkinter: 10d. functions and constructors which
     need a default root window raise now *note RuntimeError: 2bb. with
     descriptive message instead of obscure *note AttributeError: 3a3.
     or *note NameError: d83. if it is not created yet or cannot be
     created automatically.

   - bpo-42644(2): *note logging.disable: edb. will now validate the
     types and value of its parameter.  It also now accepts strings
     representing the levels (as does ‘loging.setLevel’) instead of only
     the numerical values.

   - bpo-36541(3): Fixed lib2to3.pgen2 to be able to parse PEP-570
     positional only argument syntax.

   - bpo-42375(4): subprocess module update for DragonFlyBSD support.

   - bpo-39825(5): Windows: Change
     ‘sysconfig.get_config_var('EXT_SUFFIX')’ to the expected full
     ‘platform_tag.extension’ format.  Previously it was hard-coded to
     ‘.pyd’, now it is compatible with ‘distutils.sysconfig’ and will
     result in something like ‘.cp38-win_amd64.pyd’.  This brings
     windows into conformance with the other platforms.

   - bpo-39101(6): Fixed tests using IsolatedAsyncioTestCase from
     hanging on BaseExceptions.

   - bpo-41907(7): fix *note format(): 4e3. behavior for ‘IntFlag’

   - bpo-41889(8): Enum: fix regression involving inheriting a
     multiply-inherited enum

   - bpo-41891(9): Ensure asyncio.wait_for waits for task completion

   - bpo-40219(10): Lowered ‘tkinter.ttk.LabeledScale’ dummy widget to
     prevent hiding part of the content label.

   - bpo-40084(11): Fix ‘Enum.__dir__’: dir(Enum.member) now includes
     attributes as well as methods.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42630

   (2) https://bugs.python.org/issue42644

   (3) https://bugs.python.org/issue36541

   (4) https://bugs.python.org/issue42375

   (5) https://bugs.python.org/issue39825

   (6) https://bugs.python.org/issue39101

   (7) https://bugs.python.org/issue41907

   (8) https://bugs.python.org/issue41889

   (9) https://bugs.python.org/issue41891

   (10) https://bugs.python.org/issue40219

   (11) https://bugs.python.org/issue40084


File: python.info,  Node: 文档<6>,  Next: 构建<3>,  Prev: 库<6>,  Up: Python 3 8 7 final

1.18.7.3 文档
.............

   - bpo-17140(1): Add documentation for the *note
     multiprocessing.pool.ThreadPool: edd. class.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17140


File: python.info,  Node: 构建<3>,  Next: 工具/示例<2>,  Prev: 文档<6>,  Up: Python 3 8 7 final

1.18.7.4 构建
.............

   - bpo-42604(1): Now all platforms use a value for the "EXT_SUFFIX"
     build variable derived from SOABI (for instance in freeBSD,
     "EXT_SUFFIX" is now ".cpython-310d.so" instead of ".so").
     Previosuly only Linux, Mac and VxWorks were using a value for
     "EXT_SUFFIX" that included "SOABI".

   - bpo-42598(2): Fix implicit function declarations in configure which
     could have resulted in incorrect configuration checks.  Patch
     contributed by Joshua Root.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42604

   (2) https://bugs.python.org/issue42598


File: python.info,  Node: 工具/示例<2>,  Prev: 构建<3>,  Up: Python 3 8 7 final

1.18.7.5 工具/示例
..................

   - bpo-42613(1): Fix ‘freeze.py’ tool to use the prope config and
     library directories.  Patch by Victor Stinner.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42613


File: python.info,  Node: Python 3 8 7 release candidate 1,  Next: Python 3 8 6 final,  Prev: Python 3 8 7 final,  Up: 更新日志

1.18.8 Python 3.8.7 release candidate 1
---------------------------------------

`发布日期: 2020-12-07'

* Menu:

* 安全: 安全<6>.
* 核心与内置: 核心与内置<7>.
* 库: 库<7>.
* 文档: 文档<7>.
* 测试: 测试<4>.
* 构建: 构建<4>.
* Windows: Windows<4>.
* macOS: macOS<5>.
* IDLE: IDLE<6>.
* C API: C API<3>.


File: python.info,  Node: 安全<6>,  Next: 核心与内置<7>,  Up: Python 3 8 7 release candidate 1

1.18.8.1 安全
.............

   - bpo-42103(1): Prevented potential DoS attack via CPU and RAM
     exhaustion when processing malformed Apple Property List files in
     binary format.

   - bpo-42051(2)：模块 *note plistlib: d0. 不再接受 XML 属性列表文件中
     的实体声明（避免引发 XML 脆弱性）。此更改不应该影响用户使用，因为实
     体声明在常规属性列表文件中不被使用。

   - bpo-40791(3): Add ‘volatile’ to the accumulator variable in
     ‘hmac.compare_digest’, making constant-time-defeating optimizations
     less likely.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42103

   (2) https://bugs.python.org/issue42051

   (3) https://bugs.python.org/issue40791


File: python.info,  Node: 核心与内置<7>,  Next: 库<7>,  Prev: 安全<6>,  Up: Python 3 8 7 release candidate 1

1.18.8.2 核心与内置
...................

   - bpo-41686(1): On Windows, the ‘SIGINT’ event,
     ‘_PyOS_SigintEvent()’, is now created even if Python is configured
     to not install signal handlers (if *note
     PyConfig.install_signal_handlers: ee3. equals to 0, or
     ‘Py_InitializeEx(0)’).

   - bpo-42143(2): Fix handling of errors during creation of
     ‘PyFunctionObject’, which resulted in operations on uninitialized
     memory.  Patch by Yonatan Goldschmidt.

   - bpo-41984(3): 垃圾回收器现在会跟踪所有用户定义类。 由 Brandt Bucher
     修复。

   - bpo-41909(4): Fixed stack overflow in *note issubclass(): 458. and
     *note isinstance(): 457. when getting the ‘__bases__’ attribute
     leads to infinite recursion.

   - bpo-41894(5): When loading a native module and a load failure
     occurs, prevent a possible UnicodeDecodeError when not running in a
     UTF-8 locale by decoding the load error message using the current
     locale’s encoding.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41686

   (2) https://bugs.python.org/issue42143

   (3) https://bugs.python.org/issue41984

   (4) https://bugs.python.org/issue41909

   (5) https://bugs.python.org/issue41894


File: python.info,  Node: 库<7>,  Next: 文档<7>,  Prev: 核心与内置<7>,  Up: Python 3 8 7 release candidate 1

1.18.8.3 库
...........

   - bpo-17735(1): ‘inspect.findsource()’ now raises *note OSError: 1d4.
     instead of *note IndexError: e7d. when ‘co_lineno’ of a code object
     is greater than the file length.  This can happen, for example,
     when a file is edited after it was imported.  PR by Irit Katriel.

   - bpo-42116(2): Fix handling of trailing comments by *note
     inspect.getsource(): ee5.

   - bpo-42482(3): *note TracebackException: 77f. no longer holds a
     reference to the exception’s traceback object.  Consequently,
     instances of TracebackException for equivalent but non-equal
     exceptions now compare as equal.

   - bpo-42406(4): We fixed an issue in ‘pickle.whichmodule’ in which
     importing *note multiprocessing: b8. could change the how pickle
     identifies which module an object belongs to, potentially breaking
     the unpickling of those objects.

   - bpo-42328(5): Fixed *note tkinter.ttk.Style.map(): ee6.  The
     function accepts now the representation of the default state as
     empty sequence (as returned by ‘Style.map()’).  The structure of
     the result is now the same on all platform and does not depend on
     the value of ‘wantobjects’.

   - bpo-42014(6): The ‘onerror’ callback from ‘shutil.rmtree’ now
     receives correct function when ‘os.open’ fails.

   - bpo-42237(7): Fix *note os.sendfile(): 362. on illumos.

   - bpo-42249(8): Fixed writing binary Plist files larger than 4 GiB.

   - bpo-35455(9): On Solaris, *note thread_time(): 401. is now
     implemented with ‘gethrvtime()’ because
     ‘clock_gettime(CLOCK_THREAD_CPUTIME_ID)’ is not always available.
     Patch by Jakub Kulik.

   - bpo-41754(10): webbrowser: Ignore `NotADirectoryError' when calling
     ‘xdg-settings’.

   - bpo-29566(11): ‘binhex.binhex()’ consisently writes macOS 9 line
     endings.

   - bpo-42183(12): Fix a stack overflow error for asyncio Task or
     Future repr().

     在 Task 或 Future 递归返回自身的情形下会导致栈溢出。

   - bpo-42103(13): ‘InvalidFileException’ and *note RecursionError:
     63d. are now the only errors caused by loading malformed binary
     Plist file (previously ValueError and TypeError could be raised in
     some specific cases).

   - bpo-41491(14): plistlib: fix parsing XML plists with hexadecimal
     integer values

   - bpo-32498(15): Clearer exception message when passing an argument
     of type bytes to *note urllib.parse.unquote(): ee7.  This is only
     for 3.8; in 3.9 and later this function accepts bytes inputs as
     well.  PR by Irit Katriel.

   - bpo-42065(16): Fix an incorrectly formatted error from
     ‘_codecs.charmap_decode()’ when called with a mapped value outside
     the range of valid Unicode code points.  PR by Max Bernstein.

   - bpo-41966(17): Fix pickling pure Python *note datetime.time: 4fb.
     subclasses.  Patch by Dean Inwood.

   - bpo-41976(18): Fixed a bug that was causing *note
     ctypes.util.find_library(): 613. to return ‘None’ when triying to
     locate a library in an environment when gcc>=9 is available and
     ‘ldconfig’ is not.  Patch by Pablo Galindo

   - bpo-41900(19): C14N 2.0 serialisation in xml.etree.ElementTree
     failed for unprefixed attributes when a default namespace was
     defined.

   - bpo-41855(20): In ‘importlib.metadata’, fix issue where multiple
     children can be returned from ‘FastPath.zip_children()’.  Backport
     of python-devs/importlib_metadata#117(21).

   - bpo-41840(22): Fix a bug in the *note symtable: fd. module that was
     causing module-scope global variables to not be reported as both
     local and global.  Patch by Pablo Galindo.

   - bpo-41831(23): ‘str()’ for the ‘type’ attribute of the
     ‘tkinter.Event’ object always returns now the numeric code returned
     by Tk instead of the name of the event type.

   - bpo-41662(24): No longer override exceptions raised in ‘__len__()’
     of a sequence of parameters in *note sqlite3: f3. with *note
     ProgrammingError: ee8.

   - bpo-41662(25): Fixed crash when mutate list of parameters during
     iteration in *note sqlite3: f3.

   - bpo-34215(26): Clarify the error message for *note
     asyncio.IncompleteReadError: ee9. when ‘expected’ is ‘None’.

   - bpo-41316(27): Fix the *note tarfile: 102. module to write only
     basename of TAR file to GZIP compression header.

   - bpo-12800(28): Extracting a symlink from a tarball should succeed
     and overwrite the symlink if it already exists.  The fix is to
     remove the existing file or symlink before extraction.  Based on
     patch by Chris AtLee, Jeffrey Kintscher, and Senthil Kumaran.

   - bpo-16936(29): Allow ‘ctypes.wintypes’ to be imported on
     non-Windows systems.

   - bpo-40592(30): *note shutil.which(): eea. now ignores empty entries
     in ‘PATHEXT’ instead of treating them as a match.

   - bpo-40492(31): Fix ‘--outfile’ for *note cProfile: 28. / *note
     profile: d4. not writing the output file in the original directory
     when the program being profiled changes the working directory.  PR
     by Anthony Sottile.

   - bpo-40105(32): ZipFile truncates files to avoid corruption when a
     shorter comment is provided in append ("a") mode.  Patch by Jan
     Mazur.

   - bpo-27321(33): Fixed KeyError exception when flattening an email to
     a string attempts to replace a non-existent
     Content-Transfer-Encoding header.

   - bpo-32793(34): Fix a duplicated debug message when *note
     smtplib.SMTP.connect(): eeb. is called.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17735

   (2) https://bugs.python.org/issue42116

   (3) https://bugs.python.org/issue42482

   (4) https://bugs.python.org/issue42406

   (5) https://bugs.python.org/issue42328

   (6) https://bugs.python.org/issue42014

   (7) https://bugs.python.org/issue42237

   (8) https://bugs.python.org/issue42249

   (9) https://bugs.python.org/issue35455

   (10) https://bugs.python.org/issue41754

   (11) https://bugs.python.org/issue29566

   (12) https://bugs.python.org/issue42183

   (13) https://bugs.python.org/issue42103

   (14) https://bugs.python.org/issue41491

   (15) https://bugs.python.org/issue32498

   (16) https://bugs.python.org/issue42065

   (17) https://bugs.python.org/issue41966

   (18) https://bugs.python.org/issue41976

   (19) https://bugs.python.org/issue41900

   (20) https://bugs.python.org/issue41855

   (21) https://gitlab.com/python-devs/importlib_metadata/-/issues/117

   (22) https://bugs.python.org/issue41840

   (23) https://bugs.python.org/issue41831

   (24) https://bugs.python.org/issue41662

   (25) https://bugs.python.org/issue41662

   (26) https://bugs.python.org/issue34215

   (27) https://bugs.python.org/issue41316

   (28) https://bugs.python.org/issue12800

   (29) https://bugs.python.org/issue16936

   (30) https://bugs.python.org/issue40592

   (31) https://bugs.python.org/issue40492

   (32) https://bugs.python.org/issue40105

   (33) https://bugs.python.org/issue27321

   (34) https://bugs.python.org/issue32793


File: python.info,  Node: 文档<7>,  Next: 测试<4>,  Prev: 库<7>,  Up: Python 3 8 7 release candidate 1

1.18.8.4 文档
.............

   - bpo-42153(1): Fix the URL for the IMAP protocol documents.

   - bpo-41910(2): 记录 *note object.__eq__: 348. 的默认实现。

   - bpo-41774(3): In Programming FAQ "Sequences (Tuples/Lists)"
     section, add "How do you remove multiple items from a list".

   - bpo-39416(4): Document some restrictions on the default string
     representations of numeric classes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42153

   (2) https://bugs.python.org/issue41910

   (3) https://bugs.python.org/issue41774

   (4) https://bugs.python.org/issue39416


File: python.info,  Node: 测试<4>,  Next: 构建<4>,  Prev: 文档<7>,  Up: Python 3 8 7 release candidate 1

1.18.8.5 测试
.............

   - bpo-41473(1): Reenable test_gdb on gdb 9.2 and newer:
     ‘https://bugzilla.redhat.com/show_bug.cgi?id=1866884’ bug is fixed
     in gdb 10.1.

   - bpo-42553(2): Fix ‘test_asyncio.test_call_later()’ race condition:
     don’t measure asyncio performance in the ‘call_later()’ unit test.
     The test failed randomly on the CI.

   - bpo-40754(3): Include ‘_testinternalcapi’ module in Windows
     installer for test suite

   - bpo-41739(4): Fix
     test_logging.test_race_between_set_target_and_flush(): the test now
     waits until all threads complete to avoid leaking running threads.

   - bpo-41944(5): Tests for CJK codecs no longer call ‘eval()’ on
     content received via HTTP.

   - bpo-41939(6): Fix test_site.test_license_exists_at_url(): call
     ‘urllib.request.urlcleanup()’ to reset the global
     ‘urllib.request._opener’.  Patch by Victor Stinner.

   - bpo-41561(7): test_ssl: skip test_min_max_version_mismatch when TLS
     1.0 is not available

   - bpo-41602(8): Add tests for SIGINT handling in the runpy module.

   - bpo-41306(9): Fixed a failure in ‘test_tk.test_widgets.ScaleTest’
     happening when executing the test with Tk 8.6.10.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41473

   (2) https://bugs.python.org/issue42553

   (3) https://bugs.python.org/issue40754

   (4) https://bugs.python.org/issue41739

   (5) https://bugs.python.org/issue41944

   (6) https://bugs.python.org/issue41939

   (7) https://bugs.python.org/issue41561

   (8) https://bugs.python.org/issue41602

   (9) https://bugs.python.org/issue41306


File: python.info,  Node: 构建<4>,  Next: Windows<4>,  Prev: 测试<4>,  Up: Python 3 8 7 release candidate 1

1.18.8.6 构建
.............

   - bpo-42398(1): Fix a race condition in "make regen-all" when make
     -jN option is used to run jobs in parallel.  The clinic.py script
     now only use atomic write to write files.  Moveover, generated
     files are now left unchanged if the content does not change, to not
     change the file modification time.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42398


File: python.info,  Node: Windows<4>,  Next: macOS<5>,  Prev: 构建<4>,  Up: Python 3 8 7 release candidate 1

1.18.8.7 Windows
................

   - bpo-42120(1): Remove macro definition of ‘copysign’ (to
     ‘_copysign’) in headers.

   - bpo-38439(2): Updates the icons for IDLE in the Windows Store
     package.

   - bpo-41557(3): Update Windows installer to use SQLite 3.33.0.

   - bpo-38324(4): Avoid Unicode errors when accessing certain locale
     data on Windows.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42120

   (2) https://bugs.python.org/issue38439

   (3) https://bugs.python.org/issue41557

   (4) https://bugs.python.org/issue38324


File: python.info,  Node: macOS<5>,  Next: IDLE<6>,  Prev: Windows<4>,  Up: Python 3 8 7 release candidate 1

1.18.8.8 macOS
..............

   - bpo-38443(1): The ‘--enable-universalsdk’ and
     ‘--with-universal-archs’ options for the configure script now check
     that the specified architectures can be used.

   - bpo-41471(2): Ignore invalid prefix lengths in system proxy
     excludes.

   - bpo-41557(3): Update macOS installer to use SQLite 3.33.0.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38443

   (2) https://bugs.python.org/issue41471

   (3) https://bugs.python.org/issue41557


File: python.info,  Node: IDLE<6>,  Next: C API<3>,  Prev: macOS<5>,  Up: Python 3 8 7 release candidate 1

1.18.8.9 IDLE
.............

   - bpo-42426(1): Fix reporting offset of the RE error in searchengine.

   - bpo-42415(2): Get docstrings for IDLE calltips more often by using
     inspect.getdoc.

   - bpo-33987(3): Mostly finish using ttk widgets, mainly for editor,
     settings, and searches.  Some patches by Mark Roseman.

   - bpo-41775(4): Use ’IDLE Shell’ as shell title

   - bpo-40511(5): Typing opening and closing parentheses inside the
     parentheses of a function call will no longer cause unnecessary
     "flashing" off and on of an existing open call-tip, e.g.  when
     typed in a string literal.

   - bpo-38439(6): Add a 256×256 pixel IDLE icon to the Windows .ico
     file.  Created by Andrew Clover.  Remove the low-color gif
     variations from the .ico file.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42426

   (2) https://bugs.python.org/issue42415

   (3) https://bugs.python.org/issue33987

   (4) https://bugs.python.org/issue41775

   (5) https://bugs.python.org/issue40511

   (6) https://bugs.python.org/issue38439


File: python.info,  Node: C API<3>,  Prev: IDLE<6>,  Up: Python 3 8 7 release candidate 1

1.18.8.10 C API
...............

   - bpo-41986(1): ‘Py_FileSystemDefaultEncodeErrors’ and ‘Py_UTF8Mode’
     are available again in limited API.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41986


File: python.info,  Node: Python 3 8 6 final,  Next: Python 3 8 6 release candidate 1,  Prev: Python 3 8 7 release candidate 1,  Up: 更新日志

1.18.9 Python 3.8.6 final
-------------------------

`Release date: 2020-09-23'

* Menu:

* 核心与内置: 核心与内置<8>.
* 库: 库<8>.
* 文档: 文档<8>.
* 测试: 测试<5>.
* Windows: Windows<5>.
* IDLE: IDLE<7>.


File: python.info,  Node: 核心与内置<8>,  Next: 库<8>,  Up: Python 3 8 6 final

1.18.9.1 核心与内置
...................

   - bpo-41525(1): The output of ‘python --help’ contains now only ASCII
     characters.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41525


File: python.info,  Node: 库<8>,  Next: 文档<8>,  Prev: 核心与内置<8>,  Up: Python 3 8 6 final

1.18.9.2 库
...........

   - bpo-41817(1): fix ‘tkinter.EventType’ Enum so all members are
     strings, and none are tuples

   - bpo-41815(2): Fix SQLite3 segfault when backing up closed database.
     Patch contributed by Peter David McCormick.

   - bpo-41517(3): fix bug allowing Enums to be extended via multiple
     inheritance

   - bpo-39587(4): use the correct mix-in data type when constructing
     Enums

   - bpo-41789(5): Honor *note object: 2b1. overrides in ‘Enum’ class
     creation (specifically, ‘__str__’, ‘__repr__’, ‘__format__’, and
     ‘__reduce_ex__’).

   - bpo-39651(6): Fix a race condition in the ‘call_soon_threadsafe()’
     method of ‘asyncio.ProactorEventLoop’: do nothing if the self-pipe
     socket has been closed.

   - bpo-41720(7): Fixed ‘turtle.Vec2D.__rmul__()’ for arguments which
     are not int or float.

   - bpo-39728(8): fix default ‘_missing_’ so a duplicate *note
     ValueError: 1fc. is not set as the ‘__context__’ of the original
     *note ValueError: 1fc.

   - bpo-37479(9): When ‘Enum.__str__’ is overridden in a derived class,
     the override will be used by ‘Enum.__format__’ regardless of
     whether mixin classes are present.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41817

   (2) https://bugs.python.org/issue41815

   (3) https://bugs.python.org/issue41517

   (4) https://bugs.python.org/issue39587

   (5) https://bugs.python.org/issue41789

   (6) https://bugs.python.org/issue39651

   (7) https://bugs.python.org/issue41720

   (8) https://bugs.python.org/issue39728

   (9) https://bugs.python.org/issue37479


File: python.info,  Node: 文档<8>,  Next: 测试<5>,  Prev: 库<8>,  Up: Python 3 8 6 final

1.18.9.3 文档
.............

   - bpo-35293(1): Fix RemovedInSphinx40Warning when building the
     documentation.  Patch by Dong-hee Na.

   - bpo-37149(2): Change Shipman tkinter doc link from archive.org to
     TkDocs.  (The doc has been removed from the NMT server.)  The new
     link responds much faster and includes a short explanatory note.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35293

   (2) https://bugs.python.org/issue37149


File: python.info,  Node: 测试<5>,  Next: Windows<5>,  Prev: 文档<8>,  Up: Python 3 8 6 final

1.18.9.4 测试
.............

   - bpo-41731(1): Make test_cmd_line_script pass with option ’-vv’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41731


File: python.info,  Node: Windows<5>,  Next: IDLE<7>,  Prev: 测试<5>,  Up: Python 3 8 6 final

1.18.9.5 Windows
................

   - bpo-41744(1): Fixes automatic import of props file when using the
     Nuget package.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41744


File: python.info,  Node: IDLE<7>,  Prev: Windows<5>,  Up: Python 3 8 6 final

1.18.9.6 IDLE
.............

   - bpo-35764(1): Rewrite the Calltips doc section.

   - bpo-40181(2): In calltips, stop reminding that ’/’ marks the end of
     positional-only arguments.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35764

   (2) https://bugs.python.org/issue40181


File: python.info,  Node: Python 3 8 6 release candidate 1,  Next: Python 3 8 5 final,  Prev: Python 3 8 6 final,  Up: 更新日志

1.18.10 Python 3.8.6 release candidate 1
----------------------------------------

`Release date: 2020-09-07'

* Menu:

* 核心与内置: 核心与内置<9>.
* 库: 库<9>.
* 文档: 文档<9>.
* Windows: Windows<6>.
* IDLE: IDLE<8>.
* C API: C API<4>.


File: python.info,  Node: 核心与内置<9>,  Next: 库<9>,  Up: Python 3 8 6 release candidate 1

1.18.10.1 核心与内置
....................

   - bpo-41654(1): Fix a crash that occurred when destroying subclasses
     of *note MemoryError: efc.  Patch by Pablo Galindo.

   - bpo-41533(2): Free the stack allocated in ‘va_build_stack’ if
     ‘do_mkstack’ fails and the stack is not a ‘small_stack’.

   - bpo-38156(3): 正确地处理 ‘PyOS_StdioReadline’ 中 EOF 之后的中断。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41654

   (2) https://bugs.python.org/issue41533

   (3) https://bugs.python.org/issue38156


File: python.info,  Node: 库<9>,  Next: 文档<9>,  Prev: 核心与内置<9>,  Up: Python 3 8 6 release candidate 1

1.18.10.2 库
............

   - bpo-41696(1): Fix handling of debug mode in *note asyncio.run():
     1a6.  This allows setting ‘PYTHONASYNCIODEBUG’ or ‘-X dev’ to
     enable asyncio debug mode when using *note asyncio.run(): 1a6.

   - bpo-39010(2): Restarting a ‘ProactorEventLoop’ on Windows no longer
     logs spurious ‘ConnectionResetErrors’.

   - bpo-41609(3): The pdb whatis command correctly reports instance
     methods as ’Method’ rather than ’Function’.

   - bpo-32751(4): When cancelling the task due to a timeout, *note
     asyncio.wait_for(): 289. will now wait until the cancellation is
     complete also in the case when `timeout' is <= 0, like it does with
     positive timeouts.

   - bpo-37658(5): *note asyncio.wait_for(): 289. now properly handles
     races between cancellation of itself and the completion of the
     wrapped awaitable.

   - bpo-40782(6): Change the method
     asyncio.AbstractEventLoop.run_in_executor to not be a coroutine.

   - bpo-41520(7): Fix *note codeop: 1d. regression that prevented
     turning compile warnings into errors.

   - bpo-41503(8): Fixed a race between setTarget and flush in
     logging.handlers.MemoryHandler.

   - bpo-41497(9): 在 dis 模块中修复潜在的 UnicodeDecodeError。

   - bpo-41490(10): 更新 *note ensurepip: 7a. 以安装 pip 20.2.1 和
     setuptools 49.2.1。

   - bpo-41467(11): 在 Windows 上，修复 asyncio ‘recv_into()’ 当套接字
     /管道被关闭时的返回值 (*note BrokenPipeError: 9a5.)：返回 ‘0’ 而不
     是空字节串 (‘b''’)。

   - bpo-41425(12): 让 tkinter 文档示例可运行。

   - bpo-41384(13): 当传给 tkinter.OptionMenu 的选项未知时引发 TclError
     而不是 TypeError。

   - bpo-38731(14): 修复了 *note py_compile: d8. 模块命令行界面下的
     *note NameError: d83.。

   - bpo-41364(15): 减少 *note uuid: 125. 的导入开销。

   - bpo-41344(16): Prevent creating ‘shared_memory.SharedMemory’
     objects with ‘size=0’.

   - bpo-40726(17): 处理在 *note ast.increment_lineno(): efe. 上
     ‘end_lineno’ 为 ‘None’ 的情况。

   - bpo-31122(18): ssl.wrap_socket() now raises ssl.SSLEOFError rather
     than OSError when peer closes connection during TLS negotiation

   - bpo-33660(19): Fix pathlib.PosixPath to resolve a relative path
     located on the root directory properly.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41696

   (2) https://bugs.python.org/issue39010

   (3) https://bugs.python.org/issue41609

   (4) https://bugs.python.org/issue32751

   (5) https://bugs.python.org/issue37658

   (6) https://bugs.python.org/issue40782

   (7) https://bugs.python.org/issue41520

   (8) https://bugs.python.org/issue41503

   (9) https://bugs.python.org/issue41497

   (10) https://bugs.python.org/issue41490

   (11) https://bugs.python.org/issue41467

   (12) https://bugs.python.org/issue41425

   (13) https://bugs.python.org/issue41384

   (14) https://bugs.python.org/issue38731

   (15) https://bugs.python.org/issue41364

   (16) https://bugs.python.org/issue41344

   (17) https://bugs.python.org/issue40726

   (18) https://bugs.python.org/issue31122

   (19) https://bugs.python.org/issue33660


File: python.info,  Node: 文档<9>,  Next: Windows<6>,  Prev: 库<9>,  Up: Python 3 8 6 release candidate 1

1.18.10.3 文档
..............

   - bpo-41624(1): Fix the signature of *note typing.Coroutine: f00.

   - bpo-40204(2): Enable Sphinx 3.2 ‘c_allow_pre_v3’ option and disable
     ‘c_warn_on_allowed_pre_v3’ option to make the documentation
     compatible with Sphinx 2 and Sphinx 3.

   - bpo-41045(3): 添加了 关于f-strings调试功能的文档.

   - bpo-41314(4): 将‘‘from __future__ import annotations‘‘ 的默认值由
     ‘4.0’ 变更到‘‘3.10‘‘ (参考 PEP 563的变更).

   - bpo-39883(5): Make code, examples, and recipes in the Python
     documentation be licensed under the more permissive BSD0 license in
     addition to the existing Python 2.0 license.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41624

   (2) https://bugs.python.org/issue40204

   (3) https://bugs.python.org/issue41045

   (4) https://bugs.python.org/issue41314

   (5) https://bugs.python.org/issue39883


File: python.info,  Node: Windows<6>,  Next: IDLE<8>,  Prev: 文档<9>,  Up: Python 3 8 6 release candidate 1

1.18.10.4 Windows
.................

   - bpo-41492(1): 修复了UAC提示的描述.

   - bpo-40741(2): 更新 Windows 版本以支持 SQLite 3.32.3.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41492

   (2) https://bugs.python.org/issue40741


File: python.info,  Node: IDLE<8>,  Next: C API<4>,  Prev: Windows<6>,  Up: Python 3 8 6 release candidate 1

1.18.10.5 IDLE
..............

   - bpo-41468(1): 改进IDIE运行错误信息 (也许用户永远都看不到).

   - bpo-41373(2): Save files loaded with no line ending, as when blank,
     or different line endings, by setting its line ending to the system
     default.  Fix regression in 3.8.4 and 3.9.0b4.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41468

   (2) https://bugs.python.org/issue41373


File: python.info,  Node: C API<4>,  Prev: IDLE<8>,  Up: Python 3 8 6 release candidate 1

1.18.10.6 C API
...............

   - bpo-41524(1): Fix bug in PyOS_mystrnicmp and PyOS_mystricmp that
     incremented pointers beyond the end of a string.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41524


File: python.info,  Node: Python 3 8 5 final,  Next: Python 3 8 4 final,  Prev: Python 3 8 6 release candidate 1,  Up: 更新日志

1.18.11 Python 3.8.5 final
--------------------------

`Release date: 2020-07-20'

* Menu:

* 安全: 安全<7>.
* 核心与内置: 核心与内置<10>.
* 库: 库<10>.
* 文档: 文档<10>.
* 构建: 构建<5>.
* macOS: macOS<6>.
* IDLE: IDLE<9>.


File: python.info,  Node: 安全<7>,  Next: 核心与内置<10>,  Up: Python 3 8 5 final

1.18.11.1 安全
..............

   - bpo-41304(1): Fixes ‘python3x._pth’ being ignored on Windows,
     caused by the fix for bpo-29778(2) (CVE-2020-15801).

   - bpo-39603(3): Prevent http header injection by rejecting control
     characters in http.client.putrequest(...).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41304

   (2) https://bugs.python.org/issue29778

   (3) https://bugs.python.org/issue39603


File: python.info,  Node: 核心与内置<10>,  Next: 库<10>,  Prev: 安全<7>,  Up: Python 3 8 5 final

1.18.11.2 核心与内置
....................

   - bpo-41295(1): Resolve a regression in CPython 3.8.4 where defining
     "__setattr__" in a multi-inheritance setup and calling up the
     hierarchy chain could fail if builtins/extension types were
     involved in the base types.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41295


File: python.info,  Node: 库<10>,  Next: 文档<10>,  Prev: 核心与内置<10>,  Up: Python 3 8 5 final

1.18.11.3 库
............

   - bpo-41288(1): Unpickling invalid NEWOBJ_EX opcode with the C
     implementation raises now UnpicklingError instead of crashing.

   - bpo-39017(2): Avoid infinite loop when reading specially crafted
     TAR files using the tarfile module (CVE-2019-20907).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41288

   (2) https://bugs.python.org/issue39017


File: python.info,  Node: 文档<10>,  Next: 构建<5>,  Prev: 库<10>,  Up: Python 3 8 5 final

1.18.11.4 文档
..............

   - bpo-37703(1): Updated Documentation to comprehensively elaborate on
     the behaviour of gather.cancel()

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37703


File: python.info,  Node: 构建<5>,  Next: macOS<6>,  Prev: 文档<10>,  Up: Python 3 8 5 final

1.18.11.5 构建
..............

   - bpo-41302(1): Enable building Python 3.8 with libmpdec-2.5.0 to
     ease maintenance for Linux distributions.  Patch by Felix Yan.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41302


File: python.info,  Node: macOS<6>,  Next: IDLE<9>,  Prev: 构建<5>,  Up: Python 3 8 5 final

1.18.11.6 macOS
...............

   - bpo-40741(1): Update macOS installer to use SQLite 3.32.3.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40741


File: python.info,  Node: IDLE<9>,  Prev: macOS<6>,  Up: Python 3 8 5 final

1.18.11.7 IDLE
..............

   - bpo-41300(1): Save files with non-ascii chars.  Fix regression
     released in 3.9.0b4 and 3.8.4.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41300


File: python.info,  Node: Python 3 8 4 final,  Next: Python 3 8 4 release candidate 1,  Prev: Python 3 8 5 final,  Up: 更新日志

1.18.12 Python 3.8.4 final
--------------------------

`Release date: 2020-07-13'

* Menu:

* 安全: 安全<8>.
* 核心与内置: 核心与内置<11>.
* 库: 库<11>.
* IDLE: IDLE<10>.


File: python.info,  Node: 安全<8>,  Next: 核心与内置<11>,  Up: Python 3 8 4 final

1.18.12.1 安全
..............

   - bpo-41162(1): Audit hooks are now cleared later during finalization
     to avoid missing events.

   - bpo-29778(2): Ensure ‘python3.dll’ is loaded from correct locations
     when Python is embedded (CVE-2020-15523).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41162

   (2) https://bugs.python.org/issue29778


File: python.info,  Node: 核心与内置<11>,  Next: 库<11>,  Prev: 安全<8>,  Up: Python 3 8 4 final

1.18.12.2 核心与内置
....................

   - bpo-41247(1): Always cache the running loop holder when running
     ‘asyncio.set_running_loop’.

   - bpo-41252(2): Fix incorrect refcounting in _ssl.c’s
     ‘_servername_callback()’.

   - bpo-41218(3): Python 3.8.3 had a regression where compiling with
     ast.PyCF_ALLOW_TOP_LEVEL_AWAIT would aggressively mark list
     comprehension with CO_COROUTINE. Now only list comprehension making
     use of async/await will tagged as so.

   - bpo-41175(4): Guard against a NULL pointer dereference within
     bytearrayobject triggered by the ‘bytearray() + bytearray()’
     operation.

   - bpo-39960(5): The "hackcheck" that prevents sneaking around a
     type’s __setattr__() by calling the superclass method was rewritten
     to allow C implemented heap types.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41247

   (2) https://bugs.python.org/issue41252

   (3) https://bugs.python.org/issue41218

   (4) https://bugs.python.org/issue41175

   (5) https://bugs.python.org/issue39960


File: python.info,  Node: 库<11>,  Next: IDLE<10>,  Prev: 核心与内置<11>,  Up: Python 3 8 4 final

1.18.12.3 库
............

   - bpo-41235(1): Fix the error handling in *note
     ssl.SSLContext.load_dh_params(): a9a.

   - bpo-41193(2): The ‘write_history()’ atexit function of the readline
     completer now ignores any *note OSError: 1d4. to ignore error if
     the filesystem is read-only, instead of only ignoring *note
     FileNotFoundError: 7c9. and *note PermissionError: 608.

   - bpo-41043(3): Fixed the use of *note glob(): 5cf. in the stdlib:
     literal part of the path is now always correctly escaped.

   - bpo-39384(4): Fixed email.contentmanager to allow set_content() to
     set a null string.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41235

   (2) https://bugs.python.org/issue41193

   (3) https://bugs.python.org/issue41043

   (4) https://bugs.python.org/issue39384


File: python.info,  Node: IDLE<10>,  Prev: 库<11>,  Up: Python 3 8 4 final

1.18.12.4 IDLE
..............

   - bpo-37765(1): Add keywords to module name completion list.  Rewrite
     Completions section of IDLE doc.

   - bpo-41152(2): The encoding of ‘stdin’, ‘stdout’ and ‘stderr’ in
     IDLE is now always UTF-8.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37765

   (2) https://bugs.python.org/issue41152


File: python.info,  Node: Python 3 8 4 release candidate 1,  Next: Python 3 8 3 final,  Prev: Python 3 8 4 final,  Up: 更新日志

1.18.13 Python 3.8.4 release candidate 1
----------------------------------------

`Release date: 2020-06-29'

* Menu:

* 安全: 安全<9>.
* 核心与内置: 核心与内置<12>.
* 库: 库<12>.
* 测试: 测试<6>.
* 构建: 构建<6>.
* Windows: Windows<7>.
* macOS: macOS<7>.
* IDLE: IDLE<11>.
* 工具/示例: 工具/示例<3>.


File: python.info,  Node: 安全<9>,  Next: 核心与内置<12>,  Up: Python 3 8 4 release candidate 1

1.18.13.1 安全
..............

   - bpo-41004(1): The __hash__() methods of ipaddress.IPv4Interface and
     ipaddress.IPv6Interface incorrectly generated constant hash values
     of 32 and 128 respectively.  This resulted in always causing hash
     collisions.  The fix uses hash() to generate hash values for the
     tuple of (address, mask length, network address).

   - bpo-39073(2): Disallow CR or LF in email.headerregistry.Address
     arguments to guard against header injection attacks.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41004

   (2) https://bugs.python.org/issue39073


File: python.info,  Node: 核心与内置<12>,  Next: 库<12>,  Prev: 安全<9>,  Up: Python 3 8 4 release candidate 1

1.18.13.2 核心与内置
....................

   - bpo-41094(1): Fix decoding errors with audit when open files with
     non-ASCII names on non-UTF-8 locale.

   - bpo-41056(2): Fixes a reference to deallocated stack space during
     startup when constructing sys.path involving a relative symlink
     when code was supplied via -c.  (discovered via Coverity)

   - bpo-35975(3): Stefan Behnel reported that cf_feature_version is
     used even when PyCF_ONLY_AST is not set.  This is against the
     intention and against the documented behavior, so it’s been fixed.

   - bpo-40957(4): Fix refleak in _Py_fopen_obj() when PySys_Audit()
     fails

   - bpo-40870(5): Raise *note ValueError: 1fc. when validating custom
     AST’s where the constants ‘True’, ‘False’ and ‘None’ are used
     within a ‘ast.Name’ node.

   - bpo-40826(6): Fix GIL usage in ‘PyOS_Readline()’: lock the GIL to
     set an exception and pass the Python thread state when checking if
     there is a pending signal.

   - bpo-40824(7): Unexpected errors in calling the ‘__iter__’ method
     are no longer masked by ‘TypeError’ in the *note in: 7ac. operator
     and functions *note contains(): f14, *note indexOf(): f15. and
     *note countOf(): f16. of the *note operator: c3. module.

   - bpo-40663(8): Correctly generate annotations where parentheses are
     omitted but required (e.g: ‘Type[(str, int, *other))]’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41094

   (2) https://bugs.python.org/issue41056

   (3) https://bugs.python.org/issue35975

   (4) https://bugs.python.org/issue40957

   (5) https://bugs.python.org/issue40870

   (6) https://bugs.python.org/issue40826

   (7) https://bugs.python.org/issue40824

   (8) https://bugs.python.org/issue40663


File: python.info,  Node: 库<12>,  Next: 测试<6>,  Prev: 核心与内置<12>,  Up: Python 3 8 4 release candidate 1

1.18.13.3 库
............

   - bpo-41138(1): Fixed the *note trace: 113. module CLI for Python
     source files with non-UTF-8 encoding.

   - bpo-31938(2): Fix default-value signatures of several functions in
     the *note select: e6. module - by Anthony Sottile.

   - bpo-41068(3): Fixed reading files with non-ASCII names from ZIP
     archive directly after writing them.

   - bpo-41058(4): ‘pdb.find_function()’ now correctly determines the
     source file encoding.

   - bpo-41056(5): Fix a NULL pointer dereference within the ssl module
     during a MemoryError in the keylog callback.  (discovered by
     Coverity)

   - bpo-41048(6): *note mimetypes.read_mime_types(): f18. function
     reads the rule file using UTF-8 encoding, not the locale encoding.
     Patch by Srinivas Reddy Thatiparthy.

   - bpo-40448(7): *note ensurepip: 7a. now disables the use of ‘pip’
     cache when installing the bundled versions of ‘pip’ and
     ‘setuptools’.  Patch by Krzysztof Konopko.

   - bpo-40855(8): The standard deviation and variance functions in the
     statistics module were ignoring their mu and xbar arguments.

   - bpo-40807(9): Stop codeop._maybe_compile, used by
     code.InteractiveInterpreter (and IDLE). from from emitting each
     warning three times.

   - bpo-40834(10): Fix truncate when sending str object
     with_xxsubinterpreters.channel_send.

   - bpo-38488(11): Update ensurepip to install pip 20.1.1 and
     setuptools 47.1.0.

   - bpo-40767(12): *note webbrowser: 12a. now properly finds the
     default browser in pure Wayland systems by checking the
     WAYLAND_DISPLAY environment variable.  Patch contributed by Jérémy
     Attali.

   - bpo-40795(13): *note ctypes: 2b. module: If ctypes fails to convert
     the result of a callback or if a ctypes callback function raises an
     exception, sys.unraisablehook is now called with an exception set.
     Previously, the error was logged into stderr by *note
     PyErr_Print(): f19.

   - bpo-30008(14): Fix *note ssl: f4. code to be compatible with
     OpenSSL 1.1.x builds that use ‘no-deprecated’ and ‘--api=1.1.0’.

   - bpo-40614(15): *note ast.parse(): 1a2. will not parse self
     documenting expressions in f-strings when passed ‘feature_version’
     is less than ‘(3, 8)’.

   - bpo-40626(16): Add h5 file extension as MIME Type
     application/x-hdf5, as per HDF Group recommendation for HDF5
     formatted data files.  Patch contributed by Mark Schwab.

   - bpo-25872(17): *note linecache: a9. could crash with a *note
     KeyError: 2c8. when accessed from multiple threads.  Fix by Michael
     Graczyk.

   - bpo-40597(18): If text content lines are longer than
     policy.max_line_length, always use a content-encoding to make sure
     they are wrapped.

   - bpo-40515(19): The *note ssl: f4. and *note hashlib: 8d. modules
     now actively check that OpenSSL is build with thread support.
     Python 3.7.0 made thread support mandatory and no longer works
     safely with a no-thread builds.

   - bpo-13097(20): ‘ctypes’ now raises an ‘ArgumentError’ when a
     callback is invoked with more than 1024 arguments.

   - bpo-40457(21): The ssl module now support OpenSSL builds without
     TLS 1.0 and 1.1 methods.

   - bpo-39830(22): Add *note zipfile.Path: f1a. to ‘__all__’ in the
     *note zipfile: 143. module.

   - bpo-40025(23): Raise TypeError when _generate_next_value_ is
     defined after members.  Patch by Ethan Onstott.

   - bpo-39244(24): Fixed
     ‘multiprocessing.context.get_all_start_methods’ to properly return
     the default method first on macOS.

   - bpo-39040(25): Fix parsing of invalid mime headers parameters by
     collapsing whitespace between encoded words in a bare-quote-string.

   - bpo-35714(26): *note struct.error: cbc. is now raised if there is a
     null character in a *note struct: f9. format string.

   - bpo-36290(27): AST nodes are now raising *note TypeError: 193. on
     conflicting keyword arguments.  Patch contributed by Rémi Lapeyre.

   - bpo-29620(28): *note assertWarns(): ac4. no longer raises a
     ‘RuntimeException’ when accessing a module’s ‘__warningregistry__’
     causes importation of a new module, or when a new module is
     imported in another thread.  Patch by Kernc.

   - bpo-34226(29): Fix *note cgi.parse_multipart: 2ef. without
     content_length.  Patch by Roger Duran

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41138

   (2) https://bugs.python.org/issue31938

   (3) https://bugs.python.org/issue41068

   (4) https://bugs.python.org/issue41058

   (5) https://bugs.python.org/issue41056

   (6) https://bugs.python.org/issue41048

   (7) https://bugs.python.org/issue40448

   (8) https://bugs.python.org/issue40855

   (9) https://bugs.python.org/issue40807

   (10) https://bugs.python.org/issue40834

   (11) https://bugs.python.org/issue38488

   (12) https://bugs.python.org/issue40767

   (13) https://bugs.python.org/issue40795

   (14) https://bugs.python.org/issue30008

   (15) https://bugs.python.org/issue40614

   (16) https://bugs.python.org/issue40626

   (17) https://bugs.python.org/issue25872

   (18) https://bugs.python.org/issue40597

   (19) https://bugs.python.org/issue40515

   (20) https://bugs.python.org/issue13097

   (21) https://bugs.python.org/issue40457

   (22) https://bugs.python.org/issue39830

   (23) https://bugs.python.org/issue40025

   (24) https://bugs.python.org/issue39244

   (25) https://bugs.python.org/issue39040

   (26) https://bugs.python.org/issue35714

   (27) https://bugs.python.org/issue36290

   (28) https://bugs.python.org/issue29620

   (29) https://bugs.python.org/issue34226


File: python.info,  Node: 测试<6>,  Next: 构建<6>,  Prev: 库<12>,  Up: Python 3 8 4 release candidate 1

1.18.13.4 测试
..............

   - bpo-41085(1): Fix integer overflow in the *note
     array.array.index(): f1c. method on 64-bit Windows for index larger
     than ‘2**31’.

   - bpo-38377(2): On Linux, skip tests using multiprocessing if the
     current user cannot create a file in ‘/dev/shm/’ directory.  Add
     the ‘skip_if_broken_multiprocessing_synchronize()’ function to the
     *note test.support: 107. module.

   - bpo-41009(3): Fix use of
     ‘support.require_{linux|mac|freebsd}_version()’ decorators as class
     decorator.

   - bpo-41003(4): Fix ‘test_copyreg’ when ‘numpy’ is installed:
     ‘test.pickletester’ now saves/restores warnings filters when
     importing ‘numpy’, to ignore filters installed by ‘numpy’.

   - bpo-40964(5): Disable remote *note imaplib: 98. tests, host
     cyrus.andrew.cmu.edu is blocking incoming connections.

   - bpo-40055(6): distutils.tests now saves/restores warnings filters
     to leave them unchanged.  Importing tests imports docutils which
     imports pkg_resources which adds a warnings filter.

   - bpo-34401(7): Make test_gdb properly run on HP-UX. Patch by Michael
     Osipov.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41085

   (2) https://bugs.python.org/issue38377

   (3) https://bugs.python.org/issue41009

   (4) https://bugs.python.org/issue41003

   (5) https://bugs.python.org/issue40964

   (6) https://bugs.python.org/issue40055

   (7) https://bugs.python.org/issue34401


File: python.info,  Node: 构建<6>,  Next: Windows<7>,  Prev: 测试<6>,  Up: Python 3 8 4 release candidate 1

1.18.13.5 构建
..............

   - bpo-40204(1): Pin Sphinx version to 2.3.1 in ‘Doc/Makefile’.

   - bpo-40653(2): Move _dirnameW out of HAVE_SYMLINK to fix a potential
     compiling issue.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40204

   (2) https://bugs.python.org/issue40653


File: python.info,  Node: Windows<7>,  Next: macOS<7>,  Prev: 构建<6>,  Up: Python 3 8 4 release candidate 1

1.18.13.6 Windows
.................

   - bpo-41074(1): Fixed support of non-ASCII names in functions *note
     msilib.OpenDatabase(): f1f. and *note msilib.init_database(): f20.
     and non-ASCII SQL in method *note msilib.Database.OpenView(): f21.

   - bpo-40164(2): Updates Windows OpenSSL to 1.1.1g

   - bpo-39631(3): Changes the registered MIME type for ‘.py’ files on
     Windows to ‘text/x-python’ instead of ‘text/plain’.

   - bpo-40677(4): Manually define IO_REPARSE_TAG_APPEXECLINK in case
     some old Windows SDK doesn’t have it.

   - bpo-40650(5): Include winsock2.h in pytime.c for timeval.

   - bpo-39148(6): Add IPv6 support to *note asyncio: a. datagram
     endpoints in ProactorEventLoop.  Change the raised exception for
     unknown address families to ValueError as it’s not coming from
     Windows API.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41074

   (2) https://bugs.python.org/issue40164

   (3) https://bugs.python.org/issue39631

   (4) https://bugs.python.org/issue40677

   (5) https://bugs.python.org/issue40650

   (6) https://bugs.python.org/issue39148


File: python.info,  Node: macOS<7>,  Next: IDLE<11>,  Prev: Windows<7>,  Up: Python 3 8 4 release candidate 1

1.18.13.7 macOS
...............

   - bpo-39580(1): Avoid opening Finder window if running installer from
     the command line.  Patch contributed by Rick Heil.

   - bpo-41100(2): Fix configure error when building on macOS 11.  Note
     that the current Python release was released shortly after the
     first developer preview of macOS 11 (Big Sur); there are other
     known issues with building and running on the developer preview.
     Big Sur is expected to be fully supported in a future bugfix
     release of Python 3.8.x and with 3.9.0.

   - bpo-41005(3): fixed an XDG settings issue not allowing macos to
     open browser in webbrowser.py

   - bpo-40741(4): Update macOS installer to use SQLite 3.32.2.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39580

   (2) https://bugs.python.org/issue41100

   (3) https://bugs.python.org/issue41005

   (4) https://bugs.python.org/issue40741


File: python.info,  Node: IDLE<11>,  Next: 工具/示例<3>,  Prev: macOS<7>,  Up: Python 3 8 4 release candidate 1

1.18.13.8 IDLE
..............

   - bpo-41144(1): Make Open Module open a special module such as
     os.path.

   - bpo-39885(2): Make context menu Cut and Copy work again when
     right-clicking within a selection.

   - bpo-40723(3): Make test_idle pass when run after import.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41144

   (2) https://bugs.python.org/issue39885

   (3) https://bugs.python.org/issue40723


File: python.info,  Node: 工具/示例<3>,  Prev: IDLE<11>,  Up: Python 3 8 4 release candidate 1

1.18.13.9 工具/示例
...................

   - bpo-40479(1): Update multissltest helper to test with latest
     OpenSSL 1.0.2, 1.1.0, 1.1.1, and 3.0.0-alpha.

   - bpo-40163(2): Fix multissltest tool.  OpenSSL has changed download
     URL for old releases.  The multissltest tool now tries to download
     from current and old download URLs.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40479

   (2) https://bugs.python.org/issue40163


File: python.info,  Node: Python 3 8 3 final,  Next: Python 3 8 3 release candidate 1,  Prev: Python 3 8 4 release candidate 1,  Up: 更新日志

1.18.14 Python 3.8.3 final
--------------------------

`Release date: 2020-05-13'

* Menu:

* 核心与内置: 核心与内置<13>.
* 库: 库<13>.
* 文档: 文档<11>.
* Windows: Windows<8>.
* C API: C API<5>.


File: python.info,  Node: 核心与内置<13>,  Next: 库<13>,  Up: Python 3 8 3 final

1.18.14.1 核心与内置
....................

   - bpo-40527(1): Fix command line argument parsing: no longer write
     errors multiple times into stderr.

   - bpo-40417(2): Fix imp module deprecation warning when
     PyImport_ReloadModule is called.  Patch by Robert Rouhani.

   - bpo-39562(3): The constant values of future flags in the *note
     __future__: 0. module are updated in order to prevent collision
     with compiler flags.  Previously ‘PyCF_ALLOW_TOP_LEVEL_AWAIT’ was
     clashing with ‘CO_FUTURE_DIVISION’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40527

   (2) https://bugs.python.org/issue40417

   (3) https://bugs.python.org/issue39562


File: python.info,  Node: 库<13>,  Next: 文档<11>,  Prev: 核心与内置<13>,  Up: Python 3 8 3 final

1.18.14.2 库
............

   - bpo-40559(1): Fix possible memory leak in the C implementation of
     *note asyncio.Task: 1ae.

   - bpo-40355(2): Improve error reporting in *note ast.literal_eval():
     4ad. in the presence of malformed ‘ast.Dict’ nodes instead of
     silently ignoring any non-conforming elements.  Patch by Curtis
     Bucher.

   - bpo-40459(3): *note platform.win32_ver(): f28. now produces correct
     `ptype' strings instead of empty strings.

   - bpo-40398(4): *note typing.get_args(): 245. now always returns an
     empty tuple for special generic aliases.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40559

   (2) https://bugs.python.org/issue40355

   (3) https://bugs.python.org/issue40459

   (4) https://bugs.python.org/issue40398


File: python.info,  Node: 文档<11>,  Next: Windows<8>,  Prev: 库<13>,  Up: Python 3 8 3 final

1.18.14.3 文档
..............

   - bpo-40561(1): Provide docstrings for webbrowser open functions.

   - bpo-39435(2): Fix an incorrect signature for *note pickle.loads():
     5cc. in the docs

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40561

   (2) https://bugs.python.org/issue39435


File: python.info,  Node: Windows<8>,  Next: C API<5>,  Prev: 文档<11>,  Up: Python 3 8 3 final

1.18.14.4 Windows
.................

   - bpo-40458(1): Increase reserved stack space to prevent overflow
     crash on Windows.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40458


File: python.info,  Node: C API<5>,  Prev: Windows<8>,  Up: Python 3 8 3 final

1.18.14.5 C API
...............

   - bpo-40412(1): Nullify inittab_copy during finalization, preventing
     future interpreter initializations in an embedded situation from
     crashing.  Patch by Gregory Szorc.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40412


File: python.info,  Node: Python 3 8 3 release candidate 1,  Next: Python 3 8 2 正式版,  Prev: Python 3 8 3 final,  Up: 更新日志

1.18.15 Python 3.8.3 release candidate 1
----------------------------------------

`发布日期: 2020-04-29'

* Menu:

* 安全: 安全<10>.
* 核心与内置: 核心与内置<14>.
* 库: 库<14>.
* 文档: 文档<12>.
* 测试: 测试<7>.
* 构建: 构建<7>.
* Windows: Windows<9>.
* macOS: macOS<8>.
* IDLE: IDLE<12>.
* 工具/示例: 工具/示例<4>.
* C API: C API<6>.


File: python.info,  Node: 安全<10>,  Next: 核心与内置<14>,  Up: Python 3 8 3 release candidate 1

1.18.15.1 安全
..............

   - bpo-40121(1): Fixes audit events raised on creating a new socket.

   - bpo-38576(2): Disallow control characters in hostnames in
     http.client, addressing CVE-2019-18348.  Such potentially malicious
     header injection URLs now cause a InvalidURL to be raised.

   - bpo-39503(3): CVE-2020-8492: The *note AbstractBasicAuthHandler:
     ea2. class of the *note urllib.request: 121. module uses an
     inefficient regular expression which can be exploited by an
     attacker to cause a denial of service.  Fix the regex to prevent
     the catastrophic backtracking.  Vulnerability reported by Ben
     Caller and Matt Schwager.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40121

   (2) https://bugs.python.org/issue38576

   (3) https://bugs.python.org/issue39503


File: python.info,  Node: 核心与内置<14>,  Next: 库<14>,  Prev: 安全<10>,  Up: Python 3 8 3 release candidate 1

1.18.15.2 核心与内置
....................

   - bpo-20526(1): Fix *note PyThreadState_Clear(): f2f.
     ‘PyThreadState.frame’ is a borrowed reference, not a strong
     reference: ‘PyThreadState_Clear()’ must not call
     ‘Py_CLEAR(tstate->frame)’.

   - bpo-39965(2): Correctly raise ‘SyntaxError’ if `await' is used
     inside non-async functions and ‘PyCF_ALLOW_TOP_LEVEL_AWAIT’ is set
     (like in the asyncio REPL). Patch by Pablo Galindo.

   - bpo-39562(3): Allow executing asynchronous comprehensions on the
     top level when the ‘PyCF_ALLOW_TOP_LEVEL_AWAIT’ flag is given.
     Patch by Batuhan Taskaya.

   - bpo-38894(4): Fix a bug that was causing incomplete results when
     calling ‘pathlib.Path.glob’ in the presence of symlinks that point
     to files where the user does not have read access.  Patch by Pablo
     Galindo and Matt Wozniski.

   - bpo-39871(5): Fix a possible *note SystemError: 604. in
     ‘math.{atan2,copysign,remainder}()’ when the first argument cannot
     be converted to a *note float: 188.  Patch by Zackery Spytz.

   - bpo-39776(6): Fix race condition where threads created by
     PyGILState_Ensure() could get a duplicate id.

     This affects consumers of tstate->id like the contextvar caching
     machinery, which could return invalid cached objects under heavy
     thread load (observed in embedded scenarios).

   - bpo-39778(7): Fixed a crash due to incorrect handling of weak
     references in ‘collections.OrderedDict’ classes.  Patch by Pablo
     Galindo.

   - bpo-39520(8): Fix unparsing of ext slices with no items
     (‘foo[:,]’).  Patch by Batuhan Taskaya.

   - bpo-22490(9): Don’t leak environment variable ‘__PYVENV_LAUNCHER__’
     into the interpreter session on macOS.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20526

   (2) https://bugs.python.org/issue39965

   (3) https://bugs.python.org/issue39562

   (4) https://bugs.python.org/issue38894

   (5) https://bugs.python.org/issue39871

   (6) https://bugs.python.org/issue39776

   (7) https://bugs.python.org/issue39778

   (8) https://bugs.python.org/issue39520

   (9) https://bugs.python.org/issue22490


File: python.info,  Node: 库<14>,  Next: 文档<12>,  Prev: 核心与内置<14>,  Up: Python 3 8 3 release candidate 1

1.18.15.3 库
............

   - bpo-40138(1): Fix the Windows implementation of *note os.waitpid():
     676. for exit code larger than ‘INT_MAX >> 8’.  The exit status is
     now interpreted as an unsigned number.

   - bpo-39942(2): Set "__main__" as the default module name when
     "__name__" is missing in *note typing.TypeVar: f31.  Patch by
     Weipeng Hong.

   - bpo-40330(3): In ‘ShareableList.__setitem__()’, check the size of a
     new string item after encoding it to utf-8, not before.

   - bpo-40287(4): Fixed ‘SpooledTemporaryFile.seek()’ to return the
     position.

   - bpo-40260(5): Ensure *note modulefinder: b5. uses *note
     io.open_code(): f32. and respects coding comments.

   - bpo-40196(6): Fix a bug in the *note symtable: fd. module that was
     causing incorrectly report global variables as local.  Patch by
     Pablo Galindo.

   - bpo-40126(7): Fixed reverting multiple patches in unittest.mock.
     Patcher’s ‘__exit__()’ is now never called if its ‘__enter__()’ is
     failed.  Returning true from ‘__exit__()’ silences now the
     exception.

   - bpo-40089(8): Fix threading._after_fork(): if fork was not called
     by a thread spawned by threading.Thread, threading._after_fork()
     now creates a _MainThread instance for _main_thread, instead of a
     _DummyThread instance.

   - bpo-39503(9): *note AbstractBasicAuthHandler: ea2. of *note
     urllib.request: 121. now parses all WWW-Authenticate HTTP headers
     and accepts multiple challenges per header: use the realm of the
     first Basic challenge.

   - bpo-40014(10): Fix ‘os.getgrouplist()’: if ‘getgrouplist()’
     function fails because the group list is too small, retry with a
     larger group list.  On failure, the glibc implementation of
     ‘getgrouplist()’ sets ‘ngroups’ to the total number of groups.  For
     other implementations, double the group list size.

   - bpo-40016(11): In re docstring, clarify the relationship between
     inline and argument compile flags.

   - bpo-39953(12): Update internal table of OpenSSL error codes in the
     ‘ssl’ module.

   - bpo-39360(13): Ensure all workers exit when finalizing a
     ‘multiprocessing.Pool’ implicitly via the module finalization
     handlers of multiprocessing.  This fixes a deadlock situation that
     can be experienced when the Pool is not properly finalized via the
     context manager or a call to ‘multiprocessing.Pool.terminate’.
     Patch by Batuhan Taskaya and Pablo Galindo.

   - bpo-39652(14): The column name found in
     ‘sqlite3.Cursor.description’ is now truncated on the first ’[’ only
     if the PARSE_COLNAMES option is set.

   - bpo-39915(15): Ensure *note
     unittest.mock.AsyncMock.await_args_list: f33. has call objects in
     the order of awaited arguments instead of using *note
     unittest.mock.Mock.call_args: f34. which has the last value of the
     call.  Patch by Karthikeyan Singaravelan.

   - bpo-38662(16): The ‘ensurepip’ module now invokes ‘pip’ via the
     ‘runpy’ module.  Hence it is no longer tightly coupled with the
     internal API of the bundled ‘pip’ version, allowing easier updates
     to a newer ‘pip’ version both internally and for distributors.

   - bpo-39916(17): More reliable use of ‘os.scandir()’ in
     ‘Path.glob()’.  It no longer emits a ResourceWarning when
     interrupted.

   - bpo-39850(18): *note multiprocessing: b8. now supports abstract
     socket addresses (if abstract sockets are supported in the running
     platform).  Patch by Pablo Galindo.

   - bpo-39828(19): Fix *note json.tool: a6. to catch *note
     BrokenPipeError: 9a5.  Patch by Dong-hee Na.

   - bpo-13487(20): Avoid a possible `"RuntimeError: dictionary changed
     size during iteration"' from *note inspect.getmodule(): f35. when
     it tried to loop through *note sys.modules: f36.

   - bpo-39794(21): Add –without-decimal-contextvar build option.  This
     enables a thread-local rather than a coroutine local context.

   - bpo-39769(22): The *note compileall.compile_dir(): 37b. function’s
     `ddir' parameter and the compileall command line flag ‘-d’ no
     longer write the wrong pathname to the generated pyc file for
     submodules beneath the root of the directory tree being compiled.
     This fixes a regression introduced with Python 3.5.

   - bpo-39517(23): Fix runpy.run_path() when using pathlike objects

   - bpo-39764(24): Fix AttributeError when calling get_stack on a
     PyAsyncGenObject Task

   - bpo-30566(25): Fix *note IndexError: e7d. when trying to decode an
     invalid string with punycode codec.

   - bpo-39667(26): Correct performance degradation in ‘zipfile.Path’ as
     found in zipp 3.0.  While retaining compatibility, this change
     discourages the use of ‘zipfile.Path.open’ due to the signature
     change in Python 3.9.  For compatibility across Python 3.8 and
     later versions, consider using ‘zipp.Path’ on Python 3.8.x and
     earlier.

   - bpo-39548(27): Fix handling of header in *note
     urllib.request.AbstractDigestAuthHandler: f37. when the optional
     ‘qop’ parameter is not present.

   - bpo-38971(28): Open issue in the BPO indicated a desire to make the
     implementation of codecs.open() at parity with io.open(), which
     implements a try/except to assure file stream gets closed before an
     exception is raised.

   - bpo-38410(29): Properly handle *note sys.audit(): f38. failures in
     *note sys.set_asyncgen_hooks(): f39.  Based on patch by Zackery
     Spytz.

   - bpo-36541(30): lib2to3 now recognizes named assignment expressions
     (the walrus operator, ‘:=’)

   - bpo-31758(31): Prevent crashes when using an uninitialized
     ‘_elementtree.XMLParser’ object.  Patch by Oren Milman.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40138

   (2) https://bugs.python.org/issue39942

   (3) https://bugs.python.org/issue40330

   (4) https://bugs.python.org/issue40287

   (5) https://bugs.python.org/issue40260

   (6) https://bugs.python.org/issue40196

   (7) https://bugs.python.org/issue40126

   (8) https://bugs.python.org/issue40089

   (9) https://bugs.python.org/issue39503

   (10) https://bugs.python.org/issue40014

   (11) https://bugs.python.org/issue40016

   (12) https://bugs.python.org/issue39953

   (13) https://bugs.python.org/issue39360

   (14) https://bugs.python.org/issue39652

   (15) https://bugs.python.org/issue39915

   (16) https://bugs.python.org/issue38662

   (17) https://bugs.python.org/issue39916

   (18) https://bugs.python.org/issue39850

   (19) https://bugs.python.org/issue39828

   (20) https://bugs.python.org/issue13487

   (21) https://bugs.python.org/issue39794

   (22) https://bugs.python.org/issue39769

   (23) https://bugs.python.org/issue39517

   (24) https://bugs.python.org/issue39764

   (25) https://bugs.python.org/issue30566

   (26) https://bugs.python.org/issue39667

   (27) https://bugs.python.org/issue39548

   (28) https://bugs.python.org/issue38971

   (29) https://bugs.python.org/issue38410

   (30) https://bugs.python.org/issue36541

   (31) https://bugs.python.org/issue31758


File: python.info,  Node: 文档<12>,  Next: 测试<7>,  Prev: 库<14>,  Up: Python 3 8 3 release candidate 1

1.18.15.4 文档
..............

   - bpo-27635(1): The pickle documentation incorrectly claimed that
     ‘__new__’ isn’t called by default when unpickling.

   - bpo-39879(2): Updated *note 数据模型: f3b. docs to include *note
     dict(): 1b9. insertion order preservation.  Patch by Furkan Onder
     and Samy Lahfa.

   - bpo-39868(3): Updated the Language Reference for PEP 572(4).

   - bpo-13790(5): Change ’string’ to ’specification’ in format doc.

   - bpo-17422(6): The language reference no longer restricts default
     class namespaces to dicts only.

   - bpo-39530(7): Fix misleading documentation about mixed-type numeric
     comparisons.

   - bpo-39718(8): Update *note token: 111. documentation to reflect
     additions in Python 3.8

   - bpo-39677(9): Changed operand name of `MAKE_FUNCTION' from `argc'
     to `flags' for module *note dis: 38.

   - bpo-38387(10): Document *note PyDoc_STRVAR: f3c. macro in the C-API
     reference.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27635

   (2) https://bugs.python.org/issue39879

   (3) https://bugs.python.org/issue39868

   (4) https://www.python.org/dev/peps/pep-0572

   (5) https://bugs.python.org/issue13790

   (6) https://bugs.python.org/issue17422

   (7) https://bugs.python.org/issue39530

   (8) https://bugs.python.org/issue39718

   (9) https://bugs.python.org/issue39677

   (10) https://bugs.python.org/issue38387


File: python.info,  Node: 测试<7>,  Next: 构建<7>,  Prev: 文档<12>,  Up: Python 3 8 3 release candidate 1

1.18.15.5 测试
..............

   - bpo-40436(1): test_gdb and test.pythoninfo now check gdb command
     exit code.

   - bpo-40162(2): Update Travis CI configuration to OpenSSL 1.1.1f.

   - bpo-40146(3): Update OpenSSL to 1.1.1f in Azure Pipelines.

   - bpo-40019(4): test_gdb now skips tests if it detects that gdb
     failed to read debug information because the Python binary is
     optimized.

   - bpo-27807(5): ‘test_site.test_startup_imports()’ is now skipped if
     a path of *note sys.path: 490. contains a ‘.pth’ file.

   - bpo-39793(6): Use the same domain when testing ‘make_msgid’.  Patch
     by Batuhan Taskaya.

   - bpo-1812(7): Fix newline handling in doctest.testfile when loading
     from a package whose loader has a get_data method.  Patch by Peter
     Donis.

   - bpo-37957(8): test.regrtest now can receive a list of test patterns
     to ignore (using the -i/–ignore argument) or a file with a list of
     patterns to ignore (using the –ignore-file argument).  Patch by
     Pablo Galindo.

   - bpo-38502(9): test.regrtest now uses process groups in the
     multiprocessing mode (-jN command line option) if process groups
     are available: if *note os.setsid(): f3e. and *note os.killpg():
     f3f. functions are available.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40436

   (2) https://bugs.python.org/issue40162

   (3) https://bugs.python.org/issue40146

   (4) https://bugs.python.org/issue40019

   (5) https://bugs.python.org/issue27807

   (6) https://bugs.python.org/issue39793

   (7) https://bugs.python.org/issue1812

   (8) https://bugs.python.org/issue37957

   (9) https://bugs.python.org/issue38502


File: python.info,  Node: 构建<7>,  Next: Windows<9>,  Prev: 测试<7>,  Up: Python 3 8 3 release candidate 1

1.18.15.6 构建
..............

   - bpo-38360(1): Support single-argument form of macOS -isysroot flag.

   - bpo-40204(2): Pin Sphinx version to 1.8.2 in ‘Doc/Makefile’.

   - bpo-40158(3): Fix CPython MSBuild Properties in NuGet Package
     (build/native/python.props)

   - bpo-38527(4): Fix configure check on Solaris for "float word
     ordering": sometimes, the correct "grep" command was not being
     used.  Patch by Arnon Yaari.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38360

   (2) https://bugs.python.org/issue40204

   (3) https://bugs.python.org/issue40158

   (4) https://bugs.python.org/issue38527


File: python.info,  Node: Windows<9>,  Next: macOS<8>,  Prev: 构建<7>,  Up: Python 3 8 3 release candidate 1

1.18.15.7 Windows
.................

   - bpo-40164(1): Updates Windows to OpenSSL 1.1.1f

   - bpo-39930(2): Ensures the required ‘vcruntime140.dll’ is included
     in install packages.

   - bpo-39847(3): Avoid hang when computer is hibernated whilst waiting
     for a mutex (for lock-related objects from *note threading: 10a.)
     around 49-day uptime.

   - bpo-38597(4): *note distutils: 39. will no longer statically link
     ‘vcruntime140.dll’ when a redistributable version is unavailable.
     All future releases of CPython will include a copy of this DLL to
     ensure distributed extensions can continue to load.

   - bpo-38380(5): Update Windows builds to use SQLite 3.31.1

   - bpo-39789(6): Update Windows release build machines to Visual
     Studio 2019 (MSVC 14.2).

   - bpo-34803(7): Package for nuget.org now includes repository
     reference and bundled icon image.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40164

   (2) https://bugs.python.org/issue39930

   (3) https://bugs.python.org/issue39847

   (4) https://bugs.python.org/issue38597

   (5) https://bugs.python.org/issue38380

   (6) https://bugs.python.org/issue39789

   (7) https://bugs.python.org/issue34803


File: python.info,  Node: macOS<8>,  Next: IDLE<12>,  Prev: Windows<9>,  Up: Python 3 8 3 release candidate 1

1.18.15.8 macOS
...............

   - bpo-40164(1): Update macOS installer builds to use OpenSSL 1.1.1g.

   - bpo-38380(2): Update macOS builds to use SQLite 3.31.1

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40164

   (2) https://bugs.python.org/issue38380


File: python.info,  Node: IDLE<12>,  Next: 工具/示例<4>,  Prev: macOS<8>,  Up: Python 3 8 3 release candidate 1

1.18.15.9 IDLE
..............

   - bpo-27115(1): For ’Go to Line’, use a Query box subclass with IDLE
     standard behavior and improved error checking.

   - bpo-39885(2): Since clicking to get an IDLE context menu moves the
     cursor, any text selection should be and now is cleared.

   - bpo-39852(3): Edit "Go to line" now clears any selection,
     preventing accidental deletion.  It also updates Ln and Col on the
     status bar.

   - bpo-39781(4): Selecting code context lines no longer causes a jump.

   - bpo-38439(5): Add a 256×256 pixel IDLE icon to support more modern
     environments.  Created by Andrew Clover.  Delete the unused macOS
     idle.icns icon file.

   - bpo-38689(6): IDLE will no longer freeze when inspect.signature
     fails when fetching a calltip.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27115

   (2) https://bugs.python.org/issue39885

   (3) https://bugs.python.org/issue39852

   (4) https://bugs.python.org/issue39781

   (5) https://bugs.python.org/issue38439

   (6) https://bugs.python.org/issue38689


File: python.info,  Node: 工具/示例<4>,  Next: C API<6>,  Prev: IDLE<12>,  Up: Python 3 8 3 release candidate 1

1.18.15.10 工具/示例
....................

   - bpo-40179(1): Fixed translation of ‘#elif’ in Argument Clinic.

   - bpo-36184(2): Port python-gdb.py to FreeBSD. python-gdb.py now
     checks for "take_gil" function name to check if a frame tries to
     acquire the GIL, instead of checking for "pthread_cond_timedwait"
     which is specific to Linux and can be a different condition than
     the GIL.

   - bpo-39889(3): Fixed ‘unparse.py’ for extended slices containing a
     single element (e.g.  ‘a[i:j,]’).  Remove redundant tuples when
     index with a tuple (e.g.  ‘a[i, j]’).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40179

   (2) https://bugs.python.org/issue36184

   (3) https://bugs.python.org/issue39889


File: python.info,  Node: C API<6>,  Prev: 工具/示例<4>,  Up: Python 3 8 3 release candidate 1

1.18.15.11 C API
................

   - bpo-35370(1): If *note PySys_Audit(): f46. fails in *note
     PyEval_SetProfile(): e43. or *note PyEval_SetTrace(): e44, log the
     error as an unraisable exception.

   - bpo-39884(2): *note PyDescr_NewMethod(): f47. and
     ‘PyCFunction_NewEx()’ now include the method name in the
     SystemError "bad call flags" error message to ease debug.

   - bpo-38643(3): *note PyNumber_ToBase(): f48. now raises a *note
     SystemError: 604. instead of crashing when called with invalid
     base.

   - bpo-38913(4): Fixed segfault in ‘Py_BuildValue()’ called with a
     format containing "#" and undefined PY_SSIZE_T_CLEAN whwn an
     exception is set.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35370

   (2) https://bugs.python.org/issue39884

   (3) https://bugs.python.org/issue38643

   (4) https://bugs.python.org/issue38913


File: python.info,  Node: Python 3 8 2 正式版,  Next: Python 3 8 2 rc2,  Prev: Python 3 8 3 release candidate 1,  Up: 更新日志

1.18.16 Python 3.8.2 正式版
---------------------------

`发布日期: 2020-02-24'

* Menu:

* 核心与内置: 核心与内置<15>.
* 库: 库<15>.
* 文档: 文档<13>.
* IDLE: IDLE<13>.


File: python.info,  Node: 核心与内置<15>,  Next: 库<15>,  Up: Python 3 8 2 正式版

1.18.16.1 核心与内置
....................

   - bpo-39382(1): Fix a use-after-free in the single inheritance path
     of ‘issubclass()’, when the ‘__bases__’ of an object has a single
     reference, and so does its first item.  Patch by Yonatan
     Goldschmidt.

   - bpo-39427(2): Document all possibilities for the ‘-X’ options in
     the command line help section.  Patch by Pablo Galindo.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39382

   (2) https://bugs.python.org/issue39427


File: python.info,  Node: 库<15>,  Next: 文档<13>,  Prev: 核心与内置<15>,  Up: Python 3 8 2 正式版

1.18.16.2 库
............

   - bpo-39649(1): Remove obsolete check for ‘__args__’ in
     bdb.Bdb.format_stack_entry.

   - bpo-39681(2): Fix a regression where the C pickle module wouldn’t
     allow unpickling from a file-like object that doesn’t expose a
     readinto() method.

   - bpo-39546(3): Fix a regression in *note ArgumentParser: 69e. where
     ‘allow_abbrev=False’ was ignored for long options that used a
     prefix character other than "-".

   - bpo-39432(4): Implement PEP-489 algorithm for non-ascii
     "PyInit_..."  symbol names in distutils to make it export the
     correct init symbol also on Windows.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39649

   (2) https://bugs.python.org/issue39681

   (3) https://bugs.python.org/issue39546

   (4) https://bugs.python.org/issue39432


File: python.info,  Node: 文档<13>,  Next: IDLE<13>,  Prev: 库<15>,  Up: Python 3 8 2 正式版

1.18.16.3 文档
..............

   - bpo-17422(1): The language reference now specifies restrictions on
     class namespaces.  Adapted from a patch by Ethan Furman.

   - bpo-39572(2): Updated documentation of ‘total’ flag of TypeDict.

   - bpo-39654(3): In pyclbr doc, update ’class’ to ’module’ where
     appropriate and add readmodule comment.  Patch by Hakan Çelik.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17422

   (2) https://bugs.python.org/issue39572

   (3) https://bugs.python.org/issue39654


File: python.info,  Node: IDLE<13>,  Prev: 文档<13>,  Up: Python 3 8 2 正式版

1.18.16.4 IDLE
..............

   - bpo-39663(1): Add tests for pyparse find_good_parse_start().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39663


File: python.info,  Node: Python 3 8 2 rc2,  Next: Python 3 8 2 rc1,  Prev: Python 3 8 2 正式版,  Up: 更新日志

1.18.17 Python 3.8.2 rc2
------------------------

`发布日期:: 2020-02-17'

* Menu:

* 安全: 安全<11>.
* 核心与内置: 核心与内置<16>.
* 库: 库<16>.
* IDLE: IDLE<14>.


File: python.info,  Node: 安全<11>,  Next: 核心与内置<16>,  Up: Python 3 8 2 rc2

1.18.17.1 安全
..............

   - bpo-39184(1): Add audit events to functions in *note fcntl: 7e,
     *note msvcrt: b7, *note os: c5, *note resource: e1, *note shutil:
     ea, *note signal: eb. and *note syslog: 100.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39184


File: python.info,  Node: 核心与内置<16>,  Next: 库<16>,  Prev: 安全<11>,  Up: Python 3 8 2 rc2

1.18.17.2 核心与内置
....................

   - bpo-39619(1): Enable use of *note os.chroot(): f51. on HP-UX
     systems.

   - bpo-39606(2): Fix regression caused by fix for bpo-39386(3), that
     prevented calling ‘aclose’ on an async generator that had already
     been closed or exhausted.

   - bpo-39453(4): Fixed a possible crash in ‘list.__contains__()’ when
     a list is changed during comparing items.  Patch by Dong-hee Na.

   - bpo-39219(5): Syntax errors raised in the tokenizer now always set
     correct "text" and "offset" attributes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39619

   (2) https://bugs.python.org/issue39606

   (3) https://bugs.python.org/issue39386

   (4) https://bugs.python.org/issue39453

   (5) https://bugs.python.org/issue39219


File: python.info,  Node: 库<16>,  Next: IDLE<14>,  Prev: 核心与内置<16>,  Up: Python 3 8 2 rc2

1.18.17.3 库
............

   - bpo-27657(1): The original fix for bpo-27657(2), "Fix urlparse()
     with numeric paths" (GH-16839) included in 3.8.1, inadvertently
     introduced a behavior change that broke several third-party
     packages relying on the original undefined parsing behavior.  The
     change is reverted in 3.8.2, restoring the behavior of 3.8.0 and
     earlier releases.

   - bpo-39474(3): Fixed starting position of AST for expressions like
     ‘(a)(b)’, ‘(a)[b]’ and ‘(a).b’.

   - bpo-21016(4): The *note pydoc: da. and *note trace: 113. modules
     now use the *note sysconfig: ff. module to get the path to the
     Python standard library, to support uncommon installation path like
     ‘/usr/lib64/python3.9/’ on Fedora.  Patch by Jan Matějek.

   - bpo-39595(5): Improved performance of zipfile.Path for files with a
     large number of entries.  Also improved performance and fixed minor
     issue as published with importlib_metadata 1.5(6).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27657

   (2) https://bugs.python.org/issue27657

   (3) https://bugs.python.org/issue39474

   (4) https://bugs.python.org/issue21016

   (5) https://bugs.python.org/issue39595

   (6) 
https://importlib-metadata.readthedocs.io/en/latest/changelog%20(links).html#v1-5-0


File: python.info,  Node: IDLE<14>,  Prev: 库<16>,  Up: Python 3 8 2 rc2

1.18.17.4 IDLE
..............

   - bpo-39600(1): In the font configuration window, remove duplicated
     font names.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39600


File: python.info,  Node: Python 3 8 2 rc1,  Next: Python 3 8 1 正式版,  Prev: Python 3 8 2 rc2,  Up: 更新日志

1.18.18 Python 3.8.2 rc1
------------------------

`发布日期:: 2020-02-10'

* Menu:

* 安全: 安全<12>.
* 核心与内置: 核心与内置<17>.
* 库: 库<17>.
* 文档: 文档<14>.
* 测试: 测试<8>.
* 构建: 构建<8>.
* Windows: Windows<10>.
* IDLE: IDLE<15>.


File: python.info,  Node: 安全<12>,  Next: 核心与内置<17>,  Up: Python 3 8 2 rc1

1.18.18.1 安全
..............

   - bpo-39401(1): Avoid unsafe load of
     ‘api-ms-win-core-path-l1-1-0.dll’ at startup on Windows 7.

   - bpo-39184(2): Add audit events to command execution functions in os
     and pty modules.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39401

   (2) https://bugs.python.org/issue39184


File: python.info,  Node: 核心与内置<17>,  Next: 库<17>,  Prev: 安全<12>,  Up: Python 3 8 2 rc1

1.18.18.2 核心与内置
....................

   - bpo-39579(1): Change the ending column offset of ‘Attribute’ nodes
     constructed in ‘ast_for_dotted_name’ to point at the end of the
     current node and not at the end of the last ‘NAME’ node.

   - bpo-39510(2): Fix segfault in ‘readinto()’ method on closed
     BufferedReader.

   - bpo-39492(3): Fix a reference cycle in the C Pickler that was
     preventing the garbage collection of deleted, pickled objects.

   - bpo-39421(4): Fix possible crashes when operating with the
     functions in the *note heapq: 8e. module and custom comparison
     operators.

   - bpo-39386(5): Prevent double awaiting of async iterator.

   - bpo-39235(6): Fix AST end location for lone generator expression in
     function call, e.g.  f(i for i in a).

   - bpo-39209(7): Correctly handle multi-line tokens in interactive
     mode.  Patch by Pablo Galindo.

   - bpo-39216(8): Fix constant folding optimization for positional only
     arguments - by Anthony Sottile.

   - bpo-39215(9): Fix ‘SystemError’ when nested function has annotation
     on positional-only argument - by Anthony Sottile.

   - bpo-38588(10): Fix possible crashes in dict and list when calling
     *note PyObject_RichCompareBool(): f57.

   - bpo-38610(11): Fix possible crashes in several list methods by
     holding strong references to list elements when calling *note
     PyObject_RichCompareBool(): f57.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39579

   (2) https://bugs.python.org/issue39510

   (3) https://bugs.python.org/issue39492

   (4) https://bugs.python.org/issue39421

   (5) https://bugs.python.org/issue39386

   (6) https://bugs.python.org/issue39235

   (7) https://bugs.python.org/issue39209

   (8) https://bugs.python.org/issue39216

   (9) https://bugs.python.org/issue39215

   (10) https://bugs.python.org/issue38588

   (11) https://bugs.python.org/issue38610


File: python.info,  Node: 库<17>,  Next: 文档<14>,  Prev: 核心与内置<17>,  Up: Python 3 8 2 rc1

1.18.18.3 库
............

   - bpo-39590(1): Collections.deque now holds strong references during
     deque.__contains__ and deque.count, fixing crashes.

   - bpo-38149(2): *note sys.audit(): f38. is now called only once per
     call of *note glob.glob(): 5cf. and *note glob.iglob(): 5d0.

   - bpo-39450(3): Striped whitespace from docstring before returning it
     from ‘unittest.case.shortDescription()’.

   - bpo-39493(4): Mark ‘typing.IO.closed’ as a property

   - bpo-39485(5): Fix a bug in *note unittest.mock.create_autospec():
     f59. that would complain about the wrong number of arguments for
     custom descriptors defined in an extension module returning
     functions.

   - bpo-39082(6): Allow AsyncMock to correctly patch static/class
     methods

   - bpo-39430(7): Fixed race condition in lazy imports in *note
     tarfile: 102.

   - bpo-39390(8): Fixed a regression with the ‘ignore’ callback of
     *note shutil.copytree(): 21b.  The argument types are now str and
     List[str] again.

   - bpo-39389(9): Write accurate compression level metadata in *note
     gzip: 8c. archives, rather than always signaling maximum
     compression.

   - bpo-39274(10): ‘bool(fraction.Fraction)’ now returns a boolean even
     if (numerator != 0) does not return a boolean (ex: numpy number).

   - bpo-39297(11): Improved performance of importlib.metadata
     distribution discovery and resilients to inaccessible sys.path
     entries (importlib_metadata v1.4.0).

   - bpo-39242(12): Updated the Gmane domain from news.gmane.org to
     news.gmane.io which is used for examples of *note NNTP: a34. news
     reader server and nntplib tests.

   - bpo-38907(13): In http.server script, restore binding to IPv4 on
     Windows.

   - bpo-39152(14): Fix ttk.Scale.configure([name]) to return
     configuration tuple for name or all options.  Giovanni Lombardo
     contributed part of the patch.

   - bpo-39198(15): If an exception were to be thrown in
     ‘Logger.isEnabledFor’ (say, by asyncio timeouts or stopit) , the
     *note logging: ab. global lock may not be released appropriately,
     resulting in deadlock.  This change wraps that block of code with
     ‘try...finally’ to ensure the lock is released.

   - bpo-39191(16): Perform a check for running loop before starting a
     new task in ‘loop.run_until_complete()’ to fail fast; it prevents
     the side effect of new task spawning before exception raising.

   - bpo-38871(17): Correctly parenthesize filter-based statements that
     contain lambda expressions in mod:*note lib2to3: a8.  Patch by
     Dong-hee Na.

   - bpo-39142(18): A change was made to logging.config.dictConfig to
     avoid converting instances of named tuples to ConvertingTuple.
     It’s assumed that named tuples are too specialised to be treated
     like ordinary tuples; if a user of named tuples requires
     ConvertingTuple functionality, they will have to implement that
     themselves in their named tuple class.

   - bpo-39129(19): Fix import path for ‘asyncio.TimeoutError’

   - bpo-39057(20): ‘urllib.request.proxy_bypass_environment()’ now
     ignores leading dots and no longer ignores a trailing newline.

   - bpo-39056(21): Fixed handling invalid warning category in the -W
     option.  No longer import the re module if it is not needed.

   - bpo-39055(22): *note base64.b64decode(): f5a. with ‘validate=True’
     raises now a binascii.Error if the input ends with a single ‘\n’.

   - bpo-39033(23): Fix *note NameError: d83. in *note zipimport: 144.
     Patch by Karthikeyan Singaravelan.

   - bpo-38878(24): Fixed __subclasshook__ of *note os.PathLike: 4f3. to
     return a correct result upon inheritence.  Patch by Bar Harel.

   - bpo-35182(25): Fixed ‘Popen.communicate()’ subsequent call crash
     when the child process has already closed any piped standard
     stream, but still continues to be running.  Patch by Andriy
     Maletsky.

   - bpo-38473(26): Use signature from inner mock for autospecced
     methods attached with ‘unittest.mock.attach_mock()’.  Patch by
     Karthikeyan Singaravelan.

   - bpo-38293(27): Add *note copy.copy(): 3d3. and *note
     copy.deepcopy(): 3d4. support to *note property(): 1d8. objects.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39590

   (2) https://bugs.python.org/issue38149

   (3) https://bugs.python.org/issue39450

   (4) https://bugs.python.org/issue39493

   (5) https://bugs.python.org/issue39485

   (6) https://bugs.python.org/issue39082

   (7) https://bugs.python.org/issue39430

   (8) https://bugs.python.org/issue39390

   (9) https://bugs.python.org/issue39389

   (10) https://bugs.python.org/issue39274

   (11) https://bugs.python.org/issue39297

   (12) https://bugs.python.org/issue39242

   (13) https://bugs.python.org/issue38907

   (14) https://bugs.python.org/issue39152

   (15) https://bugs.python.org/issue39198

   (16) https://bugs.python.org/issue39191

   (17) https://bugs.python.org/issue38871

   (18) https://bugs.python.org/issue39142

   (19) https://bugs.python.org/issue39129

   (20) https://bugs.python.org/issue39057

   (21) https://bugs.python.org/issue39056

   (22) https://bugs.python.org/issue39055

   (23) https://bugs.python.org/issue39033

   (24) https://bugs.python.org/issue38878

   (25) https://bugs.python.org/issue35182

   (26) https://bugs.python.org/issue38473

   (27) https://bugs.python.org/issue38293


File: python.info,  Node: 文档<14>,  Next: 测试<8>,  Prev: 库<17>,  Up: Python 3 8 2 rc1

1.18.18.4 文档
..............

   - bpo-39153(1): Clarify refcounting semantics for the following
     functions: - PyObject_SetItem - PyMapping_SetItemString -
     PyDict_SetItem - PyDict_SetItemString

   - bpo-39392(2): Explain that when filling with turtle, overlap
     regions may be left unfilled.

   - bpo-39381(3): Mention in docs that *note asyncio.get_event_loop():
     35e. implicitly creates new event loop only if called from the main
     thread.

   - bpo-38918(4): Add an entry for ‘__module__’ in the "function" &
     "method" sections of the inspect docs types and members table(5)

   - bpo-3530(6): In the *note ast: 8. module documentation, fix a
     misleading ‘NodeTransformer’ example and add advice on when to use
     the ‘fix_missing_locations’ function.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39153

   (2) https://bugs.python.org/issue39392

   (3) https://bugs.python.org/issue39381

   (4) https://bugs.python.org/issue38918

   (5) https://docs.python.org/3/library/inspect.html#types-and-members

   (6) https://bugs.python.org/issue3530


File: python.info,  Node: 测试<8>,  Next: 构建<8>,  Prev: 文档<14>,  Up: Python 3 8 2 rc1

1.18.18.5 测试
..............

   - bpo-39502(1): Skip test_zipfile.test_add_file_after_2107() if *note
     time.localtime(): f5d. fails with *note OverflowError: 968.  It is
     the case on AIX 6.1 for example.

   - bpo-38546(2): Fix test_ressources_gced_in_workers() of
     test_concurrent_futures: explicitly stop the manager to prevent
     leaking a child process running in the background after the test
     completes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39502

   (2) https://bugs.python.org/issue38546


File: python.info,  Node: 构建<8>,  Next: Windows<10>,  Prev: 测试<8>,  Up: Python 3 8 2 rc1

1.18.18.6 构建
..............

   - bpo-39144(1): The ctags and etags build targets both include
     Modules/_ctypes and Python standard library source files.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39144


File: python.info,  Node: Windows<10>,  Next: IDLE<15>,  Prev: 构建<8>,  Up: Python 3 8 2 rc1

1.18.18.7 Windows
.................

   - bpo-39439(1): Honor the Python path when a virtualenv is active on
     Windows.

   - bpo-39393(2): Improve the error message when attempting to load a
     DLL with unresolved dependencies.

   - bpo-38883(3): *note home(): 734. and *note expanduser(): 733. on
     Windows now prefer ‘USERPROFILE’ and no longer use ‘HOME’, which is
     not normally set for regular user accounts.  This makes them again
     behave like *note os.path.expanduser(): 1ff, which was changed to
     ignore ‘HOME’ in 3.8, see bpo-36264(4).

   - bpo-39185(5): The build.bat script has additional options for
     very-quiet output (-q) and very-verbose output (-vv)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39439

   (2) https://bugs.python.org/issue39393

   (3) https://bugs.python.org/issue38883

   (4) https://bugs.python.org/issue36264

   (5) https://bugs.python.org/issue39185


File: python.info,  Node: IDLE<15>,  Prev: Windows<10>,  Up: Python 3 8 2 rc1

1.18.18.8 IDLE
..............

   - bpo-30780(1): Add remaining configdialog tests for buttons and
     highlights and keys tabs.

   - bpo-39388(2): IDLE Settings Cancel button now cancels pending
     changes

   - bpo-39050(3): Make IDLE Settings dialog Help button work again.

   - bpo-34118(4): Tag memoryview, range, and tuple as classes, the same
     as list, etcetera, in the library manual built-in functions list.

   - bpo-38792(5): Close an IDLE shell calltip if a *note
     KeyboardInterrupt: 198. or shell restart occurs.  Patch by Zackery
     Spytz.

   - bpo-32989(6): Add tests for editor newline_and_indent_event method.
     Remove dead code from pyparse find_good_parse_start method.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30780

   (2) https://bugs.python.org/issue39388

   (3) https://bugs.python.org/issue39050

   (4) https://bugs.python.org/issue34118

   (5) https://bugs.python.org/issue38792

   (6) https://bugs.python.org/issue32989


File: python.info,  Node: Python 3 8 1 正式版,  Next: Python 3 8 1 rc1,  Prev: Python 3 8 2 rc1,  Up: 更新日志

1.18.19 Python 3.8.1 正式版
---------------------------

`发布日期: 2019-12-18'

* Menu:

* 核心与内置: 核心与内置<18>.
* 库: 库<18>.
* 测试: 测试<9>.
* Windows: Windows<11>.
* macOS: macOS<9>.
* IDLE: IDLE<16>.


File: python.info,  Node: 核心与内置<18>,  Next: 库<18>,  Up: Python 3 8 1 正式版

1.18.19.1 核心与内置
....................

   - bpo-39080(1): Fix the value of `end_col_offset' for Starred
     Expression AST nodes when they are among the elements in the `args'
     attribute of Call AST nodes.

   - bpo-39031(2): When parsing an "elif" node, lineno and col_offset of
     the node now point to the "elif" keyword and not to its condition,
     making it consistent with the "if" node.  Patch by Lysandros
     Nikolaou.

   - bpo-39008(3): *note PySys_Audit(): f46. now requires ‘Py_ssize_t’
     to be used for size arguments in the format string, regardless of
     whether ‘PY_SSIZE_T_CLEAN’ was defined at include time.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39080

   (2) https://bugs.python.org/issue39031

   (3) https://bugs.python.org/issue39008


File: python.info,  Node: 库<18>,  Next: 测试<9>,  Prev: 核心与内置<18>,  Up: Python 3 8 1 正式版

1.18.19.2 库
............

   - bpo-39022(1): Update importlib.metadata to include improvements
     from importlib_metadata 1.3 including better serialization of
     EntryPoints and improved documentation for custom finders.

   - bpo-38811(2): Fix an unhandled exception in *note pathlib: c9. when
     *note os.link(): a3d. is missing.  Patch by Toke Høiland-Jørgensen.

   - bpo-36406(3): Handle namespace packages in *note doctest: 67.
     Patch by Karthikeyan Singaravelan.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39022

   (2) https://bugs.python.org/issue38811

   (3) https://bugs.python.org/issue36406


File: python.info,  Node: 测试<9>,  Next: Windows<11>,  Prev: 库<18>,  Up: Python 3 8 1 正式版

1.18.19.3 测试
..............

   - bpo-38546(1): Multiprocessing and concurrent.futures tests now stop
     the resource tracker process when tests complete.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38546


File: python.info,  Node: Windows<11>,  Next: macOS<9>,  Prev: 测试<9>,  Up: Python 3 8 1 正式版

1.18.19.4 Windows
.................

   - bpo-39007(1): Add auditing events to functions in *note winreg:
     12b.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39007


File: python.info,  Node: macOS<9>,  Next: IDLE<16>,  Prev: Windows<11>,  Up: Python 3 8 1 正式版

1.18.19.5 macOS
...............

   - bpo-38295(1): Prevent failure of test_relative_path in
     test_py_compile on macOS Catalina.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38295


File: python.info,  Node: IDLE<16>,  Prev: macOS<9>,  Up: Python 3 8 1 正式版

1.18.19.6 IDLE
..............

   - bpo-38944(1): Escape key now closes IDLE completion windows.  Patch
     by Johnny Najera.

   - bpo-38943(2): Fix IDLE autocomplete windows not always appearing on
     some systems.  Patch by Johnny Najera.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38944

   (2) https://bugs.python.org/issue38943


File: python.info,  Node: Python 3 8 1 rc1,  Next: Python 3 8 0 正式版,  Prev: Python 3 8 1 正式版,  Up: 更新日志

1.18.20 Python 3.8.1 rc1
------------------------

`发布日期: 2019-12-09'

* Menu:

* 安全: 安全<13>.
* 核心与内置: 核心与内置<19>.
* 库: 库<19>.
* 文档: 文档<15>.
* 测试: 测试<10>.
* 构建: 构建<9>.
* Windows: Windows<12>.
* macOS: macOS<10>.
* IDLE: IDLE<17>.
* C API: C API<7>.


File: python.info,  Node: 安全<13>,  Next: 核心与内置<19>,  Up: Python 3 8 1 rc1

1.18.20.1 安全
..............

   - bpo-38945(1): Newline characters have been escaped when performing
     uu encoding to prevent them from overflowing into to content
     section of the encoded file.  This prevents malicious or accidental
     modification of data during the decoding process.

   - bpo-37228(2): Due to significant security concerns, the
     `reuse_address' parameter of *note
     asyncio.loop.create_datagram_endpoint(): 2e8. is no longer
     supported.  This is because of the behavior of ‘SO_REUSEADDR’ in
     UDP. For more details, see the documentation for
     ‘loop.create_datagram_endpoint()’.  (Contributed by Kyle Stanley,
     Antoine Pitrou, and Yury Selivanov in bpo-37228(3).)

   - bpo-38722(4): *note runpy: e3. now uses *note io.open_code(): f32.
     to open code files.  Patch by Jason Killen.

   - bpo-38804(5): Fixes a ReDoS vulnerability in *note http.cookiejar:
     95.  Patch by Ben Caller.

   - bpo-38622(6): Add additional audit events for the *note ctypes: 2b.
     module.

   - bpo-38418(7): 修复 *note os.system(): dc9. 的审计事件被命名为
     ‘os.system’ 。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38945

   (2) https://bugs.python.org/issue37228

   (3) https://bugs.python.org/issue37228

   (4) https://bugs.python.org/issue38722

   (5) https://bugs.python.org/issue38804

   (6) https://bugs.python.org/issue38622

   (7) https://bugs.python.org/issue38418


File: python.info,  Node: 核心与内置<19>,  Next: 库<19>,  Prev: 安全<13>,  Up: Python 3 8 1 rc1

1.18.20.2 核心与内置
....................

   - bpo-38673(1): In REPL mode, don’t switch to PS2 if the line starts
     with comment or whitespace.  Based on work by Batuhan Taşkaya.

   - bpo-38922(2): Calling ‘replace’ on a code object now raises the
     ‘code.__new__’ audit event.

   - bpo-38920(3): Add audit hooks for when *note sys.excepthook(): e6b.
     and *note sys.unraisablehook(): 22e. are invoked

   - bpo-38892(4): Improve documentation for audit events table and
     functions.

   - bpo-38707(5): ‘MainThread.native_id’ is now correctly reset in
     child processes spawned using *note multiprocessing.Process: 3ba,
     instead of retaining the parent’s value.

   - bpo-38640(6): Fixed a bug in the compiler that was causing to raise
     in the presence of break statements and continue statements inside
     always false while loops.  Patch by Pablo Galindo.

   - bpo-38535(7): 修复了装饰器中不带参数调用的AST节点的行号和列偏移量。

   - bpo-38525(8): 修复了使用空 ‘dict’ 对象的反向迭代器时的分段错误。由
     Dong-hee Na 和 Inada Naoki 补丁修复

   - bpo-35409(9): Ignore GeneratorExit exceptions when throwing an
     exception into the aclose coroutine of an asynchronous generator.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38673

   (2) https://bugs.python.org/issue38922

   (3) https://bugs.python.org/issue38920

   (4) https://bugs.python.org/issue38892

   (5) https://bugs.python.org/issue38707

   (6) https://bugs.python.org/issue38640

   (7) https://bugs.python.org/issue38535

   (8) https://bugs.python.org/issue38525

   (9) https://bugs.python.org/issue35409


File: python.info,  Node: 库<19>,  Next: 文档<15>,  Prev: 核心与内置<19>,  Up: Python 3 8 1 rc1

1.18.20.3 库
............

   - bpo-39006(1): Fix asyncio when the ssl module is missing: only
     check for ssl.SSLSocket instance if the ssl module is available.

   - bpo-38708(2): Fix a potential IndexError in email parser when
     parsing an empty msg-id.

   - bpo-38698(3): Add a new ‘InvalidMessageID’ token to email parser to
     represent invalid Message-ID headers.  Also, add defects when there
     is remaining value after parsing the header.

   - bpo-38979(4): Return class from ‘ContextVar.__class_getitem__’ to
     simplify subclassing.

   - bpo-38986(5): Make repr of C accelerated TaskWakeupMethWrapper the
     same as of pure Python version.

   - bpo-38529(6): Drop too noisy asyncio warning about deletion of a
     stream without explicit ‘.close()’ call.

   - bpo-38634(7): The *note readline: df. module now detects if Python
     is linked to libedit at runtime on all platforms.  Previously, the
     check was only done on macOS.

   - bpo-33684(8): Fix ‘json.tool’ failed to read a JSON file with
     non-ASCII characters when locale encoding is not UTF-8.

   - bpo-38698(9): Prevent UnboundLocalError to pop up in
     parse_message_id

     parse_message_id() was improperly using a token defined inside an
     exception handler, which was raising *note UnboundLocalError: e7e.
     on parsing an invalid value.  Patch by Claudiu Popa.

   - bpo-26730(10): Fix ‘SpooledTemporaryFile.rollover()’ might corrupt
     the file when it is in text mode.  Patch by Serhiy Storchaka.

   - bpo-38668(11): Calling func:*note shutil.copytree: 21b. to copy a
     directory tree from one directory to another subdirectory resulted
     in an endless loop and a RecursionError.  A fix was added to
     consume an iterator and create the list of the entries to be
     copied, avoiding the recursion for newly created directories.
     Patch by Bruno P. Kinoshita.

   - bpo-37838(12): *note typing.get_type_hints(): 313. properly handles
     functions decorated with *note functools.wraps(): 873.

   - bpo-38859(13): AsyncMock now returns StopAsyncIteration on the
     exaustion of a side_effects iterable.  Since PEP-479 its Impossible
     to raise a StopIteration exception from a coroutine.

   - bpo-38857(14): AsyncMock fix for return values that are awaitable
     types.  This also covers side_effect iterable values that happend
     to be awaitable, and wraps callables that return an awaitable type.
     Before these awaitables were being awaited instead of being
     returned as is.

   - bpo-38821(15): Fix unhandled exceptions in *note argparse: 6. when
     internationalizing error messages for arguments with ‘nargs’ set to
     special (non-integer) values.  Patch by Federico Bond.

   - bpo-38820(16): Make Python compatible with OpenSSL 3.0.0.  *note
     ssl.SSLSocket.getpeercert(): 8d9. no longer returns IPv6 addresses
     with a trailing new line.

   - bpo-38807(17): Update *note TypeError: 193. messages for *note
     os.path.join(): f6c. to include *note os.PathLike: 4f3. objects as
     acceptable input types.

   - bpo-38785(18): Prevent asyncio from crashing if parent ‘__init__’
     is not called from a constructor of object derived from
     ‘asyncio.Future’.

   - bpo-38723(19): *note pdb: ca. now uses *note io.open_code(): f32.
     to trigger auditing events.

   - bpo-27805(20): Allow opening pipes and other non-seekable files in
     append mode with *note open(): 4f8.

   - bpo-38686(21): Added support for multiple ‘qop’ values in *note
     urllib.request.AbstractDigestAuthHandler: f37.

   - bpo-38334(22): 修复了在加密的 ‘zipfile.ZipExtFile’ 上向后搜索的问题
     。

   - bpo-34679(23): asynci.ProactorEventLoop.close() 现在仅调用主线程中
     的 signal.set_wakeup_fd()

   - bpo-31202(24): ‘pathlib.WindowsPath.glob()’ 的结果现在与文本部分的
     式样匹配。

   - bpo-38521(25): Fixed erroneous equality comparison in
     statistics.NormalDist().

   - bpo-38478(26): Fixed a bug in ‘inspect.signature.bind()’ that was
     causing it to fail when handling a keyword argument with same name
     as positional-only parameter.  Patch by Pablo Galindo.

   - bpo-33604(27): Fixed *note hmac.new: 85d. and ‘hmac.HMAC’ to raise
     TypeError instead of ValueError when the digestmod parameter, now
     required in 3.8, is omitted.  Also clarified the hmac module
     documentation and docstrings.

   - bpo-38422(28): Clarify docstrings of pathlib suffix(es)

   - bpo-36993(29): Improve error reporting for corrupt zip files with
     bad zip64 extra data.  Patch by Daniel Hillier.

   - bpo-36820(30): Break cycle generated when saving an exception in
     socket.py, codeop.py and dyld.py as they keep alive not only the
     exception but user objects through the ‘__traceback__’ attribute.
     Patch by Mario Corchero.

   - bpo-34776(31): Fix dataclasses to support forward references in
     type annotations

   - bpo-33348(32): lib2to3 now recognizes expressions after ‘*’ and
     ‘**’ like in ‘f(*[] or [])’.

   - bpo-27657(33): Fix urllib.parse.urlparse() with numeric paths.  A
     string like "path:80" is no longer parsed as a path but as a scheme
     ("path") and a path ("80").

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39006

   (2) https://bugs.python.org/issue38708

   (3) https://bugs.python.org/issue38698

   (4) https://bugs.python.org/issue38979

   (5) https://bugs.python.org/issue38986

   (6) https://bugs.python.org/issue38529

   (7) https://bugs.python.org/issue38634

   (8) https://bugs.python.org/issue33684

   (9) https://bugs.python.org/issue38698

   (10) https://bugs.python.org/issue26730

   (11) https://bugs.python.org/issue38668

   (12) https://bugs.python.org/issue37838

   (13) https://bugs.python.org/issue38859

   (14) https://bugs.python.org/issue38857

   (15) https://bugs.python.org/issue38821

   (16) https://bugs.python.org/issue38820

   (17) https://bugs.python.org/issue38807

   (18) https://bugs.python.org/issue38785

   (19) https://bugs.python.org/issue38723

   (20) https://bugs.python.org/issue27805

   (21) https://bugs.python.org/issue38686

   (22) https://bugs.python.org/issue38334

   (23) https://bugs.python.org/issue34679

   (24) https://bugs.python.org/issue31202

   (25) https://bugs.python.org/issue38521

   (26) https://bugs.python.org/issue38478

   (27) https://bugs.python.org/issue33604

   (28) https://bugs.python.org/issue38422

   (29) https://bugs.python.org/issue36993

   (30) https://bugs.python.org/issue36820

   (31) https://bugs.python.org/issue34776

   (32) https://bugs.python.org/issue33348

   (33) https://bugs.python.org/issue27657


File: python.info,  Node: 文档<15>,  Next: 测试<10>,  Prev: 库<19>,  Up: Python 3 8 1 rc1

1.18.20.4 文档
..............

   - bpo-38816(1): Provides more details about the interaction between
     ‘fork()’ and CPython’s runtime, focusing just on the C-API. This
     includes cautions about where ‘fork()’ should and shouldn’t be
     called.

   - bpo-38351(2): Modernize *note email: 69. examples from %-formatting
     to f-strings.

   - bpo-38778(3): Document the fact that *note RuntimeError: 2bb. is
     raised if *note os.fork(): 969. is called in a subinterpreter.

   - bpo-38592(4): Add Brazilian Portuguese to the language switcher at
     Python Documentation website.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38816

   (2) https://bugs.python.org/issue38351

   (3) https://bugs.python.org/issue38778

   (4) https://bugs.python.org/issue38592


File: python.info,  Node: 测试<10>,  Next: 构建<9>,  Prev: 文档<15>,  Up: Python 3 8 1 rc1

1.18.20.5 测试
..............

   - bpo-38547(1): Fix test_pty: if the process is the session leader,
     closing the master file descriptor raises a SIGHUP signal: simply
     ignore SIGHUP when running the tests.

   - bpo-38992(2): Fix a test for *note math.fsum(): d46. that was
     failing due to constant folding.

   - bpo-38965(3): Fix test_faulthandler on GCC 10.  Use the "volatile"
     keyword in ‘faulthandler._stack_overflow()’ to prevent tail call
     optimization on any compiler, rather than relying on compiler
     specific pragma.

   - bpo-38875(4): test_capi: trashcan tests now require the test "cpu"
     resource.

   - bpo-38841(5): Skip asyncio
     test_create_datagram_endpoint_existing_sock_unix on platforms
     lacking a functional bind() for named unix domain sockets.

   - bpo-38669(6): Raise *note TypeError: 193. when passing target as a
     string with *note unittest.mock.patch.object(): f6f.

   - bpo-35998(7): Fix a race condition in
     test_asyncio.test_start_tls_server_1().  Previously, there was a
     race condition between the test main() function which replaces the
     protocol and the test ServerProto protocol which sends ANSWER once
     it gets HELLO. Now, only the test main() function is responsible to
     send data, ServerProto no longer sends data.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38547

   (2) https://bugs.python.org/issue38992

   (3) https://bugs.python.org/issue38965

   (4) https://bugs.python.org/issue38875

   (5) https://bugs.python.org/issue38841

   (6) https://bugs.python.org/issue38669

   (7) https://bugs.python.org/issue35998


File: python.info,  Node: 构建<9>,  Next: Windows<12>,  Prev: 测试<10>,  Up: Python 3 8 1 rc1

1.18.20.6 构建
..............

   - bpo-37404(1): *note asyncio: a. now raises ‘TyperError’ when
     calling incompatible methods with an *note ssl.SSLSocket: 3ea.
     socket.  Patch by Ido Michael.

   - bpo-38809(2): On Windows, build scripts will now recognize and use
     python.exe from an active virtual env.

   - bpo-38684(3): Fix _hashlib build when Blake2 is disabled, but
     OpenSSL supports it.

   - bpo-37415(4): Fix stdatomic.h header check for ICC compiler: the
     ICC implementation lacks atomic_uintptr_t type which is needed by
     Python.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37404

   (2) https://bugs.python.org/issue38809

   (3) https://bugs.python.org/issue38684

   (4) https://bugs.python.org/issue37415


File: python.info,  Node: Windows<12>,  Next: macOS<10>,  Prev: 构建<9>,  Up: Python 3 8 1 rc1

1.18.20.7 Windows
.................

   - bpo-33125(1): Add support for building and releasing Windows ARM64
     packages.

   - bpo-38589(2): Fixes HTML Help shortcut when Windows is not
     installed to C drive

   - bpo-38453(3): Ensure ntpath.realpath() correctly resolves relative
     paths.

   - bpo-38519(4): Restores the internal C headers that were missing
     from the nuget.org and Microsoft Store packages.

   - bpo-38492(5): 删除 pythonw.exe 依赖的 Microsoft C++ 执行库。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33125

   (2) https://bugs.python.org/issue38589

   (3) https://bugs.python.org/issue38453

   (4) https://bugs.python.org/issue38519

   (5) https://bugs.python.org/issue38492


File: python.info,  Node: macOS<10>,  Next: IDLE<17>,  Prev: Windows<12>,  Up: Python 3 8 1 rc1

1.18.20.8 macOS
...............

   - bpo-37931(1): Fixed a crash on OSX dynamic builds that occurred
     when re-initializing the posix module after a Py_Finalize if the
     environment had changed since the previous ‘import posix’.  Patch
     by Benoît Hudson.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37931


File: python.info,  Node: IDLE<17>,  Next: C API<7>,  Prev: macOS<10>,  Up: Python 3 8 1 rc1

1.18.20.9 IDLE
..............

   - bpo-38862(1): ’Strip Trailing Whitespace’ on the Format menu
     removes extra newlines at the end of non-shell files.

   - bpo-26353(2): Stop adding newline when saving an IDLE shell window.

   - bpo-38636(3): Fix IDLE Format menu tab toggle and file indent
     width.  These functions (default shortcuts Alt-T and Alt-U) were
     mistakenly disabled in 3.7.5 and 3.8.0.

   - bpo-4630(4): Add an option to toggle IDLE’s cursor blink for shell,
     editor, and output windows.  See Settings, General, Window
     Preferences, Cursor Blink.  Patch by Zackery Spytz.

   - bpo-38598(5): Do not try to compile IDLE shell or output windows

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38862

   (2) https://bugs.python.org/issue26353

   (3) https://bugs.python.org/issue38636

   (4) https://bugs.python.org/issue4630

   (5) https://bugs.python.org/issue38598


File: python.info,  Node: C API<7>,  Prev: IDLE<17>,  Up: Python 3 8 1 rc1

1.18.20.10 C API
................

   - bpo-37633(1): Re-export some function compatibility wrappers for
     macros in ‘pythonrun.h’.

   - bpo-38540(2): Fixed possible leak in *note PyArg_Parse(): f75. and
     similar functions for format units ‘"es#"’ and ‘"et#"’ when the
     macro ‘PY_SSIZE_T_CLEAN’ is not defined.

   - bpo-36389(3): The ‘_PyObject_CheckConsistency()’ function is now
     also available in release mode.  For example, it can be used to
     debug a crash in the ‘visit_decref()’ function of the GC.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37633

   (2) https://bugs.python.org/issue38540

   (3) https://bugs.python.org/issue36389


File: python.info,  Node: Python 3 8 0 正式版,  Next: Python 3 8 0 rc1,  Prev: Python 3 8 1 rc1,  Up: 更新日志

1.18.21 Python 3.8.0 正式版
---------------------------

`发布日期: 2019-10-14'

* Menu:

* 核心与内置: 核心与内置<20>.
* 库: 库<20>.
* 文档: 文档<16>.
* 测试: 测试<11>.
* Windows: Windows<13>.
* IDLE: IDLE<18>.
* 工具/示例: 工具/示例<5>.
* C API: C API<8>.


File: python.info,  Node: 核心与内置<20>,  Next: 库<20>,  Up: Python 3 8 0 正式版

1.18.21.1 核心与内置
....................

   - bpo-38469(1): Fixed a bug where the scope of named expressions was
     not being resolved correctly in the presence of the `global'
     keyword.  Patch by Pablo Galindo.

   - bpo-38379(2): When cyclic garbage collection (gc) runs finalizers
     that resurrect unreachable objects, the current gc run ends,
     without collecting any cyclic trash.  However, the statistics
     reported by ‘collect()’ and ‘get_stats()’ claimed that all cyclic
     trash found was collected, and that the resurrected objects were
     collected.  Changed the stats to report that none were collected.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38469

   (2) https://bugs.python.org/issue38379


File: python.info,  Node: 库<20>,  Next: 文档<16>,  Prev: 核心与内置<20>,  Up: Python 3 8 0 正式版

1.18.21.2 库
............

   - bpo-38449(1): Revert GH-15522, which introduces a regression in
     *note mimetypes.guess_type(): f79. due to improper handling of
     filenames as urls.

   - bpo-38431(2): Fix ‘__repr__’ method for ‘dataclasses.InitVar’ to
     support typing objects, patch by Samuel Colvin.

   - bpo-38109(3): Add missing *note stat.S_IFDOOR: 8dc, *note
     stat.S_IFPORT: 8dd, *note stat.S_IFWHT: 8de, *note stat.S_ISDOOR():
     f7a, *note stat.S_ISPORT(): f7b, and *note stat.S_ISWHT(): f7c.
     values to the Python implementation of *note stat: f5.

   - bpo-38405(4): Nested subclasses of *note typing.NamedTuple: 281.
     are now pickleable.

   - bpo-38332(5): Prevent *note KeyError: 2c8. thrown by
     ‘_encoded_words.decode()’ when given an encoded-word with invalid
     content-type encoding from propagating all the way to
     ‘email.message.get()’.

   - bpo-38341(6): Add *note smtplib.SMTPNotSupportedError: f7d. to the
     *note smtplib: ee. exported names.

   - bpo-13153(7): OS native encoding is now used for converting between
     Python strings and Tcl objects.  This allows to display, copy and
     paste to clipboard emoji and other non-BMP characters.  Converting
     strings from Tcl to Python and back now never fails (except
     MemoryError).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38449

   (2) https://bugs.python.org/issue38431

   (3) https://bugs.python.org/issue38109

   (4) https://bugs.python.org/issue38405

   (5) https://bugs.python.org/issue38332

   (6) https://bugs.python.org/issue38341

   (7) https://bugs.python.org/issue13153


File: python.info,  Node: 文档<16>,  Next: 测试<11>,  Prev: 库<20>,  Up: Python 3 8 0 正式版

1.18.21.3 文档
..............

   - bpo-38294(1): Add list of no-longer-escaped chars to re.escape
     documentation.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38294


File: python.info,  Node: 测试<11>,  Next: Windows<13>,  Prev: 文档<16>,  Up: Python 3 8 0 正式版

1.18.21.4 测试
..............

   - bpo-37531(1): On timeout, regrtest no longer attempts to call
     ‘popen.communicate()’ again: it can hang until all child processes
     using stdout and stderr pipes completes.  Kill the worker process
     and ignores its output.  Change also the faulthandler timeout of
     the main process from 1 minute to 5 minutes, for Python slowest
     buildbots.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37531


File: python.info,  Node: Windows<13>,  Next: IDLE<18>,  Prev: 测试<11>,  Up: Python 3 8 0 正式版

1.18.21.5 Windows
.................

   - bpo-38344(1): Fix error message in activate.bat.

   - bpo-38359(2): Ensures ‘pyw.exe’ launcher reads correct registry
     key.

   - bpo-38355(3): Fixes ‘ntpath.realpath’ failing on ‘sys.executable’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38344

   (2) https://bugs.python.org/issue38359

   (3) https://bugs.python.org/issue38355


File: python.info,  Node: IDLE<18>,  Next: 工具/示例<5>,  Prev: Windows<13>,  Up: Python 3 8 0 正式版

1.18.21.6 IDLE
..............

   - bpo-36698(1): IDLE no longer fails when write non-encodable
     characters to stderr.  It now escapes them with a backslash, as the
     regular Python interpreter.  Added the ‘errors’ field to the
     standard streams.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36698


File: python.info,  Node: 工具/示例<5>,  Next: C API<8>,  Prev: IDLE<18>,  Up: Python 3 8 0 正式版

1.18.21.7 工具/示例
...................

   - bpo-38118(1): Update Valgrind suppression file to ignore a false
     alarm in *note PyUnicode_Decode(): f83. when using GCC builtin
     strcmp().

   - bpo-38347(2): pathfix.py: Assume all files that end on ’.py’ are
     Python scripts when working recursively.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38118

   (2) https://bugs.python.org/issue38347


File: python.info,  Node: C API<8>,  Prev: 工具/示例<5>,  Up: Python 3 8 0 正式版

1.18.21.8 C API
...............

   - bpo-38395(1): Fix a crash in *note weakref.proxy: 251. objects due
     to incorrect lifetime management when calling some associated
     methods that may delete the last reference to object being
     referenced by the proxy.  Patch by Pablo Galindo.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38395


File: python.info,  Node: Python 3 8 0 rc1,  Next: Python 3 8 0 beta 4,  Prev: Python 3 8 0 正式版,  Up: 更新日志

1.18.22 Python 3.8.0 rc1
------------------------

`发布日期: 2019-10-01'

* Menu:

* 安全: 安全<14>.
* 核心与内置: 核心与内置<21>.
* 库: 库<21>.
* 文档: 文档<17>.
* 测试: 测试<12>.
* 构建: 构建<10>.
* Windows: Windows<14>.
* macOS: macOS<11>.
* IDLE: IDLE<19>.
* 工具/示例: 工具/示例<6>.
* C API: C API<9>.


File: python.info,  Node: 安全<14>,  Next: 核心与内置<21>,  Up: Python 3 8 0 rc1

1.18.22.1 安全
..............

   - bpo-38243(1): 在将文档页渲染为 HTML 时会对 *note
     xmlrpc.server.DocXMLRPCServer: f87. 的服务器标题进行转义。 （由
     Dong-hee Na 在 bpo-38243(2) 中贡献。）

   - bpo-38174(3): 将厂商化的 expat 库版本更新至 2.2.8，这解决了
     CVE-2019-15903。

   - bpo-37764(4): 修复了 email._header_value_parser.get_unstructured 在
     邮件头不包含末尾空格，以及在其包含无效的已编码字等特定情况下进入无
     限循环的问题。 由 Ashwin Ramaswami 贡献补丁。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38243

   (2) https://bugs.python.org/issue38243

   (3) https://bugs.python.org/issue38174

   (4) https://bugs.python.org/issue37764


File: python.info,  Node: 核心与内置<21>,  Next: 库<21>,  Prev: 安全<14>,  Up: Python 3 8 0 rc1

1.18.22.2 核心与内置
....................

   - bpo-38006(1): Fix a bug due to the interaction of weakrefs and the
     cyclic garbage collector.  We must clear any weakrefs in garbage in
     order to prevent their callbacks from executing and causing a
     crash.

   - bpo-38317(2): Fix warnings options priority: ‘PyConfig.warnoptions’
     has the highest priority, as stated in the PEP 587(3).

   - bpo-36871(4): 改进了 mock 的 assert_has_calls 和 assert_has_awaits
     方法的错误处理。 修复了一个漏洞，它会在将预期的调用绑定到 mock 的规
     格时静默接收所遇到的任何错误，从而产生误导性的错误输出。

   - bpo-38236(5): Python now dumps path configuration if it fails to
     import the Python codecs of the filesystem and stdio encodings.

   - bpo-38013(6): Allow to call ‘async_generator_athrow().throw(...)’
     even for non-started async generator helper.  It fixes annoying
     warning at the end of *note asyncio.run(): 1a6. call.

   - bpo-38124(7): Fix an off-by-one error in PyState_AddModule that
     could cause out-of-bounds memory access.

   - bpo-38005(8): 修复InterpreterID 和 ChannelID的创建和对比.

   - bpo-37994(9): Fixed silencing arbitrary errors if an attribute
     lookup fails in several sites.  Only AttributeError should be
     silenced.

   - bpo-37990(10): Fix elapsed time in gc stats was not printed
     correctly.  This bug was a regression in 3.8b4.

   - bpo-37966(11): The implementation of *note is_normalized(): 247.
     has been greatly sped up on strings that aren’t normalized, by
     implementing the full normalization-quick-check algorithm from the
     Unicode standard.

   - bpo-20490(12): Improve import error message for partially
     initialized module on circular ‘from’ imports - by Anthony Sottile.

   - bpo-37409(13): Ensure explicit relative imports from interactive
     sessions and scripts (having no parent package) always raise
     ImportError, rather than treating the current module as the
     package.  Patch by Ben Lewis.

   - bpo-37619(14): When adding a wrapper descriptor from one class to a
     different class (for example, setting ‘__add__ = str.__add__’ on an
     ‘int’ subclass), an exception is correctly raised when the operator
     is called.

   - bpo-30773(15): Prohibit parallel running of aclose() / asend() /
     athrow().  Fix ag_running to reflect the actual running status of
     the AG.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38006

   (2) https://bugs.python.org/issue38317

   (3) https://www.python.org/dev/peps/pep-0587

   (4) https://bugs.python.org/issue36871

   (5) https://bugs.python.org/issue38236

   (6) https://bugs.python.org/issue38013

   (7) https://bugs.python.org/issue38124

   (8) https://bugs.python.org/issue38005

   (9) https://bugs.python.org/issue37994

   (10) https://bugs.python.org/issue37990

   (11) https://bugs.python.org/issue37966

   (12) https://bugs.python.org/issue20490

   (13) https://bugs.python.org/issue37409

   (14) https://bugs.python.org/issue37619

   (15) https://bugs.python.org/issue30773


File: python.info,  Node: 库<21>,  Next: 文档<17>,  Prev: 核心与内置<21>,  Up: Python 3 8 0 rc1

1.18.22.3 库
............

   - bpo-38319(1): 修复 套接字 和 shutil 模块中使用的sendfile() 在
     32-bit 架构上会产生 OverflowError for files >= 2GiB .  (补丁由
     Giampaolo Rodola提供)

   - bpo-38242(2): 回滚新的 asyncio Streams API

   - bpo-38019(3): Correctly handle pause/resume reading of closed
     asyncio unix pipe.

   - bpo-38163(4): Child mocks will now detect their type as either
     synchronous or asynchronous, asynchronous child mocks will be
     AsyncMocks and synchronous child mocks will be either MagicMock or
     Mock (depending on their parent type).

   - bpo-38161(5): Removes _AwaitEvent from AsyncMock.

   - bpo-38216(6): Allow the rare code that wants to send invalid http
     requests from the *note http.client: 94. library a way to do so.
     The fixes for bpo-30458(7) led to breakage for some projects that
     were relying on this ability to test their own behavior in the face
     of bad requests.

   - bpo-38108(8): Any synchronous magic methods on an AsyncMock now
     return a MagicMock.  Any asynchronous magic methods on a MagicMock
     now return an AsyncMock.

   - bpo-38248(9): asyncio: Fix inconsistent immediate Task cancellation

   - bpo-38237(10): The arguments for the builtin pow function are more
     descriptive.  They can now also be passed in as keywords.

   - bpo-38191(11): Constructors of *note NamedTuple: 281. and *note
     TypedDict: 23c. types now accept arbitrary keyword argument names,
     including "cls", "self", "typename", "_typename", "fields" and
     "_fields".  Passing positional arguments by keyword is deprecated.

   - bpo-38185(12): Fixed case-insensitive string comparison in *note
     sqlite3.Row: 767. indexing.

   - bpo-38136(13): Changes AsyncMock call count and await count to be
     two different counters.  Now await count only counts when a
     coroutine has been awaited, not when it has been called, and
     vice-versa.  Update the documentation around this.

   - bpo-37828(14): Fix default mock name in *note
     unittest.mock.Mock.assert_called(): 5b1. exceptions.  Patch by
     Abraham Toriz Cruz.

   - bpo-38175(15): Fix a memory leak in comparison of *note
     sqlite3.Row: 767. objects.

   - bpo-33936(16): _hashlib no longer calls obsolete OpenSSL
     initialization function with OpenSSL 1.1.0+.

   - bpo-34706(17): Preserve subclassing in
     inspect.Signature.from_callable.

   - bpo-38153(18): Names of hashing algorithms frome OpenSSL are now
     normalized to follow Python’s naming conventions.  For example
     OpenSSL uses sha3-512 instead of sha3_512 or blake2b512 instead of
     blake2b.

   - bpo-38115(19): Fix a bug in dis.findlinestarts() where it would
     return invalid bytecode offsets.  Document that a code object’s
     co_lnotab can contain invalid bytecode offsets.

   - bpo-38148(20): Add slots to *note asyncio: a. transport classes,
     which can reduce memory usage.

   - bpo-36991(21): Fixes a potential incorrect AttributeError exception
     escaping ZipFile.extract() in some unsupported input error
     situations.

   - bpo-38134(22): Remove obsolete copy of PBKDF2_HMAC_fast.  All
     supported OpenSSL versions contain a fast implementation.

   - bpo-38132(23): The OpenSSL hashlib wrapper uses a simpler
     implementation.  Several Macros and pointless caches are gone.  The
     hash name now comes from OpenSSL’s EVP. The algorithm name stays
     the same, except it is now always lower case.

   - bpo-38008(24): Fix parent class check in protocols to correctly
     identify the module that provides a builtin protocol, instead of
     assuming they all come from the *note collections.abc: 1f. module

   - bpo-37405(25): Fixed regression bug for socket.getsockname() for
     non-CAN_ISOTP AF_CAN address family sockets by returning a 1-tuple
     instead of string.

   - bpo-38121(26): Update parameter names on functions in
     importlib.metadata matching the changes in the 0.22 release of
     importlib_metadata.

   - bpo-38110(27): The os.closewalk() implementation now uses the libc
     fdwalk() API on platforms where it is available.

   - bpo-38093(28): Fixes AsyncMock so it doesn’t crash when used with
     AsyncContextManagers or AsyncIterators.

   - bpo-37488(29): Add warning to ‘datetime.utctimetuple()’,
     ‘datetime.utcnow()’ and ‘datetime.utcfromtimestamp()’ .

   - bpo-38086(30): Update importlib.metadata with changes from
     importlib_metadata 0.21(31).

   - bpo-37251(32): Remove ‘__code__’ check in AsyncMock that
     incorrectly evaluated function specs as async objects but failed to
     evaluate classes with ‘__await__’ but no ‘__code__’ attribute
     defined as async objects.

   - bpo-38037(33): Fix reference counters in the *note signal: eb.
     module.

   - bpo-38066(34): Hide internal asyncio.Stream methods: feed_eof(),
     feed_data(), set_exception() and set_transport().

   - bpo-38059(35): inspect.py now uses sys.exit() instead of exit()

   - bpo-37953(36): In *note typing: 11a, improved the ‘__hash__’ and
     ‘__eq__’ methods for ‘ForwardReferences’.

   - bpo-38026(37): Fixed *note inspect.getattr_static(): bd3. used
     ‘isinstance’ while it should avoid dynamic lookup.

   - bpo-38010(38): In ‘importlib.metadata’ sync with
     ‘importlib_metadata’ 0.20, clarifying behavior of ‘files()’ and
     fixing issue where only one requirement was returned for
     ‘requires()’ on ‘dist-info’ packages.

   - bpo-38006(39): weakref.WeakValueDictionary defines a local remove()
     function used as callback for weak references.  This function was
     created with a closure.  Modify the implementation to avoid the
     closure.

   - bpo-34410(40): Fixed a crash in the ‘tee()’ iterator when re-enter
     it.  RuntimeError is now raised in this case.

   - bpo-37140(41): Fix a ctypes regression of Python 3.8.  When a
     ctypes.Structure is passed by copy to a function, ctypes internals
     created a temporary object which had the side effect of calling the
     structure finalizer (__del__) twice.  The Python semantics requires
     a finalizer to be called exactly once.  Fix ctypes internals to no
     longer call the finalizer twice.

   - bpo-37972(42): Subscripts to the *note unittest.mock.call: f8a.
     objects now receive the same chaining mechanism as any other custom
     attributes, so that the following usage no longer raises a *note
     TypeError: 193.:

     call().foo().__getitem__(’bar’)

     Patch by blhsing

   - bpo-22347(43): Update mimetypes.guess_type to allow proper parsing
     of URLs with only a host name.  Patch by Dong-hee Na.

   - bpo-37885(44): venv: Don’t generate unset variable warning on
     deactivate.

   - bpo-37785(45): Fix xgettext warnings in *note argparse: 6.

   - bpo-11953(46): Completing WSA* error codes in *note socket: f0.

   - bpo-37424(47): Fixes a possible hang when using a timeout on *note
     subprocess.run(): 3f5. while capturing output.  If the child
     process spawned its own children or otherwise connected its stdout
     or stderr handles with another process, we could hang after the
     timeout was reached and our child was killed when attempting to
     read final output from the pipes.

   - bpo-37212(48): *note unittest.mock.call(): f8a. now preserves the
     order of keyword arguments in repr output.  Patch by Karthikeyan
     Singaravelan.

   - bpo-37305(49): Add .webmanifest -> application/manifest+json to
     list of recognized file types and content type headers

   - bpo-21872(50): Fix *note lzma: ae.: module decompresses data
     incompletely.  When decompressing a FORMAT_ALONE format file, and
     it doesn’t have the end marker, sometimes the last one to dozens
     bytes can’t be output.  Patch by Ma Lin.

   - bpo-37206(51): Default values which cannot be represented as Python
     objects no longer improperly represented as ‘None’ in function
     signatures.

   - bpo-12144(52): Ensure cookies with ‘expires’ attribute are handled
     in ‘CookieJar.make_cookies()’.

   - bpo-31163(53): pathlib.Path instance’s rename and replace methods
     now return the new Path instance.

   - bpo-25068(54): *note urllib.request.ProxyHandler: f8b. now
     lowercases the keys of the passed dictionary.

   - bpo-21315(55): Email headers containing RFC2047 encoded words are
     parsed despite the missing whitespace, and a defect registered.
     Also missing trailing whitespace after encoded words is now
     registered as a defect.

   - bpo-36250(56): Ignore ‘ValueError’ from ‘signal’ with ‘interaction’
     in non-main thread.

   - bpo-35168(57): *note shlex.shlex.punctuation_chars: f8c. is now a
     read-only property.

   - bpo-20504(58): Fixes a bug in *note cgi: 16. module when a
     multipart/form-data request has no ‘Content-Length’ header.

   - bpo-34519(59): Add additional aliases for HP Roman 8.  Patch by
     Michael Osipov.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38319

   (2) https://bugs.python.org/issue38242

   (3) https://bugs.python.org/issue38019

   (4) https://bugs.python.org/issue38163

   (5) https://bugs.python.org/issue38161

   (6) https://bugs.python.org/issue38216

   (7) https://bugs.python.org/issue30458

   (8) https://bugs.python.org/issue38108

   (9) https://bugs.python.org/issue38248

   (10) https://bugs.python.org/issue38237

   (11) https://bugs.python.org/issue38191

   (12) https://bugs.python.org/issue38185

   (13) https://bugs.python.org/issue38136

   (14) https://bugs.python.org/issue37828

   (15) https://bugs.python.org/issue38175

   (16) https://bugs.python.org/issue33936

   (17) https://bugs.python.org/issue34706

   (18) https://bugs.python.org/issue38153

   (19) https://bugs.python.org/issue38115

   (20) https://bugs.python.org/issue38148

   (21) https://bugs.python.org/issue36991

   (22) https://bugs.python.org/issue38134

   (23) https://bugs.python.org/issue38132

   (24) https://bugs.python.org/issue38008

   (25) https://bugs.python.org/issue37405

   (26) https://bugs.python.org/issue38121

   (27) https://bugs.python.org/issue38110

   (28) https://bugs.python.org/issue38093

   (29) https://bugs.python.org/issue37488

   (30) https://bugs.python.org/issue38086

   (31) 
https://gitlab.com/python-devs/importlib_metadata/blob/0.21/importlib_metadata/docs/changelog.rst

   (32) https://bugs.python.org/issue37251

   (33) https://bugs.python.org/issue38037

   (34) https://bugs.python.org/issue38066

   (35) https://bugs.python.org/issue38059

   (36) https://bugs.python.org/issue37953

   (37) https://bugs.python.org/issue38026

   (38) https://bugs.python.org/issue38010

   (39) https://bugs.python.org/issue38006

   (40) https://bugs.python.org/issue34410

   (41) https://bugs.python.org/issue37140

   (42) https://bugs.python.org/issue37972

   (43) https://bugs.python.org/issue22347

   (44) https://bugs.python.org/issue37885

   (45) https://bugs.python.org/issue37785

   (46) https://bugs.python.org/issue11953

   (47) https://bugs.python.org/issue37424

   (48) https://bugs.python.org/issue37212

   (49) https://bugs.python.org/issue37305

   (50) https://bugs.python.org/issue21872

   (51) https://bugs.python.org/issue37206

   (52) https://bugs.python.org/issue12144

   (53) https://bugs.python.org/issue31163

   (54) https://bugs.python.org/issue25068

   (55) https://bugs.python.org/issue21315

   (56) https://bugs.python.org/issue36250

   (57) https://bugs.python.org/issue35168

   (58) https://bugs.python.org/issue20504

   (59) https://bugs.python.org/issue34519


File: python.info,  Node: 文档<17>,  Next: 测试<12>,  Prev: 库<21>,  Up: Python 3 8 0 rc1

1.18.22.4 文档
..............

   - bpo-26868(1): Fix example usage of *note PyModule_AddObject(): f8e.
     to properly handle errors.

   - bpo-36797(2): Fix a dead link in the distutils API Reference.

   - bpo-37977(3): Warn more strongly and clearly about pickle
     insecurity

   - bpo-37937(4): Mention ‘frame.f_trace’ in *note sys.settrace(): e46.
     docs.

   - bpo-36260(5): Add decompression pitfalls to zipfile module
     documentation.

   - bpo-36960(6): Restructured the *note datetime: 31. docs in the
     interest of making them more user-friendly and improving
     readability.  Patch by Brad Solomon.

   - bpo-23460(7): The documentation for decimal string formatting using
     the ‘:g’ specifier has been updated to reflect the correct
     exponential notation cutoff point.  Original patch contributed by
     Tuomas Suutari.

   - bpo-35803(8): Document and test that ‘tempfile’ functions may
     accept a *note path-like object: 373. for the ‘dir’ argument.
     Patch by Anthony Sottile.

   - bpo-33944(9): Added a note about the intended use of code in .pth
     files.

   - bpo-34293(10): Fix the Doc/Makefile regarding PAPER environment
     variable and PDF builds

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26868

   (2) https://bugs.python.org/issue36797

   (3) https://bugs.python.org/issue37977

   (4) https://bugs.python.org/issue37937

   (5) https://bugs.python.org/issue36260

   (6) https://bugs.python.org/issue36960

   (7) https://bugs.python.org/issue23460

   (8) https://bugs.python.org/issue35803

   (9) https://bugs.python.org/issue33944

   (10) https://bugs.python.org/issue34293


File: python.info,  Node: 测试<12>,  Next: 构建<10>,  Prev: 文档<17>,  Up: Python 3 8 0 rc1

1.18.22.5 测试
..............

   - bpo-38239(1): Fix test_gdb for Link Time Optimization (LTO) builds.

   - bpo-38275(2): test_ssl now handles disabled TLS/SSL versions
     better.  OpenSSL’s crypto policy and run-time settings are
     recognized and tests for disabled versions are skipped.  Tests also
     accept more TLS minimum_versions for platforms that override
     OpenSSL’s default with strict settings.

   - bpo-38271(3): The private keys for test_ssl were encrypted with
     3DES in traditional PKCS#5 format.  3DES and the digest algorithm
     of PKCS#5 are blocked by some strict crypto policies.  Use PKCS#8
     format with AES256 encryption instead.

   - bpo-38270(4): test.support now has a helper function to check for
     availibility of a hash digest function.  Several tests are
     refactored avoid MD5 and use SHA256 instead.  Other tests are
     marked to use MD5 and skipped when MD5 is disabled.

   - bpo-37123(5): Multiprocessing test test_mymanager() now also
     expects -SIGTERM, not only exitcode 0.
     BaseManager._finalize_manager() sends SIGTERM to the manager
     process if it takes longer than 1 second to stop, which happens on
     slow buildbots.

   - bpo-38212(6): Multiprocessing tests: increase
     test_queue_feeder_donot_stop_onexc() timeout from 1 to 60 seconds.

   - bpo-38117(7): 使用OpenSSL 1.1.1d进行测试

   - bpo-37531(8): Enhance regrtest multiprocess timeout: write a
     message when killing a worker process, catch popen.kill() and
     popen.wait() exceptions, put a timeout on the second call to
     popen.communicate().

   - bpo-37876(9): Add tests for ROT-13 codec.

   - bpo-37252(10): Fix assertions in ‘test_close’ and
     ‘test_events_mask_overflow’ devpoll tests.

   - bpo-34001(11): Make test_ssl pass with LibreSSL. LibreSSL handles
     minimum and maximum TLS version differently than OpenSSL.

   - bpo-36919(12): Make ‘test_source_encoding.test_issue2301’
     implementation independent.  The test will work now for both
     CPython and IronPython.

   - bpo-34596(13): Fallback to a default reason when *note
     unittest.skip(): f90. is uncalled.  Patch by Naitree Zhu.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38239

   (2) https://bugs.python.org/issue38275

   (3) https://bugs.python.org/issue38271

   (4) https://bugs.python.org/issue38270

   (5) https://bugs.python.org/issue37123

   (6) https://bugs.python.org/issue38212

   (7) https://bugs.python.org/issue38117

   (8) https://bugs.python.org/issue37531

   (9) https://bugs.python.org/issue37876

   (10) https://bugs.python.org/issue37252

   (11) https://bugs.python.org/issue34001

   (12) https://bugs.python.org/issue36919

   (13) https://bugs.python.org/issue34596


File: python.info,  Node: 构建<10>,  Next: Windows<14>,  Prev: 测试<12>,  Up: Python 3 8 0 rc1

1.18.22.6 构建
..............

   - bpo-38301(1): In Solaris family, we must be sure to use
     ‘-D_REENTRANT’.  Patch by Jesús Cea Avión.

   - bpo-36210(2): Update optional extension module detection for AIX.
     ossaudiodev and spwd are not applicable for AIX, and are no longer
     reported as missing.  3rd-party packaging of ncurses (with ASIS
     support) conflicts with officially supported AIX curses library, so
     configure AIX to use libcurses.a.  However, skip trying to build
     _curses_panel.

     patch by M Felt

   - bpo-36002(3): Locate ‘llvm-profdata’ and ‘llvm-ar’ binaries using
     ‘AC_PATH_TOOL’ rather than ‘AC_PATH_TARGET_TOOL’.

   - bpo-37936(4): The ‘.gitignore’ file systematically keeps "rooted",
     with a non-trailing slash, all the rules that are meant to apply to
     files in a specific place in the repo.  Previously, when the
     intended file to ignore happened to be at the root of the repo,
     we’d most often accidentally also ignore files and directories with
     the same name anywhere in the tree.

   - bpo-37936(5): The ‘.gitignore’ file no longer applies to any files
     that are in fact tracked in the Git repository.  Patch by Greg
     Price.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38301

   (2) https://bugs.python.org/issue36210

   (3) https://bugs.python.org/issue36002

   (4) https://bugs.python.org/issue37936

   (5) https://bugs.python.org/issue37936


File: python.info,  Node: Windows<14>,  Next: macOS<11>,  Prev: 构建<10>,  Up: Python 3 8 0 rc1

1.18.22.7 Windows
.................

   - bpo-38117(1): 将绑定的OpenSSL更新到1.1.1d

   - bpo-38092(2): Reduce overhead when using multiprocessing in a
     Windows virtual environment.

   - bpo-38133(3): Allow py.exe launcher to locate installations from
     the Microsoft Store and improve display of active virtual
     environments.

   - bpo-38114(4): The ‘pip.ini’ is no longer included in the Nuget
     package.

   - bpo-36634(5): *note os.cpu_count(): 888. now returns active
     processors rather than maximum processors.

   - bpo-36634(6): venv activate.bat now works when the existing
     variables contain double quote characters.

   - bpo-38081(7): Prevent error calling *note os.path.realpath(): 200.
     on ‘'NUL'’.

   - bpo-38087(8): Fix case sensitivity in test_pathlib and test_ntpath.

   - bpo-38088(9): Fixes distutils not finding vcruntime140.dll with
     only the v142 toolset installed.

   - bpo-37283(10): Ensure command-line and unattend.xml setting
     override previously detected states in Windows installer.

   - bpo-38030(11): Fixes *note os.stat(): 1f2. failing for block
     devices on Windows

   - bpo-38020(12): Fixes potential crash when calling *note
     os.readlink(): 1f4. (or indirectly through *note realpath(): 200.)
     on a file that is not a supported link.

   - bpo-37705(13): Improve the implementation of ‘winerror_to_errno()’.

   - bpo-37702(14): Fix memory leak on Windows in creating an SSLContext
     object or running urllib.request.urlopen(’‘https://’...’).

   - bpo-37445(15): Include the ‘FORMAT_MESSAGE_IGNORE_INSERTS’ flag in
     ‘FormatMessageW()’ calls.

   - bpo-37380(16): Don’t collect unfinished processes with
     ‘subprocess._active’ on Windows to cleanup later.  Patch by Ruslan
     Kuprieiev.

   - bpo-32587(17): Make *note winreg.REG_MULTI_SZ: f93. support
     zero-length strings.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38117

   (2) https://bugs.python.org/issue38092

   (3) https://bugs.python.org/issue38133

   (4) https://bugs.python.org/issue38114

   (5) https://bugs.python.org/issue36634

   (6) https://bugs.python.org/issue36634

   (7) https://bugs.python.org/issue38081

   (8) https://bugs.python.org/issue38087

   (9) https://bugs.python.org/issue38088

   (10) https://bugs.python.org/issue37283

   (11) https://bugs.python.org/issue38030

   (12) https://bugs.python.org/issue38020

   (13) https://bugs.python.org/issue37705

   (14) https://bugs.python.org/issue37702

   (15) https://bugs.python.org/issue37445

   (16) https://bugs.python.org/issue37380

   (17) https://bugs.python.org/issue32587


File: python.info,  Node: macOS<11>,  Next: IDLE<19>,  Prev: Windows<14>,  Up: Python 3 8 0 rc1

1.18.22.8 macOS
...............

   - bpo-38117(1): 在MacOS安装程序中将OpenSSL更新为1.1.1d。

   - bpo-38089(2): Move Azure Pipelines to latest VM versions and make
     macOS tests optional

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38117

   (2) https://bugs.python.org/issue38089


File: python.info,  Node: IDLE<19>,  Next: 工具/示例<6>,  Prev: macOS<11>,  Up: Python 3 8 0 rc1

1.18.22.9 IDLE
..............

   - bpo-35379(1): When exiting IDLE, catch any AttributeError.  One
     happens when EditorWindow.close is called twice.  Printing a
     traceback, when IDLE is run from a terminal, is useless and
     annoying.

   - bpo-38183(2): To avoid problems, test_idle ignores the user config
     directory.  It no longer tries to create or access .idlerc or any
     files within.  Users must run IDLE to discover problems with saving
     settings.

   - bpo-38077(3): IDLE no longer adds ’argv’ to the user namespace when
     initializing it.  This bug only affected 3.7.4 and 3.8.0b2 to
     3.8.0b4.

   - bpo-38041(4): Shell restart lines now fill the window width, always
     start with ’=’, and avoid wrapping unnecessarily.  The line will
     still wrap if the included file name is long relative to the width.

   - bpo-35771(5): To avoid occasional spurious test_idle failures on
     slower machines, increase the ‘hover_delay’ in test_tooltip.

   - bpo-37902(6): Add mousewheel scrolling for IDLE module, path, and
     stack browsers.  Patch by George Zhang.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35379

   (2) https://bugs.python.org/issue38183

   (3) https://bugs.python.org/issue38077

   (4) https://bugs.python.org/issue38041

   (5) https://bugs.python.org/issue35771

   (6) https://bugs.python.org/issue37902


File: python.info,  Node: 工具/示例<6>,  Next: C API<9>,  Prev: IDLE<19>,  Up: Python 3 8 0 rc1

1.18.22.10 工具/示例
....................

   - bpo-37803(1): pdb’s ‘--help’ and ‘--version’ long options now work.

   - bpo-37064(2): Add option -k to pathscript.py script: preserve
     shebang flags.  Add option -a to pathscript.py script: add flags.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37803

   (2) https://bugs.python.org/issue37064


File: python.info,  Node: C API<9>,  Prev: 工具/示例<6>,  Up: Python 3 8 0 rc1

1.18.22.11 C API
................

   - bpo-38234(1): *note Py_SetPath(): 274. now sets *note
     sys.executable: 275. to the program full path (*note
     Py_GetProgramFullPath(): 276.) rather than to the program name
     (*note Py_GetProgramName(): 277.).

   - bpo-38234(2): Python ignored arguments passed to *note
     Py_SetPath(): 274, *note Py_SetPythonHome(): f98. and *note
     Py_SetProgramName(): f99.: fix Python initialization to use
     specified arguments.

   - bpo-38205(3): The *note Py_UNREACHABLE(): 42b. macro now calls
     *note Py_FatalError(): f9a.

   - bpo-37879(4): Fix subtype_dealloc to suppress the type decref when
     the base type is a C heap type

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38234

   (2) https://bugs.python.org/issue38234

   (3) https://bugs.python.org/issue38205

   (4) https://bugs.python.org/issue37879


File: python.info,  Node: Python 3 8 0 beta 4,  Next: Python 3 8 0 beta 3,  Prev: Python 3 8 0 rc1,  Up: 更新日志

1.18.23 Python 3.8.0 beta 4
---------------------------

`发布日期: 2019-08-29'

* Menu:

* 安全: 安全<15>.
* 核心与内置: 核心与内置<22>.
* 库: 库<22>.
* 文档: 文档<18>.
* 测试: 测试<13>.
* 构建: 构建<11>.
* Windows: Windows<15>.
* macOS: macOS<12>.
* IDLE: IDLE<20>.
* 工具/示例: 工具/示例<7>.
* C API: C API<10>.


File: python.info,  Node: 安全<15>,  Next: 核心与内置<22>,  Up: Python 3 8 0 beta 4

1.18.23.1 安全
..............

   - bpo-34155(1): Fix parsing of invalid email addresses with more than
     one ‘@’ (e.g.  a@b@c.com.)  to not return the part before 2nd ‘@’
     as valid email address.  Patch by maxking & jpic.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34155


File: python.info,  Node: 核心与内置<22>,  Next: 库<22>,  Prev: 安全<15>,  Up: Python 3 8 0 beta 4

1.18.23.2 核心与内置
....................

   - bpo-37947(1): Adjust correctly the recursion level in the symtable
     generation for named expressions.  Patch by Pablo Galindo.

   - bpo-37830(2): Fixed compilation of *note break: 2dc. and *note
     continue: 182. in the *note finally: 183. block when the
     corresponding *note try: d7a. block contains *note return: 191.
     with a non-constant value.

   - bpo-32912(3): Reverted bpo-32912(4): emitting *note SyntaxWarning:
     192. instead of *note DeprecationWarning: 279. for invalid escape
     sequences in string and bytes literals.

   - bpo-37757(5): PEP 572(6): As described in the PEP, assignment
     expressions now raise *note SyntaxError: 460. when their
     interaction with comprehension scoping results in an ambiguous
     target scope.

     The ‘TargetScopeError’ subclass originally proposed by the PEP has
     been removed in favour of just raising regular syntax errors for
     the disallowed cases.

   - bpo-36311(7): Decoding bytes objects larger than 2GiB is faster and
     no longer fails when a multibyte characters spans a chunk boundary.

   - bpo-37433(8): Fix ‘SyntaxError’ indicator printing too many spaces
     for multi-line strings - by Anthony Sottile.

   - bpo-20523(9): ‘pdb.Pdb’ supports ~/.pdbrc in Windows 7.  Patch by
     Tim Hopper and Dan Lidral-Porter.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37947

   (2) https://bugs.python.org/issue37830

   (3) https://bugs.python.org/issue32912

   (4) https://bugs.python.org/issue32912

   (5) https://bugs.python.org/issue37757

   (6) https://www.python.org/dev/peps/pep-0572

   (7) https://bugs.python.org/issue36311

   (8) https://bugs.python.org/issue37433

   (9) https://bugs.python.org/issue20523


File: python.info,  Node: 库<22>,  Next: 文档<18>,  Prev: 核心与内置<22>,  Up: Python 3 8 0 beta 4

1.18.23.3 库
............

   - bpo-37834(1): Prevent shutil.rmtree exception when built on
     non-Windows system without fd system call support, like older
     versions of macOS.

   - bpo-37965(2): Fix C compiler warning caused by
     distutils.ccompiler.CCompiler.has_function.

   - bpo-37960(3): ‘repr()’ of buffered and text streams now silences
     only expected exceptions when get the value of "name" and "mode"
     attributes.

   - bpo-37951(4): Most features of the subprocess module now work again
     in subinterpreters.  Only `preexec_fn' is restricted in
     subinterpreters.

   - bpo-36205(5): Fix the rusage implementation of time.process_time()
     to correctly report the sum of the system and user CPU time.

   - bpo-37950(6): Fix *note ast.dump(): f9f. when call with
     incompletely initialized node.

   - bpo-34679(7): Restores instantiation of Windows IOCP event loops
     from the non-main thread.

   - bpo-36917(8): Add default implementation of the
     ‘ast.NodeVisitor.visit_Constant()’ method which emits a deprecation
     warning and calls corresponding methody ‘visit_Num()’,
     ‘visit_Str()’, etc.

   - bpo-37798(9): Update test_statistics.py to verify that the
     statistics module works well for both C and Python implementations.
     Patch by Dong-hee Na

   - bpo-26589(10): Added a new status code to the http module: 451
     UNAVAILABLE_FOR_LEGAL_REASONS

   - bpo-37915(11): Fix a segmentation fault that appeared when
     comparing instances of ‘datetime.timezone’ and ‘datetime.tzinfo’
     objects.  Patch by Pablo Galindo.

   - bpo-37868(12): Fix dataclasses.is_dataclass when given an instance
     that never raises AttributeError in __getattr__.  That is, an
     object that returns something for __dataclass_fields__ even if it’s
     not a dataclass.

   - bpo-37811(13): Fix ‘socket’ module’s ‘socket.connect(address)’
     function being unable to establish connection in case of
     interrupted system call.  The problem was observed on all OSes
     which ‘poll(2)’ system call can take only non-negative integers and
     -1 as a timeout value.

   - bpo-21131(14): Fix ‘faulthandler.register(chain=True)’ stack.
     faulthandler now allocates a dedicated stack of ‘SIGSTKSZ*2’ bytes,
     instead of just ‘SIGSTKSZ’ bytes.  Calling the previous signal
     handler in faulthandler signal handler uses more than ‘SIGSTKSZ’
     bytes of stack memory on some platforms.

   - bpo-37798(15): Add C fastpath for statistics.NormalDist.inv_cdf()
     Patch by Dong-hee Na

   - bpo-37819(16): Add Fraction.as_integer_ratio() to match the
     corresponding methods in bool, int, float, and decimal.

   - bpo-37810(17): Fix *note difflib: 37. ‘?’ hint in diff output when
     dealing with tabs.  Patch by Anthony Sottile.

   - bpo-37772(18): In ‘zipfile.Path’, when adding implicit dirs, ensure
     that ancestral directories are added and that duplicates are
     excluded.

   - bpo-28292(19): Mark calendar.py helper functions as being private.
     The follows PEP 8 guidance to maintain the style conventions in the
     module and it addresses a known case of user confusion.

   - bpo-18049(20): Add definition of THREAD_STACK_SIZE for AIX in
     Python/thread_pthread.h The default thread stacksize caused crashes
     with the default recursion limit Patch by M Felt

   - bpo-37738(21): Fix the implementation of curses ‘addch(str,
     color_pair)’: pass the color pair to ‘setcchar()’, instead of
     always passing 0 as the color pair.

   - bpo-37723(22): Fix performance regression on regular expression
     parsing with huge character sets.  Patch by Yann Vaginay.

   - bpo-32178(23): Fix IndexError in *note email: 69. package when
     trying to parse invalid address fields starting with ‘:’.

   - bpo-37685(24): Fixed comparisons of *note datetime.timedelta: 196.
     and *note datetime.timezone: a09.

   - bpo-37695(25): Correct *note curses.unget_wch(): 9e8. error
     message.  Patch by Anthony Sottile.

   - bpo-37354(26): Make Activate.ps1 Powershell script static to allow
     for signing it.

   - bpo-37664(27): Update wheels bundled with ensurepip (pip 19.2.3 and
     setuptools 41.2.0)

   - bpo-37642(28): Allowed the pure Python implementation of *note
     datetime.timezone: a09. to represent sub-minute offsets close to
     minimum and maximum boundaries, specifically in the ranges (23:59,
     24:00) and (-23:59, 24:00).  Patch by Ngalim Siregar

   - bpo-16970(29): Adding a value error when an invalid value in passed
     to nargs Patch by Robert Leenders

   - bpo-37587(30): Make json.loads faster for long strings.  (Patch by
     Marco Paolini)

   - bpo-18378(31): Recognize "UTF-8" as a valid value for LC_CTYPE in
     locale._parse_localename.

   - bpo-37531(32): "python3 -m test -jN –timeout=TIMEOUT" now kills a
     worker process if it runs longer than `TIMEOUT' seconds.

   - bpo-37482(33): Fix serialization of display name in originator or
     destination address fields with both encoded words and special
     chars.

   - bpo-37372(34): Fix error unpickling datetime.time objects from
     Python 2 with seconds>=24.  Patch by Justin Blanchard.

   - bpo-37085(35): Add the optional Linux SocketCAN Broadcast Manager
     constants, used as flags to configure the BCM behaviour, in the
     socket module.  Patch by Karl Ding.

   - bpo-36871(36): Ensure method signature is used instead of
     constructor signature of a class while asserting mock object
     against method calls.  Patch by Karthikeyan Singaravelan.

   - bpo-36582(37): Fix ‘UserString.encode()’ to correctly return
     ‘bytes’ rather than a ‘UserString’ instance.

   - bpo-34775(38): Division handling of PurePath now returns
     NotImplemented instead of raising a TypeError when passed something
     other than an instance of str or PurePath.  Patch by Roger Aiudi.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37834

   (2) https://bugs.python.org/issue37965

   (3) https://bugs.python.org/issue37960

   (4) https://bugs.python.org/issue37951

   (5) https://bugs.python.org/issue36205

   (6) https://bugs.python.org/issue37950

   (7) https://bugs.python.org/issue34679

   (8) https://bugs.python.org/issue36917

   (9) https://bugs.python.org/issue37798

   (10) https://bugs.python.org/issue26589

   (11) https://bugs.python.org/issue37915

   (12) https://bugs.python.org/issue37868

   (13) https://bugs.python.org/issue37811

   (14) https://bugs.python.org/issue21131

   (15) https://bugs.python.org/issue37798

   (16) https://bugs.python.org/issue37819

   (17) https://bugs.python.org/issue37810

   (18) https://bugs.python.org/issue37772

   (19) https://bugs.python.org/issue28292

   (20) https://bugs.python.org/issue18049

   (21) https://bugs.python.org/issue37738

   (22) https://bugs.python.org/issue37723

   (23) https://bugs.python.org/issue32178

   (24) https://bugs.python.org/issue37685

   (25) https://bugs.python.org/issue37695

   (26) https://bugs.python.org/issue37354

   (27) https://bugs.python.org/issue37664

   (28) https://bugs.python.org/issue37642

   (29) https://bugs.python.org/issue16970

   (30) https://bugs.python.org/issue37587

   (31) https://bugs.python.org/issue18378

   (32) https://bugs.python.org/issue37531

   (33) https://bugs.python.org/issue37482

   (34) https://bugs.python.org/issue37372

   (35) https://bugs.python.org/issue37085

   (36) https://bugs.python.org/issue36871

   (37) https://bugs.python.org/issue36582

   (38) https://bugs.python.org/issue34775


File: python.info,  Node: 文档<18>,  Next: 测试<13>,  Prev: 库<22>,  Up: Python 3 8 0 beta 4

1.18.23.4 文档
..............

   - bpo-37979(1): Added a link to dateutil.parser.isoparse in the
     datetime.fromisoformat documentation.  Patch by Paul Ganssle

   - bpo-37759(2): Beginning edits to Whatsnew 3.8

   - bpo-37726(3): Stop recommending getopt in the tutorial for command
     line argument parsing and promote argparse.

   - bpo-37256(4): Fix wording of arguments for ‘Request’ in *note
     urllib.request: 121.

   - bpo-37004(5): In the documentation for difflib, a note was added
     explicitly warning that the results of SequenceMatcher’s ratio
     method may depend on the order of the input strings.

   - bpo-36487(6): Make C-API docs clear about what the "main"
     interpreter is.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37979

   (2) https://bugs.python.org/issue37759

   (3) https://bugs.python.org/issue37726

   (4) https://bugs.python.org/issue37256

   (5) https://bugs.python.org/issue37004

   (6) https://bugs.python.org/issue36487


File: python.info,  Node: 测试<13>,  Next: 构建<11>,  Prev: 文档<18>,  Up: Python 3 8 0 beta 4

1.18.23.5 测试
..............

   - bpo-37805(1): Add tests for json.dump(..., skipkeys=True).  Patch
     by Dong-hee Na.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37805


File: python.info,  Node: 构建<11>,  Next: Windows<15>,  Prev: 测试<13>,  Up: Python 3 8 0 beta 4

1.18.23.6 构建
..............

   - bpo-37707(1): Mark some individual tests to skip when –pgo is used.
     The tests marked increase the PGO task time significantly and
     likely don’t help improve optimization of the final executable.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37707


File: python.info,  Node: Windows<15>,  Next: macOS<12>,  Prev: 构建<11>,  Up: Python 3 8 0 beta 4

1.18.23.7 Windows
.................

   - bpo-37549(1): *note os.dup(): fa4. no longer fails for standard
     streams on Windows 7.

   - bpo-1311(2): The ‘nul’ file on Windows now returns True from *note
     exists(): 1f7. and a valid result from *note os.stat(): 1f2. with
     ‘S_IFCHR’ set.

   - bpo-9949(3): Enable support for following symlinks in
     ‘os.realpath()’.

   - bpo-37834(4): Treat all name surrogate reparse points on Windows in
     *note os.lstat(): 1f3. and other reparse points as regular files in
     *note os.stat(): 1f2.

   - bpo-36266(5): Add the module name in the formatted error message
     when DLL load fail happens during module import in
     ‘_PyImport_FindSharedFuncptrWindows()’.  Patch by Srinivas
     Nyayapati.

   - bpo-25172(6): Trying to import the *note crypt: 29. module on
     Windows will result in an *note ImportError: 33d. with a message
     explaining that the module isn’t supported on Windows.  On other
     platforms, if the underlying ‘_crypt’ module is not available, the
     ImportError will include a message explaining the problem.

   - bpo-37778(7): Fixes the icons used for file associations to the
     Microsoft Store package.

   - bpo-37734(8): Fix use of registry values to launch Python from
     Microsoft Store app.

   - bpo-28269(9): Replace use of ‘strcasecmp()’ for the system function
     ‘_stricmp()’.  Patch by Minmin Gong.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37549

   (2) https://bugs.python.org/issue1311

   (3) https://bugs.python.org/issue9949

   (4) https://bugs.python.org/issue37834

   (5) https://bugs.python.org/issue36266

   (6) https://bugs.python.org/issue25172

   (7) https://bugs.python.org/issue37778

   (8) https://bugs.python.org/issue37734

   (9) https://bugs.python.org/issue28269


File: python.info,  Node: macOS<12>,  Next: IDLE<20>,  Prev: Windows<15>,  Up: Python 3 8 0 beta 4

1.18.23.8 macOS
...............

   - bpo-18049(1): Increase the default stack size of threads from 5MB
     to 16MB on macOS, to match the stack size of the main thread.  This
     avoids crashes on deep recursion in threads.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18049


File: python.info,  Node: IDLE<20>,  Next: 工具/示例<7>,  Prev: macOS<12>,  Up: Python 3 8 0 beta 4

1.18.23.9 IDLE
..............

   - bpo-37824(1): Properly handle user input warnings in IDLE shell.
     Cease turning SyntaxWarnings into SyntaxErrors.

   - bpo-37929(2): IDLE Settings dialog now closes properly when there
     is no shell window.

   - bpo-37849(3): Fixed completions list appearing too high or low when
     shown above the current line.

   - bpo-36419(4): Refactor IDLE autocomplete and improve testing.

   - bpo-37748(5): Reorder the Run menu.  Put the most common choice,
     Run Module, at the top.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37824

   (2) https://bugs.python.org/issue37929

   (3) https://bugs.python.org/issue37849

   (4) https://bugs.python.org/issue36419

   (5) https://bugs.python.org/issue37748


File: python.info,  Node: 工具/示例<7>,  Next: C API<10>,  Prev: IDLE<20>,  Up: Python 3 8 0 beta 4

1.18.23.10 工具/示例
....................

   - bpo-37942(1): Improve ArgumentClinic converter for floats.

   - bpo-37034(2): Argument Clinic now uses the argument name on errors
     with keyword-only argument instead of their position.  Patch
     contributed by Rémi Lapeyre.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37942

   (2) https://bugs.python.org/issue37034


File: python.info,  Node: C API<10>,  Prev: 工具/示例<7>,  Up: Python 3 8 0 beta 4

1.18.23.11 C API
................

   - bpo-36763(1): Options added by ‘PySys_AddXOption()’ are now handled
     the same way than ‘PyConfig.xoptions’ and command line ‘-X’
     options.

   - bpo-37926(2): Fix a crash in ‘PySys_SetArgvEx(0, NULL, 0)’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36763

   (2) https://bugs.python.org/issue37926


File: python.info,  Node: Python 3 8 0 beta 3,  Next: Python 3 8 0 beta 2,  Prev: Python 3 8 0 beta 4,  Up: 更新日志

1.18.24 Python 3.8.0 beta 3
---------------------------

`发布日期: 2019-07-29'

* Menu:

* 安全: 安全<16>.
* 核心与内置: 核心与内置<23>.
* 库: 库<23>.
* 文档: 文档<19>.
* 测试: 测试<14>.
* 构建: 构建<12>.
* Windows: Windows<16>.
* IDLE: IDLE<21>.
* 工具/示例: 工具/示例<8>.


File: python.info,  Node: 安全<16>,  Next: 核心与内置<23>,  Up: Python 3 8 0 beta 3

1.18.24.1 安全
..............

   - bpo-37461(1): Fix an infinite loop when parsing specially crafted
     email headers.  Patch by Abhilash Raj.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37461


File: python.info,  Node: 核心与内置<23>,  Next: 库<23>,  Prev: 安全<16>,  Up: Python 3 8 0 beta 3

1.18.24.2 核心与内置
....................

   - bpo-37593(1): Swap the positions of the `posonlyargs' and `args'
     parameters in the constructor of ‘ast.parameters’ nodes.

   - bpo-36974(2): Implemented separate vectorcall functions for every
     calling convention of builtin functions and methods.  This improves
     performance for calls.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37593

   (2) https://bugs.python.org/issue36974


File: python.info,  Node: 库<23>,  Next: 文档<19>,  Prev: 核心与内置<23>,  Up: Python 3 8 0 beta 3

1.18.24.3 库
............

   - bpo-37697(1): Syncronize ‘importlib.metadata’ with
     importlib_metadata 0.19(2), improving handling of EGG-INFO files
     and fixing a crash when entry point names contained colons.

   - bpo-37691(3): Let math.dist() accept coordinates as sequences (or
     iterables) rather than just tuples.

   - bpo-37664(4): Update wheels bundled with ensurepip (pip 19.2.1 and
     setuptools 41.0.1)

   - bpo-36324(5): Make internal attributes for statistics.NormalDist()
     private.

   - bpo-37491(6): Fix ‘IndexError’ when parsing email headers with
     unexpectedly ending bare-quoted string value.  Patch by Abhilash
     Raj.

   - bpo-37579(7): Return *note NotImplemented: 855. in Python
     implementation of ‘__eq__’ for *note timedelta: 196. and *note
     time: 4fb. when the other object being compared is not of the same
     type to match C implementation.  Patch by Karthikeyan Singaravelan.

   - bpo-21478(8): Record calls to parent when autospecced object is
     attached to a mock using ‘unittest.mock.attach_mock()’.  Patch by
     Karthikeyan Singaravelan.

   - bpo-37502(9): pickle.loads() no longer raises TypeError when the
     buffers argument is set to None

   - bpo-37520(10): Correct behavior for zipfile.Path.parent when the
     path object identifies a subdirectory.

   - bpo-18374(11): Fix the ‘.col_offset’ attribute of nested
     ‘ast.BinOp’ instances which had a too large value in some
     situations.

   - bpo-37421(12): Fix ‘multiprocessing.util.get_temp_dir()’ finalizer:
     clear also the ’tempdir’ configuration of the current process, so
     next call to ‘get_temp_dir()’ will create a new temporary
     directory, rather than reusing the removed temporary directory.

   - bpo-37481(13): The distutils ‘bdist_wininst’ command is deprecated
     in Python 3.8, use ‘bdist_wheel’ (wheel packages) instead.

   - bpo-26967(14): An *note ArgumentParser: 69e. with
     ‘allow_abbrev=False’ no longer disables grouping of short flags,
     such as ‘-vv’, but only disables abbreviation of long flags as
     documented.  Patch by Zac Hatfield-Dodds.

   - bpo-37347(15): *note sqlite3.Connection.create_aggregate(): fad,
     *note sqlite3.Connection.create_function(): fae, *note
     sqlite3.Connection.set_authorizer(): faf, *note
     sqlite3.Connection.set_progress_handler(): fb0. *note
     sqlite3.Connection.set_trace_callback(): a95. methods lead to
     segfaults if some of these methods are called twice with an equal
     object but not the same.  Now callbacks are stored more carefully.
     Patch by Aleksandr Balezin.

   - bpo-36564(16): Fix infinite loop in email header folding logic that
     would be triggered when an email policy’s max_line_length is not
     long enough to include the required markup and any values in the
     message.  Patch by Paul Ganssle

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37697

   (2) https://gitlab.com/python-devs/importlib_metadata/-/milestones/20

   (3) https://bugs.python.org/issue37691

   (4) https://bugs.python.org/issue37664

   (5) https://bugs.python.org/issue36324

   (6) https://bugs.python.org/issue37491

   (7) https://bugs.python.org/issue37579

   (8) https://bugs.python.org/issue21478

   (9) https://bugs.python.org/issue37502

   (10) https://bugs.python.org/issue37520

   (11) https://bugs.python.org/issue18374

   (12) https://bugs.python.org/issue37421

   (13) https://bugs.python.org/issue37481

   (14) https://bugs.python.org/issue26967

   (15) https://bugs.python.org/issue37347

   (16) https://bugs.python.org/issue36564


File: python.info,  Node: 文档<19>,  Next: 测试<14>,  Prev: 库<23>,  Up: Python 3 8 0 beta 3

1.18.24.4 文档
..............

   - bpo-32910(1): Remove implementation-specific behaviour of how
     venv’s Deactivate works.

   - bpo-37284(2): Add a brief note to indicate that any new
     ‘sys.implementation’ required attributes must go through the PEP
     process.

   - bpo-30088(3): Documented that *note mailbox.Maildir: cb0.
     constructor doesn’t attempt to verify the maildir folder layout
     correctness.  Patch by Sviatoslav Sydorenko.

   - bpo-37521(4): Fix *note importlib: 9b. examples to insert any newly
     created modules via importlib.util.module_from_spec() immediately
     into sys.modules instead of after calling loader.exec_module().

     Thanks to Benjamin Mintz for finding the bug.

   - bpo-37456(5): Slash (’/’) is now part of syntax.

   - bpo-37487(6): Fix PyList_GetItem index description to include 0.

   - bpo-37149(7): Replace the dead link to the Tkinter 8.5 reference by
     John Shipman, New Mexico Tech, with a link to the archive.org copy.

   - bpo-37478(8): Added possible exceptions to the description of
     os.chdir().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32910

   (2) https://bugs.python.org/issue37284

   (3) https://bugs.python.org/issue30088

   (4) https://bugs.python.org/issue37521

   (5) https://bugs.python.org/issue37456

   (6) https://bugs.python.org/issue37487

   (7) https://bugs.python.org/issue37149

   (8) https://bugs.python.org/issue37478


File: python.info,  Node: 测试<14>,  Next: 构建<12>,  Prev: 文档<19>,  Up: Python 3 8 0 beta 3

1.18.24.5 测试
..............

   - bpo-37558(1): Fix
     test_shared_memory_cleaned_after_process_termination name handling

   - bpo-37526(2): Add *note test.support.catch_threading_exception():
     fb3.: context manager catching *note threading.Thread: 235.
     exception using *note threading.excepthook(): 232.

   - bpo-37421(3): test_concurrent_futures now explicitly stops the
     ForkServer instance if it’s running.

   - bpo-37421(4): multiprocessing tests now stop the ForkServer
     instance if it’s running: close the "alive" file descriptor to ask
     the server to stop and then remove its UNIX address.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37558

   (2) https://bugs.python.org/issue37526

   (3) https://bugs.python.org/issue37421

   (4) https://bugs.python.org/issue37421


File: python.info,  Node: 构建<12>,  Next: Windows<16>,  Prev: 测试<14>,  Up: Python 3 8 0 beta 3

1.18.24.6 构建
..............

   - bpo-36044(1): Reduce the number of unit tests run for the PGO
     generation task.  This speeds up the task by a factor of about 15x.
     Running the full unit test suite is slow.  This change may result
     in a slightly less optimized build since not as many code branches
     will be executed.  If you are willing to wait for the much slower
     build, the old behavior can be restored using ’./configure [..]
     PROFILE_TASK="-m test –pgo-extended"’.  We make no guarantees as to
     which PGO task set produces a faster build.  Users who care should
     run their own relevant benchmarks as results can depend on the
     environment, workload, and compiler tool chain.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36044


File: python.info,  Node: Windows<16>,  Next: IDLE<21>,  Prev: 构建<12>,  Up: Python 3 8 0 beta 3

1.18.24.7 Windows
.................

   - bpo-37672(1): Switch Windows Store package’s pip to use bundled
     ‘pip.ini’ instead of ‘PIP_USER’ variable.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37672


File: python.info,  Node: IDLE<21>,  Next: 工具/示例<8>,  Prev: Windows<16>,  Up: Python 3 8 0 beta 3

1.18.24.8 IDLE
..............

   - bpo-37692(1): Improve highlight config sample with example shell
     interaction and better labels for shell elements.

   - bpo-37628(2): Settings dialog no longer expands with font size.

   - bpo-37627(3): Initialize the Customize Run dialog with the command
     line arguments most recently entered before.  The user can
     optionally edit before submitting them.

   - bpo-33610(4): Fix code context not showing the correct context when
     first toggled on.

   - bpo-37530(5): Optimize code context to reduce unneeded background
     activity.  Font and highlight changes now occur along with text
     changes instead of after a random delay.

   - bpo-27452(6): Cleanup ‘config.py’ by inlining ‘RemoveFile’ and
     simplifying the handling of ‘file’ in ‘CreateConfigHandlers’.

   - bpo-17535(7): Add optional line numbers for IDLE editor windows.
     Windows open without line numbers unless set otherwise in the
     General tab of the configuration dialog.

   - bpo-26806(8): To compensate for stack frames added by IDLE and
     avoid possible problems with low recursion limits, add 30 to limits
     in the user code execution process.  Subtract 30 when reporting
     recursion limits to make this addition mostly transparent.

   - bpo-36390(9): Gather Format menu functions into format.py.  Combine
     paragraph.py, rstrip.py, and format methods from editor.py.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37692

   (2) https://bugs.python.org/issue37628

   (3) https://bugs.python.org/issue37627

   (4) https://bugs.python.org/issue33610

   (5) https://bugs.python.org/issue37530

   (6) https://bugs.python.org/issue27452

   (7) https://bugs.python.org/issue17535

   (8) https://bugs.python.org/issue26806

   (9) https://bugs.python.org/issue36390


File: python.info,  Node: 工具/示例<8>,  Prev: IDLE<21>,  Up: Python 3 8 0 beta 3

1.18.24.9 工具/示例
...................

   - bpo-37675(1): 2to3 now works when run from a zipped standard
     library.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37675


File: python.info,  Node: Python 3 8 0 beta 2,  Next: Python 3 8 0 beta 1,  Prev: Python 3 8 0 beta 3,  Up: 更新日志

1.18.25 Python 3.8.0 beta 2
---------------------------

`发布日期: 2019-07-04'

* Menu:

* 安全: 安全<17>.
* 核心与内置: 核心与内置<24>.
* 库: 库<24>.
* 文档: 文档<20>.
* 测试: 测试<15>.
* 构建: 构建<13>.
* Windows: Windows<17>.
* macOS: macOS<13>.
* IDLE: IDLE<22>.
* C API: C API<11>.


File: python.info,  Node: 安全<17>,  Next: 核心与内置<24>,  Up: Python 3 8 0 beta 2

1.18.25.1 安全
..............

   - bpo-37363(1): Adds audit events for the range of supported run
     commands (see *note 命令行与环境: fba.).

   - bpo-37463(2): ssl.match_hostname() no longer accepts IPv4 addresses
     with additional text after the address and only quad-dotted
     notation without trailing whitespaces.  Some inet_aton()
     implementations ignore whitespace and all data after whitespace,
     e.g.  ’127.0.0.1 whatever’.

   - bpo-37363(3): Adds audit events for *note ensurepip: 7a, *note
     ftplib: 84, *note glob: 8a, *note imaplib: 98, *note nntplib: c1,
     *note pdb: ca, *note poplib: d1, *note shutil: ea, *note smtplib:
     ee, *note sqlite3: f3, *note subprocess: fa, *note telnetlib: 103,
     *note tempfile: 104. and *note webbrowser: 12a, as well as *note
     os.listdir(): a49, *note os.scandir(): 260. and *note breakpoint():
     302.

   - bpo-37364(4): *note io.open_code(): f32. is now used when reading
     ‘.pth’ files.

   - bpo-34631(5): 在Windows安装程序中将OpenSSL更新为1.1.1c

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37363

   (2) https://bugs.python.org/issue37463

   (3) https://bugs.python.org/issue37363

   (4) https://bugs.python.org/issue37364

   (5) https://bugs.python.org/issue34631


File: python.info,  Node: 核心与内置<24>,  Next: 库<24>,  Prev: 安全<17>,  Up: Python 3 8 0 beta 2

1.18.25.2 核心与内置
....................

   - bpo-37467(1): Fix *note sys.excepthook(): e6b. and
     ‘PyErr_Display()’ if a filename is a bytes string.  For example,
     for a SyntaxError exception where the filename attribute is a bytes
     string.

   - bpo-37417(2): ‘bytearray.extend()’ now correctly handles errors
     that arise during iteration.  Patch by Brandt Bucher.

   - bpo-24214(3): Improved support of the surrogatepass error handler
     in the UTF-8 and UTF-16 incremental decoders.

   - bpo-35224(4): Reverse evaluation order of key: value in dict
     comprehensions as proposed in PEP 572.  I.e.  in ‘{k: v for ...}’,
     ‘k’ will be evaluated before ‘v’.

   - bpo-37316(5): Fix the *note PySys_Audit(): f46. call in *note
     mmap.mmap: 1ed.

   - bpo-37269(6): Fix a bug in the peephole optimizer that was not
     treating correctly constant conditions with binary operators.
     Patch by Pablo Galindo.

   - bpo-37213(7): Handle correctly negative line offsets in the
     peephole optimizer.  Patch by Pablo Galindo.

   - bpo-37219(8): Remove errorneous optimization for empty set
     differences.

   - bpo-36922(9): Slot functions optimize any callable with
     ‘Py_TPFLAGS_METHOD_DESCRIPTOR’ instead of only instances of
     ‘function’.

   - bpo-36974(10): The slot ‘tp_vectorcall_offset’ is inherited
     unconditionally to support ‘super().__call__()’ when the base class
     uses vectorcall.

   - bpo-37160(11): *note threading.get_native_id(): 234. now also
     supports NetBSD.

   - bpo-37077(12): Add *note threading.get_native_id(): 234. support
     for AIX. Patch by M. Felt

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37467

   (2) https://bugs.python.org/issue37417

   (3) https://bugs.python.org/issue24214

   (4) https://bugs.python.org/issue35224

   (5) https://bugs.python.org/issue37316

   (6) https://bugs.python.org/issue37269

   (7) https://bugs.python.org/issue37213

   (8) https://bugs.python.org/issue37219

   (9) https://bugs.python.org/issue36922

   (10) https://bugs.python.org/issue36974

   (11) https://bugs.python.org/issue37160

   (12) https://bugs.python.org/issue37077


File: python.info,  Node: 库<24>,  Next: 文档<20>,  Prev: 核心与内置<24>,  Up: Python 3 8 0 beta 2

1.18.25.3 库
............

   - bpo-37440(1): http.client now enables TLS 1.3 post-handshake
     authentication for default context or if a cert_file is passed to
     HTTPSConnection.

   - bpo-37437(2): Update vendorized expat version to 2.2.7.

   - bpo-37428(3): SSLContext.post_handshake_auth = True no longer sets
     SSL_VERIFY_POST_HANDSHAKE verify flag for client connections.
     Although the option is documented as ignored for clients, OpenSSL
     implicitly enables cert chain validation when the flag is set.

   - bpo-37420(4): *note os.sched_setaffinity(): a5d. now correctly
     handles errors that arise during iteration over its ‘mask’
     argument.  Patch by Brandt Bucher.

   - bpo-37412(5): The *note os.getcwdb(): 2b9. function now uses the
     UTF-8 encoding on Windows, rather than the ANSI code page: see PEP
     529(6) for the rationale.  The function is no longer deprecated on
     Windows.

   - bpo-29412(7): Fix IndexError in parsing a header value ending
     unexpectedly.  Patch by Abhilash Raj.

   - bpo-36546(8): The `dist' argument for statistics.quantiles() is now
     positional only.  The current name doesn’t reflect that the
     argument can be either a dataset or a distribution.  Marking the
     parameter as positional avoids confusion and makes it possible to
     change the name later.

   - bpo-37394(9): Fix a bug that was causing the *note queue: db.
     module to fail if the accelerator module was not available.  Patch
     by Pablo Galindo.

   - bpo-33972(10): Email with single part but content-type set to
     ‘multipart/*’ doesn’t raise AttributeError anymore.

   - bpo-37280(11): Use threadpool for reading from file for sendfile
     fallback mode.

   - bpo-37279(12): Fix asyncio sendfile support when sendfile sends
     extra data in fallback mode.

   - bpo-19865(13): *note ctypes.create_unicode_buffer(): fbd. now also
     supports non-BMP characters on platforms with 16-bit ‘wchar_t’ (for
     example, Windows and AIX).

   - bpo-37210(14): Allow pure Python implementation of *note pickle:
     cb. to work even when the C ‘_pickle’ module is unavailable.

   - bpo-35922(15): Fix ‘RobotFileParser.crawl_delay()’ and
     ‘RobotFileParser.request_rate()’ to return ‘None’ rather than raise
     *note AttributeError: 3a3. when no relevant rule is defined in the
     robots.txt file.  Patch by Rémi Lapeyre.

   - bpo-35766(16): Change the format of feature_version to be a (major,
     minor) tuple.

   - bpo-36607(17): Eliminate *note RuntimeError: 2bb. raised by *note
     asyncio.all_tasks(): 35a. if internal tasks weak set is changed by
     another thread during iteration.

   - bpo-18748(18): ‘_pyio.IOBase’ destructor now does nothing if
     getting the ‘closed’ attribute fails to better mimick ‘_io.IOBase’
     finalizer.

   - bpo-36402(19): Fix a race condition at Python shutdown when waiting
     for threads.  Wait until the Python thread state of all non-daemon
     threads get deleted (join all non-daemon threads), rather than just
     wait until non-daemon Python threads complete.

   - bpo-34886(20): Fix an unintended ValueError from *note
     subprocess.run(): 3f5. when checking for conflicting *note input:
     c73. and ‘stdin’ or ‘capture_output’ and ‘stdout’ or ‘stderr’ args
     when they were explicitly provided but with *note None: 158. values
     within a passed in ‘**kwargs’ dict rather than as passed directly
     by name.  Patch contributed by Rémi Lapeyre.

   - bpo-37173(21): The exception message for ‘inspect.getfile()’ now
     correctly reports the passed class rather than the builtins module.

   - bpo-37178(22): Give math.perm() a one argument form that means the
     same as math.factorial().

   - bpo-37178(23): For math.perm(n, k), let k default to n, giving the
     same result as factorial.

   - bpo-37163(24): Deprecated passing ‘obj’ argument of *note
     dataclasses.replace(): ea8. as keyword argument.

   - bpo-37165(25): Converted _collections._count_elements to use the
     Argument Clinic.

   - bpo-34767(26): Do not always create a *note collections.deque: 539.
     in *note asyncio.Lock: 28c.

   - bpo-37158(27): Speed-up statistics.fmean() by switching from a
     function to a generator.

   - bpo-37150(28): ‘argparse._ActionsContainer.add_argument’ now throws
     error, if someone accidentally pass FileType class object instead
     of instance of FileType as *note type: 611. argument

   - bpo-35621(29): Support running asyncio subprocesses when execution
     event loop in a thread on UNIX.

   - bpo-36520(30): Lengthy email headers with UTF-8 characters are now
     properly encoded when they are folded.  Patch by Jeffrey Kintscher.

   - bpo-30835(31): Fixed a bug in email parsing where a message with
     invalid bytes in content-transfer-encoding of a multipart message
     can cause an AttributeError.  Patch by Andrew Donnellan.

   - bpo-35805(32): Add parser for Message-ID header and add it to
     default HeaderRegistry.  This should prevent folding of Message-ID
     using RFC 2048 encoded words.

   - bpo-35070(33): posix.getgrouplist() now works correctly when the
     user belongs to NGROUPS_MAX supplemental groups.  Patch by Jeffrey
     Kintscher.

   - bpo-32627(34): Fix compile error when ‘_uuid’ headers conflicting
     included.

   - bpo-11122(35): Distutils won’t check for rpmbuild in specified
     paths only.

   - bpo-4963(36): Fixed non-deterministic behavior related to mimetypes
     extension mapping and module reinitialization.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37440

   (2) https://bugs.python.org/issue37437

   (3) https://bugs.python.org/issue37428

   (4) https://bugs.python.org/issue37420

   (5) https://bugs.python.org/issue37412

   (6) https://www.python.org/dev/peps/pep-0529

   (7) https://bugs.python.org/issue29412

   (8) https://bugs.python.org/issue36546

   (9) https://bugs.python.org/issue37394

   (10) https://bugs.python.org/issue33972

   (11) https://bugs.python.org/issue37280

   (12) https://bugs.python.org/issue37279

   (13) https://bugs.python.org/issue19865

   (14) https://bugs.python.org/issue37210

   (15) https://bugs.python.org/issue35922

   (16) https://bugs.python.org/issue35766

   (17) https://bugs.python.org/issue36607

   (18) https://bugs.python.org/issue18748

   (19) https://bugs.python.org/issue36402

   (20) https://bugs.python.org/issue34886

   (21) https://bugs.python.org/issue37173

   (22) https://bugs.python.org/issue37178

   (23) https://bugs.python.org/issue37178

   (24) https://bugs.python.org/issue37163

   (25) https://bugs.python.org/issue37165

   (26) https://bugs.python.org/issue34767

   (27) https://bugs.python.org/issue37158

   (28) https://bugs.python.org/issue37150

   (29) https://bugs.python.org/issue35621

   (30) https://bugs.python.org/issue36520

   (31) https://bugs.python.org/issue30835

   (32) https://bugs.python.org/issue35805

   (33) https://bugs.python.org/issue35070

   (34) https://bugs.python.org/issue32627

   (35) https://bugs.python.org/issue11122

   (36) https://bugs.python.org/issue4963


File: python.info,  Node: 文档<20>,  Next: 测试<15>,  Prev: 库<24>,  Up: Python 3 8 0 beta 2

1.18.25.4 文档
..............

   - bpo-34903(1): Documented that in *note
     datetime.datetime.strptime(): fbf, the leading zero in some
     two-digit formats is optional.  Patch by Mike Gleen.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34903


File: python.info,  Node: 测试<15>,  Next: 构建<13>,  Prev: 文档<20>,  Up: Python 3 8 0 beta 2

1.18.25.5 测试
..............

   - bpo-37421(1): test_distutils.test_build_ext() is now able to remove
     the temporary directory on Windows: don’t import the newly built C
     extension ("xx") in the current process, but test it in a separated
     process.

   - bpo-37421(2): test_concurrent_futures now cleans up multiprocessing
     to remove immediately temporary directories created by
     multiprocessing.util.get_temp_dir().

   - bpo-37421(3): test_winconsoleio doesn’t leak a temporary file
     anymore: use tempfile.TemporaryFile() to remove it when the test
     completes.

   - bpo-37421(4): multiprocessing tests now explicitly call
     ‘_run_finalizers()’ to immediately remove temporary directories
     created by tests.

   - bpo-37199(5): Fix test failures when IPv6 is unavailable or
     disabled.

   - bpo-37335(6): Remove no longer necessary code from c locale
     coercion tests

   - bpo-37421(7): Fix test_shutil to no longer leak temporary files.

   - bpo-37411(8): Fix test_wsgiref.testEnviron() to no longer depend on
     the environment variables (don’t fail if "X" variable is set).

   - bpo-37400(9): Fix test_os.test_chown(): use os.getgroups() rather
     than grp.getgrall() to get groups.  Rename also the test to
     test_chown_gid().

   - bpo-37359(10): Add –cleanup option to python3 -m test to remove
     ‘test_python_*’ directories of previous failed jobs.  Add "make
     cleantest" to run ‘python3 -m test --cleanup’.

   - bpo-37362(11): test_gdb no longer fails if it gets an "unexpected"
     message on stderr: it now ignores stderr.  The purpose of test_gdb
     is to test that python-gdb.py commands work as expected, not to
     test gdb.

   - bpo-35998(12): Avoid TimeoutError in test_asyncio:
     test_start_tls_server_1()

   - bpo-37278(13): Fix test_asyncio ProactorLoopCtrlC: join the thread
     to prevent leaking a running thread and leaking a reference.

   - bpo-37261(14): Fix *note test.support.catch_unraisable_exception():
     fc1.: its __exit__() method now ignores unraisable exception raised
     when clearing its ‘unraisable’ attribute.

   - bpo-37169(15): Rewrite ‘_PyObject_IsFreed()’ unit tests.

   - bpo-37153(16): ‘test_venv.test_mutiprocessing()’ now explicitly
     calls ‘pool.terminate()’ to wait until the pool completes.

   - bpo-28009(17): Modify the test_uuid logic to test when a program is
     available AND can be used to obtain a MACADDR as basis for an UUID.
     Patch by M. Felt

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37421

   (2) https://bugs.python.org/issue37421

   (3) https://bugs.python.org/issue37421

   (4) https://bugs.python.org/issue37421

   (5) https://bugs.python.org/issue37199

   (6) https://bugs.python.org/issue37335

   (7) https://bugs.python.org/issue37421

   (8) https://bugs.python.org/issue37411

   (9) https://bugs.python.org/issue37400

   (10) https://bugs.python.org/issue37359

   (11) https://bugs.python.org/issue37362

   (12) https://bugs.python.org/issue35998

   (13) https://bugs.python.org/issue37278

   (14) https://bugs.python.org/issue37261

   (15) https://bugs.python.org/issue37169

   (16) https://bugs.python.org/issue37153

   (17) https://bugs.python.org/issue28009


File: python.info,  Node: 构建<13>,  Next: Windows<17>,  Prev: 测试<15>,  Up: Python 3 8 0 beta 2

1.18.25.6 构建
..............

   - bpo-37189(1): Many ‘PyRun_XXX()’ functions like *note
     PyRun_String(): fc3. were no longer exported in ‘libpython38.dll’
     by mistake.  Export them again to fix the ABI compatibiliy.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37189


File: python.info,  Node: Windows<17>,  Next: macOS<13>,  Prev: 构建<13>,  Up: Python 3 8 0 beta 2

1.18.25.7 Windows
.................

   - bpo-10945(1): 正式取消对在非Windows系统上创建 bdist_wininst 安装程
     序的支持。

   - bpo-37369(2): Fixes path for *note sys.executable: 275. when
     running from the Microsoft Store.

   - bpo-37351(3): Removes libpython38.a from standard Windows
     distribution.

   - bpo-35360(4): 更新 Windows 构建以使用 SQLite 3.28.0.

   - bpo-37267(5): On Windows, *note os.dup(): fa4. no longer creates an
     inheritable fd when handling a character file.

   - bpo-36779(6): Ensure ‘time.tzname’ is correct on Windows when the
     active code page is set to CP_UTF7 or CP_UTF8.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10945

   (2) https://bugs.python.org/issue37369

   (3) https://bugs.python.org/issue37351

   (4) https://bugs.python.org/issue35360

   (5) https://bugs.python.org/issue37267

   (6) https://bugs.python.org/issue36779


File: python.info,  Node: macOS<13>,  Next: IDLE<22>,  Prev: Windows<17>,  Up: Python 3 8 0 beta 2

1.18.25.8 macOS
...............

   - bpo-34602(1): Avoid test suite failures on macOS by no longer
     calling resource.setrlimit to increase the process stack size limit
     at runtime.  The runtime change is no longer needed since the
     interpreter is being built with a larger default stack size.

   - bpo-35360(2): 更新macOS安装程序以使用SQLite 3.28.0.

   - bpo-34631(3): 在MacOS安装程序中将OpenSSL更新为1.1.1c。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34602

   (2) https://bugs.python.org/issue35360

   (3) https://bugs.python.org/issue34631


File: python.info,  Node: IDLE<22>,  Next: C API<11>,  Prev: macOS<13>,  Up: Python 3 8 0 beta 2

1.18.25.9 IDLE
..............

   - bpo-37325(1): Fix tab focus traversal order for help source and
     custom run dialogs.

   - bpo-37321(2): Both subprocess connection error messages now refer
     to the ’Startup failure’ section of the IDLE doc.

   - bpo-37177(3): Properly ’attach’ search dialogs to their main window
     so that they behave like other dialogs and do not get hidden behind
     their main window.

   - bpo-37039(4): Adjust "Zoom Height" to individual screens by
     momemtarily maximizing the window on first use with a particular
     screen.  Changing screen settings may invalidate the saved height.
     While a window is maximized, "Zoom Height" has no effect.

   - bpo-35763(5): Make calltip reminder about ’/’ meaning
     positional-only less obtrusive by only adding it when there is room
     on the first line.

   - bpo-5680(6): Add ’Run...  Customized’ to the Run menu to run a
     module with customized settings.  Any ’command line arguments’
     entered are added to sys.argv.  One can suppress the normal Shell
     main module restart.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37325

   (2) https://bugs.python.org/issue37321

   (3) https://bugs.python.org/issue37177

   (4) https://bugs.python.org/issue37039

   (5) https://bugs.python.org/issue35763

   (6) https://bugs.python.org/issue5680


File: python.info,  Node: C API<11>,  Prev: IDLE<22>,  Up: Python 3 8 0 beta 2

1.18.25.10 C API
................

   - bpo-36763(1): Add ‘PyConfig_SetWideStringList()’ function.

   - bpo-28805(2): The *note METH_FASTCALL: fc8. calling convention has
     been documented.

   - bpo-37221(3): ‘tp_print’ is put back at the end of the
     ‘PyTypeObject’ structure to restore support for old code (in
     particular generated by Cython) setting ‘tp_print = 0’.  Note that
     ‘tp_print’ will be removed entirely in Python 3.9.

   - bpo-37221(4): The new function *note PyCode_NewWithPosOnlyArgs():
     272. allows to create code objects like *note PyCode_New(): 273,
     but with an extra `posonlyargcount' parameter for indicating the
     number of positonal-only arguments.

   - bpo-37215(5): Fix dtrace issue introduce by bpo-36842(6)

   - bpo-37191(7): Python.h does not need compiler support for
     intermingled declarations (GCC’s ‘-Wdeclaration-after-statement’),
     which were added in 3.8.0 Beta 1.  Note that in Python 3.9,
     intermingled declarations will be needed again.

   - bpo-37170(8): Fix the cast on error in *note
     PyLong_AsUnsignedLongLongMask(): fc9.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36763

   (2) https://bugs.python.org/issue28805

   (3) https://bugs.python.org/issue37221

   (4) https://bugs.python.org/issue37221

   (5) https://bugs.python.org/issue37215

   (6) https://bugs.python.org/issue36842

   (7) https://bugs.python.org/issue37191

   (8) https://bugs.python.org/issue37170


File: python.info,  Node: Python 3 8 0 beta 1,  Next: Python 3 8 0 alpha 4,  Prev: Python 3 8 0 beta 2,  Up: 更新日志

1.18.26 Python 3.8.0 beta 1
---------------------------

`发布日期: 2019-06-04'

* Menu:

* 安全: 安全<18>.
* 核心与内置: 核心与内置<25>.
* 库: 库<25>.
* 文档: 文档<21>.
* 测试: 测试<16>.
* 构建: 构建<14>.
* Windows: Windows<18>.
* macOS: macOS<14>.
* IDLE: IDLE<23>.
* 工具/示例: 工具/示例<9>.
* C API: C API<12>.


File: python.info,  Node: 安全<18>,  Next: 核心与内置<25>,  Up: Python 3 8 0 beta 1

1.18.26.1 安全
..............

   - bpo-35907(1): CVE-2019-9948: Avoid file reading by disallowing
     ‘local-file://’ and ‘local_file://’ URL schemes in
     ‘URLopener().open()’ and ‘URLopener().retrieve()’ of *note
     urllib.request: 121.

   - bpo-33529(2): Prevent fold function used in email header encoding
     from entering infinite loop when there are too many non-ASCII
     characters in a header.

   - bpo-33164(3): Updated blake2 implementation which uses secure
     memset implementation provided by platform.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35907

   (2) https://bugs.python.org/issue33529

   (3) https://bugs.python.org/issue33164


File: python.info,  Node: 核心与内置<25>,  Next: 库<25>,  Prev: 安全<18>,  Up: Python 3 8 0 beta 1

1.18.26.2 核心与内置
....................

   - bpo-35814(1): Allow unpacking in the right hand side of annotated
     assignments.  In particular, ‘t: Tuple[int, ...] = x, y, *z’ is now
     allowed.

   - bpo-37126(2): All structseq objects are now tracked by the garbage
     collector.  Patch by Pablo Galindo.

   - bpo-37122(3): Make the `co_argcount' attribute of code objects
     represent the total number of positional arguments (including
     positional-only arguments).  The value of `co_posonlyargcount' can
     be used to distinguish which arguments are positional only, and the
     difference (`co_argcount' - `co_posonlyargcount') is the number of
     positional-or-keyword arguments.  Patch by Pablo Galindo.

   - bpo-20092(4): Constructors of *note int: 185, *note float: 188. and
     *note complex: 18a. will now use the *note __index__(): 18b.
     special method, if available and the corresponding method *note
     __int__(): 18c, *note __float__(): 18d. or *note __complex__():
     18e. is not available.

   - bpo-37087(5): Add native thread ID (TID) support to OpenBSD.

   - bpo-26219(6): Implemented per opcode cache mechanism and
     ‘LOAD_GLOBAL’ instruction use it.  ‘LOAD_GLOBAL’ is now about 40%
     faster.  Contributed by Yury Selivanov, and Inada Naoki.

   - bpo-37072(7): Fix crash in PyAST_FromNodeObject() when flags is
     NULL.

   - bpo-37029(8): Freeing a great many small objects could take time
     quadratic in the number of arenas, due to using linear search to
     keep ‘obmalloc.c’’s list of usable arenas sorted by order of number
     of free memory pools.  This is accomplished without search now,
     leaving the worst-case time linear in the number of arenas.  For
     programs where this quite visibly matters (typically with more than
     100 thousand small objects alive simultaneously), this can greatly
     reduce the time needed to release their memory.

   - bpo-26423(9): Fix possible overflow in ‘wrap_lenfunc()’ when
     ‘sizeof(long) < sizeof(Py_ssize_t)’ (e.g., 64-bit Windows).

   - bpo-37050(10): Improve the AST for "debug" f-strings, which use ’=’
     to print out the source of the expression being evaluated.  Delete
     expr_text from the FormattedValue node, and instead use a Constant
     string node (possibly merged with adjacent constant expressions
     inside the f-string).

   - bpo-22385(11): The *note bytes.hex: 63a, *note bytearray.hex: 63b,
     and *note memoryview.hex: 63c. methods as well as the *note
     binascii.hexlify: fcd. and ‘b2a_hex’ functions now have the ability
     to include an optional separator between hex bytes.  This
     functionality was inspired by MicroPython’s hexlify implementation.

   - bpo-26836(12): Add *note os.memfd_create(): 1f1.

   - bpo-37032(13): Added new ‘replace()’ method to the code type (*note
     types.CodeType: 199.).

   - bpo-37007(14): Implement *note socket.if_nameindex(): 221, *note
     socket.if_nametoindex(): 222, and *note socket.if_indextoname():
     223. on Windows.

   - bpo-36829(15): *note PyErr_WriteUnraisable(): fce. now creates a
     traceback object if there is no current traceback.  Moreover, call
     *note PyErr_NormalizeException(): fcf. and *note
     PyException_SetTraceback(): fd0. to normalize the exception value.
     Ignore any error.

   - bpo-36878(16): Only accept text after ‘# type: ignore’ if the first
     character is ASCII. This is to disallow things like ‘# type:
     ignoreé’.

   - bpo-36878(17): Store text appearing after a ‘# type: ignore’
     comment in the AST. For example a type ignore like ‘# type:
     ignore[E1000]’ will have the string ‘"[E1000]"’ stored in its AST
     node.

   - bpo-2180(18): Treat line continuation at EOF as a ‘SyntaxError’ by
     Anthony Sottile.

   - bpo-36907(19): Fix a crash when calling a C function with a keyword
     dict (‘f(**kwargs)’) and changing the dict ‘kwargs’ while that
     function is running.

   - bpo-36946(20): Fix possible signed integer overflow when handling
     slices.

   - bpo-36826(21): Add NamedExpression kind support to ast_unparse.c

   - bpo-1875(22): A *note SyntaxError: 460. is now raised if a code
     blocks that will be optimized away (e.g.  if conditions that are
     always false) contains syntax errors.  Patch by Pablo Galindo.

   - bpo-36027(23): Allow computation of modular inverses via
     three-argument ‘pow’: the second argument is now permitted to be
     negative in the case where the first and third arguments are
     relatively prime.

   - bpo-36861(24): Update the Unicode database to version 12.1.0.

   - bpo-28866(25): Avoid caching attributes of classes which type
     defines mro() to avoid a hard cache invalidation problem.

   - bpo-36851(26): The ‘FrameType’ stack is now correctly cleaned up if
     the execution ends with a return and the stack is not empty.

   - bpo-34616(27): The ‘compile()’ builtin functions now support the
     ‘ast.PyCF_ALLOW_TOP_LEVEL_AWAIT’ flag, which allow to compile
     sources that contains top-level ‘await’, ‘async with’ or ‘async
     for’.  This is useful to evaluate async-code from with an already
     async functions; for example in a custom REPL.

   - bpo-36842(28): Implement PEP 578, adding sys.audit, io.open_code
     and related APIs.

   - bpo-27639(29): Correct return type for UserList slicing operations.
     Patch by Michael Blahay, Erick Cervantes, and vaultah

   - bpo-36737(30): Move PyRuntimeState.warnings into per-interpreter
     state (via "module state").

   - bpo-36793(31): Removed ‘__str__’ implementations from builtin types
     *note bool: 184, *note int: 185, *note float: 188, *note complex:
     18a. and few classes from the standard library.  They now inherit
     ‘__str__()’ from *note object: 2b1.

   - bpo-36817(32): Add a ‘=’ feature f-strings for debugging.  This can
     precede ‘!s’, ‘!r’, or ‘!a’.  It produces the text of the
     expression, followed by an equal sign, followed by the repr of the
     value of the expression.  So ‘f'{3*9+15=}'’ would be equal to the
     string ‘'3*9+15=42'’.  If ‘=’ is specified, the default conversion
     is set to ‘!r’, unless a format spec is given, in which case the
     formatting behavior is unchanged, and __format__ will be used.

   - bpo-24048(33): Save the live exception during import.c’s
     ‘remove_module()’.

   - bpo-27987(34): pymalloc returns memory blocks aligned by 16 bytes,
     instead of 8 bytes, on 64-bit platforms to conform x86-64 ABI.
     Recent compilers assume this alignment more often.  Patch by Inada
     Naoki.

   - bpo-36601(35): A long-since-meaningless check for ‘getpid() ==
     main_pid’ was removed from Python’s internal C signal handler.

   - bpo-36594(36): Fix incorrect use of ‘%p’ in format strings.  Patch
     by Zackery Spytz.

   - bpo-36045(37): builtins.help() now prefixes ‘async’ for async
     functions

   - bpo-36084(38): Add native thread ID (TID) to threading.Thread
     objects (supported platforms: Windows, FreeBSD, Linux, macOS)

   - bpo-36035(39): Added fix for broken symlinks in combination with
     pathlib

   - bpo-35983(40): Added new trashcan macros to deal with a double
     deallocation that could occur when the ‘tp_dealloc’ of a subclass
     calls the ‘tp_dealloc’ of a base class and that base class uses the
     trashcan mechanism.  Patch by Jeroen Demeyer.

   - bpo-20602(41): Do not clear *note sys.flags: b44. and *note
     sys.float_info: fd1. during shutdown.  Patch by Zackery Spytz.

   - bpo-26826(42): Expose ‘copy_file_range()’ as a low level API in the
     *note os: c5. module.

   - bpo-32388(43): Remove cross-version binary compatibility
     requirement in tp_flags.

   - bpo-31862(44): Port binascii to PEP 489 multiphase initialization.
     Patch by Marcel Plch.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35814

   (2) https://bugs.python.org/issue37126

   (3) https://bugs.python.org/issue37122

   (4) https://bugs.python.org/issue20092

   (5) https://bugs.python.org/issue37087

   (6) https://bugs.python.org/issue26219

   (7) https://bugs.python.org/issue37072

   (8) https://bugs.python.org/issue37029

   (9) https://bugs.python.org/issue26423

   (10) https://bugs.python.org/issue37050

   (11) https://bugs.python.org/issue22385

   (12) https://bugs.python.org/issue26836

   (13) https://bugs.python.org/issue37032

   (14) https://bugs.python.org/issue37007

   (15) https://bugs.python.org/issue36829

   (16) https://bugs.python.org/issue36878

   (17) https://bugs.python.org/issue36878

   (18) https://bugs.python.org/issue2180

   (19) https://bugs.python.org/issue36907

   (20) https://bugs.python.org/issue36946

   (21) https://bugs.python.org/issue36826

   (22) https://bugs.python.org/issue1875

   (23) https://bugs.python.org/issue36027

   (24) https://bugs.python.org/issue36861

   (25) https://bugs.python.org/issue28866

   (26) https://bugs.python.org/issue36851

   (27) https://bugs.python.org/issue34616

   (28) https://bugs.python.org/issue36842

   (29) https://bugs.python.org/issue27639

   (30) https://bugs.python.org/issue36737

   (31) https://bugs.python.org/issue36793

   (32) https://bugs.python.org/issue36817

   (33) https://bugs.python.org/issue24048

   (34) https://bugs.python.org/issue27987

   (35) https://bugs.python.org/issue36601

   (36) https://bugs.python.org/issue36594

   (37) https://bugs.python.org/issue36045

   (38) https://bugs.python.org/issue36084

   (39) https://bugs.python.org/issue36035

   (40) https://bugs.python.org/issue35983

   (41) https://bugs.python.org/issue20602

   (42) https://bugs.python.org/issue26826

   (43) https://bugs.python.org/issue32388

   (44) https://bugs.python.org/issue31862


File: python.info,  Node: 库<25>,  Next: 文档<21>,  Prev: 核心与内置<25>,  Up: Python 3 8 0 beta 1

1.18.26.3 库
............

   - bpo-37128(1): Added *note math.perm(): 1e7.

   - bpo-37120(2): Add SSLContext.num_tickets to control the number of
     TLSv1.3 session tickets.

   - bpo-12202(3): Fix the error handling in *note
     msilib.SummaryInformation.GetProperty(): fd3.  Patch by Zackery
     Spytz.

   - bpo-26835(4): The fcntl module now contains file sealing constants
     for sealing of memfds.

   - bpo-29262(5): Add ‘get_origin()’ and ‘get_args()’ introspection
     helpers to ‘typing’ module.

   - bpo-12639(6): *note msilib.Directory.start_component(): fd4. no
     longer fails if `keyfile' is not ‘None’.

   - bpo-36999(7): Add the ‘asyncio.Task.get_coro()’ method to publicly
     expose the tasks’s coroutine object.

   - bpo-35246(8): Make *note asyncio.create_subprocess_exec(): 292.
     accept path-like arguments.

   - bpo-35279(9): Change default `max_workers' of ‘ThreadPoolExecutor’
     from ‘cpu_count() * 5’ to ‘min(32, cpu_count() + 4))’.  Previous
     value was unreasonably large on many cores machines.

   - bpo-37076(10): *note _thread.start_new_thread(): fd5. now logs
     uncaught exception raised by the function using *note
     sys.unraisablehook(): 22e, rather than *note sys.excepthook(): e6b,
     so the hook gets access to the function which raised the exception.

   - bpo-33725(11): On macOS, the *note multiprocessing: b8. module now
     uses `spawn' start method by default.

   - bpo-37054(12): Fix destructor ‘_pyio.BytesIO’ and
     ‘_pyio.TextIOWrapper’: initialize their ‘_buffer’ attribute as soon
     as possible (in the class body), because it’s used by ‘__del__()’
     which calls ‘close()’.

   - bpo-37058(13): PEP 544: Add ‘Protocol’ and ‘@runtime_checkable’ to
     the ‘typing’ module.

   - bpo-36933(14): The functions ‘sys.set_coroutine_wrapper’ and
     ‘sys.get_coroutine_wrapper’ that were deprecated and marked for
     removal in 3.8 have been removed.

   - bpo-37047(15): Handle late binding and attribute access in *note
     unittest.mock.AsyncMock: 249. setup for autospeccing.  Document
     newly implemented async methods in *note unittest.mock.MagicMock:
     78e.

   - bpo-37049(16): PEP 589: Add ‘TypedDict’ to the ‘typing’ module.

   - bpo-37046(17): PEP 586: Add ‘Literal’ to the ‘typing’ module.

   - bpo-37045(18): PEP 591: Add ‘Final’ qualifier and ‘@final’
     decorator to the ‘typing’ module.

   - bpo-37035(19): Don’t log OSError based exceptions if a fatal error
     has occurred in asyncio transport.  Peer can generate almost any
     OSError, user cannot avoid these exceptions by fixing own code.
     Errors are still propagated to user code, it’s just logging them is
     pointless and pollute asyncio logs.

   - bpo-37001(20): *note symtable.symtable(): fd6. now accepts the same
     input types for source code as the built-in *note compile(): 1b5.
     function.  Patch by Dino Viehland.

   - bpo-37028(21): Implement asyncio REPL

   - bpo-37027(22): Return safe to use proxy socket object from
     transport.get_extra_info(’socket’)

   - bpo-32528(23): Make asyncio.CancelledError a BaseException.

     This will address the common mistake many asyncio users make: an
     "except Exception" clause breaking Tasks cancellation.

     In addition to this change, we stop inheriting asyncio.TimeoutError
     and asyncio.InvalidStateError from their concurrent.futures.*
     counterparts.  There’s no point for these exceptions to share the
     inheritance chain.

   - bpo-1230540(24): Add a new *note threading.excepthook(): 232.
     function which handles uncaught *note threading.Thread.run(): 233.
     exception.  It can be overridden to control how uncaught *note
     threading.Thread.run(): 233. exceptions are handled.

   - bpo-36996(25): Handle *note unittest.mock.patch(): 791. used as a
     decorator on async functions.

   - bpo-37008(26): Add support for calling *note next(): 68b. with the
     mock resulting from *note unittest.mock.mock_open(): fd7.

   - bpo-27737(27): Allow whitespace only header encoding in
     ‘email.header’ - by Batuhan Taskaya

   - bpo-36969(28): PDB command ‘args’ now display positional only
     arguments.  Patch contributed by Rémi Lapeyre.

   - bpo-36969(29): PDB command ‘args’ now display keyword only
     arguments.  Patch contributed by Rémi Lapeyre.

   - bpo-36983(30): Add missing names to ‘typing.__all__’: ‘ChainMap’,
     ‘ForwardRef’, ‘OrderedDict’ - by Anthony Sottile.

   - bpo-36972(31): Add SupportsIndex protocol to the typing module to
     allow type checking to detect classes that can be passed to *note
     hex(): c6e, *note oct(): c6d. and *note bin(): c48.

   - bpo-32972(32): Implement ‘unittest.IsolatedAsyncioTestCase’ to help
     testing asyncio-based code.

   - bpo-36952(33): *note fileinput.input(): 2ae. and *note
     fileinput.FileInput: 27f. `bufsize' argument has been removed (was
     deprecated and ignored since Python 3.6), and as a result the
     `mode' and `openhook' arguments have been made keyword-only.

   - bpo-36952(34): Starting with Python 3.3, importing ABCs from *note
     collections: 1e. is deprecated, and import should be done from
     *note collections.abc: 1f.  Still being able to import from *note
     collections: 1e. was marked for removal in 3.8, but has been
     delayed to 3.9; documentation and ‘DeprecationWarning’ clarified.

   - bpo-36949(35): Implement __repr__ for WeakSet objects.

   - bpo-36948(36): Fix *note NameError: d83. in *note
     urllib.request.URLopener.retrieve(): fd8.  Patch by Karthikeyan
     Singaravelan.

   - bpo-33524(37): Fix the folding of email header when the
     max_line_length is 0 or None and the header contains non-ascii
     characters.  Contributed by Licht Takeuchi (@Licht-T).

   - bpo-24564(38): *note shutil.copystat(): a7f. now ignores *note
     errno.EINVAL: fd9. on *note os.setxattr(): a56. which may occur
     when copying files on filesystems without extended attributes
     support.

     Original patch by Giampaolo Rodola, updated by Ying Wang.

   - bpo-36888(39): Python child processes can now access the status of
     their parent process using multiprocessing.process.parent_process

   - bpo-36921(40): Deprecate ‘@coroutine’ for sake of ‘async def’.

   - bpo-25652(41): Fix bug in ‘__rmod__’ of ‘UserString’ - by Batuhan
     Taskaya.

   - bpo-36916(42): Remove a message about an unhandled exception in a
     task when writer.write() is used without await and writer.drain()
     fails with an exception.

   - bpo-36889(43): Introduce ‘asyncio.Stream’ class that merges *note
     asyncio.StreamReader: fda. and *note asyncio.StreamWriter: fdb.
     functionality.  ‘asyncio.Stream’ can work in readonly, writeonly
     and readwrite modes.  Provide ‘asyncio.connect()’,
     ‘asyncio.connect_unix()’, ‘asyncio.connect_read_pipe()’ and
     ‘asyncio.connect_write_pipe()’ factories to open ‘asyncio.Stream’
     connections.  Provide ‘asyncio.StreamServer’ and ‘UnixStreamServer’
     to serve servers with asyncio.Stream API. Modify *note
     asyncio.create_subprocess_shell(): 293. and *note
     asyncio.create_subprocess_exec(): 292. to use ‘asyncio.Stream’
     instead of deprecated ‘StreamReader’ and ‘StreamWriter’.  Deprecate
     *note asyncio.StreamReader: fda. and *note asyncio.StreamWriter:
     fdb.  Deprecate usage of private classes, e.g.
     ‘asyncio.FlowControlMixing’ and ‘asyncio.StreamReaderProtocol’
     outside of asyncio package.

   - bpo-36845(44): Added validation of integer prefixes to the
     construction of IP networks and interfaces in the ipaddress module.

   - bpo-23378(45): Add an extend action to argparser.

   - bpo-36867(46): Fix a bug making a SharedMemoryManager instance and
     its parent process use two separate resource_tracker processes.

   - bpo-23896(47): Adds a grammar to lib2to3.pygram that contains exec
     as a function not as statement.

   - bpo-36895(48): The function ‘time.clock()’ was deprecated in 3.3 in
     favor of ‘time.perf_counter()’ and marked for removal in 3.8, it
     has removed.

   - bpo-35545(49): Fix asyncio discarding IPv6 scopes when ensuring
     hostname resolutions internally

   - bpo-36887(50): Add new function *note math.isqrt(): 1e9. to compute
     integer square roots.

   - bpo-34632(51): Introduce the ‘importlib.metadata’ module with
     (provisional) support for reading metadata from third-party
     packages.

   - bpo-36878(52): When using ‘type_comments=True’ in *note ast.parse:
     1a2, treat ‘# type: ignore’ followed by a non-alphanumeric
     character and then arbitrary text as a type ignore, instead of
     requiring nothing but whitespace or another comment.  This is to
     permit formations such as ‘# type: ignore[E1000]’.

   - bpo-36778(53): ‘cp65001’ encoding (Windows code page 65001) becomes
     an alias to ‘utf_8’ encoding.

   - bpo-36867(54): The multiprocessing.resource_tracker replaces the
     multiprocessing.semaphore_tracker module.  Other than semaphores,
     resource_tracker also tracks shared_memory segments.

   - bpo-30262(55): The ‘Cache’ and ‘Statement’ objects of the *note
     sqlite3: f3. module are not exposed to the user.  Patch by Aviv
     Palivoda.

   - bpo-24538(56): In *note shutil.copystat(): a7f, first copy extended
     file attributes and then file permissions, since extended
     attributes can only be set on the destination while it is still
     writeable.

   - bpo-36829(57): Add new *note sys.unraisablehook(): 22e. function
     which can be overridden to control how "unraisable exceptions" are
     handled.  It is called when an exception has occurred but there is
     no way for Python to handle it.  For example, when a destructor
     raises an exception or during garbage collection (*note
     gc.collect(): 22f.).

   - bpo-36832(58): Introducing ‘zipfile.Path’, a pathlib-compatible
     wrapper for traversing zip files.

   - bpo-36814(59): Fix an issue where os.posix_spawnp() would
     incorrectly raise a TypeError when file_actions is None.

   - bpo-33110(60): Handle exceptions raised by functions added by
     concurrent.futures add_done_callback correctly when the Future has
     already completed.

   - bpo-26903(61): Limit ‘max_workers’ in ‘ProcessPoolExecutor’ to 61
     to work around a WaitForMultipleObjects limitation.

   - bpo-36813(62): Fix *note QueueListener: 71b. to call
     ‘queue.task_done()’ upon stopping.  Patch by Bar Harel.

   - bpo-36806(63): Forbid creation of asyncio stream objects like
     StreamReader, StreamWriter, Process, and their protocols outside of
     asyncio package.

   - bpo-36802(64): Provide both sync and async calls for
     StreamWriter.write() and StreamWriter.close()

   - bpo-36801(65): Properly handle SSL connection closing in asyncio
     StreamWriter.drain() call.

   - bpo-36785(66): Implement PEP 574 (pickle protocol 5 with
     out-of-band buffers).

   - bpo-36772(67): functools.lru_cache() can now be used as a straight
     decorator in addition to its existing usage as a function that
     returns a decorator.

   - bpo-6584(68): Add a *note BadGzipFile: 1d3. exception to the *note
     gzip: 8c. module.

   - bpo-36748(69): Optimized write buffering in C implementation of
     ‘TextIOWrapper’.  Writing ASCII string to ‘TextIOWrapper’ with
     ascii, latin1, or utf-8 encoding is about 20% faster.  Patch by
     Inada Naoki.

   - bpo-8138(70): Don’t mark ‘wsgiref.simple_server.SimpleServer’ as
     multi-threaded since ‘wsgiref.simple_server.WSGIServer’ is
     single-threaded.

   - bpo-22640(71): *note py_compile.compile(): 216. now supports silent
     mode.  Patch by Joannah Nanjekye

   - bpo-29183(72): Fix double exceptions in *note
     wsgiref.handlers.BaseHandler: fdc. by calling its ‘close()’ method
     only when no exception is raised.

   - bpo-36548(73): Improved the repr of regular expression flags.

   - bpo-36542(74): The signature of Python functions can now be
     overridden by specifying the ‘__text_signature__’ attribute.

   - bpo-36533(75): Reinitialize logging.Handler locks in forked child
     processes instead of attempting to acquire them all in the parent
     before forking only to be released in the child process.  The
     acquire/release pattern was leading to deadlocks in code that has
     implemented any form of chained logging handlers that depend upon
     one another as the lock acquisition order cannot be guaranteed.

   - bpo-35252(76): Throw a TypeError instead of an AssertionError when
     using an invalid type annotation with singledispatch.

   - bpo-35900(77): Allow reduction methods to return a 6-item tuple
     where the 6th item specifies a custom state-setting method that’s
     called instead of the regular ‘__setstate__’ method.

   - bpo-35900(78): enable custom reduction callback registration for
     functions and classes in _pickle.c, using the new Pickler’s
     attribute ‘reducer_override’

   - bpo-36368(79): Fix a bug crashing SharedMemoryManager instances in
     interactive sessions after a ctrl-c (KeyboardInterrupt) was sent

   - bpo-31904(80): Fix mmap fail for VxWorks

   - bpo-27497(81): *note csv.DictWriter.writeheader(): b83. now returns
     the return value of the underlying ‘csv.Writer.writerow()’ method.
     Patch contributed by Ashish Nitin Patil.

   - bpo-36239(82): Parsing .mo files now ignores comments starting and
     ending with #-#-#-#-#.

   - bpo-26707(83): Enable plistlib to read and write binary plist files
     that were created as a KeyedArchive file.  Specifically, this
     allows the plistlib to process 0x80 tokens as UID objects.

   - bpo-31904(84): Add posix module support for VxWorks.

   - bpo-35125(85): Asyncio: Remove inner callback on outer cancellation
     in shield

   - bpo-35721(86): Fix ‘asyncio.SelectorEventLoop.subprocess_exec()’
     leaks file descriptors if ‘Popen’ fails and called with
     ‘stdin=subprocess.PIPE’.  Patch by Niklas Fiekas.

   - bpo-31855(87): *note unittest.mock.mock_open(): fd7. results now
     respects the argument of read([size]).  Patch contributed by Rémi
     Lapeyre.

   - bpo-35431(88): Implement *note math.comb(): 1e8. that returns
     binomial coefficient, that computes the number of ways to choose k
     items from n items without repetition and without order.  Patch by
     Yash Aggarwal and Keller Fuchs.

   - bpo-26660(89): Fixed permission errors in *note TemporaryDirectory:
     bd0. clean up.  Previously ‘TemporaryDirectory.cleanup()’ failed
     when non-writeable or non-searchable files or directories were
     created inside a temporary directory.

   - bpo-34271(90): Add debugging helpers to ssl module.  It’s now
     possible to dump key material and to trace TLS protocol.  The
     default and stdlib contexts also support SSLKEYLOGFILE env var.

   - bpo-26467(91): Added AsyncMock to support using unittest to mock
     asyncio coroutines.  Patch by Lisa Roach.

   - bpo-33569(92): dataclasses.InitVar: Exposes the type used to create
     the init var.

   - bpo-34424(93): Fix serialization of messages containing encoded
     strings when the policy.linesep is set to a multi-character string.
     Patch by Jens Troeger.

   - bpo-34303(94): Performance of *note functools.reduce(): c77. is
     slightly improved.  Patch by Sergey Fedoseev.

   - bpo-33361(95): Fix a bug in *note codecs.StreamRecoder: fdd. where
     seeking might leave old data in a buffer and break subsequent read
     calls.  Patch by Ammar Askar.

   - bpo-22454(96): The *note shlex: e9. module now exposes *note
     shlex.join(): 218, the inverse of *note shlex.split(): 219.  Patch
     by Bo Bayles.

   - bpo-31922(97):
     ‘asyncio.AbstractEventLoop.create_datagram_endpoint()’: Do not
     connect UDP socket when broadcast is allowed.  This allows to
     receive replies after a UDP broadcast.

   - bpo-24882(98): Change ThreadPoolExecutor to use existing idle
     threads before spinning up new ones.

   - bpo-31961(99): Added support for bytes and path-like objects in
     *note subprocess.Popen(): 2ba. on Windows.  The `args' parameter
     now accepts a *note path-like object: 373. if `shell' is ‘False’
     and a sequence containing bytes and path-like objects.  The
     `executable' parameter now accepts a bytes and *note path-like
     object: 373.  The `cwd' parameter now accepts a bytes object.
     Based on patch by Anders Lorentsen.

   - bpo-33123(100): *note pathlib.Path.unlink: fde. now accepts a
     `missing_ok' parameter to avoid a *note FileNotFoundError: 7c9.
     from being raised.  Patch by Robert Buchholz.

   - bpo-32941(101): Allow *note mmap.mmap: 1ed. objects to access the
     madvise() system call (through *note mmap.mmap.madvise(): 1ee.).

   - bpo-22102(102): Added support for ZIP files with disks set to 0.
     Such files are commonly created by builtin tools on Windows when
     use ZIP64 extension.  Patch by Francisco Facioni.

   - bpo-32515(103): trace.py can now run modules via python3 -m trace
     -t –module module_name

   - bpo-32299(104): Changed *note unittest.mock.patch.dict(): fdf. to
     return the patched dictionary when used as context manager.  Patch
     by Vadim Tsander.

   - bpo-27141(105): Added a ‘__copy__()’ to ‘collections.UserList’ and
     ‘collections.UserDict’ in order to correctly implement shallow
     copying of the objects.  Patch by Bar Harel.

   - bpo-31829(106): ‘\r’, ‘\0’ and ‘\x1a’ (end-of-file on Windows) are
     now escaped in protocol 0 pickles of Unicode strings.  This allows
     to load them without loss from files open in text mode in Python 2.

   - bpo-23395(107): ‘_thread.interrupt_main()’ now avoids setting the
     Python error status if the ‘SIGINT’ signal is ignored or not
     handled by Python.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37128

   (2) https://bugs.python.org/issue37120

   (3) https://bugs.python.org/issue12202

   (4) https://bugs.python.org/issue26835

   (5) https://bugs.python.org/issue29262

   (6) https://bugs.python.org/issue12639

   (7) https://bugs.python.org/issue36999

   (8) https://bugs.python.org/issue35246

   (9) https://bugs.python.org/issue35279

   (10) https://bugs.python.org/issue37076

   (11) https://bugs.python.org/issue33725

   (12) https://bugs.python.org/issue37054

   (13) https://bugs.python.org/issue37058

   (14) https://bugs.python.org/issue36933

   (15) https://bugs.python.org/issue37047

   (16) https://bugs.python.org/issue37049

   (17) https://bugs.python.org/issue37046

   (18) https://bugs.python.org/issue37045

   (19) https://bugs.python.org/issue37035

   (20) https://bugs.python.org/issue37001

   (21) https://bugs.python.org/issue37028

   (22) https://bugs.python.org/issue37027

   (23) https://bugs.python.org/issue32528

   (24) https://bugs.python.org/issue1230540

   (25) https://bugs.python.org/issue36996

   (26) https://bugs.python.org/issue37008

   (27) https://bugs.python.org/issue27737

   (28) https://bugs.python.org/issue36969

   (29) https://bugs.python.org/issue36969

   (30) https://bugs.python.org/issue36983

   (31) https://bugs.python.org/issue36972

   (32) https://bugs.python.org/issue32972

   (33) https://bugs.python.org/issue36952

   (34) https://bugs.python.org/issue36952

   (35) https://bugs.python.org/issue36949

   (36) https://bugs.python.org/issue36948

   (37) https://bugs.python.org/issue33524

   (38) https://bugs.python.org/issue24564

   (39) https://bugs.python.org/issue36888

   (40) https://bugs.python.org/issue36921

   (41) https://bugs.python.org/issue25652

   (42) https://bugs.python.org/issue36916

   (43) https://bugs.python.org/issue36889

   (44) https://bugs.python.org/issue36845

   (45) https://bugs.python.org/issue23378

   (46) https://bugs.python.org/issue36867

   (47) https://bugs.python.org/issue23896

   (48) https://bugs.python.org/issue36895

   (49) https://bugs.python.org/issue35545

   (50) https://bugs.python.org/issue36887

   (51) https://bugs.python.org/issue34632

   (52) https://bugs.python.org/issue36878

   (53) https://bugs.python.org/issue36778

   (54) https://bugs.python.org/issue36867

   (55) https://bugs.python.org/issue30262

   (56) https://bugs.python.org/issue24538

   (57) https://bugs.python.org/issue36829

   (58) https://bugs.python.org/issue36832

   (59) https://bugs.python.org/issue36814

   (60) https://bugs.python.org/issue33110

   (61) https://bugs.python.org/issue26903

   (62) https://bugs.python.org/issue36813

   (63) https://bugs.python.org/issue36806

   (64) https://bugs.python.org/issue36802

   (65) https://bugs.python.org/issue36801

   (66) https://bugs.python.org/issue36785

   (67) https://bugs.python.org/issue36772

   (68) https://bugs.python.org/issue6584

   (69) https://bugs.python.org/issue36748

   (70) https://bugs.python.org/issue8138

   (71) https://bugs.python.org/issue22640

   (72) https://bugs.python.org/issue29183

   (73) https://bugs.python.org/issue36548

   (74) https://bugs.python.org/issue36542

   (75) https://bugs.python.org/issue36533

   (76) https://bugs.python.org/issue35252

   (77) https://bugs.python.org/issue35900

   (78) https://bugs.python.org/issue35900

   (79) https://bugs.python.org/issue36368

   (80) https://bugs.python.org/issue31904

   (81) https://bugs.python.org/issue27497

   (82) https://bugs.python.org/issue36239

   (83) https://bugs.python.org/issue26707

   (84) https://bugs.python.org/issue31904

   (85) https://bugs.python.org/issue35125

   (86) https://bugs.python.org/issue35721

   (87) https://bugs.python.org/issue31855

   (88) https://bugs.python.org/issue35431

   (89) https://bugs.python.org/issue26660

   (90) https://bugs.python.org/issue34271

   (91) https://bugs.python.org/issue26467

   (92) https://bugs.python.org/issue33569

   (93) https://bugs.python.org/issue34424

   (94) https://bugs.python.org/issue34303

   (95) https://bugs.python.org/issue33361

   (96) https://bugs.python.org/issue22454

   (97) https://bugs.python.org/issue31922

   (98) https://bugs.python.org/issue24882

   (99) https://bugs.python.org/issue31961

   (100) https://bugs.python.org/issue33123

   (101) https://bugs.python.org/issue32941

   (102) https://bugs.python.org/issue22102

   (103) https://bugs.python.org/issue32515

   (104) https://bugs.python.org/issue32299

   (105) https://bugs.python.org/issue27141

   (106) https://bugs.python.org/issue31829

   (107) https://bugs.python.org/issue23395


File: python.info,  Node: 文档<21>,  Next: 测试<16>,  Prev: 库<25>,  Up: Python 3 8 0 beta 1

1.18.26.4 文档
..............

   - bpo-36896(1): Clarify that some types have unstable constructor
     signature between Python versions.

   - bpo-36686(2): Improve documentation of the stdin, stdout, and
     stderr arguments of the ‘asyncio.subprocess_exec’ function to
     specify which values are supported.  Also mention that decoding as
     text is not supported.

     Add a few tests to verify that the various values passed to the
     std* arguments actually work.

   - bpo-36984(3): Improve version added references in ‘typing’ module -
     by Anthony Sottile.

   - bpo-36868(4): What’s new now mentions
     SSLContext.hostname_checks_common_name instead of
     SSLContext.host_flags.

   - bpo-35924(5): Add a note to the ‘curses.addstr()’ documentation to
     warn that multiline strings can cause segfaults because of an
     ncurses bug.

   - bpo-36783(6): Added C API Documentation for Time_FromTimeAndFold
     and PyDateTime_FromDateAndTimeAndFold as per PEP 495.  Patch by
     Edison Abahurire.

   - bpo-36797(7): More of the legacy distutils documentation has been
     either pruned, or else more clearly marked as being retained solely
     until the setuptools documentation covers it independently.

   - bpo-22865(8): Add detail to the documentation on the *note
     pty.spawn: 8a1. function.

   - bpo-35397(9): Remove deprecation and document
     urllib.parse.unwrap().  Patch contributed by Rémi Lapeyre.

   - bpo-32995(10): Added the context variable in glossary.

   - bpo-33519(11): Clarify that *note copy(): 26. is not part of the
     ‘MutableSequence’ ABC.

   - bpo-33482(12): Make ‘codecs.StreamRecoder.writelines’ take a list
     of bytes.

   - bpo-25735(13): Added documentation for func factorial to indicate
     that returns integer values

   - bpo-20285(14): Expand object.__doc__ (docstring) to make it
     clearer.  Modify pydoc.py so that help(object) lists object methods
     (for other classes, help omits methods of the object base class.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36896

   (2) https://bugs.python.org/issue36686

   (3) https://bugs.python.org/issue36984

   (4) https://bugs.python.org/issue36868

   (5) https://bugs.python.org/issue35924

   (6) https://bugs.python.org/issue36783

   (7) https://bugs.python.org/issue36797

   (8) https://bugs.python.org/issue22865

   (9) https://bugs.python.org/issue35397

   (10) https://bugs.python.org/issue32995

   (11) https://bugs.python.org/issue33519

   (12) https://bugs.python.org/issue33482

   (13) https://bugs.python.org/issue25735

   (14) https://bugs.python.org/issue20285


File: python.info,  Node: 测试<16>,  Next: 构建<14>,  Prev: 文档<21>,  Up: Python 3 8 0 beta 1

1.18.26.5 测试
..............

   - bpo-37069(1): Modify test_coroutines, test_cprofile,
     test_generators, test_raise, test_ssl and test_yield_from to use
     *note test.support.catch_unraisable_exception(): fc1. rather than
     *note test.support.captured_stderr(): fe2.

   - bpo-37098(2): Fix test_memfd_create on older Linux Kernels.

   - bpo-37081(3): 使用OpenSSL 1.1.1c进行测试

   - bpo-36829(4): Add *note test.support.catch_unraisable_exception():
     fc1.: context manager catching unraisable exception using *note
     sys.unraisablehook(): 22e.

   - bpo-36915(5): The main regrtest process now always removes all
     temporary directories of worker processes even if they crash or if
     they are killed on KeyboardInterrupt (CTRL+c).

   - bpo-36719(6): "python3 -m test -jN ..."  now continues the
     execution of next tests when a worker process crash (CHILD_ERROR
     state).  Previously, the test suite stopped immediately.  Use
     –failfast to stop at the first error.

   - bpo-36816(7): Update Lib/test/selfsigned_pythontestdotnet.pem to
     match self-signed.pythontest.net’s new TLS certificate.

   - bpo-35925(8): Skip httplib and nntplib networking tests when they
     would otherwise fail due to a modern OS or distro with a default
     OpenSSL policy of rejecting connections to servers with weak
     certificates.

   - bpo-36782(9): Add tests for several C API functions in the *note
     datetime: 31. module.  Patch by Edison Abahurire.

   - bpo-36342(10): Fix test_multiprocessing in test_venv if platform
     lacks functioning sem_open.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37069

   (2) https://bugs.python.org/issue37098

   (3) https://bugs.python.org/issue37081

   (4) https://bugs.python.org/issue36829

   (5) https://bugs.python.org/issue36915

   (6) https://bugs.python.org/issue36719

   (7) https://bugs.python.org/issue36816

   (8) https://bugs.python.org/issue35925

   (9) https://bugs.python.org/issue36782

   (10) https://bugs.python.org/issue36342


File: python.info,  Node: 构建<14>,  Next: Windows<18>,  Prev: 测试<16>,  Up: Python 3 8 0 beta 1

1.18.26.6 构建
..............

   - bpo-36721(1): To embed Python into an application, a new ‘--embed’
     option must be passed to ‘python3-config --libs --embed’ to get
     ‘-lpython3.8’ (link the application to libpython).  To support both
     3.8 and older, try ‘python3-config --libs --embed’ first and
     fallback to ‘python3-config --libs’ (without ‘--embed’) if the
     previous command fails.

     增加一个 pkg-config ‘python-3.8-embed’ 模块用来将 Python 嵌入到一个
     应用中: ‘pkg-config python-3.8-embed --libs’ 包含 ‘-lpython3.8’。 要
     同时支持 3.8 和旧版本，请先尝试 ‘pkg-config python-X.Y-embed
     --libs’ 并在此命令失败时回退到 ‘pkg-config python-X.Y --libs’ (即不
     带 ‘--embed’) （请将 ‘X.Y’ 替换为 Python 版本号）。

     On the other hand, ‘pkg-config python3.8 --libs’ no longer contains
     ‘-lpython3.8’.  C extensions must not be linked to libpython
     (except on Android, case handled by the script); this change is
     backward incompatible on purpose.

   - bpo-36786(2): "make install" now runs compileall in parallel.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36721

   (2) https://bugs.python.org/issue36786


File: python.info,  Node: Windows<18>,  Next: macOS<14>,  Prev: 构建<14>,  Up: Python 3 8 0 beta 1

1.18.26.7 Windows
.................

   - bpo-36965(1): include of STATUS_CONTROL_C_EXIT without depending on
     MSC compiler

   - bpo-35926(2): 在Windows安装程序中将OpenSSL更新为1.1.1b

   - bpo-29883(3): Add Windows support for UDP transports for the
     Proactor Event Loop.  Patch by Adam Meily.

   - bpo-33407(4): The ‘Py_DEPRECATED()’ macro has been implemented for
     MSVC.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36965

   (2) https://bugs.python.org/issue35926

   (3) https://bugs.python.org/issue29883

   (4) https://bugs.python.org/issue33407


File: python.info,  Node: macOS<14>,  Next: IDLE<23>,  Prev: Windows<18>,  Up: Python 3 8 0 beta 1

1.18.26.8 macOS
...............

   - bpo-36231(1): Support building Python on macOS without /usr/include
     installed.  As of macOS 10.14, system header files are only
     available within an SDK provided by either the Command Line Tools
     or the Xcode app.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36231


File: python.info,  Node: IDLE<23>,  Next: 工具/示例<9>,  Prev: macOS<14>,  Up: Python 3 8 0 beta 1

1.18.26.9 IDLE
..............

   - bpo-35610(1): Replace now redundant .context_use_ps1 with
     .prompt_last_line.  This finishes change started in bpo-31858(2).

   - bpo-37038(3): Make idlelib.run runnable; add test clause.

   - bpo-36958(4): Print any argument other than None or int passed to
     SystemExit or sys.exit().

   - bpo-36807(5): When saving a file, call os.fsync() so bits are
     flushed to e.g.  USB drive.

   - bpo-32411(6): In browser.py, remove extraneous sorting by line
     number since dictionary was created in line number order.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35610

   (2) https://bugs.python.org/issue31858

   (3) https://bugs.python.org/issue37038

   (4) https://bugs.python.org/issue36958

   (5) https://bugs.python.org/issue36807

   (6) https://bugs.python.org/issue32411


File: python.info,  Node: 工具/示例<9>,  Next: C API<12>,  Prev: IDLE<23>,  Up: Python 3 8 0 beta 1

1.18.26.10 工具/示例
....................

   - bpo-37053(1): Handle strings like u"bar" correctly in
     Tools/parser/unparse.py.  Patch by Chih-Hsuan Yen.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37053


File: python.info,  Node: C API<12>,  Prev: 工具/示例<9>,  Up: Python 3 8 0 beta 1

1.18.26.11 C API
................

   - bpo-36763(1): Implement the PEP 587(2) "Python Initialization
     Configuration".

   - bpo-36379(3): Fix crashes when attempting to use the `modulo'
     parameter when ‘__ipow__’ is implemented in C.

   - bpo-37107(4): Update *note PyObject_CallMethodObjArgs(): fe9. and
     ‘_PyObject_CallMethodIdObjArgs’ to use ‘_PyObject_GetMethod’ to
     avoid creating a bound method object in many cases.  Patch by
     Michael J. Sullivan.

   - bpo-36974(5): Implement PEP 590(6): Vectorcall: a fast calling
     protocol for CPython.  This is a new protocol to optimize calls of
     custom callable objects.

   - bpo-36763(7): ‘Py_Main()’ now returns the exitcode rather than
     calling ‘Py_Exit(exitcode)’ when calling ‘PyErr_Print()’ if the
     current exception type is ‘SystemExit’.

   - bpo-36922(8): Add new type flag ‘Py_TPFLAGS_METHOD_DESCRIPTOR’ for
     objects behaving like unbound methods.  These are objects
     supporting the optimization given by the
     ‘LOAD_METHOD’/‘CALL_METHOD’ opcodes.  See PEP 590.

   - bpo-36728(9): The ‘PyEval_ReInitThreads()’ function has been
     removed from the C API. It should not be called explicitly: use
     *note PyOS_AfterFork_Child(): 2ce. instead.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36763

   (2) https://www.python.org/dev/peps/pep-0587

   (3) https://bugs.python.org/issue36379

   (4) https://bugs.python.org/issue37107

   (5) https://bugs.python.org/issue36974

   (6) https://www.python.org/dev/peps/pep-0590

   (7) https://bugs.python.org/issue36763

   (8) https://bugs.python.org/issue36922

   (9) https://bugs.python.org/issue36728


File: python.info,  Node: Python 3 8 0 alpha 4,  Next: Python 3 8 0 alpha 3,  Prev: Python 3 8 0 beta 1,  Up: 更新日志

1.18.27 Python 3.8.0 alpha 4
----------------------------

`发布日期: 2019-05-06'

* Menu:

* 安全: 安全<19>.
* 核心与内置: 核心与内置<26>.
* 库: 库<26>.
* 文档: 文档<22>.
* 测试: 测试<17>.
* 构建: 构建<15>.
* Windows: Windows<19>.
* macOS: macOS<15>.
* IDLE: IDLE<24>.
* 工具/示例: 工具/示例<10>.
* C API: C API<13>.


File: python.info,  Node: 安全<19>,  Next: 核心与内置<26>,  Up: Python 3 8 0 alpha 4

1.18.27.1 安全
..............

   - bpo-36742(1): 于函数 urlsplit() 中修复了对于预规格化字符的不当处理
     过程。

   - bpo-30458(2): Address CVE-2019-9740 by disallowing URL paths with
     embedded whitespace or control characters through into the
     underlying http client request.  Such potentially malicious header
     injection URLs now cause an http.client.InvalidURL exception to be
     raised.

   - bpo-35755(3): *note shutil.which(): eea. now uses
     ‘os.confstr("CS_PATH")’ if available and if the ‘PATH’ environment
     variable is not set.  Remove also the current directory from
     ‘posixpath.defpath’.  On Unix, *note shutil.which(): eea. and the
     *note subprocess: fa. module no longer search the executable in the
     current directory if the ‘PATH’ environment variable is not set.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36742

   (2) https://bugs.python.org/issue30458

   (3) https://bugs.python.org/issue35755


File: python.info,  Node: 核心与内置<26>,  Next: 库<26>,  Prev: 安全<19>,  Up: Python 3 8 0 alpha 4

1.18.27.2 核心与内置
....................

   - bpo-36722(1): In debug build, import now also looks for C
     extensions compiled in release mode and for C extensions compiled
     in the stable ABI.

   - bpo-32849(2): Fix Python Initialization code on FreeBSD to detect
     properly when stdin file descriptor (fd 0) is invalid.

   - bpo-36623(3): Remove parser headers and related function
     declarations that lack implementations after the removal of pgen.

   - bpo-20180(4): ‘dict.pop()’ is now up to 33% faster thanks to
     Argument Clinic.  Patch by Inada Naoki.

   - bpo-36611(5): Debug memory allocators: disable serialno field by
     default from debug hooks on Python memory allocators to reduce the
     memory footprint by 5%.  Enable *note tracemalloc: 115. to get the
     traceback where a memory block has been allocated when a fatal
     memory error is logged to decide where to put a breakpoint.
     Compile Python with ‘PYMEM_DEBUG_SERIALNO’ defined to get back the
     field.

   - bpo-36588(6): On AIX, *note sys.platform: 2b2. doesn’t contain the
     major version anymore.  Always return ‘'aix'’, instead of ‘'aix3'’
     ..  ‘'aix7'’.  Since older Python versions include the version
     number, it is recommended to always use
     ‘sys.platform.startswith('aix')’.  Contributed by M. Felt.

   - bpo-36549(7): Change str.capitalize to use titlecase for the first
     character instead of uppercase.

   - bpo-36540(8): Implement PEP 570(9) (Python positional-only
     parameters).  Patch by Pablo Galindo.

   - bpo-36475(10): *note PyEval_AcquireLock(): 2b3. and *note
     PyEval_AcquireThread(): 2b4. now terminate the current thread if
     called while the interpreter is finalizing, making them consistent
     with *note PyEval_RestoreThread(): 2b5, *note
     Py_END_ALLOW_THREADS(): 2b6, and *note PyGILState_Ensure(): 2b7.

   - bpo-36504(11): 在 _ctypes.c’s ‘PyCArrayType_new()’ 中修复了“有符号
     整数”类型的溢出。

   - bpo-20844(12): 修复了含有经编码的 cookie 和换行符的脚本位于 Windows
     平台可能运行失败的问题。

   - bpo-24214(13): 修复了UTF-8增量解码器对surrogatepass的错误回调方法的
     支持

   - bpo-36452(14): Changing ‘dict’ keys during iteration of the dict
     itself, ‘keys()’, ‘values()’, or ‘items()’ will now be detected in
     certain corner cases where keys are deleted/added so that the
     number of keys isn’t changed.  A *note RuntimeError: 2bb. will be
     raised after ‘len(dict)’ iterations.  Contributed by Thomas Perl.

   - bpo-36459(15): 修复了由于tokenizer.c中的 ‘tok_nextc()’ 方法可能导致
     的两次 ‘PyMem_FREE()’ 调用。

   - bpo-36433(16): 修复了位于 classmethoddescr_call 的类型错误信息

   - bpo-36430(17): 修复了函数 *note itertools.count(): c23. 中的潜在引
     用对象泄漏。

   - bpo-36440(18): Include node names in ‘ParserError’ messages,
     instead of numeric IDs.  Patch by A. Skrobov.

   - bpo-36143(19): Regenerate *note keyword: a7. from the Grammar and
     Tokens file using pgen.  Patch by Pablo Galindo.

   - bpo-18372(20): Add missing *note PyObject_GC_Track(): e4c. calls in
     the *note pickle: cb. module.  Patch by Zackery Spytz.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36722

   (2) https://bugs.python.org/issue32849

   (3) https://bugs.python.org/issue36623

   (4) https://bugs.python.org/issue20180

   (5) https://bugs.python.org/issue36611

   (6) https://bugs.python.org/issue36588

   (7) https://bugs.python.org/issue36549

   (8) https://bugs.python.org/issue36540

   (9) https://www.python.org/dev/peps/pep-0570

   (10) https://bugs.python.org/issue36475

   (11) https://bugs.python.org/issue36504

   (12) https://bugs.python.org/issue20844

   (13) https://bugs.python.org/issue24214

   (14) https://bugs.python.org/issue36452

   (15) https://bugs.python.org/issue36459

   (16) https://bugs.python.org/issue36433

   (17) https://bugs.python.org/issue36430

   (18) https://bugs.python.org/issue36440

   (19) https://bugs.python.org/issue36143

   (20) https://bugs.python.org/issue18372


File: python.info,  Node: 库<26>,  Next: 文档<22>,  Prev: 核心与内置<26>,  Up: Python 3 8 0 alpha 4

1.18.27.3 库
............

   - bpo-35952(1): Fix pythoninfo when the compiler is missing.

   - bpo-28238(2): The ‘.find*()’ methods of xml.etree.ElementTree can
     now search for wildcards like ‘{*}tag’ and ‘{ns}*’ that match a tag
     in any namespace or all tags in a namespace.  Patch by Stefan
     Behnel.

   - bpo-26978(3): ‘pathlib.path.link_to()’ is now implemented.  It
     creates a hard link pointing to a path.

   - bpo-1613500(4): *note fileinput.FileInput: 27f. now uses the input
     file mode to correctly set the output file mode (previously it was
     hardcoded to ‘'w'’) when ‘inplace=True’ is passed to its
     constructor.

   - bpo-36734(5): Fix compilation of ‘faulthandler.c’ on HP-UX.
     Initialize ‘stack_t current_stack’ to zero using ‘memset()’.

   - bpo-13611(6): The xml.etree.ElementTree packages gained support for
     C14N 2.0 serialisation.  Patch by Stefan Behnel.

   - bpo-36669(7): Add missing matrix multiplication operator support to
     weakref.proxy.

   - bpo-36676(8): The XMLParser() in xml.etree.ElementTree provides
     namespace prefix context to the parser target if it defines the
     callback methods "start_ns()" and/or "end_ns()".  Patch by Stefan
     Behnel.

   - bpo-36673(9): The TreeBuilder and XMLPullParser in
     xml.etree.ElementTree gained support for parsing comments and
     processing instructions.  Patch by Stefan Behnel.

   - bpo-36650(10): The C version of functools.lru_cache() was treating
     calls with an empty ‘**kwargs’ dictionary as being distinct from
     calls with no keywords at all.  This did not result in an incorrect
     answer, but it did trigger an unexpected cache miss.

   - bpo-28552(11): Fix *note distutils.sysconfig: 62. if *note
     sys.executable: 275. is ‘None’ or an empty string: use *note
     os.getcwd(): fee. to initialize ‘project_base’.  Fix also the
     distutils build command: don’t use *note sys.executable: 275. if it
     is ‘None’ or an empty string.

   - bpo-35755(12): *note shutil.which(): eea. and
     ‘distutils.spawn.find_executable()’ now use ‘os.confstr("CS_PATH")’
     if available instead of *note os.defpath: fef, if the ‘PATH’
     environment variable is not set.  Moreover, don’t use
     ‘os.confstr("CS_PATH")’ nor *note os.defpath: fef. if the ‘PATH’
     environment variable is set to an empty string.

   - bpo-25430(13): improve performance of ‘IPNetwork.__contains__()’

   - bpo-30485(14): Path expressions in xml.etree.ElementTree can now
     avoid explicit namespace prefixes for tags (or the "{namespace}tag"
     notation) by passing a default namespace with an empty string
     prefix.

   - bpo-36613(15): Fix *note asyncio: a. wait() not removing callback
     if exception

   - bpo-36598(16): Fix ‘isinstance’ check for Mock objects with spec
     when the code is executed under tracing.  Patch by Karthikeyan
     Singaravelan.

   - bpo-18748(17): In development mode (*note -X: 156. ‘dev’) and in
     debug build, the *note io.IOBase: 1dc. destructor now logs
     ‘close()’ exceptions.  These exceptions are silent by default in
     release mode.

   - bpo-36575(18): The ‘_lsprof’ module now uses internal timer same to
     ‘time.perf_counter()’ by default.  ‘gettimeofday(2)’ was used on
     Unix.  New timer has better resolution on most Unix platforms and
     timings are no longer impacted by system clock updates since
     ‘perf_counter()’ is monotonic.  Patch by Inada Naoki.

   - bpo-33461(19): ‘json.loads’ now emits ‘DeprecationWarning’ when
     ‘encoding’ option is specified.  Patch by Matthias Bussonnier.

   - bpo-36559(20): The random module now prefers the lean internal
     _sha512 module over hashlib for seed(version=2) to optimize import
     time.

   - bpo-17561(21): Set backlog=None as the default for
     socket.create_server.

   - bpo-34373(22): Fix *note time.mktime(): b6c. error handling on AIX
     for year before 1970.

   - bpo-36232(23): Improve error message when trying to open existing
     DBM database that actually doesn’t exist.  Patch by Marco Rougeth.

   - bpo-36546(24): Add statistics.quantiles()

   - bpo-36050(25): Optimized ‘http.client.HTTPResponse.read()’ for
     large response.  Patch by Inada Naoki.

   - bpo-36522(26): If `debuglevel' is set to >0 in *note http.client:
     94, print all values for headers with multiple values for the same
     header name.  Patch by Matt Houglum.

   - bpo-36492(27): Deprecated passing required arguments like `func' as
     keyword arguments in functions which should accept arbitrary
     keyword arguments and pass them to other function.  Arbitrary
     keyword arguments (even with names "self" and "func") can now be
     passed to these functions if the required arguments are passed as
     positional arguments.

   - bpo-27181(28): Add statistics.geometric_mean().

   - bpo-30427(29): ‘os.path.normcase()’ relies on ‘os.fspath()’ to
     check the type of its argument.  Redundant checks have been removed
     from its ‘posixpath.normcase()’ and ‘ntpath.normcase()’
     implementations.  Patch by Wolfgang Maier.

   - bpo-36385(30): Stop rejecting IPv4 octets for being ambiguously
     octal.  Leading zeros are ignored, and no longer are assumed to
     specify octal octets.  Octets are always decimal numbers.  Octets
     must still be no more than three digits, including leading zeroes.

   - bpo-36434(31): Errors during writing to a ZIP file no longer
     prevent to properly close it.

   - bpo-36407(32): Fixed wrong indentation writing for CDATA section in
     xml.dom.minidom.  Patch by Vladimir Surjaninov.

   - bpo-36326(33): inspect.getdoc() can now find docstrings for member
     objects when __slots__ is a dictionary.

   - bpo-36366(34): Calling ‘stop()’ on an unstarted or stopped *note
     unittest.mock.patch(): 791. object will now return *note None: 158.
     instead of raising *note RuntimeError: 2bb, making the method
     idempotent.  Patch by Karthikeyan Singaravelan.

   - bpo-36348(35): The ‘imap.IMAP4.logout()’ method no longer ignores
     silently arbitrary exceptions.

   - bpo-31904(36): Add time module support and fix test_time faiures
     for VxWorks.

   - bpo-36227(37): Added support for keyword arguments
     ‘default_namespace’ and ‘xml_declaration’ in functions
     ElementTree.tostring() and ElementTree.tostringlist().

   - bpo-36004(38): Added new alternate constructors *note
     datetime.date.fromisocalendar(): 1c5. and *note
     datetime.datetime.fromisocalendar(): 1c6, which construct date
     objects from ISO year, week number and weekday; these are the
     inverse of each class’s ‘isocalendar’ method.  Patch by Paul
     Ganssle.

   - bpo-35936(39): *note modulefinder: b5. no longer depends on the
     deprecated *note imp: 9a. module, and the initializer for *note
     modulefinder.ModuleFinder: ff0. now has immutable default
     arguments.  Patch by Brandt Bucher.

   - bpo-35376(40): *note modulefinder: b5. correctly handles modules
     that have the same name as a bad package.  Patch by Brandt Bucher.

   - bpo-17396(41): *note modulefinder: b5. no longer crashes when
     encountering syntax errors in followed imports.  Patch by Brandt
     Bucher.

   - bpo-35934(42): Added *note create_server(): 21f. and *note
     has_dualstack_ipv6(): 220. convenience functions to automate the
     necessary tasks usually involved when creating a server socket,
     including accepting both IPv4 and IPv6 connections on the same
     socket.  (Contributed by Giampaolo Rodola in bpo-17561(43).)

   - bpo-23078(44): Add support for *note classmethod(): 1d9. and *note
     staticmethod(): 1da. to *note unittest.mock.create_autospec(): f59.
     Initial patch by Felipe Ochoa.

   - bpo-35416(45): Fix potential resource warnings in distutils.  Patch
     by Mickaël Schoentgen.

   - bpo-25451(46): Add transparency methods to ‘tkinter.PhotoImage’.
     Patch by Zackery Spytz.

   - bpo-35082(47): Don’t return deleted attributes when calling dir on
     a *note unittest.mock.Mock: 24a.

   - bpo-34547(48): *note wsgiref.handlers.BaseHandler: fdc. now handles
     abrupt client connection terminations gracefully.  Patch by Petter
     Strandmark.

   - bpo-31658(49): *note xml.sax.parse(): ff1. now supports *note
     path-like: 373.  Patch by Mickaël Schoentgen.

   - bpo-34139(50): Remove stale unix datagram socket before binding

   - bpo-33530(51): Implemented Happy Eyeballs in
     ‘asyncio.create_connection()’.  Added two new arguments,
     `happy_eyeballs_delay' and `interleave', to specify Happy Eyeballs
     behavior.

   - bpo-33291(52): Do not raise AttributeError when calling the inspect
     functions isgeneratorfunction, iscoroutinefunction,
     isasyncgenfunction on a method created from an arbitrary callable.
     Instead, return False.

   - bpo-31310(53): Fix the multiprocessing.semaphore_tracker so it is
     reused by child processes

   - bpo-31292(54): 为包含 ‘include’ 指令的文件修复 ‘setup.py check
     --restructuredtext’。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35952

   (2) https://bugs.python.org/issue28238

   (3) https://bugs.python.org/issue26978

   (4) https://bugs.python.org/issue1613500

   (5) https://bugs.python.org/issue36734

   (6) https://bugs.python.org/issue13611

   (7) https://bugs.python.org/issue36669

   (8) https://bugs.python.org/issue36676

   (9) https://bugs.python.org/issue36673

   (10) https://bugs.python.org/issue36650

   (11) https://bugs.python.org/issue28552

   (12) https://bugs.python.org/issue35755

   (13) https://bugs.python.org/issue25430

   (14) https://bugs.python.org/issue30485

   (15) https://bugs.python.org/issue36613

   (16) https://bugs.python.org/issue36598

   (17) https://bugs.python.org/issue18748

   (18) https://bugs.python.org/issue36575

   (19) https://bugs.python.org/issue33461

   (20) https://bugs.python.org/issue36559

   (21) https://bugs.python.org/issue17561

   (22) https://bugs.python.org/issue34373

   (23) https://bugs.python.org/issue36232

   (24) https://bugs.python.org/issue36546

   (25) https://bugs.python.org/issue36050

   (26) https://bugs.python.org/issue36522

   (27) https://bugs.python.org/issue36492

   (28) https://bugs.python.org/issue27181

   (29) https://bugs.python.org/issue30427

   (30) https://bugs.python.org/issue36385

   (31) https://bugs.python.org/issue36434

   (32) https://bugs.python.org/issue36407

   (33) https://bugs.python.org/issue36326

   (34) https://bugs.python.org/issue36366

   (35) https://bugs.python.org/issue36348

   (36) https://bugs.python.org/issue31904

   (37) https://bugs.python.org/issue36227

   (38) https://bugs.python.org/issue36004

   (39) https://bugs.python.org/issue35936

   (40) https://bugs.python.org/issue35376

   (41) https://bugs.python.org/issue17396

   (42) https://bugs.python.org/issue35934

   (43) https://bugs.python.org/issue17561

   (44) https://bugs.python.org/issue23078

   (45) https://bugs.python.org/issue35416

   (46) https://bugs.python.org/issue25451

   (47) https://bugs.python.org/issue35082

   (48) https://bugs.python.org/issue34547

   (49) https://bugs.python.org/issue31658

   (50) https://bugs.python.org/issue34139

   (51) https://bugs.python.org/issue33530

   (52) https://bugs.python.org/issue33291

   (53) https://bugs.python.org/issue31310

   (54) https://bugs.python.org/issue31292


File: python.info,  Node: 文档<22>,  Next: 测试<17>,  Prev: 库<26>,  Up: Python 3 8 0 alpha 4

1.18.27.4 文档
..............

   - bpo-36625(1): Remove obsolete comments from docstrings in
     fractions.Fraction

   - bpo-30840(2): Document relative imports

   - bpo-36523(3): Add docstring for io.IOBase.writelines().

   - bpo-36425(4): 新增的文档翻译: 简体中文(5).

   - bpo-36345(6): Avoid the duplication of code from
     ‘Tools/scripts/serve.py’ in using the ‘literalinclude’ directive
     for the basic wsgiref-based web server in the documentation of
     *note wsgiref: 12d.  Contributed by Stéphane Wirtel.

   - bpo-36345(7): Using the code of the ‘Tools/scripts/serve.py’ script
     as an example in the *note wsgiref: 12d. documentation.
     Contributed by Stéphane Wirtel.

   - bpo-36157(8): Added Documention for PyInterpreterState_Main().

   - bpo-33043(9): Updates the docs.python.org page with the addition of
     a ’Contributing to Docs’ link at the end of the page (between
     ’Reporting Bugs’ and ’About Documentation’).  Updates the ’Found a
     Bug’ page with additional links and information in the
     Documentation Bugs section.

   - bpo-35581(10): @typing.type_check_only now allows type stubs to
     mark functions and classes not available during runtime.

   - bpo-33832(11): Add glossary entry for ’magic method’.

   - bpo-32913(12): Added re.Match.groupdict example to regex HOWTO.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36625

   (2) https://bugs.python.org/issue30840

   (3) https://bugs.python.org/issue36523

   (4) https://bugs.python.org/issue36425

   (5) https://docs.python.org/zh-cn/

   (6) https://bugs.python.org/issue36345

   (7) https://bugs.python.org/issue36345

   (8) https://bugs.python.org/issue36157

   (9) https://bugs.python.org/issue33043

   (10) https://bugs.python.org/issue35581

   (11) https://bugs.python.org/issue33832

   (12) https://bugs.python.org/issue32913


File: python.info,  Node: 测试<17>,  Next: 构建<15>,  Prev: 文档<22>,  Up: Python 3 8 0 alpha 4

1.18.27.5 测试
..............

   - bpo-36719(1): regrtest now always detects uncollectable objects.
     Previously, the check was only enabled by ‘--findleaks’.  The check
     now also works with ‘-jN/--multiprocess N’.  ‘--findleaks’ becomes
     a deprecated alias to ‘--fail-env-changed’.

   - bpo-36725(2): When using mulitprocessing mode (-jN), regrtest now
     better reports errors if a worker process fails, and it exits
     immediately on a worker thread failure or when interrupted.

   - bpo-36454(3): Change test_time.test_monotonic() to test only the
     lower bound of elapsed time after a sleep command rather than the
     upper bound.  This prevents unnecessary test failures on slow
     buildbots.  Patch by Victor Stinner.

   - bpo-32424(4): Improve test coverage for xml.etree.ElementTree.
     Patch by Gordon P. Hemsley.

   - bpo-32424(5): Fix typo in test_cyclic_gc() test for
     xml.etree.ElementTree.  Patch by Gordon P. Hemsley.

   - bpo-36635(6): Add a new ‘_testinternalcapi’ module to test the
     internal C API.

   - bpo-36629(7): Fix ‘test_imap4_host_default_value()’ of
     ‘test_imaplib’: catch also *note errno.ENETUNREACH: ff4. error.

   - bpo-36611(8): Fix ‘test_sys.test_getallocatedblocks()’ when *note
     tracemalloc: 115. is enabled.

   - bpo-36560(9): Fix reference leak hunting in regrtest: compute also
     deltas (of reference count, allocated memory blocks, file
     descriptor count) during warmup, to ensure that everything is
     initialized before starting to hunt reference leaks.

   - bpo-36565(10): Fix reference hunting (‘python3 -m test -R 3:3’)
     when Python has no built-in abc module.

   - bpo-31904(11): Port test_resource to VxWorks: skip tests cases
     setting RLIMIT_FSIZE and RLIMIT_CPU.

   - bpo-31904(12): Fix test_tabnanny on VxWorks: adjust ENOENT error
     message.

   - bpo-36436(13): Fix ‘_testcapi.pymem_buffer_overflow()’: handle
     memory allocation failure.

   - bpo-31904(14): Fix test_utf8_mode on VxWorks: Python always use
     UTF-8 on VxWorks.

   - bpo-36341(15): Fix tests that may fail with PermissionError upon
     calling bind() on AF_UNIX sockets.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36719

   (2) https://bugs.python.org/issue36725

   (3) https://bugs.python.org/issue36454

   (4) https://bugs.python.org/issue32424

   (5) https://bugs.python.org/issue32424

   (6) https://bugs.python.org/issue36635

   (7) https://bugs.python.org/issue36629

   (8) https://bugs.python.org/issue36611

   (9) https://bugs.python.org/issue36560

   (10) https://bugs.python.org/issue36565

   (11) https://bugs.python.org/issue31904

   (12) https://bugs.python.org/issue31904

   (13) https://bugs.python.org/issue36436

   (14) https://bugs.python.org/issue31904

   (15) https://bugs.python.org/issue36341


File: python.info,  Node: 构建<15>,  Next: Windows<19>,  Prev: 测试<17>,  Up: Python 3 8 0 alpha 4

1.18.27.6 构建
..............

   - bpo-36747(1): Remove the stale scriptsinstall Makefile target.

   - bpo-21536(2): On Unix, C extensions are no longer linked to
     libpython except on Android and Cygwin.

     通过共享库的 Python 构建的 C 扩展现在可以被静态链接的 Python 加载了
     。

     When Python is embedded, ‘libpython’ must not be loaded with
     ‘RTLD_LOCAL’, but ‘RTLD_GLOBAL’ instead.  Previously, using
     ‘RTLD_LOCAL’, it was already not possible to load C extensions
     which were not linked to ‘libpython’, such as C extensions of the
     standard library built by the ‘*shared*’ section of
     ‘Modules/Setup’.

     distutils，python-config 和 python-config.py 已被修改。

   - bpo-36707(3): ‘./configure --with-pymalloc’ no longer adds the ‘m’
     flag to SOABI (sys.implementation.cache_tag).  Enabling or
     disabling pymalloc has no impact on the ABI.

   - bpo-36635(4): Change ‘PyAPI_FUNC(type)’, ‘PyAPI_DATA(type)’ and
     ‘PyMODINIT_FUNC’ macros of ‘pyport.h’ when ‘Py_BUILD_CORE_MODULE’
     is defined.  The ‘Py_BUILD_CORE_MODULE’ define must be now be used
     to build a C extension as a dynamic library accessing Python
     internals: export the PyInit_xxx() function in DLL exports on
     Windows.

   - bpo-31904(5): Don’t build the ‘_crypt’ extension on VxWorks.

   - bpo-36618(6): Add ‘-fmax-type-align=8’ to CFLAGS when clang
     compiler is detected.  The pymalloc memory allocator aligns memory
     on 8 bytes.  On x86-64, clang expects alignment on 16 bytes by
     default and so uses MOVAPS instruction which can lead to
     segmentation fault.  Instruct clang that Python is limited to
     alignment on 8 bytes to use MOVUPS instruction instead: slower but
     don’t trigger a SIGSEGV if the memory is not aligned on 16 bytes.
     Sadly, the flag must be added to ‘CFLAGS’ and not just
     ‘CFLAGS_NODIST’, since third party C extensions can have the same
     issue.

   - bpo-36605(7): ‘make tags’ and ‘make TAGS’ now also parse
     ‘Modules/_io/*.c’ and ‘Modules/_io/*.h’.

   - bpo-36465(8): Release builds and debug builds are now ABI
     compatible: defining the ‘Py_DEBUG’ macro no longer implies the
     ‘Py_TRACE_REFS’ macro, which introduces the only ABI
     incompatibility.  The ‘Py_TRACE_REFS’ macro, which adds the
     ‘sys.getobjects()’ function and the *note PYTHONDUMPREFS: 15a.
     environment variable, can be set using the new ‘./configure
     --with-trace-refs’ build option.

   - bpo-36577(9): setup.py now correctly reports missing OpenSSL
     headers and libraries again.

   - bpo-36544(10): Fix regression introduced in bpo-36146(11)
     refactoring setup.py

   - bpo-36508(12): ‘python-config --ldflags’ no longer includes flags
     of the ‘LINKFORSHARED’ variable.  The ‘LINKFORSHARED’ variable must
     only be used to build executables.

   - bpo-36503(13): Remove references to "aix3" and "aix4".  Patch by M.
     Felt.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36747

   (2) https://bugs.python.org/issue21536

   (3) https://bugs.python.org/issue36707

   (4) https://bugs.python.org/issue36635

   (5) https://bugs.python.org/issue31904

   (6) https://bugs.python.org/issue36618

   (7) https://bugs.python.org/issue36605

   (8) https://bugs.python.org/issue36465

   (9) https://bugs.python.org/issue36577

   (10) https://bugs.python.org/issue36544

   (11) https://bugs.python.org/issue36146

   (12) https://bugs.python.org/issue36508

   (13) https://bugs.python.org/issue36503


File: python.info,  Node: Windows<19>,  Next: macOS<15>,  Prev: 构建<15>,  Up: Python 3 8 0 alpha 4

1.18.27.7 Windows
.................

   - bpo-35920(1): Added platform.win32_edition() and
     platform.win32_is_iot().  Added support for cross-compiling
     packages for Windows ARM32.  Skip tests that are not expected to
     work on Windows IoT Core ARM32.

   - bpo-36649(2): Remove trailing spaces for registry keys when
     installed via the Store.

   - bpo-34144(3): Fixed activate.bat to correctly update codepage when
     chcp.com returns dots in output.  Patch by Lorenz Mende.

   - bpo-36509(4): Added preset-iot layout for Windows IoT ARM
     containers.  This layout doesn’t contain UI components like tkinter
     or IDLE. It also doesn’t contain files to support on-target builds
     since Windows ARM32 builds must be cross-compiled when using MSVC.

   - bpo-35941(5): enum_certificates function of the ssl module now
     returns certificates from all available certificate stores inside
     windows in a query instead of returning only certificates from the
     system wide certificate store.  This includes certificates from
     these certificate stores: local machine, local machine enterprise,
     local machine group policy, current user, current user group
     policy, services, users.  ssl.enum_crls() function is changed in
     the same way to return all certificate revocation lists inside the
     windows certificate revocation list stores.

   - bpo-36441(6): Fixes creating a venv when debug binaries are
     installed.

   - bpo-36085(7): Enable better DLL resolution on Windows by using safe
     DLL search paths and adding *note os.add_dll_directory(): 1c3.

   - bpo-36010(8): Add the venv standard library module to the nuget
     distribution for Windows.

   - bpo-29515(9): Add the following socket module constants on Windows:
     IPPROTO_AH IPPROTO_CBT IPPROTO_DSTOPTS IPPROTO_EGP IPPROTO_ESP
     IPPROTO_FRAGMENT IPPROTO_GGP IPPROTO_HOPOPTS IPPROTO_ICLFXBM
     IPPROTO_ICMPV6 IPPROTO_IDP IPPROTO_IGMP IPPROTO_IGP IPPROTO_IPV4
     IPPROTO_IPV6 IPPROTO_L2TP IPPROTO_MAX IPPROTO_ND IPPROTO_NONE
     IPPROTO_PGM IPPROTO_PIM IPPROTO_PUP IPPROTO_RDP IPPROTO_ROUTING
     IPPROTO_SCTP IPPROTO_ST

   - bpo-35947(10): Added current version of libffi to
     cpython-source-deps.  Change _ctypes to use current version of
     libffi on Windows.

   - bpo-34060(11): Report system load when running test suite on
     Windows.  Patch by Ammar Askar.  Based on prior work by Jeremy
     Kloth.

   - bpo-31512(12): With the Windows 10 Creators Update, non-elevated
     users can now create symlinks as long as the computer has Developer
     Mode enabled.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35920

   (2) https://bugs.python.org/issue36649

   (3) https://bugs.python.org/issue34144

   (4) https://bugs.python.org/issue36509

   (5) https://bugs.python.org/issue35941

   (6) https://bugs.python.org/issue36441

   (7) https://bugs.python.org/issue36085

   (8) https://bugs.python.org/issue36010

   (9) https://bugs.python.org/issue29515

   (10) https://bugs.python.org/issue35947

   (11) https://bugs.python.org/issue34060

   (12) https://bugs.python.org/issue31512


File: python.info,  Node: macOS<15>,  Next: IDLE<24>,  Prev: Windows<19>,  Up: Python 3 8 0 alpha 4

1.18.27.8 macOS
...............

   - bpo-34602(1): Avoid failures setting macOS stack resource limit
     with resource.setrlimit.  This reverts an earlier fix for
     bpo-18075(2) which forced a non-default stack size when building
     the interpreter executable on macOS.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34602

   (2) https://bugs.python.org/issue18075


File: python.info,  Node: IDLE<24>,  Next: 工具/示例<10>,  Prev: macOS<15>,  Up: Python 3 8 0 alpha 4

1.18.27.9 IDLE
..............

   - bpo-36429(1): Fix starting IDLE with pyshell.  Add idlelib.pyshell
     alias at top; remove pyshell alias at bottom.  Remove obsolete
     __name__==’__main__’ command.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36429


File: python.info,  Node: 工具/示例<10>,  Next: C API<13>,  Prev: IDLE<24>,  Up: Python 3 8 0 alpha 4

1.18.27.10 工具/示例
....................

   - bpo-14546(1): Fix the argument handling in Tools/scripts/lll.py.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14546


File: python.info,  Node: C API<13>,  Prev: 工具/示例<10>,  Up: Python 3 8 0 alpha 4

1.18.27.11 C API
................

   - bpo-36763(1): Fix memory leak in *note
     Py_SetStandardStreamEncoding(): 92d.: release memory if the
     function is called twice.

   - bpo-36641(2): ‘PyDoc_VAR(name)’ and ‘PyDoc_STRVAR(name,str)’ now
     create ‘static const char name[]’ instead of ‘static char name[]’.
     Patch by Inada Naoki.

   - bpo-36389(3): Change the value of ‘CLEANBYTE’, ‘DEADDYTE’ and
     ‘FORBIDDENBYTE’ internal constants used by debug hooks on Python
     memory allocators (*note PyMem_SetupDebugHooks(): 512. function).
     Byte patterns ‘0xCB’, ‘0xDB’ and ‘0xFB’ have been replaced with
     ‘0xCD’, ‘0xDD’ and ‘0xFD’ to use the same values than Windows CRT
     debug ‘malloc()’ and ‘free()’.

   - bpo-36443(4): Since Python 3.7.0, calling *note Py_DecodeLocale():
     444. before *note Py_Initialize(): 441. produces mojibake if the
     ‘LC_CTYPE’ locale is coerced and/or if the UTF-8 Mode is enabled by
     the user configuration.  The LC_CTYPE coercion and UTF-8 Mode are
     now disabled by default to fix the mojibake issue.  They must now
     be enabled explicitly (opt-in) using the new ‘_Py_PreInitialize()’
     API with ‘_PyPreConfig’.

   - bpo-36025(5): Fixed an accidental change to the datetime C API
     where the arguments to the *note PyDate_FromTimestamp(): ffb.
     function were incorrectly interpreted as a single timestamp rather
     than an arguments tuple, which causes existing code to start
     raising *note TypeError: 193.  The backwards-incompatible change
     was only present in alpha releases of Python 3.8.  Patch by Paul
     Ganssle.

   - bpo-35810(6): Modify ‘PyObject_Init’ to correctly increase the
     refcount of heap- allocated Type objects.  Also fix the refcounts
     of the heap-allocated types that were either doing this manually or
     not decreasing the type’s refcount in tp_dealloc

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36763

   (2) https://bugs.python.org/issue36641

   (3) https://bugs.python.org/issue36389

   (4) https://bugs.python.org/issue36443

   (5) https://bugs.python.org/issue36025

   (6) https://bugs.python.org/issue35810


File: python.info,  Node: Python 3 8 0 alpha 3,  Next: Python 3 8 0 alpha 2,  Prev: Python 3 8 0 alpha 4,  Up: 更新日志

1.18.28 Python 3.8.0 alpha 3
----------------------------

`发布日期： 2019-03-25'

* Menu:

* 安全: 安全<20>.
* 核心与内置: 核心与内置<27>.
* 库: 库<27>.
* 文档: 文档<23>.
* 测试: 测试<18>.
* 构建: 构建<16>.
* Windows: Windows<20>.
* IDLE: IDLE<25>.
* 工具/示例: 工具/示例<11>.
* C API: C API<14>.


File: python.info,  Node: 安全<20>,  Next: 核心与内置<27>,  Up: Python 3 8 0 alpha 3

1.18.28.1 安全
..............

   - bpo-36216(1): Changes urlsplit() to raise ValueError when the URL
     contains characters that decompose under IDNA encoding
     (NFKC-normalization) into characters that affect how the URL is
     parsed.

   - bpo-35121(2): Don’t send cookies of domain A without Domain
     attribute to domain B when domain A is a suffix match of domain B
     while using a cookiejar with *note
     http.cookiejar.DefaultCookiePolicy: ffe. policy.  Patch by
     Karthikeyan Singaravelan.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36216

   (2) https://bugs.python.org/issue35121


File: python.info,  Node: 核心与内置<27>,  Next: 库<27>,  Prev: 安全<20>,  Up: Python 3 8 0 alpha 3

1.18.28.2 核心与内置
....................

   - bpo-36421(1): Fix a possible double decref in _ctypes.c’s
     ‘PyCArrayType_new()’.

   - bpo-36412(2): Fix a possible crash when creating a new dictionary.

   - bpo-36398(3): Fix a possible crash in ‘structseq_repr()’.

   - bpo-36256(4): Fix bug in parsermodule when parsing a state in a DFA
     that has two or more arcs with labels of the same type.  Patch by
     Pablo Galindo.

   - bpo-36365(5): repr(structseq) is no longer limited to 512 bytes.

   - bpo-36374(6): Fix a possible null pointer dereference in
     ‘merge_consts_recursive()’.  Patch by Zackery Spytz.

   - bpo-36236(7): 在 Python 初始化时，如果当前目录被移除，则它将不再会
     被添加到 *note sys.path: 490. 中。

   - bpo-36352(8): Python initialization now fails with an error, rather
     than silently truncating paths, if a path is too long.

   - bpo-36301(9): Python initialization now fails if decoding
     ‘pybuilddir.txt’ configuration file fails at startup.

   - bpo-36333(10): Fix leak in _PyRuntimeState_Fini.  Contributed by
     Stéphane Wirtel.

   - bpo-36332(11): The builtin *note compile(): 1b5. can now handle AST
     objects that contain assignment expressions.  Patch by Pablo
     Galindo.

   - bpo-36282(12): Improved error message for too much positional
     arguments in some builtin functions.

   - bpo-30040(13): New empty dict uses fewer memory for now.  It used
     more memory than empty dict created by ‘dict.clear()’.  And empty
     dict creation and deletion is about 2x faster.  Patch by Inada
     Naoki.

   - bpo-36262(14): 修复了在 ‘float(str)’, ‘complex(str)’, *note
     pickle.load(): 5cb, *note marshal.load(): 1000. 等所用的函数
     ‘_Py_dg_strtod()’ 中进行从字符串到浮点数的转换时偶有发生的一个内存
     泄漏问题。

   - bpo-36252(15): Update Unicode databases to version 12.0.0.

   - bpo-36218(16): Fix a segfault occurring when sorting a list of
     heterogeneous values.  Patch contributed by Rémi Lapeyre and Elliot
     Gorokhovsky.

   - bpo-36188(17): Cleaned up left-over vestiges of Python 2 unbound
     method handling in method objects and documentation.  Patch by
     Martijn Pieters

   - bpo-36124(18): Add a new interpreter-specific dict and expose it in
     the C-API via PyInterpreterState_GetDict().  This parallels
     PyThreadState_GetDict().  However, extension modules should
     continue using PyModule_GetState() for their own internal
     per-interpreter state.

   - bpo-35975(19): Add a ‘feature_version’ flag to ‘ast.parse()’
     (documented) and ‘compile()’ (hidden) that allows tweaking the
     parser to support older versions of the grammar.  In particular, if
     ‘feature_version’ is 5 or 6, the hacks for the ‘async’ and ‘await’
     keyword from PEP 492 are reinstated.  (For 7 or higher, these are
     unconditionally treated as keywords, but they are still special
     tokens rather than ‘NAME’ tokens that the parser driver
     recognizes.)

   - bpo-31904(20): Use UTF-8 as the system encoding on VxWorks.

   - bpo-36048(21): The *note __index__(): 18b. special method will be
     used instead of *note __int__(): 18c. for implicit conversion of
     Python numbers to C integers.  Using the ‘__int__()’ method in
     implicit conversions has been deprecated.

   - bpo-35808(22): Retire pgen and use a modified version of pgen2 to
     generate the parser.  Patch by Pablo Galindo.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36421

   (2) https://bugs.python.org/issue36412

   (3) https://bugs.python.org/issue36398

   (4) https://bugs.python.org/issue36256

   (5) https://bugs.python.org/issue36365

   (6) https://bugs.python.org/issue36374

   (7) https://bugs.python.org/issue36236

   (8) https://bugs.python.org/issue36352

   (9) https://bugs.python.org/issue36301

   (10) https://bugs.python.org/issue36333

   (11) https://bugs.python.org/issue36332

   (12) https://bugs.python.org/issue36282

   (13) https://bugs.python.org/issue30040

   (14) https://bugs.python.org/issue36262

   (15) https://bugs.python.org/issue36252

   (16) https://bugs.python.org/issue36218

   (17) https://bugs.python.org/issue36188

   (18) https://bugs.python.org/issue36124

   (19) https://bugs.python.org/issue35975

   (20) https://bugs.python.org/issue31904

   (21) https://bugs.python.org/issue36048

   (22) https://bugs.python.org/issue35808


File: python.info,  Node: 库<27>,  Next: 文档<23>,  Prev: 核心与内置<27>,  Up: Python 3 8 0 alpha 3

1.18.28.3 库
............

   - bpo-36401(1): The class documentation created by pydoc now has a
     separate section for readonly properties.

   - bpo-36320(2): The typing.NamedTuple() class has deprecated the
     _field_types attribute in favor of the __annotations__ attribute
     which carried the same information.  Also, both attributes were
     converted from OrderedDict to a regular dict.

   - bpo-34745(3): Fix *note asyncio: a. ssl memory issues caused by
     circular references

   - bpo-36324(4): Add method to statistics.NormalDist for computing the
     inverse cumulative normal distribution.

   - bpo-36321(5): collections.namedtuple() misspelled the name of an
     attribute.  To be consistent with typing.NamedTuple, the attribute
     name should have been "_field_defaults" instead of
     "_fields_defaults".  For backwards compatibility, both spellings
     are now created.  The misspelled version may be removed in the
     future.

   - bpo-36297(6): "unicode_internal" codec is removed.  It was
     deprecated since Python 3.3.  Patch by Inada Naoki.

   - bpo-36298(7): Raise ModuleNotFoundError in pyclbr when a module
     can’t be found.  Thanks to ’mental’ for the bug report.

   - bpo-36268(8): Switch the default format used for writing tars with
     mod:*note tarfile: 102. to the modern POSIX.1-2001 pax standard,
     from the vendor-specific GNU. Contributed by C.A.M. Gerlach.

   - bpo-36285(9): Fix integer overflows in the array module.  Patch by
     Stephan Hohe.

   - bpo-31904(10): Add _signal module support for VxWorks.

   - bpo-36272(11): *note logging: ab. does not silently ignore
     RecursionError anymore.  Patch contributed by Rémi Lapeyre.

   - bpo-36280(12): Add a kind field to ast.Constant.  It is ’u’ if the
     literal has a ’u’ prefix (i.e.  a Python 2 style unicode literal),
     else None.

   - bpo-35931(13): The *note pdb: ca. ‘debug’ command now gracefully
     handles all exceptions.

   - bpo-36251(14): Fix format strings used for stderrprinter and
     re.Match reprs.  Patch by Stephan Hohe.

   - bpo-36235(15): Fix ‘CFLAGS’ in ‘customize_compiler()’ of
     ‘distutils.sysconfig’: when the ‘CFLAGS’ environment variable is
     defined, don’t override ‘CFLAGS’ variable with the ‘OPT’ variable
     anymore.  Initial patch written by David Malcolm.

   - bpo-35807(16): Update ensurepip to install pip 19.0.3 and
     setuptools 40.8.0.

   - bpo-36139(17): Release GIL when closing *note mmap: 1ed. objects.

   - bpo-36179(18): Fix two unlikely reference leaks in _hashopenssl.
     The leaks only occur in out-of-memory cases.

   - bpo-36169(19): Add overlap() method to statistics.NormalDist.
     Computes the overlapping coefficient for two normal distributions.

   - bpo-36103(20): Default buffer size used by ‘shutil.copyfileobj()’
     is changed from 16 KiB to 64 KiB on non-Windows platform to reduce
     system call overhead.  Contributed by Inada Naoki.

   - bpo-36130(21): Fix ‘pdb’ with ‘skip=...’ when stepping into a frame
     without a ‘__name__’ global.  Patch by Anthony Sottile.

   - bpo-35652(22): shutil.copytree(copy_function=...)  erroneously pass
     DirEntry instead of a path string.

   - bpo-35178(23): Ensure custom *note warnings.formatwarning(): 1002.
     function can receive ‘line’ as positional argument.  Based on patch
     by Tashrif Billah.

   - bpo-36106(24): Resolve potential name clash with libm’s sinpi().
     Patch by Dmitrii Pasechnik.

   - bpo-36091(25): Clean up reference to async generator in Lib/types.
     Patch by Henry Chen.

   - bpo-36043(26): ‘FileCookieJar’ supports *note path-like object:
     373.  Contributed by Stéphane Wirtel

   - bpo-35899(27): Enum has been fixed to correctly handle empty
     strings and strings with non-Latin characters (ie.  ’α’, ’א’)
     without crashing.  Original patch contributed by Maxwell.  Assisted
     by Stéphane Wirtel.

   - bpo-21269(28): Add ‘args’ and ‘kwargs’ properties to mock call
     objects.  Contributed by Kumar Akshay.

   - bpo-30670(29): *note pprint.pp: 213. has been added to pretty-print
     objects with dictionary keys being sorted with their insertion
     order by default.  Parameter `sort_dicts' has been added to *note
     pprint.pprint: 214, *note pprint.pformat: 89f. and *note
     pprint.PrettyPrinter: 89e.  Contributed by Rémi Lapeyre.

   - bpo-35843(30): Implement ‘__getitem__’ for ‘_NamespacePath’.  Patch
     by Anthony Sottile.

   - bpo-35802(31): Clean up code which checked presence of ‘os.stat’ /
     ‘os.lstat’ / ‘os.chmod’ which are always present.  Patch by Anthony
     Sottile.

   - bpo-35715(32): Librates the return value of a ProcessPoolExecutor
     _process_worker after it’s no longer needed to free memory

   - bpo-35493(33): Use *note multiprocessing.connection.wait(): a2c.
     instead of polling each 0.2 seconds for worker updates in
     ‘multiprocessing.Pool’.  Patch by Pablo Galindo.

   - bpo-35661(34): Store the venv prompt in pyvenv.cfg.

   - bpo-35121(35): Don’t set cookie for a request when the request path
     is a prefix match of the cookie’s path attribute but doesn’t end
     with "/".  Patch by Karthikeyan Singaravelan.

   - bpo-21478(36): Calls to a child function created with *note
     unittest.mock.create_autospec(): f59. should propagate to the
     parent.  Patch by Karthikeyan Singaravelan.

   - bpo-35198(37): Fix C++ extension compilation on AIX

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36401

   (2) https://bugs.python.org/issue36320

   (3) https://bugs.python.org/issue34745

   (4) https://bugs.python.org/issue36324

   (5) https://bugs.python.org/issue36321

   (6) https://bugs.python.org/issue36297

   (7) https://bugs.python.org/issue36298

   (8) https://bugs.python.org/issue36268

   (9) https://bugs.python.org/issue36285

   (10) https://bugs.python.org/issue31904

   (11) https://bugs.python.org/issue36272

   (12) https://bugs.python.org/issue36280

   (13) https://bugs.python.org/issue35931

   (14) https://bugs.python.org/issue36251

   (15) https://bugs.python.org/issue36235

   (16) https://bugs.python.org/issue35807

   (17) https://bugs.python.org/issue36139

   (18) https://bugs.python.org/issue36179

   (19) https://bugs.python.org/issue36169

   (20) https://bugs.python.org/issue36103

   (21) https://bugs.python.org/issue36130

   (22) https://bugs.python.org/issue35652

   (23) https://bugs.python.org/issue35178

   (24) https://bugs.python.org/issue36106

   (25) https://bugs.python.org/issue36091

   (26) https://bugs.python.org/issue36043

   (27) https://bugs.python.org/issue35899

   (28) https://bugs.python.org/issue21269

   (29) https://bugs.python.org/issue30670

   (30) https://bugs.python.org/issue35843

   (31) https://bugs.python.org/issue35802

   (32) https://bugs.python.org/issue35715

   (33) https://bugs.python.org/issue35493

   (34) https://bugs.python.org/issue35661

   (35) https://bugs.python.org/issue35121

   (36) https://bugs.python.org/issue21478

   (37) https://bugs.python.org/issue35198


File: python.info,  Node: 文档<23>,  Next: 测试<18>,  Prev: 库<27>,  Up: Python 3 8 0 alpha 3

1.18.28.4 文档
..............

   - bpo-36329(1): Declare the path of the Python binary for the usage
     of ‘Tools/scripts/serve.py’ when executing ‘make -C Doc/ serve’.
     Contributed by Stéphane Wirtel

   - bpo-36138(2): Improve documentation about converting
     datetime.timedelta to scalars.

   - bpo-21314(3): A new entry was added to the Core Language Section of
     the Programming FAQ, which explaines the usage of slash(/) in the
     signature of a function.  Patch by Lysandros Nikolaou

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36329

   (2) https://bugs.python.org/issue36138

   (3) https://bugs.python.org/issue21314


File: python.info,  Node: 测试<18>,  Next: 构建<16>,  Prev: 文档<23>,  Up: Python 3 8 0 alpha 3

1.18.28.5 测试
..............

   - bpo-36234(1): test_posix.PosixUidGidTests: add tests for invalid
     uid/gid type (str).  Initial patch written by David Malcolm.

   - bpo-29571(2): Fix ‘test_re.test_locale_flag()’: use
     ‘locale.getpreferredencoding()’ rather than ‘locale.getlocale()’ to
     get the locale encoding.  With some locales, ‘locale.getlocale()’
     returns the wrong encoding.

   - bpo-36123(3): Fix race condition in test_socket.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36234

   (2) https://bugs.python.org/issue29571

   (3) https://bugs.python.org/issue36123


File: python.info,  Node: 构建<16>,  Next: Windows<20>,  Prev: 测试<18>,  Up: Python 3 8 0 alpha 3

1.18.28.6 构建
..............

   - bpo-36356(1): Fix leaks that led to build failure when configured
     with address sanitizer.

   - bpo-36146(2): Add ‘TEST_EXTENSIONS’ constant to ‘setup.py’ to allow
     to not build test extensions like ‘_testcapi’.

   - bpo-36146(3): Fix setup.py on macOS: only add ‘/usr/include/ffi’ to
     include directories of _ctypes, not for all extensions.

   - bpo-31904(4): Enable build system to cross-build for VxWorks RTOS.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36356

   (2) https://bugs.python.org/issue36146

   (3) https://bugs.python.org/issue36146

   (4) https://bugs.python.org/issue31904


File: python.info,  Node: Windows<20>,  Next: IDLE<25>,  Prev: 构建<16>,  Up: Python 3 8 0 alpha 3

1.18.28.7 Windows
.................

   - bpo-36312(1): Fixed decoders for the following code pages: 50220,
     50221, 50222, 50225, 50227, 50229, 57002 through 57011, 65000 and
     42.

   - bpo-36264(2): Don’t honor POSIX ‘HOME’ in ‘os.path.expanduser’ on
     windows.  Patch by Anthony Sottile.

   - bpo-24643(3): Fix name collisions due to ‘#define timezone
     _timezone’ in PC/pyconfig.h.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36312

   (2) https://bugs.python.org/issue36264

   (3) https://bugs.python.org/issue24643


File: python.info,  Node: IDLE<25>,  Next: 工具/示例<11>,  Prev: Windows<20>,  Up: Python 3 8 0 alpha 3

1.18.28.8 IDLE
..............

   - bpo-36405(1): Use dict unpacking in idlelib.

   - bpo-36396(2): Remove fgBg param of idlelib.config.GetHighlight().
     This param was only used twice and changed the return type.

   - bpo-36176(3): 修复 IDLE 自动补全和 calltip 悬浮窗的颜色. 避免与
     Linux 暗色主题冲突 (略微加深了calltip 的背景颜色).

   - bpo-23205(4): For the grep module, add tests for findfiles,
     refactor findfiles to be a module-level function, and refactor
     findfiles to use os.walk.

   - bpo-23216(5): 将文档字符串添加到IDLE 的搜索模块。

   - bpo-36152(6): Remove colorizer.ColorDelegator.close_when_done and
     the corresponding argument of .close().  In IDLE, both have always
     been None or False since 2007.

   - bpo-32129(7): Avoid blurry IDLE application icon on macOS with Tk
     8.6.  Patch by Kevin Walzer.

   - bpo-36096(8): Refactor class variables to instance variables in
     colorizer.

   - bpo-30348(9): Increase test coverage of idlelib.autocomplete by
     30%.  Patch by Louie Lu

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36405

   (2) https://bugs.python.org/issue36396

   (3) https://bugs.python.org/issue36176

   (4) https://bugs.python.org/issue23205

   (5) https://bugs.python.org/issue23216

   (6) https://bugs.python.org/issue36152

   (7) https://bugs.python.org/issue32129

   (8) https://bugs.python.org/issue36096

   (9) https://bugs.python.org/issue30348


File: python.info,  Node: 工具/示例<11>,  Next: C API<14>,  Prev: IDLE<25>,  Up: Python 3 8 0 alpha 3

1.18.28.9 工具/示例
...................

   - bpo-35132(1): Fix py-list and py-bt commands of python-gdb.py on
     gdb7.

   - bpo-32217(2): Fix freeze script on Windows.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35132

   (2) https://bugs.python.org/issue32217


File: python.info,  Node: C API<14>,  Prev: 工具/示例<11>,  Up: Python 3 8 0 alpha 3

1.18.28.10 C API
................

   - bpo-36381(1): Raise ‘DeprecationWarning’ when ’#’ formats are used
     for building or parsing values without ‘PY_SSIZE_T_CLEAN’.

   - bpo-36142(2): The whole coreconfig.h header is now excluded from
     Py_LIMITED_API. Move functions definitions into a new internal
     pycore_coreconfig.h header.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36381

   (2) https://bugs.python.org/issue36142


File: python.info,  Node: Python 3 8 0 alpha 2,  Next: Python 3 8 0 alpha 1,  Prev: Python 3 8 0 alpha 3,  Up: 更新日志

1.18.29 Python 3.8.0 alpha 2
----------------------------

`发布日期: 2019-02-25'

* Menu:

* 核心与内置: 核心与内置<28>.
* 库: 库<28>.
* 文档: 文档<24>.
* 测试: 测试<19>.
* Windows: Windows<21>.
* IDLE: IDLE<26>.


File: python.info,  Node: 核心与内置<28>,  Next: 库<28>,  Up: Python 3 8 0 alpha 2

1.18.29.1 核心与内置
....................

   - bpo-36052(1): Raise a *note SyntaxError: 460. when assigning a
     value to *note __debug__: 100c. with the Assignment Operator.
     Contributed by Stéphane Wirtel and Pablo Galindo.

   - bpo-36012(2): Doubled the speed of class variable writes.  When a
     non-dunder attribute was updated, there was an unnecessary call to
     update slots.

   - bpo-35942(3): The error message emitted when returning invalid
     types from ‘__fspath__’ in interfaces that allow passing *note
     PathLike: 4f3. objects has been improved and now it does explain
     the origin of the error.

   - bpo-36016(4): ‘gc.get_objects’ can now receive an optional
     parameter indicating a generation to get objects from.  Patch by
     Pablo Galindo.

   - bpo-1054041(5): When the main interpreter exits due to an uncaught
     KeyboardInterrupt, the process now exits in the appropriate manner
     for its parent process to detect that a SIGINT or ^C terminated the
     process.  This allows shells and batch scripts to understand that
     the user has asked them to stop.

   - bpo-35992(6): Fix ‘__class_getitem__()’ not being called on a class
     with a custom non-subscriptable metaclass.

   - bpo-35993(7): Fix a crash on fork when using subinterpreters.
     Contributed by Stéphane Wirtel

   - bpo-35991(8): Fix a potential double free in
     Modules/_randommodule.c.

   - bpo-35961(9): Fix a crash in slice_richcompare(): use strong
     references rather than stolen references for the two temporary
     internal tuples.

   - bpo-35911(10): Enable the creation of cell objects by adding a
     ‘cell.__new__’ method, and expose the type ‘cell’ in ‘Lib/types.py’
     under the name CellType.  Patch by Pierre Glaser.

   - bpo-12822(11): Use monotonic clock for ‘pthread_cond_timedwait’
     when ‘pthread_condattr_setclock’ and ‘CLOCK_MONOTONIC’ are
     available.

   - bpo-15248(12): The compiler emits now syntax warnings in the case
     when a comma is likely missed before tuple or list.

   - bpo-35886(13): The implementation of PyInterpreterState has been
     moved into the internal header files (guarded by Py_BUILD_CORE).

   - bpo-31506(14): Clarify the errors reported when ‘object.__new__’
     and ‘object.__init__’ receive more than one argument.  Contributed
     by Sanyam Khurana.

   - bpo-35724(15): Signal-handling is now guaranteed to happen relative
     to the main interpreter.

   - bpo-33608(16): We added a new internal _Py_AddPendingCall() that
     operates relative to the provided interpreter.  This allows us to
     use the existing implementation to ask another interpreter to do
     work that cannot be done in the current interpreter, like decref an
     object the other interpreter owns.  The existing
     Py_AddPendingCall() only operates relative to the main interpreter.

   - bpo-33989(17): Fix a possible crash in *note list.sort(): 44d. when
     sorting objects with ‘ob_type->tp_richcompare == NULL’.  Patch by
     Zackery Spytz.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36052

   (2) https://bugs.python.org/issue36012

   (3) https://bugs.python.org/issue35942

   (4) https://bugs.python.org/issue36016

   (5) https://bugs.python.org/issue1054041

   (6) https://bugs.python.org/issue35992

   (7) https://bugs.python.org/issue35993

   (8) https://bugs.python.org/issue35991

   (9) https://bugs.python.org/issue35961

   (10) https://bugs.python.org/issue35911

   (11) https://bugs.python.org/issue12822

   (12) https://bugs.python.org/issue15248

   (13) https://bugs.python.org/issue35886

   (14) https://bugs.python.org/issue31506

   (15) https://bugs.python.org/issue35724

   (16) https://bugs.python.org/issue33608

   (17) https://bugs.python.org/issue33989


File: python.info,  Node: 库<28>,  Next: 文档<24>,  Prev: 核心与内置<28>,  Up: Python 3 8 0 alpha 2

1.18.29.2 库
............

   - bpo-35512(1): *note unittest.mock.patch.dict(): fdf. used as a
     decorator with string target resolves the target during function
     call instead of during decorator construction.  Patch by
     Karthikeyan Singaravelan.

   - bpo-36018(2): Add statistics.NormalDist, a tool for creating and
     manipulating normal distributions of random variable.  Features a
     composite class that treats the mean and standard deviation of
     measurement data as single entity.

   - bpo-35904(3): Added statistics.fmean() as a faster, floating point
     variant of the existing mean() function.

   - bpo-35918(4): Removed broken ‘has_key’ method from
     multiprocessing.managers.SyncManager.dict.  Contributed by Rémi
     Lapeyre.

   - bpo-18283(5): Add support for bytes to *note shutil.which(): eea.

   - bpo-35960(6): Fix *note dataclasses.field(): 100e. throwing away
     empty mapping objects passed as metadata.

   - bpo-35500(7): Write expected and actual call parameters on separate
     lines in *note unittest.mock.Mock.assert_called_with(): 100f.
     assertion errors.  Contributed by Susan Su.

   - bpo-35931(8): The *note pdb: ca. ‘debug’ command now gracefully
     handles syntax errors.

   - bpo-24209(9): In http.server script, rely on getaddrinfo to bind to
     preferred address based on the bind parameter.  Now default bind or
     binding to a name may bind to IPv6 or dual-stack, depending on the
     environment.

   - bpo-35321(10): Set ‘__spec__.origin’ of ‘_frozen_importlib’ to
     frozen so that it matches the behavior of
     ‘_frozen_importlib_external’.  Patch by Nina Zakharenko.

   - bpo-35378(11): Fix a reference issue inside ‘multiprocessing.Pool’
     that caused the pool to remain alive if it was deleted without
     being closed or terminated explicitly.  A new strong reference is
     added to the pool iterators to link the lifetime of the pool to the
     lifetime of its iterators so the pool does not get destroyed if a
     pool iterator is still alive.

   - bpo-34294(12): re module, fix wrong capturing groups in rare cases.
     *note re.search(): bba, *note re.findall(): 96b, *note re.sub():
     483. and other functions that scan through string looking for a
     match, should reset capturing groups between two match attempts.
     Patch by Ma Lin.

   - bpo-35615(13): *note weakref: 129.: Fix a RuntimeError when copying
     a WeakKeyDictionary or a WeakValueDictionary, due to some keys or
     values disappearing while iterating.

   - bpo-35606(14): Implement *note math.prod(): 1e5. as analogous
     function to *note sum(): 1e6. that returns the product of a ’start’
     value (default: 1) times an iterable of numbers.  Patch by Pablo
     Galindo.

   - bpo-32417(15): Performing arithmetic between *note
     datetime.datetime: 195. subclasses and *note datetime.timedelta:
     196. now returns an object of the same type as the *note
     datetime.datetime: 195. subclass.  As a result, *note
     datetime.datetime.astimezone(): 197. and alternate constructors
     like *note datetime.datetime.now(): 1010. and
     ‘datetime.fromtimestamp()’ called with a ‘tz’ argument now `also'
     retain their subclass.

   - bpo-35153(16): Add `headers' optional keyword-only parameter to
     *note xmlrpc.client.ServerProxy: 256, ‘xmlrpc.client.Transport’ and
     ‘xmlrpc.client.SafeTransport’.  Patch by Cédric Krier.

   - bpo-34572(17): Fix C implementation of pickle.loads to use
     importlib’s locking mechanisms, and thereby avoid using
     partially-loaded modules.  Patch by Tim Burgess.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35512

   (2) https://bugs.python.org/issue36018

   (3) https://bugs.python.org/issue35904

   (4) https://bugs.python.org/issue35918

   (5) https://bugs.python.org/issue18283

   (6) https://bugs.python.org/issue35960

   (7) https://bugs.python.org/issue35500

   (8) https://bugs.python.org/issue35931

   (9) https://bugs.python.org/issue24209

   (10) https://bugs.python.org/issue35321

   (11) https://bugs.python.org/issue35378

   (12) https://bugs.python.org/issue34294

   (13) https://bugs.python.org/issue35615

   (14) https://bugs.python.org/issue35606

   (15) https://bugs.python.org/issue32417

   (16) https://bugs.python.org/issue35153

   (17) https://bugs.python.org/issue34572


File: python.info,  Node: 文档<24>,  Next: 测试<19>,  Prev: 库<28>,  Up: Python 3 8 0 alpha 2

1.18.29.3 文档
..............

   - bpo-36083(1): Fix formatting of –check-hash-based-pycs options in
     the manpage Synopsis.

   - bpo-36007(2): Bump minimum sphinx version to 1.8.  Patch by Anthony
     Sottile.

   - bpo-22062(3): Update documentation and docstrings for pathlib.
     Original patch by Mike Short.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36083

   (2) https://bugs.python.org/issue36007

   (3) https://bugs.python.org/issue22062


File: python.info,  Node: 测试<19>,  Next: Windows<21>,  Prev: 文档<24>,  Up: Python 3 8 0 alpha 2

1.18.29.4 测试
..............

   - bpo-27313(1): Avoid test_ttk_guionly ComboboxTest failure with
     macOS Cocoa Tk.

   - bpo-36019(2): Add test.support.TEST_HTTP_URL and replace references
     of ‘http://www.example.com’ by this new constant.  Contributed by
     Stéphane Wirtel.

   - bpo-36037(3): Fix test_ssl for strict OpenSSL configuration like
     RHEL8 strict crypto policy.  Use older TLS version for minimum TLS
     version of the server SSL context if needed, to test TLS version
     older than default minimum TLS version.

   - bpo-35798(4): Added *note test.support.check_syntax_warning():
     1013.

   - bpo-35505(5): Make test_imap4_host_default_value independent on
     whether the local IMAP server is running.

   - bpo-35917(6): multiprocessing: provide unit tests for SyncManager
     and SharedMemoryManager classes + all the shareable types which are
     supposed to be supported by them.  (patch by Giampaolo Rodola)

   - bpo-35704(7): Skip ‘test_shutil.test_unpack_archive_xztar’ to
     prevent a MemoryError on 32-bit AIX when MAXDATA setting is less
     than 0x20000000.

     Patch by Michael Felt (aixtools)

   - bpo-34720(8): Assert m_state != NULL to mimic GC traversal
     functions that do not correctly handle module creation when the
     module state has not been created.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27313

   (2) https://bugs.python.org/issue36019

   (3) https://bugs.python.org/issue36037

   (4) https://bugs.python.org/issue35798

   (5) https://bugs.python.org/issue35505

   (6) https://bugs.python.org/issue35917

   (7) https://bugs.python.org/issue35704

   (8) https://bugs.python.org/issue34720


File: python.info,  Node: Windows<21>,  Next: IDLE<26>,  Prev: 测试<19>,  Up: Python 3 8 0 alpha 2

1.18.29.5 Windows
.................

   - bpo-35976(1): Added ARM build support to Windows build files in
     PCBuild.

   - bpo-35692(2): ‘pathlib’ no longer raises when checking file and
     directory existence on drives that are not ready

   - bpo-35872(3): Uses the base Python executable when invoking venv in
     a virtual environment

   - bpo-35873(4): Prevents venv paths being inherited by child
     processes

   - bpo-35299(5): Fix sysconfig detection of the source directory and
     distutils handling of pyconfig.h during PGO profiling

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35976

   (2) https://bugs.python.org/issue35692

   (3) https://bugs.python.org/issue35872

   (4) https://bugs.python.org/issue35873

   (5) https://bugs.python.org/issue35299


File: python.info,  Node: IDLE<26>,  Prev: Windows<21>,  Up: Python 3 8 0 alpha 2

1.18.29.6 IDLE
..............

   - bpo-24310(1): IDLE – 文档设置对话框字体选项卡示例。

   - bpo-35833(2): Revise IDLE doc for control codes sent to Shell.  Add
     a code example block.

   - bpo-35689(3): Add docstrings and unittests for colorizer.py.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24310

   (2) https://bugs.python.org/issue35833

   (3) https://bugs.python.org/issue35689


File: python.info,  Node: Python 3 8 0 alpha 1,  Next: Python 3 7 0 正式版,  Prev: Python 3 8 0 alpha 2,  Up: 更新日志

1.18.30 Python 3.8.0 alpha 1
----------------------------

`发布日期: 2019-02-03'

* Menu:

* 安全: 安全<21>.
* 核心与内置: 核心与内置<29>.
* 库: 库<29>.
* 文档: 文档<25>.
* 测试: 测试<20>.
* 构建: 构建<17>.
* Windows: Windows<22>.
* macOS: macOS<16>.
* IDLE: IDLE<27>.
* 工具/示例: 工具/示例<12>.
* C API: C API<15>.


File: python.info,  Node: 安全<21>,  Next: 核心与内置<29>,  Up: Python 3 8 0 alpha 1

1.18.30.1 安全
..............

   - bpo-35746(1): [CVE-2019-5010] Fix a NULL pointer deref in ssl
     module.  The cert parser did not handle CRL distribution points
     with empty DP or URI correctly.  A malicious or buggy certificate
     can result into segfault.  Vulnerability (TALOS-2018-0758) reported
     by Colin Read and Nicolas Edet of Cisco.

   - bpo-34812(2): The *note -I: 1018. command line option (run Python
     in isolated mode) is now also copied by the *note multiprocessing:
     b8. and *note distutils: 39. modules when spawning child processes.
     Previously, only *note -E: 1019. and *note -s: d1d. options
     (enabled by *note -I: 1018.) were copied.

   - bpo-34791(3): The xml.sax and xml.dom.domreg no longer use
     environment variables to override parser implementations when
     sys.flags.ignore_environment is set by -E or -I arguments.

   - bpo-17239(4): The xml.sax and xml.dom.minidom parsers no longer
     processes external entities by default.  External DTD and ENTITY
     declarations no longer load files or create network connections.

   - bpo-34623(5): CVE-2018-14647: The C accelerated _elementtree module
     now initializes hash randomization salt from _Py_HashSecret instead
     of libexpat’s default CSPRNG.

   - bpo-34405(6): 将Windows内部版本更新到OpenSSL 1.1.0i

   - bpo-33871(7): 修复了使用 *note os.sendfile(): 362. 在macOS上发送部
     分文件的错误。使用 `trailers' 参数可能导致从输入文件发送的字节数多
     于指定的数量。

   - bpo-32533(8): Fixed thread-safety of error handling in _ssl.

   - bpo-33136(9): Harden ssl module against LibreSSL CVE-2018-8970.
     X509_VERIFY_PARAM_set1_host() is called with an explicit namelen.
     A new test ensures that NULL bytes are not allowed.

   - bpo-33001(10): Minimal fix to prevent buffer overrun in os.symlink
     on Windows

   - bpo-32981(11): Regexes in difflib and poplib were vulnerable to
     catastrophic backtracking.  These regexes formed potential DOS
     vectors (REDOS). They have been refactored.  This resolves
     CVE-2018-1060 and CVE-2018-1061.  Patch by Jamie Davis.

   - bpo-28414(12): The ssl module now allows users to perform their own
     IDN en/decoding when using SNI.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35746

   (2) https://bugs.python.org/issue34812

   (3) https://bugs.python.org/issue34791

   (4) https://bugs.python.org/issue17239

   (5) https://bugs.python.org/issue34623

   (6) https://bugs.python.org/issue34405

   (7) https://bugs.python.org/issue33871

   (8) https://bugs.python.org/issue32533

   (9) https://bugs.python.org/issue33136

   (10) https://bugs.python.org/issue33001

   (11) https://bugs.python.org/issue32981

   (12) https://bugs.python.org/issue28414


File: python.info,  Node: 核心与内置<29>,  Next: 库<29>,  Prev: 安全<21>,  Up: Python 3 8 0 alpha 1

1.18.30.2 核心与内置
....................

   - bpo-35877(1): Make parenthesis optional for named expressions in
     while statement.  Patch by Karthikeyan Singaravelan.

   - bpo-35814(2): Allow same right hand side expressions in annotated
     assignments as in normal ones.  In particular, ‘x: Tuple[int, int]
     = 1, 2’ (without parentheses on the right) is now allowed.

   - bpo-35766(3): Add the option to parse PEP 484 type comments in the
     ast module.  (Off by default.)  This is merging the key
     functionality of the third party fork thereof,
     [typed_ast](‘https://github.com/python/typed_ast’).

   - bpo-35713(4): Reorganize Python initialization to get working
     exceptions and sys.stderr earlier.

   - bpo-33416(5): Add end line and end column position information to
     the Python AST nodes.  This is a C-level backwards incompatible
     change.

   - bpo-35720(6): Fixed a minor memory leak in
     pymain_parse_cmdline_impl function in Modules/main.c

   - bpo-35634(7): ‘func(**kwargs)’ will now raise an error when
     ‘kwargs’ is a mapping containing multiple entries with the same
     key.  An error was already raised when other keyword arguments are
     passed before ‘**kwargs’ since Python 3.6.

   - bpo-35623(8): 修复了在排序超长列表时崩溃的问题。 补丁作者 Stephan
     Hohe。

   - bpo-35214(9): 添加了 clang Memory Sanitizer 构建工具以绕过来自
     posix, socket, time, test_io 和 test_faulthandler 的误报问题。

   - bpo-35560(10): 修复了在调试版中使用 "n" 格式进行零留空和小宽度的浮
     点格式化时 *note format(): 4e3. 内的一个断言错误。 发布版未受影响。
     补丁作者 Karthikeyan Singaravelan。

   - bpo-35552(11): Format characters ‘%s’ and ‘%V’ in *note
     PyUnicode_FromFormat(): 7d4. and ‘%s’ in *note
     PyBytes_FromFormat(): 101b. no longer read memory past the limit if
     `precision' is specified.

   - bpo-35504(12): 修复了在删除特定属性时的段错误和 *note SystemError:
     604. 问题。 补丁作者 Zackery Spytz。

   - bpo-35504(13): Fixed a SystemError when delete the
     characters_written attribute of an OSError.

   - bpo-35494(14): Improved syntax error messages for unbalanced
     parentheses in f-string.

   - bpo-35444(15): Fixed error handling in pickling methods when fail
     to look up builtin "getattr".  Sped up pickling iterators.

   - bpo-35436(16): Fix various issues with memory allocation error
     handling.  Patch by Zackery Spytz.

   - bpo-35423(17): Separate the signal handling trigger in the eval
     loop from the "pending calls" machinery.  There is no semantic
     change and the difference in performance is insignificant.

   - bpo-35357(18): Internal attributes’ names of unittest.mock._Call
     and unittest.mock.MagicProxy (name, parent & from_kall) are now
     prefixed with _mock_ in order to prevent clashes with widely used
     object attributes.  Fixed minor typo in test function name.

   - bpo-35372(19): Fixed the code page decoder for input longer than 2
     GiB containing undecodable bytes.

   - bpo-35336(20): Fix PYTHONCOERCECLOCALE=1 environment variable: only
     coerce the C locale if the LC_CTYPE locale is "C".

   - bpo-31241(21): The `lineno' and `col_offset' attributes of AST
     nodes for list comprehensions, generator expressions and tuples are
     now point to the opening parenthesis or square brace.  For tuples
     without parenthesis they point to the position of the first item.

   - bpo-33954(22): For *note str.format(): 4e2, ‘float.__format__()’
     and ‘complex.__format__()’ methods for non-ASCII decimal point when
     using the "n" formatter.

   - bpo-35269(23): Fix a possible segfault involving a newly-created
     coroutine.  Patch by Zackery Spytz.

   - bpo-35224(24): Implement PEP 572(25) (assignment expressions).
     Patch by Emily Morehouse.

   - bpo-32492(26): Speed up ‘namedtuple’ attribute access by 1.6x using
     a C fast-path for the name descriptors.  Patch by Pablo Galindo.

   - bpo-35214(27): Fixed an out of bounds memory access when parsing a
     truncated unicode escape sequence at the end of a string such as
     ‘'\N'’.  It would read one byte beyond the end of the memory
     allocation.

   - bpo-35214(28): The interpreter and extension modules have had
     annotations added so that they work properly under clang’s Memory
     Sanitizer.  A new configure flag –with-memory-sanitizer has been
     added to make test builds of this nature easier to perform.

   - bpo-35193(29): Fix an off by one error in the bytecode peephole
     optimizer where it could read bytes beyond the end of bounds of an
     array when removing unreachable code.  This bug was present in
     every release of Python 3.6 and 3.7 until now.

   - bpo-35169(30): Improved error messages for forbidden assignments.

   - bpo-34022(31): Fix handling of hash-based bytecode files in *note
     zipimport: 144.  Patch by Elvis Pranskevichus.

   - bpo-28401(32): Debug builds will no longer to attempt to import
     extension modules built for the ABI as they were never compatible
     to begin with.  Patch by Stefano Rivera.

   - bpo-29341(33): Clarify in the docstrings of *note os: c5. methods
     that path-like objects are also accepted as input parameters.

   - bpo-35050(34): *note socket: f0.: Fix off-by-one bug in length
     check for ‘AF_ALG’ name and type.

   - bpo-29743(35): Raise *note ValueError: 1fc. instead of *note
     OverflowError: 968. in case of a negative ‘_length_’ in a *note
     ctypes.Array: 101c. subclass.  Also raise *note TypeError: 193.
     instead of *note AttributeError: 3a3. for non-integer ‘_length_’.
     Original patch by Oren Milman.

   - bpo-16806(36): Fix ‘lineno’ and ‘col_offset’ for multi-line string
     tokens.

   - bpo-35029(37): *note SyntaxWarning: 192. raised as an exception at
     code generation time will be now replaced with a *note SyntaxError:
     460. for better error reporting.

   - bpo-34983(38): Expose *note symtable.Symbol.is_nonlocal(): 101d. in
     the symtable module.  Patch by Pablo Galindo.

   - bpo-34974(39): *note bytes: 33a. and *note bytearray: 33b.
     constructors no longer convert unexpected exceptions (e.g.  *note
     MemoryError: efc. and *note KeyboardInterrupt: 198.) to *note
     TypeError: 193.

   - bpo-34939(40): Allow annotated names in module namespace that are
     declared global before the annotation happens.  Patch by Pablo
     Galindo.

   - bpo-34973(41): Fixed crash in *note bytes(): 33a. when the *note
     list: 263. argument is mutated while it is iterated.

   - bpo-34876(42): The `lineno' and `col_offset' attributes of the AST
     for decorated function and class refer now to the position of the
     corresponding ‘def’, ‘async def’ and ‘class’ instead of the
     position of the first decorator.  This leads to more correct line
     reporting in tracing.  This is the only case when the position of
     child AST nodes can precede the position of the parent AST node.

   - bpo-34879(43): Fix a possible null pointer dereference in
     bytesobject.c.  Patch by Zackery Spytz.

   - bpo-34784(44): Fix the implementation of PyStructSequence_NewType
     in order to create heap allocated StructSequences.

   - bpo-32912(45): A *note SyntaxWarning: 192. is now emitted instead
     of a *note DeprecationWarning: 279. for invalid escape sequences in
     string and bytes literals.

   - bpo-34854(46): 修复问题——当编译包含一个没有默认值的关键字参数的
     lambda 的字符串注解时可导致崩溃。

   - bpo-34850(47): The compiler now produces a *note SyntaxWarning:
     192. when identity checks (‘is’ and ‘is not’) are used with certain
     types of literals (e.g.  strings, ints).  These can often work by
     accident in CPython, but are not guaranteed by the language spec.
     The warning advises users to use equality tests (‘==’ and ‘!=’)
     instead.

   - bpo-34824(48): Fix a possible null pointer dereference in
     Modules/_ssl.c.  Patch by Zackery Spytz.

   - bpo-30156(49): The C function ‘property_descr_get()’ uses a
     "cached" tuple to optimize function calls.  But this tuple can be
     discovered in debug mode with ‘sys.getobjects()’.  Remove the
     optimization, it’s not really worth it and it causes 3 different
     crashes last years.

   - bpo-34762(50): Fix contextvars C API to use PyObject* pointer
     types.

   - bpo-34751(51): The hash function for tuples is now based on xxHash
     which gives better collision results on (formerly) pathological
     cases.  Additionally, on 64-bit systems it improves tuple hashes in
     general.  Patch by Jeroen Demeyer with substantial contributions by
     Tim Peters.

   - bpo-34735(52): Fix a memory leak in Modules/timemodule.c.  Patch by
     Zackery Spytz.

   - bpo-34683(53): Fixed a bug where some SyntaxError error pointed to
     locations that were off-by-one.

   - bpo-34651(54): Only allow the main interpreter to fork.  The avoids
     the possibility of affecting the main interpreter, which is
     critical to operation of the runtime.

   - bpo-34653(55): Remove unused function
     PyParser_SimpleParseStringFilename.

   - bpo-32236(56): Warn that line buffering is not supported if *note
     open(): 4f8. is called with binary mode and ‘buffering=1’.

   - bpo-34641(57): Further restrict the syntax of the left-hand side of
     keyword arguments in function calls.  In particular,
     ‘f((keyword)=arg)’ is now disallowed.

   - bpo-34637(58): Make the `start' argument to `sum()' visible as a
     keyword argument.

   - bpo-1621(59): Do not assume signed integer overflow behavior (C
     undefined behavior) when performing set hash table resizing.

   - bpo-34588(60): Fix an off-by-one in the recursive call pruning
     feature of traceback formatting.

   - bpo-34485(61): On Windows, the LC_CTYPE is now set to the user
     preferred locale at startup.  Previously, the LC_CTYPE locale was
     "C" at startup, but changed when calling setlocale(LC_CTYPE, "") or
     setlocale(LC_ALL, "").

   - bpo-34485(62): Standard streams like sys.stdout now use the
     "surrogateescape" error handler, instead of "strict", on the POSIX
     locale (when the C locale is not coerced and the UTF-8 Mode is
     disabled).

   - bpo-34485(63): Fix the error handler of standard streams like
     sys.stdout: PYTHONIOENCODING=":" is now ignored instead of setting
     the error handler to "strict".

   - bpo-34485(64): Python now gets the locale encoding with C code to
     initialize the encoding of standard streams like sys.stdout.
     Moreover, the encoding is now initialized to the Python codec name
     to get a normalized encoding name and to ensure that the codec is
     loaded.  The change avoids importing _bootlocale and _locale
     modules at startup by default.

   - bpo-34527(65): On FreeBSD, Py_DecodeLocale() and Py_EncodeLocale()
     now also forces the ASCII encoding if the LC_CTYPE locale is
     "POSIX", not only if the LC_CTYPE locale is "C".

   - bpo-34527(66): The UTF-8 Mode is now also enabled by the "POSIX"
     locale, not only by the "C" locale.

   - bpo-34403(67): On HP-UX with C or POSIX locale,
     sys.getfilesystemencoding() now returns "ascii" instead of "roman8"
     (when the UTF-8 Mode is disabled and the C locale is not coerced).

   - bpo-34523(68): The Python filesystem encoding is now read earlier
     during the Python initialization.

   - bpo-12458(69): Tracebacks show now correct line number for
     subexpressions in multiline expressions.  Tracebacks show now the
     line number of the first line for multiline expressions instead of
     the line number of the last subexpression.

   - bpo-34408(70): Prevent a null pointer dereference and resource
     leakage in ‘PyInterpreterState_New()’.

   - bpo-34400(71): Fix undefined behavior in parsetok.c.  Patch by
     Zackery Spytz.

   - bpo-33073(72): Added as_integer_ratio to ints to make them more
     interoperable with floats.

   - bpo-34377(73): 更新valgrind的抑制列表，使用
     ‘_PyObject_Free’/‘_PyObject_Realloc’ 代替
     ‘PyObject_Free’/‘PyObject_Realloc’ 。

   - bpo-34353(74): Added the "socket" option in the *note
     stat.filemode(): aa5. Python implementation to match the C
     implementation.

   - bpo-34320(75): 修复问题——‘dict(od)’ 不会复制 OrderedDict 的迭代顺序
     。

   - bpo-34113(76): Fixed crash on debug builds when opcode stack was
     adjusted with negative numbers.  Patch by Constantin Petrisor.

   - bpo-34100(77): Compiler now merges constants in tuples and
     frozensets recursively.  Code attributes like ‘co_names’ are merged
     too.

   - bpo-34151(78): Performance of list concatenation, repetition and
     slicing operations is slightly improved.  Patch by Sergey Fedoseev.

   - bpo-34170(79): -X dev: 即使启用了开发模式，现在也可以使用
     PYTHONMALLOC重载内存分配器。

   - bpo-33237(80): Improved *note AttributeError: 3a3. message for
     partially initialized module.

   - bpo-34149(81): Fix min and max functions to get default behavior
     when key is None.

   - bpo-34125(82): Profiling of unbound built-in methods now works when
     ‘**kwargs’ is given.

   - bpo-34141(83): Optimized pickling atomic types (None, bool, int,
     float, bytes, str).

   - bpo-34126(84): 修复在分析某些未绑定的方法的无效调用时崩溃的问题。由
     Jeroen Demeyer修复。

   - bpo-24618(85): 修复了当创建代码对象时使用的变量名元组太小或参数太多
     导致读取无效内存的问题。

   - bpo-34068(86): 在调用 *note io.IOBase.close(): 101e. 时确保 *note
     closed: 101f. 属性未设置有效的异常。 由Zackery Spytz和Serhiy
     Storchaka修复。

   - bpo-34087(87): 修复由unicode转换为数值类型时缓冲区溢出的问题。

   - bpo-34080(88): 修复了编译器在标记化过程中引发一些不常见错误时内存泄
     漏的问题。

   - bpo-34066(89): 调用 ‘open()’ 和进入 ‘with open()’ 的 `with' 语句块
     内时禁止使用 Ctrl-C 中断。

   - bpo-34042(90): 修复 dict.copy() 以维护正确的总引用计数（由
     sys.gettotalrefcount()报告）。

   - bpo-33418(91): Fix potential memory leak in function object when it
     creates reference cycle.

   - bpo-33985(92): 实现contextvars.ContextVar.name 属性。

   - bpo-33956(93): Update vendored Expat library copy to version 2.2.5.

   - bpo-24596(94): 执行 *note PyErr_Print(): f19. 之前，在 *note
     PyRun_SimpleFileExFlags(): ed7. 内减少模块对象的引用。 由Zackery
     Spytz修复。

   - bpo-33451(95): 执行 ‘PyEval_EvalCode()’ 前先关闭直接执行的pyc文件。

   - bpo-1617161(96): The hash of ‘BuiltinMethodType’ instances (methods
     of built-in classes) now depends on the hash of the identity of
     `__self__' instead of its value.  The hash and equality of
     ‘ModuleType’ and ‘MethodWrapperType’ instances (methods of
     user-defined classes and some methods of built-in classes like
     ‘str.__add__’) now depend on the hash and equality of the identity
     of `__self__' instead of its value.  ‘MethodWrapperType’ instances
     no longer support ordering.

   - bpo-33824(97): 修复"LC_ALL=C python3.7 -V"：在读取Python配置后编码
     发生更改时，正确重置命令行解析器。

   - bpo-33803(98): Fix a crash in hamt.c caused by enabling GC tracking
     for an object that hadn’t all of its fields set to NULL.

   - bpo-33738(99): Seven macro incompatibilities with the Limited API
     were fixed, and the macros *note PyIter_Check(): 1020, *note
     PyIndex_Check(): 1021. and ‘PyExceptionClass_Name()’ were added as
     functions.  A script for automatic macro checks was added.

   - bpo-33786(100): Fix asynchronous generators to handle GeneratorExit
     in athrow() correctly

   - bpo-30167(101): ‘PyRun_SimpleFileExFlags’ removes ‘__cached__’ from
     module in addition to ‘__file__’.

   - bpo-33706(102): Fix a crash in Python initialization when parsing
     the command line options.  Thanks Christoph Gohlke for the bug
     report and the fix!

   - bpo-33597(103): Reduce ‘PyGC_Head’ size from 3 words to 2 words.

   - bpo-30654(104): Fixed reset of the SIGINT handler to SIG_DFL on
     interpreter shutdown even when there was a custom handler set
     previously.  Patch by Philipp Kerling.

   - bpo-33622(105): Fixed a leak when the garbage collector fails to
     add an object with the ‘__del__’ method or referenced by it into
     the *note gc.garbage: b48. list.  ‘PyGC_Collect()’ can now be
     called when an exception is set and preserves it.

   - bpo-33462(106): Make dict and dict views reversible.  Patch by Rémi
     Lapeyre.

   - bpo-23722(107): A *note RuntimeError: 2bb. is now raised when the
     custom metaclass doesn’t provide the ‘__classcell__’ entry in the
     namespace passed to ‘type.__new__’.  A *note DeprecationWarning:
     279. was emitted in Python 3.6–3.7.

   - bpo-33499(108): Add *note PYTHONPYCACHEPREFIX: 155. environment
     variable and *note -X: 156. ‘pycache_prefix’ command-line option to
     set an alternate root directory for writing module bytecode cache
     files.

   - bpo-25711(109): The *note zipimport: 144. module has been rewritten
     in pure Python.

   - bpo-33509(110): Fix module_globals parameter of
     warnings.warn_explicit(): don’t crash if module_globals is not a
     dict.

   - bpo-31849(111): Fix signed/unsigned comparison warning in pyhash.c.

   - bpo-33475(112): Fixed miscellaneous bugs in converting annotations
     to strings and optimized parentheses in the string representation.

   - bpo-20104(113): Added support for the ‘setpgroup’, ‘resetids’,
     ‘setsigmask’, ‘setsigdef’ and ‘scheduler’ parameters of
     ‘posix_spawn’.  Patch by Pablo Galindo.

   - bpo-33391(114): Fix a leak in set_symmetric_difference().

   - bpo-33363(115): 在异步函数外使用‘‘async with‘‘ 和 ‘async for’ 时抛
     出SyntaxError异常。

   - bpo-28055(116): Fix unaligned accesses in siphash24().  Patch by
     Rolf Eike Beer.

   - bpo-33128(117): 修复导致PathFinder在sys.meta_path上出现两次的错误。
     由Pablo Galindo Salgado提供补丁。

   - bpo-33331(118): Modules imported last are now cleared first at
     interpreter shutdown.

   - bpo-33312(119): Fixed clang ubsan (undefined behavior sanitizer)
     warnings in dictobject.c by adjusting how the internal struct
     _dictkeysobject shared keys structure is declared.

   - bpo-33305(120): Improved syntax error messages for invalid
     numerical literals.

   - bpo-33306(121): Improved syntax error messages for unbalanced
     parentheses.

   - bpo-33234(122): The list constructor will pre-size and not
     over-allocate when the input length is known.

   - bpo-33270(123): Intern the names for all anonymous code objects.
     Patch by Zackery Spytz.

   - bpo-30455(124): The C and Python code and the documentation related
     to tokens are now generated from a single source file
     ‘Grammar/Tokens’.

   - bpo-33176(125): Add a ‘toreadonly()’ method to memoryviews.

   - bpo-33231(126): 修复 ‘normalizestring()’ 中潜在的内存泄漏。

   - bpo-33205(127): Change dict growth function from
     ‘round_up_to_power_2(used*2+hashtable_size/2)’ to
     ‘round_up_to_power_2(used*3)’.  Previously, dict is shrinked only
     when ‘used == 0’.  Now dict has more chance to be shrinked.

   - bpo-29922(128): Improved error messages in ’async with’ when
     ‘__aenter__()’ or ‘__aexit__()’ return non-awaitable object.

   - bpo-33199(129): Fix ‘ma_version_tag’ in dict implementation is
     uninitialized when copying from key-sharing dict.

   - bpo-33053(130): When using the -m switch, sys.path[0] is now
     explicitly expanded as the `starting' working directory, rather
     than being left as the empty path (which allows imports from the
     current working directory at the time of the import)

   - bpo-33138(131): Changed standard error message for non-pickleable
     and non-copyable types.  It now says "cannot pickle" instead of
     "can’t pickle" or "cannot serialize".

   - bpo-33018(132): Improve consistency of errors raised by
     ‘issubclass()’ when called with a non-class and an abstract base
     class as the first and second arguments, respectively.  Patch by
     Josh Bronson.

   - bpo-33083(133): ‘math.factorial’ no longer accepts arguments that
     are not int-like.  Patch by Pablo Galindo.

   - bpo-33041(134): Added new opcode *note END_ASYNC_FOR: 2e3. and
     fixes the following issues:

        * Setting global *note StopAsyncIteration: 1022. no longer
          breaks ‘async for’ loops.

        * 跳入一个 ‘async for’ 循环现在被禁止了。

        * 跳出一个 ‘async for’ 循环不再会破坏堆栈了。

   - bpo-25750(135): Fix rare Python crash due to bad refcounting in
     ‘type_getattro()’ if a descriptor deletes itself from the class.
     Patch by Jeroen Demeyer.

   - bpo-33041(136): Fixed bytecode generation for "async for" with a
     complex target.  A StopAsyncIteration raised on assigning or
     unpacking will be now propagated instead of stopping the iteration.

   - bpo-33026(137): Fixed jumping out of "with" block by setting
     f_lineno.

   - bpo-33005(138): Fix a crash on fork when using a custom memory
     allocator (ex: using PYTHONMALLOC env var).  _PyGILState_Reinit()
     and _PyInterpreterState_Enable() now use the default RAW memory
     allocator to allocate a new interpreters mutex on fork.

   - bpo-32911(139): Due to unexpected compatibility issues discovered
     during downstream beta testing, reverted bpo-29463(140).
     ‘docstring’ field is removed from Module, ClassDef, FunctionDef,
     and AsyncFunctionDef ast nodes which was added in 3.7a1.  Docstring
     expression is restored as a first statement in their body.  Based
     on patch by Inada Naoki.

   - bpo-17288(141): Prevent jumps from ’return’ and ’exception’ trace
     events.

   - bpo-32946(142): Importing names from already imported module with
     "from ...  import ..."  is now 30% faster if the module is not a
     package.

   - bpo-32932(143): Make error message more revealing when there are
     non-str objects in ‘__all__’.

   - bpo-32925(144): Optimized iterating and containing test for literal
     lists consisting of non-constants: ‘x in [a, b]’ and ‘for x in [a,
     b]’.  The case of all constant elements already was optimized.

   - bpo-32889(145): Update Valgrind suppression list to account for the
     rename of ‘Py_ADDRESS_IN_RANG’ to ‘address_in_range’.

   - bpo-32836(146): Don’t use temporary variables in cases of
     list/dict/set comprehensions

   - bpo-31356(147): Remove the new API added in bpo-31356(148)
     (gc.ensure_disabled() context manager).

   - bpo-32305(149): For namespace packages, ensure that both ‘__file__’
     and ‘__spec__.origin’ are set to None.

   - bpo-32303(150): Make sure ‘__spec__.loader’ matches ‘__loader__’
     for namespace packages.

   - bpo-32711(151): Fix the warning messages for Python/ast_unparse.c.
     Patch by Stéphane Wirtel

   - bpo-32583(152): Fix possible crashing in builtin Unicode decoders
     caused by write out-of-bound errors when using customized decode
     error handlers.

   - bpo-32489(153): A *note continue: 182. statement is now allowed in
     the *note finally: 183. clause.

   - bpo-17611(154): Simplified the interpreter loop by moving the logic
     of unrolling the stack of blocks into the compiler.  The compiler
     emits now explicit instructions for adjusting the stack of values
     and calling the cleaning up code for *note break: 2dc, *note
     continue: 182. and *note return: 191.

     Removed opcodes ‘BREAK_LOOP’, ‘CONTINUE_LOOP’, ‘SETUP_LOOP’ and
     ‘SETUP_EXCEPT’.  Added new opcodes *note ROT_FOUR: 2dd, *note
     BEGIN_FINALLY: 2de. and *note CALL_FINALLY: 2df. and *note
     POP_FINALLY: 2e0.  Changed the behavior of *note END_FINALLY: 2e1.
     and *note WITH_CLEANUP_START: 2e2.

   - bpo-32285(155): New function unicodedata.is_normalized, which can
     check whether a string is in a specific normal form.

   - bpo-10544(156): Yield expressions are now disallowed in
     comprehensions and generator expressions except the expression for
     the outermost iterable.

   - bpo-32117(157): Iterable unpacking is now allowed without
     parentheses in yield and return statements, e.g.  ‘yield 1, 2, 3,
     *rest’.  Thanks to David Cuthbert for the change and Jordan Chapman
     for added tests.

   - bpo-31902(158): Fix the ‘col_offset’ attribute for ast nodes
     ‘ast.AsyncFor’, ‘ast.AsyncFunctionDef’, and ‘ast.AsyncWith’.
     Previously, ‘col_offset’ pointed to the keyword after ‘async’.

   - bpo-25862(159): 修复 ‘io.TextIOWrapper’ 的 ‘tell()’ 方法内的错误断
     言。

   - bpo-21983(160): Fix a crash in *note ctypes.cast(): 1023. in case
     the type argument is a ctypes structured data type.  Patch by Eryk
     Sun and Oren Milman.

   - bpo-31577(161): Fix a crash in *note os.utime(): a45. in case of a
     bad ns argument.  Patch by Oren Milman.

   - bpo-29832(162): Remove references to ’getsockaddrarg’ from various
     socket error messages.  Patch by Oren Milman.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35877

   (2) https://bugs.python.org/issue35814

   (3) https://bugs.python.org/issue35766

   (4) https://bugs.python.org/issue35713

   (5) https://bugs.python.org/issue33416

   (6) https://bugs.python.org/issue35720

   (7) https://bugs.python.org/issue35634

   (8) https://bugs.python.org/issue35623

   (9) https://bugs.python.org/issue35214

   (10) https://bugs.python.org/issue35560

   (11) https://bugs.python.org/issue35552

   (12) https://bugs.python.org/issue35504

   (13) https://bugs.python.org/issue35504

   (14) https://bugs.python.org/issue35494

   (15) https://bugs.python.org/issue35444

   (16) https://bugs.python.org/issue35436

   (17) https://bugs.python.org/issue35423

   (18) https://bugs.python.org/issue35357

   (19) https://bugs.python.org/issue35372

   (20) https://bugs.python.org/issue35336

   (21) https://bugs.python.org/issue31241

   (22) https://bugs.python.org/issue33954

   (23) https://bugs.python.org/issue35269

   (24) https://bugs.python.org/issue35224

   (25) https://www.python.org/dev/peps/pep-0572

   (26) https://bugs.python.org/issue32492

   (27) https://bugs.python.org/issue35214

   (28) https://bugs.python.org/issue35214

   (29) https://bugs.python.org/issue35193

   (30) https://bugs.python.org/issue35169

   (31) https://bugs.python.org/issue34022

   (32) https://bugs.python.org/issue28401

   (33) https://bugs.python.org/issue29341

   (34) https://bugs.python.org/issue35050

   (35) https://bugs.python.org/issue29743

   (36) https://bugs.python.org/issue16806

   (37) https://bugs.python.org/issue35029

   (38) https://bugs.python.org/issue34983

   (39) https://bugs.python.org/issue34974

   (40) https://bugs.python.org/issue34939

   (41) https://bugs.python.org/issue34973

   (42) https://bugs.python.org/issue34876

   (43) https://bugs.python.org/issue34879

   (44) https://bugs.python.org/issue34784

   (45) https://bugs.python.org/issue32912

   (46) https://bugs.python.org/issue34854

   (47) https://bugs.python.org/issue34850

   (48) https://bugs.python.org/issue34824

   (49) https://bugs.python.org/issue30156

   (50) https://bugs.python.org/issue34762

   (51) https://bugs.python.org/issue34751

   (52) https://bugs.python.org/issue34735

   (53) https://bugs.python.org/issue34683

   (54) https://bugs.python.org/issue34651

   (55) https://bugs.python.org/issue34653

   (56) https://bugs.python.org/issue32236

   (57) https://bugs.python.org/issue34641

   (58) https://bugs.python.org/issue34637

   (59) https://bugs.python.org/issue1621

   (60) https://bugs.python.org/issue34588

   (61) https://bugs.python.org/issue34485

   (62) https://bugs.python.org/issue34485

   (63) https://bugs.python.org/issue34485

   (64) https://bugs.python.org/issue34485

   (65) https://bugs.python.org/issue34527

   (66) https://bugs.python.org/issue34527

   (67) https://bugs.python.org/issue34403

   (68) https://bugs.python.org/issue34523

   (69) https://bugs.python.org/issue12458

   (70) https://bugs.python.org/issue34408

   (71) https://bugs.python.org/issue34400

   (72) https://bugs.python.org/issue33073

   (73) https://bugs.python.org/issue34377

   (74) https://bugs.python.org/issue34353

   (75) https://bugs.python.org/issue34320

   (76) https://bugs.python.org/issue34113

   (77) https://bugs.python.org/issue34100

   (78) https://bugs.python.org/issue34151

   (79) https://bugs.python.org/issue34170

   (80) https://bugs.python.org/issue33237

   (81) https://bugs.python.org/issue34149

   (82) https://bugs.python.org/issue34125

   (83) https://bugs.python.org/issue34141

   (84) https://bugs.python.org/issue34126

   (85) https://bugs.python.org/issue24618

   (86) https://bugs.python.org/issue34068

   (87) https://bugs.python.org/issue34087

   (88) https://bugs.python.org/issue34080

   (89) https://bugs.python.org/issue34066

   (90) https://bugs.python.org/issue34042

   (91) https://bugs.python.org/issue33418

   (92) https://bugs.python.org/issue33985

   (93) https://bugs.python.org/issue33956

   (94) https://bugs.python.org/issue24596

   (95) https://bugs.python.org/issue33451

   (96) https://bugs.python.org/issue1617161

   (97) https://bugs.python.org/issue33824

   (98) https://bugs.python.org/issue33803

   (99) https://bugs.python.org/issue33738

   (100) https://bugs.python.org/issue33786

   (101) https://bugs.python.org/issue30167

   (102) https://bugs.python.org/issue33706

   (103) https://bugs.python.org/issue33597

   (104) https://bugs.python.org/issue30654

   (105) https://bugs.python.org/issue33622

   (106) https://bugs.python.org/issue33462

   (107) https://bugs.python.org/issue23722

   (108) https://bugs.python.org/issue33499

   (109) https://bugs.python.org/issue25711

   (110) https://bugs.python.org/issue33509

   (111) https://bugs.python.org/issue31849

   (112) https://bugs.python.org/issue33475

   (113) https://bugs.python.org/issue20104

   (114) https://bugs.python.org/issue33391

   (115) https://bugs.python.org/issue33363

   (116) https://bugs.python.org/issue28055

   (117) https://bugs.python.org/issue33128

   (118) https://bugs.python.org/issue33331

   (119) https://bugs.python.org/issue33312

   (120) https://bugs.python.org/issue33305

   (121) https://bugs.python.org/issue33306

   (122) https://bugs.python.org/issue33234

   (123) https://bugs.python.org/issue33270

   (124) https://bugs.python.org/issue30455

   (125) https://bugs.python.org/issue33176

   (126) https://bugs.python.org/issue33231

   (127) https://bugs.python.org/issue33205

   (128) https://bugs.python.org/issue29922

   (129) https://bugs.python.org/issue33199

   (130) https://bugs.python.org/issue33053

   (131) https://bugs.python.org/issue33138

   (132) https://bugs.python.org/issue33018

   (133) https://bugs.python.org/issue33083

   (134) https://bugs.python.org/issue33041

   (135) https://bugs.python.org/issue25750

   (136) https://bugs.python.org/issue33041

   (137) https://bugs.python.org/issue33026

   (138) https://bugs.python.org/issue33005

   (139) https://bugs.python.org/issue32911

   (140) https://bugs.python.org/issue29463

   (141) https://bugs.python.org/issue17288

   (142) https://bugs.python.org/issue32946

   (143) https://bugs.python.org/issue32932

   (144) https://bugs.python.org/issue32925

   (145) https://bugs.python.org/issue32889

   (146) https://bugs.python.org/issue32836

   (147) https://bugs.python.org/issue31356

   (148) https://bugs.python.org/issue31356

   (149) https://bugs.python.org/issue32305

   (150) https://bugs.python.org/issue32303

   (151) https://bugs.python.org/issue32711

   (152) https://bugs.python.org/issue32583

   (153) https://bugs.python.org/issue32489

   (154) https://bugs.python.org/issue17611

   (155) https://bugs.python.org/issue32285

   (156) https://bugs.python.org/issue10544

   (157) https://bugs.python.org/issue32117

   (158) https://bugs.python.org/issue31902

   (159) https://bugs.python.org/issue25862

   (160) https://bugs.python.org/issue21983

   (161) https://bugs.python.org/issue31577

   (162) https://bugs.python.org/issue29832


File: python.info,  Node: 库<29>,  Next: 文档<25>,  Prev: 核心与内置<29>,  Up: Python 3 8 0 alpha 1

1.18.30.3 库
............

   - bpo-35845(1): Add ’order’ parameter to memoryview.tobytes().

   - bpo-35864(2): The _asdict() method for collections.namedtuple now
     returns a regular dict instead of an OrderedDict.

   - bpo-35537(3): An ExitStack is now used internally within
     subprocess.POpen to clean up pipe file handles.  No behavior change
     in normal operation.  But if closing one handle were ever to cause
     an exception, the others will now be closed instead of leaked.
     (patch by Giampaolo Rodola)

   - bpo-35847(4): RISC-V needed the CTYPES_PASS_BY_REF_HACK. Fixes
     ctypes Structure test_pass_by_value.

   - bpo-35813(5): Shared memory submodule added to multiprocessing to
     avoid need for serialization between processes

   - bpo-35780(6): Fix lru_cache() errors arising in recursive,
     reentrant, or multi-threaded code.  These errors could result in
     orphan links and in the cache being trapped in a state with fewer
     than the specified maximum number of links.  Fix handling of
     negative maxsize which should have been treated as zero.  Fix
     errors in toggling the "full" status flag.  Fix misordering of
     links when errors are encountered.  Sync-up the C code and pure
     Python code for the space saving path in functions with a single
     positional argument.  In this common case, the space overhead of an
     lru cache entry is reduced by almost half.  Fix counting of cache
     misses.  In error cases, the miss count was out of sync with the
     actual number of times the underlying user function was called.

   - bpo-35537(7): *note os.posix_spawn(): 258. and *note
     os.posix_spawnp(): 1025. now have a `setsid' parameter.

   - bpo-23846(8): *note asyncio.ProactorEventLoop: 1ac. now catches and
     logs send errors when the self-pipe is full.

   - bpo-34323(9): *note asyncio: a.: Enhance ‘IocpProactor.close()’
     log: wait 1 second before the first log, then log every second.
     Log also the number of seconds since ‘close()’ was called.

   - bpo-35674(10): Add a new *note os.posix_spawnp(): 1025. function.
     Patch by Joannah Nanjekye.

   - bpo-35733(11): ‘ast.Constant(boolean)’ no longer an instance of
     ‘ast.Num’.  Patch by Anthony Sottile.

   - bpo-35726(12): QueueHandler.prepare() now makes a copy of the
     record before modifying and enqueueing it, to avoid affecting other
     handlers in the chain.

   - bpo-35719(13): Sped up multi-argument *note math: b2. functions
     atan2(), copysign(), remainder() and hypot() by 1.3–2.5 times.

   - bpo-35717(14): Fix KeyError exception raised when using enums and
     compile.  Patch contributed by Rémi Lapeyre.

   - bpo-35699(15): Fixed detection of Visual Studio Build Tools 2017 in
     distutils

   - bpo-32710(16): Fix memory leaks in asyncio ProactorEventLoop on
     overlapped operation failure.

   - bpo-35702(17): The *note time.CLOCK_UPTIME_RAW: 23a. constant is
     now available for macOS 10.12.

   - bpo-32710(18): Fix a memory leak in asyncio in the
     ProactorEventLoop when ‘ReadFile()’ or ‘WSASend()’ overlapped
     operation fail immediately: release the internal buffer.

   - bpo-35682(19): Fix ‘asyncio.ProactorEventLoop.sendfile()’: don’t
     attempt to set the result of an internal future if it’s already
     done.

   - bpo-35283(20): Add a deprecated warning for the
     ‘threading.Thread.isAlive()’ method.  Patch by Dong-hee Na.

   - bpo-35664(21): Improve operator.itemgetter() performance by 33%
     with optimized argument handling and with adding a fast path for
     the common case of a single non-negative integer index into a tuple
     (which is the typical use case in the standard library).

   - bpo-35643(22): 修复了 Modules/_sha3/cleanup.py 中的一个
     SyntaxWarning: invalid escape sequence。 补丁作者 Mickaël
     Schoentgen。

   - bpo-35619(23): Improved support of custom data descriptors in *note
     help(): 57b. and *note pydoc: da.

   - bpo-28503(24): 当库函数可用时 *note crypt: 29. 模块现在将在内部使用
     ‘crypt_r()’ 而非 *note crypt(): 29.。

   - bpo-35614(25): Fixed help() on metaclasses.  Patch by Sanyam
     Khurana.

   - bpo-35568(26): Expose ‘raise(signum)’ as ‘raise_signal’

   - bpo-35588(27): The floor division and modulo operations and the
     *note divmod(): 153. function on *note fractions.Fraction: 186.
     types are 2–4x faster.  Patch by Stefan Behnel.

   - bpo-35585(28): 加快构建按值枚举的速度，例如 http.HTTPStatus(200)。

   - bpo-30561(29): random.gammavariate(1.0, beta) now computes the same
     result as random.expovariate(1.0 / beta).  This synchonizes the two
     algorithms and eliminates some idiosyncrasies in the old
     implementation.  It does however produce a difference stream of
     random variables than it used to.

   - bpo-35537(30): The *note subprocess: fa. module can now use the
     *note os.posix_spawn(): 258. function in some cases for better
     performance.

   - bpo-35526(31): Delaying the ’joke’ of barry_as_FLUFL.mandatory to
     Python version 4.0

   - bpo-35523(32): Remove *note ctypes: 2b. callback workaround: no
     longer create a callback at startup.  Avoid SELinux alert on
     ‘import ctypes’ and ‘import uuid’.

   - bpo-31784(33): *note uuid.uuid1(): 41b. now calls *note
     time.time_ns(): 32c. rather than ‘int(time.time() * 1e9)’.

   - bpo-35513(34): ‘unittest.runner’ 的 ‘TextTestRunner’ 现在将使用
     *note time.perf_counter(): 2ab. 而非 *note time.time(): 326. 来计量
     一个测试的执行时间: *note time.time(): 326. 可以回退，而 *note
     time.perf_counter(): 2ab. 为单调递增。

   - bpo-35502(35): 修复了构建树未完成的情况下 *note
     xml.etree.ElementTree.TreeBuilder: 254. 中的引用泄漏（特别是在解析
     XML 期间引发错误的时候）。

   - bpo-35348(36): Make *note platform.architecture(): 1026. parsing of
     ‘file’ command output more reliable: add the ‘-b’ option to the
     ‘file’ command to omit the filename, force the usage of the C
     locale, and search also the "shared object" pattern.

   - bpo-35491(37): *note multiprocessing: b8.: Add ‘Pool.__repr__()’
     and enhance ‘BaseProcess.__repr__()’ (add pid and parent pid) to
     ease debugging.  Pool state constant values are now strings instead
     of integers, for example ‘RUN’ value becomes ‘'RUN'’ instead of
     ‘0’.

   - bpo-35477(38): ‘multiprocessing.Pool.__enter__()’ now fails if the
     pool is not running: ‘with pool:’ fails if used more than once.

   - bpo-31446(39): 复制被传递给 CreateProcessW 的命令行，因为此函数能改
     变输入缓存的内容。

   - bpo-35471(40): Python2.4 取消了对MacOS 9 的支持。Python3.7 中已弃用
     macpath 模块。该模块现在已移除。

   - bpo-23057(41): Unblock Proactor event loop when keyboard interrupt
     is received on Windows

   - bpo-35052(42): Fix xml.dom.minidom cloneNode() on a document with
     an entity: pass the correct arguments to the user data handler of
     an entity.

   - bpo-20239(43): Allow repeated assignment deletion of *note
     unittest.mock.Mock: 24a. attributes.  Patch by Pablo Galindo.

   - bpo-17185(44): 在 mock 上设置 ‘__signature__’ 以便 *note inspect:
     a1. 能获得签名。 补丁作者为 Karthikeyan Singaravelan。

   - bpo-35445(45): Memory errors during creating posix.environ no
     longer ignored.

   - bpo-35415(46): Validate fileno= argument to socket.socket().

   - bpo-35424(47): ‘multiprocessing.Pool’ destructor now emits *note
     ResourceWarning: 4d8. if the pool is still running.

   - bpo-35330(48): When a ‘Mock’ instance was used to wrap an object,
     if ‘side_effect’ is used in one of the mocks of it methods, don’t
     call the original implementation and return the result of using the
     side effect the same way that it is done with return_value.

   - bpo-35346(49): 从 *note platform: cf. 模块中删除 MacOS 9 和
     Rhapsody 支持。Rhapsody 上一次发布是在2000年。MacOS 9 上一次发布是
     在2001年。

   - bpo-10496(50): ‘check_environ()’ of ‘distutils.utils’ now catches
     *note KeyError: 2c8. on calling *note pwd.getpwuid(): 1027.: don’t
     create the ‘HOME’ environment variable in this case.

   - bpo-10496(51): ‘posixpath.expanduser()’ now returns the input
     `path' unchanged if the ‘HOME’ environment variable is not set and
     the current user has no home directory (if the current user
     identifier doesn’t exist in the password database).  This change
     fix the *note site: ec. module if the current user doesn’t exist in
     the password database (if the user has no home directory).

   - bpo-35389(52): *note platform.libc_ver(): 1028. now uses
     ‘os.confstr('CS_GNU_LIBC_VERSION')’ if available and the
     `executable' parameter is not set.

   - bpo-35394(53): Add empty slots to asyncio abstract protocols.

   - bpo-35310(54): Fix a bug in *note select.select(): 67c. where, in
     some cases, the file descriptor sequences were returned unmodified
     after a signal interruption, even though the file descriptors might
     not be ready yet.  *note select.select(): 67c. will now always
     return empty lists if a timeout has occurred.  Patch by Oran
     Avraham.

   - bpo-35380(55): Enable TCP_NODELAY on Windows for proactor asyncio
     event loop.

   - bpo-35341(56): Add generic version of ‘collections.OrderedDict’ to
     the ‘typing’ module.  Patch by Ismo Toijala.

   - bpo-35371(57): Fixed possible crash in ‘os.utime()’ on Windows when
     pass incorrect arguments.

   - bpo-35346(58): *note platform.uname(): 1029. now redirects ‘stderr’
     to *note os.devnull: 102a. when running external programs like ‘cmd
     /c ver’.

   - bpo-35066(59): Previously, calling the strftime() method on a
     datetime object with a trailing ’%’ in the format string would
     result in an exception.  However, this only occurred when the
     datetime C module was being used; the python implementation did not
     match this behavior.  Datetime is now PEP-399 compliant, and will
     not throw an exception on a trailing ’%’.

   - bpo-35345(60): The function ‘platform.popen’ has been removed, it
     was deprecated since Python 3.3: use *note os.popen(): 2aa.
     instead.

   - bpo-35344(61): On macOS, *note platform.platform(): 102b. now uses
     *note platform.mac_ver(): 102c, if it returns a non-empty release
     string, to get the macOS version rather than the darwin version.

   - bpo-35312(62): Make ‘lib2to3.pgen2.parse.ParseError’ round-trip
     pickle-able.  Patch by Anthony Sottile.

   - bpo-35308(63): Fix regression in ‘webbrowser’ where default
     browsers may be preferred over browsers in the ‘BROWSER’
     environment variable.

   - bpo-24746(64): Avoid stripping trailing whitespace in doctest fancy
     diff.  Original patch by R. David Murray & Jairo Trad.  Enhanced by
     Sanyam Khurana.

   - bpo-28604(65): *note locale.localeconv(): 492. now sets temporarily
     the ‘LC_CTYPE’ locale to the ‘LC_MONETARY’ locale if the two
     locales are different and monetary strings are non-ASCII. This
     temporary change affects other threads.

   - bpo-35277(66): Update ensurepip to install pip 18.1 and setuptools
     40.6.2.

   - bpo-24209(67): Adds IPv6 support when invoking http.server
     directly.

   - bpo-35226(68): Recursively check arguments when testing for
     equality of *note unittest.mock.call: f8a. objects and add note
     that tracking of parameters used to create ancestors of mocks in
     ‘mock_calls’ is not possible.

   - bpo-29564(69): The warnings module now suggests to enable
     tracemalloc if the source is specified, the tracemalloc module is
     available, but tracemalloc is not tracing memory allocations.

   - bpo-35189(70): Modify the following fnctl function to retry if
     interrupted by a signal (EINTR): flock, lockf, fnctl

   - bpo-30064(71): Use add_done_callback() in sock_* asyncio API to
     unsubscribe reader/writer early on calcellation.

   - bpo-35186(72): Removed the "built with" comment added when
     ‘setup.py upload’ is used with either ‘bdist_rpm’ or ‘bdist_dumb’.

   - bpo-35152(73): Allow sending more than 2 GB at once on a
     multiprocessing connection on non-Windows systems.

   - bpo-35062(74): Fix incorrect parsing of
     ‘_io.IncrementalNewlineDecoder’’s `translate' argument.

   - bpo-35065(75): Remove ‘StreamReaderProtocol._untrack_reader’.  The
     call to ‘_untrack_reader’ is currently performed too soon, causing
     the protocol to forget about the reader before ‘connection_lost’
     can run and feed the EOF to the reader.

   - bpo-34160(76): ElementTree and minidom now preserve the attribute
     order specified by the user.

   - bpo-35079(77): Improve difflib.SequenceManager.get_matching_blocks
     doc by adding ’non-overlapping’ and changing ’!=’ to ’<’.

   - bpo-33710(78): Deprecated ‘l*gettext()’ functions and methods in
     the *note gettext: 89. module.  They return encoded bytes instead
     of Unicode strings and are artifacts from Python 2 times.  Also
     deprecated functions and methods related to setting the charset for
     ‘l*gettext()’ functions and methods.

   - bpo-35017(79): *note socketserver.BaseServer.serve_forever(): a93.
     now exits immediately if it’s *note shutdown(): 102d. method is
     called while it is polling for new events.

   - bpo-35024(80): *note importlib: 9b. no longer logs ‘wrote’
     redundantly after ‘(created|could not create)’ is already logged.
     Patch by Quentin Agren.

   - bpo-35047(81): ‘unittest.mock’ now includes mock calls in exception
     messages if ‘assert_not_called’, ‘assert_called_once’, or
     ‘assert_called_once_with’ fails.  Patch by Petter Strandmark.

   - bpo-31047(82): Fix ‘ntpath.abspath’ regression where it didn’t
     remove a trailing separator on Windows.  Patch by Tim Graham.

   - bpo-35053(83): tracemalloc now tries to update the traceback when
     an object is reused from a "free list" (optimization for faster
     object creation, used by the builtin list type for example).

   - bpo-31553(84): Add the –json-lines option to json.tool.  Patch by
     hongweipeng.

   - bpo-34794(85): Fixed a leak in Tkinter when pass the Python wrapper
     around Tcl_Obj back to Tcl/Tk.

   - bpo-34909(86): Enum: fix grandchildren subclassing when parent
     mixed with concrete data types.

   - bpo-35022(87): *note unittest.mock.MagicMock: 78e. now supports the
     ‘__fspath__’ method (from *note os.PathLike: 4f3.).

   - bpo-35008(88): Fixed references leaks when call the
     ‘__setstate__()’ method of *note xml.etree.ElementTree.Element:
     acc. in the C implementation for already initialized element.

   - bpo-23420(89): Verify the value for the parameter ’-s’ of the
     cProfile CLI. Patch by Robert Kuska

   - bpo-33947(90): dataclasses now handle recursive reprs without
     raising RecursionError.

   - bpo-34890(91): Make *note inspect.iscoroutinefunction(): 701, *note
     inspect.isgeneratorfunction(): 102e. and *note
     inspect.isasyncgenfunction(): 102f. work with *note
     functools.partial(): 7d1.  Patch by Pablo Galindo.

   - bpo-34521(92): Use *note socket.CMSG_SPACE(): 1030. to calculate
     ancillary data size instead of *note socket.CMSG_LEN(): 1031. in
     ‘multiprocessing.reduction.recvfds()’ as RFC 3542(93) requires the
     use of the former for portable applications.

   - bpo-31522(94): The ‘mailbox.mbox.get_string’ function `from_'
     parameter can now successfully be set to a non-default value.

   - bpo-34970(95): Protect tasks weak set manipulation in
     ‘asyncio.all_tasks()’

   - bpo-34969(96): gzip: Add –fast, –best on the gzip CLI, these
     parameters will be used for the fast compression method (quick) or
     the best method compress (slower, but smaller file).  Also, change
     the default compression level to 6 (tradeoff).

   - bpo-16965(97): The *note 2to3: 1032. *note execfile: 1033. fixer
     now opens the file with mode ‘'rb'’.  Patch by Zackery Spytz.

   - bpo-34966(98): *note pydoc: da. now supports aliases not only to
     methods defined in the end class, but also to inherited methods.
     The docstring is not duplicated for aliases.

   - bpo-34926(99): *note mimetypes.MimeTypes.guess_type(): 1034. now
     accepts *note path-like object: 373. in addition to url strings.
     Patch by Mayank Asthana.

   - bpo-23831(100): Add ‘moveto()’ method to the ‘tkinter.Canvas’
     widget.  Patch by Juliette Monsel.

   - bpo-34941(101): Methods ‘find()’, ‘findtext()’ and ‘findall()’ of
     the ‘Element’ class in the *note xml.etree.ElementTree: 138. module
     are now able to find children which are instances of ‘Element’
     subclasses.

   - bpo-32680(102): *note smtplib.SMTP: a89. objects now always have a
     ‘sock’ attribute present

   - bpo-34769(103): Fix for async generators not finalizing when event
     loop is in debug mode and garbage collector runs in another thread.

   - bpo-34936(104): Fix ‘TclError’ in
     ‘tkinter.Spinbox.selection_element()’.  Patch by Juliette Monsel.

   - bpo-34829(105): Add methods ‘selection_from’, ‘selection_range’,
     ‘selection_present’ and ‘selection_to’ to the ‘tkinter.Spinbox’ for
     consistency with the ‘tkinter.Entry’ widget.  Patch by Juliette
     Monsel.

   - bpo-34911(106): Added `secure_protocols' argument to
     `http.cookiejar.DefaultCookiePolicy' to allow for tweaking of
     protocols and also to add support by default for `wss', the secure
     websocket protocol.

   - bpo-34922(107): Fixed integer overflow in the *note digest(): 1035.
     and *note hexdigest(): 1036. methods for the SHAKE algorithm in the
     *note hashlib: 8d. module.

   - bpo-34925(108): 25% speedup in argument parsing for the functions
     in the bisect module.

   - bpo-34900(109): Fixed *note unittest.TestCase.debug(): 1037. when
     used to call test methods with subtests.  Patch by Bruno Oliveira.

   - bpo-34844(110): logging.Formatter enhancement - Ensure styles and
     fmt matches in logging.Formatter - Added validate method in each
     format style class: StrFormatStyle, PercentStyle,
     StringTemplateStyle.  - This method is called in the constructor of
     logging.Formatter class - Also re-raise the KeyError in the format
     method of each style class, so it would a bit clear that it’s an
     error with the invalid format fields.

   - bpo-34897(111): Adjust test.support.missing_compiler_executable
     check so that a nominal command name of "" is ignored.  Patch by
     Michael Felt.

   - bpo-34871(112): Fix inspect module polluted ‘sys.modules’ when
     parsing ‘__text_signature__’ of callable.

   - bpo-34898(113): Add ‘mtime’ argument to *note gzip.compress: 1d2.
     for reproducible output.  Patch by Guo Ci Teo.

   - bpo-28441(114): On Cygwin and MinGW, ensure that ‘sys.executable’
     always includes the full filename in the path, including the ‘.exe’
     suffix (unless it is a symbolic link).

   - bpo-34866(115): Adding ‘max_num_fields’ to ‘cgi.FieldStorage’ to
     make DOS attacks harder by limiting the number of
     ‘MiniFieldStorage’ objects created by ‘FieldStorage’.

   - bpo-34711(116): http.server ensures it reports HTTPStatus.NOT_FOUND
     when the local path ends with "/" and is not a directory, even if
     the underlying OS (e.g.  AIX) accepts such paths as a valid file
     reference.  Patch by Michael Felt.

   - bpo-34872(117): Fix self-cancellation in C implementation of
     asyncio.Task

   - bpo-34849(118): Don’t log waiting for ‘selector.select’ in asyncio
     loop iteration.  The waiting is pretty normal for any asyncio
     program, logging its time just adds a noise to logs without any
     useful information provided.

   - bpo-34022(119): The ‘SOURCE_DATE_EPOCH’ environment variable no
     longer overrides the value of the `invalidation_mode' argument to
     *note py_compile.compile(): 216, and determines its default value
     instead.

   - bpo-34819(120): 使用一个单一时钟计算 ‘Executor.map()’ 和
     ‘as_completed()’ 中的超时，以防止当系统时钟被修改时因偏离导致的超时
     。

   - bpo-34758(121): Add .wasm -> application/wasm to list of recognized
     file types and content type headers

   - bpo-34789(122): *note xml.sax.make_parser(): 1038. now accepts any
     iterable as its `parser_list' argument.  Patch by Andrés Delfino.

   - bpo-34334(123): In ‘QueueHandler’, clear ‘exc_text’ from
     ‘LogRecord’ to prevent traceback from being written twice.

   - bpo-34687(124): On Windows, asyncio now uses ProactorEventLoop,
     instead of SelectorEventLoop, by default.

   - bpo-5950(125): Support reading zip files with archive comments in
     *note zipimport: 144.

   - bpo-32892(126): The parser now represents all constants as
     ‘ast.Constant’ instead of using specific constant AST types (‘Num’,
     ‘Str’, ‘Bytes’, ‘NameConstant’ and ‘Ellipsis’).  These classes are
     considered deprecated and will be removed in future Python
     versions.

   - bpo-34728(127): Add deprecation warning when ‘loop’ is used in
     methods: *note asyncio.sleep: 286, *note asyncio.wait: 28a. and
     *note asyncio.wait_for: 289.

   - bpo-34738(128): ZIP files created by *note distutils: 39. will now
     include entries for directories.

   - bpo-34659(129): Add an optional `initial' argument to
     itertools.accumulate().

   - bpo-29577(130): Support multiple mixin classes when creating Enums.

   - bpo-34670(131): Add SSLContext.post_handshake_auth and
     SSLSocket.verify_client_post_handshake for TLS 1.3’s post handshake
     authentication feature.

   - bpo-32718(132): The Activate.ps1 script from venv works with
     PowerShell Core 6.1 and is now available under all operating
     systems.

   - bpo-31177(133): Fix bug that prevented using *note reset_mock: 5b3.
     on mock instances with deleted attributes

   - bpo-34672(134): Add a workaround, so the ‘'Z'’ *note
     time.strftime(): b6d. specifier on the musl C library can work in
     some cases.

   - bpo-34666(135): Implement ‘asyncio.StreamWriter.awrite’ and
     ‘asyncio.StreamWriter.aclose()’ coroutines.  Methods are needed for
     providing a consistent stream API with control flow switched on by
     default.

   - bpo-6721(136): Acquire the logging module’s commonly used internal
     locks while fork()ing to avoid deadlocks in the child process.

   - bpo-34658(137): Fix a rare interpreter unhandled exception state
     SystemError only seen when using subprocess with a preexec_fn while
     an after_parent handler has been registered with
     os.register_at_fork and the fork system call fails.

   - bpo-34652(138): Ensure *note os.lchmod(): 1039. is never defined on
     Linux.

   - bpo-34638(139): Store a weak reference to stream reader to break
     strong references loop between reader and protocol.  It allows to
     detect and close the socket if the stream is deleted (garbage
     collected) without ‘close()’ call.

   - bpo-34536(140): ‘Enum._missing_’: raise *note ValueError: 1fc. if
     None returned and *note TypeError: 193. if non-member is returned.

   - bpo-34636(141): Speed up re scanning of many non-matching
     characters for s w and d within bytes objects.  (microoptimization)

   - bpo-24412(142): Add *note addModuleCleanup(): 24b. and *note
     addClassCleanup(): 24c. to unittest to support cleanups for
     ‘setUpModule()’ and *note setUpClass(): 24d.  Patch by Lisa Roach.

   - bpo-34630(143): Don’t log SSL certificate errors in asyncio code
     (connection error logging is skipped already).

   - bpo-32490(144): Prevent filename duplication in *note subprocess:
     fa. exception messages.  Patch by Zackery Spytz.

   - bpo-34363(145): dataclasses.asdict() and .astuple() now handle
     namedtuples correctly.

   - bpo-34625(146): Update vendorized expat library version to 2.2.6.

   - bpo-32270(147): The subprocess module no longer mistakenly closes
     redirected fds even when they were in pass_fds when outside of the
     default {0, 1, 2} set.

   - bpo-34622(148): Create a dedicated ‘asyncio.CancelledError’,
     ‘asyncio.InvalidStateError’ and ‘asyncio.TimeoutError’ exception
     classes.  Inherit them from corresponding exceptions from
     ‘concurrent.futures’ package.  Extract ‘asyncio’ exceptions into a
     separate file.

   - bpo-34610(149): Fixed iterator of
     ‘multiprocessing.managers.DictProxy’.

   - bpo-34421(150): Fix distutils logging for non-ASCII strings.  This
     caused installation issues on Windows.

   - bpo-34604(151): Fix possible mojibake in the error message of *note
     pwd.getpwnam: 103a. and *note grp.getgrnam: 103b. using string
     representation because of invisible characters or trailing
     whitespaces.  Patch by William Grzybowski.

   - bpo-30977(152): Make uuid.UUID use ‘__slots__’ to reduce its memory
     footprint.  Based on original patch by Wouter Bolsterlee.

   - bpo-34574(153): OrderedDict iterators are not exhausted during
     pickling anymore.  Patch by Sergey Fedoseev.

   - bpo-8110(154): Refactored *note subprocess: fa. to check for
     Windows-specific modules rather than ‘sys.platform == 'win32'’.

   - bpo-34530(155): ‘distutils.spawn.find_executable()’ now falls back
     on *note os.defpath: fef. if the ‘PATH’ environment variable is not
     set.

   - bpo-34563(156): On Windows, fix multiprocessing.Connection for very
     large read: fix _winapi.PeekNamedPipe() and _winapi.ReadFile() for
     read larger than INT_MAX (usually 2^31-1).

   - bpo-34558(157): Correct typo in Lib/ctypes/_aix.py

   - bpo-34282(158): Move ‘Enum._convert’ to ‘EnumMeta._convert_’ and
     fix enum members getting shadowed by parent attributes.

   - bpo-22872(159): When the queue is closed, *note ValueError: 1fc. is
     now raised by *note multiprocessing.Queue.put(): 103c. and *note
     multiprocessing.Queue.get(): 103d. instead of *note AssertionError:
     103e. and *note OSError: 1d4, respectively.  Patch by Zackery
     Spytz.

   - bpo-34515(160): Fix parsing non-ASCII identifiers in
     ‘lib2to3.pgen2.tokenize’ (PEP 3131).

   - bpo-13312(161): Avoids a possible integer underflow (undefined
     behavior) in the time module’s year handling code when passed a
     very low negative year value.

   - bpo-34472(162): Improved compatibility for streamed files in *note
     zipfile: 143.  Previously an optional signature was not being
     written and certain ZIP applications were not supported.  Patch by
     Silas Sewell.

   - bpo-34454(163): Fix the .fromisoformat() methods of datetime types
     crashing when given unicode with non-UTF-8-encodable code points.
     Specifically, datetime.fromisoformat() now accepts surrogate
     unicode code points used as the separator.  Report and tests by
     Alexey Izbyshev, patch by Paul Ganssle.

   - bpo-6700(164): Fix inspect.getsourcelines for module level
     frames/tracebacks.  Patch by Vladimir Matveev.

   - bpo-34171(165): Running the *note trace: 113. module no longer
     creates the ‘trace.cover’ file.

   - bpo-34441(166): Fix crash when an ‘ABC’-derived class with invalid
     ‘__subclasses__’ is passed as the second argument to *note
     issubclass(): 458.  Patch by Alexey Izbyshev.

   - bpo-34427(167): Fix infinite loop in ‘a.extend(a)’ for
     ‘MutableSequence’ subclasses.

   - bpo-34412(168): Make *note signal.strsignal(): 103f. work on HP-UX.
     Patch by Michael Osipov.

   - bpo-20849(169): shutil.copytree now accepts a new ‘dirs_exist_ok’
     keyword argument.  Patch by Josh Bronson.

   - bpo-31715(170): Associate ‘.mjs’ file extension with
     ‘application/javascript’ MIME Type.

   - bpo-34384(171): *note os.readlink(): 1f4. now accepts *note
     path-like: 373. and *note bytes: 33a. objects on Windows.

   - bpo-22602(172): The UTF-7 decoder now raises *note
     UnicodeDecodeError: 1fe. for ill-formed sequences starting with "+"
     (as specified in RFC 2152).  Patch by Zackery Spytz.

   - bpo-2122(173): The *note mmap.flush(): 2c4. method now returns
     ‘None’ on success, raises an exception on error under all
     platforms.

   - bpo-34341(174): Appending to the ZIP archive with the ZIP64
     extension no longer grows the size of extra fields of existing
     entries.

   - bpo-34333(175): 修复在 *note pathlib.PurePath.with_suffix(): 1040.
     内使用%-formatting 格式化错误信息的错误。

   - bpo-18540(176): The *note imaplib.IMAP4: 614. and *note
     imaplib.IMAP4_SSL: a1f. classes now resolve to the local host IP
     correctly when the default value of `host' parameter (‘''’) is
     used.

   - bpo-26502(177): Implement ‘traceback.FrameSummary.__len__()’ method
     to preserve compatibility with the old tuple API.

   - bpo-34318(178): *note assertRaises(): ac2, *note
     assertRaisesRegex(): ac3, *note assertWarns(): ac4. and *note
     assertWarnsRegex(): ac5. no longer success if the passed callable
     is None.  They no longer ignore unknown keyword arguments in the
     context manager mode.  A DeprecationWarning was raised in these
     cases since Python 3.5.

   - bpo-9372(179): Deprecate *note __getitem__(): 280. methods of *note
     xml.dom.pulldom.DOMEventStream: 27d, *note
     wsgiref.util.FileWrapper: 27e. and *note fileinput.FileInput: 27f.

   - bpo-33613(180): Fix a race condition in
     ‘multiprocessing.semaphore_tracker’ when the tracker receives
     SIGINT before it can register signal handlers for ignoring it.

   - bpo-34248(181): Report filename in the exception raised when the
     database file cannot be opened by *note dbm.gnu.open(): 1041. and
     *note dbm.ndbm.open(): 1042. due to OS-related error.  Patch by
     Zsolt Cserna.

   - bpo-33089(182): Add math.dist() to compute the Euclidean distance
     between two points.

   - bpo-34246(183): *note smtplib.SMTP.send_message(): 74e. no longer
     modifies the content of the `mail_options' argument.  Patch by
     Pablo S. Blum de Aguiar.

   - bpo-31047(184): Fix ‘ntpath.abspath’ for invalid paths on windows.
     Patch by Franz Woellert.

   - bpo-32321(185): Add pure Python fallback for functools.reduce.
     Patch by Robert Wright.

   - bpo-34270(186): The default asyncio task class now always has a
     name which can be get or set using two new methods (*note
     get_name(): 1b2. and *note set_name(): 1b1.) and is visible in the
     *note repr(): 7d5. output.  An initial name can also be set using
     the new ‘name’ keyword argument to *note asyncio.create_task():
     1af. or the ‘create_task()’ method of the event loop.  If no
     initial name is set, the default Task implementation generates a
     name like ‘Task-1’ using a monotonic counter.

   - bpo-34263(187): asyncio’s event loop will not pass timeouts longer
     than one day to epoll/select etc.

   - bpo-34035(188): Fix several AttributeError in zipfile seek()
     methods.  Patch by Mickaël Schoentgen.

   - bpo-32215(189): Fix performance regression in *note sqlite3: f3.
     when a DML statement appeared in a different line than the rest of
     the SQL query.

   - bpo-34075(190): Deprecate passing non-ThreadPoolExecutor instances
     to ‘AbstractEventLoop.set_default_executor()’.

   - bpo-34251(191): Restore ‘msilib.Win64’ to preserve backwards
     compatibility since it’s already used by *note distutils: 39.’
     ‘bdist_msi’ command.

   - bpo-19891(192): Ignore errors caused by missing / non-writable
     homedir while writing history during exit of an interactive
     session.  Patch by Anthony Sottile.

   - bpo-33089(193): Enhanced math.hypot() to support more than two
     dimensions.

   - bpo-34228(194): tracemalloc: PYTHONTRACEMALLOC=0 environment
     variable and -X tracemalloc=0 command line option are now allowed
     to disable explicitly tracemalloc at startup.

   - bpo-13041(195): Use *note shutil.get_terminal_size(): a52. to
     calculate the terminal width correctly in the
     ‘argparse.HelpFormatter’ class.  Initial patch by Zbyszek
     Jędrzejewski-Szmek.

   - bpo-34213(196): Allow frozen dataclasses to have a field named
     "object".  Previously this conflicted with an internal use of
     "object".

   - bpo-34052(197): *note sqlite3.Connection.create_aggregate(): fad,
     *note sqlite3.Connection.create_function(): fae, *note
     sqlite3.Connection.set_authorizer(): faf, *note
     sqlite3.Connection.set_progress_handler(): fb0. methods raises
     TypeError when unhashable objects are passed as callable.  These
     methods now don’t pass such objects to SQLite API. Previous
     behavior could lead to segfaults.  Patch by Sergey Fedoseev.

   - bpo-34197(198): Attributes `skipinitialspace', `doublequote' and
     `strict' of the `dialect' attribute of the *note csv: 2a. reader
     are now *note bool: 184. instances instead of integers 0 or 1.

   - bpo-32788(199): Errors other than *note TypeError: 193. raised in
     methods ‘__adapt__()’ and ‘__conform__()’ in the *note sqlite3: f3.
     module are now propagated to the user.

   - bpo-21446(200): The *note reload: 1043. fixer now uses *note
     importlib.reload(): 3a1. instead of deprecated *note imp.reload():
     c78.

   - bpo-940286(201): pydoc’s ‘Helper.showtopic()’ method now prints the
     cross references of a topic correctly.

   - bpo-34164(202): *note base64.b32decode(): 965. could raise
     UnboundLocalError or OverflowError for incorrect padding.  Now it
     always raises ‘base64.Error’ in these cases.

   - bpo-33729(203): Fixed issues with arguments parsing in *note
     hashlib: 8d.

   - bpo-34097(204): ZipFile can zip files older than 1980-01-01 and
     newer than 2107-12-31 using a new ‘strict_timestamps’ parameter at
     the cost of setting the timestamp to the limit.

   - bpo-34108(205): Remove extraneous CR in 2to3 refactor.

   - bpo-34070(206): Make sure to only check if the handle is a tty,
     when opening a file with ‘buffering=-1’.

   - bpo-27494(207): Reverted bpo-27494(208).  2to3 rejects now a
     trailing comma in generator expressions.

   - bpo-33967(209): functools.singledispatch now raises TypeError
     instead of IndexError when no positional arguments are passed.

   - bpo-34041(210): Add the parameter `deterministic' to the *note
     sqlite3.Connection.create_function(): fae. method.  Patch by Sergey
     Fedoseev.

   - bpo-34056(211): Ensure the loader shim created by ‘imp.load_module’
     always returns bytes from its ‘get_data()’ function.  This fixes
     using ‘imp.load_module’ with PEP 552(212) hash-based pycs.

   - bpo-34054(213): The multiprocessing module now uses the monotonic
     clock *note time.monotonic(): 778. instead of the system clock
     *note time.time(): 326. to implement timeout.

   - bpo-34043(214): Optimize tarfile uncompress performance about 15%
     when gzip is used.

   - bpo-34044(215): ‘subprocess.Popen’ now copies the `startupinfo'
     argument to leave it unchanged: it will modify the copy, so that
     the same ‘STARTUPINFO’ object can be used multiple times.

   - bpo-34010(216): Fixed a performance regression for reading streams
     with tarfile.  The buffered read should use a list, instead of
     appending to a bytes object.

   - bpo-34019(217): webbrowser: Correct the arguments passed to Opera
     Browser when opening a new URL using the ‘webbrowser’ module.
     Patch by Bumsik Kim.

   - bpo-34003(218): csv.DictReader now creates dicts instead of
     OrderedDicts.  Patch by Michael Selik.

   - bpo-33978(219): Closed existing logging handlers before
     reconfiguration via fileConfig and dictConfig.  Patch by
     Karthikeyan Singaravelan.

   - bpo-14117(220): Make minor tweaks to turtledemo.  The ’wikipedia’
     example is now ’rosette’, describing what it draws.  The ’penrose’
     print output is reduced.  The’1024’ output of ’tree’ is eliminated.

   - bpo-33974(221): Fixed passing lists and tuples of strings
     containing special characters ‘"’, ‘\’, ‘{’, ‘}’ and ‘\n’ as
     options to *note ttk: 110. widgets.

   - bpo-27500(222): Fix getaddrinfo to resolve IPv6 addresses
     correctly.

   - bpo-24567(223): Improve random.choices() to handle subnormal input
     weights that could occasionally trigger an IndexError.

   - bpo-33871(224): Fixed integer overflow in *note os.readv(): 3c0,
     *note os.writev(): 3c3, *note os.preadv(): 3bf. and *note
     os.pwritev(): 3c2. and in *note os.sendfile(): 362. with `headers'
     or `trailers' arguments (on BSD-based OSes and macOS).

   - bpo-25007(225): Add *note copy.copy(): 3d3. and *note
     copy.deepcopy(): 3d4. support to zlib compressors and
     decompressors.  Patch by Zackery Spytz.

   - bpo-33929(226): multiprocessing: Fix a race condition in Popen of
     multiprocessing.popen_spawn_win32.  The child process now
     duplicates the read end of pipe instead of "stealing" it.
     Previously, the read end of pipe was "stolen" by the child process,
     but it leaked a handle if the child process had been terminated
     before it could steal the handle from the parent process.

   - bpo-33899(227): Tokenize module now implicitly emits a NEWLINE when
     provided with input that does not have a trailing new line.  This
     behavior now matches what the C tokenizer does internally.
     Contributed by Ammar Askar.

   - bpo-33897(228): Added a ’force’ keyword argument to
     logging.basicConfig().

   - bpo-33695(229): *note shutil.copytree(): 21b. uses *note
     os.scandir(): 260. function and all copy functions depending from
     it use cached *note os.stat(): 1f2. values.  The speedup for
     copying a directory with 8000 files is around +9% on Linux, +20% on
     Windows and + 30% on a Windows SMB share.  Also the number of *note
     os.stat(): 1f2. syscalls is reduced by 38% making *note
     shutil.copytree(): 21b. especially faster on network filesystems.
     (Contributed by Giampaolo Rodola’ in bpo-33695(230).)

   - bpo-33916(231): bz2 and lzma: When Decompressor.__init__() is
     called twice, free the old lock to not leak memory.

   - bpo-32568(232): Make select.epoll() and its documentation
     consistent regarding `sizehint' and `flags'.

   - bpo-33833(233): Fixed bug in asyncio where ProactorSocketTransport
     logs AssertionError if force closed during write.

   - bpo-33663(234): Convert content length to string before putting to
     header.

   - bpo-33721(235): *note os.path: c6. functions that return a boolean
     result like *note exists(): 1f7, *note lexists(): 1f8, *note
     isdir(): 1f9, *note isfile(): 1fa, *note islink(): 1f5, and *note
     ismount(): 1fb, and *note pathlib.Path: 202. methods that return a
     boolean result like *note exists(): 203, *note is_dir(): 204, *note
     is_file(): 205, *note is_mount(): 206, *note is_symlink(): 207,
     *note is_block_device(): 208, *note is_char_device(): 209, *note
     is_fifo(): 20a, *note is_socket(): 20b. now return ‘False’ instead
     of raising *note ValueError: 1fc. or its subclasses *note
     UnicodeEncodeError: 1fd. and *note UnicodeDecodeError: 1fe. for
     paths that contain characters or bytes unrepresentable at the OS
     level.

   - bpo-26544(236): Fixed implementation of *note platform.libc_ver():
     1028.  It almost always returned version ’2.9’ for glibc.

   - bpo-33843(237): Remove deprecated ‘cgi.escape’, ‘cgi.parse_qs’ and
     ‘cgi.parse_qsl’.

   - bpo-33842(238): Remove ‘tarfile.filemode’ which is deprecated since
     Python 3.3.

   - bpo-30167(239): Prevent site.main() exception if PYTHONSTARTUP is
     set.  Patch by Steve Weber.

   - bpo-33805(240): Improve error message of dataclasses.replace() when
     an InitVar is not specified

   - bpo-33687(241): Fix the call to ‘os.chmod()’ for ‘uu.decode()’ if a
     mode is given or decoded.  Patch by Timo Furrer.

   - bpo-33812(242): Datetime instance d with non-None tzinfo, but with
     d.tzinfo.utcoffset(d) returning None is now treated as naive by the
     astimezone() method.

   - bpo-32108(243): In configparser, don’t clear section when it is
     assigned to itself.

   - bpo-27397(244): Make email module properly handle invalid-length
     base64 strings.

   - bpo-33578(245): Implement multibyte encoder/decoder state methods

   - bpo-30805(246): Avoid race condition with debug logging

   - bpo-33476(247): Fix _header_value_parser.py when address group is
     missing final ’;’.  Contributed by Enrique Perez-Terron

   - bpo-33694(248): asyncio: Fix a race condition causing data loss on
     pause_reading()/resume_reading() when using the ProactorEventLoop.

   - bpo-32493(249): Correct test for ‘uuid_enc_be’ availability in
     ‘configure.ac’.  Patch by Michael Felt.

   - bpo-33792(250): Add asyncio.WindowsSelectorEventLoopPolicy and
     asyncio.WindowsProactorEventLoopPolicy.

   - bpo-33274(251): W3C DOM Level 1 specifies return value of
     Element.removeAttributeNode() as "The Attr node that was removed."
     xml.dom.minidom now complies with this requirement.

   - bpo-33778(252): Update ‘unicodedata’’s database to Unicode version
     11.0.0.

   - bpo-33165(253): Added a stacklevel parameter to logging calls to
     allow use of wrapper/helper functions for logging APIs.

   - bpo-33770(254): improve base64 exception message for encoded inputs
     of invalid length

   - bpo-33769(255): asyncio/start_tls: Fix error message; cancel
     callbacks in case of an unhandled error; mark SSLTransport as
     closed if it is aborted.

   - bpo-33767(256): The concatenation (‘+’) and repetition (‘*’)
     sequence operations now raise *note TypeError: 193. instead of
     *note SystemError: 604. when performed on *note mmap.mmap: 1ed.
     objects.  Patch by Zackery Spytz.

   - bpo-33734(257): asyncio/ssl: Fix AttributeError, increase default
     handshake timeout

   - bpo-31014(258): Fixed creating a controller for *note webbrowser:
     12a. when a user specifies a path to an entry in the BROWSER
     environment variable.  Based on patch by John Still.

   - bpo-2504(259): Add gettext.pgettext() and variants.

   - bpo-33197(260): Add description property for _ParameterKind

   - bpo-32751(261): When cancelling the task due to a timeout, *note
     asyncio.wait_for(): 289. will now wait until the cancellation is
     complete.

   - bpo-32684(262): Fix gather to propagate cancellation of itself even
     with return_exceptions.

   - bpo-33654(263): Support protocol type switching in
     SSLTransport.set_protocol().

   - bpo-33674(264): Pause the transport as early as possible to further
     reduce the risk of data_received() being called before
     connection_made().

   - bpo-33671(265): *note shutil.copyfile(): 259, *note shutil.copy():
     25a, *note shutil.copy2(): 25b, *note shutil.copytree(): 21b. and
     *note shutil.move(): 25c. use platform-specific fast-copy syscalls
     on Linux and macOS in order to copy the file more efficiently.  On
     Windows *note shutil.copyfile(): 259. uses a bigger default buffer
     size (1 MiB instead of 16 KiB) and a *note memoryview(): 25d.-based
     variant of *note shutil.copyfileobj(): 25e. is used.  The speedup
     for copying a 512MiB file is about +26% on Linux, +50% on macOS and
     +40% on Windows.  Also, much less CPU cycles are consumed.
     (Contributed by Giampaolo Rodola’ in bpo-25427(266).)

   - bpo-33674(267): Fix a race condition in
     SSLProtocol.connection_made() of asyncio.sslproto: start
     immediately the handshake instead of using call_soon().
     Previously, data_received() could be called before the handshake
     started, causing the handshake to hang or fail.

   - bpo-31647(268): Fixed bug where calling write_eof() on a
     _SelectorSocketTransport after it’s already closed raises
     AttributeError.

   - bpo-32610(269): Make asyncio.all_tasks() return only pending tasks.

   - bpo-32410(270): Avoid blocking on file IO in sendfile fallback code

   - bpo-33469(271): Fix RuntimeError after closing loop that used
     run_in_executor

   - bpo-33672(272): Fix Task.__repr__ crash with Cython’s bogus
     coroutines

   - bpo-33654(273): Fix transport.set_protocol() to support switching
     between asyncio.Protocol and asyncio.BufferedProtocol.  Fix
     loop.start_tls() to work with asyncio.BufferedProtocols.

   - bpo-33652(274): Pickles of type variables and subscripted generics
     are now future-proof and compatible with older Python versions.

   - bpo-32493(275): Fixed *note uuid.uuid1(): 41b. on FreeBSD.

   - bpo-33238(276): Add ‘InvalidStateError’ to *note
     concurrent.futures: 22.  ‘Future.set_result’ and
     ‘Future.set_exception’ now raise ‘InvalidStateError’ if the futures
     are not pending or running.  Patch by Jason Haydaman.

   - bpo-33618(277): Finalize and document preliminary and experimental
     TLS 1.3 support with OpenSSL 1.1.1

   - bpo-33625(278): Release GIL on *note grp.getgrnam: 103b, *note
     grp.getgrgid: 5e8, *note pwd.getpwnam: 103a. and *note
     pwd.getpwuid: 1027. if reentrant variants of these functions are
     available.  Patch by William Grzybowski.

   - bpo-33623(279): Fix possible SIGSGV when asyncio.Future is created
     in __del__

   - bpo-11874(280): Use a better regex when breaking usage into
     wrappable parts.  Avoids bogus assertion errors from custom metavar
     strings.

   - bpo-30877(281): Fixed a bug in the Python implementation of the
     JSON decoder that prevented the cache of parsed strings from
     clearing after finishing the decoding.  Based on patch by c-fos.

   - bpo-33604(282): Remove HMAC default to md5 marked for removal in
     3.8 (removal originally planned in 3.6, bump to 3.8 in gh-7062).

   - bpo-33582(283): Emit a deprecation warning for
     inspect.formatargspec

   - bpo-21145(284): Add ‘functools.cached_property’ decorator, for
     computed properties cached for the life of the instance.

   - bpo-33570(285): Change TLS 1.3 cipher suite settings for
     compatibility with OpenSSL 1.1.1-pre6 and newer.  OpenSSL 1.1.1
     will have TLS 1.3 ciphers enabled by default.

   - bpo-28556(286): Do not simplify arguments to *note typing.Union:
     1044.  Now ‘Union[Manager, Employee]’ is not simplified to
     ‘Employee’ at runtime.  Such simplification previously caused
     several bugs and limited possibilities for introspection.

   - bpo-12486(287): *note tokenize.generate_tokens(): 1045. is now
     documented as a public API to tokenize unicode strings.  It was
     previously present but undocumented.

   - bpo-33540(288): Add a new ‘block_on_close’ class attribute to
     ‘ForkingMixIn’ and ‘ThreadingMixIn’ classes of *note socketserver:
     f1.

   - bpo-33548(289): tempfile._candidate_tempdir_list should consider
     common TEMP locations

   - bpo-33109(290): argparse subparsers are once again not required by
     default, reverting the change in behavior introduced by
     bpo-26510(291) in 3.7.0a2.

   - bpo-33541(292): Remove unused private method
     ‘_strptime.LocaleTime.__pad’ (a.k.a.  ‘_LocaleTime__pad’).

   - bpo-33536(293): dataclasses.make_dataclass now checks for invalid
     field names and duplicate fields.  Also, added a check for invalid
     field specifications.

   - bpo-33542(294): Prevent ‘uuid.get_node’ from using a DUID instead
     of a MAC on Windows.  Patch by Zvi Effron

   - bpo-26819(295): Fix race condition with
     ‘ReadTransport.resume_reading’ in Windows proactor event loop.

   - Fix failure in *note typing.get_type_hints(): 313. when ClassVar
     was provided as a string forward reference.

   - bpo-33516(296): *note unittest.mock.MagicMock: 78e. now supports
     the ‘__round__’ magic method.

   - bpo-28612(297): Added support for Site Maps to urllib’s
     ‘RobotFileParser’ as *note RobotFileParser.site_maps(): 1046.
     Patch by Lady Red, based on patch by Peter Wirtz.

   - bpo-28167(298): Remove platform.linux_distribution, which was
     deprecated since 3.5.

   - bpo-33504(299): Switch the default dictionary implementation for
     *note configparser: 23. from *note collections.OrderedDict: 1ba. to
     the standard *note dict: 1b9. type.

   - bpo-33505(300): Optimize asyncio.ensure_future() by reordering if
     checks: 1.17x faster.

   - bpo-33497(301): Add errors param to cgi.parse_multipart and make an
     encoding in FieldStorage use the given errors (needed for Twisted).
     Patch by Amber Brown.

   - bpo-29235(302): The ‘cProfile.Profile’ class can now be used as a
     context manager.  Patch by Scott Sanderson.

   - bpo-33495(303): Change dataclasses.Fields repr to use the repr of
     each of its members, instead of str.  This makes it more clear what
     each field actually represents.  This is especially true for the
     ’type’ member.

   - bpo-26103(304): Correct ‘inspect.isdatadescriptor’ to look for
     ‘__set__’ or ‘__delete__’.  Patch by Aaron Hall.

   - bpo-29209(305): Removed the ‘doctype()’ method and the `html'
     parameter of the constructor of *note XMLParser: 253.  The
     ‘doctype()’ method defined in a subclass will no longer be called.
     Deprecated methods ‘getchildren()’ and ‘getiterator()’ in the *note
     ElementTree: 138. module emit now a *note DeprecationWarning: 279.
     instead of *note PendingDeprecationWarning: 27a.

   - bpo-33453(306): Fix dataclasses to work if using literal string
     type annotations or if using PEP 563 "Postponed Evaluation of
     Annotations".  Only specific string prefixes are detected for both
     ClassVar ("ClassVar" and "typing.ClassVar") and InitVar ("InitVar"
     and "dataclasses.InitVar").

   - bpo-28556(307): Minor fixes in typing module: add annotations to
     ‘NamedTuple.__new__’, pass ‘*args’ and ‘**kwds’ in
     ‘Generic.__new__’.  Original PRs by Paulius Šarka and Chad
     Dombrova.

   - bpo-33365(308): Print the header values besides the header keys
     instead just the header keys if `debuglevel' is set to >0 in *note
     http.client: 94.  Patch by Marco Strigl.

   - bpo-20087(309): Updated alias mapping with glibc 2.27 supported
     locales.

   - bpo-33422(310): Fix trailing quotation marks getting deleted when
     looking up byte/string literals on pydoc.  Patch by Andrés Delfino.

   - bpo-28167(311): The function ‘platform.linux_distribution’ and
     ‘platform.dist’ now trigger a ‘DeprecationWarning’ and have been
     marked for removal in Python 3.8

   - bpo-33281(312): Fix ctypes.util.find_library regression on macOS.

   - bpo-33311(313): Text and html output generated by cgitb does not
     display parentheses if the current call is done directly in the
     module.  Patch by Stéphane Blondon.

   - bpo-27300(314): The file classes in `tempfile' now accept an
     `errors' parameter that complements the already existing
     `encoding'.  Patch by Stephan Hohe.

   - bpo-32933(315): *note unittest.mock.mock_open(): fd7. now supports
     iteration over the file contents.  Patch by Tony Flury.

   - bpo-33217(316): Raise *note TypeError: 193. when looking up
     non-Enum objects in Enum classes and Enum members.

   - bpo-33197(317): Update error message when constructing invalid
     inspect.Parameters Patch by Dong-hee Na.

   - bpo-33383(318): Fixed crash in the get() method of the *note
     dbm.ndbm: 35. database object when it is called with a single
     argument.

   - bpo-33375(319): The warnings module now finds the Python file
     associated with a warning from the code object, rather than the
     frame’s global namespace.  This is consistent with how tracebacks
     and pdb find filenames, and should work better for dynamically
     executed code.

   - bpo-33336(320): ‘imaplib’ now allows ‘MOVE’ command in
     ‘IMAP4.uid()’ (RFC 6851: IMAP MOVE Extension) and potentially as a
     name of supported method of ‘IMAP4’ object.

   - bpo-32455(321): Added `jump' parameter to *note dis.stack_effect():
     843.

   - bpo-27485(322): Rename and deprecate undocumented functions in
     *note urllib.parse(): 120.

   - bpo-33332(323): Add ‘signal.valid_signals()’ to expose the POSIX
     sigfillset() functionality.

   - bpo-33251(324): ‘ConfigParser.items()’ was fixed so that key-value
     pairs passed in via *note vars: 1047. are not included in the
     resulting output.

   - bpo-33329(325): Fix multiprocessing regression on newer glibcs

   - bpo-33334(326): *note dis.stack_effect(): 843. now supports all
     defined opcodes including NOP and EXTENDED_ARG.

   - bpo-991266(327): Fix quoting of the ‘Comment’ attribute of *note
     http.cookies.SimpleCookie: 1048.

   - bpo-33131(328): Upgrade bundled version of pip to 10.0.1.

   - bpo-33308(329): Fixed a crash in the *note parser: c8. module when
     converting an ST object to a tree of tuples or lists with
     ‘line_info=False’ and ‘col_info=True’.

   - bpo-23403(330): lib2to3 now uses pickle protocol 4 for pre-computed
     grammars.

   - bpo-33266(331): lib2to3 now recognizes ‘rf'...'’ strings.

   - bpo-11594(332): Ensure line-endings are respected when using
     lib2to3.

   - bpo-33254(333): Have *note importlib.resources.contents(): 1049.
     and *note importlib.abc.ResourceReader.contents(): 104a. return an
     *note iterable: bb4. instead of an *note iterator: 104b.

   - bpo-33265(334): ‘contextlib.ExitStack’ and
     ‘contextlib.AsyncExitStack’ now use a method instead of a wrapper
     function for exit callbacks.

   - bpo-33263(335): Fix FD leak in ‘_SelectorSocketTransport’ Patch by
     Vlad Starostin.

   - bpo-33256(336): Fix display of ‘<module>’ call in the html produced
     by ‘cgitb.html()’.  Patch by Stéphane Blondon.

   - bpo-33144(337): ‘random.Random()’ and its subclassing mechanism got
     optimized to check only once at class/subclass instantiation time
     whether its ‘getrandbits()’ method can be relied on by other
     methods, including ‘randrange()’, for the generation of arbitrarily
     large random integers.  Patch by Wolfgang Maier.

   - bpo-33185(338): Fixed regression when running pydoc with the *note
     -m: 340. switch.  (The regression was introduced in 3.7.0b3 by the
     resolution of bpo-33053(339))

     This fix also changed pydoc to add ‘os.getcwd()’ to *note sys.path:
     490. when necessary, rather than adding ‘"."’.

   - bpo-29613(340): Added support for the ‘SameSite’ cookie flag to the
     ‘http.cookies’ module.

   - bpo-33169(341): Delete entries of ‘None’ in *note
     sys.path_importer_cache: 4a5. when
     ‘importlib.machinery.invalidate_caches()’ is called.

   - bpo-33203(342): ‘random.Random.choice()’ now raises ‘IndexError’
     for empty sequences consistently even when called from subclasses
     without a ‘getrandbits()’ implementation.

   - bpo-33224(343): Update difflib.mdiff() for PEP 479(344).  Convert
     an uncaught StopIteration in a generator into a return-statement.

   - bpo-33209(345): End framing at the end of C implementation of *note
     pickle.Pickler.dump(): 104c.

   - bpo-32861(346): The urllib.robotparser’s ‘__str__’ representation
     now includes wildcard entries and the "Crawl-delay" and
     "Request-rate" fields.  Also removes extra newlines that were being
     appended to the end of the string.  Patch by Michael Lazar.

   - bpo-23403(347): ‘DEFAULT_PROTOCOL’ in *note pickle: cb. was bumped
     to 4.  Protocol 4 is described in PEP 3154(348) and available since
     Python 3.4.  It offers better performance and smaller size compared
     to protocol 3 introduced in Python 3.0.

   - bpo-20104(349): Improved error handling and fixed a reference leak
     in *note os.posix_spawn(): 258.

   - bpo-33106(350): Deleting a key from a read-only dbm database raises
     module specific error instead of KeyError.

   - bpo-33175(351): In dataclasses, Field.__set_name__ now looks up the
     __set_name__ special method on the class, not the instance, of the
     default value.

   - bpo-32380(352): Create functools.singledispatchmethod to support
     generic single dispatch on descriptors and methods.

   - bpo-33141(353): Have Field objects pass through __set_name__ to
     their default values, if they have their own __set_name__.

   - bpo-33096(354): Allow ttk.Treeview.insert to insert iid that has a
     false boolean value.  Note iid=0 and iid=False would be same.
     Patch by Garvit Khatri.

   - bpo-32873(355): Treat type variables and special typing forms as
     immutable by copy and pickle.  This fixes several minor issues and
     inconsistencies, and improves backwards compatibility with Python
     3.6.

   - bpo-33134(356): When computing dataclass’s __hash__, use the lookup
     table to contain the function which returns the __hash__ value.
     This is an improvement over looking up a string, and then testing
     that string to see what to do.

   - bpo-33127(357): ssl模块现在使用LibreSSL 2.7.1编译。

   - bpo-32505(358): 如果数据类的成员变量的类型为Field，但没有类型注解，
     则引发TypeError。

   - bpo-33078(359): 修复在OSX平台因为依赖sem_getvalue而导致的失败。

   - bpo-33116(360): 将’Field’添加到dataclasses.__all__。

   - bpo-32896(361): Fix an error where subclassing a dataclass with a
     field that uses a default_factory would generate an incorrect
     class.

   - bpo-33100(362): Dataclasses: If a field has a default value that’s
     a MemberDescriptorType, then it’s from that field being in
     __slots__, not an actual default value.

   - bpo-32953(363): If a non-dataclass inherits from a frozen
     dataclass, allow attributes to be added to the derived class.  Only
     attributes from the frozen dataclass cannot be assigned to.
     Require all dataclasses in a hierarchy to be either all frozen or
     all non-frozen.

   - bpo-33097(364): Raise RuntimeError when ‘executor.submit’ is called
     during interpreter shutdown.

   - bpo-32968(365): Modulo and floor division involving Fraction and
     float should return float.

   - bpo-33061(366): 添加丢失的 ‘NoReturn’ 到typing.py的 ‘__all__’

   - bpo-33078(367): Fix the size handling in multiprocessing.Queue when
     a pickling error occurs.

   - bpo-33064(368): lib2to3 now properly supports trailing commas after
     ‘*args’ and ‘**kwargs’ in function signatures.

   - bpo-33056(369): FIX properly close leaking fds in
     concurrent.futures.ProcessPoolExecutor.

   - bpo-33021(370): Release the GIL during fstat() calls, avoiding hang
     of all threads when calling mmap.mmap(), os.urandom(), and
     random.seed().  Patch by Nir Soffer.

   - bpo-31804(371): Avoid failing in multiprocessing.Process if the
     standard streams are closed or None at exit.

   - bpo-33034(372): Providing an explicit error message when casting
     the port property to anything that is not an integer value using
     ‘urlparse()’ and ‘urlsplit()’.  Patch by Matt Eaton.

   - bpo-30249(373): Improve struct.unpack_from() exception messages for
     problems with the buffer size and offset.

   - bpo-33037(374): Skip sending/receiving data after SSL transport
     closing.

   - bpo-27683(375): Fix a regression in *note ipaddress: a3. that
     result of ‘hosts()’ is empty when the network is constructed by a
     tuple containing an integer mask and only 1 bit left for addresses.

   - bpo-22674(376): Add the strsignal() function in the signal module
     that returns the system description of the given signal, as
     returned by strsignal(3).

   - bpo-32999(377): Fix C implementation of ‘ABC.__subclasscheck__(cls,
     subclass)’ crashed when ‘subclass’ is not a type object.

   - bpo-33009(378): Fix inspect.signature() for single-parameter
     partialmethods.

   - bpo-32969(379): Expose several missing constants in zlib and fix
     corresponding documentation.

   - bpo-32056(380): Improved exceptions raised for invalid number of
     channels and sample width when read an audio file in modules *note
     aifc: 5, *note wave: 128. and *note sunau: fb.

   - bpo-32970(381): Improved disassembly of the MAKE_FUNCTION
     instruction.

   - bpo-32844(382): Fix wrong redirection of a low descriptor (0 or 1)
     to stderr in subprocess if another low descriptor is closed.

   - bpo-32960(383): For dataclasses, disallow inheriting frozen from
     non-frozen classes, and also disallow inheriting non-frozen from
     frozen classes.  This restriction will be relaxed at a future date.

   - bpo-32713(384): Fixed tarfile.itn handling of out-of-bounds float
     values.  Patch by Joffrey Fuhrer.

   - bpo-32257(385): The ssl module now contains OP_NO_RENEGOTIATION
     constant, available with OpenSSL 1.1.0h or 1.1.1.

   - bpo-32951(386): Direct instantiation of SSLSocket and SSLObject
     objects is now prohibited.  The constructors were never documented,
     tested, or designed as public constructors.  Users were suppose to
     use ssl.wrap_socket() or SSLContext.

   - bpo-32929(387): Remove the tri-state parameter "hash", and add the
     boolean "unsafe_hash".  If unsafe_hash is True, add a __hash__
     function, but if a __hash__ exists, raise TypeError.  If
     unsafe_hash is False, add a __hash__ based on the values of eq= and
     frozen=.  The unsafe_hash=False behavior is the same as the old
     hash=None behavior.  unsafe_hash=False is the default, just as
     hash=None used to be.

   - bpo-32947(388): Add OP_ENABLE_MIDDLEBOX_COMPAT and test workaround
     for TLSv1.3 for future compatibility with OpenSSL 1.1.1.

   - bpo-32146(389): Document the interaction between frozen executables
     and the spawn and forkserver start methods in multiprocessing.

   - bpo-30622(390): The ssl module now detects missing NPN support in
     LibreSSL.

   - bpo-32922(391): dbm.open() now encodes filename with the filesystem
     encoding rather than default encoding.

   - bpo-32759(392): Free unused arenas in multiprocessing.heap.

   - bpo-32859(393): In ‘os.dup2’, don’t check every call whether the
     ‘dup3’ syscall exists or not.

   - bpo-32556(394): nt._getfinalpathname, nt._getvolumepathname and
     nt._getdiskusage now correctly convert from bytes.

   - bpo-21060(395): Rewrite confusing message from setup.py upload from
     "No dist file created in earlier command" to the more helpful "Must
     create and upload files in one command".

   - bpo-32857(396): In *note tkinter: 10d, ‘after_cancel(None)’ now
     raises a *note ValueError: 1fc. instead of canceling the first
     scheduled function.  Patch by Cheryl Sabella.

   - bpo-32852(397): Make sure sys.argv remains as a list when running
     trace.

   - bpo-31333(398): ‘_abc’ module is added.  It is a speedup module
     with C implementations for various functions and methods in ‘abc’.
     Creating an ABC subclass and calling ‘isinstance’ or ‘issubclass’
     with an ABC subclass are up to 1.5x faster.  In addition, this
     makes Python start-up up to 10% faster.

     Note that the new implementation hides internal registry and
     caches, previously accessible via private attributes
     ‘_abc_registry’, ‘_abc_cache’, and ‘_abc_negative_cache’.  There
     are three debugging helper methods that can be used instead
     ‘_dump_registry’, ‘_abc_registry_clear’, and ‘_abc_caches_clear’.

   - bpo-32841(399): Fixed *note asyncio.Condition: 28e. issue which
     silently ignored cancellation after notifying and cancelling a
     conditional lock.  Patch by Bar Harel.

   - bpo-32819(400): ssl.match_hostname() has been simplified and no
     longer depends on re and ipaddress module for wildcard and IP
     addresses.  Error reporting for invalid wildcards has been
     improved.

   - bpo-19675(401): ‘multiprocessing.Pool’ no longer leaks processes if
     its initialization fails.

   - bpo-32394(402): socket: Remove
     TCP_FASTOPEN,TCP_KEEPCNT,TCP_KEEPIDLE,TCP_KEEPINTVL flags on older
     version Windows during run-time.

   - bpo-31787(403): Fixed refleaks of ‘__init__()’ methods in various
     modules.  (Contributed by Oren Milman)

   - bpo-30157(404): Fixed guessing quote and delimiter in
     csv.Sniffer.sniff() when only the last field is quoted.  Patch by
     Jake Davis.

   - bpo-30688(405): Added support of ‘\N{name}’ escapes in regular
     expressions.  Based on patch by Jonathan Eunice.

   - bpo-32792(406): collections.ChainMap() preserves the order of the
     underlying mappings.

   - bpo-32775(407): *note fnmatch.translate(): 104d. no longer produces
     patterns which contain set operations.  Sets starting with ’[’ or
     containing ’–’, ’&&’, ’~~’ or ’||’ will be interpreted differently
     in regular expressions in future versions.  Currently they emit
     warnings.  fnmatch.translate() now avoids producing patterns
     containing such sets by accident.

   - bpo-32622(408): Implement native fast sendfile for Windows proactor
     event loop.

   - bpo-32777(409): Fix a rare but potential pre-exec child process
     deadlock in subprocess on POSIX systems when marking file
     descriptors inheritable on exec in the child process.  This bug
     appears to have been introduced in 3.4.

   - bpo-32647(410): The ctypes module used to depend on indirect
     linking for dlopen.  The shared extension is now explicitly linked
     against libdl on platforms with dl.

   - bpo-32749(411): A *note dbm.dumb: 33. database opened with flags
     ’r’ is now read-only.  *note dbm.dumb.open(): 2c0. with flags ’r’
     and ’w’ no longer creates a database if it does not exist.

   - bpo-32741(412): Implement ‘asyncio.TimerHandle.when()’ method.

   - bpo-32691(413): Use mod_spec.parent when running modules with pdb

   - bpo-32734(414): Fixed ‘asyncio.Lock()’ safety issue which allowed
     acquiring and locking the same lock multiple times, without it
     being free.  Patch by Bar Harel.

   - bpo-32727(415): Do not include name field in SMTP envelope from
     address.  Patch by Stéphane Wirtel

   - bpo-31453(416): Add TLSVersion constants and
     SSLContext.maximum_version / minimum_version attributes.  The new
     API wraps OpenSSL 1.1
     ‘https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_min_proto_version.html’
     feature.

   - bpo-24334(417): Internal implementation details of ssl module were
     cleaned up.  The SSLSocket has one less layer of indirection.
     Owner and session information are now handled by the SSLSocket and
     SSLObject constructor.  Channel binding implementation has been
     simplified.

   - bpo-31848(418): Fix the error handling in Aifc_read.initfp() when
     the SSND chunk is not found.  Patch by Zackery Spytz.

   - bpo-32585(419): Add Ttk spinbox widget to *note tkinter.ttk: 110.
     Patch by Alan D Moore.

   - bpo-32512(420): *note profile: d4. CLI accepts ‘-m module_name’ as
     an alternative to script path.

   - bpo-8525(421): help() on a type now displays builtin subclasses.
     This is intended primarily to help with notification of more
     specific exception subclasses.

     Patch by Sanyam Khurana.

   - bpo-31639(422): http.server now exposes a ThreadingHTTPServer class
     and uses it when the module is run with ‘-m’ to cope with web
     browsers pre-opening sockets.

   - bpo-29877(423): compileall: import ProcessPoolExecutor only when
     needed, preventing hangs on low resource platforms

   - bpo-32221(424): Various functions returning tuple containing IPv6
     addresses now omit ‘%scope’ part since the same information is
     already encoded in `scopeid' tuple item.  Especially this speeds up
     ‘socket.recvfrom()’ when it receives multicast packet since useless
     resolving of network interface name is omitted.

   - bpo-32147(425): *note binascii.unhexlify(): 104e. is now up to 2
     times faster.  Patch by Sergey Fedoseev.

   - bpo-30693(426): The TarFile class now recurses directories in a
     reproducible way.

   - bpo-30693(427): The ZipFile class now recurses directories in a
     reproducible way.

   - bpo-31680(428): Added *note curses.ncurses_version: 1c0.

   - bpo-31908(429): Fix output of cover files for ‘trace’ module
     command-line tool.  Previously emitted cover files only when
     ‘--missing’ option was used.  Patch by Michael Selik.

   - bpo-31608(430): Raise a ‘TypeError’ instead of crashing if a
     ‘collections.deque’ subclass returns a non-deque from ‘__new__’.
     Patch by Oren Milman.

   - bpo-31425(431): Add support for sockets of the AF_QIPCRTR address
     family, supported by the Linux kernel.  This is used to communicate
     with services, such as GPS or radio, running on Qualcomm devices.
     Patch by Bjorn Andersson.

   - bpo-22005(432): Implemented unpickling instances of *note datetime:
     195, *note date: 194. and *note time: 4fb. pickled by Python 2.
     ‘encoding='latin1'’ should be used for successful decoding.

   - bpo-27645(433): *note sqlite3.Connection: 3e0. now exposes a *note
     backup: 3e1. method, if the underlying SQLite library is at version
     3.6.11 or higher.  Patch by Lele Gaifax.

   - bpo-16865(434): Support arrays >=2GiB in *note ctypes: 2b.  Patch
     by Segev Finer.

   - bpo-31508(435): Removed support of arguments in *note
     tkinter.ttk.Treeview.selection: 2be.  It was deprecated in 3.6.
     Use specialized methods like ‘selection_set’ for changing the
     selection.

   - bpo-29456(436): Fix bugs in hangul normalization: u1176, u11a7 and
     u11c3

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35845

   (2) https://bugs.python.org/issue35864

   (3) https://bugs.python.org/issue35537

   (4) https://bugs.python.org/issue35847

   (5) https://bugs.python.org/issue35813

   (6) https://bugs.python.org/issue35780

   (7) https://bugs.python.org/issue35537

   (8) https://bugs.python.org/issue23846

   (9) https://bugs.python.org/issue34323

   (10) https://bugs.python.org/issue35674

   (11) https://bugs.python.org/issue35733

   (12) https://bugs.python.org/issue35726

   (13) https://bugs.python.org/issue35719

   (14) https://bugs.python.org/issue35717

   (15) https://bugs.python.org/issue35699

   (16) https://bugs.python.org/issue32710

   (17) https://bugs.python.org/issue35702

   (18) https://bugs.python.org/issue32710

   (19) https://bugs.python.org/issue35682

   (20) https://bugs.python.org/issue35283

   (21) https://bugs.python.org/issue35664

   (22) https://bugs.python.org/issue35643

   (23) https://bugs.python.org/issue35619

   (24) https://bugs.python.org/issue28503

   (25) https://bugs.python.org/issue35614

   (26) https://bugs.python.org/issue35568

   (27) https://bugs.python.org/issue35588

   (28) https://bugs.python.org/issue35585

   (29) https://bugs.python.org/issue30561

   (30) https://bugs.python.org/issue35537

   (31) https://bugs.python.org/issue35526

   (32) https://bugs.python.org/issue35523

   (33) https://bugs.python.org/issue31784

   (34) https://bugs.python.org/issue35513

   (35) https://bugs.python.org/issue35502

   (36) https://bugs.python.org/issue35348

   (37) https://bugs.python.org/issue35491

   (38) https://bugs.python.org/issue35477

   (39) https://bugs.python.org/issue31446

   (40) https://bugs.python.org/issue35471

   (41) https://bugs.python.org/issue23057

   (42) https://bugs.python.org/issue35052

   (43) https://bugs.python.org/issue20239

   (44) https://bugs.python.org/issue17185

   (45) https://bugs.python.org/issue35445

   (46) https://bugs.python.org/issue35415

   (47) https://bugs.python.org/issue35424

   (48) https://bugs.python.org/issue35330

   (49) https://bugs.python.org/issue35346

   (50) https://bugs.python.org/issue10496

   (51) https://bugs.python.org/issue10496

   (52) https://bugs.python.org/issue35389

   (53) https://bugs.python.org/issue35394

   (54) https://bugs.python.org/issue35310

   (55) https://bugs.python.org/issue35380

   (56) https://bugs.python.org/issue35341

   (57) https://bugs.python.org/issue35371

   (58) https://bugs.python.org/issue35346

   (59) https://bugs.python.org/issue35066

   (60) https://bugs.python.org/issue35345

   (61) https://bugs.python.org/issue35344

   (62) https://bugs.python.org/issue35312

   (63) https://bugs.python.org/issue35308

   (64) https://bugs.python.org/issue24746

   (65) https://bugs.python.org/issue28604

   (66) https://bugs.python.org/issue35277

   (67) https://bugs.python.org/issue24209

   (68) https://bugs.python.org/issue35226

   (69) https://bugs.python.org/issue29564

   (70) https://bugs.python.org/issue35189

   (71) https://bugs.python.org/issue30064

   (72) https://bugs.python.org/issue35186

   (73) https://bugs.python.org/issue35152

   (74) https://bugs.python.org/issue35062

   (75) https://bugs.python.org/issue35065

   (76) https://bugs.python.org/issue34160

   (77) https://bugs.python.org/issue35079

   (78) https://bugs.python.org/issue33710

   (79) https://bugs.python.org/issue35017

   (80) https://bugs.python.org/issue35024

   (81) https://bugs.python.org/issue35047

   (82) https://bugs.python.org/issue31047

   (83) https://bugs.python.org/issue35053

   (84) https://bugs.python.org/issue31553

   (85) https://bugs.python.org/issue34794

   (86) https://bugs.python.org/issue34909

   (87) https://bugs.python.org/issue35022

   (88) https://bugs.python.org/issue35008

   (89) https://bugs.python.org/issue23420

   (90) https://bugs.python.org/issue33947

   (91) https://bugs.python.org/issue34890

   (92) https://bugs.python.org/issue34521

   (93) https://tools.ietf.org/html/rfc3542.html

   (94) https://bugs.python.org/issue31522

   (95) https://bugs.python.org/issue34970

   (96) https://bugs.python.org/issue34969

   (97) https://bugs.python.org/issue16965

   (98) https://bugs.python.org/issue34966

   (99) https://bugs.python.org/issue34926

   (100) https://bugs.python.org/issue23831

   (101) https://bugs.python.org/issue34941

   (102) https://bugs.python.org/issue32680

   (103) https://bugs.python.org/issue34769

   (104) https://bugs.python.org/issue34936

   (105) https://bugs.python.org/issue34829

   (106) https://bugs.python.org/issue34911

   (107) https://bugs.python.org/issue34922

   (108) https://bugs.python.org/issue34925

   (109) https://bugs.python.org/issue34900

   (110) https://bugs.python.org/issue34844

   (111) https://bugs.python.org/issue34897

   (112) https://bugs.python.org/issue34871

   (113) https://bugs.python.org/issue34898

   (114) https://bugs.python.org/issue28441

   (115) https://bugs.python.org/issue34866

   (116) https://bugs.python.org/issue34711

   (117) https://bugs.python.org/issue34872

   (118) https://bugs.python.org/issue34849

   (119) https://bugs.python.org/issue34022

   (120) https://bugs.python.org/issue34819

   (121) https://bugs.python.org/issue34758

   (122) https://bugs.python.org/issue34789

   (123) https://bugs.python.org/issue34334

   (124) https://bugs.python.org/issue34687

   (125) https://bugs.python.org/issue5950

   (126) https://bugs.python.org/issue32892

   (127) https://bugs.python.org/issue34728

   (128) https://bugs.python.org/issue34738

   (129) https://bugs.python.org/issue34659

   (130) https://bugs.python.org/issue29577

   (131) https://bugs.python.org/issue34670

   (132) https://bugs.python.org/issue32718

   (133) https://bugs.python.org/issue31177

   (134) https://bugs.python.org/issue34672

   (135) https://bugs.python.org/issue34666

   (136) https://bugs.python.org/issue6721

   (137) https://bugs.python.org/issue34658

   (138) https://bugs.python.org/issue34652

   (139) https://bugs.python.org/issue34638

   (140) https://bugs.python.org/issue34536

   (141) https://bugs.python.org/issue34636

   (142) https://bugs.python.org/issue24412

   (143) https://bugs.python.org/issue34630

   (144) https://bugs.python.org/issue32490

   (145) https://bugs.python.org/issue34363

   (146) https://bugs.python.org/issue34625

   (147) https://bugs.python.org/issue32270

   (148) https://bugs.python.org/issue34622

   (149) https://bugs.python.org/issue34610

   (150) https://bugs.python.org/issue34421

   (151) https://bugs.python.org/issue34604

   (152) https://bugs.python.org/issue30977

   (153) https://bugs.python.org/issue34574

   (154) https://bugs.python.org/issue8110

   (155) https://bugs.python.org/issue34530

   (156) https://bugs.python.org/issue34563

   (157) https://bugs.python.org/issue34558

   (158) https://bugs.python.org/issue34282

   (159) https://bugs.python.org/issue22872

   (160) https://bugs.python.org/issue34515

   (161) https://bugs.python.org/issue13312

   (162) https://bugs.python.org/issue34472

   (163) https://bugs.python.org/issue34454

   (164) https://bugs.python.org/issue6700

   (165) https://bugs.python.org/issue34171

   (166) https://bugs.python.org/issue34441

   (167) https://bugs.python.org/issue34427

   (168) https://bugs.python.org/issue34412

   (169) https://bugs.python.org/issue20849

   (170) https://bugs.python.org/issue31715

   (171) https://bugs.python.org/issue34384

   (172) https://bugs.python.org/issue22602

   (173) https://bugs.python.org/issue2122

   (174) https://bugs.python.org/issue34341

   (175) https://bugs.python.org/issue34333

   (176) https://bugs.python.org/issue18540

   (177) https://bugs.python.org/issue26502

   (178) https://bugs.python.org/issue34318

   (179) https://bugs.python.org/issue9372

   (180) https://bugs.python.org/issue33613

   (181) https://bugs.python.org/issue34248

   (182) https://bugs.python.org/issue33089

   (183) https://bugs.python.org/issue34246

   (184) https://bugs.python.org/issue31047

   (185) https://bugs.python.org/issue32321

   (186) https://bugs.python.org/issue34270

   (187) https://bugs.python.org/issue34263

   (188) https://bugs.python.org/issue34035

   (189) https://bugs.python.org/issue32215

   (190) https://bugs.python.org/issue34075

   (191) https://bugs.python.org/issue34251

   (192) https://bugs.python.org/issue19891

   (193) https://bugs.python.org/issue33089

   (194) https://bugs.python.org/issue34228

   (195) https://bugs.python.org/issue13041

   (196) https://bugs.python.org/issue34213

   (197) https://bugs.python.org/issue34052

   (198) https://bugs.python.org/issue34197

   (199) https://bugs.python.org/issue32788

   (200) https://bugs.python.org/issue21446

   (201) https://bugs.python.org/issue940286

   (202) https://bugs.python.org/issue34164

   (203) https://bugs.python.org/issue33729

   (204) https://bugs.python.org/issue34097

   (205) https://bugs.python.org/issue34108

   (206) https://bugs.python.org/issue34070

   (207) https://bugs.python.org/issue27494

   (208) https://bugs.python.org/issue27494

   (209) https://bugs.python.org/issue33967

   (210) https://bugs.python.org/issue34041

   (211) https://bugs.python.org/issue34056

   (212) https://www.python.org/dev/peps/pep-0552

   (213) https://bugs.python.org/issue34054

   (214) https://bugs.python.org/issue34043

   (215) https://bugs.python.org/issue34044

   (216) https://bugs.python.org/issue34010

   (217) https://bugs.python.org/issue34019

   (218) https://bugs.python.org/issue34003

   (219) https://bugs.python.org/issue33978

   (220) https://bugs.python.org/issue14117

   (221) https://bugs.python.org/issue33974

   (222) https://bugs.python.org/issue27500

   (223) https://bugs.python.org/issue24567

   (224) https://bugs.python.org/issue33871

   (225) https://bugs.python.org/issue25007

   (226) https://bugs.python.org/issue33929

   (227) https://bugs.python.org/issue33899

   (228) https://bugs.python.org/issue33897

   (229) https://bugs.python.org/issue33695

   (230) https://bugs.python.org/issue33695

   (231) https://bugs.python.org/issue33916

   (232) https://bugs.python.org/issue32568

   (233) https://bugs.python.org/issue33833

   (234) https://bugs.python.org/issue33663

   (235) https://bugs.python.org/issue33721

   (236) https://bugs.python.org/issue26544

   (237) https://bugs.python.org/issue33843

   (238) https://bugs.python.org/issue33842

   (239) https://bugs.python.org/issue30167

   (240) https://bugs.python.org/issue33805

   (241) https://bugs.python.org/issue33687

   (242) https://bugs.python.org/issue33812

   (243) https://bugs.python.org/issue32108

   (244) https://bugs.python.org/issue27397

   (245) https://bugs.python.org/issue33578

   (246) https://bugs.python.org/issue30805

   (247) https://bugs.python.org/issue33476

   (248) https://bugs.python.org/issue33694

   (249) https://bugs.python.org/issue32493

   (250) https://bugs.python.org/issue33792

   (251) https://bugs.python.org/issue33274

   (252) https://bugs.python.org/issue33778

   (253) https://bugs.python.org/issue33165

   (254) https://bugs.python.org/issue33770

   (255) https://bugs.python.org/issue33769

   (256) https://bugs.python.org/issue33767

   (257) https://bugs.python.org/issue33734

   (258) https://bugs.python.org/issue31014

   (259) https://bugs.python.org/issue2504

   (260) https://bugs.python.org/issue33197

   (261) https://bugs.python.org/issue32751

   (262) https://bugs.python.org/issue32684

   (263) https://bugs.python.org/issue33654

   (264) https://bugs.python.org/issue33674

   (265) https://bugs.python.org/issue33671

   (266) https://bugs.python.org/issue25427

   (267) https://bugs.python.org/issue33674

   (268) https://bugs.python.org/issue31647

   (269) https://bugs.python.org/issue32610

   (270) https://bugs.python.org/issue32410

   (271) https://bugs.python.org/issue33469

   (272) https://bugs.python.org/issue33672

   (273) https://bugs.python.org/issue33654

   (274) https://bugs.python.org/issue33652

   (275) https://bugs.python.org/issue32493

   (276) https://bugs.python.org/issue33238

   (277) https://bugs.python.org/issue33618

   (278) https://bugs.python.org/issue33625

   (279) https://bugs.python.org/issue33623

   (280) https://bugs.python.org/issue11874

   (281) https://bugs.python.org/issue30877

   (282) https://bugs.python.org/issue33604

   (283) https://bugs.python.org/issue33582

   (284) https://bugs.python.org/issue21145

   (285) https://bugs.python.org/issue33570

   (286) https://bugs.python.org/issue28556

   (287) https://bugs.python.org/issue12486

   (288) https://bugs.python.org/issue33540

   (289) https://bugs.python.org/issue33548

   (290) https://bugs.python.org/issue33109

   (291) https://bugs.python.org/issue26510

   (292) https://bugs.python.org/issue33541

   (293) https://bugs.python.org/issue33536

   (294) https://bugs.python.org/issue33542

   (295) https://bugs.python.org/issue26819

   (296) https://bugs.python.org/issue33516

   (297) https://bugs.python.org/issue28612

   (298) https://bugs.python.org/issue28167

   (299) https://bugs.python.org/issue33504

   (300) https://bugs.python.org/issue33505

   (301) https://bugs.python.org/issue33497

   (302) https://bugs.python.org/issue29235

   (303) https://bugs.python.org/issue33495

   (304) https://bugs.python.org/issue26103

   (305) https://bugs.python.org/issue29209

   (306) https://bugs.python.org/issue33453

   (307) https://bugs.python.org/issue28556

   (308) https://bugs.python.org/issue33365

   (309) https://bugs.python.org/issue20087

   (310) https://bugs.python.org/issue33422

   (311) https://bugs.python.org/issue28167

   (312) https://bugs.python.org/issue33281

   (313) https://bugs.python.org/issue33311

   (314) https://bugs.python.org/issue27300

   (315) https://bugs.python.org/issue32933

   (316) https://bugs.python.org/issue33217

   (317) https://bugs.python.org/issue33197

   (318) https://bugs.python.org/issue33383

   (319) https://bugs.python.org/issue33375

   (320) https://bugs.python.org/issue33336

   (321) https://bugs.python.org/issue32455

   (322) https://bugs.python.org/issue27485

   (323) https://bugs.python.org/issue33332

   (324) https://bugs.python.org/issue33251

   (325) https://bugs.python.org/issue33329

   (326) https://bugs.python.org/issue33334

   (327) https://bugs.python.org/issue991266

   (328) https://bugs.python.org/issue33131

   (329) https://bugs.python.org/issue33308

   (330) https://bugs.python.org/issue23403

   (331) https://bugs.python.org/issue33266

   (332) https://bugs.python.org/issue11594

   (333) https://bugs.python.org/issue33254

   (334) https://bugs.python.org/issue33265

   (335) https://bugs.python.org/issue33263

   (336) https://bugs.python.org/issue33256

   (337) https://bugs.python.org/issue33144

   (338) https://bugs.python.org/issue33185

   (339) https://bugs.python.org/issue33053

   (340) https://bugs.python.org/issue29613

   (341) https://bugs.python.org/issue33169

   (342) https://bugs.python.org/issue33203

   (343) https://bugs.python.org/issue33224

   (344) https://www.python.org/dev/peps/pep-0479

   (345) https://bugs.python.org/issue33209

   (346) https://bugs.python.org/issue32861

   (347) https://bugs.python.org/issue23403

   (348) https://www.python.org/dev/peps/pep-3154

   (349) https://bugs.python.org/issue20104

   (350) https://bugs.python.org/issue33106

   (351) https://bugs.python.org/issue33175

   (352) https://bugs.python.org/issue32380

   (353) https://bugs.python.org/issue33141

   (354) https://bugs.python.org/issue33096

   (355) https://bugs.python.org/issue32873

   (356) https://bugs.python.org/issue33134

   (357) https://bugs.python.org/issue33127

   (358) https://bugs.python.org/issue32505

   (359) https://bugs.python.org/issue33078

   (360) https://bugs.python.org/issue33116

   (361) https://bugs.python.org/issue32896

   (362) https://bugs.python.org/issue33100

   (363) https://bugs.python.org/issue32953

   (364) https://bugs.python.org/issue33097

   (365) https://bugs.python.org/issue32968

   (366) https://bugs.python.org/issue33061

   (367) https://bugs.python.org/issue33078

   (368) https://bugs.python.org/issue33064

   (369) https://bugs.python.org/issue33056

   (370) https://bugs.python.org/issue33021

   (371) https://bugs.python.org/issue31804

   (372) https://bugs.python.org/issue33034

   (373) https://bugs.python.org/issue30249

   (374) https://bugs.python.org/issue33037

   (375) https://bugs.python.org/issue27683

   (376) https://bugs.python.org/issue22674

   (377) https://bugs.python.org/issue32999

   (378) https://bugs.python.org/issue33009

   (379) https://bugs.python.org/issue32969

   (380) https://bugs.python.org/issue32056

   (381) https://bugs.python.org/issue32970

   (382) https://bugs.python.org/issue32844

   (383) https://bugs.python.org/issue32960

   (384) https://bugs.python.org/issue32713

   (385) https://bugs.python.org/issue32257

   (386) https://bugs.python.org/issue32951

   (387) https://bugs.python.org/issue32929

   (388) https://bugs.python.org/issue32947

   (389) https://bugs.python.org/issue32146

   (390) https://bugs.python.org/issue30622

   (391) https://bugs.python.org/issue32922

   (392) https://bugs.python.org/issue32759

   (393) https://bugs.python.org/issue32859

   (394) https://bugs.python.org/issue32556

   (395) https://bugs.python.org/issue21060

   (396) https://bugs.python.org/issue32857

   (397) https://bugs.python.org/issue32852

   (398) https://bugs.python.org/issue31333

   (399) https://bugs.python.org/issue32841

   (400) https://bugs.python.org/issue32819

   (401) https://bugs.python.org/issue19675

   (402) https://bugs.python.org/issue32394

   (403) https://bugs.python.org/issue31787

   (404) https://bugs.python.org/issue30157

   (405) https://bugs.python.org/issue30688

   (406) https://bugs.python.org/issue32792

   (407) https://bugs.python.org/issue32775

   (408) https://bugs.python.org/issue32622

   (409) https://bugs.python.org/issue32777

   (410) https://bugs.python.org/issue32647

   (411) https://bugs.python.org/issue32749

   (412) https://bugs.python.org/issue32741

   (413) https://bugs.python.org/issue32691

   (414) https://bugs.python.org/issue32734

   (415) https://bugs.python.org/issue32727

   (416) https://bugs.python.org/issue31453

   (417) https://bugs.python.org/issue24334

   (418) https://bugs.python.org/issue31848

   (419) https://bugs.python.org/issue32585

   (420) https://bugs.python.org/issue32512

   (421) https://bugs.python.org/issue8525

   (422) https://bugs.python.org/issue31639

   (423) https://bugs.python.org/issue29877

   (424) https://bugs.python.org/issue32221

   (425) https://bugs.python.org/issue32147

   (426) https://bugs.python.org/issue30693

   (427) https://bugs.python.org/issue30693

   (428) https://bugs.python.org/issue31680

   (429) https://bugs.python.org/issue31908

   (430) https://bugs.python.org/issue31608

   (431) https://bugs.python.org/issue31425

   (432) https://bugs.python.org/issue22005

   (433) https://bugs.python.org/issue27645

   (434) https://bugs.python.org/issue16865

   (435) https://bugs.python.org/issue31508

   (436) https://bugs.python.org/issue29456


File: python.info,  Node: 文档<25>,  Next: 测试<20>,  Prev: 库<29>,  Up: Python 3 8 0 alpha 1

1.18.30.4 文档
..............

   - bpo-21257(1): Document *note http.client.parse_headers(): 1050.

   - bpo-34764(2): Improve example of iter() with 2nd sentinel argument.

   - bpo-35564(3): Explicitly set master_doc variable in conf.py for
     compliance with Sphinx 2.0

   - bpo-35511(4): Specified that profile.Profile class doesn’t not
     support enable or disable methods.  Also, elaborated that Profile
     object as a context manager is only supported in cProfile module.

   - bpo-10536(5): Enhance the gettext docs.  Patch by Éric Araujo

   - bpo-35089(6): Remove mention of ‘typing.io’ and ‘typing.re’.  Their
     types should be imported from ‘typing’ directly.

   - bpo-35038(7): Fix the documentation about an unexisting
     ‘f_restricted’ attribute in the frame object.  Patch by Stéphane
     Wirtel

   - bpo-35042(8): Replace PEP XYZ by the pep role and allow to use the
     direct links to the PEPs.

   - bpo-35044(9): Fix the documentation with the role ‘exc’ for the
     appropriated exception.  Patch by Stéphane Wirtel

   - bpo-35035(10): Rename documentation for *note email.utils: 76. to
     ‘email.utils.rst’.

   - bpo-34967(11): Use app.add_object_type() instead of the deprecated
     Sphinx function app.description_unit()

   - bpo-34913(12): Add documentation about the new command line
     interface of the gzip module.

   - bpo-32174(13): chm document displays non-ASCII charaters properly
     on some MBCS Windows systems.

   - bpo-11233(14): Create availability directive for documentation.
     Original patch by Georg Brandl.

   - bpo-34790(15): Document how passing coroutines to asyncio.wait()
     can be confusing.

   - bpo-34552(16): Make clear that ‘==’ operator sometimes is
     equivalent to ‘is’.  The ‘<’, ‘<=’, ‘>’ and ‘>=’ operators are only
     defined where they make sense.

   - bpo-28617(17): Fixed info in the stdtypes docs concerning the types
     that support membership tests.

   - bpo-20177(18): Migrate datetime.date.fromtimestamp to Argument
     Clinic.  Patch by Tim Hoffmann.

   - bpo-34065(19): Fix wrongly written basicConfig documentation markup
     syntax

   - bpo-33460(20): replaced ellipsis with correct error codes in
     tutorial chapter 3.

   - bpo-33847(21): Add ’@’ operator entry to index.

   - bpo-33409(22): Clarified the relationship between PEP 538(23)’s
     PYTHONCOERCECLOCALE and PEP 540’s PYTHONUTF8 mode.

   - bpo-33197(24): Add versionadded tag to the documentation of
     ParameterKind.description

   - bpo-17045(25): Improve the C-API doc for PyTypeObject.  This
     includes adding several quick-reference tables and a lot of missing
     slot/typedef entries.  The existing entries were also cleaned up
     with a slightly more consistent format.

   - bpo-33736(26): Improve the documentation of *note
     asyncio.open_connection(): 36c, *note asyncio.start_server(): 36d.
     and their UNIX socket counterparts.

   - bpo-23859(27): Document that *note asyncio.wait(): 28a. does not
     cancel its futures on timeout.

   - bpo-32436(28): Document PEP 567(29) changes to asyncio.

   - bpo-33604(30): 更新HMAC md5默认报告DeprecationWarning，并将在3.8移
     除。

   - bpo-33594(31): Document ‘getargspec’, ‘from_function’ and
     ‘from_builtin’ as deprecated in their respective docstring, and
     include version since deprecation in DeprecationWarning message.

   - bpo-33503(32): 修复错误的pypi链接

   - bpo-33421(33): 为‘‘typing.AsyncContextManager‘‘添加缺失的文档。

   - bpo-33487(34): BZ2file now emit a DeprecationWarning when
     buffering=None is passed, the deprecation message and documentation
     also now explicitly state it is deprecated since 3.0.

   - bpo-33378(35): Add Korean language switcher for
     ‘https://docs.python.org/3/’

   - bpo-33276(36): Clarify that the ‘__path__’ attribute on modules
     cannot be just any value.

   - bpo-33201(37): Modernize documentation for writing C extension
     types.

   - bpo-33195(38): Deprecate ‘Py_UNICODE’ usage in ‘c-api/arg’
     document.  ‘Py_UNICODE’ related APIs are deprecated since Python
     3.3, but it is missed in the document.

   - bpo-33126(39): Document PyBuffer_ToContiguous().

   - bpo-27212(40): Modify documentation for the ‘islice()’ recipe to
     consume initial values up to the start index.

   - bpo-28247(41): Update *note zipapp: 142. documentation to describe
     how to make standalone applications.

   - bpo-18802(42): Documentation changes for ipaddress.  Patch by Jon
     Foster and Berker Peksag.

   - bpo-27428(43): Update documentation to clarify that
     ‘WindowsRegistryFinder’ implements ‘MetaPathFinder’.  (Patch by
     Himanshu Lakhara)

   - bpo-28124(44): The ssl module function ssl.wrap_socket() has been
     de-emphasized and deprecated in favor of the more secure and
     efficient SSLContext.wrap_socket() method.

   - bpo-17232(45): Clarify docs for -O and -OO. Patch by Terry Reedy.

   - bpo-32436(46): Add documentation for the contextvars module (PEP
     567).

   - bpo-32800(47): Update link to w3c doc for xml default namespaces.

   - bpo-11015(48): Update *note test.support: 107. documentation.

   - bpo-32613(49): Update the faq/windows.html to use the py command
     from PEP 397 instead of python.

   - bpo-8722(50): Document *note __getattr__(): 323. behavior when
     property ‘get()’ method raises *note AttributeError: 3a3.

   - bpo-32614(51): Modify RE examples in documentation to use raw
     strings to prevent *note DeprecationWarning: 279. and add text to
     REGEX HOWTO to highlight the deprecation.

   - bpo-20709(52): Remove the paragraph where we explain that
     os.utime() does not support a directory as path under Windows.
     Patch by Jan-Philip Gehrcke

   - bpo-32722(53): Remove the bad example in the tutorial of the
     Generator Expression.  Patch by Stéphane Wirtel

   - bpo-31972(54): Improve docstrings for *note pathlib.PurePath: 1051.
     subclasses.

   - bpo-30607(55): Use the externalized ‘python-docs-theme’ package
     when building the documentation.

   - bpo-8243(56): Add a note about curses.addch and curses.addstr
     exception behavior when writing outside a window, or pad.

   - bpo-32337(57): Update documentation related with ‘dict’ order.

   - bpo-25041(58): Document ‘AF_PACKET’ in the *note socket: f0.
     module.

   - bpo-31432(59): Clarify meaning of CERT_NONE, CERT_OPTIONAL, and
     CERT_REQUIRED flags for ssl.SSLContext.verify_mode.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21257

   (2) https://bugs.python.org/issue34764

   (3) https://bugs.python.org/issue35564

   (4) https://bugs.python.org/issue35511

   (5) https://bugs.python.org/issue10536

   (6) https://bugs.python.org/issue35089

   (7) https://bugs.python.org/issue35038

   (8) https://bugs.python.org/issue35042

   (9) https://bugs.python.org/issue35044

   (10) https://bugs.python.org/issue35035

   (11) https://bugs.python.org/issue34967

   (12) https://bugs.python.org/issue34913

   (13) https://bugs.python.org/issue32174

   (14) https://bugs.python.org/issue11233

   (15) https://bugs.python.org/issue34790

   (16) https://bugs.python.org/issue34552

   (17) https://bugs.python.org/issue28617

   (18) https://bugs.python.org/issue20177

   (19) https://bugs.python.org/issue34065

   (20) https://bugs.python.org/issue33460

   (21) https://bugs.python.org/issue33847

   (22) https://bugs.python.org/issue33409

   (23) https://www.python.org/dev/peps/pep-0538

   (24) https://bugs.python.org/issue33197

   (25) https://bugs.python.org/issue17045

   (26) https://bugs.python.org/issue33736

   (27) https://bugs.python.org/issue23859

   (28) https://bugs.python.org/issue32436

   (29) https://www.python.org/dev/peps/pep-0567

   (30) https://bugs.python.org/issue33604

   (31) https://bugs.python.org/issue33594

   (32) https://bugs.python.org/issue33503

   (33) https://bugs.python.org/issue33421

   (34) https://bugs.python.org/issue33487

   (35) https://bugs.python.org/issue33378

   (36) https://bugs.python.org/issue33276

   (37) https://bugs.python.org/issue33201

   (38) https://bugs.python.org/issue33195

   (39) https://bugs.python.org/issue33126

   (40) https://bugs.python.org/issue27212

   (41) https://bugs.python.org/issue28247

   (42) https://bugs.python.org/issue18802

   (43) https://bugs.python.org/issue27428

   (44) https://bugs.python.org/issue28124

   (45) https://bugs.python.org/issue17232

   (46) https://bugs.python.org/issue32436

   (47) https://bugs.python.org/issue32800

   (48) https://bugs.python.org/issue11015

   (49) https://bugs.python.org/issue32613

   (50) https://bugs.python.org/issue8722

   (51) https://bugs.python.org/issue32614

   (52) https://bugs.python.org/issue20709

   (53) https://bugs.python.org/issue32722

   (54) https://bugs.python.org/issue31972

   (55) https://bugs.python.org/issue30607

   (56) https://bugs.python.org/issue8243

   (57) https://bugs.python.org/issue32337

   (58) https://bugs.python.org/issue25041

   (59) https://bugs.python.org/issue31432


File: python.info,  Node: 测试<20>,  Next: 构建<17>,  Prev: 文档<25>,  Up: Python 3 8 0 alpha 1

1.18.30.5 测试
..............

   - bpo-35772(1): Fix sparse file tests of test_tarfile on ppc64 with
     the tmpfs filesystem.  Fix the function testing if the filesystem
     supports sparse files: create a file which contains data and
     "holes", instead of creating a file which contains no data.  tmpfs
     effective block size is a page size (tmpfs lives in the page
     cache).  RHEL uses 64 KiB pages on aarch64, ppc64, ppc64le, only
     s390x and x86_64 use 4 KiB pages, whereas the test punch holes of 4
     KiB.

   - bpo-35045(2): Make ssl tests less strict and also accept TLSv1 as
     system default.  The changes unbreaks test_min_max_version on
     Fedora 29.

   - bpo-32710(3): ‘test_asyncio/test_sendfile.py’ now resets the event
     loop policy using ‘tearDownModule()’ as done in other tests, to
     prevent a warning when running tests on Windows.

   - bpo-33717(4): test.pythoninfo now logs information of all clocks,
     not only time.time() and time.perf_counter().

   - bpo-35488(5): Add a test to pathlib’s Path.match() to verify it
     does not support glob-style ** recursive pattern matching.

   - bpo-31731(6): Fix a race condition in ‘check_interrupted_write()’
     of test_io: create directly the thread with SIGALRM signal blocked,
     rather than blocking the signal later from the thread.  Previously,
     it was possible that the thread gets the signal before the signal
     is blocked.

   - bpo-35424(7): Fix test_multiprocessing_main_handling: use
     ‘multiprocessing.Pool’ with a context manager and then explicitly
     join the pool.

   - bpo-35519(8): Rename ‘test.bisect’ module to ‘test.bisect_cmd’ to
     avoid conflict with *note bisect: 12. module when running directly
     a test like ‘./python Lib/test/test_xmlrpc.py’.

   - bpo-35513(9): Replace *note time.time(): 326. with *note
     time.monotonic(): 778. in tests to measure time delta.

   - bpo-34279(10): *note test.support.run_unittest(): 1053. no longer
     raise ‘TestDidNotRun’ if the test result contains skipped tests.
     The exception is now only raised if no test have been run and no
     test have been skipped.

   - bpo-35412(11): Add testcase to ‘test_future4’: check unicode
     literal.

   - bpo-26704(12): 添加了对一个实例方法进行双重修补的测试演示。 补丁作
     者为 Anthony Sottile。

   - bpo-33725(13): test_multiprocessing_fork may crash on recent
     versions of macOS. Until the issue is resolved, skip the test on
     macOS.

   - bpo-35352(14): Modify test_asyncio to use the certificate set from
     the test directory.

   - bpo-35317(15): Fix ‘mktime()’ overflow error in ‘test_email’: run
     ‘test_localtime_daylight_true_dst_true()’ and
     ‘test_localtime_daylight_false_dst_true()’ with a specific
     timezone.

   - bpo-21263(16): After several reports that test_gdb does not work
     properly on macOS and since gdb is not shipped by default anymore,
     test_gdb is now skipped on macOS when LLVM Clang has been used to
     compile Python.  Patch by Lysandros Nikolaou

   - bpo-34279(17): regrtest issue a warning when no tests have been
     executed in a particular test file.  Also, a new final result state
     is issued if no test have been executed across all test files.
     Patch by Pablo Galindo.

   - bpo-34962(18): make docstest in Doc now passes., and is enforced in
     CI

   - bpo-23596(19): Use argparse for the command line of the gzip
     module.  Patch by Antony Lee

   - bpo-34537(20): Fix ‘test_gdb.test_strings()’ when ‘LC_ALL=C’ and
     GDB was compiled with Python 3.6 or earlier.

   - bpo-34587(21): test_socket: Remove RDSTest.testCongestion().  The
     test tries to fill the receiver’s socket buffer and expects an
     error.  But the RDS protocol doesn’t require that.  Moreover, the
     Linux implementation of RDS expects that the producer of the
     messages reduces its rate, it’s not the role of the receiver to
     trigger an error.  The test fails on Fedora 28 by design, so just
     remove it.

   - bpo-34661(22): Fix test_shutil if unzip doesn’t support -t.

   - bpo-34200(23): Fixed non-deterministic flakiness of test_pkg by not
     using the scary test.support.module_cleanup() logic to save and
     restore sys.modules contents between test cases.

   - bpo-34569(24): The experimental PEP 554 data channels now correctly
     pass negative PyLong objects between subinterpreters on 32-bit
     systems.  Patch by Michael Felt.

   - bpo-34594(25): Fix usage of hardcoded ‘errno’ values in the tests.

   - bpo-34579(26): Fix test_embed for AIX Patch by Michael Felt

   - bpo-34542(27): Use 3072 RSA keys and SHA-256 signature for test
     certs and keys.

   - bpo-11193(28): Remove special condition for AIX in
     ‘test_subprocess.test_undecodable_env’

   - bpo-34347(29): Fix ‘test_utf8_mode.test_cmd_line’ for AIX

   - bpo-34490(30): On AIX with AF_UNIX family sockets getsockname()
     does not provide ’sockname’, so skip calls to
     transport.get_extra_info(’sockname’)

   - bpo-34391(31): Fix ftplib test for TLS 1.3 by reading from data
     socket.

   - bpo-11192(32): Fix ‘test_socket’ on AIX 6.1 and later IPv6 zone id
     supports only supported by inet_pton6_zone() Switch to
     runtime-based platform.system() to establish current platform
     rather than build-time based sys.platform()

   - bpo-34399(33): Update all RSA keys and DH params to use at least
     2048 bits.

   - bpo-34373(34): Fix ‘test_mktime’ and ‘test_pthread_getcpuclickid’
     tests for AIX Add range checking for ‘_PyTime_localtime’ for AIX
     Patch by Michael Felt

   - bpo-11191(35): Skip the distutils test ’test_search_cpp’ when using
     XLC as compiler patch by aixtools (Michael Felt)

   - Improved an error message when mock assert_has_calls fails.

   - bpo-33746(36): Fix test_unittest when run in verbose mode.

   - bpo-33901(37): Fix test_dbm_gnu on macOS with gdbm 1.15: add a
     larger value to make sure that the file size changes.

   - bpo-33873(38): Fix a bug in ‘regrtest’ that caused an extra test to
     run if –huntrleaks/-R was used.  Exit with error in case that
     invalid parameters are specified to –huntrleaks/-R (at least one
     warmup run and one repetition must be used).

   - bpo-33562(39): Check that a global asyncio event loop policy is not
     left behind by any tests.

   - bpo-33655(40): 忽略运行在BSD平台的ZFS上时test_posix_fallocate的失败
     。

   - bpo-32962(41): Fixed test_gdb when Python is compiled with flags
     -mcet -fcf-protection -O0.

   - bpo-33358(42): Fix
     ‘test_embed.test_pre_initialization_sys_options()’ when the
     interpreter is built with ‘--enable-shared’.

   - bpo-32872(43): Avoid regrtest compatibility issue with namespace
     packages.

   - bpo-32517(44): Fix failing ‘test_asyncio’ on macOS 10.12.2+ due to
     transport of ‘KqueueSelector’ loop was not being closed.

   - bpo-32663(45): Making sure the ‘SMTPUTF8SimTests’ class of tests
     gets run in test_smtplib.py.

   - bpo-27643(46): Test_C test case needs "signed short" bitfields, but
     the IBM XLC compiler (on AIX) does not support this Skip the code
     and test when AIX and XLC are used

     Applicable to Python2-2.7 and later

   - bpo-19417(47): Add test_bdb.py.

   - bpo-31809(48): Add tests to verify connection with secp ECDH
     curves.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35772

   (2) https://bugs.python.org/issue35045

   (3) https://bugs.python.org/issue32710

   (4) https://bugs.python.org/issue33717

   (5) https://bugs.python.org/issue35488

   (6) https://bugs.python.org/issue31731

   (7) https://bugs.python.org/issue35424

   (8) https://bugs.python.org/issue35519

   (9) https://bugs.python.org/issue35513

   (10) https://bugs.python.org/issue34279

   (11) https://bugs.python.org/issue35412

   (12) https://bugs.python.org/issue26704

   (13) https://bugs.python.org/issue33725

   (14) https://bugs.python.org/issue35352

   (15) https://bugs.python.org/issue35317

   (16) https://bugs.python.org/issue21263

   (17) https://bugs.python.org/issue34279

   (18) https://bugs.python.org/issue34962

   (19) https://bugs.python.org/issue23596

   (20) https://bugs.python.org/issue34537

   (21) https://bugs.python.org/issue34587

   (22) https://bugs.python.org/issue34661

   (23) https://bugs.python.org/issue34200

   (24) https://bugs.python.org/issue34569

   (25) https://bugs.python.org/issue34594

   (26) https://bugs.python.org/issue34579

   (27) https://bugs.python.org/issue34542

   (28) https://bugs.python.org/issue11193

   (29) https://bugs.python.org/issue34347

   (30) https://bugs.python.org/issue34490

   (31) https://bugs.python.org/issue34391

   (32) https://bugs.python.org/issue11192

   (33) https://bugs.python.org/issue34399

   (34) https://bugs.python.org/issue34373

   (35) https://bugs.python.org/issue11191

   (36) https://bugs.python.org/issue33746

   (37) https://bugs.python.org/issue33901

   (38) https://bugs.python.org/issue33873

   (39) https://bugs.python.org/issue33562

   (40) https://bugs.python.org/issue33655

   (41) https://bugs.python.org/issue32962

   (42) https://bugs.python.org/issue33358

   (43) https://bugs.python.org/issue32872

   (44) https://bugs.python.org/issue32517

   (45) https://bugs.python.org/issue32663

   (46) https://bugs.python.org/issue27643

   (47) https://bugs.python.org/issue19417

   (48) https://bugs.python.org/issue31809


File: python.info,  Node: 构建<17>,  Next: Windows<22>,  Prev: 测试<20>,  Up: Python 3 8 0 alpha 1

1.18.30.6 构建
..............

   - bpo-34691(1): The _contextvars module is now built into the core
     Python library on Windows.

   - bpo-35683(2): Improved Azure Pipelines build steps and now
     verifying layouts correctly

   - bpo-35642(3): Remove asynciomodule.c from pythoncore.vcxproj

   - bpo-35550(4): Fix incorrect Solaris #ifdef checks to look for __sun
     && __SVR4 instead of sun when compiling.

   - bpo-35499(5): ‘make profile-opt’ no longer replaces ‘CFLAGS_NODIST’
     with ‘CFLAGS’.  It now adds profile-guided optimization (PGO) flags
     to ‘CFLAGS_NODIST’: existing ‘CFLAGS_NODIST’ flags are kept.

   - bpo-35257(6): Avoid leaking the linker flags from Link Time
     Optimizations (LTO) into distutils when compiling C extensions.

   - bpo-35351(7): When building Python with clang and LTO, LTO flags
     are no longer passed into CFLAGS to build third-party C extensions
     through distutils.

   - bpo-35139(8): Fix a compiler error when statically linking
     ‘pyexpat’ in ‘Modules/Setup’.

   - bpo-35059(9): PCbuild: Set InlineFunctionExpansion to
     OnlyExplicitInline ("/Ob1" option) in pyproject.props in Debug mode
     to expand functions marked as inline.  This change should make
     Python compiled in Debug mode a little bit faster on Windows.

   - bpo-35011(10): Restores the use of pyexpatns.h to isolate our
     embedded copy of the expat C library so that its symbols do not
     conflict at link or dynamic loading time with an embedding
     application or other extension modules with their own version of
     libexpat.

   - bpo-28015(11): Have –with-lto works correctly with clang.

   - bpo-34765(12): Update the outdated install-sh file to the latest
     revision from automake v1.16.1

   - bpo-34585(13): Check for floating-point byte order in configure.ac
     using compilation tests instead of executing code, so that these
     checks work in cross-compiled builds.

   - bpo-34710(14): Fixed SSL module build with OpenSSL & pedantic
     CFLAGS.

   - bpo-34582(15): Add JUnit XML output for regression tests and update
     Azure DevOps builds.

   - bpo-34081(16): Make Sphinx warnings as errors in the Docs Makefile.

   - bpo-34555(17): Fix for case where it was not possible to have both
     ‘HAVE_LINUX_VM_SOCKETS_H’ and ‘HAVE_SOCKADDR_ALG’ be undefined.

   - bpo-33015(18): Fix an undefined behaviour in the pthread
     implementation of ‘PyThread_start_new_thread()’: add a function
     wrapper to always return ‘NULL’.

   - bpo-34245(19): The Python shared library is now installed with
     write permission (mode 0755), which is the standard way of
     installing such libraries.

   - bpo-34121(20): Fix detection of C11 atomic support on clang.

   - bpo-32430(21): Rename Modules/Setup.dist to Modules/Setup, and
     remove the necessity to copy the former manually to the latter when
     updating the local source tree.

   - bpo-30345(22): Add -g to LDFLAGS when compiling with LTO to get
     debug symbols.

   - bpo-5755(23): Move ‘-Wstrict-prototypes’ option to ‘CFLAGS_NODIST’
     from ‘OPT’.  This option emitted annoying warnings when building
     extension modules written in C++.

   - bpo-33614(24): Ensures module definition files for the stable ABI
     on Windows are correctly regenerated.

   - bpo-33648(25): The –with-c-locale-warning configuration flag has
     been removed.  It has had no effect for about a year.

   - bpo-33522(26): Enable CI builds on Visual Studio Team Services at
     ‘https://python.visualstudio.com/cpython’

   - bpo-33512(27): configure’s check for "long double" has been
     simplified

   - bpo-33483(28): C compiler is now correctly detected from the
     standard environment variables.  –without-gcc and –with-icc options
     have been removed.

   - bpo-33394(29): Enable the verbose build for extension modules, when
     GNU make is passed macros on the command line.

   - bpo-33393(30): Update config.guess and config.sub files.

   - bpo-33377(31): Add new triplets for mips r6 and riscv variants
     (used in extension suffixes).

   - bpo-32232(32): By default, modules configured in ‘Modules/Setup’
     are no longer built with ‘-DPy_BUILD_CORE’.  Instead, modules that
     specifically need that preprocessor definition include it in their
     individual entries.

   - bpo-33182(33): The embedding tests can once again be built with
     clang 6.0

   - bpo-33163(34): Upgrade pip to 9.0.3 and setuptools to v39.0.1.

   - bpo-33012(35): gcc 8 has added a new warning heuristic to detect
     invalid function casts and a stock python build seems to hit that
     warning quite often.  The most common is the cast of a METH_NOARGS
     function (that uses just one argument) to a PyCFunction.  Fix this
     by adding a dummy argument to all functions that implement
     METH_NOARGS.

   - bpo-32898(36): Fix the python debug build when using COUNT_ALLOCS.

   - bpo-29442(37): Replace optparse with argparse in setup.py

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34691

   (2) https://bugs.python.org/issue35683

   (3) https://bugs.python.org/issue35642

   (4) https://bugs.python.org/issue35550

   (5) https://bugs.python.org/issue35499

   (6) https://bugs.python.org/issue35257

   (7) https://bugs.python.org/issue35351

   (8) https://bugs.python.org/issue35139

   (9) https://bugs.python.org/issue35059

   (10) https://bugs.python.org/issue35011

   (11) https://bugs.python.org/issue28015

   (12) https://bugs.python.org/issue34765

   (13) https://bugs.python.org/issue34585

   (14) https://bugs.python.org/issue34710

   (15) https://bugs.python.org/issue34582

   (16) https://bugs.python.org/issue34081

   (17) https://bugs.python.org/issue34555

   (18) https://bugs.python.org/issue33015

   (19) https://bugs.python.org/issue34245

   (20) https://bugs.python.org/issue34121

   (21) https://bugs.python.org/issue32430

   (22) https://bugs.python.org/issue30345

   (23) https://bugs.python.org/issue5755

   (24) https://bugs.python.org/issue33614

   (25) https://bugs.python.org/issue33648

   (26) https://bugs.python.org/issue33522

   (27) https://bugs.python.org/issue33512

   (28) https://bugs.python.org/issue33483

   (29) https://bugs.python.org/issue33394

   (30) https://bugs.python.org/issue33393

   (31) https://bugs.python.org/issue33377

   (32) https://bugs.python.org/issue32232

   (33) https://bugs.python.org/issue33182

   (34) https://bugs.python.org/issue33163

   (35) https://bugs.python.org/issue33012

   (36) https://bugs.python.org/issue32898

   (37) https://bugs.python.org/issue29442


File: python.info,  Node: Windows<22>,  Next: macOS<16>,  Prev: 构建<17>,  Up: Python 3 8 0 alpha 1

1.18.30.7 Windows
.................

   - bpo-35890(1): Fix API calling consistency of GetVersionEx and
     wcstok.

   - bpo-32560(2): The ‘py’ launcher now forwards its ‘STARTUPINFO’
     structure to child processes.

   - bpo-35854(3): Fix EnvBuilder and –symlinks in venv on Windows

   - bpo-35811(4): Avoid propagating venv settings when launching via
     py.exe

   - bpo-35797(5): Fix default executable used by the multiprocessing
     module

   - bpo-35758(6): Allow building on ARM with MSVC.

   - bpo-29734(7): Fix handle leaks in os.stat on Windows.

   - bpo-35596(8): Use unchecked PYCs for the embeddable distro to avoid
     zipimport restrictions.

   - bpo-35596(9): Fix vcruntime140.dll being added to embeddable distro
     multiple times.

   - bpo-35402(10): 更新 Windows 构建以使用 Tcl 和 Tk 8.6.9

   - bpo-35401(11): 将Windows内部版本更新到OpenSSL 1.1.0j

   - bpo-34977(12): venv on Windows will now use a python.exe redirector
     rather than copying the actual binaries from the base environment.

   - bpo-34977(13): Adds support for building a Windows App Store
     package

   - bpo-35067(14): Remove _distutils_findvs module and use vswhere.exe
     instead.

   - bpo-32557(15): Allow shutil.disk_usage to take a file path on
     Windows

   - bpo-34770(16): Fix a possible null pointer dereference in
     pyshellext.cpp.

   - bpo-34603(17): Fix returning structs from functions produced by
     MSVC

   - bpo-34581(18): Guard MSVC-specific code in socketmodule.c with
     ‘#ifdef _MSC_VER’.

   - bpo-34532(19): Fixes exit code of list version arguments for
     py.exe.

   - bpo-34062(20): Fixed the ’–list’ and ’–list-paths’ arguments for
     the py.exe launcher

   - bpo-34225(21): Ensure INCLUDE and LIB directories do not end with a
     backslash.

   - bpo-34011(22): A suite of code has been changed which copied across
     DLLs and init.tcl from the running Python location into a venv
     being created.  These copies are needed only when running from a
     Python source build, and the copying code is now only run when that
     is the case, rather than whenever a venv is created.

   - bpo-34006(23): Revert line length limit for Windows help docs.  The
     line-length limit is not needed because the pages appear in a
     separate app rather than on a browser tab.  It can also interact
     badly with the DPI setting.

   - bpo-31546(24): Restore running PyOS_InputHook while waiting for
     user input at the prompt.  The restores integration of interactive
     GUI windows (such as Matplotlib figures) with the prompt on
     Windows.

   - bpo-30237(25): Output error when ReadConsole is canceled by
     CancelSynchronousIo instead of crashing.

   - bpo-33895(26): GIL is released while calling functions that acquire
     Windows loader lock.

   - bpo-33720(27): Reduces maximum marshal recursion depth on release
     builds.

   - bpo-29097(28): Fix bug where ‘datetime.fromtimestamp()’ erroneously
     throws an *note OSError: 1d4. on Windows for values between 0 and
     86400.  Patch by Ammar Askar.

   - bpo-33316(29): PyThread_release_lock always fails

   - bpo-33184(30): 在Windows安装程序中将OpenSSL更新为1.1.0h.

   - bpo-32890(31): Fix usage of GetLastError() instead of errno in
     os.execve() and os.truncate().

   - bpo-33016(32): Fix potential use of uninitialized memory in
     nt._getfinalpathname

   - bpo-32903(33): Fix a memory leak in os.chdir() on Windows if the
     current directory is set to a UNC path.

   - bpo-32901(34): Update Tcl and Tk versions to 8.6.8

   - bpo-31966(35): Fixed WindowsConsoleIO.write() for writing empty
     data.

   - bpo-32409(36): Ensures activate.bat can handle Unicode contents.

   - bpo-32457(37): Improves handling of denormalized executable path
     when launching Python.

   - bpo-32370(38): Use the correct encoding for ipconfig output in the
     uuid module.  Patch by Segev Finer.

   - bpo-29248(39): Fix *note os.readlink(): 1f4. on Windows, which was
     mistakenly treating the ‘PrintNameOffset’ field of the reparse data
     buffer as a number of characters instead of bytes.  Patch by Craig
     Holmquist and SSE4.

   - bpo-1104(40): Correctly handle string length in
     ‘msilib.SummaryInfo.GetProperty()’ to prevent it from truncating
     the last character.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35890

   (2) https://bugs.python.org/issue32560

   (3) https://bugs.python.org/issue35854

   (4) https://bugs.python.org/issue35811

   (5) https://bugs.python.org/issue35797

   (6) https://bugs.python.org/issue35758

   (7) https://bugs.python.org/issue29734

   (8) https://bugs.python.org/issue35596

   (9) https://bugs.python.org/issue35596

   (10) https://bugs.python.org/issue35402

   (11) https://bugs.python.org/issue35401

   (12) https://bugs.python.org/issue34977

   (13) https://bugs.python.org/issue34977

   (14) https://bugs.python.org/issue35067

   (15) https://bugs.python.org/issue32557

   (16) https://bugs.python.org/issue34770

   (17) https://bugs.python.org/issue34603

   (18) https://bugs.python.org/issue34581

   (19) https://bugs.python.org/issue34532

   (20) https://bugs.python.org/issue34062

   (21) https://bugs.python.org/issue34225

   (22) https://bugs.python.org/issue34011

   (23) https://bugs.python.org/issue34006

   (24) https://bugs.python.org/issue31546

   (25) https://bugs.python.org/issue30237

   (26) https://bugs.python.org/issue33895

   (27) https://bugs.python.org/issue33720

   (28) https://bugs.python.org/issue29097

   (29) https://bugs.python.org/issue33316

   (30) https://bugs.python.org/issue33184

   (31) https://bugs.python.org/issue32890

   (32) https://bugs.python.org/issue33016

   (33) https://bugs.python.org/issue32903

   (34) https://bugs.python.org/issue32901

   (35) https://bugs.python.org/issue31966

   (36) https://bugs.python.org/issue32409

   (37) https://bugs.python.org/issue32457

   (38) https://bugs.python.org/issue32370

   (39) https://bugs.python.org/issue29248

   (40) https://bugs.python.org/issue1104


File: python.info,  Node: macOS<16>,  Next: IDLE<27>,  Prev: Windows<22>,  Up: Python 3 8 0 alpha 1

1.18.30.8 macOS
...............

   - bpo-35401(1): 在MacOS安装程序中将OpenSSL更新为1.1.0j。

   - bpo-35025(2): Properly guard the use of the ‘CLOCK_GETTIME’ et al.
     macros in ‘timemodule’ on macOS.

   - bpo-24658(3): On macOS, fix reading from and writing into a file
     with a size larger than 2 GiB.

   - bpo-34405(4): 在MacOS安装程序中将OpenSSL更新为1.1.0i 。

   - bpo-33635(5): In macOS stat on some file descriptors (/dev/fd/3
     f.e) will result in bad file descriptor OSError.  Guard against
     this exception was added in is_dir, is_file and similar methods.
     DirEntry.is_dir can also throw this exception so
     _RecursiveWildcardSelector._iterate_directories was also extended
     with the same error ignoring pattern.

   - bpo-13631(6): The .editrc file in user’s home directory is now
     processed correctly during the readline initialization through
     editline emulation on macOS.

   - bpo-33184(7): 在MacOS安装程序中将OpenSSL更新为1.1.0h。

   - bpo-32726(8): Build and link with private copy of Tcl/Tk 8.6 for
     the macOS 10.6+ installer.  The 10.9+ installer variant already
     does this.  This means that the Python 3.7 provided by the
     python.org macOS installers no longer need or use any external
     versions of Tcl/Tk, either system-provided or user-installed, such
     as ActiveTcl.

   - bpo-32901(9): Update macOS 10.9+ installer to Tcl/Tk 8.6.8.

   - bpo-31903(10): In ‘_scproxy’, drop the GIL when calling into
     ‘SystemConfiguration’ to avoid deadlocks.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35401

   (2) https://bugs.python.org/issue35025

   (3) https://bugs.python.org/issue24658

   (4) https://bugs.python.org/issue34405

   (5) https://bugs.python.org/issue33635

   (6) https://bugs.python.org/issue13631

   (7) https://bugs.python.org/issue33184

   (8) https://bugs.python.org/issue32726

   (9) https://bugs.python.org/issue32901

   (10) https://bugs.python.org/issue31903


File: python.info,  Node: IDLE<27>,  Next: 工具/示例<12>,  Prev: macOS<16>,  Up: Python 3 8 0 alpha 1

1.18.30.9 IDLE
..............

   - bpo-35770(1): IDLE macosx deletes Options => Configure IDLE. It
     previously deleted Window => Zoom Height by mistake.  (Zoom Height
     is now on the Options menu).  On Mac, the settings dialog is
     accessed via Preferences on the IDLE menu.

   - bpo-35769(2): 将 IDLE 的新文件名从 ’Untitled’ 更改为 ’untitled’

   - bpo-35660(3): Fix imports in idlelib.window.

   - bpo-35641(4): 当函数没有文档字符串时正确地格式化 ‘calltip’。

   - bpo-33987(5): Use ttk Frame for ttk widgets.

   - bpo-34055(6): Fix erroneous ’smart’ indents and newlines in IDLE
     Shell.

   - bpo-35591(7): Find Selection now works when selection not found.

   - bpo-35196(8): Speed up squeezer line counting.

   - bpo-35598(9): Update config_key: use PEP 8 names and ttk widgets,
     make some objects global, and add tests.

   - bpo-28097(10): Add Previous/Next History entries to Shell menu.

   - bpo-35208(11): Squeezer now properly counts wrapped lines before
     newlines.

   - bpo-35555(12): Gray out Code Context menu entry when it’s not
     applicable.

   - bpo-35521(13): Document the IDLE editor code context feature.  Add
     some internal references within the IDLE doc.

   - bpo-22703(14): The Code Context menu label now toggles between
     Show/Hide Code Context.  The Zoom Height menu now toggles between
     Zoom/Restore Height.  Zoom Height has moved from the Window menu to
     the Options menu.

   - bpo-35213(15): Where appropriate, use ’macOS’ in idlelib.

   - bpo-34864(16): On macOS, warn if the system preference "Prefer tabs
     when opening documents" is set to "Always".

   - bpo-34864(17): Document two IDLE on MacOS issues.  The System
     Preferences Dock "prefer tabs always" setting disables some IDLE
     features.  Menus are a bit different than as described for Windows
     and Linux.

   - bpo-35202(18): Remove unused imports from lib/idlelib

   - bpo-33000(19): Document that IDLE’s shell has no line limit.  A
     program that runs indefinitely can overfill memory.

   - bpo-23220(20): Explain how IDLE’s Shell displays output.

   - bpo-35099(21): Improve the doc about IDLE running user code.  The
     section is renamed from "IDLE – console differences" is renamed
     "Running user code".  It mostly covers the implications of using
     custom sys.stdxxx objects.

   - bpo-35097(22): Add IDLE doc subsection explaining editor windows.
     Topics include opening, title and status bar, .py* extension, and
     running.

   - bpo-35093(23): Document the IDLE document viewer in the IDLE doc.
     Add a paragraph in "Help and preferences", "Help sources"
     subsection.

   - bpo-35088(24): Update idlelib.help.copy_string docstring.  We now
     use git and backporting instead of hg and forward merging.

   - bpo-35087(25): Update idlelib help files for the current doc build.
     The main change is the elimination of chapter-section numbers.

   - bpo-34548(26): Use configured color theme for read-only text views.

   - bpo-1529353(27): Enable "squeezing" of long outputs in the shell,
     to avoid performance degradation and to clean up the history
     without losing it.  Squeezed outputs may be copied, viewed in a
     separate window, and "unsqueezed".

   - bpo-34047(28): Fixed mousewheel scrolling direction on macOS.

   - bpo-34275(29): Make IDLE calltips always visible on Mac.  Some
     MacOS-tk combinations need .update_idletasks().  Patch by Kevin
     Walzer.

   - bpo-34120(30): Fix unresponsiveness after closing certain windows
     and dialogs.

   - bpo-33975(31): Avoid small type when running htests.  Since part of
     the purpose of human-viewed tests is to determine that widgets look
     right, it is important that they look the same for testing as when
     running IDLE.

   - bpo-33905(32): Add test for idlelib.stackview.StackBrowser.

   - bpo-33924(33): Change mainmenu.menudefs key ’windows’ to ’window’.
     Every other menudef key is lowercase version of main menu entry.

   - bpo-33906(34): Rename idlelib.windows as window Match Window on the
     main menu and remove last plural module name.

   - bpo-33917(35): Fix and document idlelib/idle_test/template.py.  The
     revised file compiles, runs, and tests OK. idle_test/README.txt
     explains how to use it to create new IDLE test files.

   - bpo-33904(36): IDLE: In rstrip, rename class RstripExtension as
     Rstrip

   - bpo-33907(37): For consistency and clarity, rename an IDLE module
     and classes.  Module calltips and its class CallTips are now
     calltip and Calltip.  In module calltip_w, class CallTip is now
     CalltipWindow.

   - bpo-33856(38): Add "help" in the welcome message of IDLE

   - bpo-33839(39): IDLE: refactor ToolTip and CallTip and add
     documentation and tests

   - bpo-33855(40): Minimally test all IDLE modules.  Add missing files,
     import module, instantiate classes, and check coverage.  Check
     existing files.

   - bpo-33656(41): On Windows, add API call saying that tk scales for
     DPI. On Windows 8.1+ or 10, with DPI compatibility properties of
     the Python binary unchanged, and a monitor resolution greater than
     96 DPI, this should make text and lines sharper.  It should
     otherwise have no effect.

   - bpo-33768(42): Clicking on a context line moves that line to the
     top of the editor window.

   - bpo-33763(43): IDLE: Use read-only text widget for code context
     instead of label widget.

   - bpo-33664(44): Scroll IDLE editor text by lines.  Previously, the
     mouse wheel and scrollbar slider moved text by a fixed number of
     pixels, resulting in partial lines at the top of the editor box.
     The change also applies to the shell and grep output windows, but
     not to read-only text views.

   - bpo-33679(45): Enable theme-specific color configuration for Code
     Context.  Use the Highlights tab to see the setting for built-in
     themes or add settings to custom themes.

   - bpo-33642(46): Display up to maxlines non-blank lines for Code
     Context.  If there is no current context, show a single blank line.

   - bpo-33628(47): IDLE: Cleanup codecontext.py and its test.

   - bpo-33564(48): IDLE’s code context now recognizes async as a block
     opener.

   - bpo-21474(49): Update word/identifier definition from ascii to
     unicode.  In text and entry boxes, this affects selection by
     double-click, movement left/right by control-left/right, and
     deletion left/right by control-BACKSPACE/DEL.

   - bpo-33204(50): IDLE: consistently color invalid string prefixes.  A
     ’u’ string prefix cannot be paired with either ’r’ or ’f’.
     Consistently color as much of the prefix, starting at the right, as
     is valid.  Revise and extend colorizer test.

   - bpo-32984(51): Set ‘__file__’ while running a startup file.  Like
     Python, IDLE optionally runs one startup file in the Shell window
     before presenting the first interactive input prompt.  For IDLE,
     ‘-s’ runs a file named in environmental variable ‘IDLESTARTUP’ or
     *note PYTHONSTARTUP: 8ed.; ‘-r file’ runs ‘file’.  Python sets
     ‘__file__’ to the startup file name before running the file and
     unsets it before the first prompt.  IDLE now does the same when run
     normally, without the ‘-n’ option.

   - bpo-32940(52): Simplify and rename StringTranslatePseudoMapping in
     pyparse.

   - bpo-32916(53): Change ‘str’ to ‘code’ in pyparse.

   - bpo-32905(54): Remove unused code in pyparse module.

   - bpo-32874(55): Add tests for pyparse.

   - bpo-32837(56): Using the system and place-dependent default
     encoding for open() is a bad idea for IDLE’s system and
     location-independent files.

   - bpo-32826(57): Add "encoding=utf-8" to open() in IDLE’s
     test_help_about.  GUI test test_file_buttons() only looks at
     initial ascii-only lines, but failed on systems where open()
     defaults to ’ascii’ because readline() internally reads and decodes
     far enough ahead to encounter a non-ascii character in CREDITS.txt.

   - bpo-32831(58): Add docstrings and tests for codecontext.

   - bpo-32765(59): Update configdialog General tab docstring to add new
     widgets to the widget list.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35770

   (2) https://bugs.python.org/issue35769

   (3) https://bugs.python.org/issue35660

   (4) https://bugs.python.org/issue35641

   (5) https://bugs.python.org/issue33987

   (6) https://bugs.python.org/issue34055

   (7) https://bugs.python.org/issue35591

   (8) https://bugs.python.org/issue35196

   (9) https://bugs.python.org/issue35598

   (10) https://bugs.python.org/issue28097

   (11) https://bugs.python.org/issue35208

   (12) https://bugs.python.org/issue35555

   (13) https://bugs.python.org/issue35521

   (14) https://bugs.python.org/issue22703

   (15) https://bugs.python.org/issue35213

   (16) https://bugs.python.org/issue34864

   (17) https://bugs.python.org/issue34864

   (18) https://bugs.python.org/issue35202

   (19) https://bugs.python.org/issue33000

   (20) https://bugs.python.org/issue23220

   (21) https://bugs.python.org/issue35099

   (22) https://bugs.python.org/issue35097

   (23) https://bugs.python.org/issue35093

   (24) https://bugs.python.org/issue35088

   (25) https://bugs.python.org/issue35087

   (26) https://bugs.python.org/issue34548

   (27) https://bugs.python.org/issue1529353

   (28) https://bugs.python.org/issue34047

   (29) https://bugs.python.org/issue34275

   (30) https://bugs.python.org/issue34120

   (31) https://bugs.python.org/issue33975

   (32) https://bugs.python.org/issue33905

   (33) https://bugs.python.org/issue33924

   (34) https://bugs.python.org/issue33906

   (35) https://bugs.python.org/issue33917

   (36) https://bugs.python.org/issue33904

   (37) https://bugs.python.org/issue33907

   (38) https://bugs.python.org/issue33856

   (39) https://bugs.python.org/issue33839

   (40) https://bugs.python.org/issue33855

   (41) https://bugs.python.org/issue33656

   (42) https://bugs.python.org/issue33768

   (43) https://bugs.python.org/issue33763

   (44) https://bugs.python.org/issue33664

   (45) https://bugs.python.org/issue33679

   (46) https://bugs.python.org/issue33642

   (47) https://bugs.python.org/issue33628

   (48) https://bugs.python.org/issue33564

   (49) https://bugs.python.org/issue21474

   (50) https://bugs.python.org/issue33204

   (51) https://bugs.python.org/issue32984

   (52) https://bugs.python.org/issue32940

   (53) https://bugs.python.org/issue32916

   (54) https://bugs.python.org/issue32905

   (55) https://bugs.python.org/issue32874

   (56) https://bugs.python.org/issue32837

   (57) https://bugs.python.org/issue32826

   (58) https://bugs.python.org/issue32831

   (59) https://bugs.python.org/issue32765


File: python.info,  Node: 工具/示例<12>,  Next: C API<15>,  Prev: IDLE<27>,  Up: Python 3 8 0 alpha 1

1.18.30.10 工具/示例
....................

   - bpo-35884(1): Add a benchmark script for timing various ways to
     access variables: ‘Tools/scripts/var_access_benchmark.py’.

   - bpo-34989(2): python-gdb.py now handles errors on computing the
     line number of a Python frame.

   - bpo-20260(3): Argument Clinic now has non-bitwise unsigned int
     converters.

   - bpo-32962(4): python-gdb now catches ‘UnicodeDecodeError’
     exceptions when calling ‘string()’.

   - bpo-32962(5): python-gdb now catches ValueError on read_var(): when
     Python has no debug symbols for example.

   - bpo-33189(6): ‘pygettext.py’ now recognizes only literal strings as
     docstrings and translatable strings, and rejects bytes literals and
     f-string expressions.

   - bpo-31920(7): Fixed handling directories as arguments in the
     ‘pygettext’ script.  Based on patch by Oleg Krasnikov.

   - bpo-29673(8): Fix pystackv and pystack gdbinit macros.

   - bpo-25427(9): Remove the pyvenv script in favor of ‘python3 -m
     venv’ in order to lower confusion as to what Python interpreter a
     virtual environment will be created for.

   - bpo-32885(10): Add an ‘-n’ flag for ‘Tools/scripts/pathfix.py’ to
     disable automatic backup creation (files with ‘~’ suffix).

   - bpo-32222(11): Fix pygettext not extracting docstrings for
     functions with type annotated arguments.  Patch by Toby Harradine.

   - bpo-31583(12): Fix 2to3 for using with –add-suffix option but
     without –output-dir option for relative path to files in current
     directory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35884

   (2) https://bugs.python.org/issue34989

   (3) https://bugs.python.org/issue20260

   (4) https://bugs.python.org/issue32962

   (5) https://bugs.python.org/issue32962

   (6) https://bugs.python.org/issue33189

   (7) https://bugs.python.org/issue31920

   (8) https://bugs.python.org/issue29673

   (9) https://bugs.python.org/issue25427

   (10) https://bugs.python.org/issue32885

   (11) https://bugs.python.org/issue32222

   (12) https://bugs.python.org/issue31583


File: python.info,  Node: C API<15>,  Prev: 工具/示例<12>,  Up: Python 3 8 0 alpha 1

1.18.30.11 C API
................

   - bpo-35713(1): The ‘PyByteArray_Init()’ and ‘PyByteArray_Fini()’
     functions have been removed.  They did nothing since Python 2.7.4
     and Python 3.2.0, were excluded from the limited API (stable ABI),
     and were not documented.

   - bpo-33817(2): Fixed *note _PyBytes_Resize(): 105a. for empty bytes
     objects.

   - bpo-35322(3): Fix memory leak in *note PyUnicode_EncodeLocale():
     447. and *note PyUnicode_EncodeFSDefault(): 105b. on error
     handling.

   - bpo-35059(4): The following C macros have been converted to static
     inline functions: *note Py_INCREF(): 266, *note Py_DECREF(): 267,
     *note Py_XINCREF(): 268, *note Py_XDECREF(): 269,
     ‘PyObject_INIT()’, ‘PyObject_INIT_VAR()’.

   - bpo-35296(5): ‘make install’ now also installs the internal API:
     ‘Include/internal/*.h’ header files.

   - bpo-35081(6): Internal APIs surrounded by ‘#ifdef Py_BUILD_CORE’
     have been moved from ‘Include/*.h’ headers to new header files
     ‘Include/internal/pycore_*.h’.

   - bpo-35259(7): 基于 Py_LIMITED_API 有条件地声明 *note
     Py_FinalizeEx(): 5d2. (3.6 中新增)。 补丁作者 Arthur Neufeld。

   - bpo-35081(8): The ‘_PyObject_GC_TRACK()’ and
     ‘_PyObject_GC_UNTRACK()’ macros have been removed from the public C
     API.

   - bpo-35134(9): Creation of a new ‘Include/cpython/’ subdirectory.

   - bpo-34725(10): Adds _Py_SetProgramFullPath so embedders may
     override sys.executable

   - bpo-34910(11): Ensure that *note PyObject_Print(): 105c. always
     returns ‘-1’ on error.  Patch by Zackery Spytz.

   - bpo-34523(12): Py_DecodeLocale() and Py_EncodeLocale() now use the
     UTF-8 encoding on Windows if Py_LegacyWindowsFSEncodingFlag is
     zero.

   - bpo-34193(13): Fix pluralization in TypeError messages in getargs.c
     and typeobject.c: ’1 argument’ instead of ’1 arguments’ and ’1
     element’ instead of ’1 elements’.

   - bpo-34127(14): Return grammatically correct error message based on
     argument count.  Patch by Karthikeyan Singaravelan.

   - bpo-23927(15): Fixed *note SystemError: 604. in *note
     PyArg_ParseTupleAndKeywords(): 5d3. when the ‘w*’ format unit is
     used for optional parameter.

   - bpo-32455(16): Added ‘PyCompile_OpcodeStackEffectWithJump()’.

   - bpo-34008(17): Py_Main() can again be called after Py_Initialize(),
     as in Python 3.6.

   - bpo-32500(18): Fixed error messages for *note PySequence_Size():
     105d, *note PySequence_GetItem(): 105e, *note PySequence_SetItem():
     105f. and *note PySequence_DelItem(): 1060. called with a mapping
     and *note PyMapping_Size(): 1061. called with a sequence.

   - bpo-33818(19): ‘PyExceptionClass_Name()’ will now return ‘const
     char *’ instead of ‘char *’.

   - bpo-33042(20): Embedding applications may once again call
     PySys_ResetWarnOptions, PySys_AddWarnOption, and PySys_AddXOption
     prior to calling Py_Initialize.

   - bpo-32374(21): Document that m_traverse for multi-phase initialized
     modules can be called with m_state=NULL, and add a sanity check

   - bpo-30863(22): *note PyUnicode_AsWideChar(): 1062. and *note
     PyUnicode_AsWideCharString(): 440. no longer cache the ‘wchar_t*’
     representation of string objects.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35713

   (2) https://bugs.python.org/issue33817

   (3) https://bugs.python.org/issue35322

   (4) https://bugs.python.org/issue35059

   (5) https://bugs.python.org/issue35296

   (6) https://bugs.python.org/issue35081

   (7) https://bugs.python.org/issue35259

   (8) https://bugs.python.org/issue35081

   (9) https://bugs.python.org/issue35134

   (10) https://bugs.python.org/issue34725

   (11) https://bugs.python.org/issue34910

   (12) https://bugs.python.org/issue34523

   (13) https://bugs.python.org/issue34193

   (14) https://bugs.python.org/issue34127

   (15) https://bugs.python.org/issue23927

   (16) https://bugs.python.org/issue32455

   (17) https://bugs.python.org/issue34008

   (18) https://bugs.python.org/issue32500

   (19) https://bugs.python.org/issue33818

   (20) https://bugs.python.org/issue33042

   (21) https://bugs.python.org/issue32374

   (22) https://bugs.python.org/issue30863


File: python.info,  Node: Python 3 7 0 正式版,  Next: Python 3 7 0 rc1,  Prev: Python 3 8 0 alpha 1,  Up: 更新日志

1.18.31 Python 3.7.0 正式版
---------------------------

`发布日期: 2018-06-27'

* Menu:

* 库: 库<30>.
* C API: C API<16>.


File: python.info,  Node: 库<30>,  Next: C API<16>,  Up: Python 3 7 0 正式版

1.18.31.1 库
............

   - bpo-33851(1): Fix *note ast.get_docstring(): 1065. for a node that
     lacks a docstring.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33851


File: python.info,  Node: C API<16>,  Prev: 库<30>,  Up: Python 3 7 0 正式版

1.18.31.2 C API
...............

   - bpo-33932(1): Calling Py_Initialize() twice does nothing, instead
     of failing with a fatal error: restore the Python 3.6 behaviour.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33932


File: python.info,  Node: Python 3 7 0 rc1,  Next: Python 3 7 0 beta 5,  Prev: Python 3 7 0 正式版,  Up: 更新日志

1.18.32 Python 3.7.0 rc1
------------------------

`发布日期: 2018-06-12'

* Menu:

* 核心与内置: 核心与内置<30>.
* 库: 库<31>.
* 文档: 文档<26>.
* 构建: 构建<18>.
* Windows: Windows<23>.
* IDLE: IDLE<28>.


File: python.info,  Node: 核心与内置<30>,  Next: 库<31>,  Up: Python 3 7 0 rc1

1.18.32.1 核心与内置
....................

   - bpo-33803(1): Fix a crash in hamt.c caused by enabling GC tracking
     for an object that hadn’t all of its fields set to NULL.

   - bpo-33706(2): Fix a crash in Python initialization when parsing the
     command line options.  Thanks Christoph Gohlke for the bug report
     and the fix!

   - bpo-30654(3): Fixed reset of the SIGINT handler to SIG_DFL on
     interpreter shutdown even when there was a custom handler set
     previously.  Patch by Philipp Kerling.

   - bpo-31849(4): Fix signed/unsigned comparison warning in pyhash.c.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33803

   (2) https://bugs.python.org/issue33706

   (3) https://bugs.python.org/issue30654

   (4) https://bugs.python.org/issue31849


File: python.info,  Node: 库<31>,  Next: 文档<26>,  Prev: 核心与内置<30>,  Up: Python 3 7 0 rc1

1.18.32.2 库
............

   - bpo-30167(1): Prevent site.main() exception if PYTHONSTARTUP is
     set.  Patch by Steve Weber.

   - bpo-33812(2): Datetime instance d with non-None tzinfo, but with
     d.tzinfo.utcoffset(d) returning None is now treated as naive by the
     astimezone() method.

   - bpo-30805(3): Avoid race condition with debug logging

   - bpo-33694(4): asyncio: Fix a race condition causing data loss on
     pause_reading()/resume_reading() when using the ProactorEventLoop.

   - bpo-32493(5): Correct test for ‘uuid_enc_be’ availability in
     ‘configure.ac’.  Patch by Michael Felt.

   - bpo-33792(6): Add asyncio.WindowsSelectorEventLoopPolicy and
     asyncio.WindowsProactorEventLoopPolicy.

   - bpo-33778(7): Update ‘unicodedata’’s database to Unicode version
     11.0.0.

   - bpo-33770(8): improve base64 exception message for encoded inputs
     of invalid length

   - bpo-33769(9): asyncio/start_tls: Fix error message; cancel
     callbacks in case of an unhandled error; mark SSLTransport as
     closed if it is aborted.

   - bpo-33767(10): The concatenation (‘+’) and repetition (‘*’)
     sequence operations now raise *note TypeError: 193. instead of
     *note SystemError: 604. when performed on *note mmap.mmap: 1ed.
     objects.  Patch by Zackery Spytz.

   - bpo-33734(11): asyncio/ssl: Fix AttributeError, increase default
     handshake timeout

   - bpo-11874(12): Use a better regex when breaking usage into
     wrappable parts.  Avoids bogus assertion errors from custom metavar
     strings.

   - bpo-33582(13): Emit a deprecation warning for inspect.formatargspec

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30167

   (2) https://bugs.python.org/issue33812

   (3) https://bugs.python.org/issue30805

   (4) https://bugs.python.org/issue33694

   (5) https://bugs.python.org/issue32493

   (6) https://bugs.python.org/issue33792

   (7) https://bugs.python.org/issue33778

   (8) https://bugs.python.org/issue33770

   (9) https://bugs.python.org/issue33769

   (10) https://bugs.python.org/issue33767

   (11) https://bugs.python.org/issue33734

   (12) https://bugs.python.org/issue11874

   (13) https://bugs.python.org/issue33582


File: python.info,  Node: 文档<26>,  Next: 构建<18>,  Prev: 库<31>,  Up: Python 3 7 0 rc1

1.18.32.3 文档
..............

   - bpo-33409(1): Clarified the relationship between PEP 538(2)’s
     PYTHONCOERCECLOCALE and PEP 540’s PYTHONUTF8 mode.

   - bpo-33736(3): Improve the documentation of *note
     asyncio.open_connection(): 36c, *note asyncio.start_server(): 36d.
     and their UNIX socket counterparts.

   - bpo-31432(4): Clarify meaning of CERT_NONE, CERT_OPTIONAL, and
     CERT_REQUIRED flags for ssl.SSLContext.verify_mode.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33409

   (2) https://www.python.org/dev/peps/pep-0538

   (3) https://bugs.python.org/issue33736

   (4) https://bugs.python.org/issue31432


File: python.info,  Node: 构建<18>,  Next: Windows<23>,  Prev: 文档<26>,  Up: Python 3 7 0 rc1

1.18.32.4 构建
..............

   - bpo-5755(1): Move ‘-Wstrict-prototypes’ option to ‘CFLAGS_NODIST’
     from ‘OPT’.  This option emitted annoying warnings when building
     extension modules written in C++.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5755


File: python.info,  Node: Windows<23>,  Next: IDLE<28>,  Prev: 构建<18>,  Up: Python 3 7 0 rc1

1.18.32.5 Windows
.................

   - bpo-33720(1): Reduces maximum marshal recursion depth on release
     builds.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33720


File: python.info,  Node: IDLE<28>,  Prev: Windows<23>,  Up: Python 3 7 0 rc1

1.18.32.6 IDLE
..............

   - bpo-33656(1): On Windows, add API call saying that tk scales for
     DPI. On Windows 8.1+ or 10, with DPI compatibility properties of
     the Python binary unchanged, and a monitor resolution greater than
     96 DPI, this should make text and lines sharper.  It should
     otherwise have no effect.

   - bpo-33768(2): Clicking on a context line moves that line to the top
     of the editor window.

   - bpo-33763(3): IDLE: Use read-only text widget for code context
     instead of label widget.

   - bpo-33664(4): Scroll IDLE editor text by lines.  Previously, the
     mouse wheel and scrollbar slider moved text by a fixed number of
     pixels, resulting in partial lines at the top of the editor box.
     The change also applies to the shell and grep output windows, but
     not to read-only text views.

   - bpo-33679(5): Enable theme-specific color configuration for Code
     Context.  Use the Highlights tab to see the setting for built-in
     themes or add settings to custom themes.

   - bpo-33642(6): Display up to maxlines non-blank lines for Code
     Context.  If there is no current context, show a single blank line.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33656

   (2) https://bugs.python.org/issue33768

   (3) https://bugs.python.org/issue33763

   (4) https://bugs.python.org/issue33664

   (5) https://bugs.python.org/issue33679

   (6) https://bugs.python.org/issue33642


File: python.info,  Node: Python 3 7 0 beta 5,  Next: Python 3 7 0 beta 4,  Prev: Python 3 7 0 rc1,  Up: 更新日志

1.18.33 Python 3.7.0 beta 5
---------------------------

`发布日期: 2018-05-30'

* Menu:

* 核心与内置: 核心与内置<31>.
* 库: 库<32>.
* 文档: 文档<27>.
* 测试: 测试<21>.
* 构建: 构建<19>.
* macOS: macOS<17>.
* IDLE: IDLE<29>.


File: python.info,  Node: 核心与内置<31>,  Next: 库<32>,  Up: Python 3 7 0 beta 5

1.18.33.1 核心与内置
....................

   - bpo-33622(1): Fixed a leak when the garbage collector fails to add
     an object with the ‘__del__’ method or referenced by it into the
     *note gc.garbage: b48. list.  ‘PyGC_Collect()’ can now be called
     when an exception is set and preserves it.

   - bpo-33509(2): Fix module_globals parameter of
     warnings.warn_explicit(): don’t crash if module_globals is not a
     dict.

   - bpo-20104(3): The new *note os.posix_spawn: 258. added in 3.7.0b1
     was removed as we are still working on what the API should look
     like.  Expect this in 3.8 instead.

   - bpo-33475(4): Fixed miscellaneous bugs in converting annotations to
     strings and optimized parentheses in the string representation.

   - bpo-33391(5): Fix a leak in set_symmetric_difference().

   - bpo-28055(6): Fix unaligned accesses in siphash24().  Patch by Rolf
     Eike Beer.

   - bpo-32911(7): Due to unexpected compatibility issues discovered
     during downstream beta testing, reverted bpo-29463(8).  ‘docstring’
     field is removed from Module, ClassDef, FunctionDef, and
     AsyncFunctionDef ast nodes which was added in 3.7a1.  Docstring
     expression is restored as a first statement in their body.  Based
     on patch by Inada Naoki.

   - bpo-21983(9): Fix a crash in *note ctypes.cast(): 1023. in case the
     type argument is a ctypes structured data type.  Patch by Eryk Sun
     and Oren Milman.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33622

   (2) https://bugs.python.org/issue33509

   (3) https://bugs.python.org/issue20104

   (4) https://bugs.python.org/issue33475

   (5) https://bugs.python.org/issue33391

   (6) https://bugs.python.org/issue28055

   (7) https://bugs.python.org/issue32911

   (8) https://bugs.python.org/issue29463

   (9) https://bugs.python.org/issue21983


File: python.info,  Node: 库<32>,  Next: 文档<27>,  Prev: 核心与内置<31>,  Up: Python 3 7 0 beta 5

1.18.33.2 库
............

   - bpo-32751(1): When cancelling the task due to a timeout, *note
     asyncio.wait_for(): 289. will now wait until the cancellation is
     complete.

   - bpo-32684(2): Fix gather to propagate cancellation of itself even
     with return_exceptions.

   - bpo-33654(3): Support protocol type switching in
     SSLTransport.set_protocol().

   - bpo-33674(4): Pause the transport as early as possible to further
     reduce the risk of data_received() being called before
     connection_made().

   - bpo-33674(5): Fix a race condition in SSLProtocol.connection_made()
     of asyncio.sslproto: start immediately the handshake instead of
     using call_soon().  Previously, data_received() could be called
     before the handshake started, causing the handshake to hang or
     fail.

   - bpo-31647(6): Fixed bug where calling write_eof() on a
     _SelectorSocketTransport after it’s already closed raises
     AttributeError.

   - bpo-32610(7): Make asyncio.all_tasks() return only pending tasks.

   - bpo-32410(8): Avoid blocking on file IO in sendfile fallback code

   - bpo-33469(9): Fix RuntimeError after closing loop that used
     run_in_executor

   - bpo-33672(10): Fix Task.__repr__ crash with Cython’s bogus
     coroutines

   - bpo-33654(11): Fix transport.set_protocol() to support switching
     between asyncio.Protocol and asyncio.BufferedProtocol.  Fix
     loop.start_tls() to work with asyncio.BufferedProtocols.

   - bpo-33652(12): Pickles of type variables and subscripted generics
     are now future-proof and compatible with older Python versions.

   - bpo-32493(13): Fixed *note uuid.uuid1(): 41b. on FreeBSD.

   - bpo-33618(14): Finalize and document preliminary and experimental
     TLS 1.3 support with OpenSSL 1.1.1

   - bpo-33623(15): Fix possible SIGSGV when asyncio.Future is created
     in __del__

   - bpo-30877(16): Fixed a bug in the Python implementation of the JSON
     decoder that prevented the cache of parsed strings from clearing
     after finishing the decoding.  Based on patch by c-fos.

   - bpo-33570(17): Change TLS 1.3 cipher suite settings for
     compatibility with OpenSSL 1.1.1-pre6 and newer.  OpenSSL 1.1.1
     will have TLS 1.3 ciphers enabled by default.

   - bpo-28556(18): Do not simplify arguments to *note typing.Union:
     1044.  Now ‘Union[Manager, Employee]’ is not simplified to
     ‘Employee’ at runtime.  Such simplification previously caused
     several bugs and limited possibilities for introspection.

   - bpo-33540(19): Add a new ‘block_on_close’ class attribute to
     ‘ForkingMixIn’ and ‘ThreadingMixIn’ classes of *note socketserver:
     f1.

   - bpo-33548(20): tempfile._candidate_tempdir_list should consider
     common TEMP locations

   - bpo-33109(21): argparse subparsers are once again not required by
     default, reverting the change in behavior introduced by
     bpo-26510(22) in 3.7.0a2.

   - bpo-33536(23): dataclasses.make_dataclass now checks for invalid
     field names and duplicate fields.  Also, added a check for invalid
     field specifications.

   - bpo-33542(24): Prevent ‘uuid.get_node’ from using a DUID instead of
     a MAC on Windows.  Patch by Zvi Effron

   - bpo-26819(25): Fix race condition with
     ‘ReadTransport.resume_reading’ in Windows proactor event loop.

   - Fix failure in *note typing.get_type_hints(): 313. when ClassVar
     was provided as a string forward reference.

   - bpo-33505(26): Optimize asyncio.ensure_future() by reordering if
     checks: 1.17x faster.

   - bpo-33497(27): Add errors param to cgi.parse_multipart and make an
     encoding in FieldStorage use the given errors (needed for Twisted).
     Patch by Amber Brown.

   - bpo-33495(28): Change dataclasses.Fields repr to use the repr of
     each of its members, instead of str.  This makes it more clear what
     each field actually represents.  This is especially true for the
     ’type’ member.

   - bpo-33453(29): Fix dataclasses to work if using literal string type
     annotations or if using PEP 563 "Postponed Evaluation of
     Annotations".  Only specific string prefixes are detected for both
     ClassVar ("ClassVar" and "typing.ClassVar") and InitVar ("InitVar"
     and "dataclasses.InitVar").

   - bpo-28556(30): Minor fixes in typing module: add annotations to
     ‘NamedTuple.__new__’, pass ‘*args’ and ‘**kwds’ in
     ‘Generic.__new__’.  Original PRs by Paulius Šarka and Chad
     Dombrova.

   - bpo-20087(31): Updated alias mapping with glibc 2.27 supported
     locales.

   - bpo-33422(32): Fix trailing quotation marks getting deleted when
     looking up byte/string literals on pydoc.  Patch by Andrés Delfino.

   - bpo-28167(33): The function ‘platform.linux_distribution’ and
     ‘platform.dist’ now trigger a ‘DeprecationWarning’ and have been
     marked for removal in Python 3.8

   - bpo-33197(34): Update error message when constructing invalid
     inspect.Parameters Patch by Dong-hee Na.

   - bpo-33263(35): Fix FD leak in ‘_SelectorSocketTransport’ Patch by
     Vlad Starostin.

   - bpo-32861(36): The urllib.robotparser’s ‘__str__’ representation
     now includes wildcard entries and the "Crawl-delay" and
     "Request-rate" fields.  Patch by Michael Lazar.

   - bpo-32257(37): The ssl module now contains OP_NO_RENEGOTIATION
     constant, available with OpenSSL 1.1.0h or 1.1.1.

   - bpo-16865(38): Support arrays >=2GiB in *note ctypes: 2b.  Patch by
     Segev Finer.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32751

   (2) https://bugs.python.org/issue32684

   (3) https://bugs.python.org/issue33654

   (4) https://bugs.python.org/issue33674

   (5) https://bugs.python.org/issue33674

   (6) https://bugs.python.org/issue31647

   (7) https://bugs.python.org/issue32610

   (8) https://bugs.python.org/issue32410

   (9) https://bugs.python.org/issue33469

   (10) https://bugs.python.org/issue33672

   (11) https://bugs.python.org/issue33654

   (12) https://bugs.python.org/issue33652

   (13) https://bugs.python.org/issue32493

   (14) https://bugs.python.org/issue33618

   (15) https://bugs.python.org/issue33623

   (16) https://bugs.python.org/issue30877

   (17) https://bugs.python.org/issue33570

   (18) https://bugs.python.org/issue28556

   (19) https://bugs.python.org/issue33540

   (20) https://bugs.python.org/issue33548

   (21) https://bugs.python.org/issue33109

   (22) https://bugs.python.org/issue26510

   (23) https://bugs.python.org/issue33536

   (24) https://bugs.python.org/issue33542

   (25) https://bugs.python.org/issue26819

   (26) https://bugs.python.org/issue33505

   (27) https://bugs.python.org/issue33497

   (28) https://bugs.python.org/issue33495

   (29) https://bugs.python.org/issue33453

   (30) https://bugs.python.org/issue28556

   (31) https://bugs.python.org/issue20087

   (32) https://bugs.python.org/issue33422

   (33) https://bugs.python.org/issue28167

   (34) https://bugs.python.org/issue33197

   (35) https://bugs.python.org/issue33263

   (36) https://bugs.python.org/issue32861

   (37) https://bugs.python.org/issue32257

   (38) https://bugs.python.org/issue16865


File: python.info,  Node: 文档<27>,  Next: 测试<21>,  Prev: 库<32>,  Up: Python 3 7 0 beta 5

1.18.33.3 文档
..............

   - bpo-23859(1): Document that *note asyncio.wait(): 28a. does not
     cancel its futures on timeout.

   - bpo-32436(2): Document PEP 567(3) changes to asyncio.

   - bpo-33604(4): 更新HMAC md5默认报告DeprecationWarning，并将在3.8移除
     。

   - bpo-33503(5): 修复错误的pypi链接

   - bpo-33421(6): 为‘‘typing.AsyncContextManager‘‘添加缺失的文档。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23859

   (2) https://bugs.python.org/issue32436

   (3) https://www.python.org/dev/peps/pep-0567

   (4) https://bugs.python.org/issue33604

   (5) https://bugs.python.org/issue33503

   (6) https://bugs.python.org/issue33421


File: python.info,  Node: 测试<21>,  Next: 构建<19>,  Prev: 文档<27>,  Up: Python 3 7 0 beta 5

1.18.33.4 测试
..............

   - bpo-33655(1): 忽略运行在BSD平台的ZFS上时test_posix_fallocate的失败
     。

   - bpo-32604(2): 删除_xxsubinterpreters模块（用于测试）和相关的帮助程
     序。该模块最初最初是在3.7b1中添加的。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33655

   (2) https://bugs.python.org/issue32604


File: python.info,  Node: 构建<19>,  Next: macOS<17>,  Prev: 测试<21>,  Up: Python 3 7 0 beta 5

1.18.33.5 构建
..............

   - bpo-33614(1): Ensures module definition files for the stable ABI on
     Windows are correctly regenerated.

   - bpo-33522(2): Enable CI builds on Visual Studio Team Services at
     ‘https://python.visualstudio.com/cpython’

   - bpo-33012(3): Add ‘-Wno-cast-function-type’ for gcc 8 for silencing
     warnings about function casts like casting to PyCFunction in method
     definition lists.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33614

   (2) https://bugs.python.org/issue33522

   (3) https://bugs.python.org/issue33012


File: python.info,  Node: macOS<17>,  Next: IDLE<29>,  Prev: 构建<19>,  Up: Python 3 7 0 beta 5

1.18.33.6 macOS
...............

   - bpo-13631(1): The .editrc file in user’s home directory is now
     processed correctly during the readline initialization through
     editline emulation on macOS.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13631


File: python.info,  Node: IDLE<29>,  Prev: macOS<17>,  Up: Python 3 7 0 beta 5

1.18.33.7 IDLE
..............

   - bpo-33628(1): IDLE: Cleanup codecontext.py and its test.

   - bpo-33564(2): IDLE’s code context now recognizes async as a block
     opener.

   - bpo-32831(3): Add docstrings and tests for codecontext.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33628

   (2) https://bugs.python.org/issue33564

   (3) https://bugs.python.org/issue32831


File: python.info,  Node: Python 3 7 0 beta 4,  Next: Python 3 7 0 beta 3,  Prev: Python 3 7 0 beta 5,  Up: 更新日志

1.18.34 Python 3.7.0 beta 4
---------------------------

`发布日期: 2018-05-02'

* Menu:

* 核心与内置: 核心与内置<32>.
* 库: 库<33>.
* 文档: 文档<28>.
* 测试: 测试<22>.
* 构建: 构建<20>.
* Windows: Windows<24>.
* macOS: macOS<18>.
* IDLE: IDLE<30>.
* 工具/示例: 工具/示例<13>.


File: python.info,  Node: 核心与内置<32>,  Next: 库<33>,  Up: Python 3 7 0 beta 4

1.18.34.1 核心与内置
....................

   - bpo-33363(1): 在异步函数外使用‘‘async with‘‘ 和 ‘async for’ 时抛出
     SyntaxError异常。

   - bpo-33128(2): 修复导致PathFinder在sys.meta_path上出现两次的错误。由
     Pablo Galindo Salgado提供补丁。

   - bpo-33312(3): Fixed clang ubsan (undefined behavior sanitizer)
     warnings in dictobject.c by adjusting how the internal struct
     _dictkeysobject shared keys structure is declared.

   - bpo-33231(4): 修复 ‘normalizestring()’ 中潜在的内存泄漏。

   - bpo-33205(5): Change dict growth function from
     ‘round_up_to_power_2(used*2+hashtable_size/2)’ to
     ‘round_up_to_power_2(used*3)’.  Previously, dict is shrinked only
     when ‘used == 0’.  Now dict has more chance to be shrinked.

   - bpo-29922(6): Improved error messages in ’async with’ when
     ‘__aenter__()’ or ‘__aexit__()’ return non-awaitable object.

   - bpo-33199(7): Fix ‘ma_version_tag’ in dict implementation is
     uninitialized when copying from key-sharing dict.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33363

   (2) https://bugs.python.org/issue33128

   (3) https://bugs.python.org/issue33312

   (4) https://bugs.python.org/issue33231

   (5) https://bugs.python.org/issue33205

   (6) https://bugs.python.org/issue29922

   (7) https://bugs.python.org/issue33199


File: python.info,  Node: 库<33>,  Next: 文档<28>,  Prev: 核心与内置<32>,  Up: Python 3 7 0 beta 4

1.18.34.2 库
............

   - bpo-33281(1): Fix ctypes.util.find_library regression on macOS.

   - bpo-33383(2): Fixed crash in the get() method of the *note
     dbm.ndbm: 35. database object when it is called with a single
     argument.

   - bpo-33329(3): Fix multiprocessing regression on newer glibcs

   - bpo-991266(4): Fix quoting of the ‘Comment’ attribute of *note
     http.cookies.SimpleCookie: 1048.

   - bpo-33131(5): Upgrade bundled version of pip to 10.0.1.

   - bpo-33308(6): Fixed a crash in the *note parser: c8. module when
     converting an ST object to a tree of tuples or lists with
     ‘line_info=False’ and ‘col_info=True’.

   - bpo-33266(7): lib2to3 now recognizes ‘rf'...'’ strings.

   - bpo-11594(8): Ensure line-endings are respected when using lib2to3.

   - bpo-33254(9): Have *note importlib.resources.contents(): 1049. and
     *note importlib.abc.ResourceReader.contents(): 104a. return an
     *note iterable: bb4. instead of an *note iterator: 104b.

   - bpo-33256(10): Fix display of ‘<module>’ call in the html produced
     by ‘cgitb.html()’.  Patch by Stéphane Blondon.

   - bpo-33185(11): Fixed regression when running pydoc with the *note
     -m: 340. switch.  (The regression was introduced in 3.7.0b3 by the
     resolution of bpo-33053(12)) This fix also changed pydoc to add
     ‘os.getcwd()’ to *note sys.path: 490. when necessary, rather than
     adding ‘"."’.

   - bpo-33169(13): Delete entries of ‘None’ in *note
     sys.path_importer_cache: 4a5. when
     ‘importlib.machinery.invalidate_caches()’ is called.

   - bpo-33217(14): Deprecate looking up non-Enum objects in Enum
     classes and Enum members (will raise *note TypeError: 193. in
     3.8+).

   - bpo-33203(15): ‘random.Random.choice()’ now raises ‘IndexError’ for
     empty sequences consistently even when called from subclasses
     without a ‘getrandbits()’ implementation.

   - bpo-33224(16): Update difflib.mdiff() for PEP 479(17).  Convert an
     uncaught StopIteration in a generator into a return-statement.

   - bpo-33209(18): End framing at the end of C implementation of *note
     pickle.Pickler.dump(): 104c.

   - bpo-20104(19): Improved error handling and fixed a reference leak
     in *note os.posix_spawn(): 258.

   - bpo-33175(20): In dataclasses, Field.__set_name__ now looks up the
     __set_name__ special method on the class, not the instance, of the
     default value.

   - bpo-33097(21): Raise RuntimeError when ‘executor.submit’ is called
     during interpreter shutdown.

   - bpo-31908(22): Fix output of cover files for ‘trace’ module
     command-line tool.  Previously emitted cover files only when
     ‘--missing’ option was used.  Patch by Michael Selik.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33281

   (2) https://bugs.python.org/issue33383

   (3) https://bugs.python.org/issue33329

   (4) https://bugs.python.org/issue991266

   (5) https://bugs.python.org/issue33131

   (6) https://bugs.python.org/issue33308

   (7) https://bugs.python.org/issue33266

   (8) https://bugs.python.org/issue11594

   (9) https://bugs.python.org/issue33254

   (10) https://bugs.python.org/issue33256

   (11) https://bugs.python.org/issue33185

   (12) https://bugs.python.org/issue33053

   (13) https://bugs.python.org/issue33169

   (14) https://bugs.python.org/issue33217

   (15) https://bugs.python.org/issue33203

   (16) https://bugs.python.org/issue33224

   (17) https://www.python.org/dev/peps/pep-0479

   (18) https://bugs.python.org/issue33209

   (19) https://bugs.python.org/issue20104

   (20) https://bugs.python.org/issue33175

   (21) https://bugs.python.org/issue33097

   (22) https://bugs.python.org/issue31908


File: python.info,  Node: 文档<28>,  Next: 测试<22>,  Prev: 库<33>,  Up: Python 3 7 0 beta 4

1.18.34.3 文档
..............

   - bpo-33378(1): Add Korean language switcher for
     ‘https://docs.python.org/3/’

   - bpo-33276(2): Clarify that the ‘__path__’ attribute on modules
     cannot be just any value.

   - bpo-33201(3): Modernize documentation for writing C extension
     types.

   - bpo-33195(4): Deprecate ‘Py_UNICODE’ usage in ‘c-api/arg’ document.
     ‘Py_UNICODE’ related APIs are deprecated since Python 3.3, but it
     is missed in the document.

   - bpo-8243(5): Add a note about curses.addch and curses.addstr
     exception behavior when writing outside a window, or pad.

   - bpo-32337(6): Update documentation related with ‘dict’ order.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33378

   (2) https://bugs.python.org/issue33276

   (3) https://bugs.python.org/issue33201

   (4) https://bugs.python.org/issue33195

   (5) https://bugs.python.org/issue8243

   (6) https://bugs.python.org/issue32337


File: python.info,  Node: 测试<22>,  Next: 构建<20>,  Prev: 文档<28>,  Up: Python 3 7 0 beta 4

1.18.34.4 测试
..............

   - bpo-33358(1): Fix
     ‘test_embed.test_pre_initialization_sys_options()’ when the
     interpreter is built with ‘--enable-shared’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33358


File: python.info,  Node: 构建<20>,  Next: Windows<24>,  Prev: 测试<22>,  Up: Python 3 7 0 beta 4

1.18.34.5 构建
..............

   - bpo-33394(1): Enable the verbose build for extension modules, when
     GNU make is passed macros on the command line.

   - bpo-33393(2): Update config.guess and config.sub files.

   - bpo-33377(3): Add new triplets for mips r6 and riscv variants (used
     in extension suffixes).

   - bpo-32232(4): By default, modules configured in ‘Modules/Setup’ are
     no longer built with ‘-DPy_BUILD_CORE’.  Instead, modules that
     specifically need that preprocessor definition include it in their
     individual entries.

   - bpo-33182(5): The embedding tests can once again be built with
     clang 6.0

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33394

   (2) https://bugs.python.org/issue33393

   (3) https://bugs.python.org/issue33377

   (4) https://bugs.python.org/issue32232

   (5) https://bugs.python.org/issue33182


File: python.info,  Node: Windows<24>,  Next: macOS<18>,  Prev: 构建<20>,  Up: Python 3 7 0 beta 4

1.18.34.6 Windows
.................

   - bpo-33184(1): 在Windows安装程序中将OpenSSL更新为1.1.0h.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33184


File: python.info,  Node: macOS<18>,  Next: IDLE<30>,  Prev: Windows<24>,  Up: Python 3 7 0 beta 4

1.18.34.7 macOS
...............

   - bpo-33184(1): 在MacOS安装程序中将OpenSSL更新为1.1.0h。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33184


File: python.info,  Node: IDLE<30>,  Next: 工具/示例<13>,  Prev: macOS<18>,  Up: Python 3 7 0 beta 4

1.18.34.8 IDLE
..............

   - bpo-21474(1): Update word/identifier definition from ascii to
     unicode.  In text and entry boxes, this affects selection by
     double-click, movement left/right by control-left/right, and
     deletion left/right by control-BACKSPACE/DEL.

   - bpo-33204(2): IDLE: consistently color invalid string prefixes.  A
     ’u’ string prefix cannot be paired with either ’r’ or ’f’.
     Consistently color as much of the prefix, starting at the right, as
     is valid.  Revise and extend colorizer test.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21474

   (2) https://bugs.python.org/issue33204


File: python.info,  Node: 工具/示例<13>,  Prev: IDLE<30>,  Up: Python 3 7 0 beta 4

1.18.34.9 工具/示例
...................

   - bpo-33189(1): ‘pygettext.py’ now recognizes only literal strings as
     docstrings and translatable strings, and rejects bytes literals and
     f-string expressions.

   - bpo-31920(2): Fixed handling directories as arguments in the
     ‘pygettext’ script.  Based on patch by Oleg Krasnikov.

   - bpo-29673(3): Fix pystackv and pystack gdbinit macros.

   - bpo-31583(4): Fix 2to3 for using with –add-suffix option but
     without –output-dir option for relative path to files in current
     directory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33189

   (2) https://bugs.python.org/issue31920

   (3) https://bugs.python.org/issue29673

   (4) https://bugs.python.org/issue31583


File: python.info,  Node: Python 3 7 0 beta 3,  Next: Python 3 7 0 beta 2,  Prev: Python 3 7 0 beta 4,  Up: 更新日志

1.18.35 Python 3.7.0 beta 3
---------------------------

`发布日期: 2018-03-29'

* Menu:

* 安全: 安全<22>.
* 核心与内置: 核心与内置<33>.
* 库: 库<34>.
* 文档: 文档<29>.
* 测试: 测试<23>.
* 构建: 构建<21>.
* Windows: Windows<25>.
* macOS: macOS<19>.
* IDLE: IDLE<31>.
* 工具/示例: 工具/示例<14>.
* C API: C API<17>.


File: python.info,  Node: 安全<22>,  Next: 核心与内置<33>,  Up: Python 3 7 0 beta 3

1.18.35.1 安全
..............

   - bpo-33136(1): Harden ssl module against LibreSSL CVE-2018-8970.
     X509_VERIFY_PARAM_set1_host() is called with an explicit namelen.
     A new test ensures that NULL bytes are not allowed.

   - bpo-33001(2): Minimal fix to prevent buffer overrun in os.symlink
     on Windows

   - bpo-32981(3): Regexes in difflib and poplib were vulnerable to
     catastrophic backtracking.  These regexes formed potential DOS
     vectors (REDOS). They have been refactored.  This resolves
     CVE-2018-1060 and CVE-2018-1061.  Patch by Jamie Davis.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33136

   (2) https://bugs.python.org/issue33001

   (3) https://bugs.python.org/issue32981


File: python.info,  Node: 核心与内置<33>,  Next: 库<34>,  Prev: 安全<22>,  Up: Python 3 7 0 beta 3

1.18.35.2 核心与内置
....................

   - bpo-33053(1): When using the -m switch, sys.path[0] is now
     explicitly expanded as the `starting' working directory, rather
     than being left as the empty path (which allows imports from the
     current working directory at the time of the import)

   - bpo-33018(2): Improve consistency of errors raised by
     ‘issubclass()’ when called with a non-class and an abstract base
     class as the first and second arguments, respectively.  Patch by
     Josh Bronson.

   - bpo-33041(3): Fixed jumping when the function contains an ‘async
     for’ loop.

   - bpo-33026(4): Fixed jumping out of "with" block by setting
     f_lineno.

   - bpo-33005(5): Fix a crash on fork when using a custom memory
     allocator (ex: using PYTHONMALLOC env var).  _PyGILState_Reinit()
     and _PyInterpreterState_Enable() now use the default RAW memory
     allocator to allocate a new interpreters mutex on fork.

   - bpo-17288(6): Prevent jumps from ’return’ and ’exception’ trace
     events.

   - bpo-32836(7): Don’t use temporary variables in cases of
     list/dict/set comprehensions

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33053

   (2) https://bugs.python.org/issue33018

   (3) https://bugs.python.org/issue33041

   (4) https://bugs.python.org/issue33026

   (5) https://bugs.python.org/issue33005

   (6) https://bugs.python.org/issue17288

   (7) https://bugs.python.org/issue32836


File: python.info,  Node: 库<34>,  Next: 文档<29>,  Prev: 核心与内置<33>,  Up: Python 3 7 0 beta 3

1.18.35.3 库
............

   - bpo-33141(1): Have Field objects pass through __set_name__ to their
     default values, if they have their own __set_name__.

   - bpo-33096(2): Allow ttk.Treeview.insert to insert iid that has a
     false boolean value.  Note iid=0 and iid=False would be same.
     Patch by Garvit Khatri.

   - bpo-32873(3): Treat type variables and special typing forms as
     immutable by copy and pickle.  This fixes several minor issues and
     inconsistencies, and improves backwards compatibility with Python
     3.6.

   - bpo-33134(4): When computing dataclass’s __hash__, use the lookup
     table to contain the function which returns the __hash__ value.
     This is an improvement over looking up a string, and then testing
     that string to see what to do.

   - bpo-33127(5): ssl模块现在使用LibreSSL 2.7.1编译。

   - bpo-32505(6): 如果数据类的成员变量的类型为Field，但没有类型注解，则
     引发TypeError。

   - bpo-33078(7): 修复在OSX平台因为依赖sem_getvalue而导致的失败。

   - bpo-33116(8): 将’Field’添加到dataclasses.__all__。

   - bpo-32896(9): Fix an error where subclassing a dataclass with a
     field that uses a default_factory would generate an incorrect
     class.

   - bpo-33100(10): Dataclasses: If a field has a default value that’s a
     MemberDescriptorType, then it’s from that field being in __slots__,
     not an actual default value.

   - bpo-32953(11): If a non-dataclass inherits from a frozen dataclass,
     allow attributes to be added to the derived class.  Only attributes
     from the frozen dataclass cannot be assigned to.  Require all
     dataclasses in a hierarchy to be either all frozen or all
     non-frozen.

   - bpo-33061(12): 添加丢失的 ‘NoReturn’ 到typing.py的 ‘__all__’

   - bpo-33078(13): Fix the size handling in multiprocessing.Queue when
     a pickling error occurs.

   - bpo-33064(14): lib2to3 now properly supports trailing commas after
     ‘*args’ and ‘**kwargs’ in function signatures.

   - bpo-33056(15): FIX properly close leaking fds in
     concurrent.futures.ProcessPoolExecutor.

   - bpo-33021(16): Release the GIL during fstat() calls, avoiding hang
     of all threads when calling mmap.mmap(), os.urandom(), and
     random.seed().  Patch by Nir Soffer.

   - bpo-31804(17): Avoid failing in multiprocessing.Process if the
     standard streams are closed or None at exit.

   - bpo-33037(18): Skip sending/receiving data after SSL transport
     closing.

   - bpo-27683(19): Fix a regression in *note ipaddress: a3. that result
     of ‘hosts()’ is empty when the network is constructed by a tuple
     containing an integer mask and only 1 bit left for addresses.

   - bpo-32999(20): Fix C implementation of ‘ABC.__subclasscheck__(cls,
     subclass)’ crashed when ‘subclass’ is not a type object.

   - bpo-33009(21): Fix inspect.signature() for single-parameter
     partialmethods.

   - bpo-32969(22): Expose several missing constants in zlib and fix
     corresponding documentation.

   - bpo-32056(23): Improved exceptions raised for invalid number of
     channels and sample width when read an audio file in modules *note
     aifc: 5, *note wave: 128. and *note sunau: fb.

   - bpo-32844(24): Fix wrong redirection of a low descriptor (0 or 1)
     to stderr in subprocess if another low descriptor is closed.

   - bpo-32857(25): In *note tkinter: 10d, ‘after_cancel(None)’ now
     raises a *note ValueError: 1fc. instead of canceling the first
     scheduled function.  Patch by Cheryl Sabella.

   - bpo-31639(26): http.server now exposes a ThreadedHTTPServer class
     and uses it when the module is run with ‘-m’ to cope with web
     browsers pre-opening sockets.

   - bpo-27645(27): *note sqlite3.Connection: 3e0. now exposes a *note
     backup: 3e1. method, if the underlying SQLite library is at version
     3.6.11 or higher.  Patch by Lele Gaifax.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33141

   (2) https://bugs.python.org/issue33096

   (3) https://bugs.python.org/issue32873

   (4) https://bugs.python.org/issue33134

   (5) https://bugs.python.org/issue33127

   (6) https://bugs.python.org/issue32505

   (7) https://bugs.python.org/issue33078

   (8) https://bugs.python.org/issue33116

   (9) https://bugs.python.org/issue32896

   (10) https://bugs.python.org/issue33100

   (11) https://bugs.python.org/issue32953

   (12) https://bugs.python.org/issue33061

   (13) https://bugs.python.org/issue33078

   (14) https://bugs.python.org/issue33064

   (15) https://bugs.python.org/issue33056

   (16) https://bugs.python.org/issue33021

   (17) https://bugs.python.org/issue31804

   (18) https://bugs.python.org/issue33037

   (19) https://bugs.python.org/issue27683

   (20) https://bugs.python.org/issue32999

   (21) https://bugs.python.org/issue33009

   (22) https://bugs.python.org/issue32969

   (23) https://bugs.python.org/issue32056

   (24) https://bugs.python.org/issue32844

   (25) https://bugs.python.org/issue32857

   (26) https://bugs.python.org/issue31639

   (27) https://bugs.python.org/issue27645


File: python.info,  Node: 文档<29>,  Next: 测试<23>,  Prev: 库<34>,  Up: Python 3 7 0 beta 3

1.18.35.4 文档
..............

   - bpo-33126(1): Document PyBuffer_ToContiguous().

   - bpo-27212(2): Modify documentation for the ‘islice()’ recipe to
     consume initial values up to the start index.

   - bpo-28247(3): Update *note zipapp: 142. documentation to describe
     how to make standalone applications.

   - bpo-18802(4): Documentation changes for ipaddress.  Patch by Jon
     Foster and Berker Peksag.

   - bpo-27428(5): Update documentation to clarify that
     ‘WindowsRegistryFinder’ implements ‘MetaPathFinder’.  (Patch by
     Himanshu Lakhara)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33126

   (2) https://bugs.python.org/issue27212

   (3) https://bugs.python.org/issue28247

   (4) https://bugs.python.org/issue18802

   (5) https://bugs.python.org/issue27428


File: python.info,  Node: 测试<23>,  Next: 构建<21>,  Prev: 文档<29>,  Up: Python 3 7 0 beta 3

1.18.35.5 测试
..............

   - bpo-32872(1): Avoid regrtest compatibility issue with namespace
     packages.

   - bpo-32517(2): Fix failing ‘test_asyncio’ on macOS 10.12.2+ due to
     transport of ‘KqueueSelector’ loop was not being closed.

   - bpo-19417(3): Add test_bdb.py.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32872

   (2) https://bugs.python.org/issue32517

   (3) https://bugs.python.org/issue19417


File: python.info,  Node: 构建<21>,  Next: Windows<25>,  Prev: 测试<23>,  Up: Python 3 7 0 beta 3

1.18.35.6 构建
..............

   - bpo-33163(1): Upgrade pip to 9.0.3 and setuptools to v39.0.1.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33163


File: python.info,  Node: Windows<25>,  Next: macOS<19>,  Prev: 构建<21>,  Up: Python 3 7 0 beta 3

1.18.35.7 Windows
.................

   - bpo-33016(1): Fix potential use of uninitialized memory in
     nt._getfinalpathname

   - bpo-32903(2): Fix a memory leak in os.chdir() on Windows if the
     current directory is set to a UNC path.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33016

   (2) https://bugs.python.org/issue32903


File: python.info,  Node: macOS<19>,  Next: IDLE<31>,  Prev: Windows<25>,  Up: Python 3 7 0 beta 3

1.18.35.8 macOS
...............

   - bpo-32726(1): Build and link with private copy of Tcl/Tk 8.6 for
     the macOS 10.6+ installer.  The 10.9+ installer variant already
     does this.  This means that the Python 3.7 provided by the
     python.org macOS installers no longer need or use any external
     versions of Tcl/Tk, either system-provided or user-installed, such
     as ActiveTcl.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32726


File: python.info,  Node: IDLE<31>,  Next: 工具/示例<14>,  Prev: macOS<19>,  Up: Python 3 7 0 beta 3

1.18.35.9 IDLE
..............

   - bpo-32984(1): Set ‘__file__’ while running a startup file.  Like
     Python, IDLE optionally runs one startup file in the Shell window
     before presenting the first interactive input prompt.  For IDLE,
     ‘-s’ runs a file named in environmental variable ‘IDLESTARTUP’ or
     *note PYTHONSTARTUP: 8ed.; ‘-r file’ runs ‘file’.  Python sets
     ‘__file__’ to the startup file name before running the file and
     unsets it before the first prompt.  IDLE now does the same when run
     normally, without the ‘-n’ option.

   - bpo-32940(2): Simplify and rename StringTranslatePseudoMapping in
     pyparse.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32984

   (2) https://bugs.python.org/issue32940


File: python.info,  Node: 工具/示例<14>,  Next: C API<17>,  Prev: IDLE<31>,  Up: Python 3 7 0 beta 3

1.18.35.10 工具/示例
....................

   - bpo-32885(1): Add an ‘-n’ flag for ‘Tools/scripts/pathfix.py’ to
     disable automatic backup creation (files with ‘~’ suffix).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32885


File: python.info,  Node: C API<17>,  Prev: 工具/示例<14>,  Up: Python 3 7 0 beta 3

1.18.35.11 C API
................

   - bpo-33042(1): Embedding applications may once again call
     PySys_ResetWarnOptions, PySys_AddWarnOption, and PySys_AddXOption
     prior to calling Py_Initialize.

   - bpo-32374(2): Document that m_traverse for multi-phase initialized
     modules can be called with m_state=NULL, and add a sanity check

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33042

   (2) https://bugs.python.org/issue32374


File: python.info,  Node: Python 3 7 0 beta 2,  Next: Python 3 7 0 beta 1,  Prev: Python 3 7 0 beta 3,  Up: 更新日志

1.18.36 Python 3.7.0 beta 2
---------------------------

`发布日期: 2018-02-27'

* Menu:

* 安全: 安全<23>.
* 核心与内置: 核心与内置<34>.
* 库: 库<35>.
* 文档: 文档<30>.
* 测试: 测试<24>.
* 构建: 构建<22>.
* Windows: Windows<26>.
* macOS: macOS<20>.
* IDLE: IDLE<32>.
* 工具/示例: 工具/示例<15>.


File: python.info,  Node: 安全<23>,  Next: 核心与内置<34>,  Up: Python 3 7 0 beta 2

1.18.36.1 安全
..............

   - bpo-28414(1): The ssl module now allows users to perform their own
     IDN en/decoding when using SNI.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28414


File: python.info,  Node: 核心与内置<34>,  Next: 库<35>,  Prev: 安全<23>,  Up: Python 3 7 0 beta 2

1.18.36.2 核心与内置
....................

   - bpo-32889(1): Update Valgrind suppression list to account for the
     rename of ‘Py_ADDRESS_IN_RANG’ to ‘address_in_range’.

   - bpo-31356(2): Remove the new API added in bpo-31356(3)
     (gc.ensure_disabled() context manager).

   - bpo-32305(4): For namespace packages, ensure that both ‘__file__’
     and ‘__spec__.origin’ are set to None.

   - bpo-32303(5): Make sure ‘__spec__.loader’ matches ‘__loader__’ for
     namespace packages.

   - bpo-32711(6): Fix the warning messages for Python/ast_unparse.c.
     Patch by Stéphane Wirtel

   - bpo-32583(7): Fix possible crashing in builtin Unicode decoders
     caused by write out-of-bound errors when using customized decode
     error handlers.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32889

   (2) https://bugs.python.org/issue31356

   (3) https://bugs.python.org/issue31356

   (4) https://bugs.python.org/issue32305

   (5) https://bugs.python.org/issue32303

   (6) https://bugs.python.org/issue32711

   (7) https://bugs.python.org/issue32583


File: python.info,  Node: 库<35>,  Next: 文档<30>,  Prev: 核心与内置<34>,  Up: Python 3 7 0 beta 2

1.18.36.3 库
............

   - bpo-32960(1): For dataclasses, disallow inheriting frozen from
     non-frozen classes, and also disallow inheriting non-frozen from
     frozen classes.  This restriction will be relaxed at a future date.

   - bpo-32713(2): Fixed tarfile.itn handling of out-of-bounds float
     values.  Patch by Joffrey Fuhrer.

   - bpo-32951(3): Direct instantiation of SSLSocket and SSLObject
     objects is now prohibited.  The constructors were never documented,
     tested, or designed as public constructors.  Users were suppose to
     use ssl.wrap_socket() or SSLContext.

   - bpo-32929(4): Remove the tri-state parameter "hash", and add the
     boolean "unsafe_hash".  If unsafe_hash is True, add a __hash__
     function, but if a __hash__ exists, raise TypeError.  If
     unsafe_hash is False, add a __hash__ based on the values of eq= and
     frozen=.  The unsafe_hash=False behavior is the same as the old
     hash=None behavior.  unsafe_hash=False is the default, just as
     hash=None used to be.

   - bpo-32947(5): Add OP_ENABLE_MIDDLEBOX_COMPAT and test workaround
     for TLSv1.3 for future compatibility with OpenSSL 1.1.1.

   - bpo-30622(6): The ssl module now detects missing NPN support in
     LibreSSL.

   - bpo-32922(7): dbm.open() now encodes filename with the filesystem
     encoding rather than default encoding.

   - bpo-32859(8): In ‘os.dup2’, don’t check every call whether the
     ‘dup3’ syscall exists or not.

   - bpo-32556(9): nt._getfinalpathname, nt._getvolumepathname and
     nt._getdiskusage now correctly convert from bytes.

   - bpo-25988(10): Emit a *note DeprecationWarning: 279. when using or
     importing an ABC directly from *note collections: 1e. rather than
     from *note collections.abc: 1f.

   - bpo-21060(11): Rewrite confusing message from setup.py upload from
     "No dist file created in earlier command" to the more helpful "Must
     create and upload files in one command".

   - bpo-32852(12): Make sure sys.argv remains as a list when running
     trace.

   - bpo-31333(13): ‘_abc’ module is added.  It is a speedup module with
     C implementations for various functions and methods in ‘abc’.
     Creating an ABC subclass and calling ‘isinstance’ or ‘issubclass’
     with an ABC subclass are up to 1.5x faster.  In addition, this
     makes Python start-up up to 10% faster.  Note that the new
     implementation hides internal registry and caches, previously
     accessible via private attributes ‘_abc_registry’, ‘_abc_cache’,
     and ‘_abc_negative_cache’.  There are three debugging helper
     methods that can be used instead ‘_dump_registry’,
     ‘_abc_registry_clear’, and ‘_abc_caches_clear’.

   - bpo-32841(14): Fixed *note asyncio.Condition: 28e. issue which
     silently ignored cancellation after notifying and cancelling a
     conditional lock.  Patch by Bar Harel.

   - bpo-32819(15): ssl.match_hostname() has been simplified and no
     longer depends on re and ipaddress module for wildcard and IP
     addresses.  Error reporting for invalid wildcards has been
     improved.

   - bpo-32394(16): socket: Remove
     TCP_FASTOPEN,TCP_KEEPCNT,TCP_KEEPIDLE,TCP_KEEPINTVL flags on older
     version Windows during run-time.

   - bpo-31787(17): Fixed refleaks of ‘__init__()’ methods in various
     modules.  (Contributed by Oren Milman)

   - bpo-30157(18): Fixed guessing quote and delimiter in
     csv.Sniffer.sniff() when only the last field is quoted.  Patch by
     Jake Davis.

   - bpo-32792(19): collections.ChainMap() preserves the order of the
     underlying mappings.

   - bpo-32775(20): *note fnmatch.translate(): 104d. no longer produces
     patterns which contain set operations.  Sets starting with ’[’ or
     containing ’–’, ’&&’, ’~~’ or ’||’ will be interpreted differently
     in regular expressions in future versions.  Currently they emit
     warnings.  fnmatch.translate() now avoids producing patterns
     containing such sets by accident.

   - bpo-32622(21): Implement native fast sendfile for Windows proactor
     event loop.

   - bpo-32777(22): Fix a rare but potential pre-exec child process
     deadlock in subprocess on POSIX systems when marking file
     descriptors inheritable on exec in the child process.  This bug
     appears to have been introduced in 3.4.

   - bpo-32647(23): The ctypes module used to depend on indirect linking
     for dlopen.  The shared extension is now explicitly linked against
     libdl on platforms with dl.

   - bpo-32741(24): Implement ‘asyncio.TimerHandle.when()’ method.

   - bpo-32691(25): Use mod_spec.parent when running modules with pdb

   - bpo-32734(26): Fixed ‘asyncio.Lock()’ safety issue which allowed
     acquiring and locking the same lock multiple times, without it
     being free.  Patch by Bar Harel.

   - bpo-32727(27): Do not include name field in SMTP envelope from
     address.  Patch by Stéphane Wirtel

   - bpo-31453(28): Add TLSVersion constants and
     SSLContext.maximum_version / minimum_version attributes.  The new
     API wraps OpenSSL 1.1
     ‘https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_min_proto_version.html’
     feature.

   - bpo-24334(29): Internal implementation details of ssl module were
     cleaned up.  The SSLSocket has one less layer of indirection.
     Owner and session information are now handled by the SSLSocket and
     SSLObject constructor.  Channel binding implementation has been
     simplified.

   - bpo-31848(30): Fix the error handling in Aifc_read.initfp() when
     the SSND chunk is not found.  Patch by Zackery Spytz.

   - bpo-32585(31): Add Ttk spinbox widget to *note tkinter.ttk: 110.
     Patch by Alan D Moore.

   - bpo-32221(32): Various functions returning tuple containing IPv6
     addresses now omit ‘%scope’ part since the same information is
     already encoded in `scopeid' tuple item.  Especially this speeds up
     ‘socket.recvfrom()’ when it receives multicast packet since useless
     resolving of network interface name is omitted.

   - bpo-30693(33): The TarFile class now recurses directories in a
     reproducible way.

   - bpo-30693(34): The ZipFile class now recurses directories in a
     reproducible way.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32960

   (2) https://bugs.python.org/issue32713

   (3) https://bugs.python.org/issue32951

   (4) https://bugs.python.org/issue32929

   (5) https://bugs.python.org/issue32947

   (6) https://bugs.python.org/issue30622

   (7) https://bugs.python.org/issue32922

   (8) https://bugs.python.org/issue32859

   (9) https://bugs.python.org/issue32556

   (10) https://bugs.python.org/issue25988

   (11) https://bugs.python.org/issue21060

   (12) https://bugs.python.org/issue32852

   (13) https://bugs.python.org/issue31333

   (14) https://bugs.python.org/issue32841

   (15) https://bugs.python.org/issue32819

   (16) https://bugs.python.org/issue32394

   (17) https://bugs.python.org/issue31787

   (18) https://bugs.python.org/issue30157

   (19) https://bugs.python.org/issue32792

   (20) https://bugs.python.org/issue32775

   (21) https://bugs.python.org/issue32622

   (22) https://bugs.python.org/issue32777

   (23) https://bugs.python.org/issue32647

   (24) https://bugs.python.org/issue32741

   (25) https://bugs.python.org/issue32691

   (26) https://bugs.python.org/issue32734

   (27) https://bugs.python.org/issue32727

   (28) https://bugs.python.org/issue31453

   (29) https://bugs.python.org/issue24334

   (30) https://bugs.python.org/issue31848

   (31) https://bugs.python.org/issue32585

   (32) https://bugs.python.org/issue32221

   (33) https://bugs.python.org/issue30693

   (34) https://bugs.python.org/issue30693


File: python.info,  Node: 文档<30>,  Next: 测试<24>,  Prev: 库<35>,  Up: Python 3 7 0 beta 2

1.18.36.4 文档
..............

   - bpo-28124(1): The ssl module function ssl.wrap_socket() has been
     de-emphasized and deprecated in favor of the more secure and
     efficient SSLContext.wrap_socket() method.

   - bpo-17232(2): Clarify docs for -O and -OO. Patch by Terry Reedy.

   - bpo-32436(3): Add documentation for the contextvars module (PEP
     567).

   - bpo-32800(4): Update link to w3c doc for xml default namespaces.

   - bpo-11015(5): Update *note test.support: 107. documentation.

   - bpo-8722(6): Document *note __getattr__(): 323. behavior when
     property ‘get()’ method raises *note AttributeError: 3a3.

   - bpo-32614(7): Modify RE examples in documentation to use raw
     strings to prevent *note DeprecationWarning: 279. and add text to
     REGEX HOWTO to highlight the deprecation.

   - bpo-31972(8): Improve docstrings for *note pathlib.PurePath: 1051.
     subclasses.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28124

   (2) https://bugs.python.org/issue17232

   (3) https://bugs.python.org/issue32436

   (4) https://bugs.python.org/issue32800

   (5) https://bugs.python.org/issue11015

   (6) https://bugs.python.org/issue8722

   (7) https://bugs.python.org/issue32614

   (8) https://bugs.python.org/issue31972


File: python.info,  Node: 测试<24>,  Next: 构建<22>,  Prev: 文档<30>,  Up: Python 3 7 0 beta 2

1.18.36.5 测试
..............

   - bpo-31809(1): Add tests to verify connection with secp ECDH curves.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31809


File: python.info,  Node: 构建<22>,  Next: Windows<26>,  Prev: 测试<24>,  Up: Python 3 7 0 beta 2

1.18.36.6 构建
..............

   - bpo-32898(1): Fix the python debug build when using COUNT_ALLOCS.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32898


File: python.info,  Node: Windows<26>,  Next: macOS<20>,  Prev: 构建<22>,  Up: Python 3 7 0 beta 2

1.18.36.7 Windows
.................

   - bpo-32901(1): Update Tcl and Tk versions to 8.6.8

   - bpo-31966(2): Fixed WindowsConsoleIO.write() for writing empty
     data.

   - bpo-32409(3): Ensures activate.bat can handle Unicode contents.

   - bpo-32457(4): Improves handling of denormalized executable path
     when launching Python.

   - bpo-32370(5): Use the correct encoding for ipconfig output in the
     uuid module.  Patch by Segev Finer.

   - bpo-29248(6): Fix *note os.readlink(): 1f4. on Windows, which was
     mistakenly treating the ‘PrintNameOffset’ field of the reparse data
     buffer as a number of characters instead of bytes.  Patch by Craig
     Holmquist and SSE4.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32901

   (2) https://bugs.python.org/issue31966

   (3) https://bugs.python.org/issue32409

   (4) https://bugs.python.org/issue32457

   (5) https://bugs.python.org/issue32370

   (6) https://bugs.python.org/issue29248


File: python.info,  Node: macOS<20>,  Next: IDLE<32>,  Prev: Windows<26>,  Up: Python 3 7 0 beta 2

1.18.36.8 macOS
...............

   - bpo-32901(1): Update macOS 10.9+ installer to Tcl/Tk 8.6.8.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32901


File: python.info,  Node: IDLE<32>,  Next: 工具/示例<15>,  Prev: macOS<20>,  Up: Python 3 7 0 beta 2

1.18.36.9 IDLE
..............

   - bpo-32916(1): Change ‘str’ to ‘code’ in pyparse.

   - bpo-32905(2): Remove unused code in pyparse module.

   - bpo-32874(3): Add tests for pyparse.

   - bpo-32837(4): Using the system and place-dependent default encoding
     for open() is a bad idea for IDLE’s system and location-independent
     files.

   - bpo-32826(5): Add "encoding=utf-8" to open() in IDLE’s
     test_help_about.  GUI test test_file_buttons() only looks at
     initial ascii-only lines, but failed on systems where open()
     defaults to ’ascii’ because readline() internally reads and decodes
     far enough ahead to encounter a non-ascii character in CREDITS.txt.

   - bpo-32765(6): Update configdialog General tab docstring to add new
     widgets to the widget list.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32916

   (2) https://bugs.python.org/issue32905

   (3) https://bugs.python.org/issue32874

   (4) https://bugs.python.org/issue32837

   (5) https://bugs.python.org/issue32826

   (6) https://bugs.python.org/issue32765


File: python.info,  Node: 工具/示例<15>,  Prev: IDLE<32>,  Up: Python 3 7 0 beta 2

1.18.36.10 工具/示例
....................

   - bpo-32222(1): Fix pygettext not extracting docstrings for functions
     with type annotated arguments.  Patch by Toby Harradine.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32222


File: python.info,  Node: Python 3 7 0 beta 1,  Next: Python 3 7 0 alpha 4,  Prev: Python 3 7 0 beta 2,  Up: 更新日志

1.18.37 Python 3.7.0 beta 1
---------------------------

`发布日期: 2018-01-30'

* Menu:

* 核心与内置: 核心与内置<35>.
* 库: 库<36>.
* 文档: 文档<31>.
* 测试: 测试<25>.
* 构建: 构建<23>.
* Windows: Windows<27>.
* macOS: macOS<21>.
* C API: C API<18>.


File: python.info,  Node: 核心与内置<35>,  Next: 库<36>,  Up: Python 3 7 0 beta 1

1.18.37.1 核心与内置
....................

   - bpo-32703(1): Fix coroutine’s ResourceWarning when there’s an
     active error set when it’s being finalized.

   - bpo-32650(2): Pdb and other debuggers dependent on bdb.py will
     correctly step over (next command) native coroutines.  Patch by
     Pablo Galindo.

   - bpo-28685(3): Optimize list.sort() and sorted() by using type
     specialized comparisons when possible.

   - bpo-32685(4): Improve suggestion when the Python 2 form of print
     statement is either present on the same line as the header of a
     compound statement or else terminated by a semi-colon instead of a
     newline.  Patch by Nitish Chandra.

   - bpo-32697(5): Python now explicitly preserves the definition order
     of keyword-only parameters.  It’s always preserved their order, but
     this behavior was never guaranteed before; this behavior is now
     guaranteed and tested.

   - bpo-32690(6): The locals() dictionary now displays in the lexical
     order that variables were defined.  Previously, the order was
     reversed.

   - bpo-32677(7): Add ‘.isascii()’ method to ‘str’, ‘bytes’ and
     ‘bytearray’.  It can be used to test that string contains only
     ASCII characters.

   - bpo-32670(8): Enforce PEP 479(9) for all code.  This means that
     manually raising a StopIteration exception from a generator is
     prohibited for all code, regardless of whether ’from __future__
     import generator_stop’ was used or not.

   - bpo-32591(10): Added built-in support for tracking the origin of
     coroutine objects; see sys.set_coroutine_origin_tracking_depth and
     CoroutineType.cr_origin.  This replaces the asyncio debug mode’s
     use of coroutine wrapping for native coroutine objects.

   - bpo-31368(11): Expose preadv and pwritev system calls in the os
     module.  Patch by Pablo Galindo

   - bpo-32544(12): ‘hasattr(obj, name)’ and ‘getattr(obj, name,
     default)’ are about 4 times faster than before when ‘name’ is not
     found and ‘obj’ doesn’t override ‘__getattr__’ or
     ‘__getattribute__’.

   - bpo-26163(13): Improved frozenset() hash to create more distinct
     hash values when faced with datasets containing many similar
     values.

   - bpo-32550(14): Remove the STORE_ANNOTATION bytecode.

   - bpo-20104(15): Expose posix_spawn as a low level API in the os
     module.  (removed before 3.7.0rc1)

   - bpo-24340(16): Fixed estimation of the code stack size.

   - bpo-32436(17): Implement PEP 567(18) Context Variables.

   - bpo-18533(19): ‘repr()’ on a dict containing its own ‘values()’ or
     ‘items()’ no longer raises ‘RecursionError’; OrderedDict similarly.
     Instead, use ‘...’, as for other recursive structures.  Patch by
     Ben North.

   - bpo-20891(20): Py_Initialize() now creates the GIL. The GIL is no
     longer created "on demand" to fix a race condition when
     PyGILState_Ensure() is called in a non-Python thread.

   - bpo-32028(21): Leading whitespace is now correctly ignored when
     generating suggestions for converting Py2 print statements to Py3
     builtin print function calls.  Patch by Sanyam Khurana.

   - bpo-31179(22): Make dict.copy() up to 5.5 times faster.

   - bpo-31113(23): Get rid of recursion in the compiler for normal
     control flow.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32703

   (2) https://bugs.python.org/issue32650

   (3) https://bugs.python.org/issue28685

   (4) https://bugs.python.org/issue32685

   (5) https://bugs.python.org/issue32697

   (6) https://bugs.python.org/issue32690

   (7) https://bugs.python.org/issue32677

   (8) https://bugs.python.org/issue32670

   (9) https://www.python.org/dev/peps/pep-0479

   (10) https://bugs.python.org/issue32591

   (11) https://bugs.python.org/issue31368

   (12) https://bugs.python.org/issue32544

   (13) https://bugs.python.org/issue26163

   (14) https://bugs.python.org/issue32550

   (15) https://bugs.python.org/issue20104

   (16) https://bugs.python.org/issue24340

   (17) https://bugs.python.org/issue32436

   (18) https://www.python.org/dev/peps/pep-0567

   (19) https://bugs.python.org/issue18533

   (20) https://bugs.python.org/issue20891

   (21) https://bugs.python.org/issue32028

   (22) https://bugs.python.org/issue31179

   (23) https://bugs.python.org/issue31113


File: python.info,  Node: 库<36>,  Next: 文档<31>,  Prev: 核心与内置<35>,  Up: Python 3 7 0 beta 1

1.18.37.2 库
............

   - bpo-25988(1): Deprecate exposing the contents of collections.abc in
     the regular collections module.

   - bpo-31429(2): The default cipher suite selection of the ssl module
     now uses a blacklist approach rather than a hard-coded whitelist.
     Python no longer re-enables ciphers that have been blocked by
     OpenSSL security update.  Default cipher suite selection can be
     configured on compile time.

   - bpo-30306(3): contextlib.contextmanager now releases the arguments
     passed to the underlying generator as soon as the context manager
     is entered.  Previously it would keep them alive for as long as the
     context manager was alive, even when not being used as a function
     decorator.  Patch by Martin Teichmann.

   - bpo-21417(4): Added support for setting the compression level for
     zipfile.ZipFile.

   - bpo-32251(5): Implement asyncio.BufferedProtocol (provisional API).

   - bpo-32513(6): In dataclasses, allow easier overriding of dunder
     methods without specifying decorator parameters.

   - bpo-32660(7): *note termios: 105. makes available ‘FIONREAD’,
     ‘FIONCLEX’, ‘FIOCLEX’, ‘FIOASYNC’ and ‘FIONBIO’ also under
     Solaris/derivatives.

   - bpo-27931(8): Fix email address header parsing error when the
     username is an empty quoted string.  Patch by Xiang Zhang.

   - bpo-32659(9): Under Solaris and derivatives, *note os.stat_result:
     109a. provides a st_fstype attribute.

   - bpo-32662(10): Implement Server.start_serving(),
     Server.serve_forever(), and Server.is_serving() methods.  Add
     ’start_serving’ keyword parameter to loop.create_server() and
     loop.create_unix_server().

   - bpo-32391(11): Implement *note asyncio.StreamWriter.wait_closed():
     35f. and *note asyncio.StreamWriter.is_closing(): 360. methods

   - bpo-32643(12): Make Task._step, Task._wakeup and
     Future._schedule_callbacks methods private.

   - bpo-32630(13): Refactor decimal module to use contextvars to store
     decimal context.

   - bpo-32622(14): Add ‘asyncio.AbstractEventLoop.sendfile()’ method.

   - bpo-32304(15): distutils’ upload command no longer corrupts tar
     files ending with a CR byte, and no longer tries to convert CR to
     CRLF in any of the upload text fields.

   - bpo-32502(16): uuid.uuid1 no longer raises an exception if a 64-bit
     hardware address is encountered.

   - bpo-32596(17): ‘concurrent.futures’ imports ‘ThreadPoolExecutor’
     and ‘ProcessPoolExecutor’ lazily (using PEP 562(18)).  It makes
     ‘import asyncio’ about 15% faster because asyncio uses only
     ‘ThreadPoolExecutor’ by default.

   - bpo-31801(19): Add ‘_ignore_’ to ‘Enum’ so temporary variables can
     be used during class construction without being turned into
     members.

   - bpo-32576(20): Use queue.SimpleQueue() in places where it can be
     invoked from a weakref callback.

   - bpo-32574(21): Fix memory leak in asyncio.Queue, when the queue has
     limited size and it is full, the cancelation of queue.put() can
     cause a memory leak.  Patch by: José Melero.

   - bpo-32521(22): The nis module is now compatible with new libnsl and
     headers location.

   - bpo-32467(23): collections.abc.ValuesView now inherits from
     collections.abc.Collection.

   - bpo-32473(24): Improve ABCMeta._dump_registry() output readability

   - bpo-32102(25): New argument ‘capture_output’ for subprocess.run

   - bpo-32521(26): glibc has removed Sun RPC. Use replacement libtirpc
     headers and library in nis module.

   - bpo-32493(27): UUID module fixes build for FreeBSD/OpenBSD

   - bpo-32503(28): Pickling with protocol 4 no longer creates too small
     frames.

   - bpo-29237(29): Create enum for pstats sorting options

   - bpo-32454(30): Add close(fd) function to the socket module.

   - bpo-25942(31): The subprocess module is now more graceful when
     handling a Ctrl-C KeyboardInterrupt during subprocess.call,
     subprocess.run, or a Popen context manager.  It now waits a short
     amount of time for the child (presumed to have also gotten the
     SIGINT) to exit, before continuing the KeyboardInterrupt exception
     handling.  This still includes a SIGKILL in the call() and run()
     APIs, but at least the child had a chance first.

   - bpo-32433(32): The hmac module now has hmac.digest(), which
     provides an optimized HMAC digest.

   - bpo-28134(33): Sockets now auto-detect family, type and protocol
     from file descriptor by default.

   - bpo-32404(34): Fix bug where *note
     datetime.datetime.fromtimestamp(): 109b. did not call __new__ in
     *note datetime.datetime: 195. subclasses.

   - bpo-32403(35): Improved speed of *note datetime.date: 194. and
     *note datetime.datetime: 195. alternate constructors.

   - bpo-32228(36): Ensure that ‘truncate()’ preserves the file position
     (as reported by ‘tell()’) after writes longer than the buffer size.

   - bpo-32410(37): Implement ‘loop.sock_sendfile’ for asyncio event
     loop.

   - bpo-22908(38): Added seek and tell to the ZipExtFile class.  This
     only works if the file object used to open the zipfile is seekable.

   - bpo-32373(39): Add socket.getblocking() method.

   - bpo-32248(40): Add *note importlib.resources: 9f. and *note
     importlib.abc.ResourceReader: 34b. as the unified API for reading
     resources contained within packages.  Loaders wishing to support
     resource reading must implement the ‘get_resource_reader()’ method.
     File-based and zipimport-based loaders both implement these APIs.
     *note importlib.abc.ResourceLoader: 46e. is deprecated in favor of
     these new APIs.

   - bpo-32320(41): collections.namedtuple() now supports default
     values.

   - bpo-29302(42): Add contextlib.AsyncExitStack.  Patch by Alexander
     Mohr and Ilya Kulakov.

   - bpo-31961(43): `Removed in Python 3.7.0b2.'  The `args' argument of
     subprocess.Popen can now be a *note path-like object: 373.  If
     `args' is given as a sequence, it’s first element can now be a
     *note path-like object: 373. as well.

   - bpo-31900(44): The *note locale.localeconv(): 492. function now
     sets temporarily the ‘LC_CTYPE’ locale to the ‘LC_NUMERIC’ locale
     to decode ‘decimal_point’ and ‘thousands_sep’ byte strings if they
     are non-ASCII or longer than 1 byte, and the ‘LC_NUMERIC’ locale is
     different than the ‘LC_CTYPE’ locale.  This temporary change
     affects other threads.  Same change for the *note str.format():
     4e2. method when formatting a number (*note int: 185, *note float:
     188, *note float: 188. and subclasses) with the ‘n’ type (ex:
     ‘'{:n}'.format(1234)’).

   - bpo-31853(45): Use super().method instead of socket.method in
     SSLSocket.  They were there most likely for legacy reasons.

   - bpo-31399(46): The ssl module now uses OpenSSL’s
     X509_VERIFY_PARAM_set1_host() and X509_VERIFY_PARAM_set1_ip() API
     to verify hostname and IP addresses.  Subject common name fallback
     can be disabled with SSLContext.hostname_checks_common_name.

   - bpo-14976(47): Add a queue.SimpleQueue class, an unbounded FIFO
     queue with a reentrant C implementation of put().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25988

   (2) https://bugs.python.org/issue31429

   (3) https://bugs.python.org/issue30306

   (4) https://bugs.python.org/issue21417

   (5) https://bugs.python.org/issue32251

   (6) https://bugs.python.org/issue32513

   (7) https://bugs.python.org/issue32660

   (8) https://bugs.python.org/issue27931

   (9) https://bugs.python.org/issue32659

   (10) https://bugs.python.org/issue32662

   (11) https://bugs.python.org/issue32391

   (12) https://bugs.python.org/issue32643

   (13) https://bugs.python.org/issue32630

   (14) https://bugs.python.org/issue32622

   (15) https://bugs.python.org/issue32304

   (16) https://bugs.python.org/issue32502

   (17) https://bugs.python.org/issue32596

   (18) https://www.python.org/dev/peps/pep-0562

   (19) https://bugs.python.org/issue31801

   (20) https://bugs.python.org/issue32576

   (21) https://bugs.python.org/issue32574

   (22) https://bugs.python.org/issue32521

   (23) https://bugs.python.org/issue32467

   (24) https://bugs.python.org/issue32473

   (25) https://bugs.python.org/issue32102

   (26) https://bugs.python.org/issue32521

   (27) https://bugs.python.org/issue32493

   (28) https://bugs.python.org/issue32503

   (29) https://bugs.python.org/issue29237

   (30) https://bugs.python.org/issue32454

   (31) https://bugs.python.org/issue25942

   (32) https://bugs.python.org/issue32433

   (33) https://bugs.python.org/issue28134

   (34) https://bugs.python.org/issue32404

   (35) https://bugs.python.org/issue32403

   (36) https://bugs.python.org/issue32228

   (37) https://bugs.python.org/issue32410

   (38) https://bugs.python.org/issue22908

   (39) https://bugs.python.org/issue32373

   (40) https://bugs.python.org/issue32248

   (41) https://bugs.python.org/issue32320

   (42) https://bugs.python.org/issue29302

   (43) https://bugs.python.org/issue31961

   (44) https://bugs.python.org/issue31900

   (45) https://bugs.python.org/issue31853

   (46) https://bugs.python.org/issue31399

   (47) https://bugs.python.org/issue14976


File: python.info,  Node: 文档<31>,  Next: 测试<25>,  Prev: 库<36>,  Up: Python 3 7 0 beta 1

1.18.37.3 文档
..............

   - bpo-32724(1): Add references to some commands in the documentation
     of Pdb.  Patch by Stéphane Wirtel

   - bpo-32649(2): Complete the C API documentation, profiling and
     tracing part with the newly added per-opcode events.

   - bpo-17799(3): Explain real behaviour of sys.settrace and
     sys.setprofile and their C-API counterparts regarding which type of
     events are received in each function.  Patch by Pablo Galindo
     Salgado.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32724

   (2) https://bugs.python.org/issue32649

   (3) https://bugs.python.org/issue17799


File: python.info,  Node: 测试<25>,  Next: 构建<23>,  Prev: 文档<31>,  Up: Python 3 7 0 beta 1

1.18.37.4 测试
..............

   - bpo-32721(1): Fix test_hashlib to not fail if the _md5 module is
     not built.

   - bpo-28414(2): Add test cases for IDNA 2003 and 2008 host names.
     IDNA 2003 internationalized host names are working since
     bpo-31399(3) has landed.  IDNA 2008 are still broken.

   - bpo-32604(4): Add a new "_xxsubinterpreters" extension module that
     exposes the existing subinterpreter C-API and a new
     cross-interpreter data sharing mechanism.  The module is primarily
     intended for more thorough testing of the existing subinterpreter
     support.  Note that the _xxsubinterpreters module has been removed
     in 3.7.0rc1.

   - bpo-32602(5): Add test certs and test for ECDSA cert and EC/RSA
     dual mode.

   - bpo-32549(6): On Travis CI, Python now Compiles and uses a local
     copy of OpenSSL 1.1.0g for testing.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32721

   (2) https://bugs.python.org/issue28414

   (3) https://bugs.python.org/issue31399

   (4) https://bugs.python.org/issue32604

   (5) https://bugs.python.org/issue32602

   (6) https://bugs.python.org/issue32549


File: python.info,  Node: 构建<23>,  Next: Windows<27>,  Prev: 测试<25>,  Up: Python 3 7 0 beta 1

1.18.37.5 构建
..............

   - bpo-32635(1): Fix segfault of the crypt module when libxcrypt is
     provided instead of libcrypt at the system.

   - bpo-32598(2): Use autoconf to detect OpenSSL libs, headers and
     supported features.  The ax_check_openssl M4 macro uses pkg-config
     to locate OpenSSL and falls back to manual search.

   - bpo-32593(3): 放弃对 FreeBSD 9 及更早版本的支持。

   - bpo-29708(4): If the ‘SOURCE_DATE_EPOCH’ environment variable is
     set, *note py_compile: d8. will always create hash-based ‘.pyc’
     files.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32635

   (2) https://bugs.python.org/issue32598

   (3) https://bugs.python.org/issue32593

   (4) https://bugs.python.org/issue29708


File: python.info,  Node: Windows<27>,  Next: macOS<21>,  Prev: 构建<23>,  Up: Python 3 7 0 beta 1

1.18.37.6 Windows
.................

   - bpo-32588(1): Create standalone _distutils_findvs module and add
     missing _queue module to installer.

   - bpo-29911(2): Ensure separate Modify and Uninstall buttons are
     displayed.

   - bpo-32507(3): Use app-local UCRT install rather than the proper
     update for old versions of Windows.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32588

   (2) https://bugs.python.org/issue29911

   (3) https://bugs.python.org/issue32507


File: python.info,  Node: macOS<21>,  Next: C API<18>,  Prev: Windows<27>,  Up: Python 3 7 0 beta 1

1.18.37.7 macOS
...............

   - bpo-32726(1): Provide an additional, more modern macOS installer
     variant that supports macOS 10.9+ systems in 64-bit mode only.
     Upgrade the supplied third-party libraries to OpenSSL 1.1.0g and to
     SQLite 3.22.0.  The 10.9+ installer now links with and supplies its
     own copy of Tcl/Tk 8.6.

   - bpo-28440(2): No longer add /Library/Python/3.x/site-packages to
     sys.path for macOS framework builds to avoid future conflicts.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32726

   (2) https://bugs.python.org/issue28440


File: python.info,  Node: C API<18>,  Prev: macOS<21>,  Up: Python 3 7 0 beta 1

1.18.37.8 C API
...............

   - bpo-32681(1): Fix uninitialized variable ’res’ in the C
     implementation of os.dup2.  Patch by Stéphane Wirtel

   - bpo-10381(2): Add C API access to the ‘datetime.timezone’
     constructor and ‘datetime.timzone.UTC’ singleton.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32681

   (2) https://bugs.python.org/issue10381


File: python.info,  Node: Python 3 7 0 alpha 4,  Next: Python 3 7 0 alpha 3,  Prev: Python 3 7 0 beta 1,  Up: 更新日志

1.18.38 Python 3.7.0 alpha 4
----------------------------

`发布日期: 2018-01-08'

* Menu:

* 核心与内置: 核心与内置<36>.
* 库: 库<37>.
* 文档: 文档<32>.
* 测试: 测试<26>.
* Windows: Windows<28>.
* 工具/示例: 工具/示例<16>.
* C API: C API<19>.


File: python.info,  Node: 核心与内置<36>,  Next: 库<37>,  Up: Python 3 7 0 alpha 4

1.18.38.1 核心与内置
....................

   - bpo-31975(1): The default warning filter list now starts with a
     "default::DeprecationWarning:__main__" entry, so deprecation
     warnings are once again shown by default in single-file scripts and
     at the interactive prompt.

   - bpo-32226(2): ‘__class_getitem__’ is now an automatic class method.

   - bpo-32399(3): Add AIX uuid library support for RFC4122 using
     uuid_create() in libc.a

   - bpo-32390(4): Fix the compilation failure on AIX after the f_fsid
     field has been added to the object returned by os.statvfs()
     (bpo-32143(5)).  Original patch by Michael Felt.

   - bpo-32379(6): Make MRO computation faster when a class inherits
     from a single base.

   - bpo-32259(7): The error message of a TypeError raised when unpack
     non-iterable is now more specific.

   - bpo-27169(8): The ‘__debug__’ constant is now optimized out at
     compile time.  This fixes also bpo-22091(9).

   - bpo-32329(10): The *note -R: 10a4. option now turns on hash
     randomization when the *note PYTHONHASHSEED: 9cd. environment
     variable is set to ‘0’.  Previously, the option was ignored.
     Moreover, ‘sys.flags.hash_randomization’ is now properly set to 0
     when hash randomization is turned off by ‘PYTHONHASHSEED=0’.

   - bpo-30416(11): The optimizer is now protected from spending much
     time doing complex calculations and consuming much memory for
     creating large constants in constant folding.  Increased limits for
     constants that can be produced in constant folding.

   - bpo-32282(12): Fix an unnecessary ifdef in the include of
     VersionHelpers.h in socketmodule on Windows.

   - bpo-30579(13): Implement TracebackType.__new__ to allow
     Python-level creation of traceback objects, and make
     TracebackType.tb_next mutable.

   - bpo-32260(14): Don’t byte swap the input keys to the SipHash
     algorithm on big-endian platforms.  This should ensure siphash
     gives consistent results across platforms.

   - bpo-31506(15): Improve the error message logic for object.__new__
     and object.__init__.  Patch by Sanyam Khurana.

   - bpo-20361(16): ‘-b’ and ‘-bb’ now inject ‘'default::BytesWarning'’
     and ‘error::BytesWarning’ entries into ‘sys.warnoptions’, ensuring
     that they take precedence over any other warning filters configured
     via the ‘-W’ option or the ‘PYTHONWARNINGS’ environment variable.

   - bpo-32230(17): ‘-X dev’ now injects a ‘'default'’ entry into
     sys.warnoptions, ensuring that it behaves identically to actually
     passing ‘-Wdefault’ at the command line.

   - bpo-29240(18): Add a new UTF-8 mode: implementation of the PEP
     540(19).

   - bpo-32226(20): PEP 560(21): Add support for ‘__mro_entries__’ and
     ‘__class_getitem__’.  Implemented by Ivan Levkivskyi.

   - bpo-32225(22): PEP 562(23): Add support for module ‘__getattr__’
     and ‘__dir__’.  Implemented by Ivan Levkivskyi.

   - bpo-31901(24): The *note atexit: c. module now has its callback
     stored per interpreter.

   - bpo-31650(25): Implement PEP 552(26) (Deterministic pycs).  Python
     now supports invalidating bytecode cache files bashed on a source
     content hash rather than source last-modified time.

   - bpo-29469(27): Move constant folding from bytecode layer to AST
     layer.  Original patch by Eugene Toder.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31975

   (2) https://bugs.python.org/issue32226

   (3) https://bugs.python.org/issue32399

   (4) https://bugs.python.org/issue32390

   (5) https://bugs.python.org/issue32143

   (6) https://bugs.python.org/issue32379

   (7) https://bugs.python.org/issue32259

   (8) https://bugs.python.org/issue27169

   (9) https://bugs.python.org/issue22091

   (10) https://bugs.python.org/issue32329

   (11) https://bugs.python.org/issue30416

   (12) https://bugs.python.org/issue32282

   (13) https://bugs.python.org/issue30579

   (14) https://bugs.python.org/issue32260

   (15) https://bugs.python.org/issue31506

   (16) https://bugs.python.org/issue20361

   (17) https://bugs.python.org/issue32230

   (18) https://bugs.python.org/issue29240

   (19) https://www.python.org/dev/peps/pep-0540

   (20) https://bugs.python.org/issue32226

   (21) https://www.python.org/dev/peps/pep-0560

   (22) https://bugs.python.org/issue32225

   (23) https://www.python.org/dev/peps/pep-0562

   (24) https://bugs.python.org/issue31901

   (25) https://bugs.python.org/issue31650

   (26) https://www.python.org/dev/peps/pep-0552

   (27) https://bugs.python.org/issue29469


File: python.info,  Node: 库<37>,  Next: 文档<32>,  Prev: 核心与内置<36>,  Up: Python 3 7 0 alpha 4

1.18.38.2 库
............

   - bpo-32506(1): Now that dict is defined as keeping insertion order,
     drop OrderedDict and just use plain dict.

   - bpo-32279(2): Add params to dataclasses.make_dataclasses(): init,
     repr, eq, order, hash, and frozen.  Pass them through to
     dataclass().

   - bpo-32278(3): Make type information optional on
     dataclasses.make_dataclass().  If omitted, the string ’typing.Any’
     is used.

   - bpo-32499(4): Add dataclasses.is_dataclass(obj), which returns True
     if obj is a dataclass or an instance of one.

   - bpo-32468(5): Improve frame repr() to mention filename, code name
     and current line number.

   - bpo-23749(6): asyncio: Implement loop.start_tls()

   - bpo-32441(7): Return the new file descriptor (i.e., the second
     argument) from ‘os.dup2’.  Previously, ‘None’ was always returned.

   - bpo-32422(8): ‘functools.lru_cache’ uses less memory (3 words for
     each cached key) and takes about 1/3 time for cyclic GC.

   - bpo-31721(9): Prevent Python crash from happening when
     Future._log_traceback is set to True manually.  Now it can only be
     set to False, or a ValueError is raised.

   - bpo-32415(10): asyncio: Add Task.get_loop() and Future.get_loop()

   - bpo-26133(11): Don’t unsubscribe signals in asyncio UNIX event loop
     on interpreter shutdown.

   - bpo-32363(12): Make asyncio.Task.set_exception() and set_result()
     raise NotImplementedError.  Task._step() and Future.__await__()
     raise proper exceptions when they are in an invalid state, instead
     of raising an AssertionError.

   - bpo-32357(13): Optimize asyncio.iscoroutine() and
     loop.create_task() for non-native coroutines (e.g.  async/await
     compiled with Cython).  ’loop.create_task(python_coroutine)’ used
     to be 20% faster than ’loop.create_task(cython_coroutine)’.  Now,
     the latter is as fast.

   - bpo-32356(14): asyncio.transport.resume_reading() and
     pause_reading() are now idempotent.  New transport.is_reading()
     method is added.

   - bpo-32355(15): Optimize asyncio.gather(); now up to 15% faster.

   - bpo-32351(16): Use fastpath in asyncio.sleep if delay<0 (2x boost)

   - bpo-32348(17): Optimize asyncio.Future schedule/add/remove
     callback.  The optimization shows 3-6% performance improvements of
     async/await code.

   - bpo-32331(18): Fix socket.settimeout() and socket.setblocking() to
     keep socket.type as is.  Fix socket.socket() constructor to reset
     any bit flags applied to socket’s type.  This change only affects
     OSes that have SOCK_NONBLOCK and/or SOCK_CLOEXEC.

   - bpo-32248(19): Add *note importlib.abc.ResourceReader: 34b. as an
     ABC for loaders to provide a unified API for reading resources
     contained within packages.  Also add *note importlib.resources: 9f.
     as the port of ‘importlib_resources’.

   - bpo-32311(20): Implement asyncio.create_task(coro) shortcut

   - bpo-32327(21): Convert asyncio functions that were documented as
     coroutines to coroutines.  Affected functions: loop.sock_sendall,
     loop.sock_recv, loop.sock_accept, loop.getaddrinfo,
     loop.getnameinfo.

   - bpo-32323(22): *note urllib.parse.urlsplit(): 602. does not convert
     zone-id (scope) to lower case for scoped IPv6 addresses in
     hostnames now.

   - bpo-32302(23): Fix bdist_wininst of distutils for CRT v142: it
     binary compatible with CRT v140.

   - bpo-29711(24): Fix ‘stop_serving’ in asyncio proactor loop kill all
     listening servers

   - bpo-32308(25): *note re.sub(): 483. now replaces empty matches
     adjacent to a previous non-empty match.

   - bpo-29970(26): Abort asyncio SSLProtocol connection if handshake
     not complete within 10s

   - bpo-32314(27): Implement asyncio.run().

   - bpo-17852(28): Revert incorrect fix based on misunderstanding of
     _Py_PyAtExit() semantics.

   - bpo-32296(29): Implement asyncio._get_running_loop() and
     get_event_loop() in C. This makes them 4x faster.

   - bpo-32250(30): Implement ‘asyncio.current_task()’ and
     ‘asyncio.all_tasks()’.  Add helpers intended to be used by
     alternative task implementations: ‘asyncio._register_task’,
     ‘asyncio._enter_task’, ‘asyncio._leave_task’ and
     ‘asyncio._unregister_task’.  Deprecate
     ‘asyncio.Task.current_task()’ and ‘asyncio.Task.all_tasks()’.

   - bpo-32255(31): A single empty field is now always quoted when
     written into a CSV file.  This allows to distinguish an empty row
     from a row consisting of a single empty field.  Patch by Licht
     Takeuchi.

   - bpo-32277(32): Raise ‘NotImplementedError’ instead of ‘SystemError’
     on platforms where ‘chmod(..., follow_symlinks=False)’ is not
     supported.  Patch by Anthony Sottile.

   - bpo-30050(33): New argument warn_on_full_buffer to
     signal.set_wakeup_fd lets you control whether Python prints a
     warning on stderr when the wakeup fd buffer overflows.

   - bpo-29137(34): The ‘fpectl’ library has been removed.  It was never
     enabled by default, never worked correctly on x86-64, and it
     changed the Python ABI in ways that caused unexpected breakage of C
     extensions.

   - bpo-32273(35): Move asyncio.test_utils to test.test_asyncio.

   - bpo-32272(36): Remove asyncio.async() function.

   - bpo-32269(37): Add asyncio.get_running_loop() function.

   - bpo-32265(38): All class and static methods of builtin types now
     are correctly classified by inspect.classify_class_attrs() and
     grouped in pydoc ouput.  Added types.ClassMethodDescriptorType for
     unbound class methods of builtin types.

   - bpo-32253(39): Deprecate ‘yield from lock’, ‘await lock’, ‘with
     (yield from lock)’ and ‘with await lock’ for asyncio
     synchronization primitives.

   - bpo-22589(40): Changed MIME type of .bmp from ’image/x-ms-bmp’ to
     ’image/bmp’

   - bpo-32193(41): Convert asyncio to use `async/await' syntax.  Old
     styled ‘yield from’ is still supported too.

   - bpo-32206(42): Add support to run modules with pdb

   - bpo-32227(43): ‘functools.singledispatch’ now supports registering
     implementations using type annotations.

   - bpo-15873(44): Added new alternate constructors *note
     datetime.datetime.fromisoformat(): 387, *note
     datetime.time.fromisoformat(): 10a6. and *note
     datetime.date.fromisoformat(): 10a7. as the inverse operation of
     each classes’s respective ‘isoformat’ methods.

   - bpo-32199(45): The getnode() ip getter now uses ’ip link’ instead
     of ’ip link list’.

   - bpo-32143(46): os.statvfs() includes the f_fsid field from
     statvfs(2)

   - bpo-26439(47): Fix ctypes.util.find_library() for AIX by
     implementing ctypes._aix.find_library() Patch by: Michael Felt

   - bpo-31993(48): The pickler now uses less memory when serializing
     large bytes and str objects into a file.  Pickles created with
     protocol 4 will require less memory for unpickling large bytes and
     str objects.

   - bpo-27456(49): Ensure TCP_NODELAY is set on Linux.  Tests by Victor
     Stinner.

   - bpo-31778(50): ast.literal_eval() is now more strict.  Addition and
     subtraction of arbitrary numbers no longer allowed.

   - bpo-31802(51): Importing native path module (‘posixpath’, ‘ntpath’)
     now works even if the ‘os’ module still is not imported.

   - bpo-30241(52): Add contextlib.AbstractAsyncContextManager.  Patch
     by Jelle Zijlstra.

   - bpo-31699(53): Fix deadlocks in *note
     concurrent.futures.ProcessPoolExecutor: 2a4. when task arguments or
     results cause pickling or unpickling errors.  This should make sure
     that calls to the ‘ProcessPoolExecutor’ API always eventually
     return.

   - bpo-15216(54): ‘TextIOWrapper.reconfigure()’ supports changing
     `encoding', `errors', and `newline'.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32506

   (2) https://bugs.python.org/issue32279

   (3) https://bugs.python.org/issue32278

   (4) https://bugs.python.org/issue32499

   (5) https://bugs.python.org/issue32468

   (6) https://bugs.python.org/issue23749

   (7) https://bugs.python.org/issue32441

   (8) https://bugs.python.org/issue32422

   (9) https://bugs.python.org/issue31721

   (10) https://bugs.python.org/issue32415

   (11) https://bugs.python.org/issue26133

   (12) https://bugs.python.org/issue32363

   (13) https://bugs.python.org/issue32357

   (14) https://bugs.python.org/issue32356

   (15) https://bugs.python.org/issue32355

   (16) https://bugs.python.org/issue32351

   (17) https://bugs.python.org/issue32348

   (18) https://bugs.python.org/issue32331

   (19) https://bugs.python.org/issue32248

   (20) https://bugs.python.org/issue32311

   (21) https://bugs.python.org/issue32327

   (22) https://bugs.python.org/issue32323

   (23) https://bugs.python.org/issue32302

   (24) https://bugs.python.org/issue29711

   (25) https://bugs.python.org/issue32308

   (26) https://bugs.python.org/issue29970

   (27) https://bugs.python.org/issue32314

   (28) https://bugs.python.org/issue17852

   (29) https://bugs.python.org/issue32296

   (30) https://bugs.python.org/issue32250

   (31) https://bugs.python.org/issue32255

   (32) https://bugs.python.org/issue32277

   (33) https://bugs.python.org/issue30050

   (34) https://bugs.python.org/issue29137

   (35) https://bugs.python.org/issue32273

   (36) https://bugs.python.org/issue32272

   (37) https://bugs.python.org/issue32269

   (38) https://bugs.python.org/issue32265

   (39) https://bugs.python.org/issue32253

   (40) https://bugs.python.org/issue22589

   (41) https://bugs.python.org/issue32193

   (42) https://bugs.python.org/issue32206

   (43) https://bugs.python.org/issue32227

   (44) https://bugs.python.org/issue15873

   (45) https://bugs.python.org/issue32199

   (46) https://bugs.python.org/issue32143

   (47) https://bugs.python.org/issue26439

   (48) https://bugs.python.org/issue31993

   (49) https://bugs.python.org/issue27456

   (50) https://bugs.python.org/issue31778

   (51) https://bugs.python.org/issue31802

   (52) https://bugs.python.org/issue30241

   (53) https://bugs.python.org/issue31699

   (54) https://bugs.python.org/issue15216


File: python.info,  Node: 文档<32>,  Next: 测试<26>,  Prev: 库<37>,  Up: Python 3 7 0 alpha 4

1.18.38.3 文档
..............

   - bpo-32418(1): Add get_loop() method to Server and AbstractServer
     classes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32418


File: python.info,  Node: 测试<26>,  Next: Windows<28>,  Prev: 文档<32>,  Up: Python 3 7 0 alpha 4

1.18.38.4 测试
..............

   - bpo-32252(1): Fix faulthandler_suppress_crash_report() used to
     prevent core dump files when testing crashes.  getrlimit() returns
     zero on success.

   - bpo-32002(2): Adjust C locale coercion testing for the empty locale
     and POSIX locale cases to more readily adjust to platform dependent
     behaviour.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32252

   (2) https://bugs.python.org/issue32002


File: python.info,  Node: Windows<28>,  Next: 工具/示例<16>,  Prev: 测试<26>,  Up: Python 3 7 0 alpha 4

1.18.38.5 Windows
.................

   - bpo-19764(1): Implement support for
     ‘subprocess.Popen(close_fds=True)’ on Windows.  Patch by Segev
     Finer.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19764


File: python.info,  Node: 工具/示例<16>,  Next: C API<19>,  Prev: Windows<28>,  Up: Python 3 7 0 alpha 4

1.18.38.6 工具/示例
...................

   - bpo-24960(1): 2to3 and lib2to3 can now read pickled grammar files
     using pkgutil.get_data() rather than probing the filesystem.  This
     lets 2to3 and lib2to3 work when run from a zipfile.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24960


File: python.info,  Node: C API<19>,  Prev: 工具/示例<16>,  Up: Python 3 7 0 alpha 4

1.18.38.7 C API
...............

   - bpo-32030(1): Py_Initialize() doesn’t reset the memory allocators
     to default if the ‘PYTHONMALLOC’ environment variable is not set.

   - bpo-29084(2): Undocumented C API for OrderedDict has been excluded
     from the limited C API. It was added by mistake and actually never
     worked in the limited C API.

   - bpo-32264(3): Moved the pygetopt.h header into internal/, since it
     has no public APIs.

   - bpo-32241(4): *note Py_SetProgramName(): f99. and *note
     Py_SetPythonHome(): f98. now take the ‘const wchar *’ arguments
     instead of ‘wchar *’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32030

   (2) https://bugs.python.org/issue29084

   (3) https://bugs.python.org/issue32264

   (4) https://bugs.python.org/issue32241


File: python.info,  Node: Python 3 7 0 alpha 3,  Next: Python 3 7 0 alpha 2,  Prev: Python 3 7 0 alpha 4,  Up: 更新日志

1.18.39 Python 3.7.0 alpha 3
----------------------------

`发布日期: 2017-12-05'

* Menu:

* 核心与内置: 核心与内置<37>.
* 库: 库<38>.
* 文档: 文档<33>.
* 测试: 测试<27>.
* 构建: 构建<24>.
* Windows: Windows<29>.
* macOS: macOS<22>.
* IDLE: IDLE<33>.
* 工具/示例: 工具/示例<17>.
* C API: C API<20>.


File: python.info,  Node: 核心与内置<37>,  Next: 库<38>,  Up: Python 3 7 0 alpha 3

1.18.39.1 核心与内置
....................

   - bpo-32176(1): co_flags.CO_NOFREE is now always set correctly by the
     code object constructor based on freevars and cellvars, rather than
     needing to be set correctly by the caller.  This ensures it will be
     cleared automatically when additional cell references are injected
     into a modified code object and function.

   - bpo-10544(2): Yield expressions are now deprecated in
     comprehensions and generator expressions.  They are still permitted
     in the definition of the outermost iterable, as that is evaluated
     directly in the enclosing scope.

   - bpo-32137(3): The repr of deeply nested dict now raises a
     RecursionError instead of crashing due to a stack overflow.

   - bpo-32096(4): Revert memory allocator changes in the C API: move
     structures back from _PyRuntime to Objects/obmalloc.c.  The memory
     allocators are once again initialized statically, and so
     PyMem_RawMalloc() and Py_DecodeLocale() can be called before
     _PyRuntime_Initialize().

   - bpo-32043(5): Add a new "developer mode": new "-X dev" command line
     option to enable debug checks at runtime.

   - bpo-32023(6): SyntaxError is now correctly raised when a generator
     expression without parenthesis is used instead of an inheritance
     list in a class definition.  The duplication of the parentheses can
     be omitted only on calls.

   - bpo-32012(7): SyntaxError is now correctly raised when a generator
     expression without parenthesis is passed as an argument, but
     followed by a trailing comma.  A generator expression always needs
     to be directly inside a set of parentheses and cannot have a comma
     on either side.

   - bpo-28180(8): A new internal ‘_Py_SetLocaleFromEnv(category)’
     helper function has been added in order to improve the consistency
     of behaviour across different ‘libc’ implementations (e.g.  Android
     doesn’t support setting the locale from the environment by
     default).

   - bpo-31949(9): Fixed several issues in printing tracebacks
     (PyTraceBack_Print()).  Setting sys.tracebacklimit to 0 or less now
     suppresses printing tracebacks.  Setting sys.tracebacklimit to None
     now causes using the default limit.  Setting sys.tracebacklimit to
     an integer larger than LONG_MAX now means using the limit LONG_MAX
     rather than the default limit.  Fixed integer overflows in the case
     of more than 2**31 traceback items on Windows.  Fixed output errors
     handling.

   - bpo-30696(10): Fix the interactive interpreter looping endlessly
     when no memory.

   - bpo-20047(11): Bytearray methods partition() and rpartition() now
     accept only bytes-like objects as separator, as documented.  In
     particular they now raise TypeError rather of returning a bogus
     result when an integer is passed as a separator.

   - bpo-21720(12): BytesWarning no longer emitted when the `fromlist'
     argument of ‘__import__()’ or the ‘__all__’ attribute of the module
     contain bytes instances.

   - bpo-31845(13): Environment variables are once more read correctly
     at interpreter startup.

   - bpo-28936(14): Ensure that lexically first syntax error involving a
     parameter and ‘global’ or ‘nonlocal’ is detected first at a given
     scope.  Patch by Ivan Levkivskyi.

   - bpo-31825(15): Fixed OverflowError in the ’unicode-escape’ codec
     and in codecs.escape_decode() when decode an escaped non-ascii
     byte.

   - bpo-31618(16): The per-frame tracing logic added in 3.7a1 has been
     altered so that ‘frame->f_lineno’ is updated before either ‘"line"’
     or ‘"opcode"’ events are emitted.  Previously, opcode events were
     emitted first, and therefore would occasionally see stale line
     numbers on the frame.  The behavior of this feature has changed
     slightly as a result: when both ‘f_trace_lines’ and
     ‘f_trace_opcodes’ are enabled, line events now occur first.

   - bpo-28603(17): Print the full context/cause chain of exceptions on
     interpreter exit, even if an exception in the chain is unhashable
     or compares equal to later ones.  Patch by Zane Bitter.

   - bpo-31786(18): Fix timeout rounding in the select module to round
     correctly negative timeouts between -1.0 and 0.0.  The functions
     now block waiting for events as expected.  Previously, the call was
     incorrectly non-blocking.  Patch by Pablo Galindo.

   - bpo-31781(19): Prevent crashes when calling methods of an
     uninitialized ‘zipimport.zipimporter’ object.  Patch by Oren
     Milman.

   - bpo-30399(20): Standard repr() of BaseException with a single
     argument no longer contains redundant trailing comma.

   - bpo-31626(21): Fixed a bug in debug memory allocator.  There was a
     write to freed memory after shrinking a memory block.

   - bpo-30817(22): ‘PyErr_PrintEx()’ clears now the ignored exception
     that may be raised by ‘_PySys_SetObjectId()’, for example when no
     memory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32176

   (2) https://bugs.python.org/issue10544

   (3) https://bugs.python.org/issue32137

   (4) https://bugs.python.org/issue32096

   (5) https://bugs.python.org/issue32043

   (6) https://bugs.python.org/issue32023

   (7) https://bugs.python.org/issue32012

   (8) https://bugs.python.org/issue28180

   (9) https://bugs.python.org/issue31949

   (10) https://bugs.python.org/issue30696

   (11) https://bugs.python.org/issue20047

   (12) https://bugs.python.org/issue21720

   (13) https://bugs.python.org/issue31845

   (14) https://bugs.python.org/issue28936

   (15) https://bugs.python.org/issue31825

   (16) https://bugs.python.org/issue31618

   (17) https://bugs.python.org/issue28603

   (18) https://bugs.python.org/issue31786

   (19) https://bugs.python.org/issue31781

   (20) https://bugs.python.org/issue30399

   (21) https://bugs.python.org/issue31626

   (22) https://bugs.python.org/issue30817


File: python.info,  Node: 库<38>,  Next: 文档<33>,  Prev: 核心与内置<37>,  Up: Python 3 7 0 alpha 3

1.18.39.2 库
............

   - bpo-28556(1): Two minor fixes for ‘typing’ module: allow shallow
     copying instances of generic classes, improve interaction of
     ‘__init_subclass__’ with generics.  Original PRs by Ivan
     Levkivskyi.

   - bpo-32214(2): PEP 557, Data Classes.  Provides a decorator which
     adds boilerplate methods to classes which use type annotations so
     specify fields.

   - bpo-27240(3): The header folding algorithm for the new email
     policies has been rewritten, which also fixes bpo-30788(4),
     bpo-31831(5), and bpo-32182(6).  In particular, RFC2231 folding is
     now done correctly.

   - bpo-32186(7): io.FileIO.readall() and io.FileIO.read() now release
     the GIL when getting the file size.  Fixed hang of all threads with
     inaccessible NFS server.  Patch by Nir Soffer.

   - bpo-321010(8): Add ‘sys.flags.dev_mode’ flag

   - bpo-32154(9): The ‘asyncio.windows_utils.socketpair()’ function has
     been removed: use directly *note socket.socketpair(): 489. which is
     available on all platforms since Python 3.5 (before, it wasn’t
     available on Windows).  ‘asyncio.windows_utils.socketpair()’ was
     just an alias to ‘socket.socketpair’ on Python 3.5 and newer.

   - bpo-32089(10): warnings: In development (-X dev) and debug mode
     (pydebug build), use the "default" action for ResourceWarning,
     rather than the "always" action, in the default warnings filters.

   - bpo-32107(11): ‘uuid.getnode()’ now preferentially returns
     universally administered MAC addresses if available, over locally
     administered MAC addresses.  This makes a better guarantee for
     global uniqueness of UUIDs returned from ‘uuid.uuid1()’.  If only
     locally administered MAC addresses are available, the first such
     one found is returned.

   - bpo-23033(12): Wildcard is now supported in hostname when it is one
     and only character in the left most segment of hostname in second
     argument of *note ssl.match_hostname(): 3e4.  Patch by Mandeep
     Singh.

   - bpo-12239(13): Make *note msilib.SummaryInformation.GetProperty():
     fd3. return ‘None’ when the value of property is ‘VT_EMPTY’.
     Initial patch by Mark Mc Mahon.

   - bpo-28334(14): Use *note os.path.expanduser(): 1ff. to find the
     ‘~/.netrc’ file in *note netrc.netrc: 10b0.  If it does not exist,
     *note FileNotFoundError: 7c9. is raised.  Patch by Dimitri
     Merejkowsky.

   - bpo-32121(15): Made ‘tracemalloc.Traceback’ behave more like the
     traceback module, sorting the frames from oldest to most recent.
     ‘Traceback.format()’ now accepts negative `limit', truncating the
     result to the ‘abs(limit)’ oldest frames.  To get the old
     behaviour, one can use the new `most_recent_first' argument to
     ‘Traceback.format()’.  (Patch by Jesse Bakker.)

   - bpo-31325(16): Fix wrong usage of *note collections.namedtuple():
     1b7. in the *note RobotFileParser.parse(): 10b1. method.  Initial
     patch by Robin Wellner.

   - bpo-12382(17): *note msilib.OpenDatabase(): f1f. now raises a
     better exception message when it couldn’t open or create an MSI
     file.  Initial patch by William Tisäter.

   - bpo-19610(18): ‘setup()’ now warns about invalid types for some
     fields.  The ‘distutils.dist.Distribution’ class now warns when
     ‘classifiers’, ‘keywords’ and ‘platforms’ fields are not specified
     as a list or a string.

   - bpo-32071(19): Added the ‘-k’ command-line option to ‘python -m
     unittest’ to run only tests that match the given pattern(s).

   - bpo-10049(20): Added `nullcontext' no-op context manager to
     contextlib.  This provides a simpler and faster alternative to
     ExitStack() when handling optional context managers.

   - bpo-28684(21): The new test.support.skip_unless_bind_unix_socket()
     decorator is used here to skip asyncio tests that fail because the
     platform lacks a functional bind() function for unix domain sockets
     (as it is the case for non root users on the recent Android
     versions that run now SELinux in enforcing mode).

   - bpo-32110(22): ‘codecs.StreamReader.read(n)’ now returns not more
     than `n' characters/bytes for non-negative `n'.  This makes it
     compatible with ‘read()’ methods of other file-like objects.

   - bpo-27535(23): The warnings module doesn’t leak memory anymore in
     the hidden warnings registry for the "ignore" action of warnings
     filters.  warn_explicit() function doesn’t add the warning key to
     the registry anymore for the "ignore" action.

   - bpo-32088(24): warnings: When Python is build is debug mode
     (‘Py_DEBUG’), *note DeprecationWarning: 279, *note
     PendingDeprecationWarning: 27a. and *note ImportWarning: 5e1.
     warnings are now displayed by default.

   - bpo-1647489(25): Fixed searching regular expression patterns that
     could match an empty string.  Non-empty string can now be correctly
     found after matching an empty string.

   - bpo-25054(26): Added support of splitting on a pattern that could
     match an empty string.

   - bpo-32072(27): Fixed issues with binary plists: Fixed saving
     bytearrays.  Identical objects will be saved only once.  Equal
     references will be load as identical objects.  Added support for
     saving and loading recursive data structures.

   - bpo-32069(28): Drop legacy SSL transport from asyncio,
     ssl.MemoryBIO is always used anyway.

   - bpo-32066(29): asyncio: Support pathlib.Path in
     create_unix_connection; sock arg should be optional

   - bpo-32046(30): Updates 2to3 to convert from
     operator.isCallable(obj) to callable(obj).  Patch by Dong-hee Na.

   - bpo-32018(31): inspect.signature should follow PEP 8(32), if the
     parameter has an annotation and a default value.  Patch by Dong-hee
     Na.

   - bpo-32025(33): Add time.thread_time() and time.thread_time_ns()

   - bpo-32037(34): Integers that fit in a signed 32-bit integer will be
     now pickled with protocol 0 using the INT opcode.  This will
     decrease the size of a pickle, speed up pickling and unpickling,
     and make these integers be unpickled as int instances in Python 2.

   - bpo-32034(35): Make asyncio.IncompleteReadError and
     LimitOverrunError pickleable.

   - bpo-32015(36): Fixed the looping of asyncio in the case of
     reconnection the socket during waiting async read/write from/to the
     socket.

   - bpo-32011(37): Restored support of loading marshal files with the
     TYPE_INT64 code.  These files can be produced in Python 2.7.

   - bpo-28369(38): Enhance add_reader/writer check that socket is not
     used by some transport.  Before, only cases when add_reader/writer
     were called with an int FD were supported.  Now the check is
     implemented correctly for all file-like objects.

   - bpo-31976(39): Fix race condition when flushing a file is slow,
     which can cause a segfault if closing the file from another thread.

   - bpo-31985(40): Formally deprecated aifc.openfp, sunau.openfp, and
     wave.openfp.  Since change 7bc817d5ba917528e8bd07ec461c635291e7b06a
     in 1993, openfp in each of the three modules had been pointing to
     that module’s open function as a matter of backwards compatibility,
     though it had been both untested and undocumented.

   - bpo-21862(41): cProfile command line now accepts ‘-m module_name’
     as an alternative to script path.  Patch by Sanyam Khurana.

   - bpo-31970(42): Reduce performance overhead of asyncio debug mode.

   - bpo-31843(43): `database' argument of sqlite3.connect() now accepts
     a *note path-like object: 373, instead of just a string.

   - bpo-31945(44): Add Configurable `blocksize' to ‘HTTPConnection’ and
     ‘HTTPSConnection’ for improved upload throughput.  Patch by Nir
     Soffer.

   - bpo-31943(45): Add a ‘cancelled()’ method to *note asyncio.Handle:
     10b2.  Patch by Marat Sharafutdinov.

   - bpo-9678(46): Fixed determining the MAC address in the uuid module:
     Using ifconfig on NetBSD and OpenBSD. Using arp on Linux, FreeBSD,
     NetBSD and OpenBSD. Based on patch by Takayuki Shimizukawa.

   - bpo-30057(47): Fix potential missed signal in signal.signal().

   - bpo-31933(48): Fix Blake2 params leaf_size and node_offset on big
     endian platforms.  Patch by Jack O’Connor.

   - bpo-21423(49): Add an initializer argument to
     {Process,Thread}PoolExecutor

   - bpo-31927(50): Fixed compilation of the socket module on NetBSD 8.
     Fixed assertion failure or reading arbitrary data when parse a
     AF_BLUETOOTH address on NetBSD and DragonFly BSD.

   - bpo-27666(51): Fixed stack corruption in curses.box() and
     curses.ungetmouse() when the size of types chtype or mmask_t is
     less than the size of C long.  curses.box() now accepts characters
     as arguments.  Based on patch by Steve Fink.

   - bpo-31917(52): Add 3 new clock identifiers: *note
     time.CLOCK_BOOTTIME: 3fd, *note time.CLOCK_PROF: 3ff. and *note
     time.CLOCK_UPTIME: 400.

   - bpo-31897(53): plistlib now catches more errors when read binary
     plists and raises InvalidFileException instead of unexpected
     exceptions.

   - bpo-25720(54): Fix the method for checking pad state of curses
     WINDOW. Patch by Masayuki Yamamoto.

   - bpo-31893(55): Fixed the layout of the kqueue_event structure on
     OpenBSD and NetBSD. Fixed the comparison of the kqueue_event
     objects.

   - bpo-31891(56): Fixed building the curses module on NetBSD.

   - bpo-31884(57): added required constants to subprocess module for
     setting priority on windows

   - bpo-28281(58): Remove year (1-9999) limits on the
     Calendar.weekday() function.  Patch by Mark Gollahon.

   - bpo-31702(59): crypt.mksalt() now allows to specify the number of
     rounds for SHA-256 and SHA-512 hashing.

   - bpo-30639(60): *note inspect.getfile(): 10b3. no longer computes
     the repr of unknown objects to display in an error message, to
     protect against badly behaved custom reprs.

   - bpo-30768(61): Fix the pthread+semaphore implementation of
     PyThread_acquire_lock_timed() when called with timeout > 0 and
     intr_flag=0: recompute the timeout if sem_timedwait() is
     interrupted by a signal (EINTR). See also the PEP 475(62).

   - bpo-31854(63): Add ‘mmap.ACCESS_DEFAULT’ constant.

   - bpo-31834(64): Use optimized code for BLAKE2 only with SSSE3+.  The
     pure SSE2 implementation is slower than the pure C reference
     implementation.

   - bpo-28292(65): Calendar.itermonthdates() will now consistently
     raise an exception when a date falls outside of the 0001-01-01
     through 9999-12-31 range.  To support applications that cannot
     tolerate such exceptions, the new methods itermonthdays3() and
     itermonthdays4() are added.  The new methods return tuples and are
     not restricted by the range supported by datetime.date.

   - bpo-28564(66): The shutil.rmtree() function has been sped up to
     20–40%.  This was done using the os.scandir() function.

   - bpo-28416(67): Instances of pickle.Pickler subclass with the
     persistent_id() method and pickle.Unpickler subclass with the
     persistent_load() method no longer create reference cycles.

   - bpo-31653(68): Don’t release the GIL if we can acquire a
     multiprocessing semaphore immediately.

   - bpo-28326(69): Fix multiprocessing.Process when stdout and/or
     stderr is closed or None.

   - bpo-20825(70): Add ‘subnet_of’ and ‘superset_of’ containment tests
     to *note ipaddress.IPv6Network: 3a7. and *note
     ipaddress.IPv4Network: 3a8.  Patch by Michel Albert and Cheryl
     Sabella.

   - bpo-31827(71): Remove the os.stat_float_times() function.  It was
     introduced in Python 2.3 for backward compatibility with Python
     2.2, and was deprecated since Python 3.1.

   - bpo-31756(72): Add a ‘subprocess.Popen(text=False)’ keyword
     argument to *note subprocess: fa. functions to be more explicit
     about when the library should attempt to decode outputs into text.
     Patch by Andrew Clegg.

   - bpo-31819(73): Add AbstractEventLoop.sock_recv_into().

   - bpo-31457(74): If nested log adapters are used, the inner
     ‘process()’ methods are no longer omitted.

   - bpo-31457(75): The ‘manager’ property on LoggerAdapter objects is
     now properly settable.

   - bpo-31806(76): Fix timeout rounding in time.sleep(),
     threading.Lock.acquire() and socket.socket.settimeout() to round
     correctly negative timeouts between -1.0 and 0.0.  The functions
     now block waiting for events as expected.  Previously, the call was
     incorrectly non-blocking.  Patch by Pablo Galindo.

   - bpo-31803(77): time.clock() and time.get_clock_info(’clock’) now
     emit a DeprecationWarning warning.

   - bpo-31800(78): Extended support for parsing UTC offsets.  strptime
     ’%z’ can now parse the output generated by datetime.isoformat,
     including seconds and microseconds.

   - bpo-28603(79): traceback: Fix a TypeError that occurred during
     printing of exception tracebacks when either the current exception
     or an exception in its context/cause chain is unhashable.  Patch by
     Zane Bitter.

   - bpo-30541(80): Add new function to seal a mock and prevent the
     automatically creation of child mocks.  Patch by Mario Corchero.

   - bpo-31784(81): Implement the PEP 564(82), add new 6 new functions
     with nanosecond resolution to the *note time: 10b. module: *note
     clock_gettime_ns(): 327, *note clock_settime_ns(): 328, *note
     monotonic_ns(): 329, *note perf_counter_ns(): 32a, *note
     process_time_ns(): 32b, *note time_ns(): 32c.

   - bpo-30143(83): 2to3 now generates a code that uses abstract
     collection classes from collections.abc rather than collections.

   - bpo-31770(84): Prevent a crash when calling the ‘__init__()’ method
     of a ‘sqlite3.Cursor’ object more than once.  Patch by Oren Milman.

   - bpo-31764(85): Prevent a crash in ‘sqlite3.Cursor.close()’ in case
     the ‘Cursor’ object is uninitialized.  Patch by Oren Milman.

   - bpo-31752(86): Fix possible crash in timedelta constructor called
     with custom integers.

   - bpo-31620(87): an empty asyncio.Queue now doesn’t leak memory when
     queue.get pollers timeout

   - bpo-31690(88): Allow the flags re.ASCII, re.LOCALE, and re.UNICODE
     to be used as group flags for regular expressions.

   - bpo-30349(89): FutureWarning is now emitted if a regular expression
     contains character set constructs that will change semantically in
     the future (nested sets and set operations).

   - bpo-31664(90): Added support for the Blowfish hashing in the crypt
     module.

   - bpo-31632(91): Fix method set_protocol() of class
     _SSLProtocolTransport in asyncio module.  This method was
     previously modifying a wrong reference to the protocol.

   - bpo-15037(92): Added a workaround for getkey() in curses for
     ncurses 5.7 and earlier.

   - bpo-31307(93): Allow use of bytes objects for arguments to *note
     configparser.ConfigParser.read(): 10b4.  Patch by Vincent Michel.

   - bpo-31334(94): Fix ‘poll.poll([timeout])’ in the ‘select’ module
     for arbitrary negative timeouts on all OSes where it can only be a
     non-negative integer or -1.  Patch by Riccardo Coccioli.

   - bpo-31310(95): multiprocessing’s semaphore tracker should be
     launched again if crashed.

   - bpo-31308(96): Make multiprocessing’s forkserver process immune to
     Ctrl-C and other user interruptions.  If it crashes, restart it
     when necessary.

   - bpo-31245(97): Added support for AF_UNIX socket in asyncio
     ‘create_datagram_endpoint’.

   - bpo-30553(98): Add HTTP/2 status code 421 (Misdirected Request) to
     *note http.HTTPStatus: 6eb.  Patch by Vitor Pereira.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28556

   (2) https://bugs.python.org/issue32214

   (3) https://bugs.python.org/issue27240

   (4) https://bugs.python.org/issue30788

   (5) https://bugs.python.org/issue31831

   (6) https://bugs.python.org/issue32182

   (7) https://bugs.python.org/issue32186

   (8) https://bugs.python.org/issue321010

   (9) https://bugs.python.org/issue32154

   (10) https://bugs.python.org/issue32089

   (11) https://bugs.python.org/issue32107

   (12) https://bugs.python.org/issue23033

   (13) https://bugs.python.org/issue12239

   (14) https://bugs.python.org/issue28334

   (15) https://bugs.python.org/issue32121

   (16) https://bugs.python.org/issue31325

   (17) https://bugs.python.org/issue12382

   (18) https://bugs.python.org/issue19610

   (19) https://bugs.python.org/issue32071

   (20) https://bugs.python.org/issue10049

   (21) https://bugs.python.org/issue28684

   (22) https://bugs.python.org/issue32110

   (23) https://bugs.python.org/issue27535

   (24) https://bugs.python.org/issue32088

   (25) https://bugs.python.org/issue1647489

   (26) https://bugs.python.org/issue25054

   (27) https://bugs.python.org/issue32072

   (28) https://bugs.python.org/issue32069

   (29) https://bugs.python.org/issue32066

   (30) https://bugs.python.org/issue32046

   (31) https://bugs.python.org/issue32018

   (32) https://www.python.org/dev/peps/pep-0008

   (33) https://bugs.python.org/issue32025

   (34) https://bugs.python.org/issue32037

   (35) https://bugs.python.org/issue32034

   (36) https://bugs.python.org/issue32015

   (37) https://bugs.python.org/issue32011

   (38) https://bugs.python.org/issue28369

   (39) https://bugs.python.org/issue31976

   (40) https://bugs.python.org/issue31985

   (41) https://bugs.python.org/issue21862

   (42) https://bugs.python.org/issue31970

   (43) https://bugs.python.org/issue31843

   (44) https://bugs.python.org/issue31945

   (45) https://bugs.python.org/issue31943

   (46) https://bugs.python.org/issue9678

   (47) https://bugs.python.org/issue30057

   (48) https://bugs.python.org/issue31933

   (49) https://bugs.python.org/issue21423

   (50) https://bugs.python.org/issue31927

   (51) https://bugs.python.org/issue27666

   (52) https://bugs.python.org/issue31917

   (53) https://bugs.python.org/issue31897

   (54) https://bugs.python.org/issue25720

   (55) https://bugs.python.org/issue31893

   (56) https://bugs.python.org/issue31891

   (57) https://bugs.python.org/issue31884

   (58) https://bugs.python.org/issue28281

   (59) https://bugs.python.org/issue31702

   (60) https://bugs.python.org/issue30639

   (61) https://bugs.python.org/issue30768

   (62) https://www.python.org/dev/peps/pep-0475

   (63) https://bugs.python.org/issue31854

   (64) https://bugs.python.org/issue31834

   (65) https://bugs.python.org/issue28292

   (66) https://bugs.python.org/issue28564

   (67) https://bugs.python.org/issue28416

   (68) https://bugs.python.org/issue31653

   (69) https://bugs.python.org/issue28326

   (70) https://bugs.python.org/issue20825

   (71) https://bugs.python.org/issue31827

   (72) https://bugs.python.org/issue31756

   (73) https://bugs.python.org/issue31819

   (74) https://bugs.python.org/issue31457

   (75) https://bugs.python.org/issue31457

   (76) https://bugs.python.org/issue31806

   (77) https://bugs.python.org/issue31803

   (78) https://bugs.python.org/issue31800

   (79) https://bugs.python.org/issue28603

   (80) https://bugs.python.org/issue30541

   (81) https://bugs.python.org/issue31784

   (82) https://www.python.org/dev/peps/pep-0564

   (83) https://bugs.python.org/issue30143

   (84) https://bugs.python.org/issue31770

   (85) https://bugs.python.org/issue31764

   (86) https://bugs.python.org/issue31752

   (87) https://bugs.python.org/issue31620

   (88) https://bugs.python.org/issue31690

   (89) https://bugs.python.org/issue30349

   (90) https://bugs.python.org/issue31664

   (91) https://bugs.python.org/issue31632

   (92) https://bugs.python.org/issue15037

   (93) https://bugs.python.org/issue31307

   (94) https://bugs.python.org/issue31334

   (95) https://bugs.python.org/issue31310

   (96) https://bugs.python.org/issue31308

   (97) https://bugs.python.org/issue31245

   (98) https://bugs.python.org/issue30553


File: python.info,  Node: 文档<33>,  Next: 测试<27>,  Prev: 库<38>,  Up: Python 3 7 0 alpha 3

1.18.39.3 文档
..............

   - bpo-32105(1): Added asyncio.BaseEventLoop.connect_accepted_socket
     versionadded marker.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32105


File: python.info,  Node: 测试<27>,  Next: 构建<24>,  Prev: 文档<33>,  Up: Python 3 7 0 alpha 3

1.18.39.4 测试
..............

   - bpo-31380(1): Skip test_httpservers test_undecodable_file on macOS:
     fails on APFS.

   - bpo-31705(2): Skip test_socket.test_sha256() on Linux kernel older
     than 4.5.  The test fails with ENOKEY on kernel 3.10 (on ppc64le).
     A fix was merged into the kernel 4.5.

   - bpo-32138(3): Skip on Android test_faulthandler tests that raise
     SIGSEGV and remove the test.support.requires_android_level
     decorator.

   - bpo-32136(4): The runtime embedding tests have been split out from
     ‘Lib/test/test_capi.py’ into a new ‘Lib/test/test_embed.py’ file.

   - bpo-28668(5): test.support.requires_multiprocessing_queue is
     removed.  Skip tests with
     test.support.import_module(’multiprocessing.synchronize’) instead
     when the semaphore implementation is broken or missing.

   - bpo-32126(6): Skip test_get_event_loop_new_process in
     test.test_asyncio.test_events when sem_open() is not functional.

   - bpo-31174(7): Fix test_tools.test_unparse: DirectoryTestCase now
     stores the names sample to always test the same files.  It prevents
     false alarms when hunting reference leaks.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31380

   (2) https://bugs.python.org/issue31705

   (3) https://bugs.python.org/issue32138

   (4) https://bugs.python.org/issue32136

   (5) https://bugs.python.org/issue28668

   (6) https://bugs.python.org/issue32126

   (7) https://bugs.python.org/issue31174


File: python.info,  Node: 构建<24>,  Next: Windows<29>,  Prev: 测试<27>,  Up: Python 3 7 0 alpha 3

1.18.39.5 构建
..............

   - bpo-28538(1): Revert the previous changes, the if_nameindex
     structure is defined by Unified Headers.

   - bpo-28762(2): Revert the last commit, the F_LOCK macro is defined
     by Android Unified Headers.

   - bpo-29040(3): Support building Android with Unified Headers.  The
     first NDK release to support Unified Headers is android-ndk-r14.

   - bpo-32059(4): ‘detect_modules()’ in ‘setup.py’ now also searches
     the sysroot paths when cross-compiling.

   - bpo-31957(5): Fixes Windows SDK version detection when building for
     Windows.

   - bpo-31609(6): Fixes quotes in PCbuild/clean.bat

   - bpo-31934(7): Abort the build when building out of a not clean
     source tree.

   - bpo-31926(8): Fixed Argument Clinic sometimes causing compilation
     errors when there was more than one function and/or method in a .c
     file with the same name.

   - bpo-28791(9): 更新 Windows 构建以使用 SQLite 3.21.0.

   - bpo-28791(10): 更新 OS X 安装程序以使用 SQLite 3.21.0.

   - bpo-28643(11): Record profile-opt build progress with stamp files.

   - bpo-31866(12): Finish removing support for AtheOS.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28538

   (2) https://bugs.python.org/issue28762

   (3) https://bugs.python.org/issue29040

   (4) https://bugs.python.org/issue32059

   (5) https://bugs.python.org/issue31957

   (6) https://bugs.python.org/issue31609

   (7) https://bugs.python.org/issue31934

   (8) https://bugs.python.org/issue31926

   (9) https://bugs.python.org/issue28791

   (10) https://bugs.python.org/issue28791

   (11) https://bugs.python.org/issue28643

   (12) https://bugs.python.org/issue31866


File: python.info,  Node: Windows<29>,  Next: macOS<22>,  Prev: 构建<24>,  Up: Python 3 7 0 alpha 3

1.18.39.6 Windows
.................

   - bpo-1102(1): Return ‘None’ when ‘View.Fetch()’ returns
     ‘ERROR_NO_MORE_ITEMS’ instead of raising ‘MSIError’.  Initial patch
     by Anthony Tuininga.

   - bpo-31944(2): Fixes Modify button in Apps and Features dialog.

   - bpo-20486(3): Implement the ‘Database.Close()’ method to help
     closing MSI database objects.

   - bpo-31857(4): Make the behavior of USE_STACKCHECK deterministic in
     a multi-threaded environment.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1102

   (2) https://bugs.python.org/issue31944

   (3) https://bugs.python.org/issue20486

   (4) https://bugs.python.org/issue31857


File: python.info,  Node: macOS<22>,  Next: IDLE<33>,  Prev: Windows<29>,  Up: Python 3 7 0 alpha 3

1.18.39.7 macOS
...............

   - bpo-31392(1): 更新 macOS 安装程序以使用OpenSSL 1.0.2m

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31392


File: python.info,  Node: IDLE<33>,  Next: 工具/示例<17>,  Prev: macOS<22>,  Up: Python 3 7 0 alpha 3

1.18.39.8 IDLE
..............

   - bpo-32207(1): Improve tk event exception tracebacks in IDLE. When
     tk event handling is driven by IDLE’s run loop, a confusing and
     distracting queue.EMPTY traceback context is no longer added to tk
     event exception tracebacks.  The traceback is now the same as when
     event handling is driven by user code.  Patch based on a suggestion
     by Serhiy Storchaka.

   - bpo-32164(2): Delete unused file idlelib/tabbedpages.py.  Use of
     TabbedPageSet in configdialog was replaced by ttk.Notebook.

   - bpo-32100(3): IDLE: Fix old and new bugs in pathbrowser; improve
     tests.  Patch mostly by Cheryl Sabella.

   - bpo-31858(4): IDLE – Restrict shell prompt manipulation to the
     shell.  Editor and output windows only see an empty last prompt
     line.  This simplifies the code and fixes a minor bug when newline
     is inserted.  Sys.ps1, if present, is read on Shell start-up, but
     is not set or changed.

   - bpo-31860(5): The font sample in the IDLE configuration dialog is
     now editable.  Changes persist while IDLE remains open

   - bpo-31836(6): Test_code_module now passes if run after test_idle,
     which sets ps1.  The code module uses sys.ps1 if present or sets it
     to ’>>> ’ if not.  Test_code_module now properly tests both
     behaviors.  Ditto for ps2.

   - bpo-28603(7): Fix a TypeError that caused a shell restart when
     printing a traceback that includes an exception that is unhashable.
     Patch by Zane Bitter.

   - bpo-13802(8): Use non-Latin characters in the IDLE’s Font settings
     sample.  Even if one selects a font that defines a limited subset
     of the unicode Basic Multilingual Plane, tcl/tk will use other
     fonts that define a character.  The expanded example give users of
     non-Latin characters a better idea of what they might see in IDLE’s
     shell and editors.  To make room for the expanded sample, frames on
     the Font tab are re-arranged.  The Font/Tabs help explains a bit
     about the additions.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32207

   (2) https://bugs.python.org/issue32164

   (3) https://bugs.python.org/issue32100

   (4) https://bugs.python.org/issue31858

   (5) https://bugs.python.org/issue31860

   (6) https://bugs.python.org/issue31836

   (7) https://bugs.python.org/issue28603

   (8) https://bugs.python.org/issue13802


File: python.info,  Node: 工具/示例<17>,  Next: C API<20>,  Prev: IDLE<33>,  Up: Python 3 7 0 alpha 3

1.18.39.9 工具/示例
...................

   - bpo-32159(1): Remove CVS and Subversion tools: remove svneol.py and
     treesync.py scripts.  CPython migrated from CVS to Subversion, to
     Mercurial, and then to Git.  CVS and Subversion are no longer used
     to develop CPython.

   - bpo-30722(2): Make redemo work with Python 3.6 and newer versions.
     Also, remove the ‘LOCALE’ option since it doesn’t work with string
     patterns in Python 3.  Patch by Christoph Sarnowski.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32159

   (2) https://bugs.python.org/issue30722


File: python.info,  Node: C API<20>,  Prev: 工具/示例<17>,  Up: Python 3 7 0 alpha 3

1.18.39.10 C API
................

   - bpo-20891(1): Fix PyGILState_Ensure().  When PyGILState_Ensure() is
     called in a non-Python thread before PyEval_InitThreads(), only
     call PyEval_InitThreads() after calling PyThreadState_New() to fix
     a crash.

   - bpo-32125(2): The ‘Py_UseClassExceptionsFlag’ flag has been
     removed.  It was deprecated and wasn’t used anymore since Python
     2.0.

   - bpo-25612(3): Move the current exception state from the frame
     object to the co-routine.  This simplifies the interpreter and
     fixes a couple of obscure bugs caused by having swap exception
     state when entering or exiting a generator.

   - bpo-23699(4): Add Py_RETURN_RICHCOMPARE macro to reduce boilerplate
     code in rich comparison functions.

   - bpo-30697(5): The ‘PyExc_RecursionErrorInst’ singleton is removed
     and ‘PyErr_NormalizeException()’ does not use it anymore.  This
     singleton is persistent and its members being never cleared may
     cause a segfault during finalization of the interpreter.  See also
     bpo-22898(6).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20891

   (2) https://bugs.python.org/issue32125

   (3) https://bugs.python.org/issue25612

   (4) https://bugs.python.org/issue23699

   (5) https://bugs.python.org/issue30697

   (6) https://bugs.python.org/issue22898


File: python.info,  Node: Python 3 7 0 alpha 2,  Next: Python 3 7 0 alpha 1,  Prev: Python 3 7 0 alpha 3,  Up: 更新日志

1.18.40 Python 3.7.0 alpha 2
----------------------------

`发布日期: 2017-10-16'

* Menu:

* 核心与内置: 核心与内置<38>.
* 库: 库<39>.
* 文档: 文档<34>.
* 构建: 构建<25>.
* IDLE: IDLE<34>.
* C API: C API<21>.


File: python.info,  Node: 核心与内置<38>,  Next: 库<39>,  Up: Python 3 7 0 alpha 2

1.18.40.1 核心与内置
....................

   - bpo-31558(1): ‘gc.freeze()’ is a new API that allows for moving all
     objects currently tracked by the garbage collector to a permanent
     generation, effectively removing them from future collection
     events.  This can be used to protect those objects from having
     their PyGC_Head mutated.  In effect, this enables great
     copy-on-write stability at fork().

   - bpo-31642(2): Restored blocking "from package import module" by
     setting sys.modules["package.module"] to None.

   - bpo-31708(3): Allow use of asynchronous generator expressions in
     synchronous functions.

   - bpo-31709(4): 取消对异步__Aiter__的支持。

   - bpo-30404(5): The -u option now makes the stdout and stderr streams
     unbuffered rather than line-buffered.

   - bpo-31619(6): Fixed a ValueError when convert a string with large
     number of underscores to integer with binary base.

   - bpo-31602(7): Fix an assertion failure in
     ‘zipimporter.get_source()’ in case of a bad *note
     zlib.decompress(): 5c8.  Patch by Oren Milman.

   - bpo-31592(8): Fixed an assertion failure in Python parser in case
     of a bad *note unicodedata.normalize(): 10bf.  Patch by Oren
     Milman.

   - bpo-31588(9): Raise a *note TypeError: 193. with a helpful error
     message when class creation fails due to a metaclass with a bad
     ‘__prepare__()’ method.  Patch by Oren Milman.

   - bpo-31574(10): Importlib was instrumented with two dtrace probes to
     profile import timing.

   - bpo-31566(11): Fix an assertion failure in ‘_warnings.warn()’ in
     case of a bad ‘__name__’ global.  Patch by Oren Milman.

   - bpo-31506(12): Improved the error message logic for object.__new__
     and object.__init__.

   - bpo-31505(13): Fix an assertion failure in *note json: a5, in case
     ‘_json.make_encoder()’ received a bad ‘encoder()’ argument.  Patch
     by Oren Milman.

   - bpo-31492(14): Fix assertion failures in case of failing to import
     from a module with a bad ‘__name__’ attribute, and in case of
     failing to access an attribute of such a module.  Patch by Oren
     Milman.

   - bpo-31478(15): Fix an assertion failure in ‘_random.Random.seed()’
     in case the argument has a bad ‘__abs__()’ method.  Patch by Oren
     Milman.

   - bpo-31336(16): Speed up class creation by 10-20% by reducing the
     overhead in the necessary special method lookups.  Patch by Stefan
     Behnel.

   - bpo-31415(17): Add ‘-X importtime’ option to show how long each
     import takes.  It can be used to optimize application’s startup
     time.  Support the *note PYTHONPROFILEIMPORTTIME: 341. as an
     equivalent way to enable this.

   - bpo-31410(18): Optimized calling wrapper and classmethod
     descriptors.

   - bpo-31353(19): PEP 553(20) - Add a new built-in called
     ‘breakpoint()’ which calls ‘sys.breakpointhook()’.  By default this
     imports ‘pdb’ and calls ‘pdb.set_trace()’, but users may override
     ‘sys.breakpointhook()’ to call whatever debugger they want.  The
     original value of the hook is saved in ‘sys.__breakpointhook__’.

   - bpo-17852(21): Maintain a list of open buffered files, flush them
     before exiting the interpreter.  Based on a patch from Armin Rigo.

   - bpo-31315(22): Fix an assertion failure in imp.create_dynamic(),
     when spec.name is not a string.  Patch by Oren Milman.

   - bpo-31311(23): Fix a crash in the ‘__setstate__()’ method of *note
     ctypes._CData: 10c0, in case of a bad ‘__dict__’.  Patch by Oren
     Milman.

   - bpo-31293(24): Fix crashes in true division and multiplication of a
     timedelta object by a float with a bad as_integer_ratio() method.
     Patch by Oren Milman.

   - bpo-31285(25): Fix an assertion failure in *note
     warnings.warn_explicit: 5b9, when the return value of the received
     loader’s get_source() has a bad splitlines() method.  Patch by Oren
     Milman.

   - bpo-30406(26): Make ‘async’ and ‘await’ proper keywords, as
     specified in PEP 492(27).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31558

   (2) https://bugs.python.org/issue31642

   (3) https://bugs.python.org/issue31708

   (4) https://bugs.python.org/issue31709

   (5) https://bugs.python.org/issue30404

   (6) https://bugs.python.org/issue31619

   (7) https://bugs.python.org/issue31602

   (8) https://bugs.python.org/issue31592

   (9) https://bugs.python.org/issue31588

   (10) https://bugs.python.org/issue31574

   (11) https://bugs.python.org/issue31566

   (12) https://bugs.python.org/issue31506

   (13) https://bugs.python.org/issue31505

   (14) https://bugs.python.org/issue31492

   (15) https://bugs.python.org/issue31478

   (16) https://bugs.python.org/issue31336

   (17) https://bugs.python.org/issue31415

   (18) https://bugs.python.org/issue31410

   (19) https://bugs.python.org/issue31353

   (20) https://www.python.org/dev/peps/pep-0553

   (21) https://bugs.python.org/issue17852

   (22) https://bugs.python.org/issue31315

   (23) https://bugs.python.org/issue31311

   (24) https://bugs.python.org/issue31293

   (25) https://bugs.python.org/issue31285

   (26) https://bugs.python.org/issue30406

   (27) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: 库<39>,  Next: 文档<34>,  Prev: 核心与内置<38>,  Up: Python 3 7 0 alpha 2

1.18.40.2 库
............

   - bpo-30058(1): Fixed buffer overflow in select.kqueue.control().

   - bpo-31672(2): ‘idpattern’ in ‘string.Template’ matched some
     non-ASCII characters.  Now it uses ‘-i’ regular expression local
     flag to avoid non-ASCII characters.

   - bpo-31701(3): On Windows, faulthandler.enable() now ignores MSC and
     COM exceptions.

   - bpo-31728(4): Prevent crashes in ‘_elementtree’ due to unsafe
     cleanup of ‘Element.text’ and ‘Element.tail’.  Patch by Oren
     Milman.

   - bpo-31671(5): Now ‘re.compile()’ converts passed RegexFlag to
     normal int object before compiling.  bm_regex_compile benchmark
     shows 14% performance improvements.

   - bpo-30397(6): The types of compiled regular objects and match
     objects are now exposed as ‘re.Pattern’ and ‘re.Match’.  This adds
     information in pydoc output for the re module.

   - bpo-31675(7): Fixed memory leaks in Tkinter’s methods splitlist()
     and split() when pass a string larger than 2 GiB.

   - bpo-31673(8): Fixed typo in the name of Tkinter’s method
     adderrorinfo().

   - bpo-31648(9): Improvements to path predicates in ElementTree: Allow
     whitespace around predicate parts, i.e.  "[a = ’text’]" instead of
     requiring the less readable "[a=’text’]".  Add support for text
     comparison of the current node, like "[.=’text’]".  Patch by Stefan
     Behnel.

   - bpo-30806(10): Fix the string representation of a netrc object.

   - bpo-31638(11): Add optional argument ‘compressed’ to
     ‘zipapp.create_archive’, and add option ‘--compress’ to the command
     line interface of ‘zipapp’.

   - bpo-25351(12): Avoid venv activate failures with undefined
     variables

   - bpo-20519(13): Avoid ctypes use (if possible) and improve import
     time for uuid.

   - bpo-28293(14): The regular expression cache is no longer completely
     dumped when it is full.

   - bpo-31596(15): Added pthread_getcpuclockid() to the time module

   - bpo-27494(16): Make 2to3 accept a trailing comma in generator
     expressions.  For example, ‘set(x for x in [],)’ is now allowed.

   - bpo-30347(17): Stop crashes when concurrently iterate over
     itertools.groupby() iterators.

   - bpo-30346(18): An iterator produced by itertools.groupby() iterator
     now becomes exhausted after advancing the groupby iterator.

   - bpo-31556(19): Cancel asyncio.wait_for future faster if timeout <=
     0

   - bpo-31540(20): Allow passing a context object in *note
     concurrent.futures.ProcessPoolExecutor: 2a4. constructor.  Also,
     free job resources in *note concurrent.futures.ProcessPoolExecutor:
     2a4. earlier to improve memory usage when a worker waits for new
     jobs.

   - bpo-31516(21): ‘threading.current_thread()’ should not return a
     dummy thread at shutdown.

   - bpo-31525(22): In the sqlite module, require the sqlite3_prepare_v2
     API. Thus, the sqlite module now requires sqlite version at least
     3.3.9.

   - bpo-26510(23): argparse subparsers are now required by default.
     This matches behaviour in Python 2.  For optional subparsers, use
     the new parameter ‘add_subparsers(required=False)’.  Patch by
     Anthony Sottile.  (As of 3.7.0rc1, the default was changed to not
     required as had been the case since Python 3.3.)

   - bpo-27541(24): Reprs of subclasses of some collection and iterator
     classes (*note bytearray: 33b, *note array.array: 459, *note
     collections.deque: 539, *note collections.defaultdict: b42, *note
     itertools.count: c23, *note itertools.repeat: 10c2.) now contain
     actual type name insteads of hardcoded name of the base class.

   - bpo-31351(25): python -m ensurepip now exits with non-zero exit
     code if pip bootstrapping has failed.

   - bpo-31389(26): ‘pdb.set_trace()’ now takes an optional keyword-only
     argument ‘header’.  If given, this is printed to the console just
     before debugging begins.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30058

   (2) https://bugs.python.org/issue31672

   (3) https://bugs.python.org/issue31701

   (4) https://bugs.python.org/issue31728

   (5) https://bugs.python.org/issue31671

   (6) https://bugs.python.org/issue30397

   (7) https://bugs.python.org/issue31675

   (8) https://bugs.python.org/issue31673

   (9) https://bugs.python.org/issue31648

   (10) https://bugs.python.org/issue30806

   (11) https://bugs.python.org/issue31638

   (12) https://bugs.python.org/issue25351

   (13) https://bugs.python.org/issue20519

   (14) https://bugs.python.org/issue28293

   (15) https://bugs.python.org/issue31596

   (16) https://bugs.python.org/issue27494

   (17) https://bugs.python.org/issue30347

   (18) https://bugs.python.org/issue30346

   (19) https://bugs.python.org/issue31556

   (20) https://bugs.python.org/issue31540

   (21) https://bugs.python.org/issue31516

   (22) https://bugs.python.org/issue31525

   (23) https://bugs.python.org/issue26510

   (24) https://bugs.python.org/issue27541

   (25) https://bugs.python.org/issue31351

   (26) https://bugs.python.org/issue31389


File: python.info,  Node: 文档<34>,  Next: 构建<25>,  Prev: 库<39>,  Up: Python 3 7 0 alpha 2

1.18.40.3 文档
..............

   - bpo-31537(1): Fix incorrect usage of ‘get_history_length’ in
     readline documentation example code.  Patch by Brad Smith.

   - bpo-30085(2): The operator functions without double underscores are
     preferred for clarity.  The one with underscores are only kept for
     back-compatibility.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31537

   (2) https://bugs.python.org/issue30085


File: python.info,  Node: 构建<25>,  Next: IDLE<34>,  Prev: 文档<34>,  Up: Python 3 7 0 alpha 2

1.18.40.4 构建
..............

   - bpo-31696(1): Improve compiler version information in *note
     sys.version: 5dc. when Python is built with Clang.

   - bpo-31625(2): Stop using ranlib on static libraries.  Instead, we
     assume ar supports the ’s’ flag.

   - bpo-31624(3): 删除对 BSD/OS 的支持。

   - bpo-22140(4): Prevent double substitution of prefix in
     python-config.sh.

   - bpo-31569(5): Correct PCBuild/ case to PCbuild/ in build scripts
     and documentation.

   - bpo-31536(6): Avoid wholesale rebuild after ‘make regen-all’ if
     nothing changed.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31696

   (2) https://bugs.python.org/issue31625

   (3) https://bugs.python.org/issue31624

   (4) https://bugs.python.org/issue22140

   (5) https://bugs.python.org/issue31569

   (6) https://bugs.python.org/issue31536


File: python.info,  Node: IDLE<34>,  Next: C API<21>,  Prev: 构建<25>,  Up: Python 3 7 0 alpha 2

1.18.40.5 IDLE
..............

   - bpo-31460(1): Simplify the API of IDLE’s Module Browser.  Passing a
     widget instead of an flist with a root widget opens the option of
     creating a browser frame that is only part of a window.  Passing a
     full file name instead of pieces assumed to come from a .py file
     opens the possibility of browsing python files that do not end in
     .py.

   - bpo-31649(2): IDLE - Make _htest, _utest parameters keyword only.

   - bpo-31559(3): Remove test order dependence in
     idle_test.test_browser.

   - bpo-31459(4): Rename IDLE’s module browser from Class Browser to
     Module Browser.  The original module-level class and method browser
     became a module browser, with the addition of module-level
     functions, years ago.  Nested classes and functions were added
     yesterday.  For back-compatibility, the virtual event
     <<open-class-browser>>, which appears on the Keys tab of the
     Settings dialog, is not changed.  Patch by Cheryl Sabella.

   - bpo-31500(5): Default fonts now are scaled on HiDPI displays.

   - bpo-1612262(6): IDLE module browser now shows nested classes and
     functions.  Original patches for code and tests by Guilherme Polo
     and Cheryl Sabella, respectively.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31460

   (2) https://bugs.python.org/issue31649

   (3) https://bugs.python.org/issue31559

   (4) https://bugs.python.org/issue31459

   (5) https://bugs.python.org/issue31500

   (6) https://bugs.python.org/issue1612262


File: python.info,  Node: C API<21>,  Prev: IDLE<34>,  Up: Python 3 7 0 alpha 2

1.18.40.6 C API
...............

   - bpo-28280(1): Make ‘PyMapping_Keys()’, ‘PyMapping_Values()’ and
     ‘PyMapping_Items()’ always return a *note list: 263. (rather than a
     *note list: 263. or a *note tuple: 486.).  Patch by Oren Milman.

   - bpo-31532(2): Fix memory corruption due to allocator mix in
     getpath.c between Py_GetPath() and Py_SetPath()

   - bpo-25658(3): Implement PEP 539(4) for Thread Specific Storage
     (TSS) API: it is a new Thread Local Storage (TLS) API to CPython
     which would supersede use of the existing TLS API within the
     CPython interpreter, while deprecating the existing API. PEP
     written by Erik M. Bray, patch by Masayuki Yamamoto.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28280

   (2) https://bugs.python.org/issue31532

   (3) https://bugs.python.org/issue25658

   (4) https://www.python.org/dev/peps/pep-0539


File: python.info,  Node: Python 3 7 0 alpha 1,  Next: Python 3 6 6 正式版,  Prev: Python 3 7 0 alpha 2,  Up: 更新日志

1.18.41 Python 3.7.0 alpha 1
----------------------------

`发布日期: 2017-09-19'

* Menu:

* 安全: 安全<24>.
* 核心与内置: 核心与内置<39>.
* 库: 库<40>.
* 文档: 文档<35>.
* 测试: 测试<28>.
* 构建: 构建<26>.
* Windows: Windows<30>.
* IDLE: IDLE<35>.
* 工具/示例: 工具/示例<18>.
* C API: C API<22>.


File: python.info,  Node: 安全<24>,  Next: 核心与内置<39>,  Up: Python 3 7 0 alpha 1

1.18.41.1 安全
..............

   - bpo-29781(1): SSLObject.version() now correctly returns None when
     handshake over BIO has not been performed yet.

   - bpo-29505(2): Add fuzz tests for float(str), int(str),
     unicode(str); for oss-fuzz.

   - bpo-30947(3): Upgrade libexpat embedded copy from version 2.2.1 to
     2.2.3 to get security fixes.

   - bpo-30730(4): Prevent environment variables injection in subprocess
     on Windows.  Prevent passing other environment variables and
     command arguments.

   - bpo-30694(5): Upgrade expat copy from 2.2.0 to 2.2.1 to get fixes
     of multiple security vulnerabilities including: CVE-2017-9233
     (External entity infinite loop DoS), CVE-2016-9063 (Integer
     overflow, re-fix), CVE-2016-0718 (Fix regression bugs from 2.2.0’s
     fix to CVE-2016-0718) and CVE-2012-0876 (Counter hash flooding with
     SipHash).  Note: the CVE-2016-5300 (Use os-specific entropy sources
     like getrandom) doesn’t impact Python, since Python already gets
     entropy from the OS to set the expat secret using
     ‘XML_SetHashSalt()’.

   - bpo-30500(6): Fix urllib.parse.splithost() to correctly parse
     fragments.  For example, ‘splithost('//127.0.0.1#@evil.com/')’ now
     correctly returns the ‘127.0.0.1’ host, instead of treating
     ‘@evil.com’ as the host in an authentication (‘login@host’).

   - bpo-29591(7): Update expat copy from 2.1.1 to 2.2.0 to get fixes of
     CVE-2016-0718 and CVE-2016-4472.  See
     ‘https://sourceforge.net/p/expat/bugs/537/’ for more information.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29781

   (2) https://bugs.python.org/issue29505

   (3) https://bugs.python.org/issue30947

   (4) https://bugs.python.org/issue30730

   (5) https://bugs.python.org/issue30694

   (6) https://bugs.python.org/issue30500

   (7) https://bugs.python.org/issue29591


File: python.info,  Node: 核心与内置<39>,  Next: 库<40>,  Prev: 安全<24>,  Up: Python 3 7 0 alpha 1

1.18.41.2 核心与内置
....................

   - bpo-31490(1): Fix an assertion failure in *note ctypes: 2b. class
     definition, in case the class has an attribute whose name is
     specified in ‘_anonymous_’ but not in ‘_fields_’.  Patch by Oren
     Milman.

   - bpo-31471(2): Fix an assertion failure in *note subprocess.Popen():
     2ba. on Windows, in case the env argument has a bad keys() method.
     Patch by Oren Milman.

   - bpo-31418(3): Fix an assertion failure in ‘PyErr_WriteUnraisable()’
     in case of an exception with a bad ‘__module__’ attribute.  Patch
     by Oren Milman.

   - bpo-31416(4): Fix assertion failures in case of a bad
     warnings.filters or warnings.defaultaction.  Patch by Oren Milman.

   - bpo-28411(5): Change direct usage of PyInterpreterState.modules to
     PyImport_GetModuleDict().  Also introduce more uniformity in other
     code that deals with sys.modules.  This helps reduce complications
     when working on sys.modules.

   - bpo-28411(6): Switch to the abstract API when dealing with
     ‘PyInterpreterState.modules’.  This allows later support for all
     dict subclasses and other Mapping implementations.  Also add a
     ‘PyImport_GetModule()’ function to reduce a bunch of duplicated
     code.

   - bpo-31411(7): Raise a TypeError instead of SystemError in case
     warnings.onceregistry is not a dictionary.  Patch by Oren Milman.

   - bpo-31344(8): For finer control of tracing behaviour when testing
     the interpreter, two new frame attributes have been added to
     control the emission of particular trace events: ‘f_trace_lines’
     (‘True’ by default) to turn off per-line trace events; and
     ‘f_trace_opcodes’ (‘False’ by default) to turn on per-opcode trace
     events.

   - bpo-31373(9): Fix several possible instances of undefined behavior
     due to floating-point demotions.

   - bpo-30465(10): Location information (‘lineno’ and ‘col_offset’) in
     f-strings is now (mostly) correct.  This fixes tools like flake8
     from showing warnings on the wrong line (typically the first line
     of the file).

   - bpo-30860(11): Consolidate CPython’s global runtime state under a
     single struct.  This improves discoverability of the runtime state.

   - bpo-31347(12): Fix possible undefined behavior in
     _PyObject_FastCall_Prepend.

   - bpo-31343(13): Include sys/sysmacros.h for major(), minor(), and
     makedev().  GNU C libray plans to remove the functions from
     sys/types.h.

   - bpo-31291(14): Fix an assertion failure in *note
     zipimport.zipimporter.get_data: 10ca. on Windows, when the return
     value of ‘pathname.replace('/','\\')’ isn’t a string.  Patch by
     Oren Milman.

   - bpo-31271(15): Fix an assertion failure in the write() method of
     *note io.TextIOWrapper: 5fc, when the encoder doesn’t return a
     bytes object.  Patch by Oren Milman.

   - bpo-31243(16): Fix a crash in some methods of *note
     io.TextIOWrapper: 5fc, when the decoder’s state is invalid.  Patch
     by Oren Milman.

   - bpo-30721(17): ‘print’ now shows correct usage hint for using
     Python 2 redirection syntax.  Patch by Sanyam Khurana.

   - bpo-31070(18): Fix a race condition in importlib
     _get_module_lock().

   - bpo-30747(19): Add a non-dummy implementation of _Py_atomic_store
     and _Py_atomic_load on MSVC.

   - bpo-31095(20): Fix potential crash during GC caused by ‘tp_dealloc’
     which doesn’t call ‘PyObject_GC_UnTrack()’.

   - bpo-31071(21): Avoid masking original TypeError in call with *
     unpacking when other arguments are passed.

   - bpo-30978(22): str.format_map() now passes key lookup exceptions
     through.  Previously any exception was replaced with a KeyError
     exception.

   - bpo-30808(23): Use _Py_atomic API for concurrency-sensitive signal
     state.

   - bpo-30876(24): Relative import from unloaded package now reimports
     the package instead of failing with SystemError.  Relative import
     from non-package now fails with ImportError rather than
     SystemError.

   - bpo-30703(25): Improve signal delivery.  Avoid using
     Py_AddPendingCall from signal handler, to avoid calling
     signal-unsafe functions.  The tests I’m adding here fail without
     the rest of the patch, on Linux and OS X. This means our signal
     delivery logic had defects (some signals could be lost).

   - bpo-30765(26): Avoid blocking in pthread_mutex_lock() when
     PyThread_acquire_lock() is asked not to block.

   - bpo-31161(27): Make sure the ’Missing parentheses’ syntax error
     message is only applied to SyntaxError, not to subclasses.  Patch
     by Martijn Pieters.

   - bpo-30814(28): Fixed a race condition when import a submodule from
     a package.

   - bpo-30736(29): The internal unicodedata database has been upgraded
     to Unicode 10.0.

   - bpo-30604(30): Move co_extra_freefuncs from per-thread to
     per-interpreter to avoid crashes.

   - bpo-30597(31): ‘print’ now shows expected input in custom error
     message when used as a Python 2 statement.  Patch by Sanyam
     Khurana.

   - bpo-30682(32): Removed a too-strict assertion that failed for
     certain f-strings, such as eval("f’\n’") and eval("f’\r’").

   - bpo-30501(33): The compiler now produces more optimal code for
     complex condition expressions in the "if", "while" and "assert"
     statement, the "if" expression, and generator expressions and
     comprehensions.

   - bpo-28180(34): Implement PEP 538(35) (legacy C locale coercion).
     This means that when a suitable coercion target locale is
     available, both the core interpreter and locale-aware C extensions
     will assume the use of UTF-8 as the default text encoding, rather
     than ASCII.

   - bpo-30486(36): Allows setting cell values for __closure__.  Patch
     by Lisa Roach.

   - bpo-30537(37): itertools.islice now accepts integer-like objects
     (having an __index__ method) as start, stop, and slice arguments

   - bpo-25324(38): Tokens needed for parsing in Python moved to C.
     ‘COMMENT’, ‘NL’ and ‘ENCODING’.  This way the tokens and tok_names
     in the token module don’t get changed when you import the tokenize
     module.

   - bpo-29104(39): Fixed parsing backslashes in f-strings.

   - bpo-27945(40): Fixed various segfaults with dict when input
     collections are mutated during searching, inserting or comparing.
     Based on patches by Duane Griffin and Tim Mitchell.

   - bpo-25794(41): Fixed type.__setattr__() and type.__delattr__() for
     non-interned attribute names.  Based on patch by Eryk Sun.

   - bpo-30039(42): If a KeyboardInterrupt happens when the interpreter
     is in the middle of resuming a chain of nested ’yield from’ or
     ’await’ calls, it’s now correctly delivered to the innermost frame.

   - bpo-28974(43): ‘object.__format__(x, '')’ is now equivalent to
     ‘str(x)’ rather than ‘format(str(self), '')’.

   - bpo-30024(44): Circular imports involving absolute imports with
     binding a submodule to a name are now supported.

   - bpo-12414(45): sys.getsizeof() on a code object now returns the
     sizes which includes the code struct and sizes of objects which it
     references.  Patch by Dong-hee Na.

   - bpo-29839(46): len() now raises ValueError rather than
     OverflowError if __len__() returned a large negative integer.

   - bpo-11913(47): README.rst is now included in the list of distutils
     standard READMEs and therefore included in source distributions.

   - bpo-29914(48): Fixed default implementations of __reduce__ and
     __reduce_ex__().  object.__reduce__() no longer takes arguments,
     object.__reduce_ex__() now requires one argument.

   - bpo-29949(49): Fix memory usage regression of set and frozenset
     object.

   - bpo-29935(50): Fixed error messages in the index() method of tuple,
     list and deque when pass indices of wrong type.

   - bpo-29816(51): Shift operation now has less opportunity to raise
     OverflowError.  ValueError always is raised rather than
     OverflowError for negative counts.  Shifting zero with non-negative
     count always returns zero.

   - bpo-24821(52): Fixed the slowing down to 25 times in the searching
     of some unlucky Unicode characters.

   - bpo-29102(53): Add a unique ID to PyInterpreterState.  This makes
     it easier to identify each subinterpreter.

   - bpo-29894(54): The deprecation warning is emitted if __complex__
     returns an instance of a strict subclass of complex.  In a future
     versions of Python this can be an error.

   - bpo-29859(55): Show correct error messages when any of the
     pthread_* calls in thread_pthread.h fails.

   - bpo-29849(56): Fix a memory leak when an ImportError is raised
     during from import.

   - bpo-28856(57): Fix an oversight that %b format for bytes should
     support objects follow the buffer protocol.

   - bpo-29723(58): The ‘sys.path[0]’ initialization change for
     bpo-29139(59) caused a regression by revealing an inconsistency in
     how sys.path is initialized when executing ‘__main__’ from a
     zipfile, directory, or other import location.  The interpreter now
     consistently avoids ever adding the import location’s parent
     directory to ‘sys.path’, and ensures no other ‘sys.path’ entries
     are inadvertently modified when inserting the import location named
     on the command line.

   - bpo-29568(60): Escaped percent "%%" in the format string for
     classic string formatting no longer allows any characters between
     two percents.

   - bpo-29714(61): Fix a regression that bytes format may fail when
     containing zero bytes inside.

   - bpo-29695(62): bool(), float(), list() and tuple() no longer take
     keyword arguments.  The first argument of int() can now be passes
     only as positional argument.

   - bpo-28893(63): Set correct __cause__ for errors about invalid
     awaitables returned from __aiter__ and __anext__.

   - bpo-28876(64): ‘bool(range)’ works even if ‘len(range)’ raises
     *note OverflowError: 968.

   - bpo-29683(65): Fixes to memory allocation in _PyCode_SetExtra.
     Patch by Brian Coleman.

   - bpo-29684(66): Fix minor regression of
     PyEval_CallObjectWithKeywords.  It should raise TypeError when
     kwargs is not a dict.  But it might cause segv when args=NULL and
     kwargs is not a dict.

   - bpo-28598(67): Support __rmod__ for subclasses of str being called
     before str.__mod__.  Patch by Martijn Pieters.

   - bpo-29607(68): Fix stack_effect computation for CALL_FUNCTION_EX.
     Patch by Matthieu Dartiailh.

   - bpo-29602(69): Fix incorrect handling of signed zeros in complex
     constructor for complex subclasses and for inputs having a
     __complex__ method.  Patch by Serhiy Storchaka.

   - bpo-29347(70): Fixed possibly dereferencing undefined pointers when
     creating weakref objects.

   - bpo-29463(71): Add ‘docstring’ field to Module, ClassDef,
     FunctionDef, and AsyncFunctionDef ast nodes.  docstring is not
     first stmt in their body anymore.  It affects ‘co_firstlineno’ and
     ‘co_lnotab’ of code object for module and class.  (Reverted in
     bpo-32911(72).)

   - bpo-29438(73): Fixed use-after-free problem in key sharing dict.

   - bpo-29546(74): Set the ’path’ and ’name’ attribute on ImportError
     for ‘from ... import ...’.

   - bpo-29546(75): Improve from-import error message with location

   - bpo-29478(76): If max_line_length=None is specified while using the
     Compat32 policy, it is no longer ignored.  Patch by Mircea Cosbuc.

   - bpo-29319(77): Prevent RunMainFromImporter overwriting sys.path[0].

   - bpo-29337(78): Fixed possible BytesWarning when compare the code
     objects.  Warnings could be emitted at compile time.

   - bpo-29327(79): Fixed a crash when pass the iterable keyword
     argument to sorted().

   - bpo-29034(80): Fix memory leak and use-after-free in os module
     (path_converter).

   - bpo-29159(81): Fix regression in bytes(x) when x.__index__() raises
     Exception.

   - bpo-29049(82): Call _PyObject_GC_TRACK() lazily when calling Python
     function.  Calling function is up to 5% faster.

   - bpo-28927(83): bytes.fromhex() and bytearray.fromhex() now ignore
     all ASCII whitespace, not only spaces.  Patch by Robert Xiao.

   - bpo-28932(84): Do not include <sys/random.h> if it does not exist.

   - bpo-25677(85): Correct the positioning of the syntax error caret
     for indented blocks.  Based on patch by Michael Layzell.

   - bpo-29000(86): Fixed bytes formatting of octals with zero padding
     in alternate form.

   - bpo-18896(87): Python function can now have more than 255
     parameters.  collections.namedtuple() now supports tuples with more
     than 255 elements.

   - bpo-28596(88): The preferred encoding is UTF-8 on Android.  Patch
     written by Chi Hsuan Yen.

   - bpo-22257(89): Clean up interpreter startup (see PEP 432(90)).

   - bpo-26919(91): On Android, operating system data is now always
     encoded/decoded to/from UTF-8, instead of the locale encoding to
     avoid inconsistencies with os.fsencode() and os.fsdecode() which
     are already using UTF-8.

   - bpo-28991(92): functools.lru_cache() was susceptible to an obscure
     reentrancy bug triggerable by a monkey-patched len() function.

   - bpo-28147(93): Fix a memory leak in split-table dictionaries:
     setattr() must not convert combined table into split table.  Patch
     written by INADA Naoki.

   - bpo-28739(94): f-string expressions are no longer accepted as
     docstrings and by ast.literal_eval() even if they do not include
     expressions.

   - bpo-28512(95): Fixed setting the offset attribute of SyntaxError by
     PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

   - bpo-28918(96): Fix the cross compilation of xxlimited when Python
     has been built with Py_DEBUG defined.

   - bpo-23722(97): Rather than silently producing a class that doesn’t
     support zero-argument ‘super()’ in methods, failing to pass the new
     ‘__classcell__’ namespace entry up to ‘type.__new__’ now results in
     a ‘DeprecationWarning’ and a class that supports zero-argument
     ‘super()’.

   - bpo-28797(98): Modifying the class __dict__ inside the __set_name__
     method of a descriptor that is used inside that class no longer
     prevents calling the __set_name__ method of other descriptors.

   - bpo-28799(99): Remove the ‘PyEval_GetCallStats()’ function and
     deprecate the untested and undocumented ‘sys.callstats()’ function.
     Remove the ‘CALL_PROFILE’ special build: use the *note
     sys.setprofile(): e45. function, *note cProfile: 28. or *note
     profile: d4. to profile function calls.

   - bpo-12844(100): More than 255 arguments can now be passed to a
     function.

   - bpo-28782(101): Fix a bug in the implementation ‘yield from’ when
     checking if the next instruction is YIELD_FROM. Regression
     introduced by WORDCODE (bpo-26647(102)).

   - bpo-28774(103): Fix error position of the unicode error in ASCII
     and Latin1 encoders when a string returned by the error handler
     contains multiple non-encodable characters (non-ASCII for the ASCII
     codec, characters out of the U+0000-U+00FF range for Latin1).

   - bpo-28731(104): Optimize _PyDict_NewPresized() to create correct
     size dict.  Improve speed of dict literal with constant keys up to
     30%.

   - bpo-28532(105): Show sys.version when -V option is supplied twice.

   - bpo-27100(106): The with-statement now checks for __enter__ before
     it checks for __exit__.  This gives less confusing error messages
     when both methods are missing.  Patch by Jonathan Ellington.

   - bpo-28746(107): Fix the set_inheritable() file descriptor method on
     platforms that do not have the ioctl FIOCLEX and FIONCLEX commands.

   - bpo-26920(108): Fix not getting the locale’s charset upon
     initializing the interpreter, on platforms that do not have
     langinfo.

   - bpo-28648(109): Fixed crash in Py_DecodeLocale() in debug build on
     Mac OS X when decode astral characters.  Patch by Xiang Zhang.

   - bpo-28665(110): Improve speed of the STORE_DEREF opcode by 40%.

   - bpo-19398(111): Extra slash no longer added to sys.path components
     in case of empty compile-time PYTHONPATH components.

   - bpo-28621(112): Sped up converting int to float by reusing faster
     bits counting implementation.  Patch by Adrian Wielgosik.

   - bpo-28580(113): Optimize iterating split table values.  Patch by
     Xiang Zhang.

   - bpo-28583(114): PyDict_SetDefault didn’t combine split table when
     needed.  Patch by Xiang Zhang.

   - bpo-28128(115): Deprecation warning for invalid str and byte escape
     sequences now prints better information about where the error
     occurs.  Patch by Serhiy Storchaka and Eric Smith.

   - bpo-28509(116): dict.update() no longer allocate unnecessary large
     memory.

   - bpo-28426(117): Fixed potential crash in
     PyUnicode_AsDecodedObject() in debug build.

   - bpo-28517(118): Fixed of-by-one error in the peephole optimizer
     that caused keeping unreachable code.

   - bpo-28214(119): Improved exception reporting for problematic
     __set_name__ attributes.

   - bpo-23782(120): Fixed possible memory leak in _PyTraceback_Add()
     and exception loss in PyTraceBack_Here().

   - bpo-28183(121): Optimize and cleanup dict iteration.

   - bpo-26081(122): Added C implementation of asyncio.Future.  Original
     patch by Yury Selivanov.

   - bpo-28379(123): Added sanity checks and tests for
     PyUnicode_CopyCharacters().  Patch by Xiang Zhang.

   - bpo-28376(124): The type of long range iterator is now registered
     as Iterator.  Patch by Oren Milman.

   - bpo-28376(125): Creating instances of range_iterator by calling
     range_iterator type now is disallowed.  Calling iter() on range
     instance is the only way.  Patch by Oren Milman.

   - bpo-26906(126): Resolving special methods of uninitialized type now
     causes implicit initialization of the type instead of a fail.

   - bpo-18287(127): PyType_Ready() now checks that tp_name is not NULL.
     Original patch by Niklas Koep.

   - bpo-24098(128): Fixed possible crash when AST is changed in process
     of compiling it.

   - bpo-28201(129): Dict reduces possibility of 2nd conflict in hash
     table when hashes have same lower bits.

   - bpo-28350(130): String constants with null character no longer
     interned.

   - bpo-26617(131): Fix crash when GC runs during weakref callbacks.

   - bpo-27942(132): String constants now interned recursively in tuples
     and frozensets.

   - bpo-28289(133): ImportError.__init__ now resets not specified
     attributes.

   - bpo-21578(134): Fixed misleading error message when ImportError
     called with invalid keyword args.

   - bpo-28203(135): Fix incorrect type in complex(1.0, {2:3}) error
     message.  Patch by Soumya Sharma.

   - bpo-28086(136): Single var-positional argument of tuple subtype was
     passed unscathed to the C-defined function.  Now it is converted to
     exact tuple.

   - bpo-28214(137): Now __set_name__ is looked up on the class instead
     of the instance.

   - bpo-27955(138): Fallback on reading /dev/urandom device when the
     getrandom() syscall fails with EPERM, for example when blocked by
     SECCOMP.

   - bpo-28192(139): Don’t import readline in isolated mode.

   - bpo-27441(140): Remove some redundant assignments to ob_size in
     longobject.c.  Thanks Oren Milman.

   - bpo-27222(141): Clean up redundant code in long_rshift function.
     Thanks Oren Milman.

   - Upgrade internal unicode databases to Unicode version 9.0.0.

   - bpo-28131(142): Fix a regression in zipimport’s compile_source().
     zipimport should use the same optimization level as the
     interpreter.

   - bpo-28126(143): Replace Py_MEMCPY with memcpy().  Visual Studio can
     properly optimize memcpy().

   - bpo-28120(144): Fix dict.pop() for splitted dictionary when trying
     to remove a "pending key" (Not yet inserted in split-table).  Patch
     by Xiang Zhang.

   - bpo-26182(145): Raise DeprecationWarning when async and await
     keywords are used as variable/attribute/class/function name.

   - bpo-26182(146): Fix a refleak in code that raises
     DeprecationWarning.

   - bpo-28721(147): Fix asynchronous generators aclose() and athrow()
     to handle StopAsyncIteration propagation properly.

   - bpo-26110(148): Speed-up method calls: add LOAD_METHOD and
     CALL_METHOD opcodes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31490

   (2) https://bugs.python.org/issue31471

   (3) https://bugs.python.org/issue31418

   (4) https://bugs.python.org/issue31416

   (5) https://bugs.python.org/issue28411

   (6) https://bugs.python.org/issue28411

   (7) https://bugs.python.org/issue31411

   (8) https://bugs.python.org/issue31344

   (9) https://bugs.python.org/issue31373

   (10) https://bugs.python.org/issue30465

   (11) https://bugs.python.org/issue30860

   (12) https://bugs.python.org/issue31347

   (13) https://bugs.python.org/issue31343

   (14) https://bugs.python.org/issue31291

   (15) https://bugs.python.org/issue31271

   (16) https://bugs.python.org/issue31243

   (17) https://bugs.python.org/issue30721

   (18) https://bugs.python.org/issue31070

   (19) https://bugs.python.org/issue30747

   (20) https://bugs.python.org/issue31095

   (21) https://bugs.python.org/issue31071

   (22) https://bugs.python.org/issue30978

   (23) https://bugs.python.org/issue30808

   (24) https://bugs.python.org/issue30876

   (25) https://bugs.python.org/issue30703

   (26) https://bugs.python.org/issue30765

   (27) https://bugs.python.org/issue31161

   (28) https://bugs.python.org/issue30814

   (29) https://bugs.python.org/issue30736

   (30) https://bugs.python.org/issue30604

   (31) https://bugs.python.org/issue30597

   (32) https://bugs.python.org/issue30682

   (33) https://bugs.python.org/issue30501

   (34) https://bugs.python.org/issue28180

   (35) https://www.python.org/dev/peps/pep-0538

   (36) https://bugs.python.org/issue30486

   (37) https://bugs.python.org/issue30537

   (38) https://bugs.python.org/issue25324

   (39) https://bugs.python.org/issue29104

   (40) https://bugs.python.org/issue27945

   (41) https://bugs.python.org/issue25794

   (42) https://bugs.python.org/issue30039

   (43) https://bugs.python.org/issue28974

   (44) https://bugs.python.org/issue30024

   (45) https://bugs.python.org/issue12414

   (46) https://bugs.python.org/issue29839

   (47) https://bugs.python.org/issue11913

   (48) https://bugs.python.org/issue29914

   (49) https://bugs.python.org/issue29949

   (50) https://bugs.python.org/issue29935

   (51) https://bugs.python.org/issue29816

   (52) https://bugs.python.org/issue24821

   (53) https://bugs.python.org/issue29102

   (54) https://bugs.python.org/issue29894

   (55) https://bugs.python.org/issue29859

   (56) https://bugs.python.org/issue29849

   (57) https://bugs.python.org/issue28856

   (58) https://bugs.python.org/issue29723

   (59) https://bugs.python.org/issue29139

   (60) https://bugs.python.org/issue29568

   (61) https://bugs.python.org/issue29714

   (62) https://bugs.python.org/issue29695

   (63) https://bugs.python.org/issue28893

   (64) https://bugs.python.org/issue28876

   (65) https://bugs.python.org/issue29683

   (66) https://bugs.python.org/issue29684

   (67) https://bugs.python.org/issue28598

   (68) https://bugs.python.org/issue29607

   (69) https://bugs.python.org/issue29602

   (70) https://bugs.python.org/issue29347

   (71) https://bugs.python.org/issue29463

   (72) https://bugs.python.org/issue32911

   (73) https://bugs.python.org/issue29438

   (74) https://bugs.python.org/issue29546

   (75) https://bugs.python.org/issue29546

   (76) https://bugs.python.org/issue29478

   (77) https://bugs.python.org/issue29319

   (78) https://bugs.python.org/issue29337

   (79) https://bugs.python.org/issue29327

   (80) https://bugs.python.org/issue29034

   (81) https://bugs.python.org/issue29159

   (82) https://bugs.python.org/issue29049

   (83) https://bugs.python.org/issue28927

   (84) https://bugs.python.org/issue28932

   (85) https://bugs.python.org/issue25677

   (86) https://bugs.python.org/issue29000

   (87) https://bugs.python.org/issue18896

   (88) https://bugs.python.org/issue28596

   (89) https://bugs.python.org/issue22257

   (90) https://www.python.org/dev/peps/pep-0432

   (91) https://bugs.python.org/issue26919

   (92) https://bugs.python.org/issue28991

   (93) https://bugs.python.org/issue28147

   (94) https://bugs.python.org/issue28739

   (95) https://bugs.python.org/issue28512

   (96) https://bugs.python.org/issue28918

   (97) https://bugs.python.org/issue23722

   (98) https://bugs.python.org/issue28797

   (99) https://bugs.python.org/issue28799

   (100) https://bugs.python.org/issue12844

   (101) https://bugs.python.org/issue28782

   (102) https://bugs.python.org/issue26647

   (103) https://bugs.python.org/issue28774

   (104) https://bugs.python.org/issue28731

   (105) https://bugs.python.org/issue28532

   (106) https://bugs.python.org/issue27100

   (107) https://bugs.python.org/issue28746

   (108) https://bugs.python.org/issue26920

   (109) https://bugs.python.org/issue28648

   (110) https://bugs.python.org/issue28665

   (111) https://bugs.python.org/issue19398

   (112) https://bugs.python.org/issue28621

   (113) https://bugs.python.org/issue28580

   (114) https://bugs.python.org/issue28583

   (115) https://bugs.python.org/issue28128

   (116) https://bugs.python.org/issue28509

   (117) https://bugs.python.org/issue28426

   (118) https://bugs.python.org/issue28517

   (119) https://bugs.python.org/issue28214

   (120) https://bugs.python.org/issue23782

   (121) https://bugs.python.org/issue28183

   (122) https://bugs.python.org/issue26081

   (123) https://bugs.python.org/issue28379

   (124) https://bugs.python.org/issue28376

   (125) https://bugs.python.org/issue28376

   (126) https://bugs.python.org/issue26906

   (127) https://bugs.python.org/issue18287

   (128) https://bugs.python.org/issue24098

   (129) https://bugs.python.org/issue28201

   (130) https://bugs.python.org/issue28350

   (131) https://bugs.python.org/issue26617

   (132) https://bugs.python.org/issue27942

   (133) https://bugs.python.org/issue28289

   (134) https://bugs.python.org/issue21578

   (135) https://bugs.python.org/issue28203

   (136) https://bugs.python.org/issue28086

   (137) https://bugs.python.org/issue28214

   (138) https://bugs.python.org/issue27955

   (139) https://bugs.python.org/issue28192

   (140) https://bugs.python.org/issue27441

   (141) https://bugs.python.org/issue27222

   (142) https://bugs.python.org/issue28131

   (143) https://bugs.python.org/issue28126

   (144) https://bugs.python.org/issue28120

   (145) https://bugs.python.org/issue26182

   (146) https://bugs.python.org/issue26182

   (147) https://bugs.python.org/issue28721

   (148) https://bugs.python.org/issue26110


File: python.info,  Node: 库<40>,  Next: 文档<35>,  Prev: 核心与内置<39>,  Up: Python 3 7 0 alpha 1

1.18.41.3 库
............

   - bpo-31499(1): xml.etree: Fix a crash when a parser is part of a
     reference cycle.

   - bpo-31482(2): ‘random.seed()’ now works with bytes in version=1

   - bpo-28556(3): typing.get_type_hints now finds the right globalns
     for classes and modules by default (when no ‘globalns’ was
     specified by the caller).

   - bpo-28556(4): Speed improvements to the ‘typing’ module.  Original
     PRs by Ivan Levkivskyi and Mitar.

   - bpo-31544(5): The C accelerator module of ElementTree ignored
     exceptions raised when looking up TreeBuilder target methods in
     XMLParser().

   - bpo-31234(6): socket.create_connection() now fixes manually a
     reference cycle: clear the variable storing the last exception on
     success.

   - bpo-31457(7): LoggerAdapter objects can now be nested.

   - bpo-31431(8): SSLContext.check_hostname now automatically sets
     SSLContext.verify_mode to ssl.CERT_REQUIRED instead of failing with
     a ValueError.

   - bpo-31233(9): socketserver.ThreadingMixIn now keeps a list of
     non-daemonic threads to wait until all these threads complete in
     server_close().

   - bpo-28638(10): Changed the implementation strategy for
     collections.namedtuple() to substantially reduce the use of exec()
     in favor of precomputed methods.  As a result, the `verbose'
     parameter and `_source' attribute are no longer supported.  The
     benefits include 1) having a smaller memory footprint for
     applications using multiple named tuples, 2) faster creation of the
     named tuple class (approx 4x to 6x depending on how it is
     measured), and 3) minor speed-ups for instance creation using
     __new__, _make, and _replace.  (The primary patch contributor is
     Jelle Zijlstra with further improvements by INADA Naoki, Serhiy
     Storchaka, and Raymond Hettinger.)

   - bpo-31400(11): Improves SSL error handling to avoid losing error
     numbers.

   - bpo-27629(12): Make return types of SSLContext.wrap_bio() and
     SSLContext.wrap_socket() customizable.

   - bpo-28958(13): ssl.SSLContext() now uses OpenSSL error information
     when a context cannot be instantiated.

   - bpo-28182(14): The SSL module now raises SSLCertVerificationError
     when OpenSSL fails to verify the peer’s certificate.  The exception
     contains more information about the error.

   - bpo-27340(15): SSLSocket.sendall() now uses memoryview to create
     slices of data.  This fixes support for all bytes-like object.  It
     is also more efficient and avoids costly copies.

   - bpo-14191(16): A new function
     ‘argparse.ArgumentParser.parse_intermixed_args’ provides the
     ability to parse command lines where there user intermixes options
     and positional arguments.

   - bpo-31178(17): Fix string concatenation bug in rare error path in
     the subprocess module

   - bpo-31350(18): Micro-optimize ‘asyncio._get_running_loop()’ to
     become up to 10% faster.

   - bpo-31170(19): expat: Update libexpat from 2.2.3 to 2.2.4.  Fix
     copying of partial characters for UTF-8 input (libexpat bug 115):
     ‘https://github.com/libexpat/libexpat/issues/115’

   - bpo-29136(20): Add TLS 1.3 cipher suites and OP_NO_TLSv1_3.

   - bpo-1198569(21): ‘string.Template’ subclasses can optionally define
     ‘braceidpattern’ if they want to specify different placeholder
     patterns inside and outside the braces.  If None (the default) it
     falls back to ‘idpattern’.

   - bpo-31326(22): concurrent.futures.ProcessPoolExecutor.shutdown()
     now explicitly closes the call queue.  Moreover,
     shutdown(wait=True) now also join the call queue thread, to prevent
     leaking a dangling thread.

   - bpo-27144(23): The ‘map()’ and ‘as_completed()’ iterators in
     ‘concurrent.futures’ now avoid keeping a reference to yielded
     objects.

   - bpo-31281(24): Fix ‘fileinput.FileInput(files, inplace=True)’ when
     ‘files’ contain ‘pathlib.Path’ objects.

   - bpo-10746(25): Fix ctypes producing wrong PEP 3118(26) type codes
     for integer types.

   - bpo-27584(27): ‘AF_VSOCK’ has been added to the socket interface
     which allows communication between virtual machines and their host.

   - bpo-22536(28): The subprocess module now sets the filename when
     FileNotFoundError is raised on POSIX systems due to the executable
     or cwd not being found.

   - bpo-29741(29): Update some methods in the _pyio module to also
     accept integer types.  Patch by Oren Milman.

   - bpo-31249(30): concurrent.futures: WorkItem.run() used by
     ThreadPoolExecutor now breaks a reference cycle between an
     exception object and the WorkItem object.

   - bpo-31247(31): xmlrpc.server now explicitly breaks reference cycles
     when using sys.exc_info() in code handling exceptions.

   - bpo-23835(32): configparser: reading defaults in the
     ‘ConfigParser()’ constructor is now using ‘read_dict()’, making its
     behavior consistent with the rest of the parser.  Non-string keys
     and values in the defaults dictionary are now being implicitly
     converted to strings.  Patch by James Tocknell.

   - bpo-31238(33): pydoc: the stop() method of the private ServerThread
     class now waits until DocServer.serve_until_quit() completes and
     then explicitly sets its docserver attribute to None to break a
     reference cycle.

   - bpo-5001(34): Many asserts in *note multiprocessing: b8. are now
     more informative, and some error types have been changed to more
     specific ones.

   - bpo-31109(35): Convert zipimport to use Argument Clinic.

   - bpo-30102(36): The ssl and hashlib modules now call
     OPENSSL_add_all_algorithms_noconf() on OpenSSL < 1.1.0.  The
     function detects CPU features and enables optimizations on some CPU
     architectures such as POWER8.  Patch is based on research from
     Gustavo Serra Scalet.

   - bpo-18966(37): Non-daemonic threads created by a
     multiprocessing.Process are now joined on child exit.

   - bpo-31183(38): *note dis: 38. now works with asynchronous generator
     and coroutine objects.  Patch by George Collins based on diagnosis
     by Luciano Ramalho.

   - bpo-5001(39): There are a number of uninformative asserts in the
     *note multiprocessing: b8. module, as noted in issue 5001.  This
     change fixes two of the most potentially problematic ones, since
     they are in error-reporting code, in the
     ‘multiprocessing.managers.convert_to_error’ function.  (It also
     makes more informative a ValueError message.)  The only potentially
     problematic change is that the AssertionError is now a TypeError;
     however, this should also help distinguish it from an
     AssertionError being `reported' by the function/its caller (such as
     in issue 31169).  - Patch by Allen W. Smith (drallensmith on
     github).

   - bpo-31185(40): Fixed miscellaneous errors in asyncio speedup
     module.

   - bpo-31151(41): socketserver.ForkingMixIn.server_close() now waits
     until all child processes completed to prevent leaking zombie
     processes.

   - bpo-31072(42): Add an ‘include_file’ parameter to
     ‘zipapp.create_archive()’

   - bpo-24700(43): Optimize array.array comparison.  It is now from 10x
     up to 70x faster when comparing arrays holding values of the same
     integer type.

   - bpo-31135(44): ttk: fix the destroy() method of LabeledScale and
     OptionMenu classes.  Call the parent destroy() method even if the
     used attribute doesn’t exist.  The LabeledScale.destroy() method
     now also explicitly clears label and scale attributes to help the
     garbage collector to destroy all widgets.

   - bpo-31107(45): Fix ‘copyreg._slotnames()’ mangled attribute
     calculation for classes whose name begins with an underscore.
     Patch by Shane Harvey.

   - bpo-31080(46): Allow *note logging.config.fileConfig: 3b1. to
     accept kwargs and/or args.

   - bpo-30897(47): ‘pathlib.Path’ objects now include an ‘is_mount()’
     method (only implemented on POSIX). This is similar to
     ‘os.path.ismount(p)’.  Patch by Cooper Ry Lees.

   - bpo-31061(48): Fixed a crash when using asyncio and threads.

   - bpo-30987(49): Added support for CAN ISO-TP protocol in the socket
     module.

   - bpo-30522(50): Added a ‘setStream’ method to
     ‘logging.StreamHandler’ to allow the stream to be set after
     creation.

   - bpo-30502(51): Fix handling of long oids in ssl.  Based on patch by
     Christian Heimes.

   - bpo-5288(52): Support tzinfo objects with sub-minute offsets.

   - bpo-30919(53): Fix shared memory performance regression in
     multiprocessing in 3.x.  Shared memory used anonymous memory
     mappings in 2.x, while 3.x mmaps actual files.  Try to be careful
     to do as little disk I/O as possible.

   - bpo-26732(54): Fix too many fds in processes started with the
     "forkserver" method.  A child process would inherit as many fds as
     the number of still-running children.

   - bpo-29403(55): Fix ‘unittest.mock’’s autospec to not fail on
     method-bound builtin functions.  Patch by Aaron Gallagher.

   - bpo-30961(56): Fix decrementing a borrowed reference in
     tracemalloc.

   - bpo-19896(57): Fix multiprocessing.sharedctypes to recognize
     typecodes ‘'q'’ and ‘'Q'’.

   - bpo-30946(58): Remove obsolete code in readline module for
     platforms where GNU readline is older than 2.1 or where select() is
     not available.

   - bpo-25684(59): Change ‘ttk.OptionMenu’ radiobuttons to be unique
     across instances of ‘OptionMenu’.

   - bpo-30886(60): Fix multiprocessing.Queue.join_thread(): it now
     waits until the thread completes, even if the thread was started by
     the same process which created the queue.

   - bpo-29854(61): Fix segfault in readline when using readline’s
     history-size option.  Patch by Nir Soffer.

   - bpo-30794(62): Added multiprocessing.Process.kill method to
     terminate using the SIGKILL signal on Unix.

   - bpo-30319(63): socket.close() now ignores ECONNRESET error.

   - bpo-30828(64): Fix out of bounds write in
     ‘asyncio.CFuture.remove_done_callback()’.

   - bpo-30302(65): Use keywords in the ‘repr’ of ‘datetime.timedelta’.

   - bpo-30807(66): signal.setitimer() may disable the timer when passed
     a tiny value.  Tiny values (such as 1e-6) are valid non-zero values
     for setitimer(), which is specified as taking
     microsecond-resolution intervals.  However, on some platform, our
     conversion routine could convert 1e-6 into a zero interval,
     therefore disabling the timer instead of (re-)scheduling it.

   - bpo-30441(67): Fix bug when modifying os.environ while iterating
     over it

   - bpo-29585(68): Avoid importing ‘sysconfig’ from ‘site’ to improve
     startup speed.  Python startup is about 5% faster on Linux and 30%
     faster on macOS.

   - bpo-29293(69): Add missing parameter "n" on
     multiprocessing.Condition.notify().  The doc claims
     multiprocessing.Condition behaves like threading.Condition, but its
     notify() method lacked the optional "n" argument (to specify the
     number of sleepers to wake up) that threading.Condition.notify()
     accepts.

   - bpo-30532(70): Fix email header value parser dropping folding white
     space in certain cases.

   - bpo-30596(71): Add a ‘close()’ method to ‘multiprocessing.Process’.

   - bpo-9146(72): Fix a segmentation fault in _hashopenssl when
     standard hash functions such as md5 are not available in the linked
     OpenSSL library.  As in some special FIPS-140 build environments.

   - bpo-29169(73): Update zlib to 1.2.11.

   - bpo-30119(74): ftplib.FTP.putline() now throws ValueError on
     commands that contains CR or LF. Patch by Dong-hee Na.

   - bpo-30879(75): os.listdir() and os.scandir() now emit bytes names
     when called with bytes-like argument.

   - bpo-30746(76): Prohibited the ’=’ character in environment variable
     names in ‘os.putenv()’ and ‘os.spawn*()’.

   - bpo-30664(77): The description of a unittest subtest now preserves
     the order of keyword arguments of TestCase.subTest().

   - bpo-21071(78): struct.Struct.format type is now *note str: 339.
     instead of *note bytes: 33a.

   - bpo-29212(79): Fix concurrent.futures.thread.ThreadPoolExecutor
     threads to have a non repr() based thread name by default when no
     thread_name_prefix is supplied.  They will now identify themselves
     as "ThreadPoolExecutor-y_n".

   - bpo-29755(80): Fixed the lgettext() family of functions in the
     gettext module.  They now always return bytes.

   - bpo-30616(81): Functional API of enum allows to create empty enums.
     Patched by Dong-hee Na

   - bpo-30038(82): Fix race condition between signal delivery and
     wakeup file descriptor.  Patch by Nathaniel Smith.

   - bpo-23894(83): lib2to3 now recognizes ‘rb'...'’ and ‘f'...'’
     strings.

   - bpo-24744(84): pkgutil.walk_packages function now raises ValueError
     if `path' is a string.  Patch by Sanyam Khurana.

   - bpo-24484(85): Avoid race condition in multiprocessing cleanup.

   - bpo-30589(86): Fix multiprocessing.Process.exitcode to return the
     opposite of the signal number when the process is killed by a
     signal (instead of 255) when using the "forkserver" method.

   - bpo-28994(87): The traceback no longer displayed for SystemExit
     raised in a callback registered by atexit.

   - bpo-30508(88): Don’t log exceptions if Task/Future "cancel()"
     method was called.

   - bpo-30645(89): Fix path calculation in ‘imp.load_package()’, fixing
     it for cases when a package is only shipped with bytecodes.  Patch
     by Alexandru Ardelean.

   - bpo-11822(90): The dis.dis() function now is able to disassemble
     nested code objects.

   - bpo-30624(91): selectors does not take KeyboardInterrupt and
     SystemExit into account, leaving a fd in a bad state in case of
     error.  Patch by Giampaolo Rodola’.

   - bpo-30595(92): multiprocessing.Queue.get() with a timeout now polls
     its reader in non-blocking mode if it succeeded to acquire the lock
     but the acquire took longer than the timeout.

   - bpo-28556(93): Updates to typing module: Add generic
     AsyncContextManager, add support for ContextManager on all
     versions.  Original PRs by Jelle Zijlstra and Ivan Levkivskyi

   - bpo-30605(94): re.compile() no longer raises a BytesWarning when
     compiling a bytes instance with misplaced inline modifier.  Patch
     by Roy Williams.

   - bpo-29870(95): Fix ssl sockets leaks when connection is aborted in
     asyncio/ssl implementation.  Patch by Michaël Sghaïer.

   - bpo-29743(96): Closing transport during handshake process leaks
     open socket.  Patch by Nikolay Kim

   - bpo-27585(97): Fix waiter cancellation in asyncio.Lock.  Patch by
     Mathieu Sornay.

   - bpo-30014(98): modify() method of poll(), epoll() and devpoll()
     based classes of selectors module is around 10% faster.  Patch by
     Giampaolo Rodola’.

   - bpo-30418(99): On Windows, subprocess.Popen.communicate() now also
     ignore EINVAL on stdin.write() if the child process is still
     running but closed the pipe.

   - bpo-30463(100): Addded empty __slots__ to abc.ABC. This allows
     subclassers to deny __dict__ and __weakref__ creation.  Patch by
     Aaron Hall.

   - bpo-30520(101): Loggers are now pickleable.

   - bpo-30557(102): faulthandler now correctly filters and displays
     exception codes on Windows

   - bpo-30526(103): Add TextIOWrapper.reconfigure() and a
     TextIOWrapper.write_through attribute.

   - bpo-30245(104): Fix possible overflow when organize
     struct.pack_into error message.  Patch by Yuan Liu.

   - bpo-30378(105): Fix the problem that logging.handlers.SysLogHandler
     cannot handle IPv6 addresses.

   - bpo-16500(106): Allow registering at-fork handlers.

   - bpo-30470(107): Deprecate invalid ctypes call protection on
     Windows.  Patch by Mariatta Wijaya.

   - bpo-30414(108): multiprocessing.Queue._feed background running
     thread do not break from main loop on exception.

   - bpo-30003(109): Fix handling escape characters in HZ codec.  Based
     on patch by Ma Lin.

   - bpo-30149(110): inspect.signature() now supports callables with
     variable-argument parameters wrapped with partialmethod.  Patch by
     Dong-hee Na.

   - bpo-30436(111): importlib.find_spec() raises ModuleNotFoundError
     instead of AttributeError if the specified parent module is not a
     package (i.e.  lacks a __path__ attribute).

   - bpo-30301(112): Fix AttributeError when using SimpleQueue.empty()
     under `spawn' and `forkserver' start methods.

   - bpo-30375(113): Warnings emitted when compile a regular expression
     now always point to the line in the user code.  Previously they
     could point into inners of the re module if emitted from inside of
     groups or conditionals.

   - bpo-30329(114): imaplib and poplib now catch the Windows socket
     WSAEINVAL error (code 10022) on shutdown(SHUT_RDWR): An invalid
     operation was attempted.  This error occurs sometimes on SSL
     connections.

   - bpo-29196(115): Removed previously deprecated in Python 2.4 classes
     Plist, Dict and _InternalDict in the plistlib module.  Dict values
     in the result of functions readPlist() and readPlistFromBytes() are
     now normal dicts.  You no longer can use attribute access to access
     items of these dictionaries.

   - bpo-9850(116): The ‘macpath’ is now deprecated and will be removed
     in Python 3.8.

   - bpo-30299(117): Compiling regular expression in debug mode on
     CPython now displays the compiled bytecode in human readable form.

   - bpo-30048(118): Fixed ‘Task.cancel()’ can be ignored when the task
     is running coroutine and the coroutine returned without any more
     ‘await’.

   - bpo-30266(119): contextlib.AbstractContextManager now supports
     anti-registration by setting __enter__ = None or __exit__ = None,
     following the pattern introduced in bpo-25958(120).  Patch by Jelle
     Zijlstra.

   - bpo-30340(121): Enhanced regular expressions optimization.  This
     increased the performance of matching some patterns up to 25 times.

   - bpo-30298(122): Weaken the condition of deprecation warnings for
     inline modifiers.  Now allowed several subsequential inline
     modifiers at the start of the pattern (e.g.  ‘'(?i)(?s)...'’).  In
     verbose mode whitespaces and comments now are allowed before and
     between inline modifiers (e.g.  ‘'(?x) (?i) (?s)...'’).

   - bpo-30285(123): Optimized case-insensitive matching and searching
     of regular expressions.

   - bpo-29990(124): Fix range checking in GB18030 decoder.  Original
     patch by Ma Lin.

   - bpo-29979(125): rewrite cgi.parse_multipart, reusing the
     FieldStorage class and making its results consistent with those of
     FieldStorage for multipart/form-data requests.  Patch by Pierre
     Quentel.

   - bpo-30243(126): Removed the __init__ methods of _json’s scanner and
     encoder.  Misusing them could cause memory leaks or crashes.  Now
     scanner and encoder objects are completely initialized in the
     __new__ methods.

   - bpo-30215(127): Compiled regular expression objects with the
     re.LOCALE flag no longer depend on the locale at compile time.
     Only the locale at matching time affects the result of matching.

   - bpo-30185(128): Avoid KeyboardInterrupt tracebacks in forkserver
     helper process when Ctrl-C is received.

   - bpo-30103(129): binascii.b2a_uu() and uu.encode() now support using
     ‘'`'’ as zero instead of space.

   - bpo-28556(130): Various updates to typing module: add
     typing.NoReturn type, use WrapperDescriptorType, minor bug-fixes.
     Original PRs by Jim Fasarakis-Hilliard and Ivan Levkivskyi.

   - bpo-30205(131): Fix getsockname() for unbound AF_UNIX sockets on
     Linux.

   - bpo-30228(132): The seek() and tell() methods of io.FileIO now set
     the internal seekable attribute to avoid one syscall on open() (in
     buffered or text mode).

   - bpo-30190(133): unittest’s assertAlmostEqual and
     assertNotAlmostEqual provide a better message in case of failure
     which includes the difference between left and right arguments.
     (patch by Giampaolo Rodola’)

   - bpo-30101(134): Add support for curses.A_ITALIC.

   - bpo-29822(135): inspect.isabstract() now works during
     __init_subclass__.  Patch by Nate Soares.

   - bpo-29960(136): Preserve generator state when
     _random.Random.setstate() raises an exception.  Patch by Bryan
     Olson.

   - bpo-30070(137): Fixed leaks and crashes in errors handling in the
     parser module.

   - bpo-22352(138): Column widths in the output of dis.dis() are now
     adjusted for large line numbers and instruction offsets.

   - bpo-30061(139): Fixed crashes in IOBase methods __next__() and
     readlines() when readline() or __next__() respectively return
     non-sizeable object.  Fixed possible other errors caused by not
     checking results of PyObject_Size(), PySequence_Size(), or
     PyMapping_Size().

   - bpo-30218(140): Fix PathLike support for shutil.unpack_archive.
     Patch by Jelle Zijlstra.

   - bpo-10076(141): Compiled regular expression and match objects in
     the re module now support copy.copy() and copy.deepcopy() (they are
     considered atomic).

   - bpo-30068(142): _io._IOBase.readlines will check if it’s closed
     first when hint is present.

   - bpo-29694(143): Fixed race condition in pathlib mkdir with flags
     parents=True.  Patch by Armin Rigo.

   - bpo-29692(144): Fixed arbitrary unchaining of RuntimeError
     exceptions in contextlib.contextmanager.  Patch by Siddharth
     Velankar.

   - bpo-26187(145): Test that sqlite3 trace callback is not called
     multiple times when schema is changing.  Indirectly fixed by
     switching to use sqlite3_prepare_v2() in bpo-9303(146).  Patch by
     Aviv Palivoda.

   - bpo-30017(147): Allowed calling the close() method of the zip entry
     writer object multiple times.  Writing to a closed writer now
     always produces a ValueError.

   - bpo-29998(148): Pickling and copying ImportError now preserves name
     and path attributes.

   - bpo-29995(149): re.escape() now escapes only regex special
     characters.

   - bpo-29962(150): Add math.remainder operation, implementing
     remainder as specified in IEEE 754.

   - bpo-29649(151): Improve struct.pack_into() exception messages for
     problems with the buffer size and offset.  Patch by Andrew Nester.

   - bpo-29654(152): Support If-Modified-Since HTTP header (browser
     cache).  Patch by Pierre Quentel.

   - bpo-29931(153): Fixed comparison check for ipaddress.ip_interface
     objects.  Patch by Sanjay Sundaresan.

   - bpo-29953(154): Fixed memory leaks in the replace() method of
     datetime and time objects when pass out of bound fold argument.

   - bpo-29942(155): Fix a crash in itertools.chain.from_iterable when
     encountering long runs of empty iterables.

   - bpo-10030(156): Sped up reading encrypted ZIP files by 2 times.

   - bpo-29204(157): Element.getiterator() and the html parameter of
     XMLParser() were deprecated only in the documentation (since Python
     3.2 and 3.4 correspondintly).  Now using them emits a deprecation
     warning.

   - bpo-27863(158): Fixed multiple crashes in ElementTree caused by
     race conditions and wrong types.

   - bpo-25996(159): Added support of file descriptors in os.scandir()
     on Unix.  os.fwalk() is sped up by 2 times by using os.scandir().

   - bpo-28699(160): Fixed a bug in pools in multiprocessing.pool that
     raising an exception at the very first of an iterable may swallow
     the exception or make the program hang.  Patch by Davin Potts and
     Xiang Zhang.

   - bpo-23890(161): unittest.TestCase.assertRaises() now manually
     breaks a reference cycle to not keep objects alive longer than
     expected.

   - bpo-29901(162): The zipapp module now supports general path-like
     objects, not just pathlib.Path.

   - bpo-25803(163): Avoid incorrect errors raised by
     Path.mkdir(exist_ok=True) when the OS gives priority to errors such
     as EACCES over EEXIST.

   - bpo-29861(164): Release references to tasks, their arguments and
     their results as soon as they are finished in multiprocessing.Pool.

   - bpo-19930(165): The mode argument of os.makedirs() no longer
     affects the file permission bits of newly-created
     intermediate-level directories.

   - bpo-29884(166): faulthandler: Restore the old sigaltstack during
     teardown.  Patch by Christophe Zeitouny.

   - bpo-25455(167): Fixed crashes in repr of recursive buffered
     file-like objects.

   - bpo-29800(168): Fix crashes in partial.__repr__ if the keys of
     partial.keywords are not strings.  Patch by Michael Seifert.

   - bpo-8256(169): Fixed possible failing or crashing input() if
     attributes "encoding" or "errors" of sys.stdin or sys.stdout are
     not set or are not strings.

   - bpo-28692(170): Using non-integer value for selecting a plural form
     in gettext is now deprecated.

   - bpo-26121(171): Use C library implementation for math functions
     erf() and erfc().

   - bpo-29619(172): os.stat() and os.DirEntry.inode() now convert inode
     (st_ino) using unsigned integers.

   - bpo-28298(173): Fix a bug that prevented array ’Q’, ’L’ and ’I’
     from accepting big intables (objects that have __int__) as
     elements.

   - bpo-29645(174): Speed up importing the webbrowser module.
     webbrowser.register() is now thread-safe.

   - bpo-28231(175): The zipfile module now accepts path-like objects
     for external paths.

   - bpo-26915(176): index() and count() methods of
     collections.abc.Sequence now check identity before checking
     equality when do comparisons.

   - bpo-28682(177): Added support for bytes paths in os.fwalk().

   - bpo-29728(178): Add new ‘socket.TCP_NOTSENT_LOWAT’ (Linux 3.12)
     constant.  Patch by Nathaniel J. Smith.

   - bpo-29623(179): Allow use of path-like object as a single argument
     in ConfigParser.read().  Patch by David Ellis.

   - bpo-9303(180): Migrate sqlite3 module to _v2 API. Patch by Aviv
     Palivoda.

   - bpo-28963(181): Fix out of bound iteration in
     asyncio.Future.remove_done_callback implemented in C.

   - bpo-29704(182): asyncio.subprocess.SubprocessStreamProtocol no
     longer closes before all pipes are closed.

   - bpo-29271(183): Fix Task.current_task and Task.all_tasks
     implemented in C to accept None argument as their pure Python
     implementation.

   - bpo-29703(184): Fix asyncio to support instantiation of new event
     loops in child processes.

   - bpo-29615(185): SimpleXMLRPCDispatcher no longer chains KeyError
     (or any other exception) to exception(s) raised in the dispatched
     methods.  Patch by Petr Motejlek.

   - bpo-7769(186): Method register_function() of
     xmlrpc.server.SimpleXMLRPCDispatcher and its subclasses can now be
     used as a decorator.

   - bpo-29376(187): Fix assertion error in
     threading._DummyThread.is_alive().

   - bpo-28624(188): Add a test that checks that cwd parameter of
     Popen() accepts PathLike objects.  Patch by Sayan Chowdhury.

   - bpo-28518(189): Start a transaction implicitly before a DML
     statement.  Patch by Aviv Palivoda.

   - bpo-29742(190): get_extra_info() raises exception if get called on
     closed ssl transport.  Patch by Nikolay Kim.

   - bpo-16285(191): urllib.parse.quote is now based on RFC 3986 and
     hence includes ’~’ in the set of characters that is not quoted by
     default.  Patch by Christian Theune and Ratnadeep Debnath.

   - bpo-29532(192): Altering a kwarg dictionary passed to
     functools.partial() no longer affects a partial object after
     creation.

   - bpo-29110(193): Fix file object leak in aifc.open() when file is
     given as a filesystem path and is not in valid AIFF format.  Patch
     by Anthony Zhang.

   - bpo-22807(194): Add uuid.SafeUUID and uuid.UUID.is_safe to relay
     information from the platform about whether generated UUIDs are
     generated with a multiprocessing safe method.

   - bpo-29576(195): Improve some deprecations in importlib.  Some
     deprecated methods now emit DeprecationWarnings and have better
     descriptive messages.

   - bpo-29534(196): Fixed different behaviour of Decimal.from_float()
     for _decimal and _pydecimal.  Thanks Andrew Nester.

   - bpo-10379(197): locale.format_string now supports the ’monetary’
     keyword argument, and locale.format is deprecated.

   - bpo-29851(198): importlib.reload() now raises ModuleNotFoundError
     if the module lacks a spec.

   - bpo-28556(199): Various updates to typing module: typing.Counter,
     typing.ChainMap, improved ABC caching, etc.  Original PRs by Jelle
     Zijlstra, Ivan Levkivskyi, Manuel Krebber, and Łukasz Langa.

   - bpo-29100(200): Fix datetime.fromtimestamp() regression introduced
     in Python 3.6.0: check minimum and maximum years.

   - bpo-29416(201): Prevent infinite loop in pathlib.Path.mkdir

   - bpo-29444(202): Fixed out-of-bounds buffer access in the group()
     method of the match object.  Based on patch by WGH.

   - bpo-29377(203): Add WrapperDescriptorType, MethodWrapperType, and
     MethodDescriptorType built-in types to types module.  Original
     patch by Manuel Krebber.

   - bpo-29218(204): Unused install_misc command is now removed.  It has
     been documented as unused since 2000.  Patch by Eric N. Vander
     Weele.

   - bpo-29368(205): The extend() method is now called instead of the
     append() method when unpickle collections.deque and other list-like
     objects.  This can speed up unpickling to 2 times.

   - bpo-29338(206): The help of a builtin or extension class now
     includes the constructor signature if __text_signature__ is
     provided for the class.

   - bpo-29335(207): Fix subprocess.Popen.wait() when the child process
     has exited to a stopped instead of terminated state (ex: when under
     ptrace).

   - bpo-29290(208): Fix a regression in argparse that help messages
     would wrap at non-breaking spaces.

   - bpo-28735(209): Fixed the comparison of mock.MagickMock with
     mock.ANY.

   - bpo-29197(210): Removed deprecated function ntpath.splitunc().

   - bpo-29210(211): Removed support of deprecated argument "exclude" in
     tarfile.TarFile.add().

   - bpo-29219(212): Fixed infinite recursion in the repr of
     uninitialized ctypes.CDLL instances.

   - bpo-29192(213): Removed deprecated features in the http.cookies
     module.

   - bpo-29193(214): A format string argument for
     string.Formatter.format() is now positional-only.

   - bpo-29195(215): Removed support of deprecated undocumented keyword
     arguments in methods of regular expression objects.

   - bpo-28969(216): Fixed race condition in C implementation of
     functools.lru_cache.  KeyError could be raised when cached function
     with full cache was simultaneously called from different threads
     with the same uncached arguments.

   - bpo-20804(217): The unittest.mock.sentinel attributes now preserve
     their identity when they are copied or pickled.

   - bpo-29142(218): In urllib.request, suffixes in no_proxy environment
     variable with leading dots could match related hostnames again
     (e.g.  .b.c matches a.b.c).  Patch by Milan Oberkirch.

   - bpo-28961(219): Fix unittest.mock._Call helper: don’t ignore the
     name parameter anymore.  Patch written by Jiajun Huang.

   - bpo-15812(220): inspect.getframeinfo() now correctly shows the
     first line of a context.  Patch by Sam Breese.

   - bpo-28985(221): Update authorizer constants in sqlite3 module.
     Patch by Dingyuan Wang.

   - bpo-29079(222): Prevent infinite loop in pathlib.resolve() on
     Windows

   - bpo-13051(223): Fixed recursion errors in large or resized
     curses.textpad.Textbox.  Based on patch by Tycho Andersen.

   - bpo-9770(224): curses.ascii predicates now work correctly with
     negative integers.

   - bpo-28427(225): old keys should not remove new values from
     WeakValueDictionary when collecting from another thread.

   - bpo-28923(226): Remove editor artifacts from Tix.py.

   - bpo-28871(227): Fixed a crash when deallocate deep ElementTree.

   - bpo-19542(228): Fix bugs in WeakValueDictionary.setdefault() and
     WeakValueDictionary.pop() when a GC collection happens in another
     thread.

   - bpo-20191(229): Fixed a crash in resource.prlimit() when passing a
     sequence that doesn’t own its elements as limits.

   - bpo-16255(230): subprocess.Popen uses /system/bin/sh on Android as
     the shell, instead of /bin/sh.

   - bpo-28779(231): multiprocessing.set_forkserver_preload() would
     crash the forkserver process if a preloaded module instantiated
     some multiprocessing objects such as locks.

   - bpo-26937(232): The chown() method of the tarfile.TarFile class
     does not fail now when the grp module cannot be imported, as for
     example on Android platforms.

   - bpo-28847(233): dbm.dumb now supports reading read-only files and
     no longer writes the index file when it is not changed.  A
     deprecation warning is now emitted if the index file is missed and
     recreated in the ’r’ and ’w’ modes (will be an error in future
     Python releases).

   - bpo-27030(234): Unknown escapes consisting of ‘'\'’ and an ASCII
     letter in re.sub() replacement templates regular expressions now
     are errors.

   - bpo-28835(235): Fix a regression introduced in
     warnings.catch_warnings(): call warnings.showwarning() if it was
     overridden inside the context manager.

   - bpo-27172(236): To assist with upgrades from 2.7, the previously
     documented deprecation of ‘inspect.getfullargspec()’ has been
     reversed.  This decision may be revisited again after the Python
     2.7 branch is no longer officially supported.

   - bpo-28740(237): Add sys.getandroidapilevel(): return the build time
     API version of Android as an integer.  Function only available on
     Android.

   - bpo-26273(238): Add new ‘socket.TCP_CONGESTION’ (Linux 2.6.13) and
     ‘socket.TCP_USER_TIMEOUT’ (Linux 2.6.37) constants.  Patch written
     by Omar Sandoval.

   - bpo-28752(239): Restored the __reduce__() methods of datetime
     objects.

   - bpo-28727(240): Regular expression patterns, _sre.SRE_Pattern
     objects created by re.compile(), become comparable (only x==y and
     x!=y operators).  This change should fix the bpo-18383(241): don’t
     duplicate warning filters when the warnings module is reloaded
     (thing usually only done in unit tests).

   - bpo-20572(242): Remove the subprocess.Popen.wait endtime parameter.
     It was deprecated in 3.4 and undocumented prior to that.

   - bpo-25659(243): In ctypes, prevent a crash calling the
     from_buffer() and from_buffer_copy() methods on abstract classes
     like Array.

   - bpo-28548(244): In the "http.server" module, parse the protocol
     version if possible, to avoid using HTTP 0.9 in some error
     responses.

   - bpo-19717(245): Makes Path.resolve() succeed on paths that do not
     exist.  Patch by Vajrasky Kok

   - bpo-28563(246): Fixed possible DoS and arbitrary code execution
     when handle plural form selections in the gettext module.  The
     expression parser now supports exact syntax supported by GNU
     gettext.

   - bpo-28387(247): Fixed possible crash in _io.TextIOWrapper
     deallocator when the garbage collector is invoked in other thread.
     Based on patch by Sebastian Cufre.

   - bpo-27517(248): LZMA compressor and decompressor no longer raise
     exceptions if given empty data twice.  Patch by Benjamin Fogle.

   - bpo-28549(249): Fixed segfault in curses’s addch() with ncurses6.

   - bpo-28449(250): tarfile.open() with mode "r" or "r:" now tries to
     open a tar file with compression before trying to open it without
     compression.  Otherwise it had 50% chance failed with
     ignore_zeros=True.

   - bpo-23262(251): The webbrowser module now supports Firefox 36+ and
     derived browsers.  Based on patch by Oleg Broytman.

   - bpo-24241(252): The webbrowser in an X environment now prefers
     using the default browser directly.  Also, the webbrowser
     register() function now has a documented ’preferred’ argument, to
     specify browsers to be returned by get() with no arguments.  Patch
     by David Steele

   - bpo-27939(253): Fixed bugs in tkinter.ttk.LabeledScale and
     tkinter.Scale caused by representing the scale as float value
     internally in Tk.  tkinter.IntVar now works if float value is set
     to underlying Tk variable.

   - bpo-28255(254): calendar.TextCalendar.prweek() no longer prints a
     space after a weeks’s calendar.  calendar.TextCalendar.pryear() no
     longer prints redundant newline after a year’s calendar.  Based on
     patch by Xiang Zhang.

   - bpo-28255(255): calendar.TextCalendar.prmonth() no longer prints a
     space at the start of new line after printing a month’s calendar.
     Patch by Xiang Zhang.

   - bpo-20491(256): The textwrap.TextWrapper class now honors
     non-breaking spaces.  Based on patch by Kaarle Ritvanen.

   - bpo-28353(257): os.fwalk() no longer fails on broken links.

   - bpo-28430(258): Fix iterator of C implemented asyncio.Future
     doesn’t accept non-None value is passed to it.send(val).

   - bpo-27025(259): Generated names for Tkinter widgets now start by
     the "!"  prefix for readability.

   - bpo-25464(260): Fixed HList.header_exists() in tkinter.tix module
     by addin a workaround to Tix library bug.

   - bpo-28488(261): shutil.make_archive() no longer adds entry "./" to
     ZIP archive.

   - bpo-25953(262): re.sub() now raises an error for invalid numerical
     group reference in replacement template even if the pattern is not
     found in the string.  Error message for invalid group reference now
     includes the group index and the position of the reference.  Based
     on patch by SilentGhost.

   - bpo-28469(263): timeit now uses the sequence 1, 2, 5, 10, 20,
     50,...  instead of 1, 10, 100,...  for autoranging.

   - bpo-28115(264): Command-line interface of the zipfile module now
     uses argparse.  Added support of long options.

   - bpo-18219(265): Optimize csv.DictWriter for large number of
     columns.  Patch by Mariatta Wijaya.

   - bpo-28448(266): Fix C implemented asyncio.Future didn’t work on
     Windows.

   - bpo-23214(267): In the "io" module, the argument to BufferedReader
     and BytesIO’s read1() methods is now optional and can be -1,
     matching the BufferedIOBase specification.

   - bpo-28480(268): Fix error building socket module when
     multithreading is disabled.

   - bpo-28240(269): timeit: remove ‘-c/--clock’ and ‘-t/--time’ command
     line options which were deprecated since Python 3.3.

   - bpo-28240(270): timeit now repeats the benchmarks 5 times instead
     of only 3 to make benchmarks more reliable.

   - bpo-28240(271): timeit autorange now uses a single loop iteration
     if the benchmark takes less than 10 seconds, instead of 10
     iterations.  "python3 -m timeit -s ’import time’ ’time.sleep(1)’"
     now takes 4 seconds instead of 40 seconds.

   - Distutils.sdist now looks for README and setup.py files with case
     sensitivity.  This behavior matches that found in Setuptools 6.0
     and later.  See setuptools 100(272) for rationale.

   - bpo-24452(273): Make webbrowser support Chrome on Mac OS X. Patch
     by Ned Batchelder.

   - bpo-20766(274): Fix references leaked by pdb in the handling of
     SIGINT handlers.

   - bpo-27998(275): Fixed bytes path support in os.scandir() on
     Windows.  Patch by Eryk Sun.

   - bpo-28317(276): The disassembler now decodes FORMAT_VALUE argument.

   - bpo-28380(277): unittest.mock Mock autospec functions now properly
     support assert_called, assert_not_called, and assert_called_once.

   - bpo-28229(278): lzma module now supports pathlib.

   - bpo-28321(279): Fixed writing non-BMP characters with binary format
     in plistlib.

   - bpo-28225(280): bz2 module now supports pathlib.  Initial patch by
     Ethan Furman.

   - bpo-28227(281): gzip now supports pathlib.  Patch by Ethan Furman.

   - bpo-28332(282): Deprecated silent truncations in socket.htons and
     socket.ntohs.  Original patch by Oren Milman.

   - bpo-27358(283): Optimized merging var-keyword arguments and
     improved error message when passing a non-mapping as a var-keyword
     argument.

   - bpo-28257(284): Improved error message when passing a non-iterable
     as a var-positional argument.  Added opcode
     BUILD_TUPLE_UNPACK_WITH_CALL.

   - bpo-28322(285): Fixed possible crashes when unpickle itertools
     objects from incorrect pickle data.  Based on patch by John Leitch.

   - bpo-28228(286): imghdr now supports pathlib.

   - bpo-28226(287): compileall now supports pathlib.

   - bpo-28314(288): Fix function declaration (C flags) for the
     getiterator() method of xml.etree.ElementTree.Element.

   - bpo-28148(289): Stop using localtime() and gmtime() in the time
     module.  Introduced platform independent _PyTime_localtime API that
     is similar to POSIX localtime_r, but available on all platforms.
     Patch by Ed Schouten.

   - bpo-28253(290): Fixed calendar functions for extreme months:
     0001-01 and 9999-12.  Methods itermonthdays() and itermonthdays2()
     are reimplemented so that they don’t call itermonthdates() which
     can cause datetime.date under/overflow.

   - bpo-28275(291): Fixed possible use after free in the decompress()
     methods of the LZMADecompressor and BZ2Decompressor classes.
     Original patch by John Leitch.

   - bpo-27897(292): Fixed possible crash in
     sqlite3.Connection.create_collation() if pass invalid string-like
     object as a name.  Patch by Xiang Zhang.

   - bpo-18844(293): random.choices() now has k as a keyword-only
     argument to improve the readability of common cases and come into
     line with the signature used in other languages.

   - bpo-18893(294): Fix invalid exception handling in
     Lib/ctypes/macholib/dyld.py.  Patch by Madison May.

   - bpo-27611(295): Fixed support of default root window in the
     tkinter.tix module.  Added the master parameter in the DisplayStyle
     constructor.

   - bpo-27348(296): In the traceback module, restore the formatting of
     exception messages like "Exception: None".  This fixes a regression
     introduced in 3.5a2.

   - bpo-25651(297): Allow falsy values to be used for msg parameter of
     subTest().

   - bpo-27778(298): Fix a memory leak in os.getrandom() when the
     getrandom() is interrupted by a signal and a signal handler raises
     a Python exception.

   - bpo-28200(299): Fix memory leak on Windows in the os module (fix
     path_converter() function).

   - bpo-25400(300): RobotFileParser now correctly returns default
     values for crawl_delay and request_rate.  Initial patch by Peter
     Wirtz.

   - bpo-27932(301): Prevent memory leak in win32_ver().

   - Fix UnboundLocalError in socket._sendfile_use_sendfile.

   - bpo-28075(302): Check for ERROR_ACCESS_DENIED in Windows
     implementation of os.stat().  Patch by Eryk Sun.

   - bpo-22493(303): Warning message emitted by using inline flags in
     the middle of regular expression now contains a (truncated) regex
     pattern.  Patch by Tim Graham.

   - bpo-25270(304): Prevent codecs.escape_encode() from raising
     SystemError when an empty bytestring is passed.

   - bpo-28181(305): Get antigravity over HTTPS. Patch by Kaartic
     Sivaraam.

   - bpo-25895(306): Enable WebSocket URL schemes in
     urllib.parse.urljoin.  Patch by Gergely Imreh and Markus
     Holtermann.

   - bpo-28114(307): Fix a crash in parse_envlist() when env contains
     byte strings.  Patch by Eryk Sun.

   - bpo-27599(308): Fixed buffer overrun in binascii.b2a_qp() and
     binascii.a2b_qp().

   - bpo-27906(309): Fix socket accept exhaustion during high TCP
     traffic.  Patch by Kevin Conway.

   - bpo-28174(310): Handle when SO_REUSEPORT isn’t properly supported.
     Patch by Seth Michael Larson.

   - bpo-26654(311): Inspect functools.partial in
     asyncio.Handle.__repr__.  Patch by iceboy.

   - bpo-26909(312): Fix slow pipes IO in asyncio.  Patch by INADA
     Naoki.

   - bpo-28176(313): Fix callbacks race in
     asyncio.SelectorLoop.sock_connect.

   - bpo-27759(314): Fix selectors incorrectly retain invalid file
     descriptors.  Patch by Mark Williams.

   - bpo-28325(315): Remove vestigial MacOS 9 macurl2path module and its
     tests.

   - bpo-28368(316): Refuse monitoring processes if the child watcher
     has no loop attached.  Patch by Vincent Michel.

   - bpo-28369(317): Raise RuntimeError when transport’s FD is used with
     add_reader, add_writer, etc.

   - bpo-28370(318): Speedup asyncio.StreamReader.readexactly.  Patch by
     Коренберг Марк.

   - bpo-28371(319): Deprecate passing asyncio.Handles to
     run_in_executor.

   - bpo-28372(320): Fix asyncio to support formatting of non-python
     coroutines.

   - bpo-28399(321): Remove UNIX socket from FS before binding.  Patch
     by Коренберг Марк.

   - bpo-27972(322): Prohibit Tasks to await on themselves.

   - bpo-24142(323): Reading a corrupt config file left configparser in
     an invalid state.  Original patch by Florian Höch.

   - bpo-29581(324): ABCMeta.__new__ now accepts ‘**kwargs’, allowing
     abstract base classes to use keyword parameters in
     __init_subclass__.  Patch by Nate Soares.

   - bpo-25532(325): inspect.unwrap() will now only try to unwrap an
     object sys.getrecursionlimit() times, to protect against objects
     which create a new object on every attribute access.

   - bpo-30177(326): path.resolve(strict=False) no longer cuts the path
     after the first element not present in the filesystem.  Patch by
     Antoine Pietri.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31499

   (2) https://bugs.python.org/issue31482

   (3) https://bugs.python.org/issue28556

   (4) https://bugs.python.org/issue28556

   (5) https://bugs.python.org/issue31544

   (6) https://bugs.python.org/issue31234

   (7) https://bugs.python.org/issue31457

   (8) https://bugs.python.org/issue31431

   (9) https://bugs.python.org/issue31233

   (10) https://bugs.python.org/issue28638

   (11) https://bugs.python.org/issue31400

   (12) https://bugs.python.org/issue27629

   (13) https://bugs.python.org/issue28958

   (14) https://bugs.python.org/issue28182

   (15) https://bugs.python.org/issue27340

   (16) https://bugs.python.org/issue14191

   (17) https://bugs.python.org/issue31178

   (18) https://bugs.python.org/issue31350

   (19) https://bugs.python.org/issue31170

   (20) https://bugs.python.org/issue29136

   (21) https://bugs.python.org/issue1198569

   (22) https://bugs.python.org/issue31326

   (23) https://bugs.python.org/issue27144

   (24) https://bugs.python.org/issue31281

   (25) https://bugs.python.org/issue10746

   (26) https://www.python.org/dev/peps/pep-3118

   (27) https://bugs.python.org/issue27584

   (28) https://bugs.python.org/issue22536

   (29) https://bugs.python.org/issue29741

   (30) https://bugs.python.org/issue31249

   (31) https://bugs.python.org/issue31247

   (32) https://bugs.python.org/issue23835

   (33) https://bugs.python.org/issue31238

   (34) https://bugs.python.org/issue5001

   (35) https://bugs.python.org/issue31109

   (36) https://bugs.python.org/issue30102

   (37) https://bugs.python.org/issue18966

   (38) https://bugs.python.org/issue31183

   (39) https://bugs.python.org/issue5001

   (40) https://bugs.python.org/issue31185

   (41) https://bugs.python.org/issue31151

   (42) https://bugs.python.org/issue31072

   (43) https://bugs.python.org/issue24700

   (44) https://bugs.python.org/issue31135

   (45) https://bugs.python.org/issue31107

   (46) https://bugs.python.org/issue31080

   (47) https://bugs.python.org/issue30897

   (48) https://bugs.python.org/issue31061

   (49) https://bugs.python.org/issue30987

   (50) https://bugs.python.org/issue30522

   (51) https://bugs.python.org/issue30502

   (52) https://bugs.python.org/issue5288

   (53) https://bugs.python.org/issue30919

   (54) https://bugs.python.org/issue26732

   (55) https://bugs.python.org/issue29403

   (56) https://bugs.python.org/issue30961

   (57) https://bugs.python.org/issue19896

   (58) https://bugs.python.org/issue30946

   (59) https://bugs.python.org/issue25684

   (60) https://bugs.python.org/issue30886

   (61) https://bugs.python.org/issue29854

   (62) https://bugs.python.org/issue30794

   (63) https://bugs.python.org/issue30319

   (64) https://bugs.python.org/issue30828

   (65) https://bugs.python.org/issue30302

   (66) https://bugs.python.org/issue30807

   (67) https://bugs.python.org/issue30441

   (68) https://bugs.python.org/issue29585

   (69) https://bugs.python.org/issue29293

   (70) https://bugs.python.org/issue30532

   (71) https://bugs.python.org/issue30596

   (72) https://bugs.python.org/issue9146

   (73) https://bugs.python.org/issue29169

   (74) https://bugs.python.org/issue30119

   (75) https://bugs.python.org/issue30879

   (76) https://bugs.python.org/issue30746

   (77) https://bugs.python.org/issue30664

   (78) https://bugs.python.org/issue21071

   (79) https://bugs.python.org/issue29212

   (80) https://bugs.python.org/issue29755

   (81) https://bugs.python.org/issue30616

   (82) https://bugs.python.org/issue30038

   (83) https://bugs.python.org/issue23894

   (84) https://bugs.python.org/issue24744

   (85) https://bugs.python.org/issue24484

   (86) https://bugs.python.org/issue30589

   (87) https://bugs.python.org/issue28994

   (88) https://bugs.python.org/issue30508

   (89) https://bugs.python.org/issue30645

   (90) https://bugs.python.org/issue11822

   (91) https://bugs.python.org/issue30624

   (92) https://bugs.python.org/issue30595

   (93) https://bugs.python.org/issue28556

   (94) https://bugs.python.org/issue30605

   (95) https://bugs.python.org/issue29870

   (96) https://bugs.python.org/issue29743

   (97) https://bugs.python.org/issue27585

   (98) https://bugs.python.org/issue30014

   (99) https://bugs.python.org/issue30418

   (100) https://bugs.python.org/issue30463

   (101) https://bugs.python.org/issue30520

   (102) https://bugs.python.org/issue30557

   (103) https://bugs.python.org/issue30526

   (104) https://bugs.python.org/issue30245

   (105) https://bugs.python.org/issue30378

   (106) https://bugs.python.org/issue16500

   (107) https://bugs.python.org/issue30470

   (108) https://bugs.python.org/issue30414

   (109) https://bugs.python.org/issue30003

   (110) https://bugs.python.org/issue30149

   (111) https://bugs.python.org/issue30436

   (112) https://bugs.python.org/issue30301

   (113) https://bugs.python.org/issue30375

   (114) https://bugs.python.org/issue30329

   (115) https://bugs.python.org/issue29196

   (116) https://bugs.python.org/issue9850

   (117) https://bugs.python.org/issue30299

   (118) https://bugs.python.org/issue30048

   (119) https://bugs.python.org/issue30266

   (120) https://bugs.python.org/issue25958

   (121) https://bugs.python.org/issue30340

   (122) https://bugs.python.org/issue30298

   (123) https://bugs.python.org/issue30285

   (124) https://bugs.python.org/issue29990

   (125) https://bugs.python.org/issue29979

   (126) https://bugs.python.org/issue30243

   (127) https://bugs.python.org/issue30215

   (128) https://bugs.python.org/issue30185

   (129) https://bugs.python.org/issue30103

   (130) https://bugs.python.org/issue28556

   (131) https://bugs.python.org/issue30205

   (132) https://bugs.python.org/issue30228

   (133) https://bugs.python.org/issue30190

   (134) https://bugs.python.org/issue30101

   (135) https://bugs.python.org/issue29822

   (136) https://bugs.python.org/issue29960

   (137) https://bugs.python.org/issue30070

   (138) https://bugs.python.org/issue22352

   (139) https://bugs.python.org/issue30061

   (140) https://bugs.python.org/issue30218

   (141) https://bugs.python.org/issue10076

   (142) https://bugs.python.org/issue30068

   (143) https://bugs.python.org/issue29694

   (144) https://bugs.python.org/issue29692

   (145) https://bugs.python.org/issue26187

   (146) https://bugs.python.org/issue9303

   (147) https://bugs.python.org/issue30017

   (148) https://bugs.python.org/issue29998

   (149) https://bugs.python.org/issue29995

   (150) https://bugs.python.org/issue29962

   (151) https://bugs.python.org/issue29649

   (152) https://bugs.python.org/issue29654

   (153) https://bugs.python.org/issue29931

   (154) https://bugs.python.org/issue29953

   (155) https://bugs.python.org/issue29942

   (156) https://bugs.python.org/issue10030

   (157) https://bugs.python.org/issue29204

   (158) https://bugs.python.org/issue27863

   (159) https://bugs.python.org/issue25996

   (160) https://bugs.python.org/issue28699

   (161) https://bugs.python.org/issue23890

   (162) https://bugs.python.org/issue29901

   (163) https://bugs.python.org/issue25803

   (164) https://bugs.python.org/issue29861

   (165) https://bugs.python.org/issue19930

   (166) https://bugs.python.org/issue29884

   (167) https://bugs.python.org/issue25455

   (168) https://bugs.python.org/issue29800

   (169) https://bugs.python.org/issue8256

   (170) https://bugs.python.org/issue28692

   (171) https://bugs.python.org/issue26121

   (172) https://bugs.python.org/issue29619

   (173) https://bugs.python.org/issue28298

   (174) https://bugs.python.org/issue29645

   (175) https://bugs.python.org/issue28231

   (176) https://bugs.python.org/issue26915

   (177) https://bugs.python.org/issue28682

   (178) https://bugs.python.org/issue29728

   (179) https://bugs.python.org/issue29623

   (180) https://bugs.python.org/issue9303

   (181) https://bugs.python.org/issue28963

   (182) https://bugs.python.org/issue29704

   (183) https://bugs.python.org/issue29271

   (184) https://bugs.python.org/issue29703

   (185) https://bugs.python.org/issue29615

   (186) https://bugs.python.org/issue7769

   (187) https://bugs.python.org/issue29376

   (188) https://bugs.python.org/issue28624

   (189) https://bugs.python.org/issue28518

   (190) https://bugs.python.org/issue29742

   (191) https://bugs.python.org/issue16285

   (192) https://bugs.python.org/issue29532

   (193) https://bugs.python.org/issue29110

   (194) https://bugs.python.org/issue22807

   (195) https://bugs.python.org/issue29576

   (196) https://bugs.python.org/issue29534

   (197) https://bugs.python.org/issue10379

   (198) https://bugs.python.org/issue29851

   (199) https://bugs.python.org/issue28556

   (200) https://bugs.python.org/issue29100

   (201) https://bugs.python.org/issue29416

   (202) https://bugs.python.org/issue29444

   (203) https://bugs.python.org/issue29377

   (204) https://bugs.python.org/issue29218

   (205) https://bugs.python.org/issue29368

   (206) https://bugs.python.org/issue29338

   (207) https://bugs.python.org/issue29335

   (208) https://bugs.python.org/issue29290

   (209) https://bugs.python.org/issue28735

   (210) https://bugs.python.org/issue29197

   (211) https://bugs.python.org/issue29210

   (212) https://bugs.python.org/issue29219

   (213) https://bugs.python.org/issue29192

   (214) https://bugs.python.org/issue29193

   (215) https://bugs.python.org/issue29195

   (216) https://bugs.python.org/issue28969

   (217) https://bugs.python.org/issue20804

   (218) https://bugs.python.org/issue29142

   (219) https://bugs.python.org/issue28961

   (220) https://bugs.python.org/issue15812

   (221) https://bugs.python.org/issue28985

   (222) https://bugs.python.org/issue29079

   (223) https://bugs.python.org/issue13051

   (224) https://bugs.python.org/issue9770

   (225) https://bugs.python.org/issue28427

   (226) https://bugs.python.org/issue28923

   (227) https://bugs.python.org/issue28871

   (228) https://bugs.python.org/issue19542

   (229) https://bugs.python.org/issue20191

   (230) https://bugs.python.org/issue16255

   (231) https://bugs.python.org/issue28779

   (232) https://bugs.python.org/issue26937

   (233) https://bugs.python.org/issue28847

   (234) https://bugs.python.org/issue27030

   (235) https://bugs.python.org/issue28835

   (236) https://bugs.python.org/issue27172

   (237) https://bugs.python.org/issue28740

   (238) https://bugs.python.org/issue26273

   (239) https://bugs.python.org/issue28752

   (240) https://bugs.python.org/issue28727

   (241) https://bugs.python.org/issue18383

   (242) https://bugs.python.org/issue20572

   (243) https://bugs.python.org/issue25659

   (244) https://bugs.python.org/issue28548

   (245) https://bugs.python.org/issue19717

   (246) https://bugs.python.org/issue28563

   (247) https://bugs.python.org/issue28387

   (248) https://bugs.python.org/issue27517

   (249) https://bugs.python.org/issue28549

   (250) https://bugs.python.org/issue28449

   (251) https://bugs.python.org/issue23262

   (252) https://bugs.python.org/issue24241

   (253) https://bugs.python.org/issue27939

   (254) https://bugs.python.org/issue28255

   (255) https://bugs.python.org/issue28255

   (256) https://bugs.python.org/issue20491

   (257) https://bugs.python.org/issue28353

   (258) https://bugs.python.org/issue28430

   (259) https://bugs.python.org/issue27025

   (260) https://bugs.python.org/issue25464

   (261) https://bugs.python.org/issue28488

   (262) https://bugs.python.org/issue25953

   (263) https://bugs.python.org/issue28469

   (264) https://bugs.python.org/issue28115

   (265) https://bugs.python.org/issue18219

   (266) https://bugs.python.org/issue28448

   (267) https://bugs.python.org/issue23214

   (268) https://bugs.python.org/issue28480

   (269) https://bugs.python.org/issue28240

   (270) https://bugs.python.org/issue28240

   (271) https://bugs.python.org/issue28240

   (272) https://github.com/pypa/setuptools/issues/100

   (273) https://bugs.python.org/issue24452

   (274) https://bugs.python.org/issue20766

   (275) https://bugs.python.org/issue27998

   (276) https://bugs.python.org/issue28317

   (277) https://bugs.python.org/issue28380

   (278) https://bugs.python.org/issue28229

   (279) https://bugs.python.org/issue28321

   (280) https://bugs.python.org/issue28225

   (281) https://bugs.python.org/issue28227

   (282) https://bugs.python.org/issue28332

   (283) https://bugs.python.org/issue27358

   (284) https://bugs.python.org/issue28257

   (285) https://bugs.python.org/issue28322

   (286) https://bugs.python.org/issue28228

   (287) https://bugs.python.org/issue28226

   (288) https://bugs.python.org/issue28314

   (289) https://bugs.python.org/issue28148

   (290) https://bugs.python.org/issue28253

   (291) https://bugs.python.org/issue28275

   (292) https://bugs.python.org/issue27897

   (293) https://bugs.python.org/issue18844

   (294) https://bugs.python.org/issue18893

   (295) https://bugs.python.org/issue27611

   (296) https://bugs.python.org/issue27348

   (297) https://bugs.python.org/issue25651

   (298) https://bugs.python.org/issue27778

   (299) https://bugs.python.org/issue28200

   (300) https://bugs.python.org/issue25400

   (301) https://bugs.python.org/issue27932

   (302) https://bugs.python.org/issue28075

   (303) https://bugs.python.org/issue22493

   (304) https://bugs.python.org/issue25270

   (305) https://bugs.python.org/issue28181

   (306) https://bugs.python.org/issue25895

   (307) https://bugs.python.org/issue28114

   (308) https://bugs.python.org/issue27599

   (309) https://bugs.python.org/issue27906

   (310) https://bugs.python.org/issue28174

   (311) https://bugs.python.org/issue26654

   (312) https://bugs.python.org/issue26909

   (313) https://bugs.python.org/issue28176

   (314) https://bugs.python.org/issue27759

   (315) https://bugs.python.org/issue28325

   (316) https://bugs.python.org/issue28368

   (317) https://bugs.python.org/issue28369

   (318) https://bugs.python.org/issue28370

   (319) https://bugs.python.org/issue28371

   (320) https://bugs.python.org/issue28372

   (321) https://bugs.python.org/issue28399

   (322) https://bugs.python.org/issue27972

   (323) https://bugs.python.org/issue24142

   (324) https://bugs.python.org/issue29581

   (325) https://bugs.python.org/issue25532

   (326) https://bugs.python.org/issue30177


File: python.info,  Node: 文档<35>,  Next: 测试<28>,  Prev: 库<40>,  Up: Python 3 7 0 alpha 1

1.18.41.4 文档
..............

   - bpo-31294(1): Fix incomplete code snippet in the
     ZeroMQSocketListener and ZeroMQSocketHandler examples and adapt
     them to Python 3.

   - bpo-21649(2): Add RFC 7525 and Mozilla server side TLS links to SSL
     documentation.

   - bpo-31128(3): Allow the pydoc server to bind to arbitrary
     hostnames.

   - bpo-30803(4): Clarify doc on truth value testing.  Original patch
     by Peter Thomassen.

   - bpo-30176(5): Add missing attribute related constants in curses
     documentation.

   - bpo-30052(6): the link targets for *note bytes(): 33a. and *note
     bytearray(): 33b. are now their respective type definitions, rather
     than the corresponding builtin function entries.  Use *note bytes:
     10cd. and *note bytearray: 10ce. to reference the latter.  In order
     to ensure this and future cross-reference updates are applied
     automatically, the daily documentation builds now disable the
     default output caching features in Sphinx.

   - bpo-26985(7): Add missing info of code object in inspect
     documentation.

   - bpo-19824(8): Improve the documentation for, and links to, template
     strings by emphasizing their utility for internationalization, and
     by clarifying some usage constraints.  (See also: bpo-20314(9),
     bpo-12518(10))

   - bpo-28929(11): Link the documentation to its source file on GitHub.

   - bpo-25008(12): Document smtpd.py as effectively deprecated and add
     a pointer to aiosmtpd, a third-party asyncio-based replacement.

   - bpo-26355(13): Add canonical header link on each page to
     corresponding major version of the documentation.  Patch by
     Matthias Bussonnier.

   - bpo-29349(14): Fix Python 2 syntax in code for building the
     documentation.

   - bpo-23722(15): The data model reference and the porting section in
     the 3.6 What’s New guide now cover the additional ‘__classcell__’
     handling needed for custom metaclasses to fully support PEP 487(16)
     and zero-argument ‘super()’.

   - bpo-28513(17): Documented command-line interface of zipfile.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31294

   (2) https://bugs.python.org/issue21649

   (3) https://bugs.python.org/issue31128

   (4) https://bugs.python.org/issue30803

   (5) https://bugs.python.org/issue30176

   (6) https://bugs.python.org/issue30052

   (7) https://bugs.python.org/issue26985

   (8) https://bugs.python.org/issue19824

   (9) https://bugs.python.org/issue20314

   (10) https://bugs.python.org/issue12518

   (11) https://bugs.python.org/issue28929

   (12) https://bugs.python.org/issue25008

   (13) https://bugs.python.org/issue26355

   (14) https://bugs.python.org/issue29349

   (15) https://bugs.python.org/issue23722

   (16) https://www.python.org/dev/peps/pep-0487

   (17) https://bugs.python.org/issue28513


File: python.info,  Node: 测试<28>,  Next: 构建<26>,  Prev: 文档<35>,  Up: Python 3 7 0 alpha 1

1.18.41.5 测试
..............

   - bpo-29639(1): test.support.HOST is now "localhost", a new HOSTv4
     constant has been added for your ‘127.0.0.1’ needs, similar to the
     existing HOSTv6 constant.

   - bpo-31320(2): Silence traceback in test_ssl

   - bpo-31346(3): Prefer PROTOCOL_TLS_CLIENT and PROTOCOL_TLS_SERVER
     protocols for SSLContext.

   - bpo-25674(4): Remove sha256.tbs-internet.com ssl test

   - bpo-30715(5): Address ALPN callback changes for OpenSSL 1.1.0f.
     The latest version behaves like OpenSSL 1.0.2 and no longer aborts
     handshake.

   - bpo-30822(6): regrtest: Exclude tzdata from regrtest –all.  When
     running the test suite using –use=all / -u all, exclude tzdata
     since it makes test_datetime too slow (15-20 min on some buildbots)
     which then times out on some buildbots.  Fix also regrtest command
     line parser to allow passing -u extralargefile to run
     test_zipfile64.

   - bpo-30695(7): Add the ‘set_nomemory(start, stop)’ and
     ‘remove_mem_hooks()’ functions to the _testcapi module.

   - bpo-30357(8): test_thread: setUp() now uses
     support.threading_setup() and support.threading_cleanup() to wait
     until threads complete to avoid random side effects on following
     tests.  Initial patch written by Grzegorz Grzywacz.

   - bpo-30197(9): Enhanced functions swap_attr() and swap_item() in the
     test.support module.  They now work when delete replaced attribute
     or item inside the with statement.  The old value of the attribute
     or item (or None if it doesn’t exist) now will be assigned to the
     target of the "as" clause, if there is one.

   - bpo-24932(10): Use proper command line parsing in _testembed

   - bpo-28950(11): Disallow -j0 to be combined with -T/-l in regrtest
     command line arguments.

   - bpo-28683(12): Fix the tests that bind() a unix socket and raise
     PermissionError on Android for a non-root user.

   - bpo-26936(13): Fix the test_socket failures on Android -
     getservbyname(), getservbyport() and getaddrinfo() are broken on
     some Android API levels.

   - bpo-28666(14): Now test.support.rmtree is able to remove unwritable
     or unreadable directories.

   - bpo-23839(15): Various caches now are cleared before running every
     test file.

   - bpo-26944(16): Fix test_posix for Android where ’id -G’ is entirely
     wrong or missing the effective gid.

   - bpo-28409(17): regrtest: fix the parser of command line arguments.

   - bpo-28217(18): Adds _testconsole module to test console input.

   - bpo-26939(19): Add the support.setswitchinterval() function to fix
     test_functools hanging on the Android armv7 qemu emulator.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29639

   (2) https://bugs.python.org/issue31320

   (3) https://bugs.python.org/issue31346

   (4) https://bugs.python.org/issue25674

   (5) https://bugs.python.org/issue30715

   (6) https://bugs.python.org/issue30822

   (7) https://bugs.python.org/issue30695

   (8) https://bugs.python.org/issue30357

   (9) https://bugs.python.org/issue30197

   (10) https://bugs.python.org/issue24932

   (11) https://bugs.python.org/issue28950

   (12) https://bugs.python.org/issue28683

   (13) https://bugs.python.org/issue26936

   (14) https://bugs.python.org/issue28666

   (15) https://bugs.python.org/issue23839

   (16) https://bugs.python.org/issue26944

   (17) https://bugs.python.org/issue28409

   (18) https://bugs.python.org/issue28217

   (19) https://bugs.python.org/issue26939


File: python.info,  Node: 构建<26>,  Next: Windows<30>,  Prev: 测试<28>,  Up: Python 3 7 0 alpha 1

1.18.41.6 构建
..............

   - bpo-31354(1): Allow –with-lto to be used on all builds, not just
     ‘make profile-opt’.

   - bpo-31370(2): Remove support for building –without-threads.  This
     option is not really useful anymore in the 21st century.  Removing
     lots of conditional paths allows us to simplify the code base,
     including in difficult to maintain low-level internal code.

   - bpo-31341(3): Per PEP 11(4), support for the IRIX operating system
     was removed.

   - bpo-30854(5): Fix compile error when compiling –without-threads.
     Patch by Masayuki Yamamoto.

   - bpo-30687(6): Locate msbuild.exe on Windows when building rather
     than vcvarsall.bat

   - bpo-20210(7): Support the `disabled' marker in Setup files.
     Extension modules listed after this marker are not built at all,
     neither by the Makefile nor by setup.py.

   - bpo-29941(8): Add ‘--with-assertions’ configure flag to explicitly
     enable C ‘assert()’ checks.  Defaults to off.  ‘--with-pydebug’
     implies ‘--with-assertions’.

   - bpo-28787(9): Fix out-of-tree builds of Python when configured with
     ‘--with--dtrace’.

   - bpo-29243(10): Prevent unnecessary rebuilding of Python during
     ‘make test’, ‘make install’ and some other make targets when
     configured with ‘--enable-optimizations’.

   - bpo-23404(11): Don’t regenerate generated files based on file
     modification time anymore: the action is now explicit.  Replace
     ‘make touch’ with ‘make regen-all’.

   - bpo-29643(12): Fix ‘--enable-optimization’ didn’t work.

   - bpo-27593(13): sys.version and the platform module python_build(),
     python_branch(), and python_revision() functions now use git
     information rather than hg when building from a repo.

   - bpo-29572(14): 更新Windows 构建和OS X安装程序以使用OpenSSL 1.0.2k。

   - bpo-27659(15): Prohibit implicit C function declarations: use
     ‘-Werror=implicit-function-declaration’ when possible (GCC and
     Clang, but it depends on the compiler version).  Patch written by
     Chi Hsuan Yen.

   - bpo-29384(16): Remove old Be OS helper scripts.

   - bpo-26851(17): Set Android compilation and link flags.

   - bpo-28768(18): Fix implicit declaration of function _setmode.
     Patch by Masayuki Yamamoto

   - bpo-29080(19): Removes hard dependency on hg.exe from
     PCBuild/build.bat

   - bpo-23903(20): Added missed names to PC/python3.def.

   - bpo-28762(21): lockf() is available on Android API level 24, but
     the F_LOCK macro is not defined in android-ndk-r13.

   - bpo-28538(22): Fix the compilation error that occurs because
     if_nameindex() is available on Android API level 24, but the
     if_nameindex structure is not defined.

   - bpo-20211(23): Do not add the directory for installing C header
     files and the directory for installing object code libraries to the
     cross compilation search paths.  Original patch by Thomas
     Petazzoni.

   - bpo-28849(24): Do not define sys.implementation._multiarch on
     Android.

   - bpo-10656(25): Fix out-of-tree building on AIX. Patch by Tristan
     Carel and Michael Haubenwallner.

   - bpo-26359(26): Rename –with-optimiations to –enable-optimizations.

   - bpo-28444(27): Fix missing extensions modules when cross compiling.

   - bpo-28208(28): 更新Windows 构建和OS X 安装程序以使用SQLite 3.14.2.

   - bpo-28248(29): 更新Windows 构建和OS X安装程序以使用OpenSSL 1.0.2j.

   - bpo-21124(30): Fix building the _struct module on Cygwin by passing
     ‘NULL’ instead of ‘&PyType_Type’ to PyVarObject_HEAD_INIT. Patch by
     Masayuki Yamamoto.

   - bpo-13756(31): Fix building extensions modules on Cygwin.  Patch by
     Roumen Petrov, based on original patch by Jason Tishler.

   - bpo-21085(32): Add configure check for siginfo_t.si_band, which
     Cygwin does not provide.  Patch by Masayuki Yamamoto with review
     and rebase by Erik Bray.

   - bpo-28258(33): Fixed build with Estonian locale (python-config and
     distclean targets in Makefile).  Patch by Arfrever Frehtes
     Taifersar Arahesis.

   - bpo-26661(34): setup.py now detects system libffi with multiarch
     wrapper.

   - bpo-27979(35): A full copy of libffi is no longer bundled for use
     when building _ctypes on non-OSX UNIX platforms.  An installed copy
     of libffi is now required when building _ctypes on such platforms.

   - bpo-15819(36): Remove redundant include search directory option for
     building outside the source tree.

   - bpo-28676(37): Prevent missing ’getentropy’ declaration warning on
     macOS. Patch by Gareth Rees.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31354

   (2) https://bugs.python.org/issue31370

   (3) https://bugs.python.org/issue31341

   (4) https://www.python.org/dev/peps/pep-0011

   (5) https://bugs.python.org/issue30854

   (6) https://bugs.python.org/issue30687

   (7) https://bugs.python.org/issue20210

   (8) https://bugs.python.org/issue29941

   (9) https://bugs.python.org/issue28787

   (10) https://bugs.python.org/issue29243

   (11) https://bugs.python.org/issue23404

   (12) https://bugs.python.org/issue29643

   (13) https://bugs.python.org/issue27593

   (14) https://bugs.python.org/issue29572

   (15) https://bugs.python.org/issue27659

   (16) https://bugs.python.org/issue29384

   (17) https://bugs.python.org/issue26851

   (18) https://bugs.python.org/issue28768

   (19) https://bugs.python.org/issue29080

   (20) https://bugs.python.org/issue23903

   (21) https://bugs.python.org/issue28762

   (22) https://bugs.python.org/issue28538

   (23) https://bugs.python.org/issue20211

   (24) https://bugs.python.org/issue28849

   (25) https://bugs.python.org/issue10656

   (26) https://bugs.python.org/issue26359

   (27) https://bugs.python.org/issue28444

   (28) https://bugs.python.org/issue28208

   (29) https://bugs.python.org/issue28248

   (30) https://bugs.python.org/issue21124

   (31) https://bugs.python.org/issue13756

   (32) https://bugs.python.org/issue21085

   (33) https://bugs.python.org/issue28258

   (34) https://bugs.python.org/issue26661

   (35) https://bugs.python.org/issue27979

   (36) https://bugs.python.org/issue15819

   (37) https://bugs.python.org/issue28676


File: python.info,  Node: Windows<30>,  Next: IDLE<35>,  Prev: 构建<26>,  Up: Python 3 7 0 alpha 1

1.18.41.7 Windows
.................

   - bpo-31392(1): 更新Windows 构建以使用OpenSSL 1.1.0f

   - bpo-30389(2): Adds detection of Visual Studio 2017 to distutils on
     Windows.

   - bpo-31358(3): zlib is no longer bundled in the CPython source,
     instead it is downloaded on demand just like bz2, lzma, OpenSSL,
     Tcl/Tk, and SQLite.

   - bpo-31340(4): Change to building with MSVC v141 (included with
     Visual Studio 2017)

   - bpo-30581(5): os.cpu_count() now returns the correct number of
     processors on Windows when the number of logical processors is
     greater than 64.

   - bpo-30916(6): Pre-build OpenSSL, Tcl and Tk and include the
     binaries in the build.

   - bpo-30731(7): Add a missing xmlns to python.manifest so that it
     matches the schema.

   - bpo-30291(8): Allow requiring 64-bit interpreters from py.exe using
     -64 suffix.  Contributed by Steve (Gadget) Barnes.

   - bpo-30362(9): Adds list options (-0, -0p) to py.exe launcher.
     Contributed by Steve Barnes.

   - bpo-23451(10): Fix socket deprecation warnings in socketmodule.c.
     Patch by Segev Finer.

   - bpo-30450(11): The build process on Windows no longer depends on
     Subversion, instead pulling external code from GitHub via a Python
     script.  If Python 3.6 is not found on the system (via ‘py -3.6’),
     NuGet is used to download a copy of 32-bit Python.

   - bpo-29579(12): Removes readme.txt from the installer.

   - bpo-25778(13): winreg does not truncate string correctly (Patch by
     Eryk Sun)

   - bpo-28896(14): Deprecate WindowsRegistryFinder and disable it by
     default

   - bpo-28522(15): Fixes mishandled buffer reallocation in getpathp.c

   - bpo-28402(16): Adds signed catalog files for stdlib on Windows.

   - bpo-28333(17): Enables Unicode for ps1/ps2 and input() prompts.
     (Patch by Eryk Sun)

   - bpo-28251(18): Improvements to help manuals on Windows.

   - bpo-28110(19): launcher.msi has different product codes between
     32-bit and 64-bit

   - bpo-28161(20): Opening CON for write access fails

   - bpo-28162(21): WindowsConsoleIO readall() fails if first line
     starts with Ctrl+Z

   - bpo-28163(22): WindowsConsoleIO fileno() passes wrong flags to
     _open_osfhandle

   - bpo-28164(23): _PyIO_get_console_type fails for various paths

   - bpo-28137(24): Renames Windows path file to ._pth

   - bpo-28138(25): Windows ._pth file should allow import site

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31392

   (2) https://bugs.python.org/issue30389

   (3) https://bugs.python.org/issue31358

   (4) https://bugs.python.org/issue31340

   (5) https://bugs.python.org/issue30581

   (6) https://bugs.python.org/issue30916

   (7) https://bugs.python.org/issue30731

   (8) https://bugs.python.org/issue30291

   (9) https://bugs.python.org/issue30362

   (10) https://bugs.python.org/issue23451

   (11) https://bugs.python.org/issue30450

   (12) https://bugs.python.org/issue29579

   (13) https://bugs.python.org/issue25778

   (14) https://bugs.python.org/issue28896

   (15) https://bugs.python.org/issue28522

   (16) https://bugs.python.org/issue28402

   (17) https://bugs.python.org/issue28333

   (18) https://bugs.python.org/issue28251

   (19) https://bugs.python.org/issue28110

   (20) https://bugs.python.org/issue28161

   (21) https://bugs.python.org/issue28162

   (22) https://bugs.python.org/issue28163

   (23) https://bugs.python.org/issue28164

   (24) https://bugs.python.org/issue28137

   (25) https://bugs.python.org/issue28138


File: python.info,  Node: IDLE<35>,  Next: 工具/示例<18>,  Prev: Windows<30>,  Up: Python 3 7 0 alpha 1

1.18.41.8 IDLE
..............

   - bpo-31493(1): IDLE code context – fix code update and font update
     timers.  Canceling timers prevents a warning message when test_idle
     completes.

   - bpo-31488(2): IDLE - Update non-key options in former extension
     classes.  When applying configdialog changes, call .reload for each
     feature class.  Change ParenMatch so updated options affect
     existing instances attached to existing editor windows.

   - bpo-31477(3): IDLE - Improve rstrip entry in doc.  Strip trailing
     whitespace strips more than blank spaces.  Multiline string
     literals are not skipped.

   - bpo-31480(4): IDLE - make tests pass with zzdummy extension
     disabled by default.

   - bpo-31421(5): Document how IDLE runs tkinter programs.  IDLE calls
     tcl/tk update in the background in order to make live interaction
     and experimentation with tkinter applications much easier.

   - bpo-31414(6): IDLE – fix tk entry box tests by deleting first.
     Adding to an int entry is not the same as deleting and inserting
     because int(’’) will fail.

   - bpo-31051(7): Rearrange IDLE configdialog GenPage into Window,
     Editor, and Help sections.

   - bpo-30617(8): IDLE - Add docstrings and tests for outwin subclass
     of editor.  Move some data and functions from the class to module
     level.  Patch by Cheryl Sabella.

   - bpo-31287(9): IDLE - Do not modify tkinter.message in
     test_configdialog.

   - bpo-27099(10): Convert IDLE’s built-in ’extensions’ to regular
     features.  About 10 IDLE features were implemented as supposedly
     optional extensions.  Their different behavior could be confusing
     or worse for users and not good for maintenance.  Hence the
     conversion.  The main difference for users is that user
     configurable key bindings for builtin features are now handled
     uniformly.  Now, editing a binding in a keyset only affects its
     value in the keyset.  All bindings are defined together in the
     system-specific default keysets in config-extensions.def.  All
     custom keysets are saved as a whole in config-extension.cfg.  All
     take effect as soon as one clicks Apply or Ok.  The affected events
     are ’<<force-open-completions>>’, ’<<expand-word>>’,
     ’<<force-open-calltip>>’, ’<<flash-paren>>’,
     ’<<format-paragraph>>’, ’<<run-module>>’, ’<<check-module>>’, and
     ’<<zoom-height>>’.  Any (global) customizations made before 3.6.3
     will not affect their keyset-specific customization after 3.6.3.
     and vice versa.  Initial patch by Charles Wohlganger.

   - bpo-31206(11): IDLE: Factor HighPage(Frame) class from
     ConfigDialog.  Patch by Cheryl Sabella.

   - bpo-31001(12): Add tests for configdialog highlight tab.  Patch by
     Cheryl Sabella.

   - bpo-31205(13): IDLE: Factor KeysPage(Frame) class from
     ConfigDialog.  The slightly modified tests continue to pass.  Patch
     by Cheryl Sabella.

   - bpo-31130(14): IDLE – stop leaks in test_configdialog.  Initial
     patch by Victor Stinner.

   - bpo-31002(15): Add tests for configdialog keys tab.  Patch by
     Cheryl Sabella.

   - bpo-19903(16): IDLE: Calltips use *note inspect.signature: 564.
     instead of *note inspect.getfullargspec: 566.  This improves
     calltips for builtins converted to use Argument Clinic.  Patch by
     Louie Lu.

   - bpo-31083(17): IDLE - Add an outline of a TabPage class in
     configdialog.  Update existing classes to match outline.  Initial
     patch by Cheryl Sabella.

   - bpo-31050(18): Factor GenPage(Frame) class from ConfigDialog.  The
     slightly modified tests continue to pass.  Patch by Cheryl Sabella.

   - bpo-31004(19): IDLE - Factor FontPage(Frame) class from
     ConfigDialog.  Slightly modified tests continue to pass.  Fix
     General tests.  Patch mostly by Cheryl Sabella.

   - bpo-30781(20): IDLE - Use ttk widgets in ConfigDialog.  Patches by
     Terry Jan Reedy and Cheryl Sabella.

   - bpo-31060(21): IDLE - Finish rearranging methods of ConfigDialog
     Grouping methods pertaining to each tab and the buttons will aid
     writing tests and improving the tabs and will enable splitting the
     groups into classes.

   - bpo-30853(22): IDLE – Factor a VarTrace class out of ConfigDialog.
     Instance tracers manages pairs consisting of a tk variable and a
     callback function.  When tracing is turned on, setting the variable
     calls the function.  Test coverage for the new class is 100%.

   - bpo-31003(23): IDLE: Add more tests for General tab.

   - bpo-30993(24): IDLE - Improve configdialog font page and tests.  In
     configdialog: Document causal pathways in create_font_tab
     docstring.  Simplify some attribute names.  Move set_samples calls
     to var_changed_font (idea from Cheryl Sabella).  Move related
     functions to positions after the create widgets function.  In
     test_configdialog: Fix test_font_set so not order dependent.  Fix
     renamed test_indent_scale so it tests the widget.  Adjust tests for
     movement of set_samples call.  Add tests for load functions.  Put
     all font tests in one class and tab indent tests in another.
     Except for two lines, these tests completely cover the related
     functions.

   - bpo-30981(25): IDLE – Add more configdialog font page tests.

   - bpo-28523(26): IDLE: replace ’colour’ with ’color’ in configdialog.

   - bpo-30917(27): Add tests for idlelib.config.IdleConf.  Increase
     coverage from 46% to 96%.  Patch by Louie Lu.

   - bpo-30934(28): Document coverage details for idlelib tests.  Add
     section to idlelib/idle-test/README.txt.  Include check that
     branches are taken both ways.  Exclude IDLE-specific code that does
     not run during unit tests.

   - bpo-30913(29): IDLE: Document ConfigDialog tk Vars, methods, and
     widgets in docstrings This will facilitate improving the dialog and
     splitting up the class.  Original patch by Cheryl Sabella.

   - bpo-30899(30): IDLE: Add tests for ConfigParser subclasses in
     config.  Patch by Louie Lu.

   - bpo-30881(31): IDLE: Add docstrings to browser.py.  Patch by Cheryl
     Sabella.

   - bpo-30851(32): IDLE: Remove unused variables in configdialog.  One
     is a duplicate, one is set but cannot be altered by users.  Patch
     by Cheryl Sabella.

   - bpo-30870(33): IDLE: In Settings dialog, select font with Up, Down
     keys as well as mouse.  Initial patch by Louie Lu.

   - bpo-8231(34): IDLE: call config.IdleConf.GetUserCfgDir only once.

   - bpo-30779(35): IDLE: Factor ConfigChanges class from configdialog,
     put in config; test.  * In config, put dump test code in a
     function; run it and unittest in ’if __name__ == ’__main__’.  * Add
     class config.ConfigChanges based on changes_class_v4.py on bpo
     issue.  * Add class test_config.ChangesTest, partly using
     configdialog_tests_v1.py.  * Revise configdialog to use
     ConfigChanges; see tracker msg297804.  * Revise test_configdialog
     to match configdialog changes.  * Remove configdialog functions
     unused or moved to ConfigChanges.  Cheryl Sabella contributed parts
     of the patch.

   - bpo-30777(36): IDLE: configdialog - Add docstrings and fix
     comments.  Patch by Cheryl Sabella.

   - bpo-30495(37): IDLE: Improve textview with docstrings, PEP8 names,
     and more tests.  Patch by Cheryl Sabella.

   - bpo-30723(38): IDLE: Make several improvements to parenmatch.  Add
     ’parens’ style to highlight both opener and closer.  Make ’default’
     style, which is not default, a synonym for ’opener’.  Make
     time-delay work the same with all styles.  Add help for config
     dialog extensions tab, including help for parenmatch.  Add new
     tests.  Original patch by Charles Wohlganger.

   - bpo-30674(39): IDLE: add docstrings to grep module.  Patch by
     Cheryl Sabella

   - bpo-21519(40): IDLE’s basic custom key entry dialog now detects
     duplicates properly.  Original patch by Saimadhav Heblikar.

   - bpo-29910(41): IDLE no longer deletes a character after commenting
     out a region by a key shortcut.  Add ‘return 'break'’ for this and
     other potential conflicts between IDLE and default key bindings.

   - bpo-30728(42): Review and change idlelib.configdialog names.
     Lowercase method and attribute names.  Replace ’colour’ with
     ’color’, expand overly cryptic names, delete unneeded underscores.
     Replace ‘import *’ with specific imports.  Patches by Cheryl
     Sabella.

   - bpo-6739(43): IDLE: Verify user-entered key sequences by trying to
     bind them with tk.  Add tests for all 3 validation functions.
     Original patch by G Polo.  Tests added by Cheryl Sabella.

   - bpo-15786(44): Fix several problems with IDLE’s autocompletion box.
     The following should now work: clicking on selection box items;
     using the scrollbar; selecting an item by hitting Return.  Hangs on
     MacOSX should no longer happen.  Patch by Louie Lu.

   - bpo-25514(45): Add doc subsubsection about IDLE failure to start.
     Popup no-connection message directs users to this section.

   - bpo-30642(46): Fix reference leaks in IDLE tests.  Patches by Louie
     Lu and Terry Jan Reedy.

   - bpo-30495(47): Add docstrings for textview.py and use PEP8 names.
     Patches by Cheryl Sabella and Terry Jan Reedy.

   - bpo-30290(48): Help-about: use pep8 names and add tests.  Increase
     coverage to 100%.  Patches by Louie Lu, Cheryl Sabella, and Terry
     Jan Reedy.

   - bpo-30303(49): Add _utest option to textview; add new tests.
     Increase coverage to 100%.  Patches by Louie Lu and Terry Jan
     Reedy.

   - bpo-29071(50): IDLE colors f-string prefixes (but not invalid ur
     prefixes).

   - bpo-28572(51): Add 10% to coverage of IDLE’s test_configdialog.
     Update and augment description of the configuration system.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31493

   (2) https://bugs.python.org/issue31488

   (3) https://bugs.python.org/issue31477

   (4) https://bugs.python.org/issue31480

   (5) https://bugs.python.org/issue31421

   (6) https://bugs.python.org/issue31414

   (7) https://bugs.python.org/issue31051

   (8) https://bugs.python.org/issue30617

   (9) https://bugs.python.org/issue31287

   (10) https://bugs.python.org/issue27099

   (11) https://bugs.python.org/issue31206

   (12) https://bugs.python.org/issue31001

   (13) https://bugs.python.org/issue31205

   (14) https://bugs.python.org/issue31130

   (15) https://bugs.python.org/issue31002

   (16) https://bugs.python.org/issue19903

   (17) https://bugs.python.org/issue31083

   (18) https://bugs.python.org/issue31050

   (19) https://bugs.python.org/issue31004

   (20) https://bugs.python.org/issue30781

   (21) https://bugs.python.org/issue31060

   (22) https://bugs.python.org/issue30853

   (23) https://bugs.python.org/issue31003

   (24) https://bugs.python.org/issue30993

   (25) https://bugs.python.org/issue30981

   (26) https://bugs.python.org/issue28523

   (27) https://bugs.python.org/issue30917

   (28) https://bugs.python.org/issue30934

   (29) https://bugs.python.org/issue30913

   (30) https://bugs.python.org/issue30899

   (31) https://bugs.python.org/issue30881

   (32) https://bugs.python.org/issue30851

   (33) https://bugs.python.org/issue30870

   (34) https://bugs.python.org/issue8231

   (35) https://bugs.python.org/issue30779

   (36) https://bugs.python.org/issue30777

   (37) https://bugs.python.org/issue30495

   (38) https://bugs.python.org/issue30723

   (39) https://bugs.python.org/issue30674

   (40) https://bugs.python.org/issue21519

   (41) https://bugs.python.org/issue29910

   (42) https://bugs.python.org/issue30728

   (43) https://bugs.python.org/issue6739

   (44) https://bugs.python.org/issue15786

   (45) https://bugs.python.org/issue25514

   (46) https://bugs.python.org/issue30642

   (47) https://bugs.python.org/issue30495

   (48) https://bugs.python.org/issue30290

   (49) https://bugs.python.org/issue30303

   (50) https://bugs.python.org/issue29071

   (51) https://bugs.python.org/issue28572


File: python.info,  Node: 工具/示例<18>,  Next: C API<22>,  Prev: IDLE<35>,  Up: Python 3 7 0 alpha 1

1.18.41.9 工具/示例
...................

   - bpo-30983(1): gdb integration commands (py-bt, etc.)  work on
     optimized shared builds now, too.  PEP 523(2) introduced
     _PyEval_EvalFrameDefault which inlines PyEval_EvalFrameEx on
     non-debug shared builds.  This broke the ability to use py-bt,
     py-up, and a few other Python-specific gdb integrations.  The
     problem is fixed by only looking for _PyEval_EvalFrameDefault
     frames in python-gdb.py.  Original patch by Bruno "Polaco"
     Penteado.

   - bpo-29748(3): Added the slice index converter in Argument Clinic.

   - bpo-24037(4): Argument Clinic now uses the converter
     ‘bool(accept={int})’ rather than *note int: 185. for semantical
     booleans.  This avoids repeating the default value for Python and C
     and will help in converting to *note bool: 184. in future.

   - bpo-29367(5): python-gdb.py now supports also ‘method-wrapper’
     (‘wrapperobject’) objects.

   - bpo-28023(6): Fix python-gdb.py didn’t support new dict
     implementation.

   - bpo-15369(7): The pybench and pystone microbenchmark have been
     removed from Tools.  Please use the new Python benchmark suite
     ‘https://github.com/python/performance’ which is more reliable and
     includes a portable version of pybench working on Python 2 and
     Python 3.

   - bpo-28102(8): The zipfile module CLI now prints usage to stderr.
     Patch by Stephen J. Turnbull.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30983

   (2) https://www.python.org/dev/peps/pep-0523

   (3) https://bugs.python.org/issue29748

   (4) https://bugs.python.org/issue24037

   (5) https://bugs.python.org/issue29367

   (6) https://bugs.python.org/issue28023

   (7) https://bugs.python.org/issue15369

   (8) https://bugs.python.org/issue28102


File: python.info,  Node: C API<22>,  Prev: 工具/示例<18>,  Up: Python 3 7 0 alpha 1

1.18.41.10 C API
................

   - bpo-31338(1): Added the ‘Py_UNREACHABLE()’ macro for code paths
     which are never expected to be reached.  This and a few other
     useful macros are now documented in the C API manual.

   - bpo-30832(2): Remove own implementation for thread-local storage.
     CPython has provided the own implementation for thread-local
     storage (TLS) on Python/thread.c, it’s used in the case which a
     platform has not supplied native TLS. However, currently all
     supported platforms (Windows and pthreads) have provided native TLS
     and defined the Py_HAVE_NATIVE_TLS macro with unconditional in any
     case.

   - bpo-30708(3): PyUnicode_AsWideCharString() now raises a ValueError
     if the second argument is NULL and the wchar_t* string contains
     null characters.

   - bpo-16500(4): Deprecate PyOS_AfterFork() and add PyOS_BeforeFork(),
     PyOS_AfterFork_Parent() and PyOS_AfterFork_Child().

   - bpo-6532(5): The type of results of PyThread_start_new_thread() and
     PyThread_get_thread_ident(), and the id parameter of
     PyThreadState_SetAsyncExc() changed from "long" to "unsigned long".

   - bpo-27867(6): Function PySlice_GetIndicesEx() is deprecated and
     replaced with a macro if Py_LIMITED_API is not set or set to the
     value between 0x03050400 and 0x03060000 (not including) or
     0x03060100 or higher.  Added functions PySlice_Unpack() and
     PySlice_AdjustIndices().

   - bpo-29083(7): Fixed the declaration of some public API functions.
     PyArg_VaParse() and PyArg_VaParseTupleAndKeywords() were not
     available in limited API. PyArg_ValidateKeywordArguments(),
     PyArg_UnpackTuple() and Py_BuildValue() were not available in
     limited API of version < 3.3 when PY_SSIZE_T_CLEAN is defined.

   - bpo-28769(8): The result of PyUnicode_AsUTF8AndSize() and
     PyUnicode_AsUTF8() is now of type ‘const char *’ rather of ‘char
     *’.

   - bpo-29058(9): All stable API extensions added after Python 3.2 are
     now available only when Py_LIMITED_API is set to the PY_VERSION_HEX
     value of the minimum Python version supporting this API.

   - bpo-28822(10): The index parameters `start' and `end' of
     PyUnicode_FindChar() are now adjusted to behave like
     ‘str[start:end]’.

   - bpo-28808(11): PyUnicode_CompareWithASCIIString() now never raises
     exceptions.

   - bpo-28761(12): The fields name and doc of structures PyMemberDef,
     PyGetSetDef, PyStructSequence_Field, PyStructSequence_Desc, and
     wrapperbase are now of type ‘const char *’ rather of ‘char *’.

   - bpo-28748(13): Private variable _Py_PackageContext is now of type
     ‘const char *’ rather of ‘char *’.

   - bpo-19569(14): Compiler warnings are now emitted if use most of
     deprecated functions.

   - bpo-28426(15): Deprecated undocumented functions
     PyUnicode_AsEncodedObject(), PyUnicode_AsDecodedObject(),
     PyUnicode_AsDecodedUnicode() and PyUnicode_AsEncodedUnicode().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31338

   (2) https://bugs.python.org/issue30832

   (3) https://bugs.python.org/issue30708

   (4) https://bugs.python.org/issue16500

   (5) https://bugs.python.org/issue6532

   (6) https://bugs.python.org/issue27867

   (7) https://bugs.python.org/issue29083

   (8) https://bugs.python.org/issue28769

   (9) https://bugs.python.org/issue29058

   (10) https://bugs.python.org/issue28822

   (11) https://bugs.python.org/issue28808

   (12) https://bugs.python.org/issue28761

   (13) https://bugs.python.org/issue28748

   (14) https://bugs.python.org/issue19569

   (15) https://bugs.python.org/issue28426


File: python.info,  Node: Python 3 6 6 正式版,  Next: Python 3 6 6 rc1,  Prev: Python 3 7 0 alpha 1,  Up: 更新日志

1.18.42 Python 3.6.6 正式版
---------------------------

`发布日期: 2018-06-27'

在 3.6.6 版本中没有新的更改。


File: python.info,  Node: Python 3 6 6 rc1,  Next: Python 3 6 5 正式版,  Prev: Python 3 6 6 正式版,  Up: 更新日志

1.18.43 Python 3.6.6 rc1
------------------------

`发布日期: 2018-06-11'

* Menu:

* 核心与内置: 核心与内置<40>.
* 库: 库<41>.
* 文档: 文档<36>.
* 测试: 测试<29>.
* 构建: 构建<27>.
* Windows: Windows<31>.
* macOS: macOS<23>.
* IDLE: IDLE<36>.
* 工具/示例: 工具/示例<19>.
* C API: C API<23>.


File: python.info,  Node: 核心与内置<40>,  Next: 库<41>,  Up: Python 3 6 6 rc1

1.18.43.1 核心与内置
....................

   - bpo-33786(1): Fix asynchronous generators to handle GeneratorExit
     in athrow() correctly

   - bpo-30654(2): Fixed reset of the SIGINT handler to SIG_DFL on
     interpreter shutdown even when there was a custom handler set
     previously.  Patch by Philipp Kerling.

   - bpo-33622(3): Fixed a leak when the garbage collector fails to add
     an object with the ‘__del__’ method or referenced by it into the
     *note gc.garbage: b48. list.  ‘PyGC_Collect()’ can now be called
     when an exception is set and preserves it.

   - bpo-31849(4): Fix signed/unsigned comparison warning in pyhash.c.

   - bpo-33391(5): Fix a leak in set_symmetric_difference().

   - bpo-28055(6): Fix unaligned accesses in siphash24().  Patch by Rolf
     Eike Beer.

   - bpo-33231(7): 修复 ‘normalizestring()’ 中潜在的内存泄漏。

   - bpo-29922(8): Improved error messages in ’async with’ when
     ‘__aenter__()’ or ‘__aexit__()’ return non-awaitable object.

   - bpo-33199(9): Fix ‘ma_version_tag’ in dict implementation is
     uninitialized when copying from key-sharing dict.

   - bpo-33041(10): Fixed jumping when the function contains an ‘async
     for’ loop.

   - bpo-32282(11): Fix an unnecessary ifdef in the include of
     VersionHelpers.h in socketmodule on Windows.

   - bpo-21983(12): Fix a crash in *note ctypes.cast(): 1023. in case
     the type argument is a ctypes structured data type.  Patch by Eryk
     Sun and Oren Milman.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33786

   (2) https://bugs.python.org/issue30654

   (3) https://bugs.python.org/issue33622

   (4) https://bugs.python.org/issue31849

   (5) https://bugs.python.org/issue33391

   (6) https://bugs.python.org/issue28055

   (7) https://bugs.python.org/issue33231

   (8) https://bugs.python.org/issue29922

   (9) https://bugs.python.org/issue33199

   (10) https://bugs.python.org/issue33041

   (11) https://bugs.python.org/issue32282

   (12) https://bugs.python.org/issue21983


File: python.info,  Node: 库<41>,  Next: 文档<36>,  Prev: 核心与内置<40>,  Up: Python 3 6 6 rc1

1.18.43.2 库
............

   - bpo-30167(1): Prevent site.main() exception if PYTHONSTARTUP is
     set.  Patch by Steve Weber.

   - bpo-33812(2): Datetime instance d with non-None tzinfo, but with
     d.tzinfo.utcoffset(d) returning None is now treated as naive by the
     astimezone() method.

   - bpo-30805(3): Avoid race condition with debug logging

   - bpo-33767(4): The concatenation (‘+’) and repetition (‘*’) sequence
     operations now raise *note TypeError: 193. instead of *note
     SystemError: 604. when performed on *note mmap.mmap: 1ed. objects.
     Patch by Zackery Spytz.

   - bpo-32684(5): Fix gather to propagate cancellation of itself even
     with return_exceptions.

   - bpo-33674(6): Fix a race condition in SSLProtocol.connection_made()
     of asyncio.sslproto: start immediately the handshake instead of
     using call_soon().  Previously, data_received() could be called
     before the handshake started, causing the handshake to hang or
     fail.

   - bpo-31647(7): Fixed bug where calling write_eof() on a
     _SelectorSocketTransport after it’s already closed raises
     AttributeError.

   - bpo-33672(8): Fix Task.__repr__ crash with Cython’s bogus
     coroutines

   - bpo-33469(9): Fix RuntimeError after closing loop that used
     run_in_executor

   - bpo-11874(10): Use a better regex when breaking usage into
     wrappable parts.  Avoids bogus assertion errors from custom metavar
     strings.

   - bpo-30877(11): Fixed a bug in the Python implementation of the JSON
     decoder that prevented the cache of parsed strings from clearing
     after finishing the decoding.  Based on patch by c-fos.

   - bpo-33548(12): tempfile._candidate_tempdir_list should consider
     common TEMP locations

   - bpo-33542(13): Prevent ‘uuid.get_node’ from using a DUID instead of
     a MAC on Windows.  Patch by Zvi Effron

   - bpo-26819(14): Fix race condition with
     ‘ReadTransport.resume_reading’ in Windows proactor event loop.

   - bpo-28556(15): Minor fixes in typing module: add annotations to
     ‘NamedTuple.__new__’, pass ‘*args’ and ‘**kwds’ in
     ‘Generic.__new__’.  Original PRs by Paulius Šarka and Chad
     Dombrova.

   - bpo-20087(16): Updated alias mapping with glibc 2.27 supported
     locales.

   - bpo-33422(17): Fix trailing quotation marks getting deleted when
     looking up byte/string literals on pydoc.  Patch by Andrés Delfino.

   - bpo-33197(18): Update error message when constructing invalid
     inspect.Parameters Patch by Dong-hee Na.

   - bpo-33383(19): Fixed crash in the get() method of the *note
     dbm.ndbm: 35. database object when it is called with a single
     argument.

   - bpo-33329(20): Fix multiprocessing regression on newer glibcs

   - bpo-991266(21): Fix quoting of the ‘Comment’ attribute of *note
     http.cookies.SimpleCookie: 1048.

   - bpo-33131(22): Upgrade bundled version of pip to 10.0.1.

   - bpo-33308(23): Fixed a crash in the *note parser: c8. module when
     converting an ST object to a tree of tuples or lists with
     ‘line_info=False’ and ‘col_info=True’.

   - bpo-33263(24): Fix FD leak in ‘_SelectorSocketTransport’ Patch by
     Vlad Starostin.

   - bpo-33256(25): Fix display of ‘<module>’ call in the html produced
     by ‘cgitb.html()’.  Patch by Stéphane Blondon.

   - bpo-33203(26): ‘random.Random.choice()’ now raises ‘IndexError’ for
     empty sequences consistently even when called from subclasses
     without a ‘getrandbits()’ implementation.

   - bpo-33224(27): Update difflib.mdiff() for PEP 479(28).  Convert an
     uncaught StopIteration in a generator into a return-statement.

   - bpo-33209(29): End framing at the end of C implementation of *note
     pickle.Pickler.dump(): 104c.

   - bpo-32861(30): The urllib.robotparser’s ‘__str__’ representation
     now includes wildcard entries and the "Crawl-delay" and
     "Request-rate" fields.  Patch by Michael Lazar.

   - bpo-33096(31): Allow ttk.Treeview.insert to insert iid that has a
     false boolean value.  Note iid=0 and iid=False would be same.
     Patch by Garvit Khatri.

   - bpo-33127(32): ssl模块现在使用LibreSSL 2.7.1编译。

   - bpo-33021(33): Release the GIL during fstat() calls, avoiding hang
     of all threads when calling mmap.mmap(), os.urandom(), and
     random.seed().  Patch by Nir Soffer.

   - bpo-27683(34): Fix a regression in *note ipaddress: a3. that result
     of ‘hosts()’ is empty when the network is constructed by a tuple
     containing an integer mask and only 1 bit left for addresses.

   - bpo-32844(35): Fix wrong redirection of a low descriptor (0 or 1)
     to stderr in subprocess if another low descriptor is closed.

   - bpo-31908(36): Fix output of cover files for ‘trace’ module
     command-line tool.  Previously emitted cover files only when
     ‘--missing’ option was used.  Patch by Michael Selik.

   - bpo-31457(37): If nested log adapters are used, the inner
     ‘process()’ methods are no longer omitted.

   - bpo-16865(38): Support arrays >=2GiB in *note ctypes: 2b.  Patch by
     Segev Finer.

   - bpo-31238(39): pydoc: the stop() method of the private ServerThread
     class now waits until DocServer.serve_until_quit() completes and
     then explicitly sets its docserver attribute to None to break a
     reference cycle.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30167

   (2) https://bugs.python.org/issue33812

   (3) https://bugs.python.org/issue30805

   (4) https://bugs.python.org/issue33767

   (5) https://bugs.python.org/issue32684

   (6) https://bugs.python.org/issue33674

   (7) https://bugs.python.org/issue31647

   (8) https://bugs.python.org/issue33672

   (9) https://bugs.python.org/issue33469

   (10) https://bugs.python.org/issue11874

   (11) https://bugs.python.org/issue30877

   (12) https://bugs.python.org/issue33548

   (13) https://bugs.python.org/issue33542

   (14) https://bugs.python.org/issue26819

   (15) https://bugs.python.org/issue28556

   (16) https://bugs.python.org/issue20087

   (17) https://bugs.python.org/issue33422

   (18) https://bugs.python.org/issue33197

   (19) https://bugs.python.org/issue33383

   (20) https://bugs.python.org/issue33329

   (21) https://bugs.python.org/issue991266

   (22) https://bugs.python.org/issue33131

   (23) https://bugs.python.org/issue33308

   (24) https://bugs.python.org/issue33263

   (25) https://bugs.python.org/issue33256

   (26) https://bugs.python.org/issue33203

   (27) https://bugs.python.org/issue33224

   (28) https://www.python.org/dev/peps/pep-0479

   (29) https://bugs.python.org/issue33209

   (30) https://bugs.python.org/issue32861

   (31) https://bugs.python.org/issue33096

   (32) https://bugs.python.org/issue33127

   (33) https://bugs.python.org/issue33021

   (34) https://bugs.python.org/issue27683

   (35) https://bugs.python.org/issue32844

   (36) https://bugs.python.org/issue31908

   (37) https://bugs.python.org/issue31457

   (38) https://bugs.python.org/issue16865

   (39) https://bugs.python.org/issue31238


File: python.info,  Node: 文档<36>,  Next: 测试<29>,  Prev: 库<41>,  Up: Python 3 6 6 rc1

1.18.43.3 文档
..............

   - bpo-33503(1): 修复错误的pypi链接

   - bpo-33421(2): 为‘‘typing.AsyncContextManager‘‘添加缺失的文档。

   - bpo-33378(3): Add Korean language switcher for
     ‘https://docs.python.org/3/’

   - bpo-33276(4): Clarify that the ‘__path__’ attribute on modules
     cannot be just any value.

   - bpo-33201(5): Modernize documentation for writing C extension
     types.

   - bpo-33195(6): Deprecate ‘Py_UNICODE’ usage in ‘c-api/arg’ document.
     ‘Py_UNICODE’ related APIs are deprecated since Python 3.3, but it
     is missed in the document.

   - bpo-33126(7): Document PyBuffer_ToContiguous().

   - bpo-27212(8): Modify documentation for the ‘islice()’ recipe to
     consume initial values up to the start index.

   - bpo-28247(9): Update *note zipapp: 142. documentation to describe
     how to make standalone applications.

   - bpo-18802(10): Documentation changes for ipaddress.  Patch by Jon
     Foster and Berker Peksag.

   - bpo-27428(11): Update documentation to clarify that
     ‘WindowsRegistryFinder’ implements ‘MetaPathFinder’.  (Patch by
     Himanshu Lakhara)

   - bpo-8243(12): Add a note about curses.addch and curses.addstr
     exception behavior when writing outside a window, or pad.

   - bpo-31432(13): Clarify meaning of CERT_NONE, CERT_OPTIONAL, and
     CERT_REQUIRED flags for ssl.SSLContext.verify_mode.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33503

   (2) https://bugs.python.org/issue33421

   (3) https://bugs.python.org/issue33378

   (4) https://bugs.python.org/issue33276

   (5) https://bugs.python.org/issue33201

   (6) https://bugs.python.org/issue33195

   (7) https://bugs.python.org/issue33126

   (8) https://bugs.python.org/issue27212

   (9) https://bugs.python.org/issue28247

   (10) https://bugs.python.org/issue18802

   (11) https://bugs.python.org/issue27428

   (12) https://bugs.python.org/issue8243

   (13) https://bugs.python.org/issue31432


File: python.info,  Node: 测试<29>,  Next: 构建<27>,  Prev: 文档<36>,  Up: Python 3 6 6 rc1

1.18.43.4 测试
..............

   - bpo-33655(1): 忽略运行在BSD平台的ZFS上时test_posix_fallocate的失败
     。

   - bpo-19417(2): Add test_bdb.py.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33655

   (2) https://bugs.python.org/issue19417


File: python.info,  Node: 构建<27>,  Next: Windows<31>,  Prev: 测试<29>,  Up: Python 3 6 6 rc1

1.18.43.5 构建
..............

   - bpo-5755(1): Move ‘-Wstrict-prototypes’ option to ‘CFLAGS_NODIST’
     from ‘OPT’.  This option emitted annoying warnings when building
     extension modules written in C++.

   - bpo-33614(2): Ensures module definition files for the stable ABI on
     Windows are correctly regenerated.

   - bpo-33522(3): Enable CI builds on Visual Studio Team Services at
     ‘https://python.visualstudio.com/cpython’

   - bpo-33012(4): Add ‘-Wno-cast-function-type’ for gcc 8 for silencing
     warnings about function casts like casting to PyCFunction in method
     definition lists.

   - bpo-33394(5): Enable the verbose build for extension modules, when
     GNU make is passed macros on the command line.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5755

   (2) https://bugs.python.org/issue33614

   (3) https://bugs.python.org/issue33522

   (4) https://bugs.python.org/issue33012

   (5) https://bugs.python.org/issue33394


File: python.info,  Node: Windows<31>,  Next: macOS<23>,  Prev: 构建<27>,  Up: Python 3 6 6 rc1

1.18.43.6 Windows
.................

   - bpo-33184(1): 更新Windows 构建以使用OpenSSL 1.0.2o.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33184


File: python.info,  Node: macOS<23>,  Next: IDLE<36>,  Prev: Windows<31>,  Up: Python 3 6 6 rc1

1.18.43.7 macOS
...............

   - bpo-33184(1): 更新macOS 安装程序以使用OpenSSL 1.0.2o.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33184


File: python.info,  Node: IDLE<36>,  Next: 工具/示例<19>,  Prev: macOS<23>,  Up: Python 3 6 6 rc1

1.18.43.8 IDLE
..............

   - bpo-33656(1): On Windows, add API call saying that tk scales for
     DPI. On Windows 8.1+ or 10, with DPI compatibility properties of
     the Python binary unchanged, and a monitor resolution greater than
     96 DPI, this should make text and lines sharper.  It should
     otherwise have no effect.

   - bpo-33768(2): Clicking on a context line moves that line to the top
     of the editor window.

   - bpo-33763(3): IDLE: Use read-only text widget for code context
     instead of label widget.

   - bpo-33664(4): Scroll IDLE editor text by lines.  Previously, the
     mouse wheel and scrollbar slider moved text by a fixed number of
     pixels, resulting in partial lines at the top of the editor box.
     The change also applies to the shell and grep output windows, but
     not to read-only text views.

   - bpo-33679(5): Enable theme-specific color configuration for Code
     Context.  Use the Highlights tab to see the setting for built-in
     themes or add settings to custom themes.

   - bpo-33642(6): Display up to maxlines non-blank lines for Code
     Context.  If there is no current context, show a single blank line.

   - bpo-33628(7): IDLE: Cleanup codecontext.py and its test.

   - bpo-33564(8): IDLE’s code context now recognizes async as a block
     opener.

   - bpo-29706(9): IDLE now colors async and await as keywords in 3.6.
     They become full keywords in 3.7.

   - bpo-21474(10): Update word/identifier definition from ascii to
     unicode.  In text and entry boxes, this affects selection by
     double-click, movement left/right by control-left/right, and
     deletion left/right by control-BACKSPACE/DEL.

   - bpo-33204(11): IDLE: consistently color invalid string prefixes.  A
     ’u’ string prefix cannot be paired with either ’r’ or ’f’.
     Consistently color as much of the prefix, starting at the right, as
     is valid.  Revise and extend colorizer test.

   - bpo-32831(12): Add docstrings and tests for codecontext.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33656

   (2) https://bugs.python.org/issue33768

   (3) https://bugs.python.org/issue33763

   (4) https://bugs.python.org/issue33664

   (5) https://bugs.python.org/issue33679

   (6) https://bugs.python.org/issue33642

   (7) https://bugs.python.org/issue33628

   (8) https://bugs.python.org/issue33564

   (9) https://bugs.python.org/issue29706

   (10) https://bugs.python.org/issue21474

   (11) https://bugs.python.org/issue33204

   (12) https://bugs.python.org/issue32831


File: python.info,  Node: 工具/示例<19>,  Next: C API<23>,  Prev: IDLE<36>,  Up: Python 3 6 6 rc1

1.18.43.9 工具/示例
...................

   - bpo-33189(1): ‘pygettext.py’ now recognizes only literal strings as
     docstrings and translatable strings, and rejects bytes literals and
     f-string expressions.

   - bpo-31920(2): Fixed handling directories as arguments in the
     ‘pygettext’ script.  Based on patch by Oleg Krasnikov.

   - bpo-29673(3): Fix pystackv and pystack gdbinit macros.

   - bpo-32885(4): Add an ‘-n’ flag for ‘Tools/scripts/pathfix.py’ to
     disable automatic backup creation (files with ‘~’ suffix).

   - bpo-31583(5): Fix 2to3 for using with –add-suffix option but
     without –output-dir option for relative path to files in current
     directory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33189

   (2) https://bugs.python.org/issue31920

   (3) https://bugs.python.org/issue29673

   (4) https://bugs.python.org/issue32885

   (5) https://bugs.python.org/issue31583


File: python.info,  Node: C API<23>,  Prev: 工具/示例<19>,  Up: Python 3 6 6 rc1

1.18.43.10 C API
................

   - bpo-32374(1): Document that m_traverse for multi-phase initialized
     modules can be called with m_state=NULL, and add a sanity check

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32374


File: python.info,  Node: Python 3 6 5 正式版,  Next: Python 3 6 5 rc1,  Prev: Python 3 6 6 rc1,  Up: 更新日志

1.18.44 Python 3.6.5 正式版
---------------------------

`发布日期: 2018-03-28'

* Menu:

* 测试: 测试<30>.
* 构建: 构建<28>.


File: python.info,  Node: 测试<30>,  Next: 构建<28>,  Up: Python 3 6 5 正式版

1.18.44.1 测试
..............

   - bpo-32872(1): Avoid regrtest compatibility issue with namespace
     packages.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32872


File: python.info,  Node: 构建<28>,  Prev: 测试<30>,  Up: Python 3 6 5 正式版

1.18.44.2 构建
..............

   - bpo-33163(1): Upgrade pip to 9.0.3 and setuptools to v39.0.1.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33163


File: python.info,  Node: Python 3 6 5 rc1,  Next: Python 3 6 4 正式版,  Prev: Python 3 6 5 正式版,  Up: 更新日志

1.18.45 Python 3.6.5 rc1
------------------------

`发布日期: 2018-03-13'

* Menu:

* 安全: 安全<25>.
* 核心与内置: 核心与内置<41>.
* 库: 库<42>.
* 文档: 文档<37>.
* 测试: 测试<31>.
* 构建: 构建<29>.
* Windows: Windows<32>.
* macOS: macOS<24>.
* IDLE: IDLE<37>.
* 工具/示例: 工具/示例<20>.
* C API: C API<24>.


File: python.info,  Node: 安全<25>,  Next: 核心与内置<41>,  Up: Python 3 6 5 rc1

1.18.45.1 安全
..............

   - bpo-33001(1): Minimal fix to prevent buffer overrun in os.symlink
     on Windows

   - bpo-32981(2): Regexes in difflib and poplib were vulnerable to
     catastrophic backtracking.  These regexes formed potential DOS
     vectors (REDOS). They have been refactored.  This resolves
     CVE-2018-1060 and CVE-2018-1061.  Patch by Jamie Davis.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33001

   (2) https://bugs.python.org/issue32981


File: python.info,  Node: 核心与内置<41>,  Next: 库<42>,  Prev: 安全<25>,  Up: Python 3 6 5 rc1

1.18.45.2 核心与内置
....................

   - bpo-33026(1): Fixed jumping out of "with" block by setting
     f_lineno.

   - bpo-17288(2): Prevent jumps from ’return’ and ’exception’ trace
     events.

   - bpo-32889(3): Update Valgrind suppression list to account for the
     rename of ‘Py_ADDRESS_IN_RANG’ to ‘address_in_range’.

   - bpo-32650(4): Pdb and other debuggers dependent on bdb.py will
     correctly step over (next command) native coroutines.  Patch by
     Pablo Galindo.

   - bpo-32685(5): Improve suggestion when the Python 2 form of print
     statement is either present on the same line as the header of a
     compound statement or else terminated by a semi-colon instead of a
     newline.  Patch by Nitish Chandra.

   - bpo-32583(6): Fix possible crashing in builtin Unicode decoders
     caused by write out-of-bound errors when using customized decode
     error handlers.

   - bpo-26163(7): Improved frozenset() hash to create more distinct
     hash values when faced with datasets containing many similar
     values.

   - bpo-27169(8): The ‘__debug__’ constant is now optimized out at
     compile time.  This fixes also bpo-22091(9).

   - bpo-32329(10): ‘sys.flags.hash_randomization’ is now properly set
     to 0 when hash randomization is turned off by ‘PYTHONHASHSEED=0’.

   - bpo-30416(11): The optimizer is now protected from spending much
     time doing complex calculations and consuming much memory for
     creating large constants in constant folding.

   - bpo-18533(12): ‘repr()’ on a dict containing its own ‘values()’ or
     ‘items()’ no longer raises ‘RecursionError’; OrderedDict similarly.
     Instead, use ‘...’, as for other recursive structures.  Patch by
     Ben North.

   - bpo-32028(13): Leading whitespace is now correctly ignored when
     generating suggestions for converting Py2 print statements to Py3
     builtin print function calls.  Patch by Sanyam Khurana.

   - bpo-32137(14): The repr of deeply nested dict now raises a
     RecursionError instead of crashing due to a stack overflow.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33026

   (2) https://bugs.python.org/issue17288

   (3) https://bugs.python.org/issue32889

   (4) https://bugs.python.org/issue32650

   (5) https://bugs.python.org/issue32685

   (6) https://bugs.python.org/issue32583

   (7) https://bugs.python.org/issue26163

   (8) https://bugs.python.org/issue27169

   (9) https://bugs.python.org/issue22091

   (10) https://bugs.python.org/issue32329

   (11) https://bugs.python.org/issue30416

   (12) https://bugs.python.org/issue18533

   (13) https://bugs.python.org/issue32028

   (14) https://bugs.python.org/issue32137


File: python.info,  Node: 库<42>,  Next: 文档<37>,  Prev: 核心与内置<41>,  Up: Python 3 6 5 rc1

1.18.45.3 库
............

   - bpo-33064(1): lib2to3 now properly supports trailing commas after
     ‘*args’ and ‘**kwargs’ in function signatures.

   - bpo-31804(2): Avoid failing in multiprocessing.Process if the
     standard streams are closed or None at exit.

   - bpo-33037(3): Skip sending/receiving data after SSL transport
     closing.

   - bpo-30353(4): Fix ctypes pass-by-value for structs on 64-bit
     Cygwin/MinGW.

   - bpo-33009(5): Fix inspect.signature() for single-parameter
     partialmethods.

   - bpo-32969(6): Expose several missing constants in zlib and fix
     corresponding documentation.

   - bpo-32713(7): Fixed tarfile.itn handling of out-of-bounds float
     values.  Patch by Joffrey Fuhrer.

   - bpo-30622(8): The ssl module now detects missing NPN support in
     LibreSSL.

   - bpo-32922(9): dbm.open() now encodes filename with the filesystem
     encoding rather than default encoding.

   - bpo-32859(10): In ‘os.dup2’, don’t check every call whether the
     ‘dup3’ syscall exists or not.

   - bpo-21060(11): Rewrite confusing message from setup.py upload from
     "No dist file created in earlier command" to the more helpful "Must
     create and upload files in one command".

   - bpo-32857(12): In *note tkinter: 10d, ‘after_cancel(None)’ now
     raises a *note ValueError: 1fc. instead of canceling the first
     scheduled function.  Patch by Cheryl Sabella.

   - bpo-32852(13): Make sure sys.argv remains as a list when running
     trace.

   - bpo-32841(14): Fixed *note asyncio.Condition: 28e. issue which
     silently ignored cancellation after notifying and cancelling a
     conditional lock.  Patch by Bar Harel.

   - bpo-31787(15): Fixed refleaks of ‘__init__()’ methods in various
     modules.  (Contributed by Oren Milman)

   - bpo-30157(16): Fixed guessing quote and delimiter in
     csv.Sniffer.sniff() when only the last field is quoted.  Patch by
     Jake Davis.

   - bpo-32394(17): socket: Remove TCP_FASTOPEN, TCP_KEEPCNT flags on
     older version Windows during run-time.

   - bpo-32777(18): Fix a rare but potential pre-exec child process
     deadlock in subprocess on POSIX systems when marking file
     descriptors inheritable on exec in the child process.  This bug
     appears to have been introduced in 3.4.

   - bpo-32647(19): The ctypes module used to depend on indirect linking
     for dlopen.  The shared extension is now explicitly linked against
     libdl on platforms with dl.

   - bpo-32734(20): Fixed ‘asyncio.Lock()’ safety issue which allowed
     acquiring and locking the same lock multiple times, without it
     being free.  Patch by Bar Harel.

   - bpo-32727(21): Do not include name field in SMTP envelope from
     address.  Patch by Stéphane Wirtel

   - bpo-27931(22): Fix email address header parsing error when the
     username is an empty quoted string.  Patch by Xiang Zhang.

   - bpo-32304(23): distutils’ upload command no longer corrupts tar
     files ending with a CR byte, and no longer tries to convert CR to
     CRLF in any of the upload text fields.

   - bpo-32502(24): uuid.uuid1 no longer raises an exception if a 64-bit
     hardware address is encountered.

   - bpo-31848(25): Fix the error handling in Aifc_read.initfp() when
     the SSND chunk is not found.  Patch by Zackery Spytz.

   - bpo-32555(26): On FreeBSD and Solaris, os.strerror() now always
     decode the byte string from the current locale encoding, rather
     than using ASCII/surrogateescape in some cases.

   - bpo-32521(27): The nis module is now compatible with new libnsl and
     headers location.

   - bpo-32473(28): Improve ABCMeta._dump_registry() output readability

   - bpo-32521(29): glibc has removed Sun RPC. Use replacement libtirpc
     headers and library in nis module.

   - bpo-32228(30): Ensure that ‘truncate()’ preserves the file position
     (as reported by ‘tell()’) after writes longer than the buffer size.

   - bpo-26133(31): Don’t unsubscribe signals in asyncio UNIX event loop
     on interpreter shutdown.

   - bpo-32185(32): The SSL module no longer sends IP addresses in SNI
     TLS extension on platforms with OpenSSL 1.0.2+ or inet_pton.

   - bpo-32323(33): *note urllib.parse.urlsplit(): 602. does not convert
     zone-id (scope) to lower case for scoped IPv6 addresses in
     hostnames now.

   - bpo-32302(34): Fix bdist_wininst of distutils for CRT v142: it
     binary compatible with CRT v140.

   - bpo-32255(35): A single empty field is now always quoted when
     written into a CSV file.  This allows to distinguish an empty row
     from a row consisting of a single empty field.  Patch by Licht
     Takeuchi.

   - bpo-32277(36): Raise ‘NotImplementedError’ instead of ‘SystemError’
     on platforms where ‘chmod(..., follow_symlinks=False)’ is not
     supported.  Patch by Anthony Sottile.

   - bpo-32199(37): The getnode() ip getter now uses ’ip link’ instead
     of ’ip link list’.

   - bpo-27456(38): Ensure TCP_NODELAY is set on Linux.  Tests by Victor
     Stinner.

   - bpo-31900(39): The *note locale.localeconv(): 492. function now
     sets temporarily the ‘LC_CTYPE’ locale to the ‘LC_NUMERIC’ locale
     to decode ‘decimal_point’ and ‘thousands_sep’ byte strings if they
     are non-ASCII or longer than 1 byte, and the ‘LC_NUMERIC’ locale is
     different than the ‘LC_CTYPE’ locale.  This temporary change
     affects other threads.  Same change for the *note str.format():
     4e2. method when formatting a number (*note int: 185, *note float:
     188, *note float: 188. and subclasses) with the ‘n’ type (ex:
     ‘'{:n}'.format(1234)’).

   - bpo-31802(40): Importing native path module (‘posixpath’, ‘ntpath’)
     now works even if the ‘os’ module still is not imported.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33064

   (2) https://bugs.python.org/issue31804

   (3) https://bugs.python.org/issue33037

   (4) https://bugs.python.org/issue30353

   (5) https://bugs.python.org/issue33009

   (6) https://bugs.python.org/issue32969

   (7) https://bugs.python.org/issue32713

   (8) https://bugs.python.org/issue30622

   (9) https://bugs.python.org/issue32922

   (10) https://bugs.python.org/issue32859

   (11) https://bugs.python.org/issue21060

   (12) https://bugs.python.org/issue32857

   (13) https://bugs.python.org/issue32852

   (14) https://bugs.python.org/issue32841

   (15) https://bugs.python.org/issue31787

   (16) https://bugs.python.org/issue30157

   (17) https://bugs.python.org/issue32394

   (18) https://bugs.python.org/issue32777

   (19) https://bugs.python.org/issue32647

   (20) https://bugs.python.org/issue32734

   (21) https://bugs.python.org/issue32727

   (22) https://bugs.python.org/issue27931

   (23) https://bugs.python.org/issue32304

   (24) https://bugs.python.org/issue32502

   (25) https://bugs.python.org/issue31848

   (26) https://bugs.python.org/issue32555

   (27) https://bugs.python.org/issue32521

   (28) https://bugs.python.org/issue32473

   (29) https://bugs.python.org/issue32521

   (30) https://bugs.python.org/issue32228

   (31) https://bugs.python.org/issue26133

   (32) https://bugs.python.org/issue32185

   (33) https://bugs.python.org/issue32323

   (34) https://bugs.python.org/issue32302

   (35) https://bugs.python.org/issue32255

   (36) https://bugs.python.org/issue32277

   (37) https://bugs.python.org/issue32199

   (38) https://bugs.python.org/issue27456

   (39) https://bugs.python.org/issue31900

   (40) https://bugs.python.org/issue31802


File: python.info,  Node: 文档<37>,  Next: 测试<31>,  Prev: 库<42>,  Up: Python 3 6 5 rc1

1.18.45.4 文档
..............

   - bpo-17232(1): Clarify docs for -O and -OO. Patch by Terry Reedy.

   - bpo-32800(2): Update link to w3c doc for xml default namespaces.

   - bpo-8722(3): Document *note __getattr__(): 323. behavior when
     property ‘get()’ method raises *note AttributeError: 3a3.

   - bpo-32614(4): Modify RE examples in documentation to use raw
     strings to prevent *note DeprecationWarning: 279. and add text to
     REGEX HOWTO to highlight the deprecation.

   - bpo-31972(5): Improve docstrings for *note pathlib.PurePath: 1051.
     subclasses.

   - bpo-17799(6): Explain real behaviour of sys.settrace and
     sys.setprofile and their C-API counterparts regarding which type of
     events are received in each function.  Patch by Pablo Galindo
     Salgado.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17232

   (2) https://bugs.python.org/issue32800

   (3) https://bugs.python.org/issue8722

   (4) https://bugs.python.org/issue32614

   (5) https://bugs.python.org/issue31972

   (6) https://bugs.python.org/issue17799


File: python.info,  Node: 测试<31>,  Next: 构建<29>,  Prev: 文档<37>,  Up: Python 3 6 5 rc1

1.18.45.5 测试
..............

   - bpo-32517(1): Fix failing ‘test_asyncio’ on macOS 10.12.2+ due to
     transport of ‘KqueueSelector’ loop was not being closed.

   - bpo-32721(2): Fix test_hashlib to not fail if the _md5 module is
     not built.

   - bpo-32252(3): Fix faulthandler_suppress_crash_report() used to
     prevent core dump files when testing crashes.  getrlimit() returns
     zero on success.

   - bpo-31518(4): Debian Unstable has disabled TLS 1.0 and 1.1 for
     SSLv23_METHOD().  Change TLS/SSL protocol of some tests to
     PROTOCOL_TLS or PROTOCOL_TLSv1_2 to make them pass on Debian.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32517

   (2) https://bugs.python.org/issue32721

   (3) https://bugs.python.org/issue32252

   (4) https://bugs.python.org/issue31518


File: python.info,  Node: 构建<29>,  Next: Windows<32>,  Prev: 测试<31>,  Up: Python 3 6 5 rc1

1.18.45.6 构建
..............

   - bpo-32635(1): Fix segfault of the crypt module when libxcrypt is
     provided instead of libcrypt at the system.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32635


File: python.info,  Node: Windows<32>,  Next: macOS<24>,  Prev: 构建<29>,  Up: Python 3 6 5 rc1

1.18.45.7 Windows
.................

   - bpo-33016(1): Fix potential use of uninitialized memory in
     nt._getfinalpathname

   - bpo-32903(2): Fix a memory leak in os.chdir() on Windows if the
     current directory is set to a UNC path.

   - bpo-31966(3): Fixed WindowsConsoleIO.write() for writing empty
     data.

   - bpo-32409(4): Ensures activate.bat can handle Unicode contents.

   - bpo-32457(5): Improves handling of denormalized executable path
     when launching Python.

   - bpo-32370(6): Use the correct encoding for ipconfig output in the
     uuid module.  Patch by Segev Finer.

   - bpo-29248(7): Fix *note os.readlink(): 1f4. on Windows, which was
     mistakenly treating the ‘PrintNameOffset’ field of the reparse data
     buffer as a number of characters instead of bytes.  Patch by Craig
     Holmquist and SSE4.

   - bpo-32588(8): Create standalone _distutils_findvs module.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33016

   (2) https://bugs.python.org/issue32903

   (3) https://bugs.python.org/issue31966

   (4) https://bugs.python.org/issue32409

   (5) https://bugs.python.org/issue32457

   (6) https://bugs.python.org/issue32370

   (7) https://bugs.python.org/issue29248

   (8) https://bugs.python.org/issue32588


File: python.info,  Node: macOS<24>,  Next: IDLE<37>,  Prev: Windows<32>,  Up: Python 3 6 5 rc1

1.18.45.8 macOS
...............

   - bpo-32726(1): Provide an additional, more modern macOS installer
     variant that supports macOS 10.9+ systems in 64-bit mode only.
     Upgrade the supplied third-party libraries to OpenSSL 1.0.2n, XZ
     5.2.3, and SQLite 3.22.0.  The 10.9+ installer now links with and
     supplies its own copy of Tcl/Tk 8.6.8.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32726


File: python.info,  Node: IDLE<37>,  Next: 工具/示例<20>,  Prev: macOS<24>,  Up: Python 3 6 5 rc1

1.18.45.9 IDLE
..............

   - bpo-32984(1): Set ‘__file__’ while running a startup file.  Like
     Python, IDLE optionally runs one startup file in the Shell window
     before presenting the first interactive input prompt.  For IDLE,
     ‘-s’ runs a file named in environmental variable ‘IDLESTARTUP’ or
     *note PYTHONSTARTUP: 8ed.; ‘-r file’ runs ‘file’.  Python sets
     ‘__file__’ to the startup file name before running the file and
     unsets it before the first prompt.  IDLE now does the same when run
     normally, without the ‘-n’ option.

   - bpo-32940(2): Simplify and rename StringTranslatePseudoMapping in
     pyparse.

   - bpo-32916(3): Change ‘str’ to ‘code’ in pyparse.

   - bpo-32905(4): Remove unused code in pyparse module.

   - bpo-32874(5): Add tests for pyparse.

   - bpo-32837(6): Using the system and place-dependent default encoding
     for open() is a bad idea for IDLE’s system and location-independent
     files.

   - bpo-32826(7): Add "encoding=utf-8" to open() in IDLE’s
     test_help_about.  GUI test test_file_buttons() only looks at
     initial ascii-only lines, but failed on systems where open()
     defaults to ’ascii’ because readline() internally reads and decodes
     far enough ahead to encounter a non-ascii character in CREDITS.txt.

   - bpo-32765(8): Update configdialog General tab docstring to add new
     widgets to the widget list.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32984

   (2) https://bugs.python.org/issue32940

   (3) https://bugs.python.org/issue32916

   (4) https://bugs.python.org/issue32905

   (5) https://bugs.python.org/issue32874

   (6) https://bugs.python.org/issue32837

   (7) https://bugs.python.org/issue32826

   (8) https://bugs.python.org/issue32765


File: python.info,  Node: 工具/示例<20>,  Next: C API<24>,  Prev: IDLE<37>,  Up: Python 3 6 5 rc1

1.18.45.10 工具/示例
....................

   - bpo-24960(1): 2to3 and lib2to3 can now read pickled grammar files
     using pkgutil.get_data() rather than probing the filesystem.  This
     lets 2to3 and lib2to3 work when run from a zipfile.

   - bpo-32222(2): Fix pygettext not extracting docstrings for functions
     with type annotated arguments.  Patch by Toby Harradine.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24960

   (2) https://bugs.python.org/issue32222


File: python.info,  Node: C API<24>,  Prev: 工具/示例<20>,  Up: Python 3 6 5 rc1

1.18.45.11 C API
................

   - bpo-29084(1): Undocumented C API for OrderedDict has been excluded
     from the limited C API. It was added by mistake and actually never
     worked in the limited C API.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29084


File: python.info,  Node: Python 3 6 4 正式版,  Next: Python 3 6 4 rc1,  Prev: Python 3 6 5 rc1,  Up: 更新日志

1.18.46 Python 3.6.4 正式版
---------------------------

`发布日期: 2017-12-18'

从 3.6.4 rc1 到 3.6.4 正式版中没有新的代码更改。


File: python.info,  Node: Python 3 6 4 rc1,  Next: Python 3 6 3 正式版,  Prev: Python 3 6 4 正式版,  Up: 更新日志

1.18.47 Python 3.6.4 rc1
------------------------

`发布日期: 2017-12-05'

* Menu:

* 核心与内置: 核心与内置<42>.
* 库: 库<43>.
* 文档: 文档<38>.
* 测试: 测试<32>.
* 构建: 构建<30>.
* Windows: Windows<33>.
* macOS: macOS<25>.
* IDLE: IDLE<38>.
* 工具/示例: 工具/示例<21>.
* C API: C API<25>.


File: python.info,  Node: 核心与内置<42>,  Next: 库<43>,  Up: Python 3 6 4 rc1

1.18.47.1 核心与内置
....................

   - bpo-32176(1): co_flags.CO_NOFREE is now always set correctly by the
     code object constructor based on freevars and cellvars, rather than
     needing to be set correctly by the caller.  This ensures it will be
     cleared automatically when additional cell references are injected
     into a modified code object and function.

   - bpo-31949(2): Fixed several issues in printing tracebacks
     (PyTraceBack_Print()).  Setting sys.tracebacklimit to 0 or less now
     suppresses printing tracebacks.  Setting sys.tracebacklimit to None
     now causes using the default limit.  Setting sys.tracebacklimit to
     an integer larger than LONG_MAX now means using the limit LONG_MAX
     rather than the default limit.  Fixed integer overflows in the case
     of more than 2**31 traceback items on Windows.  Fixed output errors
     handling.

   - bpo-30696(3): Fix the interactive interpreter looping endlessly
     when no memory.

   - bpo-20047(4): Bytearray methods partition() and rpartition() now
     accept only bytes-like objects as separator, as documented.  In
     particular they now raise TypeError rather of returning a bogus
     result when an integer is passed as a separator.

   - bpo-31852(5): Fix a segmentation fault caused by a combination of
     the async soft keyword and continuation lines.

   - bpo-21720(6): BytesWarning no longer emitted when the `fromlist'
     argument of ‘__import__()’ or the ‘__all__’ attribute of the module
     contain bytes instances.

   - bpo-31825(7): Fixed OverflowError in the ’unicode-escape’ codec and
     in codecs.escape_decode() when decode an escaped non-ascii byte.

   - bpo-28603(8): Print the full context/cause chain of exceptions on
     interpreter exit, even if an exception in the chain is unhashable
     or compares equal to later ones.  Patch by Zane Bitter.

   - bpo-31786(9): Fix timeout rounding in the select module to round
     correctly negative timeouts between -1.0 and 0.0.  The functions
     now block waiting for events as expected.  Previously, the call was
     incorrectly non-blocking.  Patch by Pablo Galindo.

   - bpo-31642(10): Restored blocking "from package import module" by
     setting sys.modules["package.module"] to None.

   - bpo-31626(11): Fixed a bug in debug memory allocator.  There was a
     write to freed memory after shrinking a memory block.

   - bpo-31619(12): Fixed a ValueError when convert a string with large
     number of underscores to integer with binary base.

   - bpo-31592(13): Fixed an assertion failure in Python parser in case
     of a bad *note unicodedata.normalize(): 10bf.  Patch by Oren
     Milman.

   - bpo-31588(14): Raise a *note TypeError: 193. with a helpful error
     message when class creation fails due to a metaclass with a bad
     ‘__prepare__()’ method.  Patch by Oren Milman.

   - bpo-31566(15): Fix an assertion failure in ‘_warnings.warn()’ in
     case of a bad ‘__name__’ global.  Patch by Oren Milman.

   - bpo-31505(16): Fix an assertion failure in *note json: a5, in case
     ‘_json.make_encoder()’ received a bad ‘encoder()’ argument.  Patch
     by Oren Milman.

   - bpo-31492(17): Fix assertion failures in case of failing to import
     from a module with a bad ‘__name__’ attribute, and in case of
     failing to access an attribute of such a module.  Patch by Oren
     Milman.

   - bpo-31490(18): Fix an assertion failure in *note ctypes: 2b. class
     definition, in case the class has an attribute whose name is
     specified in ‘_anonymous_’ but not in ‘_fields_’.  Patch by Oren
     Milman.

   - bpo-31478(19): Fix an assertion failure in ‘_random.Random.seed()’
     in case the argument has a bad ‘__abs__()’ method.  Patch by Oren
     Milman.

   - bpo-31315(20): Fix an assertion failure in imp.create_dynamic(),
     when spec.name is not a string.  Patch by Oren Milman.

   - bpo-31311(21): Fix a crash in the ‘__setstate__()’ method of *note
     ctypes._CData: 10c0, in case of a bad ‘__dict__’.  Patch by Oren
     Milman.

   - bpo-31293(22): Fix crashes in true division and multiplication of a
     timedelta object by a float with a bad as_integer_ratio() method.
     Patch by Oren Milman.

   - bpo-31285(23): Fix an assertion failure in *note
     warnings.warn_explicit: 5b9, when the return value of the received
     loader’s get_source() has a bad splitlines() method.  Patch by Oren
     Milman.

   - bpo-30817(24): ‘PyErr_PrintEx()’ clears now the ignored exception
     that may be raised by ‘_PySys_SetObjectId()’, for example when no
     memory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32176

   (2) https://bugs.python.org/issue31949

   (3) https://bugs.python.org/issue30696

   (4) https://bugs.python.org/issue20047

   (5) https://bugs.python.org/issue31852

   (6) https://bugs.python.org/issue21720

   (7) https://bugs.python.org/issue31825

   (8) https://bugs.python.org/issue28603

   (9) https://bugs.python.org/issue31786

   (10) https://bugs.python.org/issue31642

   (11) https://bugs.python.org/issue31626

   (12) https://bugs.python.org/issue31619

   (13) https://bugs.python.org/issue31592

   (14) https://bugs.python.org/issue31588

   (15) https://bugs.python.org/issue31566

   (16) https://bugs.python.org/issue31505

   (17) https://bugs.python.org/issue31492

   (18) https://bugs.python.org/issue31490

   (19) https://bugs.python.org/issue31478

   (20) https://bugs.python.org/issue31315

   (21) https://bugs.python.org/issue31311

   (22) https://bugs.python.org/issue31293

   (23) https://bugs.python.org/issue31285

   (24) https://bugs.python.org/issue30817


File: python.info,  Node: 库<43>,  Next: 文档<38>,  Prev: 核心与内置<42>,  Up: Python 3 6 4 rc1

1.18.47.2 库
............

   - bpo-28556(1): Two minor fixes for ‘typing’ module: allow shallow
     copying instances of generic classes, improve interaction of
     ‘__init_subclass__’ with generics.  Original PRs by Ivan
     Levkivskyi.

   - bpo-27240(2): The header folding algorithm for the new email
     policies has been rewritten, which also fixes bpo-30788(3),
     bpo-31831(4), and bpo-32182(5).  In particular, RFC2231 folding is
     now done correctly.

   - bpo-32186(6): io.FileIO.readall() and io.FileIO.read() now release
     the GIL when getting the file size.  Fixed hang of all threads with
     inaccessible NFS server.  Patch by Nir Soffer.

   - bpo-12239(7): Make *note msilib.SummaryInformation.GetProperty():
     fd3. return ‘None’ when the value of property is ‘VT_EMPTY’.
     Initial patch by Mark Mc Mahon.

   - bpo-31325(8): Fix wrong usage of *note collections.namedtuple():
     1b7. in the *note RobotFileParser.parse(): 10b1. method.  Initial
     patch by Robin Wellner.

   - bpo-12382(9): *note msilib.OpenDatabase(): f1f. now raises a better
     exception message when it couldn’t open or create an MSI file.
     Initial patch by William Tisäter.

   - bpo-32110(10): ‘codecs.StreamReader.read(n)’ now returns not more
     than `n' characters/bytes for non-negative `n'.  This makes it
     compatible with ‘read()’ methods of other file-like objects.

   - bpo-32072(11): Fixed issues with binary plists: Fixed saving
     bytearrays.  Identical objects will be saved only once.  Equal
     references will be load as identical objects.  Added support for
     saving and loading recursive data structures.

   - bpo-32034(12): Make asyncio.IncompleteReadError and
     LimitOverrunError pickleable.

   - bpo-32015(13): Fixed the looping of asyncio in the case of
     reconnection the socket during waiting async read/write from/to the
     socket.

   - bpo-32011(14): Restored support of loading marshal files with the
     TYPE_INT64 code.  These files can be produced in Python 2.7.

   - bpo-31970(15): Reduce performance overhead of asyncio debug mode.

   - bpo-9678(16): Fixed determining the MAC address in the uuid module:
     Using ifconfig on NetBSD and OpenBSD. Using arp on Linux, FreeBSD,
     NetBSD and OpenBSD. Based on patch by Takayuki Shimizukawa.

   - bpo-30057(17): Fix potential missed signal in signal.signal().

   - bpo-31933(18): Fix Blake2 params leaf_size and node_offset on big
     endian platforms.  Patch by Jack O’Connor.

   - bpo-31927(19): Fixed compilation of the socket module on NetBSD 8.
     Fixed assertion failure or reading arbitrary data when parse a
     AF_BLUETOOTH address on NetBSD and DragonFly BSD.

   - bpo-27666(20): Fixed stack corruption in curses.box() and
     curses.ungetmouse() when the size of types chtype or mmask_t is
     less than the size of C long.  curses.box() now accepts characters
     as arguments.  Based on patch by Steve Fink.

   - bpo-31897(21): plistlib now catches more errors when read binary
     plists and raises InvalidFileException instead of unexpected
     exceptions.

   - bpo-25720(22): Fix the method for checking pad state of curses
     WINDOW. Patch by Masayuki Yamamoto.

   - bpo-31893(23): Fixed the layout of the kqueue_event structure on
     OpenBSD and NetBSD. Fixed the comparison of the kqueue_event
     objects.

   - bpo-31891(24): Fixed building the curses module on NetBSD.

   - bpo-28416(25): Instances of pickle.Pickler subclass with the
     persistent_id() method and pickle.Unpickler subclass with the
     persistent_load() method no longer create reference cycles.

   - bpo-28326(26): Fix multiprocessing.Process when stdout and/or
     stderr is closed or None.

   - bpo-31457(27): If nested log adapters are used, the inner
     ‘process()’ methods are no longer omitted.

   - bpo-31457(28): The ‘manager’ property on LoggerAdapter objects is
     now properly settable.

   - bpo-31806(29): Fix timeout rounding in time.sleep(),
     threading.Lock.acquire() and socket.socket.settimeout() to round
     correctly negative timeouts between -1.0 and 0.0.  The functions
     now block waiting for events as expected.  Previously, the call was
     incorrectly non-blocking.  Patch by Pablo Galindo.

   - bpo-28603(30): traceback: Fix a TypeError that occurred during
     printing of exception tracebacks when either the current exception
     or an exception in its context/cause chain is unhashable.  Patch by
     Zane Bitter.

   - bpo-30058(31): Fixed buffer overflow in select.kqueue.control().

   - bpo-31770(32): Prevent a crash when calling the ‘__init__()’ method
     of a ‘sqlite3.Cursor’ object more than once.  Patch by Oren Milman.

   - bpo-31672(33): ‘idpattern’ in ‘string.Template’ matched some
     non-ASCII characters.  Now it uses ‘-i’ regular expression local
     flag to avoid non-ASCII characters.

   - bpo-31764(34): Prevent a crash in ‘sqlite3.Cursor.close()’ in case
     the ‘Cursor’ object is uninitialized.  Patch by Oren Milman.

   - bpo-31752(35): Fix possible crash in timedelta constructor called
     with custom integers.

   - bpo-31701(36): On Windows, faulthandler.enable() now ignores MSC
     and COM exceptions.

   - bpo-31728(37): Prevent crashes in ‘_elementtree’ due to unsafe
     cleanup of ‘Element.text’ and ‘Element.tail’.  Patch by Oren
     Milman.

   - bpo-31620(38): an empty asyncio.Queue now doesn’t leak memory when
     queue.get pollers timeout

   - bpo-31632(39): Fix method set_protocol() of class
     _SSLProtocolTransport in asyncio module.  This method was
     previously modifying a wrong reference to the protocol.

   - bpo-31675(40): Fixed memory leaks in Tkinter’s methods splitlist()
     and split() when pass a string larger than 2 GiB.

   - bpo-31673(41): Fixed typo in the name of Tkinter’s method
     adderrorinfo().

   - bpo-30806(42): Fix the string representation of a netrc object.

   - bpo-15037(43): Added a workaround for getkey() in curses for
     ncurses 5.7 and earlier.

   - bpo-25351(44): Avoid venv activate failures with undefined
     variables

   - bpo-25532(45): inspect.unwrap() will now only try to unwrap an
     object sys.getrecursionlimit() times, to protect against objects
     which create a new object on every attribute access.

   - bpo-30347(46): Stop crashes when concurrently iterate over
     itertools.groupby() iterators.

   - bpo-31516(47): ‘threading.current_thread()’ should not return a
     dummy thread at shutdown.

   - bpo-31351(48): python -m ensurepip now exits with non-zero exit
     code if pip bootstrapping has failed.

   - bpo-31482(49): ‘random.seed()’ now works with bytes in version=1

   - bpo-31334(50): Fix ‘poll.poll([timeout])’ in the ‘select’ module
     for arbitrary negative timeouts on all OSes where it can only be a
     non-negative integer or -1.  Patch by Riccardo Coccioli.

   - bpo-31310(51): multiprocessing’s semaphore tracker should be
     launched again if crashed.

   - bpo-31308(52): Make multiprocessing’s forkserver process immune to
     Ctrl-C and other user interruptions.  If it crashes, restart it
     when necessary.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28556

   (2) https://bugs.python.org/issue27240

   (3) https://bugs.python.org/issue30788

   (4) https://bugs.python.org/issue31831

   (5) https://bugs.python.org/issue32182

   (6) https://bugs.python.org/issue32186

   (7) https://bugs.python.org/issue12239

   (8) https://bugs.python.org/issue31325

   (9) https://bugs.python.org/issue12382

   (10) https://bugs.python.org/issue32110

   (11) https://bugs.python.org/issue32072

   (12) https://bugs.python.org/issue32034

   (13) https://bugs.python.org/issue32015

   (14) https://bugs.python.org/issue32011

   (15) https://bugs.python.org/issue31970

   (16) https://bugs.python.org/issue9678

   (17) https://bugs.python.org/issue30057

   (18) https://bugs.python.org/issue31933

   (19) https://bugs.python.org/issue31927

   (20) https://bugs.python.org/issue27666

   (21) https://bugs.python.org/issue31897

   (22) https://bugs.python.org/issue25720

   (23) https://bugs.python.org/issue31893

   (24) https://bugs.python.org/issue31891

   (25) https://bugs.python.org/issue28416

   (26) https://bugs.python.org/issue28326

   (27) https://bugs.python.org/issue31457

   (28) https://bugs.python.org/issue31457

   (29) https://bugs.python.org/issue31806

   (30) https://bugs.python.org/issue28603

   (31) https://bugs.python.org/issue30058

   (32) https://bugs.python.org/issue31770

   (33) https://bugs.python.org/issue31672

   (34) https://bugs.python.org/issue31764

   (35) https://bugs.python.org/issue31752

   (36) https://bugs.python.org/issue31701

   (37) https://bugs.python.org/issue31728

   (38) https://bugs.python.org/issue31620

   (39) https://bugs.python.org/issue31632

   (40) https://bugs.python.org/issue31675

   (41) https://bugs.python.org/issue31673

   (42) https://bugs.python.org/issue30806

   (43) https://bugs.python.org/issue15037

   (44) https://bugs.python.org/issue25351

   (45) https://bugs.python.org/issue25532

   (46) https://bugs.python.org/issue30347

   (47) https://bugs.python.org/issue31516

   (48) https://bugs.python.org/issue31351

   (49) https://bugs.python.org/issue31482

   (50) https://bugs.python.org/issue31334

   (51) https://bugs.python.org/issue31310

   (52) https://bugs.python.org/issue31308


File: python.info,  Node: 文档<38>,  Next: 测试<32>,  Prev: 库<43>,  Up: Python 3 6 4 rc1

1.18.47.3 文档
..............

   - bpo-32105(1): Added asyncio.BaseEventLoop.connect_accepted_socket
     versionadded marker.

   - bpo-31537(2): Fix incorrect usage of ‘get_history_length’ in
     readline documentation example code.  Patch by Brad Smith.

   - bpo-30085(3): The operator functions without double underscores are
     preferred for clarity.  The one with underscores are only kept for
     back-compatibility.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32105

   (2) https://bugs.python.org/issue31537

   (3) https://bugs.python.org/issue30085


File: python.info,  Node: 测试<32>,  Next: 构建<30>,  Prev: 文档<38>,  Up: Python 3 6 4 rc1

1.18.47.4 测试
..............

   - bpo-31380(1): Skip test_httpservers test_undecodable_file on macOS:
     fails on APFS.

   - bpo-31705(2): Skip test_socket.test_sha256() on Linux kernel older
     than 4.5.  The test fails with ENOKEY on kernel 3.10 (on ppc64le).
     A fix was merged into the kernel 4.5.

   - bpo-31174(3): Fix test_tools.test_unparse: DirectoryTestCase now
     stores the names sample to always test the same files.  It prevents
     false alarms when hunting reference leaks.

   - bpo-30695(4): Add the ‘set_nomemory(start, stop)’ and
     ‘remove_mem_hooks()’ functions to the _testcapi module.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31380

   (2) https://bugs.python.org/issue31705

   (3) https://bugs.python.org/issue31174

   (4) https://bugs.python.org/issue30695


File: python.info,  Node: 构建<30>,  Next: Windows<33>,  Prev: 测试<32>,  Up: Python 3 6 4 rc1

1.18.47.5 构建
..............

   - bpo-32059(1): ‘detect_modules()’ in ‘setup.py’ now also searches
     the sysroot paths when cross-compiling.

   - bpo-31957(2): Fixes Windows SDK version detection when building for
     Windows.

   - bpo-31609(3): Fixes quotes in PCbuild/clean.bat

   - bpo-31934(4): Abort the build when building out of a not clean
     source tree.

   - bpo-31926(5): Fixed Argument Clinic sometimes causing compilation
     errors when there was more than one function and/or method in a .c
     file with the same name.

   - bpo-28791(6): 更新 Windows 构建以使用 SQLite 3.21.0.

   - bpo-28791(7): 更新 OS X 安装程序以使用 SQLite 3.21.0.

   - bpo-22140(8): Prevent double substitution of prefix in
     python-config.sh.

   - bpo-31536(9): Avoid wholesale rebuild after ‘make regen-all’ if
     nothing changed.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32059

   (2) https://bugs.python.org/issue31957

   (3) https://bugs.python.org/issue31609

   (4) https://bugs.python.org/issue31934

   (5) https://bugs.python.org/issue31926

   (6) https://bugs.python.org/issue28791

   (7) https://bugs.python.org/issue28791

   (8) https://bugs.python.org/issue22140

   (9) https://bugs.python.org/issue31536


File: python.info,  Node: Windows<33>,  Next: macOS<25>,  Prev: 构建<30>,  Up: Python 3 6 4 rc1

1.18.47.6 Windows
.................

   - bpo-1102(1): Return ‘None’ when ‘View.Fetch()’ returns
     ‘ERROR_NO_MORE_ITEMS’ instead of raising ‘MSIError’.  Initial patch
     by Anthony Tuininga.

   - bpo-31944(2): Fixes Modify button in Apps and Features dialog.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1102

   (2) https://bugs.python.org/issue31944


File: python.info,  Node: macOS<25>,  Next: IDLE<38>,  Prev: Windows<33>,  Up: Python 3 6 4 rc1

1.18.47.7 macOS
...............

   - bpo-31392(1): 更新 macOS 安装程序以使用OpenSSL 1.0.2m

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31392


File: python.info,  Node: IDLE<38>,  Next: 工具/示例<21>,  Prev: macOS<25>,  Up: Python 3 6 4 rc1

1.18.47.8 IDLE
..............

   - bpo-32207(1): Improve tk event exception tracebacks in IDLE. When
     tk event handling is driven by IDLE’s run loop, a confusing and
     distracting queue.EMPTY traceback context is no longer added to tk
     event exception tracebacks.  The traceback is now the same as when
     event handling is driven by user code.  Patch based on a suggestion
     by Serhiy Storchaka.

   - bpo-32164(2): Delete unused file idlelib/tabbedpages.py.  Use of
     TabbedPageSet in configdialog was replaced by ttk.Notebook.

   - bpo-32100(3): IDLE: Fix old and new bugs in pathbrowser; improve
     tests.  Patch mostly by Cheryl Sabella.

   - bpo-31858(4): IDLE – Restrict shell prompt manipulation to the
     shell.  Editor and output windows only see an empty last prompt
     line.  This simplifies the code and fixes a minor bug when newline
     is inserted.  Sys.ps1, if present, is read on Shell start-up, but
     is not set or changed.

   - bpo-31860(5): The font sample in the IDLE configuration dialog is
     now editable.  Changes persist while IDLE remains open

   - bpo-31836(6): Test_code_module now passes if run after test_idle,
     which sets ps1.  The code module uses sys.ps1 if present or sets it
     to ’>>> ’ if not.  Test_code_module now properly tests both
     behaviors.  Ditto for ps2.

   - bpo-28603(7): Fix a TypeError that caused a shell restart when
     printing a traceback that includes an exception that is unhashable.
     Patch by Zane Bitter.

   - bpo-13802(8): Use non-Latin characters in the IDLE’s Font settings
     sample.  Even if one selects a font that defines a limited subset
     of the unicode Basic Multilingual Plane, tcl/tk will use other
     fonts that define a character.  The expanded example give users of
     non-Latin characters a better idea of what they might see in IDLE’s
     shell and editors.  To make room for the expanded sample, frames on
     the Font tab are re-arranged.  The Font/Tabs help explains a bit
     about the additions.

   - bpo-31460(9): Simplify the API of IDLE’s Module Browser.  Passing a
     widget instead of an flist with a root widget opens the option of
     creating a browser frame that is only part of a window.  Passing a
     full file name instead of pieces assumed to come from a .py file
     opens the possibility of browsing python files that do not end in
     .py.

   - bpo-31649(10): IDLE - Make _htest, _utest parameters keyword only.

   - bpo-31559(11): Remove test order dependence in
     idle_test.test_browser.

   - bpo-31459(12): Rename IDLE’s module browser from Class Browser to
     Module Browser.  The original module-level class and method browser
     became a module browser, with the addition of module-level
     functions, years ago.  Nested classes and functions were added
     yesterday.  For back-compatibility, the virtual event
     <<open-class-browser>>, which appears on the Keys tab of the
     Settings dialog, is not changed.  Patch by Cheryl Sabella.

   - bpo-31500(13): Default fonts now are scaled on HiDPI displays.

   - bpo-1612262(14): IDLE module browser now shows nested classes and
     functions.  Original patches for code and tests by Guilherme Polo
     and Cheryl Sabella, respectively.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32207

   (2) https://bugs.python.org/issue32164

   (3) https://bugs.python.org/issue32100

   (4) https://bugs.python.org/issue31858

   (5) https://bugs.python.org/issue31860

   (6) https://bugs.python.org/issue31836

   (7) https://bugs.python.org/issue28603

   (8) https://bugs.python.org/issue13802

   (9) https://bugs.python.org/issue31460

   (10) https://bugs.python.org/issue31649

   (11) https://bugs.python.org/issue31559

   (12) https://bugs.python.org/issue31459

   (13) https://bugs.python.org/issue31500

   (14) https://bugs.python.org/issue1612262


File: python.info,  Node: 工具/示例<21>,  Next: C API<25>,  Prev: IDLE<38>,  Up: Python 3 6 4 rc1

1.18.47.9 工具/示例
...................

   - bpo-30722(1): Make redemo work with Python 3.6 and newer versions.
     Also, remove the ‘LOCALE’ option since it doesn’t work with string
     patterns in Python 3.  Patch by Christoph Sarnowski.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30722


File: python.info,  Node: C API<25>,  Prev: 工具/示例<21>,  Up: Python 3 6 4 rc1

1.18.47.10 C API
................

   - bpo-20891(1): Fix PyGILState_Ensure().  When PyGILState_Ensure() is
     called in a non-Python thread before PyEval_InitThreads(), only
     call PyEval_InitThreads() after calling PyThreadState_New() to fix
     a crash.

   - bpo-31532(2): Fix memory corruption due to allocator mix in
     getpath.c between Py_GetPath() and Py_SetPath()

   - bpo-30697(3): The ‘PyExc_RecursionErrorInst’ singleton is removed
     and ‘PyErr_NormalizeException()’ does not use it anymore.  This
     singleton is persistent and its members being never cleared may
     cause a segfault during finalization of the interpreter.  See also
     bpo-22898(4).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20891

   (2) https://bugs.python.org/issue31532

   (3) https://bugs.python.org/issue30697

   (4) https://bugs.python.org/issue22898


File: python.info,  Node: Python 3 6 3 正式版,  Next: Python 3 6 3 rc1,  Prev: Python 3 6 4 rc1,  Up: 更新日志

1.18.48 Python 3.6.3 正式版
---------------------------

`发布日期: 2017-10-03'

* Menu:

* 库: 库<44>.
* 构建: 构建<31>.


File: python.info,  Node: 库<44>,  Next: 构建<31>,  Up: Python 3 6 3 正式版

1.18.48.1 库
............

   - bpo-31641(1): Re-allow arbitrary iterables in *note
     concurrent.futures.as_completed(): 10fe.  Fixes regression in
     3.6.3rc1.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31641


File: python.info,  Node: 构建<31>,  Prev: 库<44>,  Up: Python 3 6 3 正式版

1.18.48.2 构建
..............

   - bpo-31662(1): Fix typos in Windows ‘uploadrelease.bat’ script.  Fix
     Windows Doc build issues in ‘Doc/make.bat’.

   - bpo-31423(2): Fix building the PDF documentation with newer
     versions of Sphinx.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31662

   (2) https://bugs.python.org/issue31423


File: python.info,  Node: Python 3 6 3 rc1,  Next: Python 3 6 2 正式版,  Prev: Python 3 6 3 正式版,  Up: 更新日志

1.18.49 Python 3.6.3 rc1
------------------------

`发布日期: 2017-09-18'

* Menu:

* 安全: 安全<26>.
* 核心与内置: 核心与内置<43>.
* 库: 库<45>.
* 文档: 文档<39>.
* 测试: 测试<33>.
* 构建: 构建<32>.
* Windows: Windows<34>.
* IDLE: IDLE<39>.
* 工具/示例: 工具/示例<22>.


File: python.info,  Node: 安全<26>,  Next: 核心与内置<43>,  Up: Python 3 6 3 rc1

1.18.49.1 安全
..............

   - bpo-29781(1): SSLObject.version() now correctly returns None when
     handshake over BIO has not been performed yet.

   - bpo-30947(2): Upgrade libexpat embedded copy from version 2.2.1 to
     2.2.3 to get security fixes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29781

   (2) https://bugs.python.org/issue30947


File: python.info,  Node: 核心与内置<43>,  Next: 库<45>,  Prev: 安全<26>,  Up: Python 3 6 3 rc1

1.18.49.2 核心与内置
....................

   - bpo-31471(1): Fix an assertion failure in *note subprocess.Popen():
     2ba. on Windows, in case the env argument has a bad keys() method.
     Patch by Oren Milman.

   - bpo-31418(2): Fix an assertion failure in ‘PyErr_WriteUnraisable()’
     in case of an exception with a bad ‘__module__’ attribute.  Patch
     by Oren Milman.

   - bpo-31416(3): Fix assertion failures in case of a bad
     warnings.filters or warnings.defaultaction.  Patch by Oren Milman.

   - bpo-31411(4): Raise a TypeError instead of SystemError in case
     warnings.onceregistry is not a dictionary.  Patch by Oren Milman.

   - bpo-31373(5): Fix several possible instances of undefined behavior
     due to floating-point demotions.

   - bpo-30465(6): Location information (‘lineno’ and ‘col_offset’) in
     f-strings is now (mostly) correct.  This fixes tools like flake8
     from showing warnings on the wrong line (typically the first line
     of the file).

   - bpo-31343(7): Include sys/sysmacros.h for major(), minor(), and
     makedev().  GNU C libray plans to remove the functions from
     sys/types.h.

   - bpo-31291(8): Fix an assertion failure in *note
     zipimport.zipimporter.get_data: 10ca. on Windows, when the return
     value of ‘pathname.replace('/','\\')’ isn’t a string.  Patch by
     Oren Milman.

   - bpo-31271(9): Fix an assertion failure in the write() method of
     *note io.TextIOWrapper: 5fc, when the encoder doesn’t return a
     bytes object.  Patch by Oren Milman.

   - bpo-31243(10): Fix a crash in some methods of *note
     io.TextIOWrapper: 5fc, when the decoder’s state is invalid.  Patch
     by Oren Milman.

   - bpo-30721(11): ‘print’ now shows correct usage hint for using
     Python 2 redirection syntax.  Patch by Sanyam Khurana.

   - bpo-31070(12): Fix a race condition in importlib
     _get_module_lock().

   - bpo-31095(13): Fix potential crash during GC caused by ‘tp_dealloc’
     which doesn’t call ‘PyObject_GC_UnTrack()’.

   - bpo-31071(14): Avoid masking original TypeError in call with *
     unpacking when other arguments are passed.

   - bpo-30978(15): str.format_map() now passes key lookup exceptions
     through.  Previously any exception was replaced with a KeyError
     exception.

   - bpo-30808(16): Use _Py_atomic API for concurrency-sensitive signal
     state.

   - bpo-30876(17): Relative import from unloaded package now reimports
     the package instead of failing with SystemError.  Relative import
     from non-package now fails with ImportError rather than
     SystemError.

   - bpo-30703(18): Improve signal delivery.  Avoid using
     Py_AddPendingCall from signal handler, to avoid calling
     signal-unsafe functions.  The tests I’m adding here fail without
     the rest of the patch, on Linux and OS X. This means our signal
     delivery logic had defects (some signals could be lost).

   - bpo-30765(19): Avoid blocking in pthread_mutex_lock() when
     PyThread_acquire_lock() is asked not to block.

   - bpo-31161(20): Make sure the ’Missing parentheses’ syntax error
     message is only applied to SyntaxError, not to subclasses.  Patch
     by Martijn Pieters.

   - bpo-30814(21): Fixed a race condition when import a submodule from
     a package.

   - bpo-30597(22): ‘print’ now shows expected input in custom error
     message when used as a Python 2 statement.  Patch by Sanyam
     Khurana.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31471

   (2) https://bugs.python.org/issue31418

   (3) https://bugs.python.org/issue31416

   (4) https://bugs.python.org/issue31411

   (5) https://bugs.python.org/issue31373

   (6) https://bugs.python.org/issue30465

   (7) https://bugs.python.org/issue31343

   (8) https://bugs.python.org/issue31291

   (9) https://bugs.python.org/issue31271

   (10) https://bugs.python.org/issue31243

   (11) https://bugs.python.org/issue30721

   (12) https://bugs.python.org/issue31070

   (13) https://bugs.python.org/issue31095

   (14) https://bugs.python.org/issue31071

   (15) https://bugs.python.org/issue30978

   (16) https://bugs.python.org/issue30808

   (17) https://bugs.python.org/issue30876

   (18) https://bugs.python.org/issue30703

   (19) https://bugs.python.org/issue30765

   (20) https://bugs.python.org/issue31161

   (21) https://bugs.python.org/issue30814

   (22) https://bugs.python.org/issue30597


File: python.info,  Node: 库<45>,  Next: 文档<39>,  Prev: 核心与内置<43>,  Up: Python 3 6 3 rc1

1.18.49.3 库
............

   - bpo-31499(1): xml.etree: Fix a crash when a parser is part of a
     reference cycle.

   - bpo-28556(2): typing.get_type_hints now finds the right globalns
     for classes and modules by default (when no ‘globalns’ was
     specified by the caller).

   - bpo-28556(3): Speed improvements to the ‘typing’ module.  Original
     PRs by Ivan Levkivskyi and Mitar.

   - bpo-31544(4): The C accelerator module of ElementTree ignored
     exceptions raised when looking up TreeBuilder target methods in
     XMLParser().

   - bpo-31234(5): socket.create_connection() now fixes manually a
     reference cycle: clear the variable storing the last exception on
     success.

   - bpo-31457(6): LoggerAdapter objects can now be nested.

   - bpo-31400(7): Improves SSL error handling to avoid losing error
     numbers.

   - bpo-28958(8): ssl.SSLContext() now uses OpenSSL error information
     when a context cannot be instantiated.

   - bpo-27340(9): SSLSocket.sendall() now uses memoryview to create
     slices of data.  This fixes support for all bytes-like object.  It
     is also more efficient and avoids costly copies.

   - bpo-31178(10): Fix string concatenation bug in rare error path in
     the subprocess module

   - bpo-31350(11): Micro-optimize ‘asyncio._get_running_loop()’ to
     become up to 10% faster.

   - bpo-31170(12): expat: Update libexpat from 2.2.3 to 2.2.4.  Fix
     copying of partial characters for UTF-8 input (libexpat bug 115):
     ‘https://github.com/libexpat/libexpat/issues/115’

   - bpo-29136(13): Add TLS 1.3 cipher suites and OP_NO_TLSv1_3.

   - bpo-29212(14): Fix concurrent.futures.thread.ThreadPoolExecutor
     threads to have a non repr() based thread name by default when no
     thread_name_prefix is supplied.  They will now identify themselves
     as "ThreadPoolExecutor-y_n".

   - bpo-9146(15): Fix a segmentation fault in _hashopenssl when
     standard hash functions such as md5 are not available in the linked
     OpenSSL library.  As in some special FIPS-140 build environments.

   - bpo-27144(16): The ‘map()’ and ‘as_completed()’ iterators in
     ‘concurrent.futures’ now avoid keeping a reference to yielded
     objects.

   - bpo-10746(17): Fix ctypes producing wrong PEP 3118(18) type codes
     for integer types.

   - bpo-22536(19): The subprocess module now sets the filename when
     FileNotFoundError is raised on POSIX systems due to the executable
     or cwd not being found.

   - bpo-31249(20): concurrent.futures: WorkItem.run() used by
     ThreadPoolExecutor now breaks a reference cycle between an
     exception object and the WorkItem object.

   - bpo-31247(21): xmlrpc.server now explicitly breaks reference cycles
     when using sys.exc_info() in code handling exceptions.

   - bpo-30102(22): The ssl and hashlib modules now call
     OPENSSL_add_all_algorithms_noconf() on OpenSSL < 1.1.0.  The
     function detects CPU features and enables optimizations on some CPU
     architectures such as POWER8.  Patch is based on research from
     Gustavo Serra Scalet.

   - bpo-31185(23): Fixed miscellaneous errors in asyncio speedup
     module.

   - bpo-31135(24): ttk: fix the destroy() method of LabeledScale and
     OptionMenu classes.  Call the parent destroy() method even if the
     used attribute doesn’t exist.  The LabeledScale.destroy() method
     now also explicitly clears label and scale attributes to help the
     garbage collector to destroy all widgets.

   - bpo-31107(25): Fix ‘copyreg._slotnames()’ mangled attribute
     calculation for classes whose name begins with an underscore.
     Patch by Shane Harvey.

   - bpo-31061(26): Fixed a crash when using asyncio and threads.

   - bpo-30502(27): Fix handling of long oids in ssl.  Based on patch by
     Christian Heimes.

   - bpo-30119(28): ftplib.FTP.putline() now throws ValueError on
     commands that contains CR or LF. Patch by Dong-hee Na.

   - bpo-30595(29): multiprocessing.Queue.get() with a timeout now polls
     its reader in non-blocking mode if it succeeded to acquire the lock
     but the acquire took longer than the timeout.

   - bpo-29403(30): Fix ‘unittest.mock’’s autospec to not fail on
     method-bound builtin functions.  Patch by Aaron Gallagher.

   - bpo-30961(31): Fix decrementing a borrowed reference in
     tracemalloc.

   - bpo-25684(32): Change ‘ttk.OptionMenu’ radiobuttons to be unique
     across instances of ‘OptionMenu’.

   - bpo-30886(33): Fix multiprocessing.Queue.join_thread(): it now
     waits until the thread completes, even if the thread was started by
     the same process which created the queue.

   - bpo-29854(34): Fix segfault in readline when using readline’s
     history-size option.  Patch by Nir Soffer.

   - bpo-30319(35): socket.close() now ignores ECONNRESET error.

   - bpo-30828(36): Fix out of bounds write in
     ‘asyncio.CFuture.remove_done_callback()’.

   - bpo-30807(37): signal.setitimer() may disable the timer when passed
     a tiny value.  Tiny values (such as 1e-6) are valid non-zero values
     for setitimer(), which is specified as taking
     microsecond-resolution intervals.  However, on some platform, our
     conversion routine could convert 1e-6 into a zero interval,
     therefore disabling the timer instead of (re-)scheduling it.

   - bpo-30441(38): Fix bug when modifying os.environ while iterating
     over it

   - bpo-30532(39): Fix email header value parser dropping folding white
     space in certain cases.

   - bpo-30879(40): os.listdir() and os.scandir() now emit bytes names
     when called with bytes-like argument.

   - bpo-30746(41): Prohibited the ’=’ character in environment variable
     names in ‘os.putenv()’ and ‘os.spawn*()’.

   - bpo-29755(42): Fixed the lgettext() family of functions in the
     gettext module.  They now always return bytes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31499

   (2) https://bugs.python.org/issue28556

   (3) https://bugs.python.org/issue28556

   (4) https://bugs.python.org/issue31544

   (5) https://bugs.python.org/issue31234

   (6) https://bugs.python.org/issue31457

   (7) https://bugs.python.org/issue31400

   (8) https://bugs.python.org/issue28958

   (9) https://bugs.python.org/issue27340

   (10) https://bugs.python.org/issue31178

   (11) https://bugs.python.org/issue31350

   (12) https://bugs.python.org/issue31170

   (13) https://bugs.python.org/issue29136

   (14) https://bugs.python.org/issue29212

   (15) https://bugs.python.org/issue9146

   (16) https://bugs.python.org/issue27144

   (17) https://bugs.python.org/issue10746

   (18) https://www.python.org/dev/peps/pep-3118

   (19) https://bugs.python.org/issue22536

   (20) https://bugs.python.org/issue31249

   (21) https://bugs.python.org/issue31247

   (22) https://bugs.python.org/issue30102

   (23) https://bugs.python.org/issue31185

   (24) https://bugs.python.org/issue31135

   (25) https://bugs.python.org/issue31107

   (26) https://bugs.python.org/issue31061

   (27) https://bugs.python.org/issue30502

   (28) https://bugs.python.org/issue30119

   (29) https://bugs.python.org/issue30595

   (30) https://bugs.python.org/issue29403

   (31) https://bugs.python.org/issue30961

   (32) https://bugs.python.org/issue25684

   (33) https://bugs.python.org/issue30886

   (34) https://bugs.python.org/issue29854

   (35) https://bugs.python.org/issue30319

   (36) https://bugs.python.org/issue30828

   (37) https://bugs.python.org/issue30807

   (38) https://bugs.python.org/issue30441

   (39) https://bugs.python.org/issue30532

   (40) https://bugs.python.org/issue30879

   (41) https://bugs.python.org/issue30746

   (42) https://bugs.python.org/issue29755


File: python.info,  Node: 文档<39>,  Next: 测试<33>,  Prev: 库<45>,  Up: Python 3 6 3 rc1

1.18.49.4 文档
..............

   - bpo-31294(1): Fix incomplete code snippet in the
     ZeroMQSocketListener and ZeroMQSocketHandler examples and adapt
     them to Python 3.

   - bpo-21649(2): Add RFC 7525 and Mozilla server side TLS links to SSL
     documentation.

   - bpo-30803(3): Clarify doc on truth value testing.  Original patch
     by Peter Thomassen.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31294

   (2) https://bugs.python.org/issue21649

   (3) https://bugs.python.org/issue30803


File: python.info,  Node: 测试<33>,  Next: 构建<32>,  Prev: 文档<39>,  Up: Python 3 6 3 rc1

1.18.49.5 测试
..............

   - bpo-31320(1): Silence traceback in test_ssl

   - bpo-25674(2): Remove sha256.tbs-internet.com ssl test

   - bpo-30715(3): Address ALPN callback changes for OpenSSL 1.1.0f.
     The latest version behaves like OpenSSL 1.0.2 and no longer aborts
     handshake.

   - bpo-30822(4): regrtest: Exclude tzdata from regrtest –all.  When
     running the test suite using –use=all / -u all, exclude tzdata
     since it makes test_datetime too slow (15-20 min on some buildbots)
     which then times out on some buildbots.  Fix also regrtest command
     line parser to allow passing -u extralargefile to run
     test_zipfile64.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31320

   (2) https://bugs.python.org/issue25674

   (3) https://bugs.python.org/issue30715

   (4) https://bugs.python.org/issue30822


File: python.info,  Node: 构建<32>,  Next: Windows<34>,  Prev: 测试<33>,  Up: Python 3 6 3 rc1

1.18.49.6 构建
..............

   - bpo-30854(1): Fix compile error when compiling –without-threads.
     Patch by Masayuki Yamamoto.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30854


File: python.info,  Node: Windows<34>,  Next: IDLE<39>,  Prev: 构建<32>,  Up: Python 3 6 3 rc1

1.18.49.7 Windows
.................

   - bpo-30389(1): Adds detection of Visual Studio 2017 to distutils on
     Windows.

   - bpo-31340(2): Change to building with MSVC v141 (included with
     Visual Studio 2017)

   - bpo-30581(3): os.cpu_count() now returns the correct number of
     processors on Windows when the number of logical processors is
     greater than 64.

   - bpo-30731(4): Add a missing xmlns to python.manifest so that it
     matches the schema.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30389

   (2) https://bugs.python.org/issue31340

   (3) https://bugs.python.org/issue30581

   (4) https://bugs.python.org/issue30731


File: python.info,  Node: IDLE<39>,  Next: 工具/示例<22>,  Prev: Windows<34>,  Up: Python 3 6 3 rc1

1.18.49.8 IDLE
..............

   - bpo-31493(1): IDLE code context – fix code update and font update
     timers.  Canceling timers prevents a warning message when test_idle
     completes.

   - bpo-31488(2): IDLE - Update non-key options in former extension
     classes.  When applying configdialog changes, call .reload for each
     feature class.  Change ParenMatch so updated options affect
     existing instances attached to existing editor windows.

   - bpo-31477(3): IDLE - Improve rstrip entry in doc.  Strip trailing
     whitespace strips more than blank spaces.  Multiline string
     literals are not skipped.

   - bpo-31480(4): IDLE - make tests pass with zzdummy extension
     disabled by default.

   - bpo-31421(5): Document how IDLE runs tkinter programs.  IDLE calls
     tcl/tk update in the background in order to make live interaction
     and experimentation with tkinter applications much easier.

   - bpo-31414(6): IDLE – fix tk entry box tests by deleting first.
     Adding to an int entry is not the same as deleting and inserting
     because int(’’) will fail.

   - bpo-31051(7): Rearrange IDLE configdialog GenPage into Window,
     Editor, and Help sections.

   - bpo-30617(8): IDLE - Add docstrings and tests for outwin subclass
     of editor.  Move some data and functions from the class to module
     level.  Patch by Cheryl Sabella.

   - bpo-31287(9): IDLE - Do not modify tkinter.message in
     test_configdialog.

   - bpo-27099(10): Convert IDLE’s built-in ’extensions’ to regular
     features.  About 10 IDLE features were implemented as supposedly
     optional extensions.  Their different behavior could be confusing
     or worse for users and not good for maintenance.  Hence the
     conversion.  The main difference for users is that user
     configurable key bindings for builtin features are now handled
     uniformly.  Now, editing a binding in a keyset only affects its
     value in the keyset.  All bindings are defined together in the
     system-specific default keysets in config-extensions.def.  All
     custom keysets are saved as a whole in config-extension.cfg.  All
     take effect as soon as one clicks Apply or Ok.  The affected events
     are ’<<force-open-completions>>’, ’<<expand-word>>’,
     ’<<force-open-calltip>>’, ’<<flash-paren>>’,
     ’<<format-paragraph>>’, ’<<run-module>>’, ’<<check-module>>’, and
     ’<<zoom-height>>’.  Any (global) customizations made before 3.6.3
     will not affect their keyset-specific customization after 3.6.3.
     and vice versa.  Initial patch by Charles Wohlganger.

   - bpo-31206(11): IDLE: Factor HighPage(Frame) class from
     ConfigDialog.  Patch by Cheryl Sabella.

   - bpo-31001(12): Add tests for configdialog highlight tab.  Patch by
     Cheryl Sabella.

   - bpo-31205(13): IDLE: Factor KeysPage(Frame) class from
     ConfigDialog.  The slightly modified tests continue to pass.  Patch
     by Cheryl Sabella.

   - bpo-31130(14): IDLE – stop leaks in test_configdialog.  Initial
     patch by Victor Stinner.

   - bpo-31002(15): Add tests for configdialog keys tab.  Patch by
     Cheryl Sabella.

   - bpo-19903(16): IDLE: Calltips use *note inspect.signature: 564.
     instead of *note inspect.getfullargspec: 566.  This improves
     calltips for builtins converted to use Argument Clinic.  Patch by
     Louie Lu.

   - bpo-31083(17): IDLE - Add an outline of a TabPage class in
     configdialog.  Update existing classes to match outline.  Initial
     patch by Cheryl Sabella.

   - bpo-31050(18): Factor GenPage(Frame) class from ConfigDialog.  The
     slightly modified tests continue to pass.  Patch by Cheryl Sabella.

   - bpo-31004(19): IDLE - Factor FontPage(Frame) class from
     ConfigDialog.  Slightly modified tests continue to pass.  Fix
     General tests.  Patch mostly by Cheryl Sabella.

   - bpo-30781(20): IDLE - Use ttk widgets in ConfigDialog.  Patches by
     Terry Jan Reedy and Cheryl Sabella.

   - bpo-31060(21): IDLE - Finish rearranging methods of ConfigDialog
     Grouping methods pertaining to each tab and the buttons will aid
     writing tests and improving the tabs and will enable splitting the
     groups into classes.

   - bpo-30853(22): IDLE – Factor a VarTrace class out of ConfigDialog.
     Instance tracers manages pairs consisting of a tk variable and a
     callback function.  When tracing is turned on, setting the variable
     calls the function.  Test coverage for the new class is 100%.

   - bpo-31003(23): IDLE: Add more tests for General tab.

   - bpo-30993(24): IDLE - Improve configdialog font page and tests.  In
     configdialog: Document causal pathways in create_font_tab
     docstring.  Simplify some attribute names.  Move set_samples calls
     to var_changed_font (idea from Cheryl Sabella).  Move related
     functions to positions after the create widgets function.  In
     test_configdialog: Fix test_font_set so not order dependent.  Fix
     renamed test_indent_scale so it tests the widget.  Adjust tests for
     movement of set_samples call.  Add tests for load functions.  Put
     all font tests in one class and tab indent tests in another.
     Except for two lines, these tests completely cover the related
     functions.

   - bpo-30981(25): IDLE – Add more configdialog font page tests.

   - bpo-28523(26): IDLE: replace ’colour’ with ’color’ in configdialog.

   - bpo-30917(27): Add tests for idlelib.config.IdleConf.  Increase
     coverage from 46% to 96%.  Patch by Louie Lu.

   - bpo-30934(28): Document coverage details for idlelib tests.  Add
     section to idlelib/idle-test/README.txt.  Include check that
     branches are taken both ways.  Exclude IDLE-specific code that does
     not run during unit tests.

   - bpo-30913(29): IDLE: Document ConfigDialog tk Vars, methods, and
     widgets in docstrings This will facilitate improving the dialog and
     splitting up the class.  Original patch by Cheryl Sabella.

   - bpo-30899(30): IDLE: Add tests for ConfigParser subclasses in
     config.  Patch by Louie Lu.

   - bpo-30881(31): IDLE: Add docstrings to browser.py.  Patch by Cheryl
     Sabella.

   - bpo-30851(32): IDLE: Remove unused variables in configdialog.  One
     is a duplicate, one is set but cannot be altered by users.  Patch
     by Cheryl Sabella.

   - bpo-30870(33): IDLE: In Settings dialog, select font with Up, Down
     keys as well as mouse.  Initial patch by Louie Lu.

   - bpo-8231(34): IDLE: call config.IdleConf.GetUserCfgDir only once.

   - bpo-30779(35): IDLE: Factor ConfigChanges class from configdialog,
     put in config; test.  * In config, put dump test code in a
     function; run it and unittest in ’if __name__ == ’__main__’.  * Add
     class config.ConfigChanges based on changes_class_v4.py on bpo
     issue.  * Add class test_config.ChangesTest, partly using
     configdialog_tests_v1.py.  * Revise configdialog to use
     ConfigChanges; see tracker msg297804.  * Revise test_configdialog
     to match configdialog changes.  * Remove configdialog functions
     unused or moved to ConfigChanges.  Cheryl Sabella contributed parts
     of the patch.

   - bpo-30777(36): IDLE: configdialog - Add docstrings and fix
     comments.  Patch by Cheryl Sabella.

   - bpo-30495(37): IDLE: Improve textview with docstrings, PEP8 names,
     and more tests.  Patch by Cheryl Sabella.

   - bpo-30723(38): IDLE: Make several improvements to parenmatch.  Add
     ’parens’ style to highlight both opener and closer.  Make ’default’
     style, which is not default, a synonym for ’opener’.  Make
     time-delay work the same with all styles.  Add help for config
     dialog extensions tab, including help for parenmatch.  Add new
     tests.  Original patch by Charles Wohlganger.

   - bpo-30674(39): IDLE: add docstrings to grep module.  Patch by
     Cheryl Sabella

   - bpo-21519(40): IDLE’s basic custom key entry dialog now detects
     duplicates properly.  Original patch by Saimadhav Heblikar.

   - bpo-29910(41): IDLE no longer deletes a character after commenting
     out a region by a key shortcut.  Add ‘return 'break'’ for this and
     other potential conflicts between IDLE and default key bindings.

   - bpo-30728(42): Review and change idlelib.configdialog names.
     Lowercase method and attribute names.  Replace ’colour’ with
     ’color’, expand overly cryptic names, delete unneeded underscores.
     Replace ‘import *’ with specific imports.  Patches by Cheryl
     Sabella.

   - bpo-6739(43): IDLE: Verify user-entered key sequences by trying to
     bind them with tk.  Add tests for all 3 validation functions.
     Original patch by G Polo.  Tests added by Cheryl Sabella.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31493

   (2) https://bugs.python.org/issue31488

   (3) https://bugs.python.org/issue31477

   (4) https://bugs.python.org/issue31480

   (5) https://bugs.python.org/issue31421

   (6) https://bugs.python.org/issue31414

   (7) https://bugs.python.org/issue31051

   (8) https://bugs.python.org/issue30617

   (9) https://bugs.python.org/issue31287

   (10) https://bugs.python.org/issue27099

   (11) https://bugs.python.org/issue31206

   (12) https://bugs.python.org/issue31001

   (13) https://bugs.python.org/issue31205

   (14) https://bugs.python.org/issue31130

   (15) https://bugs.python.org/issue31002

   (16) https://bugs.python.org/issue19903

   (17) https://bugs.python.org/issue31083

   (18) https://bugs.python.org/issue31050

   (19) https://bugs.python.org/issue31004

   (20) https://bugs.python.org/issue30781

   (21) https://bugs.python.org/issue31060

   (22) https://bugs.python.org/issue30853

   (23) https://bugs.python.org/issue31003

   (24) https://bugs.python.org/issue30993

   (25) https://bugs.python.org/issue30981

   (26) https://bugs.python.org/issue28523

   (27) https://bugs.python.org/issue30917

   (28) https://bugs.python.org/issue30934

   (29) https://bugs.python.org/issue30913

   (30) https://bugs.python.org/issue30899

   (31) https://bugs.python.org/issue30881

   (32) https://bugs.python.org/issue30851

   (33) https://bugs.python.org/issue30870

   (34) https://bugs.python.org/issue8231

   (35) https://bugs.python.org/issue30779

   (36) https://bugs.python.org/issue30777

   (37) https://bugs.python.org/issue30495

   (38) https://bugs.python.org/issue30723

   (39) https://bugs.python.org/issue30674

   (40) https://bugs.python.org/issue21519

   (41) https://bugs.python.org/issue29910

   (42) https://bugs.python.org/issue30728

   (43) https://bugs.python.org/issue6739


File: python.info,  Node: 工具/示例<22>,  Prev: IDLE<39>,  Up: Python 3 6 3 rc1

1.18.49.9 工具/示例
...................

   - bpo-30983(1): gdb integration commands (py-bt, etc.)  work on
     optimized shared builds now, too.  PEP 523(2) introduced
     _PyEval_EvalFrameDefault which inlines PyEval_EvalFrameEx on
     non-debug shared builds.  This broke the ability to use py-bt,
     py-up, and a few other Python-specific gdb integrations.  The
     problem is fixed by only looking for _PyEval_EvalFrameDefault
     frames in python-gdb.py.  Original patch by Bruno "Polaco"
     Penteado.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30983

   (2) https://www.python.org/dev/peps/pep-0523


File: python.info,  Node: Python 3 6 2 正式版,  Next: Python 3 6 2 rc2,  Prev: Python 3 6 3 rc1,  Up: 更新日志

1.18.50 Python 3.6.2 正式版
---------------------------

`发布日期: 2017-07-17'

自rc2起没有更改


File: python.info,  Node: Python 3 6 2 rc2,  Next: Python 3 6 2 rc1,  Prev: Python 3 6 2 正式版,  Up: 更新日志

1.18.51 Python 3.6.2 rc2
------------------------

`发布日期: 2017-07-07'

* Menu:

* 安全: 安全<27>.


File: python.info,  Node: 安全<27>,  Up: Python 3 6 2 rc2

1.18.51.1 安全
..............

   - bpo-30730(1): Prevent environment variables injection in subprocess
     on Windows.  Prevent passing other environment variables and
     command arguments.

   - bpo-30694(2): Upgrade expat copy from 2.2.0 to 2.2.1 to get fixes
     of multiple security vulnerabilities including: CVE-2017-9233
     (External entity infinite loop DoS), CVE-2016-9063 (Integer
     overflow, re-fix), CVE-2016-0718 (Fix regression bugs from 2.2.0’s
     fix to CVE-2016-0718) and CVE-2012-0876 (Counter hash flooding with
     SipHash).  Note: the CVE-2016-5300 (Use os-specific entropy sources
     like getrandom) doesn’t impact Python, since Python already gets
     entropy from the OS to set the expat secret using
     ‘XML_SetHashSalt()’.

   - bpo-30500(3): Fix urllib.parse.splithost() to correctly parse
     fragments.  For example, ‘splithost('//127.0.0.1#@evil.com/')’ now
     correctly returns the ‘127.0.0.1’ host, instead of treating
     ‘@evil.com’ as the host in an authentication (‘login@host’).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30730

   (2) https://bugs.python.org/issue30694

   (3) https://bugs.python.org/issue30500


File: python.info,  Node: Python 3 6 2 rc1,  Next: Python 3 6 1 正式版,  Prev: Python 3 6 2 rc2,  Up: 更新日志

1.18.52 Python 3.6.2 rc1
------------------------

`发布日期: 2017-06-17'

* Menu:

* 核心与内置: 核心与内置<44>.
* 库: 库<46>.
* 安全: 安全<28>.
* 库: 库<47>.
* IDLE: IDLE<40>.
* C API: C API<26>.
* 构建: 构建<33>.
* 文档: 文档<40>.
* 工具/示例: 工具/示例<23>.
* 测试: 测试<34>.
* Windows: Windows<35>.


File: python.info,  Node: 核心与内置<44>,  Next: 库<46>,  Up: Python 3 6 2 rc1

1.18.52.1 核心与内置
....................

   - bpo-30682(1): Removed a too-strict assertion that failed for
     certain f-strings, such as eval("f’\n’") and eval("f’\r’").

   - bpo-30604(2): Move co_extra_freefuncs to not be per-thread to avoid
     crashes

   - bpo-29104(3): Fixed parsing backslashes in f-strings.

   - bpo-27945(4): Fixed various segfaults with dict when input
     collections are mutated during searching, inserting or comparing.
     Based on patches by Duane Griffin and Tim Mitchell.

   - bpo-25794(5): Fixed type.__setattr__() and type.__delattr__() for
     non-interned attribute names.  Based on patch by Eryk Sun.

   - bpo-30039(6): If a KeyboardInterrupt happens when the interpreter
     is in the middle of resuming a chain of nested ’yield from’ or
     ’await’ calls, it’s now correctly delivered to the innermost frame.

   - bpo-12414(7): sys.getsizeof() on a code object now returns the
     sizes which includes the code struct and sizes of objects which it
     references.  Patch by Dong-hee Na.

   - bpo-29949(8): Fix memory usage regression of set and frozenset
     object.

   - bpo-29935(9): Fixed error messages in the index() method of tuple,
     list and deque when pass indices of wrong type.

   - bpo-29859(10): Show correct error messages when any of the
     pthread_* calls in thread_pthread.h fails.

   - bpo-28876(11): ‘bool(range)’ works even if ‘len(range)’ raises
     *note OverflowError: 968.

   - bpo-29600(12): Fix wrapping coroutine return values in
     StopIteration.

   - bpo-28856(13): Fix an oversight that %b format for bytes should
     support objects follow the buffer protocol.

   - bpo-29714(14): Fix a regression that bytes format may fail when
     containing zero bytes inside.

   - bpo-29478(15): If max_line_length=None is specified while using the
     Compat32 policy, it is no longer ignored.  Patch by Mircea Cosbuc.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30682

   (2) https://bugs.python.org/issue30604

   (3) https://bugs.python.org/issue29104

   (4) https://bugs.python.org/issue27945

   (5) https://bugs.python.org/issue25794

   (6) https://bugs.python.org/issue30039

   (7) https://bugs.python.org/issue12414

   (8) https://bugs.python.org/issue29949

   (9) https://bugs.python.org/issue29935

   (10) https://bugs.python.org/issue29859

   (11) https://bugs.python.org/issue28876

   (12) https://bugs.python.org/issue29600

   (13) https://bugs.python.org/issue28856

   (14) https://bugs.python.org/issue29714

   (15) https://bugs.python.org/issue29478


File: python.info,  Node: 库<46>,  Next: 安全<28>,  Prev: 核心与内置<44>,  Up: Python 3 6 2 rc1

1.18.52.2 库
............

   - bpo-30616(1): Functional API of enum allows to create empty enums.
     Patched by Dong-hee Na

   - bpo-30038(2): Fix race condition between signal delivery and wakeup
     file descriptor.  Patch by Nathaniel Smith.

   - bpo-23894(3): lib2to3 now recognizes ‘rb'...'’ and ‘f'...'’
     strings.

   - bpo-23890(4): unittest.TestCase.assertRaises() now manually breaks
     a reference cycle to not keep objects alive longer than expected.

   - bpo-30149(5): inspect.signature() now supports callables with
     variable-argument parameters wrapped with partialmethod.  Patch by
     Dong-hee Na.

   - bpo-30645(6): Fix path calculation in imp.load_package(), fixing it
     for cases when a package is only shipped with bytecodes.  Patch by
     Alexandru Ardelean.

   - bpo-29931(7): Fixed comparison check for ipaddress.ip_interface
     objects.  Patch by Sanjay Sundaresan.

   - bpo-30605(8): re.compile() no longer raises a BytesWarning when
     compiling a bytes instance with misplaced inline modifier.  Patch
     by Roy Williams.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30616

   (2) https://bugs.python.org/issue30038

   (3) https://bugs.python.org/issue23894

   (4) https://bugs.python.org/issue23890

   (5) https://bugs.python.org/issue30149

   (6) https://bugs.python.org/issue30645

   (7) https://bugs.python.org/issue29931

   (8) https://bugs.python.org/issue30605


File: python.info,  Node: 安全<28>,  Next: 库<47>,  Prev: 库<46>,  Up: Python 3 6 2 rc1

1.18.52.3 安全
..............

   - bpo-29591(1): Update expat copy from 2.1.1 to 2.2.0 to get fixes of
     CVE-2016-0718 and CVE-2016-4472.  See
     ‘https://sourceforge.net/p/expat/bugs/537/’ for more information.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29591


File: python.info,  Node: 库<47>,  Next: IDLE<40>,  Prev: 安全<28>,  Up: Python 3 6 2 rc1

1.18.52.4 库
............

   - bpo-24484(1): Avoid race condition in multiprocessing cleanup
     (#2159)

   - bpo-28994(2): The traceback no longer displayed for SystemExit
     raised in a callback registered by atexit.

   - bpo-30508(3): Don’t log exceptions if Task/Future "cancel()" method
     was called.

   - bpo-28556(4): Updates to typing module: Add generic
     AsyncContextManager, add support for ContextManager on all
     versions.  Original PRs by Jelle Zijlstra and Ivan Levkivskyi

   - bpo-29870(5): Fix ssl sockets leaks when connection is aborted in
     asyncio/ssl implementation.  Patch by Michaël Sghaïer.

   - bpo-29743(6): Closing transport during handshake process leaks open
     socket.  Patch by Nikolay Kim

   - bpo-27585(7): Fix waiter cancellation in asyncio.Lock.  Patch by
     Mathieu Sornay.

   - bpo-30418(8): On Windows, subprocess.Popen.communicate() now also
     ignore EINVAL on stdin.write() if the child process is still
     running but closed the pipe.

   - bpo-29822(9): inspect.isabstract() now works during
     __init_subclass__.  Patch by Nate Soares.

   - bpo-29581(10): ABCMeta.__new__ now accepts ‘**kwargs’, allowing
     abstract base classes to use keyword parameters in
     __init_subclass__.  Patch by Nate Soares.

   - bpo-30557(11): faulthandler now correctly filters and displays
     exception codes on Windows

   - bpo-30378(12): Fix the problem that logging.handlers.SysLogHandler
     cannot handle IPv6 addresses.

   - bpo-29960(13): Preserve generator state when
     _random.Random.setstate() raises an exception.  Patch by Bryan
     Olson.

   - bpo-30414(14): multiprocessing.Queue._feed background running
     thread do not break from main loop on exception.

   - bpo-30003(15): Fix handling escape characters in HZ codec.  Based
     on patch by Ma Lin.

   - bpo-30301(16): Fix AttributeError when using SimpleQueue.empty()
     under `spawn' and `forkserver' start methods.

   - bpo-30329(17): imaplib and poplib now catch the Windows socket
     WSAEINVAL error (code 10022) on shutdown(SHUT_RDWR): An invalid
     operation was attempted.  This error occurs sometimes on SSL
     connections.

   - bpo-30375(18): Warnings emitted when compile a regular expression
     now always point to the line in the user code.  Previously they
     could point into inners of the re module if emitted from inside of
     groups or conditionals.

   - bpo-30048(19): Fixed ‘Task.cancel()’ can be ignored when the task
     is running coroutine and the coroutine returned without any more
     ‘await’.

   - bpo-30266(20): contextlib.AbstractContextManager now supports
     anti-registration by setting __enter__ = None or __exit__ = None,
     following the pattern introduced in bpo-25958(21).  Patch by Jelle
     Zijlstra.

   - bpo-30298(22): Weaken the condition of deprecation warnings for
     inline modifiers.  Now allowed several subsequential inline
     modifiers at the start of the pattern (e.g.  ‘'(?i)(?s)...'’).  In
     verbose mode whitespaces and comments now are allowed before and
     between inline modifiers (e.g.  ‘'(?x) (?i) (?s)...'’).

   - bpo-29990(23): Fix range checking in GB18030 decoder.  Original
     patch by Ma Lin.

   - bpo-26293(24): Change resulted because of zipfile breakage.  (See
     also: bpo-29094(25))

   - bpo-30243(26): Removed the __init__ methods of _json’s scanner and
     encoder.  Misusing them could cause memory leaks or crashes.  Now
     scanner and encoder objects are completely initialized in the
     __new__ methods.

   - bpo-30185(27): Avoid KeyboardInterrupt tracebacks in forkserver
     helper process when Ctrl-C is received.

   - bpo-28556(28): Various updates to typing module: add
     typing.NoReturn type, use WrapperDescriptorType, minor bug-fixes.
     Original PRs by Jim Fasarakis-Hilliard and Ivan Levkivskyi.

   - bpo-30205(29): Fix getsockname() for unbound AF_UNIX sockets on
     Linux.

   - bpo-30070(30): Fixed leaks and crashes in errors handling in the
     parser module.

   - bpo-30061(31): Fixed crashes in IOBase methods __next__() and
     readlines() when readline() or __next__() respectively return
     non-sizeable object.  Fixed possible other errors caused by not
     checking results of PyObject_Size(), PySequence_Size(), or
     PyMapping_Size().

   - bpo-30017(32): Allowed calling the close() method of the zip entry
     writer object multiple times.  Writing to a closed writer now
     always produces a ValueError.

   - bpo-30068(33): _io._IOBase.readlines will check if it’s closed
     first when hint is present.

   - bpo-29694(34): Fixed race condition in pathlib mkdir with flags
     parents=True.  Patch by Armin Rigo.

   - bpo-29692(35): Fixed arbitrary unchaining of RuntimeError
     exceptions in contextlib.contextmanager.  Patch by Siddharth
     Velankar.

   - bpo-29998(36): Pickling and copying ImportError now preserves name
     and path attributes.

   - bpo-29953(37): Fixed memory leaks in the replace() method of
     datetime and time objects when pass out of bound fold argument.

   - bpo-29942(38): Fix a crash in itertools.chain.from_iterable when
     encountering long runs of empty iterables.

   - bpo-27863(39): Fixed multiple crashes in ElementTree caused by race
     conditions and wrong types.

   - bpo-28699(40): Fixed a bug in pools in multiprocessing.pool that
     raising an exception at the very first of an iterable may swallow
     the exception or make the program hang.  Patch by Davin Potts and
     Xiang Zhang.

   - bpo-25803(41): Avoid incorrect errors raised by
     Path.mkdir(exist_ok=True) when the OS gives priority to errors such
     as EACCES over EEXIST.

   - bpo-29861(42): Release references to tasks, their arguments and
     their results as soon as they are finished in multiprocessing.Pool.

   - bpo-29884(43): faulthandler: Restore the old sigaltstack during
     teardown.  Patch by Christophe Zeitouny.

   - bpo-25455(44): Fixed crashes in repr of recursive buffered
     file-like objects.

   - bpo-29800(45): Fix crashes in partial.__repr__ if the keys of
     partial.keywords are not strings.  Patch by Michael Seifert.

   - bpo-29742(46): get_extra_info() raises exception if get called on
     closed ssl transport.  Patch by Nikolay Kim.

   - bpo-8256(47): Fixed possible failing or crashing input() if
     attributes "encoding" or "errors" of sys.stdin or sys.stdout are
     not set or are not strings.

   - bpo-28298(48): Fix a bug that prevented array ’Q’, ’L’ and ’I’ from
     accepting big intables (objects that have __int__) as elements.
     Patch by Oren Milman.

   - bpo-28231(49): The zipfile module now accepts path-like objects for
     external paths.

   - bpo-26915(50): index() and count() methods of
     collections.abc.Sequence now check identity before checking
     equality when do comparisons.

   - bpo-29615(51): SimpleXMLRPCDispatcher no longer chains KeyError (or
     any other exception) to exception(s) raised in the dispatched
     methods.  Patch by Petr Motejlek.

   - bpo-30177(52): path.resolve(strict=False) no longer cuts the path
     after the first element not present in the filesystem.  Patch by
     Antoine Pietri.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24484

   (2) https://bugs.python.org/issue28994

   (3) https://bugs.python.org/issue30508

   (4) https://bugs.python.org/issue28556

   (5) https://bugs.python.org/issue29870

   (6) https://bugs.python.org/issue29743

   (7) https://bugs.python.org/issue27585

   (8) https://bugs.python.org/issue30418

   (9) https://bugs.python.org/issue29822

   (10) https://bugs.python.org/issue29581

   (11) https://bugs.python.org/issue30557

   (12) https://bugs.python.org/issue30378

   (13) https://bugs.python.org/issue29960

   (14) https://bugs.python.org/issue30414

   (15) https://bugs.python.org/issue30003

   (16) https://bugs.python.org/issue30301

   (17) https://bugs.python.org/issue30329

   (18) https://bugs.python.org/issue30375

   (19) https://bugs.python.org/issue30048

   (20) https://bugs.python.org/issue30266

   (21) https://bugs.python.org/issue25958

   (22) https://bugs.python.org/issue30298

   (23) https://bugs.python.org/issue29990

   (24) https://bugs.python.org/issue26293

   (25) https://bugs.python.org/issue29094

   (26) https://bugs.python.org/issue30243

   (27) https://bugs.python.org/issue30185

   (28) https://bugs.python.org/issue28556

   (29) https://bugs.python.org/issue30205

   (30) https://bugs.python.org/issue30070

   (31) https://bugs.python.org/issue30061

   (32) https://bugs.python.org/issue30017

   (33) https://bugs.python.org/issue30068

   (34) https://bugs.python.org/issue29694

   (35) https://bugs.python.org/issue29692

   (36) https://bugs.python.org/issue29998

   (37) https://bugs.python.org/issue29953

   (38) https://bugs.python.org/issue29942

   (39) https://bugs.python.org/issue27863

   (40) https://bugs.python.org/issue28699

   (41) https://bugs.python.org/issue25803

   (42) https://bugs.python.org/issue29861

   (43) https://bugs.python.org/issue29884

   (44) https://bugs.python.org/issue25455

   (45) https://bugs.python.org/issue29800

   (46) https://bugs.python.org/issue29742

   (47) https://bugs.python.org/issue8256

   (48) https://bugs.python.org/issue28298

   (49) https://bugs.python.org/issue28231

   (50) https://bugs.python.org/issue26915

   (51) https://bugs.python.org/issue29615

   (52) https://bugs.python.org/issue30177


File: python.info,  Node: IDLE<40>,  Next: C API<26>,  Prev: 库<47>,  Up: Python 3 6 2 rc1

1.18.52.5 IDLE
..............

   - bpo-15786(1): Fix several problems with IDLE’s autocompletion box.
     The following should now work: clicking on selection box items;
     using the scrollbar; selecting an item by hitting Return.  Hangs on
     MacOSX should no longer happen.  Patch by Louie Lu.

   - bpo-25514(2): Add doc subsubsection about IDLE failure to start.
     Popup no-connection message directs users to this section.

   - bpo-30642(3): Fix reference leaks in IDLE tests.  Patches by Louie
     Lu and Terry Jan Reedy.

   - bpo-30495(4): Add docstrings for textview.py and use PEP8 names.
     Patches by Cheryl Sabella and Terry Jan Reedy.

   - bpo-30290(5): Help-about: use pep8 names and add tests.  Increase
     coverage to 100%.  Patches by Louie Lu, Cheryl Sabella, and Terry
     Jan Reedy.

   - bpo-30303(6): Add _utest option to textview; add new tests.
     Increase coverage to 100%.  Patches by Louie Lu and Terry Jan
     Reedy.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15786

   (2) https://bugs.python.org/issue25514

   (3) https://bugs.python.org/issue30642

   (4) https://bugs.python.org/issue30495

   (5) https://bugs.python.org/issue30290

   (6) https://bugs.python.org/issue30303


File: python.info,  Node: C API<26>,  Next: 构建<33>,  Prev: IDLE<40>,  Up: Python 3 6 2 rc1

1.18.52.6 C API
...............

   - bpo-27867(1): Function PySlice_GetIndicesEx() no longer replaced
     with a macro if Py_LIMITED_API is not set.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27867


File: python.info,  Node: 构建<33>,  Next: 文档<40>,  Prev: C API<26>,  Up: Python 3 6 2 rc1

1.18.52.7 构建
..............

   - bpo-29941(1): Add ‘--with-assertions’ configure flag to explicitly
     enable C ‘assert()’ checks.  Defaults to off.  ‘--with-pydebug’
     implies ‘--with-assertions’.

   - bpo-28787(2): Fix out-of-tree builds of Python when configured with
     ‘--with--dtrace’.

   - bpo-29243(3): Prevent unnecessary rebuilding of Python during ‘make
     test’, ‘make install’ and some other make targets when configured
     with ‘--enable-optimizations’.

   - bpo-23404(4): Don’t regenerate generated files based on file
     modification time anymore: the action is now explicit.  Replace
     ‘make touch’ with ‘make regen-all’.

   - bpo-29643(5): Fix ‘--enable-optimization’ didn’t work.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29941

   (2) https://bugs.python.org/issue28787

   (3) https://bugs.python.org/issue29243

   (4) https://bugs.python.org/issue23404

   (5) https://bugs.python.org/issue29643


File: python.info,  Node: 文档<40>,  Next: 工具/示例<23>,  Prev: 构建<33>,  Up: Python 3 6 2 rc1

1.18.52.8 文档
..............

   - bpo-30176(1): Add missing attribute related constants in curses
     documentation.

   - bpo-30052(2): the link targets for *note bytes(): 33a. and *note
     bytearray(): 33b. are now their respective type definitions, rather
     than the corresponding builtin function entries.  Use *note bytes:
     10cd. and *note bytearray: 10ce. to reference the latter.  In order
     to ensure this and future cross-reference updates are applied
     automatically, the daily documentation builds now disable the
     default output caching features in Sphinx.

   - bpo-26985(3): Add missing info of code object in inspect
     documentation.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30176

   (2) https://bugs.python.org/issue30052

   (3) https://bugs.python.org/issue26985


File: python.info,  Node: 工具/示例<23>,  Next: 测试<34>,  Prev: 文档<40>,  Up: Python 3 6 2 rc1

1.18.52.9 工具/示例
...................

   - bpo-29367(1): python-gdb.py now supports also ‘method-wrapper’
     (‘wrapperobject’) objects.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29367


File: python.info,  Node: 测试<34>,  Next: Windows<35>,  Prev: 工具/示例<23>,  Up: Python 3 6 2 rc1

1.18.52.10 测试
...............

   - bpo-30357(1): test_thread: setUp() now uses
     support.threading_setup() and support.threading_cleanup() to wait
     until threads complete to avoid random side effects on following
     tests.  Initial patch written by Grzegorz Grzywacz.

   - bpo-30197(2): Enhanced functions swap_attr() and swap_item() in the
     test.support module.  They now work when delete replaced attribute
     or item inside the with statement.  The old value of the attribute
     or item (or None if it doesn’t exist) now will be assigned to the
     target of the "as" clause, if there is one.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30357

   (2) https://bugs.python.org/issue30197


File: python.info,  Node: Windows<35>,  Prev: 测试<34>,  Up: Python 3 6 2 rc1

1.18.52.11 Windows
..................

   - bpo-30687(1): Locate msbuild.exe on Windows when building rather
     than vcvarsall.bat

   - bpo-30450(2): The build process on Windows no longer depends on
     Subversion, instead pulling external code from GitHub via a Python
     script.  If Python 3.6 is not found on the system (via ‘py -3.6’),
     NuGet is used to download a copy of 32-bit Python.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30687

   (2) https://bugs.python.org/issue30450


File: python.info,  Node: Python 3 6 1 正式版,  Next: Python 3 6 1 rc1,  Prev: Python 3 6 2 rc1,  Up: 更新日志

1.18.53 Python 3.6.1 正式版
---------------------------

`发布日期: 2017-03-21'

* Menu:

* 核心与内置: 核心与内置<45>.
* 构建: 构建<34>.


File: python.info,  Node: 核心与内置<45>,  Next: 构建<34>,  Up: Python 3 6 1 正式版

1.18.53.1 核心与内置
....................

   - bpo-29723(1): The ‘sys.path[0]’ initialization change for
     bpo-29139(2) caused a regression by revealing an inconsistency in
     how sys.path is initialized when executing ‘__main__’ from a
     zipfile, directory, or other import location.  The interpreter now
     consistently avoids ever adding the import location’s parent
     directory to ‘sys.path’, and ensures no other ‘sys.path’ entries
     are inadvertently modified when inserting the import location named
     on the command line.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29723

   (2) https://bugs.python.org/issue29139


File: python.info,  Node: 构建<34>,  Prev: 核心与内置<45>,  Up: Python 3 6 1 正式版

1.18.53.2 构建
..............

   - bpo-27593(1): fix format of git information used in sys.version

   - Fix incompatible comment in python.h

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27593


File: python.info,  Node: Python 3 6 1 rc1,  Next: Python 3 6 0 正式版,  Prev: Python 3 6 1 正式版,  Up: 更新日志

1.18.54 Python 3.6.1 rc1
------------------------

`发布日期: 2017-03-04'

* Menu:

* 核心与内置: 核心与内置<46>.
* 库: 库<48>.
* IDLE: IDLE<41>.
* Windows: Windows<36>.
* C API: C API<27>.
* 文档: 文档<41>.
* 测试: 测试<35>.
* 构建: 构建<35>.


File: python.info,  Node: 核心与内置<46>,  Next: 库<48>,  Up: Python 3 6 1 rc1

1.18.54.1 核心与内置
....................

   - bpo-28893(1): Set correct __cause__ for errors about invalid
     awaitables returned from __aiter__ and __anext__.

   - bpo-29683(2): Fixes to memory allocation in _PyCode_SetExtra.
     Patch by Brian Coleman.

   - bpo-29684(3): Fix minor regression of
     PyEval_CallObjectWithKeywords.  It should raise TypeError when
     kwargs is not a dict.  But it might cause segv when args=NULL and
     kwargs is not a dict.

   - bpo-28598(4): Support __rmod__ for subclasses of str being called
     before str.__mod__.  Patch by Martijn Pieters.

   - bpo-29607(5): Fix stack_effect computation for CALL_FUNCTION_EX.
     Patch by Matthieu Dartiailh.

   - bpo-29602(6): Fix incorrect handling of signed zeros in complex
     constructor for complex subclasses and for inputs having a
     __complex__ method.  Patch by Serhiy Storchaka.

   - bpo-29347(7): Fixed possibly dereferencing undefined pointers when
     creating weakref objects.

   - bpo-29438(8): Fixed use-after-free problem in key sharing dict.

   - bpo-29319(9): Prevent RunMainFromImporter overwriting sys.path[0].

   - bpo-29337(10): Fixed possible BytesWarning when compare the code
     objects.  Warnings could be emitted at compile time.

   - bpo-29327(11): Fixed a crash when pass the iterable keyword
     argument to sorted().

   - bpo-29034(12): Fix memory leak and use-after-free in os module
     (path_converter).

   - bpo-29159(13): Fix regression in bytes(x) when x.__index__() raises
     Exception.

   - bpo-28932(14): Do not include <sys/random.h> if it does not exist.

   - bpo-25677(15): Correct the positioning of the syntax error caret
     for indented blocks.  Based on patch by Michael Layzell.

   - bpo-29000(16): Fixed bytes formatting of octals with zero padding
     in alternate form.

   - bpo-26919(17): On Android, operating system data is now always
     encoded/decoded to/from UTF-8, instead of the locale encoding to
     avoid inconsistencies with os.fsencode() and os.fsdecode() which
     are already using UTF-8.

   - bpo-28991(18): functools.lru_cache() was susceptible to an obscure
     reentrancy bug triggerable by a monkey-patched len() function.

   - bpo-28739(19): f-string expressions are no longer accepted as
     docstrings and by ast.literal_eval() even if they do not include
     expressions.

   - bpo-28512(20): Fixed setting the offset attribute of SyntaxError by
     PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

   - bpo-28918(21): Fix the cross compilation of xxlimited when Python
     has been built with Py_DEBUG defined.

   - bpo-28731(22): Optimize _PyDict_NewPresized() to create correct
     size dict.  Improve speed of dict literal with constant keys up to
     30%.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28893

   (2) https://bugs.python.org/issue29683

   (3) https://bugs.python.org/issue29684

   (4) https://bugs.python.org/issue28598

   (5) https://bugs.python.org/issue29607

   (6) https://bugs.python.org/issue29602

   (7) https://bugs.python.org/issue29347

   (8) https://bugs.python.org/issue29438

   (9) https://bugs.python.org/issue29319

   (10) https://bugs.python.org/issue29337

   (11) https://bugs.python.org/issue29327

   (12) https://bugs.python.org/issue29034

   (13) https://bugs.python.org/issue29159

   (14) https://bugs.python.org/issue28932

   (15) https://bugs.python.org/issue25677

   (16) https://bugs.python.org/issue29000

   (17) https://bugs.python.org/issue26919

   (18) https://bugs.python.org/issue28991

   (19) https://bugs.python.org/issue28739

   (20) https://bugs.python.org/issue28512

   (21) https://bugs.python.org/issue28918

   (22) https://bugs.python.org/issue28731


File: python.info,  Node: 库<48>,  Next: IDLE<41>,  Prev: 核心与内置<46>,  Up: Python 3 6 1 rc1

1.18.54.2 库
............

   - bpo-29169(1): Update zlib to 1.2.11.

   - bpo-29623(2): Allow use of path-like object as a single argument in
     ConfigParser.read().  Patch by David Ellis.

   - bpo-28963(3): Fix out of bound iteration in
     asyncio.Future.remove_done_callback implemented in C.

   - bpo-29704(4): asyncio.subprocess.SubprocessStreamProtocol no longer
     closes before all pipes are closed.

   - bpo-29271(5): Fix Task.current_task and Task.all_tasks implemented
     in C to accept None argument as their pure Python implementation.

   - bpo-29703(6): Fix asyncio to support instantiation of new event
     loops in child processes.

   - bpo-29376(7): Fix assertion error in
     threading._DummyThread.is_alive().

   - bpo-28624(8): Add a test that checks that cwd parameter of Popen()
     accepts PathLike objects.  Patch by Sayan Chowdhury.

   - bpo-28518(9): Start a transaction implicitly before a DML
     statement.  Patch by Aviv Palivoda.

   - bpo-29532(10): Altering a kwarg dictionary passed to
     functools.partial() no longer affects a partial object after
     creation.

   - bpo-29110(11): Fix file object leak in aifc.open() when file is
     given as a filesystem path and is not in valid AIFF format.  Patch
     by Anthony Zhang.

   - bpo-28556(12): Various updates to typing module: typing.Counter,
     typing.ChainMap, improved ABC caching, etc.  Original PRs by Jelle
     Zijlstra, Ivan Levkivskyi, Manuel Krebber, and Łukasz Langa.

   - bpo-29100(13): Fix datetime.fromtimestamp() regression introduced
     in Python 3.6.0: check minimum and maximum years.

   - bpo-29519(14): Fix weakref spewing exceptions during interpreter
     shutdown when used with a rare combination of multiprocessing and
     custom codecs.

   - bpo-29416(15): Prevent infinite loop in pathlib.Path.mkdir

   - bpo-29444(16): Fixed out-of-bounds buffer access in the group()
     method of the match object.  Based on patch by WGH.

   - bpo-29335(17): Fix subprocess.Popen.wait() when the child process
     has exited to a stopped instead of terminated state (ex: when under
     ptrace).

   - bpo-29290(18): Fix a regression in argparse that help messages
     would wrap at non-breaking spaces.

   - bpo-28735(19): Fixed the comparison of mock.MagickMock with
     mock.ANY.

   - bpo-29316(20): Restore the provisional status of typing module, add
     corresponding note to documentation.  Patch by Ivan L.

   - bpo-29219(21): Fixed infinite recursion in the repr of
     uninitialized ctypes.CDLL instances.

   - bpo-29011(22): Fix an important omission by adding Deque to the
     typing module.

   - bpo-28969(23): Fixed race condition in C implementation of
     functools.lru_cache.  KeyError could be raised when cached function
     with full cache was simultaneously called from different threads
     with the same uncached arguments.

   - bpo-29142(24): In urllib.request, suffixes in no_proxy environment
     variable with leading dots could match related hostnames again
     (e.g.  .b.c matches a.b.c).  Patch by Milan Oberkirch.

   - bpo-28961(25): Fix unittest.mock._Call helper: don’t ignore the
     name parameter anymore.  Patch written by Jiajun Huang.

   - bpo-29203(26): functools.lru_cache() now respects PEP 468(27) and
     preserves the order of keyword arguments.  f(a=1, b=2) is now
     cached separately from f(b=2, a=1) since both calls could
     potentially give different results.

   - bpo-15812(28): inspect.getframeinfo() now correctly shows the first
     line of a context.  Patch by Sam Breese.

   - bpo-29094(29): Offsets in a ZIP file created with extern file
     object and modes "w" and "x" now are relative to the start of the
     file.

   - bpo-29085(30): Allow random.Random.seed() to use high quality OS
     randomness rather than the pid and time.

   - bpo-29061(31): Fixed bug in secrets.randbelow() which would hang
     when given a negative input.  Patch by Brendan Donegan.

   - bpo-29079(32): Prevent infinite loop in pathlib.resolve() on
     Windows

   - bpo-13051(33): Fixed recursion errors in large or resized
     curses.textpad.Textbox.  Based on patch by Tycho Andersen.

   - bpo-29119(34): Fix weakrefs in the pure python version of
     collections.OrderedDict move_to_end() method.  Contributed by Andra
     Bogildea.

   - bpo-9770(35): curses.ascii predicates now work correctly with
     negative integers.

   - bpo-28427(36): old keys should not remove new values from
     WeakValueDictionary when collecting from another thread.

   - bpo-28923(37): Remove editor artifacts from Tix.py.

   - bpo-29055(38): Neaten-up empty population error on random.choice()
     by suppressing the upstream exception.

   - bpo-28871(39): Fixed a crash when deallocate deep ElementTree.

   - bpo-19542(40): Fix bugs in WeakValueDictionary.setdefault() and
     WeakValueDictionary.pop() when a GC collection happens in another
     thread.

   - bpo-20191(41): Fixed a crash in resource.prlimit() when passing a
     sequence that doesn’t own its elements as limits.

   - bpo-28779(42): multiprocessing.set_forkserver_preload() would crash
     the forkserver process if a preloaded module instantiated some
     multiprocessing objects such as locks.

   - bpo-28847(43): dbm.dumb now supports reading read-only files and no
     longer writes the index file when it is not changed.

   - bpo-26937(44): The chown() method of the tarfile.TarFile class does
     not fail now when the grp module cannot be imported, as for example
     on Android platforms.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29169

   (2) https://bugs.python.org/issue29623

   (3) https://bugs.python.org/issue28963

   (4) https://bugs.python.org/issue29704

   (5) https://bugs.python.org/issue29271

   (6) https://bugs.python.org/issue29703

   (7) https://bugs.python.org/issue29376

   (8) https://bugs.python.org/issue28624

   (9) https://bugs.python.org/issue28518

   (10) https://bugs.python.org/issue29532

   (11) https://bugs.python.org/issue29110

   (12) https://bugs.python.org/issue28556

   (13) https://bugs.python.org/issue29100

   (14) https://bugs.python.org/issue29519

   (15) https://bugs.python.org/issue29416

   (16) https://bugs.python.org/issue29444

   (17) https://bugs.python.org/issue29335

   (18) https://bugs.python.org/issue29290

   (19) https://bugs.python.org/issue28735

   (20) https://bugs.python.org/issue29316

   (21) https://bugs.python.org/issue29219

   (22) https://bugs.python.org/issue29011

   (23) https://bugs.python.org/issue28969

   (24) https://bugs.python.org/issue29142

   (25) https://bugs.python.org/issue28961

   (26) https://bugs.python.org/issue29203

   (27) https://www.python.org/dev/peps/pep-0468

   (28) https://bugs.python.org/issue15812

   (29) https://bugs.python.org/issue29094

   (30) https://bugs.python.org/issue29085

   (31) https://bugs.python.org/issue29061

   (32) https://bugs.python.org/issue29079

   (33) https://bugs.python.org/issue13051

   (34) https://bugs.python.org/issue29119

   (35) https://bugs.python.org/issue9770

   (36) https://bugs.python.org/issue28427

   (37) https://bugs.python.org/issue28923

   (38) https://bugs.python.org/issue29055

   (39) https://bugs.python.org/issue28871

   (40) https://bugs.python.org/issue19542

   (41) https://bugs.python.org/issue20191

   (42) https://bugs.python.org/issue28779

   (43) https://bugs.python.org/issue28847

   (44) https://bugs.python.org/issue26937


File: python.info,  Node: IDLE<41>,  Next: Windows<36>,  Prev: 库<48>,  Up: Python 3 6 1 rc1

1.18.54.3 IDLE
..............

   - bpo-29071(1): IDLE colors f-string prefixes (but not invalid ur
     prefixes).

   - bpo-28572(2): Add 10% to coverage of IDLE’s test_configdialog.
     Update and augment description of the configuration system.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29071

   (2) https://bugs.python.org/issue28572


File: python.info,  Node: Windows<36>,  Next: C API<27>,  Prev: IDLE<41>,  Up: Python 3 6 1 rc1

1.18.54.4 Windows
.................

   - bpo-29579(1): Removes readme.txt from the installer

   - bpo-29326(2): Ignores blank lines in ._pth files (Patch by Alexey
     Izbyshev)

   - bpo-28164(3): Correctly handle special console filenames (patch by
     Eryk Sun)

   - bpo-29409(4): Implement PEP 529(5) for io.FileIO (Patch by Eryk
     Sun)

   - bpo-29392(6): Prevent crash when passing invalid arguments into
     msvcrt module.

   - bpo-25778(7): winreg does not truncate string correctly (Patch by
     Eryk Sun)

   - bpo-28896(8): Deprecate WindowsRegistryFinder and disable it by
     default.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29579

   (2) https://bugs.python.org/issue29326

   (3) https://bugs.python.org/issue28164

   (4) https://bugs.python.org/issue29409

   (5) https://www.python.org/dev/peps/pep-0529

   (6) https://bugs.python.org/issue29392

   (7) https://bugs.python.org/issue25778

   (8) https://bugs.python.org/issue28896


File: python.info,  Node: C API<27>,  Next: 文档<41>,  Prev: Windows<36>,  Up: Python 3 6 1 rc1

1.18.54.5 C API
...............

   - bpo-27867(1): Function PySlice_GetIndicesEx() is replaced with a
     macro if Py_LIMITED_API is not set or set to the value between
     0x03050400 and 0x03060000 (not including) or 0x03060100 or higher.

   - bpo-29083(2): Fixed the declaration of some public API functions.
     PyArg_VaParse() and PyArg_VaParseTupleAndKeywords() were not
     available in limited API. PyArg_ValidateKeywordArguments(),
     PyArg_UnpackTuple() and Py_BuildValue() were not available in
     limited API of version < 3.3 when PY_SSIZE_T_CLEAN is defined.

   - bpo-29058(3): All stable API extensions added after Python 3.2 are
     now available only when Py_LIMITED_API is set to the PY_VERSION_HEX
     value of the minimum Python version supporting this API.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27867

   (2) https://bugs.python.org/issue29083

   (3) https://bugs.python.org/issue29058


File: python.info,  Node: 文档<41>,  Next: 测试<35>,  Prev: C API<27>,  Up: Python 3 6 1 rc1

1.18.54.6 文档
..............

   - bpo-28929(1): Link the documentation to its source file on GitHub.

   - bpo-25008(2): Document smtpd.py as effectively deprecated and add a
     pointer to aiosmtpd, a third-party asyncio-based replacement.

   - bpo-26355(3): Add canonical header link on each page to
     corresponding major version of the documentation.  Patch by
     Matthias Bussonnier.

   - bpo-29349(4): Fix Python 2 syntax in code for building the
     documentation.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28929

   (2) https://bugs.python.org/issue25008

   (3) https://bugs.python.org/issue26355

   (4) https://bugs.python.org/issue29349


File: python.info,  Node: 测试<35>,  Next: 构建<35>,  Prev: 文档<41>,  Up: Python 3 6 1 rc1

1.18.54.7 测试
..............

   - bpo-28087(1): Skip test_asyncore and test_eintr poll failures on
     macOS. Skip some tests of select.poll when running on macOS due to
     unresolved issues with the underlying system poll function on some
     macOS versions.

   - bpo-29571(2): to match the behaviour of the ‘re.LOCALE’ flag,
     test_re.test_locale_flag now uses
     ‘locale.getpreferredencoding(False)’ to determine the candidate
     encoding for the test regex (allowing it to correctly skip the test
     when the default locale encoding is a multi-byte encoding)

   - bpo-28950(3): Disallow -j0 to be combined with -T/-l in regrtest
     command line arguments.

   - bpo-28683(4): Fix the tests that bind() a unix socket and raise
     PermissionError on Android for a non-root user.

   - bpo-26939(5): Add the support.setswitchinterval() function to fix
     test_functools hanging on the Android armv7 qemu emulator.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28087

   (2) https://bugs.python.org/issue29571

   (3) https://bugs.python.org/issue28950

   (4) https://bugs.python.org/issue28683

   (5) https://bugs.python.org/issue26939


File: python.info,  Node: 构建<35>,  Prev: 测试<35>,  Up: Python 3 6 1 rc1

1.18.54.8 构建
..............

   - bpo-27593(1): sys.version and the platform module python_build(),
     python_branch(), and python_revision() functions now use git
     information rather than hg when building from a repo.

   - bpo-29572(2): 更新Windows 构建和OS X安装程序以使用OpenSSL 1.0.2k。

   - bpo-26851(3): Set Android compilation and link flags.

   - bpo-28768(4): Fix implicit declaration of function _setmode.  Patch
     by Masayuki Yamamoto

   - bpo-29080(5): Removes hard dependency on hg.exe from
     PCBuild/build.bat

   - bpo-23903(6): Added missed names to PC/python3.def.

   - bpo-28762(7): lockf() is available on Android API level 24, but the
     F_LOCK macro is not defined in android-ndk-r13.

   - bpo-28538(8): Fix the compilation error that occurs because
     if_nameindex() is available on Android API level 24, but the
     if_nameindex structure is not defined.

   - bpo-20211(9): Do not add the directory for installing C header
     files and the directory for installing object code libraries to the
     cross compilation search paths.  Original patch by Thomas
     Petazzoni.

   - bpo-28849(10): Do not define sys.implementation._multiarch on
     Android.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27593

   (2) https://bugs.python.org/issue29572

   (3) https://bugs.python.org/issue26851

   (4) https://bugs.python.org/issue28768

   (5) https://bugs.python.org/issue29080

   (6) https://bugs.python.org/issue23903

   (7) https://bugs.python.org/issue28762

   (8) https://bugs.python.org/issue28538

   (9) https://bugs.python.org/issue20211

   (10) https://bugs.python.org/issue28849


File: python.info,  Node: Python 3 6 0 正式版,  Next: Python 3 6 0 rc2,  Prev: Python 3 6 1 rc1,  Up: 更新日志

1.18.55 Python 3.6.0 正式版
---------------------------

`发布日期: 2016-12-23'

自rc2起没有更改


File: python.info,  Node: Python 3 6 0 rc2,  Next: Python 3 6 0 rc1,  Prev: Python 3 6 0 正式版,  Up: 更新日志

1.18.56 Python 3.6.0 rc2
------------------------

`发布日期: 2016-12-16'

* Menu:

* 核心与内置: 核心与内置<47>.
* 工具/示例: 工具/示例<24>.
* Windows: Windows<37>.
* 构建: 构建<36>.


File: python.info,  Node: 核心与内置<47>,  Next: 工具/示例<24>,  Up: Python 3 6 0 rc2

1.18.56.1 核心与内置
....................

   - bpo-28147(1): Fix a memory leak in split-table dictionaries:
     setattr() must not convert combined table into split table.  Patch
     written by INADA Naoki.

   - bpo-28990(2): Fix asyncio SSL hanging if connection is closed
     before handshake is completed.  (Patch by HoHo-Ho)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28147

   (2) https://bugs.python.org/issue28990


File: python.info,  Node: 工具/示例<24>,  Next: Windows<37>,  Prev: 核心与内置<47>,  Up: Python 3 6 0 rc2

1.18.56.2 工具/示例
...................

   - bpo-28770(1): Fix python-gdb.py for fastcalls.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28770


File: python.info,  Node: Windows<37>,  Next: 构建<36>,  Prev: 工具/示例<24>,  Up: Python 3 6 0 rc2

1.18.56.3 Windows
.................

   - bpo-28896(1): Deprecate WindowsRegistryFinder.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28896


File: python.info,  Node: 构建<36>,  Prev: Windows<37>,  Up: Python 3 6 0 rc2

1.18.56.4 构建
..............

   - bpo-28898(1): Prevent gdb build errors due to HAVE_LONG_LONG
     redefinition.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28898


File: python.info,  Node: Python 3 6 0 rc1,  Next: Python 3 6 0 beta 4,  Prev: Python 3 6 0 rc2,  Up: 更新日志

1.18.57 Python 3.6.0 rc1
------------------------

`发布日期: 2016-12-06'

* Menu:

* 核心与内置: 核心与内置<48>.
* 库: 库<49>.
* C API: C API<28>.
* 文档: 文档<42>.
* 工具/示例: 工具/示例<25>.


File: python.info,  Node: 核心与内置<48>,  Next: 库<49>,  Up: Python 3 6 0 rc1

1.18.57.1 核心与内置
....................

   - bpo-23722(1): Rather than silently producing a class that doesn’t
     support zero-argument ‘super()’ in methods, failing to pass the new
     ‘__classcell__’ namespace entry up to ‘type.__new__’ now results in
     a ‘DeprecationWarning’ and a class that supports zero-argument
     ‘super()’.

   - bpo-28797(2): Modifying the class __dict__ inside the __set_name__
     method of a descriptor that is used inside that class no longer
     prevents calling the __set_name__ method of other descriptors.

   - bpo-28782(3): Fix a bug in the implementation ‘yield from’ when
     checking if the next instruction is YIELD_FROM. Regression
     introduced by WORDCODE (bpo-26647(4)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23722

   (2) https://bugs.python.org/issue28797

   (3) https://bugs.python.org/issue28782

   (4) https://bugs.python.org/issue26647


File: python.info,  Node: 库<49>,  Next: C API<28>,  Prev: 核心与内置<48>,  Up: Python 3 6 0 rc1

1.18.57.2 库
............

   - bpo-27030(1): Unknown escapes in re.sub() replacement template are
     allowed again.  But they still are deprecated and will be disabled
     in 3.7.

   - bpo-28835(2): Fix a regression introduced in
     warnings.catch_warnings(): call warnings.showwarning() if it was
     overridden inside the context manager.

   - bpo-27172(3): To assist with upgrades from 2.7, the previously
     documented deprecation of ‘inspect.getfullargspec()’ has been
     reversed.  This decision may be revisited again after the Python
     2.7 branch is no longer officially supported.

   - bpo-26273(4): Add new ‘socket.TCP_CONGESTION’ (Linux 2.6.13) and
     ‘socket.TCP_USER_TIMEOUT’ (Linux 2.6.37) constants.  Patch written
     by Omar Sandoval.

   - bpo-24142(5): Reading a corrupt config file left configparser in an
     invalid state.  Original patch by Florian Höch.

   - bpo-28843(6): Fix asyncio C Task to handle exceptions
     __traceback__.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27030

   (2) https://bugs.python.org/issue28835

   (3) https://bugs.python.org/issue27172

   (4) https://bugs.python.org/issue26273

   (5) https://bugs.python.org/issue24142

   (6) https://bugs.python.org/issue28843


File: python.info,  Node: C API<28>,  Next: 文档<42>,  Prev: 库<49>,  Up: Python 3 6 0 rc1

1.18.57.3 C API
...............

   - bpo-28808(1): PyUnicode_CompareWithASCIIString() now never raises
     exceptions.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28808


File: python.info,  Node: 文档<42>,  Next: 工具/示例<25>,  Prev: C API<28>,  Up: Python 3 6 0 rc1

1.18.57.4 文档
..............

   - bpo-23722(1): The data model reference and the porting section in
     the What’s New guide now cover the additional ‘__classcell__’
     handling needed for custom metaclasses to fully support PEP 487(2)
     and zero-argument ‘super()’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23722

   (2) https://www.python.org/dev/peps/pep-0487


File: python.info,  Node: 工具/示例<25>,  Prev: 文档<42>,  Up: Python 3 6 0 rc1

1.18.57.5 工具/示例
...................

   - bpo-28023(1): Fix python-gdb.py didn’t support new dict
     implementation.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28023


File: python.info,  Node: Python 3 6 0 beta 4,  Next: Python 3 6 0 beta 3,  Prev: Python 3 6 0 rc1,  Up: 更新日志

1.18.58 Python 3.6.0 beta 4
---------------------------

`发布日期: 2016-11-21'

* Menu:

* 核心与内置: 核心与内置<49>.
* 库: 库<50>.
* 文档: 文档<43>.
* 测试: 测试<36>.
* 构建: 构建<37>.


File: python.info,  Node: 核心与内置<49>,  Next: 库<50>,  Up: Python 3 6 0 beta 4

1.18.58.1 核心与内置
....................

   - bpo-28532(1): Show sys.version when -V option is supplied twice.

   - bpo-27100(2): The with-statement now checks for __enter__ before it
     checks for __exit__.  This gives less confusing error messages when
     both methods are missing.  Patch by Jonathan Ellington.

   - bpo-28746(3): Fix the set_inheritable() file descriptor method on
     platforms that do not have the ioctl FIOCLEX and FIONCLEX commands.

   - bpo-26920(4): Fix not getting the locale’s charset upon
     initializing the interpreter, on platforms that do not have
     langinfo.

   - bpo-28648(5): Fixed crash in Py_DecodeLocale() in debug build on
     Mac OS X when decode astral characters.  Patch by Xiang Zhang.

   - bpo-19398(6): Extra slash no longer added to sys.path components in
     case of empty compile-time PYTHONPATH components.

   - bpo-28665(7): Improve speed of the STORE_DEREF opcode by 40%.

   - bpo-28583(8): PyDict_SetDefault didn’t combine split table when
     needed.  Patch by Xiang Zhang.

   - bpo-27243(9): Change PendingDeprecationWarning ->
     DeprecationWarning.  As it was agreed in the issue, __aiter__
     returning an awaitable should result in PendingDeprecationWarning
     in 3.5 and in DeprecationWarning in 3.6.

   - bpo-26182(10): Fix a refleak in code that raises
     DeprecationWarning.

   - bpo-28721(11): Fix asynchronous generators aclose() and athrow() to
     handle StopAsyncIteration propagation properly.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28532

   (2) https://bugs.python.org/issue27100

   (3) https://bugs.python.org/issue28746

   (4) https://bugs.python.org/issue26920

   (5) https://bugs.python.org/issue28648

   (6) https://bugs.python.org/issue19398

   (7) https://bugs.python.org/issue28665

   (8) https://bugs.python.org/issue28583

   (9) https://bugs.python.org/issue27243

   (10) https://bugs.python.org/issue26182

   (11) https://bugs.python.org/issue28721


File: python.info,  Node: 库<50>,  Next: 文档<43>,  Prev: 核心与内置<49>,  Up: Python 3 6 0 beta 4

1.18.58.2 库
............

   - bpo-28752(1): Restored the __reduce__() methods of datetime
     objects.

   - bpo-28727(2): Regular expression patterns, _sre.SRE_Pattern objects
     created by re.compile(), become comparable (only x==y and x!=y
     operators).  This change should fix the bpo-18383(3): don’t
     duplicate warning filters when the warnings module is reloaded
     (thing usually only done in unit tests).

   - bpo-20572(4): The subprocess.Popen.wait method’s undocumented
     endtime parameter now raises a DeprecationWarning.

   - bpo-25659(5): In ctypes, prevent a crash calling the from_buffer()
     and from_buffer_copy() methods on abstract classes like Array.

   - bpo-19717(6): Makes Path.resolve() succeed on paths that do not
     exist.  Patch by Vajrasky Kok

   - bpo-28563(7): Fixed possible DoS and arbitrary code execution when
     handle plural form selections in the gettext module.  The
     expression parser now supports exact syntax supported by GNU
     gettext.

   - bpo-28387(8): Fixed possible crash in _io.TextIOWrapper deallocator
     when the garbage collector is invoked in other thread.  Based on
     patch by Sebastian Cufre.

   - bpo-28600(9): Optimize loop.call_soon.

   - bpo-28613(10): Fix get_event_loop() return the current loop if
     called from coroutines/callbacks.

   - bpo-28634(11): Fix asyncio.isfuture() to support unittest.Mock.

   - bpo-26081(12): Fix refleak in _asyncio.Future.__iter__().throw.

   - bpo-28639(13): Fix inspect.isawaitable to always return bool Patch
     by Justin Mayfield.

   - bpo-28652(14): Make loop methods reject socket kinds they do not
     support.

   - bpo-28653(15): Fix a refleak in functools.lru_cache.

   - bpo-28703(16): Fix asyncio.iscoroutinefunction to handle Mock
     objects.

   - bpo-28704(17): Fix create_unix_server to support Path-like objects
     (PEP 519).

   - bpo-28720(18): Add collections.abc.AsyncGenerator.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28752

   (2) https://bugs.python.org/issue28727

   (3) https://bugs.python.org/issue18383

   (4) https://bugs.python.org/issue20572

   (5) https://bugs.python.org/issue25659

   (6) https://bugs.python.org/issue19717

   (7) https://bugs.python.org/issue28563

   (8) https://bugs.python.org/issue28387

   (9) https://bugs.python.org/issue28600

   (10) https://bugs.python.org/issue28613

   (11) https://bugs.python.org/issue28634

   (12) https://bugs.python.org/issue26081

   (13) https://bugs.python.org/issue28639

   (14) https://bugs.python.org/issue28652

   (15) https://bugs.python.org/issue28653

   (16) https://bugs.python.org/issue28703

   (17) https://bugs.python.org/issue28704

   (18) https://bugs.python.org/issue28720


File: python.info,  Node: 文档<43>,  Next: 测试<36>,  Prev: 库<50>,  Up: Python 3 6 0 beta 4

1.18.58.3 文档
..............

   - bpo-28513(1): Documented command-line interface of zipfile.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28513


File: python.info,  Node: 测试<36>,  Next: 构建<37>,  Prev: 文档<43>,  Up: Python 3 6 0 beta 4

1.18.58.4 测试
..............

   - bpo-28666(1): Now test.support.rmtree is able to remove unwritable
     or unreadable directories.

   - bpo-23839(2): Various caches now are cleared before running every
     test file.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28666

   (2) https://bugs.python.org/issue23839


File: python.info,  Node: 构建<37>,  Prev: 测试<36>,  Up: Python 3 6 0 beta 4

1.18.58.5 构建
..............

   - bpo-10656(1): Fix out-of-tree building on AIX. Patch by Tristan
     Carel and Michael Haubenwallner.

   - bpo-26359(2): Rename –with-optimiations to –enable-optimizations.

   - bpo-28676(3): Prevent missing ’getentropy’ declaration warning on
     macOS. Patch by Gareth Rees.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10656

   (2) https://bugs.python.org/issue26359

   (3) https://bugs.python.org/issue28676


File: python.info,  Node: Python 3 6 0 beta 3,  Next: Python 3 6 0 beta 2,  Prev: Python 3 6 0 beta 4,  Up: 更新日志

1.18.59 Python 3.6.0 beta 3
---------------------------

`发布日期: 2016-10-31'

* Menu:

* 核心与内置: 核心与内置<50>.
* 库: 库<51>.
* Windows: Windows<38>.
* 构建: 构建<38>.
* 测试: 测试<37>.


File: python.info,  Node: 核心与内置<50>,  Next: 库<51>,  Up: Python 3 6 0 beta 3

1.18.59.1 核心与内置
....................

   - bpo-28128(1): Deprecation warning for invalid str and byte escape
     sequences now prints better information about where the error
     occurs.  Patch by Serhiy Storchaka and Eric Smith.

   - bpo-28509(2): dict.update() no longer allocate unnecessary large
     memory.

   - bpo-28426(3): Fixed potential crash in PyUnicode_AsDecodedObject()
     in debug build.

   - bpo-28517(4): Fixed of-by-one error in the peephole optimizer that
     caused keeping unreachable code.

   - bpo-28214(5): Improved exception reporting for problematic
     __set_name__ attributes.

   - bpo-23782(6): Fixed possible memory leak in _PyTraceback_Add() and
     exception loss in PyTraceBack_Here().

   - bpo-28471(7): Fix "Python memory allocator called without holding
     the GIL" crash in socket.setblocking.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28128

   (2) https://bugs.python.org/issue28509

   (3) https://bugs.python.org/issue28426

   (4) https://bugs.python.org/issue28517

   (5) https://bugs.python.org/issue28214

   (6) https://bugs.python.org/issue23782

   (7) https://bugs.python.org/issue28471


File: python.info,  Node: 库<51>,  Next: Windows<38>,  Prev: 核心与内置<50>,  Up: Python 3 6 0 beta 3

1.18.59.2 库
............

   - bpo-27517(1): LZMA compressor and decompressor no longer raise
     exceptions if given empty data twice.  Patch by Benjamin Fogle.

   - bpo-28549(2): Fixed segfault in curses’s addch() with ncurses6.

   - bpo-28449(3): tarfile.open() with mode "r" or "r:" now tries to
     open a tar file with compression before trying to open it without
     compression.  Otherwise it had 50% chance failed with
     ignore_zeros=True.

   - bpo-23262(4): The webbrowser module now supports Firefox 36+ and
     derived browsers.  Based on patch by Oleg Broytman.

   - bpo-27939(5): Fixed bugs in tkinter.ttk.LabeledScale and
     tkinter.Scale caused by representing the scale as float value
     internally in Tk.  tkinter.IntVar now works if float value is set
     to underlying Tk variable.

   - bpo-18844(6): The various ways of specifying weights for
     random.choices() now produce the same result sequences.

   - bpo-28255(7): calendar.TextCalendar().prmonth() no longer prints a
     space at the start of new line after printing a month’s calendar.
     Patch by Xiang Zhang.

   - bpo-20491(8): The textwrap.TextWrapper class now honors
     non-breaking spaces.  Based on patch by Kaarle Ritvanen.

   - bpo-28353(9): os.fwalk() no longer fails on broken links.

   - bpo-28430(10): Fix iterator of C implemented asyncio.Future doesn’t
     accept non-None value is passed to it.send(val).

   - bpo-27025(11): Generated names for Tkinter widgets now start by the
     "!"  prefix for readability.

   - bpo-25464(12): Fixed HList.header_exists() in tkinter.tix module by
     addin a workaround to Tix library bug.

   - bpo-28488(13): shutil.make_archive() no longer adds entry "./" to
     ZIP archive.

   - bpo-25953(14): re.sub() now raises an error for invalid numerical
     group reference in replacement template even if the pattern is not
     found in the string.  Error message for invalid group reference now
     includes the group index and the position of the reference.  Based
     on patch by SilentGhost.

   - bpo-18219(15): Optimize csv.DictWriter for large number of columns.
     Patch by Mariatta Wijaya.

   - bpo-28448(16): Fix C implemented asyncio.Future didn’t work on
     Windows.

   - bpo-28480(17): Fix error building socket module when multithreading
     is disabled.

   - bpo-24452(18): Make webbrowser support Chrome on Mac OS X.

   - bpo-20766(19): Fix references leaked by pdb in the handling of
     SIGINT handlers.

   - bpo-28492(20): Fix how StopIteration exception is raised in
     _asyncio.Future.

   - bpo-28500(21): Fix asyncio to handle async gens GC from another
     thread.

   - bpo-26923(22): Fix asyncio.Gather to refuse being cancelled once
     all children are done.  Patch by Johannes Ebke.

   - bpo-26796(23): Don’t configure the number of workers for default
     threadpool executor.  Initial patch by Hans Lawrenz.

   - bpo-28544(24): Implement asyncio.Task in C.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27517

   (2) https://bugs.python.org/issue28549

   (3) https://bugs.python.org/issue28449

   (4) https://bugs.python.org/issue23262

   (5) https://bugs.python.org/issue27939

   (6) https://bugs.python.org/issue18844

   (7) https://bugs.python.org/issue28255

   (8) https://bugs.python.org/issue20491

   (9) https://bugs.python.org/issue28353

   (10) https://bugs.python.org/issue28430

   (11) https://bugs.python.org/issue27025

   (12) https://bugs.python.org/issue25464

   (13) https://bugs.python.org/issue28488

   (14) https://bugs.python.org/issue25953

   (15) https://bugs.python.org/issue18219

   (16) https://bugs.python.org/issue28448

   (17) https://bugs.python.org/issue28480

   (18) https://bugs.python.org/issue24452

   (19) https://bugs.python.org/issue20766

   (20) https://bugs.python.org/issue28492

   (21) https://bugs.python.org/issue28500

   (22) https://bugs.python.org/issue26923

   (23) https://bugs.python.org/issue26796

   (24) https://bugs.python.org/issue28544


File: python.info,  Node: Windows<38>,  Next: 构建<38>,  Prev: 库<51>,  Up: Python 3 6 0 beta 3

1.18.59.3 Windows
.................

   - bpo-28522(1): Fixes mishandled buffer reallocation in getpathp.c

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28522


File: python.info,  Node: 构建<38>,  Next: 测试<37>,  Prev: Windows<38>,  Up: Python 3 6 0 beta 3

1.18.59.4 构建
..............

   - bpo-28444(1): Fix missing extensions modules when cross compiling.

   - bpo-28208(2): 更新Windows 构建和OS X 安装程序以使用SQLite 3.14.2.

   - bpo-28248(3): 更新Windows 构建和OS X安装程序以使用OpenSSL 1.0.2j.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28444

   (2) https://bugs.python.org/issue28208

   (3) https://bugs.python.org/issue28248


File: python.info,  Node: 测试<37>,  Prev: 构建<38>,  Up: Python 3 6 0 beta 3

1.18.59.5 测试
..............

   - bpo-26944(1): Fix test_posix for Android where ’id -G’ is entirely
     wrong or missing the effective gid.

   - bpo-28409(2): regrtest: fix the parser of command line arguments.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26944

   (2) https://bugs.python.org/issue28409


File: python.info,  Node: Python 3 6 0 beta 2,  Next: Python 3 6 0 beta 1,  Prev: Python 3 6 0 beta 3,  Up: 更新日志

1.18.60 Python 3.6.0 beta 2
---------------------------

`发布日期: 2016-10-10'

* Menu:

* 核心与内置: 核心与内置<51>.
* 库: 库<52>.
* Windows: Windows<39>.
* C API: C API<29>.
* 构建: 构建<39>.
* 测试: 测试<38>.


File: python.info,  Node: 核心与内置<51>,  Next: 库<52>,  Up: Python 3 6 0 beta 2

1.18.60.1 核心与内置
....................

   - bpo-28183(1): Optimize and cleanup dict iteration.

   - bpo-26081(2): Added C implementation of asyncio.Future.  Original
     patch by Yury Selivanov.

   - bpo-28379(3): Added sanity checks and tests for
     PyUnicode_CopyCharacters().  Patch by Xiang Zhang.

   - bpo-28376(4): The type of long range iterator is now registered as
     Iterator.  Patch by Oren Milman.

   - bpo-28376(5): Creating instances of range_iterator by calling
     range_iterator type now is deprecated.  Patch by Oren Milman.

   - bpo-28376(6): The constructor of range_iterator now checks that
     step is not 0.  Patch by Oren Milman.

   - bpo-26906(7): Resolving special methods of uninitialized type now
     causes implicit initialization of the type instead of a fail.

   - bpo-18287(8): PyType_Ready() now checks that tp_name is not NULL.
     Original patch by Niklas Koep.

   - bpo-24098(9): Fixed possible crash when AST is changed in process
     of compiling it.

   - bpo-28201(10): Dict reduces possibility of 2nd conflict in hash
     table when hashes have same lower bits.

   - bpo-28350(11): String constants with null character no longer
     interned.

   - bpo-26617(12): Fix crash when GC runs during weakref callbacks.

   - bpo-27942(13): String constants now interned recursively in tuples
     and frozensets.

   - bpo-21578(14): Fixed misleading error message when ImportError
     called with invalid keyword args.

   - bpo-28203(15): Fix incorrect type in complex(1.0, {2:3}) error
     message.  Patch by Soumya Sharma.

   - bpo-28086(16): Single var-positional argument of tuple subtype was
     passed unscathed to the C-defined function.  Now it is converted to
     exact tuple.

   - bpo-28214(17): Now __set_name__ is looked up on the class instead
     of the instance.

   - bpo-27955(18): Fallback on reading /dev/urandom device when the
     getrandom() syscall fails with EPERM, for example when blocked by
     SECCOMP.

   - bpo-28192(19): Don’t import readline in isolated mode.

   - Upgrade internal unicode databases to Unicode version 9.0.0.

   - bpo-28131(20): Fix a regression in zipimport’s compile_source().
     zipimport should use the same optimization level as the
     interpreter.

   - bpo-28126(21): Replace Py_MEMCPY with memcpy().  Visual Studio can
     properly optimize memcpy().

   - bpo-28120(22): Fix dict.pop() for splitted dictionary when trying
     to remove a "pending key" (Not yet inserted in split-table).  Patch
     by Xiang Zhang.

   - bpo-26182(23): Raise DeprecationWarning when async and await
     keywords are used as variable/attribute/class/function name.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28183

   (2) https://bugs.python.org/issue26081

   (3) https://bugs.python.org/issue28379

   (4) https://bugs.python.org/issue28376

   (5) https://bugs.python.org/issue28376

   (6) https://bugs.python.org/issue28376

   (7) https://bugs.python.org/issue26906

   (8) https://bugs.python.org/issue18287

   (9) https://bugs.python.org/issue24098

   (10) https://bugs.python.org/issue28201

   (11) https://bugs.python.org/issue28350

   (12) https://bugs.python.org/issue26617

   (13) https://bugs.python.org/issue27942

   (14) https://bugs.python.org/issue21578

   (15) https://bugs.python.org/issue28203

   (16) https://bugs.python.org/issue28086

   (17) https://bugs.python.org/issue28214

   (18) https://bugs.python.org/issue27955

   (19) https://bugs.python.org/issue28192

   (20) https://bugs.python.org/issue28131

   (21) https://bugs.python.org/issue28126

   (22) https://bugs.python.org/issue28120

   (23) https://bugs.python.org/issue26182


File: python.info,  Node: 库<52>,  Next: Windows<39>,  Prev: 核心与内置<51>,  Up: Python 3 6 0 beta 2

1.18.60.2 库
............

   - bpo-27998(1): Fixed bytes path support in os.scandir() on Windows.
     Patch by Eryk Sun.

   - bpo-28317(2): The disassembler now decodes FORMAT_VALUE argument.

   - bpo-26293(3): Fixed writing ZIP files that starts not from the
     start of the file.  Offsets in ZIP file now are relative to the
     start of the archive in conforming to the specification.

   - bpo-28380(4): unittest.mock Mock autospec functions now properly
     support assert_called, assert_not_called, and assert_called_once.

   - bpo-27181(5): remove statistics.geometric_mean and defer until 3.7.

   - bpo-28229(6): lzma module now supports pathlib.

   - bpo-28321(7): Fixed writing non-BMP characters with binary format
     in plistlib.

   - bpo-28225(8): bz2 module now supports pathlib.  Initial patch by
     Ethan Furman.

   - bpo-28227(9): gzip now supports pathlib.  Patch by Ethan Furman.

   - bpo-27358(10): Optimized merging var-keyword arguments and improved
     error message when passing a non-mapping as a var-keyword argument.

   - bpo-28257(11): Improved error message when passing a non-iterable
     as a var-positional argument.  Added opcode
     BUILD_TUPLE_UNPACK_WITH_CALL.

   - bpo-28322(12): Fixed possible crashes when unpickle itertools
     objects from incorrect pickle data.  Based on patch by John Leitch.

   - bpo-28228(13): imghdr now supports pathlib.

   - bpo-28226(14): compileall now supports pathlib.

   - bpo-28314(15): Fix function declaration (C flags) for the
     getiterator() method of xml.etree.ElementTree.Element.

   - bpo-28148(16): Stop using localtime() and gmtime() in the time
     module.  Introduced platform independent _PyTime_localtime API that
     is similar to POSIX localtime_r, but available on all platforms.
     Patch by Ed Schouten.

   - bpo-28253(17): Fixed calendar functions for extreme months: 0001-01
     and 9999-12.  Methods itermonthdays() and itermonthdays2() are
     reimplemented so that they don’t call itermonthdates() which can
     cause datetime.date under/overflow.

   - bpo-28275(18): Fixed possible use after free in the decompress()
     methods of the LZMADecompressor and BZ2Decompressor classes.
     Original patch by John Leitch.

   - bpo-27897(19): Fixed possible crash in
     sqlite3.Connection.create_collation() if pass invalid string-like
     object as a name.  Patch by Xiang Zhang.

   - bpo-18844(20): random.choices() now has k as a keyword-only
     argument to improve the readability of common cases and come into
     line with the signature used in other languages.

   - bpo-18893(21): Fix invalid exception handling in
     Lib/ctypes/macholib/dyld.py.  Patch by Madison May.

   - bpo-27611(22): Fixed support of default root window in the
     tkinter.tix module.  Added the master parameter in the DisplayStyle
     constructor.

   - bpo-27348(23): In the traceback module, restore the formatting of
     exception messages like "Exception: None".  This fixes a regression
     introduced in 3.5a2.

   - bpo-25651(24): Allow falsy values to be used for msg parameter of
     subTest().

   - bpo-27778(25): Fix a memory leak in os.getrandom() when the
     getrandom() is interrupted by a signal and a signal handler raises
     a Python exception.

   - bpo-28200(26): Fix memory leak on Windows in the os module (fix
     path_converter() function).

   - bpo-25400(27): RobotFileParser now correctly returns default values
     for crawl_delay and request_rate.  Initial patch by Peter Wirtz.

   - bpo-27932(28): Prevent memory leak in win32_ver().

   - Fix UnboundLocalError in socket._sendfile_use_sendfile.

   - bpo-28075(29): Check for ERROR_ACCESS_DENIED in Windows
     implementation of os.stat().  Patch by Eryk Sun.

   - bpo-22493(30): Warning message emitted by using inline flags in the
     middle of regular expression now contains a (truncated) regex
     pattern.  Patch by Tim Graham.

   - bpo-25270(31): Prevent codecs.escape_encode() from raising
     SystemError when an empty bytestring is passed.

   - bpo-28181(32): Get antigravity over HTTPS. Patch by Kaartic
     Sivaraam.

   - bpo-25895(33): Enable WebSocket URL schemes in
     urllib.parse.urljoin.  Patch by Gergely Imreh and Markus
     Holtermann.

   - bpo-28114(34): Fix a crash in parse_envlist() when env contains
     byte strings.  Patch by Eryk Sun.

   - bpo-27599(35): Fixed buffer overrun in binascii.b2a_qp() and
     binascii.a2b_qp().

   - bpo-27906(36): Fix socket accept exhaustion during high TCP
     traffic.  Patch by Kevin Conway.

   - bpo-28174(37): Handle when SO_REUSEPORT isn’t properly supported.
     Patch by Seth Michael Larson.

   - bpo-26654(38): Inspect functools.partial in
     asyncio.Handle.__repr__.  Patch by iceboy.

   - bpo-26909(39): Fix slow pipes IO in asyncio.  Patch by INADA Naoki.

   - bpo-28176(40): Fix callbacks race in
     asyncio.SelectorLoop.sock_connect.

   - bpo-27759(41): Fix selectors incorrectly retain invalid file
     descriptors.  Patch by Mark Williams.

   - bpo-28368(42): Refuse monitoring processes if the child watcher has
     no loop attached.  Patch by Vincent Michel.

   - bpo-28369(43): Raise RuntimeError when transport’s FD is used with
     add_reader, add_writer, etc.

   - bpo-28370(44): Speedup asyncio.StreamReader.readexactly.  Patch by
     Коренберг Марк.

   - bpo-28371(45): Deprecate passing asyncio.Handles to
     run_in_executor.

   - bpo-28372(46): Fix asyncio to support formatting of non-python
     coroutines.

   - bpo-28399(47): Remove UNIX socket from FS before binding.  Patch by
     Коренберг Марк.

   - bpo-27972(48): Prohibit Tasks to await on themselves.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27998

   (2) https://bugs.python.org/issue28317

   (3) https://bugs.python.org/issue26293

   (4) https://bugs.python.org/issue28380

   (5) https://bugs.python.org/issue27181

   (6) https://bugs.python.org/issue28229

   (7) https://bugs.python.org/issue28321

   (8) https://bugs.python.org/issue28225

   (9) https://bugs.python.org/issue28227

   (10) https://bugs.python.org/issue27358

   (11) https://bugs.python.org/issue28257

   (12) https://bugs.python.org/issue28322

   (13) https://bugs.python.org/issue28228

   (14) https://bugs.python.org/issue28226

   (15) https://bugs.python.org/issue28314

   (16) https://bugs.python.org/issue28148

   (17) https://bugs.python.org/issue28253

   (18) https://bugs.python.org/issue28275

   (19) https://bugs.python.org/issue27897

   (20) https://bugs.python.org/issue18844

   (21) https://bugs.python.org/issue18893

   (22) https://bugs.python.org/issue27611

   (23) https://bugs.python.org/issue27348

   (24) https://bugs.python.org/issue25651

   (25) https://bugs.python.org/issue27778

   (26) https://bugs.python.org/issue28200

   (27) https://bugs.python.org/issue25400

   (28) https://bugs.python.org/issue27932

   (29) https://bugs.python.org/issue28075

   (30) https://bugs.python.org/issue22493

   (31) https://bugs.python.org/issue25270

   (32) https://bugs.python.org/issue28181

   (33) https://bugs.python.org/issue25895

   (34) https://bugs.python.org/issue28114

   (35) https://bugs.python.org/issue27599

   (36) https://bugs.python.org/issue27906

   (37) https://bugs.python.org/issue28174

   (38) https://bugs.python.org/issue26654

   (39) https://bugs.python.org/issue26909

   (40) https://bugs.python.org/issue28176

   (41) https://bugs.python.org/issue27759

   (42) https://bugs.python.org/issue28368

   (43) https://bugs.python.org/issue28369

   (44) https://bugs.python.org/issue28370

   (45) https://bugs.python.org/issue28371

   (46) https://bugs.python.org/issue28372

   (47) https://bugs.python.org/issue28399

   (48) https://bugs.python.org/issue27972


File: python.info,  Node: Windows<39>,  Next: C API<29>,  Prev: 库<52>,  Up: Python 3 6 0 beta 2

1.18.60.3 Windows
.................

   - bpo-28402(1): Adds signed catalog files for stdlib on Windows.

   - bpo-28333(2): Enables Unicode for ps1/ps2 and input() prompts.
     (Patch by Eryk Sun)

   - bpo-28251(3): Improvements to help manuals on Windows.

   - bpo-28110(4): launcher.msi has different product codes between
     32-bit and 64-bit

   - bpo-28161(5): Opening CON for write access fails

   - bpo-28162(6): WindowsConsoleIO readall() fails if first line starts
     with Ctrl+Z

   - bpo-28163(7): WindowsConsoleIO fileno() passes wrong flags to
     _open_osfhandle

   - bpo-28164(8): _PyIO_get_console_type fails for various paths

   - bpo-28137(9): Renames Windows path file to ._pth

   - bpo-28138(10): Windows ._pth file should allow import site

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28402

   (2) https://bugs.python.org/issue28333

   (3) https://bugs.python.org/issue28251

   (4) https://bugs.python.org/issue28110

   (5) https://bugs.python.org/issue28161

   (6) https://bugs.python.org/issue28162

   (7) https://bugs.python.org/issue28163

   (8) https://bugs.python.org/issue28164

   (9) https://bugs.python.org/issue28137

   (10) https://bugs.python.org/issue28138


File: python.info,  Node: C API<29>,  Next: 构建<39>,  Prev: Windows<39>,  Up: Python 3 6 0 beta 2

1.18.60.4 C API
...............

   - bpo-28426(1): Deprecated undocumented functions
     PyUnicode_AsEncodedObject(), PyUnicode_AsDecodedObject(),
     PyUnicode_AsDecodedUnicode() and PyUnicode_AsEncodedUnicode().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28426


File: python.info,  Node: 构建<39>,  Next: 测试<38>,  Prev: C API<29>,  Up: Python 3 6 0 beta 2

1.18.60.5 构建
..............

   - bpo-28258(1): Fixed build with Estonian locale (python-config and
     distclean targets in Makefile).  Patch by Arfrever Frehtes
     Taifersar Arahesis.

   - bpo-26661(2): setup.py now detects system libffi with multiarch
     wrapper.

   - bpo-15819(3): Remove redundant include search directory option for
     building outside the source tree.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28258

   (2) https://bugs.python.org/issue26661

   (3) https://bugs.python.org/issue15819


File: python.info,  Node: 测试<38>,  Prev: 构建<39>,  Up: Python 3 6 0 beta 2

1.18.60.6 测试
..............

   - bpo-28217(1): Adds _testconsole module to test console input.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28217


File: python.info,  Node: Python 3 6 0 beta 1,  Next: Python 3 6 0 alpha 4,  Prev: Python 3 6 0 beta 2,  Up: 更新日志

1.18.61 Python 3.6.0 beta 1
---------------------------

`发布日期： 2016-09-12'

* Menu:

* 核心与内置: 核心与内置<52>.
* 库: 库<53>.
* IDLE: IDLE<42>.
* C API: C API<30>.
* 测试: 测试<39>.
* 构建: 构建<40>.
* 工具/示例: 工具/示例<26>.
* Windows: Windows<40>.


File: python.info,  Node: 核心与内置<52>,  Next: 库<53>,  Up: Python 3 6 0 beta 1

1.18.61.1 核心与内置
....................

   - bpo-23722(1): The __class__ cell used by zero-argument super() is
     now initialized from type.__new__ rather than __build_class__, so
     class methods relying on that will now work correctly when called
     from metaclass methods during class creation.  Patch by Martin
     Teichmann.

   - bpo-25221(2): Fix corrupted result from PyLong_FromLong(0) when
     Python is compiled with NSMALLPOSINTS = 0.

   - bpo-27080(3): Implement formatting support for PEP 515(4).  Initial
     patch by Chris Angelico.

   - bpo-27199(5): In tarfile, expose copyfileobj bufsize to improve
     throughput.  Patch by Jason Fried.

   - bpo-27948(6): In f-strings, only allow backslashes inside the
     braces (where the expressions are).  This is a breaking change from
     the 3.6 alpha releases, where backslashes are allowed anywhere in
     an f-string.  Also, require that expressions inside f-strings be
     enclosed within literal braces, and not escapes like
     ‘f'\x7b"hi"\x7d'’.

   - bpo-28046(7): Remove platform-specific directories from sys.path.

   - bpo-28071(8): Add early-out for differencing from an empty set.

   - bpo-25758(9): Prevents zipimport from unnecessarily encoding a
     filename (patch by Eryk Sun)

   - bpo-25856(10): The __module__ attribute of extension classes and
     functions now is interned.  This leads to more compact pickle data
     with protocol 4.

   - bpo-27213(11): Rework CALL_FUNCTION* opcodes to produce shorter and
     more efficient bytecode.  Patch by Demur Rumed, design by Serhiy
     Storchaka, reviewed by Serhiy Storchaka and Victor Stinner.

   - bpo-26331(12): Implement tokenizing support for PEP 515(13).  Patch
     by Georg Brandl.

   - bpo-27999(14): Make "global after use" a SyntaxError, and ditto for
     nonlocal.  Patch by Ivan Levkivskyi.

   - bpo-28003(15): Implement PEP 525(16) – Asynchronous Generators.

   - bpo-27985(17): Implement PEP 526(18) – Syntax for Variable
     Annotations.  Patch by Ivan Levkivskyi.

   - bpo-26058(19): Add a new private version to the builtin dict type,
     incremented at each dictionary creation and at each dictionary
     change.  Implementation of the PEP 509.

   - bpo-27364(20): A backslash-character pair that is not a valid
     escape sequence now generates a DeprecationWarning.  Patch by
     Emanuel Barry.

   - bpo-27350(21): *note dict: 1b9. implementation is changed like
     PyPy.  It is more compact and preserves insertion order.  (Concept
     developed by Raymond Hettinger and patch by Inada Naoki.)

   - bpo-27911(22): Remove unnecessary error checks in
     ‘exec_builtin_or_dynamic()’.

   - bpo-27078(23): Added BUILD_STRING opcode.  Optimized f-strings
     evaluation.

   - bpo-17884(24): Python now requires systems with inttypes.h and
     stdint.h

   - bpo-27961(25): Require platforms to support ‘long long’.  Python
     hasn’t compiled without ‘long long’ for years, so this is basically
     a formality.

   - bpo-27355(26): Removed support for Windows CE. It was never
     finished, and Windows CE is no longer a relevant platform for
     Python.

   - Implement PEP 523(27).

   - bpo-27870(28): A left shift of zero by a large integer no longer
     attempts to allocate large amounts of memory.

   - bpo-25402(29): In int-to-decimal-string conversion, improve the
     estimate of the intermediate memory required, and remove an
     unnecessarily strict overflow check.  Patch by Serhiy Storchaka.

   - bpo-27214(30): In long_invert, be more careful about modifying
     object returned by long_add, and remove an unnecessary check for
     small longs.  Thanks Oren Milman for analysis and patch.

   - bpo-27506(31): Support passing the bytes/bytearray.translate()
     "delete" argument by keyword.

   - bpo-27812(32): Properly clear out a generator’s frame’s
     backreference to the generator to prevent crashes in frame.clear().

   - bpo-27811(33): Fix a crash when a coroutine that has not been
     awaited is finalized with warnings-as-errors enabled.

   - bpo-27587(34): Fix another issue found by PVS-Studio: Null pointer
     check after use of ’def’ in _PyState_AddModule().  Initial patch by
     Christian Heimes.

   - bpo-27792(35): The modulo operation applied to ‘bool’ and other
     ‘int’ subclasses now always returns an ‘int’.  Previously the
     return type depended on the input values.  Patch by Xiang Zhang.

   - bpo-26984(36): int() now always returns an instance of exact int.

   - bpo-25604(37): Fix a minor bug in integer true division; this bug
     could potentially have caused off-by-one-ulp results on platforms
     with unreliable ldexp implementations.

   - bpo-24254(38): Make class definition namespace ordered by default.

   - bpo-27662(39): Fix an overflow check in ‘List_New’: the original
     code was checking against ‘Py_SIZE_MAX’ instead of the correct
     upper bound of ‘Py_SSIZE_T_MAX’.  Patch by Xiang Zhang.

   - bpo-27782(40): Multi-phase extension module import now correctly
     allows the ‘m_methods’ field to be used to add module level
     functions to instances of non-module types returned from
     ‘Py_create_mod’.  Patch by Xiang Zhang.

   - bpo-27936(41): The round() function accepted a second None argument
     for some types but not for others.  Fixed the inconsistency by
     accepting None for all numeric types.

   - bpo-27487(42): Warn if a submodule argument to "python -m" or
     runpy.run_module() is found in sys.modules after parent packages
     are imported, but before the submodule is executed.

   - bpo-27157(43): Make only type() itself accept the one-argument
     form.  Patch by Eryk Sun and Emanuel Barry.

   - bpo-27558(44): Fix a SystemError in the implementation of "raise"
     statement.  In a brand new thread, raise a RuntimeError since there
     is no active exception to reraise.  Patch written by Xiang Zhang.

   - bpo-28008(45): Implement PEP 530(46) – asynchronous comprehensions.

   - bpo-27942(47): Fix memory leak in codeobject.c

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23722

   (2) https://bugs.python.org/issue25221

   (3) https://bugs.python.org/issue27080

   (4) https://www.python.org/dev/peps/pep-0515

   (5) https://bugs.python.org/issue27199

   (6) https://bugs.python.org/issue27948

   (7) https://bugs.python.org/issue28046

   (8) https://bugs.python.org/issue28071

   (9) https://bugs.python.org/issue25758

   (10) https://bugs.python.org/issue25856

   (11) https://bugs.python.org/issue27213

   (12) https://bugs.python.org/issue26331

   (13) https://www.python.org/dev/peps/pep-0515

   (14) https://bugs.python.org/issue27999

   (15) https://bugs.python.org/issue28003

   (16) https://www.python.org/dev/peps/pep-0525

   (17) https://bugs.python.org/issue27985

   (18) https://www.python.org/dev/peps/pep-0526

   (19) https://bugs.python.org/issue26058

   (20) https://bugs.python.org/issue27364

   (21) https://bugs.python.org/issue27350

   (22) https://bugs.python.org/issue27911

   (23) https://bugs.python.org/issue27078

   (24) https://bugs.python.org/issue17884

   (25) https://bugs.python.org/issue27961

   (26) https://bugs.python.org/issue27355

   (27) https://www.python.org/dev/peps/pep-0523

   (28) https://bugs.python.org/issue27870

   (29) https://bugs.python.org/issue25402

   (30) https://bugs.python.org/issue27214

   (31) https://bugs.python.org/issue27506

   (32) https://bugs.python.org/issue27812

   (33) https://bugs.python.org/issue27811

   (34) https://bugs.python.org/issue27587

   (35) https://bugs.python.org/issue27792

   (36) https://bugs.python.org/issue26984

   (37) https://bugs.python.org/issue25604

   (38) https://bugs.python.org/issue24254

   (39) https://bugs.python.org/issue27662

   (40) https://bugs.python.org/issue27782

   (41) https://bugs.python.org/issue27936

   (42) https://bugs.python.org/issue27487

   (43) https://bugs.python.org/issue27157

   (44) https://bugs.python.org/issue27558

   (45) https://bugs.python.org/issue28008

   (46) https://www.python.org/dev/peps/pep-0530

   (47) https://bugs.python.org/issue27942


File: python.info,  Node: 库<53>,  Next: IDLE<42>,  Prev: 核心与内置<52>,  Up: Python 3 6 0 beta 1

1.18.61.2 库
............

   - bpo-28732(1): Fix crash in os.spawnv() with no elements in args

   - bpo-28485(2): Always raise ValueError for negative
     compileall.compile_dir(workers=...)  parameter, even when
     multithreading is unavailable.

   - bpo-28037(3): Use sqlite3_get_autocommit() instead of setting
     Connection->inTransaction manually.

   - bpo-25283(4): Attributes tm_gmtoff and tm_zone are now available on
     all platforms in the return values of time.localtime() and
     time.gmtime().

   - bpo-24454(5): Regular expression match object groups are now
     accessible using __getitem__.  "mo[x]" is equivalent to
     "mo.group(x)".

   - bpo-10740(6): sqlite3 no longer implicitly commit an open
     transaction before DDL statements.

   - bpo-17941(7): Add a `module' parameter to collections.namedtuple().

   - bpo-22493(8): Inline flags now should be used only at the start of
     the regular expression.  Deprecation warning is emitted if uses
     them in the middle of the regular expression.

   - bpo-26885(9): xmlrpc now supports unmarshalling additional data
     types used by Apache XML-RPC implementation for numerics and None.

   - bpo-28070(10): Fixed parsing inline verbose flag in regular
     expressions.

   - bpo-19500(11): Add client-side SSL session resumption to the ssl
     module.

   - bpo-28022(12): Deprecate ssl-related arguments in favor of
     SSLContext.  The deprecation include manual creation of SSLSocket
     and certfile/keyfile (or similar) in ftplib, httplib, imaplib,
     smtplib, poplib and urllib.

   - bpo-28043(13): SSLContext has improved default settings:
     OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
     OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE, OP_SINGLE_ECDH_USE
     and HIGH ciphers without MD5.

   - bpo-24693(14): Changed some RuntimeError’s in the zipfile module to
     more appropriate types.  Improved some error messages and debugging
     output.

   - bpo-17909(15): ‘json.load’ and ‘json.loads’ now support binary
     input encoded as UTF-8, UTF-16 or UTF-32.  Patch by Serhiy
     Storchaka.

   - bpo-27137(16): the pure Python fallback implementation of
     ‘functools.partial’ now matches the behaviour of its accelerated C
     counterpart for subclassing, pickling and text representation
     purposes.  Patch by Emanuel Barry and Serhiy Storchaka.

   - Fix possible integer overflows and crashes in the mmap module with
     unusual usage patterns.

   - bpo-1703178(17): Fix the ability to pass the –link-objects option
     to the distutils build_ext command.

   - bpo-28019(18): itertools.count() no longer rounds non-integer step
     in range between 1.0 and 2.0 to 1.

   - bpo-18401(19): Pdb now supports the ’readrc’ keyword argument to
     control whether .pdbrc files should be read.  Patch by Martin
     Matusiak and Sam Kimbrel.

   - bpo-25969(20): Update the lib2to3 grammar to handle the unpacking
     generalizations added in 3.5.

   - bpo-14977(21): mailcap now respects the order of the lines in the
     mailcap files ("first match"), as required by RFC 1542.  Patch by
     Michael Lazar.

   - bpo-28082(22): Convert re flag constants to IntFlag.

   - bpo-28025(23): Convert all ssl module constants to IntEnum and
     IntFlags.  SSLContext properties now return flags and enums.

   - bpo-23591(24): Add Flag, IntFlag, and auto() to enum module.

   - bpo-433028(25): Added support of modifier spans in regular
     expressions.

   - bpo-24594(26): Validates persist parameter when opening MSI
     database

   - bpo-17582(27): xml.etree.ElementTree nows preserves whitespaces in
     attributes (Patch by Duane Griffin.  Reviewed and approved by
     Stefan Behnel.)

   - bpo-28047(28): Fixed calculation of line length used for the base64
     CTE in the new email policies.

   - bpo-27576(29): Fix call order in OrderedDict.__init__().

   - email.generator.DecodedGenerator now supports the policy keyword.

   - bpo-28027(30): Remove undocumented modules from ‘Lib/plat-*’: IN,
     CDROM, DLFCN, TYPES, CDIO, and STROPTS.

   - bpo-27445(31): Don’t pass str(_charset) to MIMEText.set_payload().
     Patch by Claude Paroz.

   - bpo-24277(32): The new email API is no longer provisional, and the
     docs have been reorganized and rewritten to emphasize the new API.

   - bpo-22450(33): urllib now includes an ‘Accept: */*’ header among
     the default headers.  This makes the results of REST API requests
     more consistent and predictable especially when proxy servers are
     involved.

   - lib2to3.pgen3.driver.load_grammar() now creates a stable cache file
     between runs given the same Grammar.txt input regardless of the
     hash randomization setting.

   - bpo-28005(34): Allow ImportErrors in encoding implementation to
     propagate.

   - bpo-26667(35): Support path-like objects in importlib.util.

   - bpo-27570(36): Avoid zero-length memcpy() etc calls with null
     source pointers in the "ctypes" and "array" modules.

   - bpo-22233(37): Break email header lines `only' on the RFC specified
     CR and LF characters, not on arbitrary unicode line breaks.  This
     also fixes a bug in HTTP header parsing.

   - bpo-27331(38): The email.mime classes now all accept an optional
     policy keyword.

   - bpo-27988(39): Fix email iter_attachments incorrect mutation of
     payload list.

   - bpo-16113(40): Add SHA-3 and SHAKE support to hashlib module.

   - Eliminate a tautological-pointer-compare warning in _scproxy.c.

   - bpo-27776(41): The *note os.urandom(): 4d9. function does now block
     on Linux 3.17 and newer until the system urandom entropy pool is
     initialized to increase the security.  This change is part of the
     PEP 524(42).

   - bpo-27778(43): Expose the Linux ‘getrandom()’ syscall as a new
     *note os.getrandom(): 572. function.  This change is part of the
     PEP 524(44).

   - bpo-27691(45): Fix ssl module’s parsing of GEN_RID subject
     alternative name fields in X.509 certs.

   - bpo-18844(46): Add random.choices().

   - bpo-25761(47): Improved error reporting about truncated pickle data
     in C implementation of unpickler.  UnpicklingError is now raised
     instead of AttributeError and ValueError in some cases.

   - bpo-26798(48): Add BLAKE2 (blake2b and blake2s) to hashlib.

   - bpo-26032(49): Optimized globbing in pathlib by using os.scandir();
     it is now about 1.5–4 times faster.

   - bpo-25596(50): Optimized glob() and iglob() functions in the glob
     module; they are now about 3–6 times faster.

   - bpo-27928(51): Add scrypt (password-based key derivation function)
     to hashlib module (requires OpenSSL 1.1.0).

   - bpo-27850(52): Remove 3DES from ssl module’s default cipher list to
     counter measure sweet32 attack (CVE-2016-2183).

   - bpo-27766(53): Add ChaCha20 Poly1305 to ssl module’s default cipher
     list.  (Required OpenSSL 1.1.0 or LibreSSL).

   - bpo-25387(54): Check return value of winsound.MessageBeep.

   - bpo-27866(55): Add SSLContext.get_ciphers() method to get a list of
     all enabled ciphers.

   - bpo-27744(56): Add AF_ALG (Linux Kernel crypto) to socket module.

   - bpo-26470(57): Port ssl and hashlib module to OpenSSL 1.1.0.

   - bpo-11620(58): Fix support for SND_MEMORY in winsound.PlaySound.
     Based on a patch by Tim Lesher.

   - bpo-11734(59): Add support for IEEE 754 half-precision floats to
     the struct module.  Based on a patch by Eli Stevens.

   - bpo-27919(60): Deprecated ‘extra_path’ distribution option in
     distutils packaging.

   - bpo-23229(61): Add new ‘cmath’ constants: ‘cmath.inf’ and
     ‘cmath.nan’ to match ‘math.inf’ and ‘math.nan’, and also
     ‘cmath.infj’ and ‘cmath.nanj’ to match the format used by complex
     repr.

   - bpo-27842(62): The csv.DictReader now returns rows of type
     OrderedDict.  (Contributed by Steve Holden.)

   - Remove support for passing a file descriptor to os.access.  It
     never worked but previously didn’t raise.

   - bpo-12885(63): Fix error when distutils encounters symlink.

   - bpo-27881(64): Fixed possible bugs when setting
     sqlite3.Connection.isolation_level.  Based on patch by Xiang Zhang.

   - bpo-27861(65): Fixed a crash in sqlite3.Connection.cursor() when a
     factory creates not a cursor.  Patch by Xiang Zhang.

   - bpo-19884(66): Avoid spurious output on OS X with Gnu Readline.

   - bpo-27706(67): Restore deterministic behavior of
     random.Random().seed() for string seeds using seeding version 1.
     Allows sequences of calls to random() to exactly match those
     obtained in Python 2.  Patch by Nofar Schnider.

   - bpo-10513(68): Fix a regression in Connection.commit().  Statements
     should not be reset after a commit.

   - bpo-12319(69): Chunked transfer encoding support added to
     http.client.HTTPConnection requests.  The
     urllib.request.AbstractHTTPHandler class does not enforce a
     Content-Length header any more.  If a HTTP request has a file or
     iterable body, but no Content-Length header, the library now falls
     back to use chunked transfer-encoding.

   - A new version of typing.py from ‘https://github.com/python/typing’:
     - Collection (only for 3.6) (bpo-27598(70)) - Add FrozenSet to
     __all__ (upstream #261) - fix crash in _get_type_vars() (upstream
     #259) - Remove the dict constraint in ForwardRef._eval_type
     (upstream #252)

   - bpo-27832(71): Make ‘_normalize’ parameter to ‘Fraction’
     constructor keyword-only, so that ‘Fraction(2, 3, 4)’ now raises
     ‘TypeError’.

   - bpo-27539(72): Fix unnormalised ‘Fraction.__pow__’ result in the
     case of negative exponent and negative base.

   - bpo-21718(73): cursor.description is now available for queries
     using CTEs.

   - bpo-27819(74): In distutils sdists, simply produce the "gztar"
     (gzipped tar format) distributions on all platforms unless
     "formats" is supplied.

   - bpo-2466(75): posixpath.ismount now correctly recognizes mount
     points which the user does not have permission to access.

   - bpo-9998(76): On Linux, ctypes.util.find_library now looks in
     LD_LIBRARY_PATH for shared libraries.

   - bpo-27573(77): exit message for code.interact is now configurable.

   - bpo-27930(78): Improved behaviour of
     logging.handlers.QueueListener.  Thanks to Paulo Andrade and Petr
     Viktorin for the analysis and patch.

   - bpo-6766(79): Distributed reference counting added to
     multiprocessing to support nesting of shared values / proxy
     objects.

   - bpo-21201(80): Improves readability of multiprocessing error
     message.  Thanks to Wojciech Walczak for patch.

   - asyncio: 在各Transport类中添加了 set_protocol / get_protocol 方法

   - bpo-27456(81): asyncio: Set TCP_NODELAY by default.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28732

   (2) https://bugs.python.org/issue28485

   (3) https://bugs.python.org/issue28037

   (4) https://bugs.python.org/issue25283

   (5) https://bugs.python.org/issue24454

   (6) https://bugs.python.org/issue10740

   (7) https://bugs.python.org/issue17941

   (8) https://bugs.python.org/issue22493

   (9) https://bugs.python.org/issue26885

   (10) https://bugs.python.org/issue28070

   (11) https://bugs.python.org/issue19500

   (12) https://bugs.python.org/issue28022

   (13) https://bugs.python.org/issue28043

   (14) https://bugs.python.org/issue24693

   (15) https://bugs.python.org/issue17909

   (16) https://bugs.python.org/issue27137

   (17) https://bugs.python.org/issue1703178

   (18) https://bugs.python.org/issue28019

   (19) https://bugs.python.org/issue18401

   (20) https://bugs.python.org/issue25969

   (21) https://bugs.python.org/issue14977

   (22) https://bugs.python.org/issue28082

   (23) https://bugs.python.org/issue28025

   (24) https://bugs.python.org/issue23591

   (25) https://bugs.python.org/issue433028

   (26) https://bugs.python.org/issue24594

   (27) https://bugs.python.org/issue17582

   (28) https://bugs.python.org/issue28047

   (29) https://bugs.python.org/issue27576

   (30) https://bugs.python.org/issue28027

   (31) https://bugs.python.org/issue27445

   (32) https://bugs.python.org/issue24277

   (33) https://bugs.python.org/issue22450

   (34) https://bugs.python.org/issue28005

   (35) https://bugs.python.org/issue26667

   (36) https://bugs.python.org/issue27570

   (37) https://bugs.python.org/issue22233

   (38) https://bugs.python.org/issue27331

   (39) https://bugs.python.org/issue27988

   (40) https://bugs.python.org/issue16113

   (41) https://bugs.python.org/issue27776

   (42) https://www.python.org/dev/peps/pep-0524

   (43) https://bugs.python.org/issue27778

   (44) https://www.python.org/dev/peps/pep-0524

   (45) https://bugs.python.org/issue27691

   (46) https://bugs.python.org/issue18844

   (47) https://bugs.python.org/issue25761

   (48) https://bugs.python.org/issue26798

   (49) https://bugs.python.org/issue26032

   (50) https://bugs.python.org/issue25596

   (51) https://bugs.python.org/issue27928

   (52) https://bugs.python.org/issue27850

   (53) https://bugs.python.org/issue27766

   (54) https://bugs.python.org/issue25387

   (55) https://bugs.python.org/issue27866

   (56) https://bugs.python.org/issue27744

   (57) https://bugs.python.org/issue26470

   (58) https://bugs.python.org/issue11620

   (59) https://bugs.python.org/issue11734

   (60) https://bugs.python.org/issue27919

   (61) https://bugs.python.org/issue23229

   (62) https://bugs.python.org/issue27842

   (63) https://bugs.python.org/issue12885

   (64) https://bugs.python.org/issue27881

   (65) https://bugs.python.org/issue27861

   (66) https://bugs.python.org/issue19884

   (67) https://bugs.python.org/issue27706

   (68) https://bugs.python.org/issue10513

   (69) https://bugs.python.org/issue12319

   (70) https://bugs.python.org/issue27598

   (71) https://bugs.python.org/issue27832

   (72) https://bugs.python.org/issue27539

   (73) https://bugs.python.org/issue21718

   (74) https://bugs.python.org/issue27819

   (75) https://bugs.python.org/issue2466

   (76) https://bugs.python.org/issue9998

   (77) https://bugs.python.org/issue27573

   (78) https://bugs.python.org/issue27930

   (79) https://bugs.python.org/issue6766

   (80) https://bugs.python.org/issue21201

   (81) https://bugs.python.org/issue27456


File: python.info,  Node: IDLE<42>,  Next: C API<30>,  Prev: 库<53>,  Up: Python 3 6 0 beta 1

1.18.61.3 IDLE
..............

   - bpo-15308(1): Add ’interrupt execution’ (^C) to Shell menu.  Patch
     by Roger Serwy, updated by Bayard Randel.

   - bpo-27922(2): Stop IDLE tests from ’flashing’ gui widgets on the
     screen.

   - bpo-27891(3): Consistently group and sort imports within idlelib
     modules.

   - bpo-17642(4): add larger font sizes for classroom projection.

   - 在 IDLE 帮助窗口的标题中加入版本号

   - bpo-25564(5): In section on IDLE – console differences, mention
     that using exec means that __builtins__ is defined for each
     statement.

   - bpo-27821(6): Fix 3.6.0a3 regression that prevented custom key sets
     from being selected when no custom theme was defined.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15308

   (2) https://bugs.python.org/issue27922

   (3) https://bugs.python.org/issue27891

   (4) https://bugs.python.org/issue17642

   (5) https://bugs.python.org/issue25564

   (6) https://bugs.python.org/issue27821


File: python.info,  Node: C API<30>,  Next: 测试<39>,  Prev: IDLE<42>,  Up: Python 3 6 0 beta 1

1.18.61.4 C API
...............

   - bpo-26900(1): Excluded underscored names and other private API from
     limited API.

   - bpo-26027(2): Add support for path-like objects in
     PyUnicode_FSConverter() & PyUnicode_FSDecoder().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26900

   (2) https://bugs.python.org/issue26027


File: python.info,  Node: 测试<39>,  Next: 构建<40>,  Prev: C API<30>,  Up: Python 3 6 0 beta 1

1.18.61.5 测试
..............

   - bpo-27427(1): Additional tests for the math module.  Patch by
     Francisco Couzo.

   - bpo-27953(2): Skip math and cmath tests that fail on OS X 10.4 due
     to a poor libm implementation of tan.

   - bpo-26040(3): Improve test_math and test_cmath coverage and rigour.
     Patch by Jeff Allen.

   - bpo-27787(4): Call gc.collect() before checking each test for
     "dangling threads", since the dangling threads are weak references.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27427

   (2) https://bugs.python.org/issue27953

   (3) https://bugs.python.org/issue26040

   (4) https://bugs.python.org/issue27787


File: python.info,  Node: 构建<40>,  Next: 工具/示例<26>,  Prev: 测试<39>,  Up: Python 3 6 0 beta 1

1.18.61.6 构建
..............

   - bpo-27566(1): Fix clean target in freeze makefile (patch by Lisa
     Roach)

   - bpo-27705(2): Update message in validate_ucrtbase.py

   - bpo-27976(3): Deprecate building _ctypes with the bundled copy of
     libffi on non-OSX UNIX platforms.

   - bpo-27983(4): Cause lack of llvm-profdata tool when using clang as
     required for PGO linking to be a configure time error rather than
     make time when ‘--with-optimizations’ is enabled.  Also improve our
     ability to find the llvm-profdata tool on MacOS and some Linuxes.

   - bpo-21590(5): Support for DTrace and SystemTap probes.

   - bpo-26307(6): The profile-opt build now applies PGO to the built-in
     modules.

   - bpo-26359(7): Add the –with-optimizations flag to turn on LTO and
     PGO build support when available.

   - bpo-27917(8): Set platform triplets for Android builds.

   - bpo-25825(9): Update references to the $(LIBPL) installation path
     on AIX. This path was changed in 3.2a4.

   - 更新 OS X 安装包，使用SQLite 3.14.1 和 XZ 5.2.2版本。

   - bpo-21122(10): Fix LTO builds on OS X.

   - bpo-17128(11): Build OS X installer with a private copy of OpenSSL.
     Also provide a sample Install Certificates command script to
     install a set of root certificates from the third-party certifi
     module.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27566

   (2) https://bugs.python.org/issue27705

   (3) https://bugs.python.org/issue27976

   (4) https://bugs.python.org/issue27983

   (5) https://bugs.python.org/issue21590

   (6) https://bugs.python.org/issue26307

   (7) https://bugs.python.org/issue26359

   (8) https://bugs.python.org/issue27917

   (9) https://bugs.python.org/issue25825

   (10) https://bugs.python.org/issue21122

   (11) https://bugs.python.org/issue17128


File: python.info,  Node: 工具/示例<26>,  Next: Windows<40>,  Prev: 构建<40>,  Up: Python 3 6 0 beta 1

1.18.61.7 工具/示例
...................

   - bpo-27952(1): Get Tools/scripts/fixcid.py working with Python 3 and
     the current "re" module, avoid invalid Python backslash escapes,
     and fix a bug parsing escaped C quote signs.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27952


File: python.info,  Node: Windows<40>,  Prev: 工具/示例<26>,  Up: Python 3 6 0 beta 1

1.18.61.8 Windows
.................

   - bpo-28065(1): Update xz dependency to 5.2.2 and build it from
     source.

   - bpo-25144(2): Ensures TargetDir is set before continuing with
     custom install.

   - bpo-1602(3): Windows console doesn’t input or print Unicode (PEP
     528)

   - bpo-27781(4): Change file system encoding on Windows to UTF-8 (PEP
     529)

   - bpo-27731(5): Opt-out of MAX_PATH on Windows 10

   - bpo-6135(6): Adds encoding and errors parameters to subprocess.

   - bpo-27959(7): Adds oem encoding, alias ansi to mbcs, move aliasmbcs
     to codec lookup.

   - bpo-27982(8): The functions of the winsound module now accept
     keyword arguments.

   - bpo-20366(9): Build full text search support into SQLite on
     Windows.

   - bpo-27756(10): Adds new icons for Python files and processes on
     Windows.  Designs by Cherry Wang.

   - bpo-27883(11): 在Windows上将sqlite更新到3.14.1.0

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28065

   (2) https://bugs.python.org/issue25144

   (3) https://bugs.python.org/issue1602

   (4) https://bugs.python.org/issue27781

   (5) https://bugs.python.org/issue27731

   (6) https://bugs.python.org/issue6135

   (7) https://bugs.python.org/issue27959

   (8) https://bugs.python.org/issue27982

   (9) https://bugs.python.org/issue20366

   (10) https://bugs.python.org/issue27756

   (11) https://bugs.python.org/issue27883


File: python.info,  Node: Python 3 6 0 alpha 4,  Next: Python 3 6 0 alpha 3,  Prev: Python 3 6 0 beta 1,  Up: 更新日志

1.18.62 Python 3.6.0 alpha 4
----------------------------

`发布日期: 2016-08-15'

* Menu:

* 核心与内置: 核心与内置<53>.
* 库: 库<54>.
* IDLE: IDLE<43>.
* 测试: 测试<40>.
* Windows: Windows<41>.
* 构建: 构建<41>.


File: python.info,  Node: 核心与内置<53>,  Next: 库<54>,  Up: Python 3 6 0 alpha 4

1.18.62.1 核心与内置
....................

   - bpo-27704(1): Optimized creating bytes and bytearray from byte-like
     objects and iterables.  Speed up to 3 times for short objects.
     Original patch by Naoki Inada.

   - bpo-26823(2): Large sections of repeated lines in tracebacks are
     now abbreviated as "[Previous line repeated {count} more times]" by
     the builtin traceback rendering.  Patch by Emanuel Barry.

   - bpo-27574(3): Decreased an overhead of parsing keyword arguments in
     functions implemented with using Argument Clinic.

   - bpo-22557(4): Now importing already imported modules is up to 2.5
     times faster.

   - bpo-17596(5): Include <wincrypt.h> to help with Min GW building.

   - bpo-17599(6): On Windows, rename the privately defined
     REPARSE_DATA_BUFFER structure to avoid conflicting with the
     definition from Min GW.

   - bpo-27507(7): Add integer overflow check in bytearray.extend().
     Patch by Xiang Zhang.

   - bpo-27581(8): Don’t rely on wrapping for overflow check in
     PySequence_Tuple().  Patch by Xiang Zhang.

   - bpo-1621(9): Avoid signed integer overflow in list and tuple
     operations.  Patch by Xiang Zhang.

   - bpo-27419(10): Standard __import__() no longer look up "__import__"
     in globals or builtins for importing submodules or "from import".
     Fixed a crash if raise a warning about unabling to resolve package
     from __spec__ or __package__.

   - bpo-27083(11): Respect the PYTHONCASEOK environment variable under
     Windows.

   - bpo-27514(12): Make having too many statically nested blocks a
     SyntaxError instead of SystemError.

   - bpo-27366(13): Implemented PEP 487(14) (Simpler customization of
     class creation).  Upon subclassing, the __init_subclass__
     classmethod is called on the base class.  Descriptors are
     initialized with __set_name__ after class creation.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27704

   (2) https://bugs.python.org/issue26823

   (3) https://bugs.python.org/issue27574

   (4) https://bugs.python.org/issue22557

   (5) https://bugs.python.org/issue17596

   (6) https://bugs.python.org/issue17599

   (7) https://bugs.python.org/issue27507

   (8) https://bugs.python.org/issue27581

   (9) https://bugs.python.org/issue1621

   (10) https://bugs.python.org/issue27419

   (11) https://bugs.python.org/issue27083

   (12) https://bugs.python.org/issue27514

   (13) https://bugs.python.org/issue27366

   (14) https://www.python.org/dev/peps/pep-0487


File: python.info,  Node: 库<54>,  Next: IDLE<43>,  Prev: 核心与内置<53>,  Up: Python 3 6 0 alpha 4

1.18.62.2 库
............

   - bpo-26027(1): Add PEP 519(2)/__fspath__() support to the os and
     os.path modules.  Includes code from Jelle Zijlstra.  (See also:
     bpo-27524(3))

   - bpo-27598(4): Add Collections to collections.abc.  Patch by Ivan
     Levkivskyi, docs by Neil Girdhar.

   - bpo-25958(5): Support "anti-registration" of special methods from
     various ABCs, like __hash__, __iter__ or __len__.  All these (and
     several more) can be set to None in an implementation class and the
     behavior will be as if the method is not defined at all.
     (Previously, this mechanism existed only for __hash__, to make
     mutable classes unhashable.)  Code contributed by Andrew Barnert
     and Ivan Levkivskyi.

   - bpo-16764(6): Support keyword arguments to zlib.decompress().
     Patch by Xiang Zhang.

   - bpo-27736(7): Prevent segfault after interpreter re-initialization
     due to ref count problem introduced in code for bpo-27038(8) in
     3.6.0a3.  Patch by Xiang Zhang.

   - bpo-25628(9): The `verbose' and `rename' parameters for
     collections.namedtuple are now keyword-only.

   - bpo-12345(10): Add mathematical constant tau to math and cmath.
     See also PEP 628(11).

   - bpo-26823(12): traceback.StackSummary.format now abbreviates large
     sections of repeated lines as "[Previous line repeated {count} more
     times]" (this change then further affects other traceback display
     operations in the module).  Patch by Emanuel Barry.

   - bpo-27664(13): Add to
     concurrent.futures.thread.ThreadPoolExecutor() the ability to
     specify a thread name prefix.

   - bpo-27181(14): Add geometric_mean and harmonic_mean to statistics
     module.

   - bpo-27573(15): code.interact now prints an message when exiting.

   - bpo-6422(16): Add autorange method to timeit.Timer objects.

   - bpo-27773(17): Correct some memory management errors
     server_hostname in _ssl.wrap_socket().

   - bpo-26750(18): unittest.mock.create_autospec() now works properly
     for subclasses of property() and other data descriptors.  Removes
     the never publicly used, never documented
     unittest.mock.DescriptorTypes tuple.

   - bpo-26754(19): Undocumented support of general bytes-like objects
     as path in compile() and similar functions is now deprecated.

   - bpo-26800(20): Undocumented support of general bytes-like objects
     as paths in os functions is now deprecated.

   - bpo-26981(21): Add _order_ compatibility shim to enum.Enum for
     Python 2/3 code bases.

   - bpo-27661(22): Added tzinfo keyword argument to datetime.combine.

   - In the curses module, raise an error if window.getstr() or
     window.instr() is passed a negative value.

   - bpo-27783(23): Fix possible usage of uninitialized memory in
     operator.methodcaller.

   - bpo-27774(24): Fix possible Py_DECREF on unowned object in _sre.

   - bpo-27760(25): Fix possible integer overflow in binascii.b2a_qp.

   - bpo-27758(26): Fix possible integer overflow in the _csv module for
     large record lengths.

   - bpo-27568(27): Prevent HTTPoxy attack (CVE-2016-1000110).  Ignore
     the HTTP_PROXY variable when REQUEST_METHOD environment is set,
     which indicates that the script is in CGI mode.

   - bpo-7063(28): Remove dead code from the "array" module’s slice
     handling.  Patch by Chuck.

   - bpo-27656(29): Do not assume sched.h defines any SCHED_* constants.

   - bpo-27130(30): In the "zlib" module, fix handling of large buffers
     (typically 4 GiB) when compressing and decompressing.  Previously,
     inputs were limited to 4 GiB, and compression and decompression
     operations did not properly handle results of 4 GiB.

   - bpo-24773(31): Implemented PEP 495(32) (Local Time Disambiguation).

   - Expose the EPOLLEXCLUSIVE constant (when it is defined) in the
     select module.

   - bpo-27567(33): Expose the EPOLLRDHUP and POLLRDHUP constants in the
     select module.

   - bpo-1621(34): Avoid signed int negation overflow in the "audioop"
     module.

   - bpo-27533(35): Release GIL in nt._isdir

   - bpo-17711(36): Fixed unpickling by the persistent ID with protocol
     0.  Original patch by Alexandre Vassalotti.

   - bpo-27522(37): Avoid an unintentional reference cycle in
     email.feedparser.

   - bpo-27512(38): Fix a segfault when os.fspath() called an
     __fspath__() method that raised an exception.  Patch by Xiang
     Zhang.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26027

   (2) https://www.python.org/dev/peps/pep-0519

   (3) https://bugs.python.org/issue27524

   (4) https://bugs.python.org/issue27598

   (5) https://bugs.python.org/issue25958

   (6) https://bugs.python.org/issue16764

   (7) https://bugs.python.org/issue27736

   (8) https://bugs.python.org/issue27038

   (9) https://bugs.python.org/issue25628

   (10) https://bugs.python.org/issue12345

   (11) https://www.python.org/dev/peps/pep-0628

   (12) https://bugs.python.org/issue26823

   (13) https://bugs.python.org/issue27664

   (14) https://bugs.python.org/issue27181

   (15) https://bugs.python.org/issue27573

   (16) https://bugs.python.org/issue6422

   (17) https://bugs.python.org/issue27773

   (18) https://bugs.python.org/issue26750

   (19) https://bugs.python.org/issue26754

   (20) https://bugs.python.org/issue26800

   (21) https://bugs.python.org/issue26981

   (22) https://bugs.python.org/issue27661

   (23) https://bugs.python.org/issue27783

   (24) https://bugs.python.org/issue27774

   (25) https://bugs.python.org/issue27760

   (26) https://bugs.python.org/issue27758

   (27) https://bugs.python.org/issue27568

   (28) https://bugs.python.org/issue7063

   (29) https://bugs.python.org/issue27656

   (30) https://bugs.python.org/issue27130

   (31) https://bugs.python.org/issue24773

   (32) https://www.python.org/dev/peps/pep-0495

   (33) https://bugs.python.org/issue27567

   (34) https://bugs.python.org/issue1621

   (35) https://bugs.python.org/issue27533

   (36) https://bugs.python.org/issue17711

   (37) https://bugs.python.org/issue27522

   (38) https://bugs.python.org/issue27512


File: python.info,  Node: IDLE<43>,  Next: 测试<40>,  Prev: 库<54>,  Up: Python 3 6 0 alpha 4

1.18.62.3 IDLE
..............

   - bpo-27714(1): text_textview and test_autocomplete now pass when
     re-run in the same process.  This occurs when test_idle fails when
     run with the -w option but without -jn.  Fix warning from
     test_config.

   - bpo-27621(2): Put query response validation error messages in the
     query box itself instead of in a separate messagebox.  Redo tests
     to match.  Add Mac OSX refinements.  Original patch by Mark
     Roseman.

   - bpo-27620(3): Escape key now closes Query box as cancelled.

   - bpo-27609(4): IDLE: tab after initial whitespace should tab, not
     autocomplete.  This fixes problem with writing docstrings at least
     twice indented.

   - bpo-27609(5): Explicitly return None when there are also non-None
     returns.  In a few cases, reverse a condition and eliminate a
     return.

   - bpo-25507(6): IDLE no longer runs buggy code because of its tkinter
     imports.  Users must include the same imports required to run
     directly in Python.

   - bpo-27173(7): Add ’IDLE Modern Unix’ to the built-in key sets.
     Make the default key set depend on the platform.  Add tests for the
     changes to the config module.

   - bpo-27452(8): add line counter and crc to IDLE configHandler test
     dump.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27714

   (2) https://bugs.python.org/issue27621

   (3) https://bugs.python.org/issue27620

   (4) https://bugs.python.org/issue27609

   (5) https://bugs.python.org/issue27609

   (6) https://bugs.python.org/issue25507

   (7) https://bugs.python.org/issue27173

   (8) https://bugs.python.org/issue27452


File: python.info,  Node: 测试<40>,  Next: Windows<41>,  Prev: IDLE<43>,  Up: Python 3 6 0 alpha 4

1.18.62.4 测试
..............

   - bpo-25805(1): Skip a test in test_pkgutil as needed that doesn’t
     work when ‘__name__ == __main__’.  Patch by SilentGhost.

   - bpo-27472(2): Add test.support.unix_shell as the path to the
     default shell.

   - bpo-27369(3): In test_pyexpat, avoid testing an error message
     detail that changed in Expat 2.2.0.

   - bpo-27594(4): Prevent assertion error when running test_ast with
     coverage enabled: ensure code object has a valid first line number.
     Patch suggested by Ivan Levkivskyi.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25805

   (2) https://bugs.python.org/issue27472

   (3) https://bugs.python.org/issue27369

   (4) https://bugs.python.org/issue27594


File: python.info,  Node: Windows<41>,  Next: 构建<41>,  Prev: 测试<40>,  Up: Python 3 6 0 alpha 4

1.18.62.5 Windows
.................

   - bpo-27647(1): Update bundled Tcl/Tk to 8.6.6.

   - bpo-27610(2): Adds PEP 514(3) metadata to Windows installer

   - bpo-27469(4): Adds a shell extension to the launcher so that drag
     and drop works correctly.

   - bpo-27309(5): Enables proper Windows styles in python[w].exe
     manifest.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27647

   (2) https://bugs.python.org/issue27610

   (3) https://www.python.org/dev/peps/pep-0514

   (4) https://bugs.python.org/issue27469

   (5) https://bugs.python.org/issue27309


File: python.info,  Node: 构建<41>,  Prev: Windows<41>,  Up: Python 3 6 0 alpha 4

1.18.62.6 构建
..............

   - bpo-27713(1): Suppress spurious build warnings when updating
     importlib’s bootstrap files.  Patch by Xiang Zhang

   - bpo-25825(2): Correct the references to Modules/python.exp, which
     is required on AIX. The references were accidentally changed in
     3.5.0a1.

   - bpo-27453(3): CPP invocation in configure must use CPPFLAGS. Patch
     by Chi Hsuan Yen.

   - bpo-27641(4): The configure script now inserts comments into the
     makefile to prevent the pgen and _freeze_importlib executables from
     being cross-compiled.

   - bpo-26662(5): Set PYTHON_FOR_GEN in configure as the Python program
     to be used for file generation during the build.

   - bpo-10910(6): Avoid C++ compilation errors on FreeBSD and OS X.
     Also update FreedBSD version checks for the original ctype UTF-8
     workaround.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27713

   (2) https://bugs.python.org/issue25825

   (3) https://bugs.python.org/issue27453

   (4) https://bugs.python.org/issue27641

   (5) https://bugs.python.org/issue26662

   (6) https://bugs.python.org/issue10910


File: python.info,  Node: Python 3 6 0 alpha 3,  Next: Python 3 6 0 alpha 2,  Prev: Python 3 6 0 alpha 4,  Up: 更新日志

1.18.63 Python 3.6.0 alpha 3
----------------------------

`发布日期: 2016-07-11'

* Menu:

* 核心与内置: 核心与内置<54>.
* 库: 库<55>.
* 安全: 安全<29>.
* 库: 库<56>.
* 安全: 安全<30>.
* 库: 库<57>.
* IDLE: IDLE<44>.
* C API: C API<31>.
* 构建: 构建<42>.
* 工具/示例: 工具/示例<27>.
* 文档: 文档<44>.
* 测试: 测试<41>.


File: python.info,  Node: 核心与内置<54>,  Next: 库<55>,  Up: Python 3 6 0 alpha 3

1.18.63.1 核心与内置
....................

   - bpo-27473(1): Fixed possible integer overflow in bytes and
     bytearray concatenations.  Patch by Xiang Zhang.

   - bpo-23034(2): The output of a special Python build with defined
     COUNT_ALLOCS, SHOW_ALLOC_COUNT or SHOW_TRACK_COUNT macros is now
     off by default.  It can be re-enabled using the "-X showalloccount"
     option.  It now outputs to stderr instead of stdout.

   - bpo-27443(3): __length_hint__() of bytearray iterators no longer
     return a negative integer for a resized bytearray.

   - bpo-27007(4): The fromhex() class methods of bytes and bytearray
     subclasses now return an instance of corresponding subclass.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27473

   (2) https://bugs.python.org/issue23034

   (3) https://bugs.python.org/issue27443

   (4) https://bugs.python.org/issue27007


File: python.info,  Node: 库<55>,  Next: 安全<29>,  Prev: 核心与内置<54>,  Up: Python 3 6 0 alpha 3

1.18.63.2 库
............

   - bpo-26844(1): Fix error message for imp.find_module() to refer to
     ’path’ instead of ’name’.  Patch by Lev Maximov.

   - bpo-23804(2): Fix SSL zero-length recv() calls to not block and not
     raise an error about unclean EOF.

   - bpo-27466(3): Change time format returned by
     http.cookie.time2netscape, confirming the netscape cookie format
     and making it consistent with documentation.

   - bpo-21708(4): Deprecated dbm.dumb behavior that differs from common
     dbm behavior: creating a database in ’r’ and ’w’ modes and
     modifying a database in ’r’ mode.

   - bpo-26721(5): Change the socketserver.StreamRequestHandler.wfile
     attribute to implement BufferedIOBase.  In particular, the write()
     method no longer does partial writes.

   - bpo-22115(6): Added methods trace_add, trace_remove and trace_info
     in the tkinter.Variable class.  They replace old methods
     trace_variable, trace, trace_vdelete and trace_vinfo that use
     obsolete Tcl commands and might not work in future versions of Tcl.
     Fixed old tracing methods: trace_vdelete() with wrong mode no
     longer break tracing, trace_vinfo() now always returns a list of
     pairs of strings, tracing in the "u" mode now works.

   - bpo-26243(7): Only the level argument to zlib.compress() is keyword
     argument now.  The first argument is positional-only.

   - bpo-27038(8): Expose the DirEntry type as os.DirEntry.  Code patch
     by Jelle Zijlstra.

   - bpo-27186(9): Update os.fspath()/PyOS_FSPath() to check the return
     value of __fspath__() to be either str or bytes.

   - bpo-18726(10): All optional parameters of the dump(), dumps(),
     load() and loads() functions and JSONEncoder and JSONDecoder class
     constructors in the json module are now keyword-only.

   - bpo-27319(11): Methods selection_set(), selection_add(),
     selection_remove() and selection_toggle() of ttk.TreeView now allow
     passing multiple items as multiple arguments instead of passing
     them as a tuple.  Deprecated undocumented ability of calling the
     selection() method with arguments.

   - bpo-27079(12): Fixed curses.ascii functions isblank(), iscntrl()
     and ispunct().

   - bpo-27294(13): Numerical state in the repr for Tkinter event
     objects is now represented as a combination of known flags.

   - bpo-27177(14): Match objects in the re module now support
     index-like objects as group indices.  Based on patches by Jeroen
     Demeyer and Xiang Zhang.

   - bpo-26754(15): Some functions (compile() etc) accepted a filename
     argument encoded as an iterable of integers.  Now only strings and
     byte-like objects are accepted.

   - bpo-26536(16): socket.ioctl now supports SIO_LOOPBACK_FAST_PATH.
     Patch by Daniel Stokes.

   - bpo-27048(17): Prevents distutils failing on Windows when
     environment variables contain non-ASCII characters

   - bpo-27330(18): Fixed possible leaks in the ctypes module.

   - bpo-27238(19): Got rid of bare excepts in the turtle module.
     Original patch by Jelle Zijlstra.

   - bpo-27122(20): When an exception is raised within the context being
     managed by a contextlib.ExitStack() and one of the exit stack
     generators catches and raises it in a chain, do not re-raise the
     original exception when exiting, let the new chained one through.
     This avoids the PEP 479(21) bug described in issue25782.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26844

   (2) https://bugs.python.org/issue23804

   (3) https://bugs.python.org/issue27466

   (4) https://bugs.python.org/issue21708

   (5) https://bugs.python.org/issue26721

   (6) https://bugs.python.org/issue22115

   (7) https://bugs.python.org/issue26243

   (8) https://bugs.python.org/issue27038

   (9) https://bugs.python.org/issue27186

   (10) https://bugs.python.org/issue18726

   (11) https://bugs.python.org/issue27319

   (12) https://bugs.python.org/issue27079

   (13) https://bugs.python.org/issue27294

   (14) https://bugs.python.org/issue27177

   (15) https://bugs.python.org/issue26754

   (16) https://bugs.python.org/issue26536

   (17) https://bugs.python.org/issue27048

   (18) https://bugs.python.org/issue27330

   (19) https://bugs.python.org/issue27238

   (20) https://bugs.python.org/issue27122

   (21) https://www.python.org/dev/peps/pep-0479


File: python.info,  Node: 安全<29>,  Next: 库<56>,  Prev: 库<55>,  Up: Python 3 6 0 alpha 3

1.18.63.3 安全
..............

   - bpo-27278(1): Fix os.urandom() implementation using getrandom() on
     Linux.  Truncate size to INT_MAX and loop until we collected enough
     random bytes, instead of casting a directly Py_ssize_t to int.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27278


File: python.info,  Node: 库<56>,  Next: 安全<30>,  Prev: 安全<29>,  Up: Python 3 6 0 alpha 3

1.18.63.4 库
............

   - bpo-16864(1): sqlite3.Cursor.lastrowid now supports REPLACE
     statement.  Initial patch by Alex LordThorsen.

   - bpo-26386(2): Fixed ttk.TreeView selection operations with item
     id’s containing spaces.

   - bpo-8637(3): Honor a pager set by the env var MANPAGER (in
     preference to one set by the env var PAGER).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16864

   (2) https://bugs.python.org/issue26386

   (3) https://bugs.python.org/issue8637


File: python.info,  Node: 安全<30>,  Next: 库<57>,  Prev: 库<56>,  Up: Python 3 6 0 alpha 3

1.18.63.5 安全
..............

   - bpo-22636(1): Avoid shell injection problems with
     ctypes.util.find_library().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22636


File: python.info,  Node: 库<57>,  Next: IDLE<44>,  Prev: 安全<30>,  Up: Python 3 6 0 alpha 3

1.18.63.6 库
............

   - bpo-16182(1): Fix various functions in the "readline" module to use
     the locale encoding, and fix get_begidx() and get_endidx() to
     return code point indexes.

   - bpo-27392(2): Add loop.connect_accepted_socket().  Patch by Jim
     Fulton.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16182

   (2) https://bugs.python.org/issue27392


File: python.info,  Node: IDLE<44>,  Next: C API<31>,  Prev: 库<57>,  Up: Python 3 6 0 alpha 3

1.18.63.7 IDLE
..............

   - bpo-27477(1): IDLE search dialogs now use ttk widgets.

   - bpo-27173(2): Add ’IDLE Modern Unix’ to the built-in key sets.
     Make the default key set depend on the platform.  Add tests for the
     changes to the config module.

   - bpo-27452(3): make command line "idle-test> python test_help.py"
     work.  __file__ is relative when python is started in the file’s
     directory.

   - bpo-27452(4): add line counter and crc to IDLE configHandler test
     dump.

   - bpo-27380(5): IDLE: add query.py with base Query dialog and ttk
     widgets.  Module had subclasses SectionName, ModuleName, and
     HelpSource, which are used to get information from users by
     configdialog and file =>Load Module.  Each subclass has itw own
     validity checks.  Using ModuleName allows users to edit bad module
     names instead of starting over.  Add tests and delete the two files
     combined into the new one.

   - bpo-27372(6): Test_idle no longer changes the locale.

   - bpo-27365(7): Allow non-ascii chars in IDLE NEWS.txt, for
     contributor names.

   - bpo-27245(8): IDLE: Cleanly delete custom themes and key bindings.
     Previously, when IDLE was started from a console or by import, a
     cascade of warnings was emitted.  Patch by Serhiy Storchaka.

   - bpo-24137(9): Run IDLE, test_idle, and htest with tkinter default
     root disabled.  Fix code and tests that fail with this restriction.
     Fix htests to not create a second and redundant root and mainloop.

   - bpo-27310(10): Fix IDLE.app failure to launch on OS X due to
     vestigial import.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27477

   (2) https://bugs.python.org/issue27173

   (3) https://bugs.python.org/issue27452

   (4) https://bugs.python.org/issue27452

   (5) https://bugs.python.org/issue27380

   (6) https://bugs.python.org/issue27372

   (7) https://bugs.python.org/issue27365

   (8) https://bugs.python.org/issue27245

   (9) https://bugs.python.org/issue24137

   (10) https://bugs.python.org/issue27310


File: python.info,  Node: C API<31>,  Next: 构建<42>,  Prev: IDLE<44>,  Up: Python 3 6 0 alpha 3

1.18.63.8 C API
...............

   - bpo-26754(1): PyUnicode_FSDecoder() accepted a filename argument
     encoded as an iterable of integers.  Now only strings and byte-like
     objects are accepted.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26754


File: python.info,  Node: 构建<42>,  Next: 工具/示例<27>,  Prev: C API<31>,  Up: Python 3 6 0 alpha 3

1.18.63.9 构建
..............

   - bpo-28066(1): Fix the logic that searches build directories for
     generated include files when building outside the source tree.

   - bpo-27442(2): Expose the Android API level that python was built
     against, in sysconfig.get_config_vars() as ’ANDROID_API_LEVEL’.

   - bpo-27434(3): The interpreter that runs the cross-build, found in
     PATH, must now be of the same feature version (e.g.  3.6) as the
     source being built.

   - bpo-26930(4): 更新Windows 构建以使用OpenSSL OpenSSL 1.0.2h.

   - bpo-23968(5): Rename the platform directory from plat-$(MACHDEP) to
     plat-$(PLATFORM_TRIPLET). Rename the config directory (LIBPL) from
     config-$(LDVERSION) to config-$(LDVERSION)-$(PLATFORM_TRIPLET).
     Install the platform specific _sysconfigdata module into the
     platform directory and rename it to include the ABIFLAGS.

   - 在 GNU/Hurd 系统中不使用大文件支持。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28066

   (2) https://bugs.python.org/issue27442

   (3) https://bugs.python.org/issue27434

   (4) https://bugs.python.org/issue26930

   (5) https://bugs.python.org/issue23968


File: python.info,  Node: 工具/示例<27>,  Next: 文档<44>,  Prev: 构建<42>,  Up: Python 3 6 0 alpha 3

1.18.63.10 工具/示例
....................

   - bpo-27332(1): Fixed the type of the first argument of module-level
     functions generated by Argument Clinic.  Patch by Petr Viktorin.

   - bpo-27418(2): Fixed Tools/importbench/importbench.py.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27332

   (2) https://bugs.python.org/issue27418


File: python.info,  Node: 文档<44>,  Next: 测试<41>,  Prev: 工具/示例<27>,  Up: Python 3 6 0 alpha 3

1.18.63.11 文档
...............

   - bpo-19489(1): Moved the search box from the sidebar to the header
     and footer of each page.  Patch by Ammar Askar.

   - bpo-27285(2): Update documentation to reflect the deprecation of
     ‘pyvenv’ and normalize on the term "virtual environment".  Patch by
     Steve Piercy.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19489

   (2) https://bugs.python.org/issue27285


File: python.info,  Node: 测试<41>,  Prev: 文档<44>,  Up: Python 3 6 0 alpha 3

1.18.63.12 测试
...............

   - bpo-27027(1): Added test.support.is_android that is True when this
     is an Android build.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27027


File: python.info,  Node: Python 3 6 0 alpha 2,  Next: Python 3 6 0 alpha 1,  Prev: Python 3 6 0 alpha 3,  Up: 更新日志

1.18.64 Python 3.6.0 alpha 2
----------------------------

`发布日期: 2016-06-13'

* Menu:

* 核心与内置: 核心与内置<55>.
* 库: 库<58>.
* 安全: 安全<31>.
* 库: 库<59>.
* 安全: 安全<32>.
* 库: 库<60>.
* IDLE: IDLE<45>.
* 文档: 文档<45>.
* 测试: 测试<42>.
* Windows: Windows<42>.
* 构建: 构建<43>.
* Windows: Windows<43>.
* C API: C API<32>.
* 工具/示例: 工具/示例<28>.


File: python.info,  Node: 核心与内置<55>,  Next: 库<58>,  Up: Python 3 6 0 alpha 2

1.18.64.1 核心与内置
....................

   - bpo-27095(1): Simplified MAKE_FUNCTION and removed MAKE_CLOSURE
     opcodes.  Patch by Demur Rumed.

   - bpo-27190(2): Raise NotSupportedError if sqlite3 is older than
     3.3.1.  Patch by Dave Sawyer.

   - bpo-27286(3): Fixed compiling BUILD_MAP_UNPACK_WITH_CALL opcode.
     Calling function with generalized unpacking (PEP 448) and
     conflicting keyword names could cause undefined behavior.

   - bpo-27140(4): Added BUILD_CONST_KEY_MAP opcode.

   - bpo-27186(5): Add support for os.PathLike objects to open() (part
     of PEP 519(6)).

   - bpo-27066(7): Fixed SystemError if a custom opener (for open())
     returns a negative number without setting an exception.

   - bpo-26983(8): float() now always return an instance of exact float.
     The deprecation warning is emitted if __float__ returns an instance
     of a strict subclass of float.  In a future versions of Python this
     can be an error.

   - bpo-27097(9): Python interpreter is now about 7% faster due to
     optimized instruction decoding.  Based on patch by Demur Rumed.

   - bpo-26647(10): Python interpreter now uses 16-bit wordcode instead
     of bytecode.  Patch by Demur Rumed.

   - bpo-23275(11): Allow assigning to an empty target list in round
     brackets: () = iterable.

   - bpo-27243(12): Update the __aiter__ protocol: instead of returning
     an awaitable that resolves to an asynchronous iterator, the
     asynchronous iterator should be returned directly.  Doing the
     former will trigger a PendingDeprecationWarning.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27095

   (2) https://bugs.python.org/issue27190

   (3) https://bugs.python.org/issue27286

   (4) https://bugs.python.org/issue27140

   (5) https://bugs.python.org/issue27186

   (6) https://www.python.org/dev/peps/pep-0519

   (7) https://bugs.python.org/issue27066

   (8) https://bugs.python.org/issue26983

   (9) https://bugs.python.org/issue27097

   (10) https://bugs.python.org/issue26647

   (11) https://bugs.python.org/issue23275

   (12) https://bugs.python.org/issue27243


File: python.info,  Node: 库<58>,  Next: 安全<31>,  Prev: 核心与内置<55>,  Up: Python 3 6 0 alpha 2

1.18.64.2 库
............

   - Comment out socket (SO_REUSEPORT) and posix (O_SHLOCK, O_EXLOCK)
     constants exposed on the API which are not implemented on GNU/Hurd.
     They would not work at runtime anyway.

   - bpo-27025(1): Generated names for Tkinter widgets are now more
     meaningful and recognizable.

   - bpo-25455(2): Fixed crashes in repr of recursive
     ElementTree.Element and functools.partial objects.

   - bpo-27294(3): Improved repr for Tkinter event objects.

   - bpo-20508(4): Improve exception message of
     IPv{4,6}Network.__getitem__.  Patch by Gareth Rees.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27025

   (2) https://bugs.python.org/issue25455

   (3) https://bugs.python.org/issue27294

   (4) https://bugs.python.org/issue20508


File: python.info,  Node: 安全<31>,  Next: 库<59>,  Prev: 库<58>,  Up: Python 3 6 0 alpha 2

1.18.64.3 安全
..............

   - bpo-26556(1): Update expat to 2.1.1, fixes CVE-2015-1283.

   - Fix TLS stripping vulnerability in smtplib, CVE-2016-0772.
     Reported by Team Oststrom.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26556


File: python.info,  Node: 库<59>,  Next: 安全<32>,  Prev: 安全<31>,  Up: Python 3 6 0 alpha 2

1.18.64.4 库
............

   - bpo-21386(1): Implement missing IPv4Address.is_global property.  It
     was documented since 07a5610bae9d.  Initial patch by Roger Luethi.

   - bpo-27029(2): Removed deprecated support of universal newlines mode
     from ZipFile.open().

   - bpo-27030(3): Unknown escapes consisting of ‘'\'’ and an ASCII
     letter in regular expressions now are errors.  The re.LOCALE flag
     now can be used only with bytes patterns.

   - bpo-27186(4): Add os.PathLike support to DirEntry (part of PEP
     519(5)).  Initial patch by Jelle Zijlstra.

   - bpo-20900(6): distutils register command now decodes HTTP responses
     correctly.  Initial patch by ingrid.

   - bpo-27186(7): Add os.PathLike support to pathlib, removing its
     provisional status (part of PEP 519).  Initial patch by Dusty
     Phillips.

   - bpo-27186(8): Add support for os.PathLike objects to os.fsencode()
     and os.fsdecode() (part of PEP 519(9)).

   - bpo-27186(10): Introduce os.PathLike and os.fspath() (part of PEP
     519(11)).

   - A new version of typing.py provides several new classes and
     features: @overload outside stubs, Reversible, DefaultDict, Text,
     ContextManager, Type[], NewType(), TYPE_CHECKING, and numerous bug
     fixes (note that some of the new features are not yet implemented
     in mypy or other static analyzers).  Also classes for PEP 492(12)
     (Awaitable, AsyncIterable, AsyncIterator) have been added (in fact
     they made it into 3.5.1 but were never mentioned).

   - bpo-25738(13): Stop http.server.BaseHTTPRequestHandler.send_error()
     from sending a message body for 205 Reset Content.  Also, don’t
     send Content header fields in responses that don’t have a body.
     Patch by Susumu Koshiba.

   - bpo-21313(14): Fix the "platform" module to tolerate when
     sys.version contains truncated build information.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21386

   (2) https://bugs.python.org/issue27029

   (3) https://bugs.python.org/issue27030

   (4) https://bugs.python.org/issue27186

   (5) https://www.python.org/dev/peps/pep-0519

   (6) https://bugs.python.org/issue20900

   (7) https://bugs.python.org/issue27186

   (8) https://bugs.python.org/issue27186

   (9) https://www.python.org/dev/peps/pep-0519

   (10) https://bugs.python.org/issue27186

   (11) https://www.python.org/dev/peps/pep-0519

   (12) https://www.python.org/dev/peps/pep-0492

   (13) https://bugs.python.org/issue25738

   (14) https://bugs.python.org/issue21313


File: python.info,  Node: 安全<32>,  Next: 库<60>,  Prev: 库<59>,  Up: Python 3 6 0 alpha 2

1.18.64.5 安全
..............

   - bpo-26839(1): On Linux, *note os.urandom(): 4d9. now calls
     ‘getrandom()’ with ‘GRND_NONBLOCK’ to fall back on reading
     ‘/dev/urandom’ if the urandom entropy pool is not initialized yet.
     Patch written by Colm Buckley.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26839


File: python.info,  Node: 库<60>,  Next: IDLE<45>,  Prev: 安全<32>,  Up: Python 3 6 0 alpha 2

1.18.64.6 库
............

   - bpo-23883(1): Added missing APIs to __all__ to match the documented
     APIs for the following modules: cgi, mailbox, mimetypes, plistlib
     and smtpd.  Patches by Jacek Kołodziej.

   - bpo-27164(2): In the zlib module, allow decompressing raw Deflate
     streams with a predefined zdict.  Based on patch by Xiang Zhang.

   - bpo-24291(3): Fix wsgiref.simple_server.WSGIRequestHandler to
     completely write data to the client.  Previously it could do
     partial writes and truncate data.  Also,
     wsgiref.handler.ServerHandler can now handle stdout doing partial
     writes, but this is deprecated.

   - bpo-21272(4): Use _sysconfigdata.py to initialize
     distutils.sysconfig.

   - bpo-19611(5): *note inspect: a1. now reports the implicit ‘.0’
     parameters generated by the compiler for comprehension and
     generator expression scopes as if they were positional-only
     parameters called ‘implicit0’.  Patch by Jelle Zijlstra.

   - bpo-26809(6): Add ‘__all__’ to *note string: f7.  Patch by Emanuel
     Barry.

   - bpo-26373(7): subprocess.Popen.communicate now correctly ignores
     BrokenPipeError when the child process dies before .communicate()
     is called in more/all circumstances.

   - signal, socket, and ssl module IntEnum constant name lookups now
     return a consistent name for values having multiple names.  Ex:
     signal.Signals(6) now refers to itself as signal.SIGALRM rather
     than flipping between that and signal.SIGIOT based on the
     interpreter’s hash randomization seed.

   - bpo-27167(8): Clarify the subprocess.CalledProcessError error
     message text when the child process died due to a signal.

   - bpo-25931(9): Don’t define socketserver.Forking* names on platforms
     such as Windows that do not support os.fork().

   - bpo-21776(10): distutils.upload now correctly handles HTTPError.
     Initial patch by Claudiu Popa.

   - bpo-26526(11): Replace custom parse tree validation in the parser
     module with a simple DFA validator.

   - bpo-27114(12): Fix SSLContext._load_windows_store_certs fails with
     PermissionError

   - bpo-18383(13): Avoid creating duplicate filters when using
     filterwarnings and simplefilter.  Based on patch by Alex Shkop.

   - bpo-23026(14): winreg.QueryValueEx() now return an integer for
     REG_QWORD type.

   - bpo-26741(15): subprocess.Popen destructor now emits a
     ResourceWarning warning if the child process is still running.

   - bpo-27056(16): Optimize pickle.load() and pickle.loads(), up to 10%
     faster to deserialize a lot of small objects.

   - bpo-21271(17): New keyword only parameters in reset_mock call.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23883

   (2) https://bugs.python.org/issue27164

   (3) https://bugs.python.org/issue24291

   (4) https://bugs.python.org/issue21272

   (5) https://bugs.python.org/issue19611

   (6) https://bugs.python.org/issue26809

   (7) https://bugs.python.org/issue26373

   (8) https://bugs.python.org/issue27167

   (9) https://bugs.python.org/issue25931

   (10) https://bugs.python.org/issue21776

   (11) https://bugs.python.org/issue26526

   (12) https://bugs.python.org/issue27114

   (13) https://bugs.python.org/issue18383

   (14) https://bugs.python.org/issue23026

   (15) https://bugs.python.org/issue26741

   (16) https://bugs.python.org/issue27056

   (17) https://bugs.python.org/issue21271


File: python.info,  Node: IDLE<45>,  Next: 文档<45>,  Prev: 库<60>,  Up: Python 3 6 0 alpha 2

1.18.64.7 IDLE
..............

   - bpo-5124(1): Paste with text selected now replaces the selection on
     X11.  This matches how paste works on Windows, Mac, most modern
     Linux apps, and ttk widgets.  Original patch by Serhiy Storchaka.

   - bpo-24750(2): Switch all scrollbars in IDLE to ttk versions.  Where
     needed, minimal tests are added to cover changes.

   - bpo-24759(3): IDLE requires tk 8.5 and availability ttk widgets.
     Delete now unneeded tk version tests and code for older versions.
     Add test for IDLE syntax colorizer.

   - bpo-27239(4): idlelib.macosx.isXyzTk functions initialize as
     needed.

   - bpo-27262(5): move Aqua unbinding code, which enable context menus,
     to macosx.

   - bpo-24759(6): Make clear in idlelib.idle_test.__init__ that the
     directory is a private implementation of test.test_idle and tool
     for maintainers.

   - bpo-27196(7): Stop ’ThemeChanged’ warnings when running IDLE tests.
     These persisted after other warnings were suppressed in #20567.
     Apply Serhiy Storchaka’s update_idletasks solution to four test
     files.  Record this additional advice in idle_test/README.txt

   - bpo-20567(8): Revise idle_test/README.txt with advice about
     avoiding tk warning messages from tests.  Apply advice to several
     IDLE tests.

   - bpo-24225(9): Update idlelib/README.txt with new file names and
     event handlers.

   - bpo-27156(10): Remove obsolete code not used by IDLE.

   - bpo-27117(11): Make colorizer htest and turtledemo work with dark
     themes.  Move code for configuring text widget colors to a new
     function.

   - bpo-24225(12): Rename many ‘idlelib/*.py’ and ‘idle_test/test_*.py’
     files.  Edit files to replace old names with new names when the old
     name referred to the module rather than the class it contained.
     See the issue and IDLE section in What’s New in 3.6 for more.

   - bpo-26673(13): When tk reports font size as 0, change to size 10.
     Such fonts on Linux prevented the configuration dialog from
     opening.

   - bpo-21939(14): Add test for IDLE’s percolator.  Original patch by
     Saimadhav Heblikar.

   - bpo-21676(15): Add test for IDLE’s replace dialog.  Original patch
     by Saimadhav Heblikar.

   - bpo-18410(16): Add test for IDLE’s search dialog.  Original patch
     by Westley Martínez.

   - bpo-21703(17): Add test for undo delegator.  Patch mostly by
     Saimadhav Heblikar .

   - bpo-27044(18): Add ConfigDialog.remove_var_callbacks to stop memory
     leaks.

   - bpo-23977(19): Add more asserts to test_delegator.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5124

   (2) https://bugs.python.org/issue24750

   (3) https://bugs.python.org/issue24759

   (4) https://bugs.python.org/issue27239

   (5) https://bugs.python.org/issue27262

   (6) https://bugs.python.org/issue24759

   (7) https://bugs.python.org/issue27196

   (8) https://bugs.python.org/issue20567

   (9) https://bugs.python.org/issue24225

   (10) https://bugs.python.org/issue27156

   (11) https://bugs.python.org/issue27117

   (12) https://bugs.python.org/issue24225

   (13) https://bugs.python.org/issue26673

   (14) https://bugs.python.org/issue21939

   (15) https://bugs.python.org/issue21676

   (16) https://bugs.python.org/issue18410

   (17) https://bugs.python.org/issue21703

   (18) https://bugs.python.org/issue27044

   (19) https://bugs.python.org/issue23977


File: python.info,  Node: 文档<45>,  Next: 测试<42>,  Prev: IDLE<45>,  Up: Python 3 6 0 alpha 2

1.18.64.8 文档
..............

   - bpo-16484(1): Change the default PYTHONDOCS URL to "https:", and
     fix the resulting links to use lowercase.  Patch by Sean Rodman,
     test by Kaushik Nadikuditi.

   - bpo-24136(2): Document the new PEP 448(3) unpacking syntax of 3.5.

   - bpo-22558(4): Add remaining doc links to source code for
     Python-coded modules.  Patch by Yoni Lavi.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16484

   (2) https://bugs.python.org/issue24136

   (3) https://www.python.org/dev/peps/pep-0448

   (4) https://bugs.python.org/issue22558


File: python.info,  Node: 测试<42>,  Next: Windows<42>,  Prev: 文档<45>,  Up: Python 3 6 0 alpha 2

1.18.64.9 测试
..............

   - bpo-25285(1): regrtest now uses subprocesses when the -j1 command
     line option is used: each test file runs in a fresh child process.
     Before, the -j1 option was ignored.

   - bpo-25285(2): Tools/buildbot/test.bat script now uses -j1 by
     default to run each test file in fresh child process.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25285

   (2) https://bugs.python.org/issue25285


File: python.info,  Node: Windows<42>,  Next: 构建<43>,  Prev: 测试<42>,  Up: Python 3 6 0 alpha 2

1.18.64.10 Windows
..................

   - bpo-27064(1): The py.exe launcher now defaults to Python 3.  The
     Windows launcher ‘py.exe’ no longer prefers an installed Python 2
     version over Python 3 by default when used interactively.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27064


File: python.info,  Node: 构建<43>,  Next: Windows<43>,  Prev: Windows<42>,  Up: Python 3 6 0 alpha 2

1.18.64.11 构建
...............

   - bpo-27229(1): Fix the cross-compiling pgen rule for in-tree builds.
     Patch by Xavier de Gaye.

   - bpo-26930(2): 更新OS X 10.5+（仅32位）安装程序以构建并链接OpenSSL
     1.0.2h。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27229

   (2) https://bugs.python.org/issue26930


File: python.info,  Node: Windows<43>,  Next: C API<32>,  Prev: 构建<43>,  Up: Python 3 6 0 alpha 2

1.18.64.12 Windows
..................

   - bpo-17500(1): Remove unused and outdated icons.  (See also:
     ‘https://github.com/python/pythondotorg/issues/945’)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17500


File: python.info,  Node: C API<32>,  Next: 工具/示例<28>,  Prev: Windows<43>,  Up: Python 3 6 0 alpha 2

1.18.64.13 C API
................

   - bpo-27186(1): Add the PyOS_FSPath() function (part of PEP 519(2)).

   - bpo-26282(3): PyArg_ParseTupleAndKeywords() now supports
     positional-only parameters.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27186

   (2) https://www.python.org/dev/peps/pep-0519

   (3) https://bugs.python.org/issue26282


File: python.info,  Node: 工具/示例<28>,  Prev: C API<32>,  Up: Python 3 6 0 alpha 2

1.18.64.14 工具/示例
....................

   - bpo-26282(1): Argument Clinic now supports positional-only and
     keyword parameters in the same function.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26282


File: python.info,  Node: Python 3 6 0 alpha 1,  Next: Python 3 5 5 正式版,  Prev: Python 3 6 0 alpha 2,  Up: 更新日志

1.18.65 Python 3.6.0 alpha 1
----------------------------

`发布日期: 2016-05-16'

* Menu:

* 核心与内置: 核心与内置<56>.
* 库: 库<61>.
* 安全: 安全<33>.
* 库: 库<62>.
* 安全: 安全<34>.
* 库: 库<63>.
* 安全: 安全<35>.
* 库: 库<64>.
* IDLE: IDLE<46>.
* 文档: 文档<46>.
* 测试: 测试<43>.
* 构建: 构建<44>.
* Windows: Windows<44>.
* 工具/示例: 工具/示例<29>.
* C API: C API<33>.


File: python.info,  Node: 核心与内置<56>,  Next: 库<61>,  Up: Python 3 6 0 alpha 1

1.18.65.1 核心与内置
....................

   - bpo-20041(1): Fixed TypeError when frame.f_trace is set to None.
     Patch by Xavier de Gaye.

   - bpo-26168(2): Fixed possible refleaks in failing Py_BuildValue()
     with the "N" format unit.

   - bpo-26991(3): Fix possible refleak when creating a function with
     annotations.

   - bpo-27039(4): Fixed bytearray.remove() for values greater than 127.
     Based on patch by Joe Jevnik.

   - bpo-23640(5): int.from_bytes() no longer bypasses constructors for
     subclasses.

   - bpo-27005(6): Optimized the float.fromhex() class method for exact
     float.  It is now 2 times faster.

   - bpo-18531(7): Single var-keyword argument of dict subtype was
     passed unscathed to the C-defined function.  Now it is converted to
     exact dict.

   - bpo-26811(8): gc.get_objects() no longer contains a broken tuple
     with NULL pointer.

   - bpo-20120(9): Use RawConfigParser for .pypirc parsing, removing
     support for interpolation unintentionally added with move to Python
     3.  Behavior no longer does any interpolation in .pypirc files,
     matching behavior in Python 2.7 and Setuptools 19.0.

   - bpo-26249(10): Memory functions of the *note PyMem_Malloc(): 50d.
     domain (*note PYMEM_DOMAIN_MEM: 511.) now use the *note pymalloc
     allocator: 5ca. rather than system ‘malloc()’.  Applications
     calling *note PyMem_Malloc(): 50d. without holding the GIL can now
     crash: use ‘PYTHONMALLOC=debug’ environment variable to validate
     the usage of memory allocators in your application.

   - bpo-26802(11): Optimize function calls only using unpacking like
     ‘func(*tuple)’ (no other positional argument, no keyword): avoid
     copying the tuple.  Patch written by Joe Jevnik.

   - bpo-26659(12): Make the builtin slice type support cycle
     collection.

   - bpo-26718(13): super.__init__ no longer leaks memory if called
     multiple times.  NOTE: A direct call of super.__init__ is not
     endorsed!

   - bpo-27138(14): Fix the doc comment for FileFinder.find_spec().

   - bpo-27147(15): Mention PEP 420(16) in the importlib docs.

   - bpo-25339(17): PYTHONIOENCODING now has priority over locale in
     setting the error handler for stdin and stdout.

   - bpo-26494(18): Fixed crash on iterating exhausting iterators.
     Affected classes are generic sequence iterators, iterators of str,
     bytes, bytearray, list, tuple, set, frozenset, dict, OrderedDict,
     corresponding views and os.scandir() iterator.

   - bpo-26574(19): Optimize ‘bytes.replace(b'', b'.')’ and
     ‘bytearray.replace(b'', b'.')’.  Patch written by Josh Snider.

   - bpo-26581(20): If coding cookie is specified multiple times on a
     line in Python source code file, only the first one is taken to
     account.

   - bpo-19711(21): Add tests for reloading namespace packages.

   - bpo-21099(22): Switch applicable importlib tests to use PEP 451(23)
     API.

   - bpo-26563(24): Debug hooks on Python memory allocators now raise a
     fatal error if functions of the *note PyMem_Malloc(): 50d. family
     are called without holding the GIL.

   - bpo-26564(25): On error, the debug hooks on Python memory
     allocators now use the *note tracemalloc: 115. module to get the
     traceback where a memory block was allocated.

   - bpo-26558(26): The debug hooks on Python memory allocator *note
     PyObject_Malloc(): 510. now detect when functions are called
     without holding the GIL.

   - bpo-26516(27): Add *note PYTHONMALLOC: 50b. environment variable to
     set the Python memory allocators and/or install debug hooks.

   - bpo-26516(28): The *note PyMem_SetupDebugHooks(): 512. function can
     now also be used on Python compiled in release mode.

   - bpo-26516(29): The *note PYTHONMALLOCSTATS: 1172. environment
     variable can now also be used on Python compiled in release mode.
     It now has no effect if set to an empty string.

   - bpo-26516(30): In debug mode, debug hooks are now also installed on
     Python memory allocators when Python is configured without
     pymalloc.

   - bpo-26464(31): Fix str.translate() when string is ASCII and first
     replacements removes character, but next replacement uses a
     non-ASCII character or a string longer than 1 character.
     Regression introduced in Python 3.5.0.

   - bpo-22836(32): Ensure exception reports from PyErr_Display() and
     PyErr_WriteUnraisable() are sensible even when formatting them
     produces secondary errors.  This affects the reports produced by
     sys.__excepthook__() and when __del__() raises an exception.

   - bpo-26302(33): Correct behavior to reject comma as a legal
     character for cookie names.

   - bpo-26136(34): Upgrade the warning when a generator raises
     StopIteration from PendingDeprecationWarning to DeprecationWarning.
     Patch by Anish Shah.

   - bpo-26204(35): The compiler now ignores all constant statements:
     bytes, str, int, float, complex, name constants (None, False,
     True), Ellipsis and ast.Constant; not only str and int.  For
     example, ‘1.0’ is now ignored in ‘def f(): 1.0’.

   - bpo-4806(36): Avoid masking the original TypeError exception when
     using star (‘*’) unpacking in function calls.  Based on patch by
     Hagen Fürstenau and Daniel Urban.

   - bpo-26146(37): Add a new kind of AST node: ‘ast.Constant’.  It can
     be used by external AST optimizers, but the compiler does not emit
     directly such node.

   - bpo-23601(38): Sped-up allocation of dict key objects by using
     Python’s small object allocator.  (Contributed by Julian Taylor.)

   - bpo-18018(39): Import raises ImportError instead of SystemError if
     a relative import is attempted without a known parent package.

   - bpo-25843(40): When compiling code, don’t merge constants if they
     are equal but have a different types.  For example, ‘f1, f2 =
     lambda: 1, lambda: 1.0’ is now correctly compiled to two different
     functions: ‘f1()’ returns ‘1’ (‘int’) and ‘f2()’ returns ‘1.0’
     (‘float’), even if ‘1’ and ‘1.0’ are equal.

   - bpo-26107(41): The format of the ‘co_lnotab’ attribute of code
     objects changes to support negative line number delta.

   - bpo-26154(42): Add a new private _PyThreadState_UncheckedGet()
     function to get the current Python thread state, but don’t issue a
     fatal error if it is NULL. This new function must be used instead
     of accessing directly the _PyThreadState_Current variable.  The
     variable is no more exposed since Python 3.5.1 to hide the exact
     implementation of atomic C types, to avoid compiler issues.

   - bpo-25791(43): If __package__ != __spec__.parent or if neither
     __package__ or __spec__ are defined then ImportWarning is raised.

   - bpo-22995(44): [UPDATE] Comment out the one of the pickleability
     tests in _PyObject_GetState() due to regressions observed in
     Cython-based projects.

   - bpo-25961(45): Disallowed null characters in the type name.

   - bpo-25973(46): Fix segfault when an invalid nonlocal statement
     binds a name starting with two underscores.

   - bpo-22995(47): Instances of extension types with a state that
     aren’t subclasses of list or dict and haven’t implemented any
     pickle-related methods (__reduce__, __reduce_ex__, __getnewargs__,
     __getnewargs_ex__, or __getstate__), can no longer be pickled.
     Including memoryview.

   - bpo-20440(48): Massive replacing unsafe attribute setting code with
     special macro Py_SETREF.

   - bpo-25766(49): Special method __bytes__() now works in str
     subclasses.

   - bpo-25421(50): __sizeof__ methods of builtin types now use dynamic
     basic size.  This allows sys.getsize() to work correctly with their
     subclasses with __slots__ defined.

   - bpo-25709(51): Fixed problem with in-place string concatenation and
     utf-8 cache.

   - bpo-5319(52): New Py_FinalizeEx() API allowing Python to set an
     exit status of 120 on failure to flush buffered streams.

   - bpo-25485(53): telnetlib.Telnet is now a context manager.

   - bpo-24097(54): Fixed crash in object.__reduce__() if slot name is
     freed inside __getattr__.

   - bpo-24731(55): Fixed crash on converting objects with special
     methods __bytes__, __trunc__, and __float__ returning instances of
     subclasses of bytes, int, and float to subclasses of bytes, int,
     and float correspondingly.

   - bpo-25630(56): Fix a possible segfault during argument parsing in
     functions that accept filesystem paths.

   - bpo-23564(57): Fixed a partially broken sanity check in the
     _posixsubprocess internals regarding how fds_to_pass were passed to
     the child.  The bug had no actual impact as subprocess.py already
     avoided it.

   - bpo-25388(58): Fixed tokenizer crash when processing undecodable
     source code with a null byte.

   - bpo-25462(59): The hash of the key now is calculated only once in
     most operations in C implementation of OrderedDict.

   - bpo-22995(60): Default implementation of __reduce__ and
     __reduce_ex__ now rejects builtin types with not defined __new__.

   - bpo-24802(61): Avoid buffer overreads when int(), float(),
     compile(), exec() and eval() are passed bytes-like objects.  These
     objects are not necessarily terminated by a null byte, but the
     functions assumed they were.

   - bpo-25555(62): Fix parser and AST: fill lineno and col_offset of
     "arg" node when compiling AST from Python objects.

   - bpo-24726(63): Fixed a crash and leaking NULL in repr() of
     OrderedDict that was mutated by direct calls of dict methods.

   - bpo-25449(64): Iterating OrderedDict with keys with unstable hash
     now raises KeyError in C implementations as well as in Python
     implementation.

   - bpo-25395(65): Fixed crash when highly nested OrderedDict
     structures were garbage collected.

   - bpo-25401(66): Optimize bytes.fromhex() and bytearray.fromhex():
     they are now between 2x and 3.5x faster.

   - bpo-25399(67): Optimize bytearray % args using the new private
     _PyBytesWriter API. Formatting is now between 2.5 and 5 times
     faster.

   - bpo-25274(68): sys.setrecursionlimit() now raises a RecursionError
     if the new recursion limit is too low depending at the current
     recursion depth.  Modify also the "lower-water mark" formula to
     make it monotonic.  This mark is used to decide when the overflowed
     flag of the thread state is reset.

   - bpo-24402(69): Fix input() to prompt to the redirected stdout when
     sys.stdout.fileno() fails.

   - bpo-25349(70): Optimize bytes % args using the new private
     _PyBytesWriter API. Formatting is now up to 2 times faster.

   - bpo-24806(71): Prevent builtin types that are not allowed to be
     subclassed from being subclassed through multiple inheritance.

   - bpo-25301(72): The UTF-8 decoder is now up to 15 times as fast for
     error handlers: ‘ignore’, ‘replace’ and ‘surrogateescape’.

   - bpo-24848(73): Fixed a number of bugs in UTF-7 decoding of
     misformed data.

   - bpo-25267(74): The UTF-8 encoder is now up to 75 times as fast for
     error handlers: ‘ignore’, ‘replace’, ‘surrogateescape’,
     ‘surrogatepass’.  Patch co-written with Serhiy Storchaka.

   - bpo-25280(75): Import trace messages emitted in verbose (-v) mode
     are no longer formatted twice.

   - bpo-25227(76): Optimize ASCII and latin1 encoders with the
     ‘surrogateescape’ error handler: the encoders are now up to 3 times
     as fast.  Initial patch written by Serhiy Storchaka.

   - bpo-25003(77): On Solaris 11.3 or newer, os.urandom() now uses the
     getrandom() function instead of the getentropy() function.  The
     getentropy() function is blocking to generate very good quality
     entropy, os.urandom() doesn’t need such high-quality entropy.

   - bpo-9232(78): Modify Python’s grammar to allow trailing commas in
     the argument list of a function declaration.  For example, "def
     f(*, a = 3,): pass" is now legal.  Patch from Mark Dickinson.

   - bpo-24965(79): Implement PEP 498(80) "Literal String
     Interpolation".  This allows you to embed expressions inside
     f-strings, which are converted to normal strings at run time.
     Given x=3, then f’value={x}’ == ’value=3’.  Patch by Eric V. Smith.

   - bpo-26478(81): Fix semantic bugs when using binary operators with
     dictionary views and tuples.

   - bpo-26171(82): Fix possible integer overflow and heap corruption in
     zipimporter.get_data().

   - bpo-25660(83): Fix TAB key behaviour in REPL with readline.

   - bpo-26288(84): Optimize PyLong_AsDouble.

   - bpo-26289(85): Optimize floor and modulo division for single-digit
     longs.  Microbenchmarks show 2-2.5x improvement.  Built-in ’divmod’
     function is now also ~10% faster.  (See also: bpo-26315(86))

   - bpo-25887(87): Raise a RuntimeError when a coroutine object is
     awaited more than once.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20041

   (2) https://bugs.python.org/issue26168

   (3) https://bugs.python.org/issue26991

   (4) https://bugs.python.org/issue27039

   (5) https://bugs.python.org/issue23640

   (6) https://bugs.python.org/issue27005

   (7) https://bugs.python.org/issue18531

   (8) https://bugs.python.org/issue26811

   (9) https://bugs.python.org/issue20120

   (10) https://bugs.python.org/issue26249

   (11) https://bugs.python.org/issue26802

   (12) https://bugs.python.org/issue26659

   (13) https://bugs.python.org/issue26718

   (14) https://bugs.python.org/issue27138

   (15) https://bugs.python.org/issue27147

   (16) https://www.python.org/dev/peps/pep-0420

   (17) https://bugs.python.org/issue25339

   (18) https://bugs.python.org/issue26494

   (19) https://bugs.python.org/issue26574

   (20) https://bugs.python.org/issue26581

   (21) https://bugs.python.org/issue19711

   (22) https://bugs.python.org/issue21099

   (23) https://www.python.org/dev/peps/pep-0451

   (24) https://bugs.python.org/issue26563

   (25) https://bugs.python.org/issue26564

   (26) https://bugs.python.org/issue26558

   (27) https://bugs.python.org/issue26516

   (28) https://bugs.python.org/issue26516

   (29) https://bugs.python.org/issue26516

   (30) https://bugs.python.org/issue26516

   (31) https://bugs.python.org/issue26464

   (32) https://bugs.python.org/issue22836

   (33) https://bugs.python.org/issue26302

   (34) https://bugs.python.org/issue26136

   (35) https://bugs.python.org/issue26204

   (36) https://bugs.python.org/issue4806

   (37) https://bugs.python.org/issue26146

   (38) https://bugs.python.org/issue23601

   (39) https://bugs.python.org/issue18018

   (40) https://bugs.python.org/issue25843

   (41) https://bugs.python.org/issue26107

   (42) https://bugs.python.org/issue26154

   (43) https://bugs.python.org/issue25791

   (44) https://bugs.python.org/issue22995

   (45) https://bugs.python.org/issue25961

   (46) https://bugs.python.org/issue25973

   (47) https://bugs.python.org/issue22995

   (48) https://bugs.python.org/issue20440

   (49) https://bugs.python.org/issue25766

   (50) https://bugs.python.org/issue25421

   (51) https://bugs.python.org/issue25709

   (52) https://bugs.python.org/issue5319

   (53) https://bugs.python.org/issue25485

   (54) https://bugs.python.org/issue24097

   (55) https://bugs.python.org/issue24731

   (56) https://bugs.python.org/issue25630

   (57) https://bugs.python.org/issue23564

   (58) https://bugs.python.org/issue25388

   (59) https://bugs.python.org/issue25462

   (60) https://bugs.python.org/issue22995

   (61) https://bugs.python.org/issue24802

   (62) https://bugs.python.org/issue25555

   (63) https://bugs.python.org/issue24726

   (64) https://bugs.python.org/issue25449

   (65) https://bugs.python.org/issue25395

   (66) https://bugs.python.org/issue25401

   (67) https://bugs.python.org/issue25399

   (68) https://bugs.python.org/issue25274

   (69) https://bugs.python.org/issue24402

   (70) https://bugs.python.org/issue25349

   (71) https://bugs.python.org/issue24806

   (72) https://bugs.python.org/issue25301

   (73) https://bugs.python.org/issue24848

   (74) https://bugs.python.org/issue25267

   (75) https://bugs.python.org/issue25280

   (76) https://bugs.python.org/issue25227

   (77) https://bugs.python.org/issue25003

   (78) https://bugs.python.org/issue9232

   (79) https://bugs.python.org/issue24965

   (80) https://www.python.org/dev/peps/pep-0498

   (81) https://bugs.python.org/issue26478

   (82) https://bugs.python.org/issue26171

   (83) https://bugs.python.org/issue25660

   (84) https://bugs.python.org/issue26288

   (85) https://bugs.python.org/issue26289

   (86) https://bugs.python.org/issue26315

   (87) https://bugs.python.org/issue25887


File: python.info,  Node: 库<61>,  Next: 安全<33>,  Prev: 核心与内置<56>,  Up: Python 3 6 0 alpha 1

1.18.65.2 库
............

   - bpo-27057(1): Fix os.set_inheritable() on Android, ioctl() is
     blocked by SELinux and fails with EACCESS. The function now falls
     back to fcntl().  Patch written by Michał Bednarski.

   - bpo-27014(2): Fix infinite recursion using typing.py.  Thanks to
     Kalle Tuure!

   - bpo-27031(3): Removed dummy methods in Tkinter widget classes:
     tk_menuBar() and tk_bindForTraversal().

   - bpo-14132(4): Fix urllib.request redirect handling when the target
     only has a query string.  Original fix by Ján Janech.

   - bpo-17214(5): The "urllib.request" module now percent-encodes
     non-ASCII bytes found in redirect target URLs.  Some servers send
     Location header fields with non-ASCII bytes, but "http.client"
     requires the request target to be ASCII-encodable, otherwise a
     UnicodeEncodeError is raised.  Based on patch by Christian Heimes.

   - bpo-27033(6): The default value of the decode_data parameter for
     smtpd.SMTPChannel and smtpd.SMTPServer constructors is changed to
     False.

   - bpo-27034(7): Removed deprecated class asynchat.fifo.

   - bpo-26870(8): Added readline.set_auto_history(), which can stop
     entries being automatically added to the history list.  Based on
     patch by Tyler Crompton.

   - bpo-26039(9): zipfile.ZipFile.open() can now be used to write data
     into a ZIP file, as well as for extracting data.  Patch by Thomas
     Kluyver.

   - bpo-26892(10): Honor debuglevel flag in urllib.request.HTTPHandler.
     Patch contributed by Chi Hsuan Yen.

   - bpo-22274(11): In the subprocess module, allow stderr to be
     redirected to stdout even when stdout is not redirected.  Patch by
     Akira Li.

   - bpo-26807(12): mock_open ’files’ no longer error on readline at end
     of file.  Patch from Yolanda Robla.

   - bpo-25745(13): Fixed leaking a userptr in curses panel destructor.

   - bpo-26977(14): Removed unnecessary, and ignored, call to sum of
     squares helper in statistics.pvariance.

   - bpo-26002(15): Use bisect in statistics.median instead of a linear
     search.  Patch by Upendra Kuma.

   - bpo-25974(16): Make use of new Decimal.as_integer_ratio() method in
     statistics module.  Patch by Stefan Krah.

   - bpo-26996(17): Add secrets module as described in PEP 506(18).

   - bpo-26881(19): The modulefinder module now supports extended opcode
     arguments.

   - bpo-23815(20): Fixed crashes related to directly created instances
     of types in _tkinter and curses.panel modules.

   - bpo-17765(21): weakref.ref() no longer silently ignores keyword
     arguments.  Patch by Georg Brandl.

   - bpo-26873(22): xmlrpc now raises ResponseError on unsupported type
     tags instead of silently return incorrect result.

   - bpo-26915(23): The __contains__ methods in the collections ABCs now
     check for identity before checking equality.  This better matches
     the behavior of the concrete classes, allows sensible handling of
     NaNs, and makes it easier to reason about container invariants.

   - bpo-26711(24): Fixed the comparison of plistlib.Data with other
     types.

   - bpo-24114(25): Fix an uninitialized variable in ‘ctypes.util’.  The
     bug only occurs on SunOS when the ctypes implementation searches
     for the ‘crle’ program.  Patch by Xiang Zhang.  Tested on SunOS by
     Kees Bos.

   - bpo-26864(26): In urllib.request, change the proxy bypass host
     checking against no_proxy to be case-insensitive, and to not match
     unrelated host names that happen to have a bypassed hostname as a
     suffix.  Patch by Xiang Zhang.

   - bpo-24902(27): Print server URL on http.server startup.  Initial
     patch by Felix Kaiser.

   - bpo-25788(28): fileinput.hook_encoded() now supports an "errors"
     argument for passing to open.  Original patch by Joseph Hackman.

   - bpo-26634(29): recursive_repr() now sets __qualname__ of wrapper.
     Patch by Xiang Zhang.

   - bpo-26804(30): urllib.request will prefer lower_case proxy
     environment variables over UPPER_CASE or Mixed_Case ones.  Patch
     contributed by Hans-Peter Jansen.

   - bpo-26837(31): assertSequenceEqual() now correctly outputs
     non-stringified differing items (like bytes in the -b mode).  This
     affects assertListEqual() and assertTupleEqual().

   - bpo-26041(32): Remove "will be removed in Python 3.7" from
     deprecation messages of platform.dist() and
     platform.linux_distribution().  Patch by Kumaripaba Miyurusara
     Athukorala.

   - bpo-26822(33): itemgetter, attrgetter and methodcaller objects no
     longer silently ignore keyword arguments.

   - bpo-26733(34): Disassembling a class now disassembles class and
     static methods.  Patch by Xiang Zhang.

   - bpo-26801(35): Fix error handling in *note
     shutil.get_terminal_size(): a52, catch *note AttributeError: 3a3.
     instead of *note NameError: d83.  Patch written by Emanuel Barry.

   - bpo-24838(36): tarfile’s ustar and gnu formats now correctly
     calculate name and link field limits for multibyte character
     encodings like utf-8.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27057

   (2) https://bugs.python.org/issue27014

   (3) https://bugs.python.org/issue27031

   (4) https://bugs.python.org/issue14132

   (5) https://bugs.python.org/issue17214

   (6) https://bugs.python.org/issue27033

   (7) https://bugs.python.org/issue27034

   (8) https://bugs.python.org/issue26870

   (9) https://bugs.python.org/issue26039

   (10) https://bugs.python.org/issue26892

   (11) https://bugs.python.org/issue22274

   (12) https://bugs.python.org/issue26807

   (13) https://bugs.python.org/issue25745

   (14) https://bugs.python.org/issue26977

   (15) https://bugs.python.org/issue26002

   (16) https://bugs.python.org/issue25974

   (17) https://bugs.python.org/issue26996

   (18) https://www.python.org/dev/peps/pep-0506

   (19) https://bugs.python.org/issue26881

   (20) https://bugs.python.org/issue23815

   (21) https://bugs.python.org/issue17765

   (22) https://bugs.python.org/issue26873

   (23) https://bugs.python.org/issue26915

   (24) https://bugs.python.org/issue26711

   (25) https://bugs.python.org/issue24114

   (26) https://bugs.python.org/issue26864

   (27) https://bugs.python.org/issue24902

   (28) https://bugs.python.org/issue25788

   (29) https://bugs.python.org/issue26634

   (30) https://bugs.python.org/issue26804

   (31) https://bugs.python.org/issue26837

   (32) https://bugs.python.org/issue26041

   (33) https://bugs.python.org/issue26822

   (34) https://bugs.python.org/issue26733

   (35) https://bugs.python.org/issue26801

   (36) https://bugs.python.org/issue24838


File: python.info,  Node: 安全<33>,  Next: 库<62>,  Prev: 库<61>,  Up: Python 3 6 0 alpha 1

1.18.65.3 安全
..............

   - bpo-26657(1): Fix directory traversal vulnerability with
     http.server on Windows.  This fixes a regression that was
     introduced in 3.3.4rc1 and 3.4.0rc1.  Based on patch by Philipp
     Hagemeister.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26657


File: python.info,  Node: 库<62>,  Next: 安全<34>,  Prev: 安全<33>,  Up: Python 3 6 0 alpha 1

1.18.65.4 库
............

   - bpo-26717(1): Stop encoding Latin-1-ized WSGI paths with UTF-8.
     Patch by Anthony Sottile.

   - bpo-26782(2): Add STARTUPINFO to subprocess.__all__ on Windows.

   - bpo-26404(3): Add context manager to socketserver.  Patch by Aviv
     Palivoda.

   - bpo-26735(4): Fix *note os.urandom(): 4d9. on Solaris 11.3 and
     newer when reading more than 1,024 bytes: call ‘getrandom()’
     multiple times with a limit of 1024 bytes per call.

   - bpo-26585(5): Eliminate http.server._quote_html() and use
     html.escape(quote=False).  Patch by Xiang Zhang.

   - bpo-26685(6): Raise OSError if closing a socket fails.

   - bpo-16329(7): Add .webm to mimetypes.types_map.  Patch by Giampaolo
     Rodola’.

   - bpo-13952(8): Add .csv to mimetypes.types_map.  Patch by Geoff
     Wilson.

   - bpo-26587(9): the site module now allows .pth files to specify
     files to be added to sys.path (e.g.  zip files).

   - bpo-25609(10): Introduce contextlib.AbstractContextManager and
     typing.ContextManager.

   - bpo-26709(11): Fixed Y2038 problem in loading binary PLists.

   - bpo-23735(12): Handle terminal resizing with Readline 6.3+ by
     installing our own SIGWINCH handler.  Patch by Eric Price.

   - bpo-25951(13): Change SSLSocket.sendall() to return None, as
     explicitly documented for plain socket objects.  Patch by Aviv
     Palivoda.

   - bpo-26586(14): In http.server, respond with "413 Request header
     fields too large" if there are too many header fields to parse,
     rather than killing the connection and raising an unhandled
     exception.  Patch by Xiang Zhang.

   - bpo-26676(15): Added missing XMLPullParser to ElementTree.__all__.

   - bpo-22854(16): Change BufferedReader.writable() and
     BufferedWriter.readable() to always return False.

   - bpo-26492(17): Exhausted iterator of array.array now conforms with
     the behavior of iterators of other mutable sequences: it lefts
     exhausted even if iterated array is extended.

   - bpo-26641(18): doctest.DocFileTest and doctest.testfile() now
     support packages (module splitted into multiple directories) for
     the package parameter.

   - bpo-25195(19): Fix a regression in mock.MagicMock.  _Call is a
     subclass of tuple (changeset 3603bae63c13 only works for classes)
     so we need to implement __ne__ ourselves.  Patch by Andrew Plummer.

   - bpo-26644(20): Raise ValueError rather than SystemError when a
     negative length is passed to SSLSocket.recv() or read().

   - bpo-23804(21): Fix SSL recv(0) and read(0) methods to return zero
     bytes instead of up to 1024.

   - bpo-26616(22): Fixed a bug in datetime.astimezone() method.

   - bpo-26637(23): The *note importlib: 9b. module now emits an *note
     ImportError: 33d. rather than a *note TypeError: 193. if *note
     __import__(): 619. is tried during the Python shutdown process but
     *note sys.path: 490. is already cleared (set to ‘None’).

   - bpo-21925(24): *note warnings.formatwarning(): 1002. now catches
     exceptions when calling *note linecache.getline(): 712. and *note
     tracemalloc.get_object_traceback(): 1176. to be able to log *note
     ResourceWarning: 4d8. emitted late during the Python shutdown
     process.

   - bpo-23848(25): On Windows, faulthandler.enable() now also installs
     an exception handler to dump the traceback of all Python threads on
     any Windows exception, not only on UNIX signals (SIGSEGV, SIGFPE,
     SIGABRT).

   - bpo-26530(26): Add C functions ‘_PyTraceMalloc_Track()’ and
     ‘_PyTraceMalloc_Untrack()’ to track memory blocks using the *note
     tracemalloc: 115. module.  Add ‘_PyTraceMalloc_GetTraceback()’ to
     get the traceback of an object.

   - bpo-26588(27): The _tracemalloc now supports tracing memory
     allocations of multiple address spaces (domains).

   - bpo-24266(28): Ctrl+C during Readline history search now cancels
     the search mode when compiled with Readline 7.

   - bpo-26590(29): Implement a safe finalizer for the _socket.socket
     type.  It now releases the GIL to close the socket.

   - bpo-18787(30): spwd.getspnam() now raises a PermissionError if the
     user doesn’t have privileges.

   - bpo-26560(31): Avoid potential ValueError in
     BaseHandler.start_response.  Initial patch by Peter Inglesby.

   - bpo-26567(32): Add a new function *note PyErr_ResourceWarning():
     5d5. function to pass the destroyed object.  Add a `source'
     attribute to ‘warnings.WarningMessage’.  Add
     warnings._showwarnmsg() which uses tracemalloc to get the traceback
     where source object was allocated.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26717

   (2) https://bugs.python.org/issue26782

   (3) https://bugs.python.org/issue26404

   (4) https://bugs.python.org/issue26735

   (5) https://bugs.python.org/issue26585

   (6) https://bugs.python.org/issue26685

   (7) https://bugs.python.org/issue16329

   (8) https://bugs.python.org/issue13952

   (9) https://bugs.python.org/issue26587

   (10) https://bugs.python.org/issue25609

   (11) https://bugs.python.org/issue26709

   (12) https://bugs.python.org/issue23735

   (13) https://bugs.python.org/issue25951

   (14) https://bugs.python.org/issue26586

   (15) https://bugs.python.org/issue26676

   (16) https://bugs.python.org/issue22854

   (17) https://bugs.python.org/issue26492

   (18) https://bugs.python.org/issue26641

   (19) https://bugs.python.org/issue25195

   (20) https://bugs.python.org/issue26644

   (21) https://bugs.python.org/issue23804

   (22) https://bugs.python.org/issue26616

   (23) https://bugs.python.org/issue26637

   (24) https://bugs.python.org/issue21925

   (25) https://bugs.python.org/issue23848

   (26) https://bugs.python.org/issue26530

   (27) https://bugs.python.org/issue26588

   (28) https://bugs.python.org/issue24266

   (29) https://bugs.python.org/issue26590

   (30) https://bugs.python.org/issue18787

   (31) https://bugs.python.org/issue26560

   (32) https://bugs.python.org/issue26567


File: python.info,  Node: 安全<34>,  Next: 库<63>,  Prev: 库<62>,  Up: Python 3 6 0 alpha 1

1.18.65.5 安全
..............

   - bpo-26313(1): ssl.py _load_windows_store_certs fails if windows
     cert store is empty.  Patch by Baji.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26313


File: python.info,  Node: 库<63>,  Next: 安全<35>,  Prev: 安全<34>,  Up: Python 3 6 0 alpha 1

1.18.65.6 库
............

   - bpo-26569(1): Fix *note pyclbr.readmodule(): 1179. and *note
     pyclbr.readmodule_ex(): 117a. to support importing packages.

   - bpo-26499(2): Account for remaining Content-Length in
     HTTPResponse.readline() and read1().  Based on patch by Silent
     Ghost.  Also document that HTTPResponse now supports these methods.

   - bpo-25320(3): Handle sockets in directories unittest discovery is
     scanning.  Patch from Victor van den Elzen.

   - bpo-16181(4): cookiejar.http2time() now returns None if year is
     higher than datetime.MAXYEAR.

   - bpo-26513(5): Fixes platform module detection of Windows Server

   - bpo-23718(6): Fixed parsing time in week 0 before Jan 1.  Original
     patch by Tamás Bence Gedai.

   - bpo-26323(7): Add Mock.assert_called() and
     Mock.assert_called_once() methods to unittest.mock.  Patch written
     by Amit Saha.

   - bpo-20589(8): Invoking Path.owner() and Path.group() on Windows now
     raise NotImplementedError instead of ImportError.

   - bpo-26177(9): Fixed the keys() method for Canvas and Scrollbar
     widgets.

   - bpo-15068(10): Got rid of excessive buffering in fileinput.  The
     bufsize parameter is now deprecated and ignored.

   - bpo-19475(11): Added an optional argument timespec to the datetime
     isoformat() method to choose the precision of the time component.

   - bpo-2202(12): Fix UnboundLocalError in
     AbstractDigestAuthHandler.get_algorithm_impls.  Initial patch by
     Mathieu Dupuy.

   - bpo-26167(13): Minimized overhead in copy.copy() and
     copy.deepcopy().  Optimized copying and deepcopying bytearrays,
     NotImplemented, slices, short lists, tuples, dicts, sets.

   - bpo-25718(14): Fixed pickling and copying the accumulate() iterator
     with total is None.

   - bpo-26475(15): Fixed debugging output for regular expressions with
     the (?x) flag.

   - bpo-26482(16): Allowed pickling recursive dequeues.

   - bpo-26335(17): Make mmap.write() return the number of bytes written
     like other write methods.  Patch by Jakub Stasiak.

   - bpo-26457(18): Fixed the subnets() methods in IP network classes
     for the case when resulting prefix length is equal to maximal
     prefix length.  Based on patch by Xiang Zhang.

   - bpo-26385(19): Remove the file if the internal open() call in
     NamedTemporaryFile() fails.  Patch by Silent Ghost.

   - bpo-26402(20): Fix XML-RPC client to retry when the server shuts
     down a persistent connection.  This was a regression related to the
     new http.client.RemoteDisconnected exception in 3.5.0a4.

   - bpo-25913(21): Leading ‘<~’ is optional now in base64.a85decode()
     with adobe=True.  Patch by Swati Jaiswal.

   - bpo-26186(22): Remove an invalid type check in
     importlib.util.LazyLoader.

   - bpo-26367(23): importlib.__import__() raises ImportError like
     builtins.__import__() when ‘level’ is specified but without an
     accompanying package specified.

   - bpo-26309(24): In the "socketserver" module, shut down the request
     (closing the connected socket) when verify_request() returns false.
     Patch by Aviv Palivoda.

   - bpo-23430(25): Change the socketserver module to only catch
     exceptions raised from a request handler that are derived from
     Exception (instead of BaseException).  Therefore SystemExit and
     KeyboardInterrupt no longer trigger the handle_error() method, and
     will now to stop a single-threaded server.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26569

   (2) https://bugs.python.org/issue26499

   (3) https://bugs.python.org/issue25320

   (4) https://bugs.python.org/issue16181

   (5) https://bugs.python.org/issue26513

   (6) https://bugs.python.org/issue23718

   (7) https://bugs.python.org/issue26323

   (8) https://bugs.python.org/issue20589

   (9) https://bugs.python.org/issue26177

   (10) https://bugs.python.org/issue15068

   (11) https://bugs.python.org/issue19475

   (12) https://bugs.python.org/issue2202

   (13) https://bugs.python.org/issue26167

   (14) https://bugs.python.org/issue25718

   (15) https://bugs.python.org/issue26475

   (16) https://bugs.python.org/issue26482

   (17) https://bugs.python.org/issue26335

   (18) https://bugs.python.org/issue26457

   (19) https://bugs.python.org/issue26385

   (20) https://bugs.python.org/issue26402

   (21) https://bugs.python.org/issue25913

   (22) https://bugs.python.org/issue26186

   (23) https://bugs.python.org/issue26367

   (24) https://bugs.python.org/issue26309

   (25) https://bugs.python.org/issue23430


File: python.info,  Node: 安全<35>,  Next: 库<64>,  Prev: 库<63>,  Up: Python 3 6 0 alpha 1

1.18.65.7 安全
..............

   - bpo-25939(1): On Windows open the cert store readonly in
     ssl.enum_certificates.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25939


File: python.info,  Node: 库<64>,  Next: IDLE<46>,  Prev: 安全<35>,  Up: Python 3 6 0 alpha 1

1.18.65.8 库
............

   - bpo-25995(1): os.walk() no longer uses FDs proportional to the tree
     depth.

   - bpo-25994(2): Added the close() method and the support of the
     context manager protocol for the os.scandir() iterator.

   - bpo-23992(3): multiprocessing: make MapResult not fail-fast upon
     exception.

   - bpo-26243(4): Support keyword arguments to zlib.compress().  Patch
     by Aviv Palivoda.

   - bpo-26117(5): The os.scandir() iterator now closes file descriptor
     not only when the iteration is finished, but when it was failed
     with error.

   - bpo-25949(6): __dict__ for an OrderedDict instance is now created
     only when needed.

   - bpo-25911(7): Restored support of bytes paths in os.walk() on
     Windows.

   - bpo-26045(8): Add UTF-8 suggestion to error message when posting a
     non-Latin-1 string with http.client.

   - bpo-26039(9): Added zipfile.ZipInfo.from_file() and
     zipinfo.ZipInfo.is_dir().  Patch by Thomas Kluyver.

   - bpo-12923(10): Reset FancyURLopener’s redirect counter even if
     there is an exception.  Based on patches by Brian Brazil and Daniel
     Rocco.

   - bpo-25945(11): Fixed a crash when unpickle the functools.partial
     object with wrong state.  Fixed a leak in failed functools.partial
     constructor.  "args" and "keywords" attributes of functools.partial
     have now always types tuple and dict correspondingly.

   - bpo-26202(12): copy.deepcopy() now correctly copies range() objects
     with non-atomic attributes.

   - bpo-23076(13): Path.glob() now raises a ValueError if it’s called
     with an invalid pattern.  Patch by Thomas Nyberg.

   - bpo-19883(14): Fixed possible integer overflows in zipimport.

   - bpo-26227(15): On Windows, getnameinfo(), gethostbyaddr() and
     gethostbyname_ex() functions of the socket module now decode the
     hostname from the ANSI code page rather than UTF-8.

   - bpo-26099(16): The site module now writes an error into stderr if
     sitecustomize module can be imported but executing the module raise
     an ImportError.  Same change for usercustomize.

   - bpo-26147(17): xmlrpc now works with strings not encodable with
     used non-UTF-8 encoding.

   - bpo-25935(18): Garbage collector now breaks reference loops with
     OrderedDict.

   - bpo-16620(19): Fixed AttributeError in msilib.Directory.glob().

   - bpo-26013(20): Added compatibility with broken protocol 2 pickles
     created in old Python 3 versions (3.4.3 and lower).

   - bpo-26129(21): Deprecated accepting non-integers in grp.getgrgid().

   - bpo-25850(22): Use cross-compilation by default for 64-bit Windows.

   - bpo-25822(23): Add docstrings to the fields of urllib.parse
     results.  Patch contributed by Swati Jaiswal.

   - bpo-22642(24): Convert trace module option parsing mechanism to
     argparse.  Patch contributed by SilentGhost.

   - bpo-24705(25): Fix sysconfig._parse_makefile not expanding ${} vars
     appearing before $() vars.

   - bpo-26069(26): Remove the deprecated apis in the trace module.

   - bpo-22138(27): Fix mock.patch behavior when patching descriptors.
     Restore original values after patching.  Patch contributed by Sean
     McCully.

   - bpo-25672(28): In the ssl module, enable the
     SSL_MODE_RELEASE_BUFFERS mode option if it is safe to do so.

   - bpo-26012(29): Don’t traverse into symlinks for ‘**’ pattern in
     pathlib.Path.[r]glob().

   - bpo-24120(30): Ignore PermissionError when traversing a tree with
     pathlib.Path.[r]glob().  Patch by Ulrich Petri.

   - bpo-21815(31): Accept ] characters in the data portion of imap
     responses, in order to handle the flags with square brackets
     accepted and produced by servers such as gmail.

   - bpo-25447(32): fileinput now uses sys.stdin as-is if it does not
     have a buffer attribute (restores backward compatibility).

   - bpo-25971(33): Optimized creating Fractions from floats by 2 times
     and from Decimals by 3 times.

   - bpo-25802(34): Document as deprecated the remaining implementations
     of importlib.abc.Loader.load_module().

   - bpo-25928(35): Add Decimal.as_integer_ratio().

   - bpo-25447(36): Copying the lru_cache() wrapper object now always
     works, independently from the type of the wrapped object (by
     returning the original object unchanged).

   - bpo-25768(37): Have the functions in compileall return booleans
     instead of ints and add proper documentation and tests for the
     return values.

   - bpo-24103(38): Fixed possible use after free in
     ElementTree.XMLPullParser.

   - bpo-25860(39): os.fwalk() no longer skips remaining directories
     when error occurs.  Original patch by Samson Lee.

   - bpo-25914(40): Fixed and simplified OrderedDict.__sizeof__.

   - bpo-25869(41): Optimized deepcopying ElementTree; it is now 20
     times faster.

   - bpo-25873(42): Optimized iterating ElementTree.  Iterating elements
     Element.iter() is now 40% faster, iterating text Element.itertext()
     is now up to 2.5 times faster.

   - bpo-25902(43): Fixed various refcount issues in ElementTree
     iteration.

   - bpo-22227(44): The TarFile iterator is reimplemented using
     generator.  This implementation is simpler that using class.

   - bpo-25638(45): Optimized ElementTree.iterparse(); it is now 2x
     faster.  Optimized ElementTree parsing; it is now 10% faster.

   - bpo-25761(46): Improved detecting errors in broken pickle data.

   - bpo-25717(47): Restore the previous behaviour of tolerating most
     fstat() errors when opening files.  This was a regression in 3.5a1,
     and stopped anonymous temporary files from working in special
     cases.

   - bpo-24903(48): Fix regression in number of arguments compileall
     accepts when ’-d’ is specified.  The check on the number of
     arguments has been dropped completely as it never worked correctly
     anyway.

   - bpo-25764(49): In the subprocess module, preserve any exception
     caused by fork() failure when preexec_fn is used.

   - bpo-25771(50): Tweak the exception message for
     importlib.util.resolve_name() when ’package’ isn’t specified but
     necessary.

   - bpo-6478(51): _strptime’s regexp cache now is reset after changing
     timezone with time.tzset().

   - bpo-14285(52): When executing a package with the "python -m
     package" option, and package initialization fails, a proper
     traceback is now reported.  The "runpy" module now lets exceptions
     from package initialization pass back to the caller, rather than
     raising ImportError.

   - bpo-19771(53): Also in runpy and the "-m" option, omit the
     irrelevant message ".  .  .  is a package and cannot be directly
     executed" if the package could not even be initialized (e.g.  due
     to a bad ‘*.pyc’ file).

   - bpo-25177(54): Fixed problem with the mean of very small and very
     large numbers.  As a side effect, statistics.mean and
     statistics.variance should be significantly faster.

   - bpo-25718(55): Fixed copying object with state with boolean value
     is false.

   - bpo-10131(56): Fixed deep copying of minidom documents.  Based on
     patch by Marian Ganisin.

   - bpo-7990(57): dir() on ElementTree.Element now lists properties:
     "tag", "text", "tail" and "attrib".  Original patch by Santoso
     Wijaya.

   - bpo-25725(58): Fixed a reference leak in pickle.loads() when
     unpickling invalid data including tuple instructions.

   - bpo-25663(59): In the Readline completer, avoid listing duplicate
     global names, and search the global namespace before searching
     builtins.

   - bpo-25688(60): Fixed file leak in ElementTree.iterparse() raising
     an error.

   - bpo-23914(61): Fixed SystemError raised by unpickler on broken
     pickle data.

   - bpo-25691(62): Fixed crash on deleting ElementTree.Element
     attributes.

   - bpo-25624(63): ZipFile now always writes a ZIP_STORED header for
     directory entries.  Patch by Dingyuan Wang.

   - bpo-25626(64): Change three zlib functions to accept sizes that fit
     in Py_ssize_t, but internally cap those sizes to UINT_MAX. This
     resolves a regression in 3.5 where GzipFile.read() failed to read
     chunks larger than 2 or 4 GiB. The change affects the
     zlib.Decompress.decompress() max_length parameter, the
     zlib.decompress() bufsize parameter, and the
     zlib.Decompress.flush() length parameter.

   - bpo-25583(65): Avoid incorrect errors raised by
     os.makedirs(exist_ok=True) when the OS gives priority to errors
     such as EACCES over EEXIST.

   - bpo-25593(66): Change semantics of EventLoop.stop() in asyncio.

   - bpo-6973(67): When we know a subprocess.Popen process has died, do
     not allow the send_signal(), terminate(), or kill() methods to do
     anything as they could potentially signal a different process.

   - bpo-23883(68): Added missing APIs to __all__ to match the
     documented APIs for the following modules: calendar, csv, enum,
     fileinput, ftplib, logging, optparse, tarfile, threading and wave.
     Also added a test.support.check__all__() helper.  Patches by Jacek
     Kołodziej, Mauro S. M. Rodrigues and Joel Taddei.

   - bpo-25590(69): In the Readline completer, only call getattr() once
     per attribute.  Also complete names of attributes such as
     properties and slots which are listed by dir() but not yet created
     on an instance.

   - bpo-25498(70): Fix a crash when garbage-collecting ctypes objects
     created by wrapping a memoryview.  This was a regression made in
     3.5a1.  Based on patch by Eryksun.

   - bpo-25584(71): Added "escape" to the __all__ list in the glob
     module.

   - bpo-25584(72): Fixed recursive glob() with patterns starting with
     ‘**’.

   - bpo-25446(73): Fix regression in smtplib’s AUTH LOGIN support.

   - bpo-18010(74): Fix the pydoc web server’s module search function to
     handle exceptions from importing packages.

   - bpo-25554(75): Got rid of circular references in regular expression
     parsing.

   - bpo-18973(76): Command-line interface of the calendar module now
     uses argparse instead of optparse.

   - bpo-25510(77): fileinput.FileInput.readline() now returns b’’
     instead of ’’ at the end if the FileInput was opened with binary
     mode.  Patch by Ryosuke Ito.

   - bpo-25503(78): Fixed inspect.getdoc() for inherited docstrings of
     properties.  Original patch by John Mark Vandenberg.

   - bpo-25515(79): Always use os.urandom as a source of randomness in
     uuid.uuid4.

   - bpo-21827(80): Fixed textwrap.dedent() for the case when largest
     common whitespace is a substring of smallest leading whitespace.
     Based on patch by Robert Li.

   - bpo-25447(81): The lru_cache() wrapper objects now can be copied
     and pickled (by returning the original object unchanged).

   - bpo-25390(82): typing: Don’t crash on Union[str, Pattern].

   - bpo-25441(83): asyncio: Raise error from drain() when socket is
     closed.

   - bpo-25410(84): Cleaned up and fixed minor bugs in C implementation
     of OrderedDict.

   - bpo-25411(85): Improved Unicode support in SMTPHandler through
     better use of the email package.  Thanks to user simon04 for the
     patch.

   - Move the imp module from a PendingDeprecationWarning to
     DeprecationWarning.

   - bpo-25407(86): Remove mentions of the formatter module being
     removed in Python 3.6.

   - bpo-25406(87): Fixed a bug in C implementation of
     OrderedDict.move_to_end() that caused segmentation fault or hang in
     iterating after moving several items to the start of ordered dict.

   - bpo-25382(88): pickletools.dis() now outputs implicit memo index
     for the MEMOIZE opcode.

   - bpo-25357(89): Add an optional newline parameter to
     binascii.b2a_base64().  base64.b64encode() uses it to avoid a
     memory copy.

   - bpo-24164(90): Objects that need calling ‘__new__’ with keyword
     arguments, can now be pickled using pickle protocols older than
     protocol version 4.

   - bpo-25364(91): zipfile now works in threads disabled builds.

   - bpo-25328(92): smtpd’s SMTPChannel now correctly raises a
     ValueError if both decode_data and enable_SMTPUTF8 are set to true.

   - bpo-16099(93): RobotFileParser now supports Crawl-delay and
     Request-rate extensions.  Patch by Nikolay Bogoychev.

   - bpo-25316(94): distutils raises OSError instead of
     DistutilsPlatformError when MSVC is not installed.

   - bpo-25380(95): Fixed protocol for the STACK_GLOBAL opcode in
     pickletools.opcodes.

   - bpo-23972(96): Updates asyncio datagram create method allowing
     reuseport and reuseaddr socket options to be set prior to binding
     the socket.  Mirroring the existing asyncio create_server method
     the reuseaddr option for datagram sockets defaults to True if the
     O/S is ’posix’ (except if the platform is Cygwin).  Patch by Chris
     Laws.

   - bpo-25304(97): Add asyncio.run_coroutine_threadsafe().  This lets
     you submit a coroutine to a loop from another thread, returning a
     concurrent.futures.Future.  By Vincent Michel.

   - bpo-25232(98): Fix CGIRequestHandler to split the query from the
     URL at the first question mark (?)  rather than the last.  Patch
     from Xiang Zhang.

   - bpo-24657(99): Prevent CGIRequestHandler from collapsing slashes in
     the query part of the URL as if it were a path.  Patch from Xiang
     Zhang.

   - bpo-25287(100): Don’t add crypt.METHOD_CRYPT to crypt.methods if
     it’s not supported.  Check if it is supported, it may not be
     supported on OpenBSD for example.

   - bpo-23600(101): Default implementation of tzinfo.fromutc() was
     returning wrong results in some cases.

   - bpo-25203(102): Failed readline.set_completer_delims() no longer
     left the module in inconsistent state.

   - bpo-25011(103): rlcompleter now omits private and special attribute
     names unless the prefix starts with underscores.

   - bpo-25209(104): rlcompleter now can add a space or a colon after
     completed keyword.

   - bpo-22241(105): timezone.utc name is now plain ’UTC’, not
     ’UTC-00:00’.

   - bpo-23517(106): fromtimestamp() and utcfromtimestamp() methods of
     datetime.datetime now round microseconds to nearest with ties going
     to nearest even integer (ROUND_HALF_EVEN), as round(float), instead
     of rounding towards -Infinity (ROUND_FLOOR).

   - bpo-23552(107): Timeit now warns when there is substantial (4x)
     variance between best and worst times.  Patch from Serhiy
     Storchaka.

   - bpo-24633(108): site-packages/README -> README.txt.

   - bpo-24879(109): help() and pydoc can now list named tuple fields in
     the order they were defined rather than alphabetically.  The
     ordering is determined by the _fields attribute if present.

   - bpo-24874(110): Improve speed of itertools.cycle() and make its
     pickle more compact.

   - Fix crash in itertools.cycle.__setstate__() when the first argument
     wasn’t a list.

   - bpo-20059(111): urllib.parse raises ValueError on all invalid
     ports.  Patch by Martin Panter.

   - bpo-24360(112): Improve __repr__ of argparse.Namespace() for
     invalid identifiers.  Patch by Matthias Bussonnier.

   - bpo-23426(113): run_setup was broken in distutils.  Patch from
     Alexander Belopolsky.

   - bpo-13938(114): 2to3 converts StringTypes to a tuple.  Patch from
     Mark Hammond.

   - bpo-2091(115): open() accepted a ’U’ mode string containing ’+’,
     but ’U’ can only be used with ’r’.  Patch from Jeff Balogh and John
     O’Connor.

   - bpo-8585(116): improved tests for zipimporter2.  Patch from Mark
     Lawrence.

   - bpo-18622(117): unittest.mock.mock_open().reset_mock would recurse
     infinitely.  Patch from Nicola Palumbo and Laurent De Buyst.

   - bpo-24426(118): Fast searching optimization in regular expressions
     now works for patterns that starts with capturing groups.  Fast
     searching optimization now can’t be disabled at compile time.

   - bpo-23661(119): unittest.mock side_effects can now be exceptions
     again.  This was a regression vs Python 3.4.  Patch from Ignacio
     Rossi

   - bpo-13248(120): Remove deprecated inspect.getmoduleinfo function.

   - bpo-25578(121): Fix (another) memory leak in
     SSLSocket.getpeercer().

   - bpo-25530(122): Disable the vulnerable SSLv3 protocol by default
     when creating ssl.SSLContext.

   - bpo-25569(123): Fix memory leak in SSLSocket.getpeercert().

   - bpo-25471(124): Sockets returned from accept() shouldn’t appear to
     be nonblocking.

   - bpo-25319(125): When threading.Event is reinitialized, the
     underlying condition should use a regular lock rather than a
     recursive lock.

   - Skip getaddrinfo if host is already resolved.  Patch by A. Jesse
     Jiryu Davis.

   - bpo-26050(126): Add asyncio.StreamReader.readuntil() method.  Patch
     by Марк Коренберг.

   - bpo-25924(127): Avoid unnecessary serialization of getaddrinfo(3)
     calls on OS X versions 10.5 or higher.  Original patch by A. Jesse
     Jiryu Davis.

   - bpo-26406(128): Avoid unnecessary serialization of getaddrinfo(3)
     calls on current versions of OpenBSD and NetBSD. Patch by A. Jesse
     Jiryu Davis.

   - bpo-26848(129): Fix asyncio/subprocess.communicate() to handle
     empty input.  Patch by Jack O’Connor.

   - bpo-27040(130): Add loop.get_exception_handler method

   - bpo-27041(131): asyncio: Add loop.create_future method

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25995

   (2) https://bugs.python.org/issue25994

   (3) https://bugs.python.org/issue23992

   (4) https://bugs.python.org/issue26243

   (5) https://bugs.python.org/issue26117

   (6) https://bugs.python.org/issue25949

   (7) https://bugs.python.org/issue25911

   (8) https://bugs.python.org/issue26045

   (9) https://bugs.python.org/issue26039

   (10) https://bugs.python.org/issue12923

   (11) https://bugs.python.org/issue25945

   (12) https://bugs.python.org/issue26202

   (13) https://bugs.python.org/issue23076

   (14) https://bugs.python.org/issue19883

   (15) https://bugs.python.org/issue26227

   (16) https://bugs.python.org/issue26099

   (17) https://bugs.python.org/issue26147

   (18) https://bugs.python.org/issue25935

   (19) https://bugs.python.org/issue16620

   (20) https://bugs.python.org/issue26013

   (21) https://bugs.python.org/issue26129

   (22) https://bugs.python.org/issue25850

   (23) https://bugs.python.org/issue25822

   (24) https://bugs.python.org/issue22642

   (25) https://bugs.python.org/issue24705

   (26) https://bugs.python.org/issue26069

   (27) https://bugs.python.org/issue22138

   (28) https://bugs.python.org/issue25672

   (29) https://bugs.python.org/issue26012

   (30) https://bugs.python.org/issue24120

   (31) https://bugs.python.org/issue21815

   (32) https://bugs.python.org/issue25447

   (33) https://bugs.python.org/issue25971

   (34) https://bugs.python.org/issue25802

   (35) https://bugs.python.org/issue25928

   (36) https://bugs.python.org/issue25447

   (37) https://bugs.python.org/issue25768

   (38) https://bugs.python.org/issue24103

   (39) https://bugs.python.org/issue25860

   (40) https://bugs.python.org/issue25914

   (41) https://bugs.python.org/issue25869

   (42) https://bugs.python.org/issue25873

   (43) https://bugs.python.org/issue25902

   (44) https://bugs.python.org/issue22227

   (45) https://bugs.python.org/issue25638

   (46) https://bugs.python.org/issue25761

   (47) https://bugs.python.org/issue25717

   (48) https://bugs.python.org/issue24903

   (49) https://bugs.python.org/issue25764

   (50) https://bugs.python.org/issue25771

   (51) https://bugs.python.org/issue6478

   (52) https://bugs.python.org/issue14285

   (53) https://bugs.python.org/issue19771

   (54) https://bugs.python.org/issue25177

   (55) https://bugs.python.org/issue25718

   (56) https://bugs.python.org/issue10131

   (57) https://bugs.python.org/issue7990

   (58) https://bugs.python.org/issue25725

   (59) https://bugs.python.org/issue25663

   (60) https://bugs.python.org/issue25688

   (61) https://bugs.python.org/issue23914

   (62) https://bugs.python.org/issue25691

   (63) https://bugs.python.org/issue25624

   (64) https://bugs.python.org/issue25626

   (65) https://bugs.python.org/issue25583

   (66) https://bugs.python.org/issue25593

   (67) https://bugs.python.org/issue6973

   (68) https://bugs.python.org/issue23883

   (69) https://bugs.python.org/issue25590

   (70) https://bugs.python.org/issue25498

   (71) https://bugs.python.org/issue25584

   (72) https://bugs.python.org/issue25584

   (73) https://bugs.python.org/issue25446

   (74) https://bugs.python.org/issue18010

   (75) https://bugs.python.org/issue25554

   (76) https://bugs.python.org/issue18973

   (77) https://bugs.python.org/issue25510

   (78) https://bugs.python.org/issue25503

   (79) https://bugs.python.org/issue25515

   (80) https://bugs.python.org/issue21827

   (81) https://bugs.python.org/issue25447

   (82) https://bugs.python.org/issue25390

   (83) https://bugs.python.org/issue25441

   (84) https://bugs.python.org/issue25410

   (85) https://bugs.python.org/issue25411

   (86) https://bugs.python.org/issue25407

   (87) https://bugs.python.org/issue25406

   (88) https://bugs.python.org/issue25382

   (89) https://bugs.python.org/issue25357

   (90) https://bugs.python.org/issue24164

   (91) https://bugs.python.org/issue25364

   (92) https://bugs.python.org/issue25328

   (93) https://bugs.python.org/issue16099

   (94) https://bugs.python.org/issue25316

   (95) https://bugs.python.org/issue25380

   (96) https://bugs.python.org/issue23972

   (97) https://bugs.python.org/issue25304

   (98) https://bugs.python.org/issue25232

   (99) https://bugs.python.org/issue24657

   (100) https://bugs.python.org/issue25287

   (101) https://bugs.python.org/issue23600

   (102) https://bugs.python.org/issue25203

   (103) https://bugs.python.org/issue25011

   (104) https://bugs.python.org/issue25209

   (105) https://bugs.python.org/issue22241

   (106) https://bugs.python.org/issue23517

   (107) https://bugs.python.org/issue23552

   (108) https://bugs.python.org/issue24633

   (109) https://bugs.python.org/issue24879

   (110) https://bugs.python.org/issue24874

   (111) https://bugs.python.org/issue20059

   (112) https://bugs.python.org/issue24360

   (113) https://bugs.python.org/issue23426

   (114) https://bugs.python.org/issue13938

   (115) https://bugs.python.org/issue2091

   (116) https://bugs.python.org/issue8585

   (117) https://bugs.python.org/issue18622

   (118) https://bugs.python.org/issue24426

   (119) https://bugs.python.org/issue23661

   (120) https://bugs.python.org/issue13248

   (121) https://bugs.python.org/issue25578

   (122) https://bugs.python.org/issue25530

   (123) https://bugs.python.org/issue25569

   (124) https://bugs.python.org/issue25471

   (125) https://bugs.python.org/issue25319

   (126) https://bugs.python.org/issue26050

   (127) https://bugs.python.org/issue25924

   (128) https://bugs.python.org/issue26406

   (129) https://bugs.python.org/issue26848

   (130) https://bugs.python.org/issue27040

   (131) https://bugs.python.org/issue27041


File: python.info,  Node: IDLE<46>,  Next: 文档<46>,  Prev: 库<64>,  Up: Python 3 6 0 alpha 1

1.18.65.9 IDLE
..............

   - bpo-20640(1): Add tests for idlelib.configHelpSourceEdit.  Patch by
     Saimadhav Heblikar.

   - In the ’IDLE-console differences’ section of the IDLE doc, clarify
     how running with IDLE affects sys.modules and the standard streams.

   - bpo-25507(2): fix incorrect change in IOBinding that prevented
     printing.  Augment IOBinding htest to include all major IOBinding
     functions.

   - bpo-25905(3): Revert unwanted conversion of ’ to ’ RIGHT SINGLE
     QUOTATION MARK in README.txt and open this and NEWS.txt with
     ’ascii’.  Re-encode CREDITS.txt to utf-8 and open it with ’utf-8’.

   - bpo-15348(4): Stop the debugger engine (normally in a user process)
     before closing the debugger window (running in the IDLE process).
     This prevents the RuntimeErrors that were being caught and ignored.

   - bpo-24455(5): Prevent IDLE from hanging when a) closing the shell
     while the debugger is active (15347); b) closing the debugger with
     the [X] button (15348); and c) activating the debugger when already
     active (24455).  The patch by Mark Roseman does this by making two
     changes.  1.  Suspend and resume the gui.interaction method with
     the tcl vwait mechanism intended for this purpose (instead of
     root.mainloop & .quit).  2.  In gui.run, allow any existing
     interaction to terminate first.

   - Change ’The program’ to ’Your program’ in an IDLE ’kill program?’
     message to make it clearer that the program referred to is the
     currently running user program, not IDLE itself.

   - bpo-24750(6): Improve the appearance of the IDLE editor window
     status bar.  Patch by Mark Roseman.

   - bpo-25313(7): Change the handling of new built-in text color themes
     to better address the compatibility problem introduced by the
     addition of IDLE Dark.  Consistently use the revised
     idleConf.CurrentTheme everywhere in idlelib.

   - bpo-24782(8): Extension configuration is now a tab in the IDLE
     Preferences dialog rather than a separate dialog.  The former tabs
     are now a sorted list.  Patch by Mark Roseman.

   - bpo-22726(9): Re-activate the config dialog help button with some
     content about the other buttons and the new IDLE Dark theme.

   - bpo-24820(10): IDLE now has an ’IDLE Dark’ built-in text color
     theme.  It is more or less IDLE Classic inverted, with a cobalt
     blue background.  Strings, comments, keywords, ...  are still
     green, red, orange, ...  .  To use it with IDLEs released before
     November 2015, hit the ’Save as New Custom Theme’ button and enter
     a new name, such as ’Custom Dark’.  The custom theme will work with
     any IDLE release, and can be modified.

   - bpo-25224(11): README.txt is now an idlelib index for IDLE
     developers and curious users.  The previous user content is now in
     the IDLE doc chapter.  ’IDLE’ now means ’Integrated Development and
     Learning Environment’.

   - bpo-24820(12): Users can now set breakpoint colors in Settings ->
     Custom Highlighting.  Original patch by Mark Roseman.

   - bpo-24972(13): Inactive selection background now matches active
     selection background, as configured by users, on all systems.
     Found items are now always highlighted on Windows.  Initial patch
     by Mark Roseman.

   - bpo-24570(14): Idle: make calltip and completion boxes appear on
     Macs affected by a tk regression.  Initial patch by Mark Roseman.

   - bpo-24988(15): Idle ScrolledList context menus (used in debugger)
     now work on Mac Aqua.  Patch by Mark Roseman.

   - bpo-24801(16): Make right-click for context menu work on Mac Aqua.
     Patch by Mark Roseman.

   - bpo-25173(17): Associate tkinter messageboxes with a specific
     widget.  For Mac OSX, make them a ’sheet’.  Patch by Mark Roseman.

   - bpo-25198(18): Enhance the initial html viewer now used for Idle
     Help.  Properly indent fixed-pitch text (patch by Mark Roseman).
     Give code snippet a very Sphinx-like light blueish-gray background.
     Re-use initial width and height set by users for shell and editor.
     When the Table of Contents (TOC) menu is used, put the section
     header at the top of the screen.

   - bpo-25225(19): Condense and rewrite Idle doc section on text
     colors.

   - bpo-21995(20): Explain some differences between IDLE and console
     Python.

   - bpo-22820(21): Explain need for `print' when running file from Idle
     editor.

   - bpo-25224(22): Doc: augment Idle feature list and no-subprocess
     section.

   - bpo-25219(23): Update doc for Idle command line options.  Some were
     missing and notes were not correct.

   - bpo-24861(24): Most of idlelib is private and subject to change.
     Use idleib.idle.* to start Idle.  See idlelib.__init__.__doc__.

   - bpo-25199(25): Idle: add synchronization comments for future
     maintainers.

   - bpo-16893(26): Replace help.txt with help.html for Idle doc
     display.  The new idlelib/help.html is rstripped
     Doc/build/html/library/idle.html.  It looks better than help.txt
     and will better document Idle as released.  The tkinter html viewer
     that works for this file was written by Rose Roseman.  The now
     unused EditorWindow.HelpDialog class and helt.txt file are
     deprecated.

   - bpo-24199(27): Deprecate unused idlelib.idlever with possible
     removal in 3.6.

   - bpo-24790(28): Remove extraneous code (which also create 2 & 3
     conflicts).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20640

   (2) https://bugs.python.org/issue25507

   (3) https://bugs.python.org/issue25905

   (4) https://bugs.python.org/issue15348

   (5) https://bugs.python.org/issue24455

   (6) https://bugs.python.org/issue24750

   (7) https://bugs.python.org/issue25313

   (8) https://bugs.python.org/issue24782

   (9) https://bugs.python.org/issue22726

   (10) https://bugs.python.org/issue24820

   (11) https://bugs.python.org/issue25224

   (12) https://bugs.python.org/issue24820

   (13) https://bugs.python.org/issue24972

   (14) https://bugs.python.org/issue24570

   (15) https://bugs.python.org/issue24988

   (16) https://bugs.python.org/issue24801

   (17) https://bugs.python.org/issue25173

   (18) https://bugs.python.org/issue25198

   (19) https://bugs.python.org/issue25225

   (20) https://bugs.python.org/issue21995

   (21) https://bugs.python.org/issue22820

   (22) https://bugs.python.org/issue25224

   (23) https://bugs.python.org/issue25219

   (24) https://bugs.python.org/issue24861

   (25) https://bugs.python.org/issue25199

   (26) https://bugs.python.org/issue16893

   (27) https://bugs.python.org/issue24199

   (28) https://bugs.python.org/issue24790


File: python.info,  Node: 文档<46>,  Next: 测试<43>,  Prev: IDLE<46>,  Up: Python 3 6 0 alpha 1

1.18.65.10 文档
...............

   - bpo-26736(1): Used HTTPS for external links in the documentation if
     possible.

   - bpo-6953(2): Rework the Readline module documentation to group
     related functions together, and add more details such as what
     underlying Readline functions and variables are accessed.

   - bpo-23606(3): Adds note to ctypes documentation regarding
     cdll.msvcrt.

   - bpo-24952(4): Clarify the default size argument of stack_size() in
     the "threading" and "_thread" modules.  Patch from Mattip.

   - bpo-26014(5): Update 3.x packaging documentation: * "See also"
     links to the new docs are now provided in the legacy pages * links
     to setuptools documentation have been updated

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26736

   (2) https://bugs.python.org/issue6953

   (3) https://bugs.python.org/issue23606

   (4) https://bugs.python.org/issue24952

   (5) https://bugs.python.org/issue26014


File: python.info,  Node: 测试<43>,  Next: 构建<44>,  Prev: 文档<46>,  Up: Python 3 6 0 alpha 1

1.18.65.11 测试
...............

   - bpo-21916(1): Added tests for the turtle module.  Patch by ingrid,
     Gregory Loyse and Jelle Zijlstra.

   - bpo-26295(2): When using "python3 -m test –testdir=TESTDIR",
     regrtest doesn’t add "test."  prefix to test module names.

   - bpo-26523(3): The multiprocessing thread pool
     (multiprocessing.dummy.Pool) was untested.

   - bpo-26015(4): Added new tests for pickling iterators of mutable
     sequences.

   - bpo-26325(5): Added test.support.check_no_resource_warning() to
     check that no ResourceWarning is emitted.

   - bpo-25940(6): Changed test_ssl to use its internal local server
     more.  This avoids relying on svn.python.org, which recently
     changed root certificate.

   - bpo-25616(7): Tests for OrderedDict are extracted from
     test_collections into separate file test_ordered_dict.

   - bpo-25449(8): Added tests for OrderedDict subclasses.

   - bpo-25188(9): Add -P/–pgo to test.regrtest to suppress error output
     when running the test suite for the purposes of a PGO build.
     Initial patch by Alecsandru Patrascu.

   - bpo-22806(10): Add ‘python -m test --list-tests’ command to list
     tests.

   - bpo-18174(11): ‘python -m test --huntrleaks ...’ now also checks
     for leak of file descriptors.  Patch written by Richard Oudkerk.

   - bpo-25260(12): Fix ‘python -m test --coverage’ on Windows.  Remove
     the list of ignored directories.

   - ‘PCbuild\rt.bat’ now accepts an unlimited number of arguments to
     pass along to regrtest.py.  Previously there was a limit of 9.

   - bpo-26583(13): Skip test_timestamp_overflow in test_import if
     bytecode files cannot be written.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21916

   (2) https://bugs.python.org/issue26295

   (3) https://bugs.python.org/issue26523

   (4) https://bugs.python.org/issue26015

   (5) https://bugs.python.org/issue26325

   (6) https://bugs.python.org/issue25940

   (7) https://bugs.python.org/issue25616

   (8) https://bugs.python.org/issue25449

   (9) https://bugs.python.org/issue25188

   (10) https://bugs.python.org/issue22806

   (11) https://bugs.python.org/issue18174

   (12) https://bugs.python.org/issue25260

   (13) https://bugs.python.org/issue26583


File: python.info,  Node: 构建<44>,  Next: Windows<44>,  Prev: 测试<43>,  Up: Python 3 6 0 alpha 1

1.18.65.12 构建
...............

   - bpo-21277(1): Don’t try to link _ctypes with a ffi_convenience
     library.

   - bpo-26884(2): Fix linking extension modules for cross builds.
     Patch by Xavier de Gaye.

   - bpo-26932(3): Fixed support of RTLD_* constants defined as enum
     values, not via macros (in particular on Android).  Patch by Chi
     Hsuan Yen.

   - bpo-22359(4): Disable the rules for running _freeze_importlib and
     pgen when cross-compiling.  The output of these programs is
     normally saved with the source code anyway, and is still
     regenerated when doing a native build.  Patch by Xavier de Gaye.

   - bpo-21668(5): Link audioop, _datetime, _ctypes_test modules to
     libm, except on Mac OS X. Patch written by Chi Hsuan Yen.

   - bpo-25702(6): A –with-lto configure option has been added that will
     enable link time optimizations at build time during a make
     profile-opt.  Some compilers and toolchains are known to not
     produce stable code when using LTO, be sure to test things
     thoroughly before relying on it.  It can provide a few % speed up
     over profile-opt alone.

   - bpo-26624(7): Adds validation of ucrtbase[d].dll version with
     warning for old versions.

   - bpo-17603(8): Avoid error about nonexistent fileblocks.o file by
     using a lower-level check for st_blocks in struct stat.

   - bpo-26079(9): Fixing the build output folder for tix-8.4.3.6.
     Patch by Bjoern Thiel.

   - bpo-26465(10): 更新Windows 构建OpenSSL 1.0.2g.

   - bpo-25348(11): Added ‘--pgo’ and ‘--pgo-job’ arguments to
     ‘PCbuild\build.bat’ for building with Profile-Guided Optimization.
     The old ‘PCbuild\build_pgo.bat’ script is removed.

   - bpo-25827(12): Add support for building with ICC to ‘configure’,
     including a new ‘--with-icc’ flag.

   - bpo-25696(13): Fix installation of Python on UNIX with make -j9.

   - bpo-24986(14): It is now possible to build Python on Windows
     without errors when external libraries are not available.

   - bpo-24421(15): Compile Modules/_math.c once, before building
     extensions.  Previously it could fail to compile properly if the
     math and cmath builds were concurrent.

   - bpo-26465(16): 更新 OS X 10.5+（仅32位）安装程序以构建并链接
     OpenSSL 1.0.2g.

   - bpo-26268(17): 更新Windows 构建OpenSSL 1.0.2f.

   - bpo-25136(18): Support Apple Xcode 7’s new textual SDK stub
     libraries.

   - bpo-24324(19): Do not enable unreachable code warnings when using
     gcc as the option does not work correctly in older versions of gcc
     and has been silently removed as of gcc-4.5.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21277

   (2) https://bugs.python.org/issue26884

   (3) https://bugs.python.org/issue26932

   (4) https://bugs.python.org/issue22359

   (5) https://bugs.python.org/issue21668

   (6) https://bugs.python.org/issue25702

   (7) https://bugs.python.org/issue26624

   (8) https://bugs.python.org/issue17603

   (9) https://bugs.python.org/issue26079

   (10) https://bugs.python.org/issue26465

   (11) https://bugs.python.org/issue25348

   (12) https://bugs.python.org/issue25827

   (13) https://bugs.python.org/issue25696

   (14) https://bugs.python.org/issue24986

   (15) https://bugs.python.org/issue24421

   (16) https://bugs.python.org/issue26465

   (17) https://bugs.python.org/issue26268

   (18) https://bugs.python.org/issue25136

   (19) https://bugs.python.org/issue24324


File: python.info,  Node: Windows<44>,  Next: 工具/示例<29>,  Prev: 构建<44>,  Up: Python 3 6 0 alpha 1

1.18.65.13 Windows
..................

   - bpo-27053(1): Updates make_zip.py to correctly generate library ZIP
     file.

   - bpo-26268(2): Update the prepare_ssl.py script to handle OpenSSL
     releases that don’t include the contents of the include directory
     (that is, 1.0.2e and later).

   - bpo-26071(3): bdist_wininst created binaries fail to start and find
     32bit Python

   - bpo-26073(4): Update the list of magic numbers in launcher

   - bpo-26065(5): Excludes venv from library when generating embeddable
     distro.

   - bpo-25022(6): Removed very outdated PC/example_nt/ directory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27053

   (2) https://bugs.python.org/issue26268

   (3) https://bugs.python.org/issue26071

   (4) https://bugs.python.org/issue26073

   (5) https://bugs.python.org/issue26065

   (6) https://bugs.python.org/issue25022


File: python.info,  Node: 工具/示例<29>,  Next: C API<33>,  Prev: Windows<44>,  Up: Python 3 6 0 alpha 1

1.18.65.14 工具/示例
....................

   - bpo-26799(1): Fix python-gdb.py: don’t get C types once when the
     Python code is loaded, but get C types on demand.  The C types can
     change if python-gdb.py is loaded before the Python executable.
     Patch written by Thomas Ilsche.

   - bpo-26271(2): Fix the Freeze tool to properly use flags passed
     through configure.  Patch by Daniel Shaulov.

   - bpo-26489(3): Add dictionary unpacking support to
     Tools/parser/unparse.py.  Patch by Guo Ci Teo.

   - bpo-26316(4): Fix variable name typo in Argument Clinic.

   - bpo-25440(5): Fix output of python-config –extension-suffix.

   - bpo-25154(6): The pyvenv script has been deprecated in favour of
     ‘python3 -m venv’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26799

   (2) https://bugs.python.org/issue26271

   (3) https://bugs.python.org/issue26489

   (4) https://bugs.python.org/issue26316

   (5) https://bugs.python.org/issue25440

   (6) https://bugs.python.org/issue25154


File: python.info,  Node: C API<33>,  Prev: 工具/示例<29>,  Up: Python 3 6 0 alpha 1

1.18.65.15 C API
................

   - bpo-26312(1): SystemError is now raised in all programming bugs
     with using PyArg_ParseTupleAndKeywords().  RuntimeError did raised
     before in some programming bugs.

   - bpo-26198(2): ValueError is now raised instead of TypeError on
     buffer overflow in parsing "es#" and "et#" format units.
     SystemError is now raised instead of TypeError on programmatical
     error in parsing format string.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26312

   (2) https://bugs.python.org/issue26198


File: python.info,  Node: Python 3 5 5 正式版,  Next: Python 3 5 5 rc1,  Prev: Python 3 6 0 alpha 1,  Up: 更新日志

1.18.66 Python 3.5.5 正式版
---------------------------

`发布日期e: 2018-02-04'

在 3.5.5 版本中没有新的更改。


File: python.info,  Node: Python 3 5 5 rc1,  Next: Python 3 5 4 正式版,  Prev: Python 3 5 5 正式版,  Up: 更新日志

1.18.67 Python 3.5.5 rc1
------------------------

`发布日期: 2018-01-23'

* Menu:

* 安全: 安全<36>.
* 核心与内置: 核心与内置<57>.
* 库: 库<65>.


File: python.info,  Node: 安全<36>,  Next: 核心与内置<57>,  Up: Python 3 5 5 rc1

1.18.67.1 安全
..............

   - bpo-32551(1): The ‘sys.path[0]’ initialization change for
     bpo-29139(2) caused a regression by revealing an inconsistency in
     how sys.path is initialized when executing ‘__main__’ from a
     zipfile, directory, or other import location.  This is considered a
     potential security issue, as it may lead to privileged processes
     unexpectedly loading code from user controlled directories in
     situations where that was not previously the case.  The interpreter
     now consistently avoids ever adding the import location’s parent
     directory to ‘sys.path’, and ensures no other ‘sys.path’ entries
     are inadvertently modified when inserting the import location named
     on the command line.  (Originally reported as bpo-29723(3) against
     Python 3.6rc1, but it was missed at the time that the then upcoming
     Python 3.5.4 release would also be affected)

   - bpo-30657(4): Fixed possible integer overflow in
     PyBytes_DecodeEscape, CVE-2017-1000158.  Original patch by Jay
     Bosamiya; rebased to Python 3 by Miro Hrončok.

   - bpo-30947(5): Upgrade libexpat embedded copy from version 2.2.1 to
     2.2.3 to get security fixes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32551

   (2) https://bugs.python.org/issue29139

   (3) https://bugs.python.org/issue29723

   (4) https://bugs.python.org/issue30657

   (5) https://bugs.python.org/issue30947


File: python.info,  Node: 核心与内置<57>,  Next: 库<65>,  Prev: 安全<36>,  Up: Python 3 5 5 rc1

1.18.67.2 核心与内置
....................

   - bpo-31095(1): Fix potential crash during GC caused by ‘tp_dealloc’
     which doesn’t call ‘PyObject_GC_UnTrack()’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31095


File: python.info,  Node: 库<65>,  Prev: 核心与内置<57>,  Up: Python 3 5 5 rc1

1.18.67.3 库
............

   - bpo-32072(1): Fixed issues with binary plists: Fixed saving
     bytearrays.  Identical objects will be saved only once.  Equal
     references will be load as identical objects.  Added support for
     saving and loading recursive data structures.

   - bpo-31170(2): expat: Update libexpat from 2.2.3 to 2.2.4.  Fix
     copying of partial characters for UTF-8 input (libexpat bug 115):
     ‘https://github.com/libexpat/libexpat/issues/115’

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32072

   (2) https://bugs.python.org/issue31170


File: python.info,  Node: Python 3 5 4 正式版,  Next: Python 3 5 4 rc1,  Prev: Python 3 5 5 rc1,  Up: 更新日志

1.18.68 Python 3.5.4 正式版
---------------------------

`发布日期: 2017-08-07'

* Menu:

* 库: 库<66>.


File: python.info,  Node: 库<66>,  Up: Python 3 5 4 正式版

1.18.68.1 库
............

   - bpo-30119(1): ftplib.FTP.putline() now throws ValueError on
     commands that contains CR or LF. Patch by Dong-hee Na.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30119


File: python.info,  Node: Python 3 5 4 rc1,  Next: Python 3 5 3 正式版,  Prev: Python 3 5 4 正式版,  Up: 更新日志

1.18.69 Python 3.5.4 rc1
------------------------

`发布日期: 2017-07-23'

* Menu:

* 安全: 安全<37>.
* 核心与内置: 核心与内置<58>.
* 库: 库<67>.
* 文档: 文档<47>.
* 测试: 测试<44>.
* 构建: 构建<45>.
* Windows: Windows<45>.
* C API: C API<34>.


File: python.info,  Node: 安全<37>,  Next: 核心与内置<58>,  Up: Python 3 5 4 rc1

1.18.69.1 安全
..............

   - bpo-30730(1): Prevent environment variables injection in subprocess
     on Windows.  Prevent passing other environment variables and
     command arguments.

   - bpo-30694(2): Upgrade expat copy from 2.2.0 to 2.2.1 to get fixes
     of multiple security vulnerabilities including: CVE-2017-9233
     (External entity infinite loop DoS), CVE-2016-9063 (Integer
     overflow, re-fix), CVE-2016-0718 (Fix regression bugs from 2.2.0’s
     fix to CVE-2016-0718) and CVE-2012-0876 (Counter hash flooding with
     SipHash).  Note: the CVE-2016-5300 (Use os-specific entropy sources
     like getrandom) doesn’t impact Python, since Python already gets
     entropy from the OS to set the expat secret using
     ‘XML_SetHashSalt()’.

   - bpo-30500(3): Fix urllib.parse.splithost() to correctly parse
     fragments.  For example, ‘splithost('//127.0.0.1#@evil.com/')’ now
     correctly returns the ‘127.0.0.1’ host, instead of treating
     ‘@evil.com’ as the host in an authentication (‘login@host’).

   - bpo-29591(4): Update expat copy from 2.1.1 to 2.2.0 to get fixes of
     CVE-2016-0718 and CVE-2016-4472.  See
     ‘https://sourceforge.net/p/expat/bugs/537/’ for more information.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30730

   (2) https://bugs.python.org/issue30694

   (3) https://bugs.python.org/issue30500

   (4) https://bugs.python.org/issue29591


File: python.info,  Node: 核心与内置<58>,  Next: 库<67>,  Prev: 安全<37>,  Up: Python 3 5 4 rc1

1.18.69.2 核心与内置
....................

   - bpo-30876(1): Relative import from unloaded package now reimports
     the package instead of failing with SystemError.  Relative import
     from non-package now fails with ImportError rather than
     SystemError.

   - bpo-30765(2): Avoid blocking in pthread_mutex_lock() when
     PyThread_acquire_lock() is asked not to block.

   - bpo-27945(3): Fixed various segfaults with dict when input
     collections are mutated during searching, inserting or comparing.
     Based on patches by Duane Griffin and Tim Mitchell.

   - bpo-25794(4): Fixed type.__setattr__() and type.__delattr__() for
     non-interned attribute names.  Based on patch by Eryk Sun.

   - bpo-29935(5): Fixed error messages in the index() method of tuple,
     list and deque when pass indices of wrong type.

   - bpo-28876(6): ‘bool(range)’ works even if ‘len(range)’ raises *note
     OverflowError: 968.

   - bpo-29600(7): Fix wrapping coroutine return values in
     StopIteration.

   - bpo-29537(8): Restore runtime compatibility with bytecode files
     generated by CPython 3.5.0 to 3.5.2, and adjust the eval loop to
     avoid the problems that could be caused by the malformed variant of
     the BUILD_MAP_UNPACK_WITH_CALL opcode that they may contain.  Patch
     by Petr Viktorin, Serhiy Storchaka, and Nick Coghlan.

   - bpo-28598(9): Support __rmod__ for subclasses of str being called
     before str.__mod__.  Patch by Martijn Pieters.

   - bpo-29602(10): Fix incorrect handling of signed zeros in complex
     constructor for complex subclasses and for inputs having a
     __complex__ method.  Patch by Serhiy Storchaka.

   - bpo-29347(11): Fixed possibly dereferencing undefined pointers when
     creating weakref objects.

   - bpo-29438(12): Fixed use-after-free problem in key sharing dict.

   - bpo-29319(13): Prevent RunMainFromImporter overwriting sys.path[0].

   - bpo-29337(14): Fixed possible BytesWarning when compare the code
     objects.  Warnings could be emitted at compile time.

   - bpo-29478(15): If max_line_length=None is specified while using the
     Compat32 policy, it is no longer ignored.  Patch by Mircea Cosbuc.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30876

   (2) https://bugs.python.org/issue30765

   (3) https://bugs.python.org/issue27945

   (4) https://bugs.python.org/issue25794

   (5) https://bugs.python.org/issue29935

   (6) https://bugs.python.org/issue28876

   (7) https://bugs.python.org/issue29600

   (8) https://bugs.python.org/issue29537

   (9) https://bugs.python.org/issue28598

   (10) https://bugs.python.org/issue29602

   (11) https://bugs.python.org/issue29347

   (12) https://bugs.python.org/issue29438

   (13) https://bugs.python.org/issue29319

   (14) https://bugs.python.org/issue29337

   (15) https://bugs.python.org/issue29478


File: python.info,  Node: 库<67>,  Next: 文档<47>,  Prev: 核心与内置<58>,  Up: Python 3 5 4 rc1

1.18.69.3 库
............

   - bpo-29403(1): Fix ‘unittest.mock’’s autospec to not fail on
     method-bound builtin functions.  Patch by Aaron Gallagher.

   - bpo-30961(2): Fix decrementing a borrowed reference in tracemalloc.

   - bpo-30886(3): Fix multiprocessing.Queue.join_thread(): it now waits
     until the thread completes, even if the thread was started by the
     same process which created the queue.

   - bpo-29854(4): Fix segfault in readline when using readline’s
     history-size option.  Patch by Nir Soffer.

   - bpo-30807(5): signal.setitimer() may disable the timer when passed
     a tiny value.  Tiny values (such as 1e-6) are valid non-zero values
     for setitimer(), which is specified as taking
     microsecond-resolution intervals.  However, on some platform, our
     conversion routine could convert 1e-6 into a zero interval,
     therefore disabling the timer instead of (re-)scheduling it.

   - bpo-30441(6): Fix bug when modifying os.environ while iterating
     over it

   - bpo-30532(7): Fix email header value parser dropping folding white
     space in certain cases.

   - bpo-29169(8): Update zlib to 1.2.11.

   - bpo-30879(9): os.listdir() and os.scandir() now emit bytes names
     when called with bytes-like argument.

   - bpo-30746(10): Prohibited the ’=’ character in environment variable
     names in ‘os.putenv()’ and ‘os.spawn*()’.

   - bpo-29755(11): Fixed the lgettext() family of functions in the
     gettext module.  They now always return bytes.

   - bpo-30645(12): Fix path calculation in imp.load_package(), fixing
     it for cases when a package is only shipped with bytecodes.  Patch
     by Alexandru Ardelean.

   - bpo-23890(13): unittest.TestCase.assertRaises() now manually breaks
     a reference cycle to not keep objects alive longer than expected.

   - bpo-30149(14): inspect.signature() now supports callables with
     variable-argument parameters wrapped with partialmethod.  Patch by
     Dong-hee Na.

   - bpo-29931(15): Fixed comparison check for ipaddress.ip_interface
     objects.  Patch by Sanjay Sundaresan.

   - bpo-24484(16): Avoid race condition in multiprocessing cleanup.

   - bpo-28994(17): The traceback no longer displayed for SystemExit
     raised in a callback registered by atexit.

   - bpo-30508(18): Don’t log exceptions if Task/Future "cancel()"
     method was called.

   - bpo-28556(19): Updates to typing module: Add generic
     AsyncContextManager, add support for ContextManager on all
     versions.  Original PRs by Jelle Zijlstra and Ivan Levkivskyi

   - bpo-29870(20): Fix ssl sockets leaks when connection is aborted in
     asyncio/ssl implementation.  Patch by Michaël Sghaïer.

   - bpo-29743(21): Closing transport during handshake process leaks
     open socket.  Patch by Nikolay Kim

   - bpo-27585(22): Fix waiter cancellation in asyncio.Lock.  Patch by
     Mathieu Sornay.

   - bpo-30418(23): On Windows, subprocess.Popen.communicate() now also
     ignore EINVAL on stdin.write() if the child process is still
     running but closed the pipe.

   - bpo-30378(24): Fix the problem that logging.handlers.SysLogHandler
     cannot handle IPv6 addresses.

   - bpo-29960(25): Preserve generator state when
     _random.Random.setstate() raises an exception.  Patch by Bryan
     Olson.

   - bpo-30414(26): multiprocessing.Queue._feed background running
     thread do not break from main loop on exception.

   - bpo-30003(27): Fix handling escape characters in HZ codec.  Based
     on patch by Ma Lin.

   - bpo-30301(28): Fix AttributeError when using SimpleQueue.empty()
     under `spawn' and `forkserver' start methods.

   - bpo-30329(29): imaplib and poplib now catch the Windows socket
     WSAEINVAL error (code 10022) on shutdown(SHUT_RDWR): An invalid
     operation was attempted.  This error occurs sometimes on SSL
     connections.

   - bpo-30375(30): Warnings emitted when compile a regular expression
     now always point to the line in the user code.  Previously they
     could point into inners of the re module if emitted from inside of
     groups or conditionals.

   - bpo-30048(31): Fixed ‘Task.cancel()’ can be ignored when the task
     is running coroutine and the coroutine returned without any more
     ‘await’.

   - bpo-29990(32): Fix range checking in GB18030 decoder.  Original
     patch by Ma Lin.

   - bpo-26293(33): Change resulted because of zipfile breakage.  (See
     also: bpo-29094(34))

   - bpo-30243(35): Removed the __init__ methods of _json’s scanner and
     encoder.  Misusing them could cause memory leaks or crashes.  Now
     scanner and encoder objects are completely initialized in the
     __new__ methods.

   - bpo-30185(36): Avoid KeyboardInterrupt tracebacks in forkserver
     helper process when Ctrl-C is received.

   - bpo-28556(37): Various updates to typing module: add
     typing.NoReturn type, use WrapperDescriptorType, minor bug-fixes.
     Original PRs by Jim Fasarakis-Hilliard and Ivan Levkivskyi.

   - bpo-30205(38): Fix getsockname() for unbound AF_UNIX sockets on
     Linux.

   - bpo-30070(39): Fixed leaks and crashes in errors handling in the
     parser module.

   - bpo-30061(40): Fixed crashes in IOBase methods __next__() and
     readlines() when readline() or __next__() respectively return
     non-sizeable object.  Fixed possible other errors caused by not
     checking results of PyObject_Size(), PySequence_Size(), or
     PyMapping_Size().

   - bpo-30068(41): _io._IOBase.readlines will check if it’s closed
     first when hint is present.

   - bpo-29694(42): Fixed race condition in pathlib mkdir with flags
     parents=True.  Patch by Armin Rigo.

   - bpo-29692(43): Fixed arbitrary unchaining of RuntimeError
     exceptions in contextlib.contextmanager.  Patch by Siddharth
     Velankar.

   - bpo-29998(44): Pickling and copying ImportError now preserves name
     and path attributes.

   - bpo-29942(45): Fix a crash in itertools.chain.from_iterable when
     encountering long runs of empty iterables.

   - bpo-27863(46): Fixed multiple crashes in ElementTree caused by race
     conditions and wrong types.

   - bpo-28699(47): Fixed a bug in pools in multiprocessing.pool that
     raising an exception at the very first of an iterable may swallow
     the exception or make the program hang.  Patch by Davin Potts and
     Xiang Zhang.

   - bpo-25803(48): Avoid incorrect errors raised by
     Path.mkdir(exist_ok=True) when the OS gives priority to errors such
     as EACCES over EEXIST.

   - bpo-29861(49): Release references to tasks, their arguments and
     their results as soon as they are finished in multiprocessing.Pool.

   - bpo-29884(50): faulthandler: Restore the old sigaltstack during
     teardown.  Patch by Christophe Zeitouny.

   - bpo-25455(51): Fixed crashes in repr of recursive buffered
     file-like objects.

   - bpo-29800(52): Fix crashes in partial.__repr__ if the keys of
     partial.keywords are not strings.  Patch by Michael Seifert.

   - bpo-29742(53): get_extra_info() raises exception if get called on
     closed ssl transport.  Patch by Nikolay Kim.

   - bpo-8256(54): Fixed possible failing or crashing input() if
     attributes "encoding" or "errors" of sys.stdin or sys.stdout are
     not set or are not strings.

   - bpo-28298(55): Fix a bug that prevented array ’Q’, ’L’ and ’I’ from
     accepting big intables (objects that have __int__) as elements.
     Patch by Oren Milman.

   - bpo-29615(56): SimpleXMLRPCDispatcher no longer chains KeyError (or
     any other exception) to exception(s) raised in the dispatched
     methods.  Patch by Petr Motejlek.

   - bpo-29704(57): asyncio.subprocess.SubprocessStreamProtocol no
     longer closes before all pipes are closed.

   - bpo-29703(58): Fix asyncio to support instantiation of new event
     loops in child processes.

   - bpo-29376(59): Fix assertion error in
     threading._DummyThread.is_alive().

   - bpo-29110(60): Fix file object leak in aifc.open() when file is
     given as a filesystem path and is not in valid AIFF format.  Patch
     by Anthony Zhang.

   - bpo-28961(61): Fix unittest.mock._Call helper: don’t ignore the
     name parameter anymore.  Patch written by Jiajun Huang.

   - bpo-29532(62): Altering a kwarg dictionary passed to
     functools.partial() no longer affects a partial object after
     creation.

   - bpo-28556(63): Various updates to typing module: typing.Counter,
     typing.ChainMap, improved ABC caching, etc.  Original PRs by Jelle
     Zijlstra, Ivan Levkivskyi, Manuel Krebber, and Łukasz Langa.

   - bpo-29100(64): Fix datetime.fromtimestamp() regression introduced
     in Python 3.6.0: check minimum and maximum years.

   - bpo-29519(65): Fix weakref spewing exceptions during interpreter
     shutdown when used with a rare combination of multiprocessing and
     custom codecs.

   - bpo-29416(66): Prevent infinite loop in pathlib.Path.mkdir

   - bpo-29444(67): Fixed out-of-bounds buffer access in the group()
     method of the match object.  Based on patch by WGH.

   - bpo-29335(68): Fix subprocess.Popen.wait() when the child process
     has exited to a stopped instead of terminated state (ex: when under
     ptrace).

   - bpo-29290(69): Fix a regression in argparse that help messages
     would wrap at non-breaking spaces.

   - bpo-28735(70): Fixed the comparison of mock.MagickMock with
     mock.ANY.

   - bpo-29011(71): Fix an important omission by adding Deque to the
     typing module.

   - bpo-29219(72): Fixed infinite recursion in the repr of
     uninitialized ctypes.CDLL instances.

   - bpo-28969(73): Fixed race condition in C implementation of
     functools.lru_cache.  KeyError could be raised when cached function
     with full cache was simultaneously called from different threads
     with the same uncached arguments.

   - bpo-29142(74): In urllib.request, suffixes in no_proxy environment
     variable with leading dots could match related hostnames again
     (e.g.  .b.c matches a.b.c).  Patch by Milan Oberkirch.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29403

   (2) https://bugs.python.org/issue30961

   (3) https://bugs.python.org/issue30886

   (4) https://bugs.python.org/issue29854

   (5) https://bugs.python.org/issue30807

   (6) https://bugs.python.org/issue30441

   (7) https://bugs.python.org/issue30532

   (8) https://bugs.python.org/issue29169

   (9) https://bugs.python.org/issue30879

   (10) https://bugs.python.org/issue30746

   (11) https://bugs.python.org/issue29755

   (12) https://bugs.python.org/issue30645

   (13) https://bugs.python.org/issue23890

   (14) https://bugs.python.org/issue30149

   (15) https://bugs.python.org/issue29931

   (16) https://bugs.python.org/issue24484

   (17) https://bugs.python.org/issue28994

   (18) https://bugs.python.org/issue30508

   (19) https://bugs.python.org/issue28556

   (20) https://bugs.python.org/issue29870

   (21) https://bugs.python.org/issue29743

   (22) https://bugs.python.org/issue27585

   (23) https://bugs.python.org/issue30418

   (24) https://bugs.python.org/issue30378

   (25) https://bugs.python.org/issue29960

   (26) https://bugs.python.org/issue30414

   (27) https://bugs.python.org/issue30003

   (28) https://bugs.python.org/issue30301

   (29) https://bugs.python.org/issue30329

   (30) https://bugs.python.org/issue30375

   (31) https://bugs.python.org/issue30048

   (32) https://bugs.python.org/issue29990

   (33) https://bugs.python.org/issue26293

   (34) https://bugs.python.org/issue29094

   (35) https://bugs.python.org/issue30243

   (36) https://bugs.python.org/issue30185

   (37) https://bugs.python.org/issue28556

   (38) https://bugs.python.org/issue30205

   (39) https://bugs.python.org/issue30070

   (40) https://bugs.python.org/issue30061

   (41) https://bugs.python.org/issue30068

   (42) https://bugs.python.org/issue29694

   (43) https://bugs.python.org/issue29692

   (44) https://bugs.python.org/issue29998

   (45) https://bugs.python.org/issue29942

   (46) https://bugs.python.org/issue27863

   (47) https://bugs.python.org/issue28699

   (48) https://bugs.python.org/issue25803

   (49) https://bugs.python.org/issue29861

   (50) https://bugs.python.org/issue29884

   (51) https://bugs.python.org/issue25455

   (52) https://bugs.python.org/issue29800

   (53) https://bugs.python.org/issue29742

   (54) https://bugs.python.org/issue8256

   (55) https://bugs.python.org/issue28298

   (56) https://bugs.python.org/issue29615

   (57) https://bugs.python.org/issue29704

   (58) https://bugs.python.org/issue29703

   (59) https://bugs.python.org/issue29376

   (60) https://bugs.python.org/issue29110

   (61) https://bugs.python.org/issue28961

   (62) https://bugs.python.org/issue29532

   (63) https://bugs.python.org/issue28556

   (64) https://bugs.python.org/issue29100

   (65) https://bugs.python.org/issue29519

   (66) https://bugs.python.org/issue29416

   (67) https://bugs.python.org/issue29444

   (68) https://bugs.python.org/issue29335

   (69) https://bugs.python.org/issue29290

   (70) https://bugs.python.org/issue28735

   (71) https://bugs.python.org/issue29011

   (72) https://bugs.python.org/issue29219

   (73) https://bugs.python.org/issue28969

   (74) https://bugs.python.org/issue29142


File: python.info,  Node: 文档<47>,  Next: 测试<44>,  Prev: 库<67>,  Up: Python 3 5 4 rc1

1.18.69.4 文档
..............

   - bpo-30176(1): Add missing attribute related constants in curses
     documentation.

   - bpo-26985(2): Add missing info of code object in inspect
     documentation.

   - bpo-28929(3): Link the documentation to its source file on GitHub.

   - bpo-25008(4): Document smtpd.py as effectively deprecated and add a
     pointer to aiosmtpd, a third-party asyncio-based replacement.

   - bpo-26355(5): Add canonical header link on each page to
     corresponding major version of the documentation.  Patch by
     Matthias Bussonnier.

   - bpo-29349(6): Fix Python 2 syntax in code for building the
     documentation.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30176

   (2) https://bugs.python.org/issue26985

   (3) https://bugs.python.org/issue28929

   (4) https://bugs.python.org/issue25008

   (5) https://bugs.python.org/issue26355

   (6) https://bugs.python.org/issue29349


File: python.info,  Node: 测试<44>,  Next: 构建<45>,  Prev: 文档<47>,  Up: Python 3 5 4 rc1

1.18.69.5 测试
..............

   - bpo-30822(1): Fix regrtest command line parser to allow passing -u
     extralargefile to run test_zipfile64.

   - bpo-30383(2): regrtest: Enhance regrtest and backport features from
     the master branch.  Add options: –coverage, –testdir, –list-tests
     (list test files, don’t run them), –list-cases (list test
     identifiers, don’t run them, bpo-30523(3)), –matchfile (load a list
     of test filters from a text file, bpo-30540(4)), –slowest (alias to
     –slow).  Enhance output: add timestamp, test result, currently
     running tests, "Tests result: xxx" summary with total duration,
     etc.  Fix reference leak hunting in regrtest, –huntrleaks: regrtest
     now warms up caches, create explicitly all internal singletons
     which are created on demand to prevent false positives when
     checking for reference leaks.  (bpo-30675(5)).

   - bpo-30357(6): test_thread: setUp() now uses
     support.threading_setup() and support.threading_cleanup() to wait
     until threads complete to avoid random side effects on following
     tests.  Initial patch written by Grzegorz Grzywacz.

   - bpo-28087(7): Skip test_asyncore and test_eintr poll failures on
     macOS. Skip some tests of select.poll when running on macOS due to
     unresolved issues with the underlying system poll function on some
     macOS versions.

   - bpo-30197(8): Enhanced functions swap_attr() and swap_item() in the
     test.support module.  They now work when delete replaced attribute
     or item inside the with statement.  The old value of the attribute
     or item (or None if it doesn’t exist) now will be assigned to the
     target of the "as" clause, if there is one.

   - bpo-29571(9): to match the behaviour of the ‘re.LOCALE’ flag,
     test_re.test_locale_flag now uses
     ‘locale.getpreferredencoding(False)’ to determine the candidate
     encoding for the test regex (allowing it to correctly skip the test
     when the default locale encoding is a multi-byte encoding)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30822

   (2) https://bugs.python.org/issue30383

   (3) https://bugs.python.org/issue30523

   (4) https://bugs.python.org/issue30540

   (5) https://bugs.python.org/issue30675

   (6) https://bugs.python.org/issue30357

   (7) https://bugs.python.org/issue28087

   (8) https://bugs.python.org/issue30197

   (9) https://bugs.python.org/issue29571


File: python.info,  Node: 构建<45>,  Next: Windows<45>,  Prev: 测试<44>,  Up: Python 3 5 4 rc1

1.18.69.6 构建
..............

   - bpo-29243(1): Prevent unnecessary rebuilding of Python during ‘make
     test’, ‘make install’ and some other make targets when configured
     with ‘--enable-optimizations’.

   - bpo-23404(2): Don’t regenerate generated files based on file
     modification time anymore: the action is now explicit.  Replace
     ‘make touch’ with ‘make regen-all’.

   - bpo-29643(3): Fix ‘--enable-optimization’ didn’t work.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29243

   (2) https://bugs.python.org/issue23404

   (3) https://bugs.python.org/issue29643


File: python.info,  Node: Windows<45>,  Next: C API<34>,  Prev: 构建<45>,  Up: Python 3 5 4 rc1

1.18.69.7 Windows
.................

   - bpo-30687(1): Locate msbuild.exe on Windows when building rather
     than vcvarsall.bat

   - bpo-29392(2): Prevent crash when passing invalid arguments into
     msvcrt module.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30687

   (2) https://bugs.python.org/issue29392


File: python.info,  Node: C API<34>,  Prev: Windows<45>,  Up: Python 3 5 4 rc1

1.18.69.8 C API
...............

   - bpo-27867(1): Function PySlice_GetIndicesEx() is replaced with a
     macro if Py_LIMITED_API is set to the value between 0x03050400 and
     0x03060000 (not including) or 0x03060100 or higher.

   - bpo-29083(2): Fixed the declaration of some public API functions.
     PyArg_VaParse() and PyArg_VaParseTupleAndKeywords() were not
     available in limited API. PyArg_ValidateKeywordArguments(),
     PyArg_UnpackTuple() and Py_BuildValue() were not available in
     limited API of version < 3.3 when PY_SSIZE_T_CLEAN is defined.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27867

   (2) https://bugs.python.org/issue29083


File: python.info,  Node: Python 3 5 3 正式版,  Next: Python 3 5 3 rc1,  Prev: Python 3 5 4 rc1,  Up: 更新日志

1.18.70 Python 3.5.3 正式版
---------------------------

`发布日期: 2017-01-17'

There were no code changes between 3.5.3rc1 and 3.5.3 final.


File: python.info,  Node: Python 3 5 3 rc1,  Next: Python 3 5 2 正式版,  Prev: Python 3 5 3 正式版,  Up: 更新日志

1.18.71 Python 3.5.3 rc1
------------------------

`发布日期: 2017-01-02'

* Menu:

* 核心与内置: 核心与内置<59>.
* 库: 库<68>.
* 安全: 安全<38>.
* 库: 库<69>.
* 安全: 安全<39>.
* 库: 库<70>.
* IDLE: IDLE<47>.
* C API: C API<35>.
* 文档: 文档<48>.
* 测试: 测试<45>.
* 工具/示例: 工具/示例<30>.
* Windows: Windows<46>.
* 构建: 构建<46>.


File: python.info,  Node: 核心与内置<59>,  Next: 库<68>,  Up: Python 3 5 3 rc1

1.18.71.1 核心与内置
....................

   - bpo-29073(1): bytearray formatting no longer truncates on first
     null byte.

   - bpo-28932(2): Do not include <sys/random.h> if it does not exist.

   - bpo-28147(3): Fix a memory leak in split-table dictionaries:
     setattr() must not convert combined table into split table.

   - bpo-25677(4): Correct the positioning of the syntax error caret for
     indented blocks.  Based on patch by Michael Layzell.

   - bpo-29000(5): Fixed bytes formatting of octals with zero padding in
     alternate form.

   - bpo-28512(6): Fixed setting the offset attribute of SyntaxError by
     PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

   - bpo-28991(7): functools.lru_cache() was susceptible to an obscure
     reentrancy bug caused by a monkey-patched len() function.

   - bpo-28648(8): Fixed crash in Py_DecodeLocale() in debug build on
     Mac OS X when decode astral characters.  Patch by Xiang Zhang.

   - bpo-19398(9): Extra slash no longer added to sys.path components in
     case of empty compile-time PYTHONPATH components.

   - bpo-28426(10): Fixed potential crash in PyUnicode_AsDecodedObject()
     in debug build.

   - bpo-23782(11): Fixed possible memory leak in _PyTraceback_Add() and
     exception loss in PyTraceBack_Here().

   - bpo-28379(12): Added sanity checks and tests for
     PyUnicode_CopyCharacters().  Patch by Xiang Zhang.

   - bpo-28376(13): The type of long range iterator is now registered as
     Iterator.  Patch by Oren Milman.

   - bpo-28376(14): The constructor of range_iterator now checks that
     step is not 0.  Patch by Oren Milman.

   - bpo-26906(15): Resolving special methods of uninitialized type now
     causes implicit initialization of the type instead of a fail.

   - bpo-18287(16): PyType_Ready() now checks that tp_name is not NULL.
     Original patch by Niklas Koep.

   - bpo-24098(17): Fixed possible crash when AST is changed in process
     of compiling it.

   - bpo-28350(18): String constants with null character no longer
     interned.

   - bpo-26617(19): Fix crash when GC runs during weakref callbacks.

   - bpo-27942(20): String constants now interned recursively in tuples
     and frozensets.

   - bpo-21578(21): Fixed misleading error message when ImportError
     called with invalid keyword args.

   - bpo-28203(22): Fix incorrect type in error message from
     ‘complex(1.0, {2:3})’.  Patch by Soumya Sharma.

   - bpo-27955(23): Fallback on reading /dev/urandom device when the
     getrandom() syscall fails with EPERM, for example when blocked by
     SECCOMP.

   - bpo-28131(24): Fix a regression in zipimport’s compile_source().
     zipimport should use the same optimization level as the
     interpreter.

   - bpo-25221(25): Fix corrupted result from PyLong_FromLong(0) when
     Python is compiled with NSMALLPOSINTS = 0.

   - bpo-25758(26): Prevents zipimport from unnecessarily encoding a
     filename (patch by Eryk Sun)

   - bpo-28189(27): dictitems_contains no longer swallows compare
     errors.  (Patch by Xiang Zhang)

   - bpo-27812(28): Properly clear out a generator’s frame’s
     backreference to the generator to prevent crashes in frame.clear().

   - bpo-27811(29): Fix a crash when a coroutine that has not been
     awaited is finalized with warnings-as-errors enabled.

   - bpo-27587(30): Fix another issue found by PVS-Studio: Null pointer
     check after use of ’def’ in _PyState_AddModule().  Initial patch by
     Christian Heimes.

   - bpo-26020(31): set literal evaluation order did not match
     documented behaviour.

   - bpo-27782(32): Multi-phase extension module import now correctly
     allows the ‘m_methods’ field to be used to add module level
     functions to instances of non-module types returned from
     ‘Py_create_mod’.  Patch by Xiang Zhang.

   - bpo-27936(33): The round() function accepted a second None argument
     for some types but not for others.  Fixed the inconsistency by
     accepting None for all numeric types.

   - bpo-27487(34): Warn if a submodule argument to "python -m" or
     runpy.run_module() is found in sys.modules after parent packages
     are imported, but before the submodule is executed.

   - bpo-27558(35): Fix a SystemError in the implementation of "raise"
     statement.  In a brand new thread, raise a RuntimeError since there
     is no active exception to reraise.  Patch written by Xiang Zhang.

   - bpo-27419(36): Standard __import__() no longer look up "__import__"
     in globals or builtins for importing submodules or "from import".
     Fixed handling an error of non-string package name.

   - bpo-27083(37): Respect the PYTHONCASEOK environment variable under
     Windows.

   - bpo-27514(38): Make having too many statically nested blocks a
     SyntaxError instead of SystemError.

   - bpo-27473(39): Fixed possible integer overflow in bytes and
     bytearray concatenations.  Patch by Xiang Zhang.

   - bpo-27507(40): Add integer overflow check in bytearray.extend().
     Patch by Xiang Zhang.

   - bpo-27581(41): Don’t rely on wrapping for overflow check in
     PySequence_Tuple().  Patch by Xiang Zhang.

   - bpo-27443(42): __length_hint__() of bytearray iterators no longer
     return a negative integer for a resized bytearray.

   - bpo-27942(43): Fix memory leak in codeobject.c

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29073

   (2) https://bugs.python.org/issue28932

   (3) https://bugs.python.org/issue28147

   (4) https://bugs.python.org/issue25677

   (5) https://bugs.python.org/issue29000

   (6) https://bugs.python.org/issue28512

   (7) https://bugs.python.org/issue28991

   (8) https://bugs.python.org/issue28648

   (9) https://bugs.python.org/issue19398

   (10) https://bugs.python.org/issue28426

   (11) https://bugs.python.org/issue23782

   (12) https://bugs.python.org/issue28379

   (13) https://bugs.python.org/issue28376

   (14) https://bugs.python.org/issue28376

   (15) https://bugs.python.org/issue26906

   (16) https://bugs.python.org/issue18287

   (17) https://bugs.python.org/issue24098

   (18) https://bugs.python.org/issue28350

   (19) https://bugs.python.org/issue26617

   (20) https://bugs.python.org/issue27942

   (21) https://bugs.python.org/issue21578

   (22) https://bugs.python.org/issue28203

   (23) https://bugs.python.org/issue27955

   (24) https://bugs.python.org/issue28131

   (25) https://bugs.python.org/issue25221

   (26) https://bugs.python.org/issue25758

   (27) https://bugs.python.org/issue28189

   (28) https://bugs.python.org/issue27812

   (29) https://bugs.python.org/issue27811

   (30) https://bugs.python.org/issue27587

   (31) https://bugs.python.org/issue26020

   (32) https://bugs.python.org/issue27782

   (33) https://bugs.python.org/issue27936

   (34) https://bugs.python.org/issue27487

   (35) https://bugs.python.org/issue27558

   (36) https://bugs.python.org/issue27419

   (37) https://bugs.python.org/issue27083

   (38) https://bugs.python.org/issue27514

   (39) https://bugs.python.org/issue27473

   (40) https://bugs.python.org/issue27507

   (41) https://bugs.python.org/issue27581

   (42) https://bugs.python.org/issue27443

   (43) https://bugs.python.org/issue27942


File: python.info,  Node: 库<68>,  Next: 安全<38>,  Prev: 核心与内置<59>,  Up: Python 3 5 3 rc1

1.18.71.2 库
............

   - bpo-15812(1): inspect.getframeinfo() now correctly shows the first
     line of a context.  Patch by Sam Breese.

   - bpo-29094(2): Offsets in a ZIP file created with extern file object
     and modes "w" and "x" now are relative to the start of the file.

   - bpo-13051(3): Fixed recursion errors in large or resized
     curses.textpad.Textbox.  Based on patch by Tycho Andersen.

   - bpo-29119(4): Fix weakrefs in the pure python version of
     collections.OrderedDict move_to_end() method.  Contributed by Andra
     Bogildea.

   - bpo-9770(5): curses.ascii predicates now work correctly with
     negative integers.

   - bpo-28427(6): old keys should not remove new values from
     WeakValueDictionary when collecting from another thread.

   - bpo-28923(7): Remove editor artifacts from Tix.py.

   - bpo-28871(8): Fixed a crash when deallocate deep ElementTree.

   - bpo-19542(9): Fix bugs in WeakValueDictionary.setdefault() and
     WeakValueDictionary.pop() when a GC collection happens in another
     thread.

   - bpo-20191(10): Fixed a crash in resource.prlimit() when pass a
     sequence that doesn’t own its elements as limits.

   - bpo-28779(11): multiprocessing.set_forkserver_preload() would crash
     the forkserver process if a preloaded module instantiated some
     multiprocessing objects such as locks.

   - bpo-28847(12): dbm.dumb now supports reading read-only files and no
     longer writes the index file when it is not changed.

   - bpo-25659(13): In ctypes, prevent a crash calling the from_buffer()
     and from_buffer_copy() methods on abstract classes like Array.

   - bpo-28732(14): Fix crash in os.spawnv() with no elements in args

   - bpo-28485(15): Always raise ValueError for negative
     compileall.compile_dir(workers=...)  parameter, even when
     multithreading is unavailable.

   - bpo-28387(16): Fixed possible crash in _io.TextIOWrapper
     deallocator when the garbage collector is invoked in other thread.
     Based on patch by Sebastian Cufre.

   - bpo-27517(17): LZMA compressor and decompressor no longer raise
     exceptions if given empty data twice.  Patch by Benjamin Fogle.

   - bpo-28549(18): Fixed segfault in curses’s addch() with ncurses6.

   - bpo-28449(19): tarfile.open() with mode "r" or "r:" now tries to
     open a tar file with compression before trying to open it without
     compression.  Otherwise it had 50% chance failed with
     ignore_zeros=True.

   - bpo-23262(20): The webbrowser module now supports Firefox 36+ and
     derived browsers.  Based on patch by Oleg Broytman.

   - bpo-27939(21): Fixed bugs in tkinter.ttk.LabeledScale and
     tkinter.Scale caused by representing the scale as float value
     internally in Tk.  tkinter.IntVar now works if float value is set
     to underlying Tk variable.

   - bpo-28255(22): calendar.TextCalendar().prmonth() no longer prints a
     space at the start of new line after printing a month’s calendar.
     Patch by Xiang Zhang.

   - bpo-20491(23): The textwrap.TextWrapper class now honors
     non-breaking spaces.  Based on patch by Kaarle Ritvanen.

   - bpo-28353(24): os.fwalk() no longer fails on broken links.

   - bpo-25464(25): Fixed HList.header_exists() in tkinter.tix module by
     addin a workaround to Tix library bug.

   - bpo-28488(26): shutil.make_archive() no longer add entry "./" to
     ZIP archive.

   - bpo-24452(27): Make webbrowser support Chrome on Mac OS X.

   - bpo-20766(28): Fix references leaked by pdb in the handling of
     SIGINT handlers.

   - bpo-26293(29): Fixed writing ZIP files that starts not from the
     start of the file.  Offsets in ZIP file now are relative to the
     start of the archive in conforming to the specification.

   - bpo-28321(30): Fixed writing non-BMP characters with binary format
     in plistlib.

   - bpo-28322(31): Fixed possible crashes when unpickle itertools
     objects from incorrect pickle data.  Based on patch by John Leitch.

   - Fix possible integer overflows and crashes in the mmap module with
     unusual usage patterns.

   - bpo-1703178(32): Fix the ability to pass the –link-objects option
     to the distutils build_ext command.

   - bpo-28253(33): Fixed calendar functions for extreme months: 0001-01
     and 9999-12.  Methods itermonthdays() and itermonthdays2() are
     reimplemented so that they don’t call itermonthdates() which can
     cause datetime.date under/overflow.

   - bpo-28275(34): Fixed possible use after free in the decompress()
     methods of the LZMADecompressor and BZ2Decompressor classes.
     Original patch by John Leitch.

   - bpo-27897(35): Fixed possible crash in
     sqlite3.Connection.create_collation() if pass invalid string-like
     object as a name.  Patch by Xiang Zhang.

   - bpo-18893(36): Fix invalid exception handling in
     Lib/ctypes/macholib/dyld.py.  Patch by Madison May.

   - bpo-27611(37): Fixed support of default root window in the
     tkinter.tix module.

   - bpo-27348(38): In the traceback module, restore the formatting of
     exception messages like "Exception: None".  This fixes a regression
     introduced in 3.5a2.

   - bpo-25651(39): Allow falsy values to be used for msg parameter of
     subTest().

   - bpo-27932(40): Prevent memory leak in win32_ver().

   - Fix UnboundLocalError in socket._sendfile_use_sendfile.

   - bpo-28075(41): Check for ERROR_ACCESS_DENIED in Windows
     implementation of os.stat().  Patch by Eryk Sun.

   - bpo-25270(42): Prevent codecs.escape_encode() from raising
     SystemError when an empty bytestring is passed.

   - bpo-28181(43): Get antigravity over HTTPS. Patch by Kaartic
     Sivaraam.

   - bpo-25895(44): Enable WebSocket URL schemes in
     urllib.parse.urljoin.  Patch by Gergely Imreh and Markus
     Holtermann.

   - bpo-27599(45): Fixed buffer overrun in binascii.b2a_qp() and
     binascii.a2b_qp().

   - bpo-19003(46): m email.generator now replaces only ‘\r’ and/or ‘\n’
     line endings, per the RFC, instead of all unicode line endings.

   - bpo-28019(47): itertools.count() no longer rounds non-integer step
     in range between 1.0 and 2.0 to 1.

   - bpo-25969(48): Update the lib2to3 grammar to handle the unpacking
     generalizations added in 3.5.

   - bpo-14977(49): mailcap now respects the order of the lines in the
     mailcap files ("first match"), as required by RFC 1542.  Patch by
     Michael Lazar.

   - bpo-24594(50): Validates persist parameter when opening MSI
     database

   - bpo-17582(51): xml.etree.ElementTree nows preserves whitespaces in
     attributes (Patch by Duane Griffin.  Reviewed and approved by
     Stefan Behnel.)

   - bpo-28047(52): Fixed calculation of line length used for the base64
     CTE in the new email policies.

   - bpo-27445(53): Don’t pass str(_charset) to MIMEText.set_payload().
     Patch by Claude Paroz.

   - bpo-22450(54): urllib now includes an ‘Accept: */*’ header among
     the default headers.  This makes the results of REST API requests
     more consistent and predictable especially when proxy servers are
     involved.

   - lib2to3.pgen3.driver.load_grammar() now creates a stable cache file
     between runs given the same Grammar.txt input regardless of the
     hash randomization setting.

   - bpo-27570(55): Avoid zero-length memcpy() etc calls with null
     source pointers in the "ctypes" and "array" modules.

   - bpo-22233(56): Break email header lines `only' on the RFC specified
     CR and LF characters, not on arbitrary unicode line breaks.  This
     also fixes a bug in HTTP header parsing.

   - bpo-27988(57): Fix email iter_attachments incorrect mutation of
     payload list.

   - bpo-27691(58): Fix ssl module’s parsing of GEN_RID subject
     alternative name fields in X.509 certs.

   - bpo-27850(59): Remove 3DES from ssl module’s default cipher list to
     counter measure sweet32 attack (CVE-2016-2183).

   - bpo-27766(60): Add ChaCha20 Poly1305 to ssl module’s default cipher
     list.  (Required OpenSSL 1.1.0 or LibreSSL).

   - bpo-26470(61): Port ssl and hashlib module to OpenSSL 1.1.0.

   - Remove support for passing a file descriptor to os.access.  It
     never worked but previously didn’t raise.

   - bpo-12885(62): Fix error when distutils encounters symlink.

   - bpo-27881(63): Fixed possible bugs when setting
     sqlite3.Connection.isolation_level.  Based on patch by Xiang Zhang.

   - bpo-27861(64): Fixed a crash in sqlite3.Connection.cursor() when a
     factory creates not a cursor.  Patch by Xiang Zhang.

   - bpo-19884(65): Avoid spurious output on OS X with Gnu Readline.

   - bpo-27706(66): Restore deterministic behavior of
     random.Random().seed() for string seeds using seeding version 1.
     Allows sequences of calls to random() to exactly match those
     obtained in Python 2.  Patch by Nofar Schnider.

   - bpo-10513(67): Fix a regression in Connection.commit().  Statements
     should not be reset after a commit.

   - A new version of typing.py from ‘https://github.com/python/typing’:
     Collection (only for 3.6) (bpo-27598(68)).  Add FrozenSet to
     __all__ (upstream #261).  Fix crash in _get_type_vars() (upstream
     #259).  Remove the dict constraint in ForwardRef._eval_type
     (upstream #252).

   - bpo-27539(69): Fix unnormalised ‘Fraction.__pow__’ result in the
     case of negative exponent and negative base.

   - bpo-21718(70): cursor.description is now available for queries
     using CTEs.

   - bpo-2466(71): posixpath.ismount now correctly recognizes mount
     points which the user does not have permission to access.

   - bpo-27773(72): Correct some memory management errors
     server_hostname in _ssl.wrap_socket().

   - bpo-26750(73): unittest.mock.create_autospec() now works properly
     for subclasses of property() and other data descriptors.

   - In the curses module, raise an error if window.getstr() or
     window.instr() is passed a negative value.

   - bpo-27783(74): Fix possible usage of uninitialized memory in
     operator.methodcaller.

   - bpo-27774(75): Fix possible Py_DECREF on unowned object in _sre.

   - bpo-27760(76): Fix possible integer overflow in binascii.b2a_qp.

   - bpo-27758(77): Fix possible integer overflow in the _csv module for
     large record lengths.

   - bpo-27568(78): Prevent HTTPoxy attack (CVE-2016-1000110).  Ignore
     the HTTP_PROXY variable when REQUEST_METHOD environment is set,
     which indicates that the script is in CGI mode.

   - bpo-27656(79): Do not assume sched.h defines any SCHED_* constants.

   - bpo-27130(80): In the "zlib" module, fix handling of large buffers
     (typically 4 GiB) when compressing and decompressing.  Previously,
     inputs were limited to 4 GiB, and compression and decompression
     operations did not properly handle results of 4 GiB.

   - bpo-27533(81): Release GIL in nt._isdir

   - bpo-17711(82): Fixed unpickling by the persistent ID with protocol
     0.  Original patch by Alexandre Vassalotti.

   - bpo-27522(83): Avoid an unintentional reference cycle in
     email.feedparser.

   - bpo-26844(84): Fix error message for imp.find_module() to refer to
     ’path’ instead of ’name’.  Patch by Lev Maximov.

   - bpo-23804(85): Fix SSL zero-length recv() calls to not block and
     not raise an error about unclean EOF.

   - bpo-27466(86): Change time format returned by
     http.cookie.time2netscape, confirming the netscape cookie format
     and making it consistent with documentation.

   - bpo-26664(87): Fix activate.fish by removing mis-use of ‘$’.

   - bpo-22115(88): Fixed tracing Tkinter variables: trace_vdelete()
     with wrong mode no longer break tracing, trace_vinfo() now always
     returns a list of pairs of strings, tracing in the "u" mode now
     works.

   - Fix a scoping issue in importlib.util.LazyLoader which triggered an
     UnboundLocalError when lazy-loading a module that was already put
     into sys.modules.

   - bpo-27079(89): Fixed curses.ascii functions isblank(), iscntrl()
     and ispunct().

   - bpo-26754(90): Some functions (compile() etc) accepted a filename
     argument encoded as an iterable of integers.  Now only strings and
     byte-like objects are accepted.

   - bpo-27048(91): Prevents distutils failing on Windows when
     environment variables contain non-ASCII characters

   - bpo-27330(92): Fixed possible leaks in the ctypes module.

   - bpo-27238(93): Got rid of bare excepts in the turtle module.
     Original patch by Jelle Zijlstra.

   - bpo-27122(94): When an exception is raised within the context being
     managed by a contextlib.ExitStack() and one of the exit stack
     generators catches and raises it in a chain, do not re-raise the
     original exception when exiting, let the new chained one through.
     This avoids the PEP 479(95) bug described in issue25782.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15812

   (2) https://bugs.python.org/issue29094

   (3) https://bugs.python.org/issue13051

   (4) https://bugs.python.org/issue29119

   (5) https://bugs.python.org/issue9770

   (6) https://bugs.python.org/issue28427

   (7) https://bugs.python.org/issue28923

   (8) https://bugs.python.org/issue28871

   (9) https://bugs.python.org/issue19542

   (10) https://bugs.python.org/issue20191

   (11) https://bugs.python.org/issue28779

   (12) https://bugs.python.org/issue28847

   (13) https://bugs.python.org/issue25659

   (14) https://bugs.python.org/issue28732

   (15) https://bugs.python.org/issue28485

   (16) https://bugs.python.org/issue28387

   (17) https://bugs.python.org/issue27517

   (18) https://bugs.python.org/issue28549

   (19) https://bugs.python.org/issue28449

   (20) https://bugs.python.org/issue23262

   (21) https://bugs.python.org/issue27939

   (22) https://bugs.python.org/issue28255

   (23) https://bugs.python.org/issue20491

   (24) https://bugs.python.org/issue28353

   (25) https://bugs.python.org/issue25464

   (26) https://bugs.python.org/issue28488

   (27) https://bugs.python.org/issue24452

   (28) https://bugs.python.org/issue20766

   (29) https://bugs.python.org/issue26293

   (30) https://bugs.python.org/issue28321

   (31) https://bugs.python.org/issue28322

   (32) https://bugs.python.org/issue1703178

   (33) https://bugs.python.org/issue28253

   (34) https://bugs.python.org/issue28275

   (35) https://bugs.python.org/issue27897

   (36) https://bugs.python.org/issue18893

   (37) https://bugs.python.org/issue27611

   (38) https://bugs.python.org/issue27348

   (39) https://bugs.python.org/issue25651

   (40) https://bugs.python.org/issue27932

   (41) https://bugs.python.org/issue28075

   (42) https://bugs.python.org/issue25270

   (43) https://bugs.python.org/issue28181

   (44) https://bugs.python.org/issue25895

   (45) https://bugs.python.org/issue27599

   (46) https://bugs.python.org/issue19003

   (47) https://bugs.python.org/issue28019

   (48) https://bugs.python.org/issue25969

   (49) https://bugs.python.org/issue14977

   (50) https://bugs.python.org/issue24594

   (51) https://bugs.python.org/issue17582

   (52) https://bugs.python.org/issue28047

   (53) https://bugs.python.org/issue27445

   (54) https://bugs.python.org/issue22450

   (55) https://bugs.python.org/issue27570

   (56) https://bugs.python.org/issue22233

   (57) https://bugs.python.org/issue27988

   (58) https://bugs.python.org/issue27691

   (59) https://bugs.python.org/issue27850

   (60) https://bugs.python.org/issue27766

   (61) https://bugs.python.org/issue26470

   (62) https://bugs.python.org/issue12885

   (63) https://bugs.python.org/issue27881

   (64) https://bugs.python.org/issue27861

   (65) https://bugs.python.org/issue19884

   (66) https://bugs.python.org/issue27706

   (67) https://bugs.python.org/issue10513

   (68) https://bugs.python.org/issue27598

   (69) https://bugs.python.org/issue27539

   (70) https://bugs.python.org/issue21718

   (71) https://bugs.python.org/issue2466

   (72) https://bugs.python.org/issue27773

   (73) https://bugs.python.org/issue26750

   (74) https://bugs.python.org/issue27783

   (75) https://bugs.python.org/issue27774

   (76) https://bugs.python.org/issue27760

   (77) https://bugs.python.org/issue27758

   (78) https://bugs.python.org/issue27568

   (79) https://bugs.python.org/issue27656

   (80) https://bugs.python.org/issue27130

   (81) https://bugs.python.org/issue27533

   (82) https://bugs.python.org/issue17711

   (83) https://bugs.python.org/issue27522

   (84) https://bugs.python.org/issue26844

   (85) https://bugs.python.org/issue23804

   (86) https://bugs.python.org/issue27466

   (87) https://bugs.python.org/issue26664

   (88) https://bugs.python.org/issue22115

   (89) https://bugs.python.org/issue27079

   (90) https://bugs.python.org/issue26754

   (91) https://bugs.python.org/issue27048

   (92) https://bugs.python.org/issue27330

   (93) https://bugs.python.org/issue27238

   (94) https://bugs.python.org/issue27122

   (95) https://www.python.org/dev/peps/pep-0479


File: python.info,  Node: 安全<38>,  Next: 库<69>,  Prev: 库<68>,  Up: Python 3 5 3 rc1

1.18.71.3 安全
..............

   - bpo-27278(1): Fix os.urandom() implementation using getrandom() on
     Linux.  Truncate size to INT_MAX and loop until we collected enough
     random bytes, instead of casting a directly Py_ssize_t to int.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27278


File: python.info,  Node: 库<69>,  Next: 安全<39>,  Prev: 安全<38>,  Up: Python 3 5 3 rc1

1.18.71.4 库
............

   - bpo-26386(1): Fixed ttk.TreeView selection operations with item
     id’s containing spaces.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26386


File: python.info,  Node: 安全<39>,  Next: 库<70>,  Prev: 库<69>,  Up: Python 3 5 3 rc1

1.18.71.5 安全
..............

   - bpo-22636(1): Avoid shell injection problems with
     ctypes.util.find_library().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22636


File: python.info,  Node: 库<70>,  Next: IDLE<47>,  Prev: 安全<39>,  Up: Python 3 5 3 rc1

1.18.71.6 库
............

   - bpo-16182(1): Fix various functions in the "readline" module to use
     the locale encoding, and fix get_begidx() and get_endidx() to
     return code point indexes.

   - bpo-27392(2): Add loop.connect_accepted_socket().  Patch by Jim
     Fulton.

   - bpo-27930(3): Improved behaviour of logging.handlers.QueueListener.
     Thanks to Paulo Andrade and Petr Viktorin for the analysis and
     patch.

   - bpo-21201(4): Improves readability of multiprocessing error
     message.  Thanks to Wojciech Walczak for patch.

   - bpo-27456(5): asyncio: Set TCP_NODELAY by default.

   - bpo-27906(6): Fix socket accept exhaustion during high TCP traffic.
     Patch by Kevin Conway.

   - bpo-28174(7): Handle when SO_REUSEPORT isn’t properly supported.
     Patch by Seth Michael Larson.

   - bpo-26654(8): Inspect functools.partial in asyncio.Handle.__repr__.
     Patch by iceboy.

   - bpo-26909(9): Fix slow pipes IO in asyncio.  Patch by INADA Naoki.

   - bpo-28176(10): Fix callbacks race in
     asyncio.SelectorLoop.sock_connect.

   - bpo-27759(11): Fix selectors incorrectly retain invalid file
     descriptors.  Patch by Mark Williams.

   - bpo-28368(12): Refuse monitoring processes if the child watcher has
     no loop attached.  Patch by Vincent Michel.

   - bpo-28369(13): Raise RuntimeError when transport’s FD is used with
     add_reader, add_writer, etc.

   - bpo-28370(14): Speedup asyncio.StreamReader.readexactly.  Patch by
     Коренберг Марк.

   - bpo-28371(15): Deprecate passing asyncio.Handles to
     run_in_executor.

   - bpo-28372(16): Fix asyncio to support formatting of non-python
     coroutines.

   - bpo-28399(17): Remove UNIX socket from FS before binding.  Patch by
     Коренберг Марк.

   - bpo-27972(18): Prohibit Tasks to await on themselves.

   - bpo-26923(19): Fix asyncio.Gather to refuse being cancelled once
     all children are done.  Patch by Johannes Ebke.

   - bpo-26796(20): Don’t configure the number of workers for default
     threadpool executor.  Initial patch by Hans Lawrenz.

   - bpo-28600(21): Optimize loop.call_soon().

   - bpo-28613(22): Fix get_event_loop() return the current loop if
     called from coroutines/callbacks.

   - bpo-28639(23): Fix inspect.isawaitable to always return bool Patch
     by Justin Mayfield.

   - bpo-28652(24): Make loop methods reject socket kinds they do not
     support.

   - bpo-28653(25): Fix a refleak in functools.lru_cache.

   - bpo-28703(26): Fix asyncio.iscoroutinefunction to handle Mock
     objects.

   - bpo-24142(27): Reading a corrupt config file left the parser in an
     invalid state.  Original patch by Florian Höch.

   - bpo-28990(28): Fix SSL hanging if connection is closed before
     handshake completed.  (Patch by HoHo-Ho)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16182

   (2) https://bugs.python.org/issue27392

   (3) https://bugs.python.org/issue27930

   (4) https://bugs.python.org/issue21201

   (5) https://bugs.python.org/issue27456

   (6) https://bugs.python.org/issue27906

   (7) https://bugs.python.org/issue28174

   (8) https://bugs.python.org/issue26654

   (9) https://bugs.python.org/issue26909

   (10) https://bugs.python.org/issue28176

   (11) https://bugs.python.org/issue27759

   (12) https://bugs.python.org/issue28368

   (13) https://bugs.python.org/issue28369

   (14) https://bugs.python.org/issue28370

   (15) https://bugs.python.org/issue28371

   (16) https://bugs.python.org/issue28372

   (17) https://bugs.python.org/issue28399

   (18) https://bugs.python.org/issue27972

   (19) https://bugs.python.org/issue26923

   (20) https://bugs.python.org/issue26796

   (21) https://bugs.python.org/issue28600

   (22) https://bugs.python.org/issue28613

   (23) https://bugs.python.org/issue28639

   (24) https://bugs.python.org/issue28652

   (25) https://bugs.python.org/issue28653

   (26) https://bugs.python.org/issue28703

   (27) https://bugs.python.org/issue24142

   (28) https://bugs.python.org/issue28990


File: python.info,  Node: IDLE<47>,  Next: C API<35>,  Prev: 库<70>,  Up: Python 3 5 3 rc1

1.18.71.7 IDLE
..............

   - bpo-15308(1): Add ’interrupt execution’ (^C) to Shell menu.  Patch
     by Roger Serwy, updated by Bayard Randel.

   - bpo-27922(2): Stop IDLE tests from ’flashing’ gui widgets on the
     screen.

   - 在 IDLE 帮助窗口的标题中加入版本号

   - bpo-25564(3): In section on IDLE – console differences, mention
     that using exec means that __builtins__ is defined for each
     statement.

   - bpo-27714(4): text_textview and test_autocomplete now pass when
     re-run in the same process.  This occurs when test_idle fails when
     run with the -w option but without -jn.  Fix warning from
     test_config.

   - bpo-25507(5): IDLE no longer runs buggy code because of its tkinter
     imports.  Users must include the same imports required to run
     directly in Python.

   - bpo-27452(6): add line counter and crc to IDLE configHandler test
     dump.

   - bpo-27365(7): Allow non-ascii chars in IDLE NEWS.txt, for
     contributor names.

   - bpo-27245(8): IDLE: Cleanly delete custom themes and key bindings.
     Previously, when IDLE was started from a console or by import, a
     cascade of warnings was emitted.  Patch by Serhiy Storchaka.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15308

   (2) https://bugs.python.org/issue27922

   (3) https://bugs.python.org/issue25564

   (4) https://bugs.python.org/issue27714

   (5) https://bugs.python.org/issue25507

   (6) https://bugs.python.org/issue27452

   (7) https://bugs.python.org/issue27365

   (8) https://bugs.python.org/issue27245


File: python.info,  Node: C API<35>,  Next: 文档<48>,  Prev: IDLE<47>,  Up: Python 3 5 3 rc1

1.18.71.8 C API
...............

   - bpo-28808(1): PyUnicode_CompareWithASCIIString() now never raises
     exceptions.

   - bpo-26754(2): PyUnicode_FSDecoder() accepted a filename argument
     encoded as an iterable of integers.  Now only strings and
     bytes-like objects are accepted.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28808

   (2) https://bugs.python.org/issue26754


File: python.info,  Node: 文档<48>,  Next: 测试<45>,  Prev: C API<35>,  Up: Python 3 5 3 rc1

1.18.71.9 文档
..............

   - bpo-28513(1): Documented command-line interface of zipfile.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28513


File: python.info,  Node: 测试<45>,  Next: 工具/示例<30>,  Prev: 文档<48>,  Up: Python 3 5 3 rc1

1.18.71.10 测试
...............

   - bpo-28950(1): Disallow -j0 to be combined with -T/-l/-M in regrtest
     command line arguments.

   - bpo-28666(2): Now test.support.rmtree is able to remove unwritable
     or unreadable directories.

   - bpo-23839(3): Various caches now are cleared before running every
     test file.

   - bpo-28409(4): regrtest: fix the parser of command line arguments.

   - bpo-27787(5): Call gc.collect() before checking each test for
     "dangling threads", since the dangling threads are weak references.

   - bpo-27369(6): In test_pyexpat, avoid testing an error message
     detail that changed in Expat 2.2.0.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28950

   (2) https://bugs.python.org/issue28666

   (3) https://bugs.python.org/issue23839

   (4) https://bugs.python.org/issue28409

   (5) https://bugs.python.org/issue27787

   (6) https://bugs.python.org/issue27369


File: python.info,  Node: 工具/示例<30>,  Next: Windows<46>,  Prev: 测试<45>,  Up: Python 3 5 3 rc1

1.18.71.11 工具/示例
....................

   - bpo-27952(1): Get Tools/scripts/fixcid.py working with Python 3 and
     the current "re" module, avoid invalid Python backslash escapes,
     and fix a bug parsing escaped C quote signs.

   - bpo-27332(2): Fixed the type of the first argument of module-level
     functions generated by Argument Clinic.  Patch by Petr Viktorin.

   - bpo-27418(3): Fixed Tools/importbench/importbench.py.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27952

   (2) https://bugs.python.org/issue27332

   (3) https://bugs.python.org/issue27418


File: python.info,  Node: Windows<46>,  Next: 构建<46>,  Prev: 工具/示例<30>,  Up: Python 3 5 3 rc1

1.18.71.12 Windows
..................

   - bpo-28251(1): Improvements to help manuals on Windows.

   - bpo-28110(2): launcher.msi has different product codes between
     32-bit and 64-bit

   - bpo-25144(3): Ensures TargetDir is set before continuing with
     custom install.

   - bpo-27469(4): Adds a shell extension to the launcher so that drag
     and drop works correctly.

   - bpo-27309(5): Enabled proper Windows styles in python[w].exe
     manifest.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28251

   (2) https://bugs.python.org/issue28110

   (3) https://bugs.python.org/issue25144

   (4) https://bugs.python.org/issue27469

   (5) https://bugs.python.org/issue27309


File: python.info,  Node: 构建<46>,  Prev: Windows<46>,  Up: Python 3 5 3 rc1

1.18.71.13 构建
...............

   - bpo-29080(1): Removes hard dependency on hg.exe from
     PCBuild/build.bat

   - bpo-23903(2): Added missed names to PC/python3.def.

   - bpo-10656(3): Fix out-of-tree building on AIX. Patch by Tristan
     Carel and Michael Haubenwallner.

   - bpo-26359(4): Rename –with-optimiations to –enable-optimizations.

   - bpo-28444(5): Fix missing extensions modules when cross compiling.

   - bpo-28248(6): 更新Windows 构建和OS X安装程序以使用OpenSSL 1.0.2j.

   - bpo-28258(7): Fixed build with Estonian locale (python-config and
     distclean targets in Makefile).  Patch by Arfrever Frehtes
     Taifersar Arahesis.

   - bpo-26661(8): setup.py now detects system libffi with multiarch
     wrapper.

   - bpo-28066(9): Fix the logic that searches build directories for
     generated include files when building outside the source tree.

   - bpo-15819(10): Remove redundant include search directory option for
     building outside the source tree.

   - bpo-27566(11): Fix clean target in freeze makefile (patch by Lisa
     Roach)

   - bpo-27705(12): Update message in validate_ucrtbase.py

   - bpo-27983(13): Cause lack of llvm-profdata tool when using clang as
     required for PGO linking to be a configure time error rather than
     make time when –with-optimizations is enabled.  Also improve our
     ability to find the llvm-profdata tool on MacOS and some Linuxes.

   - bpo-26307(14): The profile-opt build now applies PGO to the
     built-in modules.

   - bpo-26359(15): Add the –with-optimizations configure flag.

   - bpo-27713(16): Suppress spurious build warnings when updating
     importlib’s bootstrap files.  Patch by Xiang Zhang

   - bpo-25825(17): Correct the references to Modules/python.exp and
     ld_so_aix, which are required on AIX. This updates references to an
     installation path that was changed in 3.2a4, and undoes changed
     references to the build tree that were made in 3.5.0a1.

   - bpo-27453(18): CPP invocation in configure must use CPPFLAGS. Patch
     by Chi Hsuan Yen.

   - bpo-27641(19): The configure script now inserts comments into the
     makefile to prevent the pgen and _freeze_importlib executables from
     being cross-compiled.

   - bpo-26662(20): Set PYTHON_FOR_GEN in configure as the Python
     program to be used for file generation during the build.

   - bpo-10910(21): Avoid C++ compilation errors on FreeBSD and OS X.
     Also update FreedBSD version checks for the original ctype UTF-8
     workaround.

   - bpo-28676(22): Prevent missing ’getentropy’ declaration warning on
     macOS. Patch by Gareth Rees.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29080

   (2) https://bugs.python.org/issue23903

   (3) https://bugs.python.org/issue10656

   (4) https://bugs.python.org/issue26359

   (5) https://bugs.python.org/issue28444

   (6) https://bugs.python.org/issue28248

   (7) https://bugs.python.org/issue28258

   (8) https://bugs.python.org/issue26661

   (9) https://bugs.python.org/issue28066

   (10) https://bugs.python.org/issue15819

   (11) https://bugs.python.org/issue27566

   (12) https://bugs.python.org/issue27705

   (13) https://bugs.python.org/issue27983

   (14) https://bugs.python.org/issue26307

   (15) https://bugs.python.org/issue26359

   (16) https://bugs.python.org/issue27713

   (17) https://bugs.python.org/issue25825

   (18) https://bugs.python.org/issue27453

   (19) https://bugs.python.org/issue27641

   (20) https://bugs.python.org/issue26662

   (21) https://bugs.python.org/issue10910

   (22) https://bugs.python.org/issue28676


File: python.info,  Node: Python 3 5 2 正式版,  Next: Python 3 5 2 rc1,  Prev: Python 3 5 3 rc1,  Up: 更新日志

1.18.72 Python 3.5.2 正式版
---------------------------

`发布日期: 2016-06-26'

* Menu:

* 核心与内置: 核心与内置<60>.
* 测试: 测试<46>.
* IDLE: IDLE<48>.


File: python.info,  Node: 核心与内置<60>,  Next: 测试<46>,  Up: Python 3 5 2 正式版

1.18.72.1 核心与内置
....................

   - bpo-26930(1): 更新Windows 构建以使用OpenSSL OpenSSL 1.0.2h.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26930


File: python.info,  Node: 测试<46>,  Next: IDLE<48>,  Prev: 核心与内置<60>,  Up: Python 3 5 2 正式版

1.18.72.2 测试
..............

   - bpo-26867(1): Ubuntu’s openssl OP_NO_SSLv3 is forced on by default;
     fix test.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26867


File: python.info,  Node: IDLE<48>,  Prev: 测试<46>,  Up: Python 3 5 2 正式版

1.18.72.3 IDLE
..............

   - bpo-27365(1): Allow non-ascii in idlelib/NEWS.txt - minimal part
     for 3.5.2.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27365


File: python.info,  Node: Python 3 5 2 rc1,  Next: Python 3 5 1 正式版,  Prev: Python 3 5 2 正式版,  Up: 更新日志

1.18.73 Python 3.5.2 rc1
------------------------

`发布日期: 2016-06-12'

* Menu:

* 核心与内置: 核心与内置<61>.
* 安全: 安全<40>.
* 库: 库<71>.
* 安全: 安全<41>.
* 库: 库<72>.
* 安全: 安全<42>.
* 库: 库<73>.
* 安全: 安全<43>.
* 库: 库<74>.
* 安全: 安全<44>.
* 库: 库<75>.
* IDLE: IDLE<49>.
* 文档: 文档<49>.
* 测试: 测试<47>.
* 构建: 构建<47>.
* Windows: Windows<47>.
* 工具/示例: 工具/示例<31>.
* Windows: Windows<48>.


File: python.info,  Node: 核心与内置<61>,  Next: 安全<40>,  Up: Python 3 5 2 rc1

1.18.73.1 核心与内置
....................

   - bpo-27066(1): Fixed SystemError if a custom opener (for open())
     returns a negative number without setting an exception.

   - bpo-20041(2): Fixed TypeError when frame.f_trace is set to None.
     Patch by Xavier de Gaye.

   - bpo-26168(3): Fixed possible refleaks in failing Py_BuildValue()
     with the "N" format unit.

   - bpo-26991(4): Fix possible refleak when creating a function with
     annotations.

   - bpo-27039(5): Fixed bytearray.remove() for values greater than 127.
     Patch by Joe Jevnik.

   - bpo-23640(6): int.from_bytes() no longer bypasses constructors for
     subclasses.

   - bpo-26811(7): gc.get_objects() no longer contains a broken tuple
     with NULL pointer.

   - bpo-20120(8): Use RawConfigParser for .pypirc parsing, removing
     support for interpolation unintentionally added with move to Python
     3.  Behavior no longer does any interpolation in .pypirc files,
     matching behavior in Python 2.7 and Setuptools 19.0.

   - bpo-26659(9): Make the builtin slice type support cycle collection.

   - bpo-26718(10): super.__init__ no longer leaks memory if called
     multiple times.  NOTE: A direct call of super.__init__ is not
     endorsed!

   - bpo-25339(11): PYTHONIOENCODING now has priority over locale in
     setting the error handler for stdin and stdout.

   - bpo-26494(12): Fixed crash on iterating exhausting iterators.
     Affected classes are generic sequence iterators, iterators of str,
     bytes, bytearray, list, tuple, set, frozenset, dict, OrderedDict,
     corresponding views and os.scandir() iterator.

   - bpo-26581(13): If coding cookie is specified multiple times on a
     line in Python source code file, only the first one is taken to
     account.

   - bpo-26464(14): Fix str.translate() when string is ASCII and first
     replacements removes character, but next replacement uses a
     non-ASCII character or a string longer than 1 character.
     Regression introduced in Python 3.5.0.

   - bpo-22836(15): Ensure exception reports from PyErr_Display() and
     PyErr_WriteUnraisable() are sensible even when formatting them
     produces secondary errors.  This affects the reports produced by
     sys.__excepthook__() and when __del__() raises an exception.

   - bpo-26302(16): Correct behavior to reject comma as a legal
     character for cookie names.

   - bpo-4806(17): Avoid masking the original TypeError exception when
     using star (‘*’) unpacking in function calls.  Based on patch by
     Hagen Fürstenau and Daniel Urban.

   - bpo-27138(18): Fix the doc comment for FileFinder.find_spec().

   - bpo-26154(19): Add a new private _PyThreadState_UncheckedGet()
     function to get the current Python thread state, but don’t issue a
     fatal error if it is NULL. This new function must be used instead
     of accessing directly the _PyThreadState_Current variable.  The
     variable is no more exposed since Python 3.5.1 to hide the exact
     implementation of atomic C types, to avoid compiler issues.

   - bpo-26194(20): Deque.insert() gave odd results for bounded deques
     that had reached their maximum size.  Now an IndexError will be
     raised when attempting to insert into a full deque.

   - bpo-25843(21): When compiling code, don’t merge constants if they
     are equal but have a different types.  For example, ‘f1, f2 =
     lambda: 1, lambda: 1.0’ is now correctly compiled to two different
     functions: ‘f1()’ returns ‘1’ (‘int’) and ‘f2()’ returns ‘1.0’
     (‘int’), even if ‘1’ and ‘1.0’ are equal.

   - bpo-22995(22): [UPDATE] Comment out the one of the pickleability
     tests in _PyObject_GetState() due to regressions observed in
     Cython-based projects.

   - bpo-25961(23): Disallowed null characters in the type name.

   - bpo-25973(24): Fix segfault when an invalid nonlocal statement
     binds a name starting with two underscores.

   - bpo-22995(25): Instances of extension types with a state that
     aren’t subclasses of list or dict and haven’t implemented any
     pickle-related methods (__reduce__, __reduce_ex__, __getnewargs__,
     __getnewargs_ex__, or __getstate__), can no longer be pickled.
     Including memoryview.

   - bpo-20440(26): Massive replacing unsafe attribute setting code with
     special macro Py_SETREF.

   - bpo-25766(27): Special method __bytes__() now works in str
     subclasses.

   - bpo-25421(28): __sizeof__ methods of builtin types now use dynamic
     basic size.  This allows sys.getsize() to work correctly with their
     subclasses with __slots__ defined.

   - bpo-25709(29): Fixed problem with in-place string concatenation and
     utf-8 cache.

   - bpo-27147(30): Mention PEP 420(31) in the importlib docs.

   - bpo-24097(32): Fixed crash in object.__reduce__() if slot name is
     freed inside __getattr__.

   - bpo-24731(33): Fixed crash on converting objects with special
     methods __bytes__, __trunc__, and __float__ returning instances of
     subclasses of bytes, int, and float to subclasses of bytes, int,
     and float correspondingly.

   - bpo-26478(34): Fix semantic bugs when using binary operators with
     dictionary views and tuples.

   - bpo-26171(35): Fix possible integer overflow and heap corruption in
     zipimporter.get_data().

   - bpo-25660(36): Fix TAB key behaviour in REPL with readline.

   - bpo-25887(37): Raise a RuntimeError when a coroutine object is
     awaited more than once.

   - bpo-27243(38): Update the __aiter__ protocol: instead of returning
     an awaitable that resolves to an asynchronous iterator, the
     asynchronous iterator should be returned directly.  Doing the
     former will trigger a PendingDeprecationWarning.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27066

   (2) https://bugs.python.org/issue20041

   (3) https://bugs.python.org/issue26168

   (4) https://bugs.python.org/issue26991

   (5) https://bugs.python.org/issue27039

   (6) https://bugs.python.org/issue23640

   (7) https://bugs.python.org/issue26811

   (8) https://bugs.python.org/issue20120

   (9) https://bugs.python.org/issue26659

   (10) https://bugs.python.org/issue26718

   (11) https://bugs.python.org/issue25339

   (12) https://bugs.python.org/issue26494

   (13) https://bugs.python.org/issue26581

   (14) https://bugs.python.org/issue26464

   (15) https://bugs.python.org/issue22836

   (16) https://bugs.python.org/issue26302

   (17) https://bugs.python.org/issue4806

   (18) https://bugs.python.org/issue27138

   (19) https://bugs.python.org/issue26154

   (20) https://bugs.python.org/issue26194

   (21) https://bugs.python.org/issue25843

   (22) https://bugs.python.org/issue22995

   (23) https://bugs.python.org/issue25961

   (24) https://bugs.python.org/issue25973

   (25) https://bugs.python.org/issue22995

   (26) https://bugs.python.org/issue20440

   (27) https://bugs.python.org/issue25766

   (28) https://bugs.python.org/issue25421

   (29) https://bugs.python.org/issue25709

   (30) https://bugs.python.org/issue27147

   (31) https://www.python.org/dev/peps/pep-0420

   (32) https://bugs.python.org/issue24097

   (33) https://bugs.python.org/issue24731

   (34) https://bugs.python.org/issue26478

   (35) https://bugs.python.org/issue26171

   (36) https://bugs.python.org/issue25660

   (37) https://bugs.python.org/issue25887

   (38) https://bugs.python.org/issue27243


File: python.info,  Node: 安全<40>,  Next: 库<71>,  Prev: 核心与内置<61>,  Up: Python 3 5 2 rc1

1.18.73.2 安全
..............

   - bpo-26556(1): Update expat to 2.1.1, fixes CVE-2015-1283.

   - Fix TLS stripping vulnerability in smtplib, CVE-2016-0772.
     Reported by Team Oststrom

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26556


File: python.info,  Node: 库<71>,  Next: 安全<41>,  Prev: 安全<40>,  Up: Python 3 5 2 rc1

1.18.73.3 库
............

   - bpo-21386(1): Implement missing IPv4Address.is_global property.  It
     was documented since 07a5610bae9d.  Initial patch by Roger Luethi.

   - bpo-20900(2): distutils register command now decodes HTTP responses
     correctly.  Initial patch by ingrid.

   - A new version of typing.py provides several new classes and
     features: @overload outside stubs, Reversible, DefaultDict, Text,
     ContextManager, Type[], NewType(), TYPE_CHECKING, and numerous bug
     fixes (note that some of the new features are not yet implemented
     in mypy or other static analyzers).  Also classes for PEP 492(3)
     (Awaitable, AsyncIterable, AsyncIterator) have been added (in fact
     they made it into 3.5.1 but were never mentioned).

   - bpo-25738(4): Stop http.server.BaseHTTPRequestHandler.send_error()
     from sending a message body for 205 Reset Content.  Also, don’t
     send Content header fields in responses that don’t have a body.
     Patch by Susumu Koshiba.

   - bpo-21313(5): Fix the "platform" module to tolerate when
     sys.version contains truncated build information.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21386

   (2) https://bugs.python.org/issue20900

   (3) https://www.python.org/dev/peps/pep-0492

   (4) https://bugs.python.org/issue25738

   (5) https://bugs.python.org/issue21313


File: python.info,  Node: 安全<41>,  Next: 库<72>,  Prev: 库<71>,  Up: Python 3 5 2 rc1

1.18.73.4 安全
..............

   - bpo-26839(1): On Linux, *note os.urandom(): 4d9. now calls
     ‘getrandom()’ with ‘GRND_NONBLOCK’ to fall back on reading
     ‘/dev/urandom’ if the urandom entropy pool is not initialized yet.
     Patch written by Colm Buckley.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26839


File: python.info,  Node: 库<72>,  Next: 安全<42>,  Prev: 安全<41>,  Up: Python 3 5 2 rc1

1.18.73.5 库
............

   - bpo-27164(1): In the zlib module, allow decompressing raw Deflate
     streams with a predefined zdict.  Based on patch by Xiang Zhang.

   - bpo-24291(2): Fix wsgiref.simple_server.WSGIRequestHandler to
     completely write data to the client.  Previously it could do
     partial writes and truncate data.  Also,
     wsgiref.handler.ServerHandler can now handle stdout doing partial
     writes, but this is deprecated.

   - bpo-26809(3): Add ‘__all__’ to *note string: f7.  Patch by Emanuel
     Barry.

   - bpo-26373(4): subprocess.Popen.communicate now correctly ignores
     BrokenPipeError when the child process dies before .communicate()
     is called in more/all circumstances.

   - bpo-21776(5): distutils.upload now correctly handles HTTPError.
     Initial patch by Claudiu Popa.

   - bpo-27114(6): Fix SSLContext._load_windows_store_certs fails with
     PermissionError

   - bpo-18383(7): Avoid creating duplicate filters when using
     filterwarnings and simplefilter.  Based on patch by Alex Shkop.

   - bpo-27057(8): Fix os.set_inheritable() on Android, ioctl() is
     blocked by SELinux and fails with EACCESS. The function now falls
     back to fcntl().  Patch written by Michał Bednarski.

   - bpo-27014(9): Fix infinite recursion using typing.py.  Thanks to
     Kalle Tuure!

   - bpo-14132(10): Fix urllib.request redirect handling when the target
     only has a query string.  Original fix by Ján Janech.

   - bpo-17214(11): The "urllib.request" module now percent-encodes
     non-ASCII bytes found in redirect target URLs.  Some servers send
     Location header fields with non-ASCII bytes, but "http.client"
     requires the request target to be ASCII-encodable, otherwise a
     UnicodeEncodeError is raised.  Based on patch by Christian Heimes.

   - bpo-26892(12): Honor debuglevel flag in urllib.request.HTTPHandler.
     Patch contributed by Chi Hsuan Yen.

   - bpo-22274(13): In the subprocess module, allow stderr to be
     redirected to stdout even when stdout is not redirected.  Patch by
     Akira Li.

   - bpo-26807(14): mock_open ’files’ no longer error on readline at end
     of file.  Patch from Yolanda Robla.

   - bpo-25745(15): Fixed leaking a userptr in curses panel destructor.

   - bpo-26977(16): Removed unnecessary, and ignored, call to sum of
     squares helper in statistics.pvariance.

   - bpo-26881(17): The modulefinder module now supports extended opcode
     arguments.

   - bpo-23815(18): Fixed crashes related to directly created instances
     of types in _tkinter and curses.panel modules.

   - bpo-17765(19): weakref.ref() no longer silently ignores keyword
     arguments.  Patch by Georg Brandl.

   - bpo-26873(20): xmlrpc now raises ResponseError on unsupported type
     tags instead of silently return incorrect result.

   - bpo-26711(21): Fixed the comparison of plistlib.Data with other
     types.

   - bpo-24114(22): Fix an uninitialized variable in ‘ctypes.util’.  The
     bug only occurs on SunOS when the ctypes implementation searches
     for the ‘crle’ program.  Patch by Xiang Zhang.  Tested on SunOS by
     Kees Bos.

   - bpo-26864(23): In urllib.request, change the proxy bypass host
     checking against no_proxy to be case-insensitive, and to not match
     unrelated host names that happen to have a bypassed hostname as a
     suffix.  Patch by Xiang Zhang.

   - bpo-26634(24): recursive_repr() now sets __qualname__ of wrapper.
     Patch by Xiang Zhang.

   - bpo-26804(25): urllib.request will prefer lower_case proxy
     environment variables over UPPER_CASE or Mixed_Case ones.  Patch
     contributed by Hans-Peter Jansen.

   - bpo-26837(26): assertSequenceEqual() now correctly outputs
     non-stringified differing items (like bytes in the -b mode).  This
     affects assertListEqual() and assertTupleEqual().

   - bpo-26041(27): Remove "will be removed in Python 3.7" from
     deprecation messages of platform.dist() and
     platform.linux_distribution().  Patch by Kumaripaba Miyurusara
     Athukorala.

   - bpo-26822(28): itemgetter, attrgetter and methodcaller objects no
     longer silently ignore keyword arguments.

   - bpo-26733(29): Disassembling a class now disassembles class and
     static methods.  Patch by Xiang Zhang.

   - bpo-26801(30): Fix error handling in *note
     shutil.get_terminal_size(): a52, catch *note AttributeError: 3a3.
     instead of *note NameError: d83.  Patch written by Emanuel Barry.

   - bpo-24838(31): tarfile’s ustar and gnu formats now correctly
     calculate name and link field limits for multibyte character
     encodings like utf-8.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27164

   (2) https://bugs.python.org/issue24291

   (3) https://bugs.python.org/issue26809

   (4) https://bugs.python.org/issue26373

   (5) https://bugs.python.org/issue21776

   (6) https://bugs.python.org/issue27114

   (7) https://bugs.python.org/issue18383

   (8) https://bugs.python.org/issue27057

   (9) https://bugs.python.org/issue27014

   (10) https://bugs.python.org/issue14132

   (11) https://bugs.python.org/issue17214

   (12) https://bugs.python.org/issue26892

   (13) https://bugs.python.org/issue22274

   (14) https://bugs.python.org/issue26807

   (15) https://bugs.python.org/issue25745

   (16) https://bugs.python.org/issue26977

   (17) https://bugs.python.org/issue26881

   (18) https://bugs.python.org/issue23815

   (19) https://bugs.python.org/issue17765

   (20) https://bugs.python.org/issue26873

   (21) https://bugs.python.org/issue26711

   (22) https://bugs.python.org/issue24114

   (23) https://bugs.python.org/issue26864

   (24) https://bugs.python.org/issue26634

   (25) https://bugs.python.org/issue26804

   (26) https://bugs.python.org/issue26837

   (27) https://bugs.python.org/issue26041

   (28) https://bugs.python.org/issue26822

   (29) https://bugs.python.org/issue26733

   (30) https://bugs.python.org/issue26801

   (31) https://bugs.python.org/issue24838


File: python.info,  Node: 安全<42>,  Next: 库<73>,  Prev: 库<72>,  Up: Python 3 5 2 rc1

1.18.73.6 安全
..............

   - bpo-26657(1): Fix directory traversal vulnerability with
     http.server on Windows.  This fixes a regression that was
     introduced in 3.3.4rc1 and 3.4.0rc1.  Based on patch by Philipp
     Hagemeister.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26657


File: python.info,  Node: 库<73>,  Next: 安全<43>,  Prev: 安全<42>,  Up: Python 3 5 2 rc1

1.18.73.7 库
............

   - bpo-26717(1): Stop encoding Latin-1-ized WSGI paths with UTF-8.
     Patch by Anthony Sottile.

   - bpo-26735(2): Fix *note os.urandom(): 4d9. on Solaris 11.3 and
     newer when reading more than 1,024 bytes: call ‘getrandom()’
     multiple times with a limit of 1024 bytes per call.

   - bpo-16329(3): Add .webm to mimetypes.types_map.  Patch by Giampaolo
     Rodola’.

   - bpo-13952(4): Add .csv to mimetypes.types_map.  Patch by Geoff
     Wilson.

   - bpo-26709(5): Fixed Y2038 problem in loading binary PLists.

   - bpo-23735(6): Handle terminal resizing with Readline 6.3+ by
     installing our own SIGWINCH handler.  Patch by Eric Price.

   - bpo-26586(7): In http.server, respond with "413 Request header
     fields too large" if there are too many header fields to parse,
     rather than killing the connection and raising an unhandled
     exception.  Patch by Xiang Zhang.

   - bpo-22854(8): Change BufferedReader.writable() and
     BufferedWriter.readable() to always return False.

   - bpo-25195(9): Fix a regression in mock.MagicMock.  _Call is a
     subclass of tuple (changeset 3603bae63c13 only works for classes)
     so we need to implement __ne__ ourselves.  Patch by Andrew Plummer.

   - bpo-26644(10): Raise ValueError rather than SystemError when a
     negative length is passed to SSLSocket.recv() or read().

   - bpo-23804(11): Fix SSL recv(0) and read(0) methods to return zero
     bytes instead of up to 1024.

   - bpo-26616(12): Fixed a bug in datetime.astimezone() method.

   - bpo-21925(13): *note warnings.formatwarning(): 1002. now catches
     exceptions on ‘linecache.getline(...)’ to be able to log *note
     ResourceWarning: 4d8. emitted late during the Python shutdown
     process.

   - bpo-24266(14): Ctrl+C during Readline history search now cancels
     the search mode when compiled with Readline 7.

   - bpo-26560(15): Avoid potential ValueError in
     BaseHandler.start_response.  Initial patch by Peter Inglesby.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26717

   (2) https://bugs.python.org/issue26735

   (3) https://bugs.python.org/issue16329

   (4) https://bugs.python.org/issue13952

   (5) https://bugs.python.org/issue26709

   (6) https://bugs.python.org/issue23735

   (7) https://bugs.python.org/issue26586

   (8) https://bugs.python.org/issue22854

   (9) https://bugs.python.org/issue25195

   (10) https://bugs.python.org/issue26644

   (11) https://bugs.python.org/issue23804

   (12) https://bugs.python.org/issue26616

   (13) https://bugs.python.org/issue21925

   (14) https://bugs.python.org/issue24266

   (15) https://bugs.python.org/issue26560


File: python.info,  Node: 安全<43>,  Next: 库<74>,  Prev: 库<73>,  Up: Python 3 5 2 rc1

1.18.73.8 安全
..............

   - bpo-26313(1): ssl.py _load_windows_store_certs fails if windows
     cert store is empty.  Patch by Baji.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26313


File: python.info,  Node: 库<74>,  Next: 安全<44>,  Prev: 安全<43>,  Up: Python 3 5 2 rc1

1.18.73.9 库
............

   - bpo-26569(1): Fix *note pyclbr.readmodule(): 1179. and *note
     pyclbr.readmodule_ex(): 117a. to support importing packages.

   - bpo-26499(2): Account for remaining Content-Length in
     HTTPResponse.readline() and read1().  Based on patch by Silent
     Ghost.  Also document that HTTPResponse now supports these methods.

   - bpo-25320(3): Handle sockets in directories unittest discovery is
     scanning.  Patch from Victor van den Elzen.

   - bpo-16181(4): cookiejar.http2time() now returns None if year is
     higher than datetime.MAXYEAR.

   - bpo-26513(5): Fixes platform module detection of Windows Server

   - bpo-23718(6): Fixed parsing time in week 0 before Jan 1.  Original
     patch by Tamás Bence Gedai.

   - bpo-20589(7): Invoking Path.owner() and Path.group() on Windows now
     raise NotImplementedError instead of ImportError.

   - bpo-26177(8): Fixed the keys() method for Canvas and Scrollbar
     widgets.

   - bpo-15068(9): Got rid of excessive buffering in the fileinput
     module.  The bufsize parameter is no longer used.

   - bpo-2202(10): Fix UnboundLocalError in
     AbstractDigestAuthHandler.get_algorithm_impls.  Initial patch by
     Mathieu Dupuy.

   - bpo-25718(11): Fixed pickling and copying the accumulate() iterator
     with total is None.

   - bpo-26475(12): Fixed debugging output for regular expressions with
     the (?x) flag.

   - bpo-26457(13): Fixed the subnets() methods in IP network classes
     for the case when resulting prefix length is equal to maximal
     prefix length.  Based on patch by Xiang Zhang.

   - bpo-26385(14): Remove the file if the internal open() call in
     NamedTemporaryFile() fails.  Patch by Silent Ghost.

   - bpo-26402(15): Fix XML-RPC client to retry when the server shuts
     down a persistent connection.  This was a regression related to the
     new http.client.RemoteDisconnected exception in 3.5.0a4.

   - bpo-25913(16): Leading ‘<~’ is optional now in base64.a85decode()
     with adobe=True.  Patch by Swati Jaiswal.

   - bpo-26186(17): Remove an invalid type check in
     importlib.util.LazyLoader.

   - bpo-26367(18): importlib.__import__() raises SystemError like
     builtins.__import__() when ‘level’ is specified but without an
     accompanying package specified.

   - bpo-26309(19): In the "socketserver" module, shut down the request
     (closing the connected socket) when verify_request() returns false.
     Patch by Aviv Palivoda.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26569

   (2) https://bugs.python.org/issue26499

   (3) https://bugs.python.org/issue25320

   (4) https://bugs.python.org/issue16181

   (5) https://bugs.python.org/issue26513

   (6) https://bugs.python.org/issue23718

   (7) https://bugs.python.org/issue20589

   (8) https://bugs.python.org/issue26177

   (9) https://bugs.python.org/issue15068

   (10) https://bugs.python.org/issue2202

   (11) https://bugs.python.org/issue25718

   (12) https://bugs.python.org/issue26475

   (13) https://bugs.python.org/issue26457

   (14) https://bugs.python.org/issue26385

   (15) https://bugs.python.org/issue26402

   (16) https://bugs.python.org/issue25913

   (17) https://bugs.python.org/issue26186

   (18) https://bugs.python.org/issue26367

   (19) https://bugs.python.org/issue26309


File: python.info,  Node: 安全<44>,  Next: 库<75>,  Prev: 库<74>,  Up: Python 3 5 2 rc1

1.18.73.10 安全
...............

   - bpo-25939(1): On Windows open the cert store readonly in
     ssl.enum_certificates.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25939


File: python.info,  Node: 库<75>,  Next: IDLE<49>,  Prev: 安全<44>,  Up: Python 3 5 2 rc1

1.18.73.11 库
.............

   - bpo-25995(1): os.walk() no longer uses FDs proportional to the tree
     depth.

   - bpo-26117(2): The os.scandir() iterator now closes file descriptor
     not only when the iteration is finished, but when it was failed
     with error.

   - bpo-25911(3): Restored support of bytes paths in os.walk() on
     Windows.

   - bpo-26045(4): Add UTF-8 suggestion to error message when posting a
     non-Latin-1 string with http.client.

   - bpo-12923(5): Reset FancyURLopener’s redirect counter even if there
     is an exception.  Based on patches by Brian Brazil and Daniel
     Rocco.

   - bpo-25945(6): Fixed a crash when unpickle the functools.partial
     object with wrong state.  Fixed a leak in failed functools.partial
     constructor.  "args" and "keywords" attributes of functools.partial
     have now always types tuple and dict correspondingly.

   - bpo-26202(7): copy.deepcopy() now correctly copies range() objects
     with non-atomic attributes.

   - bpo-23076(8): Path.glob() now raises a ValueError if it’s called
     with an invalid pattern.  Patch by Thomas Nyberg.

   - bpo-19883(9): Fixed possible integer overflows in zipimport.

   - bpo-26227(10): On Windows, getnameinfo(), gethostbyaddr() and
     gethostbyname_ex() functions of the socket module now decode the
     hostname from the ANSI code page rather than UTF-8.

   - bpo-26147(11): xmlrpc now works with strings not encodable with
     used non-UTF-8 encoding.

   - bpo-25935(12): Garbage collector now breaks reference loops with
     OrderedDict.

   - bpo-16620(13): Fixed AttributeError in msilib.Directory.glob().

   - bpo-26013(14): Added compatibility with broken protocol 2 pickles
     created in old Python 3 versions (3.4.3 and lower).

   - bpo-25850(15): Use cross-compilation by default for 64-bit Windows.

   - bpo-17633(16): Improve zipimport’s support for namespace packages.

   - bpo-24705(17): Fix sysconfig._parse_makefile not expanding ${} vars
     appearing before $() vars.

   - bpo-22138(18): Fix mock.patch behavior when patching descriptors.
     Restore original values after patching.  Patch contributed by Sean
     McCully.

   - bpo-25672(19): In the ssl module, enable the
     SSL_MODE_RELEASE_BUFFERS mode option if it is safe to do so.

   - bpo-26012(20): Don’t traverse into symlinks for ‘**’ pattern in
     pathlib.Path.[r]glob().

   - bpo-24120(21): Ignore PermissionError when traversing a tree with
     pathlib.Path.[r]glob().  Patch by Ulrich Petri.

   - bpo-25447(22): fileinput now uses sys.stdin as-is if it does not
     have a buffer attribute (restores backward compatibility).

   - bpo-25447(23): Copying the lru_cache() wrapper object now always
     works, independently from the type of the wrapped object (by
     returning the original object unchanged).

   - bpo-24103(24): Fixed possible use after free in
     ElementTree.XMLPullParser.

   - bpo-25860(25): os.fwalk() no longer skips remaining directories
     when error occurs.  Original patch by Samson Lee.

   - bpo-25914(26): Fixed and simplified OrderedDict.__sizeof__.

   - bpo-25902(27): Fixed various refcount issues in ElementTree
     iteration.

   - bpo-25717(28): Restore the previous behaviour of tolerating most
     fstat() errors when opening files.  This was a regression in 3.5a1,
     and stopped anonymous temporary files from working in special
     cases.

   - bpo-24903(29): Fix regression in number of arguments compileall
     accepts when ’-d’ is specified.  The check on the number of
     arguments has been dropped completely as it never worked correctly
     anyway.

   - bpo-25764(30): In the subprocess module, preserve any exception
     caused by fork() failure when preexec_fn is used.

   - bpo-6478(31): _strptime’s regexp cache now is reset after changing
     timezone with time.tzset().

   - bpo-14285(32): When executing a package with the "python -m
     package" option, and package initialization fails, a proper
     traceback is now reported.  The "runpy" module now lets exceptions
     from package initialization pass back to the caller, rather than
     raising ImportError.

   - bpo-19771(33): Also in runpy and the "-m" option, omit the
     irrelevant message ".  .  .  is a package and cannot be directly
     executed" if the package could not even be initialized (e.g.  due
     to a bad ‘*.pyc’ file).

   - bpo-25177(34): Fixed problem with the mean of very small and very
     large numbers.  As a side effect, statistics.mean and
     statistics.variance should be significantly faster.

   - bpo-25718(35): Fixed copying object with state with boolean value
     is false.

   - bpo-10131(36): Fixed deep copying of minidom documents.  Based on
     patch by Marian Ganisin.

   - bpo-25725(37): Fixed a reference leak in pickle.loads() when
     unpickling invalid data including tuple instructions.

   - bpo-25663(38): In the Readline completer, avoid listing duplicate
     global names, and search the global namespace before searching
     builtins.

   - bpo-25688(39): Fixed file leak in ElementTree.iterparse() raising
     an error.

   - bpo-23914(40): Fixed SystemError raised by unpickler on broken
     pickle data.

   - bpo-25691(41): Fixed crash on deleting ElementTree.Element
     attributes.

   - bpo-25624(42): ZipFile now always writes a ZIP_STORED header for
     directory entries.  Patch by Dingyuan Wang.

   - Skip getaddrinfo if host is already resolved.  Patch by A. Jesse
     Jiryu Davis.

   - bpo-26050(43): Add asyncio.StreamReader.readuntil() method.  Patch
     by Марк Коренберг.

   - bpo-25924(44): Avoid unnecessary serialization of getaddrinfo(3)
     calls on OS X versions 10.5 or higher.  Original patch by A. Jesse
     Jiryu Davis.

   - bpo-26406(45): Avoid unnecessary serialization of getaddrinfo(3)
     calls on current versions of OpenBSD and NetBSD. Patch by A. Jesse
     Jiryu Davis.

   - bpo-26848(46): Fix asyncio/subprocess.communicate() to handle empty
     input.  Patch by Jack O’Connor.

   - bpo-27040(47): Add loop.get_exception_handler method

   - bpo-27041(48): asyncio: Add loop.create_future method

   - bpo-27223(49): asyncio: Fix _read_ready and _write_ready to respect
     _conn_lost.  Patch by Łukasz Langa.

   - bpo-22970(50): asyncio: Fix inconsistency cancelling
     Condition.wait.  Patch by David Coles.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25995

   (2) https://bugs.python.org/issue26117

   (3) https://bugs.python.org/issue25911

   (4) https://bugs.python.org/issue26045

   (5) https://bugs.python.org/issue12923

   (6) https://bugs.python.org/issue25945

   (7) https://bugs.python.org/issue26202

   (8) https://bugs.python.org/issue23076

   (9) https://bugs.python.org/issue19883

   (10) https://bugs.python.org/issue26227

   (11) https://bugs.python.org/issue26147

   (12) https://bugs.python.org/issue25935

   (13) https://bugs.python.org/issue16620

   (14) https://bugs.python.org/issue26013

   (15) https://bugs.python.org/issue25850

   (16) https://bugs.python.org/issue17633

   (17) https://bugs.python.org/issue24705

   (18) https://bugs.python.org/issue22138

   (19) https://bugs.python.org/issue25672

   (20) https://bugs.python.org/issue26012

   (21) https://bugs.python.org/issue24120

   (22) https://bugs.python.org/issue25447

   (23) https://bugs.python.org/issue25447

   (24) https://bugs.python.org/issue24103

   (25) https://bugs.python.org/issue25860

   (26) https://bugs.python.org/issue25914

   (27) https://bugs.python.org/issue25902

   (28) https://bugs.python.org/issue25717

   (29) https://bugs.python.org/issue24903

   (30) https://bugs.python.org/issue25764

   (31) https://bugs.python.org/issue6478

   (32) https://bugs.python.org/issue14285

   (33) https://bugs.python.org/issue19771

   (34) https://bugs.python.org/issue25177

   (35) https://bugs.python.org/issue25718

   (36) https://bugs.python.org/issue10131

   (37) https://bugs.python.org/issue25725

   (38) https://bugs.python.org/issue25663

   (39) https://bugs.python.org/issue25688

   (40) https://bugs.python.org/issue23914

   (41) https://bugs.python.org/issue25691

   (42) https://bugs.python.org/issue25624

   (43) https://bugs.python.org/issue26050

   (44) https://bugs.python.org/issue25924

   (45) https://bugs.python.org/issue26406

   (46) https://bugs.python.org/issue26848

   (47) https://bugs.python.org/issue27040

   (48) https://bugs.python.org/issue27041

   (49) https://bugs.python.org/issue27223

   (50) https://bugs.python.org/issue22970


File: python.info,  Node: IDLE<49>,  Next: 文档<49>,  Prev: 库<75>,  Up: Python 3 5 2 rc1

1.18.73.12 IDLE
...............

   - bpo-5124(1): Paste with text selected now replaces the selection on
     X11.  This matches how paste works on Windows, Mac, most modern
     Linux apps, and ttk widgets.  Original patch by Serhiy Storchaka.

   - bpo-24759(2): Make clear in idlelib.idle_test.__init__ that the
     directory is a private implementation of test.test_idle and tool
     for maintainers.

   - bpo-27196(3): Stop ’ThemeChanged’ warnings when running IDLE tests.
     These persisted after other warnings were suppressed in #20567.
     Apply Serhiy Storchaka’s update_idletasks solution to four test
     files.  Record this additional advice in idle_test/README.txt

   - bpo-20567(4): Revise idle_test/README.txt with advice about
     avoiding tk warning messages from tests.  Apply advice to several
     IDLE tests.

   - bpo-27117(5): Make colorizer htest and turtledemo work with dark
     themes.  Move code for configuring text widget colors to a new
     function.

   - bpo-26673(6): When tk reports font size as 0, change to size 10.
     Such fonts on Linux prevented the configuration dialog from
     opening.

   - bpo-21939(7): Add test for IDLE’s percolator.  Original patch by
     Saimadhav Heblikar.

   - bpo-21676(8): Add test for IDLE’s replace dialog.  Original patch
     by Saimadhav Heblikar.

   - bpo-18410(9): Add test for IDLE’s search dialog.  Original patch by
     Westley Martínez.

   - bpo-21703(10): Add test for IDLE’s undo delegator.  Original patch
     by Saimadhav Heblikar .

   - bpo-27044(11): Add ConfigDialog.remove_var_callbacks to stop memory
     leaks.

   - bpo-23977(12): Add more asserts to test_delegator.

   - bpo-20640(13): Add tests for idlelib.configHelpSourceEdit.  Patch
     by Saimadhav Heblikar.

   - In the ’IDLE-console differences’ section of the IDLE doc, clarify
     how running with IDLE affects sys.modules and the standard streams.

   - bpo-25507(14): fix incorrect change in IOBinding that prevented
     printing.  Augment IOBinding htest to include all major IOBinding
     functions.

   - bpo-25905(15): Revert unwanted conversion of ’ to ’ RIGHT SINGLE
     QUOTATION MARK in README.txt and open this and NEWS.txt with
     ’ascii’.  Re-encode CREDITS.txt to utf-8 and open it with ’utf-8’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5124

   (2) https://bugs.python.org/issue24759

   (3) https://bugs.python.org/issue27196

   (4) https://bugs.python.org/issue20567

   (5) https://bugs.python.org/issue27117

   (6) https://bugs.python.org/issue26673

   (7) https://bugs.python.org/issue21939

   (8) https://bugs.python.org/issue21676

   (9) https://bugs.python.org/issue18410

   (10) https://bugs.python.org/issue21703

   (11) https://bugs.python.org/issue27044

   (12) https://bugs.python.org/issue23977

   (13) https://bugs.python.org/issue20640

   (14) https://bugs.python.org/issue25507

   (15) https://bugs.python.org/issue25905


File: python.info,  Node: 文档<49>,  Next: 测试<47>,  Prev: IDLE<49>,  Up: Python 3 5 2 rc1

1.18.73.13 文档
...............

   - bpo-19489(1): Moved the search box from the sidebar to the header
     and footer of each page.  Patch by Ammar Askar.

   - bpo-24136(2): Document the new PEP 448(3) unpacking syntax of 3.5.

   - bpo-26736(4): Used HTTPS for external links in the documentation if
     possible.

   - bpo-6953(5): Rework the Readline module documentation to group
     related functions together, and add more details such as what
     underlying Readline functions and variables are accessed.

   - bpo-23606(6): Adds note to ctypes documentation regarding
     cdll.msvcrt.

   - bpo-25500(7): Fix documentation to not claim that __import__ is
     searched for in the global scope.

   - bpo-26014(8): Update 3.x packaging documentation: * "See also"
     links to the new docs are now provided in the legacy pages * links
     to setuptools documentation have been updated

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19489

   (2) https://bugs.python.org/issue24136

   (3) https://www.python.org/dev/peps/pep-0448

   (4) https://bugs.python.org/issue26736

   (5) https://bugs.python.org/issue6953

   (6) https://bugs.python.org/issue23606

   (7) https://bugs.python.org/issue25500

   (8) https://bugs.python.org/issue26014


File: python.info,  Node: 测试<47>,  Next: 构建<47>,  Prev: 文档<49>,  Up: Python 3 5 2 rc1

1.18.73.14 测试
...............

   - bpo-21916(1): Added tests for the turtle module.  Patch by ingrid,
     Gregory Loyse and Jelle Zijlstra.

   - bpo-26523(2): The multiprocessing thread pool
     (multiprocessing.dummy.Pool) was untested.

   - bpo-26015(3): Added new tests for pickling iterators of mutable
     sequences.

   - bpo-26325(4): Added test.support.check_no_resource_warning() to
     check that no ResourceWarning is emitted.

   - bpo-25940(5): Changed test_ssl to use self-signed.pythontest.net.
     This avoids relying on svn.python.org, which recently changed root
     certificate.

   - bpo-25616(6): Tests for OrderedDict are extracted from
     test_collections into separate file test_ordered_dict.

   - bpo-26583(7): Skip test_timestamp_overflow in test_import if
     bytecode files cannot be written.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21916

   (2) https://bugs.python.org/issue26523

   (3) https://bugs.python.org/issue26015

   (4) https://bugs.python.org/issue26325

   (5) https://bugs.python.org/issue25940

   (6) https://bugs.python.org/issue25616

   (7) https://bugs.python.org/issue26583


File: python.info,  Node: 构建<47>,  Next: Windows<47>,  Prev: 测试<47>,  Up: Python 3 5 2 rc1

1.18.73.15 构建
...............

   - bpo-26884(1): Fix linking extension modules for cross builds.
     Patch by Xavier de Gaye.

   - bpo-22359(2): Disable the rules for running _freeze_importlib and
     pgen when cross-compiling.  The output of these programs is
     normally saved with the source code anyway, and is still
     regenerated when doing a native build.  Patch by Xavier de Gaye.

   - bpo-27229(3): Fix the cross-compiling pgen rule for in-tree builds.
     Patch by Xavier de Gaye.

   - bpo-21668(4): Link audioop, _datetime, _ctypes_test modules to
     libm, except on Mac OS X. Patch written by Xavier de Gaye.

   - bpo-25702(5): A –with-lto configure option has been added that will
     enable link time optimizations at build time during a make
     profile-opt.  Some compilers and toolchains are known to not
     produce stable code when using LTO, be sure to test things
     thoroughly before relying on it.  It can provide a few % speed up
     over profile-opt alone.

   - bpo-26624(6): Adds validation of ucrtbase[d].dll version with
     warning for old versions.

   - bpo-17603(7): Avoid error about nonexistent fileblocks.o file by
     using a lower-level check for st_blocks in struct stat.

   - bpo-26079(8): Fixing the build output folder for tix-8.4.3.6.
     Patch by Bjoern Thiel.

   - bpo-26465(9): 更新Windows 构建OpenSSL 1.0.2g.

   - bpo-24421(10): Compile Modules/_math.c once, before building
     extensions.  Previously it could fail to compile properly if the
     math and cmath builds were concurrent.

   - bpo-25348(11): Added ‘--pgo’ and ‘--pgo-job’ arguments to
     ‘PCbuild\build.bat’ for building with Profile-Guided Optimization.
     The old ‘PCbuild\build_pgo.bat’ script is now deprecated, and
     simply calls ‘PCbuild\build.bat --pgo %*’.

   - bpo-25827(12): Add support for building with ICC to ‘configure’,
     including a new ‘--with-icc’ flag.

   - bpo-25696(13): Fix installation of Python on UNIX with make -j9.

   - bpo-26930(14): 更新OS X 10.5+（仅32位）安装程序以构建并链接OpenSSL
     1.0.2h。

   - bpo-26268(15): 更新Windows 构建OpenSSL 1.0.2f.

   - bpo-25136(16): Support Apple Xcode 7’s new textual SDK stub
     libraries.

   - bpo-24324(17): Do not enable unreachable code warnings when using
     gcc as the option does not work correctly in older versions of gcc
     and has been silently removed as of gcc-4.5.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26884

   (2) https://bugs.python.org/issue22359

   (3) https://bugs.python.org/issue27229

   (4) https://bugs.python.org/issue21668

   (5) https://bugs.python.org/issue25702

   (6) https://bugs.python.org/issue26624

   (7) https://bugs.python.org/issue17603

   (8) https://bugs.python.org/issue26079

   (9) https://bugs.python.org/issue26465

   (10) https://bugs.python.org/issue24421

   (11) https://bugs.python.org/issue25348

   (12) https://bugs.python.org/issue25827

   (13) https://bugs.python.org/issue25696

   (14) https://bugs.python.org/issue26930

   (15) https://bugs.python.org/issue26268

   (16) https://bugs.python.org/issue25136

   (17) https://bugs.python.org/issue24324


File: python.info,  Node: Windows<47>,  Next: 工具/示例<31>,  Prev: 构建<47>,  Up: Python 3 5 2 rc1

1.18.73.16 Windows
..................

   - bpo-27053(1): Updates make_zip.py to correctly generate library ZIP
     file.

   - bpo-26268(2): Update the prepare_ssl.py script to handle OpenSSL
     releases that don’t include the contents of the include directory
     (that is, 1.0.2e and later).

   - bpo-26071(3): bdist_wininst created binaries fail to start and find
     32bit Python

   - bpo-26073(4): Update the list of magic numbers in launcher

   - bpo-26065(5): Excludes venv from library when generating embeddable
     distro.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27053

   (2) https://bugs.python.org/issue26268

   (3) https://bugs.python.org/issue26071

   (4) https://bugs.python.org/issue26073

   (5) https://bugs.python.org/issue26065


File: python.info,  Node: 工具/示例<31>,  Next: Windows<48>,  Prev: Windows<47>,  Up: Python 3 5 2 rc1

1.18.73.17 工具/示例
....................

   - bpo-26799(1): Fix python-gdb.py: don’t get C types once when the
     Python code is loaded, but get C types on demand.  The C types can
     change if python-gdb.py is loaded before the Python executable.
     Patch written by Thomas Ilsche.

   - bpo-26271(2): Fix the Freeze tool to properly use flags passed
     through configure.  Patch by Daniel Shaulov.

   - bpo-26489(3): Add dictionary unpacking support to
     Tools/parser/unparse.py.  Patch by Guo Ci Teo.

   - bpo-26316(4): Fix variable name typo in Argument Clinic.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26799

   (2) https://bugs.python.org/issue26271

   (3) https://bugs.python.org/issue26489

   (4) https://bugs.python.org/issue26316


File: python.info,  Node: Windows<48>,  Prev: 工具/示例<31>,  Up: Python 3 5 2 rc1

1.18.73.18 Windows
..................

   - bpo-17500(1): Remove unused and outdated icons.  (See also:
     ‘https://github.com/python/pythondotorg/issues/945’)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17500


File: python.info,  Node: Python 3 5 1 正式版,  Next: Python 3 5 1 rc1,  Prev: Python 3 5 2 rc1,  Up: 更新日志

1.18.74 Python 3.5.1 正式版
---------------------------

`发布日期: 2015-12-06'

* Menu:

* 核心与内置: 核心与内置<62>.
* Windows: Windows<49>.


File: python.info,  Node: 核心与内置<62>,  Next: Windows<49>,  Up: Python 3 5 1 正式版

1.18.74.1 核心与内置
....................

   - bpo-25709(1): Fixed problem with in-place string concatenation and
     utf-8 cache.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25709


File: python.info,  Node: Windows<49>,  Prev: 核心与内置<62>,  Up: Python 3 5 1 正式版

1.18.74.2 Windows
.................

   - bpo-25715(1): Python 3.5.1 installer shows wrong upgrade path and
     incorrect logic for launcher detection.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25715


File: python.info,  Node: Python 3 5 1 rc1,  Next: Python 3 5 0 正式版,  Prev: Python 3 5 1 正式版,  Up: 更新日志

1.18.75 Python 3.5.1 rc1
------------------------

`发布日期: 2015-11-22'

* Menu:

* 核心与内置: 核心与内置<63>.
* 库: 库<76>.
* IDLE: IDLE<50>.
* 文档: 文档<50>.
* 测试: 测试<48>.
* 构建: 构建<48>.
* Windows: Windows<50>.
* 工具/示例: 工具/示例<32>.


File: python.info,  Node: 核心与内置<63>,  Next: 库<76>,  Up: Python 3 5 1 rc1

1.18.75.1 核心与内置
....................

   - bpo-25630(1): Fix a possible segfault during argument parsing in
     functions that accept filesystem paths.

   - bpo-23564(2): Fixed a partially broken sanity check in the
     _posixsubprocess internals regarding how fds_to_pass were passed to
     the child.  The bug had no actual impact as subprocess.py already
     avoided it.

   - bpo-25388(3): Fixed tokenizer crash when processing undecodable
     source code with a null byte.

   - bpo-25462(4): The hash of the key now is calculated only once in
     most operations in C implementation of OrderedDict.

   - bpo-22995(5): Default implementation of __reduce__ and
     __reduce_ex__ now rejects builtin types with not defined __new__.

   - bpo-25555(6): Fix parser and AST: fill lineno and col_offset of
     "arg" node when compiling AST from Python objects.

   - bpo-24802(7): Avoid buffer overreads when int(), float(),
     compile(), exec() and eval() are passed bytes-like objects.  These
     objects are not necessarily terminated by a null byte, but the
     functions assumed they were.

   - bpo-24726(8): Fixed a crash and leaking NULL in repr() of
     OrderedDict that was mutated by direct calls of dict methods.

   - bpo-25449(9): Iterating OrderedDict with keys with unstable hash
     now raises KeyError in C implementations as well as in Python
     implementation.

   - bpo-25395(10): Fixed crash when highly nested OrderedDict
     structures were garbage collected.

   - bpo-25274(11): sys.setrecursionlimit() now raises a RecursionError
     if the new recursion limit is too low depending at the current
     recursion depth.  Modify also the "lower-water mark" formula to
     make it monotonic.  This mark is used to decide when the overflowed
     flag of the thread state is reset.

   - bpo-24402(12): Fix input() to prompt to the redirected stdout when
     sys.stdout.fileno() fails.

   - bpo-24806(13): Prevent builtin types that are not allowed to be
     subclassed from being subclassed through multiple inheritance.

   - bpo-24848(14): Fixed a number of bugs in UTF-7 decoding of
     misformed data.

   - bpo-25280(15): Import trace messages emitted in verbose (-v) mode
     are no longer formatted twice.

   - bpo-25003(16): On Solaris 11.3 or newer, os.urandom() now uses the
     getrandom() function instead of the getentropy() function.  The
     getentropy() function is blocking to generate very good quality
     entropy, os.urandom() doesn’t need such high-quality entropy.

   - bpo-25182(17): The stdprinter (used as sys.stderr before the io
     module is imported at startup) now uses the backslashreplace error
     handler.

   - bpo-25131(18): Make the line number and column offset of set/dict
     literals and comprehensions correspond to the opening brace.

   - bpo-25150(19): Hide the private _Py_atomic_xxx symbols from the
     public Python.h header to fix a compilation error with OpenMP.
     PyThreadState_GET() becomes an alias to PyThreadState_Get() to
     avoid ABI incompatibilities.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25630

   (2) https://bugs.python.org/issue23564

   (3) https://bugs.python.org/issue25388

   (4) https://bugs.python.org/issue25462

   (5) https://bugs.python.org/issue22995

   (6) https://bugs.python.org/issue25555

   (7) https://bugs.python.org/issue24802

   (8) https://bugs.python.org/issue24726

   (9) https://bugs.python.org/issue25449

   (10) https://bugs.python.org/issue25395

   (11) https://bugs.python.org/issue25274

   (12) https://bugs.python.org/issue24402

   (13) https://bugs.python.org/issue24806

   (14) https://bugs.python.org/issue24848

   (15) https://bugs.python.org/issue25280

   (16) https://bugs.python.org/issue25003

   (17) https://bugs.python.org/issue25182

   (18) https://bugs.python.org/issue25131

   (19) https://bugs.python.org/issue25150


File: python.info,  Node: 库<76>,  Next: IDLE<50>,  Prev: 核心与内置<63>,  Up: Python 3 5 1 rc1

1.18.75.2 库
............

   - bpo-25626(1): Change three zlib functions to accept sizes that fit
     in Py_ssize_t, but internally cap those sizes to UINT_MAX. This
     resolves a regression in 3.5 where GzipFile.read() failed to read
     chunks larger than 2 or 4 GiB. The change affects the
     zlib.Decompress.decompress() max_length parameter, the
     zlib.decompress() bufsize parameter, and the
     zlib.Decompress.flush() length parameter.

   - bpo-25583(2): Avoid incorrect errors raised by
     os.makedirs(exist_ok=True) when the OS gives priority to errors
     such as EACCES over EEXIST.

   - bpo-25593(3): Change semantics of EventLoop.stop() in asyncio.

   - bpo-6973(4): When we know a subprocess.Popen process has died, do
     not allow the send_signal(), terminate(), or kill() methods to do
     anything as they could potentially signal a different process.

   - bpo-25590(5): In the Readline completer, only call getattr() once
     per attribute.

   - bpo-25498(6): Fix a crash when garbage-collecting ctypes objects
     created by wrapping a memoryview.  This was a regression made in
     3.5a1.  Based on patch by Eryksun.

   - bpo-25584(7): Added "escape" to the __all__ list in the glob
     module.

   - bpo-25584(8): Fixed recursive glob() with patterns starting with
     ‘**’.

   - bpo-25446(9): Fix regression in smtplib’s AUTH LOGIN support.

   - bpo-18010(10): Fix the pydoc web server’s module search function to
     handle exceptions from importing packages.

   - bpo-25554(11): Got rid of circular references in regular expression
     parsing.

   - bpo-25510(12): fileinput.FileInput.readline() now returns b’’
     instead of ’’ at the end if the FileInput was opened with binary
     mode.  Patch by Ryosuke Ito.

   - bpo-25503(13): Fixed inspect.getdoc() for inherited docstrings of
     properties.  Original patch by John Mark Vandenberg.

   - bpo-25515(14): Always use os.urandom as a source of randomness in
     uuid.uuid4.

   - bpo-21827(15): Fixed textwrap.dedent() for the case when largest
     common whitespace is a substring of smallest leading whitespace.
     Based on patch by Robert Li.

   - bpo-25447(16): The lru_cache() wrapper objects now can be copied
     and pickled (by returning the original object unchanged).

   - bpo-25390(17): typing: Don’t crash on Union[str, Pattern].

   - bpo-25441(18): asyncio: Raise error from drain() when socket is
     closed.

   - bpo-25410(19): Cleaned up and fixed minor bugs in C implementation
     of OrderedDict.

   - bpo-25411(20): Improved Unicode support in SMTPHandler through
     better use of the email package.  Thanks to user simon04 for the
     patch.

   - bpo-25407(21): Remove mentions of the formatter module being
     removed in Python 3.6.

   - bpo-25406(22): Fixed a bug in C implementation of
     OrderedDict.move_to_end() that caused segmentation fault or hang in
     iterating after moving several items to the start of ordered dict.

   - bpo-25364(23): zipfile now works in threads disabled builds.

   - bpo-25328(24): smtpd’s SMTPChannel now correctly raises a
     ValueError if both decode_data and enable_SMTPUTF8 are set to true.

   - bpo-25316(25): distutils raises OSError instead of
     DistutilsPlatformError when MSVC is not installed.

   - bpo-25380(26): Fixed protocol for the STACK_GLOBAL opcode in
     pickletools.opcodes.

   - bpo-23972(27): Updates asyncio datagram create method allowing
     reuseport and reuseaddr socket options to be set prior to binding
     the socket.  Mirroring the existing asyncio create_server method
     the reuseaddr option for datagram sockets defaults to True if the
     O/S is ’posix’ (except if the platform is Cygwin).  Patch by Chris
     Laws.

   - bpo-25304(28): Add asyncio.run_coroutine_threadsafe().  This lets
     you submit a coroutine to a loop from another thread, returning a
     concurrent.futures.Future.  By Vincent Michel.

   - bpo-25232(29): Fix CGIRequestHandler to split the query from the
     URL at the first question mark (?)  rather than the last.  Patch
     from Xiang Zhang.

   - bpo-24657(30): Prevent CGIRequestHandler from collapsing slashes in
     the query part of the URL as if it were a path.  Patch from Xiang
     Zhang.

   - bpo-24483(31): C implementation of functools.lru_cache() now
     calculates key’s hash only once.

   - bpo-22958(32): Constructor and update method of
     weakref.WeakValueDictionary now accept the self and the dict
     keyword arguments.

   - bpo-22609(33): Constructor of collections.UserDict now accepts the
     self keyword argument.

   - bpo-25111(34): Fixed comparison of traceback.FrameSummary.

   - bpo-25262(35): Added support for BINBYTES8 opcode in Python
     implementation of unpickler.  Highest 32 bits of 64-bit size for
     BINUNICODE8 and BINBYTES8 opcodes no longer silently ignored on
     32-bit platforms in C implementation.

   - bpo-25034(36): Fix string.Formatter problem with auto-numbering and
     nested format_specs.  Patch by Anthon van der Neut.

   - bpo-25233(37): Rewrite the guts of asyncio.Queue and
     asyncio.Semaphore to be more understandable and correct.

   - bpo-25203(38): Failed readline.set_completer_delims() no longer
     left the module in inconsistent state.

   - bpo-23600(39): Default implementation of tzinfo.fromutc() was
     returning wrong results in some cases.

   - bpo-23329(40): Allow the ssl module to be built with older versions
     of LibreSSL.

   - Prevent overflow in _Unpickler_Read.

   - bpo-25047(41): The XML encoding declaration written by Element Tree
     now respects the letter case given by the user.  This restores the
     ability to write encoding names in uppercase like "UTF-8", which
     worked in Python 2.

   - bpo-25135(42): Make deque_clear() safer by emptying the deque
     before clearing.  This helps avoid possible reentrancy issues.

   - bpo-19143(43): platform module now reads Windows version from
     kernel32.dll to avoid compatibility shims.

   - bpo-25092(44): Fix datetime.strftime() failure when errno was
     already set to EINVAL.

   - bpo-23517(45): Fix rounding in fromtimestamp() and
     utcfromtimestamp() methods of datetime.datetime: microseconds are
     now rounded to nearest with ties going to nearest even integer
     (ROUND_HALF_EVEN), instead of being rounding towards minus infinity
     (ROUND_FLOOR). It’s important that these methods use the same
     rounding mode than datetime.timedelta to keep the property:
     (datetime(1970,1,1) + timedelta(seconds=t)) ==
     datetime.utcfromtimestamp(t).  It also the rounding mode used by
     round(float) for example.

   - bpo-25155(46): Fix datetime.datetime.now() and
     datetime.datetime.utcnow() on Windows to support date after year
     2038.  It was a regression introduced in Python 3.5.0.

   - bpo-25108(47): Omitted internal frames in traceback functions
     print_stack(), format_stack(), and extract_stack() called without
     arguments.

   - bpo-25118(48): Fix a regression of Python 3.5.0 in os.waitpid() on
     Windows.

   - bpo-24684(49): socket.socket.getaddrinfo() now calls
     PyUnicode_AsEncodedString() instead of calling the encode() method
     of the host, to handle correctly custom string with an encode()
     method which doesn’t return a byte string.  The encoder of the IDNA
     codec is now called directly instead of calling the encode() method
     of the string.

   - bpo-25060(50): Correctly compute stack usage of the BUILD_MAP
     opcode.

   - bpo-24857(51): Comparing call_args to a long sequence now correctly
     returns a boolean result instead of raising an exception.  Patch by
     A Kaptur.

   - bpo-23144(52): Make sure that HTMLParser.feed() returns all the
     data, even when convert_charrefs is True.

   - bpo-24982(53): shutil.make_archive() with the "zip" format now adds
     entries for directories (including empty directories) in ZIP file.

   - bpo-25019(54): Fixed a crash caused by setting non-string key of
     expat parser.  Based on patch by John Leitch.

   - bpo-16180(55): Exit pdb if file has syntax error, instead of
     trapping user in an infinite loop.  Patch by Xavier de Gaye.

   - bpo-24891(56): Fix a race condition at Python startup if the file
     descriptor of stdin (0), stdout (1) or stderr (2) is closed while
     Python is creating sys.stdin, sys.stdout and sys.stderr objects.
     These attributes are now set to None if the creation of the object
     failed, instead of raising an OSError exception.  Initial patch
     written by Marco Paolini.

   - bpo-24992(57): Fix error handling and a race condition (related to
     garbage collection) in collections.OrderedDict constructor.

   - bpo-24881(58): Fixed setting binary mode in Python implementation
     of FileIO on Windows and Cygwin.  Patch from Akira Li.

   - bpo-25578(59): Fix (another) memory leak in SSLSocket.getpeercer().

   - bpo-25530(60): Disable the vulnerable SSLv3 protocol by default
     when creating ssl.SSLContext.

   - bpo-25569(61): Fix memory leak in SSLSocket.getpeercert().

   - bpo-25471(62): Sockets returned from accept() shouldn’t appear to
     be nonblocking.

   - bpo-25319(63): When threading.Event is reinitialized, the
     underlying condition should use a regular lock rather than a
     recursive lock.

   - bpo-21112(64): Fix regression in unittest.expectedFailure on
     subclasses.  Patch from Berker Peksag.

   - bpo-24764(65): cgi.FieldStorage.read_multi() now ignores the
     Content-Length header in part headers.  Patch written by Peter
     Landry and reviewed by Pierre Quentel.

   - bpo-24913(66): Fix overrun error in deque.index().  Found by John
     Leitch and Bryce Darling.

   - bpo-24774(67): Fix docstring in http.server.test.  Patch from
     Chiu-Hsiang Hsu.

   - bpo-21159(68): Improve message in
     configparser.InterpolationMissingOptionError.  Patch from Łukasz
     Langa.

   - bpo-20362(69): Honour TestCase.longMessage correctly in
     assertRegex.  Patch from Ilia Kurenkov.

   - bpo-23572(70): Fixed functools.singledispatch on classes with falsy
     metaclasses.  Patch by Ethan Furman.

   - asyncio: ensure_future() now accepts awaitable objects.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25626

   (2) https://bugs.python.org/issue25583

   (3) https://bugs.python.org/issue25593

   (4) https://bugs.python.org/issue6973

   (5) https://bugs.python.org/issue25590

   (6) https://bugs.python.org/issue25498

   (7) https://bugs.python.org/issue25584

   (8) https://bugs.python.org/issue25584

   (9) https://bugs.python.org/issue25446

   (10) https://bugs.python.org/issue18010

   (11) https://bugs.python.org/issue25554

   (12) https://bugs.python.org/issue25510

   (13) https://bugs.python.org/issue25503

   (14) https://bugs.python.org/issue25515

   (15) https://bugs.python.org/issue21827

   (16) https://bugs.python.org/issue25447

   (17) https://bugs.python.org/issue25390

   (18) https://bugs.python.org/issue25441

   (19) https://bugs.python.org/issue25410

   (20) https://bugs.python.org/issue25411

   (21) https://bugs.python.org/issue25407

   (22) https://bugs.python.org/issue25406

   (23) https://bugs.python.org/issue25364

   (24) https://bugs.python.org/issue25328

   (25) https://bugs.python.org/issue25316

   (26) https://bugs.python.org/issue25380

   (27) https://bugs.python.org/issue23972

   (28) https://bugs.python.org/issue25304

   (29) https://bugs.python.org/issue25232

   (30) https://bugs.python.org/issue24657

   (31) https://bugs.python.org/issue24483

   (32) https://bugs.python.org/issue22958

   (33) https://bugs.python.org/issue22609

   (34) https://bugs.python.org/issue25111

   (35) https://bugs.python.org/issue25262

   (36) https://bugs.python.org/issue25034

   (37) https://bugs.python.org/issue25233

   (38) https://bugs.python.org/issue25203

   (39) https://bugs.python.org/issue23600

   (40) https://bugs.python.org/issue23329

   (41) https://bugs.python.org/issue25047

   (42) https://bugs.python.org/issue25135

   (43) https://bugs.python.org/issue19143

   (44) https://bugs.python.org/issue25092

   (45) https://bugs.python.org/issue23517

   (46) https://bugs.python.org/issue25155

   (47) https://bugs.python.org/issue25108

   (48) https://bugs.python.org/issue25118

   (49) https://bugs.python.org/issue24684

   (50) https://bugs.python.org/issue25060

   (51) https://bugs.python.org/issue24857

   (52) https://bugs.python.org/issue23144

   (53) https://bugs.python.org/issue24982

   (54) https://bugs.python.org/issue25019

   (55) https://bugs.python.org/issue16180

   (56) https://bugs.python.org/issue24891

   (57) https://bugs.python.org/issue24992

   (58) https://bugs.python.org/issue24881

   (59) https://bugs.python.org/issue25578

   (60) https://bugs.python.org/issue25530

   (61) https://bugs.python.org/issue25569

   (62) https://bugs.python.org/issue25471

   (63) https://bugs.python.org/issue25319

   (64) https://bugs.python.org/issue21112

   (65) https://bugs.python.org/issue24764

   (66) https://bugs.python.org/issue24913

   (67) https://bugs.python.org/issue24774

   (68) https://bugs.python.org/issue21159

   (69) https://bugs.python.org/issue20362

   (70) https://bugs.python.org/issue23572


File: python.info,  Node: IDLE<50>,  Next: 文档<50>,  Prev: 库<76>,  Up: Python 3 5 1 rc1

1.18.75.3 IDLE
..............

   - bpo-15348(1): Stop the debugger engine (normally in a user process)
     before closing the debugger window (running in the IDLE process).
     This prevents the RuntimeErrors that were being caught and ignored.

   - bpo-24455(2): Prevent IDLE from hanging when a) closing the shell
     while the debugger is active (15347); b) closing the debugger with
     the [X] button (15348); and c) activating the debugger when already
     active (24455).  The patch by Mark Roseman does this by making two
     changes.  1.  Suspend and resume the gui.interaction method with
     the tcl vwait mechanism intended for this purpose (instead of
     root.mainloop & .quit).  2.  In gui.run, allow any existing
     interaction to terminate first.

   - Change ’The program’ to ’Your program’ in an IDLE ’kill program?’
     message to make it clearer that the program referred to is the
     currently running user program, not IDLE itself.

   - bpo-24750(3): Improve the appearance of the IDLE editor window
     status bar.  Patch by Mark Roseman.

   - bpo-25313(4): Change the handling of new built-in text color themes
     to better address the compatibility problem introduced by the
     addition of IDLE Dark.  Consistently use the revised
     idleConf.CurrentTheme everywhere in idlelib.

   - bpo-24782(5): Extension configuration is now a tab in the IDLE
     Preferences dialog rather than a separate dialog.  The former tabs
     are now a sorted list.  Patch by Mark Roseman.

   - bpo-22726(6): Re-activate the config dialog help button with some
     content about the other buttons and the new IDLE Dark theme.

   - bpo-24820(7): IDLE now has an ’IDLE Dark’ built-in text color
     theme.  It is more or less IDLE Classic inverted, with a cobalt
     blue background.  Strings, comments, keywords, ...  are still
     green, red, orange, ...  .  To use it with IDLEs released before
     November 2015, hit the ’Save as New Custom Theme’ button and enter
     a new name, such as ’Custom Dark’.  The custom theme will work with
     any IDLE release, and can be modified.

   - bpo-25224(8): README.txt is now an idlelib index for IDLE
     developers and curious users.  The previous user content is now in
     the IDLE doc chapter.  ’IDLE’ now means ’Integrated Development and
     Learning Environment’.

   - bpo-24820(9): Users can now set breakpoint colors in Settings ->
     Custom Highlighting.  Original patch by Mark Roseman.

   - bpo-24972(10): Inactive selection background now matches active
     selection background, as configured by users, on all systems.
     Found items are now always highlighted on Windows.  Initial patch
     by Mark Roseman.

   - bpo-24570(11): Idle: make calltip and completion boxes appear on
     Macs affected by a tk regression.  Initial patch by Mark Roseman.

   - bpo-24988(12): Idle ScrolledList context menus (used in debugger)
     now work on Mac Aqua.  Patch by Mark Roseman.

   - bpo-24801(13): Make right-click for context menu work on Mac Aqua.
     Patch by Mark Roseman.

   - bpo-25173(14): Associate tkinter messageboxes with a specific
     widget.  For Mac OSX, make them a ’sheet’.  Patch by Mark Roseman.

   - bpo-25198(15): Enhance the initial html viewer now used for Idle
     Help.  Properly indent fixed-pitch text (patch by Mark Roseman).
     Give code snippet a very Sphinx-like light blueish-gray background.
     Re-use initial width and height set by users for shell and editor.
     When the Table of Contents (TOC) menu is used, put the section
     header at the top of the screen.

   - bpo-25225(16): Condense and rewrite Idle doc section on text
     colors.

   - bpo-21995(17): Explain some differences between IDLE and console
     Python.

   - bpo-22820(18): Explain need for `print' when running file from Idle
     editor.

   - bpo-25224(19): Doc: augment Idle feature list and no-subprocess
     section.

   - bpo-25219(20): Update doc for Idle command line options.  Some were
     missing and notes were not correct.

   - bpo-24861(21): Most of idlelib is private and subject to change.
     Use idleib.idle.* to start Idle.  See idlelib.__init__.__doc__.

   - bpo-25199(22): Idle: add synchronization comments for future
     maintainers.

   - bpo-16893(23): Replace help.txt with help.html for Idle doc
     display.  The new idlelib/help.html is rstripped
     Doc/build/html/library/idle.html.  It looks better than help.txt
     and will better document Idle as released.  The tkinter html viewer
     that works for this file was written by Mark Roseman.  The now
     unused EditorWindow.HelpDialog class and helt.txt file are
     deprecated.

   - bpo-24199(24): Deprecate unused idlelib.idlever with possible
     removal in 3.6.

   - bpo-24790(25): Remove extraneous code (which also create 2 & 3
     conflicts).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15348

   (2) https://bugs.python.org/issue24455

   (3) https://bugs.python.org/issue24750

   (4) https://bugs.python.org/issue25313

   (5) https://bugs.python.org/issue24782

   (6) https://bugs.python.org/issue22726

   (7) https://bugs.python.org/issue24820

   (8) https://bugs.python.org/issue25224

   (9) https://bugs.python.org/issue24820

   (10) https://bugs.python.org/issue24972

   (11) https://bugs.python.org/issue24570

   (12) https://bugs.python.org/issue24988

   (13) https://bugs.python.org/issue24801

   (14) https://bugs.python.org/issue25173

   (15) https://bugs.python.org/issue25198

   (16) https://bugs.python.org/issue25225

   (17) https://bugs.python.org/issue21995

   (18) https://bugs.python.org/issue22820

   (19) https://bugs.python.org/issue25224

   (20) https://bugs.python.org/issue25219

   (21) https://bugs.python.org/issue24861

   (22) https://bugs.python.org/issue25199

   (23) https://bugs.python.org/issue16893

   (24) https://bugs.python.org/issue24199

   (25) https://bugs.python.org/issue24790


File: python.info,  Node: 文档<50>,  Next: 测试<48>,  Prev: IDLE<50>,  Up: Python 3 5 1 rc1

1.18.75.4 文档
..............

   - bpo-22558(1): Add remaining doc links to source code for
     Python-coded modules.  Patch by Yoni Lavi.

   - bpo-12067(2): Rewrite Comparisons section in the Expressions
     chapter of the language reference.  Some of the details of
     comparing mixed types were incorrect or ambiguous.  NotImplemented
     is only relevant at a lower level than the Expressions chapter.
     Added details of comparing range() objects, and default behaviour
     and consistency suggestions for user-defined classes.  Patch from
     Andy Maier.

   - bpo-24952(3): Clarify the default size argument of stack_size() in
     the "threading" and "_thread" modules.  Patch from Mattip.

   - bpo-23725(4): Overhaul tempfile docs.  Note deprecated status of
     mktemp.  Patch from Zbigniew Jędrzejewski-Szmek.

   - bpo-24808(5): Update the types of some PyTypeObject fields.  Patch
     by Joseph Weston.

   - bpo-22812(6): Fix unittest discovery examples.  Patch from Pam
     McA’Nulty.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22558

   (2) https://bugs.python.org/issue12067

   (3) https://bugs.python.org/issue24952

   (4) https://bugs.python.org/issue23725

   (5) https://bugs.python.org/issue24808

   (6) https://bugs.python.org/issue22812


File: python.info,  Node: 测试<48>,  Next: 构建<48>,  Prev: 文档<50>,  Up: Python 3 5 1 rc1

1.18.75.5 测试
..............

   - bpo-25449(1): Added tests for OrderedDict subclasses.

   - bpo-25099(2): Make test_compileall not fail when an entry on
     sys.path cannot be written to (commonly seen in administrative
     installs on Windows).

   - bpo-23919(3): Prevents assert dialogs appearing in the test suite.

   - ‘PCbuild\rt.bat’ now accepts an unlimited number of arguments to
     pass along to regrtest.py.  Previously there was a limit of 9.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25449

   (2) https://bugs.python.org/issue25099

   (3) https://bugs.python.org/issue23919


File: python.info,  Node: 构建<48>,  Next: Windows<50>,  Prev: 测试<48>,  Up: Python 3 5 1 rc1

1.18.75.6 构建
..............

   - bpo-24915(1): Add LLVM support for PGO builds and use the test
     suite to generate the profile data.  Initial patch by Alecsandru
     Patrascu of Intel.

   - bpo-24910(2): Windows MSIs now have unique display names.

   - bpo-24986(3): It is now possible to build Python on Windows without
     errors when external libraries are not available.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24915

   (2) https://bugs.python.org/issue24910

   (3) https://bugs.python.org/issue24986


File: python.info,  Node: Windows<50>,  Next: 工具/示例<32>,  Prev: 构建<48>,  Up: Python 3 5 1 rc1

1.18.75.7 Windows
.................

   - bpo-25450(1): Updates shortcuts to start Python in installation
     directory.

   - bpo-25164(2): Changes default all-users install directory to match
     per-user directory.

   - bpo-25143(3): Improves installer error messages for unsupported
     platforms.

   - bpo-25163(4): Display correct directory in installer when using
     non-default settings.

   - bpo-25361(5): Disables use of SSE2 instructions in Windows 32-bit
     build

   - bpo-25089(6): Adds logging to installer for case where launcher is
     not selected on upgrade.

   - bpo-25165(7): Windows uninstallation should not remove launcher if
     other versions remain

   - bpo-25112(8): py.exe launcher is missing icons

   - bpo-25102(9): Windows installer does not precompile for -O or -OO.

   - bpo-25081(10): Makes Back button in installer go back to upgrade
     page when upgrading.

   - bpo-25091(11): Increases font size of the installer.

   - bpo-25126(12): Clarifies that the non-web installer will download
     some components.

   - bpo-25213(13): Restores requestedExecutionLevel to manifest to
     disable UAC virtualization.

   - bpo-25022(14): Removed very outdated PC/example_nt/ directory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25450

   (2) https://bugs.python.org/issue25164

   (3) https://bugs.python.org/issue25143

   (4) https://bugs.python.org/issue25163

   (5) https://bugs.python.org/issue25361

   (6) https://bugs.python.org/issue25089

   (7) https://bugs.python.org/issue25165

   (8) https://bugs.python.org/issue25112

   (9) https://bugs.python.org/issue25102

   (10) https://bugs.python.org/issue25081

   (11) https://bugs.python.org/issue25091

   (12) https://bugs.python.org/issue25126

   (13) https://bugs.python.org/issue25213

   (14) https://bugs.python.org/issue25022


File: python.info,  Node: 工具/示例<32>,  Prev: Windows<50>,  Up: Python 3 5 1 rc1

1.18.75.8 工具/示例
...................

   - bpo-25440(1): Fix output of python-config –extension-suffix.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25440


File: python.info,  Node: Python 3 5 0 正式版,  Next: Python 3 5 0 rc4,  Prev: Python 3 5 1 rc1,  Up: 更新日志

1.18.76 Python 3.5.0 正式版
---------------------------

`发布日期: 2015-09-13'

* Menu:

* 构建: 构建<49>.


File: python.info,  Node: 构建<49>,  Up: Python 3 5 0 正式版

1.18.76.1 构建
..............

   - bpo-25071(1): Windows installer should not require TargetDir
     parameter when installing quietly.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25071


File: python.info,  Node: Python 3 5 0 rc4,  Next: Python 3 5 0 rc3,  Prev: Python 3 5 0 正式版,  Up: 更新日志

1.18.77 Python 3.5.0 rc4
------------------------

`发布日期: 2015-09-09'

* Menu:

* 库: 库<77>.
* 构建: 构建<50>.


File: python.info,  Node: 库<77>,  Next: 构建<50>,  Up: Python 3 5 0 rc4

1.18.77.1 库
............

   - bpo-25029(1): Fixes MemoryError in test_strptime.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25029


File: python.info,  Node: 构建<50>,  Prev: 库<77>,  Up: Python 3 5 0 rc4

1.18.77.2 构建
..............

   - bpo-25027(1): Reverts partial-static build options and adds
     vcruntime140.dll to Windows installation.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25027


File: python.info,  Node: Python 3 5 0 rc3,  Next: Python 3 5 0 rc2,  Prev: Python 3 5 0 rc4,  Up: 更新日志

1.18.78 Python 3.5.0 rc3
------------------------

`发布日期: 2015-09-07'

* Menu:

* 核心与内置: 核心与内置<64>.
* 库: 库<78>.


File: python.info,  Node: 核心与内置<64>,  Next: 库<78>,  Up: Python 3 5 0 rc3

1.18.78.1 核心与内置
....................

   - bpo-24305(1): Prevent import subsystem stack frames from being
     counted by the warnings.warn(stacklevel=) parameter.

   - bpo-24912(2): Prevent __class__ assignment to immutable built-in
     objects.

   - bpo-24975(3): Fix AST compilation for PEP 448(4) syntax.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24305

   (2) https://bugs.python.org/issue24912

   (3) https://bugs.python.org/issue24975

   (4) https://www.python.org/dev/peps/pep-0448


File: python.info,  Node: 库<78>,  Prev: 核心与内置<64>,  Up: Python 3 5 0 rc3

1.18.78.2 库
............

   - bpo-24917(1): time_strftime() buffer over-read.

   - bpo-24748(2): To resolve a compatibility problem found with py2exe
     and pywin32, imp.load_dynamic() once again ignores previously
     loaded modules to support Python modules replacing themselves with
     extension modules.  Patch by Petr Viktorin.

   - bpo-24635(3): Fixed a bug in typing.py where isinstance([],
     typing.Iterable) would return True once, then False on subsequent
     calls.

   - bpo-24989(4): Fixed buffer overread in BytesIO.readline() if a
     position is set beyond size.  Based on patch by John Leitch.

   - bpo-24913(5): Fix overrun error in deque.index().  Found by John
     Leitch and Bryce Darling.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24917

   (2) https://bugs.python.org/issue24748

   (3) https://bugs.python.org/issue24635

   (4) https://bugs.python.org/issue24989

   (5) https://bugs.python.org/issue24913


File: python.info,  Node: Python 3 5 0 rc2,  Next: Python 3 5 0 rc1,  Prev: Python 3 5 0 rc3,  Up: 更新日志

1.18.79 Python 3.5.0 rc2
------------------------

`发布日期: 2015-08-25'

* Menu:

* 核心与内置: 核心与内置<65>.
* 库: 库<79>.


File: python.info,  Node: 核心与内置<65>,  Next: 库<79>,  Up: Python 3 5 0 rc2

1.18.79.1 核心与内置
....................

   - bpo-24769(1): Interpreter now starts properly when dynamic loading
     is disabled.  Patch by Petr Viktorin.

   - bpo-21167(2): NAN operations are now handled correctly when python
     is compiled with ICC even if -fp-model strict is not specified.

   - bpo-24492(3): A "package" lacking a __name__ attribute when trying
     to perform a ‘from .. import ...’ statement will trigger an
     ImportError instead of an AttributeError.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24769

   (2) https://bugs.python.org/issue21167

   (3) https://bugs.python.org/issue24492


File: python.info,  Node: 库<79>,  Prev: 核心与内置<65>,  Up: Python 3 5 0 rc2

1.18.79.2 库
............

   - bpo-24847(1): Removes vcruntime140.dll dependency from Tcl/Tk.

   - bpo-24839(2): platform._syscmd_ver raises DeprecationWarning

   - bpo-24867(3): Fix Task.get_stack() for ’async def’ coroutines

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24847

   (2) https://bugs.python.org/issue24839

   (3) https://bugs.python.org/issue24867


File: python.info,  Node: Python 3 5 0 rc1,  Next: Python 3 5 0 beta 4,  Prev: Python 3 5 0 rc2,  Up: 更新日志

1.18.80 Python 3.5.0 rc1
------------------------

`发布日期: 2015-08-09'

* Menu:

* 核心与内置: 核心与内置<66>.
* 库: 库<80>.
* IDLE: IDLE<51>.
* 文档: 文档<51>.
* 测试: 测试<49>.


File: python.info,  Node: 核心与内置<66>,  Next: 库<80>,  Up: Python 3 5 0 rc1

1.18.80.1 核心与内置
....................

   - bpo-24667(1): Resize odict in all cases that the underlying dict
     resizes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24667


File: python.info,  Node: 库<80>,  Next: IDLE<51>,  Prev: 核心与内置<66>,  Up: Python 3 5 0 rc1

1.18.80.2 库
............

   - bpo-24824(1): Signatures of codecs.encode() and codecs.decode() now
     are compatible with pydoc.

   - bpo-24634(2): Importing uuid should not try to load libc on Windows

   - bpo-24798(3): _msvccompiler.py doesn’t properly support manifests

   - bpo-4395(4): Better testing and documentation of binary operators.
     Patch by Martin Panter.

   - bpo-23973(5): Update typing.py from GitHub repo.

   - bpo-23004(6): mock_open() now reads binary data correctly when the
     type of read_data is bytes.  Initial patch by Aaron Hill.

   - bpo-23888(7): Handle fractional time in cookie expiry.  Patch by
     ssh.

   - bpo-23652(8): Make it possible to compile the select module against
     the libc headers from the Linux Standard Base, which do not include
     some EPOLL macros.  Patch by Matt Frank.

   - bpo-22932(9): Fix timezones in email.utils.formatdate.  Patch from
     Dmitry Shachnev.

   - bpo-23779(10): imaplib raises TypeError if authenticator tries to
     abort.  Patch from Craig Holmquist.

   - bpo-23319(11): Fix ctypes.BigEndianStructure, swap correctly bytes.
     Patch written by Matthieu Gautier.

   - bpo-23254(12): Document how to close the TCPServer listening
     socket.  Patch from Martin Panter.

   - bpo-19450(13): 更新Windows和OS X安装程序以使用SQLite 3.8.11

   - bpo-17527(14): Add PATCH to wsgiref.validator.  Patch from Luca
     Sbardella.

   - bpo-24791(15): Fix grammar regression for call syntax: ’g(*a or
     b)’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24824

   (2) https://bugs.python.org/issue24634

   (3) https://bugs.python.org/issue24798

   (4) https://bugs.python.org/issue4395

   (5) https://bugs.python.org/issue23973

   (6) https://bugs.python.org/issue23004

   (7) https://bugs.python.org/issue23888

   (8) https://bugs.python.org/issue23652

   (9) https://bugs.python.org/issue22932

   (10) https://bugs.python.org/issue23779

   (11) https://bugs.python.org/issue23319

   (12) https://bugs.python.org/issue23254

   (13) https://bugs.python.org/issue19450

   (14) https://bugs.python.org/issue17527

   (15) https://bugs.python.org/issue24791


File: python.info,  Node: IDLE<51>,  Next: 文档<51>,  Prev: 库<80>,  Up: Python 3 5 0 rc1

1.18.80.3 IDLE
..............

   - bpo-23672(1): Allow Idle to edit and run files with astral chars in
     name.  Patch by Mohd Sanad Zaki Rizvi.

   - bpo-24745(2): Idle editor default font.  Switch from Courier to
     platform-sensitive TkFixedFont.  This should not affect current
     customized font selections.  If there is a problem, edit
     $HOME/.idlerc/config-main.cfg and remove ’fontxxx’ entries from
     [Editor Window].  Patch by Mark Roseman.

   - bpo-21192(3): Idle editor.  When a file is run, put its name in the
     restart bar.  Do not print false prompts.  Original patch by Adnan
     Umer.

   - bpo-13884(4): Idle menus.  Remove tearoff lines.  Patch by Roger
     Serwy.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23672

   (2) https://bugs.python.org/issue24745

   (3) https://bugs.python.org/issue21192

   (4) https://bugs.python.org/issue13884


File: python.info,  Node: 文档<51>,  Next: 测试<49>,  Prev: IDLE<51>,  Up: Python 3 5 0 rc1

1.18.80.4 文档
..............

   - bpo-24129(1): Clarify the reference documentation for name
     resolution.  This includes removing the assumption that readers
     will be familiar with the name resolution scheme Python used prior
     to the introduction of lexical scoping for function namespaces.
     Patch by Ivan Levkivskyi.

   - bpo-20769(2): Improve reload() docs.  Patch by Dorian Pula.

   - bpo-23589(3): Remove duplicate sentence from the FAQ. Patch by
     Yongzhi Pan.

   - bpo-24729(4): Correct IO tutorial to match implementation regarding
     encoding parameter to open function.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24129

   (2) https://bugs.python.org/issue20769

   (3) https://bugs.python.org/issue23589

   (4) https://bugs.python.org/issue24729


File: python.info,  Node: 测试<49>,  Prev: 文档<51>,  Up: Python 3 5 0 rc1

1.18.80.5 测试
..............

   - bpo-24751(1): When running regrtest with the ‘-w’ command line
     option, a test run is no longer marked as a failure if all tests
     succeed when re-run.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24751


File: python.info,  Node: Python 3 5 0 beta 4,  Next: Python 3 5 0 beta 3,  Prev: Python 3 5 0 rc1,  Up: 更新日志

1.18.81 Python 3.5.0 beta 4
---------------------------

`发布日期: 2015-07-26'

* Menu:

* 核心与内置: 核心与内置<67>.
* 库: 库<81>.
* 构建: 构建<51>.


File: python.info,  Node: 核心与内置<67>,  Next: 库<81>,  Up: Python 3 5 0 beta 4

1.18.81.1 核心与内置
....................

   - bpo-23573(1): Restored optimization of bytes.rfind() and
     bytearray.rfind() for single-byte argument on Linux.

   - bpo-24569(2): Make PEP 448(3) dictionary evaluation more
     consistent.

   - bpo-24583(4): Fix crash when set is mutated while being updated.

   - bpo-24407(5): Fix crash when dict is mutated while being updated.

   - bpo-24619(6): New approach for tokenizing async/await.  As a
     consequence, it is now possible to have one-line ’async def foo():
     await ..’ functions.

   - bpo-24687(7): Plug refleak on SyntaxError in function parameters
     annotations.

   - bpo-15944(8): memoryview: Allow arbitrary formats when casting to
     bytes.  Patch by Martin Panter.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23573

   (2) https://bugs.python.org/issue24569

   (3) https://www.python.org/dev/peps/pep-0448

   (4) https://bugs.python.org/issue24583

   (5) https://bugs.python.org/issue24407

   (6) https://bugs.python.org/issue24619

   (7) https://bugs.python.org/issue24687

   (8) https://bugs.python.org/issue15944


File: python.info,  Node: 库<81>,  Next: 构建<51>,  Prev: 核心与内置<67>,  Up: Python 3 5 0 beta 4

1.18.81.2 库
............

   - bpo-23441(1): rcompleter now prints a tab character instead of
     displaying possible completions for an empty word.  Initial patch
     by Martin Sekera.

   - bpo-24683(2): Fixed crashes in _json functions called with
     arguments of inappropriate type.

   - bpo-21697(3): shutil.copytree() now correctly handles symbolic
     links that point to directories.  Patch by Eduardo Seabra and
     Thomas Kluyver.

   - bpo-14373(4): Fixed segmentation fault when gc.collect() is called
     during constructing lru_cache (C implementation).

   - bpo-24695(5): Fix a regression in traceback.print_exception().  If
     exc_traceback is None we shouldn’t print a traceback header like
     described in the documentation.

   - bpo-24620(6): Random.setstate() now validates the value of state
     last element.

   - bpo-22485(7): Fixed an issue that caused *note inspect.getsource:
     ee5. to return incorrect results on nested functions.

   - bpo-22153(8): Improve unittest docs.  Patch from Martin Panter and
     evilzero.

   - bpo-24580(9): Symbolic group references to open group in re
     patterns now are explicitly forbidden as well as numeric group
     references.

   - bpo-24206(10): Fixed __eq__ and __ne__ methods of inspect classes.

   - bpo-24631(11): Fixed regression in the timeit module with multiline
     setup.

   - bpo-18622(12): unittest.mock.mock_open().reset_mock would recurse
     infinitely.  Patch from Nicola Palumbo and Laurent De Buyst.

   - bpo-23661(13): unittest.mock side_effects can now be exceptions
     again.  This was a regression vs Python 3.4.  Patch from Ignacio
     Rossi

   - bpo-24608(14): chunk.Chunk.read() now always returns bytes, not
     str.

   - bpo-18684(15): Fixed reading out of the buffer in the re module.

   - bpo-24259(16): tarfile now raises a ReadError if an archive is
     truncated inside a data segment.

   - bpo-15014(17): SMTP.auth() and SMTP.login() now support RFC 4954’s
     optional initial-response argument to the SMTP AUTH command.

   - bpo-24669(18): Fix inspect.getsource() for ’async def’ functions.
     Patch by Kai Groner.

   - bpo-24688(19): ast.get_docstring() for ’async def’ functions.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23441

   (2) https://bugs.python.org/issue24683

   (3) https://bugs.python.org/issue21697

   (4) https://bugs.python.org/issue14373

   (5) https://bugs.python.org/issue24695

   (6) https://bugs.python.org/issue24620

   (7) https://bugs.python.org/issue22485

   (8) https://bugs.python.org/issue22153

   (9) https://bugs.python.org/issue24580

   (10) https://bugs.python.org/issue24206

   (11) https://bugs.python.org/issue24631

   (12) https://bugs.python.org/issue18622

   (13) https://bugs.python.org/issue23661

   (14) https://bugs.python.org/issue24608

   (15) https://bugs.python.org/issue18684

   (16) https://bugs.python.org/issue24259

   (17) https://bugs.python.org/issue15014

   (18) https://bugs.python.org/issue24669

   (19) https://bugs.python.org/issue24688


File: python.info,  Node: 构建<51>,  Prev: 库<81>,  Up: Python 3 5 0 beta 4

1.18.81.3 构建
..............

   - bpo-24603(1): 更新Windows 构建和OS X 10.5 安装程序以使用OpenSSL
     1.0.2d.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24603


File: python.info,  Node: Python 3 5 0 beta 3,  Next: Python 3 5 0 beta 2,  Prev: Python 3 5 0 beta 4,  Up: 更新日志

1.18.82 Python 3.5.0 beta 3
---------------------------

`发布日期: 2015-07-05'

* Menu:

* 核心与内置: 核心与内置<68>.
* 库: 库<82>.
* 测试: 测试<50>.
* 文档: 文档<52>.
* 构建: 构建<52>.


File: python.info,  Node: 核心与内置<68>,  Next: 库<82>,  Up: Python 3 5 0 beta 3

1.18.82.1 核心与内置
....................

   - bpo-24467(1): Fixed possible buffer over-read in bytearray.  The
     bytearray object now always allocates place for trailing null byte
     and it’s buffer now is always null-terminated.

   - Upgrade to Unicode 8.0.0.

   - bpo-24345(2): Add Py_tp_finalize slot for the stable ABI.

   - bpo-24400(3): Introduce a distinct type for PEP 492(4) coroutines;
     add types.CoroutineType, inspect.getcoroutinestate,
     inspect.getcoroutinelocals; coroutines no longer use CO_GENERATOR
     flag; sys.set_coroutine_wrapper works only for ’async def’
     coroutines; inspect.iscoroutine no longer uses
     collections.abc.Coroutine, it’s intended to test for pure ’async
     def’ coroutines only; add new opcode: GET_YIELD_FROM_ITER; fix
     generators wrapper used in types.coroutine to be instance of
     collections.abc.Generator; collections.abc.Awaitable and
     collections.abc.Coroutine can no longer be used to detect
     generator-based coroutines–use inspect.isawaitable instead.

   - bpo-24450(5): Add gi_yieldfrom to generators and cr_await to
     coroutines.  Contributed by Benno Leslie and Yury Selivanov.

   - bpo-19235(6): Add new RecursionError exception.  Patch by Georg
     Brandl.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24467

   (2) https://bugs.python.org/issue24345

   (3) https://bugs.python.org/issue24400

   (4) https://www.python.org/dev/peps/pep-0492

   (5) https://bugs.python.org/issue24450

   (6) https://bugs.python.org/issue19235


File: python.info,  Node: 库<82>,  Next: 测试<50>,  Prev: 核心与内置<68>,  Up: Python 3 5 0 beta 3

1.18.82.2 库
............

   - bpo-21750(1): mock_open.read_data can now be read from each
     instance, as it could in Python 3.3.

   - bpo-24552(2): Fix use after free in an error case of the _pickle
     module.

   - bpo-24514(3): tarfile now tolerates number fields consisting of
     only whitespace.

   - bpo-19176(4): Fixed doctype() related bugs in C implementation of
     ElementTree.  A deprecation warning no longer issued by XMLParser
     subclass with default doctype() method.  Direct call of doctype()
     now issues a warning.  Parser’s doctype() now is not called if
     target’s doctype() is called.  Based on patch by Martin Panter.

   - bpo-20387(5): Restore semantic round-trip correctness in
     tokenize/untokenize for tab-indented blocks.

   - bpo-24456(6): Fixed possible buffer over-read in adpcm2lin() and
     lin2adpcm() functions of the audioop module.

   - bpo-24336(7): The contextmanager decorator now works with functions
     with keyword arguments called "func" and "self".  Patch by Martin
     Panter.

   - bpo-24522(8): Fix possible integer overflow in json accelerator
     module.

   - bpo-24489(9): ensure a previously set C errno doesn’t disturb
     cmath.polar().

   - bpo-24408(10): Fixed AttributeError in measure() and metrics()
     methods of tkinter.Font.

   - bpo-14373(11): C implementation of functools.lru_cache() now can be
     used with methods.

   - bpo-24347(12): Set KeyError if PyDict_GetItemWithError returns
     NULL.

   - bpo-24348(13): Drop superfluous incref/decref.

   - bpo-24359(14): Check for changed OrderedDict size during iteration.

   - bpo-24368(15): Support keyword arguments in OrderedDict methods.

   - bpo-24362(16): Simplify the C OrderedDict fast nodes resize logic.

   - bpo-24377(17): Fix a ref leak in OrderedDict.__repr__.

   - bpo-24369(18): Defend against key-changes during iteration.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21750

   (2) https://bugs.python.org/issue24552

   (3) https://bugs.python.org/issue24514

   (4) https://bugs.python.org/issue19176

   (5) https://bugs.python.org/issue20387

   (6) https://bugs.python.org/issue24456

   (7) https://bugs.python.org/issue24336

   (8) https://bugs.python.org/issue24522

   (9) https://bugs.python.org/issue24489

   (10) https://bugs.python.org/issue24408

   (11) https://bugs.python.org/issue14373

   (12) https://bugs.python.org/issue24347

   (13) https://bugs.python.org/issue24348

   (14) https://bugs.python.org/issue24359

   (15) https://bugs.python.org/issue24368

   (16) https://bugs.python.org/issue24362

   (17) https://bugs.python.org/issue24377

   (18) https://bugs.python.org/issue24369


File: python.info,  Node: 测试<50>,  Next: 文档<52>,  Prev: 库<82>,  Up: Python 3 5 0 beta 3

1.18.82.3 测试
..............

   - bpo-24373(1): _testmultiphase and xxlimited now use tp_traverse and
     tp_finalize to avoid reference leaks encountered when combining
     tp_dealloc with PyType_FromSpec (see bpo-16690(2) for details)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24373

   (2) https://bugs.python.org/issue16690


File: python.info,  Node: 文档<52>,  Next: 构建<52>,  Prev: 测试<50>,  Up: Python 3 5 0 beta 3

1.18.82.4 文档
..............

   - bpo-24458(1): Update documentation to cover multi-phase
     initialization for extension modules (PEP 489).  Patch by Petr
     Viktorin.

   - bpo-24351(2): Clarify what is meant by "identifier" in the context
     of string.Template instances.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24458

   (2) https://bugs.python.org/issue24351


File: python.info,  Node: 构建<52>,  Prev: 文档<52>,  Up: Python 3 5 0 beta 3

1.18.82.5 构建
..............

   - bpo-24432(1): 更新Windows 构建和OS X 10.5 安装程序以使用OpenSSL
     1.0.2c.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24432


File: python.info,  Node: Python 3 5 0 beta 2,  Next: Python 3 5 0 beta 1,  Prev: Python 3 5 0 beta 3,  Up: 更新日志

1.18.83 Python 3.5.0 beta 2
---------------------------

`发布日期: 2015-05-31'

* Menu:

* 核心与内置: 核心与内置<69>.
* 库: 库<83>.


File: python.info,  Node: 核心与内置<69>,  Next: 库<83>,  Up: Python 3 5 0 beta 2

1.18.83.1 核心与内置
....................

   - bpo-24284(1): The startswith and endswith methods of the str class
     no longer return True when finding the empty string and the indexes
     are completely out of range.

   - bpo-24115(2): Update uses of PyObject_IsTrue(), PyObject_Not(),
     PyObject_IsInstance(), PyObject_RichCompareBool() and
     _PyDict_Contains() to check for and handle errors correctly.

   - bpo-24328(3): Fix importing one character extension modules.

   - bpo-11205(4): In dictionary displays, evaluate the key before the
     value.

   - bpo-24285(5): Fixed regression that prevented importing extension
     modules from inside packages.  Patch by Petr Viktorin.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24284

   (2) https://bugs.python.org/issue24115

   (3) https://bugs.python.org/issue24328

   (4) https://bugs.python.org/issue11205

   (5) https://bugs.python.org/issue24285


File: python.info,  Node: 库<83>,  Prev: 核心与内置<69>,  Up: Python 3 5 0 beta 2

1.18.83.2 库
............

   - bpo-23247(1): Fix a crash in the StreamWriter.reset() of CJK
     codecs.

   - bpo-24270(2): Add math.isclose() and cmath.isclose() functions as
     per PEP 485(3).  Contributed by Chris Barker and Tal Einat.

   - bpo-5633(4): Fixed timeit when the statement is a string and the
     setup is not.

   - bpo-24326(5): Fixed audioop.ratecv() with non-default weightB
     argument.  Original patch by David Moore.

   - bpo-16991(6): Add a C implementation of OrderedDict.

   - bpo-23934(7): Fix inspect.signature to fail correctly for builtin
     types lacking signature information.  Initial patch by James
     Powell.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23247

   (2) https://bugs.python.org/issue24270

   (3) https://www.python.org/dev/peps/pep-0485

   (4) https://bugs.python.org/issue5633

   (5) https://bugs.python.org/issue24326

   (6) https://bugs.python.org/issue16991

   (7) https://bugs.python.org/issue23934


File: python.info,  Node: Python 3 5 0 beta 1,  Next: Python 3 5 0 alpha 4,  Prev: Python 3 5 0 beta 2,  Up: 更新日志

1.18.84 Python 3.5.0 beta 1
---------------------------

`发布日期: 2015-05-24'

* Menu:

* 核心与内置: 核心与内置<70>.
* 库: 库<84>.
* IDLE: IDLE<52>.
* 测试: 测试<51>.
* 文档: 文档<53>.
* 工具/示例: 工具/示例<33>.


File: python.info,  Node: 核心与内置<70>,  Next: 库<84>,  Up: Python 3 5 0 beta 1

1.18.84.1 核心与内置
....................

   - bpo-24276(1): Fixed optimization of property descriptor getter.

   - bpo-24268(2): PEP 489: Multi-phase extension module initialization.
     Patch by Petr Viktorin.

   - bpo-23955(3): Add pyvenv.cfg option to suppress
     registry/environment lookup for generating sys.path on Windows.

   - bpo-24257(4): Fixed system error in the comparison of faked
     types.SimpleNamespace.

   - bpo-22939(5): Fixed integer overflow in iterator object.  Patch by
     Clement Rouault.

   - bpo-23985(6): Fix a possible buffer overrun when deleting a slice
     from the front of a bytearray and then appending some other bytes
     data.

   - bpo-24102(7): Fixed exception type checking in standard error
     handlers.

   - bpo-15027(8): The UTF-32 encoder is now 3x to 7x faster.

   - bpo-23290(9): Optimize set_merge() for cases where the target is
     empty.  (Contributed by Serhiy Storchaka.)

   - bpo-2292(10): PEP 448: Additional Unpacking Generalizations.

   - bpo-24096(11): Make warnings.warn_explicit more robust against
     mutation of the warnings.filters list.

   - bpo-23996(12): Avoid a crash when a delegated generator raises an
     unnormalized StopIteration exception.  Patch by Stefan Behnel.

   - bpo-23910(13): Optimize property() getter calls.  Patch by Joe
     Jevnik.

   - bpo-23911(14): Move path-based importlib bootstrap code to a
     separate frozen module.

   - bpo-24192(15): Fix namespace package imports.

   - bpo-24022(16): Fix tokenizer crash when processing undecodable
     source code.

   - bpo-9951(17): Added a hex() method to bytes, bytearray, and
     memoryview.

   - bpo-22906(18): PEP 479: Change StopIteration handling inside
     generators.

   - bpo-24017(19): PEP 492: Coroutines with async and await syntax.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24276

   (2) https://bugs.python.org/issue24268

   (3) https://bugs.python.org/issue23955

   (4) https://bugs.python.org/issue24257

   (5) https://bugs.python.org/issue22939

   (6) https://bugs.python.org/issue23985

   (7) https://bugs.python.org/issue24102

   (8) https://bugs.python.org/issue15027

   (9) https://bugs.python.org/issue23290

   (10) https://bugs.python.org/issue2292

   (11) https://bugs.python.org/issue24096

   (12) https://bugs.python.org/issue23996

   (13) https://bugs.python.org/issue23910

   (14) https://bugs.python.org/issue23911

   (15) https://bugs.python.org/issue24192

   (16) https://bugs.python.org/issue24022

   (17) https://bugs.python.org/issue9951

   (18) https://bugs.python.org/issue22906

   (19) https://bugs.python.org/issue24017


File: python.info,  Node: 库<84>,  Next: IDLE<52>,  Prev: 核心与内置<70>,  Up: Python 3 5 0 beta 1

1.18.84.2 库
............

   - bpo-14373(1): Added C implementation of functools.lru_cache().
     Based on patches by Matt Joiner and Alexey Kachayev.

   - bpo-24230(2): The tempfile module now accepts bytes for prefix,
     suffix and dir parameters and returns bytes in such situations
     (matching the os module APIs).

   - bpo-22189(3): collections.UserString now supports __getnewargs__(),
     __rmod__(), casefold(), format_map(), isprintable(), and
     maketrans().  Patch by Joe Jevnik.

   - bpo-24244(4): Prevents termination when an invalid format string is
     encountered on Windows in strftime.

   - bpo-23973(5): PEP 484: Add the typing module.

   - bpo-23086(6): The collections.abc.Sequence() abstract base class
     added `start' and `stop' parameters to the index() mixin.  Patch by
     Devin Jeanpierre.

   - bpo-20035(7): Replaced the ‘tkinter._fix’ module used for setting
     up the Tcl/Tk environment on Windows with a private function in the
     ‘_tkinter’ module that makes no permanent changes to the
     environment.

   - bpo-24257(8): Fixed segmentation fault in sqlite3.Row constructor
     with faked cursor type.

   - bpo-15836(9): assertRaises(), assertRaisesRegex(), assertWarns()
     and assertWarnsRegex() assertments now check the type of the first
     argument to prevent possible user error.  Based on patch by Daniel
     Wagner-Hall.

   - bpo-9858(10): Add missing method stubs to _io.RawIOBase.  Patch by
     Laura Rupprecht.

   - bpo-22955(11): attrgetter, itemgetter and methodcaller objects in
     the operator module now support pickling.  Added readable and
     evaluable repr for these objects.  Based on patch by Josh
     Rosenberg.

   - bpo-22107(12): tempfile.gettempdir() and tempfile.mkdtemp() now try
     again when a directory with the chosen name already exists on
     Windows as well as on Unix.  tempfile.mkstemp() now fails early if
     parent directory is not valid (not exists or is a file) on Windows.

   - bpo-23780(13): Improved error message in os.path.join() with single
     argument.

   - bpo-6598(14): Increased time precision and random number range in
     email.utils.make_msgid() to strengthen the uniqueness of the
     message ID.

   - bpo-24091(15): Fixed various crashes in corner cases in C
     implementation of ElementTree.

   - bpo-21931(16): msilib.FCICreate() now raises TypeError in the case
     of a bad argument instead of a ValueError with a bogus FCI error
     number.  Patch by Jeffrey Armstrong.

   - bpo-13866(17): `quote_via' argument added to
     urllib.parse.urlencode.

   - bpo-20098(18): New mangle_from policy option for email, default
     True for compat32, but False for all other policies.

   - bpo-24211(19): The email library now supports RFC 6532: it can
     generate headers using utf-8 instead of encoded words.

   - bpo-16314(20): Added support for the LZMA compression in distutils.

   - bpo-21804(21): poplib now supports RFC 6856 (UTF8).

   - bpo-18682(22): Optimized pprint functions for builtin scalar types.

   - bpo-22027(23): smtplib now supports RFC 6531 (SMTPUTF8).

   - bpo-23488(24): Random generator objects now consume 2x less memory
     on 64-bit.

   - bpo-1322(25): platform.dist() and platform.linux_distribution()
     functions are now deprecated.  Initial patch by Vajrasky Kok.

   - bpo-22486(26): Added the math.gcd() function.  The fractions.gcd()
     function now is deprecated.  Based on patch by Mark Dickinson.

   - bpo-24064(27): Property() docstrings are now writeable.  (Patch by
     Berker Peksag.)

   - bpo-22681(28): Added support for the koi8_t encoding.

   - bpo-22682(29): Added support for the kz1048 encoding.

   - bpo-23796(30): peek and read1 methods of BufferedReader now raise
     ValueError if they called on a closed object.  Patch by John
     Hergenroeder.

   - bpo-21795(31): smtpd now supports the 8BITMIME extension whenever
     the new `decode_data' constructor argument is set to False.

   - bpo-24155(32): optimize heapq.heapify() for better cache
     performance when heapifying large lists.

   - bpo-21800(33): imaplib now supports RFC 5161 (enable), RFC 6855
     (utf8/internationalized email) and automatically encodes non-ASCII
     usernames and passwords to UTF8.

   - bpo-20274(34): When calling a _sqlite.Connection, it now complains
     if passed any keyword arguments.  Previously it silently ignored
     them.

   - bpo-20274(35): Remove ignored and erroneous "kwargs" parameters
     from three METH_VARARGS methods on _sqlite.Connection.

   - bpo-24134(36): assertRaises(), assertRaisesRegex(), assertWarns()
     and assertWarnsRegex() checks now emits a deprecation warning when
     callable is None or keyword arguments except msg is passed in the
     context manager mode.

   - bpo-24018(37): Add a collections.abc.Generator abstract base class.
     Contributed by Stefan Behnel.

   - bpo-23880(38): Tkinter’s getint() and getdouble() now support
     Tcl_Obj.  Tkinter’s getdouble() now supports any numbers (in
     particular int).

   - bpo-22619(39): Added negative limit support in the traceback
     module.  Based on patch by Dmitry Kazakov.

   - bpo-24094(40): Fix possible crash in json.encode with poorly
     behaved dict subclasses.

   - bpo-9246(41): On POSIX, os.getcwd() now supports paths longer than
     1025 bytes.  Patch written by William Orr.

   - bpo-17445(42): add difflib.diff_bytes() to support comparison of
     byte strings (fixes a regression from Python 2).

   - bpo-23917(43): Fall back to sequential compilation when
     ProcessPoolExecutor doesn’t exist.  Patch by Claudiu Popa.

   - bpo-23008(44): Fixed resolving attributes with boolean value is
     False in pydoc.

   - Fix asyncio issue 235: LifoQueue and PriorityQueue’s put didn’t
     increment unfinished tasks (this bug was introduced when
     JoinableQueue was merged with Queue).

   - bpo-23908(45): os functions now reject paths with embedded null
     character on Windows instead of silently truncating them.

   - bpo-23728(46): binascii.crc_hqx() could return an integer outside
     of the range 0-0xffff for empty data.

   - bpo-23887(47): urllib.error.HTTPError now has a proper repr()
     representation.  Patch by Berker Peksag.

   - asyncio: New event loop APIs: set_task_factory() and
     get_task_factory().

   - asyncio: async() function is deprecated in favour of
     ensure_future().

   - bpo-24178(48): asyncio.Lock, Condition, Semaphore, and
     BoundedSemaphore support new ’async with’ syntax.  Contributed by
     Yury Selivanov.

   - bpo-24179(49): Support ’async for’ for asyncio.StreamReader.
     Contributed by Yury Selivanov.

   - bpo-24184(50): Add AsyncIterator and AsyncIterable ABCs to
     collections.abc.  Contributed by Yury Selivanov.

   - bpo-22547(51): Implement informative __repr__ for
     inspect.BoundArguments.  Contributed by Yury Selivanov.

   - bpo-24190(52): Implement inspect.BoundArgument.apply_defaults()
     method.  Contributed by Yury Selivanov.

   - bpo-20691(53): Add ’follow_wrapped’ argument to
     inspect.Signature.from_callable() and inspect.signature().
     Contributed by Yury Selivanov.

   - bpo-24248(54): Deprecate inspect.Signature.from_function() and
     inspect.Signature.from_builtin().

   - bpo-23898(55): Fix inspect.classify_class_attrs() to support
     attributes with overloaded __eq__ and __bool__.  Patch by Mike
     Bayer.

   - bpo-24298(56): Fix inspect.signature() to correctly unwrap wrappers
     around bound methods.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14373

   (2) https://bugs.python.org/issue24230

   (3) https://bugs.python.org/issue22189

   (4) https://bugs.python.org/issue24244

   (5) https://bugs.python.org/issue23973

   (6) https://bugs.python.org/issue23086

   (7) https://bugs.python.org/issue20035

   (8) https://bugs.python.org/issue24257

   (9) https://bugs.python.org/issue15836

   (10) https://bugs.python.org/issue9858

   (11) https://bugs.python.org/issue22955

   (12) https://bugs.python.org/issue22107

   (13) https://bugs.python.org/issue23780

   (14) https://bugs.python.org/issue6598

   (15) https://bugs.python.org/issue24091

   (16) https://bugs.python.org/issue21931

   (17) https://bugs.python.org/issue13866

   (18) https://bugs.python.org/issue20098

   (19) https://bugs.python.org/issue24211

   (20) https://bugs.python.org/issue16314

   (21) https://bugs.python.org/issue21804

   (22) https://bugs.python.org/issue18682

   (23) https://bugs.python.org/issue22027

   (24) https://bugs.python.org/issue23488

   (25) https://bugs.python.org/issue1322

   (26) https://bugs.python.org/issue22486

   (27) https://bugs.python.org/issue24064

   (28) https://bugs.python.org/issue22681

   (29) https://bugs.python.org/issue22682

   (30) https://bugs.python.org/issue23796

   (31) https://bugs.python.org/issue21795

   (32) https://bugs.python.org/issue24155

   (33) https://bugs.python.org/issue21800

   (34) https://bugs.python.org/issue20274

   (35) https://bugs.python.org/issue20274

   (36) https://bugs.python.org/issue24134

   (37) https://bugs.python.org/issue24018

   (38) https://bugs.python.org/issue23880

   (39) https://bugs.python.org/issue22619

   (40) https://bugs.python.org/issue24094

   (41) https://bugs.python.org/issue9246

   (42) https://bugs.python.org/issue17445

   (43) https://bugs.python.org/issue23917

   (44) https://bugs.python.org/issue23008

   (45) https://bugs.python.org/issue23908

   (46) https://bugs.python.org/issue23728

   (47) https://bugs.python.org/issue23887

   (48) https://bugs.python.org/issue24178

   (49) https://bugs.python.org/issue24179

   (50) https://bugs.python.org/issue24184

   (51) https://bugs.python.org/issue22547

   (52) https://bugs.python.org/issue24190

   (53) https://bugs.python.org/issue20691

   (54) https://bugs.python.org/issue24248

   (55) https://bugs.python.org/issue23898

   (56) https://bugs.python.org/issue24298


File: python.info,  Node: IDLE<52>,  Next: 测试<51>,  Prev: 库<84>,  Up: Python 3 5 0 beta 1

1.18.84.3 IDLE
..............

   - bpo-23184(1): remove unused names and imports in idlelib.  Initial
     patch by Al Sweigart.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23184


File: python.info,  Node: 测试<51>,  Next: 文档<53>,  Prev: IDLE<52>,  Up: Python 3 5 0 beta 1

1.18.84.4 测试
..............

   - bpo-21520(1): test_zipfile no longer fails if the word ’bad’
     appears anywhere in the name of the current directory.

   - bpo-9517(2): Move script_helper into the support package.  Patch by
     Christie Wilson.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21520

   (2) https://bugs.python.org/issue9517


File: python.info,  Node: 文档<53>,  Next: 工具/示例<33>,  Prev: 测试<51>,  Up: Python 3 5 0 beta 1

1.18.84.5 文档
..............

   - bpo-22155(1): Add File Handlers subsection with createfilehandler
     to tkinter doc.  Remove obsolete example from FAQ. Patch by Martin
     Panter.

   - bpo-24029(2): Document the name binding behavior for submodule
     imports.

   - bpo-24077(3): Fix typo in man page for -I command option: -s, not
     -S

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22155

   (2) https://bugs.python.org/issue24029

   (3) https://bugs.python.org/issue24077


File: python.info,  Node: 工具/示例<33>,  Prev: 文档<53>,  Up: Python 3 5 0 beta 1

1.18.84.6 工具/示例
...................

   - bpo-24000(1): Improved Argument Clinic’s mapping of converters to
     legacy "format units".  Updated the documentation to match.

   - bpo-24001(2): Argument Clinic converters now use accept={type}
     instead of types={’type’} to specify the types the converter
     accepts.

   - bpo-23330(3): h2py now supports arbitrary filenames in #include.

   - bpo-24031(4): make patchcheck now supports git checkouts, too.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24000

   (2) https://bugs.python.org/issue24001

   (3) https://bugs.python.org/issue23330

   (4) https://bugs.python.org/issue24031


File: python.info,  Node: Python 3 5 0 alpha 4,  Next: Python 3 5 0 alpha 3,  Prev: Python 3 5 0 beta 1,  Up: 更新日志

1.18.85 Python 3.5.0 alpha 4
----------------------------

`发布日期: 2015-04-19'

* Menu:

* 核心与内置: 核心与内置<71>.
* 库: 库<85>.
* 构建: 构建<53>.
* 测试: 测试<52>.
* 工具/示例: 工具/示例<34>.
* C API: C API<36>.


File: python.info,  Node: 核心与内置<71>,  Next: 库<85>,  Up: Python 3 5 0 alpha 4

1.18.85.1 核心与内置
....................

   - bpo-22980(1): Under Linux, GNU/KFreeBSD and the Hurd, C extensions
     now include the architecture triplet in the extension name, to make
     it easy to test builds for different ABIs in the same working tree.
     Under OS X, the extension name now includes PEP 3149(2)-style
     information.

   - bpo-22631(3): Added Linux-specific socket constant
     CAN_RAW_FD_FRAMES. Patch courtesy of Joe Jevnik.

   - bpo-23731(4): Implement PEP 488(5): removal of .pyo files.

   - bpo-23726(6): Don’t enable GC for user subclasses of non-GC types
     that don’t add any new fields.  Patch by Eugene Toder.

   - bpo-23309(7): Avoid a deadlock at shutdown if a daemon thread is
     aborted while it is holding a lock to a buffered I/O object, and
     the main thread tries to use the same I/O object (typically stdout
     or stderr).  A fatal error is emitted instead.

   - bpo-22977(8): Fixed formatting Windows error messages on Wine.
     Patch by Martin Panter.

   - bpo-23466(9): %c, %o, %x, and %X in bytes formatting now raise
     TypeError on non-integer input.

   - bpo-24044(10): Fix possible null pointer dereference in list.sort
     in out of memory conditions.

   - bpo-21354(11): PyCFunction_New function is exposed by python DLL
     again.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22980

   (2) https://www.python.org/dev/peps/pep-3149

   (3) https://bugs.python.org/issue22631

   (4) https://bugs.python.org/issue23731

   (5) https://www.python.org/dev/peps/pep-0488

   (6) https://bugs.python.org/issue23726

   (7) https://bugs.python.org/issue23309

   (8) https://bugs.python.org/issue22977

   (9) https://bugs.python.org/issue23466

   (10) https://bugs.python.org/issue24044

   (11) https://bugs.python.org/issue21354


File: python.info,  Node: 库<85>,  Next: 构建<53>,  Prev: 核心与内置<71>,  Up: Python 3 5 0 alpha 4

1.18.85.2 库
............

   - bpo-23840(1): tokenize.open() now closes the temporary binary file
     on error to fix a resource warning.

   - bpo-16914(2): new debuglevel 2 in smtplib adds timestamps to debug
     output.

   - bpo-7159(3): urllib.request now supports sending auth credentials
     automatically after the first 401.  This enhancement is a superset
     of the enhancement from bpo-19494(4) and supersedes that change.

   - bpo-23703(5): Fix a regression in urljoin() introduced in
     901e4e52b20a.  Patch by Demian Brecht.

   - bpo-4254(6): Adds _curses.update_lines_cols().  Patch by Arnon
     Yaari

   - bpo-19933(7): Provide default argument for ndigits in round.  Patch
     by Vajrasky Kok.

   - bpo-23193(8): Add a numeric_owner parameter to
     tarfile.TarFile.extract and tarfile.TarFile.extractall.  Patch by
     Michael Vogt and Eric Smith.

   - bpo-23342(9): Add a subprocess.run() function than returns a
     CalledProcess instance for a more consistent API than the existing
     call* functions.

   - bpo-21217(10): inspect.getsourcelines() now tries to compute the
     start and end lines from the code object, fixing an issue when a
     lambda function is used as decorator argument.  Patch by Thomas
     Ballinger and Allison Kaptur.

   - bpo-24521(11): Fix possible integer overflows in the pickle module.

   - bpo-22931(12): Allow ’[’ and ’]’ in cookie values.

   - The keywords attribute of functools.partial is now always a
     dictionary.

   - bpo-23811(13): Add missing newline to the PyCompileError error
     message.  Patch by Alex Shkop.

   - bpo-21116(14): Avoid blowing memory when allocating a
     multiprocessing shared array that’s larger than 50% of the
     available RAM. Patch by Médéric Boquien.

   - bpo-22982(15): Improve BOM handling when seeking to multiple
     positions of a writable text file.

   - bpo-23464(16): Removed deprecated asyncio JoinableQueue.

   - bpo-23529(17): Limit the size of decompressed data when reading
     from GzipFile, BZ2File or LZMAFile.  This defeats denial of service
     attacks using compressed bombs (i.e.  compressed payloads which
     decompress to a huge size).  Patch by Martin Panter and Nikolaus
     Rath.

   - bpo-21859(18): Added Python implementation of io.FileIO.

   - bpo-23865(19): close() methods in multiple modules now are
     idempotent and more robust at shutdown.  If they need to release
     multiple resources, all are released even if errors occur.

   - bpo-23400(20): Raise same exception on both Python 2 and 3 if
     sem_open is not available.  Patch by Davin Potts.

   - bpo-10838(21): The subprocess now module includes SubprocessError
     and TimeoutError in its list of exported names for the users wild
     enough to use ‘from subprocess import *’.

   - bpo-23411(22): Added DefragResult, ParseResult, SplitResult,
     DefragResultBytes, ParseResultBytes, and SplitResultBytes to
     urllib.parse.__all__.  Patch by Martin Panter.

   - bpo-23881(23): urllib.request.ftpwrapper constructor now closes the
     socket if the FTP connection failed to fix a ResourceWarning.

   - bpo-23853(24): *note socket.socket.sendall(): 684. does no more
     reset the socket timeout each time data is sent successfully.  The
     socket timeout is now the maximum total duration to send all data.

   - bpo-22721(25): An order of multiline pprint output of set or dict
     containing orderable and non-orderable elements no longer depends
     on iteration order of set or dict.

   - bpo-15133(26): _tkinter.tkapp.getboolean() now supports Tcl_Obj and
     always returns bool.  tkinter.BooleanVar now validates input values
     (accepted bool, int, str, and Tcl_Obj).  tkinter.BooleanVar.get()
     now always returns bool.

   - bpo-10590(27): xml.sax.parseString() now supports string argument.

   - bpo-23338(28): Fixed formatting ctypes error messages on Cygwin.
     Patch by Makoto Kato.

   - bpo-15582(29): inspect.getdoc() now follows inheritance chains.

   - bpo-2175(30): SAX parsers now support a character stream of
     InputSource object.

   - bpo-16840(31): Tkinter now supports 64-bit integers added in Tcl
     8.4 and arbitrary precision integers added in Tcl 8.5.

   - bpo-23834(32): Fix socket.sendto(), use the C Py_ssize_t type to
     store the result of sendto() instead of the C int type.

   - bpo-23618(33): *note socket.socket.connect(): 67f. now waits until
     the connection completes instead of raising *note InterruptedError:
     662. if the connection is interrupted by signals, signal handlers
     don’t raise an exception and the socket is blocking or has a
     timeout.  *note socket.socket.connect(): 67f. still raise *note
     InterruptedError: 662. for non-blocking sockets.

   - bpo-21526(34): Tkinter now supports new boolean type in Tcl 8.5.

   - bpo-23836(35): Fix the faulthandler module to handle reentrant
     calls to its signal handlers.

   - bpo-23838(36): linecache now clears the cache and returns an empty
     result on MemoryError.

   - bpo-10395(37): Added os.path.commonpath().  Implemented in
     posixpath and ntpath.  Based on patch by Rafik Draoui.

   - bpo-23611(38): Serializing more "lookupable" objects (such as
     unbound methods or nested classes) now are supported with pickle
     protocols < 4.

   - bpo-13583(39): sqlite3.Row now supports slice indexing.

   - bpo-18473(40): Fixed 2to3 and 3to2 compatible pickle mappings.
     Fixed ambiguous reverse mappings.  Added many new mappings.  Import
     mapping is no longer applied to modules already mapped with full
     name mapping.

   - bpo-23485(41): select.select() is now retried automatically with
     the recomputed timeout when interrupted by a signal, except if the
     signal handler raises an exception.  This change is part of the PEP
     475(42).

   - bpo-23752(43): When built from an existing file descriptor,
     io.FileIO() now only calls fstat() once.  Before fstat() was called
     twice, which was not necessary.

   - bpo-23704(44): collections.deque() objects now support __add__,
     __mul__, and __imul__().

   - bpo-23171(45): csv.Writer.writerow() now supports arbitrary
     iterables.

   - bpo-23745(46): The new email header parser now handles duplicate
     MIME parameter names without error, similar to how get_param
     behaves.

   - bpo-22117(47): Fix os.utime(), it now rounds the timestamp towards
     minus infinity (-inf) instead of rounding towards zero.

   - bpo-23310(48): Fix MagicMock’s initializer to work with
     __methods__, just like configure_mock().  Patch by Kasia Jachim.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23840

   (2) https://bugs.python.org/issue16914

   (3) https://bugs.python.org/issue7159

   (4) https://bugs.python.org/issue19494

   (5) https://bugs.python.org/issue23703

   (6) https://bugs.python.org/issue4254

   (7) https://bugs.python.org/issue19933

   (8) https://bugs.python.org/issue23193

   (9) https://bugs.python.org/issue23342

   (10) https://bugs.python.org/issue21217

   (11) https://bugs.python.org/issue24521

   (12) https://bugs.python.org/issue22931

   (13) https://bugs.python.org/issue23811

   (14) https://bugs.python.org/issue21116

   (15) https://bugs.python.org/issue22982

   (16) https://bugs.python.org/issue23464

   (17) https://bugs.python.org/issue23529

   (18) https://bugs.python.org/issue21859

   (19) https://bugs.python.org/issue23865

   (20) https://bugs.python.org/issue23400

   (21) https://bugs.python.org/issue10838

   (22) https://bugs.python.org/issue23411

   (23) https://bugs.python.org/issue23881

   (24) https://bugs.python.org/issue23853

   (25) https://bugs.python.org/issue22721

   (26) https://bugs.python.org/issue15133

   (27) https://bugs.python.org/issue10590

   (28) https://bugs.python.org/issue23338

   (29) https://bugs.python.org/issue15582

   (30) https://bugs.python.org/issue2175

   (31) https://bugs.python.org/issue16840

   (32) https://bugs.python.org/issue23834

   (33) https://bugs.python.org/issue23618

   (34) https://bugs.python.org/issue21526

   (35) https://bugs.python.org/issue23836

   (36) https://bugs.python.org/issue23838

   (37) https://bugs.python.org/issue10395

   (38) https://bugs.python.org/issue23611

   (39) https://bugs.python.org/issue13583

   (40) https://bugs.python.org/issue18473

   (41) https://bugs.python.org/issue23485

   (42) https://www.python.org/dev/peps/pep-0475

   (43) https://bugs.python.org/issue23752

   (44) https://bugs.python.org/issue23704

   (45) https://bugs.python.org/issue23171

   (46) https://bugs.python.org/issue23745

   (47) https://bugs.python.org/issue22117

   (48) https://bugs.python.org/issue23310


File: python.info,  Node: 构建<53>,  Next: 测试<52>,  Prev: 库<85>,  Up: Python 3 5 0 alpha 4

1.18.85.3 构建
..............

   - bpo-23817(1): FreeBSD now uses "1.0" in the SOVERSION as other
     operating systems, instead of just "1".

   - bpo-23501(2): Argument Clinic now generates code into separate
     files by default.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23817

   (2) https://bugs.python.org/issue23501


File: python.info,  Node: 测试<52>,  Next: 工具/示例<34>,  Prev: 构建<53>,  Up: Python 3 5 0 alpha 4

1.18.85.4 测试
..............

   - bpo-23799(1): Added test.support.start_threads() for running and
     cleaning up multiple threads.

   - bpo-22390(2): test.regrtest now emits a warning if temporary files
     or directories are left after running a test.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23799

   (2) https://bugs.python.org/issue22390


File: python.info,  Node: 工具/示例<34>,  Next: C API<36>,  Prev: 测试<52>,  Up: Python 3 5 0 alpha 4

1.18.85.5 工具/示例
...................

   - bpo-18128(1): pygettext now uses standard +NNNN format in the
     POT-Creation-Date header.

   - bpo-23935(2): Argument Clinic’s understanding of format units
     accepting bytes, bytearrays, and buffers is now consistent with
     both the documentation and the implementation.

   - bpo-23944(3): Argument Clinic now wraps long impl prototypes at
     column 78.

   - bpo-20586(4): Argument Clinic now ensures that functions without
     docstrings have signatures.

   - bpo-23492(5): Argument Clinic now generates argument parsing code
     with PyArg_Parse instead of PyArg_ParseTuple if possible.

   - bpo-23500(6): Argument Clinic is now smarter about generating the
     "#ifndef" (empty) definition of the methoddef macro: it’s only
     generated once, even if Argument Clinic processes the same symbol
     multiple times, and it’s emitted at the end of all processing
     rather than immediately after the first use.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18128

   (2) https://bugs.python.org/issue23935

   (3) https://bugs.python.org/issue23944

   (4) https://bugs.python.org/issue20586

   (5) https://bugs.python.org/issue23492

   (6) https://bugs.python.org/issue23500


File: python.info,  Node: C API<36>,  Prev: 工具/示例<34>,  Up: Python 3 5 0 alpha 4

1.18.85.6 C API
...............

   - bpo-23998(1): PyImport_ReInitLock() now checks for lock allocation
     error

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23998


File: python.info,  Node: Python 3 5 0 alpha 3,  Next: Python 3 5 0 alpha 2,  Prev: Python 3 5 0 alpha 4,  Up: 更新日志

1.18.86 Python 3.5.0 alpha 3
----------------------------

`发布日期: 2015-03-28'

* Menu:

* 核心与内置: 核心与内置<72>.
* 库: 库<86>.
* 构建: 构建<54>.
* 测试: 测试<53>.
* 工具/示例: 工具/示例<35>.


File: python.info,  Node: 核心与内置<72>,  Next: 库<86>,  Up: Python 3 5 0 alpha 3

1.18.86.1 核心与内置
....................

   - bpo-23573(1): Increased performance of string search operations
     (str.find, str.index, str.count, the in operator, str.split,
     str.partition) with arguments of different kinds (UCS1, UCS2,
     UCS4).

   - bpo-23753(2): Python doesn’t support anymore platforms without
     stat() or fstat(), these functions are always required.

   - bpo-23681(3): The -b option now affects comparisons of bytes with
     int.

   - bpo-23632(4): Memoryviews now allow tuple indexing (including for
     multi-dimensional memoryviews).

   - bpo-23192(5): Fixed generator lambdas.  Patch by Bruno Cauet.

   - bpo-23629(6): Fix the default __sizeof__ implementation for
     variable-sized objects.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23573

   (2) https://bugs.python.org/issue23753

   (3) https://bugs.python.org/issue23681

   (4) https://bugs.python.org/issue23632

   (5) https://bugs.python.org/issue23192

   (6) https://bugs.python.org/issue23629


File: python.info,  Node: 库<86>,  Next: 构建<54>,  Prev: 核心与内置<72>,  Up: Python 3 5 0 alpha 3

1.18.86.2 库
............

   - bpo-14260(1): The groupindex attribute of regular expression
     pattern object now is non-modifiable mapping.

   - bpo-23792(2): Ignore KeyboardInterrupt when the pydoc pager is
     active.  This mimics the behavior of the standard unix pagers, and
     prevents pipepager from shutting down while the pager itself is
     still running.

   - bpo-23775(3): pprint() of OrderedDict now outputs the same
     representation as repr().

   - bpo-23765(4): Removed IsBadStringPtr calls in ctypes

   - bpo-22364(5): Improved some re error messages using regex for
     hints.

   - bpo-23742(6): ntpath.expandvars() no longer loses unbalanced single
     quotes.

   - bpo-21717(7): The zipfile.ZipFile.open function now supports ’x’
     (exclusive creation) mode.

   - bpo-21802(8): The reader in BufferedRWPair now is closed even when
     closing writer failed in BufferedRWPair.close().

   - bpo-23622(9): Unknown escapes in regular expressions that consist
     of ‘'\'’ and ASCII letter now raise a deprecation warning and will
     be forbidden in Python 3.6.

   - bpo-23671(10): string.Template now allows specifying the "self"
     parameter as a keyword argument.  string.Formatter now allows
     specifying the "self" and the "format_string" parameters as keyword
     arguments.

   - bpo-23502(11): The pprint module now supports mapping proxies.

   - bpo-17530(12): pprint now wraps long bytes objects and bytearrays.

   - bpo-22687(13): Fixed some corner cases in breaking words in
     tetxtwrap.  Got rid of quadratic complexity in breaking long words.

   - bpo-4727(14): The copy module now uses pickle protocol 4 (PEP 3154)
     and supports copying of instances of classes whose __new__ method
     takes keyword-only arguments.

   - bpo-23491(15): Added a zipapp module to support creating executable
     zip file archives of Python code.  Registered ".pyz" and ".pyzw"
     extensions on Windows for these archives (PEP 441).

   - bpo-23657(16): Avoid explicit checks for str in zipapp, adding
     support for pathlib.Path objects as arguments.

   - bpo-23688(17): Added support of arbitrary bytes-like objects and
     avoided unnecessary copying of memoryview in gzip.GzipFile.write().
     Original patch by Wolfgang Maier.

   - bpo-23252(18): Added support for writing ZIP files to unseekable
     streams.

   - bpo-23647(19): Increase imaplib’s MAXLINE to accommodate modern
     mailbox sizes.

   - bpo-23539(20): If body is None, http.client.HTTPConnection.request
     now sets Content-Length to 0 for PUT, POST, and PATCH headers to
     avoid 411 errors from some web servers.

   - bpo-22351(21): The nntplib.NNTP constructor no longer leaves the
     connection and socket open until the garbage collector cleans them
     up.  Patch by Martin Panter.

   - bpo-23704(22): collections.deque() objects now support methods for
     index(), insert(), and copy().  This allows deques to be registered
     as a MutableSequence and it improves their substitutability for
     lists.

   - bpo-23715(23): *note signal.sigwaitinfo(): 688. and *note
     signal.sigtimedwait(): 687. are now retried when interrupted by a
     signal not in the `sigset' parameter, if the signal handler does
     not raise an exception.  signal.sigtimedwait() recomputes the
     timeout with a monotonic clock when it is retried.

   - bpo-23001(24): Few functions in modules mmap, ossaudiodev, socket,
     ssl, and codecs, that accepted only read-only bytes-like object now
     accept writable bytes-like object too.

   - bpo-23646(25): If time.sleep() is interrupted by a signal, the
     sleep is now retried with the recomputed delay, except if the
     signal handler raises an exception (PEP 475).

   - bpo-23136(26): _strptime now uniformly handles all days in week 0,
     including Dec 30 of previous year.  Based on patch by Jim Carroll.

   - bpo-23700(27): Iterator of NamedTemporaryFile now keeps a reference
     to NamedTemporaryFile instance.  Patch by Bohuslav Kabrda.

   - bpo-22903(28): The fake test case created by unittest.loader when
     it fails importing a test module is now picklable.

   - bpo-22181(29): On Linux, os.urandom() now uses the new getrandom()
     syscall if available, syscall introduced in the Linux kernel 3.17.
     It is more reliable and more secure, because it avoids the need of
     a file descriptor and waits until the kernel has enough entropy.

   - bpo-2211(30): Updated the implementation of the http.cookies.Morsel
     class.  Setting attributes key, value and coded_value directly now
     is deprecated.  update() and setdefault() now transform and check
     keys.  Comparing for equality now takes into account attributes
     key, value and coded_value.  copy() now returns a Morsel, not a
     dict.  repr() now contains all attributes.  Optimized checking keys
     and quoting values.  Added new tests.  Original patch by Demian
     Brecht.

   - bpo-18983(31): Allow selection of output units in timeit.  Patch by
     Julian Gindi.

   - bpo-23631(32): Fix traceback.format_list when a traceback has been
     mutated.

   - bpo-23568(33): Add rdivmod support to MagicMock() objects.  Patch
     by Håkan Lövdahl.

   - bpo-2052(34): Add charset parameter to HtmlDiff.make_file().

   - bpo-23668(35): Support os.truncate and os.ftruncate on Windows.

   - bpo-23138(36): Fixed parsing cookies with absent keys or values in
     cookiejar.  Patch by Demian Brecht.

   - bpo-23051(37): multiprocessing.Pool methods imap() and
     imap_unordered() now handle exceptions raised by an iterator.
     Patch by Alon Diamant and Davin Potts.

   - bpo-23581(38): Add matmul support to MagicMock.  Patch by Håkan
     Lövdahl.

   - bpo-23566(39): enable(), register(), dump_traceback() and
     dump_traceback_later() functions of faulthandler now accept file
     descriptors.  Patch by Wei Wu.

   - bpo-22928(40): Disabled HTTP header injections in http.client.
     Original patch by Demian Brecht.

   - bpo-23615(41): Modules bz2, tarfile and tokenize now can be
     reloaded with imp.reload().  Patch by Thomas Kluyver.

   - bpo-23605(42): os.walk() now calls os.scandir() instead of
     os.listdir().  The usage of os.scandir() reduces the number of
     calls to os.stat().  Initial patch written by Ben Hoyt.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14260

   (2) https://bugs.python.org/issue23792

   (3) https://bugs.python.org/issue23775

   (4) https://bugs.python.org/issue23765

   (5) https://bugs.python.org/issue22364

   (6) https://bugs.python.org/issue23742

   (7) https://bugs.python.org/issue21717

   (8) https://bugs.python.org/issue21802

   (9) https://bugs.python.org/issue23622

   (10) https://bugs.python.org/issue23671

   (11) https://bugs.python.org/issue23502

   (12) https://bugs.python.org/issue17530

   (13) https://bugs.python.org/issue22687

   (14) https://bugs.python.org/issue4727

   (15) https://bugs.python.org/issue23491

   (16) https://bugs.python.org/issue23657

   (17) https://bugs.python.org/issue23688

   (18) https://bugs.python.org/issue23252

   (19) https://bugs.python.org/issue23647

   (20) https://bugs.python.org/issue23539

   (21) https://bugs.python.org/issue22351

   (22) https://bugs.python.org/issue23704

   (23) https://bugs.python.org/issue23715

   (24) https://bugs.python.org/issue23001

   (25) https://bugs.python.org/issue23646

   (26) https://bugs.python.org/issue23136

   (27) https://bugs.python.org/issue23700

   (28) https://bugs.python.org/issue22903

   (29) https://bugs.python.org/issue22181

   (30) https://bugs.python.org/issue2211

   (31) https://bugs.python.org/issue18983

   (32) https://bugs.python.org/issue23631

   (33) https://bugs.python.org/issue23568

   (34) https://bugs.python.org/issue2052

   (35) https://bugs.python.org/issue23668

   (36) https://bugs.python.org/issue23138

   (37) https://bugs.python.org/issue23051

   (38) https://bugs.python.org/issue23581

   (39) https://bugs.python.org/issue23566

   (40) https://bugs.python.org/issue22928

   (41) https://bugs.python.org/issue23615

   (42) https://bugs.python.org/issue23605


File: python.info,  Node: 构建<54>,  Next: 测试<53>,  Prev: 库<86>,  Up: Python 3 5 0 alpha 3

1.18.86.3 构建
..............

   - bpo-23585(1): make patchcheck will ensure the interpreter is built.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23585


File: python.info,  Node: 测试<53>,  Next: 工具/示例<35>,  Prev: 构建<54>,  Up: Python 3 5 0 alpha 3

1.18.86.4 测试
..............

   - bpo-23583(1): Added tests for standard IO streams in IDLE.

   - bpo-22289(2): Prevent test_urllib2net failures due to ftp
     connection timeout.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23583

   (2) https://bugs.python.org/issue22289


File: python.info,  Node: 工具/示例<35>,  Prev: 测试<53>,  Up: Python 3 5 0 alpha 3

1.18.86.5 工具/示例
...................

   - bpo-22826(1): The result of open() in Tools/freeze/bkfile.py is now
     better compatible with regular files (in particular it now supports
     the context management protocol).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22826


File: python.info,  Node: Python 3 5 0 alpha 2,  Next: Python 3 5 0 alpha 1,  Prev: Python 3 5 0 alpha 3,  Up: 更新日志

1.18.87 Python 3.5.0 alpha 2
----------------------------

`发布日期: 2015-03-09'

* Menu:

* 核心与内置: 核心与内置<73>.
* 库: 库<87>.
* 构建: 构建<55>.
* C API: C API<37>.
* Windows: Windows<51>.


File: python.info,  Node: 核心与内置<73>,  Next: 库<87>,  Up: Python 3 5 0 alpha 2

1.18.87.1 核心与内置
....................

   - bpo-23571(1): PyObject_Call() and PyCFunction_Call() now raise a
     SystemError if a function returns a result and raises an exception.
     The SystemError is chained to the previous exception.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23571


File: python.info,  Node: 库<87>,  Next: 构建<55>,  Prev: 核心与内置<73>,  Up: Python 3 5 0 alpha 2

1.18.87.2 库
............

   - bpo-22524(1): New os.scandir() function, part of the PEP 471(2):
     "os.scandir() function – a better and faster directory iterator".
     Patch written by Ben Hoyt.

   - bpo-23103(3): Reduced the memory consumption of IPv4Address and
     IPv6Address.

   - bpo-21793(4): BaseHTTPRequestHandler again logs response code as
     numeric, not as stringified enum.  Patch by Demian Brecht.

   - bpo-23476(5): In the ssl module, enable OpenSSL’s
     X509_V_FLAG_TRUSTED_FIRST flag on certificate stores when it is
     available.

   - bpo-23576(6): Avoid stalling in SSL reads when EOF has been reached
     in the SSL layer but the underlying connection hasn’t been closed.

   - bpo-23504(7): Added an __all__ to the types module.

   - bpo-23563(8): Optimized utility functions in urllib.parse.

   - bpo-7830(9): Flatten nested functools.partial.

   - bpo-20204(10): Added the __module__ attribute to _tkinter classes.

   - bpo-19980(11): Improved help() for non-recognized strings.
     help(’’) now shows the help on str.  help(’help’) now shows the
     help on help().  Original patch by Mark Lawrence.

   - bpo-23521(12): Corrected pure python implementation of timedelta
     division.  Eliminated OverflowError from ‘timedelta * float’ for
     some floats; Corrected rounding in timedelta true division.

   - bpo-21619(13): Popen objects no longer leave a zombie after exit in
     the with statement if the pipe was broken.  Patch by Martin Panter.

   - bpo-22936(14): Make it possible to show local variables in
     tracebacks for both the traceback module and unittest.

   - bpo-15955(15): Add an option to limit the output size in
     bz2.decompress().  Patch by Nikolaus Rath.

   - bpo-6639(16): Module-level turtle functions no longer raise
     TclError after closing the window.

   - bpo-814253(17): Group references and conditional group references
     now work in lookbehind assertions in regular expressions.  (See
     also: bpo-9179(18))

   - bpo-23215(19): Multibyte codecs with custom error handlers that
     ignores errors consumed too much memory and raised SystemError or
     MemoryError.  Original patch by Aleksi Torhamo.

   - bpo-5700(20): io.FileIO() called flush() after closing the file.
     flush() was not called in close() if closefd=False.

   - bpo-23374(21): Fixed pydoc failure with non-ASCII files when stdout
     encoding differs from file system encoding (e.g.  on Mac OS).

   - bpo-23481(22): Remove RC4 from the SSL module’s default cipher
     list.

   - bpo-21548(23): Fix pydoc.synopsis() and pydoc.apropos() on modules
     with empty docstrings.

   - bpo-22885(24): Fixed arbitrary code execution vulnerability in the
     dbm.dumb module.  Original patch by Claudiu Popa.

   - bpo-23239(25): ssl.match_hostname() now supports matching of IP
     addresses.

   - bpo-23146(26): Fix mishandling of absolute Windows paths with
     forward slashes in pathlib.

   - bpo-23096(27): Pickle representation of floats with protocol 0 now
     is the same for both Python and C implementations.

   - bpo-19105(28): pprint now more efficiently uses free space at the
     right.

   - bpo-14910(29): Add allow_abbrev parameter to
     argparse.ArgumentParser.  Patch by Jonathan Paugh, Steven Bethard,
     paul j3 and Daniel Eriksson.

   - bpo-21717(30): tarfile.open() now supports ’x’ (exclusive creation)
     mode.

   - bpo-23344(31): marshal.dumps() is now 20-25% faster on average.

   - bpo-20416(32): marshal.dumps() with protocols 3 and 4 is now 40-50%
     faster on average.

   - bpo-23421(33): Fixed compression in tarfile CLI. Patch by wdv4758h.

   - bpo-23367(34): Fix possible overflows in the unicodedata module.

   - bpo-23361(35): Fix possible overflow in Windows subprocess creation
     code.

   - logging.handlers.QueueListener now takes a respect_handler_level
     keyword argument which, if set to True, will pass messages to
     handlers taking handler levels into account.

   - bpo-19705(36): turtledemo now has a visual sorting algorithm demo.
     Original patch from Jason Yeo.

   - bpo-23801(37): Fix issue where cgi.FieldStorage did not always
     ignore the entire preamble to a multipart body.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22524

   (2) https://www.python.org/dev/peps/pep-0471

   (3) https://bugs.python.org/issue23103

   (4) https://bugs.python.org/issue21793

   (5) https://bugs.python.org/issue23476

   (6) https://bugs.python.org/issue23576

   (7) https://bugs.python.org/issue23504

   (8) https://bugs.python.org/issue23563

   (9) https://bugs.python.org/issue7830

   (10) https://bugs.python.org/issue20204

   (11) https://bugs.python.org/issue19980

   (12) https://bugs.python.org/issue23521

   (13) https://bugs.python.org/issue21619

   (14) https://bugs.python.org/issue22936

   (15) https://bugs.python.org/issue15955

   (16) https://bugs.python.org/issue6639

   (17) https://bugs.python.org/issue814253

   (18) https://bugs.python.org/issue9179

   (19) https://bugs.python.org/issue23215

   (20) https://bugs.python.org/issue5700

   (21) https://bugs.python.org/issue23374

   (22) https://bugs.python.org/issue23481

   (23) https://bugs.python.org/issue21548

   (24) https://bugs.python.org/issue22885

   (25) https://bugs.python.org/issue23239

   (26) https://bugs.python.org/issue23146

   (27) https://bugs.python.org/issue23096

   (28) https://bugs.python.org/issue19105

   (29) https://bugs.python.org/issue14910

   (30) https://bugs.python.org/issue21717

   (31) https://bugs.python.org/issue23344

   (32) https://bugs.python.org/issue20416

   (33) https://bugs.python.org/issue23421

   (34) https://bugs.python.org/issue23367

   (35) https://bugs.python.org/issue23361

   (36) https://bugs.python.org/issue19705

   (37) https://bugs.python.org/issue23801


File: python.info,  Node: 构建<55>,  Next: C API<37>,  Prev: 库<87>,  Up: Python 3 5 0 alpha 2

1.18.87.3 构建
..............

   - bpo-23445(1): pydebug builds now use "gcc -Og" where possible, to
     make the resulting executable faster.

   - bpo-23686(2): 更新OS X 10.5 安装程序以使用OpenSSL 1.0.2a.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23445

   (2) https://bugs.python.org/issue23686


File: python.info,  Node: C API<37>,  Next: Windows<51>,  Prev: 构建<55>,  Up: Python 3 5 0 alpha 2

1.18.87.4 C API
...............

   - bpo-20204(1): Deprecation warning is now raised for builtin types
     without the __module__ attribute.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20204


File: python.info,  Node: Windows<51>,  Prev: C API<37>,  Up: Python 3 5 0 alpha 2

1.18.87.5 Windows
.................

   - bpo-23465(1): Implement PEP 486(2) - Make the Python Launcher aware
     of virtual environments.  Patch by Paul Moore.

   - bpo-23437(3): Make user scripts directory versioned on Windows.
     Patch by Paul Moore.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23465

   (2) https://www.python.org/dev/peps/pep-0486

   (3) https://bugs.python.org/issue23437


File: python.info,  Node: Python 3 5 0 alpha 1,  Prev: Python 3 5 0 alpha 2,  Up: 更新日志

1.18.88 Python 3.5.0 alpha 1
----------------------------

`发布日期: 2015-02-08'

* Menu:

* 核心与内置: 核心与内置<74>.
* 库: 库<88>.
* IDLE: IDLE<53>.
* 构建: 构建<56>.
* C API: C API<38>.
* 文档: 文档<54>.
* 测试: 测试<54>.
* 工具/示例: 工具/示例<36>.
* Windows: Windows<52>.


File: python.info,  Node: 核心与内置<74>,  Next: 库<88>,  Up: Python 3 5 0 alpha 1

1.18.88.1 核心与内置
....................

   - bpo-23285(1): PEP 475 - EINTR handling.

   - bpo-22735(2): Fix many edge cases (including crashes) involving
     custom mro() implementations.

   - bpo-22896(3): Avoid using PyObject_AsCharBuffer(),
     PyObject_AsReadBuffer() and PyObject_AsWriteBuffer().

   - bpo-21295(4): Revert some changes (bpo-16795(5)) to AST line
     numbers and column offsets that constituted a regression.

   - bpo-22986(6): Allow changing an object’s __class__ between a
     dynamic type and static type in some cases.

   - bpo-15859(7): PyUnicode_EncodeFSDefault(), PyUnicode_EncodeMBCS()
     and PyUnicode_EncodeCodePage() now raise an exception if the object
     is not a Unicode object.  For PyUnicode_EncodeFSDefault(), it was
     already the case on platforms other than Windows.  Patch written by
     Campbell Barton.

   - bpo-21408(8): The default __ne__() now returns NotImplemented if
     __eq__() returned NotImplemented.  Original patch by Martin Panter.

   - bpo-23321(9): Fixed a crash in str.decode() when error handler
     returned replacement string longer than malformed input data.

   - bpo-22286(10): The "backslashreplace" error handlers now works with
     decoding and translating.

   - bpo-23253(11): Delay-load ShellExecute[AW] in os.startfile for
     reduced startup overhead on Windows.

   - bpo-22038(12): pyatomic.h now uses stdatomic.h or GCC built-in
     functions for atomic memory access if available.  Patch written by
     Vitor de Lima and Gustavo Temple.

   - bpo-20284(13): %-interpolation (aka printf) formatting added for
     bytes and bytearray.

   - bpo-23048(14): Fix jumping out of an infinite while loop in the
     pdb.

   - bpo-20335(15): bytes constructor now raises TypeError when encoding
     or errors is specified with non-string argument.  Based on patch by
     Renaud Blanch.

   - bpo-22834(16): If the current working directory ends up being set
     to a non-existent directory then import will no longer raise
     FileNotFoundError.

   - bpo-22869(17): Move the interpreter startup & shutdown code to a
     new dedicated pylifecycle.c module

   - bpo-22847(18): Improve method cache efficiency.

   - bpo-22335(19): Fix crash when trying to enlarge a bytearray to
     0x7fffffff bytes on a 32-bit platform.

   - bpo-22653(20): Fix an assertion failure in debug mode when doing a
     reentrant dict insertion in debug mode.

   - bpo-22643(21): Fix integer overflow in Unicode case operations
     (upper, lower, title, swapcase, casefold).

   - bpo-17636(22): Circular imports involving relative imports are now
     supported.

   - bpo-22604(23): Fix assertion error in debug mode when dividing a
     complex number by (nan+0j).

   - bpo-21052(24): Do not raise ImportWarning when sys.path_hooks or
     sys.meta_path are set to None.

   - bpo-16518(25): Use ’bytes-like object required’ in error messages
     that previously used the far more cryptic "’x’ does not support the
     buffer protocol.

   - bpo-22470(26): Fixed integer overflow issues in "backslashreplace",
     "xmlcharrefreplace", and "surrogatepass" error handlers.

   - bpo-22540(27): speed up ‘PyObject_IsInstance’ and
     ‘PyObject_IsSubclass’ in the common case that the second argument
     has metaclass *note type: 611.

   - bpo-18711(28): Add a new ‘PyErr_FormatV’ function, similar to
     ‘PyErr_Format’ but accepting a ‘va_list’ argument.

   - bpo-22520(29): Fix overflow checking when generating the repr of a
     unicode object.

   - bpo-22519(30): Fix overflow checking in PyBytes_Repr.

   - bpo-22518(31): Fix integer overflow issues in latin-1 encoding.

   - bpo-16324(32): _charset parameter of MIMEText now also accepts
     email.charset.Charset instances.  Initial patch by Claude Paroz.

   - bpo-1764286(33): Fix inspect.getsource() to support decorated
     functions.  Patch by Claudiu Popa.

   - bpo-18554(34): os.__all__ includes posix functions.

   - bpo-21391(35): Use os.path.abspath in the shutil module.

   - bpo-11471(36): avoid generating a JUMP_FORWARD instruction at the
     end of an if-block if there is no else-clause.  Original patch by
     Eugene Toder.

   - bpo-22215(37): Now ValueError is raised instead of TypeError when
     str or bytes argument contains not permitted null character or
     byte.

   - bpo-22258(38): Fix the internal function set_inheritable() on
     Illumos.  This platform exposes the function ‘ioctl(FIOCLEX)’, but
     calling it fails with errno is ENOTTY: "Inappropriate ioctl for
     device".  set_inheritable() now falls back to the slower ‘fcntl()’
     (‘F_GETFD’ and then ‘F_SETFD’).

   - bpo-21389(39): Displaying the __qualname__ of the underlying
     function in the repr of a bound method.

   - bpo-22206(40): Using pthread, PyThread_create_key() now sets errno
     to ENOMEM and returns -1 (error) on integer overflow.

   - bpo-20184(41): Argument Clinic based signature introspection added
     for 30 of the builtin functions.

   - bpo-22116(42): C functions and methods (of the
     ’builtin_function_or_method’ type) can now be weakref’ed.  Patch by
     Wei Wu.

   - bpo-22077(43): Improve index error messages for bytearrays, bytes,
     lists, and tuples by adding ’or slices’.  Added ’, not <typename>’
     for bytearrays.  Original patch by Claudiu Popa.

   - bpo-20179(44): Apply Argument Clinic to bytes and bytearray.  Patch
     by Tal Einat.

   - bpo-22082(45): Clear interned strings in slotdefs.

   - 升级 Unicode 数据库到 7.0.0 版本。

   - bpo-21897(46): Fix a crash with the f_locals attribute with closure
     variables when frame.clear() has been called.

   - bpo-21205(47): Add a new ‘__qualname__’ attribute to generator, the
     qualified name, and use it in the representation of a generator
     (‘repr(gen)’).  The default name of the generator (‘__name__’
     attribute) is now get from the function instead of the code.  Use
     ‘gen.gi_code.co_name’ to get the name of the code.

   - bpo-21669(48): With the aid of heuristics in SyntaxError.__init__,
     the parser now attempts to generate more meaningful (or at least
     more search engine friendly) error messages when "exec" and "print"
     are used as statements.

   - bpo-21642(49): In the conditional if-else expression, allow an
     integer written with no space between itself and the ‘else’ keyword
     (e.g.  ‘True if 42else False’) to be valid syntax.

   - bpo-21523(50): Fix over-pessimistic computation of the stack effect
     of some opcodes in the compiler.  This also fixes a quadratic
     compilation time issue noticeable when compiling code with a large
     number of "and" and "or" operators.

   - bpo-21418(51): Fix a crash in the builtin function super() when
     called without argument and without current frame (ex: embedded
     Python).

   - bpo-21425(52): Fix flushing of standard streams in the interactive
     interpreter.

   - bpo-21435(53): In rare cases, when running finalizers on objects in
     cyclic trash a bad pointer dereference could occur due to a subtle
     flaw in internal iteration logic.

   - bpo-21377(54): PyBytes_Concat() now tries to concatenate in-place
     when the first argument has a reference count of 1.  Patch by
     Nikolaus Rath.

   - bpo-20355(55): -W command line options now have higher priority
     than the PYTHONWARNINGS environment variable.  Patch by Arfrever.

   - bpo-21274(56): Define PATH_MAX for GNU/Hurd in Python/pythonrun.c.

   - bpo-20904(57): Support setting FPU precision on m68k.

   - bpo-21209(58): Fix sending tuples to custom generator objects with
     the yield from syntax.

   - bpo-21193(59): pow(a, b, c) now raises ValueError rather than
     TypeError when b is negative.  Patch by Josh Rosenberg.

   - bpo-21176(60): PEP 465: Add the ’@’ operator for matrix
     multiplication.

   - bpo-21134(61): Fix segfault when str is called on an uninitialized
     UnicodeEncodeError, UnicodeDecodeError, or UnicodeTranslateError
     object.

   - bpo-19537(62): Fix PyUnicode_DATA() alignment under m68k.  Patch by
     Andreas Schwab.

   - bpo-20929(63): Add a type cast to avoid shifting a negative number.

   - bpo-20731(64): Properly position in source code files even if they
     are opened in text mode.  Patch by Serhiy Storchaka.

   - bpo-20637(65): Key-sharing now also works for instance dictionaries
     of subclasses.  Patch by Peter Ingebretson.

   - bpo-8297(66): Attributes missing from modules now include the
     module name in the error text.  Original patch by ysj.ray.

   - bpo-19995(67): %c, %o, %x, and %X now raise TypeError on
     non-integer input.

   - bpo-19655(68): The ASDL parser - used by the build process to
     generate code for managing the Python AST in C - was rewritten.
     The new parser is self contained and does not require to carry long
     the spark.py parser-generator library; spark.py was removed from
     the source base.

   - bpo-12546(69): Allow ‘\x00’ to be used as a fill character when
     using str, int, float, and complex __format__ methods.

   - bpo-20480(70): Add ipaddress.reverse_pointer.  Patch by Leon Weber.

   - bpo-13598(71): Modify string.Formatter to support auto-numbering of
     replacement fields.  It now matches the behavior of str.format() in
     this regard.  Patches by Phil Elson and Ramchandra Apte.

   - bpo-8931(72): Make alternate formatting (’#’) for type ’c’ raise an
     exception.  In versions prior to 3.5, ’#’ with ’c’ had no effect.
     Now specifying it is an error.  Patch by Torsten Landschoff.

   - bpo-23165(73): Perform overflow checks before allocating memory in
     the _Py_char2wchar function.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23285

   (2) https://bugs.python.org/issue22735

   (3) https://bugs.python.org/issue22896

   (4) https://bugs.python.org/issue21295

   (5) https://bugs.python.org/issue16795

   (6) https://bugs.python.org/issue22986

   (7) https://bugs.python.org/issue15859

   (8) https://bugs.python.org/issue21408

   (9) https://bugs.python.org/issue23321

   (10) https://bugs.python.org/issue22286

   (11) https://bugs.python.org/issue23253

   (12) https://bugs.python.org/issue22038

   (13) https://bugs.python.org/issue20284

   (14) https://bugs.python.org/issue23048

   (15) https://bugs.python.org/issue20335

   (16) https://bugs.python.org/issue22834

   (17) https://bugs.python.org/issue22869

   (18) https://bugs.python.org/issue22847

   (19) https://bugs.python.org/issue22335

   (20) https://bugs.python.org/issue22653

   (21) https://bugs.python.org/issue22643

   (22) https://bugs.python.org/issue17636

   (23) https://bugs.python.org/issue22604

   (24) https://bugs.python.org/issue21052

   (25) https://bugs.python.org/issue16518

   (26) https://bugs.python.org/issue22470

   (27) https://bugs.python.org/issue22540

   (28) https://bugs.python.org/issue18711

   (29) https://bugs.python.org/issue22520

   (30) https://bugs.python.org/issue22519

   (31) https://bugs.python.org/issue22518

   (32) https://bugs.python.org/issue16324

   (33) https://bugs.python.org/issue1764286

   (34) https://bugs.python.org/issue18554

   (35) https://bugs.python.org/issue21391

   (36) https://bugs.python.org/issue11471

   (37) https://bugs.python.org/issue22215

   (38) https://bugs.python.org/issue22258

   (39) https://bugs.python.org/issue21389

   (40) https://bugs.python.org/issue22206

   (41) https://bugs.python.org/issue20184

   (42) https://bugs.python.org/issue22116

   (43) https://bugs.python.org/issue22077

   (44) https://bugs.python.org/issue20179

   (45) https://bugs.python.org/issue22082

   (46) https://bugs.python.org/issue21897

   (47) https://bugs.python.org/issue21205

   (48) https://bugs.python.org/issue21669

   (49) https://bugs.python.org/issue21642

   (50) https://bugs.python.org/issue21523

   (51) https://bugs.python.org/issue21418

   (52) https://bugs.python.org/issue21425

   (53) https://bugs.python.org/issue21435

   (54) https://bugs.python.org/issue21377

   (55) https://bugs.python.org/issue20355

   (56) https://bugs.python.org/issue21274

   (57) https://bugs.python.org/issue20904

   (58) https://bugs.python.org/issue21209

   (59) https://bugs.python.org/issue21193

   (60) https://bugs.python.org/issue21176

   (61) https://bugs.python.org/issue21134

   (62) https://bugs.python.org/issue19537

   (63) https://bugs.python.org/issue20929

   (64) https://bugs.python.org/issue20731

   (65) https://bugs.python.org/issue20637

   (66) https://bugs.python.org/issue8297

   (67) https://bugs.python.org/issue19995

   (68) https://bugs.python.org/issue19655

   (69) https://bugs.python.org/issue12546

   (70) https://bugs.python.org/issue20480

   (71) https://bugs.python.org/issue13598

   (72) https://bugs.python.org/issue8931

   (73) https://bugs.python.org/issue23165


File: python.info,  Node: 库<88>,  Next: IDLE<53>,  Prev: 核心与内置<74>,  Up: Python 3 5 0 alpha 1

1.18.88.2 库
............

   - bpo-23399(1): pyvenv creates relative symlinks where possible.

   - bpo-20289(2): cgi.FieldStorage() now supports the context
     management protocol.

   - bpo-13128(3): Print response headers for CONNECT requests when
     debuglevel > 0.  Patch by Demian Brecht.

   - bpo-15381(4): Optimized io.BytesIO to make less allocations and
     copyings.

   - bpo-22818(5): Splitting on a pattern that could match an empty
     string now raises a warning.  Patterns that can only match empty
     strings are now rejected.

   - bpo-23099(6): Closing io.BytesIO with exported buffer is rejected
     now to prevent corrupting exported buffer.

   - bpo-23326(7): Removed __ne__ implementations.  Since fixing default
     __ne__ implementation in bpo-21408(8) they are redundant.

   - bpo-23363(9): Fix possible overflow in itertools.permutations.

   - bpo-23364(10): Fix possible overflow in itertools.product.

   - bpo-23366(11): Fixed possible integer overflow in
     itertools.combinations.

   - bpo-23369(12): Fixed possible integer overflow in
     _json.encode_basestring_ascii.

   - bpo-23353(13): Fix the exception handling of generators in
     PyEval_EvalFrameEx().  At entry, save or swap the exception state
     even if PyEval_EvalFrameEx() is called with throwflag=0.  At exit,
     the exception state is now always restored or swapped, not only if
     why is WHY_YIELD or WHY_RETURN. Patch co-written with Antoine
     Pitrou.

   - bpo-14099(14): Restored support of writing ZIP files to tellable
     but non-seekable streams.

   - bpo-14099(15): Writing to ZipFile and reading multiple ZipExtFiles
     is threadsafe now.

   - bpo-19361(16): JSON decoder now raises JSONDecodeError instead of
     ValueError.

   - bpo-18518(17): timeit now rejects statements which can’t be
     compiled outside a function or a loop (e.g.  "return" or "break").

   - bpo-23094(18): Fixed readline with frames in Python implementation
     of pickle.

   - bpo-23268(19): Fixed bugs in the comparison of ipaddress classes.

   - bpo-21408(20): Removed incorrect implementations of __ne__() which
     didn’t returned NotImplemented if __eq__() returned NotImplemented.
     The default __ne__() now works correctly.

   - bpo-19996(21): ‘email.feedparser.FeedParser’ now handles
     (malformed) headers with no key rather than assuming the body has
     started.

   - bpo-20188(22): Support Application-Layer Protocol Negotiation
     (ALPN) in the ssl module.

   - bpo-23133(23): Pickling of ipaddress objects now produces more
     compact and portable representation.

   - bpo-23248(24): 从最新的OpenSSL git master更新SSL错误代码。

   - bpo-23266(25): Much faster implementation of
     ipaddress.collapse_addresses() when there are many non-consecutive
     addresses.

   - bpo-23098(26): 64-bit dev_t is now supported in the os module.

   - bpo-21817(27): When an exception is raised in a task submitted to a
     ProcessPoolExecutor, the remote traceback is now displayed in the
     parent process.  Patch by Claudiu Popa.

   - bpo-15955(28): Add an option to limit output size when
     decompressing LZMA data.  Patch by Nikolaus Rath and Martin Panter.

   - bpo-23250(29): In the http.cookies module, capitalize "HttpOnly"
     and "Secure" as they are written in the standard.

   - bpo-23063(30): In the distutils’ check command, fix parsing of reST
     with code or code-block directives.

   - bpo-23209(31): selectors.BaseSelector.get_key() now raises a
     RuntimeError if the selector is closed.  And
     selectors.BaseSelector.close() now clears its internal reference to
     the selector mapping to break a reference cycle.  Initial patch
     written by Martin Richard.  (See also: bpo-23225(32))

   - bpo-17911(33): Provide a way to seed the linecache for a PEP-302
     module without actually loading the code.

   - bpo-17911(34): Provide a new object API for traceback, including
     the ability to not lookup lines at all until the traceback is
     actually rendered, without any trace of the original objects being
     kept alive.

   - bpo-19777(35): Provide a home() classmethod on Path objects.
     Contributed by Victor Salgado and Mayank Tripathi.

   - bpo-23206(36): Make ‘json.dumps(..., ensure_ascii=False)’ as fast
     as the default case of ‘ensure_ascii=True’.  Patch by Naoki Inada.

   - bpo-23185(37): Add math.inf and math.nan constants.

   - bpo-23186(38): Add ssl.SSLObject.shared_ciphers() and
     ssl.SSLSocket.shared_ciphers() to fetch the client’s list ciphers
     sent at handshake.

   - bpo-23143(39): Remove compatibility with OpenSSLs older than 0.9.8.

   - bpo-23132(40): Improve performance and introspection support of
     comparison methods created by functool.total_ordering.

   - bpo-19776(41): Add an expanduser() method on Path objects.

   - bpo-23112(42): Fix SimpleHTTPServer to correctly carry the query
     string and fragment when it redirects to add a trailing slash.

   - bpo-21793(43): Added http.HTTPStatus enums (i.e.  HTTPStatus.OK,
     HTTPStatus.NOT_FOUND). Patch by Demian Brecht.

   - bpo-23093(44): In the io, module allow more operations to work on
     detached streams.

   - bpo-23111(45): In the ftplib, make ssl.PROTOCOL_SSLv23 the default
     protocol version.

   - bpo-22585(46): On OpenBSD 5.6 and newer, os.urandom() now calls
     getentropy(), instead of reading /dev/urandom, to get pseudo-random
     bytes.

   - bpo-19104(47): pprint now produces evaluable output for wrapped
     strings.

   - bpo-23071(48): Added missing names to codecs.__all__.  Patch by
     Martin Panter.

   - bpo-22783(49): Pickling now uses the NEWOBJ opcode instead of the
     NEWOBJ_EX opcode if possible.

   - bpo-15513(50): Added a __sizeof__ implementation for pickle
     classes.

   - bpo-19858(51): pickletools.optimize() now aware of the MEMOIZE
     opcode, can produce more compact result and no longer produces
     invalid output if input data contains MEMOIZE opcodes together with
     PUT or BINPUT opcodes.

   - bpo-22095(52): Fixed HTTPConnection.set_tunnel with default port.
     The port value in the host header was set to "None".  Patch by
     Demian Brecht.

   - bpo-23016(53): A warning no longer produces an AttributeError when
     the program is run with pythonw.exe.

   - bpo-21775(54): shutil.copytree(): fix crash when copying to VFAT.
     An exception handler assumed that OSError objects always have a
     ’winerror’ attribute.  That is not the case, so the exception
     handler itself raised AttributeError when run on Linux (and,
     presumably, any other non-Windows OS). Patch by Greg Ward.

   - bpo-1218234(55): Fix inspect.getsource() to load updated source of
     reloaded module.  Initial patch by Berker Peksag.

   - bpo-21740(56): Support wrapped callables in doctest.  Patch by
     Claudiu Popa.

   - bpo-23009(57): Make sure selectors.EpollSelector.select() works
     when no FD is registered.

   - bpo-22959(58): In the constructor of http.client.HTTPSConnection,
     prefer the context’s check_hostname attribute over the
     `check_hostname' parameter.

   - bpo-22696(59): Add function *note sys.is_finalizing(): 76b. to know
     about interpreter shutdown.

   - bpo-16043(60): Add a default limit for the amount of data
     xmlrpclib.gzip_decode will return.  This resolves CVE-2013-1753.

   - bpo-14099(61): ZipFile.open() no longer reopen the underlying file.
     Objects returned by ZipFile.open() can now operate independently of
     the ZipFile even if the ZipFile was created by passing in a
     file-like object as the first argument to the constructor.

   - bpo-22966(62): Fix __pycache__ pyc file name clobber when
     pyc_compile is asked to compile a source file containing multiple
     dots in the source file name.

   - bpo-21971(63): Update turtledemo doc and add module to the index.

   - bpo-21032(64): Fixed socket leak if HTTPConnection.getresponse()
     fails.  Original patch by Martin Panter.

   - bpo-22407(65): Deprecated the use of re.LOCALE flag with str
     patterns or re.ASCII. It was newer worked.

   - bpo-22902(66): The "ip" command is now used on Linux to determine
     MAC address in uuid.getnode().  Pach by Bruno Cauet.

   - bpo-22960(67): Add a context argument to xmlrpclib.ServerProxy
     constructor.

   - bpo-22389(68): Add contextlib.redirect_stderr().

   - bpo-21356(69): Make ssl.RAND_egd() optional to support LibreSSL.
     The availability of the function is checked during the compilation.
     Patch written by Bernard Spil.

   - bpo-22915(70): SAX parser now supports files opened with file
     descriptor or bytes path.

   - bpo-22609(71): Constructors and update methods of mapping classes
     in the collections module now accept the self keyword argument.

   - bpo-22940(72): Add readline.append_history_file.

   - bpo-19676(73): Added the "namereplace" error handler.

   - bpo-22788(74): Add `context' parameter to
     logging.handlers.HTTPHandler.

   - bpo-22921(75): Allow SSLContext to take the `hostname' parameter
     even if OpenSSL doesn’t support SNI.

   - bpo-22894(76): TestCase.subTest() would cause the test suite to be
     stopped when in failfast mode, even in the absence of failures.

   - bpo-22796(77): HTTP cookie parsing is now stricter, in order to
     protect against potential injection attacks.

   - bpo-22370(78): Windows detection in pathlib is now more robust.

   - bpo-22841(79): Reject coroutines in asyncio add_signal_handler().
     Patch by Ludovic.Gasc.

   - bpo-19494(80): Added urllib.request.HTTPBasicPriorAuthHandler.
     Patch by Matej Cepl.

   - bpo-22578(81): Added attributes to the re.error class.

   - bpo-22849(82): Fix possible double free in the io.TextIOWrapper
     constructor.

   - bpo-12728(83): Different Unicode characters having the same
     uppercase but different lowercase are now matched in
     case-insensitive regular expressions.

   - bpo-22821(84): Fixed fcntl() with integer argument on 64-bit
     big-endian platforms.

   - bpo-21650(85): Add an ‘--sort-keys’ option to json.tool CLI.

   - bpo-22824(86): Updated reprlib output format for sets to use set
     literals.  Patch contributed by Berker Peksag.

   - bpo-22824(87): Updated reprlib output format for arrays to display
     empty arrays without an unnecessary empty list.  Suggested by
     Serhiy Storchaka.

   - bpo-22406(88): Fixed the uu_codec codec incorrectly ported to 3.x.
     Based on patch by Martin Panter.

   - bpo-17293(89): uuid.getnode() now determines MAC address on AIX
     using netstat.  Based on patch by Aivars Kalvāns.

   - bpo-22769(90): Fixed ttk.Treeview.tag_has() when called without
     arguments.

   - bpo-22417(91): Verify certificates by default in httplib (PEP 476).

   - bpo-22775(92): Fixed unpickling of http.cookies.SimpleCookie with
     protocol 2 and above.  Patch by Tim Graham.

   - bpo-22776(93): Brought excluded code into the scope of a try block
     in SysLogHandler.emit().

   - bpo-22665(94): Add missing get_terminal_size and SameFileError to
     shutil.__all__.

   - bpo-6623(95): Remove deprecated Netrc class in the ftplib module.
     Patch by Matt Chaput.

   - bpo-17381(96): Fixed handling of case-insensitive ranges in regular
     expressions.

   - bpo-22410(97): Module level functions in the re module now cache
     compiled locale-dependent regular expressions taking into account
     the locale.

   - bpo-22759(98): Query methods on pathlib.Path() (exists(), is_dir(),
     etc.)  now return False when the underlying stat call raises
     NotADirectoryError.

   - bpo-8876(99): distutils now falls back to copying files when hard
     linking doesn’t work.  This allows use with special filesystems
     such as VirtualBox shared folders.

   - bpo-22217(100): Implemented reprs of classes in the zipfile module.

   - bpo-22457(101): Honour load_tests in the start_dir of discovery.

   - bpo-18216(102): gettext now raises an error when a .mo file has an
     unsupported major version number.  Patch by Aaron Hill.

   - bpo-13918(103): Provide a locale.delocalize() function which can
     remove locale-specific number formatting from a string representing
     a number, without then converting it to a specific type.  Patch by
     Cédric Krier.

   - bpo-22676(104): Make the pickling of global objects which don’t
     have a __module__ attribute less slow.

   - bpo-18853(105): Fixed ResourceWarning in shlex.__nain__.

   - bpo-9351(106): Defaults set with set_defaults on an argparse
     subparser are no longer ignored when also set on the parent parser.

   - bpo-7559(107): unittest test loading ImportErrors are reported as
     import errors with their import exception rather than as attribute
     errors after the import has already failed.

   - bpo-19746(108): Make it possible to examine the errors from
     unittest discovery without executing the test suite.  The new
     ‘errors’ attribute on TestLoader exposes these non-fatal errors
     encountered during discovery.

   - bpo-21991(109): Make email.headerregistry’s header ’params’
     attributes be read-only (MappingProxyType).  Previously the
     dictionary was modifiable but a new one was created on each access
     of the attribute.

   - bpo-22638(110): SSLv3 is now disabled throughout the standard
     library.  It can still be enabled by instantiating a SSLContext
     manually.

   - bpo-22641(111): In asyncio, the default SSL context for client
     connections is now created using ssl.create_default_context(), for
     stronger security.

   - bpo-17401(112): Include closefd in io.FileIO repr.

   - bpo-21338(113): Add silent mode for compileall.  quiet parameters
     of compile_{dir, file, path} functions now have a multilevel value.
     Also, -q option of the CLI now have a multilevel value.  Patch by
     Thomas Kluyver.

   - bpo-20152(114): Convert the array and cmath modules to Argument
     Clinic.

   - bpo-18643(115): Add socket.socketpair() on Windows.

   - bpo-22435(116): Fix a file descriptor leak when socketserver bind
     fails.

   - bpo-13096(117): Fixed segfault in CTypes POINTER handling of large
     values.

   - bpo-11694(118): Raise ConversionError in xdrlib as documented.
     Patch by Filip Gruszczyński and Claudiu Popa.

   - bpo-19380(119): Optimized parsing of regular expressions.

   - bpo-1519638(120): Now unmatched groups are replaced with empty
     strings in re.sub() and re.subn().

   - bpo-18615(121): sndhdr.what/whathdr now return a namedtuple.

   - bpo-22462(122): Fix pyexpat’s creation of a dummy frame to make it
     appear in exception tracebacks.

   - bpo-21965(123): Add support for in-memory SSL to the ssl module.
     Patch by Geert Jansen.

   - bpo-21173(124): Fix len() on a WeakKeyDictionary when .clear() was
     called with an iterator alive.

   - bpo-11866(125): Eliminated race condition in the computation of
     names for new threads.

   - bpo-21905(126): Avoid RuntimeError in pickle.whichmodule() when
     sys.modules is mutated while iterating.  Patch by Olivier Grisel.

   - bpo-11271(127): concurrent.futures.Executor.map() now takes a
     `chunksize' argument to allow batching of tasks in child processes
     and improve performance of ProcessPoolExecutor.  Patch by Dan
     O’Reilly.

   - bpo-21883(128): os.path.join() and os.path.relpath() now raise a
     TypeError with more helpful error message for unsupported or
     mismatched types of arguments.

   - bpo-22219(129): The zipfile module CLI now adds entries for
     directories (including empty directories) in ZIP file.

   - bpo-22449(130): In the ssl.SSLContext.load_default_certs, consult
     the environmental variables SSL_CERT_DIR and SSL_CERT_FILE on
     Windows.

   - bpo-22508(131): The email.__version__ variable has been removed;
     the email code is no longer shipped separately from the stdlib, and
     __version__ hasn’t been updated in several releases.

   - bpo-20076(132): Added non derived UTF-8 aliases to locale aliases
     table.

   - bpo-20079(133): Added locales supported in glibc 2.18 to locale
     alias table.

   - bpo-20218(134): Added convenience methods read_text/write_text and
     read_bytes/ write_bytes to pathlib.Path objects.

   - bpo-22396(135): On 32-bit AIX platform, don’t expose
     os.posix_fadvise() nor os.posix_fallocate() because their
     prototypes in system headers are wrong.

   - bpo-22517(136): When an io.BufferedRWPair object is deallocated,
     clear its weakrefs.

   - bpo-22437(137): Number of capturing groups in regular expression is
     no longer limited by 100.

   - bpo-17442(138): InteractiveInterpreter now displays the full
     chained traceback in its showtraceback method, to match the built
     in interactive interpreter.

   - bpo-23392(139): Added tests for marshal C API that works with
     FILE*.

   - bpo-10510(140): distutils register and upload methods now use HTML
     standards compliant CRLF line endings.

   - bpo-9850(141): Fixed macpath.join() for empty first component.
     Patch by Oleg Oshmyan.

   - bpo-5309(142): distutils’ build and build_ext commands now accept a
     ‘-j’ option to enable parallel building of extension modules.

   - bpo-22448(143): Improve canceled timer handles cleanup to prevent
     unbound memory usage.  Patch by Joshua Moore-Oliva.

   - bpo-22427(144): TemporaryDirectory no longer attempts to clean up
     twice when used in the with statement in generator.

   - bpo-22362(145): Forbidden ambiguous octal escapes out of range
     0-0o377 in regular expressions.

   - bpo-20912(146): Now directories added to ZIP file have correct Unix
     and MS-DOS directory attributes.

   - bpo-21866(147): ZipFile.close() no longer writes ZIP64 central
     directory records if allowZip64 is false.

   - bpo-22278(148): Fix urljoin problem with relative urls, a
     regression observed after changes to issue22118 were submitted.

   - bpo-22415(149): Fixed debugging output of the GROUPREF_EXISTS
     opcode in the re module.  Removed trailing spaces in debugging
     output.

   - bpo-22423(150): Unhandled exception in thread no longer causes
     unhandled AttributeError when sys.stderr is None.

   - bpo-21332(151): Ensure that ‘bufsize=1’ in subprocess.Popen()
     selects line buffering, rather than block buffering.  Patch by
     Akira Li.

   - bpo-21091(152): Fix API bug:
     email.message.EmailMessage.is_attachment is now a method.

   - bpo-21079(153): Fix email.message.EmailMessage.is_attachment to
     return the correct result when the header has parameters as well as
     a value.

   - bpo-22247(154): Add NNTPError to nntplib.__all__.

   - bpo-22366(155): urllib.request.urlopen will accept a context object
     (SSLContext) as an argument which will then be used for HTTPS
     connection.  Patch by Alex Gaynor.

   - bpo-4180(156): The warnings registries are now reset when the
     filters are modified.

   - bpo-22419(157): Limit the length of incoming HTTP request in
     wsgiref server to 65536 bytes and send a 414 error code for higher
     lengths.  Patch contributed by Devin Cook.

   - Lax cookie parsing in http.cookies could be a security issue when
     combined with non-standard cookie handling in some Web browsers.
     Reported by Sergey Bobrov.

   - bpo-20537(158): logging methods now accept an exception instance as
     well as a Boolean value or exception tuple.  Thanks to Yury
     Selivanov for the patch.

   - bpo-22384(159): An exception in Tkinter callback no longer crashes
     the program when it is run with pythonw.exe.

   - bpo-22168(160): Prevent turtle AttributeError with non-default
     Canvas on OS X.

   - bpo-21147(161): sqlite3 now raises an exception if the request
     contains a null character instead of truncating it.  Based on patch
     by Victor Stinner.

   - bpo-13968(162): The glob module now supports recursive search in
     subdirectories using the ‘**’ pattern.

   - bpo-21951(163): Fixed a crash in Tkinter on AIX when called Tcl
     command with empty string or tuple argument.

   - bpo-21951(164): Tkinter now most likely raises MemoryError instead
     of crash if the memory allocation fails.

   - bpo-22338(165): Fix a crash in the json module on memory allocation
     failure.

   - bpo-12410(166): imaplib.IMAP4 now supports the context management
     protocol.  Original patch by Tarek Ziadé.

   - bpo-21270(167): We now override tuple methods in mock.call objects
     so that they can be used as normal call attributes.

   - bpo-16662(168): load_tests() is now unconditionally run when it is
     present in a package’s __init__.py.
     TestLoader.loadTestsFromModule() still accepts use_load_tests, but
     it is deprecated and ignored.  A new keyword-only attribute
     ‘pattern’ is added and documented.  Patch given by Robert Collins,
     tweaked by Barry Warsaw.

   - bpo-22226(169): First letter no longer is stripped from the
     "status" key in the result of Treeview.heading().

   - bpo-19524(170): Fixed resource leak in the HTTP connection when an
     invalid response is received.  Patch by Martin Panter.

   - bpo-20421(171): Add a .version() method to SSL sockets exposing the
     actual protocol version in use.

   - bpo-19546(172): configparser exceptions no longer expose
     implementation details.  Chained KeyErrors are removed, which leads
     to cleaner tracebacks.  Patch by Claudiu Popa.

   - bpo-22051(173): turtledemo no longer reloads examples to re-run
     them.  Initialization of variables and gui setup should be done in
     main(), which is called each time a demo is run, but not on import.

   - bpo-21933(174): Turtledemo users can change the code font size with
     a menu selection or control(command) ’-’ or ’+’ or
     control-mousewheel.  Original patch by Lita Cho.

   - bpo-21597(175): The separator between the turtledemo text pane and
     the drawing canvas can now be grabbed and dragged with a mouse.
     The code text pane can be widened to easily view or copy the full
     width of the text.  The canvas can be widened on small screens.
     Original patches by Jan Kanis and Lita Cho.

   - bpo-18132(176): Turtledemo buttons no longer disappear when the
     window is shrunk.  Original patches by Jan Kanis and Lita Cho.

   - bpo-22043(177): time.monotonic() is now always available.
     ‘threading.Lock.acquire()’, ‘threading.RLock.acquire()’ and socket
     operations now use a monotonic clock, instead of the system clock,
     when a timeout is used.

   - bpo-21527(178): Add a default number of workers to
     ThreadPoolExecutor equal to 5 times the number of CPUs.  Patch by
     Claudiu Popa.

   - bpo-22216(179): smtplib now resets its state more completely after
     a quit.  The most obvious consequence of the previous behavior was
     a STARTTLS failure during a connect/starttls/quit/connect/starttls
     sequence.

   - bpo-22098(180): ctypes’ BigEndianStructure and
     LittleEndianStructure now define an empty __slots__ so that
     subclasses don’t always get an instance dict.  Patch by Claudiu
     Popa.

   - bpo-22185(181): Fix an occasional RuntimeError in
     threading.Condition.wait() caused by mutation of the waiters queue
     without holding the lock.  Patch by Doug Zongker.

   - bpo-22287(182): On UNIX, _PyTime_gettimeofday() now uses
     clock_gettime(CLOCK_REALTIME) if available.  As a side effect,
     Python now depends on the librt library on Solaris and on Linux
     (only with glibc older than 2.17).

   - bpo-22182(183): Use e.args to unpack exceptions correctly in
     distutils.file_util.move_file.  Patch by Claudiu Popa.

   - The webbrowser module now uses subprocess’s start_new_session=True
     rather than a potentially risky preexec_fn=os.setsid call.

   - bpo-22042(184): signal.set_wakeup_fd(fd) now raises an exception if
     the file descriptor is in blocking mode.

   - bpo-16808(185): inspect.stack() now returns a named tuple instead
     of a tuple.  Patch by Daniel Shahaf.

   - bpo-22236(186): Fixed Tkinter images copying operations in
     NoDefaultRoot mode.

   - bpo-2527(187): Add a `globals' argument to timeit functions, in
     order to override the globals namespace in which the timed code is
     executed.  Patch by Ben Roberts.

   - bpo-22118(188): Switch urllib.parse to use RFC 3986 semantics for
     the resolution of relative URLs, rather than RFCs 1808 and 2396.
     Patch by Demian Brecht.

   - bpo-21549(189): Added the "members" parameter to TarFile.list().

   - bpo-19628(190): Allow compileall recursion depth to be specified
     with a -r option.

   - bpo-15696(191): Add a __sizeof__ implementation for mmap objects on
     Windows.

   - bpo-22068(192): Avoided reference loops with Variables and Fonts in
     Tkinter.

   - bpo-22165(193): SimpleHTTPRequestHandler now supports undecodable
     file names.

   - bpo-15381(194): Optimized line reading in io.BytesIO.

   - bpo-8797(195): Raise HTTPError on failed Basic Authentication
     immediately.  Initial patch by Sam Bull.

   - bpo-20729(196): Restored the use of lazy
     iterkeys()/itervalues()/iteritems() in the mailbox module.

   - bpo-21448(197): Changed FeedParser feed() to avoid O(N**2) behavior
     when parsing long line.  Original patch by Raymond Hettinger.

   - bpo-22184(198): The functools LRU Cache decorator factory now gives
     an earlier and clearer error message when the user forgets the
     required parameters.

   - bpo-17923(199): glob() patterns ending with a slash no longer match
     non-dirs on AIX. Based on patch by Delhallt.

   - bpo-21725(200): Added support for RFC 6531 (SMTPUTF8) in smtpd.

   - bpo-22176(201): Update the ctypes module’s libffi to v3.1.  This
     release adds support for the Linux AArch64 and POWERPC ELF ABIv2
     little endian architectures.

   - bpo-5411(202): Added support for the "xztar" format in the shutil
     module.

   - bpo-21121(203): Don’t force 3rd party C extensions to be built with
     -Werror=declaration-after-statement.

   - bpo-21975(204): Fixed crash when using uninitialized sqlite3.Row
     (in particular when unpickling pickled sqlite3.Row).  sqlite3.Row
     is now initialized in the __new__() method.

   - bpo-20170(205): Convert posixmodule to use Argument Clinic.

   - bpo-21539(206): Add an `exists_ok' argument to ‘Pathlib.mkdir()’ to
     mimic ‘mkdir -p’ and *note os.makedirs(): 3c5. functionality.  When
     true, ignore FileExistsErrors.  Patch by Berker Peksag.

   - bpo-22127(207): Bypass IDNA for pure-ASCII host names in the socket
     module (in particular for numeric IPs).

   - bpo-21047(208): set the default value for the `convert_charrefs'
     argument of HTMLParser to True.  Patch by Berker Peksag.

   - 在 html.entities 包中增加 __all__ 变量。

   - bpo-15114(209): the strict mode and argument of HTMLParser,
     HTMLParser.error, and the HTMLParserError exception have been
     removed.

   - bpo-22085(210): 在 Tkinter 中删除了对 TK 8.3 的支持。

   - bpo-21580(211): Now Tkinter correctly handles bytes arguments
     passed to Tk.  In particular this allows initializing images from
     binary data.

   - bpo-22003(212): When initialized from a bytes object, io.BytesIO()
     now defers making a copy until it is mutated, improving performance
     and memory use on some use cases.  Patch by David Wilson.

   - bpo-22018(213): On Windows, signal.set_wakeup_fd() now also
     supports sockets.  A side effect is that Python depends to the
     WinSock library.

   - bpo-22054(214): Add os.get_blocking() and os.set_blocking()
     functions to get and set the blocking mode of a file descriptor
     (False if the O_NONBLOCK flag is set, True otherwise).  These
     functions are not available on Windows.

   - bpo-17172(215): Make turtledemo start as active on OS X even when
     run with subprocess.  Patch by Lita Cho.

   - bpo-21704(216): Fix build error for _multiprocessing when
     semaphores are not available.  Patch by Arfrever Frehtes Taifersar
     Arahesis.

   - bpo-20173(217): Convert sha1, sha256, sha512 and md5 to
     ArgumentClinic.  Patch by Vajrasky Kok.

   - Fix repr(_socket.socket) on Windows 64-bit: don’t fail with
     OverflowError on closed socket.  repr(socket.socket) already works
     fine.

   - bpo-22033(218): Reprs of most Python implemented classes now
     contain actual class name instead of hardcoded one.

   - bpo-21947(219): The dis module can now disassemble
     generator-iterator objects based on their gi_code attribute.  Patch
     by Clement Rouault.

   - bpo-16133(220): The asynchat.async_chat.handle_read() method now
     ignores BlockingIOError exceptions.

   - bpo-22044(221): Fixed premature DECREF in call_tzinfo_method.
     Patch by Tom Flanagan.

   - bpo-19884(222): readline: Disable the meta modifier key if stdout
     is not a terminal to not write the ANSI sequence ‘"\033[1034h"’
     into stdout.  This sequence is used on some terminal (ex:
     TERM=xterm-256color") to enable support of 8 bit characters.

   - bpo-4350(223): Removed a number of out-of-dated and non-working for
     a long time Tkinter methods.

   - bpo-6167(224): Scrollbar.activate() now returns the name of active
     element if the argument is not specified.  Scrollbar.set() now
     always accepts only 2 arguments.

   - bpo-15275(225): Clean up and speed up the ntpath module.

   - bpo-21888(226): plistlib’s load() and loads() now work if the fmt
     parameter is specified.

   - bpo-22032(227): __qualname__ instead of __name__ is now always used
     to format fully qualified class names of Python implemented
     classes.

   - bpo-22031(228): Reprs now always use hexadecimal format with the
     "0x" prefix when contain an id in form " at 0x...".

   - bpo-22018(229): signal.set_wakeup_fd() now raises an OSError
     instead of a ValueError on ‘fstat()’ failure.

   - bpo-21044(230): tarfile.open() now handles fileobj with an integer
     ’name’ attribute.  Based on patch by Antoine Pietri.

   - bpo-21966(231): Respect -q command-line option when code module is
     ran.

   - bpo-19076(232): Don’t pass the redundant ’file’ argument to
     self.error().

   - bpo-16382(233): Improve exception message of warnings.warn() for
     bad category.  Initial patch by Phil Elson.

   - bpo-21932(234): os.read() now uses a ‘Py_ssize_t()’ type instead of
     ‘int’ for the size to support reading more than 2 GB at once.  On
     Windows, the size is truncated to INT_MAX. As any call to
     os.read(), the OS may read less bytes than the number of requested
     bytes.

   - bpo-21942(235): Fixed source file viewing in pydoc’s server mode on
     Windows.

   - bpo-11259(236): asynchat.async_chat().set_terminator() now raises a
     ValueError if the number of received bytes is negative.

   - bpo-12523(237): asynchat.async_chat.push() now raises a TypeError
     if it doesn’t get a bytes string

   - bpo-21707(238): Add missing kwonlyargcount argument to
     ModuleFinder.replace_paths_in_code().

   - bpo-20639(239): calling Path.with_suffix(’’) allows removing the
     suffix again.  Patch by July Tikhonov.

   - bpo-21714(240): Disallow the construction of invalid paths using
     Path.with_name().  Original patch by Antony Lee.

   - bpo-15014(241): Added ’auth’ method to smtplib to make implementing
     auth mechanisms simpler, and used it internally in the login
     method.

   - bpo-21151(242): Fixed a segfault in the winreg module when ‘None’
     is passed as a ‘REG_BINARY’ value to SetValueEx.  Patch by John
     Ehresman.

   - bpo-21090(243): io.FileIO.readall() does not ignore I/O errors
     anymore.  Before, it ignored I/O errors if at least the first C
     call read() succeed.

   - bpo-5800(244): headers parameter of wsgiref.headers.Headers is now
     optional.  Initial patch by Pablo Torres Navarrete and SilentGhost.

   - bpo-21781(245): ssl.RAND_add() now supports strings longer than 2
     GB.

   - bpo-21679(246): Prevent extraneous fstat() calls during open().
     Patch by Bohuslav Kabrda.

   - bpo-21863(247): cProfile now displays the module name of C
     extension functions, in addition to their own name.

   - bpo-11453(248): asyncore: emit a ResourceWarning when an unclosed
     file_wrapper object is destroyed.  The destructor now closes the
     file if needed.  The close() method can now be called twice: the
     second call does nothing.

   - bpo-21858(249): Better handling of Python exceptions in the sqlite3
     module.

   - bpo-21476(250): Make sure the email.parser.BytesParser
     TextIOWrapper is discarded after parsing, so the input file isn’t
     unexpectedly closed.

   - bpo-20295(251): imghdr now recognizes OpenEXR format images.

   - bpo-21729(252): Used the "with" statement in the dbm.dumb module to
     ensure files closing.  Patch by Claudiu Popa.

   - bpo-21491(253): socketserver: Fix a race condition in child
     processes reaping.

   - bpo-21719(254): Added the ‘st_file_attributes’ field to
     os.stat_result on Windows.

   - bpo-21832(255): Require named tuple inputs to be exact strings.

   - bpo-21722(256): The distutils "upload" command now exits with a
     non-zero return code when uploading fails.  Patch by Martin
     Dengler.

   - bpo-21723(257): asyncio.Queue: support any type of number (ex:
     float) for the maximum size.  Patch written by Vajrasky Kok.

   - bpo-21711(258): support for "site-python" directories has now been
     removed from the site module (it was deprecated in 3.4).

   - bpo-17552(259): new socket.sendfile() method allowing a file to be
     sent over a socket by using high-performance os.sendfile() on UNIX.
     Patch by Giampaolo Rodola’.

   - bpo-18039(260): dbm.dump.open() now always creates a new database
     when the flag has the value ’n’.  Patch by Claudiu Popa.

   - bpo-21326(261): Add a new is_closed() method to
     asyncio.BaseEventLoop.  run_forever() and run_until_complete()
     methods of asyncio.BaseEventLoop now raise an exception if the
     event loop was closed.

   - bpo-21766(262): Prevent a security hole in CGIHTTPServer by URL
     unquoting paths before checking for a CGI script at that path.

   - bpo-21310(263): Fixed possible resource leak in failed open().

   - bpo-21256(264): Printout of keyword args should be in deterministic
     order in a mock function call.  This will help to write better
     doctests.

   - bpo-21677(265): Fixed chaining nonnormalized exceptions in io
     close() methods.

   - bpo-11709(266): Fix the pydoc.help function to not fail when
     sys.stdin is not a valid file.

   - bpo-21515(267): tempfile.TemporaryFile now uses os.O_TMPFILE flag
     is available.

   - bpo-13223(268): Fix pydoc.writedoc so that the HTML documentation
     for methods that use ’self’ in the example code is generated
     correctly.

   - bpo-21463(269): In urllib.request, fix pruning of the FTP cache.

   - bpo-21618(270): The subprocess module could fail to close open fds
     that were inherited by the calling process and already higher than
     POSIX resource limits would otherwise allow.  On systems with a
     functioning /proc/self/fd or /dev/fd interface the max is now
     ignored and all fds are closed.

   - bpo-20383(271): Introduce importlib.util.module_from_spec() as the
     preferred way to create a new module.

   - bpo-21552(272): Fixed possible integer overflow of too long string
     lengths in the tkinter module on 64-bit platforms.

   - bpo-14315(273): The zipfile module now ignores extra fields in the
     central directory that are too short to be parsed instead of
     letting a struct.unpack error bubble up as this "bad data" appears
     in many real world zip files in the wild and is ignored by other
     zip tools.

   - bpo-13742(274): Added "key" and "reverse" parameters to
     heapq.merge().  (First draft of patch contributed by Simon Sapin.)

   - bpo-21402(275): tkinter.ttk now works when default root window is
     not set.

   - bpo-3015(276): _tkinter.create() now creates tkapp object with
     wantobject=1 by default.

   - bpo-10203(277): sqlite3.Row now truly supports sequence protocol.
     In particular it supports reverse() and negative indices.  Original
     patch by Claudiu Popa.

   - bpo-18807(278): If copying (no symlinks) specified for a venv, then
     the python interpreter aliases (python, python3) are now created by
     copying rather than symlinking.

   - bpo-20197(279): Added support for the WebP image type in the imghdr
     module.  Patch by Fabrice Aneche and Claudiu Popa.

   - bpo-21513(280): Speedup some properties of IP addresses
     (IPv4Address, IPv6Address) such as .is_private or .is_multicast.

   - bpo-21137(281): Improve the repr for threading.Lock() and its
     variants by showing the "locked" or "unlocked" status.  Patch by
     Berker Peksag.

   - bpo-21538(282): The plistlib module now supports loading of binary
     plist files when reference or offset size is not a power of two.

   - bpo-21455(283): Add a default backlog to socket.listen().

   - bpo-21525(284): Most Tkinter methods which accepted tuples now
     accept lists too.

   - bpo-22166(285): With the assistance of a new internal
     _codecs._forget_codec helping function, test_codecs now clears the
     encoding caches to avoid the appearance of a reference leak

   - bpo-22236(286): Tkinter tests now don’t reuse default root window.
     New root window is created for every test class.

   - bpo-10744(287): Fix PEP 3118(288) format strings on ctypes objects
     with a nontrivial shape.

   - bpo-20826(289): Optimize ipaddress.collapse_addresses().

   - bpo-21487(290): Optimize ipaddress.summarize_address_range() and
     ipaddress.{IPv4Network,IPv6Network}.subnets().

   - bpo-21486(291): Optimize parsing of netmasks in
     ipaddress.IPv4Network and ipaddress.IPv6Network.

   - bpo-13916(292): Disallowed the surrogatepass error handler for non
     UTF-* encodings.

   - bpo-20998(293): Fixed re.fullmatch() of repeated single character
     pattern with ignore case.  Original patch by Matthew Barnett.

   - bpo-21075(294): fileinput.FileInput now reads bytes from standard
     stream if binary mode is specified.  Patch by Sam Kimbrel.

   - bpo-19775(295): Add a samefile() method to pathlib Path objects.
     Initial patch by Vajrasky Kok.

   - bpo-21226(296): Set up modules properly in
     PyImport_ExecCodeModuleObject (and friends).

   - bpo-21398(297): Fix a unicode error in the pydoc pager when the
     documentation contains characters not encodable to the stdout
     encoding.

   - bpo-16531(298): ipaddress.IPv4Network and ipaddress.IPv6Network now
     accept an (address, netmask) tuple argument, so as to easily
     construct network objects from existing addresses.

   - bpo-21156(299): importlib.abc.InspectLoader.source_to_code() is now
     a staticmethod.

   - bpo-21424(300): Simplified and optimized heaqp.nlargest() and
     nmsmallest() to make fewer tuple comparisons.

   - bpo-21396(301): Fix TextIOWrapper(..., write_through=True) to not
     force a flush() on the underlying binary stream.  Patch by akira.

   - bpo-18314(302): Unlink now removes junctions on Windows.  Patch by
     Kim Gräsman

   - bpo-21088(303): Bugfix for curses.window.addch() regression in
     3.4.0.  In porting to Argument Clinic, the first two arguments were
     reversed.

   - bpo-21407(304): _decimal: The module now supports function
     signatures.

   - bpo-10650(305): Remove the non-standard ’watchexp’ parameter from
     the Decimal.quantize() method in the Python version.  It had never
     been present in the C version.

   - bpo-21469(306): Reduced the risk of false positives in robotparser
     by checking to make sure that robots.txt has been read or does not
     exist prior to returning True in can_fetch().

   - bpo-19414(307): Have the OrderedDict mark deleted links as
     unusable.  This gives an early failure if the link is deleted
     during iteration.

   - bpo-21421(308): Add __slots__ to the MappingViews ABC. Patch by
     Josh Rosenberg.

   - bpo-21101(309): Eliminate double hashing in the C speed-up code for
     collections.Counter().

   - bpo-21321(310): itertools.islice() now releases the reference to
     the source iterator when the slice is exhausted.  Patch by Anton
     Afanasyev.

   - bpo-21057(311): TextIOWrapper now allows the underlying binary
     stream’s read() or read1() method to return an arbitrary bytes-like
     object (such as a memoryview).  Patch by Nikolaus Rath.

   - bpo-20951(312): SSLSocket.send() now raises either SSLWantReadError
     or SSLWantWriteError on a non-blocking socket if the operation
     would block.  Previously, it would return 0.  Patch by Nikolaus
     Rath.

   - bpo-13248(313): removed previously deprecated asyncore.dispatcher
     __getattr__ cheap inheritance hack.

   - bpo-9815(314): assertRaises now tries to clear references to local
     variables in the exception’s traceback.

   - bpo-19940(315): ssl.cert_time_to_seconds() now interprets the given
     time string in the UTC timezone (as specified in RFC 5280), not the
     local timezone.

   - bpo-13204(316): Calling sys.flags.__new__ would crash the
     interpreter, now it raises a TypeError.

   - bpo-19385(317): Make operations on a closed dbm.dumb database
     always raise the same exception.

   - bpo-21207(318): Detect when the os.urandom cached fd has been
     closed or replaced, and open it anew.

   - bpo-21291(319): subprocess’s Popen.wait() is now thread safe so
     that multiple threads may be calling wait() or poll() on a Popen
     instance at the same time without losing the Popen.returncode
     value.

   - bpo-21127(320): Path objects can now be instantiated from str
     subclass instances (such as ‘numpy.str_’).

   - bpo-15002(321): urllib.response object to use _TemporaryFileWrapper
     (and _TemporaryFileCloser) facility.  Provides a better way to
     handle file descriptor close.  Patch contributed by Christian
     Theune.

   - bpo-12220(322): mindom now raises a custom ValueError indicating it
     doesn’t support spaces in URIs instead of letting a ’split’
     ValueError bubble up.

   - bpo-21068(323): The ssl.PROTOCOL* constants are now enum members.

   - bpo-21276(324): posixmodule: Don’t define USE_XATTRS on KFreeBSD
     and the Hurd.

   - bpo-21262(325): New method assert_not_called for Mock.  It raises
     AssertionError if the mock has been called.

   - bpo-21238(326): New keyword argument ‘unsafe’ to Mock.  It raises
     *note AttributeError: 3a3. incase of an attribute startswith assert
     or assret.

   - bpo-20896(327): ssl.get_server_certificate() now uses
     PROTOCOL_SSLv23, not PROTOCOL_SSLv3, for maximum compatibility.

   - bpo-21239(328): patch.stopall() didn’t work deterministically when
     the same name was patched more than once.

   - bpo-21203(329): Updated fileConfig and dictConfig to remove
     inconsistencies.  Thanks to Jure Koren for the patch.

   - bpo-21222(330): Passing name keyword argument to
     mock.create_autospec now works.

   - bpo-21197(331): Add lib64 -> lib symlink in venvs on 64-bit non-OS
     X POSIX.

   - bpo-17498(332): Some SMTP servers disconnect after certain errors,
     violating strict RFC conformance.  Instead of losing the error code
     when we issue the subsequent RSET, smtplib now returns the error
     code and defers raising the SMTPServerDisconnected error until the
     next command is issued.

   - bpo-17826(333): setting an iterable side_effect on a mock function
     created by create_autospec now works.  Patch by Kushal Das.

   - bpo-7776(334): Fix ‘Host:’ header and reconnection when using
     http.client.HTTPConnection.set_tunnel().  Patch by Nikolaus Rath.

   - bpo-20968(335): unittest.mock.MagicMock now supports division.
     Patch by Johannes Baiter.

   - bpo-21529(336): Fix arbitrary memory access in
     JSONDecoder.raw_decode with a negative second parameter.  Bug
     reported by Guido Vranken.  (See also: CVE-2014-4616)

   - bpo-21169(337): getpass now handles non-ascii characters that the
     input stream encoding cannot encode by re-encoding using the
     replace error handler.

   - bpo-21171(338): Fixed undocumented filter API of the rot13 codec.
     Patch by Berker Peksag.

   - bpo-20539(339): Improved math.factorial error message for large
     positive inputs and changed exception type (OverflowError ->
     ValueError) for large negative inputs.

   - bpo-21172(340): isinstance check relaxed from dict to
     collections.Mapping.

   - bpo-21155(341): asyncio.EventLoop.create_unix_server() now raises a
     ValueError if path and sock are specified at the same time.

   - bpo-21136(342): Avoid unnecessary normalization of Fractions
     resulting from power and other operations.  Patch by Raymond
     Hettinger.

   - bpo-17621(343): Introduce importlib.util.LazyLoader.

   - bpo-21076(344): signal module constants were turned into enums.
     Patch by Giampaolo Rodola’.

   - bpo-20636(345): Improved the repr of Tkinter widgets.

   - bpo-19505(346): The items, keys, and values views of OrderedDict
     now support reverse iteration using reversed().

   - bpo-21149(347): Improved thread-safety in logging cleanup during
     interpreter shutdown.  Thanks to Devin Jeanpierre for the patch.

   - bpo-21058(348): Fix a leak of file descriptor in *note
     tempfile.NamedTemporaryFile(): d51, close the file descriptor if
     *note io.open(): 663. fails

   - bpo-21200(349): Return None from pkgutil.get_loader() when __spec__
     is missing.

   - bpo-21013(350): Enhance ssl.create_default_context() when used for
     server side sockets to provide better security by default.

   - bpo-20145(351): ‘assertRaisesRegex’ and ‘assertWarnsRegex’ now
     raise a TypeError if the second argument is not a string or
     compiled regex.

   - bpo-20633(352): Replace relative import by absolute import.

   - bpo-20980(353): Stop wrapping exception when using ThreadPool.

   - bpo-21082(354): In os.makedirs, do not set the process-wide umask.
     Note this changes behavior of makedirs when exist_ok=True.

   - bpo-20990(355): Fix issues found by pyflakes for multiprocessing.

   - bpo-21015(356): SSL contexts will now automatically select an
     elliptic curve for ECDH key exchange on OpenSSL 1.0.2 and later,
     and otherwise default to "prime256v1".

   - bpo-21000(357): Improve the command-line interface of json.tool.

   - bpo-20995(358): Enhance default ciphers used by the ssl module to
     enable better security and prioritize perfect forward secrecy.

   - bpo-20884(359): Don’t assume that __file__ is defined on
     importlib.__init__.

   - bpo-21499(360): Ignore __builtins__ in several
     test_importlib.test_api tests.

   - bpo-20627(361): xmlrpc.client.ServerProxy is now a context manager.

   - bpo-19165(362): The formatter module now raises DeprecationWarning
     instead of PendingDeprecationWarning.

   - bpo-13936(363): Remove the ability of datetime.time instances to be
     considered false in boolean contexts.

   - bpo-18931(364): selectors module now supports /dev/poll on Solaris.
     Patch by Giampaolo Rodola’.

   - bpo-19977(365): When the ‘LC_TYPE’ locale is the POSIX locale (‘C’
     locale), *note sys.stdin: 316. and *note sys.stdout: 317. are now
     using the ‘surrogateescape’ error handler, instead of the ‘strict’
     error handler.

   - bpo-20574(366): Implement incremental decoder for cp65001 code
     (Windows code page 65001, Microsoft UTF-8).

   - bpo-20879(367): Delay the initialization of encoding and decoding
     tables for base32, ascii85 and base85 codecs in the base64 module,
     and delay the initialization of the unquote_to_bytes() table of the
     urllib.parse module, to not waste memory if these modules are not
     used.

   - bpo-19157(368): Include the broadcast address in the usuable hosts
     for IPv6 in ipaddress.

   - bpo-11599(369): When an external command (e.g.  compiler) fails,
     distutils now prints out the whole command line (instead of just
     the command name) if the environment variable DISTUTILS_DEBUG is
     set.

   - bpo-4931(370): distutils should not produce unhelpful "error: None"
     messages anymore.  distutils.util.grok_environment_error is kept
     but doc-deprecated.

   - bpo-20875(371): Prevent possible gzip "’read’ is not defined"
     NameError.  Patch by Claudiu Popa.

   - bpo-11558(372): ‘email.message.Message.attach’ now returns a more
     useful error message if ‘attach’ is called on a message for which
     ‘is_multipart’ is False.

   - bpo-20283(373): RE pattern methods now accept the string keyword
     parameters as documented.  The pattern and source keyword
     parameters are left as deprecated aliases.

   - bpo-20778(374): Fix modulefinder to work with bytecode-only
     modules.

   - bpo-20791(375): copy.copy() now doesn’t make a copy when the input
     is a bytes object.  Initial patch by Peter Otten.

   - bpo-19748(376): On AIX, time.mktime() now raises an OverflowError
     for year outsize range [1902; 2037].

   - bpo-19573(377): inspect.signature: Use enum for parameter kind
     constants.

   - bpo-20726(378): inspect.signature: Make Signature and Parameter
     picklable.

   - bpo-17373(379): Add inspect.Signature.from_callable method.

   - bpo-20378(380): Improve repr of inspect.Signature and
     inspect.Parameter.

   - bpo-20816(381): Fix inspect.getcallargs() to raise correct
     TypeError for missing keyword-only arguments.  Patch by Jeremiah
     Lowin.

   - bpo-20817(382): Fix inspect.getcallargs() to fail correctly if more
     than 3 arguments are missing.  Patch by Jeremiah Lowin.

   - bpo-6676(383): Ensure a meaningful exception is raised when
     attempting to parse more than one XML document per pyexpat
     xmlparser instance.  (Original patches by Hirokazu Yamamoto and
     Amaury Forgeot d’Arc, with suggested wording by David Gutteridge)

   - bpo-21117(384): Fix inspect.signature to better support
     functools.partial.  Due to the specifics of functools.partial
     implementation, positional-or-keyword arguments passed as keyword
     arguments become keyword-only.

   - bpo-20334(385): inspect.Signature and inspect.Parameter are now
     hashable.  Thanks to Antony Lee for bug reports and suggestions.

   - bpo-15916(386): doctest.DocTestSuite returns an empty
     unittest.TestSuite instead of raising ValueError if it finds no
     tests

   - bpo-21209(387): Fix asyncio.tasks.CoroWrapper to workaround a bug
     in yield-from implementation in CPythons prior to 3.4.1.

   - asyncio: Add gi_{frame,running,code} properties to CoroWrapper
     (upstream bpo-163(388)).

   - bpo-21311(389): Avoid exception in _osx_support with non-standard
     compiler configurations.  Patch by John Szakmeister.

   - bpo-11571(390): Ensure that the turtle window becomes the topmost
     window when launched on OS X.

   - bpo-21801(391): Validate that __signature__ is None or an instance
     of Signature.

   - bpo-21923(392): Prevent AttributeError in
     distutils.sysconfig.customize_compiler due to possible
     uninitialized _config_vars.

   - bpo-21323(393): Fix http.server to again handle scripts in CGI
     subdirectories, broken by the fix for security bpo-19435(394).
     Patch by Zach Byrne.

   - bpo-22733(395): Fix ffi_prep_args not zero-extending argument
     values correctly on 64-bit Windows.

   - bpo-23302(396): Default to TCP_NODELAY=1 upon establishing an
     HTTPConnection.  Removed use of hard-coded MSS as it’s an
     optimization that’s no longer needed with Nagle disabled.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23399

   (2) https://bugs.python.org/issue20289

   (3) https://bugs.python.org/issue13128

   (4) https://bugs.python.org/issue15381

   (5) https://bugs.python.org/issue22818

   (6) https://bugs.python.org/issue23099

   (7) https://bugs.python.org/issue23326

   (8) https://bugs.python.org/issue21408

   (9) https://bugs.python.org/issue23363

   (10) https://bugs.python.org/issue23364

   (11) https://bugs.python.org/issue23366

   (12) https://bugs.python.org/issue23369

   (13) https://bugs.python.org/issue23353

   (14) https://bugs.python.org/issue14099

   (15) https://bugs.python.org/issue14099

   (16) https://bugs.python.org/issue19361

   (17) https://bugs.python.org/issue18518

   (18) https://bugs.python.org/issue23094

   (19) https://bugs.python.org/issue23268

   (20) https://bugs.python.org/issue21408

   (21) https://bugs.python.org/issue19996

   (22) https://bugs.python.org/issue20188

   (23) https://bugs.python.org/issue23133

   (24) https://bugs.python.org/issue23248

   (25) https://bugs.python.org/issue23266

   (26) https://bugs.python.org/issue23098

   (27) https://bugs.python.org/issue21817

   (28) https://bugs.python.org/issue15955

   (29) https://bugs.python.org/issue23250

   (30) https://bugs.python.org/issue23063

   (31) https://bugs.python.org/issue23209

   (32) https://bugs.python.org/issue23225

   (33) https://bugs.python.org/issue17911

   (34) https://bugs.python.org/issue17911

   (35) https://bugs.python.org/issue19777

   (36) https://bugs.python.org/issue23206

   (37) https://bugs.python.org/issue23185

   (38) https://bugs.python.org/issue23186

   (39) https://bugs.python.org/issue23143

   (40) https://bugs.python.org/issue23132

   (41) https://bugs.python.org/issue19776

   (42) https://bugs.python.org/issue23112

   (43) https://bugs.python.org/issue21793

   (44) https://bugs.python.org/issue23093

   (45) https://bugs.python.org/issue23111

   (46) https://bugs.python.org/issue22585

   (47) https://bugs.python.org/issue19104

   (48) https://bugs.python.org/issue23071

   (49) https://bugs.python.org/issue22783

   (50) https://bugs.python.org/issue15513

   (51) https://bugs.python.org/issue19858

   (52) https://bugs.python.org/issue22095

   (53) https://bugs.python.org/issue23016

   (54) https://bugs.python.org/issue21775

   (55) https://bugs.python.org/issue1218234

   (56) https://bugs.python.org/issue21740

   (57) https://bugs.python.org/issue23009

   (58) https://bugs.python.org/issue22959

   (59) https://bugs.python.org/issue22696

   (60) https://bugs.python.org/issue16043

   (61) https://bugs.python.org/issue14099

   (62) https://bugs.python.org/issue22966

   (63) https://bugs.python.org/issue21971

   (64) https://bugs.python.org/issue21032

   (65) https://bugs.python.org/issue22407

   (66) https://bugs.python.org/issue22902

   (67) https://bugs.python.org/issue22960

   (68) https://bugs.python.org/issue22389

   (69) https://bugs.python.org/issue21356

   (70) https://bugs.python.org/issue22915

   (71) https://bugs.python.org/issue22609

   (72) https://bugs.python.org/issue22940

   (73) https://bugs.python.org/issue19676

   (74) https://bugs.python.org/issue22788

   (75) https://bugs.python.org/issue22921

   (76) https://bugs.python.org/issue22894

   (77) https://bugs.python.org/issue22796

   (78) https://bugs.python.org/issue22370

   (79) https://bugs.python.org/issue22841

   (80) https://bugs.python.org/issue19494

   (81) https://bugs.python.org/issue22578

   (82) https://bugs.python.org/issue22849

   (83) https://bugs.python.org/issue12728

   (84) https://bugs.python.org/issue22821

   (85) https://bugs.python.org/issue21650

   (86) https://bugs.python.org/issue22824

   (87) https://bugs.python.org/issue22824

   (88) https://bugs.python.org/issue22406

   (89) https://bugs.python.org/issue17293

   (90) https://bugs.python.org/issue22769

   (91) https://bugs.python.org/issue22417

   (92) https://bugs.python.org/issue22775

   (93) https://bugs.python.org/issue22776

   (94) https://bugs.python.org/issue22665

   (95) https://bugs.python.org/issue6623

   (96) https://bugs.python.org/issue17381

   (97) https://bugs.python.org/issue22410

   (98) https://bugs.python.org/issue22759

   (99) https://bugs.python.org/issue8876

   (100) https://bugs.python.org/issue22217

   (101) https://bugs.python.org/issue22457

   (102) https://bugs.python.org/issue18216

   (103) https://bugs.python.org/issue13918

   (104) https://bugs.python.org/issue22676

   (105) https://bugs.python.org/issue18853

   (106) https://bugs.python.org/issue9351

   (107) https://bugs.python.org/issue7559

   (108) https://bugs.python.org/issue19746

   (109) https://bugs.python.org/issue21991

   (110) https://bugs.python.org/issue22638

   (111) https://bugs.python.org/issue22641

   (112) https://bugs.python.org/issue17401

   (113) https://bugs.python.org/issue21338

   (114) https://bugs.python.org/issue20152

   (115) https://bugs.python.org/issue18643

   (116) https://bugs.python.org/issue22435

   (117) https://bugs.python.org/issue13096

   (118) https://bugs.python.org/issue11694

   (119) https://bugs.python.org/issue19380

   (120) https://bugs.python.org/issue1519638

   (121) https://bugs.python.org/issue18615

   (122) https://bugs.python.org/issue22462

   (123) https://bugs.python.org/issue21965

   (124) https://bugs.python.org/issue21173

   (125) https://bugs.python.org/issue11866

   (126) https://bugs.python.org/issue21905

   (127) https://bugs.python.org/issue11271

   (128) https://bugs.python.org/issue21883

   (129) https://bugs.python.org/issue22219

   (130) https://bugs.python.org/issue22449

   (131) https://bugs.python.org/issue22508

   (132) https://bugs.python.org/issue20076

   (133) https://bugs.python.org/issue20079

   (134) https://bugs.python.org/issue20218

   (135) https://bugs.python.org/issue22396

   (136) https://bugs.python.org/issue22517

   (137) https://bugs.python.org/issue22437

   (138) https://bugs.python.org/issue17442

   (139) https://bugs.python.org/issue23392

   (140) https://bugs.python.org/issue10510

   (141) https://bugs.python.org/issue9850

   (142) https://bugs.python.org/issue5309

   (143) https://bugs.python.org/issue22448

   (144) https://bugs.python.org/issue22427

   (145) https://bugs.python.org/issue22362

   (146) https://bugs.python.org/issue20912

   (147) https://bugs.python.org/issue21866

   (148) https://bugs.python.org/issue22278

   (149) https://bugs.python.org/issue22415

   (150) https://bugs.python.org/issue22423

   (151) https://bugs.python.org/issue21332

   (152) https://bugs.python.org/issue21091

   (153) https://bugs.python.org/issue21079

   (154) https://bugs.python.org/issue22247

   (155) https://bugs.python.org/issue22366

   (156) https://bugs.python.org/issue4180

   (157) https://bugs.python.org/issue22419

   (158) https://bugs.python.org/issue20537

   (159) https://bugs.python.org/issue22384

   (160) https://bugs.python.org/issue22168

   (161) https://bugs.python.org/issue21147

   (162) https://bugs.python.org/issue13968

   (163) https://bugs.python.org/issue21951

   (164) https://bugs.python.org/issue21951

   (165) https://bugs.python.org/issue22338

   (166) https://bugs.python.org/issue12410

   (167) https://bugs.python.org/issue21270

   (168) https://bugs.python.org/issue16662

   (169) https://bugs.python.org/issue22226

   (170) https://bugs.python.org/issue19524

   (171) https://bugs.python.org/issue20421

   (172) https://bugs.python.org/issue19546

   (173) https://bugs.python.org/issue22051

   (174) https://bugs.python.org/issue21933

   (175) https://bugs.python.org/issue21597

   (176) https://bugs.python.org/issue18132

   (177) https://bugs.python.org/issue22043

   (178) https://bugs.python.org/issue21527

   (179) https://bugs.python.org/issue22216

   (180) https://bugs.python.org/issue22098

   (181) https://bugs.python.org/issue22185

   (182) https://bugs.python.org/issue22287

   (183) https://bugs.python.org/issue22182

   (184) https://bugs.python.org/issue22042

   (185) https://bugs.python.org/issue16808

   (186) https://bugs.python.org/issue22236

   (187) https://bugs.python.org/issue2527

   (188) https://bugs.python.org/issue22118

   (189) https://bugs.python.org/issue21549

   (190) https://bugs.python.org/issue19628

   (191) https://bugs.python.org/issue15696

   (192) https://bugs.python.org/issue22068

   (193) https://bugs.python.org/issue22165

   (194) https://bugs.python.org/issue15381

   (195) https://bugs.python.org/issue8797

   (196) https://bugs.python.org/issue20729

   (197) https://bugs.python.org/issue21448

   (198) https://bugs.python.org/issue22184

   (199) https://bugs.python.org/issue17923

   (200) https://bugs.python.org/issue21725

   (201) https://bugs.python.org/issue22176

   (202) https://bugs.python.org/issue5411

   (203) https://bugs.python.org/issue21121

   (204) https://bugs.python.org/issue21975

   (205) https://bugs.python.org/issue20170

   (206) https://bugs.python.org/issue21539

   (207) https://bugs.python.org/issue22127

   (208) https://bugs.python.org/issue21047

   (209) https://bugs.python.org/issue15114

   (210) https://bugs.python.org/issue22085

   (211) https://bugs.python.org/issue21580

   (212) https://bugs.python.org/issue22003

   (213) https://bugs.python.org/issue22018

   (214) https://bugs.python.org/issue22054

   (215) https://bugs.python.org/issue17172

   (216) https://bugs.python.org/issue21704

   (217) https://bugs.python.org/issue20173

   (218) https://bugs.python.org/issue22033

   (219) https://bugs.python.org/issue21947

   (220) https://bugs.python.org/issue16133

   (221) https://bugs.python.org/issue22044

   (222) https://bugs.python.org/issue19884

   (223) https://bugs.python.org/issue4350

   (224) https://bugs.python.org/issue6167

   (225) https://bugs.python.org/issue15275

   (226) https://bugs.python.org/issue21888

   (227) https://bugs.python.org/issue22032

   (228) https://bugs.python.org/issue22031

   (229) https://bugs.python.org/issue22018

   (230) https://bugs.python.org/issue21044

   (231) https://bugs.python.org/issue21966

   (232) https://bugs.python.org/issue19076

   (233) https://bugs.python.org/issue16382

   (234) https://bugs.python.org/issue21932

   (235) https://bugs.python.org/issue21942

   (236) https://bugs.python.org/issue11259

   (237) https://bugs.python.org/issue12523

   (238) https://bugs.python.org/issue21707

   (239) https://bugs.python.org/issue20639

   (240) https://bugs.python.org/issue21714

   (241) https://bugs.python.org/issue15014

   (242) https://bugs.python.org/issue21151

   (243) https://bugs.python.org/issue21090

   (244) https://bugs.python.org/issue5800

   (245) https://bugs.python.org/issue21781

   (246) https://bugs.python.org/issue21679

   (247) https://bugs.python.org/issue21863

   (248) https://bugs.python.org/issue11453

   (249) https://bugs.python.org/issue21858

   (250) https://bugs.python.org/issue21476

   (251) https://bugs.python.org/issue20295

   (252) https://bugs.python.org/issue21729

   (253) https://bugs.python.org/issue21491

   (254) https://bugs.python.org/issue21719

   (255) https://bugs.python.org/issue21832

   (256) https://bugs.python.org/issue21722

   (257) https://bugs.python.org/issue21723

   (258) https://bugs.python.org/issue21711

   (259) https://bugs.python.org/issue17552

   (260) https://bugs.python.org/issue18039

   (261) https://bugs.python.org/issue21326

   (262) https://bugs.python.org/issue21766

   (263) https://bugs.python.org/issue21310

   (264) https://bugs.python.org/issue21256

   (265) https://bugs.python.org/issue21677

   (266) https://bugs.python.org/issue11709

   (267) https://bugs.python.org/issue21515

   (268) https://bugs.python.org/issue13223

   (269) https://bugs.python.org/issue21463

   (270) https://bugs.python.org/issue21618

   (271) https://bugs.python.org/issue20383

   (272) https://bugs.python.org/issue21552

   (273) https://bugs.python.org/issue14315

   (274) https://bugs.python.org/issue13742

   (275) https://bugs.python.org/issue21402

   (276) https://bugs.python.org/issue3015

   (277) https://bugs.python.org/issue10203

   (278) https://bugs.python.org/issue18807

   (279) https://bugs.python.org/issue20197

   (280) https://bugs.python.org/issue21513

   (281) https://bugs.python.org/issue21137

   (282) https://bugs.python.org/issue21538

   (283) https://bugs.python.org/issue21455

   (284) https://bugs.python.org/issue21525

   (285) https://bugs.python.org/issue22166

   (286) https://bugs.python.org/issue22236

   (287) https://bugs.python.org/issue10744

   (288) https://www.python.org/dev/peps/pep-3118

   (289) https://bugs.python.org/issue20826

   (290) https://bugs.python.org/issue21487

   (291) https://bugs.python.org/issue21486

   (292) https://bugs.python.org/issue13916

   (293) https://bugs.python.org/issue20998

   (294) https://bugs.python.org/issue21075

   (295) https://bugs.python.org/issue19775

   (296) https://bugs.python.org/issue21226

   (297) https://bugs.python.org/issue21398

   (298) https://bugs.python.org/issue16531

   (299) https://bugs.python.org/issue21156

   (300) https://bugs.python.org/issue21424

   (301) https://bugs.python.org/issue21396

   (302) https://bugs.python.org/issue18314

   (303) https://bugs.python.org/issue21088

   (304) https://bugs.python.org/issue21407

   (305) https://bugs.python.org/issue10650

   (306) https://bugs.python.org/issue21469

   (307) https://bugs.python.org/issue19414

   (308) https://bugs.python.org/issue21421

   (309) https://bugs.python.org/issue21101

   (310) https://bugs.python.org/issue21321

   (311) https://bugs.python.org/issue21057

   (312) https://bugs.python.org/issue20951

   (313) https://bugs.python.org/issue13248

   (314) https://bugs.python.org/issue9815

   (315) https://bugs.python.org/issue19940

   (316) https://bugs.python.org/issue13204

   (317) https://bugs.python.org/issue19385

   (318) https://bugs.python.org/issue21207

   (319) https://bugs.python.org/issue21291

   (320) https://bugs.python.org/issue21127

   (321) https://bugs.python.org/issue15002

   (322) https://bugs.python.org/issue12220

   (323) https://bugs.python.org/issue21068

   (324) https://bugs.python.org/issue21276

   (325) https://bugs.python.org/issue21262

   (326) https://bugs.python.org/issue21238

   (327) https://bugs.python.org/issue20896

   (328) https://bugs.python.org/issue21239

   (329) https://bugs.python.org/issue21203

   (330) https://bugs.python.org/issue21222

   (331) https://bugs.python.org/issue21197

   (332) https://bugs.python.org/issue17498

   (333) https://bugs.python.org/issue17826

   (334) https://bugs.python.org/issue7776

   (335) https://bugs.python.org/issue20968

   (336) https://bugs.python.org/issue21529

   (337) https://bugs.python.org/issue21169

   (338) https://bugs.python.org/issue21171

   (339) https://bugs.python.org/issue20539

   (340) https://bugs.python.org/issue21172

   (341) https://bugs.python.org/issue21155

   (342) https://bugs.python.org/issue21136

   (343) https://bugs.python.org/issue17621

   (344) https://bugs.python.org/issue21076

   (345) https://bugs.python.org/issue20636

   (346) https://bugs.python.org/issue19505

   (347) https://bugs.python.org/issue21149

   (348) https://bugs.python.org/issue21058

   (349) https://bugs.python.org/issue21200

   (350) https://bugs.python.org/issue21013

   (351) https://bugs.python.org/issue20145

   (352) https://bugs.python.org/issue20633

   (353) https://bugs.python.org/issue20980

   (354) https://bugs.python.org/issue21082

   (355) https://bugs.python.org/issue20990

   (356) https://bugs.python.org/issue21015

   (357) https://bugs.python.org/issue21000

   (358) https://bugs.python.org/issue20995

   (359) https://bugs.python.org/issue20884

   (360) https://bugs.python.org/issue21499

   (361) https://bugs.python.org/issue20627

   (362) https://bugs.python.org/issue19165

   (363) https://bugs.python.org/issue13936

   (364) https://bugs.python.org/issue18931

   (365) https://bugs.python.org/issue19977

   (366) https://bugs.python.org/issue20574

   (367) https://bugs.python.org/issue20879

   (368) https://bugs.python.org/issue19157

   (369) https://bugs.python.org/issue11599

   (370) https://bugs.python.org/issue4931

   (371) https://bugs.python.org/issue20875

   (372) https://bugs.python.org/issue11558

   (373) https://bugs.python.org/issue20283

   (374) https://bugs.python.org/issue20778

   (375) https://bugs.python.org/issue20791

   (376) https://bugs.python.org/issue19748

   (377) https://bugs.python.org/issue19573

   (378) https://bugs.python.org/issue20726

   (379) https://bugs.python.org/issue17373

   (380) https://bugs.python.org/issue20378

   (381) https://bugs.python.org/issue20816

   (382) https://bugs.python.org/issue20817

   (383) https://bugs.python.org/issue6676

   (384) https://bugs.python.org/issue21117

   (385) https://bugs.python.org/issue20334

   (386) https://bugs.python.org/issue15916

   (387) https://bugs.python.org/issue21209

   (388) https://bugs.python.org/issue163

   (389) https://bugs.python.org/issue21311

   (390) https://bugs.python.org/issue11571

   (391) https://bugs.python.org/issue21801

   (392) https://bugs.python.org/issue21923

   (393) https://bugs.python.org/issue21323

   (394) https://bugs.python.org/issue19435

   (395) https://bugs.python.org/issue22733

   (396) https://bugs.python.org/issue23302


File: python.info,  Node: IDLE<53>,  Next: 构建<56>,  Prev: 库<88>,  Up: Python 3 5 0 alpha 1

1.18.88.3 IDLE
..............

   - bpo-20577(1): Configuration of the max line length for the
     FormatParagraph extension has been moved from the General tab of
     the Idle preferences dialog to the FormatParagraph tab of the
     Config Extensions dialog.  Patch by Tal Einat.

   - bpo-16893(2): Update Idle doc chapter to match current Idle and add
     new information.

   - bpo-3068(3): Add Idle extension configuration dialog to Options
     menu.  Changes are written to HOME/.idlerc/config-extensions.cfg.
     Original patch by Tal Einat.

   - bpo-16233(4): A module browser (File : Class Browser, Alt+C)
     requires an editor window with a filename.  When Class Browser is
     requested otherwise, from a shell, output window, or ’Untitled’
     editor, Idle no longer displays an error box.  It now pops up an
     Open Module box (Alt+M). If a valid name is entered and a module is
     opened, a corresponding browser is also opened.

   - bpo-4832(5): Save As to type Python files automatically adds .py to
     the name you enter (even if your system does not display it).  Some
     systems automatically add .txt when type is Text files.

   - bpo-21986(6): Code objects are not normally pickled by the pickle
     module.  To match this, they are no longer pickled when running
     under Idle.

   - bpo-17390(7): Adjust Editor window title; remove ’Python’, move
     version to end.

   - bpo-14105(8): Idle debugger breakpoints no longer disappear when
     inserting or deleting lines.

   - bpo-17172(9): Turtledemo can now be run from Idle.  Currently, the
     entry is on the Help menu, but it may move to Run.  Patch by
     Ramchandra Apt and Lita Cho.

   - bpo-21765(10): Add support for non-ascii identifiers to
     HyperParser.

   - bpo-21940(11): Add unittest for WidgetRedirector.  Initial patch by
     Saimadhav Heblikar.

   - bpo-18592(12): Add unittest for SearchDialogBase.  Patch by Phil
     Webster.

   - bpo-21694(13): Add unittest for ParenMatch.  Patch by Saimadhav
     Heblikar.

   - bpo-21686(14): add unittest for HyperParser.  Original patch by
     Saimadhav Heblikar.

   - bpo-12387(15): Add missing upper(lower)case versions of default
     Windows key bindings for Idle so Caps Lock does not disable them.
     Patch by Roger Serwy.

   - bpo-21695(16): Closing a Find-in-files output window while the
     search is still in progress no longer closes Idle.

   - bpo-18910(17): Add unittest for textView.  Patch by Phil Webster.

   - bpo-18292(18): Add unittest for AutoExpand.  Patch by Saihadhav
     Heblikar.

   - bpo-18409(19): Add unittest for AutoComplete.  Patch by Phil
     Webster.

   - bpo-21477(20): htest.py - Improve framework, complete set of tests.
     Patches by Saimadhav Heblikar

   - bpo-18104(21): Add idlelib/idle_test/htest.py with a few sample
     tests to begin consolidating and improving human-validated tests of
     Idle.  Change other files as needed to work with htest.  Running
     the module as __main__ runs all tests.

   - bpo-21139(22): Change default paragraph width to 72, the PEP 8(23)
     recommendation.

   - bpo-21284(24): Paragraph reformat test passes after user changes
     reformat width.

   - bpo-17654(25): Ensure IDLE menus are customized properly on OS X
     for non-framework builds and for all variants of Tk.

   - bpo-23180(26): Rename IDLE "Windows" menu item to "Window".  Patch
     by Al Sweigart.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20577

   (2) https://bugs.python.org/issue16893

   (3) https://bugs.python.org/issue3068

   (4) https://bugs.python.org/issue16233

   (5) https://bugs.python.org/issue4832

   (6) https://bugs.python.org/issue21986

   (7) https://bugs.python.org/issue17390

   (8) https://bugs.python.org/issue14105

   (9) https://bugs.python.org/issue17172

   (10) https://bugs.python.org/issue21765

   (11) https://bugs.python.org/issue21940

   (12) https://bugs.python.org/issue18592

   (13) https://bugs.python.org/issue21694

   (14) https://bugs.python.org/issue21686

   (15) https://bugs.python.org/issue12387

   (16) https://bugs.python.org/issue21695

   (17) https://bugs.python.org/issue18910

   (18) https://bugs.python.org/issue18292

   (19) https://bugs.python.org/issue18409

   (20) https://bugs.python.org/issue21477

   (21) https://bugs.python.org/issue18104

   (22) https://bugs.python.org/issue21139

   (23) https://www.python.org/dev/peps/pep-0008

   (24) https://bugs.python.org/issue21284

   (25) https://bugs.python.org/issue17654

   (26) https://bugs.python.org/issue23180


File: python.info,  Node: 构建<56>,  Next: C API<38>,  Prev: IDLE<53>,  Up: Python 3 5 0 alpha 1

1.18.88.4 构建
..............

   - bpo-15506(1): Use standard PKG_PROG_PKG_CONFIG autoconf macro in
     the configure script.

   - bpo-22935(2): Allow the ssl module to be compiled if openssl
     doesn’t support SSL 3.

   - bpo-22592(3): 放弃对 Borland C 编译器构建Python的支持。distutils模
     块仍然支持它来构建扩展。

   - bpo-22591(4): 放弃对 MS-DOS 的支持，尤其是 DJGPP 编译器（GCC的
     MS-DOS端口）。

   - bpo-16537(5): Check whether self.extensions is empty in setup.py.
     Patch by Jonathan Hosmer.

   - bpo-22359(6): Remove incorrect uses of recursive make.  Patch by
     Jonas Wagner.

   - bpo-21958(7): Define HAVE_ROUND when building with Visual Studio
     2013 and above.  Patch by Zachary Turner.

   - bpo-18093(8): the programs that embed the CPython runtime are now
     in a separate "Programs" directory, rather than being kept in the
     Modules directory.

   - bpo-15759(9): "make suspicious", "make linkcheck" and "make
     doctest" in Doc/ now display special message when and only when
     there are failures.

   - bpo-21141(10): The Windows build process no longer attempts to find
     Perl, instead relying on OpenSSL source being configured and ready
     to build.  The ‘PCbuild\build_ssl.py’ script has been re-written
     and re-named to ‘PCbuild\prepare_ssl.py’, and takes care of
     configuring OpenSSL source for both 32 and 64 bit platforms.
     OpenSSL sources obtained from svn.python.org will always be
     pre-configured and ready to build.

   - bpo-21037(11): Add a build option to enable AddressSanitizer
     support.

   - bpo-19962(12): The Windows build process now creates "python.bat"
     in the root of the source tree, which passes all arguments through
     to the most recently built interpreter.

   - bpo-21285(13): Refactor and fix curses configure check to always
     search in a ncursesw directory.

   - bpo-15234(14): For BerkelyDB and Sqlite, only add the found library
     and include directories if they aren’t already being searched.
     This avoids an explicit runtime library dependency.

   - bpo-17861(15): Tools/scripts/generate_opcode_h.py automatically
     regenerates Include/opcode.h from Lib/opcode.py if the latter gets
     any change.

   - bpo-20644(16): OS X installer build support for documentation build
     changes in 3.4.1: assume externally supplied sphinx-build is
     available in /usr/bin.

   - bpo-20022(17): Eliminate use of deprecated bundlebuilder in OS X
     builds.

   - bpo-15968(18): Incorporated Tcl, Tk, and Tix builds into the
     Windows build solution.

   - bpo-17095(19): Fix Modules/Setup `shared' support.

   - bpo-21811(20): Anticipated fixes to support OS X versions > 10.9.

   - bpo-21166(21): Prevent possible segfaults and other random failures
     of python –generate-posix-vars in pybuilddir.txt build target.

   - bpo-18096(22): Fix library order returned by python-config.

   - bpo-17219(23): Add library build dir for Python extension
     cross-builds.

   - bpo-22919(24): Windows build updated to support VC 14.0 (Visual
     Studio 2015), which will be used for the official release.

   - bpo-21236(25): Build _msi.pyd with cabinet.lib instead of fci.lib

   - bpo-17128(26): Use private version of OpenSSL for OS X 10.5+
     installer.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15506

   (2) https://bugs.python.org/issue22935

   (3) https://bugs.python.org/issue22592

   (4) https://bugs.python.org/issue22591

   (5) https://bugs.python.org/issue16537

   (6) https://bugs.python.org/issue22359

   (7) https://bugs.python.org/issue21958

   (8) https://bugs.python.org/issue18093

   (9) https://bugs.python.org/issue15759

   (10) https://bugs.python.org/issue21141

   (11) https://bugs.python.org/issue21037

   (12) https://bugs.python.org/issue19962

   (13) https://bugs.python.org/issue21285

   (14) https://bugs.python.org/issue15234

   (15) https://bugs.python.org/issue17861

   (16) https://bugs.python.org/issue20644

   (17) https://bugs.python.org/issue20022

   (18) https://bugs.python.org/issue15968

   (19) https://bugs.python.org/issue17095

   (20) https://bugs.python.org/issue21811

   (21) https://bugs.python.org/issue21166

   (22) https://bugs.python.org/issue18096

   (23) https://bugs.python.org/issue17219

   (24) https://bugs.python.org/issue22919

   (25) https://bugs.python.org/issue21236

   (26) https://bugs.python.org/issue17128


File: python.info,  Node: C API<38>,  Next: 文档<54>,  Prev: 构建<56>,  Up: Python 3 5 0 alpha 1

1.18.88.5 C API
...............

   - bpo-14203(1): Remove obsolete support for view==NULL in
     PyBuffer_FillInfo(), bytearray_getbuffer(), bytesiobuf_getbuffer()
     and array_buffer_getbuf().  All functions now raise BufferError in
     that case.

   - bpo-22445(2): PyBuffer_IsContiguous() now implements precise
     contiguity tests, compatible with NumPy’s
     NPY_RELAXED_STRIDES_CHECKING compilation flag.  Previously the
     function reported false negatives for corner cases.

   - bpo-22079(3): PyType_Ready() now checks that statically allocated
     type has no dynamically allocated bases.

   - bpo-22453(4): Removed non-documented macro PyObject_REPR().

   - bpo-18395(5): Rename ‘_Py_char2wchar()’ to *note Py_DecodeLocale():
     444, rename ‘_Py_wchar2char()’ to *note Py_EncodeLocale(): 445, and
     document these functions.

   - bpo-21233(6): Add new C functions: PyMem_RawCalloc(),
     PyMem_Calloc(), PyObject_Calloc(), _PyObject_GC_Calloc().
     bytes(int) is now using ‘calloc()’ instead of ‘malloc()’ for large
     objects which is faster and use less memory.

   - bpo-20942(7): PyImport_ImportFrozenModuleObject() no longer sets
     __file__ to match what importlib does; this affects
     _frozen_importlib as well as any module loaded using
     imp.init_frozen().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14203

   (2) https://bugs.python.org/issue22445

   (3) https://bugs.python.org/issue22079

   (4) https://bugs.python.org/issue22453

   (5) https://bugs.python.org/issue18395

   (6) https://bugs.python.org/issue21233

   (7) https://bugs.python.org/issue20942


File: python.info,  Node: 文档<54>,  Next: 测试<54>,  Prev: C API<38>,  Up: Python 3 5 0 alpha 1

1.18.88.6 文档
..............

   - bpo-19548(1): Update the codecs module documentation to better
     cover the distinction between text encodings and other codecs,
     together with other clarifications.  Patch by Martin Panter.

   - bpo-22394(2): Doc/Makefile now supports ‘make venv
     PYTHON=../python’ to create a venv for generating the
     documentation, e.g., ‘make html PYTHON=venv/bin/python3’.

   - bpo-21514(3): The documentation of the json module now refers to
     new JSON RFC 7159 instead of obsoleted RFC 4627.

   - bpo-21777(4): The binary sequence methods on bytes and bytearray
     are now documented explicitly, rather than assuming users will be
     able to derive the expected behaviour from the behaviour of the
     corresponding str methods.

   - bpo-6916(5): undocument deprecated asynchat.fifo class.

   - bpo-17386(6): Expanded functionality of the ‘Doc/make.bat’ script
     to make it much more comparable to ‘Doc/Makefile’.

   - bpo-21312(7): Update the thread_foobar.h template file to include
     newer threading APIs.  Patch by Jack McCracken.

   - bpo-21043(8): Remove the recommendation for specific CA
     organizations and to mention the ability to load the OS
     certificates.

   - bpo-20765(9): Add missing documentation for PurePath.with_name()
     and PurePath.with_suffix().

   - bpo-19407(10): New package installation and distribution guides
     based on the Python Packaging Authority tools.  Existing guides
     have been retained as legacy links from the distutils docs, as they
     still contain some required reference material for tool developers
     that isn’t recorded anywhere else.

   - bpo-19697(11): Document cases where __main__.__spec__ is None.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19548

   (2) https://bugs.python.org/issue22394

   (3) https://bugs.python.org/issue21514

   (4) https://bugs.python.org/issue21777

   (5) https://bugs.python.org/issue6916

   (6) https://bugs.python.org/issue17386

   (7) https://bugs.python.org/issue21312

   (8) https://bugs.python.org/issue21043

   (9) https://bugs.python.org/issue20765

   (10) https://bugs.python.org/issue19407

   (11) https://bugs.python.org/issue19697


File: python.info,  Node: 测试<54>,  Next: 工具/示例<36>,  Prev: 文档<54>,  Up: Python 3 5 0 alpha 1

1.18.88.7 测试
..............

   - bpo-18982(1): Add tests for CLI of the calendar module.

   - bpo-19548(2): Added some additional checks to test_codecs to ensure
     that statements in the updated documentation remain accurate.
     Patch by Martin Panter.

   - bpo-22838(3): All test_re tests now work with unittest test
     discovery.

   - bpo-22173(4): Update lib2to3 tests to use unittest test discovery.

   - bpo-16000(5): Convert test_curses to use unittest.

   - bpo-21456(6): Skip two tests in test_urllib2net.py if _ssl module
     not present.  Patch by Remi Pointel.

   - bpo-20746(7): Fix test_pdb to run in refleak mode (-R). Patch by
     Xavier de Gaye.

   - bpo-22060(8): test_ctypes has been somewhat cleaned up and
     simplified; it now uses unittest test discovery to find its tests.

   - bpo-22104(9): regrtest.py no longer holds a reference to the suite
     of tests loaded from test modules that don’t define test_main().

   - bpo-22111(10): Assorted cleanups in test_imaplib.  Patch by Milan
     Oberkirch.

   - bpo-22002(11): Added ‘load_package_tests’ function to test.support
     and used it to implement/augment test discovery in test_asyncio,
     test_email, test_importlib, test_json, and test_tools.

   - bpo-21976(12): Fix test_ssl to accept LibreSSL version strings.
     Thanks to William Orr.

   - bpo-21918(13): Converted test_tools from a module to a package
     containing separate test files for each tested script.

   - bpo-9554(14): Use modern unittest features in test_argparse.
     Initial patch by Denver Coneybeare and Radu Voicilas.

   - bpo-20155(15): Changed HTTP method names in failing tests in
     test_httpservers so that packet filtering software (specifically
     Windows Base Filtering Engine) does not interfere with the
     transaction semantics expected by the tests.

   - bpo-19493(16): Refactored the ctypes test package to skip tests
     explicitly rather than silently.

   - bpo-18492(17): All resources are now allowed when tests are not run
     by regrtest.py.

   - bpo-21634(18): Fix pystone micro-benchmark: use floor division
     instead of true division to benchmark integers instead of floating
     point numbers.  Set pystone version to 1.2.  Patch written by
     Lennart Regebro.

   - bpo-21605(19): Added tests for Tkinter images.

   - bpo-21493(20): Added test for ntpath.expanduser().  Original patch
     by Claudiu Popa.

   - bpo-19925(21): Added tests for the spwd module.  Original patch by
     Vajrasky Kok.

   - bpo-21522(22): Added Tkinter tests for Listbox.itemconfigure(),
     PanedWindow.paneconfigure(), and Menu.entryconfigure().

   - bpo-17756(23): Fix test_code test when run from the installed
     location.

   - bpo-17752(24): Fix distutils tests when run from the installed
     location.

   - bpo-18604(25): Consolidated checks for GUI availability.  All
     platforms now at least check whether Tk can be instantiated when
     the GUI resource is requested.

   - bpo-21275(26): 修复KFreeBSD上的套接字测试。

   - bpo-21223(27): Pass test_site/test_startup_imports when some of the
     extensions are built as builtins.

   - bpo-20635(28): 添加了针对Tk几何管理器的测试。

   - 增加freeze包的测试用例。

   - bpo-20743(29): 修复test_tcl中的引用泄漏。

   - bpo-21097(30): 将test_namespace_pkgs 移至 test_importlib。

   - bpo-21503(31): Use test_both() consistently in test_importlib.

   - bpo-20939(32): Avoid various network test failures due to new
     redirect of ‘http://www.python.org/’ to ‘https://www.python.org’:
     use ‘http://www.example.com’ instead.

   - bpo-20668(33): asyncio tests no longer rely on tests.txt file.
     (Patch by Vajrasky Kok)

   - bpo-21093(34): Prevent failures of ctypes test_macholib on OS X if
     a copy of libz exists in $HOME/lib or /usr/local/lib.

   - bpo-22770(35): Prevent some Tk segfaults on OS X when running gui
     tests.

   - bpo-23211(36): Workaround test_logging failure on some OS X 10.6
     systems.

   - bpo-23345(37): Prevent test_ssl failures with large OpenSSL patch
     level values (like 0.9.8zc).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18982

   (2) https://bugs.python.org/issue19548

   (3) https://bugs.python.org/issue22838

   (4) https://bugs.python.org/issue22173

   (5) https://bugs.python.org/issue16000

   (6) https://bugs.python.org/issue21456

   (7) https://bugs.python.org/issue20746

   (8) https://bugs.python.org/issue22060

   (9) https://bugs.python.org/issue22104

   (10) https://bugs.python.org/issue22111

   (11) https://bugs.python.org/issue22002

   (12) https://bugs.python.org/issue21976

   (13) https://bugs.python.org/issue21918

   (14) https://bugs.python.org/issue9554

   (15) https://bugs.python.org/issue20155

   (16) https://bugs.python.org/issue19493

   (17) https://bugs.python.org/issue18492

   (18) https://bugs.python.org/issue21634

   (19) https://bugs.python.org/issue21605

   (20) https://bugs.python.org/issue21493

   (21) https://bugs.python.org/issue19925

   (22) https://bugs.python.org/issue21522

   (23) https://bugs.python.org/issue17756

   (24) https://bugs.python.org/issue17752

   (25) https://bugs.python.org/issue18604

   (26) https://bugs.python.org/issue21275

   (27) https://bugs.python.org/issue21223

   (28) https://bugs.python.org/issue20635

   (29) https://bugs.python.org/issue20743

   (30) https://bugs.python.org/issue21097

   (31) https://bugs.python.org/issue21503

   (32) https://bugs.python.org/issue20939

   (33) https://bugs.python.org/issue20668

   (34) https://bugs.python.org/issue21093

   (35) https://bugs.python.org/issue22770

   (36) https://bugs.python.org/issue23211

   (37) https://bugs.python.org/issue23345


File: python.info,  Node: 工具/示例<36>,  Next: Windows<52>,  Prev: 测试<54>,  Up: Python 3 5 0 alpha 1

1.18.88.8 工具/示例
...................

   - bpo-22314(1): pydoc now works when the LINES environment variable
     is set.

   - bpo-22615(2): Argument Clinic now supports the "type" argument for
     the int converter.  This permits using the int converter with enums
     and typedefs.

   - bpo-20076(3): The makelocalealias.py script no longer ignores UTF-8
     mapping.

   - bpo-20079(4): The makelocalealias.py script now can parse the
     SUPPORTED file from glibc sources and supports command line options
     for source paths.

   - bpo-22201(5): Command-line interface of the zipfile module now
     correctly extracts ZIP files with directory entries.  Patch by Ryan
     Wilson.

   - bpo-22120(6): For functions using an unsigned integer return
     converter, Argument Clinic now generates a cast to that type for
     the comparison to -1 in the generated code.  (This suppresses a
     compilation warning.)

   - bpo-18974(7): Tools/scripts/diff.py now uses argparse instead of
     optparse.

   - bpo-21906(8): 让Tools/scripts/md5sum.py可以工作在Python 3。由
     Zachary Ware提供补丁。

   - bpo-21629(9): Fix Argument Clinic’s "–converters" feature.

   - 为2to3添加 ‘yield from’ 的支持。

   - 为 2to3 添加对 PEP 465 矩阵乘法运算符的支持。

   - bpo-16047(10): Fix module exception list and __file__ handling in
     freeze.  Patch by Meador Inge.

   - bpo-11824(11): Consider ABI tags in freeze.  Patch by Meador Inge.

   - bpo-20535(12): PYTHONWARNING no longer affects the run_tests.py
     script.  Patch by Arfrever Frehtes Taifersar Arahesis.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22314

   (2) https://bugs.python.org/issue22615

   (3) https://bugs.python.org/issue20076

   (4) https://bugs.python.org/issue20079

   (5) https://bugs.python.org/issue22201

   (6) https://bugs.python.org/issue22120

   (7) https://bugs.python.org/issue18974

   (8) https://bugs.python.org/issue21906

   (9) https://bugs.python.org/issue21629

   (10) https://bugs.python.org/issue16047

   (11) https://bugs.python.org/issue11824

   (12) https://bugs.python.org/issue20535


File: python.info,  Node: Windows<52>,  Prev: 工具/示例<36>,  Up: Python 3 5 0 alpha 1

1.18.88.9 Windows
.................

   - bpo-23260(1): 更新Windows安装器

   - The bundled version of Tcl/Tk has been updated to 8.6.3.  The most
     visible result of this change is the addition of new native file
     dialogs when running on Windows Vista or newer.  See Tcl/Tk’s TIP
     432 for more information.  Also, this version of Tcl/Tk includes
     support for Windows 10.

   - bpo-17896(2): The Windows build scripts now expect external library
     sources to be in ‘PCbuild\..\externals’ rather than
     ‘PCbuild\..\..’.

   - bpo-17717(3): The Windows build scripts now use a copy of NASM
     pulled from svn.python.org to build OpenSSL.

   - bpo-21907(4): Improved the batch scripts provided for building
     Python.

   - bpo-22644(5): OpenSSL的捆绑版本已更新到1.0.1j。

   - bpo-10747(6): Use versioned labels in the Windows start menu.
     Patch by Olive Kilburn.

   - bpo-22980(7): .pyd files with a version and platform tag (for
     example, ".cp35-win32.pyd") will now be loaded in preference to
     those without tags.

`（有关旧版本的信息，请参阅HISTORY文件。)'

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23260

   (2) https://bugs.python.org/issue17896

   (3) https://bugs.python.org/issue17717

   (4) https://bugs.python.org/issue21907

   (5) https://bugs.python.org/issue22644

   (6) https://bugs.python.org/issue10747

   (7) https://bugs.python.org/issue22980


File: python.info,  Node: Python 教程,  Next: Python安装和使用,  Prev: Python的新变化,  Up: Top

2 Python 教程
*************

Python 是一种易于学习又功能强大的编程语言。它提供了高效的高级数据结构，
还能简单有效地面向对象编程。Python 优雅的语法和动态类型，以及解释型语言
的本质，使它成为多数平台上写脚本和快速开发应用的理想语言。

Python 解释器及丰富的标准库，提供了适用于各个主要系统平台的源码或机器码
，这些可以到 Python 官网 ‘https://www.python.org/’ 免费获取，并可自由地
分发。许多免费的第三方 Python 模块、程序、工具和它们的文档，也能在这个网
站上找到对应内容或链接。

Python 解释器易于扩展，可以使用 C 或 C++（或者其他可以从 C 调用的语言）
扩展新的功能和数据类型。Python 也可用作可定制化软件中的扩展程序语言。

这个教程非正式地介绍了 Python 语言和系统的基本概念和功能。最好在阅读的时
候准备一个 Python 解释器进行练习。所有的例子都是相互独立的，所以这个教程
也可以离线阅读。

有关标准的对象和模块，请参阅 *note Python 标准库: 120b.。*note
Python语言参考: 120c. 提供了更正式的语言定义。想要编写 C 或者 C++ 扩展可
以参考 *note 扩展和嵌入 Python 解释器: 120d. 和 *note Python/C API
参考手册: 120e.。另外还有不少书籍深入讲解 Python。

这个教程并没有完整地介绍每一个功能，甚至可能没有涉及全部的常用功能。这个
教程只介绍 Python 中最值得注意的功能，也会让你体会到这个语言的风格特色。
学习完这个教程，你将可以阅读和编写 Python 模块和程序，也可以开始学习
*note Python 标准库: 120b.。

*note 术语对照表: 120f. 也很值得一读。

* Menu:

* 课前甜点::
* 使用 Python 解释器::
* Python 的非正式介绍::
* 其他流程控制工具::
* 数据结构::
* 模块::
* 输入输出::
* 错误和异常::
* 类::
* 标准库简介::
* 标准库简介 —— 第二部分::
* 虚拟环境和包::
* 接下来？::
* 交互式编辑和编辑历史::
* 浮点算术：争议和限制::
* 附录::


File: python.info,  Node: 课前甜点,  Next: 使用 Python 解释器,  Up: Python 教程

2.1 课前甜点
============

如果你经常在电脑上工作，总会有些任务会想让它自动化。比如，对一大堆文本文
件进行查找替换，对很多照片文件按照比较复杂的规则重命名并放入不同的文件夹
。也可能你想写一个小型的数据库应用，一个特定的图形界面应用，或者一个简单
的游戏。

如果你是专业的软件开发人员，你可能需要编写一些 C/C++/Java 库，但总觉得通
常的 编写、编译、测试、再次编译 流程太慢了。可能给这样的库写一组测试，就
是很麻烦的工作了。或许你写了个软件，可以支持插件扩展语言，但你不想为了自
己这一个应用，专门设计和实现一种新语言了。

那么，Python 正好能满足你的需要。

对于这些任务，你也可以写 Unix shell 脚本或者 Windows 批处理完成，但是
shell 脚本最擅长移动文件和替换文本，并不适合 GUI 界面或者游戏开发。你可
以写一个 C/C++/Java 程序，但是可能初稿都要很长的开发时间。Python 的使用
则更加简单，可以在 Windows，Mac OS X，以及 Unix 操作系统上使用，而且可以
帮你更快地完成工作。

Python 很容易使用，但它是一种真正的编程语言，提供了很多数据结构，也支持
大型程序，远超 shell 脚本或批处理文件的功能。Python 还提供比 C 语言更多
的错误检查，而且作为一种 “超高级语言”，它有高级的内置数据类型，比如灵活
的数组和字典。正因为这些更加通用的数据类型，Python 能够应付更多的问题，
超过 Awk 甚至 Perl，而且很多东西在 Python 中至少和那些语言同样简单。

Python 允许你将程序划分为能在其他的 Python 程序中重复利用的模块。它内置
了很多的标准模块，你可以在此基础上开发程序——也可以作为例子，开始学习
Python 编程。例如，一切内置模块提供诸如文件输入输出、系统调用、套接字、
甚至图形界面接口工作包比如 Tk。

Python 是一种解释型语言，在程序开发阶段可以为你节省大量时间，因为不需要
编译和链接。解释器可以交互式使用，这样就可以方便地尝试语言特性，写一些一
次性的程序，或者在自底向上的程序开发中测试功能。它也是一个顺手的桌面计算
器。

Python 程序的书写是紧凑而易读的。Python 代码通常比同样功能的 C，C++，
Java 代码要短很多，有如下几个原因：

   * 高级数据类型允许在一个表达式中表示复杂的操作；

   * 代码块的划分是按照缩进而不是成对的花括号；

   * 不需要预先定义变量或参数。

Python 是 “可扩展的”：如果你知道怎么写 C 语言程序，就能很容易地给解释器
添加新的内置函数或模块，不论是让关键的操作以最高速度运行，还是把 Python
程序链接到只提供预编译程序的库（比如硬件相关的图形库）。一旦你真正链接上
了，就能在 Python 解释器中扩展或者控制 C 语言编写的应用了。

顺便提一下，这种语言的名字（python 一词直译为 “蟒蛇”）得名自 BBC 节目
“Monty Python的飞行马戏团” ，而与爬行动物没有关系。在文档中用 Monty
Python 来开玩笑不只是被允许的，还是被推荐的！

现在你已经对 Python 跃跃欲试了，想要深入了解一些细节了。因为学习语言的最
佳方式是使用它，本教程邀请你一边阅读，一边在 Python 解释器中玩耍。

在下一章节，会讲解使用解释器的方法。看起来相当枯燥，但是对于尝试后续的例
子来说，是非常关键的。

教程的其他部分将通过示例介绍 Python 语言和系统中的不同功能，开始是比较简
单的表达式、语句和数据类型，然后是函数和模块，最终接触一些高级概念，比如
异常、用户定义的类。


File: python.info,  Node: 使用 Python 解释器,  Next: Python 的非正式介绍,  Prev: 课前甜点,  Up: Python 教程

2.2 使用 Python 解释器
======================

* Menu:

* 调用解释器::
* 解释器的运行环境::


File: python.info,  Node: 调用解释器,  Next: 解释器的运行环境,  Up: 使用 Python 解释器

2.2.1 调用解释器
----------------

Python 解释器在其被使用的机器上通常安装为 ‘/usr/local/bin/python3.8’；将
‘/usr/local/bin’ 加入你的 Unix 终端的搜索路径就可以通过键入以下命令来启
动它：

     python3.8

就能运行了 (1) 。安装时可以选择安装目录，所以解释器也可能在别的地方；可
以问问你身边的 Python 大牛，或者你的系统管理员。（比如
‘/usr/local/python’ 也是比较常用的备选路径）

在 Windows 机器上当你从 *note Microsoft Store: 1218. 安装 Python 之后，
‘python3.8’ 命令将可使用。 如果你安装了 *note py.exe 启动器: 997.，你将
可以使用 ‘py’ 命令。 参阅 *note 附录：设置环境变量: 1219. 了解其他启动
Python 的方式。

在主提示符中输入文件结束字符（在 Unix 系统中是 ‘Control-D’，Windows 系统
中是 ‘Control-Z’）就退出解释器并返回退出状态为0。如果这样不管用，你还可
以写这个命令退出：‘quit()’。

解释器的行编辑功能在支持 GNU Readline(2) 库的系统中也包括交互式编辑，历
史替换和代码补全等。 检测是否支持行编辑最快速的方式是在首次出现 Python 提
示符时输入 ‘Control-P’。 如果听到“哔”提示音，就说明支持行编辑；请参阅附
录 *note 交互式编辑和编辑历史: 121a. 了解有关功能键的介绍。 如果什么都没
发生，或是回显了 ‘^P’，说明不支持行编辑；你只能用退格键从当前行中删除字
符。

解释器运行的时候有点像 Unix 命令行：在一个标准输入 tty 设备上调用，它能
交互式地读取和执行命令；调用时提供文件名参数，或者有个文件重定向到标准输
入的话，它就会读取和执行文件中的 `脚本'。

另一种启动解释器的方式是 ‘python -c command [arg] ...’，其中 `command' 要
换成想执行的指令，就像命令行的 *note -c: 121b. 选项。由于 Python 代码中
经常会包含对终端来说比较特殊的字符，通常情况下都建议用英文单引号把
`command' 括起来。

有些 Python 模块也可以作为脚本使用。可以这样输入：‘python -m module
[arg] ...’，这会执行 `module' 的源文件，就跟你在命令行把路径写全了一样。

在运行脚本的时候，有时可能也会需要在运行后进入交互模式。这种时候在文件参
数前，加上选项 *note -i: e27. 就可以了。

关于所有的命令行选项，请参考 *note 命令行与环境: fba.。

* Menu:

* 传入参数::
* 交互模式::

   ---------- Footnotes ----------

   (1) (1) 在Unix系统中，Python 3.x解释器默认安装后的执行文件并不叫作
‘python’，这样才不会与同时安装的Python 2.x冲突。

   (2) https://tiswww.case.edu/php/chet/readline/rltop.html


File: python.info,  Node: 传入参数,  Next: 交互模式,  Up: 调用解释器

2.2.1.1 传入参数
................

如果可能的话，解释器会读取命令行参数，转化为字符串列表存入 ‘sys’ 模块中
的 ‘argv’ 变量中。执行命令 ‘import sys’ 你可以导入这个模块并访问这个列表
。这个列表最少也会有一个元素；如果没有给定输入参数，‘sys.argv[0]’ 就是个
空字符串。如果给定的脚本名是 ‘'-'’ (表示标准输入)，‘sys.argv[0]’ 就是
‘'-'’。使用 *note -c: 121b. `command' 时，‘sys.argv[0]’ 就会是 ‘'-c'’。
如果使用选项 *note -m: 340. `module'，‘sys.argv[0]’ 就是包含目录的模块全
名。在 *note -c: 121b. `command' 或 *note -m: 340. `module' 之后的选项不
会被解释器处理，而会直接留在 ‘sys.argv’ 中给命令或模块来处理。


File: python.info,  Node: 交互模式,  Prev: 传入参数,  Up: 调用解释器

2.2.1.2 交互模式
................

在终端（tty）输入并执行指令时，我们说解释器是运行在 `交互模式（
interactive mode）'。在这种模式中，它会显示 `主提示符（primary prompt）
'，提示输入下一条指令，通常用三个大于号（‘>>>’）表示；连续输入行的时候，
它会显示 `次要提示符'，默认是三个点（‘...’）。进入解释器时，它会先显示欢
迎信息、版本信息、版权声明，然后就会出现提示符：

     $ python3.8
     Python 3.8 (default, Sep 16 2015, 09:25:04)
     [GCC 4.8.2] on linux
     Type "help", "copyright", "credits" or "license" for more information.
     >>>

多行指令需要在连续的多行中输入。比如，以 *note if: def. 为例：

     >>> the_world_is_flat = True
     >>> if the_world_is_flat:
     ...     print("Be careful not to fall off!")
     ...
     Be careful not to fall off!

有关交互模式的更多内容，请见 *note 交互模式: 121f.。


File: python.info,  Node: 解释器的运行环境,  Prev: 调用解释器,  Up: 使用 Python 解释器

2.2.2 解释器的运行环境
----------------------

* Menu:

* 源文件的字符编码::


File: python.info,  Node: 源文件的字符编码,  Up: 解释器的运行环境

2.2.2.1 源文件的字符编码
........................

默认情况下，Python 源码文件以 UTF-8 编码方式处理。在这种编码方式中，世界
上大多数语言的字符都可以同时用于字符串字面值、变量或函数名称以及注释中
——尽管标准库中只用常规的 ASCII 字符作为变量或函数名，而且任何可移植的代
码都应该遵守此约定。要正确显示这些字符，你的编辑器必须能识别 UTF-8 编码
，而且必须使用能支持打开的文件中所有字符的字体。

如果不使用默认编码，要声明文件所使用的编码，文件的 `第一' 行要写成特殊的
注释。语法如下所示：

     # -*- coding: encoding -*-

其中 `encoding' 可以是 Python 支持的任意一种 *note codecs: 1c.。

比如，要声明使用 Windows-1252 编码，你的源码文件要写成：

     # -*- coding: cp1252 -*-

关于 `第一行' 规则的一种例外情况是，源码以 *note UNIX "shebang" 行:
1224. 开头。这种情况下，编码声明就要写在文件的第二行。例如：

     #!/usr/bin/env python3
     # -*- coding: cp1252 -*-

备注
....


File: python.info,  Node: Python 的非正式介绍,  Next: 其他流程控制工具,  Prev: 使用 Python 解释器,  Up: Python 教程

2.3 Python 的非正式介绍
=======================

在下面的例子中，通过提示符 (*note >>>: 1228. 与 *note ...: 1229.) 的出现
与否来区分输入和输出：如果你想复现这些例子，当提示符出现后，你必须在提示
符后键入例子中的每一个词；不以提示符开头的那些行是解释器的输出。注意例子
中某行中出现第二个提示符意味着你必须键入一个空白行；这是用来结束多行命令
的。

这个手册中的许多例子都包含注释，甚至交互性命令中也有。Python中的注释以井
号 ‘#’ 开头，并且一直延伸到该文本行结束为止。注释可以出现在一行的开头或
者是空白和代码的后边，但是不能出现在字符串中间。字符串中的井号就是井号。
因为注释是用来阐明代码的，不会被 Python 解释，所以在键入这些例子时，注释
是可以被忽略的。

几个例子:

     # this is the first comment
     spam = 1  # and this is the second comment
               # ... and now a third!
     text = "# This is not a comment because it's inside quotes."

* Menu:

* Python 作为计算器使用::
* 走向编程的第一步::


File: python.info,  Node: Python 作为计算器使用,  Next: 走向编程的第一步,  Up: Python 的非正式介绍

2.3.1 Python 作为计算器使用
---------------------------

让我们尝试一些简单的 Python 命令。启动解释器，等待界面中的提示符，‘>>>’
（这应该花不了多少时间）。

* Menu:

* 数字::
* 字符串::
* 列表::


File: python.info,  Node: 数字,  Next: 字符串,  Up: Python 作为计算器使用

2.3.1.1 数字
............

解释器就像一个简单的计算器一样：你可以在里面输入一个表达式然后它会写出答
案。 表达式的语法很直接：运算符 ‘+’、‘-’、‘*’、‘/’ 的用法和其他大部分语
言一样（比如 Pascal 或者 C 语言）；括号 (‘()’) 用来分组。比如:

     >>> 2 + 2
     4
     >>> 50 - 5*6
     20
     >>> (50 - 5*6) / 4
     5.0
     >>> 8 / 5  # division always returns a floating point number
     1.6

整数（比如 ‘2’、‘4’、‘20’ ）的类型是 *note int: 185.，有小数部分的（比如
‘5.0’、‘1.6’ ）的类型是 *note float: 188.。 在这个手册的后半部分我们会看
到更多的数字类型。

除法运算 (‘/’) 永远返回浮点数类型。如果要做 *note floor division: 122e.
得到一个整数结果（忽略小数部分）你可以使用 ‘//’ 运算符；如果要计算余数，
可以使用 ‘%’

     >>> 17 / 3  # classic division returns a float
     5.666666666666667
     >>>
     >>> 17 // 3  # floor division discards the fractional part
     5
     >>> 17 % 3  # the % operator returns the remainder of the division
     2
     >>> 5 * 3 + 2  # result * divisor + remainder
     17

在Python中，可以使用 ‘**’ 运算符来计算乘方 (1)

     >>> 5 ** 2  # 5 squared
     25
     >>> 2 ** 7  # 2 to the power of 7
     128

等号 (‘=’) 用于给一个变量赋值。然后在下一个交互提示符之前不会有结果显示
出来:

     >>> width = 20
     >>> height = 5 * 9
     >>> width * height
     900

如果一个变量未定义（未赋值），试图使用它时会向你提示错误:

     >>> n  # try to access an undefined variable
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     NameError: name 'n' is not defined

Python中提供浮点数的完整支持；包含多种混合类型运算数的运算会把整数转换为
浮点数:

     >>> 4 * 3.75 - 1
     14.0

在交互模式下，上一次打印出来的表达式被赋值给变量 ‘_’。这意味着当你把
Python用作桌面计算器时，继续计算会相对简单，比如:

     >>> tax = 12.5 / 100
     >>> price = 100.50
     >>> price * tax
     12.5625
     >>> price + _
     113.0625
     >>> round(_, 2)
     113.06

这个变量应该被使用者当作是只读类型。不要向它显式地赋值——你会创建一个和它
名字相同独立的本地变量，它会使用魔法行为屏蔽内部变量。

除了 *note int: 185. 和 *note float: 188.，Python也支持其他类型的数字，
例如 *note Decimal: 189. 或者 *note Fraction: 186.。Python 也内置对
*note 复数: 122f. 的支持，使用后缀 ‘j’ 或者 ‘J’ 就可以表示虚数部分（例如
‘3+5j’ ）。

   ---------- Footnotes ----------

   (1) (1) 因为 ‘**’ 比 ‘-’ 有更高的优先级, 所以 ‘-3**2’ 会被解释成
‘-(3**2)’ ，因此结果是 ‘-9’.  为了避免这个并且得到结果 ‘9’, 你可以用这个
式子 ‘(-3)**2’.


File: python.info,  Node: 字符串,  Next: 列表,  Prev: 数字,  Up: Python 作为计算器使用

2.3.1.2 字符串
..............

除了数字，Python 也可以操作字符串。字符串有多种形式，可以使用单引号（
‘'...'’），双引号（‘"..."’）都可以获得同样的结果 (1)。反斜杠 ‘\’ 可以用
来转义:

     >>> 'spam eggs'  # single quotes
     'spam eggs'
     >>> 'doesn\'t'  # use \' to escape the single quote...
     "doesn't"
     >>> "doesn't"  # ...or use double quotes instead
     "doesn't"
     >>> '"Yes," they said.'
     '"Yes," they said.'
     >>> "\"Yes,\" they said."
     '"Yes," they said.'
     >>> '"Isn\'t," they said.'
     '"Isn\'t," they said.'

在交互式解释器中，输出的字符串外面会加上引号，特殊字符会使用反斜杠来转义
。 虽然有时这看起来会与输入不一样（外面所加的引号可能会改变），但两个字
符串是相同的。 如果字符串中有单引号而没有双引号，该字符串外将加双引号来
表示，否则就加单引号。 *note print(): 88f. 函数会生成可读性更强的输出，
即略去两边的引号，并且打印出经过转义的特殊字符:

     >>> '"Isn\'t," they said.'
     '"Isn\'t," they said.'
     >>> print('"Isn\'t," they said.')
     "Isn't," they said.
     >>> s = 'First line.\nSecond line.'  # \n means newline
     >>> s  # without print(), \n is included in the output
     'First line.\nSecond line.'
     >>> print(s)  # with print(), \n produces a new line
     First line.
     Second line.

如果你不希望前置了 ‘\’ 的字符转义成特殊字符，可以使用 `原始字符串' 方式
，在引号前添加 ‘r’ 即可:

     >>> print('C:\some\name')  # here \n means newline!
     C:\some
     ame
     >>> print(r'C:\some\name')  # note the r before the quote
     C:\some\name

字符串字面值可以跨行连续输入。一种方式是用三重引号：‘"""..."""’ 或
‘'''...'''’。字符串中的回车换行会自动包含到字符串中，如果不想包含，在行
尾添加一个 ‘\’ 即可。如下例:

     print("""\
     Usage: thingy [OPTIONS]
          -h                        Display this usage message
          -H hostname               Hostname to connect to
     """)

将产生如下输出（注意最开始的换行没有包括进来）:

     Usage: thingy [OPTIONS]
          -h                        Display this usage message
          -H hostname               Hostname to connect to

字符串可以用 ‘+’ 进行连接（粘到一起），也可以用 ‘*’ 进行重复:

     >>> # 3 times 'un', followed by 'ium'
     >>> 3 * 'un' + 'ium'
     'unununium'

相邻的两个或多个 `字符串字面值' （引号引起来的字符）将会自动连接到一起.

     >>> 'Py' 'thon'
     'Python'

把很长的字符串拆开分别输入的时候尤其有用:

     >>> text = ('Put several strings within parentheses '
     ...         'to have them joined together.')
     >>> text
     'Put several strings within parentheses to have them joined together.'

只能对两个字面值这样操作，变量或表达式不行:

     >>> prefix = 'Py'
     >>> prefix 'thon'  # can't concatenate a variable and a string literal
       File "<stdin>", line 1
         prefix 'thon'
                     ^
     SyntaxError: invalid syntax
     >>> ('un' * 3) 'ium'
       File "<stdin>", line 1
         ('un' * 3) 'ium'
                        ^
     SyntaxError: invalid syntax

如果你想连接变量，或者连接变量和字面值，可以用 ‘+’ 号:

     >>> prefix + 'thon'
     'Python'

字符串是可以被 `索引' （下标访问）的，第一个字符索引是 0。单个字符并没有
特殊的类型，只是一个长度为一的字符串:

     >>> word = 'Python'
     >>> word[0]  # character in position 0
     'P'
     >>> word[5]  # character in position 5
     'n'

索引也可以用负数，这种会从右边开始数:

     >>> word[-1]  # last character
     'n'
     >>> word[-2]  # second-last character
     'o'
     >>> word[-6]
     'P'

注意 -0 和 0 是一样的，所以负数索引从 -1 开始。

除了索引，字符串还支持 `切片'。索引可以得到单个字符，而 `切片' 可以获取
子字符串:

     >>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
     'Py'
     >>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
     'tho'

注意切片的开始总是被包括在结果中，而结束不被包括。这使得 ‘s[:i] + s[i:]’
总是等于 ‘s’

     >>> word[:2] + word[2:]
     'Python'
     >>> word[:4] + word[4:]
     'Python'

切片的索引有默认值；省略开始索引时默认为0，省略结束索引时默认为到字符串
的结束:

     >>> word[:2]   # character from the beginning to position 2 (excluded)
     'Py'
     >>> word[4:]   # characters from position 4 (included) to the end
     'on'
     >>> word[-2:]  # characters from the second-last (included) to the end
     'on'

您也可以这么理解切片：将索引视作指向字符 `之间' ，第一个字符的左侧标为
0，最后一个字符的右侧标为 `n' ，其中 `n' 是字符串长度。例如:

      +---+---+---+---+---+---+
      | P | y | t | h | o | n |
      +---+---+---+---+---+---+
      0   1   2   3   4   5   6
     -6  -5  -4  -3  -2  -1

第一行数标注了字符串 0...6 的索引的位置，第二行标注了对应的负的索引。那
么从 `i' 到 `j' 的切片就包括了标有 `i' 和 `j' 的位置之间的所有字符。

对于使用非负索引的切片，如果索引不越界，那么得到的切片长度就是起止索引之
差。例如， ‘word[1:3]’ 的长度为2。

试图使用过大的索引会产生一个错误:

     >>> word[42]  # the word only has 6 characters
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     IndexError: string index out of range

但是，切片中的越界索引会被自动处理:

     >>> word[4:42]
     'on'
     >>> word[42:]
     ''

Python 中的字符串不能被修改，它们是 *note immutable: 1232. 的。因此，向
字符串的某个索引位置赋值会产生一个错误:

     >>> word[0] = 'J'
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: 'str' object does not support item assignment
     >>> word[2:] = 'py'
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: 'str' object does not support item assignment

如果需要一个不同的字符串，应当新建一个:

     >>> 'J' + word[1:]
     'Jython'
     >>> word[:2] + 'py'
     'Pypy'

内建函数 *note len(): 151. 返回一个字符串的长度:

     >>> s = 'supercalifragilisticexpialidocious'
     >>> len(s)
     34

参见
....

*note 文本序列类型 — str: 1233.

     字符串是一种 `序列类型' ，因此也支持序列类型的各种操作。

*note 字符串的方法: 1234.

     字符串支持许多变换和查找的方法。

*note 格式化字符串字面值: 15d.

     内嵌表达式的字符串字面值。

*note 格式字符串语法: d22.

     使用 *note str.format(): 4e2. 进行字符串格式化。

*note printf 风格的字符串格式化: 1235.

     这里详述了使用 ‘%’ 运算符进行字符串格式化。

   ---------- Footnotes ----------

   (1) (2) 和其他语言不一样的是, 特殊字符比如说 ‘\n’ 在单引号 (‘'...'’)
和双引号 (‘"..."’) 里有一样的意义. 这两种引号唯一的区别是，你不需要在单
引号里转义双引号 ‘"’ (但是你必须把单引号转义成 ‘\'’) ， 反之亦然.


File: python.info,  Node: 列表,  Prev: 字符串,  Up: Python 作为计算器使用

2.3.1.3 列表
............

Python 中可以通过组合一些值得到多种 `复合' 数据类型。其中最常用的 `列表'
，可以通过方括号括起、逗号分隔的一组值（元素）得到。一个 `列表' 可以包含
不同类型的元素，但通常使用时各个元素类型相同:

     >>> squares = [1, 4, 9, 16, 25]
     >>> squares
     [1, 4, 9, 16, 25]

和字符串（以及各种内置的 *note sequence: 1238. 类型）一样，列表也支持索
引和切片:

     >>> squares[0]  # indexing returns the item
     1
     >>> squares[-1]
     25
     >>> squares[-3:]  # slicing returns a new list
     [9, 16, 25]

所有的切片操作都返回一个包含所请求元素的新列表。 这意味着以下切片操作会
返回列表的一个 *note 浅拷贝: 1239.:

     >>> squares[:]
     [1, 4, 9, 16, 25]

列表同样支持拼接操作:

     >>> squares + [36, 49, 64, 81, 100]
     [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

与 *note immutable: 1232. 的字符串不同, 列表是一个 *note mutable: 123a.
类型，就是说，它自己的内容可以改变:

     >>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
     >>> 4 ** 3  # the cube of 4 is 64, not 65!
     64
     >>> cubes[3] = 64  # replace the wrong value
     >>> cubes
     [1, 8, 27, 64, 125]

你也可以在列表末尾通过 ‘append()’ `方法' 来添加新元素（我们将在后面介绍
有关方法的详情）:

     >>> cubes.append(216)  # add the cube of 6
     >>> cubes.append(7 ** 3)  # and the cube of 7
     >>> cubes
     [1, 8, 27, 64, 125, 216, 343]

给切片赋值也是可以的，这样甚至可以改变列表大小，或者把列表整个清空:

     >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
     >>> letters
     ['a', 'b', 'c', 'd', 'e', 'f', 'g']
     >>> # replace some values
     >>> letters[2:5] = ['C', 'D', 'E']
     >>> letters
     ['a', 'b', 'C', 'D', 'E', 'f', 'g']
     >>> # now remove them
     >>> letters[2:5] = []
     >>> letters
     ['a', 'b', 'f', 'g']
     >>> # clear the list by replacing all the elements with an empty list
     >>> letters[:] = []
     >>> letters
     []

内置函数 *note len(): 151. 也可以作用到列表上:

     >>> letters = ['a', 'b', 'c', 'd']
     >>> len(letters)
     4

也可以嵌套列表 (创建包含其他列表的列表), 比如说:

     >>> a = ['a', 'b', 'c']
     >>> n = [1, 2, 3]
     >>> x = [a, n]
     >>> x
     [['a', 'b', 'c'], [1, 2, 3]]
     >>> x[0]
     ['a', 'b', 'c']
     >>> x[0][1]
     'b'


File: python.info,  Node: 走向编程的第一步,  Prev: Python 作为计算器使用,  Up: Python 的非正式介绍

2.3.2 走向编程的第一步
----------------------

当然，我们可以将 Python 用于更复杂的任务，而不是仅仅两个和两个一起添加。
例如，我们可以编写 斐波那契数列(1) 的初始子序列，如下所示:

     >>> # Fibonacci series:
     ... # the sum of two elements defines the next
     ... a, b = 0, 1
     >>> while a < 10:
     ...     print(a)
     ...     a, b = b, a+b
     ...
     0
     1
     1
     2
     3
     5
     8

这个例子引入了几个新的特性。

   * 第一行含有一个 `多重赋值': 变量 ‘a’ 和 ‘b’ 同时得到了新值 0 和 1.  最
     后一行又用了一次多重赋值, 这展示出了右手边的表达式，在任何赋值发生
     之前就被求值了。右手边的表达式是从左到右被求值的。

   * *note while: 123d. 循环只要它的条件（这里指： ‘a < 10’）保持为真就
     会一直执行。Python 和 C 一样，任何非零整数都为真；零为假。这个条件
     也可以是字符串或是列表的值，事实上任何序列都可以；长度非零就为真，
     空序列就为假。在这个例子里，判断条件是一个简单的比较。标准的比较操
     作符的写法和 C 语言里是一样： ‘<’ （小于）、 ‘>’ （大于）、 ‘==’ （
     等于）、 ‘<=’ （小于或等于)、 ‘>=’ （大于或等于）以及 ‘!=’ （不等于
     ）。

   * `循环体' 是 `缩进的' ：缩进是 Python 组织语句的方式。在交互式命令行
     里，你得给每个缩进的行敲下 Tab 键或者（多个）空格键。实际上用文本编
     辑器的话，你要准备更复杂的输入方式；所有像样的文本编辑器都有自动缩
     进的设置。交互式命令行里，当一个组合的语句输入时, 需要在最后敲一个
     空白行表示完成（因为语法分析器猜不出来你什么时候打的是最后一行）。
     注意，在同一块语句中的每一行，都要缩进相同的长度。

   * *note print(): 88f. 函数将所有传进来的参数值打印出来. 它和直接输入
     你要显示的表达式(比如我们之前在计算器的例子里做的)不一样， print()
     能处理多个参数，包括浮点数，字符串。 字符串会打印不带引号的内容, 并
     且在参数项之间会插入一个空格, 这样你就可以很好的把东西格式化, 像这
     样:

          >>> i = 256*256
          >>> print('The value of i is', i)
          The value of i is 65536

     关键字参数 `end' 可以用来取消输出后面的换行, 或使用另外一个字符串来
     结尾:

          >>> a, b = 0, 1
          >>> while a < 1000:
          ...     print(a, end=',')
          ...     a, b = b, a+b
          ...
          0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

备注
....

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Fibonacci_number


File: python.info,  Node: 其他流程控制工具,  Next: 数据结构,  Prev: Python 的非正式介绍,  Up: Python 教程

2.4 其他流程控制工具
====================

除了刚刚介绍过的 *note while: 123d. 语句，Python 中也会使用其他语言中常
见的流程控制语句，只是稍有变化。

* Menu:

* if 语句::
* for 语句::
* range() 函数: range 函数.
* break 和 continue 语句，以及循环中的 else 子句::
* pass 语句::
* 定义函数::
* 函数定义的更多形式::
* 小插曲：编码风格::


File: python.info,  Node: if 语句,  Next: for 语句,  Up: 其他流程控制工具

2.4.1 ‘if’ 语句
---------------

可能最为人所熟知的编程语句就是 *note if: def. 语句了。例如

     >>> x = int(input("Please enter an integer: "))
     Please enter an integer: 42
     >>> if x < 0:
     ...     x = 0
     ...     print('Negative changed to zero')
     ... elif x == 0:
     ...     print('Zero')
     ... elif x == 1:
     ...     print('Single')
     ... else:
     ...     print('More')
     ...
     More

可以有零个或多个 *note elif: 1243. 部分，以及一个可选的 *note else:
1244. 部分。 关键字 ’‘elif’’ 是 ’else if’ 的缩写，适合用于避免过多的缩进
。 一个 ‘if’ ...  ‘elif’ ...  ‘elif’ ... 序列可以看作是其他语言中的
‘switch’ 或 ‘case’ 语句的替代。


File: python.info,  Node: for 语句,  Next: range 函数,  Prev: if 语句,  Up: 其他流程控制工具

2.4.2 ‘for’ 语句
----------------

Python 中的 *note for: c38. 语句与你在 C 或 Pascal 中所用到的有所不同。
Python 中的 ‘for’ 语句并不总是对算术递增的数值进行迭代（如同 Pascal），
或是给予用户定义迭代步骤和暂停条件的能力（如同 C），而是对任意序列进行迭
代（例如列表或字符串），条目的迭代顺序与它们在序列中出现的顺序一致。 例
如（此处英文为双关语）:

     >>> # Measure some strings:
     ... words = ['cat', 'window', 'defenestrate']
     >>> for w in words:
     ...     print(w, len(w))
     ...
     cat 3
     window 6
     defenestrate 12

在遍历同一个集合时修改该集合的代码可能很难获得正确的结果。通常，更直接的
做法是循环遍历该集合的副本或创建新集合：

     # Strategy:  Iterate over a copy
     for user, status in users.copy().items():
         if status == 'inactive':
             del users[user]

     # Strategy:  Create a new collection
     active_users = {}
     for user, status in users.items():
         if status == 'active':
             active_users[user] = status


File: python.info,  Node: range 函数,  Next: break 和 continue 语句，以及循环中的 else 子句,  Prev: for 语句,  Up: 其他流程控制工具

2.4.3 ‘range()’ 函数
--------------------

如果你确实需要遍历一个数字序列，内置函数 *note range(): 9c6. 会派上用场
。它生成算术级数:

     >>> for i in range(5):
     ...     print(i)
     ...
     0
     1
     2
     3
     4

给定的终止数值并不在要生成的序列里；‘range(10)’ 会生成10个值，并且是以合
法的索引生成一个长度为10的序列。range也可以以另一个数字开头，或者以指定
的幅度增加（甚至是负数；有时这也被叫做 ’步进’）

     range(5, 10)
        5, 6, 7, 8, 9

     range(0, 10, 3)
        0, 3, 6, 9

     range(-10, -100, -30)
       -10, -40, -70

要以序列的索引来迭代，您可以将 *note range(): 9c6. 和 *note len(): 151.
组合如下:

     >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
     >>> for i in range(len(a)):
     ...     print(i, a[i])
     ...
     0 Mary
     1 had
     2 a
     3 little
     4 lamb

然而，在大多数这类情况下，使用 *note enumerate(): deb. 函数比较方便，请
参见 *note 循环的技巧: 1249. 。

如果你只打印 range，会出现奇怪的结果:

     >>> print(range(10))
     range(0, 10)

*note range(): 9c6. 所返回的对象在许多方面表现得像一个列表，但实际上却并
不是。此对象会在你迭代它时基于所希望的序列返回连续的项，但它没有真正生成
列表，这样就能节省空间。

我们称这样对象为 *note iterable: bb4.，也就是说，适合作为这样的目标对象
：函数和结构期望从中获取连续的项直到所提供的项全部耗尽。 我们已经看到
*note for: c38. 语句就是这样一种结构，而接受可迭代对象的函数的一个例子是
*note sum(): 1e6.:

     >>> sum(range(4))  # 0 + 1 + 2 + 3
     6

稍后我们将看到更多返回可迭代对象以及将可迭代对象作为参数的函数。 最后，
也许你会很好奇如何从一个指定范围内获取一个列表。 以下是解决方案：

     >>> list(range(4))
     [0, 1, 2, 3]

在 *note 数据结构: 124a. 章节中，我们将讨论 *note list(): 263. 的更多细
节。


File: python.info,  Node: break 和 continue 语句，以及循环中的 else 子句,  Next: pass 语句,  Prev: range 函数,  Up: 其他流程控制工具

2.4.4 ‘break’ 和 ‘continue’ 语句，以及循环中的 ‘else’ 子句
----------------------------------------------------------

*note break: 2dc. 语句，和 C 中的类似，用于跳出最近的 *note for: c38. 或
*note while: 123d. 循环.

循环语句可能带有 ‘else’ 子句；它会在循环耗尽了可迭代对象 (使用 *note
for: c38.) 或循环条件变为假值 (使用 *note while: 123d.) 时被执行，但不会
在循环被 *note break: 2dc. 语句终止时被执行。 以下搜索素数的循环就是这样
的一个例子:

     >>> for n in range(2, 10):
     ...     for x in range(2, n):
     ...         if n % x == 0:
     ...             print(n, 'equals', x, '*', n//x)
     ...             break
     ...     else:
     ...         # loop fell through without finding a factor
     ...         print(n, 'is a prime number')
     ...
     2 is a prime number
     3 is a prime number
     4 equals 2 * 2
     5 is a prime number
     6 equals 2 * 3
     7 is a prime number
     8 equals 2 * 4
     9 equals 3 * 3

（是的，这是正确的代码。仔细看： ‘else’ 子句属于 *note for: c38. 循环，
`不属于' *note if: def. 语句。）

当和循环一起使用时，‘else’ 子句与 *note try: d7a. 语句中的 ‘else’ 子句的
共同点多于 *note if: def. 语句中的同类子句: *note try: d7a. 语句中的
‘else’ 子句会在未发生异常时执行，而循环中的 ‘else’ 子句则会在未发生
‘break’ 时执行。 有关 ‘try’ 语句和异常的更多信息，请参阅 *note 处理异常:
124d.。

*note continue: 182. 语句也是借鉴自 C 语言，表示继续循环中的下一次迭代:

     >>> for num in range(2, 10):
     ...     if num % 2 == 0:
     ...         print("Found an even number", num)
     ...         continue
     ...     print("Found an odd number", num)
     Found an even number 2
     Found an odd number 3
     Found an even number 4
     Found an odd number 5
     Found an even number 6
     Found an odd number 7
     Found an even number 8
     Found an odd number 9


File: python.info,  Node: pass 语句,  Next: 定义函数,  Prev: break 和 continue 语句，以及循环中的 else 子句,  Up: 其他流程控制工具

2.4.5 ‘pass’ 语句
-----------------

*note pass: 1250. 语句什么也不做。当语法上需要一个语句，但程序需要什么动
作也不做时，可以使用它。例如:

     >>> while True:
     ...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
     ...

这通常用于创建最小的类:

     >>> class MyEmptyClass:
     ...     pass
     ...

*note pass: 1250. 的另一个可以使用的场合是在你编写新的代码时作为一个函数
或条件子句体的占位符，允许你保持在更抽象的层次上进行思考。 ‘pass’ 会被静
默地忽略:

     >>> def initlog(*args):
     ...     pass   # Remember to implement this!
     ...


File: python.info,  Node: 定义函数,  Next: 函数定义的更多形式,  Prev: pass 语句,  Up: 其他流程控制工具

2.4.6 定义函数
--------------

我们可以创建一个输出任意范围内 Fibonacci 数列的函数:

     >>> def fib(n):    # write Fibonacci series up to n
     ...     """Print a Fibonacci series up to n."""
     ...     a, b = 0, 1
     ...     while a < n:
     ...         print(a, end=' ')
     ...         a, b = b, a+b
     ...     print()
     ...
     >>> # Now call the function we just defined:
     ... fib(2000)
     0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

关键字 *note def: dc6. 引入一个函数 `定义'。它必须后跟函数名称和带括号的
形式参数列表。构成函数体的语句从下一行开始，并且必须缩进。

函数体的第一个语句可以（可选的）是字符串文字；这个字符串文字是函数的文档
字符串或 `docstring' 。（有关文档字符串的更多信息，请参阅 *note
文档字符串: 1253. 部分）有些工具使用文档字符串自动生成在线或印刷文档，或
者让用户以交互式的形式浏览代码；在你编写的代码中包含文档字符串是一种很好
的做法，所以要养成习惯。

函数的 `执行' 会引入一个用于函数局部变量的新符号表。 更确切地说，函数中
所有的变量赋值都将存储在局部符号表中；而变量引用会首先在局部符号表中查找
，然后是外层函数的局部符号表，再然后是全局符号表，最后是内置名称的符号表
。 因此，全局变量和外层函数的变量不能在函数内部直接赋值（除非是在 *note
global: 1254. 语句中定义的全局变量，或者是在 *note nonlocal: c47. 语句中
定义的外层函数的变量），尽管它们可以被引用。

在调用函数时会将实际参数（实参）引入到被调用函数的局部符号表中；因此，实
参是使用 `按值调用' 来传递的（其中的 `值' 始终是对象的 `引用' 而不是对象
的值）。 (1) 当一个函数调用另外一个函数时，会为该调用创建一个新的局部符
号表。

函数定义会将函数名称与函数对象在当前符号表中进行关联。 解释器会将该名称
所指向的对象识别为用户自定义函数。 其他名称也可指向同一个函数对象并可被
用来访问访函数:

     >>> fib
     <function fib at 10042ed0>
     >>> f = fib
     >>> f(100)
     0 1 1 2 3 5 8 13 21 34 55 89

如果你学过其他语言，你可能会认为 ‘fib’ 不是函数而是一个过程，因为它并不
返回值。事实上，即使没有 *note return: 191. 语句的函数也会返回一个值，尽
管它是一个相当无聊的值。这个值称为 ‘None’ （它是内置名称）。一般来说解释
器不会打印出单独的返回值 ‘None’ ，如果你真想看到它，你可以使用 *note
print(): 88f.

     >>> fib(0)
     >>> print(fib(0))
     None

写一个返回斐波那契数列的列表（而不是把它打印出来）的函数，非常简单:

     >>> def fib2(n):  # return Fibonacci series up to n
     ...     """Return a list containing the Fibonacci series up to n."""
     ...     result = []
     ...     a, b = 0, 1
     ...     while a < n:
     ...         result.append(a)    # see below
     ...         a, b = b, a+b
     ...     return result
     ...
     >>> f100 = fib2(100)    # call it
     >>> f100                # write the result
     [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

此示例中，像往常一样，演示了一些新的 Python 功能:

   * *note return: 191. 语句会从函数内部返回一个值。 不带表达式参数的
     ‘return’ 会返回 ‘None’。 函数执行完毕退出也会返回 ‘None’。

   * ‘result.append(a)’ 语句调用了列表对象 ‘result’ 的 `方法' 。方法是
     “属于”一个对象的函数，它被命名为 ‘obj.methodname’ ，其中 ‘obj’ 是某
     个对象（也可能是一个表达式）， ‘methodname’ 是由对象类型中定义的方
     法的名称。不同的类型可以定义不同的方法。不同类型的方法可以有相同的
     名称而不会引起歧义。（可以使用 `类' 定义自己的对象类型和方法，请参
     阅 *note 类: 1255. ）示例中的方法 ‘append()’ 是为列表对象定义的；它
     会在列表的最后添加一个新的元素。在这个示例中它相当于 ‘result =
     result + [a]’ ，但更高效。

   ---------- Footnotes ----------

   (1) (1) 实际上，`通过对象引用调用' 会是一个更好的表述，因为如果传递的
是可变对象，则调用者将看到被调用者对其做出的任何更改（插入到列表中的元素
）。


File: python.info,  Node: 函数定义的更多形式,  Next: 小插曲：编码风格,  Prev: 定义函数,  Up: 其他流程控制工具

2.4.7 函数定义的更多形式
------------------------

给函数定义有可变数目的参数也是可行的。这里有三种形式，可以组合使用。

* Menu:

* 参数默认值::
* 关键字参数::
* 特殊参数::
* 任意的参数列表::
* 解包参数列表::
* Lambda 表达式::
* 文档字符串::
* 函数标注::


File: python.info,  Node: 参数默认值,  Next: 关键字参数,  Up: 函数定义的更多形式

2.4.7.1 参数默认值
..................

最有用的形式是对一个或多个参数指定一个默认值。这样创建的函数，可以用比定
义时允许的更少的参数调用，比如:

     def ask_ok(prompt, retries=4, reminder='Please try again!'):
         while True:
             ok = input(prompt)
             if ok in ('y', 'ye', 'yes'):
                 return True
             if ok in ('n', 'no', 'nop', 'nope'):
                 return False
             retries = retries - 1
             if retries < 0:
                 raise ValueError('invalid user response')
             print(reminder)

这个函数可以通过几种方式调用:

   * 只给出必需的参数：‘ask_ok('Do you really want to quit?')’

   * 给出一个可选的参数：‘ask_ok('OK to overwrite the file?', 2)’

   * 或者给出所有的参数：‘ask_ok('OK to overwrite the file?', 2, 'Come
     on, only yes or no!')’

这个示例还介绍了 *note in: 7ac. 关键字。它可以测试一个序列是否包含某个值
。

默认值是在 `定义过程' 中在函数定义处计算的，所以

     i = 5

     def f(arg=i):
         print(arg)

     i = 6
     f()

会打印 ‘5’。

`重要警告：' 默认值只会执行一次。这条规则在默认值为可变对象（列表、字典
以及大多数类实例）时很重要。比如，下面的函数会存储在后续调用中传递给它的
参数:

     def f(a, L=[]):
         L.append(a)
         return L

     print(f(1))
     print(f(2))
     print(f(3))

这将打印出

     [1]
     [1, 2]
     [1, 2, 3]

如果你不想要在后续调用之间共享默认值，你可以这样写这个函数:

     def f(a, L=None):
         if L is None:
             L = []
         L.append(a)
         return L


File: python.info,  Node: 关键字参数,  Next: 特殊参数,  Prev: 参数默认值,  Up: 函数定义的更多形式

2.4.7.2 关键字参数
..................

也可以使用形如 ‘kwarg=value’ 的 *note 关键字参数: 5cd. 来调用函数。例如
下面的函数:

     def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
         print("-- This parrot wouldn't", action, end=' ')
         print("if you put", voltage, "volts through it.")
         print("-- Lovely plumage, the", type)
         print("-- It's", state, "!")

接受一个必需的参数（‘voltage’）和三个可选的参数（‘state’, ‘action’，和
‘type’）。这个函数可以通过下面的任何一种方式调用:

     parrot(1000)                                          # 1 positional argument
     parrot(voltage=1000)                                  # 1 keyword argument
     parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
     parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
     parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
     parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

但下面的函数调用都是无效的:

     parrot()                     # required argument missing
     parrot(voltage=5.0, 'dead')  # non-keyword argument after a keyword argument
     parrot(110, voltage=220)     # duplicate value for the same argument
     parrot(actor='John Cleese')  # unknown keyword argument

在函数调用中，关键字参数必须跟随在位置参数的后面。传递的所有关键字参数必
须与函数接受的其中一个参数匹配（比如 ‘actor’ 不是函数 ‘parrot’ 的有效参
数），它们的顺序并不重要。这也包括非可选参数，（比如
‘parrot(voltage=1000)’ 也是有效的）。不能对同一个参数多次赋值。下面是一
个因为此限制而失败的例子:

     >>> def function(a):
     ...     pass
     ...
     >>> function(0, a=0)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: function() got multiple values for keyword argument 'a'

当存在一个形式为 ‘**name’ 的最后一个形参时，它会接收一个字典 (参见 *note
映射类型 — dict: 305.)，其中包含除了与已有形参相对应的关键字参数以外的所
有关键字参数。 这可以与一个形式为 ‘*name’，接收一个包含除了已有形参列表
以外的位置参数的 *note 元组: 125c. 的形参 (将在下一小节介绍) 组合使用
(‘*name’ 必须出现在 ‘**name’ 之前。) 例如，如果我们这样定义一个函数:

     def cheeseshop(kind, *arguments, **keywords):
         print("-- Do you have any", kind, "?")
         print("-- I'm sorry, we're all out of", kind)
         for arg in arguments:
             print(arg)
         print("-" * 40)
         for kw in keywords:
             print(kw, ":", keywords[kw])

它可以像这样调用:

     cheeseshop("Limburger", "It's very runny, sir.",
                "It's really very, VERY runny, sir.",
                shopkeeper="Michael Palin",
                client="John Cleese",
                sketch="Cheese Shop Sketch")

当然它会打印:

     -- Do you have any Limburger ?
     -- I'm sorry, we're all out of Limburger
     It's very runny, sir.
     It's really very, VERY runny, sir.
     ----------------------------------------
     shopkeeper : Michael Palin
     client : John Cleese
     sketch : Cheese Shop Sketch

注意打印时关键字参数的顺序保证与调用函数时提供它们的顺序是相匹配的。


File: python.info,  Node: 特殊参数,  Next: 任意的参数列表,  Prev: 关键字参数,  Up: 函数定义的更多形式

2.4.7.3 特殊参数
................

默认情况下，函数的参数传递形式可以是位置参数或是显式的关键字参数。 为了
确保可读性和运行效率，限制允许的参数传递形式是有意义的，这样开发者只需查
看函数定义即可确定参数项是仅按位置、按位置也按关键字，还是仅按关键字传递
。

函数的定义看起来可以像是这样：

     def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
           -----------    ----------     ----------
             |             |                  |
             |        Positional or keyword   |
             |                                - Keyword only
              -- Positional only

在这里 ‘/’ 和 ‘*’ 是可选的。 如果使用这些符号则表明可以通过何种形参将参
数值传递给函数：仅限位置、位置或关键字，以及仅限关键字。 关键字形参也被
称为命名形参。

* Menu:

* 位置或关键字参数::
* 仅限位置参数::
* 仅限关键字参数::
* 函数示例::
* 概括::


File: python.info,  Node: 位置或关键字参数,  Next: 仅限位置参数,  Up: 特殊参数

2.4.7.4 位置或关键字参数
........................

如果函数定义中未使用 ‘/’ 和 ‘*’，则参数可以按位置或按关键字传递给函数。


File: python.info,  Node: 仅限位置参数,  Next: 仅限关键字参数,  Prev: 位置或关键字参数,  Up: 特殊参数

2.4.7.5 仅限位置参数
....................

在这里还可以发现更多细节，特定形参可以被标记为 `仅限位置'。 如果是 `仅限
位置' 的形参，则其位置是重要的，并且该形参不能作为关键字传入。 仅限位置
形参要放在 ‘/’ (正斜杠) 之前。 这个 ‘/’ 被用来从逻辑上分隔仅限位置形参和
其它形参。 如果函数定义中没有 ‘/’，则表示没有仅限位置形参。

在 ‘/’ 之后的形参可以为 `位置或关键字' 或 `仅限关键字'。


File: python.info,  Node: 仅限关键字参数,  Next: 函数示例,  Prev: 仅限位置参数,  Up: 特殊参数

2.4.7.6 仅限关键字参数
......................

要将形参标记为 `仅限关键字'，即指明该形参必须以关键字参数的形式传入，应
在参数列表的第一个 `仅限关键字' 形参之前放置一个 ‘*’。


File: python.info,  Node: 函数示例,  Next: 概括,  Prev: 仅限关键字参数,  Up: 特殊参数

2.4.7.7 函数示例
................

请考虑以下示例函数定义并特别注意 ‘/’ 和 ‘*’ 标记:

     >>> def standard_arg(arg):
     ...     print(arg)
     ...
     >>> def pos_only_arg(arg, /):
     ...     print(arg)
     ...
     >>> def kwd_only_arg(*, arg):
     ...     print(arg)
     ...
     >>> def combined_example(pos_only, /, standard, *, kwd_only):
     ...     print(pos_only, standard, kwd_only)

第一个函数定义 ‘standard_arg’ 是最常见的形式，对调用方式没有任何限制，参
数可以按位置也可以按关键字传入:

     >>> standard_arg(2)
     2

     >>> standard_arg(arg=2)
     2

第二个函数 ‘pos_only_arg’ 在函数定义中带有 ‘/’，限制仅使用位置形参。:

     >>> pos_only_arg(1)
     1

     >>> pos_only_arg(arg=1)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: pos_only_arg() got an unexpected keyword argument 'arg'

第三个函数 ‘kwd_only_args’ 在函数定义中通过 ‘*’ 指明仅允许关键字参数:

     >>> kwd_only_arg(3)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given

     >>> kwd_only_arg(arg=3)
     3

而最后一个则在同一函数定义中使用了全部三种调用方式:

     >>> combined_example(1, 2, 3)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: combined_example() takes 2 positional arguments but 3 were given

     >>> combined_example(1, 2, kwd_only=3)
     1 2 3

     >>> combined_example(1, standard=2, kwd_only=3)
     1 2 3

     >>> combined_example(pos_only=1, standard=2, kwd_only=3)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: combined_example() got an unexpected keyword argument 'pos_only'

最后，请考虑这个函数定义，它的位置参数 ‘name’ 和 ‘**kwds’ 之间由于存在关
键字名称 ‘name’ 而可能产生潜在冲突:

     def foo(name, **kwds):
         return 'name' in kwds

任何调用都不可能让它返回 ‘True’，因为关键字 ‘'name'’ 将总是绑定到第一个
形参。 例如:

     >>> foo(1, **{'name': 2})
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: foo() got multiple values for argument 'name'
     >>>

但使用 ‘/’ (仅限位置参数) 就可能做到，因为它允许 ‘name’ 作为位置参数，也
允许 ‘'name'’ 作为关键字参数的关键字名称:

     def foo(name, /, **kwds):
         return 'name' in kwds
     >>> foo(1, **{'name': 2})
     True

换句话说，仅限位置形参的名称可以在 ‘**kwds’ 中使用而不产生歧义。


File: python.info,  Node: 概括,  Prev: 函数示例,  Up: 特殊参数

2.4.7.8 概括
............

用例将确定要在函数定义中使用的参数:

     def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):

作为指导：

   * 如果你希望形参名称对用户来说不可用，则使用仅限位置形参。 这适用于形
     参名称没有实际意义，以及当你希望强制规定调用时的参数顺序，或是需要
     同时收受一些位置形参和任意关键字形参等情况。

   * 当形参名称有实际意义，以及显式指定形参名称可使函数定义更易理解，或
     者当你想要防止用户过于依赖传入参数的位置时，则使用仅限关键字形参。

   * 对于 API 来说，使用仅限位置形参可以防止形参名称在未来被修改时造成破
     坏性的 API 变动。


File: python.info,  Node: 任意的参数列表,  Next: 解包参数列表,  Prev: 特殊参数,  Up: 函数定义的更多形式

2.4.7.9 任意的参数列表
......................

最后，最不常用的选项是可以使用任意数量的参数调用函数。这些参数会被包含在
一个元组里（参见 *note 元组和序列: 125c. ）。在可变数量的参数之前，可能
会出现零个或多个普通参数。:

     def write_multiple_items(file, separator, *args):
         file.write(separator.join(args))

一般来说，这些 ‘可变参数’ 将在形式参数列表的末尾，因为它们收集传递给函数
的所有剩余输入参数。出现在 ‘*args’ 参数之后的任何形式参数都是 ‘仅限关键
字参数’，也就是说它们只能作为关键字参数而不能是位置参数。:

     >>> def concat(*args, sep="/"):
     ...     return sep.join(args)
     ...
     >>> concat("earth", "mars", "venus")
     'earth/mars/venus'
     >>> concat("earth", "mars", "venus", sep=".")
     'earth.mars.venus'


File: python.info,  Node: 解包参数列表,  Next: Lambda 表达式,  Prev: 任意的参数列表,  Up: 函数定义的更多形式

2.4.7.10 解包参数列表
.....................

当参数已经在列表或元组中但要为需要单独位置参数的函数调用解包时，会发生相
反的情况。例如，内置的 *note range(): 9c6. 函数需要单独的 `start' 和
`stop' 参数。如果它们不能单独使用，可以使用 ‘*’ 操作符 来编写函数调用以
便从列表或元组中解包参数:

     >>> list(range(3, 6))            # normal call with separate arguments
     [3, 4, 5]
     >>> args = [3, 6]
     >>> list(range(*args))            # call with arguments unpacked from a list
     [3, 4, 5]

同样的方式，字典可使用 ‘**’ 操作符 来提供关键字参数:

     >>> def parrot(voltage, state='a stiff', action='voom'):
     ...     print("-- This parrot wouldn't", action, end=' ')
     ...     print("if you put", voltage, "volts through it.", end=' ')
     ...     print("E's", state, "!")
     ...
     >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
     >>> parrot(**d)
     -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !


File: python.info,  Node: Lambda 表达式,  Next: 文档字符串,  Prev: 解包参数列表,  Up: 函数定义的更多形式

2.4.7.11 Lambda 表达式
......................

可以用 *note lambda: c37. 关键字来创建一个小的匿名函数。这个函数返回两个
参数的和： ‘lambda a, b: a+b’ 。Lambda函数可以在需要函数对象的任何地方使
用。它们在语法上限于单个表达式。从语义上来说，它们只是正常函数定义的语法
糖。与嵌套函数定义一样，lambda函数可以引用所包含域的变量:

     >>> def make_incrementor(n):
     ...     return lambda x: x + n
     ...
     >>> f = make_incrementor(42)
     >>> f(0)
     42
     >>> f(1)
     43

上面的例子使用一个lambda表达式来返回一个函数。另一个用法是传递一个小函数
作为参数:

     >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
     >>> pairs.sort(key=lambda pair: pair[1])
     >>> pairs
     [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]


File: python.info,  Node: 文档字符串,  Next: 函数标注,  Prev: Lambda 表达式,  Up: 函数定义的更多形式

2.4.7.12 文档字符串
...................

以下是有关文档字符串的内容和格式的一些约定。

第一行应该是对象目的的简要概述。为简洁起见，它不应显式声明对象的名称或类
型，因为这些可通过其他方式获得（除非名称恰好是描述函数操作的动词）。这一
行应以大写字母开头，以句点结尾。

如果文档字符串中有更多行，则第二行应为空白，从而在视觉上将摘要与其余描述
分开。后面几行应该是一个或多个段落，描述对象的调用约定，它的副作用等。

Python 解析器不会从 Python 中删除多行字符串文字的缩进，因此处理文档的工
具必须在需要时删除缩进。 这是使用以下约定完成的。 文档字符串第一行 `之后
' 的第一个非空行确定整个文档字符串的缩进量。（我们不能使用第一行，因为它
通常与字符串的开头引号相邻，因此它的缩进在字符串文字中不明显。）然后从字
符串的所有行的开头剥离与该缩进 "等效" 的空格。 缩进更少的行不应该出现，
但是如果它们出现，则应该剥离它们的所有前导空格。 应在转化制表符为空格后
测试空格的等效性（通常转化为8个空格）。

下面是一个多行文档字符串的例子:

     >>> def my_function():
     ...     """Do nothing, but document it.
     ...
     ...     No, really, it doesn't do anything.
     ...     """
     ...     pass
     ...
     >>> print(my_function.__doc__)
     Do nothing, but document it.

         No, really, it doesn't do anything.


File: python.info,  Node: 函数标注,  Prev: 文档字符串,  Up: 函数定义的更多形式

2.4.7.13 函数标注
.................

*note 函数标注: 126c. 是关于用户自定义函数中使用的类型的完全可选元数据信
息（有关详情请参阅 PEP 3107(1) 和 PEP 484(2) ）。

*note 标注: 126d. 以字典的形式存放在函数的 ‘__annotations__’ 属性中，并
且不会影响函数的任何其他部分。 形参标注的定义方式是在形参名后加冒号，后
面跟一个表达式，该表达式会被求值为标注的值。 返回值标注的定义方式是加组
合符号 ‘->’，后面跟一个表达式，该标注位于形参列表和表示 *note def: dc6.
语句结束的冒号之间。 下面的示例有一个必须的参数，一个可选的关键字参数以
及返回值都带有相应的标注:

     >>> def f(ham: str, eggs: str = 'eggs') -> str:
     ...     print("Annotations:", f.__annotations__)
     ...     print("Arguments:", ham, eggs)
     ...     return ham + ' and ' + eggs
     ...
     >>> f('spam')
     Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
     Arguments: spam eggs
     'spam and eggs'

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3107

   (2) https://www.python.org/dev/peps/pep-0484


File: python.info,  Node: 小插曲：编码风格,  Prev: 函数定义的更多形式,  Up: 其他流程控制工具

2.4.8 小插曲：编码风格
----------------------

现在你将要写更长，更复杂的 Python 代码，是时候讨论一下 `代码风格' 了。 大
多数语言都能以不同的风格被编写（或更准确地说，被格式化）；有些比其他的更
具有可读性。 能让其他人轻松阅读你的代码总是一个好主意，采用一种好的编码
风格对此有很大帮助。

对于Python， PEP 8(1) 已经成为大多数项目所遵循的风格指南；它促进了一种非
常易读且令人赏心悦目的编码风格。每个Python开发人员都应该在某个时候阅读它
；以下是为你提取的最重要的几个要点：

   * 使用4个空格缩进，不要使用制表符。

     4个空格是一个在小缩进（允许更大的嵌套深度）和大缩进（更容易阅读）的
     一种很好的折中方案。制表符会引入混乱，最好不要使用它。

   * 换行，使一行不超过79个字符。

     这有助于使用小型显示器的用户，并且可以在较大的显示器上并排放置多个
     代码文件。

   * 使用空行分隔函数和类，以及函数内的较大的代码块。

   * 如果可能，把注释放到单独的一行。

   * 使用文档字符串。

   * 在运算符前后和逗号后使用空格，但不能直接在括号内使用： ‘a = f(1, 2)
     + g(3, 4)’。

   * 以一致的规则为你的类和函数命名；按照惯例应使用 ‘UpperCamelCase’ 来
     命名类，而以 ‘lowercase_with_underscores’ 来命名函数和方法。 始终应
     使用 ‘self’ 来命名第一个方法参数 (有关类和方法的更多信息请参阅
     *note 初探类: 1270.)。

   * 如果你的代码旨在用于国际环境，请不要使用花哨的编码。Python 默认的
     UTF-8 或者纯 ASCII 在任何情况下都能有最好的表现。

   * 同样，哪怕只有很小的可能，遇到说不同语言的人阅读或维护代码，也不要
     在标识符中使用非ASCII字符。

备注
....

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0008


File: python.info,  Node: 数据结构,  Next: 模块,  Prev: 其他流程控制工具,  Up: Python 教程

2.5 数据结构
============

本章节将详细介绍一些您已经了解的内容，并添加了一些新内容。

* Menu:

* 列表的更多特性::
* del 语句::
* 元组和序列::
* 集合::
* 字典::
* 循环的技巧::
* 深入条件控制::
* 比较序列和其他类型::


File: python.info,  Node: 列表的更多特性,  Next: del 语句,  Up: 数据结构

2.5.1 列表的更多特性
--------------------

列表数据类型还有很多的方法。这里是列表对象方法的清单：

 -- 方法: list.append (x)

     在列表的末尾添加一个元素。相当于 ‘a[len(a):] = [x]’ 。

 -- 方法: list.extend (iterable)

     使用可迭代对象中的所有元素来扩展列表。相当于 ‘a[len(a):] =
     iterable’ 。

 -- 方法: list.insert (i, x)

     在给定的位置插入一个元素。第一个参数是要插入的元素的索引，所以
     ‘a.insert(0, x)’ 插入列表头部， ‘a.insert(len(a), x)’ 等同于
     ‘a.append(x)’ 。

 -- 方法: list.remove (x)

     移除列表中第一个值为 `x' 的元素。如果没有这样的元素，则抛出 *note
     ValueError: 1fc. 异常。

 -- 方法: list.pop ([i])

     删除列表中给定位置的元素并返回它。如果没有给定位置，‘a.pop()’ 将会
     删除并返回列表中的最后一个元素。（ 方法签名中 `i' 两边的方括号表示
     这个参数是可选的，而不是要你输入方括号。你会在 Python 参考库中经常
     看到这种表示方法)。

 -- 方法: list.clear ()

     移除列表中的所有元素。等价于‘‘del a[:]‘‘

 -- 方法: list.index (x[, start[, end]])

     返回列表中第一个值为 `x' 的元素的从零开始的索引。如果没有这样的元素
     将会抛出 *note ValueError: 1fc. 异常。

     可选参数 `start' 和 `end' 是切片符号，用于将搜索限制为列表的特定子
     序列。返回的索引是相对于整个序列的开始计算的，而不是 `start' 参数。

 -- 方法: list.count (x)

     返回元素 `x' 在列表中出现的次数。

 -- 方法: list.sort (*, key=None, reverse=False)

     对列表中的元素进行排序（参数可用于自定义排序，解释请参见 *note
     sorted(): 44c.）。

 -- 方法: list.reverse ()

     翻转列表中的元素。

 -- 方法: list.copy ()

     返回列表的一个浅拷贝，等价于 ‘a[:]’。

多数列表方法示例：

     >>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
     >>> fruits.count('apple')
     2
     >>> fruits.count('tangerine')
     0
     >>> fruits.index('banana')
     3
     >>> fruits.index('banana', 4)  # Find next banana starting a position 4
     6
     >>> fruits.reverse()
     >>> fruits
     ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
     >>> fruits.append('grape')
     >>> fruits
     ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
     >>> fruits.sort()
     >>> fruits
     ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
     >>> fruits.pop()
     'pear'

你可能已经注意到，像 ‘insert’ ，‘remove’ 或者 ‘sort’ 方法，只修改列表，
没有打印出返回值——它们返回默认值 ‘None’ 。(1) 这是Python中所有可变数据结
构的设计原则。

你可能会注意到的另一件事是并非所有数据或可以排序或比较。 例如，‘[None,
'hello', 10]’ 就不可排序，因为整数不能与字符串比较，而 `None' 不能与其他
类型比较。 并且还存在一些没有定义顺序关系的类型。 例如，‘3+4j < 5+7j’ 就
不是一个合法的比较。

* Menu:

* 列表作为栈使用::
* 列表作为队列使用::
* 列表推导式: 列表推导式<2>.
* 嵌套的列表推导式::

   ---------- Footnotes ----------

   (1) (1) 别的语言可能会返回一个可变对象，他们允许方法连续执行，例如
‘d->insert("a")->remove("b")->sort();’。


File: python.info,  Node: 列表作为栈使用,  Next: 列表作为队列使用,  Up: 列表的更多特性

2.5.1.1 列表作为栈使用
......................

列表方法使得列表作为堆栈非常容易，最后一个插入，最先取出（“后进先出”）。
要添加一个元素到堆栈的顶端，使用 ‘append()’ 。要从堆栈顶部取出一个元素，
使用 ‘pop()’ ，不用指定索引。例如

     >>> stack = [3, 4, 5]
     >>> stack.append(6)
     >>> stack.append(7)
     >>> stack
     [3, 4, 5, 6, 7]
     >>> stack.pop()
     7
     >>> stack
     [3, 4, 5, 6]
     >>> stack.pop()
     6
     >>> stack.pop()
     5
     >>> stack
     [3, 4]


File: python.info,  Node: 列表作为队列使用,  Next: 列表推导式<2>,  Prev: 列表作为栈使用,  Up: 列表的更多特性

2.5.1.2 列表作为队列使用
........................

列表也可以用作队列，其中先添加的元素被最先取出 (“先进先出”)；然而列表用
作这个目的相当低效。因为在列表的末尾添加和弹出元素非常快，但是在列表的开
头插入或弹出元素却很慢 (因为所有的其他元素都必须移动一位)。

若要实现一个队列，可使用 *note collections.deque: 539.，它被设计成可以快
速地从两端添加或弹出元素。例如

     >>> from collections import deque
     >>> queue = deque(["Eric", "John", "Michael"])
     >>> queue.append("Terry")           # Terry arrives
     >>> queue.append("Graham")          # Graham arrives
     >>> queue.popleft()                 # The first to arrive now leaves
     'Eric'
     >>> queue.popleft()                 # The second to arrive now leaves
     'John'
     >>> queue                           # Remaining queue in order of arrival
     deque(['Michael', 'Terry', 'Graham'])


File: python.info,  Node: 列表推导式<2>,  Next: 嵌套的列表推导式,  Prev: 列表作为队列使用,  Up: 列表的更多特性

2.5.1.3 列表推导式
..................

列表推导式提供了一个更简单的创建列表的方法。常见的用法是把某种操作应用于
序列或可迭代对象的每个元素上，然后使用其结果来创建列表，或者通过满足某些
特定条件元素来创建子序列。

例如，假设我们想创建一个平方列表，像这样

     >>> squares = []
     >>> for x in range(10):
     ...     squares.append(x**2)
     ...
     >>> squares
     [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

注意，这将创建（或覆盖）一个名为 ‘x’ 的变量，该变量在循环结束后仍然存在
。 下述方法可以无副作用地计算平方列表:

     squares = list(map(lambda x: x**2, range(10)))

或者，等价于

     squares = [x**2 for x in range(10)]

上面这种写法更加简洁易读。

列表推导式的结构是由一对方括号所包含的以下内容：一个表达式，后面跟一个
‘for’ 子句，然后是零个或多个 ‘for’ 或 ‘if’ 子句。 其结果将是一个新列表，
由对表达式依据后面的 ‘for’ 和 ‘if’ 子句的内容进行求值计算而得出。 举例来
说，以下列表推导式会将两个列表中不相等的元素组合起来:

     >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
     [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

而它等价于

     >>> combs = []
     >>> for x in [1,2,3]:
     ...     for y in [3,1,4]:
     ...         if x != y:
     ...             combs.append((x, y))
     ...
     >>> combs
     [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

注意在上面两个代码片段中， *note for: c38. 和 *note if: def. 的顺序是相
同的。

如果表达式是一个元组（例如上面的 ‘(x, y)’），那么就必须加上括号

     >>> vec = [-4, -2, 0, 2, 4]
     >>> # create a new list with the values doubled
     >>> [x*2 for x in vec]
     [-8, -4, 0, 4, 8]
     >>> # filter the list to exclude negative numbers
     >>> [x for x in vec if x >= 0]
     [0, 2, 4]
     >>> # apply a function to all the elements
     >>> [abs(x) for x in vec]
     [4, 2, 0, 2, 4]
     >>> # call a method on each element
     >>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
     >>> [weapon.strip() for weapon in freshfruit]
     ['banana', 'loganberry', 'passion fruit']
     >>> # create a list of 2-tuples like (number, square)
     >>> [(x, x**2) for x in range(6)]
     [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
     >>> # the tuple must be parenthesized, otherwise an error is raised
     >>> [x, x**2 for x in range(6)]
       File "<stdin>", line 1, in <module>
         [x, x**2 for x in range(6)]
                    ^
     SyntaxError: invalid syntax
     >>> # flatten a list using a listcomp with two 'for'
     >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
     >>> [num for elem in vec for num in elem]
     [1, 2, 3, 4, 5, 6, 7, 8, 9]

列表推导式可以使用复杂的表达式和嵌套函数

     >>> from math import pi
     >>> [str(round(pi, i)) for i in range(1, 6)]
     ['3.1', '3.14', '3.142', '3.1416', '3.14159']


File: python.info,  Node: 嵌套的列表推导式,  Prev: 列表推导式<2>,  Up: 列表的更多特性

2.5.1.4 嵌套的列表推导式
........................

列表推导式中的初始表达式可以是任何表达式，包括另一个列表推导式。

考虑下面这个 3x4的矩阵，它由3个长度为4的列表组成

     >>> matrix = [
     ...     [1, 2, 3, 4],
     ...     [5, 6, 7, 8],
     ...     [9, 10, 11, 12],
     ... ]

下面的列表推导式将交换其行和列

     >>> [[row[i] for row in matrix] for i in range(4)]
     [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

如上节所示，嵌套的列表推导式是基于跟随其后的 *note for: c38. 进行求值的
，所以这个例子等价于:

     >>> transposed = []
     >>> for i in range(4):
     ...     transposed.append([row[i] for row in matrix])
     ...
     >>> transposed
     [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

反过来说，也等价于

     >>> transposed = []
     >>> for i in range(4):
     ...     # the following 3 lines implement the nested listcomp
     ...     transposed_row = []
     ...     for row in matrix:
     ...         transposed_row.append(row[i])
     ...     transposed.append(transposed_row)
     ...
     >>> transposed
     [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

实际应用中，你应该会更喜欢使用内置函数去组成复杂的流程语句。 *note
zip(): c3a. 函数将会很好地处理这种情况

     >>> list(zip(*matrix))
     [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

关于本行中星号的详细说明，参见 *note 解包参数列表: 1265.。


File: python.info,  Node: del 语句,  Next: 元组和序列,  Prev: 列表的更多特性,  Up: 数据结构

2.5.2 ‘del’ 语句
----------------

有一种方式可以从列表按照给定的索引而不是值来移除一个元素: 那就是 *note
del: 127e. 语句。 它不同于会返回一个值的 ‘pop()’ 方法。 ‘del’ 语句也可以
用来从列表中移除切片或者清空整个列表（我们之前用过的方式是将一个空列表赋
值给指定的切片）。 例如:

     >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
     >>> del a[0]
     >>> a
     [1, 66.25, 333, 333, 1234.5]
     >>> del a[2:4]
     >>> a
     [1, 66.25, 1234.5]
     >>> del a[:]
     >>> a
     []

*note del: 127e. 也可以删除整个变量

     >>> del a

此后再引用 ‘a’ 时会报错（直到另一个值被赋给它）。我们会在后面了解到
*note del: 127e. 的其他用法。


File: python.info,  Node: 元组和序列,  Next: 集合,  Prev: del 语句,  Up: 数据结构

2.5.3 元组和序列
----------------

我们看到列表和字符串有很多共同特性，例如索引和切片操作。他们是 `序列' 数
据类型（参见 *note 序列类型 — list, tuple, range: 1280.）中的两种。随着
Python 语言的发展，其他的序列类型也会被加入其中。这里介绍另一种标准序列
类型: `元组'。

一个元组由几个被逗号隔开的值组成，例如

     >>> t = 12345, 54321, 'hello!'
     >>> t[0]
     12345
     >>> t
     (12345, 54321, 'hello!')
     >>> # Tuples may be nested:
     ... u = t, (1, 2, 3, 4, 5)
     >>> u
     ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
     >>> # Tuples are immutable:
     ... t[0] = 88888
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: 'tuple' object does not support item assignment
     >>> # but they can contain mutable objects:
     ... v = ([1, 2, 3], [3, 2, 1])
     >>> v
     ([1, 2, 3], [3, 2, 1])

如你所见，元组在输出时总是被圆括号包围的，以便正确表示嵌套元组。输入时圆
括号可有可无，不过经常会是必须的（如果这个元组是一个更大的表达式的一部分
）。给元组中的一个单独的元素赋值是不允许的，当然你可以创建包含可变对象的
元组，例如列表。

虽然元组可能看起来与列表很像，但它们通常是在不同的场景被使用，并且有着不
同的用途。元组是 *note immutable: 1232. ，其序列通常包含不同种类的元素，
并且通过解包（这一节下面会解释）或者索引来访问（如果是 *note
namedtuples: 1b7. 的话甚至还可以通过属性访问）。列表是 *note mutable:
123a. ，并且列表中的元素一般是同种类型的，并且通过迭代访问。

一个特殊的问题是构造包含0个或1个元素的元组：为了适应这种情况，语法有一些
额外的改变。空元组可以直接被一对空圆括号创建，含有一个元素的元组可以通过
在这个元素后添加一个逗号来构建（圆括号里只有一个值的话不够明确）。丑陋，
但是有效。例如

     >>> empty = ()
     >>> singleton = 'hello',    # <-- note trailing comma
     >>> len(empty)
     0
     >>> len(singleton)
     1
     >>> singleton
     ('hello',)

语句 ‘t = 12345, 54321, 'hello!'’ 是 `元组打包' 的一个例子：值 ‘12345’,
‘54321’ 和 ‘'hello!'’ 被打包进元组。其逆操作也是允许的

     >>> x, y, z = t

这被称为 `序列解包' 也是很恰当的，因为解包操作的等号右侧可以是任何序列。
序列解包要求等号左侧的变量数与右侧序列里所含的元素数相同。注意多重赋值其
实也只是元组打包和序列解包的组合。


File: python.info,  Node: 集合,  Next: 字典,  Prev: 元组和序列,  Up: 数据结构

2.5.4 集合
----------

Python也包含有 `集合' 类型。集合是由不重复元素组成的无序的集。它的基本用
法包括成员检测和消除重复元素。集合对象也支持像 联合，交集，差集，对称差
分等数学运算。

花括号或 *note set(): b77. 函数可以用来创建集合。注意：要创建一个空集合
你只能用 ‘set()’ 而不能用 ‘{}’，因为后者是创建一个空字典，这种数据结构我
们会在下一节进行讨论。

以下是一些简单的示例

     >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
     >>> print(basket)                      # show that duplicates have been removed
     {'orange', 'banana', 'pear', 'apple'}
     >>> 'orange' in basket                 # fast membership testing
     True
     >>> 'crabgrass' in basket
     False

     >>> # Demonstrate set operations on unique letters from two words
     ...
     >>> a = set('abracadabra')
     >>> b = set('alacazam')
     >>> a                                  # unique letters in a
     {'a', 'r', 'b', 'c', 'd'}
     >>> a - b                              # letters in a but not in b
     {'r', 'd', 'b'}
     >>> a | b                              # letters in a or b or both
     {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
     >>> a & b                              # letters in both a and b
     {'a', 'c'}
     >>> a ^ b                              # letters in a or b but not both
     {'r', 'd', 'b', 'm', 'z', 'l'}

类似于 *note 列表推导式: 127a.，集合也支持推导式形式

     >>> a = {x for x in 'abracadabra' if x not in 'abc'}
     >>> a
     {'r', 'd'}


File: python.info,  Node: 字典,  Next: 循环的技巧,  Prev: 集合,  Up: 数据结构

2.5.5 字典
----------

另一个非常有用的 Python 內置数据类型是 `字典' (参见 *note 映射类型 —
dict: 305.)。字典在其他语言里可能会被叫做 `联合内存' 或 `联合数组'。与以
连续整数为索引的序列不同，字典是以 `关键字' 为索引的，关键字可以是任意不
可变类型，通常是字符串或数字。如果一个元组只包含字符串、数字或元组，那么
这个元组也可以用作关键字。但如果元组直接或间接地包含了可变对象，那么它就
不能用作关键字。列表不能用作关键字，因为列表可以通过索引、切片或
‘append()’ 和 ‘extend()’ 之类的方法来改变。

理解字典的最好方式，就是将它看做是一个 `键: 值' 对的集合，键必须是唯一的
（在一个字典中）。一对花括号可以创建一个空字典：‘{}’ 。另一种初始化字典
的方式是在一对花括号里放置一些以逗号分隔的键值对，而这也是字典输出的方式
。

字典主要的操作是使用关键字存储和解析值。也可以用 ‘del’ 来删除一个键值对
。如果你使用了一个已经存在的关键字来存储值，那么之前与这个关键字关联的值
就会被遗忘。用一个不存在的键来取值则会报错。

对一个字典执行 ‘list(d)’ 将返回包含该字典中所有键的列表，按插入次序排列
(如需其他排序，则要使用 ‘sorted(d)’)。要检查字典中是否存在一个特定键，可
使用 *note in: 7ac. 关键字。

以下是使用字典的一些简单示例

     >>> tel = {'jack': 4098, 'sape': 4139}
     >>> tel['guido'] = 4127
     >>> tel
     {'jack': 4098, 'sape': 4139, 'guido': 4127}
     >>> tel['jack']
     4098
     >>> del tel['sape']
     >>> tel['irv'] = 4127
     >>> tel
     {'jack': 4098, 'guido': 4127, 'irv': 4127}
     >>> list(tel)
     ['jack', 'guido', 'irv']
     >>> sorted(tel)
     ['guido', 'irv', 'jack']
     >>> 'guido' in tel
     True
     >>> 'jack' not in tel
     False

*note dict(): 1b9. 构造函数可以直接从键值对序列里创建字典。

     >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
     {'sape': 4139, 'guido': 4127, 'jack': 4098}

此外，字典推导式可以从任意的键值表达式中创建字典

     >>> {x: x**2 for x in (2, 4, 6)}
     {2: 4, 4: 16, 6: 36}

当关键字是简单字符串时，有时直接通过关键字参数来指定键值对更方便

     >>> dict(sape=4139, guido=4127, jack=4098)
     {'sape': 4139, 'guido': 4127, 'jack': 4098}


File: python.info,  Node: 循环的技巧,  Next: 深入条件控制,  Prev: 字典,  Up: 数据结构

2.5.6 循环的技巧
----------------

当在字典中循环时，用 ‘items()’ 方法可将关键字和对应的值同时取出

     >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
     >>> for k, v in knights.items():
     ...     print(k, v)
     ...
     gallahad the pure
     robin the brave

当在序列中循环时，用 *note enumerate(): deb. 函数可以将索引位置和其对应
的值同时取出

     >>> for i, v in enumerate(['tic', 'tac', 'toe']):
     ...     print(i, v)
     ...
     0 tic
     1 tac
     2 toe

当同时在两个或更多序列中循环时，可以用 *note zip(): c3a. 函数将其内元素
一一匹配。

     >>> questions = ['name', 'quest', 'favorite color']
     >>> answers = ['lancelot', 'the holy grail', 'blue']
     >>> for q, a in zip(questions, answers):
     ...     print('What is your {0}?  It is {1}.'.format(q, a))
     ...
     What is your name?  It is lancelot.
     What is your quest?  It is the holy grail.
     What is your favorite color?  It is blue.

如果要逆向循环一个序列，可以先正向定位序列，然后调用 *note reversed():
18f. 函数

     >>> for i in reversed(range(1, 10, 2)):
     ...     print(i)
     ...
     9
     7
     5
     3
     1

如果要按某个指定顺序循环一个序列，可以用 *note sorted(): 44c. 函数，它可
以在不改动原序列的基础上返回一个新的排好序的序列

     >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
     >>> for f in sorted(set(basket)):
     ...     print(f)
     ...
     apple
     banana
     orange
     pear

有时可能会想在循环时修改列表内容，一般来说改为创建一个新列表是比较简单且
安全的

     >>> import math
     >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
     >>> filtered_data = []
     >>> for value in raw_data:
     ...     if not math.isnan(value):
     ...         filtered_data.append(value)
     ...
     >>> filtered_data
     [56.2, 51.7, 55.3, 52.5, 47.8]


File: python.info,  Node: 深入条件控制,  Next: 比较序列和其他类型,  Prev: 循环的技巧,  Up: 数据结构

2.5.7 深入条件控制
------------------

‘while’ 和 ‘if’ 条件句中可以使用任意操作，而不仅仅是比较操作。

比较操作符 ‘in’ 和 ‘not in’ 校验一个值是否在（或不在）一个序列里。操作符
‘is’ 和 ‘is not’ 比较两个对象是不是同一个对象，这只对像列表这样的可变对
象比较重要。所有的比较操作符都有相同的优先级，且这个优先级比数值运算符低
。

比较操作可以传递。例如 ‘a < b == c’ 会校验是否 ‘a’ 小于 ‘b’ 并且 ‘b’ 等
于 ‘c’。

比较操作可以通过布尔运算符 ‘and’ 和 ‘or’ 来组合，并且比较操作（或其他任
何布尔运算）的结果都可以用 ‘not’ 来取反。这些操作符的优先级低于比较操作
符；在它们之中，‘not’ 优先级最高， ‘or’ 优先级最低，因此 ‘A and not B or
C’ 等价于 ‘(A and (not B)) or C’。和之前一样，你也可以在这种式子里使用圆
括号。

布尔运算符 ‘and’ 和 ‘or’ 也被称为 `短路' 运算符：它们的参数从左至右解析
，一旦可以确定结果解析就会停止。例如，如果 ‘A’ 和 ‘C’ 为真而 ‘B’ 为假，
那么 ‘A and B and C’ 不会解析 ‘C’。当用作普通值而非布尔值时，短路操作符
的返回值通常是最后一个变量。

也可以把比较操作或者逻辑表达式的结果赋值给一个变量，例如

     >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
     >>> non_null = string1 or string2 or string3
     >>> non_null
     'Trondheim'

请注意 Python 与 C 不同，在表达式内部赋值必须显式地使用 *note
海象运算符: 1288. ‘:=’ 来完成。 这避免了 C 程序中常见的一种问题：想要在
表达式中写 ‘==’ 时却写成了 ‘=’。


File: python.info,  Node: 比较序列和其他类型,  Prev: 深入条件控制,  Up: 数据结构

2.5.8 比较序列和其他类型
------------------------

序列对象通常可以与相同序列类型的其他对象比较。 这种比较使用 `字典式' 顺
序：首先比较开头的两个对应元素，如果两者不相等则比较结果就由此确定；如果
两者相等则比较之后的两个元素，以此类推，直到有一个序列被耗尽。 如果要比
较的两个元素本身又是相同类型的序列，则会递归地执行字典式顺序比较。 如果
两个序列中所有的对应元素都相等，则两个序列也将被视为相等。 如果一个序列
是另一个的初始子序列，则较短的序列就被视为较小（较少）。 对于字符串来说
，字典式顺序是使用 Unicode 码位序号对单个字符排序。 下面是一些相同类型序
列之间比较的例子:

     (1, 2, 3)              < (1, 2, 4)
     [1, 2, 3]              < [1, 2, 4]
     'ABC' < 'C' < 'Pascal' < 'Python'
     (1, 2, 3, 4)           < (1, 2, 4)
     (1, 2)                 < (1, 2, -1)
     (1, 2, 3)             == (1.0, 2.0, 3.0)
     (1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)

注意对不同类型对象来说，只要待比较对象提供了合适的比较方法，就可以使用
‘<’ 和 ‘>’ 来比较。例如，混合数值类型是通过他们的数值进行比较的，所以 0
等于 0.0，等等。否则，解释器将抛出一个 *note TypeError: 193. 异常，而不
是随便给出一个结果。

备注
....


File: python.info,  Node: 模块,  Next: 输入输出,  Prev: 数据结构,  Up: Python 教程

2.6 模块
========

如果你从Python解释器退出并再次进入，之前的定义（函数和变量）都会丢失。因
此，如果你想编写一个稍长些的程序，最好使用文本编辑器为解释器准备输入并将
该文件作为输入运行。这被称作编写 `脚本' 。随着程序变得越来越长，你或许会
想把它拆分成几个文件，以方便维护。你亦或想在不同的程序中使用一个便捷的函
数， 而不必把这个函数复制到每一个程序中去。

为支持这些，Python有一种方法可以把定义放在一个文件里，并在脚本或解释器的
交互式实例中使用它们。这样的文件被称作 `模块' ；模块中的定义可以 `导入'
到其它模块或者 `主' 模块（你在顶级和计算器模式下执行的脚本中可以访问的变
量集合）。

模块是一个包含Python定义和语句的文件。文件名就是模块名后跟文件后缀 ‘.py’
。在一个模块内部，模块名（作为一个字符串）可以通过全局变量 ‘__name__’ 的
值获得。例如，使用你最喜爱的文本编辑器在当前目录下创建一个名为 ‘fibo.py’
的文件， 文件中含有以下内容:

     # Fibonacci numbers module

     def fib(n):    # write Fibonacci series up to n
         a, b = 0, 1
         while a < n:
             print(a, end=' ')
             a, b = b, a+b
         print()

     def fib2(n):   # return Fibonacci series up to n
         result = []
         a, b = 0, 1
         while a < n:
             result.append(a)
             a, b = b, a+b
         return result

现在进入Python解释器，并用以下命令导入该模块:

     >>> import fibo

在当前的符号表中，这并不会直接进入到定义在 ‘fibo’ 函数内的名称；它只是进
入到模块名 ‘fibo’ 中。你可以用模块名访问这些函数:

     >>> fibo.fib(1000)
     0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
     >>> fibo.fib2(100)
     [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
     >>> fibo.__name__
     'fibo'

如果你想经常使用某个函数，你可以把它赋值给一个局部变量:

     >>> fib = fibo.fib
     >>> fib(500)
     0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

* Menu:

* 更多有关模块的信息::
* 标准模块::
* dir() 函数: dir 函数.
* 包::


File: python.info,  Node: 更多有关模块的信息,  Next: 标准模块,  Up: 模块

2.6.1 更多有关模块的信息
------------------------

模块可以包含可执行的语句以及函数定义。这些语句用于初始化模块。它们仅在模
块 `第一次' 在 import 语句中被导入时才执行。 (1) (当文件被当作脚本运行时
，它们也会执行。)

每个模块都有它自己的私有符号表，该表用作模块中定义的所有函数的全局符号表
。因此，模块的作者可以在模块内使用全局变量，而不必担心与用户的全局变量发
生意外冲突。另一方面，如果你知道自己在做什么，则可以用跟访问模块内的函数
的同样标记方法，去访问一个模块的全局变量，‘modname.itemname’。

模块可以导入其它模块。习惯上但不要求把所有 *note import: c25. 语句放在模
块（或脚本）的开头。被导入的模块名存放在调入模块的全局符号表中。

*note import: c25. 语句有一个变体，它可以把名字从一个被调模块内直接导入
到现模块的符号表里。例如:

     >>> from fibo import fib, fib2
     >>> fib(500)
     0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

这并不会把被调模块名引入到局部变量表里（因此在这个例子里，‘fibo’ 是未被
定义的）。

还有一个变体甚至可以导入模块内定义的所有名称:

     >>> from fibo import *
     >>> fib(500)
     0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

这会调入所有非以下划线（‘_’）开头的名称。 在多数情况下，Python程序员都不
会使用这个功能，因为它在解释器中引入了一组未知的名称，而它们很可能会覆盖
一些你已经定义过的东西。

注意通常情况下从一个模块或者包内调入 ‘*’ 的做法是不太被接受的， 因为这通
常会导致代码的可读性很差。不过，在交互式编译器中为了节省打字可以这么用。

如果模块名称之后带有 ‘as’，则跟在 ‘as’ 之后的名称将直接绑定到所导入的模
块。

     >>> import fibo as fib
     >>> fib.fib(500)
     0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

这会和 ‘import fibo’ 方式一样有效地调入模块， 唯一的区别是它以 ‘fib’ 的
名称存在的。

这种方式也可以在用到 *note from: c4d. 的时候使用，并会有类似的效果:

     >>> from fibo import fib as fibonacci
     >>> fibonacci(500)
     0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

     注解: 出于效率的考虑，每个模块在每个解释器会话中只被导入一次。因此
     ，如果你更改了你的模块，则必须重新启动解释器， 或者，如果它只是一个
     要交互式地测试的模块，请使用 *note importlib.reload(): 3a1.，例如
     ‘import importlib; importlib.reload(modulename)’。

* Menu:

* 以脚本的方式执行模块::
* 模块搜索路径::
* “编译过的”Python文件::

   ---------- Footnotes ----------

   (1) (1) 实际上，函数定义也是“被执行”的“语句”；模块级函数定义的执行在
模块的全局符号表中输入该函数名。


File: python.info,  Node: 以脚本的方式执行模块,  Next: 模块搜索路径,  Up: 更多有关模块的信息

2.6.1.1 以脚本的方式执行模块
............................

当你用下面方式运行一个Python模块:

     python fibo.py <arguments>

这项操作将执行模块里的代码，和导入模块一样，但会把 ‘__name__’ 赋值为
‘"__main__"’。 也就是把下列代码添加到模块末尾：

     if __name__ == "__main__":
         import sys
         fib(int(sys.argv[1]))

你既可以把这个文件当作脚本又可当作一个可调入的模块来使用， 因为那段解析
命令行的代码只有在当模块是以“main”文件的方式执行的时候才会运行:

     $ python fibo.py 50
     0 1 1 2 3 5 8 13 21 34

如果模块是被导入的，那些代码是不运行的:

     >>> import fibo
     >>>

这经常用于为模块提供一个方便的用户接口，或用于测试（以脚本的方式运行模块
从而执行一些测试套件）。


File: python.info,  Node: 模块搜索路径,  Next: “编译过的”Python文件,  Prev: 以脚本的方式执行模块,  Up: 更多有关模块的信息

2.6.1.2 模块搜索路径
....................

当一个名为 ‘spam’ 的模块被导入的时候，解释器首先寻找具有该名称的内置模块
。如果没有找到，然后解释器从 *note sys.path: 490. 变量给出的目录列表里寻
找名为 ‘spam.py’ 的文件。*note sys.path: 490. 初始有这些目录地址:

   * 包含输入脚本的目录（或者未指定文件时的当前目录）。

   * *note PYTHONPATH: 95b. （一个包含目录名称的列表，它和shell变量
     ‘PATH’ 有一样的语法）。

   * 取决于安装的默认设置

     注解: 在支持符号链接的文件系统上，包含输入脚本的目录是在追加符号链
     接后才计算出来的。换句话说，包含符号链接的目录并 `没有' 被添加到模
     块的搜索路径上。

在初始化后，Python程序可以更改 *note sys.path: 490.。包含正在运行脚本的
文件目录被放在搜索路径的开头处， 在标准库路径之前。这意味着将加载此目录
里的脚本，而不是标准库中的同名模块。 除非有意更换，否则这是错误。更多信
息请参阅 *note 标准模块: 1294.。


File: python.info,  Node: “编译过的”Python文件,  Prev: 模块搜索路径,  Up: 更多有关模块的信息

2.6.1.3 “编译过的”Python文件
............................

为了加速模块载入，Python在 ‘__pycache__’ 目录里缓存了每个模块的编译后版
本，名称为 ‘module.`version'.pyc’ ，其中名称中的版本字段对编译文件的格式
进行编码； 它一般使用Python版本号。例如，在CPython版本3.3中，spam.py的编
译版本将被缓存为 ‘__pycache__/spam.cpython-33.pyc’。此命名约定允许来自不
同发行版和不同版本的Python的已编译模块共存。

Python根据编译版本检查源的修改日期，以查看它是否已过期并需要重新编译。这
是一个完全自动化的过程。此外，编译的模块与平台无关，因此可以在具有不同体
系结构的系统之间共享相同的库。

Python在两种情况下不会检查缓存。首先，对于从命令行直接载入的模块，它从来
都是重新编译并且不存储编译结果；其次，如果没有源模块，它不会检查缓存。为
了支持无源文件（仅编译）发行版本， 编译模块必须是在源目录下，并且绝对不
能有源模块。

给专业人士的一些小建议:

   * 你可以在Python命令中使用 *note -O: 694. 或者 *note -OO: 695. 开关，
     以减小编译后模块的大小。 ‘-O’ 开关去除断言语句，‘-OO’ 开关同时去除
     断言语句和 __doc__ 字符串。由于有些程序可能依赖于这些，你应当只在清
     楚自己在做什么时才使用这个选项。“优化过的”模块有一个 ‘opt-’ 标签并
     且通常小些。将来的发行版本或许会更改优化的效果。

   * 一个从 ‘.pyc’ 文件读出的程序并不会比它从 ‘.py’ 读出时运行的更快，
     ‘.pyc’ 文件唯一快的地方在于载入速度。

   * *note compileall: 21. 模块可以为一个目录下的所有模块创建.pyc文件。

   * 关于这个过程， PEP 3147(1) 中有更多细节，包括一个决策流程图。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: 标准模块,  Next: dir 函数,  Prev: 更多有关模块的信息,  Up: 模块

2.6.2 标准模块
--------------

Python附带了一个标准模块库，在单独的文档Python库参考（以下称为“库参考”）
中进行了描述。一些模块内置于解释器中；它们提供对不属于语言核心但仍然内置
的操作的访问，以提高效率或提供对系统调用等操作系统原语的访问。这些模块的
集合是一个配置选项，它也取决于底层平台。例如，*note winreg: 12b. 模块只
在Windows操作系统上提供。一个特别值得注意的模块 *note sys: fe.，它被内嵌
到每一个Python解释器中。变量 ‘sys.ps1’ 和 ‘sys.ps2’ 定义用作主要和辅助提
示的字符串:

     >>> import sys
     >>> sys.ps1
     '>>> '
     >>> sys.ps2
     '... '
     >>> sys.ps1 = 'C> '
     C> print('Yuck!')
     Yuck!
     C>

这两个变量只有在编译器是交互模式下才被定义。

‘sys.path’ 变量是一个字符串列表，用于确定解释器的模块搜索路径。该变量被
初始化为从环境变量 *note PYTHONPATH: 95b. 获取的默认路径，或者如果 *note
PYTHONPATH: 95b. 未设置，则从内置默认路径初始化。你可以使用标准列表操作
对其进行修改:

     >>> import sys
     >>> sys.path.append('/ufs/guido/lib/python')


File: python.info,  Node: dir 函数,  Next: 包,  Prev: 标准模块,  Up: 模块

2.6.3 ‘dir()’ 函数
------------------

内置函数 *note dir(): d3b. 用于查找模块定义的名称。 它返回一个排序过的字
符串列表:

     >>> import fibo, sys
     >>> dir(fibo)
     ['__name__', 'fib', 'fib2']
     >>> dir(sys)
     ['__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__',
      '__package__', '__stderr__', '__stdin__', '__stdout__',
      '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe',
      '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv',
      'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder',
      'call_tracing', 'callstats', 'copyright', 'displayhook',
      'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix',
      'executable', 'exit', 'flags', 'float_info', 'float_repr_style',
      'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
      'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',
      'getrefcount', 'getsizeof', 'getswitchinterval', 'gettotalrefcount',
      'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
      'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path',
      'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',
      'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit',
      'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout',
      'thread_info', 'version', 'version_info', 'warnoptions']

如果没有参数，*note dir(): d3b. 会列出你当前定义的名称:

     >>> a = [1, 2, 3, 4, 5]
     >>> import fibo
     >>> fib = fibo.fib
     >>> dir()
     ['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']

注意：它列出所有类型的名称：变量，模块，函数，等等。

*note dir(): d3b. 不会列出内置函数和变量的名称。如果你想要这些，它们的定
义是在标准模块 *note builtins: 13. 中:

     >>> import builtins
     >>> dir(builtins)
     ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
      'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
      'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
      'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
      'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
      'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
      'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
      'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',
      'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
      'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
      'NotImplementedError', 'OSError', 'OverflowError',
      'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
      'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
      'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
      'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',
      'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
      'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
      'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
      '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',
      'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',
      'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
      'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
      'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
      'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
      'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',
      'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',
      'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
      'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',
      'zip']


File: python.info,  Node: 包,  Prev: dir 函数,  Up: 模块

2.6.4 包
--------

包是一种通过用“带点号的模块名”来构造 Python 模块命名空间的方法。 例如，
模块名 ‘A.B’ 表示 ‘A’ 包中名为 ‘B’ 的子模块。正如模块的使用使得不同模块
的作者不必担心彼此的全局变量名称一样，使用加点的模块名可以使得 NumPy 或
Pillow 等多模块软件包的作者不必担心彼此的模块名称一样。

假设你想为声音文件和声音数据的统一处理，设计一个模块集合（一个“包”）。由
于存在很多不同的声音文件格式（通常由它们的扩展名来识别，例如：‘.wav’，
‘.aiff’， ‘.au’），因此为了不同文件格式间的转换，你可能需要创建和维护一
个不断增长的模块集合。 你可能还想对声音数据还做很多不同的处理（例如，混
声，添加回声，使用均衡器功能，创造人工立体声效果）， 因此为了实现这些处
理，你将另外写一个无穷尽的模块流。这是你的包的可能结构（以分层文件系统的
形式表示）：

     sound/                          Top-level package
           __init__.py               Initialize the sound package
           formats/                  Subpackage for file format conversions
                   __init__.py
                   wavread.py
                   wavwrite.py
                   aiffread.py
                   aiffwrite.py
                   auread.py
                   auwrite.py
                   ...
           effects/                  Subpackage for sound effects
                   __init__.py
                   echo.py
                   surround.py
                   reverse.py
                   ...
           filters/                  Subpackage for filters
                   __init__.py
                   equalizer.py
                   vocoder.py
                   karaoke.py
                   ...

当导入这个包时，Python搜索 ‘sys.path’ 里的目录，查找包的子目录。

必须要有 ‘__init__.py’ 文件才能让 Python 将包含该文件的目录当作包。 这样
可以防止具有通常名称例如 ‘string’ 的目录在无意中隐藏稍后在模块搜索路径上
出现的有效模块。 在最简单的情况下，‘__init__.py’ 可以只是一个空文件，但
它也可以执行包的初始化代码或设置 ‘__all__’ 变量，具体将在后文介绍。

包的用户可以从包中导入单个模块，例如:

     import sound.effects.echo

这会加载子模块 ‘sound.effects.echo’ 。但引用它时必须使用它的全名。

     sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

导入子模块的另一种方法是

     from sound.effects import echo

这也会加载子模块 ‘echo’ ，并使其在没有包前缀的情况下可用，因此可以按如下
方式使用:

     echo.echofilter(input, output, delay=0.7, atten=4)

另一种形式是直接导入所需的函数或变量:

     from sound.effects.echo import echofilter

同样，这也会加载子模块 ‘echo’，但这会使其函数 ‘echofilter()’ 直接可用:

     echofilter(input, output, delay=0.7, atten=4)

请注意，当使用 ‘from package import item’ 时，item可以是包的子模块（或子
包），也可以是包中定义的其他名称，如函数，类或变量。 ‘import’ 语句首先测
试是否在包中定义了item；如果没有，它假定它是一个模块并尝试加载它。如果找
不到它，则引发 *note ImportError: 33d. 异常。

相反，当使用 ‘import item.subitem.subsubitem’ 这样的语法时，除了最后一项
之外的每一项都必须是一个包；最后一项可以是模块或包，但不能是前一项中定义
的类或函数或变量。

* Menu:

* 从包中导入 *::
* 子包参考::
* 多个目录中的包::


File: python.info,  Node: 从包中导入 *,  Next: 子包参考,  Up: 包

2.6.4.1 从包中导入 *
....................

当用户写 ‘from sound.effects import *’ 会发生什么？理想情况下，人们希望
这会以某种方式传递给文件系统，找到包中存在哪些子模块，并将它们全部导入。
这可能需要很长时间，导入子模块可能会产生不必要的副作用，这种副作用只有在
显式导入子模块时才会发生。

唯一的解决方案是让包作者提供一个包的显式索引。*note import: c25. 语句使
用下面的规范：如果一个包的 ‘__init__.py’ 代码定义了一个名为 ‘__all__’ 的
列表，它会被视为在遇到 ‘from package import *’ 时应该导入的模块名列表。
在发布该包的新版本时，包作者可以决定是否让此列表保持更新。包作者如果认为
从他们的包中导入 * 的操作没有必要被使用，也可以决定不支持此列表。例如，
文件 ‘sound/effects/__init__.py’ 可以包含以下代码:

     __all__ = ["echo", "surround", "reverse"]

这意味着 ‘from sound.effects import *’ 将导入 ‘sound’ 包的三个命名子模块
。

如果没有定义 ‘__all__’，‘from sound.effects import *’ 语句 `不会' 从包
‘sound.effects’ 中导入所有子模块到当前命名空间；它只确保导入了包
‘sound.effects’ （可能运行任何在 ‘__init__.py’ 中的初始化代码），然后导
入包中定义的任何名称。 这包括 ‘__init__.py’ 定义的任何名称（以及显式加载
的子模块）。它还包括由之前的 *note import: c25. 语句显式加载的包的任何子
模块。思考下面的代码:

     import sound.effects.echo
     import sound.effects.surround
     from sound.effects import *

在这个例子中， ‘echo’ 和 ‘surround’ 模块是在执行 ‘from...import’ 语句时
导入到当前命名空间中的，因为它们定义在 ‘sound.effects’ 包中。（这在定义
了 ‘__all__’ 时也有效。）

虽然某些模块被设计为在使用 ‘import *’ 时只导出遵循某些模式的名称，但在生
产代码中它仍然被认为是不好的做法。

请记住，使用 ‘from package import specific_submodule’ 没有任何问题！ 实
际上，除非导入的模块需要使用来自不同包的同名子模块，否则这是推荐的表示法
。


File: python.info,  Node: 子包参考,  Next: 多个目录中的包,  Prev: 从包中导入 *,  Up: 包

2.6.4.2 子包参考
................

当包被构造成子包时（与示例中的 ‘sound’ 包一样），你可以使用绝对导入来引
用兄弟包的子模块。例如，如果模块 ‘sound.filters.vocoder’ 需要在
‘sound.effects’ 包中使用 ‘echo’ 模块，它可以使用 ‘from sound.effects
import echo’ 。

你还可以使用import语句的 ‘from module import name’ 形式编写相对导入。这
些导入使用前导点来指示相对导入中涉及的当前包和父包。例如，从 ‘surround’
模块，你可以使用:

     from . import echo
     from .. import formats
     from ..filters import equalizer

请注意，相对导入是基于当前模块的名称进行导入的。由于主模块的名称总是
‘"__main__"’ ，因此用作Python应用程序主模块的模块必须始终使用绝对导入。


File: python.info,  Node: 多个目录中的包,  Prev: 子包参考,  Up: 包

2.6.4.3 多个目录中的包
......................

包支持另一个特殊属性， *note __path__: 129f. 。它被初始化为一个列表，其
中包含在执行该文件中的代码之前保存包的文件 ‘__init__.py’ 的目录的名称。
这个变量可以修改；这样做会影响将来对包中包含的模块和子包的搜索。

虽然通常不需要此功能，但它可用于扩展程序包中的模块集。

备注
....


File: python.info,  Node: 输入输出,  Next: 错误和异常,  Prev: 模块,  Up: Python 教程

2.7 输入输出
============

有几种方法可以显示程序的输出；数据可以以人类可读的形式打印出来，或者写入
文件以供将来使用。本章将讨论一些可能性。

* Menu:

* 更漂亮的输出格式::
* 读写文件::


File: python.info,  Node: 更漂亮的输出格式,  Next: 读写文件,  Up: 输入输出

2.7.1 更漂亮的输出格式
----------------------

到目前为止，我们遇到了两种写入值的方法：`表达式语句' 和 *note print():
88f. 函数。（第三种是使用文件对象的 ‘write()’ 方法；标准输出文件可以作为
‘sys.stdout’ 引用。更多相关信息可参考标准库指南。）

通常，你需要更多地控制输出的格式，而不仅仅是打印空格分隔的值。有几种格式
化输出的方法。

   * 要使用 *note 格式化字符串字面值: 12a5. ，请在字符串的开始引号或三引
     号之前加上一个 ‘f’ 或 ‘F’ 。在此字符串中，你可以在 ‘{’ 和 ‘}’ 字符
     之间写可以引用的变量或字面值的 Python 表达式。

          >>> year = 2016
          >>> event = 'Referendum'
          >>> f'Results of the {year} {event}'
          'Results of the 2016 Referendum'

   * 字符串的 *note str.format(): 4e2. 方法需要更多的手动操作。你仍将使
     用 ‘{’ 和 ‘}’ 来标记变量将被替换的位置，并且可以提供详细的格式化指
     令，但你还需要提供要格式化的信息。

          >>> yes_votes = 42_572_654
          >>> no_votes = 43_132_495
          >>> percentage = yes_votes / (yes_votes + no_votes)
          >>> '{:-9} YES votes  {:2.2%}'.format(yes_votes, percentage)
          ' 42572654 YES votes  49.67%'

   * 最后，你可以使用字符串切片和连接操作自己完成所有的字符串处理，以创
     建你可以想象的任何布局。字符串类型有一些方法可以执行将字符串填充到
     给定列宽的有用操作。

当你不需要花哨的输出而只是想快速显示某些变量以进行调试时，可以使用 *note
repr(): 7d5. or *note str(): 339. 函数将任何值转化为字符串。

*note str(): 339. 函数是用于返回人类可读的值的表示，而 *note repr():
7d5. 是用于生成解释器可读的表示（如果没有等效的语法，则会强制执行 *note
SyntaxError: 460.）对于没有人类可读性的表示的对象， *note str(): 339. 将
返回和 *note repr(): 7d5. 一样的值。很多值使用任一函数都具有相同的表示，
比如数字或类似列表和字典的结构。特殊的是字符串有两个不同的表示。

几个例子:

     >>> s = 'Hello, world.'
     >>> str(s)
     'Hello, world.'
     >>> repr(s)
     "'Hello, world.'"
     >>> str(1/7)
     '0.14285714285714285'
     >>> x = 10 * 3.25
     >>> y = 200 * 200
     >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
     >>> print(s)
     The value of x is 32.5, and y is 40000...
     >>> # The repr() of a string adds string quotes and backslashes:
     ... hello = 'hello, world\n'
     >>> hellos = repr(hello)
     >>> print(hellos)
     'hello, world\n'
     >>> # The argument to repr() may be any Python object:
     ... repr((x, y, ('spam', 'eggs')))
     "(32.5, 40000, ('spam', 'eggs'))"

*note string: f7. 模块包含一个 *note Template: 3f3. 类，它提供了另一种将
值替换为字符串的方法，使用类似 ‘$x’ 的占位符并用字典中的值替换它们，但对
格式的控制要少的多。

* Menu:

* 格式化字符串文字::
* 字符串的 format() 方法: 字符串的 format 方法.
* 手动格式化字符串::
* 旧的字符串格式化方法::


File: python.info,  Node: 格式化字符串文字,  Next: 字符串的 format 方法,  Up: 更漂亮的输出格式

2.7.1.1 格式化字符串文字
........................

*note 格式化字符串字面值: 15d. （常简称为 f-字符串）能让你在字符串前加上
‘f’ 和 ‘F’ 并将表达式写成 ‘{expression}’ 来在字符串中包含 Python 表达式
的值。

可选的格式说明符可以跟在表达式后面。这样可以更好地控制值的格式化方式。以
下示例将pi舍入到小数点后三位:

     >>> import math
     >>> print(f'The value of pi is approximately {math.pi:.3f}.')
     The value of pi is approximately 3.142.

在 ‘':'’ 后传递一个整数可以让该字段成为最小字符宽度。这在使列对齐时很有
用。:

     >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
     >>> for name, phone in table.items():
     ...     print(f'{name:10} ==> {phone:10d}')
     ...
     Sjoerd     ==>       4127
     Jack       ==>       4098
     Dcab       ==>       7678

其他的修饰符可用于在格式化之前转化值。 ‘'!a'’ 应用 *note ascii(): d54. ，
‘'!s'’ 应用 *note str(): 339.，还有 ‘'!r'’ 应用 *note repr(): 7d5.:

     >>> animals = 'eels'
     >>> print(f'My hovercraft is full of {animals}.')
     My hovercraft is full of eels.
     >>> print(f'My hovercraft is full of {animals!r}.')
     My hovercraft is full of 'eels'.

有关这些格式规范的参考，请参阅参考指南 *note 格式规格迷你语言: 4e6.。


File: python.info,  Node: 字符串的 format 方法,  Next: 手动格式化字符串,  Prev: 格式化字符串文字,  Up: 更漂亮的输出格式

2.7.1.2 字符串的 format() 方法
..............................

*note str.format(): 4e2. 方法的基本用法如下所示:

     >>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
     We are the knights who say "Ni!"

花括号和其中的字符（称为格式字段）将替换为传递给 *note str.format():
4e2. 方法的对象。花括号中的数字可用来表示传递给 *note str.format(): 4e2.
方法的对象的位置。

     >>> print('{0} and {1}'.format('spam', 'eggs'))
     spam and eggs
     >>> print('{1} and {0}'.format('spam', 'eggs'))
     eggs and spam

如果在 *note str.format(): 4e2. 方法中使用关键字参数，则使用参数的名称引
用它们的值。:

     >>> print('This {food} is {adjective}.'.format(
     ...       food='spam', adjective='absolutely horrible'))
     This spam is absolutely horrible.

位置和关键字参数可以任意组合:

     >>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
                                                            other='Georg'))
     The story of Bill, Manfred, and Georg.

如果你有一个非常长的格式字符串，你不想把它拆开，那么你最好是按名称而不是
按位置引用变量来进行格式化。 这可以通过简单地传递字典并使用方括号 ‘'[]'’
访问键来完成。

     >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
     >>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
     ...       'Dcab: {0[Dcab]:d}'.format(table))
     Jack: 4098; Sjoerd: 4127; Dcab: 8637678

这也可以通过使用 ’**’ 符号将 table 作为关键字参数传递。

     >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
     >>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
     Jack: 4098; Sjoerd: 4127; Dcab: 8637678

这在与内置函数 *note vars(): 1047. 结合使用时非常有用，它会返回包含所有
局部变量的字典。

例如，下面几行代码生成一组整齐的列，其中包含给定的整数和它的平方以及立方
:

     >>> for x in range(1, 11):
     ...     print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
     ...
      1   1    1
      2   4    8
      3   9   27
      4  16   64
      5  25  125
      6  36  216
      7  49  343
      8  64  512
      9  81  729
     10 100 1000

关于使用 *note str.format(): 4e2. 进行字符串格式化的完整概述，请参阅
*note 格式字符串语法: d22. 。


File: python.info,  Node: 手动格式化字符串,  Next: 旧的字符串格式化方法,  Prev: 字符串的 format 方法,  Up: 更漂亮的输出格式

2.7.1.3 手动格式化字符串
........................

这是同一个平方和立方的表，手动格式化的:

     >>> for x in range(1, 11):
     ...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
     ...     # Note use of 'end' on previous line
     ...     print(repr(x*x*x).rjust(4))
     ...
      1   1    1
      2   4    8
      3   9   27
      4  16   64
      5  25  125
      6  36  216
      7  49  343
      8  64  512
      9  81  729
     10 100 1000

（注意每列之间的一个空格是通过使用 *note print(): 88f. 的方式添加的：它
总是在其参数间添加空格。）

字符串对象的 *note str.rjust(): 12aa. 方法通过在左侧填充空格来对给定宽度
的字段中的字符串进行右对齐。类似的方法还有 *note str.ljust(): 12ab. 和
*note str.center(): 12ac. 。这些方法不会写入任何东西，它们只是返回一个新
的字符串，如果输入的字符串太长，它们不会截断字符串，而是原样返回；这虽然
会弄乱你的列布局，但这通常比另一种方法好，后者会在显示值时可能不准确（如
果你真的想截断，你可以添加一个切片操作，例如 ‘x.ljust(n)[:n]’ 。）

还有另外一个方法，*note str.zfill(): 12ad. ，它会在数字字符串的左边填充
零。它能识别正负号:

     >>> '12'.zfill(5)
     '00012'
     >>> '-3.14'.zfill(7)
     '-003.14'
     >>> '3.14159265359'.zfill(5)
     '3.14159265359'


File: python.info,  Node: 旧的字符串格式化方法,  Prev: 手动格式化字符串,  Up: 更漂亮的输出格式

2.7.1.4 旧的字符串格式化方法
............................

% 运算符（求余）也可用于字符串格式化。 给定 ‘'string' % values’，则
‘string’ 中的 ‘%’ 实例会以零个或多个 ‘values’ 元素替换。 此操作通常被称
为字符串插值。 例如:

     >>> import math
     >>> print('The value of pi is approximately %5.3f.' % math.pi)
     The value of pi is approximately 3.142.

可在 *note printf 风格的字符串格式化: 1235. 部分找到更多信息。


File: python.info,  Node: 读写文件,  Prev: 更漂亮的输出格式,  Up: 输入输出

2.7.2 读写文件
--------------

*note open(): 4f8. 返回一个 *note file object: b4a.，最常用的有两个参数
： ‘open(filename, mode)’。

     >>> f = open('workfile', 'w')

第一个参数是包含文件名的字符串。第二个参数是另一个字符串，其中包含一些描
述文件使用方式的字符。`mode' 可以是 ‘'r'’ ，表示文件只能读取，‘'w'’ 表示
只能写入（已存在的同名文件会被删除），还有 ‘'a'’ 表示打开文件以追加内容
；任何写入的数据会自动添加到文件的末尾。‘'r+'’ 表示打开文件进行读写。
`mode' 参数是可选的；省略时默认为 ‘'r'’。

通常文件是以 `text mode' 打开的，这意味着从文件中读取或写入字符串时，都
会以指定的编码方式进行编码。如果未指定编码格式，默认值与平台相关 (参见
*note open(): 4f8.)。在mode 中追加的 ‘'b'’ 则以 `binary mode' 打开文件：
现在数据是以字节对象的形式进行读写的。这个模式应该用于所有不包含文本的文
件。

在文本模式下读取时，默认会把平台特定的行结束符 (Unix 上的 ‘\n’, Windows
上的 ‘\r\n’) 转换为 ‘\n’。在文本模式下写入时，默认会把出现的 ‘\n’ 转换回
平台特定的结束符。这样在幕后修改文件数据对文本文件来说没有问题，但是会破
坏二进制数据例如 ‘JPEG’ 或 ‘EXE’ 文件中的数据。请一定要注意在读写此类文
件时应使用二进制模式。

在处理文件对象时，最好使用 *note with: 6f2. 关键字。 优点是当子句体结束
后文件会正确关闭，即使在某个时刻引发了异常。 而且使用 ‘with’ 相比等效的
*note try: d7a.-*note finally: 183. 代码块要简短得多:

     >>> with open('workfile') as f:
     ...     read_data = f.read()

     >>> # We can check that the file has been automatically closed.
     >>> f.closed
     True

如果你没有使用 *note with: 6f2. 关键字，则你应当调用 ‘f.close()’ 来关闭
文件并立即释放它所使用的任何系统资源。

     警告: 调用 ‘f.write()’ 时未使用 ‘with’ 关键字或未调用 ‘f.close()’
     `可能' 导致 ‘f.write()’ 的参数没有完全写入到磁盘，即使程序是正常退
     出的。

通过 *note with: 6f2. 语句或者调用 ‘f.close()’ 关闭文件对象后，尝试使用
该文件对象将自动失败。:

     >>> f.close()
     >>> f.read()
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     ValueError: I/O operation on closed file.

* Menu:

* 文件对象的方法::
* 使用 json 保存结构化数据::


File: python.info,  Node: 文件对象的方法,  Next: 使用 json 保存结构化数据,  Up: 读写文件

2.7.2.1 文件对象的方法
......................

本节中剩下的例子将假定你已创建名为 ‘f’ 的文件对象。

要读取文件内容，请调用 ‘f.read(size)’，它会读取一些数据并将其作为字符串
（在文本模式下）或字节串对象（在二进制模式下）返回。 `size' 是一个可选的
数值参数。 当 `size' 被省略或者为负数时，将读取并返回整个文件的内容；如
果文件的大小是你的机器内存的两倍就会出现问题。 当取其他值时，将读取并返
回至多 `size' 个字符（在文本模式下）或 `size' 个字节（在二进制模式下）。
如果已到达文件末尾，‘f.read()’ 将返回一个空字符串 (‘''’)。

     >>> f.read()
     'This is the entire file.\n'
     >>> f.read()
     ''

‘f.readline()’ 从文件中读取一行；换行符（‘\n’）留在字符串的末尾，如果文
件不以换行符结尾，则在文件的最后一行省略。这使得返回值明确无误；如果
‘f.readline()’ 返回一个空的字符串，则表示已经到达了文件末尾，而空行使用
‘'\n'’ 表示，该字符串只包含一个换行符。:

     >>> f.readline()
     'This is the first line of the file.\n'
     >>> f.readline()
     'Second line of the file\n'
     >>> f.readline()
     ''

要从文件中读取行，你可以循环遍历文件对象。这是内存高效，快速的，并简化代
码:

     >>> for line in f:
     ...     print(line, end='')
     ...
     This is the first line of the file.
     Second line of the file

如果你想以列表的形式读取文件中的所有行，你也可以使用 ‘list(f)’ 或
‘f.readlines()’。

‘f.write(string)’ 会把 `string' 的内容写入到文件中，并返回写入的字符数。
:

     >>> f.write('This is a test\n')
     15

在写入其他类型的对象之前，需要先把它们转化为字符串（在文本模式下）或者字
节对象（在二进制模式下）:

     >>> value = ('the answer', 42)
     >>> s = str(value)  # convert the tuple to string
     >>> f.write(s)
     18

‘f.tell()’ 返回一个整数，给出文件对象在文件中的当前位置，表示为二进制模
式下时从文件开始的字节数，以及文本模式下的意义不明的数字。

要改变文件对象的位置，请使用 ‘f.seek(offset, whence)’。 通过向一个参考点
添加 `offset' 来计算位置；参考点由 `whence' 参数指定。 `whence' 的 0 值
表示从文件开头起算，1 表示使用当前文件位置，2 表示使用文件末尾作为参考点
。 `whence' 如果省略则默认值为 0，即使用文件开头作为参考点。

     >>> f = open('workfile', 'rb+')
     >>> f.write(b'0123456789abcdef')
     16
     >>> f.seek(5)      # Go to the 6th byte in the file
     5
     >>> f.read(1)
     b'5'
     >>> f.seek(-3, 2)  # Go to the 3rd byte before the end
     13
     >>> f.read(1)
     b'd'

在文本文件（那些在模式字符串中没有 ‘b’ 的打开的文件）中，只允许相对于文
件开头搜索（使用 ‘seek(0, 2)’ 搜索到文件末尾是个例外）并且唯一有效的
`offset' 值是那些能从 ‘f.tell()’ 中返回的或者是零。其他 `offset' 值都会
产生未定义的行为。

文件对象有一些额外的方法，例如 ‘isatty()’ 和 ‘truncate()’ ，它们使用频率
较低；有关文件对象的完整指南请参阅库参考。


File: python.info,  Node: 使用 json 保存结构化数据,  Prev: 文件对象的方法,  Up: 读写文件

2.7.2.2 使用 ‘json’ 保存结构化数据
..................................

字符串可以很轻松地写入文件并从文件中读取出来。数字可能会费点劲，因为
‘read()’ 方法只能返回字符串，这些字符串必须传递给类似 *note int(): 185.
的函数，它会接受类似 ‘'123'’ 这样的字符串并返回其数字值 123。当你想保存
诸如嵌套列表和字典这样更复杂的数据类型时，手动解析和序列化会变得复杂。

Python 允许你使用称为 JSON (JavaScript Object Notation)(1) 的流行数据交
换格式，而不是让用户不断的编写和调试代码以将复杂的数据类型保存到文件中。
名为 *note json: a5. 的标准模块可以采用 Python 数据层次结构，并将它们转
化为字符串表示形式；这个过程称为 `serializing' 。从字符串表示中重建数据
称为 `deserializing' 。在序列化和反序列化之间，表示对象的字符串可能已存
储在文件或数据中，或通过网络连接发送到某个远程机器。

     注解: JSON格式通常被现代应用程序用于允许数据交换。许多程序员已经熟
     悉它，这使其成为互操作性的良好选择。

如果你有一个对象 ‘x’ ，你可以用一行简单的代码来查看它的 JSON 字符串表示:

     >>> import json
     >>> json.dumps([1, 'simple', 'list'])
     '[1, "simple", "list"]'

*note dumps(): 60e. 函数的另一个变体叫做 *note dump(): 60d. ，它只是将对
象序列化为 *note text file: 12b5. 。因此，如果 ‘f’ 是一个 *note text
file: 12b5. 对象，我们可以这样做:

     json.dump(x, f)

要再次解码对象，如果 ‘f’ 是一个打开的以供阅读的 *note text file: 12b5. 对
象:

     x = json.load(f)

这种简单的序列化技术可以处理列表和字典，但是在JSON中序列化任意类的实例需
要额外的努力。 *note json: a5. 模块的参考包含对此的解释。

参见
....

*note pickle: cb. - 封存模块

与 *note JSON: 12b4. 不同，`pickle' 是一种允许对任意复杂 Python 对象进行
序列化的协议。因此，它为 Python 所特有，不能用于与其他语言编写的应用程序
通信。默认情况下它也是不安全的：如果数据是由熟练的攻击者精心设计的，则反
序列化来自不受信任来源的 pickle 数据可以执行任意代码。

   ---------- Footnotes ----------

   (1) http://json.org


File: python.info,  Node: 错误和异常,  Next: 类,  Prev: 输入输出,  Up: Python 教程

2.8 错误和异常
==============

到目前为止，我们还没有提到错误消息，但是如果你已经尝试过那些例子，你可能
已经看过了一些错误消息。 目前（至少）有两种可区分的错误：`语法错误' 和
`异常'。

* Menu:

* 语法错误::
* 异常::
* 处理异常::
* 抛出异常::
* 用户自定义异常::
* 定义清理操作::
* 预定义的清理操作::


File: python.info,  Node: 语法错误,  Next: 异常,  Up: 错误和异常

2.8.1 语法错误
--------------

语法错误又称解析错误，可能是你在学习Python 时最容易遇到的错误:

     >>> while True print('Hello world')
       File "<stdin>", line 1
         while True print('Hello world')
                        ^
     SyntaxError: invalid syntax

解析器会输出出现语法错误的那一行，并显示一个“箭头”，指向这行里面检测到的
第一个错误。 错误是由箭头指示的位置 `上面' 的 token 引起的（或者至少是在
这里被检测出的）：在示例中，在 *note print(): 88f. 这个函数中检测到了错
误，因为在它前面少了个冒号 (‘':'’) 。文件名和行号也会被输出，以便输入来
自脚本文件时你能知道去哪检查。


File: python.info,  Node: 异常,  Next: 处理异常,  Prev: 语法错误,  Up: 错误和异常

2.8.2 异常
----------

即使语句或表达式在语法上是正确的，但在尝试执行时，它仍可能会引发错误。 在
执行时检测到的错误被称为 `异常'，异常不一定会导致严重后果：你将很快学会
如何在 Python 程序中处理它们。 但是，大多数异常并不会被程序处理，此时会
显示如下所示的错误信息:

     >>> 10 * (1/0)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     ZeroDivisionError: division by zero
     >>> 4 + spam*3
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     NameError: name 'spam' is not defined
     >>> '2' + 2
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: Can't convert 'int' object to str implicitly

错误信息的最后一行告诉我们程序遇到了什么类型的错误。异常有不同的类型，而
其类型名称将会作为错误信息的一部分中打印出来：上述示例中的异常类型依次是
：*note ZeroDivisionError: 12bd.， *note NameError: d83. 和 *note
TypeError: 193.。作为异常类型打印的字符串是发生的内置异常的名称。对于所
有内置异常都是如此，但对于用户定义的异常则不一定如此（虽然这是一个有用的
规范）。标准的异常类型是内置的标识符（而不是保留关键字）。

这一行的剩下的部分根据异常类型及其原因提供详细信息。

错误信息的前一部分以堆栈回溯的形式显示发生异常时的上下文。通常它包含列出
源代码行的堆栈回溯；但是它不会显示从标准输入中读取的行。

*note 内置异常: 12be. 列出了内置异常和它们的含义。


File: python.info,  Node: 处理异常,  Next: 抛出异常,  Prev: 异常,  Up: 错误和异常

2.8.3 处理异常
--------------

可以编写处理所选异常的程序。请看下面的例子，它会要求用户一直输入，直到输
入的是一个有效的整数，但允许用户中断程序（使用 ‘Control-C’ 或操作系统支
持的其他操作）；请注意用户引起的中断可以通过引发 *note
KeyboardInterrupt: 198. 异常来指示。:

     >>> while True:
     ...     try:
     ...         x = int(input("Please enter a number: "))
     ...         break
     ...     except ValueError:
     ...         print("Oops!  That was no valid number.  Try again...")
     ...

*note try: d7a. 语句的工作原理如下：

   * 首先，执行 `try 子句' （*note try: d7a. 和 *note except: b46. 关键
     字之间的（多行）语句）。

   * 如果没有异常发生，则跳过 `except 子句' 并完成 *note try: d7a. 语句
     的执行。

   * 如果在执行 try 子句时发生了异常，则跳过该子句中剩下的部分。 然后，
     如果异常的类型和 *note except: b46. 关键字后面的异常匹配，则执行
     except 子句，然后继续执行 *note try: d7a. 语句之后的代码。

   * 如果发生的异常和 except 子句中指定的异常不匹配，则将其传递到外部的
     *note try: d7a. 语句中；如果没有找到处理程序，则它是一个 `未处理异
     常'，执行将停止并显示如上所示的消息。

一个 *note try: d7a. 语句可能有多个 except 子句，以指定不同异常的处理程
序。 最多会执行一个处理程序。 处理程序只处理相应的 try 子句中发生的异常
，而不处理同一 ‘try’ 语句内其他处理程序中的异常。 一个 except 子句可以将
多个异常命名为带括号的元组，例如:

     ... except (RuntimeError, TypeError, NameError):
     ...     pass

如果发生的异常和 *note except: b46. 子句中的类是同一个类或者是它的基类，
则异常和 except 子句中的类是兼容的（但反过来则不成立 — 列出派生类的
except 子句与基类不兼容）。 例如，下面的代码将依次打印 B, C, D

     class B(Exception):
         pass

     class C(B):
         pass

     class D(C):
         pass

     for cls in [B, C, D]:
         try:
             raise cls()
         except D:
             print("D")
         except C:
             print("C")
         except B:
             print("B")

请注意如果 except 子句被颠倒（把 ‘except B’ 放到第一个），它将打印 B，
B，B — 即第一个匹配的 except 子句被触发。

最后的 except 子句可以省略异常名，以用作通配符。但请谨慎使用，因为以这种
方式很容易掩盖真正的编程错误！它还可用于打印错误消息，然后重新引发异常（
同样允许调用者处理异常）:

     import sys

     try:
         f = open('myfile.txt')
         s = f.readline()
         i = int(s.strip())
     except OSError as err:
         print("OS error: {0}".format(err))
     except ValueError:
         print("Could not convert data to an integer.")
     except:
         print("Unexpected error:", sys.exc_info()[0])
         raise

*note try: d7a. ...  *note except: b46. 语句有一个可选的 `else 子句'，在
使用时必须放在所有的 except 子句后面。对于在 try 子句不引发异常时必须执
行的代码来说很有用。 例如:

     for arg in sys.argv[1:]:
         try:
             f = open(arg, 'r')
         except OSError:
             print('cannot open', arg)
         else:
             print(arg, 'has', len(f.readlines()), 'lines')
             f.close()

使用 ‘else’ 子句比向 *note try: d7a. 子句添加额外的代码要好，因为它避免
了意外捕获非 ‘try’ ...  ‘except’ 语句保护的代码引发的异常。

发生异常时，它可能具有关联值，也称为异常 `参数' 。参数的存在和类型取决于
异常类型。

except 子句可以在异常名称后面指定一个变量。这个变量和一个异常实例绑定，
它的参数存储在 ‘instance.args’ 中。为了方便起见，异常实例定义了 *note
__str__(): e3f. ，因此可以直接打印参数而无需引用 ‘.args’ 。也可以在抛出
之前首先实例化异常，并根据需要向其添加任何属性。:

     >>> try:
     ...     raise Exception('spam', 'eggs')
     ... except Exception as inst:
     ...     print(type(inst))    # the exception instance
     ...     print(inst.args)     # arguments stored in .args
     ...     print(inst)          # __str__ allows args to be printed directly,
     ...                          # but may be overridden in exception subclasses
     ...     x, y = inst.args     # unpack args
     ...     print('x =', x)
     ...     print('y =', y)
     ...
     <class 'Exception'>
     ('spam', 'eggs')
     ('spam', 'eggs')
     x = spam
     y = eggs

如果异常有参数，则它们将作为未处理异常的消息的最后一部分（’详细信息’）打
印。

异常处理程序不仅处理 try 子句中遇到的异常，还处理 try 子句中调用（即使是
间接地）的函数内部发生的异常。例如:

     >>> def this_fails():
     ...     x = 1/0
     ...
     >>> try:
     ...     this_fails()
     ... except ZeroDivisionError as err:
     ...     print('Handling run-time error:', err)
     ...
     Handling run-time error: division by zero


File: python.info,  Node: 抛出异常,  Next: 用户自定义异常,  Prev: 处理异常,  Up: 错误和异常

2.8.4 抛出异常
--------------

*note raise: c4a. 语句允许程序员强制发生指定的异常。例如:

     >>> raise NameError('HiThere')
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     NameError: HiThere

*note raise: c4a. 唯一的参数就是要抛出的异常。这个参数必须是一个异常实例
或者是一个异常类（派生自 *note Exception: 1aa. 的类）。如果传递的是一个
异常类，它将通过调用没有参数的构造函数来隐式实例化:

     raise ValueError  # shorthand for 'raise ValueError()'

如果你需要确定是否引发了异常但不打算处理它，则可以使用更简单的 *note
raise: c4a. 语句形式重新引发异常

     >>> try:
     ...     raise NameError('HiThere')
     ... except NameError:
     ...     print('An exception flew by!')
     ...     raise
     ...
     An exception flew by!
     Traceback (most recent call last):
       File "<stdin>", line 2, in <module>
     NameError: HiThere


File: python.info,  Node: 用户自定义异常,  Next: 定义清理操作,  Prev: 抛出异常,  Up: 错误和异常

2.8.5 用户自定义异常
--------------------

程序可以通过创建新的异常类来命名它们自己的异常（有关Python 类的更多信息
，请参阅 *note 类: 1255.）。异常通常应该直接或间接地从 *note Exception:
1aa. 类派生。

可以定义异常类，它可以执行任何其他类可以执行的任何操作，但通常保持简单，
只提供一些属性，这些属性允许处理程序为异常提取有关错误的信息。 在创建可
能引发多个不同错误的模块时，通常的做法是为该模块定义的异常创建基类，并为
不同错误条件创建特定异常类的子类:

     class Error(Exception):
         """Base class for exceptions in this module."""
         pass

     class InputError(Error):
         """Exception raised for errors in the input.

         Attributes:
             expression -- input expression in which the error occurred
             message -- explanation of the error
         """

         def __init__(self, expression, message):
             self.expression = expression
             self.message = message

     class TransitionError(Error):
         """Raised when an operation attempts a state transition that's not
         allowed.

         Attributes:
             previous -- state at beginning of transition
             next -- attempted new state
             message -- explanation of why the specific transition is not allowed
         """

         def __init__(self, previous, next, message):
             self.previous = previous
             self.next = next
             self.message = message

大多数异常都定义为名称以“Error”结尾，类似于标准异常的命名。

许多标准模块定义了它们自己的异常，以报告它们定义的函数中可能出现的错误。
有关类的更多信息，请参见 *note 类: 1255. 章节。


File: python.info,  Node: 定义清理操作,  Next: 预定义的清理操作,  Prev: 用户自定义异常,  Up: 错误和异常

2.8.6 定义清理操作
------------------

*note try: d7a. 语句有另一个可选子句，用于定义必须在所有情况下执行的清理
操作。例如:

     >>> try:
     ...     raise KeyboardInterrupt
     ... finally:
     ...     print('Goodbye, world!')
     ...
     Goodbye, world!
     Traceback (most recent call last):
       File "<stdin>", line 2, in <module>
     KeyboardInterrupt

如果存在 *note finally: 183. 子句，则 ‘finally’ 子句将作为 *note try:
d7a. 语句结束前的最后一项任务被执行。 ‘finally’ 子句不论 ‘try’ 语句是否
产生了异常都会被执行。 以下几点讨论了当异常发生时一些更复杂的情况：

   * 如果在执行 ‘try’ 子句期间发生了异常，该异常可由一个 *note except:
     b46. 子句进行处理。 如果异常没有被某个 ‘except’ 子句所处理，则该异
     常会在 ‘finally’ 子句执行之后被重新引发。

   * 异常也可能在 ‘except’ 或 ‘else’ 子句执行期间发生。 同样地，该异常会
     在 ‘finally’ 子句执行之后被重新引发。

   * 如果在执行 ‘try’ 语句时遇到一个 *note break: 2dc, *note continue:
     182. 或 *note return: 191. 语句，则 ‘finally’ 子句将在执行 ‘break’,
     ‘continue’ 或 ‘return’ 语句之前被执行。

   * 如果 ‘finally’ 子句中包含一个 ‘return’ 语句，则返回值将来自
     ‘finally’ 子句的某个 ‘return’ 语句的返回值，而非来自 ‘try’ 子句的
     ‘return’ 语句的返回值。

例如

     >>> def bool_return():
     ...     try:
     ...         return True
     ...     finally:
     ...         return False
     ...
     >>> bool_return()
     False

一个更为复杂的例子:

     >>> def divide(x, y):
     ...     try:
     ...         result = x / y
     ...     except ZeroDivisionError:
     ...         print("division by zero!")
     ...     else:
     ...         print("result is", result)
     ...     finally:
     ...         print("executing finally clause")
     ...
     >>> divide(2, 1)
     result is 2.0
     executing finally clause
     >>> divide(2, 0)
     division by zero!
     executing finally clause
     >>> divide("2", "1")
     executing finally clause
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
       File "<stdin>", line 3, in divide
     TypeError: unsupported operand type(s) for /: 'str' and 'str'

正如你所看到的，*note finally: 183. 子句在任何情况下都会被执行。 两个字
符串相除所引发的 *note TypeError: 193. 不会由 *note except: b46. 子句处
理，因此会在 ‘finally’ 子句执行后被重新引发。

在实际应用程序中，*note finally: 183. 子句对于释放外部资源（例如文件或者
网络连接）非常有用，无论是否成功使用资源。


File: python.info,  Node: 预定义的清理操作,  Prev: 定义清理操作,  Up: 错误和异常

2.8.7 预定义的清理操作
----------------------

某些对象定义了在不再需要该对象时要执行的标准清理操作，无论使用该对象的操
作是成功还是失败，清理操作都会被执行。 请查看下面的示例，它尝试打开一个
文件并把其内容打印到屏幕上。:

     for line in open("myfile.txt"):
         print(line, end="")

这个代码的问题在于，它在这部分代码执行完后，会使文件在一段不确定的时间内
处于打开状态。这在简单脚本中不是问题，但对于较大的应用程序来说可能是个问
题。 *note with: 6f2. 语句允许像文件这样的对象能够以一种确保它们得到及时
和正确的清理的方式使用。:

     with open("myfile.txt") as f:
         for line in f:
             print(line, end="")

执行完语句后，即使在处理行时遇到问题，文件 `f' 也始终会被关闭。和文件一
样，提供预定义清理操作的对象将在其文档中指出这一点。


File: python.info,  Node: 类,  Next: 标准库简介,  Prev: 错误和异常,  Up: Python 教程

2.9 类
======

类提供了一种组合数据和功能的方法。 创建一个新类意味着创建一个新的对象 `类
型'，从而允许创建一个该类型的新 `实例' 。 每个类的实例可以拥有保存自己状
态的属性。 一个类的实例也可以有改变自己状态的（定义在类中的）方法。

和其他编程语言相比，Python 用非常少的新语法和语义将类加入到语言中。它是
C++ 和 Modula-3 中类机制的结合。Python 的类提供了面向对象编程的所有标准
特性：类继承机制允许多个基类，派生类可以覆盖它基类的任何方法，一个方法可
以调用基类中相同名称的的方法。对象可以包含任意数量和类型的数据。和模块一
样，类也拥有 Python 天然的动态特性：它们在运行时创建，可以在创建后修改。

在 C++ 术语中，通常类成员（包括数据成员）是 `public' (例外见下文 *note
私有变量: 12ca.)，所有成员函数都是 `virtual'。 与在 Modula-3 中一样，没
有用于从其方法引用对象成员的简写：方法函数使用表示对象的显式第一个参数声
明，该参数由调用隐式提供。 与 Smalltalk 一样，类本身也是对象。 这为导入
和重命名提供了语义。 与 C++ 和 Modula-3 不同，内置类型可以用作用户扩展的
基类。 此外，与 C++ 一样，大多数具有特殊语法（算术运算符，下标等）的内置
运算符都可以为类实例而重新定义。

（由于缺乏关于类的公认术语，我会偶尔使用 Smalltalk 和 C++ 的用辞。 我还
会使用 Modula-3 的术语，因为其面向对象的语义比 C++ 更接近 Python，但我预
计少有读者听说过它。）

* Menu:

* 名称和对象::
* Python 作用域和命名空间::
* 初探类::
* 补充说明::
* 继承::
* 私有变量::
* 杂项说明::
* 迭代器::
* 生成器::
* 生成器表达式::


File: python.info,  Node: 名称和对象,  Next: Python 作用域和命名空间,  Up: 类

2.9.1 名称和对象
----------------

对象具有个性，多个名称（在多个作用域内）可以绑定到同一个对象。 这在其他
语言中称为别名。 乍一看 Python 时通常不会理解这一点，在处理不可变的基本
类型（数字，字符串，元组）时可以安全地忽略它。 但是，别名对涉及可变对象
，如列表，字典和大多数其他类型的 Python 代码的语义可能会产生惊人的影响。
通常这样做是为了使程序受益，因为别名在某些方面表现得像指针。 例如，传递
一个对象的代价很小，因为实现只传递一个指针；如果函数修改了作为参数传递的
对象，调用者将看到更改 — 这就不需要像 Pascal 中那样使用两个不同的参数传
递机制。


File: python.info,  Node: Python 作用域和命名空间,  Next: 初探类,  Prev: 名称和对象,  Up: 类

2.9.2 Python 作用域和命名空间
-----------------------------

在介绍类之前，我首先要告诉你一些 Python 的作用域规则。类定义对命名空间有
一些巧妙的技巧，你需要知道作用域和命名空间如何工作才能完全理解正在发生的
事情。顺便说一下，关于这个主题的知识对任何高级 Python 程序员都很有用。

让我们从一些定义开始。

`namespace' （命名空间）是一个从名字到对象的映射。 大部分命名空间当前都
由 Python 字典实现，但一般情况下基本不会去关注它们（除了要面对性能问题时
），而且也有可能在将来更改。 下面是几个命名空间的例子：存放内置函数的集
合（包含 *note abs(): 12cf. 这样的函数，和内建的异常等）；模块中的全局名
称；函数调用中的局部名称。 从某种意义上说，对象的属性集合也是一种命名空
间的形式。 关于命名空间的重要一点是，不同命名空间中的名称之间绝对没有关
系；例如，两个不同的模块都可以定义一个 ‘maximize’ 函数而不会产生混淆 — 模
块的用户必须在其前面加上模块名称。

顺便说明一下，我把任何跟在一个点号之后的名称都称为 `属性' — 例如，在表达
式 ‘z.real’ 中，‘real’ 是对象 ‘z’ 的一个属性。按严格的说法，对模块中名称
的引用属于属性引用：在表达式 ‘modname.funcname’ 中，‘modname’ 是一个模块
对象而 ‘funcname’ 是它的一个属性。在此情况下在模块的属性和模块中定义的全
局名称之间正好存在一个直观的映射：它们共享相同的命名空间！ (1)

属性可以是只读或者可写的。如果为后者，那么对属性的赋值是可行的。模块属性
是可以写，你可以写出 ‘modname.the_answer = 42’ 。可写的属性同样可以用
*note del: 127e. 语句删除。例如， ‘del modname.the_answer’ 将会从名为
‘modname’ 的对象中移除 ‘the_answer’ 属性。

在不同时刻创建的命名空间拥有不同的生存期。包含内置名称的命名空间是在
Python 解释器启动时创建的，永远不会被删除。模块的全局命名空间在模块定义
被读入时创建；通常，模块命名空间也会持续到解释器退出。被解释器的顶层调用
执行的语句，从一个脚本文件读取或交互式地读取，被认为是 *note __main__:
1. 模块调用的一部分，因此它们拥有自己的全局命名空间。（内置名称实际上也
存在于一个模块中；这个模块称作 *note builtins: 13. 。）

一个函数的本地命名空间在这个函数被调用时创建，并在函数返回或抛出一个不在
函数内部处理的错误时被删除。（事实上，比起描述到底发生了什么，忘掉它更好
。）当然，每次递归调用都会有它自己的本地命名空间。

一个 `作用域' 是一个命名空间可直接访问的 Python 程序的文本区域。 这里的
“可直接访问” 意味着对名称的非限定引用会尝试在命名空间中查找名称。

虽然作用域是静态地确定的，但它们会被动态地使用。 在执行期间的任何时刻，
会有 3 或 4 个命名空间可被直接访问的嵌套作用域:

   * 最先搜索的最内部作用域包含局部名称

   * 从最近的封闭作用域开始搜索的任何封闭函数的作用域包含非局部名称，也
     包括非全局名称

   * 倒数第二个作用域包含当前模块的全局名称

   * 最外面的作用域（最后搜索）是包含内置名称的命名空间

如果一个名称被声明为全局变量，则所有引用和赋值将直接指向包含该模块的全局
名称的中间作用域。 要重新绑定在最内层作用域以外找到的变量，可以使用
*note nonlocal: c47. 语句声明为非本地变量。 如果没有被声明为非本地变量，
这些变量将是只读的（尝试写入这样的变量只会在最内层作用域中创建一个 `新的
' 局部变量，而同名的外部变量保持不变）。

通常，当前局部作用域将（按字面文本）引用当前函数的局部名称。 在函数以外
，局部作用域将引用与全局作用域相一致的命名空间：模块的命名空间。 类定义
将在局部命名空间内再放置另一个命名空间。

重要的是应该意识到作用域是按字面文本来确定的：在一个模块内定义的函数的全
局作用域就是该模块的命名空间，无论该函数从什么地方或以什么别名被调用。 另
一方面，实际的名称搜索是在运行时动态完成的 — 但是，Python 正在朝着“编译
时静态名称解析”的方向发展，因此不要过于依赖动态名称解析！ （事实上，局部
变量已经是被静态确定了。）

Python 的一个特殊规定是这样的 – 如果不存在生效的 *note global: 1254. 或
*note nonlocal: c47. 语句 – 则对名称的赋值总是会进入最内层作用域。 赋值
不会复制数据 — 它们只是将名称绑定到对象。 删除也是如此：语句 ‘del x’ 会
从局部作用域所引用的命名空间中移除对 ‘x’ 的绑定。 事实上，所有引入新名称
的操作都是使用局部作用域：特别地，*note import: c25. 语句和函数定义会在
局部作用域中绑定模块或函数名称。

*note global: 1254. 语句可被用来表明特定变量生存于全局作用域并且应当在其
中被重新绑定；*note nonlocal: c47. 语句表明特定变量生存于外层作用域中并
且应当在其中被重新绑定。

* Menu:

* 作用域和命名空间示例::

   ---------- Footnotes ----------

   (1) (1) 存在一个例外。 模块对象有一个秘密的只读属性 *note __dict__:
504.，它返回用于实现模块命名空间的字典；*note __dict__: 504. 是属性但不
是全局名称。 显然，使用这个将违反命名空间实现的抽象，应当仅被用于事后调
试器之类的场合。


File: python.info,  Node: 作用域和命名空间示例,  Up: Python 作用域和命名空间

2.9.2.1 作用域和命名空间示例
............................

这个例子演示了如何引用不同作用域和名称空间，以及 *note global: 1254. 和
*note nonlocal: c47. 会如何影响变量绑定:

     def scope_test():
         def do_local():
             spam = "local spam"

         def do_nonlocal():
             nonlocal spam
             spam = "nonlocal spam"

         def do_global():
             global spam
             spam = "global spam"

         spam = "test spam"
         do_local()
         print("After local assignment:", spam)
         do_nonlocal()
         print("After nonlocal assignment:", spam)
         do_global()
         print("After global assignment:", spam)

     scope_test()
     print("In global scope:", spam)

示例代码的输出是：

     After local assignment: test spam
     After nonlocal assignment: nonlocal spam
     After global assignment: nonlocal spam
     In global scope: global spam

请注意 `局部' 赋值（这是默认状态）不会改变 `scope_test' 对 `spam' 的绑定
。 *note nonlocal: c47. 赋值会改变 `scope_test' 对 `spam' 的绑定，而
*note global: 1254. 赋值会改变模块层级的绑定。

您还可以在 *note global: 1254. 赋值之前看到之前没有 `spam' 的绑定。


File: python.info,  Node: 初探类,  Next: 补充说明,  Prev: Python 作用域和命名空间,  Up: 类

2.9.3 初探类
------------

类引入了一些新语法，三种新对象类型和一些新语义。

* Menu:

* 类定义语法::
* 类对象::
* 实例对象::
* 方法对象::
* 类和实例变量::


File: python.info,  Node: 类定义语法,  Next: 类对象,  Up: 初探类

2.9.3.1 类定义语法
..................

最简单的类定义看起来像这样:

     class ClassName:
         <statement-1>
         .
         .
         .
         <statement-N>

类定义与函数定义 (*note def: dc6. 语句) 一样必须被执行才会起作用。 （你
可以尝试将类定义放在 *note if: def. 语句的一个分支或是函数的内部。）

在实践中，类定义内的语句通常都是函数定义，但也允许有其他语句，有时还很有
用 — 我们会稍后再回来说明这个问题。 在类内部的函数定义通常具有一种特别形
式的参数列表，这是方法调用的约定规范所指明的 — 这个问题也将在稍后再说明
。

当进入类定义时，将创建一个新的命名空间，并将其用作局部作用域 — 因此，所
有对局部变量的赋值都是在这个新命名空间之内。 特别的，函数定义会绑定到这
里的新函数名称。

当（从结尾处）正常离开类定义时，将创建一个 `类对象'。 这基本上是一个包围
在类定义所创建命名空间内容周围的包装器；我们将在下一节了解有关类对象的更
多信息。 原始的（在进入类定义之前起作用的）局部作用域将重新生效，类对象
将在这里被绑定到类定义头所给出的类名称 (在这个示例中为 ‘ClassName’)。


File: python.info,  Node: 类对象,  Next: 实例对象,  Prev: 类定义语法,  Up: 初探类

2.9.3.2 类对象
..............

类对象支持两种操作：属性引用和实例化。

`属性引用' 使用 Python 中所有属性引用所使用的标准语法: ‘obj.name’。 有效
的属性名称是类对象被创建时存在于类命名空间中的所有名称。 因此，如果类定
义是这样的:

     class MyClass:
         """A simple example class"""
         i = 12345

         def f(self):
             return 'hello world'

那么 ‘MyClass.i’ 和 ‘MyClass.f’ 就是有效的属性引用，将分别返回一个整数和
一个函数对象。 类属性也可以被赋值，因此可以通过赋值来更改 ‘MyClass.i’ 的
值。 ‘__doc__’ 也是一个有效的属性，将返回所属类的文档字符串: ‘"A simple
example class"’。

类的 `实例化' 使用函数表示法。 可以把类对象视为是返回该类的一个新实例的
不带参数的函数。 举例来说（假设使用上述的类）:

     x = MyClass()

创建类的新 `实例' 并将此对象分配给局部变量 ‘x’。

实例化操作（“调用”类对象）会创建一个空对象。 许多类喜欢创建带有特定初始
状态的自定义实例。 为此类定义可能包含一个名为 *note __init__(): d66. 的
特殊方法，就像这样:

     def __init__(self):
         self.data = []

当一个类定义了 *note __init__(): d66. 方法时，类的实例化操作会自动为新创
建的类实例发起调用 *note __init__(): d66.。 因此在这个示例中，可以通过以
下语句获得一个经初始化的新实例:

     x = MyClass()

当然，*note __init__(): d66. 方法还可以有额外参数以实现更高灵活性。 在这
种情况下，提供给类实例化运算符的参数将被传递给 *note __init__(): d66.。
例如，:

     >>> class Complex:
     ...     def __init__(self, realpart, imagpart):
     ...         self.r = realpart
     ...         self.i = imagpart
     ...
     >>> x = Complex(3.0, -4.5)
     >>> x.r, x.i
     (3.0, -4.5)


File: python.info,  Node: 实例对象,  Next: 方法对象,  Prev: 类对象,  Up: 初探类

2.9.3.3 实例对象
................

现在我们能用实例对象做什么？ 实例对象理解的唯一操作是属性引用。 有两种有
效的属性名称：数据属性和方法。

`数据属性' 对应于 Smalltalk 中的“实例变量”，以及 C++ 中的“数据成员”。 数
据属性不需要声明；像局部变量一样，它们将在第一次被赋值时产生。 例如，如
果 ‘x’ 是上面创建的 ‘MyClass’ 的实例，则以下代码段将打印数值 ‘16’，且不
保留任何追踪信息:

     x.counter = 1
     while x.counter < 10:
         x.counter = x.counter * 2
     print(x.counter)
     del x.counter

另一类实例属性引用称为 `方法'。 方法是“从属于”对象的函数。 （在 Python 中
，方法这个术语并不是类实例所特有的：其他对象也可以有方法。 例如，列表对
象具有 append, insert, remove, sort 等方法。 然而，在以下讨论中，我们使
用方法一词将专指类实例对象的方法，除非另外显式地说明。）

实例对象的有效方法名称依赖于其所属的类。 根据定义，一个类中所有是函数对
象的属性都是定义了其实例的相应方法。 因此在我们的示例中，‘x.f’ 是有效的
方法引用，因为 ‘MyClass.f’ 是一个函数，而 ‘x.i’ 不是方法，因为
‘MyClass.i’ 不是一个函数。 但是 ‘x.f’ 与 ‘MyClass.f’ 并不是一回事 — 它是
一个 `方法对象'，不是函数对象。


File: python.info,  Node: 方法对象,  Next: 类和实例变量,  Prev: 实例对象,  Up: 初探类

2.9.3.4 方法对象
................

通常，方法在绑定后立即被调用:

     x.f()

在 ‘MyClass’ 示例中，这将返回字符串 ‘'hello world'’。 但是，立即调用一个
方法并不是必须的: ‘x.f’ 是一个方法对象，它可以被保存起来以后再调用。 例
如:

     xf = x.f
     while True:
         print(xf())

将继续打印 ‘hello world’，直到结束。

当一个方法被调用时到底发生了什么？ 你可能已经注意到上面调用 ‘x.f()’ 时并
没有带参数，虽然 ‘f()’ 的函数定义指定了一个参数。 这个参数发生了什么事？
当不带参数地调用一个需要参数的函数时 Python 肯定会引发异常 — 即使参数实
际未被使用...

实际上，你可能已经猜到了答案：方法的特殊之处就在于实例对象会作为函数的第
一个参数被传入。 在我们的示例中，调用 ‘x.f()’ 其实就相当于
‘MyClass.f(x)’。 总之，调用一个具有 `n' 个参数的方法就相当于调用再多一个
参数的对应函数，这个参数值为方法所属实例对象，位置在其他参数之前。

如果你仍然无法理解方法的运作原理，那么查看实现细节可能会澄清问题。 当一
个实例的非数据属性被引用时，将搜索实例所属的类。 如果被引用的属性名称表
示一个有效的类属性中的函数对象，会通过打包（指向）查找到的实例对象和函数
对象到一个抽象对象的方式来创建方法对象：这个抽象对象就是方法对象。 当附
带参数列表调用方法对象时，将基于实例对象和参数列表构建一个新的参数列表，
并使用这个新参数列表调用相应的函数对象。


File: python.info,  Node: 类和实例变量,  Prev: 方法对象,  Up: 初探类

2.9.3.5 类和实例变量
....................

一般来说，实例变量用于每个实例的唯一数据，而类变量用于类的所有实例共享的
属性和方法:

     class Dog:

         kind = 'canine'         # class variable shared by all instances

         def __init__(self, name):
             self.name = name    # instance variable unique to each instance

     >>> d = Dog('Fido')
     >>> e = Dog('Buddy')
     >>> d.kind                  # shared by all dogs
     'canine'
     >>> e.kind                  # shared by all dogs
     'canine'
     >>> d.name                  # unique to d
     'Fido'
     >>> e.name                  # unique to e
     'Buddy'

正如 *note 名称和对象: 12cc. 中已讨论过的，共享数据可能在涉及 *note
mutable: 123a. 对象例如列表和字典的时候导致令人惊讶的结果。 例如以下代码
中的 `tricks' 列表不应该被用作类变量，因为所有的 `Dog' 实例将只共享一个
单独的列表:

     class Dog:

         tricks = []             # mistaken use of a class variable

         def __init__(self, name):
             self.name = name

         def add_trick(self, trick):
             self.tricks.append(trick)

     >>> d = Dog('Fido')
     >>> e = Dog('Buddy')
     >>> d.add_trick('roll over')
     >>> e.add_trick('play dead')
     >>> d.tricks                # unexpectedly shared by all dogs
     ['roll over', 'play dead']

正确的类设计应该使用实例变量:

     class Dog:

         def __init__(self, name):
             self.name = name
             self.tricks = []    # creates a new empty list for each dog

         def add_trick(self, trick):
             self.tricks.append(trick)

     >>> d = Dog('Fido')
     >>> e = Dog('Buddy')
     >>> d.add_trick('roll over')
     >>> e.add_trick('play dead')
     >>> d.tricks
     ['roll over']
     >>> e.tricks
     ['play dead']


File: python.info,  Node: 补充说明,  Next: 继承,  Prev: 初探类,  Up: 类

2.9.4 补充说明
--------------

如果同样的属性名称同时出现在实例和类中，则属性查找会优先选择实例:

     >>> class Warehouse:
             purpose = 'storage'
             region = 'west'

     >>> w1 = Warehouse()
     >>> print(w1.purpose, w1.region)
     storage west
     >>> w2 = Warehouse()
     >>> w2.region = 'east'
     >>> print(w2.purpose, w2.region)
     storage east

数据属性可以被方法以及一个对象的普通用户（“客户端”）所引用。 换句话说，
类不能用于实现纯抽象数据类型。 实际上，在 Python 中没有任何东西能强制隐
藏数据 — 它是完全基于约定的。 （而在另一方面，用 C 语言编写的 Python 实
现则可以完全隐藏实现细节，并在必要时控制对象的访问；此特性可以通过用 C 编
写 Python 扩展来使用。）

客户端应当谨慎地使用数据属性 — 客户端可能通过直接操作数据属性的方式破坏
由方法所维护的固定变量。 请注意客户端可以向一个实例对象添加他们自己的数
据属性而不会影响方法的可用性，只要保证避免名称冲突 — 再次提醒，在此使用
命名约定可以省去许多令人头痛的麻烦。

在方法内部引用数据属性（或其他方法！）并没有简便方式。 我发现这实际上提
升了方法的可读性：当浏览一个方法代码时，不会存在混淆局部变量和实例变量的
机会。

方法的第一个参数常常被命名为 ‘self’。 这也不过就是一个约定: ‘self’ 这一
名称在 Python 中绝对没有特殊含义。 但是要注意，不遵循此约定会使得你的代
码对其他 Python 程序员来说缺乏可读性，而且也可以想像一个 `类浏览器' 程序
的编写可能会依赖于这样的约定。

任何一个作为类属性的函数都为该类的实例定义了一个相应方法。 函数定义的文
本并非必须包含于类定义之内：将一个函数对象赋值给一个局部变量也是可以的。
例如:

     # Function defined outside the class
     def f1(self, x, y):
         return min(x, x+y)

     class C:
         f = f1

         def g(self):
             return 'hello world'

         h = g

现在 ‘f’, ‘g’ 和 ‘h’ 都是 ‘C’ 类的引用函数对象的属性，因而它们就都是 ‘C’
的实例的方法 — 其中 ‘h’ 完全等同于 ‘g’。 但请注意，本示例的做法通常只会
令程序的阅读者感到迷惑。

方法可以通过使用 ‘self’ 参数的方法属性调用其他方法:

     class Bag:
         def __init__(self):
             self.data = []

         def add(self, x):
             self.data.append(x)

         def addtwice(self, x):
             self.add(x)
             self.add(x)

方法可以通过与普通函数相同的方式引用全局名称。 与方法相关联的全局作用域
就是包含其定义的模块。 （类永远不会被作为全局作用域。） 虽然我们很少会有
充分的理由在方法中使用全局作用域，但全局作用域存在许多合法的使用场景：举
个例子，导入到全局作用域的函数和模块可以被方法所使用，在其中定义的函数和
类也一样。 通常，包含该方法的类本身是在全局作用域中定义的，而在下一节中
我们将会发现为何方法需要引用其所属类的很好的理由。

每个值都是一个对象，因此具有 `类' （也称为 `类型'），并存储为
‘object.__class__’ 。


File: python.info,  Node: 继承,  Next: 私有变量,  Prev: 补充说明,  Up: 类

2.9.5 继承
----------

当然，如果不支持继承，语言特性就不值得称为“类”。派生类定义的语法如下所示
:

     class DerivedClassName(BaseClassName):
         <statement-1>
         .
         .
         .
         <statement-N>

名称 ‘BaseClassName’ 必须定义于包含派生类定义的作用域中。 也允许用其他任
意表达式代替基类名称所在的位置。 这有时也可能会用得上，例如，当基类定义
在另一个模块中的时候:

     class DerivedClassName(modname.BaseClassName):

派生类定义的执行过程与基类相同。 当构造类对象时，基类会被记住。 此信息将
被用来解析属性引用：如果请求的属性在类中找不到，搜索将转往基类中进行查找
。 如果基类本身也派生自其他某个类，则此规则将被递归地应用。

派生类的实例化没有任何特殊之处: ‘DerivedClassName()’ 会创建该类的一个新
实例。 方法引用将按以下方式解析：搜索相应的类属性，如有必要将按基类继承
链逐步向下查找，如果产生了一个函数对象则方法引用就生效。

派生类可能会重载其基类的方法。 因为方法在调用同一对象的其他方法时没有特
殊权限，调用同一基类中定义的另一方法的基类方法最终可能会调用覆盖它的派生
类的方法。 （对 C++ 程序员的提示：Python 中所有的方法实际上都是
‘virtual’ 方法。）

在派生类中的重载方法实际上可能想要扩展而非简单地替换同名的基类方法。 有
一种方式可以简单地直接调用基类方法：即调用
‘BaseClassName.methodname(self, arguments)’。 有时这对客户端来说也是有用
的。 （请注意仅当此基类可在全局作用域中以 ‘BaseClassName’ 的名称被访问时
方可使用此方式。）

Python有两个内置函数可被用于继承机制：

   * 使用 *note isinstance(): 457. 来检查一个实例的类型:
     ‘isinstance(obj, int)’ 仅会在 ‘obj.__class__’ 为 *note int: 185. 或
     某个派生自 *note int: 185. 的类时为 ‘True’。

   * 使用 *note issubclass(): 458. 来检查类的继承关系: ‘issubclass(bool,
     int)’ 为 ‘True’，因为 *note bool: 184. 是 *note int: 185. 的子类。
     但是，‘issubclass(float, int)’ 为 ‘False’，因为 *note float: 188. 不
     是 *note int: 185. 的子类。

* Menu:

* 多重继承::


File: python.info,  Node: 多重继承,  Up: 继承

2.9.5.1 多重继承
................

Python 也支持一种多重继承。 带有多个基类的类定义语句如下所示:

     class DerivedClassName(Base1, Base2, Base3):
         <statement-1>
         .
         .
         .
         <statement-N>

对于多数应用来说，在最简单的情况下，你可以认为搜索从父类所继承属性的操作
是深度优先、从左至右的，当层次结构中存在重叠时不会在同一个类中搜索两次。
因此，如果某一属性在 ‘DerivedClassName’ 中未找到，则会到 ‘Base1’ 中搜索
它，然后（递归地）到 ‘Base1’ 的基类中搜索，如果在那里未找到，再到
‘Base2’ 中搜索，依此类推。

真实情况比这个更复杂一些；方法解析顺序会动态改变以支持对 *note super():
4eb. 的协同调用。 这种方式在某些其他多重继承型语言中被称为后续方法调用，
它比单继承型语言中的 super 调用更强大。

动态改变顺序是有必要的，因为所有多重继承的情况都会显示出一个或更多的菱形
关联（即至少有一个父类可通过多条路径被最底层类所访问）。 例如，所有类都
是继承自 *note object: 2b1.，因此任何多重继承的情况都提供了一条以上的路
径可以通向 *note object: 2b1.。 为了确保基类不会被访问一次以上，动态算法
会用一种特殊方式将搜索顺序线性化， 保留每个类所指定的从左至右的顺序，只
调用每个父类一次，并且保持单调（即一个类可以被子类化而不影响其父类的优先
顺序）。 总而言之，这些特性使得设计具有多重继承的可靠且可扩展的类成为可
能。 要了解更多细节，请参阅
‘https://www.python.org/download/releases/2.3/mro/’。


File: python.info,  Node: 私有变量,  Next: 杂项说明,  Prev: 继承,  Up: 类

2.9.6 私有变量
--------------

那种仅限从一个对象内部访问的“私有”实例变量在 Python 中并不存在。 但是，
大多数 Python 代码都遵循这样一个约定：带有一个下划线的名称 (例如
‘_spam’) 应该被当作是 API 的非公有部分 (无论它是函数、方法或是数据成员
)。 这应当被视为一个实现细节，可能不经通知即加以改变。

由于存在对于类私有成员的有效使用场景（例如避免名称与子类所定义的名称相冲
突），因此存在对此种机制的有限支持，称为 `名称改写'。 任何形式为
‘__spam’ 的标识符（至少带有两个前缀下划线，至多一个后缀下划线）的文本将
被替换为 ‘_classname__spam’，其中 ‘classname’ 为去除了前缀下划线的当前类
名称。 这种改写不考虑标识符的句法位置，只要它出现在类定义内部就会进行。

名称改写有助于让子类重载方法而不破坏类内方法调用。例如:

     class Mapping:
         def __init__(self, iterable):
             self.items_list = []
             self.__update(iterable)

         def update(self, iterable):
             for item in iterable:
                 self.items_list.append(item)

         __update = update   # private copy of original update() method

     class MappingSubclass(Mapping):

         def update(self, keys, values):
             # provides new signature for update()
             # but does not break __init__()
             for item in zip(keys, values):
                 self.items_list.append(item)

上面的示例即使在 ‘MappingSubclass’ 引入了一个 ‘__update’ 标识符的情况下
也不会出错，因为它会在 ‘Mapping’ 类中被替换为 ‘_Mapping__update’ 而在
‘MappingSubclass’ 类中被替换为 ‘_MappingSubclass__update’。

请注意，改写规则的设计主要是为了避免意外冲突；访问或修改被视为私有的变量
仍然是可能的。这在特殊情况下甚至会很有用，例如在调试器中。

请注意传递给 ‘exec()’ 或 ‘eval()’ 的代码不会将发起调用类的类名视作当前类
；这类似于 ‘global’ 语句的效果，因此这种效果仅限于同时经过字节码编译的代
码。 同样的限制也适用于 ‘getattr()’, ‘setattr()’ 和 ‘delattr()’，以及对
于 ‘__dict__’ 的直接引用。


File: python.info,  Node: 杂项说明,  Next: 迭代器,  Prev: 私有变量,  Up: 类

2.9.7 杂项说明
--------------

有时会需要使用类似于 Pascal 的“record”或 C 的“struct”这样的数据类型，将
一些命名数据项捆绑在一起。 这种情况适合定义一个空类:

     class Employee:
         pass

     john = Employee()  # Create an empty employee record

     # Fill the fields of the record
     john.name = 'John Doe'
     john.dept = 'computer lab'
     john.salary = 1000

一段需要特定抽象数据类型的 Python 代码往往可以被传入一个模拟了该数据类型
的方法的类作为替代。 例如，如果你有一个基于文件对象来格式化某些数据的函
数，你可以定义一个带有 ‘read()’ 和 ‘readline()’ 方法从字符串缓存获取数据
的类，并将其作为参数传入。

实例方法对象也具有属性: ‘m.__self__’ 就是带有 ‘m()’ 方法的实例对象，而
‘m.__func__’ 则是该方法所对应的函数对象。


File: python.info,  Node: 迭代器,  Next: 生成器,  Prev: 杂项说明,  Up: 类

2.9.8 迭代器
------------

到目前为止，您可能已经注意到大多数容器对象都可以使用 *note for: c38. 语
句:

     for element in [1, 2, 3]:
         print(element)
     for element in (1, 2, 3):
         print(element)
     for key in {'one':1, 'two':2}:
         print(key)
     for char in "123":
         print(char)
     for line in open("myfile.txt"):
         print(line, end='')

这种访问风格清晰、简洁又方便。 迭代器的使用非常普遍并使得 Python 成为一
个统一的整体。 在幕后，*note for: c38. 语句会在容器对象上调用 *note
iter(): d2f.。 该函数返回一个定义了 *note __next__(): c6c. 方法的迭代器
对象，此方法将逐一访问容器中的元素。 当元素用尽时，*note __next__():
c6c. 将引发 *note StopIteration: 48e. 异常来通知终止 ‘for’ 循环。 你可以
使用 *note next(): 68b. 内置函数来调用 *note __next__(): c6c. 方法；这个
例子显示了它的运作方式:

     >>> s = 'abc'
     >>> it = iter(s)
     >>> it
     <iterator object at 0x00A1DB50>
     >>> next(it)
     'a'
     >>> next(it)
     'b'
     >>> next(it)
     'c'
     >>> next(it)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
         next(it)
     StopIteration

看过迭代器协议的幕后机制，给你的类添加迭代器行为就很容易了。 定义一个
*note __iter__(): 517. 方法来返回一个带有 *note __next__(): c6c. 方法的
对象。 如果类已定义了 ‘__next__()’，则 *note __iter__(): 517. 可以简单地
返回 ‘self’:

     class Reverse:
         """Iterator for looping over a sequence backwards."""
         def __init__(self, data):
             self.data = data
             self.index = len(data)

         def __iter__(self):
             return self

         def __next__(self):
             if self.index == 0:
                 raise StopIteration
             self.index = self.index - 1
             return self.data[self.index]

     >>> rev = Reverse('spam')
     >>> iter(rev)
     <__main__.Reverse object at 0x00A1DB50>
     >>> for char in rev:
     ...     print(char)
     ...
     m
     a
     p
     s


File: python.info,  Node: 生成器,  Next: 生成器表达式,  Prev: 迭代器,  Up: 类

2.9.9 生成器
------------

*note 生成器: 9aa. 是一个用于创建迭代器的简单而强大的工具。 它们的写法类
似于标准的函数，但当它们要返回数据时会使用 *note yield: 190. 语句。 每次
在生成器上调用 *note next(): 68b. 时，它会从上次离开的位置恢复执行（它会
记住上次执行语句时的所有数据值）。 一个显示如何非常容易地创建生成器的示
例如下:

     def reverse(data):
         for index in range(len(data)-1, -1, -1):
             yield data[index]

     >>> for char in reverse('golf'):
     ...     print(char)
     ...
     f
     l
     o
     g

可以用生成器来完成的操作同样可以用前一节所描述的基于类的迭代器来完成。 但
生成器的写法更为紧凑，因为它会自动创建 *note __iter__(): 517. 和 *note
__next__(): 12ea. 方法。

另一个关键特性在于局部变量和执行状态会在每次调用之间自动保存。 这使得该
函数相比使用 ‘self.index’ 和 ‘self.data’ 这种实例变量的方式更易编写且更
为清晰。

除了会自动创建方法和保存程序状态，当生成器终结时，它们还会自动引发 *note
StopIteration: 48e.。 这些特性结合在一起，使得创建迭代器能与编写常规函数
一样容易。


File: python.info,  Node: 生成器表达式,  Prev: 生成器,  Up: 类

2.9.10 生成器表达式
-------------------

某些简单的生成器可以写成简洁的表达式代码，所用语法类似列表推导式，但外层
为圆括号而非方括号。 这种表达式被设计用于生成器将立即被外层函数所使用的
情况。 生成器表达式相比完整的生成器更紧凑但较不灵活，相比等效的列表推导
式则更为节省内存。

示例:

     >>> sum(i*i for i in range(10))                 # sum of squares
     285

     >>> xvec = [10, 20, 30]
     >>> yvec = [7, 5, 3]
     >>> sum(x*y for x,y in zip(xvec, yvec))         # dot product
     260

     >>> unique_words = set(word for line in page  for word in line.split())

     >>> valedictorian = max((student.gpa, student.name) for student in graduates)

     >>> data = 'golf'
     >>> list(data[i] for i in range(len(data)-1, -1, -1))
     ['f', 'l', 'o', 'g']

备注
....


File: python.info,  Node: 标准库简介,  Next: 标准库简介 —— 第二部分,  Prev: 类,  Up: Python 教程

2.10 标准库简介
===============

* Menu:

* 操作系统接口::
* 文件通配符::
* 命令行参数::
* 错误输出重定向和程序终止::
* 字符串模式匹配::
* 数学::
* 互联网访问::
* 日期和时间::
* 数据压缩::
* 性能测量::
* 质量控制::
* 自带电池::


File: python.info,  Node: 操作系统接口,  Next: 文件通配符,  Up: 标准库简介

2.10.1 操作系统接口
-------------------

*note os: c5. 模块提供了许多与操作系统交互的函数:

     >>> import os
     >>> os.getcwd()      # Return the current working directory
     'C:\\Python38'
     >>> os.chdir('/server/accesslogs')   # Change current working directory
     >>> os.system('mkdir today')   # Run the command mkdir in the system shell
     0

一定要使用 ‘import os’ 而不是 ‘from os import *’ 。这将避免内建的 *note
open(): 4f8. 函数被 *note os.open(): 66e. 隐式替换掉，它们的使用方式大不
相同。

内置的 *note dir(): d3b. 和 *note help(): 57b. 函数可用作交互式辅助工具
，用于处理大型模块，如 *note os: c5.:

     >>> import os
     >>> dir(os)
     <returns a list of all module functions>
     >>> help(os)
     <returns an extensive manual page created from the module's docstrings>

对于日常文件和目录管理任务， *note shutil: ea. 模块提供了更易于使用的更
高级别的接口:

     >>> import shutil
     >>> shutil.copyfile('data.db', 'archive.db')
     'archive.db'
     >>> shutil.move('/build/executables', 'installdir')
     'installdir'


File: python.info,  Node: 文件通配符,  Next: 命令行参数,  Prev: 操作系统接口,  Up: 标准库简介

2.10.2 文件通配符
-----------------

*note glob: 8a. 模块提供了一个在目录中使用通配符搜索创建文件列表的函数:

     >>> import glob
     >>> glob.glob('*.py')
     ['primes.py', 'random.py', 'quote.py']


File: python.info,  Node: 命令行参数,  Next: 错误输出重定向和程序终止,  Prev: 文件通配符,  Up: 标准库简介

2.10.3 命令行参数
-----------------

通用实用程序脚本通常需要处理命令行参数。这些参数作为列表存储在 *note
sys: fe. 模块的 `argv' 属性中。例如，以下输出来自在命令行运行 ‘python
demo.py one two three’

     >>> import sys
     >>> print(sys.argv)
     ['demo.py', 'one', 'two', 'three']

*note argparse: 6. 模块提供了一种更复杂的机制来处理命令行参数。 以下脚本
可提取一个或多个文件名，并可选择要显示的行数:

     import argparse

     parser = argparse.ArgumentParser(prog = 'top',
         description = 'Show top lines from each file')
     parser.add_argument('filenames', nargs='+')
     parser.add_argument('-l', '--lines', type=int, default=10)
     args = parser.parse_args()
     print(args)

当在通过 ‘python top.py --lines=5 alpha.txt beta.txt’ 在命令行运行时，该
脚本会将 ‘args.lines’ 设为 ‘5’ 并将 ‘args.filenames’ 设为 ‘['alpha.txt',
'beta.txt']’。


File: python.info,  Node: 错误输出重定向和程序终止,  Next: 字符串模式匹配,  Prev: 命令行参数,  Up: 标准库简介

2.10.4 错误输出重定向和程序终止
-------------------------------

*note sys: fe. 模块还具有 `stdin' ， `stdout' 和 `stderr' 的属性。后者对
于发出警告和错误消息非常有用，即使在 `stdout' 被重定向后也可以看到它们:

     >>> sys.stderr.write('Warning, log file not found starting a new one\n')
     Warning, log file not found starting a new one

终止脚本的最直接方法是使用 ‘sys.exit()’ 。


File: python.info,  Node: 字符串模式匹配,  Next: 数学,  Prev: 错误输出重定向和程序终止,  Up: 标准库简介

2.10.5 字符串模式匹配
---------------------

*note re: de. 模块为高级字符串处理提供正则表达式工具。对于复杂的匹配和操
作，正则表达式提供简洁，优化的解决方案:

     >>> import re
     >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
     ['foot', 'fell', 'fastest']
     >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
     'cat in the hat'

当只需要简单的功能时，首选字符串方法因为它们更容易阅读和调试:

     >>> 'tea for too'.replace('too', 'two')
     'tea for two'


File: python.info,  Node: 数学,  Next: 互联网访问,  Prev: 字符串模式匹配,  Up: 标准库简介

2.10.6 数学
-----------

*note math: b2. 模块提供对浮点数学的底层C库函数的访问:

     >>> import math
     >>> math.cos(math.pi / 4)
     0.70710678118654757
     >>> math.log(1024, 2)
     10.0

*note random: dd. 模块提供了进行随机选择的工具:

     >>> import random
     >>> random.choice(['apple', 'pear', 'banana'])
     'apple'
     >>> random.sample(range(100), 10)   # sampling without replacement
     [30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
     >>> random.random()    # random float
     0.17970987693706186
     >>> random.randrange(6)    # random integer chosen from range(6)
     4

*note statistics: f6. 模块计算数值数据的基本统计属性（均值，中位数，方差
等）:

     >>> import statistics
     >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
     >>> statistics.mean(data)
     1.6071428571428572
     >>> statistics.median(data)
     1.25
     >>> statistics.variance(data)
     1.3720238095238095

SciPy项目 <‘https://scipy.org’> 有许多其他模块用于数值计算。


File: python.info,  Node: 互联网访问,  Next: 日期和时间,  Prev: 数学,  Up: 标准库简介

2.10.7 互联网访问
-----------------

有许多模块可用于访问互联网和处理互联网协议。其中两个最简单的 *note
urllib.request: 121. 用于从URL检索数据，以及 *note smtplib: ee. 用于发送
邮件:

     >>> from urllib.request import urlopen
     >>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
     ...     for line in response:
     ...         line = line.decode('utf-8')  # Decoding the binary data to text.
     ...         if 'EST' in line or 'EDT' in line:  # look for Eastern Time
     ...             print(line)

     <BR>Nov. 25, 09:43:32 PM EST

     >>> import smtplib
     >>> server = smtplib.SMTP('localhost')
     >>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
     ... """To: jcaesar@example.org
     ... From: soothsayer@example.org
     ...
     ... Beware the Ides of March.
     ... """)
     >>> server.quit()

（请注意，第二个示例需要在localhost上运行的邮件服务器。）


File: python.info,  Node: 日期和时间,  Next: 数据压缩,  Prev: 互联网访问,  Up: 标准库简介

2.10.8 日期和时间
-----------------

*note datetime: 31. 模块提供了以简单和复杂的方式操作日期和时间的类。虽然
支持日期和时间算法，但实现的重点是有效的成员提取以进行输出格式化和操作。
该模块还支持可感知时区的对象。

     >>> # dates are easily constructed and formatted
     >>> from datetime import date
     >>> now = date.today()
     >>> now
     datetime.date(2003, 12, 2)
     >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
     '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

     >>> # dates support calendar arithmetic
     >>> birthday = date(1964, 7, 31)
     >>> age = now - birthday
     >>> age.days
     14368


File: python.info,  Node: 数据压缩,  Next: 性能测量,  Prev: 日期和时间,  Up: 标准库简介

2.10.9 数据压缩
---------------

常见的数据存档和压缩格式由模块直接支持，包括：*note zlib: 145, *note
gzip: 8c, *note bz2: 14, *note lzma: ae, *note zipfile: 143. 和 *note
tarfile: 102.。:

     >>> import zlib
     >>> s = b'witch which has which witches wrist watch'
     >>> len(s)
     41
     >>> t = zlib.compress(s)
     >>> len(t)
     37
     >>> zlib.decompress(t)
     b'witch which has which witches wrist watch'
     >>> zlib.crc32(s)
     226805979


File: python.info,  Node: 性能测量,  Next: 质量控制,  Prev: 数据压缩,  Up: 标准库简介

2.10.10 性能测量
----------------

一些Python用户对了解同一问题的不同方法的相对性能产生了浓厚的兴趣。
Python提供了一种可以立即回答这些问题的测量工具。

例如，元组封包和拆包功能相比传统的交换参数可能更具吸引力。*note timeit:
10c. 模块可以快速演示在运行效率方面一定的优势:

     >>> from timeit import Timer
     >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
     0.57535828626024577
     >>> Timer('a,b = b,a', 'a=1; b=2').timeit()
     0.54962537085770791

与 *note timeit: 10c. 的精细粒度级别相反， *note profile: d4. 和 *note
pstats: d5. 模块提供了用于在较大的代码块中识别时间关键部分的工具。


File: python.info,  Node: 质量控制,  Next: 自带电池,  Prev: 性能测量,  Up: 标准库简介

2.10.11 质量控制
----------------

开发高质量软件的一种方法是在开发过程中为每个函数编写测试，并在开发过程中
经常运行这些测试。

*note doctest: 67. 模块提供了一个工具，用于扫描模块并验证程序文档字符串
中嵌入的测试。测试构造就像将典型调用及其结果剪切并粘贴到文档字符串一样简
单。这通过向用户提供示例来改进文档，并且它允许doctest模块确保代码保持对
文档的真实:

     def average(values):
         """Computes the arithmetic mean of a list of numbers.

         >>> print(average([20, 30, 70]))
         40.0
         """
         return sum(values) / len(values)

     import doctest
     doctest.testmod()   # automatically validate the embedded tests

*note unittest: 11c. 模块不像 *note doctest: 67. 模块那样易于使用，但它
允许在一个单独的文件中维护更全面的测试集:

     import unittest

     class TestStatisticalFunctions(unittest.TestCase):

         def test_average(self):
             self.assertEqual(average([20, 30, 70]), 40.0)
             self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
             with self.assertRaises(ZeroDivisionError):
                 average([])
             with self.assertRaises(TypeError):
                 average(20, 30, 70)

     unittest.main()  # Calling from the command line invokes all tests


File: python.info,  Node: 自带电池,  Prev: 质量控制,  Up: 标准库简介

2.10.12 自带电池
----------------

Python有“自带电池”的理念。通过其包的复杂和强大功能可以最好地看到这一点。
例如:

   * *note xmlrpc.client: 140. 和 *note xmlrpc.server: 141. 模块使得实现
     远程过程调用变成了小菜一碟。 尽管存在于模块名称中，但用户不需要直接
     了解或处理 XML。

   * *note email: 69. 包是一个用于管理电子邮件的库，包括MIME和其他符合
     RFC 2822(1) 规范的邮件文档。与 *note smtplib: ee. 和 *note poplib:
     d1. 不同（它们实际上做的是发送和接收消息），电子邮件包提供完整的工
     具集，用于构建或解码复杂的消息结构（包括附件）以及实现互联网编码和
     标头协议。

   * *note json: a5. 包为解析这种流行的数据交换格式提供了强大的支持。
     *note csv: 2a. 模块支持以逗号分隔值格式直接读取和写入文件，这种格式
     通常为数据库和电子表格所支持。 XML 处理由 *note
     xml.etree.ElementTree: 138. ， *note xml.dom: 135. 和 *note
     xml.sax: 13c. 包支持。这些模块和软件包共同大大简化了 Python 应用程
     序和其他工具之间的数据交换。

   * *note sqlite3: f3. 模块是 SQLite 数据库库的包装器，提供了一个可以使
     用稍微非标准的 SQL 语法更新和访问的持久数据库。

   * 国际化由许多模块支持，包括 *note gettext: 89. ， *note locale: aa.
     ，以及 *note codecs: 1c. 包。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2822.html


File: python.info,  Node: 标准库简介 —— 第二部分,  Next: 虚拟环境和包,  Prev: 标准库简介,  Up: Python 教程

2.11 标准库简介 —— 第二部分
===========================

第二部分涵盖了专业编程所需要的更高级的模块。这些模块很少用在小脚本中。

* Menu:

* 格式化输出::
* 模板::
* 使用二进制数据记录格式::
* 多线程: 多线程<2>.
* 日志记录::
* 弱引用::
* 用于操作列表的工具::
* 十进制浮点运算::


File: python.info,  Node: 格式化输出,  Next: 模板,  Up: 标准库简介 —— 第二部分

2.11.1 格式化输出
-----------------

*note reprlib: e0. 模块提供了一个定制化版本的 *note repr(): 7d5. 函数，
用于缩略显示大型或深层嵌套的容器对象:

     >>> import reprlib
     >>> reprlib.repr(set('supercalifragilisticexpialidocious'))
     "{'a', 'c', 'd', 'e', 'f', 'g', ...}"

*note pprint: d3. 模块提供了更加复杂的打印控制，其输出的内置对象和用户自
定义对象能够被解释器直接读取。当输出结果过长而需要折行时，“美化输出机制
”会添加换行符和缩进，以更清楚地展示数据结构:

     >>> import pprint
     >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
     ...     'yellow'], 'blue']]]
     ...
     >>> pprint.pprint(t, width=30)
     [[[['black', 'cyan'],
        'white',
        ['green', 'red']],
       [['magenta', 'yellow'],
        'blue']]]

*note textwrap: 109. 模块能够格式化文本段落，以适应给定的屏幕宽度:

     >>> import textwrap
     >>> doc = """The wrap() method is just like fill() except that it returns
     ... a list of strings instead of one big string with newlines to separate
     ... the wrapped lines."""
     ...
     >>> print(textwrap.fill(doc, width=40))
     The wrap() method is just like fill()
     except that it returns a list of strings
     instead of one big string with newlines
     to separate the wrapped lines.

*note locale: aa. 模块处理与特定地域文化相关的数据格式。locale 模块的
format 函数包含一个 grouping 属性，可直接将数字格式化为带有组分隔符的样
式:

     >>> import locale
     >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
     'English_United States.1252'
     >>> conv = locale.localeconv()          # get a mapping of conventions
     >>> x = 1234567.8
     >>> locale.format("%d", x, grouping=True)
     '1,234,567'
     >>> locale.format_string("%s%.*f", (conv['currency_symbol'],
     ...                      conv['frac_digits'], x), grouping=True)
     '$1,234,567.80'


File: python.info,  Node: 模板,  Next: 使用二进制数据记录格式,  Prev: 格式化输出,  Up: 标准库简介 —— 第二部分

2.11.2 模板
-----------

*note string: f7. 模块包含一个通用的 *note Template: 3f3. 类，具有适用于
最终用户的简化语法。它允许用户在不更改应用逻辑的情况下定制自己的应用。

上述格式化操作是通过占位符实现的，占位符由 ‘$’ 加上合法的 Python 标识符
（只能包含字母、数字和下划线）构成。一旦使用花括号将占位符括起来，就可以
在后面直接跟上更多的字母和数字而无需空格分割。‘$$’ 将被转义成单个字符
‘$’:

     >>> from string import Template
     >>> t = Template('${village}folk send $$10 to $cause.')
     >>> t.substitute(village='Nottingham', cause='the ditch fund')
     'Nottinghamfolk send $10 to the ditch fund.'

如果在字典或关键字参数中未提供某个占位符的值，那么 *note substitute():
130f. 方法将抛出 *note KeyError: 2c8.。对于邮件合并类型的应用，用户提供
的数据有可能是不完整的，此时使用 *note safe_substitute(): 1310. 方法更加
合适 —— 如果数据缺失，它会直接将占位符原样保留。

     >>> t = Template('Return the $item to $owner.')
     >>> d = dict(item='unladen swallow')
     >>> t.substitute(d)
     Traceback (most recent call last):
       ...
     KeyError: 'owner'
     >>> t.safe_substitute(d)
     'Return the unladen swallow to $owner.'

Template 的子类可以自定义分隔符。例如，以下是某个照片浏览器的批量重命名
功能，采用了百分号作为日期、照片序号和照片格式的占位符:

     >>> import time, os.path
     >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
     >>> class BatchRename(Template):
     ...     delimiter = '%'
     >>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format):  ')
     Enter rename style (%d-date %n-seqnum %f-format):  Ashley_%n%f

     >>> t = BatchRename(fmt)
     >>> date = time.strftime('%d%b%y')
     >>> for i, filename in enumerate(photofiles):
     ...     base, ext = os.path.splitext(filename)
     ...     newname = t.substitute(d=date, n=i, f=ext)
     ...     print('{0} --> {1}'.format(filename, newname))

     img_1074.jpg --> Ashley_0.jpg
     img_1076.jpg --> Ashley_1.jpg
     img_1077.jpg --> Ashley_2.jpg

模板的另一个应用是将程序逻辑与多样的格式化输出细节分离开来。这使得对 XML
文件、纯文本报表和 HTML 网络报表使用自定义模板成为可能。


File: python.info,  Node: 使用二进制数据记录格式,  Next: 多线程<2>,  Prev: 模板,  Up: 标准库简介 —— 第二部分

2.11.3 使用二进制数据记录格式
-----------------------------

*note struct: f9. 模块提供了 *note pack(): c13. 和 *note unpack(): 1313.
函数，用于处理不定长度的二进制记录格式。下面的例子展示了在不使用 *note
zipfile: 143. 模块的情况下，如何循环遍历一个 ZIP 文件的所有头信息。Pack
代码 ‘"H"’ 和 ‘"I"’ 分别代表两字节和四字节无符号整数。‘"<"’ 代表它们是标
准尺寸的小端字节序:

     import struct

     with open('myfile.zip', 'rb') as f:
         data = f.read()

     start = 0
     for i in range(3):                      # show the first 3 file headers
         start += 14
         fields = struct.unpack('<IIIHH', data[start:start+16])
         crc32, comp_size, uncomp_size, filenamesize, extra_size = fields

         start += 16
         filename = data[start:start+filenamesize]
         start += filenamesize
         extra = data[start:start+extra_size]
         print(filename, hex(crc32), comp_size, uncomp_size)

         start += extra_size + comp_size     # skip to the next header


File: python.info,  Node: 多线程<2>,  Next: 日志记录,  Prev: 使用二进制数据记录格式,  Up: 标准库简介 —— 第二部分

2.11.4 多线程
-------------

线程是一种对于非顺序依赖的多个任务进行解耦的技术。多线程可以提高应用的响
应效率，当接收用户输入的同时，保持其他任务在后台运行。一个有关的应用场景
是，将 I/O 和计算运行在两个并行的线程中。

以下代码展示了高阶的 *note threading: 10a. 模块如何在后台运行任务，且不
影响主程序的继续运行:

     import threading, zipfile

     class AsyncZip(threading.Thread):
         def __init__(self, infile, outfile):
             threading.Thread.__init__(self)
             self.infile = infile
             self.outfile = outfile

         def run(self):
             f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
             f.write(self.infile)
             f.close()
             print('Finished background zip of:', self.infile)

     background = AsyncZip('mydata.txt', 'myarchive.zip')
     background.start()
     print('The main program continues to run in foreground.')

     background.join()    # Wait for the background task to finish
     print('Main program waited until background was done.')

多线程应用面临的主要挑战是，相互协调的多个线程之间需要共享数据或其他资源
。为此，threading 模块提供了多个同步操作原语，包括线程锁、事件、条件变量
和信号量。

尽管这些工具非常强大，但微小的设计错误却可以导致一些难以复现的问题。因此
，实现多任务协作的首选方法是将所有对资源的请求集中到一个线程中，然后使用
*note queue: db. 模块向该线程供应来自其他线程的请求。 应用程序使用 *note
Queue: d20. 对象进行线程间通信和协调，更易于设计，更易读，更可靠。


File: python.info,  Node: 日志记录,  Next: 弱引用,  Prev: 多线程<2>,  Up: 标准库简介 —— 第二部分

2.11.5 日志记录
---------------

*note logging: ab. 模块提供功能齐全且灵活的日志记录系统。在最简单的情况
下，日志消息被发送到文件或 ‘sys.stderr’

     import logging
     logging.debug('Debugging information')
     logging.info('Informational message')
     logging.warning('Warning:config file %s not found', 'server.conf')
     logging.error('Error occurred')
     logging.critical('Critical error -- shutting down')

这会产生以下输出:

     WARNING:root:Warning:config file server.conf not found
     ERROR:root:Error occurred
     CRITICAL:root:Critical error -- shutting down

默认情况下，informational 和 debugging 消息被压制，输出会发送到标准错误
流。其他输出选项包括将消息转发到电子邮件，数据报，套接字或 HTTP 服务器。
新的过滤器可以根据消息优先级选择不同的路由方式：‘DEBUG’，‘INFO’，
‘WARNING’，‘ERROR’，和 ‘CRITICAL’。

日志系统可以直接从 Python 配置，也可以从用户配置文件加载，以便自定义日志
记录而无需更改应用程序。


File: python.info,  Node: 弱引用,  Next: 用于操作列表的工具,  Prev: 日志记录,  Up: 标准库简介 —— 第二部分

2.11.6 弱引用
-------------

Python 会自动进行内存管理（对大多数对象进行引用计数并使用 *note garbage
collection: ed8. 来清除循环引用）。 当某个对象的最后一个引用被移除后不久
就会释放其所占用的内存。

此方式对大多数应用来说都适用，但偶尔也必须在对象持续被其他对象所使用时跟
踪它们。 不幸的是，跟踪它们将创建一个会令其永久化的引用。 *note weakref:
129. 模块提供的工具可以不必创建引用就能跟踪对象。 当对象不再需要时，它将
自动从一个弱引用表中被移除，并为弱引用对象触发一个回调。 典型应用包括对
创建开销较大的对象进行缓存:

     >>> import weakref, gc
     >>> class A:
     ...     def __init__(self, value):
     ...         self.value = value
     ...     def __repr__(self):
     ...         return str(self.value)
     ...
     >>> a = A(10)                   # create a reference
     >>> d = weakref.WeakValueDictionary()
     >>> d['primary'] = a            # does not create a reference
     >>> d['primary']                # fetch the object if it is still alive
     10
     >>> del a                       # remove the one reference
     >>> gc.collect()                # run garbage collection right away
     0
     >>> d['primary']                # entry was automatically removed
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
         d['primary']                # entry was automatically removed
       File "C:/python38/lib/weakref.py", line 46, in __getitem__
         o = self.data[key]()
     KeyError: 'primary'


File: python.info,  Node: 用于操作列表的工具,  Next: 十进制浮点运算,  Prev: 弱引用,  Up: 标准库简介 —— 第二部分

2.11.7 用于操作列表的工具
-------------------------

许多对于数据结构的需求可以通过内置列表类型来满足。 但是，有时也会需要具
有不同效费比的替代实现。

*note array: 7. 模块提供了一种 *note array(): 459. 对象，它类似于列表，
但只能存储类型一致的数据且存储密集更高。 下面的例子演示了一个以两个字节
为存储单元的无符号二进制数值的数组 (类型码为 ‘"H"’)，而对于普通列表来说
，每个条目存储为标准 Python 的 int 对象通常要占用16 个字节:

     >>> from array import array
     >>> a = array('H', [4000, 10, 700, 22222])
     >>> sum(a)
     26932
     >>> a[1:3]
     array('H', [10, 700])

*note collections: 1e. 模块提供了一种 *note deque(): 539. 对象，它类似于
列表，但从左端添加和弹出的速度较快，而在中间查找的速度较慢。 此种对象适
用于实现队列和广度优先树搜索:

     >>> from collections import deque
     >>> d = deque(["task1", "task2", "task3"])
     >>> d.append("task4")
     >>> print("Handling", d.popleft())
     Handling task1

     unsearched = deque([starting_node])
     def breadth_first_search(unsearched):
         node = unsearched.popleft()
         for m in gen_moves(node):
             if is_goal(m):
                 return m
             unsearched.append(m)

在替代的列表实现以外，标准库也提供了其他工具，例如 *note bisect: 12. 模
块具有用于操作有序列表的函数:

     >>> import bisect
     >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
     >>> bisect.insort(scores, (300, 'ruby'))
     >>> scores
     [(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]

*note heapq: 8e. 模块提供了基于常规列表来实现堆的函数。 最小值的条目总是
保持在位置零。 这对于需要重复访问最小元素而不希望运行完整列表排序的应用
来说非常有用:

     >>> from heapq import heapify, heappop, heappush
     >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
     >>> heapify(data)                      # rearrange the list into heap order
     >>> heappush(data, -5)                 # add a new entry
     >>> [heappop(data) for i in range(3)]  # fetch the three smallest entries
     [-5, 0, 1]


File: python.info,  Node: 十进制浮点运算,  Prev: 用于操作列表的工具,  Up: 标准库简介 —— 第二部分

2.11.8 十进制浮点运算
---------------------

*note decimal: 36. 模块提供了一种 *note Decimal: 189. 数据类型用于十进制
浮点运算。 相比内置的 *note float: 188. 二进制浮点实现，该类特别适用于

   * 财务应用和其他需要精确十进制表示的用途，

   * 控制精度，

   * 控制四舍五入以满足法律或监管要求，

   * 跟踪有效小数位，或

   * 用户期望结果与手工完成的计算相匹配的应用程序。

例如，使用十进制浮点和二进制浮点数计算70美分手机和5％税的总费用，会产生
的不同结果。如果结果四舍五入到最接近的分数差异会更大:

     >>> from decimal import *
     >>> round(Decimal('0.70') * Decimal('1.05'), 2)
     Decimal('0.74')
     >>> round(.70 * 1.05, 2)
     0.73

*note Decimal: 189. 表示的结果会保留尾部的零，并根据具有两个有效位的被乘
数自动推出四个有效位。 Decimal 可以模拟手工运算来避免当二进制浮点数无法
精确表示十进制数时会导致的问题。

精确表示特性使得 *note Decimal: 189. 类能够执行对于二进制浮点数来说不适
用的模运算和相等性检测:

     >>> Decimal('1.00') % Decimal('.10')
     Decimal('0.00')
     >>> 1.00 % 0.10
     0.09999999999999995

     >>> sum([Decimal('0.1')]*10) == Decimal('1.0')
     True
     >>> sum([0.1]*10) == 1.0
     False

*note decimal: 36. 模块提供了运算所需要的足够精度:

     >>> getcontext().prec = 36
     >>> Decimal(1) / Decimal(7)
     Decimal('0.142857142857142857142857142857142857')


File: python.info,  Node: 虚拟环境和包,  Next: 接下来？,  Prev: 标准库简介 —— 第二部分,  Up: Python 教程

2.12 虚拟环境和包
=================

* Menu:

* 概述: 概述<4>.
* 创建虚拟环境::
* 使用pip管理包::


File: python.info,  Node: 概述<4>,  Next: 创建虚拟环境,  Up: 虚拟环境和包

2.12.1 概述
-----------

Python应用程序通常会使用不在标准库内的软件包和模块。应用程序有时需要特定
版本的库，因为应用程序可能需要修复特定的错误，或者可以使用库的过时版本的
接口编写应用程序。

这意味着一个Python安装可能无法满足每个应用程序的要求。如果应用程序A需要
特定模块的1.0版本但应用程序B需要2.0版本，则需求存在冲突，安装版本1.0或
2.0将导致某一个应用程序无法运行。

这个问题的解决方案是创建一个 *note virtual environment: 1322.，一个目录
树，其中安装有特定Python版本，以及许多其他包。

然后，不同的应用将可以使用不同的虚拟环境。 要解决先前需求相冲突的例子，
应用程序 A 可以拥有自己的 安装了 1.0 版本的虚拟环境，而应用程序 B 则拥有
安装了 2.0 版本的另一个虚拟环境。 如果应用程序 B 要求将某个库升级到 3.0
版本，也不会影响应用程序 A 的环境。


File: python.info,  Node: 创建虚拟环境,  Next: 使用pip管理包,  Prev: 概述<4>,  Up: 虚拟环境和包

2.12.2 创建虚拟环境
-------------------

用于创建和管理虚拟环境的模块称为 *note venv: 126.。*note venv: 126. 通常
会安装你可用的最新版本的 Python。如果您的系统上有多个版本的 Python，您可
以通过运行 ‘python3’ 或您想要的任何版本来选择特定的Python版本。

要创建虚拟环境，请确定要放置它的目录，并将 *note venv: 126. 模块作为脚本
运行目录路径:

     python3 -m venv tutorial-env

如果它不存在，这将创建 ‘tutorial-env’ 目录，并在其中创建包含Python解释器
，标准库和各种支持文件的副本的目录。

虚拟环境的常用目录位置是 ‘.venv’。 这个名称通常会令该目录在你的终端中保
持隐藏，从而避免需要对所在目录进行额外解释的一般名称。 它还能防止与某些
工具所支持的 ‘.env’ 环境变量定义文件发生冲突。

创建虚拟环境后，您可以激活它。

在Windows上，运行:

     tutorial-env\Scripts\activate.bat

在Unix或MacOS上，运行:

     source tutorial-env/bin/activate

（这个脚本是为bash shell编写的。如果你使用 ‘csh’ 或 ‘fish’ shell，你应该
改用 ‘activate.csh’ 或 ‘activate.fish’ 脚本。）

激活虚拟环境将改变你所用终端的提示符，以显示你正在使用的虚拟环境，并修改
环境以使 ‘python’ 命令所运行的将是已安装的特定 Python 版本。 例如：

     $ source ~/envs/tutorial-env/bin/activate
     (tutorial-env) $ python
     Python 3.5.1 (default, May  6 2016, 10:59:36)
       ...
     >>> import sys
     >>> sys.path
     ['', '/usr/local/lib/python35.zip', ...,
     '~/envs/tutorial-env/lib/python3.5/site-packages']
     >>>


File: python.info,  Node: 使用pip管理包,  Prev: 创建虚拟环境,  Up: 虚拟环境和包

2.12.3 使用pip管理包
--------------------

你可以使用一个名为 ‘pip’ 的程序来安装、升级和移除软件包。 默认情况下
‘pip’ 将从 Python Package Index <‘https://pypi.org’> 安装软件包。 你可以
在你的 web 浏览器中查看 Python Package Index。

‘pip’ 有许多子命令: "install", "uninstall", "freeze" 等等。 （请在 *note
安装 Python 模块: 7fe. 指南页查看完整的 ‘pip’ 文档。）

您可以通过指定包的名称来安装最新版本的包：

     (tutorial-env) $ pip install novas
     Collecting novas
       Downloading novas-3.1.1.3.tar.gz (136kB)
     Installing collected packages: novas
       Running setup.py install for novas
     Successfully installed novas-3.1.1.3

您还可以通过提供包名称后跟 ‘==’ 和版本号来安装特定版本的包：

     (tutorial-env) $ pip install requests==2.6.0
     Collecting requests==2.6.0
       Using cached requests-2.6.0-py2.py3-none-any.whl
     Installing collected packages: requests
     Successfully installed requests-2.6.0

如果你重新运行这个命令，‘pip’ 会注意到已经安装了所请求的版本并且什么都不
做。您可以提供不同的版本号来获取该版本，或者您可以运行 ‘pip install
--upgrade’ 将软件包升级到最新版本：

     (tutorial-env) $ pip install --upgrade requests
     Collecting requests
     Installing collected packages: requests
       Found existing installation: requests 2.6.0
         Uninstalling requests-2.6.0:
           Successfully uninstalled requests-2.6.0
     Successfully installed requests-2.7.0

‘pip uninstall’ 后跟一个或多个包名称将从虚拟环境中删除包。

‘pip show’ 将显示有关特定包的信息：

     (tutorial-env) $ pip show requests
     ---
     Metadata-Version: 2.0
     Name: requests
     Version: 2.7.0
     Summary: Python HTTP for Humans.
     Home-page: http://python-requests.org
     Author: Kenneth Reitz
     Author-email: me@kennethreitz.com
     License: Apache 2.0
     Location: /Users/akuchling/envs/tutorial-env/lib/python3.4/site-packages
     Requires:

‘pip list’ 将显示虚拟环境中安装的所有软件包：

     (tutorial-env) $ pip list
     novas (3.1.1.3)
     numpy (1.9.2)
     pip (7.0.3)
     requests (2.7.0)
     setuptools (16.0)

‘pip freeze‘’ 将生成一个类似的已安装包列表，但输出使用 ‘pip install’ 期
望的格式。一个常见的约定是将此列表放在 ‘requirements.txt’ 文件中：

     (tutorial-env) $ pip freeze > requirements.txt
     (tutorial-env) $ cat requirements.txt
     novas==3.1.1.3
     numpy==1.9.2
     requests==2.7.0

然后可以将 ‘requirements.txt’ 提交给版本控制并作为应用程序的一部分提供。
然后用户可以使用 ‘install -r’ 安装所有必需的包：

     (tutorial-env) $ pip install -r requirements.txt
     Collecting novas==3.1.1.3 (from -r requirements.txt (line 1))
       ...
     Collecting numpy==1.9.2 (from -r requirements.txt (line 2))
       ...
     Collecting requests==2.7.0 (from -r requirements.txt (line 3))
       ...
     Installing collected packages: novas, numpy, requests
       Running setup.py install for novas
     Successfully installed novas-3.1.1.3 numpy-1.9.2 requests-2.7.0

‘pip’ 有更多选择。有关 ‘pip’ 的完整文档，请参阅 *note 安装 Python 模块:
7fe. 指南。当您编写一个包并希望在 Python 包索引中使它可用时，请参考
*note 分发 Python 模块: 7ff. 指南。


File: python.info,  Node: 接下来？,  Next: 交互式编辑和编辑历史,  Prev: 虚拟环境和包,  Up: Python 教程

2.13 接下来？
=============

阅读本教程可能会增强您对使用Python的兴趣 - 您应该热衷于应用Python来解决
您的实际问题。你应该去哪里了解更多？

本教程是Python文档集的一部分。其他文档：

   * *note Python 标准库: 120b.:

     您应该浏览本手册，该手册提供了有关标准库中的类型，功能和模块的完整
     （尽管简洁）参考资料。标准的Python发行版包含 `很多' 的附加代码。有
     些模块可以读取Unix邮箱，通过HTTP检索文档，生成随机数，解析命令行选
     项，编写CGI程序，压缩数据以及许多其他任务。浏览标准库参考可以了解更
     多可用的内容。

   * *note 安装 Python 模块: 7fe. 解释了怎么安装由其他Python开发者编写的
     模块。

   * *note Python语言参考: 120c.: Python的语法和语义的详细解释。尽管阅读
     完非常繁重，但作为语言本身的完整指南是有用的。

更多Python资源：

   * ‘https://www.python.org’ ：主要的Python网站。它包含代码，文档以及指
     向Web上与Python相关的页面的链接。该网站世界很多地区都有镜像，如欧洲
     ，日本和澳大利亚；镜像可能比主站点更快，具体取决于您的地理位置。

   * ‘https://docs.python.org’ ：快速访问Python的文档。

   * ‘https://pypi.org’: The Python Package Index，以前也被昵称为 Cheese
     Shop (1)，是可下载用户自制 Python 模块的索引。 当你要开始发布代码时
     ，你可以在此处进行注册以便其他人能找到它。

   * ‘https://code.activestate.com/recipes/langs/python/’ ：Python
     Cookbook是一个相当大的代码示例集，更多的模块和有用的脚本。特别值得
     注意的贡献收集在一本名为Python Cookbook（O’Reilly＆Associates，ISBN
     0-596-00797-3）的书中。

   * ‘http://www.pyvideo.org’ 从会议和用户组会议中收集与Python相关的视频
     的链接。

   * ‘https://scipy.org’ ：Ecientific Python项目包括用于快速阵列计算和操
     作的模块，以及用于诸如线性代数，傅里叶变换，非线性求解器，随机数分
     布，统计分析等的一系列包。

对于与Python相关的问题和问题报告，您可以发布到新闻组 ‘comp.lang.python’
，或者将它们发送到邮件列表python-<list@python.org>。新闻组和邮件列表是互
通的，因此发布到一个地方将自动转发给另一个。每天有数百个帖子，询问（和回
答）问题，建议新功能，以及宣布新模块。邮件列表档案可在
‘https://mail.python.org/pipermail/’ 上找到。

在发问之前，请务必查看以下列表 *note 常见问题: 1328. （或简写为 FAQ）。
常见问题包含了很多一次又一次问到的问题及答案，并且可能已经包含了您的问题
的解决方案。

备注
....

   ---------- Footnotes ----------

   (1) (1) “Cheese Shop”是 Monty Python 的一个短剧：一位顾客来到一家奶酪
商店，但无论他要哪种奶酪，店员都说没有货。


File: python.info,  Node: 交互式编辑和编辑历史,  Next: 浮点算术：争议和限制,  Prev: 接下来？,  Up: Python 教程

2.14 交互式编辑和编辑历史
=========================

某些版本的 Python 解释器支持编辑当前输入行和编辑历史记录，类似 Korn
shell 和 GNU Bash shell 的功能 。这个功能使用了 GNU Readline(1) 来实现，
一个支持多种编辑方式的库。这个库有它自己的文档，在这里我们就不重复说明了
。

* Menu:

* Tab 补全和编辑历史::
* 默认交互式解释器的替代品::

   ---------- Footnotes ----------

   (1) https://tiswww.case.edu/php/chet/readline/rltop.html


File: python.info,  Node: Tab 补全和编辑历史,  Next: 默认交互式解释器的替代品,  Up: 交互式编辑和编辑历史

2.14.1 Tab 补全和编辑历史
-------------------------

在解释器启动的时候，补全变量和模块名的功能将 *note 自动打开: 8ee.，以便
在按下 ‘Tab’ 键的时候调用补全函数。它会查看 Python 语句名称，当前局部变
量和可用的模块名称。处理像 ‘string.a’ 的表达式，它会求值在最后一个 ‘'.'’
之前的表达式，接着根据求值结果对象的属性给出补全建议。如果拥有 *note
__getattr__(): 323. 方法的对象是表达式的一部分，注意这可能会执行程序定义
的代码。默认配置下会把编辑历史记录保存在用户目录下名为 ‘.python_history’
的文件。在下一次 Python 解释器会话期间，编辑历史记录仍旧可用。


File: python.info,  Node: 默认交互式解释器的替代品,  Prev: Tab 补全和编辑历史,  Up: 交互式编辑和编辑历史

2.14.2 默认交互式解释器的替代品
-------------------------------

Python 解释器与早期版本的相比，向前迈进了一大步；无论怎样，还有些希望的
功能：如果能在编辑连续行时建议缩进（解析器知道接下来是否需要缩进符号），
那将很棒。补全机制可以使用解释器的符号表。有命令去检查（甚至建议）括号，
引号以及其他符号是否匹配。

一个可选的增强型交互式解释器是 IPython(1)，它已经存在了有一段时间，它具
有 tab 补全，探索对象和高级历史记录管理功能。它还可以彻底定制并嵌入到其
他应用程序中。另一个相似的增强型交互式环境是 bpython(2)。

   ---------- Footnotes ----------

   (1) https://ipython.org/

   (2) https://www.bpython-interpreter.org/


File: python.info,  Node: 浮点算术：争议和限制,  Next: 附录,  Prev: 交互式编辑和编辑历史,  Up: Python 教程

2.15 浮点算术：争议和限制
=========================

浮点数在计算机硬件中表示为以 2 为基数（二进制）的小数。举例而言，十进制
的小数

     0.125

等于 1/10 + 2/100 + 5/1000 ，同理，二进制的小数

     0.001

等于0/2 + 0/4 + 1/8。这两个小数具有相同的值，唯一真正的区别是第一个是以
10 为基数的小数表示法，第二个则是 2 为基数。

不幸的是，大多数的十进制小数都不能精确地表示为二进制小数。这导致在大多数
情况下，你输入的十进制浮点数都只能近似地以二进制浮点数形式储存在计算机中
。

用十进制来理解这个问题显得更加容易一些。考虑分数 1/3 。我们可以得到它在
十进制下的一个近似值

     0.3

或者，更近似的，:

     0.33

或者，更近似的，:

     0.333

以此类推。结果是无论你写下多少的数字，它都永远不会等于 1/3 ，只是更加更
加地接近 1/3 。

同样的道理，无论你使用多少位以 2 为基数的数码，十进制的 0.1 都无法精确地
表示为一个以 2 为基数的小数。 在以 2 为基数的情况下， 1/10 是一个无限循
环小数

     0.0001100110011001100110011001100110011001100110011...

在任何一个位置停下，你都只能得到一个近似值。因此，在今天的大部分架构上，
浮点数都只能近似地使用二进制小数表示，对应分数的分子使用每 8 字节的前 53
位表示，分母则表示为 2 的幂次。在 1/10 这个例子中，相应的二进制分数是
‘3602879701896397 / 2 ** 55’ ，它很接近 1/10 ，但并不是 1/10 。

大部分用户都不会意识到这个差异的存在，因为 Python 只会打印计算机中存储的
二进制值的十进制近似值。在大部分计算机中，如果 Python 想把 0.1 的二进制
对应的精确十进制打印出来，将会变成这样

     >>> 0.1
     0.1000000000000000055511151231257827021181583404541015625

这比大多数人认为有用的数字更多，因此Python通过显示舍入值来保持可管理的位
数

     >>> 1 / 10
     0.1

牢记，即使输出的结果看起来好像就是 1/10 的精确值，实际储存的值只是最接近
1/10 的计算机可表示的二进制分数。

有趣的是，有许多不同的十进制数共享相同的最接近的近似二进制小数。例如，
‘0.1’ 、 ‘0.10000000000000001’ 、
‘0.1000000000000000055511151231257827021181583404541015625’ 全都近似于
‘3602879701896397 / 2 ** 55’ 。由于所有这些十进制值都具有相同的近似值，
因此可以显示其中任何一个，同时仍然保留不变的 ‘eval(repr(x)) == x’ 。

在历史上，Python 提示符和内置的 *note repr(): 7d5. 函数会选择具有 17 位
有效数字的来显示，即 ‘0.10000000000000001’。 从 Python 3.1 开始，
Python（在大多数系统上）现在能够选择这些表示中最短的并简单地显示 ‘0.1’ 。

请注意这种情况是二进制浮点数的本质特性：它不是 Python 的错误，也不是你代
码中的错误。 你会在所有支持你的硬件中的浮点运算的语言中发现同样的情况（
虽然某些语言在默认状态或所有输出模块下都不会 `显示' 这种差异）。

想要更美观的输出，你可能会希望使用字符串格式化来产生限定长度的有效位数:

     >>> format(math.pi, '.12g')  # give 12 significant digits
     '3.14159265359'

     >>> format(math.pi, '.2f')   # give 2 digits after the point
     '3.14'

     >>> repr(math.pi)
     '3.141592653589793'

必须重点了解的是，这在实际上只是一个假象：你只是将真正的机器码值进行了舍
入操作再 `显示' 而已。

一个假象还可能导致另一个假象。 例如，由于这个 0.1 并非真正的 1/10，将三
个 0.1 的值相加也不一定能恰好得到 0.3:

     >>> .1 + .1 + .1 == .3
     False

而且，由于这个 0.1 无法精确表示 1/10 的值而这个 0.3 也无法精确表示 3/10
的值，使用 *note round(): c75. 函数进行预先舍入也是没用的:

     >>> round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1)
     False

虽然这些小数无法精确表示其所要代表的实际值，*note round(): c75. 函数还是
可以用来“事后舍入”，使得实际的结果值可以做相互比较:

     >>> round(.1 + .1 + .1, 10) == round(.3, 10)
     True

二进制浮点运算会造成许多这样的“意外”。 有关 "0.1" 的问题会在下面的“表示
性错误”一节中更详细地描述。 请参阅 浮点数的危险性(1) 一文了解有关其他常
见意外现象的更详细介绍。

正如那篇文章的结尾所言，“对此问题并无简单的答案。” 但是也不必过于担心浮
点数的问题！ Python 浮点运算中的错误是从浮点运算硬件继承而来，而在大多数
机器上每次浮点运算得到的 2**53 数码位都会被作为 1 个整体来处理。 这对大
多数任务来说都已足够，但你确实需要记住它并非十进制算术，且每次浮点运算都
可能会导致新的舍入错误。

虽然病态的情况确实存在，但对于大多数正常的浮点运算使用来说，你只需简单地
将最终显示的结果舍入为你期望的十进制数值即可得到你期望的结果。 *note
str(): 339. 通常已足够，对于更精度的控制可参看 *note 格式字符串语法:
d22. 中 *note str.format(): 4e2. 方法的格式描述符。

对于需要精确十进制表示的使用场景，请尝试使用 *note decimal: 36. 模块，该
模块实现了适合会计应用和高精度应用的十进制运算。

另一种形式的精确运算由 *note fractions: 83. 模块提供支持，该模块实现了基
于有理数的算术运算（因此可以精确表示像 1/3 这样的数值）。

如果你是浮点运算的重度用户，你应该看一下数值运算 Python 包 NumPy 以及由
SciPy 项目所提供的许多其它数学和统计运算包。 参见 <‘https://scipy.org’>。

Python 也提供了一些工具，可以在你真的 `想要' 知道一个浮点数精确值的少数
情况下提供帮助。 例如 *note float.as_integer_ratio(): 1333. 方法会将浮点
数表示为一个分数:

     >>> x = 3.14159
     >>> x.as_integer_ratio()
     (3537115888337719, 1125899906842624)

由于这是一个精确的比值，它可以被用来无损地重建原始值:

     >>> x == 3537115888337719 / 1125899906842624
     True

*note float.hex(): 1334. 方法会以十六进制（以 16 为基数）来表示浮点数，
同样能给出保存在你的计算机中的精确值:

     >>> x.hex()
     '0x1.921f9f01b866ep+1'

这种精确的十六进制表示法可被用来精确地重建浮点值:

     >>> x == float.fromhex('0x1.921f9f01b866ep+1')
     True

由于这种表示法是精确的，它适用于跨越不同版本（平台无关）的 Python 移植数
值，以及与支持相同格式的其他语言（例如 Java 和 C99）交换数据.

另一个有用的工具是 *note math.fsum(): d46. 函数，它有助于减少求和过程中
的精度损失。 它会在数值被添加到总计值的时候跟踪“丢失的位”。 这可以很好地
保持总计值的精确度， 使得错误不会积累到能影响结果总数的程度:

     >>> sum([0.1] * 10) == 1.0
     False
     >>> math.fsum([0.1] * 10) == 1.0
     True

* Menu:

* 表示性错误::

   ---------- Footnotes ----------

   (1) http://www.lahey.com/float.htm


File: python.info,  Node: 表示性错误,  Up: 浮点算术：争议和限制

2.15.1 表示性错误
-----------------

本小节将详细解释 "0.1" 的例子，并说明你可以怎样亲自对此类情况进行精确分
析。 假定前提是已基本熟悉二进制浮点表示法。

`表示性错误' 是指某些（其实是大多数）十进制小数无法以二进制（以 2 为基数
的计数制）精确表示这一事实造成的错误。 这就是为什么 Python（或者 Perl、
C、C++、Java、Fortran 以及许多其他语言）经常不会显示你所期待的精确十进制
数值的主要原因。

为什么会这样？ 1/10 是无法用二进制小数精确表示的。 目前（2000年11月）几
乎所有使用 IEEE-754 浮点运算标准的机器以及几乎所有系统平台都会将 Python
浮点数映射为 IEEE-754 “双精度类型”。 754 双精度类型包含 53 位精度，因此
在输入时，计算会尽量将 0.1 转换为以 `J'/2**`N' 形式所能表示的最接近分数
，其中 `J' 为恰好包含 53 个二进制位的整数。 重新将

     1 / 10 ~= J / (2**N)

写为

     J ~= 2**N / 10

并且由于 `J' 恰好有 53 位 (即 ‘>= 2**52’ 但 ‘< 2**53’)，`N' 的最佳值为
56:

     >>> 2**52 <=  2**56 // 10  < 2**53
     True

也就是说，56 是唯一的 `N' 值能令 `J' 恰好有 53 位。 这样 `J' 的最佳可能
值就是经过舍入的商:

     >>> q, r = divmod(2**56, 10)
     >>> r
     6

由于余数超过 10 的一半，最佳近似值可通过四舍五入获得:

     >>> q+1
     7205759403792794

这样在 754 双精度下 1/10 的最佳近似值为:

     7205759403792794 / 2 ** 56

分子和分母都除以二则结果小数为:

     3602879701896397 / 2 ** 55

请注意由于我们做了向上舍入，这个结果实际上略大于 1/10；如果我们没有向上
舍入，则商将会略小于 1/10。 但无论如何它都不会是 `精确的' 1/10！

因此计算永远不会“看到”1/10：它实际看到的就是上面所给出的小数，它所能达到
的最佳 754 双精度近似值:

     >>> 0.1 * 2 ** 55
     3602879701896397.0

如果我们将该小数乘以 10**55，我们可以看到该值输出为 55 位的十进制数:

     >>> 3602879701896397 * 10 ** 55 // 2 ** 55
     1000000000000000055511151231257827021181583404541015625

这意味着存储在计算机中的确切数值等于十进制数值
0.1000000000000000055511151231257827021181583404541015625。 许多语言（包
括较旧版本的 Python）都不会显示这个完整的十进制数值，而是将结果舍入为 17
位有效数字:

     >>> format(0.1, '.17f')
     '0.10000000000000001'

*note fractions: 83. 和 *note decimal: 36. 模块可令进行此类计算更加容易:

     >>> from decimal import Decimal
     >>> from fractions import Fraction

     >>> Fraction.from_float(0.1)
     Fraction(3602879701896397, 36028797018963968)

     >>> (0.1).as_integer_ratio()
     (3602879701896397, 36028797018963968)

     >>> Decimal.from_float(0.1)
     Decimal('0.1000000000000000055511151231257827021181583404541015625')

     >>> format(Decimal.from_float(0.1), '.17')
     '0.10000000000000001'


File: python.info,  Node: 附录,  Prev: 浮点算术：争议和限制,  Up: Python 教程

2.16 附录
=========

* Menu:

* 交互模式: 交互模式<2>.


File: python.info,  Node: 交互模式<2>,  Up: 附录

2.16.1 交互模式
---------------

* Menu:

* 错误处理::
* 可执行的Python脚本::
* 交互式启动文件::
* 定制模块::


File: python.info,  Node: 错误处理,  Next: 可执行的Python脚本,  Up: 交互模式<2>

2.16.1.1 错误处理
.................

当发生错误时，解释器会打印错误信息和错误堆栈。在交互模式下，将返回到主命
令提示符；如果输入内容来自文件，在打印错误堆栈之后，程序会以非零状态退出
。（这里所说的错误不包括 *note try: d7a. 语句中由 *note except: b46. 所
捕获的异常。）有些错误是无条件致命的，会导致程序以非零状态退出；比如内部
逻辑矛盾或内存耗尽。所有错误信息都会被写入标准错误流；而命令的正常输出则
被写入标准输出流。

将中断字符（通常为 ‘Control-C’ 或 ‘Delete’ ）键入主要或辅助提示会取消输
入并返回主提示符。 (1) 在执行命令时键入中断引发的 *note
KeyboardInterrupt: 198. 异常，可以由 *note try: d7a. 语句处理。

   ---------- Footnotes ----------

   (1) (1) GNU Readline 包的问题可能会阻止这种情况。


File: python.info,  Node: 可执行的Python脚本,  Next: 交互式启动文件,  Prev: 错误处理,  Up: 交互模式<2>

2.16.1.2 可执行的Python脚本
...........................

在BSD等类Unix系统上，Python脚本可以直接执行，就像shell脚本一样，第一行添
加:

     #!/usr/bin/env python3.5

（假设解释器位于用户的 ‘PATH’ ）脚本的开头，并将文件设置为可执行。 ‘#!’
必须是文件的前两个字符。在某些平台上，第一行必须以Unix样式的行结尾（
‘'\n'’）结束，而不是以Windows（‘'\r\n'’）行结尾。请注意，散列或磅字符
‘'#'’ 在Python中代表注释开始。

可以使用 ‘chmod’ 命令为脚本提供可执行模式或权限。

     $ chmod +x myscript.py

在Windows系统上，没有“可执行模式”的概念。 Python安装程序自动将 ‘.py’ 文
件与 ‘python.exe’ 相关联，这样双击Python文件就会将其作为脚本运行。扩展也
可以是 ‘.pyw’ ，在这种情况下，会隐藏通常出现的控制台窗口。


File: python.info,  Node: 交互式启动文件,  Next: 定制模块,  Prev: 可执行的Python脚本,  Up: 交互模式<2>

2.16.1.3 交互式启动文件
.......................

当您以交互方式使用Python时，每次启动解释器时都会执行一些标准命令，这通常
很方便。您可以通过将名为 *note PYTHONSTARTUP: 8ed. 的环境变量设置为包含
启动命令的文件名来实现。这类似于Unix shell的 ‘.profile’ 功能。

This file is only read in interactive sessions, not when Python reads
commands from a script, and not when ‘/dev/tty’ is given as the explicit
source of commands (which otherwise behaves like an interactive
session).  It is executed in the same namespace where interactive
commands are executed, so that objects that it defines or imports can be
used without qualification in the interactive session.  You can also
change the prompts ‘sys.ps1’ and ‘sys.ps2’ in this file.

如果你想从当前目录中读取一个额外的启动文件，你可以使用像 ‘if
os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read())’ 这样
的代码在全局启动文件中对它进行编程。如果要在脚本中使用启动文件，则必须在
脚本中显式执行此操作:

     import os
     filename = os.environ.get('PYTHONSTARTUP')
     if filename and os.path.isfile(filename):
         with open(filename) as fobj:
             startup_file = fobj.read()
         exec(startup_file)


File: python.info,  Node: 定制模块,  Prev: 交互式启动文件,  Up: 交互模式<2>

2.16.1.4 定制模块
.................

Python提供了两个钩子来让你自定义它：‘sitecustomize’ 和 ‘usercustomize’。
要查看其工作原理，首先需要找到用户site-packages目录的位置。启动Python并
运行此代码:

     >>> import site
     >>> site.getusersitepackages()
     '/home/user/.local/lib/python3.5/site-packages'

现在，您可以在该目录中创建一个名为 ‘usercustomize.py’ 的文件，并将所需内
容放入其中。它会影响Python的每次启动，除非它以 *note -s: d1d. 选项启动，
以禁用自动导入。

‘sitecustomize’ 以相同的方式工作，但通常由计算机管理员在全局
site-packages 目录中创建，并在 ‘usercustomize’ 之前被导入。有关详情请参
阅 *note site: ec. 模块的文档。

备注
....


File: python.info,  Node: Python安装和使用,  Next: Python语言参考,  Prev: Python 教程,  Up: Top

3 Python安装和使用
******************

这一部分文档专门介绍关于在不同平台上设置Python环境、调用解释器以及让使用
Python更容易的一些事情的有用信息。

* Menu:

* 命令行与环境::
* 在类Unix环境下使用Python::
* 在Windows上使用 Python::
* 在苹果系统上使用 Python::
* 编辑器和集成开发环境::


File: python.info,  Node: 命令行与环境,  Next: 在类Unix环境下使用Python,  Up: Python安装和使用

3.1 命令行与环境
================

CPython 解析器会扫描命令行与环境用于获取各种设置信息。

`CPython implementation detail:' 其他实现的命令行方案可能有所不同。 更多
相关资源请参阅 *note 其他实现: 1347.。

* Menu:

* 命令行::
* 环境变量::


File: python.info,  Node: 命令行,  Next: 环境变量,  Up: 命令行与环境

3.1.1 命令行
------------

对 Python 发起调用时，你可以指定以下的任意选项:

     python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]

当然最常见的用例就是简单地启动执行一个脚本:

     python myscript.py

* Menu:

* 接口选项::
* 通用选项::
* 其他选项::
* 不应当使用的选项::


File: python.info,  Node: 接口选项,  Next: 通用选项,  Up: 命令行

3.1.1.1 接口选项
................

解释器接口类似于 UNIX shell，但提供了一些额外的发起调用方法:

   * 当调用时附带连接到某个 tty 设备的标准输入时，它会提示输入命令并执行
     它们，直到读入一个 EOF（文件结束字符，其产生方式是在 UNIX 中按
     ‘Ctrl-D’ 或在 Windows 中按 ‘Ctrl-Z, Enter’。）

   * 当调用时附带一个文件名参数或以一个文件作为标准输入时，它会从该文件
     读取并执行脚本程序。

   * 当调用时附带一个目录名参数时，它会从该目录读取并执行具有适当名称的
     脚本程序。

   * 当调用时附带 ‘-c command’ 时，它会执行 `command' 所给出的 Python 语
     句。 在这里 `command' 可以包含以换行符分隔的多条语句。 请注意前导空
     格在 Python 语句中是有重要作用的！

   * 当调用时附带 ‘-m module-name’ 时，会在 Python 模块路径中查找指定的
     模块，并将其作为脚本程序执行。

在非交互模式下，会对全部输入先解析再执行。

一个接口选项会终结解释器所读入的选项列表，后续的所有参数将被放入 *note
sys.argv: c03. – 请注意其中首个元素即第零项 (‘sys.argv[0]’) 会是一个表示
程序源的字符串。

 -- 程序选项: -c <command>

     执行 `command' 中的 Python 代码。 `command' 可以为一条或以换行符分
     隔的多条语句，其中前导空格像在普通模块代码中一样具有作用。

     如果给出此选项，*note sys.argv: c03. 的首个元素将为 ‘"-c"’ 并且当前
     目录将被加入 *note sys.path: 490. 的开头（以允许该目录中的模块作为
     最高层级模块被导入）。

     使用 ‘command’ 参数会引发 *note 审计事件: ea1.
     ‘cpython.run_command’ 。

 -- 程序选项: -m <module-name>

     在 *note sys.path: 490. 中搜索指定名称的模块并将其内容作为 *note
     __main__: 1. 模块来执行。

     由于该参数为 `module' 名称，你不应给出文件扩展名 (‘.py’)。 模块名称
     应为绝对有效的 Python 模块名称，但具体实现可能并不总是强制要求这一
     点（例如它可能允许你使用包含连字符的名称）。

     包名称（包括命名空间包）也允许使用。 当所提供的是包名称而非普通模块
     名称时，解释器将把 ‘<pkg>.__main__’ 作为主模块来执行。 此行为特意被
     设计为与作为脚本参数传递给解释器的目录和 zip 文件的处理方式类似。

          注解: 此选项不适用于内置模块和以 C 编写的扩展模块，因为它们并
          没有对应的 Python 模块文件。 但是它仍然适用于预编译的模块，即
          使没有可用的初始源文件。

     如果给出此选项，*note sys.argv: c03. 的首个元素将为模块文件的完整路
     径 (在定位模块文件期间，首个元素将设为 ‘"-m"’)。 与 *note -c: 121b.
     选项一样，当前目录将被加入 *note sys.path: 490. 的开头。

     *note -I: 1018. 选项可用来在隔离模式下运行脚本，此模式中 *note
     sys.path: 490. 既不包含当前目录也不包含用户的 site-packages 目录。
     所有 ‘PYTHON*’ 环境变量也会被忽略。

     许多标准库模块都包含作为脚本执行时会被发起调用的代码。 其中的一个例
     子是 *note timeit: 10c. 模块:

          python -m timeit -s 'setup here' 'benchmarked code here'
          python -m timeit -h # for details

     使用 ‘module-name’ 参数会引发 *note 审计事件: ea1.
     ‘cpython.run_module’ 。

     参见
     ....

     *note runpy.run_module(): 134b.

          Python 代码可以直接使用的等效功能

     PEP 338(1) – 将模块作为脚本执行

     在 3.1 版更改: 提供包名称来运行 ‘__main__’ 子模块。

     在 3.4 版更改: 同样支持命名空间包

 -- Describe: -

     从标准输入 (*note sys.stdin: 316.) 读取命令。 如果标准输入为一个终
     端，则使用 *note -i: e27.。

     如果给出此选项，*note sys.argv: c03. 的首个元素将为 ‘"-"’ 并且当前
     目录将被加入 *note sys.path: 490. 的开头。

     没有参数会引发 *note 审计事件: ea1. ‘cpython.run_stdin’ 。

 -- Describe: <script>

     执行 `script' 中的 Python 代码，该参数应为一个（绝对或相对）文件系
     统路径，指向某个 Python 文件、包含 ‘__main__.py’ 文件的目录，或包含
     ‘__main__.py’ 文件的 zip 文件。

     如果给出此选项，*note sys.argv: c03. 的首个元素将为在命令行中指定的
     脚本名称。

     如果脚本名称直接指向一个 Python 文件，则包含该文件的目录将被加入
     *note sys.path: 490. 的开头，并且该文件会被作为 *note __main__: 1.
     模块来执行。

     如果脚本名称指向一个目录或 zip 文件，则脚本名称将被加入 *note
     sys.path: 490. 的开头，并且该位置中的 ‘__main__.py’ 文件会被作为
     *note __main__: 1. 模块来执行。

     *note -I: 1018. 选项可用来在隔离模式下运行脚本，此模式中 *note
     sys.path: 490. 既不包含脚本所在目录也不包含用户的 site-packages 目
     录。 所有 ‘PYTHON*’ 环境变量也会被忽略。

     使用 ‘filename’ 参数会引发 *note 审计事件: ea1. ‘cpython.run_file’
     。

     参见
     ....

     *note runpy.run_path(): cb9.

          Python 代码可以直接使用的等效功能

如果没有给出接口选项，则使用 *note -i: e27.，‘sys.argv[0]’ 将为空字符串
(‘""’)，并且当前目录会被加入 *note sys.path: 490. 的开头。 此外，tab 补
全和历史编辑会自动启用，如果你的系统平台支持此功能的话 (参见 *note
Readline（类库） 配置: 8ee.)。

参见
....

*note 调用解释器: 1217.

在 3.4 版更改: 自动启用 tab 补全和历史编辑。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0338


File: python.info,  Node: 通用选项,  Next: 其他选项,  Prev: 接口选项,  Up: 命令行

3.1.1.2 通用选项
................

 -- 程序选项: -?
 -- 程序选项: -h
 -- 程序选项: --help

     打印全部命令行选项的简短描述。

 -- 程序选项: -V
 -- 程序选项: --version

     打印 Python 版本号并退出。 示例输出信息如下:

          Python 3.8.0b2+

     如果重复给出，则打印有关构建的更多信息，例如:

          Python 3.8.0b2+ (3.8:0c076caaa8, Apr 20 2019, 21:55:00)
          [GCC 6.2.0 20161005]

     3.6 新版功能: ‘-VV’ 选项。


File: python.info,  Node: 其他选项,  Next: 不应当使用的选项,  Prev: 通用选项,  Up: 命令行

3.1.1.3 其他选项
................

 -- 程序选项: -b

     在将 *note bytes: 33a. 或 *note bytearray: 33b. 与 *note str: 339.
     或是将 *note bytes: 33a. 与 *note int: 185. 比较时发出警告。 如果重
     复给出该选项 (‘-bb’) 则会引发错误。

     在 3.5 版更改: 影响 *note bytes: 33a. 与 *note int: 185. 的比较。

 -- 程序选项: -B

     如果给出此选项，Python 将不会试图在导入源模块时写入 ‘.pyc’ 文件。 另
     请参阅 *note PYTHONDONTWRITEBYTECODE: d41.。

 -- 程序选项: --check-hash-based-pycs default|always|never

     控制基于哈希值的 ‘.pyc’ 文件的验证行为。 参见 *note
     已缓存字节码的失效: 332.。 当设为 ‘default’ 时，已选定和未选定的基
     于哈希值的字节码缓存文件将根据其默认语义进行验证。 当设为 ‘always’
     时，所有基于哈希值的 ‘.pyc’ 文件，不论是已选定还是未选定的都将根据
     其对应的源文件进行验证。 当设为 ‘never’ 时，基于哈希值的 ‘.pyc’ 文
     件将不会根据其对应的源文件进行验证。

     基于时间戳的 ‘.pyc’ 文件的语义不会受此选项影响。

 -- 程序选项: -d

     开启解析器调试输出（限专家使用，依赖于编译选项）。 另请参阅 *note
     PYTHONDEBUG: 1353.。

 -- 程序选项: -E

     忽略所有 ‘PYTHON*’ 环境变量，例如可能已设置的 *note PYTHONPATH:
     95b. 和 *note PYTHONHOME: 4de.。

 -- 程序选项: -i

     当有脚本被作为首个参数传入或使用了 *note -c: 121b. 选项时，在执行脚
     本或命令之后进入交互模式，即使是在 *note sys.stdin: 316. 并不是一个
     终端的时候。 *note PYTHONSTARTUP: 8ed. 文件不会被读取。

     这一选项的用处是在脚本引发异常时检查全局变量或者栈跟踪。 另请参阅
     *note PYTHONINSPECT: e26.。

 -- 程序选项: -I

     在隔离模式下运行 Python。 这将同时应用 -E 和 -s。 在隔离模式下
     *note sys.path: 490. 既不包含脚本所在目录也不包含用户的
     site-packages 目录。 所有 ‘PYTHON*’ 环境变量也会被忽略。 还可以施加
     更进一步的限制以防止用户注入恶意代码。

     3.4 新版功能.

 -- 程序选项: -O

     移除 assert 语句以及任何以 *note __debug__: 100c. 的值作为条件的代
     码。 通过在 ‘.pyc’ 扩展名之前添加 ‘.opt-1’ 来扩充已编译文件 (*note
     bytecode: 61d.) 的文件名 (参见 PEP 488(1))。 另请参阅 *note
     PYTHONOPTIMIZE: 1354.。

     在 3.5 版更改: 依据 PEP 488(2) 修改 ‘.pyc’ 文件名。

 -- 程序选项: -OO

     在启用 *note -O: 694. 的同时丢弃文档字符串。 通过在 ‘.pyc’ 扩展名之
     前添加 ‘.opt-2’ 来扩展已编译文件 (*note bytecode: 61d.) 的文件名 (参
     见 PEP 488(3))。

     在 3.5 版更改: 依据 PEP 488(4) 修改 ‘.pyc’ 文件名。

 -- 程序选项: -q

     即使在交互模式下也不显示版权和版本信息。

     3.2 新版功能.

 -- 程序选项: -R

     开启哈希随机化。 此选项权 *note PYTHONHASHSEED: 9cd. 环境变量设置为
     ‘0’ 时起作用，因为哈希随机化是默认启用的。

     在Python的早期版本中，此选项启用哈希随机化，将 str 和 bytes 的对象
     *note __hash__(): 349. 的值 "加盐" 为不可预测的随机值。虽然它们在单
     个Python进程中保持不变，但是在重复调用的Python进程之间它们是不可预
     测的。

     哈希随机化旨在针对由精心选择的输入引起的拒绝服务攻击提供防护，这种
     输入利用了构造 dict 在最坏情况下的性能即 O(n^2) 复杂度。 详情请参阅
     ‘http://www.ocert.org/advisories/ocert-2011-003.html’。

     *note PYTHONHASHSEED: 9cd. 允许你为哈希种子密码设置一个固定值。

     在 3.7 版更改: 此选项不会再被忽略。

     3.2.3 新版功能.

 -- 程序选项: -s

     不要将 *note 用户 site-packages 目录: 1356. 添加到 *note sys.path:
     490.。

     参见
     ....

     PEP 370(5) – 分用户的 site-packages 目录

 -- 程序选项: -S

     禁用 *note site: ec. 的导入及其所附带的基于站点对 *note sys.path:
     490. 的操作。 如果 *note site: ec. 会在稍后被显式地导入也会禁用这些
     操作 (如果你希望触发它们则应调用 *note site.main(): 1357.)。

 -- 程序选项: -u

     强制 stdout 和 stderr 流不使用缓冲。 此选项对 stdin 流无影响。

     另请参阅 *note PYTHONUNBUFFERED: 1359.。

     在 3.7 版更改: stdout 和 stderr 流在文本层现在不使用缓冲。

 -- 程序选项: -v

     每当一个模块被初始化时打印一条信息，显示其加载位置（文件名或内置模
     块）。 当重复给出时 (‘-vv’)，为搜索模块时所检查的每个文件都打印一条
     消息。 此外还提供退出时有关模块清理的信息A。 另请参阅 *note
     PYTHONVERBOSE: 135a.。
 -- 程序选项: -W arg

     警告控制。 Python 的警告机制在默认情况下会向 *note sys.stderr: 318.
     打印警告消息。 典型的警告消息具有如下形式：

          file:line: category: message

     默认情况下，每个警告都对于其发生所在的每个源行都会打印一次。 此选项
     可控制警告打印的频繁程度。

     可以给出多个 *note -W: 41f. 选项；当某个警告能与多个选项匹配时，将
     执行最后一个匹配选项的操作。 无效的 *note -W: 41f. 选项将被忽略（但
     是，在发出第一个警告时会打印有关无效选项的警告消息）。

     警告也可以使用 *note PYTHONWARNINGS: 420. 环境变量以及使用 *note
     warnings: 127. 模块在 Python 程序内部进行控制。

     最简单的设置是将某个特定操作无条件地应用于进程所发出所有警告 (即使
     是在默认情况下会忽略的那些警告):

          -Wdefault  # Warn once per call location
          -Werror    # Convert to exceptions
          -Walways   # Warn every time
          -Wmodule   # Warn once per calling module
          -Wonce     # Warn once per Python process
          -Wignore   # Never warn

     操作名称可以根据需要进行缩写 (例如 ‘-Wi’, ‘-Wd’, ‘-Wa’, ‘-We’)，解
     释器将会把它们解析为适当的操作名称。

     请参阅 *note The Warnings Filter: 135c. 和 *note Describing Warning
     Filters: 135d. 了解更多细节。

 -- 程序选项: -x

     跳过源中第一行，以允许使用非 Unix 形式的 ‘#!cmd’。 这适用于 DOS 专
     属的破解操作。

 -- 程序选项: -X

     保留用于各种具体实现专属的选项。 CPython 目前定义了下列可用的值：

        * ‘-X faulthandler’ 启用 *note faulthandler: 7d.；

        * ‘-X showrefcount’ 当程序结束或在交互解释器中的每条语句之后输出
          总引用计数和已使用内存块计数。 此选项仅在调试版本中有效。

        * ‘-X tracemalloc’ 使用 *note tracemalloc: 115. 模块启动对
          Python 内存分配的跟踪。 默认情况下，只有最近的帧会保存在跟踪的
          回溯信息中。 使用 ‘-X tracemalloc=NFRAME’ 以启动限定回溯
          `NFRAME' 帧的跟踪。 请参阅 *note tracemalloc.start(): 135f. 了
          解详情。

        * ‘-X showalloccount’ 当程序结束时输出每种类型的已分配对象的总数
          。 此选项仅当 Python 在定义了 ‘COUNT_ALLOCS’ 后构建时才会生效
          。

        * ‘-X importtime’ 显示每次导入耗费的时间。 它会显示模块名称，累
          计时间（包括嵌套的导入）和自身时间（排除嵌套的导入）。 请注意
          它的输出在多线程应用程序中可能会出错。 典型用法如 ‘python3 -X
          importtime -c 'import asyncio'’。 另请参阅 *note
          PYTHONPROFILEIMPORTTIME: 341.。

        * ‘-X dev’: 启用 CPython 的“开发模式”，引入额外的运行时检测，这
          些检测因开销过大而无法默认启用。 如果代码是正确的则它不会比默
          认输出更详细：新增警告只会在发现问题时才会发出。 开发模式的作
          用效果：

             * 添加 ‘default’ 警告过滤器，即 *note -W: 41f. ‘default’。

             * 在内存分配器上安装调试钩子：参见 *note
               PyMem_SetupDebugHooks(): 512. C 函数。

             * 启用 *note faulthandler: 7d. 模块以在发生崩溃时转储
               Python 回溯信息。

             * 启用 *note asyncio 调试模式: 1360.。

             * 将 *note sys.flags: b44. 的 ‘dev_mode’ 属性设为 ‘True’。

             * *note io.IOBase: 1dc. 析构函数记录 ‘close()’ 异常。

        * ‘-X utf8’ 为操作系统接口启用 UTF-8 模式，覆盖默认的区域感知模
          式。 ‘-X utf8=0’ 显式地禁用 UTF-8 模式（即使在它应当被自动激活
          的时候）。 请参阅 *note PYTHONUTF8: 31a. 了解详情。

        * ‘-X pycache_prefix=PATH’ 允许将 ‘.pyc’ 文件写入以给定目录为根
          的并行树，而不是代码树。另见 *note PYTHONPYCACHEPREFIX: 155. 。

     它还允许传入任意值并通过 *note sys._xoptions: 1361. 字典来提取这些
     值。

     在 3.2 版更改: 增加了 *note -X: 156. 选项。

     3.3 新版功能: ‘-X faulthandler’ 选项。

     3.4 新版功能: ‘-X showrefcount’ 与 ‘-X tracemalloc’ 选项。

     3.6 新版功能: ‘-X showalloccount’ 选项。

     3.7 新版功能: ‘-X importtime’, ‘-X dev’ 与 ‘-X utf8’ 选项。

     3.8 新版功能: ‘-X pycache_prefix’ 选项。 ‘-X dev’ 选项现在在 *note
     io.IOBase: 1dc. 析构函数中记录 ‘close()’ 异常。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0488

   (2) https://www.python.org/dev/peps/pep-0488

   (3) https://www.python.org/dev/peps/pep-0488

   (4) https://www.python.org/dev/peps/pep-0488

   (5) https://www.python.org/dev/peps/pep-0370


File: python.info,  Node: 不应当使用的选项,  Prev: 其他选项,  Up: 命令行

3.1.1.4 不应当使用的选项
........................

 -- 程序选项: -J

     保留给 Jython(1) 使用。

   ---------- Footnotes ----------

   (1) http://www.jython.org/


File: python.info,  Node: 环境变量,  Prev: 命令行,  Up: 命令行与环境

3.1.2 环境变量
--------------

这些环境变量会影响 Python 的行为，它们是在命令行开关之前被处理的，但 -E
或 -I 除外。 根据约定，当存在冲突时命令行开关会覆盖环境变量的设置。

 -- 环境变量: PYTHONHOME

     更改标准 Python 库的位置。 默认情况下库是在
     ‘`prefix'/lib/python`version'’ 和
     ‘`exec_prefix'/lib/python`version'’ 中搜索，其中 ‘`prefix'’ 和
     ‘`exec_prefix'’ 是由安装位置确定的目录，默认都位于 ‘/usr/local’。

     当 *note PYTHONHOME: 4de. 被设为单个目录时，它的值会同时替代
     ‘`prefix'’ 和 ‘`exec_prefix'’。 要为两者指定不同的值，请将 *note
     PYTHONHOME: 4de. 设为 ‘`prefix':`exec_prefix'’。

 -- 环境变量: PYTHONPATH

     增加模块文件默认搜索路径。 所用格式与终端的 ‘PATH’ 相同：一个或多个
     由 *note os.pathsep: 1365. 分隔的目录路径名称（例如 Unix 上用冒号而
     在 Windows 上用分号）。 默认忽略不存在的目录。

     除了普通目录之外，单个 *note PYTHONPATH: 95b. 条目可以引用包含纯
     Python模块的zip文件（源代码或编译形式）。无法从zip文件导入扩展模块
     。

     默认索引路径依赖于安装路径，但通常都是以
     ‘`prefix'/lib/python`version'’ 开始 (参见上文中的 *note PYTHONHOME:
     4de.)。 它 `总是' 会被添加到 *note PYTHONPATH: 95b.。

     有一个附加目录将被插入到索引路径的 *note PYTHONPATH: 95b. 之前，正
     如上文中 *note 接口选项: 134a. 所描述的。 搜索路径可以在 Python 程
     序内作为变量 *note sys.path: 490. 来进行操作。

 -- 环境变量: PYTHONSTARTUP

     这如果是一个可读文件的名称，该文件中的 Python 命令会在交互模式的首
     个提示符显示之前被执行。 该文件会在与交互式命令执行所在的同一命名空
     间中被执行，因此其中所定义或导入的对象可以在交互式会话中无限制地使
     用。 你还可以在这个文件中修改提示符 *note sys.ps1: 1366. 和 *note
     sys.ps2: 1367. 以及钩子 *note sys.__interactivehook__: 8ec.。

     使用 ‘filename’ 参数会引发 *note 审计事件: ea1.
     ‘cpython.run_startup’ 。

 -- 环境变量: PYTHONOPTIMIZE

     这如果被设为一个非空字符串，它就相当于指定 *note -O: 694. 选项。 如
     果设为一个整数，则它就相当于多次指定 *note -O: 694.。

 -- 环境变量: PYTHONBREAKPOINT

     此变量如果被设定，它会使用加点号的路径标记一个可调用对象。 包含该可
     调用对象的模块将被导入，随后该可调用对象将由 *note
     sys.breakpointhook(): 31c. 的默认实现来运行，后者自身将由内置的
     *note breakpoint(): 302. 来调用。 如果未设定，或设定为空字符串，则
     它相当于值 "pdb.set_trace"。 将此变量设为字符串 "0" 会导致 *note
     sys.breakpointhook(): 31c. 的默认实现不做任何事而直接返回。

     3.7 新版功能.

 -- 环境变量: PYTHONDEBUG

     此变量如果被设为一个非空字符串，它就相当于指定 *note -d: 1352. 选项
     。 如果设为一个整数，则它就相当于多次指定 *note -d: 1352.。

 -- 环境变量: PYTHONINSPECT

     此变量如果被设为一个非空字符串，它就相当于指定 *note -i: e27. 选项
     。

     此变量也可由 Python 代码使用 *note os.environ: b3f. 来修改以在程序
     终结时强制检查模式。

 -- 环境变量: PYTHONUNBUFFERED

     此变量如果被设为一个非空字符串，它就相当于指定 *note -u: 1358. 选项
     。

 -- 环境变量: PYTHONVERBOSE

     此变量如果被设为一个非空字符串，它就相当于指定 *note -v: d90. 选项
     。 如果设为一个整数，则它就相当于多次指定 *note -v: d90.。

 -- 环境变量: PYTHONCASEOK

     如果设置此变量，Python 将忽略 *note import: c25. 语句中的大小写。 这
     仅在 Windows 和 OS X 上有效。

 -- 环境变量: PYTHONDONTWRITEBYTECODE

     此变量如果被设为一个非空字符串，Python 将不会尝试在导入源模块时写入
     ‘.pyc’ 文件。 这相当于指定 *note -B: d40. 选项。

 -- 环境变量: PYTHONPYCACHEPREFIX

     如果设置了此选项，Python将在镜像目录树中的此路径中写入 ‘.pyc’ 文件
     ，而不是源树中的 ‘__pycache__’ 目录中。这相当于指定 *note -X: 156.
     ‘pycache_prefix=PATH’ 选项。

     3.8 新版功能.

 -- 环境变量: PYTHONHASHSEED

     如果此变量未设置或设为 ‘random’，将使用一个随机值作为 str 和 bytes
     对象哈希运算的种子。

     如果 *note PYTHONHASHSEED: 9cd. 被设为一个整数值，它将被作为固定的
     种子数用来生成哈希随机化所涵盖的类型的 hash() 结果。

     它的目的是允许可复现的哈希运算，例如用于解释器本身的自我检测，或允
     许一组 python 进程共享哈希值。

     该整数必须为一个 [0,4294967295] 范围内的十进制数。 指定数值 0 将禁
     用哈希随机化。

     3.2.3 新版功能.

 -- 环境变量: PYTHONIOENCODING

     如果此变量在运行解释器之前被设置，它会覆盖通过
     ‘encodingname:errorhandler’ 语法设置的 stdin/stdout/stderr 所用编码
     。 ‘encodingname’ 和 ‘:errorhandler’ 部分都是可选项，与在 *note
     str.encode(): c3f. 中的含义相同。

     对于 stderr，‘:errorhandler’ 部分会被忽略；处理程序将总是为
     ‘'backslashreplace'’。

     在 3.4 版更改: “encodingname” 部分现在是可选的。

     在 3.6 版更改: 在 Windows 上，对于交互式控制台缓冲区会忽略此变量所
     指定的编码，除非还指定了 *note PYTHONLEGACYWINDOWSSTDIO: 502.。 通
     过标准流重定向的文件和管道则不受其影响。

 -- 环境变量: PYTHONNOUSERSITE

     如果设置了此变量，Python 将不会把 *note 用户 site-packages 目录:
     1356. 添加到 *note sys.path: 490.。

     参见
     ....

     PEP 370(1) – 分用户的 site-packages 目录

 -- 环境变量: PYTHONUSERBASE

     定义 *note 用户基准目录: 1368.，它会在执行 ‘python setup.py install
     --user’ 时被用来计算 *note 用户 site-packages 目录: 1356. 的路径以
     及 *note Distutils 安装路径: 1369.。

     参见
     ....

     PEP 370(2) – 分用户的 site-packages 目录

 -- 环境变量: PYTHONEXECUTABLE

     如果设置了此环境变量，则 ‘sys.argv[0]’ 将被设为此变量的值而不是通过
     C 运行时所获得的值。 仅在 Mac OS X 上起作用。

 -- 环境变量: PYTHONWARNINGS

     此变量等价于 *note -W: 41f. 选项。 如果被设为一个以逗号分隔的字符串
     ，它就相当于多次指定 *note -W: 41f.，列表中后出现的过滤器优先级会高
     于列表中先出现的。

     最简单的设置是将某个特定操作无条件地应用于进程所发出所有警告 (即使
     是在默认情况下会忽略的那些警告):

          PYTHONWARNINGS=default  # Warn once per call location
          PYTHONWARNINGS=error    # Convert to exceptions
          PYTHONWARNINGS=always   # Warn every time
          PYTHONWARNINGS=module   # Warn once per calling module
          PYTHONWARNINGS=once     # Warn once per Python process
          PYTHONWARNINGS=ignore   # Never warn

     请参阅 *note The Warnings Filter: 135c. 和 *note Describing Warning
     Filters: 135d. 了解更多细节。

 -- 环境变量: PYTHONFAULTHANDLER

     如果此环境变量被设为一个非空字符串，*note faulthandler.enable():
     551. 会在启动时被调用：为 ‘SIGSEGV’, ‘SIGFPE’, ‘SIGABRT’, ‘SIGBUS’
     和 ‘SIGILL’ 等信号安装一个处理句柄以转储 Python 回溯信息。 此变量等
     价于 *note -X: 156. ‘faulthandler’ 选项。

     3.3 新版功能.

 -- 环境变量: PYTHONTRACEMALLOC

     如果此环境变量被设为一个非空字符串，则会使用 *note tracemalloc:
     115. 模块启动对 Python 内存分配的跟踪。 该变量的值是保存于跟踪的回
     溯信息中的最大帧数。 例如，‘PYTHONTRACEMALLOC=1’ 只保存最近的帧。 请
     参阅 *note tracemalloc.start(): 135f. 了解详情。

     3.4 新版功能.

 -- 环境变量: PYTHONPROFILEIMPORTTIME

     如果此变量被设为一个非空字符串，Python 将显示每次导入花费了多长时间
     。 此变量完全等价于在命令行为设置 ‘-X importtime’。

     3.7 新版功能.

 -- 环境变量: PYTHONASYNCIODEBUG

     如果此变量被设为一个非空字符串，则会启用 *note asyncio: a. 模块的
     *note 调试模式: 1360.。

     3.4 新版功能.

 -- 环境变量: PYTHONMALLOC

     设置 Python 内存分配器和/或安装调试钩子。

     设置 Python 所使用的内存分配器族群：

        * ‘default’: 使用 *note 默认内存分配器: 136d.。

        * ‘malloc’: 对所有域 (*note PYMEM_DOMAIN_RAW: 136e, *note
          PYMEM_DOMAIN_MEM: 511, *note PYMEM_DOMAIN_OBJ: 50f.) 使用 C 库
          的 ‘malloc()’ 函数。

        * ‘pymalloc’: 对 *note PYMEM_DOMAIN_MEM: 511. 和 *note
          PYMEM_DOMAIN_OBJ: 50f. 域使用 *note pymalloc 分配器: 5ca. 而对
          *note PYMEM_DOMAIN_RAW: 136e. 域使用 ‘malloc()’ 函数。

     安装调试钩子：

        * ‘debug’: 在 *note 默认内存分配器: 136d. 之上安装调试钩子。

        * ‘malloc_debug’: 与 ‘malloc’ 相同但还会安装调试钩子。

        * ‘pymalloc_debug’: 与 ‘pymalloc’ 相同但还会安装调试钩子。

     请参阅 *note 默认内存分配器: 136d. 以及 *note
     PyMem_SetupDebugHooks(): 512. 函数（在 Python 内存分配器之上安装调
     试钩子）。

     在 3.7 版更改: 增加了 ‘"default"’ 分配器。

     3.6 新版功能.

 -- 环境变量: PYTHONMALLOCSTATS

     如果设为一个非空字符串，Python 将在每次创建新的 pymalloc 对象区域以
     及在关闭时打印 *note pymalloc 内存分配器: 5ca. 的统计信息。

     如果 *note PYTHONMALLOC: 50b. 环境变量被用来强制开启 C 库的
     ‘malloc()’ 分配器，或者如果 Python 的配置不支持 ‘pymalloc’，则此变
     量将被忽略。

     在 3.6 版更改: 此变量现在也可以被用于在发布模式下编译的 Python。 如
     果它被设置为一个空字符串则将没有任何效果。

 -- 环境变量: PYTHONLEGACYWINDOWSFSENCODING

     如果设为一个非空字符串，则默认的文件系统编码和错误模式将分别恢复为
     它们在 3.6 版之前的值 ’mbcs’ 和 ’replace’。 否则会使用新的默认值
     ’utf-8’ 和 ’surrogatepass’。

     这也可以在运行时通过 *note sys._enablelegacywindowsfsencoding():
     500. 来启用。

     *note 可用性: 136f.: Windows。

     3.6 新版功能: 有关更多详细信息，请参阅 PEP 529(3)。

 -- 环境变量: PYTHONLEGACYWINDOWSSTDIO

     如果设为一个非空字符串，则不使用新的控制台读取器和写入器。 这意味着
     Unicode 字符将根据活动控制台的代码页进行编码，而不是使用 utf-8。

     如果标准流被重定向（到文件或管道）而不是指向控制台缓冲区则该变量会
     被忽略。

     *note 可用性: 136f.: Windows。

     3.6 新版功能.

 -- 环境变量: PYTHONCOERCECLOCALE

     如果值设为 ‘0’，将导致主 Python 命令行应用跳过将传统的基于 ASCII 的
     C 与 POSIX 区域设置强制转换为更强大的基于 UTF-8 的替代方案。

     如果此变量 `未被' 设置（或被设为 ‘0’ 以外的值），则覆盖环境变量的
     ‘LC_ALL’ 区域选项也不会被设置，并且报告给 ‘LC_CTYPE’ 类别的当前区域
     选项或者为默认的 ‘C’ 区域，或者为显式指明的基于 ASCII 的 ‘POSIX’ 区
     域，然后 Python CLI 将在加载解释器运行时之前尝试为 ‘LC_CTYPE’ 类别
     按指定的顺序配置下列区域选项：

        * ‘C.UTF-8’

        * ‘C.utf8’

        * ‘UTF-8’

     如果成功设置了以上区域类别中的一个，则初始化 Python 运行时之前也将
     在当前进程环境中相应地设置 ‘LC_CTYPE’ 环境变量。 这会确保除了解释器
     本身和运行于同一进程中的其他可感知区域选项的组件 (例如 GNU
     ‘readline’ 库) 之外，还能在子进程 (无论这些进程是否在运行 Python 解
     释器) 以及在查询环境而非当前 C 区域的操作 (例如 Python 自己的 *note
     locale.getdefaultlocale(): 1370.) 中看到更新的设置。

     (显式地或通过上述的隐式区域强制转换) 配置其中一个区域选项将自动为
     *note sys.stdin: 316. 和 *note sys.stdout: 317. 启用
     ‘surrogateescape’ *note 错误处理句柄: 1371. (*note sys.stderr: 318.
     会继续使用 ‘backslashreplace’ 如同在任何其他区域选项中一样)。 这种
     流处理行为可以按通常方式使用 *note PYTHONIOENCODING: 937. 来覆盖。

     出于调试目的，如果激活了区域强制转换，或者如果当 Python 运行时被初
     始化时某个 `应该' 触发强制转换的区域选项仍处于激活状态则设置
     ‘PYTHONCOERCECLOCALE=warn’ 将导致 Python 在 ‘stderr’ 上发出警告消息
     。

     还要注意，即使在区域转换转换被禁用，或者在其无法找到合适的目标区域
     时，默认 *note PYTHONUTF8: 31a. 仍将在传统的基于 ASCII 的区域中被激
     活。 必须同时禁用这两项特性以强制解释器使用 ‘ASCII’ 而不是 ‘UTF-8’
     作为系统接口。

     *note 可用性: 136f.: *nix。

     3.7 新版功能: 请参阅 PEP 538(4) 了解详情。

 -- 环境变量: PYTHONDEVMODE

     如果此环境变量被设为一个非空字符串，则会启用 CPython “开发模式”。 参
     见 *note -X: 156. ‘dev’ 选项。

     3.7 新版功能.

 -- 环境变量: PYTHONUTF8

     如果设为 ‘1’，则会启用解释器的 UTF-8 模式，将 ‘UTF-8’ 用作系统接口
     的文本编码，无论当前区域选项如何设置。

     这意味着：

             * *note sys.getfilesystemencoding(): 4fe. 将返回 ‘'UTF-8'’
               (本地编码会被忽略)。

             * *note locale.getpreferredencoding(): 3ad. 将返回
               ‘'UTF-8'’ (本地编码会被忽略，并且该函数的 ‘do_setlocale’
               参数不起作用)。

             * *note sys.stdin: 316, *note sys.stdout: 317. 和 *note
               sys.stderr: 318. 都将 UTF-8 用作它们的文本编码，并且为
               *note sys.stdin: 316. 和 *note sys.stdout: 317. 启用
               ‘surrogateescape’ *note 错误处理句柄: 1371. (*note
               sys.stderr: 318. 会继续使用 ‘backslashreplace’ 如同在默认
               的局部感知模式下一样)

     作为低层级 API 发生改变的结果，其他高层级 API 也会表现出不同的默认
     行为：

             * 命令行参数，环境变量和文件名会使用 UTF-8 编码来解码为文本
               。

             * *note os.fsdecode(): 4f6. 和 *note os.fsencode(): 4f7. 会
               使用 UTF-8 编码。

             * *note open(): 4f8, *note io.open(): 663. 和 *note
               codecs.open(): 1372. 默认会使用 UTF-8 编码。 但是，它们默
               认仍将使用严格错误处理句柄，因此试图在文本模式下打开二进
               制文件将可能引发异常，而不是生成无意义的数据。

     请注意 UTF-8 模式下的标准流设置可以被 *note PYTHONIOENCODING: 937.
     所覆盖（在默认的区域感知模式下也同样如此）。

     如果设置为“0”，则解释器以其默认的区域识别模式运行。

     设置任何其他非空字符串会在解释器初始化期间导致错误。

     如果根本未设置此环境变量，则解释器默认使用当前区域设置，`除非' 当前
     区域被标识为基于 ASCII 的旧式区域设置（如 *note
     PYTHONCOERCECLOCALE: 315. 所述），并且区域强制转换被禁用或失败。 在
     此类旧式区域设置中，解释器将默认启用 UTF-8 模式，除非显式地指定不这
     样做。

     也可以使用 *note -X: 156. ‘utf8’ 选项。

     3.7 新版功能: 有关更多详细信息，请参阅 PEP 540(5) 。

* Menu:

* 调试模式变量::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0370

   (2) https://www.python.org/dev/peps/pep-0370

   (3) https://www.python.org/dev/peps/pep-0529

   (4) https://www.python.org/dev/peps/pep-0538

   (5) https://www.python.org/dev/peps/pep-0540


File: python.info,  Node: 调试模式变量,  Up: 环境变量

3.1.2.1 调试模式变量
....................

设置这些变量只会在Python的调试版本中产生影响。

 -- 环境变量: PYTHONTHREADDEBUG

     如果设置，Python将打印线程调试信息。

     需要使用 ‘--with-pydebug’ 构建选项配置Python。

 -- 环境变量: PYTHONDUMPREFS

     如果设置，Python在关闭解释器，及转储对象和引用计数后仍将保持活动。

     需要使用 ‘--with-trace-refs’ 构建选项配置Python。


File: python.info,  Node: 在类Unix环境下使用Python,  Next: 在Windows上使用 Python,  Prev: 命令行与环境,  Up: Python安装和使用

3.2 在类Unix环境下使用Python
============================

* Menu:

* 获得并安装Python的最新版本::
* 构建Python::
* 与Python相关的路径和文件::
* 杂项::


File: python.info,  Node: 获得并安装Python的最新版本,  Next: 构建Python,  Up: 在类Unix环境下使用Python

3.2.1 获得并安装Python的最新版本
--------------------------------

* Menu:

* 在Linux中::
* 在FreeBSD和OpenBSD上::
* 在OpenSolaris系统上::


File: python.info,  Node: 在Linux中,  Next: 在FreeBSD和OpenBSD上,  Up: 获得并安装Python的最新版本

3.2.1.1 在Linux中
.................

Python预装在大多数Linux发行版上，并作为一个包提供给所有其他用户。 但是，
您可能想要使用的某些功能在发行版提供的软件包中不可用。这时您可以从源代码
轻松编译最新版本的Python。

如果Python没有预先安装并且不在发行版提供的库中，您可以轻松地为自己使用的
发行版创建包。 参阅以下链接：

参见
....

‘https://www.debian.org/doc/manuals/maint-guide/first.en.html’

     对于Debian用户

‘https://en.opensuse.org/Portal:Packaging’

     对于OpenSuse用户

‘https://docs-old.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/RPM_Guide/ch-creating-rpms.html’

     对于Fedora用户

‘http://www.slackbook.org/html/package-management-making-packages.html’

     对于Slackware用户


File: python.info,  Node: 在FreeBSD和OpenBSD上,  Next: 在OpenSolaris系统上,  Prev: 在Linux中,  Up: 获得并安装Python的最新版本

3.2.1.2 在FreeBSD和OpenBSD上
............................

   * FreeBSD用户，使用以下命令添加包:

          pkg install python3

   * OpenBSD用户，使用以下命令添加包:

          pkg_add -r python

          pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/<insert your architecture here>/python-<version>.tgz

     例如：i386用户获取Python 2.5.1的可用版本:

          pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz


File: python.info,  Node: 在OpenSolaris系统上,  Prev: 在FreeBSD和OpenBSD上,  Up: 获得并安装Python的最新版本

3.2.1.3 在OpenSolaris系统上
...........................

你可以从 OpenCSW(1) 获取、安装及使用各种版本的Python。比如 ‘pkgutil -i
python27’ 。

   ---------- Footnotes ----------

   (1) https://www.opencsw.org/


File: python.info,  Node: 构建Python,  Next: 与Python相关的路径和文件,  Prev: 获得并安装Python的最新版本,  Up: 在类Unix环境下使用Python

3.2.2 构建Python
----------------

如果你想自己编译CPython，首先要做的是获取 source(1) 。您可以下载最新版本
的源代码，也可以直接提取最新的 clone(2) 。 （如果你想要制作补丁，则需要
克隆代码。）

构建过程由常用命令组成：

     ./configure
     make
     make install

特定Unix平台的配置选项和注意事项通常记录在Python源代码的根目录下的
README.rst(3) 文件中。

     警告: ‘make install’ 可以覆盖或伪装 ‘python3’ 二进制文件。因此，建
     议使用 ‘make altinstall’ 而不是 ‘make install’ ，因为后者只安装了
     ‘`exec_prefix'/bin/python`version'’ 。

   ---------- Footnotes ----------

   (1) https://www.python.org/downloads/source/

   (2) https://devguide.python.org/setup/#getting-the-source-code

   (3) https://github.com/python/cpython/tree/3.8/README.rst


File: python.info,  Node: 与Python相关的路径和文件,  Next: 杂项,  Prev: 构建Python,  Up: 在类Unix环境下使用Python

3.2.3 与Python相关的路径和文件
------------------------------

这取决于本地安装惯例； ‘prefix’ （ ‘${prefix}’ ）和 ‘exec_prefix’ （
‘${exec_prefix}’ ） 取决于安装，应解释为GNU软件；它们可能相同。

例如，在大多数Linux系统上，两者的默认值是 ‘/usr’ 。

文件/目录                                           含义
                                                    
---------------------------------------------------------------------------------------------------
                                                    
‘`exec_prefix'/bin/python3’                         解释器的推荐位置
                                                    
                                                    
‘`prefix'/lib/python`version'’,                     包含标准模块的目录的推荐位置
‘`exec_prefix'/lib/python`version'’                 

‘`prefix'/include/python`version'’,                 包含开发Python扩展和嵌入解释器所需的
‘`exec_prefix'/include/python`version'’             include文件的目录的推荐位置
                                                    


File: python.info,  Node: 杂项,  Prev: 与Python相关的路径和文件,  Up: 在类Unix环境下使用Python

3.2.4 杂项
----------

要在Unix上使用Python脚本，需要添加可执行权限，例如：

     $ chmod +x script

并在脚本的顶部放置一个合适的Shebang线。一个很好的选择通常是:

     #!/usr/bin/env python3

将在整个 ‘PATH’ 中搜索Python解释器。但是，某些Unix系统可能没有 ‘env’ 命
令，因此可能需要将 ‘/usr/bin/python3’ 硬编码为解释器路径。

要在Python脚本中使用shell命令，请查看 *note subprocess: fa. 模块。


File: python.info,  Node: 在Windows上使用 Python,  Next: 在苹果系统上使用 Python,  Prev: 在类Unix环境下使用Python,  Up: Python安装和使用

3.3 在Windows上使用 Python
==========================

本文档旨在概述在 Microsoft Windows 上使用 Python 时应了解的特定于
Windows 的行为。

与大多数UNIX系统和服务不同，Windows系统没有预安装Python。多年来CPython 团
队已经编译了每一个 发行版(1) 的Windows安装程序（MSI 包），已便Windows 用
户下载和安装。这些安装程序主要用于每个用户单独安装Python时，添加核心解释
器和库。安装程序还可以为一台机器的所有用户安装，并且可以为应用程序本地分
发提供单独的zip文件。

如 PEP 11(2) 中所述，Python 仅支持微软产品支持生命周期内的Windows 版本。
这意味着 Python 3.8 支持Windows Vista和更新版本。如果需要Windows XP支持
，请安装Python 3.4。

Windows提供了许多不同的安装程序，每个安装程序都有一定的优点和缺点。

*note 完整安装程序: 1381. 内含所有组件，对于使用Python 进行任何类型项目
的开发人员而言，它是最佳选择。

*note Microsoft Store包: 1218. 是一个简单的Python 安装，适用于运行脚本和
包，以及使用IDLE或其他开发环境。 它需要Windows 10，但可以安全地安装而不
会破坏其他程序。 它还提供了许多方便的命令来启动Python及其工具。

*note nuget.org 安装包: 1382. 是用于持续集成系统的轻量级安装。它可用于构
建Python包或运行脚本，但不可更新且没有用户界面工具。

*note 可嵌入的包: 1383. 是Python的最小安装包，适合嵌入到更大的应用程序中
。

* Menu:

* 完整安装程序::
* Microsoft Store包::
* nuget.org 安装包: nuget org 安装包.
* 可嵌入的包::
* 替代捆绑包::
* 配置Python::
* UTF-8 模式::
* 适用于Windows的Python启动器::
* 查找模块::
* 附加模块::
* 在Windows上编译Python::
* 其他平台::

   ---------- Footnotes ----------

   (1) https://www.python.org/download/releases/

   (2) https://www.python.org/dev/peps/pep-0011


File: python.info,  Node: 完整安装程序,  Next: Microsoft Store包,  Up: 在Windows上使用 Python

3.3.1 完整安装程序
------------------

* Menu:

* 安装步骤::
* 删除 MAX_PATH 限制::
* 无UI 安装::
* 免下载安装::
* 修改安装::


File: python.info,  Node: 安装步骤,  Next: 删除 MAX_PATH 限制,  Up: 完整安装程序

3.3.1.1 安装步骤
................

四个 Python 3.8 安装程序可供下载 - 32位和64位版本的各有两个。 `web
installer' （网络安装包）是一个小的初始化工具，它将在安装过程中，根据需
要自动下载所需的组件。 `offline installer' （离线安装包）内含默认安装所
需的组件，可选择功能仍需要Internet连接下载。请参阅 *note 免下载安装:
1386. 以了解在安装过程中避免下载的其他方法。

启动安装程序后，可以选择以下两个选项之一：

[python-figures/win_installer]
如果选择“Install Now（立即安装）”：

   * 您 `不' 需要成为管理员（除非需要对C运行库进行系统更新，或者为所有用
     户安装 *note 适用于Windows的Python启动器: 997. ）

   * Python将安装到您的用户目录中

   * *note 适用于Windows的Python启动器: 997. 将根据第一页底部的选项安装

   * 将安装标准库，测试套件，启动器和pip

   * 如果选择将安装目录将添加到 ‘PATH’

   * 快捷方式仅对当前用户可见

选择“自定义安装”将允许您选择：要安装的功能、安装位置、其他选项或安装后的
操作。如果要安装调试符号或二进制文件，您需要使用此选项。

如要为全部用户安装，应选择“自定义安装”。在这种情况下:

   * 您可能需要提供管理凭据或批准

   * Python 将安装到Program Files目录中

   * *note 适用于Windows的Python启动器: 997. 将安装到Windows目录中

   * 安装期间可以选择可选功能

   * 标准库可以预编译为字节码

   * 如果选中，安装目录将添加到系统 ‘PATH’

   * 快捷方式所有用户可用


File: python.info,  Node: 删除 MAX_PATH 限制,  Next: 无UI 安装,  Prev: 安装步骤,  Up: 完整安装程序

3.3.1.2 删除 MAX_PATH 限制
..........................

历史上Windows的路径长度限制为260个字符。这意味着长于此的路径将无法解决并
导致错误。

在最新版本的 Windows 中，此限制可被扩展到大约 32,000 个字符。 但需要让管
理员激活“启用 Win32 长路径”组策略，或在注册表键
‘HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem’ 中设置
‘LongPathsEnabled’ 为 ‘1’。

这允许 *note open(): 4f8. 函数，*note os: c5. 模块和大多数其他路径功能接
受并返回长度超过 260 个字符的路径。

更改上述选项后，无需进一步配置。

在 3.6 版更改: Python中启用了对长路径的支持。


File: python.info,  Node: 无UI 安装,  Next: 免下载安装,  Prev: 删除 MAX_PATH 限制,  Up: 完整安装程序

3.3.1.3 无UI 安装
.................

安装程序UI中的所有选项也可以从命令行指定，允许脚本安装程序在许多机器上复
制安装，而无需用户交互。还可以在不禁用UI的情况下设置这些选项，以更改一些
默认值。

要完全隐藏安装程序UI并静默安装Python，请使用 ‘/quiet’ 选项。要跳过用户交
互但仍然显示进度和错误，请使用 ‘/passive’ 选项。可以通过 ‘/uninstall’ 选
项立即开始删除Python - - 不会显示任何提示。

所有其他选项都传递为 ‘name=value’ ，其中值通常是 ‘0’ 来禁用某个特性，
‘1’ 来启用某个特性或路径。可用选项的完整列表如下所示。

名称                            描述                                       默认值
                                                                           
----------------------------------------------------------------------------------------------------------
                                                                           
InstallAllUsers                 为所有用户安装。                           0
                                                                           
                                                                           
TargetDir                       安装目录                                   基于InstallAllUsers选择
                                                                           
                                                                           
DefaultAllUsersTargetDir        为所有用户安装时的默认安装路径             ‘%ProgramFiles%\Python X.Y’
                                                                           或
                                                                           ‘%ProgramFiles(x86)%\Python
                                                                           X.Y’
                                                                           
                                                                           
DefaultJustForMeTargetDir       仅为当前用户安装时的默认安装路径           ‘%LocalAppData%\Programs\PythonXY’
                                                                           或
                                                                           ‘%LocalAppData%\Programs\PythonXY-32’
                                                                           或
                                                                           ‘%LocalAppData%\Programs\PythonXY-64’
                                                                           
                                                                           
DefaultCustomTargetDir          UI中显示的默认自定义安装目录               （空）
                                                                           
                                                                           
AssociateFiles                  如果还安装了启动器，则创建文件关联。       1
                                                                           
                                                                           
CompileAll                      将所有 ‘.py’ 文件编译为 ‘.pyc’ 。          0
                                                                           
                                                                           
PrependPath                     将install和Scripts目录添加到 ‘PATH’ 以及   0
                                将 ‘.PY’ 添加到 ‘PATHEXT’                  
                                
                                                                           
Shortcuts                       如果已安装，为解释器，文档和IDLE创建快捷   1
                                方式                                       
                                
                                                                           
Include_doc                     安装Python手册                             1
                                                                           
                                                                           
Include_debug                   安装调试二进制文件                         0
                                                                           
                                                                           
Include_dev                     安装开发人员头文件和库                     1
                                                                           
                                                                           
Include_exe                     安装 ‘python.exe’ 及相关文件               1
                                                                           
                                                                           
Include_launcher                安装                                       1
                                *note 适用于Windows的Python启动器: 997.    
                                .
                                
                                                                           
InstallLauncherAllUsers         为所有用户安装                             1
                                *note 适用于Windows的Python启动器: 997.    
                                。
                                
                                                                           
Include_lib                     安装标准库和扩展模块                       1
                                                                           
                                                                           
Include_pip                     安装捆绑的pip和setuptools                  1
                                                                           
                                                                           
Include_symbols                 安装调试符号(‘*’.pdb)                      0
                                                                           
                                                                           
Include_tcltk                   安装Tcl/Tk 支持和IDLE                      1
                                                                           
                                                                           
Include_test                    安装标准库测试套件                         1
                                                                           
                                                                           
Include_tools                   安装实用程序脚本                           1
                                                                           
                                                                           
LauncherOnly                    仅安装启动器。这将覆盖大多数其他选项。     0
                                                                           
                                                                           
SimpleInstall                   禁用大多数安装UI                           0
                                                                           
                                                                           
SimpleInstallDescription        使用简化安装UI时显示的自定义消息。         （空）
                                                                           

例如，要以静默方式全局安装默认的Python，您可以（在命令提示符>）使用以下
命令:

     python-3.8.0.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0

要允许用户在没有测试套件的情况下轻松安装Python的个人副本，可以使用以下命
令提供快捷方式。这将显示一个简化的初始页面，不允许自定义:

     python-3.8.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0
         SimpleInstall=1 SimpleInstallDescription="Just for me, no test suite."

（请注意，省略启动器也会省略文件关联，并且仅在全局安装包含启动器时才建议
用于每用户安装。）

上面列出的选项也可以在一个名为 ‘unattend.xml’ 的文件中与可执行文件一起提
供。此文件指定选项和值的列表。作为属性提供的值，（如果可能）它将转换为数
字。作为文本提供的值，始终保留为字符串。此示例文件设置与上一示例采用相同
的选项：

     <Options>
         <Option Name="InstallAllUsers" Value="no" />
         <Option Name="Include_launcher" Value="0" />
         <Option Name="Include_test" Value="no" />
         <Option Name="SimpleInstall" Value="yes" />
         <Option Name="SimpleInstallDescription">Just for me, no test suite</Option>
     </Options>


File: python.info,  Node: 免下载安装,  Next: 修改安装,  Prev: 无UI 安装,  Up: 完整安装程序

3.3.1.4 免下载安装
..................

由于下载的初始安装包中未包含Python的某些可选功能，如果选择安装这些功能可
能需要Internet连接。为了避免这种需要，可以按需下载所有可能的组件，以创建
一个完整的布局，该布局将不再需要internet连接，而不管所选择的特性是什么。
请注意，此下载可能比要求的要大，但是如果要执行大量安装，则拥有本地缓存​​的
副本非常有用。

从命令提示符执行以下命令以下载所有可能的必需文件。请记住将
‘python-3.8.0.exe’ 替换为安装程序的实际名称，并在自己的目录中创建布局，
以避免同名的文件之间发生冲突。

     python-3.8.0.exe /layout [optional target directory]

您也可以指定 ‘/quiet’ 选项来隐藏进度显示。


File: python.info,  Node: 修改安装,  Prev: 免下载安装,  Up: 完整安装程序

3.3.1.5 修改安装
................

安装Python后，您可以通过Windows中的“程序和功能”工具添加或删除功能。选择
Python条目并选择“卸载/更改”以在维护模式下打开安装程序。

“修改” 允许您通过修改复选框来添加或删除功能 - 未更改的复选框将不会安装或
删除任何内容。在此模式下无法更改某些选项，例如安装目录；要修改这些，您需
要完全删除然后重新安装Python。

“修复” 将使用当前设置验证应安装的所有文件，并替换已删除或修改的任何文件

“卸载” 将完全删除Python，但 *note 适用于Windows的Python启动器: 997. 除外
，它在“程序和功能”中有自己的条目。


File: python.info,  Node: Microsoft Store包,  Next: nuget org 安装包,  Prev: 完整安装程序,  Up: 在Windows上使用 Python

3.3.2 Microsoft Store包
-----------------------

3.7.2 新版功能.

Microsoft Store包是一个易于安装的Python解释器，主要用于交互式使用，例如
，学生。

要安装软件包，请确保您拥有最新的Windows 10更新，并在Microsoft Store应用
程序中搜索 "Python 3.8" 。确保您选择的应用程序由 Python Software
Foundation 发布并安装。

     警告: Python将始终在Microsoft Store上免费提供。如果要求您付款，则表
     示您没有选择正确的包。

安装完成后，可以在开始菜单中找到它来启动 Python。或者可以在命令提示符或
PowerShell 会话中输入 ‘python’ 来启动。此外可以输入 ‘pip’ 或 ‘idle’ 来使
用 pip 和 IDLE。IDLE 也在开始菜单中。

所有这三个命令也可以使用版本号后缀，例如， ‘python3.exe’ 和
‘python3.x.exe’ 以及 ‘python.exe’ （其中 ‘3.x’ 是您要启动的特定版本，例
如 3.8 ）。在 ‘设置-->主页-->应用和功能’ 页面中，点选 ‘管理可选功能’ ，
选择与每个命令关联的python版本。建议确保 ‘pip’ 和 ‘idle’ 与选择的
‘python’ 版本一致。

可以使用 ‘python -m venv’ 创建虚拟环境并激活并正常使用。

如果你已经安装了另一个版本的Python并将它添加到你的 ‘PATH’ 变量中，那么它
将作为 ‘python.exe’ 而不是来自Microsoft Store的那个。要访问新安装，请使
用 ‘python3.exe’ 或 ‘python3.x.exe’ 。

‘py.exe’ 启动器将检测此 Python 安装版，但会优先使用来自传统安装器的安装
版。

要删除Python，请打开“设置”并使用“应用程序和功能”，或者在“开始”中找到
Python，然后右键单击以选择“卸载”。卸载将删除该已安装Python程序中的所有软
件包，但不会删除任何虚拟环境

* Menu:

* 已知的问题::


File: python.info,  Node: 已知的问题,  Up: Microsoft Store包

3.3.2.1 已知的问题
..................

由于Microsoft Store应用程序的限制，Python脚本可能无法对共享位置（如
‘TEMP’ ）和注册表进行完全写入访问。相反，它将写入私人副本。如果脚本必须
修改共享位置，则需要安装完整安装程序。

有关此限制的技术原理的更多细节，请查询 Microsoft 已打包完全可信应用的文
档，当前位于
docs.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-behind-the-scenes(1)

   ---------- Footnotes ----------

   (1) 
https://docs.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-behind-the-scenes


File: python.info,  Node: nuget org 安装包,  Next: 可嵌入的包,  Prev: Microsoft Store包,  Up: 在Windows上使用 Python

3.3.3 nuget.org 安装包
----------------------

3.5.2 新版功能.

nuget.org是一个精简的Python环境，用于在没有全局安装Python的系统的持续集
成和构建。虽然Nuget是“.NET的包管理器”，但是对于包含构建时工具的包来说，
它也可以很好地工作。

访问 nuget.org(1) 获取有关使用nuget的最新信息。下面的摘要对Python开发人
员来说已经足够了。

‘nuget.exe’ 命令行工具可以直接从 ‘https://aka.ms/nugetclidl’ 下载，例如
，使用curl或PowerShell。使用该工具安装64位或32位最新版本的Python:

     nuget.exe install python -ExcludeVersion -OutputDirectory .
     nuget.exe install pythonx86 -ExcludeVersion -OutputDirectory .

要选择特定版本，请添加 ‘-Version 3.x.y’ 。输出目录可以从 ‘.’ 更改，包将
安装到子目录中。默认情况下，子目录的名称与包的名称相同，如果没有
‘-ExcludeVersion’ 选项，则此名称将包含已安装的特定版本。子目录里面是一个
包含Python安装的 ‘tools’ 目录:

     # Without -ExcludeVersion
     > .\python.3.5.2\tools\python.exe -V
     Python 3.5.2

     # With -ExcludeVersion
     > .\python\tools\python.exe -V
     Python 3.5.2

通常，nuget包不可升级，应该平行安装较新版本并使用完整路径引用。或者，手
动删除程序包目录并再次安装。如果在构建之间不保留文件，许多CI系统将自动执
行此操作。

除了 ‘tools’ 目录外，还有一个 ‘build\native’ 目录。它包含一个MSBuild属性
文件 ‘python.props’ ，可以在C++项目中使用该文件来引用Python安装。包含这
些设置将自动在生成中使用标头和导入库。

nuget.org上的包信息页是 www.nuget.org/packages/python(2) 对于64位版本和
www.nuget.org/packages/pythonx86(3) 表示32位版本。

   ---------- Footnotes ----------

   (1) https://www.nuget.org/

   (2) https://www.nuget.org/packages/python

   (3) https://www.nuget.org/packages/pythonx86


File: python.info,  Node: 可嵌入的包,  Next: 替代捆绑包,  Prev: nuget org 安装包,  Up: 在Windows上使用 Python

3.3.4 可嵌入的包
----------------

3.5 新版功能.

嵌入式发行版是一个包含最小Python环境的ZIP文件。它旨在作为另一个应用程序
的一部分，而不是由最终用户直接访问。

解压缩后，嵌入式发行版（几乎）与用户系统完全隔离，包括环境变量、系统注册
表设置和已安装的软件包。标准库作为预先编译和优化的 ‘.pyc’ 文件包含在
ZIP中，并提供了 ‘python3.dll’ ， ‘python37.dll’ ， ‘python.exe’ 和
‘pythonw.exe’ 文件。不包括Tcl/tk（包括所有依赖项，如Idle），pip和
Python文档。

     注解: 嵌入式发行版不包括 Microsoft C Runtime(1) ，应用程序安装程序
     负责提供此功能。运行时可能已经预先安装在用户的系统上或通过Windows
     Update自动安装，并且可以通过在系统目录中找到 ‘ucrtbase.dll’ 来检测

     注解: 当在Windows 7上运行时, Python 3.8 需求KB2533623更新才能够安装
     .嵌入式分配器不能检查这次更新, 所以将在运行时出现问题. 最新版本的
     Windows包含次更新.

第三方软件包应该由应用程序与嵌入式发行版一起安装。这个发行版不支持像常规
Python安装那样使用pip来管理依赖关系，不过可以小心地将pip包含进来并使用它
进行自动更新。通常，第三方包应该作为应用程序的一部分(“打包”)处理，以便开
发人员在向用户提供更新之前能够确保与新版本兼容。

下面描述了这个发行版的两个推荐用例。

* Menu:

* Python应用程序::
* 嵌入Python::

   ---------- Footnotes ----------

   (1) https://www.microsoft.com/en-us/download/details.aspx?id=48145


File: python.info,  Node: Python应用程序,  Next: 嵌入Python,  Up: 可嵌入的包

3.3.4.1 Python应用程序
......................

用Python编写的应用程序并不一定要求用户了解这一事实。在这种情况下，可以使
用嵌入式发行版在安装包中包含Python的私有版本。根据它应该有多透明(或者相
反，它应该看起来有多专业)，有两个选项。

使用专门的可执行文件作为启动程序需要一些编码，但为用户提供了最透明的体验
。使用定制的启动器，没有明显的迹象表明程序是在Python上运行的：图标可以定
制，公司和版本信息可以指定，文件关联可以正常运行。在大多数情况下，自定义
启动程序应该只需使用硬编码的命令行就能调用 ‘Py_Main’

更简单的方法是提供批处理文件或生成的快捷方式，使用所需的命令行参数直接调
用 ‘python.exe’ 或 ‘pythonw.exe’ 。在这种情况下，应用程序将显示为
Python而不是其实际名称，并且用户可能无法将其与其他正在运行的Python进程或
文件关联区分开来。

对于后一种方法，包应该与Python可执行文件一起作为目录安装，以确保它们在路
径上可用。使用专用的启动器，包可以位于其他位置，因为在启动应用程序之前有
机会指定搜索路径。


File: python.info,  Node: 嵌入Python,  Prev: Python应用程序,  Up: 可嵌入的包

3.3.4.2 嵌入Python
..................

用本地代码编写的应用程序通常需要某种形式的脚本语言，嵌入式Python发行版可
以用于此目的。通常，应用程序的大部分都是本机代码，某些部分将调用
‘python.exe’ 或直接使用 ‘python3.dll’ 。无论是哪种情况，将嵌入的发行版解
压缩到应用程序安装的子目录中就足以提供可加载的Python解释器。

与应用程序使用一样，包可以安装到任何位置，因为在初始化解释器之前有机会指
定搜索路径。否则，使用嵌入式发行版和常规安装之间没有根本区别。


File: python.info,  Node: 替代捆绑包,  Next: 配置Python,  Prev: 可嵌入的包,  Up: 在Windows上使用 Python

3.3.5 替代捆绑包
----------------

除了标准的CPython发行版之外，还有一些包含附加功能的修改包。以下是热门版
本及其主要功能的列表：

ActivePython(1)

     具有多平台兼容性的安装程序，文档，PyWin32

Anaconda(2)

     流行的科学模块（如numpy，scipy和pandas）和 ‘conda’ 包管理器。

Canopy(3)

     具有编辑器和其他开发工具的“全面的Python分析环境”。

WinPython(4)

     特定于Windows的发行版，包含用于构建包的预构建科学包和工具。

请注意，这些软件包可能不包含最新版本的Python或其他库，并且不由核心
Python团队维护或支持。

   ---------- Footnotes ----------

   (1) https://www.activestate.com/activepython/

   (2) https://www.anaconda.com/download/

   (3) https://www.enthought.com/product/canopy/

   (4) https://winpython.github.io/


File: python.info,  Node: 配置Python,  Next: UTF-8 模式,  Prev: 替代捆绑包,  Up: 在Windows上使用 Python

3.3.6 配置Python
----------------

要从命令提示符方便地运行Python，您可以考虑在Windows中更改一些默认环境变
量。虽然安装程序提供了为您配置PATH和PATHEXT变量的选项，但这仅适用于单版
本、全局安装。如果您经常使用多个版本的Python，请考虑使用 *note
适用于Windows的Python启动器: 997. 。

* Menu:

* 附录：设置环境变量::
* 查找Python可执行文件::


File: python.info,  Node: 附录：设置环境变量,  Next: 查找Python可执行文件,  Up: 配置Python

3.3.6.1 附录：设置环境变量
..........................

Windows允许在用户级别和系统级别永久配置环境变量，或临时在命令提示符中配
置环境变量。

要临时设置环境变量，请打开命令提示符并使用 ‘set’ 命令：

     C:\>set PATH=C:\Program Files\Python 3.8;%PATH%
     C:\>set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
     C:\>python

这些环境变量的更改将应用​​于在该控制台中执行的任何其他命令，并且，由该控制
台启动的任何应用程序都继承设这些设置。

在百分号中包含的变量名将被现有值替换，允许在开始或结束时添加新值。通过将
包含 ‘python.exe’ 的目录添加到开头来修改 ‘PATH’ 是确保启动正确版本的
Python的常用方法。

要永久修改默认环境变量，请单击“开始”并搜索“编辑环境变量”，或打开“系统属
性” Advanced system settings ，然后单击 Environment Variables 按钮。在此
对话框中，您可以添加或修改用户和系统变量。要更改系统变量，您需要对计算机
进行无限制访问（即管理员权限）。

     注解: Windows会将用户变量串联的系统变量 `之后' ，这可能会在修改
     ‘PATH’ 时导致意外结果。

     *note PYTHONPATH: 95b. 变量被Python 2和Python 3的所有版本使用，因此
     除非它只包含与所有已安装的Python版本兼容的代码，否则不要永久配置此
     变量。

参见
....

‘https://www.microsoft.com/en-us/wdsi/help/folder-variables’

     Windows NT 的环境变量

‘https://technet.microsoft.com/en-us/library/cc754250.aspx’

     用于临时修改环境变量的SET命令

‘https://technet.microsoft.com/en-us/library/cc755104.aspx’

     用于永久修改环境变量的SETX命令

‘https://support.microsoft.com/en-us/help/310519/how-to-manage-environment-variables-in-windows-xp’

     如何在Windows XP中管理环境变量

‘https://www.chem.gla.ac.uk/~louis/software/faq/q1.html’

     设置环境变量（For Windows 2000/NT），Louis J. Farrugia


File: python.info,  Node: 查找Python可执行文件,  Prev: 附录：设置环境变量,  Up: 配置Python

3.3.6.2 查找Python可执行文件
............................

在 3.5 版更改.

除了使用自动创建的Python解释器的开始菜单项之外，您可能还想在命令提示符下
启动Python。安装程序有一个选项可以为您设置。

在安装程序的第一页上，可以选择标记为“将Python添加到环境变量”的选项，以使
安装程序将安装位置添加到 ‘PATH’ 。还添加了 ‘Scripts\’ 文件夹的位置。这允
许你输入 ‘python’ 来运行解释器，并且 ‘pip’ 用于包安装程序。因此，您还可
以使用命令行选项执行脚本，请参阅 *note 命令行: 933. 文档。

如果在安装时未启用此选项，则始终可以重新运行安装程序，选择“修改”并启用它
。或者，您可以使用 *note 附录：设置环境变量: 1219. 的方法手动修改 ‘PATH’
。您需要将Python安装目录添加到 ‘PATH’ 环境变量中，该内容与其他条目用分号
分隔。示例变量可能如下所示（假设前两个条目已经存在）:

     C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Python 3.8


File: python.info,  Node: UTF-8 模式,  Next: 适用于Windows的Python启动器,  Prev: 配置Python,  Up: 在Windows上使用 Python

3.3.7 UTF-8 模式
----------------

3.7 新版功能.

Windows 仍然使用传统编码格式作为系统的编码格式（ANSI 代码页）。 Python 使
用它作为文本文件默认的编码格式 (即 *note locale.getpreferredencoding():
3ad.)。

这可能会造成问题，因为因特网和大多数 Unix 系统包括 WSL (Windows
Subsystem for Linux) 广泛使用 UTF-8。

你可以使用 UTF-8 模式将默认的文本编码格式改为 UTF-8。 要启用 UTF-8 模式
可以通过 ‘-X utf8’ 命令行选项，或者 ‘PYTHONUTF8=1’ 环境变量。 请参见
*note PYTHONUTF8: 31a. 了解如何启用 UTF-8 模式，并参见 *note
附录：设置环境变量: 1219. 了解如何修改环境变量。

当 UTF-8 模式被启用时：

   * *note locale.getpreferredencoding(): 3ad. 将返回 ‘'UTF-8'’ 而不是系
     统的编码格式。 此函数可用来在许多场合下获取默认的文本编码格式，包括
     *note open(): 4f8, ‘Popen’, ‘Path.read_text()’ 等等。

   * *note sys.stdin: 316, *note sys.stdout: 317. 和 *note sys.stderr:
     318. 都将使用 UTF-8 作为其文本编码格式。

   * 你仍然可以通过 "mbcs" 编解码器来使用系统的编码格式。

请注意添加 ‘PYTHONUTF8=1’ 到默认环境变量将会影响你的系统中的所有 Python
3.7+ 应用。 如果你有任何 Python 3.7+ 应用仍然依赖于传统的系统编码格式，
则推荐设置临时环境变量或使用 ‘-X utf8’ 命令行选项。

     注解: 即使在不启用 UTF-8 模式时，Windows 版的 Python 也会在以下情况
     中默认使用 UTF-8：

        * 控制台 I/O 包括标准 I/O (详情见 PEP 528(1))。

        * 文件系统编码格式 (详情见 PEP 529(2))。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0528

   (2) https://www.python.org/dev/peps/pep-0529


File: python.info,  Node: 适用于Windows的Python启动器,  Next: 查找模块,  Prev: UTF-8 模式,  Up: 在Windows上使用 Python

3.3.8 适用于Windows的Python启动器
---------------------------------

3.3 新版功能.

用于Windows的Python启动器是一个实用程序，可帮助定位和执行不同的Python版
本。它允许脚本（或命令行）指示特定Python版本的首选项，并将定位并执行该版
本。

与 ‘PATH’ 变量不同，启动器将正确选择最合适的Python版本。它更倾向于按用户
安装而不是系统安装，并按语言版本排序，而不是使用最新安装的版本。

启动器最初是在 PEP 397(1) 中指定的。

* Menu:

* 入门::
* Shebang Lines::
* shebang lines 的参数::
* 自定义::
* 诊断::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0397


File: python.info,  Node: 入门,  Next: Shebang Lines,  Up: 适用于Windows的Python启动器

3.3.8.1 入门
............

* Menu:

* 从命令行::
* 从虚拟环境::
* 从脚本::
* 从文件关联::


File: python.info,  Node: 从命令行,  Next: 从虚拟环境,  Up: 入门

3.3.8.2 从命令行
................

在 3.6 版更改.

全局安装Python 3.3及更高版本将把启动器放在你的 ‘PATH’ 上。启动程序与所有
可用的Python版本兼容，因此安装哪个版本无关紧要。要检查启动程序是否可用，
请在命令提示符中执行以下命令：

     py

您应该会发现已安装的最新版本的Python已启动 - 它可以正常退出，并且将指定
的任何其他命令行参数直接发送到Python。

如果您安装了多个版本的Python（例如，2.7和 3.8 ），您会注意到Python 3.8 启
动 - 如果要启动Python 2.7，尝试命令：

     py -2.7

如果您想使用 Python 2.x 的最新版本，请尝试以下命令：

     py -2

你会发现Python 2.x 的最新版本已启动。

如果您看到以下错误，则表明您没有安装启动器：

     'py' is not recognized as an internal or external command,
     operable program or batch file.

除非在安装时选择了该选项，单个用户安装的Python不会将启动程序添加到
‘PATH’ 。


File: python.info,  Node: 从虚拟环境,  Next: 从脚本,  Prev: 从命令行,  Up: 入门

3.3.8.3 从虚拟环境
..................

3.5 新版功能.

如果启动程序运行时没有明确的Python版本，并且虚拟环境（使用标准库创建
*note venv: 126. 模块或外部 ‘virtualenv’ 工具）处于活动状态，则启动程序
将运行虚拟环境的解释器而不是全局的。要运行全局解释器，请停用虚拟环境，或
显式指定全局Python版本。


File: python.info,  Node: 从脚本,  Next: 从文件关联,  Prev: 从虚拟环境,  Up: 入门

3.3.8.4 从脚本
..............

让我们创建一个测试Python脚本 - 创建一个名为‘‘hello.py‘‘的文件，其中包含
以下内容

     #! python
     import sys
     sys.stdout.write("hello from Python %s\n" % (sys.version,))

从hello.py所在的目录中，执行以下命令：

     py hello.py

您应该注意到最新的Python 2.x安装的版本号已打印出来。现在尝试将第一行更改
为：

     #! python3

现在，重新执行该命令应该打印最新的Python 3.x信息。与上面的命令行示例一样
，你可以更明确的指定版本限定符。假设您安装了Python 2.6，请尝试将第一行更
改为 ‘#! python2.6’ ，你会发现打印的2.6版本信息。

请注意，与交互式使用不同，裸“python”将使用您已安装的Python 2.x的最新版本
。这是为了向后兼容及兼容Unix，其中命令 ‘python’ 通常是指Python 2。


File: python.info,  Node: 从文件关联,  Prev: 从脚本,  Up: 入门

3.3.8.5 从文件关联
..................

安装时应该将启动器与Python文件（即 ‘.py’, ‘.pyw’, ‘.pyc’ 文件）相关联。
这意味着当您从Windows资源管理器中双击其中一个文件时，将使用启动程序，因
此您可以使用上述相同的工具让脚本指定应使用的版本。

这样做的主要好处是，单个启动程序可以同时支持多个Python版本，具体取决于第
一行的内容。


File: python.info,  Node: Shebang Lines,  Next: shebang lines 的参数,  Prev: 入门,  Up: 适用于Windows的Python启动器

3.3.8.6 Shebang Lines
.....................

如果脚本文件的第一行以 ‘#!’ 开头，则称为 "shebang" 行。Linux和其他类
Unix操作系统都有对这些行的本机支持，它们通常在此类系统上用来指示应该如何
执行脚本。这个启动器允许在Windows上对Python脚本使用相同的工具，上面的示
例演示了它们的使用。

为了允许Python脚本中的shebang行在Unix和Windows之间移植，该启动器支持许多
“虚拟”命令来指定要使用的解释器。支持的虚拟命令是：

   * ‘/usr/bin/env python’

   * ‘/usr/bin/python’

   * ‘/usr/local/bin/python’

   * ‘python’

例如，如果脚本开始的第一行

     #! /usr/bin/python

将找到并使用默认的Python。因为在Unix上编写的许多Python脚本已经有了这一行
，你应该发现这些脚本可以由启动器使用而无需修改。如果您在Windows上编写一
个新脚本，希望在Unix上有用，那么您应该使用以 ‘/usr’ 开头的一个shebang行
。

任何上述虚拟命令都可以显式指定版本（可以仅为主要版本，也可以为主要版本加
次要版本）作为后缀。 此外，可以通过在次要版本之后添加 “-32” 来请求 32 位
版本。 例如 ‘/usr/bin/python2.7-32’ 将请求使用 32 位 python 2.7。

3.7 新版功能: 从python启动程序3.7开始，可以通过“-64”后缀调用64位版本。此
外，可以指定没有次要的主要和架构（即 ‘/usr/bin/python3-64’ ）。

shebang line的 ‘/usr/bin/env’ 形式还有一个特殊属性。在寻找已安装的
Python解释器之前，此表单将搜索可执行文件 ‘PATH’ 以获取Python可执行文件。
这对应于Unix中 ‘env’ 程序的行为，该程序将在 ‘PATH’ 执行搜索。


File: python.info,  Node: shebang lines 的参数,  Next: 自定义,  Prev: Shebang Lines,  Up: 适用于Windows的Python启动器

3.3.8.7 shebang lines 的参数
............................

shebang lines 还可以指定要传递给Python解释器的其他选项。例如，如果你有一
个shebang lines ：

     #! /usr/bin/python -v

然后Python将以 ‘-v’ 选项启动


File: python.info,  Node: 自定义,  Next: 诊断,  Prev: shebang lines 的参数,  Up: 适用于Windows的Python启动器

3.3.8.8 自定义
..............

* Menu:

* 通过INI文件自定义::
* 自定义默认的Python版本::


File: python.info,  Node: 通过INI文件自定义,  Next: 自定义默认的Python版本,  Up: 自定义

3.3.8.9 通过INI文件自定义
.........................

启动程序将搜索两个.ini文件 - 在当前用户的 "application data" 目录中搜索
‘py.ini’ （即通过使用 ‘CSIDL_LOCAL_APPDATA’ 调用Windows函数
‘SHGetFolderPath’ 返回的目录）以及与启动器位于同一目录中的 ‘py.ini’ 。相
同的.ini文件既用于启动器的“控制台”版本（即 py.exe），也用于“windows”版本
（即pyw.exe）

“应用程序目录”中指定的自定义优先于可执行文件旁边.ini文件的自定义，因此对
启动程序旁边的.ini文件不具有写访问权限的用户可以覆盖该全局.ini文件中的命
令。


File: python.info,  Node: 自定义默认的Python版本,  Prev: 通过INI文件自定义,  Up: 自定义

3.3.8.10 自定义默认的Python版本
...............................

在某些情况下，可以在命令中包含版本限定符，以指定命令将使用哪个Python版本
。版本限定符以主版本号开头，可以选择后跟 (’.’) 和次版本说明符。此外，可
以通过添加 "-32" 或 “-64” 来指定是请求32位还是64位实现。

例如，一个shebang line 的 ‘#!python’ 行没有版本限定符，而 ‘#!python3’ 有
一个版本限定符，它只指定一个主要版本。

如果在命令中找不到版本限定符，则可以设置环境变量 ‘PY_PYTHON’ 以指定默认
版本限定符。 如果未设置，则默认为 "3"。 该变量可以指定能通过命令行传递的
任何值，比如 "3", "3.7", "3.7-32" 或 "3.7-64"。 （请注意 "-64" 选项仅适
用于 Python 3.7 或更高版本中包含的启动器。）

如果没有找到次要版本限定符，则可以设置环境变量 ‘PY_PYTHON{major}’ （其中
‘{major}’ 是上面确定的当前主要版本限定符）以指定完整版本。如果没有找到这
样的选项，启动器将枚举已安装的Python版本并使用为主要版本找到的最新次要版
本，尽管不能保证，但该版本可能是该系列中最新安装的版本。

在安装了相同（major.minor）Python版本的32位和64位的64位Windows上，64位版
本将始终是首选。对于启动程序的32位和64位实现都是如此 – 这对于启动程序
32位和64位都是正确的 – 如果可用，32位启动程序将倾向于执行指定版本的64位
Python安装。这样就可以预测启动器的行为，只知道PC上安装了哪些版本，而不考
虑它们的安装顺序（即，不知道32位或64位版本的Python和相应的启动器是否是最
后安装）。如上所述，可以在版本说明符上使用可选的“-32”或“-64”后缀来更改此
行为。

示例：

   * 如果没有设置相关选项，命令 ‘python’ 和 ‘python2’ 将使用安装的最新
     Python 2.x版本，命令 ‘python3’ 将使用最新安装的Python 3.x.

   * 命令 ‘python3.1’ 和 ‘python2.7’ 根本不会查阅任何选项，因为版本已完
     全指定。

   * 如果 ‘PY_PYTHON=3’ ，命令‘‘python‘‘ 和 ‘python3’ 都将使用最新安装的
     Python 3版本。

   * 如果 ‘PY_PYTHON=3.1-32’ ，命令 ‘python’ 将使用3.1的32位实现，而命令
     ‘python3’ 将使用最新安装的Python（PY_PYTHON根本没有被视为指定了主要
     版本。）

   * 如果 ‘PY_PYTHON=3’ 且 ‘PY_PYTHON3=3.1’，命令 ‘python’ 和 ‘python3’
     都将特别使用3.1

除环境变量外，还可以在启动程序使用的.INI文件中配置相同的设置。 INI文件中
的部分称为 ‘[defaults]’ ，键名称将与没有前导 ‘PY_’ 前缀的环境变量相同（
并注意INI文件中的键名不区分大小写） 。）环境变量的内容将覆盖INI文件中指
定的内容。

例如:

   * 设置 ‘PY_PYTHON=3.1’ 等同于包含以下内容的INI文件：

     [defaults]
     python=3.1

   * 设置 ‘PY_PYTHON=3’ 和 ‘PY_PYTHON3=3.1’ 相当于包含以下内容的INI文件
     ：

     [defaults]
     python=3
     python3=3.1


File: python.info,  Node: 诊断,  Prev: 自定义,  Up: 适用于Windows的Python启动器

3.3.8.11 诊断
.............

如果设置了环境变量 ‘PYLAUNCH_DEBUG’ （任何值），启动器将诊断信息打印到
stderr（即：控制台）。虽然这些信息同时具有冗长 `和' 简洁性，但它应该允许
您查看Python的版本、选择特定版本的原因以及用于执行目标Python的确切命令行
。


File: python.info,  Node: 查找模块,  Next: 附加模块,  Prev: 适用于Windows的Python启动器,  Up: 在Windows上使用 Python

3.3.9 查找模块
--------------

Python通常将其库（以及您的site-packages文件夹）存储在安装目录中。因此，
如果您已将Python安装到 ‘C:\Python\’ ，则默认库将驻留在 ‘C:\Python\Lib\’
中，第三方模块存储在 ‘C:\Python\Lib\site-packages\’ 。

若要完全覆盖 *note sys.path: 490. ，请创建与DLL(‘python37._pth’)或可执行
文件(“python._pth‘”)同名的 ‘._pth’ 文件，并为要添加的每个路径指定一行
*note sys.path: 490. 。基于DLL名称的文件覆盖基于可执行文件的文件，如果需
要，可以为加载运行时的任何程序限制路径。

当文件存在时，将忽略所有注册表和环境变量，启用隔离模式，并且：除非文件中
的一行指定 ‘import site’ ，否则不会导入 *note site: ec. 。以 ‘＃’ 开头的
空白路径和行将被忽略。每个路径可以是绝对的或相对于文件的位置。不允许使用
除 ‘site’ 以外的导入语句，并且不能指定任意代码。

请注意，当指定 ‘import site’ 时， ‘.pth’ 文件（没有前导下划线）将由
*note site: ec. 模块正常处理。

当找不到 ‘._pth’ 文件时， *note sys.path: 490. 是如何在Windows上填充的：

   * 在开始时，添加一个空条目，该条目对应于当前目录。

   * 如果环境变量 *note PYTHONPATH: 95b. 存在，如 *note 环境变量: 1364.
     中所述，则接下来添加其条目。请注意，在Windows上，此变量中的路径必须
     用分号分隔，以区别于驱动器标识符中使用的冒号（ ‘C:\’ 等）。

   * 额外的 "应用程序路径" 可以作为子键被同时添加到注册表
     ‘HKEY_CURRENT_USER’ 和 ‘HKEY_LOCAL_MACHINE’ 分支下的
     ‘\SOFTWARE\Python\PythonCore{version}\PythonPath’ 中。 以分号分隔的
     路径字符串作为默认值的子键将导致每个路径都被添加到 *note sys.path:
     490. 中。 （请注意所有已知的安装程序都只使用 HKLM，因此 HKCU 通常为
     空。）

   * 如果设置了环境变量 *note PYTHONHOME: 4de. ，则将其假定为 “Python 主
     目录” 。否则，主Python可执行文件的路径用于定位 “landmark 文件” （
     ‘Lib\os.py’ 或 ‘pythonXY.zip’ ）以推断 ”Python 主目录“ 。如果找到了
     Python主目录，则基于该文件夹将相关的子目录添加到 *note sys.path:
     490. （‘Lib’ , ‘plat-win’ 等）。否则，核心Python路径是从存储在注册
     表中的PythonPath构造的。

   * 如果找不到Python Home，也没有指定 *note PYTHONPATH: 95b. 环境变量，
     并且找不到注册表项，则使用具有相对条目的默认路径（例如 ‘.\Lib;
     .\plat-win’ 等等）。

如果在主可执行文件旁边或在可执行文件上一级的目录中找到 ‘pyvenv.cfg’ 文件
，则以下变体适用：

   * 如果 ‘home’ 是一个绝对路径，并且 *note PYTHONHOME: 4de. 未设置，则
     在推断起始位置时使用此路径而不是主可执行文件的路径。

这一切的最终结果是：

   * 运行 ‘python.exe’ ，或主Python目录中的任何其他.exe（安装版本，或直
     接来自PCbuild目录）时，推导出核心路径，并忽略注册表中的核心路径。始
     终读取注册表中的其他“应用程序路径”。

   * 当Python托管在另一个.exe（不同的目录，通过COM嵌入等）时，将不会推断
     出“Python Home”，因此使用了来自注册表的核心路径。始终读取注册表中的
     其他“应用程序路径”。

   * 如果Python找不到它的主目录并且没有注册表值（冻结的.exe，一些非常奇
     怪的安装设置），那么你会得到一条带有一些默认但相对的路径的路径。

对于那些想要将Python捆绑到其应用程序或发行版中的人，以下建议将防止与其他
安装冲突：

   * 在您的可执行文件中包含一个 ‘._pth’ 文件，其中包含目录。这将忽略注册
     表和环境变量中列出的路径，并忽略 *note site: ec. ，除非列出 ‘import
     site’ 。

   * 如果你在自己的可执行文件中加载 ‘python3.dll’ 或 ‘python37.dll’ ，在
     *note Py_Initialize(): 441. 之前，要显式调用 *note Py_SetPath():
     274. 或（至少） *note Py_SetProgramName(): f99.

   * 清除 和/或 覆盖 *note PYTHONPATH: 95b. 并在启动来自应用程序的
     ‘python.exe’ 之前设置 *note PYTHONHOME: 4de. 。

   * 如果您不能使用前面的建议（例如，您是一个允许人们直接运行
     ‘python.exe’ 的分发版），请确保安装目录中存在 landmark 文件
     (‘Lib\os.py’)。 （请注意，在 ZIP 文件中不会检测到该文件，但会检测到
     正确命名的 ZIP 文件。）

这些将确保系统范围安装中的文件不会优先于与应用程序捆绑在一起的标准库的副
本。否则，用户可能会在使用您的应用程序时遇到问题请注意，第一个建议是最好
的，因为其他建议可能仍然容易受到注册表和用户站点包中的非标准路径的影响。

     在 3.6 版更改:

        * 添加 ‘._pth’ 文件支持并从 ‘pyvenv.cfg’ 中删除 ‘applocal’ 选项

        * 当直接与可执行文件相邻时，添加 ‘pythonXX.zip’ 作为潜在的
          landmark 。

     3.6 版后已移除: 在 ‘Modules’ （不是 ‘PythonPath’ ）下的注册表中指定
     的模块可以通过以下方式导入 *note
     importlib.machinery.WindowsRegistryFinder: 5ee. 。在Windows上，此查
     找程序在3.6.0及更早版本的可用，但可能需要在将来显式添加到 *note
     sys.meta_path: 5ef.


File: python.info,  Node: 附加模块,  Next: 在Windows上编译Python,  Prev: 查找模块,  Up: 在Windows上使用 Python

3.3.10 附加模块
---------------

尽管Python的目标是在所有平台中都可移植，但是Windows有一些独特的特性。在
标准库和外部都有一些模块和代码片段在使用这些特性。

特定于Windows的标准模块记录在 *note Windows系统相关模块: 13a6. 中。

* Menu:

* PyWin32::
* cx_Freeze::
* WConio::


File: python.info,  Node: PyWin32,  Next: cx_Freeze,  Up: 附加模块

3.3.10.1 PyWin32
................

Mark Hammond 的 PyWin32(1) 模块是一组用于高级Windows特定支持的模块。这包
括以下实用程序：

   * 组件对象模型(2) (COM)

   * Win32 API 调用

   * 注册

   * 事件日志

   * Microsoft Foundation Classes(3) (MFC) 用户界面

PythonWin(4) 是PyWin32附带的一个示例MFC应用程序。它是一个内置调试器的可
嵌入IDE。

参见
....

Win32 How Do I...?(5)

     Tim Golden 著

Python and COM(6)

     David 和 Paul Boddie 著

   ---------- Footnotes ----------

   (1) https://pypi.org/project/pywin32

   (2) 
https://docs.microsoft.com/en-us/windows/desktop/com/component-object-model–com–portal

   (3) https://msdn.microsoft.com/en-us/library/fe1cf721%28VS.80%29.aspx

   (4) 
https://web.archive.org/web/20060524042422/https://www.python.org/windows/pythonwin/

   (5) http://timgolden.me.uk/python/win32_how_do_i.html

   (6) http://www.boddie.org.uk/python/COM.html


File: python.info,  Node: cx_Freeze,  Next: WConio,  Prev: PyWin32,  Up: 附加模块

3.3.10.2 cx_Freeze
..................

cx_Freeze(1) 是一个 *note distutils: 39. 的扩展 (参见 *note 扩展
Distutils: 13a9.)，它将 Python 脚本包装成可执行的 Windows 程序
(‘`*'.exe’ 文件)。 完成此操作后，你就可以分发你的应用程序而无需用户安装
Python。

   ---------- Footnotes ----------

   (1) https://cx-freeze.readthedocs.io/en/latest/


File: python.info,  Node: WConio,  Prev: cx_Freeze,  Up: 附加模块

3.3.10.3 WConio
...............

由于Python的高级终端处理层 *note curses: 2c. 仅限于类Unix系统，因此
Windows还有一个独立的库：用于Python的Windows 控制台 I/O .

WConio(1) 是Turbo-C的 ‘CONIO.H’ 装饰器,用于创建文本用户界面。

   ---------- Footnotes ----------

   (1) http://newcenturycomputers.net/projects/wconio.html


File: python.info,  Node: 在Windows上编译Python,  Next: 其他平台,  Prev: 附加模块,  Up: 在Windows上使用 Python

3.3.11 在Windows上编译Python
----------------------------

如果你想自己编译CPython，首先要做的是获取 source(1). 。您可以下载最新版
本的源代码，也可以重新签出 checkout(2). 。

源代码树包含Microsoft Visual Studio 2015的构建解决方案和项目文件，它是用
于构建官方Python版本的编译器。这些文件位于 ‘PCbuild’ 目录中。

检查 ‘PCbuild/readme.txt’ 以获取有关构建过程的一般信息。

有关扩展模块，请参阅 *note 在Windows平台编译C和C++扩展: 13ac. 。

参见
....

Python + Windows + distutils + SWIG + gcc MinGW(3)

     或 "Creating Python extensions in C/C++ with SWIG and compiling
     them with MinGW gcc under Windows" 或 "Installing Python extension
     with distutils and without Microsoft Visual C++" by Sébastien
     Sauvage, 2003

   ---------- Footnotes ----------

   (1) https://www.python.org/downloads/source/

   (2) https://devguide.python.org/setup/#getting-the-source-code

   (3) http://sebsauvage.net/python/mingw.html


File: python.info,  Node: 其他平台,  Prev: 在Windows上编译Python,  Up: 在Windows上使用 Python

3.3.12 其他平台
---------------

随着Python的不断发展，不再支持以前曾经支持的一些平台（由于缺少用户或开发
人员）。检查 PEP 11(1) 了解所有不支持的平台的详细信息。

   * Windows CE(2) 仍然受支持。

   * Cygwin(3) 安装包也提供安装Python解释器 (cf.  Cygwin package
     source(4), Maintainer releases(5))

有关具有预编译安装程序平台的详细信息，请参阅 Python for Windows(6)

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0011

   (2) http://pythonce.sourceforge.net/

   (3) https://cygwin.com/

   (4) 
ftp://ftp.uni-erlangen.de/pub/pc/gnuwin32/cygwin/mirrors/cygnus/release/python

   (5) http://www.tishler.net/jason/software/python/

   (6) https://www.python.org/downloads/windows/


File: python.info,  Node: 在苹果系统上使用 Python,  Next: 编辑器和集成开发环境,  Prev: 在Windows上使用 Python,  Up: Python安装和使用

3.4 在苹果系统上使用 Python
===========================


作者: Bob Savage <<bobsavage@mac.com>>

运行 Mac OS X 的 Macintosh上 的 Python 原则上与任何其他 Unix 平台上的
Python 非常相似，但是还有一些额外的功能，例如 IDE 和包管理器，值得一提。

* Menu:

* 获取和安装 MacPython::
* IDE::
* 安装额外的 Python 包::
* Mac 上的图形界面编程::
* 在 Mac 上分发 Python 应用程序::
* 其他资源::


File: python.info,  Node: 获取和安装 MacPython,  Next: IDE,  Up: 在苹果系统上使用 Python

3.4.1 获取和安装 MacPython
--------------------------

Mac OS X 10.8 附带 Apple 预安装的 Python 2.7 。 如果你愿意，可以从
Python 网站（ ‘https://www.python.org’ ）安装最新版本的 Python 3 。
Python 的当前“通用二进制”版本可以在 Mac 的新 Intel 和传统 PPC CPU 上本地
运行。

你安装后得到的东西有：

   * 会有一个 ‘Python 3.8’ 文件夹在你的 ‘Applications’ 文件夹中。 在这里
     你可以找到 IDLE，它是作为官方 Python 发行版标准组成部分的开发环境；
     以及 PythonLauncher，它负责处理在 Finder 中双击 Python 脚本的操作。

   * 框架 ‘/Library/Frameworks/Python.framework’ ，包括 Python 可执行文
     件和库。安装程序将此位置添加到 shell 路径。 要卸载 MacPython ，你可
     以简单地移除这三个项目。 Python 可执行文件的符号链接放在
     /usr/local/bin/ 中。

Apple 提供的 Python 版本分别安装在
‘/System/Library/Frameworks/Python.framework’ 和 ‘/usr/bin/python’ 中。
你永远不应修改或删除这些内容，因为它们由 Apple 控制并由 Apple 或第三方软
件使用。 请记住，如果你选择从 python.org 安装较新的 Python 版本，那么你
的计算机上将安装两个不同但都有用的 Python ，因此你的路径和用法与你想要执
行的操作一致非常重要。

IDLE 包含一个帮助菜单，允许你访问 Python 文档。 如果您是 Python 的新手，
你应该开始阅读该文档中的教程介绍。

如果你熟悉其他 Unix 平台上的 Python ，那么你应该阅读有关从 Unix shell 运
行 Python 脚本的部分。

* Menu:

* 如何运行 Python 脚本::
* 运行有图形界面的脚本::
* 配置::


File: python.info,  Node: 如何运行 Python 脚本,  Next: 运行有图形界面的脚本,  Up: 获取和安装 MacPython

3.4.1.1 如何运行 Python 脚本
............................

在 Mac OS X 上开始使用 Python 的最佳方法是通过 IDLE 集成开发环境，参见
*note IDE: 13b4. 部分，并在 IDE 运行时使用“帮助”菜单。

如果要从终端窗口命令行或 Finder 运行 Python 脚本，首先需要一个编辑器来创
建脚本。 Mac OS X 附带了许多标准的 Unix 命令行编辑器，如 ‘vim’ 和
‘emacs’ 。 如果你想要一个更 Mac 化的编辑器，那么:program:‘BBEdit’ 或来自
Bare Bones Software 的 ‘TextWrangler’ （参见
‘http://www.barebones.com/products/bbedit/index.html’ ）是不错的选择 ，
就如 ‘TextMate`（参见 https://macromates.com/ ）。 其他编辑器包括
:program:`Gvim’ （ ‘http://macvim-dev.github.io/macvim/’ ）和 ‘Aquamacs’
（ ‘http://aquamacs.org/’ ）。

要从终端窗口运行脚本，必须确保:file:‘/usr/local/bin’ 位于 shell 搜索路径
中。

要从 Finder 运行你的脚本，你有两个选择：

   * 把脚本拖拽到 ‘PythonLauncher’

   * 选择 ‘PythonLauncher’ 作为通过 finder Info 窗口打开脚本（或任何 .py
     脚本）的默认应用程序，然后双击脚本。 ‘PythonLauncher’ 有各种首选项
     来控制脚本的启动方式。 拖拽方式允许你为一次调用更改这些选项，或使用
     其“首选项”菜单全局更改内容。


File: python.info,  Node: 运行有图形界面的脚本,  Next: 配置,  Prev: 如何运行 Python 脚本,  Up: 获取和安装 MacPython

3.4.1.2 运行有图形界面的脚本
............................

对于旧版本的 Python ，你需要注意一个 Mac OS X 的怪异之处：与 Aqua 窗口管
理器通信的程序（换而言之，任何具有图形界面的程序）需要以特殊方式运行。 使
用 ‘pythonw’ 而不是 ‘python’ 来启动这样的脚本。

对于Python 3.8，可以使用 ‘python’ 或 ‘pythonw’


File: python.info,  Node: 配置,  Prev: 运行有图形界面的脚本,  Up: 获取和安装 MacPython

3.4.1.3 配置
............

OS X 上的 Python 遵循所有标准的 Unix 环境变量，例如 *note PYTHONPATH:
95b. ，但是为 Finder 启动的程序设置这些变量是非标准的，因为 Finder 在启
动时不读取你的 ‘.profile’ 或 ‘.cshrc’ 。你需要创建一个文件
‘~/.MacOSX/environment.plist’ 。 有关详细信息，请参阅 Apple 的技术文档
QA1067 。

更多关于在 MacPython 中安装 Python 包的信息，参阅 *note 安装额外的
Python 包: 13b8. 部分。


File: python.info,  Node: IDE,  Next: 安装额外的 Python 包,  Prev: 获取和安装 MacPython,  Up: 在苹果系统上使用 Python

3.4.2 IDE
---------

MacPython 附带标准的 IDLE 开发环境。 有关使用 IDLE 的详细介绍，请访问
‘http://www.hashcollision.org/hkn/python/idle_intro/index.html’ 。


File: python.info,  Node: 安装额外的 Python 包,  Next: Mac 上的图形界面编程,  Prev: IDE,  Up: 在苹果系统上使用 Python

3.4.3 安装额外的 Python 包
--------------------------

有几个方法可以安装额外的 Python 包：

   * 可以通过标准的 Python distutils 模式（ ‘python setup.py install’ ）
     安装软件包。

   * 许多包也可以通过 ‘setuptools’ 扩展或 ‘pip’ 包装器安装，请参阅
     ‘https://pip.pypa.io/’ 。


File: python.info,  Node: Mac 上的图形界面编程,  Next: 在 Mac 上分发 Python 应用程序,  Prev: 安装额外的 Python 包,  Up: 在苹果系统上使用 Python

3.4.4 Mac 上的图形界面编程
--------------------------

使用 Python 在 Mac 上构建 GUI 应用程序有多种选择。

`PyObjC' 是一个 Python 到 Apple 的 Objective-C/Cocoa 框架的绑定，这是大
多数现代 Mac 开发的基础。 有关 PyObjC 的信息，请访问
‘https://pypi.org/project/pyobjc/’。

标准的 Python GUI 工具包是 *note tkinter: 10d. ，基于跨平台的 Tk 工具包
（ ‘https://www.tcl.tk’ ）。 Apple 的 OS X 捆绑了 Aqua 原生版本的 Tk ，
最新版本可以从 ‘https://www.activestate.com’ 下载和安装；它也可以从源代
码构建。

`wxPython' 是另一种流行的跨平台 GUI 工具包，可在 Mac OS X 上本机运行。软
件包和文档可从 ‘https://www.wxpython.org’ 获得。

`PyQt' 是另一种流行的跨平台 GUI 工具包，可在 Mac OS X 上本机运行。更多信
息可在 ‘https://riverbankcomputing.com/software/pyqt/intro’ 上找到。


File: python.info,  Node: 在 Mac 上分发 Python 应用程序,  Next: 其他资源,  Prev: Mac 上的图形界面编程,  Up: 在苹果系统上使用 Python

3.4.5 在 Mac 上分发 Python 应用程序
-----------------------------------

在 Mac 上部署独立 Python 应用程序的标准工具是 ‘py2app’ 。有关安装和使用
py2app 的更多信息，请访问 ‘http://undefined.org/python/#py2app’ 。


File: python.info,  Node: 其他资源,  Prev: 在 Mac 上分发 Python 应用程序,  Up: 在苹果系统上使用 Python

3.4.6 其他资源
--------------

MacPython 邮件列表是 Mac 上 Python 用户和开发人员的优秀支持资源：

‘https://www.python.org/community/sigs/current/pythonmac-sig/’

另一个有用的资源是 MacPython wiki ：

‘https://wiki.python.org/moin/MacPython’


File: python.info,  Node: 编辑器和集成开发环境,  Prev: 在苹果系统上使用 Python,  Up: Python安装和使用

3.5 编辑器和集成开发环境
========================

有很多支持Python编程语言的集成开发环境。大多数编辑器和集成开发环境支持语
法高亮，调试工具和 PEP 8(1) 检查。

请访问 Python Editors(2) 和 Integrated Development Environments(3) 以获
取完整列表。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0008

   (2) https://wiki.python.org/moin/PythonEditors

   (3) https://wiki.python.org/moin/IntegratedDevelopmentEnvironments


File: python.info,  Node: Python语言参考,  Next: Python 标准库,  Prev: Python安装和使用,  Up: Top

4 Python语言参考
****************

本参考手册描述了 Python 的语法和“核心语义”。本参考是简洁的，但试图做到准
确和完整。 非必要的内建对象类型和内建函数、模块的语义描述在 *note Python
标准库: 120b. 中。有关该语言的非正式介绍，请参阅 *note Python 教程:
120a. 。对 C 或 C++ 程序员，还有两个额外的手册： *note 扩展和嵌入 Python
解释器: 120d. 概述了如何编写一个 Python 扩展模块，*note Python/C API
参考手册: 120e. 详细介绍了 C/C++ 中可用的接口。

* Menu:

* 概述: 概述<5>.
* 词法分析::
* 数据模型::
* 执行模型::
* 导入系统::
* 表达式::
* 简单语句::
* 复合语句::
* 最高层级组件::
* 完整的语法规范::


File: python.info,  Node: 概述<5>,  Next: 词法分析,  Up: Python语言参考

4.1 概述
========

本参考手册是对 Python 编程语言的描述。并不适宜作为教程使用。

我希望尽可能地保证内容精确无误，但还是选择使用自然词句进行描述，正式的规
格定义仅用于句法和词法解析。这样应该能使文档对于普通人来说更易理解，但也
可能导致一些歧义。因此，如果你是来自火星并且想凭借这份文档把 Python 重新
实现一遍，也许有时需要自行猜测，实际上最终大概会得到一个十分不同的语言。
而在另一方面，如果你正在使用 Python 并且想了解有关该语言特定领域的精确规
则，你应该能够在这里找到它们。如果你希望查看对该语言更正式的定义，也许你
可以花些时间自己写上一份 — 或者发明一台克隆机器 :-)

在语言参考文档里加入过多的实现细节是很危险的 — 具体实现可能发生改变，对
同一语言的其他实现可能使用不同的方式。而在另一方面，CPython 是得到广泛使
用的 Python 实现 (然而其他一些实现的拥护者也在增加)，其中的特殊细节有时
也值得一提，特别是当其实现方式导致额外的限制时。因此，你会发现在正文里不
时会跳出来一些简短的 "实现注释"。

每种 Python 实现都带有一些内置和标准的模块。相关的文档可参见 *note
Python 标准库: 120b. 索引。少数内置模块也会在此提及，如果它们同语言描述
存在明显的关联。

* Menu:

* 其他实现::
* 标注::


File: python.info,  Node: 其他实现,  Next: 标注,  Up: 概述<5>

4.1.1 其他实现
--------------

虽然官方 Python 实现差不多得到最广泛的欢迎，但也有一些其他实现对特定领域
的用户来说更具吸引力。

知名的实现包括:

CPython

     这是最早出现并持续维护的 Python 实现，以 C 语言编写。新的语言特性通
     常在此率先添加。

Jython

     以 Java 语言编写的 Python 实现。此实现可以作为 Java 应用的一个脚本
     语言，或者可以用来创建需要 Java 类库支持的应用。想了解更多信息可访
     问 Jython 网站(1)。

Python for .NET

     此实现实际上使用了 CPython 实现，但是属于 .NET 托管应用并且可以引入
     .NET 类库。它的创造者是 Brian Lloyd。想了解详情可访问 Python for
     .NET 主页(2)。

IronPython

     另一个 .NET 的 Python 实现，与 Python.NET 不同点在于它是生成 IL 的
     完全 Python 实现，并且将 Python 代码直接编译为 .NET 程序集。它的创
     造者就是当初创造 Jython 的 Jim Hugunin。想了解详情可访问 IronPython
     网站(3)。

PyPy

     完全使用 Python 语言编写的 Python 实现。它支持多个其他实现所没有的
     高级特性，例如非栈式支持和 JIT 编译器等。此项目的目标之一是通过允许
     方便地修改解释器 (因为它是用 Python 编写的)，鼓励该对语言本身进行试
     验。想了解详情可访问 PyPy 项目主页(4)。

以上这些实现都可能在某些方面与此参考文档手册的描述有所差异，或是引入了超
出标准 Python 文档范围的特定信息。请参考它们各自的专门文档，以确定你正在
使用的这个实现有哪些你需要了解的东西。

   ---------- Footnotes ----------

   (1) http://www.jython.org/

   (2) https://pythonnet.github.io/

   (3) http://ironpython.net/

   (4) http://pypy.org/


File: python.info,  Node: 标注,  Prev: 其他实现,  Up: 概述<5>

4.1.2 标注
----------

句法和词法解析的描述采用经过改进的 BNF 语法标注。这包含以下定义样式:

     name      ::= lc_letter (lc_letter | "_")*
     lc_letter ::= "a"..."z"

第一行表示 ‘name’ 是一个 ‘lc_letter’ 之后跟零个或多个 ‘lc_letter’ 和下划
线。而一个 ‘lc_letter’ 则是任意单个 ‘'a'’ 至 ‘'z'’ 字符。(实际上在本文档
中始终采用此规则来定义词法和语法规则的名称。)

每条规则的开头是一个名称 (即该规则所定义的名称) 加上 ‘::=’。 竖线 (‘|’)
被用来分隔可选项，它是此标注中绑定程度最低的操作符。 星号 (‘*’) 表示前一
项的零次或多次重复，类似地，加号 (‘+’) 表示一次或多次重复，而由方括号括
起的内容 (‘[ ]’) 表示出现零次或一次 (或者说，这部分内容是可选的)。 ‘*’ 和
‘+’ 操作符的绑定是最紧密的，圆括号用于分组。 字符串字面值包含在引号内。
空格的作用仅限于分隔形符。 每条规则通常为一行，有许多个可选项的规则可能
会以竖线为界分为多行。

在词法定义中 (如上述示例)，还额外使用了两个约定: 由三个点号分隔的两个字
符字面值表示在指定 (闭) 区间范围内的任意单个 ASCII 字符。由尖括号
(‘<...>’) 括起来的内容是对于所定义符号的非正式描述；即可以在必要时用来说
明 ’控制字符’ 的意图。

虽然所用的标注方式几乎相同，但是词法定义和句法定义是存在很大区别的: 词法
定义作用于输入源中单独的字符，而句法定义则作用于由词法分析所生成的形符流
。在下一章节 ("词法分析") 中使用的 BNF 全部都是词法定义；在之后的章节中
使用的则是句法定义。


File: python.info,  Node: 词法分析,  Next: 数据模型,  Prev: 概述<5>,  Up: Python语言参考

4.2 词法分析
============

Python 程序由一个 `解析器' 读取。输入到解析器的是一个由 `词法分析器' 所
生成的 `形符' 流，本章将描述词法分析器是如何将一个文件拆分为一个个形符的
。

Python 会将读取的程序文本转为 Unicode 码点；源文件的文本编码可由编码声明
指定，默认为 UTF-8，详情见 PEP 3120(1)。如果源文件无法被解码，将会引发
*note SyntaxError: 460.。

* Menu:

* 行结构::
* 其他形符::
* 标识符和关键字::
* 字面值::
* 运算符::
* 分隔符::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3120


File: python.info,  Node: 行结构,  Next: 其他形符,  Up: 词法分析

4.2.1 行结构
------------

一个 Python 程序可分为许多 `逻辑行'。

* Menu:

* 逻辑行::
* 物理行::
* 注释::
* 编码声明::
* 显式的行拼接::
* 隐式的行拼接::
* 空白行::
* 缩进::
* 形符之间的空白::


File: python.info,  Node: 逻辑行,  Next: 物理行,  Up: 行结构

4.2.1.1 逻辑行
..............

逻辑行的结束是以 NEWLINE 形符表示的。语句不能跨越逻辑行的边界，除非其语
法允许包含 NEWLINE (例如复合语句可由多行子语句组成)。一个逻辑行可由一个
或多个 `物理行' 按照明确或隐含的 `行拼接' 规则构成。


File: python.info,  Node: 物理行,  Next: 注释,  Prev: 逻辑行,  Up: 行结构

4.2.1.2 物理行
..............

物理行是以一个行终止序列结束的字符序列。在源文件和字符串中，可以使用任何
标准平台上的行终止序列 - Unix 所用的 ASCII 字符 LF (换行), Windows 所用
的 ASCII 字符序列 CR LF (回车加换行), 或者旧 Macintosh 所用的 ASCII 字符
CR (回车)。所有这些形式均可使用，无论具体平台。输入的结束也会被作为最后
一个物理行的隐含终止标志。

当嵌入 Python 时，源码字符串传入 Python API 应使用标准 C 的传统换行符 (即
‘\n’，表示 ASCII 字符 LF 作为行终止标志)。


File: python.info,  Node: 注释,  Next: 编码声明,  Prev: 物理行,  Up: 行结构

4.2.1.3 注释
............

一条注释以不包含在字符串字面值内的井号 (‘#’) 开头，并在物理行的末尾结束
。 一条注释标志着逻辑行的结束，除非存在隐含的行拼接规则。 注释在语法分析
中会被忽略。


File: python.info,  Node: 编码声明,  Next: 显式的行拼接,  Prev: 注释,  Up: 行结构

4.2.1.4 编码声明
................

如果一条注释位于 Python 脚本的第一或第二行，并且匹配正则表达式
‘coding[=:]\s*([-\w.]+)’，这条注释会被作为编码声明来处理；上述表达式的第
一组指定了源码文件的编码。编码声明必须独占一行。如果它是在第二行，则第一
行也必须是注释。推荐的编码声明形式如下

     # -*- coding: <encoding-name> -*-

这也是 GNU Emacs 认可的形式，以及

     # vim:fileencoding=<encoding-name>

这是 Bram Moolenaar 的 VIM 认可的形式。

如果没有编码声明，则默认编码为 UTF-8。此外，如果文件的首字节为 UTF-8 字
节顺序标志 (‘b'\xef\xbb\xbf'’)，文件编码也声明为 UTF-8 (这是 Microsoft 的
‘notepad’ 等软件支持的形式)。

编码声明指定的编码名称必须是 Python 所认可的编码。所有词法分析将使用此编
码，包括语义字符串、注释和标识符。


File: python.info,  Node: 显式的行拼接,  Next: 隐式的行拼接,  Prev: 编码声明,  Up: 行结构

4.2.1.5 显式的行拼接
....................

两个或更多个物理行可使用反斜杠字符 (‘\’) 拼接为一个逻辑行，规则如下: 当
一个物理行以一个不在字符串或注释内的反斜杠结尾时，它将与下一行拼接构成一
个单独的逻辑行，反斜杠及其后的换行符会被删除。例如:

     if 1900 < year < 2100 and 1 <= month <= 12 \
        and 1 <= day <= 31 and 0 <= hour < 24 \
        and 0 <= minute < 60 and 0 <= second < 60:   # Looks like a valid date
             return 1

以反斜杠结束的行不能带有注释。反斜杠不能用来拼接注释。反斜杠不能用来拼接
形符，字符串除外 (即原文字符串以外的形符不能用反斜杠分隔到两个物理行)。
不允许有原文字符串以外的反斜杠存在于物理行的其他位置。


File: python.info,  Node: 隐式的行拼接,  Next: 空白行,  Prev: 显式的行拼接,  Up: 行结构

4.2.1.6 隐式的行拼接
....................

圆括号、方括号或花括号以内的表达式允许分成多个物理行，无需使用反斜杠。例
如:

     month_names = ['Januari', 'Februari', 'Maart',      # These are the
                    'April',   'Mei',      'Juni',       # Dutch names
                    'Juli',    'Augustus', 'September',  # for the months
                    'Oktober', 'November', 'December']   # of the year

隐式的行拼接可以带有注释。后续行的缩进不影响程序结构。后续行也允许为空白
行。隐式拼接的行之间不会有 NEWLINE 形符。隐式拼接的行也可以出现于三引号
字符串中 (见下)；此情况下这些行不允许带有注释。


File: python.info,  Node: 空白行,  Next: 缩进,  Prev: 隐式的行拼接,  Up: 行结构

4.2.1.7 空白行
..............

一个只包含空格符，制表符，进纸符或者注释的逻辑行会被忽略 (即不生成
NEWLINE 形符)。在交互模式输入语句时，对空白行的处理可能会因读取-求值-打
印循环的具体实现方式而存在差异。在标准交互模式解释器中，一个完全空白的逻
辑行 (即连空格或注释都没有) 将会结束一条多行复合语句。


File: python.info,  Node: 缩进,  Next: 形符之间的空白,  Prev: 空白行,  Up: 行结构

4.2.1.8 缩进
............

一个逻辑行开头处的空白 (空格符和制表符) 被用来计算该行的缩进等级，以决定
语句段落的组织结构。

制表符会被 (从左至右) 替换为一至八个空格，这样缩进的空格总数为八的倍数
(这是为了与 Unix 所用的规则一致)。首个非空白字符之前的空格总数将确定该行
的缩进层次。一个缩进不可使用反斜杠进行多行拼接；首个反斜杠之前的空格将确
定缩进层次。

在一个源文件中如果混合使用制表符和空格符缩进，并使得确定缩进层次需要依赖
于制表符对应的空格数量设置，则被视为不合规则；此情况将会引发 *note
TabError: e7f.。

`跨平台兼容性注释:' 由于非 UNIX 平台上文本编辑器本身的特性，在一个源文件
中混合使用制表符和空格符是不明智的。另外也要注意不同平台还可能会显式地限
制最大缩进层级。

行首有时可能会有一个进纸符；它在上述缩进层级计算中会被忽略。处于行首空格
内其他位置的进纸符的效果未定义 (例如它可能导致空格计数重置为零)。

多个连续行各自的缩进层级将会被放入一个堆栈用来生成 INDENT 和 DEDENT 形符
，具体说明如下。

在读取文件的第一行之前，先向堆栈推入一个零值；它将不再被弹出。被推入栈的
层级数值从底至顶持续增加。每个逻辑行开头的行缩进层级将与栈顶行比较。如果
相同，则不做处理。如果新行层级较高，则会被推入栈顶，并生成一个 INDENT 形
符。如果新行层级较低，则 `应当' 是栈中的层级数值之一；栈中高于该层级的所
有数值都将被弹出，每弹出一级数值生成一个 DEDENT 形符。在文件末尾，栈中剩
余的每个大于零的数值生成一个 DEDENT 形符。

这是一个正确 (但令人迷惑) 的Python 代码缩进示例:

     def perm(l):
             # Compute the list of all permutations of l
         if len(l) <= 1:
                       return [l]
         r = []
         for i in range(len(l)):
                  s = l[:i] + l[i+1:]
                  p = perm(s)
                  for x in p:
                   r.append(l[i:i+1] + x)
         return r

以下示例显示了各种缩进错误:

      def perm(l):                       # error: first line indented
     for i in range(len(l)):             # error: not indented
         s = l[:i] + l[i+1:]
             p = perm(l[:i] + l[i+1:])   # error: unexpected indent
             for x in p:
                     r.append(l[i:i+1] + x)
                 return r                # error: inconsistent dedent

(实际上，前三个错误会被解析器发现；只有最后一个错误是由词法分析器发现的
— ‘return r’ 的缩进无法匹配弹出栈的缩进层级。)


File: python.info,  Node: 形符之间的空白,  Prev: 缩进,  Up: 行结构

4.2.1.9 形符之间的空白
......................

除非是在逻辑行的开头或字符串内，空格符、制表符和进纸符等空白符都同样可以
用来分隔形符。如果两个形符彼此相连会被解析为一个不同的形符，则需要使用空
白来分隔 (例如 ab 是一个形符，而 a b 是两个形符)。


File: python.info,  Node: 其他形符,  Next: 标识符和关键字,  Prev: 行结构,  Up: 词法分析

4.2.2 其他形符
--------------

除了 NEWLINE, INDENT 和 DEDENT，还存在以下类别的形符: `标识符', `关键字
', `字面值', `运算符' 以及 `分隔符'。 空白字符 (之前讨论过的行终止符除外
) 不属于形符，而是用来分隔形符。如果存在二义性，将从左至右读取尽可能长的
合法字符串组成一个形符。


File: python.info,  Node: 标识符和关键字,  Next: 字面值,  Prev: 其他形符,  Up: 词法分析

4.2.3 标识符和关键字
--------------------

标识符 (或者叫做 `名称') 由以下词法定义进行描述。

Python 中的标识符语法是基于 Unicode 标准附件 UAX-31，并加入了下文所定义
的细化与修改；更多细节还可参见 PEP 3131(1) 。

在 ASCII 范围内 (U+0001..U+007F)，可用于标识符的字符与 Python 2.x 一致:
大写和小写字母 ‘A’ 至 ‘Z’，下划线 ‘_’ 以及数字 ‘0’ 至 ‘9’，但不可以数字
打头。

Python 3.0 引入了 ASCII 范围以外的额外字符 (见 PEP 3131(2))。这些字符的
分类使用包含于 *note unicodedata: 11b. 模块中的 Unicode 字符数据库版本。

标识符的长度没有限制。对大小写敏感。

     identifier   ::= xid_start xid_continue*
     id_start     ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>
     id_continue  ::= <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>
     xid_start    ::= <all characters in id_start whose NFKC normalization is in "id_start xid_continue*">
     xid_continue ::= <all characters in id_continue whose NFKC normalization is in "id_continue*">

上文所用 Unicode 类别码的含义:

   * `Lu' - 大写字母

   * `Ll' - 小写字母

   * `Lt' - 词首大写字母

   * `Lm' - 修饰字母

   * `Lo' - 其他字母

   * `Nl' - 字母数字

   * `Mn' - 非空白标识

   * `Mc' - 含空白标识

   * `Nd' - 十进制数字

   * `Pc' - 连接标点

   * `Other_ID_Start' - 由 PropList.txt(3) 定义的显式字符列表，用来支持
     向下兼容

   * `Other_ID_Continue' - 同上

所有标识符在解析时会被转换为规范形式 NFKC；标识符的比较都是基于 NFKC。

Unicode 4.1 中所有可用的标识符字符列表可参见以下非正式 HTML 文件
‘https://www.unicode.org/Public/13.0.0/ucd/DerivedCoreProperties.txt’

* Menu:

* 关键字::
* 保留的标识符类::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3131

   (2) https://www.python.org/dev/peps/pep-3131

   (3) http://www.unicode.org/Public/12.1.0/ucd/PropList.txt


File: python.info,  Node: 关键字,  Next: 保留的标识符类,  Up: 标识符和关键字

4.2.3.1 关键字
..............

以下标识符被作为语言的保留字或称 `关键字'，不可被用作普通标识符。关键字
的拼写必须与这里列出的完全一致。

     False      await      else       import     pass
     None       break      except     in         raise
     True       class      finally    is         return
     and        continue   for        lambda     try
     as         def        from       nonlocal   while
     assert     del        global     not        with
     async      elif       if         or         yield


File: python.info,  Node: 保留的标识符类,  Prev: 关键字,  Up: 标识符和关键字

4.2.3.2 保留的标识符类
......................

某些标识符类 (除了关键字) 具有特殊的含义。这些标识符类的命名模式是以下划
线字符打头和结尾:

‘_*’

     不会被 ‘from module import *’ 导入。特殊标识符 ‘_’ 在交互式解释器中
     被用来存放最近一次求值结果；它保存在 *note builtins: 13. 模块中。当
     不处于交互模式时，‘_’ 无特殊含义也没有预定义。参见 *note import
     语句: c25.。

          注解: ‘_’ 作为名称常用于连接国际化文本；请参看 *note gettext:
          89. 模块文档了解有关此约定的详情。

‘__*__’

     系统定义的名称，在非正式场合下被叫做 "dunder" 名称。 这些名称是由解
     释器及其实现（包括标准库）定义的。 现有系统定义名称相关的讨论请参见
     *note 特殊方法名称: 516. 等章节。 未来的 Python 版本中还将定义更多
     此类名称。 任何情况下 `任何' 不遵循文档所显式指明的 ‘__*__’ 名称使
     用方式都可能导致无警告的错误。

‘__*’

     类的私有名称。这种名称在类定义中使用时，会以一种混合形式重写以避免
     在基类及派生类的 "私有" 属性之间出现名称冲突。参见 *note
     标识符（名称）: 13ef.。


File: python.info,  Node: 字面值,  Next: 运算符,  Prev: 标识符和关键字,  Up: 词法分析

4.2.4 字面值
------------

字面值用于表示一些内置类型的常量。

* Menu:

* 字符串和字节串字面值::
* 字符串字面值拼接::
* 格式化字符串字面值::
* 数字字面值::
* 整型数字面值::
* 浮点数字面值::
* 虚数字面值::


File: python.info,  Node: 字符串和字节串字面值,  Next: 字符串字面值拼接,  Up: 字面值

4.2.4.1 字符串和字节串字面值
............................

字符串字面值由以下词法定义进行描述:

     stringliteral   ::= [stringprefix](shortstring | longstring)
     stringprefix    ::= "r" | "u" | "R" | "U" | "f" | "F"
                         | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"
     shortstring     ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'
     longstring      ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
     shortstringitem ::= shortstringchar | stringescapeseq
     longstringitem  ::= longstringchar | stringescapeseq
     shortstringchar ::= <any source character except "\" or newline or the quote>
     longstringchar  ::= <any source character except "\">
     stringescapeseq ::= "\" <any source character>

     bytesliteral   ::= bytesprefix(shortbytes | longbytes)
     bytesprefix    ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
     shortbytes     ::= "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
     longbytes      ::= "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
     shortbytesitem ::= shortbyteschar | bytesescapeseq
     longbytesitem  ::= longbyteschar | bytesescapeseq
     shortbyteschar ::= <any ASCII character except "\" or newline or the quote>
     longbyteschar  ::= <any ASCII character except "\">
     bytesescapeseq ::= "\" <any ASCII character>

这些条目中未提及的一个语法限制是 *note stringprefix: 13f5. 或 *note
bytesprefix: 13fe. 与字面值的剩余部分之间不允许有空白。源字符集是由编码
声明定义的；如果源文件中没有编码声明则默认为 UTF-8；参见 *note 编码声明:
13d7.。

自然语言描述: 两种字面值都可以用成对单引号 (‘'’) 或双引号 (‘"’) 来标示首
尾。它们也可以用成对的连续三个单引号或双引号来标示首尾 (这通常被称为 `三
引号字符串')。反斜杠 (‘\’) 字符被用来对特殊含义的字符进行转义，例如换行
，反斜杠本身或是引号等字符。

字节串字面值总是带有前缀 ‘'b'’ 或 ‘'B'’；它们生成 *note bytes: 33a. 类型
而非 *note str: 339. 类型的实例。它们只能包含 ASCII 字符；字节对应数值在
128及以上必须以转义形式来表示。

字符串和字节串字面值都可以带有前缀 ‘'r'’ 或 ‘'R'’；这种字符串被称为 `原
始字符串' 其中的反斜杠会被当作其本身的字面字符来处理。因此在原始字符串字
面值中，‘'\U'’ 和 ‘'\u'’ 转义形式不会被特殊对待。由于 Python 2.x 的原始
统一码字面值的特性与 Python 3.x 不一致，‘'ur'’ 语法已不再被支持。

3.3 新版功能: 新加入了表示原始字节串的 ‘'rb'’ 前缀，与 ‘'br'’ 的意义相同
。

3.3 新版功能: 对旧式统一码字面值 (‘u'value'’) 的支持被重新引入以简化
Python 2.x 和 3.x 代码库的同步维护。详情见 PEP 414(1)。

包含 ‘'f'’ 或 ‘'F'’ 前缀的字符串字面值称为 `格式化字符串字面值'；参见
*note 格式化字符串字面值: 15d.。‘'f'’ 可与 ‘'r'’ 连用，但不能与 ‘'b'’ 或
‘'u'’ 连用，因此存在原始格式化字符串，但不存在格式化字节串字面值。

在三引号字面值中，允许存在未经转义的换行和引号 (并原样保留)，除非是未经
转义的连续三引号，这标示着字面值的结束。 ("引号" 是用来标示字面值的字符
，即 ‘'’ 或 ‘"’。)

除非带有 ‘'r'’ 或 ‘'R'’ 前缀，字符串和字节串字面值中的转义序列会基于类似
标准 C 中的转义规则来解读。可用的转义序列如下:

转义序列              含义                                  注释
                                                            
------------------------------------------------------------------------
                                                            
‘\newline’            反斜杠加换行全被忽略
                      
                                                            
‘\\’                  反斜杠 (‘\’)
                      
                                                            
‘\'’                  单引号 (‘'’)
                      
                                                            
‘\"’                  双引号 (‘"’)
                      
                                                            
‘\a’                  ASCII 响铃 (BEL)
                      
                                                            
‘\b’                  ASCII 退格 (BS)
                      
                                                            
‘\f’                  ASCII 进纸 (FF)
                      
                                                            
‘\n’                  ASCII 换行 (LF)
                      
                                                            
‘\r’                  ASCII 回车 (CR)
                      
                                                            
‘\t’                  ASCII 水平制表 (TAB)
                      
                                                            
‘\v’                  ASCII 垂直制表 (VT)
                      
                                                            
‘\ooo’                八进制数 `ooo' 码位的字符             (1,3)
                                                            
                                                            
‘\xhh’                十六进制数 `hh' 码位的字符            (2,3)
                                                            

仅在字符串字面值中可用的转义序列如下:

转义序列              含义                                  注释
                                                            
------------------------------------------------------------------------
                                                            
‘\N{name}’            Unicode 数据库中名称为 `name' 的字    (4)
                      符                                    
                      
                                                            
‘\uxxxx’              16位十六进制数 `xxxx' 码位的字符      (5)
                                                            
                                                            
‘\Uxxxxxxxx’          32位16进制数 `xxxxxxxx' 码位的字符    (6)
                                                            

注释:

  1. 与标准 C 一致，接受最多三个八进制数码。

  2. 与标准 C 不同，要求必须为两个十六进制数码。

  3. 在字节串字面值中，十六进制数和八进制数转义码以相应数值代表每个字节
     。在字符串字面值中，这些转义码以相应数值代表每个 Unicode 字符。

  4. 
     在 3.3 版更改: 加入了对别名 (2) 的支持。

  5. 要求必须为四个十六进制数码。

  6. 此方式可用来表示任意 Unicode 字符。要求必须为八个十六进制数码。

与标准 C 不同，所有无法识别的转义序列将原样保留在字符串中，也就是说，`反
斜杠会在结果中保留'。(这种方式在调试时很有用: 如果输错了一个转义序列，更
容易在输出结果中识别错误。) 另外要注意的一个关键点是：专用于字符串字面值
中的转义序列如果在字节串字面值中出现，会被归类为无法识别的转义序列。

     在 3.6 版更改: 无法识别的转义序列将引发 *note DeprecationWarning:
     279.。 在某个未来的 Python 版本中它们将引发 *note SyntaxWarning:
     192. 并最终将改为引发 *note SyntaxError: 460.。

即使在原始字面值中，引号也可以加上反斜杠转义符，但反斜杠会保留在输出结果
中；例如 ‘r"\""’ 是一个有效的字符串字面值，包含两个字符: 一个反斜杠和一
个双引号；而 ‘r"\"’ 不是一个有效的字符串字面值 (即便是原始字符串也不能以
奇数个反斜杠结束)。特别地，`一个原始字面值不能以单个反斜杠结束' (因为此
反斜杠会转义其后的引号字符)。还要注意一个反斜杠加一个换行在字面值中会被
解释为两个字符，而 `不是' 一个连续行。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0414

   (2) (1) ‘http://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt’


File: python.info,  Node: 字符串字面值拼接,  Next: 格式化字符串字面值,  Prev: 字符串和字节串字面值,  Up: 字面值

4.2.4.2 字符串字面值拼接
........................

多个相邻的字符串或字节串字面值 (以空白符分隔)，所用的引号可以彼此不同，
其含义等同于全部拼接为一体。因此， ‘"hello" 'world'’ 等同于
‘"helloworld"’。此特性可以减少反斜杠的使用，以方便地将很长的字符串分成多
个物理行，甚至每部分字符串还可分别加注释，例如:

     re.compile("[A-Za-z_]"       # letter or underscore
                "[A-Za-z0-9_]*"   # letter, digit or underscore
               )

注意此特性是在句法层面定义的，但是在编译时实现。在运行时拼接字符串表达式
必须使用 ’+’ 运算符。还要注意字面值拼接时每个部分可以使用不同的引号风格
(甚至混合使用原始字符串和三引号字符串)，格式化字符串字面值也可与普通字符
串字面值拼接。


File: python.info,  Node: 格式化字符串字面值,  Next: 数字字面值,  Prev: 字符串字面值拼接,  Up: 字面值

4.2.4.3 格式化字符串字面值
..........................

3.6 新版功能.

`格式化字符串字面值' 或称 `f-string' 是带有 ‘'f'’ 或 ‘'F'’ 前缀的字符串
字面值。这种字符串可包含替换字段，即以 ‘{}’ 标示的表达式。而其他字符串字
面值总是一个常量，格式化字符串字面值实际上是会在运行时被求值的表达式。

转义序列会像在普通字符串字面值中一样被解码 (除非字面值还被标示为原始字符
串)。解码之后，字符串内容所用的语法如下:

     f_string          ::= (literal_char | "{{" | "}}" | replacement_field)*
     replacement_field ::= "{" f_expression ["="] ["!" conversion] [":" format_spec] "}"
     f_expression      ::= (conditional_expression | "*" or_expr)
                             ("," conditional_expression | "," "*" or_expr)* [","]
                           | yield_expression
     conversion        ::= "s" | "r" | "a"
     format_spec       ::= (literal_char | NULL | replacement_field)*
     literal_char      ::= <any code point except "{", "}" or NULL>

字符串在花括号以外的部分按其字面值处理，除了双重花括号 ‘'{{'’ 或 ‘'}}'’
会被替换为相应的单个花括号。 单个左花括号 ‘'{'’ 标示一个替换字段，它以一
个 Python 表达式打头。 要同时显示表达式文本及其求值后的结果值（这在调试
时很有用），可以在表达式后加一个等于号 ‘'='’。 之后可能带有一个以叹号
‘'!'’ 标示的转换字段。 之后还可能带有一个以冒号 ‘':'’ 标示的格式说明符。
替换字段以一个右花括号 ‘'}'’ 作为结束。

格式化字符串字面值中的表达式会被当作包含在圆括号中的普通 Python 表达式一
样处理，但有少数例外。 空表达式不被允许，*note lambda: c37. 和赋值表达式
‘:=’ 必须显式地加上圆括号。 替换表达式可以包含换行（例如在三重引号字符串
中），但是不能包含注释。 每个表达式会在格式化字符串字面值所包含的位置按
照从左至右的顺序被求值。

在 3.7 版更改: 在 Python 3.7 之前， *note await: 1a4. 表达式包含 *note
async for: 2e4. 子句的推导式不允许在格式化字符串字面值表达式中使用，这是
因为具体实现存在一个问题。

在提供了等于号 ‘'='’ 的时候，输出将包含表达式文本，‘'='’ 以及求值结果。
左花括号 ‘'{'’ 之后包含在表达式中及 ‘'='’ 后的空格将在输出时被保留。 默
认情况下，‘'='’ 会导致表达式的 *note repr(): 7d5. 被使用，除非专门指定了
格式。 当指定了格式时默认会使用表达式的 *note str(): 339.，除非声明了转
换字段 ‘'!r'’。

3.8 新版功能: 等号 ‘'='’。

如果指定了转换符，表达式的求值结果会先转换再格式化。转换符 ‘'!s'’ 即对结
果调用 *note str(): 339.，‘'!r'’ 为调用 *note repr(): 7d5.，而 ‘'!a'’ 为
调用 *note ascii(): d54.。

在此之后结果会使用 *note format(): 4e3. 协议进行格式化。格式说明符会被传
入表达式或转换结果的 *note __format__(): 956. 方法。如果省略格式说明符则
会传入一个空字符串。然后格式化结果会包含在整个字符串最终的值当中。

顶层的格式说明符可以包含有嵌套的替换字段。这些嵌套字段也可以包含有自己的
转换字段和 *note 格式说明符: 4e6.，但不可再包含更深层嵌套的替换字段。这
里的 *note 格式说明符微型语言: 4e6. 与字符串 .format() 方法所使用的相同
。

格式化字符串字面值可以拼接，但是一个替换字段不能拆分到多个字面值。

一些格式化字符串字面值的示例:

     >>> name = "Fred"
     >>> f"He said his name is {name!r}."
     "He said his name is 'Fred'."
     >>> f"He said his name is {repr(name)}."  # repr() is equivalent to !r
     "He said his name is 'Fred'."
     >>> width = 10
     >>> precision = 4
     >>> value = decimal.Decimal("12.34567")
     >>> f"result: {value:{width}.{precision}}"  # nested fields
     'result:      12.35'
     >>> today = datetime(year=2017, month=1, day=27)
     >>> f"{today:%B %d, %Y}"  # using date format specifier
     'January 27, 2017'
     >>> f"{today=:%B %d, %Y}" # using date format specifier and debugging
     'today=January 27, 2017'
     >>> number = 1024
     >>> f"{number:#0x}"  # using integer format specifier
     '0x400'
     >>> foo = "bar"
     >>> f"{ foo = }" # preserves whitespace
     " foo = 'bar'"
     >>> line = "The mill's closed"
     >>> f"{line = }"
     'line = "The mill\'s closed"'
     >>> f"{line = :20}"
     "line = The mill's closed   "
     >>> f"{line = !r:20}"
     'line = "The mill\'s closed" '

与正常字符串字面值采用相同语法导致的一个结果就是替换字段中的字符不能与外
部的格式化字符串字面值所用的引号相冲突:

     f"abc {a["x"]} def"    # error: outer string literal ended prematurely
     f"abc {a['x']} def"    # workaround: use different quoting

格式表达式中不允许有反斜杠，这会引发错误:

     f"newline: {ord('\n')}"  # raises SyntaxError

想包含需要用反斜杠转义的值，可以创建一个临时变量。

     >>> newline = ord('\n')
     >>> f"newline: {newline}"
     'newline: 10'

格式化字符串字面值不可用作文档字符串，即便其中没有包含表达式。

     >>> def foo():
     ...     f"Not a docstring"
     ...
     >>> foo.__doc__ is None
     True

另请参见 PEP 498(1) 了解加入格式化字符串字面值的提议，以及使用了相关的格
式字符串机制的 *note str.format(): 4e2.。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0498


File: python.info,  Node: 数字字面值,  Next: 整型数字面值,  Prev: 格式化字符串字面值,  Up: 字面值

4.2.4.4 数字字面值
..................

数字字面值有三种类型: 整型数、浮点数和虚数。没有专门的复数字面值 (复数可
由一个实数加一个虚数合成)。

注意数字字面值并不包含正负号；‘-1’ 这样的负数实际上是由单目运算符 ’‘-’’
和字面值 ‘1’ 合成的。


File: python.info,  Node: 整型数字面值,  Next: 浮点数字面值,  Prev: 数字字面值,  Up: 字面值

4.2.4.5 整型数字面值
....................

整型数字面值由以下词法定义进行描述:

     integer      ::= decinteger | bininteger | octinteger | hexinteger
     decinteger   ::= nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
     bininteger   ::= "0" ("b" | "B") (["_"] bindigit)+
     octinteger   ::= "0" ("o" | "O") (["_"] octdigit)+
     hexinteger   ::= "0" ("x" | "X") (["_"] hexdigit)+
     nonzerodigit ::= "1"..."9"
     digit        ::= "0"..."9"
     bindigit     ::= "0" | "1"
     octdigit     ::= "0"..."7"
     hexdigit     ::= digit | "a"..."f" | "A"..."F"

整型数字面值的长度没有限制，能一直大到占满可用内存。

在确定数字大小时字面值中的下划线会被忽略。它们可用来将数码分组以提高可读
性。一个下划线可放在数码之间，也可放在基数说明符例如 ‘0x’ 之后。

注意非零的十进制数开头不允许有额外的零。这是为了避免与 Python 在版本 3.0
之前所使用的 C 风格八进制字面值相混淆。

一些整型数字面值的示例如下:

     7     2147483647                        0o177    0b100110111
     3     79228162514264337593543950336     0o377    0xdeadbeef
           100_000_000_000                   0b_1110_0101

在 3.6 版更改: 允许在字面值中使用下划线进行分组。


File: python.info,  Node: 浮点数字面值,  Next: 虚数字面值,  Prev: 整型数字面值,  Up: 字面值

4.2.4.6 浮点数字面值
....................

浮点数字面值由以下词法定义进行描述:

     floatnumber   ::= pointfloat | exponentfloat
     pointfloat    ::= [digitpart] fraction | digitpart "."
     exponentfloat ::= (digitpart | pointfloat) exponent
     digitpart     ::= digit (["_"] digit)*
     fraction      ::= "." digitpart
     exponent      ::= ("e" | "E") ["+" | "-"] digitpart

注意整型数部分和指数部分在解析时总是以 10 为基数。例如，‘077e010’ 是合法
的，且表示的数值与 ‘77e10’ 相同。浮点数字面值允许的范围依赖于具体实现。
对于整型数字面值，支持以下划线进行分组。

一些浮点数字面值的示例如下:

     3.14    10.    .001    1e100    3.14e-10    0e0    3.14_15_93

在 3.6 版更改: 允许在字面值中使用下划线进行分组。


File: python.info,  Node: 虚数字面值,  Prev: 浮点数字面值,  Up: 字面值

4.2.4.7 虚数字面值
..................

虚数字面值由以下词法定义进行描述:

     imagnumber ::= (floatnumber | digitpart) ("j" | "J")

一个虚数字面值将生成一个实部为 0.0 的复数。复数是以一对浮点数来表示的，
它们的取值范围相同。要创建一个实部不为零的复数，就加上一个浮点数，例如
‘(3+4j)’。一些虚数字面值的示例如下:

     3.14j   10.j    10j     .001j   1e100j   3.14e-10j   3.14_15_93j


File: python.info,  Node: 运算符,  Next: 分隔符,  Prev: 字面值,  Up: 词法分析

4.2.5 运算符
------------

以下形符属于运算符:

     +       -       *       **      /       //      %      @
     <<      >>      &       |       ^       ~       :=
     <       >       <=      >=      ==      !=


File: python.info,  Node: 分隔符,  Prev: 运算符,  Up: 词法分析

4.2.6 分隔符
------------

以下形符在语法中归类为分隔符:

     (       )       [       ]       {       }
     ,       :       .       ;       @       =       ->
     +=      -=      *=      /=      //=     %=      @=
     &=      |=      ^=      >>=     <<=     **=

句点也可出现于浮点数和虚数字面值中。连续三个句点有表示一个省略符的特殊含
义。以上列表的后半部分为增强赋值操作符，在词法中作为分隔符，但也起到运算
作用。

以下可打印 ASCII 字符作为其他形符的组成部分时具有特殊含义，或是对词法分
析器有重要意义:

     '       "       #       \

以下可打印 ASCII 字符不在 Python 词法中使用。如果出现于字符串字面值和注
释之外将无条件地引发错误:

     $       ?       `

备注
....


File: python.info,  Node: 数据模型,  Next: 执行模型,  Prev: 词法分析,  Up: Python语言参考

4.3 数据模型
============

* Menu:

* 对象、值与类型::
* 标准类型层级结构::
* 特殊方法名称::
* 协程::


File: python.info,  Node: 对象、值与类型,  Next: 标准类型层级结构,  Up: 数据模型

4.3.1 对象、值与类型
--------------------

`对象' 是 Python 中对数据的抽象。 Python 程序中的所有数据都是由对象或对
象间关系来表示的。 （从某种意义上说，按照冯·诺依曼的“存储程序计算机”模型
，代码本身也是由对象来表示的。）

每个对象都有各自的编号、类型和值。一个对象被创建后，它的 `编号' 就绝不会
改变；你可以将其理解为该对象在内存中的地址。 ’*note is: eca.’ 运算符可以
比较两个对象的编号是否相同；*note id(): d8e. 函数能返回一个代表其编号的
整型数。

`CPython implementation detail:' 在 CPython 中，‘id(x)’ 就是存放 ‘x’ 的
内存的地址。

对象的类型决定该对象所支持的操作 (例如 "对象是否有长度属性？") 并且定义
了该类型的对象可能的取值。*note type(): 611. 函数能返回一个对象的类型 (类
型本身也是对象)。与编号一样，一个对象的 `类型' 也是不可改变的。(1)

有些对象的 `值' 可以改变。值可以改变的对象被称为 `可变的'；值不可以改变
的对象就被称为 `不可变的'。(一个不可变容器对象如果包含对可变对象的引用，
当后者的值改变时，前者的值也会改变；但是该容器仍属于不可变对象，因为它所
包含的对象集是不会改变的。因此，不可变并不严格等同于值不能改变，实际含义
要更微妙。) 一个对象的可变性是由其类型决定的；例如，数字、字符串和元组是
不可变的，而字典和列表是可变的。

对象绝不会被显式地销毁；然而，当无法访问时它们可能会被作为垃圾回收。允许
具体的实现推迟垃圾回收或完全省略此机制 — 如何实现垃圾回收是实现的质量问
题，只要可访问的对象不会被回收即可。

`CPython implementation detail:' CPython 目前使用带有 (可选) 延迟检测循
环链接垃圾的引用计数方案，会在对象不可访问时立即回收其中的大部分，但不保
证回收包含循环引用的垃圾。请查看 *note gc: 86. 模块的文档了解如何控制循
环垃圾的收集相关信息。其他实现会有不同的行为方式，CPython 现有方式也可能
改变。不要依赖不可访问对象的立即终结机制 (所以你应当总是显式地关闭文件
)。

注意：使用实现的跟踪或调试功能可能令正常情况下会被回收的对象继续存活。还
要注意通过 ’*note try: d7a...*note except: b46.’ 语句捕捉异常也可能令对
象保持存活。

有些对象包含对 "外部" 资源的引用，例如打开文件或窗口。当对象被作为垃圾回
收时这些资源也应该会被释放，但由于垃圾回收并不确保发生，这些对象还提供了
明确地释放外部资源的操作，通常为一个 ‘close()’ 方法。强烈推荐在程序中显
式关闭此类对象。’*note try: d7a...*note finally: 183.’ 语句和 ’*note
with: 6f2.’ 语句提供了进行此种操作的更便捷方式。

有些对象包含对其他对象的引用；它们被称为 `容器'。容器的例子有元组、列表
和字典等。这些引用是容器对象值的组成部分。在多数情况下，当谈论一个容器的
值时，我们是指所包含对象的值而不是其编号；但是，当我们谈论一个容器的可变
性时，则仅指其直接包含的对象的编号。因此，如果一个不可变容器 (例如元组)
包含对一个可变对象的引用，则当该可变对象被改变时容器的值也会改变。

类型会影响对象行为的几乎所有方面。甚至对象编号的重要性也在某种程度上受到
影响: 对于不可变类型，会得出新值的运算实际上会返回对相同类型和取值的任一
现有对象的引用，而对于可变类型来说这是不允许的。例如在 ‘a = 1; b = 1’ 之
后，‘a’ 和 ‘b’ 可能会也可能不会指向同一个值为一的对象，这取决于具体实现
，但是在 ‘c = []; d = []’ 之后，‘c’ 和 ‘d’ 保证会指向两个不同、单独的新
建空列表。(请注意 ‘c = d = []’ 则是将同一个对象赋值给 ‘c’ 和 ‘d’。)

   ---------- Footnotes ----------

   (1) (1) 在某些情况下 `有可能' 基于可控的条件改变一个对象的类型。 但这
通常不是个好主意，因为如果处理不当会导致一些非常怪异的行为。


File: python.info,  Node: 标准类型层级结构,  Next: 特殊方法名称,  Prev: 对象、值与类型,  Up: 数据模型

4.3.2 标准类型层级结构
----------------------

以下是 Python 内置类型的列表。扩展模块 (具体实现会以 C, Java 或其他语言
编写) 可以定义更多的类型。未来版本的 Python 可能会加入更多的类型 (例如有
理数、高效存储的整型数组等等)，不过新增类型往往都是通过标准库来提供的。

以下部分类型的描述中包含有 ’特殊属性列表’ 段落。这些属性提供对具体实现的
访问而非通常使用。它们的定义在未来可能会改变。

None

     此类型只有一种取值。是一个具有此值的单独对象。此对象通过内置名称
     ‘None’ 访问。在许多情况下它被用来表示空值，例如未显式指明返回值的函
     数将返回 None。它的逻辑值为假。

NotImplemented

     此类型只有一种取值。是一个具有此值的单独对象。此对象通过内置名称
     ‘NotImplemented’ 访问。数值方法和丰富比较方法如未实现指定运算符表示
     的运算则应返回此值。(解释器会根据指定运算符继续尝试反向运算或其他回
     退操作)。它的逻辑值为真。

     详情参见 *note 实现算术运算: 1432.。

Ellipsis

     此类型只有一种取值。是一个具有此值的单独对象。此对象通过字面值
     ‘...’ 或内置名称 ‘Ellipsis’ 访问。它的逻辑值为真。

*note numbers.Number: 1433.

     此类对象由数字字面值创建，并会被作为算术运算符和算术内置函数的返回
     结果。数字对象是不可变的；一旦创建其值就不再改变。Python 中的数字当
     然非常类似数学中的数字，但也受限于计算机中的数字表示方法。

     数字类的字符串表示形式，由 *note __repr__(): 347. 和 *note
     __str__(): e3f. 算出，具有以下属性:

        * 它们是有效的数字字面值，当被传给它们的类构造器时，将会产生具有
          原数字值的对象。

        * 表示形式会在可能的情况下采用 10 进制。

        * 开头的零，除小数点前可能存在的单个零之外，将不会被显示。

        * 末尾的零，除小数点后可能存在的单个零之外，将不会被显示。

        * 正负号仅在当数字为负值时会被显示。

     Python 区分整型数、浮点型数和复数:

     *note numbers.Integral: 1434.

          此类对象表示数学中整数集合的成员 (包括正数和负数)。

          整型数可细分为两种类型:

          整型 (*note int: 185.)

               此类对象表示任意大小的数字，仅受限于可用的内存 (包括虚拟
               内存)。在变换和掩码运算中会以二进制表示，负数会以 2 的补
               码表示，看起来像是符号位向左延伸补满空位。

          布尔型 (*note bool: 184.)

               此类对象表示逻辑值 False 和 True。代表 ‘False’ 和 ‘True’
               值的两个对象是唯二的布尔对象。布尔类型是整型的子类型，两
               个布尔值在各种场合的行为分别类似于数值 0 和 1，例外情况只
               有在转换为字符串时分别返回字符串 ‘"False"’ 或 ‘"True"’。

          整型数表示规则的目的是在涉及负整型数的变换和掩码运算时提供最为
          合理的解释。

     *note numbers.Real: 1435. (*note float: 188.)

          此类对象表示机器级的双精度浮点数。其所接受的取值范围和溢出处理
          将受制于底层的机器架构 (以及 C 或 Java 实现)。Python 不支持单
          精度浮点数；支持后者通常的理由是节省处理器和内存消耗，但这点节
          省相对于在 Python 中使用对象的开销来说太过微不足道，因此没有理
          由包含两种浮点数而令该语言变得复杂。

     *note numbers.Complex: 1436. (*note complex: 18a.)

          此类对象以一对机器级的双精度浮点数来表示复数值。有关浮点数的附
          带规则对其同样有效。一个复数值 ‘z’ 的实部和虚部可通过只读属性
          ‘z.real’ 和 ‘z.imag’ 来获取。

序列

     此类对象表示以非负整数作为索引的有限有序集。内置函数 *note len():
     151. 可返回一个序列的条目数量。当一个序列的长度为 `n' 时，索引集包
     含数字 0, 1, ..., `n'-1。序列 `a' 的条目 `i' 可通过 ‘a[i]’ 选择。

     序列还支持切片: ‘a[i:j]’ 选择索引号为 `k' 的所有条目，`i' ‘<=’ `k'
     ‘<’ `j'。当用作表达式时，序列的切片就是一个与序列类型相同的新序列。
     新序列的索引还是从 0 开始。

     有些序列还支持带有第三个 "step" 形参的 "扩展切片": ‘a[i:j:k]’ 选择
     `a' 中索引号为 `x' 的所有条目，‘x = i + n*k’, `n' ‘>=’ ‘0’ 且 `i'
     ‘<=’ `x' ‘<’ `j'。

     序列可根据其可变性来加以区分:

     不可变序列

          不可变序列类型的对象一旦创建就不能再改变。(如果对象包含对其他
          对象的引用，其中的可变对象就是可以改变的；但是，一个不可变对象
          所直接引用的对象集是不能改变的。)

          以下类型属于不可变对象:

          字符串

               字符串是由 Unicode 码位值组成的序列。范围在 ‘U+0000 -
               U+10FFFF’ 之内的所有码位值都可在字符串中使用。Python 没有
               ‘char’ 类型；而是将字符串中的每个码位表示为一个长度为 ‘1’
               的字符串对象。内置函数 *note ord(): 1437. 可将一个码位由
               字符串形式转换成一个范围在 ‘0 - 10FFFF’ 之内的整型数；
               *note chr(): 1438. 可将一个范围在 ‘0 - 10FFFF’ 之内的整型
               数转换为长度为 ‘1’ 的对应字符串对象。*note str.encode():
               c3f. 可以使用指定的文本编码将 *note str: 339. 转换为
               *note bytes: 33a.，而 *note bytes.decode(): c40. 则可以实
               现反向的解码。

          元组

               一个元组中的条目可以是任意 Python 对象。包含两个或以上条
               目的元组由逗号分隔的表达式构成。只有一个条目的元组 (’单项
               元组’) 可通过在表达式后加一个逗号来构成 (一个表达式本身不
               能创建为元组，因为圆括号要用来设置表达式分组)。一个空元组
               可通过一对内容为空的圆括号创建。

          字节串

               字节串对象是不可变的数组。其中每个条目都是一个 8 位字节，
               以取值范围 0 <= x < 256 的整型数表示。字节串字面值 (例如
               ‘b'abc'’) 和内置的 *note bytes(): 33a. 构造器可被用来创建
               字节串对象。字节串对象还可以通过 *note decode(): c40. 方
               法解码为字符串。

     可变序列

          可变序列在被创建后仍可被改变。下标和切片标注可被用作赋值和
          *note del: 127e. (删除) 语句的目标。

          目前有两种内生可变序列类型:

          列表

               列表中的条目可以是任意 Python 对象。列表由用方括号括起并
               由逗号分隔的多个表达式构成。(注意创建长度为 0 或 1 的列表
               无需使用特殊规则。)

          字节数组

               字节数组对象属于可变数组。可以通过内置的 *note
               bytearray(): 33b. 构造器来创建。除了是可变的 (因而也是不
               可哈希的)，在其他方面字节数组提供的接口和功能都与不可变的
               *note bytes: 33a. 对象一致。

          扩展模块 *note array: 7. 提供了一个额外的可变序列类型示例，
          *note collections: 1e. 模块也是如此。

集合类型

     此类对象表示由不重复且不可变对象组成的无序且有限的集合。因此它们不
     能通过下标来索引。但是它们可被迭代，也可用内置函数 *note len():
     151. 返回集合中的条目数。集合常见的用处是快速成员检测，去除序列中的
     重复项，以及进行交、并、差和对称差等数学运算。

     对于集合元素所采用的不可变规则与字典的键相同。注意数字类型遵循正常
     的数字比较规则: 如果两个数字相等 (例如 ‘1’ 和 ‘1.0’)，则同一集合中
     只能包含其中一个。

     目前有两种内生集合类型:

     集合

          此类对象表示可变集合。它们可通过内置的 *note set(): b77. 构造
          器创建，并且创建之后可以通过方法进行修改，例如 ‘add()’。

     冻结集合

          此类对象表示不可变集合。它们可通过内置的 *note frozenset():
          bf6. 构造器创建。由于 frozenset 对象不可变且 *note hashable:
          1439.，它可以被用作另一个集合的元素或是字典的键。

映射

     此类对象表示由任意索引集合所索引的对象的集合。通过下标 ‘a[k]’ 可在
     映射 ‘a’ 中选择索引为 ‘k’ 的条目；这可以在表达式中使用，也可作为赋
     值或 *note del: 127e. 语句的目标。内置函数 *note len(): 151. 可返回
     一个映射中的条目数。

     目前只有一种内生映射类型:

     字典

          此类对象表示由几乎任意值作为索引的有限个对象的集合。不可作为键
          的值类型只有包含列表或字典或其他可变类型，通过值而非对象编号进
          行比较的值，其原因在于高效的字典实现需要使用键的哈希值以保持一
          致性。用作键的数字类型遵循正常的数字比较规则: 如果两个数字相等
          (例如 ‘1’ 和 ‘1.0’) 则它们均可来用来索引同一个字典条目。

          字典会保留插入顺序，这意味着键将以它们被添加的顺序在字典中依次
          产生。 替换某个现有的键不会改变其顺序，但是移除某个键再重新插
          入则会将其添加到末尾而不会保留其原有位置。

          字典是可变的；它们可通过 ‘{...}’ 标注来创建 (参见 *note
          字典显示: 657. 小节)。

          扩展模块 *note dbm.ndbm: 35. 和 *note dbm.gnu: 34. 提供了额外
          的映射类型示例，*note collections: 1e. 模块也是如此。

          在 3.7 版更改: 在 Python 3.6 版之前字典不会保留插入顺序。 在
          CPython 3.6 中插入顺序会被保留，但这在当时被当作是一个实现细节
          而非确定的语言特性。

可调用类型

     此类型可以被应用于函数调用操作 (参见 *note 调用: 655. 小节):

     用户定义函数

          用户定义函数对象可通过函数定义来创建 (参见 *note 函数定义:
          126c. 小节)。它被调用时应附带一个参数列表，其中包含的条目应与
          函数所定义的形参列表一致。

          特殊属性:

          属性                          含义
                                        
          ----------------------------------------------------------------------------------
                                                                            
          ‘__doc__’                     该函数的文档字符串，没有则为        可写
                                        ‘None’；不会被子类继承。            
                                        
                                                                            
          *note __name__: c6f.          该函数的名称。                      可写
                                                                            
                                                                            
          *note __qualname__: 143a.     该函数的                            可写
                                        *note qualified name: 143b.。       
                                        
                                        3.3 新版功能.
                                        
                                                                            
          ‘__module__’                  该函数所属模块的名称，没有则为      可写
                                        ‘None’。                            
                                        
                                                                            
          ‘__defaults__’                由具有默认值的参数的默认参数值组    可写
                                        成的元组，如无任何参数具有默认值    
                                        则为 ‘None’。
                                        
                                                                            
          ‘__code__’                    表示编译后的函数体的代码对象。      可写
                                                                            
                                                                            
          ‘__globals__’                 对存放该函数中全局变量的字典的引    只读
                                        用 — 函数所属模块的全局命名空间。   
                                        
                                                                            
          *note __dict__: 504.          命名空间支持的函数属性。            可写
                                                                            
                                                                            
          ‘__closure__’                 ‘None’ 或包含该函数可用变量的绑定   只读
                                        的单元的元组。有关                  
                                        ‘cell_contents’ 属性的详情见下。
                                        
                                                                            
          ‘__annotations__’             包含参数标注的字典。字典的键是参    可写
                                        数名，如存在返回标注则为            
                                        ‘'return'’。
                                        
                                                                            
          ‘__kwdefaults__’              仅包含关键字参数默认值的字典。      可写
                                                                            

          大部分标有 "Writable" 的属性均会检查赋值的类型。

          函数对象也支持获取和设置任意属性，例如这可以被用来给函数附加元
          数据。使用正规的属性点号标注获取和设置此类属性。`注意当前实现
          仅支持用户定义函数属性。未来可能会增加支持内置函数属性。'

          单元对象具有 ‘cell_contents’ 属性。这可被用来获取以及设置单元
          的值。

          有关函数定义的额外信息可以从其代码对象中提取；参见下文对内部类
          型的描述。 *note cell: 143c. 类型可以在 *note types: 119. 模块
          中访问。

     实例方法

          实例方法用于结合类、类实例和任何可调用对象 (通常为用户定义函数
          )。

          特殊的只读属性: ‘__self__’ 为类实例对象本身，‘__func__’ 为函数
          对象；‘__doc__’ 为方法的文档 (与 ‘__func__.__doc__’ 作用相同
          )；*note __name__: c6f. 为方法名称 (与 ‘__func__.__name__’ 作
          用相同)；‘__module__’ 为方法所属模块的名称，没有则为 ‘None’。

          方法还支持获取 (但不能设置) 下层函数对象的任意函数属性。

          用户定义方法对象可在获取一个类的属性时被创建 (也可能通过该类的
          一个实例)，如果该属性为用户定义函数对象或类方法对象。

          当通过从类实例获取一个用户定义函数对象的方式创建一个实例方法对
          象时，类实例对象的 ‘__self__’ 属性即为该实例，并会绑定方法对象
          。该新建方法的 ‘__func__’ 属性就是原来的函数对象。

          当通过从类或实例获取一个类方法对象的方式创建一个实例对象时，实
          例对象的 ‘__self__’ 属性为该类本身，其 ‘__func__’ 属性为类方法
          对应的下层函数对象。

          当一个实例方法对象被调用时，会调用对应的下层函数 (‘__func__’)，
          并将类实例 (‘__self__’) 插入参数列表的开头。例如，当 ‘C’ 是一
          个包含了 ‘f()’ 函数定义的类，而 ‘x’ 是 ‘C’ 的一个实例，则调用
          ‘x.f(1)’ 就等同于调用 ‘C.f(x, 1)’。

          当一个实例方法对象是衍生自一个类方法对象时，保存在 ‘__self__’
          中的 "类实例" 实际上会是该类本身，因此无论是调用 ‘x.f(1)’ 还是
          ‘C.f(1)’ 都等同于调用 ‘f(C,1)’，其中 ‘f’ 为对应的下层函数。

          请注意从函数对象到实例方法对象的变换会在每一次从实例获取属性时
          发生。在某些情况下，一种高效的优化方式是将属性赋值给一个本地变
          量并调用该本地变量。还要注意这样的变换只发生于用户定义函数；其
          他可调用对象 (以及所有不可调用对象) 在被获取时都不会发生变换。
          还有一个需要关注的要点是作为一个类实例属性的用户定义函数不会被
          转换为绑定方法；这样的变换 `仅当' 函数是类属性时才会发生。

     生成器函数

          一个使用 *note yield: 190. 语句 （见 *note yield 语句: 190. 章
          节）的函数或方法被称作一个 `生成器函数'。 这样的函数在被调用时
          ，总是返回一个可以执行函数体的迭代器对象：调用该迭代器的 *note
          iterator.__next__(): c6c. 方法将会导致这个函数一直运行直到它使
          用 ‘yield’ 语句提供了一个值为止。 当这个函数执行 *note return:
          191. 语句或者执行到末尾时，将引发 *note StopIteration: 48e. 异
          常并且这个迭代器将到达所返回的值集合的末尾。

     协程函数

          使用 *note async def: 285. 来定义的函数或方法就被称为 `协程函
          数'。这样的函数在被调用时会返回一个 *note coroutine: 1a7. 对象
          。它可能包含 *note await: 1a4. 表达式以及 *note async with:
          64c. 和 *note async for: 2e4. 语句。详情可参见 *note 协程对象:
          143d. 一节。

     异步生成器函数

          使用 *note async def: 285. 来定义并包含 *note yield: 190. 语句
          的函数或方法就被称为 `异步生成器函数'。这样的函数在被调用时会
          返回一个异步迭代器对象，该对象可在 *note async for: 2e4. 语句
          中用来执行函数体。

          调用异步迭代器的 ‘aiterator.__anext__()’ 方法将会返回一个
          *note awaitable: 521.，此对象会在被等待时执行直到使用 *note
          yield: 190. 表达式输出一个值。当函数执行时到空的 *note return:
          191. 语句或是最后一条语句时，将会引发 *note
          StopAsyncIteration: 1022. 异常，异步迭代器也会到达要输出的值集
          合的末尾。

     内置函数

          内置函数对象是对于 C 函数的外部封装。内置函数的例子包括 *note
          len(): 151. 和 *note math.sin(): e17. (*note math: b2. 是一个
          标准内置模块)。内置函数参数的数量和类型由 C 函数决定。特殊的只
          读属性: ‘__doc__’ 是函数的文档字符串，如果没有则为 ‘None’;
          *note __name__: c6f. 是函数的名称; ‘__self__’ 设定为 ‘None’ (参
          见下一条目); ‘__module__’ 是函数所属模块的名称，如果没有则为
          ‘None’。

     内置方法

          此类型实际上是内置函数的另一种形式，只不过还包含了一个传入 C 函
          数的对象作为隐式的额外参数。内置方法的一个例子是
          ‘alist.append()’，其中 `alist' 为一个列表对象。在此示例中，特
          殊的只读属性 ‘__self__’ 会被设为 `alist' 所标记的对象。

     类

          类是可调用的。此种对象通常是作为“工厂”来创建自身的实例，类也可
          以有重载 *note __new__(): 892. 的变体类型。调用的参数会传给
          *note __new__(): 892.，而且通常也会传给 *note __init__(): d66.
          来初始化新的实例。

     类实例

          任意类的实例通过在所属类中定义 *note __call__(): 143e. 方法即
          能成为可调用的对象。

模块

     模块是 Python 代码的基本组织单元，由 *note 导入系统: 143f. 创建，由
     *note import: c25. 语句发起调用，或者通过 *note
     importlib.import_module(): b1b. 和内置的 *note __import__(): 619. 等
     函数发起调用。 模块对象具有由字典对象实现的命名空间（这是被模块中定
     义的函数的 ‘__globals__’ 属性引用的字典）。 属性引用被转换为该字典
     中的查找，例如 ‘m.x’ 相当于 ‘m.__dict__["x"]’。 模块对象不包含用于
     初始化模块的代码对象（因为初始化完成后不需要它）。

     属性赋值会更新模块的命名空间字典，例如 ‘m.x = 1’ 等同于
     ‘m.__dict__["x"] = 1’。

     预定义的 (可写) 属性: *note __name__: d1a. 为模块的名称; ‘__doc__’
     为模块的文档字符串，如果没有则为 ‘None’; ‘__annotations__’ (可选) 为
     一个包含 *note 变量标注: 628. 的字典，它是在模块体执行时获取的;
     *note __file__: ec7. 是模块对应的被加载文件的路径名，如果它是加载自
     一个文件的话。某些类型的模块可能没有 *note __file__: ec7. 属性，例
     如 C 模块是静态链接到解释器内部的; 对于从一个共享库动态加载的扩展模
     块来说该属性为该共享库文件的路径名。

     特殊的只读属性: *note __dict__: 504. 为以字典对象表示的模块命名空间
     。

     `CPython implementation detail:' 由于 CPython 清理模块字典的设定，
     当模块离开作用域时模块字典将会被清理，即使该字典还有活动的引用。想
     避免此问题，可复制该字典或保持模块状态以直接使用其字典。

自定义类

     自定义类这种类型一般通过类定义来创建 (参见 *note 类定义: c72. 一节
     )。每个类都有通过一个字典对象实现的独立命名空间。类属性引用会被转化
     为在此字典中查找，例如 ‘C.x’ 会被转化为 ‘C.__dict__["x"]’ (不过也存
     在一些钩子对象以允许其他定位属性的方式)。当未在其中发现某个属性名称
     时，会继续在基类中查找。这种基类查找使用 C3 方法解析顺序，即使存在
     ’钻石形’ 继承结构即有多条继承路径连到一个共同祖先也能保持正确的行为
     。有关 Python 使用的 C3 MRO 的详情可查看配合 2.3 版发布的文档
     ‘https://www.python.org/download/releases/2.3/mro/’.

     当一个类属性引用 (假设类名为 ‘C’) 会产生一个类方法对象时，它将转化
     为一个 ‘__self__’ 属性为 ‘C’ 的实例方法对象。当其会产生一个静态方法
     对象时，它将转化为该静态方法对象所封装的对象。从类的 *note
     __dict__: 504. 所包含内容以外获取属性的其他方式请参看 *note
     实现描述器: 4f1. 一节。

     类属性赋值会更新类的字典，但不会更新基类的字典。

     类对象可被调用 (见上文) 以产生一个类实例 (见下文)。

     特殊属性: *note __name__: c6f. 为类的名称; ‘__module__’ 为类所在模
     块的名称; *note __dict__: 504. 为包含类命名空间的字典; *note
     __bases__: e11. 为包含基类的元组，按其在基类列表中的出现顺序排列;
     ‘__doc__’ 为类的文档字符串，如果没有则为 ‘None’; ‘__annotations__’
     (可选) 为一个包含 *note 变量标注: 628. 的字典，它是在类体执行时获取
     的。

类实例

     类实例可通过调用类对象来创建 (见上文)。每个类实例都有通过一个字典对
     象实现的独立命名空间，属性引用会首先在此字典中查找。当未在其中发现
     某个属性，而实例对应的类中有该属性时，会继续在类属性中查找。如果找
     到的类属性为一个用户定义函数对象，它会被转化为实例方法对象，其
     ‘__self__’ 属性即该实例。静态方法和类方法对象也会被转化；参见上文
     "Classes" 一节。要了解其他通过类实例来获取相应类属性的方式可参见
     *note 实现描述器: 4f1. 一节，这样得到的属性可能与实际存放于类的
     *note __dict__: 504. 中的对象不同。如果未找到类属性，而对象对应的类
     具有 *note __getattr__(): 323. 方法，则会调用该方法来满足查找要求。

     属性赋值和删除会更新实例的字典，但不会更新对应类的字典。如果类具有
     *note __setattr__(): e34. 或 *note __delattr__(): 1440. 方法，则将
     调用方法而不再直接更新实例的字典。

     如果类实例具有某些特殊名称的方法，就可以伪装为数字、序列或映射。参
     见 *note 特殊方法名称: 516. 一节。

     特殊属性: *note __dict__: 504. 为属性字典; *note __class__: e12. 为
     实例对应的类。

I/O 对象 (或称文件对象)

     *note file object: b4a. 表示一个打开的文件。有多种快捷方式可用来创
     建文件对象: *note open(): 4f8. 内置函数，以及 *note os.popen():
     2aa, *note os.fdopen(): 1441. 和 socket 对象的 *note makefile():
     b21. 方法 (还可能使用某些扩展模块所提供的其他函数或方法)。

     ‘sys.stdin’, ‘sys.stdout’ 和 ‘sys.stderr’ 会初始化为对应于解释器标
     准输入、输出和错误流的文件对象；它们都会以文本模式打开，因此都遵循
     *note io.TextIOBase: c41. 抽象类所定义的接口。

内部类型

     某些由解释器内部使用的类型也被暴露给用户。它们的定义可能随未来解释
     器版本的更新而变化，为内容完整起见在此处一并介绍。

     代码对象

          代码对象表示 `编译为字节的' 可执行 Python 代码，或称 *note
          bytecode: 61d.。代码对象和函数对象的区别在于函数对象包含对函数
          全局对象 (函数所属的模块) 的显式引用，而代码对象不包含上下文；
          而且默认参数值会存放于函数对象而不是代码对象内 (因为它们表示在
          运行时算出的值)。与函数对象不同，代码对象不可变，也不包含对可
          变对象的引用 (不论是直接还是间接)。

          特殊的只读属性: ‘co_name’ 给出了函数名; ‘co_argcount’ 为位置参
          数的总数量 (包括仅限位置参数和带有默认值的参数);
          ‘co_posonlyargcount’ 为仅限位置参数的数量 (包括带有默认值的参
          数); ‘co_kwonlyargcount’ 为仅限关键字参数的数量 (包括带有默认
          值的参数); ‘co_nlocals’ 为函数使用的局部变量的数量 (包括参数);
          ‘co_varnames’ 为一个包含局部变量名称的元组 (参数名排在最前面);
          ‘co_cellvars’ 为一个包含被嵌套函数所引用的局部变量名称的元组;
          ‘co_freevars’ 为一个包含自由变量名称的元组; ‘co_code’ 为一个表
          示字节码指令序列的字符口中; ‘co_consts’ 为一个包含字节码所使用
          的字面值的元组; ‘co_names’ 为一个包含字节码所使用的名称的元组;
          ‘co_filename’ 为被编码代码所在的文件名; ‘co_firstlineno’ 为函
          数首行的行号; ‘co_lnotab’ 为一个字符串，其中编码了从字节码偏移
          量到行号的映射 (详情参见解释器的源代码); ‘co_stacksize’ 为要求
          的栈大小; ‘co_flags’ 为一个整数，其中编码了解释器所用的多个旗
          标。

          以下是可用于 ‘co_flags’ 的标志位定义：如果函数使用
          ‘*arguments’ 语法来接受任意数量的位置参数，则 ‘0x04’ 位被设置
          ；如果函数使用 ‘**keywords’ 语法来接受任意数量的关键字参数，则
          ‘0x08’ 位被设置；如果函数是一个生成器，则 ‘0x20’ 位被设置。

          未来特性声明 (‘from __future__ import division’) 也使用
          ‘co_flags’ 中的标志位来指明代码对象的编译是否启用特定的特性: 如
          果函数编译时启用未来除法特性则设置 ‘0x2000’ 位; 在更早的
          Python 版本中则使用 ‘0x10’ 和 ‘0x1000’ 位。

          ‘co_flags’ 中的其他位被保留为内部使用。

          如果代码对象表示一个函数，‘co_consts’ 中的第一项将是函数的文档
          字符串，如果未定义则为 ‘None’。

     帧对象

          帧对象表示执行帧。它们可能出现在回溯对象中 (见下文)，还会被传
          递给注册跟踪函数。

          特殊的只读属性: ‘f_back’ 为前一堆栈帧 (指向调用者)，如是最底层
          堆栈帧则为 ‘None’; ‘f_code’ 为此帧中所执行的代码对象;
          ‘f_locals’ 为用于查找本地变量的字典; ‘f_globals’ 则用于查找全
          局变量; ‘f_builtins’ 用于查找内置 (固有) 名称; ‘f_lasti’ 给出
          精确指令 (这是代码对象的字节码字符串的一个索引)。

          访问 ‘f_code’ 会引发一个 *note 审计事件: ea1.
          ‘object.__getattr__’，附带参数 ‘obj’ 和 ‘"f_code"’。

          特殊的可写属性: ‘f_trace’，如果不为 ‘None’，则是在代码执行期间
          调用各类事件的函数 (由调试器使用)。通常每个新源码行会触发一个
          事件 - 这可以通过将 ‘f_trace_lines’ 设为 *note False: 390. 来
          禁用。

          具体的实现 `可能' 会通过将 ‘f_trace_opcodes’ 设为 *note True:
          4a1. 来允许按操作码请求事件。请注意如果跟踪函数引发的异常逃逸
          到被跟踪的函数中，这可能会导致未定义的解释器行为。

          ‘f_lineno’ 为帧的当前行号 — 在这里写入从一个跟踪函数内部跳转的
          指定行 (仅用于最底层的帧)。调试器可以通过写入 f_lineno 实现一
          个 Jump 命令 (即设置下一语句)。

          帧对象支持一个方法:

           -- 方法: frame.clear ()

               此方法清除该帧持有的全部对本地变量的引用。而且如果该帧属
               于一个生成器，生成器会被完成。这有助于打破包含帧对象的循
               环引用 (例如当捕获一个异常并保存其回溯在之后使用)。

               如果该帧当前正在执行则会引发 *note RuntimeError: 2bb.。

               3.4 新版功能.

     回溯对象

          回溯对象表示一个异常的栈跟踪记录。当异常发生时会隐式地创建一个
          回溯对象，也可能通过调用 *note types.TracebackType: 33e. 显式
          地创建。

          对于隐式地创建的回溯对象，当查找异常句柄使得执行栈展开时，会在
          每个展开层级的当前回溯之前插入一个回溯对象。当进入一个异常句柄
          时，栈跟踪将对程序启用。(参见 *note try 语句: d7a. 一节。) 它
          可作为 ‘sys.exc_info()’ 所返回的元组的第三项，以及所捕获异常的
          ‘__traceback__’ 属性被获取。

          当程序不包含可用的句柄时，栈跟踪会 (以良好的格式) 写入标准错误
          流；如果解释器处于交互模式，它也可作为 ‘sys.last_traceback’ 对
          用户启用。

          对于显式创建的回溯对象，则由回溯对象的创建者来决定应该如何链接
          ‘tb_next’ 属性来构成完整的栈跟踪。

          特殊的只读属性: ‘tb_frame’ 指向当前层级的执行帧; ‘tb_lineno’ 给
          出发生异常所在的行号; ‘tb_lasti’ 标示具体指令。如果异常发生于
          没有匹配的 except 子句或有 finally 子句的 *note try: d7a. 语句
          中，回溯对象中的行号和最后指令可能与相应帧对象中行号不同。

          访问 ‘tb_frame’ 会引发一个 *note 审计事件: ea1.
          ‘object.__getattr__’，附带参数 ‘obj’ 和 ‘"tb_frame"’。

          特殊的可写属性: ‘tb_next’ 为栈跟踪中的下一层级 (通往发生异常的
          帧)，如果没有下一层级则为 ‘None’。

          在 3.7 版更改: 回溯对象现在可以使用 Python 代码显式地实例化，
          现有实例的 ‘tb_next’ 属性可以被更新。

     切片对象

          切片对象用来表示 *note __getitem__(): 280. 方法用到的切片。 该
          对象也可使用内置的 *note slice(): e0c. 函数来创建。

          特殊的只读属性: ‘start’ 为下界; ‘stop’ 为上界; ‘step’ 为步长值
          ; 各值如省略则为 ‘None’。这些属性可具有任意类型。

          切片对象支持一个方法:

           -- 方法: slice.indices (self, length)

               此方法接受一个整型参数 `length' 并计算在切片对象被应用到
               `length' 指定长度的条目序列时切片的相关信息应如何描述。 其
               返回值为三个整型数组成的元组；这些数分别为切片的 `start'
               和 `stop' 索引号以及 `step' 步长值。索引号缺失或越界则按
               照与正规切片相一致的方式处理。

     静态方法对象

          静态方法对象提供了一种避免上文所述将函数对象转换为方法对象的方
          式。静态方法对象为对任意其他对象的封装，通常用来封装用户定义方
          法对象。当从类或类实例获取一个静态方法对象时，实际返回的对象是
          封装的对象，它不会被进一步转换。静态方法对象自身不是可调用的，
          但它们所封装的对象通常都是可调用的。静态方法对象可通过内置的
          *note staticmethod(): 1da. 构造器来创建。

     类方法对象

          类方法对象和静态方法一样是对其他对象的封装，会改变从类或类实例
          获取该对象的方式。类方法对象在此类获取操作中的行为已在上文 "用
          户定义方法" 一节中描述。类方法对象可通过内置的 *note
          classmethod(): 1d9. 构造器来创建。


File: python.info,  Node: 特殊方法名称,  Next: 协程,  Prev: 标准类型层级结构,  Up: 数据模型

4.3.3 特殊方法名称
------------------

一个类可以通过定义具有特殊名称的方法来实现由特殊语法所引发的特定操作 (例
如算术运算或下标与切片)。这是 Python 实现 `操作符重载' 的方式，允许每个
类自行定义基于操作符的特定行为。例如，如果一个类定义了名为 *note
__getitem__(): 280. 的方法，并且 ‘x’ 为该类的一个实例，则 ‘x[i]’ 基本就
等同于 ‘type(x).__getitem__(x, i)’。除非有说明例外情况，在没有定义适当方
法的情况下尝试执行一种操作将引发一个异常 (通常为 *note AttributeError:
3a3. 或 *note TypeError: 193.)。

将一个特殊方法设为 ‘None’ 表示对应的操作不可用。例如，如果一个类将 *note
__iter__(): 517. 设为 ‘None’，则该类就是不可迭代的，因此对其实例调用
*note iter(): d2f. 将引发一个 *note TypeError: 193. (而不会回退至 *note
__getitem__(): 280.).  (1)

在实现模拟任何内置类型的类时，很重要的一点是模拟的实现程度对于被模拟对象
来说应当是有意义的。例如，提取单个元素的操作对于某些序列来说是适宜的，但
提取切片可能就没有意义。(这种情况的一个实例是 W3C 的文档对象模型中的
‘NodeList’ 接口。)

* Menu:

* 基本定制::
* 自定义属性访问::
* 自定义类创建::
* 自定义实例及子类检查::
* 模拟泛型类型::
* 模拟可调用对象::
* 模拟容器类型::
* 模拟数字类型::
* with 语句上下文管理器::
* 特殊方法查找::

   ---------- Footnotes ----------

   (1) (2) *note __hash__(): 349, *note __iter__(): 517, *note
__reversed__(): 537. 以及 *note __contains__(): d30. 方法对此有特殊处理
；其他方法仍会引发 *note TypeError: 193.，但可能依靠 ‘None’ 属于不可调用
对象的行为来做到这一点。


File: python.info,  Node: 基本定制,  Next: 自定义属性访问,  Up: 特殊方法名称

4.3.3.1 基本定制
................

 -- 方法: object.__new__ (cls[, ...])

     调用以创建一个 `cls' 类的新实例。*note __new__(): 892. 是一个静态方
     法 (因为是特例所以你不需要显式地声明)，它会将所请求实例所属的类作为
     第一个参数。其余的参数会被传递给对象构造器表达式 (对类的调用)。
     *note __new__(): 892. 的返回值应为新对象实例 (通常是 `cls' 的实例
     )。

     典型的实现会附带适宜的参数使用 ‘super().__new__(cls[, ...])’，通过
     超类的 *note __new__(): 892. 方法来创建一个类的新实例，然后根据需要
     修改新创建的实例再将其返回。

     If *note __new__(): 892. is invoked during object construction and
     it returns an instance of `cls', then the new instance’s *note
     __init__(): d66. method will be invoked like ‘__init__(self[,
     ...])’, where `self' is the new instance and the remaining
     arguments are the same as were passed to the object constructor.

     如果 *note __new__(): 892. 未返回一个 `cls' 的实例，则新实例的
     *note __init__(): d66. 方法就不会被执行。

     *note __new__(): 892. 的目的主要是允许不可变类型的子类 (例如 int,
     str 或 tuple) 定制实例创建过程。它也常会在自定义元类中被重载以便定
     制类创建过程。

 -- 方法: object.__init__ (self[, ...])

     在实例 (通过 *note __new__(): 892.) 被创建之后，返回调用者之前调用
     。其参数与传递给类构造器表达式的参数相同。一个基类如果有 *note
     __init__(): d66. 方法，则其所派生的类如果也有 *note __init__():
     d66. 方法，就必须显式地调用它以确保实例基类部分的正确初始化；例如:
     ‘super().__init__([args...])’.

     因为对象是由 *note __new__(): 892. 和 *note __init__(): d66. 协作构
     造完成的 (由 *note __new__(): 892. 创建，并由 *note __init__():
     d66. 定制)，所以 *note __init__(): d66. 返回的值只能是 ‘None’，否则
     会在运行时引发 *note TypeError: 193.。

 -- 方法: object.__del__ (self)

     在实例将被销毁时调用。 这还被称为终结器或析构器（不适当）。 如果一
     个基类具有 *note __del__(): 927. 方法，则其所派生的类如果也有 *note
     __del__(): 927. 方法，就必须显式地调用它以确保实例基类部分的正确清
     除。

     *note __del__(): 927. 方法可以 (但不推荐!) 通过创建一个该实例的新引
     用来推迟其销毁。这被称为对象 `重生'。*note __del__(): 927. 是否会在
     重生的对象将被销毁时再次被调用是由具体实现决定的 ；当前的 *note
     CPython: 1446. 实现只会调用一次。

     当解释器退出时不会确保为仍然存在的对象调用 *note __del__(): 927. 方
     法。

          注解: ‘del x’ 并不直接调用 ‘x.__del__()’ — 前者会将 ‘x’ 的引用
          计数减一，而后者仅会在 ‘x’ 的引用计数变为零时被调用。

     `CPython implementation detail:' It is possible for a reference
     cycle to prevent the reference count of an object from going to
     zero.  In this case, the cycle will be later detected and deleted
     by the *note cyclic garbage collector: ed8.  A common cause of
     reference cycles is when an exception has been caught in a local
     variable.  The frame’s locals then reference the exception, which
     references its own traceback, which references the locals of all
     frames caught in the traceback.

     参见
     ....

     *note gc: 86. 模块的文档。

          警告: 由于调用 *note __del__(): 927. 方法时周边状况已不确定，
          在其执行期间发生的异常将被忽略，改为打印一个警告到
          ‘sys.stderr’。特别地：

             * *note __del__(): 927. 可在任意代码被执行时启用，包括来自
               任意线程的代码。如果 *note __del__(): 927. 需要接受锁或启
               用其他阻塞资源，可能会发生死锁，例如该资源已被为执行
               *note __del__(): 927. 而中断的代码所获取。

             * *note __del__(): 927. 可以在解释器关闭阶段被执行。因此，
               它需要访问的全局变量（包含其他模块）可能已被删除或设为
               ‘None’。Python 会保证先删除模块中名称以单个下划线打头的全
               局变量再删除其他全局变量；如果已不存在其他对此类全局变量
               的引用，这有助于确保导入的模块在 *note __del__(): 927. 方
               法被调用时仍然可用。

 -- 方法: object.__repr__ (self)

     由 *note repr(): 7d5. 内置函数调用以输出一个对象的“官方”字符串表示
     。如果可能，这应类似一个有效的 Python 表达式，能被用来重建具有相同
     取值的对象（只要有适当的环境）。如果这不可能，则应返回形式如
     ‘<...some useful description...>’ 的字符串。返回值必须是一个字符串
     对象。如果一个类定义了 *note __repr__(): 347. 但未定义 *note
     __str__(): e3f.，则在需要该类的实例的“非正式”字符串表示时也会使用
     *note __repr__(): 347.。

     此方法通常被用于调试，因此确保其表示的内容包含丰富信息且无歧义是很
     重要的。

 -- 方法: object.__str__ (self)

     通过 *note str(object): 339. 以及内置函数 *note format(): 4e3. 和
     *note print(): 88f. 调用以生成一个对象的“非正式”或格式良好的字符串
     表示。返回值必须为一个 *note 字符串: 1233. 对象。

     此方法与 *note object.__repr__(): 347. 的不同点在于 *note
     __str__(): e3f. 并不预期返回一个有效的 Python 表达式：可以使用更方
     便或更准确的描述信息。

     内置类型 *note object: 2b1. 所定义的默认实现会调用 *note
     object.__repr__(): 347.。

 -- 方法: object.__bytes__ (self)

     通过 *note bytes: 10cd. 调用以生成一个对象的字节串表示。这应该返回
     一个 *note bytes: 33a. 对象。

 -- 方法: object.__format__ (self, format_spec)

     通过 *note format(): 4e3. 内置函数、扩展、*note 格式化字符串字面值:
     15d. 的求值以及 *note str.format(): 4e2. 方法调用以生成一个对象的
     “格式化”字符串表示。 `format_spec' 参数为包含所需格式选项描述的字符
     串。 `format_spec' 参数的解读是由实现 *note __format__(): 956. 的类
     型决定的，不过大多数类或是将格式化委托给某个内置类型，或是使用相似
     的格式化选项语法。

     请参看 *note 格式规格迷你语言: 4e6. 了解标准格式化语法的描述。

     返回值必须为一个字符串对象。

     在 3.4 版更改: ‘object’ 本身的 __format__ 方法如果被传入任何非空字
     符，将会引发一个 *note TypeError: 193.。

     在 3.7 版更改: ‘object.__format__(x, '')’ 现在等同于 ‘str(x)’ 而不
     再是 ‘format(str(self), '')’。

 -- 方法: object.__lt__ (self, other)
 -- 方法: object.__le__ (self, other)
 -- 方法: object.__eq__ (self, other)
 -- 方法: object.__ne__ (self, other)
 -- 方法: object.__gt__ (self, other)
 -- 方法: object.__ge__ (self, other)

     以上这些被称为“富比较”方法。运算符号与方法名称的对应关系如下：‘x<y’
     调用 ‘x.__lt__(y)’、‘x<=y’ 调用 ‘x.__le__(y)’、‘x==y’ 调用
     ‘x.__eq__(y)’、‘x!=y’ 调用 ‘x.__ne__(y)’、‘x>y’ 调用 ‘x.__gt__(y)’、
     ‘x>=y’ 调用 ‘x.__ge__(y)’。

     如果指定的参数对没有相应的实现，富比较方法可能会返回单例对象
     ‘NotImplemented’。按照惯例，成功的比较会返回 ‘False’ 或 ‘True’。不
     过实际上这些方法可以返回任意值，因此如果比较运算符是要用于布尔值判
     断（例如作为 ‘if’ 语句的条件），Python 会对返回值调用 *note bool():
     184. 以确定结果为真还是假。

     在默认情况下，‘object’ 通过使用 ‘is’ 来实现 *note __eq__(): 348.，
     并在比较结果为假值时返回 ‘NotImplemented’: ‘True if x is y else
     NotImplemented’。 对于 *note __ne__(): e5e.，默认会委托给 *note
     __eq__(): 348. 并对结果取反，除非结果为 ‘NotImplemented’。 比较运算
     符之间没有其他隐含关系或默认实现；例如，‘(x<y or x==y)’ 为真并不意
     味着 ‘x<=y’。 要根据单根运算自动生成排序操作，请参看 *note
     functools.total_ordering(): 854.。

     请查看 *note __hash__(): 349. 的相关段落，了解创建可支持自定义比较
     运算并可用作字典键的 *note hashable: 1439. 对象时要注意的一些事项。

     这些方法并没有对调参数版本（在左边参数不支持该操作但右边参数支持时
     使用）；而是 *note __lt__(): c3c. 和 *note __gt__(): ca9. 互为对方
     的反射， *note __le__(): ca8. 和 *note __ge__(): caa. 互为对方的反
     射，而 *note __eq__(): 348. 和 *note __ne__(): e5e. 则是它们自己的
     反射。如果两个操作数的类型不同，且右操作数类型是左操作数类型的直接
     或间接子类，则优先选择右操作数的反射方法，否则优先选择左操作数的方
     法。虚拟子类不会被考虑。

 -- 方法: object.__hash__ (self)

     通过内置函数 *note hash(): 9cc. 调用以对哈希集的成员进行操作，属于
     哈希集的类型包括 *note set: b77.、*note frozenset: bf6. 以及 *note
     dict: 1b9.。*note __hash__(): 349. 应该返回一个整数。对象比较结果相
     同所需的唯一特征属性是其具有相同的哈希值；建议的做法是把参与比较的
     对象全部组件的哈希值混在一起，即将它们打包为一个元组并对该元组做哈
     希运算。例如:

          def __hash__(self):
              return hash((self.name, self.nick, self.color))

          注解: *note hash(): 9cc. 会从一个对象自定义的 *note
          __hash__(): 349. 方法返回值中截断为 ‘Py_ssize_t’ 的大小。通常
          对 64 位构建为 8 字节，对 32 位构建为 4 字节。如果一个对象的
          *note __hash__(): 349. 必须在不同位大小的构建上进行互操作，请
          确保检查全部所支持构建的宽度。做到这一点的简单方法是使用
          ‘python -c "import sys; print(sys.hash_info.width)"’。

     如果一个类没有定义 *note __eq__(): 348. 方法，那么也不应该定义
     *note __hash__(): 349. 操作；如果它定义了 *note __eq__(): 348. 但没
     有定义 *note __hash__(): 349.，则其实例将不可被用作可哈希集的项。如
     果一个类定义了可变对象并实现了 *note __eq__(): 348. 方法，则不应该
     实现 *note __hash__(): 349.，因为可哈希集的实现要求键的哈希集是不可
     变的（如果对象的哈希值发生改变，它将处于错误的哈希桶中）。

     用户定义的类默认带有 *note __eq__(): 348. 和 *note __hash__(): 349.
     方法；使用它们与任何对象（自己除外）比较必定不相等，并且
     ‘x.__hash__()’ 会返回一个恰当的值以确保 ‘x == y’ 同时意味着 ‘x is
     y’ 且 ‘hash(x) == hash(y)’。

     一个类如果重载了 *note __eq__(): 348. 且没有定义 *note __hash__():
     349. 则会将其 *note __hash__(): 349. 隐式地设为 ‘None’。当一个类的
     *note __hash__(): 349. 方法为 ‘None’ 时，该类的实例将在一个程序尝试
     获取其哈希值时正确地引发 *note TypeError: 193.，并会在检测
     ‘isinstance(obj, collections.abc.Hashable)’ 时被正确地识别为不可哈
     希对象。

     如果一个重载了 *note __eq__(): 348. 的类需要保留来自父类的 *note
     __hash__(): 349. 实现，则必须通过设置 ‘__hash__ =
     <ParentClass>.__hash__’ 来显式地告知解释器。

     如果一个没有重载 *note __eq__(): 348. 的类需要去掉哈希支持，则应该
     在类定义中包含 ‘__hash__ = None’。一个自定义了 *note __hash__():
     349. 以显式地引发 *note TypeError: 193. 的类会被 ‘isinstance(obj,
     collections.abc.Hashable)’ 调用错误地识别为可哈希对象。

          注解: 在默认情况下，str 和 bytes 对象的 *note __hash__(): 349.
          值会使用一个不可预知的随机值“加盐”。 虽然它们在一个单独 Python
          进程中会保持不变，但它们的值在重复运行的 Python 间是不可预测的
          。

          这种做法是为了防止以下形式的拒绝服务攻击：通过仔细选择输入来利
          用字典插入操作在最坏情况下的执行效率即 O(n^2) 复杂度。详情见
          ‘http://www.ocert.org/advisories/ocert-2011-003.html’

          改变哈希值会影响集合的迭代次序。Python 也从不保证这个次序不会
          被改变（通常它在 32 位和 64 位构建上是不一致的）。

          另见 *note PYTHONHASHSEED: 9cd.

     在 3.3 版更改: 默认启用哈希随机化。

 -- 方法: object.__bool__ (self)

     调用此方法以实现真值检测以及内置的 ‘bool()’ 操作；应该返回 ‘False’
     或 ‘True’。如果未定义此方法，则会查找并调用 *note __len__(): dd3. 并
     在其返回非零值时视对象的逻辑值为真。如果一个类既未定义 *note
     __len__(): dd3. 也未定义 *note __bool__(): c70. 则视其所有实例的逻
     辑值为真。


File: python.info,  Node: 自定义属性访问,  Next: 自定义类创建,  Prev: 基本定制,  Up: 特殊方法名称

4.3.3.2 自定义属性访问
......................

可以定义下列方法来自定义对类实例属性访问（‘x.name’ 的使用、赋值或删除）
的具体含义.

 -- 方法: object.__getattr__ (self, name)

     当默认属性访问因引发 *note AttributeError: 3a3. 而失败时被调用 (可
     能是调用 *note __getattribute__(): 44f. 时由于 `name' 不是一个实例
     属性或 ‘self’ 的类关系树中的属性而引发了 *note AttributeError:
     3a3.；或者是对 `name' 特性属性调用 *note __get__(): 144b. 时引发了
     *note AttributeError: 3a3.)。此方法应当返回（找到的）属性值或是引发
     一个 *note AttributeError: 3a3. 异常。

     请注意如果属性是通过正常机制找到的，*note __getattr__(): 323. 就不
     会被调用。（这是在 *note __getattr__(): 323. 和 *note
     __setattr__(): e34. 之间故意设置的不对称性。）这既是出于效率理由也
     是因为不这样设置的话 *note __getattr__(): 323. 将无法访问实例的其他
     属性。要注意至少对于实例变量来说，你不必在实例属性字典中插入任何值
     （而是通过插入到其他对象）就可以模拟对它的完全控制。请参阅下面的
     *note __getattribute__(): 44f. 方法了解真正获取对属性访问的完全控制
     权的办法。

 -- 方法: object.__getattribute__ (self, name)

     此方法会无条件地被调用以实现对类实例属性的访问。如果类还定义了
     *note __getattr__(): 323.，则后者不会被调用，除非 *note
     __getattribute__(): 44f. 显式地调用它或是引发了 *note
     AttributeError: 3a3.。此方法应当返回（找到的）属性值或是引发一个
     *note AttributeError: 3a3. 异常。为了避免此方法中的无限递归，其实现
     应该总是调用具有相同名称的基类方法来访问它所需要的任何属性，例如
     ‘object.__getattribute__(self, name)’。

          注解: 此方法在作为通过特定语法或内置函数隐式地调用的结果的情况
          下查找特殊方法时仍可能会被跳过。参见 *note 特殊方法查找:
          144c.。

     引发一个 *note 审计事件: ea1. ‘object.__getattr__’，附带参数 ‘obj’,
     ‘name’。

 -- 方法: object.__setattr__ (self, name, value)

     此方法在一个属性被尝试赋值时被调用。这个调用会取代正常机制（即将值
     保存到实例字典）。 `name' 为属性名称， `value' 为要赋给属性的值。

     如果 *note __setattr__(): e34. 想要赋值给一个实例属性，它应该调用同
     名的基类方法，例如 ‘object.__setattr__(self, name, value)’。

     引发一个 *note 审计事件: ea1. ‘object.__setattr__’，附带参数 ‘obj’,
     ‘name’, ‘value’。

 -- 方法: object.__delattr__ (self, name)

     类似于 *note __setattr__(): e34. 但其作用为删除而非赋值。此方法应该
     仅在 ‘del obj.name’ 对于该对象有意义时才被实现。

     引发一个 *note 审计事件: ea1. ‘object.__delattr__’，附带参数 ‘obj’,
     ‘name’。

 -- 方法: object.__dir__ (self)

     此方法会在对相应对象调用 *note dir(): d3b. 时被调用。返回值必须为一
     个序列。 *note dir(): d3b. 会把返回的序列转换为列表并对其排序。

* Menu:

* 自定义模块属性访问::
* 实现描述器::
* 调用描述器::
* __slots__::


File: python.info,  Node: 自定义模块属性访问,  Next: 实现描述器,  Up: 自定义属性访问

4.3.3.3 自定义模块属性访问
..........................

特殊名称 ‘__getattr__’ 和 ‘__dir__’ 还可被用来自定义对模块属性的访问。模
块层级的 ‘__getattr__’ 函数应当接受一个参数，其名称为一个属性名，并返回
计算结果值或引发一个 *note AttributeError: 3a3.。如果通过正常查找即
*note object.__getattribute__(): 44f. 未在模块对象中找到某个属性，则
‘__getattr__’ 会在模块的 ‘__dict__’ 中查找，未找到时会引发一个 *note
AttributeError: 3a3.。如果找到，它会以属性名被调用并返回结果值。

‘__dir__’ 函数应当不接受任何参数，并且返回一个表示模块中可访问名称的字符
串序列。 此函数如果存在，将会重载一个模块中的标准 *note dir(): d3b. 查找
。

想要更细致地自定义模块的行为（设置属性和特性属性等待），可以将模块对象的
‘__class__’ 属性设置为一个 *note types.ModuleType: 6fa. 的子类。例如:

     import sys
     from types import ModuleType

     class VerboseModule(ModuleType):
         def __repr__(self):
             return f'Verbose {self.__name__}'

         def __setattr__(self, attr, value):
             print(f'Setting {attr}...')
             super().__setattr__(attr, value)

     sys.modules[__name__].__class__ = VerboseModule

     注解: 定义模块的 ‘__getattr__’ 和设置模块的 ‘__class__’ 只会影响使
     用属性访问语法进行的查找 – 直接访问模块全局变量（不论是通过模块内的
     代码还是通过对模块全局字典的引用）是不受影响的。

在 3.5 版更改: ‘__class__’ 模块属性改为可写。

3.7 新版功能: ‘__getattr__’ 和 ‘__dir__’ 模块属性。

参见
....

PEP 562(1) - 模块 __getattr__ 和 __dir__

     描述用于模块的 ‘__getattr__’ 和 ‘__dir__’ 函数。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0562


File: python.info,  Node: 实现描述器,  Next: 调用描述器,  Prev: 自定义模块属性访问,  Up: 自定义属性访问

4.3.3.4 实现描述器
..................

以下方法仅当一个包含该方法的类（称为 `描述器' 类）的实例出现于一个 `所有
者' 类中的时候才会起作用（该描述器必须在所有者类或其某个上级类的字典中）
。在以下示例中，“属性”指的是名称为所有者类 *note __dict__: 504. 中的特征
属性的键名的属性。

 -- 方法: object.__get__ (self, instance, owner=None)

     调用此方法以获取所有者类的属性（类属性访问）或该类的实例的属性（实
     例属性访问）。 可选的 `owner' 参数是所有者类而 `instance' 是被用来
     访问属性的实例，如果通过 `owner' 来访问属性则返回 ‘None’。

     此方法应当返回计算得到的属性值或是引发 *note AttributeError: 3a3. 异
     常。

     PEP 252(1) 指明 *note __get__(): 144b. 为带有一至二个参数的可调用对
     象。 Python 自身内置的描述器支持此规格定义；但是，某些第三方工具可
     能要求必须带两个参数。 Python 自身的 *note __getattribute__(): 44f.
     实现总是会传入两个参数，无论它们是否被要求提供。

 -- 方法: object.__set__ (self, instance, value)

     调用此方法以设置 `instance' 指定的所有者类的实例的属性为新值
     `value'。

     请注意，添加 *note __set__(): 144f. 或 *note __delete__(): 1450. 会
     将描述器变成“数据描述器”。 更多细节请参阅 *note 调用描述器: 1451.。

 -- 方法: object.__delete__ (self, instance)

     调用此方法以删除 `instance' 指定的所有者类的实例的属性。

 -- 方法: object.__set_name__ (self, owner, name)

     在所有者类 `owner' 创建时被调用。描述器会被赋值给 `name'。

          注解: *note __set_name__(): 4f0. 只是作为 *note type: 611. 构
          造器的一部分被隐式地调用，因此在某个类被初次创建之后又额外添加
          一个描述器时，那就需要显式地调用它并且附带适当的形参:

               class A:
                  pass
               descr = custom_descriptor()
               A.attr = descr
               descr.__set_name__(A, 'attr')

          详情参见 *note 创建类对象: 4ec.。

     3.6 新版功能.

属性 ‘__objclass__’ 会被 *note inspect: a1. 模块解读为指定此对象定义所在
的类（正确设置此属性有助于动态类属性的运行时内省）。对于可调用对象来说，
它可以指明预期或要求提供一个特定类型（或子类）的实例作为第一个位置参数（
例如，CPython 会为实现于 C 中的未绑定方法设置此属性）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0252


File: python.info,  Node: 调用描述器,  Next: __slots__,  Prev: 实现描述器,  Up: 自定义属性访问

4.3.3.5 调用描述器
..................

总的说来，描述器就是具有“绑定行为”的对象属性，其属性访问已被描述器协议中
的方法所重载，包括 *note __get__(): 144b, *note __set__(): 144f. 和
*note __delete__(): 1450.。如果一个对象定义了以上方法中的任意一个，它就
被称为描述器。

属性访问的默认行为是从一个对象的字典中获取、设置或删除属性。例如，‘a.x’
的查找顺序会从 ‘a.__dict__['x']’ 开始，然后是 ‘type(a).__dict__['x']’，
接下来依次查找 ‘type(a)’ 的上级基类，不包括元类。

但是，如果找到的值是定义了某个描述器方法的对象，则 Python 可能会重载默认
行为并转而发起调用描述器方法。这具体发生在优先级链的哪个环节则要根据所定
义的描述器方法及其被调用的方式来决定。

描述器发起调用的开始点是一个绑定 ‘a.x’。参数的组合方式依 ‘a’ 而定:

直接调用

     最简单但最不常见的调用方式是用户代码直接发起调用一个描述器方法:
     ‘x.__get__(a)’。

实例绑定

     如果绑定到一个对象实例，‘a.x’ 会被转换为调用:
     ‘type(a).__dict__['x'].__get__(a, type(a))’。

类绑定

     如果绑定到一个类，‘A.x’ 会被转换为调用:
     ‘A.__dict__['x'].__get__(None, A)’。

超绑定

     如果 ‘a’ 是 *note super: 4eb. 的一个实例，则绑定 ‘super(B,
     obj).m()’ 会在 ‘obj.__class__.__mro__’ 中搜索 ‘B’ 的直接上级基类
     ‘A’ 然后通过以下调用发起调用描述器: ‘A.__dict__['m'].__get__(obj,
     obj.__class__)’。

对于实例绑定，描述符调用的优先级取决于定义了哪些描述符方法。 描述符可以
定义 *note __get__(): 144b.、*note __set__(): 144f. 和 *note
__delete__(): 1450. 的任意组合。 如果它没有定义 *note __get__(): 144b.，
那么访问属性将返回描述符对象本身，除非对象的实例字典中有一个值。 如果描
述符定义了 *note __set__(): 144f. 和/或 *note __delete__(): 1450.，则它
是数据描述符； 如果两者都没有定义，则它是一个非数据描述符。 通常，数据描
述符同时定义 *note __get__(): 144b. 和 *note __set__(): 144f.，而非数据
描述符只有 *note __get__(): 144b. 方法。 定义了 *note __set__(): 144f. 和
*note __get__(): 144b. 的数据描述符总是覆盖实例字典中的重定义。 相反，非
数据描述符可以被实例覆盖。

Python 方法 (包括 *note staticmethod(): 1da. 和 *note classmethod():
1d9.) 都是作为非数据描述器来实现的。 因此实例可以重定义并重载方法。 这允
许单个实例获得与相同类的其他实例不一样的行为。

*note property(): 1d8. 函数是作为数据描述器来实现的。因此实例不能重载特
性属性的行为。


File: python.info,  Node: __slots__,  Prev: 调用描述器,  Up: 自定义属性访问

4.3.3.6 __slots__
.................

`__slots__' 允许我们显式地声明数据成员（例如特征属性）并禁止创建
`__dict__' 和 `__weakref__' (除非是在 `__slots__' 中显式地声明或是在父类
中可用。)

相比使用 `__dict__' 此方式可以显著地节省空间。 属性查找速度也可得到显著
的提升。

 -- 数据: object.__slots__

     这个类变量可赋值为字符串、可迭代对象或由实例使用的变量名构成的字符
     串序列。 `__slots__' 会为已声明的变量保留空间，并阻止自动为每个实例
     创建 `__dict__' 和 `__weakref__'。

* Menu:

* 使用 __slots__ 的注意事项::


File: python.info,  Node: 使用 __slots__ 的注意事项,  Up: __slots__

4.3.3.7 使用 `__slots__' 的注意事项
...................................

   * 当继承自一个未定义 `__slots__' 的类时，实例的 `__dict__' 和
     `__weakref__' 属性将总是可访问。

   * 没有 `__dict__' 变量，实例就不能给未在 `__slots__' 定义中列出的新变
     量赋值。尝试给一个未列出的变量名赋值将引发 *note AttributeError:
     3a3.。新变量需要动态赋值，就要将 ‘'__dict__'’ 加入到 `__slots__' 声
     明的字符串序列中。

   * 如果未给每个实例设置 `__weakref__' 变量，定义了 `__slots__' 的类就
     不支持对其实际的弱引用。如果需要弱引用支持，就要将 ‘'__weakref__'’
     加入到 `__slots__' 声明的字符串序列中。

   * `__slots__' 是通过为每个变量名创建描述器 (*note 实现描述器: 4f1.) 在
     类层级上实现的。因此，类属性不能被用来为通过 `__slots__' 定义的实例
     变量设置默认值；否则，类属性就会覆盖描述器赋值。

   * `__slots__' 声明的作用不只限于定义它的类。在父类中声明的
     `__slots__' 在其子类中同样可用。不过，子类将会获得 `__dict__' 和
     `__weakref__' 除非它们也定义了 `__slots__' (其中应该仅包含对任何 `额
     外' 名称的声明位置)。

   * 如果一个类定义的位置在某个基类中也有定义，则由基类位置定义的实例变
     量将不可访问（除非通过直接从基类获取其描述器的方式）。这会使得程序
     的含义变成未定义。未来可能会添加一个防止此情况的检查。

   * 非空的 `__slots__' 不适用于派生自“可变长度”内置类型例如 *note int:
     185.、*note bytes: 33a. 和 *note tuple: 486. 的派生类。

   * 任何非字符串可迭代对象都可以被赋值给 `__slots__'。映射也可以被使用
     ；不过，未来可能会分别赋给每个键具有特殊含义的值。

   * `__class__' 赋值仅在两个类具有相同的 `__slots__' 时才会起作用。

   * 带有多个父类声明位置的多重继承也是可用的，但仅允许一个父类具有由声
     明位置创建的属性（其他基类必须具有空的位置布局） —— 违反规则将引发
     *note TypeError: 193.。

   * 如果为 `__slots__' 使用了一个迭代器，则会为迭代器的每个值创建描述器
     。 但是 `__slots__' 属性将为一个空迭代器。


File: python.info,  Node: 自定义类创建,  Next: 自定义实例及子类检查,  Prev: 自定义属性访问,  Up: 特殊方法名称

4.3.3.8 自定义类创建
....................

当一个类继承其他类时，那个类的 `__init_subclass__' 会被调用。这样就可以
编写能够改变子类行为的类。这与类装饰器有紧密的关联，但是类装饰器是影响它
们所应用的特定类，而 ‘__init_subclass__’ 则只作用于定义了该方法的类所派
生的子类。

 -- 方法: classmethod object.__init_subclass__ (cls)

     当所在类派生子类时此方法就会被调用。`cls' 将指向新的子类。如果定义
     为一个普通实例方法，此方法将被隐式地转换为类方法。

     传入一个新类的关键字参数会被传给父类的 ‘__init_subclass__’。为了与
     其他使用 ‘__init_subclass__’ 的类兼容，应当根据需要去掉部分关键字参
     数再将其余的传给基类，例如:

          class Philosopher:
              def __init_subclass__(cls, /, default_name, **kwargs):
                  super().__init_subclass__(**kwargs)
                  cls.default_name = default_name

          class AustralianPhilosopher(Philosopher, default_name="Bruce"):
              pass

     ‘object.__init_subclass__’ 的默认实现什么都不做，只在带任意参数调用
     时引发一个错误。

          注解: 元类提示 ‘metaclass’ 将被其它类型机制消耗掉，并不会被传
          给 ‘__init_subclass__’ 的实现。实际的元类（而非显式的提示）可
          通过 ‘type(cls)’ 访问。

     3.6 新版功能.

* Menu:

* 元类::
* 解析 MRO 条目::
* 确定适当的元类::
* 准备类命名空间::
* 执行类主体::
* 创建类对象::
* 元类的作用::


File: python.info,  Node: 元类,  Next: 解析 MRO 条目,  Up: 自定义类创建

4.3.3.9 元类
............

默认情况下，类是使用 *note type(): 611. 来构建的。类体会在一个新的命名空
间内执行，类名会被局部绑定到 ‘type(name, bases, namespace)’ 的结果。

类创建过程可通过在定义行传入 ‘metaclass’ 关键字参数，或是通过继承一个包
含此参数的现有类来进行定制。在以下示例中，‘MyClass’ 和 ‘MySubclass’ 都是
‘Meta’ 的实例:

     class Meta(type):
         pass

     class MyClass(metaclass=Meta):
         pass

     class MySubclass(MyClass):
         pass

在类定义内指定的任何其他关键字参数都会在下面所描述的所有元类操作中进行传
递。

当一个类定义被执行时，将发生以下步骤:

   * 解析 MRO 条目；

   * 确定适当的元类；

   * 准备类命名空间；

   * 执行类主体；

   * 创建类对象。


File: python.info,  Node: 解析 MRO 条目,  Next: 确定适当的元类,  Prev: 元类,  Up: 自定义类创建

4.3.3.10 解析 MRO 条目
......................

如果在类定义中出现的基类不是 *note type: 611. 的实例，则使用
‘__mro_entries__’ 方法对其进行搜索，当找到结果时，它会以原始基类元组做参
数进行调用。此方法必须返回类的元组以替代此基类被使用。元组可以为空，在此
情况下原始基类将被忽略。

参见
....

PEP 560(1) - 对 typing 模块和泛型类型的核心支持

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0560


File: python.info,  Node: 确定适当的元类,  Next: 准备类命名空间,  Prev: 解析 MRO 条目,  Up: 自定义类创建

4.3.3.11 确定适当的元类
.......................

为一个类定义确定适当的元类是根据以下规则:

   * 如果没有基类且没有显式指定元类，则使用 *note type(): 611.；

   * 如果给出一个显式元类而且 `不是' *note type(): 611. 的实例，则其会被
     直接用作元类；

   * 如果给出一个 *note type(): 611. 的实例作为显式元类，或是定义了基类
     ，则使用最近派生的元类。

最近派生的元类会从显式指定的元类（如果有）以及所有指定的基类的元类（即
‘type(cls)’）中选取。最近派生的元类应为 `所有' 这些候选元类的一个子类型
。如果没有一个候选元类符合该条件，则类定义将失败并抛出 ‘TypeError’。


File: python.info,  Node: 准备类命名空间,  Next: 执行类主体,  Prev: 确定适当的元类,  Up: 自定义类创建

4.3.3.12 准备类命名空间
.......................

一旦确定了适当的元类，则将准备好类命名空间。 如果元类具有 ‘__prepare__’
属性，它会以 ‘namespace = metaclass.__prepare__(name, bases, **kwds)’ 的
形式被调用（其中如果有任何额外的关键字参数，则应当来自类定义）。
‘__prepare__’ 方法应该被实现为 *note classmethod(): 1d9.。 ‘__prepare__’
所返回的命名空间会被传入 ‘__new__’，但是当最终的类对象被创建时，该命名空
间会被拷贝到一个新的 ‘dict’ 中。

如果元类没有 ‘__prepare__’ 属性，则类命名空间将初始化为一个空的有序映射
。

参见
....

PEP 3115(1) - Python 3000 中的元类

     引入 ‘__prepare__’ 命名空间钩子

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3115


File: python.info,  Node: 执行类主体,  Next: 创建类对象,  Prev: 准备类命名空间,  Up: 自定义类创建

4.3.3.13 执行类主体
...................

类主体会以（类似于） ‘exec(body, globals(), namespace)’ 的形式被执行。普
通调用与 *note exec(): c4c. 的关键区别在于当类定义发生于函数内部时，词法
作用域允许类主体（包括任何方法）引用来自当前和外部作用域的名称。

但是，即使当类定义发生于函数内部时，在类内部定义的方法仍然无法看到在类作
用域层次上定义的名称。类变量必须通过实例的第一个形参或类方法来访问，或者
是通过下一节中描述的隐式词法作用域的 ‘__class__’ 引用。


File: python.info,  Node: 创建类对象,  Next: 元类的作用,  Prev: 执行类主体,  Up: 自定义类创建

4.3.3.14 创建类对象
...................

一旦执行类主体完成填充类命名空间，将通过调用 ‘metaclass(name, bases,
namespace, **kwds)’ 创建类对象（此处的附加关键字参数与传入 ‘__prepare__’
的相同）。

如果类主体中有任何方法引用了 ‘__class__’ 或 ‘super’，这个类对象会通过零
参数形式的 *note super(): 4eb.  ‘__class__’ 所引用，这是由编译器所创建的
隐式闭包引用。这使用零参数形式的 *note super(): 4eb. 能够正确标识正在基
于词法作用域来定义的类，而被用于进行当前调用的类或实例则是基于传递给方法
的第一个参数来标识的。

`CPython implementation detail:' 在 CPython 3.6 及之后的版本中，
‘__class__’ 单元会作为类命名空间中的 ‘__classcell__’ 条目被传给元类。 如
果存在，它必须被向上传播给 ‘type.__new__’ 调用，以便能正确地初始化该类。
如果不这样做，在 Python 3.8 中将引发 *note RuntimeError: 2bb.。

当使用默认的元类 *note type: 611. 或者任何最终会调用 ‘type.__new__’ 的元
类时，以下额外的自定义步骤将在创建类对象之后被发起调用:

   * 首先，‘type.__new__’ 将收集类命名空间中所有定义了 *note
     __set_name__(): 4f0. 方法的描述器；

   * 接下来，所有这些 ‘__set_name__’ 方法将使用所定义的类和特定描述器所
     赋的名称进行调用；

   * 最后，将在新类根据方法解析顺序所确定的直接父类上调用 *note
     __init_subclass__(): 4ea. 钩子。

在类对象创建之后，它会被传给包含在类定义中的类装饰器（如果有的话），得到
的对象将作为已定义的类绑定到局部命名空间。

当通过 ‘type.__new__’ 创建一个新类时，提供以作为命名空间形参的对象会被复
制到一个新的有序映射并丢弃原对象。这个新副本包装于一个只读代理中，后者则
成为类对象的 *note __dict__: 504. 属性。

参见
....

PEP 3135(1) - 新的超类型

     描述隐式的 ‘__class__’ 闭包引用

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3135


File: python.info,  Node: 元类的作用,  Prev: 创建类对象,  Up: 自定义类创建

4.3.3.15 元类的作用
...................

元类的潜在作用非常广泛。已经过尝试的设想包括枚举、日志、接口检查、自动委
托、自动特征属性创建、代理、框架以及自动资源锁定/同步等等。


File: python.info,  Node: 自定义实例及子类检查,  Next: 模拟泛型类型,  Prev: 自定义类创建,  Up: 特殊方法名称

4.3.3.16 自定义实例及子类检查
.............................

以下方法被用来重载 *note isinstance(): 457. 和 *note issubclass(): 458.
内置函数的默认行为。

特别地，元类 *note abc.ABCMeta: 822. 实现了这些方法以便允许将抽象基类（
ABC）作为“虚拟基类”添加到任何类或类型（包括内置类型），包括其他 ABC 之中
。

 -- 方法: class.__instancecheck__ (self, instance)

     如果 `instance' 应被视为 `class' 的一个（直接或间接）实例则返回真值
     。如果定义了此方法，则会被调用以实现 ‘isinstance(instance, class)’。

 -- 方法: class.__subclasscheck__ (self, subclass)

     Return true 如果 `subclass' 应被视为 `class' 的一个（直接或间接）子
     类则返回真值。如果定义了此方法，则会被调用以实现
     ‘issubclass(subclass, class)’。

请注意这些方法的查找是基于类的类型（元类）。它们不能作为类方法在实际的类
中被定义。这与基于实例被调用的特殊方法的查找是一致的，只有在此情况下实例
本身被当作是类。

参见
....

PEP 3119(1) - 引入抽象基类

     新增功能描述，通过 *note __instancecheck__(): 1460. 和 *note
     __subclasscheck__(): 1461. 来定制 *note isinstance(): 457. 和 *note
     issubclass(): 458. 行为，加入此功能的动机是出于向该语言添加抽象基类
     的内容（参见 *note abc: 4. 模块）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3119


File: python.info,  Node: 模拟泛型类型,  Next: 模拟可调用对象,  Prev: 自定义实例及子类检查,  Up: 特殊方法名称

4.3.3.17 模拟泛型类型
.....................

通过定义一个特殊方法，可以实现由 PEP 484(1) 所规定的泛型类语法 (例如
‘List[int]’):

 -- 方法: classmethod object.__class_getitem__ (cls, key)

     按照 `key' 参数指定的类型返回一个表示泛型类的专门化对象。

此方法的查找会基于对象自身，并且当定义于类体内部时，此方法将隐式地成为类
方法。请注意，此机制主要是被保留用于静态类型提示，不鼓励在其他场合使用。

参见
....

PEP 560(2) - 对 typing 模块和泛型类型的核心支持

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0560


File: python.info,  Node: 模拟可调用对象,  Next: 模拟容器类型,  Prev: 模拟泛型类型,  Up: 特殊方法名称

4.3.3.18 模拟可调用对象
.......................

 -- 方法: object.__call__ (self[, args...])

     此方法会在实例作为一个函数被“调用”时被调用；如果定义了此方法，则
     ‘x(arg1, arg2, ...)’ 就大致可以被改写为 ‘type(x).__call__(x, arg1,
     ...)’。


File: python.info,  Node: 模拟容器类型,  Next: 模拟数字类型,  Prev: 模拟可调用对象,  Up: 特殊方法名称

4.3.3.19 模拟容器类型
.....................

可以定义下列方法来实现容器对象。 容器通常属于序列（如列表或元组）或映射
（如字典），但也存在其他形式的容器。 前几个方法集被用于模拟序列或是模拟
映射；两者的不同之处在于序列允许的键应为整数 `k' 且 ‘0 <= k < N’ 其中
`N' 是序列或定义指定区间的项的切片对象的长度。 此外还建议让映射提供
‘keys()’, ‘values()’, ‘items()’, ‘get()’, ‘clear()’, ‘setdefault()’,
‘pop()’, ‘popitem()’, ‘copy()’ 以及 ‘update()’ 等方法，它们的行为应与
Python 标准字典对象的相应方法类似。 此外 *note collections.abc: 1f. 模块
提供了一个 *note MutableMapping: 9f7. 抽象基类以便根据由 *note
__getitem__(): 280, *note __setitem__(): c6a, *note __delitem__(): c6b,
和 ‘keys()’ 组成的基本集来创建所需的方法。 可变序列还应像 Python 标准列
表对象那样提供 ‘append()’, ‘count()’, ‘index()’, ‘extend()’, ‘insert()’,
‘pop()’, ‘remove()’, ‘reverse()’ 和 ‘sort()’ 等方法。 最后，序列类型还应
通过定义下文描述的 *note __add__(): 1467, *note __radd__(): 1468, *note
__iadd__(): e77, *note __mul__(): 1469, *note __rmul__(): 146a. 和 *note
__imul__(): 146b. 等方法来实现加法（指拼接）和乘法（指重复）；它们不应定
义其他数值运算符。 此外还建议映射和序列都实现 *note __contains__(): d30.
方法以允许高效地使用 ‘in’ 运算符；对于映射，‘in’ 应该搜索映射的键；对于
序列，则应搜索其中的值。 另外还建议映射和序列都实现 *note __iter__():
517. 方法以允许高效地迭代容器中的条目；对于映射，*note __iter__(): 517.
应当迭代对象的键；对于序列，则应当迭代其中的值。

 -- 方法: object.__len__ (self)

     调用此方法以实现内置函数 *note len(): 151.。应该返回对象的长度，以
     一个 ‘>=’ 0 的整数表示。此外，如果一个对象未定义 *note __bool__():
     c70. 方法而其 *note __len__(): dd3. 方法返回值为零，则在布尔运算中
     会被视为假值。

     `CPython implementation detail:' 在 CPython 中，要求长度最大为
     *note sys.maxsize: b4b.。如果长度大于 ‘sys.maxsize’ 则某些特性 (例
     如 *note len(): 151.) 可能会引发 *note OverflowError: 968.。要通过
     真值检测来防止引发 ‘OverflowError’，对象必须定义 *note __bool__():
     c70. 方法。

 -- 方法: object.__length_hint__ (self)

     调用此方法以实现 *note operator.length_hint(): 886.。 应该返回对象
     长度的估计值（可能大于或小于实际长度）。 此长度应为一个 ‘>=’ 0 的整
     数。 返回值也可以为 *note NotImplemented: 855.，这会被视作与
     ‘__length_hint__’ 方法完全不存在时一样处理。 此方法纯粹是为了优化性
     能，并不要求正确无误。

     3.4 新版功能.

     注解: 切片是通过下述三个专门方法完成的。以下形式的调用

          a[1:2] = b

     会为转写为

          a[slice(1, 2, None)] = b

     其他形式以此类推。略去的切片项总是以 ‘None’ 补全。

 -- 方法: object.__getitem__ (self, key)

     调用此方法以实现 ‘self[key]’ 的求值。对于序列类型，接受的键应为整数
     和切片对象。请注意负数索引（如果类想要模拟序列类型）的特殊解读是取
     决于 *note __getitem__(): 280. 方法。如果 `key' 的类型不正确则会引
     发 *note TypeError: 193. 异常；如果为序列索引集范围以外的值（在进行
     任何负数索引的特殊解读之后）则应引发 *note IndexError: e7d. 异常。
     对于映射类型，如果 `key' 找不到（不在容器中）则应引发 *note
     KeyError: 2c8. 异常。

          注解: *note for: c38. 循环在有不合法索引时会期待捕获 *note
          IndexError: e7d. 以便正确地检测到序列的结束。

 -- 方法: object.__setitem__ (self, key, value)

     调用此方法以实现向 ‘self[key]’ 赋值。注意事项与 *note
     __getitem__(): 280. 相同。为对象实现此方法应该仅限于需要映射允许基
     于键修改值或添加键，或是序列允许元素被替换时。不正确的 `key' 值所引
     发的异常应与 *note __getitem__(): 280. 方法的情况相同。

 -- 方法: object.__delitem__ (self, key)

     调用此方法以实现 ‘self[key]’ 的删除。注意事项与 *note
     __getitem__(): 280. 相同。为对象实现此方法应该权限于需要映射允许移
     除键，或是序列允许移除元素时。不正确的 `key' 值所引发的异常应与
     *note __getitem__(): 280. 方法的情况相同。

 -- 方法: object.__missing__ (self, key)

     此方法由 *note dict: 1b9.*note __getitem__(): 280. 在找不到字典中的
     键时调用以实现 dict 子类的 ‘self[key]’。

 -- 方法: object.__iter__ (self)

     此方法在需要为容器创建迭代器时被调用。此方法应该返回一个新的迭代器
     对象，它能够逐个迭代容器中的所有对象。对于映射，它应该逐个迭代容器
     中的键。

     迭代器对象也需要实现此方法；它们需要返回对象自身。有关迭代器对象的
     详情请参看 *note 迭代器类型: 146c. 一节。

 -- 方法: object.__reversed__ (self)

     此方法（如果存在）会被 *note reversed(): 18f. 内置函数调用以实现逆
     向迭代。它应当返回一个新的以逆序逐个迭代容器内所有对象的迭代器对象
     。

     如果未提供 *note __reversed__(): 537. 方法，则 *note reversed():
     18f. 内置函数将回退到使用序列协议 (*note __len__(): dd3. 和 *note
     __getitem__(): 280.)。支持序列协议的对象应当仅在能够提供比 *note
     reversed(): 18f. 所提供的实现更高效的实现时才提供 *note
     __reversed__(): 537. 方法。

成员检测运算符 (*note in: 7ac. 和 *note not in: 146d.) 通常以对容器进行
逐个迭代的方式来实现。 不过，容器对象可以提供以下特殊方法并采用更有效率
的实现，这样也不要求对象必须为可迭代对象。

 -- 方法: object.__contains__ (self, item)

     调用此方法以实现成员检测运算符。如果 `item' 是 `self' 的成员则应返
     回真，否则返回假。对于映射类型，此检测应基于映射的键而不是值或者键
     值对。

     对于未定义 *note __contains__(): d30. 的对象，成员检测将首先尝试通
     过 *note __iter__(): 517. 进行迭代，然后再使用 *note __getitem__():
     280. 的旧式序列迭代协议，参看 *note 语言参考中的相应部分: 146e.。


File: python.info,  Node: 模拟数字类型,  Next: with 语句上下文管理器,  Prev: 模拟容器类型,  Up: 特殊方法名称

4.3.3.20 模拟数字类型
.....................

定义以下方法即可模拟数字类型。特定种类的数字不支持的运算（例如非整数不能
进行位运算）所对应的方法应当保持未定义状态。

 -- 方法: object.__add__ (self, other)
 -- 方法: object.__sub__ (self, other)
 -- 方法: object.__mul__ (self, other)
 -- 方法: object.__matmul__ (self, other)
 -- 方法: object.__truediv__ (self, other)
 -- 方法: object.__floordiv__ (self, other)
 -- 方法: object.__mod__ (self, other)
 -- 方法: object.__divmod__ (self, other)
 -- 方法: object.__pow__ (self, other[, modulo])
 -- 方法: object.__lshift__ (self, other)
 -- 方法: object.__rshift__ (self, other)
 -- 方法: object.__and__ (self, other)
 -- 方法: object.__xor__ (self, other)
 -- 方法: object.__or__ (self, other)

     调用这些方法来实现二进制算术运算 (‘+’, ‘-’, ‘*’, ‘@’, ‘/’, ‘//’,
     ‘%’, *note divmod(): 153, *note pow(): 19b, ‘**’, ‘<<’, ‘>>’, ‘&’,
     ‘^’, ‘|’)。例如，求表达式 ‘x + y’ 的值，其中 `x' 是具有 *note
     __add__(): 1467. 方法的类的一个实例，则会调用 ‘x.__add__(y)’。*note
     __divmod__(): 790. 方法应该等价于使用 *note __floordiv__(): e3d. 和
     *note __mod__(): 1472.，它不应该被关联到 *note __truediv__(): 78f.。
     请注意如果要支持三元版本的内置 *note pow(): 19b. 函数，则 *note
     __pow__(): 1473. 的定义应该接受可选的第三个参数。

     如果这些方法中的某一个不支持与所提供参数进行运算，它应该返回
     ‘NotImplemented’。

 -- 方法: object.__radd__ (self, other)
 -- 方法: object.__rsub__ (self, other)
 -- 方法: object.__rmul__ (self, other)
 -- 方法: object.__rmatmul__ (self, other)
 -- 方法: object.__rtruediv__ (self, other)
 -- 方法: object.__rfloordiv__ (self, other)
 -- 方法: object.__rmod__ (self, other)
 -- 方法: object.__rdivmod__ (self, other)
 -- 方法: object.__rpow__ (self, other[, modulo])
 -- 方法: object.__rlshift__ (self, other)
 -- 方法: object.__rrshift__ (self, other)
 -- 方法: object.__rand__ (self, other)
 -- 方法: object.__rxor__ (self, other)
 -- 方法: object.__ror__ (self, other)

     调用这些方法来实现具有反射（交换）操作数的二进制算术运算 (‘+’, ‘-’,
     ‘*’, ‘@’, ‘/’, ‘//’, ‘%’, *note divmod(): 153, *note pow(): 19b,
     ‘**’, ‘<<’, ‘>>’, ‘&’, ‘^’, ‘|’)。这些成员函数仅会在左操作数不支持
     相应运算 (1) 且两个操作数类型不同时被调用。(2) 例如，求表达式 ‘x -
     y’ 的值，其中 `y' 是具有 *note __rsub__(): 1479. 方法的类的一个实例
     ，则当 ‘x.__sub__(y)’ 返回 `NotImplemented' 时会调用
     ‘y.__rsub__(x)’。

     请注意三元版的 *note pow(): 19b. 并不会尝试调用 *note __rpow__():
     147d. (因为强制转换规则会太过复杂)。

          注解: 如果右操作数类型为左操作数类型的一个子类，且该子类提供了
          指定运算的反射方法，则此方法将先于左操作数的非反射方法被调用。
          此行为可允许子类重载其祖先类的运算符。

 -- 方法: object.__iadd__ (self, other)
 -- 方法: object.__isub__ (self, other)
 -- 方法: object.__imul__ (self, other)
 -- 方法: object.__imatmul__ (self, other)
 -- 方法: object.__itruediv__ (self, other)
 -- 方法: object.__ifloordiv__ (self, other)
 -- 方法: object.__imod__ (self, other)
 -- 方法: object.__ipow__ (self, other[, modulo])
 -- 方法: object.__ilshift__ (self, other)
 -- 方法: object.__irshift__ (self, other)
 -- 方法: object.__iand__ (self, other)
 -- 方法: object.__ixor__ (self, other)
 -- 方法: object.__ior__ (self, other)

     调用这些方法来实现扩展算术赋值 (‘+=’, ‘-=’, ‘*=’, ‘@=’, ‘/=’,
     ‘//=’, ‘%=’, ‘**=’, ‘<<=’, ‘>>=’, ‘&=’, ‘^=’, ‘|=’)。这些方法应该尝
     试进行自身操作 (修改 `self') 并返回结果 (结果应该但并非必须为
     `self')。如果某个方法未被定义，相应的扩展算术赋值将回退到普通方法。
     例如，如果 `x' 是具有 *note __iadd__(): e77. 方法的类的一个实例，则
     ‘x += y’ 就等价于 ‘x = x.__iadd__(y)’。否则就如 ‘x + y’ 的求值一样
     选择 ‘x.__add__(y)’ 和 ‘y.__radd__(x)’。在某些情况下，扩展赋值可导
     致未预期的错误 (参见 *note 为什么 a_tuple[i] += [’item’]
     会在执行加法时引发异常？: 148c.)，但此行为实际上是数据模型的一个组
     成部分。

          注解: 由于 ‘**=’ 的分配机制存在一个错误，定义了 *note
          __ipow__(): 1486. 但是返回 ‘NotImplemented’ 的类将无法回退到
          ‘x.__pow__(y)’ 和 ‘y.__rpow__(x)’。 此错误在 Python 3.10 中被
          修正。

 -- 方法: object.__neg__ (self)
 -- 方法: object.__pos__ (self)
 -- 方法: object.__abs__ (self)
 -- 方法: object.__invert__ (self)

     调用此方法以实现一元算术运算 (‘-’, ‘+’, *note abs(): 12cf. 和 ‘~’)。

 -- 方法: object.__complex__ (self)
 -- 方法: object.__int__ (self)
 -- 方法: object.__float__ (self)

     调用这些方法以实现内置函数 *note complex(): 18a, *note int(): 185.
     和 *note float(): 188.。应当返回一个相应类型的值。

 -- 方法: object.__index__ (self)

     调用此方法以实现 *note operator.index(): 1491. 以及 Python 需要无损
     地将数字对象转换为整数对象的场合（例如切片或是内置的 *note bin():
     c48, *note hex(): c6e. 和 *note oct(): c6d. 函数)。 存在此方法表明
     数字对象属于整数类型。 必须返回一个整数。

     如果未定义 *note __int__(): 18c, *note __float__(): 18d. 和 *note
     __complex__(): 18e. 则相应的内置函数 *note int(): 185, *note
     float(): 188. 和 *note complex(): 18a. 将回退为 *note __index__():
     18b.。

 -- 方法: object.__round__ (self[, ndigits])
 -- 方法: object.__trunc__ (self)
 -- 方法: object.__floor__ (self)
 -- 方法: object.__ceil__ (self)

     调用这些方法以实现内置函数 *note round(): c75. 以及 *note math: b2.
     函数 *note trunc(): d36, *note floor(): d34. 和 *note ceil(): d35.。
     除了将 `ndigits' 传给 ‘__round__()’ 的情况之外这些方法的返回值都应
     当是原对象截断为 *note Integral: 1434. (通常为 *note int: 185.)。

     如果未定义 *note __int__(): 18c. 则内置函数 *note int(): 185. 会回
     退到 *note __trunc__(): 1493.。

   ---------- Footnotes ----------

   (1) (3) 这里的“不支持”是指该类无此方法，或方法返回 ‘NotImplemented’。
如果你想强制回退到右操作数的反射方法，请不要设置方法为 ‘None’ — 那会造成
显式地 `阻塞' 此种回退的相反效果。

   (2) (4) 对于相同类型的操作数，如果非反射方法 – 例如 *note __add__():
1467. – 失败则会认为整个运算都不被支持，这就是反射方法未被调用的原因。


File: python.info,  Node: with 语句上下文管理器,  Next: 特殊方法查找,  Prev: 模拟数字类型,  Up: 特殊方法名称

4.3.3.21 with 语句上下文管理器
..............................

`上下文管理器' 是一个对象，它定义了在执行 *note with: 6f2. 语句时要建立
的运行时上下文。 上下文管理器处理进入和退出所需运行时上下文以执行代码块
。 通常使用 ‘with’ 语句（在 *note with 语句: 6f2. 中描述），但是也可以通
过直接调用它们的方法来使用。

上下文管理器的典型用法包括保存和恢复各种全局状态，锁定和解锁资源，关闭打
开的文件等等。

要了解上下文管理器的更多信息，请参阅 *note 上下文管理器类型: 1498.。

 -- 方法: object.__enter__ (self)

     进入与此对象相关的运行时上下文。 *note with: 6f2. 语句将会绑定这个
     方法的返回值到 ‘as’ 子句中指定的目标，如果有的话。

 -- 方法: object.__exit__ (self, exc_type, exc_value, traceback)

     退出关联到此对象的运行时上下文。 各个参数描述了导致上下文退出的异常
     。 如果上下文是无异常地退出的，三个参数都将为 *note None: 158.。

     如果提供了异常，并且希望方法屏蔽此异常（即避免其被传播），则应当返
     回真值。 否则的话，异常将在退出此方法时按正常流程处理。

     请注意 *note __exit__(): c9e. 方法不应该重新引发被传入的异常，这是
     调用者的责任。

参见
....

PEP 343(1) - "with" 语句

     Python *note with: 6f2. 语句的规范描述、背景和示例。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0343


File: python.info,  Node: 特殊方法查找,  Prev: with 语句上下文管理器,  Up: 特殊方法名称

4.3.3.22 特殊方法查找
.....................

对于自定义类来说，特殊方法的隐式发起调用仅保证在其定义于对象类型中时能正
确地发挥作用，而不能定义在对象实例字典中。 该行为就是以下代码会引发异常
的原因。:

     >>> class C:
     ...     pass
     ...
     >>> c = C()
     >>> c.__len__ = lambda: 5
     >>> len(c)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: object of type 'C' has no len()

此行为背后的原理在于包括类型对象在内的所有对象都会实现的几个特殊方法，例
如 *note __hash__(): 349. 和 *note __repr__(): 347.。 如果这些方法的隐式
查找使用了传统的查找过程，它们会在对类型对象本身发起调用时失败:

     >>> 1 .__hash__() == hash(1)
     True
     >>> int.__hash__() == hash(int)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: descriptor '__hash__' of 'int' object needs an argument

以这种方式不正确地尝试发起调用一个类的未绑定方法有时被称为‘元类混淆’，可
以通过在查找特殊方法时绕过实例的方式来避免:

     >>> type(1).__hash__(1) == hash(1)
     True
     >>> type(int).__hash__(int) == hash(int)
     True

除了为了正确性而绕过任何实例属性之外，隐式特殊方法查找通常也会绕过 *note
__getattribute__(): 44f. 方法，甚至包括对象的元类:

     >>> class Meta(type):
     ...     def __getattribute__(*args):
     ...         print("Metaclass getattribute invoked")
     ...         return type.__getattribute__(*args)
     ...
     >>> class C(object, metaclass=Meta):
     ...     def __len__(self):
     ...         return 10
     ...     def __getattribute__(*args):
     ...         print("Class getattribute invoked")
     ...         return object.__getattribute__(*args)
     ...
     >>> c = C()
     >>> c.__len__()                 # Explicit lookup via instance
     Class getattribute invoked
     10
     >>> type(c).__len__(c)          # Explicit lookup via type
     Metaclass getattribute invoked
     10
     >>> len(c)                      # Implicit lookup
     10

以这种方式绕过 *note __getattribute__(): 44f. 机制为解析器内部的速度优化
提供了显著的空间，其代价则是牺牲了处理特殊方法时的一些灵活性（特殊方法
`必须' 设置在类对象本身上以便始终一致地由解释器发起调用）。


File: python.info,  Node: 协程,  Prev: 特殊方法名称,  Up: 数据模型

4.3.4 协程
----------

* Menu:

* 可等待对象::
* 协程对象::
* 异步迭代器::
* 异步上下文管理器::


File: python.info,  Node: 可等待对象,  Next: 协程对象,  Up: 协程

4.3.4.1 可等待对象
..................

*note awaitable: 521. 对象主要实现了 *note __await__(): 64b. 方法。 从
*note async def: 285. 函数返回的 *note 协程对象: 1a7. 即属于可等待对象。

     注解: 从带有 *note types.coroutine(): 785. 或 *note
     asyncio.coroutine(): 283. 装饰器的生成器返回的 *note generator
     iterator: 45f. 对象也属于可等待对象，但它们并未实现 *note
     __await__(): 64b.。

 -- 方法: object.__await__ (self)

     必须返回一个 *note iterator: 104b.。 应当被用来实现 *note
     awaitable: 521. 对象。 例如，*note asyncio.Future: 44b. 实现了此方
     法以与 *note await: 1a4. 表达式相兼容。

3.5 新版功能.

参见
....

PEP 492(1) 了解有关可等待对象的详细信息。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: 协程对象,  Next: 异步迭代器,  Prev: 可等待对象,  Up: 协程

4.3.4.2 协程对象
................

*note 协程对象: 1a7. 属于 *note awaitable: 521. 对象。 协程的执行可通过
调用 *note __await__(): 64b. 并迭代其结果来控制。 当协程结束执行并返回时
，迭代器会引发 *note StopIteration: 48e.，该异常的 ‘value’ 属性将存放返
回值。 如果协程引发了异常，它会被迭代器所传播。 协程不应直接引发未处理的
*note StopIteration: 48e. 异常。

协程也具有下面列出的方法，它们类似于生成器的对应方法 (参见 *note
生成器-迭代器的方法: 149d.)。 但是，与生成器不同，协程并不直接支持迭代。

在 3.5.2 版更改: 等待一个协程超过一次将引发 *note RuntimeError: 2bb.。

 -- 方法: coroutine.send (value)

     开始或恢复协程的执行。 如果 `value' 为 ‘None’，则这相当于前往 *note
     __await__(): 64b. 所返回迭代器的下一项。 如果 `value' 不为 ‘None’，
     此方法将委托给导致协程挂起的迭代器的 *note send(): 149f. 方法。 其
     结果（返回值，*note StopIteration: 48e. 或是其他异常）将与上述对
     *note __await__(): 64b. 返回值进行迭代的结果相同。

 -- 方法: coroutine.throw (type[, value[, traceback]])

     在协程内引发指定的异常。 此方法将委托给导致协程挂起的迭代器的 *note
     throw(): 14a1. 方法，如果存在该方法。 否则的话，异常会在挂起点被引
     发。 其结果（返回值，*note StopIteration: 48e. 或是其他异常）将与上
     述对 *note __await__(): 64b. 返回值进行迭代的结果相同。 如果异常未
     在协程内被捕获，则将回传给调用者。

 -- 方法: coroutine.close ()

     此方法会使得协程清理自身并退出。 如果协程被挂起，此方法会先委托给导
     致协程挂起的迭代器的 *note close(): 14a3. 方法，如果存在该方法。 然
     后它会在挂起点引发 *note GeneratorExit: d3a.，使得协程立即清理自身
     。 最后，协程会被标记为已结束执行，即使它根本未被启动。

     当协程对象将要被销毁时，会使用以上处理过程来自动关闭。


File: python.info,  Node: 异步迭代器,  Next: 异步上下文管理器,  Prev: 协程对象,  Up: 协程

4.3.4.3 异步迭代器
..................

`异步迭代器' 可以在其 ‘__anext__’ 方法中调用异步代码。

异步迭代器可在 *note async for: 2e4. 语句中使用。

 -- 方法: object.__aiter__ (self)

     必须返回一个 `异步迭代器' 对象。

 -- 方法: object.__anext__ (self)

     必须返回一个 `可迭代对象' 输出迭代器的下一结果值。 当迭代结束时应该
     引发 *note StopAsyncIteration: 1022. 错误。

异步可迭代对象的一个示例:

     class Reader:
         async def readline(self):
             ...

         def __aiter__(self):
             return self

         async def __anext__(self):
             val = await self.readline()
             if val == b'':
                 raise StopAsyncIteration
             return val

3.5 新版功能.

在 3.7 版更改: 在 Python 3.7 之前，‘__aiter__’ 可以返回一个 `可迭代对象'
并解析为 *note 异步迭代器: 64e.。

从 Python 3.7 开始，‘__aiter__’ 必须 返回一个异步迭代器对象。 返回任何其
他对象都将导致 *note TypeError: 193. 错误。


File: python.info,  Node: 异步上下文管理器,  Prev: 异步迭代器,  Up: 协程

4.3.4.4 异步上下文管理器
........................

`异步上下文管理器' 是 `上下文管理器' 的一种，它能够在其 ‘__aenter__’ 和
‘__aexit__’ 方法中暂停执行。

异步上下文管理器可在 *note async with: 64c. 语句中使用。

 -- 方法: object.__aenter__ (self)

     在语义上类似于 *note __enter__(): c9d.，仅有的区别是它必须返回一个
     `可等待对象'。

 -- 方法: object.__aexit__ (self, exc_type, exc_value, traceback)

     在语义上类似于 *note __exit__(): c9e.，仅有的区别是它必须返回一个
     `可等待对象'。

异步上下文管理器类的一个示例:

     class AsyncContextManager:
         async def __aenter__(self):
             await log('entering context')

         async def __aexit__(self, exc_type, exc, tb):
             await log('exiting context')

3.5 新版功能.

备注
....


File: python.info,  Node: 执行模型,  Next: 导入系统,  Prev: 数据模型,  Up: Python语言参考

4.4 执行模型
============

* Menu:

* 程序的结构::
* 命名与绑定::
* 异常: 异常<2>.


File: python.info,  Node: 程序的结构,  Next: 命名与绑定,  Up: 执行模型

4.4.1 程序的结构
----------------

Python 程序是由代码块构成的。 `代码块' 是被作为一个单元来执行的一段
Python 程序文本。 以下几个都是代码块：模块、函数体和类定义。 交互式输入
的每条命令都是一个代码块。 一个脚本文件（作为标准输入发送给解释器或是作
为命令行参数发送给解释器的文件）也是一个代码块。 一条脚本命令（通过
*note -c: 121b. 选项在解释器命令行中指定的命令）也是一个代码块。 传递给
内置函数 *note eval(): b98. 和 *note exec(): c4c. 的字符串参数也是代码块
。

代码块在 `执行帧' 中被执行。 一个帧会包含某些管理信息（用于调试）并决定
代码块执行完成后应前往何处以及如何继续执行。


File: python.info,  Node: 命名与绑定,  Next: 异常<2>,  Prev: 程序的结构,  Up: 执行模型

4.4.2 命名与绑定
----------------

* Menu:

* 名称的绑定::
* 名称的解析::
* 内置命名空间和受限的执行::
* 与动态特性的交互::


File: python.info,  Node: 名称的绑定,  Next: 名称的解析,  Up: 命名与绑定

4.4.2.1 名称的绑定
..................

`名称' 用于指代对象。 名称是通过名称绑定操作来引入的。

以下构造会绑定名称：传给函数的正式形参，*note import: c25. 语句，类与函
数定义（这会在定义的代码块中绑定类或函数名称）以及发生以标识符为目标的赋
值，*note for: c38. 循环的开头，或 *note with: 6f2. 语句和 *note except:
b46. 子句的 ‘as’ 之后。 ‘import’ 语句的 ‘from ... import *’ 形式会绑定在
被导入模块中定义的所有名称，那些以下划线开头的除外。 这种形式仅在模块层
级上被使用。

*note del: 127e. 语句的目标也被视作一种绑定（虽然其实际语义为解除名称绑
定）。

每条赋值或导入语句均发生于类或函数内部定义的代码块中，或是发生于模块层级
（即最高层级的代码块）。

如果名称绑定在一个代码块中，则为该代码块的局部变量，除非声明为 *note
nonlocal: c47. 或 *note global: 1254.。 如果名称绑定在模块层级，则为全局
变量。 (模块代码块的变量既为局部变量又为全局变量。) 如果变量在一个代码块
中被使用但不是在其中定义，则为 `自由变量'。

每个在程序文本中出现的名称是指由以下名称解析规则所建立的对该名称的 `绑定
'。


File: python.info,  Node: 名称的解析,  Next: 内置命名空间和受限的执行,  Prev: 名称的绑定,  Up: 命名与绑定

4.4.2.2 名称的解析
..................

`作用域' 定义了一个代码块中名称的可见性。 如果代码块中定义了一个局部变量
，则其作用域包含该代码块。 如果定义发生于函数代码块中，则其作用域会扩展
到该函数所包含的任何代码块，除非有某个被包含代码块引入了对该名称的不同绑
定。

当一个名称在代码块中被使用时，会由包含它的最近作用域来解析。 对一个代码
块可见的所有这种作用域的集合称为该代码块的 `环境'。

当一个名称完全找不到时，将会引发 *note NameError: d83. 异常。 如果当前作
用域为函数作用域，且该名称指向一个局部变量，而此变量在该名称被使用的时候
尚未绑定到特定值，将会引发 *note UnboundLocalError: e7e. 异常。 *note
UnboundLocalError: e7e. 为 *note NameError: d83. 的一个子类。

如果一个代码块内的任何位置发生名称绑定操作，则代码块内所有对该名称的使用
会被认为是对当前代码块的引用。 当一个名称在其被绑定前就在代码块内被使用
时则会导致错误。 这个一个很微妙的规则。 Python 缺少声明语法，并允许名称
绑定操作发生于代码块内的任何位置。 一个代码块的局部变量可通过在整个代码
块文本中扫描名称绑定操作来确定。

如果 *note global: 1254. 语句出现在一个代码块中，则所有对该语句所指定名
称的使用都是在最高层级命名空间内对该名称绑定的引用。 名称在最高层级命名
内的解析是通过全局命名空间，也就是包含该代码块的模块的命名空间，以及内置
命名空间即 *note builtins: 13. 模块的命名空间。 全局命名空间会先被搜索。
如果未在其中找到指定名称，再搜索内置命名空间。 ‘global’ 语句必须位于所有
对其所指定名称的使用之前。

*note global: 1254. 语句与同一代码块中名称绑定具有相同的作用域。 如果一
个自由变量的最近包含作用域中有一条 global 语句，则该自由变量也会被当作是
全局变量。

*note nonlocal: c47. 语句会使得相应的名称指向之前在最近包含函数作用域中
绑定的变量。 如果指定名称不存在于任何包含函数作用域中则将在编译时引发
*note SyntaxError: 460.。

模块的作用域会在模块第一次被导入时自动创建。 一个脚本的主模块总是被命名
为 *note __main__: 1.。

类定义代码块以及传给 *note exec(): c4c. 和 *note eval(): b98. 的参数是名
称解析上下文中的特殊情况。 类定义是可能使用并定义名称的可执行语句。 这些
引用遵循正常的名称解析规则，例外之处在于未绑定的局部变量将会在全局命名空
间中查找。 类定义的命名空间会成为该类的属性字典。 在类代码块中定义的名称
的作用域会被限制在类代码块中；它不会扩展到方法的代码块中 – 这也包括推导
式和生成器表达式，因为它们都是使用函数作用域实现的。 这意味着以下代码将
会失败:

     class A:
         a = 42
         b = list(a + i for i in range(10))


File: python.info,  Node: 内置命名空间和受限的执行,  Next: 与动态特性的交互,  Prev: 名称的解析,  Up: 命名与绑定

4.4.2.3 内置命名空间和受限的执行
................................

`CPython implementation detail:' 用户不应该接触 ‘__builtins__’，严格说来
它属于实现细节。 用户如果要重载内置命名空间中的值则应该 *note import:
c25. *note builtins: 13. 并相应地修改该模块中的属性。

与一个代码块的执行相关联的内置命名空间实际上是通过在其全局命名空间中搜索
名称 ‘__builtins__’ 来找到的；这应该是一个字典或一个模块（在后一种情况下
会使用该模块的字典）。 默认情况下，当在 *note __main__: 1. 模块中时，
‘__builtins__’ 就是内置模块 *note builtins: 13.；当在任何其他模块中时，
‘__builtins__’ 则是 *note builtins: 13. 模块自身的字典的一个别名。


File: python.info,  Node: 与动态特性的交互,  Prev: 内置命名空间和受限的执行,  Up: 命名与绑定

4.4.2.4 与动态特性的交互
........................

自由变量的名称解析发生于运行时而不是编译时。 这意味着以下代码将打印出
42:

     i = 10
     def f():
         print(i)
     i = 42
     f()

*note eval(): b98. 和 *note exec(): c4c. 函数没有对完整环境的访问权限来
解析名称。 名称可以在调用者的局部和全局命名空间中被解析。 自由变量的解析
不是在最近包含命名空间中，而是在全局命名空间中。 (1) *note exec(): c4c.
和 *note eval(): b98. 函数有可选参数用来重载全局和局部命名空间。 如果只
指定一个命名空间，则它会同时作用于两者。

   ---------- Footnotes ----------

   (1) (1) 出现这样的限制是由于通过这些操作执行的代码在模块被编译的时候
并不可用。


File: python.info,  Node: 异常<2>,  Prev: 命名与绑定,  Up: 执行模型

4.4.3 异常
----------

异常是中断代码块的正常控制流程以便处理错误或其他异常条件的一种方式。 异
常会在错误被检测到的位置 `引发'，它可以被当前包围代码块或是任何直接或间
接发起调用发生错误的代码块的其他代码块所 `处理'。

Python 解析器会在检测到运行时错误（例如零作为被除数）的时候引发异常。
Python 程序也可以通过 *note raise: c4a. 语句显式地引发异常。 异常处理是
通过 *note try: d7a. ...  *note except: b46. 语句来指定的。 该语句的
*note finally: 183. 子句可被用来指定清理代码，它并不处理异常，而是无论之
前的代码是否发生异常都会被执行。

Python 的错误处理采用的是“终止”模型：异常处理器可以找出发生了什么问题，
并在外层继续执行，但它不能修复错误的根源并重试失败的操作（除非通过从顶层
重新进入出错的代码片段）。

当一个异常完全未被处理时，解释器会终止程序的执行，或者返回交互模式的主循
环。 无论是哪种情况，它都会打印栈回溯信息，除非是当异常为 *note
SystemExit: 605. 的时候。

异常是通过类实例来标识的。 *note except: b46. 子句会依据实例的类来选择：
它必须引用实例的类或是其所属的基类。 实例可通过处理器被接收，并可携带有
关异常条件的附加信息。

     注解: 异常消息不是 Python API 的组成部分。 其内容可能在 Python 升级
     到新版本时不经警告地发生改变，不应该被需要在多版本解释器中运行的代
     码所依赖。

另请参看 *note try 语句: d7a. 小节中对 *note try: d7a. 语句的描述以及
*note raise 语句: c4a. 小节中对 *note raise: c4a. 语句的描述。

备注
....


File: python.info,  Node: 导入系统,  Next: 表达式,  Prev: 执行模型,  Up: Python语言参考

4.5 导入系统
============

一个 *note module: 14bd. 内的 Python 代码通过 *note importing: 14be. 操
作就能够访问另一个模块内的代码。 *note import: c25. 语句是发起调用导入机
制的最常用方式，但不是唯一的方式。 *note importlib.import_module(): b1b.
以及内置的 *note __import__(): 619. 等函数也可以被用来发起调用导入机制。

*note import: c25. 语句结合了两个操作；它先搜索指定名称的模块，然后将搜
索结果绑定到当前作用域中的名称。 ‘import’ 语句的搜索操作被定义为对 *note
__import__(): 619. 函数的调用并带有适当的参数。 *note __import__(): 619.
的返回值会被用于执行 ‘import’ 语句的名称绑定操作。 请参阅 ‘import’ 语句
了解名称绑定操作的更多细节。

对 *note __import__(): 619. 的直接调用将仅执行模块搜索以及在找到时的模块
创建操作。 不过也可能产生某些副作用，例如导入父包和更新各种缓存 (包括
*note sys.modules: f36.)，只有 *note import: c25. 语句会执行名称绑定操作
。

当 *note import: c25. 语句被执行时，标准的内置 *note __import__(): 619.
函数会被调用。 其他发起调用导入系统的机制 (例如 *note
importlib.import_module(): b1b.) 可能会选择绕过 *note __import__(): 619.
并使用它们自己的解决方案来实现导入机制。

当一个模块首次被导入时，Python 会搜索该模块，如果找到就创建一个 module 对
象 (1) 并初始化它。 如果指定名称的模块未找到，则会引发 *note
ModuleNotFoundError: 3a2.。 当发起调用导入机制时，Python 会实现多种策略
来搜索指定名称的模块。 这些策略可以通过使用使用下文所描述的多种钩子来加
以修改和扩展。

在 3.3 版更改: 导入系统已被更新以完全实现 PEP 302(2) 中的第二阶段要求。
不会再有任何隐式的导入机制 —— 整个导入系统都通过 *note sys.meta_path:
5ef. 暴露出来。 此外，对原生命名空间包的支持也已被实现 (参见 PEP
420(3))。

* Menu:

* importlib: importlib<7>.
* 包: 包<2>.
* 搜索::
* 加载::
* 基于路径的查找器::
* 替换标准导入系统::
* 包相对导入::
* 有关 __main__ 的特殊事项::
* 开放问题项::
* 参考文献::

   ---------- Footnotes ----------

   (1) (1) 参见 *note types.ModuleType: 6fa.。

   (2) https://www.python.org/dev/peps/pep-0302

   (3) https://www.python.org/dev/peps/pep-0420


File: python.info,  Node: importlib<7>,  Next: 包<2>,  Up: 导入系统

4.5.1 ‘importlib’
-----------------

*note importlib: 9b. 模块提供了一个丰富的 API 用来与导入系统进行交互。 例
如 *note importlib.import_module(): b1b. 提供了相比内置的 *note
__import__(): 619. 更推荐、更简单的 API 用来发起调用导入机制。 更多细节
请参看 *note importlib: 9b. 库文档。


File: python.info,  Node: 包<2>,  Next: 搜索,  Prev: importlib<7>,  Up: 导入系统

4.5.2 包
--------

Python 只有一种模块对象类型，所有模块都属于该类型，无论模块是用 Python、
C 还是别的语言实现。 为了帮助组织模块并提供名称层次结构，Python 还引入了
*note 包: ec6. 的概念。

你可以把包看成是文件系统中的目录，并把模块看成是目录中的文件，但请不要对
这个类比做过于字面的理解，因为包和模块不是必须来自于文件系统。 为了方便
理解本文档，我们将继续使用这种目录和文件的类比。 与文件系统一样，包通过
层次结构进行组织，在包之内除了一般的模块，还可以有子包。

要注意的一个重点概念是所有包都是模块，但并非所有模块都是包。 或者换句话
说，包只是一种特殊的模块。 特别地，任何具有 ‘__path__’ 属性的模块都会被
当作是包。

所有模块都有自己的名字。 子包名与其父包名以点号分隔，与 Python 的标准属
性访问语法一致。 例如你可能看到一个名为 *note sys: fe. 的模块，以及一个
名为 *note email: 69. 的包，这个包又有一个名为 *note email.mime: 73. 的
子包和该子包中的名为 ‘email.mime.text’ 的子包。

* Menu:

* 常规包::
* 命名空间包::


File: python.info,  Node: 常规包,  Next: 命名空间包,  Up: 包<2>

4.5.2.1 常规包
..............

Python 定义了两种类型的包，*note 常规包: 14c2. 和 *note 命名空间包:
14c3.。 常规包是传统的包类型，它们在 Python 3.2 及之前就已存在。 常规包
通常以一个包含 ‘__init__.py’ 文件的目录形式实现。 当一个常规包被导入时，
这个 ‘__init__.py’ 文件会隐式地被执行，它所定义的对象会被绑定到该包命名
空间中的名称。‘__init__.py’ 文件可以包含与任何其他模块中所包含的 Python
代码相似的代码，Python 将在模块被导入时为其添加额外的属性。

例如，以下文件系统布局定义了一个最高层级的 ‘parent’ 包和三个子包:

     parent/
         __init__.py
         one/
             __init__.py
         two/
             __init__.py
         three/
             __init__.py

导入 ‘parent.one’ 将隐式地执行 ‘parent/__init__.py’ 和
‘parent/one/__init__.py’。 后续导入 ‘parent.two’ 或 ‘parent.three’ 则将
分别执行 ‘parent/two/__init__.py’ 和 ‘parent/three/__init__.py’。


File: python.info,  Node: 命名空间包,  Prev: 常规包,  Up: 包<2>

4.5.2.2 命名空间包
..................

命名空间包是由多个 *note 部分: 14c5. 构成的，每个部分为父包增加一个子包
。 各个部分可能处于文件系统的不同位置。 部分也可能处于 zip 文件中、网络
上，或者 Python 在导入期间可以搜索的其他地方。 命名空间包并不一定会直接
对应到文件系统中的对象；它们有可能是无实体表示的虚拟模块。

命名空间包的 ‘__path__’ 属性不使用普通的列表。 而是使用定制的可迭代类型
，如果其父包的路径 (或者最高层级包的 *note sys.path: 490.) 发生改变，这
种对象会在该包内的下一次导入尝试时自动执行新的对包部分的搜索。

命名空间包没有 ‘parent/__init__.py’ 文件。 实际上，在导入搜索期间可能找
到多个 ‘parent’ 目录，每个都由不同的部分所提供。 因此 ‘parent/one’ 的物
理位置不一定与 ‘parent/two’ 相邻。 在这种情况下，Python 将为顶级的
‘parent’ 包创建一个命名空间包，无论是它本身还是它的某个子包被导入。

另请参阅 PEP 420(1) 了解对命名空间包的规格描述。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0420


File: python.info,  Node: 搜索,  Next: 加载,  Prev: 包<2>,  Up: 导入系统

4.5.3 搜索
----------

为了开始搜索，Python 需要被导入模块（或者包，对于当前讨论来说两者没有差
别）的完整 *note 限定名称: 143b.。 此名称可以来自 *note import: c25. 语
句所带的各种参数，或者来自传给 *note importlib.import_module(): b1b. 或
*note __import__(): 619. 函数的形参。

此名称会在导入搜索的各个阶段被使用，它也可以是指向一个子模块的带点号路径
，例如 ‘foo.bar.baz’。 在这种情况下，Python 会先尝试导入 ‘foo’，然后是
‘foo.bar’，最后是 ‘foo.bar.baz’。 如果这些导入中的任何一个失败，都会引发
*note ModuleNotFoundError: 3a2.。

* Menu:

* 模块缓存::
* 查找器和加载器::
* 导入钩子::
* 元路径::


File: python.info,  Node: 模块缓存,  Next: 查找器和加载器,  Up: 搜索

4.5.3.1 模块缓存
................

在导入搜索期间首先会被检查的地方是 *note sys.modules: f36.。 这个映射起
到缓存之前导入的所有模块的作用（包括其中间路径）。 因此如果之前导入过
‘foo.bar.baz’，则 *note sys.modules: f36. 将包含 ‘foo’, ‘foo.bar’ 和
‘foo.bar.baz’ 条目。 每个键的值就是相应的模块对象。

在导入期间，会在 *note sys.modules: f36. 查找模块名称，如存在则其关联的
值就是需要导入的模块，导入过程完成。 然而，如果值为 ‘None’，则会引发
*note ModuleNotFoundError: 3a2.。 如果找不到指定模块名称，Python 将继续
搜索该模块。

*note sys.modules: f36. 是可写的。删除键可能不会破坏关联的模块（因为其他
模块可能会保留对它的引用），但它会使命名模块的缓存条目无效，导致 Python
在下次导入时重新搜索命名模块。键也可以赋值为 ‘None’ ，强制下一次导入模块
导致 *note ModuleNotFoundError: 3a2. 。

但是要小心，因为如果你还保有对某个模块对象的引用，同时停用其在 *note
sys.modules: f36. 中的缓存条目，然后又再次导入该名称的模块，则前后两个模
块对象将 `不是' 同一个。 相反地，*note importlib.reload(): 3a1. 将重用
`同一个' 模块对象，并简单地通过重新运行模块的代码来重新初始化模块内容。


File: python.info,  Node: 查找器和加载器,  Next: 导入钩子,  Prev: 模块缓存,  Up: 搜索

4.5.3.2 查找器和加载器
......................

如果指定名称的模块在 *note sys.modules: f36. 找不到，则将发起调用 Python
的导入协议以查找和加载该模块。 此协议由两个概念性模块构成，即 *note
查找器: 14ca. 和 *note 加载器: 14cb.。 查找器的任务是确定是否能使用其所
知的策略找到该名称的模块。 同时实现这两种接口的对象称为 *note 导入器:
14cc. —— 它们在确定能加载所需的模块时会返回其自身。

Python 包含了多个默认查找器和导入器。 第一个知道如何定位内置模块，第二个
知道如何定位冻结模块。 第三个默认查找器会在 *note import path: 14cd. 中
搜索模块。 *note import path: 14cd. 是一个由文件系统路径或 zip 文件组成
的位置列表。 它还可以扩展为搜索任意可定位资源，例如由 URL 指定的资源。

导入机制是可扩展的，因此可以加入新的查找器以扩展模块搜索的范围和作用域。

查找器并不真正加载模块。 如果它们能找到指定名称的模块，会返回一个 `模块
规格说明'，这是对模块导入相关信息的封装，供后续导入机制用于在加载模块时
使用。

以下各节描述了有关查找器和加载器协议的更多细节，包括你应该如何创建并注册
新的此类对象来扩展导入机制。

在 3.4 版更改: 在之前的 Python 版本中，查找器会直接返回 *note 加载器:
14cb.，现在它们则返回模块规格说明，其中 `包含' 加载器。 加载器仍然在导入
期间被使用，但负担的任务有所减少。


File: python.info,  Node: 导入钩子,  Next: 元路径,  Prev: 查找器和加载器,  Up: 搜索

4.5.3.3 导入钩子
................

导入机制被设计为可扩展；其中的基本机制是 `导入钩子'。 导入钩子有两种类型
: `元钩子' 和 `导入路径钩子'。

元钩子在导入过程开始时被调用，此时任何其他导入过程尚未发生，但 *note
sys.modules: f36. 缓存查找除外。 这允许元钩子重载 *note sys.path: 490. 过
程、冻结模块甚至内置模块。 元钩子的注册是通过向 *note sys.meta_path:
5ef. 添加新的查找器对象，具体如下所述。

导入路径钩子是作为 *note sys.path: 490. (或 ‘package.__path__’) 过程的一
部分，在遇到它们所关联的路径项的时候被调用。 导入路径钩子的注册是通过向
*note sys.path_hooks: 964. 添加新的可调用对象，具体如下所述。


File: python.info,  Node: 元路径,  Prev: 导入钩子,  Up: 搜索

4.5.3.4 元路径
..............

当指定名称的模块在 *note sys.modules: f36. 中找不到时，Python 会接着搜索
*note sys.meta_path: 5ef.，其中包含元路径查找器对象列表。 这些查找器按顺
序被查询以确定它们是否知道如何处理该名称的模块。 元路径查找器必须实现名
为 *note find_spec(): 46b. 的方法，该方法接受三个参数：名称、导入路径和
目标模块（可选）。 元路径查找器可使用任何策略来确定它是否能处理指定名称
的模块。

如果元路径查找器知道如何处理指定名称的模块，它将返回一个说明对象。 如果
它不能处理该名称的模块，则会返回 ‘None’。 如果 *note sys.meta_path: 5ef.
处理过程到达列表末尾仍未返回说明对象，则将引发 *note
ModuleNotFoundError: 3a2.。 任何其他被引发异常将直接向上传播，并放弃导入
过程。

元路径查找器的 *note find_spec(): 46b. 方法调用带有两到三个参数。 第一个
是被导入模块的完整限定名称，例如 ‘foo.bar.baz’。 第二个参数是供模块搜索
使用的路径条目。 对于最高层级模块，第二个参数为 ‘None’，但对于子模块或子
包，第二个参数为父包 ‘__path__’ 属性的值。 如果相应的 ‘__path__’ 属性无
法访问，将引发 *note ModuleNotFoundError: 3a2.。 第三个参数是一个将被作
为稍后加载目标的现有模块对象。 导入系统仅会在重加载期间传入一个目标模块
。

对于单个导入请求可以多次遍历元路径。 例如，假设所涉及的模块都尚未被缓存
，则导入 ‘foo.bar.baz’ 将首先执行顶级的导入，在每个元路径查找器 (‘mpf’)
上调用 ‘mpf.find_spec("foo", None, None)’。 在导入 ‘foo’ 之后，‘foo.bar’
将通过第二次遍历元路径来导入，调用 ‘mpf.find_spec("foo.bar",
foo.__path__, None)’。 一旦 ‘foo.bar’ 完成导入，最后一次遍历将调用
‘mpf.find_spec("foo.bar.baz", foo.bar.__path__, None)’。

有些元路径查找器只支持顶级导入。 当把 ‘None’ 以外的对象作为第三个参数传
入时，这些导入器将总是返回 ‘None’。

Python 的默认 *note sys.meta_path: 5ef. 具有三种元路径查找器，一种知道如
何导入内置模块，一种知道如何导入冻结模块，还有一种知道如何导入来自 *note
import path: 14cd. 的模块 (即 *note path based finder: 14d0.)。

在 3.4 版更改: 元路径查找器的 *note find_spec(): 46b. 方法替代了 *note
find_module(): 46a.，后者现已弃用，它将继续可用但不会再做改变，导入机制
仅会在查找器未实现 ‘find_spec()’ 时尝试使用它。


File: python.info,  Node: 加载,  Next: 基于路径的查找器,  Prev: 搜索,  Up: 导入系统

4.5.4 加载
----------

当一个模块说明被找到时，导入机制将在加载该模块时使用它（及其所包含的加载
器）。 下面是导入的加载部分所发生过程的简要说明:

     module = None
     if spec.loader is not None and hasattr(spec.loader, 'create_module'):
         # It is assumed 'exec_module' will also be defined on the loader.
         module = spec.loader.create_module(spec)
     if module is None:
         module = ModuleType(spec.name)
     # The import-related module attributes get set here:
     _init_module_attrs(spec, module)

     if spec.loader is None:
         # unsupported
         raise ImportError
     if spec.origin is None and spec.submodule_search_locations is not None:
         # namespace package
         sys.modules[spec.name] = module
     elif not hasattr(spec.loader, 'exec_module'):
         module = spec.loader.load_module(spec.name)
         # Set __loader__ and __package__ if missing.
     else:
         sys.modules[spec.name] = module
         try:
             spec.loader.exec_module(module)
         except BaseException:
             try:
                 del sys.modules[spec.name]
             except KeyError:
                 pass
             raise
     return sys.modules[spec.name]

请注意以下细节:

        * 如果在 *note sys.modules: f36. 中存在指定名称的模块对象，导入
          操作会已经将其返回。

        * 在加载器执行模块代码之前，该模块将存在于 *note sys.modules:
          f36. 中。 这一点很关键，因为该模块代码可能（直接或间接地）导入
          其自身；预先将其添加到 *note sys.modules: f36. 可防止在最坏情
          况下的无限递归和最好情况下的多次加载。

        * 如果加载失败，则该模块 – 只限加载失败的模块 – 将从 *note
          sys.modules: f36. 中移除。 任何已存在于 *note sys.modules:
          f36. 缓存的模块，以及任何作为附带影响被成功加载的模块仍会保留
          在缓存中。 这与重新加载不同，后者会把即使加载失败的模块也保留
          在 *note sys.modules: f36. 中。

        * 在模块创建完成但还未执行之前，导入机制会设置导入相关模块属性（
          在上面的示例伪代码中为 “_init_module_attrs”），详情参见 *note
          后续部分: 14d2.。

        * 模块执行是加载的关键时刻，在此期间将填充模块的命名空间。 执行
          会完全委托给加载器，由加载器决定要填充的内容和方式。

        * 在加载过程中创建并传递给 exec_module() 的模块并不一定就是在导
          入结束时返回的模块 (1)。

在 3.4 版更改: 导入系统已经接管了加载器建立样板的责任。 这些在以前是由
*note importlib.abc.Loader.load_module(): 5ec. 方法来执行的。

* Menu:

* 加载器::
* 子模块::
* 模块规格说明::
* 导入相关的模块属性::
* module.__path__: module __path__.
* 模块的 repr::
* 已缓存字节码的失效::

   ---------- Footnotes ----------

   (1) (2) importlib 实现避免直接使用返回值。 而是通过在 *note
sys.modules: f36. 中查找模块名称来获取模块对象。 这种方式的间接影响是被
导入的模块可能在 *note sys.modules: f36. 中替换其自身。 这属于具体实现的
特定行为，不保证能在其他 Python 实现中起作用。


File: python.info,  Node: 加载器,  Next: 子模块,  Up: 加载

4.5.4.1 加载器
..............

模块加载器提供关键的加载功能：模块执行。 导入机制调用 *note
importlib.abc.Loader.exec_module(): 5ed. 方法并传入一个参数来执行模块对
象。 从 *note exec_module(): 5ed. 返回的任何值都将被忽略。

加载器必须满足下列要求:

        * 如果模块是一个 Python 模块（而非内置模块或动态加载的扩展），加
          载器应该在模块的全局命名空间 (‘module.__dict__’) 中执行模块的
          代码。

        * 如果加载器无法执行指定模块，它应该引发 *note ImportError:
          33d.，不过在 *note exec_module(): 5ed. 期间引发的任何其他异常
          也会被传播。

在许多情况下，查找器和加载器可以是同一对象；在此情况下 *note
find_spec(): 46b. 方法将返回一个规格说明，其中加载器会被设为 ‘self’。

模块加载器可以选择通过实现 *note create_module(): 55d. 方法在加载期间创
建模块对象。 它接受一个参数，即模块规格说明，并返回新的模块对象供加载期
间使用。 ‘create_module()’ 不需要在模块对象上设置任何属性。 如果模块返回
‘None’，导入机制将自行创建新模块。

3.4 新版功能: 加载器的 *note create_module(): 55d. 方法。

在 3.4 版更改: *note load_module(): 5ec. 方法被 *note exec_module():
5ed. 所替代，导入机制会对加载的所有样板责任作出假定。

为了与现有的加载器兼容，导入机制会使用导入器的 ‘load_module()’ 方法，如
果它存在且导入器也未实现 ‘exec_module()’。 但是，‘load_module()’ 现已弃
用，加载器应该转而实现 ‘exec_module()’。

除了执行模块之外，‘load_module()’ 方法必须实现上文描述的所有样板加载功能
。 所有相同的限制仍然适用，并带有一些附加规定:

        * 如果 *note sys.modules: f36. 中存在指定名称的模块对象，加载器
          必须使用已存在的模块。 （否则 *note importlib.reload(): 3a1. 将
          无法正确工作。） 如果该名称模块不存在于 *note sys.modules:
          f36. 中，加载器必须创建一个新的模块对象并将其加入 *note
          sys.modules: f36.。

        * 在加载器执行模块代码之前，模块 `必须' 存在于 *note
          sys.modules: f36. 之中，以防止无限递归或多次加载。

        * 如果加载失败，加载器必须移除任何它已加入到 *note sys.modules:
          f36. 中的模块，但它必须 `仅限' 移除加载失败的模块，且所移除的
          模块应为加载器自身显式加载的。

在 3.5 版更改: 当 ‘exec_module()’ 已定义但 ‘create_module()’ 未定义时将
引发 *note DeprecationWarning: 279.。

在 3.6 版更改: 当 ‘exec_module()’ 已定义但 ‘create_module()’ 未定义时将
引发 *note ImportError: 33d.。


File: python.info,  Node: 子模块,  Next: 模块规格说明,  Prev: 加载器,  Up: 加载

4.5.4.2 子模块
..............

当使用任意机制 (例如 ‘importlib’ API, ‘import’ 及 ‘import-from’ 语句或者
内置的 ‘__import__()’) 加载一个子模块时，父模块的命名空间中会添加一个对
子模块对象的绑定。 例如，如果包 ‘spam’ 有一个子模块 ‘foo’，则在导入
‘spam.foo’ 之后，‘spam’ 将具有一个 绑定到相应子模块的 ‘foo’ 属性。 假如
现在有如下的目录结构:

     spam/
         __init__.py
         foo.py
         bar.py

并且 ‘spam/__init__.py’ 中有如下几行内容:

     from .foo import Foo
     from .bar import Bar

则执行如下代码将在 ‘spam’ 模块中添加对 ‘foo’ 和 ‘bar’ 的名称绑定:

     >>> import spam
     >>> spam.foo
     <module 'spam.foo' from '/tmp/imports/spam/foo.py'>
     >>> spam.bar
     <module 'spam.bar' from '/tmp/imports/spam/bar.py'>

按照通常的 Python 名称绑定规则，这看起来可能会令人惊讶，但它实际上是导入
系统的一个基本特性。 保持不变的一点是如果你有 ‘sys.modules['spam']’ 和
‘sys.modules['spam.foo']’ (例如在上述导入之后就是如此)，则后者必须显示为
前者的 ‘foo’ 属性。


File: python.info,  Node: 模块规格说明,  Next: 导入相关的模块属性,  Prev: 子模块,  Up: 加载

4.5.4.3 模块规格说明
....................

导入机制在导入期间会使用有关每个模块的多种信息，特别是加载之前。 大多数
信息都是所有模块通用的。 模块规格说明的目的是基于每个模块来封装这些导入
相关信息。

在导入期间使用规格说明可允许状态在导入系统各组件之间传递，例如在创建模块
规格说明的查找器和执行模块的加载器之间。 最重要的一点是，它允许导入机制
执行加载的样板操作，在没有模块规格说明的情况下这是加载器的责任。

模块的规格说明会作为模块对象的 ‘__spec__’ 属性对外公开。 有关模块规格的
详细内容请参阅 *note ModuleSpec: 14d6.。

3.4 新版功能.


File: python.info,  Node: 导入相关的模块属性,  Next: module __path__,  Prev: 模块规格说明,  Up: 加载

4.5.4.4 导入相关的模块属性
..........................

导入机制会在加载期间会根据模块的规格说明填充每个模块对象的这些属性，并在
加载器执行模块之前完成。

 -- 属性: __name__

     ‘__name__’ 属性必须被设为模块的完整限定名称。 此名称被用来在导入系
     统中唯一地标识模块。

 -- 属性: __loader__

     ‘__loader__’ 属性必须被设为导入系统在加载模块时使用的加载器对象。 这
     主要是用于内省，但也可用于额外的加载器专用功能，例如获取关联到加载
     器的数据。

 -- 属性: __package__

     模块的 ‘__package__’ 属性必须设定。 其取值必须为一个字符串，但可以
     与 ‘__name__’ 取相同的值。 当模块是包时，其 ‘__package__’ 值应该设
     为其 ‘__name__’ 值。 当模块不是包时，对于最高层级模块 ‘__package__’
     应该设为空字符串，对于子模块则应该设为其父包名。 更多详情可参阅 PEP
     366(1)。

     该属性取代 ‘__name__’ 被用来为主模块计算显式相对导入，相关定义见
     PEP 366(2)。 预期它与 ‘__spec__.parent’ 具有相同的值。

     在 3.6 版更改: ‘__package__’ 预期与 ‘__spec__.parent’ 具有相同的值
     。

 -- 属性: __spec__

     ‘__spec__’ 属性必须设为在导入模块时要使用的模块规格说明。 对
     ‘__spec__’ 的正确设定将同时作用于 *note 解释器启动期间初始化的模块:
     14d8.。 唯一的例外是 ‘__main__’，其中的 ‘__spec__’ 会 *note
     在某些情况下设为 None: 14d9.

     当 ‘__package__’ 未定义时， ‘__spec__.parent’ 会被用作回退项。

     3.4 新版功能.

     在 3.6 版更改: 当 ‘__package__’ 未定义时，‘__spec__.parent’ 会被用
     作回退项。

 -- 属性: __path__

     如果模块为包（不论是正规包还是命名空间包），则必须设置模块对象的
     ‘__path__’ 属性。 属性值必须为可迭代对象，但如果 ‘__path__’ 没有进
     一步的用处则可以为空。 如果 ‘__path__’ 不为空，则在迭代时它应该产生
     字符串。 有关 ‘__path__’ 语义的更多细节将在 *note 下文: 14da. 中给
     出。

     不是包的模块不应该具有 ‘__path__’ 属性。

 -- 属性: __file__

 -- 属性: __cached__

     ‘__file__’ 是可选项。 如果设置，此属性的值必须为字符串。 导入系统可
     以选择在其没有语法意义时不设置 ‘__file__’ (例如从数据库加载的模块
     )。

     如果设置了 ‘__file__’，则也可以再设置 ‘__cached__’ 属性，后者取值为
     编译版本代码（例如字节码文件）所在的路径。 设置此属性不要求文件已存
     在；该路径可以简单地指向应该存放编译文件的位置 (参见 PEP 3147(3))。

     当未设置 ‘__file__’ 时也可以设置 ‘__cached__’。 但是，那样的场景很
     不典型。 最终，加载器会使用 ‘__file__’ 和/或 ‘__cached__’。 因此如
     果一个加载器可以从缓存加载模块但是不能从文件加载，那种非典型场景就
     是适当的。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0366

   (2) https://www.python.org/dev/peps/pep-0366

   (3) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: module __path__,  Next: 模块的 repr,  Prev: 导入相关的模块属性,  Up: 加载

4.5.4.5 module.__path__
.......................

根据定义，如果一个模块具有 ‘__path__’ 属性，它就是包。

包的 ‘__path__’ 属性会在导入其子包期间被使用。 在导入机制内部，它的功能
与 *note sys.path: 490. 基本相同，即在导入期间提供一个模块搜索位置列表。
但是，‘__path__’ 通常会比 *note sys.path: 490. 受到更多限制。

‘__path__’ 必须是由字符串组成的可迭代对象，但它也可以为空。 作用于 *note
sys.path: 490. 的规则同样适用于包的 ‘__path__’，并且 *note
sys.path_hooks: 964. (见下文) 会在遍历包的 ‘__path__’ 时被查询。

包的 ‘__init__.py’ 文件可以设置或更改包的 ‘__path__’ 属性，而且这是在
PEP 420(1) 之前实现命名空间包的典型方式。 随着 PEP 420(2) 的引入，命名空
间包不再需要提供仅包含 ‘__path__’ 操控代码的 ‘__init__.py’ 文件；导入机
制会自动为命名空间包正确地设置 ‘__path__’。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0420

   (2) https://www.python.org/dev/peps/pep-0420


File: python.info,  Node: 模块的 repr,  Next: 已缓存字节码的失效,  Prev: module __path__,  Up: 加载

4.5.4.6 模块的 repr
...................

默认情况下，全部模块都具有一个可用的 repr，但是你可以依据上述的属性设置
，在模块的规格说明中更为显式地控制模块对象的 repr。

如果模块具有 spec (‘__spec__’)，导入机制将尝试用它来生成一个 repr。 如果
生成失败或找不到 spec，导入系统将使用模块中的各种可用信息来制作一个默认
repr。 它将尝试使用 ‘module.__name__’, ‘module.__file__’ 以及
‘module.__loader__’ 作为 repr 的输入，并将任何丢失的信息赋为默认值。

以下是所使用的确切规则:

        * 如果模块具有 ‘__spec__’ 属性，其中的规格信息会被用来生成 repr。
          被查询的属性有 "name", "loader", "origin" 和 "has_location" 等
          等。

        * 如果模块具有 ‘__file__’ 属性，这会被用作模块 repr 的一部分。

        * 如果模块没有 ‘__file__’ 但是有 ‘__loader__’ 且取值不为 ‘None’，
          则加载器的 repr 会被用作模块 repr 的一部分。

        * 对于其他情况，仅在 repr 中使用模块的 ‘__name__’。

在 3.4 版更改: *note loader.module_repr(): 949. 已弃用，导入机制现在使用
模块规格说明来生成模块 repr。

为了向后兼容 Python 3.3，如果加载器定义了 *note module_repr(): 949. 方法
，则会在尝试上述两种方式之前先调用该方法来生成模块 repr。 但请注意此方法
已弃用。


File: python.info,  Node: 已缓存字节码的失效,  Prev: 模块的 repr,  Up: 加载

4.5.4.7 已缓存字节码的失效
..........................

在 Python 从 ‘.pyc’ 文件加载已缓存字节码之前，它会检查缓存是否由最新的
‘.py’ 源文件所生成。 默认情况下，Python 通过在所写入缓存文件中保存源文件
的最新修改时间戳和大小来实现这一点。 在运行时，导入系统会通过比对缓存文
件中保存的元数据和源文件的元数据确定该缓存的有效性。

Python 也支持“基于哈希的”缓存文件，即保存源文件内容的哈希值而不是其元数
据。 存在两种基于哈希的 ‘.pyc’ 文件：检查型和非检查型。 对于检查型基于哈
希的 ‘.pyc’ 文件，Python 会通过求哈希源文件并将结果哈希值与缓存文件中的
哈希值比对来确定缓存有效性。 如果检查型基于哈希的缓存文件被确定为失效，
Python 会重新生成并写入一个新的检查型基于哈希的缓存文件。 对于非检查型
‘.pyc’ 文件，只要其存在 Python 就会直接认定缓存文件有效。 确定基于哈希的
‘.pyc’ 文件有效性的行为可通过 *note –check-hash-based-pycs: 1351. 旗标来
重载。

在 3.7 版更改: 增加了基于哈希的 ‘.pyc’ 文件。在此之前，Python 只支持基于
时间戳来确定字节码缓存的有效性。


File: python.info,  Node: 基于路径的查找器,  Next: 替换标准导入系统,  Prev: 加载,  Up: 导入系统

4.5.5 基于路径的查找器
----------------------

在之前已经提及，Python 带有几种默认的元路径查找器。 其中之一是 *note
path based finder: 14d0. (*note PathFinder: 963.)，它会搜索包含一个
*note 路径条目: 14df. 列表的 *note import path: 14cd.。 每个路径条目指定
一个用于搜索模块的位置。

基于路径的查找器自身并不知道如何进行导入。 它只是遍历单独的路径条目，将
它们各自关联到某个知道如何处理特定类型路径的路径条目查找器。

默认的路径条目查找器集合实现了在文件系统中查找模块的所有语义，可处理多种
特殊文件类型例如 Python 源码 (‘.py’ 文件)，Python 字节码 (‘.pyc’ 文件) 以
及共享库 (例如 ‘.so’ 文件)。 在标准库中 *note zipimport: 144. 模块的支持
下，默认路径条目查找器还能处理所有来自 zip 文件的上述文件类型。

路径条目不必仅限于文件系统位置。 它们可以指向 URL、数据库查询或可以用字
符串指定的任何其他位置。

基于路径的查找器还提供了额外的钩子和协议以便能扩展和定制可搜索路径条目的
类型。 例如，如果你想要支持网络 URL 形式的路径条目，你可以编写一个实现
HTTP 语义在网络上查找模块的钩子。 这个钩子（可调用对象）应当返回一个支持
下述协议的 *note path entry finder: 9ba.，以被用来获取一个专门针对来自网
络的模块的加载器。

预先的警告：本节和上节都使用了 `查找器' 这一术语，并通过 *note meta path
finder: 9b9. 和 *note path entry finder: 9ba. 两个术语来明确区分它们。 这
两种类型的查找器非常相似，支持相似的协议，且在导入过程中以相似的方式运作
，但关键的一点是要记住它们是有微妙差异的。 特别地，元路径查找器作用于导
入过程的开始，主要是启动 *note sys.meta_path: 5ef. 遍历。

相比之下，路径条目查找器在某种意义上说是基于路径的查找器的实现细节，实际
上，如果需要从 *note sys.meta_path: 5ef. 移除基于路径的查找器，并不会有
任何路径条目查找器被发起调用。

* Menu:

* 路径条目查找器::
* 路径条目查找器协议::


File: python.info,  Node: 路径条目查找器,  Next: 路径条目查找器协议,  Up: 基于路径的查找器

4.5.5.1 路径条目查找器
......................

*note path based finder: 14d0. 会负责查找和加载通过 *note path entry:
14df. 字符串来指定位置的 Python 模块和包。 多数路径条目所指定的是文件系
统中的位置，但它们并不必受限于此。

作为一种元路径查找器，*note path based finder: 14d0. 实现了上文描述的
*note find_spec(): 46b. 协议，但是它还对外公开了一些附加钩子，可被用来定
制模块如何从 *note import path: 14cd. 查找和加载。

有三个变量由 *note path based finder: 14d0, *note sys.path: 490, *note
sys.path_hooks: 964. 和 *note sys.path_importer_cache: 4a5. 所使用。 包
对象的 ‘__path__’ 属性也会被使用。 它们提供了可用于定制导入机制的额外方
式。

*note sys.path: 490. 包含一个提供模块和包搜索位置的字符串列表。 它初始化
自 ‘PYTHONPATH’ 环境变量以及多种其他特定安装和实现的默认设置。 *note
sys.path: 490. 条目可指定的名称有文件系统中的目录、zip 文件和其他可用于
搜索模块的潜在“位置”（参见 *note site: ec. 模块），例如 URL 或数据库查询
等。 在 *note sys.path: 490. 中只能出现字符串和字节串；所有其他数据类型
都会被忽略。 字节串条目使用的编码由单独的 *note 路径条目查找器: 9ba. 来
确定。

*note path based finder: 14d0. 是一种 *note meta path finder: 9b9.，因此
导入机制会通过调用上文描述的基于路径的查找器的 *note find_spec(): 942. 方
法来启动 *note import path: 14cd. 搜索。 当要向 *note find_spec(): 942.
传入 ‘path’ 参数时，它将是一个可遍历的字符串列表 —— 通常为用来在其内部进
行导入的包的 ‘__path__’ 属性。 如果 ‘path’ 参数为 ‘None’，这表示最高层级
的导入，将会使用 *note sys.path: 490.。

基于路径的查找器会迭代搜索路径中的每个条目，并且每次都查找与路径条目对应
的 *note path entry finder: 9ba. (*note PathEntryFinder: 9bc.)。 因为这
种操作可能很耗费资源（例如搜索会有 ‘stat()’ 调用的开销），基于路径的查找
器会维持一个缓存来将路径条目映射到路径条目查找器。 这个缓存放于 *note
sys.path_importer_cache: 4a5. (尽管如此命名，但这个缓存实际存放的是查找
器对象而非仅限于 *note importer: 14cc. 对象)。 通过这种方式，对特定
*note path entry: 14df. 位置的 *note path entry finder: 9ba. 的高耗费搜
索只需进行一次。 用户代码可以自由地从 *note sys.path_importer_cache:
4a5. 移除缓存条目，以强制基于路径的查找器再次执行路径条目搜索 (1)。

如果路径条目不存在于缓存中，基于路径的查找器会迭代 *note sys.path_hooks:
964. 中的每个可调用对象。 对此列表中的每个 *note 路径条目钩子: 14e1. 的
调用会带有一个参数，即要搜索的路径条目。 每个可调用对象或是返回可处理路
径条目的 *note path entry finder: 9ba.，或是引发 *note ImportError:
33d.。 基于路径的查找器使用 *note ImportError: 33d. 来表示钩子无法找到与
*note path entry: 14df. 相对应的 *note path entry finder: 9ba.。 该异常
会被忽略并继续进行 *note import path: 14cd. 的迭代。 每个钩子应该期待接
收一个字符串或字节串对象；字节串对象的编码由钩子决定（例如可以是文件系统
使用的编码 UTF-8 或其它编码），如果钩子无法解码参数，它应该引发 *note
ImportError: 33d.。

如果 *note sys.path_hooks: 964. 迭代结束时没有返回 *note path entry
finder: 9ba.，则基于路径的查找器 *note find_spec(): 942. 方法将在 *note
sys.path_importer_cache: 4a5. 中存入 ‘None’ (表示此路径条目没有对应的查
找器) 并返回 ‘None’，表示此 *note meta path finder: 9b9. 无法找到该模块
。

如果 *note sys.path_hooks: 964. 中的某个 *note path entry hook: 14e1. 可
调用对象的返回值 `是' 一个 *note path entry finder: 9ba.，则以下协议会被
用来向查找器请求一个模块的规格说明，并在加载该模块时被使用。

当前工作目录 – 由一个空字符串表示 – 的处理方式与 *note sys.path: 490. 中
的其他条目略有不同。 首先，如果发现当前工作目录不存在，则 *note
sys.path_importer_cache: 4a5. 中不会存放任何值。 其次，每个模块查找会对
当前工作目录的值进行全新查找。 第三，由 *note sys.path_importer_cache:
4a5. 所使用并由 *note importlib.machinery.PathFinder.find_spec(): 942. 所
返回的路径将是实际的当前工作目录而非空字符串。

   ---------- Footnotes ----------

   (1) (3) 在遗留代码中，有可能在 *note sys.path_importer_cache: 4a5. 中
找到 *note imp.NullImporter: 9c3. 的实例。 建议将这些代码修改为使用
‘None’ 代替。 详情参见 *note Porting Python code: b1a.。


File: python.info,  Node: 路径条目查找器协议,  Prev: 路径条目查找器,  Up: 基于路径的查找器

4.5.5.2 路径条目查找器协议
..........................

为了支持模块和已初始化包的导入，也为了给命名空间包提供组成部分，路径条目
查找器必须实现 *note find_spec(): 46d. 方法。

*note find_spec(): 46d. 接受两个参数，即要导入模块的完整限定名称，以及（
可选的）目标模块。 ‘find_spec()’ 返回模块的完全填充好的规格说明。 这个规
格说明总是包含“加载器”集合（但有一个例外）。

为了向导入机制提示该规格说明代表一个命名空间 *note portion: 14c5.，路径
条目查找器会将 "submodule_search_locations" 设为一个包含该部分的列表。

在 3.4 版更改: *note find_spec(): 46d. 替代了 *note find_loader(): 46c.
和 *note find_module(): 943.，后两者现在都已弃用，但会在 ‘find_spec()’ 未
定义时被使用。

较旧的路径条目查找器可能会实现这两个已弃用的方法中的一个而没有实现
‘find_spec()’。 为保持向后兼容，这两个方法仍会被接受。 但是，如果在路径
条目查找器上实现了 ‘find_spec()’，这两个遗留方法就会被忽略。

*note find_loader(): 46c. 接受一个参数，即要导入模块的完整限定名称。
‘find_loader()’ 返回一个 2 元组，其中第一项是加载器而第二项是命名空间
*note portion: 14c5.。

为了向后兼容其他导入协议的实现，许多路径条目查找器也同样支持元路径查找器
所支持的传统 ‘find_module()’ 方法。 但是路径条目查找器 ‘find_module()’ 方
法的调用绝不会带有 ‘path’ 参数（它们被期望记录来自对路径钩子初始调用的恰
当路径信息）。

路径条目查找器的 ‘find_module()’ 方法已弃用，因为它不允许路径条目查找器
为命名空间包提供部分。 如果 ‘find_loader()’ 和 ‘find_module()’ 同时存在
于一个路径条目查找器中，导入系统将总是调用 ‘find_loader()’ 而不选择
‘find_module()’。


File: python.info,  Node: 替换标准导入系统,  Next: 包相对导入,  Prev: 基于路径的查找器,  Up: 导入系统

4.5.6 替换标准导入系统
----------------------

替换整个导入系统的最可靠机制是移除 *note sys.meta_path: 5ef. 的默认内容
，,将其完全替换为自定义的元路径钩子。

一个可行的方式是仅改变导入语句的行为而不影响访问导入系统的其他 API，那么
替换内置的 *note __import__(): 619. 函数可能就够了。 这种技巧也可以在模
块层级上运用，即只在某个模块内部改变导入语句的行为。

想要选择性地预先防止在元路径上从一个钩子导入某些模块（而不是完全禁用标准
导入系统），只需直接从 *note find_spec(): 46b. 引发 *note
ModuleNotFoundError: 3a2. 而非返回 ‘None’ 就足够了。 返回后者表示元路径
搜索应当继续，而引发异常则会立即终止搜索。


File: python.info,  Node: 包相对导入,  Next: 有关 __main__ 的特殊事项,  Prev: 替换标准导入系统,  Up: 导入系统

4.5.7 包相对导入
----------------

相对导入使用前缀点号。 一个前缀点号表示相对导入从当前包开始。 两个或更多
前缀点号表示对当前包的上级包的相对导入，第一个点号之后的每个点号代表一级
。 例如，给定以下的包布局结构:

     package/
         __init__.py
         subpackage1/
             __init__.py
             moduleX.py
             moduleY.py
         subpackage2/
             __init__.py
             moduleZ.py
         moduleA.py

不论是在 ‘subpackage1/moduleX.py’ 还是 ‘subpackage1/__init__.py’ 中，以
下导入都是有效的:

     from .moduleY import spam
     from .moduleY import spam as ham
     from . import moduleY
     from ..subpackage1 import moduleY
     from ..subpackage2.moduleZ import eggs
     from ..moduleA import foo

绝对导入可以使用 ‘import <>’ 或 ‘from <> import <>’ 语法，但相对导入只能
使用第二种形式；其中的原因在于:

     import XXX.YYY.ZZZ

应当提供 ‘XXX.YYY.ZZZ’ 作为可用表达式，但 .moduleY 不是一个有效的表达式
。


File: python.info,  Node: 有关 __main__ 的特殊事项,  Next: 开放问题项,  Prev: 包相对导入,  Up: 导入系统

4.5.8 有关 __main__ 的特殊事项
------------------------------

对于 Python 的导入系统来说 *note __main__: 1. 模块是一个特殊情况。 正如
在 *note 另一节: 14d8. 中所述，‘__main__’ 模块是在解释器启动时直接初始化
的，与 *note sys: fe. 和 *note builtins: 13. 很类似。 但是，与那两者不同
，它并不被严格归类为内置模块。 这是因为 ‘__main__’ 被初始化的方式依赖于
发起调用解释器所附带的旗标和其他选项。

* Menu:

* __main__.__spec__: __main__ __spec__.


File: python.info,  Node: __main__ __spec__,  Up: 有关 __main__ 的特殊事项

4.5.8.1 __main__.__spec__
.........................

根据 *note __main__: 1. 被初始化的方式，‘__main__.__spec__’ 会被设置相应
值或是 ‘None’。

当 Python 附加 *note -m: 340. 选项启动时，‘__spec__’ 会被设为相应模块或
包的模块规格说明。 ‘__spec__’ 也会在 ‘__main__’ 模块作为执行某个目录，
zip 文件或其它 *note sys.path: 490. 条目的一部分加载时被填充。

在 *note 其余的情况: 134a. 下 ‘__main__.__spec__’ 会被设为 ‘None’，因为
用于填充 *note __main__: 1. 的代码不直接与可导入的模块相对应:

   - 交互型提示

   - *note -c: 121b. 选项

   - 从 stdin 运行

   - 直接从源码或字节码文件运行

请注意在最后一种情况中 ‘__main__.__spec__’ 总是为 ‘None’，`即使' 文件从
技术上说可以作为一个模块被导入。 如果想要让 *note __main__: 1. 中的元数
据生效，请使用 *note -m: 340. 开关。

还要注意即使是在 ‘__main__’ 对应于一个可导入模块且 ‘__main__.__spec__’ 被
相应地设定时，它们仍会被视为 `不同的' 模块。 这是由于以下事实：使用 ‘if
__name__ == "__main__":’ 检测来保护的代码块仅会在模块被用来填充
‘__main__’ 命名空间时而非普通的导入时被执行。


File: python.info,  Node: 开放问题项,  Next: 参考文献,  Prev: 有关 __main__ 的特殊事项,  Up: 导入系统

4.5.9 开放问题项
----------------

XXX 最好是能增加一个图表。

XXX * (import_machinery.rst) 是否要专门增加一节来说明模块和包的属性，也
许可以扩展或移植数据模型参考页中的相关条目？

XXX 库手册中的 runpy 和 pkgutil 等等应该都在页面顶端增加指向新的导入系统
章节的“另请参阅”链接。

XXX 是否要增加关于初始化 ‘__main__’ 的不同方式的更多解释？

XXX 增加更多有关 ‘__main__’ 怪异/坑人特性的信息 (例如直接从 PEP 395(1) 复
制)。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0395


File: python.info,  Node: 参考文献,  Prev: 开放问题项,  Up: 导入系统

4.5.10 参考文献
---------------

导入机制自 Python 诞生之初至今已发生了很大的变化。 原始的 包规格说明(1)
仍然可以查阅，但在撰写该文档之后许多相关细节已被修改。

原始的 *note sys.meta_path: 5ef. 规格说明见 PEP 302(2)，后续的扩展说明见
PEP 420(3)。

PEP 420(4) 为 Python 3.3 引入了 *note 命名空间包: 14c3.。 PEP 420(5) 还
引入了 ‘find_loader()’ 协议作为 ‘find_module()’ 的替代。

PEP 366(6) 描述了新增的 ‘__package__’ 属性，用于在模块中的显式相对导入。

PEP 328(7) 引入了绝对和显式相对导入，并初次提出了 ‘__name__’ 语义，最终
由 PEP 366(8) 为 ‘__package__’ 加入规范描述。

PEP 338(9) 定义了将模块作为脚本执行。

PEP 451(10) 在 spec 对象中增加了对每个模块导入状态的封装。 它还将加载器
的大部分样板责任移交回导入机制中。 这些改变允许弃用导入系统中的一些 API
并为查找器和加载器增加一些新的方法。

备注
....

   ---------- Footnotes ----------

   (1) https://www.python.org/doc/essays/packages/

   (2) https://www.python.org/dev/peps/pep-0302

   (3) https://www.python.org/dev/peps/pep-0420

   (4) https://www.python.org/dev/peps/pep-0420

   (5) https://www.python.org/dev/peps/pep-0420

   (6) https://www.python.org/dev/peps/pep-0366

   (7) https://www.python.org/dev/peps/pep-0328

   (8) https://www.python.org/dev/peps/pep-0366

   (9) https://www.python.org/dev/peps/pep-0338

   (10) https://www.python.org/dev/peps/pep-0451


File: python.info,  Node: 表达式,  Next: 简单语句,  Prev: 导入系统,  Up: Python语言参考

4.6 表达式
==========

本章将解释 Python 中组成表达式的各种元素的的含义。

`语法注释:' 在本章和后续章节中，会使用扩展 BNF 标注来描述语法而不是词法
分析。 当（某种替代的）语法规则具有如下形式

     name ::= othername

并且没有给出语义，则这种形式的 ‘name’ 在语法上与 ‘othername’ 相同。

* Menu:

* 算术转换::
* 原子::
* 原型::
* await 表达式::
* 幂运算符::
* 一元算术和位运算::
* 二元算术运算符::
* 移位运算::
* 二元位运算::
* 比较运算::
* 布尔运算::
* 赋值表达式: 赋值表达式<2>.
* 条件表达式::
* lambda 表达式::
* 表达式列表::
* 求值顺序::
* 运算符优先级::


File: python.info,  Node: 算术转换,  Next: 原子,  Up: 表达式

4.6.1 算术转换
--------------

当对下述某个算术运算符的描述中使用了“数值参数被转换为普通类型”这样的说法
，这意味着内置类型的运算符实现采用了如下运作方式:

   * 如果任一参数为复数，另一参数会被转换为复数；

   * 否则，如果任一参数为浮点数，另一参数会被转换为浮点数；

   * 否则，两者应该都为整数，不需要进行转换。

某些附加规则会作用于特定运算符（例如，字符串作为 ’%’ 运算符的左运算参数
）。 扩展必须定义它们自己的转换行为。


File: python.info,  Node: 原子,  Next: 原型,  Prev: 算术转换,  Up: 表达式

4.6.2 原子
----------

“原子”指表达式的最基本构成元素。 最简单的原子是标识符和字面值。 以圆括号
、方括号或花括号包括的形式在语法上也被归类为原子。 原子的句法为:

     atom      ::= identifier | literal | enclosure
     enclosure ::= parenth_form | list_display | dict_display | set_display
                   | generator_expression | yield_atom

* Menu:

* 标识符（名称）::
* 字面值: 字面值<2>.
* 带圆括号的形式::
* 列表、集合与字典的显示::
* 列表显示::
* 集合显示::
* 字典显示::
* 生成器表达式: 生成器表达式<2>.
* yield 表达式::


File: python.info,  Node: 标识符（名称）,  Next: 字面值<2>,  Up: 原子

4.6.2.1 标识符（名称）
......................

作为原子出现的标识符叫做名称。 请参看 *note 标识符和关键字: 13e4. 一节了
解其词法定义，以及 *note 命名与绑定: 14af. 获取有关命名与绑定的文档。

当名称被绑定到一个对象时，对该原子求值将返回相应对象。 当名称未被绑定时
，尝试对其求值将引发 *note NameError: d83. 异常。

`私有名称转换:' 当以文本形式出现在类定义中的一个标识符以两个或更多下划线
开头并且不以两个或更多下划线结尾，它会被视为该类的 `私有名称'。 私有名称
会在为其生成代码之前被转换为一种更长的形式。 转换时会插入类名，移除打头
的下划线再在名称前增加一个下划线。 例如，出现在一个名为 ‘Ham’ 的类中的标
识符 ‘__spam’ 会被转换为 ‘_Ham__spam’。 这种转换独立于标识符所使用的相关
句法。 如果转换后的名称太长（超过 255 个字符），可能发生由具体实现定义的
截断。 如果类名仅由下划线组成，则不会进行转换。


File: python.info,  Node: 字面值<2>,  Next: 带圆括号的形式,  Prev: 标识符（名称）,  Up: 原子

4.6.2.2 字面值
..............

Python 支持字符串和字节串字面值，以及几种数字字面值:

     literal ::= stringliteral | bytesliteral
                 | integer | floatnumber | imagnumber

对字面值求值将返回一个该值所对应类型的对象（字符串、字节串、整数、浮点数
、复数）。 对于浮点数和虚数（复数）的情况，该值可能为近似值。 详情参见
*note 字面值: 13f1.。

所有字面值都对应与不可变数据类型，因此对象标识的重要性不如其实际值。 多
次对具有相同值的字面值求值（不论是发生在程序文本的相同位置还是不同位置）
可能得到相同对象或是具有相同值的不同对象。


File: python.info,  Node: 带圆括号的形式,  Next: 列表、集合与字典的显示,  Prev: 字面值<2>,  Up: 原子

4.6.2.3 带圆括号的形式
......................

带圆括号的形式是包含在圆括号中的可选表达式列表。

     parenth_form ::= "(" [starred_expression] ")"

带圆括号的表达式列表将返回该表达式列表所产生的任何东西：如果该列表包含至
少一个逗号，它会产生一个元组；否则，它会产生该表达式列表所对应的单一表达
式。

一对内容为空的圆括号将产生一个空的元组对象。 由于元组是不可变对象，因此
适用与字面值相同的规则（即两次出现的空元组产生的对象可能相同也可能不同）
。

请注意元组并不是由圆括号构建，实际起作用的是逗号操作符。 例外情况是空元
组，这时圆括号 `才是' 必须的 — 允许在表达式中使用不带圆括号的 "空" 会导
致歧义，并会造成常见输入错误无法被捕获。


File: python.info,  Node: 列表、集合与字典的显示,  Next: 列表显示,  Prev: 带圆括号的形式,  Up: 原子

4.6.2.4 列表、集合与字典的显示
..............................

为了构建列表、集合或字典，Python 提供了名为“显示”的特殊句法，每个类型各
有两种形式:

   * 第一种是显式地列出容器内容

   * 第二种是通过一组循环和筛选指令计算出来，称为 `推导式'。

推导式的常用句法元素为:

     comprehension ::= assignment_expression comp_for
     comp_for      ::= ["async"] "for" target_list "in" or_test [comp_iter]
     comp_iter     ::= comp_for | comp_if
     comp_if       ::= "if" expression_nocond [comp_iter]

推导式的结构是一个单独表达式后面加至少一个 ‘for’ 子句以及零个或更多个
‘for’ 或 ‘if’ 子句。 在这种情况下，新容器的元素产生方式是将每个 ‘for’ 或
‘if’ 子句视为一个代码块，按从左至右的顺序嵌套，然后每次到达最内层代码块
时就对表达式进行求值以产生一个元素。

不过，除了最左边 ‘for’ 子句中的可迭代表达式，推导式是在另一个隐式嵌套的
作用域内执行的。 这能确保赋给目标列表的名称不会“泄露”到外层的作用域。

最左边的 ‘for’ 子句中的可迭代对象表达式会直接在外层作用域中被求值，然后
作为一个参数被传给隐式嵌套的作用域。 后续的 ‘for’ 子句以及最左侧 ‘for’ 子
句中的任何筛选条件不能在外层作用域中被求值，因为它们可能依赖于从最左侧可
迭代对象中获得的值。 例如: ‘[x*y for x in range(10) for y in range(x,
x+10)]’。

为了确保推导式得出的结果总是一个类型正确的容器，在隐式嵌套作用域内禁止使
用 ‘yield’ 和 ‘yield from’ 表达式。

从 Python 3.6 开始，在 *note async def: 285. 函数中可以使用 ‘async for’
子句来迭代 *note asynchronous iterator: 64e.。 在 ‘async def’ 函数中构建
推导式可以通过在打头的表达式后加上 ‘for’ 或 ‘async for’ 子句，也可能包含
额外的 ‘for’ 或 ‘async for’ 子句，还可能使用 *note await: 1a4. 表达式。
如果一个推导式包含 ‘async for’ 子句或者 ‘await’ 表达式，则被称为 `异步推
导式'。 异步推导式可以暂停执行它所在的协程函数。 另请参阅 PEP 530(1)。

3.6 新版功能: 引入了异步推导式。

在 3.8 版更改: ‘yield’ 和 ‘yield from’ 在隐式嵌套的作用域中已被禁用。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0530


File: python.info,  Node: 列表显示,  Next: 集合显示,  Prev: 列表、集合与字典的显示,  Up: 原子

4.6.2.5 列表显示
................

列表显示是一个用方括号括起来的可能为空的表达式系列:

     list_display ::= "[" [starred_list | comprehension] "]"

列表显示会产生一个新的列表对象，其内容通过一系列表达式或一个推导式来指定
。 当提供由逗号分隔的一系列表达式时，其元素会从左至右被求值并按此顺序放
入列表对象。 当提供一个推导式时，列表会根据推导式所产生的结果元素进行构
建。


File: python.info,  Node: 集合显示,  Next: 字典显示,  Prev: 列表显示,  Up: 原子

4.6.2.6 集合显示
................

集合显示是用花括号标明的，与字典显示的区别在于没有冒号分隔的键和值:

     set_display ::= "{" (starred_list | comprehension) "}"

集合显示会产生一个新的可变集合对象，其内容通过一系列表达式或一个推导式来
指定。 当提供由逗号分隔的一系列表达式时，其元素会从左至右被求值并加入到
集合对象。 当提供一个推导式时，集合会根据推导式所产生的结果元素进行构建
。

空集合不能用 ‘{}’ 来构建；该字面值所构建的是一个空字典。


File: python.info,  Node: 字典显示,  Next: 生成器表达式<2>,  Prev: 集合显示,  Up: 原子

4.6.2.7 字典显示
................

字典显示是一个用花括号括起来的可能为空的键/数据对系列:

     dict_display       ::= "{" [key_datum_list | dict_comprehension] "}"
     key_datum_list     ::= key_datum ("," key_datum)* [","]
     key_datum          ::= expression ":" expression | "**" or_expr
     dict_comprehension ::= expression ":" expression comp_for

字典显示会产生一个新的字典对象。

如果给出一个由逗号分隔的键/数据对序列，它们会从左至右被求值以定义字典的
条目：每个键对象会被用作在字典中存放相应数据的键。 这意味着你可以在键/数
据对序列中多次指定相同的键，最终字典的值将由最后一次给出的键决定。

双星号 ‘**’ 表示 `字典拆包'。 它的操作数必须是一个 *note mapping: b41.。
每个映射项被会加入新的字典。 后续的值会替代先前的键/数据对和先前的字典拆
包所设置的值。

3.5 新版功能: 拆包到字典显示，最初由 PEP 448(1) 提出。

字典推导式与列表和集合推导式有所不同，它需要以冒号分隔的两个表达式，后面
带上标准的 "for" 和 "if" 子句。 当推导式被执行时，作为结果的键和值元素会
按它们的产生顺序被加入新的字典。

对键取值类型的限制已列在之前的 *note 标准类型层级结构: 1431. 一节中。 (总
的说来，键的类型应该为 *note hashable: 1439.，这就把所有可变对象都排除在
外。) 重复键之间的冲突不会被检测；指定键所保存的最后一个数据 (即在显示中
排最右边的文本) 为最终有效数据。

在 3.8 版更改: 在 Python 3.8 之前的字典推导式中，并没有定义好键和值的求
值顺序。 在 CPython 中，值会先于键被求值。 根据 PEP 572(2) 的提议，从
3.8 开始，键会先于值被求值。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0448

   (2) https://www.python.org/dev/peps/pep-0572


File: python.info,  Node: 生成器表达式<2>,  Next: yield 表达式,  Prev: 字典显示,  Up: 原子

4.6.2.8 生成器表达式
....................

生成器表达式是用圆括号括起来的紧凑形式生成器标注。

     generator_expression ::= "(" expression comp_for ")"

生成器表达式会产生一个新的生成器对象。 其句法与推导式相同，区别在于它是
用圆括号而不是用方括号或花括号括起来的。

在生成器表达式中使用的变量会在为生成器对象调用 *note __next__(): 12ea. 方
法的时候以惰性方式被求值（即与普通生成器相同的方式）。 但是，最左侧
‘for’ 子句内的可迭代对象是会被立即求值的，因此它所造成的错误会在生成器表
达式被定义时被检测到，而不是在获取第一个值时才出错。 后续的 ‘for’ 子句以
及最左侧 ‘for’ 子句内的任何筛选条件无法在外层作用域内被求值，因为它们可
能会依赖于从最左侧可迭代对象获取的值。 例如: ‘(x*y for x in range(10)
for y in range(x, x+10))’.

圆括号在只附带一个参数的调用中可以被省略。 详情参见 *note 调用: 655. 一
节。

为了避免干扰到生成器表达式本身的预期操作，禁止在隐式定义的生成器中使用
‘yield’ 和 ‘yield from’ 表达式。

如果生成器表达式包含 ‘async for’ 子句或 *note await: 1a4. 表达式，则称为
`异步生成器表达式'。 异步生成器表达式会返回一个新的异步生成器对象，此对
象属于异步迭代器 (参见 *note 异步迭代器: 64f.)。

3.6 新版功能: 引入了异步生成器表达式。

在 3.7 版更改: 在 Python 3.7 之前，异步生成器表达式只能在 *note async
def: 285. 协和中出现。 从 3.7 开始，任何函数都可以使用异步生成器表达式。

在 3.8 版更改: ‘yield’ 和 ‘yield from’ 在隐式嵌套的作用域中已被禁用。


File: python.info,  Node: yield 表达式,  Prev: 生成器表达式<2>,  Up: 原子

4.6.2.9 yield 表达式
....................

     yield_atom       ::= "(" yield_expression ")"
     yield_expression ::= "yield" [expression_list | "from" expression]

yield 表达式在定义 *note generator: 9aa. 函数或是 *note asynchronous
generator: 1513. 的时候才会用到。 因此只能在函数定义的内部使用yield表达
式。 在一个函数体内使用 yield 表达式会使这个函数变成一个生成器，并且在一
个 *note async def: 285. 定义的函数体内使用 yield 表达式会让协程函数变成
异步的生成器。 比如说:

     def gen():  # defines a generator function
         yield 123

     async def agen(): # defines an asynchronous generator function
         yield 123

由于它们会对外层作用域造成附带影响，‘yield’ 表达式不被允许作为用于实现推
导式和生成器表达式的隐式定义作用域的一部分。

在 3.8 版更改: 禁止在实现推导式和生成器表达式的隐式嵌套作用域中使用
yield 表达式。

下面是对生成器函数的描述，异步生成器函数会在 *note 异步生成器函数: 1514.
一节中单独介绍。

当一个生成器函数被调用的时候，它返回一个迭代器，称为生成器。然后这个生成
器来控制生成器函数的执行。当这个生成器的某一个方法被调用的时候，生成器函
数开始执行。这时会一直执行到第一个 yield 表达式，在此执行再次被挂起，给
生成器的调用者返回 *note expression_list: 1515. 的值。挂起后，我们说所有
局部状态都被保留下来，包括局部变量的当前绑定，指令指针，内部求值栈和任何
异常处理的状态。通过调用生成器的某一个方法，生成器函数继续执行。此时函数
的运行就和 yield 表达式只是一个外部函数调用的情况完全一致。恢复后 yield
表达式的值取决于调用的哪个方法来恢复执行。 如果用的是 *note __next__():
12ea. (通常通过语言内置的 *note for: c38. 或是 *note next(): 68b. 来调用
) 那么结果就是 *note None: 158.  否则，如果用 *note send(): 149f, 那么结
果就是传递给send方法的值。

所有这些使生成器函数与协程非常相似；它们 yield 多次，它们具有多个入口点
，并且它们的执行可以被挂起。唯一的区别是生成器函数不能控制在它在 yield 后
交给哪里继续执行；控制权总是转移到生成器的调用者。

在 *note try: d7a. 结构中的任何位置都允许yield表达式。如果生成器在(因为
引用计数到零或是因为被垃圾回收)销毁之前没有恢复执行，将调用生成器-迭代器
的 *note close(): 14a3. 方法.  close 方法允许任何挂起的 *note finally:
183. 子句执行。

当使用 ‘yield from <expr>’ 时，所提供的表达式必须是一个可迭代对象。 迭代
该可迭代对象所产生的值会被直接传递给当前生成器方法的调用者。 任何通过
*note send(): 149f. 传入的值以及任何通过 *note throw(): 14a1. 传入的异常
如果有适当的方法则会被传给下层迭代器。 如果不是这种情况，那么 *note
send(): 149f. 将引发 *note AttributeError: 3a3. 或 *note TypeError:
193.，而 *note throw(): 14a1. 将立即引发所转入的异常。

当下层迭代器完成时，被引发的 *note StopIteration: 48e. 实例的 ‘value’ 属
性会成为 yield 表达式的值。 它可以在引发 *note StopIteration: 48e. 时被
显式地设置，也可以在子迭代器是一个生成器时自动地设置（通过从子生成器返回
一个值）。

     在 3.3 版更改: 添加 ‘yield from <expr>’ 以委托控制流给一个子迭代器
     。

当yield表达式是赋值语句右侧的唯一表达式时，括号可以省略。

参见
....

PEP 255(1) - 简单生成器

     在 Python 中加入生成器和 *note yield: 190. 语句的提议。

PEP 342(2) - 通过增强型生成器实现协程

     增强生成器 API 和语法的提议，使其可以被用作简单的协程。

PEP 380(3) - 委托给子生成器的语法

     引入 ‘yield_from’ 语法以方便地委托给子生成器的提议。

PEP 525(4) - 异步生成器

     通过给协程函数加入生成器功能对 PEP 492(5) 进行扩展的提议。

* Menu:

* 生成器-迭代器的方法::
* 例子::
* 异步生成器函数::
* 异步生成器-迭代器方法::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0255

   (2) https://www.python.org/dev/peps/pep-0342

   (3) https://www.python.org/dev/peps/pep-0380

   (4) https://www.python.org/dev/peps/pep-0525

   (5) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: 生成器-迭代器的方法,  Next: 例子,  Up: yield 表达式

4.6.2.10 生成器-迭代器的方法
............................

这个子小节描述了生成器迭代器的方法。 它们可被用于控制生成器函数的执行。

请注意在生成器已经在执行时调用以下任何方法都会引发 *note ValueError:
1fc. 异常。

 -- 方法: generator.__next__ ()

     开始一个生成器函数的执行或是从上次执行的 yield 表达式位置恢复执行。
     当一个生成器函数通过 *note __next__(): 12ea. 方法恢复执行时，当前的
     yield 表达式总是取值为 *note None: 158.。 随后会继续执行到下一个
     yield 表达式，其 *note expression_list: 1515. 的值会返回给 *note
     __next__(): 12ea. 的调用者。 如果生成器没有产生下一个值就退出，则将
     引发 *note StopIteration: 48e. 异常。

     此方法通常是隐式地调用，例如通过 *note for: c38. 循环或是内置的
     *note next(): 68b. 函数。

 -- 方法: generator.send (value)

     恢复执行并向生成器函数“发送”一个值。 `value' 参数将成为当前 yield 表
     达式的结果。 *note send(): 149f. 方法会返回生成器所产生的下一个值，
     或者如果生成器没有产生下一个值就退出则会引发 *note StopIteration:
     48e.。 当调用 *note send(): 149f. 来启动生成器时，它必须以 *note
     None: 158. 作为调用参数，因为这时没有可以接收值的 yield 表达式。

 -- 方法: generator.throw (type[, value[, traceback]])

     在生成器暂停的位置引发 ‘type’ 类型的异常，并返回该生成器函数所产生
     的下一个值。 如果生成器没有产生下一个值就退出，则将引发 *note
     StopIteration: 48e. 异常。 如果生成器函数没有捕获传入的异常，或引发
     了另一个异常，则该异常会被传播给调用者。

 -- 方法: generator.close ()

     在生成器函数暂停的位置引发 *note GeneratorExit: d3a.。 如果之后生成
     器函数正常退出、关闭或引发 *note GeneratorExit: d3a. (由于未捕获该
     异常) 则关闭并返回其调用者。 如果生成器产生了一个值，关闭会引发
     *note RuntimeError: 2bb.。 如果生成器引发任何其他异常，它会被传播给
     调用者。 如果生成器已经由于异常或正常退出则 *note close(): 14a3. 不
     会做任何事。


File: python.info,  Node: 例子,  Next: 异步生成器函数,  Prev: 生成器-迭代器的方法,  Up: yield 表达式

4.6.2.11 例子
.............

这里是一个简单的例子，演示了生成器和生成器函数的行为:

     >>> def echo(value=None):
     ...     print("Execution starts when 'next()' is called for the first time.")
     ...     try:
     ...         while True:
     ...             try:
     ...                 value = (yield value)
     ...             except Exception as e:
     ...                 value = e
     ...     finally:
     ...         print("Don't forget to clean up when 'close()' is called.")
     ...
     >>> generator = echo(1)
     >>> print(next(generator))
     Execution starts when 'next()' is called for the first time.
     1
     >>> print(next(generator))
     None
     >>> print(generator.send(2))
     2
     >>> generator.throw(TypeError, "spam")
     TypeError('spam',)
     >>> generator.close()
     Don't forget to clean up when 'close()' is called.

对于 ‘yield from’ 的例子, 参见“Python 有什么新变化”中的 *note PEP 380;
委托给子生成器的语法: 980.。


File: python.info,  Node: 异步生成器函数,  Next: 异步生成器-迭代器方法,  Prev: 例子,  Up: yield 表达式

4.6.2.12 异步生成器函数
.......................

在一个使用 *note async def: 285. 定义的函数或方法中出现的 yield 表达式会
进一步将该函数定义为一个 *note asynchronous generator: 1513. 函数。

当一个异步生成器函数被调用时，它会返回一个名为异步生成器对象的异步迭代器
。 此对象将在之后控制该生成器函数的执行。 异步生成器对象通常被用在协程函
数的 *note async for: 2e4. 语句中，类似于在 *note for: c38. 语句中使用生
成器对象。

调用异步生成器的方法之一将返回 *note awaitable: 521. 对象，执行会在此对
象被等待时启动。 到那时，执行将前往第一个 yield 表达式，在那里它会再次暂
停，将 *note expression_list: 1515. 的值返回给等待中的协程。 与生成器一
样，挂起意味着局部的所有状态会被保留，包括局部变量的当前绑定、指令的指针
、内部求值的堆栈以及任何异常处理的状态。 当执行在等待异步生成器的方法返
回下一个对象后恢复时，该函数可以从原状态继续进行，就仿佛 yield 表达式只
是另一个外部调用。 恢复执行之后 yield 表达式的值取决于恢复执行所用的方法
。 如果使用 *note __anext__(): 1519. 则结果为 *note None: 158.。 否则的
话，如果使用 *note asend(): 151a. 则结果将是传递给该方法的值。

在异步生成器函数中，yield 表达式允许出现在 *note try: d7a. 结构的任何位
置。 但是，如果一个异步生成器在其被终结（由于引用计数达到零或被作为垃圾
回收）之前未被恢复，则then a yield expression within a ‘try’ 结构中的
yield 表达式可能导致挂起的 *note finally: 183. 子句执行失败。 在此情况下
，应由运行该异步生成器的事件循环或任务调度器来负责调用异步生成器-迭代器
的 *note aclose(): 151b. 方法并运行所返回的协程对象，从而允许任何挂起的
‘finally’ 子句得以执行。

为了能处理最终化，事件循环应该定义一个 `终结器' 函数，它接受一个异步生成
器-迭代器且可能调用 *note aclose(): 151b. 并执行协程。 这个 `终结器' 可
能通过调用 *note sys.set_asyncgen_hooks(): f39. 来注册。 当首次迭代时，
异步生成器-迭代器将保存已注册的 `终结器' 以便在最终化时调用。 有关For a
reference example of a `终结器' 方法的参考示例请查看
Lib/asyncio/base_events.py(1) 中实现的
‘asyncio.Loop.shutdown_asyncgens’。

‘yield from <expr>’ 表达式如果在异步生成器函数中使用会引发语法错误。

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/asyncio/base_events.py


File: python.info,  Node: 异步生成器-迭代器方法,  Prev: 异步生成器函数,  Up: yield 表达式

4.6.2.13 异步生成器-迭代器方法
..............................

这个子小节描述了异步生成器迭代器的方法，它们可被用于控制生成器函数的执行
。

 -- 方法: coroutine agen.__anext__ ()

     返回一个可等待对象，它在运行时会开始执行该异步生成器或是从上次执行
     的 yield 表达式位置恢复执行。 当一个异步生成器函数通过 *note
     __anext__(): 1519. 方法恢复执行时，当前的 yield 表达式所返回的可等
     待对象总是取值为 *note None: 158.，它在运行时将继续执行到下一个
     yield 表达式。 该 yield 表达式的 *note expression_list: 1515. 的值
     会是完成的协程所引发的 *note StopIteration: 48e. 异常的值。 如果异
     步生成器没有产生下一个值就退出，则该可等待对象将引发 *note
     StopAsyncIteration: 1022. 异常，提示该异步迭代操作已完成。

     此方法通常是通过 *note async for: 2e4. 循环隐式地调用。

 -- 方法: coroutine agen.asend (value)

     返回一个可等待对象，它在运行时会恢复该异步生成器的执行。 与生成器的
     *note send(): 149f. 方法一样，此方法会“发送”一个值给异步生成器函数
     ，其 `value' 参数会成为当前 yield 表达式的结果值。 *note asend():
     151a. 方法所返回的可等待对象将返回生成器产生的下一个值，其值为所引
     发的 *note StopIteration: 48e.，或者如果异步生成器没有产生下一个值
     就退出则引发 *note StopAsyncIteration: 1022.。 当调用 *note
     asend(): 151a. 来启动异步生成器时，它必须以 *note None: 158. 作为调
     用参数，因为这时没有可以接收值的 yield 表达式。

 -- 方法: coroutine agen.athrow (type[, value[, traceback]])

     返回一个可等待对象，它会在异步生成器暂停的位置引发 ‘type’ 类型的异
     常，并返回该生成器函数所产生的下一个值，其值为所引发的 *note
     StopIteration: 48e. 异常。 如果异步生成器没有产生下一个值就退出，则
     将由该可等待对象引发 *note StopAsyncIteration: 1022. 异步。 如果生
     成器函数没有捕获传入的异常，或引发了另一个异常，则当可等待对象运行
     时该异常会被传播给可等待对象的调用者。

 -- 方法: coroutine agen.aclose ()

     返回一个可等待对象，它会在运行时向异步生成器函数暂停的位置抛入一个
     *note GeneratorExit: d3a.。 如果该异步生成器函数正常退出、关闭或引
     发 *note GeneratorExit: d3a. (由于未捕获该异常) 则返回的可等待对象
     将引发 *note StopIteration: 48e. 异常。 后续调用异步生成器所返回的
     任何其他可等待对象将引发 *note StopAsyncIteration: 1022. 异常。 如
     果异步生成器产生了一个值，该可等待对象会引发 *note RuntimeError:
     2bb.。 如果异步生成器引发任何其他异常，它会被传播给可等待对象的调用
     者。 如果异步生成器已经由于异常或正常退出则后续调用 *note aclose():
     151b. 将返回一个不会做任何事的可等待对象。


File: python.info,  Node: 原型,  Next: await 表达式,  Prev: 原子,  Up: 表达式

4.6.3 原型
----------

原型代表编程语言中最紧密绑定的操作。 它们的句法如下:

     primary ::= atom | attributeref | subscription | slicing | call

* Menu:

* 属性引用::
* 抽取::
* 切片::
* 调用::


File: python.info,  Node: 属性引用,  Next: 抽取,  Up: 原型

4.6.3.1 属性引用
................

属性引用是后面带有一个句点加一个名称的原型:

     attributeref ::= primary "." identifier

此原型必须求值为一个支持属性引用的类型的对象，多数对象都支持属性引用。 随
后该对象会被要求产生以指定标识符为名称的属性。 这个产生过程可通过重载
*note __getattr__(): 323. 方法来自定义。 如果这个属性不可用，则将引发
*note AttributeError: 3a3. 异常。 否则的话，所产生对象的类型和值会根据该
对象来确定。 对同一属性引用的多次求值可能产生不同的对象。


File: python.info,  Node: 抽取,  Next: 切片,  Prev: 属性引用,  Up: 原型

4.6.3.2 抽取
............

抽取就是在序列（字符串、元组或列表）或映射（字典）对象中选择一项:

     subscription ::= primary "[" expression_list "]"

此原型必须求值为一个支持抽取操作的对象（例如列表或字典）。 用户定义的对
象可通过定义 *note __getitem__(): 280. 方法来支持抽取操作。

对于内置对象，有两种类型的对象支持抽取操作:

如果原型为映射，表达式列表必须求值为一个以该映射的键为值的对象，抽取操作
会在映射中选出该键所对应的值。（表达式列表为一个元组，除非其中只有一项。
）

如果原型为序列，表达式列表必须求值为一个整数或一个切片（详情见下节）。

正式句法规则并没有在序列中设置负标号的特殊保留条款；但是，内置序列所提供
的 *note __getitem__(): 280. 方法都可通过在索引中添加序列长度来解析负标
号 (这样 ‘x[-1]’ 会选出 ‘x’ 中的最后一项)。 结果值必须为一个小于序列中项
数的非负整数，抽取操作会选出标号为该值的项（从零开始数）。 由于对负标号
和切片的支持存在于对象的 *note __getitem__(): 280. 方法，重载此方法的子
类需要显式地添加这种支持。

字符串的项是字符。 字符不是单独的数据类型而是仅有一个字符的字符串。


File: python.info,  Node: 切片,  Next: 调用,  Prev: 抽取,  Up: 原型

4.6.3.3 切片
............

切片就是在序列对象（字符串、元组或列表）中选择某个范围内的项。 切片可被
用作表达式以及赋值或 *note del: 127e. 语句的目标。 切片的句法如下:

     slicing      ::= primary "[" slice_list "]"
     slice_list   ::= slice_item ("," slice_item)* [","]
     slice_item   ::= expression | proper_slice
     proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
     lower_bound  ::= expression
     upper_bound  ::= expression
     stride       ::= expression

此处的正式句法中存在一点歧义：任何形似表达式列表的东西同样也会形似切片列
表，因此任何抽取操作也可以被解析为切片。 为了不使句法更加复杂，于是通过
定义将此情况解析为抽取优先于解析为切片来消除这种歧义（切片列表未包含正确
的切片就属于此情况）。

切片的语义如下所述。 元型通过一个根据下面的切片列表来构造的键进行索引（
与普通抽取一样使用 *note __getitem__(): 280. 方法）。 如果切片列表包含至
少一个逗号，则键将是一个包含切片项转换的元组；否则的话，键将是单个切片项
的转换。 切片项如为一个表达式，则其转换就是该表达式。 一个正确切片的转换
就是一个切片对象（参见 *note 标准类型层级结构: 1431. 一节），该对象的
‘start’, ‘stop’ 和 ‘step’ 属性将分别为表达式所给出的下界、上界和步长值，
省略的表达式将用 ‘None’ 来替换。


File: python.info,  Node: 调用,  Prev: 切片,  Up: 原型

4.6.3.4 调用
............

所谓调用就是附带可能为空的一系列 *note 参数: 1532. 来执行一个可调用对象
(例如 *note function: 1533.):

     call                 ::= primary "(" [argument_list [","] | comprehension] ")"
     argument_list        ::= positional_arguments ["," starred_and_keywords]
                                ["," keywords_arguments]
                              | starred_and_keywords ["," keywords_arguments]
                              | keywords_arguments
     positional_arguments ::= positional_item ("," positional_item)*
     positional_item      ::= assignment_expression | "*" expression
     starred_and_keywords ::= ("*" expression | keyword_item)
                              ("," "*" expression | "," keyword_item)*
     keywords_arguments   ::= (keyword_item | "**" expression)
                              ("," keyword_item | "," "**" expression)*
     keyword_item         ::= identifier "=" expression

一个可选项为在位置和关键字参数后加上逗号而不影响语义。

此原型必须求值为一个可调用对象（用户定义的函数，内置函数，内置对象的方法
，类对象，类实例的方法以及任何具有 *note __call__(): 143e. 方法的对象都
是可调用对象）。 所有参数表达式将在尝试调用前被求值。 请参阅 *note
函数定义: 126c. 一节了解正式的 *note parameter: 153b. 列表句法。

如果存在关键字参数，它们会先通过以下操作被转换为位置参数。 首先，为正式
参数创建一个未填充空位的列表. 如果有 N 个位置参数，则将它们放入前 N 个空
位。 然后，对于每个关键字参数，使用标识符来确定其对应的空位（如果标识符
与第一个正式参数名相同则使用第一个个空位，依此类推）。 如果空位已被填充
，则会引发 *note TypeError: 193. 异常。 否则，将参数值放入空位进行填充（
即使表达式为 ‘None’ 也会填充空位）。 当所有参数处理完毕时，尚未填充的空
位将用来自函数定义的相应默认值来填充。 （函数一旦定义其参数默认值就会被
计算；因此，当列表或字典这类可变对象被用作默认值时，将会被所有未指定相应
空位参数值的调用所共享；这种情况通常应当避免。） 如果任何一个未填充空位
没有指定默认值，则会引发 *note TypeError: 193. 异常。 否则的话，已填充空
位的列表会被作为调用的参数列表。

`CPython implementation detail:' 某些实现可能提供位置参数没有名称的内置
函数，即使它们在文档说明的场合下有“命名”，因此不能以关键字形式提供参数。
在 CPython 中，以 C 编写并使用 *note PyArg_ParseTuple(): 26b. 来解析其参
数的函数实现就属于这种情况。

如果存在比正式参数空位多的位置参数，将会引发 *note TypeError: 193. 异常
，除非有一个正式参数使用了 ‘*identifier’ 句法；在此情况下，该正式参数将
接受一个包含了多余位置参数的元组（如果没有多余位置参数则为一个空元组）。

如果任何关键字参数没有与之对应的正式参数名称，将会引发 *note TypeError:
193. 异常，除非有一个正式参数使用了 ‘**identifier’ 句法，该正式参数将接
受一个包含了多余关键字参数的字典（使用关键字作为键而参数值作为与键对应的
值），如果没有多余关键字参数则为一个（新的）空字典。

如果函数调用中出现了 ‘*expression’ 句法，‘expression’ 必须求值为一个
*note iterable: bb4.。 来自该可迭代对象的元素会被当作是额外的位置参数。
对于 ‘f(x1, x2, *y, x3, x4)’ 调用，如果 `y' 求值为一个序列 `y1', ...,
`yM'，则它就等价于一个带有 M+4 个位置参数 `x1', `x2', `y1', ..., `yM',
`x3', `x4' 的调用。

这样做的一个后果是虽然 ‘*expression’ 句法可能出现于显式的关键字参数 `之
后'，但它会在关键字参数（以及任何 ‘**expression’ 参数 – 见下文） `之前'
被处理。 因此:

     >>> def f(a, b):
     ...     print(a, b)
     ...
     >>> f(b=1, *(2,))
     2 1
     >>> f(a=1, *(2,))
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: f() got multiple values for keyword argument 'a'
     >>> f(1, *(2,))
     1 2

在同一个调用中同时使用关键字参数和 ‘*expression’ 句法并不常见，因此实际
上这样的混淆不会发生。

如果函数调用中出现了 ‘**expression’ 句法，‘expression’ 必须求值为一个
*note mapping: b41.，其内容会被当作是额外的关键字参数。 如果一个关键字已
存在（作为显式关键字参数，或来自另一个拆包），则将引发 *note TypeError:
193. 异常。

使用 ‘*identifier’ 或 ‘**identifier’ 句法的正式参数不能被用作位置参数空
位或关键字参数名称。

在 3.5 版更改: 函数调用接受任意数量的 ‘*’ 和 ‘**’ 拆包，位置参数可能跟在
可迭代对象拆包 (‘*’) 之后，而关键字参数可能跟在字典拆包 (‘**’) 之后。 由
PEP 448(1) 发起最初提议。

除非引发了异常，调用总是会有返回值，返回值也可能为 ‘None’。 返回值的计算
方式取决于可调用对象的类型。

如果类型为—

用户自定义函数:

     函数的代码块会被执行，并向其传入参数列表。 代码块所做的第一件事是将
     正式形参绑定到对应参数；相关描述参见 *note 函数定义: 126c. 一节。 当
     代码块执行 *note return: 191. 语句时，由其指定函数调用的返回值。

内置函数或方法:

     具体结果依赖于解释器；有关内置函数和方法的描述参见 *note 内置函数:
     bfb.。

类对象:

     返回该类的一个新实例。

类实例方法:

     调用相应的用户自定义函数，向其传入的参数列表会比调用的参数列表多一
     项：该实例将成为第一个参数。

类实例:

     该类必须定义有 *note __call__(): 143e. 方法；作用效果将等价于调用该
     方法。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0448


File: python.info,  Node: await 表达式,  Next: 幂运算符,  Prev: 原型,  Up: 表达式

4.6.4 await 表达式
------------------

挂起 *note coroutine: 1a7. 的执行以等待一个 *note awaitable: 521. 对象。
只能在 *note coroutine function: 648. 内部使用。

     await_expr ::= "await" primary

3.5 新版功能.


File: python.info,  Node: 幂运算符,  Next: 一元算术和位运算,  Prev: await 表达式,  Up: 表达式

4.6.5 幂运算符
--------------

幂运算符的绑定比在其左侧的一元运算符更紧密；但绑定紧密程度不及在其右侧的
一元运算符。 句法如下:

     power ::= (await_expr | primary) ["**" u_expr]

因此，在一个未加圆括号的幂运算符和单目运算符序列中，运算符将从右向左求值
（这不会限制操作数的求值顺序）: ‘-1**2’ 结果将为 ‘-1’。

幂运算符与附带两个参数调用内置 *note pow(): 19b. 函数具有相同的语义：结
果为对其左参数进行其右参数所指定幂次的乘方运算。 数值参数会先转换为相同
类型，结果也为转换后的类型。

对于 int 类型的操作数，结果将具有与操作数相同的类型，除非第二个参数为负
数；在那种情况下，所有参数会被转换为 float 类型并输出 float 类型的结果。
例如，‘10**2’ 返回 ‘100’，而 ‘10**-2’ 返回 ‘0.01’。

对 ‘0.0’ 进行负数幂次运算将导致 *note ZeroDivisionError: 12bd.。 对负数
进行分数幂次运算将返回 *note complex: 18a. 数值。 （在早期版本中这将引发
*note ValueError: 1fc.。）


File: python.info,  Node: 一元算术和位运算,  Next: 二元算术运算符,  Prev: 幂运算符,  Up: 表达式

4.6.6 一元算术和位运算
----------------------

所有算术和位运算具有相同的优先级:

     u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr

一元运算符 ‘-’ (负) 会产生其数值参数的负值。

一元运算符 ‘+’ (正) 会产生与其数值参数相同的值。

一元运算符 ‘~’ (取反) 的结果是对其整数参数按位取反。 ‘x’ 的按位取反被定
义为 ‘-(x+1)’。 它只作用于整数。

在所有三种情况下，如果参数的类型不正确，将引发 *note TypeError: 193. 异
常。


File: python.info,  Node: 二元算术运算符,  Next: 移位运算,  Prev: 一元算术和位运算,  Up: 表达式

4.6.7 二元算术运算符
--------------------

二元算术运算符遵循传统的优先级。 请注意某些此类运算符也作用于特定的非数
字类型。 除幂运算符以外只有两个优先级别，一个作用于乘法型运算符，另一个
作用于加法型运算符:

     m_expr ::= u_expr | m_expr "*" u_expr | m_expr "@" m_expr |
                m_expr "//" u_expr | m_expr "/" u_expr |
                m_expr "%" u_expr
     a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr

运算符 ‘*’ (乘) 将输出其参数的乘积。 两个参数或者必须都为数字，或者一个
参数必须为整数而另一个参数必须为序列。 在前一种情况下，两个数字将被转换
为相同类型然后相乘。 在后一种情况下，将执行序列的重复；重复因子为负数将
输出空序列。

运算符 ‘@’ (at) 的目标是用于矩阵乘法。 没有内置 Python 类型实现此运算符
。

3.5 新版功能.

运算符 ‘/’ (除) 和 ‘//’ (整除) 将输出其参数的商。 两个数字参数将先被转换
为相同类型。 整数相除会输出一个 float 值，整数相整除的结果仍是整数；整除
的结果就是使用 ’floor’ 函数进行算术除法的结果。 除以零的运算将引发 *note
ZeroDivisionError: 12bd. 异常。

运算符 ‘%’ (模) 将输出第一个参数除以第二个参数的余数。 两个数字参数将先
被转换为相同类型。 右参数为零将引发 *note ZeroDivisionError: 12bd. 异常
。 参数可以为浮点数，例如 ‘3.14%0.7’ 等于 ‘0.34’ (因为 ‘3.14’ 等于
‘4*0.7 + 0.34’)。 模运算符的结果的正负总是与第二个操作数一致（或是为零）
；结果的绝对值一定小于第二个操作数的绝对值 (1)。

整除与模运算符的联系可通过以下等式说明: ‘x == (x//y)*y + (x%y)’。 此外整
除与模也可通过内置函数 *note divmod(): 153. 来同时进行: ‘divmod(x, y) ==
(x//y, x%y)’。 (2)。

除了对数字执行模运算，运算符 ‘%’ 还被字符串对象重载用于执行旧式的字符串
格式化（又称插值）。 字符串格式化句法的描述参见 Python 库参考的 *note
printf 风格的字符串格式化: 1235. 一节。

整除运算符，模运算符和 *note divmod(): 153. 函数未被定义用于复数。 如果
有必要可以使用 *note abs(): 12cf. 函数将其转换为浮点数。

运算符 ‘+’ (addition) 将输出其参数的和。 两个参数或者必须都为数字，或者
都为相同类型的序列。 在前一种情况下，两个数字将被转换为相同类型然后相加
。 在后一种情况下，将执行序列拼接操作。

运算符 ‘-’ (减) 将输出其参数的差。 两个数字参数将先被转换为相同类型。

   ---------- Footnotes ----------

   (1) (1) 虽然 ‘abs(x%y) < abs(y)’ 在数学中必为真，但对于浮点数而言，由
于舍入的存在，其在数值上未必为真。 例如，假设在某个平台上的 Python 浮点
数为一个 IEEE 754 双精度数值，为了使 ‘-1e-100 % 1e100’ 具有与 ‘1e100’ 相
同的正负性，计算结果将是 ‘-1e-100 + 1e100’，这在数值上正好等于 ‘1e100’。
函数 *note math.fmod(): 1548. 返回的结果则会具有与第一个参数相同的正负性
，因此在这种情况下将返回 ‘-1e-100’。 何种方式更适宜取决于具体的应用。

   (2) (2) 如果 x 恰好非常接近于 y 的整数倍，则由于舍入的存在 ‘x//y’ 可
能会比 ‘(x-x%y)//y’ 大。 在这种情况下，Python 会返回后一个结果，以便保持
令 ‘divmod(x,y)[0] * y + x % y’ 尽量接近 ‘x’.


File: python.info,  Node: 移位运算,  Next: 二元位运算,  Prev: 二元算术运算符,  Up: 表达式

4.6.8 移位运算
--------------

移位运算的优先级低于算术运算:

     shift_expr ::= a_expr | shift_expr ("<<" | ">>") a_expr

这些运算符接受整数参数。 它们会将第一个参数左移或右移第二个参数所指定的
比特位数。

右移 `n' 位被定义为被 ‘pow(2,n)’ 整除。 左移 `n' 位被定义为乘以
‘pow(2,n)’。


File: python.info,  Node: 二元位运算,  Next: 比较运算,  Prev: 移位运算,  Up: 表达式

4.6.9 二元位运算
----------------

三种位运算具有各不相同的优先级:

     and_expr ::= shift_expr | and_expr "&" shift_expr
     xor_expr ::= and_expr | xor_expr "^" and_expr
     or_expr  ::= xor_expr | or_expr "|" xor_expr

运算符 ‘&’ 对两个参数进行按位 AND (与) 运算，两个参数必须为整数。

运算符 ‘^’ 对两个参数进行按位 XOR (异或) 运算，两个参数必须为整数。

运算符 ‘|’ 对两个参数进行按位 OR (或) 运算，两个参数必须为整数。


File: python.info,  Node: 比较运算,  Next: 布尔运算,  Prev: 二元位运算,  Up: 表达式

4.6.10 比较运算
---------------

与 C 不同，Python 中所有比较运算的优先级相同，低于任何算术、移位或位运算
。 另一个与 C 不同之处在于 ‘a < b < c’ 这样的表达式会按传统算术法则来解
读:

     comparison    ::= or_expr (comp_operator or_expr)*
     comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="
                       | "is" ["not"] | ["not"] "in"

比较运算将输出布尔值: ‘True’ 或 ‘False’。

比较运算可以任意串连，例如 ‘x < y <= z’ 等价于 ‘x < y and y <= z’，除了
‘y’ 只被求值一次（但在两种写法下当 ‘x < y’ 值为假时 ‘z’ 都不会被求值）。

正式的说法是这样：如果 `a', `b', `c', ..., `y', `z' 为表达式而 `op1',
`op2', ..., `opN' 为比较运算符，则 ‘a op1 b op2 c ... y opN z’ 就等价于
‘a op1 b and b op2 c and ... y opN z’，后者的不同之处只是每个表达式最多
只被求值一次。

请注意 ‘a op1 b op2 c’ 不意味着在 `a' 和 `c' 之间进行任何比较，因此，如
‘x < y > z’ 这样的写法是完全合法的（虽然也许不太好看）。

* Menu:

* 值比较::
* 成员检测运算::
* 标识号比较::


File: python.info,  Node: 值比较,  Next: 成员检测运算,  Up: 比较运算

4.6.10.1 值比较
...............

运算符 ‘<’, ‘>’, ‘==’, ‘>=’, ‘<=’ 和 ‘!=’ 将比较两个对象的值。 两个对象
不要求为相同类型。

*note 对象、值与类型: 142e. 一章已说明对象都有相应的值（还有类型和标识号
）。 对象值在 Python 中是一个相当抽象的概念：例如，对象值并没有一个规范
的访问方法。 而且，对象值并不要求具有特定的构建方式，例如由其全部数据属
性组成等。 比较运算符实现了一个特定的对象值概念。 人们可以认为这是通过实
现对象比较间接地定义了对象值。

由于所有类型都是 *note object: 2b1. 的（直接或间接）子类型，它们都从
*note object: 2b1. 继承了默认的比较行为。 类型可以通过实现 `丰富比较方法
' 例如 *note __lt__(): c3c. 来定义自己的比较行为，详情参见 *note
基本定制: 1445.。

默认的一致性比较 (‘==’ 和 ‘!=’) 是基于对象的标识号。 因此，具有相同标识
号的实例一致性比较结果为相等，具有不同标识号的实例一致性比较结果为不等。
规定这种默认行为的动机是希望所有对象都应该是自反射的 (即 ‘x is y’ 就意味
着 ‘x == y’)。

次序比较 (‘<’, ‘>’, ‘<=’ 和 ‘>=’) 默认没有提供；如果尝试比较会引发 *note
TypeError: 193.。 规定这种默认行为的原因是缺少与一致性比较类似的固定值。

按照默认的一致性比较行为，具有不同标识号的实例总是不相等，这可能不适合某
些对象值需要有合理定义并有基于值的一致性的类型。 这样的类型需要定制自己
的比较行为，实际上，许多内置类型都是这样做的。

以下列表描述了最主要内置类型的比较行为。

   * 内置数值类型 (*note 数字类型 — int, float, complex: 122f.) 以及标准
     库类型 *note fractions.Fraction: 186. 和 *note decimal.Decimal:
     189. 可进行类型内部和跨类型的比较，例外限制是复数不支持次序比较。 在
     类型相关的限制以内，它们会按数学（算法）规则正确进行比较且不会有精
     度损失。

     非数字值 ‘float('NaN')’ 和 ‘decimal.Decimal('NaN')’ 属于特例。 任何
     数字与非数字值的排序比较均返回假值。 还有一个反直觉的结果是非数字值
     不等于其自身。 举例来说，如果 ‘x = float('NaN')’ 则 ‘3 < x’, ‘x <
     3’ 和 ‘x == x’ 均为假值，而 ‘x != x’ 则为真值。 此行为是遵循 IEEE
     754 标准的。

   * ‘None’ 和 ‘NotImplemented’ 都是单例对象。 PEP 8(1) 建议单例对象的比
     较应当总是通过 ‘is’ 或 ‘is not’ 而不是等于运算符来进行。

   * 二进制码序列 (*note bytes: 33a. 或 *note bytearray: 33b. 的实例) 可
     进行类型内部和跨类型的比较。 它们使用其元素的数字值按字典顺序进行比
     较。

   * 字符串 (*note str: 339. 的实例) 使用其字符的 Unicode 码位数字值 (内
     置函数 *note ord(): 1437. 的结果) 按字典顺序进行比较。 (2)

     字符串和二进制码序列不能直接比较。

   * 序列 (*note tuple: 486, *note list: 263. 或 *note range: 9c6. 的实
     例) 只可进行类型内部的比较，range 还有一个限制是不支持次序比较。 以
     上对象的跨类型一致性比较结果将是不相等，跨类型次序比较将引发 *note
     TypeError: 193.。

     序列比较是按字典序对相应元素进行逐个比较。 内置容器通常设定同一对象
     与其自身是相等的。 这使得它们能跳过同一对象的相等性检测以提升运行效
     率并保持它们的内部不变性。

     内置多项集间的字典序比较规则如下:

        - 两个多项集若要相等，它们必须为相同类型、相同长度，并且每对相应
          的元素都必须相等（例如，‘[1,2] == (1,2)’ 为假值，因为类型不同
          ）。

        - 对于支持次序比较的多项集，排序与其第一个不相等元素的排序相同（
          例如 ‘[1,2,x] <= [1,2,y]’ 的值与‘‘x <= y‘‘ 相同）。 如果对应元
          素不存在，较短的多项集排序在前（例如 ‘[1,2] < [1,2,3]’ 为真值
          ）。

   * 两个映射 (*note dict: 1b9. 的实例) 若要相等，必须当且仅当它们具有相
     同的 ‘(键, 值)’ 对。 键和值的一致性比较强制规定自反射性。

     次序比较 (‘<’, ‘>’, ‘<=’ 和 ‘>=’) 将引发 *note TypeError: 193.。

   * 集合 (*note set: b77. 或 *note frozenset: bf6. 的实例) 可进行类型内
     部和跨类型的比较。

     它们将比较运算符定义为子集和超集检测。 这类关系没有定义完全排序（例
     如 ‘{1,2}’ 和 ‘{2,3}’ 两个集合不相等，即不为彼此的子集，也不为彼此
     的超集。 相应地，集合不适宜作为依赖于完全排序的函数的参数（例如如果
     给出一个集合列表作为 *note min(): 812, *note max(): 813. 和 *note
     sorted(): 44c. 的输入将产生未定义的结果）。

     集合的比较强制规定其元素的自反射性。

   * 大多数其他内置类型没有实现比较方法，因此它们会继承默认的比较行为。

在可能的情况下，用户定义类在定制其比较行为时应当遵循一些一致性规则:

   * 相等比较应该是自反射的。 换句话说，相同的对象比较时应该相等:

          ‘x is y’ 意味着 ‘x == y’

   * 比较应该是对称的。 换句话说，下列表达式应该有相同的结果:

          ‘x == y’ 和 ‘y == x’

          ‘x != y’ 和 ‘y != x’

          ‘x < y’ 和 ‘y > x’

          ‘x <= y’ 和 ‘y >= x’

   * 比较应该是可传递的。 下列（简要的）例子显示了这一点:

          ‘x > y and y > z’ 意味着 ‘x > z’

          ‘x < y and y <= z’ 意味着 ‘x < z’

   * 反向比较应该导致布尔值取反。 换句话说，下列表达式应该有相同的结果:

          ‘x == y’ 和 ‘not x != y’

          ‘x < y’ 和 ‘not x >= y’ (对于完全排序)

          ‘x > y’ 和 ‘not x <= y’ (对于完全排序)

     最后两个表达式适用于完全排序的多项集（即序列而非集合或映射）。 另请
     参阅 *note total_ordering(): 854. 装饰器。

   * *note hash(): 9cc. 的结果应该与是否相等一致。 相等的对象应该或者具
     有相同的哈希值，或者标记为不可哈希。

Python 并不强制要求这些一致性规则。 实际上，非数字值就是一个不遵循这些规
则的例子。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0008

   (2) (3) Unicode 标准明确区分 `码位' (例如 U+0041) 和 `抽象字符' (例如
"大写拉丁字母 A")。 虽然 Unicode 中的大多数抽象字符都只用一个码位来代表
，但也存在一些抽象字符可使用由多个码位组成的序列来表示。 例如，抽象字符
"带有下加符的大写拉丁字母 C" 可以用 U+00C7 码位上的单个 `预设字符' 来表
示，也可以用一个 U+0043 码位上的 `基础字符' (大写拉丁字母 C) 加上一个
U+0327 码位上的 `组合字符' (组合下加符) 组成的序列来表示。

对于字符串，比较运算符会按 Unicode 码位级别进行比较。 这可能会违反人类的
直觉。 例如，‘"\u00C7" == "\u0043\u0327"’ 为 ‘False’，虽然两个字符串都代
表同一个抽象字符 "带有下加符的大写拉丁字母 C"。

要按抽象字符级别（即对人类来说更直观的方式）对字符串进行比较，应使用
*note unicodedata.normalize(): 10bf.。


File: python.info,  Node: 成员检测运算,  Next: 标识号比较,  Prev: 值比较,  Up: 比较运算

4.6.10.2 成员检测运算
.....................

运算符 *note in: 7ac. 和 *note not in: 146d. 用于成员检测。 如果 `x' 是
`s' 的成员则 ‘x in s’ 求值为 ‘True’，否则为 ‘False’。 ‘x not in s’ 返回
‘x in s’ 取反后的值。 所有内置序列和集合类型以及字典都支持此运算，对于字
典来说 ‘in’ 检测其是否有给定的键。 对于 list, tuple, set, frozenset,
dict 或 collections.deque 这样的容器类型，表达式 ‘x in y’ 等价于 ‘any(x
is e or x == e for e in y)’。

对于字符串和字节串类型来说，当且仅当 `x' 是 `y' 的子串时 ‘x in y’ 为
‘True’。 一个等价的检测是 ‘y.find(x) != -1’。 空字符串总是被视为任何其他
字符串的子串，因此 ‘"" in "abc"’ 将返回 ‘True’。

对于定义了 *note __contains__(): d30. 方法的用户自定义类来说，如果
‘y.__contains__(x)’ 返回真值则 ‘x in y’ 返回 ‘True’，否则返回 ‘False’。

对于未定义 *note __contains__(): d30. 但定义了 *note __iter__(): 517. 的
用户自定义类来说，如果在对 ‘y’ 进行迭代时产生了值 ‘z’ 使得表达式 ‘x is z
or x == z’ 为真，则 ‘x in y’ 为 ‘True’。 如果在迭代期间引发了异常，则等
同于 *note in: 7ac. 引发了该异常。

最后将会尝试旧式的迭代协议：如果一个类定义了 *note __getitem__(): 280.，
则当且仅当存在非负整数索引号 `i' 使得 ‘x is y[i] or x == y[i]’ 并且没有
更小的索引号引发 *note IndexError: e7d. 异常时 ‘x in y’ 为 ‘True’。 （如
果引发了任何其他异常，则等同于 *note in: 7ac. 引发了该异常）。

运算符 *note not in: 146d. 被定义为具有与 *note in: 7ac. 相反的逻辑值。


File: python.info,  Node: 标识号比较,  Prev: 成员检测运算,  Up: 比较运算

4.6.10.3 标识号比较
...................

运算符 *note is: eca. 和 *note is not: 1558. 用于检测对象的标识号：当且
仅当 `x' 和 `y' 是同一对象时 ‘x is y’ 为真。 一个对象的标识号可使用
*note id(): d8e. 函数来确定。 ‘x is not y’ 会产生相反的逻辑值。 (1)

   ---------- Footnotes ----------

   (1) (4) 由于存在自动垃圾收集、空闲列表以及描述器的动态特性，你可能会
注意到在特定情况下使用 *note is: eca. 运算符会出现看似不正常的行为，例如
涉及到实例方法或常量之间的比较时就是如此。 更多信息请查看有关它们的文档
。


File: python.info,  Node: 布尔运算,  Next: 赋值表达式<2>,  Prev: 比较运算,  Up: 表达式

4.6.11 布尔运算
---------------

     or_test  ::= and_test | or_test "or" and_test
     and_test ::= not_test | and_test "and" not_test
     not_test ::= comparison | "not" not_test

在执行布尔运算的情况下，或是当表达式被用于流程控制语句时，以下值会被解析
为假值: ‘False’, ‘None’, 所有类型的数字零，以及空字符串和空容器（包括字
符串、元组、列表、字典、集合与冻结集合）。 所有其他值都会被解析为真值。
用户自定义对象可通过提供 *note __bool__(): c70. 方法来定制其逻辑值。

运算符 *note not: 155d. 将在其参数为假值时产生 ‘True’，否则产生 ‘False’。

表达式 ‘x and y’ 首先对 `x' 求值；如果 `x' 为假则返回该值；否则对 `y' 求
值并返回其结果值。

表达式 ‘x or y’ 首先对 `x' 求值；如果 `x' 为真则返回该值；否则对 `y' 求
值并返回其结果值。

请注意 *note and: 155a. 和 *note or: 155b. 都不限制其返回的值和类型必须
为 ‘False’ 和 ‘True’，而是返回最终求值的参数。 此行为是有必要的，例如假
设 ‘s’ 为一个当其为空时应被替换为某个默认值的字符串，表达式 ‘s or 'foo'’
将产生希望的值。 由于 *note not: 155d. 必须创建一个新值，不论其参数为何
种类型它都会返回一个布尔值（例如，‘not 'foo'’ 结果为 ‘False’ 而非 ‘''’。
）


File: python.info,  Node: 赋值表达式<2>,  Next: 条件表达式,  Prev: 布尔运算,  Up: 表达式

4.6.12 赋值表达式
-----------------

     assignment_expression ::= [identifier ":="] expression

赋值表达式（有时又被叫做“命名表达式”或“海象表达式”）将一个 *note
expression: 1563. 赋值给一个 *note identifier: 13e6.，同时还返回 *note
expression: 1563. 的值。

一个常见用例是在处理匹配的正则表达式的时候:

     if matching := pattern.search(data):
         do_something(matching)

或者是在处理分块的文件流的时候:

     while chunk := file.read(9000):
         process(chunk)

3.8 新版功能: 请参阅 PEP 572(1) 了解有关赋值表达式的详情。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0572


File: python.info,  Node: 条件表达式,  Next: lambda 表达式,  Prev: 赋值表达式<2>,  Up: 表达式

4.6.13 条件表达式
-----------------

     conditional_expression ::= or_test ["if" or_test "else" expression]
     expression             ::= conditional_expression | lambda_expr
     expression_nocond      ::= or_test | lambda_expr_nocond

条件表达式（有时称为“三元运算符”）在所有 Python 运算中具有最低的优先级。

表达式 ‘x if C else y’ 首先是对条件 `C' 而非 `x' 求值。 如果 `C' 为真，
`x' 将被求值并返回其值；否则将对 `y' 求值并返回其值。

请参阅 PEP 308(1) 了解有关条件表达式的详情。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0308


File: python.info,  Node: lambda 表达式,  Next: 表达式列表,  Prev: 条件表达式,  Up: 表达式

4.6.14 lambda 表达式
--------------------

     lambda_expr        ::= "lambda" [parameter_list] ":" expression
     lambda_expr_nocond ::= "lambda" [parameter_list] ":" expression_nocond

lambda 表达式（有时称为 lambda 构型）被用于创建匿名函数。 表达式 ‘lambda
parameters: expression’ 会产生一个函数对象 。 该未命名对象的行为类似于用
以下方式定义的函数:

     def <lambda>(parameters):
         return expression

请参阅 *note 函数定义: 126c. 了解有关参数列表的句法。 请注意通过 lambda
表达式创建的函数不能包含语句或标注。


File: python.info,  Node: 表达式列表,  Next: 求值顺序,  Prev: lambda 表达式,  Up: 表达式

4.6.15 表达式列表
-----------------

     expression_list    ::= expression ("," expression)* [","]
     starred_list       ::= starred_item ("," starred_item)* [","]
     starred_expression ::= expression | (starred_item ",")* [starred_item]
     starred_item       ::= assignment_expression | "*" or_expr

除了作为列表或集合显示的一部分，包含至少一个逗号的表达式列表将生成一个元
组。 元组的长度就是列表中表达式的数量。 表达式将从左至右被求值。

一个星号 ‘*’ 表示 `可迭代拆包'。 其操作数必须为一个 *note iterable:
bb4.。 该可迭代对象将被拆解为迭代项的序列，并被包含于在拆包位置上新建的
元组、列表或集合之中。

3.5 新版功能: 表达式列表中的可迭代对象拆包，最初由 PEP 448(1) 提出。

末尾的逗号仅在创建单独元组 (或称 `单例') 时需要；在所有其他情况下都是可
选项。 没有末尾逗号的单独表达式不会创建一个元组，而是产生该表达式的值。
（要创建一个空元组，应使用一对内容为空的圆括号: ‘()’。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0448


File: python.info,  Node: 求值顺序,  Next: 运算符优先级,  Prev: 表达式列表,  Up: 表达式

4.6.16 求值顺序
---------------

Python 按从左至右的顺序对表达式求值。 但注意在对赋值操作求值时，右侧会先
于左侧被求值。

在以下几行中，表达式将按其后缀的算术优先顺序被求值。:

     expr1, expr2, expr3, expr4
     (expr1, expr2, expr3, expr4)
     {expr1: expr2, expr3: expr4}
     expr1 + expr2 * (expr3 - expr4)
     expr1(expr2, expr3, *expr4, **expr5)
     expr3, expr4 = expr1, expr2


File: python.info,  Node: 运算符优先级,  Prev: 求值顺序,  Up: 表达式

4.6.17 运算符优先级
-------------------

下表对 Python 中运算符的优先顺序进行了总结，从最低优先级（最后绑定）到最
高优先级（最先绑定）。 相同单元格内的运算符具有相同优先级。 除非句法显式
地给出，否则运算符均指二元运算。 相同单元格内的运算符均从左至右分组（除
了幂运算是从右至左分组）。

请注意比较、成员检测和标识号检测均为相同优先级，并具有如 *note 比较运算:
1551. 一节所描述的从左至右串连特性。

运算符                                              描述
                                                    
----------------------------------------------------------------------------------------------
                                                    
‘:=’                                                赋值表达式
                                                    
                                                    
*note lambda: c37.                                  lambda 表达式
                                                    
                                                    
*note if: 1565. – ‘else’                            条件表达式
                                                    
                                                    
*note or: 155b.                                     布尔逻辑或 OR
                                                    
                                                    
*note and: 155a.                                    布尔逻辑与 AND
                                                    
                                                    
*note not: 155d. ‘x’                                布尔逻辑非 NOT
                                                    
                                                    
*note in: 7ac, *note not in: 146d, *note is: eca,   比较运算，包括成员检测和标识号检测
*note is not: 1558, ‘<’, ‘<=’, ‘>’, ‘>=’, ‘!=’,     
‘==’

‘|’                                                 按位或 OR
                                                    
                                                    
‘^’                                                 按位异或 XOR
                                                    
                                                    
‘&’                                                 按位与 AND
                                                    
                                                    
‘<<’, ‘>>’                                          移位
                                                    
                                                    
‘+’, ‘-’                                            加和减
                                                    
                                                    
‘*’, ‘@’, ‘/’, ‘//’, ‘%’                            乘，矩阵乘，除，整除，取余 (1)
                                                    
                                                    
‘+x’, ‘-x’, ‘~x’                                    正，负，按位非 NOT
                                                    
                                                    
‘**’                                                乘方 (2)
                                                    
                                                    
*note await: 1a4. ‘x’                               await 表达式
                                                    
                                                    
‘x[index]’, ‘x[index:index]’, ‘x(arguments...)’,    抽取，切片，调用，属性引用
‘x.attribute’                                       

‘(expressions...)’,                                 绑定或加圆括号的表达式，列表显示，字典
                                                    显示，集合显示
‘[expressions...]’, ‘{key: value...}’,              
‘{expressions...}’

备注
....

   ---------- Footnotes ----------

   (1) (5) ‘%’ 运算符也被用于字符串格式化；在此场合下会使用同样的优先级
。

   (2) (6) 幂运算符 ‘**’ 绑定的紧密程度低于在其右侧的算术或按位一元运算
符，也就是说 ‘2**-1’ 为 ‘0.5’。


File: python.info,  Node: 简单语句,  Next: 复合语句,  Prev: 表达式,  Up: Python语言参考

4.7 简单语句
============

简单语句由一个单独的逻辑行构成。 多条简单语句可以存在于同一行内并以分号
分隔。 简单语句的句法为:

     simple_stmt ::= expression_stmt
                     | assert_stmt
                     | assignment_stmt
                     | augmented_assignment_stmt
                     | annotated_assignment_stmt
                     | pass_stmt
                     | del_stmt
                     | return_stmt
                     | yield_stmt
                     | raise_stmt
                     | break_stmt
                     | continue_stmt
                     | import_stmt
                     | future_stmt
                     | global_stmt
                     | nonlocal_stmt

* Menu:

* 表达式语句::
* 赋值语句::
* assert 语句::
* pass 语句: pass 语句<2>.
* del 语句: del 语句<2>.
* return 语句::
* yield 语句::
* raise 语句::
* break 语句::
* continue 语句::
* import 语句::
* global 语句::
* nonlocal 语句::


File: python.info,  Node: 表达式语句,  Next: 赋值语句,  Up: 简单语句

4.7.1 表达式语句
----------------

表达式语句用于计算和写入值（大多是在交互模式下），或者（通常情况）调用一
个过程 (过程就是不返回有意义结果的函数；在 Python 中，过程的返回值为
‘None’)。 表达式语句的其他使用方式也是允许且有特定用处的。 表达式语句的
句法为:

     expression_stmt ::= starred_expression

表达式语句会对指定的表达式列表（也可能为单一表达式）进行求值。

在交互模式下，如果结果值不为 ‘None’，它会通过内置的 *note repr(): 7d5. 函
数转换为一个字符串，该结果字符串将以单独一行的形式写入标准输出（例外情况
是如果结果为 ‘None’，则该过程调用不产生任何输出。）


File: python.info,  Node: 赋值语句,  Next: assert 语句,  Prev: 表达式语句,  Up: 简单语句

4.7.2 赋值语句
--------------

赋值语句用于将名称（重）绑定到特定值，以及修改属性或可变对象的成员项:

     assignment_stmt ::= (target_list "=")+ (starred_expression | yield_expression)
     target_list     ::= target ("," target)* [","]
     target          ::= identifier
                         | "(" [target_list] ")"
                         | "[" [target_list] "]"
                         | attributeref
                         | subscription
                         | slicing
                         | "*" target

(请参阅 *note 原型: 1520. 一节了解 `属性引用', `抽取' 和 `切片' 的句法定
义。)

赋值语句会对指定的表达式列表进行求值（注意这可能为单一表达式或是由逗号分
隔的列表，后者将产生一个元组）并将单一结果对象从左至右逐个赋值给目标列表
。

赋值是根据目标（列表）的格式递归地定义的。 当目标为一个可变对象（属性引
用、抽取或切片）的组成部分时，该可变对象必须最终执行赋值并决定其有效性，
如果赋值操作不可接受也可能引发异常。 各种类型可用的规则和引发的异常通过
对象类型的定义给出（参见 *note 标准类型层级结构: 1431. 一节）。

对象赋值的目标对象可以包含于圆括号或方括号内，具体操作按以下方式递归地定
义。

   * 如果目标列表为后面不带逗号、可以包含于圆括号内的单一目标，则将对象
     赋值给该目标。

   * 否则：该对象必须为具有与目标列表相同项数的可迭代对象，这些项将按从
     左至右的顺序被赋值给对应的目标。

        * 如果目标列表包含一个带有星号前缀的目标，这称为“加星”目标：则该
          对象至少必须为与目标列表项数减一相同项数的可迭代对象。 该可迭
          代对象前面的项将按从左至右的顺序被赋值给加星目标之前的目标。 该
          可迭代对象末尾的项将被赋值给加星目标之后的目标。 然后该可迭代
          对象中剩余项的列表将被赋值给加星目标（该列表可以为空）。

        * 否则：该对象必须为具有与目标列表相同项数的可迭代对象，这些项将
          按从左至右的顺序被赋值给对应的目标。

对象赋值给单个目标的操作按以下方式递归地定义。

   * 如果目标为标识符（名称）:

        * 如果该名称未出现于当前代码块的 *note global: 1254. 或 *note
          nonlocal: c47. 语句中：该名称将被绑定到当前局部命名空间的对象
          。

        * 否则：该名称将被分别绑定到全局命名空间或由 *note nonlocal:
          c47. 所确定的外层命名空间的对象。

     如果该名称已经被绑定则将被重新绑定。 这可能导致之前被绑定到该名称的
     对象的引用计数变为零，造成该对象进入释放过程并调用其析构器（如果存
     在）。

   * 如果该对象为属性引用：引用中的原型表达式会被求值。 它应该产生一个具
     有可赋值属性的对象；否则将引发 *note TypeError: 193.。 该对象会被要
     求将可赋值对象赋值给指定的属性；如果它无法执行赋值，则会引发异常 (通
     常应为 *note AttributeError: 3a3. 但并不强制要求)。 注意：如果该对
     象为类实例并且属性引用在赋值运算符的两侧都出现，则右侧表达式 ‘a.x’
     可以访问实例属性或（如果实例属性不存在）类属性。 左侧目标 ‘a.x’ 将
     总是设定为实例属性，并在必要时创建该实例属性。 因此 ‘a.x’ 的两次出
     现不一定指向相同的属性：如果右侧表达式指向一个类属性，则左侧会创建
     一个新的实例属性作为赋值的目标:

          class Cls:
              x = 3             # class variable
          inst = Cls()
          inst.x = inst.x + 1   # writes inst.x as 4 leaving Cls.x as 3

     此描述不一定作用于描述器属性，例如通过 *note property(): 1d8. 创建
     的特征属性。

   * 如果目标为一个抽取项：引用中的原型表达式会被求值。 它应当产生一个可
     变序列对象（例如列表）或一个映射对象（例如字典）。 接下来，该抽取表
     达式会被求值。

     如果原型为一个可变序列对象（例如列表），抽取应产生一个整数。 如其为
     负值，则再加上序列长度。 结果值必须为一个小于序列长度的非负整数，序
     列将把被赋值对象赋值给该整数指定索引号的项。 如果索引超出范围，将会
     引发 *note IndexError: e7d. (给被抽取序列赋值不能向列表添加新项)。

     如果原型为一个映射对象（例如字典），抽取必须具有与该映射的键类型相
     兼容的类型，然后映射中会创建一个将抽取映射到被赋值对象的键/值对。 这
     可以是替换一个现有键/值对并保持相同键值，也可以是插入一个新键/值对
     （如果具有相同值的键不存在）。

     对于用户定义对象，会调用 *note __setitem__(): c6a. 方法并附带适当的
     参数。

   * 如果目标为一个切片：引用中的原型表达式会被求值。 它应当产生一个可变
     序列对象（例如列表）。 被赋值对象应当是一个相同类型的序列对象。 接
     下来，下界与上界表达式如果存在的话将被求值；默认值分别为零和序列长
     度。 上下边界值应当为整数。 如果某一边界为负值，则会加上序列长度。
     求出的边界会被裁剪至介于零和序列长度的开区间中。 最后，将要求序列对
     象以被赋值序列的项替换该切片。 切片的长度可能与被赋值序列的长度不同
     ，这会在目标序列允许的情况下改变目标序列的长度。

`CPython implementation detail:' 在当前实现中，目标的句法被当作与表达式
的句法相同，无效的句法会在代码生成阶段被拒绝，导致不太详细的错误信息。

虽然赋值的定义意味着左手边与右手边的重叠是“同时”进行的（例如 ‘a, b = b,
a’ 会交换两个变量的值），但在赋值给变量的多项集 `之内' 的重叠是从左至右
进行的，这有时会令人混淆。 例如，以下程序将会打印出 ‘[0, 2]’:

     x = [0, 1]
     i = 0
     i, x[i] = 1, 2         # i is updated, then x[i] is updated
     print(x)

参见
....

PEP 3132(1) - 扩展的可迭代对象拆包

     对 ‘*target’ 特性的规范说明。

* Menu:

* 增强赋值语句::
* 带标注的赋值语句::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3132


File: python.info,  Node: 增强赋值语句,  Next: 带标注的赋值语句,  Up: 赋值语句

4.7.2.1 增强赋值语句
....................

增强赋值语句就是在单个语句中将二元运算和赋值语句合为一体:

     augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)
     augtarget                 ::= identifier | attributeref | subscription | slicing
     augop                     ::= "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
                                   | ">>=" | "<<=" | "&=" | "^=" | "|="

（请参阅 *note 原型: 1520. 一节了解最后三种符号的句法定义。）

增强赋值语句将对目标和表达式列表求值（与普通赋值语句不同的是，前者不能为
可迭代对象拆包），对两个操作数相应类型的赋值执行指定的二元运算，并将结果
赋值给原始目标。 目标仅会被求值一次。

增强赋值语句例如 ‘x += 1’ 可以改写为 ‘x = x + 1’ 获得类似但并非完全等价
的效果。 在增强赋值的版本中，‘x’ 仅会被求值一次。 而且，在可能的情况下，
实际的运算是 `原地' 执行的，也就是说并不是创建一个新对象并将其赋值给目标
，而是直接修改原对象。

不同于普通赋值，增强赋值会在对右手边求值 `之前' 对左手边求值。 例如，
‘a[i] += f(x)’ 首先查找 ‘a[i]’，然后对 ‘f(x)’ 求值并执行加法操作，最后将
结果写回到 ‘a[i]’。

除了在单个语句中赋值给元组和多个目标的例外情况，增强赋值语句的赋值操作处
理方式与普通赋值相同。 类似地，除了可能存在 `原地' 操作行为的例外情况，
增强赋值语句执行的二元运算也与普通二元运算相同。

对于属性引用类目标，针对常规赋值的 *note 关于类和实例属性的警告: 1580. 也
同样适用。


File: python.info,  Node: 带标注的赋值语句,  Prev: 增强赋值语句,  Up: 赋值语句

4.7.2.2 带标注的赋值语句
........................

*note 标注: 628. 赋值就是在单个语句中将变量或属性标注和可选的赋值语句合
为一体:

     annotated_assignment_stmt ::= augtarget ":" expression
                                   ["=" (starred_expression | yield_expression)]

与普通 *note 赋值语句: 157b. 的差别在于仅允许单个目标。

对于将简单名称作为赋值目标的情况，如果是在类或模块作用域中，标注会被求值
并存入一个特殊的类或模块属性 ‘__annotations__’ 中，这是一个将变量名称（
如为私有会被移除）映射到被求值标注的字典。 此属性为可写并且在类或模块体
开始执行时如果静态地发现标注就会自动创建。

对于将表达式作为赋值目标的情况，如果是在类或模块作用域中，标注会被求值，
但不会保存。

如果一个名称在函数作用域内被标注，则该名称为该作用域的局部变量。 标注绝
不会在函数作用域内被求值和保存。

如果存在右手边，带标注的赋值会在对标注求值之前（如果适用）执行实际的赋值
。 如果用作表达式目标的右手边不存在，则解释器会对目标求值，但最后的
*note __setitem__(): c6a. 或 *note __setattr__(): e34. 调用除外。

参见
....

PEP 526(1) - 变量标注的语法

     该提议增加了标注变量（也包括类变量和实例变量）类型的语法，而不再是
     通过注释来进行表达。

PEP 484(2) - 类型提示

     该提议增加了 *note typing: 11a. 模块以便为类型标注提供标准句法，可
     被静态分析工具和 IDE 所使用。

在 3.8 版更改: 现在带有标注的赋值允许在右边以同样的表达式作为常规赋值。
之前，某些表达式（例如未加圆括号的元组表达式）会导致语法错误。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0526

   (2) https://www.python.org/dev/peps/pep-0484


File: python.info,  Node: assert 语句,  Next: pass 语句<2>,  Prev: 赋值语句,  Up: 简单语句

4.7.3 ‘assert’ 语句
-------------------

assert 语句是在程序中插入调试性断言的简便方式:

     assert_stmt ::= "assert" expression ["," expression]

简单形式 ‘assert expression’ 等价于

     if __debug__:
         if not expression: raise AssertionError

扩展形式 ‘assert expression1, expression2’ 等价于

     if __debug__:
         if not expression1: raise AssertionError(expression2)

以上等价形式假定 *note __debug__: 100c. 和 *note AssertionError: 103e. 指
向具有指定名称的内置变量。 在当前实现中，内置变量 *note __debug__: 100c.
在正常情况下为 ‘True’，在请求优化时为 ‘False’ (对应命令行选项为 *note
-O: 694.)。 如果在编译时请求优化，当前代码生成器不会为 assert 语句发出任
何代码。 请注意不必在错误信息中包含失败表达式的源代码；它会被作为栈追踪
的一部分被显示。

赋值给 *note __debug__: 100c. 是非法的。 该内置变量的值会在解释器启动时
确定。


File: python.info,  Node: pass 语句<2>,  Next: del 语句<2>,  Prev: assert 语句,  Up: 简单语句

4.7.4 ‘pass’ 语句
-----------------

     pass_stmt ::= "pass"

*note pass: 1250. 是一个空操作 — 当它被执行时，什么都不发生。 它适合当语
法上需要一条语句但并不需要执行任何代码时用来临时占位，例如:

     def f(arg): pass    # a function that does nothing (yet)

     class C: pass       # a class with no methods (yet)


File: python.info,  Node: del 语句<2>,  Next: return 语句,  Prev: pass 语句<2>,  Up: 简单语句

4.7.5 ‘del’ 语句
----------------

     del_stmt ::= "del" target_list

删除是递归定义的，与赋值的定义方式非常类似。 此处不再详细说明，只给出一
些提示。

目标列表的删除将从左至右递归地删除每一个目标。

名称的删除将从局部或全局命名空间中移除该名称的绑定，具体作用域的确定是看
该名称是否有在同一代码块的 *note global: 1254. 语句中出现。 如果该名称未
被绑定，将会引发 *note NameError: d83.。

属性引用、抽取和切片的删除会被传递给相应的原型对象；删除一个切片基本等价
于赋值为一个右侧类型的空切片（但即便这一点也是由切片对象决定的）。

在 3.2 版更改: 在之前版本中，如果一个名称作为被嵌套代码块中的自由变量出
现，则将其从局部命名空间中删除是非法的。


File: python.info,  Node: return 语句,  Next: yield 语句,  Prev: del 语句<2>,  Up: 简单语句

4.7.6 ‘return’ 语句
-------------------

     return_stmt ::= "return" [expression_list]

*note return: 191. 在语法上只会出现于函数定义所嵌套的代码，不会出现于类
定义所嵌套的代码。

如果提供了表达式列表，它将被求值，否则以 ‘None’ 替代。

*note return: 191. 会离开当前函数调用，并以表达式列表 (或 ‘None’) 作为返
回值。

当 *note return: 191. 将控制流传出一个带有 *note finally: 183. 子句的
*note try: d7a. 语句时，该 ‘finally’ 子句会先被执行然后再真正离开该函数
。

在一个生成器函数中，*note return: 191. 语句表示生成器已完成并将导致
*note StopIteration: 48e. 被引发。 返回值（如果有的话）会被当作一个参数
用来构建 *note StopIteration: 48e. 并成为 ‘StopIteration.value’ 属性。

在一个异步生成器函数中，一个空的 *note return: 191. 语句表示异步生成器已
完成并将导致 *note StopAsyncIteration: 1022. 被引发。 一个非空的
‘return’ 语句在异步生成器函数中会导致语法错误。


File: python.info,  Node: yield 语句,  Next: raise 语句,  Prev: return 语句,  Up: 简单语句

4.7.7 ‘yield’ 语句
------------------

     yield_stmt ::= yield_expression

*note yield: 190. 语句在语义上等同于 *note yield 表达式: 1510.。 yield 语
句可用来省略在使用等效的 yield 表达式语句时所必须的圆括号。 例如，以下
yield 语句

     yield <expr>
     yield from <expr>

等同于以下 yield 表达式语句

     (yield <expr>)
     (yield from <expr>)

yield 表达式和语句仅在定义 *note generator: 9aa. 函数时使用，并且仅被用
于生成器函数的函数体内部。 在函数定义中使用 yield 就足以使得该定义创建的
是生成器函数而非普通函数。

有关 *note yield: 190. 语义的完整细节请参看 *note yield 表达式: 1510. 一
节。


File: python.info,  Node: raise 语句,  Next: break 语句,  Prev: yield 语句,  Up: 简单语句

4.7.8 ‘raise’ 语句
------------------

     raise_stmt ::= "raise" [expression ["from" expression]]

如果不带表达式，*note raise: c4a. 会重新引发当前作用域内最后一个激活的异
常。 如果当前作用域内没有激活的异常，将会引发 *note RuntimeError: 2bb. 来
提示错误。

否则的话，*note raise: c4a. 会将第一个表达式求值为异常对象。 它必须为
*note BaseException: 1a9. 的子类或实例。 如果它是一个类，当需要时会通过
不带参数地实例化该类来获得异常的实例。

异常的 `类型' 为异常实例的类，`值' 为实例本身。

当异常被引发时通常会自动创建一个回溯对象并将其关联到可写的
‘__traceback__’ 属性。 你可以创建一个异常并同时使用 ‘with_traceback()’ 异
常方法（该方法将返回同一异常实例，并将回溯对象设为其参数）设置自己的回溯
，就像这样:

     raise Exception("foo occurred").with_traceback(tracebackobj)

‘from’ 子句用于异常串连：如果有该子句，则第二个 `表达式' 必须为另一个异
常类或实例。 如果第二个表达式是一个异常实例，它将作为可写的 ‘__cause__’
属性被关联到所引发的异常。 如果该表达式是一个异常类，这个类将被实例化且
所生成的异常实例将作为 ‘__cause__’ 属性被关联到所引发的异常。 如果所引发
的异常未被处理，则两个异常都将被打印出来:

     >>> try:
     ...     print(1 / 0)
     ... except Exception as exc:
     ...     raise RuntimeError("Something bad happened") from exc
     ...
     Traceback (most recent call last):
       File "<stdin>", line 2, in <module>
     ZeroDivisionError: division by zero

     The above exception was the direct cause of the following exception:

     Traceback (most recent call last):
       File "<stdin>", line 4, in <module>
     RuntimeError: Something bad happened

如果一个异常在异常处理器或 *note finally: 183. clause: 中被引发，类似的
机制会隐式地发挥作用，之前的异常将被关联到新异常的 ‘__context__’ 属性:

     >>> try:
     ...     print(1 / 0)
     ... except:
     ...     raise RuntimeError("Something bad happened")
     ...
     Traceback (most recent call last):
       File "<stdin>", line 2, in <module>
     ZeroDivisionError: division by zero

     During handling of the above exception, another exception occurred:

     Traceback (most recent call last):
       File "<stdin>", line 4, in <module>
     RuntimeError: Something bad happened

异常串连可通过在 ‘from’ 子句中指定 *note None: 158. 来显式地加以抑制:

     >>> try:
     ...     print(1 / 0)
     ... except:
     ...     raise RuntimeError("Something bad happened") from None
     ...
     Traceback (most recent call last):
       File "<stdin>", line 4, in <module>
     RuntimeError: Something bad happened

有关异常的更多信息可在 *note 异常: 14b9. 一节查看，有关处理异常的信息可
在 *note try 语句: d7a. 一节查看。

在 3.3 版更改: *note None: 158. 现在允许被用作 ‘raise X from Y’ 中的
‘Y’。

3.3 新版功能: 使用 ‘__suppress_context__’ 属性来抑制异常上下文的自动显示
。


File: python.info,  Node: break 语句,  Next: continue 语句,  Prev: raise 语句,  Up: 简单语句

4.7.9 ‘break’ 语句
------------------

     break_stmt ::= "break"

*note break: 2dc. 在语法上只会出现于 *note for: c38. 或 *note while:
123d. 循环所嵌套的代码，但不会出现于该循环内部的函数或类定义所嵌套的代码
。

它会终结最近的外层循环，如果循环有可选的 ‘else’ 子句，也会跳过该子句。

如果一个 *note for: c38. 循环被 *note break: 2dc. 所终结，该循环的控制目
标会保持其当前值。

当 *note break: 2dc. 将控制流传出一个带有 *note finally: 183. 子句的
*note try: d7a. 语句时，该 ‘finally’ 子句会先被执行然后再真正离开该循环
。


File: python.info,  Node: continue 语句,  Next: import 语句,  Prev: break 语句,  Up: 简单语句

4.7.10 ‘continue’ 语句
----------------------

     continue_stmt ::= "continue"

*note continue: 182. 在语法上只会出现于 *note for: c38. 或 *note while:
123d. 循环所嵌套的代码中，但不会出现于该循环内部的函数或类定义中。 它会
继续执行最近的外层循环的下一个轮次。

当 *note continue: 182. 将控制流传出一个带有 *note finally: 183. 子句的
*note try: d7a. 语句时，该 ‘finally’ 子句会先被执行然后再真正开始循环的
下一个轮次。


File: python.info,  Node: import 语句,  Next: global 语句,  Prev: continue 语句,  Up: 简单语句

4.7.11 ‘import’ 语句
--------------------

     import_stmt     ::= "import" module ["as" identifier] ("," module ["as" identifier])*
                         | "from" relative_module "import" identifier ["as" identifier]
                         ("," identifier ["as" identifier])*
                         | "from" relative_module "import" "(" identifier ["as" identifier]
                         ("," identifier ["as" identifier])* [","] ")"
                         | "from" module "import" "*"
     module          ::= (identifier ".")* identifier
     relative_module ::= "."* module | "."+

基本的 import 语句（不带 *note from: c4d. 子句）会分两步执行:

  1. 查找一个模块，如果有必要还会加载并初始化模块。

  2. 在局部命名空间中为 *note import: c25. 语句发生位置所处的作用域定义
     一个或多个名称。

当语句包含多个子句（由逗号分隔）时这两个步骤将对每个子句分别执行，如同这
些子句被分成独立的 import 语句一样。

第一个步骤即查找和加载模块的详情 *note 导入系统: 143f. 一节中有更详细的
描述，其中也描述了可被导入的多种类型的包和模块，以及可用于定制导入系统的
所有钩子对象。 请注意这一步如果失败，则可能说明模块无法找到，`或者' 是在
初始化模块，包括执行模块代码期间发生了错误。

如果成功获取到请求的模块，则可以通过以下三种方式一之在局部命名空间中使用
它:

   * 如果模块名称之后带有 ‘as’，则跟在 ‘as’ 之后的名称将直接绑定到所导入
     的模块。

   * 如果没有指定其他名称，且被导入的模块为最高层级模块，则模块的名称将
     被绑定到局部命名空间作为对所导入模块的引用。

   * 如果被导入的模块 `不是' 最高层级模块，则包含该模块的最高层级包的名
     称将被绑定到局部命名空间作为对该最高层级包的引用。 所导入的模块必须
     使用其完整限定名称来访问而不能直接访问。

*note from: c4d. 形式使用的过程略微繁复一些:

  1. 查找 *note from: c4d. 子句中指定的模块，如有必要还会加载并初始化模
     块；

  2. 对于 *note import: c25. 子句中指定的每个标识符：

       1. 检查被导入模块是否有该名称的属性

       2. 如果没有，尝试导入具有该名称的子模块，然后再次检查被导入模块是
          否有该属性

       3. 如果未找到该属性，则引发 *note ImportError: 33d.。

       4. 否则的话，将对该值的引用存入局部命名空间，如果有 ‘as’ 子句则使
          用其指定的名称，否则使用该属性的名称

示例:

     import foo                 # foo imported and bound locally
     import foo.bar.baz         # foo.bar.baz imported, foo bound locally
     import foo.bar.baz as fbb  # foo.bar.baz imported and bound as fbb
     from foo.bar import baz    # foo.bar.baz imported and bound as baz
     from foo import attr       # foo imported and foo.attr bound as attr

如果标识符列表改为一个星号 (‘'*'’)，则在模块中定义的全部公有名称都将按
*note import: c25. 语句所在的作用域被绑定到局部命名空间。

一个模块所定义的 `公有名称' 是由在模块的命名空间中检测一个名为 ‘__all__’
的变量来确定的；如果有定义，它必须是一个字符串列表，其中的项为该模块所定
义或导入的名称。 在 ‘__all__’ 中所给出的名称都会被视为公有并且应当存在。
如果 ‘__all__’ 没有被定义，则公有名称的集合将包含在模块的命名空间中找到
的所有不以下划线字符 (‘'_'’) 打头的名称。 ‘__all__’ 应当包括整个公有
API。 它的目标是避免意外地导出不属于 API 的一部分的项（例如在模块内部被
导入和使用的库模块）。

通配符形式的导入 — ‘from module import *’ — 仅在模块层级上被允许。 尝试
在类或函数定义中使用它将引发 *note SyntaxError: 460.。

当指定要导入哪个模块时，你不必指定模块的绝对名称。 当一个模块或包被包含
在另一个包之中时，可以在同一个最高层级包中进行相对导入，而不必提及包名称
。 通过在 *note from: c4d. 之后指定的模块或包中使用前缀点号，你可以在不
指定确切名称的情况下指明在当前包层级结构中要上溯多少级。 一个前缀点号表
示是执行导入的模块所在的当前包，两个点号表示上溯一个包层级。 三个点号表
示上溯两级，依此类推。 因此如果你执行 ‘from . import mod’ 时所处位置为
‘pkg’ 包内的一个模块，则最终你将导入 ‘pkg.mod’。 如果你执行 ‘from
..subpkg2 import mod’ 时所处位置为 ‘pkg.subpkg1’ 则你将导入
‘pkg.subpkg2.mod’。 有关相对导入的规范说明包含在 *note 包相对导入: 14e5.
一节中。

*note importlib.import_module(): b1b. 被提供用来为动态地确定要导入模块的
应用提供支持。

引发一个 *note 审计事件: ea1. ‘import’ 附带参数 ‘module’, ‘filename’,
‘sys.path’, ‘sys.meta_path’, ‘sys.path_hooks’。

* Menu:

* future 语句::


File: python.info,  Node: future 语句,  Up: import 语句

4.7.11.1 future 语句
....................

`future 语句' 是一种针对编译器的指令，指明某个特定模块应当使用在特定的未
来某个 Python 发行版中成为标准特性的语法或语义。

future 语句的目的是使得向在语言中引入了不兼容改变的 Python 未来版本的迁
移更为容易。 它允许基于每个模块在某种新特性成为标准之前的发行版中使用该
特性。

     future_stmt ::= "from" "__future__" "import" feature ["as" identifier]
                     ("," feature ["as" identifier])*
                     | "from" "__future__" "import" "(" feature ["as" identifier]
                     ("," feature ["as" identifier])* [","] ")"
     feature     ::= identifier

future 语句必须在靠近模块开头的位置出现。 可以出现在 future 语句之前行只
有:

   * 模块的文档字符串（如果存在），

   * 注释，

   * 空行，以及

   * 其他 future 语句。

唯一需要使用 future 语句的特性是 ‘标注’ (参见 PEP 563(1))。

future 语句所启用的所有历史特性仍然为 Python 3 所认可。 其中包括
‘absolute_import’, ‘division’, ‘generators’, ‘generator_stop’,
‘unicode_literals’, ‘print_function’, ‘nested_scopes’ 和
‘with_statement’。 它们都已成为冗余项，因为它们总是为已启用状态，保留它
们只是为了向后兼容。

future 语句在编译时会被识别并做特殊对待：对核心构造语义的改变常常是通过
生成不同的代码来实现。 新的特性甚至可能会引入新的不兼容语法（例如新的保
留字），在这种情况下编译器可能需要以不同的方式来解析模块。 这样的决定不
能推迟到运行时方才作出。

对于任何给定的发布版本，编译器要知道哪些特性名称已被定义，如果某个
future 语句包含未知的特性则会引发编译时错误。

直接运行时的语义与任何 import 语句相同：存在一个后文将详细说明的标准模块
*note __future__: 0.，它会在执行 future 语句时以通常的方式被导入。

相应的运行时语义取决于 future 语句所启用的指定特性。

请注意以下语句没有任何特别之处:

     import __future__ [as name]

这并非 future 语句；它只是一条没有特殊语义或语法限制的普通 import 语句。

在默认情况下，通过对Code compiled by calls to the 内置函数 *note exec():
c4c. 和 *note compile(): 1b5. 的调用所编译的代码如果出现于一个包含有
future 语句的模块 ‘M’ 之中，就会使用 future 语句所关联的语法和语义。 此
行为可以通过 *note compile(): 1b5. 的可选参数加以控制 — 请参阅该函数的文
档以了解详情。

在交互式解释器提示符中键入的 future 语句将在解释器会话此后的交互中有效。
如果一个解释器的启动使用了 *note -i: e27. 选项启动，并传入了一个脚本名称
来执行，且该脚本包含 future 语句，它将在交互式会话开始执行脚本之后保持有
效。

参见
....

PEP 236(2) - 回到 __future__

     有关 __future__ 机制的最初提议。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0563

   (2) https://www.python.org/dev/peps/pep-0236


File: python.info,  Node: global 语句,  Next: nonlocal 语句,  Prev: import 语句,  Up: 简单语句

4.7.12 ‘global’ 语句
--------------------

     global_stmt ::= "global" identifier ("," identifier)*

*note global: 1254. 语句是作用于整个当前代码块的声明。 它意味着所列出的
标识符将被解读为全局变量。 要给全局变量赋值不可能不用到 ‘global’ 关键字
，不过自由变量也可以指向全局变量而不必声明为全局变量。

在 *note global: 1254. 语句中列出的名称不得在同一代码块内该 ‘global’ 语
句之前的位置中使用。

在 *note global: 1254. 语句中列出的名称不能被定义为形式参数，也不能在
*note for: c38. 循环的控制目标、*note class: c72. 定义、函数定义、*note
import: c25. 语句或变量标注中定义。

`CPython implementation detail:' 当前的实现并未强制要求所有的上述限制，
但程序不应当滥用这样的自由，因为未来的实现可能会改为强制要求，并静默地改
变程序的含义。

`程序员注意事项:' *note global: 1254. 是对解析器的指令。 它仅对与
‘global’ 语句同时被解析的代码起作用。 特别地，包含在提供给内置 *note
exec(): c4c. 函数字符串或代码对象中的 ‘global’ 语句并不会影响 `包含' 该
函数调用的代码块，而包含在这种字符串中的代码也不会受到包含该函数调用的代
码中的 ‘global’ 语句影响。 这同样适用于 *note eval(): b98. 和 *note
compile(): 1b5. 函数。


File: python.info,  Node: nonlocal 语句,  Prev: global 语句,  Up: 简单语句

4.7.13 ‘nonlocal’ 语句
----------------------

     nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*

*note nonlocal: c47. 语句会使得所列出的名称指向之前在最近的包含作用域中
绑定的除全局变量以外的变量。 这种功能很重要，因为绑定的默认行为是先搜索
局部命名空间。 这个语句允许被封装的代码重新绑定局部作用域以外且非全局（
模块）作用域当中的变量。

与 *note global: 1254. 语句中列出的名称不同，*note nonlocal: c47. 语句中
列出的名称必须指向之前存在于包含作用域之中的绑定（在这个应当用来创建新绑
定的作用域不能被无歧义地确定）。

*note nonlocal: c47. 语句中列出的名称不得与之前存在于局部作用域中的绑定
相冲突。

参见
....

PEP 3104(1) - 访问外层作用域中的名称

     有关 *note nonlocal: c47. 语句的规范说明。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3104


File: python.info,  Node: 复合语句,  Next: 最高层级组件,  Prev: 简单语句,  Up: Python语言参考

4.8 复合语句
============

复合语句是包含其它语句（语句组）的语句；它们会以某种方式影响或控制所包含
其它语句的执行。 通常，复合语句会跨越多行，虽然在某些简单形式下整个复合
语句也可能包含于一行之内。

*note if: def, *note while: 123d. 和 *note for: c38. 语句用来实现传统的
控制流程构造。 *note try: d7a. 语句为一组语句指定异常处理和/和清理代码，
而 *note with: 6f2. 语句允许在一个代码块周围执行初始化和终结化代码。 函
数和类定义在语法上也属于复合语句。

一条复合语句由一个或多个‘子句’组成。 一个子句则包含一个句头和一个‘句体
’。 特定复合语句的子句头都处于相同的缩进层级。 每个子句头以一个作为唯一
标识的关键字开始并以一个冒号结束。 子句体是由一个子句控制的一组语句。 子
句体可以是在子句头的冒号之后与其同处一行的一条或由分号分隔的多条简单语句
，或者也可以是在其之后缩进的一行或多行语句。 只有后一种形式的子句体才能
包含嵌套的复合语句；以下形式是不合法的，这主要是因为无法分清某个后续的
*note else: 1244. 子句应该属于哪个 *note if: def. 子句:

     if test1: if test2: print(x)

还要注意的是在这种情形下分号的绑定比冒号更紧密，因此在以下示例中，所有
*note print(): 88f. 调用或者都不执行，或者都执行:

     if x < y < z: print(x); print(y); print(z)

总结:

     compound_stmt ::= if_stmt
                       | while_stmt
                       | for_stmt
                       | try_stmt
                       | with_stmt
                       | funcdef
                       | classdef
                       | async_with_stmt
                       | async_for_stmt
                       | async_funcdef
     suite         ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
     statement     ::= stmt_list NEWLINE | compound_stmt
     stmt_list     ::= simple_stmt (";" simple_stmt)* [";"]

请注意语句总是以 ‘NEWLINE’ 结束，之后可能跟随一个 ‘DEDENT’。 还要注意可
选的后续子句总是以一个不能作为语句开头的关键字作为开头，因此不会产生歧义
（‘悬空的 *note else: 1244.’问题在 Python 中是通过要求嵌套的 *note if:
def. 语句必须缩进来解决的)。

为了保证清晰，以下各节中语法规则采用将每个子句都放在单独行中的格式。
* Menu:

* if 语句: if 语句<2>.
* while 语句::
* for 语句: for 语句<2>.
* try 语句::
* with 语句::
* 函数定义::
* 类定义::
* 协程: 协程<2>.


File: python.info,  Node: if 语句<2>,  Next: while 语句,  Up: 复合语句

4.8.1 ‘if’ 语句
---------------

*note if: def. 语句用于有条件的执行:

     if_stmt ::= "if" assignment_expression ":" suite
                 ("elif" assignment_expression ":" suite)*
                 ["else" ":" suite]

它通过对表达式逐个求值直至找到一个真值（请参阅 *note 布尔运算: 1559. 了
解真值与假值的定义）在子句体中选择唯一匹配的一个；然后执行该子句体（而且
*note if: def. 语句的其他部分不会被执行或求值）。 如果所有表达式均为假值
，则如果 *note else: 1244. 子句体如果存在就会被执行。


File: python.info,  Node: while 语句,  Next: for 语句<2>,  Prev: if 语句<2>,  Up: 复合语句

4.8.2 ‘while’ 语句
------------------

*note while: 123d. 语句用于在表达式保持为真的情况下重复地执行:

     while_stmt ::= "while" assignment_expression ":" suite
                    ["else" ":" suite]

这将重复地检验表达式，并且如果其值为真就执行第一个子句体；如果表达式值为
假（这可能在第一次检验时就发生）则如果 ‘else’ 子句体存在就会被执行并终止
循环。

第一个子句体中的 *note break: 2dc. 语句在执行时将终止循环且不执行 ‘else’
子句体。 第一个子句体中的 *note continue: 182. 语句在执行时将跳过子句体
中的剩余部分并返回检验表达式。


File: python.info,  Node: for 语句<2>,  Next: try 语句,  Prev: while 语句,  Up: 复合语句

4.8.3 ‘for’ 语句
----------------

*note for: c38. 语句用于对序列（例如字符串、元组或列表）或其他可迭代对象
中的元素进行迭代:

     for_stmt ::= "for" target_list "in" expression_list ":" suite
                  ["else" ":" suite]

表达式列表会被求值一次；它应该产生一个可迭代对象。 系统将为
‘expression_list’ 的结果创建一个迭代器，然后将为迭代器所提供的每一项执行
一次子句体，具体次序与迭代器的返回顺序一致。 每一项会按标准赋值规则 (参
见 *note 赋值语句: 157b.) 被依次赋值给目标列表，然后子句体将被执行。 当
所有项被耗尽时 (这会在序列为空或迭代器引发 *note StopIteration: 48e. 异
常时立刻发生)，‘else’ 子句的子句体如果存在将会被执行，并终止循环。

第一个子句体中的 *note break: 2dc. 语句在执行时将终止循环且不执行 ‘else’
子句体。 第一个子句体中的 *note continue: 182. 语句在执行时将跳过子句体
中的剩余部分并转往下一项继续执行，或者在没有下一项时转往 ‘else’ 子句执行
。

for 循环会对目标列表中的变量进行赋值。 这将覆盖之前对这些变量的所有赋值
，包括在 for 循环体中的赋值:

     for i in range(10):
         print(i)
         i = 5             # this will not affect the for-loop
                           # because i will be overwritten with the next
                           # index in the range

目标列表中的名称在循环结束时不会被删除，但如果序列为空，则它们根本不会被
循环所赋值。 提示：内置函数 *note range(): 9c6. 会返回一个可迭代的整数序
列，适用于模拟 Pascal 中的 ‘for i := a to b do’ 这种效果；例如
‘list(range(3))’ 会返回列表 ‘[0, 1, 2]’。

     注解: 
     当序列在循环中被修改时会有一个微妙的问题（这只可能发生于可变序列例
     如列表中）。 会有一个内部计数器被用来跟踪下一个要使用的项，每次迭代
     都会使计数器递增。 当计数器值达到序列长度时循环就会终止。 这意味着
     如果语句体从序列中删除了当前（或之前）的一项，下一项就会被跳过（因
     为其标号将变成已被处理的当前项的标号）。 类似地，如果语句体在序列当
     前项的前面插入一个新项，当前项会在循环的下一轮中再次被处理。 这会导
     致麻烦的程序错误，避免此问题的办法是对整个序列使用切片来创建一个临
     时副本，例如

          for x in a[:]:
              if x < 0: a.remove(x)


File: python.info,  Node: try 语句,  Next: with 语句,  Prev: for 语句<2>,  Up: 复合语句

4.8.4 ‘try’ 语句
----------------

*note try: d7a. 语句可为一组语句指定异常处理器和/或清理代码:

     try_stmt  ::= try1_stmt | try2_stmt
     try1_stmt ::= "try" ":" suite
                   ("except" [expression ["as" identifier]] ":" suite)+
                   ["else" ":" suite]
                   ["finally" ":" suite]
     try2_stmt ::= "try" ":" suite
                   "finally" ":" suite

*note except: b46. 子句指定一个或多个异常处理程序。 当 *note try: d7a. 子
句中没有发生异常时，没有任何异常处理程序会被执行。 当 ‘try’ 子句中发生异
常时，将启动对异常处理程序的搜索。 此搜索会逐一检查 except 子句直至找到
与该异常相匹配的子句。 如果存在无表达式的 except 子句，它必须是最后一个
；它将匹配任何异常。 对于带有表达式的 except 子句，该表达式会被求值，如
果结果对象与发生的异常“兼容”则该子句将匹配该异常。 如果一个对象是异常对
象所属的类或基类，或者是包含兼容该异常的项的元组则两者就是兼容的。

如果没有 except 子句与异常相匹配，则会在周边代码和发起调用栈上继续搜索异
常处理器。 (1)

如果在对 except 子句头中的表达式求值时引发了异常，则原来对处理器的搜索会
被取消，并在周边代码和调用栈上启动对新异常的搜索（它会被视作是整个 *note
try: d7a. 语句所引发的异常）。

当找到一个匹配的 except 子句时，该异常将被赋值给该 except 子句在 ‘as’ 关
键字之后指定的目标，如果存在此关键字的话，并且该 except 子句体将被执行。
所有 except 子句都必须有可执行的子句体。 当到达子句体的末尾时，通常会转
向整个 try 语句之后继续执行。 （这意味着如果对于同一异常存在有嵌套的两个
处理器，而异常发生于内层处理器的 try 子句中，则外层处理器将不会处理该异
常。）

当使用 ‘as’ 将目标赋值为一个异常时，它将在 except 子句结束时被清除。 这
就相当于

     except E as N:
         foo

被转写为

     except E as N:
         try:
             foo
         finally:
             del N

这意味着异常必须赋值给一个不同的名称才能在 except 子句之后引用它。 异常
会被清除是因为在附加了回溯信息的情况下，它们会形成堆栈帧的循环引用，使得
所有局部变量保持存活直到发生下一次垃圾回收。

在一个 except 子句体被执行之前，有关异常的详细信息存放在 *note sys: fe.
模块中，可通过 *note sys.exc_info(): c67. 来访问。 *note sys.exc_info():
c67. 返回一个 3 元组，由异常类、异常实例和回溯对象组成（参见 *note
标准类型层级结构: 1431. 一节），用于在程序中标识异常发生点。 当从处理异
常的函数返回时 *note sys.exc_info(): c67. 的值会恢复为（调用前的）原值。

如果控制流离开 *note try: d7a. 子句体时没有引发异常，并且没有执行 *note
return: 191, *note continue: 182. 或 *note break: 2dc. 语句，可选的
‘else’ 子句将被执行。 ‘else’ 语句中的异常不会由之前的 *note except: b46.
子句处理。

如果存在 *note finally: 183.，它将指定一个‘清理’处理程序。 *note try:
d7a. 子句会被执行，包括任何 *note except: b46. 和 ‘else’ 子句。 如果在这
些子句中发生任何未处理的异常，该异常会被临时保存。 ‘finally’ 子句将被执
行。 如果存在被保存的异常，它会在 ‘finally’ 子句的末尾被重新引发。 如果
‘finally’ 子句引发了另一个异常，被保存的异常会被设为新异常的上下文。 如
果 ‘finally’ 子句执行了 *note return: 191, *note break: 2dc. 或 *note
continue: 182. 语句，则被保存的异常会被丢弃:

     >>> def f():
     ...     try:
     ...         1/0
     ...     finally:
     ...         return 42
     ...
     >>> f()
     42

在 *note finally: 183. 子句执行期间，程序不能获取异常信息。

当 *note return: 191, *note break: 2dc. 或 *note continue: 182. 语句在一
个 ‘try’...‘finally’ 语句的 *note try: d7a. 子语句体中被执行时，*note
finally: 183. 子语句也会‘在离开时’被执行。

函数的返回值是由最后被执行的 *note return: 191. 语句所决定的。 由于
*note finally: 183. 子句总是被执行，因此在 ‘finally’ 子句中被执行的
‘return’ 语句总是最后被执行的:

     >>> def foo():
     ...     try:
     ...         return 'try'
     ...     finally:
     ...         return 'finally'
     ...
     >>> foo()
     'finally'

有关异常的更多信息可以在 *note 异常: 14b9. 一节找到，有关使用 *note
raise: c4a. 语句生成异常的信息可以在 *note raise 语句: c4a. 一节找到。

在 3.8 版更改: 在 Python 3.8 之前，*note continue: 182. 语句不允许在
*note finally: 183. 子句中使用，这是因为具体实现存在一个问题。

   ---------- Footnotes ----------

   (1) (1) 异常会被传播给发起调用栈，除非存在一个 *note finally: 183. 子
句正好引发了另一个异常。 新引发的异常将导致旧异常的丢失。


File: python.info,  Node: with 语句,  Next: 函数定义,  Prev: try 语句,  Up: 复合语句

4.8.5 ‘with’ 语句
-----------------

*note with: 6f2. 语句用于包装带有使用上下文管理器 (参见 *note with
语句上下文管理器: 1496. 一节) 定义的方法的代码块的执行。 这允许对普通的
*note try: d7a...*note except: b46...*note finally: 183. 使用模式进行封
装以方便地重用。

     with_stmt ::= "with" with_item ("," with_item)* ":" suite
     with_item ::= expression ["as" target]

带有一个“项目”的 *note with: 6f2. 语句的执行过程如下:

  1. 对上下文表达式 (在 *note with_item: 15b9. 中给出的表达式) 求值以获
     得一个上下文管理器。

  2. 载入上下文管理器的 *note __enter__(): c9d. 以便后续使用。

  3. 载入上下文管理器的 *note __exit__(): c9e. 以便后续使用。

  4. 发起调用上下文管理器的 *note __enter__(): c9d. 方法。

  5. 如果 *note with: 6f2. 语句中包含一个目标，来自 *note __enter__():
     c9d. 的返回值将被赋值给它。

          注解: *note with: 6f2. 语句会保证如果 *note __enter__(): c9d.
          方法返回时未发生错误，则 *note __exit__(): c9e. 将总是被调用。
          因此，如果在对目标列表赋值期间发生错误，则会将其视为在语句体内
          部发生的错误。 参见下面的第 6 步。

  6. 执行语句体。

  7. 发起调用上下文管理器的 *note __exit__(): c9e. 方法。 如果语句体的退
     出是由异常导致的，则其类型、值和回溯信息将被作为参数传递给 *note
     __exit__(): c9e.。 否则的话，将提供三个 *note None: 158. 参数。

     如果语句体的退出是由异常导致的，并且来自 *note __exit__(): c9e. 方
     法的返回值为假，则该异常会被重新引发。 如果返回值为真，则该异常会被
     抑制，并会继续执行 *note with: 6f2. 语句之后的语句。

     如果语句体由于异常以外的任何原因退出，则来自 *note __exit__(): c9e.
     的返回值会被忽略，并会在该类退出正常的发生位置继续执行。

以下代码:

     with EXPRESSION as TARGET:
         SUITE

在语义上等价于:

     manager = (EXPRESSION)
     enter = type(manager).__enter__
     exit = type(manager).__exit__
     value = enter(manager)
     hit_except = False

     try:
         TARGET = value
         SUITE
     except:
         hit_except = True
         if not exit(manager, *sys.exc_info()):
             raise
     finally:
         if not hit_except:
             exit(manager, None, None, None)

如果有多个项目，则会视作存在多个 *note with: 6f2. 语句嵌套来处理多个上下
文管理器:

     with A() as a, B() as b:
         SUITE

在语义上等价于:

     with A() as a:
         with B() as b:
             SUITE

在 3.1 版更改: 支持多个上下文表达式。

参见
....

PEP 343(1) - "with" 语句

     Python *note with: 6f2. 语句的规范描述、背景和示例。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0343


File: python.info,  Node: 函数定义,  Next: 类定义,  Prev: with 语句,  Up: 复合语句

4.8.6 函数定义
--------------

函数定义就是对用户自定义函数的定义（参见 *note 标准类型层级结构: 1431. 一
节）:

     funcdef                   ::= [decorators] "def" funcname "(" [parameter_list] ")"
                                   ["->" expression] ":" suite
     decorators                ::= decorator+
     decorator                 ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
     dotted_name               ::= identifier ("." identifier)*
     parameter_list            ::= defparameter ("," defparameter)* "," "/" ["," [parameter_list_no_posonly]]
                                     | parameter_list_no_posonly
     parameter_list_no_posonly ::= defparameter ("," defparameter)* ["," [parameter_list_starargs]]
                                   | parameter_list_starargs
     parameter_list_starargs   ::= "*" [parameter] ("," defparameter)* ["," ["**" parameter [","]]]
                                   | "**" parameter [","]
     parameter                 ::= identifier [":" expression]
     defparameter              ::= parameter ["=" expression]
     funcname                  ::= identifier

函数定义是一条可执行语句。 它执行时会在当前局部命名空间中将函数名称绑定
到一个函数对象（函数可执行代码的包装器）。 这个函数对象包含对当前全局命
名空间的引用，作为函数被调用时所使用的全局命名空间。

函数定义并不会执行函数体；只有当函数被调用时才会执行此操作。 (1)

一个函数定义可以被一个或多个 *note decorator: 284. 表达式所包装。 当函数
被定义时将在包含该函数定义的作用域中对装饰器表达式求值。 求值结果必须是
一个可调用对象，它会以该函数对象作为唯一参数被发起调用。 其返回值将被绑
定到函数名称而非函数对象。 多个装饰器会以嵌套方式被应用。 例如以下代码

     @f1(arg)
     @f2
     def func(): pass

大致等价于

     def func(): pass
     func = f1(arg)(f2(func))

不同之处在于原始函数并不会被临时绑定到名称 ‘func’。

当一个或多个 *note 形参: 153b. 具有 `形参' ‘=’ `表达式' 这样的形式时，该
函数就被称为具有“默认形参值”。 对于一个具有默认值的形参，其对应的 *note
argument: 1532. 可以在调用中被省略，在此情况下会用形参的默认值来替代。 如
果一个形参具有默认值，后续所有在 "‘*’" 之前的形参也必须具有默认值 — 这个
句法限制并未在语法中明确表达。

`默认形参值会在执行函数定义时按从左至右的顺序被求值。' 这意味着当函数被
定义时将对表达式求值一次，相同的“预计算”值将在每次调用时被使用。 这一点
在默认形参为可变对象，例如列表或字典的时候尤其需要重点理解：如果函数修改
了该对象（例如向列表添加了一项），则实际上默认值也会被修改。 这通常不是
人们所预期的。 绕过此问题的一个方法是使用 ‘None’ 作为默认值，并在函数体
中显式地对其进行测试，例如:

     def whats_on_the_telly(penguin=None):
         if penguin is None:
             penguin = []
         penguin.append("property of the zoo")
         return penguin

函数调用的语义在 *note 调用: 655. 一节中有更详细的描述。 函数调用总是会
给形参列表中列出的所有形参赋值，或是用位置参数，或是用关键字参数，或是用
默认值。 如果存在 "‘*identifier’" 这样的形式，它会被初始化为一个元组来接
收任何额外的位置参数，默认为一个空元组。 如果存在 "‘**identifier’" 这样
的形式，它会被初始化为一个新的有序映射来接收任何额外的关键字参数，默认为
一个相同类型的空映射。 在 "‘*’" 或 "‘*identifier’" 之后的形参都是仅限关
键字形参因而只能通过关键字参数传入。 在 "‘/’" 之前的形参都是仅限位置形参
因而只能通过位置参数传入。

在 3.8 版更改: 可以使用 ‘/’ 函数形参语法来标示仅限位置形参。 请参阅 PEP
570(2) 了解详情。

形参可以带有 *note 标注: 126d.，其形式为在形参名称后加上 "‘:
expression’"。 任何形参都可以带有标注，甚至 ‘*identifier’ 或
‘**identifier’ 这样的形参也可以。 函数可以带有“返回”标注，其形式为在形参
列表后加上 "‘-> expression’"。 这些标注可以是任何有效的 Python 表达式。
标注的存在不会改变函数的语义。 标注值可以作为函数对象的
‘__annotations__’ 属性中以对应形参名称为键的字典值被访问。 如果使用了
‘annotations’ import from *note __future__: 0. 的方式，则标注会在运行时
保存为字符串以启用延迟求值特性。 否则，它们会在执行函数定义时被求值。 在
这种情况下，标注的求值顺序可能与它们在源代码中出现的顺序不同。

创建匿名函数（未绑定到一个名称的函数）以便立即在表达式中使用也是可能的。
这需要使用 lambda 表达式，具体描述见 *note lambda 表达式: c37. 一节。 请
注意 lambda 只是简单函数定义的一种简化写法；在 "*note def: dc6." 语句中
定义的函数也可以像用 lambda 表达式定义的函数一样被传递或赋值给其他名称。
"‘def’" 形式实际上更为强大，因为它允许执行多条语句和使用标注。

`程序员注意事项:' 函数属于一类对象。 在一个函数内部执行的 "‘def’" 语句会
定义一个局部函数并可被返回或传递。 在嵌套函数中使用的自由变量可以访问包
含该 def 语句的函数的局部变量。 详情参见 *note 命名与绑定: 14af. 一节。

参见
....

PEP 3107(3) - 函数标注

     最初的函数标注规范说明。

PEP 484(4) - 类型提示

     标注的标准含意定义：类型提示。

PEP 526(5) - 变量标注的语法

     变量声明的类型提示功能，包括类变量和实例变量

PEP 563(6) - 延迟的标注求值

     支持在运行时通过以字符串形式保存标注而非不是即求值来实现标注内部的
     向前引用。

   ---------- Footnotes ----------

   (1) (2) 作为函数体的第一条语句出现的字符串字面值会被转换为函数的
‘__doc__’ 属性，也就是该函数的 *note docstring: 15c5.。

   (2) https://www.python.org/dev/peps/pep-0570

   (3) https://www.python.org/dev/peps/pep-3107

   (4) https://www.python.org/dev/peps/pep-0484

   (5) https://www.python.org/dev/peps/pep-0526

   (6) https://www.python.org/dev/peps/pep-0563


File: python.info,  Node: 类定义,  Next: 协程<2>,  Prev: 函数定义,  Up: 复合语句

4.8.7 类定义
------------

类定义就是对类对象的定义 (参见 *note 标准类型层级结构: 1431. 一节):

     classdef    ::= [decorators] "class" classname [inheritance] ":" suite
     inheritance ::= "(" [argument_list] ")"
     classname   ::= identifier

类定义是一条可执行语句。 其中继承列表通常给出基类的列表 (进阶用法请参见
*note 元类: 1458.)，列表中的每一项都应当被求值为一个允许子类的类对象。 没
有继承列表的类默认继承自基类 *note object: 2b1.；因此，:

     class Foo:
         pass

等价于

     class Foo(object):
         pass

随后类体将在一个新的执行帧 (参见 *note 命名与绑定: 14af.) 中被执行，使用
新创建的局部命名空间和原有的全局命名空间。 （通常，类体主要包含函数定义
。） 当类体结束执行时，其执行帧将被丢弃而其局部命名空间会被保存。 (1) 一
个类对象随后会被创建，其基类使用给定的继承列表，属性字典使用保存的局部命
名空间。 类名称将在原有的全局命名空间中绑定到该类对象。

在类体内定义的属性的顺序保存在新类的 ‘__dict__’ 中。 请注意此顺序的可靠
性只限于类刚被创建时，并且只适用于使用定义语法所定义的类。

类的创建可使用 *note 元类: 1458. 进行重度定制。

类也可以被装饰：就像装饰函数一样，:

     @f1(arg)
     @f2
     class Foo: pass

大致等价于

     class Foo: pass
     Foo = f1(arg)(f2(Foo))

装饰器表达式的求值规则与函数装饰器相同。 结果随后会被绑定到类名称。

`程序员注意事项:' 在类定义内定义的变量是类属性；它们将被类实例所共享。 实
例属性可通过 ‘self.name = value’ 在方法中设定。 类和实例属性均可通过
"‘self.name’" 表示法来访问，当通过此方式访问时实例属性会隐藏同名的类属性
。 类属性可被用作实例属性的默认值，但在此场景下使用可变值可能导致未预期
的结果。 可以使用 *note 描述器: 4f1. 来创建具有不同实现细节的实例变量。

参见
....

PEP 3115(2) - Python 3000 中的元类

     将元类声明修改为当前语法的提议，以及关于如何构建带有元类的类的语义
     描述。

PEP 3129(3) - 类装饰器

     增加类装饰器的提议。 函数和方法装饰器是在 PEP 318(4) 中被引入的。

   ---------- Footnotes ----------

   (1) (3) 作为类体的第一条语句出现的字符串字面值会被转换为命名空间的
‘__doc__’ 条目，也就是该类的 *note docstring: 15c5.。

   (2) https://www.python.org/dev/peps/pep-3115

   (3) https://www.python.org/dev/peps/pep-3129

   (4) https://www.python.org/dev/peps/pep-0318


File: python.info,  Node: 协程<2>,  Prev: 类定义,  Up: 复合语句

4.8.8 协程
----------

3.5 新版功能.

* Menu:

* 协程函数定义::
* async for 语句::
* async with 语句::


File: python.info,  Node: 协程函数定义,  Next: async for 语句,  Up: 协程<2>

4.8.8.1 协程函数定义
....................

     async_funcdef ::= [decorators] "async" "def" funcname "(" [parameter_list] ")"
                       ["->" expression] ":" suite

Python 协程可以在多个位置上挂起和恢复执行 (参见 *note coroutine: 1a7.)。
在协程函数体内部，‘await’ 和 ‘async’ 标识符已成为保留关键字；*note
await: 1a4. 表达式，*note async for: 2e4. 以及 *note async with: 64c. 只
能在协程函数体中使用。

使用 ‘async def’ 语法定义的函数总是为协程函数，即使它们不包含 ‘await’ 或
‘async’ 关键字。

在协程函数体中使用 ‘yield from’ 表达式将引发 *note SyntaxError: 460.。

协程函数的例子:

     async def func(param1, param2):
         do_stuff()
         await some_coroutine()


File: python.info,  Node: async for 语句,  Next: async with 语句,  Prev: 协程函数定义,  Up: 协程<2>

4.8.8.2 ‘async for’ 语句
........................

     async_for_stmt ::= "async" for_stmt

*note asynchronous iterable: 649. 能够在其 `iter' 实现中调用异步代码，而
*note asynchronous iterator: 64e. 可以在其 `next' 方法中调用异步代码。

‘async for’ 语句允许方便地对异步迭代器进行迭代。

以下代码:

     async for TARGET in ITER:
         SUITE
     else:
         SUITE2

在语义上等价于:

     iter = (ITER)
     iter = type(iter).__aiter__(iter)
     running = True

     while running:
         try:
             TARGET = await type(iter).__anext__(iter)
         except StopAsyncIteration:
             running = False
         else:
             SUITE
     else:
         SUITE2

另请参阅 *note __aiter__(): 48f. 和 *note __anext__(): 14a5. 了解详情。

在协程函数体之外使用 ‘async for’ 语句将引发 *note SyntaxError: 460.。


File: python.info,  Node: async with 语句,  Prev: async for 语句,  Up: 协程<2>

4.8.8.3 ‘async with’ 语句
.........................

     async_with_stmt ::= "async" with_stmt

*note asynchronous context manager: 64a. 是一种 *note context manager:
571.，能够在其 `enter' 和 `exit' 方法中暂停执行。

以下代码:

     async with EXPRESSION as TARGET:
         SUITE

在语义上等价于:

     manager = (EXPRESSION)
     aexit = type(manager).__aexit__
     aenter = type(manager).__aenter__
     value = await aenter(manager)
     hit_except = False

     try:
         TARGET = value
         SUITE
     except:
         hit_except = True
         if not await aexit(manager, *sys.exc_info()):
             raise
     finally:
         if not hit_except:
             await aexit(manager, None, None, None)

另请参阅 *note __aenter__(): 14a8. 和 *note __aexit__(): 14a9. 了解详情
。

在协程函数体之外使用 ‘async with’ 语句将引发 *note SyntaxError: 460.。

参见
....

PEP 492(1) - 使用 async 和 await 语法实现协程

     将协程作为 Python 中的一个正式的单独概念，并增加相应的支持语法。

备注
....

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: 最高层级组件,  Next: 完整的语法规范,  Prev: 复合语句,  Up: Python语言参考

4.9 最高层级组件
================

Python 解释器可以从多种源获得输入：作为标准输入或程序参数传入的脚本，以
交互方式键入的语句，导入的模块源文件等等。 这一章将给出在这些情况下所用
的语法。

* Menu:

* 完整的 Python 程序::
* 文件输入::
* 交互式输入::
* 表达式输入::


File: python.info,  Node: 完整的 Python 程序,  Next: 文件输入,  Up: 最高层级组件

4.9.1 完整的 Python 程序
------------------------

虽然语言规范描述不必规定如何发起调用语言解释器，但对完整的 Python 程序加
以说明还是很有用的。 一个完整的 Python 程序会在最小初始化环境中被执行：
所有内置和标准模块均为可用，但均处于未初始化状态，只有 *note sys: fe. (各
种系统服务), *note builtins: 13. (内置函数、异常以及 ‘None’) 和 *note
__main__: 1. 除外。 最后一个模块用于为完整程序的执行提供局部和全局命名空
间。

适用于一个完整 Python 程序的语法即下节所描述的文件输入。

解释器也可以通过交互模式被发起调用；在此情况下，它并不读取和执行一个完整
程序，而是每次读取和执行一条语句（可能为复合语句）。 此时的初始环境与一
个完整程序的相同；每条语句会在 *note __main__: 1. 的命名空间中被执行。

一个完整程序可通过三种形式被传递给解释器：使用 *note -c: 121b. `字符串'
命令行选项，使用一个文件作为第一个命令行参数，或者使用标准输入。 如果文
件或标准输入是一个 tty 设置，解释器会进入交互模式；否则的话，它会将文件
当作一个完整程序来执行。


File: python.info,  Node: 文件输入,  Next: 交互式输入,  Prev: 完整的 Python 程序,  Up: 最高层级组件

4.9.2 文件输入
--------------

所有从非交互式文件读取的输入都具有相同的形式:

     file_input ::= (NEWLINE | statement)*

此语法用于下列几种情况:

   * 解析一个完整 Python 程序时（从文件或字符串）；

   * 解析一个模块时；

   * 解析一个传递给 *note exec(): c4c. 函数的字符串时；


File: python.info,  Node: 交互式输入,  Next: 表达式输入,  Prev: 文件输入,  Up: 最高层级组件

4.9.3 交互式输入
----------------

交互模式下的输入使用以下语法进行解析:

     interactive_input ::= [stmt_list] NEWLINE | compound_stmt NEWLINE

请注意在交互模式下一条（最高层级）复合语句必须带有一个空行；这对于帮助解
析器确定输入的结束是必须的。


File: python.info,  Node: 表达式输入,  Prev: 交互式输入,  Up: 最高层级组件

4.9.4 表达式输入
----------------

*note eval(): b98. 被用于表达式输入。 它会忽略开头的空白。 传递给 *note
eval(): b98. 的字符串参数必须具有以下形式:

     eval_input ::= expression_list NEWLINE*


File: python.info,  Node: 完整的语法规范,  Prev: 最高层级组件,  Up: Python语言参考

4.10 完整的语法规范
===================

这是完整的Python语法，它被送入解析器生成器，以生成解析Python源文件的解析
器：

     # Grammar for Python

     # NOTE WELL: You should also follow all the steps listed at
     # https://devguide.python.org/grammar/

     # Start symbols for the grammar:
     #       single_input is a single interactive statement;
     #       file_input is a module or sequence of commands read from an input file;
     #       eval_input is the input for the eval() functions.
     #       func_type_input is a PEP 484 Python 2 function type comment
     # NB: compound_stmt in single_input is followed by extra NEWLINE!
     # NB: due to the way TYPE_COMMENT is tokenized it will always be followed by a NEWLINE
     single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
     file_input: (NEWLINE | stmt)* ENDMARKER
     eval_input: testlist NEWLINE* ENDMARKER

     decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
     decorators: decorator+
     decorated: decorators (classdef | funcdef | async_funcdef)

     async_funcdef: ASYNC funcdef
     funcdef: 'def' NAME parameters ['->' test] ':' [TYPE_COMMENT] func_body_suite

     parameters: '(' [typedargslist] ')'

     # The following definition for typedarglist is equivalent to this set of rules:
     #
     #     arguments = argument (',' [TYPE_COMMENT] argument)*
     #     argument = tfpdef ['=' test]
     #     kwargs = '**' tfpdef [','] [TYPE_COMMENT]
     #     args = '*' [tfpdef]
     #     kwonly_kwargs = (',' [TYPE_COMMENT] argument)* (TYPE_COMMENT | [',' [TYPE_COMMENT] [kwargs]])
     #     args_kwonly_kwargs = args kwonly_kwargs | kwargs
     #     poskeyword_args_kwonly_kwargs = arguments ( TYPE_COMMENT | [',' [TYPE_COMMENT] [args_kwonly_kwargs]])
     #     typedargslist_no_posonly  = poskeyword_args_kwonly_kwargs | args_kwonly_kwargs
     #     typedarglist = (arguments ',' [TYPE_COMMENT] '/' [',' [[TYPE_COMMENT] typedargslist_no_posonly]])|(typedargslist_no_posonly)"
     #
     # It needs to be fully expanded to allow our LL(1) parser to work on it.

     typedargslist: (
       (tfpdef ['=' test] (',' [TYPE_COMMENT] tfpdef ['=' test])* ',' [TYPE_COMMENT] '/' [',' [ [TYPE_COMMENT] tfpdef ['=' test] (
             ',' [TYPE_COMMENT] tfpdef ['=' test])* (TYPE_COMMENT | [',' [TYPE_COMMENT] [
             '*' [tfpdef] (',' [TYPE_COMMENT] tfpdef ['=' test])* (TYPE_COMMENT | [',' [TYPE_COMMENT] ['**' tfpdef [','] [TYPE_COMMENT]]])
           | '**' tfpdef [','] [TYPE_COMMENT]]])
       | '*' [tfpdef] (',' [TYPE_COMMENT] tfpdef ['=' test])* (TYPE_COMMENT | [',' [TYPE_COMMENT] ['**' tfpdef [','] [TYPE_COMMENT]]])
       | '**' tfpdef [','] [TYPE_COMMENT]]] )
     |  (tfpdef ['=' test] (',' [TYPE_COMMENT] tfpdef ['=' test])* (TYPE_COMMENT | [',' [TYPE_COMMENT] [
        '*' [tfpdef] (',' [TYPE_COMMENT] tfpdef ['=' test])* (TYPE_COMMENT | [',' [TYPE_COMMENT] ['**' tfpdef [','] [TYPE_COMMENT]]])
       | '**' tfpdef [','] [TYPE_COMMENT]]])
       | '*' [tfpdef] (',' [TYPE_COMMENT] tfpdef ['=' test])* (TYPE_COMMENT | [',' [TYPE_COMMENT] ['**' tfpdef [','] [TYPE_COMMENT]]])
       | '**' tfpdef [','] [TYPE_COMMENT])
     )
     tfpdef: NAME [':' test]

     # The following definition for varargslist is equivalent to this set of rules:
     #
     #     arguments = argument (',' argument )*
     #     argument = vfpdef ['=' test]
     #     kwargs = '**' vfpdef [',']
     #     args = '*' [vfpdef]
     #     kwonly_kwargs = (',' argument )* [',' [kwargs]]
     #     args_kwonly_kwargs = args kwonly_kwargs | kwargs
     #     poskeyword_args_kwonly_kwargs = arguments [',' [args_kwonly_kwargs]]
     #     vararglist_no_posonly = poskeyword_args_kwonly_kwargs | args_kwonly_kwargs
     #     varargslist = arguments ',' '/' [','[(vararglist_no_posonly)]] | (vararglist_no_posonly)
     #
     # It needs to be fully expanded to allow our LL(1) parser to work on it.

     varargslist: vfpdef ['=' test ](',' vfpdef ['=' test])* ',' '/' [',' [ (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [
             '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
           | '**' vfpdef [',']]]
       | '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
       | '**' vfpdef [',']) ]] | (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [
             '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
           | '**' vfpdef [',']]]
       | '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
       | '**' vfpdef [',']
     )
     vfpdef: NAME

     stmt: simple_stmt | compound_stmt
     simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
     small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
                  import_stmt | global_stmt | nonlocal_stmt | assert_stmt)
     expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |
                          [('=' (yield_expr|testlist_star_expr))+ [TYPE_COMMENT]] )
     annassign: ':' test ['=' (yield_expr|testlist_star_expr)]
     testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']
     augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
                 '<<=' | '>>=' | '**=' | '//=')
     # For normal and annotated assignments, additional restrictions enforced by the interpreter
     del_stmt: 'del' exprlist
     pass_stmt: 'pass'
     flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
     break_stmt: 'break'
     continue_stmt: 'continue'
     return_stmt: 'return' [testlist_star_expr]
     yield_stmt: yield_expr
     raise_stmt: 'raise' [test ['from' test]]
     import_stmt: import_name | import_from
     import_name: 'import' dotted_as_names
     # note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS
     import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+)
                   'import' ('*' | '(' import_as_names ')' | import_as_names))
     import_as_name: NAME ['as' NAME]
     dotted_as_name: dotted_name ['as' NAME]
     import_as_names: import_as_name (',' import_as_name)* [',']
     dotted_as_names: dotted_as_name (',' dotted_as_name)*
     dotted_name: NAME ('.' NAME)*
     global_stmt: 'global' NAME (',' NAME)*
     nonlocal_stmt: 'nonlocal' NAME (',' NAME)*
     assert_stmt: 'assert' test [',' test]

     compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt
     async_stmt: ASYNC (funcdef | with_stmt | for_stmt)
     if_stmt: 'if' namedexpr_test ':' suite ('elif' namedexpr_test ':' suite)* ['else' ':' suite]
     while_stmt: 'while' namedexpr_test ':' suite ['else' ':' suite]
     for_stmt: 'for' exprlist 'in' testlist ':' [TYPE_COMMENT] suite ['else' ':' suite]
     try_stmt: ('try' ':' suite
                ((except_clause ':' suite)+
                 ['else' ':' suite]
                 ['finally' ':' suite] |
                'finally' ':' suite))
     with_stmt: 'with' with_item (',' with_item)*  ':' [TYPE_COMMENT] suite
     with_item: test ['as' expr]
     # NB compile.c makes sure that the default except clause is last
     except_clause: 'except' [test ['as' NAME]]
     suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT

     namedexpr_test: test [':=' test]
     test: or_test ['if' or_test 'else' test] | lambdef
     test_nocond: or_test | lambdef_nocond
     lambdef: 'lambda' [varargslist] ':' test
     lambdef_nocond: 'lambda' [varargslist] ':' test_nocond
     or_test: and_test ('or' and_test)*
     and_test: not_test ('and' not_test)*
     not_test: 'not' not_test | comparison
     comparison: expr (comp_op expr)*
     # <> isn't actually a valid comparison operator in Python. It's here for the
     # sake of a __future__ import described in PEP 401 (which really works :-)
     comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
     star_expr: '*' expr
     expr: xor_expr ('|' xor_expr)*
     xor_expr: and_expr ('^' and_expr)*
     and_expr: shift_expr ('&' shift_expr)*
     shift_expr: arith_expr (('<<'|'>>') arith_expr)*
     arith_expr: term (('+'|'-') term)*
     term: factor (('*'|'@'|'/'|'%'|'//') factor)*
     factor: ('+'|'-'|'~') factor | power
     power: atom_expr ['**' factor]
     atom_expr: [AWAIT] atom trailer*
     atom: ('(' [yield_expr|testlist_comp] ')' |
            '[' [testlist_comp] ']' |
            '{' [dictorsetmaker] '}' |
            NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')
     testlist_comp: (namedexpr_test|star_expr) ( comp_for | (',' (namedexpr_test|star_expr))* [','] )
     trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
     subscriptlist: subscript (',' subscript)* [',']
     subscript: test | [test] ':' [test] [sliceop]
     sliceop: ':' [test]
     exprlist: (expr|star_expr) (',' (expr|star_expr))* [',']
     testlist: test (',' test)* [',']
     dictorsetmaker: ( ((test ':' test | '**' expr)
                        (comp_for | (',' (test ':' test | '**' expr))* [','])) |
                       ((test | star_expr)
                        (comp_for | (',' (test | star_expr))* [','])) )

     classdef: 'class' NAME ['(' [arglist] ')'] ':' suite

     arglist: argument (',' argument)*  [',']

     # The reason that keywords are test nodes instead of NAME is that using NAME
     # results in an ambiguity. ast.c makes sure it's a NAME.
     # "test '=' test" is really "keyword '=' test", but we have no such token.
     # These need to be in a single rule to avoid grammar that is ambiguous
     # to our LL(1) parser. Even though 'test' includes '*expr' in star_expr,
     # we explicitly match '*' here, too, to give it proper precedence.
     # Illegal combinations and orderings are blocked in ast.c:
     # multiple (test comp_for) arguments are blocked; keyword unpackings
     # that precede iterable unpackings are blocked; etc.
     argument: ( test [comp_for] |
                 test ':=' test |
                 test '=' test |
                 '**' test |
                 '*' test )

     comp_iter: comp_for | comp_if
     sync_comp_for: 'for' exprlist 'in' or_test [comp_iter]
     comp_for: [ASYNC] sync_comp_for
     comp_if: 'if' test_nocond [comp_iter]

     # not used in grammar, but may appear in "node" passed from Parser to Compiler
     encoding_decl: NAME

     yield_expr: 'yield' [yield_arg]
     yield_arg: 'from' test | testlist_star_expr

     # the TYPE_COMMENT in suites is only parsed for funcdefs,
     # but can't go elsewhere due to ambiguity
     func_body_suite: simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] INDENT stmt+ DEDENT

     func_type_input: func_type NEWLINE* ENDMARKER
     func_type: '(' [typelist] ')' '->' test
     # typelist is a modified typedargslist (see above)
     typelist: (test (',' test)* [','
            ['*' [test] (',' test)* [',' '**' test] | '**' test]]
          |  '*' [test] (',' test)* [',' '**' test] | '**' test)


File: python.info,  Node: Python 标准库,  Next: 扩展和嵌入 Python 解释器,  Prev: Python语言参考,  Up: Top

5 Python 标准库
***************

*note Python语言参考: 120c. 描述了 Python 语言的具体语法和语义，这份库参
考则介绍了与 Python 一同发行的标准库。它还描述了通常包含在 Python 发行版
中的一些可选组件。

Python 标准库非常庞大，所提供的组件涉及范围十分广泛，正如以下内容目录所
显示的。这个库包含了多个内置模块 (以 C 编写)，Python 程序员必须依靠它们
来实现系统级功能，例如文件 I/O，此外还有大量以 Python 编写的模块，提供了
日常编程中许多问题的标准解决方案。其中有些模块经过专门设计，通过将特定平
台功能抽象化为平台中立的 API 来鼓励和加强 Python 程序的可移植性。

Windows 版本的 Python 安装程序通常包含整个标准库，往往还包含许多额外组件
。对于类 Unix 操作系统，Python 通常会分成一系列的软件包，因此可能需要使
用操作系统所提供的包管理工具来获取部分或全部可选组件。

在这个标准库以外还存在成千上万并且不断增加的其他组件 (从单独的程序、模块
、软件包直到完整的应用开发框架)，访问 Python 包索引(1) 即可获取这些第三
方包。

* Menu:

* 概述: 概述<6>.
* 内置函数::
* 内置常量::
* 内置类型::
* 内置异常::
* 文本处理服务::
* 二进制数据服务::
* 数据类型::
* 数字和数学模块::
* 函数式编程模块::
* 文件和目录访问::
* 数据持久化::
* 数据压缩和存档::
* 文件格式::
* 加密服务::
* 通用操作系统服务::
* 并发执行::
* 网络和进程间通信::
* 互联网数据处理::
* 结构化标记处理工具::
* 互联网协议和支持::
* 多媒体服务::
* 国际化::
* 程序框架::
* Tk图形用户界面(GUI): Tk图形用户界面 GUI.
* 开发工具::
* 调试和分析::
* 软件打包和分发::
* Python运行时服务::
* 自定义 Python 解释器::
* 导入模块::
* Python 语言服务::
* 杂项服务::
* Windows系统相关模块::
* Unix 专有服务::
* 被取代的模块::
* 未创建文档的模块::

   ---------- Footnotes ----------

   (1) https://pypi.org


File: python.info,  Node: 概述<6>,  Next: 内置函数,  Up: Python 标准库

5.1 概述
========

"Python 库"中包含了几种不同的组件。

它包含通常被视为语言“核心”中的一部分的数据类型，例如数字和列表。对于这些
类型，Python语言核心定义了文字的形式，并对它们的语义设置了一些约束，但没
有完全定义语义。（另一方面，语言核心确实定义了语法属性，如操作符的拼写和
优先级。）

这个库也包含了内置函数和异常 — 不需要 *note import: c25. 语句就可以在所
有Python代码中使用的对象。有一些是由语言核心定义的，但是许多对于核心语义
不是必需的，并且仅在这里描述。

不过这个库主要是由一系列的模块组成。这些模块集可以不同方式分类。有些模块
是用 C 编写并内置于 Python 解释器中；另一些模块则是用 Python 编写并以源
码形式导入。有些模块提供专用于 Python 的接口，例如打印栈追踪信息；有些模
块提供专用于特定操作系统的接口，例如操作特定的硬件；另一些模块则提供针对
特定应用领域的接口，例如万维网。有些模块在所有更新和移植版本的 Python 中
可用；另一些模块仅在底层系统支持或要求时可用；还有些模块则仅当编译和安装
Python 时选择了特定配置选项时才可用。

本手册以 "从内到外" 的顺序组织：首先描述内置函数、数据类型和异常，最后是
根据相关性进行分组的各种模块。

这意味着如果你从头开始阅读本手册，并在感到厌烦时跳到下一章，你仍能对
Python 库的可用模块和所支持的应用领域有个大致了解。当然，你并非 `必须' 如
同读小说一样从头读到尾 — 你也可以先浏览内容目录 (在手册开头)，或在索引
(在手册末尾) 中查找某个特定函数、模块或条目。最后，如果你喜欢随意学习某
个主题，你可以选择一个随机页码 (参见 *note random: dd. 模块) 并读上一两
小节。无论你想以怎样的顺序阅读本手册，还是建议先从 *note 内置函数: bfb.
这一章开始，因为本手册的其余内容都需要你熟悉其中的基本概念。

让我们开始吧！

* Menu:

* 可用性注释::


File: python.info,  Node: 可用性注释,  Up: 概述<6>

5.1.1 可用性注释
----------------

   * 如果出现“适用：Unix”注释，意味着相应函数通常存在于 Unix 系统中。 但
     这并不保证其存在于某个特定的操作系统中。

   * 如果没有单独说明，所有注明 “适用：Unix” 的函数都支持基于 Unix 核心
     构建的 Mac OS X 系统。


File: python.info,  Node: 内置函数,  Next: 内置常量,  Prev: 概述<6>,  Up: Python 标准库

5.2 内置函数
============

Python 解释器内置了很多函数和类型，您可以在任何时候使用它们。以下按字母
表顺序列出它们。

                                              内置函数
                                              
---------------------------------------------------------------------------------------------------------------------
                                                                                            
*note abs(): 12cf.      *note delattr(): 15e8.*note hash(): 9cc.     *note memoryview(): 15e9.*note set(): 15ea.
                                                                                            
                                                                                            
*note all(): d8d.       *note dict(): 15eb.   *note help(): 57b.     *note min(): 812.      *note setattr(): 15ec.
                                                                                            
                                                                                            
*note any(): d8c.       *note dir(): d3b.     *note hex(): c6e.      *note next(): 68b.     *note slice(): e0c.
                                                                                            
                                                                                            
*note ascii(): d54.     *note divmod(): 153.  *note id(): d8e.       *note object(): 2b1.   *note sorted(): 44c.
                                                                                            
                                                                                            
*note bin(): c48.       *note enumerate(): deb.*note input(): c73.   *note oct(): c6d.      *note staticmethod(): 1da.
                                                                                            
                                                                                            
*note bool(): 184.      *note eval(): b98.    *note int(): 185.      *note open(): 4f8.     *note str(): 15ed.
                                                                                            
                                                                                            
*note breakpoint(): 302.*note exec(): c4c.    *note isinstance(): 457.*note ord(): 1437.    *note sum(): 1e6.
                                                                                            
                                                                                            
*note bytearray(): 10ce.*note filter(): c36.  *note issubclass(): 458.*note pow(): 19b.     *note super(): 4eb.
                                                                                            
                                                                                            
*note bytes(): 10cd.    *note float(): 188.   *note iter(): d2f.     *note print(): 88f.    *note tuple(): 15ee.
                                                                                            
                                                                                            
*note callable(): b4c.  *note format(): 4e3.  *note len(): 151.      *note property(): 1d8. *note type(): 611.
                                                                                            
                                                                                            
*note chr(): 1438.      *note frozenset(): 15ef.*note list(): 15f0.  *note range(): 15f1.   *note vars(): 1047.
                                                                                            
                                                                                            
*note classmethod(): 1d9.*note getattr(): 451.*note locals(): 45d.   *note repr(): 7d5.     *note zip(): c3a.
                                                                                            
                                                                                            
*note compile(): 1b5.   *note globals(): 15f2.*note map(): c35.      *note reversed(): 18f. *note __import__(): 619.
                                                                                            
                                                                                            
*note complex(): 18a.   *note hasattr(): 450. *note max(): 813.      *note round(): c75.
                                                                     

 -- 函数: abs (x)

     返回一个数的绝对值。 参数可以是一个整数或浮点数。 如果参数是一个复
     数，则返回它的模。 如果 `x' 定义了 *note __abs__(): 148f.，则
     ‘abs(x)’ 将返回 ‘x.__abs__()’。

 -- 函数: all (iterable)

     如果 `iterable' 的所有元素均为真值（或可迭代对象为空）则返回 ‘True’
     。 等价于:

          def all(iterable):
              for element in iterable:
                  if not element:
                      return False
              return True

 -- 函数: any (iterable)

     如果 `iterable' 的任一元素为真值则返回 ‘True’。 如果可迭代对象为空
     ，返回 ‘False’。 等价于:

          def any(iterable):
              for element in iterable:
                  if element:
                      return True
              return False

 -- 函数: ascii (object)

     与 *note repr(): 7d5. 类似，返回一个包含对象的可打印表示形式的字符
     串，但是使用 ‘\x’、‘\u’ 和 ‘\U’ 对 *note repr(): 7d5. 返回的字符串
     中非 ASCII 编码的字符进行转义。 生成的字符串和 Python 2 的 *note
     repr(): 7d5. 返回的结果相似。

 -- 函数: bin (x)

     将一个整数转变为一个前缀为“0b”的二进制字符串。结果是一个合法的
     Python 表达式。如果 `x' 不是 Python 的 *note int: 185. 对象，那它需
     要定义 *note __index__(): 18b. 方法返回一个整数。一些例子：

          >>> bin(3)
          '0b11'
          >>> bin(-10)
          '-0b1010'

     如果不一定需要前缀“0b”，还可以使用如下的方法。

          >>> format(14, '#b'), format(14, 'b')
          ('0b1110', '1110')
          >>> f'{14:#b}', f'{14:b}'
          ('0b1110', '1110')

     另见 *note format(): 4e3. 获取更多信息。

 -- 类: bool ([x])

     返回一个布尔值，‘True’ 或者 ‘False’。 `x' 使用标准的 *note
     真值测试过程: 15f3. 来转换。如果 `x' 是假的或者被省略，返回
     ‘False’；其他情况返回 ‘True’。*note bool: 184. 类是 *note int: 185.
     的子类（参见 *note 数字类型 — int, float, complex: 122f.）。其他类
     不能继承自它。它只有 ‘False’ 和 ‘True’ 两个实例（参见 *note 布尔值:
     15f4.）。

     在 3.7 版更改: `x' 现在只能作为位置参数。

 -- 函数: breakpoint (*args, **kws)

     此函数会在调用时将你陷入调试器中。具体来说，它调用 *note
     sys.breakpointhook(): 31c. ，直接传递 ‘args’ 和 ‘kws’ 。默认情况下
     ， ‘sys.breakpointhook()’ 调用 *note pdb.set_trace(): 3ca. 且没有参
     数。在这种情况下，它纯粹是一个便利函数，因此您不必显式导入 *note
     pdb: ca. 且键入尽可能少的代码即可进入调试器。但是， *note
     sys.breakpointhook(): 31c. 可以设置为其他一些函数并被 *note
     breakpoint(): 302. 自动调用，以允许进入你想用的调试器。

     引发一个 *note 审计事件: ea1. ‘builtins.breakpoint’ 并附带参数
     ‘breakpointhook’。

     3.7 新版功能.

 -- 类: bytearray ([source[, encoding[, errors]]])

     返回一个新的 bytes 数组。 *note bytearray: 33b. 类是一个可变序列，
     包含范围为 0 <= x < 256 的整数。它有可变序列大部分常见的方法，见
     *note 可变序列类型: 15f5. 的描述；同时有 *note bytes: 33a. 类型的大
     部分方法，参见 *note bytes 和 bytearray 操作: 15f6.。

     可选形参 `source' 可以用不同的方式来初始化数组：

        * 如果是一个 `string'，您必须提供 `encoding' 参数（`errors' 参数
          仍是可选的）；*note bytearray(): 33b. 会使用 *note
          str.encode(): c3f. 方法来将 string 转变成 bytes。

        * 如果是一个 `integer'，会初始化大小为该数字的数组，并使用 null
          字节填充。

        * 如果是一个遵循 *note 缓冲区接口: 15f7. 的对象，该对象的只读缓
          冲区将被用来初始化字节数组。

        * 如果是一个 `iterable' 可迭代对象，它的元素的范围必须是 ‘0 <= x
          < 256’ 的整数，它会被用作数组的初始内容。

     如果没有实参，则创建大小为 0 的数组。

     另见 *note 二进制序列类型 — bytes, bytearray, memoryview: 15f8. 和
     *note bytearray 对象: 15f9.。

 -- 类: bytes ([source[, encoding[, errors]]])

     返回一个新的“bytes”对象， 是一个不可变序列，包含范围为 ‘0 <= x <
     256’ 的整数。*note bytes: 33a. 是 *note bytearray: 33b. 的不可变版
     本 - 它有其中不改变序列的方法和相同的索引、切片操作。

     因此，构造函数的实参和 *note bytearray(): 33b. 相同。

     字节对象还可以用字面值创建，参见 *note 字符串和字节串字面值: 13f3.。

     另见 *note 二进制序列类型 — bytes, bytearray, memoryview: 15f8.，
     *note bytes 对象: 15fa. 和 *note bytes 和 bytearray 操作: 15f6.。

 -- 函数: callable (object)

     如果参数 `object' 是可调用的就返回 *note True: 4a1.，否则返回 *note
     False: 390.。 如果返回 ‘True’，调用仍可能失败，但如果返回 ‘False’，
     则调用 `object' 将肯定不会成功。 请注意类是可调用的（调用类将返回一
     个新的实例）；如果实例所属的类有 *note __call__(): 143e. 则它就是可
     调用的。

     3.2 新版功能: 这个函数一开始在 Python 3.0 被移除了，但在 Python 3.2
     被重新加入。

 -- 函数: chr (i)

     返回 Unicode 码位为整数 `i' 的字符的字符串格式。例如，‘chr(97)’ 返
     回字符串 ‘'a'’，‘chr(8364)’ 返回字符串 ‘'€'’。这是 *note ord():
     1437. 的逆函数。

     实参的合法范围是 0 到 1,114,111（16 进制表示是 0x10FFFF）。如果 `i'
     超过这个范围，会触发 *note ValueError: 1fc. 异常。

 -- 函数: @classmethod

     把一个方法封装成类方法。

     一个类方法把类自己作为第一个实参，就像一个实例方法把实例自己作为第
     一个实参。请用以下习惯来声明类方法:

          class C:
              @classmethod
              def f(cls, arg1, arg2, ...): ...

     ‘@classmethod’ 这样的形式称为函数的 *note decorator: 284. – 详情参
     阅 *note 函数定义: 126c.。

     类方法的调用可以在类上进行 (例如 ‘C.f()’) 也可以在实例上进行 (例如
     ‘C().f()’)。 其所属类以外的类实例会被忽略。 如果类方法在其所属类的
     派生类上调用，则该派生类对象会被作为隐含的第一个参数被传入。

     类方法与 C++ 或 Java 中的静态方法不同。 如果你需要后者，请参阅
     *note staticmethod(): 1da.。

     想了解更多有关类方法的信息，请参阅 *note 标准类型层级结构: 1431. 。

 -- 函数: compile (source, filename, mode, flags=0, dont_inherit=False,
          optimize=-1)

     将 `source' 编译成代码或 AST 对象。代码对象可以被 *note exec():
     c4c. 或 *note eval(): b98. 执行。`source' 可以是常规的字符串、字节
     字符串，或者 AST 对象。参见 *note ast: 8. 模块的文档了解如何使用
     AST 对象。

     `filename' 实参需要是代码读取的文件名；如果代码不需要从文件中读取，
     可以传入一些可辨识的值（经常会使用 ‘'<string>'’）。

     `mode' 实参指定了编译代码必须用的模式。如果 `source' 是语句序列，可
     以是 ‘'exec'’；如果是单一表达式，可以是 ‘'eval'’；如果是单个交互式
     语句，可以是 ‘'single'’。（在最后一种情况下，如果表达式执行结果不是
     ‘None’ 将会被打印出来。）

     可选参数 `flags' 和 `dont_inherit' 控制在编译 `source' 时要用到哪个
     *note future 语句: 159d.。 如果两者都未提供（或都为零）则会使用调用
     *note compile(): 1b5. 的代码中有效的 future 语句来编译代码。 如果给
     出了 `flags' 参数但没有 `dont_inherit' (或是为零) 则 `flags' 参数所
     指定的 以及那些无论如何都有效的 future 语句会被使用。 如果
     `dont_inherit' 为一个非零整数，则只使用 `flags' 参数 – 在调用外围有
     效的 future 语句将被忽略。

     Future 语句使用比特位来指定，多个语句可以通过按位或来指定。具体特性
     的比特位可以通过 *note __future__: 0. 模块中的 ‘_Feature’ 类的实例
     的 ‘compiler_flag’ 属性来获得。

     可选参数 `flags' 还会控制是否允许编译的源码中包含最高层级 ‘await’,
     ‘async for’ 和 ‘async with’。 当设定了比特位
     ‘ast.PyCF_ALLOW_TOP_LEVEL_AWAIT’ 时，所返回代码对象在 ‘co_code’ 中
     设定了 ‘CO_COROUTINE’，并可通过 ‘await eval(code_object)’ 交互式地
     执行。

     `optimize' 实参指定编译器的优化级别；默认值 ‘-1’ 选择与解释器的
     *note -O: 694. 选项相同的优化级别。显式级别为 ‘0’ （没有优化；
     ‘__debug__’ 为真）、‘1’ （断言被删除， ‘__debug__’ 为假）或 ‘2’ （
     文档字符串也被删除）。

     如果编译的源码不合法，此函数会触发 *note SyntaxError: 460. 异常；如
     果源码包含 null 字节，则会触发 *note ValueError: 1fc. 异常。

     如果您想分析 Python 代码的 AST 表示，请参阅 *note ast.parse():
     1a2.。

     引发一个 *note 审计事件: ea1. ‘compile’ 附带参数 ‘source’,
     ‘filename’。

          注解: 在 ‘'single'’ 或 ‘'eval'’ 模式编译多行代码字符串时，输入
          必须以至少一个换行符结尾。 这使 *note code: 1b. 模块更容易检测
          语句的完整性。

          警告: 在将足够大或者足够复杂的字符串编译成 AST 对象时，Python
          解释器有可能因为 Python AST 编译器的栈深度限制而崩溃。

     在 3.2 版更改: 允许使用 Windows 和 Mac 的换行符。在 ‘'exec'’ 模式不
     再需要以换行符结尾。增加了 `optimize' 形参。

     在 3.5 版更改: 之前 `source' 中包含 null 字节的话会触发 *note
     TypeError: 193. 异常。

     3.8 新版功能: ‘ast.PyCF_ALLOW_TOP_LEVEL_AWAIT’ 现在可在旗标中传入以
     启用对最高层级 ‘await’, ‘async for’ 和 ‘async with’ 的支持。

 -- 类: complex ([real[, imag]])

     返回值为 `real' + `imag'*1j 的复数，或将字符串或数字转换为复数。如
     果第一个形参是字符串，则它被解释为一个复数，并且函数调用时必须没有
     第二个形参。第二个形参不能是字符串。每个实参都可以是任意的数值类型
     （包括复数）。如果省略了 `imag'，则默认值为零，构造函数会像 *note
     int: 185. 和 *note float: 188. 一样进行数值转换。如果两个实参都省略
     ，则返回 ‘0j’。

     对于一个普通 Python 对象 ‘x’，‘complex(x)’ 会委托给
     ‘x.__complex__()’。 如果 ‘__complex__()’ 未定义则将回退至 *note
     __float__(): 18d.。 如果 ‘__float__()’ 未定义则将回退至 *note
     __index__(): 18b.。

          注解: 当从字符串转换时，字符串在 ‘+’ 或 ‘-’ 的周围必须不能有空
          格。例如 ‘complex('1+2j')’ 是合法的，但 ‘complex('1 + 2j')’ 会
          触发 *note ValueError: 1fc. 异常。

     *note 数字类型 — int, float, complex: 122f. 描述了复数类型。

     在 3.6 版更改: 您可以使用下划线将代码文字中的数字进行分组。

     在 3.8 版更改: 如果 *note __complex__(): 18e. 和 *note __float__():
     18d. 未定义则回退至 *note __index__(): 18b.。

 -- 函数: delattr (object, name)

     *note setattr(): 15ec. 相关的函数。实参是一个对象和一个字符串。该字
     符串必须是对象的某个属性。如果对象允许，该函数将删除指定的属性。例
     如 ‘delattr(x, 'foobar')’ 等价于 ‘del x.foobar’ 。

 -- 类: dict (**kwarg)

 -- 类: dict (mapping, **kwarg)

 -- 类: dict (iterable, **kwarg)

     创建一个新的字典。*note dict: 1b9. 对象是一个字典类。参见 *note
     dict: 1b9. 和 *note 映射类型 — dict: 305. 了解这个类。

     其他容器类型，请参见内置的 *note list: 263.、*note set: b77. 和
     *note tuple: 486. 类，以及 *note collections: 1e. 模块。

 -- 函数: dir ([object])

     如果没有实参，则返回当前本地作用域中的名称列表。如果有实参，它会尝
     试返回该对象的有效属性列表。

     如果对象有一个名为 *note __dir__(): 324. 的方法，那么该方法将被调用
     ，并且必须返回一个属性列表。这允许实现自定义 *note __getattr__():
     323. 或 *note __getattribute__(): 44f. 函数的对象能够自定义 *note
     dir(): d3b. 来报告它们的属性。

     如果对象不提供 *note __dir__(): 324.，这个函数会尝试从对象已定义的
     *note __dict__: 504. 属性和类型对象收集信息。结果列表并不总是完整的
     ，如果对象有自定义 *note __getattr__(): 323.，那结果可能不准确。

     默认的 *note dir(): d3b. 机制对不同类型的对象行为不同，它会试图返回
     最相关而不是最全的信息：

        * 如果对象是模块对象，则列表包含模块的属性名称。

        * 如果对象是类型或类对象，则列表包含它们的属性名称，并且递归查找
          所有基类的属性。

        * 否则，列表包含对象的属性名称，它的类属性名称，并且递归查找它的
          类的所有基类的属性。

     返回的列表按字母表排序。例如：

          >>> import struct
          >>> dir()   # show the names in the module namespace
          ['__builtins__', '__name__', 'struct']
          >>> dir(struct)   # show the names in the struct module
          ['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
           '__initializing__', '__loader__', '__name__', '__package__',
           '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
           'unpack', 'unpack_from']
          >>> class Shape:
          ...     def __dir__(self):
          ...         return ['area', 'perimeter', 'location']
          >>> s = Shape()
          >>> dir(s)
          ['area', 'location', 'perimeter']

          注解: 因为 *note dir(): d3b. 主要是为了便于在交互式时使用，所
          以它会试图返回人们感兴趣的名字集合，而不是试图保证结果的严格性
          或一致性，它具体的行为也可能在不同版本之间改变。例如，当实参是
          一个类时，metaclass 的属性不包含在结果列表中。

 -- 函数: divmod (a, b)

     它将两个（非复数）数字作为实参，并在执行整数除法时返回一对商和余数
     。对于混合操作数类型，适用双目算术运算符的规则。对于整数，结果和
     ‘(a // b, a % b)’ 一致。对于浮点数，结果是 ‘(q, a % b)’ ，`q' 通常
     是 ‘math.floor(a / b)’ 但可能会比 1 小。在任何情况下， ‘q * b + a %
     b’ 和 `a' 基本相等；如果 ‘a % b’ 非零，它的符号和 `b' 一样，并且 ‘0
     <= abs(a % b) < abs(b)’ 。

 -- 函数: enumerate (iterable, start=0)

     返回一个枚举对象。`iterable' 必须是一个序列，或 *note iterator:
     104b.，或其他支持迭代的对象。 *note enumerate(): deb. 返回的迭代器
     的 *note __next__(): c6c. 方法返回一个元组，里面包含一个计数值（从
     `start' 开始，默认为 0）和通过迭代 `iterable' 获得的值。

          >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
          >>> list(enumerate(seasons))
          [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
          >>> list(enumerate(seasons, start=1))
          [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

     等价于:

          def enumerate(sequence, start=0):
              n = start
              for elem in sequence:
                  yield n, elem
                  n += 1

 -- 函数: eval (expression[, globals[, locals]])

     实参是一个字符串，以及可选的 globals 和 locals。`globals' 实参必须
     是一个字典。`locals' 可以是任何映射对象。

     `expression' 参数会作为一个 Python 表达式（从技术上说是一个条件列表
     ）被解析并求值，并使用 `globals' 和 `locals' 字典作为全局和局部命名
     空间。 如果 `globals' 字典存在且不包含以 ‘__builtins__’ 为键的值，
     则会在解析 `expression' 之前插入以此为键的对内置模块 *note
     builtins: 13. 的引用。 这意味着 `expression' 通常具有对标准 *note
     builtins: 13. 模块的完全访问权限且受限的环境会被传播。 如果省略
     `locals' 字典则其默认值为 `globals' 字典。 如果两个字典同时省略，则
     表达式执行时会使用 *note eval(): b98. 被调用的环境中的 `globals' 和
     `locals'。 请注意，`eval()' 并没有对外围环境下的 (非局部) *note
     嵌套作用域: 15fb. 的访问权限。

     返回值就是表达式的求值结果。 语法错误将作为异常被报告。 例如：

          >>> x = 1
          >>> eval('x+1')
          2

     这个函数也可以用来执行任何代码对象（如 *note compile(): 1b5. 创建的
     ）。这种情况下，参数是代码对象，而不是字符串。如果编译该对象时的
     `mode' 实参是 ‘'exec'’ 那么 *note eval(): b98. 返回值为 ‘None’ 。

     提示： *note exec(): c4c. 函数支持动态执行语句。 *note globals():
     15f2. 和 *note locals(): 45d. 函数各自返回当前的全局和本地字典，因
     此您可以将它们传递给 *note eval(): b98. 或 *note exec(): c4c. 来使
     用。

     另外可以参阅 *note ast.literal_eval(): 4ad.，该函数可以安全执行仅包
     含文字的表达式字符串。

     引发一个 *note 审计事件: ea1. ‘exec’ 附带参数 ‘code_object’。

 -- 函数: exec (object[, globals[, locals]])

     这个函数支持动态执行 Python 代码。 `object' 必须是字符串或者代码对
     象。 如果是字符串，那么该字符串将被解析为一系列 Python 语句并执行（
     除非发生语法错误）。 (1) 如果是代码对象，它将被直接执行。 在任何情
     况下，被执行的代码都应当是有效的文件输入（见参考手册中的“文件输入
     ”一节）。 请注意即使在传递给 *note exec(): c4c. 函数的代码的上下文
     中，*note nonlocal: c47, *note yield: 190. 和 *note return: 191. 语
     句也不能在函数定义以外使用。 该函数的返回值是 ‘None’。

     无论哪种情况，如果省略了可选项，代码将在当前作用域内执行。 如果只提
     供了 `globals'，则它必须是一个字典（不能是字典的子类），该字典将同
     时被用于全局和局部变量。 如果同时提供了 `globals' 和 `locals'，它们
     会分别被用于全局和局部变量。 如果提供了 `locals'，则它可以是任何映
     射对象。 请记住在模块层级上，globals 和 locals 是同一个字典。 如果
     exec 得到两个单独对象作为 `globals' 和 `locals'，则代码将如同嵌入类
     定义的情况一样执行。

     如果 `globals' 字典不包含 ‘__builtins__’ 键值，则将为该键插入对内建
     *note builtins: 13. 模块字典的引用。因此，在将执行的代码传递给
     *note exec(): c4c. 之前，可以通过将自己的 ‘__builtins__’ 字典插入到
     `globals' 中来控制可以使用哪些内置代码。

     引发一个 *note 审计事件: ea1. ‘exec’ 附带参数 ‘code_object’。

          注解: 内置 *note globals(): 15f2. 和 *note locals(): 45d. 函数
          各自返回当前的全局和本地字典，因此可以将它们传递给 *note
          exec(): c4c. 的第二个和第三个实参。

          注解: 默认情况下，`locals' 的行为如下面 *note locals(): 45d. 函
          数描述的一样：不要试图改变默认的 `locals' 字典。如果您想在
          *note exec(): c4c. 函数返回时知道代码对 `locals' 的变动，请明
          确地传递 `locals' 字典。

 -- 函数: filter (function, iterable)

     用 `iterable' 中函数 `function' 返回真的那些元素，构建一个新的迭代
     器。`iterable' 可以是一个序列，一个支持迭代的容器，或一个迭代器。如
     果 `function' 是 ‘None’ ，则会假设它是一个身份函数，即 `iterable' 中
     所有返回假的元素会被移除。

     请注意， ‘filter(function, iterable)’ 相当于一个生成器表达式，当
     function 不是 ‘None’ 的时候为 ‘(item for item in iterable if
     function(item))’；function 是 ‘None’ 的时候为 ‘(item for item in
     iterable if item)’ 。

     请参阅 *note itertools.filterfalse(): 15fc. 了解，只有 `function' 返
     回 false 时才选取 `iterable' 中元素的补充函数。

 -- 类: float ([x])

     返回从数字或字符串 `x' 生成的浮点数。

     如果实参是字符串，则它必须是包含十进制数字的字符串，字符串前面可以
     有符号，之前也可以有空格。可选的符号有 ‘'+'’ 和 ‘'-'’ ； ‘'+'’ 对创
     建的值没有影响。实参也可以是 NaN（非数字）、正负无穷大的字符串。确
     切地说，除去首尾的空格后，输入必须遵循以下语法：

          sign           ::= "+" | "-"
          infinity       ::= "Infinity" | "inf"
          nan            ::= "nan"
          numeric_value  ::= floatnumber | infinity | nan
          numeric_string ::= [sign] numeric_value

     这里， ‘floatnumber’ 是 Python 浮点数的字符串形式，详见 *note
     浮点数字面值: 141d.。字母大小写都可以，例如，“inf”、“Inf”、
     “INFINITY”、“iNfINity” 都可以表示正无穷大。

     另一方面，如果实参是整数或浮点数，则返回具有相同值（在 Python 浮点
     精度范围内）的浮点数。如果实参在 Python 浮点精度范围外，则会触发
     *note OverflowError: 968.。

     对于一个普通 Python 对象 ‘x’，‘float(x)’ 会委托给 ‘x.__float__()’。
     如果 ‘__float__()’ 未定义则将回退至 *note __index__(): 18b.。

     如果没有实参，则返回 ‘0.0’ 。

     示例:

          >>> float('+1.23')
          1.23
          >>> float('   -12345\n')
          -12345.0
          >>> float('1e-003')
          0.001
          >>> float('+1E6')
          1000000.0
          >>> float('-Infinity')
          -inf

     *note 数字类型 — int, float, complex: 122f. 描述了浮点类型。

     在 3.6 版更改: 您可以使用下划线将代码文字中的数字进行分组。

     在 3.7 版更改: `x' 现在只能作为位置参数。

     在 3.8 版更改: 如果 *note __float__(): 18d. 未定义则回退至 *note
     __index__(): 18b.。

 -- 函数: format (value[, format_spec])

     将 `value' 转换为 `format_spec' 控制的“格式化”表示。`format_spec' 的
     解释取决于 `value' 实参的类型，但是大多数内置类型使用标准格式化语法
     ：*note 格式规格迷你语言: 4e6.。

     默认的 `format_spec' 是一个空字符串，它通常给出与调用 *note
     str(value): 339. 相同的结果。

     调用 ‘format(value, format_spec)’ 会转换成
     ‘type(value).__format__(value, format_spec)’ ，所以实例字典中的
     *note __format__(): 956. 方法将不会调用。如果方法搜索回退到 *note
     object: 2b1. 类但 `format_spec' 不为空，或者如果 `format_spec' 或返
     回值不是字符串，则会触发 *note TypeError: 193. 异常。

     在 3.4 版更改: 当 `format_spec' 不是空字符串时，
     ‘object().__format__(format_spec)’ 会触发 *note TypeError: 193.。

 -- 类: frozenset ([iterable])

     返回一个新的 *note frozenset: bf6. 对象，它包含可选参数 `iterable'
     中的元素。 ‘frozenset’ 是一个内置的类。有关此类的文档，请参阅 *note
     frozenset: bf6. 和 *note 集合类型 — set, frozenset: 1602.。

     请参阅内建的 *note set: b77.、*note list: 263.、*note tuple: 486. 和
     *note dict: 1b9. 类，以及 *note collections: 1e. 模块来了解其它的容
     器。

 -- 函数: getattr (object, name[, default])

     返回对象命名属性的值。`name' 必须是字符串。如果该字符串是对象的属性
     之一，则返回该属性的值。例如， ‘getattr(x, 'foobar')’ 等同于
     ‘x.foobar’。如果指定的属性不存在，且提供了 `default' 值，则返回它，
     否则触发 *note AttributeError: 3a3.。

 -- 函数: globals ()

     返回表示当前全局符号表的字典。这总是当前模块的字典（在函数或方法中
     ，不是调用它的模块，而是定义它的模块）。

 -- 函数: hasattr (object, name)

     该实参是一个对象和一个字符串。如果字符串是对象的属性之一的名称，则
     返回 ‘True’，否则返回 ‘False’。（此功能是通过调用 ‘getattr(object,
     name)’ 看是否有 *note AttributeError: 3a3. 异常来实现的。）

 -- 函数: hash (object)

     返回该对象的哈希值（如果它有的话）。哈希值是整数。它们在字典查找元
     素时用来快速比较字典的键。相同大小的数字变量有相同的哈希值（即使它
     们类型不同，如 1 和 1.0）。

          注解: 如果对象实现了自己的 *note __hash__(): 349. 方法，请注意
          ，*note hash(): 9cc. 根据机器的字长来截断返回值。另请参阅
          *note __hash__(): 349.。

 -- 函数: help ([object])

     启动内置的帮助系统（此函数主要在交互式中使用）。如果没有实参，解释
     器控制台里会启动交互式帮助系统。如果实参是一个字符串，则在模块、函
     数、类、方法、关键字或文档主题中搜索该字符串，并在控制台上打印帮助
     信息。如果实参是其他任意对象，则会生成该对象的帮助页。

     请注意如果在函数的形参列表中出现了斜杠 (/)，则它在发起调用 *note
     help(): 57b. 的时候意味着斜杠之前的均为仅限位置形参。 更多相关信息
     ，请参阅 *note 有关仅限位置形参的 FAQ 条目: 1603.。

     该函数通过 *note site: ec. 模块加入到内置命名空间。

     在 3.4 版更改: *note pydoc: da. 和 *note inspect: a1. 的变更使得可
     调用对象的签名信息更加全面和一致。

 -- 函数: hex (x)

     将整数转换为以“0x”为前缀的小写十六进制字符串。如果 `x' 不是 Python
     *note int: 185. 对象，则必须定义返回整数的 *note __index__(): 18b.
     方法。一些例子：

          >>> hex(255)
          '0xff'
          >>> hex(-42)
          '-0x2a'

     如果要将整数转换为大写或小写的十六进制字符串，并可选择有无“0x”前缀
     ，则可以使用如下方法：

          >>> '%#x' % 255, '%x' % 255, '%X' % 255
          ('0xff', 'ff', 'FF')
          >>> format(255, '#x'), format(255, 'x'), format(255, 'X')
          ('0xff', 'ff', 'FF')
          >>> f'{255:#x}', f'{255:x}', f'{255:X}'
          ('0xff', 'ff', 'FF')

     另见 *note format(): 4e3. 获取更多信息。

     另请参阅 *note int(): 185. 将十六进制字符串转换为以 16 为基数的整数
     。

          注解: 如果要获取浮点数的十六进制字符串形式，请使用 *note
          float.hex(): 1334. 方法。

 -- 函数: id (object)

     返回对象的“标识值”。该值是一个整数，在此对象的生命周期中保证是唯一
     且恒定的。两个生命期不重叠的对象可能具有相同的 *note id(): d8e. 值
     。

     `CPython implementation detail:' This is the address of the object
     in memory.

     引发一个 *note 审计事件: ea1. ‘builtins.id’，附带参数 ‘id’。

 -- 函数: input ([prompt])

     如果存在 `prompt' 实参，则将其写入标准输出，末尾不带换行符。接下来
     ，该函数从输入中读取一行，将其转换为字符串（除了末尾的换行符）并返
     回。当读取到 EOF 时，则触发 *note EOFError: c74.。例如:

          >>> s = input('--> ')
          --> Monty Python's Flying Circus
          >>> s
          "Monty Python's Flying Circus"

     如果加载了 *note readline: df. 模块，*note input(): c73. 将使用它来
     提供复杂的行编辑和历史记录功能。

     引发一个 *note 审计事件: ea1. ‘builtins.input’ 附带参数 ‘prompt’。

     在成功读取输入之后引发一个审计事件 ‘builtins.input/result’ 附带结果
     。

 -- 类: int ([x])

 -- 类: int (x, base=10)

     返回一个基于数字或字符串 `x' 构造的整数对象，或者在未给出参数时返回
     ‘0’。 如果 `x' 定义了 *note __int__(): 18c.，‘int(x)’ 将返回
     ‘x.__int__()’。 如果 `x' 定义了 *note __index__(): 18b.，它将返回
     ‘x.__index__()’。 如果 `x' 定义了 *note __trunc__(): 1493.，它将返
     回 ‘x.__trunc__()’。 对于浮点数，它将向零舍入。

     如果 `x' 不是数字，或者有 `base' 参数，`x' 必须是字符串、*note
     bytes: 33a.、表示进制为 `base' 的 *note 整数字面值: 1412. 的 *note
     bytearray: 33b. 实例。该文字前可以有 ‘+’ 或 ‘-’ （中间不能有空格）
     ，前后可以有空格。一个进制为 n 的数字包含 0 到 n-1 的数，其中 ‘a’ 到
     ‘z’ （或 ‘A’ 到 ‘Z’ ）表示 10 到 35。默认的 `base' 为 10 ，允许的进
     制有 0、2-36。2、8、16 进制的数字可以在代码中用 ‘0b’/‘0B’ 、
     ‘0o’/‘0O’ 、 ‘0x’/‘0X’ 前缀来表示。进制为 0 将安照代码的字面量来精
     确解释，最后的结果会是 2、8、10、16 进制中的一个。所以 ‘int('010',
     0)’ 是非法的，但 ‘int('010')’ 和 ‘int('010', 8)’ 是合法的。

     整数类型定义请参阅 *note 数字类型 — int, float, complex: 122f. 。

     在 3.4 版更改: 如果 `base' 不是 *note int: 185. 的实例，但 `base' 对
     象有 *note base.__index__: 18b. 方法，则会调用该方法来获取进制数。
     以前的版本使用 *note base.__int__: 18c. 而不是 *note
     base.__index__: 18b.。

     在 3.6 版更改: 您可以使用下划线将代码文字中的数字进行分组。

     在 3.7 版更改: `x' 现在只能作为位置参数。

     在 3.8 版更改: 如果 *note __int__(): 18c. 未定义则回退至 *note
     __index__(): 18b.。

 -- 函数: isinstance (object, classinfo)

     如果参数 `object' 是参数 `classinfo' 的实例或者是其 (直接、间接或
     *note 虚拟: b3b.) 子类则返回 ‘True’。 如果 `object' 不是给定类型的
     对象，函数将总是返回 ‘False’。 如果 `classinfo' 是类型对象元组（或
     由其他此类元组递归组成的元组），那么如果 `object' 是其中任何一个类
     型的实例就返回 ‘True’。 如果 `classinfo' 既不是类型，也不是类型元组
     或类型元组的元组，则将引发 *note TypeError: 193. 异常。

 -- 函数: issubclass (class, classinfo)

     如果 `class' 是 `classinfo' 的 (直接、间接或 *note 虚拟: b3b.) 子类
     则返回 ‘True’。 类会被视作其自身的子类。 `classinfo' 也以是类对象的
     元组，在此情况下 `classinfo' 中的每个条目都将被检查。 在任何其他情
     况下，都将引发 *note TypeError: 193. 异常。

 -- 函数: iter (object[, sentinel])

     返回一个 *note iterator: 104b. 对象。根据是否存在第二个实参，第一个
     实参的解释是非常不同的。如果没有第二个实参，`object' 必须是支持迭代
     协议（有 *note __iter__(): 517. 方法）的集合对象，或必须支持序列协
     议（有 *note __getitem__(): 280. 方法，且数字参数从 ‘0’ 开始）。如
     果它不支持这些协议，会触发 *note TypeError: 193.。如果有第二个实参
     `sentinel'，那么 `object' 必须是可调用的对象。这种情况下生成的迭代
     器，每次迭代调用它的 *note __next__(): c6c. 方法时都会不带实参地调
     用 `object'；如果返回的结果是 `sentinel' 则触发 *note
     StopIteration: 48e.，否则返回调用结果。

     另请参阅 *note 迭代器类型: 146c.。

     适合 *note iter(): d2f. 的第二种形式的应用之一是构建块读取器。 例如
     ，从二进制数据库文件中读取固定宽度的块，直至到达文件的末尾:

          from functools import partial
          with open('mydata.db', 'rb') as f:
              for block in iter(partial(f.read, 64), b''):
                  process_block(block)

 -- 函数: len (s)

     返回对象的长度（元素个数）。实参可以是序列（如 string、bytes、
     tuple、list 或 range 等）或集合（如 dictionary、set 或 frozen set 等
     ）。

 -- 类: list ([iterable])

     虽然被称为函数，*note list: 263. 实际上是一种可变序列类型，详情请参
     阅 *note 列表: 1604. 和 *note 序列类型 — list, tuple, range: 1280.。

 -- 函数: locals ()

     更新并返回表示当前本地符号表的字典。 在函数代码块但不是类代码块中调
     用 *note locals(): 45d. 时将返回自由变量。 请注意在模块层级上，
     *note locals(): 45d. 和 *note globals(): 15f2. 是同一个字典。

          注解: 不要更改此字典的内容；更改不会影响解释器使用的局部变量或
          自由变量的值。

 -- 函数: map (function, iterable, ...)

     返回一个将 `function' 应用于 `iterable' 中每一项并输出其结果的迭代
     器。 如果传入了额外的 `iterable' 参数，`function' 必须接受相同个数
     的实参并被应用于从所有可迭代对象中并行获取的项。 当有多个可迭代对象
     时，最短的可迭代对象耗尽则整个迭代就将结束。 对于函数的输入已经是参
     数元组的情况，请参阅 *note itertools.starmap(): a30.。

 -- 函数: max (iterable, *[, key, default])

 -- 函数: max (arg1, arg2, *args[, key])

     返回可迭代对象中最大的元素，或者返回两个及以上实参中最大的。

     如果只提供了一个位置参数，它必须是非空 *note iterable: bb4.，返回可
     迭代对象中最大的元素；如果提供了两个及以上的位置参数，则返回最大的
     位置参数。

     有两个可选只能用关键字的实参。`key' 实参指定排序函数用的参数，如传
     给 *note list.sort(): 44d. 的。`default' 实参是当可迭代对象为空时返
     回的值。如果可迭代对象为空，并且没有给 `default' ，则会触发 *note
     ValueError: 1fc.。

     如果有多个最大元素，则此函数将返回第一个找到的。这和其他稳定排序工
     具如 ‘sorted(iterable, key=keyfunc, reverse=True)[0]’ 和
     ‘heapq.nlargest(1, iterable, key=keyfunc)’ 保持一致。

     3.4 新版功能: keyword-only 实参 `default' 。

     在 3.8 版更改: `key' 可以为 ‘None’。

 -- 类: memoryview (obj)

     返回由给定实参创建的“内存视图”对象。有关详细信息，请参阅 *note
     内存视图: 1605.。

 -- 函数: min (iterable, *[, key, default])

 -- 函数: min (arg1, arg2, *args[, key])

     返回可迭代对象中最小的元素，或者返回两个及以上实参中最小的。

     如果只提供了一个位置参数，它必须是 *note iterable: bb4.，返回可迭代
     对象中最小的元素；如果提供了两个及以上的位置参数，则返回最小的位置
     参数。

     有两个可选只能用关键字的实参。`key' 实参指定排序函数用的参数，如传
     给 *note list.sort(): 44d. 的。`default' 实参是当可迭代对象为空时返
     回的值。如果可迭代对象为空，并且没有给 `default' ，则会触发 *note
     ValueError: 1fc.。

     如果有多个最小元素，则此函数将返回第一个找到的。这和其他稳定排序工
     具如 ‘sorted(iterable, key=keyfunc)[0]’ 和 ‘heapq.nsmallest(1,
     iterable, key=keyfunc)’ 保持一致。

     3.4 新版功能: keyword-only 实参 `default' 。

     在 3.8 版更改: `key' 可以为 ‘None’。

 -- 函数: next (iterator[, default])

     通过调用 `iterator' 的 *note __next__(): c6c. 方法获取下一个元素。
     如果迭代器耗尽，则返回给定的 `default'，如果没有默认值则触发 *note
     StopIteration: 48e.。

 -- 类: object

     返回一个没有特征的新对象。*note object: 2b1. 是所有类的基类。它具有
     所有 Python 类实例的通用方法。这个函数不接受任何实参。

          注解: 由于 *note object: 2b1. 没有 *note __dict__: 504.，因此
          无法将任意属性赋给 *note object: 2b1. 的实例。

 -- 函数: oct (x)

     将一个整数转变为一个前缀为“0o”的八进制字符串。结果是一个合法的
     Python 表达式。如果 `x' 不是 Python 的 *note int: 185. 对象，那它需
     要定义 *note __index__(): 18b. 方法返回一个整数。一些例子：

          >>> oct(8)
          '0o10'
          >>> oct(-56)
          '-0o70'

     如果要将整数转换为八进制字符串，并可选择有无“0o”前缀，则可以使用如
     下方法：

          >>> '%#o' % 10, '%o' % 10
          ('0o12', '12')
          >>> format(10, '#o'), format(10, 'o')
          ('0o12', '12')
          >>> f'{10:#o}', f'{10:o}'
          ('0o12', '12')

     另见 *note format(): 4e3. 获取更多信息。

 -- 函数: open (file, mode='r', buffering=-1, encoding=None,
          errors=None, newline=None, closefd=True, opener=None)

     打开 `file' 并返回对应的 *note file object: b4a.。 如果该文件不能被
     打开，则引发 *note OSError: 1d4.。 请参阅 *note 读写文件: 12b0. 获
     取此函数的更多用法示例。

     `file' 是一个 *note path-like object: 373.，表示将要打开的文件的路
     径（绝对路径或者当前工作目录的相对路径），也可以是要被封装的整数类
     型文件描述符。（如果是文件描述符，它会随着返回的 I/O 对象关闭而关闭
     ，除非 `closefd' 被设为 ‘False’ 。）

     `mode' 是一个可选字符串，用于指定打开文件的模式。默认值是 ‘'r'’ ，
     这意味着它以文本模式打开并读取。其他常见模式有：写入 ‘'w'’ （截断已
     经存在的文件）；排它性创建 ‘'x'’ ；追加写 ‘'a'’ （在 `一些' Unix 系
     统上，无论当前的文件指针在什么位置，`所有' 写入都会追加到文件末尾）
     。在文本模式，如果 `encoding' 没有指定，则根据平台来决定使用的编码
     ：使用 ‘locale.getpreferredencoding(False)’ 来获取本地编码。（要读
     取和写入原始字节，请使用二进制模式并不要指定 `encoding'。）可用的模
     式有：

     字符          含义
                   
     ----------------------------------------------------------------------------------
                   
     ‘'r'’         读取（默认）
                   
                   
     ‘'w'’         写入，并先截断文件
                   
                   
     ‘'x'’         排它性创建，如果文件已存在则失败
                   
                   
     ‘'a'’         写入，如果文件存在则在末尾追加
                   
                   
     ‘'b'’         二进制模式
                   
                   
     ‘'t'’         文本模式（默认）
                   
                   
     ‘'+'’         打开用于更新（读取与写入）
                   

     默认模式为 ‘'r'’ (打开用于读取文本，与 ‘'rt'’ 同义)。 模式 ‘'w+'’ 与
     ‘'w+b'’ 将打开文件并清空内容。 模式 ‘'r+'’ 与 ‘'r+b'’ 将打开文件并
     不清空内容。

     正如在 *note 概述: 1607. 中提到的，Python区分二进制和文本I/O。以二
     进制模式打开的文件（包括 `mode' 参数中的 ‘'b'’ ）返回的内容为
     ‘bytes`对象，不进行任何解码。在文本模式下（默认情况下，或者在
     *mode* 参数中包含 `’’t’‘ ）时，文件内容返回为 *note str: 339. ，首
     先使用指定的 `encoding' （如果给定）或者使用平台默认的的字节编码解
     码。

     此外还允许使用一个模式字符 ‘'U'’，该字符已不再具有任何效果，并被视
     为已弃用。 之前它会在文本模式中启用 *note universal newlines: 5fd.，
     这在 Python 3.0 中成为默认行为。 请参阅 *note newline: 1608. 形参的
     文档了解更多细节。

          注解: Python不依赖于底层操作系统的文本文件概念;所有处理都由
          Python本身完成，因此与平台无关。

     `buffering' 是一个可选的整数，用于设置缓冲策略。传递0以切换缓冲关闭
     （仅允许在二进制模式下），1选择行缓冲（仅在文本模式下可用），并且
     >1的整数以指示固定大小的块缓冲区的大小（以字节为单位）。如果没有给
     出 `buffering' 参数，则默认缓冲策略的工作方式如下:

        * 二进制文件以固定大小的块进行缓冲；使用启发式方法选择缓冲区的大
          小，尝试确定底层设备的“块大小”或使用 *note
          io.DEFAULT_BUFFER_SIZE: 1609.。在许多系统上，缓冲区的长度通常
          为4096或8192字节。

        * “交互式”文本文件（ *note isatty(): 160a. 返回 ‘True’ 的文件）
          使用行缓冲。其他文本文件使用上述策略用于二进制文件。

     `encoding' 是用于解码或编码文件的编码的名称。这应该只在文本模式下使
     用。默认编码是依赖于平台的（不 管 *note
     locale.getpreferredencoding(): 3ad. 返回何值），但可以使用任何
     Python支持的 *note text encoding: 160b. 。有关支持的编码列表，请参
     阅 *note codecs: 1c. 模块。

     `errors' 是一个可选的字符串参数，用于指定如何处理编码和解码错误 - 这
     不能在二进制模式下使用。可以使用各种标准错误处理程序（列在 *note
     错误处理方案: 1371. ），但是使用 *note codecs.register_error():
     dfd. 注册的任何错误处理名称也是有效的。标准名称包括:

        * 如果存在编码错误，‘'strict'’ 会引发 *note ValueError: 1fc. 异
          常。 默认值 ‘None’ 具有相同的效果。

        * ‘'ignore'’ 忽略错误。请注意，忽略编码错误可能会导致数据丢失。

        * ‘'replace'’ 会将替换标记（例如 ‘'?'’ ）插入有错误数据的地方。

        * ‘'surrogateescape'’ 将表示任何不正确的字节作为Unicode专用区中
          的代码点，范围从U+DC80到U+DCFF。当在写入数据时使用
          ‘surrogateescape’ 错误处理程序时，这些私有代码点将被转回到相同
          的字节中。这对于处理未知编码的文件很有用。

        * 只有在写入文件时才支持 ‘'xmlcharrefreplace'’。编码不支持的字符
          将替换为相应的XML字符引用 ‘&#nnn;’。

        * ‘'backslashreplace'’ 用Python的反向转义序列替换格式错误的数据
          。

        * ‘'namereplace'’ （也只在编写时支持）用 ‘\N{...}’ 转义序列替换
          不支持的字符。

     `newline' 控制 *note universal newlines: 5fd. 模式如何生效（它仅适
     用于文本模式）。它可以是 ‘None’，‘''’，‘'\n'’，‘'\r'’ 和 ‘'\r\n'’。
     它的工作原理:

        * 从流中读取输入时，如果 `newline' 为 ‘None’，则启用通用换行模式
          。输入中的行可以以 ‘'\n'’，‘'\r'’ 或 ‘'\r\n'’ 结尾，这些行被翻
          译成 ‘'\n'’ 在返回呼叫者之前。如果它是 ‘''’，则启用通用换行模
          式，但行结尾将返回给调用者未翻译。如果它具有任何其他合法值，则
          输入行仅由给定字符串终止，并且行结尾将返回给未调用的调用者。

        * 将输出写入流时，如果 `newline' 为 ‘None’，则写入的任何 ‘'\n'’
          字符都将转换为系统默认行分隔符 *note os.linesep: 160c.。如果
          `newline' 是 ‘''’ 或 ‘'\n'’，则不进行翻译。如果 `newline' 是任
          何其他合法值，则写入的任何 ‘'\n'’ 字符将被转换为给定的字符串。

     如果 `closefd' 是 ‘False’ 并且给出了文件描述符而不是文件名，那么当
     文件关闭时，底层文件描述符将保持打开状态。如果给出文件名则
     `closefd' 必须为 ‘True’ （默认值），否则将引发错误。

     可以通过传递可调用的 `opener' 来使用自定义开启器。然后通过使用参数
     （ `file'，`flags' ）调用 `opener' 获得文件对象的基础文件描述符。
     `opener' 必须返回一个打开的文件描述符（使用 *note os.open: 66e. as
     `opener' 时与传递 ‘None’ 的效果相同）。

     新创建的文件是 *note 不可继承的: 803.。

     下面的示例使用 *note os.open(): 66e. 函数的 *note dir_fd: a37. 的形
     参，从给定的目录中用相对路径打开文件:

          >>> import os
          >>> dir_fd = os.open('somedir', os.O_RDONLY)
          >>> def opener(path, flags):
          ...     return os.open(path, flags, dir_fd=dir_fd)
          ...
          >>> with open('spamspam.txt', 'w', opener=opener) as f:
          ...     print('This will be written to somedir/spamspam.txt', file=f)
          ...
          >>> os.close(dir_fd)  # don't leak a file descriptor

     *note open(): 4f8. 函数所返回的 *note file object: b4a. 类型取决于
     所用模式。 当使用 *note open(): 4f8. 以文本模式 (‘'w'’, ‘'r'’,
     ‘'wt'’, ‘'rt'’ 等) 打开文件时，它将返回 *note io.TextIOBase: c41.
     (特别是 *note io.TextIOWrapper: 5fc.) 的一个子类。 当使用缓冲以二进
     制模式打开文件时，返回的类是 *note io.BufferedIOBase: 591. 的一个子
     类。 具体的类会有多种：在只读的二进制模式下，它将返回 *note
     io.BufferedReader: b92.；在写入二进制和追加二进制模式下，它将返回
     *note io.BufferedWriter: 160d.，而在读/写模式下，它将返回 *note
     io.BufferedRandom: 160e.。 当禁用缓冲时，则会返回原始流，即 *note
     io.RawIOBase: a1b. 的一个子类 *note io.FileIO: cac.。

     另请参阅文件操作模块，例如 *note fileinput: 80.、*note io: a2. （声
     明了 *note open(): 4f8.）、*note os: c5.、*note os.path: c6.、*note
     tempfile: 104. 和 *note shutil: ea.。

     引发一个 *note 审计事件: ea1. ‘open’ 附带参数 ‘file’, ‘mode’,
     ‘flags’。

     ‘mode’ 与 ‘flags’ 参数可以在原始调用的基础上被修改或传递。

          在 3.3 版更改:

             * 增加了 `opener' 形参。

             * 增加了 ‘'x'’ 模式。

             * 过去触发的 *note IOError: 99a.，现在是 *note OSError:
               1d4. 的别名。

             * 如果文件已存在但使用了排它性创建模式（ ‘'x'’ ），现在会触
               发 *note FileExistsError: 960.。

          在 3.4 版更改:

             * 文件现在禁止继承。

     Deprecated since version 3.4, will be removed in version 3.9: ‘'U'’
     模式。

          在 3.5 版更改:

             * 如果系统调用被中断，但信号处理程序没有触发异常，此函数现
               在会重试系统调用，而不是触发 *note InterruptedError: 662.
               异常 (原因详见 PEP 475(2))。

             * 增加了 ‘'namereplace'’ 错误处理接口。

          在 3.6 版更改:

             * 增加对实现了 *note os.PathLike: 4f3. 对象的支持。

             * 在 Windows 上，打开一个控制台缓冲区将返回 *note
               io.RawIOBase: a1b. 的子类，而不是 *note io.FileIO: cac.。

 -- 函数: ord (c)

     对表示单个 Unicode 字符的字符串，返回代表它 Unicode 码点的整数。例
     如 ‘ord('a')’ 返回整数 ‘97’， ‘ord('€')’ （欧元符号）返回 ‘8364’ 。
     这是 *note chr(): 1438. 的逆函数。

 -- 函数: pow (base, exp[, mod])

     返回 `base' 的 `exp' 次幂；如果 `mod' 存在，则返回 `base' 的 `exp'
     次幂对 `mod' 取余（比 ‘pow(base, exp) % mod’ 更高效）。 两参数形式
     ‘pow(base, exp)’ 等价于乘方运算符: ‘base**exp’。

     参数必须具有数值类型。 对于混用的操作数类型，则将应用双目算术运算符
     的类型强制转换规则。 对于 *note int: 185. 操作数，结果具有与操作数
     相同的类型（强制转换后），除非第二个参数为负值；在这种情况下，所有
     参数将被转换为浮点数并输出浮点数结果。 例如，‘10**2’ 返回 ‘100’，但
     ‘10**-2’ 返回 ‘0.01’。

     对于 *note int: 185. 操作数 `base' 和 `exp'，如果给出 `mod'，则
     `mod' 必须为整数类型并且 `mod' 必须不为零。 如果给出 `mod' 并且
     `exp' 为负值，则 `base' 必须相对于 `mod' 不可整除。 在这种情况下，
     将会返回 ‘pow(inv_base, -exp, mod)’，其中 `inv_base' 为 `base' 的倒
     数对 `mod' 取余。

     下面的例子是 ‘38’ 的倒数对 ‘97’ 取余:

          >>> pow(38, -1, mod=97)
          23
          >>> 23 * 38 % 97 == 1
          True

     在 3.8 版更改: 对于 *note int: 185. 操作数，三参数形式的 ‘pow’ 现在
     允许第二个参数为负值，即可以计算倒数的余数。

     在 3.8 版更改: 允许关键字参数。 之前只支持位置参数。

 -- 函数: print (*objects, sep=' ', end='\n', file=sys.stdout,
          flush=False)

     将 `objects' 打印到 `file' 指定的文本流，以 `sep' 分隔并在末尾加上
     `end'。 `sep', `end', `file' 和 `flush' 如果存在，它们必须以关键字
     参数的形式给出。

     所有非关键字参数都会被转换为字符串，就像是执行了 *note str(): 339.
     一样，并会被写入到流，以 `sep' 且在末尾加上 `end'。 `sep' 和 `end'
     都必须为字符串；它们也可以为 ‘None’，这意味着使用默认值。 如果没有
     给出 `objects'，则 *note print(): 88f. 将只写入 `end'。

     `file' 参数必须是一个具有 ‘write(string)’ 方法的对象；如果参数不存
     在或为 ‘None’，则将使用 *note sys.stdout: 317.。 由于要打印的参数会
     被转换为文本字符串，因此 *note print(): 88f. 不能用于二进制模式的文
     件对象。 对于这些对象，应改用 ‘file.write(...)’。

     输出是否被缓存通常决定于 `file'，但如果 `flush' 关键字参数为真值，
     流会被强制刷新。

     在 3.3 版更改: 增加了 `flush' 关键字参数。

 -- 类: property (fget=None, fset=None, fdel=None, doc=None)

     返回 property 属性。

     `fget' 是获取属性值的函数。 `fset' 是用于设置属性值的函数。 `fdel'
     是用于删除属性值的函数。并且 `doc' 为属性对象创建文档字符串。

     一个典型的用法是定义一个托管属性 ‘x’:

          class C:
              def __init__(self):
                  self._x = None

              def getx(self):
                  return self._x

              def setx(self, value):
                  self._x = value

              def delx(self):
                  del self._x

              x = property(getx, setx, delx, "I'm the 'x' property.")

     如果 `c' 是 `C' 的实例，‘c.x’ 将调用getter，‘c.x = value’ 将调用
     setter， ‘del c.x’ 将调用deleter。

     如果给出，`doc' 将成为该 property 属性的文档字符串。 否则该
     property 将拷贝 `fget' 的文档字符串（如果存在）。 这令使用 *note
     property(): 1d8. 作为 *note decorator: 284. 来创建只读的特征属性可
     以很容易地实现:

          class Parrot:
              def __init__(self):
                  self._voltage = 100000

              @property
              def voltage(self):
                  """Get the current voltage."""
                  return self._voltage

     以上 ‘@property’ 装饰器会将 ‘voltage()’ 方法转化为一个具有相同名称
     的只读属性的 "getter"，并将 `voltage' 的文档字符串设置为 "Get the
     current voltage."

     特征属性对象具有 ‘getter’, ‘setter’ 以及 ‘deleter’ 方法，它们可用作
     装饰器来创建该特征属性的副本，并将相应的访问函数设为所装饰的函数。
     这最好是用一个例子来解释:

          class C:
              def __init__(self):
                  self._x = None

              @property
              def x(self):
                  """I'm the 'x' property."""
                  return self._x

              @x.setter
              def x(self, value):
                  self._x = value

              @x.deleter
              def x(self):
                  del self._x

     上述代码与第一个例子完全等价。 注意一定要给附加函数与原始的特征属性
     相同的名称 (在本例中为 ‘x’。)

     返回的特征属性对象同样具有与构造器参数相对应的属性 ‘fget’, ‘fset’ 和
     ‘fdel’。

     在 3.5 版更改: 特征属性对象的文档字符串现在是可写的。

 -- 类: range (stop)

 -- 类: range (start, stop[, step])

     虽然被称为函数，但 *note range: 9c6. 实际上是一个不可变的序列类型，
     参见在 *note range 对象: 160f. 与 *note 序列类型 — list, tuple,
     range: 1280. 中的文档说明。

 -- 函数: repr (object)

     返回包含一个对象的可打印表示形式的字符串。 对于许多类型来说，该函数
     会尝试返回的字符串将会与该对象被传递给 *note eval(): b98. 时所生成
     的对象具有相同的值，在其他情况下表示形式会是一个括在尖括号中的字符
     串，其中包含对象类型的名称与通常包括对象名称和地址的附加信息。 类可
     以通过定义 *note __repr__(): 347. 方法来控制此函数为它的实例所返回
     的内容。

 -- 函数: reversed (seq)

     返回一个反向的 *note iterator: 104b.。 `seq' 必须是一个具有 *note
     __reversed__(): 537. 方法的对象或者是支持该序列协议（具有从 ‘0’ 开
     始的整数类型参数的 *note __len__(): dd3. 方法和 *note
     __getitem__(): 280. 方法）。

 -- 函数: round (number[, ndigits])

     返回 `number' 舍入到小数点后 `ndigits' 位精度的值。 如果 `ndigits'
     被省略或为 ‘None’，则返回最接近输入值的整数。

     对于支持 *note round(): c75. 的内置类型，值会被舍入到最接近的 10 的
     负 `ndigits' 次幂的倍数；如果与两个倍数的距离相等，则选择偶数 (因此
     ，‘round(0.5)’ 和 ‘round(-0.5)’ 均为 ‘0’ 而 ‘round(1.5)’ 为 ‘2’)。
     任何整数值都可作为有效的 `ndigits' (正数、零或负数)。 如果
     `ndigits' 被省略或为 ‘None’ 则返回值将为整数。 否则返回值与
     `number' 的类型相同。

     对于一般的 Python 对象 ‘number’, ‘round’ 将委托给
     ‘number.__round__’。

          注解: 对浮点数执行 *note round(): c75. 的行为可能会令人惊讶：
          例如，‘round(2.675, 2)’ 将给出 ‘2.67’ 而不是期望的 ‘2.68’。 这
          不算是程序错误：这一结果是由于大多数十进制小数实际上都不能以浮
          点数精确地表示。 请参阅 *note 浮点算术：争议和限制: 1332. 了解
          更多信息。

 -- 类: set ([iterable])

     返回一个新的 *note set: b77. 对象，可以选择带有从 `iterable' 获取的
     元素。 ‘set’ 是一个内置类型。 请查看 *note set: b77. 和 *note
     集合类型 — set, frozenset: 1602. 获取关于这个类的文档。

     有关其他容器请参看内置的 *note frozenset: bf6, *note list: 263,
     *note tuple: 486. 和 *note dict: 1b9. 类，以及 *note collections:
     1e. 模块。

 -- 函数: setattr (object, name, value)

     此函数与 *note getattr(): 451. 两相对应。 其参数为一个对象、一个字
     符串和一个任意值。 字符串指定一个现有属性或者新增属性。 函数会将值
     赋给该属性，只要对象允许这种操作。 例如，‘setattr(x, 'foobar',
     123)’ 等价于 ‘x.foobar = 123’。

 -- 类: slice (stop)

 -- 类: slice (start, stop[, step])

     返回一个表示由 ‘range(start, stop, step)’ 所指定索引集的 *note
     slice: 1610. 对象。 其中 `start' 和 `step' 参数默认为 ‘None’。 切片
     对象具有仅会返回对应参数值（或其默认值）的只读数据属性 ‘start’,
     ‘stop’ 和 ‘step’。 它们没有其他的显式功能；不过它们会被 NumPy 以及
     其他第三方扩展所使用。 切片对象也会在使用扩展索引语法时被生成。 例
     如: ‘a[start:stop:step]’ 或 ‘a[start:stop, i]’。 请参阅 *note
     itertools.islice(): 3aa. 了解返回迭代器的一种替代版本。

 -- 函数: sorted (iterable, *, key=None, reverse=False)

     根据 `iterable' 中的项返回一个新的已排序列表。

     具有两个可选参数，它们都必须指定为关键字参数。

     `key' 指定带有单个参数的函数，用于从 `iterable' 的每个元素中提取用
     于比较的键 (例如 ‘key=str.lower’)。 默认值为 ‘None’ (直接比较元素
     )。

     `reverse' 为一个布尔值。 如果设为 ‘True’，则每个列表元素将按反向顺
     序比较进行排序。

     使用 *note functools.cmp_to_key(): b5e. 可将老式的 `cmp' 函数转换为
     `key' 函数。

     内置的 *note sorted(): 44c. 确保是稳定的。 如果一个排序确保不会改变
     比较结果相等的元素的相对顺序就称其为稳定的 — 这有利于进行多重排序（
     例如先按部门、再按薪级排序）。

     有关排序示例和简要排序教程，请参阅 *note 排序指南: 1611. 。

 -- 函数: @staticmethod

     将方法转换为静态方法。

     静态方法不会接收隐式的第一个参数。要声明一个静态方法，请使用此语法

          class C:
              @staticmethod
              def f(arg1, arg2, ...): ...

     ‘@staticmethod’ 这样的形式称为函数的 *note decorator: 284. – 详情参
     阅 *note 函数定义: 126c.。

     静态方法的调用可以在类上进行 (例如 ‘C.f()’) 也可以在实例上进行 (例
     如 ‘C().f()’)。

     Python中的静态方法与Java或C ++中的静态方法类似。另请参阅 *note
     classmethod(): 1d9. ，用于创建备用类构造函数的变体。

     像所有装饰器一样，也可以像常规函数一样调用 ‘staticmethod’ ，并对其
     结果执行某些操作。比如某些情况下需要从类主体引用函数并且您希望避免
     自动转换为实例方法。对于这些情况，请使用此语法:

          class C:
              builtin_open = staticmethod(open)

     想了解更多有关静态方法的信息，请参阅 *note 标准类型层级结构: 1431.
     。

 -- 类: str (object='')

 -- 类: str (object=b'', encoding='utf-8', errors='strict')

     返回一个 *note str: 339. 版本的 `object' 。有关详细信息，请参阅
     *note str(): 339. 。

     ‘str’ 是内置字符串 *note class: 1612. 。更多关于字符串的信息查看
     *note 文本序列类型 — str: 1233.。

 -- 函数: sum (iterable, /, start=0)

     从 `start' 开始自左向右对 `iterable' 的项求和并返回总计值。
     `iterable' 的项通常为数字，而 start 值则不允许为字符串。

     对某些用例来说，存在 *note sum(): 1e6. 的更好替代。 拼接字符串序列
     的更好更快方式是调用 ‘''.join(sequence)’。 要以扩展精度对浮点值求和
     ，请参阅 *note math.fsum(): d46.。 要拼接一系列可迭代对象，请考虑使
     用 *note itertools.chain(): 1613.。

     在 3.8 版更改: `start' 形参可用关键字参数形式来指定。

 -- 函数: super ([type[, object-or-type]])

     返回一个代理对象，它会将方法调用委托给 `type' 的父类或兄弟类。 这对
     于访问已在类中被重载的继承方法很有用。

     `object-or-type' 确定用于搜索的 *note method resolution order:
     1614.。 搜索会从 `type' 之后的类开始。

     举例来说，如果 `object-or-type' 的 *note __mro__: 1615. 为 ‘D -> B
     -> C -> A -> object’ 并且 `type' 的值为 ‘B’，则 *note super(): 4eb.
     将会搜索 ‘C -> A -> object’。

     `object-or-type' 的 *note __mro__: 1615. 属性列出了 *note
     getattr(): 451. 和 *note super(): 4eb. 所共同使用的方法解析搜索顺序
     。 该属性是动态的，可以在任何继承层级结构发生更新的时候被改变。

     如果省略第二个参数，则返回的超类对象是未绑定的。 如果第二个参数为一
     个对象，则 ‘isinstance(obj, type)’ 必须为真值。 如果第二个参数为一
     个类型，则 ‘issubclass(type2, type)’ 必须为真值（这适用于类方法）。

     `super' 有两个典型用例。 在具有单继承的类层级结构中，`super' 可用来
     引用父类而不必显式地指定它们的名称，从而令代码更易维护。 这种用法与
     其他编程语言中 `super' 的用法非常相似。

     第二个用例是在动态执行环境中支持协作多重继承。 此用例为 Python 所独
     有而不存在于静态编码语言或仅支持单继承的语言当中。 这使用实现“菱形
     图”成为可能，即有多个基类实现相同的方法。 好的设计强制要求这样的方
     法在每个情况下都具有相同的调用签名（因为调用顺序是在运行时确定的，
     也因为这个顺序要适应类层级结构的更改，还因为这个顺序可能包括在运行
     时之前未知的兄弟类）。

     对于以上两个用例，典型的超类调用看起来是这样的:

          class C(B):
              def method(self, arg):
                  super().method(arg)    # This does the same thing as:
                                         # super(C, self).method(arg)

     除了方法查找之外，*note super(): 4eb. 也可用于属性查找。 一个可能的
     应用场合是在上级或同级类中调用 *note 描述器: 1616.。

     请注意 *note super(): 4eb. 是作为显式加点属性查找的绑定过程的一部分
     来实现的，例如 ‘super().__getitem__(name)’。 它做到这一点是通过实现
     自己的 *note __getattribute__(): 44f. 方法，这样就能以可预测的顺序
     搜索类，并且支持协作多重继承。 对应地，*note super(): 4eb. 在像
     ‘super()[name]’ 这样使用语句或操作符进行隐式查找时则未被定义。

     还要注意的是，除了零个参数的形式以外，*note super(): 4eb. 并不限于
     在方法内部使用。 两个参数的形式明确指定参数并进行相应的引用。 零个
     参数的形式仅适用于类定义内部，因为编译器需要填入必要的细节以正确地
     检索到被定义的类，还需要让普通方法访问当前实例。

     对于有关如何使用 *note super(): 4eb. 来如何设计协作类的实用建议，请
     参阅 使用 super() 的指南(3)。

 -- 类: tuple ([iterable])

     虽然被称为函数，但 *note tuple: 486. 实际上是一个不可变的序列类型，
     参见在 *note 元组: 1617. 与 *note 序列类型 — list, tuple, range:
     1280. 中的文档说明。

 -- 类: type (object)

 -- 类: type (name, bases, dict, **kwds)

     传入一个参数时，返回 `object' 的类型。 返回值是一个 type 对象，通常
     与 *note object.__class__: e12. 所返回的对象相同。

     推荐使用 *note isinstance(): 457. 内置函数来检测对象的类型，因为它
     会考虑子类的情况。

     传入三个参数时，返回一个新的 type 对象。 这在本质上是 *note class:
     c72. 语句的一种动态形式，`name' 字符串即类名并会成为 *note
     __name__: c6f. 属性；`bases' 元组包含基类并会成为 *note __bases__:
     e11. 属性；如果为空则会添加所有类的终极基类 *note object: 2b1.。
     `dict' 字典包含类主体的属性和方法定义；它在成为 *note __dict__:
     504. 属性之前可能会被拷贝或包装。 下面两条语句会创建相同的 *note
     type: 611. 对象:

          >>> class X:
          ...     a = 1
          ...
          >>> X = type('X', (), dict(a=1))

     另请参阅 *note 类型对象: 1618.。

     提供给三参数形式的关键字参数会被传递给适当的元类机制 (通常为 *note
     __init_subclass__(): 4ea.)，相当于类定义中关键字 (除了 `metaclass')
     的行为方式。

     另请参阅 *note 自定义类创建: 4ed.。

     在 3.6 版更改: *note type: 611. 的子类如果未重载 ‘type.__new__’，将
     不再能使用一个参数的形式来获取对象的类型。

 -- 函数: vars ([object])

     返回模块、类、实例或任何其它具有 *note __dict__: 504. 属性的对象的
     *note __dict__: 504. 属性。

     模块和实例这样的对象具有可更新的 *note __dict__: 504. 属性；但是，
     其它对象的 *note __dict__: 504. 属性可能会设为限制写入（例如，类会
     使用 *note types.MappingProxyType: abe. 来防止直接更新字典）。

     不带参数时，*note vars(): 1047. 的行为类似 *note locals(): 45d.。 请
     注意，locals 字典仅对于读取起作用，因为对 locals 字典的更新会被忽略
     。

     如果指定了一个对象但它没有 *note __dict__: 504. 属性（例如，当它所
     属的类定义了 *note __slots__: e35. 属性时）则会引发 *note
     TypeError: 193. 异常。

 -- 函数: zip (*iterables)

     创建一个聚合了来自每个可迭代对象中的元素的迭代器。

     返回一个元组的迭代器，其中的第 `i' 个元组包含来自每个参数序列或可迭
     代对象的第 `i' 个元素。 当所输入可迭代对象中最短的一个被耗尽时，迭
     代器将停止迭代。 当只有一个可迭代对象参数时，它将返回一个单元组的迭
     代器。 不带参数时，它将返回一个空迭代器。 相当于:

          def zip(*iterables):
              # zip('ABCD', 'xy') --> Ax By
              sentinel = object()
              iterators = [iter(it) for it in iterables]
              while iterators:
                  result = []
                  for it in iterators:
                      elem = next(it, sentinel)
                      if elem is sentinel:
                          return
                      result.append(elem)
                  yield tuple(result)

     函数会保证可迭代对象按从左至右的顺序被求值。 使得可以通过
     ‘zip(*[iter(s)]*n)’ 这样的惯用形式将一系列数据聚类为长度为 n 的分组
     。 这将重复 `同样的' 迭代器 ‘n’ 次，以便每个输出的元组具有第 ‘n’ 次
     调用该迭代器的结果。 它的作用效果就是将输入拆分为长度为 n 的数据块
     。

     当你不用关心较长可迭代对象末尾不匹配的值时，则 *note zip(): c3a. 只
     须使用长度不相等的输入即可。 如果那些值很重要，则应改用 *note
     itertools.zip_longest(): c39.。

     *note zip(): c3a. 与 ‘*’ 运算符相结合可以用来拆解一个列表:

          >>> x = [1, 2, 3]
          >>> y = [4, 5, 6]
          >>> zipped = zip(x, y)
          >>> list(zipped)
          [(1, 4), (2, 5), (3, 6)]
          >>> x2, y2 = zip(*zip(x, y))
          >>> x == list(x2) and y == list(y2)
          True

 -- 函数: __import__ (name, globals=None, locals=None, fromlist=(),
          level=0)

          注解: 与 *note importlib.import_module(): b1b. 不同，这是一个
          日常 Python 编程中不需要用到的高级函数。

     此函数会由 *note import: c25. 语句发起调用。 它可以被替换 (通过导入
     *note builtins: 13. 模块并赋值给 ‘builtins.__import__’) 以便修改
     ‘import’ 语句的语义，但是 `强烈' 不建议这样做，因为使用导入钩子 (参
     见 PEP 302(4)) 通常更容易实现同样的目标，并且不会导致代码问题，因为
     许多代码都会假定所用的是默认实现。 同样也不建议直接使用 *note
     __import__(): 619. 而应该用 *note importlib.import_module(): b1b.。

     该函数会导入 `name' 模块，有可能使用给定的 `globals' 和 `locals' 来
     确定如何在包的上下文中解读名称。 `fromlist' 给出了应该从由 `name' 指
     定的模块导入对象或子模块的名称。 标准实现完全不使用其 `locals' 参数
     ，而仅使用 `globals' 参数来确定 *note import: c25. 语句的包上下文。

     `level' 指定是使用绝对还是相对导入。 ‘0’ (默认值) 意味着仅执行绝对
     导入。 `level' 为正数值表示相对于模块调用 *note __import__(): 619.
     的目录，将要搜索的父目录层数 (详情参见 PEP 328(5))。

     当 `name' 变量的形式为 ‘package.module’ 时，通常将会返回最高层级的
     包（第一个点号之前的名称），而 `不是' 以 `name' 命名的模块。 但是，
     当给出了非空的 `fromlist' 参数时，则将返回以 `name' 命名的模块。

     例如，语句 ‘import spam’ 的结果将为与以下代码作用相同的字节码:

          spam = __import__('spam', globals(), locals(), [], 0)

     语句 ‘import spam.ham’ 的结果将为以下调用:

          spam = __import__('spam.ham', globals(), locals(), [], 0)

     请注意在这里 *note __import__(): 619. 是如何返回顶层模块的，因为这
     是通过 *note import: c25. 语句被绑定到特定名称的对象。

     另一方面，语句 ‘from spam.ham import eggs, sausage as saus’ 的结果
     将为

          _temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
          eggs = _temp.eggs
          saus = _temp.sausage

     在这里， ‘spam.ham’ 模块会由 *note __import__(): 619. 返回。 要导入
     的对象将从此对象中提取并赋值给它们对应的名称。

     如果您只想按名称导入模块（可能在包中），请使用 *note
     importlib.import_module(): b1b.

     在 3.3 版更改: Negative values for `level' are no longer supported
     (which also changes the default value to 0).

备注
....

   ---------- Footnotes ----------

   (1) (1) 解析器只接受 Unix 风格的行结束符。如果您从文件中读取代码，请
确保用换行符转换模式转换 Windows 或 Mac 风格的换行符。

   (2) https://www.python.org/dev/peps/pep-0475

   (3) 
https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

   (4) https://www.python.org/dev/peps/pep-0302

   (5) https://www.python.org/dev/peps/pep-0328


File: python.info,  Node: 内置常量,  Next: 内置类型,  Prev: 内置函数,  Up: Python 标准库

5.3 内置常量
============

有少数的常量存在于内置命名空间中。 它们是：

 -- 数据: False

     *note bool: 184. 类型的假值。 给 ‘False’ 赋值是非法的并会引发 *note
     SyntaxError: 460.。

 -- 数据: True

     *note bool: 184. 类型的真值。 给 ‘True’ 赋值是非法的并会引发 *note
     SyntaxError: 460.。

 -- 数据: None

     ‘NoneType’ 类型的唯一值。 ‘None’ 经常用于表示缺少值，当因为默认参数
     未传递给函数时。 给 ‘None’ 赋值是非法的并会引发 *note SyntaxError:
     460.。

 -- 数据: NotImplemented

     二进制特殊方法应返回的特殊值（例如，*note __eq__(): 348.、*note
     __lt__(): c3c.、‘__add __()’、*note __rsub__(): 1479. 等）表示操作
     没有针对其他类型实现；为了相同的目的，可以通过就地二进制特殊方法（
     例如，‘__imul __()’、‘__ rightnd__()’ 等）返回。 它的逻辑值为真。

          注解: 当二进制（或就地）方法返回‘‘NotImplemented‘‘时，解释器将
          尝试对另一种类型（或其他一些回滚操作，取决于运算符）的反射操作
          。 如果所有尝试都返回‘‘NotImplemented‘‘，则解释器将引发适当的
          异常。 错误返回的‘‘NotImplemented‘‘将导致误导性错误消息或返回
          到Python代码中的‘‘NotImplemented‘‘值。

          参见 *note 实现算术运算: 1432. 为例。

          注解: ‘NotImplementedError’ 和 ‘NotImplemented’ 不可互换，即使
          它们有相似的名称和用途。 有关何时使用它的详细信息，请参阅
          *note NotImplementedError: 617.。

 -- 数据: Ellipsis

     与省略号文字字面 “‘...’” 相同。 特殊值主要与用户定义的容器数据类型
     的扩展切片语法结合使用。

 -- 数据: __debug__

     如果 Python 没有以 *note -O: 694. 选项启动，则此常量为真值。 另请参
     见 *note assert: e0e. 语句。

     注解: 变量名 *note None: 158.，*note False: 390.，*note True: 4a1.
     和 ‘__ debug__’ 无法重新赋值（赋值给它们，即使是属性名，将引发
     *note SyntaxError: 460. ），所以它们可以被认为是“真正的”常数。

* Menu:

* 由 site 模块添加的常量::


File: python.info,  Node: 由 site 模块添加的常量,  Up: 内置常量

5.3.1 由 ‘site’ 模块添加的常量
------------------------------

*note site: ec. 模块（在启动期间自动导入，除非给出 *note -S: b2c. 命令行
选项）将几个常量添加到内置命名空间。 它们对交互式解释器 shell 很有用，并
且不应在程序中使用。

 -- 数据: quit (code=None)
 -- 数据: exit (code=None)

     当打印此对象时，会打印出一条消息，例如“Use quit() or Ctrl-D (i.e.
     EOF) to exit”，当调用此对象时，将使用指定的退出代码来引发 *note
     SystemExit: 605.。

 -- 数据: copyright
 -- 数据: credits

     打印或调用的对象分别打印版权或作者的文本。

 -- 数据: license

     当打印此对象时，会打印出一条消息“Type license() to see the full
     license text”，当调用此对象时，将以分页形式显示完整的许可证文本（每
     次显示一屏）。


File: python.info,  Node: 内置类型,  Next: 内置异常,  Prev: 内置常量,  Up: Python 标准库

5.4 内置类型
============

以下部分描述了解释器中内置的标准类型。

主要内置类型有数字、序列、映射、类、实例和异常。

有些多项集类是可变的。 它们用于添加、移除或重排其成员的方法将原地执行，
并不返回特定的项，绝对不会返回多项集实例自身而是返回 ‘None’。

有些操作受多种对象类型的支持；特别地，实际上所有对象都可以比较是否相等、
检测逻辑值，以及转换为字符串（使用 *note repr(): 7d5. 函数或略有差异的
*note str(): 339. 函数）。 后一个函数是在对象由 *note print(): 88f. 函数
输出时被隐式地调用的。

* Menu:

* 逻辑值检测::
* 布尔运算: 布尔运算 --- and or not. and, or, not
* 比较运算: 比较运算<2>.
* 数字类型: 数字类型 --- int float complex. int, float, complex
* 迭代器类型::
* 序列类型: 序列类型 --- list tuple range. list, tuple, range
* 文本序列类型: 文本序列类型 --- str. str
* 二进制序列类型: 二进制序列类型 --- bytes bytearray memoryview. bytes, bytearray, memoryview
* 集合类型: 集合类型 --- set frozenset. set, frozenset
* 映射类型: 映射类型 --- dict. dict
* 上下文管理器类型::
* 其他内置类型::
* 特殊属性::


File: python.info,  Node: 逻辑值检测,  Next: 布尔运算 --- and or not,  Up: 内置类型

5.4.1 逻辑值检测
----------------

任何对象都可以进行逻辑值的检测，以便在 *note if: def. 或 *note while:
123d. 作为条件或是作为下文所述布尔运算的操作数来使用。

一个对象在默认情况下均被视为真值，除非当该对象被调用时其所属类定义了
*note __bool__(): c70. 方法且返回 ‘False’ 或是定义了 *note __len__():
dd3. 方法且返回零。 (1) 下面基本完整地列出了会被视为假值的内置对象:

   * 被定义为假值的常量: ‘None’ 和 ‘False’。

   * 任何数值类型的零: ‘0’, ‘0.0’, ‘0j’, ‘Decimal(0)’, ‘Fraction(0, 1)’

   * 空的序列和多项集: ‘''’, ‘()’, ‘[]’, ‘{}’, ‘set()’, ‘range(0)’

产生布尔值结果的运算和内置函数总是返回 ‘0’ 或 ‘False’ 作为假值，‘1’ 或
‘True’ 作为真值，除非另行说明。 （重要例外：布尔运算 ‘or’ 和 ‘and’ 总是
返回其中一个操作数。）

   ---------- Footnotes ----------

   (1) (1) 有关这些特殊方法的额外信息可参看 Python 参考指南 (*note
基本定制: 1445.)。


File: python.info,  Node: 布尔运算 --- and or not,  Next: 比较运算<2>,  Prev: 逻辑值检测,  Up: 内置类型

5.4.2 布尔运算 — ‘and’, ‘or’, ‘not’
-----------------------------------

这些属于布尔运算，按优先级升序排列:

运算              结果：                                注释
                                                        
--------------------------------------------------------------------
                                                        
‘x or y’          if `x' is false, then `y', else `x'   (1)
                                                        
                                                        
‘x and y’         if `x' is false, then `x', else `y'   (2)
                                                        
                                                        
‘not x’           if `x' is false, then ‘True’, else    (3)
                  ‘False’                               
                  

注释:

  1. 这是个短路运算符，因此只有在第一个参数为假值时才会对第二个参数求值
     。

  2. 这是个短路运算符，因此只有在第一个参数为真值时才会对第二个参数求值
     。

  3. ‘not’ 的优先级比非布尔运算符低，因此 ‘not a == b’ 会被解读为 ‘not
     (a == b)’ 而 ‘a == not b’ 会引发语法错误。


File: python.info,  Node: 比较运算<2>,  Next: 数字类型 --- int float complex,  Prev: 布尔运算 --- and or not,  Up: 内置类型

5.4.3 比较运算
--------------

在 Python 中有八种比较运算符。 它们的优先级相同（比布尔运算的优先级高）
。 比较运算可以任意串连；例如，‘x < y <= z’ 等价于 ‘x < y and y <= z’，
前者的不同之处在于 `y' 只被求值一次（但在两种情况下当 ‘x < y’ 结果为假值
时 `z' 都不会被求值）。

此表格汇总了比较运算:

运算             含义
                 
-----------------------------------------------
                 
‘<’              严格小于
                 
                 
‘<=’             小于或等于
                 
                 
‘>’              严格大于
                 
                 
‘>=’             大于或等于
                 
                 
‘==’             等于
                 
                 
‘!=’             不等于
                 
                 
‘is’             对象标识
                 
                 
‘is not’         否定的对象标识
                 

除不同的数字类型外，不同类型的对象不能进行相等比较。‘==’ 运算符总有定义
，但对于某些对象类型（例如，类对象），它等于 *note is: eca. 。其他 ‘<’、
‘<=’、‘>’ 和 ‘>=’ 运算符仅在有意义的地方定义。例如，当参与比较的参数之一
为复数时，它们会抛出 *note TypeError: 193. 异常。

具有不同标识的类的实例比较结果通常为不相等，除非类定义了 *note __eq__():
348. 方法。

一个类实例不能与相同类或的其他实例或其他类型的对象进行排序，除非该类定义
了足够多的方法，包括 *note __lt__(): c3c, *note __le__(): ca8, *note
__gt__(): ca9. 以及 *note __ge__(): caa. (而如果你想实现常规意义上的比较
操作，通常只要有 *note __lt__(): c3c. 和 *note __eq__(): 348. 就可以了
)。

*note is: eca. 和 *note is not: 1558. 运算符无法自定义；并且它们可以被应
用于任意两个对象而不会引发异常。

还有两种具有相同语法优先级的运算 *note in: 7ac. 和 *note not in: 146d.，
它们被 *note iterable: bb4. 或实现了 *note __contains__(): d30. 方法的类
型所支持。


File: python.info,  Node: 数字类型 --- int float complex,  Next: 迭代器类型,  Prev: 比较运算<2>,  Up: 内置类型

5.4.4 数字类型 — ‘int’, ‘float’, ‘complex’
------------------------------------------

存在三种不同的数字类型: `整数', `浮点数' 和 `复数'。 此外，布尔值属于整
数的子类型。 整数具有无限的精度。 浮点数通常使用 C 中的 ‘double’ 来实现
；有关你的程序运行所在机器上浮点数的精度和内部表示法可在 *note
sys.float_info: fd1. 中查看。 复数包含实部和虚部，分别以一个浮点数表示。
要从一个复数 `z' 中提取这两个部分，可使用 ‘z.real’ 和 ‘z.imag’。 （标准
库包含附加的数字类型，如表示有理数的 *note fractions.Fraction: 186. 以及
以用户定制精度表示浮点数的 *note decimal.Decimal: 189.。）

数字是由数字字面值或内置函数与运算符的结果来创建的。 不带修饰的整数字面
值（包括十六进制、八进制和二进制数）会生成整数。 包含小数点或幂运算符的
数字字面值会生成浮点数。 在数字字面值末尾加上 ‘'j'’ 或 ‘'J'’ 会生成虚数
（实部为零的复数），你可以将其与整数或浮点数相加来得到具有实部和虚部的复
数。

Python 完全支持混合运算：当一个二元算术运算符的操作数有不同数值类型时，
"较窄"类型的操作数会拓宽到另一个操作数的类型，其中整数比浮点数窄，浮点数
比复数窄。不同类型的数字之间的比较，同比较这些数字的精确值一样。(1)

构造函数 *note int(): 185.、 *note float(): 188. 和 *note complex():
18a. 可以用来构造特定类型的数字。

所有数字类型（复数除外）都支持下列运算（有关运算优先级，请参阅：*note
运算符优先级: 1573.）:

运算                      结果：                                注释          完整文档
                                                                              
-------------------------------------------------------------------------------------------------------
                                                                              
‘x + y’                   `x' 和 `y' 的和
                          
                                                                              
‘x - y’                   `x' 和 `y' 的差
                          
                                                                              
‘x * y’                   `x' 和 `y' 的乘积
                          
                                                                              
‘x / y’                   `x' 和 `y' 的商
                          
                                                                              
‘x // y’                  `x' 和 `y' 的商数                     (1)
                                                                
                                                                              
‘x % y’                   ‘x / y’ 的余数                        (2)
                                                                
                                                                              
‘-x’                      `x' 取反
                          
                                                                              
‘+x’                      `x' 不变
                          
                                                                              
‘abs(x)’                  `x' 的绝对值或大小                                  *note abs(): 12cf.
                                                                              
                                                                              
‘int(x)’                  将 `x' 转换为整数                     (3)(6)        *note int(): 185.
                                                                              
                                                                              
‘float(x)’                将 `x' 转换为浮点数                   (4)(6)        *note float(): 188.
                                                                              
                                                                              
‘complex(re, im)’         一个带有实部 `re' 和虚部 `im' 的复    (6)           *note complex(): 18a.
                          数。`im' 默认为0。                                  
                          
                                                                              
‘c.conjugate()’           复数 `c' 的共轭
                          
                                                                              
‘divmod(x, y)’            ‘(x // y, x % y)’                     (2)           *note divmod(): 153.
                                                                              
                                                                              
‘pow(x, y)’               `x' 的 `y' 次幂                       (5)           *note pow(): 19b.
                                                                              
                                                                              
‘x ** y’                  `x' 的 `y' 次幂                       (5)
                                                                

注释:

  1. 也称为整数除法。 结果值是一个整数，但结果的类型不一定是 int。 运算
     结果总是向负无穷的方向舍入: ‘1//2’ 为 ‘0’, ‘(-1)//2’ 为 ‘-1’,
     ‘1//(-2)’ 为 ‘-1’ 而 ‘(-1)//(-2)’ 为 ‘0’。

  2. 不可用于复数。 而应在适当条件下使用 *note abs(): 12cf. 转换为浮点数
     。

  3. 
     从浮点数转换为整数会被舍入或是像在 C 语言中一样被截断；请参阅 *note
     math.floor(): d34. 和 *note math.ceil(): d35. 函数查看转换的完整定
     义。

  4. float 也接受字符串 "nan" 和附带可选前缀 "+" 或 "-" 的 "inf" 分别表
     示非数字 (NaN) 以及正或负无穷。

  5. Python 将 ‘pow(0, 0)’ 和 ‘0 ** 0’ 定义为 ‘1’，这是编程语言的普遍做
     法。

  6. 接受的数字字面值包括数码 ‘0’ 到 ‘9’ 或任何等效的 Unicode 字符（具有
     ‘Nd’ 特征属性的代码点）。

     请参阅
     ‘http://www.unicode.org/Public/12.1.0/ucd/extracted/DerivedNumericType.txt’
     查看具有 ‘Nd’ 特征属性的代码点的完整列表。

所有 *note numbers.Real: 1435. 类型 (*note int: 185. 和 *note float:
188.) 还包括下列运算:

运算                     结果：
                         
---------------------------------------------------------------------------
                         
*note math.trunc(x): d36.`x' 截断为 *note Integral: 1434.
                         
                         
*note round(x[, n]): c75.`x' 舍入到 `n' 位小数，半数值会舍入到偶数。 如
                         果省略 `n'，则默认为 0。
                         
                         
*note math.floor(x): d34.<= `x' 的最大 *note Integral: 1434.
                         
                         
*note math.ceil(x): d35. >= `x' 的最小 *note Integral: 1434.
                         

有关更多的数字运算请参阅 *note math: b2. 和 *note cmath: 19. 模块。

* Menu:

* 整数类型的按位运算::
* 整数类型的附加方法::
* 浮点类型的附加方法::
* 数字类型的哈希运算::

   ---------- Footnotes ----------

   (1) (2) 作为结果，列表 ‘[1, 2]’ 与 ‘[1.0, 2.0]’ 是相等的，元组的情况
也类似。


File: python.info,  Node: 整数类型的按位运算,  Next: 整数类型的附加方法,  Up: 数字类型 --- int float complex

5.4.4.1 整数类型的按位运算
..........................

按位运算只对整数有意义。 计算按位运算的结果，就相当于使用无穷多个二进制
符号位对二的补码执行操作。

二进制按位运算的优先级全都低于数字运算，但又高于比较运算；一元运算 ‘~’ 具
有与其他一元算术运算 (‘+’ and ‘-’) 相同的优先级。

此表格是以优先级升序排序的按位运算列表:

运算             结果：                               注释
                                                      
---------------------------------------------------------------------
                                                      
‘x | y’          `x' 和 `y' 按位 `或'                 (4)
                                                      
                                                      
‘x ^ y’          `x' 和 `y' 按位 `异或'               (4)
                                                      
                                                      
‘x & y’          `x' 和 `y' 按位 `与'                 (4)
                                                      
                                                      
‘x << n’         `x' 左移 `n' 位                      (1)(2)
                                                      
                                                      
‘x >> n’         `x' 右移 `n' 位                      (1)(3)
                                                      
                                                      
‘~x’             `x' 逐位取反
                 

注释:

  1. 负的移位数是非法的，会导致引发 *note ValueError: 1fc.。

  2. 左移 `n' 位等价于不带溢出检测地乘以 ‘pow(2, n)’ 。

  3. 右移 `n' 位等价于除以 ‘pow(2, n)’ ，作向下取整除法。

  4. 使用带有至少一个额外符号扩展位的有限个二进制补码表示（有效位宽度为
     ‘1 + max(x.bit_length(), y.bit_length())’ 或以上）执行这些计算就足
     以获得相当于有无数个符号位时的同样结果。


File: python.info,  Node: 整数类型的附加方法,  Next: 浮点类型的附加方法,  Prev: 整数类型的按位运算,  Up: 数字类型 --- int float complex

5.4.4.2 整数类型的附加方法
..........................

int 类型实现了 *note numbers.Integral: 1434. *note abstract base class:
b3b.。 此外，它还提供了其他几个方法:

 -- 方法: int.bit_length ()

     返回以二进制表示一个整数所需要的位数，不包括符号位和前面的零:

          >>> n = -37
          >>> bin(n)
          '-0b100101'
          >>> n.bit_length()
          6

     更准确地说，如果 ‘x’ 非零，则 ‘x.bit_length()’ 是使得 ‘2**(k-1) <=
     abs(x) < 2**k’ 的唯一正整数 ‘k’。 同样地，当 ‘abs(x)’ 小到足以具有
     正确的舍入对数时，则 ‘k = 1 + int(log(abs(x), 2))’。 如果 ‘x’ 为零
     ，则 ‘x.bit_length()’ 返回 ‘0’。

     等价于:

          def bit_length(self):
              s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
              s = s.lstrip('-0b') # remove leading zeros and minus sign
              return len(s)       # len('100101') --> 6

     3.1 新版功能.

 -- 方法: int.to_bytes (length, byteorder, *, signed=False)

     返回表示一个整数的字节数组。

          >>> (1024).to_bytes(2, byteorder='big')
          b'\x04\x00'
          >>> (1024).to_bytes(10, byteorder='big')
          b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
          >>> (-1024).to_bytes(10, byteorder='big', signed=True)
          b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
          >>> x = 1000
          >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
          b'\xe8\x03'

     整数会使用 `length' 个字节来表示。 如果整数不能用给定的字节数来表示
     则会引发 *note OverflowError: 968.。

     `byteorder' 参数确定用于表示整数的字节顺序。 如果 `byteorder' 为
     ‘"big"’，则最高位字节放在字节数组的开头。 如果 `byteorder' 为
     ‘"little"’，则最高位字节放在字节数组的末尾。 要请求主机系统上的原生
     字节顺序，请使用 *note sys.byteorder: 1631. 作为字节顺序值。

     `signed' 参数确定是否使用二的补码来表示整数。 如果 `signed' 为
     ‘False’ 并且给出的是负整数，则会引发 *note OverflowError: 968.。
     `signed' 的默认值为 ‘False’。

     3.2 新版功能.

 -- 方法: classmethod int.from_bytes (bytes, byteorder, *, signed=False)

     返回由给定字节数组所表示的整数。

          >>> int.from_bytes(b'\x00\x10', byteorder='big')
          16
          >>> int.from_bytes(b'\x00\x10', byteorder='little')
          4096
          >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
          -1024
          >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
          64512
          >>> int.from_bytes([255, 0, 0], byteorder='big')
          16711680

     `bytes' 参数必须为一个 *note bytes-like object: 5f1. 或是生成字节的
     可迭代对象。

     `byteorder' 参数确定用于表示整数的字节顺序。 如果 `byteorder' 为
     ‘"big"’，则最高位字节放在字节数组的开头。 如果 `byteorder' 为
     ‘"little"’，则最高位字节放在字节数组的末尾。 要请求主机系统上的原生
     字节顺序，请使用 *note sys.byteorder: 1631. 作为字节顺序值。

     `signed' 参数指明是否使用二的补码来表示整数。

     3.2 新版功能.

 -- 方法: int.as_integer_ratio ()

     返回一对整数，其比率正好等于原整数并且分母为正数。 整数的比率总是用
     这个整数本身作为分子，‘1’ 作为分母。

     3.8 新版功能.


File: python.info,  Node: 浮点类型的附加方法,  Next: 数字类型的哈希运算,  Prev: 整数类型的附加方法,  Up: 数字类型 --- int float complex

5.4.4.3 浮点类型的附加方法
..........................

float 类型实现了 *note numbers.Real: 1435. *note abstract base class:
b3b.。 float 还具有以下附加方法。

 -- 方法: float.as_integer_ratio ()

     返回一对整数，其比率正好等于原浮点数并且分母为正数。 无穷大会引发
     *note OverflowError: 968. 而 NaN 则会引发 *note ValueError: 1fc.。

 -- 方法: float.is_integer ()

     如果 float 实例可用有限位整数表示则返回 ‘True’，否则返回 ‘False’:

          >>> (-2.0).is_integer()
          True
          >>> (3.2).is_integer()
          False

两个方法均支持与十六进制数字符串之间的转换。 由于 Python 浮点数在内部存
储为二进制数，因此浮点数与 `十进制数' 字符串之间的转换往往会导致微小的舍
入错误。 而十六进制数字符串却允许精确地表示和描述浮点数。 这在进行调试和
数值工作时非常有用。

 -- 方法: float.hex ()

     以十六进制字符串的形式返回一个浮点数表示。 对于有限浮点数，这种表示
     法将总是包含前导的 ‘0x’ 和尾随的 ‘p’ 加指数。

 -- 方法: classmethod float.fromhex (s)

     返回以十六进制字符串 `s' 表示的浮点数的类方法。 字符串 `s' 可以带有
     前导和尾随的空格。

请注意 *note float.hex(): 1334. 是实例方法，而 *note float.fromhex():
1635. 是类方法。

十六进制字符串采用的形式为:

     [sign] ['0x'] integer ['.' fraction] ['p' exponent]

可选的 ‘sign’ 可以是 ‘+’ 或 ‘-’，‘integer’ 和 ‘fraction’ 是十六进制数码
组成的字符串，‘exponent’ 是带有可选前导符的十进制整数。 大小写没有影响，
在 integer 或 fraction 中必须至少有一个十六进制数码。 此语法类似于 C99 标
准的 6.4.4.2 小节中所描述的语法，也是 Java 1.5 以上所使用的语法。 特别地
，*note float.hex(): 1334. 的输出可以用作 C 或 Java 代码中的十六进制浮点
数字面值，而由 C 的 ‘%a’ 格式字符或 Java 的 ‘Double.toHexString’ 所生成
的十六进制数字符串由为 *note float.fromhex(): 1635. 所接受。

请注意 exponent 是十进制数而非十六进制数，它给出要与系数相乘的 2 的幂次
。 例如，十六进制数字符串 ‘0x3.a7p10’ 表示浮点数 ‘(3 + 10./16 +
7./16**2) * 2.0**10’ 即 ‘3740.0’:

     >>> float.fromhex('0x3.a7p10')
     3740.0

对 ‘3740.0’ 应用反向转换会得到另一个代表相同数值的十六进制数字符串:

     >>> float.hex(3740.0)
     '0x1.d380000000000p+11'


File: python.info,  Node: 数字类型的哈希运算,  Prev: 浮点类型的附加方法,  Up: 数字类型 --- int float complex

5.4.4.4 数字类型的哈希运算
..........................

对于可能为不同类型的数字 ‘x’ 和 ‘y’，要求 ‘x == y’ 时必定 ‘hash(x) ==
hash(y)’ (详情参见 *note __hash__(): 349. 方法的文档)。 为了便于在各种数
字类型 (包括 *note int: 185, *note float: 188, *note decimal.Decimal:
189. 和 *note fractions.Fraction: 186.) 上实现并保证效率，Python 对数字
类型的哈希运算是基于为任意有理数定义统一的数学函数，因此该运算对 *note
int: 185. 和 *note fractions.Fraction: 186. 的全部实例，以及 *note
float: 188. 和 *note decimal.Decimal: 189. 的全部有限实例均可用。 从本质
上说，此函数是通过以一个固定质数 ‘P’ 进行 ‘P’ 降模给出的。 ‘P’ 的值在
Python 中可以 *note sys.hash_info: 929. 的 ‘modulus’ 属性的形式被访问。

`CPython implementation detail:' 目前所用的质数设定，在 C long 为 32 位
的机器上 ‘P = 2**31 - 1’ 而在 C long 为 64 位的机器上 ‘P = 2**61 - 1’。

详细规则如下所述:

   - 如果 ‘x = m / n’ 是一个非负的有理数且 ‘n’ 不可被 ‘P’ 整除，则定义
     ‘hash(x)’ 为 ‘m * invmod(n, P) % P’，其中 ‘invmod(n, P)’ 是对 ‘n’ 模
     ‘P’ 取反。

   - 如果 ‘x = m / n’ 是一个非负的有理数且 ‘n’ 可被 ‘P’ 整除（但 ‘m’ 不
     能）则 ‘n’ 不能对 ‘P’ 降模，以上规则不适用；在此情况下则定义
     ‘hash(x)’ 为常数值 ‘sys.hash_info.inf’。

   - 如果 ‘x = m / n’ 是一个负的有理数则定义 ‘hash(x)’ 为 ‘-hash(-x)’。
     如果结果哈希值为 ‘-1’ 则将其替换为 ‘-2’。

   - 特定值 ‘sys.hash_info.inf’, ‘-sys.hash_info.inf’ 和
     ‘sys.hash_info.nan’ 被用作正无穷、负无穷和空值（所分别对应的）哈希
     值。 （所有可哈希的空值都具有相同的哈希值。）

   - 对于一个 *note complex: 18a. 值 ‘z’，会通过计算 ‘hash(z.real) +
     sys.hash_info.imag * hash(z.imag)’ 将实部和虚部的哈希值结合起来，并
     进行降模 ‘2**sys.hash_info.width’ 以使其处于
     ‘range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width -
     1))’ 范围之内。 同样地，如果结果为 ‘-1’ 则将其替换为 ‘-2’。

为了阐明上述规则，这里有一些等价于内置哈希算法的 Python 代码示例，可用于
计算有理数、*note float: 188. 或 *note complex: 18a. 的哈希值:

     import sys, math

     def hash_fraction(m, n):
         """Compute the hash of a rational number m / n.

         Assumes m and n are integers, with n positive.
         Equivalent to hash(fractions.Fraction(m, n)).

         """
         P = sys.hash_info.modulus
         # Remove common factors of P.  (Unnecessary if m and n already coprime.)
         while m % P == n % P == 0:
             m, n = m // P, n // P

         if n % P == 0:
             hash_value = sys.hash_info.inf
         else:
             # Fermat's Little Theorem: pow(n, P-1, P) is 1, so
             # pow(n, P-2, P) gives the inverse of n modulo P.
             hash_value = (abs(m) % P) * pow(n, P - 2, P) % P
         if m < 0:
             hash_value = -hash_value
         if hash_value == -1:
             hash_value = -2
         return hash_value

     def hash_float(x):
         """Compute the hash of a float x."""

         if math.isnan(x):
             return sys.hash_info.nan
         elif math.isinf(x):
             return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
         else:
             return hash_fraction(*x.as_integer_ratio())

     def hash_complex(z):
         """Compute the hash of a complex number z."""

         hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
         # do a signed reduction modulo 2**sys.hash_info.width
         M = 2**(sys.hash_info.width - 1)
         hash_value = (hash_value & (M - 1)) - (hash_value & M)
         if hash_value == -1:
             hash_value = -2
         return hash_value


File: python.info,  Node: 迭代器类型,  Next: 序列类型 --- list tuple range,  Prev: 数字类型 --- int float complex,  Up: 内置类型

5.4.5 迭代器类型
----------------

Python 支持在容器中进行迭代的概念。 这是通过使用两个单独方法来实现的；它
们被用于允许用户自定义类对迭代的支持。 将在下文中详细描述的序列总是支持
迭代方法。

容器对象要提供迭代支持，必须定义一个方法:

 -- 方法: container.__iter__ ()

     返回一个迭代器对象。 该对象需要支持下文所述的迭代器协议。 如果容器
     支持不同的迭代类型，则可以提供额外的方法来专门地请求不同迭代类型的
     迭代器。 （支持多种迭代形式的对象的例子有同时支持广度优先和深度优先
     遍历的树结构。） 此方法对应于 Python/C API 中 Python 对象类型结构体
     的 *note tp_iter: e38. 槽位。

迭代器对象自身需要支持以下两个方法，它们共同组成了 `迭代器协议':

 -- 方法: iterator.__iter__ ()

     返回迭代器对象本身。 这是同时允许容器和迭代器配合 *note for: c38. 和
     *note in: 7ac. 语句使用所必须的。 此方法对应于 Python/C API 中
     Python 对象类型结构体的 *note tp_iter: e38. 槽位。

 -- 方法: iterator.__next__ ()

     从容器中返回下一项。 如果已经没有项可返回，则会引发 *note
     StopIteration: 48e. 异常。 此方法对应于 Python/C API 中 Python 对象
     类型结构体的 *note tp_iternext: e39. 槽位。

Python 定义了几种迭代器对象以支持对一般和特定序列类型、字典和其他更特别
的形式进行迭代。 除了迭代器协议的实现，特定类型的其他性质对迭代操作来说
都不重要。

一旦迭代器的 *note __next__(): c6c. 方法引发了 *note StopIteration:
48e.，它必须一直对后续调用引发同样的异常。 不遵循此行为特性的实现将无法
正常使用。

* Menu:

* 生成器类型::


File: python.info,  Node: 生成器类型,  Up: 迭代器类型

5.4.5.1 生成器类型
..................

Python 的 *note generator: 9aa. 提供了一种实现迭代器协议的便捷方式。 如
果容器对象 *note __iter__(): 517. 方法被实现为一个生成器，它将自动返回一
个迭代器对象（从技术上说是一个生成器对象），该对象提供 *note __iter__():
517. 和 *note __next__(): 12ea. 方法。 有关生成器的更多信息可以参阅
*note yield 表达式的文档: 1510.。


File: python.info,  Node: 序列类型 --- list tuple range,  Next: 文本序列类型 --- str,  Prev: 迭代器类型,  Up: 内置类型

5.4.6 序列类型 — ‘list’, ‘tuple’, ‘range’
-----------------------------------------

有三种基本序列类型：list, tuple 和 range 对象。 为处理 *note 二进制数据:
15f8. 和 *note 文本字符串: 1233. 而特别定制的附加序列类型会在专门的小节
中描述。

* Menu:

* 通用序列操作::
* 不可变序列类型::
* 可变序列类型::
* 列表: 列表<2>.
* 元组::
* range 对象::


File: python.info,  Node: 通用序列操作,  Next: 不可变序列类型,  Up: 序列类型 --- list tuple range

5.4.6.1 通用序列操作
....................

大多数序列类型，包括可变类型和不可变类型都支持下表中的操作。 *note
collections.abc.Sequence: 1640. ABC 被提供用来更容易地在自定义序列类型上
正确地实现这些操作。

此表按优先级升序列出了序列操作。 在表格中，`s' 和 `t' 是具有相同类型的序
列，`n', `i', `j' 和 `k' 是整数而 `x' 是任何满足 `s' 所规定的类型和值限
制的任意对象。

‘in’ 和 ‘not in’ 操作具有与比较操作相同的优先级。 ‘+’ (拼接) 和 ‘*’ (重
复) 操作具有与对应数值运算相同的优先级。 (1)

运算                           结果：                               注释
                                                                    
-----------------------------------------------------------------------------------
                                                                    
‘x in s’                       如果 `s' 中的某项等于 `x' 则结果为   (1)
                               ‘True’，否则为 ‘False’               
                               
                                                                    
‘x not in s’                   如果 `s' 中的某项等于 `x' 则结果为   (1)
                               ‘False’，否则为 ‘True’               
                               
                                                                    
‘s + t’                        `s' 与 `t' 相拼接                    (6)(7)
                                                                    
                                                                    
‘s * n’ 或 ‘n * s’             相当于 `s' 与自身进行 `n' 次拼接     (2)(7)
                                                                    
                                                                    
‘s[i]’                         `s' 的第 `i' 项，起始为 0            (3)
                                                                    
                                                                    
‘s[i:j]’                       `s' 从 `i' 到 `j' 的切片             (3)(4)
                                                                    
                                                                    
‘s[i:j:k]’                     `s' 从 `i' 到 `j' 步长为 `k' 的切    (3)(5)
                               片                                   
                               
                                                                    
‘len(s)’                       `s' 的长度
                               
                                                                    
‘min(s)’                       `s' 的最小项
                               
                                                                    
‘max(s)’                       `s' 的最大项
                               
                                                                    
‘s.index(x[, i[, j]])’         `x' 在 `s' 中首次出现项的索引号（    (8)
                               索引号在 `i' 或其后且在 `j' 之前）   
                               
                                                                    
‘s.count(x)’                   `x' 在 `s' 中出现的总次数
                               

相同类型的序列也支持比较。 特别地，tuple 和 list 的比较是通过比较对应元
素的字典顺序。 这意味着想要比较结果相等，则每个元素比较结果都必须相等，
并且两个序列长度必须相同。 （完整细节请参阅语言参考的 *note 比较运算:
1551. 部分。）

注释:

  1. 虽然 ‘in’ 和 ‘not in’ 操作在通常情况下仅被用于简单的成员检测，某些
     专门化序列 (例如 *note str: 339, *note bytes: 33a. 和 *note
     bytearray: 33b.) 也使用它们进行子序列检测:

          >>> "gg" in "eggs"
          True

  2. 小于 ‘0’ 的 `n' 值会被当作 ‘0’ 来处理 (生成一个与 `s' 同类型的空序
     列)。 请注意序列 `s' 中的项并不会被拷贝；它们会被多次引用。 这一点
     经常会令 Python 编程新手感到困扰；例如:

          >>> lists = [[]] * 3
          >>> lists
          [[], [], []]
          >>> lists[0].append(3)
          >>> lists
          [[3], [3], [3]]

     具体的原因在于 ‘[[]]’ 是一个包含了一个空列表的单元素列表，所以
     ‘[[]] * 3’ 结果中的三个元素都是对这一个空列表的引用。 修改 ‘lists’
     中的任何一个元素实际上都是对这一个空列表的修改。 你可以用以下方式创
     建以不同列表为元素的列表:

          >>> lists = [[] for i in range(3)]
          >>> lists[0].append(3)
          >>> lists[1].append(5)
          >>> lists[2].append(7)
          >>> lists
          [[3], [5], [7]]

     进一步的解释可以在 FAQ 条目 *note 如何创建多维列表？: 1641. 中查看
     。

  3. 如果 `i' 或 `j' 为负值，则索引顺序是相对于序列 `s' 的末尾: 索引号会
     被替换为 ‘len(s) + i’ 或 ‘len(s) + j’。 但要注意 ‘-0’ 仍然为 ‘0’。

  4. `s' 从 `i' 到 `j' 的切片被定义为所有满足 ‘i <= k < j’ 的索引号 `k'
     的项组成的序列。 如果 `i' 或 `j' 大于 ‘len(s)’，则使用 ‘len(s)’。 如
     果 `i' 被省略或为 ‘None’，则使用 ‘0’。 如果 `j' 被省略或为 ‘None’，
     则使用 ‘len(s)’。 如果 `i' 大于等于 `j'，则切片为空。

  5. `s' 从 `i' 到 `j' 步长为 `k' 的切片被定义为所有满足 ‘0 <= n <
     (j-i)/k’ 的索引号 ‘x = i + n*k’ 的项组成的序列。 换句话说，索引号为
     ‘i’, ‘i+k’, ‘i+2*k’, ‘i+3*k’，以此类推，当达到 `j' 时停止 (但一定不
     包括 `j')。 当 `k' 为正值时，`i' 和 `j' 会被减至不大于 ‘len(s)’。 当
     `k' 为负值时，`i' 和 `j' 会被减至不大于 ‘len(s) - 1’。 如果 `i' 或
     `j' 被省略或为 ‘None’，它们会成为“终止”值 (是哪一端的终止值则取决于
     `k' 的符号)。 请注意，`k' 不可为零。 如果 `k' 为 ‘None’，则当作 ‘1’
     处理。

  6. 拼接不可变序列总是会生成新的对象。 这意味着通过重复拼接来构建序列的
     运行时开销将会基于序列总长度的乘方。 想要获得线性的运行时开销，你必
     须改用下列替代方案之一：

        * 如果拼接 *note str: 339. 对象，你可以构建一个列表并在最后使用
          *note str.join(): 1642. 或是写入一个 *note io.StringIO: 836. 实
          例并在结束时获取它的值

        * 如果拼接 *note bytes: 33a. 对象，你可以类似地使用 *note
          bytes.join(): 1643. 或 *note io.BytesIO: 7a4.，或者你也可以使
          用 *note bytearray: 33b. 对象进行原地拼接。 *note bytearray:
          33b. 对象是可变的，并且具有高效的重分配机制

        * 如果拼接 *note tuple: 486. 对象，请改为扩展 *note list: 263. 类

        * 对于其它类型，请查看相应的文档

  7. 某些序列类型 (例如 *note range: 9c6.) 仅支持遵循特定模式的项序列，
     因此并不支持序列拼接或重复。

  8. 当 `x' 在 `s' 中找不到时 ‘index’ 会引发 *note ValueError: 1fc.。 不
     是所有实现都支持传入额外参数 `i' 和 `j'。 这两个参数允许高效地搜索
     序列的子序列。 传入这两个额外参数大致相当于使用 ‘s[i:j].index(x)’，
     但是不会复制任何数据，并且返回的索引是相对于序列的开头而非切片的开
     头。

   ---------- Footnotes ----------

   (1) (3) 它们必须如此，因为解析器无法区分这些操作数的类型。


File: python.info,  Node: 不可变序列类型,  Next: 可变序列类型,  Prev: 通用序列操作,  Up: 序列类型 --- list tuple range

5.4.6.2 不可变序列类型
......................

不可变序列类型普遍实现而可变序列类型未实现的唯一操作就是对 *note hash():
9cc. 内置函数的支持。

这种支持允许不可变类型，例如 *note tuple: 486. 实例被用作 *note dict:
1b9. 键，以及存储在 *note set: b77. 和 *note frozenset: bf6. 实例中。

尝试对包含有不可哈希值的不可变序列进行哈希运算将会导致 *note TypeError:
193.。


File: python.info,  Node: 可变序列类型,  Next: 列表<2>,  Prev: 不可变序列类型,  Up: 序列类型 --- list tuple range

5.4.6.3 可变序列类型
....................

以下表格中的操作是在可变序列类型上定义的。 *note
collections.abc.MutableSequence: 6b5. ABC 被提供用来更容易地在自定义序列
类型上正确实现这些操作。

表格中的 `s' 是可变序列类型的实例，`t' 是任意可迭代对象，而 `x' 是符合对
`s' 所规定类型与值限制的任何对象 (例如，*note bytearray: 33b. 仅接受满足
‘0 <= x <= 255’ 值限制的整数)。

运算                               结果：                               注释
                                                                        
--------------------------------------------------------------------------------------------------
                                                                        
‘s[i] = x’                         将 `s' 的第 `i' 项替换为 `x'
                                   
                                                                        
‘s[i:j] = t’                       将 `s' 从 `i' 到 `j' 的切片替换为
                                   可迭代对象 `t' 的内容
                                   
                                                                        
‘del s[i:j]’                       等同于 ‘s[i:j] = []’
                                   
                                                                        
‘s[i:j:k] = t’                     将 ‘s[i:j:k]’ 的元素替换为 `t' 的    (1)
                                   元素                                 
                                   
                                                                        
‘del s[i:j:k]’                     从列表中移除 ‘s[i:j:k]’ 的元素
                                   
                                                                        
‘s.append(x)’                      将 `x' 添加到序列的末尾 (等同于
                                   ‘s[len(s):len(s)] = [x]’)
                                   
                                                                        
‘s.clear()’                        从 `s' 中移除所有项 (等同于 ‘del     (5)
                                   s[:]’)                               
                                   
                                                                        
‘s.copy()’                         创建 `s' 的浅拷贝 (等同于 ‘s[:]’)    (5)
                                                                        
                                                                        
‘s.extend(t)’ 或 ‘s += t’          用 `t' 的内容扩展 `s' (基本上等同
                                   于 ‘s[len(s):len(s)] = t’)
                                   
                                                                        
‘s *= n’                           使用 `s' 的内容重复 `n' 次来对其进   (6)
                                   行更新                               
                                   
                                                                        
‘s.insert(i, x)’                   在由 `i' 给出的索引位置将 `x' 插入
                                   `s' (等同于 ‘s[i:i] = [x]’)
                                   
                                                                        
‘s.pop()’ or ‘s.pop(i)’            提取在 `i' 位置上的项，并将其从      (2)
                                   `s' 中移除                           
                                   
                                                                        
‘s.remove(x)’                      删除 `s' 中第一个 ‘s[i]’ 等于 `x'    (3)
                                   的项目。                             
                                   
                                                                        
‘s.reverse()’                      就地将列表中的元素逆序。             (4)
                                                                        

注释:

  1. `t' 必须与它所替换的切片具有相同的长度。

  2. 可选参数 `i' 默认为 ‘-1’，因此在默认情况下会移除并返回最后一项。

  3. 当在 `s' 中找不到 `x' 时 ‘remove()’ 操作会引发 *note ValueError:
     1fc.。

  4. 当反转大尺寸序列时 ‘reverse()’ 方法会原地修改该序列以保证空间经济性
     。 为提醒用户此操作是通过间接影响进行的，它并不会返回反转后的序列。

  5. 包括 ‘clear()’ 和 ‘copy()’ 是为了与不支持切片操作的可变容器 (例如
     *note dict: 1b9. 和 *note set: b77.) 的接口保持一致。 ‘copy()’ 不是
     *note collections.abc.MutableSequence: 6b5. ABC 的一部分，但大多数
     具体的可变序列类都提供了它。

     3.3 新版功能: ‘clear()’ 和 ‘copy()’ 方法。

  6. `n' 值为一个整数，或是一个实现了 *note __index__(): 18b. 的对象。
     `n' 值为零或负数将清空序列。 序列中的项不会被拷贝；它们会被多次引用
     ，正如 *note 通用序列操作: 163f. 中有关 ‘s * n’ 的说明。


File: python.info,  Node: 列表<2>,  Next: 元组,  Prev: 可变序列类型,  Up: 序列类型 --- list tuple range

5.4.6.4 列表
............

列表是可变序列，通常用于存放同类项目的集合（其中精确的相似程度将根据应用
而变化）。

 -- 类: list ([iterable])

     可以用多种方式构建列表：

        * 使用一对方括号来表示空列表: ‘[]’

        * 使用方括号，其中的项以逗号分隔: ‘[a]’, ‘[a, b, c]’

        * 使用列表推导式: ‘[x for x in iterable]’

        * 使用类型的构造器: ‘list()’ 或 ‘list(iterable)’

     构造器将构造一个列表，其中的项与 `iterable' 中的项具有相同的的值与
     顺序。 `iterable' 可以是序列、支持迭代的容器或其它可迭代对象。 如果
     `iterable' 已经是一个列表，将创建并返回其副本，类似于
     ‘iterable[:]’。 例如，‘list('abc')’ 返回 ‘['a', 'b', 'c']’ 而
     ‘list( (1, 2, 3) )’ 返回 ‘[1, 2, 3]’。 如果没有给出参数，构造器将创
     建一个空列表 ‘[]’。

     其它许多操作也会产生列表，包括 *note sorted(): 44c. 内置函数。

     列表实现了所有 *note 一般: 163f. 和 *note 可变: 15f5. 序列的操作。
     列表还额外提供了以下方法：

      -- 方法: sort (*, key=None, reverse=False)

          此方法会对列表进行原地排序，只使用 ‘<’ 来进行各项间比较。 异常
          不会被屏蔽 —— 如果有任何比较操作失败，整个排序操作将失败（而列
          表可能会处于被部分修改的状态）。

          *note sort(): 44d. 接受两个仅限以关键字形式传入的参数 (*note
          仅限关键字参数: 2ad.):

          `key' 指定带有一个参数的函数，用于从每个列表元素中提取比较键
          (例如 ‘key=str.lower’)。 对应于列表中每一项的键会被计算一次，
          然后在整个排序过程中使用。 默认值 ‘None’ 表示直接对列表项排序
          而不计算一个单独的键值。

          可以使用 *note functools.cmp_to_key(): b5e. 将 2.x 风格的
          `cmp' 函数转换为 `key' 函数。

          `reverse' 为一个布尔值。 如果设为 ‘True’，则每个列表元素将按反
          向顺序比较进行排序。

          当顺序大尺寸序列时此方法会原地修改该序列以保证空间经济性。 为
          提醒用户此操作是通过间接影响进行的，它并不会返回排序后的序列（
          请使用 *note sorted(): 44c. 显示地请求一个新的已排序列表实例）
          。

          *note sort(): 44d. 方法确保是稳定的。 如果一个排序确保不会改变
          比较结果相等的元素的相对顺序就称其为稳定的 — 这有利于进行多重
          排序（例如先按部门、再接薪级排序）。

          有关排序示例和简要排序教程，请参阅 *note 排序指南: 1611. 。

          `CPython implementation detail:' 在一个列表被排序期间，尝试改
          变甚至进行检测也会造成未定义的影响。 Python 的 C 实现会在排序
          期间将列表显示为空，如果发现列表在排序期间被改变将会引发 *note
          ValueError: 1fc.。


File: python.info,  Node: 元组,  Next: range 对象,  Prev: 列表<2>,  Up: 序列类型 --- list tuple range

5.4.6.5 元组
............

元组是不可变序列，通常用于储存异构数据的多项集（例如由 *note
enumerate(): deb. 内置函数所产生的二元组）。 元组也被用于需要同构数据的
不可变序列的情况（例如允许存储到 *note set: b77. 或 *note dict: 1b9. 的
实例）。

 -- 类: tuple ([iterable])

     可以用多种方式构建元组：

        * 使用一对圆括号来表示空元组: ‘()’

        * 使用一个后缀的逗号来表示单元组: ‘a,’ 或 ‘(a,)’

        * 使用以逗号分隔的多个项: ‘a, b, c’ or ‘(a, b, c)’

        * 使用内置的 *note tuple(): 486.: ‘tuple()’ 或 ‘tuple(iterable)’

     构造器将构造一个元组，其中的项与 `iterable' 中的项具有相同的值与顺
     序。 `iterable' 可以是序列、支持迭代的容器或其他可迭代对象。 如果
     `iterable' 已经是一个元组，会不加改变地将其返回。 例如，
     ‘tuple('abc')’ 返回 ‘('a', 'b', 'c')’ 而 ‘tuple( [1, 2, 3] )’ 返回
     ‘(1, 2, 3)’。 如果没有给出参数，构造器将创建一个空元组 ‘()’。

     请注意决定生成元组的其实是逗号而不是圆括号。 圆括号只是可选的，生成
     空元组或需要避免语法歧义的情况除外。 例如，‘f(a, b, c)’ 是在调用函
     数时附带三个参数，而 ‘f((a, b, c))’ 则是在调用函数时附带一个三元组
     。

     元组实现了所有 *note 一般: 163f. 序列的操作。

对于通过名称访问相比通过索引访问更清晰的异构数据多项集，*note
collections.namedtuple(): 1b7. 可能是比简单元组对象更为合适的选择。


File: python.info,  Node: range 对象,  Prev: 元组,  Up: 序列类型 --- list tuple range

5.4.6.6 range 对象
..................

*note range: 9c6. 类型表示不可变的数字序列，通常用于在 *note for: c38. 循
环中循环指定的次数。

 -- 类: range (stop)

 -- 类: range (start, stop[, step])

     range 构造器的参数必须为整数（可以是内置的 *note int: 185. 或任何实
     现了 ‘__index__’ 特殊方法的对象）。 如果省略 `step' 参数，其默认值
     为 ‘1’。 如果省略 `start' 参数，其默认值为 ‘0’，如果 `step' 为零则
     会引发 *note ValueError: 1fc.。

     如果 `step' 为正值，确定 range ‘r’ 内容的公式为 ‘r[i] = start +
     step*i’ 其中 ‘i >= 0’ 且 ‘r[i] < stop’。

     如果 `step' 为负值，确定 range 内容的公式仍然为 ‘r[i] = start +
     step*i’，但限制条件改为 ‘i >= 0’ 且 ‘r[i] > stop’.

     如果 ‘r[0]’ 不符合值的限制条件，则该 range 对象为空。 range 对象确
     实支持负索引，但是会将其解读为从正索引所确定的序列的末尾开始索引。

     元素绝对值大于 *note sys.maxsize: b4b. 的 range 对象是被允许的，但
     某些特性 (例如 *note len(): 151.) 可能引发 *note OverflowError:
     968.。

     一些 range 对象的例子:

          >>> list(range(10))
          [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
          >>> list(range(1, 11))
          [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
          >>> list(range(0, 30, 5))
          [0, 5, 10, 15, 20, 25]
          >>> list(range(0, 10, 3))
          [0, 3, 6, 9]
          >>> list(range(0, -10, -1))
          [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
          >>> list(range(0))
          []
          >>> list(range(1, 0))
          []

     range 对象实现了 *note 一般: 163f. 序列的所有操作，但拼接和重复除外
     （这是由于 range 对象只能表示符合严格模式的序列，而重复和拼接通常都
     会违反这样的模式）。

      -- 属性: start

          `start' 形参的值 (如果该形参未提供则为 ‘0’)

      -- 属性: stop

          `stop' 形参的值

      -- 属性: step

          `step' 形参的值 (如果该形参未提供则为 ‘1’)

*note range: 9c6. 类型相比常规 *note list: 263. 或 *note tuple: 486. 的
优势在于一个 *note range: 9c6. 对象总是占用固定数量的（较小）内存，不论
其所表示的范围有多大（因为它只保存了 ‘start’, ‘stop’ 和 ‘step’ 值，并会
根据需要计算具体单项或子范围的值）。

range 对象实现了 *note collections.abc.Sequence: 1640. ABC，提供如包含检
测、元素索引查找、切片等特性，并支持负索引 (参见 *note 序列类型 — list,
tuple, range: 1280.):

     >>> r = range(0, 20, 2)
     >>> r
     range(0, 20, 2)
     >>> 11 in r
     False
     >>> 10 in r
     True
     >>> r.index(10)
     5
     >>> r[5]
     10
     >>> r[:5]
     range(0, 10, 2)
     >>> r[-1]
     18

使用 ‘==’ 和 ‘!=’ 检测 range 对象是否相等是将其作为序列来比较。 也就是说
，如果两个 range 对象表示相同的值序列就认为它们是相等的。 （请注意比较结
果相等的两个 range 对象可能会具有不同的 *note start: 164a, *note stop:
164b. 和 *note step: 164c. 属性，例如 ‘range(0) == range(2, 1, 3)’ 而
‘range(0, 3, 2) == range(0, 4, 2)’。）

在 3.2 版更改: 实现 Sequence ABC。 支持切片和负数索引。 使用 *note int:
185. 对象在固定时间内进行成员检测，而不是逐一迭代所有项。

在 3.3 版更改: 定义 ’==’ 和 ’!=’ 以根据 range 对象所定义的值序列来进行比
较（而不是根据对象的标识）。

3.3 新版功能: *note start: 164a, *note stop: 164b. 和 *note step: 164c.
属性。

参见
....

   * linspace recipe(1) 演示了如何实现一个延迟求值版本的适合浮点数应用的
     range 对象。

   ---------- Footnotes ----------

   (1) http://code.activestate.com/recipes/579000/


File: python.info,  Node: 文本序列类型 --- str,  Next: 二进制序列类型 --- bytes bytearray memoryview,  Prev: 序列类型 --- list tuple range,  Up: 内置类型

5.4.7 文本序列类型 — ‘str’
--------------------------

在 Python 中处理文本数据是使用 *note str: 339. 对象，也称为 `字符串'。 字
符串是由 Unicode 码位构成的不可变 *note 序列: 1280.。 字符串字面值有多种
不同的写法：

   * 单引号: ‘'允许包含有 "双" 引号'’

   * 双引号: ‘"允许包含有 '单' 引号"’。

   * 三重引号: ‘'''三重单引号'''’, ‘"""三重双引号"""’

使用三重引号的字符串可以跨越多行 —— 其中所有的空白字符都将包含在该字符串
字面值中。

作为单一表达式组成部分，之间只由空格分隔的多个字符串字面值会被隐式地转换
为单个字符串字面值。 也就是说，‘("spam " "eggs") == "spam eggs"’。

请参阅 *note 字符串和字节串字面值: 13f3. 有解有关不同字符串字面值的更多
信息，包括所支持的转义序列，以及使用 ‘r’ ("raw") 前缀来禁用大多数转义序
列的处理。

字符串也可以通过使用 *note str: 339. 构造器从其他对象创建。

由于不存在单独的“字符”类型，对字符串做索引操作将产生一个长度为 1 的字符
串。 也就是说，对于一个非空字符串 `s', ‘s[0] == s[0:1]’。

不存在可变的字符串类型，但是 *note str.join(): 1642. 或 *note
io.StringIO: 836. 可以被被用来根据多个片段高效率地构建字符串。

在 3.3 版更改: 为了与 Python 2 系列的向下兼容，再次允许字符串字面值使用
‘u’ 前缀。 它对字符串字面值的含义没有影响，并且不能与 ‘r’ 前缀同时出现。

 -- 类: str (object='')

 -- 类: str (object=b'', encoding='utf-8', errors='strict')

     返回 `object' 的 *note 字符串: 1233. 版本。 如果未提供 `object' 则
     返回空字符串。 在其他情况下 ‘str()’ 的行为取决于 `encoding' 或
     `errors' 是否有给出，具体见下。

     如果 `encoding' 或 `errors' 均未给出，‘str(object)’ 返回 *note
     object.__str__(): e3f.，这是 `object' 的“非正式”或格式良好的字符串
     表示。 对于字符串对象，这是该字符串本身。 如果 `object' 没有 *note
     __str__(): e3f. 方法，则 *note str(): 339. 将回退为返回 *note
     repr(object): 7d5.。

     如果 `encoding' 或 `errors' 至少给出其中之一，则 `object' 应该是一
     个 *note bytes-like object: 5f1. (例如 *note bytes: 33a. 或 *note
     bytearray: 33b.)。 在此情况下，如果 `object' 是一个 *note bytes:
     33a. (或 *note bytearray: 33b.) 对象，则 ‘str(bytes, encoding,
     errors)’ 等价于 *note bytes.decode(encoding, errors): c40.。 否则的
     话，会在调用 *note bytes.decode(): c40. 之前获取缓冲区对象下层的
     bytes 对象。 请参阅 *note 二进制序列类型 — bytes, bytearray,
     memoryview: 15f8. 与 *note 缓冲协议: 15f7. 了解有关缓冲区对象的信息
     。

     将一个 *note bytes: 33a. 对象传入 *note str(): 339. 而不给出
     `encoding' 或 `errors' 参数的操作属于第一种情况， 将返回非正式的字
     符串表示（另请参阅 Python 的 *note -b: 41d. 命令行选项）。 例如:

          >>> str(b'Zoot!')
          "b'Zoot!'"

     有关 ‘str’ 类及其方法的更多信息，请参阅下面的 *note 文本序列类型 —
     str: 1233. 和 *note 字符串的方法: 1234. 小节。 要输出格式化字符串，
     请参阅 *note 格式化字符串字面值: 15d. 和 *note 格式字符串语法: d22.
     小节。 此外还可以参阅 *note 文本处理服务: 164e. 小节。

* Menu:

* 字符串的方法: 字符串的方法<2>.
* printf 风格的字符串格式化::


File: python.info,  Node: 字符串的方法<2>,  Next: printf 风格的字符串格式化,  Up: 文本序列类型 --- str

5.4.7.1 字符串的方法
....................

字符串实现了所有 *note 一般: 163f. 序列的操作，还额外提供了以下列出的一
些附加方法。

字符串还支持两种字符串格式化样式，一种提供了很大程度的灵活性和可定制性
(参阅 *note str.format(): 4e2, *note 格式字符串语法: d22. 和 *note
自定义字符串格式化: 1650.) 而另一种是基于 C ‘printf’ 样式的格式化，它可
处理的类型范围较窄，并且更难以正确使用，但对于它可处理的情况往往会更为快
速 (*note printf 风格的字符串格式化: 1235.)。

标准库的 *note 文本处理服务: 1651. 部分涵盖了许多其他模块，提供各种文本
相关工具（例如包含于 *note re: de. 模块中的正则表达式支持）。

 -- 方法: str.capitalize ()

     返回原字符串的副本，其首个字符大写，其余为小写。

     在 3.8 版更改: 第一个字符现在被放入了 titlecase 而不是 uppercase。
     这意味着复合字母类字符将只有首个字母改为大写，而再不是全部字符大写
     。

 -- 方法: str.casefold ()

     返回原字符串消除大小写的副本。 消除大小写的字符串可用于忽略大小写的
     匹配。

     消除大小写类似于转为小写，但是更加彻底一些，因为它会移除字符串中的
     所有大小写变化形式。 例如，德语小写字母 ‘'ß'’ 相当于 ‘"ss"’。 由于
     它已经是小写了，*note lower(): 1653. 不会对 ‘'ß'’ 做任何改变；而
     *note casefold(): 6b9. 则会将其转换为 ‘"ss"’。

     消除大小写算法的描述请参见 Unicode 标准的 3.13 节。

     3.3 新版功能.

 -- 方法: str.center (width[, fillchar])

     返回长度为 `width' 的字符串，原字符串在其正中。 使用指定的
     `fillchar' 填充两边的空位（默认使用 ASCII 空格符）。 如果 `width' 小
     于等于 ‘len(s)’ 则返回原字符串的副本。

 -- 方法: str.count (sub[, start[, end]])

     返回子字符串 `sub' 在 [`start', `end'] 范围内非重叠出现的次数。 可
     选参数 `start' 与 `end' 会被解读为切片表示法。

 -- 方法: str.encode (encoding="utf-8", errors="strict")

     返回原字符串编码为字节串对象的版本。 默认编码为 ‘'utf-8'’。 可以给
     出 `errors' 来设置不同的错误处理方案。 `errors' 的默认值为
     ‘'strict'’，表示编码错误会引发 *note UnicodeError: c43.。 其他可用
     的值为 ‘'ignore'’, ‘'replace'’, ‘'xmlcharrefreplace'’,
     ‘'backslashreplace'’ 以及任何其他通过 *note
     codecs.register_error(): dfd. 注册的值，请参阅 *note 错误处理方案:
     1371. 小节。 要查看可用的编码列表，请参阅 *note 标准编码: 698. 小节
     。

     在 3.1 版更改: 加入了对关键字参数的支持。

 -- 方法: str.endswith (suffix[, start[, end]])

     如果字符串以指定的 `suffix' 结束返回 ‘True’，否则返回 ‘False’。
     `suffix' 也可以为由多个供查找的后缀构成的元组。 如果有可选项
     `start'，将从所指定位置开始检查。 如果有可选项 `end'，将在所指定位
     置停止比较。

 -- 方法: str.expandtabs (tabsize=8)

     返回字符串的副本，其中所有的制表符会由一个或多个空格替换，具体取决
     于当前列位置和给定的制表符宽度。 每 `tabsize' 个字符设为一个制表位
     （默认值 8 时设定的制表位在列 0, 8, 16 依次类推）。 要展开字符串，
     当前列将被设为零并逐一检查字符串中的每个字符。 如果字符为制表符
     (‘\t’)，则会在结果中插入一个或多个空格符，直到当前列等于下一个制表
     位。 （制表符本身不会被复制。） 如果字符为换行符 (‘\n’) 或回车符
     (‘\r’)，它会被复制并将当前列重设为零。 任何其他字符会被不加修改地复
     制并将当前列加一，不论该字符在被打印时会如何显示。

          >>> '01\t012\t0123\t01234'.expandtabs()
          '01      012     0123    01234'
          >>> '01\t012\t0123\t01234'.expandtabs(4)
          '01  012 0123    01234'

 -- 方法: str.find (sub[, start[, end]])

     返回子字符串 `sub' 在 ‘s[start:end]’ 切片内被找到的最小索引。 可选
     参数 `start' 与 `end' 会被解读为切片表示法。 如果 `sub' 未被找到则
     返回 ‘-1’。

          注解: *note find(): 7a8. 方法应该只在你需要知道 `sub' 所在位置
          时使用。 要检查 `sub' 是否为子字符串，请使用 *note in: 7ac. 操
          作符:

               >>> 'Py' in 'Python'
               True

 -- 方法: str.format (*args, **kwargs)

     执行字符串格式化操作。 调用此方法的字符串可以包含字符串字面值或者以
     花括号 ‘{}’ 括起来的替换域。 每个替换域可以包含一个位置参数的数字索
     引，或者一个关键字参数的名称。 返回的字符串副本中每个替换域都会被替
     换为对应参数的字符串值。

          >>> "The sum of 1 + 2 is {0}".format(1+2)
          'The sum of 1 + 2 is 3'

     请参阅 *note 格式字符串语法: d22. 了解有关可以在格式字符串中指定的
     各种格式选项的说明。

          注解: 当使用 ‘n’ 类型 (例如: ‘'{:n}'.format(1234)’) 来格式化数
          字 (*note int: 185, *note float: 188, *note complex: 18a,
          *note decimal.Decimal: 189. 及其子类) 的时候，该函数会临时性地
          将 ‘LC_CTYPE’ 区域设置为 ‘LC_NUMERIC’ 区域以解码
          ‘localeconv()’ 的 ‘decimal_point’ 和 ‘thousands_sep’ 字段，如
          果它们是非 ASCII 字符或长度超过 1 字节的话，并且 ‘LC_NUMERIC’
          区域会与 ‘LC_CTYPE’ 区域不一致。 这个临时更改会影响其他线程。

     在 3.7 版更改: 当使用 ‘n’ 类型格式化数字时，该函数在某些情况下会临
     时性地将 ‘LC_CTYPE’ 区域设置为 ‘LC_NUMERIC’ 区域。

 -- 方法: str.format_map (mapping)

     类似于 ‘str.format(**mapping)’，不同之处在于 ‘mapping’ 会被直接使用
     而不是复制到一个 *note dict: 1b9.。 适宜使用此方法的一个例子是当
     ‘mapping’ 为 dict 的子类的情况：

          >>> class Default(dict):
          ...     def __missing__(self, key):
          ...         return key
          ...
          >>> '{name} was born in {country}'.format_map(Default(name='Guido'))
          'Guido was born in country'

     3.2 新版功能.

 -- 方法: str.index (sub[, start[, end]])

     类似于 *note find(): 7a8.，但在找不到子类时会引发 *note ValueError:
     1fc.。

 -- 方法: str.isalnum ()

     如果字符串中的所有字符都是字母或数字且至少有一个字符，则返回 ‘True’
     ， 否则返回 ‘False’ 。 如果 ‘c.isalpha()’ ， ‘c.isdecimal()’ ，
     ‘c.isdigit()’ ，或 ‘c.isnumeric()’ 之中有一个返回 ‘True’ ，则字符
     ‘‘c‘‘是字母或数字。

 -- 方法: str.isalpha ()

     如果字符串中的所有字符都是字母，并且至少有一个字符，返回 ‘True’ ，
     否则返回 ‘False’ 。字母字符是指那些在 Unicode 字符数据库中定义为
     "Letter" 的字符，即那些具有 "Lm"、"Lt"、"Lu"、"Ll" 或 "Lo" 之一的通
     用类别属性的字符。 注意，这与 Unicode 标准中定义的"字母"属性不同。

 -- 方法: str.isascii ()

     如果字符串为空或字符串中的所有字符都是 ASCII ，返回 ‘True’ ，否则返
     回 ‘False’ 。ASCII 字符的码点范围是 U+0000-U+007F 。

     3.7 新版功能.

 -- 方法: str.isdecimal ()

     如果字符串中的所有字符都是十进制字符且该字符串至少有一个字符，则返
     回 ‘True’ ， 否则返回 ‘False’ 。十进制字符指那些可以用来组成10进制
     数字的字符，例如 U+0660 ，即阿拉伯字母数字0 。 严格地讲，十进制字符
     是 Unicode 通用类别 "Nd" 中的一个字符。

 -- 方法: str.isdigit ()

     如果字符串中的所有字符都是数字，并且至少有一个字符，返回 ‘True’ ，
     否则返回 ‘False’ 。 数字包括十进制字符和需要特殊处理的数字，如兼容
     性上标数字。这包括了不能用来组成十进制数的数字，如 Kharosthi 数。 严
     格地讲，数字是指属性值为 Numeric_Type=Digit 或 Numeric_Type=Decimal
     的字符。

 -- 方法: str.isidentifier ()

     如果字符串是有效的标识符，返回 ‘True’ ，依据语言定义， *note
     标识符和关键字: 13e4. 节。

     调用 *note keyword.iskeyword(): 165c. 来检测字符串 ‘s’ 是否为保留标
     识符，例如 *note def: dc6. 和 *note class: c72.。

     示例：

          >>> from keyword import iskeyword

          >>> 'hello'.isidentifier(), iskeyword('hello')
          True, False
          >>> 'def'.isidentifier(), iskeyword('def')
          True, True

 -- 方法: str.islower ()

     如果字符串中至少有一个区分大小写的字符 (1) 且此类字符均为小写则返回
     ‘True’ ，否则返回 ‘False’ 。

 -- 方法: str.isnumeric ()

     如果字符串中至少有一个字符且所有字符均为数值字符则返回 ‘True’ ，否
     则返回 ‘False’ 。 数值字符包括数字字符，以及所有在 Unicode 中设置了
     数值特性属性的字符，例如 U+2155, VULGAR FRACTION ONE FIFTH。 正式的
     定义为：数值字符就是具有特征属性值 Numeric_Type=Digit,
     Numeric_Type=Decimal 或 Numeric_Type=Numeric 的字符。

 -- 方法: str.isprintable ()

     如果字符串中所有字符均为可打印字符或字符串为空则返回 ‘True’ ，否则
     返回 ‘False’ 。 不可打印字符是在 Unicode 字符数据库中被定义为
     "Other" 或 "Separator" 的字符，例外情况是 ASCII 空格字符 (0x20) 被
     视作可打印字符。 （请注意在此语境下可打印字符是指当对一个字符串发起
     调用 *note repr(): 7d5. 时不必被转义的字符。 它们与字符串写入 *note
     sys.stdout: 317. 或 *note sys.stderr: 318. 时所需的处理无关。）

 -- 方法: str.isspace ()

     如果字符串中只有空白字符且至少有一个字符则返回 ‘True’ ，否则返回
     ‘False’ 。

     `空白' 字符是指在 Unicode 字符数据库 (参见 *note unicodedata: 11b.)
     中主要类别为 ‘Zs’ ("Separator, space") 或所属双向类为 ‘WS’, ‘B’ 或
     ‘S’ 的字符。

 -- 方法: str.istitle ()

     如果字符串中至少有一个字符且为标题字符串则返回 ‘True’ ，例如大写字
     符之后只能带非大写字符而小写字符必须有大写字符打头。 否则返回
     ‘False’ 。

 -- 方法: str.isupper ()

     如果字符串中至少有一个区分大小写的字符 (2) 且此类字符均为大写则返回
     ‘True’ ，否则返回 ‘False’ 。

 -- 方法: str.join (iterable)

     返回一个由 `iterable' 中的字符串拼接而成的字符串。 如果 `iterable'
     中存在任何非字符串值包括 *note bytes: 33a. 对象则会引发 *note
     TypeError: 193.。 调用该方法的字符串将作为元素之间的分隔。

 -- 方法: str.ljust (width[, fillchar])

     返回长度为 `width' 的字符串，原字符串在其中靠左对齐。 使用指定的
     `fillchar' 填充空位 (默认使用 ASCII 空格符)。 如果 `width' 小于等于
     ‘len(s)’ 则返回原字符串的副本。

 -- 方法: str.lower ()

     返回原字符串的副本，其所有区分大小写的字符 (3) 均转换为小写。

     所用转换小写算法的描述请参见 Unicode 标准的 3.13 节。

 -- 方法: str.lstrip ([chars])

     返回原字符串的副本，移除其中的前导字符。 `chars' 参数为指定要移除字
     符的字符串。 如果省略或为 ‘None’，则 `chars' 参数默认移除空白符。 实
     际上 `chars' 参数并非指定单个前缀；而是会移除参数值的所有组合:

          >>> '   spacious   '.lstrip()
          'spacious   '
          >>> 'www.example.com'.lstrip('cmowz.')
          'example.com'

 -- 方法: static str.maketrans (x[, y[, z]])

     此静态方法返回一个可供 *note str.translate(): 1663. 使用的转换对照
     表。

     如果只有一个参数，则它必须是一个将 Unicode 码位序号（整数）或字符（
     长度为 1 的字符串）映射到 Unicode 码位序号、（任意长度的）字符串或
     ‘None’ 的字典。 字符键将会被转换为码位序号。

     如果有两个参数，则它们必须是两个长度相等的字符串，并且在结果字典中
     ，x 中每个字符将被映射到 y 中相同位置的字符。 如果有第三个参数，它
     必须是一个字符串，其中的字符将在结果中被映射到 ‘None’。

 -- 方法: str.partition (sep)

     在 `sep' 首次出现的位置拆分字符串，返回一个 3 元组，其中包含分隔符
     之前的部分、分隔符本身，以及分隔符之后的部分。 如果分隔符未找到，则
     返回的 3 元组中包含字符本身以及两个空字符串。

 -- 方法: str.replace (old, new[, count])

     返回字符串的副本，其中出现的所有子字符串 `old' 都将被替换为 `new'。
     如果给出了可选参数 `count'，则只替换前 `count' 次出现。

 -- 方法: str.rfind (sub[, start[, end]])

     返回子字符串 `sub' 在字符串内被找到的最大（最右）索引，这样 `sub' 将
     包含在 ‘s[start:end]’ 当中。 可选参数 `start' 与 `end' 会被解读为切
     片表示法。 如果未找到则返回 ‘-1’。

 -- 方法: str.rindex (sub[, start[, end]])

     类似于 *note rfind(): 7a9.，但在子字符串 `sub' 未找到时会引发 *note
     ValueError: 1fc.。

 -- 方法: str.rjust (width[, fillchar])

     返回长度为 `width' 的字符串，原字符串在其中靠右对齐。 使用指定的
     `fillchar' 填充空位 (默认使用 ASCII 空格符)。 如果 `width' 小于等于
     ‘len(s)’ 则返回原字符串的副本。

 -- 方法: str.rpartition (sep)

     在 `sep' 最后一次出现的位置拆分字符串，返回一个 3 元组，其中包含分
     隔符之前的部分、分隔符本身，以及分隔符之后的部分。 如果分隔符未找到
     ，则返回的 3 元组中包含两个空字符串以及字符串本身。

 -- 方法: str.rsplit (sep=None, maxsplit=-1)

     返回一个由字符串内单词组成的列表，使用 `sep' 作为分隔字符串。 如果
     给出了 `maxsplit'，则最多进行 `maxsplit' 次拆分，从 `最右边' 开始。
     如果 `sep' 未指定或为 ‘None’，任何空白字符串都会被作为分隔符。 除了
     从右边开始拆分，*note rsplit(): 1667. 的其他行为都类似于下文所述的
     *note split(): 7aa.。

 -- 方法: str.rstrip ([chars])

     返回原字符串的副本，移除其中的末尾字符。 `chars' 参数为指定要移除字
     符的字符串。 如果省略或为 ‘None’，则 `chars' 参数默认移除空白符。 实
     际上 `chars' 参数并非指定单个后缀；而是会移除参数值的所有组合:

          >>> '   spacious   '.rstrip()
          '   spacious'
          >>> 'mississippi'.rstrip('ipz')
          'mississ'

 -- 方法: str.split (sep=None, maxsplit=-1)

     返回一个由字符串内单词组成的列表，使用 `sep' 作为分隔字符串。 如果
     给出了 `maxsplit'，则最多进行 `maxsplit' 次拆分（因此，列表最多会有
     ‘maxsplit+1’ 个元素）。 如果 `maxsplit' 未指定或为 ‘-1’，则不限制拆
     分次数（进行所有可能的拆分）。

     如果给出了 `sep'，则连续的分隔符不会被组合在一起而是被视为分隔空字
     符串 (例如 ‘'1,,2'.split(',')’ 将返回 ‘['1', '', '2']’)。 `sep' 参
     数可能由多个字符组成 (例如 ‘'1<>2<>3'.split('<>')’ 将返回 ‘['1',
     '2', '3']’)。 使用指定的分隔符拆分空字符串将返回 ‘['']’。

     例如

          >>> '1,2,3'.split(',')
          ['1', '2', '3']
          >>> '1,2,3'.split(',', maxsplit=1)
          ['1', '2,3']
          >>> '1,2,,3,'.split(',')
          ['1', '2', '', '3', '']

     如果 `sep' 未指定或为 ‘None’，则会应用另一种拆分算法：连续的空格会
     被视为单个分隔符，其结果将不包含开头或末尾的空字符串，如果字符串包
     含前缀或后缀空格的话。 因此，使用 ‘None’ 拆分空字符串或仅包含空格的
     字符串将返回 ‘[]’。

     例如

          >>> '1 2 3'.split()
          ['1', '2', '3']
          >>> '1 2 3'.split(maxsplit=1)
          ['1', '2 3']
          >>> '   1   2   3   '.split()
          ['1', '2', '3']

 -- 方法: str.splitlines ([keepends])

     返回由原字符串中各行组成的列表，在行边界的位置拆分。 结果列表中不包
     含行边界，除非给出了 `keepends' 且为真值。

     此方法会以下列行边界进行拆分。 特别地，行边界是 *note universal
     newlines: 5fd. 的一个超集。

     表示符                      描述
                                 
     --------------------------------------------------------------
                                 
     ‘\n’                        换行
                                 
                                 
     ‘\r’                        回车
                                 
                                 
     ‘\r\n’                      回车 + 换行
                                 
                                 
     ‘\v’ 或 ‘\x0b’              行制表符
                                 
                                 
     ‘\f’ 或 ‘\x0c’              换表单
                                 
                                 
     ‘\x1c’                      文件分隔符
                                 
                                 
     ‘\x1d’                      组分隔符
                                 
                                 
     ‘\x1e’                      记录分隔符
                                 
                                 
     ‘\x85’                      下一行 (C1 控制码)
                                 
                                 
     ‘\u2028’                    行分隔符
                                 
                                 
     ‘\u2029’                    段分隔符
                                 

     在 3.2 版更改: ‘\v’ 和 ‘\f’ 被添加到行边界列表

     例如

          >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
          ['ab c', '', 'de fg', 'kl']
          >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
          ['ab c\n', '\n', 'de fg\r', 'kl\r\n']

     不同于 *note split(): 7aa.，当给出了分隔字符串 `sep' 时，对于空字符
     串此方法将返回一个空列表，而末尾的换行不会令结果中增加额外的行:

          >>> "".splitlines()
          []
          >>> "One line\n".splitlines()
          ['One line']

     作为比较，‘split('\n')’ 的结果为:

          >>> ''.split('\n')
          ['']
          >>> 'Two lines\n'.split('\n')
          ['Two lines', '']

 -- 方法: str.startswith (prefix[, start[, end]])

     如果字符串以指定的 `prefix' 开始则返回 ‘True’，否则返回 ‘False’。
     `prefix' 也可以为由多个供查找的前缀构成的元组。 如果有可选项
     `start'，将从所指定位置开始检查。 如果有可选项 `end'，将在所指定位
     置停止比较。

 -- 方法: str.strip ([chars])

     返回原字符串的副本，移除其中的前导和末尾字符。 `chars' 参数为指定要
     移除字符的字符串。 如果省略或为 ‘None’，则 `chars' 参数默认移除空白
     符。 实际上 `chars' 参数并非指定单个前缀或后缀；而是会移除参数值的
     所有组合:

          >>> '   spacious   '.strip()
          'spacious'
          >>> 'www.example.com'.strip('cmowz.')
          'example'

     最外侧的前导和末尾 `chars' 参数值将从字符串中移除。 开头端的字符的
     移除将在遇到一个未包含于 `chars' 所指定字符集的字符时停止。 类似的
     操作也将在结尾端发生。 例如:

          >>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
          >>> comment_string.strip('.#! ')
          'Section 3.2.1 Issue #32'

 -- 方法: str.swapcase ()

     返回原字符串的副本，其中大写字符转换为小写，反之亦然。 请注意
     ‘s.swapcase().swapcase() == s’ 并不一定为真值。

 -- 方法: str.title ()

     返回原字符串的标题版本，其中每个单词第一个字母为大写，其余字母为小
     写。

     例如

          >>> 'Hello world'.title()
          'Hello World'

     该算法使用一种简单的与语言无关的定义，将连续的字母组合视为单词。 该
     定义在多数情况下都很有效，但它也意味着代表缩写形式与所有格的撇号也
     会成为单词边界，这可能导致不希望的结果:

          >>> "they're bill's friends from the UK".title()
          "They'Re Bill'S Friends From The Uk"

     可以使用正则表达式来构建针对撇号的特别处理:

          >>> import re
          >>> def titlecase(s):
          ...     return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
          ...                   lambda mo: mo.group(0).capitalize(),
          ...                   s)
          ...
          >>> titlecase("they're bill's friends.")
          "They're Bill's Friends."

 -- 方法: str.translate (table)

     返回原字符串的副本，其中每个字符按给定的转换表进行映射。 转换表必须
     是一个使用 *note __getitem__(): 280. 来实现索引操作的对象，通常为
     *note mapping: b41. 或 *note sequence: 1238.。 当以 Unicode 码位序
     号（整数）为索引时，转换表对象可以做以下任何一种操作：返回 Unicode
     序号或字符串，将字符映射为一个或多个字符；返回 ‘None’，将字符从结果
     字符串中删除；或引发 *note LookupError: 166d. 异常，将字符映射为其
     自身。

     你可以使用 *note str.maketrans(): 6bc. 基于不同格式的字符到字符映射
     来创建一个转换映射表。

     另请参阅 *note codecs: 1c. 模块以了解定制字符映射的更灵活方式。

 -- 方法: str.upper ()

     返回原字符串的副本，其中所有区分大小写的字符 (4) 均转换为大写。 请
     注意如果 ‘s’ 包含不区分大小写的字符或者如果结果字符的 Unicode 类别
     不是 "Lu" (Letter, uppercase) 而是 "Lt" (Letter, titlecase) 则
     ‘s.upper().isupper()’ 有可能为 ‘False’。

     所用转换大写算法的描述请参见 Unicode 标准的 3.13 节。

 -- 方法: str.zfill (width)

     返回原字符串的副本，在左边填充 ASCII ‘'0'’ 数码使其长度变为
     `width'。 正负值前缀 (‘'+'’/‘'-'’) 的处理方式是在正负符号 `之后' 填
     充而非在之前。 如果 `width' 小于等于 ‘len(s)’ 则返回原字符串的副本
     。

     例如

          >>> "42".zfill(5)
          '00042'
          >>> "-42".zfill(5)
          '-0042'

   ---------- Footnotes ----------

   (1) (4) 区分大小写的字符是指所属一般类别属性为 "Lu" (Letter,
uppercase), "Ll" (Letter, lowercase) 或 "Lt" (Letter, titlecase) 之一的
字符。

   (2) (4) 区分大小写的字符是指所属一般类别属性为 "Lu" (Letter,
uppercase), "Ll" (Letter, lowercase) 或 "Lt" (Letter, titlecase) 之一的
字符。

   (3) (4) 区分大小写的字符是指所属一般类别属性为 "Lu" (Letter,
uppercase), "Ll" (Letter, lowercase) 或 "Lt" (Letter, titlecase) 之一的
字符。

   (4) (4) 区分大小写的字符是指所属一般类别属性为 "Lu" (Letter,
uppercase), "Ll" (Letter, lowercase) 或 "Lt" (Letter, titlecase) 之一的
字符。


File: python.info,  Node: printf 风格的字符串格式化,  Prev: 字符串的方法<2>,  Up: 文本序列类型 --- str

5.4.7.2 ‘printf’ 风格的字符串格式化
...................................

     注解: 此处介绍的格式化操作具有多种怪异特性，可能导致许多常见错误（
     例如无法正确显示元组和字典）。 使用较新的 *note 格式化字符串字面值:
     15d.，*note str.format(): 4e2. 接口或 *note 模板字符串: 1670. 有助
     于避免这样的错误。 这些替代方案中的每一种都更好地权衡并提供了简单、
     灵活以及可扩展性优势。

字符串具有一种特殊的内置操作：使用 ‘%’ (取模) 运算符。 这也被称为字符串
的 `格式化' 或 `插值' 运算符。 对于 ‘format % values’ (其中 `format' 为
一个字符串)，在 `format' 中的 ‘%’ 转换标记符将被替换为零个或多个
`values' 条目。 其效果类似于在 C 语言中使用 ‘sprintf()’。

如果 `format' 要求一个单独参数，则 `values' 可以为一个非元组对象。 (1) 否
则的话，`values' 必须或者是一个包含项数与格式字符串中指定的转换符项数相
同的元组，或者是一个单独映射对象（例如字典）。

转换标记符包含两个或更多字符并具有以下组成，且必须遵循此处规定的顺序：

  1. ‘'%'’ 字符，用于标记转换符的起始。

  2. 映射键（可选），由加圆括号的字符序列组成 (例如 ‘(somename)’)。

  3. 转换旗标（可选），用于影响某些转换类型的结果。

  4. 最小字段宽度（可选）。 如果指定为 ‘'*'’ (星号)，则实际宽度会从
     `values' 元组的下一元素中读取，要转换的对象则为最小字段宽度和可选的
     精度之后的元素。

  5. 精度（可选），以在 ‘'.'’ (点号) 之后加精度值的形式给出。 如果指定为
     ‘'*'’ (星号)，则实际精度会从 `values' 元组的下一元素中读取，要转换
     的对象则为精度之后的元素。

  6. 长度修饰符（可选）。

  7. 转换类型。

当右边的参数为一个字典（或其他映射类型）时，字符串中的格式 `必须' 包含加
圆括号的映射键，对应 ‘'%'’ 字符之后字典中的每一项。 映射键将从映射中选取
要格式化的值。 例如：

     >>> print('%(language)s has %(number)03d quote types.' %
     ...       {'language': "Python", "number": 2})
     Python has 002 quote types.

在此情况下格式中不能出现 ‘*’ 标记符（因其需要一个序列类的参数列表）。

转换旗标为：

Flag          含义
              
----------------------------------------------------------------------------------------
              
‘'#'’         值的转换将使用“替代形式”（具体定义见下文）。
              
              
‘'0'’         转换将为数字值填充零字符。
              
              
‘'-'’         转换值将靠左对齐（如果同时给出 ‘'0'’ 转换，则会覆盖后者）。
              
              
‘' '’         (空格) 符号位转换产生的正数（或空字符串）前将留出一个空格。
              
              
‘'+'’         符号字符 (‘'+'’ 或 ‘'-'’) 将显示于转换结果的开头（会覆盖 "空格" 旗标）
              。
              

可以给出长度修饰符 (‘h’, ‘l’ 或 ‘L’)，但会被忽略，因为对 Python 来说没有
必要 – 所以 ‘%ld’ 等价于 ‘%d’。

转换类型为：

转换符           含义                                                      注释
                                                                           
---------------------------------------------------------------------------------------
                                                                           
‘'d'’            有符号十进制整数。
                 
                                                                           
‘'i'’            有符号十进制整数。
                 
                                                                           
‘'o'’            有符号八进制数。                                          (1)
                                                                           
                                                                           
‘'u'’            过时类型 – 等价于 ‘'d'’。                                 (6)
                                                                           
                                                                           
‘'x'’            有符号十六进制数（小写）。                                (2)
                                                                           
                                                                           
‘'X'’            有符号十六进制数（大写）。                                (2)
                                                                           
                                                                           
‘'e'’            浮点指数格式（小写）。                                    (3)
                                                                           
                                                                           
‘'E'’            浮点指数格式（大写）。                                    (3)
                                                                           
                                                                           
‘'f'’            浮点十进制格式。                                          (3)
                                                                           
                                                                           
‘'F'’            浮点十进制格式。                                          (3)
                                                                           
                                                                           
‘'g'’            浮点格式。 如果指数小于 -4 或不小于精度则使用小写指数格   (4)
                 式，否则使用十进制格式。                                  
                 
                                                                           
‘'G'’            浮点格式。 如果指数小于 -4 或不小于精度则使用大写指数格   (4)
                 式，否则使用十进制格式。                                  
                 
                                                                           
‘'c'’            单个字符（接受整数或单个字符的字符串）。
                 
                                                                           
‘'r'’            字符串（使用 *note repr(): 7d5. 转换任何 Python 对象）    (5)
                 。                                                        
                 
                                                                           
‘'s'’            字符串（使用 *note str(): 339. 转换任何 Python 对象）。   (5)
                                                                           
                                                                           
‘'a'’            字符串（使用 *note ascii(): d54. 转换任何 Python 对象）   (5)
                 。                                                        
                 
                                                                           
‘'%'’            不转换参数，在结果中输出一个 ‘'%'’ 字符。
                 

注释:

  1. 此替代形式会在第一个数码之前插入标示八进制数的前缀 (‘'0o'’)。

  2. 此替代形式会在第一个数码之前插入 ‘'0x'’ 或 ‘'0X'’ 前缀（取决于是使
     用 ‘'x'’ 还是 ‘'X'’ 格式）。

  3. 此替代形式总是会在结果中包含一个小数点，即使其后并没有数码。

     小数点后的数码位数由精度决定，默认为 6。

  4. 此替代形式总是会在结果中包含一个小数点，末尾各位的零不会如其他情况
     下那样被移除。

     小数点前后的有效数码位数由精度决定，默认为 6。

  5. 如果精度为 ‘N’，输出将截短为 ‘N’ 个字符。

  6. 参见 PEP 237(2)。

由于 Python 字符串显式指明长度，‘%s’ 转换不会将 ‘'\0'’ 视为字符串的结束
。

在 3.1 版更改: 绝对值超过 1e50 的 ‘%f’ 转换不会再被替换为 ‘%g’ 转换。

   ---------- Footnotes ----------

   (1) (5) 要格式化单独一个元组，那么你应当提供一个单例元组，其唯一的元
素就是要被格式化的元组。

   (2) https://www.python.org/dev/peps/pep-0237


File: python.info,  Node: 二进制序列类型 --- bytes bytearray memoryview,  Next: 集合类型 --- set frozenset,  Prev: 文本序列类型 --- str,  Up: 内置类型

5.4.8 二进制序列类型 — ‘bytes’, ‘bytearray’, ‘memoryview’
---------------------------------------------------------

操作二进制数据的核心内置类型是 *note bytes: 33a. 和 *note bytearray:
33b.。 它们由 *note memoryview: 25d. 提供支持，该对象使用 *note
缓冲区协议: 15f7. 来访问其他二进制对象所在内存，不需要创建对象的副本。

*note array: 7. 模块支持高效地存储基本数据类型，例如 32 位整数和 IEEE754
双精度浮点值。

* Menu:

* bytes 对象::
* bytearray 对象::
* bytes 和 bytearray 操作::
* printf 风格的字节串格式化::
* 内存视图::


File: python.info,  Node: bytes 对象,  Next: bytearray 对象,  Up: 二进制序列类型 --- bytes bytearray memoryview

5.4.8.1 bytes 对象
..................

bytes 对象是由单个字节构成的不可变序列。 由于许多主要二进制协议都基于
ASCII 文本编码，因此 bytes 对象提供了一些仅在处理 ASCII 兼容数据时可用，
并且在许多特性上与字符串对象紧密相关的方法。

 -- 类: bytes ([source[, encoding[, errors]]])

     首先，表示 bytes 字面值的语法与字符串字面值的大致相同，只是添加了一
     个 ‘b’ 前缀：

        * 单引号: ‘b'同样允许嵌入 "双" 引号'’。

        * 双引号: ‘b"同样允许嵌入 '单' 引号"’。

        * 三重引号: ‘b'''三重单引号'''’, ‘b"""三重双引号"""’

     bytes 字面值中只允许 ASCII 字符（无论源代码声明的编码为何）。 任何
     超出 127 的二进制值必须使用相应的转义序列形式加入 bytes 字面值。

     像字符串字面值一样，bytes 字面值也可以使用 ‘r’ 前缀来禁用转义序列处
     理。 请参阅 *note 字符串和字节串字面值: 13f3. 了解有关各种 bytes 字
     面值形式的详情，包括所支持的转义序列。

     虽然 bytes 字面值和表示法是基于 ASCII 文本的，但 bytes 对象的行为实
     际上更像是不可变的整数序列，序列中的每个值的大小被限制为 ‘0 <= x <
     256’ (如果违反此限制将引发 *note ValueError: 1fc.)。 这种限制是有意
     设计用以强调以下事实，虽然许多二进制格式都包含基于 ASCII 的元素，可
     以通过某些面向文本的算法进行有用的操作，但情况对于任意二进制数据来
     说通常却并非如此（盲目地将文本处理算法应用于不兼容 ASCII 的二进制数
     据格式往往将导致数据损坏）。

     除了字面值形式，bytes 对象还可以通过其他几种方式来创建：

        * 指定长度的以零值填充的 bytes 对象: ‘bytes(10)’

        * 通过由整数组成的可迭代对象: ‘bytes(range(20))’

        * 通过缓冲区协议复制现有的二进制数据: ‘bytes(obj)’

     另请参阅 *note bytes: 10cd. 内置类型。

     由于两个十六进制数码精确对应一个字节，因此十六进制数是描述二进制数
     据的常用格式。 相应地，bytes 类型具有从此种格式读取数据的附加类方法
     ：

      -- 方法: classmethod fromhex (string)

          此 *note bytes: 33a. 类方法返回一个解码给定字符串的 bytes 对象
          。 字符串必须由表示每个字节的两个十六进制数码构成，其中的
          ASCII 空白符会被忽略。

               >>> bytes.fromhex('2Ef0 F1f2  ')
               b'.\xf0\xf1\xf2'

          在 3.7 版更改: *note bytes.fromhex(): 337. 现在会忽略所有
          ASCII 空白符而不只是空格符。

     存在一个反向转换函数，可以将 bytes 对象转换为对应的十六进制表示。

      -- 方法: hex ([sep[, bytes_per_sep]])

          返回一个字符串对象，该对象包含实例中每个字节的两个十六进制数字
          。

               >>> b'\xf0\xf1\xf2'.hex()
               'f0f1f2'

          如果你希望令十六进制数字符串更易读，你可以指定单个字符分隔符作
          为 `sep' 形参包含于输出中。 默认会放在每个字节之间。 第二个可
          选的 `bytes_per_sep' 形参控制间距。 正值会从右开始计算分隔符的
          位置，负值则是从左开始。

               >>> value = b'\xf0\xf1\xf2'
               >>> value.hex('-')
               'f0-f1-f2'
               >>> value.hex('_', 2)
               'f0_f1f2'
               >>> b'UUDDLRLRAB'.hex(' ', -4)
               '55554444 4c524c52 4142'

          3.5 新版功能.

          在 3.8 版更改: *note bytes.hex(): 63a. 现在支持可选的 `sep' 和
          `bytes_per_sep' 形参以在十六进制输出的字节之间插入分隔符。

由于 bytes 对象是由整数构成的序列（类似于元组），因此对于一个 bytes 对象
`b'，‘b[0]’ 将为一个整数，而 ‘b[0:1]’ 将为一个长度为 1 的 bytes 对象。 （
这与文本字符串不同，索引和切片所产生的将都是一个长度为 1 的字符串）。

bytes 对象的表示使用字面值格式 (‘b'...'’)，因为它通常都要比像
‘bytes([46, 46, 46])’ 这样的格式更好用。 你总是可以使用 ‘list(b)’ 将
bytes 对象转换为一个由整数构成的列表。

     注解: 针对 Python 2.x 用户的说明：在 Python 2.x 系列中，允许 8 位字
     符串（ 2.x 所提供的最接近内置二进制数据类型的对象）与 Unicode 字符
     串进行各种隐式转换。 这是为了实现向下兼容的变通做法，以适应 Python
     最初只支持 8 位文本而 Unicode 文本是后来才被加入这一事实。 在
     Python 3.x 中，这些隐式转换已被取消 —— 8 位二进制数据与 Unicode 文
     本间的转换必须显式地进行，bytes 与字符串对象的比较结果将总是不相等
     。


File: python.info,  Node: bytearray 对象,  Next: bytes 和 bytearray 操作,  Prev: bytes 对象,  Up: 二进制序列类型 --- bytes bytearray memoryview

5.4.8.2 bytearray 对象
......................

*note bytearray: 33b. 对象是 *note bytes: 33a. 对象的可变对应物。

 -- 类: bytearray ([source[, encoding[, errors]]])

     bytearray 对象没有专属的字面值语法，它们总是通过调用构造器来创建：

        * 创建一个空实例: ‘bytearray()’

        * 创建一个指定长度的以零值填充的实例: ‘bytearray(10)’

        * 通过由整数组成的可迭代对象: ‘bytearray(range(20))’

        * 通过缓冲区协议复制现有的二进制数据: ‘bytearray(b'Hi!')’

     由于 bytearray 对象是可变的，该对象除了 *note bytes 和 bytearray
     操作: 15f6. 中所描述的 bytes 和 bytearray 共有操作之外，还支持
     *note 可变: 15f5. 序列操作。

     另请参见 *note bytearray: 10ce. 内置类型。

     由于两个十六进制数码精确对应一个字节，因此十六进制数是描述二进制数
     据的常用格式。 相应地，bytearray 类型具有从此种格式读取数据的附加类
     方法：

      -- 方法: classmethod fromhex (string)

          *note bytearray: 33b. 类方法返回一个解码给定字符串的 bytearray
          对象。 字符串必须由表示每个字节的两个十六进制数码构成，其中的
          ASCII 空白符会被忽略。

               >>> bytearray.fromhex('2Ef0 F1f2  ')
               bytearray(b'.\xf0\xf1\xf2')

          在 3.7 版更改: *note bytearray.fromhex(): 338. 现在会忽略所有
          ASCII 空白符而不只是空格符。

     存在一个反向转换函数，可以将 bytearray 对象转换为对应的十六进制表示
     。

      -- 方法: hex ([sep[, bytes_per_sep]])

          返回一个字符串对象，该对象包含实例中每个字节的两个十六进制数字
          。

               >>> bytearray(b'\xf0\xf1\xf2').hex()
               'f0f1f2'

          3.5 新版功能.

          在 3.8 版更改: 与 *note bytes.hex(): 63a. 相似， *note
          bytearray.hex(): 63b. 现在支持可选的 `sep' 和 `bytes_per_sep'
          参数以在十六进制输出的字节之间插入分隔符。

由于 bytearray 对象是由整数构成的序列（类似于列表），因此对于一个
bytearray 对象 `b'，‘b[0]’ 将为一个整数，而 ‘b[0:1]’ 将为一个长度为 1 的
bytearray 对象。 （这与文本字符串不同，索引和切片所产生的将都是一个长度
为 1 的字符串）。

bytearray 对象的表示使用 bytes 对象字面值格式 (‘bytearray(b'...')’)，因
为它通常都要比 ‘bytearray([46, 46, 46])’ 这样的格式更好用。 你总是可以使
用 ‘list(b)’ 将 bytearray 对象转换为一个由整数构成的列表。


File: python.info,  Node: bytes 和 bytearray 操作,  Next: printf 风格的字节串格式化,  Prev: bytearray 对象,  Up: 二进制序列类型 --- bytes bytearray memoryview

5.4.8.3 bytes 和 bytearray 操作
...............................

bytes 和 bytearray 对象都支持 *note 通用: 163f. 序列操作。 它们不仅能与
相同类型的操作数，也能与任何 *note bytes-like object: 5f1. 进行互操作。
由于这样的灵活性，它们可以在操作中自由地混合而不会导致错误。 但是，操作
结果的返回值类型可能取决于操作数的顺序。

     注解: bytes 和 bytearray 对象的方法不接受字符串作为其参数，就像字符
     串的方法不接受 bytes 对象作为其参数一样。 例如，你必须使用以下写法:

          a = "abc"
          b = a.replace("a", "f")

     和:

          a = b"abc"
          b = a.replace(b"a", b"f")

某些 bytes 和 bytearray 操作假定使用兼容 ASCII 的二进制格式，因此在处理
任意二进数数据时应当避免使用。 这些限制会在下文中说明。

     注解: 使用这些基于 ASCII 的操作来处理未以基于 ASCII 的格式存储的二
     进制数据可能会导致数据损坏。

bytes 和 bytearray 对象的下列方法可以用于任意二进制数据。

 -- 方法: bytes.count (sub[, start[, end]])
 -- 方法: bytearray.count (sub[, start[, end]])

     返回子序列 `sub' 在 [`start', `end'] 范围内非重叠出现的次数。 可选
     参数 `start' 与 `end' 会被解读为切片表示法。

     要搜索的子序列可以是任意 *note bytes-like object: 5f1. 或是 0 至
     255 范围内的整数。

     在 3.3 版更改: 也接受 0 至 255 范围内的整数作为子序列。

 -- 方法: bytes.decode (encoding="utf-8", errors="strict")
 -- 方法: bytearray.decode (encoding="utf-8", errors="strict")

     返回从给定 bytes 解码出来的字符串。 默认编码为 ‘'utf-8'’。 可以给出
     `errors' 来设置不同的错误处理方案。 `errors' 的默认值为 ‘'strict'’，
     表示编码错误会引发 *note UnicodeError: c43.。 其他可用的值为
     ‘'ignore'’, ‘'replace'’ 以及任何其他通过 *note
     codecs.register_error(): dfd. 注册的名称，请参阅 *note
     错误处理方案: 1371. 小节。 要查看可用的编码列表，请参阅 *note
     标准编码: 698. 小节。

          注解: 将 `encoding' 参数传给 *note str: 339. 允许直接解码任何
          *note bytes-like object: 5f1.，无须创建临时的 bytes 或
          bytearray 对象。

     在 3.1 版更改: 加入了对关键字参数的支持。

 -- 方法: bytes.endswith (suffix[, start[, end]])
 -- 方法: bytearray.endswith (suffix[, start[, end]])

     如果二进制数据以指定的 `suffix' 结束则返回 ‘True’，否则返回
     ‘False’。 `suffix' 也可以为由多个供查找的后缀构成的元组。 如果有可
     选项 `start'，将从所指定位置开始检查。 如果有可选项 `end'，将在所指
     定位置停止比较。

     要搜索的后缀可以是任意 *note bytes-like object: 5f1.。

 -- 方法: bytes.find (sub[, start[, end]])
 -- 方法: bytearray.find (sub[, start[, end]])

     返回子序列 `sub' 在数据中被找到的最小索引，`sub' 包含于切片
     ‘s[start:end]’ 之内。 可选参数 `start' 与 `end' 会被解读为切片表示
     法。 如果 `sub' 未被找到则返回 ‘-1’。

     要搜索的子序列可以是任意 *note bytes-like object: 5f1. 或是 0 至
     255 范围内的整数。

          注解: *note find(): 167a. 方法应该只在你需要知道 `sub' 所在位
          置时使用。 要检查 `sub' 是否为子串，请使用 *note in: 7ac. 操作
          符:

               >>> b'Py' in b'Python'
               True

     在 3.3 版更改: 也接受 0 至 255 范围内的整数作为子序列。

 -- 方法: bytes.index (sub[, start[, end]])
 -- 方法: bytearray.index (sub[, start[, end]])

     类似于 *note find(): 167a.，但在找不到子序列时会引发 *note
     ValueError: 1fc.。

     要搜索的子序列可以是任意 *note bytes-like object: 5f1. 或是 0 至
     255 范围内的整数。

     在 3.3 版更改: 也接受 0 至 255 范围内的整数作为子序列。

 -- 方法: bytes.join (iterable)
 -- 方法: bytearray.join (iterable)

     返回一个由 `iterable' 中的二进制数据序列拼接而成的 bytes 或
     bytearray 对象。 如果 `iterable' 中存在任何非 *note 字节类对象:
     5f1. 包括存在 *note str: 339. 对象值则会引发 *note TypeError: 193.。
     提供该方法的 bytes 或 bytearray 对象的内容将作为元素之间的分隔。

 -- 方法: static bytes.maketrans (from, to)
 -- 方法: static bytearray.maketrans (from, to)

     此静态方法返回一个可用于 *note bytes.translate(): 167f. 的转换对照
     表，它将把 `from' 中的每个字符映射为 `to' 中相同位置上的字符；
     `from' 与 `to' 必须都是 *note 字节类对象: 5f1. 并且具有相同的长度。

     3.1 新版功能.

 -- 方法: bytes.partition (sep)
 -- 方法: bytearray.partition (sep)

     在 `sep' 首次出现的位置拆分序列，返回一个 3 元组，其中包含分隔符之
     前的部分、分隔符本身或其 bytearray 副本，以及分隔符之后的部分。 如
     果分隔符未找到，则返回的 3 元组中包含原序列以及两个空的 bytes 或
     bytearray 对象。

     要搜索的分隔符可以是任意 *note bytes-like object: 5f1.。

 -- 方法: bytes.replace (old, new[, count])
 -- 方法: bytearray.replace (old, new[, count])

     返回序列的副本，其中出现的所有子序列 `old' 都将被替换为 `new'。 如
     果给出了可选参数 `count'，则只替换前 `count' 次出现。

     要搜索的子序列及其替换序列可以是任意 *note bytes-like object: 5f1.。

          注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 方法: bytes.rfind (sub[, start[, end]])
 -- 方法: bytearray.rfind (sub[, start[, end]])

     返回子序列 `sub' 在序列内被找到的最大（最右）索引，这样 `sub' 将包
     含在 ‘s[start:end]’ 当中。 可选参数 `start' 与 `end' 会被解读为切片
     表示法。 如果未找到则返回 ‘-1’。

     要搜索的子序列可以是任意 *note bytes-like object: 5f1. 或是 0 至
     255 范围内的整数。

     在 3.3 版更改: 也接受 0 至 255 范围内的整数作为子序列。

 -- 方法: bytes.rindex (sub[, start[, end]])
 -- 方法: bytearray.rindex (sub[, start[, end]])

     类似于 *note rfind(): 1684.，但在子序列 `sub' 未找到时会引发 *note
     ValueError: 1fc.。

     要搜索的子序列可以是任意 *note bytes-like object: 5f1. 或是 0 至
     255 范围内的整数。

     在 3.3 版更改: 也接受 0 至 255 范围内的整数作为子序列。

 -- 方法: bytes.rpartition (sep)
 -- 方法: bytearray.rpartition (sep)

     在 `sep' 最后一次出现的位置拆分序列，返回一个 3 元组，其中包含分隔
     符之前的部分，分隔符本身或其 bytearray 副本，以及分隔符之后的部分。
     如果分隔符未找到，则返回的 3 元组中包含两个空的 bytes 或 bytearray
     对象以及原序列的副本。

     要搜索的分隔符可以是任意 *note bytes-like object: 5f1.。

 -- 方法: bytes.startswith (prefix[, start[, end]])
 -- 方法: bytearray.startswith (prefix[, start[, end]])

     如果二进制数据以指定的 `prefix' 开头则返回 ‘True’，否则返回
     ‘False’。 `prefix' 也可以为由多个供查找的前缀构成的元组。 如果有可
     选项 `start'，将从所指定位置开始检查。 如果有可选项 `end'，将在所指
     定位置停止比较。

     要搜索的前缀可以是任意 *note bytes-like object: 5f1.。

 -- 方法: bytes.translate (table, /, delete=b'')
 -- 方法: bytearray.translate (table, /, delete=b'')

     返回原 bytes 或 bytearray 对象的副本，移除其中所有在可选参数
     `delete' 中出现的 bytes，其余 bytes 将通过给定的转换表进行映射，该
     转换表必须是长度为 256 的 bytes 对象。

     你可以使用 *note bytes.maketrans(): c11. 方法来创建转换表。

     对于仅需移除字符的转换，请将 `table' 参数设为 ‘None’:

          >>> b'read this short text'.translate(None, b'aeiou')
          b'rd ths shrt txt'

     在 3.6 版更改: 现在支持将 `delete' 作为关键字参数。

以下 bytes 和 bytearray 对象的方法的默认行为会假定使用兼容 ASCII 的二进
制格式，但通过传入适当的参数仍然可用于任意二进制数据。 请注意本小节中所
有的 bytearray 方法都 `不是' 原地执行操作，而是会产生新的对象。

 -- 方法: bytes.center (width[, fillbyte])
 -- 方法: bytearray.center (width[, fillbyte])

     返回原对象的副本，在长度为 `width' 的序列内居中，使用指定的
     `fillbyte' 填充两边的空位（默认使用 ASCII 空格符）。 对于 *note
     bytes: 33a. 对象，如果 `width' 小于等于 ‘len(s)’ 则返回原序列的副本
     。

          注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 方法: bytes.ljust (width[, fillbyte])
 -- 方法: bytearray.ljust (width[, fillbyte])

     返回原对象的副本，在长度为 `width' 的序列中靠左对齐。 使用指定的
     `fillbyte' 填充空位（默认使用 ASCII 空格符）。 对于 *note bytes:
     33a. 对象，如果 `width' 小于等于 ‘len(s)’ 则返回原序列的副本。

          注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 方法: bytes.lstrip ([chars])
 -- 方法: bytearray.lstrip ([chars])

     返回原序列的副本，移除指定的前导字节。 `chars' 参数为指定要移除字节
     值集合的二进制序列 —— 这个名称表明此方法通常是用于 ASCII 字符。 如
     果省略或为 ‘None’，则 `chars' 参数默认移除 ASCII 空白符。 `chars' 参
     数并非指定单个前缀；而是会移除参数值的所有组合:

          >>> b'   spacious   '.lstrip()
          b'spacious   '
          >>> b'www.example.com'.lstrip(b'cmowz.')
          b'example.com'

     要移除的字节值二进制序列可以是任意 *note bytes-like object: 5f1.。

          注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 方法: bytes.rjust (width[, fillbyte])
 -- 方法: bytearray.rjust (width[, fillbyte])

     返回原对象的副本，在长度为 `width' 的序列中靠右对齐。 使用指定的
     `fillbyte' 填充空位（默认使用 ASCII 空格符）。 对于 *note bytes:
     33a. 对象，如果 `width' 小于等于 ‘len(s)’ 则返回原序列的副本。

          注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 方法: bytes.rsplit (sep=None, maxsplit=-1)
 -- 方法: bytearray.rsplit (sep=None, maxsplit=-1)

     将二进制序列拆分为相同类型的子序列，使用 `sep' 作为分隔符。 如果给
     出了 `maxsplit'，则最多进行 `maxsplit' 次拆分，从 `最右边' 开始。 如
     果 `sep' 未指定或为 ‘None’，任何只包含 ASCII 空白符的子序列都会被作
     为分隔符。 除了从右边开始拆分，*note rsplit(): 1695. 的其他行为都类
     似于下文所述的 *note split(): 1696.。

 -- 方法: bytes.rstrip ([chars])
 -- 方法: bytearray.rstrip ([chars])

     返回原序列的副本，移除指定的末尾字节。 `chars' 参数为指定要移除字节
     值集合的二进制序列 —— 这个名称表明此方法通常是用于 ASCII 字符。 如
     果省略或为 ‘None’，则 `chars' 参数默认移除 ASCII 空白符。 `chars' 参
     数并非指定单个后缀；而是会移除参数值的所有组合:

          >>> b'   spacious   '.rstrip()
          b'   spacious'
          >>> b'mississippi'.rstrip(b'ipz')
          b'mississ'

     要移除的字节值二进制序列可以是任意 *note bytes-like object: 5f1.。

          注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 方法: bytes.split (sep=None, maxsplit=-1)
 -- 方法: bytearray.split (sep=None, maxsplit=-1)

     将二进制序列拆分为相同类型的子序列，使用 `sep' 作为分隔符。 如果给
     出了 `maxsplit' 且非负值，则最多进行 `maxsplit' 次拆分（因此，列表
     最多会有 ‘maxsplit+1’ 个元素）。 如果 `maxsplit' 未指定或为 ‘-1’，
     则不限制拆分次数（进行所有可能的拆分）。

     如果给出了 `sep'，则连续的分隔符不会被组合在一起而是被视为分隔空子
     序列 (例如 ‘b'1,,2'.split(b',')’ 将返回 ‘[b'1', b'', b'2']’)。
     `sep' 参数可能为一个多字节序列 (例如 ‘b'1<>2<>3'.split(b'<>')’ 将返
     回 ‘[b'1', b'2', b'3']’)。 使用指定的分隔符拆分空序列将返回 ‘[b'']’
     或 ‘[bytearray(b'')]’，具体取决于被拆分对象的类型。 `sep' 参数可以
     是任意 *note bytes-like object: 5f1.。

     例如

          >>> b'1,2,3'.split(b',')
          [b'1', b'2', b'3']
          >>> b'1,2,3'.split(b',', maxsplit=1)
          [b'1', b'2,3']
          >>> b'1,2,,3,'.split(b',')
          [b'1', b'2', b'', b'3', b'']

     如果 `sep' 未指定或为 ‘None’，则会应用另一种拆分算法：连续的 ASCII
     空白符会被视为单个分隔符，其结果将不包含序列开头或末尾的空白符。 因
     此，在不指定分隔符的情况下对空序列或仅包含 ASCII 空白符的序列进行拆
     分将返回 ‘[]’。

     例如

          >>> b'1 2 3'.split()
          [b'1', b'2', b'3']
          >>> b'1 2 3'.split(maxsplit=1)
          [b'1', b'2 3']
          >>> b'   1   2   3   '.split()
          [b'1', b'2', b'3']

 -- 方法: bytes.strip ([chars])
 -- 方法: bytearray.strip ([chars])

     返回原序列的副本，移除指定的开头和末尾字节。 `chars' 参数为指定要移
     除字节值集合的二进制序列 —— 这个名称表明此方法通常是用于 ASCII 字符
     。 如果省略或为 ‘None’，则 `chars' 参数默认移除 ASCII 空白符。
     `chars' 参数并非指定单个前缀或后缀；而是会移除参数值的所有组合:

          >>> b'   spacious   '.strip()
          b'spacious'
          >>> b'www.example.com'.strip(b'cmowz.')
          b'example'

     要移除的字节值二进制序列可以是任意 *note bytes-like object: 5f1.。

          注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

以下 bytes 和 bytearray 对象的方法会假定使用兼容 ASCII 的二进制格式，不
应当被应用于任意二进制数据。 请注意本小节中所有的 bytearray 方法都 `不是
' 原地执行操作，而是会产生新的对象。

 -- 方法: bytes.capitalize ()
 -- 方法: bytearray.capitalize ()

     返回原序列的副本，其中每个字节将都将被解读为一个 ASCII 字符，并且第
     一个字节的字符大写而其余的小写。 非 ASCII 字节值将保持原样不变。

          注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 方法: bytes.expandtabs (tabsize=8)
 -- 方法: bytearray.expandtabs (tabsize=8)

     返回序列的副本，其中所有的 ASCII 制表符会由一个或多个 ASCII 空格替
     换，具体取决于当前列位置和给定的制表符宽度。 每 `tabsize' 个字节设
     为一个制表位（默认值 8 时设定的制表位在列 0, 8, 16 依次类推）。 要
     展开序列，当前列位置将被设为零并逐一检查序列中的每个字节。 如果字节
     为 ASCII 制表符 (‘b'\t'’)，则并在结果中插入一个或多个空格符，直到当
     前列等于下一个制表位。 （制表符本身不会被复制。） 如果当前字节为
     ASCII 换行符 (‘b'\n'’) 或回车符 (‘b'\r'’)，它会被复制并将当前列重设
     为零。 任何其他字节会被不加修改地复制并将当前列加一，不论该字节值在
     被打印时会如何显示:

          >>> b'01\t012\t0123\t01234'.expandtabs()
          b'01      012     0123    01234'
          >>> b'01\t012\t0123\t01234'.expandtabs(4)
          b'01  012 0123    01234'

          注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 方法: bytes.isalnum ()
 -- 方法: bytearray.isalnum ()

     如果序列中所有字节都是字母类 ASCII 字符或 ASCII 十进制数码并且序列
     非空则返回 ‘Ture’ ，否则返回 ‘False’ 。 字母类 ASCII 字符就是字节值
     包含在序列
     ‘b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符
     。 ASCII 十进制数码就是字节值包含在序列 ‘b'0123456789'’ 中的字符。

     例如

          >>> b'ABCabc1'.isalnum()
          True
          >>> b'ABC abc1'.isalnum()
          False

 -- 方法: bytes.isalpha ()
 -- 方法: bytearray.isalpha ()

     如果序列中所有字节都是字母类 ASCII 字符并且序列不非空则返回 ‘True’
     ，否则返回 ‘False’ 。 字母类 ASCII 字符就是字节值包含在序列
     ‘b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符
     。

     例如

          >>> b'ABCabc'.isalpha()
          True
          >>> b'ABCabc1'.isalpha()
          False

 -- 方法: bytes.isascii ()
 -- 方法: bytearray.isascii ()

     如果序列为空或序列中所有字节都是 ASCII 字节则返回 ‘True’ ，否则返回
     ‘False’ 。 ASCII 字节的取值范围是 0-0x7F。

     3.7 新版功能.

 -- 方法: bytes.isdigit ()
 -- 方法: bytearray.isdigit ()

     如果序列中所有字节都是 ASCII 十进制数码并且序列非空则返回 ‘True’ ，
     否则返回 ‘False’ 。 ASCII 十进制数码就是字节值包含在序列
     ‘b'0123456789'’ 中的字符。

     例如

          >>> b'1234'.isdigit()
          True
          >>> b'1.23'.isdigit()
          False

 -- 方法: bytes.islower ()
 -- 方法: bytearray.islower ()

     如果序列中至少有一个小写的 ASCII 字符并且没有大写的 ASCII 字符则返
     回 ‘True’ ，否则返回 ‘False’ 。

     例如

          >>> b'hello world'.islower()
          True
          >>> b'Hello world'.islower()
          False

     小写 ASCII 字符就是字节值包含在序列 ‘b'abcdefghijklmnopqrstuvwxyz'’
     中的字符。 大写 ASCII 字符就是字节值包含在序列
     ‘b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符。

 -- 方法: bytes.isspace ()
 -- 方法: bytearray.isspace ()

     如果序列中所有字节都是 ASCII 空白符并且序列非空则返回 ‘True’ ，否则
     返回 ‘False’ 。 ASCII 空白符就是字节值包含在序列 ‘b' \t\n\r\x0b\f'’
     (空格, 制表, 换行, 回车, 垂直制表, 进纸) 中的字符。

 -- 方法: bytes.istitle ()
 -- 方法: bytearray.istitle ()

     如果序列为 ASCII 标题大小写形式并且序列非空则返回 ‘True’ ，否则返回
     ‘False’ 。 请参阅 *note bytes.title(): 16ae. 了解有关“标题大小写”的
     详细定义。

     例如

          >>> b'Hello World'.istitle()
          True
          >>> b'Hello world'.istitle()
          False

 -- 方法: bytes.isupper ()
 -- 方法: bytearray.isupper ()

     如果序列中至少有一个大写字母 ASCII 字符并且没有小写 ASCII 字符则返
     回 ‘True’ ，否则返回 ‘False’ 。

     例如

          >>> b'HELLO WORLD'.isupper()
          True
          >>> b'Hello world'.isupper()
          False

     小写 ASCII 字符就是字节值包含在序列 ‘b'abcdefghijklmnopqrstuvwxyz'’
     中的字符。 大写 ASCII 字符就是字节值包含在序列
     ‘b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符。

 -- 方法: bytes.lower ()
 -- 方法: bytearray.lower ()

     返回原序列的副本，其所有大写 ASCII 字符均转换为对应的小写形式。

     例如

          >>> b'Hello World'.lower()
          b'hello world'

     小写 ASCII 字符就是字节值包含在序列 ‘b'abcdefghijklmnopqrstuvwxyz'’
     中的字符。 大写 ASCII 字符就是字节值包含在序列
     ‘b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符。

          注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 方法: bytes.splitlines (keepends=False)
 -- 方法: bytearray.splitlines (keepends=False)

     返回由原二进制序列中各行组成的列表，在 ASCII 行边界符的位置拆分。 此
     方法使用 *note universal newlines: 5fd. 方式来分行。 结果列表中不包
     含换行符，除非给出了 `keepends' 且为真值。

     例如

          >>> b'ab c\n\nde fg\rkl\r\n'.splitlines()
          [b'ab c', b'', b'de fg', b'kl']
          >>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
          [b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']

     不同于 *note split(): 1699.，当给出了分隔符 `sep' 时，对于空字符串
     此方法将返回一个空列表，而末尾的换行不会令结果中增加额外的行:

          >>> b"".split(b'\n'), b"Two lines\n".split(b'\n')
          ([b''], [b'Two lines', b''])
          >>> b"".splitlines(), b"One line\n".splitlines()
          ([], [b'One line'])

 -- 方法: bytes.swapcase ()
 -- 方法: bytearray.swapcase ()

     返回原序列的副本，其所有小写 ASCII 字符均转换为对应的大写形式，反之
     亦反。

     例如

          >>> b'Hello World'.swapcase()
          b'hELLO wORLD'

     小写 ASCII 字符就是字节值包含在序列 ‘b'abcdefghijklmnopqrstuvwxyz'’
     中的字符。 大写 ASCII 字符就是字节值包含在序列
     ‘b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符。

     不同于 *note str.swapcase(): 166b.，在些二进制版本下
     ‘bin.swapcase().swapcase() == bin’ 总是成立。 大小写转换在 ASCII 中
     是对称的，即使其对于任意 Unicode 码位来说并不总是成立。

          注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 方法: bytes.title ()
 -- 方法: bytearray.title ()

     返回原二进制序列的标题版本，其中每个单词以一个大写 ASCII 字符为开头
     ，其余字母为小写。 不区别大小写的字节值将保持原样不变。

     例如

          >>> b'Hello world'.title()
          b'Hello World'

     小写 ASCII 字符就是字节值包含在序列 ‘b'abcdefghijklmnopqrstuvwxyz'’
     中的字符。 大写 ASCII 字符就是字节值包含在序列
     ‘b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符。 所有其他字节值都不区分大
     小写。

     该算法使用一种简单的与语言无关的定义，将连续的字母组合视为单词。 该
     定义在多数情况下都很有效，但它也意味着代表缩写形式与所有格的撇号也
     会成为单词边界，这可能导致不希望的结果:

          >>> b"they're bill's friends from the UK".title()
          b"They'Re Bill'S Friends From The Uk"

     可以使用正则表达式来构建针对撇号的特别处理:

          >>> import re
          >>> def titlecase(s):
          ...     return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?",
          ...                   lambda mo: mo.group(0)[0:1].upper() +
          ...                              mo.group(0)[1:].lower(),
          ...                   s)
          ...
          >>> titlecase(b"they're bill's friends.")
          b"They're Bill's Friends."

          注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 方法: bytes.upper ()
 -- 方法: bytearray.upper ()

     返回原序列的副本，其所有小写 ASCII 字符均转换为对应的大写形式。

     例如

          >>> b'Hello World'.upper()
          b'HELLO WORLD'

     小写 ASCII 字符就是字节值包含在序列 ‘b'abcdefghijklmnopqrstuvwxyz'’
     中的字符。 大写 ASCII 字符就是字节值包含在序列
     ‘b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符。

          注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 方法: bytes.zfill (width)
 -- 方法: bytearray.zfill (width)

     返回原序列的副本，在左边填充 ‘b'0'’ 数码使序列长度为 `width'。 正负
     值前缀 (‘b'+'’/ ‘b'-'’) 的处理方式是在正负符号 `之后' 填充而非在之
     前。 对于 *note bytes: 33a. 对象，如果 `width' 小于等于 ‘len(seq)’
     则返回原序列。

     例如

          >>> b"42".zfill(5)
          b'00042'
          >>> b"-42".zfill(5)
          b'-0042'

          注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。


File: python.info,  Node: printf 风格的字节串格式化,  Next: 内存视图,  Prev: bytes 和 bytearray 操作,  Up: 二进制序列类型 --- bytes bytearray memoryview

5.4.8.4 ‘printf’ 风格的字节串格式化
...................................

     注解: 此处介绍的格式化操作具有多种怪异特性，可能导致许多常见错误（
     例如无法正确显示元组和字典）。 如果要打印的值可能为元组或字典，请将
     其放入一个元组中。

字节串对象 (‘bytes’/‘bytearray’) 具有一种特殊的内置操作：使用 ‘%’ (取模)
运算符。 这也被称为字节串的 `格式化' 或 `插值' 运算符。 对于 ‘format %
values’ (其中 `format' 为一个字节串对象)，在 `format' 中的 ‘%’ 转换标记
符将被替换为零个或多个 `values' 条目。 其效果类似于在 C 语言中使用
‘sprintf()’。

如果 `format' 要求一个单独参数，则 `values' 可以为一个非元组对象。 (1) 否
则的话，`values' 必须或是是一个包含项数与格式字节串对象中指定的转换符项
数相同的元组，或者是一个单独的映射对象（例如元组）。

转换标记符包含两个或更多字符并具有以下组成，且必须遵循此处规定的顺序：

  1. ‘'%'’ 字符，用于标记转换符的起始。

  2. 映射键（可选），由加圆括号的字符序列组成 (例如 ‘(somename)’)。

  3. 转换旗标（可选），用于影响某些转换类型的结果。

  4. 最小字段宽度（可选）。 如果指定为 ‘'*'’ (星号)，则实际宽度会从
     `values' 元组的下一元素中读取，要转换的对象则为最小字段宽度和可选的
     精度之后的元素。

  5. 精度（可选），以在 ‘'.'’ (点号) 之后加精度值的形式给出。 如果指定为
     ‘'*'’ (星号)，则实际精度会从 `values' 元组的下一元素中读取，要转换
     的对象则为精度之后的元素。

  6. 长度修饰符（可选）。

  7. 转换类型。

当右边的参数为一个字典（或其他映射类型）时，字节串对象中的格式 `必须' 包
含加圆括号的映射键，对应 ‘'%'’ 字符之后字典中的每一项。 映射键将从映射中
选取要格式化的值。 例如：

     >>> print(b'%(language)s has %(number)03d quote types.' %
     ...       {b'language': b"Python", b"number": 2})
     b'Python has 002 quote types.'

在此情况下格式中不能出现 ‘*’ 标记符（因其需要一个序列类的参数列表）。

转换旗标为：

Flag          含义
              
----------------------------------------------------------------------------------------
              
‘'#'’         值的转换将使用“替代形式”（具体定义见下文）。
              
              
‘'0'’         转换将为数字值填充零字符。
              
              
‘'-'’         转换值将靠左对齐（如果同时给出 ‘'0'’ 转换，则会覆盖后者）。
              
              
‘' '’         (空格) 符号位转换产生的正数（或空字符串）前将留出一个空格。
              
              
‘'+'’         符号字符 (‘'+'’ 或 ‘'-'’) 将显示于转换结果的开头（会覆盖 "空格" 旗标）
              。
              

可以给出长度修饰符 (‘h’, ‘l’ 或 ‘L’)，但会被忽略，因为对 Python 来说没有
必要 – 所以 ‘%ld’ 等价于 ‘%d’。

转换类型为：

转换符           含义                                                      注释
                                                                           
---------------------------------------------------------------------------------------
                                                                           
‘'d'’            有符号十进制整数。
                 
                                                                           
‘'i'’            有符号十进制整数。
                 
                                                                           
‘'o'’            有符号八进制数。                                          (1)
                                                                           
                                                                           
‘'u'’            过时类型 – 等价于 ‘'d'’。                                 (8)
                                                                           
                                                                           
‘'x'’            有符号十六进制数（小写）。                                (2)
                                                                           
                                                                           
‘'X'’            有符号十六进制数（大写）。                                (2)
                                                                           
                                                                           
‘'e'’            浮点指数格式（小写）。                                    (3)
                                                                           
                                                                           
‘'E'’            浮点指数格式（大写）。                                    (3)
                                                                           
                                                                           
‘'f'’            浮点十进制格式。                                          (3)
                                                                           
                                                                           
‘'F'’            浮点十进制格式。                                          (3)
                                                                           
                                                                           
‘'g'’            浮点格式。 如果指数小于 -4 或不小于精度则使用小写指数格   (4)
                 式，否则使用十进制格式。                                  
                 
                                                                           
‘'G'’            浮点格式。 如果指数小于 -4 或不小于精度则使用大写指数格   (4)
                 式，否则使用十进制格式。                                  
                 
                                                                           
‘'c'’            单个字节（接受整数或单个字节对象）。
                 
                                                                           
‘'b'’            字节串（任何遵循 *note 缓冲区协议: 15f7. 或是具有         (5)
                 *note __bytes__(): 1447. 的对象）。                       
                 
                                                                           
‘'s'’            ‘'s'’ 是 ‘'b'’ 的一个别名，只应当在基于 Python2/3 的代    (6)
                 码中使用。                                                
                 
                                                                           
‘'a'’            字节串（使用                                              (5)
                 ‘repr(obj).encode('ascii','backslashreplace)’ 转换任何    
                 Python 对象）。
                 
                                                                           
‘'r'’            ‘'r'’ 是 ‘'a'’ 的一个别名，只应当在基于 Python2/3 的代    (7)
                 码中使用。                                                
                 
                                                                           
‘'%'’            不转换参数，在结果中输出一个 ‘'%'’ 字符。
                 

注释:

  1. 此替代形式会在第一个数码之前插入标示八进制数的前缀 (‘'0o'’)。

  2. 此替代形式会在第一个数码之前插入 ‘'0x'’ 或 ‘'0X'’ 前缀（取决于是使
     用 ‘'x'’ 还是 ‘'X'’ 格式）。

  3. 此替代形式总是会在结果中包含一个小数点，即使其后并没有数码。

     小数点后的数码位数由精度决定，默认为 6。

  4. 此替代形式总是会在结果中包含一个小数点，末尾各位的零不会如其他情况
     下那样被移除。

     小数点前后的有效数码位数由精度决定，默认为 6。

  5. 如果精度为 ‘N’，输出将截短为 ‘N’ 个字符。

  6. ‘b'%s'’ 已弃用，但在 3.x 系列中将不会被移除。

  7. ‘b'%r'’ 已弃用，但在 3.x 系列中将不会被移除。

  8. 参见 PEP 237(2)。

     注解: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一个新对
     象，即便没有做任何改变。

参见
....

PEP 461(3) - 为 bytes 和 bytearray 添加 % 格式化

3.5 新版功能.

   ---------- Footnotes ----------

   (1) (5) 要格式化单独一个元组，那么你应当提供一个单例元组，其唯一的元
素就是要被格式化的元组。

   (2) https://www.python.org/dev/peps/pep-0237

   (3) https://www.python.org/dev/peps/pep-0461


File: python.info,  Node: 内存视图,  Prev: printf 风格的字节串格式化,  Up: 二进制序列类型 --- bytes bytearray memoryview

5.4.8.5 内存视图
................

*note memoryview: 25d. 对象允许 Python 代码访问一个对象的内部数据，只要
该对象支持 *note 缓冲区协议: 15f7. 而无需进行拷贝。

 -- 类: memoryview (obj)

     创建一个引用 `obj' 的 *note memoryview: 25d.。 `obj' 必须支持缓冲区
     协议。 支持缓冲区协议的内置对象包括 *note bytes: 33a. 和 *note
     bytearray: 33b.。

     *note memoryview: 25d. 具有 `元素' 的概念，即由原始对象 `obj' 所处
     理的基本内存单元。 对于许多简单类型例如 *note bytes: 33a. 和 *note
     bytearray: 33b. 来说，一个元素就是一个字节，但是其他的类型例如
     *note array.array: 459. 可能有更大的元素。

     ‘len(view)’ 与 *note tolist: 16be. 的长度相等。 如果 ‘view.ndim =
     0’，则其长度为 1。 如果 ‘view.ndim = 1’，则其长度等于 view 中元素的
     数量。 对于更高的维度，其长度等于表示 view 的嵌套列表的长度。 *note
     itemsize: 16bf. 属性可向你给出单个元素所占的字节数。

     *note memoryview: 25d. 支持通过切片和索引访问其元素。 一维切片的结
     果将是一个子视图:

          >>> v = memoryview(b'abcefg')
          >>> v[1]
          98
          >>> v[-1]
          103
          >>> v[1:4]
          <memory at 0x7f3ddc9f4350>
          >>> bytes(v[1:4])
          b'bce'

     如果 *note format: 16c0. 是一个来自于 *note struct: f9. 模块的原生
     格式说明符，则也支持使用整数或由整数构成的元组进行索引，并返回具有
     正确类型的单个 `元素'。 一维内存视图可以使用一个整数或由一个整数构
     成的元组进行索引。 多维内存视图可以使用由恰好 `ndim' 个整数构成的元
     素进行索引，`ndim' 即其维度。 零维内存视图可以使用空元组进行索引。

     这里是一个使用非字节格式的例子:

          >>> import array
          >>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])
          >>> m = memoryview(a)
          >>> m[0]
          -11111111
          >>> m[-1]
          44444444
          >>> m[::2].tolist()
          [-11111111, -33333333]

     如果下层对象是可写的，则内存视图支持一维切片赋值。 改变大小则不被允
     许:

          >>> data = bytearray(b'abcefg')
          >>> v = memoryview(data)
          >>> v.readonly
          False
          >>> v[0] = ord(b'z')
          >>> data
          bytearray(b'zbcefg')
          >>> v[1:4] = b'123'
          >>> data
          bytearray(b'z123fg')
          >>> v[2:3] = b'spam'
          Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
          ValueError: memoryview assignment: lvalue and rvalue have different structures
          >>> v[2:6] = b'spam'
          >>> data
          bytearray(b'z1spam')

     由带有格式符号 ’B’, ’b’ 或 ’c’ 的可哈希（只读）类型构成的一维内存视
     图同样是可哈希的。 哈希定义为 ‘hash(m) == hash(m.tobytes())’:

          >>> v = memoryview(b'abcefg')
          >>> hash(v) == hash(b'abcefg')
          True
          >>> hash(v[2:4]) == hash(b'ce')
          True
          >>> hash(v[::-2]) == hash(b'abcefg'[::-2])
          True

     在 3.3 版更改: 一维内存视图现在可以被切片。 带有格式符号 ’B’, ’b’ 或
     ’c’ 的一维内存视图现在是可哈希的。

     在 3.4 版更改: 内存视图现在会自动注册为 *note
     collections.abc.Sequence: 1640.

     在 3.5 版更改: 内存视图现在可使用整数元组进行索引。

     *note memoryview: 25d. 具有以下一些方法：

      -- 方法: __eq__ (exporter)

          memoryview 与 PEP 3118(1) 中的导出器这两者如果形状相同，并且如
          果当使用 *note struct: f9. 语法解读操作数的相应格式代码时所有
          对应值都相同，则它们就是等价的。

          对于 *note tolist(): 16be. 当前所支持的 *note struct: f9. 格式
          字符串子集，如果 ‘v.tolist() == w.tolist()’ 则 ‘v’ 和 ‘w’ 相等
          :

               >>> import array
               >>> a = array.array('I', [1, 2, 3, 4, 5])
               >>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0])
               >>> c = array.array('b', [5, 3, 1])
               >>> x = memoryview(a)
               >>> y = memoryview(b)
               >>> x == a == y == b
               True
               >>> x.tolist() == a.tolist() == y.tolist() == b.tolist()
               True
               >>> z = y[::-2]
               >>> z == c
               True
               >>> z.tolist() == c.tolist()
               True

          如果两边的格式字符串都不被 *note struct: f9. 模块所支持，则两
          对象比较结果总是不相等（即使格式字符串和缓冲区内容相同）:

               >>> from ctypes import BigEndianStructure, c_long
               >>> class BEPoint(BigEndianStructure):
               ...     _fields_ = [("x", c_long), ("y", c_long)]
               ...
               >>> point = BEPoint(100, 200)
               >>> a = memoryview(point)
               >>> b = memoryview(point)
               >>> a == point
               False
               >>> a == b
               False

          请注意，与浮点数的情况一样，对于内存视图对象来说，‘v is w’ 也
          `并不' 意味着 ‘v == w’。

          在 3.3 版更改: 之前的版本比较原始内存时会忽略条目的格式与逻辑
          数组结构。

      -- 方法: tobytes (order=None)

          将缓冲区中的数据作为字节串返回。 这相当于在内存视图上调用
          *note bytes: 33a. 构造器。

               >>> m = memoryview(b"abc")
               >>> m.tobytes()
               b'abc'
               >>> bytes(m)
               b'abc'

          对于非连续数组，结果等于平面化表示的列表，其中所有元素都转换为
          字节串。 *note tobytes(): 16c2. 支持所有格式字符串，不符合
          *note struct: f9. 模块语法的那些也包括在内。

          3.8 新版功能: `order' 可以为 {’C’, ’F’, ’A’}。 当 `order' 为
          ’C’ 或 ’F’ 时，原始数组的数据会被转换至 C 或 Fortran 顺序。 对
          于连续视图，’A’ 会返回物理内存的精确副本。 特别地，内存中的
          Fortran 顺序会被保留。对于非连续视图，数据会先被转换为 C 形式
          。 `order=None' 与 `order=’C’' 是相同的。

      -- 方法: hex ([sep[, bytes_per_sep]])

          返回一个字符串对象，其中分别以两个十六进制数码表示缓冲区里的每
          个字节。

               >>> m = memoryview(b"abc")
               >>> m.hex()
               '616263'

          3.5 新版功能.

          在 3.8 版更改: 与 *note bytes.hex(): 63a. 相似， *note
          memoryview.hex(): 63c. 现在支持可选的 `sep' 和 `bytes_per_sep'
          参数以在十六进制输出的字节之间插入分隔符。

      -- 方法: tolist ()

          将缓冲区内的数据以一个元素列表的形式返回。

               >>> memoryview(b'abc').tolist()
               [97, 98, 99]
               >>> import array
               >>> a = array.array('d', [1.1, 2.2, 3.3])
               >>> m = memoryview(a)
               >>> m.tolist()
               [1.1, 2.2, 3.3]

          在 3.3 版更改: *note tolist(): 16be. 现在支持 *note struct:
          f9. 模块语法中的所有单字符原生格式以及多维表示形式。

      -- 方法: toreadonly ()

          返回 memoryview 对象的只读版本。 原始的 memoryview 对象不会被
          改变。

               >>> m = memoryview(bytearray(b'abc'))
               >>> mm = m.toreadonly()
               >>> mm.tolist()
               [89, 98, 99]
               >>> mm[0] = 42
               Traceback (most recent call last):
                 File "<stdin>", line 1, in <module>
               TypeError: cannot modify read-only memory
               >>> m[0] = 43
               >>> mm.tolist()
               [43, 98, 99]

          3.8 新版功能.

      -- 方法: release ()

          释放由内存视图对象所公开的底层缓冲区。 许多对象在被视图所获取
          时都会采取特殊动作（例如，*note bytearray: 33b. 将会暂时禁止调
          整大小）；因此，调用 release() 可以方便地尽早去除这些限制（并
          释放任何多余的资源）。

          在此方法被调用后，任何对视图的进一步操作将引发 *note
          ValueError: 1fc. (*note release(): b45. 本身除外，它可以被多次
          调用):

               >>> m = memoryview(b'abc')
               >>> m.release()
               >>> m[0]
               Traceback (most recent call last):
                 File "<stdin>", line 1, in <module>
               ValueError: operation forbidden on released memoryview object

          使用 ‘with’ 语句，可以通过上下文管理协议达到类似的效果:

               >>> with memoryview(b'abc') as m:
               ...     m[0]
               ...
               97
               >>> m[0]
               Traceback (most recent call last):
                 File "<stdin>", line 1, in <module>
               ValueError: operation forbidden on released memoryview object

          3.2 新版功能.

      -- 方法: cast (format[, shape])

          将内存视图转化为新的格式或形状。 `shape' 默认为
          ‘[byte_length//new_itemsize]’，这意味着结果视图将是一维的。 返
          回值是一个新的内存视图，但缓冲区本身不会被复制。 支持的转化有
          1D -> C-*note contiguous: 16c5. 和 C-contiguous -> 1D。

          目标格式仅限于 *note struct: f9. 语法中的单一元素原生格式。 其
          中一种格式必须为字节格式 (’B’, ’b’ 或 ’c’)。 结果的字节长度必
          须与原始长度相同。

          将 1D/long 转换为 1D/unsigned bytes:

               >>> import array
               >>> a = array.array('l', [1,2,3])
               >>> x = memoryview(a)
               >>> x.format
               'l'
               >>> x.itemsize
               8
               >>> len(x)
               3
               >>> x.nbytes
               24
               >>> y = x.cast('B')
               >>> y.format
               'B'
               >>> y.itemsize
               1
               >>> len(y)
               24
               >>> y.nbytes
               24

          将 1D/unsigned bytes 转换为 1D/char:

               >>> b = bytearray(b'zyz')
               >>> x = memoryview(b)
               >>> x[0] = b'a'
               Traceback (most recent call last):
                 File "<stdin>", line 1, in <module>
               ValueError: memoryview: invalid value for format "B"
               >>> y = x.cast('c')
               >>> y[0] = b'a'
               >>> b
               bytearray(b'ayz')

          将 1D/bytes 转换为 3D/ints 再转换为 1D/signed char:

               >>> import struct
               >>> buf = struct.pack("i"*12, *list(range(12)))
               >>> x = memoryview(buf)
               >>> y = x.cast('i', shape=[2,2,3])
               >>> y.tolist()
               [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
               >>> y.format
               'i'
               >>> y.itemsize
               4
               >>> len(y)
               2
               >>> y.nbytes
               48
               >>> z = y.cast('b')
               >>> z.format
               'b'
               >>> z.itemsize
               1
               >>> len(z)
               48
               >>> z.nbytes
               48

          将 1D/unsigned long 转换为 2D/unsigned long:

               >>> buf = struct.pack("L"*6, *list(range(6)))
               >>> x = memoryview(buf)
               >>> y = x.cast('L', shape=[2,3])
               >>> len(y)
               2
               >>> y.nbytes
               48
               >>> y.tolist()
               [[0, 1, 2], [3, 4, 5]]

          3.3 新版功能.

          在 3.5 版更改: 当转换为字节视图时，源格式将不再受限。

     还存在一些可用的只读属性：

      -- 属性: obj

          内存视图的下层对象:

               >>> b  = bytearray(b'xyz')
               >>> m = memoryview(b)
               >>> m.obj is b
               True

          3.3 新版功能.

      -- 属性: nbytes

          ‘nbytes == product(shape) * itemsize == len(m.tobytes())’。 这
          是数组在连续表示时将会占用的空间总字节数。 它不一定等于
          ‘len(m)’:

               >>> import array
               >>> a = array.array('i', [1,2,3,4,5])
               >>> m = memoryview(a)
               >>> len(m)
               5
               >>> m.nbytes
               20
               >>> y = m[::2]
               >>> len(y)
               3
               >>> y.nbytes
               12
               >>> len(y.tobytes())
               12

          多维数组:

               >>> import struct
               >>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)])
               >>> x = memoryview(buf)
               >>> y = x.cast('d', shape=[3,4])
               >>> y.tolist()
               [[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]
               >>> len(y)
               3
               >>> y.nbytes
               96

          3.3 新版功能.

      -- 属性: readonly

          一个表明内存是否只读的布尔值。

      -- 属性: format

          一个字符串，包含视图中每个元素的格式（表示为 *note struct: f9.
          模块样式）。 内存视图可以从具有任意格式字符串的导出器创建，但
          某些方法 (例如 *note tolist(): 16be.) 仅限于原生的单元素格式。

          在 3.3 版更改: 格式 ‘'B'’ 现在会按照 struct 模块语法来处理。 这
          意味着 ‘memoryview(b'abc')[0] == b'abc'[0] == 97’。

      -- 属性: itemsize

          memoryview 中每个元素以字节表示的大小:

               >>> import array, struct
               >>> m = memoryview(array.array('H', [32000, 32001, 32002]))
               >>> m.itemsize
               2
               >>> m[0]
               32000
               >>> struct.calcsize('H') == m.itemsize
               True

      -- 属性: ndim

          一个整数，表示内存所代表的多维数组具有多少个维度。

      -- 属性: shape

          一个整数元组，通过 *note ndim: 16c9. 的长度值给出内存所代表的
          N 维数组的形状。

          在 3.3 版更改: 当 ndim = 0 时值为空元组而不再为 ‘None’。

      -- 属性: strides

          一个整数元组，通过 *note ndim: 16c9. 的长度给出以字节表示的大
          小，以便访问数组中每个维度上的每个元素。

          在 3.3 版更改: 当 ndim = 0 时值为空元组而不再为 ‘None’。

      -- 属性: suboffsets

          供 PIL 风格的数组内部使用。 该值仅作为参考信息。

      -- 属性: c_contiguous

          一个表明内存是否为 C-*note contiguous: 16c5. 的布尔值。

          3.3 新版功能.

      -- 属性: f_contiguous

          一个表明内存是否为 Fortran *note contiguous: 16c5. 的布尔值。

          3.3 新版功能.

      -- 属性: contiguous

          一个表明内存是否为 *note contiguous: 16c5. 的布尔值。

          3.3 新版功能.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3118


File: python.info,  Node: 集合类型 --- set frozenset,  Next: 映射类型 --- dict,  Prev: 二进制序列类型 --- bytes bytearray memoryview,  Up: 内置类型

5.4.9 集合类型 — ‘set’, ‘frozenset’
-----------------------------------

`set' 对象是由具有唯一性的 *note hashable: 1439. 对象所组成的无序多项集
。 常见的用途包括成员检测、从序列中去除重复项以及数学中的集合类计算，例
如交集、并集、差集与对称差集等等。 （关于其他容器对象请参看 *note dict:
1b9, *note list: 263. 与 *note tuple: 486. 等内置类，以及 *note
collections: 1e. 模块。）

与其他多项集一样，集合也支持 ‘x in set’, ‘len(set)’ 和 ‘for x in set’。
作为一种无序的多项集，集合并不记录元素位置或插入顺序。 相应地，集合不支
持索引、切片或其他序列类的操作。

目前有两种内置集合类型，*note set: b77. 和 *note frozenset: bf6.。 *note
set: b77. 类型是可变的 — 其内容可以使用 ‘add()’ 和 ‘remove()’ 这样的方法
来改变。 由于是可变类型，它没有哈希值，且不能被用作字典的键或其他集合的
元素。 *note frozenset: bf6. 类型是不可变并且为 *note hashable: 1439. —
其内容在被创建后不能再改变；因此它可以被用作字典的键或其他集合的元素。

除了可以使用 *note set: b77. 构造器，非空的 set (不是 frozenset) 还可以
通过将以逗号分隔的元素列表包含于花括号之内来创建，例如: ‘{'jack',
'sjoerd'}’。

两个类的构造器具有相同的作用方式：

 -- 类: set ([iterable])
 -- 类: frozenset ([iterable])

     返回一个新的 set 或 frozenset 对象，其元素来自于 `iterable'。 集合
     的元素必须为 *note hashable: 1439.。 要表示由集合对象构成的集合，所
     有的内层集合必须为 *note frozenset: bf6. 对象。 如果未指定
     `iterable'，则将返回一个新的空集合。

     集合可用多种方式来创建:

        * 使用花括号内以逗号分隔元素的方式: ‘{'jack', 'sjoerd'}’

        * 使用集合推导式: ‘{c for c in 'abracadabra' if c not in 'abc'}’

        * 使用类型构造器: ‘set()’, ‘set('foobar')’, ‘set(['a', 'b',
          'foo'])’

     *note set: b77. 和 *note frozenset: bf6. 的实例提供以下操作：

      -- Describe: len(s)

          返回集合 `s' 中的元素数量（即 `s' 的基数）。

      -- Describe: x in s

          检测 `x' 是否为 `s' 中的成员。

      -- Describe: x not in s

          检测 `x' 是否非 `s' 中的成员。

      -- 方法: isdisjoint (other)

          如果集合中没有与 `other' 共有的元素则返回 ‘True’。 当且仅当两
          个集合的交集为空集合时，两者为不相交集合。

      -- 方法: issubset (other)

      -- 方法: set <= other

          检测是否集合中的每个元素都在 `other' 之中。

      -- 方法: set < other

          检测集合是否为 `other' 的真子集，即 ‘set <= other and set !=
          other’。

      -- 方法: issuperset (other)

      -- 方法: set >= other

          检测是否 `other' 中的每个元素都在集合之中。

      -- 方法: set > other

          检测集合是否为 `other' 的真超集，即 ‘set >= other and set !=
          other’。

      -- 方法: union (*others)

      -- 方法: set | other | ...

          返回一个新集合，其中包含来自原集合以及 others 指定的所有集合中
          的元素。

      -- 方法: intersection (*others)

      -- 方法: set & other & ...

          返回一个新集合，其中包含原集合以及 others 指定的所有集合中共有
          的元素。

      -- 方法: difference (*others)

      -- 方法: set - other - ...

          返回一个新集合，其中包含原集合中在 others 指定的其他集合中不存
          在的元素。

      -- 方法: symmetric_difference (other)

      -- 方法: set ^ other

          返回一个新集合，其中的元素或属于原集合或属于 `other' 指定的其
          他集合，但不能同时属于两者。

      -- 方法: copy ()

          返回原集合的浅拷贝。

     请注意，非运算符版本的 *note union(): 16d4, *note intersection():
     16d5, *note difference(): 16d6.，以及 *note symmetric_difference():
     16d7, *note issubset(): 16d2. 和 *note issuperset(): 16d3. 方法会接
     受任意可迭代对象作为参数。 相比之下，它们所对应的运算符版本则要求其
     参数为集合。 这就排除了容易出错的构造形式例如 ‘set('abc') & 'cbs'’，
     而推荐可读性更强的 ‘set('abc').intersection('cbs')’。

     *note set: b77. 和 *note frozenset: bf6. 均支持集合与集合的比较。 两
     个集合当且仅当每个集合中的每个元素均包含于另一个集合之内（即各为对
     方的子集）时则相等。 一个集合当且仅当其为另一个集合的真子集（即为后
     者的子集但两者不相等）时则小于另一个集合。 一个集合当且仅当其为另一
     个集合的真超集（即为后者的超集但两者不相等）时则大于另一个集合。

     *note set: b77. 的实例与 *note frozenset: bf6. 的实例之间基于它们的
     成员进行比较。 例如 ‘set('abc') == frozenset('abc')’ 返回 ‘True’，
     ‘set('abc') in set([frozenset('abc')])’ 也一样。

     子集与相等比较并不能推广为完全排序函数。 例如，任意两个非空且不相交
     的集合不相等且互不为对方的子集，因此以下 `所有' 比较均返回 ‘False’:
     ‘a<b’, ‘a==b’, or ‘a>b’。

     由于集合仅定义了部分排序（子集关系），因此由集合构成的列表 *note
     list.sort(): 44d. 方法的输出并无定义。

     集合的元素，与字典的键类似，必须为 *note hashable: 1439.。

     混合了 *note set: b77. 实例与 *note frozenset: bf6. 的二进制位运算
     将返回与第一个操作数相同的类型。例如: ‘frozenset('ab') | set('bc')’
     将返回 *note frozenset: bf6. 的实例。

     下表列出了可用于 *note set: b77. 而不能用于不可变的 *note
     frozenset: bf6. 实例的操作：

      -- 方法: update (*others)

      -- 方法: set |= other | ...

          更新集合，添加来自 others 中的所有元素。

      -- 方法: intersection_update (*others)

      -- 方法: set &= other & ...

          更新集合，只保留其中在所有 others 中也存在的元素。

      -- 方法: difference_update (*others)

      -- 方法: set -= other | ...

          更新集合，移除其中也存在于 others 中的元素。

      -- 方法: symmetric_difference_update (other)

      -- 方法: set ^= other

          更新集合，只保留存在于集合的一方而非共同存在的元素。

      -- 方法: add (elem)

          将元素 `elem' 添加到集合中。

      -- 方法: remove (elem)

          从集合中移除元素 `elem'。 如果 `elem' 不存在于集合中则会引发
          *note KeyError: 2c8.。

      -- 方法: discard (elem)

          如果元素 `elem' 存在于集合中则将其移除。

      -- 方法: pop ()

          从集合中移除并返回任意一个元素。 如果集合为空则会引发 *note
          KeyError: 2c8.。

      -- 方法: clear ()

          从集合中移除所有元素。

     请注意，非运算符版本的 *note update(): 16d9, *note
     intersection_update(): 16da, *note difference_update(): 16db. 和
     *note symmetric_difference_update(): 16dc. 方法将接受任意可迭代对象
     作为参数。

     请注意，*note __contains__(): d30, *note remove(): 16de. 和 *note
     discard(): 16df. 方法的 `elem' 参数可能是一个 set。 为支持对一个等
     价的 frozenset 进行搜索，会根据 `elem' 临时创建一个该类型对象。


File: python.info,  Node: 映射类型 --- dict,  Next: 上下文管理器类型,  Prev: 集合类型 --- set frozenset,  Up: 内置类型

5.4.10 映射类型 — ‘dict’
------------------------

*note mapping: b41. 对象会将 *note hashable: 1439. 值映射到任意对象。 映
射属于可变对象。 目前仅有一种标准映射类型 `字典'。 （关于其他容器对象请
参看 *note list: 263, *note set: b77. 与 *note tuple: 486. 等内置类，以
及 *note collections: 1e. 模块。）

字典的键 `几乎' 可以是任何值。 非 *note hashable: 1439. 的值，即包含列表
、字典或其他可变类型的值（此类对象基于值而非对象标识进行比较）不可用作键
。 数字类型用作键时遵循数字比较的一般规则：如果两个数值相等 (例如 ‘1’ 和
‘1.0’) 则两者可以被用来索引同一字典条目。 （但是请注意，由于计算机对于浮
点数存储的只是近似值，因此将其用作字典键是不明智的。）

字典可以通过将以逗号分隔的 ‘键: 值’ 对列表包含于花括号之内来创建，例如:
‘{'jack': 4098, 'sjoerd': 4127}’ 或 ‘{4098: 'jack', 4127: 'sjoerd'}’，也
可以通过 *note dict: 1b9. 构造器来创建。

 -- 类: dict (**kwarg)

 -- 类: dict (mapping, **kwarg)

 -- 类: dict (iterable, **kwarg)

     返回一个新的字典，基于可选的位置参数和可能为空的关键字参数集来初始
     化。

     字典可用多种方式来创建:

        * 使用花括号内以逗号分隔 ‘键: 值’ 对的方式: ‘{'jack': 4098,
          'sjoerd': 4127}’ or ‘{4098: 'jack', 4127: 'sjoerd'}’

        * 使用字典推导式: ‘{}’, ‘{x: x ** 2 for x in range(10)}’

        * 使用类型构造器: ‘dict()’, ‘dict([('foo', 100), ('bar',
          200)])’, ‘dict(foo=100, bar=200)’

     如果没有给出位置参数，将创建一个空字典。 如果给出一个位置参数并且其
     属于映射对象，将创建一个具有与映射对象相同键值对的字典。 否则的话，
     位置参数必须为一个 *note iterable: bb4. 对象。 该可迭代对象中的每一
     项本身必须为一个刚好包含两个元素的可迭代对象。 每一项中的第一个对象
     将成为新字典的一个键，第二个对象将成为其对应的值。 如果一个键出现一
     次以上，该键的最后一个值将成为其在新字典中对应的值。

     如果给出了关键字参数，则关键字参数及其值会被加入到基于位置参数创建
     的字典。 如果要加入的键已存在，来自关键字参数的值将替代来自位置参数
     的值。

     作为演示，以下示例返回的字典均等于 ‘{"one": 1, "two": 2, "three":
     3}’:

          >>> a = dict(one=1, two=2, three=3)
          >>> b = {'one': 1, 'two': 2, 'three': 3}
          >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
          >>> d = dict([('two', 2), ('one', 1), ('three', 3)])
          >>> e = dict({'three': 3, 'one': 1, 'two': 2})
          >>> a == b == c == d == e
          True

     像第一个例子那样提供关键字参数的方式只能使用有效的 Python 标识符作
     为键。 其他方式则可使用任何有效的键。

     这些是字典所支持的操作（因而自定义的映射类型也应当支持）：

      -- Describe: list(d)

          返回字典 `d' 中使用的所有键的列表。

      -- Describe: len(d)

          返回字典 `d' 中的项数。

      -- Describe: d[key]

          返回 `d' 中以 `key' 为键的项。 如果映射中不存在 `key' 则会引发
          *note KeyError: 2c8.。

          如果字典的子类定义了方法 *note __missing__(): b43. 并且 `key'
          不存在，则 ‘d[key]’ 操作将调用该方法并附带键 `key' 作为参数。
          ‘d[key]’ 随后将返回或引发 ‘__missing__(key)’ 调用所返回或引发
          的任何对象或异常。 没有其他操作或方法会发起调用 *note
          __missing__(): b43.。 如果未定义 *note __missing__(): b43.，则
          会引发 *note KeyError: 2c8.。 *note __missing__(): b43. 必须是
          一个方法；它不能是一个实例变量:

               >>> class Counter(dict):
               ...     def __missing__(self, key):
               ...         return 0
               >>> c = Counter()
               >>> c['red']
               0
               >>> c['red'] += 1
               >>> c['red']
               1

          上面的例子显示了 *note collections.Counter: 9e2. 实现的部分代
          码。 还有另一个不同的 ‘__missing__’ 方法是由 *note
          collections.defaultdict: b42. 所使用的。

      -- Describe: d[key] = value

          将 ‘d[key]’ 设为 `value'。

      -- Describe: del d[key]

          将 ‘d[key]’ 从 `d' 中移除。 如果映射中不存在 `key' 则会引发
          *note KeyError: 2c8.。

      -- Describe: key in d

          如果 `d' 中存在键 `key' 则返回 ‘True’，否则返回 ‘False’。

      -- Describe: key not in d

          等价于 ‘not key in d’。

      -- Describe: iter(d)

          返回以字典的键为元素的迭代器。 这是 ‘iter(d.keys())’ 的快捷方
          式。

      -- 方法: clear ()

          移除字典中的所有元素。

      -- 方法: copy ()

          返回原字典的浅拷贝。

      -- 方法: classmethod fromkeys (iterable[, value])

          使用来自 `iterable' 的键创建一个新字典，并将键值设为 `value'。

          *note fromkeys(): 16e4. 是一个返回新字典的类方法。 `value' 默
          认为 ‘None’。 所有值都只引用一个单独的实例，因此让 `value' 成
          为一个可变对象例如空列表通常是没有意义的。 要获取不同的值，请
          改用 *note 字典推导式: 657.。

      -- 方法: get (key[, default])

          如果 `key' 存在于字典中则返回 `key' 的值，否则返回 `default'。
          如果 `default' 未给出则默认为 ‘None’，因而此方法绝不会引发
          *note KeyError: 2c8.。

      -- 方法: items ()

          返回由字典项 (‘(键, 值)’ 对) 组成的一个新视图。 参见 *note
          视图对象文档: 16e6.。

      -- 方法: keys ()

          返回由字典键组成的一个新视图。 参见 *note 视图对象文档: 16e6.。

      -- 方法: pop (key[, default])

          如果 `key' 存在于字典中则将其移除并返回其值，否则返回
          `default'。 如果 `default' 未给出且 `key' 不存在于字典中，则会
          引发 *note KeyError: 2c8.。

      -- 方法: popitem ()

          从字典中移除并返回一个 ‘(键, 值)’ 对。 键值对会按 LIFO (后进先
          出) 的顺序被返回。

          *note popitem(): 16e8. 适用于对字典进行消耗性的迭代，这在集合
          算法中经常被使用。 如果字典为空，调用 *note popitem(): 16e8. 将
          引发 *note KeyError: 2c8.。

          在 3.7 版更改: 现在会确保采用 LIFO 顺序。 在之前的版本中，
          *note popitem(): 16e8. 会返回一个任意的键/值对。

      -- Describe: reversed(d)

          返回一个逆序获取字典键的迭代器。 这是 ‘reversed(d.keys())’ 的
          快捷方式。

          3.8 新版功能.

      -- 方法: setdefault (key[, default])

          如果字典存在键 `key' ，返回它的值。如果不存在，插入值为
          `default' 的键 `key' ，并返回 `default' 。 `default' 默认为
          ‘None’。

      -- 方法: update ([other])

          使用来自 `other' 的键/值对更新字典，覆盖原有的键。 返回
          ‘None’。

          *note update(): dd1. 接受另一个字典对象，或者一个包含键/值对（
          以长度为二的元组或其他可迭代对象表示）的可迭代对象。 如果给出
          了关键字参数，则会以其所指定的键/值对更新字典:
          ‘d.update(red=1, blue=2)’。

      -- 方法: values ()

          返回由字典值组成的一个新视图。 参见 *note 视图对象文档: 16e6.。

          两个 ‘dict.values()’ 视图之间的相等性比较将总是返回 ‘False’。
          这在 ‘dict.values()’ 与其自身比较时也同样适用:

               >>> d = {'a': 1}
               >>> d.values() == d.values()
               False

     两个字典的比较当且仅当它们具有相同的 ‘(键, 值)’ 对时才会相等（不考
     虑顺序）。 排序比较 (’<’, ’<=’, ’>=’, ’>’) 会引发 *note TypeError:
     193.。

     字典会保留插入时的顺序。 请注意对键的更新不会影响顺序。 删除并再次
     添加的键将被插入到末尾。

          >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
          >>> d
          {'one': 1, 'two': 2, 'three': 3, 'four': 4}
          >>> list(d)
          ['one', 'two', 'three', 'four']
          >>> list(d.values())
          [1, 2, 3, 4]
          >>> d["one"] = 42
          >>> d
          {'one': 42, 'two': 2, 'three': 3, 'four': 4}
          >>> del d["two"]
          >>> d["two"] = None
          >>> d
          {'one': 42, 'three': 3, 'four': 4, 'two': None}

     在 3.7 版更改: 字典顺序会确保为插入顺序。 此行为是自 3.6 版开始的
     CPython 实现细节。

     字典和字典视图都是可逆的。

          >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
          >>> d
          {'one': 1, 'two': 2, 'three': 3, 'four': 4}
          >>> list(reversed(d))
          ['four', 'three', 'two', 'one']
          >>> list(reversed(d.values()))
          [4, 3, 2, 1]
          >>> list(reversed(d.items()))
          [('four', 4), ('three', 3), ('two', 2), ('one', 1)]

     在 3.8 版更改: 字典现在是可逆的。

参见
....

*note types.MappingProxyType: abe. 可被用来创建一个 *note dict: 1b9. 的
只读视图。

* Menu:

* 字典视图对象::


File: python.info,  Node: 字典视图对象,  Up: 映射类型 --- dict

5.4.10.1 字典视图对象
.....................

由 *note dict.keys(): c32, *note dict.values(): c34. 和 *note
dict.items(): c33. 所返回的对象是 `视图对象'。 该对象提供字典条目的一个
动态视图，这意味着当字典改变时，视图也会相应改变。

字典视图可以被迭代以产生与其对应的数据，并支持成员检测：

 -- Describe: len(dictview)

     返回字典中的条目数。

 -- Describe: iter(dictview)

     返回字典中的键、值或项（以 ‘(键, 值)’ 为元素的元组表示）的迭代器。

     键和值是按插入时的顺序进行迭代的。 这样就允许使用 *note zip(): c3a.
     来创建 ‘(值, 键)’ 对: ‘pairs = zip(d.values(), d.keys())’。 另一个
     创建相同列表的方式是 ‘pairs = [(v, k) for (k, v) in d.items()]’.

     在添加或删除字典中的条目期间对视图进行迭代可能引发 *note
     RuntimeError: 2bb. 或者无法完全迭代所有条目。

     在 3.7 版更改: 字典顺序会确保为插入顺序。

 -- Describe: x in dictview

     如果 `x' 是对应字典中存在的键、值或项（在最后一种情况下 `x' 应为一
     个 ‘(键, 值)’ 元组） 则返回 ‘True’。

 -- Describe: reversed(dictview)

     返回一个逆序获取字典键、值或项的迭代器。 视图将按与插入时相反的顺序
     进行迭代。

     在 3.8 版更改: 字典视图现在是可逆的。

键视图类似于集合，因为其条目不重复且可哈希。 如果所有值都是可哈希的，即
‘(键, 值)’ 对也是不重复且可哈希的，那么条目视图也会类似于集合。 （值视图
则不被视为类似于集合，因其条目通常都是有重复的。） 对于类似于集合的视图
，为抽象基类 *note collections.abc.Set: 16ea. 所定义的全部操作都是有效的
(例如 ‘==’, ‘<’ 或 ‘^’)。

一个使用字典视图的示例:

     >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
     >>> keys = dishes.keys()
     >>> values = dishes.values()

     >>> # iteration
     >>> n = 0
     >>> for val in values:
     ...     n += val
     >>> print(n)
     504

     >>> # keys and values are iterated over in the same order (insertion order)
     >>> list(keys)
     ['eggs', 'sausage', 'bacon', 'spam']
     >>> list(values)
     [2, 1, 1, 500]

     >>> # view objects are dynamic and reflect dict changes
     >>> del dishes['eggs']
     >>> del dishes['sausage']
     >>> list(keys)
     ['bacon', 'spam']

     >>> # set operations
     >>> keys & {'eggs', 'bacon', 'salad'}
     {'bacon'}
     >>> keys ^ {'sausage', 'juice'}
     {'juice', 'sausage', 'bacon', 'spam'}


File: python.info,  Node: 上下文管理器类型,  Next: 其他内置类型,  Prev: 映射类型 --- dict,  Up: 内置类型

5.4.11 上下文管理器类型
-----------------------

Python 的 *note with: 6f2. 语句支持通过上下文管理器所定义的运行时上下文
这一概念。 此对象的实现使用了一对专门方法，允许用户自定义类来定义运行时
上下文，在语句体被执行前进入该上下文，并在语句执行完毕时退出该上下文：

 -- 方法: contextmanager.__enter__ ()

     进入运行时上下文并返回此对象或关联到该运行时上下文的其他对象。 此方
     法的返回值会绑定到使用此上下文管理器的 *note with: 6f2. 语句的 ‘as’
     子句中的标识符。

     一个返回其自身的上下文管理器的例子是 *note file object: b4a.。 文件
     对象会从 __enter__() 返回其自身，以允许 *note open(): 4f8. 被用作
     *note with: 6f2. 语句中的上下文表达式。

     一个返回关联对象的上下文管理器的例子是 *note
     decimal.localcontext(): 16ed. 所返回的对象。 此种管理器会将活动的
     decimal 上下文设为原始 decimal 上下文的一个副本并返回该副本。 这允
     许对 *note with: 6f2. 语句的语句体中的当前 decimal 上下文进行更改，
     而不会影响 ‘with’ 语句以外的代码。

 -- 方法: contextmanager.__exit__ (exc_type, exc_val, exc_tb)

     退出运行时上下文并返回一个布尔值旗标来表明所发生的任何异常是否应当
     被屏蔽。 如果在执行 *note with: 6f2. 语句的语句体期间发生了异常，则
     参数会包含异常的类型、值以及回溯信息。 在其他情况下三个参数均为
     ‘None’。

     自此方法返回一个真值将导致 *note with: 6f2. 语句屏蔽异常并继续执行
     紧随在 ‘with’ 语句之后的语句。 否则异常将在此方法结束执行后继续传播
     。 在此方法执行期间发生的异常将会取代 ‘with’ 语句的语句体中发生的任
     何异常。

     传入的异常绝对不应当被显式地重新引发 —— 相反地，此方法应当返回一个
     假值以表明方法已成功完成并且不希望屏蔽被引发的异常。 这允许上下文管
     理代码方便地检测 *note __exit__(): 16ee. 方法是否确实已失败。

Python 定义了一些上下文管理器来支持简易的线程同步、文件或其他对象的快速
关闭，以及更方便地操作活动的十进制算术上下文。 除了实现上下文管理协议以
外，不同类型不会被特殊处理。 请参阅 *note contextlib: 24. 模块查看相关的
示例。

Python 的 *note generator: 9aa. 和 *note contextlib.contextmanager: b86.
装饰器提供了实现这些协议的便捷方式。 如果使用 *note
contextlib.contextmanager: b86. 装饰器来装饰一个生成器函数，它将返回一个
实现了必要的 *note __enter__(): c9d. and *note __exit__(): c9e. 方法的上
下文管理器，而不再是由未经装饰的生成器函数所产生的迭代器。

请注意，Python/C API 中 Python 对象的类型结构中并没有针对这些方法的专门
槽位。 想要定义这些方法的扩展类型必须将它们作为普通的 Python 可访问方法
来提供。 与设置运行时上下文的开销相比，单个类字典查找的开销可以忽略不计
。


File: python.info,  Node: 其他内置类型,  Next: 特殊属性,  Prev: 上下文管理器类型,  Up: 内置类型

5.4.12 其他内置类型
-------------------

解释器支持一些其他种类的对象。 这些对象大都仅支持一两种操作。

* Menu:

* 模块: 模块<2>.
* 类与类实例::
* 函数::
* 方法::
* 代码对象::
* 类型对象::
* 空对象::
* 省略符对象::
* 未实现对象::
* 布尔值::
* 内部对象::


File: python.info,  Node: 模块<2>,  Next: 类与类实例,  Up: 其他内置类型

5.4.12.1 模块
.............

模块唯一的特殊操作是属性访问: ‘m.name’，这里 `m' 为一个模块而 `name' 访
问定义在 `m' 的符号表中的一个名称。 模块属性可以被赋值。 （请注意 *note
import: c25. 语句严格来说也是对模块对象的一种操作；‘import foo’ 不要求存
在一个名为 `foo' 的模块对象，而是要求存在一个对于名为 `foo' 的模块的 (永
久性) `定义'。）

每个模块都有一个特殊属性 *note __dict__: 504.。 这是包含模块的符号表的字
典。 修改此字典将实际改变模块的符号表，但是无法直接对 *note __dict__:
504. 赋值 (你可以写 ‘m.__dict__['a'] = 1’，这会将 ‘m.a’ 定义为 ‘1’，但是
你不能写 ‘m.__dict__ = {}’)。 不建议直接修改 *note __dict__: 504.。

内置于解释器中的模块会写成这样: ‘<module 'sys' (built-in)>’。 如果是从一
个文件加载，则会写成 ‘<module 'os' from
'/usr/local/lib/pythonX.Y/os.pyc'>’。


File: python.info,  Node: 类与类实例,  Next: 函数,  Prev: 模块<2>,  Up: 其他内置类型

5.4.12.2 类与类实例
...................

关于这些类型请参阅 *note 对象、值与类型: 142e. 和 *note 类定义: c72.。


File: python.info,  Node: 函数,  Next: 方法,  Prev: 类与类实例,  Up: 其他内置类型

5.4.12.3 函数
.............

函数对象是通过函数定义创建的。 对函数对象的唯一操作是调用它:
‘func(argument-list)’。

实际上存在两种不同的函数对象：内置函数和用户自定义函数。 两者支持同样的
操作（调用函数），但实现方式不同，因此对象类型也不同。

更多信息请参阅 *note 函数定义: 126c.。


File: python.info,  Node: 方法,  Next: 代码对象,  Prev: 函数,  Up: 其他内置类型

5.4.12.4 方法
.............

方法是使用属性表示法来调用的函数。 存在两种形式：内置方法（例如列表的
‘append()’ 方法）和类实例方法。 内置方法由支持它们的类型来描述。

如果你通过一个实例来访问方法（即定义在类命名空间内的函数），你会得到一个
特殊对象: `绑定方法' (或称 `实例方法') 对象。 当被调用时，它会将 ‘self’
参数添加到参数列表。 绑定方法具有两个特殊的只读属性: ‘m.__self__’ 操作该
方法的对象，而 ‘m.__func__’ 是实现该方法的函数。 调用 ‘m(arg-1, arg-2,
..., arg-n)’ 完全等价于调用 ‘m.__func__(m.__self__, arg-1, arg-2, ...,
arg-n)’。

与函数对象类似，绑定方法对象也支持获取任意属性。 但是，由于方法属性实际
上保存于下层的函数对象中 (‘meth.__func__’)，因此不允许设置绑定方法的方法
属性。 尝试设置方法的属性将会导致引发 *note AttributeError: 3a3.。 想要
设置方法属性，你必须在下层的函数对象中显式地对其进行设置:

     >>> class C:
     ...     def method(self):
     ...         pass
     ...
     >>> c = C()
     >>> c.method.whoami = 'my name is method'  # can't set on the method
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     AttributeError: 'method' object has no attribute 'whoami'
     >>> c.method.__func__.whoami = 'my name is method'
     >>> c.method.whoami
     'my name is method'

更多信息请参阅 *note 标准类型层级结构: 1431.。


File: python.info,  Node: 代码对象,  Next: 类型对象,  Prev: 方法,  Up: 其他内置类型

5.4.12.5 代码对象
.................

代码对象被具体实现用来表示“伪编译”的可执行 Python 代码，例如一个函数体。
它们不同于函数对象，因为它们不包含对其全局执行环境的引用。 代码对象由内
置的 *note compile(): 1b5. 函数返回，并可通过从函数对象的 ‘__code__’ 属
性从中提取。 另请参阅 *note code: 1b. 模块。

Accessing ‘__code__’ raises an *note auditing event: ea1.
‘object.__getattr__’ with arguments ‘obj’ and ‘"__code__"’.

可以通过将代码对象（而非源码字符串）传给 *note exec(): c4c. 或 *note
eval(): b98. 内置函数来执行或求值。

更多信息请参阅 *note 标准类型层级结构: 1431.。


File: python.info,  Node: 类型对象,  Next: 空对象,  Prev: 代码对象,  Up: 其他内置类型

5.4.12.6 类型对象
.................

类型对象表示各种对象类型。 对象的类型可通过内置函数 *note type(): 611. 来
获取。 类型没有特殊的操作。 标准库模块 *note types: 119. 定义了所有标准
内置类型的名称。

类型以这样的写法来表示: ‘<class 'int'>’。


File: python.info,  Node: 空对象,  Next: 省略符对象,  Prev: 类型对象,  Up: 其他内置类型

5.4.12.7 空对象
...............

此对象会由不显式地返回值的函数所返回。 它不支持任何特殊的操作。 空对象只
有一种值 ‘None’ (这是个内置名称)。 ‘type(None)()’ 会生成同一个单例。

该对象的写法为 ‘None’。


File: python.info,  Node: 省略符对象,  Next: 未实现对象,  Prev: 空对象,  Up: 其他内置类型

5.4.12.8 省略符对象
...................

此对象常被用于切片 (参见 *note 切片: 1529.)。 它不支持任何特殊的操作。 省
略符对象只有一种值 *note Ellipsis: 161c. (这是个内置名称)。
‘type(Ellipsis)()’ 会生成 *note Ellipsis: 161c. 单例。

该对象的写法为 ‘Ellipsis’ 或 ‘...’。


File: python.info,  Node: 未实现对象,  Next: 布尔值,  Prev: 省略符对象,  Up: 其他内置类型

5.4.12.9 未实现对象
...................

此对象会被作为比较和二元运算被应用于它们所不支持的类型时的返回值。 请参
阅 *note 比较运算: 1551. 了解更多信息。 未实现对象只有一种值
‘NotImplemented’。 ‘type(NotImplemented)()’ 会生成这个单例。

该对象的写法为 ‘NotImplemented’。


File: python.info,  Node: 布尔值,  Next: 内部对象,  Prev: 未实现对象,  Up: 其他内置类型

5.4.12.10 布尔值
................

布尔值是两个常量对象 ‘False’ 和 ‘True’。 它们被用来表示逻辑上的真假（不
过其他值也可被当作真值或假值）。 在数字类的上下文中（例如被用作算术运算
符的参数时），它们的行为分别类似于整数 0 和 1。 内置函数 *note bool():
184. 可被用来将任意值转换为布尔值，只要该值可被解析为一个逻辑值（参见之
前的 *note 逻辑值检测: 15f3. 部分）。

该对象的写法分别为 ‘False’ 和 ‘True’。


File: python.info,  Node: 内部对象,  Prev: 布尔值,  Up: 其他内置类型

5.4.12.11 内部对象
..................

有关此对象的信息请参阅 *note 标准类型层级结构: 1431.。 其中描述了栈帧对
象、回溯对象以及切片对象等等。


File: python.info,  Node: 特殊属性,  Prev: 其他内置类型,  Up: 内置类型

5.4.13 特殊属性
---------------

语言实现为部分对象类型添加了一些特殊的只读属性，它们具有各自的作用。 其
中一些并不会被 *note dir(): d3b. 内置函数所列出。

 -- 属性: object.__dict__

     一个字典或其他类型的映射对象，用于存储对象的（可写）属性。

 -- 属性: instance.__class__

     类实例所属的类。

 -- 属性: class.__bases__

     由类对象的基类所组成的元组。

 -- 属性: definition.__name__

     类、函数、方法、描述器或生成器实例的名称。

 -- 属性: definition.__qualname__

     类、函数、方法、描述器或生成器实例的 *note qualified name: 143b.。

     3.3 新版功能.

 -- 属性: class.__mro__

     此属性是由类组成的元组，在方法解析期间会基于它来查找基类。

 -- 方法: class.mro ()

     此方法可被一个元类来重载，以为其实例定制方法解析顺序。 它会在类实例
     化时被调用，其结果存储于 *note __mro__: 1615. 之中。

 -- 方法: class.__subclasses__ ()

     每个类会保存由对其直接子类的弱引用组成的列表。 此方法将返回一个由仍
     然存在的所有此类引用组成的列表。 例如:

          >>> int.__subclasses__()
          [<class 'bool'>]

备注
....


File: python.info,  Node: 内置异常,  Next: 文本处理服务,  Prev: 内置类型,  Up: Python 标准库

5.5 内置异常
============

在 Python 中，所有异常必须为一个派生自 *note BaseException: 1a9. 的类的
实例。 在带有提及一个特定类的 *note except: b46. 子句的 *note try: d7a.
语句中，该子句也会处理任何派生自该类的异常类（但不处理 `它' 所派生出的异
常类）。 通过子类化创建的两个不相关异常类永远是不等效的，既使它们具有相
同的名称。

下面列出的内置异常可通过解释器或内置函数来生成。除非另有说明，它们都会具
有一个提示导致错误详细原因的“关联值”。 这可以是一个字符串或由多个信息项
（例如一个错误码和一个解释错误的字符串）组成的元组。 关联值通常会作为参
数被传递给异常类的构造器。

用户代码可以引发内置异常。 这可被用于测试异常处理程序或报告错误条件，“就
像” 在解释器引发了相同异常的情况时一样；但是请注意，没有任何机制能防止用
户代码引发不适当的错误。

内置异常类可以被子类化以定义新的异常；鼓励程序员从 *note Exception: 1aa.
类或它的某个子类而不是从 *note BaseException: 1a9. 来派生新的异常。 关于
定义异常的更多信息可以在 Python 教程的 *note 用户自定义异常: 12c2. 部分
查看。

当在 *note except: b46. 或 *note finally: 183. 子句中引发（或重新引发）
异常时，‘__context__’ 会被自动设为所捕获的最后一个异常；如果新的异常未被
处理，则最终显示的回溯信息将包括原始的异常和最后的异常。

当引发一个新的异常（而不是简单地使用 ‘raise’ 来重新引发 当前在处理的异常
）时，隐式的异常上下文可以通过使用带有 *note raise: c4a. 的 *note from:
c4a. 子句来补充一个显式的原因:

     raise new_exc from original_exc

跟在 *note from: c4a. 之后一表达式必须为一个异常或 ‘None’。 它将在所引发
的异常上被设置为 ‘__cause__’。 设置 ‘__cause__’ 还会隐式地将
‘__suppress_context__’ 属性设为 ‘True’，这样使用 ‘raise new_exc from
None’ 可以有效地将旧异常替换为新异常来显示其目的 (例如将 *note KeyError:
2c8. 转换为 *note AttributeError: 3a3.)，同时让旧异常在 ‘__context__’ 中
保持可用状态以便在调试时进行内省。

除了异常本身的回溯以外，默认的回溯还会显示这些串连的异常。 ‘__cause__’ 中
的显式串连异常如果存在将总是显示。 ‘__context__’ 中的隐式串连异常仅在
‘__cause__’ 为 *note None: 158. 并且 ‘__suppress_context__’ 为假值时显示
。

不论在哪种情况下，异常本身总会在任何串连异常之后显示，以便回溯的最后一行
总是显示所引发的最后一个异常。

* Menu:

* 基类::
* 具体异常::
* 警告::
* 异常层次结构::


File: python.info,  Node: 基类,  Next: 具体异常,  Up: 内置异常

5.5.1 基类
----------

下列异常主要被用作其他异常的基类。

 -- 例外: BaseException

     所有内置异常的基类。 它不应该被用户自定义类直接继承 (这种情况请使用
     *note Exception: 1aa.)。 如果在此类的实例上调用 *note str(): 339.，
     则会返回实例的参数表示，或者当没有参数时返回空字符串。

      -- 属性: args

          传给异常构造器的参数元组。 某些内置异常 (例如 *note OSError:
          1d4.) 接受特定数量的参数并赋予此元组中的元素特殊的含义，而其他
          异常通常只接受一个给出错误信息的单独字符串。

      -- 方法: with_traceback (tb)

          此方法将 `tb' 设为异常的新回溯信息并返回该异常对象。 它通常以
          如下的形式在异常处理程序中使用:

               try:
                   ...
               except SomeException:
                   tb = sys.exc_info()[2]
                   raise OtherException(...).with_traceback(tb)

 -- 例外: Exception

     所有内置的非系统退出类异常都派生自此类。 所有用户自定义异常也应当派
     生自此类。

 -- 例外: ArithmeticError

     此基类用于派生针对各种算术类错误而引发的内置异常: *note
     OverflowError: 968, *note ZeroDivisionError: 12bd, *note
     FloatingPointError: 170f.。

 -- 例外: BufferError

     当与 *note 缓冲区: 15f7. 相关的操作无法执行时将被引发。

 -- 例外: LookupError

     此基类用于派生当映射或序列所使用的键或索引无效时引发的异常: *note
     IndexError: e7d, *note KeyError: 2c8.。 这可以通过 *note
     codecs.lookup(): 1711. 来直接引发。


File: python.info,  Node: 具体异常,  Next: 警告,  Prev: 基类,  Up: 内置异常

5.5.2 具体异常
--------------

以下异常属于经常被引发的异常。

 -- 例外: AssertionError

     当 *note assert: e0e. 语句失败时将被引发。

 -- 例外: AttributeError

     当属性引用 (参见 *note 属性引用: 1522.) 或赋值失败时将被引发。 （当
     一个对象根本不支持属性引用或属性赋值时则将引发 *note TypeError:
     193.。）

 -- 例外: EOFError

     当 *note input(): c73. 函数未读取任何数据即达到文件结束条件 (EOF) 时
     将被引发。 （另外，‘io.IOBase.read()’ 和 *note
     io.IOBase.readline(): 1713. 方法在遇到 EOF 则将返回一个空字符串。）

 -- 例外: FloatingPointError

     目前未被使用。

 -- 例外: GeneratorExit

     当一个 *note generator: 9aa. 或 *note coroutine: 1a7. 被关闭时将被
     引发；参见 *note generator.close(): 14a3. 和 *note
     coroutine.close(): 14a2.。 它直接继承自 *note BaseException: 1a9. 而
     不是 *note Exception: 1aa.，因为从技术上来说它并不是一个错误。

 -- 例外: ImportError

     当 *note import: c25. 语句尝试加载模块遇到麻烦时将被引发。 并且当
     ‘from ... import’ 中的 "from list" 存在无法找到的名称时也会被引发。

     ‘name’ 与 ‘path’ 属性可通过对构造器使用仅关键字参数来设定。 设定后
     它们将分别表示被尝试导入的模块名称与触发异常的任意文件所在路径。

     在 3.3 版更改: 添加了 ‘name’ 与 ‘path’ 属性。

 -- 例外: ModuleNotFoundError

     *note ImportError: 33d. 的子类，当一个模块无法被定位时将由 *note
     import: c25. 引发。 当在 *note sys.modules: f36. 中找到 ‘None’ 时也
     会被引发。

     3.6 新版功能.

 -- 例外: IndexError

     当序列抽取超出范围时将被引发。 （切片索引会被静默截短到允许的范围；
     如果指定索引不是整数则 *note TypeError: 193. 会被引发。）

 -- 例外: KeyError

     当在现有键集合中找不到指定的映射（字典）键时将被引发。

 -- 例外: KeyboardInterrupt

     当用户按下中断键 (通常为 ‘Control-C’ 或 ‘Delete’) 时将被引发。 在执
     行期间，会定期检测中断信号。 该异常继承自 *note BaseException: 1a9.
     以确保不会被处理 *note Exception: 1aa. 的代码意外捕获，这样可以避免
     退出解释器。

 -- 例外: MemoryError

     当一个操作耗尽内存但情况仍可（通过删除一些对象）进行挽救时将被引发
     。 关联的值是一个字符串，指明是哪种（内部）操作耗尽了内存。 请注意
     由于底层的内存管理架构（C 的 ‘malloc()’ 函数），解释器也许并不总是
     能够从这种情况下完全恢复；但它毕竟可以引发一个异常，这样就能打印出
     栈回溯信息，以便找出导致问题的失控程序。

 -- 例外: NameError

     当某个局部或全局名称未找到时将被引发。 此异常仅用于非限定名称。 关
     联的值是一条错误信息，其中包含未找到的名称。

 -- 例外: NotImplementedError

     此异常派生自 *note RuntimeError: 2bb.。 在用户自定义的基类中，抽象
     方法应当在其要求所派生类重载该方法，或是在其要求所开发的类提示具体
     实现尚待添加时引发此异常。

          注解: 它不应当用来表示一个运算符或方法根本不能被支持 – 在此情
          况下应当让特定运算符 / 方法保持未定义，或者在子类中将其设为
          *note None: 158.。

          注解: ‘NotImplementedError’ 和 ‘NotImplemented’ 不可互换，即使
          它们有相似的名称和用途。 请参阅 *note NotImplemented: 855. 了
          解有关何时使用它们的详细说明。

 -- 例外: OSError ([arg])

 -- 例外: OSError (errno, strerror[, filename[, winerror[, filename2]]])

     此异常在一个系统函数返回系统相关的错误时将被引发，此类错误包括 I/O
     操作失败例如 "文件未找到" 或 "磁盘已满" 等（不包括非法参数类型或其
     他偶然性错误）。

     构造器的第二种形式可设置如下所述的相应属性。 如果未指定这些属性则默
     认为 *note None: 158.。 为了能向下兼容，如果传入了三个参数，则
     *note args: 170c. 属性将仅包含由前两个构造器参数组成的 2 元组。

     构造器实际返回的往往是 *note OSError: 1d4. 的某个子类，如下文 *note
     OS exceptions: 1714. 中所描述的。 具体的子类取决于最终的 *note
     errno: 1715. 值。 此行为仅在直接或通过别名来构造 *note OSError:
     1d4. 时发生，并且在子类化时不会被继承。

      -- 属性: errno

          来自于 C 变量 ‘errno’ 的数字错误码。

      -- 属性: winerror

          在 Windows 下，此参数将给出原生的 Windows 错误码。 而 *note
          errno: 1715. 属性将是该原生错误码在 POSIX 平台下的近似转换形式
          。

          在 Windows 下，如果 `winerror' 构造器参数是一个整数，则 *note
          errno: 1715. 属性会根据 Windows 错误码来确定，而 `errno' 参数
          会被忽略。 在其他平台上，`winerror' 参数会被忽略，并且 *note
          winerror: 1716. 属性将不存在。

      -- 属性: strerror

          操作系统所提供的相应错误信息。 它在 POSIX 平台中由 C 函数
          ‘perror()’ 来格式化，在 Windows 中则是由 ‘FormatMessage()’。

      -- 属性: filename
      -- 属性: filename2

          对于与文件系统路径有关 (例如 *note open(): 4f8. 或 *note
          os.unlink(): a44.) 的异常，*note filename: 1718. 是传给函数的
          文件名。 对于涉及两个文件系统路径的函数 (例如 *note
          os.rename(): a40.)，*note filename2: 1719. 将是传给函数的第二
          个文件名。

     在 3.3 版更改: *note EnvironmentError: 99b, *note IOError: 99a,
     *note WindowsError: 99c, *note socket.error: 99d, *note
     select.error: 99e. 与 ‘mmap.error’ 已被合并到 *note OSError: 1d4.，
     构造器可能返回其中一个子类。

     在 3.4 版更改: *note filename: 1718. 属性现在将是传给函数的原始文件
     名，而不是经过编码或基于文件系统编码进行解码之后的名称。 此外还添加
     了 `filename2' 构造器参数和属性。

 -- 例外: OverflowError

     当算术运算的结果大到无法表示时将被引发。 这对整数来说不可能发生（宁
     可引发 *note MemoryError: efc. 也不会放弃尝试）。 但是出于历史原因
     ，有时也会在整数超出要求范围的情况下引发 OverflowError。 因为在 C 中
     缺少对浮点异常处理的标准化，大多数浮点运算都不会做检查。

 -- 例外: RecursionError

     此异常派生自 *note RuntimeError: 2bb.。 它会在解释器检测发现超过最
     大递归深度 (参见 *note sys.getrecursionlimit(): e82.) 时被引发。

     3.5 新版功能: 在此之前将只引发 *note RuntimeError: 2bb.。

 -- 例外: ReferenceError

     此异常将在使用 *note weakref.proxy(): 251. 函数所创建的弱引用来访问
     该引用的某个已被作为垃圾回收的属性时被引发。 有关弱引用的更多信息请
     参阅 *note weakref: 129. 模块。

 -- 例外: RuntimeError

     当检测到一个不归属于任何其他类别的错误时将被引发。 关联的值是一个指
     明究竟发生了什么问题的字符串。

 -- 例外: StopIteration

     由内置函数 *note next(): 68b. 和 *note iterator: 104b. 的 *note
     __next__(): c6c. 方法所引发，用来表示该迭代器不能产生下一项。

     该异常对象只有一个属性 ‘value’，它在构造该异常时作为参数给出，默认
     值为 *note None: 158.。

     当一个 *note generator: 9aa. 或 *note coroutine: 1a7. 函数返回时，
     将引发一个新的 *note StopIteration: 48e. 实例，函数返回的值将被用作
     异常构造器的 ‘value’ 形参。

     如果某个生成器代码直接或间接地引发了 *note StopIteration: 48e.，它
     会被转换为 *note RuntimeError: 2bb. (并将 *note StopIteration: 48e.
     保留为导致新异常的原因)。

     在 3.3 版更改: 添加了 ‘value’ 属性及其被生成器函数用作返回值的功能
     。

     在 3.5 版更改: 引入了通过 ‘from __future__ import generator_stop’ 来
     实现 RuntimeError 转换，参见 PEP 479(1)。

     在 3.7 版更改: 默认对所有代码启用 PEP 479(2): 在生成器中引发的
     *note StopIteration: 48e. 错误将被转换为 *note RuntimeError: 2bb.。

 -- 例外: StopAsyncIteration

     必须由一个 *note asynchronous iterator: 64e. 对象的 *note
     __anext__(): 14a5. 方法来引发以停止迭代操作。

     3.5 新版功能.

 -- 例外: SyntaxError

     当解析器遇到语法错误时将被引发。 这可以发生在 *note import: c25. 语
     句，对内置函数 *note exec(): c4c. 或 *note eval(): b98. 的调用，或
     者读取原始脚本或标准输入（也包括交互模式）的时候。

     异常实例的 *note str(): 339. 只返回错误消息。

      -- 属性: filename

          语法错误所在文件的名称。

      -- 属性: lineno

          发生错误所在文件中的行号。 行号索引从 1 开始：文件中首行的
          ‘lineno’ 为 1。

      -- 属性: offset

          发生错误所在文件中的列号。 列号索引从 1 开始：行中首个字符的
          ‘offset’ 为 1。

      -- 属性: text

          错误所涉及的源代码文本。

 -- 例外: IndentationError

     与不正确的缩进相关的语法错误的基类。 这是 *note SyntaxError: 460. 的
     一个子类。

 -- 例外: TabError

     当缩进包含对制表符和空格符不一致的使用时将被引发。 这是 *note
     IndentationError: e80. 的一个子类。

 -- 例外: SystemError

     当解释器发现内部错误，但情况看起来尚未严重到要放弃所有希望时将被引
     发。 关联的值是一个指明发生了什么问题的字符串（表示为低层级的符号）
     。

     你应当将此问题报告给你所用 Python 解释器的作者或维护人员。 请确认报
     告 Python 解释器的版本号 (‘sys.version’; 它也会在交互式 Python 会话
     开始时被打印出来)，具体的错误消息（异常所关联的值）以及可能触发该错
     误的程序源码。

 -- 例外: SystemExit

     此异常由 *note sys.exit(): cea. 函数引发。 它继承自 *note
     BaseException: 1a9. 而不是 *note Exception: 1aa. 以确保不会被处理
     *note Exception: 1aa. 的代码意外捕获。 这允许此异常正确地向上传播并
     导致解释器退出。 如果它未被处理，则 Python 解释器就将退出；不会打印
     任何栈回溯信息。 构造器接受的可选参数与传递给 *note sys.exit():
     cea. 的相同。 如果该值为一个整数，则它指明系统退出状态码（会传递给
     C 的 ‘exit()’ 函数）；如果该值为 ‘None’，则退出状态码为零；如果该值
     为其他类型（例如字符串），则会打印对象的值并将退出状态码设为一。

     对 *note sys.exit(): cea. 的调用会被转换为一个异常以便能执行清理处
     理程序 (*note try: d7a. 语句的 *note finally: 183. 子句)，并且使得
     调试器可以执行一段脚本而不必冒失去控制的风险。 如果绝对确实地需要立
     即退出（例如在调用 *note os.fork(): 969. 之后的子进程中）则可使用
     *note os._exit(): 171e.

      -- 属性: code

          传给构造器的退出状态码或错误信息（默认为 ‘None’。）

 -- 例外: TypeError

     当一个操作或函数被应用于类型不适当的对象时将被引发。 关联的值是一个
     字符串，给出有关类型不匹配的详情。

     此异常可以由用户代码引发，以表明尝试对某个对象进行的操作不受支持也
     不应当受支持。 如果某个对象应当支持给定的操作但尚未提供相应的实现，
     所要引发的适当异常应为 *note NotImplementedError: 617.。

     传入参数的类型错误 (例如在要求 *note int: 185. 时却传入了 *note
     list: 263.) 应当导致 *note TypeError: 193.，但传入参数的值错误 (例
     如传入要求范围之外的数值) 则应当导致 *note ValueError: 1fc.。

 -- 例外: UnboundLocalError

     当在函数或方法中对某个局部变量进行引用，但该变量并未绑定任何值时将
     被引发。 此异常是 *note NameError: d83. 的一个子类。

 -- 例外: UnicodeError

     当发生与 Unicode 相关的编码或解码错误时将被引发。 此异常是 *note
     ValueError: 1fc. 的一个子类。

     *note UnicodeError: c43. 具有一些描述编码或解码错误的属性。 例如
     ‘err.object[err.start:err.end]’ 会给出导致编解码器失败的特定无效输
     入。

      -- 属性: encoding

          引发错误的编码名称。

      -- 属性: reason

          描述特定编解码器错误的字符串。

      -- 属性: object

          编解码器试图要编码或解码的对象。

      -- 属性: start

          *note object: 2b1. 中无效数据的开始位置索引。

      -- 属性: end

          *note object: 2b1. 中无效数据的末尾位置索引（不含）。

 -- 例外: UnicodeEncodeError

     当在编码过程中发生与 Unicode 相关的错误时将被引发。 此异常是 *note
     UnicodeError: c43. 的一个子类。

 -- 例外: UnicodeDecodeError

     当在解码过程中发生与 Unicode 相关的错误时将被引发。 此异常是 *note
     UnicodeError: c43. 的一个子类。

 -- 例外: UnicodeTranslateError

     在转写过程中发生与 Unicode 相关的错误时将被引发。 此异常是 *note
     UnicodeError: c43. 的一个子类。

 -- 例外: ValueError

     当操作或函数接收到具有正确类型但值不适合的参数，并且情况不能用更精
     确的异常例如 *note IndexError: e7d. 来描述时将被引发。

 -- 例外: ZeroDivisionError

     当除法或取余运算的第二个参数为零时将被引发。 关联的值是一个字符串，
     指明操作数和运算的类型。

下列异常被保留以与之前的版本相兼容；从 Python 3.3 开始，它们都是 *note
OSError: 1d4. 的别名。

 -- 例外: EnvironmentError

 -- 例外: IOError

 -- 例外: WindowsError

     限在 Windows 中可用。

* Menu:

* OS 异常::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0479

   (2) https://www.python.org/dev/peps/pep-0479


File: python.info,  Node: OS 异常,  Up: 具体异常

5.5.2.1 OS 异常
...............

下列异常均为 *note OSError: 1d4. 的子类，它们将根据系统错误代码被引发。

 -- 例外: BlockingIOError

     当一个操作会被某个设置为非阻塞操作的对象（例如套接字）所阻塞时将被
     引发。 对应于 ‘errno’ ‘EAGAIN’, ‘EALREADY’, ‘EWOULDBLOCK’ 和
     ‘EINPROGRESS’。

     除了 *note OSError: 1d4. 已有的属性，*note BlockingIOError: 99f. 还
     有一个额外属性：

      -- 属性: characters_written

          一个整数，表示在被阻塞前已写入到流的字符数。 当使用来自 *note
          io: a2. 模块的带缓冲 I/O 类时此属性可用。

 -- 例外: ChildProcessError

     当一个子进程上的操作失败时将被引发。 对应于 ‘errno’ ‘ECHILD’。

 -- 例外: ConnectionError

     与连接相关问题的基类。

     其子类有 *note BrokenPipeError: 9a5, *note ConnectionAbortedError:
     9a6, *note ConnectionRefusedError: 9a7. 和 *note
     ConnectionResetError: 9a8.。

 -- 例外: BrokenPipeError

     *note ConnectionError: 6ef. 的子类，当试图写入另一端已被关闭的管道
     ，或是试图写入已关闭写入的套接字时将被引发。 对应于 ‘errno’ ‘EPIPE’
     和 ‘ESHUTDOWN’。

 -- 例外: ConnectionAbortedError

     *note ConnectionError: 6ef. 的子类，当连接尝试被对端中止时将被引发
     。 对应于 ‘errno’ ‘ECONNABORTED’。

 -- 例外: ConnectionRefusedError

     *note ConnectionError: 6ef. 的子类，当连接尝试被对端拒绝时将被引发
     。 对应于 ‘errno’ ‘ECONNREFUSED’。

 -- 例外: ConnectionResetError

     *note ConnectionError: 6ef. 的子类，当连接被对端重置时将被引发。 对
     应于 ‘errno’ ‘ECONNRESET’。

 -- 例外: FileExistsError

     当试图创建一个已存在的文件或目录时将被引发。 对应于 ‘errno’
     ‘EEXIST’。

 -- 例外: FileNotFoundError

     当所请求的文件或目录不存在时将被引发。 对应于 ‘errno’ ‘ENOENT’。

 -- 例外: InterruptedError

     当系统调用被输入信号中断时将被引发。 对应于 ‘errno’ *note EINTR:
     661.。

     在 3.5 版更改: 当系统调用被某个信号中断时，Python 现在会重试系统调
     用，除非该信号的处理程序引发了其它异常 (原理参见 PEP 475(1)) 而不是
     引发 *note InterruptedError: 662.。

 -- 例外: IsADirectoryError

     当请求对一个目录执行文件操作 (例如 *note os.remove(): a3f.) 将被引
     发。 对应于 ‘errno’ ‘EISDIR’。

 -- 例外: NotADirectoryError

     当请求对一个非目录对象执行目录操作 (例如 *note os.listdir(): a49.)
     时将被引发。 对应于 ‘errno’ ‘ENOTDIR’。

 -- 例外: PermissionError

     当在没有足够操作权限的情况下试图执行某个操作时将被引发 —— 例如缺少
     文件系统权限。 对应于 ‘errno’ ‘EACCES’ 和 ‘EPERM’。

 -- 例外: ProcessLookupError

     当给定的进程不存在时将被引发。 对应于 ‘errno’ ‘ESRCH’。

 -- 例外: TimeoutError

     当一个系统函数发生系统级超时的情况下将被引发。 对应于 ‘errno’
     ‘ETIMEDOUT’。

3.3 新版功能: 添加了以上所有 *note OSError: 1d4. 的子类。

参见
....

PEP 3151(2) - 重写 OS 和 IO 异常的层次结构

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475

   (2) https://www.python.org/dev/peps/pep-3151


File: python.info,  Node: 警告,  Next: 异常层次结构,  Prev: 具体异常,  Up: 内置异常

5.5.3 警告
----------

下列异常被用作警告类别；请参阅 *note 警告类别: 1729. 文档了解详情。

 -- 例外: Warning

     警告类别的基类。

 -- 例外: UserWarning

     用户代码所产生警告的基类。

 -- 例外: DeprecationWarning

     如果所发出的警告是针对其他 Python 开发者的，则以此作为与已弃用特性
     相关警告的基类。

 -- 例外: PendingDeprecationWarning

     对于已过时并预计在未来弃用，但目前尚未弃用的特性相关警告的基类。

     这个类很少被使用，因为针对未来可能的弃用发出警告的做法并不常见，而
     针对当前已有的弃用则推荐使用 *note DeprecationWarning: 279.。

 -- 例外: SyntaxWarning

     与模糊的语法相关的警告的基类。

 -- 例外: RuntimeWarning

     与模糊的运行时行为相关的警告的基类。

 -- 例外: FutureWarning

     如果所发出的警告是针对以 Python 所编写应用的最终用户的，则以此作为
     与已弃用特性相关警告的基类。

 -- 例外: ImportWarning

     与在模块导入中可能的错误相关的警告的基类。

 -- 例外: UnicodeWarning

     与 Unicode 相关的警告的基类。

 -- 例外: BytesWarning

     与 *note bytes: 33a. 和 *note bytearray: 33b. 相关的警告的基类。

 -- 例外: ResourceWarning

     与资源使用相关的警告的基类。 会被默认的警告过滤器忽略。

     3.2 新版功能.


File: python.info,  Node: 异常层次结构,  Prev: 警告,  Up: 内置异常

5.5.4 异常层次结构
------------------

内置异常的类层级结构如下：

     BaseException
      +-- SystemExit
      +-- KeyboardInterrupt
      +-- GeneratorExit
      +-- Exception
           +-- StopIteration
           +-- StopAsyncIteration
           +-- ArithmeticError
           |    +-- FloatingPointError
           |    +-- OverflowError
           |    +-- ZeroDivisionError
           +-- AssertionError
           +-- AttributeError
           +-- BufferError
           +-- EOFError
           +-- ImportError
           |    +-- ModuleNotFoundError
           +-- LookupError
           |    +-- IndexError
           |    +-- KeyError
           +-- MemoryError
           +-- NameError
           |    +-- UnboundLocalError
           +-- OSError
           |    +-- BlockingIOError
           |    +-- ChildProcessError
           |    +-- ConnectionError
           |    |    +-- BrokenPipeError
           |    |    +-- ConnectionAbortedError
           |    |    +-- ConnectionRefusedError
           |    |    +-- ConnectionResetError
           |    +-- FileExistsError
           |    +-- FileNotFoundError
           |    +-- InterruptedError
           |    +-- IsADirectoryError
           |    +-- NotADirectoryError
           |    +-- PermissionError
           |    +-- ProcessLookupError
           |    +-- TimeoutError
           +-- ReferenceError
           +-- RuntimeError
           |    +-- NotImplementedError
           |    +-- RecursionError
           +-- SyntaxError
           |    +-- IndentationError
           |         +-- TabError
           +-- SystemError
           +-- TypeError
           +-- ValueError
           |    +-- UnicodeError
           |         +-- UnicodeDecodeError
           |         +-- UnicodeEncodeError
           |         +-- UnicodeTranslateError
           +-- Warning
                +-- DeprecationWarning
                +-- PendingDeprecationWarning
                +-- RuntimeWarning
                +-- SyntaxWarning
                +-- UserWarning
                +-- FutureWarning
                +-- ImportWarning
                +-- UnicodeWarning
                +-- BytesWarning
                +-- ResourceWarning


File: python.info,  Node: 文本处理服务,  Next: 二进制数据服务,  Prev: 内置异常,  Up: Python 标准库

5.6 文本处理服务
================

本章介绍的模块提供了广泛的字符串操作和其他文本处理服务。

在 *note 二进制数据服务: 172f. 之下描述的 *note codecs: 1c. 模块也与文本
处理高度相关。 此外也请参阅 Python 内置字符串类型的文档 *note
文本序列类型 — str: 1233.。

* Menu:

* string: string --- 常见的字符串操作. 常见的字符串操作
* re: re --- 正则表达式操作. 正则表达式操作
* difflib: difflib --- 计算差异的辅助工具. 计算差异的辅助工具
* textwrap: textwrap --- 文本自动换行与填充. 文本自动换行与填充
* unicodedata: unicodedata --- Unicode 数据库. Unicode 数据库
* stringprep: stringprep --- 因特网字符串预备. 因特网字符串预备
* readline: readline --- GNU readline 接口. GNU readline 接口
* rlcompleter: rlcompleter --- GNU readline 的补全函数. GNU readline 的补全函数


File: python.info,  Node: string --- 常见的字符串操作,  Next: re --- 正则表达式操作,  Up: 文本处理服务

5.6.1 ‘string’ — 常见的字符串操作
---------------------------------

`源代码：' Lib/string.py(1)

__________________________________________________________________

参见
....

*note 文本序列类型 — str: 1233.

*note 字符串的方法: 1234.

* Menu:

* 字符串常量::
* 自定义字符串格式化::
* 格式字符串语法::
* 模板字符串::
* 辅助函数::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/string.py


File: python.info,  Node: 字符串常量,  Next: 自定义字符串格式化,  Up: string --- 常见的字符串操作

5.6.1.1 字符串常量
..................

此模块中定义的常量为：

 -- 数据: string.ascii_letters

     下文所述 *note ascii_lowercase: 1733. 和 *note ascii_uppercase:
     1734. 常量的拼连。 该值不依赖于语言区域。

 -- 数据: string.ascii_lowercase

     小写字母 ‘'abcdefghijklmnopqrstuvwxyz'’。 该值不依赖于语言区域，不
     会发生改变。

 -- 数据: string.ascii_uppercase

     大写字母 ‘'ABCDEFGHIJKLMNOPQRSTUVWXYZ'’。 该值不依赖于语言区域，不
     会发生改变。

 -- 数据: string.digits

     字符串 ‘'0123456789'’。

 -- 数据: string.hexdigits

     字符串 ‘'0123456789abcdefABCDEF'’。

 -- 数据: string.octdigits

     字符串 ‘'01234567'’。

 -- 数据: string.punctuation

     由在 ‘C’ 区域设置中被视为标点符号的 ASCII 字符所组成的字符串:
     ‘!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~’.

 -- 数据: string.printable

     由被视为可打印符号的 ASCII 字符组成的字符串。 这是 *note digits:
     1735, *note ascii_letters: c64, *note punctuation: 1738. 和 *note
     whitespace: 173a. 的总和。

 -- 数据: string.whitespace

     由被视为空白符号的 ASCII 字符组成的字符串。 其中包括空格、制表、换
     行、回车、进纸和纵向制表符。


File: python.info,  Node: 自定义字符串格式化,  Next: 格式字符串语法,  Prev: 字符串常量,  Up: string --- 常见的字符串操作

5.6.1.2 自定义字符串格式化
..........................

内置的字符串类提供了通过使用 PEP 3101(1) 所描述的 *note format(): 4e2. 方
法进行复杂变量替换和值格式化的能力。 *note string: f7. 模块中的 *note
Formatter: 7be. 类允许你使用与内置 *note format(): 4e2. 方法相同的实现来
创建并定制你自己的字符串格式化行为。

 -- 类: string.Formatter

     *note Formatter: 7be. 类包含下列公有方法：

      -- 方法: format (format_string, /, *args, **kwargs)

          首要的 API 方法。 它接受一个格式字符串和任意一组位置和关键字参
          数。 它只是一个调用 *note vformat(): 173c. 的包装器。

          在 3.7 版更改: 格式字符串参数现在是 *note 仅限位置参数: 2a8.。

      -- 方法: vformat (format_string, args, kwargs)

          此函数执行实际的格式化操作。 它被公开为一个单独的函数，用于需
          要传入一个预定义字母作为参数，而不是使用 ‘*args’ 和 ‘**kwargs’
          语法将字典解包为多个单独参数并重打包的情况。 *note vformat():
          173c. 完成将格式字符串分解为字符数据和替换字段的工作。 它会调
          用下文所述的几种不同方法。

     此外，*note Formatter: 7be. 还定义了一些旨在被子类替换的方法：

      -- 方法: parse (format_string)

          循环遍历 format_string 并返回一个由可迭代对象组成的元组
          (`literal_text', `field_name', `format_spec', `conversion')。
          它会被 *note vformat(): 173c. 用来将字符串分解为文本字面值或替
          换字段。

          元组中的值在概念上表示一段字面文本加上一个替换字段。 如果没有
          字面文本（如果连续出现两个替换字段就会发生这种情况），则
          `literal_text' 将是一个长度为零的字符串。 如果没有替换字段，则
          `field_name', `format_spec' 和 `conversion' 的值将为 ‘None’。

      -- 方法: get_field (field_name, args, kwargs)

          给定 `field_name' 作为 *note parse(): 173d. (见上文) 的返回值
          ，将其转换为要格式化的对象。 返回一个元组 (obj, used_key)。 默
          认版本接受在 PEP 3101(2) 所定义形式的字符串，例如 "0[name]" 或
          "label.title"。 `args' 和 `kwargs' 与传给 *note vformat():
          173c. 的一样。 返回值 `used_key' 与 *note get_value(): 173f. 的
          `key' 形参具有相同的含义。

      -- 方法: get_value (key, args, kwargs)

          提取给定的字段值。 `key' 参数将为整数或字符串。 如果是整数，它
          表示 `args' 中位置参数的索引；如果是字符串，它表示 `kwargs' 中
          的关键字参数名。

          `args' 形参会被设为 *note vformat(): 173c. 的位置参数列表，而
          `kwargs' 形参会被设为由关键字参数组成的字典。

          对于复合字段名称，仅会为字段名称的第一个组件调用这些函数；后续
          组件会通过普通属性和索引操作来进行处理。

          因此举例来说，字段表达式 ’0.name’ 将导致调用 *note
          get_value(): 173f. 时附带 `key' 参数值 0。 在 *note
          get_value(): 173f. 通过调用内置的 *note getattr(): 451. 函数返
          回后将会查找 ‘name’ 属性。

          如果索引或关键字引用了一个不存在的项，则将引发 *note
          IndexError: e7d. 或 *note KeyError: 2c8.。

      -- 方法: check_unused_args (used_args, args, kwargs)

          在必要时实现对未使用参数进行检测。 此函数的参数是是格式字符串
          中实际引用的所有参数键的集合（整数表示位置参数，字符串表示名称
          参数），以及被传给 vformat 的 `args' 和 `kwargs' 的引用。 未使
          用参数的集合可以根据这些形参计算出来。 如果检测失败则 *note
          check_unused_args(): 1740. 应会引发一个异常。

      -- 方法: format_field (value, format_spec)

          *note format_field(): 1741. 会简单地调用内置全局函数 *note
          format(): 4e3.。 提供该方法是为了让子类能够重载它。

      -- 方法: convert_field (value, conversion)

          使用给定的转换类型（来自 *note parse(): 173d. 方法所返回的元组
          ）来转换（由 *note get_field(): 173e. 所返回的）值。 默认版本
          支持 ’s’ (str), ’r’ (repr) 和 ’a’ (ascii) 等转换类型。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3101

   (2) https://www.python.org/dev/peps/pep-3101


File: python.info,  Node: 格式字符串语法,  Next: 模板字符串,  Prev: 自定义字符串格式化,  Up: string --- 常见的字符串操作

5.6.1.3 格式字符串语法
......................

*note str.format(): 4e2. 方法和 *note Formatter: 7be. 类共享相同的格式字
符串语法（虽然对于 *note Formatter: 7be. 来说，其子类可以定义它们自己的
格式字符串语法）。 具体语法与 *note 格式化字符串字面值: 15d. 相似，但较
为简单一些，并且关键的一点是不支持任意表达式。

格式字符串包含有以花括号 ‘{}’ 括起来的“替换字段”。 不在花括号之内的内容
被视为字面文本，会不加修改地复制到输出中。 如果你需要在字面文本中包含花
括号字符，可以通过重复来转义: ‘{{’ and ‘}}’。

替换字段的语法如下：

          replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
          field_name        ::= arg_name ("." attribute_name | "[" element_index "]")*
          arg_name          ::= [identifier | digit+]
          attribute_name    ::= identifier
          element_index     ::= digit+ | index_string
          index_string      ::= <any source character except "]"> +
          conversion        ::= "r" | "s" | "a"
          format_spec       ::= <described in the next section>

用不太正式的术语来描述，替换字段开头可以用一个 `field_name' 指定要对值进
行格式化并取代替换字符被插入到输出结果的对象。 `field_name' 之后有可选的
`conversion' 字段，它是一个感叹号 ‘'!'’ 加一个 `format_spec'，并以一个冒
号 ‘':'’ 打头。 这些指明了替换值的非默认格式。

另请参阅 *note 格式规格迷你语言: 4e6. 一节。

`field_name' 本身以一个数字或关键字 `arg_name' 打头。 如果为数字，则它指
向一个位置参数，而如果为关键字，则它指向一个命名关键字参数。 如果格式字
符串中的数字 arg_names 为 0, 1, 2, ... 的序列，它们可以全部省略（而非部
分省略），数字 0, 1, 2, ... 将会按顺序自动插入。 由于 `arg_name' 不使用
引号分隔，因此无法在格式字符串中指定任意的字典键 (例如字符串 ‘'10'’ 或
‘':-]'’)。 `arg_name' 之后可以带上任意数量的索引或属性表达式。 ‘'.name'’
形式的表达式会使用 *note getattr(): 451. 选择命名属性，而 ‘'[index]'’ 形
式的表达式会使用 *note __getitem__(): 280. 执行索引查找。

在 3.1 版更改: 位置参数说明符对于 *note str.format(): 4e2. 可以省略，因
此 ‘'{} {}'.format(a, b)’ 等价于 ‘'{0} {1}'.format(a, b)’。

在 3.4 版更改: 位置参数说明符对于 *note Formatter: 7be. 可以省略。

一些简单的格式字符串示例

     "First, thou shalt count to {0}"  # References first positional argument
     "Bring me a {}"                   # Implicitly references the first positional argument
     "From {} to {}"                   # Same as "From {0} to {1}"
     "My quest is {name}"              # References keyword argument 'name'
     "Weight in tons {0.weight}"       # 'weight' attribute of first positional arg
     "Units destroyed: {players[0]}"   # First element of keyword argument 'players'.

使用 `conversion' 字段在格式化之前进行类型强制转换。 通常，格式化值的工
作由值本身的 *note __format__(): 956. 方法来完成。 但是，在某些情况下最
好强制将类型格式化为一个字符串，覆盖其本身的格式化定义。 通过在调用
*note __format__(): 956. 之前将值转换为字符串，可以绕过正常的格式化逻辑
。

目前支持的转换旗标有三种: ‘'!s'’ 会对值调用 *note str(): 339.，‘'!r'’ 调
用 *note repr(): 7d5. 而 ‘'!a'’ 则调用 *note ascii(): d54.。

几个例子:

     "Harold's a clever {0!s}"        # Calls str() on the argument first
     "Bring out the holy {name!r}"    # Calls repr() on the argument first
     "More {!a}"                      # Calls ascii() on the argument first

`format_spec' 字段包含值应如何呈现的规格描述，例如字段宽度、对齐、填充、
小数精度等细节信息。 每种值类型可以定义自己的“格式化迷你语言”或对
`format_spec' 的解读方式。

大多数内置类型都支持同样的格式化迷你语言，具体描述见下一节。

`format_spec' 字段还可以在其内部包含嵌套的替换字段。 这些嵌套的替换字段
可能包括字段名称、转换旗标和格式规格描述，但是不再允许更深层的嵌套。
format_spec 内部的替换字段会在解读 `format_spec' 字符串之前先被解读。 这
将允许动态地指定特定值的格式。

请参阅 *note 格式示例: 174c. 一节查看相关示例。

* Menu:

* 格式规格迷你语言::
* 格式示例::


File: python.info,  Node: 格式规格迷你语言,  Next: 格式示例,  Up: 格式字符串语法

5.6.1.4 格式规格迷你语言
........................

“格式规格”在格式字符串所包含的替换字段内部使用，用于定义单个值应如何呈现
(参见 *note 格式字符串语法: d22. 和 *note 格式化字符串字面值: 15d.)。 它
们也可以被直接传给内置的 *note format(): 4e3. 函数。 每种可格式化的类型
都可以自行定义如何对格式规格进行解读。

大多数内置类型都为格式规格实现了下列选项，不过某些格式化选项只被数值类型
所支持。

一般约定空的格式描述将产生与在值上调用 *note str(): 339. 相同的结果。 非
空格式描述通常会修改此结果。

`标准格式说明符' 的一般形式如下：

     format_spec     ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]
     fill            ::= <any character>
     align           ::= "<" | ">" | "=" | "^"
     sign            ::= "+" | "-" | " "
     width           ::= digit+
     grouping_option ::= "_" | ","
     precision       ::= digit+
     type            ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

如果指定了一个有效的 `align' 值，则可以在该值前面加一个 `fill' 字符，它
可以为任意字符，如果省略则默认为空格符。 在 *note 格式化字符串字面值:
15d. 或在使用 *note str.format(): 4e2. 方法时是无法使用花括号字面值
("‘{’" or "‘}’") 作为 `fill' 字符的。 但是，通过嵌套替换字段插入花括号则
是可以的。 这个限制不会影响 *note format(): 4e3. 函数。

各种对齐选项的含义如下：

     选项          含义
                   
     -----------------------------------------------------------------------------
                   
     ‘'<'’         强制字段在可用空间内左对齐（这是大多数对象的默认值）。
                   
                   
     ‘'>'’         强制字段在可用空间内右对齐（这是数字的默认值）。
                   
                   
     ‘'='’         强制将填充放置在符号（如果有）之后但在数字之前。这用于以
                   “+000000120”形式打印字段。此对齐选项仅对数字类型有效。当
                   ’0’紧接在字段宽度之前时，它成为默认值。
                   
                   
     ‘'^'’         强制字段在可用空间内居中。
                   

请注意，除非定义了最小字段宽度，否则字段宽度将始终与填充它的数据大小相同
，因此在这种情况下，对齐选项没有意义。

`sign' 选项仅对数字类型有效，可以是以下之一：

     选项          含义
                   
     -----------------------------------------------------------------------------
                   
     ‘'+'’         表示标志应该用于正数和负数。
                   
                   
     ‘'-'’         表示标志应仅用于负数（这是默认行为）。
                   
                   
     space         表示应在正数上使用前导空格，在负数上使用减号。
                   

‘'#'’ 选项可以让“替代形式”被用于转换。 替代形式会针对不同类型分别定义。
此选项仅对整数、浮点数和复数类型有效。 对于整数类型，当使用二进制、八进
制或十六进制输出时，此选项会为输出值分别添加相应的 ‘'0b'’, ‘'0o'’, or
‘'0x'’ 前缀。 对于浮点数和复数类型，替代形式会使得转换结果总是包含小数点
符号，即使其不带小数部分。 通常只有在带有小数部分的情况下，此类转换的结
果中才会出现小数点符号。 此外，对于 ‘'g'’ 和 ‘'G'’ 转换，末尾的零不会从
结果中被移除。

‘','’ 选项表示使用逗号作为千位分隔符。 对于感应区域设置的分隔符，请改用
‘'n'’ 整数表示类型。

在 3.1 版更改: 添加了 ‘','’ 选项 (另请参阅 PEP 378(1))。

‘'_'’ 选项表示对浮点表示类型和整数表示类型 ‘'d'’ 使用下划线作为千位分隔
符。 对于整数表示类型 ‘'b'’, ‘'o'’, ‘'x'’ 和 ‘'X'’，将为每 4 个数位插入
一个下划线。 对于其他表示类型指定此选项则将导致错误。

在 3.6 版更改: 添加了 ‘'_'’ 选项 (另请参阅 PEP 515(2))。

`width' 是一个定义最小总字段宽度的十进制整数，包括任何前缀、分隔符和其他
格式化字符。 如果未指定，则字段宽度将由内容确定。

当未显式给出对齐方式时，在 `width' 字段前加一个零 (‘'0'’) 字段将为数字类
型启用感知正负号的零填充。 这相当于设置 `fill' 字符为 ‘'0'’ 且
`alignment' 类型为 ‘'='’。

`precision' 是一个十进制数字，表示对于以 ‘'f'’ and ‘'F'’ 格式化的浮点数
值要在小数点后显示多少个数位，或者对于以 ‘'g'’ 或 ‘'G'’ 格式化的浮点数值
要在小数点前后共显示多少个数位。 对于非数字类型，该字段表示最大字段大小
—— 换句话说就是要使用多少个来自字段内容的字符。 对于整数值则不允许使用
`precision'。

最后，`type' 确定了数据应如何呈现。

可用的字符串表示类型是：

     类型          含义
                   
     -----------------------------------------------------------------------------
                   
     ‘'s'’         字符串格式。这是字符串的默认类型，可以省略。
                   
                   
     None          和 ‘'s'’ 一样。
                   

可用的整数表示类型是：

     类型          含义
                   
     -----------------------------------------------------------------------------
                   
     ‘'b'’         二进制格式。 输出以 2 为基数的数字。
                   
                   
     ‘'c'’         字符。在打印之前将整数转换为相应的unicode字符。
                   
                   
     ‘'d'’         十进制整数。 输出以 10 为基数的数字。
                   
                   
     ‘'o'’         八进制格式。 输出以 8 为基数的数字。
                   
                   
     ‘'x'’         十六进制格式。 输出以 16 为基数的数字，使用小写字母表示 9 以
                   上的数码。
                   
                   
     ‘'X'’         十六进制格式。 输出以 16 为基数的数字，使用大写字母表示 9 以
                   上的数码。
                   
                   
     ‘'n'’         数字。 这与 ‘'d'’ 相似，不同之处在于它会使用当前区域设置来插
                   入适当的数字分隔字符。
                   
                   
     None          和 ‘'d'’ 相同。
                   

在上述的表示类型之外，整数还可以通过下列的浮点表示类型来格式化 (除了
‘'n'’ 和 ‘None’)。 当这样做时，会在格式化之前使用 *note float(): 188. 将
整数转换为浮点数。

*note float: 188. 和 *note Decimal: 189. 值的可用表示类型有:

     类型          含义
                   
     -----------------------------------------------------------------------------
                   
     ‘'e'’         科学计数法。 对于一个给定的精度 ‘p’，数字格式化为以字母 ’e’
                   分隔系数和指数的科学计数法形式。 系数在小数点之前有一位，之
                   后有 ‘p’ 位，总计 ‘p + 1’ 个有效数位。 如未指定精度，则会对
                   *note float: 188. 采用小数点之后 ‘6’ 位精度，而对
                   *note Decimal: 189. 则显示所有系数位。 如果小数点之后没有数
                   位，则小数点也会被略去，除非使用了 ‘#’ 选项。
                   
                   
     ‘'E'’         科学计数法。 与 ‘'e'’ 相似，不同之处在于它使用大写字母 ’E’ 作
                   为分隔字符。
                   
                   
     ‘'f'’         定点计数法。 对于一个给定的精度 ‘p’，将数字格式化为在小数点
                   之后恰好有 ‘p’ 位的小数形式。 如未指定精度，则会对
                   *note float: 188. 采用小数点之后 ‘6’ 位精度，而对
                   *note Decimal: 189. 则使用大到足够显示所有系数位的精度。 如
                   果小数点之后没有数位，则小数点也会被略去，除非使用了 ‘#’ 选
                   项。
                   
                   
     ‘'F'’         定点表示。 与 ‘'f'’ 相似，但会将 ‘nan’ 转为 ‘NAN’ 并将 ‘inf’
                   转为 ‘INF’。
                   
                   
     ‘'g'’         常规格式。 对于给定精度 ‘p >= 1’，这会将数值舍入到 ‘p’ 个有
                   效数位，再将结果以定点格式或科学计数法进行格式化，具体取决于
                   其值的大小。 精度 ‘0’ 会被视为等价于精度 ‘1’。
                   
                   准确的规则如下：假设使用表示类型 ‘'e'’ 和精度 ‘p-1’ 进行格式
                   化的结果具有指数值 ‘exp’。 那么如果 ‘m <= exp < p’，其中 ‘m’
                   以 -4 表示浮点值而以 -6 表示 *note Decimal: 189. 值，该数字
                   将使用类型 ‘'f'’ 和精度 ‘p-1-exp’ 进行格式化。 否则的话，该
                   数字将使用表示类型 ‘'e'’ 和精度 ‘p-1’ 进行格式化。 在两种情
                   况下，都会从有效数字中移除无意义的末尾零，如果小数点之后没有
                   余下数字则小数点也会被移除，除非使用了 ‘'#'’ 选项。
                   
                   如未指定精度，会对 *note float: 188. 采用 ‘6’ 个有效数位的精
                   度。 对于 *note Decimal: 189.，结果的系数会沿用原值的系数数
                   位；对于绝对值小于 ‘1e-6’ 的值以及最小有效数位的位值大于 1 的
                   数值将会使用科学计数法，在其他情况下则会使用定点计数法。
                   
                   正负无穷，正负零和 nan 会分别被格式化为 ‘inf’, ‘-inf’, ‘0’,
                   ‘-0’ 和 ‘nan’，无论精度如何设定。
                   
                   
     ‘'G'’         常规格式。 类似于 ‘'g'’，不同之处在于当数值非常大时会切换为
                   ‘'E'’。 无穷与 NaN 也会表示为大写形式。
                   
                   
     ‘'n'’         数字。 这与 ‘'g'’ 相似，不同之处在于它会使用当前区域设置来插
                   入适当的数字分隔字符。
                   
                   
     ‘'%'’         百分比。 将数字乘以 100 并显示为定点 (‘'f'’) 格式，后面带一
                   个百分号。
                   
                   
     None          对于 *note float: 188. 来说这类似于 ‘'g'’，不同之处在于当使
                   用定点表示法时，小数点之后将至少显示一位。 所用的精度会大到
                   足以精确表示给定的值。
                   
                   对于 *note Decimal: 189. 来说这相当于 ‘'g'’ 或 ‘'G'’，具体取
                   决于当前 decimal 上下文的 ‘context.capitals’ 值。
                   
                   总体效果是将 *note str(): 339. 的输出匹配为其他格式化因子所
                   调整出的样子。
                   

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0378

   (2) https://www.python.org/dev/peps/pep-0515


File: python.info,  Node: 格式示例,  Prev: 格式规格迷你语言,  Up: 格式字符串语法

5.6.1.5 格式示例
................

本节包含 *note str.format(): 4e2. 语法的示例以及与旧式 ‘%’ 格式化的比较
。

该语法在大多数情况下与旧式的 ‘%’ 格式化类似，只是增加了 ‘{}’ 和 ‘:’ 来取
代 ‘%’。 例如，，‘'%03.2f'’ 可以被改写为 ‘'{:03.2f}'’。

新的格式语法还支持新增的不同选项，将在以下示例中说明。

按位置访问参数:

     >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
     'a, b, c'
     >>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only
     'a, b, c'
     >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
     'c, b, a'
     >>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
     'c, b, a'
     >>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
     'abracadabra'

按名称访问参数:

     >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
     'Coordinates: 37.24N, -115.81W'
     >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
     >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
     'Coordinates: 37.24N, -115.81W'

访问参数的属性:

     >>> c = 3-5j
     >>> ('The complex number {0} is formed from the real part {0.real} '
     ...  'and the imaginary part {0.imag}.').format(c)
     'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
     >>> class Point:
     ...     def __init__(self, x, y):
     ...         self.x, self.y = x, y
     ...     def __str__(self):
     ...         return 'Point({self.x}, {self.y})'.format(self=self)
     ...
     >>> str(Point(4, 2))
     'Point(4, 2)'

访问参数的项:

     >>> coord = (3, 5)
     >>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
     'X: 3;  Y: 5'

替代 ‘%s’ 和 ‘%r’:

     >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
     "repr() shows quotes: 'test1'; str() doesn't: test2"

对齐文本以及指定宽度:

     >>> '{:<30}'.format('left aligned')
     'left aligned                  '
     >>> '{:>30}'.format('right aligned')
     '                 right aligned'
     >>> '{:^30}'.format('centered')
     '           centered           '
     >>> '{:*^30}'.format('centered')  # use '*' as a fill char
     '***********centered***********'

替代 ‘%+f’, ‘%-f’ 和 ‘% f’ 以及指定正负号:

     >>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
     '+3.140000; -3.140000'
     >>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
     ' 3.140000; -3.140000'
     >>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
     '3.140000; -3.140000'

替代 ‘%x’ 和 ‘%o’ 以及转换基于不同进位制的值:

     >>> # format also supports binary numbers
     >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
     'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
     >>> # with 0x, 0o, or 0b as prefix:
     >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
     'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

使用逗号作为千位分隔符:

     >>> '{:,}'.format(1234567890)
     '1,234,567,890'

表示为百分数:

     >>> points = 19
     >>> total = 22
     >>> 'Correct answers: {:.2%}'.format(points/total)
     'Correct answers: 86.36%'

使用特定类型的专属格式化:

     >>> import datetime
     >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
     >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
     '2010-07-04 12:15:58'

嵌套参数以及更复杂的示例:

     >>> for align, text in zip('<^>', ['left', 'center', 'right']):
     ...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
     ...
     'left<<<<<<<<<<<<'
     '^^^^^center^^^^^'
     '>>>>>>>>>>>right'
     >>>
     >>> octets = [192, 168, 0, 1]
     >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
     'C0A80001'
     >>> int(_, 16)
     3232235521
     >>>
     >>> width = 5
     >>> for num in range(5,12):
     ...     for base in 'dXob':
     ...         print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
     ...     print()
     ...
         5     5     5   101
         6     6     6   110
         7     7     7   111
         8     8    10  1000
         9     9    11  1001
        10     A    12  1010
        11     B    13  1011


File: python.info,  Node: 模板字符串,  Next: 辅助函数,  Prev: 格式字符串语法,  Up: string --- 常见的字符串操作

5.6.1.6 模板字符串
..................

模板字符串提供了由 PEP 292(1) 所描述的更简便的字符串替换方式。 模板字符
串的一个主要用例是文本国际化 (i18n)，因为在此场景下，更简单的语法和功能
使得文本翻译过程比使用 Python 的其他内置字符串格式化工具更为方便。 作为
基于模板字符串构建以实现 i18n 的库的一个示例，请参看 flufl.i18n(2) 包。

模板字符串支持基于 ‘$’ 的替换，使用以下规则：

   * ‘$$’ 为转义符号；它会被替换为单个的 ‘$’。

   * ‘$identifier’ 为替换占位符，它会匹配一个名为 ‘"identifier"’ 的映射
     键。 在默认情况下，‘"identifier"’ 限制为任意 ASCII 字母数字（包括下
     划线）组成的字符串，不区分大小写，以下划线或 ASCII 字母开头。 在
     ‘$’ 字符之后的第一个非标识符字符将表明占位符的终结。

   * ‘${identifier}’ 等价于 ‘$identifier’。 当占位符之后紧跟着有效的但又
     不是占位符一部分的标识符字符时需要使用，例如 ‘"${noun}ification"’。

在字符串的其他位置出现 ‘$’ 将导致引发 *note ValueError: 1fc.。

*note string: f7. 模块提供了实现这些规则的 *note Template: 3f3. 类。
*note Template: 3f3. 有下列方法：

 -- 类: string.Template (template)

     该构造器接受一个参数作为模板字符串。

      -- 方法: substitute (mapping={}, /, **kwds)

          执行模板替换，返回一个新字符串。 `mapping' 为任意字典类对象，
          其中的键将匹配模板中的占位符。 或者你也可以提供一组关键字参数
          ，其中的关键字即对应占位符。 当同时给出 `mapping' 和 `kwds' 并
          且存在重复时，则以 `kwds' 中的占位符为优先。

      -- 方法: safe_substitute (mapping={}, /, **kwds)

          类似于 *note substitute(): 130f.，不同之处是如果有占位符未在
          `mapping' 和 `kwds' 中找到，不是引发 *note KeyError: 2c8. 异常
          ，而是将原始占位符不加修改地显示在结果字符串中。 另一个与
          *note substitute(): 130f. 的差异是任何在其他情况下出现的 ‘$’ 将
          简单地返回 ‘$’ 而不是引发 *note ValueError: 1fc.。

          此方法被认为“安全”，因为虽然仍有可能发生其他异常，但它总是尝试
          返回可用的字符串而不是引发一个异常。 从另一方面来说，*note
          safe_substitute(): 1310. 也可能根本算不上安全，因为它将静默地
          忽略错误格式的模板，例如包含多余的分隔符、不成对的花括号或不是
          合法 Python 标识符的占位符等等。

     *note Template: 3f3. 的实例还提供一个公有数据属性：

      -- 属性: template

          这是作为构造器的 `template' 参数被传入的对象。 一般来说，你不
          应该修改它，但并不强制要求只读访问。

以下是一个如何使用模版的示例：

     >>> from string import Template
     >>> s = Template('$who likes $what')
     >>> s.substitute(who='tim', what='kung pao')
     'tim likes kung pao'
     >>> d = dict(who='tim')
     >>> Template('Give $who $100').substitute(d)
     Traceback (most recent call last):
     ...
     ValueError: Invalid placeholder in string: line 1, col 11
     >>> Template('$who likes $what').substitute(d)
     Traceback (most recent call last):
     ...
     KeyError: 'what'
     >>> Template('$who likes $what').safe_substitute(d)
     'tim likes $what'

进阶用法：你可以派生 *note Template: 3f3. 的子类来自定义占位符语法、分隔
符，或用于解析模板字符串的整个正则表达式。 为此目的，你可以重载这些类属
性：

   * `delimiter' – 这是用来表示占位符的起始的分隔符的字符串字面值。 默认
     值为 ‘$’。 请注意此参数 `不能' 为正则表达式，因为其实现将在必要时对
     此字符串调用 *note re.escape(): 49d.。 还要注意你不能在创建类之后改
     变此分隔符（例如在子类的类命名空间中必须设置不同的分隔符）。

   * `idpattern' – 这是用来描述不带花括号的占位符的模式的正则表达式。 默
     认值为正则表达式 ‘(?a:[_a-z][_a-z0-9]*)’。 如果给出了此属性并且
     `braceidpattern' 为 ‘None’ 则此模式也将作用于带花括号的占位符。

          注解: 由于默认的 `flags' 为 ‘re.IGNORECASE’，模式 ‘[a-z]’ 可以
          匹配某些非 ASCII 字符。 因此我们在这里使用了局部旗标 ‘a’。

     在 3.7 版更改: `braceidpattern' 可被用来定义对花括号内部和外部进行
     区分的模式。

   * `braceidpattern' – 此属性类似于 `idpattern' 但是用来描述带花括号的
     占位符的模式。 默认值 ‘None’ 意味着回退到 `idpattern' (即在花括号内
     部和外部使用相同的模式)。 如果给出此属性，这将允许你为带花括号和不
     带花括号的占位符定义不同的模式。

     3.7 新版功能.

   * `flags' – 将在编译用于识别替换内容的正则表达式被应用的正则表达式旗
     标。 默认值为 ‘re.IGNORECASE’。 请注意 ‘re.VERBOSE’ 总是会被加为旗
     标，因此自定义的 `idpattern' 必须遵循详细正则表达式的约定。

     3.2 新版功能.

作为另一种选项，你可以通过重载类属性 `pattern' 来提供整个正则表达式模式
。 如果你这样做，该值必须为一个具有四个命名捕获组的正则表达式对象。 这些
捕获组对应于上面已经给出的规则，以及无效占位符的规则：

   * `escaped' – 这个组匹配转义序列，在默认模式中即 ‘$$’。

   * `named' – 这个组匹配不带花括号的占位符名称；它不应当包含捕获组中的
     分隔符。

   * `braced' – 这个组匹配带有花括号的占位符名称；它不应当包含捕获组中的
     分隔符或者花括号。

   * `invalid' – 这个组匹配任何其他分隔符模式（通常为单个分隔符），并且
     它应当出现在正则表达式的末尾。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0292

   (2) http://flufli18n.readthedocs.io/en/latest/


File: python.info,  Node: 辅助函数,  Prev: 模板字符串,  Up: string --- 常见的字符串操作

5.6.1.7 辅助函数
................

 -- 函数: string.capwords (s, sep=None)

     使用 *note str.split(): 7aa. 将参数拆分为单词，使用 *note
     str.capitalize(): 1652. 将单词转为大写形式，使用 *note str.join():
     1642. 将大写的单词进行拼接。 如果可选的第二个参数 `sep' 被省略或为
     ‘None’，则连续的空白字符会被替换为单个空格符并且开头和末尾的空白字
     符会被移除，否则 `sep' 会被用来拆分和拼接单词。


File: python.info,  Node: re --- 正则表达式操作,  Next: difflib --- 计算差异的辅助工具,  Prev: string --- 常见的字符串操作,  Up: 文本处理服务

5.6.2 ‘re’ — 正则表达式操作
---------------------------

`源代码:' Lib/re.py(1)

__________________________________________________________________

这个模块提供了与 Perl 语言类似的正则表达式匹配操作。

模式和被搜索的字符串既可以是 Unicode 字符串 (*note str: 339.) ，也可以是
8位字节串 (*note bytes: 33a.)。 但是，Unicode 字符串与8位字节串不能混用
：也就是说，你不能用一个字节串模式去匹配 Unicode 字符串，反之亦然；类似
地，当进行替换操作时，替换字符串的类型也必须与所用的模式和搜索字符串的类
型一致。

正则表达式使用反斜杠字符 (‘'\'’) 来表示特殊形式或是允许在使用特殊字符时
不引发它们的特殊含义。 这会与 Python 的字符串字面值中对相同字符出于相同
目的的用法产生冲突；例如，要匹配一个反斜杠字面值，用户可能必须写成
‘'\\\\'’ 来作为模式字符串，因为正则表达式必须为 ‘\\’，而每个反斜杠在普通
Python 字符串字面值中又必须表示为 ‘\\’。 而且还要注意，在 Python 的字符
串字面值中使用的反斜杠如果有任何无效的转义序列，现在将会产生 *note
DeprecationWarning: 279. 并将在未来改为 *note SyntaxError: 460.。 此行为
即使对于正则表达式来说有效的转义字符同样会发生。

解决办法是对于正则表达式样式使用 Python 的原始字符串表示法；在带有 ‘'r'’
前缀的字符串字面值中，反斜杠不必做任何特殊处理。 因此 ‘r"\n"’ 表示包含
‘'\'’ 和 ‘'n'’ 两个字符的字符串，而 ‘"\n"’ 则表示只包含一个换行符的字符
串。 样式在 Python 代码中通常都会使用这种原始字符串表示法来表示。

绝大部分正则表达式操作都提供为模块函数和方法，在 *note 编译正则表达式:
8a5.  这些函数是一个捷径，不需要先编译一个正则对象，但是损失了一些优化参
数。

参见
....

第三方模块 regex(2) , 提供了与标准库 *note re: de. 模块兼容的API接口, 同
时还提供了额外的功能和更全面的Unicode支持。

* Menu:

* 正则表达式语法::
* 模块内容::
* 正则表达式对象 （正则对象）::
* 匹配对象::
* 正则表达式例子::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/re.py

   (2) https://pypi.org/project/regex/


File: python.info,  Node: 正则表达式语法,  Next: 模块内容,  Up: re --- 正则表达式操作

5.6.2.1 正则表达式语法
......................

一个正则表达式（或RE）指定了一集与之匹配的字符串；模块内的函数可以让你检
查某个字符串是否跟给定的正则表达式匹配（或者一个正则表达式是否匹配到一个
字符串，这两种说法含义相同）。

正则表达式可以拼接； 如果 `A' 和 `B' 都是正则表达式， 那么 `AB' 也是正则
表达式。 通常， 如果字符串 `p' 匹配 `A' 并且另一个字符串 `q' 匹配 `B', 那
么 `pq' 可以匹配 AB。除非 `A' 或者 `B' 包含低优先级操作，`A' 和 `B' 存在
边界条件；或者命名组引用。所以，复杂表达式可以很容易的从这里描述的简单源
语表达式构建。 了解更多正则表达式理论和实现，参考the Friedl book *note
[Frie09]: 175f. ，或者其他编译器构建的书籍。

以下是正则表达式格式的简要说明。更详细的信息和演示，参考 *note
正则表达式HOWTO: 1760.。

正则表达式可以包含普通或者特殊字符。绝大部分普通字符，比如 ‘'A'’, ‘'a'’,
或者 ‘'0'’，都是最简单的正则表达式。它们就匹配自身。你可以拼接普通字符，
所以 ‘last’ 匹配字符串 ‘'last'’.  （在这一节的其他部分，我们将用 ‘this
special style’ 这种方式表示正则表达式，通常不带引号，要匹配的字符串用
‘'in single quotes'’ ，单引号形式。）

有些字符，比如 ‘'|'’ 或者 ‘'('’，属于特殊字符。 特殊字符既可以表示它的普
通含义， 也可以影响它旁边的正则表达式的解释。

重复修饰符 (‘*’, ‘+’, ‘?’, ‘{m,n}’, 等) 不能直接嵌套。这样避免了非贪婪后
缀 ‘?’ 修饰符，和其他实现中的修饰符产生的多义性。要应用一个内层重复嵌套
，可以使用括号。 比如，表达式 ‘(?:a{6})*’ 匹配6个 ‘'a'’ 字符重复任意次数
。

特殊字符有：

‘.’

     (点) 在默认模式，匹配除了换行的任意字符。如果指定了标签 *note
     DOTALL: 1761. ，它将匹配包括换行符的任意字符。

‘^’

     (插入符号) 匹配字符串的开头， 并且在 *note MULTILINE: 1762. 模式也
     匹配换行后的首个符号。

‘$’

     匹配字符串尾或者在字符串尾的换行符的前一个字符，在 *note MULTILINE:
     1762. 模式下也会匹配换行符之前的文本。 ‘foo’ 匹配 ’foo’ 和
     ’foobar’，但正则表达式 ‘foo$’ 只匹配 ’foo’。 更有趣的是，在
     ‘'foo1\nfoo2\n'’ 中搜索 ‘foo.$’，通常匹配 ’foo2’，但在 *note
     MULTILINE: 1762. 模式下可以匹配到 ’foo1’；在 ‘'foo\n'’ 中搜索 ‘$’ 会
     找到两个（空的）匹配：一个在换行符之前，一个在字符串的末尾。

‘*’

     对它前面的正则式匹配0到任意次重复， 尽量多的匹配字符串。 ‘ab*’ 会匹
     配 ‘'a'’，‘'ab'’，或者 ‘'a'’ 后面跟随任意个 ‘'b'’。

‘+’

     对它前面的正则式匹配1到任意次重复。 ‘ab+’ 会匹配 ‘'a'’ 后面跟随1个
     以上到任意个 ‘'b'’，它不会匹配 ‘'a'’。

‘?’

     对它前面的正则式匹配0到1次重复。 ‘ab?’ 会匹配 ‘'a'’ 或者 ‘'ab'’。

‘*?’, ‘+?’, ‘??’

     ‘'*'’, ‘'+'’，和 ‘'?'’ 修饰符都是 `贪婪的'；它们在字符串进行尽可能
     多的匹配。有时候并不需要这种行为。如果正则式 ‘<.*>’ 希望找到 ‘'<a>
     b <c>'’，它将会匹配整个字符串，而不仅是 ‘'<a>'’。在修饰符之后添加
     ‘?’ 将使样式以 `非贪婪‘方式或者 :dfn:‘最小' 方式进行匹配； 尽量 `少
     ' 的字符将会被匹配。 使用正则式 ‘<.*?>’ 将会仅仅匹配 ‘'<a>'’。

‘{m}’

     对其之前的正则式指定匹配 `m' 个重复；少于 `m' 的话就会导致匹配失败
     。比如， ‘a{6}’ 将匹配6个 ‘'a'’ , 但是不能是5个。

‘{m,n}’

     对正则式进行 `m' 到 `n' 次匹配，在 `m' 和 `n' 之间取尽量多。 比如，
     ‘a{3,5}’ 将匹配 3 到 5个 ‘'a'’。忽略 `m' 意为指定下界为0，忽略 `n'
     指定上界为无限次。 比如 ‘a{4,}b’ 将匹配 ‘'aaaab'’ 或者1000个 ‘'a'’
     尾随一个 ‘'b'’，但不能匹配 ‘'aaab'’。逗号不能省略，否则无法辨别修饰
     符应该忽略哪个边界。

‘{m,n}?’

     前一个修饰符的非贪婪模式，只匹配尽量少的字符次数。比如，对于
     ‘'aaaaaa'’， ‘a{3,5}’ 匹配 5个 ‘'a'’ ，而 ‘a{3,5}?’ 只匹配3个
     ‘'a'’。

‘\’

     转义特殊字符（允许你匹配 ‘'*'’, ‘'?'’, 或者此类其他），或者表示一个
     特殊序列；特殊序列之后进行讨论。

     如果你没有使用原始字符串（ ‘r'raw'’ ）来表达样式，要牢记Python也使
     用反斜杠作为转义序列；如果转义序列不被Python的分析器识别，反斜杠和
     字符才能出现在字符串中。如果Python可以识别这个序列，那么反斜杠就应
     该重复两次。这将导致理解障碍，所以高度推荐，就算是最简单的表达式，
     也要使用原始字符串。

‘[]’

     用于表示一个字符集合。在一个集合中：

        * 字符可以单独列出，比如 ‘[amk]’ 匹配 ‘'a'’， ‘'m'’， 或者
          ‘'k'’。

        * 可以表示字符范围，通过用 ‘'-'’ 将两个字符连起来。比如 ‘[a-z]’
          将匹配任何小写ASCII字符， ‘[0-5][0-9]’ 将匹配从 ‘00’ 到 ‘59’ 的
          两位数字， ‘[0-9A-Fa-f]’ 将匹配任何十六进制数位。 如果 ‘-’ 进
          行了转义 （比如 ‘[a\-z]’）或者它的位置在首位或者末尾（如
          ‘[-a]’ 或 ‘[a-]’），它就只表示普通字符 ‘'-'’。

        * 特殊字符在集合中，失去它的特殊含义。比如 ‘[(+*)]’ 只会匹配这几
          个文法字符 ‘'('’, ‘'+'’, ‘'*'’, or ‘')'’。

        * 字符类如 ‘\w’ 或者 ‘\S’ (如下定义) 在集合内可以接受，它们可以
          匹配的字符由 *note ASCII: 3d0. 或者 *note LOCALE: 3d1. 模式决
          定。

        * 不在集合范围内的字符可以通过 `取反' 来进行匹配。如果集合首字符
          是 ‘'^'’ ，所有 `不' 在集合内的字符将会被匹配，比如 ‘[^5]’ 将
          匹配所有字符，除了 ‘'5'’， ‘[^^]’ 将匹配所有字符，除了 ‘'^'’.
          ‘^’ 如果不在集合首位，就没有特殊含义。

        * 在集合内要匹配一个字符 ‘']'’，有两种方法，要么就在它之前加上反
          斜杠，要么就把它放到集合首位。比如， ‘[()[\]{}]’ 和 ‘[]()[{}]’
          都可以匹配括号。

        * Unicode Technical Standard #18(1) 里的嵌套集合和集合操作支持可
          能在未来添加。这将会改变语法，所以为了帮助这个改变，一个 *note
          FutureWarning: 32e. 将会在有多义的情况里被 ‘raise’，包含以下几
          种情况，集合由 ‘'['’ 开始，或者包含下列字符序列 ‘'--'’,
          ‘'&&'’, ‘'~~'’, 和 ‘'||'’。为了避免警告，需要将它们用反斜杠转
          义。

     在 3.7 版更改: 如果一个字符串构建的语义在未来会改变的话，一个 *note
     FutureWarning: 32e. 会 ‘raise’ 。

‘|’

     ‘A|B’， `A' 和 `B' 可以是任意正则表达式，创建一个正则表达式，匹配
     `A' 或者 `B'. 任意个正则表达式可以用 ‘'|'’ 连接。它也可以在组合（见
     下列）内使用。扫描目标字符串时， ‘'|'’ 分隔开的正则样式从左到右进行
     匹配。当一个样式完全匹配时，这个分支就被接受。意思就是，一旦 `A' 匹
     配成功， `B' 就不再进行匹配，即便它能产生一个更好的匹配。或者说，
     ‘'|'’ 操作符绝不贪婪。 如果要匹配 ‘'|'’ 字符，使用 ‘\|’， 或者把它
     包含在字符集里，比如 ‘[|]’.

‘(...)’

     （组合），匹配括号内的任意正则表达式，并标识出组合的开始和结尾。匹
     配完成后，组合的内容可以被获取，并可以在之后用 ‘\number’ 转义序列进
     行再次匹配，之后进行详细说明。要匹配字符 ‘'('’ 或者 ‘')'’, 用 ‘\(’
     或 ‘\)’, 或者把它们包含在字符集合里: ‘[(]’, ‘[)]’.

‘(?…)’

     这是个扩展标记法 （一个 ‘'?'’ 跟随 ‘'('’ 并无含义）。 ‘'?'’ 后面的
     第一个字符决定了这个构建采用什么样的语法。这种扩展通常并不创建新的
     组合； ‘(?P<name>...)’ 是唯一的例外。 以下是目前支持的扩展。

‘(?aiLmsux)’

     ( ‘'a'’, ‘'i'’, ‘'L'’, ‘'m'’, ‘'s'’, ‘'u'’, ‘'x'’ 中的一个或多个) 这
     个组合匹配一个空字符串；这些字符对正则表达式设置以下标记 *note
     re.A: 1763. (只匹配ASCII字符), *note re.I: 1764. (忽略大小写),
     *note re.L: 1765. (语言依赖), *note re.M: 1766. (多行模式), *note
     re.S: 1767. (点dot匹配全部字符), ‘re.U’ (Unicode匹配), and *note
     re.X: 1768. (冗长模式)。 (这些标记在 *note 模块内容: 1769. 中描述)
     如果你想将这些标记包含在正则表达式中，这个方法就很有用，免去了在
     *note re.compile(): 452. 中传递 `flag' 参数。标记应该在表达式字符串
     首位表示。

‘(?:…)’

     正则括号的非捕获版本。 匹配在括号内的任何正则表达式，但该分组所匹配
     的子字符串 `不能' 在执行匹配后被获取或是之后在模式中被引用。

‘(?aiLmsux-imsx:…)’

     (‘'a'’, ‘'i'’, ‘'L'’, ‘'m'’, ‘'s'’, ‘'u'’, ‘'x'’ 中的0或者多个， 之
     后可选跟随 ‘'-'’ 在后面跟随 ‘'i'’ , ‘'m'’ , ‘'s'’ , ‘'x'’ 中的一到
     多个 .) 这些字符为表达式的其中一部分 `设置' 或者 `去除' 相应标记
     *note re.A: 1763. (只匹配ASCII), *note re.I: 1764. (忽略大小写),
     *note re.L: 1765. (语言依赖), *note re.M: 1766. (多行), *note re.S:
     1767. (点匹配所有字符), ‘re.U’ (Unicode匹配), and *note re.X: 1768.
     (冗长模式)。(标记描述在 *note 模块内容: 1769. .)

     ‘'a'’, ‘'L'’ and ‘'u'’ 作为内联标记是相互排斥的， 所以它们不能结合
     在一起，或者跟随 ‘'-'’ 。 当他们中的某个出现在内联组中，它就覆盖了
     括号组内的匹配模式。在Unicode样式中， ‘(?a:...)’ 切换为 只匹配
     ASCII， ‘(?u:...)’ 切换为Unicode匹配 (默认).  在byte样式中
     ‘(?L:...)’ 切换为语言依赖模式， ‘(?a:...)’ 切换为 只匹配ASCII (默认
     )。这种方式只覆盖组合内匹配，括号外的匹配模式不受影响。

     3.6 新版功能.

     在 3.7 版更改: 符号 ‘'a'’, ‘'L'’ 和 ‘'u'’ 同样可以用在一个组合内。

‘(?P<name>…)’

     （命名组合）类似正则组合，但是匹配到的子串组在外部是通过定义的
     `name' 来获取的。组合名必须是有效的Python标识符，并且每个组合名只能
     用一个正则表达式定义，只能定义一次。一个符号组合同样是一个数字组合
     ，就像这个组合没有被命名一样。

     命名组合可以在三种上下文中引用。如果样式是
     ‘(?P<quote>['"]).*?(?P=quote)’ （也就是说，匹配单引号或者双引号括起
     来的字符串)：

     引用组合 "quote" 的上下文                   引用方法
                                                 
     -----------------------------------------------------------------------------------
                                                 
     在正则式自身内                                 * ‘(?P=quote)’ (如示)
                                                 
                                                    * ‘\1’
                                                 
                                                 
     处理匹配对象 `m'                               * ‘m.group('quote')’
                                                 
                                                    * ‘m.end('quote')’ (等)
                                                 
                                                 
     传递到 ‘re.sub()’ 里的 `repl' 参数中           * ‘\g<quote>’
                                                 
                                                    * ‘\g<1>’
                                                 
                                                    * ‘\1’
                                                 

‘(?P=name)’

     反向引用一个命名组合；它匹配前面那个叫 `name' 的命名组中匹配到的串
     同样的字串。

‘(?#…)’

     注释；里面的内容会被忽略。

‘(?=…)’

     匹配 ‘…’ 的内容，但是并不消费样式的内容。这个叫做 `lookahead
     assertion'。比如， ‘Isaac (?=Asimov)’ 匹配 ‘'Isaac '’ 只有在后面是
     ‘'Asimov'’ 的时候。

‘(?!…)’

     匹配 ‘…’ 不符合的情况。这个叫 `negative lookahead assertion' （前视
     取反）。比如说， ‘Isaac (?!Asimov)’ 只有后面 `不' 是 ‘'Asimov'’ 的
     时候才匹配 ‘'Isaac '’ 。

‘(?<=…)’

     匹配字符串的当前位置，它的前面匹配 ‘…’ 的内容到当前位置。这叫
     :dfn:‘positive lookbehind assertion’ （正向后视断定）。
     ‘(?<=abc)def’ 会在 ‘'abcdef'’ 中找到一个匹配，因为后视会往后看3个字
     符并检查是否包含匹配的样式。包含的匹配样式必须是定长的，意思就是
     ‘abc’ 或 ‘a|b’ 是允许的，但是 ‘a*’ 和 ‘a{3,4}’ 不可以。注意以
     positive lookbehind assertions 开始的样式，如 ‘(?<=abc)def’ ，并不
     是从 a 开始搜索，而是从 d 往回看的。你可能更加愿意使用 *note
     search(): bba. 函数，而不是 *note match(): bbb. 函数：

          >>> import re
          >>> m = re.search('(?<=abc)def', 'abcdef')
          >>> m.group(0)
          'def'

     这个例子搜索一个跟随在连字符后的单词：

          >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
          >>> m.group(0)
          'egg'

     在 3.5 版更改: 添加定长组合引用的支持。

‘(?<!…)’

     匹配当前位置之前不是 ‘...’ 的样式。这个叫 `negative lookbehind
     assertion' （后视断定取非）。类似正向后视断定，包含的样式匹配必须是
     定长的。由 negative lookbehind assertion 开始的样式可以从字符串搜索
     开始的位置进行匹配。

‘(?(id/name)yes-pattern|no-pattern)’

     如果给定的 `id' 或 `name' 存在，将会尝试匹配 ‘yes-pattern’ ，否则就
     尝试匹配 ‘no-pattern’，‘no-pattern’ 可选，也可以被忽略。比如，
     ‘(<)?(\w+@\w+(?:\.\w+)+)(?(1)>|$)’ 是一个email样式匹配，将匹配
     ‘'<user@host.com>'’ 或 ‘'user@host.com'’ ，但不会匹配
     ‘'<user@host.com'’ ，也不会匹配 ‘'user@host.com>'’。

由 ‘'\'’ 和一个字符组成的特殊序列在以下列出。 如果普通字符不是ASCII数位
或者ASCII字母，那么正则样式将匹配第二个字符。比如，‘\$’ 匹配字符 ‘'$'’.

‘\number’

     匹配数字代表的组合。每个括号是一个组合，组合从1开始编号。比如 ‘(.+)
     \1’ 匹配 ‘'the the'’ 或者 ‘'55 55'’, 但不会匹配 ‘'thethe'’ (注意组
     合后面的空格)。这个特殊序列只能用于匹配前面99个组合。如果 `number'
     的第一个数位是0， 或者 `number' 是三个八进制数，它将不会被看作是一
     个组合，而是八进制的数字值。在 ‘'['’ 和 ‘']'’ 字符集合内，任何数字
     转义都被看作是字符。

‘\A’

     只匹配字符串开始。

‘\b’

     匹配空字符串，但只在单词开始或结尾的位置。一个单词被定义为一个单词
     字符的序列。注意，通常 ‘\b’ 定义为 ‘\w’ 和 ‘\W’ 字符之间，或者 ‘\w’
     和字符串开始/结尾的边界， 意思就是 ‘r'\bfoo\b'’ 匹配 ‘'foo'’,
     ‘'foo.'’, ‘'(foo)'’, ‘'bar foo baz'’ 但不匹配 ‘'foobar'’ 或者
     ‘'foo3'’。

     默认情况下，Unicode字母和数字是在Unicode样式中使用的，但是可以用
     *note ASCII: 3d0. 标记来更改。如果 *note LOCALE: 3d1. 标记被设置的
     话，词的边界是由当前语言区域设置决定的，‘\b’ 表示退格字符，以便与
     Python字符串文本兼容。

‘\B’

     匹配空字符串，但 `不' 能在词的开头或者结尾。意思就是 ‘r'py\B'’ 匹配
     ‘'python'’, ‘'py3'’, ‘'py2'’, 但不匹配 ‘'py'’, ‘'py.'’, 或者
     ‘'py!'’.  ‘\B’ 是 ‘\b’ 的取非，所以Unicode样式的词语是由Unicode字母
     ，数字或下划线构成的，虽然可以用 *note ASCII: 3d0. 标志来改变。如果
     使用了 *note LOCALE: 3d1. 标志，则词的边界由当前语言区域设置。

‘\d’

     对于 Unicode (str) 样式：

          匹配任何Unicode十进制数（就是在Unicode字符目录[Nd]里的字符）。
          这包括了 ‘[0-9]’ ，和很多其他的数字字符。如果设置了 *note
          ASCII: 3d0. 标志，就只匹配 ‘[0-9]’ 。

     对于8位(bytes)样式：

          匹配任何十进制数，就是 ‘[0-9]’。

‘\D’

     匹配任何非十进制数字的字符。就是 ‘\d’ 取非。 如果设置了 *note
     ASCII: 3d0. 标志，就相当于 ‘[^0-9]’ 。

‘\s’

     对于 Unicode (str) 样式：

          匹配任何Unicode空白字符（包括 ‘[ \t\n\r\f\v]’ ，还有很多其他字
          符，比如不同语言排版规则约定的不换行空格）。如果 *note ASCII:
          3d0. 被设置，就只匹配 ‘[ \t\n\r\f\v]’ 。

     对于8位(bytes)样式：

          匹配ASCII中的空白字符，就是 ‘[ \t\n\r\f\v]’ 。

‘\S’

     匹配任何非空白字符。就是 ‘\s’ 取非。如果设置了 *note ASCII: 3d0. 标
     志，就相当于 ‘[^ \t\n\r\f\v]’ 。

‘\w’

     对于 Unicode (str) 样式：

          匹配Unicode词语的字符，包含了可以构成词语的绝大部分字符，也包
          括数字和下划线。如果设置了 *note ASCII: 3d0. 标志，就只匹配
          ‘[a-zA-Z0-9_]’ 。

     对于8位(bytes)样式：

          匹配ASCII字符中的数字和字母和下划线，就是 ‘[a-zA-Z0-9_]’ 。如
          果设置了 *note LOCALE: 3d1. 标记，就匹配当前语言区域的数字和字
          母和下划线。

‘\W’

     匹配非单词字符的字符。这与 ‘\w’ 正相反。如果使用了 *note ASCII:
     3d0. 旗标，这就等价于 ‘[^a-zA-Z0-9_]’。如果使用了 *note LOCALE:
     3d1. 旗标，则会匹配当前区域中既非字母数字也非下划线的字符。

‘\Z’

     只匹配字符串尾。

绝大部分Python的标准转义字符也被正则表达式分析器支持。:

     \a      \b      \f      \n
     \N      \r      \t      \u
     \U      \v      \x      \\

（注意 ‘\b’ 被用于表示词语的边界，它只在字符集合内表示退格，比如 ‘[\b]’
。）

‘'\u'’, ‘'\U'’ 和 ‘'\N'’ 转义序列只在 Unicode 模式中可被识别。 在 bytes
模式中它们会导致错误。 未知的 ASCII 字母转义序列保留在未来使用，会被当作
错误来处理。

八进制转义包含为一个有限形式。如果首位数字是 0， 或者有三个八进制数位，
那么就认为它是八进制转义。其他的情况，就看作是组引用。对于字符串文本，八
进制转义最多有三个数位长。

在 3.3 版更改: 增加了 ‘'\u'’ 和 ‘'\U'’ 转义序列。

在 3.6 版更改: 由 ‘'\'’ 和一个ASCII字符组成的未知转义会被看成错误。

在 3.8 版更改: 添加了 ‘'\N{name}'’ 转义序列。 与在字符串字面值中一样，它
扩展了命名 Unicode 字符 (例如 ‘'\N{EM DASH}'’)。

   ---------- Footnotes ----------

   (1) https://unicode.org/reports/tr18/


File: python.info,  Node: 模块内容,  Next: 正则表达式对象 （正则对象）,  Prev: 正则表达式语法,  Up: re --- 正则表达式操作

5.6.2.2 模块内容
................

模块定义了几个函数，常量，和一个例外。有些函数是编译后的正则表达式方法的
简化版本（少了一些特性）。绝大部分重要的应用，总是会先将正则表达式编译，
之后在进行操作。

在 3.6 版更改: 标志常量现在是 ‘RegexFlag’ 类的实例，这个类是 *note
enum.IntFlag: 176b. 的子类。

 -- 函数: re.compile (pattern, flags=0)

     将正则表达式的样式编译为一个 *note 正则表达式对象: 8a5. （正则对象
     ），可以用于匹配，通过这个对象的方法 *note match(): 176c, *note
     search(): 176d. 以及其他如下描述。

     这个表达式的行为可以通过指定 `标记' 的值来改变。值可以是以下任意变
     量，可以通过位的OR操作来结合（ ‘|’ 操作符）。

     序列

          prog = re.compile(pattern)
          result = prog.match(string)

     等价于

          result = re.match(pattern, string)

     如果需要多次使用这个正则表达式的话，使用 *note re.compile(): 452. 和
     保存这个正则对象以便复用，可以让程序更加高效。

          注解: 通过 *note re.compile(): 452. 编译后的样式，和模块级的函
          数会被缓存， 所以少数的正则表达式使用无需考虑编译的问题。

 -- 数据: re.A
 -- 数据: re.ASCII

     让 ‘\w’, ‘\W’, ‘\b’, ‘\B’, ‘\d’, ‘\D’, ‘\s’ 和 ‘\S’ 只匹配ASCII，而
     不是Unicode。这只对Unicode样式有效，会被byte样式忽略。相当于前面语
     法中的内联标志 ‘(?a)’ 。

     注意，为了保持向后兼容， ‘re.U’ 标记依然存在（还有他的同义
     ‘re.UNICODE’ 和嵌入形式 ‘(?u)’ ) ， 但是这些在 Python 3 是冗余的，
     因为默认字符串已经是Unicode了（并且Unicode匹配不允许byte出现)。

 -- 数据: re.DEBUG

     显示编译时的debug信息，没有内联标记。

 -- 数据: re.I
 -- 数据: re.IGNORECASE

     进行忽略大小写匹配；表达式如 ‘[A-Z]’ 也会匹配小写字符。Unicode匹配
     （比如 ‘Ü’ 匹配 ‘ü’）同样有用，除非设置了 *note re.ASCII: 3d0. 标记
     来禁用非ASCII匹配。当前语言区域不会改变这个标记，除非设置了 *note
     re.LOCALE: 3d1. 标记。这个相当于内联标记 ‘(?i)’ 。

     注意，当设置了 *note IGNORECASE: 176f. 标记，搜索Unicode样式
     ‘[a-z]’ 或 ‘[A-Z]’ 的结合时，它将会匹配52个ASCII字符和4个额外的非
     ASCII字符： ’İ’ (U+0130, 拉丁大写的 I 带个点在上面), ’ı’ (U+0131, 拉
     丁小写没有点的 I ), ’ſ’ (U+017F, 拉丁小写长 s) and ’K’ (U+212A, 开
     尔文符号).如果使用 *note ASCII: 3d0. 标记，就只匹配 ’a’ 到 ’z’ 和
     ’A’ 到 ’Z’ 。

 -- 数据: re.L
 -- 数据: re.LOCALE

     由当前语言区域决定 ‘\w’, ‘\W’, ‘\b’, ‘\B’ 和大小写敏感匹配。这个标
     记只能对byte样式有效。这个标记不推荐使用，因为语言区域机制很不可靠
     ，它一次只能处理一个 "习惯”，而且只对8位字节有效。Unicode匹配在
     Python 3 里默认启用，并可以处理不同语言。 这个对应内联标记 ‘(?L)’ 。

     在 3.6 版更改: *note re.LOCALE: 3d1. 只能用于byte样式，而且不能和
     *note re.ASCII: 3d0. 一起用。

     在 3.7 版更改: 设置了 *note re.LOCALE: 3d1. 标记的编译正则对象不再
     在编译时依赖语言区域设置。语言区域设置只在匹配的时候影响其结果。

 -- 数据: re.M
 -- 数据: re.MULTILINE

     设置以后，样式字符 ‘'^'’ 匹配字符串的开始，和每一行的开始（换行符后
     面紧跟的符号）；样式字符 ‘'$'’ 匹配字符串尾，和每一行的结尾（换行符
     前面那个符号）。默认情况下，‘’^’’ 匹配字符串头，‘'$'’ 匹配字符串尾
     。对应内联标记 ‘(?m)’ 。

 -- 数据: re.S
 -- 数据: re.DOTALL

     让 ‘'.'’ 特殊字符匹配任何字符，包括换行符；如果没有这个标记，‘'.'’
     就匹配 `除了' 换行符的其他任意字符。对应内联标记 ‘(?s)’ 。

 -- 数据: re.X
 -- 数据: re.VERBOSE

     这个标记允许你编写更具可读性更友好的正则表达式。通过分段和添加注释
     。空白符号会被忽略，除非在一个字符集合当中或者由反斜杠转义，或者在
     ‘*?’, ‘(?:’ or ‘(?P<…>’ 分组之内。当一个行内有 ‘#’ 不在字符集和转义
     序列，那么它之后的所有字符都是注释。

     意思就是下面两个正则表达式等价地匹配一个十进制数字：

          a = re.compile(r"""\d +  # the integral part
                             \.    # the decimal point
                             \d *  # some fractional digits""", re.X)
          b = re.compile(r"\d+\.\d*")

     对应内联标记 ‘(?x)’ 。

 -- 函数: re.search (pattern, string, flags=0)

     扫描整个 `字符串' 找到匹配样式的第一个位置，并返回一个相应的 *note
     匹配对象: 8a6.。如果没有匹配，就返回一个 ‘None’ ； 注意这和找到一个
     零长度匹配是不同的。

 -- 函数: re.match (pattern, string, flags=0)

     如果 `string' 开始的0或者多个字符匹配到了正则表达式样式，就返回一个
     相应的 *note 匹配对象: 8a6. 。 如果没有匹配，就返回 ‘None’ ；注意它
     跟零长度匹配是不同的。

     注意即便是 *note MULTILINE: 1762. 多行模式， *note re.match(): bbb.
     也只匹配字符串的开始位置，而不匹配每行开始。

     如果你想定位 `string' 的任何位置，使用 *note search(): bba. 来替代
     （也可参考 *note search() vs.  match(): 1771. ）

 -- 函数: re.fullmatch (pattern, string, flags=0)

     如果整个 `string' 匹配到正则表达式样式，就返回一个相应的 *note
     匹配对象: 8a6. 。 否则就返回一个 ‘None’ ；注意这跟零长度匹配是不同
     的。

     3.4 新版功能.

 -- 函数: re.split (pattern, string, maxsplit=0, flags=0)

     用 `pattern' 分开 `string' 。 如果在 `pattern' 中捕获到括号，那么所
     有的组里的文字也会包含在列表里。如果 `maxsplit' 非零， 最多进行
     `maxsplit' 次分隔， 剩下的字符全部返回到列表的最后一个元素。

          >>> re.split(r'\W+', 'Words, words, words.')
          ['Words', 'words', 'words', '']
          >>> re.split(r'(\W+)', 'Words, words, words.')
          ['Words', ', ', 'words', ', ', 'words', '.', '']
          >>> re.split(r'\W+', 'Words, words, words.', 1)
          ['Words', 'words, words.']
          >>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
          ['0', '3', '9']

     如果分隔符里有捕获组合，并且匹配到字符串的开始，那么结果将会以一个
     空字符串开始。对于结尾也是一样

          >>> re.split(r'(\W+)', '...words, words...')
          ['', '...', 'words', ', ', 'words', '...', '']

     这样的话，分隔组将会出现在结果列表中同样的位置。

     样式的空匹配仅在与前一个空匹配不相邻时才会拆分字符串。

          >>> re.split(r'\b', 'Words, words, words.')
          ['', 'Words', ', ', 'words', ', ', 'words', '.']
          >>> re.split(r'\W*', '...words...')
          ['', '', 'w', 'o', 'r', 'd', 's', '', '']
          >>> re.split(r'(\W*)', '...words...')
          ['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', '']

     在 3.1 版更改: 增加了可选标记参数。

     在 3.7 版更改: 增加了空字符串的样式分隔。

 -- 函数: re.findall (pattern, string, flags=0)

     对 `string' 返回一个不重复的 `pattern' 的匹配列表， `string' 从左到
     右进行扫描，匹配按找到的顺序返回。如果样式里存在一到多个组，就返回
     一个组合列表；就是一个元组的列表（如果样式里有超过一个组合的话）。
     空匹配也会包含在结果里。

     在 3.7 版更改: 非空匹配现在可以在前一个空匹配之后出现了。

 -- 函数: re.finditer (pattern, string, flags=0)

     `pattern' 在 `string' 里所有的非重复匹配，返回为一个迭代器 *note
     iterator: 104b. 保存了 *note 匹配对象: 8a6. 。 `string' 从左到右扫
     描，匹配按顺序排列。空匹配也包含在结果里。

     在 3.7 版更改: 非空匹配现在可以在前一个空匹配之后出现了。

 -- 函数: re.sub (pattern, repl, string, count=0, flags=0)

     返回通过使用 `repl' 替换在 `string' 最左边非重叠出现的 `pattern' 而
     获得的字符串。 如果样式没有找到，则不加改变地返回 `string'。 `repl'
     可以是字符串或函数；如为字符串，则其中任何反斜杠转义序列都会被处理
     。 也就是说，‘\n’ 会被转换为一个换行符，‘\r’ 会被转换为一个回车附，
     依此类推。 未知的 ASCII 字符转义序列保留在未来使用，会被当作错误来
     处理。 其他未知转义序列例如 ‘\&’ 会保持原样。 向后引用像是 ‘\6’ 会
     用样式中第 6 组所匹配到的子字符串来替换。 例如:

          >>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
          ...        r'static PyObject*\npy_\1(void)\n{',
          ...        'def myfunc():')
          'static PyObject*\npy_myfunc(void)\n{'

     如果 `repl' 是一个函数，那它会对每个非重复的 `pattern' 的情况调用。
     这个函数只能有一个 *note 匹配对象: 8a6. 参数，并返回一个替换后的字
     符串。比如

          >>> def dashrepl(matchobj):
          ...     if matchobj.group(0) == '-': return ' '
          ...     else: return '-'
          >>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
          'pro--gram files'
          >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
          'Baked Beans & Spam'

     样式可以是一个字符串或者一个 *note 样式对象: 8a5. 。

     可选参数 `count' 是要替换的最大次数；`count' 必须是非负整数。如果省
     略这个参数或设为 0，所有的匹配都会被替换。 样式的空匹配仅在与前一个
     空匹配不相邻时才会被替换，所以 ‘sub('x*', '-', 'abxd')’ 返回
     ‘'-a-b--d-'’ 。

     在字符串类型的 `repl' 参数里，如上所述的转义和向后引用中，
     ‘\g<name>’ 会使用命名组合 ‘name’，（在 ‘(?P<name>…)’ 语法中定义）
     ‘\g<number>’ 会使用数字组；‘\g<2>’ 就是 ‘\2’，但它避免了二义性，如
     ‘\g<2>0’。 ‘\20’ 就会被解释为组20，而不是组2后面跟随一个字符 ‘'0'’。
     向后引用 ‘\g<0>’ 把 `pattern' 作为一整个组进行引用。

     在 3.1 版更改: 增加了可选标记参数。

     在 3.5 版更改: 不匹配的组合替换为空字符串。

     在 3.6 版更改: `pattern' 中的未知转义（由 ‘'\'’ 和一个 ASCII 字符组
     成）被视为错误。

     在 3.7 版更改: `repl' 中的未知转义（由 ‘'\'’ 和一个 ASCII 字符组成
     ）被视为错误。

     在 3.7 版更改: 样式中的空匹配相邻接时会被替换。

 -- 函数: re.subn (pattern, repl, string, count=0, flags=0)

     行为与 *note sub(): 483. 相同，但是返回一个元组 ‘(字符串, 替换次数
     )’.

     在 3.1 版更改: 增加了可选标记参数。

     在 3.5 版更改: 不匹配的组合替换为空字符串。

 -- 函数: re.escape (pattern)

     转义 `pattern' 中的特殊字符。如果你想对任意可能包含正则表达式元字符
     的文本字符串进行匹配，它就是有用的。比如

          >>> print(re.escape('http://www.python.org'))
          http://www\.python\.org

          >>> legal_chars = string.ascii_lowercase + string.digits + "!#$%&'*+-.^_`|~:"
          >>> print('[%s]+' % re.escape(legal_chars))
          [abcdefghijklmnopqrstuvwxyz0123456789!\#\$%\&'\*\+\-\.\^_`\|\~:]+

          >>> operators = ['+', '-', '*', '/', '**']
          >>> print('|'.join(map(re.escape, sorted(operators, reverse=True))))
          /|\-|\+|\*\*|\*

     这个函数不能被用于 *note sub(): 483. 和 *note subn(): 73d. 的替换字
     符串，只有反斜杠应该被转义。 例如:

          >>> digits_re = r'\d+'
          >>> sample = '/usr/sbin/sendmail - 0 errors, 12 warnings'
          >>> print(re.sub(digits_re, digits_re.replace('\\', r'\\'), sample))
          /usr/sbin/sendmail - \d+ errors, \d+ warnings

     在 3.3 版更改: ‘'_'’ 不再被转义。

     在 3.7 版更改: 只有在正则表达式中具有特殊含义的字符才会被转义。 因
     此， ‘'!'’, ‘'"'’, ‘'%'’, ‘"'"’, ‘','’, ‘'/'’, ‘':'’, ‘';'’, ‘'<'’,
     ‘'='’, ‘'>'’, ‘'@'’ 和 ‘"`"’ 将不再会被转义。

 -- 函数: re.purge ()

     清除正则表达式的缓存。

 -- 例外: re.error (msg, pattern=None, pos=None)

     ‘raise’ 一个例外。当传递到函数的字符串不是一个有效正则表达式的时候
     （比如，包含一个不匹配的括号）或者其他错误在编译时或匹配时产生。如
     果字符串不包含样式匹配，是不会被视为错误的。错误实例有以下附加属性
     ：

      -- 属性: msg

          未格式化的错误消息。

      -- 属性: pattern

          正则表达式的模式串。

      -- 属性: pos

          编译失败的 `pattern' 的位置索引（可以是 ‘None’ ）。

      -- 属性: lineno

          对应 `pos' (可以是 ‘None’) 的行号。

      -- 属性: colno

          对应 `pos' (可以是 ‘None’) 的列号。

     在 3.5 版更改: 增加了额外的属性。


File: python.info,  Node: 正则表达式对象 （正则对象）,  Next: 匹配对象,  Prev: 模块内容,  Up: re --- 正则表达式操作

5.6.2.3 正则表达式对象 （正则对象）
...................................

编译后的正则表达式对象支持以下方法和属性：

 -- 方法: Pattern.search (string[, pos[, endpos]])

     扫描整个 `string' 寻找第一个匹配的位置， 并返回一个相应的 *note
     匹配对象: 8a6.。如果没有匹配，就返回 ‘None’ ；注意它和零长度匹配是
     不同的。

     可选的第二个参数 `pos' 给出了字符串中开始搜索的位置索引；默认为
     ‘0’，它不完全等价于字符串切片； ‘'^'’ 样式字符匹配字符串真正的开头
     ，和换行符后面的第一个字符，但不会匹配索引规定开始的位置。

     可选参数 `endpos' 限定了字符串搜索的结束；它假定字符串长度到
     `endpos' ， 所以只有从 ‘pos’ 到 ‘endpos - 1’ 的字符会被匹配。如果
     `endpos' 小于 `pos'，就不会有匹配产生；另外，如果 `rx' 是一个编译后
     的正则对象， ‘rx.search(string, 0, 50)’ 等价于
     ‘rx.search(string[:50], 0)’。

          >>> pattern = re.compile("d")
          >>> pattern.search("dog")     # Match at index 0
          <re.Match object; span=(0, 1), match='d'>
          >>> pattern.search("dog", 1)  # No match; search doesn't include the "d"

 -- 方法: Pattern.match (string[, pos[, endpos]])

     如果 `string' 的 `开始位置' 能够找到这个正则样式的任意个匹配，就返
     回一个相应的 *note 匹配对象: 8a6.。如果不匹配，就返回 ‘None’ ；注意
     它与零长度匹配是不同的。

     可选参数 `pos' 和 `endpos' 与 *note search(): 176d. 含义相同。

          >>> pattern = re.compile("o")
          >>> pattern.match("dog")      # No match as "o" is not at the start of "dog".
          >>> pattern.match("dog", 1)   # Match as "o" is the 2nd character of "dog".
          <re.Match object; span=(1, 2), match='o'>

     如果你想定位匹配在 `string' 中的位置，使用 *note search(): 176d. 来
     替代（另参考 *note search() vs.  match(): 1771.）。

 -- 方法: Pattern.fullmatch (string[, pos[, endpos]])

     如果整个 `string' 匹配这个正则表达式，就返回一个相应的 *note
     匹配对象: 8a6. 。 否则就返回 ‘None’ ； 注意跟零长度匹配是不同的。

     可选参数 `pos' 和 `endpos' 与 *note search(): 176d. 含义相同。

          >>> pattern = re.compile("o[gh]")
          >>> pattern.fullmatch("dog")      # No match as "o" is not at the start of "dog".
          >>> pattern.fullmatch("ogre")     # No match as not the full string matches.
          >>> pattern.fullmatch("doggie", 1, 3)   # Matches within given limits.
          <re.Match object; span=(1, 3), match='og'>

     3.4 新版功能.

 -- 方法: Pattern.split (string, maxsplit=0)

     等价于 *note split(): 3d2. 函数，使用了编译后的样式。

 -- 方法: Pattern.findall (string[, pos[, endpos]])

     类似函数 *note findall(): 96b. ， 使用了编译后样式，但也可以接收可
     选参数 `pos' 和 `endpos' ，限制搜索范围，就像 *note search(): bba.。

 -- 方法: Pattern.finditer (string[, pos[, endpos]])

     类似函数 ‘finiter()’ ， 使用了编译后样式，但也可以接收可选参数
     `pos' 和 `endpos' ，限制搜索范围，就像 *note search(): bba.。

 -- 方法: Pattern.sub (repl, string, count=0)

     等价于 *note sub(): 483. 函数，使用了编译后的样式。

 -- 方法: Pattern.subn (repl, string, count=0)

     等价于 *note subn(): 73d. 函数，使用了编译后的样式。

 -- 属性: Pattern.flags

     正则匹配标记。这是可以传递给 *note compile(): 452. 的参数，任何
     ‘(?…)’ 内联标记，隐性标记比如 ‘UNICODE’ 的结合。

 -- 属性: Pattern.groups

     捕获到的模式串中组的数量。

 -- 属性: Pattern.groupindex

     映射由 ‘(?P<id>)’ 定义的命名符号组合和数字组合的字典。如果没有符号
     组，那字典就是空的。

 -- 属性: Pattern.pattern

     编译对象的原始样式字符串。

在 3.7 版更改: 添加 *note copy.copy(): 3d3. 和 *note copy.deepcopy():
3d4. 函数的支持。编译后的正则表达式对象被认为是原子性的。


File: python.info,  Node: 匹配对象,  Next: 正则表达式例子,  Prev: 正则表达式对象 （正则对象）,  Up: re --- 正则表达式操作

5.6.2.4 匹配对象
................

匹配对象总是有一个布尔值 ‘True’。如果没有匹配的话 *note match(): 176c. 和
*note search(): 176d. 返回 ‘None’ 所以你可以简单的用 ‘if’ 语句来判断是否
匹配

     match = re.search(pattern, string)
     if match:
         process(match)

匹配对象支持以下方法和属性：

 -- 方法: Match.expand (template)

     对 `template' 进行反斜杠转义替换并且返回，就像 *note sub(): 1779. 方
     法中一样。转义如同 ‘\n’ 被转换成合适的字符，数字引用(‘\1’, ‘\2’)和
     命名组合(‘\g<1>’, ‘\g<name>’) 替换为相应组合的内容。

     在 3.5 版更改: 不匹配的组合替换为空字符串。

 -- 方法: Match.group ([group1, ...])

     返回一个或者多个匹配的子组。如果只有一个参数，结果就是一个字符串，
     如果有多个参数，结果就是一个元组（每个参数对应一个项），如果没有参
     数，组1默认到0（整个匹配都被返回）。 如果一个组N 参数值为 0，相应的
     返回值就是整个匹配字符串；如果它是一个范围 [1..99]，结果就是相应的
     括号组字符串。如果一个组号是负数，或者大于样式中定义的组数，一个
     *note IndexError: e7d. 索引错误就 ‘raise’。如果一个组包含在样式的一
     部分，并被匹配多次，就返回最后一个匹配。:

          >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
          >>> m.group(0)       # The entire match
          'Isaac Newton'
          >>> m.group(1)       # The first parenthesized subgroup.
          'Isaac'
          >>> m.group(2)       # The second parenthesized subgroup.
          'Newton'
          >>> m.group(1, 2)    # Multiple arguments give us a tuple.
          ('Isaac', 'Newton')

     如果正则表达式使用了 ‘(?P<name>…)’ 语法， `groupN' 参数就也可能是命
     名组合的名字。如果一个字符串参数在样式中未定义为组合名，一个 *note
     IndexError: e7d. 就 ‘raise’。

     一个相对复杂的例子

          >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
          >>> m.group('first_name')
          'Malcolm'
          >>> m.group('last_name')
          'Reynolds'

     命名组合同样可以通过索引值引用

          >>> m.group(1)
          'Malcolm'
          >>> m.group(2)
          'Reynolds'

     如果一个组匹配成功多次，就只返回最后一个匹配

          >>> m = re.match(r"(..)+", "a1b2c3")  # Matches 3 times.
          >>> m.group(1)                        # Returns only the last match.
          'c3'

 -- 方法: Match.__getitem__ (g)

     这个等价于 ‘m.group(g)’。这允许更方便的引用一个匹配

          >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
          >>> m[0]       # The entire match
          'Isaac Newton'
          >>> m[1]       # The first parenthesized subgroup.
          'Isaac'
          >>> m[2]       # The second parenthesized subgroup.
          'Newton'

     3.6 新版功能.

 -- 方法: Match.groups (default=None)

     返回一个元组，包含所有匹配的子组，在样式中出现的从1到任意多的组合。
     `default' 参数用于不参与匹配的情况，默认为 ‘None’。

     例如

          >>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
          >>> m.groups()
          ('24', '1632')

     如果我们使小数点可选，那么不是所有的组都会参与到匹配当中。这些组合
     默认会返回一个 ‘None’ ，除非指定了 `default' 参数。

          >>> m = re.match(r"(\d+)\.?(\d+)?", "24")
          >>> m.groups()      # Second group defaults to None.
          ('24', None)
          >>> m.groups('0')   # Now, the second group defaults to '0'.
          ('24', '0')

 -- 方法: Match.groupdict (default=None)

     返回一个字典，包含了所有的 `命名' 子组。key就是组名。 `default' 参
     数用于不参与匹配的组合；默认为 ‘None’。 例如

          >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
          >>> m.groupdict()
          {'first_name': 'Malcolm', 'last_name': 'Reynolds'}

 -- 方法: Match.start ([group])
 -- 方法: Match.end ([group])

     返回 `group' 匹配到的字串的开始和结束标号。`group' 默认为0（意思是
     整个匹配的子串）。如果 `group' 存在，但未产生匹配，就返回 ‘-1’ 。对
     于一个匹配对象 `m'， 和一个未参与匹配的组 `g' ，组 `g' (等价于
     ‘m.group(g)’)产生的匹配是

          m.string[m.start(g):m.end(g)]

     注意 ‘m.start(group)’ 将会等于 ‘m.end(group)’ ，如果 `group' 匹配一
     个空字符串的话。比如，在 ‘m = re.search('b(c?)', 'cba')’ 之后，
     ‘m.start(0)’ 为 1, ‘m.end(0)’ 为 2, ‘m.start(1)’ 和 ‘m.end(1)’ 都是
     2, ‘m.start(2)’ raise 一个 *note IndexError: e7d. 例外。

     这个例子会从email地址中移除掉 `remove_this'

          >>> email = "tony@tiremove_thisger.net"
          >>> m = re.search("remove_this", email)
          >>> email[:m.start()] + email[m.end():]
          'tony@tiger.net'

 -- 方法: Match.span ([group])

     对于一个匹配 `m' ， 返回一个二元组 ‘(m.start(group), m.end(group))’
     。 注意如果 `group' 没有在这个匹配中，就返回 ‘(-1, -1)’ 。`group' 默
     认为0，就是整个匹配。

 -- 属性: Match.pos

     `pos' 的值，会传递给 *note search(): 176d. 或 *note match(): 176c.
     的方法 a *note 正则对象: 8a5. 。这个是正则引擎开始在字符串搜索一个
     匹配的索引位置。

 -- 属性: Match.endpos

     `endpos' 的值，会传递给 *note search(): 176d. 或 *note match():
     176c. 的方法 a *note 正则对象: 8a5. 。这个是正则引擎停止在字符串搜
     索一个匹配的索引位置。

 -- 属性: Match.lastindex

     捕获组的最后一个匹配的整数索引值，或者 ‘None’ 如果没有匹配产生的话
     。比如，对于字符串 ‘'ab'’，表达式 ‘(a)b’, ‘((a)(b))’, 和 ‘((ab))’ 将
     得到 ‘lastindex == 1’ ， 而 ‘(a)(b)’ 会得到 ‘lastindex == 2’ 。

 -- 属性: Match.lastgroup

     最后一个匹配的命名组名字，或者 ‘None’ 如果没有产生匹配的话。

 -- 属性: Match.re

     返回产生这个实例的 *note 正则对象: 8a5. ， 这个实例是由 正则对象的
     *note match(): 176c. 或 *note search(): 176d. 方法产生的。

 -- 属性: Match.string

     传递到 *note match(): 176c. 或 *note search(): 176d. 的字符串。

在 3.7 版更改: 添加了对 *note copy.copy(): 3d3. 和 *note
copy.deepcopy(): 3d4. 的支持。匹配对象被看作是原子性的。


File: python.info,  Node: 正则表达式例子,  Prev: 匹配对象,  Up: re --- 正则表达式操作

5.6.2.5 正则表达式例子
......................

* Menu:

* 检查对子::
* 模拟 scanf(): 模拟 scanf.
* search() vs. match(): search vs match.
* 制作一个电话本::
* 文字整理::
* 查找所有副词::
* 查找所有的副词及其位置::
* 原始字符串标记::
* 写一个词法分析器::


File: python.info,  Node: 检查对子,  Next: 模拟 scanf,  Up: 正则表达式例子

5.6.2.6 检查对子
................

在这个例子里，我们使用以下辅助函数来更好地显示匹配对象:

     def displaymatch(match):
         if match is None:
             return None
         return '<Match: %r, groups=%r>' % (match.group(), match.groups())

假设你在写一个扑克程序，一个玩家的一手牌为五个字符的串，每个字符表示一张
牌，"a" 就是 A, "k" K， "q" Q, "j" J, "t" 为 10, "2" 到 "9" 表示2 到 9。

要看给定的字符串是否有效，我们可以按照以下步骤

     >>> valid = re.compile(r"^[a2-9tjqk]{5}$")
     >>> displaymatch(valid.match("akt5q"))  # Valid.
     "<Match: 'akt5q', groups=()>"
     >>> displaymatch(valid.match("akt5e"))  # Invalid.
     >>> displaymatch(valid.match("akt"))    # Invalid.
     >>> displaymatch(valid.match("727ak"))  # Valid.
     "<Match: '727ak', groups=()>"

最后一手牌，‘"727ak"’ ，包含了一个对子，或者两张同样数值的牌。要用正则表
达式匹配它，应该使用向后引用如下

     >>> pair = re.compile(r".*(.).*\1")
     >>> displaymatch(pair.match("717ak"))     # Pair of 7s.
     "<Match: '717', groups=('7',)>"
     >>> displaymatch(pair.match("718ak"))     # No pairs.
     >>> displaymatch(pair.match("354aa"))     # Pair of aces.
     "<Match: '354aa', groups=('a',)>"

要找出对子由什么牌组成，开发者可以按照下面的方式来使用匹配对象的 *note
group(): 1781. 方法:

     >>> pair = re.compile(r".*(.).*\1")
     >>> pair.match("717ak").group(1)
     '7'

     # Error because re.match() returns None, which doesn't have a group() method:
     >>> pair.match("718ak").group(1)
     Traceback (most recent call last):
       File "<pyshell#23>", line 1, in <module>
         re.match(r".*(.).*\1", "718ak").group(1)
     AttributeError: 'NoneType' object has no attribute 'group'

     >>> pair.match("354aa").group(1)
     'a'


File: python.info,  Node: 模拟 scanf,  Next: search vs match,  Prev: 检查对子,  Up: 正则表达式例子

5.6.2.7 模拟 scanf()
....................

Python 目前没有一个类似c函数 ‘scanf()’ 的替代品。正则表达式通常比
‘scanf()’ 格式字符串要更强大一些，但也带来更多复杂性。下面的表格提供了
‘scanf()’ 格式符和正则表达式大致相同的映射。

‘scanf()’ 格式符                     正则表达式
                                     
---------------------------------------------------------------------------------------
                                     
‘%c’                                 ‘.’
                                     
                                     
‘%5c’                                ‘.{5}’
                                     
                                     
‘%d’                                 ‘[-+]?\d+’
                                     
                                     
‘%e’, ‘%E’, ‘%f’, ‘%g’               ‘[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?’
                                     
                                     
‘%i’                                 ‘[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)’
                                     
                                     
‘%o’                                 ‘[-+]?[0-7]+’
                                     
                                     
‘%s’                                 ‘\S+’
                                     
                                     
‘%u’                                 ‘\d+’
                                     
                                     
‘%x’, ‘%X’                           ‘[-+]?(0[xX])?[\dA-Fa-f]+’
                                     

从文件名和数字提取字符串

     /usr/sbin/sendmail - 0 errors, 4 warnings

你可以使用 ‘scanf()’ 格式化

     %s - %d errors, %d warnings

等价的正则表达式是：

     (\S+) - (\d+) errors, (\d+) warnings


File: python.info,  Node: search vs match,  Next: 制作一个电话本,  Prev: 模拟 scanf,  Up: 正则表达式例子

5.6.2.8 search() vs. match()
............................

Python 提供了两种不同的操作：基于 *note re.match(): bbb. 检查字符串开头
，或者 *note re.search(): bba. 检查字符串的任意位置（默认Perl中的行为）
。

例如

     >>> re.match("c", "abcdef")    # No match
     >>> re.search("c", "abcdef")   # Match
     <re.Match object; span=(2, 3), match='c'>

在 *note search(): bba. 中，可以用 ‘'^'’ 作为开始来限制匹配到字符串的首
位

     >>> re.match("c", "abcdef")    # No match
     >>> re.search("^c", "abcdef")  # No match
     >>> re.search("^a", "abcdef")  # Match
     <re.Match object; span=(0, 1), match='a'>

注意 *note MULTILINE: 1762. 多行模式中函数 *note match(): bbb. 只匹配字
符串的开始，但使用 *note search(): bba. 和以 ‘'^'’ 开始的正则表达式会匹
配每行的开始

     >>> re.match('X', 'A\nB\nX', re.MULTILINE)  # No match
     >>> re.search('^X', 'A\nB\nX', re.MULTILINE)  # Match
     <re.Match object; span=(4, 5), match='X'>


File: python.info,  Node: 制作一个电话本,  Next: 文字整理,  Prev: search vs match,  Up: 正则表达式例子

5.6.2.9 制作一个电话本
......................

*note split(): 3d2. 将字符串用参数传递的样式分隔开。这个方法对于转换文本
数据到易读而且容易修改的数据结构，是很有用的，如下面的例子证明。

首先，这里是输入。 它通常来自一个文件，这里我们使用三重引号字符串语法

     >>> text = """Ross McFluff: 834.345.1254 155 Elm Street
     ...
     ... Ronald Heathmore: 892.345.3428 436 Finley Avenue
     ... Frank Burger: 925.541.7625 662 South Dogwood Way
     ...
     ...
     ... Heather Albrecht: 548.326.4584 919 Park Place"""

条目用一个或者多个换行符分开。现在我们将字符串转换为一个列表，每个非空行
都有一个条目:

     >>> entries = re.split("\n+", text)
     >>> entries
     ['Ross McFluff: 834.345.1254 155 Elm Street',
     'Ronald Heathmore: 892.345.3428 436 Finley Avenue',
     'Frank Burger: 925.541.7625 662 South Dogwood Way',
     'Heather Albrecht: 548.326.4584 919 Park Place']

最终，将每个条目分割为一个由名字、姓氏、电话号码和地址组成的列表。我们为
*note split(): 3d2. 使用了 ‘maxsplit’ 形参，因为地址中包含有被我们作为分
割模式的空格符:

     >>> [re.split(":? ", entry, 3) for entry in entries]
     [['Ross', 'McFluff', '834.345.1254', '155 Elm Street'],
     ['Ronald', 'Heathmore', '892.345.3428', '436 Finley Avenue'],
     ['Frank', 'Burger', '925.541.7625', '662 South Dogwood Way'],
     ['Heather', 'Albrecht', '548.326.4584', '919 Park Place']]

‘:?’ 样式匹配姓后面的冒号，因此它不出现在结果列表中。如果 ‘maxsplit’ 设
置为 ‘4’ ，我们还可以从地址中获取到房间号:

     >>> [re.split(":? ", entry, 4) for entry in entries]
     [['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'],
     ['Ronald', 'Heathmore', '892.345.3428', '436', 'Finley Avenue'],
     ['Frank', 'Burger', '925.541.7625', '662', 'South Dogwood Way'],
     ['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']]


File: python.info,  Node: 文字整理,  Next: 查找所有副词,  Prev: 制作一个电话本,  Up: 正则表达式例子

5.6.2.10 文字整理
.................

*note sub(): 483. 替换字符串中出现的样式的每一个实例。这个例子证明了使用
*note sub(): 483. 来整理文字，或者随机化每个字符的位置，除了首位和末尾字
符

     >>> def repl(m):
     ...     inner_word = list(m.group(2))
     ...     random.shuffle(inner_word)
     ...     return m.group(1) + "".join(inner_word) + m.group(3)
     >>> text = "Professor Abdolmalek, please report your absences promptly."
     >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
     'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
     >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
     'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.'


File: python.info,  Node: 查找所有副词,  Next: 查找所有的副词及其位置,  Prev: 文字整理,  Up: 正则表达式例子

5.6.2.11 查找所有副词
.....................

*note findall(): 96b. 匹配样式 `所有' 的出现，不仅是像 *note search():
bba. 中的第一个匹配。比如，如果一个作者希望找到文字中的所有副词，他可能
会按照以下方法用 *note findall(): 96b.

     >>> text = "He was carefully disguised but captured quickly by police."
     >>> re.findall(r"\w+ly", text)
     ['carefully', 'quickly']


File: python.info,  Node: 查找所有的副词及其位置,  Next: 原始字符串标记,  Prev: 查找所有副词,  Up: 正则表达式例子

5.6.2.12 查找所有的副词及其位置
...............................

如果需要匹配样式的更多信息， *note finditer(): 1772. 可以起到作用，它提
供了 *note 匹配对象: 8a6. 作为返回值，而不是字符串。继续上面的例子，如果
一个作者希望找到所有副词和它的位置，可以按照下面方法使用 *note
finditer(): 1772.

     >>> text = "He was carefully disguised but captured quickly by police."
     >>> for m in re.finditer(r"\w+ly", text):
     ...     print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0)))
     07-16: carefully
     40-47: quickly


File: python.info,  Node: 原始字符串标记,  Next: 写一个词法分析器,  Prev: 查找所有的副词及其位置,  Up: 正则表达式例子

5.6.2.13 原始字符串标记
.......................

原始字符串记法 (‘r"text"’) 保持正则表达式正常。否则，每个正则式里的反斜
杠(‘'\'’) 都必须前缀一个反斜杠来转义。比如，下面两行代码功能就是完全一致
的

     >>> re.match(r"\W(.)\1\W", " ff ")
     <re.Match object; span=(0, 4), match=' ff '>
     >>> re.match("\\W(.)\\1\\W", " ff ")
     <re.Match object; span=(0, 4), match=' ff '>

当需要匹配一个字符反斜杠，它必须在正则表达式中转义。在原始字符串记法，就
是 ‘r"\\"’。否则就必须用 ‘"\\\\"’，来表示同样的意思

     >>> re.match(r"\\", r"\\")
     <re.Match object; span=(0, 1), match='\\'>
     >>> re.match("\\\\", r"\\")
     <re.Match object; span=(0, 1), match='\\'>


File: python.info,  Node: 写一个词法分析器,  Prev: 原始字符串标记,  Up: 正则表达式例子

5.6.2.14 写一个词法分析器
.........................

一个 词法器或词法分析器(1) 分析字符串，并分类成目录组。 这是写一个编译器
或解释器的第一步。

文字目录是由正则表达式指定的。这个技术是通过将这些样式合并为一个主正则式
，并且循环匹配来实现的

     from typing import NamedTuple
     import re

     class Token(NamedTuple):
         type: str
         value: str
         line: int
         column: int

     def tokenize(code):
         keywords = {'IF', 'THEN', 'ENDIF', 'FOR', 'NEXT', 'GOSUB', 'RETURN'}
         token_specification = [
             ('NUMBER',   r'\d+(\.\d*)?'),  # Integer or decimal number
             ('ASSIGN',   r':='),           # Assignment operator
             ('END',      r';'),            # Statement terminator
             ('ID',       r'[A-Za-z]+'),    # Identifiers
             ('OP',       r'[+\-*/]'),      # Arithmetic operators
             ('NEWLINE',  r'\n'),           # Line endings
             ('SKIP',     r'[ \t]+'),       # Skip over spaces and tabs
             ('MISMATCH', r'.'),            # Any other character
         ]
         tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)
         line_num = 1
         line_start = 0
         for mo in re.finditer(tok_regex, code):
             kind = mo.lastgroup
             value = mo.group()
             column = mo.start() - line_start
             if kind == 'NUMBER':
                 value = float(value) if '.' in value else int(value)
             elif kind == 'ID' and value in keywords:
                 kind = value
             elif kind == 'NEWLINE':
                 line_start = mo.end()
                 line_num += 1
                 continue
             elif kind == 'SKIP':
                 continue
             elif kind == 'MISMATCH':
                 raise RuntimeError(f'{value!r} unexpected on line {line_num}')
             yield Token(kind, value, line_num, column)

     statements = '''
         IF quantity THEN
             total := total + price * quantity;
             tax := price * 0.05;
         ENDIF;
     '''

     for token in tokenize(statements):
         print(token)

该词法器产生以下的输出

     Token(type='IF', value='IF', line=2, column=4)
     Token(type='ID', value='quantity', line=2, column=7)
     Token(type='THEN', value='THEN', line=2, column=16)
     Token(type='ID', value='total', line=3, column=8)
     Token(type='ASSIGN', value=':=', line=3, column=14)
     Token(type='ID', value='total', line=3, column=17)
     Token(type='OP', value='+', line=3, column=23)
     Token(type='ID', value='price', line=3, column=25)
     Token(type='OP', value='*', line=3, column=31)
     Token(type='ID', value='quantity', line=3, column=33)
     Token(type='END', value=';', line=3, column=41)
     Token(type='ID', value='tax', line=4, column=8)
     Token(type='ASSIGN', value=':=', line=4, column=12)
     Token(type='ID', value='price', line=4, column=15)
     Token(type='OP', value='*', line=4, column=21)
     Token(type='NUMBER', value=0.05, line=4, column=23)
     Token(type='END', value=';', line=4, column=27)
     Token(type='ENDIF', value='ENDIF', line=5, column=4)
     Token(type='END', value=';', line=5, column=9)

(Frie09) Friedl, Jeffrey.  Mastering Regular Expressions.  3rd ed.,
O’Reilly Media, 2009. 该书的第三版不再包含 Python，但第一版极详细地覆盖
了正则表达式模式串的编写。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Lexical_analysis


File: python.info,  Node: difflib --- 计算差异的辅助工具,  Next: textwrap --- 文本自动换行与填充,  Prev: re --- 正则表达式操作,  Up: 文本处理服务

5.6.3 ‘difflib’ — 计算差异的辅助工具
------------------------------------

`源代码:' Lib/difflib.py(1)

__________________________________________________________________

此模块提供用于比较序列的类和函数。 例如，它可被用于比较文件，并可产生多
种格式的不同文件差异信息，包括 HTML 和上下文以及统一的 diff 数据。 有关
比较目录和文件，另请参阅 *note filecmp: 7f. 模块。

 -- 类: difflib.SequenceMatcher

     这是一个灵活的类，可用于比较任何类型的序列对，只要序列元素为 *note
     hashable: 1439. 对象。 其基本算法要早于由 Ratcliff 和 Obershelp 于
     1980 年代末期发表并以“格式塔模式匹配”的夸张名称命名的算法，并且更加
     有趣一些。 其思路是找到不包含“垃圾”元素的最长连续匹配子序列；所谓
     “垃圾”元素是指其在某种意义上没有价值，例如空白行或空白符。 （处理垃
     圾元素是对 Ratcliff 和 Obershelp 算法的一个扩展。） 然后同样的思路
     将递归地应用于匹配序列的左右序列片段。 这并不能产生最小编辑序列，但
     确实能产生在人们看来“正确”的匹配。

     `耗时:' 基本 Ratcliff-Obershelp 算法在最坏情况下为立方时间而在一般
     情况下为平方时间。 *note SequenceMatcher: 957. 在最坏情况下为平方时
     间而在一般情况下的行为受到序列中有多少相同元素这一因素的微妙影响；
     在最佳情况下则为线性时间。

     `自动垃圾启发式计算:' *note SequenceMatcher: 957. 支持使用启发式计
     算来自动将特定序列项视为垃圾。 这种启发式计算会统计每个单独项在序列
     中出现的次数。 如果某一项（在第一项之后）的重复次数超过序列长度的
     1% 并且序列长度至少有 200 项，该项会被标记为“热门”并被视为序列匹配
     中的垃圾。 这种启发式计算可以通过在创建 *note SequenceMatcher: 957.
     时将 ‘autojunk’ 参数设为 ‘False’ 来关闭。

     3.2 新版功能: `autojunk' 形参。

 -- 类: difflib.Differ

     这个类的作用是比较由文本行组成的序列，并产生可供人阅读的差异或增量
     信息。 Differ 统一使用 *note SequenceMatcher: 957. 来完成行序列的比
     较以及相似（接近匹配）行内部字符序列的比较。

     *note Differ: 179a. 增量的每一行均以双字母代码打头：

     双字母代码     含义
                    
     ---------------------------------------------------------------
                    
     ‘'- '’         行为序列 1 所独有
                    
                    
     ‘'+ '’         行为序列 2 所独有
                    
                    
     ‘' '’          行在两序列中相同
                    
                    
     ‘'? '’         行不存在于任一输入序列
                    

     以 ’‘?’’ 打头的行尝试将视线引至行以外而不存在于任一输入序列的差异。
     如果序列包含制表符则这些行可能会令人感到迷惑。

 -- 类: difflib.HtmlDiff

     这个类可用于创建 HTML 表格（或包含表格的完整 HTML 文件）以并排地逐
     行显示文本比较，行间与行外的更改将突出显示。 此表格可以基于完全或上
     下文差异模式来生成。

     这个类的构造函数：

      -- 方法: __init__ (tabsize=8, wrapcolumn=None, linejunk=None,
               charjunk=IS_CHARACTER_JUNK)

          初始化 *note HtmlDiff: 179b. 的实例。

          `tabsize' 是一个可选关键字参数，指定制表位的间隔，默认值为
          ‘8’。

          `wrapcolumn' 是一个可选关键字参数，指定行文本自动打断并换行的
          列位置，默认值为 ‘None’ 表示不自动换行。

          `linejunk' 和 `charjunk' 均是可选关键字参数，会传入 *note
          ndiff(): 179d. (被 *note HtmlDiff: 179b. 用来生成并排显示的
          HTML 差异)。 请参阅 *note ndiff(): 179d. 文档了解参数默认值及
          其说明。

     下列是公开的方法

      -- 方法: make_file (fromlines, tolines, fromdesc='', todesc='',
               context=False, numlines=5, *, charset='utf-8')

          比较 `fromlines' 和 `tolines' (字符串列表) 并返回一个字符串，
          表示一个完整 HTML 文件，其中包含各行差异的表格，行间与行外的更
          改将突出显示。

          `fromdesc' 和 `todesc' 均是可选关键字参数，指定来源/目标文件的
          列标题字符串（默认均为空白字符串）。

          `context' 和 `numlines' 均是可选关键字参数。 当只要显示上下文
          差异时就将 `context' 设为 ‘True’，否则默认值 ‘False’ 为显示完
          整文件。 `numlines' 默认为 ‘5’。 当 `context' 为 ‘True’ 时
          `numlines' 将控制围绕突出显示差异部分的上下文行数。 当
          `context' 为 ‘False’ 时 `numlines' 将控制在使用 "next" 超链接
          时突出显示差异部分之前所显示的行数（设为零则会导致 "next" 超链
          接将下一个突出显示差异部分放在浏览器顶端，不添加任何前导上下文
          ）。

               注解: `fromdesc' 和 `todesc' 会被当作未转义的 HTML 来解读
               ，当接收不可信来源的输入时应该适当地进行转义。

          在 3.5 版更改: 增加了 `charset' 关键字参数。 HTML 文档的默认字
          符集从 ‘'ISO-8859-1'’ 更改为 ‘'utf-8'’。

      -- 方法: make_table (fromlines, tolines, fromdesc='', todesc='',
               context=False, numlines=5)

          比较 `fromlines' 和 `tolines' (字符串列表) 并返回一个字符串，
          表示一个包含各行差异的完整 HTML 表格，行间与行外的更改将突出显
          示。

          此方法的参数与 *note make_file(): 6d2. 方法的相同。

     ‘Tools/scripts/diff.py’ 是这个类的命令行前端，其中包含一个很好的使
     用示例。

 -- 函数: difflib.context_diff (a, b, fromfile='', tofile='',
          fromfiledate='', tofiledate='', n=3, lineterm='\n')

     比较 `a' 和 `b' (字符串列表)；返回上下文差异格式的增量信息 (一个产
     生增量行的 *note generator: 9aa.)。

     所谓上下文差异是一种只显示有更改的行再加几个上下文行的紧凑形式。 更
     改被显示为之前/之后的样式。 上下文行数由 `n' 设定，默认为三行。

     默认情况下，差异控制行（以 ‘***’ or ‘---’ 表示）是通过末尾换行符来
     创建的。 这样做的好处是从 *note io.IOBase.readlines(): 17a0. 创建的
     输入将得到适用于 *note io.IOBase.writelines(): 17a1. 的差异信息，因
     为输入和输出都带有末尾换行符。

     对于没有末尾换行符的输入，应将 `lineterm' 参数设为 ‘""’，这样输出内
     容将统一不带换行符。

     上下文差异格式通常带有一个记录文件名和修改时间的标头。 这些信息的部
     分或全部可以使用字符串 `fromfile', `tofile', `fromfiledate' 和
     `tofiledate' 来指定。 修改时间通常以 ISO 8601 格式表示。 如果未指定
     ，这些字符串默认为空。

          >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
          >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
          >>> sys.stdout.writelines(context_diff(s1, s2, fromfile='before.py', tofile='after.py'))
          *** before.py
          --- after.py
          ***************
          *** 1,4 ****
          ! bacon
          ! eggs
          ! ham
            guido
          --- 1,4 ----
          ! python
          ! eggy
          ! hamster
            guido

     请参阅 *note difflib 的命令行接口: 17a2. 获取更详细的示例。

 -- 函数: difflib.get_close_matches (word, possibilities, n=3,
          cutoff=0.6)

     返回由最佳“近似”匹配构成的列表。 `word' 为一个指定目标近似匹配的序
     列（通常为字符串），`possibilities' 为一个由用于匹配 `word' 的序列
     构成的列表（通常为字符串列表）。

     可选参数 `n' (默认为 ‘3’) 指定最多返回多少个近似匹配； `n' 必须大于
     ‘0’.

     可选参数 `cutoff' (默认为 ‘0.6’) 是一个 [0, 1] 范围内的浮点数。 与
     `word' 相似度得分未达到该值的候选匹配将被忽略。

     候选匹配中（不超过 `n' 个）的最佳匹配将以列表形式返回，按相似度得分
     排序，最相似的排在最前面。

          >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
          ['apple', 'ape']
          >>> import keyword
          >>> get_close_matches('wheel', keyword.kwlist)
          ['while']
          >>> get_close_matches('pineapple', keyword.kwlist)
          []
          >>> get_close_matches('accept', keyword.kwlist)
          ['except']

 -- 函数: difflib.ndiff (a, b, linejunk=None,
          charjunk=IS_CHARACTER_JUNK)

     比较 `a' 和 `b' (字符串列表)；返回 *note Differ: 179a. 形式的增量信
     息 (一个产生增量行的 *note generator: 9aa.)。

     可选关键字形参 `linejunk' 和 `charjunk' 均为过滤函数 (或为 ‘None’)：

     `linejunk': 此函数接受单个字符串参数，如果其为垃圾字符串则返回真值
     ，否则返回假值。 默认为 ‘None’。 此外还有一个模块层级的函数 *note
     IS_LINE_JUNK(): 17a4.，它会过滤掉没有可见字符的行，除非该行添加了至
     多一个井号符 (‘'#'’) – 但是下层的 *note SequenceMatcher: 957. 类会
     动态分析哪些行的重复频繁到足以形成噪音，这通常会比使用此函数的效果
     更好。

     `charjunk': 此函数接受一个字符（长度为 1 的字符串)，如果其为垃圾字
     符则返回真值，否则返回假值。 默认为模块层级的函数 *note
     IS_CHARACTER_JUNK(): 17a5.，它会过滤掉空白字符（空格符或制表符；但
     包含换行符可不是个好主意！）。

     ‘Tools/scripts/ndiff.py’ 是这个函数的命令行前端。

          >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
          ...              'ore\ntree\nemu\n'.splitlines(keepends=True))
          >>> print(''.join(diff), end="")
          - one
          ?  ^
          + ore
          ?  ^
          - two
          - three
          ?  -
          + tree
          + emu

 -- 函数: difflib.restore (sequence, which)

     返回两个序列中产生增量的那一个。

     给出一个由 *note Differ.compare(): 17a7. 或 *note ndiff(): 179d. 产
     生的 `序列'，提取出来自文件 1 或 2 (`which' 形参) 的行，去除行前缀
     。

     示例:

          >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
          ...              'ore\ntree\nemu\n'.splitlines(keepends=True))
          >>> diff = list(diff) # materialize the generated delta into a list
          >>> print(''.join(restore(diff, 1)), end="")
          one
          two
          three
          >>> print(''.join(restore(diff, 2)), end="")
          ore
          tree
          emu

 -- 函数: difflib.unified_diff (a, b, fromfile='', tofile='',
          fromfiledate='', tofiledate='', n=3, lineterm='\n')

     比较 `a' 和 `b' (字符串列表)；返回统一差异格式的增量信息 (一个产生
     增量行的 *note generator: 9aa.)。

     所以统一差异是一种只显示有更改的行再加几个上下文行的紧凑形式。 更改
     被显示为内联的样式（而不是分开的之前/之后文本块）。 上下文行数由
     `n' 设定，默认为三行。

     默认情况下，差异控制行 (以 ‘---’, ‘+++’ 或 ‘@@’ 表示) 是通过末尾换
     行符来创建的。 这样做的好处是从 *note io.IOBase.readlines(): 17a0.
     创建的输入将得到适用于 *note io.IOBase.writelines(): 17a1. 的差异信
     息，因为输入和输出都带有末尾换行符。

     对于没有末尾换行符的输入，应将 `lineterm' 参数设为 ‘""’，这样输出内
     容将统一不带换行符。

     上下文差异格式通常带有一个记录文件名和修改时间的标头。 这些信息的部
     分或全部可以使用字符串 `fromfile', `tofile', `fromfiledate' 和
     `tofiledate' 来指定。 修改时间通常以 ISO 8601 格式表示。 如果未指定
     ，这些字符串默认为空。

          >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
          >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
          >>> sys.stdout.writelines(unified_diff(s1, s2, fromfile='before.py', tofile='after.py'))
          --- before.py
          +++ after.py
          @@ -1,4 +1,4 @@
          -bacon
          -eggs
          -ham
          +python
          +eggy
          +hamster
           guido

     请参阅 *note difflib 的命令行接口: 17a2. 获取更详细的示例。

 -- 函数: difflib.diff_bytes (dfunc, a, b, fromfile=b'', tofile=b'',
          fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n')

     使用 `dfunc' 比较 `a' 和 `b' (字节串对象列表)；产生以 `dfunc' 所返
     回格式表示的差异行列表（也是字节串）。 `dfunc' 必须是可调用对象，通
     常为 *note unified_diff(): 17a8. 或 *note context_diff(): 179f.。

     允许你比较编码未知或不一致的数据。 除 `n' 之外的所有输入都必须为字
     节串对象而非字符串。 作用方式为无损地将所有输入 (除 `n' 之外) 转换
     为字符串，并调用 ‘dfunc(a, b, fromfile, tofile, fromfiledate,
     tofiledate, n, lineterm)’。 `dfunc' 的输出会被随即转换回字节串，这
     样你所得到的增量行将具有与 `a' 和 `b' 相同的未知/不一致编码。

     3.5 新版功能.

 -- 函数: difflib.IS_LINE_JUNK (line)

     对于可忽略的行返回 ‘True’。 如果 `line' 为空行或只包含单个 ‘'#'’ 则
     `line' 行就是可忽略的，否则就是不可忽略的。 此函数被用作较旧版本
     *note ndiff(): 179d. 中 `linejunk' 形参的默认值。

 -- 函数: difflib.IS_CHARACTER_JUNK (ch)

     对于可忽略的字符返回 ‘True’。 字符 `ch' 如果为空格符或制表符则 `ch'
     就是可忽略的，否则就是不可忽略的。 此函数被用作 *note ndiff():
     179d. 中 `charjunk' 形参的默认值。

参见
....

模式匹配：格式塔方法(2)

     John W. Ratcliff 和 D. E. Metzener 对于一种类似算法的讨论。 此文于
     1988 年 7 月发表于 Dr.  Dobb’s Journal(3)。

* Menu:

* SequenceMatcher 对象::
* SequenceMatcher 的示例::
* Differ 对象::
* Differ 示例::
* difflib 的命令行接口::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/difflib.py

   (2) 
http://www.drdobbs.com/database/pattern-matching-the-gestalt-approach/184407970

   (3) http://www.drdobbs.com/


File: python.info,  Node: SequenceMatcher 对象,  Next: SequenceMatcher 的示例,  Up: difflib --- 计算差异的辅助工具

5.6.3.1 SequenceMatcher 对象
............................

*note SequenceMatcher: 957. 类具有这样的构造器：

 -- 类: difflib.SequenceMatcher (isjunk=None, a='', b='', autojunk=True)

     可选参数 `isjunk' 必须为 ‘None’ (默认值) 或为接受一个序列元素并当且
     仅当其为应忽略的“垃圾”元素时返回真值的单参数函数。 传入 ‘None’ 作为
     `isjunk' 的值就相当于传入 ‘lambda x: False’；也就是说不忽略任何值。
     例如，传入:

          lambda x: x in " \t"

     如果你以字符序列的形式对行进行比较，并且不希望区分空格符或硬制表符
     。

     可选参数 `a' 和 `b' 为要比较的序列；两者默认为空字符串。 两个序列的
     元素都必须为 *note hashable: 1439.。

     可选参数 `autojunk' 可用于启用自动垃圾启发式计算。

     3.2 新版功能: `autojunk' 形参。

     SequenceMatcher 对象接受三个数据属性: `bjunk' 是 `b' 当中 `isjunk'
     为 ‘True’ 的元素集合；`bpopular' 是被启发式计算（如果其未被禁用）视
     为热门候选的非垃圾元素集合；`b2j' 是将 `b' 当中剩余元素映射到一个它
     们出现位置列表的字典。 所有三个数据属性将在 `b' 通过 *note
     set_seqs(): 17ab. 或 *note set_seq2(): 17ac. 重置时被重置。

     3.2 新版功能: `bjunk' 和 `bpopular' 属性。

     *note SequenceMatcher: 957. 对象具有以下方法：

      -- 方法: set_seqs (a, b)

          设置要比较的两个序列。

     *note SequenceMatcher: 957. 计算并缓存有关第二个序列的详细信息，这
     样如果你想要将一个序列与多个序列进行比较，可使用 *note set_seq2():
     17ac. 一次性地设置该常用序列并重复地对每个其他序列各调用一次 *note
     set_seq1(): 17ad.。

      -- 方法: set_seq1 (a)

          设置要比较的第一个序列。 要比较的第二个序列不会改变。

      -- 方法: set_seq2 (b)

          设置要比较的第二个序列。 要比较的第一个序列不会改变。

      -- 方法: find_longest_match (alo, ahi, blo, bhi)

          找出 ‘a[alo:ahi]’ 和 ‘b[blo:bhi]’ 中的最长匹配块。

          如果 `isjunk' 被省略或为 ‘None’，*note find_longest_match():
          17ae. 将返回 ‘(i, j, k)’ 使得 ‘a[i:i+k]’ 等于 ‘b[j:j+k]’，其中
          ‘alo <= i <= i+k <= ahi’ 并且 ‘blo <= j <= j+k <= bhi’。 对于
          所有满足这些条件的 ‘(i', j', k')’，如果 ‘i == i'’, ‘j <= j'’ 也
          被满足，则附加条件 ‘k >= k'’, ‘i <= i'’。 换句话说，对于所有最
          长匹配块，返回在 `a' 当中最先出现的一个，而对于在 `a' 当中最先
          出现的所有最长匹配块，则返回在 `b' 当中最先出现的一个。

               >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
               >>> s.find_longest_match(0, 5, 0, 9)
               Match(a=0, b=4, size=5)

          如果提供了 `isjunk'，将按上述规则确定第一个最长匹配块，但额外
          附加不允许块内出现垃圾元素的限制。 然后将通过（仅）匹配两边的
          垃圾元素来尽可能地扩展该块。 这样结果块绝对不会匹配垃圾元素，
          除非同样的垃圾元素正好与有意义的匹配相邻。

          这是与之前相同的例子，但是将空格符视为垃圾。 这将防止 ‘'
          abcd'’ 直接与第二个序列末尾的 ‘' abcd'’ 相匹配。 而只可以匹配
          ‘'abcd'’，并且是匹配第二个序列最左边的 ‘'abcd'’：

               >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
               >>> s.find_longest_match(0, 5, 0, 9)
               Match(a=1, b=0, size=4)

          如果未找到匹配块，此方法将返回 ‘(alo, blo, 0)’。

          此方法将返回一个 *note named tuple: aab. ‘Match(a, b, size)’。

      -- 方法: get_matching_blocks ()

          返回描述非重叠匹配子序列的三元组列表。 每个三元组的形式为 ‘(i,
          j, n)’，其含义为 ‘a[i:i+n] == b[j:j+n]’。 这些三元组按 `i' 和
          `j' 单调递增排列。

          最后一个三元组用于占位，其值为 ‘(len(a), len(b), 0)’。 它是唯
          一 ‘n == 0’ 的三元组。 如果 ‘(i, j, n)’ 和 ‘(i', j', n')’ 是在
          列表中相邻的三元组，且后者不是列表中的最后一个三元组，则 ‘i+n
          < i'’ 或 ‘j+n < j'’；换句话说，相邻的三元组总是描述非相邻的相
          等块。

               >>> s = SequenceMatcher(None, "abxcd", "abcd")
               >>> s.get_matching_blocks()
               [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]

      -- 方法: get_opcodes ()

          返回描述如何将 `a' 变为 `b' 的 5 元组列表，每个元组的形式为
          ‘(tag, i1, i2, j1, j2)’。 在第一个元组中 ‘i1 == j1 == 0’，而在
          其余的元组中 `i1' 等于前一个元组的 `i2'，并且 `j1' 也等于前一
          个元组的 `j2'。

          `tag' 值为字符串，其含义如下：

          值                  含义
                              
          ----------------------------------------------------------------------
                              
          ‘'replace'’         ‘a[i1:i2]’ 应由 ‘b[j1:j2]’ 替换。
                              
                              
          ‘'delete'’          ‘a[i1:i2]’ 应被删除。 请注意在此情况下 ‘j1 ==
                              j2’。
                              
                              
          ‘'insert'’          ‘b[j1:j2]’ 应插入到 ‘a[i1:i1]’。 请注意在此情况
                              下 ‘i1 == i2’。
                              
                              
          ‘'equal'’           ‘a[i1:i2] == b[j1:j2]’ (两个子序列相同)。
                              

          例如

               >>> a = "qabxcd"
               >>> b = "abycdf"
               >>> s = SequenceMatcher(None, a, b)
               >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
               ...     print('{:7}   a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format(
               ...         tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2]))
               delete    a[0:1] --> b[0:0]      'q' --> ''
               equal     a[1:3] --> b[0:2]     'ab' --> 'ab'
               replace   a[3:4] --> b[2:3]      'x' --> 'y'
               equal     a[4:6] --> b[3:5]     'cd' --> 'cd'
               insert    a[6:6] --> b[5:6]       '' --> 'f'

      -- 方法: get_grouped_opcodes (n=3)

          返回一个带有最多 `n' 行上下文的分组的 *note generator: 9aa.。

          从 *note get_opcodes(): 17b0. 所返回的组开始，此方法会拆分出较
          小的更改簇并消除没有更改的间隔区域。

          这些分组以与 *note get_opcodes(): 17b0. 相同的格式返回。

      -- 方法: ratio ()

          返回一个取值范围 [0, 1] 的浮点数作为序列相似性度量。

          其中 T 是两个序列中元素的总数量，M 是匹配的数量，即 2.0*M / T。
          请注意如果两个序列完全相同则该值为 ‘1.0’，如果两者完全不同则为
          ‘0.0’。

          如果 *note get_matching_blocks(): 17af. 或 *note
          get_opcodes(): 17b0. 尚未被调用则此方法运算消耗较大，在此情况
          下你可能需要先调用 *note quick_ratio(): 17b3. 或 *note
          real_quick_ratio(): 17b4. 来获取一个上界。

               注解: 注意: *note ratio(): 17b2. 调用的结果可能会取决于参
               数的顺序。 例如:

                    >>> SequenceMatcher(None, 'tide', 'diet').ratio()
                    0.25
                    >>> SequenceMatcher(None, 'diet', 'tide').ratio()
                    0.5

      -- 方法: quick_ratio ()

          相对快速地返回一个 *note ratio(): 17b2. 的上界。

      -- 方法: real_quick_ratio ()

          非常快速地返回一个 *note ratio(): 17b2. 的上界。

这三个返回匹配部分占字符总数的比率的方法可能由于不同的近似级别而给出不一
样的结果，但是 ‘quick_ratio()’ 和 ‘real_quick_ratio()’ 总是会至少与
‘ratio()’ 一样大：

     >>> s = SequenceMatcher(None, "abcd", "bcde")
     >>> s.ratio()
     0.75
     >>> s.quick_ratio()
     0.75
     >>> s.real_quick_ratio()
     1.0


File: python.info,  Node: SequenceMatcher 的示例,  Next: Differ 对象,  Prev: SequenceMatcher 对象,  Up: difflib --- 计算差异的辅助工具

5.6.3.2 SequenceMatcher 的示例
..............................

以下示例比较两个字符串，并将空格视为“垃圾”：

     >>> s = SequenceMatcher(lambda x: x == " ",
     ...                     "private Thread currentThread;",
     ...                     "private volatile Thread currentThread;")

‘ratio()’ 返回一个 [0, 1] 范围内的整数作为两个序列相似性的度量。 根据经
验，‘ratio()’ 值超过 0.6 就意味着两个序列是近似匹配的：

     >>> print(round(s.ratio(), 3))
     0.866

如果你只对两个序列相匹配的位置感兴趣，则 ‘get_matching_blocks()’ 就很方
便：

     >>> for block in s.get_matching_blocks():
     ...     print("a[%d] and b[%d] match for %d elements" % block)
     a[0] and b[0] match for 8 elements
     a[8] and b[17] match for 21 elements
     a[29] and b[38] match for 0 elements

请注意 ‘get_matching_blocks()’ 返回的最后一个元组总是只用于占位的
‘(len(a), len(b), 0)’，这也是元组末尾元素（匹配的元素数量）为 ‘0’ 的唯一
情况。

如果你想要知道如何将第一个序列转成第二个序列，可以使用 ‘get_opcodes()’:

     >>> for opcode in s.get_opcodes():
     ...     print("%6s a[%d:%d] b[%d:%d]" % opcode)
      equal a[0:8] b[0:8]
     insert a[8:8] b[8:17]
      equal a[8:29] b[17:38]

参见
....

   * 此模块中的 *note get_close_matches(): 17a3. 函数显示了如何基于
     *note SequenceMatcher: 957. 构建简单的代码来执行有用的功能。

   * 使用 *note SequenceMatcher: 957. 构建小型应用的 简易版本控制方案
     (1)。

   ---------- Footnotes ----------

   (1) https://code.activestate.com/recipes/576729/


File: python.info,  Node: Differ 对象,  Next: Differ 示例,  Prev: SequenceMatcher 的示例,  Up: difflib --- 计算差异的辅助工具

5.6.3.3 Differ 对象
...................

请注意 *note Differ: 179a. 所生成的增量并不保证是 `最小' 差异。 相反，最
小差异往往是违反直觉的，因为它们会同步任何可能的地方，有时甚至意外产生相
距 100 页的匹配。 将同步点限制为连续匹配保留了一些局部性概念，这偶尔会带
来产生更长差异的代价。

*note Differ: 179a. 类具有这样的构造器：

 -- 类: difflib.Differ (linejunk=None, charjunk=None)

     可选关键字形参 `linejunk' 和 `charjunk' 均为过滤函数 (或为 ‘None’)：

     `linejunk': 接受单个字符串作为参数的函数，如果其为垃圾字符串则返回
     真值。 默认值为 ‘None’，意味着没有任何行会被视为垃圾行。

     `charjunk': 接受单个字符（长度为 1 的字符串）作为参数的函数，如果其
     为垃圾字符则返回真值。 默认值为 ‘None’，意味着没有任何字符会被视为
     垃圾字符。

     这些垃圾过滤函数可加快查找差异的匹配速度，并且不会导致任何差异行或
     字符被忽略。 请阅读 *note find_longest_match(): 17ae. 方法的
     `isjunk' 形参的描述了解详情。

     *note Differ: 179a. 对象是通过一个单独方法来使用（生成增量）的：

      -- 方法: compare (a, b)

          比较两个由行组成的序列，并生成增量（一个由行组成的序列）。

          每个序列必须包含一个以换行符结尾的单行字符串。 这样的序列可以
          通过文件类对象的 *note readlines(): 17a0. 方法来获取。 所生成
          的增量同样由以换行符结尾的字符串构成，可以通过文件类对象的
          *note writelines(): 17a1. 方法原样打印出来。


File: python.info,  Node: Differ 示例,  Next: difflib 的命令行接口,  Prev: Differ 对象,  Up: difflib --- 计算差异的辅助工具

5.6.3.4 Differ 示例
...................

此示例比较两段文本。 首先我们设置文本为以换行符结尾的单行字符串构成的序
列（这样的序列也可以通过文件类对象的 ‘readlines()’ 方法来获取）：

     >>> text1 = '''  1. Beautiful is better than ugly.
     ...   2. Explicit is better than implicit.
     ...   3. Simple is better than complex.
     ...   4. Complex is better than complicated.
     ... '''.splitlines(keepends=True)
     >>> len(text1)
     4
     >>> text1[0][-1]
     '\n'
     >>> text2 = '''  1. Beautiful is better than ugly.
     ...   3.   Simple is better than complex.
     ...   4. Complicated is better than complex.
     ...   5. Flat is better than nested.
     ... '''.splitlines(keepends=True)

接下来我们实例化一个 Differ 对象：

     >>> d = Differ()

请注意在实例化 *note Differ: 179a. 对象时我们可以传入函数来过滤掉“垃圾
”行和字符。 详情参见 *note Differ(): 179a. 构造器说明。

最后，我们比较两个序列：

     >>> result = list(d.compare(text1, text2))

‘result’ 是一个字符串列表，让我们将其美化打印出来：

     >>> from pprint import pprint
     >>> pprint(result)
     ['    1. Beautiful is better than ugly.\n',
      '-   2. Explicit is better than implicit.\n',
      '-   3. Simple is better than complex.\n',
      '+   3.   Simple is better than complex.\n',
      '?     ++\n',
      '-   4. Complex is better than complicated.\n',
      '?            ^                     ---- ^\n',
      '+   4. Complicated is better than complex.\n',
      '?           ++++ ^                      ^\n',
      '+   5. Flat is better than nested.\n']

作为单独的多行字符串显示出来则是这样：

     >>> import sys
     >>> sys.stdout.writelines(result)
         1. Beautiful is better than ugly.
     -   2. Explicit is better than implicit.
     -   3. Simple is better than complex.
     +   3.   Simple is better than complex.
     ?     ++
     -   4. Complex is better than complicated.
     ?            ^                     ---- ^
     +   4. Complicated is better than complex.
     ?           ++++ ^                      ^
     +   5. Flat is better than nested.


File: python.info,  Node: difflib 的命令行接口,  Prev: Differ 示例,  Up: difflib --- 计算差异的辅助工具

5.6.3.5 difflib 的命令行接口
............................

这个实例演示了如何使用 difflib 来创建一个类似于 ‘diff’ 的工具。 它同样包
含在 Python 源码发布包中，文件名为 ‘Tools/scripts/diff.py’。

     #!/usr/bin/env python3
     """ Command line interface to difflib.py providing diffs in four formats:

     * ndiff:    lists every line and highlights interline changes.
     * context:  highlights clusters of changes in a before/after format.
     * unified:  highlights clusters of changes in an inline format.
     * html:     generates side by side comparison with change highlights.

     """

     import sys, os, difflib, argparse
     from datetime import datetime, timezone

     def file_mtime(path):
         t = datetime.fromtimestamp(os.stat(path).st_mtime,
                                    timezone.utc)
         return t.astimezone().isoformat()

     def main():

         parser = argparse.ArgumentParser()
         parser.add_argument('-c', action='store_true', default=False,
                             help='Produce a context format diff (default)')
         parser.add_argument('-u', action='store_true', default=False,
                             help='Produce a unified format diff')
         parser.add_argument('-m', action='store_true', default=False,
                             help='Produce HTML side by side diff '
                                  '(can use -c and -l in conjunction)')
         parser.add_argument('-n', action='store_true', default=False,
                             help='Produce a ndiff format diff')
         parser.add_argument('-l', '--lines', type=int, default=3,
                             help='Set number of context lines (default 3)')
         parser.add_argument('fromfile')
         parser.add_argument('tofile')
         options = parser.parse_args()

         n = options.lines
         fromfile = options.fromfile
         tofile = options.tofile

         fromdate = file_mtime(fromfile)
         todate = file_mtime(tofile)
         with open(fromfile) as ff:
             fromlines = ff.readlines()
         with open(tofile) as tf:
             tolines = tf.readlines()

         if options.u:
             diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
         elif options.n:
             diff = difflib.ndiff(fromlines, tolines)
         elif options.m:
             diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n)
         else:
             diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)

         sys.stdout.writelines(diff)

     if __name__ == '__main__':
         main()


File: python.info,  Node: textwrap --- 文本自动换行与填充,  Next: unicodedata --- Unicode 数据库,  Prev: difflib --- 计算差异的辅助工具,  Up: 文本处理服务

5.6.4 ‘textwrap’ — 文本自动换行与填充
-------------------------------------

`源代码:' Lib/textwrap.py(1)

__________________________________________________________________

*note textwrap: 109. 模块提供了一些快捷函数，以及可以完成所有工作的类
*note TextWrapper: 8f2.。 如果你只是要对一两个文本字符串进行自动换行或填
充，快捷函数应该就够用了；否则的话，你应该使用 *note TextWrapper: 8f2. 的
实例来提高效率。

 -- 函数: textwrap.wrap (text, width=70, **kwargs)

     对 `text' (字符串) 中的单独段落自动换行以使每行长度最多为 `width' 个
     字符。 返回由输出行组成的列表，行尾不带换行符。

     可选的关键字参数对应于 *note TextWrapper: 8f2. 的实例属性，具体文档
     见下。 `width' 默认为 ‘70’。

     请参阅 *note TextWrapper.wrap(): 17bf. 方法了解有关 *note wrap():
     17be. 行为的详细信息。

 -- 函数: textwrap.fill (text, width=70, **kwargs)

     对 `text' 中的单独段落自动换行，并返回一个包含被自动换行段落的单独
     字符串。 *note fill(): 17c0. 是以下语句的快捷方式

          "\n".join(wrap(text, ...))

     特别要说明的是，*note fill(): 17c0. 接受与 *note wrap(): 17be. 完全
     相同的关键字参数。

 -- 函数: textwrap.shorten (text, width, **kwargs)

     折叠并截短给定的 `text' 以符合给定的 `width'。

     首先将折叠 `text' 中的空格（所有连续空格替换为单个空格）。 如果结果
     能适合 `width' 则将其返回。 否则将丢弃足够数量的末尾单词以使得剩余
     单词加 ‘placeholder’ 能适合 ‘width’:

          >>> textwrap.shorten("Hello  world!", width=12)
          'Hello world!'
          >>> textwrap.shorten("Hello  world!", width=11)
          'Hello [...]'
          >>> textwrap.shorten("Hello world", width=10, placeholder="...")
          'Hello...'

     可选的关键字参数对应于 *note TextWrapper: 8f2. 的实际属性，具体见下
     文。 请注意文本在被传入 *note TextWrapper: 8f2. 的 *note fill():
     17c0. 函数之前会被折叠，因此改变 *note tabsize: 17c1, *note
     expand_tabs: 17c2, *note drop_whitespace: 17c3. 和 *note
     replace_whitespace: 17c4. 的值将没有任何效果。

     3.4 新版功能.

 -- 函数: textwrap.dedent (text)

     移除 `text' 中每一行的任何相同前缀空白符。

     这可以用来清除三重引号字符串行左侧空格，而仍然在源码中显示为缩进格
     式。

     请注意制表符和空格符都被视为是空白符，但它们并不相等：以下两行 ‘"
     hello"’ 和 ‘"\thello"’ 不会被视为具有相同的前缀空白符。

     只包含空白符的行会在输入时被忽略并在输出时被标准化为单个换行符。

     例如

          def test():
              # end first line with \ to avoid the empty line!
              s = '''\
              hello
                world
              '''
              print(repr(s))          # prints '    hello\n      world\n    '
              print(repr(dedent(s)))  # prints 'hello\n  world\n'

 -- 函数: textwrap.indent (text, prefix, predicate=None)

     将 `prefix' 添加到 `text' 中选定行的开头。

     通过调用 ‘text.splitlines(True)’ 来对行进行拆分。

     默认情况下，`prefix' 会被添加到所有不是只由空白符（包括任何行结束符
     ）组成的行。

     例如

          >>> s = 'hello\n\n \nworld'
          >>> indent(s, '  ')
          '  hello\n\n \n  world'

     可选的 `predicate' 参数可用来控制哪些行要缩进。 例如，可以很容易地
     为空行或只有空白符的行添加 `prefix':

          >>> print(indent(s, '+ ', lambda line: True))
          + hello
          +
          +
          + world

     3.3 新版功能.

*note wrap(): 17be, *note fill(): 17c0. 和 *note shorten(): 8f5. 的作用
方式为创建一个 *note TextWrapper: 8f2. 实例并在其上调用单个方法。 该实例
不会被重用，因此对于要使用 *note wrap(): 17be. 和/或 *note fill(): 17c0.
来处理许多文本字符串的应用来说，创建你自己的 *note TextWrapper: 8f2. 对
象可能会更有效率。

文本最好在空白符位置自动换行，包括带连字符单词的连字符之后；长单词仅在必
要时会被拆分，除非 *note TextWrapper.break_long_words: 17c6. 被设为假值
。

 -- 类: textwrap.TextWrapper (**kwargs)

     *note TextWrapper: 8f2. 构造器接受多个可选的关键字参数。 每个关键字
     参数对应一个实例属性，比如说

          wrapper = TextWrapper(initial_indent="* ")

     就相当于

          wrapper = TextWrapper()
          wrapper.initial_indent = "* "

     你可以多次重用相同的 *note TextWrapper: 8f2. 对象，并且你也可以在使
     用期间通过直接向实例属性赋值来修改它的任何选项。

     *note TextWrapper: 8f2. 的实例属性（以及构造器的关键字参数）如下所
     示：

      -- 属性: width

          (默认: ‘70’) 自动换行的最大行长度。 只要输入文本中没有长于
          *note width: 17c7. 的单个单词，*note TextWrapper: 8f2. 就能保
          证没有长于 *note width: 17c7. 个字符的输出行。

      -- 属性: expand_tabs

          (默认: ‘True’) 如果为真值，则 `text' 中所有的制表符将使用
          `text' 的 ‘expandtabs()’ 方法扩展为空格符。

      -- 属性: tabsize

          (默认: ‘8’) 如果 *note expand_tabs: 17c2. 为真值，则 `text' 中
          所有的制表符将扩展为零个或多个空格，具体取决于当前列位置和给定
          的制表宽度。

          3.3 新版功能.

      -- 属性: replace_whitespace

          (default: ‘True’) 如果为真值，在制表符扩展之后、自动换行之前，
          *note wrap(): 17be. 方法将把每个空白字符都替换为单个空格。 会
          被替换的空白字符如下：制表，换行，垂直制表，进纸和回车
          (‘'\t\n\v\f\r'’)。

               注解: 如果 *note expand_tabs: 17c2. 为假值且 *note
               replace_whitespace: 17c4. 为真值，每个制表符将被替换为单
               个空格，这与制表符扩展是 `不' 一样的。

               注解: 如果 *note replace_whitespace: 17c4. 为假值，在一行
               的中间有可能出现换行符并导致怪异的输出。 因此，文本应当（
               使用 *note str.splitlines(): 1669. 或类似方法）拆分为段落
               并分别进行自动换行。

      -- 属性: drop_whitespace

          (默认: ‘True’) 如果为真值，每一行开头和末尾的空白字符（在包装
          之后、缩进之前）会被丢弃。 但是段落开头的空白字符如果后面不带
          任何非空白字符则不会被丢弃。 如果被丢弃的空白字符占据了一个整
          行，则该整行将被丢弃。

      -- 属性: initial_indent

          (默认: ‘''’) 将被添加到被自动换行输出内容的第一行的字符串。 其
          长度会被计入第一行的长度。 空字符串不会被缩进。

      -- 属性: subsequent_indent

          (default: ‘''’) 将被添加到被自动换行输出内容除第一行外的所有行
          的字符串。 其长度会被计入除行一行外的所有行的长度。

      -- 属性: fix_sentence_endings

          (默认: ‘False’) 如果为真值，*note TextWrapper: 8f2. 将尝试检测
          句子结尾并确保句子间总是以恰好两个空格符分隔。 对于使用等宽字
          体的文本来说通常都需要这样。 但是，句子检测算法并不完美：它假
          定句子结尾是一个小写字母加字符 ‘'.'’, ‘'!'’ 或 ‘'?'’ 中的一个
          ，并可能带有字符 ‘'"'’ 或 ‘"'"’，最后以一个空格结束。 此算法的
          问题之一是它无法区分以下文本中的 "Dr."

               [...] Dr. Frankenstein's monster [...]

          和以下文本中的 "Spot."

               [...] See Spot. See Spot run [...]

          *note fix_sentence_endings: 17ca. 默认为假值。

          由于句子检测算法依赖于 ‘string.lowercase’ 来确定“小写字母”，以
          及约定在句点后使用两个空格来分隔处于同一行的句子，因此只适用于
          英语文本。

      -- 属性: break_long_words

          (默认: ‘True’) 如果为真值，则长度超过 *note width: 17c7. 的单
          词将被分开以保证行的长度不会超过 *note width: 17c7.。 如果为假
          值，超长单词不会被分开，因而某些行的长度可能会超过 *note
          width: 17c7.。 （超长单词将被单独作为一行，以尽量减少超出
          *note width: 17c7. 的情况。）

      -- 属性: break_on_hyphens

          (默认: ‘True’) 如果为真值，将根据英语的惯例首选在空白符和复合
          词的连字符之后自动换行。 如果为假值，则只有空白符会被视为合适
          的潜在断行位置，但如果你确实不希望出现分开的单词则你必须将
          *note break_long_words: 17c6. 设为假值。 之前版本的默认行为总
          是允许分开带有连字符的单词。

      -- 属性: max_lines

          (默认: ‘None’) 如果不为 ‘None’，则输出内容将最多包含
          `max_lines' 行，并使 `placeholder' 出现在输出内容的末尾。

          3.4 新版功能.

      -- 属性: placeholder

          (默认: ‘' [...]'’) 该文本将在输出文本被截短时出现在文本末尾。

          3.4 新版功能.

     *note TextWrapper: 8f2. 还提供了一些公有方法，类似于模块层级的便捷
     函数：

      -- 方法: wrap (text)

          对 `text' (字符串) 中的单独段落自动换行以使每行长度最多为
          *note width: 17c7. 个字符。 所有自动换行选项均获取自 *note
          TextWrapper: 8f2. 实例的实例属性。 返回由输出行组成的列表，行
          尾不带换行符。 如果自动换行输出结果没有任何内容，则返回空列表
          。

      -- 方法: fill (text)

          对 `text' 中的单独段落自动换行并返回包含被自动换行段落的单独字
          符串。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/textwrap.py


File: python.info,  Node: unicodedata --- Unicode 数据库,  Next: stringprep --- 因特网字符串预备,  Prev: textwrap --- 文本自动换行与填充,  Up: 文本处理服务

5.6.5 ‘unicodedata’ — Unicode 数据库
------------------------------------

__________________________________________________________________

此模块提供了对 Unicode Character Database (UCD) 的访问，其中定义了所有
Unicode 字符的字符属性。 此数据库中包含的数据编译自 UCD 版本 12.1.0(1)。

该模块使用与 Unicode 标准附件 #44 “Unicode 字符数据库”(2) 中所定义的相同
名称和符号。 它定义了以下函数：

 -- 函数: unicodedata.lookup (name)

     按名称查找字符。如果找到具有给定名称的字符，则返回相应的字符。 如果
     没有找到，则 *note KeyError: 2c8. 被引发。

     在 3.3 版更改: 已添加对名称别名 (3) 和命名序列 (4) 的支持。

 -- 函数: unicodedata.name (chr[, default])

     返回分配给字符 `chr' 的名称作为字符串。如果没有定义名称，则返回
     `default' ，如果没有给出，则 *note ValueError: 1fc. 被引发。

 -- 函数: unicodedata.decimal (chr[, default])

     返回分配给字符 `chr' 的十进制值作为整数。 如果没有定义这样的值，则
     返回 `default' ，如果没有给出，则 *note ValueError: 1fc. 被引发。

 -- 函数: unicodedata.digit (chr[, default])

     返回分配给字符 `chr' 的数字值作为整数。 如果没有定义这样的值，则返
     回 `default' ，如果没有给出，则 *note ValueError: 1fc. 被引发。

 -- 函数: unicodedata.numeric (chr[, default])

     返回分配给字符 `chr' 的数值作为浮点数。 如果没有定义这样的值，则返
     回 `default' ，如果没有给出，则 *note ValueError: 1fc. 被引发。

 -- 函数: unicodedata.category (chr)

     返回分配给字符 `chr' 的常规类别为字符串。

 -- 函数: unicodedata.bidirectional (chr)

     返回分配给字符 `chr' 的双向类作为字符串。如果未定义此类值，则返回空
     字符串。

 -- 函数: unicodedata.combining (chr)

     返回分配给字符 `chr' 的规范组合类作为整数。如果没有定义组合类，则返
     回 ‘0’ 。

 -- 函数: unicodedata.east_asian_width (chr)

     返回分配给字符 `chr' 的东亚宽度作为字符串。

 -- 函数: unicodedata.mirrored (chr)

     返回分配给字符 `chr' 的镜像属性为整数。如果字符在双向文本中被识别为
     “镜像”字符，则返回 ‘1’ ，否则返回 ‘0’ 。

 -- 函数: unicodedata.decomposition (chr)

     返回分配给字符 `chr' 的字符分解映射作为字符串。如果未定义此类映射，
     则返回空字符串。

 -- 函数: unicodedata.normalize (form, unistr)

     返回 Unicode 字符串 `unistr' 的正常形式 `form' 。 `form' 的有效值为
     ’NFC’ 、 ’NFKC’ 、 ’NFD’ 和 ’NFKD’ 。

     Unicode 标准基于规范等价和兼容性等效的定义定义了 Unicode 字符串的各
     种规范化形式。在 Unicode 中，可以以各种方式表示多个字符。 例如，字
     符 U+00C7 （带有 CEDILLA 的 LATIN CAPITAL LETTER C ）也可以表示为序
     列 U+0043（ LATIN CAPITAL LETTER C ）U+0327（ COMBINING CEDILLA ）
     。

     对于每个字符，有两种正规形式：正规形式 C 和正规形式 D 。正规形式D（
     NFD）也称为规范分解，并将每个字符转换为其分解形式。 正规形式C（
     NFC）首先应用规范分解，然后再次组合预组合字符。

     除了这两种形式之外，还有两种基于兼容性等效的其他常规形式。 在
     Unicode 中，支持某些字符，这些字符通常与其他字符统一。 例如，
     U+2160（ROMAN NUMERAL ONE）与 U+0049（LATIN CAPITAL LETTER I）完全
     相同。 但是， Unicode 支持它与现有字符集（例如 gb2312 ）的兼容性。

     正规形式KD（NFKD）将应用兼容性分解，即用其等价项替换所有兼容性字符
     。 正规形式KC（NFKC）首先应用兼容性分解，然后是规范组合。

     即使两个 unicode 字符串被规范化并且人类读者看起来相同，如果一个具有
     组合字符而另一个没有，则它们可能无法相等。

 -- 函数: unicodedata.is_normalized (form, unistr)

     判断 Unicode 字符串 `unistr' 是否为正规形式 `form'。 `form' 的有效
     值为 ’NFC’, ’NFKC’, ’NFD’ 和 ’NFKD’。

     3.8 新版功能.

此外，该模块暴露了以下常量：

 -- 数据: unicodedata.unidata_version

     此模块中使用的 Unicode 数据库的版本。

 -- 数据: unicodedata.ucd_3_2_0

     这是一个与整个模块具有相同方法的对象，但对于需要此特定版本的
     Unicode 数据库（如 IDNA ）的应用程序，则使用 Unicode 数据库版本 3.2
     。

示例：

     >>> import unicodedata
     >>> unicodedata.lookup('LEFT CURLY BRACKET')
     '{'
     >>> unicodedata.name('/')
     'SOLIDUS'
     >>> unicodedata.decimal('9')
     9
     >>> unicodedata.decimal('a')
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     ValueError: not a decimal
     >>> unicodedata.category('A')  # 'L'etter, 'u'ppercase
     'Lu'
     >>> unicodedata.bidirectional('\u0660') # 'A'rabic, 'N'umber
     'AN'

备注
....

   ---------- Footnotes ----------

   (1) http://www.unicode.org/Public/12.1.0/ucd

   (2) https://www.unicode.org/reports/tr44/

   (3) (1) ‘http://www.unicode.org/Public/12.1.0/ucd/NameAliases.txt’

   (4) (2) ‘http://www.unicode.org/Public/12.1.0/ucd/NamedSequences.txt’


File: python.info,  Node: stringprep --- 因特网字符串预备,  Next: readline --- GNU readline 接口,  Prev: unicodedata --- Unicode 数据库,  Up: 文本处理服务

5.6.6 ‘stringprep’ — 因特网字符串预备
-------------------------------------

`源代码:' Lib/stringprep.py(1)

__________________________________________________________________

在标识因特网上的事物（例如主机名），经常需要比较这些标识是否（相等）。 这
种比较的具体执行可能会取决于应用域的不同，例如是否要区分大小写等等。 有
时也可能需要限制允许的标识为仅由“可打印”字符组成。

RFC 3454(2) 定义了在因特网协议中 Unicode 字符串的“预备”过程。 在将字符串
连线传输之前，它们会先使用预备过程进行处理，之后它们将具有特定的标准形式
。 该 RFC 定义了一系列表格，它们可以被组合为选项配置。 每个配置必须定义
所使用的表格，‘stringprep’ 过程的其他可选项也是配置的组成部分。
‘stringprep’ 配置的一个例子是 ‘nameprep’，它被用于国际化域名。

模块 *note stringprep: f8. 仅公开了来自 RFC 3454(3) 的表格。 由于这些如
果表格如果表示为字典或列表将会非常庞大，该模块在内部使用 Unicode 字符数
据库。 该模块本身的源代码是使用 ‘mkstringprep.py’ 工具生成的。

因此，这些表格以函数而非数据结构的形式公开。 在 RFC 中有两种表格：集合与
映射。 对于集合，*note stringprep: f8. 提供了“特征函数”，即如果形参是集
合的一部分则返回值为 ‘True’ 的函数。 对于映射，它提供了映射函数：它会根
据给定的键返回所关联的值。 以下是模块中所有可用函数的列表。

 -- 函数: stringprep.in_table_a1 (code)

     确定 `code' 是否属于 tableA.1 (Unicode 3.2 中的未分配码位)。

 -- 函数: stringprep.in_table_b1 (code)

     确定 `code' 是否属于 tableB.1 (通常映射为空值)。

 -- 函数: stringprep.map_table_b2 (code)

     返回 `code' 依据 tableB.2 (配合 NFKC 使用的大小写转换映射) 所映射的
     值。

 -- 函数: stringprep.map_table_b3 (code)

     返回 `code' 依据 tableB.3 (不附带正规化的大小写折叠映射) 所映射的值
     。

 -- 函数: stringprep.in_table_c11 (code)

     确定 `code' 是否属于 tableC.1.1 (ASCII 空白字符)。

 -- 函数: stringprep.in_table_c12 (code)

     确定 `code' 是否属于 tableC.1.2 (非 ASCII 空白字符)。

 -- 函数: stringprep.in_table_c11_c12 (code)

     确定 `code' 是否属于 tableC.1 (空白字符，C.1.1 和 C.1.2 的并集)。

 -- 函数: stringprep.in_table_c21 (code)

     确定 `code' 是否属于 tableC.2.1 (ASCII 控制字符)。

 -- 函数: stringprep.in_table_c22 (code)

     确定 `code' 是否属于 tableC.2.2 (非 ASCII 控制字符)。

 -- 函数: stringprep.in_table_c21_c22 (code)

     确定 `code' 是否属于 tableC.2 (控制字符，C.2.1 和 C.2.2 的并集)。

 -- 函数: stringprep.in_table_c3 (code)

     确定 `code' 是否属于 tableC.3 (私有使用)。

 -- 函数: stringprep.in_table_c4 (code)

     确定 `code' 是否属于 tableC.4 (非字符码位)。

 -- 函数: stringprep.in_table_c5 (code)

     确定 `code' 是否属于 tableC.5 (替代码)。

 -- 函数: stringprep.in_table_c6 (code)

     确定 `code' 是否属于 tableC.6 (不适用于纯文本)。

 -- 函数: stringprep.in_table_c7 (code)

     确定 `code' 是否属于 tableC.7 (不适用于规范表示)。

 -- 函数: stringprep.in_table_c8 (code)

     确定 `code' 是否属于 tableC.8 (改变显示属性或已弃用)。

 -- 函数: stringprep.in_table_c9 (code)

     确定 `code' 是否属于 tableC.9 (标记字符)。

 -- 函数: stringprep.in_table_d1 (code)

     确定 `code' 是否属于 tableD.1 (带有双向属性 "R" 或 "AL" 的字符)。

 -- 函数: stringprep.in_table_d2 (code)

     确定 `code' 是否属于 tableD.2 (带有双向属性 "L" 的字符)。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/stringprep.py

   (2) https://tools.ietf.org/html/rfc3454.html

   (3) https://tools.ietf.org/html/rfc3454.html


File: python.info,  Node: readline --- GNU readline 接口,  Next: rlcompleter --- GNU readline 的补全函数,  Prev: stringprep --- 因特网字符串预备,  Up: 文本处理服务

5.6.7 ‘readline’ — GNU readline 接口
------------------------------------

__________________________________________________________________

*note readline: df. 模块定义了许多方便从 Python 解释器完成和读取/写入历
史文件的函数。 此模块可以直接使用，或通过支持在交互提示符下完成 Python 标
识符的 *note rlcompleter: e2. 模块使用。 使用此模块进行的设置会同时影响
解释器的交互提示符以及内置 *note input(): c73. 函数提供的提示符。

Readline keybindings may be configured via an initialization file,
typically ‘.inputrc’ in your home directory.  See Readline Init File(1)
in the GNU Readline manual for information about the format and
allowable constructs of that file, and the capabilities of the Readline
library in general.

     注解: 底层的 Readline 库 API 可能使用 ‘libedit’ 库来实现而不是 GNU
     readline。 在 macOS 上 *note readline: df. 模块会在运行时检测所使用
     的是哪个库。

     ‘libedit’ 所用的配置文件与 GNU readline 的不同。 如果你要在程序中载
     入配置字符串你可以在 ‘readline.__doc__’ 中检测文本 "libedit" 来区分
     GNU readline 和 libedit。

     如果你是在 macOS 上使用 `editline'/‘libedit’ readline 模拟，则位于
     你的主目录中的初始化文件名称为 ‘.editrc’。 例如，‘~/.editrc’ 中的以
     下内容将开启 `vi' 按键绑定以及 TAB 补全:

          python:bind -v
          python:bind ^I rl_complete

* Menu:

* 初始化文件::
* 行缓冲区::
* 历史文件::
* 历史列表::
* 启动钩子::
* Completion::
* 示例::

   ---------- Footnotes ----------

   (1) https://tiswww.cwru.edu/php/chet/readline/rluserman.html#SEC9


File: python.info,  Node: 初始化文件,  Next: 行缓冲区,  Up: readline --- GNU readline 接口

5.6.7.1 初始化文件
..................

下列函数与初始化文件和用户配置有关：

 -- 函数: readline.parse_and_bind (string)

     执行在 `string' 参数中提供的初始化行。 此函数会调用底层库中的
     ‘rl_parse_and_bind()’。

 -- 函数: readline.read_init_file ([filename])

     执行一个 readline 初始化文件。 默认文件名为最近所使用的文件名。 此
     函数会调用底层库中的 ‘rl_read_init_file()’。


File: python.info,  Node: 行缓冲区,  Next: 历史文件,  Prev: 初始化文件,  Up: readline --- GNU readline 接口

5.6.7.2 行缓冲区
................

下列函数会在行缓冲区上操作。

 -- 函数: readline.get_line_buffer ()

     返回行缓冲区的当前内容 (底层库中的 ‘rl_line_buffer’)。

 -- 函数: readline.insert_text (string)

     将文本插入行缓冲区的当前游标位置。 该函数会调用底层库中的
     ‘rl_insert_text()’，但会忽略其返回值。

 -- 函数: readline.redisplay ()

     改变屏幕的显示以反映行缓冲区的当前内容。 该函数会调用底层库中的
     ‘rl_redisplay()’。


File: python.info,  Node: 历史文件,  Next: 历史列表,  Prev: 行缓冲区,  Up: readline --- GNU readline 接口

5.6.7.3 历史文件
................

下列函数会在历史文件上操作：

 -- 函数: readline.read_history_file ([filename])

     载入一个 readline 历史文件，并将其添加到历史列表。 默认文件名为
     ‘~/.history’。 此函数会调用底层库中的 ‘read_history()’。

 -- 函数: readline.write_history_file ([filename])

     将历史列表保存为 readline 历史文件，覆盖任何现有文件。 默认文件名为
     ‘~/.history’。 此函数会调用底层库中的 ‘write_history()’。

 -- 函数: readline.append_history_file (nelements[, filename])

     将历史列表的最后 `nelements' 项添加到历史文件。 默认文件名为
     ‘~/.history’。 文件必须已存在。 此函数会调用底层库中的
     ‘append_history()’。 此函数仅当 Python 编译包带有支持此功能的库版本
     时才会存在。

     3.5 新版功能.

 -- 函数: readline.get_history_length ()
 -- 函数: readline.set_history_length (length)

     设置或返回需要保存到历史文件的行数。 *note write_history_file():
     17f9. 函数会通过调用底层库中的 ‘history_truncate_file()’ 以使用该值
     来截取历史文件。 负值意味着不限制历史文件的大小。


File: python.info,  Node: 历史列表,  Next: 启动钩子,  Prev: 历史文件,  Up: readline --- GNU readline 接口

5.6.7.4 历史列表
................

以下函数会在全局历史列表上操作：

 -- 函数: readline.clear_history ()

     清除当前历史。 此函数会调用底层库的 ‘clear_history()’。 此 Python 函
     数仅当 Python 编译包带有支持此功能的库版本时才会存在。

 -- 函数: readline.get_current_history_length ()

     返回历史列表的当前项数。 （此函数不同于 *note get_history_length():
     17fa.，后者是返回将被写入历史文件的最大行数。）

 -- 函数: readline.get_history_item (index)

     返回序号为 `index' 的历史条目的当前内容。 条目序号从一开始。 此函数
     会调用底层库中的 ‘history_get()’。

 -- 函数: readline.remove_history_item (pos)

     从历史列表中移除指定位置上的历史条目。 条目位置从零开始。 此函数会
     调用底层库中的 ‘remove_history()’。

 -- 函数: readline.replace_history_item (pos, line)

     将指定位置上的历史条目替换为 `line'。 条目位置从零开始。 此函数会调
     用底层库中的 ‘replace_history_entry()’。

 -- 函数: readline.add_history (line)

     将 `line' 添加到历史缓冲区，相当于是最近输入的一行。 此函数会调用底
     层库中的 ‘add_history()’。

 -- 函数: readline.set_auto_history (enabled)

     启用或禁用当通过 readline 读取输入时自动调用 ‘add_history()’。
     `enabled' 参数应为一个布尔值，当其为真值时启用自动历史，当其为假值
     时禁用自动历史。

     3.6 新版功能.

     `CPython implementation detail:' Auto history is enabled by
     default, and changes to this do not persist across multiple
     sessions.


File: python.info,  Node: 启动钩子,  Next: Completion,  Prev: 历史列表,  Up: readline --- GNU readline 接口

5.6.7.5 启动钩子
................

 -- 函数: readline.set_startup_hook ([function])

     设置或移除底层库的 ‘rl_startup_hook’ 回调所发起调用的函数。 如果指
     定了 `function'，它将被用作新的钩子函数；如果省略或为 ‘None’，任何
     已安装的函数将被移除。 钩子函数将在 readline 打印第一个提示信息之前
     不带参数地被调用。

 -- 函数: readline.set_pre_input_hook ([function])

     设置或移除底层库的 ‘rl_pre_input_hook’ 回调所发起调用的函数。 如果
     指定了 `function'，它将被用作新的钩子函数；如果省略或为 ‘None’，任
     何已安装的函数将被移除。 钩子函数将在打印第一个提示信息之后、
     readline 开始读取输入字符之前不带参数地被调用。 此函数仅当 Python 编
     译包带有支持此功能的库版本时才会存在。


File: python.info,  Node: Completion,  Next: 示例,  Prev: 启动钩子,  Up: readline --- GNU readline 接口

5.6.7.6 Completion
..................

以下函数与自定义单词补全函数的实现有关。 这通常使用 Tab 键进行操作，能够
提示并自动补全正在输入的单词。 默认情况下，Readline 设置为由 *note
rlcompleter: e2. 来补全交互模式解释器的 Python 标识符。 如果 *note
readline: df. 模块要配合自定义的补全函数来使用，则需要设置不同的单词分隔
符。

 -- 函数: readline.set_completer ([function])

     设置或移除补全函数。 如果指定了 `function'，它将被用作新的补全函数
     ；如果省略或为 ‘None’，任何已安装的补全函数将被移除。 补全函数的调
     用形式为 ‘function(text, state)’，其中 `state' 为 ‘0’, ‘1’, ‘2’,
     ..., 直至其返回一个非字符串值。 它应当返回下一个以 `text' 开头的候
     选补全内容。

     已安装的补全函数将由传递给底层库中 ‘rl_completion_matches()’ 的
     `entry_func' 回调函数来发起调用。 `text' 字符串来自于底层库中
     ‘rl_attempted_completion_function’ 回调函数的第一个形参。

 -- 函数: readline.get_completer ()

     获取补全函数，如果没有设置补全函数则返回 ‘None’。

 -- 函数: readline.get_completion_type ()

     获取正在尝试的补全类型。 此函数会将底层库中的 ‘rl_completion_type’
     变量作为一个整数返回。

 -- 函数: readline.get_begidx ()
 -- 函数: readline.get_endidx ()

     获取补全域的开始和结束序号。 这些序号就是传给底层库中
     ‘rl_attempted_completion_function’ 回调函数的 `start' 和 `end' 参数
     。

 -- 函数: readline.set_completer_delims (string)
 -- 函数: readline.get_completer_delims ()

     设置或获取补全的单词分隔符。 此分隔符确定了要考虑补全的单词的开始和
     结束位置（补全域）。 这些函数会访问底层库的
     ‘rl_completer_word_break_characters’ 变量。

 -- 函数: readline.set_completion_display_matches_hook ([function])

     设置或移除补全显示函数。 如果指定了 `function'，它将被用作新的补全
     显示函数；如果省略或为 ‘None’，任何已安装的补全显示函数将被移除。 此
     函数会设置或清除底层库的 ‘rl_completion_display_matches_hook’ 回调
     函数。 补全显示函数会在每次需要显示匹配项时以
     ‘function(substitution, [matches], longest_match_length)’ 的形式被
     调用。


File: python.info,  Node: 示例,  Prev: Completion,  Up: readline --- GNU readline 接口

5.6.7.7 示例
............

以下示例演示了如何使用 *note readline: df. 模块的历史读取或写入函数来自
动加载和保存用户主目录下名为 ‘.python_history’ 的历史文件。 以下代码通常
应当在交互会话期间从用户的 *note PYTHONSTARTUP: 8ed. 文件自动执行。

     import atexit
     import os
     import readline

     histfile = os.path.join(os.path.expanduser("~"), ".python_history")
     try:
         readline.read_history_file(histfile)
         # default history len is -1 (infinite), which may grow unruly
         readline.set_history_length(1000)
     except FileNotFoundError:
         pass

     atexit.register(readline.write_history_file, histfile)

此代码实际上会在 Python 运行于 *note 交互模式: 8eb. 时自动运行 (参见
*note Readline（类库） 配置: 8ee.)。

以下示例实现了同样的目标，但是通过只添加新历史的方式来支持并发的交互会话
。

     import atexit
     import os
     import readline
     histfile = os.path.join(os.path.expanduser("~"), ".python_history")

     try:
         readline.read_history_file(histfile)
         h_len = readline.get_current_history_length()
     except FileNotFoundError:
         open(histfile, 'wb').close()
         h_len = 0

     def save(prev_h_len, histfile):
         new_h_len = readline.get_current_history_length()
         readline.set_history_length(1000)
         readline.append_history_file(new_h_len - prev_h_len, histfile)
     atexit.register(save, h_len, histfile)

以下示例扩展了 *note code.InteractiveConsole: 1811. 类以支持历史保存/恢
复。

     import atexit
     import code
     import os
     import readline

     class HistoryConsole(code.InteractiveConsole):
         def __init__(self, locals=None, filename="<console>",
                      histfile=os.path.expanduser("~/.console-history")):
             code.InteractiveConsole.__init__(self, locals, filename)
             self.init_history(histfile)

         def init_history(self, histfile):
             readline.parse_and_bind("tab: complete")
             if hasattr(readline, "read_history_file"):
                 try:
                     readline.read_history_file(histfile)
                 except FileNotFoundError:
                     pass
                 atexit.register(self.save_history, histfile)

         def save_history(self, histfile):
             readline.set_history_length(1000)
             readline.write_history_file(histfile)


File: python.info,  Node: rlcompleter --- GNU readline 的补全函数,  Prev: readline --- GNU readline 接口,  Up: 文本处理服务

5.6.8 ‘rlcompleter’ — GNU readline 的补全函数
---------------------------------------------

`源代码:' Lib/rlcompleter.py(1)

__________________________________________________________________

‘rlcompeleter’ 通过补全有效的 Python 标识符和关键字定义了一个适用于
*note readline: df. 模块的补全函数。

当此模块在具有可用的 *note readline: df. 模块的 Unix 平台被导入, 一个
‘Completer’ 实例将被自动创建并且它的 ‘complete()’ 方法将设置为 *note
readline: df. 的补全器.

示例:

     >>> import rlcompleter
     >>> import readline
     >>> readline.parse_and_bind("tab: complete")
     >>> readline. <TAB PRESSED>
     readline.__doc__          readline.get_line_buffer(  readline.read_init_file(
     readline.__file__         readline.insert_text(      readline.set_completer(
     readline.__name__         readline.parse_and_bind(
     >>> readline.

*note rlcompleter: e2. 模块是为了使用 Python 的 *note 交互模式: 8eb. 而
设计的。 除非 Python 是通过 *note -S: b2c. 选项运行, 这个模块总是自动地
被导入且配置 (参见 *note Readline（类库） 配置: 8ee.)。

在没有 *note readline: df. 的平台, 此模块定义的 ‘Completer’ 类仍然可以用
于自定义行为.

* Menu:

* Completer 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/rlcompleter.py


File: python.info,  Node: Completer 对象,  Up: rlcompleter --- GNU readline 的补全函数

5.6.8.1 Completer 对象
......................

Completer 对象具有以下方法：

 -- 方法: Completer.complete (text, state)

     为 `text' 返回第 `state' 项补全。

     如果指定的 `text' 不包含句点字符 (‘'.'’)，它将根据当前 *note
     __main__: 1, *note builtins: 13. 和保留关键字（定义于 *note
     keyword: a7. 模块）所定义的名称进行补全。

     如果为带有句点的名称执行调用，它将尝试尽量求值直到最后一部分为止而
     不产生附带影响（函数不会被求值，但它可以生成对 *note __getattr__():
     323. 的调用），并通过 *note dir(): d3b. 函数来匹配剩余部分。 在对表
     达式求值期间引发的任何异常都会被捕获、静默处理并返回 *note None:
     158.。


File: python.info,  Node: 二进制数据服务,  Next: 数据类型,  Prev: 文本处理服务,  Up: Python 标准库

5.7 二进制数据服务
==================

本章介绍的模块提供了一些操作二进制数据的基本服务操作。 有关二进制数据的
其他操作，特别是与文件格式和网络协议有关的操作，将在相关章节中介绍。

下面描述的一些库 *note 文本处理服务: 1651. 也可以使用 ASCII 兼容的二进制
格式（例如 *note re: de. ）或所有二进制数据（例如 *note difflib: 37. ）
。

另外，请参阅 Python 的内置二进制数据类型的文档 *note 二进制序列类型 —
bytes, bytearray, memoryview: 15f8. 。

* Menu:

* struct: struct --- 将字节串解读为打包的二进制数据. 将字节串解读为打包的二进制数据
* codecs: codecs --- 编解码器注册和相关基类. 编解码器注册和相关基类


File: python.info,  Node: struct --- 将字节串解读为打包的二进制数据,  Next: codecs --- 编解码器注册和相关基类,  Up: 二进制数据服务

5.7.1 ‘struct’ — 将字节串解读为打包的二进制数据
-----------------------------------------------

`源代码：' Lib/struct.py(1)

__________________________________________________________________

此模块可以执行 Python 值和以 Python *note bytes: 33a. 对象表示的 C 结构
之间的转换。 这可以被用来处理存储在文件中或是从网络连接等其他来源获取的
二进制数据。 它使用 *note 格式字符串: 181b. 作为 C 结构布局的精简描述以
及与 Python 值的双向转换。

     注解: 默认情况下，打包给定 C 结构的结果会包含填充字节以使得所涉及的
     C 类型保持正确的对齐；类似地，对齐在解包时也会被纳入考虑。 选择此种
     行为的目的是使得被打包结构的字节能与相应 C 结构在内存中的布局完全一
     致。 要处理平台独立的数据格式或省略隐式的填充字节，请使用
     ‘standard’ 大小和对齐而不是 ‘native’ 大小和对齐：详情参见 *note
     字节顺序，大小和对齐方式: 181c.。

某些 *note struct: f9. 的函数（以及 *note Struct: 181d. 的方法）接受一个
`buffer' 参数。 这将指向实现了 *note 缓冲协议: 15f7. 并提供只读或是可读
写缓冲的对象。 用于此目的的最常见类型为 *note bytes: 33a. 和 *note
bytearray: 33b.，但许多其他可被视为字节数组的类型也实现了缓冲协议，因此
它们无需额外从 *note bytes: 33a. 对象复制即可被读取或填充。

* Menu:

* 函数和异常::
* 格式字符串::
* 类: 类<2>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/struct.py


File: python.info,  Node: 函数和异常,  Next: 格式字符串,  Up: struct --- 将字节串解读为打包的二进制数据

5.7.1.1 函数和异常
..................

此模块定义了下列异常和函数：

 -- 例外: struct.error

     会在多种场合下被引发的异常；其参数为一个描述错误信息的字符串。

 -- 函数: struct.pack (format, v1, v2, ...)

     返回一个 bytes 对象，其中包含根据格式字符串 `format' 打包的值 `v1',
     `v2', ... 参数个数必须与格式字符串所要求的值完全匹配。

 -- 函数: struct.pack_into (format, buffer, offset, v1, v2, ...)

     根据格式字符串 `format' 打包 `v1', `v2', ... 等值并将打包的字节串写
     入可写缓冲区 `buffer' 从 `offset' 开始的位置。 请注意 `offset' 是必
     需的参数。

 -- 函数: struct.unpack (format, buffer)

     根据格式字符串 `format' 从缓冲区 `buffer' 解包（假定是由
     ‘pack(format, ...)’ 打包）。 结果为一个元组，即使其只包含一个条目。
     缓冲区的字节大小必须匹配格式所要求的大小，如 *note calcsize():
     1820. 所示。

 -- 函数: struct.unpack_from (format, buffer, offset=0)

     对 `buffer' 从位置 `offset' 开始根据格式字符串 `format' 进行解包。
     结果为一个元组，即使其中只包含一个条目。 缓冲区的字节大小从位置
     `offset' 开始必须至少为 *note calcsize(): 1820. 显示的格式所要求的
     大小。

 -- 函数: struct.iter_unpack (format, buffer)

     根据格式字符串 `format' 以迭代方式从缓冲区 `buffer' 解包。 此函数返
     回一个迭代器，它将从缓冲区读取相同大小的块直至其内容全部耗尽。 缓冲
     区的字节大小必须整数倍于格式所要求的大小，如 *note calcsize():
     1820. 所示。

     每次迭代将产生一个如格式字符串所指定的元组。

     3.4 新版功能.

 -- 函数: struct.calcsize (format)

     返回与格式字符串 `format' 相对应的结构的大小（亦即 ‘pack(format,
     ...)’ 所产生的字节串对象的大小）。


File: python.info,  Node: 格式字符串,  Next: 类<2>,  Prev: 函数和异常,  Up: struct --- 将字节串解读为打包的二进制数据

5.7.1.2 格式字符串
..................

格式字符串是用来在打包和解包数据时指定预期布局的机制。 它们使用指定被打
包/解包数据类型的 *note 格式字符: 1823. 进行构建。 此外，还有一些特殊字
符用来控制 *note 字节顺序，大小和对齐方式: 181c.。

* Menu:

* 字节顺序，大小和对齐方式::
* 格式字符::
* 例子: 例子<2>.


File: python.info,  Node: 字节顺序，大小和对齐方式,  Next: 格式字符,  Up: 格式字符串

5.7.1.3 字节顺序，大小和对齐方式
................................

默认情况下，C类型以机器的本机格式和字节顺序表示，并在必要时通过跳过填充
字节进行正确对齐（根据C编译器使用的规则）。

或者，根据下表，格式字符串的第一个字符可用于指示打包数据的字节顺序，大小
和对齐方式：

字符            字节顺序                     大小           对齐方式
                                                            
----------------------------------------------------------------------------
                                                            
‘@’             按原字节                     按原字节       按原字节
                                                            
                                                            
‘=’             按原字节                     标准           无
                                                            
                                                            
‘<’             小端                         标准           无
                                                            
                                                            
‘>’             大端                         标准           无
                                                            
                                                            
‘!’             网络（=大端）                标准           无
                                                            

如果第一个字符不是其中之一，则假定为 ‘'@'’ 。

本机字节顺序可能为大端或是小端，取决于主机系统的不同。 例如， Intel x86
和 AMD64 (x86-64) 是小端的；Motorola 68000 和 PowerPC G5 是大端的；ARM 和
Intel Itanium 具有可切换的字节顺序（双端）。 请使用 ‘sys.byteorder’ 来检
查你的系统字节顺序。

本机大小和对齐方式是使用 C 编译器的 ‘sizeof’ 表达式来确定的。 这总是会与
本机字节顺序相绑定。

标准大小仅取决于格式字符；请参阅 *note 格式字符: 1823. 部分中的表格。

请注意 ‘'@'’ 和 ‘'='’ 之间的区别：两个都使用本机字节顺序，但后者的大小和
对齐方式是标准化的。

形式 ‘'!'’ 代表网络字节顺序总是使用在 IETF RFC 1700(1) 中所定义的大端序
。

没有什么方式能指定非本机字节顺序（强制字节对调）；请正确选择使用 ‘'<'’ 或
‘'>'’。

注释:

  1. 填充只会在连续结构成员之间自动添加。 填充不会添加到已编码结构的开头
     和末尾。

  2. 当使用非本机大小和对齐方式即 ’<’, ’>’, ’=’, and ’!’ 时不会添加任何
     填充。

  3. 要将结构的末尾对齐到符合特定类型的对齐要求，请以该类型代码加重复计
     数的零作为格式结束。 参见 *note 例子: 1825.。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc1700


File: python.info,  Node: 格式字符,  Next: 例子<2>,  Prev: 字节顺序，大小和对齐方式,  Up: 格式字符串

5.7.1.4 格式字符
................

格式字符具有以下含义；C 和 Python 值之间的按其指定类型的转换应当是相当明
显的。 ‘标准大小’列是指当使用标准大小时以字节表示的已打包值大小；也就是
当格式字符串以 ‘'<'’, ‘'>'’, ‘'!'’ 或 ‘'='’ 之一开头的情况。 当使用本机
大小时，已打包值的大小取决于具体的平台。

格式         C 类型                         Python 类型              标准大小             注释
                                                                                          
-----------------------------------------------------------------------------------------------------------
                                                                                          
‘x’          填充字节                       无
                                            
                                                                                          
‘c’          ‘char’                         长度为 1 的字节串        1
                                                                     
                                                                                          
‘b’          ‘signed char’                  整数                     1                    (1), (2)
                                                                                          
                                                                                          
‘B’          ‘unsigned char’                整数                     1                    (2)
                                                                                          
                                                                                          
‘?’          ‘_Bool’                        bool                     1                    (1)
                                                                                          
                                                                                          
‘h’          ‘short’                        整数                     2                    (2)
                                                                                          
                                                                                          
‘H’          ‘unsigned short’               整数                     2                    (2)
                                                                                          
                                                                                          
‘i’          ‘int’                          整数                     4                    (2)
                                                                                          
                                                                                          
‘I’          ‘unsigned int’                 整数                     4                    (2)
                                                                                          
                                                                                          
‘l’          ‘long’                         整数                     4                    (2)
                                                                                          
                                                                                          
‘L’          ‘unsigned long’                整数                     4                    (2)
                                                                                          
                                                                                          
‘q’          ‘long long’                    整数                     8                    (2)
                                                                                          
                                                                                          
‘Q’          ‘unsigned long long’           整数                     8                    (2)
                                                                                          
                                                                                          
‘n’          ‘ssize_t’                      整数                                          (3)
                                                                                          
                                                                                          
‘N’          ‘size_t’                       整数                                          (3)
                                                                                          
                                                                                          
‘e’          (6)                            float                    2                    (4)
                                                                                          
                                                                                          
‘f’          ‘float’                        float                    4                    (4)
                                                                                          
                                                                                          
‘d’          ‘double’                       float                    8                    (4)
                                                                                          
                                                                                          
‘s’          ‘char[]’                       字节串
                                            
                                                                                          
‘p’          ‘char[]’                       字节串
                                            
                                                                                          
‘P’          ‘void *’                       整数                                          (5)
                                                                                          

在 3.3 版更改: 增加了对 ‘'n'’ 和 ‘'N'’ 格式的支持

在 3.6 版更改: 添加了对 ‘'e'’ 格式的支持。

注释:

  1. 
     ‘'?'’ 转换码对应于 C99 定义的 ‘_Bool’ 类型。 如果此类型不可用，则使
     用 ‘char’ 来模拟。 在标准模式下，它总是以一个字节表示。

  2. 当尝试使用任何整数转换码打包一个非整数时，如果该非整数具有 *note
     __index__(): 18b. 方法，则会在打包之前调用该方法将参数转换为一个整
     数。

     在 3.2 版更改: 为非整数使用 *note __index__(): 18b. 方法是 3.2 版的
     新增特性。

  3. ‘'n'’ 和 ‘'N'’ 转换码仅对本机大小可用（选择为默认或使用 ‘'@'’ 字节
     顺序字符）。 对于标准大小，你可以使用适合你的应用的任何其他整数格式
     。

  4. 对于 ‘'f'’, ‘'d'’ 和 ‘'e'’ 转换码，打包表示形式将使用 IEEE 754
     binary32, binary64 或 binary16 格式 (分别对应于 ‘'f'’, ‘'d'’ 或
     ‘'e'’)，无论平台使用何种浮点格式。

  5. ‘'P'’ 格式字符仅对本机字节顺序可用（选择为默认或使用 ‘'@'’ 字节顺序
     字符）。 字节顺序字符 ‘'='’ 选择使用基于主机系统的小端或大端排序。
     struct 模块不会将其解读为本机排序，因此 ‘'P'’ 格式将不可用。

  6. IEEE 754 binary16 "半精度" 类型是在 IEEE 754 标准(1) 的 2008 修订版
     中引入的。 它包含一个符号位，5 个指数位和 11 个精度位（明确存储 10
     位），可以完全精确地表示大致范围在 ‘6.1e-05’ 和 ‘6.5e+04’ 之间的数
     字。 此类型并不被 C 编译器广泛支持：在一台典型的机器上，可以使用
     unsigned short 进行存储，但不会被用于数学运算。 请参阅维基百科页面
     half-precision floating-point format(2) 了解详情。

格式字符之前可以带有整数重复计数。 例如，格式字符串 ‘'4h'’ 的含义与
‘'hhhh'’ 完全相同。

格式之间的空白字符会被忽略；但是计数及其格式字符中不可有空白字符。

对于 ‘'s'’ 格式字符，计数会被解析为字节的长度，而不是像其他格式字符那样
的重复计数；例如，‘'10s'’ 表示一个 10 字节的字节串，而 ‘'10c'’ 表示 10 个
字符。 如果未给出计数，则默认值为 1。 对于打包操作，字节串会被适当地截断
或填充空字节以符合要求。 对于解包操作，结果字节对象总是恰好具有指定数量
的字节。 作为特殊情况，‘'0s'’ 表示一个空字符串（而 ‘'0c'’ 表示 0 个字符
）。

当使用某一种整数格式 (‘'b'’, ‘'B'’, ‘'h'’, ‘'H'’, ‘'i'’, ‘'I'’, ‘'l'’,
‘'L'’, ‘'q'’, ‘'Q'’) 打包值 ‘x’ 时，如果 ‘x’ 在该格式的有效范围之外则将
引发 *note struct.error: cbc.。

在 3.1 版更改: 在 3.0 中，某些包装了超范围值的整数格式会引发 *note
DeprecationWarning: 279. 而不是 *note struct.error: cbc.。

‘'p'’ 格式字符用于编码“Pascal 字符串”，即存储在由计数指定的 `固定长度字
节' 中的可变长度短字符串。 所存储的第一个字节为字符串长度或 255 中的较小
值。 之后是字符串对应的字节。 如果传入 *note pack(): c13. 的字符串过长（
超过计数值减 1），则只有字符串前 ‘count-1’ 个字节会被存储。 如果字符串短
于 ‘count-1’，则会填充空字节以使得恰好使用了 count 个字节。 请注意对于
*note unpack(): 1313.，‘'p'’ 格式字符会消耗 ‘count’ 个字节，但返回的字符
串永远不会包含超过 255 个字节。

对于 ‘'?'’ 格式字符，返回值为 *note True: 4a1. 或 *note False: 390.。 在
打包时将会使用参数对象的逻辑值。 以本机或标准 bool 类型表示的 0 或 1 将
被打包，任何非零值在解包时将为 ‘True’。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/IEEE_floating_point#IEEE_754-2008

   (2) 
https://en.wikipedia.org/wiki/Half-precision_floating-point_format


File: python.info,  Node: 例子<2>,  Prev: 格式字符,  Up: 格式字符串

5.7.1.5 例子
............

     注解: 所有示例都假定使用一台大端机器的本机字节顺序、大小和对齐方式
     。

打包/解包三个整数的基础示例:

     >>> from struct import *
     >>> pack('hhl', 1, 2, 3)
     b'\x00\x01\x00\x02\x00\x00\x00\x03'
     >>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
     (1, 2, 3)
     >>> calcsize('hhl')
     8

解包的字段可通过将它们赋值给变量或将结果包装为一个具名元组来命名:

     >>> record = b'raymond   \x32\x12\x08\x01\x08'
     >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)

     >>> from collections import namedtuple
     >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
     >>> Student._make(unpack('<10sHHb', record))
     Student(name=b'raymond   ', serialnum=4658, school=264, gradelevel=8)

格式字符的顺序可能对大小产生影响，因为满足对齐要求所需的填充是不同的:

     >>> pack('ci', b'*', 0x12131415)
     b'*\x00\x00\x00\x12\x13\x14\x15'
     >>> pack('ic', 0x12131415, b'*')
     b'\x12\x13\x14\x15*'
     >>> calcsize('ci')
     8
     >>> calcsize('ic')
     5

以下格式 ‘'llh0l'’ 指定在末尾有两个填充字节，假定 long 类型按 4 个字节的
边界对齐:

     >>> pack('llh0l', 1, 2, 3)
     b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'

这仅当本机大小和对齐方式生效时才会起作用；标准大小和对齐方式并不会强制进
行任何对齐。

参见
....

模块 *note array: 7.

     被打包为二进制存储的同质数据。

模块 *note xdrlib: 133.

     打包和解包 XDR 数据。


File: python.info,  Node: 类<2>,  Prev: 格式字符串,  Up: struct --- 将字节串解读为打包的二进制数据

5.7.1.6 类
..........

*note struct: f9. 模块还定义了以下类型：

 -- 类: struct.Struct (format)

     返回一个新的 Struct 对象，它会根据格式字符串 `format' 来写入和读取
     二进制数据。 一次性地创建 Struct 对象并调用其方法相比使用同样的格式
     调用 *note struct: f9. 函数更为高效，因为这样格式字符串只需被编译一
     次。

          注解: 传递给 *note Struct: 181d. 和模块层级函数的已编译版最新
          格式字符串会被缓存，因此只使用少量格式字符串的程序无需担心重用
          单独的 *note Struct: 181d. 实例。

     已编译的 Struct 对象支持以下方法和属性：

      -- 方法: pack (v1, v2, ...)

          等价于 *note pack(): c13. 函数，使用了已编译的格式。
          (‘len(result)’ 将等于 *note size: 182b.。)

      -- 方法: pack_into (buffer, offset, v1, v2, ...)

          等价于 *note pack_into(): 181f. 函数，使用了已编译的格式。

      -- 方法: unpack (buffer)

          等价于 *note unpack(): 1313. 函数，使用了已编译的格式。 缓冲区
          的字节大小必须等于 *note size: 182b.。

      -- 方法: unpack_from (buffer, offset=0)

          等价于 *note unpack_from(): 1821. 函数，使用了已编译的格式。 缓
          冲区的字节大小从位置 `offset' 开始必须至少为 *note size:
          182b.。

      -- 方法: iter_unpack (buffer)

          等价于 *note iter_unpack(): 8e0. 函数，使用了已编译的格式。 缓
          冲区的大小必须为 *note size: 182b. 的整数倍。

          3.4 新版功能.

      -- 属性: format

          用于构造此 Struct 对象的格式字符串。

          在 3.7 版更改: 格式字符串类型现在是 *note str: 339. 而不再是
          *note bytes: 33a.。

      -- 属性: size

          计算出对应于 *note format: 4e3. 的结构大小（亦即 *note pack():
          c13. 方法所产生的字节串对象的大小）。


File: python.info,  Node: codecs --- 编解码器注册和相关基类,  Prev: struct --- 将字节串解读为打包的二进制数据,  Up: 二进制数据服务

5.7.2 ‘codecs’ — 编解码器注册和相关基类
---------------------------------------

`源代码：' Lib/codecs.py(1)

__________________________________________________________________

这个模块定义了标准 Python 编解码器（编码器和解码器）的基类，并提供接口用
来访问内部的 Python 编解码器注册表，该注册表负责管理编解码器和错误处理的
查找过程。 大多数标准编解码器都属于 *note 文本编码: 160b.，它们可将文本
编码为字节串，但也提供了一些编解码器可将文本编码为文本，以及字节串编码为
字节串。 自定义编解码器可以在任意类型间进行编码和解码，但某些模块特性仅
适用于 *note 文本编码: 160b. 或将数据编码为 ‘字节串’ 的编解码器。

该模块定义了以下用于使用任何编解码器进行编码和解码的函数:

 -- 函数: codecs.encode (obj, encoding='utf-8', errors='strict')

     使用为 `encoding' 注册的编解码器对 `obj' 进行编码。

     可以给定 `Errors' 以设置所需要的错误处理方案。 默认的错误处理方案
     ‘'strict'’ 表示编码错误将引发 *note ValueError: 1fc. (或更特定编解
     码器相关的子类，例如 *note UnicodeEncodeError: 1fd.)。 请参阅 *note
     编解码器基类: 1832. 了解有关编解码器错误处理的更多信息。

 -- 函数: codecs.decode (obj, encoding='utf-8', errors='strict')

     使用为 `encoding' 注册的编解码器对 `obj' 进行解码。

     可以给定 `Errors' 以设置所需要的错误处理方案。 默认的错误处理方案
     ‘'strict'’ 表示编码错误将引发 *note ValueError: 1fc. (或更特定编解
     码器相关的子类，例如 *note UnicodeDecodeError: 1fe.)。 请参阅 *note
     编解码器基类: 1832. 了解有关编解码器错误处理的更多信息。

每种编解码器的完整细节也可以直接查找获取：

 -- 函数: codecs.lookup (encoding)

     在 Python 编解码器注册表中查找编解码器信息，并返回一个 *note
     CodecInfo: 1833. 对象，其定义见下文。

     首先将会在注册表缓存中查找编码，如果未找到，则会扫描注册的搜索函数
     列表。 如果没有找到 *note CodecInfo: 1833. 对象，则将引发 *note
     LookupError: 166d.。 否则，*note CodecInfo: 1833. 对象将被存入缓存
     并返回给调用者。

 -- 类: codecs.CodecInfo (encode, decode, streamreader=None,
          streamwriter=None, incrementalencoder=None,
          incrementaldecoder=None, name=None)

     查找编解码器注册表所得到的编解码器细节信息。 构造器参数将保存为同名
     的属性：

      -- 属性: name

          编码名称

      -- 属性: encode
      -- 属性: decode

          无状态的编码和解码函数。 它们必须是具有与 Codec 的 *note
          encode(): 1837. 和 *note decode(): 1838. 方法相同接口的函数或
          方法 (参见 *note Codec 接口: 1839.)。 这些函数或方法应当工作于
          无状态的模式。

      -- 属性: incrementalencoder
      -- 属性: incrementaldecoder

          增量式的编码器和解码器类或工厂函数。 这些函数必须分别提供由基
          类 *note IncrementalEncoder: 183c. 和 *note
          IncrementalDecoder: 183d. 所定义的接口。 增量式编解码器可以保
          持状态。

      -- 属性: streamwriter
      -- 属性: streamreader

          流式写入器和读取器类或工厂函数。 这些函数必须分别提供由基类
          *note StreamWriter: 1840. 和 *note StreamReader: 1841. 所定义
          的接口。 流式编解码器可以保持状态。

为了简化对各种编解码器组件的访问，本模块提供了以下附加函数，它们使用
*note lookup(): 1711. 来执行编解码器查找：

 -- 函数: codecs.getencoder (encoding)

     查找给定编码的编解码器并返回其编码器函数。

     在编码无法找到时将引发 *note LookupError: 166d.。

 -- 函数: codecs.getdecoder (encoding)

     查找给定编码的编解码器并返回其解码器函数。

     在编码无法找到时将引发 *note LookupError: 166d.。

 -- 函数: codecs.getincrementalencoder (encoding)

     查找给定编码的编解码器并返回其增量式编码器类或工厂函数。

     在编码无法找到或编解码器不支持增量式编码器时将引发 *note
     LookupError: 166d.。

 -- 函数: codecs.getincrementaldecoder (encoding)

     查找给定编码的编解码器并返回其增量式解码器类或工厂函数。

     在编码无法找到或编解码器不支持增量式解码器时将引发 *note
     LookupError: 166d.。

 -- 函数: codecs.getreader (encoding)

     查找给定编码的编解码器并返回其 *note StreamReader: 1841. 类或工厂函
     数。

     在编码无法找到时将引发 *note LookupError: 166d.。

 -- 函数: codecs.getwriter (encoding)

     查找给定编码的编解码器并返回其 *note StreamWriter: 1840. 类或工厂函
     数。

     在编码无法找到时将引发 *note LookupError: 166d.。

自定义编解码器的启用是通过注册适当的编解码器搜索函数：

 -- 函数: codecs.register (search_function)

     注册一个编解码器搜索函数。 搜索函数预期接收一个参数，即全部以小写字
     母表示的编码名称，并返回一个 *note CodecInfo: 1833. 对象。 在搜索函
     数无法找到给定编码的情况下，它应当返回 ‘None’。

          注解: 搜索函数的注册目前是不可逆的，这在某些情况下可能导致问题
          ，例如单元测试或模块重载等。

虽然内置的 *note open(): 4f8. 和相关联的 *note io: a2. 模块是操作已编码
文本文件的推荐方式，但本模块也提供了额外的工具函数和类，允许在操作二进制
文件时使用更多各类的编解码器：

 -- 函数: codecs.open (filename, mode='r', encoding=None,
          errors='strict', buffering=-1)

     使用给定的 `mode' 打开已编码的文件并返回一个 *note
     StreamReaderWriter: 1849. 的实例，提供透明的编码/解码。 默认的文件
     模式为 ‘'r'’，表示以读取模式打开文件。

          注解: 下层的已编码文件总是以二进制模式打开。 在读取和写入时不
          会自动执行 ‘'\n'’ 的转换。 `mode' 参数可以是内置 *note open():
          4f8. 函数所接受的任意二进制模式；‘'b'’ 会被自动添加。

     `encoding' 指定文件所要使用的编码格式。 允许任何编码为字节串或从字
     节串解码的编码格式，而文件方法所支持的数据类型则取决于所使用的编解
     码器。

     可以指定 `errors' 来定义错误处理方案。 默认值 ‘'strict'’ 表示在出现
     编码错误时引发 *note ValueError: 1fc.。

     `buffering' 的含义与内置 *note open(): 4f8. 函数中的相同。 默认值
     -1 表示将使用默认的缓冲区大小。

 -- 函数: codecs.EncodedFile (file, data_encoding, file_encoding=None,
          errors='strict')

     返回一个 *note StreamRecoder: fdd. 实例，它提供了 `file' 的透明转码
     包装版本。 当包装版本被关闭时原始文件也会被关闭。

     写入已包装文件的数据会根据给定的 `data_encoding' 解码，然后以使用
     `file_encoding' 的字节形式写入原始文件。 从原始文件读取的字节串将根
     据 `file_encoding' 解码，其结果将使用 `data_encoding' 进行编码。

     如果 `file_encoding' 未给定，则默认为 `data_encoding'。

     可以指定 `errors' 来定义错误处理方案。 默认值 ‘'strict'’ 表示在出现
     编码错误时引发 *note ValueError: 1fc.。

 -- 函数: codecs.iterencode (iterator, encoding, errors='strict',
          **kwargs)

     使用增量式编码器通过迭代来编码由 `iterator' 所提供的输入。 此函数属
     于 *note generator: 9aa.。 `errors' 参数（以及任何其他关键字参数）
     会被传递给增量式编码器。

     此函数要求编解码器接受 *note str: 339. 对象形式的文本进行编码。 因
     此它不支持字节到字节的编码器，例如 ‘base64_codec’。

 -- 函数: codecs.iterdecode (iterator, encoding, errors='strict',
          **kwargs)

     使用增量式解码器通过迭代来解码由 `iterator' 所提供的输入。 此函数属
     于 *note generator: 9aa.。 `errors' 参数（以及任何其他关键字参数）
     会被传递给增量式解码器。

     此函数要求编解码器接受 *note bytes: 33a. 对象进行解码。 因此它不支
     持文本到文本的编码器，例如 ‘rot_13’，但是 ‘rot_13’ 可以通过同样效果
     的 *note iterencode(): 184b. 来使用。

本模块还提供了以下常量，适用于读取和写入依赖于平台的文件：

 -- 数据: codecs.BOM
 -- 数据: codecs.BOM_BE
 -- 数据: codecs.BOM_LE
 -- 数据: codecs.BOM_UTF8
 -- 数据: codecs.BOM_UTF16
 -- 数据: codecs.BOM_UTF16_BE
 -- 数据: codecs.BOM_UTF16_LE
 -- 数据: codecs.BOM_UTF32
 -- 数据: codecs.BOM_UTF32_BE
 -- 数据: codecs.BOM_UTF32_LE

     这些常量定义了多种字节序列，即一些编码格式的 Unicode 字节顺序标记（
     BOM）。 它们在 UTF-16 和 UTF-32 数据流中被用以指明所使用的字节顺序
     ，并在 UTF-8 中被用作 Unicode 签名。 *note BOM_UTF16: 1851. 是
     *note BOM_UTF16_BE: 1852. 或 *note BOM_UTF16_LE: 1853.，具体取决于
     平台的本机字节顺序，*note BOM: 184d. 是 *note BOM_UTF16: 1851. 的别
     名, *note BOM_LE: 184f. 是 *note BOM_UTF16_LE: 1853. 的别名，*note
     BOM_BE: 184e. 是 *note BOM_UTF16_BE: 1852. 的别名。 其他序列则表示
     UTF-8 和 UTF-32 编码格式中的 BOM。

* Menu:

* 编解码器基类::
* 编码格式与 Unicode::
* 标准编码::
* Python 专属的编码格式::
* encodings.idna: encodings idna --- 应用程序中的国际化域名. 应用程序中的国际化域名
* encodings.mbcs: encodings mbcs --- Windows ANSI代码页. Windows ANSI代码页
* encodings.utf_8_sig: encodings utf_8_sig --- 带BOM签名的UTF-8编解码器. 带BOM签名的UTF-8编解码器

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/codecs.py


File: python.info,  Node: 编解码器基类,  Next: 编码格式与 Unicode,  Up: codecs --- 编解码器注册和相关基类

5.7.2.1 编解码器基类
....................

*note codecs: 1c. 模块定义了一系列基类用来定义配合编解码器对象进行工作的
接口，并且也可用作定制编解码器实现的基础。

每种编解码器必须定义四个接口以便用作 Python 中的编解码器：无状态编码器、
无状态解码器、流读取器和流写入器。 流读取器和写入器通常会重用无状态编码
器/解码器来实现文件协议。 编解码器作者还需要定义编解码器将如何处理编码和
解码错误。
* Menu:

* 错误处理方案::
* 无状态的编码和解码::
* 增量式的编码和解码::
* 流式的编码和解码::


File: python.info,  Node: 错误处理方案,  Next: 无状态的编码和解码,  Up: 编解码器基类

5.7.2.2 错误处理方案
....................

为了简化和标准化错误处理，编解码器可以通过接受 `errors' 字符串参数来实现
不同的错误处理方案。 所有标准的 Python 编解码器都定义并实现了以下字符串
值：

值                            含义
                              
----------------------------------------------------------------------------------
                              
‘'strict'’                    引发 *note UnicodeError: c43. (或其子类)；这是默
                              认的方案。 在 *note strict_errors(): 185a. 中实现
                              。
                              
                              
‘'ignore'’                    忽略错误格式的数据并且不加进一步通知就继续执行。
                              在 *note ignore_errors(): 185b. 中实现。
                              

以下错误处理方案仅适用于 *note 文本编码: 160b.:

值                            含义
                              
----------------------------------------------------------------------------------
                              
‘'replace'’                   使用适当的替换标记进行替换；Python 内置编解码器将
                              在解码时使用官方 ‘U+FFFD’ 替换字符，而在编码时使
                              用 ’?’ 。 在 *note replace_errors(): 185c. 中实现
                              。
                              
                              
‘'xmlcharrefreplace'’         使用适当的 XML 字符引用进行替换（仅在编码时）。 在
                              *note xmlcharrefreplace_errors(): 185d. 中实现。
                              
                              
‘'backslashreplace'’          使用带反斜杠的转义序列进行替换。 在
                              *note backslashreplace_errors(): 185e. 中实现。
                              
                              
‘'namereplace'’               使用 ‘\N{...}’ 转义序列进行替换（仅在编码时）。 在
                              *note namereplace_errors(): 185f. 中实现。
                              
                              
‘'surrogateescape'’           在解码时，将字节替换为 ‘U+DC80’ 至 ‘U+DCFF’ 范围
                              内的单个代理代码。 当在编码数据时使用
                              ‘'surrogateescape'’ 错误处理方案时，此代理将被转
                              换回相同的字节。 （请参阅 PEP 383(1) 了解详情。）
                              

此外，以下错误处理方案被专门用于指定的编解码器：

值                      编解码器                     含义
                                                     
-----------------------------------------------------------------------------------------------------
                                                     
‘'surrogatepass'’       utf-8, utf-16, utf-32,       允许编码和解码代理代码。 这些编解码器通常会将
                        utf-16-be, utf-16-le,        出现的代理代码视为错误。
                        utf-32-be, utf-32-le         
                        

3.1 新版功能: ‘'surrogateescape'’ 和 ‘'surrogatepass'’ 错误处理方案。

在 3.4 版更改: ‘'surrogatepass'’ 错误处理方案现在适用于 utf-16* 和
utf-32* 编解码器。

3.5 新版功能: ‘'namereplace'’ 错误处理方案。

在 3.5 版更改: ‘'backslashreplace'’ 错误处理方案现在适用于解码和转换。

允许的值集合可以通过注册新命名的错误处理方案来扩展：

 -- 函数: codecs.register_error (name, error_handler)

     在名称 `name' 之下注册错误处理函数 `error_handler'。 当 `name' 被指
     定为错误形参时，`error_handler' 参数所指定的对象将在编码和解码期间
     发生错误的情况下被调用，

     对于编码操作，将会调用 `error_handler' 并传入一个 *note
     UnicodeEncodeError: 1fd. 实例，其中包含有关错误位置的信息。 错误处
     理程序必须引发此异常或别的异常，或者也可以返回一个元组，其中包含输
     入的不可编码部分的替换对象，以及应当继续进行编码的位置。 替换对象可
     以为 *note str: 339. 或 *note bytes: 33a. 类型。 如果替换对象为字节
     串，编码器将简单地将其复制到输出缓冲区。 如果替换对象为字符串，编码
     器将对替换对象进行编码。 对原始输入的编码操作会在指定位置继续进行。
     负的位置值将被视为相对于输入字符串的末尾。 如果结果位置超出范围则将
     引发 *note IndexError: e7d.。

     解码和转换的做法很相似，不同之处在于将把 *note UnicodeDecodeError:
     1fe. 或 *note UnicodeTranslateError: 1725. 传给处理程序，并且来自错
     误处理程序的替换对象将被直接放入输出。

之前注册的错误处理方案（包括标准错误处理方案）可通过名称进行查找：

 -- 函数: codecs.lookup_error (name)

     返回之前在名称 `name' 之下注册的错误处理方案。

     在处理方案无法找到时将引发 *note LookupError: 166d.。

以下标准错误处理方案也可通过模块层级函数的方式来使用：

 -- 函数: codecs.strict_errors (exception)

     实现 ‘'strict'’ 错误处理方案：每个编码或解码错误都会引发 *note
     UnicodeError: c43.。

 -- 函数: codecs.replace_errors (exception)

     实现 ‘'replace'’ 错误处理方案 (仅用于 *note 文本编码: 160b.)：编码
     错误替换为 ‘'?'’ (并由编解码器编码)，解码错误替换为 ‘'\ufffd'’
     (Unicode 替换字符)。

 -- 函数: codecs.ignore_errors (exception)

     实现 ‘'ignore'’ 错误处理方案：忽略错误格式的数据并且不加进一步通知
     就继续执行。

 -- 函数: codecs.xmlcharrefreplace_errors (exception)

     实现 ‘'xmlcharrefreplace'’ 错误处理方案 (仅用于 *note 文本编码:
     160b. 的编码过程)：不可编码的字符将以适当的 XML 字符引用进行替换。

 -- 函数: codecs.backslashreplace_errors (exception)

     实现 ‘'backslashreplace'’ 错误处理方案 (仅用于 *note 文本编码:
     160b.)：错误格式的数据将以带反斜杠的转义序列进行替换。

 -- 函数: codecs.namereplace_errors (exception)

     实现 ‘'namereplace'’ 错误处理方案 (仅用于 *note 文本编码: 160b. 的
     编码过程)：不可编码的字符将以 ‘\N{...}’ 转义序列进行替换。

     3.5 新版功能.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0383


File: python.info,  Node: 无状态的编码和解码,  Next: 增量式的编码和解码,  Prev: 错误处理方案,  Up: 编解码器基类

5.7.2.3 无状态的编码和解码
..........................

基本 ‘Codec’ 类定义了这些方法，同时还定义了无状态编码器和解码器的函数接
口：

 -- 方法: Codec.encode (input[, errors])

     编码 `input' 对象并返回一个元组 (输出对象, 消耗长度)。 例如，*note
     text encoding: 160b. 会使用特定的字符集编码格式 (例如 ‘cp1252’ 或
     ‘iso-8859-1’) 将字符串转换为字节串对象。

     `errors' 参数定义了要应用的错误处理方案。 默认为 ‘'strict'’ 处理方
     案。

     此方法不一定会在 ‘Codec’ 实例中保存状态。 可使用必须保存状态的
     *note StreamWriter: 1840. 作为编解码器以便高效地进行编码。

     编码器必须能够处理零长度的输入并在此情况下返回输出对象类型的空对象
     。

 -- 方法: Codec.decode (input[, errors])

     解码 `input' 对象并返回一个元组 (输出对象, 消耗长度)。 例如，*note
     text encoding: 160b. 的解码操作会使用特定的字符集编码格式将字节串对
     象转换为字符串对象。

     对于文本编码格式和字节到字节编解码器，`input' 必须为一个字节串对象
     或提供了只读缓冲区接口的对象 – 例如，缓冲区对象和映射到内存的文件。

     `errors' 参数定义了要应用的错误处理方案。 默认为 ‘'strict'’ 处理方
     案。

     此方法不一定会在 ‘Codec’ 实例中保存状态。 可使用必须保存状态的
     *note StreamReader: 1841. 作为编解码器以便高效地进行解码。

     解码器必须能够处理零长度的输入并在此情况下返回输出对象类型的空对象
     。


File: python.info,  Node: 增量式的编码和解码,  Next: 流式的编码和解码,  Prev: 无状态的编码和解码,  Up: 编解码器基类

5.7.2.4 增量式的编码和解码
..........................

*note IncrementalEncoder: 183c. 和 *note IncrementalDecoder: 183d. 类提
供了增量式编码和解码的基本接口。 对输入的编码/解码不是通过对无状态编码器
/解码器的一次调用，而是通过对增量式编码器/解码器的 *note encode():
1862./*note decode(): 1863. 方法的多次调用。 增量式编码器/解码器会在方法
调用期间跟踪编码/解码过程。

调用 *note encode(): 1862./*note decode(): 1863. 方法后的全部输出相当于
将所有通过无状态编码器/解码器进行编码/解码的单个输入连接在一起所得到的输
出。

* Menu:

* IncrementalEncoder 对象::
* IncrementalDecoder 对象::


File: python.info,  Node: IncrementalEncoder 对象,  Next: IncrementalDecoder 对象,  Up: 增量式的编码和解码

5.7.2.5 IncrementalEncoder 对象
...............................

*note IncrementalEncoder: 183c. 类用来对一个输入进行分步编码。 它定义了
以下方法，每个增量式编码器都必须定义这些方法以便与 Python 编解码器注册表
相兼容。

 -- 类: codecs.IncrementalEncoder (errors='strict')

     *note IncrementalEncoder: 183c. 实例的构造器。

     所有增量式编码器必须提供此构造器接口。 它们可以自由地添加额外的关键
     字参数，但只有在这里定义的参数才会被 Python 编解码器注册表所使用。

     *note IncrementalEncoder: 183c. 可以通过提供 `errors' 关键字参数来
     实现不同的错误处理方案。 可用的值请参阅 *note 错误处理方案: 1371.。

     `errors' 参数将被赋值给一个同名的属性。 通过对此属性赋值就可以在
     *note IncrementalEncoder: 183c. 对象的生命期内在不同的错误处理策略
     之间进行切换。

      -- 方法: encode (object[, final])

          编码 `object' (会将编码器的当前状态纳入考虑) 并返回已编码的结
          果对象。 如果这是对 *note encode(): 80b. 的最终调用则 `final'
          必须为真值（默认为假值）。

      -- 方法: reset ()

          将编码器重置为初始状态。 输出将被丢弃：调用 ‘.encode(object,
          final=True)’，在必要时传入一个空字节串或字符串，重置编码器并得
          到输出。

      -- 方法: getstate ()

          返回编码器的当前状态，该值必须为一个整数。 实现应当确保 ‘0’ 是
          最常见的状态。 （比整数更复杂的状态表示可以通过编组/选择状态并
          将结果字符串的字节数据编码为整数来转换为一个整数值）。

      -- 方法: setstate (state)

          将编码器的状态设为 `state'。 `state' 必须为 *note getstate():
          1867. 所返回的一个编码器状态。


File: python.info,  Node: IncrementalDecoder 对象,  Prev: IncrementalEncoder 对象,  Up: 增量式的编码和解码

5.7.2.6 IncrementalDecoder 对象
...............................

*note IncrementalDecoder: 183d. 类用来对一个输入进行分步解码。 它定义了
以下方法，每个增量式解码器都必须定义这些方法以便与 Python 编解码器注册表
相兼容。

 -- 类: codecs.IncrementalDecoder (errors='strict')

     *note IncrementalDecoder: 183d. 实例的构造器。

     所有增量式解码器必须提供此构造器接口。 它们可以自由地添加额外的关键
     字参数，但只有在这里定义的参数才会被 Python 编解码器注册表所使用。

     *note IncrementalDecoder: 183d. 可以通过提供 `errors' 关键字参数来
     实现不同的错误处理方案。 可用的值请参阅 *note 错误处理方案: 1371.。

     `errors' 参数将被赋值给一个同名的属性。 通过对此属性赋值就可以在
     *note IncrementalDecoder: 183d. 对象的生命期内在不同的错误处理策略
     之间进行切换。

      -- 方法: decode (object[, final])

          解码 `object' (会将解码器的当前状态纳入考虑) 并返回已解码的结
          果对象。 如果这是对 *note decode(): 80c. 的最终调用则 `final'
          必须为真值（默认为假值）。 如果 `final' 为真值则解码器必须对输
          入进行完全解码并且必须 刷新所有缓冲区。 如果这无法做到（例如由
          于在输入结束时字节串序列不完整）则它必须像在无状态的情况下那样
          初始化错误处理（这可能引发一个异常）。

      -- 方法: reset ()

          将解码器重置为初始状态。

      -- 方法: getstate ()

          返回解码器的当前状态。 这必须为一个二元组，第一项必须是包含尚
          未解码的输入的缓冲区。 第二项必须为一个整数，可以表示附加状态
          信息。 （实现应当确保 ‘0’ 是最常见的附加状态信息。） 如果此附
          加状态信息为 ‘0’ 则必须可以将解码器设为没有已缓冲输入并且以
          ‘0’ 作为附加状态信息，以便将先前已缓冲的输入馈送到解码器使其返
          回到先前的状态而不产生任何输出。 （比整数更复杂的附加状态信息
          可以通过编组/选择状态信息并将结果字符串的字节数据编码为整数来
          转换为一个整数值。）

      -- 方法: setstate (state)

          将解码器的状态设为 `state'。 `state' 必须为 *note getstate():
          186c. 所返回的一个解码器状态。


File: python.info,  Node: 流式的编码和解码,  Prev: 增量式的编码和解码,  Up: 编解码器基类

5.7.2.7 流式的编码和解码
........................

*note StreamWriter: 1840. 和 *note StreamReader: 1841. 类提供了一些泛用
工作接口，可被用来非常方便地实现新的编码格式子模块。 请参阅
‘encodings.utf_8’ 中的示例了解如何做到这一点。

* Menu:

* StreamWriter 对象::
* StreamReader 对象::
* StreamReaderWriter 对象::
* StreamRecoder 对象::


File: python.info,  Node: StreamWriter 对象,  Next: StreamReader 对象,  Up: 流式的编码和解码

5.7.2.8 StreamWriter 对象
.........................

*note StreamWriter: 1840. 类是 ‘Codec’ 的子类，它定义了以下方法，每个流
式写入器都必须定义这些方法以便与 Python 编解码器注册表相兼容。

 -- 类: codecs.StreamWriter (stream, errors='strict')

     *note StreamWriter: 1840. 实例的构造器。

     所有流式写入器必须提供此构造器接口。 它们可以自由地添加额外的关键字
     参数，但只有在这里定义的参数才会被 Python 编解码器注册表所使用。

     `stream' 参数必须为一个基于特定编解码器打开用于写入文本或二进制数据
     的文件类对象。

     *note StreamWriter: 1840. 可以通过提供 `errors' 关键字参数来实现不
     同的错误处理方案。 请参阅 *note 错误处理方案: 1371. 了解下层的流式
     编解码器可支持的标准错误处理方案。

     `errors' 参数将被赋值给一个同名的属性。 通过对此属性赋值就可以在
     *note StreamWriter: 1840. 对象的生命期内在不同的错误处理策略之间进
     行切换。

      -- 方法: write (object)

          将编码后的对象内容写入到流。

      -- 方法: writelines (list)

          将拼接后的字符串列表写入到流（可能通过重用 *note write():
          1871. 方法）。 标准的字节到字节编解码器不支持此方法。

      -- 方法: reset ()

          刷新并重置用于保持状态的编解码器缓冲区。

          调用此方法应当确保在干净的状态下放入输出数据，以允许直接添加新
          的干净数据而无须重新扫描整个流来恢复状态。

除了上述的方法，*note StreamWriter: 1840. 还必须继承来自下层流的所有其他
方法和属性。


File: python.info,  Node: StreamReader 对象,  Next: StreamReaderWriter 对象,  Prev: StreamWriter 对象,  Up: 流式的编码和解码

5.7.2.9 StreamReader 对象
.........................

*note StreamReader: 1841. 类是 ‘Codec’ 的子类，它定义了以下方法，每个流
式读取器都必须定义这些方法以便与 Python 编解码器注册表相兼容。

 -- 类: codecs.StreamReader (stream, errors='strict')

     *note StreamReader: 1841. 实例的构造器。

     所有流式读取器必须提供此构造器接口。 它们可以自由地添加额外的关键字
     参数，但只有在这里定义的参数才会被 Python 编解码器注册表所使用。

     `stream' 参数必须为一个基于特定编解码器打开用于读取文本或二进制数据
     的文件类对象。

     *note StreamReader: 1841. 可以通过提供 `errors' 关键字参数来实现不
     同的错误处理方案。 请参阅 *note 错误处理方案: 1371. 了解下层的流式
     编解码器可支持的标准错误处理方案。

     `errors' 参数将被赋值给一个同名的属性。 通过对此属性赋值就可以在
     *note StreamReader: 1841. 对象的生命期内在不同的错误处理策略之间进
     行切换。

     `errors' 参数所允许的值集合可以使用 *note register_error(): dfd. 来
     扩展。

      -- 方法: read ([size[, chars[, firstline]]])

          解码来自流的数据并返回结果对象。

          `chars' 参数指明要返回的解码后码位或字节数量。 *note read():
          1876. 方法绝不会返回超出请求数量的数据，但如果可用数量不足，它
          可能返回少于请求数量的数据。

          `size' 参数指明要读取并解码的已编码字节或码位的最大数量近似值
          。 解码器可以适当地修改此设置。 默认值 -1 表示尽可能多地读取并
          解码。 此形参的目的是防止一次性解码过于巨大的文件。

          `firstline' 旗标指明如果在后续行发生解码错误，则仅返回第一行就
          足够了。

          此方法应当使用“贪婪”读取策略，这意味着它应当在编码格式定义和给
          定大小所允许的情况下尽可能多地读取数据，例如，如果在流上存在可
          选的编码结束或状态标记，这些内容也应当被读取。

      -- 方法: readline ([size[, keepends]])

          从输入流读取一行并返回解码后的数据。

          如果给定了 `size'，则将其作为 size 参数传递给流的 *note
          read(): 1876. 方法。

          如果 `keepends' 为假值，则行结束符将从返回的行中去除。

      -- 方法: readlines ([sizehint[, keepends]])

          从输入流读取所有行并将其作为一个行列表返回。

          行结束符会使用编解码器的 *note decode(): 80c. 方法来实现，并且
          如果 `keepends' 为真值则会将其包含在列表条目中。

          如果给定了 `sizehint'，则将其作为 `size' 参数传递给流的 *note
          read(): 1876. 方法。

      -- 方法: reset ()

          重置用于保持状态的编解码器缓冲区。

          请注意不应当对流进行重定位。 使用此方法的主要目的是为了能够从
          解码错误中恢复。

除了上述的方法，*note StreamReader: 1841. 还必须继承来自下层流的所有其他
方法和属性。


File: python.info,  Node: StreamReaderWriter 对象,  Next: StreamRecoder 对象,  Prev: StreamReader 对象,  Up: 流式的编码和解码

5.7.2.10 StreamReaderWriter 对象
................................

*note StreamReaderWriter: 1849. 是一个方便的类，允许对同时工作于读取和写
入模式的流进行包装。

其设计使得开发者可以使用 *note lookup(): 1711. 函数所返回的工厂函数来构
造实例。

 -- 类: codecs.StreamReaderWriter (stream, Reader, Writer,
          errors='strict')

     创建一个 *note StreamReaderWriter: 1849. 实例。 `stream' 必须为一个
     文件类对象。 `Reader' 和 `Writer' 必须为分别提供了 *note
     StreamReader: 1841. 和 *note StreamWriter: 1840. 接口的工厂函数或类
     。 错误处理通过与流式读取器和写入器所定义的相同方式来完成。

*note StreamReaderWriter: 1849. 实例定义了 *note StreamReader: 1841. 和
*note StreamWriter: 1840. 类的组合接口。 它们还继承了来自下层流的所有其
他方法和属性。


File: python.info,  Node: StreamRecoder 对象,  Prev: StreamReaderWriter 对象,  Up: 流式的编码和解码

5.7.2.11 StreamRecoder 对象
...........................

*note StreamRecoder: fdd. 将数据从一种编码格式转换为另一种，这对于处理不
同编码环境的情况有时会很有用。

其设计使得开发者可以使用 *note lookup(): 1711. 函数所返回的工厂函数来构
造实例。

 -- 类: codecs.StreamRecoder (stream, encode, decode, Reader, Writer,
          errors='strict')

     创建一个实现了双向转换的 *note StreamRecoder: fdd. 实例: `encode' 和
     `decode' 工作于前端 — 对代码可见的数据调用 ‘read()’ 和 ‘write()’，
     而 `Reader' 和 `Writer' 工作于后端 — `stream' 中的数据。

     你可以使用这些对象来进行透明转码，例如从 Latin-1 转为 UTF-8 以及反
     向转换。

     `stream' 参数必须为一个文件类对象。

     `encode' 和 `decode' 参数必须遵循 ‘Codec’ 接口。 `Reader' 和
     `Writer' 必须为分别提供了 *note StreamReader: 1841. 和 *note
     StreamWriter: 1840. 接口对象的工厂函数或类。

     错误处理通过与流式读取器和写入器所定义的相同方式来完成。

*note StreamRecoder: fdd. 实例定义了 *note StreamReader: 1841. 和 *note
StreamWriter: 1840. 类的组合接口。 它们还继承了来自下层流的所有其他方法
和属性。


File: python.info,  Node: 编码格式与 Unicode,  Next: 标准编码,  Prev: 编解码器基类,  Up: codecs --- 编解码器注册和相关基类

5.7.2.12 编码格式与 Unicode
...........................

字符串在系统内部存储为 ‘0x0’–‘0x10FFFF’ 范围内的码位序列。 （请参阅 PEP
393(1) 了解有关实现的详情。） 一旦字符串对象要在 CPU 和内存以外使用，字
节的大小端顺序和字节数组的存储方式就成为一个关键问题。 如同使用其他编解
码器一样，将字符串序列化为字节序列被称为 `编码'，而从字节序列重建字符串
被称为 `解码'。 存在许多不同的文本序列化编解码器，它们被统称为 *note
文本编码: 160b.。

最简单的文本编码格式 (称为 ‘'latin-1'’ 或 ‘'iso-8859-1'’) 将码位 0–255 映
射为字节值 ‘0x0’–‘0xff’，这意味着包含 ‘U+00FF’ 以上码位的字符串对象无法
使用此编解码器进行编码。 这样做将引发 *note UnicodeEncodeError: 1fd.，其
形式类似下面这样（不过详细的错误信息可能会有所不同）:
‘UnicodeEncodeError: 'latin-1' codec can't encode character '\u1234' in
position 3: ordinal not in range(256)’。

还有另外一组编码格式（所谓的字符映射编码）会选择全部 Unicode 码位的不同
子集并设定如何将这些码位映射为字节值 ‘0x0’–‘0xff’。 要查看这是如何实现的
，只需简单地打开相应源码例如 ‘encodings/cp1252.py’ (这是一个主要在
Windows 上使用的编码格式)。 其中会有一个包含 256 个字符的字符串常量，指
明每个字符所映射的字节值。

所有这些编码格式只能对 Unicode 所定义的 1114112 个码位中的 256 个进行编
码。 一种能够存储每个 Unicode 码位的简单而直接的办法就是将每个码位存储为
四个连续的字节。 存在两种不同的可能性：以大端序存储或以小端序存储。 这两
种编码格式分别被称为 ‘UTF-32-BE’ 和 ‘UTF-32-LE’。 它们的缺点可以举例说明
：如果你在一台小端序的机器上使用 ‘UTF-32-BE’ 则你将必须在编码和解码时翻
转字节。 ‘UTF-32’ 避免了这个问题：字节的排列将总是使用自然顺序。 当这些
字节被具有不同字节顺序的 CPU 读取时，则必须进行字节翻转。 为了能够检测
‘UTF-16’ 或 ‘UTF-32’ 字节序列的大小端序，可以使用所谓的 BOM ("字节顺序标
记")。 这对应于 Unicode 字符 ‘U+FEFF’。 此字符可添加到每个 ‘UTF-16’ 或
‘UTF-32’ 字节序列的开头。 此字符的字节翻转版本 (‘0xFFFE’) 是一个不可出现
于 Unicode 文本中的非法字符。 因此当发现一个 ‘UTF-16’ 或 ‘UTF-32’ 字节序
列的首个字符是 ‘U+FFFE’ 时，就必须在解码时进行字节翻转。 不幸的是字符
‘U+FEFF’ 还有第二个含义 ‘ZERO WIDTH NO-BREAK SPACE’: 即宽度为零并且不允
许用来拆分单词的字符。 它可以被用来为语言分析算法提供提示。 在 Unicode
4.0 中用 ‘U+FEFF’ 表示 ‘ZERO WIDTH NO-BREAK SPACE’ 已被弃用（改用
‘U+2060’ (‘WORD JOINER’) 负责此任务）。 然而 Unicode 软件仍然必须能够处
理 ‘U+FEFF’ 的两个含义：作为 BOM 它被用来确定已编码字节的存储布局，并在
字节序列被解码为字符串后将其去除；作为 ‘ZERO WIDTH NO-BREAK SPACE’ 它是
一个普通字符，将像其他字符一样被解码。

还有另一种编码格式能够对所有的 Unicode 字符进行编码：UTF-8。 UTF-8 是一
种 8 位编码，这意味着在 UTF-8 中没有字节顺序问题。 UTF-8 字节序列中的每
个字节由两部分组成：标志位（最重要的位）和内容位。 标志位是由零至四个值
为 ‘1’ 的二进制位加一个值为 ‘0’ 的二进制位构成的序列。 Unicode 字符会按
以下形式进行编码（其中 x 为内容位，当拼接为一体时将给出对应的 Unicode 字
符）：

范围                                    编码
                                        
-------------------------------------------------------------------------------------------
                                        
‘U-00000000’ ...  ‘U-0000007F’          0xxxxxxx
                                        
                                        
‘U-00000080’ ...  ‘U-000007FF’          110xxxxx 10xxxxxx
                                        
                                        
‘U-00000800’ ...  ‘U-0000FFFF’          1110xxxx 10xxxxxx 10xxxxxx
                                        
                                        
‘U-00010000’ ...  ‘U-0010FFFF’          11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
                                        

Unicode 字符最不重要的一个位就是最右侧的二进制位 x。

由于 UTF-8 是一种 8 位编码格式，因此 BOM 是不必要的，并且已编码字符串中
的任何 ‘U+FEFF’ 字符（即使是作为第一个字符）都会被视为是 ‘ZERO WIDTH
NO-BREAK SPACE’。

在没有外部信息的情况下，就不可能毫无疑义地确定一个字符串使用了何种编码格
式。 每种字符映射编码格式都可以解码任意的随机字节序列。 然而对 UTF-8 来
说这却是不可能的，因为 UTF-8 字节序列具有不允许任意字节序列的特别结构。
为了提升 UTF-8 编码检测的可靠性，Microsoft 发明了一种 UTF-8 变体形式
(Python 2.5 称之为 ‘"utf-8-sig"’) 专门用于其 Notepad 程序：在任何
Unicode 字符在被写入文件之前，会先写入一个 UTF-8 编码的 BOM (它看起来是
这样一个字节序列: ‘0xef’, ‘0xbb’, ‘0xbf’)。 由于任何字符映射编码后的文件
都不大可能以这些字节值开头（例如它们会映射为

          LATIN SMALL LETTER I WITH DIAERESIS 
          RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 
          INVERTED QUESTION MARK 

对于 iso-8859-1 编码格式来说），这提升了根据字节序列来正确猜测
‘utf-8-sig’ 编码格式的成功率。 所以在这里 BOM 的作用并不是帮助确定生成字
节序列所使用的字节顺序，而是作为帮助猜测编码格式的记号。 在进行编码时
utf-8-sig 编解码器将把 ‘0xef’, ‘0xbb’, ‘0xbf’ 作为头三个字节写入文件。 在
进行解码时 ‘utf-8-sig’ 将跳过这三个字节，如果它们作为文件的头三个字节出
现的话。 在 UTF-8 中并不推荐使用 BOM，通常应当避免它们的出现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393


File: python.info,  Node: 标准编码,  Next: Python 专属的编码格式,  Prev: 编码格式与 Unicode,  Up: codecs --- 编解码器注册和相关基类

5.7.2.13 标准编码
.................

Python 自带了许多内置的编解码器，它们的实现或者是通过 C 函数，或者是通过
映射表。 以下表格是按名称排序的编解码器列表，并提供了一些常见别名以及编
码格式通常针对的语言。 别名和语言列表都不是详尽无遗的。 请注意仅有大小写
区别或使用连字符替代下划线的拼写形式也都是有效的别名；因此，‘'utf-8'’ 是
‘'utf_8'’ 编解码器的有效别名。

`CPython implementation detail:' 有些常见编码格式可以绕过编解码器查找机
制来提升性能。 这些优化机会对于 CPython 来说仅能通过一组有限的别名（大小
写不敏感）来识别：utf-8, utf8, latin-1, latin1, iso-8859-1, iso8859-1,
mbcs (Windows 专属), ascii, us-ascii, utf-16, utf16, utf-32, utf32, 也包
括使用下划线替代连字符的的形式。 使用这些编码格式的其他别名可能会导致更
慢的执行速度。

在 3.6 版更改: 可识别针对 us-ascii 的优化机会。

许多字符集都支持相同的语言。 它们在个别字符（例如是否支持 EURO SIGN 等）
以及给字符所分配的码位方面存在差异。 特别是对于欧洲语言来说，通常存在以
下几种变体：

   * 某个 ISO 8859 编码集

   * 某个 Microsoft Windows 编码页，通常是派生自某个 8859 编码集，但会用
     附加的图形字符来替换控制字符。

   * 某个 IBM EBCDIC 编码页

   * 某个 IBM PC 编码页，通常会兼容 ASCII

编码                  别名                                 语言
                                                           
------------------------------------------------------------------------------------------------
                                                           
ascii                 646, us-ascii                        英语
                                                           
                                                           
big5                  big5-tw, csbig5                      繁体中文
                                                           
                                                           
big5hkscs             big5-hkscs, hkscs                    繁体中文
                                                           
                                                           
cp037                 IBM037, IBM039                       英语
                                                           
                                                           
cp273                 273, IBM273, csIBM273                德语
                                                           
                                                           3.4 新版功能.
                                                           
                                                           
cp424                 EBCDIC-CP-HE, IBM424                 希伯来语
                                                           
                                                           
cp437                 437, IBM437                          英语
                                                           
                                                           
cp500                 EBCDIC-CP-BE, EBCDIC-CP-CH, IBM500   西欧
                                                           
                                                           
cp720                                                      阿拉伯语
                                                           
                                                           
cp737                                                      希腊语
                                                           
                                                           
cp775                 IBM775                               波罗的海语言
                                                           
                                                           
cp850                 850, IBM850                          西欧
                                                           
                                                           
cp852                 852, IBM852                          中欧和东欧
                                                           
                                                           
cp855                 855, IBM855                          保加利亚语，白俄罗斯语，马其顿语，
                                                           俄语，塞尔维亚语
                                                           
                                                           
cp856                                                      希伯来语
                                                           
                                                           
cp857                 857, IBM857                          土耳其语
                                                           
                                                           
cp858                 858, IBM858                          西欧
                                                           
                                                           
cp860                 860, IBM860                          葡萄牙语
                                                           
                                                           
cp861                 861, CP-IS, IBM861                   冰岛语
                                                           
                                                           
cp862                 862, IBM862                          希伯来语
                                                           
                                                           
cp863                 863, IBM863                          加拿大语
                                                           
                                                           
cp864                 IBM864                               阿拉伯语
                                                           
                                                           
cp865                 865, IBM865                          丹麦语/挪威语
                                                           
                                                           
cp866                 866, IBM866                          俄语
                                                           
                                                           
cp869                 869, CP-GR, IBM869                   希腊语
                                                           
                                                           
cp874                                                      泰语
                                                           
                                                           
cp875                                                      希腊语
                                                           
                                                           
cp932                 932, ms932, mskanji, ms-kanji        日语
                                                           
                                                           
cp949                 949, ms949, uhc                      韩语
                                                           
                                                           
cp950                 950, ms950                           繁体中文
                                                           
                                                           
cp1006                                                     乌尔都语
                                                           
                                                           
cp1026                ibm1026                              土耳其语
                                                           
                                                           
cp1125                1125, ibm1125, cp866u, ruscii        乌克兰语
                                                           
                                                           3.4 新版功能.
                                                           
                                                           
cp1140                ibm1140                              西欧
                                                           
                                                           
cp1250                windows-1250                         中欧和东欧
                                                           
                                                           
cp1251                windows-1251                         保加利亚语，白俄罗斯语，马其顿语，
                                                           俄语，塞尔维亚语
                                                           
                                                           
cp1252                windows-1252                         西欧
                                                           
                                                           
cp1253                windows-1253                         希腊语
                                                           
                                                           
cp1254                windows-1254                         土耳其语
                                                           
                                                           
cp1255                windows-1255                         希伯来语
                                                           
                                                           
cp1256                windows-1256                         阿拉伯语
                                                           
                                                           
cp1257                windows-1257                         波罗的海语言
                                                           
                                                           
cp1258                windows-1258                         越南语
                                                           
                                                           
euc_jp                eucjp, ujis, u-jis                   日语
                                                           
                                                           
euc_jis_2004          jisx0213, eucjis2004                 日语
                                                           
                                                           
euc_jisx0213          eucjisx0213                          日语
                                                           
                                                           
euc_kr                euckr, korean, ksc5601, ks_c-5601,   韩语
                      ks_c-5601-1987, ksx1001, ks_x-1001   
                      
                                                           
gb2312                chinese, csiso58gb231280, euc-cn,    简体中文
                      euccn, eucgb2312-cn, gb2312-1980,    
                      gb2312-80, iso-ir-58
                      
                                                           
gbk                   936, cp936, ms936                    统一汉语
                                                           
                                                           
gb18030               gb18030-2000                         统一汉语
                                                           
                                                           
hz                    hzgb, hz-gb, hz-gb-2312              简体中文
                                                           
                                                           
iso2022_jp            csiso2022jp, iso2022jp,              日语
                      iso-2022-jp                          
                      
                                                           
iso2022_jp_1          iso2022jp-1, iso-2022-jp-1           日语
                                                           
                                                           
iso2022_jp_2          iso2022jp-2, iso-2022-jp-2           日语，韩语，简体中文，西欧，希腊语
                                                           
                                                           
iso2022_jp_2004       iso2022jp-2004, iso-2022-jp-2004     日语
                                                           
                                                           
iso2022_jp_3          iso2022jp-3, iso-2022-jp-3           日语
                                                           
                                                           
iso2022_jp_ext        iso2022jp-ext, iso-2022-jp-ext       日语
                                                           
                                                           
iso2022_kr            csiso2022kr, iso2022kr,              韩语
                      iso-2022-kr                          
                      
                                                           
latin_1               iso-8859-1, iso8859-1, 8859,         西欧
                      cp819, latin, latin1, L1             
                      
                                                           
iso8859_2             iso-8859-2, latin2, L2               中欧和东欧
                                                           
                                                           
iso8859_3             iso-8859-3, latin3, L3               世界语，马耳他语
                                                           
                                                           
iso8859_4             iso-8859-4, latin4, L4               波罗的海语言
                                                           
                                                           
iso8859_5             iso-8859-5, cyrillic                 保加利亚语，白俄罗斯语，马其顿语，
                                                           俄语，塞尔维亚语
                                                           
                                                           
iso8859_6             iso-8859-6, arabic                   阿拉伯语
                                                           
                                                           
iso8859_7             iso-8859-7, greek, greek8            希腊语
                                                           
                                                           
iso8859_8             iso-8859-8, hebrew                   希伯来语
                                                           
                                                           
iso8859_9             iso-8859-9, latin5, L5               土耳其语
                                                           
                                                           
iso8859_10            iso-8859-10, latin6, L6              北欧语言
                                                           
                                                           
iso8859_11            iso-8859-11, thai                    泰语
                                                           
                                                           
iso8859_13            iso-8859-13, latin7, L7              波罗的海语言
                                                           
                                                           
iso8859_14            iso-8859-14, latin8, L8              凯尔特语
                                                           
                                                           
iso8859_15            iso-8859-15, latin9, L9              西欧
                                                           
                                                           
iso8859_16            iso-8859-16, latin10, L10            东南欧
                                                           
                                                           
johab                 cp1361, ms1361                       韩语
                                                           
                                                           
koi8_r                                                     俄语
                                                           
                                                           
koi8_t                                                     塔吉克
                                                           
                                                           3.5 新版功能.
                                                           
                                                           
koi8_u                                                     乌克兰语
                                                           
                                                           
kz1048                kz_1048, strk1048_2002, rk1048       哈萨克语
                                                           
                                                           3.5 新版功能.
                                                           
                                                           
mac_cyrillic          maccyrillic                          保加利亚语，白俄罗斯语，马其顿语，
                                                           俄语，塞尔维亚语
                                                           
                                                           
mac_greek             macgreek                             希腊语
                                                           
                                                           
mac_iceland           maciceland                           冰岛语
                                                           
                                                           
mac_latin2            maclatin2, maccentraleurope          中欧和东欧
                                                           
                                                           
mac_roman             macroman, macintosh                  西欧
                                                           
                                                           
mac_turkish           macturkish                           土耳其语
                                                           
                                                           
ptcp154               csptcp154, pt154, cp154,             哈萨克语
                      cyrillic-asian                       
                      
                                                           
shift_jis             csshiftjis, shiftjis, sjis, s_jis    日语
                                                           
                                                           
shift_jis_2004        shiftjis2004, sjis_2004, sjis2004    日语
                                                           
                                                           
shift_jisx0213        shiftjisx0213, sjisx0213,            日语
                      s_jisx0213                           
                      
                                                           
utf_32                U32, utf32                           所有语言
                                                           
                                                           
utf_32_be             UTF-32BE                             所有语言
                                                           
                                                           
utf_32_le             UTF-32LE                             所有语言
                                                           
                                                           
utf_16                U16, utf16                           所有语言
                                                           
                                                           
utf_16_be             UTF-16BE                             所有语言
                                                           
                                                           
utf_16_le             UTF-16LE                             所有语言
                                                           
                                                           
utf_7                 U7, unicode-1-1-utf-7                所有语言
                                                           
                                                           
utf_8                 U8, UTF, utf8, cp65001               所有语言
                                                           
                                                           
utf_8_sig                                                  所有语言
                                                           

在 3.4 版更改: utf-16* 和 utf-32* 编码器将不再允许编码代理码位
(‘U+D800’–‘U+DFFF’)。 utf-32* 解码器将不再解码与代理码位相对应的字节序列
。

在 3.8 版更改: ‘cp65001’ 现在是 ‘utf_8’ 的一个别名。


File: python.info,  Node: Python 专属的编码格式,  Next: encodings idna --- 应用程序中的国际化域名,  Prev: 标准编码,  Up: codecs --- 编解码器注册和相关基类

5.7.2.14 Python 专属的编码格式
..............................

有一些预定义编解码器是 Python 专属的，因此它们在 Python 之外没有意义。 这
些编解码器按其所预期的输入和输出类型在下表中列出（请注意虽然文本编码是编
解码器最常见的使用场景，但下层的编解码器架构支持任意数据转换而不仅是文本
编码）。 对于非对称编解码器，该列描述的含义是编码方向。

* Menu:

* 文字编码::
* 二进制转换::
* 文字转换::


File: python.info,  Node: 文字编码,  Next: 二进制转换,  Up: Python 专属的编码格式

5.7.2.15 文字编码
.................

以下编解码器提供了 *note str: 339. 到 *note bytes: 33a. 的编码和 *note
bytes-like object: 5f1. 到 *note str: 339. 的解码，类似于 Unicode 文本编
码。

编码                     别名          含义
                                       
-----------------------------------------------------------------------
                                       
idna                                   实现 RFC 3490(1)，另请参阅
                                       *note encodings.idna: 77. 。
                                       仅支持 ‘errors='strict'’ 。
                                       
                                       
mbcs                     ansi, dbcs    Windows 专属：根据 ANSI 代码
                                       页（CP_ACP）对操作数进行编码
                                       。
                                       
                                       
oem                                    Windows 专属：根据 OEM 代码页
                                       （CP_OEMCP）对操作数进行编码
                                       。
                                       
                                       3.6 新版功能.
                                       
                                       
palmos                                 PalmOS 3.5 的编码格式
                                       
                                       
punycode                               实现 RFC 3492(2)。 不支持有状
                                       态编解码器。
                                       
                                       
raw_unicode_escape                     Latin-1 编码格式附带对其他码
                                       位以 ‘\uXXXX’ 和 ‘\UXXXXXXXX’
                                       进行编码。 现有反斜杠不会以任
                                       何方式转义。 它被用于 Python
                                       的 pickle 协议。
                                       
                                       
undefined                              所有转换都将引发异常，甚至对
                                       空字符串也不例外。 错误处理方
                                       案会被忽略。
                                       
                                       
unicode_escape                         适合用于以 ASCII 编码的
                                       Python 源代码中的 Unicode 字
                                       面值内容的编码格式，但引号不
                                       会被转义。 对 Latin-1 源代码
                                       进行解码。 请注意 Python 源代
                                       码实际上默认使用 UTF-8。
                                       

在 3.8 版更改: "unicode_internal" 编解码器已被移除。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3490.html

   (2) https://tools.ietf.org/html/rfc3492.html


File: python.info,  Node: 二进制转换,  Next: 文字转换,  Prev: 文字编码,  Up: Python 专属的编码格式

5.7.2.16 二进制转换
...................

以下编解码器提供了二进制转换: *note bytes-like object: 5f1. 到 *note
bytes: 33a. 的映射。 它们不被 *note bytes.decode(): c40. 所支持（该方法
只生成 *note str: 339. 类型的输出）。

编码                       别名                   含义                               编码器/解码器
                                                                                     
------------------------------------------------------------------------------------------------------------------------
                                                                                     
base64_codec (1)           base64, base_64        将操作数转换为多行 MIME base64     *note base64.encodebytes(): 1884.
                                                  (结果总是包含一个末尾的 ‘'\n'’)    /
                                                                                     *note base64.decodebytes(): 1885.
                                                  在 3.4 版更改: 接受任意            
                                                  *note bytes-like object: 5f1. 作
                                                  为输入用于编码和解码
                                                  
                                                                                     
bz2_codec                  bz2                    使用bz2压缩操作数                  *note bz2.compress(): 1886. /
                                                                                     *note bz2.decompress(): 9df.
                                                                                     
                                                                                     
hex_codec                  hex                    将操作数转换为十六进制表示，每个   *note binascii.b2a_hex(): 1887.
                                                  字节有两位数                       /
                                                                                     *note binascii.a2b_hex(): 1888.
                                                                                     
                                                                                     
quopri_codec               quopri,                将操作数转换为 MIME 带引号的可打   *note quopri.encode(): 1889. 且
                           quotedprintable,       印数据                             ‘quotetabs=True’ /
                           quoted_printable                                          *note quopri.decode(): 188a.
                                                                                     
                                                                                     
uu_codec                   uu                     使用uuencode转换操作数             *note uu.encode(): 417. /
                                                                                     *note uu.decode(): 188b.
                                                                                     
                                                                                     
zlib_codec                 zip, zlib              使用gzip压缩操作数                 *note zlib.compress(): 5c7. /
                                                                                     *note zlib.decompress(): 5c8.
                                                                                     

3.2 新版功能: 恢复二进制转换。

在 3.4 版更改: 恢复二进制转换的别名。

   ---------- Footnotes ----------

   (1) (1) 除了 *note 字节类对象: 5f1.，‘'base64_codec'’ 也接受仅包含
ASCII 的 *note str: 339. 实例用于解码


File: python.info,  Node: 文字转换,  Prev: 二进制转换,  Up: Python 专属的编码格式

5.7.2.17 文字转换
.................

以下编解码器提供了文本转换: *note str: 339. 到 *note str: 339. 的映射。
它不被 *note str.encode(): c3f. 所支持（该方法只生成 *note bytes: 33a. 类
型的输出）。

编码                     别名          含义
                                       
-----------------------------------------------------------------------
                                       
rot_13                   rot13         返回操作数的凯撒密码加密结果
                                       

3.2 新版功能: 恢复 ‘rot_13’ 文本转换。

在 3.4 版更改: 恢复 ‘rot13’ 别名。


File: python.info,  Node: encodings idna --- 应用程序中的国际化域名,  Next: encodings mbcs --- Windows ANSI代码页,  Prev: Python 专属的编码格式,  Up: codecs --- 编解码器注册和相关基类

5.7.2.18 ‘encodings.idna’ — 应用程序中的国际化域名
..................................................

此模块实现了 RFC 3490(1) (应用程序中的国际化域名) 和 RFC 3492(2)
(Nameprep: 用于国际化域名 (IDN) 的 Stringprep 配置文件)。 它是在
‘punycode’ 编码格式和 *note stringprep: f8. 的基础上构建的。

如果你需要来自 RFC 5891(3) 和 RFC 5895(4) 的 IDNA 2008 标准，请使用第三
方 ‘idna 模块 <https://pypi.org/project/idna/>_’。

这些 RFC 共同定义了一个在域名中支持非 ASCII 字符的协议。 一个包含非
ASCII 字符的域名 (例如 ‘www.Alliancefrançaise.nu’) 会被转换为兼容 ASCII
的编码格式 (简称 ACE，例如 ‘www.xn--alliancefranaise-npb.nu’)。 随后此域
名的 ACE 形式可以用于所有由于特定协议而不允许使用任意字符的场合，例如
DNS 查询，HTTP ‘Host’ 字段等等。 此转换是在应用中进行的；如有可能将对用
户可见：应用应当透明地将 Unicode 域名标签转换为线上的 IDNA，并在 ACE 标
签被呈现给用户之前将其转换回 Unicode。

Python 以多种方式支持这种转换: ‘idna’ 编解码器执行 Unicode 和 ACE 之间的
转换，基于在 section 3.1 of RFC 3490(5) 中定义的分隔字符将输入字符串拆分
为标签，再根据需要将每个标签转换为 ACE，相反地又会基于 ‘.’ 分隔符将输入
字节串拆分为标签，再将找到的任何 ACE 标签转换为 Unicode。 此外，*note
socket: f0. 模块可透明地将 Unicode 主机名转换为 ACE，以便应用在将它们传
给 socket 模块时无须自行转换主机名。 除此之外，许多包含以主机名作为函数
参数的模块例如 *note http.client: 94. 和 *note ftplib: 84. 都接受
Unicode 主机名（并且 *note http.client: 94. 也会在 ‘Host’ 字段中透明地发
送 IDNA 主机名，如果它需要发送该字段的话）。

当从线路接收主机名时（例如反向名称查找），到 Unicode 的转换不会自动被执
行：希望向用户提供此种主机名的应用应当将它们解码为 Unicode。

*note encodings.idna: 77. 模块还实现了 nameprep 过程，该过程会对主机名执
行特定的规范化操作，以实现国际域名的大小写不敏感特性与合并相似的字符。 如
果有需要可以直接使用 nameprep 函数。

 -- 函数: encodings.idna.nameprep (label)

     返回 `label' 经过名称处理操作的版本。 该实现目前基于查询字符串，因
     此 ‘AllowUnassigned’ 为真值。

 -- 函数: encodings.idna.ToASCII (label)

     将标签转换为 ASCII，规则定义见 RFC 3490(6)。 ‘UseSTD3ASCIIRules’ 预
     设为假值。

 -- 函数: encodings.idna.ToUnicode (label)

     将标签转换为 Unicode，规则定义见 RFC 3490(7)。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3490.html

   (2) https://tools.ietf.org/html/rfc3492.html

   (3) https://tools.ietf.org/html/rfc5891.html

   (4) https://tools.ietf.org/html/rfc5895.html

   (5) https://tools.ietf.org/html/rfc3490.html#section-3.1

   (6) https://tools.ietf.org/html/rfc3490.html

   (7) https://tools.ietf.org/html/rfc3490.html


File: python.info,  Node: encodings mbcs --- Windows ANSI代码页,  Next: encodings utf_8_sig --- 带BOM签名的UTF-8编解码器,  Prev: encodings idna --- 应用程序中的国际化域名,  Up: codecs --- 编解码器注册和相关基类

5.7.2.19 ‘encodings.mbcs’ — Windows ANSI代码页
..............................................

此模块实现ANSI代码页（CP_ACP）。

*note Availability: 136f.: 仅Windows可用

在 3.3 版更改: 支持任何错误处理

在 3.2 版更改: 在 3.2 版之前， `errors' 参数会被忽略；总是会使用
‘'replace'’ 进行编码，并使用 ‘'ignore'’ 进行解码。


File: python.info,  Node: encodings utf_8_sig --- 带BOM签名的UTF-8编解码器,  Prev: encodings mbcs --- Windows ANSI代码页,  Up: codecs --- 编解码器注册和相关基类

5.7.2.20 ‘encodings.utf_8_sig’ — 带BOM签名的UTF-8编解码器
.........................................................

此模块实现了 UTF-8 编解码器的一个变种：在编码时将把 UTF-8 已编码 BOM 添
加到 UTF-8 编码字节数据的开头。 对于有状态编码器此操作只执行一次（当首次
写入字节流时）。 在解码时将跳过数据开头作为可选项的 UTF-8 已编码 BOM。


File: python.info,  Node: 数据类型,  Next: 数字和数学模块,  Prev: 二进制数据服务,  Up: Python 标准库

5.8 数据类型
============

本章所描述的模块提供了许多专门的数据类型，如日期和时间、固定类型的数组、
堆队列、双端队列、以及枚举。

Python也提供一些内置数据类型，特别是，*note dict: 1b9.、 *note list:
263.、*note set: b77.、*note frozenset: bf6.、以及 *note tuple: 486.。
*note str: 339. 这个类是用来存储Unicode字符串的，而 *note bytes: 33a. 和
*note bytearray: 33b. 这两个类是用来存储二进制数据的。

本章包含以下模块的文档：

* Menu:

* datetime: datetime --- 基本的日期和时间类型. 基本的日期和时间类型
* calendar: calendar --- 日历相关函数. 日历相关函数
* collections: collections --- 容器数据类型. 容器数据类型
* collections.abc: collections abc --- 容器的抽象基类. 容器的抽象基类
* heapq: heapq --- 堆队列算法. 堆队列算法
* bisect: bisect --- 数组二分查找算法. 数组二分查找算法
* array: array --- 高效的数值数组. 高效的数值数组
* weakref: weakref --- 弱引用. 弱引用
* types: types --- 动态类型创建和内置类型名称. 动态类型创建和内置类型名称
* copy: copy --- 浅层 shallow 和深层 deep 复制操作. 浅层 (shallow) 和深层 (deep) 复制操作
* pprint: pprint --- 数据美化输出. 数据美化输出
* reprlib: reprlib --- 另一种 repr 实现. 另一种 repr() 实现
* enum: enum --- 对枚举的支持. 对枚举的支持


File: python.info,  Node: datetime --- 基本的日期和时间类型,  Next: calendar --- 日历相关函数,  Up: 数据类型

5.8.1 ‘datetime’ — 基本的日期和时间类型
---------------------------------------

`源代码：' Lib/datetime.py(1)

__________________________________________________________________

*note datetime: 31. 模块提供用于处理日期和时间的类。

在支持日期时间数学运算的同时，实现的关注点更着重于如何能够更有效地解析其
属性用于格式化输出和数据操作。

参见
....

模块 *note calendar: 15.

     通用日历相关函数

模块 *note time: 10b.

     时间的访问和转换

dateutil(2) 包

     具有扩展时区和解析支持的第三方库。

* Menu:

* 感知型对象和简单型对象::
* 常量::
* 有效的类型::
* timedelta 类对象::
* date 对象::
* datetime 对象::
* time 对象::
* tzinfo 对象::
* timezone 对象::
* strftime() 和 strptime() 的行为: strftime 和 strptime 的行为.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/datetime.py

   (2) https://dateutil.readthedocs.io/en/stable/


File: python.info,  Node: 感知型对象和简单型对象,  Next: 常量,  Up: datetime --- 基本的日期和时间类型

5.8.1.1 感知型对象和简单型对象
..............................

日期和时间对象可以根据它们是否包含时区信息而分为“感知型”和“简单型”两类。

充分掌握应用性算法和政治性时间调整信息例如时区和夏令时的情况下，一个 `感
知型' 对象就能相对于其他感知型对象来精确定位自身时间点。 感知型对象是用
来表示一个没有解释空间的固定时间点。 (1)

`简单型' 对象没有包含足够多的信息来无歧义地相对于其他 date/time 对象来定
位自身时间点。 不论一个简单型对象所代表的是世界标准时间（UTC）、当地时间
还是某个其他时区的时间完全取决于具体程序，就像一个特定数字所代表的是米、
英里还是质量完全取决于具体程序一样。 简单型对象更易于理解和使用，代价则
是忽略了某些现实性考量。

对于要求感知型对象的应用，*note datetime: 195. 和 *note time: 4fb. 对象
具有一个可选的时区信息属性 ‘tzinfo’，它可被设为抽象类 *note tzinfo: 388.
的子类的一个实例。 这些 *note tzinfo: 388. 对象会捕获与 UTC 时间的差值、
时区名称以及夏令时是否生效等信息。

*note datetime: 31. 模块只提供了一个具体的 *note tzinfo: 388. 类，即
*note timezone: a09. 类。 *note timezone: a09. 类可以表示具有相对于 UTC
的固定时差的简单时区，例如 UTC 本身或北美的 EST 和 EDT 时区等。 支持时间
的详细程度取决于具体的应用。 世界各地的时间调整规则往往是政治性多于合理
性，经常会发生变化，除了 UTC 之外并没有一个能适合所有应用的标准。

   ---------- Footnotes ----------

   (1) (1) 就是说如果我们忽略相对论效应的话。


File: python.info,  Node: 常量,  Next: 有效的类型,  Prev: 感知型对象和简单型对象,  Up: datetime --- 基本的日期和时间类型

5.8.1.2 常量
............

The *note datetime: 31. module exports the following constants:

 -- 数据: datetime.MINYEAR

     *note date: 194. 或者 *note datetime: 195. 对象允许的最小年份。 常
     量 *note MINYEAR: 189b. 是 ‘1’ 。

 -- 数据: datetime.MAXYEAR

     *note date: 194. 或 *note datetime: 195. 对象允许最大的年份。常量
     *note MAXYEAR: 189c. 是 ‘9999’ 。


File: python.info,  Node: 有效的类型,  Next: timedelta 类对象,  Prev: 常量,  Up: datetime --- 基本的日期和时间类型

5.8.1.3 有效的类型
..................

 -- 类: datetime.date

     一个理想化的简单型日期，它假设当今的公历在过去和未来永远有效。 属性
     : *note year: 189e, *note month: 189f, and *note day: 18a0.。

 -- 类: datetime.time

     一个独立于任何特定日期的理想化时间，它假设每一天都恰好等于 24*60*60
     秒。 （这里没有“闰秒”的概念。） 包含属性: *note hour: 18a1, *note
     minute: 18a2, *note second: 18a3, *note microsecond: 18a4. 和 *note
     tzinfo: 18a5.。

 -- 类: datetime.datetime

     日期和时间的结合。属性：*note year: 18a6, *note month: 18a7, *note
     day: 18a8, *note hour: 18a9, *note minute: 18aa, *note second:
     18ab, *note microsecond: 18ac, and *note tzinfo: 18ad.

 -- 类: datetime.timedelta

     表示两个 *note date: 194. 对象或者 *note time: 4fb. 对象,或者 *note
     datetime: 195. 对象之间的时间间隔，精确到微秒。

 -- 类: datetime.tzinfo

     一个描述时区信息对象的抽象基类。 用来给 *note datetime: 195. 和
     *note time: 4fb. 类提供自定义的时间调整概念（例如处理时区和/或夏令
     时）。

 -- 类: datetime.timezone

     一个实现了 *note tzinfo: 388. 抽象基类的子类，用于表示相对于 世界标
     准时间（UTC）的偏移量。

     3.2 新版功能.

这些类型的对象都是不可变的。

子类关系

     object
         timedelta
         tzinfo
             timezone
         time
         date
             datetime

* Menu:

* 通用的特征属性::
* 确定一个对象是感知型还是简单型::


File: python.info,  Node: 通用的特征属性,  Next: 确定一个对象是感知型还是简单型,  Up: 有效的类型

5.8.1.4 通用的特征属性
......................

*note date: 194, *note datetime: 195, *note time: 4fb. 和 *note
timezone: a09. 类型共享这些通用特性:

   - 这些类型的对象都是不可变的。

   - 这些类型的对象是可哈希的，这意味着它们可被作为字典的键。

   - 这些类型的对象支持通过 *note pickle: cb. 模块进行高效的封存。


File: python.info,  Node: 确定一个对象是感知型还是简单型,  Prev: 通用的特征属性,  Up: 有效的类型

5.8.1.5 确定一个对象是感知型还是简单型
......................................

*note date: 194. 类型的对象都是简单型的。

*note time: 4fb. 或 *note datetime: 195. 类型的对象可以是感知型或者简单
型。

一个 *note datetime: 195. 对象 `d' 在以下条件同时成立时将是感知型的：

  1. ‘d.tzinfo’ 不为 ‘None’

  2. ‘d.tzinfo.utcoffset(d)’ 不返回 ‘None’

在其他情况下，`d' 将是简单型的。

一个 *note time: 4fb. 对象 `t' 在以下条件同时成立时将是感知型的：

  1. ‘t.tzinfo’ 不为 ‘None’

  2. ‘t.tzinfo.utcoffset(None)’ 不返回 ‘None’。

在其他情况下，`t' 将是简单型的。

感知型和简单型之间的区别不适用于 *note timedelta: 196. 对象。


File: python.info,  Node: timedelta 类对象,  Next: date 对象,  Prev: 有效的类型,  Up: datetime --- 基本的日期和时间类型

5.8.1.6 ‘timedelta’ 类对象
..........................

*note timedelta: 196. 对象表示两个 date 或者 time 的时间间隔。

 -- 类: datetime.timedelta (days=0, seconds=0, microseconds=0,
          milliseconds=0, minutes=0, hours=0, weeks=0)

     所有参数都是可选的并且默认为 ‘0’。 这些参数可以是整数或者浮点数，也
     可以是正数或者负数。

     只有 `days', `seconds' 和 `microseconds' 会存储在内部。 参数单位的
     换算规则如下：

        * 1毫秒会转换成1000微秒。

        * 1分钟会转换成60秒。

        * 1小时会转换成3600秒。

        * 1星期会转换成7天。

     并且 days, seconds, microseconds 会经标准化处理以保证表达方式的唯一
     性，即：

        * ‘0 <= microseconds < 1000000’

        * ‘0 <= seconds < 3600*24’ (一天的秒数)

        * ‘-999999999 <= days <= 999999999’

     下面的例子演示了如何对 `days', `seconds' 和 `microseconds' 以外的任
     意参数执行“合并”操作并标准化为以上三个结果属性:

          >>> from datetime import timedelta
          >>> delta = timedelta(
          ...     days=50,
          ...     seconds=27,
          ...     microseconds=10,
          ...     milliseconds=29000,
          ...     minutes=5,
          ...     hours=8,
          ...     weeks=2
          ... )
          >>> # Only days, seconds, and microseconds remain
          >>> delta
          datetime.timedelta(days=64, seconds=29156, microseconds=10)

     在有任何参数为浮点型并且 microseconds 值为小数的情况下，从所有参数
     中余下的微秒数将被合并，并使用四舍五入偶不入奇的规则将总计值舍入到
     最接近的整数微秒值。 如果没有任何参数为浮点型的情况下，则转换和标准
     化过程将是完全精确的（不会丢失信息）。

     如果标准化后的 days 数值超过了指定范围，将会抛出 *note
     OverflowError: 968. 异常。

     请注意对负数值进行标准化的结果可能会令人感到惊讶。 例如:

          >>> from datetime import timedelta
          >>> d = timedelta(microseconds=-1)
          >>> (d.days, d.seconds, d.microseconds)
          (-1, 86399, 999999)

类属性：

 -- 属性: timedelta.min

     The most negative *note timedelta: 196. object,
     ‘timedelta(-999999999)’.

 -- 属性: timedelta.max

     The most positive *note timedelta: 196. object,
     ‘timedelta(days=999999999, hours=23, minutes=59, seconds=59,
     microseconds=999999)’.

 -- 属性: timedelta.resolution

     两个不相等的 *note timedelta: 196. 类对象最小的间隔为
     ‘timedelta(microseconds=1)’。

需要注意的是，因为标准化的缘故，‘timedelta.max’ > ‘-timedelta.min’，
‘-timedelta.max’ 不可以表示一个 *note timedelta: 196. 类对象。

实例属性（只读）：

属性                   值
                       
------------------------------------------------------------------------
                       
‘days’                 -999999999 至 999999999 ，含999999999
                       
                       
‘seconds’              0 至 86399，包含86399
                       
                       
‘microseconds’         0 至 999999，包含999999
                       

支持的运算：

运算                                 结果：
                                     
-----------------------------------------------------------------------------------------
                                     
‘t1 = t2 + t3’                       `t2' 和 `t3' 的和。 运算后 `t1'-`t2' == `t3' and
                                     `t1'-`t3' == `t2' 必为真值。(1)
                                     
                                     
‘t1 = t2 - t3’                       `t2' 减 `t3' 的差。 运算后 `t1' == `t2' - `t3'
                                     and `t2' == `t1' + `t3' 必为真值。 (1)(6)
                                     
                                     
‘t1 = t2 * i or t1 = i * t2’         乘以一个整数。运算后假如 ‘i != 0’ 则 `t1' // i ==
                                     `t2' 必为真值。
                                     
                                     
                                     In general, `t1' * i == `t1' * (i-1) + `t1' is
                                     true.  (1)
                                     
                                     
‘t1 = t2 * f or t1 = f * t2’         乘以一个浮点数，结果会被舍入到 timedelta 最接近的
                                     整数倍。 精度使用四舍五偶入奇不入规则。
                                     
                                     
‘f = t2 / t3’                        总时间 `t2' 除以间隔单位 `t3' (3)。 返回一个
                                     *note float: 188. 对象。
                                     
                                     
‘t1 = t2 / f or t1 = t2 / i’         除以一个浮点数或整数。 结果会被舍入到 timedelta 最
                                     接近的整数倍。 精度使用四舍五偶入奇不入规则。
                                     
                                     
‘t1 = t2 // i’ or ‘t1 = t2 // t3’    计算底数，其余部分（如果有）将被丢弃。在第二种情
                                     况下，将返回整数。 （3）
                                     
                                     
‘t1 = t2 % t3’                       余数为一个 *note timedelta: 196. 对象。(3)
                                     
                                     
‘q, r = divmod(t1, t2)’              通过 : ‘q = t1 // t2’ (3) and ‘r = t1 % t2’ 计算
                                     出商和余数。q是一个整数，r是一个
                                     *note timedelta: 196. 对象。
                                     
                                     
‘+t1’                                返回一个相同数值的 *note timedelta: 196. 对象。
                                     
                                     
‘-t1’                                等价于 *note timedelta: 196.(-`t1.days',
                                     -`t1.seconds', -`t1.microseconds'), 和 `t1'* -1.
                                     (1)(4)
                                     
                                     
‘abs(t)’                             当 ‘t.days >= 0``时等于 +\ *t*, 当 ``t.days < 0’
                                     时 -`t' 。 (2)
                                     
                                     
‘str(t)’                             返回一个形如 ‘[D day[s], ][H]H:MM:SS[.UUUUUU]’ 的
                                     字符串，当 ‘t’ 为负数的时候， D 也为负数。 (5)
                                     
                                     
‘repr(t)’                            返回一个 *note timedelta: 196. 对象的字符串表示形
                                     式，作为附带正规属性值的构造器调用。
                                     

注释:

  1. 结果正确，但可能会溢出。

  2. 结果正确，不会溢出。

  3. 除以0将会抛出异常 *note ZeroDivisionError: 12bd. 。

  4. -`timedelta.max' 不是一个 *note timedelta: 196. 类对象。

  5. *note timedelta: 196. 对象的字符串表示形式类似于其内部表示形式被规
     范化。对于负时间增量，这会导致一些不寻常的结果。例如:

          >>> timedelta(hours=-5)
          datetime.timedelta(days=-1, seconds=68400)
          >>> print(_)
          -1 day, 19:00:00

  6. 表达式 ‘t2 - t3’ 通常与 ‘t2 + (-t3)’ 是等价的，除非 t3 等于
     ‘timedelta.max’; 在这种情况下前者会返回结果，而后者则会溢出。

除了上面列举的操作以外，*note timedelta: 196. 对象还支持与 *note date:
194. 和 *note datetime: 195. 对象进行特定的相加和相减运算（见下文）。

在 3.2 版更改: 现在已支持 *note timedelta: 196. 对象与另一个 *note
timedelta: 196. 对象相整除或相除，包括求余运算和 *note divmod(): 153. 函
数。 现在也支持 *note timedelta: 196. 对象加上或乘以一个 *note float:
188. 对象。

支持 *note timedelta: 196. 对象之间进行比较，但其中有一些注意事项。

‘==’ 或 ‘!=’ 比较 `总是' 返回一个 *note bool: 184. 对象，无论被比较的对
象是什么类型:

     >>> from datetime import timedelta
     >>> delta1 = timedelta(seconds=57)
     >>> delta2 = timedelta(hours=25, seconds=2)
     >>> delta2 != delta1
     True
     >>> delta2 == 5
     False

对于所有其他比较 (例如 ‘<’ 和 ‘>’)，当一个 *note timedelta: 196. 对象与
其他类型的对象比较时，将引发 *note TypeError: 193.:

     >>> delta2 > delta1
     True
     >>> delta2 > 5
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: '>' not supported between instances of 'datetime.timedelta' and 'int'

在布尔运算中，*note timedelta: 196. 对象当且仅当其不等于 ‘timedelta(0)’
时则会被视为真值。

实例方法：

 -- 方法: timedelta.total_seconds ()

     返回时间间隔包含了多少秒。造价于 ‘td / timedelta(seconds=1)’。对于
     其它单位可以直接使用除法的形式 (例如 ‘td /
     timedelta(microseconds=1)’)。

     需要注意的是，时间间隔较大时，这个方法的结果中的微秒将会失真（大多
     数平台上大于270年视为一个较大的时间间隔）。

     3.2 新版功能.

* Menu:

* class;timedelta 用法示例: class timedelta 用法示例.


File: python.info,  Node: class timedelta 用法示例,  Up: timedelta 类对象

5.8.1.7 class:‘timedelta’ 用法示例
..................................

一个标准化的附加示例:

     >>> # Components of another_year add up to exactly 365 days
     >>> from datetime import timedelta
     >>> year = timedelta(days=365)
     >>> another_year = timedelta(weeks=40, days=84, hours=23,
     ...                          minutes=50, seconds=600)
     >>> year == another_year
     True
     >>> year.total_seconds()
     31536000.0

*note timedelta: 196. 算术运算的示例:

     >>> from datetime import timedelta
     >>> year = timedelta(days=365)
     >>> ten_years = 10 * year
     >>> ten_years
     datetime.timedelta(days=3650)
     >>> ten_years.days // 365
     10
     >>> nine_years = ten_years - year
     >>> nine_years
     datetime.timedelta(days=3285)
     >>> three_years = nine_years // 3
     >>> three_years, three_years.days // 365
     (datetime.timedelta(days=1095), 3)


File: python.info,  Node: date 对象,  Next: datetime 对象,  Prev: timedelta 类对象,  Up: datetime --- 基本的日期和时间类型

5.8.1.8 ‘date’ 对象
...................

*note date: 194. 对象代表一个理想化历法中的日期（年、月和日），即当今的
格列高利历向前后两个方向无限延伸。

公元 1 年 1 月 1日是第 1 日，公元 1 年 1 月 2 日是第 2 日，依此类推。
(1)

 -- 类: datetime.date (year, month, day)

     所有参数都是必要的。 参数必须是在下面范围内的整数：

        * ‘MINYEAR <= year <= MAXYEAR’

        * ‘1 <= month <= 12’

        * ‘1 <= 日期 <= 给定年月对应的天数’

     如果参数不在这些范围内，则抛出 *note ValueError: 1fc. 异常。

其它构造器，所有的类方法：

 -- 方法: classmethod date.today ()

     返回当前的本地日期。

     这等价于 ‘date.fromtimestamp(time.time())’。

 -- 方法: classmethod date.fromtimestamp (timestamp)

     返回对应于 POSIX 时间戳的当地时间，例如 *note time.time(): 326. 返
     回的就是时间戳。

     这可能引发 *note OverflowError: 968.，如果时间戳数值超出所在平台 C
     ‘localtime()’ 函数的支持范围的话，并且会在 ‘localtime()’ 出错时引发
     *note OSError: 1d4.。 通常该数值会被限制在 1970 年至 2038 年之间。
     请注意在时间戳概念包含闰秒的非 POSIX 系统上，闰秒会被 *note
     fromtimestamp(): 18b9. 所忽略。

     在 3.3 版更改: 引发 *note OverflowError: 968. 而不是 *note
     ValueError: 1fc.，如果时间戳数值超出所在平台 C ‘localtime()’ 函数的
     支持范围的话，并会在 ‘localtime()’ 出错时引发 *note OSError: 1d4. 而
     不是 *note ValueError: 1fc.。

 -- 方法: classmethod date.fromordinal (ordinal)

     返回对应于预期格列高利历序号的日期，其中公元 1 年 1 月 1 日的序号为
     1。

     除非 ‘1 <= ordinal <= date.max.toordinal()’ 否则会引发 *note
     ValueError: 1fc.。对于任意日期 `d'，
     ‘date.fromordinal(d.toordinal()) == d’。

 -- 方法: classmethod date.fromisoformat (date_string)

     返回一个对应于以 ‘YYYY-MM-DD’ 格式给出的 `date_string' 的 *note
     date: 194. 对象:

          >>> from datetime import date
          >>> date.fromisoformat('2019-12-04')
          datetime.date(2019, 12, 4)

     这是 *note date.isoformat(): 18bb. 的逆操作。 它只支持 ‘YYYY-MM-DD’
     格式。

     3.7 新版功能.

 -- 方法: classmethod date.fromisocalendar (year, week, day)

     返回指定 year, week 和 day 所对应 ISO 历法日期的 *note date: 194.。
     这是函数 *note date.isocalendar(): 18bc. 的逆操作。

     3.8 新版功能.

类属性：

 -- 属性: date.min

     最小的日期 ‘date(MINYEAR, 1, 1)’ 。

 -- 属性: date.max

     最大的日期 ，‘date(MAXYEAR, 12, 31)’。

 -- 属性: date.resolution

     两个日期对象的最小间隔，‘timedelta(days=1)’。

实例属性（只读）：

 -- 属性: date.year

     在 *note MINYEAR: 189b. 和 *note MAXYEAR: 189c. 之间，包含边界。

 -- 属性: date.month

     1 至 12（含）

 -- 属性: date.day

     返回1到指定年月的天数间的数字。

支持的运算：

运算                                结果：
                                    
---------------------------------------------------------------------------------------
                                    
‘date2 = date1 + timedelta’         `date2' 等于从 `date1' 减去 ‘timedelta.days’ 天
                                    。 (1)
                                    
                                    
‘date2 = date1 - timedelta’         计算 `date2' 的值使得 ‘date2 + timedelta ==
                                    date1’。 (2)
                                    
                                    
‘timedelta = date1 - date2’         (3)
                                    
                                    
‘date1 < date2’                     如果 `date1' 的时间在 `date2' 之前则认为 `date1'
                                    小于 `date2' 。 (4)
                                    

注释:

  1. 如果 ‘timedelta.days > 0’ 则 `date2' 将在时间线上前进，如果
     ‘timedelta.days < 0’ 则将后退。 操作完成后 ‘date2 - date1 ==
     timedelta.days’。 ‘timedelta.seconds’ 和 ‘timedelta.microseconds’ 会
     被忽略。 如果 ‘date2.year’ 将小于 *note MINYEAR: 189b. 或大于 *note
     MAXYEAR: 189c. 则会引发 *note OverflowError: 968.。

  2. ‘timedelta.seconds’ 和 ‘timedelta.microseconds’ 会被忽略。

  3. 此值完全精确且不会溢出。 操作完成后 timedelta.seconds 和
     timedelta.microseconds 均为 0，并且 date2 + timedelta == date1。

  4. 换句话说，当且仅当 ‘date1.toordinal() < date2.toordinal()’ 时
     ‘date1 < date2’。 日期比较会引发 *note TypeError: 193.，如果比较目
     标不为 *note date: 194. 对象的话。 不过也可能会返回
     ‘NotImplemented’，如果比较目标具有 ‘timetuple()’ 属性的话。 这个钩
     子给予其他日期对象类型实现混合类型比较的机会。 否则，当 *note date:
     194. 对象与不同类型的对象比较时将会引发 *note TypeError: 193.，除非
     是 ‘==’ 或 ‘!=’ 比较。 后两种情况将分别返回 *note False: 390. 或
     *note True: 4a1.。

在布尔运算中，所有 *note date: 194. 对象都会被视为真值。

实例方法：

 -- 方法: date.replace (year=self.year, month=self.month, day=self.day)

     返回一个具有同样值的日期，除非通过任何关键字参数给出了某些形参的新
     值。

     示例:

          >>> from datetime import date
          >>> d = date(2002, 12, 31)
          >>> d.replace(day=26)
          datetime.date(2002, 12, 26)

 -- 方法: date.timetuple ()

     返回一个 *note time.struct_time: 5a2.，即 *note time.localtime():
     f5d. 所返回的类型。

     hours, minutes 和 seconds 值均为 0，且 DST 旗标值为 -1。

     ‘d.timetuple()’ 等价于:

          time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))

     其中 ‘yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1’ 是
     当前年份中的日期序号，1 月 1 日的序号为 ‘1’。

 -- 方法: date.toordinal ()

     返回日期的预期格列高利历序号，其中公元 1 年 1 月 1 日的序号为 1。 对
     于任意 *note date: 194. 对象 `d'，‘date.fromordinal(d.toordinal())
     == d’。

 -- 方法: date.weekday ()

     返回一个整数代表星期几，星期一为0，星期天为6。例如， ‘date(2002,
     12, 4).weekday() == 2’，表示的是星期三。参阅 *note isoweekday():
     18c4.。

 -- 方法: date.isoweekday ()

     返回一个整数代表星期几，星期一为1，星期天为7。例如：‘date(2002, 12,
     4).isoweekday() == 3’,表示星期三。参见 *note weekday(): 18c3, *note
     isocalendar(): 18bc.。

 -- 方法: date.isocalendar ()

     返回一个三元元组，(ISO year, ISO week number, ISO weekday) 。

     ISO 历法是一种被广泛使用的格列高利历。 (2)

     ISO 年由 52 或 53 个完整星期构成，每个星期开始于星期一结束于星期日
     。 一个 ISO 年的第一个星期就是（格列高利）历法的一年中第一个包含星
     期四的星期。 这被称为 1 号星期，这个星期四所在的 ISO 年与其所在的格
     列高利年相同。

     例如，2004 年的第一天是星期四，因此 ISO 2004 年的第一个星期开始于
     2003 年 12 月 29 日星期一，结束于 2004 年 1 月 4 日星期日:

          >>> from datetime import date
          >>> date(2003, 12, 29).isocalendar()
          (2004, 1, 1)
          >>> date(2004, 1, 4).isocalendar()
          (2004, 1, 7)

 -- 方法: date.isoformat ()

     返回一个以 ISO 8601 格式 ‘YYYY-MM-DD’ 来表示日期的字符串:

          >>> from datetime import date
          >>> date(2002, 12, 4).isoformat()
          '2002-12-04'

     这是 *note date.fromisoformat(): 10a7. 的逆操作。

 -- 方法: date.__str__ ()

     对于日期对象 `d', ‘str(d)’ 等价于 ‘d.isoformat()’ 。

 -- 方法: date.ctime ()

     返回一个表示日期的字符串:

          >>> from datetime import date
          >>> date(2002, 12, 4).ctime()
          'Wed Dec  4 00:00:00 2002'

     ‘d.ctime()’ 等效于:

          time.ctime(time.mktime(d.timetuple()))

     在原生 C ‘ctime()’ 函数 (*note time.ctime(): 18c7. 会发起调用该函数
     ，但 *note date.ctime(): 18c6. 则不会) 遵循 C 标准的平台上。

 -- 方法: date.strftime (format)

     返回一个由显式格式字符串所指明的代表日期的字符串。 表示时、分或秒的
     格式代码值将为 0。 要获取格式指令的完整列表请参阅 *note strftime()
     和 strptime() 的行为: 18c8.。

 -- 方法: date.__format__ (format)

     与 *note date.strftime(): 540. 相同。 此方法使得为 *note date: 194.
     对象指定以 *note 格式化字符串字面值: 15d. 表示的格式化字符串以及使
     用 *note str.format(): 4e2. 进行格式化成为可能。 要获取格式指令的完
     整列表，请参阅 *note strftime() 和 strptime() 的行为: 18c8.。

* Menu:

* class;date 用法示例: class date 用法示例.

   ---------- Footnotes ----------

   (1) (2) 这与 Dershowitz 和 Reingold 所著 `Calendrical Calculations' 中
“预期格列高利”历法的定义一致，它是适用于该书中所有运算的基础历法。 请参
阅该书了解在预期格利高利历序列与许多其他历法系统之间进行转换的算法。

   (2) (3) 请参阅 R. H. van Gent 所著 ‘ ISO 8601 历法的数学指导
<‘https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm’>‘_
以获取更完整的说明。


File: python.info,  Node: class date 用法示例,  Up: date 对象

5.8.1.9 class:‘date’ 用法示例
.............................

计算距离特定事件天数的例子:

     >>> import time
     >>> from datetime import date
     >>> today = date.today()
     >>> today
     datetime.date(2007, 12, 5)
     >>> today == date.fromtimestamp(time.time())
     True
     >>> my_birthday = date(today.year, 6, 24)
     >>> if my_birthday < today:
     ...     my_birthday = my_birthday.replace(year=today.year + 1)
     >>> my_birthday
     datetime.date(2008, 6, 24)
     >>> time_to_birthday = abs(my_birthday - today)
     >>> time_to_birthday.days
     202

使用 *note date: 194. 的更多例子：

     >>> from datetime import date
     >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
     >>> d
     datetime.date(2002, 3, 11)

     >>> # Methods related to formatting string output
     >>> d.isoformat()
     '2002-03-11'
     >>> d.strftime("%d/%m/%y")
     '11/03/02'
     >>> d.strftime("%A %d. %B %Y")
     'Monday 11. March 2002'
     >>> d.ctime()
     'Mon Mar 11 00:00:00 2002'
     >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
     'The day is 11, the month is March.'

     >>> # Methods for to extracting 'components' under different calendars
     >>> t = d.timetuple()
     >>> for i in t:
     ...     print(i)
     2002                # year
     3                   # month
     11                  # day
     0
     0
     0
     0                   # weekday (0 = Monday)
     70                  # 70th day in the year
     -1
     >>> ic = d.isocalendar()
     >>> for i in ic:
     ...     print(i)
     2002                # ISO year
     11                  # ISO week number
     1                   # ISO day number ( 1 = Monday )

     >>> # A date object is immutable; all operations produce a new object
     >>> d.replace(year=2005)
     datetime.date(2005, 3, 11)


File: python.info,  Node: datetime 对象,  Next: time 对象,  Prev: date 对象,  Up: datetime --- 基本的日期和时间类型

5.8.1.10 ‘datetime’ 对象
........................

*note datetime: 195. 对象是包含来自 *note date: 194. 对象和 *note time:
4fb. 对象的所有信息的单一对象。

与 *note date: 194. 对象一样，*note datetime: 195. 假定当前的格列高利历
向前后两个方向无限延伸；与 *note time: 4fb. 对象一样，*note datetime:
195. 假定每一天恰好有 3600*24 秒。

构造器 ：

 -- 类: datetime.datetime (year, month, day, hour=0, minute=0, second=0,
          microsecond=0, tzinfo=None, *, fold=0)

     `year', `month' 和 `day' 参数是必须的。 `tzinfo' 可以是 ‘None’ 或者
     是一个 *note tzinfo: 388. 子类的实例。 其余的参数必须是在下面范围内
     的整数：

        * ‘MINYEAR <= year <= MAXYEAR’,

        * ‘1 <= month <= 12’,

        * ‘1 <= day <= 指定年月的天数’,

        * ‘0 <= hour < 24’,

        * ‘0 <= minute < 60’,

        * ‘0 <= second < 60’,

        * ‘0 <= microsecond < 1000000’,

        * ‘fold in [0, 1]’.

     如果参数不在这些范围内，则抛出 *note ValueError: 1fc. 异常。

     3.6 新版功能: 增加了 ‘fold’ 参数。

其它构造器，所有的类方法：

 -- 方法: classmethod datetime.today ()

     返回表示当前地方时的 datetime 对象，其中 *note tzinfo: 18ad. 为
     ‘None’。

     等价于:

          datetime.fromtimestamp(time.time())

     另请参阅 *note now(): 1010, *note fromtimestamp(): 109b.。

     此方法的功能等价于 *note now(): 1010.，但是不带 ‘tz’ 形参。

 -- 方法: classmethod datetime.now (tz=None)

     返回表示当前地方时的 date 和 time 对象。

     如果可选参数 `tz' 为 ‘None’ 或未指定，这就类似于 *note today():
     18cd.，但该方法会在可能的情况下提供比通过 *note time.time(): 326. 时
     间戳所获时间值更高的精度（例如，在提供了 C ‘gettimeofday()’ 函数的
     平台上就可以做到这一点）。

     如果 `tz' 不为 ‘None’，它必须是 *note tzinfo: 388. 子类的一个实例，
     并且当前日期和时间将被转换到 `tz' 时区。

     此函数可以替代 *note today(): 18cd. 和 *note utcnow(): 18ce.。

 -- 方法: classmethod datetime.utcnow ()

     返回表示当前 UTC 时间的 date 和 time，其中 *note tzinfo: 18ad. 为
     ‘None’。

     这类似于 *note now(): 1010.，但返回的是当前 UTC 日期和时间，类型为
     简单型 *note datetime: 195. 对象。 感知型的当前 UTC 日期时间可通过
     调用 ‘datetime.now(timezone.utc)’ 来获得。 另请参阅 *note now():
     1010.。

          警告: 由于简单型 ‘datetime’ 对象会被许多 ‘datetime’ 方法当作本
          地时间来处理，最好是使用感知型日期时间对象来表示 UTC 时间。 因
          此，创建表示当前 UTC 时间的对象的推荐方式是通过调用
          ‘datetime.now(timezone.utc)’。

 -- 方法: classmethod datetime.fromtimestamp (timestamp, tz=None)

     返回对应于 POSIX 时间戳例如 *note time.time(): 326. 的返回值的本地
     日期和时间。 如果可选参数 `tz' 为 ‘None’ 或未指定，时间戳会被转换为
     所在平台的本地日期和时间，返回的 *note datetime: 195. 对象将为天真
     型。

     如果 `tz' 不为 ‘None’，它必须是 *note tzinfo: 388. 子类的一个实例，
     并且时间戳将被转换到 `tz' 指定的时区。

     *note fromtimestamp(): 109b. 可能会引发 *note OverflowError: 968.，
     如果时间戳数值超出所在平台 C ‘localtime()’ 或 ‘gmtime()’ 函数的支持
     范围的话，并会在 ‘localtime()’ 或 ‘gmtime()’ 报错时引发 *note
     OSError: 1d4.。 通常该数值会被限制在 1970 年至 2038 年之间。 请注意
     在时间戳概念包含闰秒的非 POSIX 系统上，闰秒会被 *note
     fromtimestamp(): 109b. 所忽略，结果可能导致两个相差一秒的时间戳产生
     相同的 *note datetime: 195. 对象。 相比 *note utcfromtimestamp():
     18cf. 更推荐使用此方法。

     在 3.3 版更改: 引发 *note OverflowError: 968. 而不是 *note
     ValueError: 1fc.，如果时间戳数值超出所在平台 C ‘localtime()’ 或
     ‘gmtime()’ 函数的支持范围的话。 并会在 ‘localtime()’ 或 ‘gmtime()’
     出错时引发 *note OSError: 1d4. 而不是 *note ValueError: 1fc.。

     在 3.6 版更改: *note fromtimestamp(): 109b. 可能返回 *note fold:
     4fc. 值设为 1 的实例。

 -- 方法: classmethod datetime.utcfromtimestamp (timestamp)

     返回对应于 POSIX 时间戳的 UTC *note datetime: 195.，其中 *note
     tzinfo: 18ad. 值为 ‘None’。 （结果为简单型对象。）

     这可能引发 *note OverflowError: 968.，如果时间戳数值超出所在平台 C
     ‘gmtime()’ 函数的支持范围的话，并会在 ‘gmtime()’ 报错时引发 *note
     OSError: 1d4.。 通常该数值会被限制在 1970 至 2038 年之间。

     要得到一个感知型 *note datetime: 195. 对象，应调用 *note
     fromtimestamp(): 109b.:

          datetime.fromtimestamp(timestamp, timezone.utc)

     在 POSIX 兼容的平台上，它等价于以下表达式:

          datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)

     不同之处在于后一种形式总是支持完整年份范围：从 *note MINYEAR: 189b.
     到 *note MAXYEAR: 189c. 的开区间。

          警告: 由于简单型 ‘datetime’ 对象会被许多 ‘datetime’ 方法当作本
          地时间来处理，最好是使用感知型日期时间对象来表示 UTC 时间。 因
          此，创建表示特定 UTC 时间戳的日期时间对象的推荐方式是通过调用
          ‘datetime.fromtimestamp(timestamp, tz=timezone.utc)’。

     在 3.3 版更改: 引发 *note OverflowError: 968. 而不是 *note
     ValueError: 1fc.，如果时间戳数值超出所在平台 C ‘gmtime()’ 函数的支
     持范围的话。 并会在 ‘gmtime()’ 出错时引发 *note OSError: 1d4. 而不
     是 *note ValueError: 1fc.。

 -- 方法: classmethod datetime.fromordinal (ordinal)

     返回对应于预期格列高利历序号的 *note datetime: 195.，其中公元 1 年
     1 月 1 日的序号为 1。 除非 ‘1 <= ordinal <=
     datetime.max.toordinal()’ 否则会引发 *note ValueError: 1fc.。 结果
     的 hour, minute, second 和 microsecond 值均为 0，并且 *note tzinfo:
     18ad. 值为 ‘None’。

 -- 方法: classmethod datetime.combine (date, time, tzinfo=self.tzinfo)

     返回一个新的 *note datetime: 195. 对象，对象的日期部分等于给定的
     *note date: 194. 对象的值，而其时间部分等于给定的 *note time: 4fb.
     对象的值。 如果提供了 `tzinfo' 参数，其值会被用来设置结果的 *note
     tzinfo: 18ad. 属性，否则将使用 `time' 参数的 *note tzinfo: 18a5. 属
     性。

     对于任意 *note datetime: 195. 对象 `d'，‘d ==
     datetime.combine(d.date(), d.time(), d.tzinfo)’。 如果 date 是一个
     *note datetime: 195. 对象，它的时间部分和 *note tzinfo: 18ad. 属性
     会被忽略。

     在 3.6 版更改: 增加了 `tzinfo' 参数。

 -- 方法: classmethod datetime.fromisoformat (date_string)

     返回一个对应于 *note date.isoformat(): 18bb. 和 *note
     datetime.isoformat(): 541. 所提供的某一种 `date_string' 的 *note
     datetime: 195. 对象。

     特别地，此函数支持以下格式的字符串：

          YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]

     其中 ‘*’ 可以匹配任意的单个字符。

          警告: 此函数 `并不' 支持解析任意 ISO 8601 字符串 —— 它的目的只
          是作为 *note datetime.isoformat(): 541. 的逆操作。 在第三方包
          dateutil(1) 中提供了一个更完善的 ISO 8601 解析器
          ‘dateutil.parser.isoparse’。

     示例:

          >>> from datetime import datetime
          >>> datetime.fromisoformat('2011-11-04')
          datetime.datetime(2011, 11, 4, 0, 0)
          >>> datetime.fromisoformat('2011-11-04T00:05:23')
          datetime.datetime(2011, 11, 4, 0, 5, 23)
          >>> datetime.fromisoformat('2011-11-04 00:05:23.283')
          datetime.datetime(2011, 11, 4, 0, 5, 23, 283000)
          >>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')
          datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc)
          >>> datetime.fromisoformat('2011-11-04T00:05:23+04:00')
          datetime.datetime(2011, 11, 4, 0, 5, 23,
              tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))

     3.7 新版功能.

 -- 方法: classmethod datetime.fromisocalendar (year, week, day)

     返回以 year, week 和 day 值指明的 ISO 历法日期所对应的 *note
     datetime: 195.。 该datetime 对象的非日期部分将使用其标准默认值来填
     充。 这是函数 *note datetime.isocalendar(): 18d1. 的逆操作。

     3.8 新版功能.

 -- 方法: classmethod datetime.strptime (date_string, format)

     返回一个对应于 `date_string'，根据 `format' 进行解析得到的 *note
     datetime: 195. 对象。

     这相当于:

          datetime(*(time.strptime(date_string, format)[0:6]))

     如果 date_string 和 format 无法被 *note time.strptime(): d99. 解析
     或它返回一个不是时间元组的值，则将引发 *note ValueError: 1fc.。 要
     获取格式化指令的完整列表，请参阅 *note strftime() 和 strptime()
     的行为: 18c8.。

类属性：

 -- 属性: datetime.min

     最早的可表示 *note datetime: 195.，‘datetime(MINYEAR, 1, 1,
     tzinfo=None)’。

 -- 属性: datetime.max

     最晚的可表示 *note datetime: 195.，‘datetime(MAXYEAR, 12, 31, 23,
     59, 59, 999999, tzinfo=None)’。

 -- 属性: datetime.resolution

     两个不相等的 *note datetime: 195. 对象之间可能的最小间隔，
     ‘timedelta(microseconds=1)’。

实例属性（只读）：

 -- 属性: datetime.year

     在 *note MINYEAR: 189b. 和 *note MAXYEAR: 189c. 之间，包含边界。

 -- 属性: datetime.month

     1 至 12（含）

 -- 属性: datetime.day

     返回1到指定年月的天数间的数字。

 -- 属性: datetime.hour

     取值范围是 ‘range(24)’。

 -- 属性: datetime.minute

     取值范围是 ‘range(60)’。

 -- 属性: datetime.second

     取值范围是 ‘range(60)’。

 -- 属性: datetime.microsecond

     取值范围是 ‘range(1000000)’。

 -- 属性: datetime.tzinfo

     作为 `tzinfo' 参数被传给 *note datetime: 195. 构造器的对象，如果没
     有传入值则为 ‘None’。

 -- 属性: datetime.fold

     取值范围是 ‘[0, 1]’。 用于在重复的时间段中消除边界时间歧义。 （当夏
     令时结束时回拨时钟或由于政治原因导致当明时区的 UTC 时差减少就会出现
     重复的时间段。） 取值 0 (1) 表示两个时刻早于（晚于）所代表的同一边
     界时间。

     3.6 新版功能.

支持的运算：

运算                                        结果：
                                            
---------------------------------------------------------------------------------
                                            
‘datetime2 = datetime1 + timedelta’         (1)
                                            
                                            
‘datetime2 = datetime1 - timedelta’         (2)
                                            
                                            
‘timedelta = datetime1 - datetime2’         (3)
                                            
                                            
‘datetime1 < datetime2’                     比较 *note datetime: 195. 与
                                            *note datetime: 195.。 (4)
                                            

  1. datetime2 是从 datetime1 去掉了一段 timedelta 的结果，如果
     ‘timedelta.days’ > 0 则是在时间线上前进，如果 ‘timedelta.days’ < 0
     则是在时间线上后退。 该结果具有与输入的 datetime 相同的 *note
     tzinfo: 18ad. 属性，并且操作完成后 datetime2 - datetime1 ==
     timedelta。 如果 datetime2.year 将要小于 *note MINYEAR: 189b. 或大
     于 *note MAXYEAR: 189c. 则会引发 *note OverflowError: 968.。 请注意
     即使输入的是一个感知型对象，该方法也不会进行时区调整。

  2. 计算 datetime2 使得 datetime2 + timedelta == datetime1。 与相加操作
     一样，结果具有与输入的 datetime 相同的 *note tzinfo: 18ad. 属性，即
     使输入的是一个感知型对象，该方法也不会进行时区调整。

  3. 从一个 *note datetime: 195. 减去一个 *note datetime: 195. 仅对两个
     操作数均为简单型或均为感知型时有定义。 如果一个是感知型而另一个是简
     单型，则会引发 *note TypeError: 193.。

     如果两个操作数都是简单型，或都是感知型并且具有相同的 *note tzinfo:
     18ad. 属性，则 *note tzinfo: 18ad. 属性会被忽略，并且结果会是一个使
     得 ‘datetime2 + t == datetime1’ 的 *note timedelta: 196. 对象 `t'。
     在此情况下不会进行时区调整。

     如果两个操作数都是感知型且具有不同的 *note tzinfo: 18ad. 属性，
     ‘a-b’ 操作的效果就如同 `a' 和 `b' 首先被转换为简单型 UTC 日期时间。
     结果将是 ‘(a.replace(tzinfo=None) - a.utcoffset()) -
     (b.replace(tzinfo=None) - b.utcoffset())’，除非具体实现绝对不溢出。

  4. 当 `datetime1' 的时间在 `datetime2' 之前则认为 `datetime1' 小于
     `datetime2'。

     如果比较的一方是简单型而另一方是感知型，则如果尝试进行顺序比较将引
     发 *note TypeError: 193.。 对于相等比较，简单型实例将永远不等于感知
     型实例。

     如果两个比较方都是感知型，且具有相同的 *note tzinfo: 18ad. 属性，则
     相同的 *note tzinfo: 18ad. 属性会被忽略并对基本日期时间值进行比较。
     如果两个比较方都是感知型且具有不同的 *note tzinfo: 18ad. 属性，则两
     个比较方将首先通过减去它们的 UTC 差值（使用 ‘self.utcoffset()’ 获取
     ）来进行调整。

     在 3.3 版更改: 感知型和简单型 *note datetime: 195. 实例之间的相等比
     较不会引发 *note TypeError: 193.。

          注解: 为了防止比较操作回退为默认的对象地址比较方式，datetime 比
          较通常会引发 *note TypeError: 193.，如果比较目标不同样为 *note
          datetime: 195. 对象的话。 不过也可能会返回 ‘NotImplemented’，
          如果比较目标具有 ‘timetuple()’ 属性的话。 这个钩子给予其他种类
          的日期对象实现混合类型比较的机会。 如果未实现，则当 *note
          datetime: 195. 对象与不同类型比较时将会引发 *note TypeError:
          193.，除非是 ‘==’ 或 ‘!=’ 比较。 后两种情况将分别返回 *note
          False: 390. 或 *note True: 4a1.。

实例方法：

 -- 方法: datetime.date ()

     返回具有同样 year, month 和 day 值的 *note date: 194. 对象。

 -- 方法: datetime.time ()

     返回具有同样 hour, minute, second, microsecond 和 fold 值的 *note
     time: 4fb. 对象。 *note tzinfo: 18ad. 值为 ‘None’。 另请参见 *note
     timetz(): 18d7. 方法。

     在 3.6 版更改: fold 值会被复制给返回的 *note time: 4fb. 对象。

 -- 方法: datetime.timetz ()

     返回具有同样 hour, minute, second, microsecond, fold 和 tzinfo 属性
     性的 *note time: 4fb. 对象。 另请参见 *note time(): 10b. 方法。

     在 3.6 版更改: fold 值会被复制给返回的 *note time: 4fb. 对象。

 -- 方法: datetime.replace (year=self.year, month=self.month,
          day=self.day, hour=self.hour, minute=self.minute,
          second=self.second, microsecond=self.microsecond,
          tzinfo=self.tzinfo, *, fold=0)

     返回一个具有同样属性值的 datetime，除非通过任何关键字参数为某些属性
     指定了新值。 请注意可以通过指定 ‘tzinfo=None’ 来从一个感知型
     datetime 创建一个简单型 datetime 而不必转换日期和时间数据。

     3.6 新版功能: 增加了 ‘fold’ 参数。

 -- 方法: datetime.astimezone (tz=None)

     返回一个具有新的 *note tzinfo: 18ad. 属性 `tz' 的 *note datetime:
     195. 对象，并会调整日期和时间数据使得结果对应的 UTC 时间与 `self' 相
     同，但为 `tz' 时区的本地时间。

     如果给出了 `tz'，则它必须是一个 *note tzinfo: 388. 子类的实例，并且
     其 *note utcoffset(): 18d9. 和 *note dst(): 18da. 方法不可返回
     ‘None’。 如果 `self' 为简单型，它会被假定为基于系统时区表示的时间。

     如果调用时不传入参数 (或传入 ‘tz=None’) 则将假定目标时区为系统的本
     地时区。 转换后 datetime 实例的 ‘.tzinfo’ 属性将被设为一个 *note
     timezone: a09. 实例，时区名称和时差值将从 OS 获取。

     如果 ‘self.tzinfo’ 为 `tz'，‘self.astimezone(tz)’ 等于 `self': 不会
     对日期或时间数据进行调整。 否则结果为 `tz' 时区的本地时间，代表的
     UTC 时间与 `self' 相同：在 ‘astz = dt.astimezone(tz)’ 之后，‘astz -
     astz.utcoffset()’ 将具有与 ‘dt - dt.utcoffset()’ 相同的日期和时间数
     据。

     如果你只是想要附加一个时区对象 `tz' 到一个 datetime 对象 `dt' 而不
     调整日期和时间数据，请使用 ‘dt.replace(tzinfo=tz)’。 如果你只想从一
     个感知型 datetime 对象 `dt' 移除时区对象，请使用
     ‘dt.replace(tzinfo=None)’。

     请注意默认的 *note tzinfo.fromutc(): 18db. 方法在 *note tzinfo:
     388. 的子类中可以被重载，从而影响 *note astimezone(): 197. 的返回结
     果。 如果忽略出错的情况，*note astimezone(): 197. 的行为就类似于:

          def astimezone(self, tz):
              if self.tzinfo is tz:
                  return self
              # Convert self to UTC, and attach the new time zone object.
              utc = (self - self.utcoffset()).replace(tzinfo=tz)
              # Convert from UTC to tz's local time.
              return tz.fromutc(utc)

     在 3.3 版更改: `tz' 现在可以被省略。

     在 3.6 版更改: *note astimezone(): 197. 方法可以由简单型实例调用，
     这将假定其表示本地时间。

 -- 方法: datetime.utcoffset ()

     如果 *note tzinfo: 18ad. 为 ‘None’，则返回 ‘None’，否则返回
     ‘self.tzinfo.utcoffset(self)’，并且在后者不返回 ‘None’ 或者一个幅度
     小于一天的 *note timedelta: 196. 对象时将引发异常。

     在 3.7 版更改: UTC 时差不再限制为一个整数分钟值。

 -- 方法: datetime.dst ()

     如果 *note tzinfo: 18ad. 为 ‘None’，则返回 ‘None’，否则返回
     ‘self.tzinfo.dst(self)’，并且在后者不返回 ‘None’ 或者一个幅度小于一
     天的 *note timedelta: 196. 对象时将引发异常。

     在 3.7 版更改: DST 差值不再限制为一个整数分钟值。

 -- 方法: datetime.tzname ()

     如果 *note tzinfo: 18ad. 为 ‘None’，则返回 ‘None’，否则返回
     ‘self.tzinfo.tzname(self)’，如果后者不返回 ‘None’ 或者一个字符串对
     象则将引发异常。

 -- 方法: datetime.timetuple ()

     返回一个 *note time.struct_time: 5a2.，即 *note time.localtime():
     f5d. 所返回的类型。

     ‘d.timetuple()’ 等价于:

          time.struct_time((d.year, d.month, d.day,
                            d.hour, d.minute, d.second,
                            d.weekday(), yday, dst))

     其中 ‘yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1’ 是
     日期在当前年份中的序号，起始序号 ‘1’ 表示 1 月 1 日。 结果的
     ‘tm_isdst’ 旗标的设定会依据 *note dst(): 18da. 方法：如果 *note
     tzinfo: 18ad. 为 ‘None’ 或 *note dst(): 18da. 返回 ‘None’，则
     ‘tm_isdst’ 将设为 ‘-1’；否则如果 *note dst(): 18da. 返回一个非零值
     ，则 ‘tm_isdst’ 将设为 ‘1’；在其他情况下 ‘tm_isdst’ 将设为 ‘0’。

 -- 方法: datetime.utctimetuple ()

     如果 *note datetime: 195. 实例 `d' 为简单型，这类似于
     ‘d.timetuple()’，不同之处在于 ‘tm_isdst’ 会强制设为 0，无论
     ‘d.dst()’ 返回什么结果。 DST 对于 UTC 时间永远无效。

     如果 `d' 为感知型， `d' 会通过减去 ‘d.utcoffset()’ 来标准化为 UTC 时
     间，并返回该标准化时间所对应的 *note time.struct_time: 5a2.。
     ‘tm_isdst’ 会强制设为 0。 请注意如果 `d'.year 为 ‘MINYEAR’ 或
     ‘MAXYEAR’ 并且 UTC 调整超出一年的边界则可能引发 *note
     OverflowError: 968.。

          警告: 由于简单型 ‘datetime’ 对象会被许多 ‘datetime’ 方法当作本
          地时间来处理，最好是使用感知型日期时间来表示 UTC 时间；因此，
          使用 ‘utcfromtimetuple’ 可能会给出误导性的结果。 如果你有一个
          表示 UTC 的简单型 ‘datetime’，请使用
          ‘datetime.replace(tzinfo=timezone.utc)’ 将其改为感知型，这样你
          才能使用 *note datetime.timetuple(): 18dd.。

 -- 方法: datetime.toordinal ()

     返回日期的预期格列高利历序号。 与 ‘self.date().toordinal()’ 相同。

 -- 方法: datetime.timestamp ()

     返回对应于 *note datetime: 195. 实例的 POSIX 时间戳。 此返回值是与
     *note time.time(): 326. 返回值类似的 *note float: 188. 对象。

     简单型 *note datetime: 195. 实例会假定为代表本地时间，并且此方法依
     赖于平台的 C ‘mktime()’ 函数来执行转换。 由于在许多平台上 *note
     datetime: 195. 支持的范围比 ‘mktime()’ 更广，对于极其遥远的过去或未
     来此方法可能引发 *note OverflowError: 968.。

     对于感知型 *note datetime: 195. 实例，返回值的计算方式为:

          (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()

     3.3 新版功能.

     在 3.6 版更改: *note timestamp(): 9ea. 方法使用 *note fold: 4fc. 属
     性来消除重复间隔中的时间歧义。

          注解: 没有一个方法能直接从表示 UTC 时间的简单型 *note
          datetime: 195. 实例获取 POSIX 时间戳。 如果你的应用程序使用此
          惯例并且你的系统时区不是设为 UTC，你可以通过提供
          ‘tzinfo=timezone.utc’ 来获取 POSIX 时间戳:

               timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

          或者通过直接计算时间戳:

               timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

 -- 方法: datetime.weekday ()

     返回一个整数代表星期几，星期一为 0，星期天为 6。 相当于
     ‘self.date().weekday()’。 另请参阅 *note isoweekday(): 18e1.。

 -- 方法: datetime.isoweekday ()

     返回一个整数代表星期几，星期一为 1，星期天为 7。 相当于
     ‘self.date().isoweekday()’。 另请参阅 *note weekday(): 18e0, *note
     isocalendar(): 18d1.。

 -- 方法: datetime.isocalendar ()

     返回一个 3 元组 (ISO 年份, ISO 周序号, ISO 周日期)。 等同于
     ‘self.date().isocalendar()’。

 -- 方法: datetime.isoformat (sep='T', timespec='auto')

     返回一个以 ISO 8601 格式表示的日期和时间字符串：

        - ‘YYYY-MM-DDTHH:MM:SS.ffffff’，如果 *note microsecond: 18ac. 不
          为 0

        - ‘YYYY-MM-DDTHH:MM:SS’，如果 *note microsecond: 18ac. 为 0

     如果 *note utcoffset(): 18d9. 返回值不为 ‘None’，则添加一个字符串来
     给出 UTC 时差：

        - ‘YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]’，如果 *note
          microsecond: 18ac. 不为 0

        - ‘YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]]’，如果 *note
          microsecond: 18ac. 为 0

     示例:

          >>> from datetime import datetime, timezone
          >>> datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat()
          '2019-05-18T15:17:08.132263'
          >>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat()
          '2019-05-18T15:17:00+00:00'

     可选参数 `sep' (默认为 ‘'T'’) 为单个分隔字符，会被放在结果的日期和
     时间两部分之间。 例如:

          >>> from datetime import tzinfo, timedelta, datetime
          >>> class TZ(tzinfo):
          ...     """A time zone with an arbitrary, constant -06:39 offset."""
          ...     def utcoffset(self, dt):
          ...         return timedelta(hours=-6, minutes=-39)
          ...
          >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
          '2002-12-25 00:00:00-06:39'
          >>> datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat()
          '2009-11-27T00:00:00.000100-06:39'

     可选参数 `timespec' 要包含的额外时间组件值 (默认为 ‘'auto'’)。它可
     以是以下值之一：

        - ‘'auto'’: 如果 *note microsecond: 18ac. 为 0 则与 ‘'seconds'’
          相同，否则与 ‘'microseconds'’ 相同。

        - ‘'hours'’: 以两个数码的 ‘HH’ 格式 包含 *note hour: 18a9.。

        - ‘'minutes'’: 以 ‘HH:MM’ 格式包含 *note hour: 18a9. 和 *note
          minute: 18aa.。

        - ‘'seconds'’: 以 ‘HH:MM:SS’ 格式包含 *note hour: 18a9, *note
          minute: 18aa. 和 *note second: 18ab.。

        - ‘'milliseconds'’: 包含完整时间，但将秒值的小数部分截断至微秒。
          格式为 ‘HH:MM:SS.sss’

        - ‘'microseconds'’: 以 ‘HH:MM:SS.ffffff’ 格式包含完整时间。

          注解: 排除掉的时间部分将被截断，而不是被舍入。

     对于无效的 `timespec' 参数将引发 *note ValueError: 1fc.:

          >>> from datetime import datetime
          >>> datetime.now().isoformat(timespec='minutes')
          '2002-12-25T00:00'
          >>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
          >>> dt.isoformat(timespec='microseconds')
          '2015-01-01T12:30:59.000000'

     3.6 新版功能: 增加了 `timespec' 参数。

 -- 方法: datetime.__str__ ()

     对于 *note datetime: 195. 实例 `d'，‘str(d)’ 等价于 ‘d.isoformat('
     ')’。

 -- 方法: datetime.ctime ()

     返回一个表示日期和时间的字符串:

          >>> from datetime import datetime
          >>> datetime(2002, 12, 4, 20, 30, 40).ctime()
          'Wed Dec  4 20:30:40 2002'

     输出字符串将 `并不' 包括时区信息，无论输入的是感知型还是简单型。

     ‘d.ctime()’ 等效于:

          time.ctime(time.mktime(d.timetuple()))

     在原生 C ‘ctime()’ 函数 (*note time.ctime(): 18c7. 会发起调用该函数
     ，但 *note datetime.ctime(): 18e3. 则不会) 遵循 C 标准的平台上。

 -- 方法: datetime.strftime (format)

     返回一个由显式格式字符串所指明的代表日期和时间的字符串，要获取格式
     指令的完整列表，请参阅 *note strftime() 和 strptime() 的行为:
     18c8.。

 -- 方法: datetime.__format__ (format)

     与 *note datetime.strftime(): 53f. 相同。 此方法使得为 *note
     datetime: 195. 对象指定以 *note 格式化字符串字面值: 15d. 表示的格式
     化字符串以及使用 *note str.format(): 4e2. 进行格式化成为可能。 要获
     取格式指令的完整列表，请参阅 *note strftime() 和 strptime() 的行为:
     18c8.。

* Menu:

* 用法示例; datetime: 用法示例 datetime.

   ---------- Footnotes ----------

   (1) 
https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse


File: python.info,  Node: 用法示例 datetime,  Up: datetime 对象

5.8.1.11 用法示例: ‘datetime’
.............................

使用 *note datetime: 195. 对象的例子：

     >>> from datetime import datetime, date, time, timezone

     >>> # Using datetime.combine()
     >>> d = date(2005, 7, 14)
     >>> t = time(12, 30)
     >>> datetime.combine(d, t)
     datetime.datetime(2005, 7, 14, 12, 30)

     >>> # Using datetime.now()
     >>> datetime.now()
     datetime.datetime(2007, 12, 6, 16, 29, 43, 79043)   # GMT +1
     >>> datetime.now(timezone.utc)
     datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone.utc)

     >>> # Using datetime.strptime()
     >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
     >>> dt
     datetime.datetime(2006, 11, 21, 16, 30)

     >>> # Using datetime.timetuple() to get tuple of all attributes
     >>> tt = dt.timetuple()
     >>> for it in tt:
     ...     print(it)
     ...
     2006    # year
     11      # month
     21      # day
     16      # hour
     30      # minute
     0       # second
     1       # weekday (0 = Monday)
     325     # number of days since 1st January
     -1      # dst - method tzinfo.dst() returned None

     >>> # Date in ISO format
     >>> ic = dt.isocalendar()
     >>> for it in ic:
     ...     print(it)
     ...
     2006    # ISO year
     47      # ISO week
     2       # ISO weekday

     >>> # Formatting a datetime
     >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
     'Tuesday, 21. November 2006 04:30PM'
     >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
     'The day is 21, the month is November, the time is 04:30PM.'

以下示例定义了一个 *note tzinfo: 388. 子类，它捕获 Kabul, Afghanistan 时
区的信息，该时区使用 +4 UTC 直到 1945 年，之后则使用 +4:30 UTC:

     from datetime import timedelta, datetime, tzinfo, timezone

     class KabulTz(tzinfo):
         # Kabul used +4 until 1945, when they moved to +4:30
         UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc)

         def utcoffset(self, dt):
             if dt.year < 1945:
                 return timedelta(hours=4)
             elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, 30):
                 # An ambiguous ("imaginary") half-hour range representing
                 # a 'fold' in time due to the shift from +4 to +4:30.
                 # If dt falls in the imaginary range, use fold to decide how
                 # to resolve. See PEP495.
                 return timedelta(hours=4, minutes=(30 if dt.fold else 0))
             else:
                 return timedelta(hours=4, minutes=30)

         def fromutc(self, dt):
             # Follow same validations as in datetime.tzinfo
             if not isinstance(dt, datetime):
                 raise TypeError("fromutc() requires a datetime argument")
             if dt.tzinfo is not self:
                 raise ValueError("dt.tzinfo is not self")

             # A custom implementation is required for fromutc as
             # the input to this function is a datetime with utc values
             # but with a tzinfo set to self.
             # See datetime.astimezone or fromtimestamp.
             if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE:
                 return dt + timedelta(hours=4, minutes=30)
             else:
                 return dt + timedelta(hours=4)

         def dst(self, dt):
             # Kabul does not observe daylight saving time.
             return timedelta(0)

         def tzname(self, dt):
             if dt >= self.UTC_MOVE_DATE:
                 return "+04:30"
             return "+04"

上述 ‘KabulTz’ 的用法:

     >>> tz1 = KabulTz()

     >>> # Datetime before the change
     >>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1)
     >>> print(dt1.utcoffset())
     4:00:00

     >>> # Datetime after the change
     >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1)
     >>> print(dt2.utcoffset())
     4:30:00

     >>> # Convert datetime to another time zone
     >>> dt3 = dt2.astimezone(timezone.utc)
     >>> dt3
     datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)
     >>> dt2
     datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())
     >>> dt2 == dt3
     True


File: python.info,  Node: time 对象,  Next: tzinfo 对象,  Prev: datetime 对象,  Up: datetime --- 基本的日期和时间类型

5.8.1.12 ‘time’ 对象
....................

一个 *note time: 10b. 对象代表某日的（本地）时间，它独立于任何特定日期，
并可通过 *note tzinfo: 388. 对象来调整。

 -- 类: datetime.time (hour=0, minute=0, second=0, microsecond=0,
          tzinfo=None, *, fold=0)

     所有参数都是可选的。 `tzinfo' 可以是 ‘None’，或者是一个 *note
     tzinfo: 388. 子类的实例。 其余的参数必须是在下面范围内的整数：

        * ‘0 <= hour < 24’,

        * ‘0 <= minute < 60’,

        * ‘0 <= second < 60’,

        * ‘0 <= microsecond < 1000000’,

        * ‘fold in [0, 1]’.

     如果给出一个此范围以外的参数，则会引发 *note ValueError: 1fc.。 所
     有参数值默认为 ‘0’，只有 `tzinfo' 默认为 *note None: 158.。

类属性：

 -- 属性: time.min

     早最的可表示 *note time: 4fb, ‘time(0, 0, 0, 0)’。

 -- 属性: time.max

     最晚的可表示 *note time: 4fb, ‘time(23, 59, 59, 999999)’。

 -- 属性: time.resolution

     两个不相等的 *note time: 4fb. 对象之间可能的最小间隔，
     ‘timedelta(microseconds=1)’，但是请注意 *note time: 4fb. 对象并不支
     持算术运算。

实例属性（只读）：

 -- 属性: time.hour

     取值范围是 ‘range(24)’。

 -- 属性: time.minute

     取值范围是 ‘range(60)’。

 -- 属性: time.second

     取值范围是 ‘range(60)’。

 -- 属性: time.microsecond

     取值范围是 ‘range(1000000)’。

 -- 属性: time.tzinfo

     作为 tzinfo 参数被传给 *note time: 4fb. 构造器的对象，如果没有传入
     值则为 ‘None’。

 -- 属性: time.fold

     取值范围是 ‘[0, 1]’。 用于在重复的时间段中消除边界时间歧义。 （当夏
     令时结束时回拨时钟或由于政治原因导致当明时区的 UTC 时差减少就会出现
     重复的时间段。） 取值 0 (1) 表示两个时刻早于（晚于）所代表的同一边
     界时间。

     3.6 新版功能.

*note time: 4fb. 对象支持 *note time: 4fb. 与 *note time: 4fb. 的比较，
当 `a' 时间在 `b' 之前时，则认为 `a' 小于 `b'。 如果比较的一方是简单型而
另一方是感知型，则如果尝试进行顺序比较将引发 *note TypeError: 193.。 对
于相等比较，简单型实例将永远不等于感知型实例。

如果两个比较方都是感知型，且具有相同的 *note tzinfo: 18a5. 属性，相同的
*note tzinfo: 18a5. 属性会被忽略并对基本时间值进行比较。 如果两个比较方
都是感知型且具有不同的 *note tzinfo: 18a5. 属性，两个比较方将首先通过减
去它们的 UTC 时差（从 ‘self.utcoffset()’ 获取）来进行调整。 为了防止将混
合类型比较回退为基于对象地址的默认比较，当 *note time: 4fb. 对象与不同类
型的对象比较时，将会引发 *note TypeError: 193.，除非比较运算符是 ‘==’ 或
‘!=’。 在后两种情况下将分别返回 *note False: 390. 或 *note True: 4a1.。

在 3.3 版更改: 感知型和简单型 *note time: 4fb. 实例之间的相等比较不会引
发 *note TypeError: 193.。

在布尔运算时，*note time: 4fb. 对象总是被视为真值。

在 3.5 版更改: 在 Python 3.5 之前，如果一个 *note time: 4fb. 对象代表
UTC 午夜零时则会被视为假值。 此行为被认为容易引发困惑和错误，因此从
Python 3.5 起已被去除。 详情参见 bpo-13936(1)。

其他构造方法：

 -- 方法: classmethod time.fromisoformat (time_string)

     返回对应于 *note time.isoformat(): 18ec. 所提供的某种 `time_string'
     格式的 *note time: 4fb.。 特别地，此函数支持以下格式的字符串：

          HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]

          警告: 此方法 `并不' 支持解析任意 ISO 8601 字符串。 它的目的只
          是作为 *note time.isoformat(): 18ec. 的逆操作。

     示例:

          >>> from datetime import time
          >>> time.fromisoformat('04:23:01')
          datetime.time(4, 23, 1)
          >>> time.fromisoformat('04:23:01.000384')
          datetime.time(4, 23, 1, 384)
          >>> time.fromisoformat('04:23:01+04:00')
          datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))

     3.7 新版功能.

实例方法：

 -- 方法: time.replace (hour=self.hour, minute=self.minute,
          second=self.second, microsecond=self.microsecond,
          tzinfo=self.tzinfo, *, fold=0)

     返回一个具有同样属性值的 *note time: 4fb.，除非通过任何关键字参数指
     定了某些属性值。 请注意可以通过指定 ‘tzinfo=None’ 从一个感知型
     *note time: 4fb. 创建一个简单型 *note time: 4fb.，而不必转换时间数
     据。

     3.6 新版功能: 增加了 ‘fold’ 参数。

 -- 方法: time.isoformat (timespec='auto')

     返回表示为下列 ISO 8601 格式之一的时间字符串：

        - ‘HH:MM:SS.ffffff’，如果 *note microsecond: 18a4. 不为 0

        - ‘HH:MM:SS’，如果 *note microsecond: 18a4. 为 0

        - ‘HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]’，如果 *note utcoffset():
          18ee. 不返回 ‘None’

        - ‘HH:MM:SS+HH:MM[:SS[.ffffff]]’，如果 *note microsecond: 18a4.
          为 0 并且 *note utcoffset(): 18ee. 不返回 ‘None’

     可选参数 `timespec' 要包含的额外时间组件值 (默认为 ‘'auto'’)。它可
     以是以下值之一：

        - ‘'auto'’: 如果 *note microsecond: 18a4. 为 0 则与 ‘'seconds'’
          相同，否则与 ‘'microseconds'’ 相同。

        - ‘'hours'’: 以两个数码的 ‘HH’ 格式 包含 *note hour: 18a1.。

        - ‘'minutes'’: 以 ‘HH:MM’ 格式包含 *note hour: 18a1. 和 *note
          minute: 18a2.。

        - ‘'seconds'’: 以 ‘HH:MM:SS’ 格式包含 *note hour: 18a1, *note
          minute: 18a2. 和 *note second: 18a3.。

        - ‘'milliseconds'’: 包含完整时间，但将秒值的小数部分截断至微秒。
          格式为 ‘HH:MM:SS.sss’

        - ‘'microseconds'’: 以 ‘HH:MM:SS.ffffff’ 格式包含完整时间。

          注解: 排除掉的时间部分将被截断，而不是被舍入。

     对于无效的 `timespec' 参数将引发 *note ValueError: 1fc.。

     示例:

          >>> from datetime import time
          >>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes')
          '12:34'
          >>> dt = time(hour=12, minute=34, second=56, microsecond=0)
          >>> dt.isoformat(timespec='microseconds')
          '12:34:56.000000'
          >>> dt.isoformat(timespec='auto')
          '12:34:56'

     3.6 新版功能: 增加了 `timespec' 参数。

 -- 方法: time.__str__ ()

     对于时间对象 `t', ‘str(t)’ 等价于 ‘t.isoformat()’。

 -- 方法: time.strftime (format)

     返回一个由显式格式字符串所指明的代表时间的字符串。 要获取格式指令的
     完整列表，请参阅 *note strftime() 和 strptime() 的行为: 18c8.。

 -- 方法: time.__format__ (format)

     与 *note time.strftime(): 18f0. 相同。 此方法使得为 *note time:
     4fb. 对象指定以 *note 格式化字符串字面值: 15d. 表示的格式化字符串以
     及使用 *note str.format(): 4e2. 进行格式化成为可能。 要获取格式指令
     的完整列表，请参阅 *note strftime() 和 strptime() 的行为: 18c8.。

 -- 方法: time.utcoffset ()

     如果 *note tzinfo: 18a5. 为 ‘None’，则返回 ‘None’，否则返回
     ‘self.tzinfo.utcoffset(None)’，并且在后者不返回 ‘None’ 或一个幅度小
     于一天的 a *note timedelta: 196. 对象时将引发异常。

     在 3.7 版更改: UTC 时差不再限制为一个整数分钟值。

 -- 方法: time.dst ()

     如果 *note tzinfo: 18a5. 为 ‘None’，则返回 ‘None’，否则返回
     ‘self.tzinfo.dst(None)’，并且在后者不返回 ‘None’ 或者一个幅度小于一
     天的 *note timedelta: 196. 对象时将引发异常。

     在 3.7 版更改: DST 差值不再限制为一个整数分钟值。

 -- 方法: time.tzname ()

     如果 *note tzinfo: 18a5. 为 ‘None’，则返回 ‘None’，否则返回
     ‘self.tzinfo.tzname(None)’，如果后者不返回 ‘None’ 或者一个字符串对
     象则将引发异常。

* Menu:

* 用法示例; time: 用法示例 time.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13936


File: python.info,  Node: 用法示例 time,  Up: time 对象

5.8.1.13 用法示例: ‘time’
.........................

使用 *note time: 4fb. 对象的例子:

     >>> from datetime import time, tzinfo, timedelta
     >>> class TZ1(tzinfo):
     ...     def utcoffset(self, dt):
     ...         return timedelta(hours=1)
     ...     def dst(self, dt):
     ...         return timedelta(0)
     ...     def tzname(self,dt):
     ...         return "+01:00"
     ...     def  __repr__(self):
     ...         return f"{self.__class__.__name__}()"
     ...
     >>> t = time(12, 10, 30, tzinfo=TZ1())
     >>> t
     datetime.time(12, 10, 30, tzinfo=TZ1())
     >>> t.isoformat()
     '12:10:30+01:00'
     >>> t.dst()
     datetime.timedelta(0)
     >>> t.tzname()
     '+01:00'
     >>> t.strftime("%H:%M:%S %Z")
     '12:10:30 +01:00'
     >>> 'The {} is {:%H:%M}.'.format("time", t)
     'The time is 12:10.'


File: python.info,  Node: tzinfo 对象,  Next: timezone 对象,  Prev: time 对象,  Up: datetime --- 基本的日期和时间类型

5.8.1.14 ‘tzinfo’ 对象
......................

 -- 类: datetime.tzinfo

     这是一个抽象基类，也就是说该类不应被直接实例化。 请定义 *note
     tzinfo: 388. 的子类来捕获有关特定时区的信息。

     *note tzinfo: 388. 的（某个实体子类）的实例可以被传给 *note
     datetime: 195. 和 *note time: 4fb. 对象的构造器。 这些对象会将它们
     的属性视为对应于本地时间，并且 *note tzinfo: 388. 对象支持展示本地
     时间与 UTC 的差值、时区名称以及 DST 差值的方法，都是与传给它们的日
     期或时间对象的相对值。

     你需要派生一个实体子类，并且（至少）提供你使用 *note datetime: 195.
     方法所需要的标准 *note tzinfo: 388. 方法的实现。 *note datetime:
     31. 模块提供了 *note timezone: a09.，这是 *note tzinfo: 388. 的一个
     简单实体子类，它能以与 UTC 的固定差值来表示不同的时区，例如 UTC 本
     身或北美的 EST 和 EDT。

     对于封存操作的特殊要求：一个 *note tzinfo: 388. 子类必须具有可不带
     参数调用的 *note __init__(): d66. 方法，否则它虽然可以被封存，但可
     能无法再次解封。 这是个技术性要求，在未来可能会被取消。

     一个 *note tzinfo: 388. 的实体子类可能需要实现以下方法。 具体需要实
     现的方法取决于感知型 *note datetime: 31. 对象如何使用它。 如果有疑
     问，可以简单地全都实现。

 -- 方法: tzinfo.utcoffset (dt)

     将本地时间与 UTC 时差返回为一个 *note timedelta: 196. 对象，如果本
     地时区在 UTC 以东则为正值。 如果本地时区在 UTC 以西则为负值。

     这表示与 UTC 的 `总计' 时差；举例来说，如果一个 *note tzinfo: 388.
     对象同时代表时区和 DST 调整，则 *note utcoffset(): 18f7. 应当返回两
     者的和。 如果 UTC 时差不确定则返回 ‘None’。 在其他情况下返回值必须
     为一个 *note timedelta: 196. 对象，其取值严格限制于
     ‘-timedelta(hours=24)’ 和 ‘timedelta(hours=24)’ 之间（差值的幅度必
     须小于一天）。 大多数 *note utcoffset(): 18f7. 的实现看起来可能像是
     以下两者之一:

          return CONSTANT                 # fixed-offset class
          return CONSTANT + self.dst(dt)  # daylight-aware class

     如果 *note utcoffset(): 18f7. 返回值不为 ‘None’，则 *note dst():
     18f8. 也不应返回 ‘None’。

     默认的 *note utcoffset(): 18f7. 实现会引发 *note
     NotImplementedError: 617.。

     在 3.7 版更改: UTC 时差不再限制为一个整数分钟值。

 -- 方法: tzinfo.dst (dt)

     将夏令时（DST）调整返回为一个 *note timedelta: 196. 对象，如果 DST
     信息未知则返回 ‘None’。

     如果 DST 未启用则返回 ‘timedelta(0)’。 如果 DST 已启用则将差值作为
     一个 *note timedelta: 196. 对象返回（参见 *note utcoffset(): 18f7.
     了解详情）。 请注意 DST 差值如果可用，就会直接被加入 *note
     utcoffset(): 18f7. 所返回的 UTC 时差，因此无需额外查询 *note dst():
     18f8. 除非你希望单独获取 DST 信息。 例如，*note
     datetime.timetuple(): 18dd. 会调用其 *note tzinfo: 18ad. 属性的
     *note dst(): 18f8. 方法来确定应该如何设置 ‘tm_isdst’ 旗标，而 *note
     tzinfo.fromutc(): 18db. 会调用 *note dst(): 18f8. 来在跨越时区时处
     理 DST 的改变。

     一个可以同时处理标准时和夏令时的 *note tzinfo: 388. 子类的实例 `tz'
     必须在此情形中保持一致：

     ‘tz.utcoffset(dt) - tz.dst(dt)’

     必须为具有同样的 *note tzinfo: 388. 子类实例且 ‘dt.tzinfo == tz’ 的
     每个 *note datetime: 195. 对象 `dt' 返回同样的结果，此表达式会产生
     时区的“标准时差”，它不应取决于具体日期或时间，只取决于地理位置。
     *note datetime.astimezone(): 197. 的实现依赖此方法，但无法检测违反
     规则的情况；确保符合规则是程序员的责任。 如果一个 *note tzinfo:
     388. 子类不能保证这一点，也许可以重载 *note tzinfo.fromutc(): 18db.
     的默认实现以便在任何情况下与 ‘astimezone()’ 正确配合。

     大多数 *note dst(): 18f8. 的实现可能会如以下两者之一:

          def dst(self, dt):
              # a fixed-offset class:  doesn't account for DST
              return timedelta(0)

     或者：

          def dst(self, dt):
              # Code to set dston and dstoff to the time zone's DST
              # transition times based on the input dt.year, and expressed
              # in standard local time.

              if dston <= dt.replace(tzinfo=None) < dstoff:
                  return timedelta(hours=1)
              else:
                  return timedelta(0)

     默认的 *note dst(): 18f8. 实现会引发 *note NotImplementedError:
     617.。

     在 3.7 版更改: DST 差值不再限制为一个整数分钟值。

 -- 方法: tzinfo.tzname (dt)

     将对应于 *note datetime: 195. 对象 `dt' 的时区名称作为字符串返回。
     *note datetime: 31. 模块没有定义任何字符串名称相关内容，也不要求名
     称有任何特定含义。 例如 "GMT", "UTC", "-500", "-5:00", "EDT",
     "US/Eastern", "America/New York" 都是有效的返回值。 如果字符串名称
     未知则返回 ‘None’。 请注意这是一个方法而不是一个固定的字符串，这主
     要是因为某些 *note tzinfo: 388. 子类可能需要根据所传入的特定 `dt' 值
     返回不同的名称，特别是当 *note tzinfo: 388. 类要负责处理夏令时的时
     候。

     默认的 *note tzname(): 18f9. 实现会引发 *note NotImplementedError:
     617.。

这些方法会被 *note datetime: 195. 或 *note time: 4fb. 对象调用，用来与它
们的同名方法相对应。 *note datetime: 195. 对象会将自身作为传入参数，而
*note time: 4fb. 对象会将 ‘None’ 作为传入参数。 这样 *note tzinfo: 388.
子类的方法应当准备好接受 `dt' 参数值为 ‘None’ 或是 *note datetime: 195.
类的实例。

当传入 ‘None’ 时，应当由类的设计者来决定最佳回应方式。 例如，返回 ‘None’
适用于希望该类提示时间对象不参与 *note tzinfo: 388. 协议处理。 让
‘utcoffset(None)’ 返回标准 UTC 时差也许会更有用处，因为并没有其他可用于
发现标准时差的约定惯例。

当传入一个 *note datetime: 195. 对象来回应 *note datetime: 195. 方法时，
‘dt.tzinfo’ 与 `self' 是同一对象。 *note tzinfo: 388. 方法可以依赖这一点
，除非用户代码直接调用了 *note tzinfo: 388. 方法。 此行为的目的是使得
*note tzinfo: 388. 方法将 `dt' 解读为本地时间，而不需要担心其他时区的相
关对象。

还有一个额外的 *note tzinfo: 388. 方法，某个子类可能会希望重载它：

 -- 方法: tzinfo.fromutc (dt)

     此方法会由默认的 *note datetime.astimezone(): 197. 实现来调用。 当
     被其调用时，‘dt.tzinfo’ 为 `self'，并且 `dt' 的日期和时间数据会被视
     为表示 UTC 时间，*note fromutc(): 18db. 的目标是调整日期和时间数据
     ，返回一个等价的 datetime 来表示 `self' 的本地时间。

     大多数 *note tzinfo: 388. 子类应该能够毫无问题地继承默认的 *note
     fromutc(): 18db. 实现。 它的健壮性足以处理固定差值的时区以及同时负
     责标准时和夏令时的时区，对于后者甚至还能处理 DST 转换时间在各个年份
     有变化的情况。 一个默认 *note fromutc(): 18db. 实现可能无法在所有情
     况下正确处理的例子是（与 UTC 的）标准时差取决于所经过的特定日期和时
     间，这种情况可能由于政治原因而出现。 默认的 ‘astimezone()’ 和 *note
     fromutc(): 18db. 实现可能无法生成你希望的结果，如果这个结果恰好是跨
     越了标准时差发生改变的时刻当中的某个小时值的话。

     忽略针对错误情况的代码，默认 *note fromutc(): 18db. 实现的行为方式
     如下:

          def fromutc(self, dt):
              # raise ValueError error if dt.tzinfo is not self
              dtoff = dt.utcoffset()
              dtdst = dt.dst()
              # raise ValueError if dtoff is None or dtdst is None
              delta = dtoff - dtdst  # this is self's standard offset
              if delta:
                  dt += delta   # convert to standard local time
                  dtdst = dt.dst()
                  # raise ValueError if dtdst is None
              if dtdst:
                  return dt + dtdst
              else:
                  return dt

在以下 ‘tzinfo_examples.py’ 文件中有一些 *note tzinfo: 388. 类的例子：

     from datetime import tzinfo, timedelta, datetime

     ZERO = timedelta(0)
     HOUR = timedelta(hours=1)
     SECOND = timedelta(seconds=1)

     # A class capturing the platform's idea of local time.
     # (May result in wrong values on historical times in
     #  timezones where UTC offset and/or the DST rules had
     #  changed in the past.)
     import time as _time

     STDOFFSET = timedelta(seconds = -_time.timezone)
     if _time.daylight:
         DSTOFFSET = timedelta(seconds = -_time.altzone)
     else:
         DSTOFFSET = STDOFFSET

     DSTDIFF = DSTOFFSET - STDOFFSET

     class LocalTimezone(tzinfo):

         def fromutc(self, dt):
             assert dt.tzinfo is self
             stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND
             args = _time.localtime(stamp)[:6]
             dst_diff = DSTDIFF // SECOND
             # Detect fold
             fold = (args == _time.localtime(stamp - dst_diff))
             return datetime(*args, microsecond=dt.microsecond,
                             tzinfo=self, fold=fold)

         def utcoffset(self, dt):
             if self._isdst(dt):
                 return DSTOFFSET
             else:
                 return STDOFFSET

         def dst(self, dt):
             if self._isdst(dt):
                 return DSTDIFF
             else:
                 return ZERO

         def tzname(self, dt):
             return _time.tzname[self._isdst(dt)]

         def _isdst(self, dt):
             tt = (dt.year, dt.month, dt.day,
                   dt.hour, dt.minute, dt.second,
                   dt.weekday(), 0, 0)
             stamp = _time.mktime(tt)
             tt = _time.localtime(stamp)
             return tt.tm_isdst > 0

     Local = LocalTimezone()


     # A complete implementation of current DST rules for major US time zones.

     def first_sunday_on_or_after(dt):
         days_to_go = 6 - dt.weekday()
         if days_to_go:
             dt += timedelta(days_to_go)
         return dt


     # US DST Rules
     #
     # This is a simplified (i.e., wrong for a few cases) set of rules for US
     # DST start and end times. For a complete and up-to-date set of DST rules
     # and timezone definitions, visit the Olson Database (or try pytz):
     # http://www.twinsun.com/tz/tz-link.htm
     # http://sourceforge.net/projects/pytz/ (might not be up-to-date)
     #
     # In the US, since 2007, DST starts at 2am (standard time) on the second
     # Sunday in March, which is the first Sunday on or after Mar 8.
     DSTSTART_2007 = datetime(1, 3, 8, 2)
     # and ends at 2am (DST time) on the first Sunday of Nov.
     DSTEND_2007 = datetime(1, 11, 1, 2)
     # From 1987 to 2006, DST used to start at 2am (standard time) on the first
     # Sunday in April and to end at 2am (DST time) on the last
     # Sunday of October, which is the first Sunday on or after Oct 25.
     DSTSTART_1987_2006 = datetime(1, 4, 1, 2)
     DSTEND_1987_2006 = datetime(1, 10, 25, 2)
     # From 1967 to 1986, DST used to start at 2am (standard time) on the last
     # Sunday in April (the one on or after April 24) and to end at 2am (DST time)
     # on the last Sunday of October, which is the first Sunday
     # on or after Oct 25.
     DSTSTART_1967_1986 = datetime(1, 4, 24, 2)
     DSTEND_1967_1986 = DSTEND_1987_2006

     def us_dst_range(year):
         # Find start and end times for US DST. For years before 1967, return
         # start = end for no DST.
         if 2006 < year:
             dststart, dstend = DSTSTART_2007, DSTEND_2007
         elif 1986 < year < 2007:
             dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006
         elif 1966 < year < 1987:
             dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986
         else:
             return (datetime(year, 1, 1), ) * 2

         start = first_sunday_on_or_after(dststart.replace(year=year))
         end = first_sunday_on_or_after(dstend.replace(year=year))
         return start, end


     class USTimeZone(tzinfo):

         def __init__(self, hours, reprname, stdname, dstname):
             self.stdoffset = timedelta(hours=hours)
             self.reprname = reprname
             self.stdname = stdname
             self.dstname = dstname

         def __repr__(self):
             return self.reprname

         def tzname(self, dt):
             if self.dst(dt):
                 return self.dstname
             else:
                 return self.stdname

         def utcoffset(self, dt):
             return self.stdoffset + self.dst(dt)

         def dst(self, dt):
             if dt is None or dt.tzinfo is None:
                 # An exception may be sensible here, in one or both cases.
                 # It depends on how you want to treat them.  The default
                 # fromutc() implementation (called by the default astimezone()
                 # implementation) passes a datetime with dt.tzinfo is self.
                 return ZERO
             assert dt.tzinfo is self
             start, end = us_dst_range(dt.year)
             # Can't compare naive to aware objects, so strip the timezone from
             # dt first.
             dt = dt.replace(tzinfo=None)
             if start + HOUR <= dt < end - HOUR:
                 # DST is in effect.
                 return HOUR
             if end - HOUR <= dt < end:
                 # Fold (an ambiguous hour): use dt.fold to disambiguate.
                 return ZERO if dt.fold else HOUR
             if start <= dt < start + HOUR:
                 # Gap (a non-existent hour): reverse the fold rule.
                 return HOUR if dt.fold else ZERO
             # DST is off.
             return ZERO

         def fromutc(self, dt):
             assert dt.tzinfo is self
             start, end = us_dst_range(dt.year)
             start = start.replace(tzinfo=self)
             end = end.replace(tzinfo=self)
             std_time = dt + self.stdoffset
             dst_time = std_time + HOUR
             if end <= dst_time < end + HOUR:
                 # Repeated hour
                 return std_time.replace(fold=1)
             if std_time < start or dst_time >= end:
                 # Standard time
                 return std_time
             if start <= std_time < end - HOUR:
                 # Daylight saving time
                 return dst_time


     Eastern  = USTimeZone(-5, "Eastern",  "EST", "EDT")
     Central  = USTimeZone(-6, "Central",  "CST", "CDT")
     Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
     Pacific  = USTimeZone(-8, "Pacific",  "PST", "PDT")

请注意同时负责标准时和夏令时的 *note tzinfo: 388. 子类在每年两次的 DST 转
换点上会出现不可避免的微妙问题。具体而言，考虑美国东部时区 (UTC -0500)，
它的 EDT 从三月的第二个星期天 1:59 (EST) 之后一分钟开始，并在十一月的第
一天星期天 1:59 (EDT) 之后一分钟结束:

       UTC   3:MM  4:MM  5:MM  6:MM  7:MM  8:MM
       EST  22:MM 23:MM  0:MM  1:MM  2:MM  3:MM
       EDT  23:MM  0:MM  1:MM  2:MM  3:MM  4:MM

     start  22:MM 23:MM  0:MM  1:MM  3:MM  4:MM

       end  23:MM  0:MM  1:MM  1:MM  2:MM  3:MM

当 DST 开始时（即 "start" 行），本地时钟从 1:59 跳到 3:00。 形式为 2:MM
的时间值在那一天是没有意义的，因此在 DST 开始那一天
‘astimezone(Eastern)’ 不会输出包含 ‘hour == 2’ 的结果。 例如，在 2016 年
春季时钟向前调整时，我们得到:

     >>> from datetime import datetime, timezone
     >>> from tzinfo_examples import HOUR, Eastern
     >>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
     >>> for i in range(4):
     ...     u = u0 + i*HOUR
     ...     t = u.astimezone(Eastern)
     ...     print(u.time(), 'UTC =', t.time(), t.tzname())
     ...
     05:00:00 UTC = 00:00:00 EST
     06:00:00 UTC = 01:00:00 EST
     07:00:00 UTC = 03:00:00 EDT
     08:00:00 UTC = 04:00:00 EDT

当 DST 结束时（见 "end" 行），会有更糟糕的潜在问题：本地时间值中有一个小
时是不可能没有歧义的：夏令时的最后一小时。 即以北美东部时间表示当天夏令
时结束时的形式为 5:MM UTC 的时间。 本地时钟从 1:59 (夏令时) 再次跳回到
1:00 (标准时)。 形式为 1:MM 的本地时间就是有歧义的。 此时 ‘astimezone()’
是通过将两个相邻的 UTC 小时映射到两个相同的本地小时来模仿本地时钟的行为
。 在这个北美东部时间的示例中，形式为 5:MM 和 6:MM 的 UTC 时间在转换为北
美东部时间时都将被映射到 1:MM，但前一个时间会将 *note fold: 4fc. 属性设
为 0 而后一个时间会将其设为 1。 例如，在 2016 年秋季时钟往回调整时，我们
得到:

     >>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
     >>> for i in range(4):
     ...     u = u0 + i*HOUR
     ...     t = u.astimezone(Eastern)
     ...     print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
     ...
     04:00:00 UTC = 00:00:00 EDT 0
     05:00:00 UTC = 01:00:00 EDT 0
     06:00:00 UTC = 01:00:00 EST 1
     07:00:00 UTC = 02:00:00 EST 0

请注意不同的 *note datetime: 195. 实例仅通过 *note fold: 4fc. 属性值来加
以区分，它们在比较时会被视为相等。

不允许时间显示存在歧义的应用需要显式地检查 *note fold: 4fc. 属性的值，或
者避免使用混合式的 *note tzinfo: 388. 子类；当使用 *note timezone: a09.
或者任何其他固定差值的 *note tzinfo: 388. 子类例如仅表示 EST（固定差值
-5 小时）或仅表示 EDT（固定差值 -4 小时）的类时是不会有歧义的。

参见
....

dateutil.tz(1)

     *note datetime: 31. 模块有一个基本 *note timezone: a09. 类（用来处
     理任意与 UTC 的固定时差）及其 *note timezone.utc: 18fa. 属性（一个
     UTC 时区实例）。

     `dateutil.tz' 库将 `IANA 时区数据库' (又名 Olson 数据库) 引入
     Python 并推荐使用。

IANA 时区数据库(2)

     该时区数据库 (通常称为 tz, tzdata 或 zoneinfo) 包含大量代码和数据用
     来表示全球许多有代表性的地点的本地时间的历史信息。 它会定期进行更新
     以反映各政治实体对时区边界、UTC 差值和夏令时规则的更改。

   ---------- Footnotes ----------

   (1) https://dateutil.readthedocs.io/en/stable/tz.html

   (2) https://www.iana.org/time-zones


File: python.info,  Node: timezone 对象,  Next: strftime 和 strptime 的行为,  Prev: tzinfo 对象,  Up: datetime --- 基本的日期和时间类型

5.8.1.15 ‘timezone’ 对象
........................

*note timezone: a09. 类是 *note tzinfo: 388. 的子类，它的每个实例都代表
一个以与 UTC 的固定时差来定义的时区。

此类的对象不可被用于代表某些特殊地点的时区信息，这些地点在一年的不同日期
会使用不同的时差，或是在历史上对民用时间进行过调整。

 -- 类: datetime.timezone (offset, name=None)

     `offset' 参数必须指定为一个 *note timedelta: 196. 对象，表示本地时
     间与 UTC 的时差。 它必须严格限制于 ‘-timedelta(hours=24)’ 和
     ‘timedelta(hours=24)’ 之间，否则会引发 *note ValueError: 1fc.。

     `name' 参数是可选的。 如果指定则必须为一个字符串，它将被用作 *note
     datetime.tzname(): 18dc. 方法的返回值。

     3.2 新版功能.

     在 3.7 版更改: UTC 时差不再限制为一个整数分钟值。

 -- 方法: timezone.utcoffset (dt)

     返回当 *note timezone: a09. 实例被构造时指定的固定值。

     `dt' 参数会被忽略。 返回值是一个 *note timedelta: 196. 实例，其值等
     于本地时间与 UTC 之间的时差。

     在 3.7 版更改: UTC 时差不再限制为一个整数分钟值。

 -- 方法: timezone.tzname (dt)

     返回当 *note timezone: a09. 实例被构造时指定的固定值。

     如果没有在构造器中提供 `name'，则 ‘tzname(dt)’ 所返回的名称将根据
     ‘offset’ 值按以下规则生成。 如果 `offset' 为 ‘timedelta(0)’，则名称
     为“UTC”，否则为字符串 ‘UTC±HH:MM’，其中 ± 为 ‘offset’ 的正负符号，
     HH 和 MM 分别为表示 ‘offset.hours’ 和 ‘offset.minutes’ 的两个数码。

     在 3.6 版更改: 由 ‘offset=timedelta(0)’ 生成的名称现在为简单的
     ‘’UTC’’ 而不再是 ‘'UTC+00:00'’。

 -- 方法: timezone.dst (dt)

     总是返回 ‘None’。

 -- 方法: timezone.fromutc (dt)

     返回 ‘dt + offset’。 `dt' 参数必须为一个感知型 *note datetime: 195.
     实例，其中 ‘tzinfo’ 值设为 ‘self’。

类属性：

 -- 属性: timezone.utc

     UTC 时区，‘timezone(timedelta(0))’。


File: python.info,  Node: strftime 和 strptime 的行为,  Prev: timezone 对象,  Up: datetime --- 基本的日期和时间类型

5.8.1.16 ‘strftime()’ 和 ‘strptime()’ 的行为
............................................

*note date: 194, *note datetime: 195. 和 *note time: 4fb. 对象都支持
‘strftime(format)’ 方法，可用来创建由一个显式格式字符串所控制的表示时间
的字符串。

相反地，*note datetime.strptime(): fbf. 类会根据表示日期和时间的字符串和
相应的格式字符串来创建一个 *note datetime: 195. 对象。

下表提供了 ‘strftime()’ 与 ‘strptime()’ 的高层级比较：

                     ‘strftime’                                                   ‘strptime’
                                                                                  
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
                                                                                  
用法                 根据给定的格式将对象转换为字符串                             将字符串解析为给定相应格式的 *note datetime: 195. 对象
                                                                                  
                                                                                  
方法类型             实例方法                                                     类方法
                                                                                  
                                                                                  
方法                 *note date: 194.; *note datetime: 195.; *note time: 4fb.     *note datetime: 195.
                                                                                  
                                                                                  
签名                 ‘strftime(format)’                                           ‘strptime(date_string, format)’
                                                                                  

* Menu:

* strftime() 和 strptime() Format Codes: strftime 和 strptime Format Codes.
* 技术细节::


File: python.info,  Node: strftime 和 strptime Format Codes,  Next: 技术细节,  Up: strftime 和 strptime 的行为

5.8.1.17 ‘strftime()’ 和 ‘strptime()’ Format Codes
..................................................

以下列表显示了 1989 版 C 标准所要求的全部格式代码，它们在带有标准 C 实现
的所有平台上均可用。

指令            含义                                 示例                         注释
                                                                                  
----------------------------------------------------------------------------------------------
                                                                                  
‘%a’            当地工作日的缩写。                        Sun, Mon, ..., Sat (en_US); (1)
                                                          So, Mo, ..., Sa (de_DE) 
                                                     
                                                                                  
‘%A’            本地化的星期中每日的完整名称。            Sunday, Monday, ..., Saturday (en_US); (1)
                                                          Sonntag, Montag, ..., Samstag (de_DE) 
                                                     
                                                                                  
‘%w’            以十进制数显示的工作日，其中0表示    0, 1, ..., 6
                星期日，6表示星期六。                
                
                                                                                  
‘%d’            补零后，以十进制数显示的月份中的一   01, 02, ..., 31              (9)
                天。                                                              
                
                                                                                  
‘%b’            当地月份的缩写。                          Jan, Feb, ..., Dec (en_US); (1)
                                                          Jan, Feb, ..., Dez (de_DE) 
                                                     
                                                                                  
‘%B’            本地化的月份全名。                        January, February, ..., December (en_US); (1)
                                                          Januar, Februar, ..., Dezember (de_DE) 
                                                     
                                                                                  
‘%m’            补零后，以十进制数显示的月份。       01, 02, ..., 12              (9)
                                                                                  
                                                                                  
‘%y’            补零后，以十进制数表示的，不带世纪   00, 01, ..., 99              (9)
                的年份。                                                          
                
                                                                                  
‘%Y’            十进制数表示的带世纪的年份。         0001, 0002, ..., 2013,       (2)
                                                     2014, ..., 9998, 9999        
                                                     
                                                                                  
‘%H’            以补零后的十进制数表示的小时（24 小  00, 01, ..., 23              (9)
                时制）。                                                          
                
                                                                                  
‘%I’            以补零后的十进制数表示的小时（12 小  01, 02, ..., 12              (9)
                时制）。                                                          
                
                                                                                  
‘%p’            本地化的 AM 或 PM 。                      AM, PM (en_US);         (1), (3)
                                                          am, pm (de_DE)          
                                                     
                                                                                  
‘%M’            补零后，以十进制数显示的分钟。       00, 01, ..., 59              (9)
                                                                                  
                                                                                  
‘%S’            补零后，以十进制数显示的秒。         00, 01, ..., 59              (4), (9)
                                                                                  
                                                                                  
‘%f’            以十进制数表示的微秒，在左侧补零。   000000, 000001, ...,         (5)
                                                     999999                       
                                                     
                                                                                  
‘%z’            UTC 偏移量，格式为                   (空), +0000, -0400, +1030,   (6)
                ‘±HHMM[SS[.ffffff]]’ （如果是简单    +063415, -030712.345216      
                型对象则为空字符串）。               
                
                                                                                  
‘%Z’            时区名称（如果对象为简单型则为空字   (空), UTC, EST, CST
                符串）。                             
                
                                                                                  
‘%j’            以补零后的十进制数表示的一年中的日   001, 002, ..., 366           (9)
                序号。                                                            
                
                                                                                  
‘%U’            以补零后的十进制数表示的一年中的周   00, 01, ..., 53              (7), (9)
                序号（星期日作为每周的第一天）。 在                               
                新的一年中第一个星期日之前的所有日
                子都被视为是在第 0 周。
                
                                                                                  
‘%W’            以十进制数表示的一年中的周序号（星   00, 01, ..., 53              (7), (9)
                期一作为每周的第一天）。 在新的一                                 
                年中第一个第期一之前的所有日子都被
                视为是在第 0 周。
                
                                                                                  
‘%c’            本地化的适当日期和时间表示。              Tue Aug 16 21:30:00 1988 (en_US); (1)
                                                          Di 16 Aug 21:30:00 1988 (de_DE) 
                                                     
                                                                                  
‘%x’            本地化的适当日期表示。                    08/16/88 (None);        (1)
                                                          08/16/1988 (en_US);     
                                                          16.08.1988 (de_DE) 
                                                     
                                                                                  
‘%X’            本地化的适当时间表示。                    21:30:00 (en_US);       (1)
                                                          21:30:00 (de_DE)        
                                                     
                                                                                  
‘%%’            字面的 ‘'%'’ 字符。                  %
                                                     

为了方便起见，还包括了C89标准不需要的其他一些指令。这些参数都对应于ISO
8601日期值。

指令            含义                                 示例                         注释
                                                                                  
----------------------------------------------------------------------------------------------
                                                                                  
‘%G’            带有世纪的 ISO 8601 年份，表示包含   0001, 0002, ..., 2013,       (8)
                大部分 ISO 星期 (‘%V’) 的年份。      2014, ..., 9998, 9999        
                                                     
                                                                                  
‘%u’            以十进制数显示的 ISO 8601 星期中的   1, 2, ..., 7
                日序号，其中 1 表示星期一。          
                
                                                                                  
‘%V’            以十进制数显示的 ISO 8601 星期，以   01, 02, ..., 53              (8), (9)
                星期一作为每周的第一天。 第 01 周                                 
                为包含 1 月 4 日的星期。
                

这些代码可能不是在所有平台上都可与 ‘strftime()’ 方法配合使用。 ISO 8601
年份和 ISO 8601 星期指令并不能与上面的年份和星期序号指令相互替代。 调用
‘strptime()’ 时传入不完整或有歧义的 ISO 8601 指令将引发 *note
ValueError: 1fc.。

对完整格式代码集的支持在不同平台上有所差异，因为 Python 要调用所在平台的
C 库的 ‘strftime()’ 函数，而不同平台的差异是很常见的。 要查看你所用平台
所支持的完整格式代码集，请参阅 ‘strftime(3)’ 文档。

3.6 新版功能: 增加了 ‘%G’, ‘%u’ 和 ‘%V’。


File: python.info,  Node: 技术细节,  Prev: strftime 和 strptime Format Codes,  Up: strftime 和 strptime 的行为

5.8.1.18 技术细节
.................

总体而言，‘d.strftime(fmt)’ 类似于 *note time: 10b. 模块的
‘time.strftime(fmt, d.timetuple())’，但是并非所有对象都支持
‘timetuple()’ 方法。

对于 *note datetime.strptime(): fbf. 类方法，默认值为
‘1900-01-01T00:00:00.000’: 任何未在格式字符串中指定的部分都将从默认值中
提取。 (1)

使用 ‘datetime.strptime(date_string, format)’ 等价于:

     datetime(*(time.strptime(date_string, format)[0:6]))

除非格式中包含秒以下的部分或时区差值信息，它们在 ‘datetime.strptime’ 中
受支持但会被 ‘time.strptime’ 所丢弃。

对于 *note time: 4fb. 对象，年、月、日的格式代码不应被使用，因为 *note
time: 10b. 对象没有这些值。 如果它们被使用，则年份将被替换为 ‘1900’，而
月和日将被替换为 ‘1’。

对于 *note date: 194. 对象，时、分、秒和微秒的格式代码不应被使用，因为
*note date: 194. 对象没有这些值。 如果它们被使用，则它们都将被替换为
‘0’。

出于相同的原因，对于包含当前区域设置字符集所无法表示的 Unicode 码位的格
式字符串的处理方式也取决于具体平台。 在某些平台上这样的码位会不加修改地
原样输出，而在其他平台上 ‘strftime’ 则可能引发 *note UnicodeError: c43.
或只返回一个空字符串。

注释:

  1. 由于此格式依赖于当前区域设置，因此对具体输出值应当保持谨慎预期。 字
     段顺序会发生改变（例如 "month/day/year" 与 "day/month/year"），并且
     输出可能包含使用区域设置所指定的默认编码格式的 Unicode 字符（例如如
     果当前区域为 ‘ja_JP’，则默认编码格式可能为 ‘eucJP’, ‘SJIS’ 或
     ‘utf-8’ 中的一个；使用 *note locale.getlocale(): 1904. 可确定当前区
     域设置的编码格式）。

  2. ‘strptime()’ 方法能够解析整个 [1, 9999] 范围内的年份，但 < 1000 的
     年份必须加零填充为 4 位数字宽度。

     在 3.2 版更改: 在之前的版本中，‘strftime()’ 方法只限于 >= 1900 的年
     份。

     在 3.3 版更改: 在版本3.2中，‘strftime()’ 方法只限于 years >= 1000。

  3. 当与 ‘strptime()’ 方法一起使用时，如果使用 ‘%I’ 指令来解析小时，
     ‘%p’ 指令只影响输出小时字段。

  4. 与 *note time: 10b. 模块不同的是， *note datetime: 31. 模块不支持闰
     秒。

  5. 当与 ‘strptime()’ 方法一起使用时，‘%f’ 指令可接受一至六个数码及左边
     的零填充。 ‘%f’ 是对 C 标准中格式字符集的扩展（但单独在 datetime 对
     象中实现，因此它总是可用）。

  6. 对于简单型对象，‘%z’ and ‘%Z’ 格式代码会被替换为空字符串。

     对于一个感知型对象而言：

     ‘%z’

          ‘utcoffset()’ 会被转换为 ‘±HHMM[SS[.ffffff]]’ 形式的字符串，其
          中 ‘HH’ 为给出 UTC 时差的小时部分的 2 位数码字符串，‘MM’ 为给
          出 UTC 时差的分钟部分的 2 位数码字符串，‘SS’ 为给出 UTC 时差的
          秒部分的 2 位数码字符串，而 ‘ffffff’ 为给出 UTC 时差的微秒部分
          的 6 位数码字符串。 当时差为整数秒时 ‘ffffff’ 部分将被省略，而
          当时差为整数分钟时 ‘ffffff’ 和 ‘SS’ 部分都将被省略。 例如，如
          果 ‘utcoffset()’ 返回 ‘timedelta(hours=-3, minutes=-30)’，则
          ‘%z’ 会被替换为字符串 ‘'-0330'’。

     在 3.7 版更改: UTC 时差不再限制为一个整数分钟值。

     在 3.7 版更改: 当提供 ‘%z’ 指令给 ‘strptime()’ 方法时，UTC 差值可以
     在时、分和秒之间使用冒号分隔符。 例如，‘'+01:00:00'’ 将被解读为一小
     时的差值。 此外，提供 ‘'Z'’ 就相当于 ‘'+00:00'’。

     ‘%Z’

          如果 ‘tzname()’ 返回 ‘None’，‘%Z’ 会被替换为一个空字符串。 在
          其他情况下 ‘%Z’ 会被替换为返回值，这必须为一个字符串。

     在 3.2 版更改: 当提供 ‘%z’ 指令给 ‘strptime()’ 方法时，将产生一个感
     知型 *note datetime: 195. 对象。 结果的 ‘tzinfo’ 将被设为一个 *note
     timezone: a09. 实例。

  7. 当与 ‘strptime()’ 方法一起使用时，‘%U’ 和 ‘%W’ 仅用于指定星期几和日
     历年份 (‘%Y’) 的计算。

  8. 类似于 ‘%U’ 和 ‘%W’，‘%V’ 仅用于在 ‘strptime()’ 格式字符串中指定星
     期几和 ISO 年份 (‘%G’) 的计算。 还要注意 ‘%G’ 和 ‘%Y’ 是不可交换的
     。

  9. 当于 ‘strptime()’ 方法一起使用时，前导的零在格式 ‘%d’, ‘%m’, ‘%H’,
     ‘%I’, ‘%M’, ‘%S’, ‘%J’, ‘%U’, ‘%W’ 和 ‘%V’ 中是可选的。 格式 ‘%y’ 不
     要求有前导的零。

备注
....

   ---------- Footnotes ----------

   (1) (4) 传入 ‘datetime.strptime('Feb 29', '%b %d')’ 将导致错误，因为
‘1900’ 不是闰年。


File: python.info,  Node: calendar --- 日历相关函数,  Next: collections --- 容器数据类型,  Prev: datetime --- 基本的日期和时间类型,  Up: 数据类型

5.8.2 ‘calendar’ — 日历相关函数
-------------------------------

`源代码：' Lib/calendar.py(1)

__________________________________________________________________

这个模块让你可以输出像 Unix ‘cal’ 那样的日历，它还提供了其它与日历相关的
实用函数。 默认情况下，这些日历把星期一当作一周的第一天，星期天为一周的
最后一天（按照欧洲惯例）。 可以使用 *note setfirstweekday(): 1907. 方法
设置一周的第一天为星期天 (6) 或者其它任意一天。 使用整数作为指定日期的参
数。 更多相关的函数，参见 *note datetime: 31. 和 *note time: 10b. 模块。

在这个模块中定义的函数和类都基于一个理想化的日历，现行公历向过去和未来两
个方向无限扩展。这与 Dershowitz 和 Reingold 的书 "历法计算" 中所有计算的
基本日历 – "proleptic Gregorian" 日历的定义相符合。 ISO 8601标准还规定了
0 和 负数年份。0年指公元前1年， -1年指公元前2年，依此类推。

 -- 类: calendar.Calendar (firstweekday=0)

     创建一个 *note Calendar: 1908. 对象。 `firstweekday' 是一个整数，用
     于指定一周的第一天。 ‘0’ 是星期一（默认值），‘6’ 是星期天。

     *note Calendar: 1908. 对象提供了一些可被用于准备日历数据格式化的方
     法。 这个类本身不执行任何格式化操作。 这部分任务应由子类来完成。

     *note Calendar: 1908. 类的实例有下列方法：

      -- 方法: iterweekdays ()

          返回一个迭代器，迭代器的内容为一星期的数字。迭代器的第一个值与
          *note firstweekday: 190a. 属性的值一至。

      -- 方法: itermonthdates (year, month)

          返回一个迭代器，迭代器的内容为 `year' 年 `month' 月(1-12)的日
          期。这个迭代器返回当月的所有日期 ( *note datetime.date: 194. 对
          象)，日期包含了本月头尾用于组成完整一周的日期。

      -- 方法: itermonthdays (year, month)

          返回一个迭代器，迭代器的内容与 *note itermonthdates(): 4ae. 类
          似，为 `year' 年 `month' 月的日期，但不受 *note datetime.date:
          194. 范围限制。返回的日期为当月每一天的日期对应的天数。对于不
          在当月的日期，显示为 ‘0’。

      -- 方法: itermonthdays2 (year, month)

          返回一个迭代器，迭代器的内容与 *note itermonthdates(): 4ae. 类
          似为 `year' 年 `month' 月的日期，但不受 *note datetime.date:
          194. 范围的限制。迭代器中的元素为一个由日期和代表星期几的数字
          组成的的元组。

      -- 方法: itermonthdays3 (year, month)

          返回一个迭代器，迭代器的内容与 *note itermonthdates(): 4ae. 类
          似为 `year' 年 `month' 月的日期，但不受 *note datetime.date:
          194. 范围的限制。迭代器的元素为一个由年，月，日组成的元组。

          3.7 新版功能.

      -- 方法: itermonthdays4 (year, month)

          返回一个迭代器，迭代器的内容与 *note itermonthdates(): 4ae. 类
          似为 `year' 年 `month' 月的日期，但不受 *note datetime.date:
          194. 范围的限制。迭代器的元素为一个由年，月，日和代表星期几的
          数字组成的元组。

          3.7 新版功能.

      -- 方法: monthdatescalendar (year, month)

          返回一个表示指定年月的周列表。周列表由七个 *note
          datetime.date: 194. 对象组成。

      -- 方法: monthdays2calendar (year, month)

          返回一个表示指定年月的周列表。周列表由七个代表日期的数字和代表
          周几的数字组成的二元元组。

      -- 方法: monthdayscalendar (year, month)

          返回一个表示指定年月的周列表。周列表由七个代表日期的数字组成。

      -- 方法: yeardatescalendar (year, width=3)

          返回可以用来格式化的指定年月的数据。返回的值是一个列表，列表是
          月份组成的行。每一行包含了最多 `width' 个月(默认为3)。每个月包
          含了4到6周，每周包含1–7天。每一天使用 *note datetime.date:
          194. 对象。

      -- 方法: yeardays2calendar (year, width=3)

          返回可以用来模式化的指定年月的数据(与 *note
          yeardatescalendar(): 1910. 类似)。周列表的元素是由表示日期的数
          字和表示星期几的数字组成的元组。不在这个月的日子为0。

      -- 方法: yeardayscalendar (year, width=3)

          返回可以用来模式化的指定年月的数据(与 *note
          yeardatescalendar(): 1910. 类似)。周列表的元素是表示日期的数字
          。不在这个月的日子为0。

 -- 类: calendar.TextCalendar (firstweekday=0)

     可以使用这个类生成纯文本日历。

     *note TextCalendar: 1913. 实例有以下方法：

      -- 方法: formatmonth (theyear, themonth, w=0, l=0)

          返回一个多行字符串来表示指定年月的日历。`w' 为日期的宽度，但始
          终保持日期居中。`l' 指定了每星期占用的行数。以上这些还依赖于构
          造器或者 *note setfirstweekday(): 1907. 方法指定的周的第一天是
          哪一天。

      -- 方法: prmonth (theyear, themonth, w=0, l=0)

          与 *note formatmonth(): 1914. 方法一样，返回一个月的日历。

      -- 方法: formatyear (theyear, w=2, l=1, c=6, m=3)

          返回一个多行字符串，这个字符串为一个 `m' 列日历。可选参数 `w',
          `l', 和 `c' 分别表示日期列数， 周的行数， 和月之间的间隔。同样
          ，以上这些还依赖于构造器或者 *note setfirstweekday(): 1907. 指
          定哪一天为一周的第一天。日历的第一年由平台依赖于使用的平台。

      -- 方法: pryear (theyear, w=2, l=1, c=6, m=3)

          与 *note formatyear(): 1916. 方法一样，返回一整年的日历。

 -- 类: calendar.HTMLCalendar (firstweekday=0)

     可以使用这个类生成 HTML 日历。

     ‘HTMLCalendar’ 实例有以下方法：

      -- 方法: formatmonth (theyear, themonth, withyear=True)

          返回一个 HTML 表格作为指定年月的日历。 `withyear' 为真，则年份
          将会包含在表头，否则只显示月份。

      -- 方法: formatyear (theyear, width=3)

          返回一个 HTML 表格作为指定年份的日历。 `width' (默认为3) 用于
          规定每一行显示月份的数量。

      -- 方法: formatyearpage (theyear, width=3, css='calendar.css',
               encoding=None)

          返回一个完整的 HTML 页面作为指定年份的日历。 `width*(默认为3)
          用于规定每一行显示的月份数量。 *css' 为层叠样式表的名字。如果
          不使用任何层叠样式表，可以使用 *note None: 158. 。 `encoding'
          为输出页面的编码 (默认为系统的默认编码)。

     ‘HTMLCalendar’ 有以下属性，你可以重载它们来自定义应用日历的样式。

      -- 属性: cssclasses

          一个对应星期一到星期天的 CSS class 列表。默认列表为

               cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]

          可以向每天加入其它样式

               cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"]

          需要注意的是，列表的长度必须为7。

      -- 属性: cssclass_noday

          工作日的 CSS 类在上个月或下个月发生。

          3.7 新版功能.

      -- 属性: cssclasses_weekday_head

          用于标题行中的工作日名称的 CSS 类 列表。默认值与 *note
          cssclasses: 191b. 相同。

          3.7 新版功能.

      -- 属性: cssclass_month_head

          月份的头 CSS 类（由 ‘formatmonthname()’ 使用）。默认值为
          ‘"month"’ 。

          3.7 新版功能.

      -- 属性: cssclass_month

          某个月的月历的 CSS 类（由 *note formatmonth(): 1918. 使用）。
          默认值为 ‘"month"’ 。

          3.7 新版功能.

      -- 属性: cssclass_year

          某年的年历的 CSS 类（由 *note formatyear(): 1919. 使用）。默认
          值为 ‘"year"’ 。

          3.7 新版功能.

      -- 属性: cssclass_year_head

          年历的·表头 CSS 类（由 *note formatyear(): 1919. 使用）。默认
          值为 ‘"year"’ 。

          3.7 新版功能.

     需要注意的是，尽管上面命名的样式类都是单独出现的(如：
     ‘cssclass_month’ ‘cssclass_noday’), 但我们可以使用空格将样式类列表
     中的多个元素分隔开，例如：

          "text-bold text-red"

     下面是一个如何自定义 ‘HTMLCalendar’ 的示例

          class CustomHTMLCal(calendar.HTMLCalendar):
              cssclasses = [style + " text-nowrap" for style in
                            calendar.HTMLCalendar.cssclasses]
              cssclass_month_head = "text-center month-head"
              cssclass_month = "text-center month"
              cssclass_year = "text-italic lead"

 -- 类: calendar.LocaleTextCalendar (firstweekday=0, locale=None)

     这个子类 *note TextCalendar: 1913. 可以在构造函数中传递一个语言环境
     名称，并且返回月份和星期几的名称在特定语言环境中。如果此语言环境包
     含编码，则包含月份和工作日名称的所有字符串将作为 unicode 返回。

 -- 类: calendar.LocaleHTMLCalendar (firstweekday=0, locale=None)

     This subclass of *note HTMLCalendar: 378. can be passed a locale
     name in the constructor and will return month and weekday names in
     the specified locale.  If this locale includes an encoding all
     strings containing month and weekday names will be returned as
     unicode.

     注解: 这两个类的 ‘formatweekday()’ 和 ‘formatmonthname()’ 方法临时
     更改dang当前区域至给定 `locale' 。由于当前的区域设置是进程范围的设
     置，因此它们不是线程安全的。

对于简单的文本日历，这个模块提供了以下方法。

 -- 函数: calendar.setfirstweekday (weekday)

     设置每一周的开始(‘0’ 表示星期一，‘6’ 表示星期天)。calendar还提供了
     ‘MONDAY’, ‘TUESDAY’, ‘WEDNESDAY’, ‘THURSDAY’, ‘FRIDAY’, ‘SATURDAY’
     和 ‘SUNDAY’ 几个常量方便使用。例如，设置每周的第一天为星期天

          import calendar
          calendar.setfirstweekday(calendar.SUNDAY)

 -- 函数: calendar.firstweekday ()

     返回当前设置的每星期的第一天的数值。

 -- 函数: calendar.isleap (year)

     如果 `year' 是闰年则返回 *note True: 4a1. ,否则返回 *note False:
     390.。

 -- 函数: calendar.leapdays (y1, y2)

     返回在范围 `y1' 至 `y2' （包含 y1 和 y2 ）之间的闰年的年数，其中
     `y1' 和 `y2' 是年份。

     此函数适用于跨越一个世纪变化的范围。

 -- 函数: calendar.weekday (year, month, day)

     返回某年（ ‘1970’ – ...），某月（ ‘1’ – ‘12’ ），某日（ ‘1’ – ‘31’
     ）是星期几（ ‘0’ 是星期一）。

 -- 函数: calendar.weekheader (n)

     返回一个包含星期几的缩写名的头。 `n' 指定星期几缩写的字符宽度。

 -- 函数: calendar.monthrange (year, month)

     返回指定 `年份' 的指定 `月份' 的第一天是星期几和这个月的天数。

 -- 函数: calendar.monthcalendar (year, month)

     返回表示一个月的日历的矩阵。 每一行代表一周；此月份外的日子由零表示
     。 每周从周一开始，除非使用 *note setfirstweekday(): 1907. 改变设置
     。

 -- 函数: calendar.prmonth (theyear, themonth, w=0, l=0)

     打印由 *note month(): 192b. 返回的一个月的日历。

 -- 函数: calendar.month (theyear, themonth, w=0, l=0)

     使用 *note TextCalendar: 1913. 类的 ‘formatmonth()’ 以多行字符串形
     式返回月份日历。

 -- 函数: calendar.prcal (year, w=0, l=0, c=6, m=3)

     打印由 *note calendar(): 15. 返回的整年的日历。

 -- 函数: calendar.calendar (year, w=2, l=1, c=6, m=3)

     使用 *note TextCalendar: 1913. 类的 ‘formatyear()’ 返回整年的3列的
     日历以多行字符串的形式。

 -- 函数: calendar.timegm (tuple)

     一个不相关但很好用的函数，它接受一个时间元组例如 *note time: 10b. 模
     块中的 *note gmtime(): b47. 函数的返回并返回相应的 Unix 时间戳值，
     假定 1970 年开始计数， POSIX 编码。实际上， *note time.gmtime():
     b47. 和 *note timegm(): 192e. 是彼此相反的。

*note calendar: 15. 模块导出以下数据属性：

 -- 数据: calendar.day_name

     在当前语言环境下表示星期几的数组。

 -- 数据: calendar.day_abbr

     在当前语言环境下表示星期几缩写的数组。

 -- 数据: calendar.month_name

     在当前语言环境下表示一年中月份的数组。这遵循一月的月号为 1 的通常惯
     例，所以它的长度为 13 且 ‘month_name[0]’ 是空字符串。

 -- 数据: calendar.month_abbr

     在当前语言环境下表示月份简写的数组。这遵循一月的月号为 1 的通常惯例
     ，所以它的长度为 13 且 ‘month_abbr[0]’ 是空字符串。

参见
....

模块 *note datetime: 31.

     为日期和时间提供与 *note time: 10b. 模块相似功能的面向对象接口。

模块 *note time: 10b.

     底层时间相关函数。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/calendar.py


File: python.info,  Node: collections --- 容器数据类型,  Next: collections abc --- 容器的抽象基类,  Prev: calendar --- 日历相关函数,  Up: 数据类型

5.8.3 ‘collections’ — 容器数据类型
----------------------------------

`Source code:' Lib/collections/__init__.py(1)

__________________________________________________________________

这个模块实现了特定目标的容器，以提供Python标准内建容器 *note dict: 1b9.
, *note list: 263. , *note set: b77. , 和 *note tuple: 486. 的替代选择。

*note namedtuple(): 1b7.  创建命名元组子类的工厂函数
                          
                          
*note deque: 539.         类似列表(list)的容器，实现了在两端快速添加(append)和弹出(pop)
                          
                          
*note ChainMap: 4b1.      类似字典(dict)的容器类，将多个映射集合到一个视图里面
                          
                          
*note Counter: 9e2.       字典的子类，提供了可哈希对象的计数功能
                          
                          
*note OrderedDict: 1ba.   字典的子类，保存了他们被添加的顺序
                          
                          
*note defaultdict: b42.   字典的子类，提供了一个工厂函数，为字典查询提供一个默认值
                          
                          
*note UserDict: 1935.     封装了字典对象，简化了字典子类化
                          
                          
*note UserList: 1936.     封装了列表对象，简化了列表子类化
                          
                          
*note UserString: 6b6.    封装了字符串对象，简化了字符串子类化
                          

Deprecated since version 3.3, will be removed in version 3.10: 已将
*note 容器抽象基类: 1937. 移至 *note collections.abc: 1f. 模块。 为了保
持向下兼容性，它们在 Python 3.9 版的这个模块中仍然存在。

* Menu:

* ChainMap 对象::
* Counter 对象::
* deque 对象::
* defaultdict 对象::
* namedtuple() 命名元组的工厂函数: namedtuple 命名元组的工厂函数.
* OrderedDict 对象::
* UserDict 对象::
* UserList 对象::
* UserString 对象::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/collections/__init__.py


File: python.info,  Node: ChainMap 对象,  Next: Counter 对象,  Up: collections --- 容器数据类型

5.8.3.1 ‘ChainMap’ 对象
.......................

3.3 新版功能.

一个 *note ChainMap: 4b1. 类是为了将多个映射快速的链接到一起，这样它们就
可以作为一个单元处理。它通常比创建一个新字典和多次调用 *note update():
dd1. 要快很多。

这个类可以用于模拟嵌套作用域，并且在模版化的时候比较有用。

 -- 类: collections.ChainMap (*maps)

     一个 *note ChainMap: 4b1. 将多个字典或者其他映射组合在一起，创建一
     个单独的可更新的视图。 如果没有 `maps' 被指定，就提供一个默认的空字
     典，这样一个新链至少有一个映射。

     底层映射被存储在一个列表中。这个列表是公开的，可以通过 `maps' 属性
     存取和更新。没有其他的状态。

     搜索查询底层映射，直到一个键被找到。不同的是，写，更新和删除只操作
     第一个映射。

     一个 *note ChainMap: 4b1. 通过引用合并底层映射。 所以，如果一个底层
     映射更新了，这些更改会反映到 *note ChainMap: 4b1. 。

     支持所有常用字典方法。另外还有一个 `maps' 属性(attribute)，一个创建
     子上下文的方法(method)， 一个存取它们首个映射的属性(property):

      -- 属性: maps

          一个可以更新的映射列表。这个列表是按照第一次搜索到最后一次搜索
          的顺序组织的。它是仅有的存储状态，可以被修改。列表最少包含一个
          映射。

      -- 方法: new_child (m=None)

          返回一个新的 *note ChainMap: 4b1. 类，包含了一个新映射(map)，
          后面跟随当前实例的全部映射(map)。如果 ‘m’ 被指定，它就成为不同
          新的实例，就是在所有映射前加上 m，如果没有指定，就加上一个空字
          典，这样的话一个 ‘d.new_child()’ 调用等价于 ‘ChainMap({},
          *d.maps)’ 。这个方法用于创建子上下文，不改变任何父映射的值。

          在 3.4 版更改: 添加了 ‘m’ 可选参数。

      -- 属性: parents

          属性返回一个新的 *note ChainMap: 4b1. 包含所有的当前实例的映射
          ，除了第一个。这样可以在搜索的时候跳过第一个映射。 使用的场景
          类似在 *note nested scopes: 15fb. 嵌套作用域中使用 *note
          nonlocal: c47. 关键词。用例也可以类比内建函数 *note super():
          4eb. 。一个 ‘d.parents’ 的引用等价于 ‘ChainMap(*d.maps[1:])’ 。

     注意，一个 *note ChainMap(): 4b1. 的迭代顺序是通过从后往前扫描所有
     映射来确定的:

          >>> baseline = {'music': 'bach', 'art': 'rembrandt'}
          >>> adjustments = {'art': 'van gogh', 'opera': 'carmen'}
          >>> list(ChainMap(adjustments, baseline))
          ['music', 'art', 'opera']

     这给出了与 *note dict.update(): dd1. 调用序列相同的顺序，从最后一个
     映射开始:

          >>> combined = baseline.copy()
          >>> combined.update(adjustments)
          >>> list(combined)
          ['music', 'art', 'opera']

参见
....

   * MultiContext class(1) 在 Enthought CodeTools package(2) 有支持写映
     射的选项。

   * Django 中用于模板的 Context class(3) 是只读的映射链。 它还具有上下
     文推送和弹出特性，类似于 *note new_child(): 832. 方法和 *note
     parents: 193a. 特征属性。

   * Nested Contexts recipe(4) 提供了是否对第一个映射或其他映射进行写和
     其他修改的选项。

   * 一个 极简的只读版 Chainmap(5).

* Menu:

* ChainMap 例子和方法::

   ---------- Footnotes ----------

   (1) 
https://github.com/enthought/codetools/blob/4.0.0/codetools/contexts/multi_context.py

   (2) https://github.com/enthought/codetools

   (3) 
https://github.com/django/django/blob/main/django/template/context.py

   (4) https://code.activestate.com/recipes/577434/

   (5) https://code.activestate.com/recipes/305268/


File: python.info,  Node: ChainMap 例子和方法,  Up: ChainMap 对象

5.8.3.2 ‘ChainMap’ 例子和方法
.............................

这一节提供了多个使用链映射的案例。

模拟Python内部lookup链的例子

     import builtins
     pylookup = ChainMap(locals(), globals(), vars(builtins))

让用户指定的命令行参数优先于环境变量，优先于默认值的例子

     import os, argparse

     defaults = {'color': 'red', 'user': 'guest'}

     parser = argparse.ArgumentParser()
     parser.add_argument('-u', '--user')
     parser.add_argument('-c', '--color')
     namespace = parser.parse_args()
     command_line_args = {k: v for k, v in vars(namespace).items() if v is not None}

     combined = ChainMap(command_line_args, os.environ, defaults)
     print(combined['color'])
     print(combined['user'])

用 *note ChainMap: 4b1. 类模拟嵌套上下文的例子

     c = ChainMap()        # Create root context
     d = c.new_child()     # Create nested child context
     e = c.new_child()     # Child of c, independent from d
     e.maps[0]             # Current context dictionary -- like Python's locals()
     e.maps[-1]            # Root context -- like Python's globals()
     e.parents             # Enclosing context chain -- like Python's nonlocals

     d['x'] = 1            # Set value in current context
     d['x']                # Get first key in the chain of contexts
     del d['x']            # Delete from current context
     list(d)               # All nested values
     k in d                # Check all nested values
     len(d)                # Number of nested values
     d.items()             # All nested items
     dict(d)               # Flatten into a regular dictionary

*note ChainMap: 4b1. 类只更新链中的第一个映射，但lookup会搜索整个链。 然
而，如果需要深度写和删除，也可以很容易的通过定义一个子类来实现它

     class DeepChainMap(ChainMap):
         'Variant of ChainMap that allows direct updates to inner scopes'

         def __setitem__(self, key, value):
             for mapping in self.maps:
                 if key in mapping:
                     mapping[key] = value
                     return
             self.maps[0][key] = value

         def __delitem__(self, key):
             for mapping in self.maps:
                 if key in mapping:
                     del mapping[key]
                     return
             raise KeyError(key)

     >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'})
     >>> d['lion'] = 'orange'         # update an existing key two levels down
     >>> d['snake'] = 'red'           # new keys get added to the topmost dict
     >>> del d['elephant']            # remove an existing key one level down
     >>> d                            # display result
     DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})


File: python.info,  Node: Counter 对象,  Next: deque 对象,  Prev: ChainMap 对象,  Up: collections --- 容器数据类型

5.8.3.3 ‘Counter’ 对象
......................

一个计数器工具提供快速和方便的计数。比如

     >>> # Tally occurrences of words in a list
     >>> cnt = Counter()
     >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
     ...     cnt[word] += 1
     >>> cnt
     Counter({'blue': 3, 'red': 2, 'green': 1})

     >>> # Find the ten most common words in Hamlet
     >>> import re
     >>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
     >>> Counter(words).most_common(10)
     [('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
      ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]

 -- 类: collections.Counter ([iterable-or-mapping])

     一个 *note Counter: 9e2. 是一个 *note dict: 1b9. 的子类，用于计数可
     哈希对象。它是一个集合，元素像字典键(key)一样存储，它们的计数存储为
     值。计数可以是任何整数值，包括0和负数。 *note Counter: 9e2. 类有点
     像其他语言中的 bags或multisets。

     元素从一个 `iterable' 被计数或从其他的 `mapping' (or counter)初始化
     ：

          >>> c = Counter()                           # a new, empty counter
          >>> c = Counter('gallahad')                 # a new counter from an iterable
          >>> c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
          >>> c = Counter(cats=4, dogs=8)             # a new counter from keyword args

     Counter对象有一个字典接口，如果引用的键没有任何记录，就返回一个0，
     而不是弹出一个 *note KeyError: 2c8. :

          >>> c = Counter(['eggs', 'ham'])
          >>> c['bacon']                              # count of a missing element is zero
          0

     设置一个计数为0不会从计数器中移去一个元素。使用 ‘del’ 来删除它:

          >>> c['sausage'] = 0                        # counter entry with a zero count
          >>> del c['sausage']                        # del actually removes the entry

     3.1 新版功能.

     在 3.7 版更改: 作为 *note dict: 1b9. 的子类，*note Counter: 9e2. 继
     承了记住插入顺序的功能。 `Counter' 对象进行数学运算时同样会保持顺序
     。 结果会先按每个元素在运算符左边的出现时间排序，然后再按其在运算符
     右边的出现时间排序。

     计数器对象除了字典方法以外，还提供了三个其他的方法：

      -- 方法: elements ()

          返回一个迭代器，其中每个元素将重复出现计数值所指定次。 元素会
          按首次出现的顺序返回。 如果一个元素的计数值小于一，*note
          elements(): ca2. 将会忽略它。

               >>> c = Counter(a=4, b=2, c=0, d=-2)
               >>> sorted(c.elements())
               ['a', 'a', 'a', 'a', 'b', 'b']

      -- 方法: most_common ([n])

          返回一个列表，其中包含 `n' 个最常见的元素及出现次数，按常见程
          度由高到低排序。 如果 `n' 被省略或为 ‘None’，*note
          most_common(): ca1. 将返回计数器中的 `所有' 元素。 计数值相等
          的元素按首次出现的顺序排序：

               >>> Counter('abracadabra').most_common(3)
               [('a', 5), ('b', 2), ('r', 2)]

      -- 方法: subtract ([iterable-or-mapping])

          从 `迭代对象' 或 `映射对象' 减去元素。像 *note dict.update():
          dd1. 但是是减去，而不是替换。输入和输出都可以是0或者负数。

               >>> c = Counter(a=4, b=2, c=0, d=-2)
               >>> d = Counter(a=1, b=2, c=3, d=4)
               >>> c.subtract(d)
               >>> c
               Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

          3.2 新版功能.

     通常字典方法都可用于 *note Counter: 9e2. 对象，除了有两个方法工作方
     式与字典并不相同。

      -- 方法: fromkeys (iterable)

          这个类方法没有在 *note Counter: 9e2. 中实现。

      -- 方法: update ([iterable-or-mapping])

          从 `迭代对象' 计数元素或者 从另一个 `映射对象' (或计数器) 添加
          。 像 *note dict.update(): dd1. 但是是加上，而不是替换。另外，
          `迭代对象' 应该是序列元素，而不是一个 ‘(key, value)’ 对。

*note Counter: 9e2. 对象的常用案例

     sum(c.values())                 # total of all counts
     c.clear()                       # reset all counts
     list(c)                         # list unique elements
     set(c)                          # convert to a set
     dict(c)                         # convert to a regular dictionary
     c.items()                       # convert to a list of (elem, cnt) pairs
     Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
     c.most_common()[:-n-1:-1]       # n least common elements
     +c                              # remove zero and negative counts

提供了几个数学操作，可以结合 *note Counter: 9e2. 对象，以生产 multisets
(计数器中大于0的元素）。 加和减，结合计数器，通过加上或者减去元素的相应
计数。交集和并集返回相应计数的最小或最大值。每种操作都可以接受带符号的计
数，但是输出会忽略掉结果为零或者小于零的计数。

     >>> c = Counter(a=3, b=1)
     >>> d = Counter(a=1, b=2)
     >>> c + d                       # add two counters together:  c[x] + d[x]
     Counter({'a': 4, 'b': 3})
     >>> c - d                       # subtract (keeping only positive counts)
     Counter({'a': 2})
     >>> c & d                       # intersection:  min(c[x], d[x])
     Counter({'a': 1, 'b': 1})
     >>> c | d                       # union:  max(c[x], d[x])
     Counter({'a': 3, 'b': 2})

单目加和减（一元操作符）意思是从空计数器加或者减去。

     >>> c = Counter(a=2, b=-4)
     >>> +c
     Counter({'a': 2})
     >>> -c
     Counter({'b': 4})

3.3 新版功能: 添加了对一元加，一元减和位置集合操作的支持。

     注解: 计数器主要是为了表达运行的正的计数而设计；但是，小心不要预先
     排除负数或者其他类型。为了帮助这些用例，这一节记录了最小范围和类型
     限制。

        * *note Counter: 9e2. 类是一个字典的子类，不限制键和值。值用于表
          示计数，但你实际上 `可以' 存储任何其他值。

        * *note most_common(): ca1. 方法在值需要排序的时候用。

        * 原地操作比如 ‘c[key] += 1’ ， 值类型只需要支持加和减。 所以分
          数，小数，和十进制都可以用，负值也可以支持。这两个方法 *note
          update(): 193e. 和 *note subtract(): b62. 的输入和输出也一样支
          持负数和0。

        * Multiset多集合方法只为正值的使用情况设计。输入可以是负数或者
          0，但只输出计数为正的值。没有类型限制，但值类型需要支持加，减
          和比较操作。

        * *note elements(): ca2. 方法要求正整数计数。忽略0和负数计数。

参见
....

   * Bag class(1) 在 Smalltalk。

   * Wikipedia 链接 Multisets(2).

   * C++ multisets(3) 教程和例子。

   * 数学操作和多集合用例，参考 `Knuth, Donald.  The Art of Computer
     Programming Volume II, Section 4.6.3, Exercise 19' 。

   * 在给定数量和集合元素枚举所有不同的多集合，参考 *note
     itertools.combinations_with_replacement(): c21.

          map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC

   ---------- Footnotes ----------

   (1) 
https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html

   (2) https://en.wikipedia.org/wiki/Multiset

   (3) 
http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm


File: python.info,  Node: deque 对象,  Next: defaultdict 对象,  Prev: Counter 对象,  Up: collections --- 容器数据类型

5.8.3.4 ‘deque’ 对象
....................

 -- 类: collections.deque ([iterable[, maxlen]])

     返回一个新的双向队列对象，从左到右初始化(用方法 *note append():
     1940.) ，从 `iterable' （迭代对象) 数据创建。如果 `iterable' 没有指
     定，新队列为空。

     Deque队列是由栈或者queue队列生成的（发音是 “deck”，”double-ended
     queue”的简称）。Deque 支持线程安全，内存高效添加(append)和弹出
     (pop)，从两端都可以，两个方向的大概开销都是 O(1) 复杂度。

     虽然 *note list: 263. 对象也支持类似操作，不过这里优化了定长操作和
     ‘pop(0)’ 和 ‘insert(0, v)’ 的开销。它们引起 O(n) 内存移动的操作，改
     变底层数据表达的大小和位置。

     如果 `maxlen' 没有指定或者是 ‘None’ ，deques 可以增长到任意长度。否
     则，deque就限定到指定最大长度。一旦限定长度的deque满了，当新项加入
     时，同样数量的项就从另一端弹出。限定长度deque提供类似Unix filter
     ‘tail’ 的功能。它们同样可以用与追踪最近的交换和其他数据池活动。

     双向队列(deque)对象支持以下方法：

      -- 方法: append (x)

          添加 `x' 到右端。

      -- 方法: appendleft (x)

          添加 `x' 到左端。

      -- 方法: clear ()

          移除所有元素，使其长度为0.

      -- 方法: copy ()

          创建一份浅拷贝。

          3.5 新版功能.

      -- 方法: count (x)

          计算 deque 中元素等于 `x' 的个数。

          3.2 新版功能.

      -- 方法: extend (iterable)

          扩展deque的右侧，通过添加iterable参数中的元素。

      -- 方法: extendleft (iterable)

          扩展deque的左侧，通过添加iterable参数中的元素。注意，左添加时
          ，在结果中iterable参数中的顺序将被反过来添加。

      -- 方法: index (x[, start[, stop]])

          返回 `x' 在 deque 中的位置（在索引 `start' 之后，索引 `stop' 之
          前）。 返回第一个匹配项，如果未找到则引发 *note ValueError:
          1fc.。

          3.5 新版功能.

      -- 方法: insert (i, x)

          在位置 `i' 插入 `x' 。

          如果插入会导致一个限长 deque 超出长度 `maxlen' 的话，就引发一
          个 *note IndexError: e7d.。

          3.5 新版功能.

      -- 方法: pop ()

          移去并且返回一个元素，deque 最右侧的那一个。 如果没有元素的话
          ，就引发一个 *note IndexError: e7d.。

      -- 方法: popleft ()

          移去并且返回一个元素，deque 最左侧的那一个。 如果没有元素的话
          ，就引发 *note IndexError: e7d.。

      -- 方法: remove (value)

          移除找到的第一个 `value'。 如果没有的话就引发 *note
          ValueError: 1fc.。

      -- 方法: reverse ()

          将deque逆序排列。返回 ‘None’ 。

          3.2 新版功能.

      -- 方法: rotate (n=1)

          向右循环移动 `n' 步。 如果 `n' 是负数，就向左循环。

          如果deque不是空的，向右循环移动一步就等价于
          ‘d.appendleft(d.pop())’ ， 向左循环一步就等价于
          ‘d.append(d.popleft())’ 。

     Deque对象同样提供了一个只读属性:

      -- 属性: maxlen

          Deque的最大尺寸，如果没有限定的话就是 ‘None’ 。

          3.1 新版功能.

除了以上操作，deque 还支持迭代、封存、‘len(d)’、‘reversed(d)’、
‘copy.copy(d)’、‘copy.deepcopy(d)’、成员检测运算符 *note in: 7ac. 以及下
标引用例如通过 ‘d[0]’ 访问首个元素等。 索引访问在两端的复杂度均为 O(1) 但
在中间则会低至 O(n)。 如需快速随机访问，请改用列表。

Deque从版本3.5开始支持 ‘__add__()’, ‘__mul__()’, 和 ‘__imul__()’ 。

示例:

     >>> from collections import deque
     >>> d = deque('ghi')                 # make a new deque with three items
     >>> for elem in d:                   # iterate over the deque's elements
     ...     print(elem.upper())
     G
     H
     I

     >>> d.append('j')                    # add a new entry to the right side
     >>> d.appendleft('f')                # add a new entry to the left side
     >>> d                                # show the representation of the deque
     deque(['f', 'g', 'h', 'i', 'j'])

     >>> d.pop()                          # return and remove the rightmost item
     'j'
     >>> d.popleft()                      # return and remove the leftmost item
     'f'
     >>> list(d)                          # list the contents of the deque
     ['g', 'h', 'i']
     >>> d[0]                             # peek at leftmost item
     'g'
     >>> d[-1]                            # peek at rightmost item
     'i'

     >>> list(reversed(d))                # list the contents of a deque in reverse
     ['i', 'h', 'g']
     >>> 'h' in d                         # search the deque
     True
     >>> d.extend('jkl')                  # add multiple elements at once
     >>> d
     deque(['g', 'h', 'i', 'j', 'k', 'l'])
     >>> d.rotate(1)                      # right rotation
     >>> d
     deque(['l', 'g', 'h', 'i', 'j', 'k'])
     >>> d.rotate(-1)                     # left rotation
     >>> d
     deque(['g', 'h', 'i', 'j', 'k', 'l'])

     >>> deque(reversed(d))               # make a new deque in reverse order
     deque(['l', 'k', 'j', 'i', 'h', 'g'])
     >>> d.clear()                        # empty the deque
     >>> d.pop()                          # cannot pop from an empty deque
     Traceback (most recent call last):
         File "<pyshell#6>", line 1, in -toplevel-
             d.pop()
     IndexError: pop from an empty deque

     >>> d.extendleft('abc')              # extendleft() reverses the input order
     >>> d
     deque(['c', 'b', 'a'])

* Menu:

* deque 用法::


File: python.info,  Node: deque 用法,  Up: deque 对象

5.8.3.5 ‘deque’ 用法
....................

这一节展示了deque的多种用法。

限长deque提供了类似Unix ‘tail’ 过滤功能

     def tail(filename, n=10):
         'Return the last n lines of a file'
         with open(filename) as f:
             return deque(f, n)

另一个用法是维护一个近期添加元素的序列，通过从右边添加和从左边弹出

     def moving_average(iterable, n=3):
         # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
         # http://en.wikipedia.org/wiki/Moving_average
         it = iter(iterable)
         d = deque(itertools.islice(it, n-1))
         d.appendleft(0)
         s = sum(d)
         for elem in it:
             s += elem - d.popleft()
             d.append(elem)
             yield s / n

一个 轮询调度器(1) 可以通过在 *note deque: 539. 中放入迭代器来实现。值从
当前迭代器的位置0被取出并暂存(yield)。 如果这个迭代器消耗完毕，就用
*note popleft(): 1946. 将其从对列中移去；否则，就通过 *note rotate():
1948. 将它移到队列的末尾

     def roundrobin(*iterables):
         "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
         iterators = deque(map(iter, iterables))
         while iterators:
             try:
                 while True:
                     yield next(iterators[0])
                     iterators.rotate(-1)
             except StopIteration:
                 # Remove an exhausted iterator.
                 iterators.popleft()

*note rotate(): 1948. 方法提供了一种方式来实现 *note deque: 539. 切片和
删除。 例如， 一个纯的Python ‘del d[n]’ 实现依赖于 ‘rotate()’ 来定位要弹
出的元素

     def delete_nth(d, n):
         d.rotate(-n)
         d.popleft()
         d.rotate(n)

要实现 *note deque: 539. 切片， 使用一个类似的方法，应用 *note rotate():
1948. 将目标元素放到左边。通过 *note popleft(): 1946. 移去老的条目（
entries），通过 *note extend(): 1943. 添加新的条目， 然后反向 rotate。这
个方法可以最小代价实现命令式的栈操作，诸如 ‘dup’, ‘drop’, ‘swap’,
‘over’, ‘pick’, ‘rot’, 和 ‘roll’ 。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Round-robin_scheduling


File: python.info,  Node: defaultdict 对象,  Next: namedtuple 命名元组的工厂函数,  Prev: deque 对象,  Up: collections --- 容器数据类型

5.8.3.6 ‘defaultdict’ 对象
..........................

 -- 类: collections.defaultdict ([default_factory[, ...]])

     返回一个新的类似字典的对象。 *note defaultdict: b42. 是内置 *note
     dict: 1b9. 类的子类。它重载了一个方法并添加了一个可写的实例变量。其
     余的功能与 *note dict: 1b9. 类相同，此处不再重复说明。

     本对象包含一个名为 *note default_factory: 194b. 的属性，构造时，第
     一个参数用于为该属性提供初始值，默认为 ‘None’。所有其他参数（包括关
     键字参数）都相当于传递给 *note dict: 1b9. 的构造函数。

     *note defaultdict: b42. 对象除了支持标准 *note dict: 1b9. 的操作，
     还支持以下方法作为扩展：

      -- 方法: __missing__ (key)

          如果 *note default_factory: 194b. 属性为 ‘None’，则调用本方法
          会抛出 *note KeyError: 2c8. 异常，附带参数 `key'。

          如果 *note default_factory: 194b. 不为 ‘None’，则它会被（不带
          参数地）调用来为 `key' 提供一个默认值，这个值和 `key' 作为一对
          键值对被插入到字典中，并作为本方法的返回值返回。

          如果调用 *note default_factory: 194b. 时抛出了异常，这个异常会
          原封不动地向外层传递。

          在无法找到所需键值时，本方法会被 *note dict: 1b9. 中的 *note
          __getitem__(): 280. 方法调用。无论本方法返回了值还是抛出了异常
          ，都会被 *note __getitem__(): 280. 传递。

          注意，*note __missing__(): 194c. `不会' 被 *note
          __getitem__(): 280. 以外的其他方法调用。意味着 ‘get()’ 会像正
          常的 dict 那样返回 ‘None’，而不是使用 *note default_factory:
          194b.。

     *note defaultdict: b42. 对象支持以下实例变量：

      -- 属性: default_factory

          本属性由 *note __missing__(): 194c. 方法来调用。如果构造对象时
          提供了第一个参数，则本属性会被初始化成那个参数，如果未提供第一
          个参数，则本属性为 ‘None’。

* Menu:

* defaultdict 例子::


File: python.info,  Node: defaultdict 例子,  Up: defaultdict 对象

5.8.3.7 ‘defaultdict’ 例子
..........................

使用 *note list: 263. 作为 *note default_factory: 194b.，很轻松地将（键
-值对组成的）序列转换为（键-列表组成的）字典：

     >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
     >>> d = defaultdict(list)
     >>> for k, v in s:
     ...     d[k].append(v)
     ...
     >>> sorted(d.items())
     [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

当每个键第一次遇见时，它还没有在字典里面，所以自动创建该条目，即调用
*note default_factory: 194b. 方法，返回一个空的 *note list: 263.。
‘list.append()’ 操作添加值到这个新的列表里。当再次存取该键时，就正常操作
，‘list.append()’ 添加另一个值到列表中。这个计数比它的等价方法 *note
dict.setdefault(): 9c7. 要快速和简单：

     >>> d = {}
     >>> for k, v in s:
     ...     d.setdefault(k, []).append(v)
     ...
     >>> sorted(d.items())
     [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

设置 *note default_factory: 194b. 为 *note int: 185.，使 *note
defaultdict: b42. 用于计数（类似其他语言中的 bag 或 multiset）：

     >>> s = 'mississippi'
     >>> d = defaultdict(int)
     >>> for k in s:
     ...     d[k] += 1
     ...
     >>> sorted(d.items())
     [('i', 4), ('m', 1), ('p', 2), ('s', 4)]

当一个字母首次遇到时，它会查询失败，则 *note default_factory: 194b. 会调
用 *note int(): 185. 来提供一个整数 0 作为默认值。后续的自增操作建立起对
每个字母的计数。

函数 *note int(): 185. 总是返回 0，这是常数函数的特殊情况。一个更快和灵
活的方法是使用 lambda 函数，可以提供任何常量值（不只是0）：

     >>> def constant_factory(value):
     ...     return lambda: value
     >>> d = defaultdict(constant_factory('<missing>'))
     >>> d.update(name='John', action='ran')
     >>> '%(name)s %(action)s to %(object)s' % d
     'John ran to <missing>'

设置 *note default_factory: 194b. 为 *note set: b77. 使 *note
defaultdict: b42. 用于构建 set 集合：

     >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
     >>> d = defaultdict(set)
     >>> for k, v in s:
     ...     d[k].add(v)
     ...
     >>> sorted(d.items())
     [('blue', {2, 4}), ('red', {1, 3})]


File: python.info,  Node: namedtuple 命名元组的工厂函数,  Next: OrderedDict 对象,  Prev: defaultdict 对象,  Up: collections --- 容器数据类型

5.8.3.8 ‘namedtuple()’ 命名元组的工厂函数
.........................................

命名元组赋予每个位置一个含义，提供可读性和自文档性。它们可以用于任何普通
元组，并添加了通过名字获取值的能力，通过索引值也是可以的。

 -- 函数: collections.namedtuple (typename, field_names, *,
          rename=False, defaults=None, module=None)

     返回一个新的元组子类，名为 `typename' 。这个新的子类用于创建类元组
     的对象，可以通过字段名来获取属性值，同样也可以通过索引和迭代获取值
     。子类实例同样有文档字符串（类名和字段名）另外一个有用的 *note
     __repr__(): 347. 方法，以 ‘name=value’ 格式列明了元组内容。

     `field_names' 是一个像 ‘[‘x’, ‘y’]’ 一样的字符串序列。另外
     `field_names' 可以是一个纯字符串，用空白或逗号分隔开元素名，比如
     ‘'x y'’ 或者 ‘'x, y'’ 。

     任何有效的Python 标识符都可以作为字段名，除了下划线开头的那些。有效
     标识符由字母，数字，下划线组成，但首字母不能是数字或下划线，另外不
     能是关键词 *note keyword: a7. 比如 `class', `for', `return',
     `global', `pass', 或 `raise' 。

     如果 `rename' 为真， 无效字段名会自动转换成位置名。比如 ‘['abc',
     'def', 'ghi', 'abc']’ 转换成 ‘['abc', '_1', 'ghi', '_3']’ ， 消除关
     键词 ‘def’ 和重复字段名 ‘abc’ 。

     `defaults' 可以为 ‘None’ 或者是一个默认值的 *note iterable: bb4. 。
     如果一个默认值域必须跟其他没有默认值的域在一起出现，`defaults' 就应
     用到最右边的参数。比如如果域名 ‘['x', 'y', 'z']’ 和默认值 ‘(1, 2)’
     ，那么 ‘x’ 就必须指定一个参数值 ，‘y’ 默认值 ‘1’ ， ‘z’ 默认值 ‘2’
     。

     如果 `module' 值有定义，命名元组的 ‘__module__’ 属性值就被设置。

     命名元组实例没有字典，所以它们要更轻量，并且占用更小内存。

     在 3.1 版更改: 添加了对 `rename' 的支持。

     在 3.6 版更改: `verbose' 和 `rename' 参数成为 *note 仅限关键字参数:
     2ad.

     在 3.6 版更改: 添加了 `module' 参数。

     在 3.7 版更改: 移除了 `verbose' 形参和 ‘_source’ 属性。

     在 3.7 版更改: 添加了 `defaults' 参数和 ‘_field_defaults’ 属性。

     >>> # Basic example
     >>> Point = namedtuple('Point', ['x', 'y'])
     >>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
     >>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
     33
     >>> x, y = p                # unpack like a regular tuple
     >>> x, y
     (11, 22)
     >>> p.x + p.y               # fields also accessible by name
     33
     >>> p                       # readable __repr__ with a name=value style
     Point(x=11, y=22)

命名元组尤其有用于赋值 *note csv: 2a. *note sqlite3: f3. 模块返回的元组

     EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

     import csv
     for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
         print(emp.name, emp.title)

     import sqlite3
     conn = sqlite3.connect('/companydata')
     cursor = conn.cursor()
     cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
     for emp in map(EmployeeRecord._make, cursor.fetchall()):
         print(emp.name, emp.title)

除了继承元组的方法，命名元组还支持三个额外的方法和两个属性。为了防止字段
名冲突，方法和属性以下划线开始。

 -- 方法: classmethod somenamedtuple._make (iterable)

     类方法从存在的序列或迭代实例创建一个新实例。

          >>> t = [11, 22]
          >>> Point._make(t)
          Point(x=11, y=22)

 -- 方法: somenamedtuple._asdict ()

     返回一个新的 *note dict: 1b9. ，它将字段名称映射到它们对应的值：

          >>> p = Point(x=11, y=22)
          >>> p._asdict()
          {'x': 11, 'y': 22}

     在 3.1 版更改: 返回一个 *note OrderedDict: 1ba. 而不是 *note dict:
     1b9. 。

     在 3.8 版更改: 返回一个常规 *note dict: 1b9. 而不是 *note
     OrderedDict: 1ba.。 因为自 Python 3.7 起，常规字典已经保证有序。 如
     果需要 *note OrderedDict: 1ba. 的额外特性，推荐的解决方案是将结果转
     换为需要的类型: ‘OrderedDict(nt._asdict())’。

 -- 方法: somenamedtuple._replace (**kwargs)

     返回一个新的命名元组实例，并将指定域替换为新的值

          >>> p = Point(x=11, y=22)
          >>> p._replace(x=33)
          Point(x=33, y=22)

          >>> for partnum, record in inventory.items():
          ...     inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())

 -- 属性: somenamedtuple._fields

     字符串元组列出了字段名。用于提醒和从现有元组创建一个新的命名元组类
     型。

          >>> p._fields            # view the field names
          ('x', 'y')

          >>> Color = namedtuple('Color', 'red green blue')
          >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
          >>> Pixel(11, 22, 128, 255, 0)
          Pixel(x=11, y=22, red=128, green=255, blue=0)

 -- 属性: somenamedtuple._field_defaults

     字典将字段名称映射到默认值。

          >>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
          >>> Account._field_defaults
          {'balance': 0}
          >>> Account('premium')
          Account(type='premium', balance=0)

要获取这个名字域的值，使用 *note getattr(): 451. 函数 :

     >>> getattr(p, 'x')
     11

转换一个字典到命名元组，使用 ** 两星操作符 (所述如 *note 解包参数列表:
1265.):

     >>> d = {'x': 11, 'y': 22}
     >>> Point(**d)
     Point(x=11, y=22)

因为一个命名元组是一个正常的Python类，它可以很容易的通过子类更改功能。这
里是如何添加一个计算域和定宽输出打印格式:

     >>> class Point(namedtuple('Point', ['x', 'y'])):
     ...     __slots__ = ()
     ...     @property
     ...     def hypot(self):
     ...         return (self.x ** 2 + self.y ** 2) ** 0.5
     ...     def __str__(self):
     ...         return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)

     >>> for p in Point(3, 4), Point(14, 5/7):
     ...     print(p)
     Point: x= 3.000  y= 4.000  hypot= 5.000
     Point: x=14.000  y= 0.714  hypot=14.018

上面的子类设置 ‘__slots__’ 为一个空元组。通过阻止创建实例字典保持了较低
的内存开销。

子类化对于添加和存储新的名字域是无效的。应当通过 *note _fields: 1951. 创
建一个新的命名元组来实现它:

     >>> Point3D = namedtuple('Point3D', Point._fields + ('z',))

文档字符串可以自定义，通过直接赋值给 ‘__doc__’ 属性:

     >>> Book = namedtuple('Book', ['id', 'title', 'authors'])
     >>> Book.__doc__ += ': Hardcover book in active collection'
     >>> Book.id.__doc__ = '13-digit ISBN'
     >>> Book.title.__doc__ = 'Title of first printing'
     >>> Book.authors.__doc__ = 'List of authors sorted by last name'

在 3.5 版更改: 文档字符串属性变成可写。

参见
....

   * 请参阅 *note typing.NamedTuple: 281. ，以获取为命名元组添加类型提示
     的方法。 它还使用 *note class: c72. 关键字提供了一种优雅的符号:

          class Component(NamedTuple):
              part_number: int
              weight: float
              description: Optional[str] = None

   * 对于以字典为底层的可变域名， 参考 *note types.SimpleNamespace():
     9b4. 。

   * *note dataclasses: 30. 模块提供了一个装饰器和一些函数，用于自动将生
     成的特殊方法添加到用户定义的类中。


File: python.info,  Node: OrderedDict 对象,  Next: UserDict 对象,  Prev: namedtuple 命名元组的工厂函数,  Up: collections --- 容器数据类型

5.8.3.9 ‘OrderedDict’ 对象
..........................

有序词典就像常规词典一样，但有一些与排序操作相关的额外功能。由于内置的
*note dict: 1b9. 类获得了记住插入顺序的能力（在 Python 3.7 中保证了这种
新行为），它们变得不那么重要了。

一些与 *note dict: 1b9. 的不同仍然存在：

   * 常规的 *note dict: 1b9. 被设计为非常擅长映射操作。 跟踪插入顺序是次
     要的。

   * *note OrderedDict: 1ba. 旨在擅长重新排序操作。 空间效率、迭代速度和
     更新操作的性能是次要的。

   * 算法上， *note OrderedDict: 1ba. 可以比 *note dict: 1b9. 更好地处理
     频繁的重新排序操作。 这使其适用于跟踪最近的访问（例如在 LRU
     cache(1) 中）。

   * 对于 *note OrderedDict: 1ba. ，相等操作检查匹配顺序。

   * *note OrderedDict: 1ba. 类的 ‘popitem()’ 方法有不同的签名。它接受一
     个可选参数来指定弹出哪个元素。

   * *note OrderedDict: 1ba. 类有一个 ‘move_to_end()’ 方法，可以有效地将
     元素移动到任一端。

   * Python 3.8之前， *note dict: 1b9. 缺少 *note __reversed__(): 537. 方
     法。

 -- 类: collections.OrderedDict ([items])

     返回一个 *note dict: 1b9. 子类的实例，它具有专门用于重新排列字典顺
     序的方法。

     3.1 新版功能.

      -- 方法: popitem (last=True)

          有序字典的 *note popitem(): c8c. 方法移除并返回一个 (key,
          value) 键值对。 如果 `last' 值为真，则按 LIFO 后进先出的顺序返
          回键值对，否则就按 FIFO 先进先出的顺序返回键值对。

      -- 方法: move_to_end (key, last=True)

          将现有 `key' 移动到有序字典的任一端。 如果 `last' 为真值（默认
          ）则将元素移至末尾；如果 `last' 为假值则将元素移至开头。如果
          `key' 不存在则会触发 *note KeyError: 2c8.:

               >>> d = OrderedDict.fromkeys('abcde')
               >>> d.move_to_end('b')
               >>> ''.join(d.keys())
               'acdeb'
               >>> d.move_to_end('b', last=False)
               >>> ''.join(d.keys())
               'bacde'

          3.2 新版功能.

相对于通常的映射方法，有序字典还另外提供了逆序迭代的支持，通过 *note
reversed(): 18f. 。

*note OrderedDict: 1ba. 之间的相等测试是顺序敏感的，实现为
‘list(od1.items())==list(od2.items())’ 。 *note OrderedDict: 1ba. 对象和
其他的 *note Mapping: 1954. 的相等测试，是顺序敏感的字典测试。这允许
*note OrderedDict: 1ba. 替换为任何字典可以使用的场所。

在 3.5 版更改: *note OrderedDict: 1ba. 的项(item)，键(key)和值(value)
*note 视图: 1955. 现在支持逆序迭代，通过 *note reversed(): 18f. 。

在 3.6 版更改: PEP 468(2) 赞成将关键词参数的顺序保留， 通过传递给 *note
OrderedDict: 1ba. 构造器和它的 ‘update()’ 方法。

* Menu:

* OrderedDict 例子和用法::

   ---------- Footnotes ----------

   (1) 
https://medium.com/@krishankantsinghal/my-first-blog-on-medium-583159139237

   (2) https://www.python.org/dev/peps/pep-0468


File: python.info,  Node: OrderedDict 例子和用法,  Up: OrderedDict 对象

5.8.3.10 ‘OrderedDict’ 例子和用法
.................................

创建记住键值 `最后' 插入顺序的有序字典变体很简单。 如果新条目覆盖现有条
目，则原始插入位置将更改并移至末尾:

     class LastUpdatedOrderedDict(OrderedDict):
         'Store items in the order the keys were last added'

         def __setitem__(self, key, value):
             super().__setitem__(key, value)
             self.move_to_end(key)

一个 *note OrderedDict: 1ba. 对于实现 *note functools.lru_cache(): 1c8.
的变体也很有用:

     class LRU(OrderedDict):
         'Limit size, evicting the least recently looked-up key when full'

         def __init__(self, maxsize=128, /, *args, **kwds):
             self.maxsize = maxsize
             super().__init__(*args, **kwds)

         def __getitem__(self, key):
             value = super().__getitem__(key)
             self.move_to_end(key)
             return value

         def __setitem__(self, key, value):
             if key in self:
                 self.move_to_end(key)
             super().__setitem__(key, value)
             if len(self) > self.maxsize:
                 oldest = next(iter(self))
                 del self[oldest]


File: python.info,  Node: UserDict 对象,  Next: UserList 对象,  Prev: OrderedDict 对象,  Up: collections --- 容器数据类型

5.8.3.11 ‘UserDict’ 对象
........................

*note UserDict: 1935. 类是用作字典对象的外包装。对这个类的需求已部分由直
接创建 *note dict: 1b9. 的子类的功能所替代；不过，这个类处理起来更容易，
因为底层的字典可以作为属性来访问。

 -- 类: collections.UserDict ([initialdata])

     模拟一个字典类。这个实例的内容保存为一个正常字典， 可以通过 *note
     UserDict: 1935. 实例的 *note data: 1958. 属性存取。如果提供了
     `initialdata' 值， *note data: 1958. 就被初始化为它的内容；注意一个
     `initialdata' 的引用不会被保留作为其他用途。

     *note UserDict: 1935. 实例提供了以下属性作为扩展方法和操作的支持:

      -- 属性: data

          一个真实的字典，用于保存 *note UserDict: 1935. 类的内容。


File: python.info,  Node: UserList 对象,  Next: UserString 对象,  Prev: UserDict 对象,  Up: collections --- 容器数据类型

5.8.3.12 ‘UserList’ 对象
........................

这个类封装了列表对象。它是一个有用的基础类，对于你想自定义的类似列表的类
，可以继承和覆盖现有的方法，也可以添加新的方法。这样我们可以对列表添加新
的行为。

对这个类的需求已部分由直接创建 *note list: 263. 的子类的功能所替代；不过
，这个类处理起来更容易，因为底层的列表可以作为属性来访问。

 -- 类: collections.UserList ([list])

     模拟一个列表。这个实例的内容被保存为一个正常列表，通过 *note
     UserList: 1936. 的 *note data: 195a. 属性存取。实例内容被初始化为一
     个 `list' 的copy，默认为 ‘[]’ 空列表。 `list' 可以是迭代对象，比如
     一个Python列表，或者一个 *note UserList: 1936. 对象。

     *note UserList: 1936. 提供了以下属性作为可变序列的方法和操作的扩展:

      -- 属性: data

          一个 *note list: 263. 对象用于存储 *note UserList: 1936. 的内
          容。

`子类化的要求:' *note UserList: 1936. 的子类需要提供一个构造器，可以无参
数调用，或者一个参数调用。返回一个新序列的列表操作需要创建一个实现类的实
例。它假定了构造器可以以一个参数进行调用，这个参数是一个序列对象，作为数
据源。

如果一个分离的类不希望依照这个需求，所有的特殊方法就必须重写；请参照源代
码进行修改。


File: python.info,  Node: UserString 对象,  Prev: UserList 对象,  Up: collections --- 容器数据类型

5.8.3.13 ‘UserString’ 对象
..........................

*note UserString: 6b6. 类是用作字符串对象的外包装。对这个类的需求已部分
由直接创建 *note str: 339. 的子类的功能所替代；不过，这个类处理起来更容
易，因为底层的字符串可以作为属性来访问。

 -- 类: collections.UserString (seq)

     模拟一个字符串对象。这个实例对象的内容保存为一个正常字符串，通过
     *note UserString: 6b6. 的 *note data: 195c. 属性存取。实例内容初始
     化设置为 `seq' 的copy。`seq' 参数可以是任何可通过内建 *note str():
     339. 函数转换为字符串的对象。

     *note UserString: 6b6. 提供了以下属性作为字符串方法和操作的额外支持
     ：

      -- 属性: data

          一个真正的 *note str: 339. 对象用来存放 *note UserString: 6b6.
          类的内容。

     在 3.5 版更改: 新方法 ‘__getnewargs__’, ‘__rmod__’, ‘casefold’,
     ‘format_map’, ‘isprintable’, 和 ‘maketrans’。


File: python.info,  Node: collections abc --- 容器的抽象基类,  Next: heapq --- 堆队列算法,  Prev: collections --- 容器数据类型,  Up: 数据类型

5.8.4 ‘collections.abc’ — 容器的抽象基类
----------------------------------------

3.3 新版功能: 该模块曾是 *note collections: 1e. 模块的组成部分。

`源代码：' Lib/_collections_abc.py(1)

__________________________________________________________________

该模块定义了一些 *note 抽象基类: b3b.，它们可用于判断一个具体类是否具有
某一特定的接口；例如，这个类是否可哈希，或其是否为映射类。

* Menu:

* 容器抽象基类::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/_collections_abc.py


File: python.info,  Node: 容器抽象基类,  Up: collections abc --- 容器的抽象基类

5.8.4.1 容器抽象基类
....................

这个容器模块提供了以下 *note ABCs: b3b.:

抽象基类                       继承自                     抽象方法                    Mixin 方法
                                                                                      
-----------------------------------------------------------------------------------------------------------------------------------------------
                                                                                      
*note Container: 1960.                                    ‘__contains__’
                                                          
                                                                                      
*note Hashable: 1961.                                     ‘__hash__’
                                                          
                                                                                      
*note Iterable: 1962.                                     ‘__iter__’
                                                          
                                                                                      
*note Iterator: 1963.          *note Iterable: 1962.      ‘__next__’                  ‘__iter__’
                                                                                      
                                                                                      
*note Reversible: 536.         *note Iterable: 1962.      ‘__reversed__’
                                                          
                                                                                      
*note Generator: 6be.          *note Iterator: 1963.      ‘send’, ‘throw’             ‘close’, ‘__iter__’, ‘__next__’
                                                                                      
                                                                                      
*note Sized: 1964.                                        ‘__len__’
                                                          
                                                                                      
*note Callable: 1965.                                     ‘__call__’
                                                          
                                                                                      
*note Collection: 535.         *note Sized: 1964,         ‘__contains__’,
                               *note Iterable: 1962,      ‘__iter__’, ‘__len__’
                               *note Container: 1960.     
                               
                                                                                      
*note Sequence: 1640.          *note Reversible: 536,     ‘__getitem__’, ‘__len__’    ‘__contains__’, ‘__iter__’, ‘__reversed__’, ‘index’,
                               *note Collection: 535.                                 and ‘count’
                                                                                      
                                                                                      
*note MutableSequence: 6b5.    *note Sequence: 1640.      ‘__getitem__’,              继承自 *note Sequence: 1640. 的方法，以及 ‘append’,
                                                          ‘__setitem__’,              ‘reverse’, ‘extend’, ‘pop’, ‘remove’，和 ‘__iadd__’
                                                          ‘__delitem__’, ‘__len__’,   
                                                          ‘insert’
                                                          
                                                                                      
*note ByteString: 1966.        *note Sequence: 1640.      ‘__getitem__’, ‘__len__’    继承自 *note Sequence: 1640. 的方法
                                                                                      
                                                                                      
*note Set: 16ea.               *note Collection: 535.     ‘__contains__’,             ‘__le__’, ‘__lt__’, ‘__eq__’, ‘__ne__’, ‘__gt__’,
                                                          ‘__iter__’, ‘__len__’       ‘__ge__’, ‘__and__’, ‘__or__’, ‘__sub__’, ‘__xor__’,
                                                                                      and ‘isdisjoint’
                                                                                      
                                                                                      
*note MutableSet: 1967.        *note Set: 16ea.           ‘__contains__’,             继承自 *note Set: 16ea. 的方法以及 ‘clear’, ‘pop’,
                                                          ‘__iter__’, ‘__len__’,      ‘remove’, ‘__ior__’, ‘__iand__’, ‘__ixor__’，和
                                                          ‘add’, ‘discard’            ‘__isub__’
                                                                                      
                                                                                      
*note Mapping: 1954.           *note Collection: 535.     ‘__getitem__’,              ‘__contains__’, ‘keys’, ‘items’, ‘values’, ‘get’,
                                                          ‘__iter__’, ‘__len__’       ‘__eq__’, and ‘__ne__’
                                                                                      
                                                                                      
*note MutableMapping: 9f7.     *note Mapping: 1954.       ‘__getitem__’,              继承自 *note Mapping: 1954. 的方法以及 ‘pop’,
                                                          ‘__setitem__’,              ‘popitem’, ‘clear’, ‘update’，和 ‘setdefault’
                                                          ‘__delitem__’,              
                                                          ‘__iter__’, ‘__len__’
                                                          
                                                                                      
*note MappingView: 1968.       *note Sized: 1964.                                     ‘__len__’
                                                                                      
                                                                                      
*note ItemsView: 1969.         *note MappingView: 1968,                               ‘__contains__’, ‘__iter__’
                               *note Set: 16ea.                                       
                               
                                                                                      
*note KeysView: 196a.          *note MappingView: 1968,                               ‘__contains__’, ‘__iter__’
                               *note Set: 16ea.                                       
                               
                                                                                      
*note ValuesView: 196b.        *note MappingView: 1968,                               ‘__contains__’, ‘__iter__’
                               *note Collection: 535.                                 
                               
                                                                                      
*note Awaitable: 6bf.                                     ‘__await__’
                                                          
                                                                                      
*note Coroutine: 6c0.          *note Awaitable: 6bf.      ‘send’, ‘throw’             ‘close’
                                                                                      
                                                                                      
*note AsyncIterable: 6c2.                                 ‘__aiter__’
                                                          
                                                                                      
*note AsyncIterator: 6c1.      *note AsyncIterable: 6c2.  ‘__anext__’                 ‘__aiter__’
                                                                                      
                                                                                      
*note AsyncGenerator: 538.     *note AsyncIterator: 6c1.  ‘asend’, ‘athrow’           ‘aclose’, ‘__aiter__’, ‘__anext__’
                                                                                      

 -- 类: collections.abc.Container

     提供了 *note __contains__(): d30. 方法的抽象基类。

 -- 类: collections.abc.Hashable

     提供了 *note __hash__(): 349. 方法的抽象基类。

 -- 类: collections.abc.Sized

     提供了 *note __len__(): dd3. 方法的抽象基类。

 -- 类: collections.abc.Callable

     提供了 *note __call__(): 143e. 方法的抽象基类。

 -- 类: collections.abc.Iterable

     提供了 *note __iter__(): 517. 方法的抽象基类。

     使用 ‘isinstance(obj, Iterable)’ 可以检测一个类是否已经注册到了
     *note Iterable: 1962. 或者实现了 *note __iter__(): 517. 函数，但是
     无法检测这个类是否能够使用 *note __getitem__(): 280. 方法进行迭代。
     检测一个对象是否是 *note iterable: bb4. 的唯一可信赖的方法是调用
     ‘iter(obj)’。

 -- 类: collections.abc.Collection

     集合了 Sized 和 Iterable 类的抽象基类。

     3.6 新版功能.

 -- 类: collections.abc.Iterator

     提供了 *note __iter__(): 163a. 和 *note __next__(): c6c. 方法的抽象
     基类。参见 *note iterator: 104b. 的定义。

 -- 类: collections.abc.Reversible

     为可迭代类提供了 *note __reversed__(): 537. 方法的抽象基类。

     3.6 新版功能.

 -- 类: collections.abc.Generator

     生成器类，实现了 PEP 342(1) 中定义的协议，继承并扩展了迭代器，提供
     了 *note send(): 149f, *note throw(): 14a1. 和 *note close(): 14a3.
     方法。参见 *note generator: 9aa. 的定义。

     3.5 新版功能.

 -- 类: collections.abc.Sequence
 -- 类: collections.abc.MutableSequence
 -- 类: collections.abc.ByteString

     只读且可变的序列 *note sequences: 1238. 的抽象基类。

     实现笔记：一些混入（Maxin）方法比如 *note __iter__(): 517, *note
     __reversed__(): 537. 和 ‘index()’ 会重复调用底层的 *note
     __getitem__(): 280. 方法。因此，如果实现的 *note __getitem__():
     280. 是常数级访问速度，那么相应的混入方法会有一个线性的表现；然而，
     如果底层方法是线性实现（例如链表），那么混入方法将会是平方级的表现
     ，这也许就需要被重构了。

     在 3.5 版更改: index() 方法支持 `stop' 和 `start' 参数。

 -- 类: collections.abc.Set
 -- 类: collections.abc.MutableSet

     只读且可变的集合的抽象基类。

 -- 类: collections.abc.Mapping
 -- 类: collections.abc.MutableMapping

     只读且可变的映射 *note mappings: b41. 的抽象基类。

 -- 类: collections.abc.MappingView
 -- 类: collections.abc.ItemsView
 -- 类: collections.abc.KeysView
 -- 类: collections.abc.ValuesView

     映射及其键和值的视图 *note views: 1955. 的抽象基类。

 -- 类: collections.abc.Awaitable

     为可等待对象 *note awaitable: 521. 提供的类，可以被用于 *note
     await: 1a4. 表达式中。习惯上必须实现 *note __await__(): 64b. 方法。

     *note 协程: 1a7. 对象和 *note Coroutine: 6c0. ABC 的实例都是这个
     ABC 的实例。

          注解: 在 CPython 里，基于生成器的协程（使用 *note
          types.coroutine(): 785. 或 *note asyncio.coroutine(): 283. 包
          装的生成器）都是 `可等待对象'，即使他们不含有 *note
          __await__(): 64b. 方法。使用 ‘isinstance(gencoro, Awaitable)’
          来检测他们会返回 ‘False’。要使用 *note inspect.isawaitable():
          702. 来检测他们。

     3.5 新版功能.

 -- 类: collections.abc.Coroutine

     用于协程兼容类的抽象基类。实现了如下定义在 *note 协程对象: 143d.: 里
     的方法： *note send(): 149e.，*note throw(): 14a0. 和 *note
     close(): 14a2.。通常的实现里还需要实现 *note __await__(): 64b. 方法
     。所有的 *note Coroutine: 6c0. 实例都必须是 *note Awaitable: 6bf. 实
     例。参见 *note coroutine: 1a7. 的定义。

          注解: 在 CPython 里，基于生成器的协程（使用 *note
          types.coroutine(): 785. 或 *note asyncio.coroutine(): 283. 包
          装的生成器）都是 `可等待对象'，即使他们不含有 *note
          __await__(): 64b. 方法。使用 ‘isinstance(gencoro, Coroutine)’
          来检测他们会返回 ‘False’。要使用 *note inspect.isawaitable():
          702. 来检测他们。

     3.5 新版功能.

 -- 类: collections.abc.AsyncIterable

     提供了 ‘__aiter__’ 方法的抽象基类。参见 *note asynchronous
     iterable: 649. 的定义。

     3.5 新版功能.

 -- 类: collections.abc.AsyncIterator

     提供了 ‘__aiter__’ 和 ‘__anext__’ 方法的抽象基类。参见 *note
     asynchronous iterator: 64e. 的定义。

     3.5 新版功能.

 -- 类: collections.abc.AsyncGenerator

     为异步生成器类提供的抽象基类，这些类实现了定义在 PEP 525(2) 和 PEP
     492(3) 里的协议。

     3.6 新版功能.

这些抽象基类让我们可以确定类和示例拥有某些特定的函数，例如：

     size = None
     if isinstance(myvar, collections.abc.Sized):
         size = len(myvar)

有些抽象基类也可以用作混入类（mixin），这可以更容易地开发支持容器 API 的
类。例如，要写一个支持完整 *note Set: 16ea. API 的类，只需要提供下面这三
个方法： *note __contains__(): d30, *note __iter__(): 517. 和 *note
__len__(): dd3.。抽象基类会补充上其余的方法，比如 *note __and__(): 1476.
和 ‘isdisjoint()’:

     class ListBasedSet(collections.abc.Set):
         ''' Alternate set implementation favoring space over speed
             and not requiring the set elements to be hashable. '''
         def __init__(self, iterable):
             self.elements = lst = []
             for value in iterable:
                 if value not in lst:
                     lst.append(value)

         def __iter__(self):
             return iter(self.elements)

         def __contains__(self, value):
             return value in self.elements

         def __len__(self):
             return len(self.elements)

     s1 = ListBasedSet('abcdef')
     s2 = ListBasedSet('defghi')
     overlap = s1 & s2            # The __and__() method is supported automatically

当把 *note Set: 16ea. 和 *note MutableSet: 1967. 用作混入类时需注意：

  1. 由于某些集合操作会创建新集合，默认的混入方法需要一种从可迭代对象里
     创建新实例的方法。假如其类构造函数签名形如 ‘ClassName(iterable)’ ，
     则其会调用一个内部的类方法 ‘_from_iterable()’，其中调用了
     ‘cls(iterable)’ 来生成一个新集合。如果这个 *note Set: 16ea. 混入类
     在类中被使用，但其构造函数的签名却是不同的形式，那么你就需要重载
     ‘_from_iterable()’ 方法，将其编写成一个类方法，并且它能够从可迭代对
     象参数中构造一个新实例。

  2. 重载比较符时时（想必是为了速度，因为其语义都是固定的），只需要重定
     义 *note __le__(): ca8. 和 *note __ge__(): caa. 函数，然后其他的操
     作会自动跟进。

  3. 混入集合类 *note Set: 16ea. 提供了一个 ‘_hash()’ 方法为集合计算哈希
     值，然而， *note __hash__(): 349. 函数却没有被定义，因为并不是所有
     集合都是可哈希并且不可变的。为了使用混入类为集合添加哈希能力，可以
     同时继承 *note Set(): 16ea. 和 *note Hashable(): 1961. 类，然后定义
     ‘__hash__ = Set._hash’。

参见
....

   * OrderedSet recipe(4) 是基于 *note MutableSet: 1967. 构建的一个示例
     。

   * 对于抽象基类，参见 *note abc: 4. 模块和 PEP 3119(5)。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0342

   (2) https://www.python.org/dev/peps/pep-0525

   (3) https://www.python.org/dev/peps/pep-0492

   (4) https://code.activestate.com/recipes/576694/

   (5) https://www.python.org/dev/peps/pep-3119


File: python.info,  Node: heapq --- 堆队列算法,  Next: bisect --- 数组二分查找算法,  Prev: collections abc --- 容器的抽象基类,  Up: 数据类型

5.8.5 ‘heapq’ — 堆队列算法
--------------------------

`源码：'Lib/heapq.py(1)

__________________________________________________________________

这个模块提供了堆队列算法的实现，也称为优先队列算法。

堆是一个二叉树，它的每个父节点的值都只会小于或等于所有孩子节点（的值）。
它使用了数组来实现：从零开始计数，对于所有的 `k' ，都有 ‘heap[k] <=
heap[2*k+1]’ 和 ‘heap[k] <= heap[2*k+2]’。 为了便于比较，不存在的元素被
认为是无限大。 堆最有趣的特性在于最小的元素总是在根结点：‘heap[0]’。

这个API与教材的堆算法实现有所不同，具体区别有两方面：（a）我们使用了从零
开始的索引。这使得节点和其孩子节点索引之间的关系不太直观但更加适合，因为
Python 使用从零开始的索引。 （b）我们的 pop 方法返回最小的项而不是最大的
项（这在教材中称为“最小堆”；而“最大堆”在教材中更为常见，因为它更适用于原
地排序）。

基于这两方面，把堆看作原生的Python list也没什么奇怪的： ‘heap[0]’ 表示最
小的元素，同时 ‘heap.sort()’ 维护了堆的不变性！

要创建一个堆，可以使用list来初始化为 ‘[]’ ，或者你可以通过一个函数 *note
heapify(): 196e. ，来把一个list转换成堆。

定义了以下函数：

 -- 函数: heapq.heappush (heap, item)

     将 `item' 的值加入 `heap' 中，保持堆的不变性。

 -- 函数: heapq.heappop (heap)

     弹出并返回 `heap' 的最小的元素，保持堆的不变性。如果堆为空，抛出
     *note IndexError: e7d. 。使用 ‘heap[0]’ ，可以只访问最小的元素而不
     弹出它。

 -- 函数: heapq.heappushpop (heap, item)

     将 `item' 放入堆中，然后弹出并返回 `heap' 的最小元素。该组合操作比
     先调用 *note heappush(): 196f. 再调用 *note heappop(): 1970. 运行起
     来更有效率。

 -- 函数: heapq.heapify (x)

     将list `x' 转换成堆，原地，线性时间内。

 -- 函数: heapq.heapreplace (heap, item)

     弹出并返回 `heap' 中最小的一项，同时推入新的 `item'。 堆的大小不变
     。 如果堆为空则引发 *note IndexError: e7d.。

     这个单步骤操作比 *note heappop(): 1970. 加 *note heappush(): 196f.
     更高效，并且在使用固定大小的堆时更为适宜。 pop/push 组合总是会从堆
     中返回一个元素并将其替换为 `item'。

     返回的值可能会比添加的 `item' 更大。 如果不希望如此，可考虑改用
     *note heappushpop(): 1971.。 它的 push/pop 组合会返回两个值中较小的
     一个，将较大的值留在堆中。

该模块还提供了三个基于堆的通用功能函数。

 -- 函数: heapq.merge (*iterables, key=None, reverse=False)

     将多个已排序的输入合并为一个已排序的输出（例如，合并来自多个日志文
     件的带时间戳的条目）。 返回已排序值的 *note iterator: 104b.。

     类似于 ‘sorted(itertools.chain(*iterables))’ 但返回一个可迭代对象，
     不会一次性地将数据全部放入内存，并假定每个输入流都是已排序的（从小
     到大）。

     具有两个可选参数，它们都必须指定为关键字参数。

     `key' 指定带有单个参数的 *note key function: 6e9.，用于从每个输入元
     素中提取比较键。 默认值为 ‘None’ (直接比较元素)。

     `reverse' 为一个布尔值。 如果设为 ‘True’，则输入元素将按比较结果逆
     序进行合并。 要达成与 ‘sorted(itertools.chain(*iterables),
     reverse=True)’ 类似的行为，所有可迭代对象必须是已从大到小排序的。

     在 3.5 版更改: 添加了可选的 `key' 和 `reverse' 形参。

 -- 函数: heapq.nlargest (n, iterable, key=None)

     从 `iterable' 所定义的数据集中返回前 `n' 个最大元素组成的列表。 如
     果提供了 `key' 则其应指定一个单参数的函数，用于从 `iterable' 的每个
     元素中提取比较键 (例如 ‘key=str.lower’)。 等价于: ‘sorted(iterable,
     key=key, reverse=True)[:n]’。

 -- 函数: heapq.nsmallest (n, iterable, key=None)

     从 `iterable' 所定义的数据集中返回前 `n' 个最小元素组成的列表。 如
     果提供了 `key' 则其应指定一个单参数的函数，用于从 `iterable' 的每个
     元素中提取比较键 (例如 ‘key=str.lower’)。 等价于: ‘sorted(iterable,
     key=key)[:n]’。

后两个函数在 `n' 值较小时性能最好。 对于更大的值，使用 *note sorted():
44c. 函数会更有效率。 此外，当 ‘n==1’ 时，使用内置的 *note min(): 812. 和
*note max(): 813. 函数会更有效率。 如果需要重复使用这些函数，请考虑将可
迭代对象转为真正的堆。

* Menu:

* 基本示例::
* 优先队列实现说明::
* 理论::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/heapq.py


File: python.info,  Node: 基本示例,  Next: 优先队列实现说明,  Up: heapq --- 堆队列算法

5.8.5.1 基本示例
................

堆排序(1) 可以通过将所有值推入堆中然后每次弹出一个最小值项来实现。

     >>> def heapsort(iterable):
     ...     h = []
     ...     for value in iterable:
     ...         heappush(h, value)
     ...     return [heappop(h) for i in range(len(h))]
     ...
     >>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

这类似于 ‘sorted(iterable)’，但与 *note sorted(): 44c. 不同的是这个实现
是不稳定的。

堆元素可以为元组。 这适用于将比较值（例如任务优先级）与跟踪的主记录进行
赋值的场合:

     >>> h = []
     >>> heappush(h, (5, 'write code'))
     >>> heappush(h, (7, 'release product'))
     >>> heappush(h, (1, 'write spec'))
     >>> heappush(h, (3, 'create tests'))
     >>> heappop(h)
     (1, 'write spec')

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Heapsort


File: python.info,  Node: 优先队列实现说明,  Next: 理论,  Prev: 基本示例,  Up: heapq --- 堆队列算法

5.8.5.2 优先队列实现说明
........................

优先队列(1) 是堆的常用场合，并且它的实现包含了多个挑战：

   * 排序稳定性：你该如何令相同优先级的两个任务按它们最初被加入时的顺序
     返回？

   * 如果优先级相同且任务没有默认比较顺序，则 (priority, task) 对的元组
     比较将会中断。

   * 如果任务优先级发生改变，你该如何将其移至堆中的新位置？

   * 或者如果一个挂起的任务需要被删除，你该如何找到它并将其移出队列？

针对前两项挑战的一种解决方案是将条目保存为包含优先级、条目计数和任务对象
3 个元素的列表。 条目计数可用来打破平局，这样具有相同优先级的任务将按它
们的添加顺序返回。 并且由于没有哪两个条目计数是相同的，元组比较将永远不
会直接比较两个任务。

不可比较任务问题的另一种解决方案是创建一个忽略任务条目并且只比较优先级字
段的包装器类:

     from dataclasses import dataclass, field
     from typing import Any

     @dataclass(order=True)
     class PrioritizedItem:
         priority: int
         item: Any=field(compare=False)

其余的挑战主要包括找到挂起的任务并修改其优先级或将其完全移除。 找到一个
任务可使用一个指向队列中条目的字典来实现。

移除条目或改变其优先级的操作实现起来更为困难，因为它会破坏堆结构不变量。
因此，一种可能的解决方案是将条目标记为已移除，再添加一个改变了优先级的新
条目:

     pq = []                         # list of entries arranged in a heap
     entry_finder = {}               # mapping of tasks to entries
     REMOVED = '<removed-task>'      # placeholder for a removed task
     counter = itertools.count()     # unique sequence count

     def add_task(task, priority=0):
         'Add a new task or update the priority of an existing task'
         if task in entry_finder:
             remove_task(task)
         count = next(counter)
         entry = [priority, count, task]
         entry_finder[task] = entry
         heappush(pq, entry)

     def remove_task(task):
         'Mark an existing task as REMOVED.  Raise KeyError if not found.'
         entry = entry_finder.pop(task)
         entry[-1] = REMOVED

     def pop_task():
         'Remove and return the lowest priority task. Raise KeyError if empty.'
         while pq:
             priority, count, task = heappop(pq)
             if task is not REMOVED:
                 del entry_finder[task]
                 return task
         raise KeyError('pop from an empty priority queue')

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Priority_queue


File: python.info,  Node: 理论,  Prev: 优先队列实现说明,  Up: heapq --- 堆队列算法

5.8.5.3 理论
............

堆是通过数组来实现的，其中的元素从 0 开始计数，对于所有的 `k' 都有 ‘a[k]
<= a[2*k+1]’ 且 ‘a[k] <= a[2*k+2]’。 为了便于比较，不存在的元素被视为无
穷大。 堆最有趣的特性在于 ‘a[0]’ 总是其中最小的元素。

上面的特殊不变量是用来作为一场锦标赛的高效内存表示。 下面的数字是 `k' 而
不是 ‘a[k]’:

                                    0

                   1                                 2

           3               4                5               6

       7       8       9       10      11      12      13      14

     15 16   17 18   19 20   21 22   23 24   25 26   27 28   29 30

在上面的树中，每个 `k' 单元都位于 ‘2*k+1’ 和 ‘2*k+2’ 之上。 体育运动中我
们经常见到二元锦标赛模式，每个胜者单元都位于另两个单元之上，并且我们可以
沿着树形图向下追溯胜者所遇到的所有对手。 但是，在许多采用这种锦标赛模式
的计算机应用程序中，我们并不需要追溯胜者的历史。 为了获得更高的内存利用
效率，当一个胜者晋级时，我们会用较低层级的另一条目来替代它，因此规则变为
一个单元和它之下的两个单元包含三个不同条目，上方单元“胜过”了两个下方单元
。

如果此堆的不变量始终受到保护，则序号 0 显然是最后的赢家。 删除它并找出
“下一个”赢家的最简单算法方式是家某个输家（让我们假定是上图中的 30 号单元
）移至 0 号位置，然后将这个新的 0 号沿树下行，不断进行值的交换，直到不变
量重新建立。 这显然会是树中条目总数的对数。 通过迭代所有条目，你将得到一
个 O(n log n) 复杂度的排序。

此排序有一个很好的特性就是你可以在排序进行期间高效地插入新条目，前提是插
入的条目不比你最近取出的 0 号元素“更好”。 这在模拟上下文时特别有用，在这
种情况下树保存的是所有传入事件，“胜出”条件是最小调度时间。 当一个事件将
其他事件排入执行计划时，它们的调试时间向未来方向延长，这样它们可方便地入
堆。 因此，堆结构很适宜用来实现调度器，我的 MIDI 音序器就是用的这个 :-)。

用于实现调度器的各种结构都得到了充分的研究，堆是非常适宜的一种，因为它们
的速度相当快，并且几乎是恒定的，最坏的情况与平均情况没有太大差别。 虽然
还存在其他总体而言更高效的实现方式，但其最坏的情况却可能非常糟糕。

堆在大磁盘排序中也非常有用。 你应该已经了解大规模排序会有多个“运行轮次
”（即预排序的序列，其大小通常与 CPU 内存容量相关），随后这些轮次会进入合
并通道，轮次合并的组织往往非常巧妙 (1)。 非常重要的一点是初始排序应产生
尽可能长的运行轮次。 锦标赛模式是达成此目标的好办法。 如果你使用全部有用
内存来进行锦标赛，替换和安排恰好适合当前运行轮次的条目，你将可以对于随机
输入生成两倍于内存大小的运行轮次，对于模糊排序的输入还会有更好的效果。

另外，如果你输出磁盘上的第 0 个条目并获得一个可能不适合当前锦标赛的输入
（因为其值要“胜过”上一个输出值），它无法被放入堆中，因此堆的尺寸将缩小。
被释放的内存可以被巧妙地立即重用以逐步构建第二个堆，其增长速度与第一个堆
的缩减速度正好相同。 当第一个堆完全消失时，你可以切换新堆并启动新的运行
轮次。 这样做既聪明又高效！

总之，堆是值得了解的有用内存结构。 我在一些应用中用到了它们，并且认为保
留一个 ’heap’ 模块是很有意义的。 :-)

备注
....

   ---------- Footnotes ----------

   (1) (1) 当前时代的磁盘平衡算法与其说是巧妙，不如说是麻烦，这是由磁盘
的寻址能力导致的结果。 在无法寻址的设备例如大型磁带机上，情况则相当不同
，开发者必须非常聪明地（极为提前地）确保每次磁带转动都尽可能地高效（就是
说能够最好地加入到合并“进程”中）。 有些磁带甚至能够反向读取，这也被用来
避免倒带的耗时。 请相信我，真正优秀的磁带机排序看起来是极其壮观的，排序
从来都是一门伟大的艺术！ :-)


File: python.info,  Node: bisect --- 数组二分查找算法,  Next: array --- 高效的数值数组,  Prev: heapq --- 堆队列算法,  Up: 数据类型

5.8.6 ‘bisect’ — 数组二分查找算法
---------------------------------

`源代码：' Lib/bisect.py(1)

__________________________________________________________________

这个模块对有序列表提供了支持，使得他们可以在插入新数据仍然保持有序。对于
长列表，如果其包含元素的比较操作十分昂贵的话，这可以是对更常见方法的改进
。这个模块叫做 *note bisect: 12. 因为其使用了基本的二分（bisection）算法
。源代码也可以作为很棒的算法示例（边界判断也做好啦！）

定义了以下函数：

 -- 函数: bisect.bisect_left (a, x, lo=0, hi=len(a))

     在 `a' 中找到 `x' 合适的插入点以维持有序。参数 `lo' 和 `hi' 可以被
     用于确定需要考虑的子集；默认情况下整个列表都会被使用。如果 `x' 已经
     在 `a' 里存在，那么插入点会在已存在元素之前（也就是左边）。如果 `a'
     是列表（list）的话，返回值是可以被放在 ‘list.insert()’ 的第一个参数
     的。

     返回的插入点 `i' 可以将数组 `a' 分成两部分。左侧是 ‘all(val < x for
     val in a[lo:i])’ ，右侧是 ‘all(val >= x for val in a[i:hi])’ 。

 -- 函数: bisect.bisect_right (a, x, lo=0, hi=len(a))
 -- 函数: bisect.bisect (a, x, lo=0, hi=len(a))

     类似于 *note bisect_left(): 197a.，但是返回的插入点是 `a' 中已存在
     元素 `x' 的右侧。

     返回的插入点 `i' 可以将数组 `a' 分成两部分。左侧是 ‘all(val <= x
     for val in a[lo:i])’，右侧是 ‘all(val > x for val in a[i:hi])’ for
     the right side。

 -- 函数: bisect.insort_left (a, x, lo=0, hi=len(a))

     将 `x' 插入到一个有序序列 `a' 里，并维持其有序。如果 `a' 有序的话，
     这相当于 ‘a.insert(bisect.bisect_left(a, x, lo, hi), x)’。要注意搜
     索是 O(log n) 的，插入却是 O(n) 的。

 -- 函数: bisect.insort_right (a, x, lo=0, hi=len(a))
 -- 函数: bisect.insort (a, x, lo=0, hi=len(a))

     类似于 *note insort_left(): 197d.，但是把 `x' 插入到 `a' 中已存在元
     素 `x' 的右侧。

参见
....

SortedCollection recipe(2) 使用 bisect 构造了一个功能完整的集合类，提供
了直接的搜索方法和对用于搜索的 key 方法的支持。所有用于搜索的键都是预先
计算的，以避免在搜索时对 key 方法的不必要调用。

* Menu:

* 搜索有序列表::
* 其他示例::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/bisect.py

   (2) https://code.activestate.com/recipes/577197-sortedcollection/


File: python.info,  Node: 搜索有序列表,  Next: 其他示例,  Up: bisect --- 数组二分查找算法

5.8.6.1 搜索有序列表
....................

上面的 *note bisect(): 12. 函数对于找到插入点是有用的，但在一般的搜索任
务中可能会有点尴尬。下面 5 个函数展示了如何将其转变成有序列表中的标准查
找函数

     def index(a, x):
         'Locate the leftmost value exactly equal to x'
         i = bisect_left(a, x)
         if i != len(a) and a[i] == x:
             return i
         raise ValueError

     def find_lt(a, x):
         'Find rightmost value less than x'
         i = bisect_left(a, x)
         if i:
             return a[i-1]
         raise ValueError

     def find_le(a, x):
         'Find rightmost value less than or equal to x'
         i = bisect_right(a, x)
         if i:
             return a[i-1]
         raise ValueError

     def find_gt(a, x):
         'Find leftmost value greater than x'
         i = bisect_right(a, x)
         if i != len(a):
             return a[i]
         raise ValueError

     def find_ge(a, x):
         'Find leftmost item greater than or equal to x'
         i = bisect_left(a, x)
         if i != len(a):
             return a[i]
         raise ValueError


File: python.info,  Node: 其他示例,  Prev: 搜索有序列表,  Up: bisect --- 数组二分查找算法

5.8.6.2 其他示例
................

函数 *note bisect(): 12. 还可以用于数字表查询。这个例子是使用 *note
bisect(): 12. 从一个给定的考试成绩集合里，通过一个有序数字表，查出其对应
的字母等级：90 分及以上是 ’A’，80 到 89 是 ’B’，以此类推

     >>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
     ...     i = bisect(breakpoints, score)
     ...     return grades[i]
     ...
     >>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
     ['F', 'A', 'C', 'C', 'B', 'A', 'A']

与 *note sorted(): 44c. 函数不同，对于 *note bisect(): 12. 函数来说，
`key' 或者 `reversed' 参数并没有什么意义。因为这会导致设计效率低下（连续
调用 bisect 函数时，是不会 "记住" 过去查找过的键的）。

正相反，最好去搜索预先计算好的键列表，来查找相关记录的索引。

     >>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
     >>> data.sort(key=lambda r: r[1])
     >>> keys = [r[1] for r in data]         # precomputed list of keys
     >>> data[bisect_left(keys, 0)]
     ('black', 0)
     >>> data[bisect_left(keys, 1)]
     ('blue', 1)
     >>> data[bisect_left(keys, 5)]
     ('red', 5)
     >>> data[bisect_left(keys, 8)]
     ('yellow', 8)


File: python.info,  Node: array --- 高效的数值数组,  Next: weakref --- 弱引用,  Prev: bisect --- 数组二分查找算法,  Up: 数据类型

5.8.7 ‘array’ — 高效的数值数组
------------------------------

__________________________________________________________________

此模块定义了一种对象类型，可以紧凑地表示基本类型值的数组：字符、整数、浮
点数等。 数组属于序列类型，其行为与列表非常相似，不同之处在于其中存储的
对象类型是受限的。 类型在对象创建时使用单个字符的 `类型码' 来指定。 已定
义的类型码如下：

类型码          C 类型                   Python 类型             以字节表示的最小尺寸        注释
                                                                                             
---------------------------------------------------------------------------------------------------------
                                                                                             
‘'b'’           signed char              int                     1
                                                                 
                                                                                             
‘'B'’           unsigned char            int                     1
                                                                 
                                                                                             
‘'u'’           Py_UNICODE               Unicode 字符            2                           (1)
                                                                                             
                                                                                             
‘'h'’           signed short             int                     2
                                                                 
                                                                                             
‘'H'’           unsigned short           int                     2
                                                                 
                                                                                             
‘'i'’           signed int               int                     2
                                                                 
                                                                                             
‘'I'’           unsigned int             int                     2
                                                                 
                                                                                             
‘'l'’           signed long              int                     4
                                                                 
                                                                                             
‘'L'’           unsigned long            int                     4
                                                                 
                                                                                             
‘'q'’           signed long long         int                     8
                                                                 
                                                                                             
‘'Q'’           unsigned long long       int                     8
                                                                 
                                                                                             
‘'f'’           float                    float                   4
                                                                 
                                                                                             
‘'d'’           double                   float                   8
                                                                 

注释:

  1. ‘'u'’ 类型码对应于 Python 中已过时的 unicode 字符 (*note
     Py_UNICODE: af6. 即 ‘wchar_t’)。 根据系统平台的不同，它可能是 16 位
     或 32 位。

     ‘'u'’ 将与其它的 *note Py_UNICODE: af6. API 一起被移除。

     Deprecated since version 3.3, will be removed in version 4.0.

值的实际表示会由机器的架构决定（严格地说是由 C 实现决定）。 实际大小可通
过 ‘itemsize’ 属性来获取。

这个模块定义了以下类型：

 -- 类: array.array (typecode[, initializer])

     一个包含由 `typecode' 限制类型的条目的新数组，并由可选的
     `initializer' 值进行初始化，该值必须为一个列表、*note bytes-like
     object: 5f1. 或包含正确类型元素的可迭代对象。

     如果给定一个列表或字符串，该 initializer 会被传给新数组的 *note
     fromlist(): 1985, *note frombytes(): 1986. 或 *note fromunicode():
     1987. 方法（见下文）以将初始条目添加到数组中。 否则会将可迭代对象作
     为 initializer 传给 *note extend(): 1988. 方法。

     引发一个 *note 审计事件: ea1. ‘array.__new__’ 附带参数 ‘typecode’,
     ‘initializer’。

 -- 数据: array.typecodes

     一个包含所有可用类型码的字符串。

数组对象支持普通的序列操作如索引、切片、拼接和重复等。 当使用切片赋值时
，所赋的值必须为具有相同类型码的数组对象；所有其他情况都将引发 *note
TypeError: 193.。 数组对象也实现了缓冲区接口，可以用于所有支持 *note
字节类对象: 5f1. 的场合。

以下数据项和方法也受到支持：

 -- 属性: array.typecode

     用于创建数组的类型码字符。

 -- 属性: array.itemsize

     在内部表示中一个数组项的字节长度。

 -- 方法: array.append (x)

     添加一个值为 `x' 的新项到数组末尾。

 -- 方法: array.buffer_info ()

     返回一个元组 ‘(address, length)’ 以给出用于存放数组内容的缓冲区元素
     的当前内存地址和长度。 以字节表示的内存缓冲区大小可通过
     ‘array.buffer_info()[1] * array.itemsize’ 来计算。 这在使用需要内存
     地址的低层级（因此不够安全） I/O 接口时会很有用，例如某些 ‘ioctl()’
     操作。 只要数组存在并且没有应用改变长度的操作，返回数值就是有效的。

          注解: 当在 C 或 C++ 编写的代码中使用数组对象时（这是有效使用此
          类信息的唯一方式），使用数组对象所支持的缓冲区接口更为适宜。 此
          方法仅保留用作向下兼容，应避免在新代码中使用。 缓冲区接口的文
          档参见 *note 缓冲协议: 15f7.。

 -- 方法: array.byteswap ()

     “字节对调”所有数组项。 此方法只支持大小为 1, 2, 4 或 8 字节的值；对
     于其他值类型将引发 *note RuntimeError: 2bb.。 它适用于从不同字节序
     机器所生成的文件中读取数据的情况。

 -- 方法: array.count (x)

     返回 `x' 在数组中的出现次数。

 -- 方法: array.extend (iterable)

     将来自 `iterable' 的项添加到数组末尾。 如果 `iterable' 是另一个数组
     ，它必须具有 `完全' 相同的类型码；否则将引发 *note TypeError: 193.。
     如果 `iterable' 不是一个数组，则它必须为可迭代对象并且其元素必须为
     可添加到数组的适当类型。

 -- 方法: array.frombytes (s)

     添加来自字符串的项，将字符串解读为机器值的数组（相当于使用 *note
     fromfile(): 1990. 方法从文件中读取数据）。

     3.2 新版功能: *note fromstring(): 1991. 重命名为 *note frombytes():
     1986. 以使其含义更清晰。

 -- 方法: array.fromfile (f, n)

     从 *note file object: b4a. `f' 中读取 `n' 项并将它们添加到数组末尾
     。 如果可用数据少于 `n' 项，则会引发 *note EOFError: c74.，但可用的
     项仍然会被插入数组。

 -- 方法: array.fromlist (list)

     添加来自 list 的项。 这等价于 ‘for x in list: a.append(x)’，区别在
     于如果发生类型错误，数组将不会被改变。

 -- 方法: array.fromstring ()

     *note frombytes(): 1986. 的已弃用别名。

     Deprecated since version 3.2, will be removed in version 3.9.

 -- 方法: array.fromunicode (s)

     使用来自给定 Unicode 字符串的数组扩展数组。 数组必须是类型为 ‘'u'’
     的数组；否则将引发 *note ValueError: 1fc.。 请使用
     ‘array.frombytes(unicodestring.encode(enc))’ 来将 Unicode 数据添加
     到其他类型的数组。

 -- 方法: array.index (x)

     返回最小的 `i' 使得 `i' 为 `x' 在数组中首次出现的序号。

 -- 方法: array.insert (i, x)

     将值 `x' 作为新项插入数组的 `i' 位置之前。 负值将被视为相对于数组末
     尾的位置。

 -- 方法: array.pop ([i])

     从数组中移除序号为 `i' 的项并将其返回。 可选参数值默认为 ‘-1’，因此
     默认将移除并返回末尾项。

 -- 方法: array.remove (x)

     从数组中移除首次出现的 `x'。

 -- 方法: array.reverse ()

     反转数组中各项的顺序。

 -- 方法: array.tobytes ()

     将数组转换为一个机器值数组并返回其字节表示（即相当与通过 *note
     tofile(): 1997. 方法写入到文件的字节序列。）

     3.2 新版功能: *note tostring(): 1998. 被重命名为 *note tobytes():
     1996. 以使其含义更清晰。

 -- 方法: array.tofile (f)

     将所有项（作为机器值）写入到 *note file object: b4a. `f'。

 -- 方法: array.tolist ()

     将数组转换为包含相同项的普通列表。

 -- 方法: array.tostring ()

     *note tobytes(): 1996. 的已弃用别名。

     Deprecated since version 3.2, will be removed in version 3.9.

 -- 方法: array.tounicode ()

     将数组转换为一个 Unicode 字符串。 数组必须是类型为 ‘'u'’ 的数组；否
     则将引发 *note ValueError: 1fc.。 请使用
     ‘array.tobytes().decode(enc)’ 来从其他类型的数组生成 Unicode 字符串
     。

当一个数组对象被打印或转换为字符串时，它会表示为 ‘array(typecode,
initializer)’。 如果数组为空则 `initializer' 会被省略，否则如果
`typecode' 为 ‘'u'’ 则它是一个字符串，否则它是一个数字列表。 使用 *note
eval(): b98. 保证能将字符串转换回具有相同类型和值的数组，只要 *note
array: 459. 类已通过 ‘from array import array’ 被引入。 例如:

     array('l')
     array('u', 'hello \u2641')
     array('l', [1, 2, 3, 4, 5])
     array('d', [1.0, 2.0, 3.14])

参见
....

模块 *note struct: f9.

     打包和解包异构二进制数据。

模块 *note xdrlib: 133.

     打包和解包用于某些远程过程调用系统的 External Data Representation
     (XDR) 数据。

Numerical Python 文档(1)

     Numeric Python 扩展 (NumPy) 定义了另一种数组类型；请访问
     ‘http://www.numpy.org/’ 了解有关 Numerical Python 的更多信息。

   ---------- Footnotes ----------

   (1) https://docs.scipy.org/doc/


File: python.info,  Node: weakref --- 弱引用,  Next: types --- 动态类型创建和内置类型名称,  Prev: array --- 高效的数值数组,  Up: 数据类型

5.8.8 ‘weakref’ — 弱引用
------------------------

`源码：' Lib/weakref.py(1)

__________________________________________________________________

*note weakref: 129. 模块允许Python程序员创建对象的 `weak references' 。

在下文中，术语 `referent' 表示由弱引用引用的对象。

对对象的弱引用不能保证对象存活：当对像的引用只剩弱引用时， *note garbage
collection: ed8. 可以销毁引用并将其内存重用于其他内容。但是，在实际销毁
对象之前，即使没有强引用，弱引用也一直能返回该对象。

弱引用的主要用途是实现保存大对象的高速缓存或映射，但又不希望大对象仅仅因
为它出现在高速缓存或映射中而保持存活。

例如，如果您有许多大型二进制图像对象，则可能希望将名称与每个对象关联起来
。如果您使用Python字典将名称映射到图像，或将图像映射到名称，则图像对象将
保持活动状态，因为它们在字典中显示为值或键。 *note weakref: 129. 模块提
供的 *note WeakKeyDictionary: 199d. 和 *note WeakValueDictionary: 199e.
类可以替代Python字典，使用弱引用来构造映射，这些映射不会仅仅因为它们出现
在映射对象中而使对象保持存活。例如，如果一个图像对象是 *note
WeakValueDictionary: 199e. 中的值，那么当对该图像对象的剩余引用是弱映射
对象所持有的弱引用时，垃圾回收可以回收该对象并将其在弱映射对象中相应的条
目删除。

*note WeakKeyDictionary: 199d. 和 *note WeakValueDictionary: 199e. 在它
们的实现中使用弱引用，在弱引用上设置回调函数，当键或值被垃圾回收回收时通
知弱字典。 *note WeakSet: cc0. 实现了 *note set: b77. 接口，但像 *note
WeakKeyDictionary: 199d. 一样，只持有其元素的弱引用。

*note finalize: 29e. 提供了注册一个对象被垃圾收集时要调用的清理函数的方
式。这比在原始弱引用上设置回调函数更简单，因为模块会自动确保对象被回收前
终结器一直保持存活。

这些弱容器类型之一或者 *note finalize: 29e. 就是大多数程序所需要的 - 通
常不需要直接创建自己的弱引用。*note weakref: 129. 模块暴露了低级机制，以
便于高级用途。

并非所有对象都可以被弱引用；可以被弱引用的对象包括类实例，用 Python（而
不是用 C）编写的函数，实例方法、集合、冻结集合，某些 *note 文件对象:
b4a.，*note 生成器: 9aa.，类型对象，套接字，数组，双端队列，正则表达式模
式对象以及代码对象等。

在 3.2 版更改: 添加了对thread.lock，threading.Lock和代码对象的支持。

几个内建类型如 *note list: 263. 和 *note dict: 1b9. 不直接支持弱引用，但
可以通过子类化添加支持:

     class Dict(dict):
         pass

     obj = Dict(red=1, green=2, blue=3)   # this object is weak referenceable

`CPython implementation detail:' 其他内置类型例如 *note tuple: 486. 和
*note int: 185. 不支持弱引用，即使通过子类化也不支持。

Extension types can easily be made to support weak references; see *note
Weak Reference Support: 199f.

 -- 类: weakref.ref (object[, callback])

     返回对 `对象' 的弱引用。如果原始对象仍然存活，则可以通过调用引用对
     象来检索原始对象；如果引用的原始对象不再存在，则调用引用对象将得到
     *note None: 158. 。如果提供了 `回调' 而且值不是 *note None: 158. ，
     并且返回的弱引用对象仍然存活，则在对象即将终结时将调用回调;弱引用对
     象将作为回调的唯一参数传递；指示物将不再可用。

     许多弱引用也允许针对相同对象来构建。 为每个弱引用注册的回调将按从最
     近注册的回调到最早注册的回调的顺序被调用。

     回调所引发的异常将记录于标准错误输出，但无法被传播；它们会按与对象
     的 *note __del__(): 927. 方法所引发的异常相同的方式被处理。

     如果 `object' 可哈希，则弱引用也为 *note hashable: 1439.。 即使在
     `object' 被删除之后它们仍将保持其哈希值。 如果 *note hash(): 9cc. 在
     `object' 被删除之后才首次被调用，则该调用将引发 *note TypeError:
     193.。

     弱引用支持相等检测，但不支持排序比较。 如果被引用对象仍然存在，两个
     引用具有与它们的被引用对象一致的相等关系（无论 `callback' 是否相同
     ）。 如果删除了任一被引用对象，则仅在两个引用对象为同一对象时两者才
     相等。

     这是一个可子类化的类型而非一个工厂函数。

      -- 属性: __callback__

          这个只读属性会返回当前关联到弱引用的回调。 如果回调不存在或弱
          引用的被引用对象已不存在，则此属性的值为 ‘None’。

     在 3.4 版更改: 添加了 *note __callback__: 919. 属性。

 -- 函数: weakref.proxy (object[, callback])

     返回 `object' 的一个使用弱引用的代理。 此函数支持在大多数上下文中使
     用代理，而不要求显式地对所使用的弱引用对象解除引用。 返回的对象类型
     将为 ‘ProxyType’ 或 ‘CallableProxyType’，具体取决于 `object' 是否可
     调用。 Proxy 对象不是 *note hashable: 1439. 对象，无论被引用对象是
     否可哈希；这可避免与它们的基本可变性质相关的多种问题，并可防止它们
     被用作字典键。 `callback' 与 *note ref(): 918. 函数的同名形参含义相
     同。

     在 3.8 版更改: 扩展代理对象所支持的运算符，包括矩阵乘法运算符 ‘@’ 和
     ‘@=’。

 -- 函数: weakref.getweakrefcount (object)

     返回指向 `object' 的弱引用和代理的数量。

 -- 函数: weakref.getweakrefs (object)

     返回由指向 `object' 的所有弱引用和代理构成的列表。

 -- 类: weakref.WeakKeyDictionary ([dict])

     弱引用键的映射类。 当不再有对键的强引用时字典中的条目将被丢弃。 这
     可被用来将额外数据关联到一个应用中其他部分所拥有的对象而无需在那些
     对象中添加属性。 这对于重载了属性访问的对象来说特别有用。

*note WeakKeyDictionary: 199d. 对象具有一个额外方法可以直接公开内部引用
。 这些引用不保证在它们被使用时仍然保持“存活”，因此这些引用的调用结果需
要在使用前进行检测。 此方法可用于避免创建会导致垃圾回收器将保留键超出实
际需要时长的引用。

 -- 方法: WeakKeyDictionary.keyrefs ()

     返回包含对键的弱引用的可迭代对象。

 -- 类: weakref.WeakValueDictionary ([dict])

     弱引用值的映射类。 当不再有对键的强引用时字典中的条目将被丢弃。

*note WeakValueDictionary: 199e. 对象具有一个额外方法，此方法存在与
*note WeakKeyDictionary: 199d. 对象的 ‘keyrefs()’ 方法相同的问题。

 -- 方法: WeakValueDictionary.valuerefs ()

     返回包含对值的弱引用的可迭代对象。

 -- 类: weakref.WeakSet ([elements])

     保持对其元素弱引用的集合类。 当不再有对某个元素的强引用时元素将被丢
     弃。

 -- 类: weakref.WeakMethod (method)

     一个模拟对绑定方法（即在类中定义并在实例中查找的方法）进行弱引用的
     自定义 *note ref: 918. 子类。 由于绑定方法是临时性的，标准弱引用无
     法保持它。 *note WeakMethod: 917. 包含特别代码用来重新创建绑定方法
     ，直到对象或初始函数被销毁:

          >>> class C:
          ...     def method(self):
          ...         print("method called!")
          ...
          >>> c = C()
          >>> r = weakref.ref(c.method)
          >>> r()
          >>> r = weakref.WeakMethod(c.method)
          >>> r()
          <bound method C.method of <__main__.C object at 0x7fc859830220>>
          >>> r()()
          method called!
          >>> del c
          >>> gc.collect()
          0
          >>> r()
          >>>

     3.4 新版功能.

 -- 类: weakref.finalize (obj, func, *args, **kwargs)

     返回一个可调用的终结器对象，该对象将在 `obj' 作为垃圾回收时被调用。
     与普通的弱引用不同，终结器将总是存活，直到引用对象被回收，这极大地
     简化了生存期管理。

     终结器总是被视为 `存活' 直到它被调用（显式调用或在垃圾回收时隐式调
     用），调用之后它将 `死亡'。 调用存活的终结器将返回 ‘func(*arg,
     **kwargs)’ 的求值结果，而调用死亡的终结器将返回 *note None: 158.。

     在垃圾收集期间由终结器回调所引发异常将显示于标准错误输出，但无法被
     传播。 它们会按与对象的 *note __del__(): 927. 方法或弱引用的回调所
     引发异常相同的方式被处理。

     当程序退出时，剩余的存活终结器会被调用，除非它们的 *note atexit: c.
     属性已被设为假值。 它们会按与创建时相反的顺序被调用。

     终结器在 *note interpreter shutdown: 76c. 的后期绝不会发起调用其回
     调函数，此时模块全局变量很可能已被替换为 *note None: 158.。

      -- 方法: __call__ ()

          如果 `self' 为存活状态则将其标记为已死亡，并返回调用
          ‘func(*args, **kwargs)’ 的结果。 如果 `self' 已死亡则返回
          *note None: 158.。

      -- 方法: detach ()

          如果 `self' 为存活状态则将其标记为已死亡，并返回元组 ‘(obj,
          func, args, kwargs)’。 如果 `self' 已死亡则返 *note None:
          158.。

      -- 方法: peek ()

          如果 `self' 为存活状态则返回元组 ‘(obj, func, args, kwargs)’。
          如果 `self' 已死亡则返回 *note None: 158.。

      -- 属性: alive

          如果终结器为存活状态则该特征属性为真值，否则为假值。

      -- 属性: atexit

          一个可写的布尔型特征属性，默认为真值。 当程序退出时，它会调用
          所有 *note atexit: 19a8. 为真值的剩余存活终结器。 它们会按与创
          建时相反的顺序被调用。

          注解: 很重要的一点是确保 `func', `args' 和 `kwargs' 不拥有任何
          对 `obj' 的引用，无论是直接的或是间接的，否则的话 `obj' 将永远
          不会被作为垃圾回收。 特别地，`func' 不应当是 `obj' 的一个绑定
          方法。

     3.4 新版功能.

 -- 数据: weakref.ReferenceType

     弱引用对象的类型对象。

 -- 数据: weakref.ProxyType

     不可调用对象的代理的类型对象。

 -- 数据: weakref.CallableProxyType

     可调用对象的代理的类型对象。

 -- 数据: weakref.ProxyTypes

     包含所有代理的类型对象的序列。 这可以用于更方便地检测一个对象是否是
     代理，而不必依赖于两种代理对象的名称。

参见
....

PEP 205(2) - 弱引用

     此特性的提议和理由，包括早期实现的链接和其他语言中类似特性的相关信
     息。

* Menu:

* 弱引用对象::
* 示例: 示例<2>.
* 终结器对象::
* 比较终结器与 __del__() 方法: 比较终结器与 __del__ 方法.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/weakref.py

   (2) https://www.python.org/dev/peps/pep-0205


File: python.info,  Node: 弱引用对象,  Next: 示例<2>,  Up: weakref --- 弱引用

5.8.8.1 弱引用对象
..................

弱引用对象没有 *note ref.__callback__: 919. 以外的方法和属性。 一个弱引
用对象如果存在，就允许通过调用它来获取引用:

     >>> import weakref
     >>> class Object:
     ...     pass
     ...
     >>> o = Object()
     >>> r = weakref.ref(o)
     >>> o2 = r()
     >>> o is o2
     True

如果引用已不存在，则调用引用对象将返回 *note None: 158.:

     >>> del o, o2
     >>> print(r())
     None

检测一个弱引用对象是否仍然存在应该使用表达式 ‘ref() is not None’。 通常
，需要使用引用对象的应用代码应当遵循这样的模式:

     # r is a weak reference object
     o = r()
     if o is None:
         # referent has been garbage collected
         print("Object has been deallocated; can't frobnicate.")
     else:
         print("Object is still live!")
         o.do_something_useful()

使用单独的“存活”测试会在多线程应用中制造竞争条件；其他线程可能导致某个弱
引用在该弱引用被调用前就失效；上述的写法在多线程应用和单线程应用中都是安
全的。

特别版本的 *note ref: 918. 对象可以通过子类化来创建。 在 *note
WeakValueDictionary: 199e. 的实现中就使用了这种方式来减少映射中每个条目
的内存开销。 这对于将附加信息关联到引用的情况最为适用，但也可以被用于在
调用中插入额外处理来提取引用。

这个例子演示了如何将 *note ref: 918. 的一个子类用于存储有关对象的附加信
息并在引用被访问时影响其所返回的值:

     import weakref

     class ExtendedRef(weakref.ref):
         def __init__(self, ob, callback=None, /, **annotations):
             super().__init__(ob, callback)
             self.__counter = 0
             for k, v in annotations.items():
                 setattr(self, k, v)

         def __call__(self):
             """Return a pair containing the referent and the number of
             times the reference has been called.
             """
             ob = super().__call__()
             if ob is not None:
                 self.__counter += 1
                 ob = (ob, self.__counter)
             return ob


File: python.info,  Node: 示例<2>,  Next: 终结器对象,  Prev: 弱引用对象,  Up: weakref --- 弱引用

5.8.8.2 示例
............

这个简单的例子演示了一个应用如何使用对象 ID 来提取之前出现过的对象。 然
后对象的 ID 可以在其它数据结构中使用，而无须强制对象保持存活，但处于存活
状态的对象也仍然可以通过 ID 来提取。

     import weakref

     _id2obj_dict = weakref.WeakValueDictionary()

     def remember(obj):
         oid = id(obj)
         _id2obj_dict[oid] = obj
         return oid

     def id2obj(oid):
         return _id2obj_dict[oid]


File: python.info,  Node: 终结器对象,  Next: 比较终结器与 __del__ 方法,  Prev: 示例<2>,  Up: weakref --- 弱引用

5.8.8.3 终结器对象
..................

使用 *note finalize: 29e. 的主要好处在于它能更简便地注册回调函数，而无须
保留所返回的终结器对象。 例如

     >>> import weakref
     >>> class Object:
     ...     pass
     ...
     >>> kenny = Object()
     >>> weakref.finalize(kenny, print, "You killed Kenny!")
     <finalize object at ...; for 'Object' at ...>
     >>> del kenny
     You killed Kenny!

终结器也可以被直接调用。 但是终结器最多只能对回调函数发起一次调用。

     >>> def callback(x, y, z):
     ...     print("CALLBACK")
     ...     return x + y + z
     ...
     >>> obj = Object()
     >>> f = weakref.finalize(obj, callback, 1, 2, z=3)
     >>> assert f.alive
     >>> assert f() == 6
     CALLBACK
     >>> assert not f.alive
     >>> f()                     # callback not called because finalizer dead
     >>> del obj                 # callback not called because finalizer dead

你可以使用 *note detach(): 19a5. 方法来注销一个终结器。 该方法将销毁终结
器并返回其被创建时传给构造器的参数。

     >>> obj = Object()
     >>> f = weakref.finalize(obj, callback, 1, 2, z=3)
     >>> f.detach()
     (<...Object object ...>, <function callback ...>, (1, 2), {'z': 3})
     >>> newobj, func, args, kwargs = _
     >>> assert not f.alive
     >>> assert newobj is obj
     >>> assert func(*args, **kwargs) == 6
     CALLBACK

除非你将 *note atexit: 19a8. 属性设为 *note False: 390.，否则终结器在程
序退出时如果仍然存活就将被调用。 例如

     >>> obj = Object()
     >>> weakref.finalize(obj, print, "obj dead or exiting")
     <finalize object at ...; for 'Object' at ...>
     >>> exit()
     obj dead or exiting


File: python.info,  Node: 比较终结器与 __del__ 方法,  Prev: 终结器对象,  Up: weakref --- 弱引用

5.8.8.4 比较终结器与 ‘__del__()’ 方法
.....................................

假设我们想创建一个类，用它的实例来代表临时目录。 当以下事件中的某一个发
生时，这个目录应当与其内容一起被删除：

   * 对象被作为垃圾回收，

   * 对象的 ‘remove()’ 方法被调用，或

   * 程序退出。

我们可以尝试使用 *note __del__(): 927. 方法来实现这个类，如下所示:

     class TempDir:
         def __init__(self):
             self.name = tempfile.mkdtemp()

         def remove(self):
             if self.name is not None:
                 shutil.rmtree(self.name)
                 self.name = None

         @property
         def removed(self):
             return self.name is None

         def __del__(self):
             self.remove()

从 Python 3.4 开始，*note __del__(): 927. 方法不会再阻止循环引用被作为垃
圾回收，并且模块全局变量在 *note interpreter shutdown: 76c. 期间不会被强
制设为 *note None: 158.。 因此这段代码在 CPython 上应该会正常运行而不会
出现任何问题。

然而，*note __del__(): 927. 方法的处理会严重地受到具体实现的影响，因为它
依赖于解释器垃圾回收实现方式的内部细节。

更健壮的替代方式可以是定义一个终结器，只引用它所需要的特定函数和对象，而
不是获取对整个对象状态的访问权:

     class TempDir:
         def __init__(self):
             self.name = tempfile.mkdtemp()
             self._finalizer = weakref.finalize(self, shutil.rmtree, self.name)

         def remove(self):
             self._finalizer()

         @property
         def removed(self):
             return not self._finalizer.alive

像这样定义后，我们的终结器将只接受一个对其完成正确清理目录任务所需细节的
引用。 如果对象一直未被作为垃圾回收，终结器仍会在退出时被调用。

基于弱引用的终结器还具有另一项优势，就是它们可被用来为定义由第三方控制的
类注册终结器，例如当一个模块被卸载时运行特定代码:

     import weakref, sys
     def unloading_module():
         # implicit reference to the module globals from the function body
     weakref.finalize(sys.modules[__name__], unloading_module)

     注解: 如果当程序退出时你恰好在守护线程中创建终结器对象，则有可能该
     终结器不会在退出时被调用。 但是，在一个守护线程中 *note
     atexit.register(): e8d, ‘try: ... finally: ...’ 和 ‘with: ...’ 同样
     不能保证执行清理。


File: python.info,  Node: types --- 动态类型创建和内置类型名称,  Next: copy --- 浅层 shallow 和深层 deep 复制操作,  Prev: weakref --- 弱引用,  Up: 数据类型

5.8.9 ‘types’ — 动态类型创建和内置类型名称
------------------------------------------

`源代码:' Lib/types.py(1)

__________________________________________________________________

此模块定义了一些工具函数，用于协助动态创建新的类型。

它还为某些对象类型定义了名称，这些名称由标准 Python 解释器所使用，但并不
像内置的 *note int: 185. 或 *note str: 339. 那样对外公开。

最后，它还额外提供了一些类型相关但重要程度不足以作为内置对象的工具类和函
数。

* Menu:

* 动态类型创建::
* 标准解释器类型::
* 附加工具类和函数::
* 协程工具函数::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/types.py


File: python.info,  Node: 动态类型创建,  Next: 标准解释器类型,  Up: types --- 动态类型创建和内置类型名称

5.8.9.1 动态类型创建
....................

 -- 函数: types.new_class (name, bases=(), kwds=None, exec_body=None)

     使用适当的元类动态地创建一个类对象。

     前三个参数是组成类定义头的部件：类名称，基类 (有序排列)，关键字参数
     (例如 ‘metaclass’)。

     `exec_body' 参数是一个回调函数，用于填充新创建类的命名空间。 它应当
     接受类命名空间作为其唯一的参数并使用类内容直接更新命名空间。 如果未
     提供回调函数，则它就等效于传入 ‘lambda ns: None’。

     3.3 新版功能.

 -- 函数: types.prepare_class (name, bases=(), kwds=None)

     计算适当的元类并创建类命名空间。

     参数是组成类定义头的部件：类名称，基类 (有序排列) 以及关键字参数 (例
     如 ‘metaclass’)。

     返回值是一个 3 元组: ‘metaclass, namespace, kwds’

     `metaclass' 是适当的元类，`namespace' 是预备好的类命名空间而 `kwds'
     是所传入 `kwds' 参数移除每个 ‘'metaclass'’ 条目后的已更新副本。 如
     果未传入 `kwds' 参数，这将为一个空字典。

     3.3 新版功能.

     在 3.6 版更改: 所返回元组中 ‘namespace’ 元素的默认值已被改变。 现在
     当元类没有 ‘__prepare__’ 方法时将会使用一个保留插入顺序的映射。

参见
....

*note 元类: 1458.

     这些函数所支持的类创建过程的完整细节

PEP 3115(1) - Python 3000 中的元类

     引入 ‘__prepare__’ 命名空间钩子

 -- 函数: types.resolve_bases (bases)

     动态地解析 MRO 条目，具体描述见 PEP 560(2)。

     此函数会在 `bases' 中查找不是 *note type: 611. 的实例的项，并返回一
     个元组，其中每个具有 ‘__mro_entries__’ 方法的此种对象对象将被替换为
     调用该方法解包后的结果。 如果一个 `bases' 项是 *note type: 611. 的
     实例，或它不具有 ‘__mro_entries__’ 方法，则它将不加改变地被包含在返
     回的元组中。

     3.7 新版功能.

参见
....

PEP 560(3) - 对 typing 模块和泛型类型的核心支持

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3115

   (2) https://www.python.org/dev/peps/pep-0560

   (3) https://www.python.org/dev/peps/pep-0560


File: python.info,  Node: 标准解释器类型,  Next: 附加工具类和函数,  Prev: 动态类型创建,  Up: types --- 动态类型创建和内置类型名称

5.8.9.2 标准解释器类型
......................

此模块为许多类型提供了实现 Python 解释器所要求的名称。 它刻意地避免了包
含某些仅在处理过程中偶然出现的类型，例如 ‘listiterator’ 类型。

此种名称的典型应用如 *note isinstance(): 457. 或 *note issubclass():
458. 检测。

如果你要实例化这些类型中的任何一种，请注意其签名在不同 Python 版本之间可
能出现变化。

以下类型有相应的标准名称定义：

 -- 数据: types.FunctionType
 -- 数据: types.LambdaType

     用户自定义函数以及由 *note lambda: c37. 表达式所创建函数的类型。

     引发一个 *note 审计事件: ea1. ‘function.__new__’，附带参数 ‘code’。

     此审计事件只会被函数对象的直接实例化引发，而不会被普通编译所引发。

 -- 数据: types.GeneratorType

     *note generator: 9aa. 迭代器对象的类型，由生成器函数创建。

 -- 数据: types.CoroutineType

     *note coroutine: 1a7. 对象的类型，由 *note async def: 285. 函数创建
     。

     3.5 新版功能.

 -- 数据: types.AsyncGeneratorType

     *note asynchronous generator: 1513. 迭代器对象的类型，由异步生成器
     函数创建。

     3.6 新版功能.

 -- 类: types.CodeType (**kwargs)

     代码对象的类型，例如 *note compile(): 1b5. 的返回值。

     引发 *note 审计事件: ea1. ‘code.__new__’ 附带参数 ‘code’,
     ‘filename’, ‘name’, ‘argcount’, ‘posonlyargcount’,
     ‘kwonlyargcount’, ‘nlocals’, ‘stacksize’, ‘flags’。

     请注意被审计的参数可能与初始化代码所要求的名称或位置不相匹配。 审计
     事件只会被代码对象的直接实例化引发，而不会被普通编译所引发。

      -- 方法: replace (**kwargs)

          返回代码对象的一个副本，使用指定的新字段值。

          3.8 新版功能.

 -- 数据: types.CellType

     单元对象的类型：这种对象被用作函数中自由变量的容器。

     3.8 新版功能.

 -- 数据: types.MethodType

     用户自定义类实例方法的类型。

 -- 数据: types.BuiltinFunctionType
 -- 数据: types.BuiltinMethodType

     内置函数例如 *note len(): 151. 或 *note sys.exit(): cea. 以及内置类
     方法的类型。 （这里所说的“内置”是指“以 C 语言编写”。）

 -- 数据: types.WrapperDescriptorType

     某些内置数据类型和基类的方法的类型，例如 *note object.__init__():
     d66. 或 *note object.__lt__(): c3c.。

     3.7 新版功能.

 -- 数据: types.MethodWrapperType

     某些内置数据类型和基类的 `绑定' 方法的类型。 例如
     ‘object().__str__’ 所属的类型。

     3.7 新版功能.

 -- 数据: types.MethodDescriptorType

     某些内置数据类型方法例如 *note str.join(): 1642. 的类型。

     3.7 新版功能.

 -- 数据: types.ClassMethodDescriptorType

     某些内置数据类型 `非绑定' 类方法例如 ‘dict.__dict__['fromkeys']’ 的
     类型。

     3.7 新版功能.

 -- 类: types.ModuleType (name, doc=None)

     *note 模块: 14bd. 的类型。 构造器接受待创建模块的名称并以其 *note
     docstring: 15c5. 作为可选参数。

          注解: 如果你希望设置各种由导入控制的属性，请使用 *note
          importlib.util.module_from_spec(): 6f9. 来创建一个新模块。

      -- 属性: __doc__

          模块的 *note docstring: 15c5.。 默认为 ‘None’。

      -- 属性: __loader__

          用于加载模块的 *note loader: 14cb.。 默认为 ‘None’。

          此属性会匹配保存在 attr:‘__spec__’ 对象中的 *note
          importlib.machinery.ModuleSpec.loader: 19c2.。

               注解: 未来的 Python 版本可能停止默认设置此属性。 为了避免
               这个潜在变化的影响，如果你明确地需要使用此属性则推荐改从
               *note __spec__: ec8. 属性读取或使用 ‘getattr(module,
               "__loader__", None)’。

          在 3.4 版更改: 默认为 ‘None’。 之前该属性为可选项。

      -- 属性: __name__

          萨芬内容名称。 应当能匹配 *note
          importlib.machinery.ModuleSpec.name: 19c4.。

      -- 属性: __package__

          一个模块所属的 *note package: ec6.。 如果模块为最高层级的（即
          不是任何特定包的组成部分）则该属性应设为 ‘''’，否则它应设为特
          定包的名称 (如果模块本身也是一个包则名称可以为 *note __name__:
          d1a.)。 默认为 ‘None’。

          此属性会匹配保存在 attr:‘__spec__’ 对象中的 *note
          importlib.machinery.ModuleSpec.parent: 19c6.。

               注解: 未来的 Python 版本可能停止默认设置此属性。 为了避免
               这个潜在变化的影响，如果你明确地需要使用此属性则推荐改从
               *note __spec__: ec8. 属性读取或使用 ‘getattr(module,
               "__package__", None)’。

          在 3.4 版更改: 默认为 ‘None’。 之前该属性为可选项。

      -- 属性: __spec__

          模块的导入系统相关状态的记录。 应当是一个 *note
          importlib.machinery.ModuleSpec: 14d6. 的实例。

          3.4 新版功能.

 -- 类: types.TracebackType (tb_next, tb_frame, tb_lasti, tb_lineno)

     回溯对象的类型，例如 ‘sys.exc_info()[2]’ 中的对象。

     请查看 *note 语言参考: 33f. 了解可用属性和操作的细节，以及动态地创
     建回溯对象的指南。

 -- 数据: types.FrameType

     帧对象的类型，例如 ‘tb.tb_frame’ 中的对象，其中 ‘tb’ 是一个回溯对象
     。

     请查看 *note 语言参考: 1442. 了解可用属性和操作的细节。

 -- 数据: types.GetSetDescriptorType

     使用 ‘PyGetSetDef’ 在扩展模块中定义的对象的类型，例如
     ‘FrameType.f_locals’ 或 ‘array.array.typecode’。 此类型被用作对象属
     性的描述器；它的目的与 *note property: 1d8. 类型相同，但专门针对在
     扩展模块中定义的类。

 -- 数据: types.MemberDescriptorType

     使用 ‘PyMemberDef’ 在扩展模块中定义的对象的类型，例如
     ‘datetime.timedelta.days’。 此类型被用作使用标准转换函数的简单 C 数
     据成员的描述器；它的目的与 *note property: 1d8. 类型相同，但专门针
     对在扩展模块中定义的类。

     `CPython implementation detail:' 在 Python 的其它实现中，此类型可能
     与 ‘GetSetDescriptorType’ 完全相同。

 -- 类: types.MappingProxyType (mapping)

     一个映射的只读代理。 它提供了对映射条目的动态视图，这意味着当映射发
     生改变时，视图会反映这些改变。

     3.3 新版功能.

      -- Describe: key in proxy

          如果下层的映射中存在键 `key' 则返回 ‘True’，否则返回 ‘False’。

      -- Describe: proxy[key]

          返回下层的映射中以 `key' 为键的项。 如果下层的映射中不存在键
          `key' 则引发 *note KeyError: 2c8.。

      -- Describe: iter(proxy)

          返回由下层映射的键为元素的迭代器。 这是 ‘iter(proxy.keys())’ 的
          快捷方式。

      -- Describe: len(proxy)

          返回下层映射中的项数。

      -- 方法: copy ()

          返回下层映射的浅拷贝。

      -- 方法: get (key[, default])

          如果 `key' 存在于下层映射中则返回 `key' 的值，否则返回
          `default'。 如果 `default' 未给出则默认为 ‘None’，因而此方法绝
          不会引发 *note KeyError: 2c8.。

      -- 方法: items ()

          返回由下层映射的项 (‘(键, 值)’ 对) 组成的一个新视图。

      -- 方法: keys ()

          返回由下层映射的键组成的一个新视图。

      -- 方法: values ()

          返回由下层映射的值组成的一个新视图。


File: python.info,  Node: 附加工具类和函数,  Next: 协程工具函数,  Prev: 标准解释器类型,  Up: types --- 动态类型创建和内置类型名称

5.8.9.3 附加工具类和函数
........................

 -- 类: types.SimpleNamespace

     一个简单的 *note object: 2b1. 子类，提供了访问其命名空间的属性，以
     及一个有意义的 repr。

     不同于 *note object: 2b1.，对于 ‘SimpleNamespace’ 你可以添加和移除
     属性。 如果一个 ‘SimpleNamespace’ 对象使用关键字参数进行初始化，这
     些参数会被直接加入下层命名空间。

     此类型大致等价于以下代码:

          class SimpleNamespace:
              def __init__(self, /, **kwargs):
                  self.__dict__.update(kwargs)

              def __repr__(self):
                  keys = sorted(self.__dict__)
                  items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
                  return "{}({})".format(type(self).__name__, ", ".join(items))

              def __eq__(self, other):
                  if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace):
                     return self.__dict__ == other.__dict__
                  return NotImplemented

     ‘SimpleNamespace’ 可被用于替代 ‘class NS: pass’。 但是，对于结构化
     记录类型则应改用 *note namedtuple(): 1b7.。

     3.3 新版功能.

 -- 函数: types.DynamicClassAttribute (fget=None, fset=None, fdel=None,
          doc=None)

     在类上访问 __getattr__ 的路由属性。

     这是一个描述器，用于定义通过实例与通过类访问时具有不同行为的属性。
     当实例访问时保持正常行为，但当类访问属性时将被路由至类的
     __getattr__ 方法；这是通过引发 AttributeError 来完成的。

     这样就允许有在实例上激活的特征属性，同时又有在类上的同名虚拟属性（
     一个这样的例子是 Enum）。

     3.4 新版功能.


File: python.info,  Node: 协程工具函数,  Prev: 附加工具类和函数,  Up: types --- 动态类型创建和内置类型名称

5.8.9.4 协程工具函数
....................

 -- 函数: types.coroutine (gen_func)

     此函数可将 *note generator: 9aa. 函数转换为返回基于生成器的协程的
     *note coroutine function: 648.。 基于生成器的协程仍然属于 *note
     generator iterator: 45f.，但同时又可被视为 *note coroutine: 1a7. 对
     象兼 *note awaitable: 521.。 不过，它没有必要实现 *note
     __await__(): 64b. 方法。

     如果 `gen_func' 是一个生成器函数，它将被原地修改。

     如果 `gen_func' 不是一个生成器函数，则它会被包装。 如果它返回一个
     *note collections.abc.Generator: 6be. 的实例，该实例将被包装在一个
     `awaitable' 代理对象中。 所有其他对象类型将被原样返回。

     3.5 新版功能.


File: python.info,  Node: copy --- 浅层 shallow 和深层 deep 复制操作,  Next: pprint --- 数据美化输出,  Prev: types --- 动态类型创建和内置类型名称,  Up: 数据类型

5.8.10 ‘copy’ — 浅层 (shallow) 和深层 (deep) 复制操作
-----------------------------------------------------

`源代码:' Lib/copy.py(1)

__________________________________________________________________

Python 中赋值语句不复制对象，而是在目标和对象之间创建绑定 (bindings) 关
系。对于自身可变或者包含可变项的集合对象，开发者有时会需要生成其副本用于
改变操作，进而避免改变原对象。本模块提供了通用的浅层复制和深层复制操作（
如下所述）。

接口摘要：

 -- 函数: copy.copy (x)

     返回 `x' 的浅层复制。

 -- 函数: copy.deepcopy (x[, memo])

     返回 `x' 的深层复制。

 -- 例外: copy.Error

     针对模块特定错误引发。
浅层复制和深层复制之间的区别仅与复合对象 (即包含其他对象的对象，如列表或
类的实例) 相关:

   * 一个 `浅层复制' 会构造一个新的复合对象，然后（在可能的范围内）将原
     对象中找到的 `引用' 插入其中。

   * 一个 `深层复制' 会构造一个新的复合对象，然后递归地将原始对象中所找
     到的对象的 `副本' 插入。

深度复制操作通常存在两个问题, 而浅层复制操作并不存在这些问题：

   * 递归对象 (直接或间接包含对自身引用的复合对象) 可能会导致递归循环。

   * 由于深层复制会复制所有内容，因此可能会过多复制（例如本应该在副本之
     间共享的数据）。

The *note deepcopy(): 3d4. function avoids these problems by:

   * 保留在当前复制过程中已复制的对象的 "备忘录" （‘memo’） 字典；以及

   * 允许用户定义的类重载复制操作或复制的组件集合。

该模块不复制模块、方法、栈追踪（stack trace）、栈帧（stack frame）、文件
、套接字、窗口、数组以及任何类似的类型。它通过不改变地返回原始对象来（浅
层或深层地）“复制”函数和类；这与 *note pickle: cb. 模块处理这类问题的方
式是相似的。

制作字典的浅层复制可以使用 *note dict.copy(): 44e. 方法，而制作列表的浅
层复制可以通过赋值整个列表的切片完成，例如，‘copied_list =
original_list[:]’。

类可以使用与控制序列化（pickling）操作相同的接口来控制复制操作，关于这些
方法的描述信息请参考 *note pickle: cb. 模块。实际上，*note copy: 26. 模
块使用的正是从 *note copyreg: 27. 模块中注册的 pickle 函数。

想要给一个类定义它自己的拷贝操作实现，可以通过定义特殊方法 ‘__copy__()’
和 ‘__deepcopy__()’。 调用前者以实现浅层拷贝操作，该方法不用传入额外参数
。 调用后者以实现深层拷贝操作；它应传入一个参数即 ‘memo’ 字典。 如果
‘__deepcopy__()’ 实现需要创建一个组件的深层拷贝，它应当调用 *note
deepcopy(): 3d4. 函数并以该组件作为第一个参数，而将 memo 字典作为第二个
参数。

参见
....

模块 *note pickle: cb.

     讨论了支持对象状态检索和恢复的特殊方法。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/copy.py


File: python.info,  Node: pprint --- 数据美化输出,  Next: reprlib --- 另一种 repr 实现,  Prev: copy --- 浅层 shallow 和深层 deep 复制操作,  Up: 数据类型

5.8.11 ‘pprint’ — 数据美化输出
------------------------------

`源代码：' Lib/pprint.py(1)

__________________________________________________________________

*note pprint: d3. 模块提供了“美化打印”任意 Python 数据结构的功能，这种美
化形式可用作对解释器的输入。 如果经格式化的结构包含非基本 Python 类型的
对象，则其美化形式可能无法被加载。 包含文件、套接字或类对象，以及许多其
他不能用 Python 字面值来表示的对象都有可能导致这样的结果。

格式化后的形式会在可能的情况下以单行来表示对象，并在无法在允许宽度内容纳
对象的情况下将其分为多行。 如果你需要调整宽度限制则应显式地构造 *note
PrettyPrinter: 89e. 对象。

字典在计算其显示形式前会先根据键来排序。

*note pprint: d3. 模块定义了一个类：

 -- 类: pprint.PrettyPrinter (indent=1, width=80, depth=None,
          stream=None, *, compact=False, sort_dicts=True)

     构造一个 *note PrettyPrinter: 89e. 实例。 此构造器接受几个关键字形
     参。 使用 `stream' 关键字可设置输出流；流对象使用的唯一方法是文件协
     议的 ‘write()’ 方法。 如果未指定此关键字，则 *note PrettyPrinter:
     89e. 会选择 ‘sys.stdout’。 每个递归层次的缩进量由 `indent' 指定；默
     认值为一。 其他值可导致输出看起来有些怪异，，但可使得嵌套结构更易区
     分。 可被打印的层级数量由 `depth' 控制；如果数据结构的层级被打印得
     过深，其所包含的下一层级会被替换为 ‘...’。 在默认情况下，对被格式化
     对象的层级深度没有限制。 希望的输出宽度可使用 `width' 形参来限制；
     默认值为 80 个字符。 如果一个结构无法在限定宽度内被格式化，则将做到
     尽可能接近。 如果 `compact' 为假值（默认）则长序列的每一项将被格式
     化为单独的行。 如果 `compact' 为真值，则将在 `width' 可容纳的的情况
     下把尽可能多的项放入每个输出行。 如果 `sort_dicts' 为真值（默认），
     字典将被格式化为按键排序，否则将按插入顺序显示。

     在 3.4 版更改: 增加了 `compact' 形参。

     在 3.8 版更改: 增加了 `sort_dicts' 形参。

          >>> import pprint
          >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
          >>> stuff.insert(0, stuff[:])
          >>> pp = pprint.PrettyPrinter(indent=4)
          >>> pp.pprint(stuff)
          [   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
              'spam',
              'eggs',
              'lumberjack',
              'knights',
              'ni']
          >>> pp = pprint.PrettyPrinter(width=41, compact=True)
          >>> pp.pprint(stuff)
          [['spam', 'eggs', 'lumberjack',
            'knights', 'ni'],
           'spam', 'eggs', 'lumberjack', 'knights',
           'ni']
          >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
          ... ('parrot', ('fresh fruit',))))))))
          >>> pp = pprint.PrettyPrinter(depth=6)
          >>> pp.pprint(tup)
          ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))

*note pprint: d3. 模块还提供了一些快捷函数：

 -- 函数: pprint.pformat (object, indent=1, width=80, depth=None, *,
          compact=False, sort_dicts=True)

     `object' 的格式化表示作为字符串返回。 `indent', `width', `depth',
     `compact' 和 `sort_dicts' 将作为格式化形参被传入 *note
     PrettyPrinter: 89e. 构造器。

     在 3.4 版更改: 增加了 `compact' 形参。

     在 3.8 版更改: 增加了 `sort_dicts' 形参。

 -- 函数: pprint.pp (object, *args, sort_dicts=False, **kwargs)

     打印 `object' 的格式化表示并附带一个换行符。 如果 `sort_dicts' 为假
     值（默认），字典将按键的插入顺序显示，否则将按字典键排序。 `args' 和
     `kwargs' 将作为格式化形参被传给 *note pprint(): d3.。

     3.8 新版功能.

 -- 函数: pprint.pprint (object, stream=None, indent=1, width=80,
          depth=None, *, compact=False, sort_dicts=True)

     在 `stream' 上打打印 `object' 的格式化表示，并附带一个换行符。 如果
     `stream' 为 ‘None’，则使用 ‘sys.stdout’。 这可以替代 *note print():
     88f. 函数在交互式解释器中使用以查看值（你甚至可以执行重新赋值
     ‘print = pprint.pprint’ 以在特定作用域中使用）。 `indent', `width',
     `depth', `compact' 和 `sort_dicts' 将作为格式化形参被传给 *note
     PrettyPrinter: 89e. 构造器。

     在 3.4 版更改: 增加了 `compact' 形参。

     在 3.8 版更改: 增加了 `sort_dicts' 形参。

          >>> import pprint
          >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
          >>> stuff.insert(0, stuff)
          >>> pprint.pprint(stuff)
          [<Recursion on list with id=...>,
           'spam',
           'eggs',
           'lumberjack',
           'knights',
           'ni']

 -- 函数: pprint.isreadable (object)

     确定 `object' 的格式化表示是否“可读”，或是否可被用来通过 *note
     eval(): b98. 重新构建对象的值。 此函数对于递归对象总是返回 ‘False’。

          >>> pprint.isreadable(stuff)
          False

 -- 函数: pprint.isrecursive (object)

     确定 `object' 是否需要递归表示。

此外还定义了一个支持函数：

 -- 函数: pprint.saferepr (object)

     返回 `object' 的字符串表示，并为递归数据结构提供保护。 如果
     `object' 的表示形式公开了一个递归条目，该递归引用会被表示为
     ‘<Recursion on typename with id=number>’。 该表示因而不会进行其它格
     式化。

          >>> pprint.saferepr(stuff)
          "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"

* Menu:

* PrettyPrinter 对象::
* 示例: 示例<3>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/pprint.py


File: python.info,  Node: PrettyPrinter 对象,  Next: 示例<3>,  Up: pprint --- 数据美化输出

5.8.11.1 PrettyPrinter 对象
...........................

*note PrettyPrinter: 89e. 的实例具有下列方法：

 -- 方法: PrettyPrinter.pformat (object)

     返回 `object' 格式化表示。 这会将传给 *note PrettyPrinter: 89e. 构
     造器的选项纳入考虑。

 -- 方法: PrettyPrinter.pprint (object)

     在所配置的流上打印 `object' 的格式化表示，并附加一个换行符。

下列方法提供了与同名函数相对应的实现。 在实例上使用这些方法效率会更高一
些，因为不需要创建新的 *note PrettyPrinter: 89e. 对象。

 -- 方法: PrettyPrinter.isreadable (object)

     确定对象的格式化表示是否“可读”，或者是否可使用 *note eval(): b98. 重
     建对象值。 请注意此方法对于递归对象将返回 ‘False’。 如果设置了
     *note PrettyPrinter: 89e. 的 `depth' 形参并且对象深度超出允许范围，
     此方法将返回 ‘False’。

 -- 方法: PrettyPrinter.isrecursive (object)

     确定对象是否需要递归表示。

此方法作为一个钩子提供，允许子类修改将对象转换为字符串的方式。 默认实现
使用 *note saferepr(): 19d9. 实现的内部方式。

 -- 方法: PrettyPrinter.format (object, context, maxlevels, level)

     返回三个值：字符串形式的 `object' 已格式化版本，指明结果是否可读的
     旗标，以及指明是否检测到递归的旗标。 第一个参数是要表示的对象。 第
     二个是以对象 *note id(): d8e. 为键的字典，这些对象是当前表示上下文
     的一部分（影响 `object' 表示的直接和间接容器）；如果需要呈现一个已
     经在 `context' 中表示的对象，则第三个返回值应当为 ‘True’。 对 *note
     format(): 19e0. 方法的递归调用应当将容器的附加条目添加到此字典中。
     第三个参数 `maxlevels' 给出了对递归的请求限制；如果没有请求限制则其
     值将为 ‘0’。 此参数应当不加修改地传给递归调用。 第四个参数 `level'
     给出于当前层级；传给递归调用的参数值应当小于当前调用的值。


File: python.info,  Node: 示例<3>,  Prev: PrettyPrinter 对象,  Up: pprint --- 数据美化输出

5.8.11.2 示例
.............

为了演示 *note pprint(): d3. 函数及其形参的几种用法，让我们从 PyPI(1) 获
取关于某个项目的信息:

     >>> import json
     >>> import pprint
     >>> from urllib.request import urlopen
     >>> with urlopen('https://pypi.org/pypi/sampleproject/json') as resp:
     ...     project_info = json.load(resp)['info']

*note pprint(): d3. 以其基本形式显示了整个对象:

     >>> pprint.pprint(project_info)
     {'author': 'The Python Packaging Authority',
      'author_email': 'pypa-dev@googlegroups.com',
      'bugtrack_url': None,
      'classifiers': ['Development Status :: 3 - Alpha',
                      'Intended Audience :: Developers',
                      'License :: OSI Approved :: MIT License',
                      'Programming Language :: Python :: 2',
                      'Programming Language :: Python :: 2.6',
                      'Programming Language :: Python :: 2.7',
                      'Programming Language :: Python :: 3',
                      'Programming Language :: Python :: 3.2',
                      'Programming Language :: Python :: 3.3',
                      'Programming Language :: Python :: 3.4',
                      'Topic :: Software Development :: Build Tools'],
      'description': 'A sample Python project\n'
                     '=======================\n'
                     '\n'
                     'This is the description file for the project.\n'
                     '\n'
                     'The file should use UTF-8 encoding and be written using '
                     'ReStructured Text. It\n'
                     'will be used to generate the project webpage on PyPI, and '
                     'should be written for\n'
                     'that purpose.\n'
                     '\n'
                     'Typical contents for this file would include an overview of '
                     'the project, basic\n'
                     'usage examples, etc. Generally, including the project '
                     'changelog in here is not\n'
                     'a good idea, although a simple "What\'s New" section for the '
                     'most recent version\n'
                     'may be appropriate.',
      'description_content_type': None,
      'docs_url': None,
      'download_url': 'UNKNOWN',
      'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1},
      'home_page': 'https://github.com/pypa/sampleproject',
      'keywords': 'sample setuptools development',
      'license': 'MIT',
      'maintainer': None,
      'maintainer_email': None,
      'name': 'sampleproject',
      'package_url': 'https://pypi.org/project/sampleproject/',
      'platform': 'UNKNOWN',
      'project_url': 'https://pypi.org/project/sampleproject/',
      'project_urls': {'Download': 'UNKNOWN',
                       'Homepage': 'https://github.com/pypa/sampleproject'},
      'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
      'requires_dist': None,
      'requires_python': None,
      'summary': 'A sample Python project',
      'version': '1.2.0'}

结果可以被限制到特定的 `depth' (更深层的内容将使用省略号):

     >>> pprint.pprint(project_info, depth=1)
     {'author': 'The Python Packaging Authority',
      'author_email': 'pypa-dev@googlegroups.com',
      'bugtrack_url': None,
      'classifiers': [...],
      'description': 'A sample Python project\n'
                     '=======================\n'
                     '\n'
                     'This is the description file for the project.\n'
                     '\n'
                     'The file should use UTF-8 encoding and be written using '
                     'ReStructured Text. It\n'
                     'will be used to generate the project webpage on PyPI, and '
                     'should be written for\n'
                     'that purpose.\n'
                     '\n'
                     'Typical contents for this file would include an overview of '
                     'the project, basic\n'
                     'usage examples, etc. Generally, including the project '
                     'changelog in here is not\n'
                     'a good idea, although a simple "What\'s New" section for the '
                     'most recent version\n'
                     'may be appropriate.',
      'description_content_type': None,
      'docs_url': None,
      'download_url': 'UNKNOWN',
      'downloads': {...},
      'home_page': 'https://github.com/pypa/sampleproject',
      'keywords': 'sample setuptools development',
      'license': 'MIT',
      'maintainer': None,
      'maintainer_email': None,
      'name': 'sampleproject',
      'package_url': 'https://pypi.org/project/sampleproject/',
      'platform': 'UNKNOWN',
      'project_url': 'https://pypi.org/project/sampleproject/',
      'project_urls': {...},
      'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
      'requires_dist': None,
      'requires_python': None,
      'summary': 'A sample Python project',
      'version': '1.2.0'}

此外，还可以设置建议的最大字符 `width'。 如果一个对象无法被拆分，则将超
出指定宽度:

     >>> pprint.pprint(project_info, depth=1, width=60)
     {'author': 'The Python Packaging Authority',
      'author_email': 'pypa-dev@googlegroups.com',
      'bugtrack_url': None,
      'classifiers': [...],
      'description': 'A sample Python project\n'
                     '=======================\n'
                     '\n'
                     'This is the description file for the '
                     'project.\n'
                     '\n'
                     'The file should use UTF-8 encoding and be '
                     'written using ReStructured Text. It\n'
                     'will be used to generate the project '
                     'webpage on PyPI, and should be written '
                     'for\n'
                     'that purpose.\n'
                     '\n'
                     'Typical contents for this file would '
                     'include an overview of the project, '
                     'basic\n'
                     'usage examples, etc. Generally, including '
                     'the project changelog in here is not\n'
                     'a good idea, although a simple "What\'s '
                     'New" section for the most recent version\n'
                     'may be appropriate.',
      'description_content_type': None,
      'docs_url': None,
      'download_url': 'UNKNOWN',
      'downloads': {...},
      'home_page': 'https://github.com/pypa/sampleproject',
      'keywords': 'sample setuptools development',
      'license': 'MIT',
      'maintainer': None,
      'maintainer_email': None,
      'name': 'sampleproject',
      'package_url': 'https://pypi.org/project/sampleproject/',
      'platform': 'UNKNOWN',
      'project_url': 'https://pypi.org/project/sampleproject/',
      'project_urls': {...},
      'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
      'requires_dist': None,
      'requires_python': None,
      'summary': 'A sample Python project',
      'version': '1.2.0'}

   ---------- Footnotes ----------

   (1) https://pypi.org


File: python.info,  Node: reprlib --- 另一种 repr 实现,  Next: enum --- 对枚举的支持,  Prev: pprint --- 数据美化输出,  Up: 数据类型

5.8.12 ‘reprlib’ — 另一种 ‘repr()’ 实现
---------------------------------------

`源代码:' Lib/reprlib.py(1)

__________________________________________________________________

*note reprlib: e0. 模块提供了一种对象表示的产生方式，它会对结果字符串的
大小进行限制。 该方式被用于 Python 调试器，也适用于某些其他场景。

此模块提供了一个类、一个实例和一个函数：

 -- 类: reprlib.Repr

     该类提供了格式化服务 适用于实现与内置 *note repr(): 7d5. 相似的方法
     ；其中附加了针对不同对象类型的大小限制，以避免生成超长的表示。

 -- 数据: reprlib.aRepr

     这是 *note Repr: 19e5. 的一个实例，用于提供如下所述的 *note repr():
     19e7. 函数。 改变此对象的属性将会影响 *note repr(): 19e7. 和 Python
     调试器所使用的大小限制。

 -- 函数: reprlib.repr (obj)

     这是 ‘aRepr’ 的 *note repr(): 19e8. 方法。 它会返回与同名内置函数所
     返回字符串相似的字符串，区别在于附带了对多数类型的大小限制。

在大小限制工具以外，此模块还提供了一个装饰器，用于检测对 *note
__repr__(): 347. 的递归调用并改用一个占位符来替换。

 -- 函数: @reprlib.recursive_repr (fillvalue="...")

     用于为 *note __repr__(): 347. 方法检测同一线程内部递归调用的装饰器
     。 如果执行了递归调用，则会返回 `fillvalue'，否则执行正常的 *note
     __repr__(): 347. 调用。 例如：

          >>> from reprlib import recursive_repr
          >>> class MyList(list):
          ...     @recursive_repr()
          ...     def __repr__(self):
          ...         return '<' + '|'.join(map(repr, self)) + '>'
          ...
          >>> m = MyList('abc')
          >>> m.append(m)
          >>> m.append('x')
          >>> print(m)
          <'a'|'b'|'c'|...|'x'>

     3.2 新版功能.

* Menu:

* Repr 对象::
* 子类化 Repr 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/reprlib.py


File: python.info,  Node: Repr 对象,  Next: 子类化 Repr 对象,  Up: reprlib --- 另一种 repr 实现

5.8.12.1 Repr 对象
..................

*note Repr: 19e5. 实例对象包含一些属性可以用于为不同对象类型的表示提供大
小限制，还包含一些方法可以格式化特定的对象类型。

 -- 属性: Repr.maxlevel

     创建递归表示形式的深度限制。 默认为 ‘6’。

 -- 属性: Repr.maxdict
 -- 属性: Repr.maxlist
 -- 属性: Repr.maxtuple
 -- 属性: Repr.maxset
 -- 属性: Repr.maxfrozenset
 -- 属性: Repr.maxdeque
 -- 属性: Repr.maxarray

     表示命名对象类型的条目数量限制。 对于 *note maxdict: 19ec. 的默认值
     为 ‘4’，对于 *note maxarray: 19f2. 为 ‘5’，对于其他则为 ‘6’。

 -- 属性: Repr.maxlong

     表示整数的最大字符数量。 数码会从中间被丢弃。 默认值为 ‘40’。

 -- 属性: Repr.maxstring

     表示字符串的字符数量限制。 请注意字符源会使用字符串的“正常”表示形式
     ：如果表示中需要用到转义序列，在缩短表示时它们可能会被破坏。 默认值
     为 ‘30’。

 -- 属性: Repr.maxother

     此限制用于控制在 *note Repr: 19e5. 对象上没有特定的格式化方法可用的
     对象类型的大小。 它会以类似 *note maxstring: 19f4. 的方式被应用。 默
     认值为 ‘20’。

 -- 方法: Repr.repr (obj)

     内置 *note repr(): 7d5. 的等价形式，它使用实例专属的格式化。

 -- 方法: Repr.repr1 (obj, level)

     供 *note repr(): 19e8. 使用的递归实现。 此方法使用 `obj' 的类型来确
     定要调用哪个格式化方法，并传入 `obj' 和 `level'。 类型专属的方法应
     当调用 *note repr1(): 19f6. 来执行递归格式化，在递归调用中使用
     ‘level - 1’ 作为 `level' 的值。

 -- 方法: Repr.repr_TYPE (obj, level)

     特定类型的格式化方法会被实现为基于类型名称来命名的方法。 在方法名称
     中，`TYPE' 会被替换为 ‘'_'.join(type(obj).__name__.split())’。 对这
     些方法的分派会由 *note repr1(): 19f6. 来处理。 需要对值进行递归格式
     化的类型专属方法应当调用 ‘self.repr1(subobj, level - 1)’。


File: python.info,  Node: 子类化 Repr 对象,  Prev: Repr 对象,  Up: reprlib --- 另一种 repr 实现

5.8.12.2 子类化 Repr 对象
.........................

通过 *note Repr.repr1(): 19f6. 使用动态分派允许 *note Repr: 19e5. 的子类
添加对额外内置对象类型的支持，或是修改对已支持类型的处理。 这个例子演示
了如何添加对文件对象的特殊支持:

     import reprlib
     import sys

     class MyRepr(reprlib.Repr):

         def repr_TextIOWrapper(self, obj, level):
             if obj.name in {'<stdin>', '<stdout>', '<stderr>'}:
                 return obj.name
             return repr(obj)

     aRepr = MyRepr()
     print(aRepr.repr(sys.stdin))         # prints '<stdin>'


File: python.info,  Node: enum --- 对枚举的支持,  Prev: reprlib --- 另一种 repr 实现,  Up: 数据类型

5.8.13 ‘enum’ — 对枚举的支持
----------------------------

3.4 新版功能.

`源代码：' Lib/enum.py(1)

__________________________________________________________________

枚举是一组符号名称（枚举成员）的集合，枚举成员应该是唯一的、不可变的。在
枚举中，可以对成员进行恒等比较，并且枚举本身是可迭代的。

     注解: 枚举成员名称的大小写

     因为枚举是被用来代表常量的所以我们建议枚举成员名称应使用大写形式，
     并将在我们的示例中使用此种风格。

* Menu:

* 模块内容: 模块内容<2>.
* 创建一个 Enum::
* 对枚举成员及其属性的程序化访问::
* 复制枚举成员和值::
* 确保唯一的枚举值::
* 使用自动设定的值::
* 迭代::
* 比较运算: 比较运算<3>.
* 允许的枚举成员和属性::
* 受限的 Enum 子类化::
* 封存::
* 功能性 API::
* 派生的枚举::
* 何时使用 __new__() 与 __init__(): 何时使用 __new__ 与 __init__.
* 有趣的示例::
* 各种枚举有何区别？::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/enum.py


File: python.info,  Node: 模块内容<2>,  Next: 创建一个 Enum,  Up: enum --- 对枚举的支持

5.8.13.1 模块内容
.................

此模块定义了四个枚举类，它们可被用来定义名称和值的不重复集合: *note
Enum: 38f, *note IntEnum: 596, *note Flag: 54e. 和 *note IntFlag: 176b.。
此外还定义了一个装饰器 *note unique(): 19fc. 和一个辅助类 *note auto:
54f.。

 -- 类: enum.Enum

     此基类用于创建枚举常量。 请参阅 *note Functional API: 19fd. 小节了
     解另一种替代性的构建语法。

 -- 类: enum.IntEnum

     此基类用于创建属于 *note int: 185. 的子类的枚举常量。

 -- 类: enum.IntFlag

     此基类用于创建可使用按位运算符进行组合而不会丢失其 *note IntFlag:
     176b. 成员资格的枚举常量。 *note IntFlag: 176b. 成员同样也是 *note
     int: 185. 的子类。

 -- 类: enum.Flag

     此基类用于创建枚举常量 可使用按位运算符进行组合而不会丢失其 *note
     Flag: 54e. 成员资格的枚举常量。

 -- 函数: enum.unique ()

     此 Enum 类装饰器可确保只将一个名称绑定到任意一个值。

 -- 类: enum.auto

     实例会被替换为一个可作为 Enum 成员的适当的值。 初始值从 1 开始。

3.6 新版功能: ‘Flag’, ‘IntFlag’, ‘auto’


File: python.info,  Node: 创建一个 Enum,  Next: 对枚举成员及其属性的程序化访问,  Prev: 模块内容<2>,  Up: enum --- 对枚举的支持

5.8.13.2 创建一个 Enum
......................

枚举是使用 *note class: c72. 语法来创建的，这使得它们易于读写。 另一种替
代创建方法的描述见 *note Functional API: 19fd.。 要定义一个枚举，可以对
*note Enum: 38f. 进行如下的子类化:

     >>> from enum import Enum
     >>> class Color(Enum):
     ...     RED = 1
     ...     GREEN = 2
     ...     BLUE = 3
     ...

     注解: Enum 的成员值

     成员值可以为任意类型: *note int: 185, *note str: 339. 等等。 如果具
     体的值不重要，你可以使用 *note auto: 54f. 实例，将为你选择适当的值
     。 但如果你混用 *note auto: 54f. 与其他值则需要小心谨慎。

     注解: 命名法

        - 类 ‘Color’ 是一个 `枚举' (或称 `enum')

        - 属性 ‘Color.RED’, ‘Color.GREEN’ 等等是 `枚举成员' (或称 `enum
          成员') 并且被用作常量。

        - 枚举成员具有 `名称' 和 `值' (例如 ‘Color.RED’ 的名称为 ‘RED’，
          ‘Color.BLUE’ 的值为 ‘3’ 等等)

     注解: 虽然我们使用 *note class: c72. 语法来创建 Enum，但 Enum 并不
     是普通的 Python 类。 更多细节请参阅 *note How are Enums different?:
     19ff.。

枚举成员具有适合人类阅读的表示形式:

     >>> print(Color.RED)
     Color.RED

...而它们的 ‘repr’ 包含更多信息:

     >>> print(repr(Color.RED))
     <Color.RED: 1>

一个枚举成员的 `type' 就是它所从属的枚举:

     >>> type(Color.RED)
     <enum 'Color'>
     >>> isinstance(Color.GREEN, Color)
     True
     >>>

Enum 的成员还有一个包含其条目名称的特征属性:

     >>> print(Color.RED.name)
     RED

枚举支持按照定义顺序进行迭代:

     >>> class Shake(Enum):
     ...     VANILLA = 7
     ...     CHOCOLATE = 4
     ...     COOKIES = 9
     ...     MINT = 3
     ...
     >>> for shake in Shake:
     ...     print(shake)
     ...
     Shake.VANILLA
     Shake.CHOCOLATE
     Shake.COOKIES
     Shake.MINT

枚举成员是可哈希的，因此它们可在字典和集合中可用:

     >>> apples = {}
     >>> apples[Color.RED] = 'red delicious'
     >>> apples[Color.GREEN] = 'granny smith'
     >>> apples == {Color.RED: 'red delicious', Color.GREEN: 'granny smith'}
     True


File: python.info,  Node: 对枚举成员及其属性的程序化访问,  Next: 复制枚举成员和值,  Prev: 创建一个 Enum,  Up: enum --- 对枚举的支持

5.8.13.3 对枚举成员及其属性的程序化访问
.......................................

有时对枚举中的成员进行程序化访问是很有用的（例如在某些场合不能使用
‘Color.RED’ 因为在编程时并不知道要指定的确切颜色）。 ‘Enum’ 允许这样的访
问:

     >>> Color(1)
     <Color.RED: 1>
     >>> Color(3)
     <Color.BLUE: 3>

如果你希望通过 `name' 来访问枚举成员，可使用条目访问:

     >>> Color['RED']
     <Color.RED: 1>
     >>> Color['GREEN']
     <Color.GREEN: 2>

如果你有一个枚举成员并且需要它的 ‘name’ 或 ‘value’:

     >>> member = Color.RED
     >>> member.name
     'RED'
     >>> member.value
     1


File: python.info,  Node: 复制枚举成员和值,  Next: 确保唯一的枚举值,  Prev: 对枚举成员及其属性的程序化访问,  Up: enum --- 对枚举的支持

5.8.13.4 复制枚举成员和值
.........................

不允许有同名的枚举成员:

     >>> class Shape(Enum):
     ...     SQUARE = 2
     ...     SQUARE = 3
     ...
     Traceback (most recent call last):
     ...
     TypeError: Attempted to reuse key: 'SQUARE'

但是，允许两个枚举成员有相同的值。 假定两个成员 A 和 B 有相同的值（且 A
先被定义），则 B 就是 A 的一个别名。 按值查找 A 和 B 的值将返回 A。 按名
称查找 B 也将返回 A:

     >>> class Shape(Enum):
     ...     SQUARE = 2
     ...     DIAMOND = 1
     ...     CIRCLE = 3
     ...     ALIAS_FOR_SQUARE = 2
     ...
     >>> Shape.SQUARE
     <Shape.SQUARE: 2>
     >>> Shape.ALIAS_FOR_SQUARE
     <Shape.SQUARE: 2>
     >>> Shape(2)
     <Shape.SQUARE: 2>

     注解: 试图创建具有与某个已定义的属性（另一个成员或方法等）相同名称
     的成员或者试图创建具有相同名称的属性也是不允许的。


File: python.info,  Node: 确保唯一的枚举值,  Next: 使用自动设定的值,  Prev: 复制枚举成员和值,  Up: enum --- 对枚举的支持

5.8.13.5 确保唯一的枚举值
.........................

默认情况下，枚举允许有多个名称作为某个相同值的别名。 如果不想要这样的行
为，可以使用以下装饰器来确保每个值在枚举中只被使用一次:

 -- 函数: @enum.unique

专用于枚举的 *note class: c72. 装饰器。 它会搜索一个枚举的 ‘__members__’
并收集所找到的任何别名；只要找到任何别名就会引发 *note ValueError: 1fc.
并附带相关细节信息:

     >>> from enum import Enum, unique
     >>> @unique
     ... class Mistake(Enum):
     ...     ONE = 1
     ...     TWO = 2
     ...     THREE = 3
     ...     FOUR = 3
     ...
     Traceback (most recent call last):
     ...
     ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE


File: python.info,  Node: 使用自动设定的值,  Next: 迭代,  Prev: 确保唯一的枚举值,  Up: enum --- 对枚举的支持

5.8.13.6 使用自动设定的值
.........................

如果确切的值不重要，你可以使用 *note auto: 54f.:

     >>> from enum import Enum, auto
     >>> class Color(Enum):
     ...     RED = auto()
     ...     BLUE = auto()
     ...     GREEN = auto()
     ...
     >>> list(Color)
     [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

值将由 ‘_generate_next_value_()’ 来选择，该函数可以被重载:

     >>> class AutoName(Enum):
     ...     def _generate_next_value_(name, start, count, last_values):
     ...         return name
     ...
     >>> class Ordinal(AutoName):
     ...     NORTH = auto()
     ...     SOUTH = auto()
     ...     EAST = auto()
     ...     WEST = auto()
     ...
     >>> list(Ordinal)
     [<Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>, <Ordinal.EAST: 'EAST'>, <Ordinal.WEST: 'WEST'>]

     注解: 默认 ‘_generate_next_value_()’ 方法的目标是提供所给出的最后一
     个 *note int: 185. 所在序列的下一个 *note int: 185.，但这种行为方式
     属于实现细节并且可能发生改变。

     注解: ‘_generate_next_value_()’ 方法定义必须在任何其他成员之前。


File: python.info,  Node: 迭代,  Next: 比较运算<3>,  Prev: 使用自动设定的值,  Up: enum --- 对枚举的支持

5.8.13.7 迭代
.............

对枚举成员的迭代不会给出别名:

     >>> list(Shape)
     [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]

特殊属性 ‘__members__’ 是一个从名称到成员的只读有序映射。 它包含枚举中定
义的所有名称，包括别名:

     >>> for name, member in Shape.__members__.items():
     ...     name, member
     ...
     ('SQUARE', <Shape.SQUARE: 2>)
     ('DIAMOND', <Shape.DIAMOND: 1>)
     ('CIRCLE', <Shape.CIRCLE: 3>)
     ('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>)

‘__members__’ 属性可被用于对枚举成员进行详细的程序化访问。 例如，找出所
有别名:

     >>> [name for name, member in Shape.__members__.items() if member.name != name]
     ['ALIAS_FOR_SQUARE']


File: python.info,  Node: 比较运算<3>,  Next: 允许的枚举成员和属性,  Prev: 迭代,  Up: enum --- 对枚举的支持

5.8.13.8 比较运算
.................

枚举成员是按标识号进行比较的:

     >>> Color.RED is Color.RED
     True
     >>> Color.RED is Color.BLUE
     False
     >>> Color.RED is not Color.BLUE
     True

枚举值之间的排序比较 `不被' 支持。 Enum 成员不属于整数 (另请参阅下文的
*note IntEnum: 1a06.):

     >>> Color.RED < Color.BLUE
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: '<' not supported between instances of 'Color' and 'Color'

相等比较的定义如下:

     >>> Color.BLUE == Color.RED
     False
     >>> Color.BLUE != Color.RED
     True
     >>> Color.BLUE == Color.BLUE
     True

与非枚举值的比较将总是不相等（同样地，*note IntEnum: 596. 被显式设计成不
同的行为，参见下文）:

     >>> Color.BLUE == 2
     False


File: python.info,  Node: 允许的枚举成员和属性,  Next: 受限的 Enum 子类化,  Prev: 比较运算<3>,  Up: enum --- 对枚举的支持

5.8.13.9 允许的枚举成员和属性
.............................

以上示例使用整数作为枚举值。 使用整数相当简洁方便（并由 *note Functional
API: 19fd. 默认提供），但并不强制要求使用。 在大部分用例中，开发者都关心
枚举的实际值是什么。 但如果值 `确实' 重要，则枚举可以使用任意的值。

枚举属于 Python 的类，并可具有普通方法和特殊方法。 如果我们有这样一个枚
举:

     >>> class Mood(Enum):
     ...     FUNKY = 1
     ...     HAPPY = 3
     ...
     ...     def describe(self):
     ...         # self is the member here
     ...         return self.name, self.value
     ...
     ...     def __str__(self):
     ...         return 'my custom str! {0}'.format(self.value)
     ...
     ...     @classmethod
     ...     def favorite_mood(cls):
     ...         # cls here is the enumeration
     ...         return cls.HAPPY
     ...

那么:

     >>> Mood.favorite_mood()
     <Mood.HAPPY: 3>
     >>> Mood.HAPPY.describe()
     ('HAPPY', 3)
     >>> str(Mood.FUNKY)
     'my custom str! 1'

对于允许内容的规则如下：以单下划线开头和结尾的名称是由枚举保留而不可使用
；在枚举中定义的所有其他属性将成为该枚举的成员，例外项则包括特殊方法成员
(*note __str__(): e3f, *note __add__(): 1467. 等)，描述符 (方法也属于描
述符) 以及在 ‘_ignore_’ 中列出的变量名。

注意：如果你的枚举定义了 *note __new__(): 892. 和/或 *note __init__():
d66. 那么指定给枚举成员的任何值都会被传入这些方法。 请参阅示例 *note
Planet: 1a08.。


File: python.info,  Node: 受限的 Enum 子类化,  Next: 封存,  Prev: 允许的枚举成员和属性,  Up: enum --- 对枚举的支持

5.8.13.10 受限的 Enum 子类化
............................

一个新的 *note Enum: 38f. 类必须基于一个 Enum 类，至多一个实体数据类型以
及出于实际需要的任意多个基于 *note object: 2b1. 的 mixin 类。 这些基类的
顺序为:

     class EnumName([mix-in, ...,] [data-type,] base-enum):
         pass

另外，仅当一个枚举未定义任何成员时才允许子类化该枚举。 因此禁止这样的写
法:

     >>> class MoreColor(Color):
     ...     PINK = 17
     ...
     Traceback (most recent call last):
     ...
     TypeError: Cannot extend enumerations

但是允许这样的写法:

     >>> class Foo(Enum):
     ...     def some_behavior(self):
     ...         pass
     ...
     >>> class Bar(Foo):
     ...     HAPPY = 1
     ...     SAD = 2
     ...

允许子类化定义了成员的枚举将会导致违反类型与实例的某些重要的不可变规则。
在另一方面，允许在一组枚举之间共享某些通用行为也是有意义的。 （请参阅示
例 *note OrderedEnum: 1a0a. 。）


File: python.info,  Node: 封存,  Next: 功能性 API,  Prev: 受限的 Enum 子类化,  Up: enum --- 对枚举的支持

5.8.13.11 封存
..............

枚举可以被封存与解封:

     >>> from test.test_enum import Fruit
     >>> from pickle import dumps, loads
     >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))
     True

封存的常规限制同样适用：可封存枚举必须在模块的最高层级中定义，因为解封操
作要求它们可以从该模块导入。

     注解: 使用 pickle 协议版本 4 可以方便地封存嵌套在其他类中的枚举。

通过在枚举类中定义 *note __reduce_ex__(): 1a0c. 可以对 Enum 成员的封存
/解封方式进行修改。


File: python.info,  Node: 功能性 API,  Next: 派生的枚举,  Prev: 封存,  Up: enum --- 对枚举的支持

5.8.13.12 功能性 API
....................

*note Enum: 38f. 类属于可调用对象，它提供了以下功能性 API:

     >>> Animal = Enum('Animal', 'ANT BEE CAT DOG')
     >>> Animal
     <enum 'Animal'>
     >>> Animal.ANT
     <Animal.ANT: 1>
     >>> Animal.ANT.value
     1
     >>> list(Animal)
     [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]

该 API 的主义类似于 *note namedtuple: 1b7.。 调用 *note Enum: 38f. 的第
一个参数是枚举的名称。

第二个参数是枚举成员名称的 `来源'。 它可以是一个用空格分隔的名称字符串、
名称序列、键/值对 2 元组的序列，或者名称到值的映射（例如字典）。 最后两
种选项使得可以为枚举任意赋值；其他选项会自动以从 1 开始递增的整数赋值（
使用 ‘start’ 形参可指定不同的起始值）。 返回值是一个派生自 *note Enum:
38f. 的新类。 换句话说，以上对 ‘Animal’ 的赋值就等价于:

     >>> class Animal(Enum):
     ...     ANT = 1
     ...     BEE = 2
     ...     CAT = 3
     ...     DOG = 4
     ...

默认以 ‘1’ 而以 ‘0’ 作为起始数值的原因在于 ‘0’ 的布尔值为 ‘False’，但所
有枚举成员都应被求值为 ‘True’。

对使用功能性 API 创建的枚举执行封存可能会很麻烦，因为要使用帧堆栈的实现
细节来尝试并找出枚举是在哪个模块中创建的（例如当你使用了另一个模块中的工
具函数就可能失败，在 IronPython 或 Jython 上也可能无效）。 解决办法是显
式地指定模块名称，如下所示:

     >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)

     警告: 如果未提供 ‘module’，且 Enum 无法确定是哪个模块，新的 Enum 成
     员将不可被解封；为了让错误尽量靠近源头，封存将被禁用。

新的 pickle 协议版本 4 在某些情况下同样依赖于 *note __qualname__: 143a.
被设为特定位置以便 pickle 能够找到相应的类。 例如，类是否存在于全局作用
域的 SomeData 类中:

     >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')

完整的签名为:

     Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1)


值: 将被新 Enum 类将记录为其名称的数据。


names: Enum 的成员。 这可以是一个空格或逗号分隔的字符串 (起始值将为 1，
除非另行指定):

     'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'

或是一个名称的迭代器:

     ['RED', 'GREEN', 'BLUE']

或是一个 (名称, 值) 对的迭代器:

     [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]

或是一个映射:

     {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}


module: 新 Enum 类所在模块的名称。


qualname: 新 Enum 类在模块中的具体位置。


type: 要加入新 Enum 类的类型。


start: 当只传入名称时要使用的起始数值。

在 3.5 版更改: 增加了 `start' 形参。


File: python.info,  Node: 派生的枚举,  Next: 何时使用 __new__ 与 __init__,  Prev: 功能性 API,  Up: enum --- 对枚举的支持

5.8.13.13 派生的枚举
....................

* Menu:

* IntEnum::
* IntFlag::
* Flag::
* 其他事项::


File: python.info,  Node: IntEnum,  Next: IntFlag,  Up: 派生的枚举

5.8.13.14 IntEnum
.................

所提供的第一个变种 *note Enum: 38f. 同时也是 *note int: 185. 的一个子类
。 *note IntEnum: 596. 的成员可与整数进行比较；通过扩展，不同类型的整数
枚举也可以相互进行比较:

     >>> from enum import IntEnum
     >>> class Shape(IntEnum):
     ...     CIRCLE = 1
     ...     SQUARE = 2
     ...
     >>> class Request(IntEnum):
     ...     POST = 1
     ...     GET = 2
     ...
     >>> Shape == 1
     False
     >>> Shape.CIRCLE == 1
     True
     >>> Shape.CIRCLE == Request.POST
     True

不过，它们仍然不可与标准 *note Enum: 38f. 枚举进行比较:

     >>> class Shape(IntEnum):
     ...     CIRCLE = 1
     ...     SQUARE = 2
     ...
     >>> class Color(Enum):
     ...     RED = 1
     ...     GREEN = 2
     ...
     >>> Shape.CIRCLE == Color.RED
     False

*note IntEnum: 596. 值在其他方面的行为都如你预期的一样类似于整数:

     >>> int(Shape.CIRCLE)
     1
     >>> ['a', 'b', 'c'][Shape.CIRCLE]
     'b'
     >>> [i for i in range(Shape.SQUARE)]
     [0, 1]


File: python.info,  Node: IntFlag,  Next: Flag,  Prev: IntEnum,  Up: 派生的枚举

5.8.13.15 IntFlag
.................

所提供的下一个 *note Enum: 38f. 的变种 *note IntFlag: 176b. 同样是基于
*note int: 185. 的，不同之处在于 *note IntFlag: 176b. 成员可使用按位运算
符 (&, |, ^, ~) 进行组合且结果仍然为 *note IntFlag: 176b. 成员。 如果，
正如名称所表明的，*note IntFlag: 176b. 成员同时也是 *note int: 185. 的子
类，并能在任何使用 *note int: 185. 的场合被使用。 *note IntFlag: 176b. 成
员进行除按位运算以外的其他运算都将导致失去 *note IntFlag: 176b. 成员资格
。

3.6 新版功能.

示例 *note IntFlag: 176b. 类:

     >>> from enum import IntFlag
     >>> class Perm(IntFlag):
     ...     R = 4
     ...     W = 2
     ...     X = 1
     ...
     >>> Perm.R | Perm.W
     <Perm.R|W: 6>
     >>> Perm.R + Perm.W
     6
     >>> RW = Perm.R | Perm.W
     >>> Perm.R in RW
     True

对于组合同样可以进行命名:

     >>> class Perm(IntFlag):
     ...     R = 4
     ...     W = 2
     ...     X = 1
     ...     RWX = 7
     >>> Perm.RWX
     <Perm.RWX: 7>
     >>> ~Perm.RWX
     <Perm.-8: -8>

*note IntFlag: 176b. 和 *note Enum: 38f. 的另一个重要区别在于如果没有设
置任何旗标（值为 0），则其布尔值为 *note False: 390.:

     >>> Perm.R & Perm.X
     <Perm.0: 0>
     >>> bool(Perm.R & Perm.X)
     False

由于 *note IntFlag: 176b. 成员同时也是 *note int: 185. 的子类，因此它们
可以相互组合:

     >>> Perm.X | 8
     <Perm.8|X: 9>


File: python.info,  Node: Flag,  Next: 其他事项,  Prev: IntFlag,  Up: 派生的枚举

5.8.13.16 Flag
..............

最后一个变种是 *note Flag: 54e.。 与 *note IntFlag: 176b. 类似，*note
Flag: 54e. 成员可使用按位运算符 (&, |, ^, ~) 进行组合，与 *note IntFlag:
176b. 不同的是它们不可与任何其它 *note Flag: 54e. 枚举或 *note int: 185.
进行组合或比较。 虽然可以直接指定值，但推荐使用 *note auto: 54f. 作为值
以便让 *note Flag: 54e. 选择适当的值。

3.6 新版功能.

与 *note IntFlag: 176b. 类似，如果 *note Flag: 54e. 成员的某种组合导致没
有设置任何旗标，则其布尔值为 *note False: 390.:

     >>> from enum import Flag, auto
     >>> class Color(Flag):
     ...     RED = auto()
     ...     BLUE = auto()
     ...     GREEN = auto()
     ...
     >>> Color.RED & Color.GREEN
     <Color.0: 0>
     >>> bool(Color.RED & Color.GREEN)
     False

单个旗标的值应当为二的乘方 (1, 2, 4, 8, ...)，旗标的组合则无此限制:

     >>> class Color(Flag):
     ...     RED = auto()
     ...     BLUE = auto()
     ...     GREEN = auto()
     ...     WHITE = RED | BLUE | GREEN
     ...
     >>> Color.WHITE
     <Color.WHITE: 7>

对 "no flags set" 条件指定一个名称并不会改变其布尔值:

     >>> class Color(Flag):
     ...     BLACK = 0
     ...     RED = auto()
     ...     BLUE = auto()
     ...     GREEN = auto()
     ...
     >>> Color.BLACK
     <Color.BLACK: 0>
     >>> bool(Color.BLACK)
     False

     注解: 对于大多数新代码，强烈推荐使用 *note Enum: 38f. 和 *note
     Flag: 54e.，因为 *note IntEnum: 596. 和 *note IntFlag: 176b. 打破了
     枚举的某些语义约定（例如可以同整数进行比较，并因而导致此行为被传递
     给其他无关的枚举）。 *note IntEnum: 596. 和 *note IntFlag: 176b. 的
     使用应当仅限于 *note Enum: 38f. 和 *note Flag: 54e. 无法使用的场合
     ；例如，当使用枚举替代整数常量时，或是与其他系统进行交互操作时。


File: python.info,  Node: 其他事项,  Prev: Flag,  Up: 派生的枚举

5.8.13.17 其他事项
..................

虽然 *note IntEnum: 596. 是 *note enum: 7b. 模块的一部分，但要独立实现也
应该相当容易:

     class IntEnum(int, Enum):
         pass

这里演示了如何定义类似的派生枚举；例如一个混合了 *note str: 339. 而不是
*note int: 185. 的 ‘StrEnum’。

几条规则：

  1. 当子类化 *note Enum: 38f. 时，在基类序列中的混合类型必须出现于
     *note Enum: 38f. 本身之前，如以上 *note IntEnum: 596. 的例子所示。

  2. 虽然 *note Enum: 38f. 可以拥有任意类型的成员，不过一旦你混合了附加
     类型，则所有成员必须为相应类型的值，如在上面的例子中即为 *note int:
     185.。 此限制不适用于仅添加方法而未指定另一数据类型如 *note int:
     185. 或 *note str: 339. 的混合类。

  3. 当混合了另一数据类型时，‘value’ 属性会 `不同于' 枚举成员自身，但它
     们仍保持等价且比较结果也相等。

  4. %-style formatting: ‘%s’ 和 ‘%r’ 会分别调用 *note Enum: 38f. 类的
     *note __str__(): e3f. 和 *note __repr__(): 347.；其他代码 (例如表示
     IntEnum 的 ‘%i’ 或 ‘%h’) 会将枚举成员视为对应的混合类型。

  5. *note 格式化字符串字面值: 15d, *note str.format(): 4e2. 和 *note
     format(): 4e3. 将使用混合类型的 *note __format__(): 956. 除非在子类
     中重载了 *note __str__(): e3f. 或 *note __format__(): 956.，在这种
     情况下将使用被重载的方法或 *note Enum: 38f. 的方法。 请使用 !s 和
     !r 格式代码来强制使用 *note Enum: 38f. 类的 *note __str__(): e3f. 和
     *note __repr__(): 347. 方法。


File: python.info,  Node: 何时使用 __new__ 与 __init__,  Next: 有趣的示例,  Prev: 派生的枚举,  Up: enum --- 对枚举的支持

5.8.13.18 何时使用 ‘__new__()’ 与 ‘__init__()’
..............................................

当你想要定制 *note Enum: 38f. 成员的实际值时必须使用 *note __new__():
892.。 任何其他修改可以用 *note __new__(): 892. 也可以用 *note
__init__(): d66.，应优先使用 *note __init__(): d66.。

举例来说，如果你要向构造器传入多个条目，但只希望将其中一个作为值:

     >>> class Coordinate(bytes, Enum):
     ...     """
     ...     Coordinate with binary codes that can be indexed by the int code.
     ...     """
     ...     def __new__(cls, value, label, unit):
     ...         obj = bytes.__new__(cls, [value])
     ...         obj._value_ = value
     ...         obj.label = label
     ...         obj.unit = unit
     ...         return obj
     ...     PX = (0, 'P.X', 'km')
     ...     PY = (1, 'P.Y', 'km')
     ...     VX = (2, 'V.X', 'km/s')
     ...     VY = (3, 'V.Y', 'km/s')
     ...

     >>> print(Coordinate['PY'])
     Coordinate.PY

     >>> print(Coordinate(3))
     Coordinate.VY


File: python.info,  Node: 有趣的示例,  Next: 各种枚举有何区别？,  Prev: 何时使用 __new__ 与 __init__,  Up: enum --- 对枚举的支持

5.8.13.19 有趣的示例
....................

虽然 *note Enum: 38f, *note IntEnum: 596, *note IntFlag: 176b. 和 *note
Flag: 54e. 预期可覆盖大多数应用场景，但它们无法覆盖全部。 这里有一些不同
类型枚举的方案，它们可以被直接使用，或是作为自行创建的参考示例。

* Menu:

* 省略值::
* OrderedEnum::
* DuplicateFreeEnum::
* Planet::
* TimePeriod::


File: python.info,  Node: 省略值,  Next: OrderedEnum,  Up: 有趣的示例

5.8.13.20 省略值
................

在许多应用场景中人们都不关心枚举的实际值是什么。 有几个方式可以定义此种
类型的简单枚举：

   - 使用 *note auto: 54f. 的实例作为值

   - 使用 *note object: 2b1. 的实例作为值

   - 使用描述性的字符串作为值

   - 使用元组作为值并用自定义的 *note __new__(): 892. 以一个 *note int:
     185. 值来替代该元组

使用以上任何一种方法均可向用户指明值并不重要，并且使人能够添加、移除或重
排序成员而不必改变其余成员的数值。

无论你选择何种方法，你都应当提供一个 *note repr(): 7d5. 并且它也需要隐藏
（不重要的）值:

     >>> class NoValue(Enum):
     ...     def __repr__(self):
     ...         return '<%s.%s>' % (self.__class__.__name__, self.name)
     ...

* Menu:

* 使用 auto::
* 使用 object::
* 使用描述性字符串::
* 使用自定义的 __new__(): 使用自定义的 __new__.


File: python.info,  Node: 使用 auto,  Next: 使用 object,  Up: 省略值

5.8.13.21 使用 ‘auto’
.....................

使用 *note auto: 54f. 的形式如下:

     >>> class Color(NoValue):
     ...     RED = auto()
     ...     BLUE = auto()
     ...     GREEN = auto()
     ...
     >>> Color.GREEN
     <Color.GREEN>


File: python.info,  Node: 使用 object,  Next: 使用描述性字符串,  Prev: 使用 auto,  Up: 省略值

5.8.13.22 使用 ‘object’
.......................

使用 *note object: 2b1. 的形式如下:

     >>> class Color(NoValue):
     ...     RED = object()
     ...     GREEN = object()
     ...     BLUE = object()
     ...
     >>> Color.GREEN
     <Color.GREEN>


File: python.info,  Node: 使用描述性字符串,  Next: 使用自定义的 __new__,  Prev: 使用 object,  Up: 省略值

5.8.13.23 使用描述性字符串
..........................

使用字符串作为值的形式如下:

     >>> class Color(NoValue):
     ...     RED = 'stop'
     ...     GREEN = 'go'
     ...     BLUE = 'too fast!'
     ...
     >>> Color.GREEN
     <Color.GREEN>
     >>> Color.GREEN.value
     'go'


File: python.info,  Node: 使用自定义的 __new__,  Prev: 使用描述性字符串,  Up: 省略值

5.8.13.24 使用自定义的 ‘__new__()’
..................................

使用自动编号 *note __new__(): 892. 的形式如下:

     >>> class AutoNumber(NoValue):
     ...     def __new__(cls):
     ...         value = len(cls.__members__) + 1
     ...         obj = object.__new__(cls)
     ...         obj._value_ = value
     ...         return obj
     ...
     >>> class Color(AutoNumber):
     ...     RED = ()
     ...     GREEN = ()
     ...     BLUE = ()
     ...
     >>> Color.GREEN
     <Color.GREEN>
     >>> Color.GREEN.value
     2

要实现更通用的 ‘AutoNumber’，请添加 ‘*args’ 到签名中:

     >>> class AutoNumber(NoValue):
     ...     def __new__(cls, *args):      # this is the only change from above
     ...         value = len(cls.__members__) + 1
     ...         obj = object.__new__(cls)
     ...         obj._value_ = value
     ...         return obj
     ...

这样当你从 ‘AutoNumber’ 继承时你将可以编写你自己的 ‘__init__’ 来处理任何
附加参数:

     >>> class Swatch(AutoNumber):
     ...     def __init__(self, pantone='unknown'):
     ...         self.pantone = pantone
     ...     AUBURN = '3497'
     ...     SEA_GREEN = '1246'
     ...     BLEACHED_CORAL = () # New color, no Pantone code yet!
     ...
     >>> Swatch.SEA_GREEN
     <Swatch.SEA_GREEN: 2>
     >>> Swatch.SEA_GREEN.pantone
     '1246'
     >>> Swatch.BLEACHED_CORAL.pantone
     'unknown'

     注解: 如果定义了 *note __new__(): 892. 则它会在创建 Enum 成员期间被
     使用；随后它将被 Enum 的 *note __new__(): 892. 所替换，该方法会在类
     创建后被用来查找现有成员。


File: python.info,  Node: OrderedEnum,  Next: DuplicateFreeEnum,  Prev: 省略值,  Up: 有趣的示例

5.8.13.25 OrderedEnum
.....................

一个有序枚举，它不是基于 *note IntEnum: 596.，因此保持了正常的 *note
Enum: 38f. 不变特性（例如不可与其他枚举进行比较）:

     >>> class OrderedEnum(Enum):
     ...     def __ge__(self, other):
     ...         if self.__class__ is other.__class__:
     ...             return self.value >= other.value
     ...         return NotImplemented
     ...     def __gt__(self, other):
     ...         if self.__class__ is other.__class__:
     ...             return self.value > other.value
     ...         return NotImplemented
     ...     def __le__(self, other):
     ...         if self.__class__ is other.__class__:
     ...             return self.value <= other.value
     ...         return NotImplemented
     ...     def __lt__(self, other):
     ...         if self.__class__ is other.__class__:
     ...             return self.value < other.value
     ...         return NotImplemented
     ...
     >>> class Grade(OrderedEnum):
     ...     A = 5
     ...     B = 4
     ...     C = 3
     ...     D = 2
     ...     F = 1
     ...
     >>> Grade.C < Grade.A
     True


File: python.info,  Node: DuplicateFreeEnum,  Next: Planet,  Prev: OrderedEnum,  Up: 有趣的示例

5.8.13.26 DuplicateFreeEnum
...........................

如果发现重复的成员名称则将引发错误而不是创建别名:

     >>> class DuplicateFreeEnum(Enum):
     ...     def __init__(self, *args):
     ...         cls = self.__class__
     ...         if any(self.value == e.value for e in cls):
     ...             a = self.name
     ...             e = cls(self.value).name
     ...             raise ValueError(
     ...                 "aliases not allowed in DuplicateFreeEnum:  %r --> %r"
     ...                 % (a, e))
     ...
     >>> class Color(DuplicateFreeEnum):
     ...     RED = 1
     ...     GREEN = 2
     ...     BLUE = 3
     ...     GRENE = 2
     ...
     Traceback (most recent call last):
     ...
     ValueError: aliases not allowed in DuplicateFreeEnum:  'GRENE' --> 'GREEN'

     注解: 这个例子适用于子类化 Enum 来添加或改变禁用别名以及其他行为。
     如果需要的改变只是禁用别名，也可以选择使用 *note unique(): 19fc. 装
     饰器。


File: python.info,  Node: Planet,  Next: TimePeriod,  Prev: DuplicateFreeEnum,  Up: 有趣的示例

5.8.13.27 Planet
................

如果定义了 *note __new__(): 892. 或 *note __init__(): d66. 则枚举成员的
值将被传给这些方法:

     >>> class Planet(Enum):
     ...     MERCURY = (3.303e+23, 2.4397e6)
     ...     VENUS   = (4.869e+24, 6.0518e6)
     ...     EARTH   = (5.976e+24, 6.37814e6)
     ...     MARS    = (6.421e+23, 3.3972e6)
     ...     JUPITER = (1.9e+27,   7.1492e7)
     ...     SATURN  = (5.688e+26, 6.0268e7)
     ...     URANUS  = (8.686e+25, 2.5559e7)
     ...     NEPTUNE = (1.024e+26, 2.4746e7)
     ...     def __init__(self, mass, radius):
     ...         self.mass = mass       # in kilograms
     ...         self.radius = radius   # in meters
     ...     @property
     ...     def surface_gravity(self):
     ...         # universal gravitational constant  (m3 kg-1 s-2)
     ...         G = 6.67300E-11
     ...         return G * self.mass / (self.radius * self.radius)
     ...
     >>> Planet.EARTH.value
     (5.976e+24, 6378140.0)
     >>> Planet.EARTH.surface_gravity
     9.802652743337129


File: python.info,  Node: TimePeriod,  Prev: Planet,  Up: 有趣的示例

5.8.13.28 TimePeriod
....................

一个演示如何使用 ‘_ignore_’ 属性的例子:

     >>> from datetime import timedelta
     >>> class Period(timedelta, Enum):
     ...     "different lengths of time"
     ...     _ignore_ = 'Period i'
     ...     Period = vars()
     ...     for i in range(367):
     ...         Period['day_%d' % i] = i
     ...
     >>> list(Period)[:2]
     [<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>]
     >>> list(Period)[-2:]
     [<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>]


File: python.info,  Node: 各种枚举有何区别？,  Prev: 有趣的示例,  Up: enum --- 对枚举的支持

5.8.13.29 各种枚举有何区别？
............................

枚举具有自定义的元类，它会影响所派生枚举类及其实例（成员）的各个方面。

* Menu:

* 枚举类::
* 枚举成员（即实例）::
* 细节要点::


File: python.info,  Node: 枚举类,  Next: 枚举成员（即实例）,  Up: 各种枚举有何区别？

5.8.13.30 枚举类
................

‘EnumMeta’ 元类负责提供 *note __contains__(): d30, *note __dir__(): 324,
*note __iter__(): 517. 及其他方法以允许用户通过 *note Enum: 38f. 类来完
成一般类做不到的事情，例如 ‘list(Color)’ 或 ‘some_enum_var in Color’。
‘EnumMeta’ 会负责确保最终 *note Enum: 38f. 类中的各种其他方法是正确的 (例
如 *note __new__(): 892, *note __getnewargs__(): 6b7, *note __str__():
e3f. 和 *note __repr__(): 347.)。


File: python.info,  Node: 枚举成员（即实例）,  Next: 细节要点,  Prev: 枚举类,  Up: 各种枚举有何区别？

5.8.13.31 枚举成员（即实例）
............................

有关枚举成员最有趣的特点是它们都是单例对象。 ‘EnumMeta’ 会在创建 *note
Enum: 38f. 类本身时将它们全部创建完成，然后准备好一个自定义的 *note
__new__(): 892.，通过只返回现有的成员实例来确保不会再实例化新的对象。


File: python.info,  Node: 细节要点,  Prev: 枚举成员（即实例）,  Up: 各种枚举有何区别？

5.8.13.32 细节要点
..................

* Menu:

* 支持的 __dunder__ 名称::
* 支持的 _sunder_ 名称::
* Enum 成员类型::
* Enum 类和成员的布尔值::
* 带有方法的 Enum 类::
* 组合 Flag 的成员::


File: python.info,  Node: 支持的 __dunder__ 名称,  Next: 支持的 _sunder_ 名称,  Up: 细节要点

5.8.13.33 支持的 ‘__dunder__’ 名称
..................................

‘__members__’ 是一个 ‘member_name’:‘member’ 条目的只读有序映射。 它只在
类上可用。

如果指定了 *note __new__(): 892.，它必须创建并返回枚举成员；相应地设定成
员的 ‘_value_’ 也是一个很好的主意。 一旦所有成员都创建完成它就不会再被使
用。


File: python.info,  Node: 支持的 _sunder_ 名称,  Next: Enum 成员类型,  Prev: 支持的 __dunder__ 名称,  Up: 细节要点

5.8.13.34 支持的 ‘_sunder_’ 名称
................................

   - ‘_name_’ – 成员的名称

   - ‘_value_’ – 成员的值；可以在 ‘__new__’ 中设置 / 修改

   - ‘_missing_’ – 当未发现某个值时所使用的查找函数；可被重载

   - ‘_ignore_’ – 一个名称列表，可以为 *note list(): 263. 或 *note
     str(): 339.，它将不会被转化为成员，并会从最终类中被移除

   - ‘_order_’ – 用于 Python 2/3 代码以确保成员顺序一致（类属性，在类创
     建期间会被移除）

   - ‘_generate_next_value_’ – 用于 *note Functional API: 19fd. 并通过
     *note auto: 54f. 为枚举成员获取适当的值；可被重载

3.6 新版功能: ‘_missing_’, ‘_order_’, ‘_generate_next_value_’

3.7 新版功能: ‘_ignore_’

用来帮助 Python 2 / Python 3 代码保持同步提供 ‘_order_’ 属性。 它将与枚
举的实际顺序进行对照检查，如果两者不匹配则会引发错误:

     >>> class Color(Enum):
     ...     _order_ = 'RED GREEN BLUE'
     ...     RED = 1
     ...     BLUE = 3
     ...     GREEN = 2
     ...
     Traceback (most recent call last):
     ...
     TypeError: member order does not match _order_

     注解: 在 Python 2 代码中 ‘_order_’ 属性是必须的，因为定义顺序在被记
     录之前就会丢失。


File: python.info,  Node: Enum 成员类型,  Next: Enum 类和成员的布尔值,  Prev: 支持的 _sunder_ 名称,  Up: 细节要点

5.8.13.35 ‘Enum’ 成员类型
.........................

*note Enum: 38f. 成员是其 *note Enum: 38f. 类的实例，一般通过
‘EnumClass.member’ 的形式来访问。 在特定情况下它们也可通过
‘EnumClass.member.member’ 的形式来访问，但你绝对不应这样做，因为查找可能
失败，或者更糟糕地返回你所查找的 *note Enum: 38f. 成员以外的对象（这也是
成员应使用全大写名称的另一个好理由）:

     >>> class FieldTypes(Enum):
     ...     name = 0
     ...     value = 1
     ...     size = 2
     ...
     >>> FieldTypes.value.size
     <FieldTypes.size: 2>
     >>> FieldTypes.size.value
     2

在 3.5 版更改.


File: python.info,  Node: Enum 类和成员的布尔值,  Next: 带有方法的 Enum 类,  Prev: Enum 成员类型,  Up: 细节要点

5.8.13.36 ‘Enum’ 类和成员的布尔值
.................................

混合了非 *note Enum: 38f. 类型（例如 *note int: 185, *note str: 339. 等
）的 *note Enum: 38f. 成员会按所混合类型的规则被求值；在其他情况下，所有
成员都将被求值为 *note True: 4a1.。 要使你的自定义 Enum 的布尔值取决于成
员的值，请在你的类中添加以下代码:

     def __bool__(self):
         return bool(self.value)

*note Enum: 38f. 类总是会被求值为 *note True: 4a1.。


File: python.info,  Node: 带有方法的 Enum 类,  Next: 组合 Flag 的成员,  Prev: Enum 类和成员的布尔值,  Up: 细节要点

5.8.13.37 带有方法的 ‘Enum’ 类
..............................

如果你为你的 *note Enum: 38f. 子类添加了额外的方法，如同上述的 *note
Planet: 1a08. 类一样，这些方法将在对成员执行 *note dir(): d3b. 时显示出
来，但对类执行时则不会显示:

     >>> dir(Planet)
     ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']
     >>> dir(Planet.EARTH)
     ['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value']


File: python.info,  Node: 组合 Flag 的成员,  Prev: 带有方法的 Enum 类,  Up: 细节要点

5.8.13.38 组合 ‘Flag’ 的成员
............................

如果 Flag 成员的某种组合未被命名，则 *note repr(): 7d5. 将包含所有已命名
的旗标和值中所有已命名的旗标组合:

     >>> class Color(Flag):
     ...     RED = auto()
     ...     GREEN = auto()
     ...     BLUE = auto()
     ...     MAGENTA = RED | BLUE
     ...     YELLOW = RED | GREEN
     ...     CYAN = GREEN | BLUE
     ...
     >>> Color(3)  # named combination
     <Color.YELLOW: 3>
     >>> Color(7)      # not named combination
     <Color.CYAN|MAGENTA|BLUE|YELLOW|GREEN|RED: 7>


File: python.info,  Node: 数字和数学模块,  Next: 函数式编程模块,  Prev: 数据类型,  Up: Python 标准库

5.9 数字和数学模块
==================

本章介绍的模块提供与数字和数学相关的函数和数据类型。 *note numbers: c2.
模块定义了数字类型的抽象层次结构。 *note math: b2. 和 *note cmath: 19. 模
块包含浮点数和复数的各种数学函数。 *note decimal: 36. 模块支持使用任意精
度算术的十进制数的精确表示。

本章包含以下模块的文档：

* Menu:

* numbers: numbers --- 数字的抽象基类. 数字的抽象基类
* math: math --- 数学函数. 数学函数
* cmath: cmath --- 关于复数的数学函数. 关于复数的数学函数
* decimal: decimal --- 十进制定点和浮点运算. 十进制定点和浮点运算
* fractions: fractions --- 分数. 分数
* random: random --- 生成伪随机数. 生成伪随机数
* statistics: statistics --- 数学统计函数. 数学统计函数


File: python.info,  Node: numbers --- 数字的抽象基类,  Next: math --- 数学函数,  Up: 数字和数学模块

5.9.1 ‘numbers’ — 数字的抽象基类
--------------------------------

`源代码：' Lib/numbers.py(1)

__________________________________________________________________

*note numbers: c2. 模块 ( PEP 3141(2)) 定义了数字 *note 抽象基类: b3b. 的
层次结构，其中逐级定义了更多操作。 此模块中所定义的类型都不可被实例化。

 -- 类: numbers.Number

     数字的层次结构的基础。 如果你只想确认参数 `x' 是不是数字而不关心其
     类型，则使用 ‘isinstance(x, Number)’。

* Menu:

* 数字的层次::
* 类型接口注释。::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/numbers.py

   (2) https://www.python.org/dev/peps/pep-3141


File: python.info,  Node: 数字的层次,  Next: 类型接口注释。,  Up: numbers --- 数字的抽象基类

5.9.1.1 数字的层次
..................

 -- 类: numbers.Complex

     内置在类型 *note complex: 18a. 里的子类描述了复数和它的运算操作。这
     些操作有：转化至 *note complex: 18a. 和 *note bool: 184.， *note
     real: 1a29.、 *note imag: 1a2a.、‘+’、‘-’、‘*’、‘/’、 *note abs():
     12cf.、 *note conjugate(): 1a2b.、 ‘==’ 和 ‘!=’。 所有的异常，‘-’ 和
     ‘!=’ ，都是抽象的。

      -- 属性: real

          抽象的。得到该数字的实数部分。

      -- 属性: imag

          抽象的。得到该数字的虚数部分。

      -- 方法: abstractmethod conjugate ()

          抽象的。返回共轭复数。例如 ‘(1+3j).conjugate() == (1-3j)’。

 -- 类: numbers.Real

     相对于 *note Complex: 1436.，*note Real: 1435. 加入了只有实数才能进
     行的操作。

     简单的说，它们是：转化至 *note float: 188.，*note math.trunc():
     d36.、 *note round(): c75.、 *note math.floor(): d34.、 *note
     math.ceil(): d35.、 *note divmod(): 153.、 ‘//’、 ‘%’、 ‘<’、 ‘<=’、
     ‘>’、 和 ‘>=’。

     实数同样默认支持 *note complex(): 18a.、 *note real: 1a29.、 *note
     imag: 1a2a. 和 *note conjugate(): 1a2b.。

 -- 类: numbers.Rational

     子类型 *note Real: 1435. 并加入 *note numerator: 1a2c. 和 *note
     denominator: 1a2d. 两种属性，这两种属性应该属于最低的级别。加入后，
     这默认支持 *note float(): 188.。

      -- 属性: numerator

          抽象的。

      -- 属性: denominator

          抽象的。

 -- 类: numbers.Integral

     子类型 *note Rational: c60. 加上转化至 *note int: 185.。 默认支持
     *note float(): 188.、 *note numerator: 1a2c. 和 *note denominator:
     1a2d.。 在 ‘**’ 中加入抽象方法和比特字符串的操作： ‘<<’、 ‘>>’、
     ‘&’、 ‘^’、 ‘|’、 ‘~’。


File: python.info,  Node: 类型接口注释。,  Prev: 数字的层次,  Up: numbers --- 数字的抽象基类

5.9.1.2 类型接口注释。
......................

实现者需要注意使相等的数字相等并拥有同样的值。当这两个数使用不同的扩展模
块时，这其中的差异是很微妙的。例如，用 *note fractions.Fraction: 186. 实
现 *note hash(): 9cc. 如下:

     def __hash__(self):
         if self.denominator == 1:
             # Get integers right.
             return hash(self.numerator)
         # Expensive check, but definitely correct.
         if self == float(self):
             return hash(float(self))
         else:
             # Use tuple's hash to avoid a high collision rate on
             # simple fractions.
             return hash((self.numerator, self.denominator))

* Menu:

* 加入更多数字的ABC::
* 实现算术运算::


File: python.info,  Node: 加入更多数字的ABC,  Next: 实现算术运算,  Up: 类型接口注释。

5.9.1.3 加入更多数字的ABC
.........................

当然，这里有更多支持数字的ABC，如果不加入这些，就将缺少层次感。你可以用
如下方法在 *note Complex: 1436. 和 *note Real: 1435. 中加入 ‘MyFoo’:

     class MyFoo(Complex): ...
     MyFoo.register(Real)


File: python.info,  Node: 实现算术运算,  Prev: 加入更多数字的ABC,  Up: 类型接口注释。

5.9.1.4 实现算术运算
....................

我们希望实现计算，因此，混合模式操作要么调用一个作者知道参数类型的实现，
要么转变成为最接近的内置类型并对这个执行操作。对于子类 *note Integral:
1434.，这意味着 *note __add__(): 1467. 和 *note __radd__(): 1468. 必须用
如下方式定义：

     class MyIntegral(Integral):

         def __add__(self, other):
             if isinstance(other, MyIntegral):
                 return do_my_adding_stuff(self, other)
             elif isinstance(other, OtherTypeIKnowAbout):
                 return do_my_other_adding_stuff(self, other)
             else:
                 return NotImplemented

         def __radd__(self, other):
             if isinstance(other, MyIntegral):
                 return do_my_adding_stuff(other, self)
             elif isinstance(other, OtherTypeIKnowAbout):
                 return do_my_other_adding_stuff(other, self)
             elif isinstance(other, Integral):
                 return int(other) + int(self)
             elif isinstance(other, Real):
                 return float(other) + float(self)
             elif isinstance(other, Complex):
                 return complex(other) + complex(self)
             else:
                 return NotImplemented

*note Complex: 1436. 有 5 种不同的混合类型的操作。 我将上面提到的所有代
码作为“模板”称作 ‘MyIntegral’ 和 ‘OtherTypeIKnowAbout’。 ‘a’ 是 *note
Complex: 1436. 的子类型 ‘A’ 的实例 (‘a : A <: Complex’)，同时 ‘b : B <:
Complex’。 我将要计算 ‘a + b’:

       1. 如果 ‘A’ 被定义成一个承认 ‘b’ 的 *note __add__(): 1467.，一切
          都没有问题。

       2. 如果 ‘A’ 转回成“模板”失败，它将返回一个属于 *note __add__():
          1467. 的值，我们需要避免 ‘B’ 定义了一个更加智能的 *note
          __radd__(): 1468.，因此模板需要返回一个属于 *note __add__():
          1467. 的 *note NotImplemented: 855. 。（或者 ‘A’ 可能完全不实
          现 *note __add__(): 1467. 。）

       3. 接着看 ‘B’ 的 *note __radd__(): 1468. 。如果它承认 ‘a’ ，一切
          都没有问题。

       4. 如果没有成功回退到模板，就没有更多的方法可以去尝试，因此这里将
          使用默认的实现。

       5. 如果 ‘B <: A’ ， Python 在 ‘A.__add__’ 之前尝试 ‘B.__radd__’ 。
          这是可行的，是通过对 ‘A’ 的认识实现的，因此这可以在交给 *note
          Complex: 1436. 处理之前处理这些实例。

如果 ‘A <: Complex’ 和 ‘B <: Real’ 没有共享任何资源，那么适当的共享操作
涉及内置的 *note complex: 18a. ，并且分别获得 *note __radd__(): 1468. ，
因此 ‘a+b == b+a’。

由于对任何一直类型的大部分操作是十分相似的，可以定义一个帮助函数，即一个
生成后续或相反的实例的生成器。例如，使用 *note fractions.Fraction: 186.
如下：

     def _operator_fallbacks(monomorphic_operator, fallback_operator):
         def forward(a, b):
             if isinstance(b, (int, Fraction)):
                 return monomorphic_operator(a, b)
             elif isinstance(b, float):
                 return fallback_operator(float(a), b)
             elif isinstance(b, complex):
                 return fallback_operator(complex(a), b)
             else:
                 return NotImplemented
         forward.__name__ = '__' + fallback_operator.__name__ + '__'
         forward.__doc__ = monomorphic_operator.__doc__

         def reverse(b, a):
             if isinstance(a, Rational):
                 # Includes ints.
                 return monomorphic_operator(a, b)
             elif isinstance(a, numbers.Real):
                 return fallback_operator(float(a), float(b))
             elif isinstance(a, numbers.Complex):
                 return fallback_operator(complex(a), complex(b))
             else:
                 return NotImplemented
         reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
         reverse.__doc__ = monomorphic_operator.__doc__

         return forward, reverse

     def _add(a, b):
         """a + b"""
         return Fraction(a.numerator * b.denominator +
                         b.numerator * a.denominator,
                         a.denominator * b.denominator)

     __add__, __radd__ = _operator_fallbacks(_add, operator.add)

     # ...


File: python.info,  Node: math --- 数学函数,  Next: cmath --- 关于复数的数学函数,  Prev: numbers --- 数字的抽象基类,  Up: 数字和数学模块

5.9.2 ‘math’ — 数学函数
-----------------------

__________________________________________________________________

该模块提供了对C标准定义的数学函数的访问。

这些函数不适用于复数；如果你需要计算复数，请使用 *note cmath: 19. 模块中
的同名函数。将支持计算复数的函数区分开的目的，来自于大多数开发者并不愿意
像数学家一样需要学习复数的概念。得到一个异常而不是一个复数结果使得开发者
能够更早地监测到传递给这些函数的参数中包含复数，进而调查其产生的原因。

该模块提供了以下函数。除非另有明确说明，否则所有返回值均为浮点数。

* Menu:

* 数论与表示函数::
* 幂函数与对数函数::
* 三角函数::
* 角度转换::
* 双曲函数::
* 特殊函数::
* 常量: 常量<2>.


File: python.info,  Node: 数论与表示函数,  Next: 幂函数与对数函数,  Up: math --- 数学函数

5.9.2.1 数论与表示函数
......................

 -- 函数: math.ceil (x)

     返回 `x' 的上限，即大于或者等于 `x' 的最小整数。如果 `x' 不是一个浮
     点数，则委托 ‘x.__ceil__()’, 返回一个 *note Integral: 1434. 类的值
     。

 -- 函数: math.comb (n, k)

     返回不重复且无顺序地从 `n' 项中选择 `k' 项的方式总数。

     当 ‘k <= n’ 时取值为 ‘n! / (k! * (n - k)!)’；当 ‘k > n’ 时取值为零
     。

     也称为二项式系数，因为它等价于表达式 ‘(1 + x) ** n’ 的多项式展开中
     第 k 项的系数。

     如果任一参数不为整数则会引发 *note TypeError: 193.。 如果任一参数为
     负数则会引发 *note ValueError: 1fc.。

     3.8 新版功能.

 -- 函数: math.copysign (x, y)

     返回一个基于 `x' 的绝对值和 `y' 的符号的浮点数。在支持带符号零的平
     台上，‘copysign(1.0, -0.0)’ 返回 `-1.0'.

 -- 函数: math.fabs (x)

     返回 `x' 的绝对值。

 -- 函数: math.factorial (x)

     以一个整数返回 `x' 的阶乘。 如果 `x' 不是整数或为负数时则将引发
     *note ValueError: 1fc.。

 -- 函数: math.floor (x)

     返回 `x' 的向下取整，小于或等于 `x' 的最大整数。如果 `x' 不是浮点数
     ，则委托 ‘x.__floor__()’ ，它应返回 *note Integral: 1434. 值。

 -- 函数: math.fmod (x, y)

     返回 ‘fmod(x, y)’ ，由平台C库定义。请注意，Python表达式 ‘x % y’ 可
     能不会返回相同的结果。C标准的目的是 ‘fmod(x, y)’ 完全（数学上；到无
     限精度）等于 ‘x - n*y’ 对于某个整数 `n' ，使得结果具有 与 `x' 相同
     的符号和小于 ‘abs(y)’ 的幅度。Python的 ‘x % y’ 返回带有 `y' 符号的
     结果，并且可能不能完全计算浮点参数。 例如， ‘fmod(-1e-100, 1e100)’
     是 ‘-1e-100’ ，但Python的 ‘-1e-100 % 1e100’ 的结果是 ‘1e100-1e-100’
     ，它不能完全表示为浮点数，并且取整为令人惊讶的 ‘1e100’ 。 出于这个
     原因，函数 *note fmod(): 1548. 在使用浮点数时通常是首选，而Python的
     ‘x % y’ 在使用整数时是首选。

 -- 函数: math.frexp (x)

     以 ‘(m, e)’ 对的形式返回 `x' 的尾数和指数。 `m' 是一个浮点数， `e'
     是一个整数，正好是 ‘x == m * 2**e’ 。 如果 `x' 为零，则返回 ‘(0.0,
     0)’ ，否则返回 ‘0.5 <= abs(m) < 1’ 。这用于以可移植方式“分离”浮点数
     的内部表示。

 -- 函数: math.fsum (iterable)

     返回迭代中的精确浮点值。通过跟踪多个中间部分和来避免精度损失:

          >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
          0.9999999999999999
          >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
          1.0

     该算法的准确性取决于IEEE-754算术保证和舍入模式为半偶的典型情况。在
     某些非Windows版本中，底层C库使用扩展精度添加，并且有时可能会使中间
     和加倍，导致它在最低有效位中关闭。

     有关待进一步讨论和两种替代方法，参见 ASPN cookbook recipes for
     accurate floating point summation(1)。

 -- 函数: math.gcd (a, b)

     返回整数 `a' 和 `b' 的最大公约数。如果 `a' 或 `b' 之一非零，则
     ‘gcd(a, b)’ 的值是能同时整除 `a' 和 `b' 的最大正整数。‘gcd(0, 0)’ 返
     回 ‘0’。

     3.5 新版功能.

 -- 函数: math.isclose (a, b, *, rel_tol=1e-09, abs_tol=0.0)

     若 `a' 和 `b' 的值比较接近则返回 ‘True’，否则返回 ‘False’。

     根据给定的绝对和相对容差确定两个值是否被认为是接近的。

     `rel_tol' 是相对容差 —— 它是 `a' 和 `b' 之间允许的最大差值，相对于
     `a' 或 `b' 的较大绝对值。例如，要设置5％的容差，请传递
     ‘rel_tol=0.05’ 。默认容差为 ‘1e-09’，确保两个值在大约9位十进制数字
     内相同。 `rel_tol' 必须大于零。

     `abs_tol' 是最小绝对容差 —— 对于接近零的比较很有用。 `abs_tol' 必须
     至少为零。

     如果没有错误发生，结果将是： ‘abs(a-b) <= max(rel_tol * max(abs(a),
     abs(b)), abs_tol)’ 。

     IEEE 754特殊值 ‘NaN’ ， ‘inf’ 和 ‘-inf’ 将根据IEEE规则处理。具体来
     说， ‘NaN’ 不被认为接近任何其他值，包括 ‘NaN’ 。 ‘inf’ 和 ‘-inf’ 只
     被认为接近自己。

     3.5 新版功能.

     参见
     ....

     PEP 485(2) —— 用于测试近似相等的函数

 -- 函数: math.isfinite (x)

     如果 `x' 既不是无穷大也不是NaN，则返回 ‘True’ ，否则返回 ‘False’ 。
     （注意 ‘0.0’ 被认为 `是' 有限的。）

     3.2 新版功能.

 -- 函数: math.isinf (x)

     如果 `x' 是正或负无穷大，则返回 ‘True’ ，否则返回 ‘False’ 。

 -- 函数: math.isnan (x)

     如果 `x' 是 NaN（不是数字），则返回 ‘True’ ，否则返回 ‘False’ 。

 -- 函数: math.isqrt (n)

     返回非负整数 `n' 的整数平方根。 这就是对 `n' 的实际平方根向下取整，
     或者相当于使得 `a'² ≤ `n' 的最大整数 `a'。

     对于某些应用来说，可以更适合取值为使得 `n' ≤ `a'² 的最小整数 `a' ，
     或者换句话说就是 `n' 的实际平方根向上取整。 对于正数 `n'，这可以使
     用 ‘a = 1 + isqrt(n - 1)’ 来计算。

     3.8 新版功能.

 -- 函数: math.ldexp (x, i)

     返回 ‘x * (2**i)’ 。 这基本上是函数 *note frexp(): 1a35. 的反函数。

 -- 函数: math.modf (x)

     返回 `x' 的小数和整数部分。两个结果都带有 `x' 的符号并且是浮点数。

 -- 函数: math.perm (n, k=None)

     返回不重复且有顺序地从 `n' 项中选择 `k' 项的方式总数。

     当 ‘k <= n’ 时取值为 ‘n! / (n - k)!’；当 ‘k > n’ 时取值为零。

     如果 `k' 未指定或为 None，则 `k' 默认值为 `n' 并且函数将返回 ‘n!’。

     如果任一参数不为整数则会引发 *note TypeError: 193.。 如果任一参数为
     负数则会引发 *note ValueError: 1fc.。

     3.8 新版功能.

 -- 函数: math.prod (iterable, *, start=1)

     计算输入的 `iterable' 中所有元素的积。 积的默认 `start' 值为 ‘1’。

     当可迭代对象为空时，返回起始值。 此函数特别针对数字值使用，并会拒绝
     非数字类型。

     3.8 新版功能.

 -- 函数: math.remainder (x, y)

     返回 IEEE 754 风格的 `x' 相对于 `y' 的余数。对于有限 `x' 和有限非零
     `y' ，这是差异 ‘x - n*y’ ，其中 ‘n’ 是与商 ‘x / y’ 的精确值最接近的
     整数。如果 ‘x / y’ 恰好位于两个连续整数之间，则将最接近的 `偶数' 用
     作 ‘n’ 。 余数 ‘r = remainder(x, y)’ 因此总是满足 ‘abs(r) <= 0.5 *
     abs(y)’。

     特殊情况遵循IEEE 754：特别是 ‘remainder(x, math.inf)’ 对于任何有限
     `x' 都是 `x' ，而 ‘remainder(x, 0)’ 和 ‘remainder(math.inf, x)’ 引
     发 *note ValueError: 1fc. 适用于任何非NaN的 `x' 。如果余数运算的结
     果为零，则该零将具有与 `x' 相同的符号。

     在使用IEEE 754二进制浮点的平台上，此操作的结果始终可以完全表示：不
     会引入舍入错误。

     3.7 新版功能.

 -- 函数: math.trunc (x)

     返回 *note Real: 1435. 值 `x' 截断为 *note Integral: 1434. （通常是
     整数）。 委托给 *note x.__trunc__(): 1493.。

注意 *note frexp(): 1a35. 和 *note modf(): 1a37. 具有与它们的C等价函数不
同的调用/返回模式：它们采用单个参数并返回一对值，而不是通过 ’输出形参’ 返
回它们的第二个返回参数（Python中没有这样的东西）。

对于 *note ceil(): d35. ， *note floor(): d34. 和 *note modf(): 1a37. 函
数，请注意 `所有' 足够大的浮点数都是精确整数。Python浮点数通常不超过53位
的精度（与平台C double类型相同），在这种情况下，任何浮点 `x' 与 ‘abs(x)
>= 2**52’ 必然没有小数位。

   ---------- Footnotes ----------

   (1) https://code.activestate.com/recipes/393090/

   (2) https://www.python.org/dev/peps/pep-0485


File: python.info,  Node: 幂函数与对数函数,  Next: 三角函数,  Prev: 数论与表示函数,  Up: math --- 数学函数

5.9.2.2 幂函数与对数函数
........................

 -- 函数: math.exp (x)

     返回 `e' 次 `x' 幂，其中 `e' = 2.718281... 是自然对数的基数。这通常
     比 ‘math.e ** x’ 或 ‘pow(math.e, x)’ 更精确。

 -- 函数: math.expm1 (x)

     返回 `e' 的 `x' 次幂，减1。这里 `e' 是自然对数的基数。对于小浮点数
     `x' ， ‘exp(x) - 1’ 中的减法可能导致 significant loss of
     precision(1)； *note expm1(): b70. 函数提供了一种将此数量计算为全精
     度的方法:

          >>> from math import exp, expm1
          >>> exp(1e-5) - 1  # gives result accurate to 11 places
          1.0000050000069649e-05
          >>> expm1(1e-5)    # result accurate to full precision
          1.0000050000166668e-05

     3.2 新版功能.

 -- 函数: math.log (x[, base])

     使用一个参数，返回 `x' 的自然对数（底为 `e' ）。

     使用两个参数，返回给定的 `base' 的对数 `x' ，计算为
     ‘log(x)/log(base)’ 。

 -- 函数: math.log1p (x)

     返回 `1+x' 的自然对数（以 `e' 为底）。 以对于接近零的 `x' 精确的方
     式计算结果。

 -- 函数: math.log2 (x)

     返回 `x' 以2为底的对数。这通常比 ‘log(x, 2)’ 更准确。

     3.3 新版功能.

     参见
     ....

     *note int.bit_length(): 162f. 返回表示二进制整数所需的位数，不包括
     符号和前导零。

 -- 函数: math.log10 (x)

     返回 `x' 底为10的对数。这通常比 ‘log(x, 10)’ 更准确。

 -- 函数: math.pow (x, y)

     将返回 ‘x’ 的 ‘y’ 次幂。特殊情况尽可能遵循C99标准的附录’F’。特别是
     ， ‘pow(1.0, x)’ 和 ‘pow(x, 0.0)’ 总是返回 ‘1.0’ ，即使 ‘x’ 是零或
     NaN。 如果 ‘x’ 和 ‘y’ 都是有限的， ‘x’ 是负数， ‘y’ 不是整数那么
     ‘pow(x, y)’ 是未定义的，并且引发 *note ValueError: 1fc. 。

     与内置的 ‘**’ 运算符不同， *note math.pow(): 1a3a. 将其参数转换为
     *note float: 188. 类型。使用 ‘**’ 或内置的 *note pow(): 19b. 函数来
     计算精确的整数幂。

 -- 函数: math.sqrt (x)

     返回 `x' 的平方根。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Loss_of_significance


File: python.info,  Node: 三角函数,  Next: 角度转换,  Prev: 幂函数与对数函数,  Up: math --- 数学函数

5.9.2.3 三角函数
................

 -- 函数: math.acos (x)

     以弧度为单位返回 `x' 的反余弦值。

 -- 函数: math.asin (x)

     以弧度为单位返回 `x' 的反正弦值。

 -- 函数: math.atan (x)

     以弧度为单位返回 `x' 的反正切值。

 -- 函数: math.atan2 (y, x)

     以弧度为单位返回 ‘atan(y / x)’ 。结果是在 ‘-pi’ 和 ‘pi’ 之间。从原
     点到点 ‘(x, y)’ 的平面矢量使该角度与正X轴成正比。 *note atan2():
     1a3f. 的点的两个输入的符号都是已知的，因此它可以计算角度的正确象限
     。 例如， ‘atan(1)’ 和 ‘atan2(1, 1)’ 都是 ‘pi/4’ ，但 ‘atan2(-1,
     -1)’ 是 ‘-3*pi/4’ 。

 -- 函数: math.cos (x)

     返回 `x' 弧度的余弦值。

 -- 函数: math.dist (p, q)

     返回 `p' 与 `q' 两点之间的欧几里得距离，以一个坐标序列（或可迭代对
     象）的形式给出。 两个点必须具有相同的维度。

     大致相当于：

          sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))

     3.8 新版功能.

 -- 函数: math.hypot (*coordinates)

     返回欧几里得范数，‘sqrt(sum(x**2 for x in coordinates))’。 这是从原
     点到坐标给定点的向量长度。

     对于一个二维点 ‘(x, y)’，这等价于使用毕达哥拉斯定义 ‘sqrt(x*x +
     y*y)’ 计算一个直角三角形的斜边。

     在 3.8 版更改: 添加了对 n 维点的支持。 之前的版本只支持二维点。

 -- 函数: math.sin (x)

     返回 `x' 弧度的正弦值。

 -- 函数: math.tan (x)

     返回 `x' 弧度的正切值。


File: python.info,  Node: 角度转换,  Next: 双曲函数,  Prev: 三角函数,  Up: math --- 数学函数

5.9.2.4 角度转换
................

 -- 函数: math.degrees (x)

     将角度 `x' 从弧度转换为度数。

 -- 函数: math.radians (x)

     将角度 `x' 从度数转换为弧度。


File: python.info,  Node: 双曲函数,  Next: 特殊函数,  Prev: 角度转换,  Up: math --- 数学函数

5.9.2.5 双曲函数
................

双曲函数(1) 是基于双曲线而非圆来对三角函数进行模拟。

 -- 函数: math.acosh (x)

     返回 `x' 的反双曲余弦值。

 -- 函数: math.asinh (x)

     返回 `x' 的反双曲正弦值。

 -- 函数: math.atanh (x)

     返回 `x' 的反双曲正切值。

 -- 函数: math.cosh (x)

     返回 `x' 的双曲余弦值。

 -- 函数: math.sinh (x)

     返回 `x' 的双曲正弦值。

 -- 函数: math.tanh (x)

     返回 `x' 的双曲正切值。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Hyperbolic_function


File: python.info,  Node: 特殊函数,  Next: 常量<2>,  Prev: 双曲函数,  Up: math --- 数学函数

5.9.2.6 特殊函数
................

 -- 函数: math.erf (x)

     返回 `x' 处的 error function(1) 。

     *note erf(): 45a. 函数可用于计算传统的统计函数，如 累积标准正态分布
     (2)

          def phi(x):
              'Cumulative distribution function for the standard normal distribution'
              return (1.0 + erf(x / sqrt(2.0))) / 2.0

     3.2 新版功能.

 -- 函数: math.erfc (x)

     返回 `x' 处的互补误差函数。 互补错误函数(3) 定义为 ‘1.0 - erf(x)’。
     它用于 `x' 的大值，从其中减去一个会导致 有效位数损失(4)。

     3.2 新版功能.

 -- 函数: math.gamma (x)

     返回 `x' 处的 伽马函数(5) 值。

     3.2 新版功能.

 -- 函数: math.lgamma (x)

     返回Gamma函数在 `x' 绝对值的自然对数。

     3.2 新版功能.

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Error_function

   (2) 
https://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function

   (3) https://en.wikipedia.org/wiki/Error_function

   (4) https://en.wikipedia.org/wiki/Loss_of_significance

   (5) https://en.wikipedia.org/wiki/Gamma_function


File: python.info,  Node: 常量<2>,  Prev: 特殊函数,  Up: math --- 数学函数

5.9.2.7 常量
............

 -- 数据: math.pi

     数学常数 `π' = 3.141592...，精确到可用精度。

 -- 数据: math.e

     数学常数 `e' = 2.718281...，精确到可用精度。

 -- 数据: math.tau

     数学常数 `τ' = 6.283185...，精确到可用精度。Tau 是一个圆周常数，等
     于 2`π'，圆的周长与半径之比。更多关于 Tau 的信息可参考 Vi Hart 的视
     频 Pi is (still) Wrong(1)。吃两倍多的派来庆祝 Tau 日(2) 吧！

     3.6 新版功能.

 -- 数据: math.inf

     浮点正无穷大。 （对于负无穷大，使用 ‘-math.inf’ 。）相当于
     ‘float('inf')’ 的输出。

     3.5 新版功能.

 -- 数据: math.nan

     浮点“非数字”（NaN）值。 相当于 ‘float('nan')’ 的输出。

     3.5 新版功能.

`CPython implementation detail:' *note math: b2. 模块主要包含围绕平台C数
学库函数的简单包装器。特殊情况下的行为在适当情况下遵循C99标准的附录F。当
前的实现将引发 *note ValueError: 1fc. 用于无效操作，如 ‘sqrt(-1.0)’ 或
‘log(0.0)’ （其中C99附件F建议发出无效操作信号或被零除）， 和 *note
OverflowError: 968. 用于溢出的结果（例如， ‘exp(1000.0)’ ）。除非一个或
多个输入参数是NaN，否则不会从上述任何函数返回NaN；在这种情况下，大多数函
数将返回一个NaN，但是（再次遵循C99附件F）这个规则有一些例外，例如
‘pow(float('nan'), 0.0)’ 或 ‘hypot(float('nan'), float('inf'))’ 。

请注意，Python不会将显式NaN与静默NaN区分开来，并且显式NaN的行为仍未明确
。典型的行为是将所有NaN视为静默的。

参见
....

*note cmath: 19. 模块

     这里很多函数的复数版本。

   ---------- Footnotes ----------

   (1) https://www.youtube.com/watch?v=jG7vhMMXagQ

   (2) https://tauday.com/


File: python.info,  Node: cmath --- 关于复数的数学函数,  Next: decimal --- 十进制定点和浮点运算,  Prev: math --- 数学函数,  Up: 数字和数学模块

5.9.3 ‘cmath’ — 关于复数的数学函数
----------------------------------

__________________________________________________________________

这一模块提供了一些关于复数的数学函数。 该模块的函数的参数为整数、浮点数
或复数。 这些函数的参数也可为一个拥有 *note __complex__(): 18e. 或 *note
__float__(): 18d. 方法的 Python 对象，这些方法分别用于将对象转换为复数和
浮点数，这些函数作用于转换后的结果。

     注解: 在具有对于有符号零的硬件和系统级支持的平台上，涉及支割线的函
     数在支割线的 `两侧' 都是连续的：零的符号可用来区别支割线的一侧和另
     一侧。 在不支持有符号零的平台上，连续性的规则见下文。

* Menu:

* 到极坐标和从极坐标的转换::
* 幂函数与对数函数: 幂函数与对数函数<2>.
* 三角函数: 三角函数<2>.
* 双曲函数: 双曲函数<2>.
* 分类函数::
* 常量: 常量<3>.


File: python.info,  Node: 到极坐标和从极坐标的转换,  Next: 幂函数与对数函数<2>,  Up: cmath --- 关于复数的数学函数

5.9.3.1 到极坐标和从极坐标的转换
................................

使用 `矩形坐标' 或 `笛卡尔坐标' 在内部存储 Python 复数 ‘z’。 这完全取决
于它的 `实部' ‘z.real’ 和 `虚部' ‘z.imag’。 换句话说:

     z == z.real + z.imag*1j

`极坐标' 提供了另一种复数的表示方法。在极坐标中，一个复数 `z' 由模量 `r'
和相位角 `phi' 来定义。模量 `r' 是从 `z' 到坐标原点的距离，而相位角
`phi' 是以弧度为单位的，逆时针的，从正X轴到连接原点和 `z' 的线段间夹角的
角度。

下面的函数可用于原生直角坐标与极坐标的相互转换。

 -- 函数: cmath.phase (x)

     将 `x' 的相位 (也称为 `x' 的 `参数') 返回为一个浮点数。‘phase(x)’ 相
     当于 ‘math.atan2(x.imag, x.real)’。 结果处于 [-`π', `π'] 之间，以及
     这个操作的分支切断处于负实轴上，从上方连续。 在支持有符号零的系统上
     （这包涵大多数当前的常用系统），这意味着结果的符号与 ‘x.imag’ 的符
     号相同，即使 ‘x.imag’ 的值是 0:

          >>> phase(complex(-1.0, 0.0))
          3.141592653589793
          >>> phase(complex(-1.0, -0.0))
          -3.141592653589793

     注解: 一个复数 `x' 的模数（绝对值）可以通过内置函数 *note abs():
     12cf. 计算。没有单独的 *note cmath: 19. 模块函数用于这个操作。

 -- 函数: cmath.polar (x)

     在极坐标中返回 `x' 的表达方式。返回一个数对 ‘(r, phi)’，`r' 是 `x'
     的模数，`phi' 是 `x' 的相位角。 ‘polar(x)’ 相当于 ‘(abs(x),
     phase(x))’。

 -- 函数: cmath.rect (r, phi)

     通过极坐标的 `r' 和 `phi' 返回复数 `x'。相当于 ‘r * (math.cos(phi)
     + math.sin(phi)*1j)’。


File: python.info,  Node: 幂函数与对数函数<2>,  Next: 三角函数<2>,  Prev: 到极坐标和从极坐标的转换,  Up: cmath --- 关于复数的数学函数

5.9.3.2 幂函数与对数函数
........................

 -- 函数: cmath.exp (x)

     返回 `e' 的 `x' 次方，`e' 是自然对数的底数。

 -- 函数: cmath.log (x[, base])

     返回给定 `base' 的 `x' 的对数。如果没有给定 `base'，返回 `x' 的自然
     对数。 从 0 到 -∞ 存在一条支割线，沿负实轴之上连续。

 -- 函数: cmath.log10 (x)

     返回底数为 10 的 `x' 的对数。它具有与 *note log(): 1a55. 相同的支割
     线。

 -- 函数: cmath.sqrt (x)

     返回 `x' 的平方根。 它具有与 *note log(): 1a55. 相同的支割线。


File: python.info,  Node: 三角函数<2>,  Next: 双曲函数<2>,  Prev: 幂函数与对数函数<2>,  Up: cmath --- 关于复数的数学函数

5.9.3.3 三角函数
................

 -- 函数: cmath.acos (x)

     返回 `x' 的反余弦。这里有两条支割线：一条沿着实轴从 1 向右延伸到 ∞，
     从下面连续延伸。另外一条沿着实轴从 -1 向左延伸到 -∞，从上面连续延伸
     。

 -- 函数: cmath.asin (x)

     返回 `x' 的反正弦。它与 *note acos(): 1a59. 有相同的支割线。

 -- 函数: cmath.atan (x)

     返回 `x' 的反正切。它具有两条支割线：一条沿着虚轴从 ‘1j’ 延伸到
     ‘∞j’，向右持续延伸。另一条是沿着虚轴从 ‘-1j’ 延伸到 ‘-∞j’ ，向左持
     续延伸。

 -- 函数: cmath.cos (x)

     返回 `x' 的余弦。

 -- 函数: cmath.sin (x)

     返回 `x' 的正弦。

 -- 函数: cmath.tan (x)

     返回 `x' 的正切。


File: python.info,  Node: 双曲函数<2>,  Next: 分类函数,  Prev: 三角函数<2>,  Up: cmath --- 关于复数的数学函数

5.9.3.4 双曲函数
................

 -- 函数: cmath.acosh (x)

     返回 `x' 的反双曲余弦。它有一条支割线沿着实轴从 1 到 -∞ 向左延伸，
     从上方持续延伸。

 -- 函数: cmath.asinh (x)

     返回 `x' 的反双曲正弦。它有两条支割线：一条沿着虚轴从 ‘1j’ 向右持续
     延伸到 ‘∞j’。另一条是沿着虚轴从 ‘-1j’ 向左持续延伸到 ‘-∞j’。

 -- 函数: cmath.atanh (x)

     返回 `x' 的反双曲正切。它有两条支割线：一条是沿着实轴从 ‘1’ 延展到
     ‘∞’，从下面持续延展。另一条是沿着实轴从 ‘-1’ 延展到 ‘-∞’，从上面持
     续延展。

 -- 函数: cmath.cosh (x)

     返回 `x' 的双曲余弦值。

 -- 函数: cmath.sinh (x)

     返回 `x' 的双曲正弦值。

 -- 函数: cmath.tanh (x)

     返回 `x' 的双曲正切值。


File: python.info,  Node: 分类函数,  Next: 常量<3>,  Prev: 双曲函数<2>,  Up: cmath --- 关于复数的数学函数

5.9.3.5 分类函数
................

 -- 函数: cmath.isfinite (x)

     如果 `x' 的实部和虚部都是有限的，则返回 ‘True’，否则返回 ‘False’。

     3.2 新版功能.

 -- 函数: cmath.isinf (x)

     如果 `x' 的实部或者虚部是无穷大的，则返回 ‘True’，否则返回 ‘False’。

 -- 函数: cmath.isnan (x)

     如果 `x' 的实部或者虚部是 NaN，则返回 ‘True’ ，否则返回 ‘False’。

 -- 函数: cmath.isclose (a, b, *, rel_tol=1e-09, abs_tol=0.0)

     若 `a' 和 `b' 的值比较接近则返回 ‘True’，否则返回 ‘False’。

     根据给定的绝对和相对容差确定两个值是否被认为是接近的。

     `rel_tol' 是相对容差 —— 它是 `a' 和 `b' 之间允许的最大差值，相对于
     `a' 或 `b' 的较大绝对值。例如，要设置5％的容差，请传递
     ‘rel_tol=0.05’ 。默认容差为 ‘1e-09’，确保两个值在大约9位十进制数字
     内相同。 `rel_tol' 必须大于零。

     `abs_tol' 是最小绝对容差 —— 对于接近零的比较很有用。 `abs_tol' 必须
     至少为零。

     如果没有错误发生，结果将是： ‘abs(a-b) <= max(rel_tol * max(abs(a),
     abs(b)), abs_tol)’ 。

     IEEE 754特殊值 ‘NaN’ ， ‘inf’ 和 ‘-inf’ 将根据IEEE规则处理。具体来
     说， ‘NaN’ 不被认为接近任何其他值，包括 ‘NaN’ 。 ‘inf’ 和 ‘-inf’ 只
     被认为接近自己。

     3.5 新版功能.

     参见
     ....

     PEP 485(1) —— 用于测试近似相等的函数

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0485


File: python.info,  Node: 常量<3>,  Prev: 分类函数,  Up: cmath --- 关于复数的数学函数

5.9.3.6 常量
............

 -- 数据: cmath.pi

     数学常数 `π' ，作为一个浮点数。

 -- 数据: cmath.e

     数学常数 `e' ，作为一个浮点数。

 -- 数据: cmath.tau

     数学常数 `τ' ，作为一个浮点数。

     3.6 新版功能.

 -- 数据: cmath.inf

     浮点正无穷大。相当于 ‘float('inf')’。

     3.6 新版功能.

 -- 数据: cmath.infj

     具有零实部和正无穷虚部的复数。相当于 ‘complex(0.0, float('inf'))’。

     3.6 新版功能.

 -- 数据: cmath.nan

     浮点“非数字”（NaN）值。相当于 ‘float('nan')’。

     3.6 新版功能.

 -- 数据: cmath.nanj

     具有零实部和 NaN 虚部的复数。相当于 ‘complex(0.0, float('nan'))’。

     3.6 新版功能.

请注意，函数的选择与模块 *note math: b2. 中的函数选择相似，但不完全相同
。 拥有两个模块的原因是因为有些用户对复数不感兴趣，甚至根本不知道它们是
什么。它们宁愿 ‘math.sqrt(-1)’ 引发异常，也不想返回一个复数。 另请注意，
被 *note cmath: 19. 定义的函数始终会返回一个复数，尽管答案可以表示为一个
实数（在这种情况下，复数的虚数部分为零）。

关于支割线的注释：它们是沿着给定函数无法连续的曲线。它们是许多复变函数的
必要特征。 假设您需要使用复变函数进行计算，您将会了解支割线的概念。 请参
阅几乎所有关于复变函数的（不太基本）的书来获得启发。 对于如何正确地基于
数值目的来选择支割线的相关信息，一个良好的参考如下：

参见
....

Kahan, W: Branch cuts for complex elementary functions; or, Much ado
about nothing’s sign bit.  In Iserles, A., and Powell, M. (eds.), The
state of the art in numerical analysis.  Clarendon Press (1987)
pp165–211.


File: python.info,  Node: decimal --- 十进制定点和浮点运算,  Next: fractions --- 分数,  Prev: cmath --- 关于复数的数学函数,  Up: 数字和数学模块

5.9.4 ‘decimal’ — 十进制定点和浮点运算
--------------------------------------

`源码：' Lib/decimal.py(1)

__________________________________________________________________

*note decimal: 36. 模块为快速正确舍入的十进制浮点运算提供支持。 与 *note
float: 188. 数据类型相比，它具有以下几个优点：

   * Decimal 类型的“设计是基于考虑人类习惯的浮点数模型，并且因此具有以下
     最高指导原则 —— 计算机必须提供与人们在学校所学习的算术相一致的算术
     。” —— 摘自 decimal 算术规范描述。

   * Decimal 数字的表示是完全精确的。 相比之下，‘1.1’ 和 ‘2.2’ 这样的数
     字在二进制浮点中没有精确的表示。 最终用户通常不希望 ‘1.1 + 2.2’ 如
     二进制浮点数表示那样被显示为 ‘3.3000000000000003’。

   * 精确性会延续到算术类操作中。 对于 decimal 浮点数，‘0.1 + 0.1 + 0.1
     - 0.3’ 会精确地等于零。 而对于二进制浮点数，结果则为
     ‘5.5511151231257827e-017’ 。 虽然接近于零，但其中的误差将妨碍可靠的
     相等性检验，并且误差还会不断累积。 因此，decimal 更适合具有严格相等
     不变性要求的会计类应用。

   * 十进制模块包含有效位的概念，因此 ‘1.30 + 1.20’ 的结果是 ‘2.50’ 。 保
     留尾随零以表示有效位。 这是货币的惯用表示方法。乘法则沿用 “教科书“
     中：保留被乘数中的所有数字的方法。 例如， ‘1.3 * 1.2’ 结果是 ‘1.56’
     而 ‘1.30 * 1.20’ 结果是 ‘1.5600’ 。

   * 与基于硬件的二进制浮点不同，十进制模块具有用户可更改的精度（默认为
     28位），可以与给定问题所需的一样大：

          >>> from decimal import *
          >>> getcontext().prec = 6
          >>> Decimal(1) / Decimal(7)
          Decimal('0.142857')
          >>> getcontext().prec = 28
          >>> Decimal(1) / Decimal(7)
          Decimal('0.1428571428571428571428571429')

   * 二进制和 decimal 浮点数都是根据已发布的标准实现的。 虽然内置浮点类
     型只公开其功能的一小部分，但 decimal 模块公开了标准的所有必需部分。
     在需要时，程序员可以完全控制舍入和信号处理。 这包括通过使用异常来阻
     止任何不精确操作来强制执行精确算术的选项。

   * decimal 模块旨在支持“无偏差，精确无舍入的十进制算术（有时称为定点数
     算术）和有舍入的浮点数算术”。 —— 摘自 decimal 算术规范说明。

该模块的设计以三个概念为中心：decimal 数值，算术上下文和信号。

decimal 数值是不可变对象。 它由符号，系数和指数位组成。 为了保持有效位，
系数位不会截去末尾零。 decimal 数值也包括特殊值例如 ‘Infinity’ ，
‘-Infinity’ 和 ‘NaN’ 。 该标准还区分 ‘-0’ 和 ‘+0’ 。

算术的上下文是指定精度、舍入规则、指数限制、指示操作结果的标志以及确定符
号是否被视为异常的陷阱启用器的环境。 舍入选项包括 *note ROUND_CEILING:
1a6f. 、 *note ROUND_DOWN: 1a70. 、 *note ROUND_FLOOR: 1a71. 、 *note
ROUND_HALF_DOWN: 1a72, *note ROUND_HALF_EVEN: 1a73. 、 *note
ROUND_HALF_UP: 1a74. 、 *note ROUND_UP: 1a75. 以及 *note ROUND_05UP:
1a76.

信号是在计算过程中出现的异常条件组。 根据应用程序的需要，信号可能会被忽
略，被视为信息，或被视为异常。 十进制模块中的信号有：*note Clamped:
1a77. 、 *note InvalidOperation: 9f3. 、 *note DivisionByZero: 1a78. 、
*note Inexact: 1a79. 、 *note Rounded: 1a7a. 、 *note Subnormal: 1a7b. 、
*note Overflow: 1a7c. 、 *note Underflow: 1a7d. 以及 *note
FloatOperation: 9ed. 。

对于每个信号，都有一个标志和一个陷阱启动器。 遇到信号时，其标志设置为 1
，然后，如果陷阱启用器设置为 1 ，则引发异常。 标志是粘性的，因此用户需要
在监控计算之前重置它们。

参见
....

   * IBM 的通用十进制算术规范描述 The General Decimal Arithmetic
     Specification(2)。

* Menu:

* 快速入门教程::
* Decimal 对象::
* 上下文对象::
* 常量: 常量<4>.
* 舍入模式::
* 信号::
* 浮点数说明::
* 使用线程::
* 例程::
* Decimal 常见问题::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/decimal.py

   (2) http://speleotrove.com/decimal/decarith.html


File: python.info,  Node: 快速入门教程,  Next: Decimal 对象,  Up: decimal --- 十进制定点和浮点运算

5.9.4.1 快速入门教程
....................

通常使用 decimal 的方式是先导入该模块，通过 *note getcontext(): 1a80. 查
看当前上下文，并在必要时为精度、舍入或启用的陷阱设置新值:

     >>> from decimal import *
     >>> getcontext()
     Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
             capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
             InvalidOperation])

     >>> getcontext().prec = 7       # Set a new precision

可以基于整数、字符串、浮点数或元组构造 Decimal 实例。 基于整数或浮点数构
造将执行该整数或浮点值的精确转换。 Decimal 数字包括特殊值例如 ‘NaN’ 表示
“非数字”，正的和负的 ‘Infinity’ 和 ‘-0’

     >>> getcontext().prec = 28
     >>> Decimal(10)
     Decimal('10')
     >>> Decimal('3.14')
     Decimal('3.14')
     >>> Decimal(3.14)
     Decimal('3.140000000000000124344978758017532527446746826171875')
     >>> Decimal((0, (3, 1, 4), -2))
     Decimal('3.14')
     >>> Decimal(str(2.0 ** 0.5))
     Decimal('1.4142135623730951')
     >>> Decimal(2) ** Decimal('0.5')
     Decimal('1.414213562373095048801688724')
     >>> Decimal('NaN')
     Decimal('NaN')
     >>> Decimal('-Infinity')
     Decimal('-Infinity')

如果 *note FloatOperation: 9ed. 信号被捕获，构造函数中的小数和浮点数的意
外混合或排序比较会引发异常

     >>> c = getcontext()
     >>> c.traps[FloatOperation] = True
     >>> Decimal(3.14)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
     >>> Decimal('3.5') < 3.7
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
     >>> Decimal('3.5') == 3.5
     True

3.3 新版功能.

新 Decimal 的重要性仅由输入的位数决定。 上下文精度和舍入仅在算术运算期间
发挥作用。

     >>> getcontext().prec = 6
     >>> Decimal('3.0')
     Decimal('3.0')
     >>> Decimal('3.1415926535')
     Decimal('3.1415926535')
     >>> Decimal('3.1415926535') + Decimal('2.7182818285')
     Decimal('5.85987')
     >>> getcontext().rounding = ROUND_UP
     >>> Decimal('3.1415926535') + Decimal('2.7182818285')
     Decimal('5.85988')

如果超出了 C 版本的内部限制，则构造一个 decimal 将引发 *note
InvalidOperation: 9f3.

     >>> Decimal("1e9999999999999999999")
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

在 3.3 版更改.

Decimal 数字能很好地与 Python 的其余部分交互。 以下是一个小小的 decimal
浮点数飞行马戏团：

     >>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
     >>> max(data)
     Decimal('9.25')
     >>> min(data)
     Decimal('0.03')
     >>> sorted(data)
     [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
      Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
     >>> sum(data)
     Decimal('19.29')
     >>> a,b,c = data[:3]
     >>> str(a)
     '1.34'
     >>> float(a)
     1.34
     >>> round(a, 1)
     Decimal('1.3')
     >>> int(a)
     1
     >>> a * 5
     Decimal('6.70')
     >>> a * b
     Decimal('2.5058')
     >>> c % a
     Decimal('0.77')

Decimal 也可以使用一些数学函数：

     >>> getcontext().prec = 28
     >>> Decimal(2).sqrt()
     Decimal('1.414213562373095048801688724')
     >>> Decimal(1).exp()
     Decimal('2.718281828459045235360287471')
     >>> Decimal('10').ln()
     Decimal('2.302585092994045684017991455')
     >>> Decimal('10').log10()
     Decimal('1')

‘quantize()’ 方法将数字舍入为固定指数。 此方法对于将结果舍入到固定的位置
的货币应用程序非常有用：

     >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
     Decimal('7.32')
     >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
     Decimal('8')

如上所示，*note getcontext(): 1a80. 函数访问当前上下文并允许更改设置。 这
种方法满足大多数应用程序的需求。

对于更高级的工作，使用 Context() 构造函数创建备用上下文可能很有用。 要使
用备用活动，请使用 *note setcontext(): 1a81. 函数。

根据标准，*note decimal: 36. 模块提供了两个现成的标准上下文 *note
BasicContext: 9f1. 和 *note ExtendedContext: 9f2. 。 前者对调试特别有用
，因为许多陷阱都已启用：

     >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
     >>> setcontext(myothercontext)
     >>> Decimal(1) / Decimal(7)
     Decimal('0.142857142857142857142857142857142857142857142857142857142857')

     >>> ExtendedContext
     Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
             capitals=1, clamp=0, flags=[], traps=[])
     >>> setcontext(ExtendedContext)
     >>> Decimal(1) / Decimal(7)
     Decimal('0.142857143')
     >>> Decimal(42) / Decimal(0)
     Decimal('Infinity')

     >>> setcontext(BasicContext)
     >>> Decimal(42) / Decimal(0)
     Traceback (most recent call last):
       File "<pyshell#143>", line 1, in -toplevel-
         Decimal(42) / Decimal(0)
     DivisionByZero: x / 0

上下文还具有用于监视计算期间遇到的异常情况的信号标志。 标志保持设置直到
明确清除，因此最好通过使用 ‘clear_flags()’ 方法清除每组受监控计算之前的
标志。:

     >>> setcontext(ExtendedContext)
     >>> getcontext().clear_flags()
     >>> Decimal(355) / Decimal(113)
     Decimal('3.14159292')
     >>> getcontext()
     Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
             capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])

`flags' 条目显示对 ‘Pi’ 的有理逼近被舍入（超出上下文精度的数字被抛弃）并
且结果是不精确的（一些丢弃的数字不为零）。

使用上下文的 ‘traps’ 字段中的字典设置单个陷阱：

     >>> setcontext(ExtendedContext)
     >>> Decimal(1) / Decimal(0)
     Decimal('Infinity')
     >>> getcontext().traps[DivisionByZero] = 1
     >>> Decimal(1) / Decimal(0)
     Traceback (most recent call last):
       File "<pyshell#112>", line 1, in -toplevel-
         Decimal(1) / Decimal(0)
     DivisionByZero: x / 0

大多数程序仅在程序开始时调整当前上下文一次。 并且，在许多应用程序中，数
据在循环内单个强制转换为 *note Decimal: 189. 。 通过创建上下文集和小数，
程序的大部分操作数据与其他 Python 数字类型没有区别。


File: python.info,  Node: Decimal 对象,  Next: 上下文对象,  Prev: 快速入门教程,  Up: decimal --- 十进制定点和浮点运算

5.9.4.2 Decimal 对象
....................

 -- 类: decimal.Decimal (value="0", context=None)

     根据 `value' 构造一个新的 *note Decimal: 189. 对象。

     `value' 可以是整数，字符串，元组，*note float: 188. ，或另一个
     *note Decimal: 189. 对象。 如果没有给出 `value'，则返回
     ‘Decimal('0')’。 如果 `value' 是一个字符串，它应该在前导和尾随空格
     字符以及下划线被删除之后符合十进制数字字符串语法:

          sign           ::=  '+' | '-'
          digit          ::=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
          indicator      ::=  'e' | 'E'
          digits         ::=  digit [digit]...
          decimal-part   ::=  digits '.' [digits] | ['.'] digits
          exponent-part  ::=  indicator [sign] digits
          infinity       ::=  'Infinity' | 'Inf'
          nan            ::=  'NaN' [digits] | 'sNaN' [digits]
          numeric-value  ::=  decimal-part [exponent-part] | infinity
          numeric-string ::=  [sign] numeric-value | [sign] nan

     当上面出现 ‘digit’ 时也允许其他十进制数码。 其中包括来自各种其他语
     言系统的十进制数码（例如阿拉伯-印地语和天城文的数码）以及全宽数码
     ‘'\uff10'’ 到 ‘'\uff19'’。

     如果 `value' 是一个 *note tuple: 486. ，它应该有三个组件，一个符号
     （ ‘0’ 表示正数或 ‘1’ 表示负数），一个数字的 *note tuple: 486. 和整
     数指数。 例如， ‘Decimal((0, (1, 4, 1, 4), -3))’ 返回
     ‘Decimal('1.414')’。

     如果 `value' 是 *note float: 188. ，则二进制浮点值无损地转换为其精
     确的十进制等效值。 此转换通常需要53位或更多位数的精度。 例如，
     ‘Decimal(float('1.1'))’ 转换为
     ‘‘Decimal(’1.100000000000000088817841970012523233890533447265625’)‘‘。

     `context' 精度不会影响存储的位数。 这完全由 `value' 中的位数决定。
     例如，‘Decimal('3.00000')’ 记录所有五个零，即使上下文精度只有三。

     `context' 参数的目的是确定 `value' 是格式错误的字符串时该怎么做。 如
     果上下文陷阱 *note InvalidOperation: 9f3.，则引发异常；否则，构造函
     数返回一个新的 Decimal，其值为 ‘NaN’。

     构造完成后， *note Decimal: 189. 对象是不可变的。

     在 3.2 版更改: 现在允许构造函数的参数为 *note float: 188. 实例。

     在 3.3 版更改: *note float: 188. 参数在设置 *note FloatOperation:
     9ed. 陷阱时引发异常。 默认情况下，陷阱已关闭。

     在 3.6 版更改: 允许下划线进行分组，就像代码中的整数和浮点文字一样。

     十进制浮点对象与其他内置数值类型共享许多属性，例如 *note float:
     188. 和 *note int: 185. 。 所有常用的数学运算和特殊方法都适用。 同
     样，十进制对象可以复制、pickle、打印、用作字典键、用作集合元素、比
     较、排序和强制转换为另一种类型（例如 *note float: 188. 或 *note
     int: 185. ）。

     算术对十进制对象和算术对整数和浮点数有一些小的差别。 当余数运算符
     ‘%’ 应用于Decimal对象时，结果的符号是 `被除数' 的符号，而不是除数的
     符号:

          >>> (-7) % 4
          1
          >>> Decimal(-7) % Decimal(4)
          Decimal('-3')

     整数除法运算符 ‘//’ 的行为类似，返回真商的整数部分（截断为零）而不
     是它的向下取整，以便保留通常的标识 ‘x == (x // y) * y + x % y’:

          >>> -7 // 4
          -2
          >>> Decimal(-7) // Decimal(4)
          Decimal('-1')

     ‘%’ 和 ‘//’ 运算符实现了 ‘remainder’ 和 ‘divide-integer’ 操作（分别
     ），如规范中所述。

     十进制对象通常不能与浮点数或 *note fractions.Fraction: 186. 实例在
     算术运算中结合使用：例如,尝试将 *note Decimal: 189. 加到 *note
     float: 188. ，将引发 *note TypeError: 193.。 但是，可以使用 Python
     的比较运算符来比较 *note Decimal: 189. 实例 ‘x’ 和另一个数字 ‘y’ 。
     这样可以避免在对不同类型的数字进行相等比较时混淆结果。

     在 3.2 版更改: 现在完全支持 *note Decimal: 189. 实例和其他数字类型
     之间的混合类型比较。

     除了标准的数字属性，十进制浮点对象还有许多专门的方法：

      -- 方法: adjusted ()

          在移出系数最右边的数字之后返回调整后的指数，直到只剩下前导数字
          ：‘Decimal('321e+5').adjusted()’ 返回 7 。 用于确定最高有效位
          相对于小数点的位置。

      -- 方法: as_integer_ratio ()

          返回一对 ‘(n, d)’ 整数，表示给定的 *note Decimal: 189. 实例作
          为分数、最简形式项并带有正分母:

               >>> Decimal('-3.14').as_integer_ratio()
               (-157, 50)

          转换是精确的。 在 Infinity 上引发 OverflowError ，在 NaN 上引
          起 ValueError 。

     3.6 新版功能.

      -- 方法: as_tuple ()

          返回一个 *note named tuple: aab. 表示的数字：
          ‘DecimalTuple(sign, digits, exponent)’。

      -- 方法: canonical ()

          返回参数的规范编码。 目前，一个 *note Decimal: 189. 实例的编码
          始终是规范的，因此该操作返回其参数不变。

      -- 方法: compare (other, context=None)

          比较两个 Decimal 实例的值。 *note compare(): 1a87. 返回一个
          Decimal 实例，如果任一操作数是 NaN ，那么结果是 NaN

               a or b is a NaN  ==> Decimal('NaN')
               a < b            ==> Decimal('-1')
               a == b           ==> Decimal('0')
               a > b            ==> Decimal('1')

      -- 方法: compare_signal (other, context=None)

          除了所有 NaN 信号之外，此操作与 *note compare(): 1a87. 方法相
          同。 也就是说，如果两个操作数都不是信令NaN，那么任何静默的 NaN
          操作数都被视为信令NaN。

      -- 方法: compare_total (other, context=None)

          使用它们的抽象表示而不是它们的数值来比较两个操作数。 类似于
          *note compare(): 1a87. 方法，但结果给出了一个总排序 *note
          Decimal: 189. 实例。 两个 *note Decimal: 189. 实例具有相同的数
          值但不同的表示形式在此排序中比较不相等：

               >>> Decimal('12.0').compare_total(Decimal('12'))
               Decimal('-1')

          静默和发出信号的 NaN 也包括在总排序中。 这个函数的结果是
          ‘Decimal('0')’ 如果两个操作数具有相同的表示，或是
          ‘Decimal('-1')’ 如果第一个操作数的总顺序低于第二个操作数，或是
          ‘Decimal('1')’ 如果第一个操作数在总顺序中高于第二个操作数。 有
          关总排序的详细信息，请参阅规范。

          此操作不受上下文影响且静默：不更改任何标志且不执行舍入。 作为
          例外，如果无法准确转换第二个操作数，则C版本可能会引发
          InvalidOperation。

      -- 方法: compare_total_mag (other, context=None)

          比较两个操作数使用它们的抽象表示而不是它们的值，如 *note
          compare_total(): 1a89.，但忽略每个操作数的符号。
          ‘x.compare_total_mag(y)’ 相当于
          ‘x.copy_abs().compare_total(y.copy_abs())’。

          此操作不受上下文影响且静默：不更改任何标志且不执行舍入。 作为
          例外，如果无法准确转换第二个操作数，则C版本可能会引发
          InvalidOperation。

      -- 方法: conjugate ()

          只返回self，这种方法只符合 Decimal 规范。

      -- 方法: copy_abs ()

          返回参数的绝对值。 此操作不受上下文影响并且是静默的：没有更改
          标志且不执行舍入。

      -- 方法: copy_negate ()

          回到参数的否定。 此操作不受上下文影响并且是静默的：没有标志更
          改且不执行舍入。

      -- 方法: copy_sign (other, context=None)

          返回第一个操作数的副本，其符号设置为与第二个操作数的符号相同。
          例如：

               >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
               Decimal('-2.3')

          此操作不受上下文影响且静默：不更改任何标志且不执行舍入。 作为
          例外，如果无法准确转换第二个操作数，则C版本可能会引发
          InvalidOperation。

      -- 方法: exp (context=None)

          返回给定数字的（自然）指数函数‘‘e**x‘‘的值。结果使用 *note
          ROUND_HALF_EVEN: 1a73. 舍入模式正确舍入。

               >>> Decimal(1).exp()
               Decimal('2.718281828459045235360287471')
               >>> Decimal(321).exp()
               Decimal('2.561702493119680037517373933E+139')

      -- 方法: from_float (f)

          将浮点数转换为十进制数的类方法。

          注意， ‘Decimal.from_float(0.1)’ 与 ‘Decimal(’0.1’)’ 不同。 由
          于 0.1 在二进制浮点中不能精确表示，因此该值存储为最接近的可表
          示值，即 ‘0x1.999999999999ap-4’ 。 十进制的等效值是
          ‘0.1000000000000000055511151231257827021181583404541015625‘。

               注解: 从 Python 3.2 开始，*note Decimal: 189. 实例也可以
               直接从 *note float: 188. 构造。

               >>> Decimal.from_float(0.1)
               Decimal('0.1000000000000000055511151231257827021181583404541015625')
               >>> Decimal.from_float(float('nan'))
               Decimal('NaN')
               >>> Decimal.from_float(float('inf'))
               Decimal('Infinity')
               >>> Decimal.from_float(float('-inf'))
               Decimal('-Infinity')

          3.1 新版功能.

      -- 方法: fma (other, third, context=None)

          混合乘法加法。 返回 self*other+third ，中间乘积 self*other 没
          有舍入。

               >>> Decimal(2).fma(3, 5)
               Decimal('11')

      -- 方法: is_canonical ()

          如果参数是规范的，则为返回 *note True: 4a1.，否则为 *note
          False: 390. 。 目前，*note Decimal: 189. 实例总是规范的，所以
          这个操作总是返回 *note True: 4a1. 。

      -- 方法: is_finite ()

          如果参数是一个有限的数，则返回为 *note True: 4a1. ；如果参数为
          无穷大或 NaN ，则返回为 *note False: 390.。

      -- 方法: is_infinite ()

          如果参数为正负无穷大，则返回为 *note True: 4a1. ，否则为 *note
          False: 390. 。

      -- 方法: is_nan ()

          如果参数为 NaN （无论是否静默），则返回为 *note True: 4a1. ，
          否则为 *note False: 390. 。

      -- 方法: is_normal (context=None)

          如果参数是一个 `标准的' 有限数则返回 *note True: 4a1.。 如果参
          数为零、次标准数、无穷大或 NaN 则返回 *note False: 390.。

      -- 方法: is_qnan ()

          如果参数为静默 NaN，返回 *note True: 4a1.，否则返回 *note
          False: 390.。

      -- 方法: is_signed ()

          如果参数带有负号，则返回为 *note True: 4a1.，否则返回 *note
          False: 390.。注意，0 和 NaN 都可带有符号。

      -- 方法: is_snan ()

          如果参数为显式 NaN，则返回 *note True: 4a1.，否则返回 *note
          False: 390.。

      -- 方法: is_subnormal (context=None)

          如果参数为次标准数，则返回 *note True: 4a1.，否则返回 *note
          False: 390.。

      -- 方法: is_zero ()

          如果参数是0（正负皆可），则返回 *note True: 4a1.，否则返回
          *note False: 390.。

      -- 方法: ln (context=None)

          返回操作数的自然对数（以 e 为底）。结果是使用 *note
          ROUND_HALF_EVEN: 1a73. 舍入模式正确舍入的。

      -- 方法: log10 (context=None)

          返回操作数的以十为底的对数。结果是使用 *note ROUND_HALF_EVEN:
          1a73. 舍入模式正确舍入的。

      -- 方法: logb (context=None)

          对于一个非零数，返回其运算数的调整后指数作为一个 *note
          Decimal: 189. 实例。 如果运算数为零将返回
          ‘Decimal('-Infinity')’ 并且产生 the *note DivisionByZero:
          1a78. 标志。如果运算数是无限大则返回 ‘Decimal('Infinity')’ 。

      -- 方法: logical_and (other, context=None)

          *note logical_and(): 1a9c. 是需要两个 `逻辑运算数' 的逻辑运算
          （参考 *note 逻辑操作数: 1a9d. ）。按位输出两运算数的 ‘and’ 运
          算的结果。

      -- 方法: logical_invert (context=None)

          *note logical_invert(): 1a9e. 是一个逻辑运算。结果是操作数的按
          位求反。

      -- 方法: logical_or (other, context=None)

          *note logical_or(): 1a9f. 是需要两个 `logical operands' 的逻辑
          运算（请参阅 *note 逻辑操作数: 1a9d. ）。结果是两个运算数的按
          位的 ‘or’ 运算。

      -- 方法: logical_xor (other, context=None)

          *note logical_xor(): 1aa0. 是需要两个 `逻辑运算数' 的逻辑运算
          （参考 *note 逻辑操作数: 1a9d. ）。结果是按位输出的两运算数的
          异或运算。

      -- 方法: max (other, context=None)

          像 ‘max(self, other)’ 一样，除了在返回之前应用上下文舍入规则并
          且用信号通知或忽略 ‘NaN’ 值（取决于上下文以及它们是发信号还是
          安静）。

      -- 方法: max_mag (other, context=None)

          与 *note max(): 1aa1. 方法相似，但是操作数使用绝对值完成比较。

      -- 方法: min (other, context=None)

          像 ‘min(self, other)’ 一样，除了在返回之前应用上下文舍入规则并
          且用信号通知或忽略 ‘NaN’ 值（取决于上下文以及它们是发信号还是
          安静）。

      -- 方法: min_mag (other, context=None)

          与 *note min(): 1aa3. 方法相似，但是操作数使用绝对值完成比较。

      -- 方法: next_minus (context=None)

          返回小于给定操作数的上下文中可表示的最大数字（或者当前线程的上
          下文中的可表示的最大数字如果没有给定上下文）。

      -- 方法: next_plus (context=None)

          返回大于给定操作数的上下文中可表示的最小数字（或者当前线程的上
          下文中的可表示的最小数字如果没有给定上下文）。

      -- 方法: next_toward (other, context=None)

          如果两运算数不相等，返回在第二个操作数的方向上最接近第一个操作
          数的数。如果两操作数数值上相等，返回将符号设置为与第二个运算数
          相同的第一个运算数的拷贝。

      -- 方法: normalize (context=None)

          通过去除尾随的零并将所有结果等于 ‘Decimal('0')’ 的转化为
          ‘Decimal('0e0')’ 来标准化数字。用于为等效类的属性生成规范值。
          比如， ‘Decimal('32.100')’ 和 ‘Decimal('0.321000e+2')’ 都被标
          准化为相同的值 ‘Decimal('32.1')’。

      -- 方法: number_class (context=None)

          返回一个字符串描述运算数的 `class' 。返回值是以下十个字符串中
          的一个。

             * ‘"-Infinity"’ ，指示运算数为负无穷大。

             * ‘"-Normal"’ ，指示该运算数是负正常数字。

             * ‘"-Subnormal"’ ，指示该运算数是负的次标准数。

             * ‘"-Zero"’ ，指示该运算数是负零。

             * ‘"-Zero"’ ，指示该运算数是正零。

             * ‘"+Subnormal"’ ，指示该运算数是正的次标准数。

             * ‘"+Normal"’ ，指示该运算数是正的标准数。

             * ‘"+Infinity"’ ，指示该运算数是正无穷。

             * ‘"NaN"’ ，指示该运算数是肃静 NaN （非数字）。

             * ‘"sNaN"’ ，指示该运算数是信号 NaN 。

      -- 方法: quantize (exp, rounding=None, context=None)

          返回的值等于舍入后的第一个运算数并且具有第二个操作数的指数。

               >>> Decimal('1.41421356').quantize(Decimal('1.000'))
               Decimal('1.414')

          与其他运算不同，如果量化运算后的系数长度大于精度，那么会发出一
          个 *note InvalidOperation: 9f3. 信号。这保证了除非有一个错误情
          况，量化指数恒等于右手运算数的指数。

          与其他运算不同，量化永不信号下溢，即使结果不正常且不精确。

          如果第二个运算数的指数大于第一个运算数的指数那或许需要舍入。在
          这种情况下，舍入模式由给定 ‘rounding’ 参数决定，其余的由给定
          ‘context’ 参数决定；如果参数都未给定，使用当前线程上下文的舍入
          模式。

          每当结果的指数大于 ‘Emax’ 或小于 ‘Etiny’ 就会返回错误。

      -- 方法: radix ()

          返回 ‘Decimal(10)’，即 *note Decimal: 189. 类进行所有算术运算
          所用的数制（基数）。 这是为保持与规范描述的兼容性而加入的。

      -- 方法: remainder_near (other, context=None)

          返回 `self' 除以 `other' 的余数。 这与 ‘self % other’ 的区别在
          于所选择的余数要使其绝对值最小化。 更准确地说，返回值为 ‘self
          - n * other’ 其中 ‘n’ 是最接近 ‘self / other’ 的实际值的整数，
          并且如果两个整数与实际值的差相等则会选择其中的偶数。

          如果结果为零则其符号将为 `self' 的符号。

               >>> Decimal(18).remainder_near(Decimal(10))
               Decimal('-2')
               >>> Decimal(25).remainder_near(Decimal(10))
               Decimal('5')
               >>> Decimal(35).remainder_near(Decimal(10))
               Decimal('-5')

      -- 方法: rotate (other, context=None)

          返回对第一个操作数的数码按第二个操作数所指定的数量进行轮转的结
          果。 第二个操作数必须为 -precision 至 precision 精度范围内的整
          数。 第二个操作数的绝对值给出要轮转的位数。 如果第二个操作数为
          正值则向左轮转；否则向右轮转。 如有必要第一个操作数的系数会在
          左侧填充零以达到 precision 所指定的长度。 第一个操作数的符号和
          指数保持不变。

      -- 方法: same_quantum (other, context=None)

          检测自身与 other 是否具有相同的指数或是否均为 ‘NaN’。

          此操作不受上下文影响且静默：不更改任何标志且不执行舍入。 作为
          例外，如果无法准确转换第二个操作数，则C版本可能会引发
          InvalidOperation。

      -- 方法: scaleb (other, context=None)

          返回第一个操作数使用第二个操作数对指数进行调整的结果。 等价于
          返回第一个操作数乘以 ‘10**other’ 的结果。 第二个操作数必须为整
          数。

      -- 方法: shift (other, context=None)

          返回第一个操作数的数码按第二个操作数所指定的数量进行移位的结果
          。 第二个操作数必须为 -precision 至 precision 范围内的整数。 第
          二个操作数的绝对值给出要移动的位数。 如果第二个操作数为正值则
          向左移位；否则向右移位。 移入系数的数码为零。 第一个操作数的符
          号和指数保持不变。

      -- 方法: sqrt (context=None)

          返回参数的平方根精确到完整精度。

      -- 方法: to_eng_string (context=None)

          转换为字符串，如果需要指数则会使用工程标注法。

          工程标注法的指数是 3 的倍数。 这会在十进制位的左边保留至多 3 个
          数码，并可能要求添加一至两个末尾零。

          例如，此方法会将 ‘Decimal('123E+1')’ 转换为
          ‘Decimal('1.23E+3')’。

      -- 方法: to_integral (rounding=None, context=None)

          与 *note to_integral_value(): 1ab3. 方法相同。 保留
          ‘to_integral’ 名称是为了与旧版本兼容。

      -- 方法: to_integral_exact (rounding=None, context=None)

          舍入到最接近的整数，发出信号 *note Inexact: 1a79. 或者如果发生
          舍入则相应地发出信号 *note Rounded: 1a7a.。 如果给出
          ‘rounding’ 形参则由其确定舍入模式，否则由给定的 ‘context’ 来确
          定。 如果没有给定任何形参则会使用当前上下文的舍入模式。

      -- 方法: to_integral_value (rounding=None, context=None)

          舍入到最接近的整数而不发出 *note Inexact: 1a79. 或 *note
          Rounded: 1a7a. 信号。 如果给出 `rounding' 则会应用其所指定的舍
          入模式；否则使用所提供的 `context' 或当前上下文的舍入方法。

* Menu:

* 逻辑操作数::


File: python.info,  Node: 逻辑操作数,  Up: Decimal 对象

5.9.4.3 逻辑操作数
..................

‘logical_and()’, ‘logical_invert()’, ‘logical_or()’ 和 ‘logical_xor()’ 方
法期望其参数为 `逻辑操作数'。 `逻辑操作数' 是指数位与符号位均为零的
*note Decimal: 189. 实例，并且其数字位均为 ‘0’ 或 ‘1’。


File: python.info,  Node: 上下文对象,  Next: 常量<4>,  Prev: Decimal 对象,  Up: decimal --- 十进制定点和浮点运算

5.9.4.4 上下文对象
..................

上下文是算术运算所在的环境。 它们管理精度、设置舍入规则、确定将哪些信号
视为异常，并限制指数的范围。

每个线程都有自己的当前上下文，可使用 *note getcontext(): 1a80. 和 *note
setcontext(): 1a81. 函数来读取或修改：

 -- 函数: decimal.getcontext ()

     返回活动线程的当前上下文。

 -- 函数: decimal.setcontext (c)

     将活动线程的当前上下文设为 `c'。

你也可以使用 *note with: 6f2. 语句和 *note localcontext(): 16ed. 函数来
临时改变活动上下文。

 -- 函数: decimal.localcontext (ctx=None)

     返回一个上下文管理器，它将在进入 with 语句时将活动线程的当前上下文
     设为 `ctx' 的一个副本并在退出 with 语句时恢复之前的上下文。 如果未
     指定上下文，则会使用当前上下文的一个副本。

     例如，以下代码会将当前 decimal 精度设为 42 位，执行一个运算，然后自
     动恢复之前的上下文:

          from decimal import localcontext

          with localcontext() as ctx:
              ctx.prec = 42   # Perform a high precision calculation
              s = calculate_something()
          s = +s  # Round the final result back to the default precision

新的上下文也可使用下述的 *note Context: 9f8. 构造器来创建。 此外，模块还
提供了三种预设的上下文:

 -- 类: decimal.BasicContext

     这是由通用十进制算术规范描述所定义的标准上下文。 精度设为九。 舍入
     设为 *note ROUND_HALF_UP: 1a74.。 清除所有旗标。 启用所有陷阱（视为
     异常），但 *note Inexact: 1a79, *note Rounded: 1a7a. 和 *note
     Subnormal: 1a7b. 除外。

     由于启用了许多陷阱，此上下文适用于进行调试。

 -- 类: decimal.ExtendedContext

     这是由通用十进制算术规范描述所定义的标准上下文。 精度设为九。 舍入
     设为 *note ROUND_HALF_EVEN: 1a73.。 清除所有旗标。 不启用任何陷阱（
     因此在计算期间不会引发异常）。

     由于禁用了陷阱，此上下文适用于希望结果值为 ‘NaN’ 或 ‘Infinity’ 而不
     是引发异常的应用。 这允许应用在出现当其他情况下会中止程序的条件时仍
     能完成运行。

 -- 类: decimal.DefaultContext

     此上下文被 *note Context: 9f8. 构造器用作新上下文的原型。 改变一个
     字段（例如精度）的效果将是改变 *note Context: 9f8. 构造器所创建的新
     上下文的默认值。

     此上下文最适用于多线程环境。 在线程开始前改变一个字段具有设置全系统
     默认值的效果。 不推荐在线程开始后改变字段，因为这会要求线程同步避免
     竞争条件。

     在单线程环境中，最好完全不使用此上下文。 而是简单地电显式创建上下文
     ，具体如下所述。

     默认值为 ‘prec’=‘28’, ‘rounding’=*note ROUND_HALF_EVEN: 1a73.，并为
     *note Overflow: 1a7c, *note InvalidOperation: 9f3. 和 *note
     DivisionByZero: 1a78. 启用陷阱。

在已提供的三种上下文之外，还可以使用 *note Context: 9f8. 构造器创建新的
上下文。

 -- 类: decimal.Context (prec=None, rounding=None, Emin=None, Emax=None,
          capitals=None, clamp=None, flags=None, traps=None)

     创建一个新上下文。 如果某个字段未指定或为 *note None: 158.，则从
     *note DefaultContext: 9f0. 拷贝默认值。 如果 `flags' 字段未指定或为
     *note None: 158.，则清空所有旗标。

     `prec' 为一个 [‘1’, *note MAX_PREC: 1ab8.] 范围内的整数，用于设置该
     上下文中算术运算的精度。

     `rounding' 选项应为 *note Rounding Modes: 1ab9. 小节中列出的常量之
     一。

     `traps' 和 `flags' 字段列出要设置的任何信号。 通常，新上下文应当只
     设置 traps 而让 flags 为空。

     `Emin' 和 `Emax' 字段给定指数所允许的外部上限。 `Emin' 必须在
     [*note MIN_EMIN: 1aba, ‘0’] 范围内，`Emax' 在 [‘0’, *note MAX_EMAX:
     1abb.] 范围内。

     `capitals' 字段为 ‘0’ 或 ‘1’ (默认值)。 如果设为 ‘1’，指数将附带打
     印大写的 ‘E’；其他情况则将使用小写的 ‘e’: ‘Decimal('6.02e+23')’。

     `clamp' 字段为 ‘0’ (默认值) 或 ‘1’。 如果设为 ‘1’，则 *note
     Decimal: 189. 实例的指数 ‘e’ 的表示范围在此上下文中将严格限制为
     ‘Emin - prec + 1 <= e <= Emax - prec + 1’。 如果 `clamp' 为 ‘0’ 则
     将适用较弱的条件: *note Decimal: 189. 实例调整后的指数最大值为
     ‘Emax’。 当 `clamp' 为 ‘1’ 时，一个较大的普通数值将在可能的情况下减
     小其指数并为其系统添加相应数量的零，以便符合指数值限制；这可以保持
     数字值但会丢失有效末尾零的信息。 例如:

          >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
          Decimal('1.23000E+999')

     `clamp' 值为 ‘1’ 时即允许与在 IEEE 754 中描述的固定宽度十进制交换格
     式保持兼容性。

     *note Context: 9f8. 类定义了几种通用方法以及大量直接在给定上下文中
     进行算术运算的方法。 此外，对于上述的每种 *note Decimal: 189. 方法
     （不包括 ‘adjusted()’ 和 ‘as_tuple()’ 方法）都有一个相应的 *note
     Context: 9f8. 方法。 例如，对于一个 *note Context: 9f8. 的实例 ‘C’
     和 *note Decimal: 189. 的实例 ‘x’，‘C.exp(x)’ 就等价于
     ‘x.exp(context=C)’。 每个 *note Context: 9f8. 方法都接受一个 Python
     整数（即 *note int: 185. 的实例）在任何接受 Decimal 的实例的地方使
     用。

      -- 方法: clear_flags ()

          将所有旗标重置为 ‘0’。

      -- 方法: clear_traps ()

          将所有陷阱重置为零 ‘0’。

          3.3 新版功能.

      -- 方法: copy ()

          返回上下文的一个副本。

      -- 方法: copy_decimal (num)

          返回 Decimal 实例 num 的一个副本。

      -- 方法: create_decimal (num)

          基于 `num' 创建一个新 Decimal 实例但使用 `self' 作为上下文。 与
          *note Decimal: 189. 构造器不同，该上下文的精度、舍入方法、旗标
          和陷阱会被应用于转换过程。

          此方法很有用处，因为常量往往被给予高于应用所需的精度。 另一个
          好处在于立即执行舍入可以消除超出当前精度的数位所导致的意外效果
          。 在下面的示例中，使用未舍入的输入意味着在总和中添加零会改变
          结果：

               >>> getcontext().prec = 3
               >>> Decimal('3.4445') + Decimal('1.0023')
               Decimal('4.45')
               >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
               Decimal('4.44')

          此方法实现了 IBM 规格描述中的转换为数字操作。 如果参数为字符串
          ，则不允许有开头或末尾的空格或下划线。

      -- 方法: create_decimal_from_float (f)

          基于浮点数 `f' 创建一个新的 Decimal 实例，但会使用 `self' 作为
          上下文来执行舍入。 与 *note Decimal.from_float(): b88. 类方法
          不同，上下文的精度、舍入方法、旗标和陷阱会应用到转换中。

               >>> context = Context(prec=5, rounding=ROUND_DOWN)
               >>> context.create_decimal_from_float(math.pi)
               Decimal('3.1415')
               >>> context = Context(prec=5, traps=[Inexact])
               >>> context.create_decimal_from_float(math.pi)
               Traceback (most recent call last):
                   ...
               decimal.Inexact: None

          3.1 新版功能.

      -- 方法: Etiny ()

          返回一个等于 ‘Emin - prec + 1’ 的值即次标准化结果中的最小指数
          值。 当发生向下溢出时，指数会设为 *note Etiny: 1ac1.。

      -- 方法: Etop ()

          返回一个等于 ‘Emax - prec + 1’ 的值。

     使用 decimal 的通常方式是创建 *note Decimal: 189. 实例然后对其应用
     算术运算,这些运算发生在活动线程的当前上下文中。 一种替代方式则是使
     用上下文的方法在特定上下文中进行计算。 这些方法类似于 *note
     Decimal: 189. 类的方法，在此仅简单地重新列出。

      -- 方法: abs (x)

          返回 `x' 的绝对值。

      -- 方法: add (x, y)

          返回 `x' 与 `y' 的和。

      -- 方法: canonical (x)

          返回相同的 Decimal 对象 `x'。

      -- 方法: compare (x, y)

          对 `x' 与 `y' 进行数值比较。

      -- 方法: compare_signal (x, y)

          对两个操作数进行数值比较。

      -- 方法: compare_total (x, y)

          对两个操作数使用其抽象表示进行比较。

      -- 方法: compare_total_mag (x, y)

          对两个操作数使用其抽象表示进行比较，忽略符号。

      -- 方法: copy_abs (x)

          返回 `x' 的副本，符号设为 0。

      -- 方法: copy_negate (x)

          返回 `x' 的副本，符号取反。

      -- 方法: copy_sign (x, y)

          从 `y' 拷贝符号至 `x'。

      -- 方法: divide (x, y)

          返回 `x' 除以 `y' 的结果。

      -- 方法: divide_int (x, y)

          返回 `x' 除以 `y' 的结果，截短为整数。

      -- 方法: divmod (x, y)

          两个数字相除并返回结果的整数部分。

      -- 方法: exp (x)

          返回 ‘e ** x’。

      -- 方法: fma (x, y, z)

          返回 `x' 乘以 `y' 再加 `z' 的结果。

      -- 方法: is_canonical (x)

          如果 `x' 是规范的则返回 ‘True’；否则返回 ‘False’。

      -- 方法: is_finite (x)

          如果 `x' 为有限的则返回‘‘True‘‘；否则返回 ‘False’。

      -- 方法: is_infinite (x)

          如果 `x' 是无限的则返回 ‘True’；否则返回 ‘False’。

      -- 方法: is_nan (x)

          如果 `x' 是 qNaN 或 sNaN 则返回 ‘True’；否则返回 ‘False’。

      -- 方法: is_normal (x)

          如果 `x' 是标准数则返回 ‘True’；否则返回 ‘False’。

      -- 方法: is_qnan (x)

          如果 `x' 是静默 NaN 则返回 ‘True’；否则返回 ‘False’。

      -- 方法: is_signed (x)

          `x' 是负数则返回 ‘True’；否则返回 ‘False’。

      -- 方法: is_snan (x)

          如果 `x' 是显式 NaN 则返回 ‘True’；否则返回 ‘False’。

      -- 方法: is_subnormal (x)

          如果 `x' 是次标准数则返回 ‘True’；否则返回 ‘False’。

      -- 方法: is_zero (x)

          如果 `x' 为零则返回 ‘True’；否则返回 ‘False’。

      -- 方法: ln (x)

          返回 `x' 的自然对数（以 e 为底）。

      -- 方法: log10 (x)

          返回 `x' 的以 10 为底的对数。

      -- 方法: logb (x)

          返回操作数的 MSD 等级的指数。

      -- 方法: logical_and (x, y)

          在操作数的每个数位间应用逻辑运算 `and'。

      -- 方法: logical_invert (x)

          反转 `x' 中的所有数位。

      -- 方法: logical_or (x, y)

          在操作数的每个数位间应用逻辑运算 `or'。

      -- 方法: logical_xor (x, y)

          在操作数的每个数位间应用逻辑运算 `xor'。

      -- 方法: max (x, y)

          对两个值执行数字比较并返回其中的最大值。

      -- 方法: max_mag (x, y)

          对两个值执行忽略正负号的数字比较。

      -- 方法: min (x, y)

          对两个值执行数字比较并返回其中的最小值。

      -- 方法: min_mag (x, y)

          对两个值执行忽略正负号的数字比较。

      -- 方法: minus (x)

          对应于 Python 中的单目前缀取负运算符执行取负操作。

      -- 方法: multiply (x, y)

          返回 `x' 和 `y' 的积。

      -- 方法: next_minus (x)

          返回小于 `x' 的最大数字表示形式。

      -- 方法: next_plus (x)

          返回大于 `x' 的最小数字表示形式。

      -- 方法: next_toward (x, y)

          返回 `x' 趋向于 `y' 的最接近的数字。

      -- 方法: normalize (x)

          将 `x' 改写为最简形式。

      -- 方法: number_class (x)

          返回 `x' 的类的表示。

      -- 方法: plus (x)

          对应于 Python 中的单目前缀取正运算符执行取正操作。 此操作将应
          用上下文精度和舍入，因此它 `不是' 标识运算。

      -- 方法: power (x, y, modulo=None)

          返回 ‘x’ 的 ‘y’ 次方，如果给出了模数 ‘modulo’ 则取其余数。

          如为两个参数则计算 ‘x**y’。 如果 ‘x’ 为负值则 ‘y’ 必须为整数。
          除非 ‘y’ 为整数且结果为有限值并可在 ’precision’ 位内精确表示否
          则结果将是不精确的。 上下文的舍入模式将被使用。 结果在 Python
          版中总是会被正确地舍入。

          ‘Decimal(0) ** Decimal(0)’ 结果为 ‘InvalidOperation’，而如果
          ‘InvalidOperation’ 未被捕获，则结果为 ‘Decimal('NaN')’。

          在 3.3 版更改: C 模块计算 *note power(): 1aed. 时会使用已正确
          舍入的 *note exp(): 1acf. 和 *note ln(): 1ada. 函数。 结果是经
          过良好定义的，但仅限于“几乎总是正确地舍入”。

          带有三个参数时，计算 ‘(x**y) % modulo’。 对于三个参数的形式，
          参数将会应用以下限制：

                  - 三个参数必须都是整数

                  - ‘y’ 必须是非负数

                  - ‘x’ 或 ‘y’ 至少有一个不为零

                  - ‘modulo’ 必须不为零且至多有 ’precision’ 位

          来自 ‘Context.power(x, y, modulo)’ 的结果值等于使用无限精度计
          算 ‘(x**y) % modulo’ 所得到的值，但其计算过程更高效。 结果的指
          数为零，无论 ‘x’, ‘y’ 和 ‘modulo’ 的指数是多少。 结果值总是完
          全精确的。

      -- 方法: quantize (x, y)

          返回的值等于 `x' (舍入后)，并且指数为 `y'。

      -- 方法: radix ()

          恰好返回 10，因为这是 Decimal 对象 :)

      -- 方法: remainder (x, y)

          返回整除所得到的余数。

          结果的符号，如果不为零，则与原始除数的符号相同。

      -- 方法: remainder_near (x, y)

          返回 ‘x - y * n’，其中 `n' 为最接近 ‘x / y’ 实际值的整数（如结
          果为 0 则其符号将与 `x' 的符号相同）。

      -- 方法: rotate (x, y)

          返回 `x' 翻转 `y' 次的副本。

      -- 方法: same_quantum (x, y)

          如果两个操作数具有相同的指数则返回 ‘True’。

      -- 方法: scaleb (x, y)

          返回第一个操作数添加第二个值的指数后的结果。

      -- 方法: shift (x, y)

          返回 `x' 变换 `y' 次的副本。

      -- 方法: sqrt (x)

          非负数基于上下文精度的平方根。

      -- 方法: subtract (x, y)

          返回 `x' 和 `y' 的差。

      -- 方法: to_eng_string (x)

          转换为字符串，如果需要指数则会使用工程标注法。

          工程标注法的指数是 3 的倍数。 这会在十进制位的左边保留至多 3 个
          数码，并可能要求添加一至两个末尾零。

      -- 方法: to_integral_exact (x)

          舍入到一个整数。

      -- 方法: to_sci_string (x)

          使用科学计数法将一个数字转换为字符串。


File: python.info,  Node: 常量<4>,  Next: 舍入模式,  Prev: 上下文对象,  Up: decimal --- 十进制定点和浮点运算

5.9.4.5 常量
............

本节中的常量仅与 C 模块相关。 它们也被包含在纯 Python 版本以保持兼容性。

                          32位                      64位
                                                    
----------------------------------------------------------------------------------------
                                                    
 -- 数据:                 ‘425000000’               ‘999999999999999999’
          decimal.MAX_PREC                          

 -- 数据:                 ‘425000000’               ‘999999999999999999’
          decimal.MAX_EMAX                          

 -- 数据:                 ‘-425000000’              ‘-999999999999999999’
          decimal.MIN_EMIN                          

 -- 数据:                 ‘-849999999’              ‘-1999999999999999997’
          decimal.MIN_ETINY                         

 -- 数据: decimal.HAVE_THREADS

     该值为 ‘True’。 已弃用，因为 Python 现在总是启用线程。

3.9 版后已移除.

 -- 数据: decimal.HAVE_CONTEXTVAR

     默认值为 ‘True’。 如果 Python 的编译带有
     ‘--without-decimal-contextvar’ 选项，则 C 版本会使用线程局部而不是
     协程局部上下文并且该值为 ‘False’。 这在某些嵌套上下文场景中将稍快一
     些。

3.9 新版功能: 向下移植到 3.7 和 3.8


File: python.info,  Node: 舍入模式,  Next: 信号,  Prev: 常量<4>,  Up: decimal --- 十进制定点和浮点运算

5.9.4.6 舍入模式
................

 -- 数据: decimal.ROUND_CEILING

     舍入方向为 ‘Infinity’。

 -- 数据: decimal.ROUND_DOWN

     舍入方向为零。

 -- 数据: decimal.ROUND_FLOOR

     舍入方向为 ‘-Infinity’。

 -- 数据: decimal.ROUND_HALF_DOWN

     舍入到最接近的数，同样接近则舍入方向为零。

 -- 数据: decimal.ROUND_HALF_EVEN

     舍入到最接近的数，同样接近则舍入到最接近的偶数。

 -- 数据: decimal.ROUND_HALF_UP

     舍入到最接近的数，同样接近则舍入到零的反方向。

 -- 数据: decimal.ROUND_UP

     舍入到零的反方向。

 -- 数据: decimal.ROUND_05UP

     如果最后一位朝零的方向舍入后为 0 或 5 则舍入到零的反方向；否则舍入
     方向为零。


File: python.info,  Node: 信号,  Next: 浮点数说明,  Prev: 舍入模式,  Up: decimal --- 十进制定点和浮点运算

5.9.4.7 信号
............

信号代表在计算期间引发的条件。 每个信号对应于一个上下文旗标和一个上下文
陷阱启用器。

上下文旗标将在遇到特定条件时被设定。 在完成计算之后，将为了获得信息而检
测旗标（例如确定计算是否精确）。 在检测旗标后，请确保在开始下一次计算之
前清除所有旗标。

如果为信号设定了上下文的陷阱启用器，则条件会导致特定的 Python 异常被引发
。 举例来说，如果设定了 *note DivisionByZero: 1a78. 陷阱，则当遇到此条件
时就将引发 *note DivisionByZero: 1a78. 异常。

 -- 类: decimal.Clamped

     修改一个指数以符合表示限制。

     通常，限位将在一个指数超出上下文的 ‘Emin’ 和 ‘Emax’ 限制时发生。 在
     可能的情况下，会通过给系数添加零来将指数缩减至符合限制。

 -- 类: decimal.DecimalException

     其他信号的基类，并且也是 *note ArithmeticError: 170e. 的一个子类。

 -- 类: decimal.DivisionByZero

     非无限数被零除的信号。

     可在除法、取余队法或对一个数求负数次幂时发生。 如果此信号未被陷阱捕
     获，则返回 ‘Infinity’ 或 ‘-Infinity’ 并且由对计算的输入来确定正负符
     号。

 -- 类: decimal.Inexact

     表明发生了舍入且结果是不精确的。

     有非零数位在舍入期间被丢弃的信号。 舍入结果将被返回。 此信号旗标或
     陷阱被用于检测结果不精确的情况。

 -- 类: decimal.InvalidOperation

     执行了一个无效的操作。

     表明请求了一个无意义的操作。 如未被陷阱捕获则返回 ‘NaN’。 可能的原
     因包括:

          Infinity - Infinity
          0 * Infinity
          Infinity / Infinity
          x % 0
          Infinity % x
          sqrt(-x) and x > 0
          0 ** 0
          x ** (non-integer)
          x ** Infinity

 -- 类: decimal.Overflow

     数值的溢出。

     表明在发生舍入之后的指数大于 ‘Emax’。 如果未被陷阱捕获，则结果将取
     决于舍入模式，或者向下舍入为最大的可表示有限数，或者向上舍入为
     ‘Infinity’。 无论哪种情况，都将引发 *note Inexact: 1a79. 和 *note
     Rounded: 1a7a. 信号。

 -- 类: decimal.Rounded

     发生了舍入，但或许并没有信息丢失。

     一旦舍入丢弃了数位就会发出此信号；即使被丢弃的数位是零 (例如将
     ‘5.00’ 舍入为 ‘5.0’)。 如果未被陷阱捕获，则不经修改地返回结果。 此
     信号用于检测有效位数的丢弃。

 -- 类: decimal.Subnormal

     在舍入之前指数低于 ‘Emin’。

     当操作结果是次标准数（即指数过小）时就会发出此信号。 如果未被陷阱捕
     获，则不经修改过返回结果。

 -- 类: decimal.Underflow

     数字向下溢出导致结果舍入到零。

     当一个次标准数结果通过舍入转为零时就会发出此信号。 同时还将引发
     *note Inexact: 1a79. 和 *note Subnormal: 1a7b. 信号。

 -- 类: decimal.FloatOperation

     为 float 和 Decimal 的混合启用更严格的语义。

     如果信号未被捕获（默认），则在 *note Decimal: 189. 构造器、*note
     create_decimal(): 9f4. 和所有比较运算中允许 float 和 Decimal 的混合
     。 转换和比较都是完全精确的。 发生的任何混合运算都将通过在上下文旗
     标中设置 *note FloatOperation: 9ed. 来静默地记录。 通过 *note
     from_float(): b88. 或 *note create_decimal_from_float(): 1ac0. 进行
     显式转换则不会设置旗标。

     在其他情况下（即信号被捕获），则只静默执行相等性比较和显式转换。 所
     有其他混合运算都将引发 *note FloatOperation: 9ed.。

以下表格总结了信号的层级结构:

     exceptions.ArithmeticError(exceptions.Exception)
         DecimalException
             Clamped
             DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
             Inexact
                 Overflow(Inexact, Rounded)
                 Underflow(Inexact, Rounded, Subnormal)
             InvalidOperation
             Rounded
             Subnormal
             FloatOperation(DecimalException, exceptions.TypeError)


File: python.info,  Node: 浮点数说明,  Next: 使用线程,  Prev: 信号,  Up: decimal --- 十进制定点和浮点运算

5.9.4.8 浮点数说明
..................

* Menu:

* 通过提升精度来解决舍入错误::
* 特殊的值::


File: python.info,  Node: 通过提升精度来解决舍入错误,  Next: 特殊的值,  Up: 浮点数说明

5.9.4.9 通过提升精度来解决舍入错误
..................................

使用十进制浮点数可以消除十进制表示错误（即能够完全精确地表示 ‘0.1’ 这样
的数）；然而，某些运算在非零数位超出给定的精度时仍然可能导致舍入错误。

舍入错误的影响可能因接近相互抵销的加减运算被放大从而导致丢失有效位。
Knuth 提供了两个指导性示例，其中出现了精度不足的浮点算术舍入，导致加法的
交换律和分配律被打破：

     # Examples from Seminumerical Algorithms, Section 4.2.2.
     >>> from decimal import Decimal, getcontext
     >>> getcontext().prec = 8

     >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
     >>> (u + v) + w
     Decimal('9.5111111')
     >>> u + (v + w)
     Decimal('10')

     >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
     >>> (u*v) + (u*w)
     Decimal('0.01')
     >>> u * (v+w)
     Decimal('0.0060000')

*note decimal: 36. 模块则可以通过充分地扩展精度来避免有效位的丢失：

     >>> getcontext().prec = 20
     >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
     >>> (u + v) + w
     Decimal('9.51111111')
     >>> u + (v + w)
     Decimal('9.51111111')
     >>>
     >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
     >>> (u*v) + (u*w)
     Decimal('0.0060000')
     >>> u * (v+w)
     Decimal('0.0060000')


File: python.info,  Node: 特殊的值,  Prev: 通过提升精度来解决舍入错误,  Up: 浮点数说明

5.9.4.10 特殊的值
.................

*note decimal: 36. 模块的数字系统提供了一些特殊的值，包括 ‘NaN’, ‘sNaN’,
‘-Infinity’, ‘Infinity’ 以及两种零值 ‘+0’ 和 ‘-0’。

无穷大可以使用 ‘Decimal('Infinity')’ 来构建。 它们也可以在不捕获 *note
DivisionByZero: 1a78. 信号捕获时通过除以零来产生。 类似地，当不捕获
*note Overflow: 1a7c. 信号时，也可以通过舍入到超出最大可表示数字限制的方
式产生无穷大的结果。

无穷大是有符号的（仿射）并可用于算术运算，它们会被当作极其巨大的不确定数
字来处理。 例如，无穷大加一个常量结果也将为无穷大。

某些不存在有效结果的运算将会返回 ‘NaN’，或者如果捕获了 *note
InvalidOperation: 9f3. 信号则会引发一个异常。 例如，‘0/0’ 会返回 ‘NaN’ 表
示结果“不是一个数字”。 这样的 ‘NaN’ 是静默产生的，并且在产生之后参与其它
计算时总是会得到 ‘NaN’ 的结果。 这种行为对于偶而缺少输入的各类计算都很有
用处 — 它允许在将特定结果标记为无效的同时让计算继续运行。

另一种变体形式是 ‘sNaN’，它在每次运算后会发出信号而不是保持静默。 当对于
无效结果需要中断计算进行特别处理时，这是一个很有用的返回值。

Python 中比较运算符的行为在涉及 ‘NaN’ 时可能会令人有点惊讶。 相等性检测
在操作数中有静默型或信号型 ‘NaN’ 时总是会返回 *note False: 390. (即使是
执行 ‘Decimal('NaN')==Decimal('NaN')’)，而不等性检测总是会返回 *note
True: 4a1.。 当尝试使用 ‘<’, ‘<=’, ‘>’ 或 ‘>=’ 运算符中的任何一个来比较
两个 Decimal 值时，如果运算数中有 ‘NaN’ 则将引发 *note InvalidOperation:
9f3. 信号，如果此信号未被捕获则将返回 *note False: 390.。 请注意通用十进
制算术规范并未规定直接比较行为；这些涉及 ‘NaN’ 的比较规则来自于 IEEE 854
标准 (见第 5.7 节表 3)。 要确保严格符合标准，请改用 ‘compare()’ 和
‘compare-signal()’ 方法。

有符号零值可以由向下溢出的运算产生。 它们保留符号是为了让运算结果能以更
高的精度传递。 由于它们的大小为零，正零和负零会被视为相等，且它们的符号
具有信息。

在这两个不相同但却相等的有符号零之外，还存在几种零的不同表示形式，它们的
精度不同但值也都相等。 这需要一些时间来逐渐适应。 对于习惯了标准浮点表示
形式的眼睛来说，以下运算返回等于零的值并不是显而易见的：

     >>> 1 / Decimal('Infinity')
     Decimal('0E-1000026')


File: python.info,  Node: 使用线程,  Next: 例程,  Prev: 浮点数说明,  Up: decimal --- 十进制定点和浮点运算

5.9.4.11 使用线程
.................

*note getcontext(): 1a80. 函数会为每个线程访问不同的 *note Context: 9f8.
对象。 具有单独线程上下文意味着线程可以修改上下文 (例如
‘getcontext().prec=10’) 而不影响其他线程。

类似的 *note setcontext(): 1a81. 会为当前上下文的目标自动赋值。

如果在调用 *note setcontext(): 1a81. 之前调用了 *note getcontext():
1a80.，则 *note getcontext(): 1a80. 将自动创建一个新的上下文在当前线程中
使用。

新的上下文拷贝自一个名为 `DefaultContext' 的原型上下文。 要控制默认值以
便每个线程在应用运行期间都使用相同的值，可以直接修改 `DefaultContext' 对
象。 这应当在任何线程启动 `之前' 完成以使得调用 *note getcontext():
1a80. 的线程之间不会产生竞争条件。 例如:

     # Set applicationwide defaults for all threads about to be launched
     DefaultContext.prec = 12
     DefaultContext.rounding = ROUND_DOWN
     DefaultContext.traps = ExtendedContext.traps.copy()
     DefaultContext.traps[InvalidOperation] = 1
     setcontext(DefaultContext)

     # Afterwards, the threads can be started
     t1.start()
     t2.start()
     t3.start()
      . . .


File: python.info,  Node: 例程,  Next: Decimal 常见问题,  Prev: 使用线程,  Up: decimal --- 十进制定点和浮点运算

5.9.4.12 例程
.............

以下是一些用作工具函数的例程，它们演示了使用 *note Decimal: 189. 类的各
种方式:

     def moneyfmt(value, places=2, curr='', sep=',', dp='.',
                  pos='', neg='-', trailneg=''):
         """Convert Decimal to a money formatted string.

         places:  required number of places after the decimal point
         curr:    optional currency symbol before the sign (may be blank)
         sep:     optional grouping separator (comma, period, space, or blank)
         dp:      decimal point indicator (comma or period)
                  only specify as blank when places is zero
         pos:     optional sign for positive numbers: '+', space or blank
         neg:     optional sign for negative numbers: '-', '(', space or blank
         trailneg:optional trailing minus indicator:  '-', ')', space or blank

         >>> d = Decimal('-1234567.8901')
         >>> moneyfmt(d, curr='$')
         '-$1,234,567.89'
         >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
         '1.234.568-'
         >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
         '($1,234,567.89)'
         >>> moneyfmt(Decimal(123456789), sep=' ')
         '123 456 789.00'
         >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
         '<0.02>'

         """
         q = Decimal(10) ** -places      # 2 places --> '0.01'
         sign, digits, exp = value.quantize(q).as_tuple()
         result = []
         digits = list(map(str, digits))
         build, next = result.append, digits.pop
         if sign:
             build(trailneg)
         for i in range(places):
             build(next() if digits else '0')
         if places:
             build(dp)
         if not digits:
             build('0')
         i = 0
         while digits:
             build(next())
             i += 1
             if i == 3 and digits:
                 i = 0
                 build(sep)
         build(curr)
         build(neg if sign else pos)
         return ''.join(reversed(result))

     def pi():
         """Compute Pi to the current precision.

         >>> print(pi())
         3.141592653589793238462643383

         """
         getcontext().prec += 2  # extra digits for intermediate steps
         three = Decimal(3)      # substitute "three=3.0" for regular floats
         lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
         while s != lasts:
             lasts = s
             n, na = n+na, na+8
             d, da = d+da, da+32
             t = (t * n) / d
             s += t
         getcontext().prec -= 2
         return +s               # unary plus applies the new precision

     def exp(x):
         """Return e raised to the power of x.  Result type matches input type.

         >>> print(exp(Decimal(1)))
         2.718281828459045235360287471
         >>> print(exp(Decimal(2)))
         7.389056098930650227230427461
         >>> print(exp(2.0))
         7.38905609893
         >>> print(exp(2+0j))
         (7.38905609893+0j)

         """
         getcontext().prec += 2
         i, lasts, s, fact, num = 0, 0, 1, 1, 1
         while s != lasts:
             lasts = s
             i += 1
             fact *= i
             num *= x
             s += num / fact
         getcontext().prec -= 2
         return +s

     def cos(x):
         """Return the cosine of x as measured in radians.

         The Taylor series approximation works best for a small value of x.
         For larger values, first compute x = x % (2 * pi).

         >>> print(cos(Decimal('0.5')))
         0.8775825618903727161162815826
         >>> print(cos(0.5))
         0.87758256189
         >>> print(cos(0.5+0j))
         (0.87758256189+0j)

         """
         getcontext().prec += 2
         i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
         while s != lasts:
             lasts = s
             i += 2
             fact *= i * (i-1)
             num *= x * x
             sign *= -1
             s += num / fact * sign
         getcontext().prec -= 2
         return +s

     def sin(x):
         """Return the sine of x as measured in radians.

         The Taylor series approximation works best for a small value of x.
         For larger values, first compute x = x % (2 * pi).

         >>> print(sin(Decimal('0.5')))
         0.4794255386042030002732879352
         >>> print(sin(0.5))
         0.479425538604
         >>> print(sin(0.5+0j))
         (0.479425538604+0j)

         """
         getcontext().prec += 2
         i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
         while s != lasts:
             lasts = s
             i += 2
             fact *= i * (i-1)
             num *= x * x
             sign *= -1
             s += num / fact * sign
         getcontext().prec -= 2
         return +s


File: python.info,  Node: Decimal 常见问题,  Prev: 例程,  Up: decimal --- 十进制定点和浮点运算

5.9.4.13 Decimal 常见问题
.........................

Q. 总是输入 ‘decimal.Decimal('1234.5')’ 是否过于笨拙。 在使用交互解释器
时有没有最小化输入量的方式？

A. 有些用户会将构造器简写为一个字母：

     >>> D = decimal.Decimal
     >>> D('1.23') + D('3.45')
     Decimal('4.68')

Q. 在带有两个十进制位的定点数应用中，有些输入值具有许多位，需要被舍入。
另一些数则不应具有多余位，需要验证有效性。 这种情况应该用什么方法？

A. 用 ‘quantize()’ 方法舍入到固定数量的十进制位。 如果设置了 *note
Inexact: 1a79. 陷阱，它也适用于验证有效性：

     >>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')

     >>> # Round to two places
     >>> Decimal('3.214').quantize(TWOPLACES)
     Decimal('3.21')

     >>> # Validate that a number does not exceed two places
     >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
     Decimal('3.21')

     >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
     Traceback (most recent call last):
        ...
     Inexact: None

Q. 当我使用两个有效位的输入时，我要如何在一个应用中保持有效位不变？

A. 某些运算例如与整数相加、相减和相乘将会自动保留固定的小数位数。 其他运
算，例如相除和非整数相乘则将会改变小数位数，需要再加上 ‘quantize()’ 处理
步骤：

     >>> a = Decimal('102.72')           # Initial fixed-point values
     >>> b = Decimal('3.17')
     >>> a + b                           # Addition preserves fixed-point
     Decimal('105.89')
     >>> a - b
     Decimal('99.55')
     >>> a * 42                          # So does integer multiplication
     Decimal('4314.24')
     >>> (a * b).quantize(TWOPLACES)     # Must quantize non-integer multiplication
     Decimal('325.62')
     >>> (b / a).quantize(TWOPLACES)     # And quantize division
     Decimal('0.03')

在开发定点数应用时，更方便的做法是定义处理 ‘quantize()’ 步骤的函数：

     >>> def mul(x, y, fp=TWOPLACES):
     ...     return (x * y).quantize(fp)
     >>> def div(x, y, fp=TWOPLACES):
     ...     return (x / y).quantize(fp)

     >>> mul(a, b)                       # Automatically preserve fixed-point
     Decimal('325.62')
     >>> div(b, a)
     Decimal('0.03')

Q. 表示同一个值有许多方式。 数字 ‘200’, ‘200.000’, ‘2E2’ 和 ‘02E+4’ 的值
都相同但有精度不同。 是否有办法将它们转换为一个可识别的规范值？

A. ‘normalize()’ 方法可将所有相同的值映射为统一表示形式：

     >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
     >>> [v.normalize() for v in values]
     [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]

Q. 有些十进制值总是被打印为指数表示形式。 是否有办法得到一个非指数表示形
式？

A. 对于某些值来说，指数表示形式是表示系数中有效位的唯一办法。 例如，将
‘5.0E+3’ 表示为 ‘5000’ 可以让值保持恒定，但是无法显示原本的两位有效数字
。

如果一个应用不必关心追踪有效位，则可以很容易地移除指数和末尾的零，丢弃有
效位但让值保持不变：

     >>> def remove_exponent(d):
     ...     return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()

     >>> remove_exponent(Decimal('5E+3'))
     Decimal('5000')

Q. 是否有办法将一个普通浮点数转换为 *note Decimal: 189.？

A. 是的，任何二进制浮点数都可以精确地表示为 Decimal 值，但完全精确的转换
可能需要比平常感觉更高的精度：

     >>> Decimal(math.pi)
     Decimal('3.141592653589793115997963468544185161590576171875')

Q. 在一个复杂的计算中，我怎样才能保证不会得到由精度不足和舍入异常所导致
的虚假结果。

A. 使用 decimal 模块可以很容易地检测结果。 最好的做法是使用更高的精度和
不同的舍入模式重新进行计算。 明显不同的结果表明存在精度不足、舍入模式问
题、不符合条件的输入或是结果不稳定的算法。

Q. 我发现上下文精度的应用只针对运算结果而不针对输入。在混合使用不同精度
的值时有什么需要注意的吗？

A. 是的。 原则上所有值都会被视为精确值，在这些值上进行的算术运算也是如此
。 只有结果会被舍入。 对于输入来说其好处是“所输入即所得”。 而其缺点则是
如果你忘记了输入没有被舍入，结果看起来可能会很奇怪：

     >>> getcontext().prec = 3
     >>> Decimal('3.104') + Decimal('2.104')
     Decimal('5.21')
     >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
     Decimal('5.20')

解决办法是提高精度或使用单目加法运算对输入执行强制舍入：

     >>> getcontext().prec = 3
     >>> +Decimal('1.23456789')      # unary plus triggers rounding
     Decimal('1.23')

此外，还可以使用 *note Context.create_decimal(): 9f4. 方法在创建输入时执
行舍入：

     >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
     Decimal('1.2345')

Q. CPython 实现对于巨大数字是否足够快速？

A. 是的，在 CPython 和 PyPy3 实现中，decimal 模块的 C/CFFI 版本集成了高
速 libmpdec(1) 库用于实现任意精度正确舍入的十进制浮点算术。 ‘libmpdec’ 会
对中等的数字使用 Karatsuba 乘法(2) 而对非常巨大的数字使用 数字原理变换
(3) 。 但是，想要实现这种性能提升，需要对未舍入的运算设置上下文。

     >>> c = getcontext()
     >>> c.prec = MAX_PREC
     >>> c.Emax = MAX_EMAX
     >>> c.Emin = MIN_EMIN

3.3 新版功能.

   ---------- Footnotes ----------

   (1) https://www.bytereef.org/mpdecimal/doc/libmpdec/index.html

   (2) https://en.wikipedia.org/wiki/Karatsuba_algorithm

   (3) 
https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general)#Number-theoretic_transform


File: python.info,  Node: fractions --- 分数,  Next: random --- 生成伪随机数,  Prev: decimal --- 十进制定点和浮点运算,  Up: 数字和数学模块

5.9.5 ‘fractions’ — 分数
------------------------

`源代码' Lib/fractions.py(1)

__________________________________________________________________

*note fractions: 83. 模块支持分数运算。

分数实例可以由一对整数，一个分数，或者一个字符串构建而成。

 -- 类: fractions.Fraction (numerator=0, denominator=1)

 -- 类: fractions.Fraction (other_fraction)

 -- 类: fractions.Fraction (float)

 -- 类: fractions.Fraction (decimal)

 -- 类: fractions.Fraction (string)

     第一个版本要求 `numerator' 和 `denominator' 是 *note
     numbers.Rational: c60. 的实例，并返回一个新的 *note Fraction: 186.
     实例，其值为 ‘numerator/denominator’。 如果 `denominator' 为 ‘0’ 将
     会引发 *note ZeroDivisionError: 12bd.。 第二个版本要求
     `other_fraction' 是 *note numbers.Rational: c60. 的实例，并返回一个
     *note Fraction: 186. 实例且与传入值相等。 下两个版本接受 *note
     float: 188. 或 *note decimal.Decimal: 189. 的实例，并返回一个 *note
     Fraction: 186. 实例且与传入值完全相等。 请注意由于二进制浮点数通常
     存在的问题 (参见 *note 浮点算术：争议和限制: 1332.)，
     ‘Fraction(1.1)’ 的参数并不会精确等于 11/10，因此 ‘Fraction(1.1)’ 也
     `不会' 返回用户所期望的 ‘Fraction(11, 10)’。 （请参阅下文中 *note
     limit_denominator(): 1b0e. 方法的文档。） 构造器的最后一个版本接受
     一个字符串或 unicode 实例。 此实例的通常形式为:

          [sign] numerator ['/' denominator]

     其中的可选项 ‘sign’ 可以为 ’+’ 或 ’-’ 并且 ‘numerator’ 和
     ‘denominator’ (如果存在) 是十进制数码的字符串。 此外，*note float:
     188. 构造器所接受的任何表示一个有限值的字符串也都为 *note Fraction:
     186. 构造器所接受。 不论哪种形式的输入字符串也都可以带有前缀和/或后
     缀的空格符。 这里是一些示例:

          >>> from fractions import Fraction
          >>> Fraction(16, -10)
          Fraction(-8, 5)
          >>> Fraction(123)
          Fraction(123, 1)
          >>> Fraction()
          Fraction(0, 1)
          >>> Fraction('3/7')
          Fraction(3, 7)
          >>> Fraction(' -3/7 ')
          Fraction(-3, 7)
          >>> Fraction('1.414213 \t\n')
          Fraction(1414213, 1000000)
          >>> Fraction('-.125')
          Fraction(-1, 8)
          >>> Fraction('7e-6')
          Fraction(7, 1000000)
          >>> Fraction(2.25)
          Fraction(9, 4)
          >>> Fraction(1.1)
          Fraction(2476979795053773, 2251799813685248)
          >>> from decimal import Decimal
          >>> Fraction(Decimal('1.1'))
          Fraction(11, 10)

     *note Fraction: 186. 类继承自抽象基类 *note numbers.Rational: c60.，
     并实现了该类的所有方法和操作。 *note Fraction: 186. 实例是可哈希的
     ，并应当被视为不可变对象。 此外，*note Fraction: 186. 还具有以下属
     性和方法：

     在 3.2 版更改: *note Fraction: 186. 构造器现在接受 *note float:
     188. 和 *note decimal.Decimal: 189. 实例。

      -- 属性: numerator

          最简分数形式的分子。

      -- 属性: denominator

          最简分数形式的分母。

      -- 方法: as_integer_ratio ()

          返回由两个整数组成的元组，两数之比等于该分数的值且其分母为正数
          。

          3.8 新版功能.

      -- 方法: from_float (flt)

          此类方法可构造一个 *note Fraction: 186. 来表示 `flt' 的精确值
          ，该参数必须是一个 *note float: 188.。 请注意
          ‘Fraction.from_float(0.3)’ 的值并不等于 ‘Fraction(3, 10)’。

               注解: 从 Python 3.2 开始，在构造 *note Fraction: 186. 实
               例时可以直接使用 *note float: 188.。

      -- 方法: from_decimal (dec)

          此类方法可构造一个 *note Fraction: 186. 来表示 `dec' 的精确值
          ，该参数必须是一个 *note decimal.Decimal: 189. 实例。

               注解: 从 Python 3.2 开始，在构造 *note Fraction: 186. 实
               例时可以直接使用 *note decimal.Decimal: 189. 实例。

      -- 方法: limit_denominator (max_denominator=1000000)

          找到并返回一个 *note Fraction: 186. 使得其值最接近 ‘self’ 并且
          分母不大于 max_denominator。 此方法适用于找出给定浮点数的有理
          数近似值：

               >>> from fractions import Fraction
               >>> Fraction('3.1415926535897932').limit_denominator(1000)
               Fraction(355, 113)

          或是用来恢复被表示为一个浮点数的有理数：

               >>> from math import pi, cos
               >>> Fraction(cos(pi/3))
               Fraction(4503599627370497, 9007199254740992)
               >>> Fraction(cos(pi/3)).limit_denominator()
               Fraction(1, 2)
               >>> Fraction(1.1).limit_denominator()
               Fraction(11, 10)

      -- 方法: __floor__ ()

          返回最大的 *note int: 185. ‘<= self’。 此方法也可通过 *note
          math.floor(): d34. 函数来使用：

               >>> from math import floor
               >>> floor(Fraction(355, 113))
               3

      -- 方法: __ceil__ ()

          返回最小的 *note int: 185. ‘>= self’。 此方法也可通过 *note
          math.ceil(): d35. 函数来使用。

      -- 方法: __round__ ()

      -- 方法: __round__ (ndigits)

          第一个版本返回一个 *note int: 185. 使得其值最接近 ‘self’，位值
          为二分之一时只对偶数舍入。第二个版本会将 ‘self’ 舍入到最接近
          ‘Fraction(1, 10**ndigits)’ 的倍数（如果 ‘ndigits’ 为负值则为逻
          辑运算），位值为二分之一时同样只对偶数舍入。 此方法也可通过
          *note round(): c75. 函数来使用。

 -- 函数: fractions.gcd (a, b)

     返回整数 `a' 和 `b' 的最大公约数。如果 `a' 或 `b' 之一非零，则
     ‘gcd(a, b)’ 的绝对值是能同时整除 `a' 和 `b' 的最大整数。若 `b' 非零
     ，则 ‘gcd(a,b)’ 与 `b' 同号；否则返回值与 `a' 同号。‘gcd(0, 0)’ 返
     回 ‘0’。

     3.5 版后已移除: 由 *note math.gcd(): 71f. 取代.

参见
....

*note numbers: c2. 模块

     构成数字塔的所有抽象基类。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/fractions.py


File: python.info,  Node: random --- 生成伪随机数,  Next: statistics --- 数学统计函数,  Prev: fractions --- 分数,  Up: 数字和数学模块

5.9.6 ‘random’ — 生成伪随机数
-----------------------------

`源码：' Lib/random.py(1)

__________________________________________________________________

该模块实现了各种分布的伪随机数生成器。

对于整数，从范围中有统一的选择。 对于序列，存在随机元素的统一选择、用于
生成列表的随机排列的函数、以及用于随机抽样而无需替换的函数。

在实数轴上，有计算均匀、正态（高斯）、对数正态、负指数、伽马和贝塔分布的
函数。 为了生成角度分布，可以使用 von Mises 分布。

几乎所有模块函数都依赖于基本函数 *note random(): 1b17. ，它在半开放区间
[0.0,1.0) 内均匀生成随机浮点数。 Python 使用 Mersenne Twister 作为核心生
成器。 它产生 53 位精度浮点数，周期为 2**19937-1 ，其在 C 中的底层实现既
快又线程安全。 Mersenne Twister 是现存最广泛测试的随机数发生器之一。 但
是，因为完全确定性，它不适用于所有目的，并且完全不适合加密目的。

这个模块提供的函数实际上是 *note random.Random: 1b18. 类的隐藏实例的绑定
方法。 你可以实例化自己的 *note Random: 1b18. 类实例以获取不共享状态的生
成器。

如果你想使用自己设计的不同基础生成器，类 *note Random: 1b18. 也可以作为
子类：在这种情况下，重载 ‘random()’ 、 ‘seed()’ 、 ‘getstate()’ 以及
‘setstate()’ 方法。可选地，新生成器可以提供 ‘getrandbits()’ 方法——这允许
*note randrange(): bc3. 在任意大的范围内产生选择。

*note random: dd. 模块还提供 *note SystemRandom: 1b19. 类，它使用系统函
数 *note os.urandom(): 4d9. 从操作系统提供的源生成随机数。

     警告: 不应将此模块的伪随机生成器用于安全目的。 有关安全性或加密用途
     ，请参阅 *note secrets: e5. 模块。

参见
....

M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-dimensionally
equidistributed uniform pseudorandom number generator", ACM Transactions
on Modeling and Computer Simulation Vol.  8, No.  1, January pp.3–30
1998.

Complementary-Multiply-with-Carry recipe(2) 用于兼容的替代随机数发生器，
具有长周期和相对简单的更新操作。

* Menu:

* 簿记功能::
* 整数用函数::
* 序列用函数::
* 实值分布::
* 替代生成器::
* 关于再现性的说明::
* 例子和配方::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/random.py

   (2) https://code.activestate.com/recipes/576707/


File: python.info,  Node: 簿记功能,  Next: 整数用函数,  Up: random --- 生成伪随机数

5.9.6.1 簿记功能
................

 -- 函数: random.seed (a=None, version=2)

     初始化随机数生成器。

     如果 `a' 被省略或为 ‘None’ ，则使用当前系统时间。 如果操作系统提供
     随机源，则使用它们而不是系统时间（有关可用性的详细信息，请参阅
     *note os.urandom(): 4d9. 函数）。

     如果 `a' 是 int 类型，则直接使用。

     对于版本2（默认的），*note str: 339. 、 *note bytes: 33a. 或 *note
     bytearray: 33b. 对象转换为 *note int: 185. 并使用它的所有位。

     对于版本1（用于从旧版本的Python再现随机序列），用于 *note str: 339.
     和 *note bytes: 33a. 的算法生成更窄的种子范围。

     在 3.2 版更改: 已移至版本2方案，该方案使用字符串种子中的所有位。

 -- 函数: random.getstate ()

     返回捕获生成器当前内部状态的对象。 这个对象可以传递给 *note
     setstate(): 1b1c. 来恢复状态。

 -- 函数: random.setstate (state)

     `state' 应该是从之前调用 *note getstate(): 1b1b. 获得的，并且 *note
     setstate(): 1b1c. 将生成器的内部状态恢复到 *note getstate(): 1b1b.
     被调用时的状态。

 -- 函数: random.getrandbits (k)

     返回具有 `k' 个随机比特位的 Python 整数。 此方法随 Mersenne Twister
     生成器一起提供，其他一些生成器也可能将其作为 API 的可选部分提供。 在
     可能的情况下，*note getrandbits(): 93b. 会启用 *note randrange():
     bc3. 来处理任意大的区间。


File: python.info,  Node: 整数用函数,  Next: 序列用函数,  Prev: 簿记功能,  Up: random --- 生成伪随机数

5.9.6.2 整数用函数
..................

 -- 函数: random.randrange (stop)

 -- 函数: random.randrange (start, stop[, step])

     从 ‘range(start, stop, step)’ 返回一个随机选择的元素。 这相当于
     ‘choice(range(start, stop, step))’ ，但实际上并没有构建一个 range 对
     象。

     位置参数模式匹配 *note range(): 9c6. 。不应使用关键字参数，因为该函
     数可能以意外的方式使用它们。

     在 3.2 版更改: *note randrange(): bc3. 在生成均匀分布的值方面更为复
     杂。 以前它使用了像‘‘int(random()*n)‘‘这样的形式，它可以产生稍微不
     均匀的分布。

 -- 函数: random.randint (a, b)

     返回随机整数 `N' 满足 ‘a <= N <= b’。相当于 ‘randrange(a, b+1)’。


File: python.info,  Node: 序列用函数,  Next: 实值分布,  Prev: 整数用函数,  Up: random --- 生成伪随机数

5.9.6.3 序列用函数
..................

 -- 函数: random.choice (seq)

     从非空序列 `seq' 返回一个随机元素。 如果 `seq' 为空，则引发 *note
     IndexError: e7d.。

 -- 函数: random.choices (population, weights=None, *, cum_weights=None,
          k=1)

     从*population*中选择替换，返回大小为 `k' 的元素列表。 如果
     `population' 为空，则引发 *note IndexError: e7d.。

     如果指定了 `weight' 序列，则根据相对权重进行选择。 或者，如果给出
     `cum_weights' 序列，则根据累积权重（可能使用 *note
     itertools.accumulate(): 1de. 计算）进行选择。 例如，相对权重‘‘[10,
     5, 30, 5]‘‘相当于累积权重‘‘[10, 15, 45, 50]‘‘。 在内部，相对权重在
     进行选择之前会转换为累积权重，因此提供累积权重可以节省工作量。

     如果既未指定 `weight' 也未指定 `cum_weights' ，则以相等的概率进行选
     择。 如果提供了权重序列，则它必须与 `population' 序列的长度相同。 一
     个 *note TypeError: 193. 指定了 `weights' 和*cum_weights*。

     `weights' 或 `cum_weights' 可以使用任何与 *note random(): dd. 所返
     回的 *note float: 188. 值互操作的数值类型（包括整数、浮点数和分数但
     不包括十进制小数）。 权重假定为非负数。

     对于给定的种子，具有相等加权的 *note choices(): 57d. 函数通常产生与
     重复调用 *note choice(): bc5. 不同的序列。 *note choices(): 57d. 使
     用的算法使用浮点运算来实现内部一致性和速度。 *note choice(): bc5. 使
     用的算法默认为重复选择的整数运算，以避免因舍入误差引起的小偏差。

     3.6 新版功能.

 -- 函数: random.shuffle (x[, random])

     将序列 `x' 随机打乱位置。

     可选参数 `random' 是一个0参数函数，在 [0.0, 1.0) 中返回随机浮点数；
     默认情况下，这是函数 *note random(): 1b17. 。

     要改变一个不可变的序列并返回一个新的打乱列表，请使用‘‘sample(x,
     k=len(x))‘‘。

     请注意，即使对于小的 ‘len(x)’，`x' 的排列总数也可以快速增长，大于大
     多数随机数生成器的周期。 这意味着长序列的大多数排列永远不会产生。 例
     如，长度为2080的序列是可以在 Mersenne Twister 随机数生成器的周期内
     拟合的最大序列。

 -- 函数: random.sample (population, k)

     返回从总体序列或集合中选择的唯一元素的 `k' 长度列表。 用于无重复的
     随机抽样。

     返回包含来自总体的元素的新列表，同时保持原始总体不变。 结果列表按选
     择顺序排列，因此所有子切片也将是有效的随机样本。 这允许抽奖获奖者（
     样本）被划分为大奖和第二名获胜者（子切片）。

     总体成员不必是 *note hashable: 1439. 或 unique 。 如果总体包含重复
     ，则每次出现都是样本中可能的选择。

     要从一系列整数中选择样本，请使用 *note range(): 9c6. 对象作为参数。
     对于从大量人群中采样，这种方法特别快速且节省空间：
     ‘sample(range(10000000), k=60)’ 。

     如果样本大小大于总体大小，则引发 *note ValueError: 1fc. 。


File: python.info,  Node: 实值分布,  Next: 替代生成器,  Prev: 序列用函数,  Up: random --- 生成伪随机数

5.9.6.4 实值分布
................

以下函数生成特定的实值分布。如常用数学实践中所使用的那样, 函数参数以分布
方程中的相应变量命名;大多数这些方程都可以在任何统计学教材中找到。

 -- 函数: random.random ()

     返回 [0.0, 1.0) 范围内的下一个随机浮点数。

 -- 函数: random.uniform (a, b)

     返回一个随机浮点数 `N' ，当 ‘a <= b’ 时 ‘a <= N <= b’ ，当 ‘b < a’
     时 ‘b <= N <= a’ 。

     取决于等式 ‘a + (b-a) * random()’ 中的浮点舍入，终点 ‘b’ 可以包括或
     不包括在该范围内。

 -- 函数: random.triangular (low, high, mode)

     返回一个随机浮点数 `N' ，使得 ‘low <= N <= high’ 并在这些边界之间使
     用指定的 `mode' 。 `low' 和 `high' 边界默认为零和一。 `mode' 参数默
     认为边界之间的中点，给出对称分布。

 -- 函数: random.betavariate (alpha, beta)

     Beta 分布。 参数的条件是 ‘alpha > 0’ 和 ‘beta > 0’。 返回值的范围介
     于 0 和 1 之间。

 -- 函数: random.expovariate (lambd)

     指数分布。 `lambd' 是 1.0 除以所需的平均值，它应该是非零的。 （该参
     数本应命名为 “lambda” ，但这是 Python 中的保留字。）如果 `lambd' 为
     正，则返回值的范围为 0 到正无穷大；如果 `lambd' 为负，则返回值从负
     无穷大到 0。

 -- 函数: random.gammavariate (alpha, beta)

     Gamma 分布。 （ `不是' gamma 函数！ ） 参数的条件是 ‘alpha > 0’ 和
     ‘beta > 0’。

     概率分布函数是:

                    x ** (alpha - 1) * math.exp(-x / beta)
          pdf(x) =  --------------------------------------
                      math.gamma(alpha) * beta ** alpha

 -- 函数: random.gauss (mu, sigma)

     高斯分布。 `mu' 是平均值，`sigma' 是标准差。 这比下面定义的 *note
     normalvariate(): 1b26. 函数略快。

 -- 函数: random.lognormvariate (mu, sigma)

     对数正态分布。 如果你采用这个分布的自然对数，你将得到一个正态分布，
     平均值为 `mu' 和标准差为 `sigma' 。 `mu' 可以是任何值，`sigma' 必须
     大于零。

 -- 函数: random.normalvariate (mu, sigma)

     正态分布。 `mu' 是平均值，`sigma' 是标准差。

 -- 函数: random.vonmisesvariate (mu, kappa)

     冯·米塞斯分布。 `mu' 是平均角度，以弧度表示，介于0和 2*`pi' 之间，
     `kappa' 是浓度参数，必须大于或等于零。 如果 `kappa' 等于零，则该分
     布在 0 到 2*`pi' 的范围内减小到均匀的随机角度。

 -- 函数: random.paretovariate (alpha)

     帕累托分布。 `alpha' 是形状参数。

 -- 函数: random.weibullvariate (alpha, beta)

     威布尔分布。 `alpha' 是比例参数，`beta' 是形状参数。


File: python.info,  Node: 替代生成器,  Next: 关于再现性的说明,  Prev: 实值分布,  Up: random --- 生成伪随机数

5.9.6.5 替代生成器
..................

 -- 类: random.Random ([seed])

     该类实现了 *note random: dd. 模块所用的默认伪随机数生成器。

 -- 类: random.SystemRandom ([seed])

     使用 *note os.urandom(): 4d9. 函数的类，用从操作系统提供的源生成随
     机数。 这并非适用于所有系统。 也不依赖于软件状态，序列不可重现。 因
     此，*note seed(): c10. 方法没有效果而被忽略。 *note getstate():
     1b1b. 和 *note setstate(): 1b1c. 方法如果被调用则引发 *note
     NotImplementedError: 617.。


File: python.info,  Node: 关于再现性的说明,  Next: 例子和配方,  Prev: 替代生成器,  Up: random --- 生成伪随机数

5.9.6.6 关于再现性的说明
........................

有时能够重现伪随机数生成器给出的序列是有用的。 通过重新使用种子值，只要
多个线程没有运行，相同的序列就可以在两次不同运行之间重现。

大多数随机模块的算法和种子函数都会在 Python 版本中发生变化，但保证两个方
面不会改变：

   * 如果添加了新的播种方法，则将提供向后兼容的播种机。

   * 当兼容的播种机被赋予相同的种子时，生成器的 ‘random()’ 方法将继续产
     生相同的序列。


File: python.info,  Node: 例子和配方,  Prev: 关于再现性的说明,  Up: random --- 生成伪随机数

5.9.6.7 例子和配方
..................

基本示例:

     >>> random()                             # Random float:  0.0 <= x < 1.0
     0.37444887175646646

     >>> uniform(2.5, 10.0)                   # Random float:  2.5 <= x < 10.0
     3.1800146073117523

     >>> expovariate(1 / 5)                   # Interval between arrivals averaging 5 seconds
     5.148957571865031

     >>> randrange(10)                        # Integer from 0 to 9 inclusive
     7

     >>> randrange(0, 101, 2)                 # Even integer from 0 to 100 inclusive
     26

     >>> choice(['win', 'lose', 'draw'])      # Single random element from a sequence
     'draw'

     >>> deck = 'ace two three four'.split()
     >>> shuffle(deck)                        # Shuffle a list
     >>> deck
     ['four', 'two', 'ace', 'three']

     >>> sample([10, 20, 30, 40, 50], k=4)    # Four samples without replacement
     [40, 10, 50, 30]

模拟:

     >>> # Six roulette wheel spins (weighted sampling with replacement)
     >>> choices(['red', 'black', 'green'], [18, 18, 2], k=6)
     ['red', 'green', 'black', 'black', 'red', 'black']

     >>> # Deal 20 cards without replacement from a deck of 52 playing cards
     >>> # and determine the proportion of cards with a ten-value
     >>> # (a ten, jack, queen, or king).
     >>> deck = collections.Counter(tens=16, low_cards=36)
     >>> seen = sample(list(deck.elements()), k=20)
     >>> seen.count('tens') / 20
     0.15

     >>> # Estimate the probability of getting 5 or more heads from 7 spins
     >>> # of a biased coin that settles on heads 60% of the time.
     >>> def trial():
     ...     return choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5
     ...
     >>> sum(trial() for i in range(10_000)) / 10_000
     0.4169

     >>> # Probability of the median of 5 samples being in middle two quartiles
     >>> def trial():
     ...     return 2_500 <= sorted(choices(range(10_000), k=5))[2] < 7_500
     ...
     >>> sum(trial() for i in range(10_000)) / 10_000
     0.7958

statistical bootstrapping(1) 的示例，使用重新采样和替换来估计一个样本的
均值的置信区间:

     # http://statistics.about.com/od/Applications/a/Example-Of-Bootstrapping.htm
     from statistics import fmean as mean
     from random import choices

     data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95]
     means = sorted(mean(choices(data, k=len(data))) for i in range(100))
     print(f'The sample mean of {mean(data):.1f} has a 90% confidence '
           f'interval from {means[5]:.1f} to {means[94]:.1f}')

使用 重新采样排列测试(2) 来确定统计学显著性或者使用 p-值(3) 来观察药物与
安慰剂的作用之间差异的示例:

     # Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
     from statistics import fmean as mean
     from random import shuffle

     drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
     placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
     observed_diff = mean(drug) - mean(placebo)

     n = 10_000
     count = 0
     combined = drug + placebo
     for i in range(n):
         shuffle(combined)
         new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):])
         count += (new_diff >= observed_diff)

     print(f'{n} label reshufflings produced only {count} instances with a difference')
     print(f'at least as extreme as the observed difference of {observed_diff:.1f}.')
     print(f'The one-sided p-value of {count / n:.4f} leads us to reject the null')
     print(f'hypothesis that there is no difference between the drug and the placebo.')

多服务器队列的到达时间和服务交付模拟:

     from heapq import heappush, heappop
     from random import expovariate, gauss
     from statistics import mean, median, stdev

     average_arrival_interval = 5.6
     average_service_time = 15.0
     stdev_service_time = 3.5
     num_servers = 3

     waits = []
     arrival_time = 0.0
     servers = [0.0] * num_servers  # time when each server becomes available
     for i in range(100_000):
         arrival_time += expovariate(1.0 / average_arrival_interval)
         next_server_available = heappop(servers)
         wait = max(0.0, next_server_available - arrival_time)
         waits.append(wait)
         service_duration = gauss(average_service_time, stdev_service_time)
         service_completed = arrival_time + wait + service_duration
         heappush(servers, service_completed)

     print(f'Mean wait: {mean(waits):.1f}.  Stdev wait: {stdev(waits):.1f}.')
     print(f'Median wait: {median(waits):.1f}.  Max wait: {max(waits):.1f}.')

参见
....

Statistics for Hackers(4) Jake Vanderplas(5) 撰写的视频教程，使用一些基
本概念进行统计分析，包括模拟、抽样、改组和交叉验证。

Economics Simulation(6) Peter Norvig(7) 编写的市场模拟，显示了该模块提供
的许多工具和分布的有效使用（高斯、均匀、样本、beta变量、选择、三角和随机
范围等）。

A Concrete Introduction to Probability (using Python)(8) Peter Norvig(9)
撰写的教程，涵盖了概率论基础知识，如何编写模拟，以及如何使用 Python 进行
数据分析。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Bootstrapping_(statistics)

   (2) 
https://en.wikipedia.org/wiki/Resampling_(statistics)#Permutation_tests

   (3) https://en.wikipedia.org/wiki/P-value

   (4) https://www.youtube.com/watch?v=Iq9DzN6mvYA

   (5) https://us.pycon.org/2016/speaker/profile/295/

   (6) 
http://nbviewer.jupyter.org/url/norvig.com/ipython/Economics.ipynb

   (7) http://norvig.com/bio.html

   (8) 
http://nbviewer.jupyter.org/url/norvig.com/ipython/Probability.ipynb

   (9) http://norvig.com/bio.html


File: python.info,  Node: statistics --- 数学统计函数,  Prev: random --- 生成伪随机数,  Up: 数字和数学模块

5.9.7 ‘statistics’ — 数学统计函数
---------------------------------

3.4 新版功能.

`源代码:' Lib/statistics.py(1)

__________________________________________________________________

该模块提供了用于计算数字 (*note Real: 1435.-valued) 数据的数理统计量的函
数。

此模块并不是诸如 NumPy(2) ， SciPy(3) 等第三方库或者诸如 Minitab ， SAS
， Matlab 等针对专业统计学家的专有全功能统计软件包的竞品。此模块针对图形
和科学计算器的水平。

除非明确注释，这些函数支持 *note int: 185. ， *note float: 188. ， *note
Decimal: 189. 和 *note Fraction: 186. 。当前不支持同其他类型（是否在数字
塔中）的行为。混合类型的集合也是未定义的，并且依赖于实现。如果你输入的数
据由混合类型组成，你应该能够使用 *note map(): c35. 来确保一个一致的结果
，比如： ‘map(float, input_data)’ 。

* Menu:

* 平均值以及对中心位置的评估::
* 对分散程度的评估::
* 函数细节::
* 异常: 异常<3>.
* NormalDist 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/statistics.py

   (2) https://numpy.org

   (3) https://www.scipy.org/


File: python.info,  Node: 平均值以及对中心位置的评估,  Next: 对分散程度的评估,  Up: statistics --- 数学统计函数

5.9.7.1 平均值以及对中心位置的评估
..................................

这些函数用于计算一个总体或样本的平均值或者典型值。

*note mean(): 19a.          数据的算术平均数（“平均数”）。
                            
                            
*note fmean(): 228.         快速的，浮点算数平均数。
                            
                            
*note geometric_mean(): 229.数据的几何平均数
                            
                            
*note harmonic_mean(): 598. 数据的调和均值
                            
                            
*note median(): 1b31.       数据的中位数（中间值）
                            
                            
*note median_low(): 1b32.   数据的低中位数
                            
                            
*note median_high(): 1b33.  数据的高中位数
                            
                            
*note median_grouped(): 1b34.分组数据的中位数，即第50个百分点。
                            
                            
*note mode(): 2bc.          离散的或标称的数据的单个众数（出现最多的值）。
                            
                            
*note multimode(): 22a.     离散的或标称的数据的众数列表（出现最多的值）。
                            
                            
*note quantiles(): 22b.     将数据以相等的概率分为多个间隔。
                            


File: python.info,  Node: 对分散程度的评估,  Next: 函数细节,  Prev: 平均值以及对中心位置的评估,  Up: statistics --- 数学统计函数

5.9.7.2 对分散程度的评估
........................

这些函数用于计算总体或样本与典型值或平均值的偏离程度。

*note pstdev(): 1b36.       数据的总体标准差
                            
                            
*note pvariance(): 1b37.    数据的总体方差
                            
                            
*note stdev(): 1b38.        数据的样本标准差
                            
                            
*note variance(): 1b39.     数据的样本方差
                            


File: python.info,  Node: 函数细节,  Next: 异常<3>,  Prev: 对分散程度的评估,  Up: statistics --- 数学统计函数

5.9.7.3 函数细节
................

注释：这些函数不需要对提供给它们的数据进行排序。但是，为了方便阅读，大多
数例子展示的是已排序的序列。

 -- 函数: statistics.mean (data)

     返回 `data' 的样本算术平均数，形式为序列或迭代器。

     算术平均数是数据之和与数据点个数的商。通常称作“平均数”，尽管它指示
     诸多数学平均数之一。它是数据的中心位置的度量。

     若 `data' 为空，将会引发 *note StatisticsError: 1b3b.。

     一些用法示例：

          >>> mean([1, 2, 3, 4, 4])
          2.8
          >>> mean([-1.0, 2.5, 3.25, 5.75])
          2.625

          >>> from fractions import Fraction as F
          >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
          Fraction(13, 21)

          >>> from decimal import Decimal as D
          >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
          Decimal('0.5625')

          注解: 均值非常受异常值的影响并且这不是中心位置的可靠估计：均值
          不一定是数据点的典型示例。如需要更可靠的的估计，请参考 *note
          median(): 1b31. 和 *note mode(): 2bc. 。

          样本均值给出了一个无偏向的真实总体均值的估计，因此当平均抽取所
          有可能的样本， ‘mean(sample)’ 收敛于整个总体的真实均值。如果
          `data' 代表整个总体而不是样本，那么 ‘mean(data)’ 等同于计算真
          实整体均值 μ 。

 -- 函数: statistics.fmean (data)

     将 `data' 转换成浮点数并且计算算术平均数。

     此函数的运行速度比 *note mean(): 19a. 函数快并且它总是返回一个
     *note float: 188.。 `data' 可以为序列或可迭代对象。 如果输入数据集
     为空，则会引发 *note StatisticsError: 1b3b.。

          >>> fmean([3.5, 4.0, 5.25])
          4.25

     3.8 新版功能.

 -- 函数: statistics.geometric_mean (data)

     将 `data' 转换成浮点数并且计算几何平均数。

     几何平均值使用值的乘积表示 `数据' 的中心趋势或典型值（与使用它们的
     总和的算术平均值相反）。

     如果输入数据集为空、包含零或包含负值则将引发 *note StatisticsError:
     1b3b.。 `data' 可以是序列或可迭代对象。

     无需做出特殊努力即可获得准确的结果。（但是，将来或许会修改。）

          >>> round(geometric_mean([54, 24, 36]), 1)
          36.0

     3.8 新版功能.

 -- 函数: statistics.harmonic_mean (data)

     返回 `data' 调和均值，该参数可以是序列或包含实数值的可迭代对象。

     调和均值,也叫次相反均值，所有数据的倒数的算术平均数 *note mean():
     19a. 的倒数。比如说，数据 `a' ， `b' ， `c' 的调和均值等于 ‘3/(1/a
     + 1/b + 1/c)’ 。如果其中一个值为零，结果为零。

     调和均值是一种均值类型，是数据中心位置的度量。它通常适合于求比率和
     比例的平均值，比如速率。

     假设一辆车在 40 km/hr 的速度下行驶了 10 km ，然后又以 60 km/hr 的速
     度行驶了 10 km 。车辆的平均速率是多少？

          >>> harmonic_mean([40, 60])
          48.0

     假设一名投资者在三家公司各购买了等价值的股票，以 2.5， 3 ， 10 的
     P/E (价格/收益) 率。投资者投资组合的平均市盈率是多少？

          >>> harmonic_mean([2.5, 3, 10])  # For an equal investment portfolio.
          3.6

     如果 `data' 为空或者 任何一个元素的值小于零，会引发 *note
     StatisticsError: 1b3b. 。

     当前算法在输入中遇到零时会提前退出。这意味着不会测试后续输入的有效
     性。（此行为将来可能会更改。）

     3.6 新版功能.

 -- 函数: statistics.median (data)

     使用普通的“取中间两数平均值”方法返回数值数据的中位数（中间值）。 如
     果 `data' 为空，则将引发 *note StatisticsError: 1b3b.。 `data' 可以
     是序列或可迭代对象。

     中位数是衡量中间位置的可靠方式，并且较少受到极端值的影响。 当数据点
     的总数为奇数时，将返回中间数据点：

          >>> median([1, 3, 5])
          3

     当数据点的总数为偶数时，中位数将通过对两个中间值求平均进行插值得出
     ：

          >>> median([1, 3, 5, 7])
          4.0

     这适用于当你的数据是离散的，并且你不介意中位数不是实际数据点的情况
     。

     如果数据是有序的（支持排序操作）但不是数字（不支持加法），请考虑改
     用 *note median_low(): 1b32. 或 *note median_high(): 1b33.。

 -- 函数: statistics.median_low (data)

     返回数值数据的低中位数。 如果 `data' 为空则将引发 *note
     StatisticsError: 1b3b.。 `data' 可以是序列或可迭代对象。

     低中位数一定是数据集的成员。 当数据点总数为奇数时，将返回中间值。 当
     其为偶数时，将返回两个中间值中较小的那个。

          >>> median_low([1, 3, 5])
          3
          >>> median_low([1, 3, 5, 7])
          3

     当你的数据是离散的，并且你希望中位数是一个实际数据点而非插值结果时
     可以使用低中位数。

 -- 函数: statistics.median_high (data)

     返回数据的高中位数。 如果 `data' 为空则将引发 *note
     StatisticsError: 1b3b.。 `data' 可以是序列或可迭代对象。

     高中位数一定是数据集的成员。 当数据点总数为奇数时，将返回中间值。 当
     其为偶数时，将返回两个中间值中较大的那个。

          >>> median_high([1, 3, 5])
          3
          >>> median_high([1, 3, 5, 7])
          5

     当你的数据是离散的，并且你希望中位数是一个实际数据点而非插值结果时
     可以使用高中位数。

 -- 函数: statistics.median_grouped (data, interval=1)

     返回分组的连续数据的中位数，根据第 50 个百分点的位置使用插值来计算
     。 如果 `data' 为空则将引发 *note StatisticsError: 1b3b.。 `data' 可
     以是序列或可迭代对象。

          >>> median_grouped([52, 52, 53, 54])
          52.5

     在下面的示例中，数据已经过舍入，这样每个值都代表数据分类的中间点，
     例如 1 是 0.5–1.5 分类的中间点，2 是 1.5–2.5 分类的中间点，3 是
     2.5–3.5 的中间点等待。 根据给定的数据，中间值应落在 3.5–4.5 分类之
     内，并可使用插值法来进行估算：

          >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
          3.7

     可选参数 `interval' 表示分类间隔，默认值为 1。 改变分类间隔自然会改
     变插件结果：

          >>> median_grouped([1, 3, 3, 5, 7], interval=1)
          3.25
          >>> median_grouped([1, 3, 3, 5, 7], interval=2)
          3.5

     此函数不会检查数据点之间是否至少相隔 `interval' 的距离。

     `CPython implementation detail:' 在某些情况下，*note
     median_grouped(): 1b34. 可以会将数据点强制转换为浮点数。 此行为在未
     来有可能会发生改变。

     参见
     ....

        * "Statistics for the Behavioral Sciences", Frederick J
          Gravetter and Larry B Wallnau (8th Edition).

        * Gnome Gnumeric 电子表格中的 SSMEDIAN(1) 函数，包括 这篇讨论
          (2)。

 -- 函数: statistics.mode (data)

     从离散或标称的 `data' 返回单个出现最多的数据点。 此众数（如果存在）
     是最典型的值，并可用来度量中心的位置。

     如果存在具有相同频率的多个众数，则返回在 `data' 中遇到的第一个。 如
     果想要其中最小或最大的一个，请使用 ‘min(multimode(data))’ 或
     ‘max(multimode(data))’。 如果输入的 `data' 为空，则会引发 *note
     StatisticsError: 1b3b.。

     ‘mode’ 将假定是离散数据并返回一个单一的值。 这是通常的学校教学中标
     准的处理方式：

          >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
          3

     此众数的独特之处在于它是这个包中唯一还可应用于标称（非数字）数据的
     统计信息：

          >>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
          'red'

     在 3.8 版更改: 现在会通过返回所遇到的第一个众数来处理多模数据集。 之
     前它会在遇到超过一个的众数时引发 *note StatisticsError: 1b3b.。

 -- 函数: statistics.multimode (data)

     返回最频繁出现的值的列表，并按它们在 `data' 中首次出现的位置排序。
     如果存在多个众数则将返回一个以上的众数，或者如果 `data' 为空则将返
     回空列表：

          >>> multimode('aabbbbccddddeeffffgg')
          ['b', 'd', 'f']
          >>> multimode('')
          []

     3.8 新版功能.

 -- 函数: statistics.pstdev (data, mu=None)

     返回总体标准差（总体方差的平方根）。 请参阅 *note pvariance():
     1b37. 了解参数和其他细节。

          >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
          0.986893273527251

 -- 函数: statistics.pvariance (data, mu=None)

     返回非空序列或包含实数值的可迭代对象 `data' 的总体方差。 方差或称相
     对于均值的二阶距，是对数据变化幅度（延展度或分散度）的度量。 方差值
     较大表明数据的散布范围较大；方差值较小表明它紧密聚集于均值附近。

     如果给出了可选的第二个参数 `mu'，它通常是 `data' 的均值。 它也可以
     被用来计算相对于一个非均值点的二阶距。 如果该参数省略或为 ‘None’ (默
     认值)，则会自动进行算术均值的计算。

     使用此函数可根据所有数值来计算方差。 要根据一个样本来估算方差，通常
     *note variance(): 1b39. 函数是更好的选择。

     如果 `data' 为空则会引发 *note StatisticsError: 1b3b.。

     示例：

          >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
          >>> pvariance(data)
          1.25

     如果你已经计算过数据的平均值，你可以将其作为可选的第二个参数 `mu' 传
     入以避免重复计算：

          >>> mu = mean(data)
          >>> pvariance(data, mu)
          1.25

     同样也支持使用 Decimal 和 Fraction 值：

          >>> from decimal import Decimal as D
          >>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
          Decimal('24.815')

          >>> from fractions import Fraction as F
          >>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
          Fraction(13, 72)

          注解: 当调用时附带完整的总体数据时，这将给出总体方差 σ²。 而当
          调用时只附带一个样本时，这将给出偏置样本方差 s²，也被称为带有
          N 个自由度的方差。

          如果你通过某种方式知道了真实的总体平均值 μ，则可以使用此函数来
          计算一个样本的方差，并将已知的总体平均值作为第二个参数。 假设
          数据点是总体的一个随机样本，则结果将为总体方差的无偏估计值。

 -- 函数: statistics.stdev (data, xbar=None)

     返回样本标准差（样本方差的平方根）。 请参阅 *note variance(): 1b39.
     了解参数和其他细节。

          >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
          1.0810874155219827

 -- 函数: statistics.variance (data, xbar=None)

     返回包含至少两个实数值的可迭代对象 `data' 的样本方差。 方差或称相对
     于均值的二阶矩，是对数据变化幅度（延展度或分散度）的度量。 方差值较
     大表明数据的散布范围较大；方差值较小表明它紧密聚集于均值附近。

     如果给出了可选的第二个参数 `xbar'，它应当是 `data' 的均值。 如果该
     参数省略或为 ‘None’ (默认值)，则会自动进行均值的计算。

     当你的数据是总体数据的样本时请使用此函数。 要根据整个总体数据来计算
     方差，请参见 *note pvariance(): 1b37.。

     如果 `data' 包含的值少于两个则会引发 *note StatisticsError: 1b3b.。

     示例：

          >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
          >>> variance(data)
          1.3720238095238095

     如果你已经计算过数据的平均值，你可以将其作为可选的第二个参数 `xbar'
     传入以避免重复计算：

          >>> m = mean(data)
          >>> variance(data, m)
          1.3720238095238095

     此函数不会试图检查你所传入的 `xbar' 是否为真实的平均值。 使用任意值
     作为 `xbar' 可能导致无效或不可能的结果。

     同样也支持使用 Decimal 和 Fraction 值：

          >>> from decimal import Decimal as D
          >>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
          Decimal('31.01875')

          >>> from fractions import Fraction as F
          >>> variance([F(1, 6), F(1, 2), F(5, 3)])
          Fraction(67, 108)

          注解: 这是附带贝塞尔校正的样本方差 s²，也称为具有 N-1 自由度的
          方差。 假设数据点具有代表性（即为独立且均匀的分布），则结果应
          当是对总体方差的无偏估计。

          如果你通过某种方式知道了真实的总体平均值 μ 则应当调用 *note
          pvariance(): 1b37. 函数并将该值作为 `mu' 形参传入以得到一个样
          本的方差。

 -- 函数: statistics.quantiles (data, *, n=4, method='exclusive')

     将 `data' 分隔为具有相等概率的 `n' 个连续区间。 返回分隔这些区间的
     ‘n - 1’ 个分隔点的列表。

     将 `n' 设为 4 以使用四分位（默认值）。 将 `n' 设为 10 以使用十分位
     。 将 `n' 设为 100 以使用百分位，即给出 99 个分隔点来将 `data' 分隔
     为 100 个大小相等的组。 如果 `n' 小于 1 则将引发 *note
     StatisticsError: 1b3b.。

     `data' 可以是包含样本数据的任意可迭代对象。 为了获得有意义的结果，
     `data' 中数据点的数量应当大于 `n'。 如果数据点的数量小于两个则将引
     发 *note StatisticsError: 1b3b.。

     分隔点是通过对两个最接近的数据点进行线性插值得到的。 例如，如果一个
     分隔点落在两个样本值 ‘100’ 和 ‘112’ 之间距离三分之一的位置，则分隔
     点的取值将为 ‘104’。

     `method' 用于计算分位值，它会由于 `data' 是包含还是排除总体的最低和
     最高可能值而有所不同。

     默认 `method' 是 “唯一的” 并且被用于在总体中数据采样这样可以有比样
     本中找到的更多的极端值。落在 `m' 个排序数据点的第 `i-th' 个以下的总
     体部分被计算为 ‘i / (m + 1)’ 。给定九个样本值，方法排序它们并且分配
     一下的百分位： 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90% 。

     将 `method' 设为 "inclusive" 可用于描述总体数据或已明确知道包含有总
     体数据中最极端值的样本。 `data' 中的最小值会被作为第 0 个百分位而最
     大值会被作为第 100 个百分位。 总体数据里处于 `m' 个已排序数据点中
     `第 i 个' 以下的部分会以 ‘(i - 1) / (m - 1)’ 来计算。 给定 11 个样
     本值，该方法会对它们进行排序并赋予以下百分位: 0%, 10%, 20%, 30%,
     40%, 50%, 60%, 70%, 80%, 90%, 100%。

          # Decile cut points for empirically sampled data
          >>> data = [105, 129, 87, 86, 111, 111, 89, 81, 108, 92, 110,
          ...         100, 75, 105, 103, 109, 76, 119, 99, 91, 103, 129,
          ...         106, 101, 84, 111, 74, 87, 86, 103, 103, 106, 86,
          ...         111, 75, 87, 102, 121, 111, 88, 89, 101, 106, 95,
          ...         103, 107, 101, 81, 109, 104]
          >>> [round(q, 1) for q in quantiles(data, n=10)]
          [81.0, 86.2, 89.0, 99.4, 102.5, 103.6, 106.0, 109.8, 111.0]

     3.8 新版功能.

   ---------- Footnotes ----------

   (1) 
https://help.gnome.org/users/gnumeric/stable/gnumeric.html#gnumeric-function-SSMEDIAN

   (2) 
https://mail.gnome.org/archives/gnumeric-list/2011-April/msg00018.html


File: python.info,  Node: 异常<3>,  Next: NormalDist 对象,  Prev: 函数细节,  Up: statistics --- 数学统计函数

5.9.7.4 异常
............

只定义了一个异常：

 -- 例外: statistics.StatisticsError

     *note ValueError: 1fc. 的子类，表示统计相关的异常。


File: python.info,  Node: NormalDist 对象,  Prev: 异常<3>,  Up: statistics --- 数学统计函数

5.9.7.5 ‘NormalDist’ 对象
.........................

*note NormalDist: 22c. 工具可用于创建和操纵 随机变量(1) 的正态分布。 这
个类将数据度量值的平均值和标准差作为单一实体来处理。

正态分布的概念来自于 中央极限定理(2) 并且在统计学中有广泛的应用。

 -- 类: statistics.NormalDist (mu=0.0, sigma=1.0)

     返回一个新的 `NormalDist' 对象，其中 `mu' 代表 算术平均值(3) 而
     `sigma' 代表 标准差(4)。

     若 `sigma' 为负数，将会引发 *note StatisticsError: 1b3b.。

      -- 属性: mean

          一个只读特征属性，表示特定正态分布的 算术平均值(5)。

      -- 属性: median

          一个只读特征属性，表示特定正态分布的 中位数(6)。

      -- 属性: mode

          一个只读特征属性，表示特定正态分布的 众数(7)。

      -- 属性: stdev

          一个只读特征属性，表示特定正态分布的 标准差(8)。

      -- 属性: variance

          一个只读特征属性，表示特定正态分布的 方差(9)。 等于标准差的平
          方。

      -- 方法: classmethod from_samples (data)

          传入使用 *note fmean(): 228. 和 *note stdev(): 1b38. 基于
          `data' 估算出的 `mu' 和 `sigma' 形参创建一个正态分布实例。

          `data' 可以是任何 *note iterable: bb4. 并且应当包含能被转换为
          *note float: 188. 类型的值。 如果 `data' 不包含至少两个元素，
          则会引发 *note StatisticsError: 1b3b.，因为估算中心值至少需要
          一个点而估算分散度至少需要两个点。

      -- 方法: samples (n, *, seed=None)

          对于给定的平均值和标准差生成 `n' 个随机样本。 返回一个由 *note
          float: 188. 值组成的 *note list: 263.。

          当给定 `seed' 时，创建一个新的底层随机数生成器实例。 这适用于
          创建可重现的结果，即使对于多线程上下文也有效。

      -- 方法: pdf (x)

          使用 概率密度函数 (pdf)(10)，计算一个随机变量 `X' 趋向于给定值
          `x' 的相对可能性。 在数学意义上，它是当 `dx' 趋向于零时比率
          ‘P(x <= X < x+dx) / dx’ 的极限。

          相对可能性的计算方法是用一个狭窄区间内某个样本出现的概率除以区
          间的宽度（因此使用“密度”一词）。 由于可能性是相对于其他点的，
          它的值可以大于 ‘1.0’。

      -- 方法: cdf (x)

          使用 累积分布函数 (cdf)(11)，计算一个随机变量 `X' 小于等于 `x'
          的概率。 在数学上，它表示为 ‘P(X <= x)’。

      -- 方法: inv_cdf (p)

          计算反向累积分布函数，也称为 分位数函数(12) 或 百分点(13) 函数
          。 在数学上，它表示为 ‘x : P(X <= x) = p’。

          找出随机变量 `X' 的值 `x' 使得该变量小于等于该值的概率等于给定
          的概率 `p'。

      -- 方法: overlap (other)

          测量两个正态概率分布之间的一致性。 返回介于 0.0 和 1.0 之间的
          值，给出 两个概率密度函数的重叠区域(14)。

      -- 方法: quantiles (n=4)

          将指定正态分布划分为 `n' 个相等概率的连续分隔区。 返回这些分隔
          区对应的 (n - 1) 个分隔点的列表。

          将 `n' 设为 4 以使用四分位（默认值）。 将 `n' 设为 10 以使用十
          分位。将 `n' 设为 100 以使用百分位，即给出 99 个分隔点来将正态
          分布分隔为 100 个大小相等的组。

     *note NormalDist: 22c. 的实例支持加上、减去、乘以或除以一个常量。 这
     些运算被用于转换和缩放。 例如：

          >>> temperature_february = NormalDist(5, 2.5)             # Celsius
          >>> temperature_february * (9/5) + 32                     # Fahrenheit
          NormalDist(mu=41.0, sigma=4.5)

     不允许一个常量除以 *note NormalDist: 22c. 的实例，因为结果将不是正
     态分布。

     由于正态分布是由独立变量的累加效应产生的，因此允许表示为 *note
     NormalDist: 22c. 实例的 两组独立正态分布的随机变量相加和相减(15)。
     例如：

          >>> birth_weights = NormalDist.from_samples([2.5, 3.1, 2.1, 2.4, 2.7, 3.5])
          >>> drug_effects = NormalDist(0.4, 0.15)
          >>> combined = birth_weights + drug_effects
          >>> round(combined.mean, 1)
          3.1
          >>> round(combined.stdev, 1)
          0.5

     3.8 新版功能.

* Menu:

* NormalDist 示例和用法::

   ---------- Footnotes ----------

   (1) http://www.stat.yale.edu/Courses/1997-98/101/ranvar.htm

   (2) https://en.wikipedia.org/wiki/Central_limit_theorem

   (3) https://en.wikipedia.org/wiki/Arithmetic_mean

   (4) https://en.wikipedia.org/wiki/Standard_deviation

   (5) https://en.wikipedia.org/wiki/Arithmetic_mean

   (6) https://en.wikipedia.org/wiki/Median

   (7) https://en.wikipedia.org/wiki/Mode_(statistics)

   (8) https://en.wikipedia.org/wiki/Standard_deviation

   (9) https://en.wikipedia.org/wiki/Variance

   (10) https://en.wikipedia.org/wiki/Probability_density_function

   (11) https://en.wikipedia.org/wiki/Cumulative_distribution_function

   (12) https://en.wikipedia.org/wiki/Quantile_function

   (13) 
https://www.statisticshowto.datasciencecentral.com/inverse-distribution-function/

   (14) https://www.rasch.org/rmt/rmt101r.htm

   (15) 
https://en.wikipedia.org/wiki/Sum_of_normally_distributed_random_variables


File: python.info,  Node: NormalDist 示例和用法,  Up: NormalDist 对象

5.9.7.6 ‘NormalDist’ 示例和用法
...............................

*note NormalDist: 22c. 适合用来解决经典概率问题。

举例来说，如果 SAT 考试的历史数据(1) 显示分数呈平均值为 1060 且标准差为
195 的正态分布，则可以确定考试分数处于 1100 和 1200 之间的学生的百分比舍
入到最接近的整数应为：

     >>> sat = NormalDist(1060, 195)
     >>> fraction = sat.cdf(1200 + 0.5) - sat.cdf(1100 - 0.5)
     >>> round(fraction * 100.0, 1)
     18.4

求 SAT 分数的 四分位(2) 和 十分位(3)：

     >>> list(map(round, sat.quantiles()))
     [928, 1060, 1192]
     >>> list(map(round, sat.quantiles(n=10)))
     [810, 896, 958, 1011, 1060, 1109, 1162, 1224, 1310]

为了估算一个不易解析的模型分布，*note NormalDist: 22c. 可以生成用于 蒙特
卡洛模拟(4) 的输入样本：

     >>> def model(x, y, z):
     ...     return (3*x + 7*x*y - 5*y) / (11 * z)
     ...
     >>> n = 100_000
     >>> X = NormalDist(10, 2.5).samples(n, seed=3652260728)
     >>> Y = NormalDist(15, 1.75).samples(n, seed=4582495471)
     >>> Z = NormalDist(50, 1.25).samples(n, seed=6582483453)
     >>> quantiles(map(model, X, Y, Z))
     [1.4591308524824727, 1.8035946855390597, 2.175091447274739]

当样本量较大并且成功试验的可能性接近 50% 时，正态分布可以被用来模拟 二项
分布(5)。

例如，一次开源会议有 750 名与会者和两个可分别容纳 500 人的会议厅。 会上
有一场关于 Python 的演讲和一场关于 Ruby 的演讲。 在往届会议中，65% 的与
会者更愿意去听关于 Python 的演讲。 假定人群的偏好没有发生改变，那么
Python 演讲的会议厅不超出其容量上限的可能性是多少？

     >>> n = 750             # Sample size
     >>> p = 0.65            # Preference for Python
     >>> q = 1.0 - p         # Preference for Ruby
     >>> k = 500             # Room capacity

     >>> # Approximation using the cumulative normal distribution
     >>> from math import sqrt
     >>> round(NormalDist(mu=n*p, sigma=sqrt(n*p*q)).cdf(k + 0.5), 4)
     0.8402

     >>> # Solution using the cumulative binomial distribution
     >>> from math import comb, fsum
     >>> round(fsum(comb(n, r) * p**r * q**(n-r) for r in range(k+1)), 4)
     0.8402

     >>> # Approximation using a simulation
     >>> from random import seed, choices
     >>> seed(8675309)
     >>> def trial():
     ...     return choices(('Python', 'Ruby'), (p, q), k=n).count('Python')
     >>> mean(trial() <= k for i in range(10_000))
     0.8398

在机器学习问题中也经常会出现正态分布。

Wikipedia 上有一个 朴素贝叶斯分类器的好例子(6)。 挑战的问题是根据对多个
正态分布的特征测量值包括身高、体重和足部尺码来预测一个人的性别。

我们得到了由八个人的测量值组成的训练数据集。 假定这些测量值是正态分布的
，因此我们用 *note NormalDist: 22c. 来总结数据：

     >>> height_male = NormalDist.from_samples([6, 5.92, 5.58, 5.92])
     >>> height_female = NormalDist.from_samples([5, 5.5, 5.42, 5.75])
     >>> weight_male = NormalDist.from_samples([180, 190, 170, 165])
     >>> weight_female = NormalDist.from_samples([100, 150, 130, 150])
     >>> foot_size_male = NormalDist.from_samples([12, 11, 12, 10])
     >>> foot_size_female = NormalDist.from_samples([6, 8, 7, 9])

接下来，我们遇到一个特征测量值已知但性别未知的新人：

     >>> ht = 6.0        # height
     >>> wt = 130        # weight
     >>> fs = 8          # foot size

从是男是女各 50% 的 先验概率(7) 出发，我们通过将该先验概率乘以给定性别的
特征度量值的可能性累积值来计算后验概率：

     >>> prior_male = 0.5
     >>> prior_female = 0.5
     >>> posterior_male = (prior_male * height_male.pdf(ht) *
     ...                   weight_male.pdf(wt) * foot_size_male.pdf(fs))

     >>> posterior_female = (prior_female * height_female.pdf(ht) *
     ...                     weight_female.pdf(wt) * foot_size_female.pdf(fs))

最终预测值应为最大后验概率值。 这种算法被称为 maximum a posteriori(8) 或
MAP：

     >>> 'male' if posterior_male > posterior_female else 'female'
     'female'

   ---------- Footnotes ----------

   (1) https://nces.ed.gov/programs/digest/d17/tables/dt17_226.40.asp

   (2) https://en.wikipedia.org/wiki/Quartile

   (3) https://en.wikipedia.org/wiki/Decile

   (4) https://en.wikipedia.org/wiki/Monte_Carlo_method

   (5) http://mathworld.wolfram.com/BinomialDistribution.html

   (6) 
https://en.wikipedia.org/wiki/Naive_Bayes_classifier#Sex_classification

   (7) https://en.wikipedia.org/wiki/Prior_probability

   (8) https://en.wikipedia.org/wiki/Maximum_a_posteriori_estimation


File: python.info,  Node: 函数式编程模块,  Next: 文件和目录访问,  Prev: 数字和数学模块,  Up: Python 标准库

5.10 函数式编程模块
===================

本章里描述的模块提供了函数和类，以支持函数式编程风格和在可调用对象上的通
用操作。

本章包含以下模块的文档：

* Menu:

* itertools: itertools --- 为高效循环而创建迭代器的函数. 为高效循环而创建迭代器的函数
* functools: functools --- 高阶函数和可调用对象上的操作. 高阶函数和可调用对象上的操作
* operator: operator --- 标准运算符替代函数. 标准运算符替代函数


File: python.info,  Node: itertools --- 为高效循环而创建迭代器的函数,  Next: functools --- 高阶函数和可调用对象上的操作,  Up: 函数式编程模块

5.10.1 ‘itertools’ — 为高效循环而创建迭代器的函数
-------------------------------------------------

__________________________________________________________________

本模块实现一系列 *note iterator: 104b. ，这些迭代器受到APL，Haskell和
SML的启发。为了适用于Python，它们都被重新写过。

本模块标准化了一个快速、高效利用内存的核心工具集，这些工具本身或组合都很
有用。它们一起形成了“迭代器代数”，这使得在纯Python中有可能创建简洁又高效
的专用工具。

例如，SML有一个制表工具： ‘tabulate(f)’，它可产生一个序列 ‘f(0), f(1),
...’。在Python中可以组合 *note map(): c35. 和 *note count(): c23. 实现：
‘map(f, count())’。

这些内置工具同时也能很好地与 *note operator: c3. 模块中的高效函数配合使
用。例如，我们可以将两个向量的点积映射到乘法运算符：
‘sum(map(operator.mul, vector1, vector2))’ 。

`无穷迭代器：'

迭代器                 实参                  结果                                                  示例
                                                                                                   
-------------------------------------------------------------------------------------------------------------------------------------------------
                                                                                                   
*note count(): c23.    start, [step]         start, start+step, start+2*step, ...                  ‘count(10) --> 10 11 12 13 14 ...’
                                                                                                   
                                                                                                   
*note cycle(): 1b4f.   p                     p0, p1, ...  plast, p0, p1, ...                       ‘cycle('ABCD') --> A B C D A B C D ...’
                                                                                                   
                                                                                                   
*note repeat(): 10c2.  elem [,n]             elem, elem, elem, ... 重复无限次或n次                 ‘repeat(10, 3) --> 10 10 10’
                                                                                                   

`根据最短输入序列长度停止的迭代器：'

迭代器                           实参                             结果                                                  示例
                                                                                                                        
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
                                                                                                                        
*note accumulate(): 1de.         p [,func]                        p0, p0+p1, p0+p1+p2, ...                              ‘accumulate([1,2,3,4,5]) --> 1 3 6 10 15’
                                                                                                                        
                                                                                                                        
*note chain(): 1613.             p, q, ...                        p0, p1, ...  plast, q0, q1, ...                       ‘chain('ABC', 'DEF') --> A B C D E F’
                                                                                                                        
                                                                                                                        
*note chain.from_iterable(): 1b50.iterable – 可迭代对象           p0, p1, ...  plast, q0, q1, ...                       ‘chain.from_iterable(['ABC', 'DEF']) --> A B C D E F’
                                                                                                                        
                                                                                                                        
*note compress(): c22.           data, selectors                  (d[0] if s[0]), (d[1] if s[1]), ...                   ‘compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F’
                                                                                                                        
                                                                                                                        
*note dropwhile(): 1b51.         pred, seq                        seq[n], seq[n+1], ... 从pred首次真值测试失败开始      ‘dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1’
                                                                                                                        
                                                                                                                        
*note filterfalse(): 15fc.       pred, seq                        seq中pred(x)为假值的元素，x是seq中的元素。            ‘filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8’
                                                                                                                        
                                                                                                                        
*note groupby(): 1b52.           iterable[, key]                  根据key(v)值分组的迭代器
                                                                  
                                                                                                                        
*note islice(): 3aa.             seq, [start,] stop [, step]      seq[start:stop:step]中的元素                          ‘islice('ABCDEFG', 2, None) --> C D E F G’
                                                                                                                        
                                                                                                                        
*note starmap(): a30.            func, seq                        func(*seq[0]), func(*seq[1]), ...                     ‘starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000’
                                                                                                                        
                                                                                                                        
*note takewhile(): 1b53.         pred, seq                        seq[0], seq[1], ..., 直到pred真值测试失败             ‘takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4’
                                                                                                                        
                                                                                                                        
*note tee(): 1b54.               it, n                            it1, it2, ...  itn 将一个迭代器拆分为n个迭代器
                                                                  
                                                                                                                        
*note zip_longest(): c39.        p, q, ...                        (p[0], q[0]), (p[1], q[1]), ...                       ‘zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-’
                                                                                                                        

`排列组合迭代器：'

迭代器                                             实参                     结果
                                                                            
----------------------------------------------------------------------------------------------------------------------------------------------
                                                                            
*note product(): caf.                              p, q, ...  [repeat=1]    笛卡尔积，相当于嵌套的for循环
                                                                            
                                                                            
*note permutations(): ed9.                         p[, r]                   长度r元组，所有可能的排列，无重复元素
                                                                            
                                                                            
*note combinations(): cae.                         p, r                     长度r元组，有序，无重复元素
                                                                            
                                                                            
*note combinations_with_replacement(): c21.        p, r                     长度r元组，有序，元素可重复
                                                                            

例子                                               结果
                                                   
---------------------------------------------------------------------------------------------------------------------
                                                   
‘product('ABCD', repeat=2)’                        ‘AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD’
                                                   
                                                   
‘permutations('ABCD', 2)’                          ‘AB AC AD BA BC BD CA CB CD DA DB DC’
                                                   
                                                   
‘combinations('ABCD', 2)’                          ‘AB AC AD BC BD CD’
                                                   
                                                   
‘combinations_with_replacement('ABCD', 2)’         ‘AA AB AC AD BB BC BD CC CD DD’
                                                   

* Menu:

* Itertool函数::
* itertools 配方::


File: python.info,  Node: Itertool函数,  Next: itertools 配方,  Up: itertools --- 为高效循环而创建迭代器的函数

5.10.1.1 Itertool函数
.....................

下列模块函数均创建并返回迭代器。有些迭代器不限制输出流长度，所以它们只应
在能截断输出流的函数或循环中使用。

 -- 函数: itertools.accumulate (iterable[, func, *, initial=None])

     创建一个迭代器，返回累积汇总值或其他双目运算函数的累积结果值（通过
     可选的 `func' 参数指定）。

     如果提供了 `func'，它应当为带有两个参数的函数。 输入 `iterable' 的
     元素可以是能被 `func' 接受为参数的任意类型。 （例如，对于默认的加法
     运算，元素可以是任何可相加的类型包括 *note Decimal: 189. 或 *note
     Fraction: 186.。）

     通常，输出的元素数量与输入的可迭代对象是一致的。 但是，如果提供了关
     键字参数 `initial'，则累加会以 `initial' 值开始，这样输出就比输入的
     可迭代对象多一个元素。

     大致相当于：

          def accumulate(iterable, func=operator.add, *, initial=None):
              'Return running totals'
              # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
              # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
              # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
              it = iter(iterable)
              total = initial
              if initial is None:
                  try:
                      total = next(it)
                  except StopIteration:
                      return
              yield total
              for element in it:
                  total = func(total, element)
                  yield total

     `func' 参数有几种用法。它可以被设为 *note min(): 812. 最终得到一个
     最小值，或者设为 *note max(): 813. 最终得到一个最大值，或设为 *note
     operator.mul(): 1b57. 最终得到一个乘积。摊销表可通过累加利息和支付
     款项得到。给iterable设置初始值并只将参数 `func' 设为累加总数可以对
     一阶 递归关系(1) 建模。

          >>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
          >>> list(accumulate(data, operator.mul))     # running product
          [3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
          >>> list(accumulate(data, max))              # running maximum
          [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

          # Amortize a 5% loan of 1000 with 4 annual payments of 90
          >>> cashflows = [1000, -90, -90, -90, -90]
          >>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
          [1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]

          # Chaotic recurrence relation https://en.wikipedia.org/wiki/Logistic_map
          >>> logistic_map = lambda x, _:  r * x * (1 - x)
          >>> r = 3.8
          >>> x0 = 0.4
          >>> inputs = repeat(x0, 36)     # only the initial value is used
          >>> [format(x, '.2f') for x in accumulate(inputs, logistic_map)]
          ['0.40', '0.91', '0.30', '0.81', '0.60', '0.92', '0.29', '0.79', '0.63',
           '0.88', '0.39', '0.90', '0.33', '0.84', '0.52', '0.95', '0.18', '0.57',
           '0.93', '0.25', '0.71', '0.79', '0.63', '0.88', '0.39', '0.91', '0.32',
           '0.83', '0.54', '0.95', '0.20', '0.60', '0.91', '0.30', '0.80', '0.60']

     参考一个类似函数 *note functools.reduce(): c77. ，它只返回一个最终
     累积值。

     3.2 新版功能.

     在 3.3 版更改: 增加可选参数 `func' 。

     在 3.8 版更改: 添加了可选的 `initial' 形参。

 -- 函数: itertools.chain (*iterables)

     创建一个迭代器，它首先返回第一个可迭代对象中所有元素，接着返回下一
     个可迭代对象中所有元素，直到耗尽所有可迭代对象中的元素。可将多个序
     列处理为单个序列。大致相当于：

          def chain(*iterables):
              # chain('ABC', 'DEF') --> A B C D E F
              for it in iterables:
                  for element in it:
                      yield element

 -- 方法: classmethod chain.from_iterable (iterable)

     构建类似 *note chain(): 1613. 迭代器的另一个选择。从一个单独的可迭
     代参数中得到链式输入，该参数是延迟计算的。大致相当于：

          def from_iterable(iterables):
              # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
              for it in iterables:
                  for element in it:
                      yield element

 -- 函数: itertools.combinations (iterable, r)

     返回由输入 `iterable' 中元素组成长度为 `r' 的子序列。

     组合元组会以字典顺序根据所输入 `iterable' 的顺序发出。 因此，如果所
     输入 `iterable' 是已排序的，组合元组也将按已排序的顺序生成。

     即使元素的值相同，不同位置的元素也被认为是不同的。如果元素各自不同
     ，那么每个组合中没有重复元素。

     大致相当于：

          def combinations(iterable, r):
              # combinations('ABCD', 2) --> AB AC AD BC BD CD
              # combinations(range(4), 3) --> 012 013 023 123
              pool = tuple(iterable)
              n = len(pool)
              if r > n:
                  return
              indices = list(range(r))
              yield tuple(pool[i] for i in indices)
              while True:
                  for i in reversed(range(r)):
                      if indices[i] != i + n - r:
                          break
                  else:
                      return
                  indices[i] += 1
                  for j in range(i+1, r):
                      indices[j] = indices[j-1] + 1
                  yield tuple(pool[i] for i in indices)

     *note combinations(): cae. 的代码可被改写为 *note permutations():
     ed9. 过滤后的子序列，（相对于元素在输入中的位置）元素不是有序的。

          def combinations(iterable, r):
              pool = tuple(iterable)
              n = len(pool)
              for indices in permutations(range(n), r):
                  if sorted(indices) == list(indices):
                      yield tuple(pool[i] for i in indices)

     当 ‘0 <= r <= n’ 时，返回项的个数是 ‘n! / r! / (n-r)!’；当 ‘r > n’
     时，返回项个数为0。

 -- 函数: itertools.combinations_with_replacement (iterable, r)

     返回由输入 `iterable' 中元素组成的长度为 `r' 的子序列，允许每个元素
     可重复出现。

     组合元组会以字典顺序根据所输入 `iterable' 的顺序发出。 因此，如果所
     输入 `iterable' 是已排序的，组合元组也将按已排序的顺序生成。

     不同位置的元素是不同的，即使它们的值相同。因此如果输入中的元素都是
     不同的话，返回的组合中元素也都会不同。

     大致相当于：

          def combinations_with_replacement(iterable, r):
              # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
              pool = tuple(iterable)
              n = len(pool)
              if not n and r:
                  return
              indices = [0] * r
              yield tuple(pool[i] for i in indices)
              while True:
                  for i in reversed(range(r)):
                      if indices[i] != n - 1:
                          break
                  else:
                      return
                  indices[i:] = [indices[i] + 1] * (r - i)
                  yield tuple(pool[i] for i in indices)

     *note combinations_with_replacement(): c21. 的代码可被改写为
     ‘production()’ 过滤后的子序列，（相对于元素在输入中的位置）元素不是
     有序的。

          def combinations_with_replacement(iterable, r):
              pool = tuple(iterable)
              n = len(pool)
              for indices in product(range(n), repeat=r):
                  if sorted(indices) == list(indices):
                      yield tuple(pool[i] for i in indices)

     当 ‘n > 0’ 时，返回项个数为 ‘(n+r-1)! / r! / (n-1)!’.

     3.1 新版功能.

 -- 函数: itertools.compress (data, selectors)

     创建一个迭代器，它返回 `data' 中经 `selectors' 真值测试为 ‘True’ 的
     元素。迭代器在两者较短的长度处停止。大致相当于：

          def compress(data, selectors):
              # compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
              return (d for d, s in zip(data, selectors) if s)

     3.1 新版功能.

 -- 函数: itertools.count (start=0, step=1)

     创建一个迭代器，它从 `start' 值开始，返回均匀间隔的值。常用于 *note
     map(): c35. 中的实参来生成连续的数据点。此外，还用于 *note zip():
     c3a. 来添加序列号。大致相当于：

          def count(start=0, step=1):
              # count(10) --> 10 11 12 13 14 ...
              # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
              n = start
              while True:
                  yield n
                  n += step

     当对浮点数计数时，替换为乘法代码有时精度会更好，例如： ‘(start +
     step * i for i in count())’ 。

     在 3.1 版更改: 增加参数 `step' ，允许非整型。

 -- 函数: itertools.cycle (iterable)

     创建一个迭代器，返回 `iterable' 中所有元素并保存一个副本。当取完
     `iterable' 中所有元素，返回副本中的所有元素。无限重复。大致相当于：

          def cycle(iterable):
              # cycle('ABCD') --> A B C D A B C D A B C D ...
              saved = []
              for element in iterable:
                  yield element
                  saved.append(element)
              while saved:
                  for element in saved:
                        yield element

     注意，该函数可能需要相当大的辅助空间（取决于 `iterable' 的长度）。

 -- 函数: itertools.dropwhile (predicate, iterable)

     创建一个迭代器，如果 `predicate' 为true，迭代器丢弃这些元素，然后返
     回其他元素。注意，迭代器在 `predicate' 首次为false之前不会产生任何
     输出，所以可能需要一定长度的启动时间。大致相当于：

          def dropwhile(predicate, iterable):
              # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
              iterable = iter(iterable)
              for x in iterable:
                  if not predicate(x):
                      yield x
                      break
              for x in iterable:
                  yield x

 -- 函数: itertools.filterfalse (predicate, iterable)

     创建一个迭代器，只返回 `iterable' 中 `predicate' 为 ‘False’ 的元素
     。如果 `predicate' 是 ‘None’，返回真值测试为false的元素。大致相当于
     ：

          def filterfalse(predicate, iterable):
              # filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
              if predicate is None:
                  predicate = bool
              for x in iterable:
                  if not predicate(x):
                      yield x

 -- 函数: itertools.groupby (iterable, key=None)

     创建一个迭代器，返回 `iterable' 中连续的键和组。`key' 是一个计算元
     素键值函数。如果未指定或为 ‘None’，`key' 缺省为恒等函数（identity
     function），返回元素不变。一般来说，`iterable' 需用同一个键值函数预
     先排序。

     *note groupby(): 1b52. 操作类似于Unix中的 ‘uniq’。当每次 `key' 函数
     产生的键值改变时，迭代器会分组或生成一个新组（这就是为什么通常需要
     使用同一个键值函数先对数据进行排序）。这种行为与SQL的GROUP BY操作不
     同，SQL的操作会忽略输入的顺序将相同键值的元素分在同组中。

     返回的组本身也是一个迭代器，它与 *note groupby(): 1b52. 共享底层的
     可迭代对象。因为源是共享的，当 *note groupby(): 1b52. 对象向后迭代
     时，前一个组将消失。因此如果稍后还需要返回结果，可保存为列表：

          groups = []
          uniquekeys = []
          data = sorted(data, key=keyfunc)
          for k, g in groupby(data, keyfunc):
              groups.append(list(g))      # Store group iterator as a list
              uniquekeys.append(k)

     *note groupby(): 1b52. 大致相当于：

          class groupby:
              # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
              # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
              def __init__(self, iterable, key=None):
                  if key is None:
                      key = lambda x: x
                  self.keyfunc = key
                  self.it = iter(iterable)
                  self.tgtkey = self.currkey = self.currvalue = object()
              def __iter__(self):
                  return self
              def __next__(self):
                  self.id = object()
                  while self.currkey == self.tgtkey:
                      self.currvalue = next(self.it)    # Exit on StopIteration
                      self.currkey = self.keyfunc(self.currvalue)
                  self.tgtkey = self.currkey
                  return (self.currkey, self._grouper(self.tgtkey, self.id))
              def _grouper(self, tgtkey, id):
                  while self.id is id and self.currkey == tgtkey:
                      yield self.currvalue
                      try:
                          self.currvalue = next(self.it)
                      except StopIteration:
                          return
                      self.currkey = self.keyfunc(self.currvalue)

 -- 函数: itertools.islice (iterable, stop)

 -- 函数: itertools.islice (iterable, start, stop[, step])

     创建一个迭代器，返回从 `iterable' 里选中的元素。如果 `start' 不是
     0，跳过 `iterable' 中的元素，直到到达 `start' 这个位置。之后迭代器
     连续返回元素，除非 `step' 设置的值很高导致被跳过。如果 `stop' 为
     ‘None’，迭代器耗光为止；否则，在指定的位置停止。与普通的切片不同，
     *note islice(): 3aa. 不支持将 `start' ， `stop' ，或 `step' 设为负
     值。可用来从内部数据结构被压平的数据中提取相关字段（例如一个多行报
     告，它的名称字段出现在每三行上）。大致相当于：

          def islice(iterable, *args):
              # islice('ABCDEFG', 2) --> A B
              # islice('ABCDEFG', 2, 4) --> C D
              # islice('ABCDEFG', 2, None) --> C D E F G
              # islice('ABCDEFG', 0, None, 2) --> A C E G
              s = slice(*args)
              start, stop, step = s.start or 0, s.stop or sys.maxsize, s.step or 1
              it = iter(range(start, stop, step))
              try:
                  nexti = next(it)
              except StopIteration:
                  # Consume *iterable* up to the *start* position.
                  for i, element in zip(range(start), iterable):
                      pass
                  return
              try:
                  for i, element in enumerate(iterable):
                      if i == nexti:
                          yield element
                          nexti = next(it)
              except StopIteration:
                  # Consume to *stop*.
                  for i, element in zip(range(i + 1, stop), iterable):
                      pass

     如果 `start' 为 ‘None’，迭代从0开始。如果 `step' 为 ‘None’ ，步长缺
     省为1。

 -- 函数: itertools.permutations (iterable, r=None)

     连续返回由 `iterable' 元素生成长度为 `r' 的排列。

     如果 `r' 未指定或为 ‘None’ ，`r' 默认设置为 `iterable' 的长度，这种
     情况下，生成所有全长排列。

     排列元组会以字典顺序根据所输入 `iterable' 的顺序发出。 因此，如果所
     输入 `iterable' 是已排序的，组合元组也将按已排序的顺序生成。

     即使元素的值相同，不同位置的元素也被认为是不同的。如果元素值都不同
     ，每个排列中的元素值不会重复。

     大致相当于：

          def permutations(iterable, r=None):
              # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
              # permutations(range(3)) --> 012 021 102 120 201 210
              pool = tuple(iterable)
              n = len(pool)
              r = n if r is None else r
              if r > n:
                  return
              indices = list(range(n))
              cycles = list(range(n, n-r, -1))
              yield tuple(pool[i] for i in indices[:r])
              while n:
                  for i in reversed(range(r)):
                      cycles[i] -= 1
                      if cycles[i] == 0:
                          indices[i:] = indices[i+1:] + indices[i:i+1]
                          cycles[i] = n - i
                      else:
                          j = cycles[i]
                          indices[i], indices[-j] = indices[-j], indices[i]
                          yield tuple(pool[i] for i in indices[:r])
                          break
                  else:
                      return

     *note permutations(): ed9. 的代码也可被改写为 *note product(): caf.
     的子序列，只要将含有重复元素（来自输入中同一位置的）的项排除。

          def permutations(iterable, r=None):
              pool = tuple(iterable)
              n = len(pool)
              r = n if r is None else r
              for indices in product(range(n), repeat=r):
                  if len(set(indices)) == r:
                      yield tuple(pool[i] for i in indices)

     当 ‘0 <= r <= n’ ，返回项个数为 ‘n! / (n-r)!’ ；当 ‘r > n’ ，返回项
     个数为0。

 -- 函数: itertools.product (*iterables, repeat=1)

     可迭代对象输入的笛卡儿积。

     大致相当于生成器表达式中的嵌套循环。例如， ‘product(A, B)’ 和
     ‘((x,y) for x in A for y in B)’ 返回结果一样。

     嵌套循环像里程表那样循环变动，每次迭代时将最右侧的元素向后迭代。这
     种模式形成了一种字典序，因此如果输入的可迭代对象是已排序的，笛卡尔
     积元组依次序发出。

     要计算可迭代对象自身的笛卡尔积，将可选参数 `repeat' 设定为要重复的
     次数。例如，‘product(A, repeat=4)’ 和 ‘product(A, A, A, A)’ 是一样
     的。

     该函数大致相当于下面的代码，只不过实际实现方案不会在内存中创建中间
     结果。

          def product(*args, repeat=1):
              # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
              # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
              pools = [tuple(pool) for pool in args] * repeat
              result = [[]]
              for pool in pools:
                  result = [x+[y] for x in result for y in pool]
              for prod in result:
                  yield tuple(prod)

 -- 函数: itertools.repeat (object[, times])

     创建一个迭代器，不断重复 `object' 。除非设定参数 `times' ，否则将无
     限重复。可用于 *note map(): c35. 函数中的参数，被调用函数可得到一个
     不变参数。也可用于 *note zip(): c3a. 的参数以在元组记录中创建一个不
     变的部分。

     大致相当于：

          def repeat(object, times=None):
              # repeat(10, 3) --> 10 10 10
              if times is None:
                  while True:
                      yield object
              else:
                  for i in range(times):
                      yield object

     `repeat' 最常见的用途就是在 `map' 或 `zip' 提供一个常量流：

          >>> list(map(pow, range(10), repeat(2)))
          [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

 -- 函数: itertools.starmap (function, iterable)

     创建一个迭代器，使用从可迭代对象中获取的参数来计算该函数。当参数对
     应的形参已从一个单独可迭代对象组合为元组时（数据已被“预组对”）可用
     此函数代替 *note map(): c35.。*note map(): c35. 与 *note starmap():
     a30. 之间的区别可以类比 ‘function(a,b)’ 与 ‘function(*c)’ 的区别。
     大致相当于:

          def starmap(function, iterable):
              # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
              for args in iterable:
                  yield function(*args)

 -- 函数: itertools.takewhile (predicate, iterable)

     创建一个迭代器，只要 predicate 为真就从可迭代对象中返回元素。大致相
     当于:

          def takewhile(predicate, iterable):
              # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
              for x in iterable:
                  if predicate(x):
                      yield x
                  else:
                      break

 -- 函数: itertools.tee (iterable, n=2)

     从一个可迭代对象中返回 `n' 个独立的迭代器。

     下面的Python代码能帮助解释 `tee' 做了什么（尽管实际的实现更复杂，而
     且仅使用了一个底层的 FIFO 队列）。

     大致相当于：

          def tee(iterable, n=2):
              it = iter(iterable)
              deques = [collections.deque() for i in range(n)]
              def gen(mydeque):
                  while True:
                      if not mydeque:             # when the local deque is empty
                          try:
                              newval = next(it)   # fetch a new value and
                          except StopIteration:
                              return
                          for d in deques:        # load it to all the deques
                              d.append(newval)
                      yield mydeque.popleft()
              return tuple(gen(d) for d in deques)

     一旦 *note tee(): 1b54. 实施了一次分裂，原有的 `iterable' 不应再被
     使用；否则tee对象无法得知 `iterable' 可能已向后迭代。

     ‘tee’ 迭代器不是线程安全的。当同时使用由同一个 *note tee(): 1b54. 调
     用所返回的迭代器时可能引发 *note RuntimeError: 2bb.，即使原本的
     `iterable' 是线程安全的。

     该迭代工具可能需要相当大的辅助存储空间（这取决于要保存多少临时数据
     ）。通常，如果一个迭代器在另一个迭代器开始之前就要使用大部份或全部
     数据，使用 *note list(): 263. 会比 *note tee(): 1b54. 更快。

 -- 函数: itertools.zip_longest (*iterables, fillvalue=None)

     创建一个迭代器，从每个可迭代对象中收集元素。如果可迭代对象的长度未
     对齐，将根据 `fillvalue' 填充缺失值。迭代持续到耗光最长的可迭代对象
     。大致相当于：

          def zip_longest(*args, fillvalue=None):
              # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
              iterators = [iter(it) for it in args]
              num_active = len(iterators)
              if not num_active:
                  return
              while True:
                  values = []
                  for i, it in enumerate(iterators):
                      try:
                          value = next(it)
                      except StopIteration:
                          num_active -= 1
                          if not num_active:
                              return
                          iterators[i] = repeat(fillvalue)
                          value = fillvalue
                      values.append(value)
                  yield tuple(values)

     如果其中一个可迭代对象有无限长度，*note zip_longest(): c39. 函数应
     封装在限制调用次数的场景中（例如 *note islice(): 3aa. 或 *note
     takewhile(): 1b53.）。除非指定， `fillvalue' 默认为 ‘None’ 。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Recurrence_relation


File: python.info,  Node: itertools 配方,  Prev: Itertool函数,  Up: itertools --- 为高效循环而创建迭代器的函数

5.10.1.2 itertools 配方
.......................

本节将展示如何使用现有的 itertools 作为基础构件来创建扩展的工具集。

基本上所有这些西方和许许多多其他的配方都可以通过 Python Package Index 上
的 more-itertools 项目(1) 来安装:

     pip install more-itertools

扩展的工具提供了与底层工具集相同的高性能。保持了超棒的内存利用率，因为一
次只处理一个元素，而不是将整个可迭代对象加载到内存。代码量保持得很小，以
函数式风格将这些工具连接在一起，有助于消除临时变量。速度依然很快，因为倾
向于使用“矢量化”构件来取代解释器开销大的 for 循环和 *note generator:
9aa. 。

     def take(n, iterable):
         "Return first n items of the iterable as a list"
         return list(islice(iterable, n))

     def prepend(value, iterator):
         "Prepend a single value in front of an iterator"
         # prepend(1, [2, 3, 4]) -> 1 2 3 4
         return chain([value], iterator)

     def tabulate(function, start=0):
         "Return function(0), function(1), ..."
         return map(function, count(start))

     def tail(n, iterable):
         "Return an iterator over the last n items"
         # tail(3, 'ABCDEFG') --> E F G
         return iter(collections.deque(iterable, maxlen=n))

     def consume(iterator, n=None):
         "Advance the iterator n-steps ahead. If n is None, consume entirely."
         # Use functions that consume iterators at C speed.
         if n is None:
             # feed the entire iterator into a zero-length deque
             collections.deque(iterator, maxlen=0)
         else:
             # advance to the empty slice starting at position n
             next(islice(iterator, n, n), None)

     def nth(iterable, n, default=None):
         "Returns the nth item or a default value"
         return next(islice(iterable, n, None), default)

     def all_equal(iterable):
         "Returns True if all the elements are equal to each other"
         g = groupby(iterable)
         return next(g, True) and not next(g, False)

     def quantify(iterable, pred=bool):
         "Count how many times the predicate is true"
         return sum(map(pred, iterable))

     def padnone(iterable):
         """Returns the sequence elements and then returns None indefinitely.

         Useful for emulating the behavior of the built-in map() function.
         """
         return chain(iterable, repeat(None))

     def ncycles(iterable, n):
         "Returns the sequence elements n times"
         return chain.from_iterable(repeat(tuple(iterable), n))

     def dotproduct(vec1, vec2):
         return sum(map(operator.mul, vec1, vec2))

     def flatten(list_of_lists):
         "Flatten one level of nesting"
         return chain.from_iterable(list_of_lists)

     def repeatfunc(func, times=None, *args):
         """Repeat calls to func with specified arguments.

         Example:  repeatfunc(random.random)
         """
         if times is None:
             return starmap(func, repeat(args))
         return starmap(func, repeat(args, times))

     def pairwise(iterable):
         "s -> (s0,s1), (s1,s2), (s2, s3), ..."
         a, b = tee(iterable)
         next(b, None)
         return zip(a, b)

     def grouper(iterable, n, fillvalue=None):
         "Collect data into fixed-length chunks or blocks"
         # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
         args = [iter(iterable)] * n
         return zip_longest(*args, fillvalue=fillvalue)

     def roundrobin(*iterables):
         "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
         # Recipe credited to George Sakkis
         num_active = len(iterables)
         nexts = cycle(iter(it).__next__ for it in iterables)
         while num_active:
             try:
                 for next in nexts:
                     yield next()
             except StopIteration:
                 # Remove the iterator we just exhausted from the cycle.
                 num_active -= 1
                 nexts = cycle(islice(nexts, num_active))

     def partition(pred, iterable):
         'Use a predicate to partition entries into false entries and true entries'
         # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
         t1, t2 = tee(iterable)
         return filterfalse(pred, t1), filter(pred, t2)

     def powerset(iterable):
         "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
         s = list(iterable)
         return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

     def unique_everseen(iterable, key=None):
         "List unique elements, preserving order. Remember all elements ever seen."
         # unique_everseen('AAAABBBCCDAABBB') --> A B C D
         # unique_everseen('ABBCcAD', str.lower) --> A B C D
         seen = set()
         seen_add = seen.add
         if key is None:
             for element in filterfalse(seen.__contains__, iterable):
                 seen_add(element)
                 yield element
         else:
             for element in iterable:
                 k = key(element)
                 if k not in seen:
                     seen_add(k)
                     yield element

     def unique_justseen(iterable, key=None):
         "List unique elements, preserving order. Remember only the element just seen."
         # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
         # unique_justseen('ABBCcAD', str.lower) --> A B C A D
         return map(next, map(operator.itemgetter(1), groupby(iterable, key)))

     def iter_except(func, exception, first=None):
         """ Call a function repeatedly until an exception is raised.

         Converts a call-until-exception interface to an iterator interface.
         Like builtins.iter(func, sentinel) but uses an exception instead
         of a sentinel to end the loop.

         Examples:
             iter_except(functools.partial(heappop, h), IndexError)   # priority queue iterator
             iter_except(d.popitem, KeyError)                         # non-blocking dict iterator
             iter_except(d.popleft, IndexError)                       # non-blocking deque iterator
             iter_except(q.get_nowait, Queue.Empty)                   # loop over a producer Queue
             iter_except(s.pop, KeyError)                             # non-blocking set iterator

         """
         try:
             if first is not None:
                 yield first()            # For database APIs needing an initial cast to db.first()
             while True:
                 yield func()
         except exception:
             pass

     def first_true(iterable, default=False, pred=None):
         """Returns the first true value in the iterable.

         If no true value is found, returns *default*

         If *pred* is not None, returns the first item
         for which pred(item) is true.

         """
         # first_true([a,b,c], x) --> a or b or c or x
         # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
         return next(filter(pred, iterable), default)

     def random_product(*args, repeat=1):
         "Random selection from itertools.product(*args, **kwds)"
         pools = [tuple(pool) for pool in args] * repeat
         return tuple(random.choice(pool) for pool in pools)

     def random_permutation(iterable, r=None):
         "Random selection from itertools.permutations(iterable, r)"
         pool = tuple(iterable)
         r = len(pool) if r is None else r
         return tuple(random.sample(pool, r))

     def random_combination(iterable, r):
         "Random selection from itertools.combinations(iterable, r)"
         pool = tuple(iterable)
         n = len(pool)
         indices = sorted(random.sample(range(n), r))
         return tuple(pool[i] for i in indices)

     def random_combination_with_replacement(iterable, r):
         "Random selection from itertools.combinations_with_replacement(iterable, r)"
         pool = tuple(iterable)
         n = len(pool)
         indices = sorted(random.randrange(n) for i in range(r))
         return tuple(pool[i] for i in indices)

     def nth_combination(iterable, r, index):
         'Equivalent to list(combinations(iterable, r))[index]'
         pool = tuple(iterable)
         n = len(pool)
         if r < 0 or r > n:
             raise ValueError
         c = 1
         k = min(r, n-r)
         for i in range(1, k+1):
             c = c * (n - k + i) // i
         if index < 0:
             index += c
         if index < 0 or index >= c:
             raise IndexError
         result = []
         while r:
             c, n, r = c*r//n, n-1, r-1
             while index >= c:
                 index -= c
                 c, n = c*(n-r)//n, n-1
             result.append(pool[-1-n])
         return tuple(result)

   ---------- Footnotes ----------

   (1) https://pypi.org/project/more-itertools/


File: python.info,  Node: functools --- 高阶函数和可调用对象上的操作,  Next: operator --- 标准运算符替代函数,  Prev: itertools --- 为高效循环而创建迭代器的函数,  Up: 函数式编程模块

5.10.2 ‘functools’ — 高阶函数和可调用对象上的操作
-------------------------------------------------

`源代码:' Lib/functools.py(1)

__________________________________________________________________

*note functools: 85. 模块应用于高阶函数，即参数或（和）返回值为其他函数
的函数。 通常来说，此模块的功能适用于所有可调用对象。

*note functools: 85. 模块定义了以下函数:

 -- 函数: @functools.cached_property (func)

     将一个类方法转换为特征属性，一次性计算该特征属性的值，然后将其缓存
     为实例生命周期内的普通属性。 类似于 *note property(): 1d8. 但增加了
     缓存功能。 对于在其他情况下实际不可变的高计算资源消耗的实例特征属性
     来说该函数非常有用。

     示例:

          class DataSet:
              def __init__(self, sequence_of_numbers):
                  self._data = sequence_of_numbers

              @cached_property
              def stdev(self):
                  return statistics.stdev(self._data)

              @cached_property
              def variance(self):
                  return statistics.variance(self._data)

     3.8 新版功能.

          注解: 此装饰器要求每个实例上的 ‘__dict__’ 属性是可变的映射。 这
          意味着它将不适用于某些类型，例如元类（因为类型实例上的
          ‘__dict__’ 属性是类命名空间的只读代理），以及那些指定了
          ‘__slots__’ 但未包含 ‘__dict__’ 作为所定义的空位之一的类（因为
          这样的类根本没有提供 ‘__dict__’ 属性）。

 -- 函数: functools.cmp_to_key (func)

     将(旧式的)比较函数转换为新式的 *note key function: 6e9. .  在类似于
     *note sorted(): 44c. ， *note min(): 812. ， *note max(): 813. ，
     *note heapq.nlargest(): 1973. ， *note heapq.nsmallest(): 1974. ，
     *note itertools.groupby(): 1b52. 等函数的 ‘key’ 参数中使用。此函数
     主要用作将 Python 2 程序转换至新版的转换工具，以保持对比较函数的兼
     容。

     比较函数意为一个可调用对象，该对象接受两个参数并比较它们，结果为小
     于则返回一个负数，相等则返回零，大于则返回一个正数。key function则
     是一个接受一个参数，并返回另一个用以排序的值的可调用对象。

     示例:

          sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order

     有关排序示例和简要排序教程，请参阅 *note 排序指南: 1611. 。

     3.2 新版功能.

 -- 函数: @functools.lru_cache (user_function)

 -- 函数: @functools.lru_cache (maxsize=128, typed=False)

     一个为函数提供缓存功能的装饰器，缓存 `maxsize' 组传入参数，在下次以
     相同参数调用时直接返回上一次的结果。用以节约高开销或I/O函数的调用时
     间。

     由于使用了字典存储缓存，所以该函数的固定参数和关键字参数必须是可哈
     希的。

     不同模式的参数可能被视为不同从而产生多个缓存项，例如, ‘f(a=1, b=2)’
     和 ‘f(b=2, a=1)’ 因其参数顺序不同，可能会被缓存两次。

     如果指定了 `user_function'，它必须是一个可调用对象。 这允许
     `lru_cache' 装饰器被直接应用于一个用户自定义函数，让 `maxsize' 保持
     其默认值 128:

          @lru_cache
          def count_vowels(sentence):
              sentence = sentence.casefold()
              return sum(sentence.count(vowel) for vowel in 'aeiou')

     如果 `maxsize' 设为 ‘None’，LRU 特性将被禁用且缓存可无限增长。

     如果 `typed' 设置为true，不同类型的函数参数将被分别缓存。例如，
     ‘f(3)’ 和 ‘f(3.0)’ 将被视为不同而分别缓存。

     为了衡量缓存的有效性以便调整 `maxsize' 形参，被装饰的函数带有一个
     ‘cache_info()’ 函数。当调用 ‘cache_info()’ 函数时，返回一个具名元组
     ，包含命中次数 `hits'，未命中次数 `misses' ，最大缓存数量 `maxsize'
     和 当前缓存大小 `currsize'。在多线程环境中，命中数与未命中数是不完
     全准确的。

     该装饰器也提供了一个用于清理/使缓存失效的函数 ‘cache_clear()’ 。

     原始的未经装饰的函数可以通过 ‘__wrapped__’ 属性访问。它可以用于检查
     、绕过缓存，或使用不同的缓存再次装饰原始函数。

     “最久未使用算法”（LRU）缓存(2) 在“最近的调用是即将到来的调用的最佳
     预测因子”时性能最好（比如，新闻服务器上最受欢迎的文章倾向于每天更改
     ）。 “缓存大小限制”参数保证缓存不会在长时间运行的进程比如说网站服务
     器上无限制的增加自身的大小。

     一般来说，LRU缓存只在当你想要重用之前计算的结果时使用。因此，用它缓
     存具有副作用的函数、需要在每次调用时创建不同、易变的对象的函数或者
     诸如time（）或random（）之类的不纯函数是没有意义的。

     静态 Web 内容的 LRU 缓存示例:

          @lru_cache(maxsize=32)
          def get_pep(num):
              'Retrieve text of a Python Enhancement Proposal'
              resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
              try:
                  with urllib.request.urlopen(resource) as s:
                      return s.read()
              except urllib.error.HTTPError:
                  return 'Not Found'

          >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
          ...     pep = get_pep(n)
          ...     print(n, len(pep))

          >>> get_pep.cache_info()
          CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)

     以下是使用缓存通过 动态规划(3) 计算 斐波那契数列(4) 的例子。

          @lru_cache(maxsize=None)
          def fib(n):
              if n < 2:
                  return n
              return fib(n-1) + fib(n-2)

          >>> [fib(n) for n in range(16)]
          [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

          >>> fib.cache_info()
          CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)

     3.2 新版功能.

     在 3.3 版更改: 添加 `typed' 选项。

     在 3.8 版更改: 添加了 `user_function' 选项。

 -- 函数: @functools.total_ordering

     给定一个声明一个或多个全比较排序方法的类，这个类装饰器实现剩余的方
     法。这减轻了指定所有可能的全比较操作的工作。

     此类必须包含以下方法之一：*note __lt__(): c3c. 、*note __le__():
     ca8.、*note __gt__(): ca9. 或 *note __ge__(): caa.。另外，此类必须
     支持 *note __eq__(): 348. 方法。

     例如

          @total_ordering
          class Student:
              def _is_valid_operand(self, other):
                  return (hasattr(other, "lastname") and
                          hasattr(other, "firstname"))
              def __eq__(self, other):
                  if not self._is_valid_operand(other):
                      return NotImplemented
                  return ((self.lastname.lower(), self.firstname.lower()) ==
                          (other.lastname.lower(), other.firstname.lower()))
              def __lt__(self, other):
                  if not self._is_valid_operand(other):
                      return NotImplemented
                  return ((self.lastname.lower(), self.firstname.lower()) <
                          (other.lastname.lower(), other.firstname.lower()))

          注解: 虽然此装饰器使得创建具有良好行为的完全有序类型变得非常容
          易，但它 `确实' 是以执行速度更缓慢和派生比较方法的堆栈回溯更复
          杂为代价的。 如果性能基准测试表明这是特定应用的瓶颈所在，则改
          为实现全部六个富比较方法应该会轻松提升速度。

     3.2 新版功能.

     在 3.4 版更改: 现在已支持从未识别类型的下层比较函数返回
     NotImplemented 异常。

 -- 函数: functools.partial (func, /, *args, **keywords)

     返回一个新的 *note 部分对象: 1b5b.，当被调用时其行为类似于 `func' 附
     带位置参数 `args' 和关键字参数 `keywords' 被调用。 如果为调用提供了
     更多的参数，它们会被附加到 `args'。 如果提供了额外的关键字参数，它
     们会扩展并重载 `keywords'。 大致等价于:

          def partial(func, /, *args, **keywords):
              def newfunc(*fargs, **fkeywords):
                  newkeywords = {**keywords, **fkeywords}
                  return func(*args, *fargs, **newkeywords)
              newfunc.func = func
              newfunc.args = args
              newfunc.keywords = keywords
              return newfunc

     *note partial(): 7d1. 会被“冻结了”一部分函数参数和/或关键字的部分函
     数应用所使用，从而得到一个具有简化签名的新对象。 例如，*note
     partial(): 7d1. 可用来创建一个行为类似于 *note int(): 185. 函数的可
     调用对象，其中 `base' 参数默认为二：

          >>> from functools import partial
          >>> basetwo = partial(int, base=2)
          >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
          >>> basetwo('10010')
          18

 -- 类: functools.partialmethod (func, /, *args, **keywords)

     返回一个新的 *note partialmethod: 29d. 描述器，其行为类似 *note
     partial: 7d1. 但它被设计用作方法定义而非直接用作可调用对象。

     `func' 必须是一个 *note descriptor: 1616. 或可调用对象（同属两者的
     对象例如普通函数会被当作描述器来处理）。

     当 `func' 是一个描述器（例如普通 Python 函数, *note classmethod():
     1d9, *note staticmethod(): 1da, ‘abstractmethod()’ 或其他 *note
     partialmethod: 29d. 的实例）时, 对 ‘__get__’ 的调用会被委托给底层的
     描述器，并会返回一个适当的 *note 部分对象: 1b5b. 作为结果。

     当 `func' 是一个非描述器类可调用对象时，则会动态创建一个适当的绑定
     方法。 当用作方法时其行为类似普通 Python 函数：将会插入 `self' 参数
     作为第一个位置参数，其位置甚至会处于提供给 *note partialmethod:
     29d. 构造器的 `args' 和 `keywords' 之前。

     示例:

          >>> class Cell(object):
          ...     def __init__(self):
          ...         self._alive = False
          ...     @property
          ...     def alive(self):
          ...         return self._alive
          ...     def set_state(self, state):
          ...         self._alive = bool(state)
          ...     set_alive = partialmethod(set_state, True)
          ...     set_dead = partialmethod(set_state, False)
          ...
          >>> c = Cell()
          >>> c.alive
          False
          >>> c.set_alive()
          >>> c.alive
          True

     3.4 新版功能.

 -- 函数: functools.reduce (function, iterable[, initializer])

     将两个参数的 `function' 从左至右积累地应用到 `iterable' 的条目，以
     便将该可迭代对象缩减为单一的值。 例如，‘reduce(lambda x, y: x+y,
     [1, 2, 3, 4, 5])’ 是计算 ‘((((1+2)+3)+4)+5)’ 的值。 左边的参数 `x'
     是积累值而右边的参数 `y' 则是来自 `iterable' 的更新值。 如果存在可
     选项 `initializer'，它会被放在参与计算的可迭代对象的条目之前，并在
     可迭代对象为空时作为默认值。 如果没有给出 `initializer' 并且
     `iterable' 仅包含一个条目，则将返回第一项。

     大致相当于：

          def reduce(function, iterable, initializer=None):
              it = iter(iterable)
              if initializer is None:
                  value = next(it)
              else:
                  value = initializer
              for element in it:
                  value = function(value, element)
              return value

     请参阅 *note itertools.accumulate(): 1de. 了解有关可产生所有中间值
     的迭代器。

 -- 函数: @functools.singledispatch

     将一个函数转换为 *note 单分派: 1cb. *note generic function: 1cc.。

     要定义一个泛型函数，应使用 ‘@singledispatch’ 装饰器进行装饰。 请注
     意分派是作用于第一个参数的类型，要相应地创建你的函数:

          >>> from functools import singledispatch
          >>> @singledispatch
          ... def fun(arg, verbose=False):
          ...     if verbose:
          ...         print("Let me just say,", end=" ")
          ...     print(arg)

     要将重载的实现添加到函数中，请使用泛型函数的 ‘register()’ 属性。 它
     是一个装饰器。 对于带有类型标注的函数，该装饰器将自动推断第一个参数
     的类型:

          >>> @fun.register
          ... def _(arg: int, verbose=False):
          ...     if verbose:
          ...         print("Strength in numbers, eh?", end=" ")
          ...     print(arg)
          ...
          >>> @fun.register
          ... def _(arg: list, verbose=False):
          ...     if verbose:
          ...         print("Enumerate this:")
          ...     for i, elem in enumerate(arg):
          ...         print(i, elem)

     对于不使用类型标注的代码，可以将适当的类型参数显式地传给装饰器本身:

          >>> @fun.register(complex)
          ... def _(arg, verbose=False):
          ...     if verbose:
          ...         print("Better than complicated.", end=" ")
          ...     print(arg.real, arg.imag)
          ...

     要启用注册 lambda 和现有函数，可以使用函数形式的 ‘register()’ 属性:

          >>> def nothing(arg, verbose=False):
          ...     print("Nothing.")
          ...
          >>> fun.register(type(None), nothing)

     ‘register()’ 属性将返回启用了装饰器堆栈、封存的未装饰函数，并会为每
     个变量单独创建单元测试:

          >>> @fun.register(float)
          ... @fun.register(Decimal)
          ... def fun_num(arg, verbose=False):
          ...     if verbose:
          ...         print("Half of your number:", end=" ")
          ...     print(arg / 2)
          ...
          >>> fun_num is fun
          False

     在调用时，泛型函数会根据第一个参数的类型进行分派:

          >>> fun("Hello, world.")
          Hello, world.
          >>> fun("test.", verbose=True)
          Let me just say, test.
          >>> fun(42, verbose=True)
          Strength in numbers, eh? 42
          >>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
          Enumerate this:
          0 spam
          1 spam
          2 eggs
          3 spam
          >>> fun(None)
          Nothing.
          >>> fun(1.23)
          0.615

     在没有用于特定类型的已注册实现的情况下，则会使用其方法解析顺序来查
     找更通用的实现。 以 ‘@singledispatch’ 装饰的原始函数将为最基本的
     ‘object’ 类型进行注册，这意味着它将在找不到更好的实现时被使用。

     要检查泛型函数将为给定类型选择哪个实现，请使用 ‘dispatch()’ 属性:

          >>> fun.dispatch(float)
          <function fun_num at 0x1035a2840>
          >>> fun.dispatch(dict)    # note: default implementation
          <function fun at 0x103fe0000>

     要访问所有忆注册实现，请使用只读的 ‘registry’ 属性:

          >>> fun.registry.keys()
          dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>,
                    <class 'decimal.Decimal'>, <class 'list'>,
                    <class 'float'>])
          >>> fun.registry[float]
          <function fun_num at 0x1035a2840>
          >>> fun.registry[object]
          <function fun at 0x103fe0000>

     3.4 新版功能.

     在 3.7 版更改: ‘register()’ 属性支持使用类型标注。

 -- 类: functools.singledispatchmethod (func)

     将一个方法转换为 *note 单分派: 1cb. *note generic function: 1cc.。

     要定义一个泛型方法，应使用 ‘@singledispatchmethod’ 装饰器进行装饰。
     请注意分派是作用于第一个非 self 或非 cls 参数的类型，要相应地创建你
     的函数:

          class Negator:
              @singledispatchmethod
              def neg(self, arg):
                  raise NotImplementedError("Cannot negate a")

              @neg.register
              def _(self, arg: int):
                  return -arg

              @neg.register
              def _(self, arg: bool):
                  return not arg

     ‘@singledispatchmethod’ 支持与其他装饰器如 ‘@classmethod’ 相嵌套。
     请注意如果要允许 ‘dispatcher.register’，则 ‘singledispatchmethod’ 必
     须是 `最外层' 的装饰器。 下面的示例定义了 ‘Negator’ 类，其中包含绑
     定到类的 ‘neg’ 方法:

          class Negator:
              @singledispatchmethod
              @classmethod
              def neg(cls, arg):
                  raise NotImplementedError("Cannot negate a")

              @neg.register
              @classmethod
              def _(cls, arg: int):
                  return -arg

              @neg.register
              @classmethod
              def _(cls, arg: bool):
                  return not arg

     同样的模式也被用于其他类似的装饰器: ‘staticmethod’,
     ‘abstractmethod’ 等等。

     3.8 新版功能.

 -- 函数: functools.update_wrapper (wrapper, wrapped,
          assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

     更新一个 `wrapper' 函数以使其类似于 `wrapped' 函数。 可选参数为指明
     原函数的哪些属性要直接被赋值给 wrapper 函数的匹配属性的元组，并且这
     些 wrapper 函数的属性将使用原函数的对应属性来更新。 这些参数的默认
     值是模块级常量 ‘WRAPPER_ASSIGNMENTS’ (它将被赋值给 wrapper 函数的
     ‘__module__’, ‘__name__’, ‘__qualname__’, ‘__annotations__’ 和
     ‘__doc__’ 即文档字符串) 以及 ‘WRAPPER_UPDATES’ (它将更新 wrapper 函
     数的 ‘__dict__’ 即实例字典)。

     为了允许出于内省和其他目的访问原始函数（例如绕过 *note lru_cache():
     1c8. 之类的缓存装饰器），此函数会自动为 wrapper 添加一个指向被包装
     函数的 ‘__wrapped__’ 属性。

     此函数的主要目的是在 *note decorator: 284. 函数中用来包装被装饰的函
     数并返回包装器。 如果包装器函数未被更新，则被返回函数的元数据将反映
     包装器定义而不是原始函数定义，这通常没有什么用处。

     *note update_wrapper(): 962. 可以与函数之外的可调用对象一同使用。 在
     `assigned' 或 `updated' 中命名的任何属性如果不存在于被包装对象则会
     被忽略（即该函数将不会尝试在包装器函数上设置它们）。 如果包装器函数
     自身缺少在 `updated' 中命名的任何属性则仍将引发 *note
     AttributeError: 3a3.。

     3.2 新版功能: 自动添加 ‘__wrapped__’ 属性。

     3.2 新版功能: 默认拷贝 ‘__annotations__’ 属性。

     在 3.2 版更改: 不存在的属性将不再触发 *note AttributeError: 3a3.。

     在 3.4 版更改: ‘__wrapped__’ 属性现在总是指向被包装的函数，即使该函
     数定义了 ‘__wrapped__’ 属性。 (参见 bpo-17482(5))

 -- 函数: @functools.wraps (wrapped, assigned=WRAPPER_ASSIGNMENTS,
          updated=WRAPPER_UPDATES)

     这是一个便捷函数，用于在定义包装器函数时发起调用 *note
     update_wrapper(): 962. 作为函数装饰器。 它等价于
     ‘partial(update_wrapper, wrapped=wrapped, assigned=assigned,
     updated=updated)’。 例如:

          >>> from functools import wraps
          >>> def my_decorator(f):
          ...     @wraps(f)
          ...     def wrapper(*args, **kwds):
          ...         print('Calling decorated function')
          ...         return f(*args, **kwds)
          ...     return wrapper
          ...
          >>> @my_decorator
          ... def example():
          ...     """Docstring"""
          ...     print('Called example function')
          ...
          >>> example()
          Calling decorated function
          Called example function
          >>> example.__name__
          'example'
          >>> example.__doc__
          'Docstring'

     如果不使用这个装饰器工厂函数，则 example 函数的名称将变为
     ‘'wrapper'’，并且 ‘example()’ 原本的文档字符串将会丢失。

* Menu:

* partial 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/functools.py

   (2) https://en.wikipedia.org/wiki/Cache_algorithms#Examples

   (3) https://zh.wikipedia.org/wiki/动态规划

   (4) https://zh.wikipedia.org/wiki/斐波那契数列

   (5) https://bugs.python.org/issue17482


File: python.info,  Node: partial 对象,  Up: functools --- 高阶函数和可调用对象上的操作

5.10.2.1 ‘partial’ 对象
.......................

*note partial: 7d1. 对象是由 *note partial(): 7d1. 创建的可调用对象。 它
们具有三个只读属性：

 -- 属性: partial.func

     一个可调用对象或函数。 对 *note partial: 7d1. 对象的调用将被转发给
     *note func: 1b5d. 并附带新的参数和关键字。

 -- 属性: partial.args

     最左边的位置参数将放置在提供给 *note partial: 7d1. 对象调用的位置参
     数之前。

 -- 属性: partial.keywords

     当调用 *note partial: 7d1. 对象时将要提供的关键字参数。

*note partial: 7d1. 对象与 ‘function’ 对象的类似之处在于它们都是可调用、
可弱引用的对象并可拥有属性。 但两者也存在一些重要的区别。 例如前者不会自
动创建 *note __name__: c6f. 和 ‘__doc__’ 属性。 而且，在类中定义的 *note
partial: 7d1. 对象的行为类似于静态方法，并且不会在实例属性查找期间转换为
绑定方法。


File: python.info,  Node: operator --- 标准运算符替代函数,  Prev: functools --- 高阶函数和可调用对象上的操作,  Up: 函数式编程模块

5.10.3 ‘operator’ — 标准运算符替代函数
--------------------------------------

`源代码:' Lib/operator.py(1)

__________________________________________________________________

*note operator: c3. 模块提供了一套与Python的内置运算符对应的高效率函数。
例如，‘operator.add(x, y)’ 与表达式 ‘x+y’ 相同。 许多函数名与特殊方法名
相同，只是没有双下划线。为了向后兼容性，也保留了许多包含双下划线的函数。
为了表述清楚，建议使用没有双下划线的函数。

函数包含的种类有：对象的比较运算、逻辑运算、数学运算以及序列运算。

对象比较函数适用于所有的对象，函数名根据它们对应的比较运算符命名。

 -- 函数: operator.lt (a, b)
 -- 函数: operator.le (a, b)
 -- 函数: operator.eq (a, b)
 -- 函数: operator.ne (a, b)
 -- 函数: operator.ge (a, b)
 -- 函数: operator.gt (a, b)
 -- 函数: operator.__lt__ (a, b)
 -- 函数: operator.__le__ (a, b)
 -- 函数: operator.__eq__ (a, b)
 -- 函数: operator.__ne__ (a, b)
 -- 函数: operator.__ge__ (a, b)
 -- 函数: operator.__gt__ (a, b)

     在 `a' 和 `b' 之间进行全比较。具体的，‘lt(a, b)’ 与 ‘a < b’ 相同，
     ‘le(a, b)’ 与 ‘a <= b’ 相同，‘eq(a, b)’ 与 ‘a == b’ 相同，‘ne(a,
     b)’ 与 ‘a != b’ 相同，‘gt(a, b)’ 与 ‘a > b’ 相同，‘ge(a, b)``与 ``a
     >= b’ 相同。注意这些函数可以返回任何值，无论它是否可当作布尔值。关
     于全比较的更多信息请参考 *note 比较运算: 1551. 。

逻辑运算通常也适用于所有对象，并且支持真值检测、标识检测和布尔运算：

 -- 函数: operator.not_ (obj)
 -- 函数: operator.__not__ (obj)

     返回 *note not: 155d. `obj' 的结果。 （请注意对象实例并没有 *note
     __not__(): 1b6f. 方法；只有解释器核心可定义此操作。 结果会受 *note
     __bool__(): c70. 和 *note __len__(): dd3. 方法影响。）

 -- 函数: operator.truth (obj)

     如果 `obj' 为真值则返回 *note True: 4a1.，否则返回 *note False:
     390.。 这等价于使用 *note bool: 184. 构造器。

 -- 函数: operator.is_ (a, b)

     返回 ‘a is b’。 检测对象标识。

 -- 函数: operator.is_not (a, b)

     返回 ‘a is not b’。 检测对象标识。

数学和按位运算的种类是最多的：

 -- 函数: operator.abs (obj)
 -- 函数: operator.__abs__ (obj)

     返回 `obj' 的绝对值。

 -- 函数: operator.add (a, b)
 -- 函数: operator.__add__ (a, b)

     对于数字 `a' 和 `b'，返回 ‘a + b’。

 -- 函数: operator.and_ (a, b)
 -- 函数: operator.__and__ (a, b)

     返回 `x' 和 `y' 按位与的结果。

 -- 函数: operator.floordiv (a, b)
 -- 函数: operator.__floordiv__ (a, b)

     返回 ‘a // b’。

 -- 函数: operator.index (a)
 -- 函数: operator.__index__ (a)

     返回 `a' 转换为整数的结果。 等价于 ‘a.__index__()’。

 -- 函数: operator.inv (obj)
 -- 函数: operator.invert (obj)
 -- 函数: operator.__inv__ (obj)
 -- 函数: operator.__invert__ (obj)

     返回数字 `obj' 按位取反的结果。 这等价于 ‘~obj’。

 -- 函数: operator.lshift (a, b)
 -- 函数: operator.__lshift__ (a, b)

     返回 `a' 左移 `b' 位的结果。

 -- 函数: operator.mod (a, b)
 -- 函数: operator.__mod__ (a, b)

     返回 ‘a % b’。

 -- 函数: operator.mul (a, b)
 -- 函数: operator.__mul__ (a, b)

     对于数字 `a' 和 `b'，返回 ‘a * b’。

 -- 函数: operator.matmul (a, b)
 -- 函数: operator.__matmul__ (a, b)

     返回 ‘a @ b’。

     3.5 新版功能.

 -- 函数: operator.neg (obj)
 -- 函数: operator.__neg__ (obj)

     返回 `obj' 取负的结果 (‘-obj’)。

 -- 函数: operator.or_ (a, b)
 -- 函数: operator.__or__ (a, b)

     返回 `a' 和 `b' 按位或的结果。

 -- 函数: operator.pos (obj)
 -- 函数: operator.__pos__ (obj)

     返回 `obj' 取正的结果 (‘+obj’)。

 -- 函数: operator.pow (a, b)
 -- 函数: operator.__pow__ (a, b)

     对于数字 `a' 和 `b'，返回 ‘a ** b’。

 -- 函数: operator.rshift (a, b)
 -- 函数: operator.__rshift__ (a, b)

     返回 `a' 右移 `b' 位的结果。

 -- 函数: operator.sub (a, b)
 -- 函数: operator.__sub__ (a, b)

     返回 ‘a - b’。

 -- 函数: operator.truediv (a, b)
 -- 函数: operator.__truediv__ (a, b)

     返回 ‘a / b’ 例如 2/3 将等于 .66 而不是 0。 这也被称为“真”除法。

 -- 函数: operator.xor (a, b)
 -- 函数: operator.__xor__ (a, b)

     返回 `a' 和 `b' 按位异或的结果。

适用于序列的操作（其中一些也适用于映射）包括：

 -- 函数: operator.concat (a, b)
 -- 函数: operator.__concat__ (a, b)

     对于序列 `a' 和 `b'，返回 ‘a + b’。

 -- 函数: operator.contains (a, b)
 -- 函数: operator.__contains__ (a, b)

     返回 ‘b in a’ 检测的结果。 请注意操作数是反序的。

 -- 函数: operator.countOf (a, b)

     返回 `b' 在 `a' 中的出现次数。

 -- 函数: operator.delitem (a, b)
 -- 函数: operator.__delitem__ (a, b)

     移除 `a' 中索引号为 `b' 的值。

 -- 函数: operator.getitem (a, b)
 -- 函数: operator.__getitem__ (a, b)

     返回 `a' 中索引为 `b' 的值。

 -- 函数: operator.indexOf (a, b)

     返回 `b' 在 `a' 中首次出现所在的索引号。

 -- 函数: operator.setitem (a, b, c)
 -- 函数: operator.__setitem__ (a, b, c)

     将 `a' 中索引号为 `b' 的值设为 `c'。

 -- 函数: operator.length_hint (obj, default=0)

     返回对象 `o' 的估计长度。 首先尝试返回其实际长度，再使用 *note
     object.__length_hint__(): 815. 得出估计值，最后返回默认值。

     3.4 新版功能.

*note operator: c3. 模块还定义了一些用于常规属性和条目查找的工具。 这些
工具适合用来编写快速字段提取器作为 *note map(): c35, *note sorted():
44c, *note itertools.groupby(): 1b52. 或其他需要相应函数参数的函数的参数
。

 -- 函数: operator.attrgetter (attr)

 -- 函数: operator.attrgetter (*attrs)

     返回一个可从操作数中获取 `attr' 的可调用对象。 如果请求了一个以上的
     属性，则返回一个属性元组。 属性名称还可包含点号。 例如：

        * 在 ‘f = attrgetter('name')’ 之后，调用 ‘f(b)’ 将返回 ‘b.name’。

        * 在 ‘f = attrgetter('name', 'date')’ 之后，调用 ‘f(b)’ 将返回
          ‘(b.name, b.date)’。

        * 在 ‘f = attrgetter('name.first', 'name.last')’ 之后，调用
          ‘f(b)’ 将返回 ‘(b.name.first, b.name.last)’。

     等价于:

          def attrgetter(*items):
              if any(not isinstance(item, str) for item in items):
                  raise TypeError('attribute name must be a string')
              if len(items) == 1:
                  attr = items[0]
                  def g(obj):
                      return resolve_attr(obj, attr)
              else:
                  def g(obj):
                      return tuple(resolve_attr(obj, attr) for attr in items)
              return g

          def resolve_attr(obj, attr):
              for name in attr.split("."):
                  obj = getattr(obj, name)
              return obj

 -- 函数: operator.itemgetter (item)

 -- 函数: operator.itemgetter (*items)

     返回一个使用操作数的 *note __getitem__(): 1b9c. 方法从操作数中获取
     `item' 的可调用对象。 如果指定了多个条目，则返回一个查找值的元组。
     例如：

        * 在 ‘f = itemgetter(2)’ 之后，调用 ‘f(r)’ 将返回 ‘r[2]’。

        * 在 ‘g = itemgetter(2, 5, 3)’ 之后，调用 ‘g(r)’ 将返回 ‘(r[2],
          r[5], r[3])’。

     等价于:

          def itemgetter(*items):
              if len(items) == 1:
                  item = items[0]
                  def g(obj):
                      return obj[item]
              else:
                  def g(obj):
                      return tuple(obj[item] for item in items)
              return g

     传入的条目可以为操作数的 *note __getitem__(): 1b9c. 所接受的任何类
     型。 字典接受任意可哈希的值。 列表、元组和字符串接受 index 或 slice
     对象：

          >>> itemgetter(1)('ABCDEFG')
          'B'
          >>> itemgetter(1, 3, 5)('ABCDEFG')
          ('B', 'D', 'F')
          >>> itemgetter(slice(2, None))('ABCDEFG')
          'CDEFG'
          >>> soldier = dict(rank='captain', name='dotterbart')
          >>> itemgetter('rank')(soldier)
          'captain'

     使用 *note itemgetter(): 262. 从元组的记录中提取特定字段的例子：

          >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
          >>> getcount = itemgetter(1)
          >>> list(map(getcount, inventory))
          [3, 2, 5, 1]
          >>> sorted(inventory, key=getcount)
          [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]

 -- 函数: operator.methodcaller (name, /, *args, **kwargs)

     返回一个在操作数上调用 `name' 方法的可调用对象。 如果给出额外的参数
     和/或关键字参数，它们也将被传给该方法。 例如：

        * 在 ‘f = methodcaller('name')’ 之后，调用 ‘f(b)’ 将返回
          ‘b.name()’。

        * 在 ‘f = methodcaller('name', 'foo', bar=1)’ 之后，调用 ‘f(b)’
          将返回 ‘b.name('foo', bar=1)’。

     等价于:

          def methodcaller(name, /, *args, **kwargs):
              def caller(obj):
                  return getattr(obj, name)(*args, **kwargs)
              return caller

* Menu:

* 将运算符映射到函数::
* 原地运算符::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/operator.py


File: python.info,  Node: 将运算符映射到函数,  Next: 原地运算符,  Up: operator --- 标准运算符替代函数

5.10.3.1 将运算符映射到函数
...........................

以下表格显示了抽象运算是如何对应于 Python 语法中的运算符和 *note
operator: c3. 模块中的函数的。

运算                        语法                          函数
                                                          
------------------------------------------------------------------------------------------------------
                                                          
加法                        ‘a + b’                       ‘add(a, b)’
                                                          
                                                          
字符串拼接                  ‘seq1 + seq2’                 ‘concat(seq1, seq2)’
                                                          
                                                          
包含测试                    ‘obj in seq’                  ‘contains(seq, obj)’
                                                          
                                                          
除法                        ‘a / b’                       ‘truediv(a, b)’
                                                          
                                                          
除法                        ‘a // b’                      ‘floordiv(a, b)’
                                                          
                                                          
按位与                      ‘a & b’                       ‘and_(a, b)’
                                                          
                                                          
按位异或                    ‘a ^ b’                       ‘xor(a, b)’
                                                          
                                                          
按位取反                    ‘~ a’                         ‘invert(a)’
                                                          
                                                          
按位或                      ‘a | b’                       ‘or_(a, b)’
                                                          
                                                          
取幂                        ‘a ** b’                      ‘pow(a, b)’
                                                          
                                                          
标识                        ‘a is b’                      ‘is_(a, b)’
                                                          
                                                          
标识                        ‘a is not b’                  ‘is_not(a, b)’
                                                          
                                                          
索引赋值                    ‘obj[k] = v’                  ‘setitem(obj, k, v)’
                                                          
                                                          
索引删除                    ‘del obj[k]’                  ‘delitem(obj, k)’
                                                          
                                                          
索引取值                    ‘obj[k]’                      ‘getitem(obj, k)’
                                                          
                                                          
左移                        ‘a << b’                      ‘lshift(a, b)’
                                                          
                                                          
取模                        ‘a % b’                       ‘mod(a, b)’
                                                          
                                                          
乘法                        ‘a * b’                       ‘mul(a, b)’
                                                          
                                                          
矩阵乘法                    ‘a @ b’                       ‘matmul(a, b)’
                                                          
                                                          
取反（算术）                ‘- a’                         ‘neg(a)’
                                                          
                                                          
取反（逻辑）                ‘not a’                       ‘not_(a)’
                                                          
                                                          
正数                        ‘+ a’                         ‘pos(a)’
                                                          
                                                          
右移                        ‘a >> b’                      ‘rshift(a, b)’
                                                          
                                                          
切片赋值                    ‘seq[i:j] = values’           ‘setitem(seq, slice(i, j), values)’
                                                          
                                                          
切片删除                    ‘del seq[i:j]’                ‘delitem(seq, slice(i, j))’
                                                          
                                                          
切片取值                    ‘seq[i:j]’                    ‘getitem(seq, slice(i, j))’
                                                          
                                                          
字符串格式化                ‘s % obj’                     ‘mod(s, obj)’
                                                          
                                                          
减法                        ‘a - b’                       ‘sub(a, b)’
                                                          
                                                          
真值测试                    ‘obj’                         ‘truth(obj)’
                                                          
                                                          
比较                        ‘a < b’                       ‘lt(a, b)’
                                                          
                                                          
比较                        ‘a <= b’                      ‘le(a, b)’
                                                          
                                                          
相等                        ‘a == b’                      ‘eq(a, b)’
                                                          
                                                          
不等                        ‘a != b’                      ‘ne(a, b)’
                                                          
                                                          
比较                        ‘a >= b’                      ‘ge(a, b)’
                                                          
                                                          
比较                        ‘a > b’                       ‘gt(a, b)’
                                                          


File: python.info,  Node: 原地运算符,  Prev: 将运算符映射到函数,  Up: operator --- 标准运算符替代函数

5.10.3.2 原地运算符
...................

许多运算都有“原地”版本。 以下列出的是提供对原地运算符相比通常语法更底层
访问的函数，例如 *note statement: 1ba2. ‘x += y’ 相当于 ‘x =
operator.iadd(x, y)’。 换一种方式来讲就是 ‘z = operator.iadd(x, y)’ 等价
于语句块 ‘z = x; z += y’。

在这些例子中，请注意当调用一个原地方法时，运算和赋值是分成两个步骤来执行
的。 下面列出的原地函数只执行第一步即调用原地方法。 第二步赋值则不加处理
。

对于不可变的目标例如字符串、数字和元组，更新的值会被计算，但不会被再被赋
值给输入变量：

     >>> a = 'hello'
     >>> iadd(a, ' world')
     'hello world'
     >>> a
     'hello'

对于可变的目标例如列表和字典，原地方法将执行更新，因此不需要后续赋值操作
：

     >>> s = ['h', 'e', 'l', 'l', 'o']
     >>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])
     ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
     >>> s
     ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

 -- 函数: operator.iadd (a, b)
 -- 函数: operator.__iadd__ (a, b)

     ‘a = iadd(a, b)’ 等价于 ‘a += b’。

 -- 函数: operator.iand (a, b)
 -- 函数: operator.__iand__ (a, b)

     ‘a = iand(a, b)’ 等价于 ‘a &= b’。

 -- 函数: operator.iconcat (a, b)
 -- 函数: operator.__iconcat__ (a, b)

     ‘a = iconcat(a, b)’ 等价于 ‘a += b’ 其中 `a' 和 `b' 为序列。

 -- 函数: operator.ifloordiv (a, b)
 -- 函数: operator.__ifloordiv__ (a, b)

     ‘a = ifloordiv(a, b)’ 等价于 ‘a //= b’。

 -- 函数: operator.ilshift (a, b)
 -- 函数: operator.__ilshift__ (a, b)

     ‘a = ilshift(a, b)’ 等价于 ‘a <<= b’。

 -- 函数: operator.imod (a, b)
 -- 函数: operator.__imod__ (a, b)

     ‘a = imod(a, b)’ 等价于 ‘a %= b’。

 -- 函数: operator.imul (a, b)
 -- 函数: operator.__imul__ (a, b)

     ‘a = imul(a, b)’ 等价于 ‘a *= b’。

 -- 函数: operator.imatmul (a, b)
 -- 函数: operator.__imatmul__ (a, b)

     ‘a = imatmul(a, b)’ 等价于 ‘a @= b’。

     3.5 新版功能.

 -- 函数: operator.ior (a, b)
 -- 函数: operator.__ior__ (a, b)

     ‘a = ior(a, b)’ 等价于 ‘a |= b’。

 -- 函数: operator.ipow (a, b)
 -- 函数: operator.__ipow__ (a, b)

     ‘a = ipow(a, b)’ 等价于 ‘a **= b’。

 -- 函数: operator.irshift (a, b)
 -- 函数: operator.__irshift__ (a, b)

     ‘a = irshift(a, b)’ 等价于 ‘a >>= b’。

 -- 函数: operator.isub (a, b)
 -- 函数: operator.__isub__ (a, b)

     ‘a = isub(a, b)’ 等价于 ‘a -= b’。

 -- 函数: operator.itruediv (a, b)
 -- 函数: operator.__itruediv__ (a, b)

     ‘a = itruediv(a, b)’ 等价于 ‘a /= b’。

 -- 函数: operator.ixor (a, b)
 -- 函数: operator.__ixor__ (a, b)

     ‘a = ixor(a, b)’ 等价于 ‘a ^= b’。


File: python.info,  Node: 文件和目录访问,  Next: 数据持久化,  Prev: 函数式编程模块,  Up: Python 标准库

5.11 文件和目录访问
===================

本章中描述的模块处理磁盘文件和目录。 例如，有一些模块用于读取文件的属性
，以可移植的方式操作路径以及创建临时文件。 本章的完整模块列表如下：

* Menu:

* pathlib: pathlib --- 面向对象的文件系统路径. 面向对象的文件系统路径
* os.path: os path --- 常用路径操作. 常用路径操作
* fileinput: fileinput --- 迭代来自多个输入流的行. 迭代来自多个输入流的行
* stat: stat --- 解析 stat 结果. 解析 stat() 结果
* filecmp: filecmp --- 文件及目录的比较. 文件及目录的比较
* tempfile: tempfile --- 生成临时文件和目录. 生成临时文件和目录
* glob: glob --- Unix 风格路径名模式扩展. Unix 风格路径名模式扩展
* fnmatch: fnmatch --- Unix 文件名模式匹配. Unix 文件名模式匹配
* linecache: linecache --- 随机读写文本行. 随机读写文本行
* shutil: shutil --- 高阶文件操作. 高阶文件操作


File: python.info,  Node: pathlib --- 面向对象的文件系统路径,  Next: os path --- 常用路径操作,  Up: 文件和目录访问

5.11.1 ‘pathlib’ — 面向对象的文件系统路径
-----------------------------------------

3.4 新版功能.

`源代码' Lib/pathlib.py(1)

__________________________________________________________________

该模块提供表示文件系统路径的类，其语义适用于不同的操作系统。路径类被分为
提供纯计算操作而没有 I/O 的 *note 纯路径: 1bc3.，以及从纯路径继承而来但
提供 I/O 操作的 *note 具体路径: 1bc4.。

[python-figures/pathlib-inheritance]
如果你以前从未使用过此模块或者不确定在项目中使用哪一个类是正确的，则
*note Path: 202. 总是你需要的。它在运行代码的平台上实例化为一个 *note
具体路径: 1bc4.。

在一些用例中纯路径很有用，例如：

  1. 如果你想要在 Unix 设备上操作 Windows 路径（或者相反）。你不应在
     Unix 上实例化一个 *note WindowsPath: 1bc5.，但是你可以实例化 *note
     PureWindowsPath: 1bc6.。

  2. 你只想操作路径但不想实际访问操作系统。在这种情况下，实例化一个纯路
     径是有用的，因为它们没有任何访问操作系统的操作。

参见
....

PEP 428(2)：pathlib 模块 – 面向对象的的文件系统路径。

参见
....

对于底层的路径字符串操作，你也可以使用 *note os.path: c6. 模块。

* Menu:

* 基础使用::
* 纯路径::
* 具体路径::
* 对应的 os 模块的工具::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/pathlib.py

   (2) https://www.python.org/dev/peps/pep-0428


File: python.info,  Node: 基础使用,  Next: 纯路径,  Up: pathlib --- 面向对象的文件系统路径

5.11.1.1 基础使用
.................

导入主类:

     >>> from pathlib import Path

列出子目录:

     >>> p = Path('.')
     >>> [x for x in p.iterdir() if x.is_dir()]
     [PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
      PosixPath('__pycache__'), PosixPath('build')]

列出当前目录树下的所有 Python 源代码文件:

     >>> list(p.glob('**/*.py'))
     [PosixPath('test_pathlib.py'), PosixPath('setup.py'),
      PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
      PosixPath('build/lib/pathlib.py')]

在目录树中移动:

     >>> p = Path('/etc')
     >>> q = p / 'init.d' / 'reboot'
     >>> q
     PosixPath('/etc/init.d/reboot')
     >>> q.resolve()
     PosixPath('/etc/rc.d/init.d/halt')

查询路径的属性:

     >>> q.exists()
     True
     >>> q.is_dir()
     False

打开一个文件:

     >>> with q.open() as f: f.readline()
     ...
     '#!/bin/bash\n'


File: python.info,  Node: 纯路径,  Next: 具体路径,  Prev: 基础使用,  Up: pathlib --- 面向对象的文件系统路径

5.11.1.2 纯路径
...............

纯路径对象提供了不实际访问文件系统的路径处理操作。有三种方式来访问这些类
，也是不同的风格：

 -- 类: pathlib.PurePath (*pathsegments)

     一个通用的类，代表当前系统的路径风格（实例化为 *note PurePosixPath:
     1bc9. 或者 *note PureWindowsPath: 1bc6.）:

          >>> PurePath('setup.py')      # Running on a Unix machine
          PurePosixPath('setup.py')

     每一个 `pathsegments' 的元素可能是一个代表路径片段的字符串，一个返
     回字符串的实现了 *note os.PathLike: 4f3. 接口的对象，或者另一个路径
     对象:

          >>> PurePath('foo', 'some/path', 'bar')
          PurePosixPath('foo/some/path/bar')
          >>> PurePath(Path('foo'), Path('bar'))
          PurePosixPath('foo/bar')

     当 `pathsegments' 为空的时候，假定为当前目录:

          >>> PurePath()
          PurePosixPath('.')

     当给出一些绝对路径，最后一位将被当作锚（模仿 *note os.path.join():
     f6c. 的行为）:

          >>> PurePath('/etc', '/usr', 'lib64')
          PurePosixPath('/usr/lib64')
          >>> PureWindowsPath('c:/Windows', 'd:bar')
          PureWindowsPath('d:bar')

     但是，在 Windows 路径中，改变本地根目录并不会丢弃之前盘符的设置:

          >>> PureWindowsPath('c:/Windows', '/Program Files')
          PureWindowsPath('c:/Program Files')

     假斜线和单独的点都会被消除，但是双点 （‘‘..’’） 不会，以防改变符号
     链接的含义。

          >>> PurePath('foo//bar')
          PurePosixPath('foo/bar')
          >>> PurePath('foo/./bar')
          PurePosixPath('foo/bar')
          >>> PurePath('foo/../bar')
          PurePosixPath('foo/../bar')

     （一个很 naïve 的做法是让 ‘PurePosixPath('foo/../bar')’ 等同于
     ‘PurePosixPath('bar')’，如果 ‘foo’ 是一个指向其他目录的符号链接那么
     这个做法就将出错）

     纯路径对象实现了 *note os.PathLike: 4f3. 接口，允许它们在任何接受此
     接口的地方使用。

     在 3.6 版更改: 添加了 *note os.PathLike: 4f3. 接口支持。

 -- 类: pathlib.PurePosixPath (*pathsegments)

     一个 *note PurePath: 1051. 的子类，路径风格不同于 Windows 文件系统:

          >>> PurePosixPath('/etc')
          PurePosixPath('/etc')

     `pathsegments' 参数的指定和 *note PurePath: 1051. 相同。

 -- 类: pathlib.PureWindowsPath (*pathsegments)

     *note PurePath: 1051. 的一个子类，路径风格为 Windows 文件系统路径:

          >>> PureWindowsPath('c:/Program Files/')
          PureWindowsPath('c:/Program Files')

     `pathsegments' 参数的指定和 *note PurePath: 1051. 相同。

无论你正运行什么系统，你都可以实例化这些类，因为它们提供的操作不做任何系
统调用。

* Menu:

* 通用性质::
* 运算符: 运算符<2>.
* 访问个别部分::
* 方法和特征属性::


File: python.info,  Node: 通用性质,  Next: 运算符<2>,  Up: 纯路径

5.11.1.3 通用性质
.................

路径是不可变并可哈希的。相同风格的路径可以排序与比较。这些性质尊重对应风
格的大小写转换语义:

     >>> PurePosixPath('foo') == PurePosixPath('FOO')
     False
     >>> PureWindowsPath('foo') == PureWindowsPath('FOO')
     True
     >>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }
     True
     >>> PureWindowsPath('C:') < PureWindowsPath('d:')
     True

不同风格的路径比较得到不等的结果并且无法被排序:

     >>> PureWindowsPath('foo') == PurePosixPath('foo')
     False
     >>> PureWindowsPath('foo') < PurePosixPath('foo')
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'


File: python.info,  Node: 运算符<2>,  Next: 访问个别部分,  Prev: 通用性质,  Up: 纯路径

5.11.1.4 运算符
...............

斜杠 ‘/’ 操作符有助于创建子路径，就像 *note os.path.join(): f6c. 一样:

     >>> p = PurePath('/etc')
     >>> p
     PurePosixPath('/etc')
     >>> p / 'init.d' / 'apache2'
     PurePosixPath('/etc/init.d/apache2')
     >>> q = PurePath('bin')
     >>> '/usr' / q
     PurePosixPath('/usr/bin')

文件对象可用于任何接受 *note os.PathLike: 4f3. 接口实现的地方。

     >>> import os
     >>> p = PurePath('/etc')
     >>> os.fspath(p)
     '/etc'

路径的字符串表示法为它自己原始的文件系统路径（以原生形式，例如在 Windows
下使用反斜杠）。你可以传递给任何需要字符串形式路径的函数。

     >>> p = PurePath('/etc')
     >>> str(p)
     '/etc'
     >>> p = PureWindowsPath('c:/Program Files')
     >>> str(p)
     'c:\\Program Files'

类似地，在路径上调用 *note bytes: 33a. 将原始文件系统路径作为字节对象给
出，就像被 *note os.fsencode(): 4f7. 编码一样:

     >>> bytes(p)
     b'/etc'

     注解: 只推荐在 Unix 下调用 *note bytes: 33a.。在 Windows， unicode
     形式是文件系统路径的规范表示法。


File: python.info,  Node: 访问个别部分,  Next: 方法和特征属性,  Prev: 运算符<2>,  Up: 纯路径

5.11.1.5 访问个别部分
.....................

为了访问路径独立的部分 （组件），使用以下特征属性：

 -- 数据: PurePath.parts

     一个元组，可以访问路径的多个组件:

          >>> p = PurePath('/usr/bin/python3')
          >>> p.parts
          ('/', 'usr', 'bin', 'python3')

          >>> p = PureWindowsPath('c:/Program Files/PSF')
          >>> p.parts
          ('c:\\', 'Program Files', 'PSF')

     （注意盘符和本地根目录是如何重组的）


File: python.info,  Node: 方法和特征属性,  Prev: 访问个别部分,  Up: 纯路径

5.11.1.6 方法和特征属性
.......................

纯路径提供以下方法和特征属性：

 -- 数据: PurePath.drive

     一个表示驱动器盘符或命名的字符串，如果存在:

          >>> PureWindowsPath('c:/Program Files/').drive
          'c:'
          >>> PureWindowsPath('/Program Files/').drive
          ''
          >>> PurePosixPath('/etc').drive
          ''

     UNC 分享也被认作驱动器:

          >>> PureWindowsPath('//host/share/foo.txt').drive
          '\\\\host\\share'

 -- 数据: PurePath.root

     一个表示（本地或全局）根的字符串，如果存在:

          >>> PureWindowsPath('c:/Program Files/').root
          '\\'
          >>> PureWindowsPath('c:Program Files/').root
          ''
          >>> PurePosixPath('/etc').root
          '/'

     UNC 分享一样拥有根:

          >>> PureWindowsPath('//host/share').root
          '\\'

 -- 数据: PurePath.anchor

     驱动器和根的联合:

          >>> PureWindowsPath('c:/Program Files/').anchor
          'c:\\'
          >>> PureWindowsPath('c:Program Files/').anchor
          'c:'
          >>> PurePosixPath('/etc').anchor
          '/'
          >>> PureWindowsPath('//host/share').anchor
          '\\\\host\\share\\'

 -- 数据: PurePath.parents

     An immutable sequence providing access to the logical ancestors of
     the path:

          >>> p = PureWindowsPath('c:/foo/bar/setup.py')
          >>> p.parents[0]
          PureWindowsPath('c:/foo/bar')
          >>> p.parents[1]
          PureWindowsPath('c:/foo')
          >>> p.parents[2]
          PureWindowsPath('c:/')

 -- 数据: PurePath.parent

     此路径的逻辑父路径:

          >>> p = PurePosixPath('/a/b/c/d')
          >>> p.parent
          PurePosixPath('/a/b/c')

     你不能超过一个 anchor 或空路径:

          >>> p = PurePosixPath('/')
          >>> p.parent
          PurePosixPath('/')
          >>> p = PurePosixPath('.')
          >>> p.parent
          PurePosixPath('.')

          注解: 这是一个单纯的词法操作，因此有以下行为:

               >>> p = PurePosixPath('foo/..')
               >>> p.parent
               PurePosixPath('foo')

          如果你想要向上移动任意文件系统路径，推荐先使用 *note
          Path.resolve(): 1bd4. 来解析符号链接以及消除 ‘".."’ 组件。

 -- 数据: PurePath.name

     一个表示最后路径组件的字符串，排除了驱动器与根目录，如果存在的话:

          >>> PurePosixPath('my/library/setup.py').name
          'setup.py'

     UNC 驱动器名不被考虑:

          >>> PureWindowsPath('//some/share/setup.py').name
          'setup.py'
          >>> PureWindowsPath('//some/share').name
          ''

 -- 数据: PurePath.suffix

     最后一个组件的文件扩展名，如果存在:

          >>> PurePosixPath('my/library/setup.py').suffix
          '.py'
          >>> PurePosixPath('my/library.tar.gz').suffix
          '.gz'
          >>> PurePosixPath('my/library').suffix
          ''

 -- 数据: PurePath.suffixes

     路径的文件扩展名列表:

          >>> PurePosixPath('my/library.tar.gar').suffixes
          ['.tar', '.gar']
          >>> PurePosixPath('my/library.tar.gz').suffixes
          ['.tar', '.gz']
          >>> PurePosixPath('my/library').suffixes
          []

 -- 数据: PurePath.stem

     最后一个路径组件，除去后缀:

          >>> PurePosixPath('my/library.tar.gz').stem
          'library.tar'
          >>> PurePosixPath('my/library.tar').stem
          'library'
          >>> PurePosixPath('my/library').stem
          'library'

 -- 方法: PurePath.as_posix ()

     返回使用正斜杠（‘/’）的路径字符串:

          >>> p = PureWindowsPath('c:\\windows')
          >>> str(p)
          'c:\\windows'
          >>> p.as_posix()
          'c:/windows'

 -- 方法: PurePath.as_uri ()

     将路径表示为 ‘file’ URL。如果并非绝对路径，抛出 *note ValueError:
     1fc.。

          >>> p = PurePosixPath('/etc/passwd')
          >>> p.as_uri()
          'file:///etc/passwd'
          >>> p = PureWindowsPath('c:/Windows')
          >>> p.as_uri()
          'file:///c:/Windows'

 -- 方法: PurePath.is_absolute ()

     返回此路径是否为绝对路径。如果路径同时拥有驱动器符与根路径（如果风
     格允许）则将被认作绝对路径。

          >>> PurePosixPath('/a/b').is_absolute()
          True
          >>> PurePosixPath('a/b').is_absolute()
          False

          >>> PureWindowsPath('c:/a/b').is_absolute()
          True
          >>> PureWindowsPath('/a/b').is_absolute()
          False
          >>> PureWindowsPath('c:').is_absolute()
          False
          >>> PureWindowsPath('//some/share').is_absolute()
          True

 -- 方法: PurePath.is_reserved ()

     在 *note PureWindowsPath: 1bc6.，如果路径是被 Windows 保留的则返回
     ‘True’，否则 ‘False’。在 *note PurePosixPath: 1bc9.，总是返回
     ‘False’。

          >>> PureWindowsPath('nul').is_reserved()
          True
          >>> PurePosixPath('nul').is_reserved()
          False

     当保留路径上的文件系统被调用，则可能出现玄学失败或者意料之外的效应
     。

 -- 方法: PurePath.joinpath (*other)

     调用此方法等同于将每个 `other' 参数中的项目连接在一起:

          >>> PurePosixPath('/etc').joinpath('passwd')
          PurePosixPath('/etc/passwd')
          >>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
          PurePosixPath('/etc/passwd')
          >>> PurePosixPath('/etc').joinpath('init.d', 'apache2')
          PurePosixPath('/etc/init.d/apache2')
          >>> PureWindowsPath('c:').joinpath('/Program Files')
          PureWindowsPath('c:/Program Files')

 -- 方法: PurePath.match (pattern)

     将此路径与提供的通配符风格的模式匹配。如果匹配成功则返回 ‘True’，否
     则返回 ‘False’。

     如果 `pattern' 是相对的，则路径可以是相对路径或绝对路径，并且匹配是
     从右侧完成的：

          >>> PurePath('a/b.py').match('*.py')
          True
          >>> PurePath('/a/b/c.py').match('b/*.py')
          True
          >>> PurePath('/a/b/c.py').match('a/*.py')
          False

     如果 `pattern' 是绝对的，则路径必须是绝对的，并且路径必须完全匹配:

          >>> PurePath('/a.py').match('/*.py')
          True
          >>> PurePath('a/b.py').match('/*.py')
          False

     与其他方法一样，是否大小写敏感遵循平台的默认规则:

          >>> PurePosixPath('b.py').match('*.PY')
          False
          >>> PureWindowsPath('b.py').match('*.PY')
          True

 -- 方法: PurePath.relative_to (*other)

     计算此路径相对 `other' 表示路径的版本。如果不可计算，则抛出
     ValueError:

          >>> p = PurePosixPath('/etc/passwd')
          >>> p.relative_to('/')
          PurePosixPath('etc/passwd')
          >>> p.relative_to('/etc')
          PurePosixPath('passwd')
          >>> p.relative_to('/usr')
          Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
            File "pathlib.py", line 694, in relative_to
              .format(str(self), str(formatted)))
          ValueError: '/etc/passwd' does not start with '/usr'

 -- 方法: PurePath.with_name (name)

     返回一个新的路径并修改 *note name: 1bd5.。如果原本路径没有 name，
     ValueError 被抛出:

          >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
          >>> p.with_name('setup.py')
          PureWindowsPath('c:/Downloads/setup.py')
          >>> p = PureWindowsPath('c:/')
          >>> p.with_name('setup.py')
          Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
            File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name
              raise ValueError("%r has an empty name" % (self,))
          ValueError: PureWindowsPath('c:/') has an empty name

 -- 方法: PurePath.with_suffix (suffix)

     返回一个新的路径并修改 *note suffix: 1bd6.。如果原本的路径没有后缀
     ，新的 `suffix' 则被追加以代替。如果 `suffix' 是空字符串，则原本的
     后缀被移除:

          >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
          >>> p.with_suffix('.bz2')
          PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
          >>> p = PureWindowsPath('README')
          >>> p.with_suffix('.txt')
          PureWindowsPath('README.txt')
          >>> p = PureWindowsPath('README.txt')
          >>> p.with_suffix('')
          PureWindowsPath('README')


File: python.info,  Node: 具体路径,  Next: 对应的 os 模块的工具,  Prev: 纯路径,  Up: pathlib --- 面向对象的文件系统路径

5.11.1.7 具体路径
.................

具体路径是纯路径的子类。除了后者提供的操作之外，它们还提供了对路径对象进
行系统调用的方法。有三种方法可以实例化具体路径:

 -- 类: pathlib.Path (*pathsegments)

     一个 *note PurePath: 1051. 的子类，此类以当前系统的路径风格表示路径
     （实例化为 *note PosixPath: 1be2. 或 *note WindowsPath: 1bc5.）:

          >>> Path('setup.py')
          PosixPath('setup.py')

     `pathsegments' 参数的指定和 *note PurePath: 1051. 相同。

 -- 类: pathlib.PosixPath (*pathsegments)

     一个 *note Path: 202. 和 *note PurePosixPath: 1bc9. 的子类，此类表
     示一个非 Windows 文件系统的具体路径:

          >>> PosixPath('/etc')
          PosixPath('/etc')

     `pathsegments' 参数的指定和 *note PurePath: 1051. 相同。

 -- 类: pathlib.WindowsPath (*pathsegments)

     *note Path: 202. 和 *note PureWindowsPath: 1bc6. 的子类，从类表示一
     个 Windows 文件系统的具体路径:

          >>> WindowsPath('c:/Program Files/')
          WindowsPath('c:/Program Files')

     `pathsegments' 参数的指定和 *note PurePath: 1051. 相同。

你只能实例化与当前系统风格相同的类（允许系统调用作用于不兼容的路径风格可
能在应用程序中导致缺陷或失败）:

     >>> import os
     >>> os.name
     'posix'
     >>> Path('setup.py')
     PosixPath('setup.py')
     >>> PosixPath('setup.py')
     PosixPath('setup.py')
     >>> WindowsPath('setup.py')
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
       File "pathlib.py", line 798, in __new__
         % (cls.__name__,))
     NotImplementedError: cannot instantiate 'WindowsPath' on your system

* Menu:

* 方法: 方法<2>.


File: python.info,  Node: 方法<2>,  Up: 具体路径

5.11.1.8 方法
.............

除纯路径方法外，实体路径还提供以下方法。 如果系统调用失败（例如因为路径
不存在）这些方法中许多都会引发 *note OSError: 1d4.。

在 3.8 版更改: 对于包含 OS 层级无法表示字符的路径，*note exists(): 203,
*note is_dir(): 204, *note is_file(): 205, *note is_mount(): 206, *note
is_symlink(): 207, *note is_block_device(): 208, *note is_char_device():
209, *note is_fifo(): 20a, *note is_socket(): 20b. 现在将返回 ‘False’ 而
不是引发异常。

 -- 方法: classmethod Path.cwd ()

     返回一个新的表示当前目录的路径对象（和 *note os.getcwd(): fee. 返回
     的相同）:

          >>> Path.cwd()
          PosixPath('/home/antoine/pathlib')

 -- 方法: classmethod Path.home ()

     返回一个表示当前用户家目录的新路径对象（和 *note
     os.path.expanduser(): 1ff. 构造含 ‘~’ 路径返回的相同）:

          >>> Path.home()
          PosixPath('/home/antoine')

     3.5 新版功能.

 -- 方法: Path.stat ()

     返回一个 *note os.stat_result: 109a. 对象，其中包含有关此路径的信息
     ，例如 *note os.stat(): 1f2.。 结果会在每次调用此方法时重新搜索。

          >>> p = Path('setup.py')
          >>> p.stat().st_size
          956
          >>> p.stat().st_mtime
          1327883547.852554

 -- 方法: Path.chmod (mode)

     改变文件的模式和权限，和 *note os.chmod(): a3b. 一样:

          >>> p = Path('setup.py')
          >>> p.stat().st_mode
          33277
          >>> p.chmod(0o444)
          >>> p.stat().st_mode
          33060

 -- 方法: Path.exists ()

     此路径是否指向一个已存在的文件或目录:

          >>> Path('.').exists()
          True
          >>> Path('setup.py').exists()
          True
          >>> Path('/etc').exists()
          True
          >>> Path('nonexistentfile').exists()
          False

          注解: 如果路径指向一个符号链接， *note exists(): 203. 返回此符
          号链接是否指向存在的文件或目录。

 -- 方法: Path.expanduser ()

     返回展开了包含 ‘~’ 和 ‘~user’ 的构造，就和 *note
     os.path.expanduser(): 1ff. 一样:

          >>> p = PosixPath('~/films/Monty Python')
          >>> p.expanduser()
          PosixPath('/home/eric/films/Monty Python')

     3.5 新版功能.

 -- 方法: Path.glob (pattern)

     解析相对于此路径的通配符 `pattern'，产生所有匹配的文件:

          >>> sorted(Path('.').glob('*.py'))
          [PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
          >>> sorted(Path('.').glob('*/*.py'))
          [PosixPath('docs/conf.py')]

     "‘**’" 模式表示 “此目录以及所有子目录，递归”。换句话说，它启用递归
     通配:

          >>> sorted(Path('.').glob('**/*.py'))
          [PosixPath('build/lib/pathlib.py'),
           PosixPath('docs/conf.py'),
           PosixPath('pathlib.py'),
           PosixPath('setup.py'),
           PosixPath('test_pathlib.py')]

          注解: 在一个较大的目录树中使用 "‘**’" 模式可能会消耗非常多的时
          间。

 -- 方法: Path.group ()

     返回拥有此文件的用户组。如果文件的 GID 无法在系统数据库中找到，将抛
     出 *note KeyError: 2c8. 。

 -- 方法: Path.is_dir ()

     如果路径指向一个目录（或者一个指向目录的符号链接）则返回 ‘True’，如
     果指向其他类型的文件则返回 ‘False’。

     当路径不存在或者是一个破损的符号链接时也会返回 ‘False’；其他错误（
     例如权限错误）被传播。

 -- 方法: Path.is_file ()

     如果路径指向一个正常的文件（或者一个指向正常文件的符号链接）则返回
     ‘True’，如果指向其他类型的文件则返回 ‘False’。

     当路径不存在或者是一个破损的符号链接时也会返回 ‘False’；其他错误（
     例如权限错误）被传播。

 -- 方法: Path.is_mount ()

     如果路径是一个 `挂载点 <mount point>'：在文件系统中被其他不同的文件
     系统挂载的地点。在 POSIX 系统，此函数检查 `path' 的父级 ——
     ‘path/..’ 是否处于一个和 `path' 不同的设备中，或者 file:‘path/..’ 和
     `path' 是否指向相同设备的相同 i-node —— 这能检测所有 Unix 以及
     POSIX 变种上的挂载点。 Windows 上未实现。

     3.7 新版功能.

 -- 方法: Path.is_symlink ()

     如果路径指向符号链接则返回 ‘True’， 否则 ‘False’。

     如果路径不存在也返回 ‘False’；其他错误（例如权限错误）被传播。

 -- 方法: Path.is_socket ()

     如果路径指向一个 Unix socket 文件（或者指向 Unix socket 文件的符号
     链接）则返回 ‘True’，如果指向其他类型的文件则返回 ‘False’。

     当路径不存在或者是一个破损的符号链接时也会返回 ‘False’；其他错误（
     例如权限错误）被传播。

 -- 方法: Path.is_fifo ()

     如果路径指向一个先进先出存储（或者指向先进先出存储的符号链接）则返
     回 ‘True’ ，指向其他类型的文件则返回 ‘False’。

     当路径不存在或者是一个破损的符号链接时也会返回 ‘False’；其他错误（
     例如权限错误）被传播。

 -- 方法: Path.is_block_device ()

     如果文件指向一个块设备（或者指向块设备的符号链接）则返回 ‘True’，指
     向其他类型的文件则返回 ‘False’。

     当路径不存在或者是一个破损的符号链接时也会返回 ‘False’；其他错误（
     例如权限错误）被传播。

 -- 方法: Path.is_char_device ()

     如果路径指向一个字符设备（或指向字符设备的符号链接）则返回 ‘True’，
     指向其他类型的文件则返回 ‘False’。

     当路径不存在或者是一个破损的符号链接时也会返回 ‘False’；其他错误（
     例如权限错误）被传播。

 -- 方法: Path.iterdir ()

     当路径指向一个目录时，产生该路径下的对象的路径:

          >>> p = Path('docs')
          >>> for child in p.iterdir(): child
          ...
          PosixPath('docs/conf.py')
          PosixPath('docs/_templates')
          PosixPath('docs/make.bat')
          PosixPath('docs/index.rst')
          PosixPath('docs/_build')
          PosixPath('docs/_static')
          PosixPath('docs/Makefile')

     子条目会以任意顺序生成，并且不包括特殊条目 ‘'.'’ 和 ‘'..'’。 如果有
     文件在迭代器创建之后在目录中被移除或添加，是否要包括该文件对应的路
     径对象并没有规定。

 -- 方法: Path.lchmod (mode)

     就像 *note Path.chmod(): 1be6. 但是如果路径指向符号链接则是修改符号
     链接的模式，而不是修改符号链接的目标。

 -- 方法: Path.lstat ()

     就和 *note Path.stat(): 1be5. 一样，但是如果路径指向符号链接，则是
     返回符号链接而不是目标的信息。

 -- 方法: Path.mkdir (mode=0o777, parents=False, exist_ok=False)

     新建给定路径的目录。如果给出了 `mode' ，它将与当前进程的 ‘umask’ 值
     合并来决定文件模式和访问标志。如果路径已经存在，则抛出 *note
     FileExistsError: 960.。

     如果 `parents' 为 true，任何找不到的父目录都会伴随着此路径被创建；
     它们会以默认权限被创建，而不考虑 `mode' 设置（模仿 POSIX 的 ‘mkdir
     -p’ 命令）。

     如果 `parents' 为 false（默认），则找不到的父级目录会导致 *note
     FileNotFoundError: 7c9. 被抛出。

     如果 `exist_ok' 为 false（默认），则在目标已存在的情况下抛出 *note
     FileExistsError: 960.。

     如果 `exist_ok' 为 true， 则 *note FileExistsError: 960. 异常将被忽
     略（和 POSIX ‘mkdir -p’ 命令行为相同），但是只有在最后一个路径组件
     不是现存的非目录文件时才生效。

     在 3.5 版更改: `exist_ok' 形参被加入。

 -- 方法: Path.open (mode='r', buffering=-1, encoding=None, errors=None,
          newline=None)

     打开路径指向的文件，就像内置的 *note open(): 4f8. 函数所做的一样:

          >>> p = Path('setup.py')
          >>> with p.open() as f:
          ...     f.readline()
          ...
          '#!/usr/bin/env python3\n'

 -- 方法: Path.owner ()

     返回拥有此文件的用户名。如果文件的 UID 无法在系统数据库中找到，则抛
     出 *note KeyError: 2c8.。

 -- 方法: Path.read_bytes ()

     以字节对象的形式返回路径指向的文件的二进制内容:

          >>> p = Path('my_binary_file')
          >>> p.write_bytes(b'Binary file contents')
          20
          >>> p.read_bytes()
          b'Binary file contents'

     3.5 新版功能.

 -- 方法: Path.read_text (encoding=None, errors=None)

     以字符串形式返回路径指向的文件的解码后文本内容。

          >>> p = Path('my_text_file')
          >>> p.write_text('Text file contents')
          18
          >>> p.read_text()
          'Text file contents'

     文件先被打开然后关闭。有和 *note open(): 4f8. 一样的可选形参。

     3.5 新版功能.

 -- 方法: Path.rename (target)

     将文件或目录重命名为给定的 `target'，并返回一个新的指向 `target' 的
     Path 实例。 在 Unix 上，如果 `target' 存在且为一个文件，如果用户有
     足够权限，则它将被静默地替换。 `target' 可以是一个字符串或者另一个
     路径对象:

          >>> p = Path('foo')
          >>> p.open('w').write('some text')
          9
          >>> target = Path('bar')
          >>> p.rename(target)
          PosixPath('bar')
          >>> target.open().read()
          'some text'

     目标路径可能为绝对或相对路径。 相对路径将被解释为相对于当前工作目录
     ，而 `不是' 相对于 Path 对象的目录。

     在 3.8 版更改: 添加了返回值，返回新的 Path 实例。

 -- 方法: Path.replace (target)

     将文件名目录重命名为给定的 `target'，并返回一个新的指向 `target' 的
     Path 实例。 如果 `target' 指向一个现有文件或目录，则它将被无条件地
     替换。

     目标路径可能为绝对或相对路径。 相对路径将被解释为相对于当前工作目录
     ，而 `不是' 相对于 Path 对象的目录。

     在 3.8 版更改: 添加了返回值，返回新的 Path 实例。

 -- 方法: Path.resolve (strict=False)

     将路径绝对化，解析任何符号链接。返回新的路径对象:

          >>> p = Path()
          >>> p
          PosixPath('.')
          >>> p.resolve()
          PosixPath('/home/antoine/pathlib')

     "‘..’" 组件也将被消除（只有这一种方法这么做）:

          >>> p = Path('docs/../setup.py')
          >>> p.resolve()
          PosixPath('/home/antoine/pathlib/setup.py')

     如果路径不存在并且 `strict' 设为 ‘True’，则抛出 *note
     FileNotFoundError: 7c9.。如果 `strict' 为 ‘False’，则路径将被尽可能
     地解析并且任何剩余部分都会被不检查是否存在地追加。如果在解析路径上
     发生无限循环，则抛出 *note RuntimeError: 2bb.。

     3.6 新版功能: 加入*strict* 参数（3.6之前的版本相当于strict值为
     True）

 -- 方法: Path.rglob (pattern)

     这就像调用 ‘Path.glob`时在给定的相对 *pattern* 前面添加了
     "``**/`()’"

          >>> sorted(Path().rglob("*.py"))
          [PosixPath('build/lib/pathlib.py'),
           PosixPath('docs/conf.py'),
           PosixPath('pathlib.py'),
           PosixPath('setup.py'),
           PosixPath('test_pathlib.py')]

 -- 方法: Path.rmdir ()

     移除此目录。此目录必须为空的。

 -- 方法: Path.samefile (other_path)

     返回此目录是否指向与可能是字符串或者另一个路径对象的 `other_path' 相
     同的文件。语义类似于 *note os.path.samefile(): 88b. 与 *note
     os.path.samestat(): 88a.。

     如果两者都以同一原因无法访问，则抛出 *note OSError: 1d4.。

          >>> p = Path('spam')
          >>> q = Path('eggs')
          >>> p.samefile(q)
          False
          >>> p.samefile('spam')
          True

     3.5 新版功能.

 -- 方法: Path.symlink_to (target, target_is_directory=False)

     将此路径创建为指向 `target' 的符号链接。在 Windows 下，如果链接的目
     标是一个目录则 `target_is_directory' 必须为 true （默认为 ‘False’）
     。在 POSIX 下， `target_is_directory' 的值将被忽略。

          >>> p = Path('mylink')
          >>> p.symlink_to('setup.py')
          >>> p.resolve()
          PosixPath('/home/antoine/pathlib/setup.py')
          >>> p.stat().st_size
          956
          >>> p.lstat().st_size
          8

          注解: 参数的顺序（link, target) 和 *note os.symlink(): a43. 是
          相反的。

 -- 方法: Path.link_to (target)

     创建硬链接 `target' 指向此路径。

          警告: 此函数不是将此路径设为指向 `target' 的硬链接，这与函数和
          参数名的本义不同。 参数顺序 (target, link) 与 *note
          Path.symlink_to(): 1bf2. 相反，而与 *note os.link(): a3d. 一致
          。

     3.8 新版功能.

 -- 方法: Path.touch (mode=0o666, exist_ok=True)

     将给定的路径创建为文件。如果给出了 `mode' 它将与当前进程的 ‘umask’
     值合并以确定文件的模式和访问标志。如果文件已经存在，则当 `exist_ok'
     为 true 则函数仍会成功（并且将它的修改事件更新为当前事件），否则抛
     出 *note FileExistsError: 960.。

 -- 方法: Path.unlink (missing_ok=False)

     移除此文件或符号链接。如果路径指向目录，则用 *note Path.rmdir():
     1bf1. 代替。

     如果 `missing_ok' 为假值（默认），则如果路径不存在将会引发 *note
     FileNotFoundError: 7c9.。

     如果 `missing_ok' 为真值，则 *note FileNotFoundError: 7c9. 异常将被
     忽略（和 POSIX ‘rm -f’ 命令的行为相同）。

     在 3.8 版更改: 增加了 `missing_ok' 形参。

 -- 方法: Path.write_bytes (data)

     将文件以二进制模式打开，写入 `data' 并关闭:

          >>> p = Path('my_binary_file')
          >>> p.write_bytes(b'Binary file contents')
          20
          >>> p.read_bytes()
          b'Binary file contents'

     一个同名的现存文件将被覆盖。

     3.5 新版功能.

 -- 方法: Path.write_text (data, encoding=None, errors=None)

     将文件以文本模式打开，写入 `data' 并关闭:

          >>> p = Path('my_text_file')
          >>> p.write_text('Text file contents')
          18
          >>> p.read_text()
          'Text file contents'

     同名的现有文件会被覆盖。 可选形参的含义与 *note open(): 4f8. 的相同
     。

     3.5 新版功能.


File: python.info,  Node: 对应的 os 模块的工具,  Prev: 具体路径,  Up: pathlib --- 面向对象的文件系统路径

5.11.1.9 对应的 ‘os’ 模块的工具
...............................

以下是一个映射了 *note os: c5. 与 *note PurePath: 1051./*note Path: 202.
对应相同的函数的表。

     注解: 尽管 *note os.path.relpath(): 1bf5. 和 *note
     PurePath.relative_to(): 1bdf. 拥有相同的重叠的用例，但是它们语义相
     差很大，不能认为它们等价。

os 和 os.path                            pathlib
                                         
----------------------------------------------------------------------------
                                         
*note os.path.abspath(): cb8.            *note Path.resolve(): 1bd4.
                                         
                                         
*note os.chmod(): a3b.                   *note Path.chmod(): 1be6.
                                         
                                         
*note os.mkdir(): a3e.                   *note Path.mkdir(): 732.
                                         
                                         
*note os.rename(): a40.                  *note Path.rename(): 1bee.
                                         
                                         
*note os.replace(): a41.                 *note Path.replace(): 1bef.
                                         
                                         
*note os.rmdir(): a42.                   *note Path.rmdir(): 1bf1.
                                         
                                         
*note os.remove(): a3f,                  *note Path.unlink(): fde.
*note os.unlink(): a44.                  

*note os.getcwd(): fee.                  *note Path.cwd(): 1be4.
                                         
                                         
*note os.path.exists(): 1f7.             *note Path.exists(): 203.
                                         
                                         
*note os.path.expanduser(): 1ff.         *note Path.expanduser(): 733. 和
                                         *note Path.home(): 734.
                                         
                                         
*note os.listdir(): a49.                 *note Path.iterdir(): 1be9.
                                         
                                         
*note os.path.isdir(): 1f9.              *note Path.is_dir(): 204.
                                         
                                         
*note os.path.isfile(): 1fa.             *note Path.is_file(): 205.
                                         
                                         
*note os.path.islink(): 1f5.             *note Path.is_symlink(): 207.
                                         
                                         
*note os.link(): a3d.                    *note Path.link_to(): 20c.
                                         
                                         
*note os.symlink(): a43.                 *note Path.symlink_to(): 1bf2.
                                         
                                         
*note os.stat(): 1f2.                    *note Path.stat(): 1be5,
                                         *note Path.owner(): 1bed,
                                         *note Path.group(): 1be8.
                                         
                                         
*note os.path.isabs(): 1bf6.             *note PurePath.is_absolute(): 1bdb.
                                         
                                         
*note os.path.join(): f6c.               *note PurePath.joinpath(): 1bdd.
                                         
                                         
*note os.path.basename(): 1bf7.          *note PurePath.name: 1bd5.
                                         
                                         
*note os.path.dirname(): 1bf8.           *note PurePath.parent: 1bd3.
                                         
                                         
*note os.path.samefile(): 88b.           *note Path.samefile(): 731.
                                         
                                         
*note os.path.splitext(): 1bf9.          *note PurePath.suffix: 1bd6.
                                         


File: python.info,  Node: os path --- 常用路径操作,  Next: fileinput --- 迭代来自多个输入流的行,  Prev: pathlib --- 面向对象的文件系统路径,  Up: 文件和目录访问

5.11.2 ‘os.path’ — 常用路径操作
-------------------------------

`源代码：' Lib/posixpath.py(1) （用于 POSIX）和 Lib/ntpath.py(2) （用于
Windows NT）

__________________________________________________________________

该模块在路径名上实现了一些有用的功能：如需读取或写入文件，请参见 *note
open(): 4f8. ；有关访问文件系统的信息，请参见 *note os: c5. 模块。路径参
数可以字符串或字节形式传递。我们鼓励应用程序将文件名表示为（Unicode）字
符串。不幸的是，某些文件名在Unix上可能无法用字符串表示，因此在Unix上平台
上需要支持任意文件名的应用程序，应使用字节对象来表示路径名。反之亦然，在
Windows平台上仅使用字节对象，不能表示的所有文件名（以标准 ‘mbcs’ 编码）
，因此Windows应用程序应使用字符串对象来访问所有文件。

与unix shell不同，Python不执行任何 `自动' 路径扩展。当应用程序需要类似
shell的路径扩展时，可以显式调用诸如 *note expanduser(): 1ff. 和 *note
expandvars(): d4c. 之类的函数。 （另请参见 *note glob: 8a. 模块。）

参见
....

*note pathlib: c9. 模块提供高级路径对象。

     注解: 所有这些函数都仅接受字节或字符串对象作为其参数。如果返回路径
     或文件名，则结果是相同类型的对象。

     注解: 由于不同的操作系统具有不同的路径名称约定，因此标准库中有此模
     块的几个版本。*note os.path: c6. 模块始终是适合 Python 运行的操作系
     统的路径模块，因此可用于本地路径。但是，如果操作的路径 `总是' 以一
     种不同的格式显示，那么也可以分别导入和使用各个模块。它们都具有相同
     的接口：

        * ‘posixpath’ 用于Unix 样式的路径

        * ‘ntpath’ 用于 Windows 路径

在 3.8 版更改: *note exists(): 1f7.、*note lexists(): 1f8.、*note
isdir(): 1f9.、*note isfile(): 1fa.、*note islink(): 1f5. 和 *note
ismount(): 1fb. 现在遇到系统层面上不可表示的字符或字节的路径时，会返回
‘False’，而不是抛出异常。

 -- 函数: os.path.abspath (path)

     返回路径 `path' 的绝对路径（标准化的）。在大多数平台上，这等同于用
     ‘normpath(join(os.getcwd(), path))’ 的方式调用 *note normpath():
     cb7. 函数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.basename (path)

     返回路径 `path' 的基本名称。这是将 `path' 传入函数 *note split():
     1bfc. 之后，返回的一对值中的第二个元素。请注意，此函数的结果与Unix
     ‘basename’ 程序不同。‘basename’ 在 ‘'/foo/bar/'’ 上返回 ‘'bar'’，而
     *note basename(): 1bf7. 函数返回一个空字符串 (‘''’)。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.commonpath (paths)

     接受包含多个路径的序列 `paths'，返回 `paths' 的最长公共子路径。如果
     `paths' 同时包含绝对路径和相对路径，或 `paths' 在不同的驱动器上，或
     `paths' 为空，则抛出 *note ValueError: 1fc. 异常。与 *note
     commonprefix(): 72f. 不同，本方法返回有效路径。

     *note 可用性: 136f.: Unix, Windows。

     3.5 新版功能.

     在 3.6 版更改: 接受一个 *note 类路径对象: 373. 序列。

 -- 函数: os.path.commonprefix (list)

     接受包含多个路径的 `列表'，返回所有路径的最长公共前缀（逐字符比较）
     。如果 `列表' 为空，则返回空字符串 (‘''’)。

          注解: 此函数是逐字符比较，因此可能返回无效路径。要获取有效路径
          ，参见 *note commonpath(): 72e.。

               >>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
               '/usr/l'

               >>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
               '/usr'

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.dirname (path)

     返回路径 `path' 的目录名称。这是将 `path' 传入函数 *note split():
     1bfc. 之后，返回的一对值中的第一个元素。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.exists (path)

     如果 `path' 指向一个已存在的路径或已打开的文件描述符，返回 ‘True’。
     对于失效的符号链接，返回 ‘False’。在某些平台上，如果使用 *note
     os.stat(): 1f2. 查询到目标文件没有执行权限，即使 `path' 确实存在，
     本函数也可能返回 ‘False’。

     在 3.3 版更改: `path' 现在可以是一个整数：如果该整数是一个已打开的
     文件描述符，返回 ‘True’，否则返回 ‘False’。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.lexists (path)

     如果 `path' 指向一个已存在的路径，返回 ‘True’。对于失效的符号链接，
     也返回 ‘True’。在缺失 *note os.lstat(): 1f3. 的平台上等同于 *note
     exists(): 1f7.。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.expanduser (path)

     在 Unix 和 Windows 上，将参数中开头部分的 ‘~’ 或 ‘~user’ 替换为当前
     `用户' 的家目录并返回。

     在 Unix 上，开头的 ‘~’ 会被环境变量 ‘HOME’ 代替，如果变量未设置，则
     通过内置模块 *note pwd: d7. 在 password 目录中查找当前用户的主目录
     。以 ‘~user’ 开头则直接在 password 目录中查找。

     在 Windows 上，如果设置了 ‘USERPROFILE’，就使用这个变量，否则会将
     ‘HOMEPATH’ 和 ‘HOMEDRIVE’ 结合在一起使用。以 ‘~user’ 开头则将上述方
     法生成路径的最后一截目录替换成 user。

     如果展开路径失败，或者路径不是以波浪号开头，则路径将保持不变。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

     在 3.8 版更改: Windows 不再使用 ‘HOME’。

 -- 函数: os.path.expandvars (path)

     输入带有环境变量的路径作为参数，返回展开变量以后的路径。‘$name’ 或
     ‘${name}’ 形式的子字符串被环境变量 `name' 的值替换。格式错误的变量
     名称和对不存在变量的引用保持不变。

     在 Windows 上，除了 ‘$name’ 和 ‘${name}’ 外，还可以展开 ‘%name%’。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.getatime (path)

     返回 `path' 的最后访问时间。返回值是一个浮点数，为纪元秒数（参见
     *note time: 10b. 模块）。如果该文件不存在或不可访问，则抛出 *note
     OSError: 1d4. 异常。

 -- 函数: os.path.getmtime (path)

     返回 `path' 的最后修改时间。返回值是一个浮点数，为纪元秒数（参见
     *note time: 10b. 模块）。如果该文件不存在或不可访问，则抛出 *note
     OSError: 1d4. 异常。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.getctime (path)

     返回 `path' 在系统中的 ctime，在有些系统（比如 Unix）上，它是元数据
     的最后修改时间，其他系统（比如 Windows）上，它是 `path' 的创建时间
     。返回值是一个数，为纪元秒数（参见 *note time: 10b. 模块）。如果该
     文件不存在或不可访问，则抛出 *note OSError: 1d4. 异常。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.getsize (path)

     返回 `path' 的大小，以字节为单位。如果该文件不存在或不可访问，则抛
     出 *note OSError: 1d4. 异常。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.isabs (path)

     如果 `path' 是一个绝对路径，则返回 ‘True’。在 Unix 上，它就是以斜杠
     开头，而在 Windows 上，它可以是去掉驱动器号后以斜杠（或反斜杠）开头
     。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.isfile (path)

     如果 `path' 是 *note 现有的: 1f7. 常规文件，则返回 ‘True’。本方法会
     跟踪符号链接，因此，对于同一路径，*note islink(): 1f5. 和 *note
     isfile(): 1fa. 都可能为 ‘True’。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.isdir (path)

     如果 `path' 是 *note 现有的: 1f7. 目录，则返回 ‘True’。本方法会跟踪
     符号链接，因此，对于同一路径，*note islink(): 1f5. 和 *note
     isdir(): 1f9. 都可能为 ‘True’。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.islink (path)

     如果 `path' 指向的 *note 现有: 1f7. 目录条目是一个符号链接，则返回
     ‘True’。如果 Python 运行时不支持符号链接，则总是返回 ‘False’。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.ismount (path)

     如果路径 `path' 是 `挂载点' （文件系统中挂载其他文件系统的点），则
     返回 ‘True’。在 POSIX 上，该函数检查 `path' 的父目录 ‘`path'/..’ 是
     否在与 `path' 不同的设备上，或者 ‘`path'/..’ 和 `path' 是否指向同一
     设备上的同一 inode（这一检测挂载点的方法适用于所有 Unix 和 POSIX 变
     体）。本方法不能可靠地检测同一文件系统上的绑定挂载 (bind mount)。在
     Windows 上，盘符和共享 UNC 始终是挂载点，对于任何其他路径，将调用
     ‘GetVolumePathName’ 来查看它是否与输入的路径不同。

     3.4 新版功能: 支持在 Windows 上检测非根挂载点。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.join (path, *paths)

     智能地拼接一个或多个路径部分。 返回值是 `path' 和 `*paths' 的所有成
     员的拼接，其中每个非空部分后面都紧跟一个目录分隔符，最后一个部分除
     外，这意味着如果最后一个部分为空，则结果将以分隔符结尾。 如果某个部
     分为绝对路径，则之前的所有部分会被丢弃并从绝对路径部分开始继续拼接
     。

     在 Windows 上，遇到绝对路径部分（例如 ‘r'\foo'’）时，不会重置盘符。
     如果某部分路径包含盘符，则会丢弃所有先前的部分，并重置盘符。请注意
     ，由于每个驱动器都有一个“当前目录”，所以 ‘os.path.join("c:",
     "foo")’ 表示驱动器 ‘C:’ 上当前目录的相对路径 (‘c:foo’)，而不是
     ‘c:\foo’。

     在 3.6 版更改: 接受一个 *note 类路径对象: 373. 用于 `path' 和
     `paths' 。

 -- 函数: os.path.normcase (path)

     规范路径的大小写。在 Windows 上，将路径中的所有字符都转换为小写，并
     将正斜杠转换为反斜杠。在其他操作系统上返回原路径。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.normpath (path)

     通过折叠多余的分隔符和对上级目录的引用来标准化路径名，所以 ‘A//B’、
     ‘A/B/’、‘A/./B’ 和 ‘A/foo/../B’ 都会转换成 ‘A/B’。这个字符串操作可
     能会改变带有符号链接的路径的含义。在 Windows 上，本方法将正斜杠转换
     为反斜杠。要规范大小写，请使用 *note normcase(): 1c01.。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.realpath (path)

     返回指定文件的规范路径，消除路径中存在的任何符号链接（如果操作系统
     支持）。

          注解: 当发生符号链接循环时，返回的路径将是该循环的某个组成部分
          ，但不能保证是哪个部分。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

     在 3.8 版更改: 在 Windows 上现在可以正确解析符号链接和交接点
     (junction point)。

 -- 函数: os.path.relpath (path, start=os.curdir)

     返回从当前目录或可选的 `start' 目录至 `path' 的相对文件路径。 这只
     是一个路径计算：不会访问文件系统来确认 `path' 或 `start' 是否存在或
     其性质。 在 Windows 上，当 `path' 和 `start' 位于不同驱动器时将引发
     *note ValueError: 1fc.。

     `start' 默认为 *note os.curdir: 1c02.。

     *note 可用性: 136f.: Unix, Windows。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.samefile (path1, path2)

     如果两个路径都指向相同的文件或目录，则返回 ‘True’。这由设备号和
     inode 号确定，在任一路径上调用 *note os.stat(): 1f2. 失败则抛出异常
     。

     *note 可用性: 136f.: Unix, Windows。

     在 3.2 版更改: 添加了对 Windows 的支持。

     在 3.4 版更改: Windows现在使用与其他所有平台相同的实现。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.sameopenfile (fp1, fp2)

     如果文件描述符 `fp1' 和 `fp2' 指向相同文件，则返回 ‘True’。

     *note 可用性: 136f.: Unix, Windows。

     在 3.2 版更改: 添加了对 Windows 的支持。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.samestat (stat1, stat2)

     如果 stat 元组 `stat1' 和 `stat2' 指向相同文件，则返回 ‘True’。这些
     stat 元组可能是由 *note os.fstat(): 668.、*note os.lstat(): 1f3. 或
     *note os.stat(): 1f2. 返回的。本函数实现了 *note samefile(): 88b. 和
     *note sameopenfile(): 1c03. 底层所使用的比较过程。

     *note 可用性: 136f.: Unix, Windows。

     在 3.4 版更改: 添加了对 Windows 的支持。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.split (path)

     将路径 `path' 拆分为一对，即 ‘(head, tail)’，其中，`tail' 是路径的
     最后一部分，而 `head' 里是除最后部分外的所有内容。`tail' 部分不会包
     含斜杠，如果 `path' 以斜杠结尾，则 `tail' 将为空。如果 `path' 中没
     有斜杠，`head' 将为空。如果 `path' 为空，则 `head' 和 `tail' 均为空
     。`head' 末尾的斜杠会被去掉，除非它是根目录（即它仅包含一个或多个斜
     杠）。在所有情况下，‘join(head, tail)’ 指向的位置都与 `path' 相同（
     但字符串可能不同）。另请参见函数 *note dirname(): 1bf8. 和 *note
     basename(): 1bf7.。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.splitdrive (path)

     将路径 `path' 拆分为一对，即 ‘(drive, tail)’，其中 `drive' 是挂载点
     或空字符串。在没有驱动器概念的系统上，`drive' 将始终为空字符串。在
     所有情况下，‘drive + tail’ 都与 `path' 相同。

     在 Windows 上，本方法将路径拆分为驱动器/UNC 根节点和相对路径。

     如果路径 path 包含盘符，则 drive 将包含冒号及冒号前面的所有内容。例
     如 ‘splitdrive("c:/dir")’ 返回 ‘("c:", "/dir")’。

     如果 path 是一个 UNC 路径，则 drive 将包含主机名和共享点，但不包括
     第四个分隔符。例如 ‘splitdrive("//host/computer/dir")’ 返回
     ‘("//host/computer", "/dir")’。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.path.splitext (path)

     将路径 `path' 拆分为一对，即 ‘(root, ext)’，使 ‘root + ext ==
     path’，其中 `ext' 为空或以英文句点开头，且最多包含一个句点。路径前
     的句点将被忽略，例如 ‘splitext('.cshrc')’ 返回 ‘('.cshrc', '')’。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 数据: os.path.supports_unicode_filenames

     如果（在文件系统限制下）允许将任意 Unicode 字符串用作文件名，则为
     ‘True’。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/posixpath.py

   (2) https://github.com/python/cpython/tree/3.8/Lib/ntpath.py


File: python.info,  Node: fileinput --- 迭代来自多个输入流的行,  Next: stat --- 解析 stat 结果,  Prev: os path --- 常用路径操作,  Up: 文件和目录访问

5.11.3 ‘fileinput’ — 迭代来自多个输入流的行
-------------------------------------------

`源代码:' Lib/fileinput.py(1)

__________________________________________________________________

此模块实现了一个辅助类和一些函数用来快速编写访问标准输入或文件列表的循环
。 如果你只想要读写一个文件请参阅 *note open(): 4f8.。

典型用法为:

     import fileinput
     for line in fileinput.input():
         process(line)

此程序会迭代 ‘sys.argv[1:]’ 中列出的所有文件内的行，如果列表为空则会使用
‘sys.stdin’。 如果有一个文件名为 ‘'-'’，它也会被替换为 ‘sys.stdin’ 并且
可选参数 `mode' 和 `openhook' 会被忽略。 要指定替代文件列表，请将其作为
第一个参数传给 *note input(): 2ae.。 也允许使用单个文件。

所有文件都默认以文本模式打开，但你可以通过在调用 *note input(): 2ae. 或
*note FileInput: 27f. 时指定 `mode' 形参来重载此行为。 如果在打开或读取
文件时发生了 I/O 错误，将会引发 *note OSError: 1d4.。

在 3.3 版更改: 原来会引发 *note IOError: 99a.；现在它是 *note OSError:
1d4. 的别名。

如果 ‘sys.stdin’ 被使用超过一次，则第二次之后的使用将不返回任何行，除非
是被交互式的使用，或都是被显式地重置 (例如使用 ‘sys.stdin.seek(0)’)。

空文件打开后将立即被关闭；它们在文件列表中会被注意到的唯一情况只有当最后
打开的文件为空的时候。

反回的行不会对换行符做任何处理，这意味着文件中的最后一行可能不带换行符。

想要控制文件的打开方式，你可以通过将 `openhook' 形参传给 *note
fileinput.input(): 2ae. 或 *note FileInput(): 27f. 来提供一个打开钩子。
此钩子必须为一个函数，它接受两个参数，`filename' 和 `mode'，并返回一个以
相应模式打开的文件类对象。 此模块已经提供了两个有用的钩子。

以下函数是此模块的初始接口：

 -- 函数: fileinput.input (files=None, inplace=False, backup='', *,
          mode='r', openhook=None)

     创建一个 *note FileInput: 27f. 类的实例。 该实例将被用作此模块中函
     数的全局状态，并且还将在迭代期间被返回使用。 此函数的形参将被继续传
     递给 *note FileInput: 27f. 类的构造器。

     *note FileInput: 27f. 实例可以在 *note with: 6f2. 语句中被用作上下
     文管理器。 在这个例子中，`input' 在 ‘with’ 语句结束后将会被关闭，即
     使发生了异常也是如此:

          with fileinput.input(files=('spam.txt', 'eggs.txt')) as f:
              for line in f:
                  process(line)

     在 3.2 版更改: 可以被用作上下文管理器。

     在 3.8 版更改: 关键字形参 `mode' 和 `openhook' 现在是仅限关键字形参
     。

下列函数会使用 *note fileinput.input(): 2ae. 所创建的全局状态；如果没有
活动的状态，则会引发 *note RuntimeError: 2bb.。

 -- 函数: fileinput.filename ()

     返回当前被读取的文件名。 在第一行被读取之前，返回 ‘None’。

 -- 函数: fileinput.fileno ()

     返回以整数表示的当前文件“文件描述符”。 当未打开文件时（处在第一行和
     文件之间），返回 ‘-1’。

 -- 函数: fileinput.lineno ()

     返回已被读取的累计行号。 在第一行被读取之前，返回 ‘0’。 在最后一个
     文件的最后一行被读取之后，返回该行的行号。

 -- 函数: fileinput.filelineno ()

     返回当前文件中的行号。 在第一行被读取之前，返回 ‘0’。 在最后一个文
     件的最后一行被读取之后，返回此文件中该行的行号。

 -- 函数: fileinput.isfirstline ()

     如果刚读取的行是其所在文件的第一行则返回 ‘True’，否则返回 ‘False’。

 -- 函数: fileinput.isstdin ()

     如果最后读取的行来自 ‘sys.stdin’ 则返回 ‘True’，否则返回 ‘False’。

 -- 函数: fileinput.nextfile ()

     关闭当前文件以使下次迭代将从下一个文件（如果存在）读取第一行；不是
     从该文件读取的行将不会被计入累计行数。 直到下一个文件的第一行被读取
     之后文件名才会改变。 在第一行被读取之前，此函数将不会生效；它不能被
     用来跳过第一个文件。 在最后一个文件的最后一行被读取之后，此函数将不
     再生效。

 -- 函数: fileinput.close ()

     关闭序列。

此模块所提供的实现了序列行为的类同样也可用于子类化：

 -- 类: fileinput.FileInput (files=None, inplace=False, backup='', *,
          mode='r', openhook=None)

     类 *note FileInput: 27f. 是一个实现；它的方法 *note filename():
     1c06, *note fileno(): 1c07, *note lineno(): 1c08, *note
     filelineno(): 1c09, *note isfirstline(): 1c0a, *note isstdin():
     1c0b, *note nextfile(): 1c0c. 和 *note close(): 1c0d. 对应于此模块
     中具有相同名称的函数。 此外它还有一个 *note readline(): 1c0e. 方法
     可返回下一个输入行，以及一个 *note __getitem__(): 280. 方法，该方法
     实现了序列行为。 这种序列必须以严格的序列顺序来读写；随机读写和
     *note readline(): 1c0e. 不可以被混用。

     通过 `mode' 你可以指定要传给 *note open(): 4f8. 的文件模式。 它必须
     为 ‘'r'’, ‘'rU'’, ‘'U'’ 和 ‘'rb'’ 中的一个。

     `openhook' 如果给出则必须为一个函数，它接受两个参数 `filename' 和
     `mode'，并相应地返回一个打开的文件类对象。 你不能同时使用 `inplace'
     和 `openhook'。

     *note FileInput: 27f. 实例可以在 *note with: 6f2. 语句中被用作上下
     文管理器。 在这个例子中，`input' 在 ‘with’ 语句结束后将会被关闭，即
     使发生了异常也是如此:

          with FileInput(files=('spam.txt', 'eggs.txt')) as input:
              process(input)

     在 3.2 版更改: 可以被用作上下文管理器。

     3.4 版后已移除: ‘'rU'’ 和 ‘'U'’ 模式。

     3.8 版后已移除: 对 *note __getitem__(): 280. 方法的支持已弃用。

     在 3.8 版更改: 关键字形参 `mode' 和 `openhook' 现在是仅限关键字形参
     。

`可选的原地过滤:' 如果传递了关键字参数 ‘inplace=True’ 给 *note
fileinput.input(): 2ae. 或 *note FileInput: 27f. 构造器，则文件会被移至
备份文件并将标准输出定向到输入文件（如果已存在与备份文件同名的文件，它将
被静默地替换）。 这使得编写一个能够原地重写其输入文件的过滤器成为可能。
如果给出了 `backup' 形参 (通常形式为 ‘backup='.<some extension>'’)，它将
指定备份文件的扩展名，并且备份文件会被保留；默认情况下扩展名为 ‘'.bak'’
并且它会在输出文件关闭时被删除。 在读取标准输入时原地过滤会被禁用。

此模块提供了以下两种打开文件钩子：

 -- 函数: fileinput.hook_compressed (filename, mode)

     使用 *note gzip: 8c. 和 *note bz2: 14. 模块透明地打开 gzip 和 bzip2
     压缩的文件（通过扩展名 ‘'.gz'’ 和 ‘'.bz2'’ 来识别）。 如果文件扩展
     名不是 ‘'.gz'’ 或 ‘'.bz2'’，文件会以正常方式打开（即使用 *note
     open(): 4f8. 并且不带任何解压操作）。

     使用示例: ‘fi =
     fileinput.FileInput(openhook=fileinput.hook_compressed)’

 -- 函数: fileinput.hook_encoded (encoding, errors=None)

     返回一个通过 *note open(): 4f8. 打开每个文件的钩子，使用给定的
     `encoding' 和 `errors' 来读取文件。

     使用示例: ‘fi =
     fileinput.FileInput(openhook=fileinput.hook_encoded("utf-8",
     "surrogateescape"))’

     在 3.6 版更改: 添加了可选的 `errors' 形参。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/fileinput.py


File: python.info,  Node: stat --- 解析 stat 结果,  Next: filecmp --- 文件及目录的比较,  Prev: fileinput --- 迭代来自多个输入流的行,  Up: 文件和目录访问

5.11.4 ‘stat’ — 解析 ‘stat()’ 结果
----------------------------------

`源代码：' Lib/stat.py(1)

__________________________________________________________________

*note stat: f5. 模块定义了一些用于解析 *note os.stat(): 1f2, *note
os.fstat(): 668. 和 *note os.lstat(): 1f3. (如果它们存在) 输出结果的常量
和函数。 有关 ‘stat()’, ‘fstat()’ 和 ‘lstat()’ 调用的完整细节，请参阅你
的系统文档。

在 3.4 版更改: stat 模块是通过 C 实现来支持的。

*note stat: f5. 模块定义了以下函数来检测特定文件类型：

 -- 函数: stat.S_ISDIR (mode)

     如果 mode 来自一个目录则返回非零值。

 -- 函数: stat.S_ISCHR (mode)

     如果 mode 来自一个字符特殊设备文件则返回非零值。

 -- 函数: stat.S_ISBLK (mode)

     如果 mode 来自一个块特殊设备文件则返回非零值。

 -- 函数: stat.S_ISREG (mode)

     如果 mode 来自一个常规文件则返回非零值。

 -- 函数: stat.S_ISFIFO (mode)

     如果 mode 来自一个 FIFO (命名管道) 则返回非零值。

 -- 函数: stat.S_ISLNK (mode)

     如果 mode 来自一个符号链接则返回非零值。

 -- 函数: stat.S_ISSOCK (mode)

     如果 mode 来自一个套接字则返回非零值。

 -- 函数: stat.S_ISDOOR (mode)

     如果 mode 来自一个门则返回非零值。

     3.4 新版功能.

 -- 函数: stat.S_ISPORT (mode)

     如果 mode 来自一个事件端口则返回非零值。

     3.4 新版功能.

 -- 函数: stat.S_ISWHT (mode)

     如果 mode 来自一个白输出则返回非零值。

     3.4 新版功能.

定义了两个附加函数用于对文件模式进行更一般化的操作：

 -- 函数: stat.S_IMODE (mode)

     返回文件模式中可由 *note os.chmod(): a3b. 进行设置的部分 — 即文件的
     permission 位，加上 sticky 位、set-group-id 以及 set-user-id 位（在
     支持这些部分的系统上）。

 -- 函数: stat.S_IFMT (mode)

     返回文件模式中描述文件类型的部分（供上面的 ‘S_IS*()’ 函数使用）。

通常，你应当使用 ‘os.path.is*()’ 函数来检测文件的类型；这里提供的函数则
适用于当你要对同一文件执行多项检测并且希望避免每项检测的 ‘stat()’ 系统调
用开销的情况。 这些函数也适用于检测有关未被 *note os.path: c6. 处理的信
息，例如检测块和字符设备等。

示例:

     import os, sys
     from stat import *

     def walktree(top, callback):
         '''recursively descend the directory tree rooted at top,
            calling the callback function for each regular file'''

         for f in os.listdir(top):
             pathname = os.path.join(top, f)
             mode = os.stat(pathname).st_mode
             if S_ISDIR(mode):
                 # It's a directory, recurse into it
                 walktree(pathname, callback)
             elif S_ISREG(mode):
                 # It's a file, call the callback function
                 callback(pathname)
             else:
                 # Unknown file type, print a message
                 print('Skipping %s' % pathname)

     def visitfile(file):
         print('visiting', file)

     if __name__ == '__main__':
         walktree(sys.argv[1], visitfile)

另外还提供了一个附加的辅助函数用来将文件模式转换为人类易读的字符串：

 -- 函数: stat.filemode (mode)

     将文件模式转换为 ’-rwxrwxrwx’ 形式的字符串。

     3.3 新版功能.

     在 3.4 版更改: 此函数支持 *note S_IFDOOR: 8dc, *note S_IFPORT: 8dd.
     and *note S_IFWHT: 8de.。

以下所有变量是一些简单的符号索引，用于访问 *note os.stat(): 1f2, *note
os.fstat(): 668. 或 *note os.lstat(): 1f3. 所返回的 10 条目元组。

 -- 数据: stat.ST_MODE

     inode 保护模式。

 -- 数据: stat.ST_INO

     Inode 号

 -- 数据: stat.ST_DEV

     Inode 所在的设备。

 -- 数据: stat.ST_NLINK

     Inode 拥有的链接数量。

 -- 数据: stat.ST_UID

     所有者的用户 ID。

 -- 数据: stat.ST_GID

     所有者的用户组ID。

 -- 数据: stat.ST_SIZE

     以字节为单位的普通文件大小；对于某些特殊文件则是所等待的数据量。

 -- 数据: stat.ST_ATIME

     上次访问的时间。

 -- 数据: stat.ST_MTIME

     上次修改的时间。

 -- 数据: stat.ST_CTIME

     操作系统所报告的 "ctime"。 在某些系统上（例如 Unix）是元数据的最后
     修改时间，而在其他系统上（例如 Windows）则是创建时间（请参阅系统平
     台的文档了解相关细节）。

对于“文件大小”的解析可因文件类型的不同而变化。 对于普通文件就是文件的字
节数。 对于大部分种类的 Unix（特别包括 Linux）的 FIFO 和套接字来说，“大
小”则是指在调用 *note os.stat(): 1f2, *note os.fstat(): 668. 或 *note
os.lstat(): 1f3. 时等待读取的字节数；这在某些时候很有用处，特别是在一个
非阻塞的打开后轮询这些特殊文件中的一个时。 其他字符和块设备的文件大小字
段的含义还会有更多变化，具体取决于底层系统调用的实现方式。

以下变量定义了在 *note ST_MODE: 8db. 字段中使用的旗标。

使用上面的函数会比使用第一组旗标更容易移植：

 -- 数据: stat.S_IFSOCK

     套接字。

 -- 数据: stat.S_IFLNK

     符号链接。

 -- 数据: stat.S_IFREG

     普通文件。

 -- 数据: stat.S_IFBLK

     块设备。

 -- 数据: stat.S_IFDIR

     目录。

 -- 数据: stat.S_IFCHR

     字符设备。

 -- 数据: stat.S_IFIFO

     先进先出。

 -- 数据: stat.S_IFDOOR

     门。

     3.4 新版功能.

 -- 数据: stat.S_IFPORT

     事件端口。

     3.4 新版功能.

 -- 数据: stat.S_IFWHT

     白输出。

     3.4 新版功能.

     注解: *note S_IFDOOR: 8dc, *note S_IFPORT: 8dd. or *note S_IFWHT:
     8de. 等文件类型在不受系统平台支持时会被定义为 0。

以下旗标还可以 *note os.chmod(): a3b. 的在 `mode' 参数中使用：

 -- 数据: stat.S_ISUID

     设置 UID 位。

 -- 数据: stat.S_ISGID

     设置分组 ID 位。 这个位有几种特殊用途。 对于目录它表示该目录将使用
     BSD 语义：在其中创建的文件将从目录继承其分组 ID，而不是从创建进程的
     有效分组 ID 继承，并且在其中创建的目录也将设置 *note S_ISGID: 1c2c.
     位。 对于没有设置分组执行位 (*note S_IXGRP: 1c2d.) 的文件，设置分组
     ID 位表示强制性文件/记录锁定 (另请参见 *note S_ENFMT: 1c2e.)。

 -- 数据: stat.S_ISVTX

     固定位。 当对目录设置该位时则意味着此目录中的文件只能由文件所有者、
     目录所有者或特权进程来重命名或删除。

 -- 数据: stat.S_IRWXU

     文件所有者权限的掩码。

 -- 数据: stat.S_IRUSR

     所有者具有读取权限。

 -- 数据: stat.S_IWUSR

     所有者具有写入权限。

 -- 数据: stat.S_IXUSR

     所有者具有执行权限。

 -- 数据: stat.S_IRWXG

     组权限的掩码。

 -- 数据: stat.S_IRGRP

     组具有读取权限。

 -- 数据: stat.S_IWGRP

     组具有写入权限。

 -- 数据: stat.S_IXGRP

     组具有执行权限。

 -- 数据: stat.S_IRWXO

     其他人（不在组中）的权限掩码。

 -- 数据: stat.S_IROTH

     其他人具有读取权限。

 -- 数据: stat.S_IWOTH

     其他人具有写入权限。

 -- 数据: stat.S_IXOTH

     其他人具有执行权限。

 -- 数据: stat.S_ENFMT

     System V 执行文件锁定。 此旗标是与 *note S_ISGID: 1c2c. 共享的：文
     件/记录锁定会针对未设置分组执行位 (*note S_IXGRP: 1c2d.) 的文件强制
     执行。

 -- 数据: stat.S_IREAD

     Unix V7 中 *note S_IRUSR: 1c31. 的同义词。

 -- 数据: stat.S_IWRITE

     Unix V7 中 *note S_IWUSR: 1c32. 的同义词。

 -- 数据: stat.S_IEXEC

     Unix V7 中 *note S_IXUSR: 1c33. 的同义词。

以下旗标可以在 *note os.chflags(): a3a. 的 `flags' 参数中使用：

 -- 数据: stat.UF_NODUMP

     不要转储文件。

 -- 数据: stat.UF_IMMUTABLE

     文件不能被更改。

 -- 数据: stat.UF_APPEND

     文件只能被附加。

 -- 数据: stat.UF_OPAQUE

     当通过联合堆栈查看时，目录是不透明的。

 -- 数据: stat.UF_NOUNLINK

     文件不能重命名或删除。

 -- 数据: stat.UF_COMPRESSED

     文件是压缩存储的（Mac OS X 10.6+）。

 -- 数据: stat.UF_HIDDEN

     文件不能显示在GUI 中（Mac OS X 10.5+）。

 -- 数据: stat.SF_ARCHIVED

     文件可能已存档。

 -- 数据: stat.SF_IMMUTABLE

     文件不能被更改。

 -- 数据: stat.SF_APPEND

     文件只能被附加。

 -- 数据: stat.SF_NOUNLINK

     文件不能重命名或删除。

 -- 数据: stat.SF_SNAPSHOT

     文件有一个快照文件

请参阅 *BSD 或 Mac OS 系统的指南页 ‘chflags(2)’ 了解详情。

在 Windows 上，以下文件属性常量可被用来检测 *note os.stat(): 1f2. 所返回
的 ‘st_file_attributes’ 成员中的位。 请参阅 Windows API 文档(2) 了解有关
这些常量含义的详情。

 -- 数据: stat.FILE_ATTRIBUTE_ARCHIVE
 -- 数据: stat.FILE_ATTRIBUTE_COMPRESSED
 -- 数据: stat.FILE_ATTRIBUTE_DEVICE
 -- 数据: stat.FILE_ATTRIBUTE_DIRECTORY
 -- 数据: stat.FILE_ATTRIBUTE_ENCRYPTED
 -- 数据: stat.FILE_ATTRIBUTE_HIDDEN
 -- 数据: stat.FILE_ATTRIBUTE_INTEGRITY_STREAM
 -- 数据: stat.FILE_ATTRIBUTE_NORMAL
 -- 数据: stat.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED
 -- 数据: stat.FILE_ATTRIBUTE_NO_SCRUB_DATA
 -- 数据: stat.FILE_ATTRIBUTE_OFFLINE
 -- 数据: stat.FILE_ATTRIBUTE_READONLY
 -- 数据: stat.FILE_ATTRIBUTE_REPARSE_POINT
 -- 数据: stat.FILE_ATTRIBUTE_SPARSE_FILE
 -- 数据: stat.FILE_ATTRIBUTE_SYSTEM
 -- 数据: stat.FILE_ATTRIBUTE_TEMPORARY
 -- 数据: stat.FILE_ATTRIBUTE_VIRTUAL

     3.5 新版功能.

在 Windows 上，以下常量可被用来与 *note os.lstat(): 1f3. 所返回的
‘st_reparse_tag’ 成员进行比较。 这些是最主要的常量，而不是详尽的清单。

 -- 数据: stat.IO_REPARSE_TAG_SYMLINK
 -- 数据: stat.IO_REPARSE_TAG_MOUNT_POINT
 -- 数据: stat.IO_REPARSE_TAG_APPEXECLINK

     3.8 新版功能.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/stat.py

   (2) 
https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117.aspx


File: python.info,  Node: filecmp --- 文件及目录的比较,  Next: tempfile --- 生成临时文件和目录,  Prev: stat --- 解析 stat 结果,  Up: 文件和目录访问

5.11.5 ‘filecmp’ — 文件及目录的比较
-----------------------------------

`源代码:' Lib/filecmp.py(1)

__________________________________________________________________

*note filecmp: 7f. 模块定义了用于比较文件及目录的函数，并且可以选取多种
关于时间和准确性的折衷方案。对于文件的比较，另见 *note difflib: 37. 模块
。

*note filecmp: 7f. 模块定义了如下函数：

 -- 函数: filecmp.cmp (f1, f2, shallow=True)

     比较名为 `f1' 和 `f2' 的文件，如果它们似乎相等则返回 ‘True’ ，否则
     返回 ‘False’ 。

     如果 `shallow' 为真，那么具有相同 *note os.stat(): 1f2. 签名的文件
     将会被认为是相等的。否则，将比较文件的内容。

     需要注意，没有外部程序被该函数调用，这赋予了该函数可移植性与效率。

     该函数会缓存过去的比较及其结果，且在文件的 *note os.stat(): 1f2. 信
     息变化后缓存条目失效。所有的缓存可以通过使用 *note clear_cache():
     850. 来清除。

 -- 函数: filecmp.cmpfiles (dir1, dir2, common, shallow=True)

     比较在两个目录 `dir1' 和 `dir2' 中，由 `common' 所确定名称的文件。

     返回三组文件名列表： `match', `mismatch', `errors' 。 `match' 含有
     相匹配的文件， `mismatch' 含有那些不匹配的，然后 `errors' 列出那些
     未被比较文件的名称。如果文件不存在于两目录中的任一个，或者用户缺少
     读取它们的权限，又或者因为其他的一些原因而无法比较，那么这些文件将
     会被列在 `errors' 中。

     参数 `shallow' 具有同 *note filecmp.cmp(): 1c60. 一致的含义与默认值
     。

     例如， ‘cmpfiles('a', 'b', ['c', 'd/e'])’ 将会比较 ‘a/c’ 与 ‘b/c’ 以
     及 ‘a/d/e’ 与 ‘b/d/e’ 。 ‘'c'’ 和 ‘'d/e'’ 将会各自出现在返回的三个
     列表里的某一个列表中。

 -- 函数: filecmp.clear_cache ()

     清除 filecmp 缓存。如果一个文件过快地修改，以至于超过底层文件系统记
     录修改时间的精度，那么该函数可能有助于比较该类文件。

     3.4 新版功能.

* Menu:

* dircmp 类::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/filecmp.py


File: python.info,  Node: dircmp 类,  Up: filecmp --- 文件及目录的比较

5.11.5.1 ‘dircmp’ 类
....................

 -- 类: filecmp.dircmp (a, b, ignore=None, hide=None)

     创建一个用于比较目录 `a' 和 `b' 的新的目录比较对象。 `ignore' 是需
     要忽略的文件名列表，且默认为 *note filecmp.DEFAULT_IGNORES: 851. 。
     `hide' 是需要隐藏的文件名列表，且默认为 ‘[os.curdir, os.pardir]’ 。

     *note dircmp: 852. 类如 *note filecmp.cmp(): 1c60. 中所描述的那样对
     文件进行 `shallow' 比较。

     *note dircmp: 852. 类提供以下方法：

      -- 方法: report ()

          将 `a' 与 `b' 之间的比较结果打印（到 *note sys.stdout: 317. ）
          。

      -- 方法: report_partial_closure ()

          打印 `a' 与 `b' 及共同直接子目录的比较结果。

      -- 方法: report_full_closure ()

          打印 `a' 与 `b' 及共同子目录比较结果（递归地）。

     *note dircmp: 852. 类提供了一些有趣的属性，用以得到关于参与比较的目
     录树的各种信息。

     需要注意，通过 *note __getattr__(): 323. 钩子，所有的属性将会惰性求
     值，因此如果只使用那些计算简便的属性，将不会有速度损失。

      -- 属性: left

          目录 `a' 。

      -- 属性: right

          目录 `b' 。

      -- 属性: left_list

          经 `hide' 和 `ignore' 过滤，目录 `a' 中的文件与子目录。

      -- 属性: right_list

          经 `hide' 和 `ignore' 过滤，目录 `b' 中的文件与子目录。

      -- 属性: common

          同时存在于目录 `a' 和 `b' 中的文件和子目录。

      -- 属性: left_only

          仅在目录 `a' 中的文件和子目录。

      -- 属性: right_only

          仅在目录 `b' 中的文件和子目录。

      -- 属性: common_dirs

          同时存在于目录 `a' 和 `b' 中的子目录。

      -- 属性: common_files

          同时存在于目录 `a' 和 `b' 中的文件。

      -- 属性: common_funny

          在目录 `a' 和 `b' 中类型不同的名字，或者那些 *note os.stat():
          1f2. 报告错误的名字。

      -- 属性: same_files

          在目录 `a' 和 `b' 中，使用类的文件比较操作符判定相等的文件。

      -- 属性: diff_files

          在目录 `a' 和 `b' 中，根据类的文件比较操作符判定内容不等的文件
          。

      -- 属性: funny_files

          在目录 `a' 和 `b' 中无法比较的文件。

      -- 属性: subdirs

          一个将 *note common_dirs: 1c6e. 中名称映射为 *note dircmp:
          852. 对象的字典。

 -- 属性: filecmp.DEFAULT_IGNORES

     3.4 新版功能.

     默认被 *note dircmp: 852. 忽略的目录列表。

下面是一个简单的例子，使用 ‘subdirs’ 属性递归搜索两个目录以显示公共差异
文件：

     >>> from filecmp import dircmp
     >>> def print_diff_files(dcmp):
     ...     for name in dcmp.diff_files:
     ...         print("diff_file %s found in %s and %s" % (name, dcmp.left,
     ...               dcmp.right))
     ...     for sub_dcmp in dcmp.subdirs.values():
     ...         print_diff_files(sub_dcmp)
     ...
     >>> dcmp = dircmp('dir1', 'dir2')
     >>> print_diff_files(dcmp)


File: python.info,  Node: tempfile --- 生成临时文件和目录,  Next: glob --- Unix 风格路径名模式扩展,  Prev: filecmp --- 文件及目录的比较,  Up: 文件和目录访问

5.11.6 ‘tempfile’ — 生成临时文件和目录
--------------------------------------

`源代码：' Lib/tempfile.py(1)

__________________________________________________________________

该模块用于创建临时文件和目录，它可以跨平台使用。*note TemporaryFile:
1c77.、*note NamedTemporaryFile: d51.、*note TemporaryDirectory: bd0. 和
*note SpooledTemporaryFile: aae. 是带有自动清理功能的高级接口，可用作上
下文管理器。*note mkstemp(): 1c78. 和 *note mkdtemp(): 1c79. 是低级函数
，使用完毕需手动清理。

所有由用户调用的函数和构造函数都带有参数，这些参数可以设置临时文件和临时
目录的路径和名称。该模块生成的文件名包括一串随机字符，在公共的临时目录中
，这些字符可以让创建文件更加安全。为了保持向后兼容性，参数的顺序有些奇怪
。所以为了代码清晰，建议使用关键字参数。

这个模块定义了以下内容供用户调用：

 -- 函数: tempfile.TemporaryFile (mode='w+b', buffering=-1,
          encoding=None, newline=None, suffix=None, prefix=None,
          dir=None, *, errors=None)

     返回一个 *note file-like object: 1c7a. （文件类对象）作为临时存储区
     域。创建该文件使用了与 *note mkstemp(): 1c78. 相同的安全规则。它将
     在关闭后立即销毁（包括垃圾回收机制关闭该对象时）。在 Unix 下，该文
     件在目录中的条目根本不创建，或者创建文件后立即就被删除了，其他平台
     不支持此功能。您的代码不应依赖使用此功能创建的临时文件名称，因为它
     在文件系统中的名称可能是可见的，也可能是不可见的。

     生成的对象可以用作上下文管理器（参见 *note 例子: 1c7b.）。完成上下
     文或销毁临时文件对象后，临时文件将从文件系统中删除。

     `mode' 参数默认值为 ‘'w+b'’，所以创建的文件不用关闭，就可以读取或写
     入。因为用的是二进制模式，所以无论存的是什么数据，它在所有平台上都
     表现一致。`buffering'、`encoding'、`errors' 和 `newline' 的含义与
     *note open(): 4f8. 中的相同。

     参数 `dir'、`prefix' 和 `suffix' 的含义和默认值都与它们在 *note
     mkstemp(): 1c78. 中的相同。

     在 POSIX 平台上，它返回的对象是真实的文件对象。在其他平台上，它是一
     个文件类对象 (file-like object)，它的 ‘file’ 属性是底层的真实文件对
     象。

     如果可用，则使用 *note os.O_TMPFILE: 88d. 标志（仅限于 Linux，需要
     3.11 及更高版本的内核）。

     引发一个 ‘tempfile.mkstemp’ *note 审计事件: ea1.，附带参数
     ‘fullpath’。

     在 3.5 版更改: 如果可用，现在用的是 *note os.O_TMPFILE: 88d. 标志。

     在 3.8 版更改: 添加了 `errors' 参数。

 -- 函数: tempfile.NamedTemporaryFile (mode='w+b', buffering=-1,
          encoding=None, newline=None, suffix=None, prefix=None,
          dir=None, delete=True, *, errors=None)

     此函数执行的操作与 *note TemporaryFile(): 1c77. 完全相同，但确保了
     该临时文件在文件系统中具有可见的名称（在 Unix 上表现为目录条目不取
     消链接）。从返回的文件类对象的 ‘name’ 属性中可以检索到文件名。在临
     时文件仍打开时，是否允许用文件名第二次打开文件，在各个平台上是不同
     的（在 Unix 上可以，但在 Windows NT 或更高版本上不行）。如果
     `delete' 为 true（默认值），则文件会在关闭后立即被删除。该函数返回
     的对象始终是文件类对象 (file-like object)，它的 ‘file’ 属性是底层的
     真实文件对象。文件类对象可以像普通文件一样在 *note with: 6f2. 语句
     中使用。

     引发一个 ‘tempfile.mkstemp’ *note 审计事件: ea1.，附带参数
     ‘fullpath’。

     在 3.8 版更改: 添加了 `errors' 参数。

 -- 函数: tempfile.SpooledTemporaryFile (max_size=0, mode='w+b',
          buffering=-1, encoding=None, newline=None, suffix=None,
          prefix=None, dir=None, *, errors=None)

     此函数执行的操作与 *note TemporaryFile(): 1c77. 完全相同，但会将数
     据缓存在内存中，直到文件大小超过 `max_size'，或调用文件的
     ‘fileno()’ 方法为止，此时数据会被写入磁盘，并且写入操作与 *note
     TemporaryFile(): 1c77. 相同。

     此函数生成的文件对象有一个额外的方法——‘rollover()’，可以忽略文件大
     小，让文件立即写入磁盘。

     返回的对象是文件类对象 (file-like object)，它的 ‘_file’ 属性是
     *note io.BytesIO: 7a4. 或 *note io.TextIOWrapper: 5fc. 对象（取决于
     指定的是二进制模式还是文本模式）或真实的文件对象（取决于是否已调用
     ‘rollover()’）。文件类对象可以像普通文件一样在 *note with: 6f2. 语
     句中使用。

     在 3.3 版更改: 现在，文件的 truncate 方法可接受一个 ‘size’ 参数。

     在 3.8 版更改: 添加了 `errors' 参数。

 -- 函数: tempfile.TemporaryDirectory (suffix=None, prefix=None,
          dir=None)

     此函数会安全地创建一个临时目录，且使用与 *note mkdtemp(): 1c79. 相
     同的规则。此函数返回的对象可用作上下文管理器（参见 *note 例子:
     1c7b.）。完成上下文或销毁临时目录对象后，新创建的临时目录及其所有内
     容将从文件系统中删除。

     可以从返回对象的 ‘name’ 属性中找到临时目录的名称。当返回的对象用作
     上下文管理器时，这个 ‘name’ 会作为 *note with: 6f2. 语句中 ‘as’ 子
     句的目标（如果有 as 的话）。

     可以调用 ‘cleanup()’ 方法来手动清理目录。

     引发一个 ‘tempfile.mkdtemp’ *note 审计事件: ea1.，附带参数
     ‘fullpath’。

     3.2 新版功能.

 -- 函数: tempfile.mkstemp (suffix=None, prefix=None, dir=None,
          text=False)

     以最安全的方式创建一个临时文件。假设所在平台正确实现了 *note
     os.open(): 66e. 的 *note os.O_EXCL: 1c7c. 标志，则创建文件时不会有
     竞争的情况。该文件只能由创建者读写，如果所在平台用权限位来标记文件
     是否可执行，那么没有人有执行权。文件描述符不会过继给子进程。

     与 *note TemporaryFile(): 1c77. 不同，*note mkstemp(): 1c78. 用户用
     完临时文件后需要自行将其删除。

     如果 `suffix' 不是 ‘None’ 则文件名将以该后缀结尾，是 ‘None’ 则没有
     后缀。*note mkstemp(): 1c78. 不会在文件名和后缀之间加点，如果需要加
     一个点号，请将其放在 `suffix' 的开头。

     如果 `prefix' 不是 ‘None’，则文件名将以该前缀开头，是 ‘None’ 则使用
     默认前缀。默认前缀是 *note gettempprefix(): 1c7d. 或 *note
     gettempprefixb(): 1c7e. 函数的返回值（自动调用合适的函数）。

     如果 `dir' 不为 ‘None’，则在指定的目录创建文件，是 ‘None’ 则使用默
     认目录。默认目录是从一个列表中选择出来的，这个列表不同平台不一样，
     但是用户可以设置 `TMPDIR'、`TEMP' 或 `TMP' 环境变量来设置目录的位置
     。因此，不能保证生成的临时文件路径很规范，比如，通过 ‘os.popen()’ 将
     路径传递给外部命令时仍需要加引号。

     如果 `suffix'、`prefix' 和 `dir' 中的任何一个不是 ‘None’，就要保证
     它们是同一数据类型。如果它们是 bytes，则返回的名称的类型就是 bytes
     而不是 str。如果确实要用默认参数，但又想要返回值是 bytes 类型，请传
     入 ‘suffix=b''’。

     如果指定了 `text' 且为真值，文件会以文本模式打开。 否则，文件（默认
     ）会以二进制模式打开。

     *note mkstemp(): 1c78. 返回一个元组，元组中第一个元素是句柄，它是一
     个系统级句柄，指向一个打开的文件（等同于 *note os.open(): 66e. 的返
     回值），第二元素是该文件的绝对路径。

     引发一个 ‘tempfile.mkstemp’ *note 审计事件: ea1.，附带参数
     ‘fullpath’。

     在 3.5 版更改: 现在，`suffix'、`prefix' 和 `dir' 可以以 bytes 类型
     按顺序提供，以获得 bytes 类型的返回值。之前只允许使用 str。`suffix'
     和 `prefix' 现在可以接受 ‘None’，并且默认为 ‘None’ 以使用合适的默认
     值。

     在 3.6 版更改: `dir' 参数现在可接受一个路径类对象 (*note path-like
     object: 373.)。

 -- 函数: tempfile.mkdtemp (suffix=None, prefix=None, dir=None)

     以最安全的方式创建一个临时目录，创建该目录时不会有竞争的情况。该目
     录只能由创建者读取、写入和搜索。

     *note mkdtemp(): 1c79. 用户用完临时目录后需要自行将其删除。

     `prefix'、`suffix' 和 `dir' 的含义与它们在 *note mkstemp(): 1c78. 中
     的相同。

     *note mkdtemp(): 1c79. 返回新目录的绝对路径。

     引发一个 ‘tempfile.mkdtemp’ *note 审计事件: ea1.，附带参数
     ‘fullpath’。

     在 3.5 版更改: 现在，`suffix'、`prefix' 和 `dir' 可以以 bytes 类型
     按顺序提供，以获得 bytes 类型的返回值。之前只允许使用 str。`suffix'
     和 `prefix' 现在可以接受 ‘None’，并且默认为 ‘None’ 以使用合适的默认
     值。

     在 3.6 版更改: `dir' 参数现在可接受一个路径类对象 (*note path-like
     object: 373.)。

 -- 函数: tempfile.gettempdir ()

     返回放置临时文件的目录的名称。这个方法的返回值就是本模块所有函数的
     `dir' 参数的默认值。

     Python 搜索标准目录列表，以找到调用者可以在其中创建文件的目录。这个
     列表是：

       1. ‘TMPDIR’ 环境变量指向的目录。

       2. ‘TEMP’ 环境变量指向的目录。

       3. ‘TMP’ 环境变量指向的目录。

       4. 与平台相关的位置：

             * 在 Windows 上，依次为 ‘C:\TEMP’、‘C:\TMP’、‘\TEMP’ 和
               ‘\TMP’。

             * 在所有其他平台上，依次为 ‘/tmp’、‘/var/tmp’ 和
               ‘/usr/tmp’。

       5. 不得已时，使用当前工作目录。

     搜索的结果会缓存起来，参见下面 *note tempdir: 1c80. 的描述。

 -- 函数: tempfile.gettempdirb ()

     与 *note gettempdir(): 1c7f. 相同，但返回值为字节类型。

     3.5 新版功能.

 -- 函数: tempfile.gettempprefix ()

     返回用于创建临时文件的文件名前缀，它不包含目录部分。

 -- 函数: tempfile.gettempprefixb ()

     与 *note gettempprefix(): 1c7d. 相同，但返回值为字节类型。

     3.5 新版功能.

本模块使用一个全局变量来存储由 *note gettempdir(): 1c7f. 返回的临时文件
目录路径。可以直接给它赋值，这样可以覆盖自动选择的路径，但是不建议这样做
。本模块中的所有函数都带有一个 `dir' 参数，该参数可用于指定目录，这是推
荐的方法。

 -- 数据: tempfile.tempdir

     当设置为 ‘None’ 以外的其他值时，此变量将决定本模块所有函数的 `dir'
     参数的默认值。

     如果在调用除 *note gettempprefix(): 1c7d. 外的上述任何函数时
     ‘tempdir’ 为 ‘None’ (默认值) 则它会按照 *note gettempdir(): 1c7f. 中
     所描述的算法来初始化。

* Menu:

* 例子: 例子<3>.
* 已弃用的函数和变量::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/tempfile.py


File: python.info,  Node: 例子<3>,  Next: 已弃用的函数和变量,  Up: tempfile --- 生成临时文件和目录

5.11.6.1 例子
.............

以下是 *note tempfile: 104. 模块典型用法的一些示例:

     >>> import tempfile

     # create a temporary file and write some data to it
     >>> fp = tempfile.TemporaryFile()
     >>> fp.write(b'Hello world!')
     # read data from file
     >>> fp.seek(0)
     >>> fp.read()
     b'Hello world!'
     # close the file, it will be removed
     >>> fp.close()

     # create a temporary file using a context manager
     >>> with tempfile.TemporaryFile() as fp:
     ...     fp.write(b'Hello world!')
     ...     fp.seek(0)
     ...     fp.read()
     b'Hello world!'
     >>>
     # file is now closed and removed

     # create a temporary directory using the context manager
     >>> with tempfile.TemporaryDirectory() as tmpdirname:
     ...     print('created temporary directory', tmpdirname)
     >>>
     # directory and contents have been removed


File: python.info,  Node: 已弃用的函数和变量,  Prev: 例子<3>,  Up: tempfile --- 生成临时文件和目录

5.11.6.2 已弃用的函数和变量
...........................

创建临时文件有一种历史方法，首先使用 *note mktemp(): e95. 函数生成一个文
件名，然后使用该文件名创建文件。不幸的是，这是不安全的，因为在调用 *note
mktemp(): e95. 与随后尝试创建文件的进程之间的时间里，其他进程可能会使用
该名称创建文件。解决方案是将两个步骤结合起来，立即创建文件。这个方案目前
被 *note mkstemp(): 1c78. 和上述其他函数所采用。

 -- 函数: tempfile.mktemp (suffix='', prefix='tmp', dir=None)

     2.3 版后已移除: 使用 *note mkstemp(): 1c78. 来代替。

     返回一个绝对路径，这个路径指向的文件在调用本方法时不存在。
     `prefix'、`suffix' 和 `dir' 参数与 *note mkstemp(): 1c78. 中的同名
     参数类似，不同之处在于不支持字节类型的文件名，不支持 ‘suffix=None’
     和 ‘prefix=None’。

          警告: 使用此功能可能会在程序中引入安全漏洞。当你开始使用本方法
          返回的文件执行任何操作时，可能有人已经捷足先登了。*note
          mktemp(): e95. 的功能可以很轻松地用 *note
          NamedTemporaryFile(): d51. 代替，当然需要传递 ‘delete=False’ 参
          数:

               >>> f = NamedTemporaryFile(delete=False)
               >>> f.name
               '/tmp/tmptjujjt'
               >>> f.write(b"Hello World!\n")
               13
               >>> f.close()
               >>> os.unlink(f.name)
               >>> os.path.exists(f.name)
               False


File: python.info,  Node: glob --- Unix 风格路径名模式扩展,  Next: fnmatch --- Unix 文件名模式匹配,  Prev: tempfile --- 生成临时文件和目录,  Up: 文件和目录访问

5.11.7 ‘glob’ — Unix 风格路径名模式扩展
---------------------------------------

`源代码:' Lib/glob.py(1)

__________________________________________________________________

*note glob: 8a. 模块可根据 Unix 终端所用规则找出所有匹配特定模式的路径名
，但会按不确定的顺序返回结果。 波浪号扩展不会生效，但 ‘*’, ‘?’ 以及表示
为 ‘[]’ 的字符范围将被正确地匹配。 这是通过配合使用 *note os.scandir():
260. 和 *note fnmatch.fnmatch(): 1c86. 函数来实现的，而不是通过实际发起
调用子终端。 请注意不同于 *note fnmatch.fnmatch(): 1c86.，*note glob:
8a. 会将以点号 (‘.’) 开头的文件名作为特殊情况来处理。 （对于波浪号和终端
变量扩展，请使用 *note os.path.expanduser(): 1ff. 和 *note
os.path.expandvars(): d4c.。）

对于字面值匹配，请将原字符用方括号括起来。 例如，‘'[?]'’ 将匹配字符
‘'?'’。

参见
....

*note pathlib: c9. 模块提供高级路径对象。

 -- 函数: glob.glob (pathname, *, recursive=False)

     返回匹配 `pathname' 的可能为空的路径名列表，其中的元素必须为包含路
     径信息的字符串。 `pathname' 可以是绝对路径 (如
     ‘/usr/src/Python-1.5/Makefile’) 或相对路径 (如
     ‘../../Tools/*/*.gif’)，并且可包含 shell 风格的通配符。 结果也将包
     含无效的符号链接（与在 shell 中一样）。 结果是否排序取决于具体文件
     系统。 如果某个符合条件的文件在调用此函数期间被移除或添加，是否包括
     该文件的路径是没有规定的。

     如果 `recursive' 为真值，则模式 "‘**’" 将匹配目录中的任何文件以及零
     个或多个目录、子目录和符号链接。 如果模式加了一个 *note os.sep:
     1c87. 或 *note os.altsep: 1c88. 则将不匹配文件。

     引发一个 *note 审计事件: ea1. ‘glob.glob’ 附带参数 ‘pathname’,
     ‘recursive’。

          注解: 在一个较大的目录树中使用 "‘**’" 模式可能会消耗非常多的时
          间。

     在 3.5 版更改: 支持使用 "‘**’" 的递归 glob。

 -- 函数: glob.iglob (pathname, *, recursive=False)

     返回一个 *note iterator: 104b.，它会产生与 *note glob(): 8a. 相同的
     结果，但不会实际地同时保存它们。

     引发一个 *note 审计事件: ea1. ‘glob.glob’ 附带参数 ‘pathname’,
     ‘recursive’。

 -- 函数: glob.escape (pathname)

     转义所有特殊字符 (‘'?'’, ‘'*'’ 和 ‘'['’)。 这适用于当你想要匹配可能
     带有特殊字符的任意字符串字面值的情况。 在 drive/UNC 共享点中的特殊
     字符不会被转义，例如在 Windows 上 ‘escape('//?/c:/Quo vadis?.txt')’
     将返回 ‘'//?/c:/Quo vadis[?].txt'’。

     3.4 新版功能.

例如，考虑一个包含以下内容的目录：文件 ‘1.gif’, ‘2.txt’, ‘card.gif’ 以及
一个子目录 ‘sub’ 其中只包含一个文件 ‘3.txt’.  *note glob(): 8a. 将产生如
下结果。 请注意路径的任何开头部分都将被保留。:

     >>> import glob
     >>> glob.glob('./[0-9].*')
     ['./1.gif', './2.txt']
     >>> glob.glob('*.gif')
     ['1.gif', 'card.gif']
     >>> glob.glob('?.gif')
     ['1.gif']
     >>> glob.glob('**/*.txt', recursive=True)
     ['2.txt', 'sub/3.txt']
     >>> glob.glob('./**/', recursive=True)
     ['./', './sub/']

如果目录包含以 ‘.’ 打头的文件，它们默认将不会被匹配。 例如，考虑一个包含
‘card.gif’ 和 ‘.card.gif’ 的目录:

     >>> import glob
     >>> glob.glob('*.gif')
     ['card.gif']
     >>> glob.glob('.c*')
     ['.card.gif']

参见
....

模块 *note fnmatch: 81.

     Shell 风格文件名（而非路径）扩展

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/glob.py


File: python.info,  Node: fnmatch --- Unix 文件名模式匹配,  Next: linecache --- 随机读写文本行,  Prev: glob --- Unix 风格路径名模式扩展,  Up: 文件和目录访问

5.11.8 ‘fnmatch’ — Unix 文件名模式匹配
--------------------------------------

`源代码:' Lib/fnmatch.py(1)

__________________________________________________________________

此模块提供了 Unix shell 风格的通配符，它们 `并不' 等同于正则表达式（关于
后者的文档参见 *note re: de. 模块）。 shell 风格通配符所使用的特殊字符如
下：

模式             含义
                 
----------------------------------------------------------
                 
‘*’              匹配所有
                 
                 
‘?’              匹配任何单个字符
                 
                 
‘[seq]’          匹配 `seq' 中的任何字符
                 
                 
‘[!seq]’         匹配任何不在 `seq' 中的字符
                 

对于字面值匹配，请将原字符用方括号括起来。 例如，‘'[?]'’ 将匹配字符
‘'?'’。

注意文件名分隔符 (Unix 上为 ‘'/'’) `不是' 此模块所特有的。 请参见 *note
glob: 8a. 模块了解文件名扩展 (*note glob: 8a. 使用 *note filter(): 1c8b.
来匹配文件名的各个部分)。 类似地，以一个句点打头的文件名也不是此模块所特
有的，可以通过 ‘*’ 和 ‘?’ 模式来匹配。

 -- 函数: fnmatch.fnmatch (filename, pattern)

     检测 `filename' 字符串是否匹配 `pattern' 字符串，返回 *note True:
     4a1. 或 *note False: 390.。 两个形参都会使用 *note
     os.path.normcase(): 1c01. 进行大小写正规化。 *note fnmatchcase():
     1c8c. 可被用于执行大小写敏感的比较，无论这是否为所在操作系统的标准
     。

     这个例子将打印当前目录下带有扩展名 ‘.txt’ 的所有文件名:

          import fnmatch
          import os

          for file in os.listdir('.'):
              if fnmatch.fnmatch(file, '*.txt'):
                  print(file)

 -- 函数: fnmatch.fnmatchcase (filename, pattern)

     检测 `filename' 是否匹配 `pattern'，返回 *note True: 4a1. 或 *note
     False: 390.；此比较是大小写敏感的，并且不会应用 *note
     os.path.normcase(): 1c01.。

 -- 函数: fnmatch.filter (names, pattern)

     基于可迭代对象 `names' 中匹配 `pattern' 的元素构造一个列表。 它等价
     于 ‘[n for n in names if fnmatch(n, pattern)]’，但实现得更有效率。

 -- 函数: fnmatch.translate (pattern)

     返回 shell 风格 `pattern' 转换成的正则表达式以便用于 *note
     re.match(): bbb.。

     示例:

          >>> import fnmatch, re
          >>>
          >>> regex = fnmatch.translate('*.txt')
          >>> regex
          '(?s:.*\\.txt)\\Z'
          >>> reobj = re.compile(regex)
          >>> reobj.match('foobar.txt')
          <re.Match object; span=(0, 10), match='foobar.txt'>

参见
....

模块 *note glob: 8a.

     Unix shell 风格路径扩展。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/fnmatch.py


File: python.info,  Node: linecache --- 随机读写文本行,  Next: shutil --- 高阶文件操作,  Prev: fnmatch --- Unix 文件名模式匹配,  Up: 文件和目录访问

5.11.9 ‘linecache’ — 随机读写文本行
-----------------------------------

`源代码:' Lib/linecache.py(1)

__________________________________________________________________

*note linecache: a9. 模块允许从一个 Python 源文件中获取任意的行，并会尝
试使用缓存进行内部优化，常应用于从单个文件读取多行的场合。 此模块被
*note traceback: 114. 模块用来提取源码行以便包含在格式化的回溯中。

*note tokenize.open(): 1c8f. 函数被用于打开文件。 此函数使用 *note
tokenize.detect_encoding(): 1c90. 来获取文件的编码格式；如果未指明编码格
式，则默认编码为 UTF-8。

*note linecache: a9. 模块定义了下列函数：

 -- 函数: linecache.getline (filename, lineno, module_globals=None)

     从名为 `filename' 的文件中获取 `lineno' 行，此函数绝不会引发异常 —
     出现错误时它将返回 ‘''’ (所有找到的行都将包含换行符作为结束)。

     如果找不到名为 `filename' 的文件，此函数会先在 `module_globals' 中
     检查 PEP 302(2) ‘__loader__’。 如果存在这样的加载器并且它定义了
     ‘get_source’ 方法，则由该方法来确定源行 (如果 ‘get_source()’ 返回
     ‘None’，则该函数返回 ‘''’)。 最后，如果 `filename' 是一个相对路径文
     件名，则它会在模块搜索路径 ‘sys.path’ 中按条目的相对位置进行查找。

 -- 函数: linecache.clearcache ()

     清空缓存。 如果你不再需要之前使用 *note getline(): 712. 从文件读取
     的行即可使用此函数。

 -- 函数: linecache.checkcache (filename=None)

     检查缓存有效性。 如果缓存中的文件在磁盘上发生了改变，而你需要更新后
     的版本即可使用此函数。 如果省略了 `filename'，它会检查缓存中的所有
     条目。

 -- 函数: linecache.lazycache (filename, module_globals)

     捕获有关某个非基于文件的模块的足够细节信息，以允许稍后再通过 *note
     getline(): 712. 来获取其中的行，即使当稍后调用时 `module_globals' 为
     ‘None’。 这可以避免在实际需要读取行之前执行 I/O，也不必始终保持模块
     全局变量。

     3.5 新版功能.

示例:

     >>> import linecache
     >>> linecache.getline(linecache.__file__, 8)
     'import sys\n'

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/linecache.py

   (2) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: shutil --- 高阶文件操作,  Prev: linecache --- 随机读写文本行,  Up: 文件和目录访问

5.11.10 ‘shutil’ — 高阶文件操作
-------------------------------

`源代码：' Lib/shutil.py(1)

__________________________________________________________________

*note shutil: ea. 模块提供了一系列对文件和文件集合的高阶操作。 特别是提
供了一些支持文件拷贝和删除的函数。 对于单个文件的操作，请参阅 *note os:
c5. 模块。

     警告: 即便是高阶文件拷贝函数 (*note shutil.copy(): 25a, *note
     shutil.copy2(): 25b.) 也无法拷贝所有的文件元数据。

     在 POSIX 平台上，这意味着将丢失文件所有者和组以及 ACL 数据。 在 Mac
     OS 上，资源钩子和其他元数据不被使用。 这意味着将丢失这些资源并且文
     件类型和创建者代码将不正确。 在 Windows 上，将不会拷贝文件所有者、
     ACL 和替代数据流。

* Menu:

* 目录和文件操作::
* 归档操作::
* 查询输出终端的尺寸::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/shutil.py


File: python.info,  Node: 目录和文件操作,  Next: 归档操作,  Up: shutil --- 高阶文件操作

5.11.10.1 目录和文件操作
........................

 -- 函数: shutil.copyfileobj (fsrc, fdst[, length])

     将文件类对象 `fsrc' 的内容拷贝到文件类对象 `fdst'。 整数值 `length'
     如果给出则为缓冲区大小。 特别地， `length' 为负值表示拷贝数据时不对
     源数据进行分块循环处理；默认情况下会分块读取数据以避免不受控制的内
     存消耗。 请注意如果 `fsrc' 对象的当前文件位置不为 0，则只有从当前文
     件位置到文件末尾的内容会被拷贝。

 -- 函数: shutil.copyfile (src, dst, *, follow_symlinks=True)

     将名为 `src' 的文件的内容（不包括元数据）拷贝到名为 `dst' 的文件并
     以尽可能高效的方式返回 `dst'。 `src' 和 `dst' 均为路径类对象或以字
     符串形式给出的路径名。

     `dst' 必须是完整的目标文件名；对于接受目标目录路径的拷贝请参见
     *note copy(): 25a.。 如果 `src' 和 `dst' 指定了同一个文件，则将引发
     *note SameFileError: 8bc.。

     目标位置必须是可写的；否则将引发 *note OSError: 1d4. 异常。 如果
     `dst' 已经存在，它将被替换。 特殊文件如字符或块设备以及管道无法用此
     函数来拷贝。

     如果 `follow_symlinks' 为假值且 `src' 为符号链接，则将创建一个新的
     符号链接而不是拷贝 `src' 所指向的文件。

     引发一个 *note 审计事件: ea1. ‘shutil.copyfile’ 附带参数 ‘src’,
     ‘dst’。

     在 3.3 版更改: 曾经是引发 *note IOError: 99a. 而不是 *note OSError:
     1d4.。 增加了 `follow_symlinks' 参数。 现在是返回 `dst'。

     在 3.4 版更改: 引发 *note SameFileError: 8bc. 而不是 *note Error:
     8bb.。 由于前者是后者的子类，此改变是向后兼容的。

     在 3.8 版更改: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地
     拷贝文件。 参见 *note 依赖于具体平台的高效拷贝操作: 25f. 一节。

 -- 例外: shutil.SameFileError

     此异常会在 *note copyfile(): 259. 中的源和目标为同一文件时被引发。

     3.4 新版功能.

 -- 函数: shutil.copymode (src, dst, *, follow_symlinks=True)

     从 `src' 拷贝权限位到 `dst'。 文件的内容、所有者和分组将不受影响。
     `src' 和 `dst' 均为路径类对象或字符串形式的路径名。 如果
     `follow_symlinks' 为假值，并且 `src' 和 `dst' 均为符号链接，*note
     copymode(): 1c97. 将尝试修改 `dst' 本身的模式（而非它所指向的文件）
     。 此功能并不是在所有平台上均可用；请参阅 *note copystat(): a7f. 了
     解详情。 如果 *note copymode(): 1c97. 无法修改本机平台上的符号链接
     ，而它被要求这样做，它将不做任何操作即返回。

     引发一个 *note 审计事件: ea1. ‘shutil.copymode’ 附带参数 ‘src’,
     ‘dst’。

     在 3.3 版更改: 加入 `follow_symlinks' 参数。

 -- 函数: shutil.copystat (src, dst, *, follow_symlinks=True)

     从 `src' 拷贝权限位、最近访问时间、最近修改时间以及旗标到 `dst'。 在
     Linux上，*note copystat(): a7f. 还会在可能的情况下拷贝“扩展属性”。
     文件的内容、所有者和分组将不受影响。 `src' 和 `dst' 均为路径类对象
     或字符串形式的路径名。

     如果 `follow_symlinks' 为假值，并且 `src' 和 `dst' 均指向符号链接，
     *note copystat(): a7f. 将作用于符号链接本身而非该符号链接所指向的文
     件 — 从 `src' 符号链接读取信息，并将信息写入 `dst' 符号链接。

          注解: 并非所有平台者提供检查和修改符号链接的功能。 Python 本身
          可以告诉你哪些功能是在本机上可用的。

             * 如果 ‘os.chmod in os.supports_follow_symlinks’ 为 ‘True’，
               则 *note copystat(): a7f. 可以修改符号链接的权限位。

             * 如果 ‘os.utime in os.supports_follow_symlinks’ 为 ‘True’，
               则 *note copystat(): a7f. 可以修改符号链接的最近访问和修
               改时间。

             * 如果 ‘os.chflags in os.supports_follow_symlinks’ 为
               ‘True’，则 *note copystat(): a7f. 可以修改符号链接的旗标
               。 (‘os.chflags’ 不是在所有平台上均可用。)

          在此功能部分或全部不可用的平台上，当被要求修改一个符号链接时，
          *note copystat(): a7f. 将尽量拷贝所有内容。 *note copystat():
          a7f. 一定不会返回失败信息。

          更多信息请参阅 *note os.supports_follow_symlinks: 1c98.。

     引发一个 *note 审计事件: ea1. ‘shutil.copystat’ 附带参数 ‘src’,
     ‘dst’。

     在 3.3 版更改: 添加了 `follow_symlinks' 参数并且支持 Linux 扩展属性
     。

 -- 函数: shutil.copy (src, dst, *, follow_symlinks=True)

     将文件 `src' 拷贝到文件或目录 `dst'。 `src' 和 `dst' 应为 *note
     路径类对象: 373. 或字符串。 如果 `dst' 指定了一个目录，文件将使用
     `src' 中的基准文件名拷贝到 `dst' 中。 将返回新创建文件所对应的路径
     。

     如果 `follow_symlinks' 为假值且 `src' 为符号链接，则 `dst' 也将被创
     建为符号链接。 如果 `follow_symlinks' 为真值且 `src' 为符号链接，
     `dst' 将成为 `src' 所指向的文件的一个副本。

     *note copy(): 25a. 会拷贝文件数据和文件的权限模式 (参见 *note
     os.chmod(): a3b.)。 其他元数据，例如文件的创建和修改时间不会被保留
     。 要保留所有原有的元数据，请改用 *note copy2(): 25b. 。

     引发一个 *note 审计事件: ea1. ‘shutil.copyfile’ 附带参数 ‘src’,
     ‘dst’。

     引发一个 *note 审计事件: ea1. ‘shutil.copymode’ 附带参数 ‘src’,
     ‘dst’。

     在 3.3 版更改: 添加了 `follow_symlinks' 参数。 现在会返回新创建文件
     的路径。

     在 3.8 版更改: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地
     拷贝文件。 参见 *note 依赖于具体平台的高效拷贝操作: 25f. 一节。

 -- 函数: shutil.copy2 (src, dst, *, follow_symlinks=True)

     类似于 *note copy(): 25a.，区别在于 *note copy2(): 25b. 还会尝试保
     留文件的元数据。

     当 `follow_symlinks' 为假值且 `src' 为符号链接时，*note copy2():
     25b. 会尝试将来自 `src' 符号链接的所有元数据拷贝到新创建的 `dst' 符
     号链接。 但是，此功能不是在所有平台上均可用。 在此功能部分或全部不
     可用的平台上，*note copy2(): 25b. 将尽量保留所有元数据；*note
     copy2(): 25b. 一定不会由于无法保留文件元数据而引发异常。

     *note copy2(): 25b. 会使用 *note copystat(): a7f. 来拷贝文件元数据
     。 请参阅 *note copystat(): a7f. 了解有关修改符号链接元数据的平台支
     持的更多信息。

     引发一个 *note 审计事件: ea1. ‘shutil.copyfile’ 附带参数 ‘src’,
     ‘dst’。

     引发一个 *note 审计事件: ea1. ‘shutil.copystat’ 附带参数 ‘src’,
     ‘dst’。

     在 3.3 版更改: 添加了 `follow_symlinks' 参数，还会尝试拷贝扩展文件
     系统属性（目前仅限 Linux）。 现在会返回新创建文件的路径。

     在 3.8 版更改: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地
     拷贝文件。 参见 *note 依赖于具体平台的高效拷贝操作: 25f. 一节。

 -- 函数: shutil.ignore_patterns (*patterns)

     这个工厂函数会创建一个函数，它可被用作 *note copytree(): 21b. 的
     `ignore' 可调用对象参数，以忽略那些匹配所提供的 glob 风格的
     `patterns' 之一的文件和目录。 参见以下示例。

 -- 函数: shutil.copytree (src, dst, symlinks=False, ignore=None,
          copy_function=copy2, ignore_dangling_symlinks=False,
          dirs_exist_ok=False)

     将以 `src' 为根起点的整个目录树拷贝到名为 `dst' 的目录并返回目标目
     录。 `dirs_exist_ok' 指明是否要在 `dst' 或任何丢失的父目录已存在的
     情况下引发异常。

     目录的权限和时间会通过 *note copystat(): a7f. 来拷贝，单个文件则会
     使用 *note copy2(): 25b. 来拷贝。

     如果 `symlinks' 为真值，源目录树中的符号链接会在新目录树中表示为符
     号链接，并且原链接的元数据在平台允许的情况下也会被拷贝；如果为假值
     或省略，则会将被链接文件的内容和元数据拷贝到新目录树。

     当 `symlinks' 为假值时，如果符号链接所指向的文件不存在，则会在拷贝
     进程的末尾将一个异常添加到 *note Error: 8bb. 异常中的错误列表。 如
     果你希望屏蔽此异常那就将可选的 `ignore_dangling_symlinks' 旗标设为
     真值。 请注意此选项在不支持 *note os.symlink(): a43. 的平台上将不起
     作用。

     如果给出了 `ignore'，它必须是一个可调用对象，该对象将接受 *note
     copytree(): 21b. 所访问的目录以及 *note os.listdir(): a49. 所返回的
     目录内容列表作为其参数。 由于 *note copytree(): 21b. 是递归地被调用
     的，`ignore' 可调用对象对于每个被拷贝目录都将被调用一次。 该可调用
     对象必须返回一个相对于当前目录的目录和文件名序列（即其第二个参数的
     子集）；随后这些名称将在拷贝进程中被忽略。 *note ignore_patterns():
     1c99. 可被用于创建这种基于 glob 风格模式来忽略特定名称的可调用对象
     。

     如果发生了（一个或多个）异常，将引发一个附带原因列表的 *note Error:
     8bb.。

     如果给出了 `copy_function'，它必须是一个将被用来拷贝每个文件的可调
     用对象。 它在被调用时会将源路径和目标路径作为参数传入。 默认情况下
     ，*note copy2(): 25b. 将被使用，但任何支持同样签名（与 *note
     copy(): 25a. 一致）都可以使用。

     引发一个 *note 审计事件: ea1. ‘shutil.copytree’ 附带参数 ‘src’,
     ‘dst’。

     在 3.3 版更改: 当 `symlinks' 为假值时拷贝元数据。 现在会返回 `dst'。

     在 3.2 版更改: 添加了 `copy_function' 参数以允许提供定制的拷贝函数
     。 添加了 `ignore_dangling_symlinks' 参数以便在 `symlinks' 为假值时
     屏蔽符号链接错误。

     在 3.8 版更改: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地
     拷贝文件。 参见 *note 依赖于具体平台的高效拷贝操作: 25f. 一节。

     3.8 新版功能: `dirs_exist_ok' 形参。

 -- 函数: shutil.rmtree (path, ignore_errors=False, onerror=None)

     删除一个完整的目录树；`path' 必须指向一个目录（但不能是一个目录的符
     号链接）。 如果 `ignore_errors' 为真值，删除失败导致的错误将被忽略
     ；如果为假值或是省略，此类错误将通过调用由 `onerror' 所指定的处理程
     序来处理，或者如果此参数被省略则将引发一个异常。

          注解: 在支持必要的基于 fd 的函数的平台上，默认会使用 *note
          rmtree(): 21d. 的可防御符号链接攻击的版本。 在其他平台上，
          *note rmtree(): 21d. 较易遭受符号链接攻击：给定适当的时间和环
          境，攻击者可以操纵文件系统中的符号链接来删除他们在其他情况下无
          法访问的文件。 应用程序可以使用 *note
          rmtree.avoids_symlink_attacks: 1c9a. 函数属性来确定此类情况具
          体是哪一些。

     如果提供了 `onerror'，它必须为接受三个形参的可调用对象: `function',
     `path' 和 `excinfo'。

     第一个形参 `function' 是引发异常的函数；它依赖于具体的平台和实现。
     第二个形参 `path' 将是传递给 `function' 的路径名。 第三个形参
     `excinfo' 将是由 *note sys.exc_info(): c67. 所返回的异常信息。 由
     `onerror' 所引发的异常将不会被捕获。

     引发一个 *note 审计事件: ea1. ‘shutil.rmtree’ 附带参数 ‘path’。

     在 3.3 版更改: 添加了一个防御符号链接攻击的版本，如果平台支持基于
     fd 的函数就会被使用。

     在 3.8 版更改: 在 Windows 上将不会再在移除连接之前删除目录连接中的
     内容。

      -- 属性: rmtree.avoids_symlink_attacks

          指明当前平台和实现是否提供防御符号链接攻击的 *note rmtree():
          21d. 版本。 目前它仅在平台支持基于 fd 的目录访问函数时才返回真
          值。

          3.3 新版功能.

 -- 函数: shutil.move (src, dst, copy_function=copy2)

     递归地将一个文件或目录 (`src') 移至另一位置 (`dst') 并返回目标位置
     。

     如果目标是已存在的目录，则 `src' 会被移至该目录下。 如果目标已存在
     但不是目录，它可能会被覆盖，具体取决于 *note os.rename(): a40. 的语
     义。

     如果目标是在当前文件系统中，则会使用 *note os.rename(): a40.。 在其
     他情况下，`src' 将被拷贝至 `dst'，使用的函数为 `copy_function'，然
     后目标会被移除。 对于符号链接，则将在 `dst' 之下或以其本身为名称创
     建一个指向 `src' 目标的新符号链接，并且 `src' 将被移除。

     如果给出了 `copy_function'，则它必须为接受两个参数 `src' 和 `dst' 的
     可调用对象，并将在 *note os.rename(): a40. 无法使用时被用来将 `src'
     拷贝到 `dst'。 如果源是一个目录，则会调用 *note copytree(): 21b.，
     并向它传入 ‘copy_function()’。 默认的 `copy_function' 是 *note
     copy2(): 25b.。 使用 *note copy(): 25a. 作为 `copy_function' 允许在
     无法附带拷贝元数据时让移动操作成功执行，但其代价是不拷贝任何元数据
     。

     引发一个 *note 审计事件: ea1. ‘shutil.move’ 附带参数 ‘src’, ‘dst’。

     在 3.3 版更改: 为异类文件系统添加了显式的符号链接处理，以便使它适应
     GNU 的 ‘mv’ 的行为。 现在会返回 `dst'。

     在 3.5 版更改: 增加了 `copy_function' 关键字参数。

     在 3.8 版更改: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地
     拷贝文件。 参见 *note 依赖于具体平台的高效拷贝操作: 25f. 一节。

 -- 函数: shutil.disk_usage (path)

     返回给定路径的磁盘使用统计数据，形式为一个 *note named tuple: aab.，
     其中包含 `total', `used' 和 `free' 属性，分别表示总计、已使用和未使
     用空间的字节数。 `path' 可以是一个文件或是一个目录。

     3.3 新版功能.

     在 3.8 版更改: 在 Windows 上，`path' 现在可以是一个文件或目录。

     *note 可用性: 136f.: Unix, Windows。

 -- 函数: shutil.chown (path, user=None, group=None)

     修改给定 `path' 的所有者 `user' 和/或 `group'。

     `user' 可以是一个系统用户名或 uid；`group' 同样如此。 要求至少有一
     个参数。

     另请参阅下层的函数 *note os.chown(): a3c.。

     引发一个 *note 审计事件: ea1. ‘shutil.chown’ 附带参数 ‘path’,
     ‘user’, ‘group’。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: shutil.which (cmd, mode=os.F_OK | os.X_OK, path=None)

     返回当给定的 `cmd' 被调用时将要运行的可执行文件的路径。 如果没有
     `cmd' 会被调用则返回 ‘None’。

     `mode' 是一个传递给 *note os.access(): a39. 的权限掩码，在默认情况
     下将确定文件是否存在并且为可执行文件。

     当未指定 `path' 时，将会使用 *note os.environ(): b3f. 的结果，返回
     "PATH" 的值或回退为 *note os.defpath: fef.。

     在 Windows 上当前目录总是会被添加为 `path' 的第一项，无论你是否使用
     默认值或提供你自己的路径，这是命令行终端在查找可执行文件时所采用的
     行为方式。 此外，当在 `path' 中查找 `cmd' 时，还会检查 ‘PATHEXT’ 环
     境变量。 例如，如果你调用 ‘shutil.which("python")’，*note which():
     eea. 将搜索 ‘PATHEXT’ 来确定它要在 `path' 目录中查找 ‘python.exe’。
     例如，在 Windows 上:

          >>> shutil.which("python")
          'C:\\Python33\\python.EXE'

     3.3 新版功能.

     在 3.8 版更改: 现在可以接受 *note bytes: 33a. 类型。 如果 `cmd' 的
     类型为 *note bytes: 33a.，结果的类型也将为 *note bytes: 33a.。

 -- 例外: shutil.Error

     此异常会收集在多文件操作期间所引发的异常。 对于 *note copytree():
     21b.，此异常参数将是一个由三元组 (`srcname', `dstname',
     `exception') 构成的列表。

* Menu:

* 依赖于具体平台的高效拷贝操作::
* copytree 示例::
* rmtree 示例::


File: python.info,  Node: 依赖于具体平台的高效拷贝操作,  Next: copytree 示例,  Up: 目录和文件操作

5.11.10.2 依赖于具体平台的高效拷贝操作
......................................

从 Python 3.8 开始，所有涉及文件拷贝的函数 (*note copyfile(): 259, *note
copy(): 25a, *note copy2(): 25b, *note copytree(): 21b. 以及 *note
move(): 25c.) 将会使用平台专属的 "fast-copy" 系统调用以便更高效地拷贝文
件 (参见 bpo-33671(1))。 "fast-copy" 意味着拷贝操作将发生于内核之中，避
免像在 "‘outfd.write(infd.read())’" 中那样使用 Python 用户空间的缓冲区。

在 macOS 上将会使用 fcopyfile(2) 来拷贝文件内容（不含元数据）。

在 Linux 上将会使用 *note os.sendfile(): 362.。

在 Windows 上 *note shutil.copyfile(): 259. 将会使用更大的默认缓冲区（1
MiB 而非 64 KiB）并且会使用基于 *note memoryview(): 25d. 的 *note
shutil.copyfileobj(): 25e. 变种形式。

如果快速拷贝操作失败并且没有数据被写入目标文件，则 shutil 将在内部静默地
回退到使用效率较低的 *note copyfileobj(): 25e. 函数。

在 3.8 版更改.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33671

   (2) http://www.manpagez.com/man/3/copyfile/


File: python.info,  Node: copytree 示例,  Next: rmtree 示例,  Prev: 依赖于具体平台的高效拷贝操作,  Up: 目录和文件操作

5.11.10.3 copytree 示例
.......................

这个示例就是上面所描述的 *note copytree(): 21b. 函数的实现，其中省略了文
档字符串。 它还展示了此模块所提供的许多其他函数。

     def copytree(src, dst, symlinks=False):
         names = os.listdir(src)
         os.makedirs(dst)
         errors = []
         for name in names:
             srcname = os.path.join(src, name)
             dstname = os.path.join(dst, name)
             try:
                 if symlinks and os.path.islink(srcname):
                     linkto = os.readlink(srcname)
                     os.symlink(linkto, dstname)
                 elif os.path.isdir(srcname):
                     copytree(srcname, dstname, symlinks)
                 else:
                     copy2(srcname, dstname)
                 # XXX What about devices, sockets etc.?
             except OSError as why:
                 errors.append((srcname, dstname, str(why)))
             # catch the Error from the recursive copytree so that we can
             # continue with other files
             except Error as err:
                 errors.extend(err.args[0])
         try:
             copystat(src, dst)
         except OSError as why:
             # can't copy file access times on Windows
             if why.winerror is None:
                 errors.extend((src, dst, str(why)))
         if errors:
             raise Error(errors)

另一个使用 *note ignore_patterns(): 1c99. 辅助函数的例子:

     from shutil import copytree, ignore_patterns

     copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

这将会拷贝除 ‘.pyc’ 文件和以 ‘tmp’ 打头的文件或目录以外的所有条目.

另一个使用 `ignore' 参数来添加记录调用的例子:

     from shutil import copytree
     import logging

     def _logpath(path, names):
         logging.info('Working in %s', path)
         return []   # nothing will be ignored

     copytree(source, destination, ignore=_logpath)


File: python.info,  Node: rmtree 示例,  Prev: copytree 示例,  Up: 目录和文件操作

5.11.10.4 rmtree 示例
.....................

这个例子演示了如何在 Windows 上删除一个目录树，其中部分文件设置了只读属
性位。 它会使用 onerror 回调函数来清除只读属性位并再次尝试删除。 任何后
续的失败都将被传播。

     import os, stat
     import shutil

     def remove_readonly(func, path, _):
         "Clear the readonly bit and reattempt the removal"
         os.chmod(path, stat.S_IWRITE)
         func(path)

     shutil.rmtree(directory, onerror=remove_readonly)


File: python.info,  Node: 归档操作,  Next: 查询输出终端的尺寸,  Prev: 目录和文件操作,  Up: shutil --- 高阶文件操作

5.11.10.5 归档操作
..................

3.2 新版功能.

在 3.5 版更改: 添加了对 `xztar' 格式的支持。

本模块也提供了用于创建和读取压缩和归档文件的高层级工具。 它们依赖于
*note zipfile: 143. 和 *note tarfile: 102. 模块。

 -- 函数: shutil.make_archive (base_name, format[, root_dir[, base_dir[,
          verbose[, dry_run[, owner[, group[, logger]]]]]]])

     创建一个归档文件（例如 zip 或 tar）并返回其名称。

     `base_name' 是要创建的文件名称，包括路径，去除任何特定格式的扩展名
     。 `format' 是归档格式：为 "zip" (如果 *note zlib: 145. 模块可用),
     "tar", "gztar" (如果 *note zlib: 145. 模块可用), "bztar" (如果
     *note bz2: 14. 模块可用) 或 "xztar" (如果 *note lzma: ae. 模块可用)
     中的一个。

     `root_dir' 是一个目录，它将作为归档文件的根目录，归档中的所有路径都
     将是它的相对路径；例如，我们通常会在创建归档之前用 chdir 命令切换到
     `root_dir'。

     `base_dir' 是我们要执行归档的起始目录；也就是说 `base_dir' 将成为归
     档中所有文件和目录共有的路径前缀。 `base_dir' 必须相对于 `root_dir'
     给出。 请参阅 *note 使用 base_dir 的归档程序示例: 1ca1. 了解如何同
     时使用 `base_dir' 和 `root_dir'。

     `root_dir' 和 `base_dir' 默认均为当前目录。

     如果 `dry_run' 为真值，则不会创建归档文件，但将要被执行的操作会被记
     录到 `logger'。

     `owner' 和 `group' 将在创建 tar 归档文件时被使用。 默认会使用当前的
     所有者和分组。

     `logger' 必须是一个兼容 PEP 282(1) 的对象，通常为 *note
     logging.Logger: 3af. 的实例。

     `verbose' 参数已不再使用并进入弃用状态。

     引发一个 *note 审计事件: ea1. ‘shutil.make_archive’ 并附带参数
     ‘base_name’, ‘format’, ‘root_dir’, ‘base_dir’。

          注解: 这个函数不是线程安全的。

     在 3.8 版更改: 现在对于通过 ‘format="tar"’ 创建的归档文件将使用新式
     的 pax (POSIX.1-2001) 格式而非旧式的 GNU 格式。

 -- 函数: shutil.get_archive_formats ()

     返回支持的归档格式列表。 所返回序列中的每个元素为一个元组 ‘(name,
     description)’。

     默认情况下 *note shutil: ea. 提供以下格式:

        - `zip': ZIP 文件（如果 *note zlib: 145. 模块可用）。

        - `tar': 未压缩的 tar 文件。 对于新归档文件将使用 POSIX.1-2001
          pax 格式。

        - `gztar': gzip 压缩的 tar 文件（如果 *note zlib: 145. 模块可用
          ）。

        - `bztar': bzip2 压缩的 tar 文件（如果 *note bz2: 14. 模块可用）
          。

        - `xztar': xz 压缩的 tar 文件（如果 *note lzma: ae. 模块可用）。

     你可以通过使用 *note register_archive_format(): 1ca3. 注册新的格式
     或为任何现有格式提供你自己的归档器。

 -- 函数: shutil.register_archive_format (name, function[, extra_args[,
          description]])

     为 `name' 格式注册一个归档器。

     `function' 是将被用来解包归档文件的可调用对象。 该可调用对象将接收
     要创建文件的 `base_name'，再加上要归档内容的 `base_dir' (其默认值为
     *note os.curdir: 1c02.)。 更多参数会被作为关键字参数传入: `owner',
     `group', `dry_run' 和 `logger' (与向 *note make_archive(): 21c. 传
     入的参数一致)。

     如果给出了 `extra_args'，则其应为一个 ‘(name, value)’ 对的序列，将
     在归档器可调用对象被使用时作为附加的关键字参数。

     `description' 由 *note get_archive_formats(): 1ca2. 使用，它将返回
     归档器的列表。 默认值为一个空字符串。

 -- 函数: shutil.unregister_archive_format (name)

     从支持的格式中移除归档格式 `name'。

 -- 函数: shutil.unpack_archive (filename[, extract_dir[, format]])

     解包一个归档文件。 `filename' 是归档文件的完整路径。

     `extract_dir' 是归档文件解包的目标目录名称。 如果未提供，则将使用当
     前工作目录。

     `format' 是归档格式：应为 "zip", "tar", "gztar", "bztar" 或 "xztar"
     之一。 或者任何通过 *note register_unpack_format(): 1ca5. 注册的其
     他格式。 如果未提供，*note unpack_archive(): b9f. 将使用归档文件的
     扩展名来检查是否注册了对应于该扩展名的解包器。 在未找到任何解包器的
     情况下，将引发 *note ValueError: 1fc.。

     引发一个 *note 审计事件: ea1. ‘shutil.unpack_archive’ 附带参数
     ‘filename’, ‘extract_dir’, ‘format’。

     在 3.7 版更改: 接受一个 *note path-like object: 373. 作为
     `filename' 和 `extract_dir'。

 -- 函数: shutil.register_unpack_format (name, extensions, function[,
          extra_args[, description]])

     注册一个解包格式。 `name' 为格式名称而 `extensions' 为对应于该格式
     的扩展名列表，例如 Zip 文件的扩展名为 ‘.zip’。

     `function' 是将被用来解包归档文件的可调用对象。 该可调用对象将接受
     归档文件的路径，加上该归档文件要被解包的目标目录。

     如果提供了 `extra_args'，则其应为一个 ‘(name, value)’ 元组的序列，
     将被作为关键字参数传递给该可调用对象。

     可以提供 `description' 来描述该格式，它将被 *note
     get_unpack_formats(): 1ca6. 返回。

 -- 函数: shutil.unregister_unpack_format (name)

     撤销注册一个解包格式。 `name' 为格式的名称。

 -- 函数: shutil.get_unpack_formats ()

     返回所有已注册的解包格式列表。 所返回序列中的每个元素为一个元组
     ‘(name, extensions, description)’。

     默认情况下 *note shutil: ea. 提供以下格式:

        - `zip': ZIP 文件（只有在相应模块可用时才能解包压缩文件）。

        - `tar': 未压缩的 tar 文件。

        - `gztar': gzip 压缩的 tar 文件（如果 *note zlib: 145. 模块可用
          ）。

        - `bztar': bzip2 压缩的 tar 文件（如果 *note bz2: 14. 模块可用）
          。

        - `xztar': xz 压缩的 tar 文件（如果 *note lzma: ae. 模块可用）。

     你可以通过使用 *note register_unpack_format(): 1ca5. 注册新的格式或
     为任何现有格式提供你自己的解包器。

* Menu:

* 归档程序示例::
* 使用 base_dir 的归档程序示例::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0282


File: python.info,  Node: 归档程序示例,  Next: 使用 base_dir 的归档程序示例,  Up: 归档操作

5.11.10.6 归档程序示例
......................

在这个示例中，我们创建了一个 gzip 压缩的 tar 归档文件，其中包含用户的
‘.ssh’ 目录下的所有文件:

     >>> from shutil import make_archive
     >>> import os
     >>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
     >>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
     >>> make_archive(archive_name, 'gztar', root_dir)
     '/Users/tarek/myarchive.tar.gz'

结果归档文件中包含有:

     $ tar -tzvf /Users/tarek/myarchive.tar.gz
     drwx------ tarek/staff       0 2010-02-01 16:23:40 ./
     -rw-r--r-- tarek/staff     609 2008-06-09 13:26:54 ./authorized_keys
     -rwxr-xr-x tarek/staff      65 2008-06-09 13:26:54 ./config
     -rwx------ tarek/staff     668 2008-06-09 13:26:54 ./id_dsa
     -rwxr-xr-x tarek/staff     609 2008-06-09 13:26:54 ./id_dsa.pub
     -rw------- tarek/staff    1675 2008-06-09 13:26:54 ./id_rsa
     -rw-r--r-- tarek/staff     397 2008-06-09 13:26:54 ./id_rsa.pub
     -rw-r--r-- tarek/staff   37192 2010-02-06 18:23:10 ./known_hosts


File: python.info,  Node: 使用 base_dir 的归档程序示例,  Prev: 归档程序示例,  Up: 归档操作

5.11.10.7 使用 `base_dir' 的归档程序示例
........................................

在这个例子中，与 *note 上面的例子: 1ca9. 类似，我们演示了如何使用 *note
make_archive(): 21c.，但这次是使用 `base_dir'。 我们现在具有如下的目录结
构:

     $ tree tmp
     tmp
     └── root
         └── structure
             ├── content
                 └── please_add.txt
             └── do_not_add.txt

在最终的归档中，应当会包括 ‘please_add.txt’，但不应当包括
‘do_not_add.txt’。 因此我们使用以下代码:

     >>> from shutil import make_archive
     >>> import os
     >>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
     >>> make_archive(
     ...     archive_name,
     ...     'tar',
     ...     root_dir='tmp/root',
     ...     base_dir='structure/content',
     ... )
     '/Users/tarek/my_archive.tar'

列出结果归档中的文件我们将会得到:

     $ python -m tarfile -l /Users/tarek/myarchive.tar
     structure/content/
     structure/content/please_add.txt


File: python.info,  Node: 查询输出终端的尺寸,  Prev: 归档操作,  Up: shutil --- 高阶文件操作

5.11.10.8 查询输出终端的尺寸
............................

 -- 函数: shutil.get_terminal_size (fallback=(columns, lines))

     获取终端窗口的尺寸。

     对于两个维度中的每一个，会分别检查环境变量 ‘COLUMNS’ 和 ‘LINES’。 如
     果定义了这些变量并且其值为正整数，则将使用这些值。

     如果未定义 ‘COLUMNS’ 或 ‘LINES’，这是通常的情况，则连接到 *note
     sys.__stdout__: 1cac. 的终端将通过发起调用 *note
     os.get_terminal_size(): a51. 被查询。

     如果由于系统不支持查询，或是由于我们未连接到某个终端而导致查询终端
     尺寸不成功，则会使用在 ‘fallback’ 形参中给出的值。 ‘fallback’ 默认
     为 ‘(80, 24)’，这是许多终端模拟器所使用的默认尺寸。

     返回的值是一个 *note os.terminal_size: 1cad. 类型的具名元组。

     另请参阅: The Single UNIX Specification, Version 2, Other
     Environment Variables(1).

     3.3 新版功能.

参见
....

模块 *note os: c5.

     操作系统接口，包括处理比 Python *note 文件对象: b4a. 更低级别文件的
     功能。

模块 *note io: a2.

     Python的内置 I/O 库，包括抽象类和一些具体的类，如文件 I/O 。

内置函数 *note open(): 4f8.

     使用 Python 打开文件进行读写的标准方法。

   ---------- Footnotes ----------

   (1) 
http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html#tag_002_003


File: python.info,  Node: 数据持久化,  Next: 数据压缩和存档,  Prev: 文件和目录访问,  Up: Python 标准库

5.12 数据持久化
===============

本章中描述的模块支持在磁盘上以持久形式存储 Python 数据。 *note pickle:
cb. 和 *note marshal: b1. 模块可以将许多 Python 数据类型转换为字节流，然
后从字节中重新创建对象。 各种与 DBM 相关的模块支持一系列基于散列的文件格
式，这些格式存储字符串到其他字符串的映射。

本章中描述的模块列表是：

* Menu:

* pickle: pickle --- Python 对象序列化. Python 对象序列化
* copyreg: copyreg --- 注册配合 pickle 模块使用的函数. 注册配合 pickle 模块使用的函数
* shelve: shelve --- Python 对象持久化. Python 对象持久化
* marshal: marshal --- 内部 Python 对象序列化. 内部 Python 对象序列化
* dbm: dbm --- Unix "数据库" 接口. Unix "数据库" 接口
* sqlite3: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块. SQLite 数据库 DB-API 2.0 接口模块


File: python.info,  Node: pickle --- Python 对象序列化,  Next: copyreg --- 注册配合 pickle 模块使用的函数,  Up: 数据持久化

5.12.1 ‘pickle’ — Python 对象序列化
-----------------------------------

`源代码：' Lib/pickle.py(1)

__________________________________________________________________

模块 *note pickle: cb. 实现了对一个 Python 对象结构的二进制序列化和反序
列化。 `"pickling"' 是将 Python 对象及其所拥有的层次结构转化为一个字节流
的过程，而 `"unpickling"' 是相反的操作，会将（来自一个 *note binary
file: 1cb4. 或者 *note bytes-like object: 5f1. 的）字节流转化回一个对象
层次结构。 pickling（和 unpickling）也被称为“序列化”, “编组” (2) 或者 “平
面化”。而为了避免混乱，此处采用术语 “封存 (pickling)” 和 “解封
(unpickling)”。

     警告: ‘pickle’ 模块**并不安全**。你只应该对你信任的数据进行
     unpickle操作。

     构建恶意的 pickle 数据来**在解封时执行任意代码**是可能的。绝对不要
     对不信任来源的数据和可能被篡改过的数据进行解封。

     请考虑使用 *note hmac: 8f. 来对数据进行签名，确保数据没有被篡改。

     在你处理不信任数据时，更安全的序列化格式如 *note json: a5. 可能更为
     适合。参见 *note 与 json 模块的比较: 1cb5. 。

* Menu:

* 与其他 Python 模块间的关系::
* 数据流格式::
* 模块接口::
* 可以被封存/解封的对象::
* 封存类实例::
* 类型，函数和其他对象的自定义归约::
* 外部缓冲区::
* 限制全局变量::
* 性能: 性能<2>.
* 例子: 例子<4>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/pickle.py

   (2) (1) 不要把它与 *note marshal: b1. 模块混淆。


File: python.info,  Node: 与其他 Python 模块间的关系,  Next: 数据流格式,  Up: pickle --- Python 对象序列化

5.12.1.1 与其他 Python 模块间的关系
...................................

* Menu:

* 与 marshal 间的关系::
* 与 json 模块的比较::


File: python.info,  Node: 与 marshal 间的关系,  Next: 与 json 模块的比较,  Up: 与其他 Python 模块间的关系

5.12.1.2 与 ‘marshal’ 间的关系
..............................

Python 有一个更原始的序列化模块称为 *note marshal: b1.，但一般地 *note
pickle: cb. 应该是序列化 Python 对象时的首选。*note marshal: b1. 存在主
要是为了支持 Python 的 ‘.pyc’ 文件.

*note pickle: cb. 模块与 *note marshal: b1. 在如下几方面显著地不同：

   * *note pickle: cb. 模块会跟踪已被序列化的对象，所以该对象之后再次被
     引用时不会再次被序列化。*note marshal: b1. 不会这么做。

     这隐含了递归对象和共享对象。递归对象指包含对自己的引用的对象。这种
     对象并不会被 marshal 接受，并且实际上尝试 marshal 递归对象会让你的
     Python 解释器崩溃。对象共享发生在对象层级中存在多处引用同一对象时。
     *note pickle: cb. 只会存储这些对象一次，并确保其他的引用指向同一个
     主副本。共享对象将保持共享，这可能对可变对象非常重要。

   * *note marshal: b1. 不能被用于序列化用户定义类及其实例。*note
     pickle: cb. 能够透明地存储并保存类实例，然而此时类定义必须能够从与
     被存储时相同的模块被引入。

   * 同样用于序列化的 *note marshal: b1. 格式不保证数据能移植到不同的
     Python 版本中。因为它的主要任务是支持 ‘.pyc’ 文件，必要时会以破坏向
     后兼容的方式更改这种序列化格式，为此 Python 的实现者保留了更改格式
     的权利。*note pickle: cb. 序列化格式可以在不同版本的 Python 中实现
     向后兼容，前提是选择了合适的 pickle 协议。如果你的数据要在 Python 2
     与 Python 3 之间跨越传递，封存和解封的代码在 2 和 3 之间也是不同的
     。


File: python.info,  Node: 与 json 模块的比较,  Prev: 与 marshal 间的关系,  Up: 与其他 Python 模块间的关系

5.12.1.3 与 ‘json’ 模块的比较
.............................

Pickle 协议和 JSON (JavaScript Object Notation)(1) 间有着本质的不同：

   * JSON 是一个文本序列化格式（它输出 unicode 文本，尽管在大多数时候它
     会接着以 ‘utf-8’ 编码），而 pickle 是一个二进制序列化格式；

   * JSON 是我们可以直观阅读的，而 pickle 不是；

   * JSON是可互操作的，在Python系统之外广泛使用，而pickle则是Python专用
     的；

   * 默认情况下，JSON 只能表示 Python 内置类型的子集，不能表示自定义的类
     ；但 pickle 可以表示大量的 Python 数据类型（可以合理使用 Python 的
     对象内省功能自动地表示大多数类型，复杂情况可以通过实现 *note
     specific object APIs: 1cb9. 来解决）。

   * 不像pickle，对一个不信任的JSON进行反序列化的操作本身不会造成任意代
     码执行漏洞。

参见
....

*note json: a5. 模块:一个允许JSON序列化和反序列化的标准库模块

   ---------- Footnotes ----------

   (1) http://json.org


File: python.info,  Node: 数据流格式,  Next: 模块接口,  Prev: 与其他 Python 模块间的关系,  Up: pickle --- Python 对象序列化

5.12.1.4 数据流格式
...................

*note pickle: cb. 所使用的数据格式仅可用于 Python。这样做的好处是没有外
部标准给该格式强加限制，比如 JSON 或 XDR（不能表示共享指针）标准；但这也
意味着非 Python 程序可能无法重新读取 pickle 封存的 Python 对象。

默认情况下，*note pickle: cb. 格式使用相对紧凑的二进制来存储。如果需要让
文件更小，可以高效地 *note 压缩: 1cbb. 由 pickle 封存的数据。

*note pickletools: cc. 模块包含了相应的工具用于分析 *note pickle: cb. 生
成的数据流。*note pickletools: cc. 源码中包含了对 pickle 协议使用的操作
码的大量注释。

当前共有 6 种不同的协议可用于封存操作。 使用的协议版本越高，读取所生成
pickle 对象所需的 Python 版本就要越新。

   * v0 版协议是原始的“人类可读”协议，并且向后兼容早期版本的 Python。

   * v1 版协议是较早的二进制格式，它也与早期版本的 Python 兼容。

   * v2 版协议是在 Python 2.3 中引入的。它为存储 *note new-style class:
     1cbc. 提供了更高效的机制。欲了解有关第 2 版协议带来的改进，请参阅
     PEP 307(1)。

   * v3 版协议是在 Python 3.0 中引入的。 它显式地支持 *note bytes: 33a.
     字节对象，不能使用 Python 2.x 解封。这是 Python 3.0-3.7 的默认协议
     。

   * v4 版协议添加于 Python 3.4。它支持存储非常大的对象，能存储更多种类
     的对象，还包括一些针对数据格式的优化。它是Python 3.8使用的默认协议
     。有关第 4 版协议带来改进的信息，请参阅 PEP 3154(2)。

   * 第 5 版协议是在 Python 3.8 中加入的。 它增加了对带外数据的支持，并
     可加速带内数据处理。 请参阅 PEP 574(3) 了解第 5 版协议所带来的改进
     的详情。

     注解: 序列化是一种比持久化更底层的概念，虽然 *note pickle: cb. 读取
     和写入的是文件对象，但它不处理持久对象的命名问题，也不处理对持久对
     象的并发访问（甚至更复杂）的问题。*note pickle: cb. 模块可以将复杂
     对象转换为字节流，也可以将字节流转换为具有相同内部结构的对象。处理
     这些字节流最常见的做法是将它们写入文件，但它们也可以通过网络发送或
     存储在数据库中。*note shelve: e8. 模块提供了一个简单的接口，用于在
     DBM 类型的数据库文件上封存和解封对象。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0307

   (2) https://www.python.org/dev/peps/pep-3154

   (3) https://www.python.org/dev/peps/pep-0574


File: python.info,  Node: 模块接口,  Next: 可以被封存/解封的对象,  Prev: 数据流格式,  Up: pickle --- Python 对象序列化

5.12.1.5 模块接口
.................

要序列化某个包含层次结构的对象，只需调用 *note dumps(): e07. 函数即可。
同样，要反序列化数据流，可以调用 *note loads(): 5cc. 函数。但是，如果要
对序列化和反序列化加以更多的控制，可以分别创建 *note Pickler: 20e. 或
*note Unpickler: 1cbe. 对象。

*note pickle: cb. 模块包含了以下常量：

 -- 数据: pickle.HIGHEST_PROTOCOL

     整数，可用的最高 *note 协议版本: 577.。此值可以作为 `协议' 值传递给
     *note dump(): 1cbf. 和 *note dumps(): e07. 函数，以及 *note
     Pickler: 20e. 的构造函数。

 -- 数据: pickle.DEFAULT_PROTOCOL

     整数，用于 pickle 数据的默认 *note 协议版本: 577.。它可能小于 *note
     HIGHEST_PROTOCOL: e08.。当前默认协议是 v4，它在 Python 3.4 中首次引
     入，与之前的版本不兼容。

     在 3.0 版更改: 默认协议版本是 3。

     在 3.8 版更改: 默认协议版本是 4。

*note pickle: cb. 模块提供了以下方法，让封存过程更加方便：

 -- 函数: pickle.dump (obj, file, protocol=None, *, fix_imports=True,
          buffer_callback=None)

     将对象 `obj' 封存以后的对象写入已打开的 *note file object: b4a.
     `file'。它等同于 ‘Pickler(file, protocol).dump(obj)’。

     参数 `file'、`protocol'、`fix_imports' 和 `buffer_callback' 的含义
     与它们在 *note Pickler: 20e. 的构造函数中的含义相同。

     在 3.8 版更改: 加入了 `buffer_callback' 参数。

 -- 函数: pickle.dumps (obj, protocol=None, *, fix_imports=True,
          buffer_callback=None)

     将 `obj' 封存以后的对象作为 *note bytes: 33a. 类型直接返回，而不是
     将其写入到文件。

     参数 `protocol'、`fix_imports' 和 `buffer_callback' 的含义与它们在
     *note Pickler: 20e. 的构造函数中的含义相同。

     在 3.8 版更改: 加入了 `buffer_callback' 参数。

 -- 函数: pickle.load (file, *, fix_imports=True, encoding="ASCII",
          errors="strict", buffers=None)

     从已打开的 *note file object: b4a. `文件' 中读取封存后的对象，重建
     其中特定对象的层次结构并返回。它相当于 ‘Unpickler(file).load()’。

     Pickle 协议版本是自动检测出来的，所以不需要参数来指定协议。封存对象
     以外的其他字节将被忽略。

     参数 `file'、`fix_imports'、`encoding'、`errors'、`strict' 和
     `buffers' 的含义与它们在 *note Unpickler: 1cbe. 的构造函数中的含义
     相同。

     在 3.8 版更改: 加入了 `buffers' 参数。

 -- 函数: pickle.loads (data, *, fix_imports=True, encoding="ASCII",
          errors="strict", buffers=None)

     重建并返回一个对象的封存表示形式 `data' 的对象层级结构。 `data' 必
     须为 *note bytes-like object: 5f1.。

     Pickle 协议版本是自动检测出来的，所以不需要参数来指定协议。封存对象
     以外的其他字节将被忽略。

     参数 `file'、`fix_imports'、`encoding'、`errors'、`strict' 和
     `buffers' 的含义与它们在 *note Unpickler: 1cbe. 的构造函数中的含义
     相同。

     在 3.8 版更改: 加入了 `buffers' 参数。

*note pickle: cb. 模块定义了以下 3 个异常：

 -- 例外: pickle.PickleError

     其他 pickle 异常的基类。它是 *note Exception: 1aa. 的一个子类。

 -- 例外: pickle.PicklingError

     当 *note Pickler: 20e. 遇到无法解封的对象时抛出此错误。它是 *note
     PickleError: 1cc1. 的子类。

     参考 *note 可以被封存/解封的对象: 1cc3. 来了解哪些对象可以被封存。

 -- 例外: pickle.UnpicklingError

     当解封出错时抛出此异常，例如数据损坏或对象不安全。它是 *note
     PickleError: 1cc1. 的子类。

     注意，解封时可能还会抛出其他异常，包括（但不限于） AttributeError、
     EOFError、ImportError 和 IndexError。

*note pickle: cb. 模块包含了 3 个类，*note Pickler: 20e.、*note
Unpickler: 1cbe. 和 *note PickleBuffer: 1cc5.：

 -- 类: pickle.Pickler (file, protocol=None, *, fix_imports=True,
          buffer_callback=None)

     它接受一个二进制文件用于写入 pickle 数据流。

     可选参数 `protocol' 是一个整数，告知 pickler 使用指定的协议，可选择
     的协议范围从 0 到 *note HIGHEST_PROTOCOL: e08.。如果没有指定，这一
     参数默认值为 *note DEFAULT_PROTOCOL: 1cc0.。指定一个负数就相当于指
     定 *note HIGHEST_PROTOCOL: e08.。

     参数 `file' 必须有一个 write() 方法，该 write() 方法要能接收字节作
     为其唯一参数。因此，它可以是一个打开的磁盘文件（用于写入二进制内容
     ），也可以是一个 *note io.BytesIO: 7a4. 实例，也可以是满足这一接口
     的其他任何自定义对象。

     如果 `fix_imports' 为 True 且 `protocol' 小于 3，pickle 将尝试将
     Python 3 中的新名称映射到 Python 2 中的旧模块名称，因此 Python 2 也
     可以读取封存的数据流。

     如果 `buffer_callback' 为 None（默认情况），缓冲区视图（buffer
     view）将会作为 pickle 流的一部分被序列化到 `file' 中。

     如果 `buffer_callback' 不为 None，那它可以用缓冲区视图调用任意次。
     如果某次调用返回了 False 值（例如 None），则给定的缓冲区是 *note
     带外的: 1cc6.，否则缓冲区是带内的（例如保存在了 pickle 流里面）。

     如果 `buffer_callback' 不是 None 且 `protocol' 是 None 或小于 5，就
     会出错。

     在 3.8 版更改: 加入了 `buffer_callback' 参数。

      -- 方法: dump (obj)

          将 `obj' 封存后的内容写入已打开的文件对象，该文件对象已经在构
          造函数中指定。

      -- 方法: persistent_id (obj)

          默认无动作，子类继承重载时使用。

          如果 *note persistent_id(): 1cc7. 返回 ‘None’，`obj' 会被照常
          pickle。如果返回其他值，*note Pickler: 20e. 会将这个函数的返回
          值作为 `obj' 的持久化 ID（Pickler 本应得到序列化数据流并将其写
          入文件，若此函数有返回值，则得到此函数的返回值并写入文件）。这
          个持久化 ID 的解释应当定义在 *note
          Unpickler.persistent_load(): 1cc8. 中（该方法定义还原对象的过
          程，并返回得到的对象）。注意，*note persistent_id(): 1cc7. 的
          返回值本身不能拥有持久化 ID。

          参阅 *note 持久化外部对象: 1cc9. 获取详情和使用示例。

      -- 属性: dispatch_table

          Pickler 对象的 dispatch 表是 *note copyreg.pickle(): 1cca. 中
          用到的 `reduction 函数' 的注册。dispatch 表本身是一个 class 到
          其 reduction 函数的映射键值对。一个 reduction 函数只接受一个参
          数，就是其关联的 class，函数行为应当遵守 *note __reduce__():
          19c. 接口规范。

          Pickler 对象默认并没有 *note dispatch_table: a71. 属性，该对象
          默认使用 *note copyreg: 27. 模块中定义的全局 dispatch 表。如果
          要为特定 Pickler 对象自定义序列化过程，可以将 *note
          dispatch_table: a71. 属性设置为类字典对象（dict-like object）
          。另外，如果 *note Pickler: 20e. 的子类设置了 *note
          dispatch_table: a71. 属性，则该子类的实例会使用这个表作为默认
          的 dispatch 表。

          参阅 *note Dispatch 表: 1ccb. 获取使用示例。

          3.3 新版功能.

      -- 方法: reducer_override (self, obj)

          可以在 *note Pickler: 20e. 的子类中定义的特殊 reducer。此方法
          的优先级高于 *note dispatch_table: a71. 中的任何 reducer。它应
          该与 *note __reduce__(): 19c. 方法遵循相同的接口，它也可以返回
          ‘NotImplemented’，这将使用 *note dispatch_table: a71. 里注册的
          reducer 来封存 ‘obj’。

          参阅 *note 类型，函数和其他对象的自定义归约: 1ccc. 获取详细的
          示例。

          3.8 新版功能.

      -- 属性: fast

          已弃用。设为 True 则启用快速模式。快速模式禁用了“备忘录”
          (memo) 的使用，即不生成多余的 PUT 操作码来加快封存过程。不应将
          其与自指 (self-referential) 对象一起使用，否则将导致 *note
          Pickler: 20e. 无限递归。

          如果需要进一步提高 pickle 的压缩率，请使用 *note
          pickletools.optimize(): 1cce.。

 -- 类: pickle.Unpickler (file, *, fix_imports=True, encoding="ASCII",
          errors="strict", buffers=None)

     它接受一个二进制文件用于读取 pickle 数据流。

     Pickle 协议版本是自动检测出来的，所以不需要参数来指定协议。

     参数 `file' 必须有三个方法，read() 方法接受一个整数参数，readinto()
     方法接受一个缓冲区作为参数，readline() 方法不需要参数，这与 *note
     io.BufferedIOBase: 591. 里定义的接口是相同的。因此 `file' 可以是一
     个磁盘上用于二进制读取的文件，也可以是一个 *note io.BytesIO: 7a4. 实
     例，也可以是满足这一接口的其他任何自定义对象。

     可选的参数是 `fix_imports', `encoding' 和 `errors'，用于控制由
     Python 2 生成的 pickle 流的兼容性。如果 `fix_imports' 为 True，则
     pickle 将尝试将旧的 Python 2 名称映射到 Python 3 中对应的新名称。
     `encoding' 和 `errors' 参数告诉 pickle 如何解码 Python 2 存储的 8 位
     字符串实例；这两个参数默认分别为 ’ASCII’ 和 ’strict’。`encoding' 参
     数可置为 ’bytes’ 来将这些 8 位字符串实例读取为字节对象。读取 NumPy
     array 和 Python 2 存储的 *note datetime: 195.、*note date: 194. 和
     *note time: 4fb. 实例时，请使用 ‘encoding='latin1'’。

     如果 `buffers' 为 None（默认值），则反序列化所需的所有数据都必须包
     含在 pickle 流中。这意味着在实例化 *note Pickler: 20e. 时（或调用
     *note dump(): 1cbf. 或 *note dumps(): e07. 时），参数
     `buffer_callback' 为 None。

     如果 `buffers' 不为 None，则每次 pickle 流引用 *note 带外: 1cc6. 缓
     冲区视图时，消耗的对象都应该是可迭代的启用缓冲区的对象。这样的缓冲
     区应该按顺序地提供给 Pickler 对象的 `buffer_callback' 方法。

     在 3.8 版更改: 加入了 `buffers' 参数。

      -- 方法: load ()

          从构造函数中指定的文件对象里读取封存好的对象，重建其中特定对象
          的层次结构并返回。封存对象以外的其他字节将被忽略。

      -- 方法: persistent_load (pid)

          默认抛出 *note UnpicklingError: 1cc4. 异常。

          如果定义了此方法，*note persistent_load(): 1cc8. 应当返回持久
          化 ID `pid' 所指定的对象。 如果遇到无效的持久化 ID，则应当引发
          *note UnpicklingError: 1cc4.。

          参阅 *note 持久化外部对象: 1cc9. 获取详情和使用示例。

      -- 方法: find_class (module, name)

          如有必要，导入 `module' 模块并返回其中名叫 `name' 的对象，其中
          `module' 和 `name' 参数都是 *note str: 339. 对象。注意，不要被
          这个函数的名字迷惑， *note find_class(): 1cd0. 同样可以用来导
          入函数。

          子类可以重载此方法，来控制加载对象的类型和加载对象的方式，从而
          尽可能降低安全风险。参阅 *note 限制全局变量: 1cd1. 获取更详细
          的信息。

          引发一个 *note 审计事件: ea1. ‘pickle.find_class’ 附带参数
          ‘module’、‘name’。

 -- 类: pickle.PickleBuffer (buffer)

     缓冲区的包装器 (wrapper)，缓冲区中包含着可封存的数据。`buffer' 必须
     是一个 *note buffer-providing: 15f7. 对象，比如 *note bytes-like
     object: 5f1. 或多维数组。

     *note PickleBuffer: 1cc5. 本身就可以生成缓冲区对象，因此可以将其传
     递给需要缓冲区生成器的其他 API，比如 *note memoryview: 25d.。

     *note PickleBuffer: 1cc5. 对象只能用 pickle 版本 5 及以上协议进行序
     列化。它们符合 *note 带外序列化: 1cc6. 的条件。

     3.8 新版功能.

      -- 方法: raw ()

          返回该缓冲区底层内存区域的 *note memoryview: 25d.。 返回的对象
          是一维的、C 连续布局的 memoryview，格式为 ‘B’ (无符号字节)。 如
          果缓冲区既不是 C 连续布局也不是 Fortran 连续布局的，则抛出
          *note BufferError: 1710. 异常。

      -- 方法: release ()

          释放由 PickleBuffer 占用的底层缓冲区。


File: python.info,  Node: 可以被封存/解封的对象,  Next: 封存类实例,  Prev: 模块接口,  Up: pickle --- Python 对象序列化

5.12.1.6 可以被封存/解封的对象
..............................

下列类型可以被封存：

   * ‘None’、‘True’ 和 ‘False’

   * 整数、浮点数、复数

   * str、byte、bytearray

   * 只包含可封存对象的集合，包括 tuple、list、set 和 dict

   * 定义在模块最外层的函数（使用 *note def: dc6. 定义，*note lambda:
     c37. 函数则不可以）

   * 定义在模块最外层的内置函数

   * 定义在模块最外层的类

   * 某些类实例，这些类的 *note __dict__: 504. 属性值或 *note
     __getstate__(): e09. 函数的返回值可以被封存（详情参阅 *note
     封存类实例: 1cb9. 这一段）。

尝试封存不能被封存的对象会抛出 *note PicklingError: 1cc2. 异常，异常发生
时，可能有部分字节已经被写入指定文件中。尝试封存递归层级很深的对象时，可
能会超出最大递归层级限制，此时会抛出 *note RecursionError: 63d. 异常，可
以通过 *note sys.setrecursionlimit(): e83. 调整递归层级，不过请谨慎使用
这个函数，因为可能会导致解释器崩溃。

注意，函数（内置函数或用户自定义函数）在被封存时，引用的是函数全名。(1)
这意味着只有函数所在的模块名，与函数名会被封存，函数体及其属性不会被封存
。因此，在解封的环境中，函数所属的模块必须是可以被导入的，而且模块必须包
含这个函数被封存时的名称，否则会抛出异常。(2)

同样的，类也只封存名称，所以在解封环境中也有和函数相同的限制。注意，类体
及其数据不会被封存，所以在下面的例子中类属性 ‘attr’ 不会存在于解封后的环
境中：

     class Foo:
         attr = 'A class attribute'

     picklestring = pickle.dumps(Foo)

这些限制决定了为什么必须在一个模块的最外层定义可封存的函数和类。

类似的，在封存类的实例时，其类体和类数据不会跟着实例一起被封存，只有实例
数据会被封存。这样设计是有目的的，在将来修复类中的错误、给类增加方法之后
，仍然可以载入原来版本类实例的封存数据来还原该实例。如果你准备长期使用一
个对象，可能会同时存在较多版本的类体，可以为对象添加版本号，这样就可以通
过类的 *note __setstate__(): 19d. 方法将老版本转换成新版本。

   ---------- Footnotes ----------

   (1) (2) 这就是为什么 *note lambda: c37. 函数不可以被封存：所有的匿名
函数都有同一个名字：‘<lambda>’。

   (2) (3) 抛出的异常有可能是 *note ImportError: 33d. 或 *note
AttributeError: 3a3.，也可能是其他异常。


File: python.info,  Node: 封存类实例,  Next: 类型，函数和其他对象的自定义归约,  Prev: 可以被封存/解封的对象,  Up: pickle --- Python 对象序列化

5.12.1.7 封存类实例
...................

在本节中，我们描述了可用于定义、自定义和控制如何封存和解封类实例的通用流
程。

通常，使一个实例可被封存不需要附加任何代码。Pickle 默认会通过 Python 的
内省机制获得实例的类及属性。而当实例解封时，它的 *note __init__(): d66.
方法通常 `不会' 被调用。其默认动作是：先创建一个未初始化的实例，然后还原
其属性，下面的代码展示了这种行为的实现机制：

     def save(obj):
         return (obj.__class__, obj.__dict__)

     def load(cls, attributes):
         obj = cls.__new__(cls)
         obj.__dict__.update(attributes)
         return obj

类可以改变默认行为，只需定义以下一种或几种特殊方法：

 -- 方法: object.__getnewargs_ex__ ()

     对于使用第 2 版或更高版协议的 pickle，实现了 *note
     __getnewargs_ex__(): 1cd6. 方法的类可以控制在解封时传给 *note
     __new__(): 892. 方法的参数。本方法必须返回一对 ‘(args, kwargs)’ 用
     于构建对象，其中 `args' 是表示位置参数的 tuple，而 `kwargs' 是表示
     命名参数的 dict。它们会在解封时传递给 *note __new__(): 892. 方法。

     如果类的 *note __new__(): 892. 方法只接受关键字参数，则应当实现这个
     方法。否则，为了兼容性，更推荐实现 *note __getnewargs__(): 6b7. 方
     法。

     在 3.6 版更改: *note __getnewargs_ex__(): 1cd6. 现在可用于第 2 和第
     3 版协议。

 -- 方法: object.__getnewargs__ ()

     这个方法与上一个 *note __getnewargs_ex__(): 1cd6. 方法类似，但仅支
     持位置参数。它要求返回一个 tuple 类型的 ‘args’，用于解封时传递给
     *note __new__(): 892. 方法。

     如果定义了 *note __getnewargs_ex__(): 1cd6.，那么 *note
     __getnewargs__(): 6b7. 就不会被调用。

     在 3.6 版更改: 在 Python 3.6 前，第 2、3 版协议会调用 *note
     __getnewargs__(): 6b7.，更高版本协议会调用 *note
     __getnewargs_ex__(): 1cd6.。

 -- 方法: object.__getstate__ ()

     类还可以进一步控制其实例的封存过程。如果类定义了 *note
     __getstate__(): e09.，它就会被调用，其返回的对象是被当做实例内容来
     封存的，否则封存的是实例的 __dict__。如果 *note __getstate__():
     e09. 未定义，实例的 *note __dict__: 504. 会被照常封存。

 -- 方法: object.__setstate__ (state)

     当解封时，如果类定义了 *note __setstate__(): 19d.，就会在已解封状态
     下调用它。此时不要求实例的 state 对象必须是 dict。没有定义此方法的
     话，先前封存的 state 对象必须是 dict，且该 dict 内容会在解封时赋给
     新实例的 __dict__。

          注解: 如果 *note __getstate__(): e09. 返回 False，那么在解封时
          就不会调用 *note __setstate__(): 19d. 方法。

参考 *note 处理有状态的对象: 1cd7. 一段获取如何使用 *note
__getstate__(): e09. 和 *note __setstate__(): 19d. 方法的更多信息。

     注解: 在解封时，实例的某些方法例如 *note __getattr__(): 323, *note
     __getattribute__(): 44f. 或 *note __setattr__(): e34. 可能会被调用
     。 由于这些方法可能要求某些内部不变量为真值，因此该类型应当实现
     *note __new__(): 892. 以建立这样的不变量，因为当解封一个实例时
     *note __init__(): d66. 并不会被调用。

可以看出，其实 pickle 并不直接调用上面的几个函数。事实上，这几个函数是复
制协议的一部分，它们实现了 *note __reduce__(): 19c. 这一特殊接口。复制协
议提供了统一的接口，用于在封存或复制对象的过程中取得所需数据。(1)

尽管这个协议功能很强，但是直接在类中实现 *note __reduce__(): 19c. 接口容
易产生错误。因此，设计类时应当尽可能的使用高级接口（比如 *note
__getnewargs_ex__(): 1cd6.、*note __getstate__(): e09. 和 *note
__setstate__(): 19d.）。后面仍然可以看到直接实现 *note __reduce__():
19c. 接口的状况，可能别无他法，可能为了获得更好的性能，或者两者皆有之。

 -- 方法: object.__reduce__ ()

     该接口当前定义如下。*note __reduce__(): 19c. 方法不带任何参数，并且
     应返回字符串或最好返回一个元组（返回的对象通常称为“reduce 值”）。

     如果返回字符串，该字符串会被当做一个全局变量的名称。它应该是对象相
     对于其模块的本地名称，pickle 模块会搜索模块命名空间来确定对象所属的
     模块。这种行为常在单例模式使用。

     如果返回的是元组，则应当包含 2 到 6 个元素，可选元素可以省略或设置
     为 ‘None’。每个元素代表的意义如下：

        * 一个可调用对象，该对象会在创建对象的最初版本时调用。

        * 可调用对象的参数，是一个元组。如果可调用对象不接受参数，必须提
          供一个空元组。

        * 可选元素，用于表示对象的状态，将被传给前述的 *note
          __setstate__(): 19d. 方法。 如果对象没有此方法，则这个元素必须
          是字典类型，并会被添加至 *note __dict__: 504. 属性中。

        * 可选元素，一个返回连续项的迭代器（而不是序列）。这些项会被
          ‘obj.append(item)’ 逐个加入对象，或被
          ‘obj.extend(list_of_items)’ 批量加入对象。这个元素主要用于
          list 的子类，也可以用于那些正确实现了 ‘append()’ 和 ‘extend()’
          方法的类。（具体是使用 ‘append()’ 还是 ‘extend()’ 取决于
          pickle 协议版本以及待插入元素的项数，所以这两个方法必须同时被
          类支持。）

        * 可选元素，一个返回连续键值对的迭代器（而不是序列）。这些键值对
          将会以 ‘obj[key] = value’ 的方式存储于对象中。该元素主要用于
          dict 子类，也可以用于那些实现了 *note __setitem__(): c6a. 的类
          。

        * 可选元素，一个带有 ‘(obj, state)’ 签名的可调用对象。该可调用对
          象允许用户以编程方式控制特定对象的状态更新行为，而不是使用
          ‘obj’ 的静态 *note __setstate__(): 19d. 方法。如果此处不是
          ‘None’，则此可调用对象的优先级高于 ‘obj’ 的 *note
          __setstate__(): 19d.。

          3.8 新版功能: 新增了元组的第 6 项，可选元素 ‘(obj, state)’。

 -- 方法: object.__reduce_ex__ (protocol)

     作为替代选项，也可以实现 *note __reduce_ex__(): 1a0c. 方法。 此方法
     的唯一不同之处在于它应接受一个整型参数用于指定协议版本。 如果定义了
     这个函数，则会覆盖 *note __reduce__(): 19c. 的行为。 此外，*note
     __reduce__(): 19c. 方法会自动成为扩展版方法的同义词。 这个函数主要
     用于为以前的 Python 版本提供向后兼容的 reduce 值。

* Menu:

* 持久化外部对象::
* Dispatch 表::
* 处理有状态的对象::

   ---------- Footnotes ----------

   (1) (4) *note copy: 26. 模块使用这一协议实现浅层 (shallow) 和深层
(deep) 复制操作。


File: python.info,  Node: 持久化外部对象,  Next: Dispatch 表,  Up: 封存类实例

5.12.1.8 持久化外部对象
.......................

为了获取对象持久化的利益， *note pickle: cb. 模块支持引用已封存数据流之
外的对象。 这样的对象是通过一个持久化 ID 来引用的，它应当是一个由字母数
字类字符组成的字符串 (对于第 0 版协议) (1) 或是一个任意对象 (用于任意新
版协议)。

*note pickle: cb. 模块不提供对持久化 ID 的解析工作，它将解析工作分配给用
户定义的方法，分别是 pickler 中的 *note persistent_id(): 1cc7. 方法和
unpickler 中的 *note persistent_load(): 1cc8. 方法。

要通过持久化 ID 将外部对象封存，必须在 pickler 中实现 *note
persistent_id(): 1cc7. 方法，该方法接受需要被封存的对象作为参数，返回一
个 ‘None’ 或返回该对象的持久化 ID。如果返回 ‘None’，该对象会被按照默认方
式封存为数据流。如果返回字符串形式的持久化 ID，则会封存这个字符串并加上
一个标记，这样 unpickler 才能将其识别为持久化 ID。

要解封外部对象，Unpickler 必须实现 *note persistent_load(): 1cc8. 方法，
接受一个持久化 ID 对象作为参数并返回一个引用的对象。

下面是一个全面的例子，展示了如何使用持久化 ID 来封存外部对象。

     # Simple example presenting how persistent ID can be used to pickle
     # external objects by reference.

     import pickle
     import sqlite3
     from collections import namedtuple

     # Simple class representing a record in our database.
     MemoRecord = namedtuple("MemoRecord", "key, task")

     class DBPickler(pickle.Pickler):

         def persistent_id(self, obj):
             # Instead of pickling MemoRecord as a regular class instance, we emit a
             # persistent ID.
             if isinstance(obj, MemoRecord):
                 # Here, our persistent ID is simply a tuple, containing a tag and a
                 # key, which refers to a specific record in the database.
                 return ("MemoRecord", obj.key)
             else:
                 # If obj does not have a persistent ID, return None. This means obj
                 # needs to be pickled as usual.
                 return None


     class DBUnpickler(pickle.Unpickler):

         def __init__(self, file, connection):
             super().__init__(file)
             self.connection = connection

         def persistent_load(self, pid):
             # This method is invoked whenever a persistent ID is encountered.
             # Here, pid is the tuple returned by DBPickler.
             cursor = self.connection.cursor()
             type_tag, key_id = pid
             if type_tag == "MemoRecord":
                 # Fetch the referenced record from the database and return it.
                 cursor.execute("SELECT * FROM memos WHERE key=?", (str(key_id),))
                 key, task = cursor.fetchone()
                 return MemoRecord(key, task)
             else:
                 # Always raises an error if you cannot return the correct object.
                 # Otherwise, the unpickler will think None is the object referenced
                 # by the persistent ID.
                 raise pickle.UnpicklingError("unsupported persistent object")


     def main():
         import io
         import pprint

         # Initialize and populate our database.
         conn = sqlite3.connect(":memory:")
         cursor = conn.cursor()
         cursor.execute("CREATE TABLE memos(key INTEGER PRIMARY KEY, task TEXT)")
         tasks = (
             'give food to fish',
             'prepare group meeting',
             'fight with a zebra',
             )
         for task in tasks:
             cursor.execute("INSERT INTO memos VALUES(NULL, ?)", (task,))

         # Fetch the records to be pickled.
         cursor.execute("SELECT * FROM memos")
         memos = [MemoRecord(key, task) for key, task in cursor]
         # Save the records using our custom DBPickler.
         file = io.BytesIO()
         DBPickler(file).dump(memos)

         print("Pickled records:")
         pprint.pprint(memos)

         # Update a record, just for good measure.
         cursor.execute("UPDATE memos SET task='learn italian' WHERE key=1")

         # Load the records from the pickle data stream.
         file.seek(0)
         memos = DBUnpickler(file, conn).load()

         print("Unpickled records:")
         pprint.pprint(memos)


     if __name__ == '__main__':
         main()

   ---------- Footnotes ----------

   (1) (5) 对字母数字类字符的限制是由于持久化 ID 在协议版本 0 中是由分行
符来分隔的。 因此如果持久化 ID 中出现任何形式的分行符，封存结果就将变得
无法读取。


File: python.info,  Node: Dispatch 表,  Next: 处理有状态的对象,  Prev: 持久化外部对象,  Up: 封存类实例

5.12.1.9 Dispatch 表
....................

如果想对某些类进行自定义封存，而又不想在类中增加用于封存的代码，就可以创
建带有特殊 dispatch 表的 pickler。

在 *note copyreg: 27. 模块的 ‘copyreg.dispatch_table’ 中定义了全局
dispatch 表。因此，可以使用 ‘copyreg.dispatch_table’ 修改后的副本作为自
有 dispatch 表。

例如

     f = io.BytesIO()
     p = pickle.Pickler(f)
     p.dispatch_table = copyreg.dispatch_table.copy()
     p.dispatch_table[SomeClass] = reduce_SomeClass

创建了一个带有自有 dispatch 表的 *note pickle.Pickler: 20e. 实例，它可以
对 ‘SomeClass’ 类进行特殊处理。另外，下列代码

     class MyPickler(pickle.Pickler):
         dispatch_table = copyreg.dispatch_table.copy()
         dispatch_table[SomeClass] = reduce_SomeClass
     f = io.BytesIO()
     p = MyPickler(f)

完成了相同的操作，但所有 ‘MyPickler’ 的实例都会共用同一份 dispatch 表。
使用 *note copyreg: 27. 模块实现的等效代码是

     copyreg.pickle(SomeClass, reduce_SomeClass)
     f = io.BytesIO()
     p = pickle.Pickler(f)


File: python.info,  Node: 处理有状态的对象,  Prev: Dispatch 表,  Up: 封存类实例

5.12.1.10 处理有状态的对象
..........................

下面的示例展示了如何修改类在封存时的行为。其中 ‘TextReader’ 类打开了一个
文本文件，每次调用其 ‘readline()’ 方法则返回行号和该行的字符。 在封存这
个 ‘TextReader’ 的实例时，`除了' 文件对象，其他属性都会被保存。 当解封实
例时，需要重新打开文件，然后从上次的位置开始继续读取。实现这些功能需要实
现 *note __setstate__(): 19d. 和 *note __getstate__(): e09. 方法。

     class TextReader:
         """Print and number lines in a text file."""

         def __init__(self, filename):
             self.filename = filename
             self.file = open(filename)
             self.lineno = 0

         def readline(self):
             self.lineno += 1
             line = self.file.readline()
             if not line:
                 return None
             if line.endswith('\n'):
                 line = line[:-1]
             return "%i: %s" % (self.lineno, line)

         def __getstate__(self):
             # Copy the object's state from self.__dict__ which contains
             # all our instance attributes. Always use the dict.copy()
             # method to avoid modifying the original state.
             state = self.__dict__.copy()
             # Remove the unpicklable entries.
             del state['file']
             return state

         def __setstate__(self, state):
             # Restore instance attributes (i.e., filename and lineno).
             self.__dict__.update(state)
             # Restore the previously opened file's state. To do so, we need to
             # reopen it and read from it until the line count is restored.
             file = open(self.filename)
             for _ in range(self.lineno):
                 file.readline()
             # Finally, save the file.
             self.file = file

使用方法如下所示：

     >>> reader = TextReader("hello.txt")
     >>> reader.readline()
     '1: Hello world!'
     >>> reader.readline()
     '2: I am line number two.'
     >>> new_reader = pickle.loads(pickle.dumps(reader))
     >>> new_reader.readline()
     '3: Goodbye!'


File: python.info,  Node: 类型，函数和其他对象的自定义归约,  Next: 外部缓冲区,  Prev: 封存类实例,  Up: pickle --- Python 对象序列化

5.12.1.11 类型，函数和其他对象的自定义归约
..........................................

3.8 新版功能.

有时，*note dispatch_table: a71. 可能不够灵活。 特别是当我们想要基于对象
类型以外的其他规则来对封存进行定制，或是当我们想要对函数和类的封存进行定
制的时候。

对于那些情况，可能要基于 *note Pickler: 20e. 类进行子类化并实现 *note
reducer_override(): 20f. 方法。 此方法可返回任意的归约元组 (参见 *note
__reduce__(): 19c.)。 它也可以选择返回 ‘NotImplemented’ 来回退到传统行为
。

如果同时定义了 *note dispatch_table: a71. 和 *note reducer_override():
20f.，则 *note reducer_override(): 20f. 方法具有优先权。

     注解: 出于性能理由，可能不会为以下对象调用 *note
     reducer_override(): 20f.: ‘None’, ‘True’, ‘False’, 以及 *note int:
     185, *note float: 188, *note bytes: 33a, *note str: 339, *note
     dict: 1b9, *note set: b77, *note frozenset: bf6, *note list: 263. 和
     *note tuple: 486. 的具体实例。

以下是一个简单的例子，其中我们允许封存并重新构建一个给定的类:

     import io
     import pickle

     class MyClass:
         my_attribute = 1

     class MyPickler(pickle.Pickler):
         def reducer_override(self, obj):
             """Custom reducer for MyClass."""
             if getattr(obj, "__name__", None) == "MyClass":
                 return type, (obj.__name__, obj.__bases__,
                               {'my_attribute': obj.my_attribute})
             else:
                 # For any other object, fallback to usual reduction
                 return NotImplemented

     f = io.BytesIO()
     p = MyPickler(f)
     p.dump(MyClass)

     del MyClass

     unpickled_class = pickle.loads(f.getvalue())

     assert isinstance(unpickled_class, type)
     assert unpickled_class.__name__ == "MyClass"
     assert unpickled_class.my_attribute == 1


File: python.info,  Node: 外部缓冲区,  Next: 限制全局变量,  Prev: 类型，函数和其他对象的自定义归约,  Up: pickle --- Python 对象序列化

5.12.1.12 外部缓冲区
....................

3.8 新版功能.

在某些场景中，*note pickle: cb. 模块会被用来传输海量的数据。 因此，最小
化内存复制次数以保证性能和节省资源是很重要的。 但是 *note pickle: cb. 模
块的正常运作会将图类对象结构转换为字节序列流，因此在本质上就要从封存流中
来回复制数据。

如果 `provider' (待传输对象类型的实现) 和 `consumer' (通信系统的实现) 都
支持 pickle 第 5 版或更高版本所提供的外部传输功能，则此约束可以被撤销。

* Menu:

* 提供方 API::
* 使用方 API::
* 示例: 示例<4>.


File: python.info,  Node: 提供方 API,  Next: 使用方 API,  Up: 外部缓冲区

5.12.1.13 提供方 API
....................

大的待封存数据对象必须实现协议 5 及以上版本专属的 *note __reduce_ex__():
1a0c. 方法，该方法将为任意大的数据返回一个 *note PickleBuffer: 1cc5. 实
例（而不是 *note bytes: 33a. 对象等）。

*note PickleBuffer: 1cc5. 对象会 `表明' 底层缓冲区可被用于外部数据传输。
那些对象仍将保持与 *note pickle: cb. 模块的正常用法兼容。 但是，使用方也
可以选择告知 *note pickle: cb. 它们将自行处理那些缓冲区。


File: python.info,  Node: 使用方 API,  Next: 示例<4>,  Prev: 提供方 API,  Up: 外部缓冲区

5.12.1.14 使用方 API
....................

当序列化一个对象图时，通信系统可以启用对所生成 *note PickleBuffer: 1cc5.
对象的定制处理。

发送端需要传递 `buffer_callback' 参数到 *note Pickler: 20e. (或是到
*note dump(): 1cbf. 或 *note dumps(): e07. 函数)，该回调函数将在封存对象
图时附带每个所生成的 *note PickleBuffer: 1cc5. 被调用。 由
`buffer_callback' 所累积的缓冲区的数据将不会被拷贝到 pickle 流，而是仅插
入一个简单的标记。

接收端需要传递 `buffers' 参数到 *note Unpickler: 1cbe. (或是到 *note
load(): 5cb. 或 *note loads(): 5cc. 函数)，其值是一个由缓冲区组成的可迭
代对象，它会被传递给 `buffer_callback'。 该可迭代对象应当按其被传递给
`buffer_callback' 时的顺序产生缓冲区。 这些缓冲区将提供对象重构造器所期
望的数据，对这些数据的封存产生了原本的 *note PickleBuffer: 1cc5. 对象。

在发送端和接受端之间，通信系统可以自由地实现它自己用于外部缓冲区的传输机
制。 潜在的优化包括使用共享内存或基于特定数据类型的压缩等。


File: python.info,  Node: 示例<4>,  Prev: 使用方 API,  Up: 外部缓冲区

5.12.1.15 示例
..............

下面是一个小例子，在其中我们实现了一个 *note bytearray: 33b. 的子类，能
够用于外部缓冲区封存:

     class ZeroCopyByteArray(bytearray):

         def __reduce_ex__(self, protocol):
             if protocol >= 5:
                 return type(self)._reconstruct, (PickleBuffer(self),), None
             else:
                 # PickleBuffer is forbidden with pickle protocols <= 4.
                 return type(self)._reconstruct, (bytearray(self),)

         @classmethod
         def _reconstruct(cls, obj):
             with memoryview(obj) as m:
                 # Get a handle over the original buffer object
                 obj = m.obj
                 if type(obj) is cls:
                     # Original buffer object is a ZeroCopyByteArray, return it
                     # as-is.
                     return obj
                 else:
                     return cls(obj)

重构造器 (‘_reconstruct’ 类方法) 会在缓冲区的提供对象具有正确类型时返回
该对象。 在此小示例中这是模拟零拷贝行为的便捷方式。

在使用方，我们可以按通常方式封存那些对象，它们在反序列化时将提供原始对象
的一个副本:

     b = ZeroCopyByteArray(b"abc")
     data = pickle.dumps(b, protocol=5)
     new_b = pickle.loads(data)
     print(b == new_b)  # True
     print(b is new_b)  # False: a copy was made

但是如果我们传入 `buffer_callback' 然后在反序列化时给回累积的缓冲区，我
们就能够取回原始对象:

     b = ZeroCopyByteArray(b"abc")
     buffers = []
     data = pickle.dumps(b, protocol=5, buffer_callback=buffers.append)
     new_b = pickle.loads(data, buffers=buffers)
     print(b == new_b)  # True
     print(b is new_b)  # True: no copy was made

这个例子受限于 *note bytearray: 33b. 会自行分配内存这一事实：你无法基于
另一个对象的内存创建 *note bytearray: 33b. 的实例。 但是，第三方数据类型
例如 NumPy 数组则没有这种限制，允许在单独进程或系统间传输时使用零拷贝的
封存（或是尽可能少地拷贝） 。

参见
....

PEP 574(1) – 带有外部数据缓冲区的 pickle 协议 5

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0574


File: python.info,  Node: 限制全局变量,  Next: 性能<2>,  Prev: 外部缓冲区,  Up: pickle --- Python 对象序列化

5.12.1.16 限制全局变量
......................

默认情况下，解封将会导入在 pickle 数据中找到的任何类或函数。 对于许多应
用来说，此行为是不可接受的，因为它会允许解封器导入并发起调用任意代码。 只
须考虑当这个手工构建的 pickle 数据流被加载时会做什么:

     >>> import pickle
     >>> pickle.loads(b"cos\nsystem\n(S'echo hello world'\ntR.")
     hello world
     0

在这个例子里，解封器导入 *note os.system(): dc9. 函数然后应用字符串参数
"echo hello world"。 虽然这个例子不具攻击性，但是不难想象别人能够通过此
方式对你的系统造成损害。

出于这样的理由，你可能会希望通过定制 *note Unpickler.find_class(): 1cd0.
来控制要解封的对象。 与其名称所提示的不同，*note Unpickler.find_class():
1cd0. 会在执行对任何全局对象（例如一个类或一个函数）的请求时被调用。 因
此可以完全禁止全局对象或是将它们限制在一个安全的子集中。

下面的例子是一个解封器，它只允许某一些安全的来自 *note builtins: 13. 模
块的类被加载:

     import builtins
     import io
     import pickle

     safe_builtins = {
         'range',
         'complex',
         'set',
         'frozenset',
         'slice',
     }

     class RestrictedUnpickler(pickle.Unpickler):

         def find_class(self, module, name):
             # Only allow safe classes from builtins.
             if module == "builtins" and name in safe_builtins:
                 return getattr(builtins, name)
             # Forbid everything else.
             raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
                                          (module, name))

     def restricted_loads(s):
         """Helper function analogous to pickle.loads()."""
         return RestrictedUnpickler(io.BytesIO(s)).load()

我们这个解封器的一个示例用法所达成的目标:

     >>> restricted_loads(pickle.dumps([1, 2, range(15)]))
     [1, 2, range(0, 15)]
     >>> restricted_loads(b"cos\nsystem\n(S'echo hello world'\ntR.")
     Traceback (most recent call last):
       ...
     pickle.UnpicklingError: global 'os.system' is forbidden
     >>> restricted_loads(b'cbuiltins\neval\n'
     ...                  b'(S\'getattr(__import__("os"), "system")'
     ...                  b'("echo hello world")\'\ntR.')
     Traceback (most recent call last):
       ...
     pickle.UnpicklingError: global 'builtins.eval' is forbidden

正如我们这个例子所显示的，对于允许解封的对象你必须要保持谨慎。 因此如果
要保证安全，你可以考虑其他选择例如 *note xmlrpc.client: 140. 中的编组
API 或是第三方解决方案。


File: python.info,  Node: 性能<2>,  Next: 例子<4>,  Prev: 限制全局变量,  Up: pickle --- Python 对象序列化

5.12.1.17 性能
..............

较新版本的 pickle 协议（第 2 版或更高）具有针对某些常见特性和内置类型的
高效二进制编码格式。 此外，*note pickle: cb. 模块还拥有一个以 C 编写的透
明优化器。


File: python.info,  Node: 例子<4>,  Prev: 性能<2>,  Up: pickle --- Python 对象序列化

5.12.1.18 例子
..............

对于最简单的代码，请使用 *note dump(): 1cbf. 和 *note load(): 5cb. 函数
。

     import pickle

     # An arbitrary collection of objects supported by pickle.
     data = {
         'a': [1, 2.0, 3, 4+6j],
         'b': ("character string", b"byte string"),
         'c': {None, True, False}
     }

     with open('data.pickle', 'wb') as f:
         # Pickle the 'data' dictionary using the highest protocol available.
         pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)

以下示例读取之前封存的数据。

     import pickle

     with open('data.pickle', 'rb') as f:
         # The protocol version used is detected automatically, so we do not
         # have to specify it.
         data = pickle.load(f)

参见
....

模块 *note copyreg: 27.

     为扩展类型提供 pickle 接口所需的构造函数。

模块 *note pickletools: cc.

     用于处理和分析已封存数据的工具。

模块 *note shelve: e8.

     带索引的数据库，用于存放对象，使用了 *note pickle: cb. 模块。

模块 *note copy: 26.

     浅层 (shallow) 和深层 (deep) 复制对象操作

模块 *note marshal: b1.

     高效地序列化内置类型的数据。

备注
....


File: python.info,  Node: copyreg --- 注册配合 pickle 模块使用的函数,  Next: shelve --- Python 对象持久化,  Prev: pickle --- Python 对象序列化,  Up: 数据持久化

5.12.2 ‘copyreg’ — 注册配合 ‘pickle’ 模块使用的函数
---------------------------------------------------

`源代码:' Lib/copyreg.py(1)

__________________________________________________________________

*note copyreg: 27. 模块提供了可在封存特定对象时使用的一种定义函数方式。
*note pickle: cb. 和 *note copy: 26. 模块会在封存/拷贝特定对象时使用这些
函数。 此模块提供了非类对象构造器的相关配置信息。 这样的构造器可以是工厂
函数或类实例。

 -- 函数: copyreg.constructor (object)

     将 `object' 声明为一个有效的构造器。 如果 `object' 是不可调用的（因
     而不是一个有效的构造器）则会引发 *note TypeError: 193.。

 -- 函数: copyreg.pickle (type, function, constructor=None)

     声明该 `function' 应当被用作 `type' 类型对象的“归约函数”。
     `function' 应当返回字符串或包含两到三个元素的元组。

     如果提供了可选的 `constructor' 形参，它应当是一个可用来重建相应对象
     的可调用对象，在调用该对象时应传入由 `function' 所返回的参数元组。
     如果 `object' 是一个类或 `constructor' 是不可调用的则将引发 *note
     TypeError: 193.。

     请查看 *note pickle: cb. 模块了解 `function' 和 `constructor' 所要
     求的接口的详情。 请注意一个 pickler 对象或 *note pickle.Pickler:
     20e. 的子类的 *note dispatch_table: a71. 属性也可以被用来声明归约函
     数。

* Menu:

* 示例: 示例<5>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/copyreg.py


File: python.info,  Node: 示例<5>,  Up: copyreg --- 注册配合 pickle 模块使用的函数

5.12.2.1 示例
.............

以下示例将会显示如何注册一个封存函数，以及如何来使用它：

     >>> import copyreg, copy, pickle
     >>> class C(object):
     ...     def __init__(self, a):
     ...         self.a = a
     ...
     >>> def pickle_c(c):
     ...     print("pickling a C instance...")
     ...     return C, (c.a,)
     ...
     >>> copyreg.pickle(C, pickle_c)
     >>> c = C(1)
     >>> d = copy.copy(c)
     pickling a C instance...
     >>> p = pickle.dumps(c)
     pickling a C instance...


File: python.info,  Node: shelve --- Python 对象持久化,  Next: marshal --- 内部 Python 对象序列化,  Prev: copyreg --- 注册配合 pickle 模块使用的函数,  Up: 数据持久化

5.12.3 ‘shelve’ — Python 对象持久化
-----------------------------------

`源代码:' Lib/shelve.py(1)

__________________________________________________________________

"Shelf" 是一种持久化的类似字典的对象。 与 "dbm" 数据库的区别在于 Shelf 中
的值（不是键！）实际上可以为任意 Python 对象 — 即 *note pickle: cb. 模块
能够处理的任何东西。 这包括大部分类实例、递归数据类型，以及包含大量共享
子对象的对象。 键则为普通的字符串。

 -- 函数: shelve.open (filename, flag='c', protocol=None,
          writeback=False)

     打开一个持久化字典。 filename 指定下层数据库的基准文件名。 作为附带
     效果，会为 filename 添加一个扩展名并且可能创建更多的文件。 默认情况
     下，下层数据库会以读写模式打开。 可选的 `flag' 形参具有与 *note
     dbm.open(): 839. `flag' 形参相同的含义。

     默认会使用第 3 版 pickle 协议来序列化值。 pickle 协议版本可通过
     `protocol' 形参来指定。

     由于 Python 语义的限制，Shelf 对象无法确定一个可变的持久化字典条目
     在何时被修改。 默认情况下 `只有' 在被修改对象再赋值给 shelf 时才会
     写入该对象 (参见 *note 示例: 1ceb.)。 如果可选的 `writeback' 形参设
     为 ‘True’，则所有被访问的条目都将在内存中被缓存，并会在 *note
     sync(): 1cec. 和 *note close(): 1ced. 时被写入；这可以使得对持久化
     字典中可变条目的修改更方便，但是如果访问的条目很多，这会消耗大量内
     存作为缓存，并会使得关闭操作变得非常缓慢，因为所有被访问的条目都需
     要写回到字典（无法确定被访问的条目中哪个是可变的，也无法确定哪个被
     实际修改了）。

          注解: 请不要依赖于 Shelf 的自动关闭功能；当你不再需要时应当总
          是显式地调用 *note close(): 1ced.，或者使用 *note
          shelve.open(): 1cea. 作为上下文管理器:

               with shelve.open('spam') as db:
                   db['eggs'] = 'eggs'

     警告: 由于 *note shelve: e8. 模块需要 *note pickle: cb. 的支持，因
     此从不可靠的来源载入 shelf 是不安全的。 与 pickle 一样，载入 Shelf
     时可以执行任意代码。

字典所支持的所有方法都被 Shelf 对象所支持。 因此很容易将基于字典的代码转
换为需要持久化存储的代码。

额外支持的两个方法：

 -- 方法: Shelf.sync ()

     如果 Shelf 打开时将 `writeback' 设为 *note True: 4a1. 则写回缓存中
     的所有条目。 如果可行还会清空缓存并将持久化字典同步到磁盘。 此方法
     会在使用 *note close(): 1ced. 关闭 Shelf 时自动被调用。

 -- 方法: Shelf.close ()

     同步并关闭持久化 `dict' 对象。 对已关闭 Shelf 的操作将失败并引发
     *note ValueError: 1fc.。

参见
....

持久化字典方案(2)，使用了广泛支持的存储格式并具有原生字典的速度。

* Menu:

* 限制::
* 示例: 示例<6>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/shelve.py

   (2) https://code.activestate.com/recipes/576642/


File: python.info,  Node: 限制,  Next: 示例<6>,  Up: shelve --- Python 对象持久化

5.12.3.1 限制
.............

   * 可选择使用哪种数据库包 (例如 *note dbm.ndbm: 35. 或 *note dbm.gnu:
     34.) 取决于支持哪种接口。 因此使用 *note dbm: 32. 直接打开数据库是
     不安全的。 如果使用了 *note dbm: 32.，数据库同样会（不幸地）受限于
     它 — 这意味着存储在数据库中的（封存形式的）对象尺寸应当较小，并且在
     少数情况下键冲突有可能导致数据库拒绝更新。

   * *note shelve: e8. 模块不支持对 Shelf 对象的 `并发' 读/写访问。 （多
     个同时读取访问则是安全的。） 当一个程序打开一个 shelve 对象来写入时
     ，不应再有其他程序同时打开它来读取或写入。 Unix 文件锁定可被用来解
     决此问题，但这在不同 Unix 版本上会存在差异，并且需要有关所用数据库
     实现的细节知识。

 -- 类: shelve.Shelf (dict, protocol=None, writeback=False,
          keyencoding='utf-8')

     *note collections.abc.MutableMapping: 9f7. 的一个子类，它会将封存的
     值保存在 `dict' 对象中。

     默认会使用第 3 版 pickle 协议来序列化值。 pickle 协议版本可通过
     `protocol' 形参来指定。 请参阅 *note pickle: cb. 文档来查看 pickle
     协议的相关讨论。

     如果 `writeback' 形参为 ‘True’，对象将为所有访问过的条目保留缓存并
     在同步和关闭时将它们写回到 `dict'。 这允许对可变的条目执行自然操作
     ，但是会消耗更多内存并让同步和关闭花费更长时间。

     `keyencoding' 形参是在下层字典被使用之前用于编码键的编码格式。

     *note Shelf: 8b9. 对象还可以被用作上下文管理器，在这种情况下它将在
     *note with: 6f2. 语句块结束时自动被关闭。

     在 3.2 版更改: 添加了 `keyencoding' 形参；之前，键总是使用 UTF-8 编
     码。

     在 3.4 版更改: 添加了上下文管理器支持。

 -- 类: shelve.BsdDbShelf (dict, protocol=None, writeback=False,
          keyencoding='utf-8')

     *note Shelf: 8b9. 的一个子类，将 ‘first()’, ‘next()’, ‘previous()’,
     ‘last()’ 和 ‘set_location()’ 对外公开，在来自 pybsddb(1) 的第三方
     ‘bsddb’ 模块中可用，但在其他数据库模块中不可用。 传给构造器的
     `dict' 对象必须支持这些方法。 这通常是通过调用 ‘bsddb.hashopen()’,
     ‘bsddb.btopen()’ 或 ‘bsddb.rnopen()’ 之一来完成的。 可选的
     `protocol', `writeback' 和 `keyencoding' 形参具有与 *note Shelf:
     8b9. 类相同的含义。

 -- 类: shelve.DbfilenameShelf (filename, flag='c', protocol=None,
          writeback=False)

     *note Shelf: 8b9. 的一个子类，它接受一个 `filename' 而非字典类对象
     。 下层文件将使用 *note dbm.open(): 839. 来打开。 默认情况下，文件
     将以读写模式打开。 可选的 `flag' 形参具有与 *note open(): 1cea. 函
     数相同的含义。 可选的 `protocol' 和 `writeback' 形参具有与 *note
     Shelf: 8b9. 类相同的含义。

   ---------- Footnotes ----------

   (1) https://www.jcea.es/programacion/pybsddb.htm


File: python.info,  Node: 示例<6>,  Prev: 限制,  Up: shelve --- Python 对象持久化

5.12.3.2 示例
.............

对接口的总结如下 (‘key’ 为字符串，‘data’ 为任意对象):

     import shelve

     d = shelve.open(filename)  # open -- file may get suffix added by low-level
                                # library

     d[key] = data              # store data at key (overwrites old data if
                                # using an existing key)
     data = d[key]              # retrieve a COPY of data at key (raise KeyError
                                # if no such key)
     del d[key]                 # delete data stored at key (raises KeyError
                                # if no such key)

     flag = key in d            # true if the key exists
     klist = list(d.keys())     # a list of all existing keys (slow!)

     # as d was opened WITHOUT writeback=True, beware:
     d['xx'] = [0, 1, 2]        # this works as expected, but...
     d['xx'].append(3)          # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!

     # having opened d without writeback=True, you need to code carefully:
     temp = d['xx']             # extracts the copy
     temp.append(5)             # mutates the copy
     d['xx'] = temp             # stores the copy right back, to persist it

     # or, d=shelve.open(filename,writeback=True) would let you just code
     # d['xx'].append(5) and have it work as expected, BUT it would also
     # consume more memory and make the d.close() operation slower.

     d.close()                  # close it

参见
....

模块 *note dbm: 32.

     ‘dbm’ 风格数据库的泛型接口。

模块 *note pickle: cb.

     *note shelve: e8. 所使用的对象序列化。


File: python.info,  Node: marshal --- 内部 Python 对象序列化,  Next: dbm --- Unix "数据库" 接口,  Prev: shelve --- Python 对象持久化,  Up: 数据持久化

5.12.4 ‘marshal’ — 内部 Python 对象序列化
-----------------------------------------

__________________________________________________________________

此模块包含一此能以二进制格式来读写 Python 值的函数。 这种格式是 Python 专
属的，但是独立于特定的机器架构（即你可以在一台 PC 上写入某个 Python 值，
将文件传到一台 Sun 上并在那里读取它）。 这种格式的细节有意不带文档说明；
它可能在不同 Python 版本中发生改变（但这种情况极少发生）。 (1)

这不是一个通用的“持久化”模块。 对于通用的持久化以及通过 RPC 调用传递
Python 对象，请参阅 *note pickle: cb. 和 *note shelve: e8. 等模块。
*note marshal: b1. 模块主要是为了支持读写 ‘.pyc’ 文件形式“伪编译”代码的
Python 模块。 因此，Python 维护者保留在必要时以不向下兼容的方式修改
marshal 格式的权利。 如果你要序列化和反序列化 Python 对象，请改用 *note
pickle: cb. 模块 – 其执行效率相当，版本独立性有保证，并且 pickle 还支持
比 marshal 更多样的对象类型。

     警告: *note marshal: b1. 模块对于错误或恶意构建的数据来说是不安全的
     。 永远不要 unmarshal 来自不受信任的或未经验证的来源的数据。

不是所有 Python 对象类型都受支持；一般来说，此模块只能写入和读取不依赖于
特定 Python 调用的对象。 下列类型是受支持的：布尔值、整数、浮点数、复数
、字符串、字节串、字节数组、元组、列表、集合、冻结集合、字典和代码对象，
需要了解的一点是元组、列表、集合、冻结集合和字典只在其所包含的值也是这些
值时才受支持。 单例对象 *note None: 158, *note Ellipsis: 161c. and *note
StopIteration: 48e. 也可以被 marshal 和 unmarshal。 对于 `version' 低于
3 的格式，递归列表、集合和字典无法被写入（见下文）。

有些函数可以读/写文件，还有些函数可以操作字节类对象。

这个模块定义了以下函数：

 -- 函数: marshal.dump (value, file[, version])

     向打开的文件写入值。 值必须为受支持的类型。 文件必须为可写的 *note
     binary file: 1cb4.。

     如果值具有（或所包含的对象具有）不受支持的类型，则会引发 *note
     ValueError: 1fc. — 但是将向文件写入垃圾数据。 对象也将不能正确地通
     过 *note load(): 1000. 重新读取。

     `version' 参数指明 ‘dump’ 应当使用的数据格式（见下文）。

 -- 函数: marshal.load (file)

     从打开的文件读取一个值并返回。 如果读不到有效的值（例如由于数据为不
     同 Python 版本的不兼容 marshal 格式），则会引发 *note EOFError:
     c74, *note ValueError: 1fc. 或 *note TypeError: 193.。 文件必须为可
     读的 *note binary file: 1cb4.。

          注解: 如果通过 *note dump(): 1cf4. marshal 了一个包含不受支持
          类型的对象，*note load(): 1000. 将为不可 marshal 的类型替换
          ‘None’。

 -- 函数: marshal.dumps (value[, version])

     返回将通过 ‘dump(value, file)’ 被写入一个文件的字节串对象。 值必须
     属于受支持的类型。 如果值属于（或包含的对象属于）不受支持的类型则会
     引发 *note ValueError: 1fc.。

     `version' 参数指明 ‘dumps’ 应当使用的数据类型（见下文）。

 -- 函数: marshal.loads (bytes)

     将 *note bytes-like object: 5f1. 转换为一个值。 如果找不到有效的值
     ，则会引发 *note EOFError: c74, *note ValueError: 1fc. 或 *note
     TypeError: 193.。 输入的额外字节串会被忽略。

此外，还定义了以下常量：

 -- 数据: marshal.version

     指明模块所使用的格式。 第 0 版为历史格式，第 1 版为共享固化的字符串
     ，第 2 版对浮点数使用二进制格式。 第 3 版添加了对于对象实例化和递归
     的支持。 目前使用的为第 4 版。

备注
....

   ---------- Footnotes ----------

   (1) (1) 此模块的名称来源于 Modula-3 (及其他语言) 的设计者所使用的术语
，他们使用术语 "marshal" 来表示以自包含的形式传输数据。 严格地说，将数据
从内部形式转换为外部形式 (例如用于 RPC 缓冲区) 称为 "marshal" 而其逆过程
则称为 "unmarshal"。


File: python.info,  Node: dbm --- Unix "数据库" 接口,  Next: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块,  Prev: marshal --- 内部 Python 对象序列化,  Up: 数据持久化

5.12.5 ‘dbm’ — Unix "数据库" 接口
---------------------------------

`源代码:' Lib/dbm/__init__.py(1)

__________________________________________________________________

*note dbm: 32. 是一种泛用接口，针对各种 DBM 数据库 — 包括 *note dbm.gnu:
34. 或 *note dbm.ndbm: 35.。 如果未安装这些模块中的任何一种，则将使用
*note dbm.dumb: 33. 模块中慢速但简单的实现。 还有一个适用于 Oracle
Berkeley DB 的 第三方接口(2)。

 -- 例外: dbm.error

     一个元组，其中包含每个受支持的模块可引发的异常，另外还有一个名为
     *note dbm.error: 1cf9. 的特殊异常作为第一项 — 后者最在引发 *note
     dbm.error: 1cf9. 时被使用。

 -- 函数: dbm.whichdb (filename)

     此函数会猜测各种简单数据库模块中的哪一个是可用的 — *note dbm.gnu:
     34, *note dbm.ndbm: 35. 还是 *note dbm.dumb: 33. — 应该被用来打开给
     定的文件。

     返回下列值中的一个：如果文件由于不可读或不存在而无法打开则返回
     ‘None’；如果文件的格式无法猜测则返回空字符串 (‘''’)；或是包含所需模
     块名称的字符串，例如 ‘'dbm.ndbm'’ 或 ‘'dbm.gnu'’。

 -- 函数: dbm.open (file, flag='r', mode=0o666)

     打开数据库文件 `file' 并返回一个相应的对象。

     如果数据库文件已存在，则使用 *note whichdb(): 1cfa. 函数来确定其类
     型和要使用的适当模块；如果文件不存在，则会使用上述可导入模块中的第
     一个。

     可选的 `flag' 参数可以是：

     值            含义
                   
     --------------------------------------------------------------
                   
     ‘'r'’         以只读方式打开现有数据库（默认）
                   
                   
     ‘'w'’         以读写方式打开现有数据库
                   
                   
     ‘'c'’         以读写方式打开数据库，如果不存在则创建它
                   
                   
     ‘'n'’         始终创建一个新的空数据库，以读写方式打开
                   

     可选的 `mode' 参数是文件的 Unix 模式，仅在要创建数据库时才会被使用
     。 其默认值为八进制数 ‘0o666’ (并将被当前的 umask 所修改)。

*note open(): 839. 所返回的对象支持与字典相同的基本功能；可以存储、获取
和删除键及其对应的值，并可使用 *note in: 7ac. 运算符和 ‘keys()’ 方法，以
及 ‘get()’ 和 ‘setdefault()’。

在 3.2 版更改: 现在 ‘get()’ 和 ‘setdefault()’ 在所有数据库模块中均可用。

在 3.8 版更改: 从只读数据库中删除键将引发数据库模块专属的错误而不是
*note KeyError: 2c8.。

键和值总是被存储为字节串。 这意味着当使用字符串时它们会在被存储之前隐式
地转换至默认编码格式。

这些对象也支持在 *note with: 6f2. 语句中使用，当语句结束时将自动关闭它们
。

在 3.4 版更改: 向 *note open(): 839. 所返回的对象添加了上下文管理协议的
原生支持。

以下示例记录了一些主机名和对应的标题，随后将数据库的内容打印出来。:

     import dbm

     # Open database, creating it if necessary.
     with dbm.open('cache', 'c') as db:

         # Record some values
         db[b'hello'] = b'there'
         db['www.python.org'] = 'Python Website'
         db['www.cnn.com'] = 'Cable News Network'

         # Note that the keys are considered bytes now.
         assert db[b'www.python.org'] == b'Python Website'
         # Notice how the value is now in bytes.
         assert db['www.cnn.com'] == b'Cable News Network'

         # Often-used methods of the dict interface work too.
         print(db.get('python.org', b'not present'))

         # Storing a non-string key or value will raise an exception (most
         # likely a TypeError).
         db['www.yahoo.com'] = 4

     # db is automatically closed when leaving the with statement.

参见
....

模块 *note shelve: e8.

     存储非字符串数据的持久化模块。

以下部分描述了各个单独的子模块。

* Menu:

* dbm.gnu: dbm gnu --- GNU 对 dbm 的重解析. GNU 对 dbm 的重解析
* dbm.ndbm: dbm ndbm --- 基于 ndbm 的接口. 基于 ndbm 的接口
* dbm.dumb: dbm dumb --- 便携式 DBM 实现. 便携式 DBM 实现

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/dbm/__init__.py

   (2) https://www.jcea.es/programacion/pybsddb.htm


File: python.info,  Node: dbm gnu --- GNU 对 dbm 的重解析,  Next: dbm ndbm --- 基于 ndbm 的接口,  Up: dbm --- Unix "数据库" 接口

5.12.5.1 ‘dbm.gnu’ — GNU 对 dbm 的重解析
........................................

`源代码:' Lib/dbm/gnu.py(1)

__________________________________________________________________

此模块与 *note dbm: 32. 模块很相似，但是改用 GNU 库 ‘gdbm’ 来提供某些附
加功能。 请注意由 *note dbm.gnu: 34. 与 *note dbm.ndbm: 35. 所创建的文件
格式是不兼容的。

*note dbm.gnu: 34. 模块提供了对 GNU DBM 库的接口。 ‘dbm.gnu.gdbm’ 对象的
行为类似于映射（字典），区别在于其键和值总是会在存储之前被转换为字节串。
打印 ‘gdbm’ 对象不会打印出键和值，并且 ‘items()’ 和 ‘values()’ 等方法也
不受支持。

 -- 例外: dbm.gnu.error

     针对 *note dbm.gnu: 34. 专属错误例如 I/O 错误引发。 *note KeyError:
     2c8. 的引发则针对一般映射错误例如指定了不正确的键。

 -- 函数: dbm.gnu.open (filename[, flag[, mode]])

     打开一个 ‘gdbm’ 数据库并返回 ‘gdbm’ 对象。 `filename' 参数为数据库
     文件名称。

     可选的 `flag' 参数可以是：

     值            含义
                   
     --------------------------------------------------------------
                   
     ‘'r'’         以只读方式打开现有数据库（默认）
                   
                   
     ‘'w'’         以读写方式打开现有数据库
                   
                   
     ‘'c'’         以读写方式打开数据库，如果不存在则创建它
                   
                   
     ‘'n'’         始终创建一个新的空数据库，以读写方式打开
                   

     下列附加字符可被添加至旗标以控制数据库的打开方式：

     值            含义
                   
     ---------------------------------------------------------------
                   
     ‘'f'’         以快速模式打开数据库。写入数据库将不会同步。
                   
                   
     ‘'s'’         同步模式。这将导致数据库的更改立即写入文件。
                   
                   
     ‘'u'’         不要锁定数据库。
                   

     不是所有旗标都可用于所有版本的 ‘gdbm’。 模块常量 ‘open_flags’ 为包
     含受支持旗标字符的字符串。 如果指定了无效的旗标则会引发 *note
     error: 2c6.。

     可选的 `mode' 参数是文件的 Unix 模式，仅在要创建数据库时才会被使用
     。 其默认值为八进制数 ‘0o666’。

     除了与字典类似的方法，‘gdbm’ 对象还有以下方法：

      -- 方法: gdbm.firstkey ()

          使用此方法和 *note nextkey(): 1cfd. 方法可以循环遍历数据库中的
          每个键。 遍历的顺序是按照 ‘gdbm’ 的内部哈希值，而不会根据键的
          值排序。 此方法将返回起始键。

      -- 方法: gdbm.nextkey (key)

          在遍历中返回 `key' 之后的的下一个键。 以下代码将打印数据库
          ‘db’ 中的每个键，而不会在内存中创建一个包含所有键的列表:

               k = db.firstkey()
               while k != None:
                   print(k)
                   k = db.nextkey(k)

      -- 方法: gdbm.reorganize ()

          如果你进行了大量删除操作并且想要缩减 ‘gdbm’ 文件所使用的空间，
          此例程将可重新组织数据库。 除非使用此重组功能否则 ‘gdbm’ 对象
          不会缩减数据库文件大小；在其他情况下，被删除的文件空间将会保留
          并在添加新的 (键, 值) 对时被重用。

      -- 方法: gdbm.sync ()

          当以快速模式打开数据库时，此方法会将任何未写入数据强制写入磁盘
          。

      -- 方法: gdbm.close ()

          关闭 ‘gdbm’ 数据库。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/dbm/gnu.py


File: python.info,  Node: dbm ndbm --- 基于 ndbm 的接口,  Next: dbm dumb --- 便携式 DBM 实现,  Prev: dbm gnu --- GNU 对 dbm 的重解析,  Up: dbm --- Unix "数据库" 接口

5.12.5.2 ‘dbm.ndbm’ — 基于 ndbm 的接口
......................................

`源代码:' Lib/dbm/ndbm.py(1)

__________________________________________________________________

*note dbm.ndbm: 35. 模块提供了对 Unix "(n)dbm" 库的接口。 Dbm 对象的行为
类似于映射（字典），区别在于其键和值总是被存储为字节串。 打印 ‘dbm’ 对象
不会打印出键和值，并且 ‘items()’ 和 ‘values()’ 等方法也不受支持。

此模块可与 "经典classic" ndbm 接口或 GNU GDBM 兼容接口一同使用。 在 Unix
上，‘configure’ 脚本将尝试定位适当的头文件来简化此模块的构建。

 -- 例外: dbm.ndbm.error

     针对 *note dbm.ndbm: 35. 专属错误例如 I/O 错误引发。 *note
     KeyError: 2c8. 的引发则针对一般映射错误例如指定了不正确的键。

 -- 数据: dbm.ndbm.library

     所使用的 ‘ndbm’ 实现库的名称。

 -- 函数: dbm.ndbm.open (filename[, flag[, mode]])

     打开一个 dbm 数据库并返回 ‘ndbm’ 对象。 `filename' 参数为数据库文件
     名称（不带 ‘.dir’ 或 ‘.pag’ 扩展名）。

     可选的 `flag' 参数必须是下列值之一：

     值            含义
                   
     --------------------------------------------------------------
                   
     ‘'r'’         以只读方式打开现有数据库（默认）
                   
                   
     ‘'w'’         以读写方式打开现有数据库
                   
                   
     ‘'c'’         以读写方式打开数据库，如果不存在则创建它
                   
                   
     ‘'n'’         始终创建一个新的空数据库，以读写方式打开
                   

     可选的 `mode' 参数是文件的 Unix 模式，仅在要创建数据库时才会被使用
     。 其默认值为八进制数 ‘0o666’ (并将被当前的 umask 所修改)。

     除了与字典类似的方法，‘ndbm’ 对象还有以下方法：

      -- 方法: ndbm.close ()

          关闭 ‘ndbm’ 数据库。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/dbm/ndbm.py


File: python.info,  Node: dbm dumb --- 便携式 DBM 实现,  Prev: dbm ndbm --- 基于 ndbm 的接口,  Up: dbm --- Unix "数据库" 接口

5.12.5.3 ‘dbm.dumb’ — 便携式 DBM 实现
.....................................

`源代码:' Lib/dbm/dumb.py(1)

     注解: *note dbm.dumb: 33. 模块的目的是在更健壮的模块不可用时作为
     *note dbm: 32. 模块的最终回退项。 *note dbm.dumb: 33. 不是为高速运
     行而编写的，也不像其他数据库模块一样被经常使用。

__________________________________________________________________

*note dbm.dumb: 33. 模块提供了一个完全以 Python 编写的持久化字典类接口。
不同于 *note dbm.gnu: 34. 等其他模块，它不需要外部库。 与其他持久化映射
一样，它的键和值也总是被存储为字节串。

该模块定义以下内容：

 -- 例外: dbm.dumb.error

     针对 *note dbm.dumb: 33. 专属错误例如 I/O 错误引发。 *note
     KeyError: 2c8. 的引发则针对一般映射例如指定了不正确的键。

 -- 函数: dbm.dumb.open (filename[, flag[, mode]])

     打开一个 ‘dumbdbm’ 数据库并返回 dumbdbm 对象。 `filename' 参数为数
     据库文件的主名称（不带任何特定扩展名）。 创建一个 dumbdbm 数据库时
     将创建多个带有 ‘.dat’ 和 ‘.dir’ 扩展名的文件。

     可选的 `flag' 参数可以是：

     值            含义
                   
     --------------------------------------------------------------
                   
     ‘'r'’         以只读方式打开现有数据库（默认）
                   
                   
     ‘'w'’         以读写方式打开现有数据库
                   
                   
     ‘'c'’         以读写方式打开数据库，如果不存在则创建它
                   
                   
     ‘'n'’         始终创建一个新的空数据库，以读写方式打开
                   

     可选的 `mode' 参数是文件的 Unix 模式，仅在要创建数据库时才会被使用
     。 其默认值为八进制数 ‘0o666’ (并将被当前的 umask 所修改)。

          警告: 当载入包含足够巨大/复杂条目的数据库时有可能导致 Python 解
          释器的崩溃，这是由于 Python AST 编译器有栈深度限制。

     在 3.5 版更改: *note open(): 2c0. 在 flag 值为 ‘'n'’ 时将总是创建一
     个新的数据库。

     在 3.8 版更改: 附带 ‘'r'’ 旗标打开的数据库现在将是只读的。 附带
     ‘'r'’ 和 ‘'w'’ 旗标的打开操作不会再创建数据库。

     除了 *note collections.abc.MutableMapping: 9f7. 类所提供的方法，
     ‘dumbdbm’ 对象还提供了以下方法：

      -- 方法: dumbdbm.sync ()

          同步磁盘上的目录和数据文件。 此方法会由 ‘Shelve.sync()’ 方法来
          调用。

      -- 方法: dumbdbm.close ()

          关闭 ‘dumbdbm’ 数据库。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/dbm/dumb.py


File: python.info,  Node: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块,  Prev: dbm --- Unix "数据库" 接口,  Up: 数据持久化

5.12.6 ‘sqlite3’ — SQLite 数据库 DB-API 2.0 接口模块
----------------------------------------------------

`源代码：' Lib/sqlite3/(1)

__________________________________________________________________

SQLite 是一个C语言库，它可以提供一种轻量级的基于磁盘的数据库，这种数据库
不需要独立的服务器进程，也允许需要使用一种非标准的 SQL 查询语言来访问它
。一些应用程序可以使用 SQLite 作为内部数据存储。可以用它来创建一个应用程
序原型，然后再迁移到更大的数据库，比如 PostgreSQL 或 Oracle。

sqlite3 模块由 Gerhard Häring 编写。它提供了符合 DB-API 2.0 规范的接口，
这个规范是 PEP 249(2)。

要使用这个模块，必须先创建一个 *note Connection: 3e0. 对象，它代表数据库
。下面例子中，数据将存储在 ‘example.db’ 文件中：

     import sqlite3
     con = sqlite3.connect('example.db')

你也可以使用 ‘:memory:’ 来创建一个内存中的数据库

当有了 *note Connection: 3e0. 对象后，你可以创建一个 *note Cursor: 1d09.
游标对象，然后调用它的 *note execute(): 1d0a. 方法来执行 SQL 语句：

     cur = con.cursor()

     # Create table
     cur.execute('''CREATE TABLE stocks
                    (date text, trans text, symbol text, qty real, price real)''')

     # Insert a row of data
     cur.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

     # Save (commit) the changes
     con.commit()

     # We can also close the connection if we are done with it.
     # Just be sure any changes have been committed or they will be lost.
     con.close()

这些数据被持久化保存了，而且可以在之后的会话中使用它们：

     import sqlite3
     con = sqlite3.connect('example.db')
     cur = con.cursor()

通常你的 SQL 操作需要使用一些 Python 变量的值。你不应该使用 Python 的字
符串操作来创建你的查询语句，因为那样做不安全；它会使你的程序容易受到 SQL
注入攻击（在 ‘https://xkcd.com/327/’ 上有一个搞笑的例子，看看有什么后果
）

推荐另外一种方法：使用 DB-API 的参数替换。在你的 SQL 语句中，使用 ‘?’ 占
位符来代替值，然后把对应的值组成的元组做为 *note execute(): 1d0a. 方法的
第二个参数。（其他数据库可能会使用不同的占位符，比如 ‘%s’ 或者 ‘:1’）例
如：

     # Never do this -- insecure!
     symbol = 'RHAT'
     cur.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

     # Do this instead
     t = ('RHAT',)
     cur.execute('SELECT * FROM stocks WHERE symbol=?', t)
     print(cur.fetchone())

     # Larger example that inserts many records at a time
     purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
                  ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
                  ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
                 ]
     cur.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)

要在执行 SELECT 语句后获取数据，你可以把游标作为 *note iterator: 104b.，
然后调用它的 *note fetchone(): 1d0b. 方法来获取一条匹配的行，也可以调用
*note fetchall(): 1d0c. 来得到包含多个匹配行的列表。

下面是一个使用迭代器形式的例子：

     >>> for row in cur.execute('SELECT * FROM stocks ORDER BY price'):
             print(row)

     ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
     ('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
     ('2006-04-06', 'SELL', 'IBM', 500, 53.0)
     ('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)

参见
....

‘https://www.sqlite.org’

     SQLite的主页；它的文档详细描述了它所支持的 SQL 方言的语法和可用的数
     据类型。

‘https://www.w3schools.com/sql/’

     学习 SQL 语法的教程、参考和例子。

PEP 249(3) - DB-API 2.0 规范

     PEP 由 Marc-André Lemburg 撰写。

* Menu:

* 模块函数和常量::
* 连接对象（Connection）::
* Cursor 对象::
* 行对象::
* 异常: 异常<4>.
* SQLite 与 Python 类型::
* 控制事务::
* 有效使用 sqlite3::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/sqlite3/

   (2) https://www.python.org/dev/peps/pep-0249

   (3) https://www.python.org/dev/peps/pep-0249


File: python.info,  Node: 模块函数和常量,  Next: 连接对象（Connection）,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.1 模块函数和常量
.......................

 -- 数据: sqlite3.version

     这个模块的版本号，是一个字符串。不是 SQLite 库的版本号。

 -- 数据: sqlite3.version_info

     这个模块的版本号，是一个由整数组成的元组。不是 SQLite 库的版本号。

 -- 数据: sqlite3.sqlite_version

     使用中的 SQLite 库的版本号，是一个字符串。

 -- 数据: sqlite3.sqlite_version_info

     使用中的 SQLite 库的版本号，是一个整数组成的元组。

 -- 数据: sqlite3.PARSE_DECLTYPES

     这个常量可以作为 *note connect(): 3e2. 函数的 `detect_types' 参数。

     设置这个参数后，*note sqlite3: f3. 模块将解析它返回的每一列申明的类
     型。它会申明的类型的第一个单词，比如“integer primary key”，它会解析
     出“integer”，再比如“number(10)”，它会解析出“number”。然后，它会在转
     换器字典里查找那个类型注册的转换器函数，并调用它。

 -- 数据: sqlite3.PARSE_COLNAMES

     这个常量可以作为 *note connect(): 3e2. 函数的 `detect_types' 参数。

     设置此参数可使得 SQLite 接口解析它所返回的每一列的列名。 它将在其中
     查找形式为 [mytype] 的字符串，然后将 ’mytype’ 确定为列的类型。 它将
     尝试在转换器字典中查找 ’mytype’ 条目，然后用找到的转换器函数来返回
     值。 在 *note Cursor.description: 1d15. 中找到的列名并不包括类型，
     举例来说，如果你在你的 SQL 中使用了像 ‘'as "Expiration date
     [datetime]"'’ 这样的写法，那么我们将解析出在第一个 then we will
     parse out everything until the first ‘'['’ 之前的所有内容并去除前导
     空格作为列名：即列名将为 "Expiration date"。

 -- 函数: sqlite3.connect (database[, timeout, detect_types,
          isolation_level, check_same_thread, factory,
          cached_statements, uri])

     连接 SQLite 数据库 `database'。默认返回 *note Connection: 3e0. 对象
     ，除非使用了自定义的 `factory' 参数。

     `database' 是准备打开的数据库文件的路径（绝对路径或相对于当前目录的
     相对路径），它是 *note path-like object: 373.。你也可以用
     ‘":memory:"’ 在内存中打开一个数据库。

     当一个数据库被多个连接访问的时候，如果其中一个进程修改这个数据库，
     在这个事务提交之前，这个 SQLite 数据库将会被一直锁定。`timeout' 参
     数指定了这个连接等待锁释放的超时时间，超时之后会引发一个异常。这个
     超时时间默认是 5.0（5秒）。

     `isolation_level' 参数，请查看 *note Connection: 3e0. 对象的 *note
     isolation_level: 1d16. 属性。

     SQLite 原生只支持5种类型：TEXT，INTEGER，REAL，BLOB 和 NULL。如果你
     想用其它类型，你必须自己添加相应的支持。使用 `detect_types' 参数和
     模块级别的 *note register_converter(): 1d17. 函数注册**转换器** 可
     以简单的实现。

     `detect_types' 默认为 0 (即关闭，不进行类型检测)，你可以将其设为任
     意的 *note PARSE_DECLTYPES: 1d13. 和 *note PARSE_COLNAMES: 1d14. 组
     合来启用类型检测。 由于 SQLite 的行为，生成的字段类型 (例如
     ‘max(data)’) 不能被检测，即使在设置了 `detect_types' 形参时也是如此
     。 在此情况下，返回的类型为 *note str: 339.。

     默认情况下，`check_same_thread' 为 *note True: 4a1.，只有当前的线程
     可以使用该连接。 如果设置为 *note False: 390.，则多个线程可以共享返
     回的连接。 当多个线程使用同一个连接的时候，用户应该把写操作进行序列
     化，以避免数据损坏。

     默认情况下，当调用 connect 方法的时候，*note sqlite3: f3. 模块使用
     了它的 *note Connection: 3e0. 类。当然，你也可以创建 *note
     Connection: 3e0. 类的子类，然后创建提供了 `factory' 参数的 *note
     connect(): 3e2. 方法。

     详情请查阅当前手册的 *note SQLite 与 Python 类型: 1d18. 部分。

     *note sqlite3: f3. 模块在内部使用语句缓存来避免 SQL 解析开销。 如果
     要显式设置当前连接可以缓存的语句数，可以设置 `cached_statements' 参
     数。 当前实现的默认值是缓存100条语句。

     如果 `uri' 为真，则 `database' 被解释为 URI。 它允许您指定选项。 例
     如，以只读模式打开数据库：

          db = sqlite3.connect('file:path/to/database?mode=ro', uri=True)

     有关此功能的更多信息，包括已知选项的列表，可以在 ‘ SQLite URI 文档
     <‘https://www.sqlite.org/uri.html’>‘_ 中找到。

     引发一个 *note 审计事件: ea1. ‘sqlite3.connect’，附带参数
     ‘database’。

     在 3.4 版更改: 增加了 `uri' 参数。

     在 3.7 版更改: `database' 现在可以是一个 *note path-like object:
     373. 对象了，不仅仅是字符串。

 -- 函数: sqlite3.register_converter (typename, callable)

     注册一个回调对象 `callable', 用来转换数据库中的字节串为自定的
     Python 类型。所有类型为 `typename' 的数据库的值在转换时，都会调用这
     个回调对象。通过指定 *note connect(): 3e2. 函数的 `detect-types' 参
     数来设置类型检测的方式。注意，`typename' 与查询语句中的类型名进行匹
     配时不区分大小写。

 -- 函数: sqlite3.register_adapter (type, callable)

     注册一个回调对象 `callable'，用来转换自定义Python类型为一个 SQLite
     支持的类型。 这个回调对象 `callable' 仅接受一个 Python 值作为参数，
     而且必须返回以下某个类型的值：int，float，str 或 bytes。

 -- 函数: sqlite3.complete_statement (sql)

     如果字符串 `sql' 包含一个或多个完整的 SQL 语句（以分号结束）则返回
     *note True: 4a1.。它不会验证 SQL 语法是否正确，仅会验证字符串字面上
     是否完整，以及是否以分号结束。

     它可以用来构建一个 SQLite shell，下面是一个例子：

          # A minimal SQLite shell for experiments

          import sqlite3

          con = sqlite3.connect(":memory:")
          con.isolation_level = None
          cur = con.cursor()

          buffer = ""

          print("Enter your SQL commands to execute in sqlite3.")
          print("Enter a blank line to exit.")

          while True:
              line = input()
              if line == "":
                  break
              buffer += line
              if sqlite3.complete_statement(buffer):
                  try:
                      buffer = buffer.strip()
                      cur.execute(buffer)

                      if buffer.lstrip().upper().startswith("SELECT"):
                          print(cur.fetchall())
                  except sqlite3.Error as e:
                      print("An error occurred:", e.args[0])
                  buffer = ""

          con.close()

 -- 函数: sqlite3.enable_callback_tracebacks (flag)

     默认情况下，您不会获得任何用户定义函数中的回溯消息，比如聚合，转换
     器，授权器回调等。如果要调试它们，可以设置 `flag' 参数为 ‘True’ 并
     调用此函数。 之后，回调中的回溯信息将会输出到 ‘sys.stderr’。 再次使
     用 *note False: 390. 来禁用该功能。


File: python.info,  Node: 连接对象（Connection）,  Next: Cursor 对象,  Prev: 模块函数和常量,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.2 连接对象（Connection）
...............................

 -- 类: sqlite3.Connection

     SQLite 数据库连接对象有如下的属性和方法：

      -- 属性: isolation_level

          获取或设置当前默认的隔离级别。 表示自动提交模式的 *note None:
          158. 以及 "DEFERRED", "IMMEDIATE" 或 "EXCLUSIVE" 其中之一。 详
          细描述请参阅 *note 控制事务: 1d1e.。

      -- 属性: in_transaction

          如果是在活动事务中（还没有提交改变），返回 *note True: 4a1.，
          否则，返回 *note False: 390.。它是一个只读属性。

          3.2 新版功能.

      -- 方法: cursor (factory=Cursor)

          这个方法接受一个可选参数 `factory'，如果要指定这个参数，它必须
          是一个可调用对象，而且必须返回 *note Cursor: 1d09. 类的一个实
          例或者子类。

      -- 方法: commit ()

          这个方法提交当前事务。如果没有调用这个方法，那么从上一次提交
          ‘commit()’ 以来所有的变化在其他数据库连接上都是不可见的。如果
          你往数据库里写了数据，但是又查询不到，请检查是否忘记了调用这个
          方法。

      -- 方法: rollback ()

          这个方法回滚从上一次调用 *note commit(): 1d21. 以来所有数据库
          的改变。

      -- 方法: close ()

          关闭数据库连接。注意，它不会自动调用 *note commit(): 1d21. 方
          法。如果在关闭数据库连接之前没有调用 *note commit(): 1d21.，那
          么你的修改将会丢失！

      -- 方法: execute (sql[, parameters])

          这是一个非标准的快捷方法，它会调用 *note cursor(): 1d20. 方法
          来创建一个游标对象，并使用给定的 `parameters' 参数来调用游标对
          象的 *note execute(): 1d0a. 方法，最后返回这个游标对象。

      -- 方法: executemany (sql[, parameters])

          这是一个非标准的快捷方法，它会调用 *note cursor(): 1d20. 方法
          来创建一个游标对象，并使用给定的 `parameters' 参数来调用游标对
          象的 *note executemany(): 1d26. 方法，最后返回这个游标对象。

      -- 方法: executescript (sql_script)

          这是一个非标准的快捷方法，它会调用 *note cursor(): 1d20. 方法
          来创建一个游标对象，并使用给定的 `sql_script' 参数来调用游标对
          象的 *note executescript(): 1d28. 方法，最后返回这个游标对象。

      -- 方法: create_function (name, num_params, func, *,
               deterministic=False)

          创建一个可以在 SQL 语句中使用的用户自定义函数，函数名为
          `name'。 `num_params' 为该函数所接受的形参个数（如果
          `num_params' 为 -1，则该函数可接受任意数量的参数）， `func' 是
          一个 Python 可调用对象，它将作为 SQL 函数被调用。 如果
          `deterministic' 为真值，则所创建的函数将被标记为
          deterministic(1)，这允许 SQLite 执行额外的优化。 此旗标在
          SQLite 3.8.3 或更高版本中受到支持，如果在旧版本中使用将引发
          *note NotSupportedError: 1d29.。

          此函数可返回任何 SQLite 所支持的类型: bytes, str, int, float 和
          ‘None’。

          在 3.8 版更改: 增加了 `deterministic' 形参。

          示例:

               import sqlite3
               import hashlib

               def md5sum(t):
                   return hashlib.md5(t).hexdigest()

               con = sqlite3.connect(":memory:")
               con.create_function("md5", 1, md5sum)
               cur = con.cursor()
               cur.execute("select md5(?)", (b"foo",))
               print(cur.fetchone()[0])

               con.close()

      -- 方法: create_aggregate (name, num_params, aggregate_class)

          创建一个自定义的聚合函数。

          参数中 `aggregate_class' 类必须实现两个方法：‘step’ 和
          ‘finalize’。‘step’ 方法接受 `num_params' 个参数（如果
          `num_params' 为 -1，那么这个函数可以接受任意数量的参数）；
          ‘finalize’ 方法返回最终的聚合结果。

          ‘finalize’ 方法可以返回任何 SQLite 支持的类型：bytes，str，
          int，float 和 ‘None’。

          示例:

               import sqlite3

               class MySum:
                   def __init__(self):
                       self.count = 0

                   def step(self, value):
                       self.count += value

                   def finalize(self):
                       return self.count

               con = sqlite3.connect(":memory:")
               con.create_aggregate("mysum", 1, MySum)
               cur = con.cursor()
               cur.execute("create table test(i)")
               cur.execute("insert into test(i) values (1)")
               cur.execute("insert into test(i) values (2)")
               cur.execute("select mysum(i) from test")
               print(cur.fetchone()[0])

               con.close()

      -- 方法: create_collation (name, callable)

          使用 `name' 和 `callable' 创建排序规则。这个 `callable' 接受两
          个字符串对象，如果第一个小于第二个则返回 -1， 如果两个相等则返
          回 0，如果第一个大于第二个则返回 1。注意，这是用来控制排序的（
          SQL 中的 ORDER BY），所以它不会影响其它的 SQL 操作。

          注意，这个 `callable' 可调用对象会把它的参数作为 Python 字节串
          ，通常会以 UTF-8 编码格式对它进行编码。

          以下示例显示了使用“错误方式”进行排序的自定义排序规则：

               import sqlite3

               def collate_reverse(string1, string2):
                   if string1 == string2:
                       return 0
                   elif string1 < string2:
                       return 1
                   else:
                       return -1

               con = sqlite3.connect(":memory:")
               con.create_collation("reverse", collate_reverse)

               cur = con.cursor()
               cur.execute("create table test(x)")
               cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
               cur.execute("select x from test order by x collate reverse")
               for row in cur:
                   print(row)
               con.close()

          要移除一个排序规则，需要调用 ‘create_collation’ 并设置
          callable 参数为 ‘None’。

               con.create_collation("reverse", None)

      -- 方法: interrupt ()

          可以从不同的线程调用这个方法来终止所有查询操作，这些查询操作可
          能正在连接上执行。此方法调用之后， 查询将会终止，而且查询的调
          用者会获得一个异常。

      -- 方法: set_authorizer (authorizer_callback)

          此方法注册一个授权回调对象。每次在访问数据库中某个表的某一列的
          时候，这个回调对象将会被调用。如果要允许访问，则返回
          ‘SQLITE_OK’，如果要终止整个 SQL 语句，则返回 ‘SQLITE_DENY’，如
          果这一列需要当做 NULL 值处理，则返回 ‘SQLITE_IGNORE’。这些常量
          可以在 *note sqlite3: f3. 模块中找到。

          回调的第一个参数表示要授权的操作类型。 第二个和第三个参数将是
          参数或 *note None: 158.，具体取决于第一个参数的值。 第 4 个参
          数是数据库的名称（“main”，“temp”等），如果需要的话。 第 5 个参
          数是负责访问尝试的最内层触发器或视图的名称，或者如果此访问尝试
          直接来自输入 SQL 代码，则为 *note None: 158.。

          请参阅 SQLite 文档，了解第一个参数的可能值以及第二个和第三个参
          数的含义，具体取决于第一个参数。 所有必需的常量都可以在 *note
          sqlite3: f3. 模块中找到。

      -- 方法: set_progress_handler (handler, n)

          此例程注册回调。 对SQLite虚拟机的每个多指令调用回调。 如果要在
          长时间运行的操作期间从SQLite调用（例如更新用户界面），这非常有
          用。

          如果要清除以前安装的任何进度处理程序，调用该方法时请将
          `handler' 参数设置为 *note None: 158.。

          从处理函数返回非零值将终止当前正在执行的查询并导致它引发 *note
          OperationalError: 1d2c. 异常。

      -- 方法: set_trace_callback (trace_callback)

          为每个 SQLite 后端实际执行的 SQL 语句注册要调用的
          `trace_callback'。

          传递给回调的唯一参数是正在执行的语句（作为字符串）。 回调的返
          回值将被忽略。 请注意，后端不仅运行传递给 *note
          Cursor.execute(): 1d0a. 方法的语句。 其他来源包括 Python 模块
          的事务管理和当前数据库中定义的触发器的执行。

          将传入的 `trace_callback' 设为 *note None: 158. 将禁用跟踪回调
          。

          3.3 新版功能.

      -- 方法: enable_load_extension (enabled)

          此例程允许/禁止SQLite引擎从共享库加载SQLite扩展。 SQLite扩展可
          以定义新功能，聚合或全新的虚拟表实现。 一个众所周知的扩展是与
          SQLite一起分发的全文搜索扩展。

          默认情况下禁用可加载扩展。 见 (2).

          3.2 新版功能.

               import sqlite3

               con = sqlite3.connect(":memory:")

               # enable extension loading
               con.enable_load_extension(True)

               # Load the fulltext search extension
               con.execute("select load_extension('./fts3.so')")

               # alternatively you can load the extension using an API call:
               # con.load_extension("./fts3.so")

               # disable extension loading again
               con.enable_load_extension(False)

               # example from SQLite wiki
               con.execute("create virtual table recipe using fts3(name, ingredients)")
               con.executescript("""
                   insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes');
                   insert into recipe (name, ingredients) values ('pumpkin stew', 'pumpkin onions garlic celery');
                   insert into recipe (name, ingredients) values ('broccoli pie', 'broccoli cheese onions flour');
                   insert into recipe (name, ingredients) values ('pumpkin pie', 'pumpkin sugar flour butter');
                   """)
               for row in con.execute("select rowid, name, ingredients from recipe where name match 'pie'"):
                   print(row)

               con.close()

      -- 方法: load_extension (path)

          此例程从共享库加载SQLite扩展。 在使用此例程之前，必须使用
          *note enable_load_extension(): ba1. 启用扩展加载。

          默认情况下禁用可加载扩展。 见 (3).

          3.2 新版功能.

      -- 属性: row_factory

          您可以将此属性更改为可接受游标和原始行作为元组的可调用对象，并
          将返回实际结果行。 这样，您可以实现更高级的返回结果的方法，例
          如返回一个可以按名称访问列的对象。

          示例:

               import sqlite3

               def dict_factory(cursor, row):
                   d = {}
                   for idx, col in enumerate(cursor.description):
                       d[col[0]] = row[idx]
                   return d

               con = sqlite3.connect(":memory:")
               con.row_factory = dict_factory
               cur = con.cursor()
               cur.execute("select 1 as a")
               print(cur.fetchone()["a"])

               con.close()

          如果返回一个元组是不够的，并且你想要对列进行基于名称的访问，你
          应该考虑将 *note row_factory: 1d2d. 设置为高度优化的 *note
          sqlite3.Row: 767. 类型。 *note Row: 767. 提供基于索引和不区分
          大小写的基于名称的访问，几乎没有内存开销。 它可能比您自己的基
          于字典的自定义方法甚至基于 db_row 的解决方案更好。

      -- 属性: text_factory

          使用此属性可以控制为 ‘TEXT’ 数据类型返回的对象。 默认情况下，
          此属性设置为 *note str: 339. 和 *note sqlite3: f3. 模块将返回
          ‘TEXT’ 的 Unicode 对象。 如果要返回字节串，可以将其设置为
          *note bytes: 33a.。

          您还可以将其设置为接受单个 bytestring 参数的任何其他可调用对象
          ，并返回结果对象。

          请参阅以下示例代码以进行说明：

               import sqlite3

               con = sqlite3.connect(":memory:")
               cur = con.cursor()

               AUSTRIA = "\xd6sterreich"

               # by default, rows are returned as Unicode
               cur.execute("select ?", (AUSTRIA,))
               row = cur.fetchone()
               assert row[0] == AUSTRIA

               # but we can make sqlite3 always return bytestrings ...
               con.text_factory = bytes
               cur.execute("select ?", (AUSTRIA,))
               row = cur.fetchone()
               assert type(row[0]) is bytes
               # the bytestrings will be encoded in UTF-8, unless you stored garbage in the
               # database ...
               assert row[0] == AUSTRIA.encode("utf-8")

               # we can also implement a custom text_factory ...
               # here we implement one that appends "foo" to all strings
               con.text_factory = lambda x: x.decode("utf-8") + "foo"
               cur.execute("select ?", ("bar",))
               row = cur.fetchone()
               assert row[0] == "barfoo"

               con.close()

      -- 属性: total_changes

          返回自打开数据库连接以来已修改，插入或删除的数据库行的总数。

      -- 方法: iterdump ()

          返回以SQL文本格式转储数据库的迭代器。 保存内存数据库以便以后恢
          复时很有用。 此函数提供与 ‘sqlite3’ shell 中的 ‘.dump’ 命令相
          同的功能。

          示例:

               # Convert file existing_db.db to SQL dump file dump.sql
               import sqlite3

               con = sqlite3.connect('existing_db.db')
               with open('dump.sql', 'w') as f:
                   for line in con.iterdump():
                       f.write('%s\n' % line)
               con.close()

      -- 方法: backup (target, *, pages=-1, progress=None, name="main",
               sleep=0.250)

          即使在 SQLite 数据库被其他客户端访问时，或者同时由同一连接访问
          ，该方法也会对其进行备份。 该副本将写入强制参数 `target'，该参
          数必须是另一个 *note Connection: 3e0. 实例。

          默认情况下，或者当 `pages' 为 ‘0’ 或负整数时，整个数据库将在一
          个步骤中复制；否则该方法一次循环复制 `pages' 规定数量的页面。

          如果指定了 `progress'，则它必须为 ‘None’ 或一个将在每次迭代时
          附带三个整数参数执行的可调用对象，这三个参数分别是前一次迭代的
          状态 `status'，将要拷贝的剩余页数 `remaining' 以及总页数
          `total'。

          `name' 参数指定将被拷贝的数据库名称：它必须是一个字符串，其内
          容为表示主数据库的默认值 ‘"main"’，表示临时数据库的 ‘"temp"’ 或
          是在 ‘ATTACH DATABASE’ 语句的 ‘AS’ 关键字之后指定表示附加数据
          库的名称。

          `sleep' 参数指定在备份剩余页的连续尝试之间要休眠的秒数，可以指
          定为一个整数或一个浮点数值。

          示例一，将现有数据库复制到另一个数据库中：

               import sqlite3

               def progress(status, remaining, total):
                   print(f'Copied {total-remaining} of {total} pages...')

               con = sqlite3.connect('existing_db.db')
               bck = sqlite3.connect('backup.db')
               with bck:
                   con.backup(bck, pages=1, progress=progress)
               bck.close()
               con.close()

          示例二，将现有数据库复制到临时副本中：

               import sqlite3

               source = sqlite3.connect('existing_db.db')
               dest = sqlite3.connect(':memory:')
               source.backup(dest)

          可用性：SQLite 3.6.11 或以上版本

          3.7 新版功能.

   ---------- Footnotes ----------

   (1) https://sqlite.org/deterministic.html

   (2) (1) sqlite3 模块的构建默认没有附带可加载扩展支持，因为某些平台（
特别是 Mac OS X）上的 SQLite 库在编译时未使用此特性。 要获得可加载扩展支
持，你必须传入 ‘--enable-loadable-sqlite-extensions’ 来进行配置。

   (3) (1) sqlite3 模块的构建默认没有附带可加载扩展支持，因为某些平台（
特别是 Mac OS X）上的 SQLite 库在编译时未使用此特性。 要获得可加载扩展支
持，你必须传入 ‘--enable-loadable-sqlite-extensions’ 来进行配置。


File: python.info,  Node: Cursor 对象,  Next: 行对象,  Prev: 连接对象（Connection）,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.3 Cursor 对象
....................

 -- 类: sqlite3.Cursor

     *note Cursor: 1d09. 游标实例具有以下属性和方法。

      -- 方法: execute (sql[, parameters])

          执行SQL语句。 可以是参数化 SQL 语句（即，在 SQL 语句中使用占位
          符）。*note sqlite3: f3. 模块支持两种占位符：问号（qmark风格）
          和命名占位符（命名风格）。

          以下是两种风格的示例：

               import sqlite3

               con = sqlite3.connect(":memory:")
               cur = con.cursor()
               cur.execute("create table people (name_last, age)")

               who = "Yeltsin"
               age = 72

               # This is the qmark style:
               cur.execute("insert into people values (?, ?)", (who, age))

               # And this is the named style:
               cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})

               print(cur.fetchone())

               con.close()

          *note execute(): 1d0a. 将只执行一条单独的 SQL 语句。 如果你尝
          试用它执行超过一条语句，将会引发 *note Warning: 1d33.。 如果你
          想要用一次调用执行多条 SQL 语句请使用 *note executescript():
          1d28.。

      -- 方法: executemany (sql, seq_of_parameters)

          基于在序列 `seq_of_parameters' 中找到的所有形参序列或映射执行
          一条 SQL 命令。 *note sqlite3: f3. 模块还允许使用 *note
          iterator: 104b. 代替序列来产生形参。

               import sqlite3

               class IterChars:
                   def __init__(self):
                       self.count = ord('a')

                   def __iter__(self):
                       return self

                   def __next__(self):
                       if self.count > ord('z'):
                           raise StopIteration
                       self.count += 1
                       return (chr(self.count - 1),) # this is a 1-tuple

               con = sqlite3.connect(":memory:")
               cur = con.cursor()
               cur.execute("create table characters(c)")

               theIter = IterChars()
               cur.executemany("insert into characters(c) values (?)", theIter)

               cur.execute("select c from characters")
               print(cur.fetchall())

               con.close()

          这是一个使用生成器 *note generator: 9aa. 的简短示例：

               import sqlite3
               import string

               def char_generator():
                   for c in string.ascii_lowercase:
                       yield (c,)

               con = sqlite3.connect(":memory:")
               cur = con.cursor()
               cur.execute("create table characters(c)")

               cur.executemany("insert into characters(c) values (?)", char_generator())

               cur.execute("select c from characters")
               print(cur.fetchall())

               con.close()

      -- 方法: executescript (sql_script)

          这是一个非标准的便捷方法，可用于一次执行多条 SQL 语句。 它会首
          先执行一条 ‘COMMIT’ 语句，再执行以形参方式获取的 SQL 脚本。

          `sql_script' 可以是一个 *note str: 339. 类的实例。

          示例:

               import sqlite3

               con = sqlite3.connect(":memory:")
               cur = con.cursor()
               cur.executescript("""
                   create table person(
                       firstname,
                       lastname,
                       age
                   );

                   create table book(
                       title,
                       author,
                       published
                   );

                   insert into book(title, author, published)
                   values (
                       'Dirk Gently''s Holistic Detective Agency',
                       'Douglas Adams',
                       1987
                   );
                   """)
               con.close()

      -- 方法: fetchone ()

          获取一个查询结果集的下一行，返回一个单独序列，或是在没有更多可
          用数据时返回 *note None: 158.。

      -- 方法: fetchmany (size=cursor.arraysize)

          获取下一个多行查询结果集，返回一个列表。 当没有更多可用行时将
          返回一个空列表。

          每次调用获取的行数由 `size' 形参指定。 如果没有给出该形参，则
          由 cursor 的 arraysize 决定要获取的行数。 此方法将基于 size 形
          参值尝试获取指定数量的行。 如果获取不到指定的行数，则可能返回
          较少的行。

          请注意 `size' 形参会涉及到性能方面的考虑。为了获得优化的性能，
          通常最好是使用 arraysize 属性。 如果使用 `size' 形参，则最好在
          从一个 *note fetchmany(): 1d34. 调用到下一个调用之间保持相同的
          值。

      -- 方法: fetchall ()

          获取一个查询结果的所有（剩余）行，返回一个列表。 请注意 cursor
          的 arraysize 属性会影响此操作的执行效率。 当没有可用行时将返回
          一个空列表。

      -- 方法: close ()

          立即关闭 cursor（而不是在当 ‘__del__’ 被调用的时候）。

          从这一时刻起该 cursor 将不再可用，如果再尝试用该 cursor 执行任
          何操作将引发 *note ProgrammingError: ee8. 异常。

      -- 属性: rowcount

          虽然 *note sqlite3: f3. 模块的 *note Cursor: 1d09. 类实现了此
          属性，但数据库引擎本身对于确定 "受影响行"/"已选择行" 的支持并
          不完善。

          对于 *note executemany(): 1d26. 语句，修改行数会被汇总至 *note
          rowcount: 1d36.。

          根据 Python DB API 规格描述的要求，*note rowcount: 1d36. 属性
          "当未在 cursor 上执行 ‘executeXX()’ 或者上一次操作的 rowcount
          不是由接口确定时为 -1"。 这包括 ‘SELECT’ 语句，因为我们无法确
          定一次查询将产生的行计数，而要等获取了所有行时才会知道。

          在 SQLite 的 3.6.5 版之前，如果你执行 ‘DELETE FROM table’ 时不
          附带任何条件，则 *note rowcount: 1d36. 将被设为 0。

      -- 属性: lastrowid

          这个只读属性会提供最近修改行的 rowid。 它只在你使用 *note
          execute(): 1d0a. 方法执行 ‘INSERT’ 或 ‘REPLACE’ 语句时会被设置
          。 对于 ‘INSERT’ 或 ‘REPLACE’ 以外的操作或者当 *note
          executemany(): 1d26. 被调用时，*note lastrowid: 587. 会被设为
          *note None: 158.。

          如果 ‘INSERT’ 或 ‘REPLACE’ 语句操作失败则将返回上一次成功操作
          的 rowid。

          在 3.6 版更改: 增加了 ‘REPLACE’ 语句的支持。

      -- 属性: arraysize

          用于控制 *note fetchmany(): 1d34. 返回行数的可读取/写入属性。
          该属性的默认值为 1，表示每次调用将获取单独一行。

      -- 属性: description

          这个只读属性将提供上一次查询的列名称。 为了与 Python DB API 保
          持兼容，它会为每个列返回一个 7 元组，每个元组的最后六个条目均
          为 *note None: 158.。

          对于没有任何匹配行的 ‘SELECT’ 语句同样会设置该属性。

      -- 属性: connection

          这个只读属性将提供 *note Cursor: 1d09. 对象所使用的 SQLite 数
          据库 *note Connection: 3e0.。 通过调用 *note con.cursor():
          1d20. 创建的 *note Cursor: 1d09. 对象所包含的 *note
          connection: 1d38. 属性将指向 `con':

               >>> con = sqlite3.connect(":memory:")
               >>> cur = con.cursor()
               >>> cur.connection == con
               True


File: python.info,  Node: 行对象,  Next: 异常<4>,  Prev: Cursor 对象,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.4 行对象
...............

 -- 类: sqlite3.Row

     一个 *note Row: 767. 实例，该实例将作为用于 *note Connection: 3e0.
     对象的高度优化的 *note row_factory: 1d2d.。 它的大部分行为都会模仿
     元组的特性。

     它支持使用列名称的映射访问以及索引、迭代、文本表示、相等检测和
     *note len(): 151. 等操作。

     如果两个 *note Row: 767. 对象具有完全相同的列并且其成员均相等，则它
     们的比较结果为相等。

      -- 方法: keys ()

          此方法会在一次查询之后立即返回一个列名称的列表，它是 *note
          Cursor.description: 1d15. 中每个元组的第一个成员。

     在 3.5 版更改: 添加了对切片操作的支持。

让我们假设我们如上面的例子所示初始化一个表:

     con = sqlite3.connect(":memory:")
     cur = con.cursor()
     cur.execute('''create table stocks
     (date text, trans text, symbol text,
      qty real, price real)''')
     cur.execute("""insert into stocks
                 values ('2006-01-05','BUY','RHAT',100,35.14)""")
     con.commit()
     cur.close()

现在我们将 *note Row: 767. 插入:

     >>> con.row_factory = sqlite3.Row
     >>> cur = con.cursor()
     >>> cur.execute('select * from stocks')
     <sqlite3.Cursor object at 0x7f4e7dd8fa80>
     >>> r = cur.fetchone()
     >>> type(r)
     <class 'sqlite3.Row'>
     >>> tuple(r)
     ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
     >>> len(r)
     5
     >>> r[2]
     'RHAT'
     >>> r.keys()
     ['date', 'trans', 'symbol', 'qty', 'price']
     >>> r['qty']
     100.0
     >>> for member in r:
     ...     print(member)
     ...
     2006-01-05
     BUY
     RHAT
     100.0
     35.14


File: python.info,  Node: 异常<4>,  Next: SQLite 与 Python 类型,  Prev: 行对象,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.5 异常
.............

 -- 例外: sqlite3.Warning

     *note Exception: 1aa. 的一个子类。

 -- 例外: sqlite3.Error

     此模块中其他异常的基类。 它是 *note Exception: 1aa. 的一个子类。

 -- 例外: sqlite3.DatabaseError

     针对数据库相关错误引发的异常。

 -- 例外: sqlite3.IntegrityError

     当数据库的关系一致性受到影响时引发的异常。 例如外键检查失败等。 它
     是 *note DatabaseError: 1d3f. 的子类。

 -- 例外: sqlite3.ProgrammingError

     编程错误引发的异常，例如表未找到或已存在，SQL 语句存在语法错误，指
     定的形参数量错误等。 它是 *note DatabaseError: 1d3f. 的子类。

 -- 例外: sqlite3.OperationalError

     与数据库操作相关而不一定能受程序员掌控的错误引发的异常，例如发生非
     预期的连接中断，数据源名称未找到，事务无法被执行等。 它是 *note
     DatabaseError: 1d3f. 的子类。

 -- 例外: sqlite3.NotSupportedError

     在使用了某个数据库不支持的方法或数据库 API 时引发的异常，例如在一个
     不支持事务或禁用了事务的连接上调用 *note rollback(): 1d22. 方法等。
     它是 *note DatabaseError: 1d3f. 的子类。


File: python.info,  Node: SQLite 与 Python 类型,  Next: 控制事务,  Prev: 异常<4>,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.6 SQLite 与 Python 类型
..............................

* Menu:

* 概述: 概述<7>.
* 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。::
* 将SQLite 值转换为自定义Python 类型::
* 默认适配器和转换器::


File: python.info,  Node: 概述<7>,  Next: 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。,  Up: SQLite 与 Python 类型

5.12.6.7 概述
.............

SQLite 原生支持如下的类型： ‘NULL’，‘INTEGER’，‘REAL’，‘TEXT’，‘BLOB’。

因此可以将以下Python类型发送到SQLite而不会出现任何问题：

Python 类型                         SQLite 类型
                                    
------------------------------------------------------
                                    
*note None: 158.                    ‘NULL’
                                    
                                    
*note int: 185.                     ‘INTEGER’
                                    
                                    
*note float: 188.                   ‘REAL’
                                    
                                    
*note str: 339.                     ‘TEXT’
                                    
                                    
*note bytes: 33a.                   ‘BLOB’
                                    

这是SQLite类型默认转换为Python类型的方式：

SQLite 类型       Python 类型
                  
---------------------------------------------------------------------
                  
‘NULL’            *note None: 158.
                  
                  
‘INTEGER’         *note int: 185.
                  
                  
‘REAL’            *note float: 188.
                  
                  
‘TEXT’            取决于 *note text_factory: 1d2e. , 默认为
                  *note str: 339.
                  
                  
‘BLOB’            *note bytes: 33a.
                  

*note sqlite3: f3. 模块的类型系统可通过两种方式来扩展：你可以通过对象适
配将额外的 Python 类型保存在 SQLite 数据库中，你也可以让 *note sqlite3:
f3. 模块通过转换器将 SQLite 类型转换为不同的 Python 类型。


File: python.info,  Node: 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。,  Next: 将SQLite 值转换为自定义Python 类型,  Prev: 概述<7>,  Up: SQLite 与 Python 类型

5.12.6.8 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。
...............................................................

如上文所述，SQLite 只包含对有限类型集的原生支持。 要让 SQLite 能使用其他
Python 类型，你必须将它们 `适配' 至 sqlite3 模块所支持的 SQLite 类型中的
一种：NoneType, int, float, str, bytes。

有两种方式能让 *note sqlite3: f3. 模块将某个定制的 Python 类型适配为受支
持的类型。

* Menu:

* 让对象自行适配::
* 注册可调用的适配器::


File: python.info,  Node: 让对象自行适配,  Next: 注册可调用的适配器,  Up: 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。

5.12.6.9 让对象自行适配
.......................

如果类是你自己编写的，这将是一个很好的方式。 假设你有这样一个类:

     class Point:
         def __init__(self, x, y):
             self.x, self.y = x, y

现在你想将这种点对象保存在一个 SQLite 列中。 首先你必须选择一种受支持的
类型用来表示点对象。 让我们就用 str 并使用一个分号来分隔坐标值。 然后你
需要给你的类加一个方法 ‘__conform__(self, protocol)’，它必须返回转换后的
值。 形参 `protocol' 将为 ‘PrepareProtocol’。

     import sqlite3

     class Point:
         def __init__(self, x, y):
             self.x, self.y = x, y

         def __conform__(self, protocol):
             if protocol is sqlite3.PrepareProtocol:
                 return "%f;%f" % (self.x, self.y)

     con = sqlite3.connect(":memory:")
     cur = con.cursor()

     p = Point(4.0, -3.2)
     cur.execute("select ?", (p,))
     print(cur.fetchone()[0])

     con.close()


File: python.info,  Node: 注册可调用的适配器,  Prev: 让对象自行适配,  Up: 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。

5.12.6.10 注册可调用的适配器
............................

另一种可能的做法是创建一个将该类型转换为字符串表示的函数并使用 *note
register_adapter(): 1d19. 注册该函数。

     import sqlite3

     class Point:
         def __init__(self, x, y):
             self.x, self.y = x, y

     def adapt_point(point):
         return "%f;%f" % (point.x, point.y)

     sqlite3.register_adapter(Point, adapt_point)

     con = sqlite3.connect(":memory:")
     cur = con.cursor()

     p = Point(4.0, -3.2)
     cur.execute("select ?", (p,))
     print(cur.fetchone()[0])

     con.close()

*note sqlite3: f3. 模块有两个适配器可用于 Python 的内置 *note
datetime.date: 194. 和 *note datetime.datetime: 195. 类型。 现在假设我们
想要存储 *note datetime.datetime: 195. 对象，但不是表示为 ISO 格式，而是
表示为 Unix 时间戳。

     import sqlite3
     import datetime
     import time

     def adapt_datetime(ts):
         return time.mktime(ts.timetuple())

     sqlite3.register_adapter(datetime.datetime, adapt_datetime)

     con = sqlite3.connect(":memory:")
     cur = con.cursor()

     now = datetime.datetime.now()
     cur.execute("select ?", (now,))
     print(cur.fetchone()[0])

     con.close()


File: python.info,  Node: 将SQLite 值转换为自定义Python 类型,  Next: 默认适配器和转换器,  Prev: 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。,  Up: SQLite 与 Python 类型

5.12.6.11 将SQLite 值转换为自定义Python 类型
............................................

编写适配器让你可以将定制的 Python 类型发送给 SQLite。 但要令它真正有用，
我们需要实现从 Python 到 SQLite 再回到 Python 的双向转换。

输入转换器。

让我们回到 ‘Point’ 类。 我们以字符串形式在 SQLite 中存储了 x 和 y 坐标值
。

首先，我们将定义一个转换器函数，它接受这样的字符串作为形参并根据该参数构
造一个 ‘Point’ 对象。

     注解: 转换器函数在调用时 `总是' 会附带一个 *note bytes: 33a. 对象，
     无论你将何种数据类型的值发给 SQLite。

     def convert_point(s):
         x, y = map(float, s.split(b";"))
         return Point(x, y)

现在你需要让 *note sqlite3: f3. 模块知道你从数据库中选取的其实是一个点对
象。 有两种方式都可以做到这件事：

   * 隐式的声明类型

   * 显式的通过列名

这两种方式会在 *note 模块函数和常量: 1d0e. 一节中描述，相应条目为 *note
PARSE_DECLTYPES: 1d13. 和 *note PARSE_COLNAMES: 1d14. 常量。

下面的示例说明了这两种方法。

     import sqlite3

     class Point:
         def __init__(self, x, y):
             self.x, self.y = x, y

         def __repr__(self):
             return "(%f;%f)" % (self.x, self.y)

     def adapt_point(point):
         return ("%f;%f" % (point.x, point.y)).encode('ascii')

     def convert_point(s):
         x, y = list(map(float, s.split(b";")))
         return Point(x, y)

     # Register the adapter
     sqlite3.register_adapter(Point, adapt_point)

     # Register the converter
     sqlite3.register_converter("point", convert_point)

     p = Point(4.0, -3.2)

     #########################
     # 1) Using declared types
     con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
     cur = con.cursor()
     cur.execute("create table test(p point)")

     cur.execute("insert into test(p) values (?)", (p,))
     cur.execute("select p from test")
     print("with declared types:", cur.fetchone()[0])
     cur.close()
     con.close()

     #######################
     # 1) Using column names
     con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
     cur = con.cursor()
     cur.execute("create table test(p)")

     cur.execute("insert into test(p) values (?)", (p,))
     cur.execute('select p as "p [point]" from test')
     print("with column names:", cur.fetchone()[0])
     cur.close()
     con.close()


File: python.info,  Node: 默认适配器和转换器,  Prev: 将SQLite 值转换为自定义Python 类型,  Up: SQLite 与 Python 类型

5.12.6.12 默认适配器和转换器
............................

对于 datetime 模块中的 date 和 datetime 类型已提供了默认的适配器。 它们
将会以 ISO 日期/ISO 时间戳的形式发给 SQLite。

默认转换器使用的注册名称是针对 *note datetime.date: 194. 的 "date" 和针
对 *note datetime.datetime: 195. 的 "timestamp"。

通过这种方式，你可以在大多数情况下使用 Python 的 date/timestamp 对象而无
须任何额外处理。 适配器的格式还与实验性的 SQLite date/time 函数兼容。

下面的示例演示了这一点。

     import sqlite3
     import datetime

     con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
     cur = con.cursor()
     cur.execute("create table test(d date, ts timestamp)")

     today = datetime.date.today()
     now = datetime.datetime.now()

     cur.execute("insert into test(d, ts) values (?, ?)", (today, now))
     cur.execute("select d, ts from test")
     row = cur.fetchone()
     print(today, "=>", row[0], type(row[0]))
     print(now, "=>", row[1], type(row[1]))

     cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"')
     row = cur.fetchone()
     print("current_date", row[0], type(row[0]))
     print("current_timestamp", row[1], type(row[1]))

     con.close()

如果存储在 SQLite 中的时间戳的小数位多于 6 个数字，则时间戳转换器会将该
值截断至微秒精度。


File: python.info,  Node: 控制事务,  Next: 有效使用 sqlite3,  Prev: SQLite 与 Python 类型,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.13 控制事务
..................

底层的 ‘sqlite3’ 库默认会以 ‘autocommit’ 模式运行，但 Python 的 *note
sqlite3: f3. 模块默认则不使用此模式。

‘autocommit’ 模式意味着修改数据库的操作会立即生效。 ‘BEGIN’ 或
‘SAVEPOINT’ 语句会禁用 ‘autocommit’ 模式，而用于结束外层事务的 ‘COMMIT’,
‘ROLLBACK’ 或 ‘RELEASE’ 则会恢复 ‘autocommit’ 模式。

Python 的 *note sqlite3: f3. 模块默认会在数据修改语言 (DML) 类语句 (即
‘INSERT’/‘UPDATE’/‘DELETE’/‘REPLACE’) 之前隐式地执行一条 ‘BEGIN’ 语句。

你可以控制 *note sqlite3: f3. 隐式执行的 ‘BEGIN’ 语句的种类，具体做法是
通过将 `isolation_level' 形参传给 *note connect(): 3e2. 调用，或者通过指
定连接的 ‘isolation_level’ 属性。 如果你没有指定 `isolation_level'，将使
用基本的 ‘BEGIN’，它等价于指定 ‘DEFERRED’。 其他可能的值为 ‘IMMEDIATE’ 和
‘EXCLUSIVE’。

你可以禁用 *note sqlite3: f3. 模块的隐式事务管理，具体做法是将
‘isolation_level’ 设为 ‘None’。 这将使得下层的 ‘sqlite3’ 库采用
‘autocommit’ 模式。 随后你可以通过在代码中显式地使用 ‘BEGIN’,
‘ROLLBACK’, ‘SAVEPOINT’ 和 ‘RELEASE’ 语句来完全控制事务状态。

在 3.6 版更改: 以前 *note sqlite3: f3. 会在 DDL 语句之前隐式地提交未完成
事务。 现在则不会再这样做。


File: python.info,  Node: 有效使用 sqlite3,  Prev: 控制事务,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.14 有效使用 ‘sqlite3’
............................

* Menu:

* 使用快捷方式::
* 通过名称而不是索引访问索引::
* 使用连接作为上下文管理器::


File: python.info,  Node: 使用快捷方式,  Next: 通过名称而不是索引访问索引,  Up: 有效使用 sqlite3

5.12.6.15 使用快捷方式
......................

使用 *note Connection: 3e0. 对象的非标准 ‘execute()’, ‘executemany()’ 和
‘executescript()’ 方法，可以更简洁地编写代码，因为不必显式创建（通常是多
余的） *note Cursor: 1d09. 对象。相反， *note Cursor: 1d09. 对象是隐式创
建的，这些快捷方法返回游标对象。这样，只需对 *note Connection: 3e0. 对象
调用一次，就能直接执行 ‘SELECT’ 语句并遍历对象。

     import sqlite3

     persons = [
         ("Hugo", "Boss"),
         ("Calvin", "Klein")
         ]

     con = sqlite3.connect(":memory:")

     # Create the table
     con.execute("create table person(firstname, lastname)")

     # Fill the table
     con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)

     # Print the table contents
     for row in con.execute("select firstname, lastname from person"):
         print(row)

     print("I just deleted", con.execute("delete from person").rowcount, "rows")

     # close is not a shortcut method and it's not called automatically,
     # so the connection object should be closed manually
     con.close()


File: python.info,  Node: 通过名称而不是索引访问索引,  Next: 使用连接作为上下文管理器,  Prev: 使用快捷方式,  Up: 有效使用 sqlite3

5.12.6.16 通过名称而不是索引访问索引
....................................

*note sqlite3: f3. 模块的一个有用功能是内置的 *note sqlite3.Row: 767. 类
，它被设计用作行对象的工厂。

该类的行装饰器可以用索引（如元组）和不区分大小写的名称访问：

     import sqlite3

     con = sqlite3.connect(":memory:")
     con.row_factory = sqlite3.Row

     cur = con.cursor()
     cur.execute("select 'John' as name, 42 as age")
     for row in cur:
         assert row[0] == row["name"]
         assert row["name"] == row["nAmE"]
         assert row[1] == row["age"]
         assert row[1] == row["AgE"]

     con.close()


File: python.info,  Node: 使用连接作为上下文管理器,  Prev: 通过名称而不是索引访问索引,  Up: 有效使用 sqlite3

5.12.6.17 使用连接作为上下文管理器
..................................

连接对象可以用来作为上下文管理器，它可以自动提交或者回滚事务。如果出现异
常，事务会被回滚；否则，事务会被提交。

     import sqlite3

     con = sqlite3.connect(":memory:")
     con.execute("create table person (id integer primary key, firstname varchar unique)")

     # Successful, con.commit() is called automatically afterwards
     with con:
         con.execute("insert into person(firstname) values (?)", ("Joe",))

     # con.rollback() is called after the with block finishes with an exception, the
     # exception is still raised and must be caught
     try:
         with con:
             con.execute("insert into person(firstname) values (?)", ("Joe",))
     except sqlite3.IntegrityError:
         print("couldn't add Joe twice")

     # Connection object used as context manager only commits or rollbacks transactions,
     # so the connection object should be closed manually
     con.close()

备注
....


File: python.info,  Node: 数据压缩和存档,  Next: 文件格式,  Prev: 数据持久化,  Up: Python 标准库

5.13 数据压缩和存档
===================

本章中描述的模块支持 zlib、gzip、bzip2 和 lzma 数据压缩算法，以及创建
ZIP 和 tar 格式的归档文件。参见由 *note shutil: ea. 模块提供的 *note
归档操作: b9e. 。

* Menu:

* zlib: zlib --- 与 gzip 兼容的压缩. 与 gzip 兼容的压缩
* gzip: gzip --- 对 gzip 格式的支持. 对 gzip 格式的支持
* bz2: bz2 --- 对 bzip2 压缩算法的支持. 对 bzip2 压缩算法的支持
* lzma: lzma --- 用 LZMA 算法压缩. 用 LZMA 算法压缩
* zipfile: zipfile --- 使用ZIP存档. 使用ZIP存档
* tarfile: tarfile --- 读写tar归档文件. 读写tar归档文件


File: python.info,  Node: zlib --- 与 gzip 兼容的压缩,  Next: gzip --- 对 gzip 格式的支持,  Up: 数据压缩和存档

5.13.1 ‘zlib’ — 与 ‘gzip’ 兼容的压缩
------------------------------------

__________________________________________________________________

此模块为需要数据压缩的程序提供了一系列函数，用于压缩和解压缩。这些函数使
用了 zlib 库。zlib 库的项目主页是 ‘http://www.zlib.net’. 版本低于 1.1.3
的 zlib 与此 Python 模块之间存在已知的不兼容。1.1.3 版本的 zlib 存在一个
安全漏洞，我们推荐使用 1.1.4 或更新的版本。

zlib 的函数有很多选项，一般需要按特定顺序使用。本文档没有覆盖全部的用法
。更多详细信息请于 ‘http://www.zlib.net/manual.html’ 参阅官方手册。

要读写 ‘.gz’ 格式的文件，请参考 *note gzip: 8c. 模块。

此模块中可用的异常和函数如下：

 -- 例外: zlib.error

     在压缩或解压缩过程中发生错误时的异常。

 -- 函数: zlib.adler32 (data[, value])

     计算 `data' 的 Adler-32 校验值。(Adler-32 校验的可靠性与 CRC32 基本
     相当，但比计算 CRC32 更高效。) 计算的结果是一个 32 位的整数。参数
     `value' 是校验时的起始值，其默认值为 1。借助参数 `value' 可为分段的
     输入计算校验值。此算法没有加密强度，不应用于身份验证和数字签名。此
     算法的目的仅为验证数据的正确性，不适合作为通用散列算法。

     在 3.0 版更改: 返回值永远是无符号数。要在所有的 Python 版本和平台上
     获得相同的值，请使用 ‘adler32(data) & 0xffffffff’。

 -- 函数: zlib.compress (data, level=-1)

     压缩 `data' 中的字节，返回含有已压缩内容的 bytes 对象。参数 `level'
     为整数，可取值为 ‘0’ 到 ‘9’ 或 ‘-1’，用于指定压缩等级。‘1’
     (Z_BEST_SPEED) 表示最快速度和最低压缩率，‘9’ (Z_BEST_COMPRESSION) 表
     示最慢速度和最高压缩率。‘0’ (Z_NO_COMPRESSION) 表示不压缩。参数默认
     值为 ‘-1’ (Z_DEFAULT_COMPRESSION)。Z_DEFAULT_COMPRESSION 是速度和压
     缩率之间的平衡 (一般相当于设压缩等级为 6)。函数发生错误时抛出 *note
     error: 1d51. 异常。

     在 3.6 版更改: 现在，`level' 可作为关键字参数。

 -- 函数: zlib.compressobj (level=-1, method=DEFLATED, wbits=MAX_WBITS,
          memLevel=DEF_MEM_LEVEL, strategy=Z_DEFAULT_STRATEGY[, zdict])

     返回一个 压缩对象，用来压缩内存中难以容下的数据流。

     参数 `level' 为压缩等级，是整数，可取值为 ‘0’ 到 ‘9’ 或 ‘-1’。‘1’
     (Z_BEST_SPEED) 表示最快速度和最低压缩率，‘9’ (Z_BEST_COMPRESSION) 表
     示最慢速度和最高压缩率。‘0’ (Z_NO_COMPRESSION) 表示不压缩。参数默认
     值为 ‘-1’ (Z_DEFAULT_COMPRESSION)。Z_DEFAULT_COMPRESSION 是速度和压
     缩率之间的平衡 (一般相当于设压缩等级为 6)。

     `method' 表示压缩算法。现在只支持 ‘DEFLATED’ 这个算法。

     参数 `wbits' 指定压缩数据时所使用的历史缓冲区的大小 (窗口大小)，并
     指定压缩输出是否包含头部或尾部。参数的默认值是 ‘15’ (MAX_WBITS)。参
     数的值分为几个范围：

        * +9 至 +15：窗口大小以二为底的对数。 即这些值对应着 512 至
          32768 的窗口大小。 更大的值会提供更好的压缩，同时内存开销也会
          更大。 压缩输出会包含 zlib 特定格式的头部和尾部。

        * −9 至 −15：绝对值为窗口大小以二为底的对数。 压缩输出仅包含压缩
          数据，没有头部和尾部。

        * +25 至 +31 = 16 + (9 至 15)：后 4 个比特位为窗口大小以二为底的
          对数。 压缩输出包含一个基本的 ‘gzip’ 头部，并以校验和为尾部。

     参数 `memLevel' 指定内部压缩操作时所占用内存大小。参数取 ‘1’ 到
     ‘9’。更大的值占用更多的内存，同时速度也更快输出也更小。

     参数 `strategy' 用于调节压缩算法。可取值为 ‘Z_DEFAULT_STRATEGY’、
     ‘Z_FILTERED’、‘Z_HUFFMAN_ONLY’、‘Z_RLE’ (zlib 1.2.0.1) 或 ‘Z_FIXED’
     (zlib 1.2.2.2)。

     参数 `zdict' 指定预定义的压缩字典。它是一个字节序列 (如 *note
     bytes: 33a. 对象)，其中包含用户认为要压缩的数据中可能频繁出现的子序
     列。频率高的子序列应当放在字典的尾部。

     在 3.3 版更改: 添加关键字参数 `zdict'。

 -- 函数: zlib.crc32 (data[, value])

     计算 `data' 的 CRC (循环冗余校验) 值。计算的结果是一个 32 位的整数
     。参数 `value' 是校验时的起始值，其默认值为 0。借助参数 `value' 可
     为分段的输入计算校验值。此算法没有加密强度，不应用于身份验证和数字
     签名。此算法的目的仅为验证数据的正确性，不适合作为通用散列算法。

     在 3.0 版更改: 返回值永远是无符号数。要在所有的 Python 版本和平台上
     获得相同的值，请使用 ‘crc32(data) & 0xffffffff’。

 -- 函数: zlib.decompress (data, wbits=MAX_WBITS, bufsize=DEF_BUF_SIZE)

     解压 `data' 中的字节，返回含有已解压内容的 bytes 对象。参数 `wbits'
     取决于 `data' 的格式，具体参见下边的说明。`bufsize' 为输出缓冲区的
     起始大小。函数发生错误时抛出 *note error: 1d51. 异常。 `wbits' 形参
     控制历史缓冲区的大小（或称“窗口大小”）以及所期望的头部和尾部格式。
     它类似于 *note compressobj(): 1d53. 的形参，但可接受更大范围的值：

        * +8 至 +15：窗口尺寸以二为底的对数。 输入必须包含 zlib 头部和尾
          部。

        * 0：根据 zlib 头部自动确定窗口大小。 只从 zlib 1.2.3.5 版起受支
          持。

        * −8 至 −15：使用 `wbits' 的绝对值作为窗口大小以二为底的对数。 输
          入必须为原始数据流，没有头部和尾部。

        * +24 至 +31 = 16 + (8 至 15)：使用后 4 个比特位作为窗口大小以二
          为底的对数。 输入必须包括 gzip 头部和尾部。

        * +40 至 +47 = 32 + (8 至 15)：使用后 4 个比特位作为窗口大小以二
          为底的对数，并且自动接受 zlib 或 gzip 格式。

     当解压缩一个数据流时，窗口大小必须不小于用于压缩数据流的原始窗口大
     小；使用太小的值可能导致 *note error: 1d51. 异常。 默认 `wbits' 值
     对应于最大的窗口大小并且要求包括 zlib 头部和尾部。

     `bufsize' 是用于存放解压数据的缓冲区初始大小。 如果需要更大空间，缓
     冲区大小将按需增加，因此你不需要让这个值完全精确；对其进行调整仅会
     节省一点对 ‘malloc()’ 的调用次数。

     在 3.6 版更改: `wbits' 和 `bufsize' 可用作关键字参数。

 -- 函数: zlib.decompressobj (wbits=MAX_WBITS[, zdict])

     返回一个解压对象，用来解压无法被一次性放入内存的数据流。

     `wbits' 形参控制历史缓冲区的大小（或称“窗口大小”）以及所期望的头部
     和尾部格式。 它的含义与 *note 对 decompress() 的描述: 1d55. 相同。

     `zdict' 形参指定指定一个预定义的压缩字典。 如果提供了此形参，它必须
     与产生将解压数据的压缩器所使用的字典相同。

          注解: 如果 `zdict' 是一个可变对象 (例如 *note bytearray:
          33b.)，则你不可在对 *note decompressobj(): 1d56. 的调用和对解
          压器的 ‘decompress()’ 方法的调用之间修改其内容。

     在 3.3 版更改: 增加了 `zdict' 形参。

压缩对象支持以下方法：

 -- 方法: Compress.compress (data)

     压缩 `data' 并返回 bytes 对象，这个对象含有 `data' 的部分或全部内容
     的已压缩数据。所得的对象必须拼接在上一次调用 *note compress(): 5c7.
     方法所得数据的后面。缓冲区中可能留存部分输入以供下一次调用。

 -- 方法: Compress.flush ([mode])

     压缩所有缓冲区的数据并返回已压缩的数据。参数 `mode' 可以传入的常量
     为：‘Z_NO_FLUSH’、‘Z_PARTIAL_FLUSH’、‘Z_SYNC_FLUSH’、
     ‘Z_FULL_FLUSH’、‘Z_BLOCK’ (zlib 1.2.3.4) 或 ‘Z_FINISH’。默认值为
     ‘Z_FINISH’。‘Z_FINISH’ 关闭已压缩数据流并不允许再压缩其他数据，
     ‘Z_FINISH’ 以外的值皆允许这个对象继续压缩数据。调用 *note flush():
     1d58. 方法并将 `mode' 设为 ‘Z_FINISH’ 后会无法再次调用 *note
     compress(): 5c7.，此时只能删除这个对象。

 -- 方法: Compress.copy ()

     返回此压缩对象的一个拷贝。它可以用来高效压缩一系列拥有相同前缀的数
     据。

在 3.8 版更改: 添加了对压缩对象执行 *note copy.copy(): 3d3. 和 *note
copy.deepcopy(): 3d4. 的支持。

解压缩对象支持以下方法：

 -- 属性: Decompress.unused_data

     一个 bytes 对象，其中包含压缩数据结束之后的任何字节数据。 也就是说
     ，它将为 ‘b""’ 直到包含压缩数据的末尾字节可用。 如果整个结果字节串
     都包含压缩数据，它将为一个空的 bytes 对象 ‘b""’。

 -- 属性: Decompress.unconsumed_tail

     一个 bytes 对象，其中包含未被上一次 *note decompress(): 5c8. 调用所
     消耗的任何数据。 此数据不能被 zlib 机制看到，因此你必须将其送回（可
     能要附带额外的数据拼接）到后续的 *note decompress(): 5c8. 方法调用
     以获得正确的输出。

 -- 属性: Decompress.eof

     一个布尔值，指明是否已到达压缩数据流的末尾。

     这使得区分正确构造的压缩数据流和不完整或被截断的压缩数据流成为可能
     。

     3.3 新版功能.

 -- 方法: Decompress.decompress (data, max_length=0)

     解压缩 `data' 并返回 bytes 对象，其中包含对应于 `string' 中至少一部
     分数据的解压缩数据。 此数据应当被拼接到之前任何对 *note
     decompress(): 5c8. 方法的调用所产生的输出。 部分输入数据可能会被保
     留在内部缓冲区以供后续处理。

     如果可选的形参 `max_length' 非零则返回值将不会长于 `max_length'。 这
     可能意味着不是所有已压缩输入都能被处理；并且未被消耗的数据将被保存
     在 *note unconsumed_tail: 1d5b. 属性中。 如果要继续解压缩则这个字节
     串必须被传给对 *note decompress(): 5c8. 的后续调用。 如果
     `max_length' 为零则整个输入都会被解压缩，并且 *note
     unconsumed_tail: 1d5b. 将为空。

     在 3.6 版更改: `max_length' 可用作关键字参数。

 -- 方法: Decompress.flush ([length])

     所有挂起的输入会被处理，并且返回包含剩余未压缩输出的 bytes 对象。 在
     调用 *note flush(): 1d5d. 之后，*note decompress(): 5c8. 方法将无法
     被再次调用；唯一可行的操作是删除该对象。

     可选的形参 `length' 设置输出缓冲区的初始大小。

 -- 方法: Decompress.copy ()

     返回解压缩对象的一个拷贝。 它可以用来在数据流的中途保存解压缩器的状
     态以便加快随机查找数据流后续位置的速度。

在 3.8 版更改: 添加了对解压缩对象执行 *note copy.copy(): 3d3. 和 *note
copy.deepcopy(): 3d4. 的支持。

通过下列常量可获取模块所使用的 zlib 库的版本信息：

 -- 数据: zlib.ZLIB_VERSION

     构建此模块时所用的 zlib 库的版本字符串。它的值可能与运行时所加载的
     zlib 不同。运行时加载的 zlib 库的版本字符串为 *note
     ZLIB_RUNTIME_VERSION: acf.。

 -- 数据: zlib.ZLIB_RUNTIME_VERSION

     解释器所加载的 zlib 库的版本字符串。

     3.3 新版功能.

参见
....

模块 *note gzip: 8c.

     读写 ‘gzip’ 格式的文件。

‘http://www.zlib.net’

     zlib 库项目主页。

‘http://www.zlib.net/manual.html’

     zlib 库用户手册。提供了库的许多功能的解释和用法。


File: python.info,  Node: gzip --- 对 gzip 格式的支持,  Next: bz2 --- 对 bzip2 压缩算法的支持,  Prev: zlib --- 与 gzip 兼容的压缩,  Up: 数据压缩和存档

5.13.2 ‘gzip’ — 对 ‘gzip’ 格式的支持
------------------------------------

`源代码：' Lib/gzip.py(1)

__________________________________________________________________

此模块提供的简单接口帮助用户压缩和解压缩文件，功能类似于 GNU 应用程序
‘gzip’ 和 ‘gunzip’。

数据压缩由 *note zlib: 145. 模块提供。

*note gzip: 8c. 模块提供 *note GzipFile: 6e6. 类和 *note open(): 1d62.、
*note compress(): 1d2.、*note decompress(): b91. 几个便利的函数。*note
GzipFile: 6e6. 类可以读写 ‘gzip’ 格式的文件，还能自动压缩和解压缩数据，
这让操作压缩文件如同操作普通的 *note file object: b4a. 一样方便。

注意，此模块不支持部分可以被 ‘gzip’ 和 ‘gunzip’ 解压的格式，如利用
‘compress’ 或 ‘pack’ 压缩所得的文件。

这个模块定义了以下内容：

 -- 函数: gzip.open (filename, mode='rb', compresslevel=9,
          encoding=None, errors=None, newline=None)

     以二进制方式或者文本方式打开一个 gzip 格式的压缩文件，返回一个
     *note file object: b4a.。

     `filename' 参数可以是一个实际的文件名(一个a *note str: 339. 对象或
     者 *note bytes: 33a. 对象), 或者是一个用来读写的已存在的文件对象。

     `mode' 参数可以是二进制模式： ‘'r'’, ‘'rb'’, ‘'a'’, ‘'ab'’, ‘'w'’,
     ‘'wb'’, ‘'x'’ or ‘'xb'’ , 或者是文本模式 ‘'rt'’, ‘'at'’, ‘'wt'’, or
     ‘'xt'’。默认值是 ‘'rb'’。

     The `compresslevel' argument is an integer from 0 to 9, as for the
     *note GzipFile: 6e6. constructor.

     对于二进制模式，这个函数等价于 *note GzipFile: 6e6. 构造器：
     ‘GzipFile(filename, mode, compresslevel)’。在这个例子中，
     `encoding', `errors' 和 `newline' 三个参数一定不要设置。

     对于文本模式，将会创建一个 *note GzipFile: 6e6. 对象，并将它封装到
     一个 *note io.TextIOWrapper: 5fc. 实例中， 这个实例默认了指定编码，
     错误抓获行为和行。

     在 3.3 版更改: 支持 `filename' 为一个文件对象，支持文本模式和
     `encoding', `errors' 和 `newline' 参数。

     在 3.4 版更改: 支持 ‘'x'’, ‘'xb'’ 和‘‘’xt’‘‘ 三种模式。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 例外: gzip.BadGzipFile

     针对无效 gzip 文件引发的异常。 它继承自 *note OSError: 1d4.。 针对
     无效 gzip 文件也可能引发 *note EOFError: c74. 和 *note zlib.error:
     1d51.。

     3.8 新版功能.

 -- 类: gzip.GzipFile (filename=None, mode=None, compresslevel=9,
          fileobj=None, mtime=None)

     *note GzipFile: 6e6. 类的构造器支持 ‘truncate()’ 的异常，与 *note
     file object: b4a. 的大多数方法非常相似。`fileobj' 和 `filename' 至
     少有一个不为空。

     新的实例基于 `fileobj'，它可以是一个普通文件，一个 *note
     io.BytesIO: 7a4. 对象，或者任何一个与文件相似的对象。当 `filename'
     是一个文件对象时，它的默认值是 ‘None’。

     当 `fileobj' 为 ‘None’ 时， `filename' 参数只用于 ‘gzip’ 文件头中，
     这个文件有可能包含未压缩文件的源文件名。如果文件可以被识别，默认
     `fileobj' 的文件名；否则默认为空字符串，在这种情况下文件头将不包含
     源文件名。

     `mode' 可以是‘‘’r’‘, ``'rb'’, ‘'a'’, ‘'ab'’, ‘'w'’, ‘'wb'’, ‘'x'’,
     或者 ‘'xb'’，选择哪个取决于是读文件还是写文件。如果可以分辨是，默认
     的模式是 `fileobj'，否则为 ‘'rb'’。

     需要注意的是，文件默认使用二进制模式打开。如果要以文本模式打开文件
     一个压缩文件，请使用 *note open(): 1d62. 方法(或者使用 *note
     io.TextIOWrapper: 5fc. 包装 *note GzipFile: 6e6. )。

     `compresslevel' 参数是一个从 ‘0’ 到 ‘9’ 的整数，用于控制压缩等级；
     ‘1’ 最快但压缩比例最小，‘9’ 最慢但压缩比例最大。 ‘0’ 不压缩。默认为
     ‘9’。

     `mtime' 参数是一个可选的数字时间戳用于写入流的最后修改字段，。
     `mtime' 只在压缩模式中使用。如果省略或者值为 ‘None’，则使用当前时间
     。更多细节，详见 *note mtime: 1d63. 属性。

     调用 *note GzipFile: 6e6. 的 ‘close()’ 方法不会关闭 `fileobj'，因为
     你可以希望增加其它内容到已经压缩的数中。你可以将一个 *note
     io.BytesIO: 7a4. 对象作为 `fileobj'，也可以使用 *note io.BytesIO:
     7a4. 的 *note getvalue(): 1d64. 方法从内存缓存中恢复数据。

     *note GzipFile: 6e6. 支持 *note io.BufferedIOBase: 591. 类的接口, 包
     括迭代和 *note with: 6f2. 语句。只有 ‘truncate()’ 方法没有实现。

     *note GzipFile: 6e6. 还提供了以下的方法和属性:

      -- 方法: peek (n)

          在不移动文件指针的情况下读取 `n' 个未压缩字节。最多只有一个单
          独的读取流来服务这个方法调用。返回的字节数不一定刚好等于要求的
          数量。

               注解: 调用 *note peek(): b90. 并没有改变 *note GzipFile:
               6e6. 的文件指针，它可能改变潜在文件对象(例如： *note
               GzipFile: 6e6. 使用 `fileobj' 参数进行初始化)。

          3.2 新版功能.

      -- 属性: mtime

          在解压的过程中，最后修改时间字段的值可能来自于这个属性，以整数
          的形式出现。在读取任何文件头信息前，初始值为 ‘None’。

          所有 ‘gzip’ 东方压缩流中必须包含时间戳这个字段。以便于像
          ‘gunzip’这样的程序可以使用时间戳。格式与 *note time.time():
          326. 的返回值和 *note os.stat(): 1f2. 对象的 *note st_mtime:
          1d65. 属性值一样。

     在 3.1 版更改: 支持 *note with: 6f2. 语句，构造器参数 `mtime' 和
     *note mtime: 1d63. 属性。

     在 3.2 版更改: 添加了对零填充和不可搜索文件的支持。

     在 3.3 版更改: 实现 *note io.BufferedIOBase.read1(): 1d66. 方法。

     在 3.4 版更改: 支持 ‘'x'’ and ‘'xb'’ 两种模式。

     在 3.5 版更改: 支持写入任意 *note bytes-like objects: 5f1.。*note
     read(): 1d67. 方法可以接受‘‘None‘‘为参数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: gzip.compress (data, compresslevel=9, *, mtime=None)

     压缩 `data'，返回一个包含压缩数据的 *note bytes: 33a. 对象。
     `compresslevel' 和 `mtime' 的含义与上文中 *note GzipFile: 6e6. 构造
     器的相同。

     3.2 新版功能.

     在 3.8 版更改: 添加了 `mtime' 形参用于可重复的输出。

 -- 函数: gzip.decompress (data)

     解压缩 `data'，返回一个包含未压缩数据的 *note bytes: 33a. 对象。

     3.2 新版功能.

* Menu:

* 用法示例::
* 命令行界面::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/gzip.py


File: python.info,  Node: 用法示例,  Next: 命令行界面,  Up: gzip --- 对 gzip 格式的支持

5.13.2.1 用法示例
.................

读取压缩文件示例：

     import gzip
     with gzip.open('/home/joe/file.txt.gz', 'rb') as f:
         file_content = f.read()

创建GZIP 文件示例：

     import gzip
     content = b"Lots of content here"
     with gzip.open('/home/joe/file.txt.gz', 'wb') as f:
         f.write(content)

使用 GZIP 压缩已有的文件示例：

     import gzip
     import shutil
     with open('/home/joe/file.txt', 'rb') as f_in:
         with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
             shutil.copyfileobj(f_in, f_out)

使用 GZIP 压缩二进制字符串示例：

     import gzip
     s_in = b"Lots of content here"
     s_out = gzip.compress(s_in)

参见
....

模块 *note zlib: 145.

     支持 ‘gzip’ 格式所需要的基本压缩模块。


File: python.info,  Node: 命令行界面,  Prev: 用法示例,  Up: gzip --- 对 gzip 格式的支持

5.13.2.2 命令行界面
...................

*note gzip: 8c. 模块提供了简单的命令行界面用于压缩和解压缩文件。

在执行后 *note gzip: 8c. 模块会保留输入文件。

在 3.8 版更改: 添加一个带有用法说明的新命令行界面命令。 默认情况下，当你
要执行 CLI 时，默认压缩等级为 6。

* Menu:

* 命令行选项::


File: python.info,  Node: 命令行选项,  Up: 命令行界面

5.13.2.3 命令行选项
...................

 -- 程序选项: file

     如果 `file' 未指定，则从 *note sys.stdin: 316. 读取。

 -- 程序选项: --fast

     指明最快速的压缩方法（较低压缩率）。

 -- 程序选项: --best

     指明最慢速的压缩方法（最高压缩率）。

 -- 程序选项: -d, --decompress

     解压缩给定的文件。

 -- 程序选项: -h, --help

     显示帮助消息。


File: python.info,  Node: bz2 --- 对 bzip2 压缩算法的支持,  Next: lzma --- 用 LZMA 算法压缩,  Prev: gzip --- 对 gzip 格式的支持,  Up: 数据压缩和存档

5.13.3 ‘bz2’ — 对 ‘bzip2’ 压缩算法的支持
----------------------------------------

`源代码：' Lib/bz2.py(1)

__________________________________________________________________

此模块提供了使用 bzip2 压缩算法压缩和解压数据的一套完整的接口。

*note bz2: 14. 模块包含：

   * 用于读写压缩文件的 *note open(): 9de. 函数和 *note BZ2File: 939. 类
     。

   * 用于增量压缩和解压的 *note BZ2Compressor: 1d73. 和 *note
     BZ2Decompressor: 1d74. 类。

   * 用于一次性压缩和解压的 *note compress(): 1886. 和 *note
     decompress(): 9df. 函数。

此模块中的所有类都能安全地从多个线程访问。

* Menu:

* 文件压缩和解压::
* 增量压缩和解压::
* 一次性压缩或解压缩::
* 用法示例: 用法示例<2>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/bz2.py


File: python.info,  Node: 文件压缩和解压,  Next: 增量压缩和解压,  Up: bz2 --- 对 bzip2 压缩算法的支持

5.13.3.1 文件压缩和解压
.......................

 -- 函数: bz2.open (filename, mode='r', compresslevel=9, encoding=None,
          errors=None, newline=None)

     以二进制或文本模式打开 bzip2 压缩文件，返回一个 *note file object:
     b4a.。

     和 *note BZ2File: 939. 的构造函数类似，`filename' 参数可以是一个实
     际的文件名（*note str: 339. 或 *note bytes: 33a. 对象），或是已有的
     可供读取或写入的文件对象。

     `mode' 参数可设为二进制模式的 ‘'r'’、‘'rb'’、‘'w'’、‘'wb'’、‘'x'’、
     ‘'xb'’、‘'a'’ 或 ‘'ab'’，或者文本模式的 ‘'rt'’、‘'wt'’、‘'xt'’ 或
     ‘'at'’。默认是 ‘'rb'’。

     `compresslevel' 参数是 1 到 9 的整数，和 *note BZ2File: 939. 的构造
     函数一样。

     对于二进制模式，这个函数等价于 *note BZ2File: 939. 构造器:
     ‘BZ2File(filename, mode, compresslevel=compresslevel)’。 在这种情况
     下，不可提供 `encoding', `errors' 和 `newline' 参数。

     对于文本模式，将会创建一个 *note BZ2File: 939. 对象，并将它包装到一
     个 *note io.TextIOWrapper: 5fc. 实例中，此实例带有指定的编码格式、
     错误处理行为和行结束符。

     3.3 新版功能.

     在 3.4 版更改: 添加了 ‘'x'’ (单独创建) 模式。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 类: bz2.BZ2File (filename, mode='r', buffering=None,
          compresslevel=9)

     用二进制模式打开 bzip2 压缩文件。

     如果 `filename' 是一个 *note str: 339. 或 *note bytes: 33a. 对象，
     则打开名称对应的文件目录。 否则的话，`filename' 应当是一个 *note
     file object: b4a.，它将被用来读取或写入压缩数据。

     `mode' 参数可以是表示读取的 ‘'r'’ (默认值)，表示覆写的 ‘'w'’，表示
     单独创建的 ‘'x'’，或表示添加的 ‘'a'’。 这些模式还可分别以 ‘'rb'’,
     ‘'wb'’, ‘'xb'’ 和 ‘'ab'’ 的等价形式给出。

     如果 `filename' 是一个文件对象（而不是实际的文件名），则 ‘'w'’ 模式
     并不会截断文件，而是会等价于 ‘'a'’。

     `buffering' 参数会被忽略。 从 Python 3.0 开始它已被弃用。

     如果 `mode' 为 ‘'w'’ 或 ‘'a'’，则 `compresslevel' 可以是 ‘1’ 到 ‘9’
     之间的整数，用于指定压缩等级: ‘1’ 产生最低压缩率，而 ‘9’ (默认值) 产
     生最高压缩率。

     如果 `mode' 为 ‘'r'’，则输入文件可以为多个压缩流的拼接。

     *note BZ2File: 939. 提供了 *note io.BufferedIOBase: 591. 所指定的所
     有成员，但 ‘detach()’ 和 ‘truncate()’ 除外。 并支持迭代和 *note
     with: 6f2. 语句。

     *note BZ2File: 939. 还提供了以下方法：

      -- 方法: peek ([n])

          返回缓冲的数据而不前移文件位置。 至少将返回一个字节的数据（除
          非为 EOF）。 实际返回的字节数不确定。

               注解: 虽然调用 *note peek(): 1d76. 不会改变 *note
               BZ2File: 939. 的文件位置，但它可能改变下层文件对象的位置
               （举例来说如果 *note BZ2File: 939. 是通过传入一个文件对象
               作为 `filename' 的话）。

          3.3 新版功能.

     3.0 版后已移除: 关键字参数 `buffering' 已弃用，现在会被忽略。

     在 3.1 版更改: 添加了对 *note with: 6f2. 语句的支持。

     在 3.3 版更改: 添加了 ‘fileno()’, ‘readable()’, ‘seekable()’,
     ‘writable()’, ‘read1()’ 和 ‘readinto()’ 方法。

     在 3.3 版更改: 添加了对 `filename' 使用 *note file object: b4a. 而
     非实际文件名的支持。

     在 3.3 版更改: 添加了 ‘'a'’ (append) 模式，以及对读取多数据流文件的
     支持。

     在 3.4 版更改: 添加了 ‘'x'’ (单独创建) 模式。

     在 3.5 版更改: *note read(): 1d67. 方法现在接受 ‘None’ 作为参数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。


File: python.info,  Node: 增量压缩和解压,  Next: 一次性压缩或解压缩,  Prev: 文件压缩和解压,  Up: bz2 --- 对 bzip2 压缩算法的支持

5.13.3.2 增量压缩和解压
.......................

 -- 类: bz2.BZ2Compressor (compresslevel=9)

     创建一个新的压缩器对象。 此对象可被用来执行增量数据压缩。 对于一次
     性压缩，请改用 *note compress(): 1886. 函数。

     如果给定 `compresslevel'，它必须为 ‘1’ 至 ‘9’ 之间的整数。 默认值为
     ‘9’。

      -- 方法: compress (data)

          向压缩器对象提供数据。 在可能的情况下返回一段已压缩数据，否则
          返回空字节串。

          当你已结束向压缩器提供数据时，请调用 *note flush(): 1d79. 方法
          来完成压缩进程。

      -- 方法: flush ()

          结束压缩进程，返回内部缓冲中剩余的压缩完成的数据。

          调用此方法之后压缩器对象将不可再被使用。

 -- 类: bz2.BZ2Decompressor

     创建一个新的解压缩器对象。 此对象可被用来执行增量数据解压缩。 对于
     一次性解压缩，请改用 *note decompress(): 9df. 函数。

          注解: 这个类不会透明地处理包含多个已压缩数据流的输入，这不同于
          *note decompress(): 9df. 和 *note BZ2File: 939.。 如果你需要通
          过 *note BZ2Decompressor: 1d74. 来解压缩多个数据流输入，你必须
          为每个数据流都使用新的解压缩器。

      -- 方法: decompress (data, max_length=-1)

          解压缩 `data' (一个 *note bytes-like object: 5f1.)，返回字节串
          形式的解压缩数据。 某些 `data' 可以在内部被缓冲，以便用于后续
          的 *note decompress(): 9df. 调用。 返回的数据应当与之前任何
          *note decompress(): 9df. 调用的输出进行拼接。

          如果 `max_length' 为非负数，将返回至多 `max_length' 个字节的解
          压缩数据。 如果达到此限制并且可以产生后续输出，则 *note
          needs_input: 1d7a. 属性将被设为 ‘False’。 在这种情况下，下一次
          *note decompress(): 6ac. 调用提供的 `data' 可以为 ‘b''’ 以获取
          更多的输出。

          如果所有输入数据都已被解压缩并返回（或是因为它少于
          `max_length' 个字节，或是因为 `max_length' 为负数），则 *note
          needs_input: 1d7a. 属性将被设为 ‘True’。

          在到达数据流末尾之后再尝试解压缩数据会引发 ‘EOFError’。 在数据
          流末尾之后获取的任何数据都会被忽略并存储至 *note unused_data:
          1d7b. 属性。

          在 3.5 版更改: 添加了 `max_length' 形参。

      -- 属性: eof

          若达到了数据流的末尾标记则为 ‘True’。

          3.3 新版功能.

      -- 属性: unused_data

          在压缩数据流的末尾之后获取的数据。

          如果在达到数据流末尾之前访问此属性，其值将为 ‘b''’。

      -- 属性: needs_input

          如果在要求新的未解压缩输入之前 *note decompress(): 6ac. 方法可
          以提供更多的解压缩数据则为 ‘False’。

          3.5 新版功能.


File: python.info,  Node: 一次性压缩或解压缩,  Next: 用法示例<2>,  Prev: 增量压缩和解压,  Up: bz2 --- 对 bzip2 压缩算法的支持

5.13.3.3 一次性压缩或解压缩
...........................

 -- 函数: bz2.compress (data, compresslevel=9)

     压缩 `data'，此参数为一个 *note 字节类对象: 5f1.。

     如果给定 `compresslevel'，它必须为 ‘1’ 至 ‘9’ 之间的整数。 默认值为
     ‘9’。

     对于增量压缩，请改用 *note BZ2Compressor: 1d73.。

 -- 函数: bz2.decompress (data)

     解压缩 `data'，此参数为一个 *note 字节类对象: 5f1.。

     如果 `data' 是多个压缩数据流的拼接，则解压缩所有数据流。

     对于增量解压缩，请改用 *note BZ2Decompressor: 1d74.。

     在 3.3 版更改: 支持了多数据流的输入。


File: python.info,  Node: 用法示例<2>,  Prev: 一次性压缩或解压缩,  Up: bz2 --- 对 bzip2 压缩算法的支持

5.13.3.4 用法示例
.................

以下是 *note bz2: 14. 模块典型用法的一些示例。

使用 *note compress(): 1886. 和 *note decompress(): 9df. 来显示往复式的
压缩：

     >>> import bz2
     >>> data = b"""\
     ... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
     ... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
     ... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
     ... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
     ... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
     ... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
     ... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
     >>> c = bz2.compress(data)
     >>> len(data) / len(c)  # Data compression ratio
     1.513595166163142
     >>> d = bz2.decompress(c)
     >>> data == d  # Check equality to original object after round-trip
     True

使用 *note BZ2Compressor: 1d73. 进行增量压缩：

     >>> import bz2
     >>> def gen_data(chunks=10, chunksize=1000):
     ...     """Yield incremental blocks of chunksize bytes."""
     ...     for _ in range(chunks):
     ...         yield b"z" * chunksize
     ...
     >>> comp = bz2.BZ2Compressor()
     >>> out = b""
     >>> for chunk in gen_data():
     ...     # Provide data to the compressor object
     ...     out = out + comp.compress(chunk)
     ...
     >>> # Finish the compression process.  Call this once you have
     >>> # finished providing data to the compressor.
     >>> out = out + comp.flush()

上面的示例使用了十分“非随机”的数据流（即 ‘b"z"’ 块数据流）。 随机数据的
压缩率通常很差，而有序、重复的数据通常会产生很高的压缩率。

用二进制模式写入和读取 bzip2 压缩文件：

     >>> import bz2
     >>> data = b"""\
     ... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
     ... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
     ... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
     ... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
     ... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
     ... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
     ... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
     >>> with bz2.open("myfile.bz2", "wb") as f:
     ...     # Write compressed data to file
     ...     unused = f.write(data)
     >>> with bz2.open("myfile.bz2", "rb") as f:
     ...     # Decompress data from file
     ...     content = f.read()
     >>> content == data  # Check equality to original object after round-trip
     True


File: python.info,  Node: lzma --- 用 LZMA 算法压缩,  Next: zipfile --- 使用ZIP存档,  Prev: bz2 --- 对 bzip2 压缩算法的支持,  Up: 数据压缩和存档

5.13.4 ‘lzma’ — 用 LZMA 算法压缩
--------------------------------

3.3 新版功能.

`源代码：' Lib/lzma.py(1)

__________________________________________________________________

此模块提供了可以压缩和解压缩使用 LZMA 压缩算法的数据的类和便携函数。 其
中还包含支持 ‘xz’ 工具所使用的 ‘.xz’ 和旧式 ‘.lzma’ 文件格式的文件接口，
以及相应的原始压缩数据流。

此模块所提供的接口与 *note bz2: 14. 模块的非常类似。 但是，请注意 *note
LZMAFile: 93a. `不是' 线程安全的，这与 *note bz2.BZ2File: 939. 不同，因
此如果你需要在多个线程中使用单个 *note LZMAFile: 93a. 实例，则需要通过锁
来保护它。

 -- 例外: lzma.LZMAError

     当在压缩或解压缩期间或是在初始化压缩器/解压缩器的状态期间发生错误时
     此异常会被引发。

* Menu:

* 读写压缩文件::
* 在内存中压缩和解压缩数据::
* 杂项: 杂项<2>.
* 指定自定义的过滤器链::
* 例子: 例子<5>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/lzma.py


File: python.info,  Node: 读写压缩文件,  Next: 在内存中压缩和解压缩数据,  Up: lzma --- 用 LZMA 算法压缩

5.13.4.1 读写压缩文件
.....................

 -- 函数: lzma.open (filename, mode="rb", *, format=None, check=-1,
          preset=None, filters=None, encoding=None, errors=None,
          newline=None)

     以二进制或文本模式打开 LZMA 压缩文件，返回一个 *note file object:
     b4a.。

     `filename' 参数可以是一个实际的文件名（以 *note str: 339, *note
     bytes: 33a. 或 *note 路径类: 373. 对象的形式给出），在此情况下会打
     开指定名称的文件，或者可以是一个用于读写的现有文件对象。

     `mode' 参数可以是二进制模式的 ‘"r"’, ‘"rb"’, ‘"w"’, ‘"wb"’, ‘"x"’,
     ‘"xb"’, ‘"a"’ 或 ‘"ab"’，或者文本模式的 ‘"rt"’, ‘"wt"’, ‘"xt"’ 或
     ‘"at"’。 默认值为 ‘"rb"’。

     当打开一个文件用于读取时，`format' 和 `filters' 参数具有与 *note
     LZMADecompressor: 1d85. 的参数相同的含义。 在此情况下，`check' 和
     `preset' 参数不应被使用。

     当打开一个文件用于写入的，`format', `check', `preset' 和 `filters'
     参数具有与 *note LZMACompressor: 1d86. 的参数相同的含义。

     对于二进制模式，这个函数等价于 *note LZMAFile: 93a. 构造器:
     ‘LZMAFile(filename, mode, ...)’。 在这种情况下，不可提供
     `encoding', `errors' 和 `newline' 参数。

     对于文本模式，将会创建一个 *note LZMAFile: 93a. 对象，并将它包装到
     一个 *note io.TextIOWrapper: 5fc. 实例中，此实例带有指定的编码格式
     、错误处理行为和行结束符。

     在 3.4 版更改: 增加了对 ‘"x"’, ‘"xb"’ 和 ‘"xt"’ 模式的支持。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 类: lzma.LZMAFile (filename=None, mode="r", *, format=None,
          check=-1, preset=None, filters=None)

     以二进制模式打开一个 LZMA 压缩文件。

     *note LZMAFile: 93a. 可以包装在一个已打开的 *note file object: b4a.
     中，或者是在给定名称的文件上直接操作。 `filename' 参数指定所包装的
     文件对象，或是要打开的文件名称（类型为 *note str: 339, *note bytes:
     33a. 或 *note 路径类: 373. 对象）。 如果是包装现有的文件对象，被包
     装的文件在 *note LZMAFile: 93a. 被关闭时将不会被关闭。

     `mode' 参数可以是表示读取的 ‘"r"’ (默认值)，表示覆写的 ‘"w"’，表示
     单独创建的 ‘"x"’，或表示添加的 ‘"a"’。 这些模式还可以分别以 ‘"rb"’,
     ‘"wb"’, ‘"xb"’ 和 ‘"ab"’ 的等价形式给出。

     如果 `filename' 是一个文件对象（而不是实际的文件名），则 ‘"w"’ 模式
     并不会截断文件，而会等价于 ‘"a"’。

     当打开一个文件用于读取时，输入文件可以为多个独立压缩流的拼接。 它们
     会被作为单个逻辑流被透明地解码。

     当打开一个文件用于读取时，`format' 和 `filters' 参数具有与 *note
     LZMADecompressor: 1d85. 的参数相同的含义。 在此情况下，`check' 和
     `preset' 参数不应被使用。

     当打开一个文件用于写入的，`format', `check', `preset' 和 `filters'
     参数具有与 *note LZMACompressor: 1d86. 的参数相同的含义。

     *note LZMAFile: 93a. 支持 *note io.BufferedIOBase: 591. 所指定的所
     有成员，但 ‘detach()’ 和 ‘truncate()’ 除外。 并支持迭代和 *note
     with: 6f2. 语句。

     也提供以下方法：

      -- 方法: peek (size=-1)

          返回缓冲的数据而不前移文件位置。 至少将返回一个字节的数据，除
          非已经到达 EOF。 实际返回的字节数不确定（会忽略 `size' 参数）
          。

               注解: 虽然调用 *note peek(): 1d87. 不会改变 *note
               LZMAFile: 93a. 的文件位置，但它可能改变下层文件对象的位置
               （举例来说如果 *note LZMAFile: 93a. 是通过传入一个文件对
               象作为 `filename' 的话）。

     在 3.4 版更改: 增加了对 ‘"x"’ 和 ‘"xb"’ 模式的支持。

     在 3.5 版更改: *note read(): 1d67. 方法现在接受 ‘None’ 作为参数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。


File: python.info,  Node: 在内存中压缩和解压缩数据,  Next: 杂项<2>,  Prev: 读写压缩文件,  Up: lzma --- 用 LZMA 算法压缩

5.13.4.2 在内存中压缩和解压缩数据
.................................

 -- 类: lzma.LZMACompressor (format=FORMAT_XZ, check=-1, preset=None,
          filters=None)

     创建一个压缩器对象，此对象可被用来执行增量压缩。

     压缩单个数据块的更便捷方式请参阅 *note compress(): 1d89.。

     `format' 参数指定应当使用哪种容器格式。 可能的值有：

        * 
          ‘FORMAT_XZ’: ‘.xz’ 容器格式。

               这是默认格式。

        * 
          ‘FORMAT_ALONE’: 传统的 ‘.lzma’ 容器格式。

               这种格式相比 ‘.xz’ 更为受限 – 它不支持一致性检查或多重过
               滤器。

        * 
          ‘FORMAT_RAW’: 原始数据流，不使用任何容器格式。

               这个格式描述器不支持一致性检查，并且要求你必须指定一个自
               定义的过滤器链（用于压缩和解压缩）。 此外，以这种方式压缩
               的数据不可使用 ‘FORMAT_AUTO’ 来解压缩 (参见 *note
               LZMADecompressor: 1d85.)。

     `check' 参数指定要包含在压缩数据中的一致性检查类型。 这种检查在解压
     缩时使用，以确保数据没有被破坏。 可能的值是：

        * ‘CHECK_NONE’: 没有一致性检查。 这是 ‘FORMAT_ALONE’ 和
          ‘FORMAT_RAW’ 的默认值（也是唯一可接受的值）。

        * ‘CHECK_CRC32’: 32 位循环冗余检查。

        * ‘CHECK_CRC64’: 64 位循环冗余检查。 这是 ‘FORMAT_XZ’ 的默认值。

        * ‘CHECK_SHA256’: 256 位安全哈希算法。

     如果指定的检查不受支持，则会引发 *note LZMAError: 1d82.。

     压缩设置可被指定为一个预设的压缩等级（通过 `preset' 参数）或以自定
     义过滤器链来详细设置（通过 `filters' 参数）。

     `preset' 参数（如果提供）应当为一个 ‘0’ 到 ‘9’ (包括边界) 之间的整
     数，可以选择与常数 ‘PRESET_EXTREME’ 进行 OR 运算。 如果 `preset' 和
     `filters' 均未给出，则默认行为是使用 ‘PRESET_DEFAULT’ (预设等级
     ‘6’)。 更高的预设等级会产生更小的输出，但会使得压缩过程更缓慢。

          注解: 除了更加 CPU 密集，使用更高的预设等级来压缩还需要更多的
          内存（并产生需要更多内存来解压缩的输出）。 例如使用预设等级
          ‘9’ 时，一个 *note LZMACompressor: 1d86. 对象的开销可以高达
          800 MiB。 出于这样的原因，通常最好是保持使用默认预设等级。

     `filters' 参数（如果提供）应当指定一个过滤器链。 详情参见 *note
     指定自定义的过滤器链: 1d8a.。

      -- 方法: compress (data)

          压缩 `data' (一个 *note bytes: 33a. object)，返回包含针对输入
          的至少一部分已压缩数据的 *note bytes: 33a. 对象。 一部 `data'
          可能会被放入内部缓冲区，以便用于后续的 *note compress(): 1d89.
          和 *note flush(): 1d8c. 调用。 返回的数据应当与之前任何 *note
          compress(): 1d89. 调用的输出进行拼接。

      -- 方法: flush ()

          结束压缩进程，返回包含保存在压缩器的内部缓冲区中的任意数据的
          *note bytes: 33a. 对象。

          调用此方法之后压缩器将不可再被使用。

 -- 类: lzma.LZMADecompressor (format=FORMAT_AUTO, memlimit=None,
          filters=None)

     创建一个压缩器对象，此对象可被用来执行增量解压缩。

     一次性解压缩整个压缩数据流的更便捷方式请参阅 *note decompress():
     1d8d.。

     `format' 参数指定应当被使用的容器格式。 默认值为 ‘FORMAT_AUTO’，它
     可以解压缩 ‘.xz’ 和 ‘.lzma’ 文件。 其他可能的值为 ‘FORMAT_XZ’,
     ‘FORMAT_ALONE’ 和 ‘FORMAT_RAW’。

     `memlimit' 参数指定解压缩器可以使用的内存上限（字节数）。 当使用此
     参数时，如果不可能在给定内存上限之内解压缩输入数据则解压缩将失败并
     引发 *note LZMAError: 1d82.。

     `filters' 参数指定用于创建被解压缩数据流的过滤器链。 此参数在
     `format' 为 ‘FORMAT_RAW’ 时要求提供，但对于其他格式不应使用。 有关
     过滤器链的更多信息请参阅 *note 指定自定义的过滤器链: 1d8a.。

          注解: 这个类不会透明地处理包含多个已压缩数据流的输入，这不同于
          *note decompress(): 1d8d. 和 *note LZMAFile: 93a.。 要通过
          *note LZMADecompressor: 1d85. 来解压缩多个数据流输入，你必须为
          每个数据流都创建一个新的解压缩器。

      -- 方法: decompress (data, max_length=-1)

          解压缩 `data' (一个 *note bytes-like object: 5f1.)，返回字节串
          形式的解压缩数据。 某些 `data' 可以在内部被缓冲，以便用于后续
          的 *note decompress(): 1d8d. 调用。 返回的数据应当与之前任何
          *note decompress(): 1d8d. 调用的输出进行拼接。

          如果 `max_length' 为非负数，将返回至多 `max_length' 个字节的解
          压缩数据。 如果达到此限制并且可以产生后续输出，则 *note
          needs_input: 1d8e. 属性将被设为 ‘False’。 在这种情况下，下一次
          *note decompress(): 71d. 调用提供的 `data' 可以为 ‘b''’ 以获取
          更多的输出。

          如果所有输入数据都已被解压缩并返回（或是因为它少于
          `max_length' 个字节，或是因为 `max_length' 为负数），则 *note
          needs_input: 1d8e. 属性将被设为 ‘True’。

          在到达数据流末尾之后再尝试解压缩数据会引发 ‘EOFError’。 在数据
          流末尾之后获取的任何数据都会被忽略并存储至 *note unused_data:
          1d8f. 属性。

          在 3.5 版更改: 添加了 `max_length' 形参。

      -- 属性: check

          输入流使用的一致性检查的 ID。 这可能为 ‘CHECK_UNKNOWN’ 直到已
          解压了足够的输入数据来确定它所使用的一致性检查。

      -- 属性: eof

          若达到了数据流的末尾标记则为 ‘True’。

      -- 属性: unused_data

          在压缩数据流的末尾之后获取的数据。

          在达到数据流末尾之前，这个值将为 ‘b""’。

      -- 属性: needs_input

          如果在要求新的未解压缩输入之前 *note decompress(): 71d. 方法可
          以提供更多的解压缩数据则为 ‘False’。

          3.5 新版功能.

 -- 函数: lzma.compress (data, format=FORMAT_XZ, check=-1, preset=None,
          filters=None)

     压缩 `data' (一个 *note bytes: 33a. 对象)，返回包含压缩数据的 *note
     bytes: 33a. 对象。

     参见上文的 *note LZMACompressor: 1d86. 了解有关 `format', `check',
     `preset' 和 `filters' 参数的说明。

 -- 函数: lzma.decompress (data, format=FORMAT_AUTO, memlimit=None,
          filters=None)

     解压缩 `data' (一个 *note bytes: 33a. 对象)，返回包含解压缩数据的
     *note bytes: 33a. 对象。

     如果 `data' 是多个单独压缩数据流的拼接，则解压缩所有相应数据流，并
     返回结果的拼接。

     参见上文的 *note LZMADecompressor: 1d85. 了解有关 `format',
     `memlimit' 和 `filters' 参数的说明。


File: python.info,  Node: 杂项<2>,  Next: 指定自定义的过滤器链,  Prev: 在内存中压缩和解压缩数据,  Up: lzma --- 用 LZMA 算法压缩

5.13.4.3 杂项
.............

 -- 函数: lzma.is_check_supported (check)

     如果本系统支持给定的一致性检查则返回 ‘True’。

     ‘CHECK_NONE’ 和 ‘CHECK_CRC32’ 总是受支持。 ‘CHECK_CRC64’ 和
     ‘CHECK_SHA256’ 或许不可用，如果你正在使用基于受限制特性集编译的
     ‘liblzma’ 版本的话。


File: python.info,  Node: 指定自定义的过滤器链,  Next: 例子<5>,  Prev: 杂项<2>,  Up: lzma --- 用 LZMA 算法压缩

5.13.4.4 指定自定义的过滤器链
.............................

过滤器链描述符是由字典组成的序列，其中每个字典包含单个过滤器的 ID 和选项
。 每个字典必须包含键 ‘"id"’，并可能包含额外的键用来指定基于过滤器的选项
。 有效的过滤器 ID 如下：

   * 
     压缩过滤器：

             * ‘FILTER_LZMA1’ (配合 ‘FORMAT_ALONE’ 使用)

             * ‘FILTER_LZMA2’ (配合 ‘FORMAT_XZ’ 和 ‘FORMAT_RAW’ 使用)

   * 
     Delta 过滤器：

             * ‘FILTER_DELTA’

   * 
     Branch-Call-Jump (BCJ) 过滤器：

             * ‘FILTER_X86’

             * ‘FILTER_IA64’

             * ‘FILTER_ARM’

             * ‘FILTER_ARMTHUMB’

             * ‘FILTER_POWERPC’

             * ‘FILTER_SPARC’

一个过滤器链最多可由 4 个过滤器组成，并且不能为空。 过滤器链中的最后一个
过滤器必须为压缩过滤器，其他过滤器必须为 Delta 或 BCJ 过滤器。

压缩过滤器支持下列选项（指定为表示过滤器的字典中的附加条目）：

        * ‘preset’: 压缩预设选项，用于作为未显式指定的选项的默认值的来源
          。

        * ‘dict_size’: 以字节表示的字典大小。 这应当在 4 KiB 和 1.5 GiB
          之间（包含边界）。

        * ‘lc’: 字面值上下文的比特数。

        * ‘lp’: 字面值位置的比特数。 总计值 ‘lc + lp’ 必须不大于 4。

        * ‘pb’: 位置的比特数；必须不大于 4。

        * ‘mode’: ‘MODE_FAST’ 或 ‘MODE_NORMAL’。

        * ‘nice_len’: 对于一个匹配应当被视为“适宜长度”的值。 这应当小于
          或等于 273。

        * ‘mf’: 要使用的匹配查找器 – ‘MF_HC3’, ‘MF_HC4’, ‘MF_BT2’,
          ‘MF_BT3’ 或 ‘MF_BT4’。

        * ‘depth’: 匹配查找器使用的最大查找深度。 0 (默认值) 表示基于其
          他过滤器选项自动选择。

Delta 过滤器保存字节数据之间的差值，在特定环境下可产生更具重复性的输入。
它支持一个 ‘dist’ 选项，指明要减去的字节之间的差值大小。 默认值为 1，即
相邻字节之间的差值。

BCJ 过滤器主要作用于机器码。 它们会转换机器码内的相对分支、调用和跳转以
使用绝对寻址，其目标是提升冗余度以供压缩器利用。 这些过滤器支持一个
‘start_offset’ 选项，指明应当被映射到输入数据开头的地址。 默认值为 0。


File: python.info,  Node: 例子<5>,  Prev: 指定自定义的过滤器链,  Up: lzma --- 用 LZMA 算法压缩

5.13.4.5 例子
.............

在已压缩的数据中读取:

     import lzma
     with lzma.open("file.xz") as f:
         file_content = f.read()

创建一个压缩文件:

     import lzma
     data = b"Insert Data Here"
     with lzma.open("file.xz", "w") as f:
         f.write(data)

在内存中压缩文件:

     import lzma
     data_in = b"Insert Data Here"
     data_out = lzma.compress(data_in)

增量压缩:

     import lzma
     lzc = lzma.LZMACompressor()
     out1 = lzc.compress(b"Some data\n")
     out2 = lzc.compress(b"Another piece of data\n")
     out3 = lzc.compress(b"Even more data\n")
     out4 = lzc.flush()
     # Concatenate all the partial results:
     result = b"".join([out1, out2, out3, out4])

写入已压缩数据到已打开的文件:

     import lzma
     with open("file.xz", "wb") as f:
         f.write(b"This data will not be compressed\n")
         with lzma.open(f, "w") as lzf:
             lzf.write(b"This *will* be compressed\n")
         f.write(b"Not compressed\n")

使用自定义过滤器链创建一个已压缩文件:

     import lzma
     my_filters = [
         {"id": lzma.FILTER_DELTA, "dist": 5},
         {"id": lzma.FILTER_LZMA2, "preset": 7 | lzma.PRESET_EXTREME},
     ]
     with lzma.open("file.xz", "w", filters=my_filters) as f:
         f.write(b"blah blah blah")


File: python.info,  Node: zipfile --- 使用ZIP存档,  Next: tarfile --- 读写tar归档文件,  Prev: lzma --- 用 LZMA 算法压缩,  Up: 数据压缩和存档

5.13.5 ‘zipfile’ — 使用ZIP存档
------------------------------

`源代码：' Lib/zipfile.py(1)

__________________________________________________________________

ZIP 文件格式是一个常用的归档与压缩标准。 这个模块提供了创建、读取、写入
、添加及列出 ZIP 文件的工具。 任何对此模块的进阶使用都将需要理解此格式，
其定义参见 PKZIP 应用程序笔记(2)。

此模块目前不能处理分卷 ZIP 文件。它可以处理使用 ZIP64 扩展（超过 4 GB 的
ZIP 文件）的 ZIP 文件。它支持解密 ZIP 归档中的加密文件，但是目前不能创建
一个加密的文件。解密非常慢，因为它是使用原生 Python 而不是 C 实现的。

这个模块定义了以下内容：

 -- 例外: zipfile.BadZipFile

     为损坏的 ZIP 文件抛出的错误。

     3.2 新版功能.

 -- 例外: zipfile.BadZipfile

     *note BadZipFile: 1d98. 的别名，与旧版本 Python 保持兼容性。

     3.2 版后已移除.

 -- 例外: zipfile.LargeZipFile

     当 ZIP 文件需要 ZIP64 功能但是未启用时会抛出此错误。

 -- 类: zipfile.ZipFile

     用于读写 ZIP 文件的类。 欲了解构造函数的描述，参阅段落 *note
     ZipFile 对象: 1d9b.。

 -- 类: zipfile.Path

     用于 zip 文件的兼容 pathlib 的包装器。 详情参见 *note Path 对象:
     1d9c.。

     3.8 新版功能.

 -- 类: zipfile.PyZipFile

     用于创建包含 Python 库的 ZIP 归档的类。

 -- 类: zipfile.ZipInfo (filename='NoName', date_time=(1980, 1, 1, 0, 0,
          0))

     用于表示档案内一个成员信息的类。 此类的实例会由 *note ZipFile: 427.
     对象的 *note getinfo(): 1d9d. 和 *note infolist(): 1d9e. 方法返回。
     大多数 *note zipfile: 143. 模块的用户都不必创建它们，只需使用此模块
     所创建的实例。 `filename' 应当是档案成员的全名，`date_time' 应当是
     包含六个字段的描述最近修改时间的元组；这些字段的描述请参阅 *note
     ZipInfo 对象: 1d9f.。

 -- 函数: zipfile.is_zipfile (filename)

     根据文件的 Magic Number，如果 `filename' 是一个有效的 ZIP 文件则返
     回 ‘True’，否则返回 ‘False’。 `filename' 也可能是一个文件或类文件对
     象。

     在 3.1 版更改: 支持文件或类文件对象。

 -- 数据: zipfile.ZIP_STORED

     未被压缩的归档成员的数字常数。

 -- 数据: zipfile.ZIP_DEFLATED

     常用的 ZIP 压缩方法的数字常数。需要 *note zlib: 145. 模块。

 -- 数据: zipfile.ZIP_BZIP2

     BZIP2 压缩方法的数字常数。需要 *note bz2: 14. 模块。

     3.3 新版功能.

 -- 数据: zipfile.ZIP_LZMA

     LZMA 压缩方法的数字常数。需要 *note lzma: ae. 模块。

     3.3 新版功能.

          注解: ZIP 文件格式规范包括自 2001 年以来对 bzip2 压缩的支持，
          以及自 2006 年以来对 LZMA 压缩的支持。但是，一些工具（包括较旧
          的 Python 版本）不支持这些压缩方法，并且可能拒绝完全处理 ZIP 文
          件，或者无法提取单个文件。

参见
....

PKZIP 应用程序笔记(3)

     Phil Katz 编写的 ZIP 文件格式文档，此格式和使用的算法的创建者。

Info-ZIP 主页(4)

     有关 Info-ZIP 项目的 ZIP 存档程序和开发库的信息。

* Menu:

* ZipFile 对象::
* Path 对象::
* PyZipFile 对象::
* ZipInfo 对象::
* 命令行界面: 命令行界面<2>.
* 解压缩的障碍::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/zipfile.py

   (2) https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT

   (3) https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT

   (4) http://www.info-zip.org/


File: python.info,  Node: ZipFile 对象,  Next: Path 对象,  Up: zipfile --- 使用ZIP存档

5.13.5.1 ZipFile 对象
.....................

 -- 类: zipfile.ZipFile (file, mode='r', compression=ZIP_STORED,
          allowZip64=True, compresslevel=None, *,
          strict_timestamps=True)

     打开一个 ZIP 文件，`file' 为一个指向文件的路径（字符串），一个类文
     件对象或者一个 *note path-like object: 373.。

     形参 `mode' 应当为 ‘'r'’ 来读取一个存在的文件，‘'w'’ 来截断并写入新
     的文件， ‘'a'’ 来添加到一个存在的文件，或者 ‘'x'’ 来仅新建并写入新
     的文件。如果 `mode' 为 ‘'x'’ 并且 `file' 指向已经存在的文件，则抛出
     *note FileExistsError: 960.。如果 `mode' 为 ‘'a'’ 且 `file' 为已存
     在的文件，则格外的文件将被加入。如果 `file' 不指向 ZIP 文件，之后一
     个新的 ZIP 归档将被追加为此文件。这是为了将 ZIP 归档添加到另一个文
     件（例如 ‘python.exe’）。如果 `mode' 为 ‘'a'’ 并且文件不存在， 则会
     新建。如果 `mode' 为 ‘'r'’ 或 ‘'a'’， 则文件应当可定位。

     `compression' 是在写入归档时要使用的 ZIP 压缩方法，应为 *note
     ZIP_STORED: 1da0, *note ZIP_DEFLATED: 1da1, *note ZIP_BZIP2: 1da2.
     或 *note ZIP_LZMA: 1da3.；不可识别的值将导致引发 *note
     NotImplementedError: 617.。 如果指定了 *note ZIP_DEFLATED: 1da1,
     *note ZIP_BZIP2: 1da2. 或 *note ZIP_LZMA: 1da3. 但相应的模块 (*note
     zlib: 145, *note bz2: 14. 或 *note lzma: ae.) 不可用，则会引发
     *note RuntimeError: 2bb.。 默认值为 *note ZIP_STORED: 1da0.。

     如果 `allowZip64' 为 ‘True’ (默认值) 则当 zipfile 大于 4 GiB 时
     zipfile 将创建使用 ZIP64 扩展的 ZIP 文件。 如果该参数为 ‘false’ 则
     当 ZIP 文件需要 ZIP64 扩展时 *note zipfile: 143. 将引发异常。

     `compresslevel' 形参控制在将文件写入归档时要使用的压缩等级。 当使用
     *note ZIP_STORED: 1da0. 或 *note ZIP_LZMA: 1da3. 时无压缩效果。 当
     使用 *note ZIP_DEFLATED: 1da1. 时接受整数 ‘0’ 至 ‘9’ (更多信息参见
     *note zlib: 1d53.)。 当使用 *note ZIP_BZIP2: 1da2. 时接受整数 ‘1’ 至
     ‘9’ (更多信息参见 *note bz2: 939.)。

     `strict_timestamps' 参数在设为 ‘False’ 时允许压缩早于 1980-01-01 的
     文件，代价时会将时间戳设为 1980-01-01。 类似的行为也会对晚于
     2107-12-31 的文件发生，时间戳也会被设为该上限值。

     如果创建文件时使用 ‘'w'’, ‘'x'’ 或 ‘'a'’ 模式并且未向归档添加任何文
     件就执行了 *note closed: 1da5.，则会将适当的空归档 ZIP 结构写入文件
     。

     ZipFile 也是一个上下文管理器，因此支持 *note with: 6f2. 语句。 在这
     个示例中，`myzip' 将在 ‘with’ 语句块执行完成之后被关闭 — 即使是发生
     了异常:

          with ZipFile('spam.zip', 'w') as myzip:
              myzip.write('eggs.txt')

     3.2 新版功能: 添加了将 *note ZipFile: 427. 用作上下文管理员的功能。

     在 3.3 版更改: 添加了对 *note bzip2: 14. 和 *note lzma: ae. 压缩的
     支持。

     在 3.4 版更改: 默认启用 ZIP64 扩展。

     在 3.5 版更改: 添加了对不可查找数据流的支持。 并添加了对 ‘'x'’ 模式
     的支持。

     在 3.6 版更改: 在此之前，对于不可识别的压缩值将引发普通的 *note
     RuntimeError: 2bb.。

     在 3.6.2 版更改: `file' 形参接受一个 *note path-like object: 373.。

     在 3.7 版更改: 添加了 `compresslevel' 形参。

     3.8 新版功能: `strict_timestamps' 仅限关键字参数

 -- 方法: ZipFile.close ()

     关闭归档文件。 你必须在退出程序之前调用 *note close(): 1da5. 否则将
     不会写入关键记录数据。

 -- 方法: ZipFile.getinfo (name)

     返回一个 *note ZipInfo: 5c3. 对象，其中包含有关归档成员 `name' 的信
     息。 针对一个目前并不包含于归档中的名称调用 *note getinfo(): 1d9d.
     将会引发 *note KeyError: 2c8.。

 -- 方法: ZipFile.infolist ()

     返回一个列表，其中包含每个归档成员的 *note ZipInfo: 5c3. 对象。 如
     果是打开一个现有归档则这些对象的排列顺序与它们对应条目在磁盘上的实
     际 ZIP 文件中的顺序一致。

 -- 方法: ZipFile.namelist ()

     返回按名称排序的归档成员列表。

 -- 方法: ZipFile.open (name, mode='r', pwd=None, *, force_zip64=False)

     以二进制文件类对象的形式访问一个归档成员。 `name' 可以是归档内某个
     文件的名称也可以是某个 *note ZipInfo: 5c3. 对象。 如果包含了 `mode'
     形参，则它必须为 ‘'r'’ (默认值) 或 ‘'w'’。 `pwd' 为用于解密已加密
     ZIP 文件的密码。

     *note open(): 5c5. 也是一个上下文管理器，因此支持 *note with: 6f2.
     语句:

          with ZipFile('spam.zip') as myzip:
              with myzip.open('eggs.txt') as myfile:
                  print(myfile.read())

     如果 `mode' 为 ‘'r'’ 则文件类对象 (‘ZipExtFile’) 将为只读并且提供下
     列方法: *note read(): 1d67, *note readline(): 1713, *note
     readlines(): 17a0, *note seek(): 1da7, *note tell(): 1da8, *note
     __iter__(): 517, *note __next__(): c6c.。 这些对象可独立于 ZipFile
     进行操作。

     如果 ‘mode='w'’ 则返回一个可写入的文件句柄，它将支持 *note write():
     592. 方法。 当一个可写入的文件句柄被打开时，尝试读写 ZIP 文件中的其
     他文件将会引发 *note ValueError: 1fc.。

     当写入一个文件时，如果文件大小不能预先确定但是可能超过 2 GiB，可传
     入 ‘force_zip64=True’ 以确保标头格式能够支持超大文件。 如果文件大小
     可以预先确定，则在构造 *note ZipInfo: 5c3. 对象时应设置 *note
     file_size: 1da9.，并将其用作 `name' 形参。

          注解: *note open(): 5c5, *note read(): cc1. 和 *note
          extract(): 1daa. 方法可接受文件名或 *note ZipInfo: 5c3. 对象。
          当尝试读取一个包含重复名称成员的 ZIP 文件时你将发现此功能很有
          好处。

     在 3.6 版更改: 移除了对 ‘mode='U'’ 的支持。 请使用 *note
     io.TextIOWrapper: 5fc. 以在 *note universal newlines: 5fd. 模式中读
     取已压缩的文本文件。

     在 3.6 版更改: *note open(): 4f8. 现在可以被用来配合 ‘mode='w'’ 选
     项来将文件写入归档。

     在 3.6 版更改: 在已关闭的 ZipFile 上调用 *note open(): 5c5. 将引发
     *note ValueError: 1fc.。 在之前的版本中则会引发 *note RuntimeError:
     2bb.。

 -- 方法: ZipFile.extract (member, path=None, pwd=None)

     从归档中提取出一个成员放入当前工作目录；`member' 必须为成员的完整名
     称或 *note ZipInfo: 5c3. 对象。 成员的文件信息会尽可能精确地被提取
     。 `path' 指定一个要提取到的不同目录。 `member' 可以是一个文件名或
     *note ZipInfo: 5c3. 对象。 `pwd' 是用于解密文件的密码。

     返回所创建的经正规化的路径（对应于目录或新文件）。

          注解: 如果一个成员文件名为绝对路径，则将去掉驱动器/UNC共享点和
          前导的（反）斜杠，例如: ‘///foo/bar’ 在 Unix 上将变为
          ‘foo/bar’，而 ‘C:\foo\bar’ 在 Windows 上将变为 ‘foo\bar’。 并
          且一个成员文件名中的所有 ‘".."’ 都将被移除，例如:
          ‘../../foo../../ba..r’ 将变为 ‘foo../ba..r’。 在 Windows 上非
          法字符 (‘:’, ‘<’, ‘>’, ‘|’, ‘"’, ‘?’, and ‘*’) 会被替换为下划
          线 (‘_’)。

     在 3.6 版更改: 在已关闭的 ZipFile 上调用 *note extract(): 1daa. 将
     引发 *note ValueError: 1fc.。 在之前的版本中则将引发 *note
     RuntimeError: 2bb.。

     在 3.6.2 版更改: `path' 形参接受一个 *note path-like object: 373.。

 -- 方法: ZipFile.extractall (path=None, members=None, pwd=None)

     从归档中提取出所有成员放入当前工作目录。 `path' 指定一个要提取到的
     不同目录。 `members' 为可选项且必须为 *note namelist(): 1da6. 所返
     回列表的一个子集。 `pwd' 是用于解密文件的密码。

          警告: 绝不要未经预先检验就从不可靠的源中提取归档文件。 这样有
          可能在 `path' 之外创建文件，例如某些成员具有以 ‘"/"’ 开始的文
          件名或带有两个点号 ‘".."’ 的文件名。 此模块会尝试防止这种情况
          。 参见 *note extract(): 1daa. 的注释。

     在 3.6 版更改: 在已关闭的 ZipFile 上调用 *note extractall(): 1dab.
     将引发 *note ValueError: 1fc.。 在之前的版本中则将引发 *note
     RuntimeError: 2bb.。

     在 3.6.2 版更改: `path' 形参接受一个 *note path-like object: 373.。

 -- 方法: ZipFile.printdir ()

     将归档的目录表打印到 ‘sys.stdout’。

 -- 方法: ZipFile.setpassword (pwd)

     设置 `pwd' 为用于提取已加密文件的默认密码。

 -- 方法: ZipFile.read (name, pwd=None)

     返回归档中文件 `name' 的字节数据。 `name' 是归档中文件的名称，或是
     一个 *note ZipInfo: 5c3. 对象。 归档必须以读取或追加方式打开。
     `pwd' 为用于已加密文件的密码，并且如果指定该参数则它将覆盖通过
     *note setpassword(): 1dad. 设置的默认密码。 on a ZipFile that uses
     a compression method 在使用 *note ZIP_STORED: 1da0. , *note
     ZIP_DEFLATED: 1da1, *note ZIP_BZIP2: 1da2. 或 *note ZIP_LZMA: 1da3.
     以外的压缩方法的 ZipFile 上调用 *note read(): cc1. 将引发 *note
     NotImplementedError: 617.。 如果相应的压缩模块不可用也会引发错误。

     在 3.6 版更改: 在已关闭的 ZipFile 上调用 *note read(): cc1. 将引发
     *note ValueError: 1fc.。 在之前的版本中则会引发 *note RuntimeError:
     2bb.。

 -- 方法: ZipFile.testzip ()

     读取归档中的所有文件并检查它们的 CRC 和文件头。 返回第一个已损坏文
     件的名称，在其他情况下则返回 ‘None’。

     在 3.6 版更改: 在已关闭的 ZipFile 上调用 *note testzip(): 1dae. 将
     引发 *note ValueError: 1fc.。 在之前的版本中则将引发 *note
     RuntimeError: 2bb.。

 -- 方法: ZipFile.write (filename, arcname=None, compress_type=None,
          compresslevel=None)

     将名为 `filename' 的文件写入归档，给予的归档名为 `arcname' (默认情
     况下将与 `filename' 一致，但是不带驱动器盘符并会移除开头的路径分隔
     符)。 `compress_type' 如果给出，它将覆盖作为构造器 `compression' 形
     参对于新条目所给出的值。 类似地，`compresslevel' 如果给出也将覆盖构
     造器。 归档必须使用 ‘'w'’, ‘'x'’ 或 ‘'a'’ 模式打开。

          注解: 归档名称应当是基于归档根目录的相对路径，也就是说，它们不
          应以路径分隔符开头。

          注解: 如果 ‘arcname’ (或 ‘filename’，如果 ‘arcname’ 未给出) 包
          含一个空字节，则归档中该文件的名称将在空字节位置被截断。

     在 3.6 版更改: 在使用 ‘'r'’ 模式创建的 ZipFile 或已关闭的 ZipFile 上
     调用 *note write(): 618. 将引发 *note ValueError: 1fc.。 在之前的版
     本中则会引发 *note RuntimeError: 2bb.。

 -- 方法: ZipFile.writestr (zinfo_or_arcname, data, compress_type=None,
          compresslevel=None)

     将一个文件写入归档。 内容为 `data'，它可以是一个 *note str: 339. 或
     *note bytes: 33a. 的实例；如果是 *note str: 339.，则会先使用 UTF-8
     进行编码。 `zinfo_or_arcname' 可以是它在归档中将被给予的名称，或者
     是 *note ZipInfo: 5c3. 的实例。 如果它是一个实例，则至少必须给定文
     件名、日期和时间。 如果它是一个名称，则日期和时间会被设为当前日期和
     时间。 归档必须以 ‘'w'’, ‘'x'’ 或 ‘'a'’ 模式打开。

     如果给定了 `compress_type'，它将会覆盖作为新条目构造器的
     `compression' 形参或在 `zinfo_or_arcname' (如果是一个 *note
     ZipInfo: 5c3. 实例) 中所给出的值。 类似地，如果给定了
     `compresslevel'，它将会覆盖构造器。

          注解: 当传入一个 *note ZipInfo: 5c3. 实例作为
          `zinfo_or_arcname' 形参时，所使用的压缩方法将为在给定的 *note
          ZipInfo: 5c3. 实例的 `compress_type' 成员中指定的方法。 默认情
          况下，*note ZipInfo: 5c3. 构造器将将此成员设为 *note
          ZIP_STORED: 1da0.。

     在 3.2 版更改: `compress_type' 参数。

     在 3.6 版更改: 在使用 ‘'r'’ 模式创建的 ZipFile 或已关闭的 ZipFile 上
     调用 *note writestr(): cc3. 将引发 *note ValueError: 1fc.。 在之前
     的版本中则会引发 *note RuntimeError: 2bb.。

以下数据属性也是可用的:

 -- 属性: ZipFile.filename

     ZIP 文件的名称。

 -- 属性: ZipFile.debug

     要使用的调试输出等级。 这可以设为从 ‘0’ (默认无输出) 到 ‘3’ (最多输
     出) 的值。 调试信息会被写入 ‘sys.stdout’。

 -- 属性: ZipFile.comment

     关联到 ZIP 文件的 *note bytes: 33a. 对象形式的说明。 如果将说明赋给
     以 ‘'w'’, ‘'x'’ 或 ‘'a'’ 模式创建的 *note ZipFile: 427. 实例，它的
     长度不应超过 65535 字节。 超过此长度的说明将被截断。


File: python.info,  Node: Path 对象,  Next: PyZipFile 对象,  Prev: ZipFile 对象,  Up: zipfile --- 使用ZIP存档

5.13.5.2 Path 对象
..................

 -- 类: zipfile.Path (root, at='')

     根据 ‘root’ zipfile (它可以是一个 *note ZipFile: 427. 实例或适合传
     给 *note ZipFile: 427. 构造器的 ‘file’) 构造一个 Path 对象。

     ‘at’ 指定此 Path 在 zipfile 中的位置，例如 ’dir/file.txt’, ’dir/’ 或
     ’’。 默认为空字符串，即指定跟目录。

Path 对象会公开 *note pathlib.Path: 202. 对象的下列特性:

Path 对象可以使用 ‘/’ 操作符进行遍历。

 -- 属性: Path.name

     最终的路径组成部分。

 -- 方法: Path.open (*, **)

     在当前路径上发起调用 *note ZipFile.open(): 5c5.。 接受与 *note
     ZipFile.open(): 5c5. 相同的参数。

          警告: 此函数的签名在 Python 3.9 版进行了不兼容的改变。 想要编
          写对未来版本兼容的程序，请考虑使用第三方的 zipp.Path 包（3.0 或
          更新的版本）。

 -- 方法: Path.iterdir ()

     枚举当前目录的子目录。

 -- 方法: Path.is_dir ()

     如果当前上下文引用了一个目录则返回 ‘True’。

 -- 方法: Path.is_file ()

     如果当前上下文引用了一个文件则返回 ‘True’。

 -- 方法: Path.exists ()

     如果当前上下文引用了 zip 文件内的一个文件或目录则返回 ‘True’。

 -- 方法: Path.read_text (*, **)

     读取当前文件为 unicode 文本。 位置和关键字参数会被传递给 *note
     io.TextIOWrapper: 5fc. (‘buffer’ 除外，它将由上下文确定)。

 -- 方法: Path.read_bytes ()

     读取当前文件为字节串。


File: python.info,  Node: PyZipFile 对象,  Next: ZipInfo 对象,  Prev: Path 对象,  Up: zipfile --- 使用ZIP存档

5.13.5.3 PyZipFile 对象
.......................

*note PyZipFile: 923. 构造器接受与 *note ZipFile: 427. 构造器相同的形参
，以及一个额外的形参 `optimize'。

 -- 类: zipfile.PyZipFile (file, mode='r', compression=ZIP_STORED,
          allowZip64=True, optimize=-1)

     3.2 新版功能: `optimize' 形参。

     在 3.4 版更改: 默认启用 ZIP64 扩展。

     实例在 *note ZipFile: 427. 对象所具有的方法以外还附加了一个方法:

      -- 方法: writepy (pathname, basename='', filterfunc=None)

          查找 ‘*.py’ 文件并将相应的文件添加到归档。

          如果 *note PyZipFile: 923. 的 `optimize' 形参未给定或为 ‘-1’，
          则相应的文件为 ‘*.pyc’ 文件，并在必要时进行编译。

          如果 *note PyZipFile: 923. 的 `optimize' 形参为 ‘0’, ‘1’ 或
          ‘2’，则限具有相应优化级别 (参见 *note compile(): 1b5.) 的文件
          会被添加到归档，并在必要时进行编译。

          如果 `pathname' 是文件，则文件名必须以 ‘.py’ 为后缀，并且只有
          (相应的 ‘*.pyc’) 文件会被添加到最高层级（不带路径信息）。 如果
          `pathname' 不是以 ‘.py’ 为后缀的文件，则将引发 *note
          RuntimeError: 2bb.。 如果它是目录，并且该目录不是一个包目录，
          则所有的 ‘*.pyc’ 文件会被添加到最高层级。 如果目录是一个包目录
          ，则所有的 ‘*.pyc’ 会被添加到包名所表示的文件路径下，并且如果
          有任何子目录为包目录，则会以排好的顺序递归地添加这些目录。

          `basename' 仅限在内部使用。

          如果给定 `filterfunc'，则它必须是一个接受单个字符串参数的函数
          。 在将其添加到归档之前它将被传入每个路径（包括每个单独的完整
          路径）。 如果 `filterfunc' 返回假值，则路径将不会被添加，而如
          果它是一个目录则其内容将被忽略。 例如，如果我们的测试文件全都
          位于 ‘test’ 目录或以字符串 ‘test_’ 打头，则我们可以使用一个
          `filterfunc' 来排除它们:

               >>> zf = PyZipFile('myprog.zip')
               >>> def notests(s):
               ...     fn = os.path.basename(s)
               ...     return (not (fn == 'test' or fn.startswith('test_')))
               >>> zf.writepy('myprog', filterfunc=notests)

          *note writepy(): 922. 方法会产生带有这样一些文件名的归档:

               string.pyc                   # Top level name
               test/__init__.pyc            # Package directory
               test/testall.pyc             # Module test.testall
               test/bogus/__init__.pyc      # Subpackage directory
               test/bogus/myfile.pyc        # Submodule test.bogus.myfile

          3.4 新版功能: `filterfunc' 形参。

          在 3.6.2 版更改: `pathname' 形参接受一个 *note path-like
          object: 373.。

          在 3.7 版更改: 递归排序目录条目。


File: python.info,  Node: ZipInfo 对象,  Next: 命令行界面<2>,  Prev: PyZipFile 对象,  Up: zipfile --- 使用ZIP存档

5.13.5.4 ZipInfo 对象
.....................

*note ZipInfo: 5c3. 类的实例会通过 *note getinfo(): 1d9d. 和 *note
ZipFile: 427. 对象的 *note infolist(): 1d9e. 方法返回。 每个对象将存储关
于 ZIP 归档的一个成员的信息。

有一个类方法可以为文件系统文件创建 *note ZipInfo: 5c3. 实例:

 -- 方法: classmethod ZipInfo.from_file (filename, arcname=None, *,
          strict_timestamps=True)

     为文件系统中的文件构造一个 *note ZipInfo: 5c3. 实例，并准备将其添加
     到一个 zip 文件。

     `filename' 应为文件系统中某个文件或目录的路径。

     如果指定了 `arcname'，它会被用作归档中的名称。 如果未指定
     `arcname'，则所用名称与 `filename' 相同，但将去除任何驱动器盘符和打
     头的路径分隔符。

     `strict_timestamps' 参数在设为 ‘False’ 时允许压缩早于 1980-01-01 的
     文件，代价时会将时间戳设为 1980-01-01。 类似的行为也会对晚于
     2107-12-31 的文件发生，时间戳也会被设为该上限值。

     3.6 新版功能.

     在 3.6.2 版更改: `filename' 形参接受一个 *note path-like object:
     373.。

     3.8 新版功能: `strict_timestamps' 仅限关键字参数

实例具有下列方法和属性:

 -- 方法: ZipInfo.is_dir ()

     如果此归档成员是一个目录则返回 ‘True’。

     这会使用条目的名称：目录应当总是以 ‘/’ 结尾。

     3.6 新版功能.

 -- 属性: ZipInfo.filename

     归档中的文件名称。

 -- 属性: ZipInfo.date_time

     上次修改存档成员的时间和日期。这是六个值的元组：

     索引        值
                 
     -------------------------------------------
                 
     ‘0’         Year (>= 1980)
                 
                 
     ‘1’         月（1为基数）
                 
                 
     ‘2’         月份中的日期（1为基数）
                 
                 
     ‘3’         小时（0为基数）
                 
                 
     ‘4’         分钟（0为基数）
                 
                 
     ‘5’         秒（0为基数）
                 

          注解: ZIP文件格式不支持1980年以前的时间戳。

 -- 属性: ZipInfo.compress_type

     归档成员的压缩类型。

 -- 属性: ZipInfo.comment

     *note bytes: 33a. 对象形式的单个归档成员的注释。

 -- 属性: ZipInfo.extra

     扩展字段数据。 PKZIP Application Note(1) 包含一些保存于该 *note
     bytes: 33a. 对象中的内部结构的注释。

 -- 属性: ZipInfo.create_system

     创建 ZIP 归档所用的系统。

 -- 属性: ZipInfo.create_version

     创建 ZIP 归档所用的 PKZIP 版本。

 -- 属性: ZipInfo.extract_version

     需要用来提取归档的 PKZIP 版本。

 -- 属性: ZipInfo.reserved

     必须为零。

 -- 属性: ZipInfo.flag_bits

     ZIP 标志位。

 -- 属性: ZipInfo.volume

     文件头的分卷号。

 -- 属性: ZipInfo.internal_attr

     内部属性。

 -- 属性: ZipInfo.external_attr

     外部文件属性。

 -- 属性: ZipInfo.header_offset

     文件头的字节偏移量。

 -- 属性: ZipInfo.CRC

     未压缩文件的 CRC-32。

 -- 属性: ZipInfo.compress_size

     已压缩数据的大小。

 -- 属性: ZipInfo.file_size

     未压缩文件的大小。

   ---------- Footnotes ----------

   (1) https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT


File: python.info,  Node: 命令行界面<2>,  Next: 解压缩的障碍,  Prev: ZipInfo 对象,  Up: zipfile --- 使用ZIP存档

5.13.5.5 命令行界面
...................

*note zipfile: 143. 模块提供了简单的命令行接口用于与 ZIP 归档的交互。

如果你想要创建一个新的 ZIP 归档，请在 *note -c: 1dd0. 选项后指定其名称然
后列出应当被包含的文件名:

     $ python -m zipfile -c monty.zip spam.txt eggs.txt

传入一个字典也是可接受的:

     $ python -m zipfile -c monty.zip life-of-brian_1979/

如果你想要将一个 ZIP 归档提取到指定的目录，请使用 *note -e: 1dd1. 选项:

     $ python -m zipfile -e monty.zip target-dir/

要获取一个 ZIP 归档中的文件列表，请使用 *note -l: 1dd2. 选项:

     $ python -m zipfile -l monty.zip

* Menu:

* 命令行选项: 命令行选项<2>.


File: python.info,  Node: 命令行选项<2>,  Up: 命令行界面<2>

5.13.5.6 命令行选项
...................

 -- 程序选项: -l <zipfile>
 -- 程序选项: --list <zipfile>

     列出一个 zipfile 中的文件名。

 -- 程序选项: -c <zipfile> <source1> ... <sourceN>
 -- 程序选项: --create <zipfile> <source1> ... <sourceN>

     基于源文件创建 zipfile。

 -- 程序选项: -e <zipfile> <output_dir>
 -- 程序选项: --extract <zipfile> <output_dir>

     将 zipfile 提取到目标目录中。

 -- 程序选项: -t <zipfile>
 -- 程序选项: --test <zipfile>

     检测 zipfile 是否有效。


File: python.info,  Node: 解压缩的障碍,  Prev: 命令行界面<2>,  Up: zipfile --- 使用ZIP存档

5.13.5.7 解压缩的障碍
.....................

zipfile 模块的提取操作可能会由于下面列出的障碍而失败。

* Menu:

* 由于文件本身::
* 文件系统限制::
* 资源限制::
* 中断::
* 提取的默认行为::


File: python.info,  Node: 由于文件本身,  Next: 文件系统限制,  Up: 解压缩的障碍

5.13.5.8 由于文件本身
.....................

解压缩可能由于不正确的密码 / CRC 校验和 / ZIP 格式或不受支持的压缩 / 解
密方法而失败。


File: python.info,  Node: 文件系统限制,  Next: 资源限制,  Prev: 由于文件本身,  Up: 解压缩的障碍

5.13.5.9 文件系统限制
.....................

超出特定文件系统上的限制可能会导致解压缩失败。 例如目录条目所允许的字符
、文件名的长度、路径名的长度、单个文件的大小以及文件的数量等等。


File: python.info,  Node: 资源限制,  Next: 中断,  Prev: 文件系统限制,  Up: 解压缩的障碍

5.13.5.10 资源限制
..................

缺乏内存或磁盘空间将会导致解压缩失败。 例如，作用于 zipfile 库的解压缩炸
弹 (即 ZIP bomb(1)) 就可能造成磁盘空间耗尽。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Zip_bomb


File: python.info,  Node: 中断,  Next: 提取的默认行为,  Prev: 资源限制,  Up: 解压缩的障碍

5.13.5.11 中断
..............

在解压缩期间中断执行，例如按下 ctrl-C 或杀死解压缩进程可能会导致归档文件
的解压缩不完整。


File: python.info,  Node: 提取的默认行为,  Prev: 中断,  Up: 解压缩的障碍

5.13.5.12 提取的默认行为
........................

不了解提取的默认行为可能导致不符合期望的解压缩结果。 例如，当提取相同归
档两次时，它会不经询问地覆盖文件。


File: python.info,  Node: tarfile --- 读写tar归档文件,  Prev: zipfile --- 使用ZIP存档,  Up: 数据压缩和存档

5.13.6 ‘tarfile’ — 读写tar归档文件
----------------------------------

`源代码:' Lib/tarfile.py(1)

__________________________________________________________________

*note tarfile: 102. 模块可以用来读写 tar 归档，包括使用 gzip, bz2 和
lzma 压缩的归档。 请使用 *note zipfile: 143. 模块来读写 ‘.zip’ 文件，或
者使用 *note shutil: b9e. 的高层级函数。

一些事实和数字:

   * 读写 *note gzip: 8c, *note bz2: 14. 和 *note lzma: ae. 解压的归档要
     求相应的模块可用。

   * 支持读取 / 写入 POSIX.1-1988 (ustar) 格式。

   * 对 GNU tar 格式的读/写支持，包括 `longname' 和 `longlink' 扩展，对
     所有种类 `sparse' 扩展的只读支持，包括 sparse 文件的恢复。

   * 对 POSIX.1-2001 (pax) 格式的读/写支持。

   * 处理目录、正常文件、硬链接、符号链接、fifo 管道、字符设备和块设备，
     并且能够获取和恢复文件信息例如时间戳、访问权限和所有者等。

在 3.3 版更改: 添加了对 *note lzma: ae. 压缩的支持。

 -- 函数: tarfile.open (name=None, mode='r', fileobj=None,
          bufsize=10240, **kwargs)

     针对路径名 `name' 返回 *note TarFile: b94. 对象。 有关 *note
     TarFile: b94. 对象以及所允许的关键字参数的详细信息请参阅 *note
     TarFile 对象: 1de2.。

     `mode' 必须是 ‘'filemode[:compression]'’ 形式的字符串，其默认值为
     ‘'r'’。 以下是模式组合的完整列表:

     模式                   action
                            
     -------------------------------------------------------------------------
                            
     ‘'r' or 'r:*'’         打开和读取使用透明压缩（推荐）。
                            
                            
     ‘'r:'’                 打开和读取不使用压缩。
                            
                            
     ‘'r:gz'’               打开和读取使用gzip 压缩。
                            
                            
     ‘'r:bz2'’              打开和读取使用bzip2 压缩。
                            
                            
     ‘'r:xz'’               打开和读取使用lzma 压缩。
                            
                            
     ‘'x'’ 或 ‘'x:'’        创建tarfile不进行压缩。如果文件已经存在，则抛出
                            *note FileExistsError: 960. 异常。
                            
                            
     ‘'x:gz'’               使用gzip压缩创建tarfile。如果文件已经存在，则抛
                            出 *note FileExistsError: 960. 异常。
                            
                            
     ‘'x:bz2'’              使用bzip2 压缩创建tarfile。如果文件已经存在，则
                            抛出 *note FileExistsError: 960. 异常。
                            
                            
     ‘'x:xz'’               使用lzma 压缩创建tarfile。如果文件已经存在，则
                            抛出 *note FileExistsError: 960. 异常。
                            
                            
     ‘'a' or 'a:'’          打开以便在没有压缩的情况下追加。如果文件不存在
                            ，则创建该文件。
                            
                            
     ‘'w' or 'w:'’          打开用于未压缩的写入。
                            
                            
     ‘'w:gz'’               打开用于 gzip 压缩的写入。
                            
                            
     ‘'w:bz2'’              打开用于 bzip2 压缩的写入。
                            
                            
     ‘'w:xz'’               打开用于 lzma 压缩的写入。
                            

     请注意 ‘'a:gz'’, ‘'a:bz2'’ 或 ‘'a:xz'’ 是不可能的组合。 如果 `mode'
     不适用于打开特定（压缩的）文件用于读取，则会引发 *note ReadError:
     1de3.。 请使用 `mode' ‘'r'’ 来避免这种情况。 如果某种压缩方法不受支
     持，则会引发 *note CompressionError: 1de4.。

     如果指定了 `fileobj'，它会被用作对应于 `name' 的以二进制模式打开的
     *note file object: b4a. 的替代。 它会被设定为处在位置 0。

     对于 ‘'w:gz'’, ‘'r:gz'’, ‘'w:bz2'’, ‘'r:bz2'’, ‘'x:gz'’, ‘'x:bz2'’
     等模式，*note tarfile.open(): 76f. 接受关键字参数 `compresslevel'
     (默认值为 ‘9’) 来指定文件的压缩等级。

     针对特殊的目的，还存在第二种 `mode' 格式:
     ‘'filemode|[compression]'’。 *note tarfile.open(): 76f. 将返回一个
     将其数据作为数据块流来处理的 *note TarFile: b94. 对象。 对此文件将
     不能执行随机查找。 如果给定了 `fileobj'，它可以是任何具有 ‘read()’
     或 ‘write()’ 方法 (由 `mode' 确定) 的对象。 `bufsize' 指定块大小，
     默认值为 ‘20 * 512’ 字节。 可与此格式组合使用的有 ‘sys.stdin’, 套接
     字 *note file object: b4a. 或磁带设备等。 但是，对于这样的 *note
     TarFile: b94. 对象存在不允许随机访问的限制，参见 *note 例子: 1de5.。
     目前可用的模式如下:

     模式              动作
                       
     -------------------------------------------------------------------
                       
     ‘'r|*'’           打开 tar 块的 `流' 以进行透明压缩读取。
                       
                       
     ‘'r|'’            打开一个未压缩的 tar 块的 `stream' 用于读取。
                       
                       
     ‘'r|gz'’          打开一个 gzip 压缩的 `stream' 用于读取。
                       
                       
     ‘'r|bz2'’         打开一个 bzip2 压缩的 `stream' 用于读取。
                       
                       
     ‘'r|xz'’          打开一个 lzma 压缩 `stream' 用于读取。
                       
                       
     ‘'w|'’            打开一个未压缩的 `stream' 用于写入。
                       
                       
     ‘'w|gz'’          打开一个 gzip 压缩的 `stream' 用于写入。
                       
                       
     ‘'w|bz2'’         打开一个 bzip2 压缩的 `stream' 用于写入。
                       
                       
     ‘'w|xz'’          打开一个 lzma 压缩的 `stream' 用于写入。
                       

     在 3.5 版更改: 添加了 ‘'x'’ (单独创建) 模式。

     在 3.6 版更改: `name' 形参接受一个 *note path-like object: 373.。

 -- 类: tarfile.TarFile

     用于读取和写入 tar 归档的类。 请不要直接使用这个类：而要使用 *note
     tarfile.open(): 76f.。 参见 *note TarFile 对象: 1de2.。

 -- 函数: tarfile.is_tarfile (name)

     如果 `name' 是一个 *note tarfile: 102. 模块能读取的 tar 归档文件则
     返回 *note True: 4a1.。

*note tarfile: 102. 模块定义了以下异常:

 -- 例外: tarfile.TarError

     所有 *note tarfile: 102. 异常的基类。

 -- 例外: tarfile.ReadError

     当一个不能被 *note tarfile: 102. 模块处理或者因某种原因而无效的 tar
     归档被打开时将被引发。

 -- 例外: tarfile.CompressionError

     当一个压缩方法不受支持或者当数据无法被正确解码时将被引发。

 -- 例外: tarfile.StreamError

     当达到流式 *note TarFile: b94. 对象的典型限制时将被引发。

 -- 例外: tarfile.ExtractError

     当使用 *note TarFile.extract(): 771. 时针对 `non-fatal' 所引发的异
     常，但是仅限 ‘TarFile.errorlevel’‘== 2’。

 -- 例外: tarfile.HeaderError

     如果获取的缓冲区无效则会由 *note TarInfo.frombuf(): 1deb. 引发的异
     常。

以下常量在模块层级上可用:

 -- 数据: tarfile.ENCODING

     默认的字符编码格式：在 Windows 上为 ‘'utf-8'’，其他系统上则为 *note
     sys.getfilesystemencoding(): 4fe. 所返回的值。

以下常量各自定义了一个 *note tarfile: 102. 模块能够创建的 tar 归档格式。
相关细节请参阅 *note 受支持的 tar 格式: 1ded. 小节。

 -- 数据: tarfile.USTAR_FORMAT

     POSIX.1-1988 (ustar) 格式。

 -- 数据: tarfile.GNU_FORMAT

     GNU tar 格式。

 -- 数据: tarfile.PAX_FORMAT

     POSIX.1-2001 (pax) 格式。

 -- 数据: tarfile.DEFAULT_FORMAT

     用于创建归档的默认格式。 目前为 *note PAX_FORMAT: 1df0.。

     在 3.8 版更改: 新归档的默认格式已更改为 *note PAX_FORMAT: 1df0. 而
     不再是 *note GNU_FORMAT: 1def.。

参见
....

模块 *note zipfile: 143.

     *note zipfile: 143. 标准模块的文档。

*note 归档操作: b9e.

     标准 *note shutil: ea. 模块所提供的高层级归档工具的文档。

GNU tar manual, Basic Tar Format(2)

     针对 tar 归档文件的文档，包含 GNU tar 扩展。

* Menu:

* TarFile 对象::
* TarInfo 对象::
* 命令行界面: 命令行界面<3>.
* 例子: 例子<6>.
* 受支持的 tar 格式::
* Unicode 问题::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/tarfile.py

   (2) https://www.gnu.org/software/tar/manual/html_node/Standard.html


File: python.info,  Node: TarFile 对象,  Next: TarInfo 对象,  Up: tarfile --- 读写tar归档文件

5.13.6.1 TarFile 对象
.....................

*note TarFile: b94. 对象提供了一个 tar 归档的接口。 一个 tar 归档就是数
据块的序列。 一个归档成员（被保存文件）是由一个标头块加多个数据块组成的
。 一个文件可以在一个 tar 归档中多次被保存。 每个归档成员都由一个 *note
TarInfo: b95. 对象来代表，详情参见 *note TarInfo 对象: 1df3.。

*note TarFile: b94. 对象可在 *note with: 6f2. 语句中作为上下文管理器使用
。 当语句块结束时它将自动被关闭。 请注意在发生异常事件时被打开用于写入的
归档将不会被终结；只有内部使用的文件对象将被关闭。 相关用例请参见 *note
例子: 1de5.。

3.2 新版功能: 添加了对上下文管理器协议的支持。

 -- 类: tarfile.TarFile (name=None, mode='r', fileobj=None,
          format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False,
          ignore_zeros=False, encoding=ENCODING,
          errors='surrogateescape', pax_headers=None, debug=0,
          errorlevel=0)

     下列所有参数都是可选项并且也可作为实例属性来访问。

     `name' 是归档的路径名称。 `name' 可以是一个 *note path-like object:
     373.。 如果给定了 `fileobj' 则它可以被省略。 在此情况下，如果对象的
     ‘name’ 属性存在则它会被使用。

     `mode' 可以为 ‘'r'’ 表示从现有归档读取，‘'a'’ 表示将数据追加到现有
     文件，‘'w'’ 表示创建新文件覆盖现有文件，或者 ‘'x'’ 表示仅在文件不存
     在时创建新文件。

     如果给定了 `fileobj'，它会被用于读取或写入数据。 如果可以被确定，则
     `mode' 会被 `fileobj' 的模式所覆盖。 `fileobj' 的使用将从位置 0 开
     始。

          注解: 当 *note TarFile: b94. 被关闭时，`fileobj' 不会被关闭。

     `format' 控制用于写入的归档格式。 它必须为在模块层级定义的常量
     *note USTAR_FORMAT: 1dee, *note GNU_FORMAT: 1def. 或 *note
     PAX_FORMAT: 1df0. 中的一个。 当读取时，格式将被自动检测，即使单个归
     档中存在不同的格式。

     `tarinfo' 参数可以被用来将默认的 *note TarInfo: b95. 类替换为另一个
     。

     如果 `dereference' 为 *note False: 390.，则会将符号链接和硬链接添加
     到归档中。 如果为 *note True: 4a1.，则会将目标文件的内容添加到归档
     中。 在不支持符号链接的系统上参数将不起作用。

     如果 `ignore_zeros' 为 *note False: 390.，则会将空的数据块当作归档
     的末尾来处理。 如果为 *note True: 4a1.，则会跳过空的（和无效的）数
     据块并尝试获取尽可能多的成员。 此参数仅适用于读取拼接的或损坏的归档
     。

     `debug' 可设为从 ‘0’ (无调试消息) 到 ‘3’ (全部调试消息)。 消息会被
     写入到 ‘sys.stderr’。

     如果 `errorlevel' 为 ‘0’，则当使用 *note TarFile.extract(): 771. 时
     会忽略所有错误。 无论何种情况，当启用调试时它们都将被显示为调试输出
     的错误消息。 如果为 ‘1’，则所有 `fatal' 错误会被作为 *note OSError:
     1d4. 异常被引发。 如果为 ‘2’，则所有 `non-fatal' 错误也会被作为
     *note TarError: 1de7. 异常被引发。

     `encoding' 和 `errors' 参数定义了读取或写入归档所使用的字符编码格式
     以及要如何处理转换错误。 默认设置将适用于大多数用户。 要深入了解详
     情可参阅 *note Unicode 问题: 1df4. 小节。

     可选的 `pax_headers' 参数是字符串的字典，如果 `format' 为 *note
     PAX_FORMAT: 1df0. 它将被作为 pax 全局标头被添加。

     在 3.2 版更改: 使用 ‘'surrogateescape'’ 作为 `errors' 参数的默认值
     。

     在 3.5 版更改: 添加了 ‘'x'’ (单独创建) 模式。

     在 3.6 版更改: `name' 形参接受一个 *note path-like object: 373.。

 -- 方法: classmethod TarFile.open (...)

     作为替代的构造器。 *note tarfile.open(): 76f. 函数实际上是这个类方
     法的快捷方式。

 -- 方法: TarFile.getmember (name)

     返回成员 `name' 的 *note TarInfo: b95. 对象。 如果 `name' 在归档中
     找不到，则会引发 *note KeyError: 2c8.。

          注解: 如果一个成员在归档中出现超过一次，它的最后一次出现会被视
          为是最新的版本。

 -- 方法: TarFile.getmembers ()

     以 *note TarInfo: b95. 对象列表的形式返回归档的成员。 列表的顺序与
     归档中成员的顺序一致。

 -- 方法: TarFile.getnames ()

     以名称列表的形式返回成员。 它的顺序与 *note getmembers(): 773. 所返
     回列表的顺序一致。

 -- 方法: TarFile.list (verbose=True, *, members=None)

     将内容清单打印到 ‘sys.stdout’。 如果 `verbose' 为 *note False:
     390.，则将只打印成员名称。 如果为 *note True: 4a1.，则输出将类似于
     ‘ls -l’ 的输出效果。 如果给定了可选的 `members'，它必须为 *note
     getmembers(): 773. 所返回的列表的一个子集。

     在 3.5 版更改: 添加了 `members' 形参。

 -- 方法: TarFile.next ()

     当 *note TarFile: b94. 被打开用于读取时，以 *note TarInfo: b95. 对
     象的形式返回归档的下一个成员。 如果不再有可用对象则返回 *note None:
     158.。

 -- 方法: TarFile.extractall (path=".", members=None, *,
          numeric_owner=False)

     将归档中的所有成员提取到当前工作目录或 `path' 目录。 如果给定了可选
     的 `members'，则它必须为 *note getmembers(): 773. 所返回的列表的一
     个子集。 字典信息例如所有者、修改时间和权限会在所有成员提取完毕后被
     设置。 这样做是为了避免两个问题：目录的修改时间会在每当在其中创建文
     件时被重置。 并且如果目录的权限不允许写入，提取文件到目录的操作将失
     败。

     如果 `numeric_owner' 为 *note True: 4a1.，则将使用来自 tarfile 的
     uid 和 gid 数值来设置被提取文件的所有者/用户组。 在其他情况下，则会
     使用来自 tarfile 的名称值。

          警告: 绝不要未经预先检验就从不可靠的源中提取归档文件。 这样有
          可能在 `path' 之外创建文件，例如某些成员具有以 ‘"/"’ 开始的绝
          对路径文件名或带有两个点号 ‘".."’ 的文件名。

     在 3.5 版更改: 添加了 `numeric_owner' 形参。

     在 3.6 版更改: `path' 形参接受一个 *note path-like object: 373.。

 -- 方法: TarFile.extract (member, path="", set_attrs=True, *,
          numeric_owner=False)

     从归档中提取出一个成员放入当前工作目录，将使用其完整名称。 成员的文
     件信息会尽可能精确地被提取。 `member' 可以是一个文件名或 *note
     TarInfo: b95. 对象。 你可以使用 `path' 指定一个不同的目录。 `path'
     可以是一个 *note path-like object: 373.。 将会设置文件属性 (owner,
     mtime, mode) 除非 `set_attrs' 为假值。

     如果 `numeric_owner' 为 *note True: 4a1.，则将使用来自 tarfile 的
     uid 和 gid 数值来设置被提取文件的所有者/用户组。 在其他情况下，则会
     使用来自 tarfile 的名称值。

          注解: *note extract(): 771. 方法不会处理某些提取问题。 在大多
          数情况下你应当考虑使用 *note extractall(): 770. 方法。

          警告: 查看 *note extractall(): 770. 的警告信息。

     在 3.2 版更改: 添加了 `set_attrs' 形参。

     在 3.5 版更改: 添加了 `numeric_owner' 形参。

     在 3.6 版更改: `path' 形参接受一个 *note path-like object: 373.。

 -- 方法: TarFile.extractfile (member)

     将归档中的一个成员提取为文件对象。 `member' 可以是一个文件名或
     *note TarInfo: b95. 对象。 如果 `member' 是一个常规文件或链接，则会
     返回一个 *note io.BufferedReader: b92. 对象。 在其他情况下将返回
     *note None: 158.。

     在 3.3 版更改: 返回一个 *note io.BufferedReader: b92. 对象。

 -- 方法: TarFile.add (name, arcname=None, recursive=True, *,
          filter=None)

     将文件 `name' 添加到归档。 `name' 可以为任意类型的文件（目录、
     fifo、符号链接等等）。 如果给出 `arcname' 则它将为归档中的文件指定
     一个替代名称。 默认情况下会递归地添加目录。 这可以通过将
     `recursive' 设为 *note False: 390. 来避免。 递归操作会按排序顺序添
     加条目。 如果给定了 `filter'，它应当为一个接受 *note TarInfo: b95.
     对象并返回已修改 *note TarInfo: b95. 对象的函数。 如果它返回 *note
     None: 158. 则 *note TarInfo: b95. 对象将从归档中被排除。 具体示例参
     见 *note 例子: 1de5.。

     在 3.2 版更改: 添加了 `filter' 形参。

     在 3.7 版更改: 递归操作按排序顺序添加条目。

 -- 方法: TarFile.addfile (tarinfo, fileobj=None)

     将 *note TarInfo: b95. 对象 `tarinfo' 添加到归档。 如果给定了
     `fileobj'，它应当是一个 *note binary file: 1cb4.，并会从中读取
     ‘tarinfo.size’ 个字节添加到归档。 你可以直接创建 *note TarInfo:
     b95. 对象，或是使用 *note gettarinfo(): 1dfb. 来创建。

 -- 方法: TarFile.gettarinfo (name=None, arcname=None, fileobj=None)

     基于 *note os.stat(): 1f2. 的结果或者现有文件的相同数据创建一个
     *note TarInfo: b95.。 文件或者是命名为 `name'，或者是使用文件描述符
     指定为一个 *note file object: b4a. `fileobj'。 `name' 可以是一个
     *note path-like object: 373.。 如果给定了 `arcname'，则它将为归档中
     的文件指定一个替代名称，在其他情况下，名称将从 `fileobj' 的 *note
     name: 1dfc. 属性或 `name' 参数获取。 名称应当是一个文本字符串。

     你可以在使用 *note addfile(): 1dfa. 添加 *note TarInfo: b95. 的某些
     属性之前修改它们。 如果文件对象不是从文件开头进行定位的普通文件对象
     ，*note size: 1dfd. 之类的属性就可能需要修改。 例如 *note GzipFile:
     6e6. 之类的文件就属于这种情况。 *note name: 1dfe. 也可以被修改，在
     这种情况下 `arcname' 可以是一个占位字符串。

     在 3.6 版更改: `name' 形参接受一个 *note path-like object: 373.。

 -- 方法: TarFile.close ()

     关闭 *note TarFile: b94.。 在写入模式下，会向归档添加两个表示结束的
     零数据块。

 -- 属性: TarFile.pax_headers

     一个包含 pax 全局标头的键值对的字典。


File: python.info,  Node: TarInfo 对象,  Next: 命令行界面<3>,  Prev: TarFile 对象,  Up: tarfile --- 读写tar归档文件

5.13.6.2 TarInfo 对象
.....................

*note TarInfo: b95. 对象代表 *note TarFile: b94. 中的一个文件。 除了会存
储所有必要的文件属性（例如文件类型、大小、时间、权限、所有者等），它还提
供了一些确定文件类型的有用方法。 此对象 `并不' 包含文件数据本身。

*note TarInfo: b95. 对象可通过 *note TarFile: b94. 的方法 ‘getmember()’,
‘getmembers()’ 和 ‘gettarinfo()’ 返回。

 -- 类: tarfile.TarInfo (name="")

     创建一个 *note TarInfo: b95. 对象。

 -- 方法: classmethod TarInfo.frombuf (buf, encoding, errors)

     基于字符串缓冲区 `buf' 创建并返回一个 *note TarInfo: b95. 对象。

     如果缓冲区无效则会引发 *note HeaderError: 1dea.。

 -- 方法: classmethod TarInfo.fromtarfile (tarfile)

     从 *note TarFile: b94. 对象 `tarfile' 读取下一个成员并将其作为
     *note TarInfo: b95. 对象返回。

 -- 方法: TarInfo.tobuf (format=DEFAULT_FORMAT, encoding=ENCODING,
          errors='surrogateescape')

     基于 *note TarInfo: b95. 对象创建一个字符串缓冲区。 有关参数的信息
     请参见 *note TarFile: b94. 类的构造器。

     在 3.2 版更改: 使用 ‘'surrogateescape'’ 作为 `errors' 参数的默认值
     。

‘TarInfo’ 对象具有以下公有数据属性:

 -- 属性: TarInfo.name

     归档成员的名称。

 -- 属性: TarInfo.size

     以字节表示的大小。

 -- 属性: TarInfo.mtime

     上次修改的时间。

 -- 属性: TarInfo.mode

     权限位。

 -- 属性: TarInfo.type

     文件类型。 `type' 通常为以下常量之一: ‘REGTYPE’, ‘AREGTYPE’,
     ‘LNKTYPE’, ‘SYMTYPE’, ‘DIRTYPE’, ‘FIFOTYPE’, ‘CONTTYPE’, ‘CHRTYPE’,
     ‘BLKTYPE’, ‘GNUTYPE_SPARSE’。 要更方便地确定一个 *note TarInfo:
     b95. 对象的类型，请使用下述的 ‘is*()’ 方法。

 -- 属性: TarInfo.linkname

     目标文件名的名称，该属性仅在类型为 ‘LNKTYPE’ 和 ‘SYMTYPE’ 的 *note
     TarInfo: b95. 对象中存在。

 -- 属性: TarInfo.uid

     最初保存该成员的用户的用户 ID。

 -- 属性: TarInfo.gid

     最初保存该成员的用户的分组 ID。

 -- 属性: TarInfo.uname

     用户名。

 -- 属性: TarInfo.gname

     分组名。

 -- 属性: TarInfo.pax_headers

     一个包含所关联的 pax 扩展标头的键值对的字典。

*note TarInfo: b95. 对象还提供了一些便捷查询方法:

 -- 方法: TarInfo.isfile ()

     如果 ‘Tarinfo’ 对象为普通文件则返回 *note True: 4a1.。

 -- 方法: TarInfo.isreg ()

     与 *note isfile(): 1e0d. 相同。

 -- 方法: TarInfo.isdir ()

     如果为目录则返回 *note True: 4a1.。

 -- 方法: TarInfo.issym ()

     如果为符号链接则返回 *note True: 4a1.。

 -- 方法: TarInfo.islnk ()

     如果为硬链接则返回 *note True: 4a1.。

 -- 方法: TarInfo.ischr ()

     如果为字符设备则返回 *note True: 4a1.。

 -- 方法: TarInfo.isblk ()

     如果为块设备则返回 *note True: 4a1.。

 -- 方法: TarInfo.isfifo ()

     如果为 FIFO 则返回 *note True: 4a1.。.

 -- 方法: TarInfo.isdev ()

     如果为字符设备、块设备或 FIFO 之一则返回 *note True: 4a1.。


File: python.info,  Node: 命令行界面<3>,  Next: 例子<6>,  Prev: TarInfo 对象,  Up: tarfile --- 读写tar归档文件

5.13.6.3 命令行界面
...................

3.4 新版功能.

*note tarfile: 102. 模块提供了简单的命令行接口以便与 tar 归档进行交互。

如果你想要创建一个新的 tar 归档，请在 *note -c: 1e17. 选项后指定其名称然
后列出应当被包含的文件名:

     $ python -m tarfile -c monty.tar  spam.txt eggs.txt

传入一个字典也是可接受的:

     $ python -m tarfile -c monty.tar life-of-brian_1979/

如果你想要将一个 tar 归档提取到指定的目录，请使用 *note -e: 1e18. 选项:

     $ python -m tarfile -e monty.tar

你也可以通过传入目录名称将一个 tar 归档提取到不同的目录:

     $ python -m tarfile -e monty.tar  other-dir/

要获取一个 tar 归档中文件的列表，请使用 *note -l: 1e19. 选项:

     $ python -m tarfile -l monty.tar

* Menu:

* 命令行选项: 命令行选项<3>.


File: python.info,  Node: 命令行选项<3>,  Up: 命令行界面<3>

5.13.6.4 命令行选项
...................

 -- 程序选项: -l <tarfile>
 -- 程序选项: --list <tarfile>

     列出一个 tarfile 中的文件名。

 -- 程序选项: -c <tarfile> <source1> ... <sourceN>
 -- 程序选项: --create <tarfile> <source1> ... <sourceN>

     基于源文件创建 tarfile。

 -- 程序选项: -e <tarfile> [<output_dir>]
 -- 程序选项: --extract <tarfile> [<output_dir>]

     如果未指定 `output_dir' 则会将 tarfile 提取到当前目录。

 -- 程序选项: -t <tarfile>
 -- 程序选项: --test <tarfile>

     检测 tarfile 是否有效。

 -- 程序选项: -v, --verbose

     更详细地输出结果。


File: python.info,  Node: 例子<6>,  Next: 受支持的 tar 格式,  Prev: 命令行界面<3>,  Up: tarfile --- 读写tar归档文件

5.13.6.5 例子
.............

如何将整个 tar 归档提取到当前工作目录:

     import tarfile
     tar = tarfile.open("sample.tar.gz")
     tar.extractall()
     tar.close()

如何通过 *note TarFile.extractall(): 770. 使用生成器函数而非列表来提取一
个 tar 归档的子集:

     import os
     import tarfile

     def py_files(members):
         for tarinfo in members:
             if os.path.splitext(tarinfo.name)[1] == ".py":
                 yield tarinfo

     tar = tarfile.open("sample.tar.gz")
     tar.extractall(members=py_files(tar))
     tar.close()

如何基于一个文件名列表创建未压缩的 tar 归档:

     import tarfile
     tar = tarfile.open("sample.tar", "w")
     for name in ["foo", "bar", "quux"]:
         tar.add(name)
     tar.close()

使用 *note with: 6f2. 语句的同一个示例:

     import tarfile
     with tarfile.open("sample.tar", "w") as tar:
         for name in ["foo", "bar", "quux"]:
             tar.add(name)

如何读取一个 gzip 压缩的 tar 归档并显示一些成员信息:

     import tarfile
     tar = tarfile.open("sample.tar.gz", "r:gz")
     for tarinfo in tar:
         print(tarinfo.name, "is", tarinfo.size, "bytes in size and is ", end="")
         if tarinfo.isreg():
             print("a regular file.")
         elif tarinfo.isdir():
             print("a directory.")
         else:
             print("something else.")
     tar.close()

如何创建一个归档并使用 *note TarFile.add(): 484. 中的 `filter' 形参来重
置用户信息:

     import tarfile
     def reset(tarinfo):
         tarinfo.uid = tarinfo.gid = 0
         tarinfo.uname = tarinfo.gname = "root"
         return tarinfo
     tar = tarfile.open("sample.tar.gz", "w:gz")
     tar.add("foo", filter=reset)
     tar.close()


File: python.info,  Node: 受支持的 tar 格式,  Next: Unicode 问题,  Prev: 例子<6>,  Up: tarfile --- 读写tar归档文件

5.13.6.6 受支持的 tar 格式
..........................

通过 *note tarfile: 102. 模块可以创建三种 tar 格式:

   * The POSIX.1-1988 ustar 格式 (*note USTAR_FORMAT: 1dee.)。 它支持最
     多 256 个字符的文件名长度和最多 100 个字符的链接名长度。 文件大小上
     限为 8 GiB。 这是一种老旧但广受支持的格式。

   * GNU tar 格式 (*note GNU_FORMAT: 1def.)。 它支持长文件名和链接名、大
     于 8 GiB 的文件以及稀疏文件。 它是 GNU/Linux 系统上的事实标准。
     *note tarfile: 102. 完全支持针对长名称的 GNU tar 扩展，稀疏文件支持
     则限制为只读。

   * POSIX.1-2001 pax 格式 (*note PAX_FORMAT: 1df0.)。 它是几乎无限制的
     最灵活格式。 它支持长文件名和链接名，大文件以及使用便捷方式存储路径
     名。 现代的 tar 实现，包括 GNU tar, bsdtar/libarchive 和 star，完全
     支持扩展 `pax' 特性；某些老旧或不维护的库可能不受支持，但应当会将
     `pax' 归档视为广受支持的 `ustar' 格式。 这是目前新建归档的默认格式
     。

     它扩展了现有的 `ustar' 格式，包括用于无法以其他方式存储的附加标头。
     存在两种形式的 pax 标头：扩展标头只影响后续的文件标头，全局标头则适
     用于完整归档并会影响所有后续的文件。 为了便于移植，在 pax 标头中的
     所有数据均以 `UTF-8' 编码。

还有一些 tar 格式的其他变种，它们可以被读取但不能被创建:

   * 古老的 V7 格式。 这是来自 Unix 第七版的第一个 tar 格式，它只存储常
     规文件和目录。 名称长度不能超过 100 个字符，并且没有用户/分组名信息
     。 某些归档在带有非 ASCII 字符字段的情况下会产生计算错误的标头校验
     和。

   * SunOS tar 扩展格式。 此格式是 POSIX.1-2001 pax 格式的一个变种，但并
     不保持兼容。


File: python.info,  Node: Unicode 问题,  Prev: 受支持的 tar 格式,  Up: tarfile --- 读写tar归档文件

5.13.6.7 Unicode 问题
.....................

最初 tar 格式被设计用来在磁带机上生成备份，主要关注于保存文件系统信息。
现在 tar 归档通常用于文件分发和在网络上交换归档。 最初格式（它是所有其他
格式的基础）的一个问题是它没有支持不同字符编码格式的概念。 例如，一个在
`UTF-8' 系统上创建的普通 tar 归档如果包含非 `ASCII' 字符则将无法在
`Latin-1' 系统上被正确读取。 文本元数据（例如文件名，链接名，用户/分组名
）将变为损坏状态。 不幸的是，没有什么办法能够自动检测一个归档的编码格式
。 pax 格式被设计用来解决这个问题。 它使用通用字符编码格式 `UTF-8' 来存
储非 ASCII 元数据。

在 *note tarfile: 102. 中字符转换的细节由 *note TarFile: b94. 类的
`encoding' 和 `errors' 关键字参数控制。

`encoding' 定义了用于归档中元数据的字符编码格式。 默认值为 *note
sys.getfilesystemencoding(): 4fe. 或是回退选项 ‘'ascii'’。 根据归档是被
读取还是被写入，元数据必须被解码或编码。 如果没有正确设置 `encoding'，转
换可能会失败。

`errors' 参数定义了不能被转换的字符将如何处理。 可能的取值在 *note
错误处理方案: 1371. 小节列出。 默认方案为 ‘'surrogateescape'’，它也被
Python 用于文件系统调用，参见 *note 文件名，命令行参数，以及环境变量。:
1e24.。

对于 *note PAX_FORMAT: 1df0. 归档（默认格式），`encoding' 通常是不必要的
，因为所有元数据都使用 `UTF-8' 来存储。 `encoding' 仅在解码二进制 pax 标
头或存储带有替代字符的字符串等少数场景下会被使用。


File: python.info,  Node: 文件格式,  Next: 加密服务,  Prev: 数据压缩和存档,  Up: Python 标准库

5.14 文件格式
=============

本章中描述的模块解析各种不是标记语言且与电子邮件无关的杂项文件格式。

* Menu:

* csv: csv --- CSV 文件读写. CSV 文件读写
* configparser: configparser --- 配置文件解析器. 配置文件解析器
* netrc: netrc --- netrc 文件处理. netrc 文件处理
* xdrlib: xdrlib --- 编码与解码 XDR 数据. 编码与解码 XDR 数据
* plistlib: plistlib --- 生成与解析 Mac OS X plist 文件. 生成与解析 Mac OS X .plist 文件


File: python.info,  Node: csv --- CSV 文件读写,  Next: configparser --- 配置文件解析器,  Up: 文件格式

5.14.1 ‘csv’ — CSV 文件读写
---------------------------

`源代码：' Lib/csv.py(1)

__________________________________________________________________

CSV (Comma Separated Values) 格式是电子表格和数据库中最常见的输入、输出
文件格式。在 RFC 4180(2) 规范推出的很多年前，CSV 格式就已经被开始使用了
，由于当时并没有合理的标准，不同应用程序读写的数据会存在细微的差别。这种
差别让处理多个来源的 CSV 文件变得困难。但尽管分隔符会变化，此类文件的大
致格式是相似的，所以编写一个单独的模块以高效处理此类数据，将程序员从读写
数据的繁琐细节中解放出来是有可能的。

*note csv: 2a. 模块实现了 CSV 格式表单数据的读写。其提供了诸如“以兼容
Excel 的方式输出数据文件”或“读取 Excel 程序输出的数据文件”的功能，程序员
无需知道 Excel 所采用 CSV 格式的细节。此模块同样可以用于定义其他应用程序
可用的 CSV 格式或定义特定需求的 CSV 格式。

*note csv: 2a. 模块中的 *note reader: ecb. 类和 *note writer: e04. 类可
用于读写序列化的数据。也可使用 *note DictReader: 1be. 类和 *note
DictWriter: b82. 类以字典的形式读写数据。

参见
....

该实现在“Python 增强提议” - PEP ‘305’ (CSV 文件 API) 中被提出

     《Python 增强提议》提出了对 Python 的这一补充。

* Menu:

* 模块内容: 模块内容<3>.
* 变种与格式参数::
* Reader 对象::
* Writer 对象::
* 例子: 例子<7>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/csv.py

   (2) https://tools.ietf.org/html/rfc4180.html


File: python.info,  Node: 模块内容<3>,  Next: 变种与格式参数,  Up: csv --- CSV 文件读写

5.14.1.1 模块内容
.................

*note csv: 2a. 模块定义了以下函数：

 -- 函数: csv.reader (csvfile, dialect='excel', **fmtparams)

     返回一个 reader 对象，该对象将逐行遍历 `csvfile'。`csvfile' 可以是
     任何对象，只要这个对象支持 *note iterator: 104b. 协议并在每次调用
     ‘__next__()’ 方法时都返回字符串，*note 文件对象: b4a. 和列表对象均
     适用。如果 `csvfile' 是文件对象，则打开它时应使用 ‘newline=''’。
     (1) 可选参数 `dialect' 是用于不同的 CSV 变种的特定参数组。它可以是
     *note Dialect: 1e2c. 类的子类的实例，也可以是 *note
     list_dialects(): 1e2d. 函数返回的字符串之一。另一个可选关键字参数
     `fmtparams' 可以覆写当前变种格式中的单个格式设置。有关变种和格式设
     置参数的完整详细信息，请参见 *note 变种与格式参数: 1e2e. 部分。

     csv 文件的每一行都读取为一个由字符串组成的列表。除非指定了
     ‘QUOTE_NONNUMERIC’ 格式选项（在这种情况下，未加引号的字段会转换为浮
     点数），否则不会执行自动数据类型转换。

     一个简短的用法示例:

          >>> import csv
          >>> with open('eggs.csv', newline='') as csvfile:
          ...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
          ...     for row in spamreader:
          ...         print(', '.join(row))
          Spam, Spam, Spam, Spam, Spam, Baked Beans
          Spam, Lovely Spam, Wonderful Spam

 -- 函数: csv.writer (csvfile, dialect='excel', **fmtparams)

     返回一个 writer 对象，该对象负责将用户的数据在给定的文件类对象上转
     换为带分隔符的字符串。`csvfile' 可以是具有 ‘write()’ 方法的任何对象
     。如果 `csvfile' 是文件对象，则打开它时应使用 ‘newline=''’。 (2) 可
     选参数 `dialect' 是用于不同的 CSV 变种的特定参数组。它可以是 *note
     Dialect: 1e2c. 类的子类的实例，也可以是 *note list_dialects():
     1e2d. 函数返回的字符串之一。另一个可选关键字参数 `fmtparams' 可以覆
     写当前变种格式中的单个格式设置。有关变种和格式设置参数的完整详细信
     息，请参见 *note 变种与格式参数: 1e2e. 部分。为了尽量简化与数据库
     API 模块之间的对接，*note None: 158. 值会写入为空字符串。虽然这个转
     换是不可逆的，但它让 SQL 空数据值转储到 CSV 文件更容易，而无需预处
     理从 ‘cursor.fetch*’ 调用返回的数据。写入前，所有非字符串数据都先用
     *note str(): 339. 转化为字符串再写入。

     一个简短的用法示例:

          import csv
          with open('eggs.csv', 'w', newline='') as csvfile:
              spamwriter = csv.writer(csvfile, delimiter=' ',
                                      quotechar='|', quoting=csv.QUOTE_MINIMAL)
              spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
              spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

 -- 函数: csv.register_dialect (name[, dialect[, **fmtparams]])

     将 `name' 与 `dialect' 关联起来。`name' 必须是字符串。要指定变种
     (dialect)，可以给出 *note Dialect: 1e2c. 的子类，或给出 `fmtparams'
     关键字参数，或两者都给出（此时关键字参数会覆盖 `dialect' 参数）。 有
     关变种和格式设置参数的完整详细信息，请参见 *note 变种与格式参数:
     1e2e. 部分。

 -- 函数: csv.unregister_dialect (name)

     从变种注册表中删除 `name' 对应的变种。如果 `name' 不是已注册的变种
     名称，则抛出 *note Error: 1e31. 异常。

 -- 函数: csv.get_dialect (name)

     返回 `name' 对应的变种。如果 `name' 不是已注册的变种名称，则抛出
     *note Error: 1e31. 异常。该函数返回的是不可变的 *note Dialect:
     1e2c. 对象。

 -- 函数: csv.list_dialects ()

     返回所有已注册变种的名称。

 -- 函数: csv.field_size_limit ([new_limit])

     返回解析器当前允许的最大字段大小。如果指定了 `new_limit'，则它将成
     为新的最大字段大小。

*note csv: 2a. 模块定义了以下类：

 -- 类: csv.DictReader (f, fieldnames=None, restkey=None, restval=None,
          dialect='excel', *args, **kwds)

     创建一个对象，该对象在操作上类似于常规 reader，但是将每行中的信息映
     射到一个 *note dict: 1b9.，该 dict 的键由 `fieldnames' 可选参数给出
     。

     `fieldnames' 参数是一个 *note sequence: 1238.。如果省略
     `fieldnames'，则文件 `f' 第一行中的值将用作字段名。无论字段名是如何
     确定的，字典都将保留其原始顺序。

     如果某一行中的字段多于字段名，则剩余数据会被放入一个列表，并与
     `restkey' 所指定的字段名 (默认为 ‘None’) 一起保存。 如果某个非空白
     行的字段少于字段名，则缺失的值会使用 `restval' 的值来填充 (默认为
     ‘None’)。

     所有其他可选或关键字参数都传递给底层的 *note reader: ecb. 实例。

     在 3.6 版更改: 返回的行现在的类型是 ‘OrderedDict’。

     在 3.8 版更改: 现在，返回的行是 *note dict: 1b9. 类型。

     一个简短的用法示例:

          >>> import csv
          >>> with open('names.csv', newline='') as csvfile:
          ...     reader = csv.DictReader(csvfile)
          ...     for row in reader:
          ...         print(row['first_name'], row['last_name'])
          ...
          Eric Idle
          John Cleese

          >>> print(row)
          {'first_name': 'John', 'last_name': 'Cleese'}

 -- 类: csv.DictWriter (f, fieldnames, restval='', extrasaction='raise',
          dialect='excel', *args, **kwds)

     创建一个对象，该对象在操作上类似常规 writer，但会将字典映射到输出行
     。 `fieldnames' 参数是由键组成的 *note 序列: 1f.，它指定字典中值的
     顺序，这些值会按指定顺序传递给 ‘writerow()’ 方法并写入文件 `f'。 如
     果字典缺少 `fieldnames' 中的键，则可选参数 `restval' 用于指定要写入
     的值。 如果传递给 ‘writerow()’ 方法的字典的某些键在 `fieldnames' 中
     找不到，则可选参数 `extrasaction' 用于指定要执行的操作。 如果将其设
     置为默认值 ‘'raise'’，则会引发 *note ValueError: 1fc.。 如果将其设
     置为 ‘'ignore'’，则字典中的其他键值将被忽略。 所有其他可选或关键字
     参数都传递给底层的 *note writer: e04. 实例。

     注意，与 *note DictReader: 1be. 类不同，*note DictWriter: b82. 类的
     `fieldnames' 参数不是可选参数。

     一个简短的用法示例:

          import csv

          with open('names.csv', 'w', newline='') as csvfile:
              fieldnames = ['first_name', 'last_name']
              writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

              writer.writeheader()
              writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
              writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
              writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

 -- 类: csv.Dialect

     *note Dialect: 1e2c. 类是主要依赖于其属性的容器类，用于将定义好的参
     数传递给特定的 *note reader: ecb. 或 *note writer: e04. 实例。

 -- 类: csv.excel

     *note excel: 1e34. 类定义了 Excel 生成的 CSV 文件的常规属性。它在变
     种注册表中的名称是 ‘'excel'’。

 -- 类: csv.excel_tab

     *note excel_tab: 1e35. 类定义了 Excel 生成的、制表符分隔的 CSV 文件
     的常规属性。它在变种注册表中的名称是 ‘'excel-tab'’。

 -- 类: csv.unix_dialect

     *note unix_dialect: b81. 类定义了在 UNIX 系统上生成的 CSV 文件的常
     规属性，即使用 ‘'\n'’ 作为换行符，且所有字段都有引号包围。它在变种
     注册表中的名称是 ‘'unix'’。

     3.2 新版功能.

 -- 类: csv.Sniffer

     *note Sniffer: 1e36. 类用于推断 CSV 文件的格式。

     *note Sniffer: 1e36. 类提供了两个方法：

      -- 方法: sniff (sample, delimiters=None)

          分析给定的 `sample' 并返回一个 *note Dialect: 1e2c. 子类，该子
          类中包含了分析出的格式参数。如果给出可选的 `delimiters' 参数，
          则该参数会被解释为字符串，该字符串包含了可能的有效定界符。

      -- 方法: has_header (sample)

          分析示例文本（假定为 CSV 格式），如果第一行很可能是一系列列标
          题，则返回 *note True: 4a1.。

使用 *note Sniffer: 1e36. 的示例：

     with open('example.csv', newline='') as csvfile:
         dialect = csv.Sniffer().sniff(csvfile.read(1024))
         csvfile.seek(0)
         reader = csv.reader(csvfile, dialect)
         # ... process CSV file contents here ...

*note csv: 2a. 模块定义了以下常量：

 -- 数据: csv.QUOTE_ALL

     指示 *note writer: e04. 对象给所有字段加上引号。

 -- 数据: csv.QUOTE_MINIMAL

     指示 *note writer: e04. 对象仅为包含特殊字符（例如 `定界符'、`引号
     字符' 或 `行结束符' 中的任何字符）的字段加上引号。

 -- 数据: csv.QUOTE_NONNUMERIC

     指示 *note writer: e04. 对象为所有非数字字段加上引号。

     指示 reader 将所有未用引号引出的字段转换为 `float' 类型。

 -- 数据: csv.QUOTE_NONE

     指示 *note writer: e04. 对象不使用引号引出字段。当 `定界符' 出现在
     输出数据中时，其前面应该有 `转义符'。如果未设置 `转义符'，则遇到任
     何需要转义的字符时，writer 都会抛出 *note Error: 1e31. 异常。

     指示 *note reader: ecb. 不对引号字符进行特殊处理。

*note csv: 2a. 模块定义了以下异常：

 -- 例外: csv.Error

     该异常可能由任何发生错误的函数抛出。

   ---------- Footnotes ----------

   (1) (1) 如果没有指定 ‘newline=''’，则嵌入引号中的换行符将无法正确解析
，并且在写入时，使用 ‘\r\n’ 换行的平台会有多余的 ‘\r’ 写入。由于 csv 模
块会执行自己的（*note 通用: 5fd.）换行符处理，因此指定 ‘newline=''’ 应该
总是安全的。

   (2) (1) 如果没有指定 ‘newline=''’，则嵌入引号中的换行符将无法正确解析
，并且在写入时，使用 ‘\r\n’ 换行的平台会有多余的 ‘\r’ 写入。由于 csv 模
块会执行自己的（*note 通用: 5fd.）换行符处理，因此指定 ‘newline=''’ 应该
总是安全的。


File: python.info,  Node: 变种与格式参数,  Next: Reader 对象,  Prev: 模块内容<3>,  Up: csv --- CSV 文件读写

5.14.1.2 变种与格式参数
.......................

为了更容易指定输入和输出记录的格式，特定的一组格式参数组合为一个
dialect（变种）。一个 dialect 是一个 *note Dialect: 1e2c. 类的子类，它具
有一组特定的方法和一个 ‘validate()’ 方法。创建 *note reader: ecb. 或
*note writer: e04. 对象时，程序员可以将某个字符串或 *note Dialect: 1e2c.
类的子类指定为 dialect 参数。要想补充或覆盖 `dialect' 参数，程序员还可以
单独指定某些格式参数，这些参数的名称与下面 *note Dialect: 1e2c. 类定义的
属性相同。

Dialect 类支持以下属性：

 -- 属性: Dialect.delimiter

     一个用于分隔字段的单字符，默认为 ‘','’。

 -- 属性: Dialect.doublequote

     控制出现在字段中的 `引号字符' 本身应如何被引出。当该属性为 *note
     True: 4a1. 时，双写引号字符。如果该属性为 *note False: 390.，则在
     `引号字符' 的前面放置 `转义符'。默认值为 *note True: 4a1.。

     在输出时，如果 `doublequote' 是 *note False: 390.，且 `转义符' 未指
     定，且在字段中发现 `引号字符' 时，会抛出 *note Error: 1e31. 异常。

 -- 属性: Dialect.escapechar

     一个用于 writer 的单字符，用来在 `quoting' 设置为 *note QUOTE_NONE:
     1e3c. 的情况下转义 `定界符'，在 `doublequote' 设置为 *note False:
     390. 的情况下转义 `引号字符'。在读取时，`escapechar' 去除了其后所跟
     字符的任何特殊含义。该属性默认为 *note None: 158.，表示禁用转义。

 -- 属性: Dialect.lineterminator

     放在 *note writer: e04. 产生的行的结尾，默认为 ‘'\r\n'’。

          注解: *note reader: ecb. 经过硬编码，会识别 ‘'\r'’ 或 ‘'\n'’ 作
          为行尾，并忽略 `lineterminator'。未来可能会更改这一行为。

 -- 属性: Dialect.quotechar

     一个单字符，用于包住含有特殊字符的字段，特殊字符如 `定界符' 或 `引
     号字符' 或换行符。默认为 ‘'"'’。

 -- 属性: Dialect.quoting

     控制 writer 何时生成引号，以及 reader 何时识别引号。该属性可以等于
     任何 ‘QUOTE_*’ 常量（参见 *note 模块内容: 1e2a. 段落），默认为
     *note QUOTE_MINIMAL: 1e3a.。

 -- 属性: Dialect.skipinitialspace

     如果为 *note True: 4a1.，则忽略 `定界符' 之后的空格。默认值为 *note
     False: 390.。

 -- 属性: Dialect.strict

     如果为 ‘True’，则在输入错误的 CSV 时抛出 *note Error: 1e31. 异常。
     默认值为 ‘False’。


File: python.info,  Node: Reader 对象,  Next: Writer 对象,  Prev: 变种与格式参数,  Up: csv --- CSV 文件读写

5.14.1.3 Reader 对象
....................

Reader 对象（*note DictReader: 1be. 实例和 *note reader(): ecb. 函数返回
的对象）具有以下公开方法：

 -- 方法: csvreader.__next__ ()

     返回 reader 的可迭代对象的下一行，返回值可能是列表（由 *note
     reader(): ecb. 返回的对象）或字典（由 *note DictReader: 1be. 返回的
     对象），解析是根据当前设置的变种进行的。通常应该这样调用它：
     ‘next(reader)’。

Reader 对象具有以下公开属性：

 -- 属性: csvreader.dialect

     变种描述，只读，供解析器使用。

 -- 属性: csvreader.line_num

     源迭代器已经读取了的行数。它与返回的记录数不同，因为记录可能跨越多
     行。

DictReader 对象具有以下公开属性：

 -- 属性: csvreader.fieldnames

     字段名称。如果在创建对象时未传入字段名称，则首次访问时或从文件中读
     取第一条记录时会初始化此属性。


File: python.info,  Node: Writer 对象,  Next: 例子<7>,  Prev: Reader 对象,  Up: csv --- CSV 文件读写

5.14.1.4 Writer 对象
....................

‘Writer’ 对象（*note DictWriter: b82. 实例和 *note writer(): e04. 函数返
回的对象）具有下面的公开方法。对于 ‘Writer’ 对象，`行' 必须是（一组可迭
代的）字符串或数字。对于 *note DictWriter: b82. 对象，`行' 必须是一个字
典，这个字典将字段名映射为字符串或数字（数字要先经过 *note str(): 339. 转
换类型）。请注意，输出的复数会有括号包围。这样其他程序读取 CSV 文件时可
能会有一些问题（假设它们完全支持复数）。

 -- 方法: csvwriter.writerow (row)

     将参数 `row' 写入 writer 的文件对象，并根据当前设置的变种进行格式化
     。本方法的返回值就是底层文件对象 `write' 方法的返回值。

     在 3.5 版更改: 开始支持任意类型的迭代器。

 -- 方法: csvwriter.writerows (rows)

     将 `rows*（即能迭代出多个上述 *row' 对象的迭代器）中的所有元素写入
     writer 的文件对象，并根据当前设置的变种进行格式化。

Writer 对象具有以下公开属性：

 -- 属性: csvwriter.dialect

     变种描述，只读，供 writer 使用。

DictWriter 对象具有以下公开方法：

 -- 方法: DictWriter.writeheader ()

     在 writer 的文件对象中，写入一行字段名称（字段名称在构造函数中指定
     ），并根据当前设置的变种进行格式化。本方法的返回值就是内部使用的
     *note csvwriter.writerow(): 6cd. 方法的返回值。

     3.2 新版功能.

     在 3.8 版更改: 现在 *note writeheader(): b83. 也返回其内部使用的
     *note csvwriter.writerow(): 6cd. 方法的返回值。


File: python.info,  Node: 例子<7>,  Prev: Writer 对象,  Up: csv --- CSV 文件读写

5.14.1.5 例子
.............

读取 CSV 文件最简单的一个例子:

     import csv
     with open('some.csv', newline='') as f:
         reader = csv.reader(f)
         for row in reader:
             print(row)

读取其他格式的文件:

     import csv
     with open('passwd', newline='') as f:
         reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
         for row in reader:
             print(row)

相应最简单的写入示例是:

     import csv
     with open('some.csv', 'w', newline='') as f:
         writer = csv.writer(f)
         writer.writerows(someiterable)

由于使用 *note open(): 4f8. 来读取 CSV 文件，因此默认情况下，将使用系统
默认编码来解码文件并转换为 unicode（请参阅 *note
locale.getpreferredencoding(): 3ad.）。要使用其他编码来解码文件，请使用
open 的 ‘encoding’ 参数:

     import csv
     with open('some.csv', newline='', encoding='utf-8') as f:
         reader = csv.reader(f)
         for row in reader:
             print(row)

这同样适用于写入非系统默认编码的内容：打开输出文件时，指定 encoding 参数
。

注册一个新的变种:

     import csv
     csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
     with open('passwd', newline='') as f:
         reader = csv.reader(f, 'unixpwd')

Reader 的更高级用法——捕获并报告错误:

     import csv, sys
     filename = 'some.csv'
     with open(filename, newline='') as f:
         reader = csv.reader(f)
         try:
             for row in reader:
                 print(row)
         except csv.Error as e:
             sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))

尽管该模块不直接支持解析字符串，但仍可如下轻松完成:

     import csv
     for row in csv.reader(['one,two,three']):
         print(row)

备注
....


File: python.info,  Node: configparser --- 配置文件解析器,  Next: netrc --- netrc 文件处理,  Prev: csv --- CSV 文件读写,  Up: 文件格式

5.14.2 ‘configparser’ — 配置文件解析器
--------------------------------------

`源代码:' Lib/configparser.py(1)

__________________________________________________________________

此模块提供了它实现一种基本配置语言 *note ConfigParser: 4b2. 类，这种语言
所提供的结构与 Microsoft Windows INI 文件的类似。 你可以使用这种语言来编
写能够由最终用户来自定义的 Python 程序。

     注解: 这个库 `并不' 能够解析或写入在 Windows Registry 扩展版本 INI
     语法中所使用的值-类型前缀。

参见
....

模块 *note shlex: e9.

     支持创建可被用作应用配置文件的替代的 Unix 终端式微语言。

模块 *note json: a5.

     json 模块实现了一个 JavaScript 语法的子集，它也可被用于这种目的。

* Menu:

* 快速起步::
* 支持的数据类型::
* 回退值::
* 受支持的 INI 文件结构::
* 值的插值::
* 映射协议访问::
* 定制解析器行为::
* 旧式 API 示例::
* ConfigParser 对象::
* RawConfigParser 对象::
* 异常: 异常<5>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/configparser.py


File: python.info,  Node: 快速起步,  Next: 支持的数据类型,  Up: configparser --- 配置文件解析器

5.14.2.1 快速起步
.................

让我们准备一个非常基本的配置文件，它看起来是这样的:

     [DEFAULT]
     ServerAliveInterval = 45
     Compression = yes
     CompressionLevel = 9
     ForwardX11 = yes

     [bitbucket.org]
     User = hg

     [topsecret.server.com]
     Port = 50022
     ForwardX11 = no

INI 文件的结构描述见 *note 以下章节: 1e53.。 总的来说，这种文件由多个节
组成，每个节包含多个带有值的键。 *note configparser: 23. 类可以读取和写
入这种文件。 让我们先通过程序方式来创建上述的配置文件。

     >>> import configparser
     >>> config = configparser.ConfigParser()
     >>> config['DEFAULT'] = {'ServerAliveInterval': '45',
     ...                      'Compression': 'yes',
     ...                      'CompressionLevel': '9'}
     >>> config['bitbucket.org'] = {}
     >>> config['bitbucket.org']['User'] = 'hg'
     >>> config['topsecret.server.com'] = {}
     >>> topsecret = config['topsecret.server.com']
     >>> topsecret['Port'] = '50022'     # mutates the parser
     >>> topsecret['ForwardX11'] = 'no'  # same here
     >>> config['DEFAULT']['ForwardX11'] = 'yes'
     >>> with open('example.ini', 'w') as configfile:
     ...   config.write(configfile)
     ...

如你所见，我们可以把配置解析器当作一个字典来处理。 两者确实存在差异，
*note 将在后文说明: 1e54.，但是其行为非常接近于字典所具有一般行为。

现在我们已经创建并保存了一个配置文件，让我们再将它读取出来并探究其中包含
的数据。

     >>> config = configparser.ConfigParser()
     >>> config.sections()
     []
     >>> config.read('example.ini')
     ['example.ini']
     >>> config.sections()
     ['bitbucket.org', 'topsecret.server.com']
     >>> 'bitbucket.org' in config
     True
     >>> 'bytebong.com' in config
     False
     >>> config['bitbucket.org']['User']
     'hg'
     >>> config['DEFAULT']['Compression']
     'yes'
     >>> topsecret = config['topsecret.server.com']
     >>> topsecret['ForwardX11']
     'no'
     >>> topsecret['Port']
     '50022'
     >>> for key in config['bitbucket.org']:
     ...     print(key)
     user
     compressionlevel
     serveraliveinterval
     compression
     forwardx11
     >>> config['bitbucket.org']['ForwardX11']
     'yes'

正如我们在上面所看到的，相关的 API 相当直观。 唯一有些神奇的地方是
‘DEFAULT’ 小节，它为所有其他小节提供了默认值 (1)。 还要注意小节中的键大
小写不敏感并且会存储为小写形式 (2)。

   ---------- Footnotes ----------

   (1) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1e55. 一节。

   (2) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1e55. 一节。


File: python.info,  Node: 支持的数据类型,  Next: 回退值,  Prev: 快速起步,  Up: configparser --- 配置文件解析器

5.14.2.2 支持的数据类型
.......................

配置解析器并不会猜测配置文件中值的类型，而总是将它们在内部存储为字符串。
这意味着如果你需要其他数据类型，你应当自己来转换:

     >>> int(topsecret['Port'])
     50022
     >>> float(topsecret['CompressionLevel'])
     9.0

由于这种任务十分常用，配置解析器提供了一系列便捷的获取方法来处理整数、浮
点数和布尔值。 最后一个类型的处理最为有趣，因为简单地将值传给 ‘bool()’ 是
没有用的，‘bool('False')’ 仍然会是 ‘True’。 为解决这个问题配置解析器还提
供了 *note getboolean(): 1e57.。 这个方法对大小写不敏感并可识别
‘'yes'’/‘'no'’, ‘'on'’/‘'off'’, ‘'true'’/‘'false'’ 和 ‘'1'’/‘'0'’ (1) 等
布尔值。 例如:

     >>> topsecret.getboolean('ForwardX11')
     False
     >>> config['bitbucket.org'].getboolean('ForwardX11')
     True
     >>> config.getboolean('bitbucket.org', 'Compression')
     True

除了 *note getboolean(): 1e57.，配置解析器还提供了同类的 *note getint():
1e58. 和 *note getfloat(): 1e59. 方法。 你可以注册你自己的转换器并或是定
制已提供的转换器。 (2)

   ---------- Footnotes ----------

   (1) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1e55. 一节。

   (2) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1e55. 一节。


File: python.info,  Node: 回退值,  Next: 受支持的 INI 文件结构,  Prev: 支持的数据类型,  Up: configparser --- 配置文件解析器

5.14.2.3 回退值
...............

与字典类似，你可以使用某个小节的 ‘get()’ 方法来提供回退值:

     >>> topsecret.get('Port')
     '50022'
     >>> topsecret.get('CompressionLevel')
     '9'
     >>> topsecret.get('Cipher')
     >>> topsecret.get('Cipher', '3des-cbc')
     '3des-cbc'

请注意默认值会优先于回退值。 例如，在我们的示例中 ‘'CompressionLevel'’ 键
仅在 ‘'DEFAULT'’ 小节被指定。 如果你尝试在 ‘'topsecret.server.com'’ 小节
获取它，我们将总是获取到默认值，即使我们指定了一个回退值:

     >>> topsecret.get('CompressionLevel', '3')
     '9'

还需要注意的一点是解析器层级的 ‘get()’ 方法提供了自定义的更复杂接口，它
被维护用于向下兼容。 当使用此方法时，回退值可以通过 ‘fallback’ 仅限关键
字参数来提供:

     >>> config.get('bitbucket.org', 'monster',
     ...            fallback='No such things as monsters')
     'No such things as monsters'

同样的 ‘fallback’ 参数也可在 *note getint(): 1e58, *note getfloat():
1e59. 和 *note getboolean(): 1e57. 方法中使用，例如:

     >>> 'BatchMode' in topsecret
     False
     >>> topsecret.getboolean('BatchMode', fallback=True)
     True
     >>> config['DEFAULT']['BatchMode'] = 'no'
     >>> topsecret.getboolean('BatchMode', fallback=True)
     False


File: python.info,  Node: 受支持的 INI 文件结构,  Next: 值的插值,  Prev: 回退值,  Up: configparser --- 配置文件解析器

5.14.2.4 受支持的 INI 文件结构
..............................

配置文件是由小节组成的，每个小节都有一个 ‘[section]’ 标头，加上多个由特
定字符串 (默认为 ‘=’ 或 ‘:’ (1)) 分隔的键/值条目。 默认情况下小节名对大
小写敏感而键对大小写不敏感 (2)。 键和值开头和末尾的空格会被移除。 值可以
被省略，在此情况下键/值分隔符也可以被省略。 值还可以跨越多行，只要其他行
带有比值的第一行更深的缩进。 依据解析器的具体模式，空白行可能被视为多行
值的组成部分也可能被忽略。

配置文件可以包含注释，要带有指定字符前缀 (默认为 ‘#’ 和 ‘;’ (3))。 注释
可以单独出现于原本的空白行，并可使用缩进。 (4)

例如:

     [Simple Values]
     key=value
     spaces in keys=allowed
     spaces in values=allowed as well
     spaces around the delimiter = obviously
     you can also use : to delimit keys from values

     [All Values Are Strings]
     values like this: 1000000
     or this: 3.14159265359
     are they treated as numbers? : no
     integers, floats and booleans are held as: strings
     can use the API to get converted values directly: true

     [Multiline Values]
     chorus: I'm a lumberjack, and I'm okay
         I sleep all night and I work all day

     [No Values]
     key_without_value
     empty string value here =

     [You can use comments]
     # like this
     ; or this

     # By default only in an empty line.
     # Inline comments can be harmful because they prevent users
     # from using the delimiting characters as parts of values.
     # That being said, this can be customized.

         [Sections Can Be Indented]
             can_values_be_as_well = True
             does_that_mean_anything_special = False
             purpose = formatting for readability
             multiline_values = are
                 handled just fine as
                 long as they are indented
                 deeper than the first line
                 of a value
             # Did I mention we can indent comments, too?

   ---------- Footnotes ----------

   (1) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1e55. 一节。

   (2) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1e55. 一节。

   (3) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1e55. 一节。

   (4) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1e55. 一节。


File: python.info,  Node: 值的插值,  Next: 映射协议访问,  Prev: 受支持的 INI 文件结构,  Up: configparser --- 配置文件解析器

5.14.2.5 值的插值
.................

在核心功能之上，*note ConfigParser: 4b2. 还支持插值。 这意味着值可以在被
‘get()’ 调用返回之前进行预处理。

 -- 类: configparser.BasicInterpolation

     默认实现由 *note ConfigParser: 4b2. 来使用。 它允许值包含引用了相同
     小节中其他值或者特殊的默认小节中的值的格式字符串 (1)。 额外的默认值
     可以在初始化时提供。

     例如:

          [Paths]
          home_dir: /Users
          my_dir: %(home_dir)s/lumberjack
          my_pictures: %(my_dir)s/Pictures

          [Escape]
          gain: 80%%  # use a %% to escape the % sign (% is the only character that needs to be escaped)

     在上面的例子里，*note ConfigParser: 4b2. 的 `interpolation' 设为
     ‘BasicInterpolation()’，这会将 ‘%(home_dir)s’ 求解为 ‘home_dir’ 的
     值 (在这里是 ‘/Users’)。 ‘%(my_dir)s’ 的将被实际求解为
     ‘/Users/lumberjack’。 所有插值都是按需进行的，这样引用链中使用的键
     不必以任何特定顺序在配置文件中指明。

     当 ‘interpolation’ 设为 ‘None’ 时，解析器会简单地返回
     ‘%(my_dir)s/Pictures’ 作为 ‘my_pictures’ 的值，并返回
     ‘%(home_dir)s/lumberjack’ 作为 ‘my_dir’ 的值。

 -- 类: configparser.ExtendedInterpolation

     一个用于插值的替代处理程序实现了更高级的语法，它被用于
     ‘zc.buildout’ 中的实例。 扩展插值使用 ‘${section:option}’ 来表示来
     自外部小节的值。 插值可以跨越多个层级。 为了方便使用，‘section:’ 部
     分可被省略，插值会默认作用于当前小节（可能会从特殊小节获取默认值）
     。

     例如，上面使用基本插值描述的配置，使用扩展插值将是这个样子:

          [Paths]
          home_dir: /Users
          my_dir: ${home_dir}/lumberjack
          my_pictures: ${my_dir}/Pictures

          [Escape]
          cost: $$80  # use a $$ to escape the $ sign ($ is the only character that needs to be escaped)

     来自其他小节的值也可以被获取:

          [Common]
          home_dir: /Users
          library_dir: /Library
          system_dir: /System
          macports_dir: /opt/local

          [Frameworks]
          Python: 3.2
          path: ${Common:system_dir}/Library/Frameworks/

          [Arthur]
          nickname: Two Sheds
          last_name: Jackson
          my_dir: ${Common:home_dir}/twosheds
          my_pictures: ${my_dir}/Pictures
          python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}

   ---------- Footnotes ----------

   (1) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1e55. 一节。


File: python.info,  Node: 映射协议访问,  Next: 定制解析器行为,  Prev: 值的插值,  Up: configparser --- 配置文件解析器

5.14.2.6 映射协议访问
.....................

3.2 新版功能.

映射协议访问这个通用名称是指允许以字典的方式来使用自定义对象的功能。 在
*note configparser: 23. 中，映射接口的实现使用了
‘parser['section']['option']’ 标记法。

‘parser['section']’ 专门为解析器中的小节数据返回一个代理。 这意味着其中
的值不会被拷贝，而是在需要时从原始解析器中获取。 更为重要的是，当值在小
节代理上被修改时，它们其实是在原始解析器中发生了改变。

*note configparser: 23. 对象的行为会尽可能地接近真正的字典。 映射接口是
完整而且遵循 *note MutableMapping: 9f7. ABC 规范的。 但是，还是有一些差
异应当被纳入考虑:

   * 默认情况下，小节中的所有键是以大小写不敏感的方式来访问的 (1)。 例如
     ‘for option in parser["section"]’ 只会产生 ‘optionxform’ 形式的选项
     键名称。 也就是说默认使用小写字母键名。 与此同时，对于一个包含键
     ‘'a'’ 的小节，以下两个表达式均将返回 ‘True’:

          "a" in parser["section"]
          "A" in parser["section"]

   * 所有小节也包括 ‘DEFAULTSECT’，这意味着对一个小节执行 ‘.clear()’ 可
     能无法使得该小节显示为空。 这是因为默认值是无法从小节中被删除的（因
     为从技术上说它们并不在那里）。 如果它们在小节中被覆盖，删除将导致默
     认值重新变为可见。 尝试删除默认值将会引发 *note KeyError: 2c8.。

   * ‘DEFAULTSECT’ 无法从解析器中被移除:

        * 尝试删除将引发 *note ValueError: 1fc.，

        * ‘parser.clear()’ 会保留其原状，

        * ‘parser.popitem()’ 绝不会将其返回。

   * ‘parser.get(section, option, **kwargs)’ - 第二个参数 `并非' 回退值
     。 但是请注意小节层级的 ‘get()’ 方法可同时兼容映射协议和经典配置解
     析器 API。

   * ‘parser.items()’ 兼容映射协议（返回 `section_name', `section_proxy'
     对的列表，包括 DEFAULTSECT）。 但是，此方法也可以带参数发起调用:
     ‘parser.items(section, raw, vars)’。 这种调用形式返回指定 ‘section’
     的 `option', `value' 对的列表，将展开所有插值（除非提供了
     ‘raw=True’ 选项）。

映射协议是在现有的传统 API 之上实现的，以便重载原始接口的子类仍然具有符
合预期的有效映射。

   ---------- Footnotes ----------

   (1) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1e55. 一节。


File: python.info,  Node: 定制解析器行为,  Next: 旧式 API 示例,  Prev: 映射协议访问,  Up: configparser --- 配置文件解析器

5.14.2.7 定制解析器行为
.......................

INI 格式的变种数量几乎和使用此格式的应用一样多。 *note configparser: 23.
花费了很大力气来为尽量大范围的可用 INI 样式提供支持。 默认的可用功能主要
由历史状况来确定，你很可能会想要定制某些特性。

改变特定配置解析器行为的最常见方式是使用 *note __init__(): d66. 选项:

   * `defaults'，默认值: ‘None’

     此选项接受一个键值对的字典，它将被首先放入 ‘DEFAULT’ 小节。 这实现
     了一种优雅的方式来支持简洁的配置文件，它不必指定与已记录的默认值相
     同的值。

     提示：如果你想要为特定的小节指定默认的值，请在读取实际文件之前使用
     ‘read_dict()’。

   * `dict_type'，默认值: *note dict: 1b9.

     此选项主要影响映射协议的行为和写入配置文件的外观。 使用标准字典时，
     每个小节是按照它们被加入解析器的顺序保存的。 在小节内的选项也是如此
     。

     还有其他替换的字典类型可以使用，例如在写回数据时对小节和选项进行排
     序。

     请注意：存在其他方式只用一次操作来添加键值对的集合。 当你在这些操作
     中使用一个常规字典时，键将按顺序进行排列。 例如:

          >>> parser = configparser.ConfigParser()
          >>> parser.read_dict({'section1': {'key1': 'value1',
          ...                                'key2': 'value2',
          ...                                'key3': 'value3'},
          ...                   'section2': {'keyA': 'valueA',
          ...                                'keyB': 'valueB',
          ...                                'keyC': 'valueC'},
          ...                   'section3': {'foo': 'x',
          ...                                'bar': 'y',
          ...                                'baz': 'z'}
          ... })
          >>> parser.sections()
          ['section1', 'section2', 'section3']
          >>> [option for option in parser['section3']]
          ['foo', 'bar', 'baz']

   * `allow_no_value'，默认值: ‘False’

     已知某些配置文件会包括不带值的设置，但其在其他方面均符合 *note
     configparser: 23. 所支持的语法。 构造器的 `allow_no_value' 形参可用
     于指明应当接受这样的值:

          >>> import configparser

          >>> sample_config = """
          ... [mysqld]
          ...   user = mysql
          ...   pid-file = /var/run/mysqld/mysqld.pid
          ...   skip-external-locking
          ...   old_passwords = 1
          ...   skip-bdb
          ...   # we don't need ACID today
          ...   skip-innodb
          ... """
          >>> config = configparser.ConfigParser(allow_no_value=True)
          >>> config.read_string(sample_config)

          >>> # Settings with values are treated as before:
          >>> config["mysqld"]["user"]
          'mysql'

          >>> # Settings without values provide None:
          >>> config["mysqld"]["skip-bdb"]

          >>> # Settings which aren't specified still raise an error:
          >>> config["mysqld"]["does-not-exist"]
          Traceback (most recent call last):
            ...
          KeyError: 'does-not-exist'

   * `delimiters'，默认值: ‘('=', ':')’

     分隔符是用于在小节内分隔键和值的子字符串。 在一行中首次出现的分隔子
     字符串会被视为一个分隔符。 这意味着值可以包含分隔符（但键不可以）。

     另请参见 *note ConfigParser.write(): 1e5d. 的
     `space_around_delimiters' 参数。

   * `comment_prefixes'，默认值: ‘('#', ';')’

   * `inline_comment_prefixes'，默认值: ‘None’

     注释前缀是配置文件中用于标示一条有效注释的开头的字符串。
     `comment_prefixes' 仅用在被视为空白的行（可以缩进）之前而
     `inline_comment_prefixes' 可用在每个有效值之后（例如小节名称、选项
     以及空白的行）。 默认情况下禁用行内注释，并且 ‘'#'’ 和 ‘';'’ 都被用
     作完整行注释的前缀。

     在 3.2 版更改: 在之前的 *note configparser: 23. 版本中行为匹配
     ‘comment_prefixes=('#',';')’ 和 ‘inline_comment_prefixes=(';',)’。

     请注意配置解析器不支持对注释前缀的转义，因此使用
     `inline_comment_prefixes' 可能妨碍用户将被用作注释前缀的字符指定为
     可选值。 当有疑问时，请避免设置 `inline_comment_prefixes'。 在许多
     情况下，在多行值的一行开头存储注释前缀字符的唯一方式是进行前缀插值
     ，例如:

          >>> from configparser import ConfigParser, ExtendedInterpolation
          >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
          >>> # the default BasicInterpolation could be used as well
          >>> parser.read_string("""
          ... [DEFAULT]
          ... hash = #
          ...
          ... [hashes]
          ... shebang =
          ...   ${hash}!/usr/bin/env python
          ...   ${hash} -*- coding: utf-8 -*-
          ...
          ... extensions =
          ...   enabled_extension
          ...   another_extension
          ...   #disabled_by_comment
          ...   yet_another_extension
          ...
          ... interpolation not necessary = if # is not at line start
          ... even in multiline values = line #1
          ...   line #2
          ...   line #3
          ... """)
          >>> print(parser['hashes']['shebang'])

          #!/usr/bin/env python
          # -*- coding: utf-8 -*-
          >>> print(parser['hashes']['extensions'])

          enabled_extension
          another_extension
          yet_another_extension
          >>> print(parser['hashes']['interpolation not necessary'])
          if # is not at line start
          >>> print(parser['hashes']['even in multiline values'])
          line #1
          line #2
          line #3

   * `strict'，默认值: ‘True’

     当设为 ‘True’ 时，解析器在从单一源读取 (使用 ‘read_file()’,
     ‘read_string()’ 或 ‘read_dict()’) 期间将不允许任何小节或选项出现重
     复。 推荐在新的应用中使用严格解析器。

     在 3.2 版更改: 在之前的 *note configparser: 23. 版本中行为匹配
     ‘strict=False’。

   * `empty_lines_in_values'，默认值: ‘True’

     在配置解析器中，值可以包含多行，只要它们的缩进级别低于它们所对应的
     键。 默认情况下解析器还会将空行视为值的一部分。 于此同时，键本身也
     可以任意缩进以提升可读性。 因此，当配置文件变得非常庞大而复杂时，用
     户很容易失去对文件结构的掌控。 例如:

          [Section]
          key = multiline
            value with a gotcha

           this = is still a part of the multiline value of 'key'

     在用户查看时这可能会特别有问题，如果她是使用比例字体来编辑文件的话
     。 这就是为什么当你的应用不需要带有空行的值时，你应该考虑禁用它们。
     这将使得空行每次都会作为键之间的分隔。 在上面的示例中，空行产生了两
     个键，‘key’ 和 ‘this’。

   * `default_section'，默认值: ‘configparser.DEFAULTSECT’ (即:
     ‘"DEFAULT"’)

     允许设置一个保存默认值的特殊节在其他节或插值等目的中使用的惯例是这
     个库所拥有的一个强大概念，使得用户能够创建复杂的声明性配置。 这种特
     殊节通常称为 ‘"DEFAULT"’ 但也可以被定制为指向任何其他有效的节名称。
     一些典型的值包括: ‘"general"’ 或 ‘"common"’。 所提供的名称在从任意
     节读取的时候被用于识别默认的节，而且也会在将配置写回文件时被使用。
     它的当前值可以使用 ‘parser_instance.default_section’ 属性来获取，并
     且可以在运行时被修改（即将文件从一种格式转换为另一种格式）。

   * `interpolation'，默认值: ‘configparser.BasicInterpolation’

     插值行为可以用通过提供 `interpolation' 参数提供自定义处理程序的方式
     来定制。 ‘None’ 可用来完全禁用插值，‘ExtendedInterpolation()’ 提供
     了一种更高级的变体形式，它的设计受到了 ‘zc.buildout’ 的启发。 有关
     该主题的更多信息请参见 *note 专门的文档章节: 1e5b.。 *note
     RawConfigParser: 87a. 具有默认的值 ‘None’。

   * `converters'，默认值: 不设置

     配置解析器提供了可选的值获取方法用来执行类型转换。 默认实现包括
     *note getint(): 1e58, *note getfloat(): 1e59. 以及 *note
     getboolean(): 1e57.。 如果还需要其他获取方法，用户可以在子类中定义
     它们，或者传入一个字典，其中每个键都是一个转换器的名称而每个值都是
     一个实现了特定转换的可调用对象。 例如，传入 ‘{'decimal':
     decimal.Decimal}’ 将对解释器对象和所有节代理添加 ‘getdecimal()’。 换
     句话说，可以同时编写 ‘parser_instance.getdecimal('section', 'key',
     fallback=0)’ 和 ‘parser_instance['section'].getdecimal('key', 0)’。

     如果转换器需要访问解析器的状态，可以在配置解析器子类上作为一个方法
     来实现。 如果该方法的名称是以 ‘get’ 打头的，它将在所有节代理上以兼
     容字典的形式提供（参见上面的 ‘getdecimal()’ 示例）。

更多高级定制选项可通过重载这些解析器属性的默认值来达成。 默认值是在类中
定义的，因此它们可以通过子类或属性赋值来重载。

 -- 属性: ConfigParser.BOOLEAN_STATES

     默认情况下当使用 *note getboolean(): 1e57. 时，配置解析器会将下列值
     视为 ‘True’: ‘'1'’, ‘'yes'’, ‘'true'’, ‘'on'’ 而将下列值视为
     ‘False’: ‘'0'’, ‘'no'’, ‘'false'’, ‘'off'’。 你可以通过指定一个自定
     义的字符串键及其对应的布尔值字典来重载此行为。 例如:

          >>> custom = configparser.ConfigParser()
          >>> custom['section1'] = {'funky': 'nope'}
          >>> custom['section1'].getboolean('funky')
          Traceback (most recent call last):
          ...
          ValueError: Not a boolean: nope
          >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
          >>> custom['section1'].getboolean('funky')
          False

     其他典型的布尔值对包括 ‘accept’/‘reject’ 或 ‘enabled’/‘disabled’。

 -- 方法: ConfigParser.optionxform (option)

     这个方法会转换每次 read, get, 或 set 操作的选项名称。 默认会将名称
     转换为小写形式。 这也意味着当一个配置文件被写入时，所有键都将为小写
     形式。 如果此行为不合适则要重载此方法。 例如:

          >>> config = """
          ... [Section1]
          ... Key = Value
          ...
          ... [Section2]
          ... AnotherKey = Value
          ... """
          >>> typical = configparser.ConfigParser()
          >>> typical.read_string(config)
          >>> list(typical['Section1'].keys())
          ['key']
          >>> list(typical['Section2'].keys())
          ['anotherkey']
          >>> custom = configparser.RawConfigParser()
          >>> custom.optionxform = lambda option: option
          >>> custom.read_string(config)
          >>> list(custom['Section1'].keys())
          ['Key']
          >>> list(custom['Section2'].keys())
          ['AnotherKey']

          注解: optionxform 函数会将选项名称转换为规范形式。 这应该是一
          个幂等函数：如果名称已经为规范形式，则应不加修改地将其返回。

 -- 属性: ConfigParser.SECTCRE

     一个已编译正则表达式会被用来解析节标头。 默认将 ‘[section]’ 匹配到
     名称 ‘"section"’。 空格会被视为节名称的一部分，因此 ‘[ larch ]’ 将
     被读取为一个名称为 ‘" larch "’ 的节。 如果此行为不合适则要重载此属
     性。 例如:

          >>> import re
          >>> config = """
          ... [Section 1]
          ... option = value
          ...
          ... [  Section 2  ]
          ... another = val
          ... """
          >>> typical = configparser.ConfigParser()
          >>> typical.read_string(config)
          >>> typical.sections()
          ['Section 1', '  Section 2  ']
          >>> custom = configparser.ConfigParser()
          >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
          >>> custom.read_string(config)
          >>> custom.sections()
          ['Section 1', 'Section 2']

          注解: 虽然 ConfigParser 对象也使用 ‘OPTCRE’ 属性来识别选项行，
          但并不推荐重载它，因为这会与构造器选项 `allow_no_value' 和
          `delimiters' 产生冲突。


File: python.info,  Node: 旧式 API 示例,  Next: ConfigParser 对象,  Prev: 定制解析器行为,  Up: configparser --- 配置文件解析器

5.14.2.8 旧式 API 示例
......................

主要出于向下兼容性的考虑，*note configparser: 23. 还提供了一种采用显式
‘get’/‘set’ 方法的旧式 API。 虽然以下介绍的方法存在有效的用例，但对于新
项目仍建议采用映射协议访问。 旧式 API 在多数时候都更复杂、更底层并且完全
违反直觉。

一个写入配置文件的示例:

     import configparser

     config = configparser.RawConfigParser()

     # Please note that using RawConfigParser's set functions, you can assign
     # non-string values to keys internally, but will receive an error when
     # attempting to write to a file or when you get it in non-raw mode. Setting
     # values using the mapping protocol or ConfigParser's set() does not allow
     # such assignments to take place.
     config.add_section('Section1')
     config.set('Section1', 'an_int', '15')
     config.set('Section1', 'a_bool', 'true')
     config.set('Section1', 'a_float', '3.1415')
     config.set('Section1', 'baz', 'fun')
     config.set('Section1', 'bar', 'Python')
     config.set('Section1', 'foo', '%(bar)s is %(baz)s!')

     # Writing our configuration file to 'example.cfg'
     with open('example.cfg', 'w') as configfile:
         config.write(configfile)

一个再次读取配置文件的示例:

     import configparser

     config = configparser.RawConfigParser()
     config.read('example.cfg')

     # getfloat() raises an exception if the value is not a float
     # getint() and getboolean() also do this for their respective types
     a_float = config.getfloat('Section1', 'a_float')
     an_int = config.getint('Section1', 'an_int')
     print(a_float + an_int)

     # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
     # This is because we are using a RawConfigParser().
     if config.getboolean('Section1', 'a_bool'):
         print(config.get('Section1', 'foo'))

要获取插值，请使用 *note ConfigParser: 4b2.:

     import configparser

     cfg = configparser.ConfigParser()
     cfg.read('example.cfg')

     # Set the optional *raw* argument of get() to True if you wish to disable
     # interpolation in a single get operation.
     print(cfg.get('Section1', 'foo', raw=False))  # -> "Python is fun!"
     print(cfg.get('Section1', 'foo', raw=True))   # -> "%(bar)s is %(baz)s!"

     # The optional *vars* argument is a dict with members that will take
     # precedence in interpolation.
     print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
                                            'baz': 'evil'}))

     # The optional *fallback* argument can be used to provide a fallback value
     print(cfg.get('Section1', 'foo'))
           # -> "Python is fun!"

     print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
           # -> "Python is fun!"

     print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
           # -> "No such things as monsters."

     # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
     # but we can also use:

     print(cfg.get('Section1', 'monster', fallback=None))
           # -> None

默认值在两种类型的 ConfigParser 中均可用。 它们将在当某个选项未在别处定
义时被用于插值。

     import configparser

     # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
     config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
     config.read('example.cfg')

     print(config.get('Section1', 'foo'))     # -> "Python is fun!"
     config.remove_option('Section1', 'bar')
     config.remove_option('Section1', 'baz')
     print(config.get('Section1', 'foo'))     # -> "Life is hard!"


File: python.info,  Node: ConfigParser 对象,  Next: RawConfigParser 对象,  Prev: 旧式 API 示例,  Up: configparser --- 配置文件解析器

5.14.2.9 ConfigParser 对象
..........................

 -- 类: configparser.ConfigParser (defaults=None, dict_type=dict,
          allow_no_value=False, delimiters=('=', ':'),
          comment_prefixes=('#', ';'), inline_comment_prefixes=None,
          strict=True, empty_lines_in_values=True,
          default_section=configparser.DEFAULTSECT,
          interpolation=BasicInterpolation(), converters={})

     主配置解析器。 当给定 `defaults' 时，它会被初始化为包含固有默认值的
     字典。 当给定 `dict_type' 时，它将被用来创建包含节、节中的选项以及
     默认值的字典。

     当给定 `delimiters' 时，它会被用作分隔键与值的子字符串的集合。 当给
     定 `comment_prefixes' 时，它将被用作在否则为空行的注释的前缀子字符
     串的集合。 注释可以被缩进。 当给定 `inline_comment_prefixes' 时，它
     将被用作非空行的注释的前缀子字符串的集合。

     当 `strict' 为 ‘True’ (默认值) 时，解析器在从单个源（文件、字符串或
     字典）读取时将不允许任何节或选项出现重复，否则会引发 *note
     DuplicateSectionError: c0d. 或 *note DuplicateOptionError: c0e.。 当
     `empty_lines_in_values' 为 ‘False’ (默认值: ‘True’) 时，每个空行均
     表示一个选项的结束。 在其他情况下，一个多行选项内部的空行会被保留为
     值的一部分。 当 `allow_no_value' 为 ‘True’ (默认值: ‘False’) 时，将
     接受没有值的选项；此种选项的值将为 ‘None’ 并且它们会以不带末尾分隔
     符的形式被序列化。

     当给定 `default_section' 时，它将指定存放其他节的默认值和用于插值的
     特殊节的名称 (通常命名为 ‘"DEFAULT"’)。 该值可通过使用
     ‘default_section’ 实例属性在运行时被读取或修改。

     插值行为可通过给出 `interpolation' 参数提供自定义处理程序的方式来定
     制。 ‘None’ 可用来完全禁用插值，‘ExtendedInterpolation()’ 提供了一
     种更高级的变体形式，它的设计受到了 ‘zc.buildout’ 的启发。 有关该主
     题的更多信息请参见 *note 专门的文档章节: 1e5b.。

     插值中使用的所有选项名称将像任何其他选项名称引用一样通过 *note
     optionxform(): 1e63. 方法来传递。 例如，使用 *note optionxform():
     1e63. 的默认实现（它会将选项名称转换为小写形式）时，值 ‘foo
     %(bar)s’ 和 ‘foo %(BAR)s’ 是等价的。

     当给定 `converters' 时，它应当为一个字典，其中每个键代表一个类型转
     换器的名称而每个值则为实现从字符串到目标数据类型的转换的可调用对象
     。 每个转换器会获得其在解析器对象和节代理上对应的 ‘get*()’ 方法。

     在 3.1 版更改: 默认的 `dict_type' 为 *note collections.OrderedDict:
     1ba.。

     在 3.2 版更改: 添加了 `allow_no_value', `delimiters',
     `comment_prefixes', `strict', `empty_lines_in_values',
     `default_section' 以及 `interpolation'。

     在 3.5 版更改: 添加了 `converters' 参数。

     在 3.7 版更改: `defaults' 参数会通过 *note read_dict(): 1e64. 来读
     取，提供全解析器范围内一致的行为：非字符串类型的键和值会被隐式地转
     换为字符串。

     在 3.8 版更改: 默认的 `dict_type' 为 *note dict: 1b9.，因为它现在会
     保留插入顺序。

      -- 方法: defaults ()

          返回包含实例范围内默认值的字典。

      -- 方法: sections ()

          返回可用节的列表；`default section' 不包括在该列表中。

      -- 方法: add_section (section)

          向实例添加一个名为 `section' 的节。 如果给定名称的节已存在，将
          会引发 *note DuplicateSectionError: c0d.。 如果传入了 `default
          section' 名称，则会引发 *note ValueError: 1fc.。 节名称必须为
          字符串；如果不是则会引发 *note TypeError: 193.。

          在 3.2 版更改: 非字符串的节名称将引发 *note TypeError: 193.。

      -- 方法: has_section (section)

          指明相应名称的 `section' 是否存在于配置中。 `default section'
          不包含在内。

      -- 方法: options (section)

          返回指定 `section' 中可用选项的列表。

      -- 方法: has_option (section, option)

          如果给定的 `section' 存在并且包含给定的 `option' 则返回 *note
          True: 4a1.；否则返回 *note False: 390.。 如果指定的 `section'
          为 *note None: 158. 或空字符串，则会使用 DEFAULT。

      -- 方法: read (filenames, encoding=None)

          尝试读取并解析一个包含文件名的可迭代对象，返回一个被成功解析的
          文件名列表。

          如果 `filenames' 为字符串、*note bytes: 33a. 对象或 *note
          path-like object: 373.，它会被当作单个文件来处理。 如果
          `filenames' 中名称对应的某个文件无法被打开，该文件将被忽略。 这
          样的设计使得你可以指定包含多个潜在配置文件位置的可迭代对象（例
          如当前目录、用户家目录以及某个系统级目录），存在于该可迭代对象
          中的所有配置文件都将被读取。

          如果名称对应的文件全都不存在，则 *note ConfigParser: 4b2. 实例
          将包含一个空数据集。 一个要求从文件加载初始值的应用应当在调用
          *note read(): 10b4. 来获取任何可选文件之前使用 *note
          read_file(): 1e6a. 来加载所要求的一个或多个文件:

               import configparser, os

               config = configparser.ConfigParser()
               config.read_file(open('defaults.cfg'))
               config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
                           encoding='cp1250')

          3.2 新版功能: `encoding' 形参。 在之前的版本中，所有文件都将使
          用 *note open(): 4f8. 的默认编码格式来读取。

          3.6.1 新版功能: `filenames' 形参接受一个 *note path-like
          object: 373.。

          3.7 新版功能: `filenames' 形参接受一个 *note bytes: 33a. 对象
          。

      -- 方法: read_file (f, source=None)

          从 `f' 读取并解析配置数据，它必须是一个产生 Unicode 字符串的可
          迭代对象（例如以文本模式打开的文件）。

          可选参数 `source' 指定要读取的文件名称。 如果未给出并且 `f' 具
          有 ‘name’ 属性，则该属性会被用作 `source'；默认值为 ‘'<???>'’。

          3.2 新版功能: 替代 *note readfp(): 1e6b.。

      -- 方法: read_string (string, source='<string>')

          从字符串中解析配置数据。

          可选参数 `source' 指定一个所传入字符串的上下文专属名称。 如果
          未给出，则会使用 ‘'<string>'’。 这通常应为一个文件系统路径或
          URL。

          3.2 新版功能.

      -- 方法: read_dict (dictionary, source='<dict>')

          从任意一个提供了类似于字典的 ‘items()’ 方法的对象加载配置。 键
          为节名称，值为包含节中所出现的键和值的字典。 如果所用的字典类
          型会保留顺序，则节和其中的键将按顺序加入。 值会被自动转换为字
          符串。

          可选参数 `source' 指定一个所传入字曲的上下文专属名称。 如果未
          给出，则会使用 ‘<dict>’。

          此方法可被用于在解析器之间拷贝状态。

          3.2 新版功能.

      -- 方法: get (section, option, *, raw=False, vars=None[,
               fallback])

          获取指定名称的 `section' 的一个 `option' 的值。 如果提供了
          `vars'，则它必须为一个字典。 `option' 的查找顺序为 `vars*（如
          果有提供）、*section' 以及 `DEFAULTSECT'。 如果未找到该键并且
          提供了 `fallback'，则它会被用作回退值。 可以提供 ‘None’ 作为
          `fallback' 值。

          所有 ‘'%'’ 插值会在返回值中被展开，除非 `raw' 参数为真值。 插
          值键所使用的值会按与选项相同的方式来查找。

          在 3.2 版更改: `raw', `vars' 和 `fallback' 都是仅限关键字参数
          ，以防止用户试图使用第三个参数作业为 `fallback' 回退值（特别是
          在使用映射 协议的时候）。

      -- 方法: getint (section, option, *, raw=False, vars=None[,
               fallback])

          将在指定 `section' 中的 `option' 强制转换为整数的便捷方法。 参
          见 *note get(): c0a. 获取对于 `raw', `vars' 和 `fallback' 的解
          释。

      -- 方法: getfloat (section, option, *, raw=False, vars=None[,
               fallback])

          将在指定 `section' 中的 `option' 强制转换为浮点数的便捷方法。
          参见 *note get(): c0a. 获取对于 `raw', `vars' 和 `fallback' 的
          解释。

      -- 方法: getboolean (section, option, *, raw=False, vars=None[,
               fallback])

          将在指定 `section' 中的 `option' 强制转换为布尔值的便捷方法。
          请注意选项所接受的值为 ‘'1'’, ‘'yes'’, ‘'true'’ 和 ‘'on'’，它
          们会使得此方法返回 ‘True’，以及 ‘'0'’, ‘'no'’, ‘'false'’ 和
          ‘'off'’，它们会使得此方法返回 ‘False’。 这些字符串值会以对大小
          写不敏感的方式被检测。 任何其他值都将导致引发 *note
          ValueError: 1fc.。 参见 *note get(): c0a. 获取对于 `raw',
          `vars' 和 `fallback' 的解释。

      -- 方法: items (raw=False, vars=None)

      -- 方法: items (section, raw=False, vars=None)

          当未给出 `section' 时，将返回由 `section_name',
          `section_proxy' 对组成的列表，包括 DEFAULTSECT。

          在其他情况下，将返回给定的 `section' 中的 option 的 `name',
          `value' 对组成的列表。 可选参数具有与 *note get(): c0a. 方法的
          参数相同的含义。

          在 3.8 版更改: `vars' 中的条目将不在结果中出现。 之前的行为混
          淆了实际的解析器选项和为插值提供的变量。

      -- 方法: set (section, option, value)

          如果给定的节存在，则将所给出的选项设为指定的值；在其他情况下将
          引发 *note NoSectionError: 1e6e.。 `option' 和 `value' 必须为
          字符串；如果不是则将引发 *note TypeError: 193.。

      -- 方法: write (fileobject, space_around_delimiters=True)

          将配置的表示形式写入指定的 *note file object: b4a.，该对象必须
          以文本模式打开（接受字符串）。 此表示形式可由将来的 *note
          read(): 10b4. 调用进行解析。 如果 `space_around_delimiters' 为
          真值，键和值之前的分隔符两边将加上空格。

      -- 方法: remove_option (section, option)

          将指定的 `option' 从指定的 `section' 中移除。 如果指定的节不存
          在则会引发 *note NoSectionError: 1e6e.。 如果要移除的选项存在
          则返回 *note True: 4a1.；在其他情况下将返回 *note False: 390.。

      -- 方法: remove_section (section)

          从配置中移除指定的 `section'。 如果指定的节确实存在则返回
          ‘True’。 在其他情况下将返回 ‘False’。

      -- 方法: optionxform (option)

          将选项名 `option' 转换为输入文件中的形式或客户端代码所传入的应
          当在内部结构中使用的形式。 默认实现将返回 `option' 的小写形式
          版本；子类可以重载此行为，或者客户端代码也可以在实例上设置一个
          具有此名称的属性来影响此行为。

          你不需要子类化解析器来使用此方法，你也可以在一个实例上设置它，
          或使用一个接受字符串参数并返回字符串的函数。 例如将它设为
          ‘str’ 将使得选项名称变得大小写敏感:

               cfgparser = ConfigParser()
               cfgparser.optionxform = str

          请注意当读取配置文件时，选项名称两边的空格将在调用 *note
          optionxform(): 1e63. 之前被去除。

      -- 方法: readfp (fp, filename=None)

          3.2 版后已移除: 使用 *note read_file(): 1e6a. 来代替。

          在 3.2 版更改: *note readfp(): 1e6b. 现在将在 `fp' 上执行迭代
          而不是调用 ‘fp.readline()’。

          对于调用 *note readfp(): 1e6b. 时传入不支持迭代的参数的现有代
          码，可以在文件类对象外使用以下生成器作为包装器:

               def readline_generator(fp):
                   line = fp.readline()
                   while line:
                       yield line
                       line = fp.readline()

          不再使用 ‘parser.readfp(fp)’ 而是改用
          ‘parser.read_file(readline_generator(fp))’。

 -- 数据: configparser.MAX_INTERPOLATION_DEPTH

     当 `raw' 形参为假值时 ‘get()’ 所采用的递归插值的最大深度。 这只在使
     用默认的 `interpolation' 时会起作用。


File: python.info,  Node: RawConfigParser 对象,  Next: 异常<5>,  Prev: ConfigParser 对象,  Up: configparser --- 配置文件解析器

5.14.2.10 RawConfigParser 对象
..............................

 -- 类: configparser.RawConfigParser (defaults=None, dict_type=dict,
          allow_no_value=False, *, delimiters=('=', ':'),
          comment_prefixes=('#', ';'), inline_comment_prefixes=None,
          strict=True, empty_lines_in_values=True,
          default_section=configparser.DEFAULTSECT[, interpolation])

     旧式 *note ConfigParser: 4b2.。 它默认禁用插值并且允许通过不安全的
     ‘add_section’ 和 ‘set’ 方法以及旧式 ‘defaults=’ 关键字参数处理来设
     置非字符串的节名、选项名和值。

     在 3.8 版更改: 默认的 `dict_type' 为 *note dict: 1b9.，因为它现在会
     保留插入顺序。

          注解: 考虑改用 *note ConfigParser: 4b2.，它会检查内部保存的值
          的类型。 如果你不想要插值，你可以使用
          ‘ConfigParser(interpolation=None)’。

      -- 方法: add_section (section)

          向实例添加一个名为 `section' 的节。 如果给定名称的节已存在，将
          会引发 *note DuplicateSectionError: c0d.。 如果传入了 `default
          section' 名称，则会引发 *note ValueError: 1fc.。

          不检查 `section' 以允许用户创建以非字符串命名的节。 此行为已不
          受支持并可能导致内部错误。

      -- 方法: set (section, option, value)

          如果给定的节存在，则将给定的选项设为指定的值；在其他情况下将引
          发 *note NoSectionError: 1e6e.。 虽然可能使用 *note
          RawConfigParser: 87a. (或使用 *note ConfigParser: 4b2. 并将
          `raw' 形参设为真值) 以便实现非字符串值的 `internal' 存储，但是
          完整功能（包括插值和输出到文件）只能使用字符串值来实现。

          此方法允许用户在内部将非字符串值赋给键。 此行为已不受支持并会
          在尝试写入到文件或在非原始模式下获取数据时导致错误。 `请使用映
          射协议 API'，它不允许出现这样的赋值。


File: python.info,  Node: 异常<5>,  Prev: RawConfigParser 对象,  Up: configparser --- 配置文件解析器

5.14.2.11 异常
..............

 -- 例外: configparser.Error

     所有其他 *note configparser: 23. 异常的基类。

 -- 例外: configparser.NoSectionError

     当找不到指定节时引发的异常。

 -- 例外: configparser.DuplicateSectionError

     当调用 ‘add_section()’ 时传入已存在的节名称，或者在严格解析器中当单
     个输入文件、字符串或字典内出现重复的节时引发的异常。

     3.2 新版功能: 将可选的 ‘source’ 和 ‘lineno’ 属性和参数添加到 *note
     __init__(): d66.。

 -- 例外: configparser.DuplicateOptionError

     当单个选项在从单个文件、字符串或字典读取时出现两次时引发的异常。 这
     会捕获拼写错误和大小写敏感相关的错误，例如一个字典可能包含两个键分
     别代表同一个大小写不敏感的配置键。

 -- 例外: configparser.NoOptionError

     当指定的选项未在指定的节中被找到时引发的异常。

 -- 例外: configparser.InterpolationError

     当执行字符串插值发生问题时所引发的异常的基类。

 -- 例外: configparser.InterpolationDepthError

     当字符串插值由于迭代次数超出 *note MAX_INTERPOLATION_DEPTH: 1e71. 而
     无法完成所引发的异常。 为 *note InterpolationError: 1e79. 的子类。

 -- 例外: configparser.InterpolationMissingOptionError

     当从某个值引用的选项并不存在时引发的异常。 为 *note
     InterpolationError: 1e79. 的子类。

 -- 例外: configparser.InterpolationSyntaxError

     当将要执行替换的源文本不符合要求的语法时引发的异常。 为 *note
     InterpolationError: 1e79. 的子类。

 -- 例外: configparser.MissingSectionHeaderError

     当尝试解析一个不带节标头的文件时引发的异常。

 -- 例外: configparser.ParsingError

     当尝试解析一个文件而发生错误时引发的异常。

     在 3.2 版更改: ‘filename’ 属性和 *note __init__(): d66. 参数被重命
     名为 ‘source’ 以保持一致性。

备注
....


File: python.info,  Node: netrc --- netrc 文件处理,  Next: xdrlib --- 编码与解码 XDR 数据,  Prev: configparser --- 配置文件解析器,  Up: 文件格式

5.14.3 ‘netrc’ — netrc 文件处理
-------------------------------

`源代码:' Lib/netrc.py(1)

__________________________________________________________________

*note netrc: 10b0. 类解析并封装了 Unix 的 ‘ftp’ 程序和其他 FTP 客户端所
使用的 netrc 文件格式。

 -- 类: netrc.netrc ([file])

     *note netrc: 10b0. 的实例或其子类的实例会被用来封装来自 netrc 文件
     的数据。 如果有初始化参数，它将指明要解析的文件。 如果未给出参数，
     则位于用户家目录的 ‘.netrc’ 文件 – 即 *note os.path.expanduser():
     1ff. 所确定的文件 – 将会被读取。 在其他情况下，则将引发 *note
     FileNotFoundError: 7c9. 异常。 解析错误将引发 *note
     NetrcParseError: 1e81. 并附带诊断信息，包括文件名、行号以及终止令牌
     。 如果在 POSIX 系统上未指明参数，则当 ‘.netrc’ 文件中有密码时，如
     果文件归属或权限不安全（归属的用户不是运行进程的用户，或者可供任何
     其他用户读取或写入）将引发 *note NetrcParseError: 1e81.。 这实现了
     与 ftp 和其他使用 ‘.netrc’ 的程序同等的安全行为。

     在 3.4 版更改: 添加了 POSIX 权限检查。

     在 3.7 版更改: 当未将 `file' 作为参数传入时会使用 *note
     os.path.expanduser(): 1ff. 来查找 ‘.netrc’ 文件的位置。

 -- 例外: netrc.NetrcParseError

     当在源文本中遇到语法错误时由 *note netrc: 10b0. 类引发的异常。 此异
     常的实例提供了三个有用属性: ‘msg’ 为错误的文本说明，‘filename’ 为源
     文件的名称，而 ‘lineno’ 给出了错误所在的行号。

* Menu:

* netrc 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/netrc.py


File: python.info,  Node: netrc 对象,  Up: netrc --- netrc 文件处理

5.14.3.1 netrc 对象
...................

*note netrc: 10b0. 实例具有下列方法:

 -- 方法: netrc.authenticators (host)

     针对 `host' 的身份验证者返回一个 3 元组 ‘(login, account,
     password)’。 如果 netrc 文件不包含针对给定主机的条目，则返回关联到
     ’default’ 条目的元组。 如果匹配的主机或默认条目均不可用，则返回
     ‘None’。

 -- 方法: netrc.__repr__ ()

     将类数据以 netrc 文件的格式转储为一个字符串。 （这会丢弃注释并可能
     重排条目顺序。）

*note netrc: 10b0. 的实例具有一些公共实例变量:

 -- 属性: netrc.hosts

     将主机名映射到 ‘(login, account, password)’ 元组的字典。 如果存在
     ’default’ 条目，则会表示为使用该名称的伪主机。

 -- 属性: netrc.macros

     将宏名称映射到字符串列表的字典。

     注解: 密码会被限制为 ASCII 字符集的一个子集。 所有 ASCII 标点符号均
     可用作密码，但是要注意空白符和非打印字符不允许用作密码。 这是
     .netrc 文件解析方式带来的限制，在未来可能会被解除。


File: python.info,  Node: xdrlib --- 编码与解码 XDR 数据,  Next: plistlib --- 生成与解析 Mac OS X plist 文件,  Prev: netrc --- netrc 文件处理,  Up: 文件格式

5.14.4 ‘xdrlib’ — 编码与解码 XDR 数据
-------------------------------------

`源代码:' Lib/xdrlib.py(1)

__________________________________________________________________

*note xdrlib: 133. 模块为外部数据表示标准提供支持，该标准的描述见 RFC
1014(2)，由 Sun Microsystems, Inc. 在 1987 年 6 月撰写。 它支持该 RFC 中
描述的大部分数据类型。

*note xdrlib: 133. 模块定义了两个类，一个用于将变量打包为 XDR 表示形式，
另一个用于从 XDR 表示形式解包。 此外还有两个异常类。

 -- 类: xdrlib.Packer

     *note Packer: 1e8a. 是用于将数据打包为 XDR 表示形式的类。 *note
     Packer: 1e8a. 类的实例化不附带参数。

 -- 类: xdrlib.Unpacker (data)

     ‘Unpacker’ 是用于相应地从字符串缓冲区解包 XDR 数据值的类。 输入缓冲
     区将作为 `data' 给出。

参见
....

RFC 1014(3) - XDR: 外部数据表示标准

     这个 RFC 定义了最初编写此模块时 XDR 所用的数据编码格式。 显然它已被
     RFC 1832(4) 所淘汰。

RFC 1832(5) - XDR: 外部数据表示标准

     更新的 RFC，它提供了经修订的 XDR 定义。

* Menu:

* Packer 对象::
* Unpacker 对象::
* 异常: 异常<6>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/xdrlib.py

   (2) https://tools.ietf.org/html/rfc1014.html

   (3) https://tools.ietf.org/html/rfc1014.html

   (4) https://tools.ietf.org/html/rfc1832.html

   (5) https://tools.ietf.org/html/rfc1832.html


File: python.info,  Node: Packer 对象,  Next: Unpacker 对象,  Up: xdrlib --- 编码与解码 XDR 数据

5.14.4.1 Packer 对象
....................

*note Packer: 1e8a. 实例具有下列方法:

 -- 方法: Packer.get_buffer ()

     将当前打包缓冲区以字符串的形式返回。

 -- 方法: Packer.reset ()

     将打包缓冲区重置为空字符串。

总体来说，你可以通过调用适当的 ‘pack_type()’ 方法来打包任何最常见的 XDR
数据类型。 每个方法都是接受单个参数，即要打包的值。 受支持的简单数据类型
打包方法如下: ‘pack_uint()’, ‘pack_int()’, ‘pack_enum()’, ‘pack_bool()’,
‘pack_uhyper()’ 以及 ‘pack_hyper()’。

 -- 方法: Packer.pack_float (value)

     打包单精度浮点数 `value'。

 -- 方法: Packer.pack_double (value)

     打包双精度浮点数 `value'。

以下方法支持打包字符串、字节串以及不透明数据。

 -- 方法: Packer.pack_fstring (n, s)

     打包固定长度字符串 `s'。 `n' 为字符串的长度，但它 `不会' 被打包进数
     据缓冲区。 如有必要字符串会以空字节串填充以保证 4 字节对齐。

 -- 方法: Packer.pack_fopaque (n, data)

     打包固定长度不透明数据流，类似于 *note pack_fstring(): 1e92.。

 -- 方法: Packer.pack_string (s)

     打包可变长度字符串 `s'。 先将字符串的长度打包为无符号整数，再用
     *note pack_fstring(): 1e92. 来打包字符串数据。

 -- 方法: Packer.pack_opaque (data)

     打包可变长度不透明数据流，类似于 *note pack_string(): 1e94.。

 -- 方法: Packer.pack_bytes (bytes)

     打包可变长度字节流，类似于 *note pack_string(): 1e94.。

下列方法支持打包数组和列表:

 -- 方法: Packer.pack_list (list, pack_item)

     打包由同质条目构成的 `list'。 此方法适用于不确定长度的列表；即其长
     度无法在遍历整个列表之前获知。 对于列表中的每个条目，先打包一个无符
     号整数 ‘1’，再添加列表中数据的值。 `pack_item' 是在打包单个条目时要
     调用的函数。 在列表的末尾，会再打包一个无符号整数 ‘0’。

     例如，要打包一个整数列表，代码看起来会是这样:

          import xdrlib
          p = xdrlib.Packer()
          p.pack_list([1, 2, 3], p.pack_int)

 -- 方法: Packer.pack_farray (n, array, pack_item)

     打包由同质条目构成的固定长度列表 (`array')。 `n' 为列表长度；它 `不
     会' 被打包到缓冲区，但是如果 ‘len(array)’ 不等于 `n' 则会引发 *note
     ValueError: 1fc.。 如上所述，`pack_item' 是在打包每个元素时要使用的
     函数。

 -- 方法: Packer.pack_array (list, pack_item)

     打包由同质条目构成的可变长度 `list'。 先将列表的长度打包为无符号整
     数，再像上面的 *note pack_farray(): 1e98. 一样打包每个元素。


File: python.info,  Node: Unpacker 对象,  Next: 异常<6>,  Prev: Packer 对象,  Up: xdrlib --- 编码与解码 XDR 数据

5.14.4.2 Unpacker 对象
......................

*note Unpacker: 1e8b. 类提供以下方法:

 -- 方法: Unpacker.reset (data)

     使用给定的 `data' 重置字符串缓冲区。

 -- 方法: Unpacker.get_position ()

     返回数据缓冲区中的当前解包位置。

 -- 方法: Unpacker.set_position (position)

     将数据缓冲区的解包位置设为 `position'。 你应当小心使用 *note
     get_position(): 1e9d. 和 *note set_position(): 1e9e.。

 -- 方法: Unpacker.get_buffer ()

     将当前解包数据缓冲区以字符串的形式返回。

 -- 方法: Unpacker.done ()

     表明解包完成。 如果数据没有全部完成解包则会引发 *note Error: 1ea1.
     异常。

此外，每种可通过 *note Packer: 1e8a. 打包的数据类型都可通过 *note
Unpacker: 1e8b. 来解包。 解包方法的形式为 ‘unpack_type()’，并且不接受任
何参数。 该方法将返回解包后的对象。

 -- 方法: Unpacker.unpack_float ()

     解包单精度浮点数。

 -- 方法: Unpacker.unpack_double ()

     解包双精度浮点数，类似于 *note unpack_float(): 1ea2.。

此外，以下方法可用来解包字符串、字节串以及不透明数据:

 -- 方法: Unpacker.unpack_fstring (n)

     解包并返回固定长度字符串。 `n' 为期望的字符数量。 会预设以空字节串
     填充以保证 4 字节对齐。

 -- 方法: Unpacker.unpack_fopaque (n)

     解包并返回固定长度数据流，类似于 *note unpack_fstring(): 1ea4.。

 -- 方法: Unpacker.unpack_string ()

     解包并返回可变长度字符串。 先将字符串的长度解包为无符号整数，再用
     *note unpack_fstring(): 1ea4. 来解包字符串数据。

 -- 方法: Unpacker.unpack_opaque ()

     解包并返回可变长度不透明数据流，类似于 *note unpack_string():
     1ea6.。

 -- 方法: Unpacker.unpack_bytes ()

     解包并返回可变长度字节流，类似于 *note unpack_string(): 1ea6.。

下列方法支持解包数组和列表:

 -- 方法: Unpacker.unpack_list (unpack_item)

     解包并返回同质条目的列表。 该列表每次解包一个元素，先解包一个无符号
     整数旗标。 如果旗标为 ‘1’，则解包条目并将其添加到列表。 旗标为 ‘0’
     表明列表结束。 `unpack_item' 为在解包条目时调用的函数。

 -- 方法: Unpacker.unpack_farray (n, unpack_item)

     解包并（以列表形式）返回由同质条目构成的固定长度数组。 `n' 为期望的
     缓冲区内列表元素数量。 如上所述，`unpack_item' 是解包每个元素时要使
     用的函数。

 -- 方法: Unpacker.unpack_array (unpack_item)

     解包并返回由同质条目构成的可变长度 `list'。 先将列表的长度解包为无
     符号整数，再像上面的 *note unpack_farray(): 1eaa. 一样解包每个元素
     。


File: python.info,  Node: 异常<6>,  Prev: Unpacker 对象,  Up: xdrlib --- 编码与解码 XDR 数据

5.14.4.3 异常
.............

此模块中的异常会表示为类实例代码:

 -- 例外: xdrlib.Error

     基本异常类。 *note Error: 1ea1. 具有一个公共属性 ‘msg’，其中包含对
     错误的描述。

 -- 例外: xdrlib.ConversionError

     从 *note Error: 1ea1. 所派生的类。 不包含额外的实例变量。

以下是一个应该如何捕获这些异常的示例:

     import xdrlib
     p = xdrlib.Packer()
     try:
         p.pack_double(8.01)
     except xdrlib.ConversionError as instance:
         print('packing the double failed:', instance.msg)


File: python.info,  Node: plistlib --- 生成与解析 Mac OS X plist 文件,  Prev: xdrlib --- 编码与解码 XDR 数据,  Up: 文件格式

5.14.5 ‘plistlib’ — 生成与解析 Mac OS X ‘.plist’ 文件
-----------------------------------------------------

`源代码:' Lib/plistlib.py(1)

__________________________________________________________________

此模块提供了读写主要用于 Mac OS X 的 "property list" 文件的接口，并同时
支持二进制和 XML plist 文件。

property list (‘.plist’) 文件格式是一种简单的序列化格式，它支持一些基本
对象类型，例如字典、列表、数字和字符串等。 通常使用一个字典作为最高层级
对象。

要写入和解析 plist 文件，请使用 *note dump(): 895. 和 *note load(): 894.
函数。

要以字节串对象形式操作 plist 数据，请使用 *note dumps(): 897. 和 *note
loads(): 896.。

值可以为字符串、整数、浮点数、布尔值、元组、列表、字典（但只允许用字符串
作为键）、*note Data: 94f.、*note bytes: 33a.、‘bytesarray’ 或 *note
datetime.datetime: 195. 对象。

在 3.4 版更改: 新版 API，旧版 API 已被弃用。 添加了对二进制 plist 格式的
支持。

在 3.8 版更改: 添加了在二进制 plist 中读写 *note UID: 211. 令牌的支持，
例如用于 NSKeyedArchiver 和 NSKeyedUnarchiver。

参见
....

PList 指南页面(2)

     针对该文件格式的 Apple 文档。

这个模块定义了以下函数：

 -- 函数: plistlib.load (fp, *, fmt=None, use_builtin_types=True,
          dict_type=dict)

     读取 plist 文件。 `fp' 应当可读并且为二进制文件对象。 返回已解包的
     根对象（通常是一个字典）。

     `fmt' 为文件的格式，有效的值如下:

        * *note None: 158.: 自动检测文件格式

        * *note FMT_XML: 898.: XML 文件格式

        * *note FMT_BINARY: 899.: 二进制 plist 格式

     如果 `use_builtin_types' 为真值（默认）则将以 *note bytes: 33a. 实
     例的形式返回二进制数据，否则将以 *note Data: 94f. 实例的形式返回。

     `dict_type' 为字典用来从 plist 文件读取的类型。

     *note FMT_XML: 898. 格式的 XML 数据 会使用来自 *note
     xml.parsers.expat: 139. 的 Expat 解析器 – 请参阅其文档了解错误格式
     XML 可能引发的异常。 未知元素将被 plist 解析器直接略过。

     当文件无法被解析时二进制格式的解析器将引发 ‘InvalidFileException’。

     3.4 新版功能.

 -- 函数: plistlib.loads (data, *, fmt=None, use_builtin_types=True,
          dict_type=dict)

     从一个 bytes 对象加载 plist。 参阅 *note load(): 894. 获取相应关键
     字参数的说明。

     3.4 新版功能.

 -- 函数: plistlib.dump (value, fp, *, fmt=FMT_XML, sort_keys=True,
          skipkeys=False)

     将 `value' 写入 plist 文件。 `Fp' 应当可写并且为二进制文件对象。

     `fmt' 参数指定 plist 文件的格式，可以是以下值之一:

        * *note FMT_XML: 898.: XML 格式的 plist 文件

        * *note FMT_BINARY: 899.: 二进制格式的 plist 文件

     当 `sort_keys' 为真值（默认）时字典的键将经过排序再写入 plist，否则
     将按字典的迭代顺序写入。

     当 `skipkeys' 为假值（默认）时该函数将在字典的键不为字符串时引发
     *note TypeError: 193.，否则将跳过这样的键。

     如果对象是不受支持的类型或者是包含不受支持类型的对象的容器则将引发
     *note TypeError: 193.。

     对于无法在（二进制）plist 文件中表示的整数值，将会引发 *note
     OverflowError: 968.。

     3.4 新版功能.

 -- 函数: plistlib.dumps (value, *, fmt=FMT_XML, sort_keys=True,
          skipkeys=False)

     将 `value' 以 plist 格式字节串对象的形式返回。 参阅 *note dump():
     895. 的文档获取此函数的关键字参数的说明。

     3.4 新版功能.

以下函数已被弃用:

 -- 函数: plistlib.readPlist (pathOrFile)

     读取 plist 文件。 `pathOrFile' 可以是文件名或（可读并且为二进制的）
     文件对象。 返回已解包的根对象（通常是一个字典）。

     此函数会调用 *note load(): 894. 来完成实际操作，请参阅 *note
     该函数: 894. 的文档获取相应关键字参数的说明。

     3.4 版后已移除: 使用 *note load(): 894. 来代替。

     在 3.7 版更改: 结果中的字典值现在是普通字典。 你不能再使用属性引用
     形式来访问这些字典中的项。

 -- 函数: plistlib.writePlist (rootObject, pathOrFile)

     将 `rootObject' 写入 XML plist 文件。 `pathOrFile' 可以是文件名或（
     可写并且为二进制的）文件对象。

     3.4 版后已移除: 使用 *note dump(): 895. 来代替。

 -- 函数: plistlib.readPlistFromBytes (data)

     从字节串对象读取 plist 数据。 返回根对象。

     参阅 *note load(): 894. 获取相应关键字参数的说明。

     3.4 版后已移除: 使用 *note loads(): 896. 来代替。

     在 3.7 版更改: 结果中的字典值现在是普通字典。 你不能再使用属性引用
     形式来访问这些字典中的项。

 -- 函数: plistlib.writePlistToBytes (rootObject)

     将 `rootObject' 作为 XML plist 格式的字节串对象返回。

     3.4 版后已移除: 使用 *note dumps(): 897. 来代替。

可以使用以下的类:

 -- 类: plistlib.Data (data)

     返回一个包含字节串对象 `data' 的 "data" 包装器对象。 该类将在对
     plist 进行双向转换的函数中被用来代表 plist 中可用的 ‘<data>’ 类型。

     它具有一个属性 ‘data’，可被用来提取其中所保存的 Python 字节串对象。

     3.4 版后已移除: 使用 *note bytes: 33a. 对象来代替。

 -- 类: plistlib.UID (data)

     包装一个 *note int: 185.。 该类将在读取或写入 NSKeyedArchiver 编码
     的数据时被使用，其中包含 UID（参见 PList 指南）。

     它具有一个属性 ‘data’，可被用来提取 UID 的 int 值。 ‘data’ 的取值范
     围必须为 ‘0 <= data < 2**64’。

     3.8 新版功能.

可以使用以下的常量:

 -- 数据: plistlib.FMT_XML

     用于 plist 文件的 XML 格式。

     3.4 新版功能.

 -- 数据: plistlib.FMT_BINARY

     用于 plist 文件的二进制格式。

     3.4 新版功能.

* Menu:

* 例子: 例子<8>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/plistlib.py

   (2) 
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/PropertyLists/


File: python.info,  Node: 例子<8>,  Up: plistlib --- 生成与解析 Mac OS X plist 文件

5.14.5.1 例子
.............

生成一个 plist:

     pl = dict(
         aString = "Doodah",
         aList = ["A", "B", 12, 32.1, [1, 2, 3]],
         aFloat = 0.1,
         anInt = 728,
         aDict = dict(
             anotherString = "<hello & hi there!>",
             aThirdString = "M\xe4ssig, Ma\xdf",
             aTrueValue = True,
             aFalseValue = False,
         ),
         someData = b"<binary gunk>",
         someMoreData = b"<lots of binary gunk>" * 10,
         aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
     )
     with open(fileName, 'wb') as fp:
         dump(pl, fp)

解析一个 plist:

     with open(fileName, 'rb') as fp:
         pl = load(fp)
     print(pl["aKey"])


File: python.info,  Node: 加密服务,  Next: 通用操作系统服务,  Prev: 文件格式,  Up: Python 标准库

5.15 加密服务
=============

本章中描述的模块实现了加密性质的各种算法。 它们可以在安装时自行选择。 在
Unix 系统上，*note crypt: 29. 模块也可以使用。 以下是为内容概要：

* Menu:

* hashlib: hashlib --- 安全哈希与消息摘要. 安全哈希与消息摘要
* hmac: hmac --- 基于密钥的消息验证. 基于密钥的消息验证
* secrets: secrets --- 生成安全随机数字用于管理密码. 生成安全随机数字用于管理密码


File: python.info,  Node: hashlib --- 安全哈希与消息摘要,  Next: hmac --- 基于密钥的消息验证,  Up: 加密服务

5.15.1 ‘hashlib’ — 安全哈希与消息摘要
-------------------------------------

`源码：' Lib/hashlib.py(1)

__________________________________________________________________

这个模块针对不同的安全哈希和消息摘要算法实现了一个通用的接口。包括 FIPS
的 SHA1, SHA224, SHA256, SHA384, and SHA512 (定义于 FIPS 180-2) 算法，以
及 RSA 的 MD5 算法( 定义于 Internet RFC 1321(2))。术语“安全哈希”和“消息
摘要”是可互换的，较旧的算法被称为消息摘要，现代术语是安全哈希。

     注解: 如果你想找到 adler32 或 crc32 哈希函数，它们在 *note zlib:
     145. 模块中。

     警告: 有些算法已知存在哈希碰撞弱点，请参考最后的“另请参阅”段。

* Menu:

* 哈希算法::
* SHAKE 可变长度摘要::
* 密钥派生::
* BLAKE2::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/hashlib.py

   (2) https://tools.ietf.org/html/rfc1321.html


File: python.info,  Node: 哈希算法,  Next: SHAKE 可变长度摘要,  Up: hashlib --- 安全哈希与消息摘要

5.15.1.1 哈希算法
.................

每种类型的 `hash' 都有一个构造器方法。 它们都返回一个具有相同的简单接口
的 hash 对象。 例如，使用 use ‘sha256()’ 创建一个 SHA-256 hash 对象。 你
可以使用 ‘update()’ 方法向这个对象输入 *note 字节类对象: 5f1. (通常是
*note bytes: 33a.)。 在任何时候你都可以使用 ‘digest()’ 或 ‘hexdigest()’
方法获得到目前为止输入这个对象的拼接数据的 `digest'。

     注解: 为了更好的多线程性能，在对象创建或者更新时，若数据大于2047字
     节则 Python 的 *note GIL: bf2. 会被释放。

     注解: 向 ‘update()’ 输入字符串对象是不被支持的，因为哈希基于字节而
     非字符。

此模块中总是可用的哈希算法构造器有 ‘sha1()’, ‘sha224()’, ‘sha256()’,
‘sha384()’, ‘sha512()’, *note blake2b(): 555. 和 *note blake2s(): 556.。
‘md5()’ 通常也是可用的，但如果你在使用少见的 "FIPS 兼容" 的 Python 编译
版本则可能会找不到它。 此外还可能有一些附加的算法，具体取决于你的平台上
的 Python 所使用的 OpenSSL 库。 在大部分平台上可用的还有 ‘sha3_224()’,
‘sha3_256()’, ‘sha3_384()’, ‘sha3_512()’, ‘shake_128()’, ‘shake_256()’ 等
等。

3.6 新版功能: SHA3 (Keccak) 和 SHAKE 构造器 ‘sha3_224()’, ‘sha3_256()’,
‘sha3_384()’, ‘sha3_512()’, ‘shake_128()’, ‘shake_256()’.

3.6 新版功能: 添加了 *note blake2b(): 555. 和 *note blake2s(): 556. 。

例如，如果想获取字节串 ‘b'Nobody inspects the spammish repetition'’ 的摘
要:

     >>> import hashlib
     >>> m = hashlib.sha256()
     >>> m.update(b"Nobody inspects")
     >>> m.update(b" the spammish repetition")
     >>> m.digest()
     b'\x03\x1e\xdd}Ae\x15\x93\xc5\xfe\\\x00o\xa5u+7\xfd\xdf\xf7\xbcN\x84:\xa6\xaf\x0c\x95\x0fK\x94\x06'
     >>> m.digest_size
     32
     >>> m.block_size
     64

更简要的写法：

     >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()
     'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'

 -- 函数: hashlib.new (name[, data])

     一个接受所希望的算法对应的字符串 `name' 作为第一个形参的通用构造器
     。 它还允许访问上面列出的哈希算法以及你的 OpenSSL 库可能提供的任何
     其他算法。 同名的构造器要比 *note new(): 1eb9. 更快所以应当优先使用
     。

使用 *note new(): 1eb9. 并附带由 OpenSSL 所提供了算法:

     >>> h = hashlib.new('sha512_256')
     >>> h.update(b"Nobody inspects the spammish repetition")
     >>> h.hexdigest()
     '19197dc4d03829df858011c6c87600f994a858103bbc19005f20987aa19a97e2'

Hashlib 提供下列常量属性：

 -- 数据: hashlib.algorithms_guaranteed

     一个集合，其中包含此模块在所有平台上都保证支持的哈希算法的名称。 请
     注意 ’md5’ 也在此清单中，虽然某些上游厂商提供了一个怪异的排除了此算
     法的 "FIPS 兼容" Python 编译版本。

     3.2 新版功能.

 -- 数据: hashlib.algorithms_available

     一个集合，其中包含在所运行的 Python 解释器上可用的哈希算法的名称。
     将这些名称传给 *note new(): 1eb9. 时将可被识别。 *note
     algorithms_guaranteed: d04. 将总是它的一个子集。 同样的算法在此集合
     中可能以不同的名称出现多次（这是 OpenSSL 的原因）。

     3.2 新版功能.

下列值会以构造器所返回的哈希对象的常量属性的形式被提供:

 -- 数据: hash.digest_size

     以字节表示的结果哈希对象的大小。

 -- 数据: hash.block_size

     以字节表示的哈希算法的内部块大小。

hash 对象具有以下属性：

 -- 属性: hash.name

     此哈希对象的规范名称，总是为小写形式并且总是可以作为 *note new():
     1eb9. 的形参用来创建另一个此类型的哈希对象。

     在 3.4 版更改: 该属性名称自被引入起即存在于 CPython 中，但在 Python
     3.4 之前并未正式指明，因此可能不存在于某些平台上。

哈希对象具有下列方法:

 -- 方法: hash.update (data)

     用 *note bytes-like object: 5f1. 来更新哈希对象。 重复调用相当于单
     次调用并传入所有参数的拼接结果: ‘m.update(a); m.update(b)’ 等价于
     ‘m.update(a+b)’。

     在 3.1 版更改: 当使用 OpenSSL 提供的哈希算法在大于 2047 字节的数据
     上执行哈希更新时 Python GIL 会被释放以允许其他线程运行。

 -- 方法: hash.digest ()

     返回当前已传给 *note update(): 1ebc. 方法的数据摘要。 这是一个大小
     为 *note digest_size: 1eba. 的字节串对象，字节串中可包含 0 至 255 的
     完整取值范围。

 -- 方法: hash.hexdigest ()

     类似于 *note digest(): 1ebd. 但摘要会以两倍长度字符串对象的形式返回
     ，其中仅包含十六进制数码。 这可以被用于在电子邮件或其他非二进制环境
     中安全地交换数据值。

 -- 方法: hash.copy ()

     返回哈希对象的副本（“克隆”）。 这可被用来高效地计算共享相同初始子串
     的数据的摘要。


File: python.info,  Node: SHAKE 可变长度摘要,  Next: 密钥派生,  Prev: 哈希算法,  Up: hashlib --- 安全哈希与消息摘要

5.15.1.2 SHAKE 可变长度摘要
...........................

‘shake_128()’ 和 ‘shake_256()’ 算法提供安全的 length_in_bits//2 至 128 或
256 位可变长度摘要。 为此，它们的摘要需指定一个长度。 SHAKE 算法不限制最
大长度。

 -- 方法: shake.digest (length)

     返回当前已传给 ‘update()’ 方法的数据摘要。 这是一个大小为 `length'
     的字节串对象，字节串中可包含 0 to 255 的完整取值范围。

 -- 方法: shake.hexdigest (length)

     类似于 *note digest(): 1035. 但摘要会以两倍长度字符串对象的形式返回
     ，其中仅包含十六进制数码。 这可以被用于在电子邮件或其他非二进制环境
     中安全地交换数据值。


File: python.info,  Node: 密钥派生,  Next: BLAKE2,  Prev: SHAKE 可变长度摘要,  Up: hashlib --- 安全哈希与消息摘要

5.15.1.3 密钥派生
.................

密钥派生和密钥延展算法被设计用于安全密码哈希。 ‘sha1(password)’ 这样的简
单算法无法防御暴力攻击。 好的密码哈希函数必须可以微调、放慢步调，并且包
含 加盐(1)。

 -- 函数: hashlib.pbkdf2_hmac (hash_name, password, salt, iterations,
          dklen=None)

     此函数提供 PKCS#5 基于密码的密钥派生函数 2。 它使用 HMAC 作为伪随机
     函数。

     字符串 `hash_name' 是要求用于 HMAC 的哈希摘要算法的名称，例如
     ’sha1’ 或 ’sha256’。 `password' 和 `salt' 会以字节串缓冲区的形式被
     解析。 应用和库应当将 `password' 限制在合理长度 (例如 1024)。
     `salt' 应当为适当来源例如 *note os.urandom(): 4d9. 的大约 16 个或更
     多的字节串数据。

     `iterations' 数值应当基于哈希算法和算力来选择。 在 2013 年时，建议
     至少为 100,000 次 SHA-256 迭代。

     `dklen' 为派生密钥的长度。 如果 `dklen' 为 ‘None’ 则会使用哈希算法
     `hash_name' 的摘要大小，例如 SHA-512 为 64。

          >>> import hashlib
          >>> dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000)
          >>> dk.hex()
          '0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5'

     3.4 新版功能.

          注解: 随同 OpenSSL 提供了一个快速的 `pbkdf2_hmac' 实现。
          Python 实现是使用 *note hmac: 8f. 的内联版本。 它的速度大约要
          慢上三倍并且不会释放 GIL。

 -- 函数: hashlib.scrypt (password, *, salt, n, r, p, maxmem=0,
          dklen=64)

     此函数提供基于密码加密的密钥派生函数，其定义参见 RFC 7914(2)。

     `password' 和 `salt' 必须为 *note 字节类对象: 5f1.。 应用和库应当将
     `password' 限制在合理长度 (例如 1024)。 `salt' 应当为适当来源例如
     *note os.urandom(): 4d9. 的大约 16 个或更多的字节串数据。

     `n' 为 CPU/内存开销因子，`r' 为块大小，`p' 为并行化因子，`maxmem' 为
     内存限制 (OpenSSL 1.1.0 默认为 32 MiB)。 `dklen' 为派生密钥的长度。

     *note 可用性: 136f.: OpenSSL 1.1+。

     3.6 新版功能.

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Salt_%28cryptography%29

   (2) https://tools.ietf.org/html/rfc7914.html


File: python.info,  Node: BLAKE2,  Prev: 密钥派生,  Up: hashlib --- 安全哈希与消息摘要

5.15.1.4 BLAKE2
...............

BLAKE2(1) 是在 RFC 7693(2) 中定义的加密哈希函数，它有两种形式:

   * `BLAKE2b'，针对 64 位平台进行优化，并会生成长度介于 1 和 64 字节之
     间任意大小的摘要。

   * `BLAKE2s'，针对 8 至 32 位平台进行优化，并会生成长度介于 1 和 32 字
     节之间任意大小的摘要。

BLAKE2 支持 `keyed mode' (HMAC(3) 的更快速更简单的替代), `salted
hashing', `personalization' 和 `tree hashing'.

此模块的哈希对象遵循标准库 *note hashlib: 8d. 对象的 API。

* Menu:

* 创建哈希对象::
* 常量: 常量<5>.
* 例子: 例子<9>.
* 开发人员::

   ---------- Footnotes ----------

   (1) https://blake2.net

   (2) https://tools.ietf.org/html/rfc7693.html

   (3) 
https://en.wikipedia.org/wiki/Hash-based_message_authentication_code


File: python.info,  Node: 创建哈希对象,  Next: 常量<5>,  Up: BLAKE2

5.15.1.5 创建哈希对象
.....................

新哈希对象可通过调用构造器函数来创建:

 -- 函数: hashlib.blake2b (data=b'', *, digest_size=64, key=b'',
          salt=b'', person=b'', fanout=1, depth=1, leaf_size=0,
          node_offset=0, node_depth=0, inner_size=0, last_node=False)

 -- 函数: hashlib.blake2s (data=b'', *, digest_size=32, key=b'',
          salt=b'', person=b'', fanout=1, depth=1, leaf_size=0,
          node_offset=0, node_depth=0, inner_size=0, last_node=False)

这些函数返回用于计算 BLAKE2b 或 BLAKE2s 的相应的哈希对象。 它们接受下列
可选通用形参:

   * `data': 要哈希的初始数据块，它必须为 *note bytes-like object: 5f1.。
     它只能作为位置参数传入。

   * `digest_size': 以字节数表示的输出摘要大小。

   * `key': 用于密钥哈希的密钥（对于 BLAKE2b 最长 64 字节，对于 BLAKE2s
     最长 32 字节）。

   * `salt': 用于随机哈希的盐值（对于 BLAKE2b 最长 16 字节，对于 BLAKE2s
     最长 8 字节）。

   * `person': 个性化字符串（对于 BLAKE2b 最长 16 字节，对于 BLAKE2s 最
     长 8 字节）。

下表显示了常规参数的限制（以字节为单位）：

Hash        目标长度        长度（键）   长度（盐）    长度（个人）
                                                       
-----------------------------------------------------------------------
                                                       
BLAKE2b     64              64           16            16
                                                       
                                                       
BLAKE2s     32              32           8             8
                                                       

     注解: BLAKE2 规格描述为盐值和个性化形参定义了固定的长度，但是为了方
     便起见，此实现接受指定在长度以内的任意大小的字节串。 如果形参长度小
     于指定值，它将以零值进行填充，因此举例来说，‘b'salt'’ 和
     ‘b'salt\x00'’ 为相同的值 (`key' 的情况则并非如此。)

如下面的模块 *note constants: 1ec4. 所描述，这些是可用的大小取值。

构造器函数还接受下列树形哈希形参:

   * `fanout': 扇出值 (0 至 255，如无限制即为 0，连续模式下为 1)。

   * `depth': 树的最大深度 (1 至 255，如无限制则为 255，连续模式下为 1)。

   * `leaf_size': 叶子的最大字节长度 (0 至 2**32-1，如无限制或在连续模式
     下则为 0)。

   * `node_offset': 节点偏移量 (对于 BLAKE2b 为 0 至 2**64-1，对于
     BLAKE2s 为 0 至 2**48-1，对于最左边第一个叶子或在连续模式下则为 0)。

   * `node_depth': 节点深度 (0 至 255，对于叶子或在连续模式下则为 0)。

   * `inner_size': 内部摘要大小 (对于 BLAKE2b 为 0 至 64，对于 BLAKE2s 为
     0 至 32，连续模式下则为 0)。

   * `last_node': 一个布尔值，指明所处理的节点是否为最后一个 (连续模式下
     则为 ‘False’)。

[Explanation of tree mode parameters.]
Figure

请参阅 BLAKE2 规格描述(1) 第 2.10 节获取有关树形哈希的完整说明。

   ---------- Footnotes ----------

   (1) https://blake2.net/blake2_20130129.pdf


File: python.info,  Node: 常量<5>,  Next: 例子<9>,  Prev: 创建哈希对象,  Up: BLAKE2

5.15.1.6 常量
.............

 -- 数据: blake2b.SALT_SIZE

 -- 数据: blake2s.SALT_SIZE

盐值长度（构造器所接受的最大长度）。

 -- 数据: blake2b.PERSON_SIZE

 -- 数据: blake2s.PERSON_SIZE

个性化字符串长度（构造器所接受的最大长度）。

 -- 数据: blake2b.MAX_KEY_SIZE

 -- 数据: blake2s.MAX_KEY_SIZE

最大密钥长度。

 -- 数据: blake2b.MAX_DIGEST_SIZE

 -- 数据: blake2s.MAX_DIGEST_SIZE

哈希函数可输出的最大摘要长度。


File: python.info,  Node: 例子<9>,  Next: 开发人员,  Prev: 常量<5>,  Up: BLAKE2

5.15.1.7 例子
.............

* Menu:

* 简单哈希::
* 使用不同的摘要大小::
* 密钥哈希::
* 随机哈希::
* 个性化::
* 树形模式::


File: python.info,  Node: 简单哈希,  Next: 使用不同的摘要大小,  Up: 例子<9>

5.15.1.8 简单哈希
.................

要计算某个数据的哈希值，你应该首先通过调用适当的构造器函数 (*note
blake2b(): 555. 或 *note blake2s(): 556.) 来构造一个哈希对象，然后通过在
该对象上调用 ‘update()’ 来更新目标数据，最后通过调用 ‘digest()’ (或针对
十六进制编码字符串的 ‘hexdigest()’) 来获取该对象的摘要。

     >>> from hashlib import blake2b
     >>> h = blake2b()
     >>> h.update(b'Hello world')
     >>> h.hexdigest()
     '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'

作为快捷方式，你可以直接以位置参数的形式向构造器传入第一个数据块来直接更
新:

     >>> from hashlib import blake2b
     >>> blake2b(b'Hello world').hexdigest()
     '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'

你可以多次调用 *note hash.update(): 1ebc. 至你所想要的任意次数以迭代地更
新哈希值:

     >>> from hashlib import blake2b
     >>> items = [b'Hello', b' ', b'world']
     >>> h = blake2b()
     >>> for item in items:
     ...     h.update(item)
     >>> h.hexdigest()
     '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'


File: python.info,  Node: 使用不同的摘要大小,  Next: 密钥哈希,  Prev: 简单哈希,  Up: 例子<9>

5.15.1.9 使用不同的摘要大小
...........................

BLAKE2 具有可配置的摘要大小，对于 BLAKE2b 最多 64 字节，对于 BLAKE2s 最
多 32 字节。 例如，要使用 BLAKE2b 来替代 SHA-1 而不改变输出大小，我们可
以让 BLAKE2b 产生 20 个字节的摘要:

     >>> from hashlib import blake2b
     >>> h = blake2b(digest_size=20)
     >>> h.update(b'Replacing SHA1 with the more secure function')
     >>> h.hexdigest()
     'd24f26cf8de66472d58d4e1b1774b4c9158b1f4c'
     >>> h.digest_size
     20
     >>> len(h.digest())
     20

不同摘要大小的哈希对象具有完全不同的输出（较短哈希值 `并非' 较长哈希值的
前缀）；即使输出长度相同，BLAKE2b 和 BLAKE2s 也会产生不同的输出:

     >>> from hashlib import blake2b, blake2s
     >>> blake2b(digest_size=10).hexdigest()
     '6fa1d8fcfd719046d762'
     >>> blake2b(digest_size=11).hexdigest()
     'eb6ec15daf9546254f0809'
     >>> blake2s(digest_size=10).hexdigest()
     '1bf21a98c78a1c376ae9'
     >>> blake2s(digest_size=11).hexdigest()
     '567004bf96e4a25773ebf4'


File: python.info,  Node: 密钥哈希,  Next: 随机哈希,  Prev: 使用不同的摘要大小,  Up: 例子<9>

5.15.1.10 密钥哈希
..................

密钥哈希可被用于身份验证，作为 基于哈希的消息验证代码(1) (HMAC) 的一种更
快速更简单的替代。 BLAKE2 可在前缀 MAC 模式下安全地使用，这是由于它从
BLAKE 所继承的不可区分特性。

这个例子演示了如何使用密钥 ‘b'pseudorandom key'’ 来为 ‘b'message data'’
获取一个（十六进制编码的）128 位验证代码:

     >>> from hashlib import blake2b
     >>> h = blake2b(key=b'pseudorandom key', digest_size=16)
     >>> h.update(b'message data')
     >>> h.hexdigest()
     '3d363ff7401e02026f4a4687d4863ced'

作为实际的例子，一个 Web 应用可为发送给用户的 cookies 进行对称签名，并在
之后对其进行验证以确保它们没有被篡改:

     >>> from hashlib import blake2b
     >>> from hmac import compare_digest
     >>>
     >>> SECRET_KEY = b'pseudorandomly generated server secret key'
     >>> AUTH_SIZE = 16
     >>>
     >>> def sign(cookie):
     ...     h = blake2b(digest_size=AUTH_SIZE, key=SECRET_KEY)
     ...     h.update(cookie)
     ...     return h.hexdigest().encode('utf-8')
     >>>
     >>> def verify(cookie, sig):
     ...     good_sig = sign(cookie)
     ...     return compare_digest(good_sig, sig)
     >>>
     >>> cookie = b'user-alice'
     >>> sig = sign(cookie)
     >>> print("{0},{1}".format(cookie.decode('utf-8'), sig))
     user-alice,b'43b3c982cf697e0c5ab22172d1ca7421'
     >>> verify(cookie, sig)
     True
     >>> verify(b'user-bob', sig)
     False
     >>> verify(cookie, b'0102030405060708090a0b0c0d0e0f00')
     False

即使存在原生的密钥哈希模式，BLAKE2 也同样可在 *note hmac: 8f. 模块的
HMAC 构造过程中使用:

     >>> import hmac, hashlib
     >>> m = hmac.new(b'secret key', digestmod=hashlib.blake2s)
     >>> m.update(b'message')
     >>> m.hexdigest()
     'e3c8102868d28b5ff85fc35dda07329970d1a01e273c37481326fe0c861c8142'

   ---------- Footnotes ----------

   (1) 
https://en.wikipedia.org/wiki/Hash-based_message_authentication_code


File: python.info,  Node: 随机哈希,  Next: 个性化,  Prev: 密钥哈希,  Up: 例子<9>

5.15.1.11 随机哈希
..................

用户可通过设置 `salt' 形参来为哈希函数引入随机化。 随机哈希适用于防止对
数字签名中使用的哈希函数进行碰撞攻击。

     随机哈希被设计用来处理当一方（消息准备者）要生成由另一方（消息签名
     者）进行签名的全部或部分消息的情况。 如果消息准备者能够找到加密哈希
     函数的碰撞现象（即两条消息产生相同的哈希值），则他们就可以准备将产
     生相同哈希值和数字签名但却具有不同结果的有意义的消息版本（例如向某
     个账户转入 $1,000,000 而不是 $10）。 加密哈希函数的设计都是以防碰撞
     性能为其主要目标之一的，但是当前针对加密哈希函数的集中攻击可能导致
     特定加密哈希函数所提供的防碰撞性能低于预期。 随机哈希为签名者提供了
     额外的保护，可以降低准备者在数字签名生成过程中使得两条或更多条消息
     最终产生相同哈希值的可能性 — 即使为特定哈希函数找到碰撞现象是可行的
     。 但是，当消息的所有部分均由签名者准备时，使用随机哈希可能降低数字
     签名所提供的安全性。

     (NIST SP-800-106 "数字签名的随机哈希"(1))

在 BLAKE2 中，盐值会在初始化期间作为对哈希函数的一次性输入而不是对每个压
缩函数的输入来处理。

     警告: 使用 BLAKE2 或任何其他通用加密哈希函数例如 SHA-256 进行 `加盐
     哈希' (或纯哈希) 并不适用于哈希密码。 请参阅 BLAKE2 FAQ(2) 了解更多
     信息。

     >>> import os
     >>> from hashlib import blake2b
     >>> msg = b'some message'
     >>> # Calculate the first hash with a random salt.
     >>> salt1 = os.urandom(blake2b.SALT_SIZE)
     >>> h1 = blake2b(salt=salt1)
     >>> h1.update(msg)
     >>> # Calculate the second hash with a different random salt.
     >>> salt2 = os.urandom(blake2b.SALT_SIZE)
     >>> h2 = blake2b(salt=salt2)
     >>> h2.update(msg)
     >>> # The digests are different.
     >>> h1.digest() != h2.digest()
     True

   ---------- Footnotes ----------

   (1) https://csrc.nist.gov/publications/detail/sp/800-106/final

   (2) https://blake2.net/#qa


File: python.info,  Node: 个性化,  Next: 树形模式,  Prev: 随机哈希,  Up: 例子<9>

5.15.1.12 个性化
................

出于不同的目的强制让哈希函数为相同的输入生成不同的摘要有时也是有用的。 正
如 Skein 哈希函数的作者所言:

     我们建议所有应用设计者慎重考虑这种做法；我们已看到有许多协议在协议
     的某一部分中计算出来的哈希值在另一个完全不同的部分中也可以被使用，
     因为两次哈希计算是针对类似或相关的数据进行的，这样攻击者可以强制应
     用为相同的输入生成哈希值。 个性化协议中所使用的每个哈希函数将有效地
     阻止这种类型的攻击。

     (Skein 哈希函数族(1), p.  21)

BLAKE2 可通过向 `person' 参数传入字节串来进行个性化:

     >>> from hashlib import blake2b
     >>> FILES_HASH_PERSON = b'MyApp Files Hash'
     >>> BLOCK_HASH_PERSON = b'MyApp Block Hash'
     >>> h = blake2b(digest_size=32, person=FILES_HASH_PERSON)
     >>> h.update(b'the same content')
     >>> h.hexdigest()
     '20d9cd024d4fb086aae819a1432dd2466de12947831b75c5a30cf2676095d3b4'
     >>> h = blake2b(digest_size=32, person=BLOCK_HASH_PERSON)
     >>> h.update(b'the same content')
     >>> h.hexdigest()
     'cf68fb5761b9c44e7878bfb2c4c9aea52264a80b75005e65619778de59f383a3'

个性化配合密钥模式也可被用来从单个密钥派生出多个不同密钥。

     >>> from hashlib import blake2s
     >>> from base64 import b64decode, b64encode
     >>> orig_key = b64decode(b'Rm5EPJai72qcK3RGBpW3vPNfZy5OZothY+kHY6h21KM=')
     >>> enc_key = blake2s(key=orig_key, person=b'kEncrypt').digest()
     >>> mac_key = blake2s(key=orig_key, person=b'kMAC').digest()
     >>> print(b64encode(enc_key).decode('utf-8'))
     rbPb15S/Z9t+agffno5wuhB77VbRi6F9Iv2qIxU7WHw=
     >>> print(b64encode(mac_key).decode('utf-8'))
     G9GtHFE1YluXY1zWPlYk1e/nWfu0WSEb0KRcjhDeP/o=

   ---------- Footnotes ----------

   (1) http://www.skein-hash.info/sites/default/files/skein1.3.pdf


File: python.info,  Node: 树形模式,  Prev: 个性化,  Up: 例子<9>

5.15.1.13 树形模式
..................

以下是对包含两个叶子节点的最小树进行哈希的例子:

       10
      /  \
     00  01

这个例子使用 64 字节内部摘要，返回 32 字节最终摘要:

     >>> from hashlib import blake2b
     >>>
     >>> FANOUT = 2
     >>> DEPTH = 2
     >>> LEAF_SIZE = 4096
     >>> INNER_SIZE = 64
     >>>
     >>> buf = bytearray(6000)
     >>>
     >>> # Left leaf
     ... h00 = blake2b(buf[0:LEAF_SIZE], fanout=FANOUT, depth=DEPTH,
     ...               leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
     ...               node_offset=0, node_depth=0, last_node=False)
     >>> # Right leaf
     ... h01 = blake2b(buf[LEAF_SIZE:], fanout=FANOUT, depth=DEPTH,
     ...               leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
     ...               node_offset=1, node_depth=0, last_node=True)
     >>> # Root node
     ... h10 = blake2b(digest_size=32, fanout=FANOUT, depth=DEPTH,
     ...               leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
     ...               node_offset=0, node_depth=1, last_node=True)
     >>> h10.update(h00.digest())
     >>> h10.update(h01.digest())
     >>> h10.hexdigest()
     '3ad2a9b37c6070e374c7a8c508fe20ca86b6ed54e286e93a0318e95e881db5aa'


File: python.info,  Node: 开发人员,  Prev: 例子<9>,  Up: BLAKE2

5.15.1.14 开发人员
..................

BLAKE2(1) 是由 `Jean-Philippe Aumasson', `Samuel Neves', `Zooko
Wilcox-O’Hearn' 和 `Christian Winnerlein' 基于 `Jean-Philippe Aumasson',
`Luca Henzen', `Willi Meier' 和 `Raphael C.-W. Phan' 所创造的 SHA-3(2) 入
围方案 BLAKE(3) 进行设计的。

它使用的核心算法来自由 `Daniel J. Bernstein' 所设计的 ChaCha(4) 加密。

stdlib 实现是基于 pyblake2(5) 模块的。 它由 `Dmitry Chestnykh' 在
`Samuel Neves' 所编写的 C 实现的基础上编写。 此文档拷贝自 pyblake2(6) 并
由 `Dmitry Chestnykh' 撰写。

C 代码由 `Christian Heimes' 针对 Python 进行了部分的重写。

以下公共领域贡献同时适用于 C 哈希函数实现、扩展代码和本文档:

     在法律许可的范围内，作者已将此软件的全部版权以及关联和邻接权利贡献
     到全球公共领域。 此软件的发布不附带任何担保。

     你应该已收到此软件附带的 CC0 公共领域专属证书的副本。 如果没有，请
     参阅 ‘https://creativecommons.org/publicdomain/zero/1.0/’。

根据创意分享公共领域贡献 1.0 通用规范，下列人士为此项目的开发提供了帮助
或对公共领域的修改作出了贡献:

   * `Alexandr Sokolovskiy'

参见
....

模块 *note hmac: 8f.

     使用哈希运算来生成消息验证代码的模块。

模块 *note base64: e.

     针对非二进制环境对二进制哈希值进行编辑的另一种方式。

‘https://blake2.net’

     BLAKE2 官方网站

‘https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2.pdf’

     有关安全哈希算法的 FIPS 180-2 出版物。

‘https://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms’

     包含关于哪些算法存在已知问题以及对其使用所造成的影响的信息的
     Wikipedia 文章。

‘https://www.ietf.org/rfc/rfc2898.txt’

     PKCS #5: 基于密码的加密规范描述 2.0 版

   ---------- Footnotes ----------

   (1) https://blake2.net

   (2) https://en.wikipedia.org/wiki/NIST_hash_function_competition

   (3) https://131002.net/blake/

   (4) https://cr.yp.to/chacha.html

   (5) https://pythonhosted.org/pyblake2/

   (6) https://pythonhosted.org/pyblake2/


File: python.info,  Node: hmac --- 基于密钥的消息验证,  Next: secrets --- 生成安全随机数字用于管理密码,  Prev: hashlib --- 安全哈希与消息摘要,  Up: 加密服务

5.15.2 ‘hmac’ — 基于密钥的消息验证
----------------------------------

`源代码:' Lib/hmac.py(1)

__________________________________________________________________

此模块实现了 HMAC 算法，算法的描述参见 RFC 2104(2)。

 -- 函数: hmac.new (key, msg=None, digestmod='')

     返回一个新的 hmac 对象。 `key' 是一个指定密钥的 bytes 或 bytearray
     对象。 如果提供了 `msg'，将会调用 ‘update(msg)’ 方法。 `digestmod'
     为 HMAC 对象所用的摘要名称、摘要构造器或模块。 它可以是适用于 *note
     hashlib.new(): 1eb9. 的任何名称。 虽然该参数位置靠后，但它却是必须
     的。

     在 3.4 版更改: 形参 `key' 可以为 bytes 或 bytearray 对象。 形参
     `msg' 可以为 *note hashlib: 8d. 所支持的任意类型。 形参 `digestmod'
     可以为某种哈希算法的名称。

     Deprecated since version 3.4, removed in version 3.8: MD5 作为
     `digestmod' 的隐式默认摘要已被弃用。 digestmod 形参现在是必须的。 请
     将其作为关键字参数传入以避免当你没有初始 msg 时将导致的麻烦。

 -- 函数: hmac.digest (key, msg, digest)

     基于给定密钥 `key' 和 `digest' 返回 `msg' 的摘要。 此函数等价于
     ‘HMAC(key, msg, digest).digest()’，但使用了优化的 C 或内联实现，对
     放入内存的消息能处理得更快。 形参 `key', `msg' 和 `digest' 具有与
     *note new(): 85d. 中相同的含义。

     作为 CPython 的实现细节，优化的 C 实现仅当 `digest' 为字符串并且是
     一个 OpenSSL 所支持的摘要算法的名称时才会被使用。

     3.7 新版功能.

HMAC 对象具有下列方法:

 -- 方法: HMAC.update (msg)

     用 `msg' 来更新 hmac 对象。 重复调用相当于单次调用并传入所有参数的
     拼接结果: ‘m.update(a); m.update(b)’ 等价于 ‘m.update(a + b)’。

     在 3.4 版更改: 形参 `msg' 可以为 *note hashlib: 8d. 所支持的任何类
     型。

 -- 方法: HMAC.digest ()

     返回当前已传给 *note update(): 85e. 方法的字节串数据的摘要。 这个字
     节串数据的长度将与传给构造器的摘要的长度 `digest_size' 相同。 它可
     以包含非 ASCII 的字节，包括 NUL 字节。

          警告: 在验证例程运行期间将 *note digest(): 398. 的输出与外部提
          供的摘要进行比较时，建议使用 *note compare_digest(): a14. 函数
          而不是 ‘==’ 运算符以减少定时攻击防御力的不足。

 -- 方法: HMAC.hexdigest ()

     类似于 *note digest(): 398. 但摘要会以两倍长度字符串的形式返回，其
     中仅包含十六进制数码。 这可以被用于在电子邮件或其他非二进制环境中安
     全地交换数据值。

          警告: 在验证例程运行期间将 *note hexdigest(): 1ed8. 的输出与外
          部提供的摘要进行比较时，建议使用 *note compare_digest(): a14.
          函数而不是 ‘==’ 运算符以减少定时攻击防御力的不足。

 -- 方法: HMAC.copy ()

     返回 hmac 对象的副本（“克隆）。 这可被用来高效地计算共享相同初始子
     串的数据的摘要。

hash 对象具有以下属性：

 -- 属性: HMAC.digest_size

     以字节表示的结果 HMAC 摘要的大小。

 -- 属性: HMAC.block_size

     以字节表示的哈希算法的内部块大小。

     3.4 新版功能.

 -- 属性: HMAC.name

     HMAC 的规范名称，总是为小写形式，例如 ‘hmac-md5’。

     3.4 新版功能.

这个模块还提供了下列辅助函数:

 -- 函数: hmac.compare_digest (a, b)

     返回 ‘a == b’。 此函数使用一种经专门设计的方式通过避免基于内容的短
     路行为来防止定时分析，使得它适合处理密码。 `a' 和 `b' 必须为相同的
     类型：或者是 *note str: 339. (仅限 ASCII 字符，如 *note
     HMAC.hexdigest(): 1ed8. 的返回值)，或者是 *note bytes-like object:
     5f1.。

          注解: 如果 `a' 和 `b' 具有不同的长度，或者如果发生了错误，定时
          攻击在理论上可以获取有关 `a' 和 `b' 的类型和长度信息 — 但不能
          获取它们的值。

     3.3 新版功能.

参见
....

模块 *note hashlib: 8d.

     提供安全哈希函数的 Python 模块。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/hmac.py

   (2) https://tools.ietf.org/html/rfc2104.html


File: python.info,  Node: secrets --- 生成安全随机数字用于管理密码,  Prev: hmac --- 基于密钥的消息验证,  Up: 加密服务

5.15.3 ‘secrets’ — 生成安全随机数字用于管理密码
-----------------------------------------------

3.6 新版功能.

`源代码:' Lib/secrets.py(1)

__________________________________________________________________

*note secrets: e5. 模块可用于生成高加密强度的随机数，适应管理密码、账户
验证、安全凭据和相关机密数据管理的需要。

特别地，应当优先使用 *note secrets: e5. 来替代 *note random: dd. 模块中
的默认伪随机数生成器，后者被设计用于建模和仿真，而不适用于安全和加密。

参见
....

PEP 506(2)

* Menu:

* 随机数::
* 生成凭据::
* 其他功能::
* 应用技巧与最佳实践::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/secrets.py

   (2) https://www.python.org/dev/peps/pep-0506


File: python.info,  Node: 随机数,  Next: 生成凭据,  Up: secrets --- 生成安全随机数字用于管理密码

5.15.3.1 随机数
...............

通过 *note secrets: e5. 模块可以访问你的操作系统所能提供的最安全的随机性
来源。

 -- 类: secrets.SystemRandom

     使用操作系统所提供的最高质量源来生成随机数的类。 请参阅 *note
     random.SystemRandom: 1b19. 了解更多细节。

 -- 函数: secrets.choice (sequence)

     返回从一个非空序列中随机选取的元素。

 -- 函数: secrets.randbelow (n)

     返回一个 [0, `n') 范围之内的随机整数。

 -- 函数: secrets.randbits (k)

     返回一个具有 `k' 个随机比特位的整数。


File: python.info,  Node: 生成凭据,  Next: 其他功能,  Prev: 随机数,  Up: secrets --- 生成安全随机数字用于管理密码

5.15.3.2 生成凭据
.................

*note secrets: e5. 模块提供了一些生成安全凭据的函数，适用于诸如密码重置
、难以猜测的 URL 之类的应用场景。

 -- 函数: secrets.token_bytes ([nbytes=None])

     返回一个包含 `nbytes' 个字节的随机字节串。 如果 `nbytes' 为 ‘None’
     或未提供，则会使用一个合理的默认值。

          >>> token_bytes(16)
          b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b'

 -- 函数: secrets.token_hex ([nbytes=None])

     返回一个十六进制数码形式的随机字符串。 字符串具有 `nbytes' 个随机字
     节，每个字节转换为两个十六进制数码。 如果 `nbytes' 为 ‘None’ 或未提
     供，则会使用一个合理的默认值。

          >>> token_hex(16)
          'f9bf78b9a18ce6d46a0cd2b0b86df9da'

 -- 函数: secrets.token_urlsafe ([nbytes=None])

     返回一个 URL 安全的随机字符串，包含 `nbytes' 个随机字节。 文本将使
     用 Base64 编码，因此平均来说每个字节将对应 1.3 个结果字符。 如果
     `nbytes' 为 ‘None’ 或未提供，则会使用一个合理的默认值。

          >>> token_urlsafe(16)
          'Drmhze6EPcv0fN_81Bj-nA'

* Menu:

* 凭据应当使用多少个字节？::


File: python.info,  Node: 凭据应当使用多少个字节？,  Up: 生成凭据

5.15.3.3 凭据应当使用多少个字节？
.................................

为了在面对 暴力攻击(1) 时保证安全，凭据必须具有足够的随机性。 不幸的是，
对随机性是否足够的标准会随着计算机越来越强大并能够在更短时间内进行更多猜
测而不断提高。 在 2015 年时，人们认为 32 字节（256 位）的随机性对于
*note secrets: e5. 模块所适合的典型用例来说是足够的。

作为想要自行管理凭据长度的用户，你可以通过为各种 ‘token_*’ 函数指定一个
*note int: 185. 参数来显式地指定凭据要使用多大的随机性。 该参数以字节数
来表示要使用的随机性大小。

在其他情况下，如果未提供参数，或者如果参数为 ‘None’，则 ‘token_*’ 函数将
改用一个合理的默认值。

     注解: 该默认值可能在任何时候被改变，包括在维护版本更新的时候。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Brute-force_attack


File: python.info,  Node: 其他功能,  Next: 应用技巧与最佳实践,  Prev: 生成凭据,  Up: secrets --- 生成安全随机数字用于管理密码

5.15.3.4 其他功能
.................

 -- 函数: secrets.compare_digest (a, b)

     如果字符串 `a' 与 `b' 相等则返回 ‘True’，否则返回 ‘False’，该处理方
     式可降低 定时攻击(1) 的风险。 请参阅 *note hmac.compare_digest():
     a14. 了解更多细节。

   ---------- Footnotes ----------

   (1) https://codahale.com/a-lesson-in-timing-attacks/


File: python.info,  Node: 应用技巧与最佳实践,  Prev: 其他功能,  Up: secrets --- 生成安全随机数字用于管理密码

5.15.3.5 应用技巧与最佳实践
...........................

本节展示了一些使用 *note secrets: e5. 来管理基本安全级别的应用技巧和最佳
实践。

生成长度为八个字符的字母数字密码:

     import string
     import secrets
     alphabet = string.ascii_letters + string.digits
     password = ''.join(secrets.choice(alphabet) for i in range(8))

     注解: 应用程序不能 以可恢复的格式存储密码(1)，无论是用纯文本还是加
     密。 它们应当使用高加密强度的单向（不可恢复）哈希函数来加盐并生成哈
     希值。

生成长度为十个字符的字母数字密码，其中包含至少一个小写字母，至少一个大写
字母以及至少三个数字:

     import string
     import secrets
     alphabet = string.ascii_letters + string.digits
     while True:
         password = ''.join(secrets.choice(alphabet) for i in range(10))
         if (any(c.islower() for c in password)
                 and any(c.isupper() for c in password)
                 and sum(c.isdigit() for c in password) >= 3):
             break

生成 XKCD 风格的密码串(2):

     import secrets
     # On standard Linux systems, use a convenient dictionary file.
     # Other platforms may need to provide their own word-list.
     with open('/usr/share/dict/words') as f:
         words = [word.strip() for word in f]
         password = ' '.join(secrets.choice(words) for i in range(4))

生成难以猜测的临时 URL，其中包含适合密码恢复应用的安全凭据:

     import secrets
     url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()

   ---------- Footnotes ----------

   (1) http://cwe.mitre.org/data/definitions/257.html

   (2) https://xkcd.com/936/


File: python.info,  Node: 通用操作系统服务,  Next: 并发执行,  Prev: 加密服务,  Up: Python 标准库

5.16 通用操作系统服务
=====================

本章中描述的各模块提供了在（几乎）所有的操作系统上可用的操作系统特性的接
口，例如文件和时钟。这些接口通常以 Unix 或 C 接口为参考对象，不过在大多
数其他系统上也可用。这里有一个概述：

* Menu:

* os: os --- 多种操作系统接口. 多种操作系统接口
* io: io --- 处理流的核心工具. 处理流的核心工具
* time: time --- 时间的访问和转换. 时间的访问和转换
* argparse: argparse --- 命令行选项、参数和子命令解析器. 命令行选项、参数和子命令解析器
* getopt: getopt --- C 风格的命令行选项解析器. C 风格的命令行选项解析器
* logging: logging --- Python 的日志记录工具. Python 的日志记录工具
* logging.config: logging config --- 日志记录配置. 日志记录配置
* logging.handlers: logging handlers --- 日志处理. 日志处理
* getpass: getpass --- 便携式密码输入工具. 便携式密码输入工具
* curses: curses --- 终端字符单元显示的处理. 终端字符单元显示的处理
* curses.textpad: curses textpad --- 用于 curses 程序的文本输入控件. 用于 curses 程序的文本输入控件
* curses.ascii: curses ascii --- 用于 ASCII 字符的工具. 用于 ASCII 字符的工具
* curses.panel: curses panel --- curses 的 panel 栈扩展. curses 的 panel 栈扩展
* platform: platform --- 获取底层平台的标识数据. 获取底层平台的标识数据
* errno: errno --- 标准 errno 系统符号. 标准 errno 系统符号
* ctypes: ctypes --- Python 的外部函数库. Python 的外部函数库


File: python.info,  Node: os --- 多种操作系统接口,  Next: io --- 处理流的核心工具,  Up: 通用操作系统服务

5.16.1 ‘os’ — 多种操作系统接口
------------------------------

`源代码：' Lib/os.py(1)

__________________________________________________________________

本模块提供了一种使用与操作系统相关的功能的便捷式途径。 如果你只是想读写
一个文件，请参阅 *note open(): 4f8.，如果你想操作文件路径，请参阅 *note
os.path: c6. 模块，如果你想读取通过命令行给出的所有文件中的所有行，请参
阅 *note fileinput: 80. 模块。 为了创建临时文件和目录，请参阅 *note
tempfile: 104. 模块，对于高级文件和目录处理，请参阅 *note shutil: ea. 模
块。

关于这些函数的适用性的说明：

   * Python中所有依赖于操作系统的内置模块的设计都是这样，只要不同的操作
     系统某一相同的功能可用，它就使用相同的接口。例如，函数
     ‘os.stat(path)’ 以相同的格式返回关于 `path' 的状态信息（该格式源于
     POSIX 接口）。

   * 特定于某一操作系统的扩展通过操作 *note os: c5. 模块也是可用的，但是
     使用它们当然是对可移植性的一种威胁。

   * 所有接受路径或文件名的函数都同时支持字节串和字符串对象，并在返回路
     径或文件名时使用相应类型的对象作为结果。

   * 在 VxWorks 系统上，os.fork, os.execv 和 os.spawn*p* 不被支持。

     注解: 如果使用无效或无法访问的文件名与路径，或者其他类型正确但操作
     系统不接受的参数，此模块的所有函数都抛出 *note OSError: 1d4. （或者
     它的子类）。

 -- 例外: os.error

     内建的 *note OSError: 1d4. 异常的一个别名。

 -- 数据: os.name

     导入的依赖特定操作系统的模块的名称。以下名称目前已注册: ‘'posix'’,
     ‘'nt'’, ‘'java'’.

     参见
     ....

     *note sys.platform: 2b2. 有更详细的描述.  *note os.uname(): a65. 只
     给出系统提供的版本信息。

     *note platform: cf. 模块对系统的标识有更详细的检查。

* Menu:

* 文件名，命令行参数，以及环境变量。::
* 进程参数::
* 创建文件对象::
* 文件描述符操作::
* 文件和目录::
* 进程管理::
* 调度器接口::
* 其他系统信息::
* 随机数: 随机数<2>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/os.py


File: python.info,  Node: 文件名，命令行参数，以及环境变量。,  Next: 进程参数,  Up: os --- 多种操作系统接口

5.16.1.1 文件名，命令行参数，以及环境变量。
...........................................

在 Python 中，使用字符串类型表示文件名、命令行参数和环境变量。 在某些系
统上，在将这些字符串传递给操作系统之前，必须将这些字符串解码为字节。
Python 使用文件系统编码来执行此转换（请参阅 *note
sys.getfilesystemencoding(): 4fe. ）。

在 3.1 版更改: 在某些系统上，使用文件系统编码进行转换可能会失败。 在这种
情况下，Python 会使用 *note 代理转义编码错误处理器: 1858.，这意味着在解
码时，不可解码的字节被 Unicode 字符 U+DCxx 替换，并且这些字节在编码时再
次转换为原始字节。

文件系统编码必须保证成功解码小于 128 的所有字节。如果文件系统编码无法提
供此保证， API 函数可能会引发 UnicodeErrors 。


File: python.info,  Node: 进程参数,  Next: 创建文件对象,  Prev: 文件名，命令行参数，以及环境变量。,  Up: os --- 多种操作系统接口

5.16.1.2 进程参数
.................

这些函数和数据项提供了操作当前进程和用户的信息。

 -- 函数: os.ctermid ()

     返回与进程控制终端对应的文件名。

     *note 可用性: 136f.: Unix。

 -- 数据: os.environ

     一个表示字符串环境的 *note mapping: b41. 对象。 例如，
     ‘environ['HOME']’ 是你的主目录（在某些平台上）的路径名，相当于 C 中
     的 ‘getenv("HOME")’。

     这个映射是在第一次导入 *note os: c5. 模块时捕获的，通常作为 Python
     启动时处理 ‘site.py’ 的一部分。除了通过直接修改 ‘os.environ’ 之外，
     在此之后对环境所做的更改不会反映在 ‘os.environ’ 中。

     如果平台支持 *note putenv(): 1ef5. 函数，这个映射除了可以用于查询环
     境外还能用于修改环境。 当这个映射被修改时，*note putenv(): 1ef5. 将
     被自动调用。

     在Unix系统上，键和值会使用 *note sys.getfilesystemencoding(): 4fe.
     和 ‘'surrogateescape'’ 的错误处理。如果你想使用其他的编码，使用
     *note environb: b9c.。

          注解: 直接调用 *note putenv(): 1ef5. 并不会影响 ‘os.environ’，
          所以推荐直接修改 ‘os.environ’。

          注解: 在某些平台上，包括 FreeBSD 和 Mac OS X，设置 ‘environ’ 可
          能导致内存泄露。参阅 ‘putenv()’ 的系统文档。

     如果平台没有提供 *note putenv(): 1ef5, 为了使启动的子进程使用修改后
     的环境，一份修改后的映射会被传给合适的进程创建函数。

     如果平台支持 *note unsetenv(): d4b. 函数，你可以通过删除映射中元素
     的方式来删除对应的环境变量。当一个元素被从 ‘os.environ’ 删除时，以
     及 ‘pop()’ 或 ‘clear()’ 被调用时， *note unsetenv(): d4b. 会被自动
     调用。

 -- 数据: os.environb

     字节版本的 *note environ: b3f.: 一个以字节串表示环境的 *note
     mapping: b41. 对象。 *note environ: b3f. 和 *note environb: b9c. 是
     同步的（修改 *note environb: b9c. 会更新 *note environ: b3f.，反之
     亦然）。

     只有在 *note supports_bytes_environ: b9a. 为 ‘True’ 的时候 *note
     environb: b9c. 才是可用的。

     3.2 新版功能.

 -- 函数: os.chdir (path)

 -- 函数: os.fchdir (fd)

 -- 函数: os.getcwd ()

     以上函数请参阅 *note 文件和目录: 1ef6. 。

 -- 函数: os.fsencode (filename)

     编码 *note 路径类: 373. `文件名' 为文件系统接受的形式，使用
     ‘'surrogateescape'’ 代理转义编码错误处理器，在Windows系统上会使用
     ‘'strict'’ ；返回 *note bytes: 33a. 字节类型不变。

     *note fsdecode(): 4f6. 是此函数的逆向函数。

     3.2 新版功能.

     在 3.6 版更改: 增加对实现了 *note os.PathLike: 4f3. 接口的对象的支
     持。

 -- 函数: os.fsdecode (filename)

     从文件系统编码方式解码为 *note 路径类: 373. 文件名，使用
     ‘'surrogateescape'’ 代理转义编码错误处理器，在Windows系统上会使用
     ‘'strict'’ ；返回 *note str: 339. 字符串不变。

     *note fsencode(): 4f7. 是此函数的逆向函数。

     3.2 新版功能.

     在 3.6 版更改: 增加对实现了 *note os.PathLike: 4f3. 接口的对象的支
     持。

 -- 函数: os.fspath (path)

     返回路径的文件系统表示。

     如果传入的是 *note str: 339. 或 *note bytes: 33a. 类型的字符串，将
     原样返回。否则 *note __fspath__(): 4f4. 将被调用，如果得到的是一个
     *note str: 339. 或 *note bytes: 33a. 类型的对象，那就返回这个值。其
     他所有情况则会抛出 *note TypeError: 193.  异常。

     3.6 新版功能.

 -- 类: os.PathLike

     某些对象用于表示文件系统中的路径（如 *note pathlib.PurePath: 1051.
     对象），本类是这些对象的 *note 抽象基类: b3b.。

     3.6 新版功能.

      -- 方法: abstractmethod __fspath__ ()

          返回当前对象的文件系统表示。

          这个方法只应该返回一个 *note str: 339. 字符串或 *note bytes:
          33a. 字节串，请优先选择 *note str: 339. 字符串。

 -- 函数: os.getenv (key, default=None)

     如果存在，返回环境变量 `key' 的值，否则返回 `default'。 `key' ，
     `default' 和返回值均为 str 字符串类型。

     在Unix系统上，键和值会使用 *note sys.getfilesystemencoding():
     4fe. 和‘‘’surrogateescape’‘‘ 错误处理进行解码。如果你想使用其他的编
     码，使用 *note os.getenvb(): b9b.。

     *note 可用性: 136f.: 大部分的Unix系统，Windows。

 -- 函数: os.getenvb (key, default=None)

     如果存在环境变量 `key' 那么返回其值，否则返回 `default'。 `key' ，
     `default' 和返回值均为bytes字节串类型。

     *note getenvb(): b9b. 仅在 *note supports_bytes_environ: b9a. 为
     ‘True’ 时可用。

     *note 可用性: 136f.: 大部分的Unix系统。

     3.2 新版功能.

 -- 函数: os.get_exec_path (env=None)

     返回将用于搜索可执行文件的目录列表，与在外壳程序中启动一个进程时相
     似。指定的 `env' 应为用于搜索 PATH 的环境变量字典。默认情况下，当
     `env' 为 ‘None’ 时，将会使用 *note environ: b3f. 。

     3.2 新版功能.

 -- 函数: os.getegid ()

     返回当前进程的有效组ID。对应当前进程执行文件的 "set id" 位。

     *note 可用性: 136f.: Unix。

 -- 函数: os.geteuid ()

     返回当前进程的有效用户ID。

     *note 可用性: 136f.: Unix。

 -- 函数: os.getgid ()

     返回当前进程的实际组ID。

     *note 可用性: 136f.: Unix。

 -- 函数: os.getgrouplist (user, group)

     返回该用户所在的组 ID 列表。可能 `group' 参数没有在返回的列表中，实
     际上用户应该也是属于该 `group'。`group' 参数一般可以从储存账户信息
     的密码记录文件中找到。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: os.getgroups ()

     返回当前进程关联的附加组ID列表

     *note 可用性: 136f.: Unix。

          注解: 在Mac OS X系统中，*note getgroups(): 1efc. 会和其他 Unix
          平台有些不同。如果 Python 解释器是在 ‘10.5’ 或更早版本中部署，
          *note getgroups(): 1efc. 返回当前用户进程相关的有效组ID列表。
          该列表长度由于系统预设的接口限制，最长为 16。 而且在适当的权限
          下，返回结果还会因 *note getgroups(): 1efc. 而发生变化；如果
          Python 解释器是在 ‘10.5’ 以上版本中部署，*note getgroups():
          1efc. 返回进程所属有效用户 ID 所对应的用户的组 ID 列表，组用户
          列表可能因为进程的生存周期而发生变动，而且也不会因为 *note
          setgroups(): 1efd. 的调用而发生，返回的组用户列表长度也没有长
          度 16 的限制。在部署中，Python 解释器用到的变量
          ‘MACOSX_DEPLOYMENT_TARGET’ 可以用 *note
          sysconfig.get_config_var(): 96c.。

 -- 函数: os.getlogin ()

     返回通过控制终端进程进行登录的用户名。在多数情况下，使用 *note
     getpass.getuser(): 1eff. 会更有效，因为后者会通过检查环境变量
     ‘LOGNAME’ 或 ‘USERNAME’ 来查找用户，再由
     ‘pwd.getpwuid(os.getuid())[0]’ 来获取当前用户 ID 的登录名。

     *note 可用性: 136f.: Unix, Windows。

 -- 函数: os.getpgid (pid)

     根据进程id `pid' 返回进程的组 ID 列表。如果 `pid' 为 0，则返回当前
     进程的进程组 ID 列表

     *note 可用性: 136f.: Unix。

 -- 函数: os.getpgrp ()

     返回当时进程组的ID

     *note 可用性: 136f.: Unix。

 -- 函数: os.getpid ()

     返回当前进程ID

 -- 函数: os.getppid ()

     返回父进程ID。当父进程已经结束，在Unix中返回的ID是初始进程(1)中的一
     个，在Windows中仍然是同一个进程ID，该进程ID有可能已经被进行进程所占
     用。

     *note 可用性: 136f.: Unix, Windows。

     在 3.2 版更改: 添加WIndows的支持。

 -- 函数: os.getpriority (which, who)

     获取程序调度优先级。`which' 参数值可以是 *note PRIO_PROCESS: 1f04.，
     *note PRIO_PGRP: 1f05.，或 *note PRIO_USER: 1f06. 中的一个，`who' 是
     相对于 `which' (*note PRIO_PROCESS: 1f04. 的进程标识符，*note
     PRIO_PGRP: 1f05. 的进程组标识符和 *note PRIO_USER: 1f06. 的用户
     ID)。当 `who' 为 0 时（分别）表示调用的进程，调用进程的进程组或调用
     进程所属的真实用户 ID。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 数据: os.PRIO_PROCESS
 -- 数据: os.PRIO_PGRP
 -- 数据: os.PRIO_USER

     函数 *note getpriority(): a4e. 和 *note setpriority(): a4f. 的参数
     。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: os.getresuid ()

     返回一个由 (ruid, euid, suid) 所组成的元组，分别表示当前进程的真实
     用户ID，有效用户ID和暂存用户ID。

     *note 可用性: 136f.: Unix。

     3.2 新版功能.

 -- 函数: os.getresgid ()

     返回一个由 (rgid, egid, sgid) 所组成的元组，分别表示当前进程的真实
     组ID，有效组ID和暂存组ID。

     *note 可用性: 136f.: Unix。

     3.2 新版功能.

 -- 函数: os.getuid ()

     返回当前进程的真实用户ID。

     *note 可用性: 136f.: Unix。

 -- 函数: os.initgroups (username, gid)

     调用系统 initgroups()，使用指定用户所在的所有值来初始化组访问列表，
     包括指定的组ID。

     *note 可用性: 136f.: Unix。

     3.2 新版功能.

 -- 函数: os.putenv (key, value)

     将名为 `key' 的环境变量值设置为 `value'。该变量名修改会影响由 *note
     os.system(): dc9.， *note popen(): 2aa. ，*note fork(): 969. 和
     *note execv(): 1f08. 发起的子进程。

     *note 可用性: 136f.: 大部分的Unix系统，Windows。

          注解: 在一些平台，包括 FreeBSD 和 Mac OS X，设置 ‘environ’ 可
          能导致内存泄露。详情参考 putenv 相关系统文档。

     当系统支持 *note putenv(): 1ef5. 时，‘os.environ’ 中的参数赋值会自
     动转换为对 *note putenv(): 1ef5. 的调用。不过 *note putenv(): 1ef5.
     的调用不会更新 ‘os.environ’，因此最好使用 ‘os.environ’ 对变量赋值。

     引发一个 *note 审计事件: ea1. ‘os.putenv’，附带参数 ‘key’, ‘value’。

 -- 函数: os.setegid (egid)

     设置当前进程的有效组ID。

     *note 可用性: 136f.: Unix。

 -- 函数: os.seteuid (euid)

     设置当前进程的有效用户ID。

     *note 可用性: 136f.: Unix。

 -- 函数: os.setgid (gid)

     设置当前进程的组ID。

     *note 可用性: 136f.: Unix。

 -- 函数: os.setgroups (groups)

     将 `group' 参数值设置为与当进程相关联的附加组ID列表。`group' 参数必
     须为一个序列，每个元素应为每个组的数字ID。该操作通常只适用于超级用
     户。

     *note 可用性: 136f.: Unix。

          注解: 在 Mac OS X 中，`groups' 的长度不能超过系统定义的最大有
          效组 ID 个数，一般为 16。 如果它没有返回与调用 setgroups() 所
          设置的相同的组列表，请参阅 *note getgroups(): 1efc. 的文档。

 -- 函数: os.setpgrp ()

     根据已实现的版本（如果有）来调用系统 ‘setpgrp()’ 或 ‘setpgrp(0, 0)’
     。相关说明，请参考 Unix 手册。

     *note 可用性: 136f.: Unix。

 -- 函数: os.setpgid (pid, pgrp)

     使用系统调用 ‘setpgid()’，将 `pid' 对应进程的组ID设置为 `pgrp'。相
     关说明，请参考 Unix 手册。

     *note 可用性: 136f.: Unix。

 -- 函数: os.setpriority (which, who, priority)

     设置程序调度优先级。 `which' 的值为 *note PRIO_PROCESS: 1f04, *note
     PRIO_PGRP: 1f05. 或 *note PRIO_USER: 1f06. 之一，而 `who' 会相对于
     `which' (*note PRIO_PROCESS: 1f04. 的进程标识符, *note PRIO_PGRP:
     1f05. 的进程组标识符和 *note PRIO_USER: 1f06. 的用户 ID) 被解析。
     `who' 值为零 (分别) 表示调用进程，调用进程的进程组或调用进程的真实
     用户 ID。 `priority' 是范围在 -20 至 19 的值。 默认优先级为 0；较小
     的优先级数值会更优先被调度。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: os.setregid (rgid, egid)

     设置当前进程的真实和有效组ID。

     *note 可用性: 136f.: Unix。

 -- 函数: os.setresgid (rgid, egid, sgid)

     设置当前进程的真实，有效和暂存组ID。

     *note 可用性: 136f.: Unix。

     3.2 新版功能.

 -- 函数: os.setresuid (ruid, euid, suid)

     设置当前进程的真实，有效和暂存用户ID。

     *note 可用性: 136f.: Unix。

     3.2 新版功能.

 -- 函数: os.setreuid (ruid, euid)

     设置当前进程的真实和有效用户ID。

     *note 可用性: 136f.: Unix。

 -- 函数: os.getsid (pid)

     调用系统调用 ‘getsid()’。相关说明，请参考 Unix 手册。

     *note 可用性: 136f.: Unix。

 -- 函数: os.setsid ()

     使用系统调用 ‘getsid()’。相关说明，请参考 Unix 手册。

     *note 可用性: 136f.: Unix。

 -- 函数: os.setuid (uid)

     设置当前进程的用户ID。

     *note 可用性: 136f.: Unix。

 -- 函数: os.strerror (code)

     根据 `code' 中的错误码返回错误消息。 在某些平台上当给出未知错误码时
     ‘strerror()’ 将返回 ‘NULL’ 并会引发 *note ValueError: 1fc.。

 -- 数据: os.supports_bytes_environ

     如果操作系统上原生环境类型是字节型则为 ‘True’ (例如在 Windows 上为
     ‘False’)。

     3.2 新版功能.

 -- 函数: os.umask (mask)

     设定当前数值掩码并返回之前的掩码。

 -- 函数: os.uname ()

     返回当前操作系统的识别信息。返回值是一个有5个属性的对象：

        * ‘sysname’ - 操作系统名

        * ‘nodename’ - 机器在网络上的名称（需要先设定）

        * ‘release’ - 操作系统发行信息

        * ‘version’ - 操作系统版本信息

        * ‘machine’ - 硬件标识符

     为了向后兼容，该对象也是可迭代的，像是一个按照 ‘sysname’，
     ‘nodename’，‘release’，‘version’，和 ‘machine’ 顺序组成的元组。

     有些系统会将 ‘nodename’ 截短为 8 个字符或截短至前缀部分；获取主机名
     的一个更好方式是 *note socket.gethostname(): 1f14. 或甚至可以用
     ‘socket.gethostbyaddr(socket.gethostname())’。

     *note 可用性: 136f.: 较新的 Unix 版本。

     在 3.3 版更改: 返回结果的类型由元组变成一个类似元组的对象，同时具有
     命名的属性。

 -- 函数: os.unsetenv (key)

     取消设置（删除）名为 `key' 的环境变量。变量名的改变会影响由 *note
     os.system(): dc9.，*note popen(): 2aa.，*note fork(): 969. 和 *note
     execv(): 1f08. 触发的子进程。

     当系统支持 *note unsetenv(): d4b. ，删除在 ‘os.environ’ 中的变量会
     自动转换为对 *note unsetenv(): d4b. 的调用。但是 *note unsetenv():
     d4b. 不能更新 ‘os.environ’，因此最好直接删除 ‘os.environ’ 中的变量
     。

     引发一个 *note 审计事件: ea1. ‘os.unsetenv’，附带参数 ‘key’。

     *note 可用性: 136f.: 大部分的Unix系统。


File: python.info,  Node: 创建文件对象,  Next: 文件描述符操作,  Prev: 进程参数,  Up: os --- 多种操作系统接口

5.16.1.3 创建文件对象
.....................

这些函数创建新的 *note file objects: b4a. 。（参见 *note open(): 66e. 以
获取打开文件描述符的相关信息。）

 -- 函数: os.fdopen (fd, *args, **kwargs)

     返回打开文件描述符 `fd' 对应文件的对象。类似内建 *note open(): 4f8.
     函数，二者接受同样的参数。不同之处在于 *note fdopen(): 1441. 第一个
     参数应该为整数。


File: python.info,  Node: 文件描述符操作,  Next: 文件和目录,  Prev: 创建文件对象,  Up: os --- 多种操作系统接口

5.16.1.4 文件描述符操作
.......................

这些函数对文件描述符所引用的 I/O 流进行操作。

文件描述符是一些小的整数，对应于当前进程所打开的文件。例如，标准输入的文
件描述符通常是0，标准输出是1，标准错误是2。之后被进程打开的文件的文件描
述符会被依次指定为3，4，5等。“文件描述符”这个词有点误导性，在 Unix 平台
中套接字和管道也被文件描述符所引用。

当需要时，可以用 *note fileno(): 1f19. 可以获得 *note file object: b4a.
所对应的文件描述符。需要注意的是，直接使用文件描述符会绕过文件对象的方法
，会忽略如数据内部缓冲等情况。

 -- 函数: os.close (fd)

     关闭文件描述符 `fd'。

          注解: 该功能适用于低级 I/O 操作，必须用于 *note os.open():
          66e. 或 *note pipe(): 1f1a. 返回的文件描述符。若要关闭由内建函
          数 *note open(): 4f8.、*note popen(): 2aa. 或 *note fdopen():
          1441. 返回的 "文件对象"，则应使用其相应的 *note close(): 101e.
          方法。

 -- 函数: os.closerange (fd_low, fd_high)

     关闭从 `fd_low' （包括）到 `fd_high' （排除）间的文件描述符，并忽略
     错误。类似（但快于）:

          for fd in range(fd_low, fd_high):
              try:
                  os.close(fd)
              except OSError:
                  pass

 -- 函数: os.copy_file_range (src, dst, count, offset_src=None,
          offset_dst=None)

     从文件描述符 `src' 复制 `count' 字节，从偏移量 `offset_src' 开始读
     取，到文件描述符 `dst'，从偏移量 `offset_dst' 开始写入。如果
     `offset_src' 为 None，则 `src' 将从当前位置开始读取；`offset_dst' 同
     理。`src' 和 `dst' 指向的文件必须处于相同的文件系统，否则将会抛出一
     个 *note errno: 1715. 被设为 *note errno.EXDEV: 1f1d. 的 *note
     OSError: 1d4. 。

     此复制的完成没有额外的从内核到用户空间再回到内核的数据转移花费。另
     外，一些文件系统可能实现额外的优化。完成复制就如同打开两个二进制文
     件一样。

     返回值是复制的字节的数目。这可能低于需求的数目。

     *note Availability: 136f.: Linux kernel >= 4.5 或 glibc >= 2.27。

     3.8 新版功能.

 -- 函数: os.device_encoding (fd)

     如果连接到终端，则返回一个与 `fd' 关联的设备描述字符，否则返回
     *note None: 158.。

 -- 函数: os.dup (fd)

     返回一个文件描述符 `fd' 的副本。该文件描述符的副本是 *note
     不可继承的: 803.。

     在 Windows 中，当复制一个标准流（0: stdin, 1: stdout, 2: stderr）时
     ，新的文件描述符是 *note 可继承的: 803.。

     在 3.4 版更改: 新的文件描述符现在是不可继承的。

 -- 函数: os.dup2 (fd, fd2, inheritable=True)

     把文件描述符 `fd' 复制为 `fd2'，必要时先关闭后者。返回 `fd2'。新的
     文件描述符默认是 *note 可继承的: 803.，除非在 `inheritable' 为
     ‘False’ 时，是不可继承的。

     在 3.4 版更改: 添加可选参数 `inheritable'。

     在 3.7 版更改: 成功时返回 `fd2'，以过去的版本中，总是返回 ‘None’。

 -- 函数: os.fchmod (fd, mode)

     将 `fd' 指定文件的权限状态修改为 `mode'。可以参考 *note chmod():
     a3b. 中列出 `mode' 的可用值。从Python 3.3开始，这相当于
     ‘os.chmod(fd, mode)’。

     引发一个 *note 审计事件: ea1. ‘os.chmod’，附带参数 ‘path’、‘mode’、
     ‘dir_fd’。

     *note 可用性: 136f.: Unix。

 -- 函数: os.fchown (fd, uid, gid)

     分别将 `fd' 指定文件的所有者和组 ID 修改为 `uid' 和 `gid' 的值。若
     不想变更其中的某个 ID，可将相应值设为 -1。参考 *note chown(): a3c.。
     从 Python 3.3 开始，这相当于 ‘os.chown(fd, uid, gid)’。

     引发一个 *note 审计事件: ea1. ‘os.chown’，附带参数 ‘path’、‘uid’、
     ‘gid’、‘dir_fd’。

     *note 可用性: 136f.: Unix。

 -- 函数: os.fdatasync (fd)

     强制将文件描述符 `fd' 指定文件写入磁盘。不强制更新元数据。

     *note 可用性: 136f.: Unix。

          注解: 该功能在 MacOS 中不可用。

 -- 函数: os.fpathconf (fd, name)

     返回与打开的文件有关的系统配置信息。`name' 指定要查找的配置名称，它
     可以是字符串，是一个系统已定义的名称，这些名称定义在不同标准（
     POSIX.1，Unix 95，Unix 98 等）中。一些平台还定义了额外的其他名称。
     当前操作系统已定义的名称在 ‘pathconf_names’ 字典中给出。对于未包含
     在该映射中的配置名称，也可以传递一个整数作为 `name'。

     如果 `name' 是一个字符串且不是已定义的名称，将抛出 *note
     ValueError: 1fc. 异常。如果当前系统不支持 `name' 指定的配置名称，即
     使该名称存在于 ‘pathconf_names’，也会抛出 *note OSError: 1d4. 异常
     ，错误码为 *note errno.EINVAL: fd9.。

     从 Python 3.3 起，此功能等价于 ‘os.pathconf(fd, name)’。

     *note 可用性: 136f.: Unix。

 -- 函数: os.fstat (fd)

     获取文件描述符 `fd' 的状态. 返回一个 *note stat_result: 109a. 对象
     。

     从 Python 3.3 起，此功能等价于 ‘os.stat(fd)’。

     参见
     ....

     *note stat(): 1f2. 函数。

 -- 函数: os.fstatvfs (fd)

     返回文件系统的信息，该文件系统是文件描述符 `fd' 指向的文件所在的文
     件系统，与 *note statvfs(): a4b. 一样。从 Python 3.3 开始，它等效于
     ‘os.statvfs(fd)’。

     *note 可用性: 136f.: Unix。

 -- 函数: os.fsync (fd)

     强制将文件描述符 `fd' 指向的文件写入磁盘。在 Unix，这将调用原生
     ‘fsync()’ 函数；在 Windows，则是 MS ‘_commit()’ 函数。

     如果要写入的是缓冲区内的 Python *note 文件对象: b4a. `f'，请先执行
     ‘f.flush()’，然后执行 ‘os.fsync(f.fileno())’，以确保与 `f' 关联的所
     有内部缓冲区都写入磁盘。

     *note 可用性: 136f.: Unix, Windows。

 -- 函数: os.ftruncate (fd, length)

     截断文件描述符 `fd' 指向的文件，以使其最大为 `length' 字节。从
     Python 3.3 开始，它等效于 ‘os.truncate(fd, length)’。

     引发一个 *note 审计事件: ea1. ‘os.truncate’，附带参数 ‘fd’,
     ‘length’。

     *note 可用性: 136f.: Unix, Windows。

     在 3.5 版更改: 添加了 Windows 支持

 -- 函数: os.get_blocking (fd)

     获取文件描述符的阻塞模式：如果设置了 *note O_NONBLOCK: 72c. 标志位
     ，返回 ‘False’，如果该标志位被清除，返回 ‘True’。

     参见 *note set_blocking(): 72b. 和 *note
     socket.socket.setblocking(): 1f20.。

     *note 可用性: 136f.: Unix。

     3.5 新版功能.

 -- 函数: os.isatty (fd)

     如果文件描述符 `fd' 打开且已连接至 tty 设备（或类 tty 设备），返回
     ‘True’，否则返回 ‘False’。

 -- 函数: os.lockf (fd, cmd, len)

     在打开的文件描述符上，使用、测试或删除 POSIX 锁。`fd' 是一个打开的
     文件描述符。`cmd' 指定要进行的操作，它们是 *note F_LOCK: 1f22.、
     *note F_TLOCK: 1f23.、*note F_ULOCK: 1f24. 或 *note F_TEST: 1f25. 中
     的一个。`len' 指定哪部分文件需要锁定。

     引发一个 *note 审计事件: ea1. ‘os.lockf’，附带参数 ‘fd’、‘cmd’、
     ‘len’。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 数据: os.F_LOCK
 -- 数据: os.F_TLOCK
 -- 数据: os.F_ULOCK
 -- 数据: os.F_TEST

     标志位，用于指定 *note lockf(): a62. 进行哪一种操作。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: os.lseek (fd, pos, how)

     将文件描述符 `fd' 的当前位置设置为 `pos'，位置的计算方式 `how' 如下
     ：设置为 *note SEEK_SET: d9c. 或 ‘0’ 表示从文件开头计算，设置为
     *note SEEK_CUR: d9d. 或 ‘1’ 表示从文件当前位置计算，设置为 *note
     SEEK_END: d9e. 或 ‘2’ 表示文件末尾计算。返回新指针位置，这个位置是
     从文件开头计算的，单位是字节。

 -- 数据: os.SEEK_SET
 -- 数据: os.SEEK_CUR
 -- 数据: os.SEEK_END

     *note lseek(): a66. 函数的参数，它们的值分别为 0、1 和 2。

     3.3 新版功能: 某些操作系统可能支持其他值，例如 ‘os.SEEK_HOLE’ 或
     ‘os.SEEK_DATA’。

 -- 函数: os.open (path, flags, mode=0o777, *, dir_fd=None)

     打开文件 `path'，根据 `flags' 设置各种标志位，并根据 `mode' 设置其
     权限状态。当计算 `mode' 时，会首先根据当前 umask 值将部分权限去除。
     本方法返回新文件的描述符。新的文件描述符是 *note 不可继承: 803. 的
     。

     有关 flag 和 mode 取值的说明，请参见 C 运行时文档。标志位常量（如
     *note O_RDONLY: 1f26. 和 *note O_WRONLY: 1f27.）在 *note os: c5. 模
     块中定义。特别地，在 Windows 上需要添加 *note O_BINARY: 1f28. 才能
     以二进制模式打开文件。

     本函数带有 `dir_fd' 参数，支持 *note 基于目录描述符的相对路径:
     a37.。

     ‘open’ 附带参数 ‘path’、‘mode’、‘flags’ 会引发 *note 审计事件:
     ea1.。

     在 3.4 版更改: 新的文件描述符现在是不可继承的。

          注解: 本函数适用于底层的 I/O。常规用途请使用内置函数 *note
          open(): 4f8.，该函数的 ‘read()’ 和 ‘write()’ 方法（及其他方法
          ）会返回 *note 文件对象: b4a.。要将文件描述符包装在文件对象中
          ，请使用 *note fdopen(): 1441.。

     3.3 新版功能: `dir_fd' 参数。

     在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此函
     数现在会重试系统调用，而不是触发 *note InterruptedError: 662. 异常
     (原因详见 PEP 475(1))。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

以下常量是 *note open(): 66e. 函数 `flags' 参数的选项。可以用按位或运算
符 ‘|’ 将它们组合使用。部分常量并非在所有平台上都可用。有关其可用性和用
法的说明，请参阅 ‘open(2)’ 手册（Unix 上）或 MSDN(2) （Windows 上）。

 -- 数据: os.O_RDONLY
 -- 数据: os.O_WRONLY
 -- 数据: os.O_RDWR
 -- 数据: os.O_APPEND
 -- 数据: os.O_CREAT
 -- 数据: os.O_EXCL
 -- 数据: os.O_TRUNC

     上述常量在 Unix 和 Windows 上均可用。

 -- 数据: os.O_DSYNC
 -- 数据: os.O_RSYNC
 -- 数据: os.O_SYNC
 -- 数据: os.O_NDELAY
 -- 数据: os.O_NONBLOCK
 -- 数据: os.O_NOCTTY
 -- 数据: os.O_CLOEXEC

     这个常数仅在 Unix 系统中可用。

     在 3.3 版更改: 增加 *note O_CLOEXEC: 9cb. 常量。

 -- 数据: os.O_BINARY
 -- 数据: os.O_NOINHERIT
 -- 数据: os.O_SHORT_LIVED
 -- 数据: os.O_TEMPORARY
 -- 数据: os.O_RANDOM
 -- 数据: os.O_SEQUENTIAL
 -- 数据: os.O_TEXT

     这个常数仅在 Windows 系统中可用。

 -- 数据: os.O_ASYNC
 -- 数据: os.O_DIRECT
 -- 数据: os.O_DIRECTORY
 -- 数据: os.O_NOFOLLOW
 -- 数据: os.O_NOATIME
 -- 数据: os.O_PATH
 -- 数据: os.O_TMPFILE
 -- 数据: os.O_SHLOCK
 -- 数据: os.O_EXLOCK

     上述常量是扩展常量，如果 C 库未定义它们，则不存在。

     在 3.4 版更改: 在支持的系统上增加 *note O_PATH: 88c.。增加 *note
     O_TMPFILE: 88d.，仅在 Linux Kernel 3.11 或更高版本可用。

 -- 函数: os.openpty ()

     打开一对新的伪终端，返回一对文件描述符 ‘（主，从）’，分别为 pty 和
     tty。新的文件描述符是 *note 不可继承: 803. 的。对于（稍微）轻量一些
     的方法，请使用 *note pty: d6. 模块。

     *note 可用性: 136f.: 某些 Unix。

     在 3.4 版更改: 新的文件描述符不再可继承。

 -- 函数: os.pipe ()

     创建一个管道，返回一对分别用于读取和写入的文件描述符 ‘(r, w)’。新的
     文件描述符是 *note 不可继承: 803. 的。

     *note 可用性: 136f.: Unix, Windows。

     在 3.4 版更改: 新的文件描述符不再可继承。

 -- 函数: os.pipe2 (flags)

     创建带有 `flags' 标志位的管道。可通过对以下一个或多个值进行“或”运算
     来构造这些 `flags'：*note O_NONBLOCK: 72c.、*note O_CLOEXEC: 9cb.。
     返回一对分别用于读取和写入的文件描述符 ‘(r, w)’。

     *note 可用性: 136f.: 某些 Unix。

     3.3 新版功能.

 -- 函数: os.posix_fallocate (fd, offset, len)

     确保为 `fd' 指向的文件分配了足够的磁盘空间，该空间从偏移量 `offset'
     开始，到 `len' 字节为止。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: os.posix_fadvise (fd, offset, len, advice)

     声明即将以特定模式访问数据，使内核可以提前进行优化。数据范围是从
     `fd' 所指向文件的 `offset' 开始，持续 `len' 个字节。`advice' 的取值
     是如下之一：*note POSIX_FADV_NORMAL: 1f3e, *note
     POSIX_FADV_SEQUENTIAL: 1f3f, *note POSIX_FADV_RANDOM: 1f40, *note
     POSIX_FADV_NOREUSE: 1f41, *note POSIX_FADV_WILLNEED: 1f42. 或 *note
     POSIX_FADV_DONTNEED: 1f43.。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 数据: os.POSIX_FADV_NORMAL
 -- 数据: os.POSIX_FADV_SEQUENTIAL
 -- 数据: os.POSIX_FADV_RANDOM
 -- 数据: os.POSIX_FADV_NOREUSE
 -- 数据: os.POSIX_FADV_WILLNEED
 -- 数据: os.POSIX_FADV_DONTNEED

     用于 *note posix_fadvise(): 66f. 的 `advice' 参数的标志位，指定可能
     使用的访问模式。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: os.pread (fd, n, offset)

     从文件描述符 `fd' 所指向文件的偏移位置 `offset' 开始，读取至多 `n'
     个字节，而保持文件偏移量不变。

     返回所读取字节的字节串 (bytestring)。如果到达了 `fd' 指向的文件末尾
     ，则返回空字节对象。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: os.preadv (fd, buffers, offset, flags=0)

     从文件描述符 `fd' 所指向文件的偏移位置 `offset' 开始，将数据读取至
     可变 *note 字节类对象: 5f1. 缓冲区 `buffers' 中，保持文件偏移量不变
     。将数据依次存放到每个缓冲区中，填满一个后继续存放到序列中的下一个
     缓冲区，来保存其余数据。

     flags 参数可以由零个或多个标志位进行按位或运算来得到：

        - *note RWF_HIPRI: 1f44.

        - *note RWF_NOWAIT: 1f45.

     返回实际读取的字节总数，该总数可以小于所有对象的总容量。

     操作系统可能对允许使用的缓冲区数量有限制（使用 *note sysconf():
     1f46. 获取 ‘'SC_IOV_MAX'’ 值）。

     本方法结合了 *note os.readv(): 3c0. 和 *note os.pread(): 3c1. 的功
     能。

     *note 可用性: 136f.：Linux 2.6.30 或更高版本，FreeBSD 6.0 或更高版
     本，OpenBSD 2.7 或更高版本。使用标志位需要 Linux 4.6 或更高版本。

     3.7 新版功能.

 -- 数据: os.RWF_NOWAIT

     不要等待无法立即获得的数据。如果指定了此标志，那么当需要从后备存储
     器中读取数据，或等待文件锁时，系统调用将立即返回。

     如果成功读取数据，则返回读取的字节数。如果未读取到数据，则返回
     ‘-1’，并将错误码 errno 置为 *note errno.EAGAIN: 1f47.。

     *note 可用性: 136f.：Linux 4.14 或更高版本。

     3.7 新版功能.

 -- 数据: os.RWF_HIPRI

     高优先级读/写。允许基于块的文件系统对设备进行轮询，这样可以降低延迟
     ，但可能会占用更多资源。

     目前在 Linux 上，此功能仅在使用 *note O_DIRECT: 1f39. 标志打开的文
     件描述符上可用。

     *note 可用性: 136f.：Linux 4.6 或更高版本。

     3.7 新版功能.

 -- 函数: os.pwrite (fd, str, offset)

     将 `str' 中的字节串 (bytestring) 写入文件描述符 `fd' 的偏移位置
     `offset' 处，保持文件偏移量不变。

     返回实际写入的字节数。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: os.pwritev (fd, buffers, offset, flags=0)

     将缓冲区 `buffers' 的内容写入文件描述符 `fd' 的偏移位置 `offset' 处
     ，保持文件偏移量不变。缓冲区 `buffers' 必须是由 *note 字节类对象:
     5f1. 组成的序列。缓冲区以数组顺序处理。先写入第一个缓冲区的全部内容
     ，再写入第二个缓冲区，照此继续。

     flags 参数可以由零个或多个标志位进行按位或运算来得到：

        - *note RWF_DSYNC: 1f48.

        - *note RWF_SYNC: 1f49.

     返回实际写入的字节总数。

     操作系统可能对允许使用的缓冲区数量有限制（使用 *note sysconf():
     1f46. 获取 ‘'SC_IOV_MAX'’ 值）。

     本方法结合了 *note os.writev(): 3c3. 和 *note os.pwrite(): 3c4. 的
     功能。

     *note 可用性: 136f.：Linux 2.6.30 或更高版本，FreeBSD 6.0 或更高版
     本，OpenBSD 2.7 或更高版本。使用标志位需要 Linux 4.7 或更高版本。

     3.7 新版功能.

 -- 数据: os.RWF_DSYNC

     提供立即写入功能，等效于 *note O_DSYNC: 1f2d. ‘open(2)’ 标志。该标
     志仅作用于系统调用写入的数据。

     *note 可用性: 136f.：Linux 4.7 或更高版本。

     3.7 新版功能.

 -- 数据: os.RWF_SYNC

     提供立即写入功能，等效于 *note O_SYNC: 1f2f. ‘open(2)’ 标志。该标志
     仅作用于系统调用写入的数据。

     *note 可用性: 136f.：Linux 4.7 或更高版本。

     3.7 新版功能.

 -- 函数: os.read (fd, n)

     从文件描述符 `fd' 中读取至多 `n' 个字节。

     返回所读取字节的字节串 (bytestring)。如果到达了 `fd' 指向的文件末尾
     ，则返回空字节对象。

          注解: 该功能适用于低级 I/O 操作，必须用于 *note os.open():
          66e. 或 *note pipe(): 1f1a. 返回的文件描述符。若要读取由内建函
          数 *note open(): 4f8.、*note popen(): 2aa.、*note fdopen():
          1441. 或 *note sys.stdin: 316. 返回的 "文件对象"，则应使用其相
          应的 ‘read()’ 或 ‘readline()’ 方法。

     在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此函
     数现在会重试系统调用，而不是触发 *note InterruptedError: 662. 异常
     (原因详见 PEP 475(3))。

 -- 函数: os.sendfile (out, in, offset, count)

 -- 函数: os.sendfile (out, in, offset, count[, headers][, trailers],
          flags=0)

     将文件描述符 `in' 中的 `count' 字节复制到文件描述符 `out' 的偏移位
     置 `offset' 处。返回复制的字节数，如果到达 EOF，返回 0。

     定义了 *note sendfile(): 362. 的所有平台均支持第一种函数用法。

     在 Linux 上，将 `offset' 设置为 ‘None’，则从 `in' 的当前位置开始读
     取，并更新 `in' 的位置。

     第二种函数用法可以在 Mac OS X 和 FreeBSD 上使用，其中，`headers' 和
     `trailers' 是任意的缓冲区序列，它们分别在写入 `in' 的数据前、后被写
     入。返回值与第一种用法相同。

     在 Mac OS X 和 FreeBSD 上，将 `count' 设为 0 表示持续复制直到 `in'
     的结尾。

     所有平台都支持将套接字作为 `out' 文件描述符，有些平台也支持其他类型
     （如常规文件或管道）。

     跨平台应用程序不应使用 `headers'、`trailers' 和 `flags' 参数。

     *note 可用性: 136f.: Unix。

          注解: 有关 *note sendfile(): 362. 的高级封装，参见 *note
          socket.socket.sendfile(): 753.。

     3.3 新版功能.

 -- 函数: os.set_blocking (fd, blocking)

     设置指定文件描述符的阻塞模式：如果 blocking 为 ‘False’，则为该描述
     符设置 *note O_NONBLOCK: 72c. 标志位，反之则清除该标志位。

     参见 *note get_blocking(): 72a. 和 *note
     socket.socket.setblocking(): 1f20.。

     *note 可用性: 136f.: Unix。

     3.5 新版功能.

 -- 数据: os.SF_NODISKIO
 -- 数据: os.SF_MNOWAIT
 -- 数据: os.SF_SYNC

     *note sendfile(): 362. 函数的参数（假设当前实现支持这些参数）。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: os.readv (fd, buffers)

     从文件描述符 `fd' 将数据读取至多个可变的 *note 字节类对象: 5f1. 缓
     冲区 `buffers' 中。将数据依次存放到每个缓冲区中，填满一个后继续存放
     到序列中的下一个缓冲区，来保存其余数据。

     返回实际读取的字节总数，该总数可以小于所有对象的总容量。

     操作系统可能对允许使用的缓冲区数量有限制（使用 *note sysconf():
     1f46. 获取 ‘'SC_IOV_MAX'’ 值）。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: os.tcgetpgrp (fd)

     返回与 `fd' 指定的终端相关联的进程组（`fd' 是由 *note os.open():
     66e. 返回的已打开的文件描述符）。

     *note 可用性: 136f.: Unix。

 -- 函数: os.tcsetpgrp (fd, pg)

     设置与 `fd' 指定的终端相关联的进程组为 `pg*（*fd' 是由 *note
     os.open(): 66e. 返回的已打开的文件描述符）。

     *note 可用性: 136f.: Unix。

 -- 函数: os.ttyname (fd)

     返回一个字符串，该字符串表示与文件描述符 `fd' 关联的终端。如果 `fd'
     没有与终端关联，则抛出异常。

     *note 可用性: 136f.: Unix。

 -- 函数: os.write (fd, str)

     将 `str' 中的字节串 (bytestring) 写入文件描述符 `fd'。

     返回实际写入的字节数。

          注解: 该功能适用于低级 I/O 操作，必须用于 *note os.open():
          66e. 或 *note pipe(): 1f1a. 返回的文件描述符。若要写入由内建函
          数 *note open(): 4f8.、*note popen(): 2aa.、*note fdopen():
          1441.、*note sys.stdout: 317. 或 *note sys.stderr: 318. 返回的
          "文件对象"，则应使用其相应的 ‘write()’ 方法。

     在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此函
     数现在会重试系统调用，而不是触发 *note InterruptedError: 662. 异常
     (原因详见 PEP 475(4))。

 -- 函数: os.writev (fd, buffers)

     将缓冲区 `buffers' 的内容写入文件描述符 `fd'。缓冲区 `buffers' 必须
     是由 *note 字节类对象: 5f1. 组成的序列。缓冲区以数组顺序处理。先写
     入第一个缓冲区的全部内容，再写入第二个缓冲区，照此继续。

     返回实际写入的字节总数。

     操作系统可能对允许使用的缓冲区数量有限制（使用 *note sysconf():
     1f46. 获取 ‘'SC_IOV_MAX'’ 值）。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

* Menu:

* 查询终端的尺寸::
* 文件描述符的继承::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475

   (2) https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx

   (3) https://www.python.org/dev/peps/pep-0475

   (4) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: 查询终端的尺寸,  Next: 文件描述符的继承,  Up: 文件描述符操作

5.16.1.5 查询终端的尺寸
.......................

3.3 新版功能.

 -- 函数: os.get_terminal_size (fd=STDOUT_FILENO)

     返回终端窗口的尺寸，格式为 ‘(columns, lines)’，它是类型为 *note
     terminal_size: 1cad. 的元组。

     可选参数 ‘fd’ （默认为 ‘STDOUT_FILENO’ 或标准输出）指定应查询的文件
     描述符。

     如果文件描述符未连接到终端，则抛出 *note OSError: 1d4. 异常。

     *note shutil.get_terminal_size(): a52. 是供常规使用的高阶函数，
     ‘os.get_terminal_size’ 是其底层的实现。

     *note 可用性: 136f.: Unix, Windows。

 -- 类: os.terminal_size

     元组的子类，存储终端窗口尺寸 ‘(columns, lines)’。

      -- 属性: columns

          终端窗口的宽度，单位为字符。

      -- 属性: lines

          终端窗口的高度，单位为字符。


File: python.info,  Node: 文件描述符的继承,  Prev: 查询终端的尺寸,  Up: 文件描述符操作

5.16.1.6 文件描述符的继承
.........................

3.4 新版功能.

每个文件描述符都有一个 "inheritable"（可继承）标志位，该标志位控制了文件
描述符是否可以由子进程继承。从 Python 3.4 开始，由 Python 创建的文件描述
符默认是不可继承的。

在 UNIX 上，执行新程序时，不可继承的文件描述符在子进程中是关闭的，其他文
件描述符将被继承。

在 Windows 上，不可继承的句柄和文件描述符在子进程中是关闭的，但标准流（
文件描述符 0、1 和 2 即标准输入、标准输出和标准错误）是始终继承的。如果
使用 *note spawn*: 1f55. 函数，所有可继承的句柄和文件描述符都将被继承。
如果使用 *note subprocess: fa. 模块，将关闭除标准流以外的所有文件描述符
，并且仅当 `close_fds' 参数为 ‘False’ 时才继承可继承的句柄。

 -- 函数: os.get_inheritable (fd)

     获取指定文件描述符的“可继承”标志位（为布尔值）。

 -- 函数: os.set_inheritable (fd, inheritable)

     设置指定文件描述符的“可继承”标志位。

 -- 函数: os.get_handle_inheritable (handle)

     获取指定句柄的“可继承”标志位（为布尔值）。

     *note 可用性: 136f.: Windows。

 -- 函数: os.set_handle_inheritable (handle, inheritable)

     设置指定句柄的“可继承”标志位。

     *note 可用性: 136f.: Windows。


File: python.info,  Node: 文件和目录,  Next: 进程管理,  Prev: 文件描述符操作,  Up: os --- 多种操作系统接口

5.16.1.7 文件和目录
...................

在某些 Unix 平台上，许多函数支持以下一项或多项功能：

   * `指定文件描述符为参数：' 通常在 *note os: c5. 模块中提供给函数的
     `path' 参数必须是表示文件路径的字符串，但是，某些函数现在可以接受其
     `path' 参数为打开文件描述符，该函数将对描述符指向的文件进行操作。（
     对于 POSIX 系统，Python 将调用以 ‘f’ 开头的函数变体（如调用
     ‘fchdir’ 而不是 ‘chdir’）。）

     可以用 *note os.supports_fd: a4c. 检查某个函数在你的平台上是否支持
     将 `path' 参数指定为文件描述符。如果不支持，使用该功能将抛出 *note
     NotImplementedError: 617. 异常。

     如果该函数还支持 `dir_fd' 或 `follow_symlinks' 参数，那么用文件描述
     符作为 `path' 后就不能再指定上述参数了。

   * `基于目录描述符的相对路径：' 如果 `dir_fd' 不是 ‘None’，它就应该是
     一个指向目录的文件描述符，这时待操作的 path 应该是相对路径，相对路
     径是相对于前述目录的。如果 path 是绝对路径，则 `dir_fd' 将被忽略。
     （对于 POSIX 系统，Python 将调用该函数的变体，变体以 ‘at’ 结尾，可
     能以 ‘f’ 开头（如调用 ‘faccessat’ 而不是 ‘access’）。

     可以用 *note os.supports_dir_fd: a46. 检查某个函数在你的平台上是否
     支持 `dir_fd'。如果不支持，使用该功能将抛出 *note
     NotImplementedError: 617. 异常。

   * `不跟踪符号链接：' 如果 `follow_symlinks' 为 ‘False’，并且待操作路
     径的最后一个元素是符号链接，则该函数将在符号链接本身而不是链接所指
     向的文件上操作。（对于 POSIX 系统，Python 将调用该函数的 ‘l...’ 变
     体。）

     可以用 *note os.supports_follow_symlinks: 1c98. 检查某个函数在你的
     平台上是否支持 `follow_symlinks'。如果不支持，使用该功能将抛出
     *note NotImplementedError: 617. 异常。

 -- 函数: os.access (path, mode, *, dir_fd=None, effective_ids=False,
          follow_symlinks=True)

     使用 实际用户ID/用户组ID 测试对 `path' 的访问。请注意，大多数测试操
     作将使用 有效用户ID/用户组ID，因此可以在 suid/sgid 环境中运用此例程
     ，来测试调用用户是否具有对 `path' 的指定访问权限。`mode' 为 *note
     F_OK: 1f57. 时用于测试 `path' 是否存在，也可以对 *note R_OK: 1f58.、
     *note W_OK: 1f59. 和 *note X_OK: 1f5a. 中的一个或多个进行“或”运算来
     测试指定权限。允许访问则返回 *note True: 4a1.，否则返回 *note
     False: 390.。更多信息请参见 Unix 手册页 ‘access(2)’。

     本函数支持指定 *note 基于目录描述符的相对路径: a37. 和 *note
     不跟踪符号链接: a38.。

     如果 `effective_ids' 为 ‘True’，*note access(): a39. 将使用 有效用
     户ID/用户组ID 而非 实际用户ID/用户组ID 进行访问检查。您的平台可能不
     支持 `effective_ids'，您可以使用 *note os.supports_effective_ids:
     a4d. 检查它是否可用。如果不可用，使用它时会抛出 *note
     NotImplementedError: 617. 异常。

          注解: 使用 *note access(): a39. 来检查用户是否具有某项权限（如
          打开文件的权限），然后再使用 *note open(): 4f8. 打开文件，这样
          做存在一个安全漏洞，因为用户可能会在检查和打开文件之间的时间里
          做其他操作。推荐使用 *note EAFP: 1f5b. 技术。如:

               if os.access("myfile", os.R_OK):
                   with open("myfile") as fp:
                       return fp.read()
               return "some default data"

          最好写成:

               try:
                   fp = open("myfile")
               except PermissionError:
                   return "some default data"
               else:
                   with fp:
                       return fp.read()

          注解: 即使 *note access(): a39. 指示 I/O 操作会成功，但实际操
          作仍可能失败，尤其是对网络文件系统的操作，其权限语义可能超出常
          规的 POSIX 权限位模型。

     在 3.3 版更改: 添加 `dir_fd'、`effective_ids' 和 `follow_symlinks'
     参数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 数据: os.F_OK
 -- 数据: os.R_OK
 -- 数据: os.W_OK
 -- 数据: os.X_OK

     作为 *note access(): a39. 的 `mode' 参数的可选值，分别测试 `path' 的
     存在性、可读性、可写性和可执行性。

 -- 函数: os.chdir (path)

     将当前工作目录更改为 `path'。

     本函数支持 *note 指定文件描述符为参数: 3bd.。其中，描述符必须指向打
     开的目录，不能是打开的文件。

     本函数可以抛出 *note OSError: 1d4. 及其子类的异常，如 *note
     FileNotFoundError: 7c9.、*note PermissionError: 608. 和 *note
     NotADirectoryError: 9a2. 异常。

     引发一个 *note 审计事件: ea1. ‘os.chdir’，附带参数 ‘path’。

     3.3 新版功能: 在某些平台上新增支持将 `path' 参数指定为文件描述符。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.chflags (path, flags, *, follow_symlinks=True)

     将 `path' 的 flags 设置为其他由数字表示的 `flags'。`flags' 可以用以
     下值按位或组合起来（以下值在 *note stat: f5. 模块中定义）：

        * *note stat.UF_NODUMP: 1c3e.

        * *note stat.UF_IMMUTABLE: 1c3f.

        * *note stat.UF_APPEND: 1c40.

        * *note stat.UF_OPAQUE: 1c41.

        * *note stat.UF_NOUNLINK: 1c42.

        * *note stat.UF_COMPRESSED: 1c43.

        * *note stat.UF_HIDDEN: 1c44.

        * *note stat.SF_ARCHIVED: 1c45.

        * *note stat.SF_IMMUTABLE: 1c46.

        * *note stat.SF_APPEND: 1c47.

        * *note stat.SF_NOUNLINK: 1c48.

        * *note stat.SF_SNAPSHOT: 1c49.

     本函数支持 *note 不跟踪符号链接: a38.。

     引发一个 *note 审计事件: ea1. ‘os.chflags’，附带参数 ‘path’、
     ‘flags’。

     *note 可用性: 136f.: Unix。

     3.3 新版功能: `follow_symlinks' 参数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.chmod (path, mode, *, dir_fd=None, follow_symlinks=True)

     将 `path' 的 mode 更改为其他由数字表示的 `mode'。`mode' 可以用以下
     值之一，也可以将它们按位或组合起来（以下值在 *note stat: f5. 模块中
     定义）：

        * *note stat.S_ISUID: 1c2b.

        * *note stat.S_ISGID: 1c2c.

        * *note stat.S_ENFMT: 1c2e.

        * *note stat.S_ISVTX: 1c2f.

        * *note stat.S_IREAD: 1c3b.

        * *note stat.S_IWRITE: 1c3c.

        * *note stat.S_IEXEC: 1c3d.

        * *note stat.S_IRWXU: 1c30.

        * *note stat.S_IRUSR: 1c31.

        * *note stat.S_IWUSR: 1c32.

        * *note stat.S_IXUSR: 1c33.

        * *note stat.S_IRWXG: 1c34.

        * *note stat.S_IRGRP: 1c35.

        * *note stat.S_IWGRP: 1c36.

        * *note stat.S_IXGRP: 1c2d.

        * *note stat.S_IRWXO: 1c37.

        * *note stat.S_IROTH: 1c38.

        * *note stat.S_IWOTH: 1c39.

        * *note stat.S_IXOTH: 1c3a.

     本函数支持 *note 指定文件描述符: 3bd.、*note
     指定基于目录描述符的相对路径: a37. 和 *note 不跟踪符号链接: a38.。

          注解: 尽管 Windows 支持 *note chmod(): a3b.，但只能用它设置文
          件的只读标志（‘stat.S_IWRITE’ 和 ‘stat.S_IREAD’ 常量或对应的整
          数值）。所有其他标志位都会被忽略。

     引发一个 *note 审计事件: ea1. ‘os.chmod’，附带参数 ‘path’、‘mode’、
     ‘dir_fd’。

     3.3 新版功能: 添加了指定 `path' 为文件描述符的支持，以及 `dir_fd' 和
     `follow_symlinks' 参数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.chown (path, uid, gid, *, dir_fd=None,
          follow_symlinks=True)

     将 `path' 的用户和组 ID 分别修改为数字形式的 `uid' 和 `gid'。若要使
     其中某个 ID 保持不变，请将其置为 -1。

     本函数支持 *note 指定文件描述符: 3bd.、*note
     指定基于目录描述符的相对路径: a37. 和 *note 不跟踪符号链接: a38.。

     参见更高阶的函数 *note shutil.chown(): a7e.，除了数字 ID 之外，它也
     接受名称。

     引发一个 *note 审计事件: ea1. ‘os.chown’，附带参数 ‘path’、‘uid’、
     ‘gid’、‘dir_fd’。

     *note 可用性: 136f.: Unix。

     3.3 新版功能: 添加了指定 `path' 为文件描述符的支持，以及 `dir_fd' 和
     `follow_symlinks' 参数。

     在 3.6 版更改: 支持 *note 类路径对象: 373.。

 -- 函数: os.chroot (path)

     将当前进程的根目录更改为 `path'。

     *note 可用性: 136f.: Unix。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.fchdir (fd)

     将当前工作目录更改为文件描述符 `fd' 指向的目录。fd 必须指向打开的目
     录而非文件。从 Python 3.3 开始，它等效于 ‘os.chdir(fd)’。

     引发一个 *note 审计事件: ea1. ‘os.chdir’，附带参数 ‘path’。

     *note 可用性: 136f.: Unix。

 -- 函数: os.getcwd ()

     返回表示当前工作目录的字符串。

 -- 函数: os.getcwdb ()

     返回表示当前工作目录的字节串 (bytestring)。

     在 3.8 版更改: 在 Windows 上，本函数现在会使用 UTF-8 编码格式而不是
     ANSI 代码页：请参看 PEP 529(1) 了解具体原因。 该函数在 Windows 上不
     再被弃用。

 -- 函数: os.lchflags (path, flags)

     将 `path' 的 flags 设置为其他由数字表示的 `flags'，与 *note
     chflags(): a3a. 类似，但不跟踪符号链接。从 Python 3.3 开始，它等效
     于 ‘os.chflags(path, flags, follow_symlinks=False)’。

     引发一个 *note 审计事件: ea1. ‘os.chflags’，附带参数 ‘path’、
     ‘flags’。

     *note 可用性: 136f.: Unix。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.lchmod (path, mode)

     将 `path' 的权限状态修改为 `mode'。如果 path 是符号链接，则影响符号
     链接本身而非链接目标。可以参考 *note chmod(): a3b. 中列出 `mode' 的
     可用值。从 Python 3.3 开始，它等效于 ‘os.chmod(path, mode,
     follow_symlinks=False)’。

     引发一个 *note 审计事件: ea1. ‘os.chmod’，附带参数 ‘path’、‘mode’、
     ‘dir_fd’。

     *note 可用性: 136f.: Unix。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.lchown (path, uid, gid)

     将 `path' 的用户和组 ID 分别修改为数字形式的 `uid' 和 `gid'，本函数
     不跟踪符号链接。从 Python 3.3 开始，它等效于 ‘os.chown(path, uid,
     gid, follow_symlinks=False)’。

     引发一个 *note 审计事件: ea1. ‘os.chown’，附带参数 ‘path’、‘uid’、
     ‘gid’、‘dir_fd’。

     *note 可用性: 136f.: Unix。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.link (src, dst, *, src_dir_fd=None, dst_dir_fd=None,
          follow_symlinks=True)

     创建一个指向 `src' 的硬链接，名为 `dst'。

     本函数支持将 `src_dir_fd' 和 `dst_dir_fd' 中的一个或两个指定为
     *note 基于目录描述符的相对路径: a37.，支持 *note 不跟踪符号链接:
     a38.。

     引发一个 *note 审计事件: ea1. ‘os.link’ 附带参数 ‘src’、‘dst’、
     ‘src_dir_fd’、‘dst_dir_fd’。

     *note 可用性: 136f.: Unix, Windows。

     在 3.2 版更改: 添加了对 Windows 的支持。

     3.3 新版功能: 添加 `src_dir_fd'、`dst_dir_fd' 和 `follow_symlinks'
     参数。

     在 3.6 版更改: 接受一个 *note 类路径对象: 373. 作为 `src' 和 `dst'。

 -- 函数: os.listdir (path='.')

     返回一个包含由 `path' 指定目录中条目名称组成的列表。 该列表按任意顺
     序排列，并且不包括特殊条目 ‘'.'’ 和 ‘'..'’，即使它们存在于目录中。
     如果有文件在调用此函数期间在被移除或添加到目录中，是否要包括该文件
     的名称并没有规定。

     `path' 可以是 *note 类路径对象: 373.。如果 `path' 是（直接传入或通
     过 *note PathLike: 4f3. 接口间接传入） ‘bytes’ 类型，则返回的文件名
     也将是 ‘bytes’ 类型，其他情况下是 ‘str’ 类型。

     本函数也支持 *note 指定文件描述符为参数: 3bd.，其中描述符必须指向目
     录。

     引发一个 *note 审计事件: ea1. ‘os.listdir’，附带参数 ‘path’。

          注解: 要将 ‘str’ 类型的文件名编码为 ‘bytes’，请使用 *note
          fsencode(): 4f7.。

     参见
     ....

     *note scandir(): 260. 函数返回目录内文件名的同时，也返回文件属性信
     息，它在某些具体情况下能提供更好的性能。

     在 3.2 版更改: `path' 变为可选参数。

     3.3 新版功能: 新增支持将 `path' 参数指定为打开的文件描述符。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.lstat (path, *, dir_fd=None)

     在给定路径上执行本函数，其操作相当于 ‘lstat()’ 系统调用，类似于
     *note stat(): 1f2. 但不跟踪符号链接。返回值是 *note stat_result:
     109a. 对象。

     在不支持符号链接的平台上，本函数是 *note stat(): 1f2. 的别名。

     从 Python 3.3 起，此功能等价于 ‘os.stat(path, dir_fd=dir_fd,
     follow_symlinks=False)’。

     本函数支持 *note 基于目录描述符的相对路径: a37.。

     参见
     ....

     *note stat(): 1f2. 函数。

     在 3.2 版更改: 添加对 Windows 6.0 (Vista) 符号链接的支持。

     在 3.3 版更改: 添加了 `dir_fd' 参数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

     在 3.8 版更改: 目前在 Windows 上，遇到表示另一个路径的重解析点（即
     名称代理，包括符号链接和目录结点），本函数将打开它。其他种类的重解
     析点由 *note stat(): 1f2. 交由操作系统解析。

 -- 函数: os.mkdir (path, mode=0o777, *, dir_fd=None)

     创建一个名为 `path' 的目录，应用以数字表示的权限模式 `mode'。

     如果目录已存在，则抛出 *note FileExistsError: 960. 异常。 某些系统
     会忽略 `mode'。如果没有忽略它，那么将首先从它中减去当前的 umask 值
     。如果除最后 9 位（即 `mode' 八进制的最后 3 位）之外，还设置了其他
     位，则其他位的含义取决于各个平台。在某些平台上，它们会被忽略，应显
     式调用 *note chmod(): a3b. 进行设置。

     本函数支持 *note 基于目录描述符的相对路径: a37.。

     如果需要创建临时目录，请参阅 *note tempfile: 104. 模块中的 *note
     tempfile.mkdtemp(): 1c79. 函数。

     引发一个 *note 审计事件: ea1. ‘os.mkdir’，附带参数 ‘path’、‘mode’、
     ‘dir_fd’。

     3.3 新版功能: `dir_fd' 参数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.makedirs (name, mode=0o777, exist_ok=False)

     递归目录创建函数。与 *note mkdir(): a3e. 类似，但会自动创建到达最后
     一级目录所需要的中间目录。

     `mode' 参数会传递给 *note mkdir(): a3e.，用来创建最后一级目录，对于
     该参数的解释，请参阅 *note mkdir() 中的描述: 1f5e.。要设置某些新建
     的父目录的权限，可以在调用 *note makedirs(): 3c5. 之前设置 umask。
     现有父目录的权限不会更改。

     如果 `exist_ok' 为 ‘False’ (默认值)，则如果目标目录已存在将引发
     *note FileExistsError: 960.。

          注解: 如果要创建的路径元素包含 *note pardir: 1f5f. (如 UNIX 系
          统中的 "..")  *note makedirs(): 3c5. 将无法明确目标。

     本函数能正确处理 UNC 路径。

     引发一个 *note 审计事件: ea1. ‘os.mkdir’，附带参数 ‘path’、‘mode’、
     ‘dir_fd’。

     3.2 新版功能: `exist_ok' 参数。

     在 3.4.1 版更改: 在 Python 3.4.1 以前，如果 `exist_ok' 为 ‘True’，
     且目录已存在，且 `mode' 与现有目录的权限不匹配，*note makedirs():
     3c5. 仍会抛出错误。由于无法安全地实现此行为，因此在 Python 3.4.1 中
     将该行为删除。请参阅 bpo-21082(2)。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

     在 3.7 版更改: `mode' 参数不再影响新创建的中间目录的权限。

 -- 函数: os.mkfifo (path, mode=0o666, *, dir_fd=None)

     创建一个名为 `path' 的 FIFO（命名管道，一种先进先出队列），具有以数
     字表示的权限状态 `mode'。将从 mode 中首先减去当前的 umask 值。

     本函数支持 *note 基于目录描述符的相对路径: a37.。

     FIFO 是可以像常规文件一样访问的管道。FIFO 如果没有被删除（如使用
     *note os.unlink(): a44.），会一直存在。通常，FIFO 用作“客户端”和“服
     务器”进程之间的汇合点：服务器打开 FIFO 进行读取，而客户端打开 FIFO
     进行写入。请注意，*note mkfifo(): 66c. 不会打开 FIFO — 它只是创建汇
     合点。

     *note 可用性: 136f.: Unix。

     3.3 新版功能: `dir_fd' 参数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.mknod (path, mode=0o600, device=0, *, dir_fd=None)

     创建一个名为 `path' 的文件系统节点（文件，设备专用文件或命名管道）
     。`mode' 指定权限和节点类型，方法是将权限与下列节点类型
     ‘stat.S_IFREG’、‘stat.S_IFCHR’、‘stat.S_IFBLK’ 和 ‘stat.S_IFIFO’ 之
     一（按位或）组合（这些常量可以在 *note stat: f5. 模块中找到）。对于
     ‘stat.S_IFCHR’ 和 ‘stat.S_IFBLK’，`device' 参数指定了新创建的设备专
     用文件（可能会用到 *note os.makedev(): 1f60.），否则该参数将被忽略
     。

     本函数支持 *note 基于目录描述符的相对路径: a37.。

     *note 可用性: 136f.: Unix。

     3.3 新版功能: `dir_fd' 参数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.major (device)

     提取主设备号，提取自原始设备号（通常是 ‘stat’ 中的 ‘st_dev’ 或
     ‘st_rdev’ 字段）。

 -- 函数: os.minor (device)

     提取次设备号，提取自原始设备号（通常是 ‘stat’ 中的 ‘st_dev’ 或
     ‘st_rdev’ 字段）。

 -- 函数: os.makedev (major, minor)

     将主设备号和次设备号组合成原始设备号。

 -- 函数: os.pathconf (path, name)

     返回所给名称的文件有关的系统配置信息。`name' 指定要查找的配置名称，
     它可以是字符串，是一个系统已定义的名称，这些名称定义在不同标准（
     POSIX.1，Unix 95，Unix 98 等）中。一些平台还定义了额外的其他名称。
     当前操作系统已定义的名称在 ‘pathconf_names’ 字典中给出。对于未包含
     在该映射中的配置名称，也可以传递一个整数作为 `name'。

     如果 `name' 是一个字符串且不是已定义的名称，将抛出 *note
     ValueError: 1fc. 异常。如果当前系统不支持 `name' 指定的配置名称，即
     使该名称存在于 ‘pathconf_names’，也会抛出 *note OSError: 1d4. 异常
     ，错误码为 *note errno.EINVAL: fd9.。

     本函数支持 *note 指定文件描述符为参数: 3bd.。

     *note 可用性: 136f.: Unix。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 数据: os.pathconf_names

     字典，表示映射关系，为 *note pathconf(): a4a. 和 *note fpathconf():
     1f1f. 可接受名称与操作系统为这些名称定义的整数值之间的映射。这可用
     于判断系统已定义了哪些名称。

     *note 可用性: 136f.: Unix。

 -- 函数: os.readlink (path, *, dir_fd=None)

     返回一个字符串，为符号链接指向的实际路径。其结果可以是绝对或相对路
     径。如果是相对路径，则可用 ‘os.path.join(os.path.dirname(path),
     result)’ 转换为绝对路径。

     如果 `path' 是字符串对象（直接传入或通过 *note PathLike: 4f3. 接口
     间接传入），则结果也将是字符串对象，且此类调用可能会引发
     UnicodeDecodeError。如果 `path' 是字节对象（直接传入或间接传入），
     则结果将会是字节对象。

     本函数支持 *note 基于目录描述符的相对路径: a37.。

     当尝试解析的路径可能含有链接时，请改用 *note realpath(): 200. 以正
     确处理递归和平台差异。

     *note 可用性: 136f.: Unix, Windows。

     在 3.2 版更改: 添加对 Windows 6.0 (Vista) 符号链接的支持。

     3.3 新版功能: `dir_fd' 参数。

     在 3.6 版更改: 在 Unix 上可以接受一个 *note 类路径对象: 373.。

     在 3.8 版更改: 在 Windows 上接受 *note 类路径对象: 373. 和字节对象
     。

     在 3.8 版更改: 增加了对目录链接的支持，且返回值改为了“替换路径”的形
     式（通常带有 ‘\\?\’ 前缀），而不是先前那样返回可选的 "print name" 字
     段。

 -- 函数: os.remove (path, *, dir_fd=None)

     移除（删除）文件 `path'。 如果 `path' 是目录，则会引发 *note
     IsADirectoryError: 9a1.。 请使用 *note rmdir(): a42. 来删除目录。 如
     果文件不存在，则会引发 *note FileNotFoundError: 7c9.。

     本函数支持 *note 基于目录描述符的相对路径: a37.。

     在 Windows 上，尝试删除正在使用的文件会抛出异常。而在 Unix 上，虽然
     该文件的条目会被删除，但分配给文件的存储空间仍然不可用，直到原始文
     件不再使用为止。

     本函数在语义上与 *note unlink(): a44. 相同。

     引发一个 *note 审计事件: ea1. ‘os.remove’，附带参数 ‘path’、
     ‘dir_fd’。

     3.3 新版功能: `dir_fd' 参数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.removedirs (name)

     递归删除目录。工作方式类似于 *note rmdir(): a42.，不同之处在于，如
     果成功删除了末尾一级目录，*note removedirs(): 1f64. 会尝试依次删除
     `path' 中提到的每个父目录，直到抛出错误为止（但该错误会被忽略，因为
     这通常表示父目录不是空目录）。例如，‘os.removedirs('foo/bar/baz')’
     将首先删除目录 ‘'foo/bar/baz'’，然后如果 ‘'foo/bar'’ 和 ‘'foo'’ 为
     空，则继续删除它们。如果无法成功删除末尾一级目录，则抛出 *note
     OSError: 1d4. 异常。

     引发一个 *note 审计事件: ea1. ‘os.remove’，附带参数 ‘path’、
     ‘dir_fd’。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.rename (src, dst, *, src_dir_fd=None, dst_dir_fd=None)

     将文件或目录 `src' 重命名为 `dst'。如果 `dst' 已存在，则下列情况下
     将会操作失败，并抛出 *note OSError: 1d4. 的子类：

     在 Windows 上，如果 `dst' 已存在，则抛出 *note FileExistsError:
     960. 异常。

     在 Unix 上，如果 `src' 是文件而 `dst' 是目录，将抛出 *note
     IsADirectoryError: 9a1. 异常，反之则抛出 *note NotADirectoryError:
     9a2. 异常。如果两者都是目录且 `dst' 为空，则 `dst' 将被静默替换。如
     果 `dst' 是非空目录，则抛出 *note OSError: 1d4. 异常。如果两者都是
     文件，则在用户具有权限的情况下，将对 `dst' 进行静默替换。如果 `src'
     和 `dst' 在不同的文件系统上，则本操作在某些 Unix 分支上可能会失败。
     如果成功，重命名操作将是一个原子操作（这是 POSIX 的要求）。

     本函数支持将 `src_dir_fd' 和 `dst_dir_fd' 中的一个或两个指定为
     *note 基于目录描述符的相对路径: a37.。

     如果需要在不同平台上都能替换目标，请使用 *note replace(): a41.。

     引发一个 *note 审计事件: ea1. ‘os.rename’ 附带参数 ‘src’、‘dst’、
     ‘src_dir_fd’、‘dst_dir_fd’。

     3.3 新版功能: `src_dir_fd' 和 `dst_dir_fd' 参数。

     在 3.6 版更改: 接受一个 *note 类路径对象: 373. 作为 `src' 和 `dst'。

 -- 函数: os.renames (old, new)

     递归重命名目录或文件。工作方式类似 *note rename(): a40.，除了会首先
     创建新路径所需的中间目录。重命名后，将调用 *note removedirs():
     1f64. 删除旧路径中不需要的目录。

          注解: 如果用户没有权限删除末级的目录或文件，则本函数可能会无法
          建立新的目录结构。

     引发一个 *note 审计事件: ea1. ‘os.rename’ 附带参数 ‘src’、‘dst’、
     ‘src_dir_fd’、‘dst_dir_fd’。

     在 3.6 版更改: 接受一个 *note 类路径对象: 373. 作为 `old' 和 `new'。

 -- 函数: os.replace (src, dst, *, src_dir_fd=None, dst_dir_fd=None)

     将文件或目录 `src' 重命名为 `dst'。如果 `dst' 是目录，将抛出 *note
     OSError: 1d4. 异常。如果 `dst' 已存在且为文件，则在用户具有权限的情
     况下，将对其进行静默替换。如果 `src' 和 `dst' 在不同的文件系统上，
     本操作可能会失败。如果成功，重命名操作将是一个原子操作（这是 POSIX
     的要求）。

     本函数支持将 `src_dir_fd' 和 `dst_dir_fd' 中的一个或两个指定为
     *note 基于目录描述符的相对路径: a37.。

     引发一个 *note 审计事件: ea1. ‘os.rename’ 附带参数 ‘src’、‘dst’、
     ‘src_dir_fd’、‘dst_dir_fd’。

     3.3 新版功能.

     在 3.6 版更改: 接受一个 *note 类路径对象: 373. 作为 `src' 和 `dst'。

 -- 函数: os.rmdir (path, *, dir_fd=None)

     移除（删除）目录 `path'。如果目录不存在或不为空，则会分别抛出 *note
     FileNotFoundError: 7c9. 或 *note OSError: 1d4. 异常。要删除整个目录
     树，可以使用 *note shutil.rmtree(): 21d.。

     本函数支持 *note 基于目录描述符的相对路径: a37.。

     引发一个 *note 审计事件: ea1. ‘os.rmdir’，附带参数 ‘path’、
     ‘dir_fd’。

     3.3 新版功能: `dir_fd' 参数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.scandir (path='.')

     返回一个 *note os.DirEntry: 4f9. 对象的迭代器，它们对应于由 `path'
     指定目录中的条目。 这些条目会以任意顺序生成，并且不包括特殊条目
     ‘'.'’ 和 ‘'..'’。 如果有文件在迭代器创建之后在目录中被移除或添加，
     是否要包括该文件对应的条目并没有规定。

     如果需要文件类型或文件属性信息，使用 *note scandir(): 260. 代替
     *note listdir(): a49. 可以大大提高这部分代码的性能，因为如果操作系
     统在扫描目录时返回的是 *note os.DirEntry: 4f9. 对象，则该对象包含了
     这些信息。所有 *note os.DirEntry: 4f9. 的方法都可能执行一次系统调用
     ，但是 *note is_dir(): 1f66. 和 *note is_file(): 65e. 通常只在有符
     号链接时才执行一次系统调用。*note os.DirEntry.stat(): 1f67. 在 Unix
     上始终需要一次系统调用，而在 Windows 上只在有符号链接时才需要。

     `path' 可以是 *note 类路径对象: 373.。如果 `path' 是（直接传入或通
     过 *note PathLike: 4f3. 接口间接传入的） ‘bytes’ 类型，那么每个
     *note os.DirEntry: 4f9. 的 *note name: 1f68. 和 *note path: 1f69. 属
     性将是 ‘bytes’ 类型，其他情况下是 ‘str’ 类型。

     本函数也支持 *note 指定文件描述符为参数: 3bd.，其中描述符必须指向目
     录。

     引发一个 *note 审计事件: ea1. ‘os.scandir’，附带参数 ‘path’。

     *note scandir(): 260. 迭代器支持 *note 上下文管理: 571. 协议，并具
     有以下方法：

      -- 方法: scandir.close ()

          关闭迭代器并释放占用的资源。

          当迭代器迭代完毕，或垃圾回收，或迭代过程出错时，将自动调用本方
          法。但仍建议显式调用它或使用 *note with: 6f2. 语句。

          3.6 新版功能.

     下面的例子演示了 *note scandir(): 260. 的简单用法，用来显示给定
     `path' 中所有不以 ‘'.'’ 开头的文件（不包括目录）。‘entry.is_file()’
     通常不会增加一次额外的系统调用:

          with os.scandir(path) as it:
              for entry in it:
                  if not entry.name.startswith('.') and entry.is_file():
                      print(entry.name)

          注解: 在基于 Unix 的系统上，*note scandir(): 260. 使用系统的
          opendir()(3) 和 readdir()(4) 函数。在 Windows 上，它使用 Win32
          FindFirstFileW(5) 和 FindNextFileW(6) 函数。

     3.5 新版功能.

     3.6 新版功能: 添加了对 *note 上下文管理: 571. 协议和 *note close():
     570. 方法的支持。如果 *note scandir(): 260. 迭代器没有迭代完毕且没
     有显式关闭，其析构函数将发出 *note ResourceWarning: 4d8. 警告。

     本函数接受一个 *note 类路径对象: 373.。

     在 3.7 版更改: 在 Unix 上新增支持 *note 指定文件描述符为参数: 3bd.。

 -- 类: os.DirEntry

     由 *note scandir(): 260. 生成的对象，用于显示目录内某个条目的文件路
     径和其他文件属性。

     *note scandir(): 260. 将在不进行额外系统调用的情况下，提供尽可能多
     的此类信息。每次进行 ‘stat()’ 或 ‘lstat()’ 系统调用时，
     ‘os.DirEntry’ 对象会将结果缓存下来。

     ‘os.DirEntry’ 实例不适合存储在长期存在的数据结构中，如果你知道文件
     元数据已更改，或者自调用 *note scandir(): 260. 以来已经经过了很长时
     间，请调用 ‘os.stat(entry.path)’ 来获取最新信息。

     因为 ‘os.DirEntry’ 方法可以进行系统调用，所以它也可能抛出 *note
     OSError: 1d4. 异常。如需精确定位错误，可以逐个调用 ‘os.DirEntry’ 中
     的方法来捕获 *note OSError: 1d4.，并适当处理。

     为了能直接用作 *note 类路径对象: 373.，‘os.DirEntry’ 实现了 *note
     PathLike: 4f3. 接口。

     ‘os.DirEntry’ 实例所包含的属性和方法如下：

      -- 属性: name

          本条目的基本文件名，是根据 *note scandir(): 260. 的 `path' 参
          数得出的相对路径。

          如果 *note scandir(): 260. 的 `path' 参数是 ‘bytes’ 类型，则
          *note name: 1eef. 属性也是 ‘bytes’ 类型，否则为 ‘str’。使用
          *note fsdecode(): 4f6. 解码 byte 类型的文件名。

      -- 属性: path

          本条目的完整路径：等效于 ‘os.path.join(scandir_path,
          entry.name)’，其中 `scandir_path' 就是 *note scandir(): 260. 的
          `path' 参数。仅当 *note scandir(): 260. 的 `path' 参数为绝对路
          径时，本路径才是绝对路径。如果 *note scandir(): 260. 的 `path'
          参数是 *note 文件描述符: 3bd.，则 *note path: c6. 属性与上述
          *note name: 1eef. 属性相同。

          如果 *note scandir(): 260. 的 `path' 参数是 ‘bytes’ 类型，则
          *note path: c6. 属性也是 ‘bytes’ 类型，否则为 ‘str’。使用
          *note fsdecode(): 4f6. 解码 byte 类型的文件名。

      -- 方法: inode ()

          返回本条目的索引节点号 (inode number)。

          这一结果是缓存在 ‘os.DirEntry’ 对象中的，请调用
          ‘os.stat(entry.path, follow_symlinks=False).st_ino’ 来获取最新
          信息。

          一开始没有缓存时，在 Windows 上需要一次系统调用，但在 Unix 上
          不需要。

      -- 方法: is_dir (*, follow_symlinks=True)

          如果本条目是目录，或是指向目录的符号链接，则返回 ‘True’。如果
          本条目是文件，或指向任何其他类型的文件，或该目录不再存在，则返
          回 ‘False’。

          如果 `follow_symlinks' 是 ‘False’，那么仅当本条目为目录时返回
          ‘True’ （不跟踪符号链接），如果本条目是任何类型的文件，或该文
          件不再存在，则返回 ‘False’。

          这一结果是缓存在 ‘os.DirEntry’ 对象中的，且 `follow_symlinks'
          为 ‘True’ 和 ‘False’ 时的缓存是分开的。请调用 *note os.stat():
          1f2. 和 *note stat.S_ISDIR(): 1c12. 来获取最新信息。

          一开始没有缓存时，大多数情况下不需要系统调用。特别是对于非符号
          链接，Windows 和 Unix 都不需要系统调用，除非某些 Unix 文件系统
          （如网络文件系统）返回了 ‘dirent.d_type == DT_UNKNOWN’。如果本
          条目是符号链接，则需要一次系统调用来跟踪它（除非
          `follow_symlinks' 为 ‘False’）。

          本方法可能抛出 *note OSError: 1d4. 异常，如 *note
          PermissionError: 608. 异常，但 *note FileNotFoundError: 7c9. 异
          常会被内部捕获且不会抛出。

      -- 方法: is_file (*, follow_symlinks=True)

          如果本条目是文件，或是指向文件的符号链接，则返回 ‘True’。如果
          本条目是目录，或指向目录，或指向其他非文件条目，或该文件不再存
          在，则返回 ‘False’。

          如果 `follow_symlinks' 是 ‘False’，那么仅当本条目为文件时返回
          ‘True’ （不跟踪符号链接），如果本条目是目录或其他非文件条目，
          或该文件不再存在，则返回 ‘False’。

          这一结果是缓存在 ‘os.DirEntry’ 对象中的。缓存、系统调用、异常
          抛出都与 *note is_dir(): 1f66. 一致。

      -- 方法: is_symlink ()

          如果本条目是符号链接（即使是断开的链接），返回 ‘True’。如果是
          目录或任何类型的文件，或本条目不再存在，返回 ‘False’。

          这一结果是缓存在 ‘os.DirEntry’ 对象中的，请调用 *note
          os.path.islink(): 1f5. 来获取最新信息。

          一开始没有缓存时，大多数情况下不需要系统调用。其实 Windows 和
          Unix 都不需要系统调用，除非某些 Unix 文件系统（如网络文件系统
          ）返回了 ‘dirent.d_type == DT_UNKNOWN’。

          本方法可能抛出 *note OSError: 1d4. 异常，如 *note
          PermissionError: 608. 异常，但 *note FileNotFoundError: 7c9. 异
          常会被内部捕获且不会抛出。

      -- 方法: stat (*, follow_symlinks=True)

          返回本条目对应的 *note stat_result: 109a. 对象。本方法默认会跟
          踪符号链接，要获取符号链接本身的 stat，请添加
          ‘follow_symlinks=False’ 参数。

          在 Unix 上，本方法需要一次系统调用。在 Windows 上，仅在
          `follow_symlinks' 为 ‘True’ 且该条目是一个重解析点（如符号链接
          或目录结点）时，才需要一次系统调用。

          在 Windows 上，*note stat_result: 109a. 的 ‘st_ino’、‘st_dev’
          和 ‘st_nlink’ 属性总是为零。请调用 *note os.stat(): 1f2. 以获
          得这些属性。

          这一结果是缓存在 ‘os.DirEntry’ 对象中的，且 `follow_symlinks'
          为 ‘True’ 和 ‘False’ 时的缓存是分开的。请调用 *note os.stat():
          1f2. 来获取最新信息。

     注意，‘os.DirEntry’ 和 *note pathlib.Path: 202. 的几个属性和方法之
     间存在很好的对应关系。具体来说是 ‘name’ 属性，以及 ‘is_dir()’、
     ‘is_file()’、‘is_symlink()’ 和 ‘stat()’ 方法，在两个类中具有相同的
     含义。

     3.5 新版功能.

     在 3.6 版更改: 添加了对 *note PathLike: 4f3. 接口的支持。在 Windows
     上添加了对 *note bytes: 33a. 类型路径的支持。

 -- 函数: os.stat (path, *, dir_fd=None, follow_symlinks=True)

     获取文件或文件描述符的状态。在所给路径上执行等效于 ‘stat()’ 系统调
     用的操作。`path' 可以是字符串类型，或（直接传入或通过 *note
     PathLike: 4f3. 接口间接传入的） bytes 类型，或打开的文件描述符。返
     回一个 *note stat_result: 109a. 对象。

     本函数默认会跟踪符号链接，要获取符号链接本身的 stat，请添加
     ‘follow_symlinks=False’ 参数，或使用 *note lstat(): 1f3.。

     本函数支持 *note 指定文件描述符为参数: 3bd. 和 *note
     不跟踪符号链接: a38.。

     在 Windows 上，传入 ‘follow_symlinks=False’ 将禁用所有名称代理重解
     析点，其中包括符号链接和目录结点。其他类型的重解析点将直接打开，比
     如不像链接的或系统无法跟踪的重解析点。当多个链接形成一个链时，本方
     法可能会返回原始链接的 stat，无法完整遍历到非链接的对象。在这种情况
     下，要获取最终路径的 stat，请使用 *note os.path.realpath(): 200. 函
     数尽可能地解析路径，并在解析结果上调用 *note lstat(): 1f3.。这不适
     用于空链接或交接点，否则会抛出异常。

     示例:

          >>> import os
          >>> statinfo = os.stat('somefile.txt')
          >>> statinfo
          os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
          st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
          st_mtime=1297230027, st_ctime=1297230027)
          >>> statinfo.st_size
          264

     参见
     ....

     *note fstat(): 668. 和 *note lstat(): 1f3. 函数。

     3.3 新版功能: 增加 `dir_fd' 和 `follow_symlinks' 参数，可指定文件描
     述符代替路径。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

     在 3.8 版更改: 在 Windows 上，本方法将跟踪系统能解析的所有重解析点
     ，并且传入 ‘follow_symlinks=False’ 会停止跟踪所有名称代理重解析点。
     现在，如果操作系统遇到无法跟踪的重解析点，`stat' 将返回原始路径的信
     息，就像已指定 ‘follow_symlinks=False’ 一样，而不会抛出异常。

 -- 类: os.stat_result

     本对象的属性大致对应于 ‘stat’ 结构体成员，主要作为 *note os.stat():
     1f2.、*note os.fstat(): 668. 和 *note os.lstat(): 1f3. 的返回值。

     属性：

      -- 属性: st_mode

          文件模式：包括文件类型和文件模式位（即权限位）。

      -- 属性: st_ino

          与平台有关，但如果不为零，则根据 ‘st_dev’ 值唯一地标识文件。通
          常：

             * 在 Unix 上该值表示索引节点号 (inode number)。

             * 在 Windows 上该值表示 文件索引号(7) 。

      -- 属性: st_dev

          该文件所在设备的标识符。

      -- 属性: st_nlink

          硬链接的数量。

      -- 属性: st_uid

          文件所有者的用户 ID。

      -- 属性: st_gid

          文件所有者的用户组 ID。

      -- 属性: st_size

          文件大小（以字节为单位），文件可以是常规文件或符号链接。符号链
          接的大小是它包含的路径的长度，不包括末尾的空字节。

     时间戳：

      -- 属性: st_atime

          最近的访问时间，以秒为单位。

      -- 属性: st_mtime

          最近的修改时间，以秒为单位。

      -- 属性: st_ctime

          取决于平台：

             * 在 Unix 上表示最近的元数据更改时间，

             * 在 Windows 上表示创建时间，以秒为单位。

      -- 属性: st_atime_ns

          最近的访问时间，以纳秒表示，为整数。

      -- 属性: st_mtime_ns

          最近的修改时间，以纳秒表示，为整数。

      -- 属性: st_ctime_ns

          取决于平台：

             * 在 Unix 上表示最近的元数据更改时间，

             * 在 Windows 上表示创建时间，以纳秒表示，为整数。

          注解: *note st_atime: 1f73.、*note st_mtime: 1d65. 和 *note
          st_ctime: 1f74. 属性的确切含义和分辨率取决于操作系统和文件系统
          。例如，在使用 FAT 或 FAT32 文件系统的 Windows 上，*note
          st_mtime: 1d65. 有 2 秒的分辨率，而 *note st_atime: 1f73. 仅有
          1 天的分辨率。详细信息请参阅操作系统文档。

          类似地，尽管 *note st_atime_ns: 1f75.、*note st_mtime_ns:
          1f76. 和 *note st_ctime_ns: 1f77. 始终以纳秒表示，但许多系统并
          不提供纳秒精度。在确实提供纳秒精度的系统上，用于存储 *note
          st_atime: 1f73.、*note st_mtime: 1d65. 和 *note st_ctime:
          1f74. 的浮点对象无法保留所有精度，因此不够精确。如果需要确切的
          时间戳，则应始终使用 *note st_atime_ns: 1f75.、*note
          st_mtime_ns: 1f76. 和 *note st_ctime_ns: 1f77.。

     在某些 Unix 系统上（如 Linux 上），以下属性可能也可用：

      -- 属性: st_blocks

          为文件分配的字节块数，每块 512 字节。文件是稀疏文件时，它可能
          小于 *note st_size: 1f72./512。

      -- 属性: st_blksize

          “首选的” 块大小，用于提高文件系统 I/O 效率。写入文件时块大小太
          小可能会导致读取-修改-重写效率低下。

      -- 属性: st_rdev

          设备类型（如果是 inode 设备）。

      -- 属性: st_flags

          用户定义的文件标志位。

     在其他 Unix 系统上（如 FreeBSD 上），以下属性可能可用（但仅当 root
     使用它们时才被填充）：

      -- 属性: st_gen

          文件生成号。

      -- 属性: st_birthtime

          文件创建时间。

     在 Solaris 及其衍生版本上，以下属性可能也可用：

      -- 属性: st_fstype

          文件所在文件系统的类型的唯一标识，为字符串。

     在 Mac OS 系统上，以下属性可能也可用：

      -- 属性: st_rsize

          文件的实际大小。

      -- 属性: st_creator

          文件的创建者。

      -- 属性: st_type

          文件类型。

     在 Windows 系统上，以下属性也可用：

      -- 属性: st_file_attributes

          Windows 文件属性：‘dwFileAttributes’，由
          ‘GetFileInformationByHandle()’ 返回的
          ‘BY_HANDLE_FILE_INFORMATION’ 结构体的成员之一。请参阅 *note
          stat: f5. 模块中的 ‘FILE_ATTRIBUTE_*’ 常量。

      -- 属性: st_reparse_tag

          当 *note st_file_attributes: 729. 存在
          ‘FILE_ATTRIBUTE_REPARSE_POINT’ 集合时，本字段包含重解析点类型
          标记。请参阅 *note stat: f5. 模块中的 ‘IO_REPARSE_TAG_*’ 常量
          。

     标准模块 *note stat: f5. 中定义了函数和常量，这些函数和常量可用于从
     ‘stat’ 结构体中提取信息。（在 Windows 上，某些项填充的是虚值。）

     为了向后兼容，一个 *note stat_result: 109a. 实例还可以作为至少包含
     10 个整数的元组访问，以提供 ‘stat’ 结构中最重要（和可移植）的成员，
     整数顺序为 *note st_mode: 1f6c, *note st_ino: 1f6d, *note st_dev:
     1f6e, *note st_nlink: 1f6f, *note st_uid: 1f70, *note st_gid: 1f71,
     *note st_size: 1f72, *note st_atime: 1f73, *note st_mtime: 1d65,
     *note st_ctime: 1f74.。某些实现可能在末尾还有更多项。为了与旧版
     Python 兼容，以元组形式访问 *note stat_result: 109a. 始终返回整数。

     3.3 新版功能: 添加了 *note st_atime_ns: 1f75.、*note st_mtime_ns:
     1f76. 和 *note st_ctime_ns: 1f77. 成员。

     3.5 新版功能: 在 Windows 上添加了 *note st_file_attributes: 729. 成
     员。

     在 3.5 版更改: 在 Windows 上，如果可用，会返回文件索引作为 *note
     st_ino: 1f6d. 的值。

     3.7 新版功能: 在 Solaris 及其衍生版本上添加了 *note st_fstype: 3c7.
     成员。

     3.8 新版功能: 在 Windows 上添加了 *note st_reparse_tag: 1f81. 成员
     。

     在 3.8 版更改: 在 Windows 上，*note st_mode: 1f6c. 成员现在可以根据
     需要将特殊文件标识为 ‘S_IFCHR’、‘S_IFIFO’ 或 ‘S_IFBLK’。

 -- 函数: os.statvfs (path)

     在所给的路径上执行 ‘statvfs()’ 系统调用。返回值是一个对象，其属性描
     述了所给路径上的文件系统，并且与 ‘statvfs’ 结构体的成员相对应，即：
     ‘f_bsize’, ‘f_frsize’, ‘f_blocks’, ‘f_bfree’, ‘f_bavail’,
     ‘f_files’, ‘f_ffree’, ‘f_favail’, ‘f_flag’, ‘f_namemax’, ‘f_fsid’。

     为 ‘f_flag’ 属性位定义了两个模块级常量：如果存在 ‘ST_RDONLY’ 位，则
     文件系统以只读挂载；如果存在 ‘ST_NOSUID’ 位，则文件系统禁用或不支持
     setuid/setgid 位。

     为基于 GNU/glibc 的系统还定义了额外的模块级常量。它们是 ‘ST_NODEV’
     （禁止访问设备专用文件），‘ST_NOEXEC’ （禁止执行程序），
     ‘ST_SYNCHRONOUS’ （写入后立即同步），‘ST_MANDLOCK’ （允许文件系统上
     的强制锁定），‘ST_WRITE’ （写入文件/目录/符号链接），‘ST_APPEND’ （
     仅追加文件），‘ST_IMMUTABLE’ （不可变文件），‘ST_NOATIME’ （不更新
     访问时间），‘ST_NODIRATIME’ （不更新目录访问时间），‘ST_RELATIME’ （
     相对于 mtime/ctime 更新访问时间）。

     本函数支持 *note 指定文件描述符为参数: 3bd.。

     *note 可用性: 136f.: Unix。

     在 3.2 版更改: 添加了 ‘ST_RDONLY’ 和 ‘ST_NOSUID’ 常量。

     3.3 新版功能: 新增支持将 `path' 参数指定为打开的文件描述符。

     在 3.4 版更改: 添加了 ‘ST_NODEV’、‘ST_NOEXEC’、‘ST_SYNCHRONOUS’、
     ‘ST_MANDLOCK’、‘ST_WRITE’、‘ST_APPEND’、‘ST_IMMUTABLE’、
     ‘ST_NOATIME’、‘ST_NODIRATIME’ 和 ‘ST_RELATIME’ 常量。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

     3.7 新版功能: 添加了 ‘f_fsid’。

 -- 数据: os.supports_dir_fd

     一个 *note set: b77. 对象，指示 *note os: c5. 模块中的哪些函数接受
     一个打开的文件描述符作为 `dir_fd' 参数。不同平台提供的功能不同，且
     Python 用于实现 `dir_fd' 参数的底层函数并非在 Python 支持的所有平台
     上都可用。考虑到一致性，支持 `dir_fd' 的函数始终允许指定描述符，但
     如果在底层不支持时调用了该函数，则会抛出异常。（在所有平台上始终支
     持将 `dir_fd' 指定为 ‘None’。）

     要检查某个函数是否接受打开的文件描述符作为 `dir_fd' 参数，请在
     ‘supports_dir_fd’ 前使用 ‘in’ 运算符。例如，如果 *note os.stat():
     1f2. 在当前平台上接受打开的文件描述符作为 `dir_fd' 参数，则此表达式
     的计算结果为 ‘True’:

          os.stat in os.supports_dir_fd

     目前 `dir_fd' 参数仅在 Unix 平台上有效，在 Windows 上均无效。

     3.3 新版功能.

 -- 数据: os.supports_effective_ids

     一个 *note set: b77. 对象，指示 *note os.access(): a39. 是否允许在
     当前平台上将其 `effective_ids' 参数指定为 ‘True’。（所有平台都支持
     将 `effective_ids' 指定为 ‘False’。）如果当前平台支持，则集合将包含
     *note os.access(): a39.，否则集合为空。

     如果当前平台上的 *note os.access(): a39. 支持 ‘effective_ids=True’，
     则此表达式的计算结果为 ‘True’:

          os.access in os.supports_effective_ids

     目前仅 Unix 平台支持 `effective_ids'，Windows 不支持。

     3.3 新版功能.

 -- 数据: os.supports_fd

     一个 *note set: b77. 对象，指示在当前平台上 *note os: c5. 模块中的
     哪些函数接受一个打开的文件描述符作为 `path' 参数。不同平台提供的功
     能不同，且 Python 所使用到的底层函数（用于实现接受描述符作为
     `path'）并非在 Python 支持的所有平台上都可用。

     要判断某个函数是否接受打开的文件描述符作为 `path' 参数，请在
     ‘supports_fd’ 前使用 ‘in’ 运算符。例如，如果 *note os.chdir(): a47.
     在当前平台上接受打开的文件描述符作为 `path' 参数，则此表达式的计算
     结果为 ‘True’:

          os.chdir in os.supports_fd

     3.3 新版功能.

 -- 数据: os.supports_follow_symlinks

     一个 *note set: b77. 对象，指示在当前平台上 *note os: c5. 模块中的
     哪些函数的 `follow_symlinks' 参数可指定为 ‘False’。不同平台提供的功
     能不同，且 Python 用于实现 `follow_symlinks' 的底层函数并非在
     Python 支持的所有平台上都可用。考虑到一致性，支持 `follow_symlinks'
     的函数始终允许将其指定为 ‘False’，但如果在底层不支持时调用了该函数
     ，则会抛出异常。（在所有平台上始终支持将 `follow_symlinks' 指定为
     ‘True’。）

     要检查某个函数的 `follow_symlinks' 参数是否可以指定为 ‘False’，请在
     ‘supports_follow_symlinks’ 前使用 ‘in’ 运算符。例如，如果在当前平台
     上调用 *note os.stat(): 1f2. 时可以指定 ‘follow_symlinks=False’，则
     此表达式的计算结果为 ‘True’:

          os.stat in os.supports_follow_symlinks

     3.3 新版功能.

 -- 函数: os.symlink (src, dst, target_is_directory=False, *,
          dir_fd=None)

     创建一个指向 `src' 的符号链接，名为 `dst'。

     在 Windows 上，符号链接可以表示文件或目录两种类型，并且不会动态改变
     类型。如果目标存在，则新建链接的类型将与目标一致。否则，如果
     `target_is_directory' 为 ‘True’，则符号链接将创建为目录链接，为
     ‘False’ （默认）将创建为文件链接。在非 Windows 平台上，
     `target_is_directory' 被忽略。

     本函数支持 *note 基于目录描述符的相对路径: a37.。

          注解: 在 Windows 10 或更高版本上，如果启用了开发人员模式，非特
          权帐户可以创建符号链接。如果开发人员模式不可用/未启用，则需要
          `SeCreateSymbolicLinkPrivilege' 权限，或者该进程必须以管理员身
          份运行。

          当本函数由非特权账户调用时，抛出 *note OSError: 1d4. 异常。

     引发一个 *note 审计事件: ea1. ‘os.symlink’，附带参数 ‘src’、‘dst’、
     ‘dir_fd’。

     *note 可用性: 136f.: Unix, Windows。

     在 3.2 版更改: 添加对 Windows 6.0 (Vista) 符号链接的支持。

     3.3 新版功能: 添加了 `dir_fd' 参数，现在在非 Windows 平台上允许
     `target_is_directory' 参数。

     在 3.6 版更改: 接受一个 *note 类路径对象: 373. 作为 `src' 和 `dst'。

     在 3.8 版更改: 针对启用了开发人员模式的 Windows，添加了非特权账户创
     建符号链接的支持。

 -- 函数: os.sync ()

     强制将所有内容写入磁盘。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: os.truncate (path, length)

     截断 `path' 对应的文件，以使其最大为 `length' 字节。

     本函数支持 *note 指定文件描述符为参数: 3bd.。

     引发一个 *note 审计事件: ea1. ‘os.truncate’，附带参数 ‘path’,
     ‘length’。

     *note 可用性: 136f.: Unix, Windows。

     3.3 新版功能.

     在 3.5 版更改: 添加了 Windows 支持

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.unlink (path, *, dir_fd=None)

     移除（删除）文件 `path'。该函数在语义上与 *note remove(): a3f. 相同
     ，‘unlink’ 是其传统的 Unix 名称。请参阅 *note remove(): a3f. 的文档
     以获取更多信息。

     引发一个 *note 审计事件: ea1. ‘os.remove’，附带参数 ‘path’、
     ‘dir_fd’。

     3.3 新版功能: `dir_fd' 参数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.utime (path, times=None, *[, ns], dir_fd=None,
          follow_symlinks=True)

     设置文件 `path' 的访问时间和修改时间。

     *note utime(): a45. 有 `times' 和 `ns' 两个可选参数，它们指定了设置
     给 `path' 的时间，用法如下：

        - 如果指定 `ns'，它必须是一个 ‘(atime_ns, mtime_ns)’ 形式的二元
          组，其中每个成员都是一个表示纳秒的整数。

        - 如果 `times' 不为 ‘None’，则它必须是 ‘(atime, mtime)’ 形式的二
          元组，其中每个成员都是一个表示秒的 int 或 float。

        - 如果 `times' 为 ‘None’ 且未指定 `ns'，则相当于指定
          ‘ns=(atime_ns, mtime_ns)’，其中两个时间均为当前时间。

     同时为 `times' 和 `ns' 指定元组会出错。

     注意，根据操作系统记录访问时间和修改时间的分辨率，后续的 *note
     stat(): 1f2. 调用可能不会返回此处设置的确切时间。请参阅 *note
     stat(): 1f2.。保留精确时间的最佳方法是使用 *note os.stat(): 1f2. 结
     果对象中的 `st_atime_ns' 和 `st_mtime_ns' 字段，并将 `ns' 参数设置
     为 ‘utime’。

     本函数支持 *note 指定文件描述符: 3bd.、*note
     指定基于目录描述符的相对路径: a37. 和 *note 不跟踪符号链接: a38.。

     引发一个 *note 审计事件: ea1. ‘os.utime’，附带参数 ‘path’、
     ‘times’、‘ns’、‘dir_fd’。

     3.3 新版功能: 新增支持将 `path' 参数指定为打开的文件描述符，以及支
     持 `dir_fd'、`follow_symlinks' 和 `ns' 参数。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.walk (top, topdown=True, onerror=None, followlinks=False)

     生成目录树中的文件名，方式是按上->下或下->上顺序浏览目录树。对于以
     `top' 为根的目录树中的每个目录（包括 `top' 本身），它都会生成一个三
     元组 ‘(dirpath, dirnames, filenames)’。

     `dirpath' 是表示目录路径的字符串。 `dirnames' 是 `dirpath' 中子目录
     名称组成的列表 (excluding ‘'.'’ and ‘'..'’)。 `filenames' 是
     `dirpath' 中非目录文件名称组成的列表。 请注意列表中的名称不带路径部
     分。 要获取 `dirpath' 中文件或目录的完整路径（以 `top' 打头），请执
     行 ‘os.path.join(dirpath, name)’。 列表是否排序取决于具体文件系统。
     如果有文件或列表生成期间被移除或添加到 `dirpath' 目录中，是否要包括
     该文件的名称并没有规定。

     如果可选参数 `topdown' 为 ‘True’ 或未指定，则在所有子目录的三元组之
     前生成父目录的三元组（目录是自上而下生成的）。如果 `topdown' 为
     ‘False’，则在所有子目录的三元组生成之后再生成父目录的三元组（目录是
     自下而上生成的）。无论 `topdown' 为何值，在生成目录及其子目录的元组
     之前，都将检索全部子目录列表。

     当 `topdown' 为 ‘True’ 时，调用者可以就地修改 `dirnames' 列表（也许
     用到了 *note del: 127e. 或切片），而 *note walk(): 65d. 将仅仅递归
     到仍保留在 `dirnames' 中的子目录内。这可用于减少搜索、加入特定的访
     问顺序，甚至可在继续 *note walk(): 65d. 之前告知 *note walk(): 65d.
     由调用者新建或重命名的目录的信息。当 `topdown' 为 ‘False’ 时，修改
     `dirnames' 对 walk 的行为没有影响，因为在自下而上模式中，`dirnames'
     中的目录是在 `dirpath' 本身之前生成的。

     默认将忽略 *note scandir(): 260. 调用中的错误。如果指定了可选参数
     `onerror'，它应该是一个函数。出错时它会被调用，参数是一个 *note
     OSError: 1d4. 实例。它可以报告错误然后继续遍历，或者抛出异常然后中
     止遍历。注意，可以从异常对象的 ‘filename’ 属性中获取出错的文件名。

     *note walk(): 65d. 默认不会递归进指向目录的符号链接。可以在支持符号
     链接的系统上将 `followlinks' 设置为 ‘True’，以访问符号链接指向的目
     录。

          注解: 注意，如果链接指向自身的父目录，则将 `followlinks' 设置
          为 ‘True’ 可能导致无限递归。*note walk(): 65d. 不会记录它已经
          访问过的目录。

          注解: 如果传入的是相对路径，请不要在恢复 *note walk(): 65d. 之
          间更改当前工作目录。*note walk(): 65d. 不会更改当前目录，并假
          定其调用者也不会更改当前目录。

     下面的示例遍历起始目录内所有子目录，打印每个目录内的文件占用的字节
     数，CVS 子目录不会被遍历:

          import os
          from os.path import join, getsize
          for root, dirs, files in os.walk('python/Lib/email'):
              print(root, "consumes", end=" ")
              print(sum(getsize(join(root, name)) for name in files), end=" ")
              print("bytes in", len(files), "non-directory files")
              if 'CVS' in dirs:
                  dirs.remove('CVS')  # don't visit CVS directories

     在下一个示例（*note shutil.rmtree(): 21d. 的简单实现）中，必须使树
     自下而上遍历，因为 *note rmdir(): a42. 只允许在目录为空时删除目录:

          # Delete everything reachable from the directory named in "top",
          # assuming there are no symbolic links.
          # CAUTION:  This is dangerous!  For example, if top == '/', it
          # could delete all your disk files.
          import os
          for root, dirs, files in os.walk(top, topdown=False):
              for name in files:
                  os.remove(os.path.join(root, name))
              for name in dirs:
                  os.rmdir(os.path.join(root, name))

     在 3.5 版更改: 现在，本函数调用的是 *note os.scandir(): 260. 而不是
     *note os.listdir(): a49.，从而减少了调用 *note os.stat(): 1f2. 的次
     数而变得更快。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.fwalk (top='.', topdown=True, onerror=None, *,
          follow_symlinks=False, dir_fd=None)

     本方法的行为与 *note walk(): 65d. 完全一样，除了它产生的是 4 元组
     ‘(dirpath, dirnames, filenames, dirfd)’，并且它支持 ‘dir_fd’。

     `dirpath'、`dirnames' 和 `filenames' 与 *note walk(): 65d. 输出的相
     同，`dirfd' 是指向目录 `dirpath' 的文件描述符。

     本函数始终支持 *note 基于目录描述符的相对路径: a37. 和 *note
     不跟踪符号链接: a38.。但是请注意，与其他函数不同，*note fwalk():
     3bc. 的 `follow_symlinks' 的默认值为 ‘False’。

          注解: 由于 *note fwalk(): 3bc. 会生成文件描述符，而它们仅在下
          一个迭代步骤前有效，因此如果要将描述符保留更久，则应复制它们（
          比如使用 *note dup(): fa4.）。

     下面的示例遍历起始目录内所有子目录，打印每个目录内的文件占用的字节
     数，CVS 子目录不会被遍历:

          import os
          for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
              print(root, "consumes", end="")
              print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
                    end="")
              print("bytes in", len(files), "non-directory files")
              if 'CVS' in dirs:
                  dirs.remove('CVS')  # don't visit CVS directories

     在下一个示例中，必须使树自下而上遍历，因为 *note rmdir(): a42. 只允
     许在目录为空时删除目录:

          # Delete everything reachable from the directory named in "top",
          # assuming there are no symbolic links.
          # CAUTION:  This is dangerous!  For example, if top == '/', it
          # could delete all your disk files.
          import os
          for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
              for name in files:
                  os.unlink(name, dir_fd=rootfd)
              for name in dirs:
                  os.rmdir(name, dir_fd=rootfd)

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

     在 3.7 版更改: 添加了对 *note bytes: 33a. 类型路径的支持。

 -- 函数: os.memfd_create (name[, flags=os.MFD_CLOEXEC])

     创建一个匿名文件，返回指向该文件的文件描述符。`flags' 必须是系统上
     可用的 ‘os.MFD_*’ 常量之一（或将它们按位“或”组合起来）。新文件描述
     符默认是 *note 不可继承的: 803.。

     `name' 提供的名称会被用作文件名，并且 ‘/proc/self/fd/’ 目录中相应符
     号链接的目标将显示为该名称。显示的名称始终以 ‘memfd:’ 为前缀，并且
     仅用于调试目的。名称不会影响文件描述符的行为，因此多个文件可以有相
     同的名称，不会有副作用。

     *note 可用性: 136f.：Linux 3.17 或更高版本，且装有 glibc 2.27 或更
     高版本。

     3.8 新版功能.

 -- 数据: os.MFD_CLOEXEC
 -- 数据: os.MFD_ALLOW_SEALING
 -- 数据: os.MFD_HUGETLB
 -- 数据: os.MFD_HUGE_SHIFT
 -- 数据: os.MFD_HUGE_MASK
 -- 数据: os.MFD_HUGE_64KB
 -- 数据: os.MFD_HUGE_512KB
 -- 数据: os.MFD_HUGE_1MB
 -- 数据: os.MFD_HUGE_2MB
 -- 数据: os.MFD_HUGE_8MB
 -- 数据: os.MFD_HUGE_16MB
 -- 数据: os.MFD_HUGE_32MB
 -- 数据: os.MFD_HUGE_256MB
 -- 数据: os.MFD_HUGE_512MB
 -- 数据: os.MFD_HUGE_1GB
 -- 数据: os.MFD_HUGE_2GB
 -- 数据: os.MFD_HUGE_16GB

     以上标志位可以传递给 *note memfd_create(): 1f1.。

     *note 可用性: 136f.：Linux 3.17 或更高版本，且装有 glibc 2.27 或更
     高版本。‘MFD_HUGE*’ 标志仅在 Linux 4.14 及以上可用。

     3.8 新版功能.

* Menu:

* Linux 扩展属性::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0529

   (2) https://bugs.python.org/issue21082

   (3) 
http://pubs.opengroup.org/onlinepubs/009695399/functions/opendir.html

   (4) 
http://pubs.opengroup.org/onlinepubs/009695399/functions/readdir_r.html

   (5) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx

   (6) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx

   (7) https://msdn.microsoft.com/en-us/library/aa363788


File: python.info,  Node: Linux 扩展属性,  Up: 文件和目录

5.16.1.8 Linux 扩展属性
.......................

3.3 新版功能.

这些函数仅在 Linux 上可用。

 -- 函数: os.getxattr (path, attribute, *, follow_symlinks=True)

     返回 `path' 的扩展文件系统属性 `attribute' 的值。`attribute' 可以是
     bytes 或 str （直接传入或通过 *note PathLike: 4f3. 接口间接传入）。
     如果是 str，则使用文件系统编码来编码字符串。

     本函数支持 *note 指定文件描述符为参数: 3bd. 和 *note
     不跟踪符号链接: a38.。

     引发一个 *note 审计事件: ea1. ‘os.getxattr’，附带参数 ‘path’、
     ‘attribute’。

     在 3.6 版更改: 接受一个 *note 类路径对象: 373. 作为 `path' 和
     `attribute'。

 -- 函数: os.listxattr (path=None, *, follow_symlinks=True)

     返回一个列表，包含 `path' 的所有扩展文件系统属性。列表中的属性都表
     示为字符串，它们是根据文件系统编码解码出来的。如果 `path' 为
     ‘None’，则 *note listxattr(): a54. 将检查当前目录。

     本函数支持 *note 指定文件描述符为参数: 3bd. 和 *note
     不跟踪符号链接: a38.。

     引发一个 *note 审计事件: ea1. ‘os.listxattr’，附带参数 ‘path’。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os.removexattr (path, attribute, *, follow_symlinks=True)

     从 `path' 中删除扩展文件系统属性 `attribute'。`attribute' 应该是
     bytes 或 str （直接传入或通过 *note PathLike: 4f3. 接口间接传入）。
     如果是 str，则使用文件系统编码来编码字符串。

     本函数支持 *note 指定文件描述符为参数: 3bd. 和 *note
     不跟踪符号链接: a38.。

     引发一个 *note 审计事件: ea1. ‘os.removexattr’，附带参数 ‘path’、
     ‘attribute’。

     在 3.6 版更改: 接受一个 *note 类路径对象: 373. 作为 `path' 和
     `attribute'。

 -- 函数: os.setxattr (path, attribute, value, flags=0, *,
          follow_symlinks=True)

     将 `path' 的扩展文件系统属性 `attribute' 设为 `value'。 `attribute'
     必须是没有内嵌 NUL 的字节串或字符串（直接或通过 *note PathLike:
     4f3. 间接传入）。 如果是字符串，则使用文件系统编码格式进行编码。
     `flags' 可以为 *note XATTR_REPLACE: 1f94. 或 *note XATTR_CREATE:
     1f95.。 如果指定 *note XATTR_REPLACE: 1f94. 而该属性不存在，则将引
     发 ‘ENODATA’。 如果指定 *note XATTR_CREATE: 1f95. 而该属性已存在，
     则将不创建该属性并将引发 ‘EEXISTS’。

     本函数支持 *note 指定文件描述符为参数: 3bd. 和 *note
     不跟踪符号链接: a38.。

          注解: Linux kernel 2.6.39 以下版本的一个 bug 导致在某些文件系
          统上，flags 参数会被忽略。

     引发一个 *note 审计事件: ea1. ‘os.setxattr’，附带参数 ‘path’、
     ‘attribute’、‘value’、‘flags’。

     在 3.6 版更改: 接受一个 *note 类路径对象: 373. 作为 `path' 和
     `attribute'。

 -- 数据: os.XATTR_SIZE_MAX

     一条扩展属性的值的最大大小。在当前的 Linux 上是 64 KiB。

 -- 数据: os.XATTR_CREATE

     这是 *note setxattr(): a56. 的 flags 参数的可取值，它表示该操作必须
     创建一个属性。

 -- 数据: os.XATTR_REPLACE

     这是 *note setxattr(): a56. 的 flags 参数的可取值，它表示该操作必须
     替换现有属性。


File: python.info,  Node: 进程管理,  Next: 调度器接口,  Prev: 文件和目录,  Up: os --- 多种操作系统接口

5.16.1.9 进程管理
.................

下列函数可用于创建和管理进程。

所有 *note exec*: 1f99. 函数都接受一个参数列表，用来给新程序加载到它的进
程中。在所有情况下，传递给新程序的第一个参数是程序本身的名称，而不是用户
在命令行上输入的参数。对于 C 程序员来说，这就是传递给 ‘main()’ 函数的
‘argv[0]’。例如，‘os.execv('/bin/echo', ['foo', 'bar'])’ 只会在标准输出
上打印 ‘bar’，而 ‘foo’ 会被忽略。

 -- 函数: os.abort ()

     发送 ‘SIGABRT’ 信号到当前进程。在 Unix 上，默认行为是生成一个核心转
     储。在 Windows 上，该进程立即返回退出代码 ‘3’。请注意，使用 *note
     signal.signal(): a85. 可以为 ‘SIGABRT’ 注册 Python 信号处理程序，而
     调用本函数将不会调用按前述方法注册的程序。

 -- 函数: os.add_dll_directory (path)

     将路径添加到 DLL 搜索路径。

     当需要解析扩展模块的依赖时（扩展模块本身通过 sys.path 解析），会使
     用该搜索路径，*note ctypes: 2b. 也会使用该搜索路径。

     要移除目录，可以在返回的对象上调用 `close()'，也可以在 *note with:
     6f2. 语句内使用本方法。

     参阅 Microsoft 文档(1) 获取如何加载 DLL 的信息。

     引发一个 *note 审计事件: ea1. ‘os.add_dll_directory’，附带参数
     ‘path’。

     *note 可用性: 136f.: Windows。

     3.8 新版功能: 早期版本的 CPython 解析 DLL 时用的是当前进程的默认行
     为。这会导致不一致，比如不是每次都会去搜索 ‘PATH’ 和当前工作目录，
     且系统函数（如 ‘AddDllDirectory’ ）失效。

     在 3.8 中，DLL 的两种主要加载方式现在可以显式覆盖进程的行为，以确保
     一致性。请参阅 *note 移植说明: 2cb. 了解如何更新你的库。

 -- 函数: os.execl (path, arg0, arg1, ...)
 -- 函数: os.execle (path, arg0, arg1, ..., env)
 -- 函数: os.execlp (file, arg0, arg1, ...)
 -- 函数: os.execlpe (file, arg0, arg1, ..., env)
 -- 函数: os.execv (path, args)
 -- 函数: os.execve (path, args, env)
 -- 函数: os.execvp (file, args)
 -- 函数: os.execvpe (file, args, env)

     这些函数都将执行一个新程序，以替换当前进程。它们没有返回值。在 Unix
     上，新程序会加载到当前进程中，且进程号与调用者相同。过程中的错误会
     被报告为 *note OSError: 1d4. 异常。

     当前进程会被立即替换。打开的文件对象和描述符都不会刷新，因此如果这
     些文件上可能缓冲了数据，则应在调用 *note exec*: 1f99. 函数之前使用
     ‘sys.stdout.flush()’ 或 *note os.fsync(): 66a. 刷新它们。

     *note exec*: 1f99. 函数的 "l" 和 "v" 变体不同在于命令行参数的传递方
     式。如果在编码时固定了参数数量，则 "l" 变体可能是最方便的，各参数作
     为 ‘execl*()’ 函数的附加参数传入即可。当参数数量可变时，"v" 变体更
     方便，参数以列表或元组的形式作为 `args' 参数传递。在这两种情况下，
     子进程的第一个参数都应该是即将运行的命令名称，但这不是强制性的。

     结尾包含 "p" 的变体（*note execlp(): 1f9c.、*note execlpe(): 1f9d.、
     *note execvp(): 1f9e. 和 *note execvpe(): 1f9f. ）将使用 ‘PATH’ 环
     境变量来查找程序 `file'。当环境被替换时（使用下一段讨论的 *note
     exec*e: 1f99. 变体之一）， ‘PATH’ 变量将来自于新环境。其他变体
     *note execl(): 1f99.、*note execle(): 1f9b.、*note execv(): 1f08. 和
     *note execve(): a48. 不使用 ‘PATH’ 变量来查找程序，因此 `path' 必须
     包含正确的绝对或相对路径。

     对于 *note execle(): 1f9b.、*note execlpe(): 1f9d.、*note execve():
     a48. 和 *note execvpe(): 1f9f. （都以 "e" 结尾），`env' 参数是一个
     映射，用于定义新进程的环境变量（代替当前进程的环境变量）。而函数
     *note execl(): 1f99.、*note execlp(): 1f9c.、*note execv(): 1f08. 和
     *note execvp(): 1f9e. 会将当前进程的环境变量过继给新进程。

     某些平台上的 *note execve(): a48. 可以将 `path' 指定为打开的文件描
     述符。当前平台可能不支持此功能，可以使用 *note os.supports_fd: a4c.
     检查它是否支持。如果不可用，则使用它会抛出 *note
     NotImplementedError: 617. 异常。

     引发一个 *note 审计事件: ea1. ‘os.exec’，附带参数 ‘path’、‘args’、
     ‘env’。

     *note 可用性: 136f.: Unix, Windows。

     3.3 新版功能: 新增支持将 *note execve(): a48. 的 `path' 参数指定为
     打开的文件描述符。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: os._exit (n)

     以状态码 `n' 退出进程，不会调用清理处理程序，不会刷新 stdio，等等。

          注解: 退出的标准方法是使用 ‘sys.exit(n)’。而 *note _exit():
          171e. 通常只应在 *note fork(): 969. 出的子进程中使用。

以下是已定义的退出代码，可以用于 *note _exit(): 171e.，尽管它们不是必需
的。这些退出代码通常用于 Python 编写的系统程序，例如邮件服务器的外部命令
传递程序。

     注解: 其中部分退出代码在部分 Unix 平台上可能不可用，因为平台间存在
     差异。如果底层平台定义了这些常量，那上层也会定义。

 -- 数据: os.EX_OK

     退出代码，表示未发生任何错误。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_USAGE

     退出代码，表示命令使用不正确，如给出的参数数量有误。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_DATAERR

     退出代码，表示输入数据不正确。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_NOINPUT

     退出代码，表示某个输入文件不存在或不可读。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_NOUSER

     退出代码，表示指定的用户不存在。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_NOHOST

     退出代码，表示指定的主机不存在。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_UNAVAILABLE

     退出代码，表示所需的服务不可用。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_SOFTWARE

     退出代码，表示检测到内部软件错误。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_OSERR

     退出代码，表示检测到操作系统错误，例如无法 fork 或创建管道。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_OSFILE

     退出代码，表示某些系统文件不存在、无法打开或发生其他错误。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_CANTCREAT

     退出代码，表示无法创建用户指定的输出文件。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_IOERR

     退出代码，表示对某些文件进行读写时发生错误。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_TEMPFAIL

     退出代码，表示发生了暂时性故障。它可能并非意味着真正的错误，例如在
     可重试的情况下无法建立网络连接。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_PROTOCOL

     退出代码，表示协议交换是非法的、无效的或无法解读的。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_NOPERM

     退出代码，表示没有足够的权限执行该操作（但不适用于文件系统问题）。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_CONFIG

     退出代码，表示发生某种配置错误。

     *note 可用性: 136f.: Unix。

 -- 数据: os.EX_NOTFOUND

     退出代码，表示的内容类似于“找不到条目”。

     *note 可用性: 136f.: Unix。

 -- 函数: os.fork ()

     Fork 出一个子进程。在子进程中返回 ‘0’，在父进程中返回子进程的进程号
     。如果发生错误，则抛出 *note OSError: 1d4. 异常。

     注意，当从线程中使用 ‘fork()’ 时，某些平台（包括 FreeBSD <= 6.3 和
     Cygwin）存在已知问题。

     引发一个 *note 审计事件: ea1. ‘os.fork’，没有附带参数。

     在 3.8 版更改: 不再支持在子解释器中调用 ‘fork()’ （将抛出 *note
     RuntimeError: 2bb. 异常）。

          警告: 有关 SSL 模块与 fork() 结合的应用，请参阅 *note ssl:
          f4.。

     *note 可用性: 136f.: Unix。

 -- 函数: os.forkpty ()

     Fork 出一个子进程，使用新的伪终端作为子进程的控制终端。返回一对
     ‘(pid, fd)’，其中 `pid' 在子进程中为 ‘0’，这是父进程中新子进程的进
     程号，而 `fd' 是伪终端主设备的文件描述符。对于更便于移植的方法，请
     使用 *note pty: d6. 模块。如果发生错误，则抛出 *note OSError: 1d4.
     异常。

     引发一个 *note 审计事件: ea1. ‘os.forkpty’，没有附带参数。

     在 3.8 版更改: 不再支持在子解释器中调用 ‘forkpty()’ （将抛出 *note
     RuntimeError: 2bb. 异常）。

     *note 可用性: 136f.: 某些 Unix。

 -- 函数: os.kill (pid, sig)

     将信号 `sig' 发送至进程 `pid'。特定平台上可用的信号常量定义在 *note
     signal: eb. 模块中。

     Windows： *note signal.CTRL_C_EVENT: 1fb2. 和 *note
     signal.CTRL_BREAK_EVENT: 1fb3. 信号是特殊信号，只能发送给共享同一个
     控制台窗口的控制台进程，如某些子进程。`sig' 取任何其他值将导致该进
     程被 TerminateProcess API 无条件终止，且退出代码为 `sig'。Windows 版
     本的 *note kill(): cfb. 还需要传入待结束进程的句柄。

     另请参阅 *note signal.pthread_kill(): a82.。

     引发一个 *note 审计事件: ea1. ‘os.kill’，附带参数 ‘pid’、‘sig’。

     3.2 新版功能: Windows 支持。

 -- 函数: os.killpg (pgid, sig)

     将信号 `sig' 发送给进程组 `pgid'。

     引发一个 *note 审计事件: ea1. ‘os.killpg’，附带参数 ‘pgid’、‘sig’。

     *note 可用性: 136f.: Unix。

 -- 函数: os.nice (increment)

     将进程的优先级（nice 值）增加 `increment'，返回新的 nice 值。

     *note 可用性: 136f.: Unix。

 -- 函数: os.plock (op)

     将程序段锁定到内存中。`op' 的值（定义在 ‘<sys/lock.h>’ 中）决定了哪
     些段被锁定。

     *note 可用性: 136f.: Unix。

 -- 函数: os.popen (cmd, mode='r', buffering=-1)

     打开一个管道，它通往 / 接受自命令 `cmd'。返回值是连接到管道的文件对
     象，根据 `mode' 是 ‘'r'’ （默认）还是 ‘'w'’ 决定该对象可以读取还是
     写入。`buffering' 参数与内置函数 *note open(): 4f8. 相应的参数含义
     相同。返回的文件对象只能读写文本字符串，不能是字节类型。

     如果子进程成功退出，则 ‘close’ 方法返回 *note None: 158.。如果发生
     错误，则返回子进程的返回码。在 POSIX 系统上，如果返回码为正，则它就
     是进程返回值左移一个字节后的值。如果返回码为负，则进程是被信号终止
     的，返回码取反后就是该信号。（例如，如果子进程被终止，则返回值可能
     是 ‘- signal.SIGKILL’。）在 Windows 系统上，返回值包含子进程的返回
     码（有符号整数）。

     本方法是使用 *note subprocess.Popen: 2ba. 实现的，如需更强大的方法
     来管理和沟通子进程，请参阅该类的文档。

 -- 函数: os.posix_spawn (path, argv, env, *, file_actions=None,
          setpgroup=None, resetids=False, setsid=False, setsigmask=(),
          setsigdef=(), scheduler=None)

     包装 ‘posix_spawn()’ C 库 API，使其可以从 Python 调用。

     大多数用户应使用 *note subprocess.run(): 3f5. 代替 *note
     posix_spawn(): 258.。

     仅位置参数 (Positional-only arguments) `path'、`args' 和 `env' 与
     *note execve(): a48. 中的类似。

     `path' 形参是可执行文件的路径，`path' 中应当包含目录。 使用 *note
     posix_spawnp(): 1025. 可传入不带目录的可执行文件。

     `file_actions' 参数可以是由元组组成的序列，序列描述了对子进程中指定
     文件描述符采取的操作，这些操作会在 C 库实现的 ‘fork()’ 和 ‘exec()’
     步骤间完成。每个元组的第一个元素必须是下面列出的三个类型指示符之一
     ，用于描述元组剩余的元素：

      -- 数据: os.POSIX_SPAWN_OPEN

          (‘os.POSIX_SPAWN_OPEN’, `fd', `path', `flags', `mode')

          执行 ‘os.dup2(os.open(path, flags, mode), fd)’。

      -- 数据: os.POSIX_SPAWN_CLOSE

          (‘os.POSIX_SPAWN_CLOSE’, `fd')

          执行 ‘os.close(fd)’。

      -- 数据: os.POSIX_SPAWN_DUP2

          (‘os.POSIX_SPAWN_DUP2’, `fd', `new_fd')

          执行 ‘os.dup2(fd, new_fd)’。

     这些元组对应于 C 库 ‘posix_spawn_file_actions_addopen()’，
     ‘posix_spawn_file_actions_addclose()’ 和
     ‘posix_spawn_file_actions_adddup2()’ API 调用，它们为调用
     ‘posix_spawn()’ 自身做准备。

     `setpgroup' 参数将子进程的进程组设置为指定值。如果指定值为 0，则子
     进程的进程组 ID 将与其进程 ID 相同。如果未设置 `setpgroup' 值，则子
     进程将继承父进程的进程组 ID。本参数对应于 C 库
     ‘POSIX_SPAWN_SETPGROUP’ 标志。

     如果 `resetids' 参数为 ‘True’，则会将子进程的有效用户 ID 和有效组
     ID 重置为父进程的实际用户 ID 和实际组 ID。如果该参数为 ‘False’，则
     子进程保留父进程的有效用户 ID 和有效组 ID。无论哪种情况，若在可执行
     文件上启用了 “设置用户 ID” 和 “设置组 ID” 权限位，它们将覆盖有效用
     户 ID 和有效组 ID 的设置。本参数对应于 C 库 ‘POSIX_SPAWN_RESETIDS’
     标志。

     如果 `setsid' 参数为 ‘True’，它将为 ‘posix_spawn’ 新建一个会话 ID。
     `setsid' 需要 ‘POSIX_SPAWN_SETSID’ 或 ‘POSIX_SPAWN_SETSID_NP’ 标志
     ，否则会抛出 *note NotImplementedError: 617. 异常。

     `setsigmask' 参数将信号掩码设置为指定的信号集合。如果未使用该参数，
     则子进程将继承父进程的信号掩码。本参数对应于 C 库
     ‘POSIX_SPAWN_SETSIGMASK’ 标志。

     `sigdef' 参数将集合中所有信号的操作全部重置为默认。本参数对应于 C 库
     ‘POSIX_SPAWN_SETSIGDEF’ 标志。

     `scheduler' 参数必须是一个元组，其中包含调度器策略（可选）以及携带
     了调度器参数的 *note sched_param: 1fb8. 实例。在调度器策略所在位置
     为 ‘None’ 表示未提供该值。本参数是 C 库 ‘POSIX_SPAWN_SETSCHEDPARAM’
     和 ‘POSIX_SPAWN_SETSCHEDULER’ 标志的组合。

     引发一个 *note 审计事件: ea1. ‘os.posix_spawn’，附带参数 ‘path’、
     ‘argv’、‘env’。

     3.8 新版功能.

     *note 可用性: 136f.: Unix。

 -- 函数: os.posix_spawnp (path, argv, env, *, file_actions=None,
          setpgroup=None, resetids=False, setsid=False, setsigmask=(),
          setsigdef=(), scheduler=None)

     包装 ‘posix_spawnp()’ C 库 API，使其可以从 Python 调用。

     与 *note posix_spawn(): 258. 相似，但是系统会在 ‘PATH’ 环境变量指定
     的目录列表中搜索可执行文件 `executable' （与 ‘execvp(3)’ 相同）。

     引发一个 *note 审计事件: ea1. ‘os.posix_spawn’，附带参数 ‘path’、
     ‘argv’、‘env’。

     3.8 新版功能.

     *note 可用性: 136f.: 请参阅 *note posix_spawn(): 258. 文档。

 -- 函数: os.register_at_fork (*, before=None, after_in_parent=None,
          after_in_child=None)

     注册可调用对象，在使用 *note os.fork(): 969. 或类似的进程克隆 API 派
     生新的子进程时，这些对象会运行。参数是可选的，且为仅关键字
     (Keyword-only) 参数。每个参数指定一个不同的调用点。

        * `before' 是一个函数，在 fork 子进程前调用。

        * `after_in_parent' 是一个函数，在 fork 子进程后从父进程调用。

        * `after_in_child' 是一个函数，从子进程中调用。

     只有希望控制权回到 Python 解释器时，才进行这些调用。典型的 *note
     子进程: fa. 启动时不会触发它们，因为子进程不会重新进入解释器。

     在注册的函数中，用于 fork 前运行的函数将按与注册相反的顺序调用。用
     于 fork 后（从父进程或子进程）运行的函数按注册顺序调用。

     注意，第三方 C 代码的 ‘fork()’ 调用可能不会调用这些函数，除非它显式
     调用了 *note PyOS_BeforeFork(): 43a.、*note
     PyOS_AfterFork_Parent(): 43b. 和 *note PyOS_AfterFork_Child():
     2ce.。

     函数注册后无法注销。

     *note 可用性: 136f.: Unix。

     3.7 新版功能.

 -- 函数: os.spawnl (mode, path, ...)
 -- 函数: os.spawnle (mode, path, ..., env)
 -- 函数: os.spawnlp (mode, file, ...)
 -- 函数: os.spawnlpe (mode, file, ..., env)
 -- 函数: os.spawnv (mode, path, args)
 -- 函数: os.spawnve (mode, path, args, env)
 -- 函数: os.spawnvp (mode, file, args)
 -- 函数: os.spawnvpe (mode, file, args, env)

     在新进程中执行程序 `path'。

     （注意，*note subprocess: fa. 模块提供了更强大的工具来生成新进程并
     跟踪执行结果，使用该模块比使用这些函数更好。尤其应当检查 *note 使用
     subprocess 模块替换旧函数: af2. 部分。）

     `mode' 为 *note P_NOWAIT: 1fc0. 时，本函数返回新进程的进程号。
     `mode' 为 *note P_WAIT: 1fc1. 时，如果进程正常退出，返回退出代码，
     如果被终止，返回 ‘-signal’，其中 `signal' 是终止进程的信号。在
     Windows 上，进程号实际上是进程句柄，因此可以与 *note waitpid():
     676. 函数一起使用。

     注意在 VxWorks 上，新进程被终止时，本函数不会返回 ‘-signal’，而是会
     抛出 OSError 异常。

     *note spawn*: 1f55. 函数的 "l" 和 "v" 变体不同在于命令行参数的传递
     方式。如果在编码时固定了参数数量，则 "l" 变体可能是最方便的，各参数
     作为 ‘spawnl*()’ 函数的附加参数传入即可。当参数数量可变时，"v" 变体
     更方便，参数以列表或元组的形式作为 `args' 参数传递。在这两种情况下
     ，子进程的第一个参数都必须是即将运行的命令名称。

     结尾包含第二个 "p" 的变体（*note spawnlp(): 1fba.、*note
     spawnlpe(): 1fbb.、*note spawnvp(): 1fbe. 和 *note spawnvpe():
     1fbf.）将使用 ‘PATH’ 环境变量来查找程序 `file'。当环境被替换时（使
     用下一段讨论的 *note spawn*e: 1f55. 变体之一）， ‘PATH’ 变量将来自
     于新环境。其他变体 *note spawnl(): 1f55.、*note spawnle(): 1fb9.、
     *note spawnv(): 1fbc. 和 *note spawnve(): 1fbd. 不使用 ‘PATH’ 变量
     来查找程序，因此 `path' 必须包含正确的绝对或相对路径。

     对于 *note spawnle(): 1fb9.、*note spawnlpe(): 1fbb.、*note
     spawnve(): 1fbd. 和 *note spawnvpe(): 1fbf. （都以 "e" 结尾），
     `env' 参数是一个映射，用于定义新进程的环境变量（代替当前进程的环境
     变量）。而函数 *note spawnl(): 1f55.、*note spawnlp(): 1fba.、*note
     spawnv(): 1fbc. 和 *note spawnvp(): 1fbe. 会将当前进程的环境变量过
     继给新进程。注意，`env' 字典中的键和值必须是字符串。无效的键或值将
     导致函数出错，返回值为 ‘127’。

     例如，以下对 *note spawnlp(): 1fba. 和 *note spawnvpe(): 1fbf. 的调
     用是等效的:

          import os
          os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')

          L = ['cp', 'index.html', '/dev/null']
          os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)

     引发一个 *note 审计事件: ea1. ‘os.spawn’，附带参数 ‘mode’、‘path’、
     ‘args’、‘env’。

     *note 可用性: 136f.: Unix, Windows。*note spawnlp(): 1fba.、*note
     spawnlpe(): 1fbb.、*note spawnvp(): 1fbe. 和 *note spawnvpe():
     1fbf. 在 Windows 上不可用。*note spawnle(): 1fb9. 和 *note
     spawnve(): 1fbd. 在 Windows 上不是线程安全的，建议使用 *note
     subprocess: fa. 模块替代。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 数据: os.P_NOWAIT
 -- 数据: os.P_NOWAITO

     *note spawn*: 1f55. 系列函数的 `mode' 参数的可取值。如果给出这些值
     中的任何一个，则 ‘spawn*()’ 函数将在创建新进程后立即返回，且返回值
     为进程号。

     *note 可用性: 136f.: Unix, Windows。

 -- 数据: os.P_WAIT

     *note spawn*: 1f55. 系列函数的 `mode' 参数的可取值。如果将 `mode' 指
     定为该值，则 ‘spawn*()’ 函数将在新进程运行完毕后返回，运行成功则返
     回进程的退出代码，被信号终止则返回 ‘-signal’。

     *note 可用性: 136f.: Unix, Windows。

 -- 数据: os.P_DETACH
 -- 数据: os.P_OVERLAY

     *note spawn*: 1f55. 系列函数的 `mode' 参数的可取值。它们比上面列出
     的值可移植性差。*note P_DETACH: 1fc3. 与 *note P_NOWAIT: 1fc0. 相似
     ，但是新进程会与父进程的控制台脱离。使用 *note P_OVERLAY: 1fc4. 则
     会替换当前进程，*note spawn*: 1f55. 函数将不会返回。

     *note 可用性: 136f.: Windows。

 -- 函数: os.startfile (path[, operation])

     使用已关联的应用程序打开文件。

     当 `operation' 未指定或指定为 ‘'open'’ 时，这类似于在 Windows 资源
     管理器中双击文件，或在交互式命令行中将文件名作为 ‘start’ 命令的参数
     ：通过扩展名相关联的应用程序（如果有）打开文件。

     当指定另一个 `operation' 时，它必须是一个“命令动词” ("command
     verb")，该词指定对文件执行的操作。Microsoft 文档中的常用动词有
     ‘'print'’ 和 ‘'edit'’ （用于文件），以及 ‘'explore'’ 和 ‘'find'’ （
     用于目录）。

     关联的应用程序启动后 *note startfile(): 1fc5. 就会立即返回。本函数
     没有等待应用程序关闭的选项，也没有办法检索应用程序的退出状态。
     `path' 参数是基于当前目录的相对路径。如果要使用绝对路径，请确保第一
     个字符不是斜杠 (‘'/'’)，是斜杠的话底层的 Win32 ‘ShellExecute()’ 函
     数将失效。使用 *note os.path.normpath(): cb7. 函数确保路径已针对
     Win32 正确编码。

     为了减少解释器的启动开销，直到第一次调用本函数后，才解析 Win32
     ‘ShellExecute()’ 函数。如果无法解析该函数​​，则抛出 *note
     NotImplementedError: 617. 异常。

     引发一个 *note 审计事件: ea1. ‘os.startfile’，附带参数 ‘path’、
     ‘operation’。

     *note 可用性: 136f.: Windows。

 -- 函数: os.system (command)

     在子 shell 中执行命令（字符串）。这是调用标准 C 函数 ‘system()’ 来
     实现的，因此限制条件与该函数相同。对 *note sys.stdin: 316. 等的更改
     不会反映在执行命令的环境中。`command' 产生的任何输出将被发送到解释
     器标准输出流。

     在 Unix 上，返回值是进程的退出状态，编码格式与为 *note wait(): 674.
     指定的格式相同。注意，POSIX 没有指定 C 函数 ‘system()’ 返回值的含义
     ，因此 Python 函数的返回值与系统有关。

     在 Windows 上，返回值是运行 `command' 后系统 Shell 返回的值。该
     Shell 由 Windows 环境变量 ‘COMSPEC’: 给出：通常是 ‘cmd.exe’，它会返
     回命令的退出状态。在使用非原生 Shell 的系统上，请查阅 Shell 的文档
     。

     *note subprocess: fa. 模块提供了更强大的工具来生成新进程并跟踪执行
     结果，使用该模块比使用本函数更好。参阅 *note subprocess: fa. 文档中
     的 *note 使用 subprocess 模块替换旧函数: af2. 部分以获取有用的帮助
     。

     引发一个 *note 审计事件: ea1. ‘os.system’，附带参数 ‘command’。

     *note 可用性: 136f.: Unix, Windows。

 -- 函数: os.times ()

     返回当前的全局进程时间。返回值是一个有 5 个属性的对象：

        * ‘user’ - 用户时间

        * *note system: dc9. - 系统时间

        * ‘children_user’ - 所有子进程的用户时间

        * ‘children_system’ - 所有子进程的系统时间

        * ‘elapsed’ - 从过去的固定时间点起，经过的真实时间

     为了向后兼容，该对象的行为也类似于五元组，按照 ‘user’，*note
     system: dc9.，‘children_user’，‘children_system’ 和 ‘elapsed’ 顺序
     组成。

     在 Unix 上请参阅 ‘times(2)’ 和 ‘times(3)’ 手册页，在 Windows 上请参
     阅 the GetProcessTimes MSDN(2) 。在 Windows 上，只有 ‘user’ 和
     *note system: dc9. 是已知的，其他属性均为零。

     *note 可用性: 136f.: Unix, Windows。

     在 3.3 版更改: 返回结果的类型由元组变成一个类似元组的对象，同时具有
     命名的属性。

 -- 函数: os.wait ()

     等待子进程执行完毕，返回一个元组，包含其 pid 和退出状态指示：一个
     16 位数字，其低字节是终止该进程的信号编号，高字节是退出状态码（信号
     编号为零的情况下），如果生成了核心文件，则低字节的高位会置位。

     *note 可用性: 136f.: Unix。

 -- 函数: os.waitid (idtype, id, options)

     等待一个或多个子进程执行完毕。`idtype' 可以是 *note P_PID: 1fc6.、
     *note P_PGID: 1fc7. 或 *note P_ALL: 1fc8.。`id' 指定要等待的 pid。
     `options' 是由 *note WEXITED: 1fc9.、*note WSTOPPED: 1fca. 或 *note
     WCONTINUED: 1fcb. 中的一个或多个进行或运算构造的，且额外可以与
     *note WNOHANG: 1fcc. 或 *note WNOWAIT: 1fcd. 进行或运算。返回值是一
     个对象，对应着 ‘siginfo_t’ 结构体中的数据，即： ‘si_pid’, ‘si_uid’,
     ‘si_signo’, ‘si_status’, ‘si_code’ 或 ‘None’ （如果指定了 *note
     WNOHANG: 1fcc. 且没有子进程处于等待状态）。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 数据: os.P_PID
 -- 数据: os.P_PGID
 -- 数据: os.P_ALL

     *note waitid(): 675. 的 `idtype' 参数的可取值。它们影响 `id' 的解释
     方式。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 数据: os.WEXITED
 -- 数据: os.WSTOPPED
 -- 数据: os.WNOWAIT

     用于 *note waitid(): 675. 的 `options' 参数的标志位，指定要等待的子
     进程信号。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 数据: os.CLD_EXITED
 -- 数据: os.CLD_DUMPED
 -- 数据: os.CLD_TRAPPED
 -- 数据: os.CLD_CONTINUED

     *note waitid(): 675. 返回的结果中，‘si_code’ 的可取值。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: os.waitpid (pid, options)

     本函数的细节在 Unix 和 Windows 上有不同之处。

     在 Unix 上：等待进程号为 `pid' 的子进程执行完毕，返回一个元组，内含
     其进程 ID 和退出状态指示（编码与 *note wait(): 674. 相同）。调用的
     语义受整数 `options' 的影响，常规操作下该值应为 ‘0’。

     如果 `pid' 大于 ‘0’，则 *note waitpid(): 676. 会获取该指定进程的状
     态信息。如果 `pid' 为 ‘0’，则获取当前进程所在进程组中的所有子进程的
     状态。如果 `pid' 为 ‘-1’，则获取当前进程的子进程状态。如果 `pid' 小
     于 ‘-1’，则获取进程组 ‘-pid’ （ `pid' 的绝对值）中所有进程的状态。

     当系统调用返回 -1 时，将抛出带有错误码的 *note OSError: 1d4. 异常。

     在 Windows 上：等待句柄为 `pid' 的进程执行完毕，返回一个元组，内含
     `pid' 以及左移 8 位后的退出状态码（移位简化了跨平台使用本函数）。小
     于或等于 ‘0’ 的 `pid' 在 Windows 上没有特殊含义，且会抛出异常。整数
     值 `options' 无效。`pid' 可以指向任何 ID 已知的进程，不一定是子进程
     。调用 *note spawn*: 1f55. 函数时传入 *note P_NOWAIT: 1fc0. 将返回
     合适的进程句柄。

     在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此函
     数现在会重试系统调用，而不是触发 *note InterruptedError: 662. 异常
     (原因详见 PEP 475(3))。

 -- 函数: os.wait3 (options)

     与 *note waitpid(): 676. 相似，差别在于没有进程 ID 参数，且返回一个
     3 元组，其中包括子进程 ID，退出状态指示和资源使用信息。关于资源使用
     信息的详情，请参考 *note resource: e1.*note getrusage(): da1.。
     option 参数与传入 *note waitpid(): 676. 和 *note wait4(): 673. 的相
     同。

     *note 可用性: 136f.: Unix。

 -- 函数: os.wait4 (pid, options)

     与 *note waitpid(): 676. 相似，差别在本方法返回一个 3 元组，其中包
     括子进程 ID，退出状态指示和资源使用信息。关于资源使用信息的详情，请
     参考 *note resource: e1.*note getrusage(): da1.。*note wait4():
     673. 的参数与 *note waitpid(): 676. 的参数相同。

     *note 可用性: 136f.: Unix。

 -- 数据: os.WNOHANG

     用于 *note waitpid(): 676. 的选项，如果没有立即可用的子进程状态，则
     立即返回。在这种情况下，函数返回 ‘(0, 0)’。

     *note 可用性: 136f.: Unix。

 -- 数据: os.WCONTINUED

     被任务控制 (job control) 停止的子进程，如果上次报告状态后已恢复运行
     ，则此选项将报告这些子进程。

     *note 可用性: 136f.: 部分 Unix 系统。

 -- 数据: os.WUNTRACED

     已停止的子进程，如果自停止以来尚未报告其当前状态，则此选项将报告这
     些子进程。

     *note 可用性: 136f.: Unix。

下列函数采用进程状态码作为参数，状态码由 *note system(): dc9.、*note
wait(): 674. 或 *note waitpid(): 676. 返回。它们可用于确定进程上发生的操
作。

 -- 函数: os.WCOREDUMP (status)

     如果为该进程生成了核心转储，返回 ‘True’，否则返回 ‘False’。

     此函数应当仅在 *note WIFSIGNALED(): 1fd4. 为真值时使用。

     *note 可用性: 136f.: Unix。

 -- 函数: os.WIFCONTINUED (status)

     如果一个已停止的子进程通过传送 *note SIGCONT: 1fd6. 获得恢复（如果
     该进程是从任务控制停止后再继续的）则返回 ‘True’，否则返回 ‘False’。

     参见 *note WCONTINUED: 1fcb. 选项。

     *note 可用性: 136f.: Unix。

 -- 函数: os.WIFSTOPPED (status)

     如果进程是通过传送一个信号来停止的则返回 ‘True’，否则返回 ‘False’。

     *note WIFSTOPPED(): 1fd7. 只有在当 *note waitpid(): 676. 调用是通过
     使用 *note WUNTRACED: 1fd2. 选项来完成或者当该进程正被追踪时 (参见
     ‘ptrace(2)’) 才返回 ‘True’。

     *note 可用性: 136f.: Unix。

 -- 函数: os.WIFSIGNALED (status)

     如果进程是通过一个信号来终止的则返回 ‘True’ ，否则返回 ‘False’。

     *note 可用性: 136f.: Unix。

 -- 函数: os.WIFEXITED (status)

     如果进程正常终止退出则返回 ‘True’，也就是说通过调用 ‘exit()’ 或
     ‘_exit()’，或者通过从 ‘main()’ 返回；在其他情况下则返回 ‘False’。

     *note 可用性: 136f.: Unix。

 -- 函数: os.WEXITSTATUS (status)

     返回进程退出状态。

     此函数应当仅在 *note WIFEXITED(): 1fd8. 为真值时使用。

     *note 可用性: 136f.: Unix。

 -- 函数: os.WSTOPSIG (status)

     返回导致进程停止的信号。

     此函数应当仅在 *note WIFSTOPPED(): 1fd7. 为真值时使用。

     *note 可用性: 136f.: Unix。

 -- 函数: os.WTERMSIG (status)

     返回导致进程终止的信号的编号。

     此函数应当仅在 *note WIFSIGNALED(): 1fd4. 为真值时使用。

     *note 可用性: 136f.: Unix。

   ---------- Footnotes ----------

   (1) https://msdn.microsoft.com/44228cf2-6306-466c-8f16-f513cd3ba8b5

   (2) 
https://docs.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-getprocesstimes

   (3) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: 调度器接口,  Next: 其他系统信息,  Prev: 进程管理,  Up: os --- 多种操作系统接口

5.16.1.10 调度器接口
....................

这些函数控制操作系统如何为进程分配 CPU 时间。 它们仅在某些 Unix 平台上可
用。 更多细节信息请查阅你所用 Unix 的指南页面。

3.3 新版功能.

以下调度策略如果被操作系统支持就会对外公开。

 -- 数据: os.SCHED_OTHER

     默认调度策略。

 -- 数据: os.SCHED_BATCH

     用于 CPU 密集型进程的调度策略，它会尽量为计算机中的其余任务保留交互
     性。

 -- 数据: os.SCHED_IDLE

     用于极低优先级的后台任务的调度策略。

 -- 数据: os.SCHED_SPORADIC

     用于偶发型服务程序的调度策略。

 -- 数据: os.SCHED_FIFO

     先进先出的调度策略。

 -- 数据: os.SCHED_RR

     循环式的调度策略。

 -- 数据: os.SCHED_RESET_ON_FORK

     此旗标可与任何其他调度策略进行 OR 运算。 当带有此旗标的进程设置分叉
     时，其子进程的调度策略和优先级会被重置为默认值。

 -- 类: os.sched_param (sched_priority)

     这个类表示在 *note sched_setparam(): a5e, *note
     sched_setscheduler(): a5f. 和 *note sched_getparam(): a5a. 中使用的
     可修改调度形参。 它属于不可变对象。

     目前它只有一个可能的形参：

      -- 属性: sched_priority

          一个调度策略的调度优先级。

 -- 函数: os.sched_get_priority_min (policy)

     获取 `policy' 的最低优先级数值。 `policy' 是以上调度策略常量之一。

 -- 函数: os.sched_get_priority_max (policy)

     获取 `policy' 的最高优先级数值。 `policy' 是以上调度策略常量之一。

 -- 函数: os.sched_setscheduler (pid, policy, param)

     设置 PID 为 `pid' 的进程的调度策略。`pid' 为 0 指的是调用本方法的进
     程。`policy' 是以上调度策略常量之一。`param' 是一个 *note
     sched_param: 1fb8. 实例。

 -- 函数: os.sched_getscheduler (pid)

     返回 PID 为 `pid' 的进程的调度策略。`pid' 为 0 指的是调用本方法的进
     程。返回的结果是以上调度策略常量之一。

 -- 函数: os.sched_setparam (pid, param)

     设置 PID 为 `pid' 的进程的某个调度参数。`pid' 为 0 指的是调用本方法
     的进程。`param' 是一个 *note sched_param: 1fb8. 实例。

 -- 函数: os.sched_getparam (pid)

     返回 PID 为 `pid' 的进程的调度参数为一个 *note sched_param: 1fb8. 实
     例。`pid' 为 0 指的是调用本方法的进程。

 -- 函数: os.sched_rr_get_interval (pid)

     返回 PID 为 `pid' 的进程在时间片轮转调度下的时间片长度（单位为秒）
     。`pid' 为 0 指的是调用本方法的进程。

 -- 函数: os.sched_yield ()

     自愿放弃 CPU。

 -- 函数: os.sched_setaffinity (pid, mask)

     将 PID 为 `pid' 的进程（为零则为当前进程）限制到一组 CPU 上。`mask'
     是整数的可迭代对象，表示应将进程限制在其中的一组 CPU。

 -- 函数: os.sched_getaffinity (pid)

     返回 PID 为 `pid' 的进程（为零则为当前进程）被限制到的那一组 CPU。


File: python.info,  Node: 其他系统信息,  Next: 随机数<2>,  Prev: 调度器接口,  Up: os --- 多种操作系统接口

5.16.1.11 其他系统信息
......................

 -- 函数: os.confstr (name)

     返回字符串格式的系统配置信息。`name' 指定要查找的配置名称，它可以是
     字符串，是一个系统已定义的名称，这些名称定义在不同标准（POSIX，Unix
     95，Unix 98 等）中。一些平台还定义了额外的其他名称。当前操作系统已
     定义的名称在 ‘confstr_names’ 字典的键中给出。对于未包含在该映射中的
     配置名称，也可以传递一个整数作为 `name'。

     如果 `name' 指定的配置值未定义，返回 ‘None’。

     如果 `name' 是一个字符串且不是已定义的名称，将抛出 *note
     ValueError: 1fc. 异常。如果当前系统不支持 `name' 指定的配置名称，即
     使该名称存在于 ‘confstr_names’，也会抛出 *note OSError: 1d4. 异常，
     错误码为 *note errno.EINVAL: fd9.。

     *note 可用性: 136f.: Unix。

 -- 数据: os.confstr_names

     字典，表示映射关系，为 *note confstr(): 1fe7. 可接受名称与操作系统
     为这些名称定义的整数值之间的映射。这可用于判断系统已定义了哪些名称
     。

     *note 可用性: 136f.: Unix。

 -- 函数: os.cpu_count ()

     返回系统的 CPU 数量。不确定则返回 ‘None’。

     该数量不同于当前进程可以使用的CPU数量。可用的CPU数量可以由
     ‘len(os.sched_getaffinity(0))’ 方法获得。

     3.4 新版功能.

 -- 函数: os.getloadavg ()

     返回系统运行队列中最近 1、5 和 15 分钟内的平均进程数。无法获得平均
     负载则抛出 *note OSError: 1d4. 异常。

     *note 可用性: 136f.: Unix。

 -- 函数: os.sysconf (name)

     返回整数格式的系统配置信息。如果 `name' 指定的配置值未定义，返回
     ‘-1’。对 *note confstr(): 1fe7. 的 `name' 参数的注释在此处也适用。
     当前已知的配置名称在 ‘sysconf_names’ 字典中提供。

     *note 可用性: 136f.: Unix。

 -- 数据: os.sysconf_names

     字典，表示映射关系，为 *note sysconf(): 1f46. 可接受名称与操作系统
     为这些名称定义的整数值之间的映射。这可用于判断系统已定义了哪些名称
     。

     *note 可用性: 136f.: Unix。

以下数据值用于支持对路径本身的操作。所有平台都有定义。

对路径的高级操作在 *note os.path: c6. 模块中定义。

 -- 数据: os.curdir

     操作系统用来表示当前目录的常量字符串。在 Windows 和 POSIX 上是
     ‘'.'’。在 *note os.path: c6. 中也可用。

 -- 数据: os.pardir

     操作系统用来表示父目录的常量字符串。在 Windows 和 POSIX 上是
     ‘'..'’。在 *note os.path: c6. 中也可用。

 -- 数据: os.sep

     操作系统用来分隔路径不同部分的字符。在 POSIX 上是 ‘'/'’，在 Windows
     上是是 ‘'\\'’。注意，仅了解它不足以能解析或连接路径，请使用 *note
     os.path.split(): 1bfc. 和 *note os.path.join(): f6c.，但它有时是有
     用的。在 *note os.path: c6. 中也可用。

 -- 数据: os.altsep

     操作系统用来分隔路径不同部分的替代字符。如果仅存在一个分隔符，则为
     ‘None’。在 ‘sep’ 是反斜杠的 Windows 系统上，该值被设为 ‘'/'’。在
     *note os.path: c6. 中也可用。

 -- 数据: os.extsep

     分隔基本文件名与扩展名的字符，如 ‘os.py’ 中的 ‘'.'’。在 *note
     os.path: c6. 中也可用。

 -- 数据: os.pathsep

     操作系统通常用于分隔搜索路径（如 ‘PATH’）中不同部分的字符，如 POSIX
     上是 ‘':'’，Windows 上是 ‘';'’。在 *note os.path: c6. 中也可用。

 -- 数据: os.defpath

     在环境变量没有 ‘'PATH'’ 键的情况下，*note exec*p*: 1f99. and *note
     spawn*p*: 1f55. 使用的默认搜索路径。在 *note os.path: c6. 中也可用
     。

 -- 数据: os.linesep

     当前平台用于分隔（或终止）行的字符串。它可以是单个字符，如 POSIX 上
     是 ‘'\n'’，也可以是多个字符，如 Windows 上是 ‘'\r\n'’。在写入以文本
     模式（默认模式）打开的文件时，请不要使用 `os.linesep' 作为行终止符
     ，请在所有平台上都使用一个 ‘'\n'’ 代替。

 -- 数据: os.devnull

     空设备的文件路径。如 POSIX 上为 ‘'/dev/null'’，Windows 上为
     ‘'nul'’。在 *note os.path: c6. 中也可用。

 -- 数据: os.RTLD_LAZY
 -- 数据: os.RTLD_NOW
 -- 数据: os.RTLD_GLOBAL
 -- 数据: os.RTLD_LOCAL
 -- 数据: os.RTLD_NODELETE
 -- 数据: os.RTLD_NOLOAD
 -- 数据: os.RTLD_DEEPBIND

     *note setdlopenflags(): a6e. 和 *note getdlopenflags(): e56. 函数所
     使用的标志。请参阅 Unix 手册页 ‘dlopen(3)’ 获取不同标志的含义。

     3.3 新版功能.


File: python.info,  Node: 随机数<2>,  Prev: 其他系统信息,  Up: os --- 多种操作系统接口

5.16.1.12 随机数
................

 -- 函数: os.getrandom (size, flags=0)

     获得最多为 `size' 的随机字节。本函数返回的字节数可能少于请求的字节
     数。

     这些字节可用于为用户空间的随机数生成器提供种子，或用于加密目的。

     ‘getrandom()’ 依赖于从设备驱动程序和其他环境噪声源收集的熵。不必要
     地读取大量数据将对使用 ‘/dev/random’ 和 ‘/dev/urandom’ 设备的其他用
     户产生负面影响。

     flags 参数是一个位掩码，可以是零个或多个下列值以或运算组合： *note
     os.GRND_RANDOM: 1fed. 和 *note GRND_NONBLOCK: 1fee.。

     另请参阅 Linux getrandom() 手册页(1) 。

     *note 可用性: 136f.：Linux 3.17 或更高版本。

     3.6 新版功能.

 -- 函数: os.urandom (size)

     返回大小为 `size' 的字符串，它是适合加密使用的随机字节。

     本函数从系统指定的随机源获取随机字节。对于加密应用程序，返回的数据
     应有足够的不可预测性，尽管其确切的品质取决于操作系统的实现。

     在 Linux 上，如果 ‘getrandom()’ 系统调用可用，它将以阻塞模式使用：
     阻塞直到系统的 urandom 熵池初始化完毕（内核收集了 128 位熵）。原理
     请参阅 PEP 524(2)。在 Linux 上，*note getrandom(): 572. 可以以非阻
     塞模式（使用 *note GRND_NONBLOCK: 1fee. 标志）获取随机字节，或者轮
     询直到系统的 urandom 熵池初始化完毕。

     在类 Unix 系统上，随机字节是从 ‘/dev/urandom’ 设备读取的。如果
     ‘/dev/urandom’ 设备不可用或不可读，则抛出 *note
     NotImplementedError: 617. 异常。

     在 Windows 上将使用 ‘CryptGenRandom()’。

     参见
     ....

     *note secrets: e5. 模块提供了更高级的功能。所在平台会提供随机数生成
     器，有关其易于使用的接口，请参阅 *note random.SystemRandom: 1b19.。

     在 3.6.0 版更改: 在 Linux 上，‘getrandom()’ 现在以阻塞模式使用，以
     提高安全性。

     在 3.5.2 版更改: 在 Linux 上，如果 ‘getrandom()’ 系统调用阻塞（
     urandom 熵池尚未初始化完毕），则退回一步读取 ‘/dev/urandom’。

     在 3.5 版更改: 在 Linux 3.17 和更高版本上，现在使用 ‘getrandom()’ 系
     统调用（如果可用）。在 OpenBSD 5.6 和更高版本上，现在使用
     ‘getentropy()’ C 函数。这些函数避免了使用内部文件描述符。

 -- 数据: os.GRND_NONBLOCK

     默认情况下，从 ‘/dev/random’ 读取时，如果没有可用的随机字节，则
     *note getrandom(): 572. 会阻塞；从 ‘/dev/urandom’ 读取时，如果熵池
     尚未初始化，则会阻塞。

     如果设置了 *note GRND_NONBLOCK: 1fee. 标志，则这些情况下 *note
     getrandom(): 572. 不会阻塞，而是立即抛出 *note BlockingIOError:
     99f. 异常。

     3.6 新版功能.

 -- 数据: os.GRND_RANDOM

     如果设置了此标志位，那么将从 ‘/dev/random’ 池而不是 ‘/dev/urandom’
     池中提取随机字节。

     3.6 新版功能.

   ---------- Footnotes ----------

   (1) http://man7.org/linux/man-pages/man2/getrandom.2.html

   (2) https://www.python.org/dev/peps/pep-0524


File: python.info,  Node: io --- 处理流的核心工具,  Next: time --- 时间的访问和转换,  Prev: os --- 多种操作系统接口,  Up: 通用操作系统服务

5.16.2 ‘io’ — 处理流的核心工具
------------------------------

`源代码:' Lib/io.py(1)

__________________________________________________________________

* Menu:

* 概述: 概述<8>.
* 高阶模块接口::
* 类的层次结构::
* 性能: 性能<3>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/io.py


File: python.info,  Node: 概述<8>,  Next: 高阶模块接口,  Up: io --- 处理流的核心工具

5.16.2.1 概述
.............

*note io: a2. 模块提供了 Python 用于处理各种 I/O 类型的主要工具。三种主
要的 I/O类型分别为: `文本 I/O', `二进制 I/O' 和 `原始 I/O'。这些是泛型类
型，有很多种后端存储可以用在他们上面。一个隶属于任何这些类型的具体对象被
称作 *note file object: b4a.。 其他同类的术语还有 `流' 和 `类文件对象'。

独立于其类别，每个具体流对象也将具有各种功能：它可以是只读，只写或读写。
它还可以允许任意随机访问（向前或向后寻找任何位置），或仅允许顺序访问（例
如在套接字或管道的情况下）。

所有流对提供给它们的数据类型都很敏感。例如将 *note str: 339. 对象给二进
制流的 ‘write()’ 方法会引发 *note TypeError: 193.。将 *note bytes: 33a.
对象提供给文本流的 ‘write()’ 方法也是如此。

在 3.3 版更改: 由于 *note IOError: 99a. 现在是 *note OSError: 1d4. 的别
名，因此用于引发 *note IOError: 99a. 的操作现在会引发 *note OSError:
1d4. 。

* Menu:

* 文本 I/O::
* 二进制 I/O::
* 原始 I/O::


File: python.info,  Node: 文本 I/O,  Next: 二进制 I/O,  Up: 概述<8>

5.16.2.2 文本 I/O
.................

文本I/O预期并生成 *note str: 339. 对象。这意味着，无论何时后台存储是由字
节组成的（例如在文件的情况下），数据的编码和解码都是透明的，并且可以选择
转换特定于平台的换行符。

创建文本流的最简单方法是使用 *note open(): 4f8.，可以选择指定编码：

     f = open("myfile.txt", "r", encoding="utf-8")

内存中文本流也可以作为 *note StringIO: 836. 对象使用：

     f = io.StringIO("some initial text data")

*note TextIOBase: c41. 的文档中详细描述了文本流的API


File: python.info,  Node: 二进制 I/O,  Next: 原始 I/O,  Prev: 文本 I/O,  Up: 概述<8>

5.16.2.3 二进制 I/O
...................

二进制I/O（也称为缓冲I/O）预期 *note bytes-like objects: 5f1. 并生成
*note bytes: 33a. 对象。不执行编码、解码或换行转换。这种类型的流可以用于
所有类型的非文本数据，并且还可以在需要手动控制文本数据的处理时使用。

创建二进制流的最简单方法是使用 *note open(): 4f8.，并在模式字符串中指定
‘'b'’ ：

     f = open("myfile.jpg", "rb")

内存中二进制流也可以作为 *note BytesIO: 7a4. 对象使用：

     f = io.BytesIO(b"some initial binary data: \x00\x01")

*note BufferedIOBase: 591. 的文档中详细描述了二进制流 API。

其他库模块可以提供额外的方式来创建文本或二进制流。参见 *note
socket.socket.makefile(): b21. 的示例。


File: python.info,  Node: 原始 I/O,  Prev: 二进制 I/O,  Up: 概述<8>

5.16.2.4 原始 I/O
.................

原始 I/O（也称为 `非缓冲 I/O'）通常用作二进制和文本流的低级构建块。用户
代码直接操作原始流的用法非常罕见。不过，可以通过在禁用缓冲的情况下以二进
制模式打开文件来创建原始流：

     f = open("myfile.jpg", "rb", buffering=0)

*note RawIOBase: a1b. 的文档中详细描述了原始流的API


File: python.info,  Node: 高阶模块接口,  Next: 类的层次结构,  Prev: 概述<8>,  Up: io --- 处理流的核心工具

5.16.2.5 高阶模块接口
.....................

 -- 数据: io.DEFAULT_BUFFER_SIZE

     包含模块缓冲 I/O 类使用的默认缓冲区大小的 int。 在可能的情况下
     *note open(): 4f8. 将使用文件的 blksize（由 *note os.stat(): 1f2. 获
     得）。

 -- 函数: io.open (file, mode='r', buffering=-1, encoding=None,
          errors=None, newline=None, closefd=True, opener=None)

     这是内置的 *note open(): 4f8. 函数的别名。

     ‘open’ 附带参数 ‘path’、‘mode’、‘flags’ 会引发 *note 审计事件:
     ea1.。

 -- 函数: io.open_code (path)

     以 ‘'rb'’ 模式打开提供的文件。如果目的是将文件内容做为可执行代码，
     则应使用此函数。

     ‘path’ 应当为 *note str: 339. 类型并且是一个绝对路径。

     此函数的行为可以由对 *note PyFile_SetOpenCodeHook(): 1ff6. 的先期调
     用所重载。 但是，如果 ‘path’ 为 *note str: 339. 类型并且是一个绝对
     路径，‘open_code(path)’ 的行为应当总是与 ‘open(path, 'rb')’ 一致。
     重载此行为的目的是为了给文件附加额外的验证或预处理。

     3.8 新版功能.

 -- 例外: io.BlockingIOError

     这是内置的 *note BlockingIOError: 99f. 异常的兼容性别名。

 -- 例外: io.UnsupportedOperation

     在流上调用不支持的操作时引发的继承 *note OSError: 1d4. 和 *note
     ValueError: 1fc. 的异常。

参见
....

*note sys: fe.

     包含标准IO流: *note sys.stdin: 316, *note sys.stdout: 317. 和 *note
     sys.stderr: 318. 。


File: python.info,  Node: 类的层次结构,  Next: 性能<3>,  Prev: 高阶模块接口,  Up: io --- 处理流的核心工具

5.16.2.6 类的层次结构
.....................

I/O 流被安排为按类的层次结构实现。 首先是 *note 抽象基类: b3b. (ABC)，用
于指定流的各种类别，然后是提供标准流实现的具体类。

          注解: 抽象基类还提供某些方法的默认实现，以帮助实现具体的流类。
          例如 *note BufferedIOBase: 591. 提供了 ‘readinto()’ 和 *note
          readline(): 1713. 的未优化实现。

I/O层次结构的顶部是抽象基类 *note IOBase: 1dc. 。它定义了流的基本接口。
但是请注意，对流的读取和写入之间没有分离。如果实现不支持指定的操作，则会
引发 *note UnsupportedOperation: 1ff8. 。

抽象基类 *note RawIOBase: a1b. 是 *note IOBase: 1dc. 的子类。它负责将字
节读取和写入流中。 *note RawIOBase: a1b. 的子类 *note FileIO: cac. 提供
计算机文件系统中文件的接口。

抽象基类 *note BufferedIOBase: 591. 处理原始字节流（ *note RawIOBase:
a1b. ）上的缓冲。其子类 *note BufferedWriter: 160d. 、 *note
BufferedReader: b92. 和 *note BufferedRWPair: 1ffa. 缓冲流是可读、可写以
及可读写的。 *note BufferedRandom: 160e. 为随机访问流提供缓冲接口。
*note BufferedIOBase: 591. 的另一个子类 *note BytesIO: 7a4. 是内存中字节
流。

抽象基类 *note TextIOBase: c41. 是 *note IOBase: 1dc. 的另一个子类，它处
理字节表示文本的流，并处理字符串之间的编码和解码。其一个子类 *note
TextIOWrapper: 5fc. 是原始缓冲流（ *note BufferedIOBase: 591. ）的缓冲文
本接口。另一个子类 *note StringIO: 836. 用于文本的内存流。

参数名不是规范的一部分，只有 *note open(): 4f8. 的参数才用作关键字参数。

下表总结了抽象基类提供的 *note io: a2. 模块：

抽象基类                      继承                   抽象方法                     Mixin方法和属性
                                                                                  
-----------------------------------------------------------------------------------------------------------------------------------------
                                                                                  
*note IOBase: 1dc.                                   ‘fileno’, ‘seek’, 和         ‘close’, ‘closed’, ‘__enter__’, ‘__exit__’, ‘flush’,
                                                     ‘truncate’                   ‘isatty’, ‘__iter__’, ‘__next__’, ‘readable’,
                                                                                  ‘readline’, ‘readlines’, ‘seekable’, ‘tell’,
                                                                                  ‘writable’ 和 ‘writelines’
                                                                                  
                                                                                  
*note RawIOBase: a1b.         *note IOBase: 1dc.     ‘readinto’ 和 ‘write’        继承 *note IOBase: 1dc. 方法, ‘read’, 和 ‘readall’
                                                                                  
                                                                                  
*note BufferedIOBase: 591.    *note IOBase: 1dc.     ‘detach’, ‘read’, ‘read1’,   继承 *note IOBase: 1dc. 方法, ‘readinto’, 和
                                                     和 ‘write’                   ‘readinto1’
                                                                                  
                                                                                  
*note TextIOBase: c41.        *note IOBase: 1dc.     ‘detach’, ‘read’,            继承 *note IOBase: 1dc. 方法, ‘encoding’, ‘errors’,
                                                     ‘readline’, 和 ‘write’       和 ‘newlines’
                                                                                  

* Menu:

* I/O 基类::
* 原始文件 I/O::
* 缓冲流::
* 文本 I/O: 文本 I/O<2>.


File: python.info,  Node: I/O 基类,  Next: 原始文件 I/O,  Up: 类的层次结构

5.16.2.7 I/O 基类
.................

 -- 类: io.IOBase

     所有 I/O 类的抽象基类，作用于字节流。没有公共构造函数。

     此类为许多方法提供了空的抽象实现，派生类可以有选择地重写。默认实现
     代表一个无法读取、写入或查找的文件。

     尽管 *note IOBase: 1dc. 没有声明 ‘read()’ 或 ‘write()’ ，因为它们的
     签名会有所不同，但是实现和客户端应该将这些方法视为接口的一部分。此
     外，当调用不支持的操作时可能会引发 *note ValueError: 1fc. （或
     *note UnsupportedOperation: 1ff8. ）。

     从文件读取或写入文件的二进制数据的基本类型为 *note bytes: 33a. 。其
     他 *note bytes-like objects: 5f1. 也可以作为方法参数。文本I/O类使用
     *note str: 339. 数据。

     请注意，在关闭的流上调用任何方法（甚至查询）都是未定义的（
     undefined）。在这种情况下，实现可能会引发 *note ValueError: 1fc. 。

     *note IOBase: 1dc. （及其子类）支持迭代器协议，这意味着可以迭代
     *note IOBase: 1dc. 对象以产生流中的行。根据流是二进制流（产生字节）
     还是文本流（产生字符串），行的定义略有不同。请参见下面的 *note
     readline(): 1713. 。

     *note IOBase: 1dc. 也是一个上下文管理器，因此支持 *note with: 6f2.
     语句。 在这个示例中，`file' 将在 ‘with’ 语句块执行完成之后被关闭 —
     即使是发生了异常:

          with open('spam.txt', 'w') as file:
              file.write('Spam and eggs!')

     *note IOBase: 1dc. 提供以下数据属性和方法：

      -- 方法: close ()

          刷新并关闭此流。如果文件已经关闭，则此方法无效。文件关闭后，对
          文件的任何操作（例如读取或写入）都会引发 *note ValueError:
          1fc. 。

          为方便起见，允许多次调用此方法。但是，只有第一个调用才会生效。

      -- 属性: closed

          如果流已关闭，则返回 True。

      -- 方法: fileno ()

          返回流的底层文件描述符（整数）—如果存在。如果 IO 对象不使用文
          件描述符，则会引发 *note OSError: 1d4. 。

      -- 方法: flush ()

          刷新流的写入缓冲区（如果适用）。这对只读和非阻塞流不起作用。

      -- 方法: isatty ()

          如果流是交互式的（即连接到终端/tty设备），则返回 ‘True’ 。

      -- 方法: readable ()

          如果可以读取流，则返回 ‘True’ 。否则为 ‘False’ ，且 ‘read()’ 将
          引发 *note OSError: 1d4. 错误。

      -- 方法: readline (size=-1)

          从流中读取并返回一行。如果指定了 `size'，将至多读取 `size' 个
          字节。

          对于二进制文件行结束符总是 ‘b'\n'’；对于文本文件，可以用将
          `newline' 参数传给 *note open(): 4f8. 的方式来选择要识别的行结
          束符。

      -- 方法: readlines (hint=-1)

          从流中读取并返回包含多行的列表。可以指定 `hint' 来控制要读取的
          行数：如果（以字节/字符数表示的）所有行的总大小超出了 `hint' 则
          将不会读取更多的行。

          请注意使用 ‘for line in file: ...’ 就足够对文件对象进行迭代了
          ，可以不必调用 ‘file.readlines()’。

      -- 方法: seek (offset, whence=SEEK_SET)

          将流位置修改到给定的字节 `offset'。 `offset' 将相对于由
          `whence' 指定的位置进行解析。 `whence' 的默认值为 ‘SEEK_SET’。
          `whence' 的可用值有：

             * ‘SEEK_SET’ 或 ‘0’ – 流的开头（默认值）；`offset' 应为零或
               正值

             * ‘SEEK_CUR’ or ‘1’ – 当前流位置；`offset' 可以为负值

             * ‘SEEK_END’ or ‘2’ – 流的末尾；`offset' 通常为负值

          返回新的绝对位置。

          3.1 新版功能: ‘SEEK_*’ 常量.

          3.3 新版功能: 某些操作系统还可支持其他的值，例如
          ‘os.SEEK_HOLE’ 或 ‘os.SEEK_DATA’。特定文件的可用值还会取决于它
          是以文本还是二进制模式打开。

      -- 方法: seekable ()

          如果流支持随机访问则返回 ‘True’。 如为 ‘False’，则 *note
          seek(): 1da7, *note tell(): 1da8. 和 *note truncate(): cad. 将
          引发 *note OSError: 1d4.。

      -- 方法: tell ()

          返回当前流的位置。

      -- 方法: truncate (size=None)

          将流的大小调整为给定的 `size' 个字节（如果未指定 `size' 则调整
          至当前位置）。 当前的流位置不变。 这个调整操作可扩展或减小当前
          文件大小。 在扩展的情况下，新文件区域的内容取决于具体平台（在
          大多数系统上，额外的字节会填充为零）。 返回新的文件大小。

          在 3.5 版更改: 现在Windows在扩展时将文件填充为零。

      -- 方法: writable ()

          如果流支持写入则返回 ‘True’。 如为 ‘False’，则 ‘write()’ 和
          *note truncate(): cad. 将引发 *note OSError: 1d4.。

      -- 方法: writelines (lines)

          将行列表写入到流。 不会添加行分隔符，因此通常所提供的每一行都
          带有末尾行分隔符。

      -- 方法: __del__ ()

          为对象销毁进行准备。 *note IOBase: 1dc. 提供了此方法的默认实现
          ，该实现会调用实例的 *note close(): 101e. 方法。

 -- 类: io.RawIOBase

     原始二进制 I/O 的基类。 它继承自 *note IOBase: 1dc.。 没有公共构造
     器。

     原始二进制 I/O 通常提供对下层 OS 设备或 API 的低层级访问，而不尝试
     将其封装到高层级的基元中（这是留给缓冲 I/O 和 Text I/O 的，将在下文
     中描述）。

     在 *note IOBase: 1dc. 的属性和方法之外，*note RawIOBase: a1b. 还提
     供了下列方法:

      -- 方法: read (size=-1)

          从对象中读取 `size' 个字节并将其返回。 作为一个便捷选项，如果
          `size' 未指定或为 -1，则返回所有字节直到 EOF。 在其他情况下，
          仅会执行一次系统调用。 如果操作系统调用返回字节数少于 `size' 则
          此方法也可能返回少于 `size' 个字节。

          如果返回 0 个字节而 `size' 不为零 0，这表明到达文件末尾。 如果
          处于非阻塞模式并且没有更多字节可用，则返回 ‘None’。

          默认实现会转至 *note readall(): 2001. 和 *note readinto():
          70c.。

      -- 方法: readall ()

          从流中读取并返回所有字节直到 EOF，如有必要将对流执行多次调用。

      -- 方法: readinto (b)

          将字节数据读入预先分配的可写 *note bytes-like object: 5f1.
          `b'，并返回所读取的字节数。 例如，`b' 可以是一个 *note
          bytearray: 33b.。 如果对象处理非阻塞模式并且没有更多字节可用，
          则返回 ‘None’。

      -- 方法: write (b)

          将给定的 *note bytes-like object: 5f1. `b' 写入到下层的原始流
          ，并返回所写入的字节数。 这可以少于 `b' 的总字节数，具体取决于
          下层原始流的设定，特别是如果它处于非阻塞模式的话。 如果原始流
          设为非阻塞并且不能真正向其写入单个字节时则返回 ‘None’。 调用者
          可以在此方法返回后释放或改变 `b'，因此该实现应该仅在方法调用期
          间访问 `b'。

 -- 类: io.BufferedIOBase

     支持某种缓冲的二进制流的基类。 它继承自 *note IOBase: 1dc.。 没有公
     共构造器。

     与 *note RawIOBase: a1b. 的主要差别在于 *note read(): 1d67, *note
     readinto(): 2003. 和 *note write(): 592. 等方法将（分别）尝试按照要
     求读取尽可能多的输入或是耗尽所有给定的输出，其代价是可能会执行一次
     以上的系统调用。

     除此之外，那些方法还可能引发 *note BlockingIOError: 99f.，如果下层
     的原始数据流处于非阻塞模式并且无法接受或给出足够数据的话；不同于对
     应的 *note RawIOBase: a1b. 方法，它们将永远不会返回 ‘None’。

     并且，*note read(): 1d67. 方法也没有转向 *note readinto(): 2003. 的
     默认实现。

     典型的 *note BufferedIOBase: 591. 实现不应当继承自 *note RawIOBase:
     a1b. 实现，而要包装一个该实现，正如 *note BufferedWriter: 160d. 和
     *note BufferedReader: b92. 所做的那样。

     *note BufferedIOBase: 591. 在 *note IOBase: 1dc. 的现有成员以外还提
     供或重载了下列方法和属性:

      -- 属性: raw

          由 *note BufferedIOBase: 591. 处理的下层原始流 (*note
          RawIOBase: a1b. 的实例)。 它不是 *note BufferedIOBase: 591.
          API 的组成部分并且不存在于某些实现中。

      -- 方法: detach ()

          从缓冲区分离出下层原始流并将其返回。

          在原始流被分离之后，缓冲区将处于不可用的状态。

          某些缓冲区例如 *note BytesIO: 7a4. 并无可从此方法返回的单独原
          始流的概念。 它们将会引发 *note UnsupportedOperation: 1ff8.。

          3.1 新版功能.

      -- 方法: read (size=-1)

          读取并返回最多 `size' 个字节。 如果此参数被省略、为 ‘None’ 或
          为负值，则读取并返回所有数据直到 EOF。 如果流已经到达 EOF 则返
          回一个空的 *note bytes: 33a. 对象。

          如果此参数为正值，并且下层原始流不可交互，则可能发起多个原始读
          取以满足字节计数（直至先遇到 EOF）。 但对于可交互原始流，则将
          至多发起一个原始读取，并且简短的结果并不意味着已到达 EOF。

          *note BlockingIOError: 99f. 会在下层原始流不处于阻塞模式，并且
          当前没有可用数据时被引发。

      -- 方法: read1 ([size])

          通过至多一次对下层流的 *note read(): 70b. (或 *note
          readinto(): 70c.) 方法的调用读取并返回至多 `size' 个字节。 这
          适用于在 *note BufferedIOBase: 591. 对象之上实现你自己的缓冲区
          的情况。

          如果 `size' 为 ‘-1’ (默认值)，则返回任意数量的字节（多于零字节
          ，除非已到达 EOF）。

      -- 方法: readinto (b)

          将字节数据读入预先分配的可写 *note bytes-like object: 5f1. `b'
          并返回所读取的字节数。 例如，`b' 可以是一个 *note bytearray:
          33b.。

          类似于 *note read(): 1d67.，可能对下层原始流发起多次读取，除非
          后者为交互式。

          *note BlockingIOError: 99f. 会在下层原始流不处于阻塞模式，并且
          当前没有可用数据时被引发。

      -- 方法: readinto1 (b)

          将字节数据读入预先分配的可写 *note bytes-like object: 5f1.
          `b'，其中至多使用一次对下层原始流 *note read(): 70b. (或 *note
          readinto(): 70c.) 方法的调用。 返回所读取的字节数。

          *note BlockingIOError: 99f. 会在下层原始流不处于阻塞模式，并且
          当前没有可用数据时被引发。

          3.5 新版功能.

      -- 方法: write (b)

          写入给定的 *note bytes-like object: 5f1. `b'，并返回写入的字节
          数 (总是等于 `b' 的字节长度，因为如果写入失败则会引发 *note
          OSError: 1d4.)。 根据具体实现的不同，这些字节可能被实际写入下
          层流，或是出于运行效率和冗余等考虑而暂存于缓冲区。

          当处于非阻塞模式时，如果需要将数据写入原始流但它无法在不阻塞的
          情况下接受所有数据则将引发 *note BlockingIOError: 99f.。

          调用者可能会在此方法返回后释放或改变 `b'，因此该实现应当仅在方
          法调用期间访问 `b'。


File: python.info,  Node: 原始文件 I/O,  Next: 缓冲流,  Prev: I/O 基类,  Up: 类的层次结构

5.16.2.8 原始文件 I/O
.....................

 -- 类: io.FileIO (name, mode='r', closefd=True, opener=None)

     *note FileIO: cac. 代表在 OS 层级上包含文件的字节数据。 它实现了
     *note RawIOBase: a1b. 接口（因而也实现了 *note IOBase: 1dc. 接口）
     。

     `name' 可以是以下两项之一：

        * 代表将被打开的文件路径的字符串或 *note bytes: 33a. 对象。 在此
          情况下 closefd 必须为 ‘True’ (默认值) 否则将会引发异常。

        * 代表一个现有 OS 层级文件描述符的号码的整数，作为结果的 *note
          FileIO: cac. 对象将可访问该文件。 当 FileIO 对象被关闭时此 fd
          也将被关闭，除非 `closefd' 设为 ‘False’。

     `mode' 可以为 ‘'r'’, ‘'w'’, ‘'x'’ 或 ‘'a'’ 分别表示读取（默认模式）
     、写入、独占新建或添加。 如果以写入或添加模式打开的文件不存在将自动
     新建；当以写入模式打开时文件将先清空。 以新建模式打开时如果文件已存
     在则将引发 *note FileExistsError: 960.。 以新建模式打开文件也意味着
     要写入，因此该模式的行为与 ‘'w'’ 类似。 在模式中附带 ‘'+'’ 将允许同
     时读取和写入。

     该类的 ‘read()’ (当附带正值参数调用时), ‘readinto()’ 和 ‘write()’ 方
     法将只执行一次系统调用。

     可以通过传入一个可调用对象作为 `opener' 来使用自定义文件打开器。 然
     后通过调用 `opener' 并传入 (`name', `flags') 来获取文件对象所对应的
     下层文件描述符。 `opener' 必须返回一个打开文件描述符（传入 *note
     os.open: 66e. 作为 `opener' 的结果在功能上将与传入 ‘None’ 类似）。

     新创建的文件是 *note 不可继承的: 803.。

     有关 opener 参数的示例，请参见内置函数 *note open(): 4f8. 。

     在 3.3 版更改: 增加了 `opener' 参数。增加了 ‘'x'’ 模式。

     在 3.4 版更改: 文件现在禁止继承。

     除了来自 *note IOBase: 1dc. 和 *note RawIOBase: a1b. 的属性和方法之
     外，*note FileIO: cac. 还提供了下列数据属性:

      -- 属性: mode

          构造函数中给定的模式。

      -- 属性: name

          文件名。当构造函数中没有给定名称时，这是文件的文件描述符。


File: python.info,  Node: 缓冲流,  Next: 文本 I/O<2>,  Prev: 原始文件 I/O,  Up: 类的层次结构

5.16.2.9 缓冲流
...............

相比原始 I/O，缓冲 I/O 流提供了针对 I/O 设备的更高层级接口。

 -- 类: io.BytesIO ([initial_bytes])

     一个使用内存字节缓冲区的流实现。 它继承自 *note BufferedIOBase:
     591.。 在 *note close(): 101e. 方法被调用时将会丢弃缓冲区。

     可选参数 `initial_bytes' 是一个包含初始数据的 *note bytes-like
     object: 5f1.。

     *note BytesIO: 7a4. 在继承自 *note BufferedIOBase: 591. 和 *note
     IOBase: 1dc. 的成员以外还提供或重载了下列方法:

      -- 方法: getbuffer ()

          返回一个对应于缓冲区内容的可读写视图而不必拷贝其数据。 此外，
          改变视图将透明地更新缓冲区内容:

               >>> b = io.BytesIO(b"abcdef")
               >>> view = b.getbuffer()
               >>> view[2:4] = b"56"
               >>> b.getvalue()
               b'ab56ef'

               注解: 只要视图保持存在，*note BytesIO: 7a4. 对象就无法被
               改变大小或关闭。

          3.2 新版功能.

      -- 方法: getvalue ()

          返回包含整个缓冲区内容的 *note bytes: 33a.。

      -- 方法: read1 ([size])

          在 *note BytesIO: 7a4. 中，这与 *note read(): 1d67. 相同。

          在 3.7 版更改: `size' 参数现在是可选的。

      -- 方法: readinto1 (b)

          在 *note BytesIO: 7a4. 中，这与 *note readinto(): 2003. 相同。

          3.5 新版功能.

 -- 类: io.BufferedReader (raw, buffer_size=DEFAULT_BUFFER_SIZE)

     一个提供对可读的序列型 *note RawIOBase: a1b. 对象更高层级访问的缓冲
     区。 它继承自 *note BufferedIOBase: 591.。 当从此对象读取数据时，可
     能会从下层原始流请求更大量的数据，并存放到内部缓冲区中。 接下来可以
     在后续读取时直接返回缓冲数据。

     根据给定的可读 `raw' 流和 `buffer_size' 创建 *note BufferedReader:
     b92. 的构造器。 如果省略 `buffer_size'，则会使用 *note
     DEFAULT_BUFFER_SIZE: 1609.。

     *note BufferedReader: b92. 在继承自 *note BufferedIOBase: 591. 和
     *note IOBase: 1dc. 的成员以外还提供或重载了下列方法:

      -- 方法: peek ([size])

          从流返回字节数据而不前移位置。 完成此调用将至多读取一次原始流
          。 返回的字节数量可能少于或多于请求的数量。

      -- 方法: read ([size])

          读取并返回 `size' 个字节，如果 `size' 未给定或为负值，则读取至
          EOF 或是在非阻塞模式下读取调用将会阻塞。

      -- 方法: read1 ([size])

          在原始流上通过单次调用读取并返回至多 `size' 个字节。 如果至少
          缓冲了一个字节，则只返回缓冲的字节。 在其他情况下，将执行一次
          原始流读取。

          在 3.7 版更改: `size' 参数现在是可选的。

 -- 类: io.BufferedWriter (raw, buffer_size=DEFAULT_BUFFER_SIZE)

     一个提供对可读的序列型 *note RawIOBase: a1b. 对象更高层级访问的缓冲
     区。 它继承自 *note BufferedIOBase: 591.。 当写入到此对象时，数据通
     常会被放入到内部缓冲区中。 缓冲区将在满足某些条件的情况下被写到下层
     的 *note RawIOBase: a1b. 对象，包括:

        * 当缓冲区对于所有挂起数据而言太小时；

        * 当 *note flush(): 200e. 被调用时

        * 当（为 *note BufferedRandom: 160e. 对象）请求 ‘seek()’ 时；

        * 当 *note BufferedWriter: 160d. 对象被关闭或销毁时。

     该构造器会为给定的可写 `raw' 流创建一个 *note BufferedWriter:
     160d.。 如果未给定 `buffer_size'，则使用默认的 *note
     DEFAULT_BUFFER_SIZE: 1609.。

     *note BufferedWriter: 160d. 在继承自 *note BufferedIOBase: 591. 和
     *note IOBase: 1dc. 的成员以外还提供或重载了下列方法:

      -- 方法: flush ()

          将缓冲区中保存的字节数据强制放入原始流。 如果原始流发生阻塞则
          应当引发 *note BlockingIOError: 99f.。

      -- 方法: write (b)

          写入 *note bytes-like object: 5f1. `b' 并返回写入的字节数。 当
          处于非阻塞模式时，如果缓冲区需要被写入但原始流发生阻塞则将引发
          *note BlockingIOError: 99f.。

 -- 类: io.BufferedRandom (raw, buffer_size=DEFAULT_BUFFER_SIZE)

     随机访问流的带缓冲的接口。 它继承自 *note BufferedReader: b92. 和
     *note BufferedWriter: 160d.。

     该构造器会为在第一个参数中给定的可查找原始流创建一个读取器和定稿器
     。 如果省略 `buffer_size' 则使用默认的 *note DEFAULT_BUFFER_SIZE:
     1609.。

     *note BufferedRandom: 160e. 能做到 *note BufferedReader: b92. 或
     *note BufferedWriter: 160d. 所能做的任何事。 此外，还会确保实现
     ‘seek()’ 和 ‘tell()’。

 -- 类: io.BufferedRWPair (reader, writer,
          buffer_size=DEFAULT_BUFFER_SIZE)

     一个带缓冲的 I/O 对象，它将两个单向 *note RawIOBase: a1b. 对象 – 一
     个可读，另一个可写 – 组合为单个双向端点。 它继承自 *note
     BufferedIOBase: 591.。

     `reader' 和 `writer' 分别是可读和可写的 *note RawIOBase: a1b. 对象
     。 如果省略 `buffer_size' 则使用默认的 *note DEFAULT_BUFFER_SIZE:
     1609.。

     *note BufferedRWPair: 1ffa. 实现了 *note BufferedIOBase: 591. 的所
     有方法，但 *note detach(): 2005. 除外，调用该方法将引发 *note
     UnsupportedOperation: 1ff8.。

          警告: *note BufferedRWPair: 1ffa. 不会尝试同步访问其下层的原始
          流。 你不应当将传给它与读取器和写入器相同的对象；而要改用
          *note BufferedRandom: 160e.。


File: python.info,  Node: 文本 I/O<2>,  Prev: 缓冲流,  Up: 类的层次结构

5.16.2.10 文本 I/O
..................

 -- 类: io.TextIOBase

     文本流的基类。 该类提供了基于字符和行的流 I/O 接口。 它继承自 *note
     IOBase: 1dc.。 该类无公有构造器。

     *note TextIOBase: c41. 在来自 *note IOBase: 1dc. 的成员以外还提供或
     重载了以下数据属性和方法:

      -- 属性: encoding

          用于将流的字节串解码为字符串以及将字符串编码为字节串的编码格式
          名称。

      -- 属性: errors

          解码器或编码器的错误设置。

      -- 属性: newlines

          一个字符串、字符串元组或者 ‘None’，表示目前已经转写的新行。 根
          据具体实现和初始构造器旗标的不同，此属性或许会不可用。

      -- 属性: buffer

          由 *note TextIOBase: c41. 处理的下层二进制缓冲区（为一个 *note
          BufferedIOBase: 591. 的实例）。 它不是 *note TextIOBase: c41.
          API 的组成部分并且不存在于某些实现中。

      -- 方法: detach ()

          从 *note TextIOBase: c41. 分离出下层二进制缓冲区并将其返回。

          在下层缓冲区被分离后，*note TextIOBase: c41. 将处于不可用的状
          态。

          某些 *note TextIOBase: c41. 的实现，例如 *note StringIO: 836.
          可能并无下层缓冲区的概念，因此调用此方法将引发 *note
          UnsupportedOperation: 1ff8.。

          3.1 新版功能.

      -- 方法: read (size=-1)

          从流中读取至多 `size' 个字符并以单个 *note str: 339. 的形式返
          回。 如果 `size' 为负值或 ‘None’，则读取至 EOF。

      -- 方法: readline (size=-1)

          读取至换行符或 EOF 并返回单个 ‘str’。 如果流已经到达 EOF，则将
          返回一个空字符串。

          如果指定了 `size' ，最多将读取 `size' 个字符。

      -- 方法: seek (offset, whence=SEEK_SET)

          将流位置改为给定的偏移位置 `offset'。 具体行为取决于 `whence'
          形参。 `whence' 的默认值为 ‘SEEK_SET’。

             * ‘SEEK_SET’ 或 ‘0’: 从流的开始位置起查找（默认值）；
               `offset' 必须为 *note TextIOBase.tell(): 2017. 所返回的数
               值或为零。 任何其他 `offset' 值都将导致未定义的行为。

             * ‘SEEK_CUR’ 或 ‘1’: "查找" 到当前位置；`offset' 必须为零，
               表示无操作（所有其他值均不受支持）。

             * ‘SEEK_END’ 或 ‘2’: 查找到流的末尾；`offset' 必须为零（所
               有其他值均不受支持）。

          以不透明数字形式返回新的绝对位置。

          3.1 新版功能: ‘SEEK_*’ 常量.

      -- 方法: tell ()

          以不透明数字形式返回当前流的位置。 该数字通常并不代表下层二进
          制存储中对应的字节数。

      -- 方法: write (s)

          将字符串 `s' 写入到流并返回写入的字符数。

 -- 类: io.TextIOWrapper (buffer, encoding=None, errors=None,
          newline=None, line_buffering=False, write_through=False)

     一个基于 *note BufferedIOBase: 591. 二进制流的缓冲文本流。 它继承自
     *note TextIOBase: c41.。

     `encoding' 给出流被解码或编码时将使用的编码格式。 它默认为 *note
     locale.getpreferredencoding(False): 3ad.。

     `errors' 是一个可选的字符串，它指明编码格式和编码格式错误的处理方式
     。 传入 ‘'strict'’ 将在出现编码格式错误时引发 *note ValueError:
     1fc. (默认值 ‘None’ 具有相同的效果)，传入 ‘'ignore'’ 将忽略错误。
     (请注意忽略编码格式错误会导致数据丢失。) ‘'replace'’ 会在出现错误数
     据时插入一个替换标记 (例如 ‘'?'’)。 ‘'backslashreplace'’ 将把错误数
     据替换为一个反斜杠转义序列。 在写入时，还可以使用
     ‘'xmlcharrefreplace'’ (替换为适当的 XML 字符引用) 或
     ‘'namereplace'’ (替换为 ‘\N{...}’ 转义序列)。 任何其他通过 *note
     codecs.register_error(): dfd. 注册的错误处理方式名称也可以被接受。

     `newline' 控制行结束符处理方式。 它可以为 ‘None’, ‘''’, ‘'\n'’,
     ‘'\r'’ 和 ‘'\r\n'’。 其工作原理如下:

        * 当从流中读取输入时，如果 `newline' 为 ‘None’，则会启用 *note
          universal newlines: 5fd. 模式。 输入中的行结束符可以为 ‘'\n'’,
          ‘'\r'’ 或 ‘'\r\n'’，在返回给调用者之前它们会被统一转写为
          ‘'\n'’。 如果参数为 ‘''’，也会启用通用换行模式，但行结束符会不
          加转写即返回给调用者。 如果它具有任何其他合法的值，则输入行将
          仅由给定的字符串结束，并且行结束符会不加转写即返回给调用者。

        * 将输出写入流时，如果 `newline' 为 ‘None’，则写入的任何 ‘'\n'’
          字符都将转换为系统默认行分隔符 *note os.linesep: 160c.。如果
          `newline' 是 ‘''’ 或 ‘'\n'’，则不进行翻译。如果 `newline' 是任
          何其他合法值，则写入的任何 ‘'\n'’ 字符将被转换为给定的字符串。

     如果 `line_buffering' 为 ‘True’，则当一个写入调用包含换行符或回车时
     将会应用 ‘flush()’。

     如果 `write_through' 为 ‘True’，对 ‘write()’ 的调用会确保不被缓冲：
     在 *note TextIOWrapper: 5fc. 对象上写入的任何数据会立即交给其下层的
     `buffer' 来处理。

     在 3.3 版更改: 已添加 `write_through' 参数

     在 3.3 版更改: 默认的 `encoding' 现在将为
     ‘locale.getpreferredencoding(False)’ 而非
     ‘locale.getpreferredencoding()’。 不要使用 *note
     locale.setlocale(): 2019. 来临时改变区域编码格式，要使用当前区域编
     码格式而不是用户的首选编码格式。

     *note TextIOWrapper: 5fc. 在继承自 *note TextIOBase: c41. 及其父类
     的现有成员以外还提供了下列成员:

      -- 属性: line_buffering

          是否启用行缓冲。

      -- 属性: write_through

          写入是否要立即传给下层的二进制缓冲。

          3.7 新版功能.

      -- 方法: reconfigure (*[, encoding][, errors][, newline][,
               line_buffering][, write_through])

          使用 `encoding', `errors', `newline', `line_buffering' 和
          `write_through' 的新设置来重新配置此文本流。

          未指定的形参将保留当前设定，例外情况是当指定了 `encoding' 但未
          指定 `errors' 时将会使用 ‘errors='strict'’。

          如果已经有数据从流中被读取则将无法再改变编码格式或行结束符。 另
          一方面，在写入数据之后再改变编码格式则是可以的。

          此方法会在设置新的形参之前执行隐式的流刷新。

          3.7 新版功能.

 -- 类: io.StringIO (initial_value='', newline='\n')

     用于文本 I/O 的内存数据流。 当调用 *note close(): 101e. 方法时将会
     丢弃文本缓冲区。

     缓冲区的初始值可通过提供 `initial_value' 来设置。 如果启用了行结束
     符转写，换行将以 *note write(): 2018. 所用的方式被编码。 数据流位置
     将被设为缓冲区的开头。

     `newline' 参数的规则与 *note TextIOWrapper: 5fc. 所用的一致。 默认
     规则是仅将 ‘\n’ 字符视为行结束符并且不执行换行符转写。 如果
     `newline' 设为 ‘None’，在所有平台上换行符都将被写入为 ‘\n’，但当读
     取时仍然会执行通用换行编码格式。

     *note StringIO: 836. 在继承自 *note TextIOBase: c41. 及其父类的现有
     成员以外还提供了以下方法:

      -- 方法: getvalue ()

          返回一个包含缓冲区全部内容的 ‘str’。 换行符会以与 *note
          read(): 2015. 相同的方式被编码，但是流的位置不会被改变。

     用法示例：

          import io

          output = io.StringIO()
          output.write('First line.\n')
          print('Second line.', file=output)

          # Retrieve file contents -- this will be
          # 'First line.\nSecond line.\n'
          contents = output.getvalue()

          # Close object and discard memory buffer --
          # .getvalue() will now raise an exception.
          output.close()

 -- 类: io.IncrementalNewlineDecoder

     用于在 *note universal newlines: 5fd. 模式下解码换行符的辅助编解码
     器。 它继承自 *note codecs.IncrementalDecoder: 183d.。


File: python.info,  Node: 性能<3>,  Prev: 类的层次结构,  Up: io --- 处理流的核心工具

5.16.2.11 性能
..............

本节讨论所提供的具体 I/O 实现的性能。

* Menu:

* 二进制 I/O: 二进制 I/O<2>.
* 文本 I/O: 文本 I/O<3>.
* 多线程: 多线程<3>.
* 可重入性::


File: python.info,  Node: 二进制 I/O<2>,  Next: 文本 I/O<3>,  Up: 性能<3>

5.16.2.12 二进制 I/O
....................

即使在用户请求单个字节时，也只读取和写入大块数据。通过该方法，缓冲 I/O 隐
藏了操作系统调用和执行无缓冲 I/O 例程时的任何低效性。增益取决于操作系统
和执行的 I/O 类型。例如，在某些现代操作系统上（例如 Linux），无缓冲磁盘
I/O 可以与缓冲 I/O 一样快。但最重要的是，无论平台和支持设备如何，缓冲
I/O 都能提供可预测的性能。因此，对于二进制数据，应首选使用缓冲的 I/O 而
不是未缓冲的 I/O 。


File: python.info,  Node: 文本 I/O<3>,  Next: 多线程<3>,  Prev: 二进制 I/O<2>,  Up: 性能<3>

5.16.2.13 文本 I/O
..................

二进制存储（如文件）上的文本 I/O 比同一存储上的二进制 I/O 慢得多，因为它
需要使用字符编解码器在Unicode和二进制数据之间进行转换。这在处理大量文本
数据（如大型日志文件）时会变得非常明显。此外，由于使用的重构算法
‘TextIOWrapper.tell()’ 和 ‘TextIOWrapper.seek()’ 都相当慢。

*note StringIO: 836. 是原生的内存 Unicode 容器，速度与 *note BytesIO:
7a4. 相似。


File: python.info,  Node: 多线程<3>,  Next: 可重入性,  Prev: 文本 I/O<3>,  Up: 性能<3>

5.16.2.14 多线程
................

*note FileIO: cac. 对象是线程安全的，只要它们封装的操作系统调用（比如
Unix下的 ‘read(2)’ ）也是线程安全的。

二进制缓冲对象（例如 *note BufferedReader: b92, *note BufferedWriter:
160d, *note BufferedRandom: 160e. 和 *note BufferedRWPair: 1ffa.）使用锁
来保护其内部结构；因此，可以安全地一次从多个线程中调用它们。

*note TextIOWrapper: 5fc. 对象不再是线程安全的。


File: python.info,  Node: 可重入性,  Prev: 多线程<3>,  Up: 性能<3>

5.16.2.15 可重入性
..................

二进制缓冲对象（ *note BufferedReader: b92. ， *note BufferedWriter:
160d. ， *note BufferedRandom: 160e. 和 *note BufferedRWPair: 1ffa. 的实
例）不是可重入的。虽然在正常情况下不会发生可重入调用，但仍可能会在 *note
signal: eb. 处理程序执行 I/O 时产生。如果线程尝试重入已经访问的缓冲对象
，则会引发 *note RuntimeError: 2bb. 。注意，这并不禁止其他线程进入缓冲对
象。

上面的内容隐含地扩展到文本文件，因为 *note open(): 4f8. 函数会把缓冲对象
封装在 *note TextIOWrapper: 5fc. 中。这包括标准流，因此也会影响内置函数
*note print(): 88f. 。


File: python.info,  Node: time --- 时间的访问和转换,  Next: argparse --- 命令行选项、参数和子命令解析器,  Prev: io --- 处理流的核心工具,  Up: 通用操作系统服务

5.16.3 ‘time’ — 时间的访问和转换
--------------------------------

__________________________________________________________________

该模块提供了各种时间相关的函数。相关功能还可以参阅 *note datetime: 31. 和
*note calendar: 15. 模块。

尽管此模块始终可用，但并非所有平台上都提供所有功能。 此模块中定义的大多
数函数是调用了所在平台 C 语言库的同名函数。 因为这些函数的语义因平台而异
,所以使用时最好查阅平台相关文档。

下面是一些术语和惯例的解释.

   * `epoch' 是时间开始的点，并且取决于平台。对于Unix， epoch 是1970年
     1月1日00:00:00（UTC）。要找出给定平台上的 epoch ，请查看
     ‘time.gmtime(0)’ 。

   * 术语 `Unix 纪元秒数' 是指自国际标准时间 1970 年 1 月 1 日零时以来经
     过的总秒数，通常不包括 闰秒(1)。 在所有符合 POSIX 标准的平台上，闰
     秒都会从总秒数中被扣除。

   * 此模块中的功能可能无法处理纪元之前或将来的远期日期和时间。未来的截
     止点由C库决定；对于32位系统，它通常在2038年。

   * 函数 *note strptime(): d99. 在接收到 ‘%y’ 格式代码时可以解析 2 位数
     的年份。 当解析 2 位数年份时，会按照 POSIX 和 ISO C 标准进行转换：
     数值 69–99 映射为 1969–1999，而数值 0–68 被映射为 2000–2068。

   * UTC是协调世界时（以前称为格林威治标准时间，或GMT）。缩写UTC不是错误
     ，而是英语和法语之间的妥协。

   * DST是夏令时，在一年中的一部分时间（通常）调整时区一小时。 DST规则很
     神奇（由当地法律确定），并且每年都会发生变化。 C 库有一个包含本地规
     则的表（通常是从系统文件中读取以获得灵活性），并且在这方面是True
     Wisdom的唯一来源。

   * 各种实时函数的精度可能低于表示其值或参数的单位所建议的精度。例如，
     在大多数Unix系统上，时钟 "ticks" 仅为每秒50或100次。

   * 另一方面， *note time(): 326. 和 *note sleep(): 689. 的精度优于它们
     的Unix等价物：时间表示为浮点数，*note time(): 326. 返回最准确的时间
     （使用Unix ‘gettimeofday()’ 如果可用），并且 *note sleep(): 689. 将
     接受非零分数的时间（Unix ‘select()’ 用于实现此功能，如果可用）。

   * 时间值由 *note gmtime(): b47.，*note localtime(): f5d. 和 *note
     strptime(): d99. 返回，并被 *note asctime(): b6b.， *note mktime():
     b6c. 和 *note strftime(): b6d. 接受，是一个 9 个整数的序列。 *note
     gmtime(): b47.， *note localtime(): f5d. 和 *note strptime(): d99.
     的返回值还提供各个字段的属性名称。

     请参阅 *note struct_time: 5a2. 以获取这些对象的描述。

     在 3.3 版更改: 在平台支持相应的 ‘struct tm’ 成员时，*note
     struct_time: 5a2. 类型被扩展提供 ‘tm_gmtoff’ 和 ‘tm_zone’ 属性。

     在 3.6 版更改: *note struct_time: 5a2. 的属性 ‘tm_gmtoff’ 和
     ‘tm_zone’ 现在可在所有平台上使用。

   * 使用以下函数在时间表示之间进行转换：

     从                            到                            使用
                                                                 
     ------------------------------------------------------------------------------------------
                                                                 
     自纪元以来的秒数              UTC 的                        *note gmtime(): b47.
                                   *note struct_time: 5a2.       
                                   
                                                                 
     自纪元以来的秒数              本地时间的                    *note localtime(): f5d.
                                   *note struct_time: 5a2.       
                                   
                                                                 
     UTC 的                        自纪元以来的秒数              *note calendar.timegm(): 192e.
     *note struct_time: 5a2.                                     

     本地时间的                    自纪元以来的秒数              *note mktime(): b6c.
     *note struct_time: 5a2.                                     

* Menu:

* 函数: 函数<2>.
* Clock ID 常量::
* 时区常量::

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Leap_second


File: python.info,  Node: 函数<2>,  Next: Clock ID 常量,  Up: time --- 时间的访问和转换

5.16.3.1 函数
.............

 -- 函数: time.asctime ([t])

     转换由 *note gmtime(): b47. 或 *note localtime(): f5d. 所返回的表示
     时间的元组或 *note struct_time: 5a2. 为以下形式的字符串: ‘'Sun Jun
     20 23:21:05 1993'’。 日期字段的长度为两个字符，如果日期只有一个数字
     则会以零填充，例如: ‘'Wed Jun 9 04:26:40 1993'’。

     如果未提供 `t'，则会使用 *note localtime(): f5d. 所返回的当前时间。
     *note asctime(): b6b. 不会使用区域设置信息。

          注解: 与同名的C函数不同， *note asctime(): b6b. 不添加尾随换行
          符。

 -- 函数: time.pthread_getcpuclockid (thread_id)

     返回指定的 `thread_id' 的特定于线程的CPU时间时钟的 `clk_id' 。

     使用 *note threading.Thread: 235. 对象的 *note
     threading.get_ident(): ab7. 或 *note ident: 2028. 属性为
     `thread_id' 获取合适的值。

          警告: 传递无效的或过期的 `thread_id' 可能会导致未定义的行为，
          例如段错误。

     *note 可用性: 136f. ： Unix（有关详细信息，请参见
     ‘pthread_getcpuclockid(3)’ 的手册页）。

     3.7 新版功能.

 -- 函数: time.clock_getres (clk_id)

     返回指定时钟 `clk_id' 的分辨率（精度）。有关 `clk_id' 的可接受值列
     表，请参阅 *note Clock ID 常量: 2029. 。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: time.clock_gettime (clk_id) -> float

     返回指定 `clk_id' 时钟的时间。有关 `clk_id' 的可接受值列表，请参阅
     *note Clock ID 常量: 2029. 。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: time.clock_gettime_ns (clk_id) -> int

     与 *note clock_gettime(): abb. 相似，但返回时间为纳秒。

     *note 可用性: 136f.: Unix。

     3.7 新版功能.

 -- 函数: time.clock_settime (clk_id, time: float)

     设置指定 `clk_id' 时钟的时间。 目前， *note CLOCK_REALTIME: 202a. 是
     `clk_id' 唯一可接受的值。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: time.clock_settime_ns (clk_id, time: int)

     与 *note clock_settime(): abc. 相似，但设置时间为纳秒。

     *note 可用性: 136f.: Unix。

     3.7 新版功能.

 -- 函数: time.ctime ([secs])

     转换以距离初始纪元的秒数表示的时间为以下形式的字符串: ‘'Sun Jun 20
     23:21:05 1993'’ 代表本地时间。 日期字段的长度为两个字符，如果日期只
     有一个数字则会以零填充，例如: ‘'Wed Jun 9 04:26:40 1993'’。

     如果 `secs' 未提供或为 *note None: 158.，则使用 *note time(): 326.
     所返回的当前时间。 ‘ctime(secs)’ 等价于 ‘asctime(localtime(secs))’。
     *note ctime(): 18c7. 不会使用区域设置信息。

 -- 函数: time.get_clock_info (name)

     获取有关指定时钟的信息作为命名空间对象。 支持的时钟名称和读取其值的
     相应函数是：

        * ‘'monotonic'’: *note time.monotonic(): 778.

        * ‘'perf_counter'’: *note time.perf_counter(): 2ab.

        * ‘'process_time'’: *note time.process_time(): 2ac.

        * ‘'thread_time'’: *note time.thread_time(): 401.

        * ‘'time'’: *note time.time(): 326.

     结果具有以下属性：

        - `adjustable' ： 如果时钟可以自动更改（例如通过NTP守护程序）或
          由系统管理员手动更改，则为 ‘True’ ，否则为 ‘False’ 。

        - `implementation' ： 用于获取时钟值的基础C函数的名称。有关可能
          的值，请参阅 *note Clock ID 常量: 2029. 。

        - `monotonic' ：如果时钟不能倒退，则为 ‘True’ ，否则为 ‘False’ 。

        - `resolution' ： 以秒为单位的时钟分辨率（ *note float: 188. ）

     3.3 新版功能.

 -- 函数: time.gmtime ([secs])

     将以自 epoch 开始的秒数表示的时间转换为 UTC 的 *note struct_time:
     5a2. ，其中 dst 标志始终为零。 如果未提供 `secs' 或为 *note None:
     158. ，则使用 *note time(): 326. 所返回的当前时间。 一秒以内的小数
     将被忽略。 有关 *note struct_time: 5a2. 对象的说明请参见上文。 有关
     此函数的逆操作请参阅 *note calendar.timegm(): 192e.。

 -- 函数: time.localtime ([secs])

     与 *note gmtime(): b47. 相似但转换为当地时间。如果未提供 `secs' 或
     为 *note None: 158. ，则使用由 *note time(): 326. 返回的当前时间。
     当 DST 适用于给定时间时，dst标志设置为 ‘1’ 。

 -- 函数: time.mktime (t)

     这是 *note localtime(): f5d. 的反函数。它的参数是 *note
     struct_time: 5a2. 或者完整的 9 元组（因为需要 dst 标志；如果它是未
     知的则使用 ‘-1’ 作为dst标志），它表示 `local' 的时间，而不是 UTC 。
     它返回一个浮点数，以便与 *note time(): 326. 兼容。如果输入值不能表
     示为有效时间，则 *note OverflowError: 968. 或 *note ValueError:
     1fc. 将被引发（这取决于Python或底层C库是否捕获到无效值）。它可以生
     成时间的最早日期取决于平台。

 -- 函数: time.monotonic () -> float

     （以小数表示的秒为单位）返回一个单调时钟的值，即不能倒退的时钟。 该
     时钟不受系统时钟更新的影响。 返回值的参考点未被定义，因此只有两次调
     用之间的差值才是有意义的。

     3.3 新版功能.

     在 3.5 版更改: 该功能现在始终可用且始终在系统范围内。

 -- 函数: time.monotonic_ns () -> int

     与 *note monotonic(): 778. 相似，但是返回时间为纳秒数。

     3.7 新版功能.

 -- 函数: time.perf_counter () -> float

     （以小数表示的秒为单位）返回一个性能计数器的值，即用于测量较短持续
     时间的具有最高有效精度的时钟。 它会包括睡眠状态所消耗的时间并且作用
     于全系统范围。 返回值的参考点未被定义，因此只有两次调用之间的差值才
     是有效的。

     3.3 新版功能.

 -- 函数: time.perf_counter_ns () -> int

     与 *note perf_counter(): 2ab. 相似，但是返回时间为纳秒。

     3.7 新版功能.

 -- 函数: time.process_time () -> float

     （以小数表示的秒为单位）返回当前进程的系统和用户 CPU 时间的总计值。
     它不包括睡眠状态所消耗的时间。 根据定义它只作用于进程范围。 返回值
     的参考点未被定义，因此只有两次调用之间的差值才是有效的。

     3.3 新版功能.

 -- 函数: time.process_time_ns () -> int

     与 *note process_time(): 2ac. 相似，但是返回时间为纳秒。

     3.7 新版功能.

 -- 函数: time.sleep (secs)

     暂停执行调用线程达到给定的秒数。参数可以是浮点数，以指示更精确的睡
     眠时间。实际的暂停时间可能小于请求的时间，因为任何捕获的信号将在执
     行该信号的捕获例程后终止 *note sleep(): 689. 。此外，由于系统中其他
     活动的安排，暂停时间可能比请求的时间长任意量。

     在 3.5 版更改: 即使睡眠被信号中断，该函数现在至少睡眠 `secs' ，除非
     信号处理程序引发异常（参见 PEP 475(1) 作为基本原理）。

 -- 函数: time.strftime (format[, t])

     转换一个元组或 *note struct_time: 5a2. 表示的由 *note gmtime():
     b47. 或 *note localtime(): f5d. 返回的时间到由 `format' 参数指定的
     字符串。如果未提供 `t' ，则使用由 *note localtime(): f5d. 返回的当
     前时间。 `format' 必须是一个字符串。如果 `t' 中的任何字段超出允许范
     围，则引发 *note ValueError: 1fc. 。

     0是时间元组中任何位置的合法参数；如果它通常是非法的，则该值被强制改
     为正确的值。

     以下指令可以嵌入 `format' 字符串中。它们显示时没有可选的字段宽度和
     精度规范，并被 *note strftime(): b6d. 结果中的指示字符替换：

     指令            含义                                                 注释
                                                                          
     ---------------------------------------------------------------------------------
                                                                          
     ‘%a’            本地化的缩写星期中每日的名称。
                     
                                                                          
     ‘%A’            本地化的星期中每日的完整名称。
                     
                                                                          
     ‘%b’            本地化的月缩写名称。
                     
                                                                          
     ‘%B’            本地化的月完整名称。
                     
                                                                          
     ‘%c’            本地化的适当日期和时间表示。
                     
                                                                          
     ‘%d’            十进制数 [01,31] 表示的月中日。
                     
                                                                          
     ‘%H’            十进制数 [00,23] 表示的小时（24小时制）。
                     
                                                                          
     ‘%I’            十进制数 [01,12] 表示的小时（12小时制）。
                     
                                                                          
     ‘%j’            十进制数 [001,366] 表示的年中日。
                     
                                                                          
     ‘%m’            十进制数 [01,12] 表示的月。
                     
                                                                          
     ‘%M’            十进制数 [00,59] 表示的分钟。
                     
                                                                          
     ‘%p’            本地化的 AM 或 PM 。                                 (1)
                                                                          
                                                                          
     ‘%S’            十进制数 [00,61] 表示的秒。                          (2)
                                                                          
                                                                          
     ‘%U’            十进制数 [00,53] 表示的一年中的周数（星期日作为一    (3)
                     周的第一天）。 在第一个星期日之前的新年中的所有日    
                     子都被认为是在第 0 周。
                     
                                                                          
     ‘%w’            十进制数 [0(星期日),6] 表示的周中日。
                     
                                                                          
     ‘%W’            十进制数 [00,53] 表示的一年中的周数（星期一作为一    (3)
                     周的第一天）。 在第一个星期一之前的新年中的所有日    
                     子被认为是在第 0 周。
                     
                                                                          
     ‘%x’            本地化的适当日期表示。
                     
                                                                          
     ‘%X’            本地化的适当时间表示。
                     
                                                                          
     ‘%y’            十进制数 [00,99] 表示的没有世纪的年份。
                     
                                                                          
     ‘%Y’            十进制数表示的带世纪的年份。
                     
                                                                          
     ‘%z’            时区偏移以格式 +HHMM 或 -HHMM 形式的 UTC/GMT 的正
                     或负时差指示，其中H表示十进制小时数字，M表示小数分
                     钟数字 [-23:59, +23:59] 。
                     
                                                                          
     ‘%Z’            时区名称（如果不存在时区，则不包含字符）。
                     
                                                                          
     ‘%%’            字面的 ‘'%'’ 字符。
                     

     注释:

       1. 当与 *note strptime(): d99. 函数一起使用时，如果使用 ‘%I’ 指令
          来解析小时， ‘%p’ 指令只影响输出小时字段。

       2. 范围真的是 ‘0’ 到 ‘61’ ；值 ‘60’ 在表示 leap seconds(2) 的时间
          戳中有效，并且由于历史原因支持值 ‘61’ 。

       3. 当与 *note strptime(): d99. 函数一起使用时， ‘%U’ 和 ‘%W’ 仅用
          于指定星期几和年份的计算。

     下面是一个示例，一个与 RFC 2822(3) Internet电子邮件标准以兼容的日期
     格式。 (4)

          >>> from time import gmtime, strftime
          >>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
          'Thu, 28 Jun 2001 14:17:15 +0000'

     某些平台可能支持其他指令，但只有此处列出的指令具有 ANSI C 标准化的
     含义。要查看平台支持的完整格式代码集，请参阅 ‘strftime(3)’ 文档。

     在某些平台上，可选的字段宽度和精度规范可以按照以下顺序紧跟在指令的
     初始 ‘'%'’ 之后；这也不可移植。字段宽度通常为2，除了 ‘%j’ ，它是3。

 -- 函数: time.strptime (string[, format])

     根据格式解析表示时间的字符串。 返回值为一个被 *note gmtime(): b47.
     或 *note localtime(): f5d. 返回的 *note struct_time: 5a2. 。

     `format' 参数使用与 *note strftime(): b6d. 相同的指令。 它默认为匹
     配 *note ctime(): 18c7. 所返回的格式 ‘"%a %b %d %H:%M:%S %Y"`’ 。 如
     果 `string' 不能根据 `format' 来解析，或者解析后它有多余的数据，则
     会引发 *note ValueError: 1fc.。 当无法推断出更准确的值时，用于填充
     任何缺失数据的默认值是 ‘(1900, 1, 1, 0, 0, 0, 0, 1, -1)’ 。
     `string' 和 `format' 都必须为字符串。

     例如:

          >>> import time
          >>> time.strptime("30 Nov 00", "%d %b %y")
          time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
                           tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)

     支持 ‘%Z’ 指令是基于 ‘tzname’ 中包含的值以及 ‘daylight’ 是否为真。
     因此，它是特定于平台的，除了识别始终已知的 UTC 和 GMT （并且被认为
     是非夏令时时区）。

     仅支持文档中指定的指令。因为每个平台都实现了 ‘strftime()’ ，它有时
     会提供比列出的指令更多的指令。但是 ‘strptime()’ 独立于任何平台，因
     此不一定支持所有未记录为支持的可用指令。

 -- 类: time.struct_time

     返回的时间值序列的类型为 *note gmtime(): b47. 、 *note localtime():
     f5d. 和 *note strptime(): d99. 。它是一个带有 *note named tuple:
     aab. 接口的对象：可以通过索引和属性名访问值。 存在以下值：

     索引        属性                    值
                                         
     --------------------------------------------------------------------------
                                         
     0           ‘tm_year’               （例如，1993）
                                         
                                         
     1           ‘tm_mon’                range [1, 12]
                                         
                                         
     2           ‘tm_mday’               range [1, 31]
                                         
                                         
     3           ‘tm_hour’               range [0, 23]
                                         
                                         
     4           ‘tm_min’                range [0, 59]
                                         
                                         
     5           ‘tm_sec’                range [0, 61]； 见
                                         *note strftime(): b6d. 介绍中的
                                         `(2)'
                                         
                                         
     6           ‘tm_wday’               range [0, 6] ，周一为 0
                                         
                                         
     7           ‘tm_yday’               range [1, 366]
                                         
                                         
     8           ‘tm_isdst’              0, 1 或 -1；如下所示
                                         
                                         
     N/A         ‘tm_zone’               时区名称的缩写
                                         
                                         
     N/A         ‘tm_gmtoff’             以秒为单位的UTC以东偏离
                                         

     请注意，与C结构不同，月份值是 [1,12] 的范围，而不是 [0,11] 。

     在调用 *note mktime(): b6c. 时， ‘tm_isdst’ 可以在夏令时生效时设置
     为1，而在夏令时不生效时设置为0。 值-1表示这是未知的，并且通常会导致
     填写正确的状态。

     当一个长度不正确的元组被传递给期望 *note struct_time: 5a2. 的函数，
     或者具有错误类型的元素时，会引发 *note TypeError: 193. 。

 -- 函数: time.time () -> float

     返回以浮点数表示的从 *note epoch: 2025. 开始的秒数的时间值。 epoch
     的具体日期和 leap seconds(5) 的处理取决于平台。 在 Windows 和大多数
     Unix 系统中， epoch 是 1970 年 1 月 1 日 00:00:00 (UTC)，并且闰秒将
     不计入从 epoch 开始的秒数。 这通常被称为 Unix 时间(6)。 要了解给定
     平台上 epoch 的具体定义，请查看 ‘gmtime(0)’。

     请注意，即使时间总是作为浮点数返回，但并非所有系统都提供高于1秒的精
     度。虽然此函数通常返回非递减值，但如果在两次调用之间设置了系统时钟
     ，则它可以返回比先前调用更低的值。

     返回的数字 *note time(): 326. 可以通过将其传递给 *note gmtime():
     b47. 函数或转换为UTC中更常见的时间格式（即年、月、日、小时等）或通
     过将它传递给 *note localtime(): f5d. 函数获得本地时间。在这两种情况
     下都返回一个 *note struct_time: 5a2. 对象，日历日期组件可以从中作为
     属性访问。

 -- 函数: time.thread_time () -> float

     （以小数表示的秒为单位）返回当前线程的系统和用户 CPU 时间的总计值。
     它不包括睡眠状态所消耗的时间。 根据定义它只作用于线程范围。 返回值
     的参考点未被定义，因此只有两次调用之间的差值才是有效的。

     *note 可用性: 136f. ： Windows、 Linux、 Unix 系统支持
     ‘CLOCK_THREAD_CPUTIME_ID’ 。

     3.7 新版功能.

 -- 函数: time.thread_time_ns () -> int

     与 *note thread_time(): 401. 相似，但返回纳秒时间。

     3.7 新版功能.

 -- 函数: time.time_ns () -> int

     与 *note time(): 326. 相似，但返回时间为用整数表示的自 *note epoch:
     2025. 以来所经过的纳秒数。

     3.7 新版功能.

 -- 函数: time.tzset ()

     重置库例程使用的时间转换规则。环境变量 ‘TZ’ 指定如何完成。它还将设
     置变量 ‘tzname’ （来自 ‘TZ’ 环境变量）， ‘timezone’ （UTC的西部非
     DST秒）， ‘altzone’ （UTC以西的DST秒）和 ‘daylight’ （如果此时区没
     有任何夏令时规则则为0，如果有夏令时适用的时间，无论过去、现在或未来
     ，则为非零）。

     *note 可用性: 136f.: Unix。

          注解: 虽然在很多情况下，更改 ‘TZ’ 环境变量而不调用 *note
          tzset(): 202b. 可能会影响函数的输出，例如 *note localtime():
          f5d. ，不应该依赖此行为。

          ‘TZ’ 不应该包含空格。

     ‘TZ’ 环境变量的标准格式是（为了清晰起见，添加了空格）:

          std offset [dst [offset [,start[/time], end[/time]]]]

     组件的位置是：

     ‘std’ 和 ‘dst’

          三个或更多字母数字，给出时区缩写。这些将传到 time.tzname

     ‘offset’

          偏移量的形式为： ‘± hh[:mm[:ss]]’ 。这表示添加到达UTC的本地时
          间的值。如果前面有 ’-’ ，则时区位于本初子午线的东边；否则，在
          它是西边。如果dst之后没有偏移，则假设夏令时比标准时间提前一小
          时。

     ‘start[/time], end[/time]’

          指示何时更改为DST和从DST返回。开始日期和结束日期的格式为以下之
          一：

          ‘J`n'’

               Julian日 `n' （1 <= `n' <= 365）。闰日不计算在内，因此在
               所有年份中，2月28日是第59天，3月1日是第60天。

          ‘`n'’

               从零开始的Julian日（0 <= `n' <= 365）。 闰日计入，可以引
               用2月29日。

          ‘M`m'.`n'.`d'’

               一年中 `m' 月的第 `n' 周（1 <= `n' <= 5 ，1 <= `m' <= 12
               ，第 5 周表示 “可能在 `m' 月第 4 周或第 5 周出现的最后第
               `d' 日”）的第 `d' 天（0 <= `d' <= 6）。 第 1 周是第 `d' 天
               发生的第一周。 第 0 天是星期天。

          ‘time’ 的格式与 ‘offset’ 的格式相同，但不允许使用前导符号（
          ’-’ 或 ’+’ ）。如果没有给出时间，则默认值为02:00:00。

          >>> os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
          >>> time.tzset()
          >>> time.strftime('%X %x %Z')
          '02:07:36 05/08/03 EDT'
          >>> os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
          >>> time.tzset()
          >>> time.strftime('%X %x %Z')
          '16:08:12 05/08/03 AEST'

     在许多Unix系统（包括 *BSD ， Linux ， Solaris 和 Darwin 上），使用
     系统的区域信息（ ‘tzfile(5)’ ）数据库来指定时区规则会更方便。为此，
     将 ‘TZ’ 环境变量设置为所需时区数据文件的路径，相对于系统 ’zoneinfo’
     时区数据库的根目录，通常位于 ‘/usr/share/zoneinfo’ 。 例如，
     ‘'US/Eastern'’ 、 ‘'Australia/Melbourne'’ 、 ‘'Egypt'’ 或
     ‘'Europe/Amsterdam'’。

          >>> os.environ['TZ'] = 'US/Eastern'
          >>> time.tzset()
          >>> time.tzname
          ('EST', 'EDT')
          >>> os.environ['TZ'] = 'Egypt'
          >>> time.tzset()
          >>> time.tzname
          ('EET', 'EEST')

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475

   (2) https://en.wikipedia.org/wiki/Leap_second

   (3) https://tools.ietf.org/html/rfc2822.html

   (4) (1) 现在不推荐使用 ‘%Z’ ，但是所有 ANSI C 库都不支持扩展为首选小
时/分钟偏移量的‘‘%z‘‘转义符。 此外，严格的 1982 年原始 RFC 822
(https://tools.ietf.org/html/rfc822.html) 标准要求两位数的年份（%y而不是
%Y），但是实际在2000年之前很久就转移到了4位数年。之后， RFC 822
(https://tools.ietf.org/html/rfc822.html) 已经废弃了，4位数的年份首先被
推荐 RFC 1123 (https://tools.ietf.org/html/rfc1123.html) ，然后被 RFC
2822 (https://tools.ietf.org/html/rfc2822.html) 强制执行。

   (5) https://en.wikipedia.org/wiki/Leap_second

   (6) https://en.wikipedia.org/wiki/Unix_time


File: python.info,  Node: Clock ID 常量,  Next: 时区常量,  Prev: 函数<2>,  Up: time --- 时间的访问和转换

5.16.3.2 Clock ID 常量
......................

这些常量用作 *note clock_getres(): aba. 和 *note clock_gettime(): abb. 的
参数。

 -- 数据: time.CLOCK_BOOTTIME

     与 *note CLOCK_MONOTONIC: 3fe. 相同，除了它还包括系统暂停的任何时间
     。

     这允许应用程序获得一个暂停感知的单调时钟，而不必处理 *note
     CLOCK_REALTIME: 202a. 的复杂性，如果使用 ‘settimeofday()’ 或类似的
     时间更改时间可能会有不连续性。

     *note 可用性: 136f.: Linux 2.6.39 或更新

     3.7 新版功能.

 -- 数据: time.CLOCK_HIGHRES

     Solaris OS 有一个 ‘CLOCK_HIGHRES’ 计时器，试图使用最佳硬件源，并可
     能提供接近纳秒的分辨率。 ‘CLOCK_HIGHRES’ 是不可调节的高分辨率时钟。

     *note 可用性: 136f.: Solaris.

     3.3 新版功能.

 -- 数据: time.CLOCK_MONOTONIC

     无法设置的时钟，表示自某些未指定的起点以来的单调时间。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 数据: time.CLOCK_MONOTONIC_RAW

     类似于 *note CLOCK_MONOTONIC: 3fe. ，但可以访问不受NTP调整影响的原
     始硬件时间。

     *note 可用性: 136f.: Linux 2.6.28 和更新版本， macOS 10.12 和更新版
     本。

     3.3 新版功能.

 -- 数据: time.CLOCK_PROCESS_CPUTIME_ID

     来自CPU的高分辨率每进程计时器。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 数据: time.CLOCK_PROF

     来自CPU的高分辨率每进程计时器。

     *note 可用性: 136f.: FreeBSD， NetBSD 7 或更新， OpenBSD.

     3.7 新版功能.

 -- 数据: time.CLOCK_THREAD_CPUTIME_ID

     特定于线程的CPU时钟。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 数据: time.CLOCK_UPTIME

     该时间的绝对值是系统运行且未暂停的时间，提供准确的正常运行时间测量
     ，包括绝对值和间隔值。

     *note 可用性: 136f.: FreeBSD， OpenBSD 5.5 或更新。

     3.7 新版功能.

 -- 数据: time.CLOCK_UPTIME_RAW

     单调递增的时钟，记录从一个任意起点开始的时间，不受频率或时间调整的
     影响，并且当系统休眠时将不会递增。

     *note 可用性: 136f.: macOS 10.12 和更新版本。

     3.8 新版功能.

以下常量是唯一可以发送到 *note clock_settime(): abc. 的参数。

 -- 数据: time.CLOCK_REALTIME

     系统范围的实时时钟。 设置此时钟需要适当的权限。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.


File: python.info,  Node: 时区常量,  Prev: Clock ID 常量,  Up: time --- 时间的访问和转换

5.16.3.3 时区常量
.................

 -- 数据: time.altzone

     本地DST时区的偏移量，以UTC为单位的秒数，如果已定义。如果当地DST时区
     在UTC以东（如在西欧，包括英国），则是负数。 只有当 ‘daylight’ 非零
     时才使用它。 见下面的注释。

 -- 数据: time.daylight

     如果定义了DST时区，则为非零。 见下面的注释。

 -- 数据: time.timezone

     本地（非DST）时区的偏移量，UTC以西的秒数（西欧大部分地区为负，美国
     为正，英国为零）。 见下面的注释。

 -- 数据: time.tzname

     两个字符串的元组：第一个是本地非DST时区的名称，第二个是本地DST时区
     的名称。 如果未定义DST时区，则不应使用第二个字符串。 见下面的注释。

     注解: 对于上述时区常量（ *note altzone: 2033. 、 *note daylight:
     2034. 、 *note timezone: 2035. 和 *note tzname: 2036. ），该值由模
     块加载时有效的时区规则确定，或者最后一次 *note tzset(): 202b. 被调
     用时，并且在过去的时间可能不正确。建议使用来自 *note localtime():
     f5d. 结果的 ‘tm_gmtoff’ 和 ‘tm_zone’ 来获取时区信息。

参见
....

模块 *note datetime: 31.

     更多面向对象的日期和时间接口。

模块 *note locale: aa.

     国际化服务。 区域设置会影响 *note strftime(): b6d. 和 *note
     strptime(): d99. 中许多格式说明符的解析。

模块 *note calendar: 15.

     一般日历相关功能。这个模块的 ‘timegm()’ 是函数 *note gmtime(): b47.
     的反函数。

备注
....


File: python.info,  Node: argparse --- 命令行选项、参数和子命令解析器,  Next: getopt --- C 风格的命令行选项解析器,  Prev: time --- 时间的访问和转换,  Up: 通用操作系统服务

5.16.4 ‘argparse’ — 命令行选项、参数和子命令解析器
--------------------------------------------------

3.2 新版功能.

`源代码：' Lib/argparse.py(1)

__________________________________________________________________

教程
....

此页面包含该 API 的参考信息。有关 Python 命令行解析更细致的介绍，请参阅
*note argparse 教程: 2039.。

*note argparse: 6. 模块可以让人轻松编写用户友好的命令行接口。程序定义它
需要的参数，然后 *note argparse: 6. 将弄清如何从 *note sys.argv: c03. 解
析出那些参数。 *note argparse: 6. 模块还会自动生成帮助和使用手册，并在用
户给程序传入无效参数时报出错误信息。

* Menu:

* 示例: 示例<7>.
* ArgumentParser 对象::
* add_argument() 方法: add_argument 方法.
* parse_args() 方法: parse_args 方法.
* 其它实用工具::
* 升级 optparse 代码::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/argparse.py


File: python.info,  Node: 示例<7>,  Next: ArgumentParser 对象,  Up: argparse --- 命令行选项、参数和子命令解析器

5.16.4.1 示例
.............

以下代码是一个 Python 程序，它获取一个整数列表并计算总和或者最大值：

     import argparse

     parser = argparse.ArgumentParser(description='Process some integers.')
     parser.add_argument('integers', metavar='N', type=int, nargs='+',
                         help='an integer for the accumulator')
     parser.add_argument('--sum', dest='accumulate', action='store_const',
                         const=sum, default=max,
                         help='sum the integers (default: find the max)')

     args = parser.parse_args()
     print(args.accumulate(args.integers))

假设上面的 Python 代码保存在名为 ‘prog.py’ 的文件中，它可以在命令行运行
并提供有用的帮助信息：

     $ python prog.py -h
     usage: prog.py [-h] [--sum] N [N ...]

     Process some integers.

     positional arguments:
      N           an integer for the accumulator

     optional arguments:
      -h, --help  show this help message and exit
      --sum       sum the integers (default: find the max)

当使用适当的参数运行时，它会输出命令行传入整数的总和或者最大值：

     $ python prog.py 1 2 3 4
     4

     $ python prog.py 1 2 3 4 --sum
     10

如果传入无效参数，则会报出错误：

     $ python prog.py a b c
     usage: prog.py [-h] [--sum] N [N ...]
     prog.py: error: argument N: invalid int value: 'a'

以下部分将引导你完成这个示例。

* Menu:

* 创建一个解析器::
* 添加参数::
* 解析参数::


File: python.info,  Node: 创建一个解析器,  Next: 添加参数,  Up: 示例<7>

5.16.4.2 创建一个解析器
.......................

使用 *note argparse: 6. 的第一步是创建一个 *note ArgumentParser: 69e. 对
象：

     >>> parser = argparse.ArgumentParser(description='Process some integers.')

*note ArgumentParser: 69e. 对象包含将命令行解析成 Python 数据类型所需的
全部信息。


File: python.info,  Node: 添加参数,  Next: 解析参数,  Prev: 创建一个解析器,  Up: 示例<7>

5.16.4.3 添加参数
.................

给一个 *note ArgumentParser: 69e. 添加程序参数信息是通过调用 *note
add_argument(): 203d. 方法完成的。通常，这些调用指定 *note
ArgumentParser: 69e. 如何获取命令行字符串并将其转换为对象。这些信息在
*note parse_args(): 203e. 调用时被存储和使用。例如：

     >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
     ...                     help='an integer for the accumulator')
     >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
     ...                     const=sum, default=max,
     ...                     help='sum the integers (default: find the max)')

然后，调用 *note parse_args(): 203e. 将返回一个具有 ‘integers’ 和
‘accumulate’ 两个属性的对象。‘integers’ 属性将是一个包含一个或多个整数的
列表，而 ‘accumulate’ 属性当命令行中指定了 ‘--sum’ 参数时将是 *note
sum(): 1e6. 函数，否则则是 *note max(): 813. 函数。


File: python.info,  Node: 解析参数,  Prev: 添加参数,  Up: 示例<7>

5.16.4.4 解析参数
.................

*note ArgumentParser: 69e. 通过 *note parse_args(): 203e. 方法解析参数。
它将检查命令行，把每个参数转换为适当的类型然后调用相应的操作。在大多数情
况下，这意味着一个简单的 *note Namespace: 2040. 对象将从命令行解析出的属
性构建：

     >>> parser.parse_args(['--sum', '7', '-1', '42'])
     Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])

在脚本中，通常 *note parse_args(): 203e. 会被不带参数调用，而 *note
ArgumentParser: 69e. 将自动从 *note sys.argv: c03. 中确定命令行参数。


File: python.info,  Node: ArgumentParser 对象,  Next: add_argument 方法,  Prev: 示例<7>,  Up: argparse --- 命令行选项、参数和子命令解析器

5.16.4.5 ArgumentParser 对象
............................

 -- 类: argparse.ArgumentParser (prog=None, usage=None,
          description=None, epilog=None, parents=[],
          formatter_class=argparse.HelpFormatter, prefix_chars='-',
          fromfile_prefix_chars=None, argument_default=None,
          conflict_handler='error', add_help=True, allow_abbrev=True)

     创建一个新的 *note ArgumentParser: 69e. 对象。所有的参数都应当作为
     关键字参数传入。每个参数在下面都有它更详细的描述，但简而言之，它们
     是：

        * *note prog: 2042. - 程序的名称（默认值：‘sys.argv[0]’）

        * *note usage: 2043. - 描述程序用途的字符串（默认值：从添加到解
          析器的参数生成）

        * *note description: 2044. - 在参数帮助文档之前显示的文本（默认
          值：无）

        * *note epilog: 2045. - 在参数帮助文档之后显示的文本（默认值：无
          ）

        * *note parents: 2046. - 一个 *note ArgumentParser: 69e. 对象的
          列表，它们的参数也应包含在内

        * *note formatter_class: 2047. - 用于自定义帮助文档输出格式的类

        * *note prefix_chars: 2048. - 可选参数的前缀字符集合（默认值：
          ’-’）

        * *note fromfile_prefix_chars: 2049. - 当需要从文件中读取其他参
          数时，用于标识文件名的前缀字符集合（默认值： ‘None’）

        * *note argument_default: 204a. - 参数的全局默认值（默认值：
          ‘None’）

        * *note conflict_handler: 204b. - 解决冲突选项的策略（通常是不必
          要的）

        * *note add_help: 204c. - 为解析器添加一个 ‘-h/--help’ 选项（默
          认值： ‘True’）

        * *note allow_abbrev: 6a0. - 如果缩写是无歧义的，则允许缩写长选
          项 （默认值：‘True’）

     在 3.5 版更改: 增加了 `allow_abbrev' 参数。

     在 3.8 版更改: 在之前的版本中，`allow_abbrev' 还会禁用短旗标分组，
     例如 ‘-vv’ 表示为 ‘-v -v’。

以下部分描述这些参数如何使用。

* Menu:

* prog::
* usage::
* description::
* epilog::
* parents::
* formatter_class::
* prefix_chars::
* fromfile_prefix_chars::
* argument_default::
* allow_abbrev::
* conflict_handler::
* add_help::


File: python.info,  Node: prog,  Next: usage,  Up: ArgumentParser 对象

5.16.4.6 prog
.............

默认情况下，*note ArgumentParser: 69e. 对象使用 ‘sys.argv[0]’ 来确定如何
在帮助消息中显示程序名称。这一默认值几乎总是可取的，因为它将使帮助消息与
从命令行调用此程序的方式相匹配。例如，对于有如下代码的名为
‘myprogram.py’ 的文件：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument('--foo', help='foo help')
     args = parser.parse_args()

该程序的帮助信息将显示 ‘myprogram.py’ 作为程序名称（无论程序从何处被调用
）：

     $ python myprogram.py --help
     usage: myprogram.py [-h] [--foo FOO]

     optional arguments:
      -h, --help  show this help message and exit
      --foo FOO   foo help
     $ cd ..
     $ python subdir/myprogram.py --help
     usage: myprogram.py [-h] [--foo FOO]

     optional arguments:
      -h, --help  show this help message and exit
      --foo FOO   foo help

要更改这样的默认行为，可以使用 ‘prog=’ 参数为 *note ArgumentParser: 69e.
指定另一个值：

     >>> parser = argparse.ArgumentParser(prog='myprogram')
     >>> parser.print_help()
     usage: myprogram [-h]

     optional arguments:
      -h, --help  show this help message and exit

需要注意的是，无论是从 ‘sys.argv[0]’ 或是从 ‘prog=’ 参数确定的程序名称，
都可以在帮助消息里通过 ‘%(prog)s’ 格式说明符来引用。

     >>> parser = argparse.ArgumentParser(prog='myprogram')
     >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
     >>> parser.print_help()
     usage: myprogram [-h] [--foo FOO]

     optional arguments:
      -h, --help  show this help message and exit
      --foo FOO   foo of the myprogram program


File: python.info,  Node: usage,  Next: description,  Prev: prog,  Up: ArgumentParser 对象

5.16.4.7 usage
..............

默认情况下，*note ArgumentParser: 69e. 根据它包含的参数来构建用法消息：

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('--foo', nargs='?', help='foo help')
     >>> parser.add_argument('bar', nargs='+', help='bar help')
     >>> parser.print_help()
     usage: PROG [-h] [--foo [FOO]] bar [bar ...]

     positional arguments:
      bar          bar help

     optional arguments:
      -h, --help   show this help message and exit
      --foo [FOO]  foo help

可以通过 ‘usage=’ 关键字参数覆盖这一默认消息：

     >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
     >>> parser.add_argument('--foo', nargs='?', help='foo help')
     >>> parser.add_argument('bar', nargs='+', help='bar help')
     >>> parser.print_help()
     usage: PROG [options]

     positional arguments:
      bar          bar help

     optional arguments:
      -h, --help   show this help message and exit
      --foo [FOO]  foo help

在用法消息中可以使用 ‘%(prog)s’ 格式说明符来填入程序名称。


File: python.info,  Node: description,  Next: epilog,  Prev: usage,  Up: ArgumentParser 对象

5.16.4.8 description
....................

大多数对 *note ArgumentParser: 69e. 构造方法的调用都会使用
‘description=’ 关键字参数。 这个参数简要描述这个程序做什么以及怎么做。 在
帮助消息中，这个描述会显示在命令行用法字符串和各种参数的帮助消息之间:

     >>> parser = argparse.ArgumentParser(description='A foo that bars')
     >>> parser.print_help()
     usage: argparse.py [-h]

     A foo that bars

     optional arguments:
      -h, --help  show this help message and exit

在默认情况下，description 将被换行以便适应给定的空间。如果想改变这种行为
，见 *note formatter_class: 2047. 参数。


File: python.info,  Node: epilog,  Next: parents,  Prev: description,  Up: ArgumentParser 对象

5.16.4.9 epilog
...............

一些程序喜欢在 description 参数后显示额外的对程序的描述。这种文字能够通
过给 *note ArgumentParser: 69e.:: 提供 ‘epilog=’ 参数而被指定。

     >>> parser = argparse.ArgumentParser(
     ...     description='A foo that bars',
     ...     epilog="And that's how you'd foo a bar")
     >>> parser.print_help()
     usage: argparse.py [-h]

     A foo that bars

     optional arguments:
      -h, --help  show this help message and exit

     And that's how you'd foo a bar

和 *note description: 2044. 参数一样，‘epilog=’ text 在默认情况下会换行
，但是这种行为能够被调整通过提供 *note formatter_class: 2047. 参数给
‘ArgumentParse’.


File: python.info,  Node: parents,  Next: formatter_class,  Prev: epilog,  Up: ArgumentParser 对象

5.16.4.10 parents
.................

有些时候，少数解析器会使用同一系列参数。 单个解析器能够通过提供
‘parents=’ 参数给 *note ArgumentParser: 69e. 而使用相同的参数而不是重复
这些参数的定义。‘parents=’ 参数使用 *note ArgumentParser: 69e. 对象的列
表，从它们那里收集所有的位置和可选的行为，然后将这写行为加到正在构建的
*note ArgumentParser: 69e. 对象。

     >>> parent_parser = argparse.ArgumentParser(add_help=False)
     >>> parent_parser.add_argument('--parent', type=int)

     >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
     >>> foo_parser.add_argument('foo')
     >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
     Namespace(foo='XXX', parent=2)

     >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
     >>> bar_parser.add_argument('--bar')
     >>> bar_parser.parse_args(['--bar', 'YYY'])
     Namespace(bar='YYY', parent=None)

请注意大多数父解析器会指定 ‘add_help=False’ . 否则， ‘ArgumentParse’ 将
会看到两个 ‘-h/--help’ 选项（一个在父参数中一个在子参数中）并且产生一个
错误。

     注解: 你在通过‘‘parents=‘‘ 传递解析器之前必须完全初始化它们。 如果
     你在子解析器之后改变父解析器，这些改变将不会反映在子解析器上。


File: python.info,  Node: formatter_class,  Next: prefix_chars,  Prev: parents,  Up: ArgumentParser 对象

5.16.4.11 formatter_class
.........................

*note ArgumentParser: 69e. 对象允许通过指定备用格式化类来自定义帮助格式
。目前，有四种这样的类。

 -- 类: argparse.RawDescriptionHelpFormatter
 -- 类: argparse.RawTextHelpFormatter
 -- 类: argparse.ArgumentDefaultsHelpFormatter
 -- 类: argparse.MetavarTypeHelpFormatter

*note RawDescriptionHelpFormatter: 204d. 和 *note RawTextHelpFormatter:
204e. 在正文的描述和展示上给与了更多的控制。*note ArgumentParser: 69e. 对
象会将 *note description: 2044. 和 *note epilog: 2045. 的文字在命令行中
自动换行。

     >>> parser = argparse.ArgumentParser(
     ...     prog='PROG',
     ...     description='''this description
     ...         was indented weird
     ...             but that is okay''',
     ...     epilog='''
     ...             likewise for this epilog whose whitespace will
     ...         be cleaned up and whose words will be wrapped
     ...         across a couple lines''')
     >>> parser.print_help()
     usage: PROG [-h]

     this description was indented weird but that is okay

     optional arguments:
      -h, --help  show this help message and exit

     likewise for this epilog whose whitespace will be cleaned up and whose words
     will be wrapped across a couple lines

传 *note RawDescriptionHelpFormatter: 204d. 给 ‘formatter_class=’ 表示
*note description: 2044. 和 *note epilog: 2045. 已经被正确的格式化了，不
能在命令行中被自动换行:

     >>> parser = argparse.ArgumentParser(
     ...     prog='PROG',
     ...     formatter_class=argparse.RawDescriptionHelpFormatter,
     ...     description=textwrap.dedent('''\
     ...         Please do not mess up this text!
     ...         --------------------------------
     ...             I have indented it
     ...             exactly the way
     ...             I want it
     ...         '''))
     >>> parser.print_help()
     usage: PROG [-h]

     Please do not mess up this text!
     --------------------------------
        I have indented it
        exactly the way
        I want it

     optional arguments:
      -h, --help  show this help message and exit

*note RawTextHelpFormatter: 204e. 保留所有种类文字的空格，包括参数的描述
。然而，多重的新行会被替换成一行。如果你想保留多重的空白行，可以在新行之
间加空格。

*note ArgumentDefaultsHelpFormatter: 204f. 自动添加默认的值的信息到每一
个帮助信息的参数中:

     >>> parser = argparse.ArgumentParser(
     ...     prog='PROG',
     ...     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
     >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
     >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
     >>> parser.print_help()
     usage: PROG [-h] [--foo FOO] [bar [bar ...]]

     positional arguments:
      bar         BAR! (default: [1, 2, 3])

     optional arguments:
      -h, --help  show this help message and exit
      --foo FOO   FOO! (default: 42)

*note MetavarTypeHelpFormatter: 2050. 为它的值在每一个参数中使用 *note
type: 2051. 的参数名当作它的显示名（而不是使用通常的格式 *note dest:
2052. ):

     >>> parser = argparse.ArgumentParser(
     ...     prog='PROG',
     ...     formatter_class=argparse.MetavarTypeHelpFormatter)
     >>> parser.add_argument('--foo', type=int)
     >>> parser.add_argument('bar', type=float)
     >>> parser.print_help()
     usage: PROG [-h] [--foo int] float

     positional arguments:
       float

     optional arguments:
       -h, --help  show this help message and exit
       --foo int


File: python.info,  Node: prefix_chars,  Next: fromfile_prefix_chars,  Prev: formatter_class,  Up: ArgumentParser 对象

5.16.4.12 prefix_chars
......................

许多命令行会使用 ‘-’ 当作前缀，比如 ‘-f/--foo’。如果解析器需要支持不同的
或者额外的字符，比如像 ‘+f’ 或者 ‘/foo’ 的选项，可以在参数解析构建器中使
用 ‘prefix_chars=’ 参数。

     >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
     >>> parser.add_argument('+f')
     >>> parser.add_argument('++bar')
     >>> parser.parse_args('+f X ++bar Y'.split())
     Namespace(bar='Y', f='X')

‘prefix_chars=’ 参数默认使用 ‘'-'’。 提供一组不包括 ‘-’ 的字符将导致
‘-f/--foo’ 选项不被允许。


File: python.info,  Node: fromfile_prefix_chars,  Next: argument_default,  Prev: prefix_chars,  Up: ArgumentParser 对象

5.16.4.13 fromfile_prefix_chars
...............................

有些时候，先举个例子，当处理一个特别长的参数列表的时候，把它存入一个文件
中而不是在命令行打出来会很有意义。如果 ‘fromfile_prefix_chars=’ 参数提供
给 *note ArgumentParser: 69e. 构造函数，之后所有类型的字符的参数都会被当
成文件处理，并且会被文件包含的参数替代。举个栗子:

     >>> with open('args.txt', 'w') as fp:
     ...     fp.write('-f\nbar')
     >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
     >>> parser.add_argument('-f')
     >>> parser.parse_args(['-f', 'foo', '@args.txt'])
     Namespace(f='bar')

从文件读取的参数在默认情况下必须一个一行（但是可参见 *note
convert_arg_line_to_args(): 2053.）并且它们被视为与命令行上的原始文件引
用参数位于同一位置。所以在以上例子中，‘['-f', 'foo', '@args.txt']’ 的表
示和 ‘['-f', 'foo', '-f', 'bar']’ 的表示相同。

‘fromfile_prefix_chars=’ 参数默认为 ‘None’，意味着参数不会被当作文件对待
。


File: python.info,  Node: argument_default,  Next: allow_abbrev,  Prev: fromfile_prefix_chars,  Up: ArgumentParser 对象

5.16.4.14 argument_default
..........................

一般情况下，参数默认会通过设置一个默认到 *note add_argument(): 203d. 或
者调用带一组指定键值对的 *note ArgumentParser.set_defaults(): 2054. 方法
。但是有些时候，为参数指定一个普遍适用的解析器会更有用。这能够通过传输
‘argument_default=’ 关键词参数给 *note ArgumentParser: 69e. 来完成。举个
栗子，要全局禁止在 *note parse_args(): 203e. 中创建属性，我们提供
‘argument_default=SUPPRESS’:

     >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
     >>> parser.add_argument('--foo')
     >>> parser.add_argument('bar', nargs='?')
     >>> parser.parse_args(['--foo', '1', 'BAR'])
     Namespace(bar='BAR', foo='1')
     >>> parser.parse_args([])
     Namespace()


File: python.info,  Node: allow_abbrev,  Next: conflict_handler,  Prev: argument_default,  Up: ArgumentParser 对象

5.16.4.15 allow_abbrev
......................

正常情况下，当你向 *note ArgumentParser: 69e. 的 *note parse_args():
203e. 方法传入一个参数列表时，它会 *note recognizes abbreviations: 69f.。

这个特性可以设置 ‘allow_abbrev’ 为 ‘False’ 来关闭:

     >>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
     >>> parser.add_argument('--foobar', action='store_true')
     >>> parser.add_argument('--foonley', action='store_false')
     >>> parser.parse_args(['--foon'])
     usage: PROG [-h] [--foobar] [--foonley]
     PROG: error: unrecognized arguments: --foon

3.5 新版功能.


File: python.info,  Node: conflict_handler,  Next: add_help,  Prev: allow_abbrev,  Up: ArgumentParser 对象

5.16.4.16 conflict_handler
..........................

*note ArgumentParser: 69e. 对象不允许在相同选项字符串下有两种行为。默认
情况下， *note ArgumentParser: 69e. 对象会产生一个异常如果去创建一个正在
使用的选项字符串参数。

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('-f', '--foo', help='old foo help')
     >>> parser.add_argument('--foo', help='new foo help')
     Traceback (most recent call last):
      ..
     ArgumentError: argument --foo: conflicting option string(s): --foo

有些时候（例如：使用 *note parents: 2046.），重写旧的有相同选项字符串的
参数会更有用。为了产生这种行为， ‘'resolve'’ 值可以提供给 *note
ArgumentParser: 69e. 的 ‘conflict_handler=’ 参数:

     >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
     >>> parser.add_argument('-f', '--foo', help='old foo help')
     >>> parser.add_argument('--foo', help='new foo help')
     >>> parser.print_help()
     usage: PROG [-h] [-f FOO] [--foo FOO]

     optional arguments:
      -h, --help  show this help message and exit
      -f FOO      old foo help
      --foo FOO   new foo help

注意 *note ArgumentParser: 69e. 对象只能移除一个行为如果它所有的选项字符
串都被重写。所以，在上面的例子中，旧的 ‘-f/--foo’ 行为 回合 ‘-f’ 行为保
持一样, 因为只有 ‘--foo’ 选项字符串被重写。


File: python.info,  Node: add_help,  Prev: conflict_handler,  Up: ArgumentParser 对象

5.16.4.17 add_help
..................

默认情况下，ArgumentParser 对象添加一个简单的显示解析器帮助信息的选项。
举个栗子，考虑一个名为 ‘myprogram.py’ 的文件包含如下代码:

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument('--foo', help='foo help')
     args = parser.parse_args()

如果 ‘-h’ or ‘--help’ 在命令行中被提供, 参数解析器帮助信息会打印:

     $ python myprogram.py --help
     usage: myprogram.py [-h] [--foo FOO]

     optional arguments:
      -h, --help  show this help message and exit
      --foo FOO   foo help

有时候可能会需要关闭额外的帮助信息。这可以通过在 *note ArgumentParser:
69e. 中设置 ‘add_help=’ 参数为 ‘False’ 来实现。

     >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
     >>> parser.add_argument('--foo', help='foo help')
     >>> parser.print_help()
     usage: PROG [--foo FOO]

     optional arguments:
      --foo FOO  foo help

帮助选项一般为 ‘-h/--help’。如果 ‘prefix_chars=’ 被指定并且没有包含 ‘-’
字符，在这种情况下， ‘-h’ ‘--help’ 不是有效的选项。此时， ‘prefix_chars’
的第一个字符将用作帮助选项的前缀。

     >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
     >>> parser.print_help()
     usage: PROG [+h]

     optional arguments:
       +h, ++help  show this help message and exit


File: python.info,  Node: add_argument 方法,  Next: parse_args 方法,  Prev: ArgumentParser 对象,  Up: argparse --- 命令行选项、参数和子命令解析器

5.16.4.18 add_argument() 方法
.............................

 -- 方法: ArgumentParser.add_argument (name or flags...[, action][,
          nargs][, const][, default][, type][, choices][, required][,
          help][, metavar][, dest])

     定义单个的命令行参数应当如何解析。每个形参都在下面有它自己更多的描
     述，长话短说有：

        * *note name or flags: 2057. - 一个命名或者一个选项字符串的列表
          ，例如 ‘foo’ 或 ‘-f, --foo’。

        * *note action: 2058. - 当参数在命令行中出现时使用的动作基本类型
          。

        * *note nargs: 2059. - 命令行参数应当消耗的数目。

        * *note const: 205a. - 被一些 *note action: 2058. 和 *note
          nargs: 2059. 选择所需求的常数。

        * *note default: 205b. - 当参数未在命令行中出现时使用的值。

        * *note type: 2051. - 命令行参数应当被转换成的类型。

        * *note choices: 205c. - 可用的参数的容器。

        * *note required: 205d. - 此命令行选项是否可省略 （仅选项可用）
          。

        * *note help: 205e. - 一个此选项作用的简单描述。

        * *note metavar: 205f. - 在使用方法消息中使用的参数值示例。

        * *note dest: 2052. - 被添加到 *note parse_args(): 203e. 所返回
          对象上的属性名。

以下部分描述这些参数如何使用。

* Menu:

* name or flags::
* action::
* nargs::
* const::
* 默认值::
* type::
* choices::
* required::
* help::
* metavar::
* dest::
* Action 类::


File: python.info,  Node: name or flags,  Next: action,  Up: add_argument 方法

5.16.4.19 name or flags
.......................

*note add_argument(): 203d. 方法必须知道它是否是一个选项，例如 ‘-f’ 或
‘--foo’，或是一个位置参数，例如一组文件名。第一个传递给 *note
add_argument(): 203d. 的参数必须是一系列 flags 或者是一个简单的参数名。
例如，可以选项可以被这样创建:

     >>> parser.add_argument('-f', '--foo')

而位置参数可以这么创建:

     >>> parser.add_argument('bar')

当 *note parse_args(): 203e. 被调用，选项会以 ‘-’ 前缀识别，剩下的参数则
会被假定为位置参数:

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('-f', '--foo')
     >>> parser.add_argument('bar')
     >>> parser.parse_args(['BAR'])
     Namespace(bar='BAR', foo=None)
     >>> parser.parse_args(['BAR', '--foo', 'FOO'])
     Namespace(bar='BAR', foo='FOO')
     >>> parser.parse_args(['--foo', 'FOO'])
     usage: PROG [-h] [-f FOO] bar
     PROG: error: the following arguments are required: bar


File: python.info,  Node: action,  Next: nargs,  Prev: name or flags,  Up: add_argument 方法

5.16.4.20 action
................

*note ArgumentParser: 69e. 对象将命令行参数与动作相关联。这些动作可以做
与它们相关联的命令行参数的任何事，尽管大多数动作只是简单的向 *note
parse_args(): 203e. 返回的对象上添加属性。‘action’ 命名参数指定了这个命
令行参数应当如何处理。供应的动作有：

   * ‘'store'’ - 存储参数的值。这是默认的动作。例如:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--foo')
          >>> parser.parse_args('--foo 1'.split())
          Namespace(foo='1')

   * ‘'store_const'’ - 存储被 *note const: 205a. 命名参数指定的值。
     ‘'store_const'’ 动作通常用在选项中来指定一些标志。例如:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--foo', action='store_const', const=42)
          >>> parser.parse_args(['--foo'])
          Namespace(foo=42)

   * ‘'store_true'’ and ‘'store_false'’ - 这些是 ‘'store_const'’ 分别用
     作存储 ‘True’ 和 ‘False’ 值的特殊用例。另外，它们的默认值分别为
     ‘False’ 和 ‘True’。例如:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--foo', action='store_true')
          >>> parser.add_argument('--bar', action='store_false')
          >>> parser.add_argument('--baz', action='store_false')
          >>> parser.parse_args('--foo --bar'.split())
          Namespace(foo=True, bar=False, baz=True)

   * ‘'append'’ - 存储一个列表，并且将每个参数值追加到列表中。在允许多次
     使用选项时很有用。例如:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--foo', action='append')
          >>> parser.parse_args('--foo 1 --foo 2'.split())
          Namespace(foo=['1', '2'])

   * ‘'append_const'’ - 这存储一个列表，并将 *note const: 205a. 命名参数
     指定的值追加到列表中。（注意 *note const: 205a. 命名参数默认为
     ‘None’。）‘‘’append_const’‘‘ 动作一般在多个参数需要在同一列表中存储
     常数时会有用。例如:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
          >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
          >>> parser.parse_args('--str --int'.split())
          Namespace(types=[<class 'str'>, <class 'int'>])

   * ‘'count'’ - 计算一个关键字参数出现的数目或次数。例如，对于一个增长
     的详情等级来说有用:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--verbose', '-v', action='count', default=0)
          >>> parser.parse_args(['-vvv'])
          Namespace(verbose=3)

     请注意，`default' 将为 ‘None’，除非显式地设为 `0'。

   * ‘'help'’ - 打印所有当前解析器中的选项和参数的完整帮助信息，然后退出
     。默认情况下，一个 help 动作会被自动加入解析器。关于输出是如何创建
     的，参与 *note ArgumentParser: 69e.。

   * ‘'version'’ - 期望有一个 ‘version=’ 命名参数在 *note
     add_argument(): 203d. 调用中，并打印版本信息并在调用后退出:

          >>> import argparse
          >>> parser = argparse.ArgumentParser(prog='PROG')
          >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
          >>> parser.parse_args(['--version'])
          PROG 2.0

   * ‘'extend'’ - 这会存储一个列表，并将每个参数值加入到列表中。 示例用
     法:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument("--foo", action="extend", nargs="+", type=str)
          >>> parser.parse_args(["--foo", "f1", "--foo", "f2", "f3", "f4"])
          Namespace(foo=['f1', 'f2', 'f3', 'f4'])

     3.8 新版功能.

您还可以通过传递 Action 子类或实现相同接口的其他对象来指定任意操作。建议
的方法是扩展 *note Action: 2060.，覆盖 ‘__call__’ 方法和可选的
‘__init__’ 方法。

一个自定义动作的例子:

     >>> class FooAction(argparse.Action):
     ...     def __init__(self, option_strings, dest, nargs=None, **kwargs):
     ...         if nargs is not None:
     ...             raise ValueError("nargs not allowed")
     ...         super().__init__(option_strings, dest, **kwargs)
     ...     def __call__(self, parser, namespace, values, option_string=None):
     ...         print('%r %r %r' % (namespace, values, option_string))
     ...         setattr(namespace, self.dest, values)
     ...
     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', action=FooAction)
     >>> parser.add_argument('bar', action=FooAction)
     >>> args = parser.parse_args('1 --foo 2'.split())
     Namespace(bar=None, foo=None) '1' None
     Namespace(bar='1', foo=None) '2' '--foo'
     >>> args
     Namespace(bar='1', foo='2')

更多描述，见 *note Action: 2060.。


File: python.info,  Node: nargs,  Next: const,  Prev: action,  Up: add_argument 方法

5.16.4.21 nargs
...............

ArgumentParser 对象通常关联一个单独的命令行参数到一个单独的被执行的动作
。 ‘nargs’ 命名参数关联不同数目的命令行参数到单一动作。支持的值有：

   * ‘N’ （一个整数）。命令行中的 ‘N’ 个参数会被聚集到一个列表中。 例如:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--foo', nargs=2)
          >>> parser.add_argument('bar', nargs=1)
          >>> parser.parse_args('c --foo a b'.split())
          Namespace(bar=['c'], foo=['a', 'b'])

     注意 ‘nargs=1’ 会产生一个单元素列表。这和默认的元素本身是不同的。

   * ‘'?'’。如果可能的话，会从命令行中消耗一个参数，并产生一个单一项。如
     果当前没有命令行参数，则会产生 *note default: 205b. 值。注意，对于
     选项，有另外的用例 - 选项字符串出现但没有跟随命令行参数，则会产生
     *note const: 205a. 值。一些说用用例:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
          >>> parser.add_argument('bar', nargs='?', default='d')
          >>> parser.parse_args(['XX', '--foo', 'YY'])
          Namespace(bar='XX', foo='YY')
          >>> parser.parse_args(['XX', '--foo'])
          Namespace(bar='XX', foo='c')
          >>> parser.parse_args([])
          Namespace(bar='d', foo='d')

     ‘nargs='?'’ 的一个更普遍用法是允许可选的输入或输出文件:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
          ...                     default=sys.stdin)
          >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
          ...                     default=sys.stdout)
          >>> parser.parse_args(['input.txt', 'output.txt'])
          Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
                    outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
          >>> parser.parse_args([])
          Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
                    outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)

   * ‘'*'’。所有当前命令行参数被聚集到一个列表中。注意通过 ‘nargs='*'’ 来
     实现多个位置参数通常没有意义，但是多个选项是可能的。例如:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--foo', nargs='*')
          >>> parser.add_argument('--bar', nargs='*')
          >>> parser.add_argument('baz', nargs='*')
          >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
          Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])

   * ‘'+'’。和 ‘'*'’ 类似，所有当前命令行参数被聚集到一个列表中。另外，
     当前没有至少一个命令行参数时会产生一个错误信息。例如:

          >>> parser = argparse.ArgumentParser(prog='PROG')
          >>> parser.add_argument('foo', nargs='+')
          >>> parser.parse_args(['a', 'b'])
          Namespace(foo=['a', 'b'])
          >>> parser.parse_args([])
          usage: PROG [-h] foo [foo ...]
          PROG: error: the following arguments are required: foo

   * ‘argarse.REMAINDER’。所有剩余的命令行参数被聚集到一个列表中。这通常
     在从一个命令行功能传递参数到另一个命令行功能中时有用:

          >>> parser = argparse.ArgumentParser(prog='PROG')
          >>> parser.add_argument('--foo')
          >>> parser.add_argument('command')
          >>> parser.add_argument('args', nargs=argparse.REMAINDER)
          >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
          Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')

如果不提供 ‘nargs’ 命名参数，则消耗参数的数目将被 *note action: 2058. 决
定。通常这意味着单一项目（非列表）消耗单一命令行参数。


File: python.info,  Node: const,  Next: 默认值,  Prev: nargs,  Up: add_argument 方法

5.16.4.22 const
...............

*note add_argument(): 203d. 的‘‘const‘‘ 参数用于保存不从命令行中读取但被
各种 *note ArgumentParser: 69e. 动作需求的常数值。最常用的两例为：

   * 当 *note add_argument(): 203d. 通过 ‘action='store_const'’ 或
     ‘action='append_const’ 调用时。这些动作将 ‘const’ 值添加到 *note
     parse_args(): 203e. 返回的对象的属性中。在 *note action: 2058. 的描
     述中查看案例。

   * 当 *note add_argument(): 203d. 通过选项（例如 ‘-f’ 或 ‘--foo’）调用
     并且 ‘nargs='?'’ 时。这会创建一个可以跟随零个或一个命令行参数的选项
     。当解析命令行时，如果选项后没有参数，则将用 ‘const’ 代替。在 *note
     nargs: 2059. 描述中查看案例。

对 ‘'store_const'’ 和 ‘'append_const'’ 动作， ‘const’ 命名参数必须给出。
对其他动作，默认为 ‘None’。


File: python.info,  Node: 默认值,  Next: type,  Prev: const,  Up: add_argument 方法

5.16.4.23 默认值
................

所有选项和一些位置参数可能在命令行中被忽略。*note add_argument(): 203d.
的命名参数 ‘default’，默认值为 ‘None’，指定了在命令行参数未出现时应当使
用的值。对于选项， ‘default’ 值在选项未在命令行中出现时使用:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', default=42)
     >>> parser.parse_args(['--foo', '2'])
     Namespace(foo='2')
     >>> parser.parse_args([])
     Namespace(foo=42)

如果 ‘default’ 值是一个字符串，解析器解析此值就像一个命令行参数。特别是
，在将属性设置在 *note Namespace: 2040. 的返回值之前，解析器应用任何提供
的 *note type: 2051. 转换参数。否则解析器使用原值:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--length', default='10', type=int)
     >>> parser.add_argument('--width', default=10.5, type=int)
     >>> parser.parse_args()
     Namespace(length=10, width=10.5)

对于 *note nargs: 2059. 等于 ‘?’ 或 ‘*’ 的位置参数， ‘default’ 值在没有
命令行参数出现时使用。

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('foo', nargs='?', default=42)
     >>> parser.parse_args(['a'])
     Namespace(foo='a')
     >>> parser.parse_args([])
     Namespace(foo=42)

提供 ‘default=argparse.SUPPRESS’ 导致命令行参数未出现时没有属性被添加:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
     >>> parser.parse_args([])
     Namespace()
     >>> parser.parse_args(['--foo', '1'])
     Namespace(foo='1')


File: python.info,  Node: type,  Next: choices,  Prev: 默认值,  Up: add_argument 方法

5.16.4.24 type
..............

默认情况下，*note ArgumentParser: 69e. 对象将命令行参数当作简单字符串读
入。然而，命令行字符串经常需要被当作其它的类型，比如 *note float: 188. 或
者 *note int: 185.。*note add_argument(): 203d. 的 ‘type’ 关键词参数允许
任何的类型检查和类型转换。一般的内建类型和函数可以直接被 ‘type’ 参数使用
。

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('foo', type=int)
     >>> parser.add_argument('bar', type=open)
     >>> parser.parse_args('2 temp.txt'.split())
     Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)

当 ‘type’ 参数被应用到默认参数时，请参考 *note default: 205b. 参数的部分
。

为方便使用不同类型的文件，argparse 模块提供了 FileType 工厂类，该类接受
‘mode=’, ‘bufsize=’, ‘encoding=’ 和 ‘errors=’ 等 *note open(): 4f8. 函数
参数。 例如，‘FileType('w')’ 可被用来创建一个可写文件:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('bar', type=argparse.FileType('w'))
     >>> parser.parse_args(['out.txt'])
     Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)

‘type=’ 可接受任意可调用对象，该对象应传入单个字符串参数并返回转换后的值
:

     >>> def perfect_square(string):
     ...     value = int(string)
     ...     sqrt = math.sqrt(value)
     ...     if sqrt != int(sqrt):
     ...         msg = "%r is not a perfect square" % string
     ...         raise argparse.ArgumentTypeError(msg)
     ...     return value
     ...
     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('foo', type=perfect_square)
     >>> parser.parse_args(['9'])
     Namespace(foo=9)
     >>> parser.parse_args(['7'])
     usage: PROG [-h] foo
     PROG: error: argument foo: '7' is not a perfect square

*note choices: 205c. 关键词参数可能会使类型检查者更方便的检查一个范围的
值。

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('foo', type=int, choices=range(5, 10))
     >>> parser.parse_args(['7'])
     Namespace(foo=7)
     >>> parser.parse_args(['11'])
     usage: PROG [-h] {5,6,7,8,9}
     PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)

详情请查阅 *note choices: 205c. 段落。


File: python.info,  Node: choices,  Next: required,  Prev: type,  Up: add_argument 方法

5.16.4.25 choices
.................

某些命令行参数应当从一组受限值中选择。 这可通过将一个容器对象作为
`choices' 关键字参数传给 *note add_argument(): 203d. 来处理。 当执行命令
行解析时，参数值将被检查，如果参数不是可接受的值之一就将显示错误消息:

     >>> parser = argparse.ArgumentParser(prog='game.py')
     >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
     >>> parser.parse_args(['rock'])
     Namespace(move='rock')
     >>> parser.parse_args(['fire'])
     usage: game.py [-h] {rock,paper,scissors}
     game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
     'paper', 'scissors')

请注意 `choices' 容器包含的内容会在执行任意 *note type: 2051. 转换之后被
检查，因此 `choices' 容器中对象的类型应当与指定的 *note type: 2051. 相匹
配:

     >>> parser = argparse.ArgumentParser(prog='doors.py')
     >>> parser.add_argument('door', type=int, choices=range(1, 4))
     >>> print(parser.parse_args(['3']))
     Namespace(door=3)
     >>> parser.parse_args(['4'])
     usage: doors.py [-h] {1,2,3}
     doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)

任何容器都可作为 `choices' 值传入，因此 *note list: 263. 对象，*note
set: b77. 对象以及自定义容器都是受支持的。


File: python.info,  Node: required,  Next: help,  Prev: choices,  Up: add_argument 方法

5.16.4.26 required
..................

通常，*note argparse: 6. 模块会认为 ‘-f’ 和 ‘--bar’ 等旗标是指明 `可选的
' 参数，它们总是可以在命令行中被忽略。 要让一个选项成为 `必需的'，则可以
将 ‘True’ 作为 ‘required=’ 关键字参数传给 *note add_argument(): 203d.:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', required=True)
     >>> parser.parse_args(['--foo', 'BAR'])
     Namespace(foo='BAR')
     >>> parser.parse_args([])
     usage: [-h] --foo FOO
     : error: the following arguments are required: --foo

如这个例子所示，如果一个选项被标记为 ‘required’，则当该选项未在命令行中
出现时，*note parse_args(): 203e. 将会报告一个错误。

     注解: 必需的选项通常被认为是不适宜的，因为用户会预期 `options' 都是
     `可选的'，因此在可能的情况下应当避免使用它们。


File: python.info,  Node: help,  Next: metavar,  Prev: required,  Up: add_argument 方法

5.16.4.27 help
..............

‘help’ 值是一个包含参数简短描述的字符串。 当用户请求帮助时（一般是通过在
命令行中使用 ‘-h’ 或 ‘--help’ 的方式），这些 ‘help’ 描述将随每个参数一同
显示:

     >>> parser = argparse.ArgumentParser(prog='frobble')
     >>> parser.add_argument('--foo', action='store_true',
     ...                     help='foo the bars before frobbling')
     >>> parser.add_argument('bar', nargs='+',
     ...                     help='one of the bars to be frobbled')
     >>> parser.parse_args(['-h'])
     usage: frobble [-h] [--foo] bar [bar ...]

     positional arguments:
      bar     one of the bars to be frobbled

     optional arguments:
      -h, --help  show this help message and exit
      --foo   foo the bars before frobbling

‘help’ 字符串可包括各种格式描述符以避免重复使用程序名称或参数 *note
default: 205b. 等文本。 有效的描述符包括程序名称 ‘%(prog)s’ 和传给 *note
add_argument(): 203d. 的大部分关键字参数，例如 ‘%(default)s’, ‘%(type)s’
等等:

     >>> parser = argparse.ArgumentParser(prog='frobble')
     >>> parser.add_argument('bar', nargs='?', type=int, default=42,
     ...                     help='the bar to %(prog)s (default: %(default)s)')
     >>> parser.print_help()
     usage: frobble [-h] [bar]

     positional arguments:
      bar     the bar to frobble (default: 42)

     optional arguments:
      -h, --help  show this help message and exit

由于帮助字符串支持 %-formatting，如果你希望在帮助字符串中显示 ‘%’ 字面值
，你必须将其转义为 ‘%%’。

*note argparse: 6. 支持静默特定选项的帮助，具体做法是将 ‘help’ 的值设为
‘argparse.SUPPRESS’:

     >>> parser = argparse.ArgumentParser(prog='frobble')
     >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
     >>> parser.print_help()
     usage: frobble [-h]

     optional arguments:
       -h, --help  show this help message and exit


File: python.info,  Node: metavar,  Next: dest,  Prev: help,  Up: add_argument 方法

5.16.4.28 metavar
.................

当 *note ArgumentParser: 69e. 生成帮助消息时，它需要用某种方式来引用每个
预期的参数。 默认情况下，ArgumentParser 对象使用 *note dest: 2052. 值作
为每个对象的 "name"。 默认情况下，对于位置参数动作，*note dest: 2052. 值
将被直接使用，而对于可选参数动作，*note dest: 2052. 值将被转为大写形式。
因此，一个位置参数 ‘dest='bar'’ 的引用形式将为 ‘bar’。 一个带有单独命令
行参数的可选参数 ‘--foo’ 的引用形式将为 ‘FOO’。 示例如下:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo')
     >>> parser.add_argument('bar')
     >>> parser.parse_args('X --foo Y'.split())
     Namespace(bar='X', foo='Y')
     >>> parser.print_help()
     usage:  [-h] [--foo FOO] bar

     positional arguments:
      bar

     optional arguments:
      -h, --help  show this help message and exit
      --foo FOO

可以使用 ‘metavar’ 来指定一个替代名称:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', metavar='YYY')
     >>> parser.add_argument('bar', metavar='XXX')
     >>> parser.parse_args('X --foo Y'.split())
     Namespace(bar='X', foo='Y')
     >>> parser.print_help()
     usage:  [-h] [--foo YYY] XXX

     positional arguments:
      XXX

     optional arguments:
      -h, --help  show this help message and exit
      --foo YYY

请注意 ‘metavar’ 仅改变 `显示的' 名称 - *note parse_args(): 203e. 对象的
属性名称仍然会由 *note dest: 2052. 值确定。

不同的 ‘nargs’ 值可能导致 metavar 被多次使用。 提供一个元组给 ‘metavar’
即为每个参数指定不同的显示信息:

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('-x', nargs=2)
     >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
     >>> parser.print_help()
     usage: PROG [-h] [-x X X] [--foo bar baz]

     optional arguments:
      -h, --help     show this help message and exit
      -x X X
      --foo bar baz


File: python.info,  Node: dest,  Next: Action 类,  Prev: metavar,  Up: add_argument 方法

5.16.4.29 dest
..............

大多数 *note ArgumentParser: 69e. 动作会添加一些值作为 *note
parse_args(): 203e. 所返回对象的一个属性。 该属性的名称由 *note
add_argument(): 203d. 的 ‘dest’ 关键字参数确定。 对于位置参数动作，
‘dest’ 通常会作为 *note add_argument(): 203d. 的第一个参数提供:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('bar')
     >>> parser.parse_args(['XXX'])
     Namespace(bar='XXX')

对于可选参数动作，‘dest’ 的值通常取自选项字符串。 *note ArgumentParser:
69e. 会通过接受第一个长选项字符串并去掉开头的 ‘--’ 字符串来生成 ‘dest’ 的
值。 如果没有提供长选项字符串，则 ‘dest’ 将通过接受第一个短选项字符串并
去掉开头的 ‘-’ 字符来获得。 任何内部的 ‘-’ 字符都将被转换为 ‘_’ 字符以确
保字符串是有效的属性名称。 下面的例子显示了这种行为:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('-f', '--foo-bar', '--foo')
     >>> parser.add_argument('-x', '-y')
     >>> parser.parse_args('-f 1 -x 2'.split())
     Namespace(foo_bar='1', x='2')
     >>> parser.parse_args('--foo 1 -y 2'.split())
     Namespace(foo_bar='1', x='2')

‘dest’ 允许提供自定义属性名称:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', dest='bar')
     >>> parser.parse_args('--foo XXX'.split())
     Namespace(bar='XXX')


File: python.info,  Node: Action 类,  Prev: dest,  Up: add_argument 方法

5.16.4.30 Action 类
...................

Action 类实现了 Action API，它是一个返回可调用对象的可调用对象，返回的可
调用对象可处理来自命令行的参数。 任何遵循此 API 的对象均可作为 ‘action’
形参传给 ‘add_argument()’。

 -- 类: argparse.Action (option_strings, dest, nargs=None, const=None,
          default=None, type=None, choices=None, required=False,
          help=None, metavar=None)

Action 对象会被 ArgumentParser 用来表示解析从命令行中的一个或多个字符串
中解析出单个参数所必须的信息。 Action 类必须接受两个位置参数以及传给
*note ArgumentParser.add_argument(): 203d. 的任何关键字参数，除了
‘action’ 本身。

Action 的实例（或作为or return value of any callable to the ‘action’ 形
参的任何可调用对象的返回值）应当定义 "dest", "option_strings",
"default", "type", "required", "help" 等属性。 确保这些属性被定义的最容
易方式是调用 ‘Action.__init__’。

Action 的实例应当为可调用对象，因此所有子类都必须重载 ‘__call__’ 方法，
该方法应当接受四个形参:

   * ‘parser’ - 包含此动作的 ArgumentParser 对象。

   * ‘namespace’ - 将由 *note parse_args(): 203e. 返回的 *note
     Namespace: 2040. 对象。 大多数动作会使用 *note setattr(): 15ec. 为
     此对象添加属性。

   * ‘values’ - 已关联的命令行参数，并提供相应的类型转换。 类型转换由
     *note add_argument(): 203d. 的 *note type: 2051. 关键字参数来指定。

   * ‘option_string’ - 被用来发起调用此动作的选项字符串。
     ‘option_string’ 参数是可选的，且此参数在动作关联到位置参数时将被略
     去。

‘__call__’ 方法可以执行任意动作，但通常将基于 ‘dest’ 和 ‘values’ 来设置
‘namespace’ 的属性。


File: python.info,  Node: parse_args 方法,  Next: 其它实用工具,  Prev: add_argument 方法,  Up: argparse --- 命令行选项、参数和子命令解析器

5.16.4.31 parse_args() 方法
...........................

 -- 方法: ArgumentParser.parse_args (args=None, namespace=None)

     将参数字符串转换为对象并将其设为命名空间的属性。 返回带有成员的命名
     空间。

     之前对 *note add_argument(): 203d. 的调用决定了哪些对象被创建以及它
     们如何被赋值。 请参阅 *note add_argument(): 203d. 的文档了解详情。

        * *note args: 2064. - 要解析的字符串列表。 默认值是从 *note
          sys.argv: c03. 获取。

        * *note namespace: 2065. - 用于获取属性的对象。 默认值是一个新的
          空 *note Namespace: 2040. 对象。

* Menu:

* 选项值语法::
* 无效的参数::
* 包含 - 的参数::
* 参数缩写（前缀匹配）::
* 在 sys.argv 以外: 在 sys argv 以外.
* 命名空间对象::


File: python.info,  Node: 选项值语法,  Next: 无效的参数,  Up: parse_args 方法

5.16.4.32 选项值语法
....................

*note parse_args(): 203e. 方法支持多种指定选项值的方式（如果它接受选项的
话）。 在最简单的情况下，选项和它的值是作为两个单独参数传入的:

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('-x')
     >>> parser.add_argument('--foo')
     >>> parser.parse_args(['-x', 'X'])
     Namespace(foo=None, x='X')
     >>> parser.parse_args(['--foo', 'FOO'])
     Namespace(foo='FOO', x=None)

对于长选项（名称长度超过一个字符的选项），选项和值也可以作为单个命令行参
数传入，使用 ‘=’ 分隔它们即可:

     >>> parser.parse_args(['--foo=FOO'])
     Namespace(foo='FOO', x=None)

对于短选项（长度只有一个字符的选项），选项和它的值可以拼接在一起:

     >>> parser.parse_args(['-xX'])
     Namespace(foo=None, x='X')

有些短选项可以使用单个 ‘-’ 前缀来进行合并，如果仅有最后一个选项（或没有
任何选项）需要值的话:

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('-x', action='store_true')
     >>> parser.add_argument('-y', action='store_true')
     >>> parser.add_argument('-z')
     >>> parser.parse_args(['-xyzZ'])
     Namespace(x=True, y=True, z='Z')


File: python.info,  Node: 无效的参数,  Next: 包含 - 的参数,  Prev: 选项值语法,  Up: parse_args 方法

5.16.4.33 无效的参数
....................

在解析命令行时，*note parse_args(): 203e. 会检测多种错误，包括有歧义的选
项、无效的类型、无效的选项、错误的位置参数个数等等。 当遇到这种错误时，
它将退出并打印出错误文本同时附带用法消息:

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('--foo', type=int)
     >>> parser.add_argument('bar', nargs='?')

     >>> # invalid type
     >>> parser.parse_args(['--foo', 'spam'])
     usage: PROG [-h] [--foo FOO] [bar]
     PROG: error: argument --foo: invalid int value: 'spam'

     >>> # invalid option
     >>> parser.parse_args(['--bar'])
     usage: PROG [-h] [--foo FOO] [bar]
     PROG: error: no such option: --bar

     >>> # wrong number of arguments
     >>> parser.parse_args(['spam', 'badger'])
     usage: PROG [-h] [--foo FOO] [bar]
     PROG: error: extra arguments found: badger


File: python.info,  Node: 包含 - 的参数,  Next: 参数缩写（前缀匹配）,  Prev: 无效的参数,  Up: parse_args 方法

5.16.4.34 包含 ‘-’ 的参数
.........................

*note parse_args(): 203e. 方法会在用户明显出错时尝试给出错误信息，但某些
情况本身就存在歧义。 例如，命令行参数 ‘-1’ 可能是尝试指定一个选项也可能
是尝试提供一个位置参数。 *note parse_args(): 203e. 方法在此会谨慎行事：
位置参数只有在它们看起来像负数并且解析器中没有任何选项看起来像负数时才能
以 ‘-’ 打头。:

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('-x')
     >>> parser.add_argument('foo', nargs='?')

     >>> # no negative number options, so -1 is a positional argument
     >>> parser.parse_args(['-x', '-1'])
     Namespace(foo=None, x='-1')

     >>> # no negative number options, so -1 and -5 are positional arguments
     >>> parser.parse_args(['-x', '-1', '-5'])
     Namespace(foo='-5', x='-1')

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('-1', dest='one')
     >>> parser.add_argument('foo', nargs='?')

     >>> # negative number options present, so -1 is an option
     >>> parser.parse_args(['-1', 'X'])
     Namespace(foo=None, one='X')

     >>> # negative number options present, so -2 is an option
     >>> parser.parse_args(['-2'])
     usage: PROG [-h] [-1 ONE] [foo]
     PROG: error: no such option: -2

     >>> # negative number options present, so both -1s are options
     >>> parser.parse_args(['-1', '-1'])
     usage: PROG [-h] [-1 ONE] [foo]
     PROG: error: argument -1: expected one argument

如果你有必须以 ‘-’ 打头的位置参数并且看起来不像负数，你可以插入伪参数
‘'--'’ 以告诉 *note parse_args(): 203e. 在那之后的内容是一个位置参数:

     >>> parser.parse_args(['--', '-f'])
     Namespace(foo='-f', one=None)


File: python.info,  Node: 参数缩写（前缀匹配）,  Next: 在 sys argv 以外,  Prev: 包含 - 的参数,  Up: parse_args 方法

5.16.4.35 参数缩写（前缀匹配）
..............................

*note parse_args(): 203e. 方法 *note 在默认情况下: 6a0. 允许将长选项缩写
为前缀，如果缩写无歧义（即前缀与一个特定选项相匹配）的话:

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('-bacon')
     >>> parser.add_argument('-badger')
     >>> parser.parse_args('-bac MMM'.split())
     Namespace(bacon='MMM', badger=None)
     >>> parser.parse_args('-bad WOOD'.split())
     Namespace(bacon=None, badger='WOOD')
     >>> parser.parse_args('-ba BA'.split())
     usage: PROG [-h] [-bacon BACON] [-badger BADGER]
     PROG: error: ambiguous option: -ba could match -badger, -bacon

可产生一个以上选项的参数会引发错误。 此特定可通过将 *note allow_abbrev:
6a0. 设为 ‘False’ 来禁用。


File: python.info,  Node: 在 sys argv 以外,  Next: 命名空间对象,  Prev: 参数缩写（前缀匹配）,  Up: parse_args 方法

5.16.4.36 在 ‘sys.argv’ 以外
............................

有时在 *note sys.argv: c03. 以外用 ArgumentParser 解析参数也是有用的。 这
可以通过将一个字符串列表传给 *note parse_args(): 203e. 来实现。 它适用于
在交互提示符下进行检测:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument(
     ...     'integers', metavar='int', type=int, choices=range(10),
     ...     nargs='+', help='an integer in the range 0..9')
     >>> parser.add_argument(
     ...     '--sum', dest='accumulate', action='store_const', const=sum,
     ...     default=max, help='sum the integers (default: find the max)')
     >>> parser.parse_args(['1', '2', '3', '4'])
     Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
     >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
     Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])


File: python.info,  Node: 命名空间对象,  Prev: 在 sys argv 以外,  Up: parse_args 方法

5.16.4.37 命名空间对象
......................

 -- 类: argparse.Namespace

     由 *note parse_args(): 203e. 默认使用的简单类，可创建一个存放属性的
     对象并将其返回。

这个类被有意做得很简单，只是一个具有可读字符串表示形式的 *note object:
2b1.。 如果你更喜欢类似字典的属性视图，你可以使用标准 Python 中惯常的
*note vars(): 1047.:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo')
     >>> args = parser.parse_args(['--foo', 'BAR'])
     >>> vars(args)
     {'foo': 'BAR'}

另一个用处是让 *note ArgumentParser: 69e. 为一个已存在对象而不是为一个新
的 *note Namespace: 2040. 对象的属性赋值。 这可以通过指定 ‘namespace=’ 关
键字参数来实现:

     >>> class C:
     ...     pass
     ...
     >>> c = C()
     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo')
     >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
     >>> c.foo
     'BAR'


File: python.info,  Node: 其它实用工具,  Next: 升级 optparse 代码,  Prev: parse_args 方法,  Up: argparse --- 命令行选项、参数和子命令解析器

5.16.4.38 其它实用工具
......................

* Menu:

* 子命令::
* FileType 对象::
* 参数组::
* 互斥::
* 解析器默认值::
* 打印帮助::
* 部分解析::
* 自定义文件解析::
* 退出方法::
* 混合解析::


File: python.info,  Node: 子命令,  Next: FileType 对象,  Up: 其它实用工具

5.16.4.39 子命令
................

 -- 方法: ArgumentParser.add_subparsers ([title][, description][,
          prog][, parser_class][, action][, option_string][, dest][,
          required][, help][, metavar])

     许多程序都会将其功能拆分为一系列子命令，例如，‘svn’ 程序包含的子命
     令有 ‘svn checkout’, ‘svn update’ 和 ‘svn commit’。 当一个程序能执
     行需要多组不同种类命令行参数时这种拆分功能的方式是一个非常好的主意
     。 *note ArgumentParser: 69e. 通过 *note add_subparsers(): 4ac. 方
     法支持创建这样的子命令。 *note add_subparsers(): 4ac. 方法通常不带
     参数地调用并返回一个特殊的动作对象。 这种对象只有一个方法
     ‘add_parser()’，它接受一个命令名称和任意多个 *note ArgumentParser:
     69e. 构造器参数，并返回一个可以通常方式进行修改的 *note
     ArgumentParser: 69e. 对象。

     形参的描述

        * title - 输出帮助的子解析器分组的标题；如果提供了描述则默认为
          "subcommands"，否则使用位置参数的标题

        * description - 输出帮助中对子解析器的描述，默认为 ‘None’

        * prog - 将与子命令帮助一同显示的用法信息，默认为程序名称和子解
          析器参数之前的任何位置参数。

        * parser_class - 将被用于创建子解析器实例的类，默认为当前解析器
          类（例如 ArgumentParser）

        * *note action: 2058. - 当此参数在命令行中出现时要执行动作的基本
          类型

        * *note dest: 2052. - 将被用于保存子命令名称的属性名；默认为
          ‘None’ 即不保存任何值

        * *note required: 205d. - 是否必须要提供子命令，默认为 ‘False’
          (在 3.7 中新增)

        * *note help: 205e. - 在输出帮助中的子解析器分组帮助信息，默认为
          ‘None’

        * *note metavar: 205f. - 帮助信息中表示可用子命令的字符串；默认
          为 ‘None’ 并以 {cmd1, cmd2, ..} 的形式表示子命令

     一些使用示例:

          >>> # create the top-level parser
          >>> parser = argparse.ArgumentParser(prog='PROG')
          >>> parser.add_argument('--foo', action='store_true', help='foo help')
          >>> subparsers = parser.add_subparsers(help='sub-command help')
          >>>
          >>> # create the parser for the "a" command
          >>> parser_a = subparsers.add_parser('a', help='a help')
          >>> parser_a.add_argument('bar', type=int, help='bar help')
          >>>
          >>> # create the parser for the "b" command
          >>> parser_b = subparsers.add_parser('b', help='b help')
          >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
          >>>
          >>> # parse some argument lists
          >>> parser.parse_args(['a', '12'])
          Namespace(bar=12, foo=False)
          >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
          Namespace(baz='Z', foo=True)

     请注意 *note parse_args(): 203e. 返回的对象将只包含主解析器和由命令
     行所选择的子解析器的属性（而没有任何其他子解析器）。 因此在上面的例
     子中，当指定了 ‘a’ 命令时，将只存在 ‘foo’ 和 ‘bar’ 属性，而当指定了
     ‘b’ 命令时，则只存在 ‘foo’ 和 ‘baz’ 属性。

     类似地，当从一个子解析器请求帮助消息时，只有该特定解析器的帮助消息
     会被打印出来。 帮助消息将不包括父解析器或同级解析器的消息。 （每个
     子解析器命令一条帮助消息，但是，也可以像上面那样通过提供 ‘help=’ 参
     数给 ‘add_parser()’ 来给出。）

          >>> parser.parse_args(['--help'])
          usage: PROG [-h] [--foo] {a,b} ...

          positional arguments:
            {a,b}   sub-command help
              a     a help
              b     b help

          optional arguments:
            -h, --help  show this help message and exit
            --foo   foo help

          >>> parser.parse_args(['a', '--help'])
          usage: PROG a [-h] bar

          positional arguments:
            bar     bar help

          optional arguments:
            -h, --help  show this help message and exit

          >>> parser.parse_args(['b', '--help'])
          usage: PROG b [-h] [--baz {X,Y,Z}]

          optional arguments:
            -h, --help     show this help message and exit
            --baz {X,Y,Z}  baz help

     *note add_subparsers(): 4ac. 方法也支持 ‘title’ 和 ‘description’ 关
     键字参数。 当两者都存在时，子解析器的命令将出现在输出帮助消息中它们
     自己的分组内。 例如:

          >>> parser = argparse.ArgumentParser()
          >>> subparsers = parser.add_subparsers(title='subcommands',
          ...                                    description='valid subcommands',
          ...                                    help='additional help')
          >>> subparsers.add_parser('foo')
          >>> subparsers.add_parser('bar')
          >>> parser.parse_args(['-h'])
          usage:  [-h] {foo,bar} ...

          optional arguments:
            -h, --help  show this help message and exit

          subcommands:
            valid subcommands

            {foo,bar}   additional help

     此外，‘add_parser’ 还支持附加的 ‘aliases’ 参数，它允许多个字符串指
     向同一子解析器。 这个例子类似于 ‘svn’，将别名 ‘co’ 设为 ‘checkout’
     的缩写形式:

          >>> parser = argparse.ArgumentParser()
          >>> subparsers = parser.add_subparsers()
          >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
          >>> checkout.add_argument('foo')
          >>> parser.parse_args(['co', 'bar'])
          Namespace(foo='bar')

     一个特别有效的处理子命令的方式是将 *note add_subparsers(): 4ac. 方
     法与对 *note set_defaults(): 2054. 的调用结合起来使用，这样每个子解
     析器就能知道应当执行哪个 Python 函数。 例如:

          >>> # sub-command functions
          >>> def foo(args):
          ...     print(args.x * args.y)
          ...
          >>> def bar(args):
          ...     print('((%s))' % args.z)
          ...
          >>> # create the top-level parser
          >>> parser = argparse.ArgumentParser()
          >>> subparsers = parser.add_subparsers()
          >>>
          >>> # create the parser for the "foo" command
          >>> parser_foo = subparsers.add_parser('foo')
          >>> parser_foo.add_argument('-x', type=int, default=1)
          >>> parser_foo.add_argument('y', type=float)
          >>> parser_foo.set_defaults(func=foo)
          >>>
          >>> # create the parser for the "bar" command
          >>> parser_bar = subparsers.add_parser('bar')
          >>> parser_bar.add_argument('z')
          >>> parser_bar.set_defaults(func=bar)
          >>>
          >>> # parse the args and call whatever function was selected
          >>> args = parser.parse_args('foo 1 -x 2'.split())
          >>> args.func(args)
          2.0
          >>>
          >>> # parse the args and call whatever function was selected
          >>> args = parser.parse_args('bar XYZYX'.split())
          >>> args.func(args)
          ((XYZYX))

     通过这种方式，你可以在参数解析结束后让 *note parse_args(): 203e. 执
     行调用适当函数的任务。 像这样将函数关联到动作通常是你处理每个子解析
     器的不同动作的最简便方式。 但是，如果有必要检查被发起调用的子解析器
     的名称，则 *note add_subparsers(): 4ac. 调用的 ‘dest’ 关键字参数将
     可实现:

          >>> parser = argparse.ArgumentParser()
          >>> subparsers = parser.add_subparsers(dest='subparser_name')
          >>> subparser1 = subparsers.add_parser('1')
          >>> subparser1.add_argument('-x')
          >>> subparser2 = subparsers.add_parser('2')
          >>> subparser2.add_argument('y')
          >>> parser.parse_args(['2', 'frobble'])
          Namespace(subparser_name='2', y='frobble')

     在 3.7 版更改: 新增 `required' 关键字参数。


File: python.info,  Node: FileType 对象,  Next: 参数组,  Prev: 子命令,  Up: 其它实用工具

5.16.4.40 FileType 对象
.......................

 -- 类: argparse.FileType (mode='r', bufsize=-1, encoding=None,
          errors=None)

     *note FileType: 829. 工厂类用于创建可作为 *note
     ArgumentParser.add_argument(): 203d. 的 type 参数传入的对象。 以
     *note FileType: 829. 对象作为其类型的参数将使用命令行参数以所请求模
     式、缓冲区大小、编码格式和错误处理方式打开文件（请参阅 *note
     open(): 4f8. 函数了解详情）:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
          >>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
          >>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
          Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>)

     FileType 对象能理解伪参数 ‘'-'’ 并会自动将其转换为 ‘sys.stdin’ 用于
     可读的 *note FileType: 829. 对象，或是 ‘sys.stdout’ 用于可写的
     *note FileType: 829. 对象:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('infile', type=argparse.FileType('r'))
          >>> parser.parse_args(['-'])
          Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)

     3.4 新版功能: `encodings' 和 `errors' 关键字参数。


File: python.info,  Node: 参数组,  Next: 互斥,  Prev: FileType 对象,  Up: 其它实用工具

5.16.4.41 参数组
................

 -- 方法: ArgumentParser.add_argument_group (title=None,
          description=None)

     在默认情况下，*note ArgumentParser: 69e. 会在显示帮助消息时将命令行
     参数分为“位置参数”和“可选参数”两组。 当存在比默认更好的参数分组概念
     时，可以使用 *note add_argument_group(): 2070. 方法来创建适当的分组
     :

          >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
          >>> group = parser.add_argument_group('group')
          >>> group.add_argument('--foo', help='foo help')
          >>> group.add_argument('bar', help='bar help')
          >>> parser.print_help()
          usage: PROG [--foo FOO] bar

          group:
            bar    bar help
            --foo FOO  foo help

     *note add_argument_group(): 2070. 方法返回一个具有 *note
     add_argument(): 203d. 方法的参数分组对象，这与常规的 *note
     ArgumentParser: 69e. 一样。 当一个参数被加入分组时，解析器会将它视
     为一个正常的参数，但是会在不同的帮助消息分组中显示该参数。 *note
     add_argument_group(): 2070. 方法接受 `title' 和 `description' 参数
     ，它们可被用来定制显示内容:

          >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
          >>> group1 = parser.add_argument_group('group1', 'group1 description')
          >>> group1.add_argument('foo', help='foo help')
          >>> group2 = parser.add_argument_group('group2', 'group2 description')
          >>> group2.add_argument('--bar', help='bar help')
          >>> parser.print_help()
          usage: PROG [--bar BAR] foo

          group1:
            group1 description

            foo    foo help

          group2:
            group2 description

            --bar BAR  bar help

     请注意任意不在你的自定义分组中的参数最终都将回到通常的“位置参数”和
     “可选参数”分组中。


File: python.info,  Node: 互斥,  Next: 解析器默认值,  Prev: 参数组,  Up: 其它实用工具

5.16.4.42 互斥
..............

 -- 方法: ArgumentParser.add_mutually_exclusive_group (required=False)

     创建一个互斥组。 *note argparse: 6. 将会确保互斥组中只有一个参数在
     命令行中可用:

          >>> parser = argparse.ArgumentParser(prog='PROG')
          >>> group = parser.add_mutually_exclusive_group()
          >>> group.add_argument('--foo', action='store_true')
          >>> group.add_argument('--bar', action='store_false')
          >>> parser.parse_args(['--foo'])
          Namespace(bar=True, foo=True)
          >>> parser.parse_args(['--bar'])
          Namespace(bar=False, foo=False)
          >>> parser.parse_args(['--foo', '--bar'])
          usage: PROG [-h] [--foo | --bar]
          PROG: error: argument --bar: not allowed with argument --foo

     *note add_mutually_exclusive_group(): 2072. 方法也接受一个
     `required' 参数，表示在互斥组中至少有一个参数是需要的:

          >>> parser = argparse.ArgumentParser(prog='PROG')
          >>> group = parser.add_mutually_exclusive_group(required=True)
          >>> group.add_argument('--foo', action='store_true')
          >>> group.add_argument('--bar', action='store_false')
          >>> parser.parse_args([])
          usage: PROG [-h] (--foo | --bar)
          PROG: error: one of the arguments --foo --bar is required

     注意，目前互斥参数组不支持 *note add_argument_group(): 2070. 的
     `title' 和 `description' 参数。


File: python.info,  Node: 解析器默认值,  Next: 打印帮助,  Prev: 互斥,  Up: 其它实用工具

5.16.4.43 解析器默认值
......................

 -- 方法: ArgumentParser.set_defaults (**kwargs)

     在大多数时候，*note parse_args(): 203e. 所返回对象的属性将完全通过
     检查命令行参数和参数动作来确定。 *note set_defaults(): 2054. 则允许
     加入一些无须任何命令行检查的额外属性:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('foo', type=int)
          >>> parser.set_defaults(bar=42, baz='badger')
          >>> parser.parse_args(['736'])
          Namespace(bar=42, baz='badger', foo=736)

     请注意解析器层级的默认值总是会覆盖参数层级的默认值:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--foo', default='bar')
          >>> parser.set_defaults(foo='spam')
          >>> parser.parse_args([])
          Namespace(foo='spam')

     解析器层级默认值在需要多解析器时会特别有用。 请参阅 *note
     add_subparsers(): 4ac. 方法了解此类型的一个示例。

 -- 方法: ArgumentParser.get_default (dest)

     获取一个命名空间属性的默认值，该值是由 *note add_argument(): 203d.
     或 *note set_defaults(): 2054. 设置的:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--foo', default='badger')
          >>> parser.get_default('foo')
          'badger'


File: python.info,  Node: 打印帮助,  Next: 部分解析,  Prev: 解析器默认值,  Up: 其它实用工具

5.16.4.44 打印帮助
..................

在大多数典型应用中，*note parse_args(): 203e. 将负责任何用法和错误消息的
格式化和打印。 但是，也可使用某些其他格式化方法:

 -- 方法: ArgumentParser.print_usage (file=None)

     打印一段简短描述，说明应当如何在命令行中发起调用 *note
     ArgumentParser: 69e.。 如果 `file' 为 ‘None’，则默认使用 *note
     sys.stdout: 317.。

 -- 方法: ArgumentParser.print_help (file=None)

     打印一条帮助消息，包括程序用法和通过 *note ArgumentParser: 69e. 注
     册的相关参数信息。 如果 `file' 为 ‘None’，则默认使用 *note
     sys.stdout: 317.。

还存在这些方法的几个变化形式，它们只返回字符串而不打印消息:

 -- 方法: ArgumentParser.format_usage ()

     返回一个包含简短描述的字符串，说明应当如何在命令行中发起调用 *note
     ArgumentParser: 69e.。

 -- 方法: ArgumentParser.format_help ()

     反回一个包含帮助消息的字符串，包括程序用法和通过 *note
     ArgumentParser: 69e. 注册的相关参数信息。


File: python.info,  Node: 部分解析,  Next: 自定义文件解析,  Prev: 打印帮助,  Up: 其它实用工具

5.16.4.45 部分解析
..................

 -- 方法: ArgumentParser.parse_known_args (args=None, namespace=None)

有时一个脚本可能只解析部分命令行参数，而将其余的参数继续传递给另一个脚本
或程序。 在这种情况下，*note parse_known_args(): 207b. 方法会很有用处。
它的作用方式很类似 *note parse_args(): 203e. 但区别在于当存在额外参数时
它不会产生错误。 而是会返回一个由两个条目构成的元组，其中包含带成员的命
名空间和剩余参数字符串的列表。

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', action='store_true')
     >>> parser.add_argument('bar')
     >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
     (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])

     警告: *note 前缀匹配: 69f. 规则应用于 ‘parse_known_args()’。 一个选
     项即使只是已知选项的前缀部分解析器也能识别该选项，不会将其放入剩余
     参数列表。


File: python.info,  Node: 自定义文件解析,  Next: 退出方法,  Prev: 部分解析,  Up: 其它实用工具

5.16.4.46 自定义文件解析
........................

 -- 方法: ArgumentParser.convert_arg_line_to_args (arg_line)

     从文件读取的参数（见 *note ArgumentParser: 69e. 的
     `fromfile_prefix_chars' 关键字参数）将是一行读取一个参数。 *note
     convert_arg_line_to_args(): 2053. 可被重载以使用更复杂的读取方式。

     此方法接受从参数文件读取的字符串形式的单个参数 `arg_line'。 它返回
     从该字符串解析出的参数列表。 此方法将在每次按顺序从参数文件读取一行
     时被调用一次。

     此方法的一个有用的重载是将每个以空格分隔的单词视为一个参数。 下面的
     例子演示了如何实现此重载:

          class MyArgumentParser(argparse.ArgumentParser):
              def convert_arg_line_to_args(self, arg_line):
                  return arg_line.split()


File: python.info,  Node: 退出方法,  Next: 混合解析,  Prev: 自定义文件解析,  Up: 其它实用工具

5.16.4.47 退出方法
..................

 -- 方法: ArgumentParser.exit (status=0, message=None)

     此方法将终结程序，退出时附带指定的 `status'，并且如果给出了
     `message' 则会在退出前将其打印输出。 用户可重载此方法以不同方式来处
     理这些步骤:

          class ErrorCatchingArgumentParser(argparse.ArgumentParser):
              def exit(self, status=0, message=None):
                  if status:
                      raise Exception(f'Exiting because of an error: {message}')
                  exit(status)

 -- 方法: ArgumentParser.error (message)

     此方法将向标准错误打印包括 `message' 的用法消息并附带状态码 2 终结
     程序。


File: python.info,  Node: 混合解析,  Prev: 退出方法,  Up: 其它实用工具

5.16.4.48 混合解析
..................

 -- 方法: ArgumentParser.parse_intermixed_args (args=None,
          namespace=None)

 -- 方法: ArgumentParser.parse_known_intermixed_args (args=None,
          namespace=None)

许多 Unix 命令允许用户混用可选参数与位置参数。 *note
parse_intermixed_args(): 34e. 和 *note parse_known_intermixed_args():
2081. 方法均支持这种解析风格。

这些解析器并不支持所有的 argparse 特性，并且当未支持的特性被使用时将会引
发异常。 特别地，子解析器，‘argparse.REMAINDER’ 以及同时包括可选与位置参
数的互斥分组是不受支持的。

下面的例子显示了 *note parse_known_args(): 207b. 与 *note
parse_intermixed_args(): 34e. 之间的差异：前者会将 ‘['2', '3']’ 返回为未
解析的参数，而后者会将所有位置参数收集至 ‘rest’ 中。

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo')
     >>> parser.add_argument('cmd')
     >>> parser.add_argument('rest', nargs='*', type=int)
     >>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())
     (Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])
     >>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())
     Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])

*note parse_known_intermixed_args(): 2081. 返回由两个条目组成的元组，其
中包含带成员的命名空间以及剩余参数字符串列表。 当存在任何剩余的未解析参
数字符串时 *note parse_intermixed_args(): 34e. 将引发一个错误。

3.7 新版功能.


File: python.info,  Node: 升级 optparse 代码,  Prev: 其它实用工具,  Up: argparse --- 命令行选项、参数和子命令解析器

5.16.4.49 升级 optparse 代码
............................

起初，*note argparse: 6. 曾经尝试通过 *note optparse: c4. 来维持兼容性。
但是，*note optparse: c4. 很难透明地扩展，特别是那些为支持新的 ‘nargs=’
描述方式和更好的用法消息所需的修改。当When most everything in *note
optparse: c4. 中几乎所有内容都已被复制粘贴或打上补丁时，维持向下兼容看来
已是不切实际的。

*note argparse: 6. 模块在许多方面对标准库的 *note optparse: c4. 模块进行
了增强，包括:

   * 处理位置参数。

   * 支持子命令。

   * 允许替代选项前缀例如 ‘+’ 和 ‘/’。

   * 处理零个或多个以及一个或多个风格的参数。

   * 生成更具信息量的用法消息。

   * 提供用于定制 ‘type’ 和 ‘action’ 的更为简单的接口。

从 *note optparse: c4. 到 *note argparse: 6. 的部分升级路径:

   * 将所有 *note optparse.OptionParser.add_option(): 2083. 调用替换为
     *note ArgumentParser.add_argument(): 203d. 调用。

   * 将 ‘(options, args) = parser.parse_args()’ 替换为 ‘args =
     parser.parse_args()’ 并为位置参数添加额外的 *note
     ArgumentParser.add_argument(): 203d. 调用。 请注意之前所谓的
     ‘options’ 在 *note argparse: 6. 上下文中被称为 ‘args’。

   * 通过使用 *note parse_intermixed_args(): 34e. 而非 *note
     parse_args(): 203e. 来替换 *note
     optparse.OptionParser.disable_interspersed_args(): 2084.。

   * 将回调动作和 ‘callback_*’ 关键字参数替换为 ‘type’ 或 ‘action’ 参数
     。

   * 将 ‘type’ 关键字参数字符串名称替换为相应的类型对象（例如 int,
     float, complex 等）。

   * 将 ‘optparse.Values’ 替换为 *note Namespace: 2040. 并将
     ‘optparse.OptionError’ 和 ‘optparse.OptionValueError’ 替换为
     ‘ArgumentError’。

   * 将隐式参数字符串例如使用标准 Python 字典语法的 ‘%default’ 或
     ‘%prog’ 替换为格式字符串，即 ‘%(default)s’ 和 ‘%(prog)s’。

   * 将 OptionParser 构造器 ‘version’ 参数替换为对
     ‘parser.add_argument('--version', action='version', version='<the
     version>')’ 的调用。


File: python.info,  Node: getopt --- C 风格的命令行选项解析器,  Next: logging --- Python 的日志记录工具,  Prev: argparse --- 命令行选项、参数和子命令解析器,  Up: 通用操作系统服务

5.16.5 ‘getopt’ — C 风格的命令行选项解析器
------------------------------------------

`源代码:' Lib/getopt.py(1)

     注解: *note getopt: 87. 模块是一个命令行选项解析器，其 API 设计会让
     C ‘getopt()’ 函数的用户感到熟悉。 不熟悉 C ‘getopt()’ 函数或者希望
     写更少代码并获得更完善帮助和错误消息的用户应当考虑改用 *note
     argparse: 6. 模块。

__________________________________________________________________

此模块可协助脚本解析 ‘sys.argv’ 中的命令行参数。 它支持与 Unix
‘getopt()’ 函数相同的惯例（包括形式如 ’‘-’’ 与 ’‘--’’ 的参数的特殊含义）
。 也能通过可选的第三个参数来使用与 GNU 软件所支持形式相类似的长选项。

此模块提供了两个函数和一个异常:

 -- 函数: getopt.getopt (args, shortopts, longopts=[])

     解析命令行选项与形参列表。 `args' 为要解析的参数列表，不包含最开头
     的对正在运行的程序的引用。 通常这意味着 ‘sys.argv[1:]’。
     `shortopts' 为脚本所要识别的字母选项，包含要求后缀一个冒号 (‘':'’；
     即与 Unix ‘getopt()’ 所用的格式相同) 的选项。

          注解: 与 GNU ‘getopt()’ 不同，在非选项参数之后，所有后续参数都
          会被视为非选项。 这类似于非 GNU Unix 系统的运作方式。

     如果指定了 `longopts'，则必须为一个由应当被支持的长选项名称组成的列
     表。 开头的 ‘'--'’ 字符不应被包括在选项名称中。 要求参数的长选项后
     应当带一个等号 (‘'='’)。 可选参数不被支持。 如果想仅接受长选项，则
     `shortopts' 应为一个空字符串。 命令行中的长选项只要提供了恰好能匹配
     可接受选项之一的选项名称前缀即可被识别。 举例来说，如果 `longopts'
     为 ‘['foo', 'frob']’，则选项 ‘--fo’ 将匹配为 ‘--foo’，但 ‘--f’ 将不
     能得到唯一匹配，因此将引发 *note GetoptError: 2088.。

     返回值由两个元素组成：第一个是 ‘(option, value)’ 对的列表；第二个是
     在去除该选项列表后余下的程序参数列表（这也就是 `args' 的尾部切片）
     。每个被返回的选项与值对的第一个元素是选项，短选项前缀一个连字符 (例
     如 ‘'-x'’)，长选项则前缀两个连字符 (例如 ‘'--long-option'’)，第二个
     元素是选项参数，如果选项不带参数则为空字符串。 列表中选项的排列顺序
     与它们被解析的顺序相同，因此允许多次出现。 长选项与短选项可以混用。

 -- 函数: getopt.gnu_getopt (args, shortopts, longopts=[])

     此函数与 *note getopt(): 87. 类似，区别在于它默认使用 GNU 风格的扫
     描模式。 这意味着选项和非选项参数可能会混在一起。 *note getopt():
     87. 函数将在遇到非选项参数时立即停止处理选项。

     如果选项字符串的第一个字符为 ‘'+'’，或者如果设置了环境变量
     ‘POSIXLY_CORRECT’，则选项处理会在遇到非选项参数时立即停止。

 -- 例外: getopt.GetoptError

     This is raised当参数列表中出现不可识别的选项或者当一个需要参数的选
     项未带参数时将引发此异常。 此异常的参数是一个指明错误原因的字符串。
     对于长选项，将一个参数传给不需要参数的选项也将导致引发此异常。
     ‘msg’ 和 ‘opt’ 属性会给出错误消息和关联的选项；如果没有关联到异常的
     特定选项，则 ‘opt’ 将为空字符串。

 -- 例外: getopt.error

     *note GetoptError: 2088. 的别名；用于向后兼容。

一个仅使用 Unix 风格选项的例子:

     >>> import getopt
     >>> args = '-a -b -cfoo -d bar a1 a2'.split()
     >>> args
     ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
     >>> optlist, args = getopt.getopt(args, 'abc:d:')
     >>> optlist
     [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
     >>> args
     ['a1', 'a2']

使用长选项名也同样容易:

     >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
     >>> args = s.split()
     >>> args
     ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
     >>> optlist, args = getopt.getopt(args, 'x', [
     ...     'condition=', 'output-file=', 'testing'])
     >>> optlist
     [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
     >>> args
     ['a1', 'a2']

在脚本中，典型的用法类似这样:

     import getopt, sys

     def main():
         try:
             opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
         except getopt.GetoptError as err:
             # print help information and exit:
             print(err)  # will print something like "option -a not recognized"
             usage()
             sys.exit(2)
         output = None
         verbose = False
         for o, a in opts:
             if o == "-v":
                 verbose = True
             elif o in ("-h", "--help"):
                 usage()
                 sys.exit()
             elif o in ("-o", "--output"):
                 output = a
             else:
                 assert False, "unhandled option"
         # ...

     if __name__ == "__main__":
         main()

请注意通过 *note argparse: 6. 模块可以使用更少的代码并附带更详细的帮助与
错误消息生成等价的命令行接口:

     import argparse

     if __name__ == '__main__':
         parser = argparse.ArgumentParser()
         parser.add_argument('-o', '--output')
         parser.add_argument('-v', dest='verbose', action='store_true')
         args = parser.parse_args()
         # ... do something with args.output ...
         # ... do something with args.verbose ..

参见
....

模块 *note argparse: 6.

     替代的命令行选项和参数解析库。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/getopt.py


File: python.info,  Node: logging --- Python 的日志记录工具,  Next: logging config --- 日志记录配置,  Prev: getopt --- C 风格的命令行选项解析器,  Up: 通用操作系统服务

5.16.6 ‘logging’ — Python 的日志记录工具
----------------------------------------

`源代码：' Lib/logging/__init__.py(1)

Important
.........

此页面仅包含 API 参考信息。教程信息和更多高级用法的讨论，请参阅

   * *note 基础教程: b7a.

   * *note 进阶教程: b7b.

   * *note 日志操作手册: b7c.

__________________________________________________________________

这个模块为应用与库实现了灵活的事件日志系统的函数与类。

使用标准库提提供的 logging API 最主要的好处是，所有的 Python 模块都可能
参与日志输出，包括你自己的日志消息和第三方模块的日志消息。

这个模块提供许多强大而灵活的功能。如果你对 logging 不太熟悉的话， 掌握它
最好的方式就是查看它对应的教程（详见右侧的链接）。

该模块定义的基础类和函数都列在下面。

   * 记录器暴露了应用程序代码直接使用的接口。

   * 处理器将日志记录（由记录器创建）发送到适当的目标。

   * 过滤器提供了更精细的附加功能，用于确定要输出的日志记录。

   * 格式器指定最终输出中日志记录的样式。

* Menu:

* 记录器对象::
* 日志级别::
* 处理器对象::
* 格式器对象::
* Filter 对象::
* LogRecord 属性::
* LogRecord 属性: LogRecord 属性<2>.
* LoggerAdapter 对象::
* 线程安全::
* 模块级别函数::
* 模块级属性::
* 与警告模块集成::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/logging/__init__.py


File: python.info,  Node: 记录器对象,  Next: 日志级别,  Up: logging --- Python 的日志记录工具

5.16.6.1 记录器对象
...................

记录器有以下的属性和方法。注意 `永远' 不要直接实例化记录器，应当通过模块
级别的函数 ‘logging.getLogger(name)’ 。多次使用相同的名字调用 *note
getLogger(): 208f. 会一直返回相同的 Logger 对象的引用。

‘name’ 一般是句点分割的层级值, 像‘‘foo.bar.baz‘‘ (尽管也可以只是普通的
‘foo’)。层次结构列表中位于下方的记录器是列表中较高位置的记录器的子级。例
如，有个名叫 ‘foo’ 的记录器，而名字是 ‘foo.bar’，‘foo.bar.baz’，和
‘foo.bam’ 的记录器都是 ‘foo’ 的子级。记录器的名字分级类似 Python 包的层
级，如果您使用建议的结构 ‘logging.getLogger(__name__)’ 在每个模块的基础
上组织记录器，则与之完全相同。这是因为在模块里，‘__name__’ 是该模块在
Python 包命名空间中的名字。

 -- 类: logging.Logger

      -- 属性: propagate

          如果这个属性为真，记录到这个记录器的事件除了会发送到此记录器的
          所有处理程序外，还会传递给更高级别（祖先）记录器的处理器，此外
          任何关联到这个记录器的处理器。消息会直接传递给祖先记录器的处理
          器 —— 不考虑祖先记录器的级别和过滤器。

          如果为假，记录消息将不会传递给当前记录器的祖先记录器的处理器。

          构造器将这个属性初始化为 ‘True’。

               注解: 如果你将一个处理器附加到一个记录器 `和' 其一个或多
               个祖先记录器，它可能发出多次相同的记录。通常，您不需要将
               一个处理器附加到一个以上的记录器上 —— 如果您将它附加到记
               录器层次结构中最高的适当记录器上，则它将看到所有后代记录
               器记录的所有事件，前提是它们的传播设置保留为 ‘True’。一种
               常见的方案是仅将处理程序附加到根记录器，通过传播来处理其
               余部分。

      -- 方法: setLevel (level)

          给记录器设置阈值为 `level' 。日志等级小于 `level' 会被忽略。严
          重性为 `level' 或更高的日志消息将由该记录器的任何一个或多个处
          理器发出，除非将处理器的级别设置为比 `level' 更高的级别。

          创建记录器时，级别默认设置为 ‘NOTSET’ （当记录器是根记录器时，
          将处理所有消息；如果记录器不是根记录器，则将委托给父级）。请注
          意，根记录器的默认级别为 ‘WARNING’。

          委派给父级的意思是如果一个记录器的级别设置为 NOTSET，将遍历其
          祖先记录器，直到找到级别不是 NOTSET 的记录器，或者到根记录器为
          止。

          如果发现某个父级的级别不是 NOTSET ，那么该父级的级别将被视为发
          起搜索的记录器的有效级别，并用于确定如何处理日志事件。

          如果搜索到达根记录器，并且其级别为 NOTSET，则将处理所有消息。
          否则，将使用根记录器的级别作为有效级别。

          参见 *note 日志级别: 2092. 级别列表。

          在 3.2 版更改: 现在 `level' 参数可以接受形如 ’INFO’ 的级别字符
          串表示形式，以代替形如 ‘INFO’ 的整数常量。 但是请注意，级别在
          内部存储为整数，并且 *note getEffectiveLevel(): 2093. 和 *note
          isEnabledFor(): 2094. 等方法的传入/返回值也为整数。

      -- 方法: isEnabledFor (level)

          指示此记录器是否将处理级别为 `level' 的消息。此方法首先检查由
          ‘logging.disable(level)’ 设置的模块级的级别，然后检查由 *note
          getEffectiveLevel(): 2093. 确定的记录器的有效级别。

      -- 方法: getEffectiveLevel ()

          指示此记录器的有效级别。如果通过 *note setLevel(): 2091. 设置
          了除 ‘NOTSET’ 以外的值，则返回该值。否则，将层次结构遍历到根，
          直到找到除 ‘NOTSET’ 以外的其他值，然后返回该值。返回的值是一个
          整数，通常为 ‘logging.DEBUG’、 ‘logging.INFO’ 等等。

      -- 方法: getChild (suffix)

          返回由后缀确定的，是该记录器的后代的记录器。 因此，
          ‘logging.getLogger('abc').getChild('def.ghi')’ 与
          ‘logging.getLogger('abc.def.ghi')’ 将返回相同的记录器。 这是一
          个便捷方法，当使用如 ‘__name__’ 而不是字符串字面值命名父记录器
          时很有用。

          3.2 新版功能.

      -- 方法: debug (msg, *args, **kwargs)

          在此纪录器上记录 ‘DEBUG’ 级别的消息。 `msg' 是消息格式字符串，
          而 `args' 是用于字符串格式化操作合并到 `msg' 的参数。（请注意
          ，这意味着您可以在格式字符串中使用关键字以及单个字典参数。）当
          未提供 `args' 时，不会对 `msg' 执行 ％ 格式化操作。

          在 `kwargs' 中会检查四个关键字参数： `exc_info'，
          `stack_info'，`stacklevel*和*extra'。

          如果 `exc_info' 的求值结果不为 false，则它将异常信息添加到日志
          消息中。如果提供了一个异常元组（按照 *note sys.exc_info():
          c67. 返回的格式）或一个异常实例，则将其使用；否则，调用 *note
          sys.exc_info(): c67. 以获取异常信息。

          第二个可选关键字参数是 `stack_info'，默认为 ‘False’。如果为
          True，则将堆栈信息添加到日志消息中，包括实际的日志调用。请注意
          ，这与通过指定 `exc_info' 显示的堆栈信息不同：前者是从堆栈底部
          到当前线程中的日志记录调用的堆栈帧，而后者是在搜索异常处理程序
          时，跟踪异常而打开的堆栈帧的信息。

          您可以独立于 `exc_info' 来指定 `stack_info'，例如，即使在未引
          发任何异常的情况下，也可以显示如何到达代码中的特定点。堆栈帧在
          标题行之后打印：

               Stack (most recent call last):

          这模仿了显示异常帧时所使用的 ‘Traceback (most recent call
          last):’ 。

          第三个可选关键字参数是 `stacklevel'，默认为 ‘1’。如果大于 1，
          则在为日志记录事件创建的 *note LogRecord: 90e. 中计算行号和函
          数名时，将跳过相应数量的堆栈帧。可以在记录帮助器时使用它，以便
          记录的函数名称，文件名和行号不是帮助器的函数/方法的信息，而是
          其调用方的信息。此参数是 *note warnings: 127. 模块中的同名等效
          参数。

          第四个关键字参数是 `extra' ，传递一个字典，该字典用于填充为日
          志记录事件创建的、带有用户自定义属性的 *note LogRecord: 90e. 中
          的__dict__ 。然后可以按照需求使用这些自定义属性。例如，可以将
          它们合并到已记录的消息中：

               FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
               logging.basicConfig(format=FORMAT)
               d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
               logger = logging.getLogger('tcpserver')
               logger.warning('Protocol problem: %s', 'connection reset', extra=d)

          输出类似于

               2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset

          The keys in the dictionary passed in `extra' should not clash
          with the keys used by the logging system.  (See the *note
          Formatter: 2095. documentation for more information on which
          keys are used by the logging system.)

          如果在已记录的消息中使用这些属性，则需要格外小心。例如，在上面
          的示例中，*note Formatter: 2095. 已设置了格式字符串，其在
          *note LogRecord: 90e. 的属性字典中键值为 “clientip” 和 “user”。
          如果缺少这些内容，则将不会记录该消息，因为会引发字符串格式化异
          常。因此，在这种情况下，您始终需要使用这些键传递 `extra' 字典
          。

          尽管这可能很烦人，但此功能旨在用于特殊情况，例如在多个上下文中
          执行相同代码的多线程服务器，并且出现的有趣条件取决于此上下文（
          例如在上面的示例中就是远程客户端IP地址和已验证用户名）。在这种
          情况下，很可能将专门的 *note Formatter: 2095. 与特定的 *note
          Handler: 2096. 一起使用。

          在 3.2 版更改: 增加了 `stack_info' 参数。

          在 3.5 版更改: The `exc_info' parameter can now accept
          exception instances.

          在 3.8 版更改: 增加了 `stacklevel' 参数。

      -- 方法: info (msg, *args, **kwargs)

          在此记录器上记录 ‘INFO’ 级别的消息。参数解释同 *note debug():
          2098.。

      -- 方法: warning (msg, *args, **kwargs)

          在此记录器上记录 ‘WARNING’ 级别的消息。参数解释同 *note
          debug(): 2098.。

               注解: 有一个功能上与 ‘warning’ 一致的方法 ‘warn’。由于
               ‘warn’ 已被弃用，请不要使用它 —— 改为使用 ‘warning’。

      -- 方法: error (msg, *args, **kwargs)

          在此记录器上记录 ‘ERROR’ 级别的消息。参数解释同 *note debug():
          2098.。

      -- 方法: critical (msg, *args, **kwargs)

          在此记录器上记录 ‘CRITICAL’ 级别的消息。参数解释同 *note
          debug(): 2098.。

      -- 方法: log (level, msg, *args, **kwargs)

          在此记录器上记录 `level' 整数代表的级别的消息。参数解释同
          *note debug(): 2098.。

      -- 方法: exception (msg, *args, **kwargs)

          在此记录器上记录 ‘ERROR’ 级别的消息。参数解释同 *note debug():
          2098.。异常信息将添加到日志消息中。仅应从异常处理程序中调用此
          方法。

      -- 方法: addFilter (filter)

          将指定的过滤器 `filter' 添加到此记录器。

      -- 方法: removeFilter (filter)

          从此记录器中删除指定的过滤器 `filter'。

      -- 方法: filter (record)

          将此记录器的过滤器应用于记录，如果记录能被处理则返回 ‘True’。
          过滤器会被依次使用，直到其中一个返回假值为止。如果它们都不返回
          假值，则记录将被处理（传递给处理器）。如果返回任一为假值，则不
          会对该记录做进一步处理。

      -- 方法: addHandler (hdlr)

          将指定的处理器 `hdlr' 添加到此记录器。

      -- 方法: removeHandler (hdlr)

          从此记录器中删除指定的处理器 `hdlr'。

      -- 方法: findCaller (stack_info=False, stacklevel=1)

          查找调用源的文件名和行号，以 文件名，行号，函数名称和堆栈信息
          4元素元组的形式返回。堆栈信息将返回 ‘None’，除非 `stack_info'
          为 ‘True’。

          `stacklevel' 参数用于调用 *note debug(): 2098. 和其他 API。如
          果大于 1，则多余部分将用于跳过堆栈帧，然后再确定要返回的值。当
          从帮助器/包装器代码调用日志记录 API 时，这通常很有用，以便事件
          日志中的信息不是来自帮助器/包装器代码，而是来自调用它的代码。

      -- 方法: handle (record)

          通过将记录传递给与此记录器及其祖先关联的所有处理器来处理（直到
          某个 `propagate' 值为 false）。此方法用于从套接字接收的未序列
          化的以及在本地创建的记录。使用 *note filter(): 209d. 进行记录
          器级别过滤。

      -- 方法: makeRecord (name, level, fn, lno, msg, args, exc_info,
               func=None, extra=None, sinfo=None)

          这是一种工厂方法，可以在子类中对其进行重写以创建专门的 *note
          LogRecord: 90e. 实例。

      -- 方法: hasHandlers ()

          检查此记录器是否配置了任何处理器。通过在此记录器及其记录器层次
          结构中的父级中查找处理器完成此操作。如果找到处理器则返回
          ‘True’，否则返回 ‘False’。只要找到 “propagate” 属性设置为假值
          的记录器，该方法就会停止搜索层次结构 —— 其将是最后一个检查处理
          器是否存在的记录器。

          3.2 新版功能.

     在 3.7 版更改: 现在可以对处理器进行序列化和反序列化。


File: python.info,  Node: 日志级别,  Next: 处理器对象,  Prev: 记录器对象,  Up: logging --- Python 的日志记录工具

5.16.6.2 日志级别
.................

日志记录级别的数值在下表中给出。如果你想要定义自己的级别，并且需要它们具
有相对于预定义级别的特定值，那么这些内容可能是你感兴趣的。如果你定义具有
相同数值的级别，它将覆盖预定义的值; 预定义的名称丢失。

级别               数值
                   
---------------------------------------
                   
‘CRITICAL’         50
                   
                   
‘ERROR’            40
                   
                   
‘WARNING’          30
                   
                   
‘INFO’             20
                   
                   
‘DEBUG’            10
                   
                   
‘NOTSET’           0
                   


File: python.info,  Node: 处理器对象,  Next: 格式器对象,  Prev: 日志级别,  Up: logging --- Python 的日志记录工具

5.16.6.3 处理器对象
...................

Handler 有以下属性和方法。注意不要直接实例化 *note Handler: 2096. ；这个
类用来派生其他更有用的子类。但是，子类的 *note __init__(): d66. 方法需要
调用 *note Handler.__init__(): 20a7. 。

 -- 类: logging.Handler

      -- 方法: __init__ (level=NOTSET)

          初始化 *note Handler: 2096. 实例时，需要设置它的级别，将过滤列
          表置为空，并且创建锁（通过 *note createLock(): 20a8. ）来序列
          化对 I/O 的访问。

      -- 方法: createLock ()

          初始化一个线程锁，用来序列化对底层的 I/O 功能的访问，底层的
          I/O 功能可能不是线程安全的。

      -- 方法: acquire ()

          使用 *note createLock(): 20a8. 获取线程锁。

      -- 方法: release ()

          使用 *note acquire(): 20a9. 来释放线程锁。

      -- 方法: setLevel (level)

          给处理器设置阈值为 `level' 。日志级别小于 `level' 将被忽略。创
          建处理器时，日志级别被设置为 ‘NOTSET’ （所有的消息都会被处理）
          。

          参见 *note 日志级别: 2092. 级别列表。

          在 3.2 版更改: `level' 形参现在接受像 ’INFO’ 这样的字符串形式
          的级别表达方式，也可以使用像 ‘INFO’ 这样的整数常量。

      -- 方法: setFormatter (fmt)

          将此处理器的 *note Formatter: 2095. 设置为 `fmt'。

      -- 方法: addFilter (filter)

          将指定的过滤器 `filter' 添加到此处理器。

      -- 方法: removeFilter (filter)

          从此处理器中删除指定的过滤器 `filter' 。

      -- 方法: filter (record)

          将此处理器的过滤器应用于记录，在要处理记录时返回 ‘True’ 。依次
          查询过滤器，直到其中一个返回假值为止。如果它们都不返回假值，则
          将发出记录。如果返回一个假值，则处理器将不会发出记录。

      -- 方法: flush ()

          确保所有日志记录从缓存输出。此版本不执行任何操作，并且应由子类
          实现。

      -- 方法: close ()

          整理处理器使用的所有资源。此版本不输出，但从内部处理器列表中删
          除处理器，内部处理器在 *note shutdown(): 20b2. 被调用时关闭 。
          子类应确保从重写的 *note close(): 20b1. 方法中调用此方法。

      -- 方法: handle (record)

          经已添加到处理器的过滤器过滤后，有条件地发出指定的日志记录。用
          获取/释放 I/O 线程锁包装记录的实际发出行为。

      -- 方法: handleError (record)

          调用 *note emit(): 20b5. 期间遇到异常时，应从处理器中调用此方
          法。如果模块级属性 ‘raiseExceptions’ 是 ‘False’，则异常将被静
          默忽略。这是大多数情况下日志系统需要的 —— 大多数用户不会关心日
          志系统中的错误，他们对应用程序错误更感兴趣。但是，你可以根据需
          要将其替换为自定义处理器。指定的记录是发生异常时正在处理的记录
          。（‘raiseExceptions’ 的默认值是 ‘True’，因为这在开发过程中是
          比较有用的）。

      -- 方法: format (record)

          如果设置了格式器则用其对记录进行格式化。否则，使用模块的默认格
          式器。

      -- 方法: emit (record)

          执行实际记录给定日志记录所需的操作。这个版本应由子类实现，因此
          这里直接引发 *note NotImplementedError: 617. 异常。

有关作为标准随附的处理程序列表，请参见 *note logging.handlers: ad.。


File: python.info,  Node: 格式器对象,  Next: Filter 对象,  Prev: 处理器对象,  Up: logging --- Python 的日志记录工具

5.16.6.4 格式器对象
...................

*note Formatter: 2095. 对象拥有以下的属性和方法。一般情况下，它们负责将
*note LogRecord: 90e. 转换为可由人或外部系统解释的字符串。基础的 *note
Formatter: 2095. 允许指定格式字符串。如果未提供任何值，则使用默认值
‘'%(message)s'’ ，它仅将消息包括在日志记录调用中。要在格式化输出中包含其
他信息（如时间戳），请阅读下文。

格式器可以使用格式化字符串来初始化，该字符串利用 *note LogRecord: 90e. 的
属性 —— 例如上述默认值，用户的消息和参数预先格式化为 *note LogRecord:
90e. 的 `message' 属性后被使用。此格式字符串包含标准的 Python %-s 样式映
射键。有关字符串格式的更多信息，请参见 *note printf 风格的字符串格式化:
1235.。

The useful mapping keys in a *note LogRecord: 90e. are given in the
section on *note LogRecord 属性: 20b9.

 -- 类: logging.Formatter (fmt=None, datefmt=None, style='%')

     返回 *note Formatter: 2095. 类的新实例。实例将使用整个消息的格式字
     符串以及消息的日期/时间部分的格式字符串进行初始化。如果未指定 `fmt'
     ，则使用 ‘'%(message)s'’。如果未指定 `datefmt'，则使用 *note
     formatTime(): 20ba. 文档中描述的格式。

     `style' 形参可以是 ’%’, ’{’ 或 ’$’ 之一，它决定格式字符串如何与数据
     进行合并：使用 %-formatting, *note str.format(): 4e2. 或 *note
     string.Template: 3f3. 之一。 请参阅 *note
     生效于整个应用程序的格式化样式: 20bb. 了解有关在日志消息中使用 {- 和
     $-formatting 的更多信息。

     在 3.2 版更改: `style' 参数已加入.

     在 3.8 版更改: The `validate' parameter was added.  Incorrect or
     mismatched style and fmt will raise a ‘ValueError’.  For example:
     ‘logging.Formatter('%(asctime)s - %(message)s', style='{')’.

      -- 方法: format (record)

          记录的属性字典用作字符串格式化操作的参数。返回结果字符串。在格
          式化字典之前，需要执行几个准备步骤。 使用 `msg' % `args' 计算
          记录的 `message' 属性。如果格式化字符串包含 ‘'(asctime)'’，则
          调用 *note formatTime(): 20ba. 来格式化事件时间。如果有异常信
          息，则使用 *note formatException(): 20bd. 将其格式化并附加到消
          息中。请注意，格式化的异常信息缓存在属性 `exc_text' 中。这很有
          用，因为可以对异常信息进行序列化并通过网络发送，但是如果您有不
          止一个定制了异常信息格式的 *note Formatter: 2095. 子类，则应格
          外小心。在这种情况下，您必须在格式器完成格式化后清除缓存的值，
          以便下一个处理事件的格式化程序不使用缓存的值，而是重新计算它。

          如果栈信息可用，它将被添加在异常信息之后，如有必要请使用 *note
          formatStack(): 20be. 来转换它。

      -- 方法: formatTime (record, datefmt=None)

          此方法应由想要使用格式化时间的格式器中的 *note format(): 4e3.
          调用。可以在格式器中重写此方法以提供任何特定要求，但是基本行为
          如下：如果指定了 `datefmt' （字符串），则将其用于 *note
          time.strftime(): b6d. 来格式化记录的创建时间。否则，使用格式
          ’%Y-%m-%d %H:%M:%S,uuu’，其中 uuu 部分是毫秒值，其他字母根据
          *note time.strftime(): b6d. 文档。这种时间格式的示例为
          ‘2003-01-23 00:29:50,411’。返回结果字符串。

          此函数使用一个用户可配置函数将创建时间转换为元组。 默认情况下
          ，使用 *note time.localtime(): f5d.；要为特定格式化程序实例更
          改此项，请将实例的 ‘converter’ 属性设为具有与 *note
          time.localtime(): f5d. 或 *note time.gmtime(): b47. 相同签名的
          函数。 要为所有格式化程序更改此项，例如当你希望所有日志时间都
          显示为 GMT，请在 ‘Formatter’ 类中设置 ‘converter’ 属性。

          在 3.3 版更改: 在之前版本中，默认格式为写死的代码，例如这个例
          子: ‘2010-09-06 22:38:15,292’ 其中逗号之前的部分由 strptime 格
          式字符串 (‘'%Y-%m-%d %H:%M:%S'’) 处理，而逗号之后的部分为毫秒
          值。 因为 strptime 没有表示毫秒的占位符，毫秒值使用了另外的格
          式字符串来添加 ‘'%s,%03d'’ — 这两个格式字符串代码都是写死在该
          方法中的。 经过修改，这些字符串被定义为类层级的属性，当需要时
          可以在实例层级上被重载。 属性的名称为 ‘default_time_format’ (用
          于 strptime 格式字符串) 和 ‘default_msec_format’ (用于添加毫秒
          值)。

      -- 方法: formatException (exc_info)

          将指定的异常信息（由 *note sys.exc_info(): c67. 返回的标准异常
          元组）格式化为字符串。 这个默认实现只使用了 *note
          traceback.print_exception(): 20bf.。 结果字符串将被返回。

      -- 方法: formatStack (stack_info)

          将指定的堆栈信息（由 *note traceback.print_stack(): 783. 返回
          的字符串，但移除末尾的换行符）格式化为字符串。 这个默认实现只
          是返回输入值。


File: python.info,  Node: Filter 对象,  Next: LogRecord 属性,  Prev: 格式器对象,  Up: logging --- Python 的日志记录工具

5.16.6.5 Filter 对象
....................

‘Filters’ 可被 ‘Handlers’ 和 ‘Loggers’ 用来实现比按层级提供更复杂的过滤
操作。 基本过滤器类只允许低于日志记录器层级结构中低于特定层级的事件。 例
如，一个用 ’A.B’ 初始化的过滤器将允许 ’A.B’, ’A.B.C’, ’A.B.C.D’, ’A.B.D’
等日志记录器所记录的事件。 但 ’A.BB’, ’B.A.B’ 等则不允许。 如果用空字符
串初始化，则所有事件都会被略过。

 -- 类: logging.Filter (name='')

     返回一个 *note Filter: b7f. 类的实例。 如果指定了 `name'，则它将被
     用来为日志记录器命名，该类及其子类将通过该过滤器允许指定事件通过。
     如果 `name' 为空字符串，则允许所有事件通过。

      -- 方法: filter (record)

          是否要记录指定的记录？返回零表示否，非零表示是。如果认为合适，
          则可以通过此方法就地修改记录。

请注意关联到处理程序的过滤器会在事件由处理程序发出之前被查询，而关联到日
志记录器的过滤器则会在有事件被记录的的任何时候（使用 *note debug():
2098, *note info(): 20c3. 等等）在将事件发送给处理程序之前被查询。 这意
味着由后代日志记录器生成的事件将不会被日志记录器的过滤器设置所过滤，除非
该过滤器也已被应用于后代日志记录器。

你实际上不需要子类化 ‘Filter’: 你可以将传入任何包含 ‘filter’ 方法的具有
相同语义的的实例。

在 3.2 版更改: 你不需要创建专门的 ‘Filter’ 类，或使用具有 ‘filter’ 方法
的其他类：你可以使用一个函数（或其他可调用对象）作为过滤器。 过滤逻辑将
检查过滤器对象是否文化的 ‘filter’ 属性：如果有，就会将它当作是 ‘Filter’
并调用它的 *note filter(): 20c2. 方法。 在其他情况下，则会将它当作是可调
用对象并附带记录作为单一形参进行调用。 返回值应当与 *note filter():
20c2. 的返回值相一致。

虽然过滤器主要被用来根据比层级更复杂的规则来过滤记录，但它们可以查看 由
它们关联的处理程序或日志记录器所处理的每条记录：当你想要执行统计特定日志
记录器或处理程序处理了多少条记录，或是在所处理的 *note LogRecord: 90e. 中
添加、修改或移除属性这样的任务时该特性将很有用处。 显然改变 LogRecord 时
需要相当小心，但将上下文信息注入日志确实是被允许的 (参见 *note
使用过滤器传递上下文信息: 20c4.)。


File: python.info,  Node: LogRecord 属性,  Next: LogRecord 属性<2>,  Prev: Filter 对象,  Up: logging --- Python 的日志记录工具

5.16.6.6 LogRecord 属性
.......................

*note LogRecord: 90e. 实例是每当有日志被记录时由 *note Logger: 3af. 自动
创建的，并且可通过 *note makeLogRecord(): 20c7. 手动创建（例如根据从网络
接收的已封存事件创建）。

 -- 类: logging.LogRecord (name, level, pathname, lineno, msg, args,
          exc_info, func=None, sinfo=None)

     包含与被记录的事件相关的所有信息。

     主要信息是在 ‘msg’ 和 ‘args’ 中传递的，它们使用 ‘msg % args’ 组合到
     一起以创建记录的 ‘message’ 字段。


     参数:

        * ‘name’ – 用于记录由此 LogRecord 所表示 的事件的日志记录器名称
          。 请注意此名称将始终为该值，即使它可以是由附加到不同（祖先）
          日志记录器的处理程序所发出的。

        * ‘level’ – 以数字表示的日志记录事件层级（如 DEBUG, INFO 等）。
          请注意这会转换为 LogRecord 的 `两个' 属性: ‘levelno’ 为数字值
          而 ‘levelname’ 为对应的层级名称。

        * ‘pathname’ – 进行日志记录调用的文件的完整路径名。

        * ‘lineno’ – 记录调用所在源文件中的行号。

        * ‘msg’ – 事件描述消息，可能为带有可变数据占位符的格式字符串。

        * ‘args’ – 要合并到 `msg' 参数以获得事件描述的可变数据。

        * ‘exc_info’ – 包含当前异常信息的异常元组，或者如果没有可用异常
          信息则为 ‘None’。

        * ‘func’ – 发起调用日志记录调用的函数或方法名称。

        * ‘sinfo’ – 一个文本字符串，表示当前线程中从堆栈底部直到日志记录
          调用的堆栈信息。

      -- 方法: getMessage ()

          在将 *note LogRecord: 90e. 实例与任何用户提供的参数合并之后，
          返回此实例的消息。 如果用户提供给日志记录调用的消息参数不是字
          符串，则会在其上调用 *note str(): 339. 以将它转换为字符串。 此
          方法允许将用户定义的类用作消息，类的 ‘__str__’ 方法可以返回要
          使用的实际格式字符串。

     在 3.2 版更改: 通过提供用于创建记录的工厂方法已使得 *note
     LogRecord: 90e. 的创建更易于配置。 该工厂方法可使用 *note
     getLogRecordFactory(): 20c9. 和 *note setLogRecordFactory(): 20ca.
     来设置（在此可查看工厂方法的签名）。

     在创建时可使用此功能将你自己的值注入 *note LogRecord: 90e.。 你可以
     使用以下模式:

          old_factory = logging.getLogRecordFactory()

          def record_factory(*args, **kwargs):
              record = old_factory(*args, **kwargs)
              record.custom_attribute = 0xdecafbad
              return record

          logging.setLogRecordFactory(record_factory)

     通过此模式，多个工厂方法可以被链接起来，并且只要它们不重载彼此的属
     性或是在无意中覆盖了上面列出的标准属性，就不会发生意外。


File: python.info,  Node: LogRecord 属性<2>,  Next: LoggerAdapter 对象,  Prev: LogRecord 属性,  Up: logging --- Python 的日志记录工具

5.16.6.7 LogRecord 属性
.......................

LogRecord 具有许多属性，它们大多数来自于传递给构造器的形参。 （请注意
LogRecord 构造器形参与 LogRecord 属性的名称并不总是完全彼此对应的。） 这
些属性可被用于将来自记录的数据合并到格式字符串中。 下面的表格（按字母顺
序）列出了属性名称、它们的含义以及相应的 %-style 格式字符串内占位符。

如果是使用 {}-格式化 (*note str.format(): 4e2.)，你可以将 ‘{attrname}’ 用
作格式字符串内的占位符。 如果是使用 $-格式化 (*note string.Template:
3f3.)，则会使用 ‘${attrname}’ 的形式。 当然在这两种情况下，都应当将
‘attrname’ 替换为你想要使用的实际属性名称。

在 {}-格式化的情况下，你可以在属性名称之后放置指定的格式化旗标，并用冒号
来分隔两者。 例如，占位符 ‘{msecs:03d}’ 会将毫秒值 ‘4’ 格式化为 ‘004’。
请参看 *note str.format(): 4e2. 文档了解你所能使用的选项的完整细节。

属性名称             格式                          描述
                                                   
-------------------------------------------------------------------------------------------------------
                                                   
args                 不需要格式化。                合并到 ‘msg’ 以产生 ‘message’ 的包含参数的元组，
                                                   或是其中的值将被用于合并的字典（当只有一个参数且
                                                   其类型为字典时）。
                                                   
                                                   
asctime              ‘%(asctime)s’                 表示 *note LogRecord: 90e. 何时被创建的供人查看时
                                                   间值。 默认形式为 ’2003-07-08 16:49:45,896’ (逗号
                                                   之后的数字为时间的毫秒部分)。
                                                   
                                                   
created              ‘%(created)f’                 *note LogRecord: 90e. 被创建的时间（即
                                                   *note time.time(): 326. 的返回值）。
                                                   
                                                   
exc_info             不需要格式化。                异常元组 (例如 ‘sys.exc_info’) 或者如未发生异常则
                                                   为 ‘None’。
                                                   
                                                   
文件名               ‘%(filename)s’                ‘pathname’ 的文件名部分。
                                                   
                                                   
funcName             ‘%(funcName)s’                函数名包括调用日志记录.
                                                   
                                                   
levelname            ‘%(levelname)s’               消息文本记录级别 (‘'DEBUG'’, ‘'INFO'’,
                                                   ‘'WARNING'’, ‘'ERROR'’, ‘'CRITICAL'’).
                                                   
                                                   
levelno              ‘%(levelno)s’                 消息数字记录级别 (‘DEBUG’, ‘INFO’, ‘WARNING’,
                                                   ‘ERROR’, ‘CRITICAL’).
                                                   
                                                   
lineno               ‘%(lineno)d’                  发出日志记录调用所在的源行号（如果可用）。
                                                   
                                                   
message              ‘%(message)s’                 记入日志的消息，即 ‘msg % args’ 的结果。 这是在发
                                                   起调用 *note Formatter.format(): 20bc. 时设置的。
                                                   
                                                   
module               ‘%(module)s’                  模块 (‘filename’ 的名称部分)。
                                                   
                                                   
msecs                ‘%(msecs)d’                   *note LogRecord: 90e. 被创建的时间的毫秒部分。
                                                   
                                                   
msg                  不需要格式化。                在原始日志记录调用中传入的格式字符串。 与 ‘args’
                                                   合并以产生 ‘message’，或是一个任意对象 (参见
                                                   *note 使用任意对象作为消息: 20cc.)。
                                                   
                                                   
名称                 ‘%(name)s’                    用于记录调用的日志记录器名称。
                                                   
                                                   
pathname             ‘%(pathname)s’                发出日志记录调用的源文件的完整路径名（如果可用）
                                                   。
                                                   
                                                   
process              ‘%(process)d’                 进程ID（如果可用）
                                                   
                                                   
processName          ‘%(processName)s’             进程名（如果可用）
                                                   
                                                   
relativeCreated      ‘%(relativeCreated)d’         以毫秒数表示的 LogRecord 被创建的时间，即相对于
                                                   logging 模块被加载时间的差值。
                                                   
                                                   
stack_info           不需要格式化。                当前线程中从堆栈底部起向上直到包括日志记录调用并
                                                   导致创建此记录的堆栈帧的堆栈帧信息（如果可用）。
                                                   
                                                   
thread               ‘%(thread)d’                  线程ID（如果可用）
                                                   
                                                   
threadName           ‘%(threadName)s’              线程名（如果可用）
                                                   

在 3.1 版更改: 添加了 `processName'


File: python.info,  Node: LoggerAdapter 对象,  Next: 线程安全,  Prev: LogRecord 属性<2>,  Up: logging --- Python 的日志记录工具

5.16.6.8 LoggerAdapter 对象
...........................

*note LoggerAdapter: c94. 实例会被用来方便地将上下文信息传入日志记录调用
。 要获取用法示例，请参阅 *note 添加上下文信息到你的日志记录输出: 20cf.
部分。

 -- 类: logging.LoggerAdapter (logger, extra)

     返回一个 *note LoggerAdapter: c94. 的实例，该实例的初始化带有一个下
     层的 *note Logger: 3af. 实例和一个字典类对象。

      -- 方法: process (msg, kwargs)

          修改传递给日志记录调用的消息和/或关键字参数以便插入上下文信息
          。 此实现接受以 `extra' 形式传给构造器的对象并使用 ’extra’ 键
          名将其加入 `kwargs'。 返回值为一个 (`msg', `kwargs') 元组，其
          中传入了（可能经过修改的）参数版本。

在上述方法之外，*note LoggerAdapter: c94. 还支持 *note Logger: 3af. 的下
列方法: *note debug(): 719, *note info(): 2097, *note warning(): 2099,
*note error(): 209a, *note exception(): 717, *note critical(): 718,
*note log(): 716, *note isEnabledFor(): 2094, *note getEffectiveLevel():
2093, *note setLevel(): 2091. 以及 *note hasHandlers(): 20a3.。 这些方法
具有与它们在 *note Logger: 3af. 中的对应方法相同的签名，因此你可以互换使
用这两种类型的实例。

在 3.2 版更改: *note isEnabledFor(): 2094, *note getEffectiveLevel():
2093, *note setLevel(): 2091. 和 *note hasHandlers(): 20a3. 方法已被添加
到 *note LoggerAdapter: c94.。 这些方法会委托给下层的日志记录器。


File: python.info,  Node: 线程安全,  Next: 模块级别函数,  Prev: LoggerAdapter 对象,  Up: logging --- Python 的日志记录工具

5.16.6.9 线程安全
.................

logging 模块的目标是使客户端不必执行任何特殊操作即可确保线程安全。 它通
过使用线程锁来达成这个目标；用一个锁来序列化对模块共享数据的访问，并且每
个处理程序也会创建一个锁来序列化对其下层 I/O 的访问。

如果你要使用 *note signal: eb. 模块来实现异步信号处理程序，则可能无法在
这些处理程序中使用 logging。 这是因为 *note threading: 10a. 模块中的锁实
现并非总是可重入的，所以无法从此类信号处理程序发起调用。


File: python.info,  Node: 模块级别函数,  Next: 模块级属性,  Prev: 线程安全,  Up: logging --- Python 的日志记录工具

5.16.6.10 模块级别函数
......................

在上述的类之外，还有一些模块层级的函数。

 -- 函数: logging.getLogger (name=None)

     返回具有指定 name 的日志记录器，或者当 name 为 ‘None’ 时返回层级结
     构中作为根日志记录器的日志记录器。 如果指定了 name，它通常是以点号
     分隔的带层级结构的名称如 `’a’', `’a.b’' 或 `’a.b.c.d’'。 这些名称的
     选择完全取决于使用 logging 的开发者。

     附带给定 name 的所有对此函数的调用都将返回相同的日志记录器实例。 这
     意味着日志记录器实例不需要在应用的不同部分间传递。

 -- 函数: logging.getLoggerClass ()

     返回标准的 *note Logger: 3af. 类，或是最近传给 *note
     setLoggerClass(): 20d4. 的类。 此函数可以从一个新的类定义中调用，以
     确保安装自定义的 *note Logger: 3af. 类不会撤销其他代码已经应用的自
     定义操作。 例如:

          class MyLogger(logging.getLoggerClass()):
              # ... override behaviour here

 -- 函数: logging.getLogRecordFactory ()

     返回一个被用来创建 *note LogRecord: 90e. 的可调用对象。

     3.2 新版功能: 此函数与 *note setLogRecordFactory(): 20ca. 一起提供
     ，以便允许开发者对如何构造表示日志记录事件的 *note LogRecord: 90e.
     有更好的控制。

     请参阅 *note setLogRecordFactory(): 20ca. 了解有关如何调用该工厂方
     法的更多信息。

 -- 函数: logging.debug (msg, *args, **kwargs)

     在根日志记录器上记录一条 ‘DEBUG’ 级别的消息。 `msg' 是消息格式字符
     串，而 `args' 是要使用字符串格式化运算符合并到 `msg' 的参数。 （请
     注意这意味着你可以在格式字符串中使用关键字以及单个字典参数。）

     在 `kwargs' 中有三个关键字参数会被检查: `exc_info' 参数如果不为假值
     则会将异常信息添加到日志记录消息。 如果提供了异常元组（为 *note
     sys.exc_info(): c67. 的返回值格式）或异常实例则它会被使用；在其他情
     况下，会调用 *note sys.exc_info(): c67. 以获取异常信息。

     第二个可选关键字参数是 `stack_info'，默认为 ‘False’。如果为 True，
     则将堆栈信息添加到日志消息中，包括实际的日志调用。请注意，这与通过
     指定 `exc_info' 显示的堆栈信息不同：前者是从堆栈底部到当前线程中的
     日志记录调用的堆栈帧，而后者是在搜索异常处理程序时，跟踪异常而打开
     的堆栈帧的信息。

     您可以独立于 `exc_info' 来指定 `stack_info'，例如，即使在未引发任何
     异常的情况下，也可以显示如何到达代码中的特定点。堆栈帧在标题行之后
     打印：

          Stack (most recent call last):

     这模仿了显示异常帧时所使用的 ‘Traceback (most recent call last):’ 。

     第三个可选关键字参数是 `extra'，它可被用来传递一个字典，该字典会被
     用来填充为日志记录事件创建并附带用户自定义属性的 LogRecord 的
     __dict__。 之后将可按你的需要使用这些自定义属性。 例如，可以将它们
     合并到已记录的消息中。 举例来说:

          FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
          logging.basicConfig(format=FORMAT)
          d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
          logging.warning('Protocol problem: %s', 'connection reset', extra=d)

     应当会打印出这样的内容:

          2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset

     The keys in the dictionary passed in `extra' should not clash with
     the keys used by the logging system.  (See the *note Formatter:
     2095. documentation for more information on which keys are used by
     the logging system.)

     如果你选择在已记录的消息中使用这些属性，则需要格外小心。 例如在上面
     的示例中，*note Formatter: 2095. 已设置了格式字符串，其在 LogRecord
     的属性字典中应有 ’clientip’ 和 ’user’。 如果缺少这些属性，消息将不
     被记录，因为会引发字符串格式化异常，你始终需要传入带有这些键的
     `extra' 字典。

     尽管这可能很烦人，但此功能旨在用于特殊情况，例如在多个上下文中执行
     相同代码的多线程服务器，并且出现的有趣条件取决于此上下文（例如在上
     面的示例中就是远程客户端IP地址和已验证用户名）。在这种情况下，很可
     能将专门的 *note Formatter: 2095. 与特定的 *note Handler: 2096. 一
     起使用。

     在 3.2 版更改: 增加了 `stack_info' 参数。

 -- 函数: logging.info (msg, *args, **kwargs)

     在根日志记录器上记录一条 ‘INFO’ 级别的消息。 参数解释同 *note
     debug(): 2098.。

 -- 函数: logging.warning (msg, *args, **kwargs)

     在根日志记录器上记录一条 ‘WARNING’ 级别的消息。 参数解释同 *note
     debug(): 2098.。

          注解: 有一个已过时方法 ‘warn’ 其功能与 ‘warning’ 一致。 由于
          ‘warn’ 已被弃用，请不要使用它 —— 而要改用 ‘warning’。

 -- 函数: logging.error (msg, *args, **kwargs)

     在根日志记录器上记录一条 ‘ERROR’ 级别的消息。 参数解释同 *note
     debug(): 2098.

 -- 函数: logging.critical (msg, *args, **kwargs)

     在根日志记录器上记录一条 ‘CRITICAL’ 级别的消息。 参数解释同 *note
     debug(): 2098.。

 -- 函数: logging.exception (msg, *args, **kwargs)

     在根日志记录器上记录一条 ‘ERROR’ 级别的消息。 参数解释同 *note
     debug(): 2098.。 异常信息将被添加到日志消息中。 此函数应当仅从异常
     处理程序中调用。

 -- 函数: logging.log (level, msg, *args, **kwargs)

     在根日志记录器上记录一条 `level' 级别的消息。 其他参数解释同 *note
     debug(): 2098.。

          注解: 上述模块层级的便捷函数均委托给根日志记录器，它们会调用
          *note basicConfig(): 1e1. 以确保至少有一个处理程序可用。 因此
          ，它们 `不应' 在线程中使用，在 Python 2.7.1 和 3.2 之前的版本
          中，除非线程启动 `之前' 已向根日志记录器添加了至少一个处理程序
          方可使用。 在较早的 Python 版本中，由于 *note basicConfig():
          1e1. 中存在线程安全性的不足，这（在少数情况下）可能导致处理程
          序被多次加入根日志记录器，这会进一步导致同一事件出现多条消息。

 -- 函数: logging.disable (level=CRITICAL)

     为所有日志记录器提供重载的级别 `level'，其优先级高于日志记录器自己
     的级别。 当需要临时限制整个应用程序中的日志记录输出时，此功能会很有
     用。 它的效果是禁用所有重要程度为 `level' 及以下的日志记录调用，因
     此如果你附带 INFO 值调用它，则所有 INFO 和 DEBUG 事件就会被丢弃，而
     重要程度为 WARNING 以及上的事件将根据日志记录器的当前有效级别来处理
     。 如果 ‘logging.disable(logging.NOTSET)’ 被调用，它将在实际上移除
     这个重载的级别，因此日志记录输出会再次取决于单个日志记录器的有效级
     别。

     请注意如果你定义了任何高于 ‘CRITICAL’ 的自定义日志级别（并不建议这
     样做），你就将无法沿用 `level' 形参的默认值，而必须显式地提供适当的
     值。

     在 3.7 版更改: `level' 形参默认级别为 ‘CRITICAL’。 请参阅
     bpo-28524(1) 了解此项改变的更多细节。

 -- 函数: logging.addLevelName (level, levelName)

     在一个内部字典中关联级别 `level' 与文本 `levelName'，该字典会被用来
     将数字级别映射为文本表示形式，例如在 *note Formatter: 2095. 格式化
     消息的时候。 此函数也可被用来定义你自己的级别。 唯一的限制是所用的
     所有级别必须使用此函数来注册，级别值必须为正整数并且它们应当按严重
     程度递增顺序逐一递增。

          注解: 如果你考虑要定义你自己的级别，请参阅 *note 自定义级别:
          20db. 部分。

 -- 函数: logging.getLevelName (level)

     返回日志记录级别 `level' 的字符串表示。

     如果 `level' 为预定义的级别 ‘CRITICAL’, ‘ERROR’, ‘WARNING’, ‘INFO’
     或 ‘DEBUG’ 之一则你会得到相应的字符串。 如果你使用 *note
     addLevelName(): 20da. 将级别关联到名称则返回你为 `level' 所关联的名
     称。 如果传入了与已定义级别相对应的数字值，则返回对应的字符串表示。

     `level' 形参也接受级别的字符串表示例如 ’INFO’。 在这种情况下，此函
     数将返回级别所对应的数字值。

     如果未传入可匹配的数字或字符串值，则返回字符串 ’Level %s’ % level。

          注解: 级别在内部以整数表示（因为它们在日志记录逻辑中需要进行比
          较）。 此函数被用于在整数级别与通过 ‘%(levelname)s’ 格式描述符
          方式在格式化日志输出中显示的级别名称之间进行相互的转换 (参见
          *note LogRecord 属性: 20b9.)。

     在 3.4 版更改: 在早于 3.4 的 Python 版本中，此函数也可传入一个文本
     级别名称，并将返回对应的级别数字值。 此未记入文档的行为被视为是一个
     错误，并在 Python 3.4 中被移除，但又在 3.4.2 中被恢复以保持向下兼容
     性。

 -- 函数: logging.makeLogRecord (attrdict)

     创建并返回一个新的 *note LogRecord: 90e. 实例，实例属性由
     `attrdict' 定义。 此函数适用于接受一个封存的 *note LogRecord: 90e.
     属性字典，通过套接字传输，并在接收端将其重建为一个 *note LogRecord:
     90e. 实例。

 -- 函数: logging.basicConfig (**kwargs)

     通过使用默认的 *note Formatter: 2095. 创建一个 *note StreamHandler:
     b7d. 并将其加入根日志记录器来为日志记录系统执行基本配置。 如果没有
     为根日志记录器定义处理程序则 *note debug(): 2098, *note info():
     20c3, *note warning(): 20d5, *note error(): 20d6. 和 *note
     critical(): 20d7. 等函数将自动调用 *note basicConfig(): 1e1.。

     如果根日志记录器已配置了处理程序则此函数将不执行任何操作，除非关键
     字参数 `force' 被设为 ‘True’。

          注解: 此函数应当在其他线程启动之前从主线程被调用。 在 2.7.1 和
          3.2 之前的 Python 版本中，如果此函数从多个线程被调用，一个处理
          程序（在极少的情况下）有可能被多次加入根日志记录器，导致非预期
          的结果例如日志中的消息出现重复。

     支持以下关键字参数。

     格式               描述
                        
     ---------------------------------------------------------------------
                        
     `filename'         使用指定的文件名而不是 StreamHandler 创建
                        FileHandler。
                        
                        
     `filemode'         如果指定了 `filename'，则用此 *note 模式: 1606.
                        打开该文件。 默认模式为 ‘'a'’。
                        
                        
     `format'           使用指定的格式字符串作为处理程序。 默认为属性以
                        冒号分隔的 ‘levelname’, ‘name’ 和 ‘message’。
                        
                        
     `datefmt'          使用指定的日期/时间格式，与
                        *note time.strftime(): b6d. 所接受的格式相同。
                        
                        
     `style'            如果指定了 `format'，将为格式字符串使用此风格。
                        ‘'%'’, ‘'{'’ 或 ‘'$'’ 分别对应于
                        *note printf 风格: 1235,
                        *note str.format(): 4e2. 或
                        *note string.Template: 3f3.。 默认为 ‘'%'’。
                        
                        
     `level'            设置根记录器级别去指定 *note level: 2092.
                        
                        
     `stream'           使用指定的流初始化 StreamHandler。 请注意此参数
                        与 `filename' 是不兼容的 - 如果两者同时存在，则
                        会引发 ‘ValueError’。
                        
                        
     `handlers'         如果指定，这应为一个包含要加入根日志记录器的已
                        创建处理程序的可迭代对象。 任何尚未设置格式描述
                        符的处理程序将被设置为在此函数中创建的默认格式
                        描述符。 请注意此参数与 `filename' 或 `stream'
                        不兼容 —— 如果两者同时存在，则会引发
                        ‘ValueError’。
                        
                        
     `force'            如果将此关键字参数指定为 true，则在执行其他参数
                        指定的配置之前，将移除并关闭附加到根记录器的所
                        有现有处理器。
                        

     在 3.2 版更改: 增加了 `style' 参数。

     在 3.3 版更改: 增加了 `handlers' 参数。 增加了额外的检查来捕获指定
     不兼容参数的情况 (例如同时指定 `handlers' 与 `stream' 或
     `filename'，或者同时指定 `stream' 与 `filename')。

     在 3.8 版更改: 增加了 `force' 参数。

 -- 函数: logging.shutdown ()

     通过刷新和关闭所有处理程序来通知日志记录系统执行有序停止。 此函数应
     当在应用退出时被调用并且在此调用之后不应再使用日志记录系统。

     当 logging 模块被导入时，它会将此函数注册为退出处理程序 (参见 *note
     atexit: c.)，因此通常不需要手动执行该操作。

 -- 函数: logging.setLoggerClass (klass)

     通知日志记录系统在实例化日志记录器时使用 `klass' 类。 该类应当定义
     *note __init__(): d66. 使其只要求一个 name 参数，并且 *note
     __init__(): d66. 应当调用 ‘Logger.__init__()’。 此函数通常会在需要
     使用自定义日志记录器行为的应用程序实例化任何日志记录器之前被调用。
     在此调用之后，在任何其他时刻都不要使用该子类来直接实例化日志记录器
     ：请继续使用 *note logging.getLogger(): 208f. API 来获取你的日志记
     录器。

 -- 函数: logging.setLogRecordFactory (factory)

     设置一个用来创建 *note LogRecord: 90e. 的可调用对象。


     参数: ‘factory’ – 用来实例化日志记录的工厂可调用对象。

     3.2 新版功能: 此函数与 *note getLogRecordFactory(): 20c9. 一起提供
     ，以便允许开发者对如何构造表示日志记录事件的 *note LogRecord: 90e.
     有更好的控制。

     可调用对象 factory 具有如下签名:

     ‘factory(name, level, fn, lno, msg, args, exc_info, func=None,
     sinfo=None, **kwargs)’


          名称: 日志记录器名称


          level: 日志记录级别（数字）。


          fn: 进行日志记录调用的文件的完整路径名。


          lno: 记录调用所在文件中的行号。


          msg: 日志消息。


          args: 日志记录消息的参数。


          exc_info: 异常元组，或 ‘None’ 。


          func: 调用日志记录调用的函数或方法的名称。


          sinfo: 与 *note traceback.print_stack(): 783. 所提供的类似的栈
          回溯信息，显示调用的层级结构。


          kwargs: 其他关键字参数。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28524


File: python.info,  Node: 模块级属性,  Next: 与警告模块集成,  Prev: 模块级别函数,  Up: logging --- Python 的日志记录工具

5.16.6.11 模块级属性
....................

 -- 属性: logging.lastResort

     通过此属性提供的“最后处理者”。 这是一个以 ‘WARNING’ 级别写入到
     ‘sys.stderr’ 的 *note StreamHandler: b7d.，用于在没有任何日志记录配
     置的情况下处理日志记录事件。 最终结果就是将消息打印到 ‘sys.stderr’，
     这会替代先前形式为 "no handlers could be found for logger XYZ" 的错
     误消息。 如果出于某种原因你需要先前的行为，可将 ‘lastResort’ 设为
     ‘None’。

     3.2 新版功能.


File: python.info,  Node: 与警告模块集成,  Prev: 模块级属性,  Up: logging --- Python 的日志记录工具

5.16.6.12 与警告模块集成
........................

*note captureWarnings(): 20df. 函数可用来将 *note logging: ab. 和 *note
warnings: 127. 模块集成。

 -- 函数: logging.captureWarnings (capture)

     此函数用于打开和关闭日志系统对警告的捕获。

     如果 `capture' 是 ‘True’，则 *note warnings: 127. 模块发出的警告将
     重定向到日志记录系统。具体来说，将使用 *note
     warnings.formatwarning(): 1002. 格式化警告信息，并将结果字符串使用
     ‘WARNING’ 等级记录到名为 ‘'py.warnings'’ 的记录器中。

     如果 `capture' 是 ‘False’，则将停止将警告重定向到日志记录系统，并且
     将警告重定向到其原始目标（即在 ‘captureWarnings(True)’ 调用之前的有
     效目标）。

参见
....

*note logging.config: ac. 模块

     日志记录模块的配置 API 。

*note logging.handlers: ad. 模块

     日志记录模块附带的有用处理器。

PEP 282(1) - Logging 系统

     该提案描述了Python标准库中包含的这个特性。

Original Python logging package(2)

     这是该 *note logging: ab. 包的原始来源。该站点提供的软件包版本适用
     于 Python 1.5.2、2.1.x 和 2.2.x，它们不被 *note logging: ab. 包含在
     标准库中。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0282

   (2) https://www.red-dove.com/python_logging.html


File: python.info,  Node: logging config --- 日志记录配置,  Next: logging handlers --- 日志处理,  Prev: logging --- Python 的日志记录工具,  Up: 通用操作系统服务

5.16.7 ‘logging.config’ — 日志记录配置
--------------------------------------

`源代码：' Lib/logging/config.py(1)

Important
.........

此页面仅包含参考信息。有关教程，请参阅

   * *note 基础教程: b7a.

   * *note 进阶教程: b7b.

   * *note 日志操作手册: b7c.

__________________________________________________________________

这一节描述了用于配置 logging 模块的 API。

* Menu:

* 配置函数::
* 配置字典架构::
* 配置文件格式::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/logging/config.py


File: python.info,  Node: 配置函数,  Next: 配置字典架构,  Up: logging config --- 日志记录配置

5.16.7.1 配置函数
.................

下列函数可配置 logging 模块。 它们位于 *note logging.config: ac. 模块中
。 它们的使用是可选的 — 要配置 logging 模块你可以使用这些函数，也可以通
过调用主 API (在 *note logging: ab. 本身定义) 并定义在 *note logging:
ab. 或 *note logging.handlers: ad. 中声明的处理程序。

 -- 函数: logging.config.dictConfig (config)

     从一个字典获取日志记录配置。 字典的内容描述见下文的 *note
     配置字典架构: 20e3.。

     如果在配置期间遇到错误，此函数将引发 *note ValueError: 1fc, *note
     TypeError: 193, *note AttributeError: 3a3. 或 *note ImportError:
     33d. 并附带适当的描述性消息。 下面是将会引发错误的（可能不完整的）
     条件列表:

        * ‘level’ 不是字符串或者不是对应于实际日志记录级别的字符串。

        * ‘propagate’ 值不是布尔类型。

        * id 没有对应的目标。

        * 在增量调用期间发现不存在的处理程序 id。

        * 无效的日志记录器名称。

        * 无法解析为内部或外部对象。

     解析由 ‘DictConfigurator’ 类执行，该类的构造器可传入用于配置的字典
     ，并且具有 ‘configure()’ 方法。 *note logging.config: ac. 模块具有
     可调用属性 ‘dictConfigClass’，其初始值设为 ‘DictConfigurator’。 你
     可以使用你自己的适当实现来替换 ‘dictConfigClass’ 的值。

     *note dictConfig(): b33. 会调用 ‘dictConfigClass’ 并传入指定的字典
     ，然后在所返回的对象上调用 ‘configure()’ 方法以使配置生效:

          def dictConfig(config):
              dictConfigClass(config).configure()

     例如，‘DictConfigurator’ 的子类可以在它自己的 *note __init__():
     d66. 中调用 ‘DictConfigurator.__init__()’，然后设置可以在后续
     ‘configure()’ 调用中使用的自定义前缀。 ‘dictConfigClass’ 将被绑定到
     这个新的子类，然后就可以与在默认的未定制状态下完全相同的方式调用
     *note dictConfig(): b33.。

     3.2 新版功能.

 -- 函数: logging.config.fileConfig (fname, defaults=None,
          disable_existing_loggers=True)

     从一个 *note configparser: 23. 格式文件中读取日志记录配置。 文件格
     式应当与 *note 配置文件格式: 20e4. 中的描述一致。 此函数可在应用程
     序中被多次调用，以允许最终用户在多个预设配置中进行选择（如果开发者
     提供了展示选项并加载选定配置的机制）。


     参数:

        * ‘fname’ – 一个文件名，或一个文件类对象，或是一个派生自 *note
          RawConfigParser: 87a. 的实例。 如果传入了一个派生自
          ‘RawConfigParser’ 的实例，它会被原样使用。 否则，将会实例化一
          个 ‘Configparser’，并且它会从作为 ‘fname’ 传入的对象中读取配置
          。 如果存在 *note readline(): df. 方法，则它会被当作一个文件类
          对象并使用 *note read_file(): 1e6a. 来读取；在其它情况下，它会
          被当作一个文件名并传递给 *note read(): 10b4.。

        * ‘defaults’ – 要传递给 ConfigParser 的默认值可在此参数中指定。

        * ‘disable_existing_loggers’ – 如果指定为 ‘False’，则当执行此调
          用时已存在的日志记录器会保持启用。 默认值为 ‘True’ 因为这将以
          向下兼容方式启用旧行为。 此行为是禁用任何现有的非根日志记录器
          除非它们或它们的上级在日志记录配置中被显式地命名。

     在 3.4 版更改: 现在接受 *note RawConfigParser: 87a. 子类的实例作为
     ‘fname’ 的值。 这有助于:

        * 使用一个配置文件，其中日志记录配置只是全部应用程序配置的一部分
          。

        * 使用从一个文件读取的配置，它随后会在被传给 ‘fileConfig’ 之前由
          使用配置的应用程序来修改（例如基于命令行参数或运行时环境的其他
          部分）。

 -- 函数: logging.config.listen (port=DEFAULT_LOGGING_CONFIG_PORT,
          verify=None)

     在指定的端口上启动套接字服务器，并监听新的配置。 如果未指定端口，则
     会使用模块默认的 ‘DEFAULT_LOGGING_CONFIG_PORT’。 日志记录配置将作为
     适合由 *note dictConfig(): b33. 或 *note fileConfig(): 3b1. 进行处
     理的文件来发送。 返回一个 *note Thread: 235. 实例，你可以在该实例上
     调用 *note start(): 20e5. 来启动服务器，对该服务器你可以在适当的时
     候执行 *note join(): b68.。 要停止该服务器，请调用 *note
     stopListening(): 20e6.。

     如果指定 ‘verify’ 参数，则它应当是一个可调用对象，该对象应当验证通
     过套接字接收的字节数据是否有效且应被处理。 这可以通过对通过套接字发
     送的内容进行加密和/或签名来完成，这样 ‘verify’ 可调用对象就能执行签
     名验证和/或解密。 ‘verify’ 可调用对象的调用会附带一个参数 —— 通过套
     接字接收的字节数据 —— 并应当返回要处理的字节数据，或者返回 ‘None’ 来
     指明这些字节数据应当被丢弃。 返回的字节数据可以与传入的字节数据相同
     （例如在只执行验证的时候），或者也可以完全不同（例如在可能执行了解
     密的时候）。

     要将配置发送到套接字，请读取配置文件并将其作为字节序列发送到套接字
     ，字节序列要以使用 ‘struct.pack('>L', n)’ 打包为二进制格式的四字节
     长度的字符串打头。

          注解: 因为配置的各部分是通过 *note eval(): b98. 传递的，使用此
          函数可能让用户面临安全风险。 虽然此函数仅绑定到 ‘localhost’ 上
          的套接字，因此并不接受来自远端机器的连接，但在某些场景中不受信
          任的代码可以在调用 *note listen(): 87b. 的进程的账户下运行。 具
          体来说，如果如果调用 *note listen(): 87b. 的进程在用户无法彼此
          信任的多用户机器上运行，则恶意用户就能简单地通过连接到受害者的
          *note listen(): 87b. 套接字并发送运行攻击者想在受害者的进程上
          执行的任何代码的配置的方式，安排运行几乎任意的代码。 如果是使
          用默认端口这会特别容易做到，即便使用了不同端口也不难做到。 要
          避免发生这种情况的风险，请在 *note listen(): 87b. 中使用
          ‘verify’ 参数来防止未经认可的配置被应用。

     在 3.4 版更改: 添加了 ‘verify’ 参数。

          注解: 如果你希望将配置发送给未禁用现有日志记录器的监听器，你将
          需要使用 JSON 格式的配置，该格式将使用 *note dictConfig():
          b33. 进行配置。 此方法允许你在你发送的配置中将
          ‘disable_existing_loggers’ 指定为 ‘False’。

 -- 函数: logging.config.stopListening ()

     停止通过对 *note listen(): 87b. 的调用所创建的监听服务器。 此函数的
     调用通常会先于在 *note listen(): 87b. 的返回值上调用 ‘join()’。


File: python.info,  Node: 配置字典架构,  Next: 配置文件格式,  Prev: 配置函数,  Up: logging config --- 日志记录配置

5.16.7.2 配置字典架构
.....................

描述日志记录配置需要列出要创建的不同对象及它们之间的连接；例如，你可以创
建一个名为 ’console’ 的处理程序，然后名为 ’startup’ 的日志记录器将可以把
它的消息发送给 ’console’ 处理程序。 这些对象并不仅限于 *note logging:
ab. 模块所提供的对象，因为你还可以编写你自己的格式化或处理程序类。 这些
类的形参可能还需要包括 ‘sys.stderr’ 这样的外部对象。 描述这些对象和连接
的语法会在下面的 *note 对象连接: 20e8. 中定义。

* Menu:

* 字典架构细节::
* 增量配置::
* 对象连接::
* 用户定义对象::
* 访问外部对象::
* 访问内部对象::
* 导入解析与定制导入器::


File: python.info,  Node: 字典架构细节,  Next: 增量配置,  Up: 配置字典架构

5.16.7.3 字典架构细节
.....................

传给 *note dictConfig(): b33. 的字典必须包含以下的键:

   * `version' - 应设为代表架构版本的整数值。 目前唯一有效的值是 1，使用
     此键可允许架构在继续演化的同时保持向下兼容性。

所有其他键都是可选项，但如存在它们将根据下面的描述来解读。 在下面提到
’configuring dict’ 的所有情况下，都将检查它的特殊键 ‘'()'’ 以确定是否需
要自定义实例化。 如果需要，则会使用下面 *note 用户定义对象: 20ea. 所描述
的机制来创建一个实例；否则，会使用上下文来确定要实例化的对象。

   * `formatters' - 对应的值将是一个字典，其中每个键是一个格式器 ID 而每
     个值则是一个描述如何配置相应 *note Formatter: 2095. 实例的字典。

     将在配置字典中搜索键 ‘format’ 和 ‘datefmt’ (默认值均为 ‘None’) 并且
     这些键会被用于构造 *note Formatter: 2095. 实例。

     在 3.8 版更改: 一个 ‘validate’ 键 (默认值为 ‘True’) 可被添加到配置
     字典的 ‘formatters’ 部分，这会被用来验证格式的有效性。

   * `filters' - 对应的值将是一个字典，其中每个键是一个过滤器 ID 而每个
     值则是一个描述如何配置相应 Filter 实例的字典。

     将在配置字典中搜索键 ‘name’ (默认值为空字符串) 并且该键会被用于构造
     *note logging.Filter: b7f. 实例。

   * `handlers' - 对应的值将是一个字典，其中每个键是一个处理程序 ID 而每
     个值则是一个描述如何配置相应 Handler 实例的字典。

     将在配置字典中搜索下列键:

        * ‘class’ (强制)。 这是处理程序类的完整限定名称。

        * ‘level’ (可选)。 处理程序的级别。

        * ‘formatter’ (可选)。 处理程序所对应格式化器的 ID。

        * ‘filters’ (可选)。 由处理程序所对应过滤器的 ID 组成的列表。

     所有 `其他' 键会被作为关键字参数传递给处理程序类的构造器。 例如，给
     定如下代码段:

          handlers:
            console:
              class : logging.StreamHandler
              formatter: brief
              level   : INFO
              filters: [allow_foo]
              stream  : ext://sys.stdout
            file:
              class : logging.handlers.RotatingFileHandler
              formatter: precise
              filename: logconfig.log
              maxBytes: 1024
              backupCount: 3

     ID 为 ‘console’ 的处理程序会被实例化为 *note logging.StreamHandler:
     b7d.，并使用 ‘sys.stdout’ 作为下层流。 ID 为 ‘file’ 的处理程序会被
     实例化为 *note logging.handlers.RotatingFileHandler: 20eb.，并附带
     关键字参数 ‘filename='logconfig.log', maxBytes=1024,
     backupCount=3’。

   * `loggers' - 对应的值将是一个字典，其中每个键是一个日志记录器名称而
     每个值则是一个描述如何配置相应 Logger 实例的字典。

     将在配置字典中搜索下列键:

        * ‘level’ (可选)。 日志记录器的级别。

        * ‘propagate’ (可选)。 日志记录器的传播设置。

        * ‘filters’ (可选)。 由日志记录器对应过滤器的 ID 组成的列表。

        * ‘handlers’ (可选)。 由日志记录器对应处理程序的 ID 组成的列表。

     指定的日志记录器将根据指定的级别、传播、过滤器和处理程序来配置。

   * `root' - 这将成为根日志记录器对应的配置。 配置的处理方式将与所有日
     志记录器一致，除了 ‘propagate’ 设置将不可用之外。

   * `incremental' - 配置是否要被解读为在现有配置上新增。 该值默认为
     ‘False’，这意味着指定的配置将以与当前 *note fileConfig(): 3b1. API
     所使用的相同语义来替代现有的配置。

     如果指定的值为 ‘True’，配置会按照 *note 增量配置: 20ec. 部分所描述
     的方式来处理。

   * `disable_existing_loggers' - 是否要禁用任何现有的非根日志记录器。 该
     设置对应于 *note fileConfig(): 3b1. 中的同名形参。 如果省略，则此形
     参默认为 ‘True’。 如果 `incremental' 为 ‘True’ 则该省会被忽略。


File: python.info,  Node: 增量配置,  Next: 对象连接,  Prev: 字典架构细节,  Up: 配置字典架构

5.16.7.4 增量配置
.................

为增量配置提供完全的灵活性是很困难的。 例如，由于过滤器和格式化器这样的
对象是匿名的，一旦完成配置，在增加配置时就不可能引用这些匿名对象。

此外，一旦完成了配置，在运行时任意改变日志记录器、处理程序、过滤器、格式
化器的对象图就不是很有必要；日志记录器和处理程序的详细程度只需通过设置级
别即可实现控制（对于日志记录器则可设置传播旗标）。 在多线程环境中以安全
的方式任意改变对象图也许会导致问题；虽然并非不可能，但这样做的好处不足以
抵销其所增加的实现复杂度。

这样，当配置字典的 ‘incremental’ 键存在且为 ‘True’ 时，系统将完全忽略任
何 ‘formatters’ 和 ‘filters’ 条目，并仅会处理 ‘handlers’ 条目中的
‘level’ 设置，以及 ‘loggers’ 和 ‘root’ 条目中的 ‘level’ 和 ‘propagate’ 设
置。

使用配置字典中的值可让配置以封存字典对象的形式通过线路传送给套接字监听器
。 这样，长时间运行的应用程序的日志记录的详细程度可随时间改变而无须停止
并重新启动应用程序。


File: python.info,  Node: 对象连接,  Next: 用户定义对象,  Prev: 增量配置,  Up: 配置字典架构

5.16.7.5 对象连接
.................

该架构描述了一组日志记录对象 —— 日志记录器、处理程序、格式化器、过滤器
—— 它们在对象图中彼此连接。 因此，该架构需要能表示对象之间的连接。 例如
，在配置完成后，一个特定的日志记录器关联到了一个特定的处理程序。 出于讨
论的目的，我们可以说该日志记录器代表两者间连接的源头，而处理程序则代表对
应的目标。 当然在已配置对象中这是由包含对处理程序的引用的日志记录器来代
表的。 在配置字典中，这是通过给每个目标对象一个 ID 来无歧义地标识它，然
后在源头对象中使用该 ID 来实现的。

因此，举例来说，考虑以下 YAML 代码段:

     formatters:
       brief:
         # configuration for formatter with id 'brief' goes here
       precise:
         # configuration for formatter with id 'precise' goes here
     handlers:
       h1: #This is an id
        # configuration of handler with id 'h1' goes here
        formatter: brief
       h2: #This is another id
        # configuration of handler with id 'h2' goes here
        formatter: precise
     loggers:
       foo.bar.baz:
         # other configuration for logger 'foo.bar.baz'
         handlers: [h1, h2]

（注：这里使用 YAML 是因为它的可读性比表示字典的等价 Python 源码形式更好
。）

日志记录器 ID 就是日志记录器的名称，它会在程序中被用来获取对日志记录器的
引用，例如 ‘foo.bar.baz’。 格式化器和过滤器的 ID 可以是任意字符串值 (例
如上面的 ‘brief’, ‘precise’) 并且它们是瞬态的，因为它们仅对处理配置字典
有意义并会被用来确定对象之间的连接，而当配置调用完成时不会在任何地方保留
。

上面的代码片段指明名为 ‘foo.bar.baz’ 的日志记录器应当关联到两个处理程序
，它们的 ID 是 ‘h1’ 和 ‘h2’。 ‘h1’ 的格式化器的 ID 是 ‘brief’，而 ‘h2’ 的
格式化器的 ID 是 ‘precise’。


File: python.info,  Node: 用户定义对象,  Next: 访问外部对象,  Prev: 对象连接,  Up: 配置字典架构

5.16.7.6 用户定义对象
.....................

此架构支持用户定义对象作为处理程序、过滤器和格式化器。 （日志记录器的不
同实例不需要具有不同类型，因此这个配置架构并不支持用户定义日志记录器类。
）

要配置的对象是由字典描述的，其中包含它们的配置详情。 在某些地方，日志记
录系统将能够从上下文中推断出如何实例化一个对象，但是当要实例化一个用户自
定义对象时，系统将不知道要如何做。 为了提供用户自定义对象实例化的完全灵
活性，用户需要提供一个‘工厂’函数 —— 即在调用时传入配置字典并返回实例化对
象的可调用对象。 这是用一个通过特殊键 ‘'()'’ 来访问的工厂函数的绝对导入
路径来标示的。 下面是一个实际的例子:

     formatters:
       brief:
         format: '%(message)s'
       default:
         format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
         datefmt: '%Y-%m-%d %H:%M:%S'
       custom:
           (): my.package.customFormatterFactory
           bar: baz
           spam: 99.9
           answer: 42

上面的 YAML 代码片段定义了三个格式化器。 第一个的 ID 为 ‘brief’，是带有
特殊格式字符串的标准 *note logging.Formatter: 2095. 实例。 第二个的 ID 为
‘default’，具有更长的格式同时还显式地定义了时间格式，并将最终实例化一个
带有这两个格式字符串的 *note logging.Formatter: 2095.。 以 Python 源代码
形式显示的 ‘brief’ 和 ‘default’ 格式化器具有下列配置子字典:

     {
       'format' : '%(message)s'
     }

和:

     {
       'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
       'datefmt' : '%Y-%m-%d %H:%M:%S'
     }

并且由于这些字典不包含特殊键 ‘'()'’，实例化方式是从上下文中推断出来的：
结果会创建标准的 *note logging.Formatter: 2095. 实例。 第三个格式器的 ID
为 ‘custom’，对应配置子字典为:

     {
       '()' : 'my.package.customFormatterFactory',
       'bar' : 'baz',
       'spam' : 99.9,
       'answer' : 42
     }

并且它包含特殊键 ‘'()'’，这意味着需要用户自定义实例化方式。 在此情况下，
将使用指定的工厂可调用对象。 如果它本身就是一个可调用对象则将被直接使用
—— 否则如果你指定了一个字符串（如这个例子所示）则将使用正常的导入机制来
定位实例的可调用对象。 调用该可调用对象将传入配置子字典中 `剩余的' 条目
作为关键字参数。 在上面的例子中，调用将预期返回 ID 为 ‘custom’ 的格式化
器:

     my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)

将 ‘'()'’ 用作特殊键是因为它不是一个有效的关键字形参名称，这样就不会与调
用中使用的关键字参数发生冲突。 ‘'()'’ 还被用作表明对应值为可调用对象的助
记符。


File: python.info,  Node: 访问外部对象,  Next: 访问内部对象,  Prev: 用户定义对象,  Up: 配置字典架构

5.16.7.7 访问外部对象
.....................

有时一个配置需要引用配置以外的对象，例如 ‘sys.stderr’。 如果配置字典是使
用 Python 代码构造的，这会很直观，但是当配置是通过文本文件（例如 JSON,
YAML）提供的时候就会引发问题。 在一个文本文件中，没有将 ‘sys.stderr’ 与
字符串字面值 ‘'sys.stderr'’ 区分开来的标准方式。 为了实现这种区分，配置
系统会在字符串值中查找规定的特殊前缀并对其做特殊处理。 例如，如果在配置
中将字符串字面值 ‘'ext://sys.stderr'’ 作为一个值来提供，则 ‘ext://’ 将被
去除而该值的剩余部分将使用正常导入机制来处理。

此类前缀的处理方式类似于协议处理：存在一种通用机制来查找与正则表达式
‘^(?P<prefix>[a-z]+)://(?P<suffix>.*)$’ 相匹配的前缀，如果识别出了
‘prefix’，则 ‘suffix’ 会以与前缀相对应的方式来处理并且处理的结果将替代原
字符串值。 如果未识别出前缀，则原字符串将保持不变。


File: python.info,  Node: 访问内部对象,  Next: 导入解析与定制导入器,  Prev: 访问外部对象,  Up: 配置字典架构

5.16.7.8 访问内部对象
.....................

除了外部对象，有时还需要引用配置中的对象。 这将由配置系统针对它所了解的
内容隐式地完成。 例如，在日志记录器或处理程序中表示 ‘level’ 的字符串值
‘'DEBUG'’ 将被自动转换为值 ‘logging.DEBUG’，而 ‘handlers’, ‘filters’ 和
‘formatter’ 条目将接受一个对象 ID 并解析为适当的目标对象。

但是，对于 *note logging: ab. 模块所不了解的用户自定义对象则需要一种更通
用的机制。 例如，考虑 *note logging.handlers.MemoryHandler: 20f4.，它接
受一个 ‘target’ 参数即其所委托的另一个处理程序。 由于系统已经知道存在该
类，因而在配置中，给定的 ‘target’ 只需为相应目标处理程序的的对象 ID 即可
，而系统将根据该 ID 解析出处理程序。 但是，如果用户定义了一个具有
‘alternate’ 处理程序的 ‘my.package.MyHandler’，则配置程序将不知道
‘alternate’ 指向的是一个处理程序。 为了应对这种情况，通用解析系统允许用
户指定:

     handlers:
       file:
         # configuration of file handler goes here

       custom:
         (): my.package.MyHandler
         alternate: cfg://handlers.file

字符串字面值 ‘'cfg://handlers.file'’ 将按照与 ‘ext://’ 前缀类似的方式被
解析为结果字符串，但查找操作是在配置自身而不是在导入命名空间中进行。 该
机制允许按点号或按索引来访问，与 ‘str.format’ 所提供的方式类似。 这样，
给定以下代码段:

     handlers:
       email:
         class: logging.handlers.SMTPHandler
         mailhost: localhost
         fromaddr: my_app@domain.tld
         toaddrs:
           - support_team@domain.tld
           - dev_team@domain.tld
         subject: Houston, we have a problem.

在该配置中，字符串 ‘'cfg://handlers'’ 将解析为带有 ‘handlers’ 键的字典，
字符串 ‘'cfg://handlers.email’ 将解析为 ‘handlers’ 字典中带有 ‘email’ 键
的字典，依此类推。 字符串 ‘'cfg://handlers.email.toaddrs[1]’ 将解析为
‘'dev_team.domain.tld'’ 而字符串 ‘'cfg://handlers.email.toaddrs[0]'’ 将
解析为值 ‘'support_team@domain.tld'’。 ‘subject’ 值可以使用
‘'cfg://handlers.email.subject'’ 或者等价的
‘'cfg://handlers.email[subject]'’ 来访问。 后一种形式仅在键包含空格或非
字母数字类字符的情况下才需要使用。 如果一个索引仅由十进制数码构成，则将
尝试使用相应的整数值来访问，如果有必要则将回退为字符串值。

给定字符串 ‘cfg://handlers.myhandler.mykey.123’，这将解析为
‘config_dict['handlers']['myhandler']['mykey']['123']’。 如果字符串被指
定为 ‘cfg://handlers.myhandler.mykey[123]’，系统将尝试从
‘config_dict['handlers']['myhandler']['mykey'][123]’ 中提取值，并在尝试
失败时回退为 ‘config_dict['handlers']['myhandler']['mykey']['123']’。


File: python.info,  Node: 导入解析与定制导入器,  Prev: 访问内部对象,  Up: 配置字典架构

5.16.7.9 导入解析与定制导入器
.............................

导入解析默认使用内置的 *note __import__(): 619. 函数来执行导入。 你可能
想要将其替换为你自己的导入机制：如果是这样的话，你可以替换
‘DictConfigurator’ 或其超类 ‘BaseConfigurator’ 类的 ‘importer’ 属性。 但
是你必须小心谨慎，因为函数是从类中通过描述器方式来访问的。 如果你使用
Python 可调用对象来执行导入，并且你希望在类层级而不是在实例层级上定义它
，则你需要用 *note staticmethod(): 1da. 来装饰它。 例如:

     from importlib import import_module
     from logging.config import BaseConfigurator

     BaseConfigurator.importer = staticmethod(import_module)

如果你是在一个配置器的 `实例' 上设置导入可调用对象则你不需要用 *note
staticmethod(): 1da. 来装饰。


File: python.info,  Node: 配置文件格式,  Prev: 配置字典架构,  Up: logging config --- 日志记录配置

5.16.7.10 配置文件格式
......................

*note fileConfig(): 3b1. 所能理解的配置文件格式是基于 *note
configparser: 23. 功能的。 该文件必须包含 ‘[loggers]’, ‘[handlers]’ 和
‘[formatters]’ 等小节，它们通过名称来标识文件中定义的每种类型的实体。 对
于每个这样的实体，都有单独的小节来标识实体的配置方式。 因此，对于
‘[loggers]’ 小节中名为 ‘log01’ 的日志记录器，相应的配置详情保存在
‘[logger_log01]’ 小节中。 类似地，对于 ‘[handlers]’ 小节中名为 ‘hand01’
的处理程序，其配置将保存在名为 ‘[handler_hand01]’ 的小节中，而对于
‘[formatters]’ 小节中名为 ‘form01’ 的格式化器，其配置将在名为
‘[formatter_form01]’ 的小节中指定。 根日志记录器的配置必须在名为
‘[logger_root]’ 的小节中指定。

     注解: *note fileConfig(): 3b1. API 比 *note dictConfig(): b33. API
     更旧因而没有提供涵盖日志记录特定方面的功能。 例如，你无法配置 *note
     Filter: b7f. 对象，该对象使用 *note fileConfig(): 3b1. 提供超出简单
     整数级别的消息过滤功能。 如果你想要在你的日志记录配置中包含 *note
     Filter: b7f. 的实例，你将必须使用 *note dictConfig(): b33.。 请注意
     未来还将向 *note dictConfig(): b33. 添加对配置功能的强化，因此值得
     考虑在方便的时候转换到这个新 API。

在文件中这些小节的例子如下所示。

     [loggers]
     keys=root,log02,log03,log04,log05,log06,log07

     [handlers]
     keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09

     [formatters]
     keys=form01,form02,form03,form04,form05,form06,form07,form08,form09

根日志记录器必须指定一个级别和一个处理程序列表。 根日志小节的例子如下所
示。

     [logger_root]
     level=NOTSET
     handlers=hand01

‘level’ 条目可以为 ‘DEBUG, INFO, WARNING, ERROR, CRITICAL’ 或 ‘NOTSET’ 之
一。 其中 ‘NOTSET’ 仅适用于根日志记录器，表示将会记录所有消息。 级别值会
在 ‘logging’ 包命名空间的上下文中通过 *note eval(): b98. 来得出。

‘handlers’ 条目是以逗号分隔的处理程序名称列表，它必须出现于 ‘[handlers]’
小节并且在配置文件中有相应的小节。

对于根日志记录器以外的日志记录器，还需要某些附加信息。 下面的例子演示了
这些信息。

     [logger_parser]
     level=DEBUG
     handlers=hand01
     propagate=1
     qualname=compiler.parser

‘level’ 和 ‘handlers’ 条目的解释方式与根日志记录器的一致，不同之处在于如
果一个非根日志记录器的级别被指定为 ‘NOTSET’，则系统会咨询更高层级的日志
记录器来确定该日志记录器的有效级别。 ‘propagate’ 条目设为 1 表示消息必须
从此日志记录器传播到更高层级的处理程序，设为 0 表示消息 `不会' 传播到更
高层级的处理程序。 ‘qualname’ 条目是日志记录器的层级通道名称，也就是应用
程序获取日志记录器所用的名称。

指定处理程序配置的小节说明如下。

     [handler_hand01]
     class=StreamHandler
     level=NOTSET
     formatter=form01
     args=(sys.stdout,)

‘class’ 条目指明处理程序的类（由 ‘logging’ 包命名空间中的 *note eval():
b98. 来确定）。 ‘level’ 会以与日志记录器相同的方式来解读，‘NOTSET’ 会被
视为表示‘记录一切消息’。

‘formatter’ 条目指明此处理程序的格式化器的键名称。 如为空白，则会使用默
认的格式化器 (‘logging._defaultFormatter’)。 如果指定了名称，则它必须出
现于 ‘[formatters]’ 小节并且在配置文件中有相应的小节。

‘args’ 条目，当在 ‘logging’ 包命名空间的上下文中执行 *note eval(): b98.
时将是传给处理程序类构造器的参数列表。 请参阅相应处理程序的构造器说明或
者下面的示例，以了解典型的条目是如何构造的。 如果未提供，则默认为 ‘()’。

可选的 ‘kwargs’ 条目，当在 ‘logging’ 包命名空间的上下文中执行 *note
eval(): b98. 时将是传给处理程序的构造器的关键字参数字典。 如果未提供，则
默认为 ‘{}’。

     [handler_hand02]
     class=FileHandler
     level=DEBUG
     formatter=form02
     args=('python.log', 'w')

     [handler_hand03]
     class=handlers.SocketHandler
     level=INFO
     formatter=form03
     args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)

     [handler_hand04]
     class=handlers.DatagramHandler
     level=WARN
     formatter=form04
     args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)

     [handler_hand05]
     class=handlers.SysLogHandler
     level=ERROR
     formatter=form05
     args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)

     [handler_hand06]
     class=handlers.NTEventLogHandler
     level=CRITICAL
     formatter=form06
     args=('Python Application', '', 'Application')

     [handler_hand07]
     class=handlers.SMTPHandler
     level=WARN
     formatter=form07
     args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
     kwargs={'timeout': 10.0}

     [handler_hand08]
     class=handlers.MemoryHandler
     level=NOTSET
     formatter=form08
     target=
     args=(10, ERROR)

     [handler_hand09]
     class=handlers.HTTPHandler
     level=NOTSET
     formatter=form09
     args=('localhost:9022', '/log', 'GET')
     kwargs={'secure': True}

指定格式化器配置的小节说明如下。

     [formatter_form01]
     format=F1 %(asctime)s %(levelname)s %(message)s
     datefmt=
     class=logging.Formatter

‘format’ 是整个格式字符串，而 ‘datefmt’ 条目则是兼容 ‘strftime()’ 的日期
/时间格式字符串。 如果为空，此包将替换任何接近于日期格式字符串
‘'%Y-%m-%d %H:%M:%S'’ 的内容。 此格式还指定了毫秒，并使用逗号分隔符将其
附加到结果当中。 此格式的时间示例如 ‘2003-01-23 00:29:50,411’。

‘class’ 条目是可选的。 它指明格式化器类的名称（形式为带点号的模块名加类
名。） 此选项适用于实例化 *note Formatter: 2095. 的子类。 *note
Formatter: 2095. 的子类可通过扩展或收缩格式来显示异常回溯信息。

     注解: 由于如上所述使用了 *note eval(): b98.，因此使用 *note
     listen(): 87b. 通过套接字来发送和接收配置会导致潜在的安全风险。 此
     风险仅限于相互间没有信任的多个用户在同一台机器上运行代码的情况；请
     参阅 *note listen(): 87b. 了解更多信息。

参见
....

模块 *note logging: ab.

     日志记录模块的 API 参考。

*note logging.handlers: ad. 模块

     日志记录模块附带的有用处理器。


File: python.info,  Node: logging handlers --- 日志处理,  Next: getpass --- 便携式密码输入工具,  Prev: logging config --- 日志记录配置,  Up: 通用操作系统服务

5.16.8 ‘logging.handlers’ — 日志处理
------------------------------------

`源代码:' Lib/logging/handlers.py(1)

Important
.........

此页面仅包含参考信息。有关教程，请参阅

   * *note 基础教程: b7a.

   * *note 进阶教程: b7b.

   * *note 日志操作手册: b7c.

__________________________________________________________________

这个包提供了以下有用的处理程序。 请注意有三个处理程序类 (*note
StreamHandler: b7d, *note FileHandler: 20fa. 和 *note NullHandler: c24.)
实际上是在 *note logging: ab. 模块本身定义的，但其文档与其他处理程序一同
记录在此。

* Menu:

* StreamHandler::
* FileHandler::
* NullHandler::
* WatchedFileHandler::
* BaseRotatingHandler::
* RotatingFileHandler::
* TimedRotatingFileHandler::
* SocketHandler::
* DatagramHandler::
* SysLogHandler::
* NTEventLogHandler::
* SMTPHandler::
* MemoryHandler::
* HTTPHandler::
* QueueHandler::
* QueueListener::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/logging/handlers.py


File: python.info,  Node: StreamHandler,  Next: FileHandler,  Up: logging handlers --- 日志处理

5.16.8.1 StreamHandler
......................

*note StreamHandler: b7d. 类位于核心 *note logging: ab. 包，它可将日志记
录输出发送到数据流例如 `sys.stdout', `sys.stderr' 或任何文件类对象（或者
更精确地说，任何支持 ‘write()’ 和 ‘flush()’ 方法的对象）。

 -- 类: logging.StreamHandler (stream=None)

     返回一个新的 *note StreamHandler: b7d. 类。 如果指定了 `stream'，则
     实例将用它作为日志记录输出；在其他情况下将使用 `sys.stderr'。

      -- 方法: emit (record)

          If a formatter is specified, it is used to format the record.
          The record is then written to the stream with a terminator.
          If exception information is present, it is formatted using
          *note traceback.print_exception(): 20bf. and appended to the
          stream.

      -- 方法: flush ()

          通过调用流的 *note flush(): 20fe. 方法来刷新它。 请注意
          ‘close()’ 方法是继承自 *note Handler: 2096. 的所以没有输出，因
          此有时可能需要显式地调用 *note flush(): 20fe.。

      -- 方法: setStream (stream)

          将实例的流设为指定值，如果两者不一致的话。 旧的流会在设置新的
          流之前被刷新。


          参数: ‘stream’ – 处理程序应当使用的流。


          返回: 旧的流，如果流已被改变的话，如果未被改变则为 `None'。

     3.7 新版功能.

在 3.2 版更改: The ‘StreamHandler’ class now has a ‘terminator’
attribute, default value ‘'\n'’, which is used as the terminator when
writing a formatted record to a stream.  If you don’t want this newline
termination, you can set the handler instance’s ‘terminator’ attribute
to the empty string.  In earlier versions, the terminator was hardcoded
as ‘'\n'’.


File: python.info,  Node: FileHandler,  Next: NullHandler,  Prev: StreamHandler,  Up: logging handlers --- 日志处理

5.16.8.2 FileHandler
....................

*note FileHandler: 20fa. 类位于核心 *note logging: ab. 包，它可将日志记
录输出到磁盘文件中。 它从 *note StreamHandler: b7d. 继承了输出功能。

 -- 类: logging.FileHandler (filename, mode='a', encoding=None,
          delay=False)

     Returns a new instance of the *note FileHandler: 20fa. class.  The
     specified file is opened and used as the stream for logging.  If
     `mode' is not specified, ‘'a'’ is used.  If `encoding' is not
     ‘None’, it is used to open the file with that encoding.  If `delay'
     is true, then file opening is deferred until the first call to
     *note emit(): 2101.  By default, the file grows indefinitely.

     在 3.6 版更改: 除了字符串值，也接受 *note Path: 202. 对象作为
     `filename' 参数。

      -- 方法: close ()

          关闭文件。

      -- 方法: emit (record)

          将记录输出到文件。


File: python.info,  Node: NullHandler,  Next: WatchedFileHandler,  Prev: FileHandler,  Up: logging handlers --- 日志处理

5.16.8.3 NullHandler
....................

3.1 新版功能.

*note NullHandler: c24. 类位于核心 *note logging: ab. 包，它不执行任何格
式化或输出。 它实际上是一个供库开发者使用的‘无操作’处理程序。

 -- 类: logging.NullHandler

     返回一个 *note NullHandler: c24. 类的新实例。

      -- 方法: emit (record)

          此方法不执行任何操作。

      -- 方法: handle (record)

          此方法不执行任何操作。

      -- 方法: createLock ()

          此方法会对锁返回 ‘None’，因为没有下层 I/O 的访问需要被序列化。

请参阅 *note 配置库的日志记录: 2108. 了解有关如何使用 *note NullHandler:
c24. 的更多信息。


File: python.info,  Node: WatchedFileHandler,  Next: BaseRotatingHandler,  Prev: NullHandler,  Up: logging handlers --- 日志处理

5.16.8.4 WatchedFileHandler
...........................

*note WatchedFileHandler: 210b. 类位于 *note logging.handlers: ad. 模块
，这个 ‘FileHandler’ 用于监视它所写入日志记录的文件。 如果文件发生变化，
它会被关闭并使用文件名重新打开。

发生文件更改可能是由于使用了执行文件轮换的程序例如 `newsyslog' 和
`logrotate'。 这个处理程序在 Unix/Linux 下使用，它会监视文件来查看自上次
发出数据后是否有更改。 （如果文件的设备或 inode 发生变化就认为已被更改。
） 如果文件被更改，则会关闭旧文件流，并再打开文件以获得新文件流。

这个处理程序不适合在 Windows 下使用，因为在 Windows 下打开的日志文件无法
被移动或改名 —— 日志记录会使用排他的锁来打开文件 —— 因此这样的处理程序是
没有必要的。 此外，`ST_INO' 在 Windows 下不受支持；*note stat(): 1f2. 将
总是为该值返回零。

 -- 类: logging.handlers.WatchedFileHandler (filename, mode='a',
          encoding=None, delay=False)

     Returns a new instance of the *note WatchedFileHandler: 210b.
     class.  The specified file is opened and used as the stream for
     logging.  If `mode' is not specified, ‘'a'’ is used.  If `encoding'
     is not ‘None’, it is used to open the file with that encoding.  If
     `delay' is true, then file opening is deferred until the first call
     to *note emit(): 210c.  By default, the file grows indefinitely.

     在 3.6 版更改: 除了字符串值，也接受 *note Path: 202. 对象作为
     `filename' 参数。

      -- 方法: reopenIfNeeded ()

          检查文件是否已更改。 如果已更改，则会刷新并关闭现有流然后重新
          打开文件，这通常是将记录输出到文件的先导操作。

          3.6 新版功能.

      -- 方法: emit (record)

          将记录输出到文件，但如果文件已更改则会先调用 *note
          reopenIfNeeded(): 56b. 来重新打开它。


File: python.info,  Node: BaseRotatingHandler,  Next: RotatingFileHandler,  Prev: WatchedFileHandler,  Up: logging handlers --- 日志处理

5.16.8.5 BaseRotatingHandler
............................

*note BaseRotatingHandler: 210f. 类位于 *note logging.handlers: ad. 模块
中，它是轮换文件处理程序类 *note RotatingFileHandler: 20eb. 和 *note
TimedRotatingFileHandler: 877. 的基类。 你不需要实例化此类，但它具有你可
能需要重载的属性和方法。

 -- 类: logging.handlers.BaseRotatingHandler (filename, mode,
          encoding=None, delay=False)

     类的形参与 ‘FileHandler’ 的相同。 其属性有:

      -- 属性: namer

          如果此属性被设为一个可调用对象，则 *note rotation_filename():
          2111. 方法会委托给该可调用对象。 传给该可调用对象的形参与传给
          *note rotation_filename(): 2111. 的相同。

               注解: namer 函数会在轮换期间被多次调用，因此它应当尽可能
               的简单快速。 它还应当对给定的输入每次都返回相同的输出，否
               则轮换行为可能无法按预期工作。

          3.3 新版功能.

      -- 属性: rotator

          如果此属性被设为一个可调用对象，则 *note rotate(): 2113. 方法
          会委托给该可调用对象。 传给该可调用对象的形参与传给 *note
          rotate(): 2113. 的相同。

          3.3 新版功能.

      -- 方法: rotation_filename (default_name)

          当轮换时修改日志文件的文件名。

          提供该属性以便可以提供自定义文件名。

          默认实现会调用处理程序的 ’namer’ 属性，如果它是可调用对象的话
          ，并传给它默认的名称。 如果该属性不是可调用对象 (默认值为
          ‘None’)，则将名称原样返回。


          参数: ‘default_name’ – 日志文件的默认名称。

          3.3 新版功能.

      -- 方法: rotate (source, dest)

          当执行轮换时，轮换当前日志。

          默认实现会调用处理程序的 ’rotator’ 属性，如果它是可调用对象的
          话，并传给它 source 和 dest 参数。 如果该属性不是可调用对象 (默
          认值为 ‘None’)，则将源简单地重命名为目标。


          参数:

             * ‘source’ – 源文件名。 这通常为基本文件名，例如
               ’test.log’。

             * ‘dest’ – 目标文件名。 这通常是源被轮换后的名称，例如
               ’test.log.1’。

          3.3 新版功能.

该属性存在的理由是让你不必进行子类化 —— 你可以使用与 *note
RotatingFileHandler: 20eb. 和 *note TimedRotatingFileHandler: 877. 的实
例相同的可调用对象。 如果 namer 或 rotator 可调用对象引发了异常，将会按
照与 ‘emit()’ 调用期间的任何其他异常相同的方式来处理，例如通过处理程序的
‘handleError()’ 方法。

如果你需要对轮换进程执行更多的修改，你可以重载这些方法。

请参阅 *note 利用 rotator 和 namer 自定义日志轮换操作: 2114. 获取具体示
例。


File: python.info,  Node: RotatingFileHandler,  Next: TimedRotatingFileHandler,  Prev: BaseRotatingHandler,  Up: logging handlers --- 日志处理

5.16.8.6 RotatingFileHandler
............................

*note RotatingFileHandler: 20eb. 类位于 *note logging.handlers: ad. 模块
，它支持磁盘日志文件的轮换。

 -- 类: logging.handlers.RotatingFileHandler (filename, mode='a',
          maxBytes=0, backupCount=0, encoding=None, delay=False)

     Returns a new instance of the *note RotatingFileHandler: 20eb.
     class.  The specified file is opened and used as the stream for
     logging.  If `mode' is not specified, ‘'a'’ is used.  If `encoding'
     is not ‘None’, it is used to open the file with that encoding.  If
     `delay' is true, then file opening is deferred until the first call
     to *note emit(): 2117.  By default, the file grows indefinitely.

     你可以使用 `maxBytes' 和 `backupCount' 值来允许文件以预定的大小执行
     `rollover'。 当即将超出预定大小时，将关闭旧文件并打开一个新文件用于
     输出。 只要当前日志文件长度接近 `maxBytes' 就会发生轮换；但是如果
     `maxBytes' 或 `backupCount' 两者之一的值为零，就不会发生轮换，因此
     你通常要设置 `backupCount' 至少为 1，而 `maxBytes' 不能为零。 当
     `backupCount' 为非零值时，系统将通过为原文件名添加扩展名 ’.1’, ’.2’
     等来保存旧日志文件。 例如，当 `backupCount' 为 5 而基本文件名为
     ‘app.log’ 时，你将得到 ‘app.log’, ‘app.log.1’, ‘app.log.2’ 直至
     ‘app.log.5’。 当前被写入的文件总是 ‘app.log’。 当此文件写满时，它会
     被关闭并重户名为 ‘app.log.1’，而如果文件 ‘app.log.1’, ‘app.log.2’ 等
     存在，则它们会被分别重命名为 ‘app.log.2’, ‘app.log.3’ 等等。

     在 3.6 版更改: 除了字符串值，也接受 *note Path: 202. 对象作为
     `filename' 参数。

      -- 方法: doRollover ()

          执行上文所描述的轮换。

      -- 方法: emit (record)

          将记录输出到文件，以适应上文所描述的轮换。


File: python.info,  Node: TimedRotatingFileHandler,  Next: SocketHandler,  Prev: RotatingFileHandler,  Up: logging handlers --- 日志处理

5.16.8.7 TimedRotatingFileHandler
.................................

*note TimedRotatingFileHandler: 877. 类位于 *note logging.handlers: ad.
模块，它支持基于特定时间间隔的磁盘日志文件轮换。

 -- 类: logging.handlers.TimedRotatingFileHandler (filename, when='h',
          interval=1, backupCount=0, encoding=None, delay=False,
          utc=False, atTime=None)

     返回一个新的 *note TimedRotatingFileHandler: 877. 类实例。 指定的文
     件会被打开并用作日志记录的流。 对于轮换操作它还会设置文件名前缀。 轮
     换的发生是基于 `when' 和 `interval' 的积。

     你可以使用 `when' 来指定 `interval' 的类型。 可能的值列表如下。 请
     注意它们不是大小写敏感的。

     值                   间隔类型                         如果/如何使用 `atTime'
                                                           
     ------------------------------------------------------------------------------------
                                                           
     ‘'S'’                秒                               忽略
                                                           
                                                           
     ‘'M'’                分钟                             忽略
                                                           
                                                           
     ‘'H'’                小时                             忽略
                                                           
                                                           
     ‘'D'’                天                               忽略
                                                           
                                                           
     ‘'W0'-'W6'’          工作日(0=星期一)                 用于计算初始轮换时间
                                                           
                                                           
     ‘'midnight'’         如果未指定 `atTime' 则在午夜执   用于计算初始轮换时间
                          行轮换，否则将使用 `atTime'。    
                          

     当使用基于星期的轮换时，星期一为 ’W0’，星期二为 ’W1’，以此类推直至
     星期日为 ’W6’。 在这种情况下，传入的 `interval' 值不会被使用。

     系统将通过为文件名添加扩展名来保存旧日志文件。 扩展名是基于日期和时
     间的，根据轮换间隔的长短使用 strftime 格式 ‘%Y-%m-%d_%H-%M-%S’ 或是
     其中有变动的部分。

     当首次计算下次轮换的时间时（即当处理程序被创建时），现有日志文件的
     上次被修改时间或者当前时间会被用来计算下次轮换的发生时间。

     如果 `utc' 参数为真值，将使用 UTC 时间；否则会使用本地时间。

     如果 `backupCount' 不为零，则最多将保留 `backupCount' 个文件，而如
     果当轮换发生时创建了更多的文件，则最旧的文件会被删除。 删除逻辑使用
     间隔时间来确定要删除的文件，因此改变间隔时间可能导致旧文件被继续保
     留。

     如果 `delay' 为真值，则会将文件打开延迟到首次调用 *note emit():
     211b. 的时候。

     如果 `atTime' 不为 ‘None’，则它必须是一个 ‘datetime.time’ 的实例，
     该实例指定轮换在一天内的发生时间，用于轮换被设为“在午夜”或“在每星期
     的某一天”之类的情况。 请注意在这些情况下，`atTime' 值实际上会被用于
     计算 `初始' 轮换，而后续轮换将会通过正常的间隔时间计算来得出。

          注解: 初始轮换时间的计算是在处理程序被初始化时执行的。 后续轮
          换时间的计算则仅在轮换发生时执行，而只有当提交输出时轮换才会发
          生。 如果不记住这一点，你就可能会感到困惑。 例如，如果设置时间
          间隔为“每分钟”，那并不意味着你总会看到（文件名中）带有间隔一分
          钟时间的日志文件；如果在应用程序执行期间，日志记录输出的生成频
          率高于每分钟一次，`那么' 你可以预期看到间隔一分钟时间的日志文
          件。 另一方面，如果（假设）日志记录消息每五分钟才输出一次，那
          么文件时间将会存在对应于没有输出（因而没有轮换）的缺失。

     在 3.4 版更改: 添加了 `atTime' 形参。

     在 3.6 版更改: 除了字符串值，也接受 *note Path: 202. 对象作为
     `filename' 参数。

      -- 方法: doRollover ()

          执行上文所描述的轮换。

      -- 方法: emit (record)

          将记录输出到文件，以适应上文所描述的轮换。


File: python.info,  Node: SocketHandler,  Next: DatagramHandler,  Prev: TimedRotatingFileHandler,  Up: logging handlers --- 日志处理

5.16.8.8 SocketHandler
......................

*note SocketHandler: 878. 类位于 *note logging.handlers: ad. 模块，它会
将日志记录输出发送到网络套接字。 基类所使用的是 TCP 套接字。

 -- 类: logging.handlers.SocketHandler (host, port)

     返回一个 *note SocketHandler: 878. 类的新实例，该实例旨在与使用
     `host' 与 `port' 给定地址的远程主机进行通信。

     在 3.4 版更改: 如果 ‘port’ 指定为 ‘None’，会使用 ‘host’ 中的值来创
     建一个 Unix 域套接字 —— 在其他情况下，则会创建一个 TCP 套接字。

      -- 方法: close ()

          关闭套接字。

      -- 方法: emit ()

          对记录的属性字典执行封存并以二进制格式将其写入套接字。 如果套
          接字存在错误，则静默地丢弃数据包。 如果连接在此之前丢失，则重
          新建立连接。 要在接收端将记录解封并输出到 *note LogRecord:
          90e.，请使用 *note makeLogRecord(): 20c7. 函数。

      -- 方法: handleError ()

          处理在 *note emit(): 2120. 期间发生的错误。 最可能的原因是连接
          丢失。 关闭套接字以便我们能在下次事件时重新尝试。

      -- 方法: makeSocket ()

          这是一个工厂方法，它允许子类定义它们想要的套接字的准确类型。 默
          认实现会创建一个 TCP 套接字 (*note socket.SOCK_STREAM: c92.)。

      -- 方法: makePickle (record)

          将记录的属性字典封存为带有长度前缀的二进制格式，并将其返回以准
          备通过套接字进行传输。 此操作在细节上相当于:

               data = pickle.dumps(record_attr_dict, 1)
               datalen = struct.pack('>L', len(data))
               return datalen + data

          请注意封存操作不是绝对安全的。 如果你关心安全问题，你可能会想
          要重载此方法以实现更安全的机制。 例如，你可以使用 HMAC 对封存
          对象进行签名然后在接收端验证它们，或者你也可以在接收端禁用全局
          对象的解封操作。

      -- 方法: send (packet)

          将封存后的字节串 `packet' 发送到套接字。 所发送字节串的格式与
          *note makePickle(): 2123. 文档中的描述一致。

          此函数允许部分发送，这可能会在网络繁忙时发生。

      -- 方法: createSocket ()

          尝试创建一个套接字；失败时将使用指数化回退算法处理。 在失败初
          次发生时，处理程序将丢弃它正尝试发送的消息。 当后续消息交由同
          一实例处理时，它将不会尝试连接直到经过一段时间以后。 默认形参
          设置为初始延迟一秒，如果在延迟之后连接仍然无法建立，处理程序将
          每次把延迟翻倍直至达到 30 秒的最大值。

          此行为由下列处理程序属性控制:

             * ‘retryStart’ (初始延迟，默认为 1.0 秒)。

             * ‘retryFactor’ (倍数，默认为 2.0)。

             * ‘retryMax’ (最大延迟，默认为 30.0 秒)。

          这意味着如果远程监听器在处理程序被使用 `之后' 启动，你可能会丢
          失消息（因为处理程序在延迟结束之前甚至不会尝试连接，而在延迟期
          间静默地丢弃消息）。


File: python.info,  Node: DatagramHandler,  Next: SysLogHandler,  Prev: SocketHandler,  Up: logging handlers --- 日志处理

5.16.8.9 DatagramHandler
........................

*note DatagramHandler: 879. 类位于 *note logging.handlers: ad. 模块，它
继承自 *note SocketHandler: 878.，支持通过 UDP 套接字发送日志记录消息。

 -- 类: logging.handlers.DatagramHandler (host, port)

     返回一个 *note DatagramHandler: 879. 类的新实例，该实例旨在与使用
     `host' 与 `port' 给定地址的远程主机进行通信。

     在 3.4 版更改: 如果 ‘port’ 指定为 ‘None’，会使用 ‘host’ 中的值来创
     建一个 Unix 域套接字 —— 在其他情况下，则会创建一个 UDP 套接字。

      -- 方法: emit ()

          对记录的属性字典执行封存并以二进制格式将其写入套接字。 如果套
          接字存在错误，则静默地丢弃数据包。 要在接收端将记录解封并输出
          到 *note LogRecord: 90e.，请使用 *note makeLogRecord(): 20c7.
          函数。

      -- 方法: makeSocket ()

          *note SocketHandler: 878. 的工厂方法会在此被重载以创建一个 UDP
          套接字 (*note socket.SOCK_DGRAM: c91.)。

      -- 方法: send (s)

          将封存后的字节串发送到套接字。 所发送字节串的格式与 *note
          SocketHandler.makePickle(): 2123. 文档中的描述一致。


File: python.info,  Node: SysLogHandler,  Next: NTEventLogHandler,  Prev: DatagramHandler,  Up: logging handlers --- 日志处理

5.16.8.10 SysLogHandler
.......................

*note SysLogHandler: a26. 类位于 *note logging.handlers: ad. 模块，它支
持将日志记录消息发送到远程或本地 Unix syslog。

 -- 类: logging.handlers.SysLogHandler (address=('localhost',
          SYSLOG_UDP_PORT), facility=LOG_USER,
          socktype=socket.SOCK_DGRAM)

     返回一个 *note SysLogHandler: a26. 类的新实例用来与通过 `address' 以
     ‘(host, port)’ 元组形式给出地址的远程 Unix 机器进行通讯。 如果未指
     定 `address'，则使用 ‘('localhost', 514)’。 该地址会被用于打开套接
     字。 提供 ‘(host, port)’ 元组的一种替代方式是提供字符串形式的地址，
     例如 ’/dev/log’。 在这种情况下，会使用 Unix 域套接字将消息发送到
     syslog。 如果未指定 `facility'，则使用 ‘LOG_USER’。 打开的套接字类
     型取决于 `socktype' 参数，该参数的默认值为 *note socket.SOCK_DGRAM:
     c91. 即打开一个 UDP 套接字。 要打开一个 TCP 套接字（用来配合较新的
     syslog 守护程序例如 rsyslog 使用），请指定值为 *note
     socket.SOCK_STREAM: c92.。

     请注意如果你的服务器不是在 UDP 端口 514 上进行侦听，则 *note
     SysLogHandler: a26. 可能无法正常工作。 在这种情况下，请检查你应当为
     域套接字所使用的地址 —— 它依赖于具体的系统。 例如，在 Linux 上通常
     为 ’/dev/log’ 而在 OS/X 上则为 ’/var/run/syslog’。 你需要检查你的系
     统平台并使用适当的地址（如果你的应用程序需要在多个平台上运行则可能
     需要在运行时进行这样的检查）。 在 Windows 上，你大概必须要使用 UDP
     选项。

     在 3.2 版更改: 添加了 `socktype'。

      -- 方法: close ()

          关闭连接远程主机的套接字。

      -- 方法: emit (record)

          记录会被格式化，然后发送到 syslog 服务器。 如果存在异常信息，
          则它 `不会' 被发送到服务器。

          在 3.2.1 版更改: (参见: bpo-12168(1)。) 在较早的版本中，发送至
          syslog 守护程序的消息总是以一个 NUL 字节结束，因为守护程序的早
          期版本期望接收一个以 NUL 结束的消息 —— 即使它不包含于对应的规
          范说明 ( RFC 5424(2))。 这些守护程序的较新版本不再期望接收 NUL
          字节，如果其存在则会将其去除，而最新的守护程序（更紧密地遵循
          RFC 5424）会将 NUL 字节作为消息的一部分传递出去。

          为了在面对所有这些不同守护程序行为时能够更方便地处理 syslog 消
          息，通过使用类层级属性 ‘append_nul’，添加 NUL 字节的操作已被作
          为可配置项。 该属性默认为 ‘True’ (保留现有行为) 但可在
          ‘SysLogHandler’ 实例上设为 ‘False’ 以便让实例 `不会' 添加 NUL
          结束符。

          在 3.3 版更改: (参见: bpo-12419(3)。) 在较早的版本中，没有
          "ident" 或 "tag" 前缀工具可以用来标识消息的来源。 现在则可以使
          用一个类层级属性来设置它，该属性默认为 ‘""’ 表示保留现有行为，
          但可在 ‘SysLogHandler’ 实例上重载以便让实例不会为所处理的每条
          消息添加标识。 请注意所提供的标识必须为文本而非字节串，并且它
          会被原封不动地添加到消息中。

      -- 方法: encodePriority (facility, priority)

          将功能和优先级编码为一个整数。 你可以传入字符串或者整数 —— 如
          果传入的是字符串，则会使用内部的映射字典将其转换为整数。

          符号 ‘LOG_’ 的值在 *note SysLogHandler: a26. 中定义并且是
          ‘sys/syslog.h’ 头文件中所定义值的镜像。

          `优先级'

          名称（字符串）                 符号值
                                         
          ---------------------------------------------------
                                         
          ‘alert’                        LOG_ALERT
                                         
                                         
          ‘crit’ 或 ‘critical’           LOG_CRIT
                                         
                                         
          ‘debug’                        LOG_DEBUG
                                         
                                         
          ‘emerg’ 或 ‘panic’             LOG_EMERG
                                         
                                         
          ‘err’ 或 ‘error’               LOG_ERR
                                         
                                         
          ‘info’                         LOG_INFO
                                         
                                         
          ‘notice’                       LOG_NOTICE
                                         
                                         
          ‘warn’ 或 ‘warning’            LOG_WARNING
                                         

          `设备'

          名称（字符串）      符号值
                              
          ----------------------------------------
                              
          ‘auth’              LOG_AUTH
                              
                              
          ‘authpriv’          LOG_AUTHPRIV
                              
                              
          ‘cron’              LOG_CRON
                              
                              
          ‘daemon’            LOG_DAEMON
                              
                              
          ‘ftp’               LOG_FTP
                              
                              
          ‘kern’              LOG_KERN
                              
                              
          ‘lpr’               LOG_LPR
                              
                              
          ‘mail’              LOG_MAIL
                              
                              
          ‘news’              LOG_NEWS
                              
                              
          ‘syslog’            LOG_SYSLOG
                              
                              
          ‘user’              LOG_USER
                              
                              
          ‘uucp’              LOG_UUCP
                              
                              
          ‘local0’            LOG_LOCAL0
                              
                              
          ‘local1’            LOG_LOCAL1
                              
                              
          ‘local2’            LOG_LOCAL2
                              
                              
          ‘local3’            LOG_LOCAL3
                              
                              
          ‘local4’            LOG_LOCAL4
                              
                              
          ‘local5’            LOG_LOCAL5
                              
                              
          ‘local6’            LOG_LOCAL6
                              
                              
          ‘local7’            LOG_LOCAL7
                              

      -- 方法: mapPriority (levelname)

          将日志记录级别名称映射到 syslog 优先级名称。 如果你使用自定义
          级别，或者如果默认算法不适合你的需要，你可能需要重载此方法。 默
          认算法将 ‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’ 和 ‘CRITICAL’ 映
          射到等价的 syslog 名称，并将所有其他级别名称映射到 ’warning’。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12168

   (2) https://tools.ietf.org/html/rfc5424.html

   (3) https://bugs.python.org/issue12419


File: python.info,  Node: NTEventLogHandler,  Next: SMTPHandler,  Prev: SysLogHandler,  Up: logging handlers --- 日志处理

5.16.8.11 NTEventLogHandler
...........................

*note NTEventLogHandler: 2133. 类位于 *note logging.handlers: ad. 模块，
它支持将日志记录消息发送到本地 Windows NT, Windows 2000 或 Windows XP 事
件日志。 在你使用它之前，你需要安装 Mark Hammond 的 Python Win32 扩展。

 -- 类: logging.handlers.NTEventLogHandler (appname, dllname=None,
          logtype='Application')

     返回一个 *note NTEventLogHandler: 2133. 类的新实例。 `appname' 用来
     定义出现在事件日志中的应用名称。 将使用此名称创建适当的注册表条目。
     `dllname' 应当给出要包含在日志中的消息定义的 .dll 或 .exe 的完整限
     定路径名称（如未指定则会使用 ‘'win32service.pyd'’ —— 此文件随 Win32
     扩展安装且包含一些基本的消息定义占位符。 请注意使用这些占位符将使你
     的事件日志变得很大，因为整个消息源都会被放入日志。 如果你希望有较小
     的日志，你必须自行传入包含你想要在事件日志中使用的消息定义的 .dll 或
     .exe 名称）。 `logtype' 为 ‘'Application'’, ‘'System'’ 或
     ‘'Security'’ 之一，且默认值为 ‘'Application'’。

      -- 方法: close ()

          这时，你就可以从注册表中移除作为事件日志条目来源的应用名称。 但
          是，如果你这样做，你将无法如你所预期的那样在事件日志查看器中看
          到这些事件 —— 它必须能访问注册表来获取 .dll 名称。 当前版本并
          不会这样做。

      -- 方法: emit (record)

          确定消息 ID，事件类别和事件类型，然后将消息记录到 NT 事件日志
          中。

      -- 方法: getEventCategory (record)

          返回记录的事件类别。 如果你希望指定你自己的类别就要重载此方法
          。 此版本将返回 0。

      -- 方法: getEventType (record)

          返回记录的事件类型。 如果你希望指定你自己的类型就要重载此方法
          。 此版本将使用处理程序的 typemap 属性来执行映射，该属性在
          *note __init__(): d66. 被设置为一个字典，其中包含 ‘DEBUG’,
          ‘INFO’, ‘WARNING’, ‘ERROR’ 和 ‘CRITICAL’ 的映射。 如果你使用你
          自己的级别，你将需要重载此方法或者在处理程序的 `typemap' 属性
          中放置一个合适的字典。

      -- 方法: getMessageID (record)

          返回记录的消息 ID。 如果你使用你自己的消息，你可以通过将 `msg'
          传给日志记录器作为 ID 而非格式字符串实现此功能。 然后，你可以
          在这里使用字典查找来获取消息 ID。 此版本将返回 1，是
          ‘win32service.pyd’ 中的基本消息 ID.


File: python.info,  Node: SMTPHandler,  Next: MemoryHandler,  Prev: NTEventLogHandler,  Up: logging handlers --- 日志处理

5.16.8.12 SMTPHandler
.....................

*note SMTPHandler: 213b. 类位于 *note logging.handlers: ad. 模块，它支持
将日志记录消息通过 SMTP 发送到一个电子邮件地址。

 -- 类: logging.handlers.SMTPHandler (mailhost, fromaddr, toaddrs,
          subject, credentials=None, secure=None, timeout=1.0)

     返回一个 *note SMTPHandler: 213b. 类的新实例。 该实例使用电子邮件的
     发件人、收件人地址和主题行进行初始化。 `toaddrs' 应当为字符串列表。
     要指定一个非标准 SMTP 端口，请使用 (host, port) 元组格式作为
     `mailhost' 参数。 如果你使用一个字符串，则会使用标准 SMTP 端口。 如
     果你的 SMTP 服务器要求验证，你可以指定一个 (username, password) 元
     组作为 `credentials' 参数。

     要指定使用安全协议 (TLS)，请传入一个元组作为 `secure' 参数。 这将仅
     在提供了验证凭据时才能被使用。 元组应当或是一个空元组，或是一个包含
     密钥文件名的单值元组，或是一个包含密钥文件和证书文件的 2 值元组。 （
     此元组会被传给 *note smtplib.SMTP.starttls(): a8c. 方法。）

     可以使用 `timeout' 参数为与 SMTP 服务器的通信指定超时限制。

     3.3 新版功能: 增加了 `timeout' 参数。

      -- 方法: emit (record)

          对记录执行格式化并将其发送到指定的地址。

      -- 方法: getSubject (record)

          如果你想要指定一个基于记录的主题行，请重载此方法。


File: python.info,  Node: MemoryHandler,  Next: HTTPHandler,  Prev: SMTPHandler,  Up: logging handlers --- 日志处理

5.16.8.13 MemoryHandler
.......................

*note MemoryHandler: 20f4. 类位于 *note logging.handlers: ad. 模块，它支
持在内存中缓冲日志记录，并定期将其刷新到 `target' 处理程序中。 刷新会在
缓冲区满的时候，或是在遇到特定或更高严重程度事件的时候发生。

*note MemoryHandler: 20f4. 是更通用的 *note BufferingHandler: 2140. 的子
类，后者属于抽象类。 它会在内存中缓冲日志记录。 当每条记录被添加到缓冲区
时，会通过调用 ‘shouldFlush()’ 来检查缓冲区是否应当刷新。 如果应当刷新，
则要使用 ‘flush()’ 来执行刷新。

 -- 类: logging.handlers.BufferingHandler (capacity)

     使用指定容量的缓冲区初始化处理程序。 这里，`capacity' 是指缓冲的日
     志记录数量。

      -- 方法: emit (record)

          将记录添加到缓冲区。 如果 *note shouldFlush(): 2142. 返回真值
          ，则会调用 *note flush(): 2143. 来处理缓冲区。

      -- 方法: flush ()

          你可以重载此方法来实现自定义的刷新行为。 此版本只是将缓冲区清
          空。

      -- 方法: shouldFlush (record)

          如果缓冲区容量已满则返回 ‘True’。 可以重载此方法以实现自定义的
          刷新策略。

 -- 类: logging.handlers.MemoryHandler (capacity, flushLevel=ERROR,
          target=None, flushOnClose=True)

     返回一个 *note MemoryHandler: 20f4. 类的新实例。 该实例使用
     `capacity' 指定的缓冲区大小（要缓冲的记录数量）来初始化。 如果
     `flushLevel' 未指定，则使用 ‘ERROR’。 如果未指定 `target'，则需要在
     此处理程序执行任何实际操作之前使用 *note setTarget(): 2144. 来设置
     目标。 如果 `flushOnClose' 指定为 ‘False’，则当处理程序被关闭时 `不
     会' 刷新缓冲区。 如果未指定或指定为 ‘True’，则当处理程序被关闭时将
     会发生之前的缓冲区刷新行为。

     在 3.6 版更改: 增加了 `flushOnClose' 形参。

      -- 方法: close ()

          调用 *note flush(): 2146.，设置目标为 ‘None’ 并清空缓冲区。

      -- 方法: flush ()

          对于 *note MemoryHandler: 20f4.，刷新是指将缓冲的记录发送到目
          标，如果存在目标的话。 当此行为发生时缓冲区也将被清空。 如果你
          想要不同的行为请重载此方法。

      -- 方法: setTarget (target)

          设置此处理程序的目标处理程序。

      -- 方法: shouldFlush (record)

          检测缓冲区是否已满或是有记录为 `flushLevel' 或更高级别。


File: python.info,  Node: HTTPHandler,  Next: QueueHandler,  Prev: MemoryHandler,  Up: logging handlers --- 日志处理

5.16.8.14 HTTPHandler
.....................

*note HTTPHandler: 71a. 类位于 *note logging.handlers: ad. 模块，它支持
使用 ‘GET’ 或 ‘POST’ 语义将日志记录消息发送到 Web 服务器。

 -- 类: logging.handlers.HTTPHandler (host, url, method='GET',
          secure=False, credentials=None, context=None)

     返回一个 *note HTTPHandler: 71a. 类的新实例。 `host' 可以为
     ‘host:port’ 的形式，如果你需要使用指定端口号的话。 如果没有指定
     `method'，则会使用 ‘GET’。 如果 `secure' 为真值，则将使用 HTTPS 连
     接。 `context' 形参可以设为一个 *note ssl.SSLContext: 3ec. 实例以配
     置用于 HTTPS 连接的 SSL 设置。 如果指定了 `credentials'，它应当为包
     含 userid 和 password 的二元组，该元组将被放入使用 Basic 验证的
     HTTP ’Authorization’ 标头中。 如果你指定了 credentials，你还应当指
     定 secure=True 这样你的 userid 和 password 就不会以纯文本形式在线路
     上传输。

     在 3.5 版更改: 增加了 `context' 形参。

      -- 方法: mapLogRecord (record)

          基于 ‘record’ 提供一个字典，它将被执行 URL 编码并发送至 Web 服
          务器。 默认实现仅返回 ‘record.__dict__’。 在只需将 *note
          LogRecord: 90e. 的某个子集发送至 Web 服务器，或者需要对发送至
          服务器的内容进行更多定制时可以重载此方法。

      -- 方法: emit (record)

          将记录以经 URL 编码的形式发送至 Web 服务器。 会使用 *note
          mapLogRecord(): 214a. 方法来将要发送的记录转换为字典。

          注解: 由于记录发送至 Web 服务器所需的预处理与通用的格式化操作
          不同，使用 *note setFormatter(): 20ac. 来指定一个 *note
          Formatter: 2095. 用于 *note HTTPHandler: 71a. 是没有效果的。 此
          处理程序不会调用 *note format(): 20b6.，而是调用 *note
          mapLogRecord(): 214a. 然后再调用 *note
          urllib.parse.urlencode(): 794. 来以适合发送至 Web 服务器的形式
          对字典进行编码。


File: python.info,  Node: QueueHandler,  Next: QueueListener,  Prev: HTTPHandler,  Up: logging handlers --- 日志处理

5.16.8.15 QueueHandler
......................

3.2 新版功能.

*note QueueHandler: 214e. 类位于 *note logging.handlers: ad. 模块，它支
持将日志记录消息发送到一个队列，例如在 *note queue: db. 或 *note
multiprocessing: b8. 模块中实现的队列。

配合 *note QueueListener: 71b. 类使用，*note QueueHandler: 214e. 可用来
使处理程序在与执行日志记录的线程不同的线程上完成工作。 这对 Web 应用程序
以及其他服务于客户端的线程需要尽可能快地响应的服务应用程序来说很重要，任
何潜在的慢速操作（例如通过 *note SMTPHandler: 213b. 发送邮件）都要在单独
的线程上完成。

 -- 类: logging.handlers.QueueHandler (queue)

     返回一个 *note QueueHandler: 214e. 类的新实例。 该实例使用队列来初
     始化以向其发送消息。 `queue' 可以为任何队列类对象；它由 *note
     enqueue(): 214f. 方法来使用，该方法需要知道如何向其发送消息。 队列
     `不要求' 具有任务跟踪 API，这意味着你可以为 `queue' 使用 *note
     SimpleQueue: 3ce. 实例。

      -- 方法: emit (record)

          将准备 LogRecord 的结果排入队列。 如果发生了异常（例如由于有界
          队列已满），则会调用 *note handleError(): 20b4. 方法来处理错误
          。 这可能导致记录被静默地丢弃 (如果 ‘logging.raiseExceptions’
          为 ‘False’) 或者消息被打印到 ‘sys.stderr’ (如果
          ‘logging.raiseExceptions’ 为 ‘True’)。

      -- 方法: prepare (record)

          准备用于队列的记录。 此方法返回的对象会被排入队列。

          基本实现会格式化记录以合并消息、参数以及可能存在的异常信息。 它
          还会从记录中原地移除无法封存的条目。

          如果你想要将记录转换为 dict 或 JSON 字符串，或者发送记录被修改
          后的副本而让初始记录保持原样，则你可能会想要重载此方法。

      -- 方法: enqueue (record)

          使用 ‘put_nowait()’ 将记录排入队列；如果你想要使用阻塞行为，或
          超时设置，或自定义的队列实现，则你可能会想要重载此方法。


File: python.info,  Node: QueueListener,  Prev: QueueHandler,  Up: logging handlers --- 日志处理

5.16.8.16 QueueListener
.......................

3.2 新版功能.

*note QueueListener: 71b. 类位于 *note logging.handlers: ad. 模块，它支
持从一个队列接收日志记录消息，例如在 *note queue: db. 或 *note
multiprocessing: b8. 模块中实现的队列。 消息是在内部线程中从队列接收并在
同一线程上传递到一个或多个处理程序进行处理的。 尽管 *note QueueListener:
71b. 本身并不是一个处理程序，但由于它要与 *note QueueHandler: 214e. 配合
工作，因此也在此处介绍。

配合 *note QueueHandler: 214e. 类使用，*note QueueListener: 71b. 可用来
使处理程序在与执行日志记录的线程不同的线程上完成工作。 这对 Web 应用程序
以及其他服务与客户端的线程需要尽可能快地响应的服务应用程序来说很重要，任
何潜在的慢速动作（例如通过 *note SMTPHandler: 213b. 发送邮件）都要在单独
的线程上完成。

 -- 类: logging.handlers.QueueListener (queue, *handlers,
          respect_handler_level=False)

     返回一个 *note QueueListener: 71b. 类的新实例。 该实例初始化时要传
     入一个队列以向其发送消息，还要传入一个处理程序列表用来处理放置在队
     列中的条目。 队列可以是任何队列类对象；它会被原样传给 *note
     dequeue(): 2154. 方法，该方法需要知道如何从其获取消息。 队列 `不要
     求' 具有任务跟踪 API（但如提供则会使用它），这意味着你可以为
     `queue' 使用 *note SimpleQueue: 3ce. 实例。

     如果 ‘respect_handler_level’ 为 ‘True’，则在决定是否将消息传递给处
     理程序之前会遵循处理程序的级别（与消息的级别进行比较）；在其他情况
     下，其行为与之前的 Python 版本一致 —— 总是将每条消息传递给每个处理
     程序。

     在 3.5 版更改: 增加了 ‘respect_handler_level’ 参数。

      -- 方法: dequeue (block)

          从队列移出一条记录并将其返回，可以选择阻塞。

          基本实现使用 ‘get()’。 如果你想要使用超时设置或自定义的队列实
          现，则你可能会想要重载此方法。

      -- 方法: prepare (record)

          准备一条要处理的记录。

          该实现只是返回传入的记录。 如果你想要对记录执行任何自定义的
          marshal 操作或在将其传给处理程序之前进行调整，则你可能会想要重
          载此方法。

      -- 方法: handle (record)

          处理一条记录。

          此方法简单地循环遍历处理程序，向它们提供要处理的记录。 实际传
          给处理程序的对象就是从 *note prepare(): 2155. 返回的对象。

      -- 方法: start ()

          启动监听器。

          此方法启动一个后台线程来监视 LogRecords 队列以进行处理。

      -- 方法: stop ()

          停止监听器。

          此方法要求线程终止，然后等待它完成终止操作。 请注意在你的应用
          程序退出之前如果你没有调用此方法，则可能会有一些记录在留在队列
          中，它们将不会被处理。

      -- 方法: enqueue_sentinel ()

          将一个标记写入队列以通知监听器退出。 此实现会使用
          ‘put_nowait()’。 如果你想要使得超时设置或自定义的队列实现，则
          你可能会想要重载此方法。

          3.3 新版功能.

参见
....

模块 *note logging: ab.

     日志记录模块的 API 参考。

*note logging.config: ac. 模块

     日志记录模块的配置 API 。


File: python.info,  Node: getpass --- 便携式密码输入工具,  Next: curses --- 终端字符单元显示的处理,  Prev: logging handlers --- 日志处理,  Up: 通用操作系统服务

5.16.9 ‘getpass’ — 便携式密码输入工具
-------------------------------------

`源代码:' Lib/getpass.py(1)

__________________________________________________________________

*note getpass: 88. 模块提供了两个函数：

 -- 函数: getpass.getpass (prompt='Password: ', stream=None)

     提示用户输入一个密码且不会回显。 用户会看到字符串 `prompt' 作为提示
     ，其默认值为 ‘'Password: '’。 在 Unix 上，如有必要提示会使用替换错
     误句柄写入到文件类对象 `stream'。 `stream' 默认指向控制终端
     (‘/dev/tty’)，如果不可用则指向 ‘sys.stderr’ (此参数在 Windows 上会
     被忽略)。

     如果回显自由输入不可用则 getpass() 将回退为打印一条警告消息到
     `stream' 并且从 ‘sys.stdin’ 读取同时发出 *note GetPassWarning:
     215d.。

          注解: 如果你从 IDLE 内部调用 getpass，输入可能是在你启动 IDLE
          的终端中而非在 IDLE 窗口本身中完成。

 -- 例外: getpass.GetPassWarning

     一个当密码输入可能被回显时发出的 *note UserWarning: 172b. 子类。

 -- 函数: getpass.getuser ()

     返回用户的“登录名称”。

     此函数会按顺序检查环境变量 ‘LOGNAME’, ‘USER’, ‘LNAME’ 和
     ‘USERNAME’，并返回其中第一个被设置为非空字符串的值。 如果均未设置，
     则在支持 *note pwd: d7. 模块的系统上将返回来自密码数据库的登录名，
     否则将引发一个异常。

     通常情况下，此函数应优先于 *note os.getlogin(): 1efe. 使用。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/getpass.py


File: python.info,  Node: curses --- 终端字符单元显示的处理,  Next: curses textpad --- 用于 curses 程序的文本输入控件,  Prev: getpass --- 便携式密码输入工具,  Up: 通用操作系统服务

5.16.10 ‘curses’ — 终端字符单元显示的处理
-----------------------------------------

__________________________________________________________________

*note curses: 2c. 模块提供了 curses 库的接口，这是可移植高级终端处理的事
实标准。

虽然 curses 在 Unix 环境中使用最为广泛，但也有适用于 Windows，DOS 以及其
他可能的系统的版本。此扩展模块旨在匹配 ncurses 的 API，这是一个部署在
Linux 和 Unix 的 BSD 变体上的开源 curses 库。

     注解: 每当文档提到 `字符' 时，它可以被指定为一个整数，一个单字符
     Unicode 字符串或者一个单字节的字节字符串。

     每当此文档提到 `字符串' 时，它可以被指定为一个 Unicode 字符串或者一
     个字节字符串。

     注解: 从 5.4 版本开始，ncurses 库使用 ‘nl_langinfo’ 函数来决定如何
     解释非 ASCII 数据。这意味着你需要在程序中调用 *note
     locale.setlocale(): 2019. 函数，并使用一种系统中可用的编码方法来编
     码 Unicode 字符串。这个例子使用了系统默认的编码:

          import locale
          locale.setlocale(locale.LC_ALL, '')
          code = locale.getpreferredencoding()

     然后使用 `code' 作为 *note str.encode(): c3f. 调用的编码。

参见
....

模块 *note curses.ascii: 2d.

     在 ASCII 字符上工作的工具，无论你的区域设置是什么。

模块 *note curses.panel: 2e.

     为 curses 窗口添加深度的面板栈扩展。

模块 *note curses.textpad: 2f.

     用于使 curses 支持 ‘Emacs’ 式绑定的可编辑文本部件。

*note 用 Python 进行 Curses 编程: 2160.

     关于配合 Python 使用 curses 的教学材料，由 Andrew Kuchling 和 Eric
     Raymond 撰写。

Python 源码发布包的 Tools/demo/(1) 目录包含了一些使用此模块所提供的
curses 绑定的示例程序。

* Menu:

* 函数: 函数<3>.
* Window 对象::
* 常量: 常量<6>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Tools/demo/


File: python.info,  Node: 函数<3>,  Next: Window 对象,  Up: curses --- 终端字符单元显示的处理

5.16.10.1 函数
..............

*note curses: 2c. 模块定义了以下异常：

 -- 例外: curses.error

     当 curses 库中函数返回一个错误时引发的异常。

     注解: 只要一个函数或方法的 `x' 或 `y' 参数是可选项，它们会默认为当
     前光标位置。 而当 `attr' 是可选项时，它会默认为 ‘A_NORMAL’。

*note curses: 2c. 模块定义了以下函数：

 -- 函数: curses.baudrate ()

     以每秒比特数为单位返回终端输出速度。 在软件终端模拟器上它将具有一个
     固定的最高值。 此函数出于历史原因被包括；在以前，它被用于写输出循环
     以提供时间延迟，并偶尔根据线路速度来改变接口。

 -- 函数: curses.beep ()

     发出短促的提醒声音。

 -- 函数: curses.can_change_color ()

     根据程序员能否改变终端显示的颜色返回 ‘True’ 或 ‘False’。

 -- 函数: curses.cbreak ()

     进入 cbreak 模式。 在 cbreak 模式（有时也称为“稀有”模式）通常的 tty
     行缓冲会被关闭并且字符可以被一个一个地读取。 但是，与原始模式不同，
     特殊字符（中断、退出、挂起和流程控制）会在 tty 驱动和调用程序上保留
     其效果。 首先调用 *note raw(): 2168. 然后调用 *note cbreak(): 2167.
     会将终端置于 cbreak 模式。

 -- 函数: curses.color_content (color_number)

     返回颜色值 `color_number' 中红、绿和蓝（RGB）分量的强度，此强度值必
     须介于 ‘0’ 和 ‘COLORS - 1’ 之间。 返回一个 3 元组，其中包含给定颜色
     的 R,G,B 值，它们必须介于 ‘0’ (无分量) 和 ‘1000’ (最大分量) 之间。

 -- 函数: curses.color_pair (pair_number)

     返回用于以指定颜色对显示文本的属性值。 仅支持前 256 个颜色对。 该属
     性值可与 ‘A_STANDOUT’, ‘A_REVERSE’ 以及其他 ‘A_*’ 属性组合使用。
     *note pair_number(): 216b. 是此函数的对应操作。

 -- 函数: curses.curs_set (visibility)

     设置光标状态。 `visibility' 可设为 ‘0’, ‘1’ 或 ‘2’ 表示不可见、正常
     与高度可见。 如果终端支持所请求的可见性，则返回之前的光标状态；否则
     会引发异常。 在许多终端上，“正常可见”模式为下划线光标而“高度可见”模
     式为方块形光标。

 -- 函数: curses.def_prog_mode ()

     将当前终端模式保存为 "program" 模式，即正在运行的程序使用 curses 时
     的模式。 （与其相对的是 "shell" 模式，即程序不使用 curses。） 对
     *note reset_prog_mode(): 216e. 的后续调用将恢复此模式。

 -- 函数: curses.def_shell_mode ()

     将当前终端模式保存为 "shell" 模式，即正在运行的程序不使用 curses 的
     模式。 （与其相对的是 "program" 模式，即程序使用 功能。） 对 *note
     reset_shell_mode(): 2170. 的后续调用将恢复此模式。

 -- 函数: curses.delay_output (ms)

     在输出中插入 `ms' 毫秒的暂停。

 -- 函数: curses.doupdate ()

     更新物理屏幕。 curses 库会保留两个数据结构，一个代表当前物理屏幕的
     内容以及一个虚拟屏幕代表需要的后续状态。 *note doupdate(): 2172. 整
     体更新物理屏幕以匹配虚拟屏幕。

     虚拟屏幕可以通过在写入操作例如在一个窗口上执行 *note addstr():
     2173. 之后调用 *note noutrefresh(): 2174. 来刷新。 普通的 *note
     refresh(): 2175. 调用只是简单的 ‘noutrefresh()’ 加 ‘doupdate()’；如
     果你需要更新多个窗口，你可以通过在所有窗口上发出 ‘noutrefresh()’ 调
     用再加单次 ‘doupdate()’ 来提升性能并可减少屏幕闪烁。

 -- 函数: curses.echo ()

     进入 echo 模式。 在 echo 模式下，输入的每个字符都会在输入后回显到屏
     幕上。

 -- 函数: curses.endwin ()

     撤销库的初始化，使终端返回正常状态。

 -- 函数: curses.erasechar ()

     将用户的当前擦除字符以单字节字节串对象的形式返回。 在 Unix 操作系统
     下这是 curses 程序用来控制 tty 的属性，而不是由 curses 库本身来设置
     的。

 -- 函数: curses.filter ()

     如果要使用 *note filter(): 2179. 例程，它必须在调用 *note
     initscr(): 217a. 之前被调用。 其效果是在这些调用期间， ‘LINES’ 会被
     设为 ‘1’；‘clear’, ‘cup’, ‘cud’, ‘cud1’, ‘cuu1’, ‘cuu’, ‘vpa’ 等功
     能会被禁用；而 ‘home’ 字符串会被设为 ‘cr’ 的值。 其影响是光标会被限
     制在当前行内，屏幕刷新也是如此。 这可被用于启用单字符模式的行编辑而
     不触及屏幕的其余部分。

 -- 函数: curses.flash ()

     闪烁屏幕。 也就是将其改为反显并在很短的时间内将其改回原状。 有些人
     更喜欢这样的‘视觉响铃’而非 *note beep(): 2165. 所产生的听觉提醒信号
     。

 -- 函数: curses.flushinp ()

     刷新所有输入缓冲区。 这会丢弃任何已被用户输入但尚未被程序处理的预输
     入内容。

 -- 函数: curses.getmouse ()

     在 *note getch(): 217e. 返回 ‘KEY_MOUSE’ 以发出鼠标事件信号之后，应
     当调用此方法来获取加入队列的鼠标事件，事件以一个 5 元组 ‘(id, x, y,
     z, bstate)’ 来表示。 `id' 为用于区分多个设置的 ID 值， `x', `y',
     `z' 为事件的坐标。 (`z' 目前未被使用。) `bstate' 为一个整数值，其各
     比特位将设置用于表示事件类型，并将是下列常量中一个或多个按位 OR 的
     结果，其中 `n' 是以 1 至 4 表示的键号: ‘BUTTONn_PRESSED’,
     ‘BUTTONn_RELEASED’, ‘BUTTONn_CLICKED’, ‘BUTTONn_DOUBLE_CLICKED’,
     ‘BUTTONn_TRIPLE_CLICKED’, ‘BUTTON_SHIFT’, ‘BUTTON_CTRL’,
     ‘BUTTON_ALT’。

 -- 函数: curses.getsyx ()

     将当前虚拟屏幕光标的坐标作为元组 ‘(y, x)’ 返回。 如果 *note
     leaveok: 2180. 当前为 ‘True’，则返回 ‘(-1, -1)’。

 -- 函数: curses.getwin (file)

     读取由之前的 ‘putwin()’ 调用存放在文件中的窗口相关数据。 该例程随后
     将使用该数据创建并初始化一个新窗口，并返回该新窗口对象。

 -- 函数: curses.has_colors ()

     如果终端能显示彩色则返回 ‘True’；否则返回 ‘False’。

 -- 函数: curses.has_ic ()

     如果终端具有插入和删除字符的功能则返回 ‘True’。 此函数仅是出于历史
     原因而被包括的，因为所有现代软件终端模拟器都具有这些功能。

 -- 函数: curses.has_il ()

     如果终端具有插入和删除字符功能，或者能够使用滚动区域来模拟这些功能
     则返回 ‘True’。 此函数仅是出于历史原因而被包括的，因为所有现代软件
     终端模拟器都具有这些功能。

 -- 函数: curses.has_key (ch)

     接受一个键值 `ch'，并在当前终端类型能识别出具有该值的键时返回
     ‘True’。

 -- 函数: curses.halfdelay (tenths)

     用于半延迟模式，与 cbreak 模式的类似之处是用户所键入的字符会立即对
     程序可用。 但是，在阻塞 `tenths' 个十分之一秒之后，如果还未输入任何
     内容则将引发异常。 `tenths' 值必须为 ‘1’ 和 ‘255’ 之间的数字。 使用
     *note nocbreak(): 2187. 可退出半延迟模式。

 -- 函数: curses.init_color (color_number, r, g, b)

     更改某个颜色的定义，接受要更改的颜色编号以及三个 RGB 值（表示红绿蓝
     三分量的强度）。 `color_number' 值必须为 ‘0’ 和 ‘COLORS - 1’ 之间的
     数字。 `r', `g', `b' 值必须为 ‘0’ 和 ‘1000’ 之间的数字。 当使用
     *note init_color(): 2188. 时，出现在屏幕上的对应颜色会立即按照新定
     义来更改。 此函数在大多数终端上都是无操作的；它仅会在 *note
     can_change_color(): 2166. 返回 ‘True’ 时生效。

 -- 函数: curses.init_pair (pair_number, fg, bg)

     更改某个颜色对的定义。 它接受三个参数：要更改的颜色对编号，前景色编
     号和背景色编号。 `pair_number' 值必须为 ‘1’ 和 ‘COLOR_PAIRS - 1’ 之
     间的数字（并且 ‘0’ 号颜色对固定为黑底白字而无法更改）。 `fg' 和
     `bg' 参数必须为 ‘0’ 和 ‘COLORS - 1’ 之间的数字，或者在调用 *note
     use_default_colors(): 218a. 之后则为 ‘-1’。 如果颜色对之前已被初始
     化，则屏幕会被刷新使得出现在屏幕上的该颜色会立即按照新定义来更改。

 -- 函数: curses.initscr ()

     初始化库。 返回代表整个屏幕的 *note 窗口: 218b. 对象。

          注解: 如果打开终端时发生错误，则下层的 curses 库可能会导致解释
          器退出。

 -- 函数: curses.is_term_resized (nlines, ncols)

     如果 *note resize_term(): 218d. 会修改窗口结构则返回 ‘True’，否则返
     回 ‘False’。

 -- 函数: curses.isendwin ()

     如果 *note endwin(): 2177. 已经被调用（即 curses 库已经被撤销初始化
     则返回 ‘True’。

 -- 函数: curses.keyname (k)

     将编号为 `k' 的键名称作为字节串对象返回。 生成可打印 ASCII 字符的键
     名称就是键所对应的字符。 Ctrl-键组合的键名称则是一个两字节的字节串
     对象，它由插入符 (‘b'^'’) 加对应的可打印 ASCII 字符组成。 Alt-键组
     合 (128–255) 的键名称则是由前缀 ‘b'M-'’ 加对应的可打印 ASCII 字符组
     成的字节串对象。

 -- 函数: curses.killchar ()

     将用户的当前行删除字符以单字节字节串对象的形式返回。 在 Unix 操作系
     统下这是 curses 程序用来控制 tty 的属性，而不是由 curses 库本身来设
     置的。

 -- 函数: curses.longname ()

     返回一个字节串对象，其中包含描述当前终端的 terminfo 长名称字段。 详
     细描述的最大长度为 128 个字符。 它仅在调用 *note initscr(): 217a. 之
     后才会被定义。

 -- 函数: curses.meta (flag)

     如果 `flag' 为 ‘True’，则允许输入 8 比特位的字符。 如果 `flag' 为
     ‘False’，则只允许 7 比特位的字符。

 -- 函数: curses.mouseinterval (interval)

     以毫秒为单位设置能够被识别为点击的按下和释放事件之间可以间隔的最长
     时间，并返回之前的间隔值。 默认值为 200 毫秒，即五分之一秒。

 -- 函数: curses.mousemask (mousemask)

     设置要报告的鼠标事件，并返回一个元组 ‘(availmask, oldmask)’。
     `availmask' 表明指定的鼠标事件中哪些可以被报告；当完全失败时将返回
     ‘0’。 `oldmask' 是给定窗口的鼠标事件之前的掩码值。 如果从未调用此函
     数，则不会报告任何鼠标事件。

 -- 函数: curses.napms (ms)

     休眠 `ms' 毫秒。

 -- 函数: curses.newpad (nlines, ncols)

     创建并返回一个指向具有给定行数和列数新的填充数据结构的指针。 将填充
     作为窗口对象返回。

     面板类似于窗口，区别在于它不受屏幕大小的限制，并且不必与屏幕的特定
     部分相关联。 面板可以在需要使用大窗口时使用，并且每次只需将窗口的一
     部分放在屏幕上。 面板不会发生自动刷新（例如由于滚动或输入回显）。 面
     板的 *note refresh(): 2175. 和 *note noutrefresh(): 2174. 方法需要
     6 个参数来指定面板要显示的部分以及要用于显示的屏幕位置。 这些参数是
     `pminrow', `pmincol', `sminrow', `smincol', `smaxrow', `smaxcol'；
     `p' 参数表示要显示的面板区域的左上角而 `s' 参数定义了要显示的面板区
     域在屏幕上的剪切框。

 -- 函数: curses.newwin (nlines, ncols)

 -- 函数: curses.newwin (nlines, ncols, begin_y, begin_x)

     返回一个新的 *note 窗口: 218b.，其左上角位于 ‘(begin_y, begin_x)’，
     并且其高度/宽度为 `nlines'/`ncols'。

     默认情况下，窗口将从指定位置扩展到屏幕的右下角。

 -- 函数: curses.nl ()

     进入换行模式。 此模式会在输入时将回车转换为换行符，并在输出时将换行
     符转换为回车加换行。 换行模式会在初始时启用。

 -- 函数: curses.nocbreak ()

     退出 cbreak 模式。 返回具有行缓冲的正常 "cooked" 模式。

 -- 函数: curses.noecho ()

     退出 echo 模式。 关闭输入字符的回显。

 -- 函数: curses.nonl ()

     退出 newline 模式。 停止在输入时将回车转换为换行，并停止在输出时从
     换行到换行/回车的底层转换（但这不会改变 ‘addch('\n')’ 的行为，此行
     为总是在虚拟屏幕上执行相当于回车加换行的操作）。 当停止转换时，
     curses 有时能使纵向移动加快一些；并且，它将能够在输入时检测回车键。

 -- 函数: curses.noqiflush ()

     当使用 ‘noqiflush()’ 例程时，与 ‘INTR’, ‘QUIT’ 和 ‘SUSP’ 字符相关联
     的输入和输出队列的正常刷新将不会被执行。 如果你希望在处理程序退出后
     还能继续输出，就像没有发生过中断一样，你可能会想要在信号处理程序中
     调用 ‘noqiflush()’。

 -- 函数: curses.noraw ()

     退出 raw 模式。 返回具有行缓冲的正常 "cooked" 模式。

 -- 函数: curses.pair_content (pair_number)

     返回包含对应于所请求颜色对的元组 ‘(fg, bg)’。 `pair_number' 的值必
     须在 ‘0’ 和 ‘COLOR_PAIRS - 1’ 之间。

 -- 函数: curses.pair_number (attr)

     返回通过属性值 `attr' 所设置的颜色对的编号。 *note color_pair():
     216a. 是此函数的对应操作。

 -- 函数: curses.putp (str)

     等价于 ‘tputs(str, 1, putchar)’；为当前终端发出指定 terminfo 功能的
     值。 请注意 *note putp(): 219e. 的输出总是前往标准输出。

 -- 函数: curses.qiflush ([flag])

     如果 `flag' 为 ‘False’，则效果与调用 *note noqiflush(): 219b. 相同
     。 如果 `flag' 为 ‘True’ 或未提供参数，则在读取这些控制字符时队列将
     被刷新。

 -- 函数: curses.raw ()

     进入 raw 模式。 在 raw 模式下，正常的行缓冲和对中断、退出、挂起和流
     程控制键的处理会被关闭；字符会被逐个地提交给 curses 输入函数。

 -- 函数: curses.reset_prog_mode ()

     将终端恢复到 "program" 模式，如之前由 *note def_prog_mode(): 216d.
     所保存的一样。

 -- 函数: curses.reset_shell_mode ()

     将终端恢复到 "shell" 模式，如之前由 *note def_shell_mode(): 216f. 所
     保存的一样。

 -- 函数: curses.resetty ()

     将终端模式恢复到最后一次调用 *note savetty(): 21a1. 时的状态。

 -- 函数: curses.resize_term (nlines, ncols)

     由 *note resizeterm(): 21a2. 用来执行大部分工作的后端函数；当调整窗
     口大小时，*note resize_term(): 218d. 会以空白填充扩展区域。 调用方
     应用程序应当以适当的数据填充这些区域。 ‘resize_term()’ 函数会尝试调
     整所有窗口的大小。 但是，由于面板的调用约定，在不与应用程序进行额外
     交互的情况下是无法调整其大小的。

 -- 函数: curses.resizeterm (nlines, ncols)

     将标准窗口和当前窗口的大小调整为指定的尺寸，并调整由 curses 库所使
     用的记录窗口尺寸的其他记录数据（特别是 SIGWINCH 处理程序）。

 -- 函数: curses.savetty ()

     将终端模式的当前状态保存在缓冲区中，可供 *note resetty(): 21a0. 使
     用。

 -- 函数: curses.setsyx (y, x)

     将虚拟屏幕光标设置到 `y', `x'。 如果 `y' 和 `x' 均为 ‘-1’，则 *note
     leaveok: 2180. 将设为 ‘True’。

 -- 函数: curses.setupterm (term=None, fd=-1)

     初始化终端。 `term' 为给出终端名称的字符串或为 ‘None’；如果省略或为
     ‘None’，则将使用 ‘TERM’ 环境变量的值。 `fd' 是任何初始化序列将被发
     送到的文件描述符；如未指定或为 ‘-1’，则将使用 ‘sys.stdout’ 的文件描
     述符。

 -- 函数: curses.start_color ()

     如果程序员想要使用颜色，则必须在任何其他颜色操作例程被调用之前调用
     它。 在 *note initscr(): 217a. 之后立即调用此例程是一个很好的做法。

     *note start_color(): 21a5. 会初始化八种基本颜色（黑、红、绿、黄、蓝
     、品、青和白）以及 *note curses: 2c. 模块中的两个全局变量 ‘COLORS’
     和 ‘COLOR_PAIRS’，其中包含终端可支持的颜色和颜色对的最大数量。 它还
     会将终端中的颜色恢复为终端刚启动时的值。

 -- 函数: curses.termattrs ()

     返回终端所支持的所有视频属性逻辑 OR 的值。 此信息适用于当 curses 程
     序需要对屏幕外观进行完全控制的情况。

 -- 函数: curses.termname ()

     将环境变量 ‘TERM’ 的值截短至 14 个字节，作为字节串对象返回。

 -- 函数: curses.tigetflag (capname)

     将与 terminfo 功能名称 `capname' 相对应的布尔功能值以整数形式返回。
     如果 `capname' 不是一个布尔功能则返回 ‘-1’，如果其被取消或不存在于
     终端描述中则返回 ‘0’。

 -- 函数: curses.tigetnum (capname)

     将与 terminfo 功能名称 `capname' 相对应的数字功能值以整数形式返回。
     如果 `capname' 不是一个数字功能则返回 ‘-2’，如果其被取消或不存在于
     终端描述中则返回 ‘-1’。

 -- 函数: curses.tigetstr (capname)

     将与 terminfo 功能名称 `capname' 相对应的字符串功能值以字节串对象形
     式返回。 如果 `capname' 不是一个 terminfo "字符串功能" 或者如果其被
     取消或不存在于终端描述中则返回 ‘None’。

 -- 函数: curses.tparm (str[, ...])

     使用提供的形参初始化字节串对象 `str'，其中 `str' 应当是从 terminfo
     数据库获取的参数化字符串。 例如 ‘tparm(tigetstr("cup"), 5, 3)’ 的结
     果可能为 ‘b'\033[6;4H'’，实际结果将取决于终端类型。

 -- 函数: curses.typeahead (fd)

     指定将被用于预输入检查的文件描述符 `fd'。 如果 `fd' 为 ‘-1’，则不执
     行预输入检查。

     curses 库会在更新屏幕时通过定期查找预输入来执行 "断行优化"。 如果找
     到了输入，并且输入是来自于 tty，则会将当前更新推迟至 refresh 或
     doupdate 再次被调用的时候，以便允许更快地响应预先输入的命令。 此函
     数允许为预输入检查指定其他的文件描述符。

 -- 函数: curses.unctrl (ch)

     返回一个字节串对象作为字符 `ch' 的可打印表示形式。 控制字符会表示为
     一个变换符加相应的字符，例如 ‘b'^C'’。 可打印字符则会保持原样。

 -- 函数: curses.ungetch (ch)

     推送 `ch' 以便让下一个 *note getch(): 217e. 返回该字符。

          注解: 在 ‘getch()’ 被调用之前只能推送一个 `ch'。

 -- 函数: curses.update_lines_cols ()

     更新 ‘LINES’ 和 ‘COLS’。 适用于检测屏幕大小的手动调整。

     3.5 新版功能.

 -- 函数: curses.unget_wch (ch)

     推送 `ch' 以便让下一个 *note get_wch(): 9e7. 返回该字符。

          注解: 在 ‘get_wch()’ 被调用之前只能推送一个 `ch'。

     3.3 新版功能.

 -- 函数: curses.ungetmouse (id, x, y, z, bstate)

     将 ‘KEY_MOUSE’ 事件推送到输入队列，将其与给定的状态数据进行关联。

 -- 函数: curses.use_env (flag)

     如果使用此函数，则应当在调用 *note initscr(): 217a. 或 newterm 之前
     调用它。 当 `flag' 为 ‘False’ 时，将会使用在 terminfo 数据库中指定
     的行和列的值，即使设置了环境变量 ‘LINES’ 和 ‘COLUMNS’ (默认使用)，
     或者如果 curses 是在窗口中运行（在此情况下如果未设置 ‘LINES’ 和
     ‘COLUMNS’ 则默认行为将是使用窗口大小）。

 -- 函数: curses.use_default_colors ()

     允许在支持此特性的终端上使用默认的颜色值。 使用此函数可在你的应用程
     序中支持透明效果。 默认颜色会被赋给颜色编号 ‘-1’。 举例来说，在调用
     此函数后，‘init_pair(x, curses.COLOR_RED, -1)’ 会将颜色对 `x' 初始
     化为红色前景和默认颜色背景。

 -- 函数: curses.wrapper (func, ...)

     初始化 curses 并调用另一个可调用对象 `func'，该对象应当为你的使用
     curses 的应用程序的其余部分。 如果应用程序引发了异常，此函数将在重
     新引发异常并生成回溯信息之前将终端恢复到正常状态。 随后可调用对象
     `func' 会被传入主窗口 ’stdscr’ 作为其第一个参数，再带上其他所有传给
     ‘wrapper()’ 的参数。 在调用 `func' 之前，‘wrapper()’ 会启用 cbreak
     模式，关闭回显，启用终端键盘，并在终端具有颜色支持的情况下初始化颜
     色。 在退出时（无论是正常退出还是异常退出）它会恢复 cooked 模式，打
     开回显，并禁用终端键盘。


File: python.info,  Node: Window 对象,  Next: 常量<6>,  Prev: 函数<3>,  Up: curses --- 终端字符单元显示的处理

5.16.10.2 Window 对象
.....................

Window 对象会由上面的 *note initscr(): 217a. 和 *note newwin(): 2197. 返
回，它具有以下方法和属性:

 -- 方法: window.addch (ch[, attr])

 -- 方法: window.addch (y, x, ch[, attr])

     将带有属性 `attr' 的字符 `ch' 绘制到 ‘(y, x)’，覆盖之前在该位置上绘
     制的任何字符。 默认情况下，字符的位置和属性均为窗口对象的当前设置。

          注解: 在窗口、子窗口或面板之外写入会引发 *note curses.error:
          2163.。 尝试在窗口、子窗口或面板的右下角写入将在字符被打印之后
          导致异常被引发。

 -- 方法: window.addnstr (str, n[, attr])

 -- 方法: window.addnstr (y, x, str, n[, attr])

     将带有属性 `attr' 的字符串 `str' 中的至多 `n' 个字符绘制到 ‘(y,
     x)’，覆盖之前在屏幕上的任何内容。

 -- 方法: window.addstr (str[, attr])

 -- 方法: window.addstr (y, x, str[, attr])

     将带有属性 `attr' 的字符串 `str' 绘制到 ‘(y, x)’，覆盖之前在屏幕上
     的任何内容。

          注解: 
             * 在窗口、子窗口或面板之外写入会引发 *note curses.error:
               2163.。 尝试在窗口、子窗口或面板的右下角写入将在字符串被
               打印之后导致异常被引发。

             * 此 Python 模块的后端 ncurses 中的一个缺陷(1) 会在调整窗口
               大小时导致段错误。 此缺陷已在 ncurses-6.1-20190511 中被修
               复。 如果你必须使用较早版本的 ncurses，则你只要在调用
               *note addstr(): 2173. 时不传入嵌入了换行符的 `str' 即可避
               免触发此错误。 请为每一行分别调用 *note addstr(): 2173.。

 -- 方法: window.attroff (attr)

     从应用于写入到当前窗口的 "background" 集中移除属性 `attr'。

 -- 方法: window.attron (attr)

     向应用于写入到当前窗口的 "background" 集中添加属性 `attr'。

 -- 方法: window.attrset (attr)

     将 "background" 属性集设为 `attr'。 该集合初始时为 ‘0’ (无属性)。

 -- 方法: window.bkgd (ch[, attr])

     将窗口 background 特征属性设为带有属性 `attr' 的字符 `ch'。 随后此
     修改将应用于放置到该窗口中的每个字符。

        * 窗口中每个字符的属性会被修改为新的 background 属性。

        * 不论之前的 background 字符出现在哪里，它都会被修改为新的
          background 字符。

 -- 方法: window.bkgdset (ch[, attr])

     设置窗口的背景。 窗口的背景由字符和属性的任意组合构成。 背景的属性
     部分会与写入窗口的所有非空白字符合并（即 OR 运算）。 背景和字符和属
     性部分均会与空白字符合并。 背景将成为字符的特征属性并在任何滚动与插
     入/删除行/字符操作中与字符一起移动。

 -- 方法: window.border ([ls[, rs[, ts[, bs[, tl[, tr[, bl[, br]]]]]]]])

     在窗口边缘绘制边框。每个参数指定用于边界特定部分的字符;请参阅下表了
     解更多详情。

          注解: 任何形参的值为 ‘0’ 都将导致该形参使用默认字符。 关键字形
          参 `不可' 被使用。 默认字符在下表中列出:

     参数            描述                      默认值
                                               
     ----------------------------------------------------------------------
                                               
     `ls'            左侧                      ‘ACS_VLINE’
                                               
                                               
     `rs'            右侧                      ‘ACS_VLINE’
                                               
                                               
     `ts'            顶部                      ‘ACS_HLINE’
                                               
                                               
     `bs'            底部                      ‘ACS_HLINE’
                                               
                                               
     `tl'            左上角                    ‘ACS_ULCORNER’
                                               
                                               
     `tr'            右上角                    ‘ACS_URCORNER’
                                               
                                               
     `bl'            左下角                    ‘ACS_LLCORNER’
                                               
                                               
     `br'            右下角                    ‘ACS_LRCORNER’
                                               

 -- 方法: window.box ([vertch, horch])

     类似于 *note border(): 21b9.，但 `ls' 和 `rs' 均为 `vertch' 而 `ts'
     和 `bs' 均为 `horch'。 此函数总是会使用默认的转角字符。

 -- 方法: window.chgat (attr)

 -- 方法: window.chgat (num, attr)

 -- 方法: window.chgat (y, x, attr)

 -- 方法: window.chgat (y, x, num, attr)

     在当前光标位置或是在所提供的位置 ‘(y, x)’ 设置 `num' 个字符的属性。
     如果 `num' 未给出或为 ‘-1’，则将属性设置到所有字符上直至行尾。 如果
     提供了位置 ‘(y, x)’ 则此函数会将光标移至该位置。 修改过的行将使用
     *note touchline(): 21bc. 方法处理以便下次窗口刷新时内容会重新显示。

 -- 方法: window.clear ()

     类似于 *note erase(): 21be.，但还会导致在下次调用 *note refresh():
     2175. 时整个窗口被重新绘制。

 -- 方法: window.clearok (flag)

     如果 `flag' 为 ‘True’，则在下次调用 *note refresh(): 2175. 时将完全
     清除窗口。

 -- 方法: window.clrtobot ()

     从光标位置开始擦除直至窗口末端：光标以下的所有行都会被删除，然后会
     执行 *note clrtoeol(): 21c1. 的等效操作。

 -- 方法: window.clrtoeol ()

     从光标位置开始擦除直至行尾。

 -- 方法: window.cursyncup ()

     更新窗口所有上级窗口的当前光标位置以反映窗口的当前光标位置。

 -- 方法: window.delch ([y, x])

     删除位于 ‘(y, x)’ 的任何字符。

 -- 方法: window.deleteln ()

     删除在光标之下的行。 所有后续的行都会上移一行。

 -- 方法: window.derwin (begin_y, begin_x)

 -- 方法: window.derwin (nlines, ncols, begin_y, begin_x)

     "derive window" 的缩写，*note derwin(): 21c5. 与调用 *note
     subwin(): 21c6. 等效，不同之处在于 `begin_y' 和 `begin_x' 是想对于
     窗口的初始位置，而不是相对于整个屏幕。 返回代表所派生窗口的窗口对象
     。

 -- 方法: window.echochar (ch[, attr])

     使用属性 `attr' 添加字符 `ch'，并立即在窗口上调用 *note refresh():
     2175.。

 -- 方法: window.enclose (y, x)

     检测给定的相对屏幕的字符-单元格坐标是否被给定的窗口所包围，返回
     ‘True’ 或 ‘False’。 它适用于确定是哪个屏幕窗口子集包围着某个鼠标事
     件的位置。

 -- 属性: window.encoding

     用于编码方法参数（Unicode 字符串和字符）的编码格式。 encoding 属性
     是在创建子窗口时从父窗口继承的，例如通过 *note window.subwin():
     21c6.。 默认情况下，会使用当前区域的编码格式 (参见 *note
     locale.getpreferredencoding(): 3ad.)。

     3.3 新版功能.

 -- 方法: window.erase ()

     清空窗口。

 -- 方法: window.getbegyx ()

     返回左上角坐标的元组 ‘(y, x)’。

 -- 方法: window.getbkgd ()

     返回给定窗口的当前背景字符/属性对。

 -- 方法: window.getch ([y, x])

     获取一个字符。 请注意所返回的整数 `不一定' 要在 ASCII 范围以内：功
     能键、小键盘键等等是由大于 255 的数字表示的。 在无延迟模式下，如果
     没有输入则返回 ‘-1’，在其他情况下都会等待直至有键被按下。

 -- 方法: window.get_wch ([y, x])

     获取一个宽字符。 对于大多数键都是返回一个字符，对于功能键、小键盘键
     和其他特殊键则是返回一个整数。 在无延迟模式下，如果没有输入则返回一
     个异常。

     3.3 新版功能.

 -- 方法: window.getkey ([y, x])

     获取一个字符，返回一个字符串而不是像 *note getch(): 217e. 那样返回
     一个整数。 功能键、小键盘键和其他特殊键则是返回一个包含键名的多字节
     字符串。 在无延迟模式下，如果没有输入则引发一个异常。

 -- 方法: window.getmaxyx ()

     返回窗口高度和宽度的元组 ‘(y, x)’。

 -- 方法: window.getparyx ()

     将此窗口相对于父窗口的起始坐标作为元组 ‘(y, x)’ 返回。 如果此窗口没
     有父窗口则返回 ‘(-1, -1)’。

 -- 方法: window.getstr ()

 -- 方法: window.getstr (n)

 -- 方法: window.getstr (y, x)

 -- 方法: window.getstr (y, x, n)

     从用户读取一个字节串对象，附带基本的行编辑功能。

 -- 方法: window.getyx ()

     返回当前光标相对于窗口左上角的位置的元组 ‘(y, x)’。

 -- 方法: window.hline (ch, n)

 -- 方法: window.hline (y, x, ch, n)

     显示一条起始于 ‘(y, x)’ 长度为 `n' 个字符 `ch' 的水平线。

 -- 方法: window.idcok (flag)

     如果 `flag' 为 ‘False’，curses 将不再考虑使用终端的硬件插入/删除字
     符功能；如果 `flag' 为 ‘True’，则会启用字符插入和删除。 当 curses 首
     次初始化时，默认会启用字符插入/删除。

 -- 方法: window.idlok (flag)

     如果 `flag' 为 ‘True’，*note curses: 2c. 将尝试使用硬件行编辑功能。
     否则，行插入/删除会被禁用。

 -- 方法: window.immedok (flag)

     如果 `flag' 为 ‘True’，窗口图像中的任何改变都会自动导致窗口被刷新；
     你不必再自己调用 *note refresh(): 2175.。 但是，这可能会由于重复调
     用 wrefresh 而显著降低性能。 此选项默认被禁用。

 -- 方法: window.inch ([y, x])

     返回窗口中给定位置上的字符。 下面的 8 个比特位是字符本身，上面的比
     特位则为属性。

 -- 方法: window.insch (ch[, attr])

 -- 方法: window.insch (y, x, ch[, attr])

     将带有属性 `attr' 的字符串 `ch' 绘制到 ‘(y, x)’，将该行从位置 `x' 开
     始右移一个字符。

 -- 方法: window.insdelln (nlines)

     在指定窗口的当前行上方插入 `nlines' 行。 下面的 `nlines' 行将丢失。
     对于 `nlines' 为负值的情况，则从光标下方的行开始删除 `nlines' 行，
     并将其余的行向上移动。 下面的 `nlines' 行会被清空。 当前光标位置将
     保持不变。

 -- 方法: window.insertln ()

     在光标下方插入一个空行。 所有后续的行都会下移一行。

 -- 方法: window.insnstr (str, n[, attr])

 -- 方法: window.insnstr (y, x, str, n[, attr])

     在光标下方的字符之前插入一个至多为 `n' 个字符的字符串（字符数量将与
     该行相匹配）。 如果 `n' 为零或负数，则插入整个字符串。 光标右边的所
     有字符将被右移，该行右端的字符将丢失。 光标位置将保持不变（在移到可
     能指定的 `y', `x' 之后）。

 -- 方法: window.insstr (str[, attr])

 -- 方法: window.insstr (y, x, str[, attr])

     在光标下方的字符之前插入一个字符串（字符数量将与该行相匹配）。 光标
     右边的所有字符将被右移，该行右端的字符将丢失。 光标位置将保持不变（
     在移到可能指定的 `y', `x' 之后）。

 -- 方法: window.instr ([n])

 -- 方法: window.instr (y, x[, n])

     返回从窗口的当前光标位置，或者指定的 `y', `x' 开始提取的字符所对应
     的字节串对象。 属性会从字符中去除。 如果指定了 `n'，*note instr():
     21da. 将返回长度至多为 `n' 个字符的字符串（不包括末尾的 NUL）。

 -- 方法: window.is_linetouched (line)

     如果指定的行自上次调用 *note refresh(): 2175. 后发生了改变则返回
     ‘True’；否则返回 ‘False’。 如果 `line' 对于给定的窗口不可用则会引发
     *note curses.error: 2163. 异常。

 -- 方法: window.is_wintouched ()

     如果指定的窗口自上次调用 *note refresh(): 2175. 后发生了改变则返回
     ‘True’；否则返回 ‘False’。

 -- 方法: window.keypad (flag)

     如果 `flag' 为 ‘True’，则某些键（小键盘键、功能键等）生成的转义序列
     将由 *note curses: 2c. 来解析。 如果 `flag' 为 ‘False’，转义序列将
     保持在输入流中的原样。

 -- 方法: window.leaveok (flag)

     如果 `flag' 为 ‘True’，则在更新时光标将停留在原地，而不是在“光标位
     置”。 这将可以减少光标的移动。 在可能的情况下光标将变为不可见。

     如果 `flag' 为 ‘False’，光标在更新后将总是位于“光标位置”。

 -- 方法: window.move (new_y, new_x)

     将光标移至 ‘(new_y, new_x)’。

 -- 方法: window.mvderwin (y, x)

     让窗口在其父窗口内移动。 窗口相对于屏幕的参数不会被更改。 此例程用
     于在屏幕的相同物理位置显示父窗口的不同部分。

 -- 方法: window.mvwin (new_y, new_x)

     移动窗口以使其左上角位于 ‘(new_y, new_x)’。

 -- 方法: window.nodelay (flag)

     如果 `flag' 为 ‘True’，则 *note getch(): 217e. 将为非阻塞的。

 -- 方法: window.notimeout (flag)

     如果 `flag' 为 ‘True’，则转义序列将不会发生超时。

     如果 `flag' 为 ‘False’，则在几毫秒之后，转义序列将不会被解析，并将
     保持在输入流中的原样。

 -- 方法: window.noutrefresh ()

     标记为刷新但保持等待。 此函数会更新代表预期窗口状态的数据结构，但并
     不强制更新物理屏幕。 要完成后者，请调用 *note doupdate(): 2172.。

 -- 方法: window.overlay (destwin[, sminrow, smincol, dminrow, dmincol,
          dmaxrow, dmaxcol])

     将窗口覆盖在 `destwin' 上方。 窗口的大小不必相同，只有重叠的区域会
     被复制。 此复制是非破坏性的，这意味着当前背景字符不会覆盖掉
     `destwin' 的旧内容。

     为了获得对被复制区域的细粒度控制，可以使用 *note overlay(): 21e3. 的
     第二种形式。 `sminrow' 和 `smincol' 是源窗口的左上角坐标，而其他变
     量则在目标窗口中标记出一个矩形。

 -- 方法: window.overwrite (destwin[, sminrow, smincol, dminrow,
          dmincol, dmaxrow, dmaxcol])

     将窗口覆盖在 `destwin' 上方。 窗口的大小不必相同，此时只有重叠的区
     域会被复制。 此复制是破坏性的，这意味着当前背景字符会覆盖掉
     `destwin' 的旧内容。

     为了获得对被复制区域的细粒度控制，可以使用 *note overwrite(): 21e4.
     的第二种形式。 `sminrow' 和 `smincol' 是源窗口的左上角坐标，而其他
     变量则在目标窗口中标记出一个矩形。

 -- 方法: window.putwin (file)

     将关联到窗口的所有数据写入到所提供的文件对象。 此信息可在以后使用
     *note getwin(): 2181. 函数来提取。

 -- 方法: window.redrawln (beg, num)

     指明从 `beg' 行开始的 `num' 个屏幕行已被破坏并且应当在下次 *note
     refresh(): 2175. 调用时完全重绘。

 -- 方法: window.redrawwin ()

     标记整个窗口，以使其在下次 *note refresh(): 2175. 调用时完全重绘。

 -- 方法: window.refresh ([pminrow, pmincol, sminrow, smincol, smaxrow,
          smaxcol])

     立即更新显示（将实际屏幕与之前的绘制/删除方法进行同步）。

     6 个可选参数仅在窗口为使用 *note newpad(): 2196. 创建的面板时可被指
     定。 需要额外的形参来指定所涉及到的是面板和屏幕的哪一部分。
     `pminrow' 和 `pmincol' 指定要在面板中显示的矩形的左上角。
     `sminrow', `smincol', `smaxrow' 和 `smaxcol' 指定要在屏幕中显示的矩
     形的边。 要在面板中显示的矩形的右下角是根据屏幕坐标计算出来的，由于
     矩形的大小必须相同。 两个矩形都必须完全包含在其各自的结构之内。 负
     的 `pminrow', `pmincol', `sminrow' 或 `smincol' 值会被视为将它们设
     为零值。

 -- 方法: window.resize (nlines, ncols)

     为 curses 窗口重新分配存储空间以将其尺寸调整为指定的值。 如果任一维
     度的尺寸大于当前值，则窗口的数据将以具有合并了当前背景渲染（由
     *note bkgdset(): 21b8. 设置）的空白来填充。

 -- 方法: window.scroll ([lines=1])

     将屏幕或滚动区域向上滚动 `lines' 行。

 -- 方法: window.scrollok (flag)

     控制当一个窗口的光标移出窗口或滚动区域边缘时会发生什么，这可能是在
     底端行执行换行操作，或者在最后一行输入最后一个字符导致的结果。 如果
     `flag' 为 ‘False’，光标会留在底端行。 如果 `flag' 为 ‘True’，窗口会
     向上滚动一行。 请注意为了在终端上获得实际的滚动效果，还需要调用
     *note idlok(): 21d2.。

 -- 方法: window.setscrreg (top, bottom)

     设置从 `top' 行至 `bottom' 行的滚动区域。 所有滚动操作将在此区域中
     进行。

 -- 方法: window.standend ()

     关闭 standout 属性。 在某些终端上此操作会有关闭所有属性的副作用。

 -- 方法: window.standout ()

     启用属性 `A_STANDOUT'。

 -- 方法: window.subpad (begin_y, begin_x)

 -- 方法: window.subpad (nlines, ncols, begin_y, begin_x)

     返回一个子窗口，其左上角位于 ‘(begin_y, begin_x)’，并且其宽度/高度
     为 `ncols'/`nlines'。

 -- 方法: window.subwin (begin_y, begin_x)

 -- 方法: window.subwin (nlines, ncols, begin_y, begin_x)

     返回一个子窗口，其左上角位于 ‘(begin_y, begin_x)’，并且其宽度/高度
     为 `ncols'/`nlines'。

     默认情况下，子窗口将从指定位置扩展到窗口的右下角。

 -- 方法: window.syncdown ()

     触碰已在上级窗口上被触碰的每个位置。 此例程由 *note refresh():
     2175. 调用，因此几乎从不需要手动调用。

 -- 方法: window.syncok (flag)

     如果 `flag' 为 ‘True’，则 *note syncup(): 21f1. 会在窗口发生改变的
     任何时候自动被调用。

 -- 方法: window.syncup ()

     触碰已在窗口中被改变的此窗口的各个上级窗口中的所有位置。

 -- 方法: window.timeout (delay)

     为窗口设置阻塞或非阻塞读取行为。 如果 `delay' 为负值，则会使用阻塞
     读取（这将无限期地等待输入）。 如果 `delay' 为零，则会使用非阻塞读
     取，并且当没有输入在等待时 *note getch(): 217e. 将返回 ‘-1’。 如果
     `delay' 为正值，则 *note getch(): 217e. 将阻塞 `delay' 毫秒，并且当
     此延时结束时仍无输入将返回 ‘-1’。

 -- 方法: window.touchline (start, count[, changed])

     假定从行 `start' 开始的 `count' 行已被更改。 如果提供了 `changed'，
     它将指明是将受影响的行标记为已更改 (`changed'‘=True’) 还是未更改
     (`changed'‘=False’)。

 -- 方法: window.touchwin ()

     假定整个窗口已被更改，其目的是用于绘制优化。

 -- 方法: window.untouchwin ()

     将自上次调用 *note refresh(): 2175. 以来窗口中的所有行标记为未改变
     。

 -- 方法: window.vline (ch, n)

 -- 方法: window.vline (y, x, ch, n)

     显示一条起始于 ‘(y, x)’ 长度为 `n' 个字符 `ch' 的垂直线。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35924


File: python.info,  Node: 常量<6>,  Prev: Window 对象,  Up: curses --- 终端字符单元显示的处理

5.16.10.3 常量
..............

*note curses: 2c. 模块定义了以下数据成员:

 -- 数据: curses.ERR

     一些返回整数的 curses 例程，例如 *note getch(): 217e.，在失败时将返
     回 *note ERR: 21f7.。

 -- 数据: curses.OK

     一些返回整数的 curses 例程，例如 *note napms(): 2195.，在成功时将返
     回 *note OK: 21f8.。

 -- 数据: curses.version

     一个代表当前模块版本的字节串对象。 也作 ‘__version__’。

 -- 数据: curses.ncurses_version

     一个具名元组，它包含构成 ncurses 库版本号的三个数字: `major',
     `minor' 和 `patch'。 三个值均为整数。 三个值也可通过名称来访问，因
     此 ‘curses.ncurses_version[0]’ 等价于
     ‘curses.ncurses_version.major’，依此类推。

     可用性：如果使用了 ncurses 库。

     3.8 新版功能.

有些常量可用于指定字符单元属性。 实际可用的常量取决于具体的系统。

属性                   含义
                       
-----------------------------------------------------------
                       
‘A_ALTCHARSET’         备用字符集模式
                       
                       
‘A_BLINK’              闪烁模式
                       
                       
‘A_BOLD’               粗体模式
                       
                       
‘A_DIM’                暗淡模式
                       
                       
‘A_INVIS’              不可见或空白模式
                       
                       
‘A_ITALIC’             斜体模式
                       
                       
‘A_NORMAL’             正常属性
                       
                       
‘A_PROTECT’            保护模式
                       
                       
‘A_REVERSE’            反转背景色和前景色
                       
                       
‘A_STANDOUT’           突出模式
                       
                       
‘A_UNDERLINE’          下划线模式
                       
                       
‘A_HORIZONTAL’         水平突出显示
                       
                       
‘A_LEFT’               左高亮
                       
                       
‘A_LOW’                底部高亮
                       
                       
‘A_RIGHT’              右高亮
                       
                       
‘A_TOP’                顶部高亮
                       
                       
‘A_VERTICAL’           垂直突出显示
                       
                       
‘A_CHARTEXT’           用于提取字符的位掩码
                       

3.7 新版功能: ‘A_ITALIC’ was added.

有几个常量可用于提取某些方法返回的相应属性。

位掩码                 含义
                       
-----------------------------------------------------------
                       
‘A_ATTRIBUTES’         用于提取属性的位掩码
                       
                       
‘A_CHARTEXT’           用于提取字符的位掩码
                       
                       
‘A_COLOR’              用于提取颜色对字段信息的位掩码
                       

键由名称以 ‘KEY_’ 开头的整数常量引用。确切的可用键取决于系统。

关键常数                键
                        
-------------------------------------------------------------------------
                        
‘KEY_MIN’               最小键值
                        
                        
‘KEY_BREAK’             中断键（不可靠）
                        
                        
‘KEY_DOWN’              向下箭头
                        
                        
‘KEY_UP’                向上箭头
                        
                        
‘KEY_LEFT’              向左箭头
                        
                        
‘KEY_RIGHT’             向右箭头
                        
                        
‘KEY_HOME’              Home 键 (上+左箭头)
                        
                        
‘KEY_BACKSPACE’         退格（不可靠）
                        
                        
‘KEY_F0’                功能键。 支持至多 64 个功能键。
                        
                        
‘KEY_Fn’                功能键 `n' 的值
                        
                        
‘KEY_DL’                删除行
                        
                        
‘KEY_IL’                插入行
                        
                        
‘KEY_DC’                删除字符
                        
                        
‘KEY_IC’                插入字符或进入插入模式
                        
                        
‘KEY_EIC’               退出插入字符模式
                        
                        
‘KEY_CLEAR’             清空屏幕
                        
                        
‘KEY_EOS’               清空至屏幕底部
                        
                        
‘KEY_EOL’               清空至行尾
                        
                        
‘KEY_SF’                向前滚动 1 行
                        
                        
‘KEY_SR’                向后滚动 1 行 (反转)
                        
                        
‘KEY_NPAGE’             下一页
                        
                        
‘KEY_PPAGE’             上一页
                        
                        
‘KEY_STAB’              设置制表符
                        
                        
‘KEY_CTAB’              清除制表制
                        
                        
‘KEY_CATAB’             清除所有制表符
                        
                        
‘KEY_ENTER’             回车或发送 (不可靠)
                        
                        
‘KEY_SRESET’            软件 (部分) 重置 (不可靠)
                        
                        
‘KEY_RESET’             重置或硬重置 (不可靠)
                        
                        
‘KEY_PRINT’             打印
                        
                        
‘KEY_LL’                Home 向下或到底 (左下)
                        
                        
‘KEY_A1’                键盘的左上角
                        
                        
‘KEY_A3’                键盘的右上角
                        
                        
‘KEY_B2’                键盘的中心
                        
                        
‘KEY_C1’                键盘左下方
                        
                        
‘KEY_C3’                键盘右下方
                        
                        
‘KEY_BTAB’              回退制表符
                        
                        
‘KEY_BEG’               Beg (开始)
                        
                        
‘KEY_CANCEL’            取消
                        
                        
‘KEY_CLOSE’             关闭
                        
                        
‘KEY_COMMAND’           Cmd (命令行)
                        
                        
‘KEY_COPY’              复制
                        
                        
‘KEY_CREATE’            创建
                        
                        
‘KEY_END’               End
                        
                        
‘KEY_EXIT’              退出
                        
                        
‘KEY_FIND’              查找
                        
                        
‘KEY_HELP’              帮助
                        
                        
‘KEY_MARK’              标记
                        
                        
‘KEY_MESSAGE’           消息
                        
                        
‘KEY_MOVE’              移动
                        
                        
‘KEY_NEXT’              下一个
                        
                        
‘KEY_OPEN’              打开
                        
                        
‘KEY_OPTIONS’           选项
                        
                        
‘KEY_PREVIOUS’          Prev (上一个)
                        
                        
‘KEY_REDO’              重做
                        
                        
‘KEY_REFERENCE’         Ref (引用)
                        
                        
‘KEY_REFRESH’           刷新
                        
                        
‘KEY_REPLACE’           替换
                        
                        
‘KEY_RESTART’           重启
                        
                        
‘KEY_RESUME’            恢复
                        
                        
‘KEY_SAVE’              保存
                        
                        
‘KEY_SBEG’              Shift 的 Beg (开始)
                        
                        
‘KEY_SCANCEL’           Shift 的 Cancel
                        
                        
‘KEY_SCOMMAND’          Shift 的 Command
                        
                        
‘KEY_SCOPY’             Shift + Copy
                        
                        
‘KEY_SCREATE’           Shift + Create
                        
                        
‘KEY_SDC’               Shift + 删除字符
                        
                        
‘KEY_SDL’               Shift + 删除行
                        
                        
‘KEY_SELECT’            选择
                        
                        
‘KEY_SEND’              Shift + End
                        
                        
‘KEY_SEOL’              Shift + 清空行
                        
                        
‘KEY_SEXIT’             Shift + Exit
                        
                        
‘KEY_SFIND’             Shift + 查找
                        
                        
‘KEY_SHELP’             Shift + 帮助
                        
                        
‘KEY_SHOME’             Shift + Home
                        
                        
‘KEY_SIC’               Shift + 输入
                        
                        
‘KEY_SLEFT’             Shift + 向左箭头
                        
                        
‘KEY_SMESSAGE’          Shift + 消息
                        
                        
‘KEY_SMOVE’             Shift + 移动
                        
                        
‘KEY_SNEXT’             Shift + 下一个
                        
                        
‘KEY_SOPTIONS’          Shift + 选项
                        
                        
‘KEY_SPREVIOUS’         Shift + 上一个
                        
                        
‘KEY_SPRINT’            Shift + 打印
                        
                        
‘KEY_SREDO’             Shift + 重做
                        
                        
‘KEY_SREPLACE’          Shift + 替换
                        
                        
‘KEY_SRIGHT’            Shift + 向右箭头
                        
                        
‘KEY_SRSUME’            Shift + 恢复
                        
                        
‘KEY_SSAVE’             Shift + 保存
                        
                        
‘KEY_SSUSPEND’          Shift + 挂起
                        
                        
‘KEY_SUNDO’             Shift + 撤销
                        
                        
‘KEY_SUSPEND’           挂起
                        
                        
‘KEY_UNDO’              撤销操作
                        
                        
‘KEY_MOUSE’             鼠标事件已发生
                        
                        
‘KEY_RESIZE’            终端大小改变事件
                        
                        
‘KEY_MAX’               最大键值
                        

在VT100及其软件仿真（例如X终端仿真器）上，通常至少有四个功能键（
‘KEY_F1’, ‘KEY_F2’, ‘KEY_F3’, ‘KEY_F4’ ）可用，并且箭头键以明显的方式映
射到 ‘KEY_UP’, ‘KEY_DOWN’, ‘KEY_LEFT’ 和 ‘KEY_RIGHT’ 。如果您的机器有一
个PC键盘，可以安全地使用箭头键和十二个功能键（旧的PC键盘可能只有十个功能
键）;此外，以下键盘映射是标准的：

键帽                   常数
                       
---------------------------------------
                       
‘Insert’               KEY_IC
                       
                       
‘Delete’               KEY_DC
                       
                       
‘Home’                 KEY_HOME
                       
                       
‘End’                  KEY_END
                       
                       
‘Page Up’              KEY_PPAGE
                       
                       
‘Page Down’            KEY_NPAGE
                       

下表列出了替代字符集中的字符。 这些字符继承自 VT100 终端，在 X 终端等软
件模拟器上通常均为可用。 当没有可用的图形时，curses 会回退为粗糙的可打印
ASCII 近似符号。

     注解: 只有在调用 *note initscr(): 217a. 之后才能使用它们

ACS代码                含义
                       
----------------------------------------------------------------------
                       
‘ACS_BBSS’             右上角的别名
                       
                       
‘ACS_BLOCK’            实心方块
                       
                       
‘ACS_BOARD’            正方形
                       
                       
‘ACS_BSBS’             水平线的别名
                       
                       
‘ACS_BSSB’             左上角的别名
                       
                       
‘ACS_BSSS’             顶部 T 型的别名
                       
                       
‘ACS_BTEE’             底部 T 型
                       
                       
‘ACS_BULLET’           正方形
                       
                       
‘ACS_CKBOARD’          棋盘（点刻）
                       
                       
‘ACS_DARROW’           向下箭头
                       
                       
‘ACS_DEGREE’           等级符
                       
                       
‘ACS_DIAMOND’          菱形
                       
                       
‘ACS_GEQUAL’           大于或等于
                       
                       
‘ACS_HLINE’            水平线
                       
                       
‘ACS_LANTERN’          灯形符号
                       
                       
‘ACS_LARROW’           向左箭头
                       
                       
‘ACS_LEQUAL’           小于或等于
                       
                       
‘ACS_LLCORNER’         左下角
                       
                       
‘ACS_LRCORNER’         右下角
                       
                       
‘ACS_LTEE’             左侧 T 型
                       
                       
‘ACS_NEQUAL’           不等号
                       
                       
‘ACS_PI’               字母π
                       
                       
‘ACS_PLMINUS’          正负号
                       
                       
‘ACS_PLUS’             加号
                       
                       
‘ACS_RARROW’           向右箭头
                       
                       
‘ACS_RTEE’             右侧 T 型
                       
                       
‘ACS_S1’               扫描线 1
                       
                       
‘ACS_S3’               扫描线3
                       
                       
‘ACS_S7’               扫描线7
                       
                       
‘ACS_S9’               扫描线 9
                       
                       
‘ACS_SBBS’             右下角的别名
                       
                       
‘ACS_SBSB’             垂直线的别名
                       
                       
‘ACS_SBSS’             右侧 T 型的别名
                       
                       
‘ACS_SSBB’             左下角的别名
                       
                       
‘ACS_SSBS’             底部 T 型的别名
                       
                       
‘ACS_SSSB’             左侧 T 型的别名
                       
                       
‘ACS_SSSS’             交叉或大加号的替代名称
                       
                       
‘ACS_STERLING’         英镑
                       
                       
‘ACS_TTEE’             顶部 T 型
                       
                       
‘ACS_UARROW’           向上箭头
                       
                       
‘ACS_ULCORNER’         左上角
                       
                       
‘ACS_URCORNER’         右上角
                       
                       
‘ACS_VLINE’            垂线
                       

下表列出了预定义的颜色：

常数                    颜色
                        
---------------------------------------------------------
                        
‘COLOR_BLACK’           黑色
                        
                        
‘COLOR_BLUE’            蓝色
                        
                        
‘COLOR_CYAN’            青色（浅绿蓝色）
                        
                        
‘COLOR_GREEN’           绿色
                        
                        
‘COLOR_MAGENTA’         洋红色（紫红色）
                        
                        
‘COLOR_RED’             红色
                        
                        
‘COLOR_WHITE’           白色
                        
                        
‘COLOR_YELLOW’          黄色
                        


File: python.info,  Node: curses textpad --- 用于 curses 程序的文本输入控件,  Next: curses ascii --- 用于 ASCII 字符的工具,  Prev: curses --- 终端字符单元显示的处理,  Up: 通用操作系统服务

5.16.11 ‘curses.textpad’ — 用于 curses 程序的文本输入控件
---------------------------------------------------------

*note curses.textpad: 2f. 模块提供了一个 *note Textbox: 21fb. 类，该类在
curses 窗口中处理基本的文本编辑，支持一组与 Emacs 类似的键绑定（因此这也
适用于 Netscape Navigator, BBedit 6.x, FrameMaker 和许多其他程序）。 该
模块还提供了一个绘制矩形的函数，适用于容纳文本框或其他目的。

*note curses.textpad: 2f. 模块定义了以下函数:

 -- 函数: curses.textpad.rectangle (win, uly, ulx, lry, lrx)

     绘制一个矩形。 第一个参数必须为窗口对象；其余参数均为相对于该窗口的
     坐标值。 第二和第三个参数为要绘制的矩形的左上角的 y 和 x 坐标值；第
     四和第五个参数为其右下角的 y 和 x 坐标值。 将会使用 VT100/IBM PC 形
     式的字符在可用的终端上（包括 xterm 和大多数其他软件终端模拟器）绘制
     矩形。 在其他情况下则将使用 ASCII 横杠、竖线和加号绘制。

* Menu:

* 文本框对象::


File: python.info,  Node: 文本框对象,  Up: curses textpad --- 用于 curses 程序的文本输入控件

5.16.11.1 文本框对象
....................

你可以通过如下方式实例化一个 *note Textbox: 21fb.:

 -- 类: curses.textpad.Textbox (win)

     返回一个文本框控件对象。 `win' 参数必须是一个 curses *note 窗口:
     218b. 对象，文本框将被包含在其中。 文本框的编辑光标在初始时位于包含
     窗口的左上角，坐标值为 ‘(0, 0)’。 实例的 *note stripspaces: 21ff. 旗
     标初始时为启用。

     *note Textbox: 21fb. 对象具有以下方法:

      -- 方法: edit ([validator])

          这是你通常将使用的入口点。 它接受编辑按键直到键入了一个终止按
          键。 如果提供了 `validator'，它必须是一个函数。 它将在每次按键
          时被调用并传入相应的按键作作为形参；命令发送将在结果上执行。 此
          方法会以字符串形式返回窗口内容；是否包括窗口中的空白将受到
          *note stripspaces: 21ff. 属性的影响。

      -- 方法: do_command (ch)

          处理单个按键命令。以下是支持的特殊按键：

          按键                   动作
                                 
          -----------------------------------------------------------------------
                                 
          ‘Control-A’            转到窗口的左边缘。
                                 
                                 
          ‘Control-B’            光标向左，如果可能，包含前一行。
                                 
                                 
          ‘Control-D’            删除光标下的字符。
                                 
                                 
          ‘Control-E’            前往右边缘（stripspaces 关闭时）或者行尾（
                                 stripspaces 启用时）。
                                 
                                 
          ‘Control-F’            向右移动光标，适当时换行到下一行。
                                 
                                 
          ‘Control-G’            终止，返回窗口内容。
                                 
                                 
          ‘Control-H’            向后删除字符。
                                 
                                 
          ‘Control-J’            如果窗口是1行则终止，否则插入换行符。
                                 
                                 
          ‘Control-K’            如果行为空，则删除它，否则清除到行尾。
                                 
                                 
          ‘Control-L’            刷新屏幕。
                                 
                                 
          ‘Control-N’            光标向下;向下移动一行。
                                 
                                 
          ‘Control-O’            在光标位置插入一个空行。
                                 
                                 
          ‘Control-P’            光标向上;向上移动一行。
                                 

          如果光标位于无法移动的边缘，则移动操作不执行任何操作。在可能的
          情况下，支持以下同义词：

          常数                         按键
                                       
          ----------------------------------------------------
                                       
          ‘KEY_LEFT’                   ‘Control-B’
                                       
                                       
          ‘KEY_RIGHT’                  ‘Control-F’
                                       
                                       
          ‘KEY_UP’                     ‘Control-P’
                                       
                                       
          ‘KEY_DOWN’                   ‘Control-N’
                                       
                                       
          ‘KEY_BACKSPACE’              ‘Control-h’
                                       

          所有其他按键将被视为插入给定字符并右移的命令（带有自动折行）。

      -- 方法: gather ()

          以字符串形式返回窗口内容；是否包括窗口中的空白将受到 *note
          stripspaces: 21ff. 成员的影响。

      -- 属性: stripspaces

          此属性是控制窗口中空白解读方式的旗标。 当启用时，每一行的末尾
          空白会被忽略；任何将光标定位至末尾空白的光标动作都将改为前往该
          行末尾，并且在收集窗口内容时将去除末尾空白。


File: python.info,  Node: curses ascii --- 用于 ASCII 字符的工具,  Next: curses panel --- curses 的 panel 栈扩展,  Prev: curses textpad --- 用于 curses 程序的文本输入控件,  Up: 通用操作系统服务

5.16.12 ‘curses.ascii’ — 用于 ASCII 字符的工具
----------------------------------------------

__________________________________________________________________

*note curses.ascii: 2d. 模块提供了一些 ASCII 字符的名称常量以及在各种
ASCII 字符类中执行成员检测的函数。 所提供的控制字符常量如下:

名称               含义
                   
----------------------------------------------------------------------
                   
‘NUL’

‘SOH’              标题开始，控制台中断
                   
                   
‘STX’              文本开始
                   
                   
‘ETX’              文本结束
                   
                   
‘EOT’              传输结束
                   
                   
‘ENQ’              查询，附带 ‘ACK’ 流量控制
                   
                   
‘ACK’              确认
                   
                   
‘BEL’              蜂鸣器
                   
                   
‘BS’               退格
                   
                   
‘TAB’              Tab
                   
                   
‘HT’               ‘TAB’ 的别名： "水平制表符”
                   
                   
‘LF’               换行
                   
                   
‘NL’               ‘LF’ 的别名： "新行"
                   
                   
‘VT’               垂直制表符
                   
                   
‘FF’               换页
                   
                   
‘CR’               回车
                   
                   
‘SO’               Shift-out，开始替换字符集
                   
                   
‘SI’               Shift-in，恢复默认字符集
                   
                   
‘DLE’              Data-link escape
                   
                   
‘DC1’              XON，用于流程控制
                   
                   
‘DC2’              Device control 2，阻塞模式流程控制
                   
                   
‘DC3’              XOFF，用于流程控制
                   
                   
‘DC4’              设备控制4
                   
                   
‘NAK’              否定确认
                   
                   
‘SYN’              同步空闲
                   
                   
‘ETB’              末端传输块
                   
                   
‘CAN’              取消
                   
                   
‘EM’               媒体结束
                   
                   
‘SUB’              替换
                   
                   
‘ESC’              退出
                   
                   
‘FS’               文件分隔符
                   
                   
‘GS’               组分隔符
                   
                   
‘RS’               记录分隔符，块模式终结器
                   
                   
‘US’               单位分隔符
                   
                   
‘SP’               空格
                   
                   
‘DEL’              删除
                   

请注意其中有许多在现今已经没有实际作用。 这些助记符是来源于数字计算机之
前的电传打印机规范。

此模块提供了下列函数，对应于标准 C 库中的函数:

 -- 函数: curses.ascii.isalnum (c)

     检测 ASCII 字母数字类字符；它等价于 ‘isalpha(c) 或 isdigit(c)’。

 -- 函数: curses.ascii.isalpha (c)

     检测 ASCII 字母类字符；它等价于 ‘isupper(c) or islower(c)’。

 -- 函数: curses.ascii.isascii (c)

     检测字符值是否在 7 位 ASCII 集范围内。

 -- 函数: curses.ascii.isblank (c)

     检测 ASCII 空白字符；包括空格或水平制表符。

 -- 函数: curses.ascii.iscntrl (c)

     检测 ASCII 控制字符（在 0x00 到 0x1f 或 0x7f 范围内）。

 -- 函数: curses.ascii.isdigit (c)

     检测 ASCII 十进制数码，即 ‘'0'’ 至 ‘'9'’。 它等价于 ‘c in
     string.digits’。

 -- 函数: curses.ascii.isgraph (c)

     检测任意 ASCII 可打印字符，不包括空白符。

 -- 函数: curses.ascii.islower (c)

     检测 ASCII 小写字母字符。

 -- 函数: curses.ascii.isprint (c)

     检测任意 ASCII 可打印字符，包括空白符。

 -- 函数: curses.ascii.ispunct (c)

     检测任意 ASCII 可打印字符，不包括空白符或字母数字类字符。

 -- 函数: curses.ascii.isspace (c)

     检测 ASCII 空白字符；包括空格，换行，回车，进纸，水平制表和垂直制表
     。

 -- 函数: curses.ascii.isupper (c)

     检测 ASCII 大写字母字符。

 -- 函数: curses.ascii.isxdigit (c)

     检测 ASCII 十六进制数码。 这等价于 ‘c in string.hexdigits’。

 -- 函数: curses.ascii.isctrl (c)

     检测 ASCII 控制字符（序号值 0 至 31）。

 -- 函数: curses.ascii.ismeta (c)

     检测非 ASCII 字符（码位值 0x80 及以上）。

这些函数接受整数或单字符字符串；当参数为字符串时，会先使用内置函数 *note
ord(): 1437. 进行转换。

请注意所有这些函数都是检测根据你传入的字符串的字符所生成的码位值；它们实
际上完全不会知晓本机的字符编码格式。

以下两个函数接受单字符字符串或整数形式的字节值；它们会返回相同类型的值。

 -- 函数: curses.ascii.ascii (c)

     返回对应于 `c' 的下个 7 比特位的 ASCII 值。

 -- 函数: curses.ascii.ctrl (c)

     返回对应于给定字符的控制字符（字符比特值会与 0x1f 进行按位与运算）
     。

 -- 函数: curses.ascii.alt (c)

     返回对应于给定 ASCII 字符的 8 比特位字符（字符比特值会与 0x80 进行
     按位或运算）。

以下函数接受单字符字符串或整数值；它会返回一个字符串。

 -- 函数: curses.ascii.unctrl (c)

     返回 ASCII 字符 `c' 的字符串表示形式。 如果 `c' 是可打印字符，则字
     符串为字符本身。 如果该字符是控制字符 (0x00–0x1f) 则字符串由一个插
     入符 (‘'^'’) 加相应的大写字母组成。 如果该字符是 ASCII 删除符
     (0x7f) 则字符串为 ‘'^?'’。 如果该字符设置了元比特位 (0x80)，元比特
     位会被去除，应用以上规则后将在结果之前添加 ‘'!'’。

 -- 数据: curses.ascii.controlnames

     一个 33 元素的字符串数据，其中按从 0 (NUL) 到 0x1f (US) 的顺序包含
     了三十二个 ASCII 控制字符的 ASCII 助记符，另加空格符的助记符 ‘SP’。


File: python.info,  Node: curses panel --- curses 的 panel 栈扩展,  Next: platform --- 获取底层平台的标识数据,  Prev: curses ascii --- 用于 ASCII 字符的工具,  Up: 通用操作系统服务

5.16.13 ‘curses.panel’ — curses 的 panel 栈扩展
-----------------------------------------------

__________________________________________________________________

面板是具有添加深度功能的窗口，因此它们可以从上至下堆叠为栈，只有显示每个
窗口的可见部分会显示出来。 面板可以在栈中被添加、上移或下移，也可以被移
除。

* Menu:

* 函数: 函数<4>.
* Panel 对象::


File: python.info,  Node: 函数<4>,  Next: Panel 对象,  Up: curses panel --- curses 的 panel 栈扩展

5.16.13.1 函数
..............

*note curses.panel: 2e. 模块定义了以下函数:

 -- 函数: curses.panel.bottom_panel ()

     返回面板栈中的底部面板。

 -- 函数: curses.panel.new_panel (win)

     返回一个面板对象，将其与给定的窗口 `win' 相关联。 请注意你必须显式
     地保持所返回的面板对象。 如果你不这样做，面板对象会被垃圾回收并从面
     板栈中被移除。

 -- 函数: curses.panel.top_panel ()

     返回面板栈中的顶部面板。

 -- 函数: curses.panel.update_panels ()

     在面板栈发生改变后更新虚拟屏幕。 这不会调用 *note
     curses.doupdate(): 2172.，因此你不必自己执行此操作。


File: python.info,  Node: Panel 对象,  Prev: 函数<4>,  Up: curses panel --- curses 的 panel 栈扩展

5.16.13.2 Panel 对象
....................

Panel 对象，如上面 *note new_panel(): 221e. 所返回的对象，是带有栈顺序的
多个窗口。 总是会有一个窗口与确定内容的面板相关联，面板方法会负责窗口在
面板栈中的深度。

Panel 对象具有以下方法:

 -- 方法: Panel.above ()

     返回当前面板之上的面板。

 -- 方法: Panel.below ()

     返回当前面板之下的面板。

 -- 方法: Panel.bottom ()

     将面板推至栈底部。

 -- 方法: Panel.hidden ()

     如果面板被隐藏（不可见）则返回 ‘True’，否则返回 ‘False’。

 -- 方法: Panel.hide ()

     隐藏面板。 这不会删除对象，它只是让窗口在屏幕上不可见。

 -- 方法: Panel.move (y, x)

     将面板移至屏幕坐标 ‘(y, x)’。

 -- 方法: Panel.replace (win)

     将与面板相关联的窗口改为窗口 `win'。

 -- 方法: Panel.set_userptr (obj)

     将面板的用户指向设为 `obj'。 这被用来将任意数据与面板相关联，数据可
     以是任何 Python 对象。

 -- 方法: Panel.show ()

     显示面板（面板可能已被隐藏）。

 -- 方法: Panel.top ()

     将面板推至栈顶部。

 -- 方法: Panel.userptr ()

     返回面板的用户指针。 这可以是任何 Python 对象。

 -- 方法: Panel.window ()

     返回与面板相关联的窗口对象。


File: python.info,  Node: platform --- 获取底层平台的标识数据,  Next: errno --- 标准 errno 系统符号,  Prev: curses panel --- curses 的 panel 栈扩展,  Up: 通用操作系统服务

5.16.14 ‘platform’ — 获取底层平台的标识数据
-------------------------------------------

`示例代码：' Lib/platform.py(1)

__________________________________________________________________

     注解: 特定平台按字母顺序排列，Linux 包括在 Unix 小节之中。

* Menu:

* 跨平台::
* Java平台::
* Windows平台::
* Mac OS平台::
* Unix 平台::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/platform.py


File: python.info,  Node: 跨平台,  Next: Java平台,  Up: platform --- 获取底层平台的标识数据

5.16.14.1 跨平台
................

 -- 函数: platform.architecture (executable=sys.executable, bits='',
          linkage='')

     查询给定的可执行文件（默认为 Python 解释器二进制码文件）来获取各种
     架构信息。

     返回一个元素 ‘(bits, linkage)’，其中包含可执行文件所使用的位架构和
     链接格式信息。 这两个值均以字符串形式返回。

     无法确定的值将返回为形参预设所给出的值。 如果给出的位数为 ‘''’，则
     会使用 ‘sizeof(pointer)’ (或者当 Python 版本 < 1.5.2 时为
     ‘sizeof(long)’) 作为所支持的指针大小的提示。

     此函数依赖于系统的 ‘file’ 命令来执行实际的操作。 这在几乎所有 Unix
     平台和某些非 Unix 平台上只有当可执行文件指向 Python 解释器时才可用
     。 当以上要求不满足时将会使用合理的默认值。

          注解: 在 Mac OS X（也许还有其他平台）上，可执行文件可能是包含
          多种架构的通用文件。

          要获取当前解释器的“64 位性”，更可靠的做法是查询 *note
          sys.maxsize: b4b. 属性:

               is_64bits = sys.maxsize > 2**32

 -- 函数: platform.machine ()

     返回机器类型，例如 ‘'i386'’。 如果该值无法确定则会返回一个空字符串
     。

 -- 函数: platform.node ()

     返回计算机的网络名称（可能不是完整限定名称！）。 如果该值无法确定则
     会返回一个空字符串。

 -- 函数: platform.platform (aliased=0, terse=0)

     返回一个标识底层平台的字符串，其中带有尽可能多的有用信息。

     输出信息的目标是“人类易读”而非机器易解析。 它在不同平台上可能看起来
     不一致，这是有意为之的。

     如果 `aliased' 为真值，此函数将使用各种平台不同与其通常名称的别名来
     报告系统名称，例如 SunOS 将被报告为 Solaris。 *note system_alias():
     2234. 函数将被用于实现此功能。

     将 `terse' 设为真值将导致此函数只返回标识平台所必须的最小量信息。

     在 3.8 版更改: 在 macOS 上，此函数现在会在 *note mac_ver(): 102c. 返
     回的发布版字符串非空时使用它，以便获取 macOS 版本而非 darwin 版本。

 -- 函数: platform.processor ()

     返回（真实的）处理器名称，例如 ‘'amdk6'’。

     如果该值无法确定则将返回空字符串。 请注意许多平台都不提供此信息或是
     简单地返回与 *note machine(): 2232. 相同的值。 NetBSD 则会提供此信
     息。

 -- 函数: platform.python_build ()

     返回一个元组 ‘(buildno, builddate)’，以字符串表示的 Python 编译代码
     和日期。

 -- 函数: platform.python_compiler ()

     返回一个表示用于编译 Python 的编译器的的字符串。

 -- 函数: platform.python_branch ()

     返回一个表示 Python 实现的 SCM 分支的字符串。

 -- 函数: platform.python_implementation ()

     返回一个标识 Python 实现的字符串。 可能的返回值有: ’CPython’,
     ’IronPython’, ’Jython’, ’PyPy’。

 -- 函数: platform.python_revision ()

     返回一个标识 Python 实现的 SCM 修订版的字符串。

 -- 函数: platform.python_version ()

     将 Python 版本以字符串 ‘'major.minor.patchlevel'’ 形式返回。

     请注意此返回值不同于 Python ‘sys.version’，它将总是包括 patchlevel
     (默认为 0)。

 -- 函数: platform.python_version_tuple ()

     将 Python 版本以字符串元组 ‘(major, minor, patchlevel)’ 形式返回。

     请注意此返回值不同于 Python ‘sys.version’，它将总是包括 patchlevel
     (默认为 ‘'0'’)。

 -- 函数: platform.release ()

     返回系统的发布版本，例如 ‘'2.2.0'’ 或 ‘'NT'’，如果该值无法确定则将
     返回一个空字符串。

 -- 函数: platform.system ()

     返回系统平台/OS的名称，例如 ‘'Linux'’, ‘'Darwin'’, ‘'Java'’,
     ‘'Windows'’。 如果该值无法确定则将返回一个空字符串。

 -- 函数: platform.system_alias (system, release, version)

     返回别名为某些系统所使用的常见营销名称的 ‘(system, release,
     version)’。 它还会在可能导致混淆的情况下对信息进行一些重排序操作。

 -- 函数: platform.version ()

     返回系统的发布版本信息，例如 ‘'#3 on degas'’。 如果该值无法确定则将
     返回一个空字符串。

 -- 函数: platform.uname ()

     具有高可移植性的 uname 接口。 返回包含六个属性的 *note
     namedtuple(): 1b7.: *note system: 223e, *note node: 2233, *note
     release: 223d, *note version: 223f, *note machine: 2232. 和 *note
     processor: 2235.。

     请注意此函数添加的第六个属性 (*note processor: 2235.) 并不存在于
     *note os.uname(): a65. 的结果中。 并且前两个属性的属性名称也不一致
     ；*note os.uname(): a65. 是将它们称为 ‘sysname’ 和 ‘nodename’。

     无法确定的条目会被设为 ‘''’。

     在 3.3 版更改: 将结果从元组改为命名元组。


File: python.info,  Node: Java平台,  Next: Windows平台,  Prev: 跨平台,  Up: platform --- 获取底层平台的标识数据

5.16.14.2 Java平台
..................

 -- 函数: platform.java_ver (release='', vendor='', vminfo=('', '', ''),
          osinfo=('', '', ''))

     Jython的版本接口

     返回一个元组 ‘(release, vendor, vminfo, osinfo)’，其中 `vminfo' 为
     元组 ‘(vm_name, vm_release, vm_vendor)’ 而 `osinfo' 为元组
     ‘(os_name, os_version, os_arch)’。 无法确定的值将设为由形参所给出的
     默认值 (默认均为 ‘''’)。


File: python.info,  Node: Windows平台,  Next: Mac OS平台,  Prev: Java平台,  Up: platform --- 获取底层平台的标识数据

5.16.14.3 Windows平台
.....................

 -- 函数: platform.win32_ver (release='', version='', csd='', ptype='')

     从 Windows 注册表获取额外的版本信息并返回一个元组 ‘(release,
     version, csd, ptype)’ 表示 OS 发行版, 版本号, CSD 级别 (Service
     Pack) 和 OS 类型 (多个/单个处理器)。

     一点提示: `ptype' 在单个处理器的 NT 机器上为 ‘'Uniprocessor Free'’
     而在多个处理器的机器上为 ‘'Multiprocessor Free'’。 `’Free’' 是指该
     OS 版本没有调试代码。 它还可能显示 `’Checked’' 表示该 OS 版本使用了
     调试代码，即检测参数、范围等的代码。

 -- 函数: platform.win32_edition ()

     返回一个代表当前 Windows 版本的字符串。 可能的值包括但不限于
     ‘'Enterprise'’, ‘'IoTUAP'’, ‘'ServerStandard'’ 和 ‘'nanoserver'’。

     3.8 新版功能.

 -- 函数: platform.win32_is_iot ()

     如果 *note win32_edition(): 2243. 返回的 Windows 版本被识别为 IoT 版
     则返回 ‘True’。

     3.8 新版功能.


File: python.info,  Node: Mac OS平台,  Next: Unix 平台,  Prev: Windows平台,  Up: platform --- 获取底层平台的标识数据

5.16.14.4 Mac OS平台
....................

 -- 函数: platform.mac_ver (release='', versioninfo=('', '', ''),
          machine='')

     获取 Mac OS 版本信息并将其返回为元组 ‘(release, versioninfo,
     machine)’，其中 `versioninfo' 是一个元组 ‘(version, dev_stage,
     non_release_version)’。

     无法确定的条目会被设为 ‘''’。 所有元组条目均为字符串。


File: python.info,  Node: Unix 平台,  Prev: Mac OS平台,  Up: platform --- 获取底层平台的标识数据

5.16.14.5 Unix 平台
...................

 -- 函数: platform.libc_ver (executable=sys.executable, lib='',
          version='', chunksize=16384)

     尝试确定可执行文件（默认为 Python 解释器）所链接到的 libc 版本。 返
     回一个字符串元组 ‘(lib, version)’，当查找失败时其默认值将设为给定的
     形参值。

     请注意此函数对于不同 libc 版本向可执行文件添加符号的方式有深层的关
     联，可能仅适用于使用 ‘gcc’ 编译出来的可执行文件。

     文件将按 `chunksize' 个字节的分块来读取和扫描。


File: python.info,  Node: errno --- 标准 errno 系统符号,  Next: ctypes --- Python 的外部函数库,  Prev: platform --- 获取底层平台的标识数据,  Up: 通用操作系统服务

5.16.15 ‘errno’ — 标准 errno 系统符号
-------------------------------------

__________________________________________________________________

本模块提供标准的 ‘errno’ 系统符号。每个符号的值是其对应的整数值。符号的
名称和描述来自 ‘linux/include/errno.h’，应该是非常全面的。

 -- 数据: errno.errorcode

     提供从 errno 值到底层系统中字符串名称的映射的字典。例如，
     ‘errno.errorcode[errno.EPERM]’ 映射为 ‘'EPERM'’ 。

如果要将数字的错误代码转换为错误信息，请使用 *note os.strerror(): 1f12.。

在下面的列表中，当前平台上没有使用的符号没有被本模块定义。 已定义的符号
的具体列表可参见 ‘errno.errorcode.keys()’。 可用的符号包括：

 -- 数据: errno.EPERM

     操作不被允许

 -- 数据: errno.ENOENT

     无此文件或目录

 -- 数据: errno.ESRCH

     无此进程

 -- 数据: errno.EINTR

     系统调用中断。

     参见
     ....

     此错误被映射到异常 *note InterruptedError: 662.。

 -- 数据: errno.EIO

     I/O 错误

 -- 数据: errno.ENXIO

     无此设备或地址

 -- 数据: errno.E2BIG

     参数列表过长

 -- 数据: errno.ENOEXEC

     执行格式错误

 -- 数据: errno.EBADF

     错误的文件号

 -- 数据: errno.ECHILD

     无子进程

 -- 数据: errno.EAGAIN

     重试

 -- 数据: errno.ENOMEM

     内存不足

 -- 数据: errno.EACCES

     没有权限

 -- 数据: errno.EFAULT

     错误的地址

 -- 数据: errno.ENOTBLK

     需要块设备

 -- 数据: errno.EBUSY

     设备或资源忙

 -- 数据: errno.EEXIST

     文件已存在

 -- 数据: errno.EXDEV

     跨设备链接

 -- 数据: errno.ENODEV

     无此设备

 -- 数据: errno.ENOTDIR

     不是目录

 -- 数据: errno.EISDIR

     是目录

 -- 数据: errno.EINVAL

     无效的参数

 -- 数据: errno.ENFILE

     文件表溢出

 -- 数据: errno.EMFILE

     打开的文件过多

 -- 数据: errno.ENOTTY

     不是打字机

 -- 数据: errno.ETXTBSY

     文本文件忙

 -- 数据: errno.EFBIG

     文件过大

 -- 数据: errno.ENOSPC

     设备已无可用空间

 -- 数据: errno.ESPIPE

     非法查找

 -- 数据: errno.EROFS

     只读文件系统

 -- 数据: errno.EMLINK

     链接过多

 -- 数据: errno.EPIPE

     管道已损坏

 -- 数据: errno.EDOM

     数学参数超出函数范围

 -- 数据: errno.ERANGE

     数学运算结果无法表示

 -- 数据: errno.EDEADLK

     将发生资源死锁

 -- 数据: errno.ENAMETOOLONG

     文件名过长

 -- 数据: errno.ENOLCK

     没有可用的记录锁

 -- 数据: errno.ENOSYS

     功能未实现

 -- 数据: errno.ENOTEMPTY

     目录非空

 -- 数据: errno.ELOOP

     遇到过多的符号链接

 -- 数据: errno.EWOULDBLOCK

     操作将阻塞

 -- 数据: errno.ENOMSG

     没有所需类型的消息

 -- 数据: errno.EIDRM

     标识符被移除

 -- 数据: errno.ECHRNG

     信道编号超出范围

 -- 数据: errno.EL2NSYNC

     级别 2 未同步

 -- 数据: errno.EL3HLT

     级别 3 已停止

 -- 数据: errno.EL3RST

     级别 3 重置

 -- 数据: errno.ELNRNG

     链接编号超出范围

 -- 数据: errno.EUNATCH

     未附加协议驱动

 -- 数据: errno.ENOCSI

     没有可用的 CSI 结构

 -- 数据: errno.EL2HLT

     级别 2 已停止

 -- 数据: errno.EBADE

     无效的交换

 -- 数据: errno.EBADR

     无效的请求描述符

 -- 数据: errno.EXFULL

     交换已满

 -- 数据: errno.ENOANO

     没有阳极

 -- 数据: errno.EBADRQC

     无效的请求码·

 -- 数据: errno.EBADSLT

     无效的槽位

 -- 数据: errno.EDEADLOCK

     文件锁定死锁错误

 -- 数据: errno.EBFONT

     错误的字体文件格式

 -- 数据: errno.ENOSTR

     设备不是流

 -- 数据: errno.ENODATA

     没有可用的数据

 -- 数据: errno.ETIME

     计时器已到期

 -- 数据: errno.ENOSR

     流资源不足

 -- 数据: errno.ENONET

     机器不在网络上

 -- 数据: errno.ENOPKG

     包未安装

 -- 数据: errno.EREMOTE

     对象是远程的

 -- 数据: errno.ENOLINK

     链接已被切断

 -- 数据: errno.EADV

     广告错误

 -- 数据: errno.ESRMNT

     挂载错误

 -- 数据: errno.ECOMM

     发送时通讯错误

 -- 数据: errno.EPROTO

     协议错误

 -- 数据: errno.EMULTIHOP

     已尝试多跳

 -- 数据: errno.EDOTDOT

     RFS 专属错误

 -- 数据: errno.EBADMSG

     非数据消息

 -- 数据: errno.EOVERFLOW

     值相对于已定义数据类型过大

 -- 数据: errno.ENOTUNIQ

     名称在网络上不唯一

 -- 数据: errno.EBADFD

     文件描述符处于错误状态

 -- 数据: errno.EREMCHG

     远端地址已改变

 -- 数据: errno.ELIBACC

     无法访问所需的共享库

 -- 数据: errno.ELIBBAD

     访问已损坏的共享库

 -- 数据: errno.ELIBSCN

     a.out 中的 .lib 部分已损坏

 -- 数据: errno.ELIBMAX

     尝试链接过多的共享库

 -- 数据: errno.ELIBEXEC

     无法直接执行共享库

 -- 数据: errno.EILSEQ

     非法字节序列

 -- 数据: errno.ERESTART

     已中断系统调用需要重启

 -- 数据: errno.ESTRPIPE

     流管道错误

 -- 数据: errno.EUSERS

     用户过多

 -- 数据: errno.ENOTSOCK

     在非套接字上执行套接字操作

 -- 数据: errno.EDESTADDRREQ

     需要目标地址

 -- 数据: errno.EMSGSIZE

     消息过长

 -- 数据: errno.EPROTOTYPE

     套接字的协议类型错误

 -- 数据: errno.ENOPROTOOPT

     协议不可用

 -- 数据: errno.EPROTONOSUPPORT

     协议不受支持

 -- 数据: errno.ESOCKTNOSUPPORT

     套接字类型不受支持

 -- 数据: errno.EOPNOTSUPP

     操作在传输端点上不受支持

 -- 数据: errno.EPFNOSUPPORT

     协议族不受支持

 -- 数据: errno.EAFNOSUPPORT

     地址族不受协议支持

 -- 数据: errno.EADDRINUSE

     地址已被使用

 -- 数据: errno.EADDRNOTAVAIL

     无法分配要求的地址

 -- 数据: errno.ENETDOWN

     网络已断开

 -- 数据: errno.ENETUNREACH

     网络不可达

 -- 数据: errno.ENETRESET

     网络因重置而断开连接

 -- 数据: errno.ECONNABORTED

     软件导致连接中止

 -- 数据: errno.ECONNRESET

     连接被对方重置

 -- 数据: errno.ENOBUFS

     没有可用的缓冲区空间

 -- 数据: errno.EISCONN

     传输端点已连接

 -- 数据: errno.ENOTCONN

     传输端点未连接

 -- 数据: errno.ESHUTDOWN

     传输端点关闭后无法发送

 -- 数据: errno.ETOOMANYREFS

     引用过多：无法拼接

 -- 数据: errno.ETIMEDOUT

     连接超时

 -- 数据: errno.ECONNREFUSED

     连接被拒

 -- 数据: errno.EHOSTDOWN

     主机已关闭

 -- 数据: errno.EHOSTUNREACH

     没有到主机的路由

 -- 数据: errno.EALREADY

     操作已在进行

 -- 数据: errno.EINPROGRESS

     操作正在进行

 -- 数据: errno.ESTALE

     过期的 NFS 文件句柄

 -- 数据: errno.EUCLEAN

     结构需要清理

 -- 数据: errno.ENOTNAM

     不是 XENIX 命名类型文件

 -- 数据: errno.ENAVAIL

     没有可用的 XENIX 信标

 -- 数据: errno.EISNAM

     是命名类型文件

 -- 数据: errno.EREMOTEIO

     远程 I/O 错误

 -- 数据: errno.EDQUOT

     超出配额


File: python.info,  Node: ctypes --- Python 的外部函数库,  Prev: errno --- 标准 errno 系统符号,  Up: 通用操作系统服务

5.16.16 ‘ctypes’ — Python 的外部函数库
--------------------------------------

__________________________________________________________________

*note ctypes: 2b. 是 Python 的外部函数库。它提供了与 C 兼容的数据类型，
并允许调用 DLL 或共享库中的函数。可使用该模块以纯 Python 形式对这些库进
行封装。

* Menu:

* ctypes 教程::
* ctypes 参考手册::


File: python.info,  Node: ctypes 教程,  Next: ctypes 参考手册,  Up: ctypes --- Python 的外部函数库

5.16.16.1 ctypes 教程
.....................

注意：在本教程中的示例代码使用 *note doctest: 67. 进行过测试，保证其正确
运行。由于有些代码在Linux，Windows或Mac OS X下的表现不同，这些代码会在
doctest 中包含相关的指令注解。

注意：部分示例代码引用了 ctypes *note c_int: 22c3. 类型。在
‘sizeof(long) == sizeof(int)’ 的平台上此类型是 *note c_long: 22c4. 的一
个别名。所以，在程序输出 *note c_long: 22c4. 而不是你期望的 *note c_int:
22c3. 时不必感到迷惑 — 它们实际上是同一种类型。

* Menu:

* 载入动态连接库::
* 操作导入的动态链接库中的函数::
* 调用函数::
* 基础数据类型::
* 调用函数，继续::
* 使用自定义的数据类型调用函数::
* 指定必选参数的类型(函数原型): 指定必选参数的类型 函数原型.
* 返回类型::
* 传递指针(或者传递引用): 传递指针 或者传递引用.
* 结构体和联合::
* 结构体/联合 字段对齐及字节顺序::
* 结构体和联合中的位域::
* 数组::
* 指针::
* 类型强制转换::
* 不完整类型::
* 回调函数::
* 访问 dll 中导出的值::
* 意外::
* 变长数据类型::


File: python.info,  Node: 载入动态连接库,  Next: 操作导入的动态链接库中的函数,  Up: ctypes 教程

5.16.16.2 载入动态连接库
........................

*note ctypes: 2b. 导出了 `cdll' 对象，在 Windows 系统中还导出了 `windll'
和 `oledll' 对象用于载入动态连接库。

通过操作这些对象的属性，你可以载入外部的动态链接库。`cdll' 载入按标准的
‘cdecl’ 调用协议导出的函数，而 `windll' 导入的库按 ‘stdcall’ 调用协议调
用其中的函数。 `oledll' 也按 ‘stdcall’ 调用协议调用其中的函数，并假定该
函数返回的是 Windows ‘HRESULT’ 错误代码，并当函数调用失败时，自动根据该
代码甩出一个 *note OSError: 1d4. 异常。

在 3.3 版更改: 原来在 Windows 下甩出的异常类型 *note WindowsError: 99c.
现在是 *note OSError: 1d4. 的一个别名。

这是一些 Windows 下的例子。注意：‘msvcrt’ 是微软 C 标准库，包含了大部分
C 标准函数，这些函数都是以 cdecl 调用协议进行调用的。

     >>> from ctypes import *
     >>> print(windll.kernel32)
     <WinDLL 'kernel32', handle ... at ...>
     >>> print(cdll.msvcrt)
     <CDLL 'msvcrt', handle ... at ...>
     >>> libc = cdll.msvcrt
     >>>

Windows会自动添加通常的 ‘.dll’ 文件扩展名。

     注解: 通过 ‘cdll.msvcrt’ 调用的标准 C 函数，可能会导致调用一个过时
     的，与当前 Python 所不兼容的函数。因此，请尽量使用标准的 Python 函
     数，而不要使用 ‘msvcrt’ 模块。

在 Linux 下，必须使用 `包含' 文件扩展名的文件名来导入共享库。因此不能简
单使用对象属性的方式来导入库。因此，你可以使用方法 ‘LoadLibrary()’，或构
造 CDLL 对象来导入库。

     >>> cdll.LoadLibrary("libc.so.6")
     <CDLL 'libc.so.6', handle ... at ...>
     >>> libc = CDLL("libc.so.6")
     >>> libc
     <CDLL 'libc.so.6', handle ... at ...>
     >>>


File: python.info,  Node: 操作导入的动态链接库中的函数,  Next: 调用函数,  Prev: 载入动态连接库,  Up: ctypes 教程

5.16.16.3 操作导入的动态链接库中的函数
......................................

通过操作dll对象的属性来操作这些函数。

     >>> from ctypes import *
     >>> libc.printf
     <_FuncPtr object at 0x...>
     >>> print(windll.kernel32.GetModuleHandleA)
     <_FuncPtr object at 0x...>
     >>> print(windll.kernel32.MyOwnFunction)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
       File "ctypes.py", line 239, in __getattr__
         func = _StdcallFuncPtr(name, self)
     AttributeError: function 'MyOwnFunction' not found
     >>>

注意：Win32系统的动态库，比如 ‘kernel32’ 和 ‘user32’，通常会同时导出同一
个函数的 ANSI 版本和 UNICODE 版本。UNICODE 版本通常会在名字最后以 ‘W’ 结
尾，而 ANSI 版本的则以 ‘A’ 结尾。 win32的 ‘GetModuleHandle’ 函数会根据一
个模块名返回一个 `模块句柄'，该函数暨同时包含这样的两个版本的原型函数，
并通过宏 UNICODE 是否定义，来决定宏 ‘GetModuleHandle’ 导出的是哪个具体函
数。

     /* ANSI version */
     HMODULE GetModuleHandleA(LPCSTR lpModuleName);
     /* UNICODE version */
     HMODULE GetModuleHandleW(LPCWSTR lpModuleName);

`windll' 不会通过这样的魔法手段来帮你决定选择哪一种函数，你必须显式的调
用 ‘GetModuleHandleA’ 或 ‘GetModuleHandleW’，并分别使用字节对象或字符串
对象作参数。

有时候，dlls的导出的函数名不符合 Python 的标识符规范，比如
‘"??2@YAPAXI@Z"’。此时，你必须使用 *note getattr(): 451. 方法来获得该函
数。

     >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")
     <_FuncPtr object at 0x...>
     >>>

Windows 下，有些 dll 导出的函数没有函数名，而是通过其顺序号调用。对此类
函数，你也可以通过 dll 对象的数值索引来操作这些函数。

     >>> cdll.kernel32[1]
     <_FuncPtr object at 0x...>
     >>> cdll.kernel32[0]
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
       File "ctypes.py", line 310, in __getitem__
         func = _StdcallFuncPtr(name, self)
     AttributeError: function ordinal 0 not found
     >>>


File: python.info,  Node: 调用函数,  Next: 基础数据类型,  Prev: 操作导入的动态链接库中的函数,  Up: ctypes 教程

5.16.16.4 调用函数
..................

你可以貌似是调用其它 Python 函数那样直接调用这些函数。在这个例子中，我们
调用了 ‘time()’ 函数，该函数返回一个系统时间戳（从 Unix 时间起点到现在的
秒数），而‘‘GetModuleHandleA()‘‘ 函数返回一个 win32 模块句柄。

此函数中调用的两个函数都使用了空指针（用 ‘None’ 作为空指针）:

     >>> print(libc.time(None))
     1150640792
     >>> print(hex(windll.kernel32.GetModuleHandleA(None)))
     0x1d000000
     >>>

如果你用 ‘cdecl’ 调用方式调用 ‘stdcall’ 约定的函数，则会甩出一个异常
*note ValueError: 1fc.。反之亦然。

     >>> cdll.kernel32.GetModuleHandleA(None)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     ValueError: Procedure probably called with not enough arguments (4 bytes missing)
     >>>

     >>> windll.msvcrt.printf(b"spam")
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     ValueError: Procedure probably called with too many arguments (4 bytes in excess)
     >>>

你必须阅读这些库的头文件或说明文档来确定它们的正确的调用协议。

在Windows中，*note ctypes: 2b. 使用 win32 结构化异常处理来防止由于在调用
函数时使用非法参数导致的程序崩溃。

     >>> windll.kernel32.GetModuleHandleA(32)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     OSError: exception: access violation reading 0x00000020
     >>>

然而，总有许多办法，通过调用 *note ctypes: 2b. 使得 Python 程序崩溃。因
此，你必须小心使用。 *note faulthandler: 7d. 模块可以用于帮助诊断程序崩
溃的原因。（比如由于错误的C库函数调用导致的段错误）。

‘None’，整型，字节对象和（UNICODE）字符串是仅有的可以直接作为函数参数使
用的四种Python本地数据类型。‘None‘’ 作为C的空指针 (‘NULL’)，字节和字符串
类型作为一个指向其保存数据的内存块指针 （‘char *’ 或 ‘wchar_t *’)。
Python 的整型则作为平台默认的C的 ‘int’ 类型，他们的数值被截断以适应C类型
的整型长度。

在我们开始调用函数前，我们必须先了解作为函数参数的 *note ctypes: 2b. 数
据类型。


File: python.info,  Node: 基础数据类型,  Next: 调用函数，继续,  Prev: 调用函数,  Up: ctypes 教程

5.16.16.5 基础数据类型
......................

*note ctypes: 2b. 定义了一些和C兼容的基本数据类型：

ctypes 类型                C 类型                                         Python 类型
                                                                          
-----------------------------------------------------------------------------------------------------------
                                                                          
*note c_bool: 22cd.        ‘_Bool’                                        bool (1)
                                                                          
                                                                          
*note c_char: 22ce.        ‘char’                                         单字符字节对象
                                                                          
                                                                          
*note c_wchar: 22cf.       ‘wchar_t’                                      单字符字符串
                                                                          
                                                                          
*note c_byte: 22d0.        ‘char’                                         int
                                                                          
                                                                          
*note c_ubyte: 22d1.       ‘unsigned char’                                int
                                                                          
                                                                          
*note c_short: 22d2.       ‘short’                                        int
                                                                          
                                                                          
*note c_ushort: 22d3.      ‘unsigned short’                               int
                                                                          
                                                                          
*note c_int: 22c3.         ‘int’                                          int
                                                                          
                                                                          
*note c_uint: 22d4.        ‘unsigned int’                                 int
                                                                          
                                                                          
*note c_long: 22c4.        ‘long’                                         int
                                                                          
                                                                          
*note c_ulong: 22d5.       ‘unsigned long’                                int
                                                                          
                                                                          
*note c_longlong: 22d6.    ‘__int64’ 或 ‘long long’                       int
                                                                          
                                                                          
*note c_ulonglong: 22d7.   ‘unsigned __int64’ 或 ‘unsigned long long’     int
                                                                          
                                                                          
*note c_size_t: 22d8.      ‘size_t’                                       int
                                                                          
                                                                          
*note c_ssize_t: bd9.      ‘ssize_t’ 或 ‘Py_ssize_t’                      int
                                                                          
                                                                          
*note c_float: 22d9.       ‘float’                                        float
                                                                          
                                                                          
*note c_double: ec1.       ‘double’                                       float
                                                                          
                                                                          
*note c_longdouble: ec2.   ‘long double’                                  float
                                                                          
                                                                          
*note c_char_p: 22da.      ‘char *’ (以 NUL 结尾)                         字节串对象或 ‘None’
                                                                          
                                                                          
*note c_wchar_p: ea9.      ‘wchar_t *’ (以 NUL 结尾)                      字符串或 ‘None’
                                                                          
                                                                          
*note c_void_p: 22db.      ‘void *’                                       int 或 ‘None’
                                                                          

  1. 构造函数接受任何具有真值的对象。

所有这些类型都可以通过使用正确类型和值的可选初始值调用它们来创建:

     >>> c_int()
     c_long(0)
     >>> c_wchar_p("Hello, World")
     c_wchar_p(140018365411392)
     >>> c_ushort(-3)
     c_ushort(65533)
     >>>

由于这些类型是可变的，它们的值也可以在以后更改:

     >>> i = c_int(42)
     >>> print(i)
     c_long(42)
     >>> print(i.value)
     42
     >>> i.value = -99
     >>> print(i.value)
     -99
     >>>

当给指针类型的对象 *note c_char_p: 22da, *note c_wchar_p: ea9. 和 *note
c_void_p: 22db. 等赋值时，将改变它们所指向的 `内存地址'，而 `不是' 它们
所指向的内存区域的 `内容' (这是理所当然的，因为 Python 的 bytes 对象是不
可变的):

     >>> s = "Hello, World"
     >>> c_s = c_wchar_p(s)
     >>> print(c_s)
     c_wchar_p(139966785747344)
     >>> print(c_s.value)
     Hello World
     >>> c_s.value = "Hi, there"
     >>> print(c_s)              # the memory location has changed
     c_wchar_p(139966783348904)
     >>> print(c_s.value)
     Hi, there
     >>> print(s)                # first object is unchanged
     Hello, World
     >>>

但你要注意不能将它们传递给会改变指针所指内存的函数。如果你需要可改变的内
存块，ctypes 提供了 *note create_string_buffer(): 22dc. 函数，它提供多种
方式创建这种内存块。当前的内存块内容可以通过 ‘raw’ 属性存取，如果你希望
将它作为NUL结束的字符串，请使用 ‘value’ 属性:

     >>> from ctypes import *
     >>> p = create_string_buffer(3)            # create a 3 byte buffer, initialized to NUL bytes
     >>> print(sizeof(p), repr(p.raw))
     3 b'\x00\x00\x00'
     >>> p = create_string_buffer(b"Hello")     # create a buffer containing a NUL terminated string
     >>> print(sizeof(p), repr(p.raw))
     6 b'Hello\x00'
     >>> print(repr(p.value))
     b'Hello'
     >>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
     >>> print(sizeof(p), repr(p.raw))
     10 b'Hello\x00\x00\x00\x00\x00'
     >>> p.value = b"Hi"
     >>> print(sizeof(p), repr(p.raw))
     10 b'Hi\x00lo\x00\x00\x00\x00\x00'
     >>>

*note create_string_buffer(): 22dc. 函数替代以前的ctypes版本中的
‘c_buffer()’ 函数 (仍然可当作别名使用)和 ‘c_string()’ 函数。*note
create_unicode_buffer(): fbd. 函数创建包含 unicode 字符的可变内存块，与
之对应的C语言类型是 ‘wchar_t’。


File: python.info,  Node: 调用函数，继续,  Next: 使用自定义的数据类型调用函数,  Prev: 基础数据类型,  Up: ctypes 教程

5.16.16.6 调用函数，继续
........................

注意 printf 将打印到真正标准输出设备，而*不是* *note sys.stdout: 317.，
因此这些实例只能在控制台提示符下工作，而不能在 `IDLE' 或 `PythonWin' 中
运行。

     >>> printf = libc.printf
     >>> printf(b"Hello, %s\n", b"World!")
     Hello, World!
     14
     >>> printf(b"Hello, %S\n", "World!")
     Hello, World!
     14
     >>> printf(b"%d bottles of beer\n", 42)
     42 bottles of beer
     19
     >>> printf(b"%f bottles of beer\n", 42.5)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
     >>>

正如前面所提到过的，除了整数、字符串以及字节串之外，所有的 Python 类型都
必须使用它们对应的 *note ctypes: 2b. 类型包装，才能够被正确地转换为所需
的C语言类型。

     >>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
     An int 1234, a double 3.140000
     31
     >>>


File: python.info,  Node: 使用自定义的数据类型调用函数,  Next: 指定必选参数的类型 函数原型,  Prev: 调用函数，继续,  Up: ctypes 教程

5.16.16.7 使用自定义的数据类型调用函数
......................................

你也可以通过自定义 *note ctypes: 2b. 参数转换方式来允许自定义类型作为参
数。 *note ctypes: 2b. 会寻找 ‘_as_parameter_’ 属性并使用它作为函数参数
。当然，它必须是数字、字符串或者二进制字符串:

     >>> class Bottles:
     ...     def __init__(self, number):
     ...         self._as_parameter_ = number
     ...
     >>> bottles = Bottles(42)
     >>> printf(b"%d bottles of beer\n", bottles)
     42 bottles of beer
     19
     >>>

如果你不想把实例的数据存储到 ‘_as_parameter_’ 属性。可以通过定义 *note
property: 1d8. 函数计算出这个属性。


File: python.info,  Node: 指定必选参数的类型 函数原型,  Next: 返回类型,  Prev: 使用自定义的数据类型调用函数,  Up: ctypes 教程

5.16.16.8 指定必选参数的类型(函数原型)
......................................

可以通过设置 ‘argtypes’ 属性的方法指定从 DLL 中导出函数的必选参数类型。

‘argtypes’ 必须是一个 C 数据类型的序列 (这里的 ‘printf’ 可能不是个好例子
，因为它是变长参数，而且每个参数的类型依赖于格式化字符串，不过尝试这个功
能也很方便):

     >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
     >>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)
     String 'Hi', Int 10, Double 2.200000
     37
     >>>

指定数据类型可以防止不合理的参数传递(就像C函数的函数签名)，并且会自动尝
试将参数转换为需要的类型:

     >>> printf(b"%d %d %d", 1, 2, 3)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     ArgumentError: argument 2: exceptions.TypeError: wrong type
     >>> printf(b"%s %d %f\n", b"X", 2, 3)
     X 2 3.000000
     13
     >>>

如果你想通过自定义类型传递参数给函数，必须实现 ‘from_param()’ 类方法，才
能够将此自定义类型用于 ‘argtypes’ 序列。‘from_param()’ 类方法接受一个
Python 对象作为函数输入，它应该进行类型检查或者其他必要的操作以保证接收
到的对象是合法的，然后返回这个对象，或者它的 ‘_as_parameter_’ 属性，或者
其他你想要传递给 C 函数的参数。这里也一样，返回的结果必须是整型、字符串
、二进制字符串、 *note ctypes: 2b. 类型，或者一个具有 ‘_as_parameter_’ 属
性的对象。


File: python.info,  Node: 返回类型,  Next: 传递指针 或者传递引用,  Prev: 指定必选参数的类型 函数原型,  Up: ctypes 教程

5.16.16.9 返回类型
..................

默认情况下都会假定函数返回C ‘int’ 类型。其他返回类型可以通过设置函数对象
的 ‘restype’ 属性来指定。

这是个更高级的例子，它调用了 ‘strchr’ 函数，这个函数接收一个字符串指针以
及一个字符作为参数，返回另一个字符串指针。

     >>> strchr = libc.strchr
     >>> strchr(b"abcdef", ord("d"))
     8059983
     >>> strchr.restype = c_char_p    # c_char_p is a pointer to a string
     >>> strchr(b"abcdef", ord("d"))
     b'def'
     >>> print(strchr(b"abcdef", ord("x")))
     None
     >>>

如果希望避免上述的 ‘ord("x")’ 调用，可以设置 ‘argtypes’  属性，第二个参
数就会将单字符的 Python 二进制字符对象转换为 C 字符:

     >>> strchr.restype = c_char_p
     >>> strchr.argtypes = [c_char_p, c_char]
     >>> strchr(b"abcdef", b"d")
     'def'
     >>> strchr(b"abcdef", b"def")
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     ArgumentError: argument 2: exceptions.TypeError: one character string expected
     >>> print(strchr(b"abcdef", b"x"))
     None
     >>> strchr(b"abcdef", b"d")
     'def'
     >>>

如果外部函数返回了一个整数，你也可以使用要给可调用的 Python 对象（比如函
数或者类）作为 ‘restype’ 属性的值。将会以 C 函数返回的 `整数' 对象作为参
数调用这个可调用对象，执行后的结果作为最终函数返回值。这在错误返回值校验
和自动抛出异常等方面比较有用。

     >>> GetModuleHandle = windll.kernel32.GetModuleHandleA
     >>> def ValidHandle(value):
     ...     if value == 0:
     ...         raise WinError()
     ...     return value
     ...
     >>>
     >>> GetModuleHandle.restype = ValidHandle
     >>> GetModuleHandle(None)
     486539264
     >>> GetModuleHandle("something silly")
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
       File "<stdin>", line 3, in ValidHandle
     OSError: [Errno 126] The specified module could not be found.
     >>>

‘WinError’ 函数可以调用 Windows 的 ‘FormatMessage()’ API 获取错误码的字
符串说明，然后 `返回' 一个异常。 ‘WinError’ 接收一个可选的错误码作为参数
，如果没有的话，它将调用 *note GetLastError(): 22e5. 获取错误码。

请注意，使用 ‘errcheck’ 属性可以实现更强大的错误检查手段；详情请见参考手
册。


File: python.info,  Node: 传递指针 或者传递引用,  Next: 结构体和联合,  Prev: 返回类型,  Up: ctypes 教程

5.16.16.10 传递指针(或者传递引用)
.................................

有时候 C 函数接口可能由于要往某个地址写入值，或者数据太大不适合作为值传
递，从而希望接收一个 `指针' 作为数据参数类型。这和 `传递参数引用' 类似。

*note ctypes: 2b. 暴露了 *note byref(): 22e8. 函数用于通过引用传递参数，
使用 *note pointer(): 22e9. 函数也能达到同样的效果，只不过 *note
pointer(): 22e9. 需要更多步骤，因为它要先构造一个真实指针对象。所以在
Python 代码本身不需要使用这个指针对象的情况下，使用 *note byref(): 22e8.
效率更高。

     >>> i = c_int()
     >>> f = c_float()
     >>> s = create_string_buffer(b'\000' * 32)
     >>> print(i.value, f.value, repr(s.value))
     0 0.0 b''
     >>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s",
     ...             byref(i), byref(f), s)
     3
     >>> print(i.value, f.value, repr(s.value))
     1 3.1400001049 b'Hello'
     >>>


File: python.info,  Node: 结构体和联合,  Next: 结构体/联合 字段对齐及字节顺序,  Prev: 传递指针 或者传递引用,  Up: ctypes 教程

5.16.16.11 结构体和联合
.......................

结构体和联合必须继承自 *note ctypes: 2b. 模块中的 *note Structure: 22ec.
和 *note Union: 22ed. 。子类必须定义 ‘_fields_’ 属性。 ‘_fields_’ 是一个
二元组列表，二元组中包含 `field name' 和 `field type' 。

type 字段必须是一个 *note ctypes: 2b. 类型，比如 *note c_int: 22c3.，或
者其他 *note ctypes: 2b. 类型: 结构体、联合、数组、指针。

这是一个简单的 POINT 结构体，它包含名称为 `x' 和 `y' 的两个变量，还展示
了如何通过构造函数初始化结构体。

     >>> from ctypes import *
     >>> class POINT(Structure):
     ...     _fields_ = [("x", c_int),
     ...                 ("y", c_int)]
     ...
     >>> point = POINT(10, 20)
     >>> print(point.x, point.y)
     10 20
     >>> point = POINT(y=5)
     >>> print(point.x, point.y)
     0 5
     >>> POINT(1, 2, 3)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: too many initializers
     >>>

当然，你可以构造更复杂的结构体。一个结构体可以通过设置 type 字段包含其他
结构体或者自身。

这是以一个 RECT 结构体，他包含了两个 POINT ，分别叫 `upperleft' 和
`lowerright':

     >>> class RECT(Structure):
     ...     _fields_ = [("upperleft", POINT),
     ...                 ("lowerright", POINT)]
     ...
     >>> rc = RECT(point)
     >>> print(rc.upperleft.x, rc.upperleft.y)
     0 5
     >>> print(rc.lowerright.x, rc.lowerright.y)
     0 0
     >>>

嵌套结构体可以通过几种方式构造初始化:

     >>> r = RECT(POINT(1, 2), POINT(3, 4))
     >>> r = RECT((1, 2), (3, 4))

可以通过 `类' 获取字段 *note descriptor: 1616. ，它能提供很多有用的调试
信息。

     >>> print(POINT.x)
     <Field type=c_long, ofs=0, size=4>
     >>> print(POINT.y)
     <Field type=c_long, ofs=4, size=4>
     >>>
     警告: *note ctypes: 2b. 不支持带位域的结构体、联合以值的方式传给函
     数。这可能在 32 位 x86 平台上可以正常工作，但是对于一般情况，这种行
     为是未定义的。带位域的结构体、联合应该总是通过指针传递给函数。


File: python.info,  Node: 结构体/联合 字段对齐及字节顺序,  Next: 结构体和联合中的位域,  Prev: 结构体和联合,  Up: ctypes 教程

5.16.16.12 结构体/联合 字段对齐及字节顺序
.........................................

默认情况下，结构体和联合的字段与C的字节对齐是一样的。也可以在定义子类的
时候指定类的 ‘_pack_’ 属性来覆盖这种行为。它必须设置为一个正整数，表示字
段的最大对齐字节。这和 MSVC 中的 ‘#pragma pack(n)’ 功能一样。

*note ctypes: 2b. 中的结构体和联合使用的是本地字节序。要使用非本地字节序
，可以使用 *note BigEndianStructure: 22f0, *note LittleEndianStructure:
22f1, ‘BigEndianUnion’, and ‘LittleEndianUnion’ 作为基类。这些类不能包含
指针字段。


File: python.info,  Node: 结构体和联合中的位域,  Next: 数组,  Prev: 结构体/联合 字段对齐及字节顺序,  Up: ctypes 教程

5.16.16.13 结构体和联合中的位域
...............................

结构体和联合中是可以包含位域字段的。位域只能用于整型字段，位长度通过
‘_fields_’ 中的第三个参数指定:

     >>> class Int(Structure):
     ...     _fields_ = [("first_16", c_int, 16),
     ...                 ("second_16", c_int, 16)]
     ...
     >>> print(Int.first_16)
     <Field type=c_long, ofs=0:0, bits=16>
     >>> print(Int.second_16)
     <Field type=c_long, ofs=0:16, bits=16>
     >>>


File: python.info,  Node: 数组,  Next: 指针,  Prev: 结构体和联合中的位域,  Up: ctypes 教程

5.16.16.14 数组
...............

数组是一个序列，包含指定个数元素，且必须类型相同。

创建数组类型的推荐方式是使用一个类型乘以一个正数:

     TenPointsArrayType = POINT * 10

下面是一个构造的数据案例，结构体中包含了4个 POINT 和一些其他东西。

     >>> from ctypes import *
     >>> class POINT(Structure):
     ...     _fields_ = ("x", c_int), ("y", c_int)
     ...
     >>> class MyStruct(Structure):
     ...     _fields_ = [("a", c_int),
     ...                 ("b", c_float),
     ...                 ("point_array", POINT * 4)]
     >>>
     >>> print(len(MyStruct().point_array))
     4
     >>>

和平常一样，通过调用它创建实例:

     arr = TenPointsArrayType()
     for pt in arr:
         print(pt.x, pt.y)

以上代码会打印几行 ‘0 0’ ，因为数组内容被初始化为 0.

也能通过指定正确类型的数据来初始化:

     >>> from ctypes import *
     >>> TenIntegers = c_int * 10
     >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
     >>> print(ii)
     <c_long_Array_10 object at 0x...>
     >>> for i in ii: print(i, end=" ")
     ...
     1 2 3 4 5 6 7 8 9 10
     >>>


File: python.info,  Node: 指针,  Next: 类型强制转换,  Prev: 数组,  Up: ctypes 教程

5.16.16.15 指针
...............

指针可以通过 *note ctypes: 2b. 中的 *note pointer(): 22e9. 函数进行创建:

     >>> from ctypes import *
     >>> i = c_int(42)
     >>> pi = pointer(i)
     >>>

指针实例拥有 *note contents: 22f8. 属性，它存储了指针指向的真实对象，如
上面的 ‘i’ 对象:

     >>> pi.contents
     c_long(42)
     >>>

注意 *note ctypes: 2b. 并没有 OOR （返回原始对象）, 每次访问这个属性时都
会构造返回一个新的相同对象:

     >>> pi.contents is i
     False
     >>> pi.contents is pi.contents
     False
     >>>

将这个指针的 contents 属性赋值为另一个 *note c_int: 22c3. 实例将会导致该
指针指向该实例的内存地址:

     >>> i = c_int(99)
     >>> pi.contents = i
     >>> pi.contents
     c_long(99)
     >>>

指针对象也可以通过整数下标进行访问:

     >>> pi[0]
     99
     >>>

通过整数下标赋值可以改变内容。

     >>> print(i)
     c_long(99)
     >>> pi[0] = 22
     >>> print(i)
     c_long(22)
     >>>

使用0以外的索引也是合法的，但是你必须确保这么做的后果，就像 C 语言中: 你
可以访问或者修改任意内存内容。通常只会在函数接收指针是才会使用这种特性，
而且你 `知道' 这个指针指向的是一个数组而不是单个值。

内部细节, *note pointer(): 22e9. 函数不只是创建了一个指针实例，它首先创
建了一个指针 `类型' 。这是通过调用 *note POINTER(): 22f9. 函数实现的，它
接收 *note ctypes: 2b. 类型为参数，返回一个新的类型:

     >>> PI = POINTER(c_int)
     >>> PI
     <class 'ctypes.LP_c_long'>
     >>> PI(42)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: expected c_long instead of int
     >>> PI(c_int(42))
     <ctypes.LP_c_long object at 0x...>
     >>>

无参调用指针类型可以创建一个 ‘NULL’ 指针。 ‘NULL’ 指针的布尔值是 ‘False’

     >>> null_ptr = POINTER(c_int)()
     >>> print(bool(null_ptr))
     False
     >>>

解引用指针的时候， *note ctypes: 2b. 会帮你检测是否指针为 ‘NULL’ (但是解
引用无效的 非 ‘NULL’ 指针仍会导致 Python 崩溃):

     >>> null_ptr[0]
     Traceback (most recent call last):
         ....
     ValueError: NULL pointer access
     >>>

     >>> null_ptr[0] = 1234
     Traceback (most recent call last):
         ....
     ValueError: NULL pointer access
     >>>


File: python.info,  Node: 类型强制转换,  Next: 不完整类型,  Prev: 指针,  Up: ctypes 教程

5.16.16.16 类型强制转换
.......................

通常情况下, ctypes 具有严格的类型检查。这代表着, 如果在函数 ‘argtypes’ 中
或者结构体定义成员中有 ‘POINTER(c_int)’ 类型，只有相同类型的实例才会被接
受。 也有一些例外。比如，你可以传递兼容的数组实例给指针类型。所以，对于
‘POINTER(c_int)’ ，ctypes 也可以接受 c_int 类型的数组:

     >>> class Bar(Structure):
     ...     _fields_ = [("count", c_int), ("values", POINTER(c_int))]
     ...
     >>> bar = Bar()
     >>> bar.values = (c_int * 3)(1, 2, 3)
     >>> bar.count = 3
     >>> for i in range(bar.count):
     ...     print(bar.values[i])
     ...
     1
     2
     3
     >>>

另外，如果一个函数 ‘argtypes’ 列表中的参数显式的定义为指针类型(如
‘POINTER(c_int)’ )，指针所指向的 类型 (这个例子中是 ‘c_int’ )也可以传递
给函数。ctypes 会自动调用对应的 *note byref(): 22e8. 转换。

可以给指针内容赋值为 None 将其设置为 ‘Null’

     >>> bar.values = None
     >>>

有时候你拥有一个不完整的类型。在 C 中，你可以将一个类型强制转换为另一个
。 *note ctypes: 2b.  中的 a *note cast(): 1023. 函数提供了相同的功能。
上面的结构体 ‘Bar’ 的 ‘value’ 字段接收 ‘POINTER(c_int)’ 指针或者 *note
c_int: 22c3.  数组，但是不能接受其他类型的实例:

     >>> bar.values = (c_byte * 4)()
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
     >>>

这种情况下, 需要手动使用 *note cast(): 1023. 函数。

*note cast(): 1023. 函数可以将一个指针实例强制转换为另一种 ctypes 类型。
*note cast(): 1023.  接收两个参数，一个 ctypes 指针对象或者可以被转换为
指针的其他类型对象，和一个 ctypes 指针类型。返回第二个类型的一个实例，该
返回实例和第一个参数指向同一片内存空间:

     >>> a = (c_byte * 4)()
     >>> cast(a, POINTER(c_int))
     <ctypes.LP_c_long object at ...>
     >>>

所以 *note cast(): 1023. 可以用来给结构体 ‘Bar’ 的 ‘values’ 字段赋值:

     >>> bar = Bar()
     >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
     >>> print(bar.values[0])
     0
     >>>


File: python.info,  Node: 不完整类型,  Next: 回调函数,  Prev: 类型强制转换,  Up: ctypes 教程

5.16.16.17 不完整类型
.....................

`不完整类型' 即还没有定义成员的结构体、联合或者数组。在 C 中，它们通常用
于前置声明，然后在后面定义:

     struct cell; /* forward declaration */

     struct cell {
         char *name;
         struct cell *next;
     };

直接翻译成 ctypes 的代码如下，但是这行不通:

     >>> class cell(Structure):
     ...     _fields_ = [("name", c_char_p),
     ...                 ("next", POINTER(cell))]
     ...
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
       File "<stdin>", line 2, in cell
     NameError: name 'cell' is not defined
     >>>

因为新的 ‘cell 类’ 在 class 语句结束之前还没有完成定义。在 *note ctypes:
2b. 中，我们可以先定义 ‘cell’ 类，在 class 语句结束之后再设置 ‘_fields_’
属性:

     >>> from ctypes import *
     >>> class cell(Structure):
     ...     pass
     ...
     >>> cell._fields_ = [("name", c_char_p),
     ...                  ("next", POINTER(cell))]
     >>>

让我们试试。我们定义两个 ‘cell’ 实例，让它们互相指向对方，然后通过指针链
式访问几次:

     >>> c1 = cell()
     >>> c1.name = b"foo"
     >>> c2 = cell()
     >>> c2.name = b"bar"
     >>> c1.next = pointer(c2)
     >>> c2.next = pointer(c1)
     >>> p = c1
     >>> for i in range(8):
     ...     print(p.name, end=" ")
     ...     p = p.next[0]
     ...
     foo bar foo bar foo bar foo bar
     >>>


File: python.info,  Node: 回调函数,  Next: 访问 dll 中导出的值,  Prev: 不完整类型,  Up: ctypes 教程

5.16.16.18 回调函数
...................

*note ctypes: 2b. 允许创建一个指向 Python 可调用对象的 C 函数。它们有时
候被称为 `回调函数' 。

首先，你必须为回调函数创建一个类，这个类知道调用约定，包括返回值类型以及
函数接收的参数类型及个数。

*note CFUNCTYPE(): 2300. 工厂函数使用 ‘cdecl’ 调用约定创建回调函数类型。
在 Windows 上， *note WINFUNCTYPE(): 2301. 工厂函数使用 ‘stdcall’ 调用约
定为回调函数创建类型。

这些工厂函数都是用返回值类型作为第一个参数，回掉函数的参数类型作为剩余参
数。

这里展示一个使用 C 标准库函数 ‘qsort()’  的例子，它使用一个回掉函数对数
据进行排序。 ‘qsort()’ 将用来给整数数组排序:

     >>> IntArray5 = c_int * 5
     >>> ia = IntArray5(5, 1, 7, 33, 99)
     >>> qsort = libc.qsort
     >>> qsort.restype = None
     >>>

‘qsort()’ 必须接收的参数，一个指向待排序数据的指针，元素个数，每个元素的
大小，以及一个指向排序函数的指针，即回调函数。然后回调函数接收两个元素的
指针，如果第一个元素小于第二个，则返回一个负整数，如果相等则返回0，否则
返回一个正整数。

所以，我们的回调函数要接收两个整数指针，返回一个整数。首先我们创建回调函
数的 ‘类型’

     >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
     >>>

首先，这是一个简单的回调，它会显示传入的值:

     >>> def py_cmp_func(a, b):
     ...     print("py_cmp_func", a[0], b[0])
     ...     return 0
     ...
     >>> cmp_func = CMPFUNC(py_cmp_func)
     >>>

结果:

     >>> qsort(ia, len(ia), sizeof(c_int), cmp_func)
     py_cmp_func 5 1
     py_cmp_func 33 99
     py_cmp_func 7 33
     py_cmp_func 5 7
     py_cmp_func 1 7
     >>>

现在我们可以比较两个元素并返回有用的结果了:

     >>> def py_cmp_func(a, b):
     ...     print("py_cmp_func", a[0], b[0])
     ...     return a[0] - b[0]
     ...
     >>>
     >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func))
     py_cmp_func 5 1
     py_cmp_func 33 99
     py_cmp_func 7 33
     py_cmp_func 1 7
     py_cmp_func 5 7
     >>>

我们可以轻易地验证，现在数组是有序的了:

     >>> for i in ia: print(i, end=" ")
     ...
     1 5 7 33 99
     >>>

这些工厂函数可以当作装饰器工厂，所以可以这样写:

     >>> @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
     ... def py_cmp_func(a, b):
     ...     print("py_cmp_func", a[0], b[0])
     ...     return a[0] - b[0]
     ...
     >>> qsort(ia, len(ia), sizeof(c_int), py_cmp_func)
     py_cmp_func 5 1
     py_cmp_func 33 99
     py_cmp_func 7 33
     py_cmp_func 1 7
     py_cmp_func 5 7
     >>>

     注解: 请确保你维持 *note CFUNCTYPE(): 2300. 对象的引用与它们在 C 代
     码中的使用期一样长。 *note ctypes: 2b. 不会确保这一点，而如果你不这
     样做，它们可能会被垃圾回收，导致你的程序在执行回调函数时发生崩溃。

     注意，如果回调函数在Python之外的另外一个线程使用(比如，外部代码调用
     这个回调函数)， ctypes 会在每一次调用上创建一个虚拟 Python 线程。这
     个行为在大多数情况下是合理的，但也意味着如果有数据使用 *note
     threading.local: 2302. 方式存储，将无法访问，就算它们是在同一个 C 线
     程中调用的 。


File: python.info,  Node: 访问 dll 中导出的值,  Next: 意外,  Prev: 回调函数,  Up: ctypes 教程

5.16.16.19 访问 dll 中导出的值
..............................

一些动态链接库不仅仅导出函数，也会导出变量。一个例子就是 Python 库本身的
*note Py_OptimizeFlag: 2305. ，根据启动选项 *note -O: 694. 、 *note -OO:
695. 的不同，它是值可能为 0、1、2 的整型。

*note ctypes: 2b. 可以通过 ‘in_dll()’ 类方法访问这类变量 。 `pythonapi'
是用于访问 Python C 接口的预定义符号:

     >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
     >>> print(opt_flag)
     c_long(0)
     >>>

如果解释器使用 *note -O: 694. 选项启动，这个例子会打印 ‘c_long(1)’ ， 如
果使用 *note -OO: 695. 启动，则会打印 ‘c_long(2)’ 。

一个扩展例子, 同时也展示了使用指针访问 Python 导出的 *note
PyImport_FrozenModules: 2306. 指针对象。

对文档中这个值的解释说明

     该指针被初始化为指向 ‘struct _frozen’ 数组，以 ‘NULL’ 或者 0 作为结
     束标记。当一个冻结模块被导入，首先要在这个表中搜索。第三方库可以以
     此来提供动态创建的冻结模块集合。

这足以证明修改这个指针是很有用的。为了让实例大小不至于太长，这里只展示如
何使用 *note ctypes: 2b. 读取这个表:

     >>> from ctypes import *
     >>>
     >>> class struct_frozen(Structure):
     ...     _fields_ = [("name", c_char_p),
     ...                 ("code", POINTER(c_ubyte)),
     ...                 ("size", c_int)]
     ...
     >>>

我们定义了 ‘struct _frozen’  数据类型，接着就可以获取这张表的指针了:

     >>> FrozenTable = POINTER(struct_frozen)
     >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
     >>>

由于 ‘table’ 是指向 ‘struct_frozen’ 数组的 ‘指针’ ，我们可以遍历它，只不
过需要自己判断循环是否结束，因为指针本身并不包含长度。它早晚会因为访问到
野指针或者什么的把自己搞崩溃，所以我们最好在遇到 ‘NULL’ 后就让它退出循环
:

     >>> for item in table:
     ...     if item.name is None:
     ...         break
     ...     print(item.name.decode("ascii"), item.size)
     ...
     _frozen_importlib 31764
     _frozen_importlib_external 41499
     __hello__ 161
     __phello__ -161
     __phello__.spam 161
     >>>

Python 的冻结模块和冻结包(由负 ‘size’ 成员表示)并不是广为人知的事情，它
们仅仅用于实验。例如，可以使用 ‘import __hello__’ 尝试一下这个功能。


File: python.info,  Node: 意外,  Next: 变长数据类型,  Prev: 访问 dll 中导出的值,  Up: ctypes 教程

5.16.16.20 意外
...............

*note ctypes: 2b. 也有自己的边界，有时候会发生一些意想不到的事情。

比如下面的例子:

     >>> from ctypes import *
     >>> class POINT(Structure):
     ...     _fields_ = ("x", c_int), ("y", c_int)
     ...
     >>> class RECT(Structure):
     ...     _fields_ = ("a", POINT), ("b", POINT)
     ...
     >>> p1 = POINT(1, 2)
     >>> p2 = POINT(3, 4)
     >>> rc = RECT(p1, p2)
     >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
     1 2 3 4
     >>> # now swap the two points
     >>> rc.a, rc.b = rc.b, rc.a
     >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
     3 4 3 4
     >>>

嗯。我们预想应该打印 ‘3 4 1 2’ 。但是为什么呢? 这是 ‘rc.a, rc.b = rc.b,
rc.a’ 这行代码展开后的步骤:

     >>> temp0, temp1 = rc.b, rc.a
     >>> rc.a = temp0
     >>> rc.b = temp1
     >>>

注意 ‘temp0’ 和 ‘temp1’ 对象始终引用了对象 ‘rc’ 的内容。然后执行 ‘rc.a =
temp0’ 会把 ‘temp0’ 的内容拷贝到 ‘rc’ 的空间。这也改变了 ‘temp1’ 的内容
。最终导致赋值语句 ‘rc.b = temp1’ 没有产生预想的效果。

记住，访问被包含在结构体、联合、数组中的对象并不会将其 `复制' 出来，而是
得到了一个代理对象，它是对根对象的内部内容进行了一层包装。

另一个和预期可能有偏差的例子是这样:

     >>> s = c_char_p()
     >>> s.value = b"abc def ghi"
     >>> s.value
     b'abc def ghi'
     >>> s.value is s.value
     False
     >>>

     注解: 使用 *note c_char_p: 22da.  实例化的对象只能将其值设置为
     bytes 或者整数。

为什么这里打印了 ‘False’ ？ ctypes 实例是一些内存块加上一些用于访问这些
内存块的 *note descriptor: 1616. 组成。将 Python 对象存储在内存块并不会
存储对象本身，而是存储了对象的 ‘内容’ 。每次访问对象的内容都会构造一个新
的 Python 对象。


File: python.info,  Node: 变长数据类型,  Prev: 意外,  Up: ctypes 教程

5.16.16.21 变长数据类型
.......................

*note ctypes: 2b. 对变长数组和结构体提供了一些支持 。

The *note resize(): 230b. function can be used to resize the memory
buffer of an existing ctypes object.  The function takes the object as
first argument, and the requested size in bytes as the second argument.
The memory block cannot be made smaller than the natural memory block
specified by the objects type, a *note ValueError: 1fc. is raised if
this is tried:

     >>> short_array = (c_short * 4)()
     >>> print(sizeof(short_array))
     8
     >>> resize(short_array, 4)
     Traceback (most recent call last):
         ...
     ValueError: minimum size is 8
     >>> resize(short_array, 32)
     >>> sizeof(short_array)
     32
     >>> sizeof(type(short_array))
     8
     >>>

这非常好，但是要怎么访问数组中额外的元素呢？因为数组类型已经定义包含4个
元素，women访问新增元素会产生以下错误:

     >>> short_array[:]
     [0, 0, 0, 0]
     >>> short_array[7]
     Traceback (most recent call last):
         ...
     IndexError: invalid index
     >>>

使用 *note ctypes: 2b. 访问变长数据类型的一个可行方法是利用 Python 的动
态特性，根据具体情况，在知道这个数据的大小后，(重新)指定这个数据的类型。


File: python.info,  Node: ctypes 参考手册,  Prev: ctypes 教程,  Up: ctypes --- Python 的外部函数库

5.16.16.22 ctypes 参考手册
..........................

* Menu:

* 寻找动态链接库::
* 加载动态链接库::
* 外部函数::
* 函数原型::
* 工具函数::
* 数据类型: 数据类型<2>.
* 基础数据类型: 基础数据类型<2>.
* 结构化数据类型::
* 数组与指针::


File: python.info,  Node: 寻找动态链接库,  Next: 加载动态链接库,  Up: ctypes 参考手册

5.16.16.23 寻找动态链接库
.........................

在编译型语言中，动态链接库会在编译、链接或者程序运行时访问。

The purpose of the ‘find_library()’ function is to locate a library in a
way similar to what the compiler or runtime loader does (on platforms
with several versions of a shared library the most recent should be
loaded), while the ctypes library loaders act like when a program is
run, and call the runtime loader directly.

‘ctypes.util’ 模块提供了一个函数，可以帮助确定需要加载的库。

 -- 数据: ctypes.util.find_library (name)

     尝试寻找一个库然后返回其路径名， `name' 是库名称, 且去除了 `lib' 等
     前缀和 ‘.so’ 、 ‘.dylib’ 、版本号等后缀(这是 posix 连接器 ‘-l’ 选项
     使用的格式)。如果没有找到对应的库，则返回 ‘None’ 。

确切的功能取决于系统。

在 Linux 上， ‘find_library()’ 会尝试运行外部程序(‘/sbin/ldconfig’,
‘gcc’, ‘objdump’ 以及 ‘ld’) 来寻找库文件。返回库文件的文件名。

在 3.6 版更改: 在Linux 上，如果其他方式找不到的话，会使用环境变量
‘LD_LIBRARY_PATH’ 搜索动态链接库。

这是一些例子:

     >>> from ctypes.util import find_library
     >>> find_library("m")
     'libm.so.6'
     >>> find_library("c")
     'libc.so.6'
     >>> find_library("bz2")
     'libbz2.so.1.0'
     >>>

在 OS X 上， ‘find_library()’ 会尝试几种预定义的命名方案和路径来查找库，
如果成功，则返回完整的路径名:

     >>> from ctypes.util import find_library
     >>> find_library("c")
     '/usr/lib/libc.dylib'
     >>> find_library("m")
     '/usr/lib/libm.dylib'
     >>> find_library("bz2")
     '/usr/lib/libbz2.dylib'
     >>> find_library("AGL")
     '/System/Library/Frameworks/AGL.framework/AGL'
     >>>

在 Windows 上， ‘find_library()’ 在系统路径中搜索，然后返回全路径，但是
如果没有预定义的命名方案， ‘find_library("c")’ 调用会返回 ‘None’

使用 *note ctypes: 2b. 包装动态链接库，更好的方式 `可能' 是在开发的时候
就确定名称，然后硬编码到包装模块中去，而不是在运行时使用
‘find_library()’ 寻找库。


File: python.info,  Node: 加载动态链接库,  Next: 外部函数,  Prev: 寻找动态链接库,  Up: ctypes 参考手册

5.16.16.24 加载动态链接库
.........................

有很多方式可以将动态链接库加载到 Python 进程。其中之一是实例化以下类的其
中一个:

 -- 类: ctypes.CDLL (name, mode=DEFAULT_MODE, handle=None,
          use_errno=False, use_last_error=False, winmode=0)

     此类的实例即已加载的动态链接库。库中的函数使用标准 C 调用约定，并假
     定返回 ‘int’ 。

     在 Windows 上创建 *note CDLL: 1c2. 实例可能会失败，即使 DLL 名称确
     实存在。 当某个被加载 DLL 所依赖的 DLL 未找到时，将引发 *note
     OSError: 1d4. 错误并附带消息 `"[WinError 126] The specified module
     could not be found".' 此错误消息不包含缺失 DLL 的名称，因为 Windows
     API 并不会返回此类信息，这使得此错误难以诊断。 要解决此错误并确定是
     哪一个 DLL 未找到，你需要找出所依赖的 DLL 列表并使用 Windows 调试与
     跟踪工具确定是哪一个未找到。

参见
....

Microsoft DUMPBIN 工具(1) – 一个用于查找 DLL 依赖的工具。

 -- 类: ctypes.OleDLL (name, mode=DEFAULT_MODE, handle=None,
          use_errno=False, use_last_error=False, winmode=0)

     仅 Windows : 此类的实例即加载好的动态链接库，其中的函数使用
     ‘stdcall’ 调用约定，并且假定返回 windows 指定的 *note HRESULT:
     2313. 返回码。 *note HRESULT: 2313. 的值包含的信息说明函数调用成功
     还是失败，以及额外错误码。 如果返回值表示失败，会自动抛出 *note
     OSError: 1d4. 异常。

     在 3.3 版更改: 以前是引发 *note WindowsError: 99c.。

 -- 类: ctypes.WinDLL (name, mode=DEFAULT_MODE, handle=None,
          use_errno=False, use_last_error=False, winmode=0)

     仅 Windows: 此类的实例即加载好的动态链接库，其中的函数使用
     ‘stdcall’ 调用约定，并假定默认返回 ‘int’ 。

     在 Windows CE 上，只能使用 stdcall 调用约定，为了方便， *note
     WinDLL: 2314. 和 *note OleDLL: 2312. 在这个平台上都使用标准调用约定
     。

调用动态库导出的函数之前，Python会释放 *note global interpreter lock:
50e. ，并在调用后重新获取。

 -- 类: ctypes.PyDLL (name, mode=DEFAULT_MODE, handle=None)

     这个类实例的行为与 *note CDLL: 1c2. 类似，只不过 `不会' 在调用函数
     的时候释放 GIL 锁，且调用结束后会检查 Python 错误码。 如果错误码被
     设置，会抛出一个 Python 异常。

     所以，它只在直接调用 Python C 接口函数的时候有用。

通过使用至少一个参数（共享库的路径名）调用它们，可以实例化所有这些类。也
可以传入一个已加载的动态链接库作为 ‘handler’ 参数，其他情况会调用系统底
层的 ‘dlopen’ 或 ‘LoadLibrary’ 函数将库加载到进程，并获取其句柄。

`mode' 可以指定库加载方式。详情请参见 ‘dlopen(3)’ 手册页。 在 Windows 上
， 会忽略 `mode' ，在 posix 系统上， 总是会加上 RTLD_NOW ，且无法配置。

`use_errno' 参数如果设置为 true，可以启用ctypes的机制，通过一种安全的方
法获取系统的 *note errno: 7c. 错误码。 *note ctypes: 2b. 维护了一个线程
局部变量，它是系统 *note errno: 7c. 的一份拷贝；如果调用了使用
‘use_errno=True’ 创建的外部函数， *note errno: 7c. 的值会与 ctypes 自己
拷贝的那一份进行交换，函数执行完后立即再交换一次。

The function *note ctypes.get_errno(): 2316. returns the value of the
ctypes private copy, and the function *note ctypes.set_errno(): 2317.
changes the ctypes private copy to a new value and returns the former
value.

`use_last_error' 参数如果设置为 true，可以在 Windows 上启用相同的策略，
它是通过 Windows API 函数 *note GetLastError(): 22e5.  和
‘SetLastError()’ 管理的。 *note ctypes.get_last_error(): 2318. 和 *note
ctypes.set_last_error(): 2319. 可用于获取和设置 ctypes 自己维护的
windows 错误码拷贝。

`winmode' 参数用于在 Windows 平台上指定库的加载方式( 因为 `mode' 会被忽
略)。他接受任何与 Win32 API 的 ‘LoadLibraryEx’ 的标志兼容的值作为参数。
省略时，默认设置使用最安全的DLL加载的标志，以避免DLL劫持等问题。传入 DLL
的全路径是保证正确加载库及其依赖最安全的方法。

在 3.8 版更改: 增加了 `winmode' 参数。

 -- 数据: ctypes.RTLD_GLOBAL

     用于 `mode' 参数的标识值。在此标识不可用的系统上，它被定义为整数0。

 -- 数据: ctypes.RTLD_LOCAL

     Flag to use as `mode' parameter.  On platforms where this is not
     available, it is the same as `RTLD_GLOBAL'.

 -- 数据: ctypes.DEFAULT_MODE

     加载动态链接库的默认模式。在 OSX 10.3 上，它是 `RTLD_GLOBAL' ，其余
     系统上是 `RTLD_LOCAL' 。

这些类的实例没有共用方法。动态链接库的导出函数可以通过属性或者数组下标的
方式访问。注意，通过属性的方式访问会缓存这个函数，因而每次访问它时返回的
都是同一个对象。另一方面，通过数组下标访问，每次都会返回一个新的对象:

     >>> from ctypes import CDLL
     >>> libc = CDLL("libc.so.6")  # On Linux
     >>> libc.time == libc.time
     True
     >>> libc['time'] == libc['time']
     False

还有下面这些属性可用，他们的名称以下划线开头，以避免和导出函数重名:

 -- 属性: PyDLL._handle

     用于访问库的系统句柄。

 -- 属性: PyDLL._name

     传入构造函数的库名称。

共享库也可以通用使用一个预制对象来加载，这种对象是 *note LibraryLoader:
231c. 类的实例，具体做法或是通过调用 ‘LoadLibrary()’ 方法，或是通过将库
作为加载实例的属性来提取。

 -- 类: ctypes.LibraryLoader (dlltype)

     加载共享库的类。 `dlltype' 应当为 *note CDLL: 1c2, *note PyDLL:
     2315, *note WinDLL: 2314. 或 *note OleDLL: 2312. 类型之一。

     *note __getattr__(): 323. 具有特殊的行为：它允许通过将一个共享库作
     为库加载器实例的属性进行访问来加载它。 加载结果将被缓存，因此重复的
     属性访问每次都会返回相同的库。

      -- 方法: LoadLibrary (name)

          加载一个共享库到进程中并将其返回。 此方法总是返回一个新的库实
          例。

可用的预制库加载器有如下这些:

 -- 数据: ctypes.cdll

     创建 *note CDLL: 1c2. 实例。

 -- 数据: ctypes.windll

     仅Windows中: 创建 *note WinDLL: 2314. 实例.

 -- 数据: ctypes.oledll

     仅Windows中: 创建 *note OleDLL: 2312. 实例。

 -- 数据: ctypes.pydll

     创建 *note PyDLL: 2315. 实例。

要直接访问 C Python api，可以使用一个现成的 Python 共享库对象:

 -- 数据: ctypes.pythonapi

     一个 *note PyDLL: 2315. 的实例，它将 Python C API 函数作为属性公开
     。 请注意所有这些函数都应返回 C ‘int’，当然这也不是绝对的，因此你必
     须分配正确的 ‘restype’ 属性以使用这些函数。

引发一个 *note 审计事件: ea1. ‘ctypes.dlopen’，附带参数 ‘name’。

引发一个审计事件 ‘ctypes.dlsym’，附带参数 ‘library’, ‘name’。

引发一个审计事件 ‘ctypes.dlsym/handle’，附带参数 ‘handle’, ‘name’。

   ---------- Footnotes ----------

   (1) https://docs.microsoft.com/cpp/build/reference/dependents


File: python.info,  Node: 外部函数,  Next: 函数原型,  Prev: 加载动态链接库,  Up: ctypes 参考手册

5.16.16.25 外部函数
...................

正如之前小节的说明，外部函数可作为被加载共享库的属性来访问。 用此方式创
建的函数对象默认接受任意数量的参数，接受任意 ctypes 数据实例作为参数，并
且返回库加载器所指定的默认结果类型。 它们是一个私有类的实例:

 -- 类: ctypes._FuncPtr

     C 可调用外部函数的基类。

     外部函数的实例也是兼容 C 的数据类型；它们代表 C 函数指针。

     此行为可通过对外部函数对象的特殊属性赋值来自定义。

      -- 属性: restype

          赋值为一个 ctypes 类型来指定外部函数的结果类型。 使用 ‘None’ 表
          示 ‘void’，即不返回任何结果的函数。

          赋值为一个不为 ctypes 类型的可调用 Python 对象也是可以的，在此
          情况下函数应返回 C ‘int’，该可调用对象将附带此整数被调用，以允
          许进一步的处理或错误检测。 这种用法已被弃用，为了更灵活的后续
          处理或错误检测请使用一个 ctypes 数据类型作为 *note restype:
          2321. 并将 *note errcheck: 2322. 属性赋值为一个可调用对象。

      -- 属性: argtypes

          赋值为一个 ctypes 类型的元组来指定函数所接受的参数类型。 使用
          ‘stdcall’ 调用规范的函数只能附带与此元组长度相同数量的参数进行
          调用；使用 C 调用规范的函数还可接受额外的未指明参数。

          当外部函数被调用时，每个实际参数都会被传给 *note argtypes:
          2323. 元组中条目的 ‘from_param()’ 类方法，此方法允许将实际参数
          适配为此外部函数所接受的对象。 例如，*note argtypes: 2323. 元
          组中的 *note c_char_p: 22da. 条目将使用 ctypes 约定规则把作为
          参数传入的字符串转换为字节串对象。

          新增：现在可以将不是 ctypes 类型的条目放入 argtypes，但每个条
          目都必须具有 ‘from_param()’ 方法用于返回可作为参数的值（整数、
          字符串、ctypes 实例）。 这样就允许定义可将自定义对象适配为函数
          形参的适配器。

      -- 属性: errcheck

          将一个 Python 函数或其他可调用对象赋值给此属性。 该可调用对象
          将附带三个及以上的参数被调用。

           -- 函数: callable (result, func, arguments)

               `result' 是外部函数返回的结果，由 ‘restype’ 属性指明。

               `func' 是外部函数对象本身，这样就允许重新使用相同的可调用
               对象来对多个函数进行检查或后续处理。

               `arguments' 是一个包含最初传递给函数调用的形参的元组，这
               样就允许对所用参数的行为进行特别处理。

          此函数所返回的对象将会由外部函数调用返回，但它还可以在外部函数
          调用失败时检查结果并引发异常。

 -- 例外: ctypes.ArgumentError

     此异常会在外部函数无法对某个传入参数执行转换时被引发。

引发一个审计事件 ‘ctypes.seh_exception’ 并附带参数 ‘code’。

引发一个审计事件 ‘ctypes.call_function’，附带参数 ‘func_pointer’,
‘arguments’。


File: python.info,  Node: 函数原型,  Next: 工具函数,  Prev: 外部函数,  Up: ctypes 参考手册

5.16.16.26 函数原型
...................

外部函数也可通过实例化函数原型来创建。 函数原型类似于 C 中的函数原型；它
们在不定义具体实现的情况下描述了一个函数（返回类型、参数类型、调用约定）
。 工厂函数必须使用函数所需要的结果类型和参数类型来调用，并可被用作装饰
器工厂函数，在此情况下可以通过 ‘@wrapper’ 语法应用于函数。 请参阅 *note
回调函数: 22ff. 了解有关示例。

 -- 函数: ctypes.CFUNCTYPE (restype, *argtypes, use_errno=False,
          use_last_error=False)

     返回的函数原型会创建使用标准 C 调用约定的函数。 该函数在调用过程中
     将释放 GIL。 如果 `use_errno' 设为真值，则在调用之前和之后系统
     *note errno: 7c. 变量的 ctypes 私有副本会与真正的 *note errno: 7c.
     值进行交换；`use_last_error' 会为 Windows 错误码执行同样的操作。

 -- 函数: ctypes.WINFUNCTYPE (restype, *argtypes, use_errno=False,
          use_last_error=False)

     仅限 Windows only：返回的函数原型会创建使用 ‘stdcall’ 调用约定的函
     数，但在 Windows CE 上 *note WINFUNCTYPE(): 2301. 则会与 *note
     CFUNCTYPE(): 2300. 相同。 该函数在调用过程中将释放 GIL。
     `use_errno' 和 `use_last_error' 具有与前面相同的含义。

 -- 函数: ctypes.PYFUNCTYPE (restype, *argtypes)

     返回的函数原型会创建使用 Python 调用约定的函数。 该函数在调用过程中
     将 `不会' 释放 GIL。

这些工厂函数所创建的函数原型可通过不同的方式来实例化，具体取决于调用中的
类型与数量:

      -- 函数: prototype (address)

          在指定地址上返回一个外部函数，地址值必须为整数。

      -- 函数: prototype (callable)

          基于 Python `callable' 创建一个 C 可调用函数（回调函数）。

      -- 函数: prototype (func_spec[, paramflags])

          返回由一个共享库导出的外部函数。 `func_spec' 必须为一个 2 元组
          ‘(name_or_ordinal, library)’。 第一项是字符串形式的所导出函数
          名称，或小整数形式的所导出函数序号。 第二项是该共享库实例。

      -- 函数: prototype (vtbl_index, name[, paramflags[, iid]])

          返回将调用一个 COM 方法的外部函数。 `vtbl_index' 虚拟函数表中
          的索引。 `name' 是 COM 方法的名称。 `iid' 是可选的指向接口标识
          符的指针，它被用于扩展的错误报告。

          COM 方法使用特殊的调用约定：除了在 ‘argtypes’ 元组中指定的形参
          ，它们还要求一个指向 COM 接口的指针作为第一个参数。

     可选的 `paramflags' 形参会创建相比上述特性具有更多功能的外部函数包
     装器。

     `paramflags' 必须为一个与 ‘argtypes’ 长度相同的元组。

     此元组中的每一项都包含有关形参的更多信息，它必须为包含一个、两个或
     更多条目的元组。

     第一项是包含形参指令旗标组合的整数。

          1

               指定函数的一个输入形参。

          2

               输出形参。 外部函数会填入一个值。

          4

               默认为整数零值的输入形参。

     可选的第二项是字符串形式的形参名称。 如果指定此项，则可以使用该形参
     名称来调用外部函数。

     可选的第三项是该形参的默认值。

这个例子演示了如何包装 Windows 的 ‘MessageBoxW’ 函数以使其支持默认形参和
已命名参数。 相应 windows 头文件的 C 声明是这样的:

     WINUSERAPI int WINAPI
     MessageBoxW(
         HWND hWnd,
         LPCWSTR lpText,
         LPCWSTR lpCaption,
         UINT uType);

这是使用 *note ctypes: 2b. 的包装:

     >>> from ctypes import c_int, WINFUNCTYPE, windll
     >>> from ctypes.wintypes import HWND, LPCWSTR, UINT
     >>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT)
     >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", "Hello from ctypes"), (1, "flags", 0)
     >>> MessageBox = prototype(("MessageBoxW", windll.user32), paramflags)

现在 ‘MessageBox’ 外部函数可以通过以下方式来调用:

     >>> MessageBox()
     >>> MessageBox(text="Spam, spam, spam")
     >>> MessageBox(flags=2, text="foo bar")

第二个例子演示了输出形参。 这个 win32 ‘GetWindowRect’ 函数通过将指定窗口
的维度拷贝至调用者必须提供的 ‘RECT’ 结构体来提取这些值。 这是相应的 C 声
明:

     WINUSERAPI BOOL WINAPI
     GetWindowRect(
          HWND hWnd,
          LPRECT lpRect);

这是使用 *note ctypes: 2b. 的包装:

     >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
     >>> from ctypes.wintypes import BOOL, HWND, RECT
     >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
     >>> paramflags = (1, "hwnd"), (2, "lprect")
     >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
     >>>

带有输出形参的函数如果输出形参存在单一值则会自动返回该值，或是当输出形参
存在多个值时返回包含这些值的元组，因此当 GetWindowRect 被调用时现在将返
回一个 RECT 实例。

输出形参可以与 ‘errcheck’ 协议相结合以执行进一步的输出处理与错误检查。
Win32 ‘GetWindowRect’ API 函数返回一个 ‘BOOL’ 来表示成功或失败，因此此函
数可执行错误检查，并在 API 调用失败时引发异常:

     >>> def errcheck(result, func, args):
     ...     if not result:
     ...         raise WinError()
     ...     return args
     ...
     >>> GetWindowRect.errcheck = errcheck
     >>>

如果 ‘errcheck’ 不加更改地返回它所接收的参数元组，则 *note ctypes: 2b. 会
继续对输出形参执行常规处理。 如果你希望返回一个窗口坐标的元组而非 ‘RECT’
实例，你可以从函数中提取这些字段并返回它们，常规处理将不会再执行:

     >>> def errcheck(result, func, args):
     ...     if not result:
     ...         raise WinError()
     ...     rc = args[1]
     ...     return rc.left, rc.top, rc.bottom, rc.right
     ...
     >>> GetWindowRect.errcheck = errcheck
     >>>


File: python.info,  Node: 工具函数,  Next: 数据类型<2>,  Prev: 函数原型,  Up: ctypes 参考手册

5.16.16.27 工具函数
...................

 -- 函数: ctypes.addressof (obj)

     以整数形式返回内存缓冲区地址。 `obj' 必须为一个 ctypes 类型的实例。

     引发一个 *note 审计事件: ea1. ‘ctypes.addressof’，附带参数 ‘obj’。

 -- 函数: ctypes.alignment (obj_or_type)

     返回一个 ctypes 类型的对齐要求。 `obj_or_type' 必须为一个 ctypes 类
     型或实例。

 -- 函数: ctypes.byref (obj[, offset])

     返回指向 `obj' 的轻量指针，该对象必须为一个 ctypes 类型的实例。
     `offset' 默认值为零，且必须为一个将被添加到内部指针值的整数。

     ‘byref(obj, offset)’ 对应于这段 C 代码:

          (((char *)&obj) + offset)

     返回的对象只能被用作外部函数调用形参。 它的行为类似于
     ‘pointer(obj)’，但构造起来要快很多。

 -- 函数: ctypes.cast (obj, type)

     此函数类似于 C 的强制转换运算符。 它返回一个 `type' 的新实例，该实
     例指向与 `obj' 相同的内存块。 `type' 必须为指针类型，而 `obj' 必须
     为可以被作为指针来解读的对象。

 -- 函数: ctypes.create_string_buffer (init_or_size, size=None)

     此函数会创建一个可变的字符缓冲区。 返回的对象是一个 *note c_char:
     22ce. 的 ctypes 数组。

     `init_or_size' 必须是一个指明数组大小的整数，或者是一个将被用来初始
     化数组条目的字节串对象。

     如果将一个字节串对象指定为第一个参数，则将使缓冲区大小比其长度多一
     项以便数组的最后一项为一个 NUL 终结符。 可以传入一个整数作为第二个
     参数以允许在不使用字节串长度的情况下指定数组大小。

     引发一个 *note 审计事件: ea1. ‘ctypes.create_string_buffer’，附带参
     数 ‘init’, ‘size’。

 -- 函数: ctypes.create_unicode_buffer (init_or_size, size=None)

     此函数会创建一个可变的 unicode 字符缓冲区。 返回的对象是一个 *note
     c_wchar: 22cf. 的 ctypes 数组。

     `init_or_size' 必须是一个指明数组大小的整数，或者是一个将被用来初始
     化数组条目的字符串。

     如果将一个字符串指定为第一个参数，则将使缓冲区大小比其长度多一项以
     便数组的最后一项为一个 NUL 终结符。 可以传入一个整数作为第二个参数
     以允许在不使用字符串长度的情况下指定数组大小。

     引发一个 *note 审计事件: ea1. ‘ctypes.create_unicode_buffer’，附带
     参数 ‘init’, ‘size’。

 -- 函数: ctypes.DllCanUnloadNow ()

     仅限 Windows：此函数是一个允许使用 ctypes 实现进程内 COM 服务的钩子
     。 它将由 _ctypes 扩展 dll 所导出的 DllCanUnloadNow 函数来调用。

 -- 函数: ctypes.DllGetClassObject ()

     仅限 Windows：此函数是一个允许使用 ctypes 实现进程内 COM 服务的钩子
     。 它将由 ‘_ctypes’ 扩展 dll 所导出的 DllGetClassObject 函数来调用
     。

 -- 函数: ctypes.util.find_library (name)

     尝试寻找一个库并返回路径名称。 `name' 是库名称并且不带任何前缀如
     ‘lib’ 以及后缀如 ‘.so’，‘.dylib’ 或版本号（形式与 posix 链接器选项
     ‘-l’ 所用的一致）。 如果找不到库，则返回 ‘None’。

     确切的功能取决于系统。

 -- 函数: ctypes.util.find_msvcrt ()

     仅限 Windows：返回 Python 以及扩展模块所使用的 VC 运行时库的文件名
     。 如果无法确定库名称，则返回 ‘None’。

     如果你需要通过调用 ‘free(void *)’ 来释放内存，例如某个扩展模块所分
     配的内存，重要的一点是你应当使用分配内存的库中的函数。

 -- 函数: ctypes.FormatError ([code])

     仅限 Windows：返回错误码 `code' 的文本描述。 如果未指定错误码，则会
     通过调用 the last error code is used by calling the Windows api 函
     数 GetLastError 来获得最新的错误码。

 -- 函数: ctypes.GetLastError ()

     仅限 Windows：返回 Windows 在调用线程中设置的最新错误码。 此函数会
     直接调用 Windows ‘GetLastError()’ 函数，它并不返回错误码的 ctypes 私
     有副本。

 -- 函数: ctypes.get_errno ()

     返回调用线程中系统 *note errno: 7c. 变量的 ctypes 私有副本的当前值
     。

     引发一个 *note 审计事件: ea1. ‘ctypes.get_errno’，不附带任何参数。

 -- 函数: ctypes.get_last_error ()

     仅限 Windows：返回调用线程中系统 ‘LastError’ 变量的 ctypes 私有副本
     的当前值。

     引发一个 *note 审计事件: ea1. ‘ctypes.get_last_error’，不附带任何参
     数。

 -- 函数: ctypes.memmove (dst, src, count)

     与标准 C memmove 库函数相同：将 `count' 个字节从 `src' 拷贝到
     `dst'。 `dst' 和 `src' 必须为整数或可被转换为指针的 ctypes 实例。

 -- 函数: ctypes.memset (dst, c, count)

     与标准 C memset 库函数相同：将位于地址 `dst' 的内存块用 `count' 个
     字节的 `c' 值填充。 `dst' 必须为指定地址的整数或 ctypes 实例。

 -- 函数: ctypes.POINTER (type)

     这个工厂函数创建并返回一个新的 ctypes 指针类型。 指针类型会被缓存并
     在内部重用，因此重复调用此函数耗费不大。 `type' 必须为 ctypes 类型
     。

 -- 函数: ctypes.pointer (obj)

     此函数会创建一个新的指向 `obj' 的指针实例。 返回的对象类型为
     ‘POINTER(type(obj))’。

     注意：如果你只是想向外部函数调用传递一个对象指针，你应当使用更为快
     速的 ‘byref(obj)’。

 -- 函数: ctypes.resize (obj, size)

     此函数可改变 `obj' 的内部内存缓冲区大小，其参数必须为 ctypes 类型的
     实例。 没有可能将缓冲区设为小于对象类型的本机大小值，该值由
     ‘sizeof(type(obj))’ 给出，但将缓冲区加大则是可能的。

 -- 函数: ctypes.set_errno (value)

     设置调用线程中系统 *note errno: 7c. 变量的 ctypes 私有副本的当前值
     为 `value' 并返回原来的值。

     引发一个 *note 审计事件: ea1. ‘ctypes.set_errno’ 附带参数 ‘errno’。

 -- 函数: ctypes.set_last_error (value)

     仅限 Windows：设置调用线程中系统 ‘LastError’ 变量的 ctypes 私有副本
     的当前值为 `value' 并返回原来的值。

     引发一个 *note 审计事件: ea1. ‘ctypes.set_last_error’，附带参数
     ‘error’。

 -- 函数: ctypes.sizeof (obj_or_type)

     返回 ctypes 类型或实例的内存缓冲区以字节表示的大小。 其功能与 C
     ‘sizeof’ 运算符相同。

 -- 函数: ctypes.string_at (address, size=-1)

     此函数返回从内存地址 `address' 开始的以字节串表示的 C 字符串。 如果
     指定了 size，则将其用作长度，否则将假定字符串以零值结尾。

     引发一个 *note 审计事件: ea1. ‘ctypes.string_at’，附带参数
     ‘address’, ‘size’。

 -- 函数: ctypes.WinError (code=None, descr=None)

     仅限 Windows：此函数可能是 ctypes 中名字起得最差的函数。 它会创建一
     个 OSError 的实例。 如果未指定 `code'，则会调用 ‘GetLastError’ 来确
     定错误码。 如果未指定 `descr'，则会调用 *note FormatError(): 232f.
     来获取错误的文本描述。

     在 3.3 版更改: 以前是会创建一个 *note WindowsError: 99c. 的实例。

 -- 函数: ctypes.wstring_at (address, size=-1)

     此函数返回从内存地址 `address' 开始的以字符串表示的宽字节字符串。 如
     果指定了 `size'，则将其用作字符串中的字符数量，否则将假定字符串以零
     值结尾。

     引发一个 *note 审计事件: ea1. ‘ctypes.wstring_at’，附带参数
     ‘address’, ‘size’。


File: python.info,  Node: 数据类型<2>,  Next: 基础数据类型<2>,  Prev: 工具函数,  Up: ctypes 参考手册

5.16.16.28 数据类型
...................

 -- 类: ctypes._CData

     这个非公有类是所有 ctypes 数据类型的共同基类。 另外，所有 ctypes 类
     型的实例都包含一个存放 C 兼容数据的内存块；该内存块的地址可由 *note
     addressof(): 232a. 辅助函数返回。 还有一个实例变量被公开为 *note
     _objects: 2338.；此变量包含其他在内存块包含指针的情况下需要保持存活
     的 Python 对象。

     ctypes 数据类型的通用方法，它们都是类方法（严谨地说，它们是 *note
     metaclass: 2339. 的方法）:

      -- 方法: from_buffer (source[, offset])

          此方法返回一个共享 `source' 对象缓冲区的 ctypes 实例。
          `source' 对象必须支持可写缓冲区接口。 可选的 `offset' 形参指定
          以字节表示的源缓冲区内偏移量；默认值为零。 如果源缓冲区不够大
          则会引发 *note ValueError: 1fc.。

          引发一个 *note 审计事件: ea1. ‘ctypes.cdata/buffer’ 附带参数
          ‘pointer’, ‘size’, ‘offset’。

      -- 方法: from_buffer_copy (source[, offset])

          此方法创建一个 ctypes 实例，从 `source' 对象缓冲区拷贝缓冲区，
          该对象必须是可读的。 可选的 `offset' 形参指定以字节表示的源缓
          冲区内偏移量；默认值为零。 如果源缓冲区不够大则会引发 *note
          ValueError: 1fc.。

          引发一个 *note 审计事件: ea1. ‘ctypes.cdata/buffer’ 附带参数
          ‘pointer’, ‘size’, ‘offset’。

      -- 方法: from_address (address)

          此方法会使用 `address' 所指定的内存返回一个 ctypes 类型的实例
          ，该参数必须为一个整数。

          引发一个 *note 审计事件: ea1. ‘ctypes.cdata’，附带参数
          ‘address’。

      -- 方法: from_param (obj)

          此方法会将 `obj' 适配为一个 ctypes 类型。 它调用时会在当该类型
          存在于外部函数的 ‘argtypes’ 元组时传入外部函数调用所使用的实际
          对象；它必须返回一个可被用作函数调用参数的对象。

          所有 ctypes 数据类型都带有这个类方法的默认实现，它通常会返回
          `obj'，如果该对象是此类型的实例的话。 某些类型也能接受其他对象
          。

      -- 方法: in_dll (library, name)

          此方法返回一个由共享库导出的 ctypes 类型。 `name' 为导出数据的
          符号名称，`library' 为所加载的共享库。

     ctypes 数据类型的通用实例变量:

      -- 属性: _b_base_

          有时 ctypes 数据实例并不拥有它们所包含的内存块，它们只是共享了
          某个基对象的部分内存块。 *note _b_base_: 233f. 只读成员是拥有
          内存块的根 ctypes 对象。

      -- 属性: _b_needsfree_

          这个只读变量在 ctypes 数据实例自身已分配了内存块时为真值，否则
          为假值。

      -- 属性: _objects

          这个成员或者为 ‘None’，或者为一个包含需要保持存活以使内存块的
          内存保持有效的 Python 对象的字典。 这个对象只是出于调试目的而
          对外公开；绝对不要修改此字典的内容。


File: python.info,  Node: 基础数据类型<2>,  Next: 结构化数据类型,  Prev: 数据类型<2>,  Up: ctypes 参考手册

5.16.16.29 基础数据类型
.......................

 -- 类: ctypes._SimpleCData

     这个非公有类是所有基本 ctypes 数据类型的基类。 它在这里被提及是因为
     它包含基本 ctypes 数据类型共有的属性。 *note _SimpleCData: 2343. 是
     *note _CData: 10c0. 的子类，因此继承了其方法和属性。 非指针及不包含
     指针的 ctypes 数据类型现在将可以被封存。

     实例拥有一个属性:

      -- 属性: value

          这个属性包含实例的实际值。 对于整数和指针类型，它是一个整数，
          对于字符类型，它是一个单字符字符串对象或字符串，对于字符指针类
          型，它是一个 Python 字节串对象或字符串。

          当从 ctypes 实例提取 ‘value’ 属性时，通常每次会返回一个新的对
          象。 *note ctypes: 2b. 并 `没有' 实现原始对象返回，它总是会构
          造一个新的对象。 所有其他 ctypes 对象实例也同样如此。

基本数据类型当作为外部函数调用结果被返回或者作为结构字段成员或数组项被提
取时，会透明地转换为原生 Python 类型。 换句话说，如果某个外部函数具有
*note c_char_p: 22da. 的 ‘restype’，你将总是得到一个 Python 字节串对象，
而 `不是' 一个 *note c_char_p: 22da. 实例。

基本数据类型的子类并 `没有' 继续此行为。 因此，如果一个外部函数的
‘restype’ 是 *note c_void_p: 22db. 的一个子类，你将从函数调用得到一个该
子类的实例。 当然，你可以通过访问 ‘value’ 属性来获取指针的值。

这些是基本 ctypes 数据类型:

 -- 类: ctypes.c_byte

     代表 C ‘signed char’ 数据类型，并将值解读为一个小整数。 该构造器接
     受一个可选的整数初始化器；不会执行溢出检查。

 -- 类: ctypes.c_char

     代表 C ‘char’ 数据类型，并将值解读为单个字符。 该构造器接受一个可选
     的字符串初始化器，字符串的长度必须恰好为一个字符。

 -- 类: ctypes.c_char_p

     当指向一个以零为结束符的字符串时代表 C ‘char *’ 数据类型。 对于通用
     字符指针来说也可能指向二进制数据，必须要使用 ‘POINTER(c_char)’。 该
     构造器接受一个整数地址，或者一个字节串对象。

 -- 类: ctypes.c_double

     代表 C ‘double’ 数据类型。 该构造器接受一个可选的浮点数初始化器。

 -- 类: ctypes.c_longdouble

     代表 C ‘long double’ 数据类型。 该构造器接受一个可选的浮点数初始化
     器。 在 ‘sizeof(long double) == sizeof(double)’ 的平台上它是 *note
     c_double: ec1. 的一个别名。

 -- 类: ctypes.c_float

     代表 C ‘float’ 数据类型。 该构造器接受一个可选的浮点数初始化器。

 -- 类: ctypes.c_int

     代表 C ‘signed int’ 数据类型。 该构造器接受一个可选的整数初始化器；
     不会执行溢出检查。 在 ‘sizeof(int) == sizeof(long)’ 的平台上它是
     *note c_long: 22c4. 的一个别名。

 -- 类: ctypes.c_int8

     代表 C 8 位 ‘signed int’ 数据类型。 通常是 *note c_byte: 22d0. 的一
     个别名。

 -- 类: ctypes.c_int16

     代表 C 16 位 ‘signed int’ 数据类型。 通常是 *note c_short: 22d2. 的
     一个别名。

 -- 类: ctypes.c_int32

     代表 C 32 位 ‘signed int’ 数据类型。 通常是 *note c_int: 22c3. 的一
     个别名。

 -- 类: ctypes.c_int64

     代表 C 64 位 ‘signed int’ 数据类型。 通常是 *note c_longlong: 22d6.
     的一个别名。

 -- 类: ctypes.c_long

     代表 C ‘signed long’ 数据类型。 该构造器接受一个可选的整数初始化器
     ；不会执行溢出检查。

 -- 类: ctypes.c_longlong

     代表 C ‘signed long long’ 数据类型。 该构造器接受一个可选的整数初始
     化器；不会执行溢出检查。

 -- 类: ctypes.c_short

     代表 C ‘signed short’ 数据类型。 该构造器接受一个可选的整数初始化器
     ；不会执行溢出检查。

 -- 类: ctypes.c_size_t

     代表 C ‘size_t’ 数据类型。

 -- 类: ctypes.c_ssize_t

     代表 C ‘ssize_t’ 数据类型。

     3.2 新版功能.

 -- 类: ctypes.c_ubyte

     代表 C ‘unsigned char’ 数据类型，它将值解读为一个小整数。 该构造器
     接受一个可选的整数初始化器；不会执行溢出检查。

 -- 类: ctypes.c_uint

     代表 C ‘unsigned int’ 数据类型。 该构造器接受一个可选的整数初始化器
     ；不会执行溢出检查。 在 ‘sizeof(int) == sizeof(long)’ 的平台上它是
     *note c_ulong: 22d5. 的一个别名。

 -- 类: ctypes.c_uint8

     代表 C 8 位 ‘unsigned int’ 数据类型。 通常是 *note c_ubyte: 22d1. 的
     一个别名。

 -- 类: ctypes.c_uint16

     代表 C 16 位 ‘unsigned int’ 数据类型。 通常是 *note c_ushort: 22d3.
     的一个别名。

 -- 类: ctypes.c_uint32

     代表 C 32 位 ‘unsigned int’ 数据类型。 通常是 *note c_uint: 22d4. 的
     一个别名。.

 -- 类: ctypes.c_uint64

     代表 C 64 位 ‘unsigned int’ 数据类型。 通常是 *note c_ulonglong:
     22d7. 的一个别名。

 -- 类: ctypes.c_ulong

     代表 C ‘unsigned long’ 数据类型。 该构造器接受一个可选的整数初始化
     器；不会执行溢出检查。

 -- 类: ctypes.c_ulonglong

     代表 C ‘unsigned long long’ 数据类型。 该构造器接受一个可选的整数初
     始化器；不会执行溢出检查。

 -- 类: ctypes.c_ushort

     代表 C ‘unsigned short’ 数据类型。 该构造器接受一个可选的整数初始化
     器；不会执行溢出检查。

 -- 类: ctypes.c_void_p

     代表 C ‘void *’ 类型。 该值被表示为整数形式。 该构造器接受一个可选
     的整数初始化器。

 -- 类: ctypes.c_wchar

     代表 C ‘wchar_t’ 数据类型，并将值解读为一单个字符的 unicode 字符串
     。 该构造器接受一个可选的字符串初始化器，字符串的长度必须恰好为一个
     字符。

 -- 类: ctypes.c_wchar_p

     代表 C ‘wchar_t *’ 数据类型，它必须为指向以零为结束符的宽字符串的指
     针。 该构造器接受一个整数地址或者一个字符串。

 -- 类: ctypes.c_bool

     代表 C ‘bool’ 数据类型 (更准确地说是 C99 ‘_Bool’)。 它的值可以为
     ‘True’ 或 ‘False’，并且该构造器接受任何具有逻辑值的对象。

 -- 类: ctypes.HRESULT

     Windows 专属：代表一个 ‘HRESULT’ 值，它包含某个函数或方法调用的成功
     或错误信息。

 -- 类: ctypes.py_object

     代表 C *note PyObject *: 4c2. 数据类型。 不带参数地调用此构造器将创
     建一个 ‘NULL’ *note PyObject *: 4c2. 指针。

‘ctypes.wintypes’ 模块提供了其他许多 Windows 专属的数据类型，例如
‘HWND’, ‘WPARAM’ 或 ‘DWORD’。 还定义了一些有用的结构体例如 ‘MSG’ 或
‘RECT’。


File: python.info,  Node: 结构化数据类型,  Next: 数组与指针,  Prev: 基础数据类型<2>,  Up: ctypes 参考手册

5.16.16.30 结构化数据类型
.........................

 -- 类: ctypes.Union (*args, **kw)

     本机字节序的联合所对应的抽象基类。

 -- 类: ctypes.BigEndianStructure (*args, **kw)

     `大端' 字节序的结构体所对应的抽象基类。

 -- 类: ctypes.LittleEndianStructure (*args, **kw)

     `小端' 字节序的结构体所对应的抽象基类。

非本机字节序的结构体不能包含指针类型字段，或任何其他包含指针类型字段的数
据类型。

 -- 类: ctypes.Structure (*args, **kw)

     `本机' 字节序的结构体所对应的抽象基类。

     实际的结构体和联合类型必须通过子类化这些类型之一来创建，并且至少要
     定义一个 *note _fields_: 2350. 类变量。 *note ctypes: 2b. 将创建
     *note descriptor: 1616.，它允许通过直接属性访问来读取和写入字段。 这
     些是

      -- 属性: _fields_

          一个定义结构体字段的序列。 其中的条目必须为 2 元组或 3 元组。
          元组的第一项是字段名称，第二项指明字段类型；它可以是任何
          ctypes 数据类型。

          对于整数类型字段例如 *note c_int: 22c3.，可以给定第三个可选项
          。 它必须是一个定义字段比特位宽度的小正整数。

          字段名称在一个结构体或联合中必须唯一。 不会检查这个唯一性，但
          当名称出现重复时将只有一个字段可被访问。

          可以在定义 Structure 子类的类语句 `之后' 再定义 *note
          _fields_: 2350. 类变量，这将允许创建直接或间接引用其自身的数据
          类型:

               class List(Structure):
                   pass
               List._fields_ = [("pnext", POINTER(List)),
                                ...
                               ]

          但是，*note _fields_: 2350. 类变量必须在类型第一次被使用（创建
          实例，调用 *note sizeof(): 2332. 等等）之前进行定义。 在此之后
          对 *note _fields_: 2350. 类变量赋值将会引发 AttributeError。

          可以定义结构体类型的子类，它们会继承基类的字段再加上在子类中定
          义的任何 *note _fields_: 2350.。

      -- 属性: _pack_

          一个可选的小整数，它允许覆盖实体中结构体字段的对齐方式。 当
          *note _fields_: 2350. 被赋值时必须已经定义了 *note _pack_:
          2351.，否则它将没有效果。

      -- 属性: _anonymous_

          一个可选的序列，它会列出未命名（匿名）字段的名称。 当 *note
          _fields_: 2350. 被赋值时必须已经定义了 *note _anonymous_:
          2352.，否则它将没有效果。

          在此变量中列出的字段必须为结构体或联合类型字段。 *note ctypes:
          2b. 将在结构体类型中创建描述器以允许直接访问嵌套字段，而无需创
          建结构体或联合字段。

          以下是一个示例类型（Windows）:

               class _U(Union):
                   _fields_ = [("lptdesc", POINTER(TYPEDESC)),
                               ("lpadesc", POINTER(ARRAYDESC)),
                               ("hreftype", HREFTYPE)]

               class TYPEDESC(Structure):
                   _anonymous_ = ("u",)
                   _fields_ = [("u", _U),
                               ("vt", VARTYPE)]

          ‘TYPEDESC’ 结构体描述了一个 COM 数据类型，‘vt’ 字段指明哪个联
          合字段是有效的。 由于 ‘u’ 字段被定义为匿名字段，现在可以直接从
          TYPEDESC 实例访问成员。 ‘td.lptdesc’ 和 ‘td.u.lptdesc’ 是等价
          的，但前者速度更快，因为它不需要创建临时的联合实例:

               td = TYPEDESC()
               td.vt = VT_PTR
               td.lptdesc = POINTER(some_type)
               td.u.lptdesc = POINTER(some_type)

     可以定义结构体的子类，它们会继承基类的字段。 如果子类定义具有单独的
     *note _fields_: 2350. 变量，在其中指定的字段会被添加到基类的字段中
     。

     结构体和联合的构造器均可接受位置和关键字参数。 位置参数用于按照
     *note _fields_: 2350. 中的出现顺序来初始化成员字段。 构造器中的关键
     字参数会被解读为属性赋值，因此它们将以相应的名称来初始化 *note
     _fields_: 2350.，或为不存在于 *note _fields_: 2350. 中的名称创建新
     的属性。


File: python.info,  Node: 数组与指针,  Prev: 结构化数据类型,  Up: ctypes 参考手册

5.16.16.31 数组与指针
.....................

 -- 类: ctypes.Array (*args)

     数组的抽象基类。

     创建实际数组类型的推荐方式是通过将任意 *note ctypes: 2b. 类型与一个
     正整数相乘。 作为替代方式，你也可以子类化这个类型并定义 *note
     _length_: 2355. 和 *note _type_: 2356. 类变量。 数组元素可使用标准
     的抽取和切片方式来读写；对于切片读取，结果对象本身 `并非' 一个
     *note Array: 101c.。

      -- 属性: _length_

          一个指明数组中元素数量的正整数。 超出范围的抽取会导致 *note
          IndexError: e7d.。 该值将由 *note len(): 151. 返回。

      -- 属性: _type_

          指明数组中每个元素的类型。

     Array 子类构造器可接受位置参数，用来按顺序初始化元素。

 -- 类: ctypes._Pointer

     私有对象，指针的抽象基类。

     实际的指针类型是通过调用 *note POINTER(): 22f9. 并附带其将指向的类
     型来创建的；这会由 *note pointer(): 22e9. 自动完成。

     如果一个指针指向的是数组，则其元素可使用标准的抽取和切片方式来读写
     。 指针对象没有长度，因此 *note len(): 151. 将引发 *note TypeError:
     193.。 抽取负值将会从指针 `之前' 的内存中读取（与 C 一样），并且超
     出范围的抽取将可能因非法访问而导致崩溃（视你的运气而定）。

      -- 属性: _type_

          指明所指向的类型。

      -- 属性: contents

          返回指针所指向的对象。 对此属性赋值会使指针改为指向所赋值的对
          象。


File: python.info,  Node: 并发执行,  Next: 网络和进程间通信,  Prev: 通用操作系统服务,  Up: Python 标准库

5.17 并发执行
=============

本章中描述的模块支持并发执行代码。 适当的工具选择取决于要执行的任务（
CPU密集型或IO密集型）和偏好的开发风格（事件驱动的协作式多任务或抢占式多
任务处理）。 这是一个概述：

* Menu:

* threading: threading --- 基于线程的并行. 基于线程的并行
* multiprocessing: multiprocessing --- 基于进程的并行. 基于进程的并行
* multiprocessing.shared_memory: multiprocessing shared_memory --- 可从进程直接访问的共享内存. 可从进程直接访问的共享内存
* concurrent 包::
* concurrent.futures: concurrent futures --- 启动并行任务. 启动并行任务
* subprocess: subprocess --- 子进程管理. 子进程管理
* sched: sched --- 事件调度器. 事件调度器
* queue: queue --- 一个同步的队列类. 一个同步的队列类
* contextvars 上下文变量::
* _thread: _thread --- 底层多线程 API. 底层多线程 API
* _dummy_thread: _dummy_thread --- _thread 的替代模块. _thread 的替代模块
* dummy_threading: dummy_threading --- 可直接替代 threading 模块。. 可直接替代 threading 模块。


File: python.info,  Node: threading --- 基于线程的并行,  Next: multiprocessing --- 基于进程的并行,  Up: 并发执行

5.17.1 ‘threading’ — 基于线程的并行
-----------------------------------

`源代码:' Lib/threading.py(1)

__________________________________________________________________

这个模块在较低级的模块 *note _thread: 3. 基础上建立较高级的线程接口。参
见： *note queue: db. 模块。

在 3.7 版更改: 这个模块曾经为可选项，但现在总是可用。

     注解: 虽然他们没有在下面列出，这个模块仍然支持Python 2.x系列的这个
     模块下以 ‘camelCase’ （驼峰法）命名的方法和函数。

`CPython implementation detail:' 在 CPython 中，由于存在 *note
全局解释器锁: 50e.，同一时刻只有一个线程可以执行 Python 代码（虽然某些性
能导向的库可能会去除此限制）。 如果你想让你的应用更好地利用多核心计算机
的计算资源，推荐你使用 *note multiprocessing: b8. 或 *note
concurrent.futures.ProcessPoolExecutor: 2a4.。 但是，如果你想要同时运行
多个 I/O 密集型任务，则多线程仍然是一个合适的模型。

这个模块定义了以下函数：

 -- 函数: threading.active_count ()

     返回当前存活的 *note Thread: 235. 对象的数量。 返回值与 *note
     enumerate(): 235f. 所返回的列表长度一致。

 -- 函数: threading.current_thread ()

     返回当前对应调用者的控制线程的 *note Thread: 235. 对象。如果调用者
     的控制线程不是利用 *note threading: 10a. 创建，会返回一个功能受限的
     虚拟线程对象。

 -- 函数: threading.excepthook (args, /)

     处理由 *note Thread.run(): 233. 引发的未捕获异常。

     `args' 参数具有以下属性:

        * `exc_type': 异常类型

        * `exc_value': 异常值，可以是 ‘None’.

        * `exc_traceback': 异常回溯，可以是 ‘None’.

        * `thread': 引发异常的线程，可以为 ‘None’。

     如果 `exc_type' 为 *note SystemExit: 605.，则异常会被静默地忽略。 在
     其他情况下，异常将被打印到 *note sys.stderr: 318.。

     如果此函数引发了异常，则会调用 *note sys.excepthook(): e6b. 来处理
     它。

     *note threading.excepthook(): 232. 可以被重载以控制由 *note
     Thread.run(): 233. 引发的未捕获异常的处理方式。

     使用定制钩子存放 `exc_value' 可能会创建引用循环。 它应当在不再需要
     异常时被显式地清空以打破引用循环。

     如果一个对象正在被销毁，那么使用自定义的钩子储存 `thread' 可能会将
     其复活。请在自定义钩子生效后避免储存 `thread'，以避免对象的复活。

     参见
     ....

     *note sys.excepthook(): e6b. 处理未捕获的异常。

     3.8 新版功能.

 -- 函数: threading.get_ident ()

     返回当前线程的 “线程标识符”。它是一个非零的整数。它的值没有直接含义
     ，主要是用作 magic cookie，比如作为含有线程相关数据的字典的索引。线
     程标识符可能会在线程退出，新线程创建时被复用。

     3.3 新版功能.

 -- 函数: threading.get_native_id ()

     返回内核分配给当前线程的原生集成线程 ID。 这是一个非负整数。 它的值
     可被用来在整个系统中唯一地标识这个特定线程（直到线程终结，在那之后
     该值可能会被 OS 回收再利用）。

     *note 可用性: 136f.: Windows, FreeBSD, Linux, macOS, OpenBSD,
     NetBSD, AIX。

     3.8 新版功能.

 -- 函数: threading.enumerate ()

     以列表形式返回当前所有存活的 *note Thread: 235. 对象。 该列表包含守
     护线程，*note current_thread(): 2360. 创建的虚拟线程对象和主线程。
     它不包含已终结的线程和尚未开始的线程。

 -- 函数: threading.main_thread ()

     返回主 *note Thread: 235. 对象。一般情况下，主线程是Python解释器开
     始时创建的线程。

     3.4 新版功能.

 -- 函数: threading.settrace (func)

     为所有 *note threading: 10a. 模块开始的线程设置追踪函数。在每个线程
     的 *note run(): 233. 方法被调用前，`func' 会被传递给 *note
     sys.settrace(): e46. 。

 -- 函数: threading.setprofile (func)

     为所有 *note threading: 10a. 模块开始的线程设置性能测试函数。在每个
     线程的 *note run(): 233. 方法被调用前，`func' 会被传递给 *note
     sys.setprofile(): e45. 。

 -- 函数: threading.stack_size ([size])

     返回创建线程时使用的堆栈大小。可选参数 `size' 指定之后新建的线程的
     堆栈大小，而且一定要是0（根据平台或者默认配置）或者最小是
     32,768(32KiB)的一个正整数。如果 `size' 没有指定，默认是0。如果不支
     持改变线程堆栈大小，会抛出 *note RuntimeError: 2bb. 错误。如果指定
     的堆栈大小不合法，会抛出 *note ValueError: 1fc. 错误并且不会修改堆
     栈大小。32KiB是当前最小的能保证解释器有足够堆栈空间的堆栈大小。需要
     注意的是部分平台对于堆栈大小会有特定的限制，例如要求大于32KiB的堆栈
     大小或者需要根据系统内存页面的整数倍进行分配 - 应当查阅平台文档有关
     详细信息（4KiB页面比较普遍，在没有更具体信息的情况下，建议的方法是
     使用4096的倍数作为堆栈大小）。

     *note 适用于: 136f.: Windows，具有 POSIX 线程的系统。

这个模块同时定义了以下常量：

 -- 数据: threading.TIMEOUT_MAX

     阻塞函数（ *note Lock.acquire(): 775, *note RLock.acquire(): 776,
     *note Condition.wait(): 2365, ...）中形参 `timeout' 允许的最大值。
     传入超过这个值的 timeout 会抛出 *note OverflowError: 968. 异常。

     3.2 新版功能.

这个模块定义了许多类，详见以下部分。

该模块的设计基于 Java的线程模型。 但是，在Java里面，锁和条件变量是每个对
象的基础特性，而在Python里面，这些被独立成了单独的对象。 Python 的 *note
Thread: 235. 类只是 Java 的 Thread 类的一个子集；目前还没有优先级，没有
线程组，线程还不能被销毁、停止、暂停、恢复或中断。 Java 的 Thread 类的静
态方法在实现时会映射为模块级函数。

下述方法的执行都是原子性的。

* Menu:

* 线程本地数据::
* 线程对象::
* 锁对象::
* 递归锁对象::
* 条件对象::
* 信号量对象::
* 事件对象::
* 定时器对象::
* 栅栏对象::
* 在 with 语句中使用锁、条件和信号量::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/threading.py


File: python.info,  Node: 线程本地数据,  Next: 线程对象,  Up: threading --- 基于线程的并行

5.17.1.1 线程本地数据
.....................

线程本地数据是特定线程的数据。管理线程本地数据，只需要创建一个 *note
local: 2302. （或者一个子类型）的实例并在实例中储存属性：

     mydata = threading.local()
     mydata.x = 1

在不同的线程中，实例的值会不同。

 -- 类: threading.local

     一个代表线程本地数据的类。

     更多相关细节和大量示例，参见 ‘_threading_local’ 模块的文档。


File: python.info,  Node: 线程对象,  Next: 锁对象,  Prev: 线程本地数据,  Up: threading --- 基于线程的并行

5.17.1.2 线程对象
.................

The *note Thread: 235. class represents an activity that is run in a
separate thread of control.  There are two ways to specify the activity:
by passing a callable object to the constructor, or by overriding the
*note run(): 233. method in a subclass.  No other methods (except for
the constructor) should be overridden in a subclass.  In other words,
`only' override the ‘__init__()’ and *note run(): 233. methods of this
class.

当线程对象一但被创建，其活动一定会因调用线程的 *note start(): 20e5. 方法
开始。这会在独立的控制线程调用 *note run(): 233. 方法。

一旦线程活动开始，该线程会被认为是 ’存活的’ 。当它的 *note run(): 233. 方
法终结了（不管是正常的还是抛出未被处理的异常），就不是’存活的’。 *note
is_alive(): 2369. 方法用于检查线程是否存活。

其他线程可以调用一个线程的 *note join(): b68. 方法。这会阻塞调用该方法的
线程，直到被调用 *note join(): b68. 方法的线程终结。

线程有名字。名字可以传递给构造函数，也可以通过 *note name: 236a. 属性读
取或者修改。

如果 *note run(): 233. 方法引发了异常，则会调用 *note
threading.excepthook(): 232. 来处理它。 在默认情况下，*note
threading.excepthook(): 232. 会静默地忽略 *note SystemExit: 605.。

一个线程可以被标记成一个“守护线程”。 这个标志的意义是，当剩下的线程都是
守护线程时，整个 Python 程序将会退出。 初始值继承于创建线程。 这个标志可
以通过 *note daemon: 236b. 特征属性或者 `daemon' 构造器参数来设置。

     注解: 守护线程在程序关闭时会突然关闭。他们的资源（例如已经打开的文
     档，数据库事务等等）可能没有被正确释放。如果你想你的线程正常停止，
     设置他们成为非守护模式并且使用合适的信号机制，例如： *note Event:
     ab5.。

有个 "主线程" 对象；这对应Python程序里面初始的控制线程。它不是一个守护线
程。

"虚拟线程对象" 是可以被创建的。这些是对应于“外部线程”的线程对象，它们是
在线程模块外部启动的控制线程，例如直接来自C代码。虚拟线程对象功能受限；
他们总是被认为是存活的和守护模式，不能被 *note join(): b68. 。因为无法检
测外来线程的终结，它们永远不会被删除。

 -- 类: threading.Thread (group=None, target=None, name=None, args=(),
          kwargs={}, *, daemon=None)

     调用这个构造函数时，必需带有关键字参数。参数如下：

     `group' 应该为 ‘None’；为了日后扩展 ‘ThreadGroup’ 类实现而保留。

     `target' 是用于 *note run(): 233. 方法调用的可调用对象。默认是
     ‘None’，表示不需要调用任何方法。

     `name' 是线程名称。默认情况下，由 "Thread-`N'" 格式构成一个唯一的名
     称，其中 `N' 是小的十进制数。

     `args' 是用于调用目标函数的参数元组。默认是 ‘()’。

     `kwargs' 是用于调用目标函数的关键字参数字典。默认是 ‘{}’。

     如果不是 ‘None’，`daemon' 参数将显式地设置该线程是否为守护模式。 如
     果是 ‘None’ (默认值)，线程将继承当前线程的守护模式属性。

     如果子类型重载了构造函数，它一定要确保在做任何事前，先发起调用基类
     构造器(‘Thread.__init__()’)。

     在 3.3 版更改: 加入 `daemon' 参数。

      -- 方法: start ()

          开始线程活动。

          它在一个线程里最多只能被调用一次。它安排对象的 *note run():
          233. 方法在一个独立的控制进程中调用。

          如果同一个线程对象中调用这个方法的次数大于一次，会抛出 *note
          RuntimeError: 2bb. 。

      -- 方法: run ()

          代表线程活动的方法。

          你可以在子类型里重载这个方法。 标准的 *note run(): 233. 方法会
          对作为 `target' 参数传递给该对象构造器的可调用对象（如果存在）
          发起调用，并附带从 `args' 和 `kwargs' 参数分别获取的位置和关键
          字参数。

      -- 方法: join (timeout=None)

          等待，直到线程终结。这会阻塞调用这个方法的线程，直到被调用
          *note join(): b68. 的线程终结 – 不管是正常终结还是抛出未处理异
          常 – 或者直到发生超时，超时选项是可选的。

          当 `timeout' 参数存在而且不是 ‘None’ 时，它应该是一个用于指定
          操作超时的以秒为单位的浮点数或者分数。因为 *note join(): b68.
          总是返回 ‘None’ ，所以你一定要在 *note join(): b68. 后调用
          *note is_alive(): 2369. 才能判断是否发生超时 – 如果线程仍然存
          活，则 *note join(): b68. 超时。

          当 `timeout' 参数不存在或者是 ‘None’ ，这个操作会阻塞直到线程
          终结。

          一个线程可以被 *note join(): b68. 很多次。

          如果尝试加入当前线程会导致死锁， *note join(): b68. 会引起
          *note RuntimeError: 2bb. 异常。如果尝试 *note join(): b68. 一
          个尚未开始的线程，也会抛出相同的异常。

      -- 属性: name

          只用于识别的字符串。它没有语义。多个线程可以赋予相同的名称。 初
          始名称由构造函数设置。

      -- 方法: getName ()
      -- 方法: setName ()

          旧的 *note name: 236a. 取值/设值 API；请改为直接以特征属性方式
          使用它。

      -- 属性: ident

          这个线程的 ’线程标识符’，如果线程尚未开始则为 ‘None’ 。这是个
          非零整数。参见 *note get_ident(): ab7. 函数。当一个线程退出而
          另外一个线程被创建，线程标识符会被复用。即使线程退出后，仍可得
          到标识符。

      -- 属性: native_id

          此线程的原生集成线程 ID。 这是一个非负整数，或者如果线程还未启
          动则为 ‘None’。 请参阅 *note get_native_id(): 234. 函数。 这表
          示线程 ID (‘TID’) 已被 OS (内核) 赋值给线程。 它的值可能被用来
          在全系统范围内唯一地标识这个特定线程（直到线程终结，在那之后该
          值可能会被 OS 回收再利用）。

               注解: 类似于进程 ID，线程 ID 的有效期（全系统范围内保证唯
               一）将从线程被创建开始直到线程被终结。

          *note 可用性: 136f.: 需要 *note get_native_id(): 234. 函数。

          3.8 新版功能.

      -- 方法: is_alive ()

          返回线程是否存活。

          当 *note run(): 233. 方法刚开始直到 *note run(): 233. 方法刚结
          束，这个方法返回 ‘True’ 。模块函数 *note enumerate(): 235f. 返
          回包含所有存活线程的列表。

      -- 属性: daemon

          一个表示这个线程是（True）否（False）守护线程的布尔值。一定要
          在调用 *note start(): 20e5. 前设置好，不然会抛出 *note
          RuntimeError: 2bb. 。初始值继承于创建线程；主线程不是守护线程
          ，因此主线程创建的所有线程默认都是 *note daemon: 236b. =
          ‘False’。

          当没有存活的非守护线程时，整个Python程序才会退出。

      -- 方法: isDaemon ()
      -- 方法: setDaemon ()

          旧的 *note daemon: 236b. 取值/设值 API；请改为直接以特性属性方
          式使用它。


File: python.info,  Node: 锁对象,  Next: 递归锁对象,  Prev: 线程对象,  Up: threading --- 基于线程的并行

5.17.1.3 锁对象
...............

原始锁是一个在锁定时不属于特定线程的同步基元组件。在Python中，它是能用的
最低级的同步基元组件，由 *note _thread: 3. 扩展模块直接实现。

原始锁处于 "锁定" 或者 "非锁定" 两种状态之一。它被创建时为非锁定状态。它
有两个基本方法， *note acquire(): 775. 和 *note release(): 2372. 。当状
态为非锁定时， *note acquire(): 775. 将状态改为 锁定 并立即返回。当状态
是锁定时， *note acquire(): 775. 将阻塞至其他线程调用 *note release():
2372. 将其改为非锁定状态，然后 *note acquire(): 775. 调用重置其为锁定状
态并返回。 *note release(): 2372. 只在锁定状态下调用； 它将状态改为非锁
定并立即返回。如果尝试释放一个非锁定的锁，则会引发 *note RuntimeError:
2bb.  异常。

锁同样支持 *note 上下文管理协议: 2373.。

当多个线程在 *note acquire(): 775. 等待状态转变为未锁定被阻塞，然后
*note release(): 2372. 重置状态为未锁定时，只有一个线程能继续执行；至于
哪个等待线程继续执行没有定义，并且会根据实现而不同。

所有方法的执行都是原子性的。

 -- 类: threading.Lock

     实现原始锁对象的类。一旦一个线程获得一个锁，会阻塞随后尝试获得锁的
     线程，直到它被释放；任何线程都可以释放它。

     需要注意的是 ‘Lock’ 其实是一个工厂函数，返回平台支持的具体锁类中最
     有效的版本的实例。

      -- 方法: acquire (blocking=True, timeout=-1)

          可以阻塞或非阻塞地获得锁。

          当调用时参数 `blocking' 设置为 ‘True’ （缺省值），阻塞直到锁被
          释放，然后将锁锁定并返回 ‘True’ 。

          在参数 `blocking' 被设置为 ‘False’ 的情况下调用，将不会发生阻
          塞。如果调用时 `blocking' 设为 ‘True’ 会阻塞，并立即返回
          ‘False’ ；否则，将锁锁定并返回 ‘True’。

          当浮点型 `timeout' 参数被设置为正值调用时，只要无法获得锁，将
          最多阻塞 `timeout' 设定的秒数。`timeout' 参数被设置为 ‘-1’ 时
          将无限等待。当 `blocking' 为 false 时，`timeout' 指定的值将被
          忽略。

          如果成功获得锁，则返回 ‘True’，否则返回 ‘False’ (例如发生 `超
          时' 的时候)。

          在 3.2 版更改: 新的 `timeout' 形参。

          在 3.2 版更改: 现在如果底层线程实现支持，则可以通过POSIX上的信
          号中断锁的获取。

      -- 方法: release ()

          释放一个锁。这个方法可以在任何线程中调用，不单指获得锁的线程。

          当锁被锁定，将它重置为未锁定，并返回。如果其他线程正在等待这个
          锁解锁而被阻塞，只允许其中一个允许。

          在未锁定的锁调用时，会引发 *note RuntimeError: 2bb. 异常。

          没有返回值。

      -- 方法: locked ()

          如果获得了锁则返回真值。


File: python.info,  Node: 递归锁对象,  Next: 条件对象,  Prev: 锁对象,  Up: threading --- 基于线程的并行

5.17.1.4 递归锁对象
...................

重入锁是一个可以被同一个线程多次获取的同步基元组件。在内部，它在基元锁的
锁定/非锁定状态上附加了 "所属线程" 和 "递归等级" 的概念。在锁定状态下，
某些线程拥有锁 ； 在非锁定状态下， 没有线程拥有它。

若要锁定锁，线程调用其 *note acquire(): 776. 方法；一旦线程拥有了锁，方
法将返回。若要解锁，线程调用 *note release(): 2372. 方法。 *note
acquire(): 775./*note release(): 2372. 对可以嵌套；只有最终 *note
release(): 2372. (最外面一对的 *note release(): 2372. ) 将锁解开，才能让
其他线程继续处理 *note acquire(): 775. 阻塞。

递归锁也支持 *note 上下文管理协议: 2373.。

 -- 类: threading.RLock

     此类实现了重入锁对象。重入锁必须由获取它的线程释放。一旦线程获得了
     重入锁，同一个线程再次获取它将不阻塞；线程必须在每次获取它时释放一
     次。

     需要注意的是 ‘RLock’ 其实是一个工厂函数，返回平台支持的具体递归锁类
     中最有效的版本的实例。

      -- 方法: acquire (blocking=True, timeout=-1)

          可以阻塞或非阻塞地获得锁。

          当无参数调用时： 如果这个线程已经拥有锁，递归级别增加一，并立
          即返回。否则，如果其他线程拥有该锁，则阻塞至该锁解锁。一旦锁被
          解锁(不属于任何线程)，则抢夺所有权，设置递归等级为一，并返回。
          如果多个线程被阻塞，等待锁被解锁，一次只有一个线程能抢到锁的所
          有权。在这种情况下，没有返回值。

          当发起调用时将 `blocking' 参数设为真值，则执行与无参数调用时一
          样的操作，然后返回 ‘True’。

          当发起调用时将 `blocking' 参数设为假值，则不进行阻塞。 如果一
          个无参数调用将要阻塞，则立即返回 ‘False’；在其他情况下，执行与
          无参数调用时一样的操作，然后返回 ‘True’。

          当发起调用时将浮点数的 `timeout' 参数设为正值时，只要无法获得
          锁，将最多阻塞 `timeout' 所指定的秒数。 如果已经获得锁则返回
          ‘True’，如果超时则返回假值。

          在 3.2 版更改: 新的 `timeout' 形参。

      -- 方法: release ()

          释放锁，自减递归等级。如果减到零，则将锁重置为非锁定状态(不被
          任何线程拥有)，并且，如果其他线程正被阻塞着等待锁被解锁，则仅
          允许其中一个线程继续。如果自减后，递归等级仍然不是零，则锁保持
          锁定，仍由调用线程拥有。

          只有当前线程拥有锁才能调用这个方法。如果锁被释放后调用这个方法
          ，会引起 *note RuntimeError: 2bb. 异常。

          没有返回值。


File: python.info,  Node: 条件对象,  Next: 信号量对象,  Prev: 递归锁对象,  Up: threading --- 基于线程的并行

5.17.1.5 条件对象
.................

条件变量总是与某种类型的锁对象相关联，锁对象可以通过传入获得，或者在缺省
的情况下自动创建。当多个条件变量需要共享同一个锁时，传入一个锁很有用。锁
是条件对象的一部分，你不必单独地跟踪它。

条件变量服从 *note 上下文管理协议: 2373.：使用 ‘with’ 语句会在它包围的代
码块内获取关联的锁。 *note acquire(): 237b. 和 *note release(): 237c. 方
法也能调用关联锁的相关方法。

其它方法必须在持有关联的锁的情况下调用。 *note wait(): 2365. 方法释放锁
，然后阻塞直到其它线程调用 *note notify(): 237d. 方法或 *note
notify_all(): 237e. 方法唤醒它。一旦被唤醒， *note wait(): 2365. 方法重
新获取锁并返回。它也可以指定超时时间。

The *note notify(): 237d. method wakes up one of the threads waiting for
the condition variable, if any are waiting.  The *note notify_all():
237e. method wakes up all threads waiting for the condition variable.

注意： *note notify(): 237d. 方法和 *note notify_all(): 237e. 方法并不会
释放锁，这意味着被唤醒的线程不会立即从它们的 *note wait(): 2365. 方法调
用中返回，而是会在调用了 *note notify(): 237d. 方法或 *note
notify_all(): 237e. 方法的线程最终放弃了锁的所有权后返回。

使用条件变量的典型编程风格是将锁用于同步某些共享状态的权限，那些对状态的
某些特定改变感兴趣的线程，它们重复调用 *note wait(): 2365. 方法，直到看
到所期望的改变发生；而对于修改状态的线程，它们将当前状态改变为可能是等待
者所期待的新状态后，调用 *note notify(): 237d. 方法或者 *note
notify_all(): 237e. 方法。例如，下面的代码是一个通用的无限缓冲区容量的生
产者-消费者情形：

     # Consume one item
     with cv:
         while not an_item_is_available():
             cv.wait()
         get_an_available_item()

     # Produce one item
     with cv:
         make_an_item_available()
         cv.notify()

使用 ‘while’ 循环检查所要求的条件成立与否是有必要的，因为 *note wait():
2365. 方法可能要经过不确定长度的时间后才会返回，而此时导致 *note
notify(): 237d. 方法调用的那个条件可能已经不再成立。这是多线程编程所固有
的问题。 *note wait_for(): 237f. 方法可自动化条件检查，并简化超时计算。

     # Consume an item
     with cv:
         cv.wait_for(an_item_is_available)
         get_an_available_item()

选择 *note notify(): 237d. 还是 *note notify_all(): 237e. ，取决于一次状
态改变是只能被一个还是能被多个等待线程所用。例如在一个典型的生产者-消费
者情形中，添加一个项目到缓冲区只需唤醒一个消费者线程。

 -- 类: threading.Condition (lock=None)

     实现条件变量对象的类。一个条件变量对象允许一个或多个线程在被其它线
     程所通知之前进行等待。

     如果给出了非 ‘None’ 的 `lock' 参数，则它必须为 *note Lock: 2374. 或
     者 *note RLock: bf7. 对象，并且它将被用作底层锁。否则，将会创建新的
     *note RLock: bf7. 对象，并将其用作底层锁。

     在 3.3 版更改: 从工厂函数变为类。

      -- 方法: acquire (*args)

          请求底层锁。此方法调用底层锁的相应方法，返回值是底层锁相应方法
          的返回值。

      -- 方法: release ()

          释放底层锁。此方法调用底层锁的相应方法。没有返回值。

      -- 方法: wait (timeout=None)

          等待直到被通知或发生超时。如果线程在调用此方法时没有获得锁，将
          会引发 *note RuntimeError: 2bb. 异常。

          这个方法释放底层锁，然后阻塞，直到在另外一个线程中调用同一个条
          件变量的 *note notify(): 237d. 或 *note notify_all(): 237e. 唤
          醒它，或者直到可选的超时发生。一旦被唤醒或者超时，它重新获得锁
          并返回。

          当提供了 `timeout' 参数且不是 ‘None’ 时，它应该是一个浮点数，
          代表操作的超时时间，以秒为单位（可以为小数）。

          当底层锁是个 *note RLock: bf7. ，不会使用它的 *note release():
          237c. 方法释放锁，因为当它被递归多次获取时，实际上可能无法解锁
          。相反，使用了 *note RLock: bf7. 类的内部接口，即使多次递归获
          取它也能解锁它。 然后，在重新获取锁时，使用另一个内部接口来恢
          复递归级别。

          返回 ‘True’ ，除非提供的 `timeout' 过期，这种情况下返回
          ‘False’。

          在 3.2 版更改: 很明显，方法总是返回 ‘None’。

      -- 方法: wait_for (predicate, timeout=None)

          等待，直到条件计算为真。 `predicate' 应该是一个可调用对象而且
          它的返回值可被解释为一个布尔值。可以提供 `timeout' 参数给出最
          大等待时间。

          这个实用方法会重复地调用 *note wait(): 2365. 直到满足判断式或
          者发生超时。返回值是判断式最后一个返回值，而且如果方法发生超时
          会返回 ‘False’ 。

          忽略超时功能，调用此方法大致相当于编写:

               while not predicate():
                   cv.wait()

          因此，规则同样适用于 *note wait(): 2365. ：锁必须在被调用时保
          持获取，并在返回时重新获取。 随着锁定执行判断式。

          3.2 新版功能.

      -- 方法: notify (n=1)

          默认唤醒一个等待这个条件的线程。如果调用线程在没有获得锁的情况
          下调用这个方法，会引发 *note RuntimeError: 2bb. 异常。

          这个方法唤醒最多 `n' 个正在等待这个条件变量的线程；如果没有线
          程在等待，这是一个空操作。

          当前实现中，如果至少有 `n' 个线程正在等待，准确唤醒 `n' 个线程
          。但是依赖这个行为并不安全。未来，优化的实现有时会唤醒超过 `n'
          个线程。

          注意：被唤醒的线程实际上不会返回它调用的 *note wait(): 2365. ，
          直到它可以重新获得锁。因为 *note notify(): 237d. 不会释放锁，
          只有它的调用者应该这样做。

      -- 方法: notify_all ()

          唤醒所有正在等待这个条件的线程。这个方法行为与 *note notify():
          237d. 相似，但并不只唤醒单一线程，而是唤醒所有等待线程。如果调
          用线程在调用这个方法时没有获得锁，会引发 *note RuntimeError:
          2bb. 异常。


File: python.info,  Node: 信号量对象,  Next: 事件对象,  Prev: 条件对象,  Up: threading --- 基于线程的并行

5.17.1.6 信号量对象
...................

这是计算机科学史上最古老的同步原语之一，早期的荷兰科学家 Edsger W.
Dijkstra 发明了它。（他使用名称 ‘P()’ 和 ‘V()’ 而不是 *note acquire():
bf4. 和 *note release(): 2382. ）。

一个信号量管理一个内部计数器，该计数器因 *note acquire(): bf4. 方法的调
用而递减，因 *note release(): 2382. 方法的调用而递增。 计数器的值永远不
会小于零；当 *note acquire(): bf4. 方法发现计数器为零时，将会阻塞，直到
其它线程调用 *note release(): 2382. 方法。

信号量对象也支持 *note 上下文管理协议: 2373. 。

 -- 类: threading.Semaphore (value=1)

     该类实现信号量对象。信号量对象管理一个原子性的计数器，代表 *note
     release(): 2382. 方法的调用次数减去 *note acquire(): bf4. 的调用次
     数再加上一个初始值。如果需要， *note acquire(): bf4. 方法将会阻塞直
     到可以返回而不会使得计数器变成负数。在没有显式给出 `value' 的值时，
     默认为1。

     可选参数 `value' 赋予内部计数器初始值，默认值为 ‘1’ 。如果 `value'
     被赋予小于0的值，将会引发 *note ValueError: 1fc. 异常。

     在 3.3 版更改: 从工厂函数变为类。

      -- 方法: acquire (blocking=True, timeout=None)

          获取一个信号量。

          在不带参数的情况下调用时：

             * 如果在进入时内部计数器的值大于零，则将其减一并立即返回
               ‘True’。

             * 如果在进入时内部计数器的值为零，则将会阻塞直到被对 *note
               release(): 2382. 的调用唤醒。 一旦被唤醒（并且计数器的值
               大于 0），则将计数器减 1 并返回 ‘True’。 每次对 *note
               release(): 2382. 的调用将只唤醒一个线程。 线程被唤醒的次
               序是不可确定的。

          当发起调用时将 `blocking' 设为假值，则不进行阻塞。 如果一个无
          参数调用将要阻塞，则立即返回 ‘False’；在其他情况下，执行与无参
          数调用时一样的操作，然后返回 ‘True’。

          当发起调用时如果 `timeout' 不为 ‘None’，则它将阻塞最多
          `timeout' 秒。 请求在此时段时未能成功完成获取则将返回 ‘False’。
          在其他情况下返回 ‘True’。

          在 3.2 版更改: 新的 `timeout' 形参。

      -- 方法: release ()

          释放一个信号量，将内部计数器的值增加1。当计数器原先的值为0且有
          其它线程正在等待它再次大于0时，唤醒正在等待的线程。

 -- 类: threading.BoundedSemaphore (value=1)

     该类实现有界信号量。有界信号量通过检查以确保它当前的值不会超过初始
     值。如果超过了初始值，将会引发 *note ValueError: 1fc. 异常。在大多
     情况下，信号量用于保护数量有限的资源。如果信号量被释放的次数过多，
     则表明出现了错误。没有指定时， `value' 的值默认为1。

     在 3.3 版更改: 从工厂函数变为类。

* Menu:

* Semaphore 例子::


File: python.info,  Node: Semaphore 例子,  Up: 信号量对象

5.17.1.7 ‘Semaphore’ 例子
.........................

信号量通常用于保护数量有限的资源，例如数据库服务器。在资源数量固定的任何
情况下，都应该使用有界信号量。在生成任何工作线程前，应该在主线程中初始化
信号量。

     maxconnections = 5
     # ...
     pool_sema = BoundedSemaphore(value=maxconnections)

工作线程生成后，当需要连接服务器时，这些线程将调用信号量的 acquire 和
release 方法：

     with pool_sema:
         conn = connectdb()
         try:
             # ... use connection ...
         finally:
             conn.close()

使用有界信号量能减少这种编程错误：信号量的释放次数多于其请求次数。


File: python.info,  Node: 事件对象,  Next: 定时器对象,  Prev: 信号量对象,  Up: threading --- 基于线程的并行

5.17.1.8 事件对象
.................

这是线程之间通信的最简单机制之一：一个线程发出事件信号，而其他线程等待该
信号。

一个事件对象管理一个内部标志，调用 *note set(): 2387. 方法可将其设置为
true，调用 *note clear(): 2388. 方法可将其设置为false，调用 *note
wait(): cbf. 方法将进入阻塞直到标志为true。

 -- 类: threading.Event

     实现事件对象的类。事件对象管理一个内部标志，调用 *note set(): 2387.
     方法可将其设置为true。调用 *note clear(): 2388. 方法可将其设置为
     false。调用 *note wait(): cbf. 方法将进入阻塞直到标志为true。这个标
     志初始时为false。

     在 3.3 版更改: 从工厂函数变为类。

      -- 方法: is_set ()

          当且仅当内部旗标为时返回 ‘True’。

      -- 方法: set ()

          将内部标志设置为true。所有正在等待这个事件的线程将被唤醒。当标
          志为true时，调用 *note wait(): cbf. 方法的线程不会被被阻塞。

      -- 方法: clear ()

          将内部标志设置为false。之后调用 *note wait(): cbf. 方法的线程
          将会被阻塞，直到调用 *note set(): 2387. 方法将内部标志再次设置
          为true。

      -- 方法: wait (timeout=None)

          阻塞线程直到内部变量为true。如果调用时内部标志为true，将立即返
          回。否则将阻塞线程，直到调用 *note set(): 2387. 方法将标志设置
          为true或者发生可选的超时。

          当提供了timeout参数且不是 ‘None’ 时，它应该是一个浮点数，代表
          操作的超时时间，以秒为单位（可以为小数）。

          当且仅当内部旗标在等待调用之前或者等待开始之后被设为真值时此方
          法将返回 ‘True’，也就是说，它将总是返回 ‘True’ 除非设定了超时
          且操作发生了超时。

          在 3.1 版更改: 很明显，方法总是返回 ‘None’。


File: python.info,  Node: 定时器对象,  Next: 栅栏对象,  Prev: 事件对象,  Up: threading --- 基于线程的并行

5.17.1.9 定时器对象
...................

此类表示一个操作应该在等待一定的时间之后运行 — 相当于一个定时器。 *note
Timer: ab6. 类是 *note Thread: 235. 类的子类，因此可以像一个自定义线程一
样工作。

与线程一样，通过调用 ‘start()’ 方法启动定时器。而 *note cancel(): 238c.
方法可以停止计时器（在计时结束前）， 定时器在执行其操作之前等待的时间间
隔可能与用户指定的时间间隔不完全相同。

例如

     def hello():
         print("hello, world")

     t = Timer(30.0, hello)
     t.start()  # after 30 seconds, "hello, world" will be printed

 -- 类: threading.Timer (interval, function, args=None, kwargs=None)

     创建一个定时器，在经过 `interval' 秒的间隔事件后，将会用参数 `args'
     和关键字参数 `kwargs' 调用 `function'。如果 `args' 为 ‘None’ （默认
     值），则会使用一个空列表。如果 `kwargs' 为 ‘None’ （默认值），则会
     使用一个空字典。

     在 3.3 版更改: 从工厂函数变为类。

      -- 方法: cancel ()

          停止定时器并取消执行计时器将要执行的操作。仅当计时器仍处于等待
          状态时有效。


File: python.info,  Node: 栅栏对象,  Next: 在 with 语句中使用锁、条件和信号量,  Prev: 定时器对象,  Up: threading --- 基于线程的并行

5.17.1.10 栅栏对象
..................

3.2 新版功能.

栅栏类提供一个简单的同步原语，用于应对固定数量的线程需要彼此相互等待的情
况。线程调用 *note wait(): 238e. 方法后将阻塞，直到所有线程都调用了
*note wait(): 238e. 方法。此时所有线程将被同时释放。

栅栏对象可以被多次使用，但进程的数量不能改变。

这是一个使用简便的方法实现客户端进程与服务端进程同步的例子：

     b = Barrier(2, timeout=5)

     def server():
         start_server()
         b.wait()
         while True:
             connection = accept_connection()
             process_server_connection(connection)

     def client():
         b.wait()
         while True:
             connection = make_connection()
             process_client_connection(connection)

 -- 类: threading.Barrier (parties, action=None, timeout=None)

     创建一个需要 `parties' 个线程的栅栏对象。如果提供了可调用的
     `action' 参数，它会在所有线程被释放时在其中一个线程中自动调用。
     `timeout' 是默认的超时时间，如果没有在 *note wait(): 238e. 方法中指
     定超时时间的话。

      -- 方法: wait (timeout=None)

          冲出栅栏。当栅栏中所有线程都已经调用了这个函数，它们将同时被释
          放。如果提供了 `timeout' 参数，这里的 `timeout' 参数优先于创建
          栅栏对象时提供的 `timeout' 参数。

          函数返回值是一个整数，取值范围在0到 `parties' – 1，在每个线程
          中的返回值不相同。可用于从所有线程中选择唯一的一个线程执行一些
          特别的工作。例如：

               i = barrier.wait()
               if i == 0:
                   # Only one thread needs to print this
                   print("passed the barrier")

          如果创建栅栏对象时在构造函数中提供了 `action' 参数，它将在其中
          一个线程释放前被调用。如果此调用引发了异常，栅栏对象将进入损坏
          态。

          如果发生了超时，栅栏对象将进入破损态。

          如果栅栏对象进入破损态，或重置栅栏时仍有线程等待释放，将会引发
          *note BrokenBarrierError: b69. 异常。

      -- 方法: reset ()

          重置栅栏为默认的初始态。如果栅栏中仍有线程等待释放，这些线程将
          会收到 *note BrokenBarrierError: b69. 异常。

          请注意使用此函数时，如果存在状态未知的其他线程，则可能需要执行
          外部同步。 如果栅栏已损坏则最好将其废弃并新建一个。

      -- 方法: abort ()

          使栅栏处于损坏状态。 这将导致任何现有和未来对 *note wait():
          238e. 的调用失败并引发 *note BrokenBarrierError: b69.。 例如可
          以在需要中止某个线程时使用此方法，以避免应用程序的死锁。

          更好的方式是：创建栅栏时提供一个合理的超时时间，来自动避免某个
          线程出错。

      -- 属性: parties

          冲出栅栏所需要的线程数量。

      -- 属性: n_waiting

          当前时刻正在栅栏中阻塞的线程数量。

      -- 属性: broken

          一个布尔值，值为 ‘True’ 表明栅栏为破损态。

 -- 例外: threading.BrokenBarrierError

     异常类，是 *note RuntimeError: 2bb. 异常的子类，在 *note Barrier:
     b67. 对象重置时仍有线程阻塞时和对象进入破损态时被引发。


File: python.info,  Node: 在 with 语句中使用锁、条件和信号量,  Prev: 栅栏对象,  Up: threading --- 基于线程的并行

5.17.1.11 在 ‘with’ 语句中使用锁、条件和信号量
..............................................

这个模块提供的带有 ‘acquire()’ 和 ‘release()’ 方法的对象，可以被用作
*note with: 6f2. 语句的上下文管理器。当进入语句块时 ‘acquire()’ 方法会被
调用，退出语句块时 ‘release()’ 会被调用。因此，以下片段:

     with some_lock:
         # do something...

相当于:

     some_lock.acquire()
     try:
         # do something...
     finally:
         some_lock.release()

现在 *note Lock: 2374. 、 *note RLock: bf7. 、 *note Condition: ab2. 、
*note Semaphore: ab3. 和 *note BoundedSemaphore: ab4. 对象可以用作 *note
with: 6f2. 语句的上下文管理器。


File: python.info,  Node: multiprocessing --- 基于进程的并行,  Next: multiprocessing shared_memory --- 可从进程直接访问的共享内存,  Prev: threading --- 基于线程的并行,  Up: 并发执行

5.17.2 ‘multiprocessing’ — 基于进程的并行
-----------------------------------------

`源代码' Lib/multiprocessing/(1)

__________________________________________________________________

* Menu:

* 概述: 概述<9>.
* 参考::
* 编程指导::
* 例子: 例子<10>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/multiprocessing/


File: python.info,  Node: 概述<9>,  Next: 参考,  Up: multiprocessing --- 基于进程的并行

5.17.2.1 概述
.............

*note multiprocessing: b8. 是一个支持使用与 *note threading: 10a. 模块类
似的 API 来产生进程的包。 *note multiprocessing: b8. 包同时提供了本地和
远程并发操作，通过使用子进程而非线程有效地绕过了 *note 全局解释器锁:
50e.。 因此，*note multiprocessing: b8. 模块允许程序员充分利用给定机器上
的多个处理器。 它在 Unix 和 Windows 上均可运行。

*note multiprocessing: b8. 模块还引入了在 *note threading: 10a. 模块中没
有的API。一个主要的例子就是 *note Pool: 884. 对象，它提供了一种快捷的方
法，赋予函数并行化处理一系列输入值的能力，可以将输入数据分配给不同进程处
理（数据并行）。下面的例子演示了在模块中定义此类函数的常见做法，以便子进
程可以成功导入该模块。这个数据并行的基本例子使用了 *note Pool: 884. ，

     from multiprocessing import Pool

     def f(x):
         return x*x

     if __name__ == '__main__':
         with Pool(5) as p:
             print(p.map(f, [1, 2, 3]))

将在标准输出中打印

     [1, 4, 9]

* Menu:

* Process 类::
* 上下文和启动方法::
* 在进程之间交换对象::
* 进程间同步::
* 进程间共享状态::
* 使用工作进程::


File: python.info,  Node: Process 类,  Next: 上下文和启动方法,  Up: 概述<9>

5.17.2.2 ‘Process’ 类
.....................

在 *note multiprocessing: b8. 中，通过创建一个 *note Process: 3ba. 对象
然后调用它的 ‘start()’ 方法来生成进程。 *note Process: 3ba. 和 *note
threading.Thread: 235. API 相同。 一个简单的多进程程序示例是:

     from multiprocessing import Process

     def f(name):
         print('hello', name)

     if __name__ == '__main__':
         p = Process(target=f, args=('bob',))
         p.start()
         p.join()

要显示所涉及的各个进程ID，这是一个扩展示例:

     from multiprocessing import Process
     import os

     def info(title):
         print(title)
         print('module name:', __name__)
         print('parent process:', os.getppid())
         print('process id:', os.getpid())

     def f(name):
         info('function f')
         print('hello', name)

     if __name__ == '__main__':
         info('main line')
         p = Process(target=f, args=('bob',))
         p.start()
         p.join()

关于为什么 ‘if __name__ == '__main__'’ 部分是必需的解释，请参见 *note
编程指导: 2399.。


File: python.info,  Node: 上下文和启动方法,  Next: 在进程之间交换对象,  Prev: Process 类,  Up: 概述<9>

5.17.2.3 上下文和启动方法
.........................

根据不同的平台， *note multiprocessing: b8. 支持三种启动进程的方法。这些
`启动方法' 有

     `spawn'

          父进程会启动一个全新的 python 解释器进程。 子进程将只继承那些
          运行进程对象的 *note run(): 239b. 方法所必需的资源。 特别地，
          来自父进程的非必需文件描述符和句柄将不会被继承。 使用此方法启
          动进程相比使用 `fork' 或 `forkserver' 要慢上许多。

          可在Unix和Windows上使用。 Windows上的默认设置。

     `fork'

          父进程使用 *note os.fork(): 969. 来产生 Python 解释器分叉。子
          进程在开始时实际上与父进程相同。父进程的所有资源都由子进程继承
          。请注意，安全分叉多线程进程是棘手的。

          只存在于Unix。Unix中的默认值。

     `forkserver'

          程序启动并选择* forkserver * 启动方法时，将启动服务器进程。从
          那时起，每当需要一个新进程时，父进程就会连接到服务器并请求它分
          叉一个新进程。分叉服务器进程是单线程的，因此使用 *note
          os.fork(): 969. 是安全的。没有不必要的资源被继承。

          可在Unix平台上使用，支持通过Unix管道传递文件描述符。

在 3.8 版更改: 对于 macOS，`spawn' 启动方式是默认方式。 因为 `fork' 可能
导致subprocess崩溃，被认为是不安全的，查看 bpo-33725(1) 。

在 3.4 版更改: 在所有unix平台上添加支持了 `spawn' ，并且为一些unix平台添
加了 `forkserver' 。在Windows上子进程不再继承所有可继承的父进程句柄。

在 Unix 上通过 `spawn' 和 `forkserver' 方式启动多进程会同时启动一个 `资
源追踪' 进程，负责追踪当前程序的进程产生的、并且不再被使用的命名系统资源
(如命名信号量以及 *note SharedMemory: 239c. 对象)。当所有进程退出后，资
源追踪会负责释放这些仍被追踪的的对象。通常情况下是不会有这种对象的，但是
假如一个子进程被某个信号杀死，就可能存在这一类资源的“泄露”情况。（泄露的
信号量以及共享内存不会被释放，直到下一次系统重启，对于这两类资源来说，这
是一个比较大的问题，因为操作系统允许的命名信号量的数量是有限的，而共享内
存也会占据主内存的一片空间）

要选择一个启动方法，你应该在主模块的 ‘if __name__ == '__main__'’ 子句中
调用 *note set_start_method(): 882. 。例如：

     import multiprocessing as mp

     def foo(q):
         q.put('hello')

     if __name__ == '__main__':
         mp.set_start_method('spawn')
         q = mp.Queue()
         p = mp.Process(target=foo, args=(q,))
         p.start()
         print(q.get())
         p.join()

在程序中 *note set_start_method(): 882. 不应该被多次调用。

或者，你可以使用 *note get_context(): 883. 来获取上下文对象。上下文对象
与 multiprocessing 模块具有相同的API，并允许在同一程序中使用多种启动方法
。:

     import multiprocessing as mp

     def foo(q):
         q.put('hello')

     if __name__ == '__main__':
         ctx = mp.get_context('spawn')
         q = ctx.Queue()
         p = ctx.Process(target=foo, args=(q,))
         p.start()
         print(q.get())
         p.join()

请注意，对象在不同上下文创建的进程间可能并不兼容。 特别是，使用 `fork' 上
下文创建的锁不能传递给使用 `spawn' 或 `forkserver' 启动方法启动的进程。

想要使用特定启动方法的库应该使用 *note get_context(): 883. 以避免干扰库
用户的选择。

     警告: ‘'spawn'’ 和 ‘'forkserver'’ 启动方法当前不能在Unix上和“冻结的
     ”可执行内容一同使用（例如，有类似 `PyInstaller' 和 `cx_Freeze' 的包
     产生的二进制文件）。 ‘'fork'’ 启动方法可以使用。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33725


File: python.info,  Node: 在进程之间交换对象,  Next: 进程间同步,  Prev: 上下文和启动方法,  Up: 概述<9>

5.17.2.4 在进程之间交换对象
...........................

*note multiprocessing: b8. 支持进程之间的两种通信通道：

`队列'

     *note Queue: 239e. 类是一个近似 *note queue.Queue: d20. 的克隆。 例
     如:

          from multiprocessing import Process, Queue

          def f(q):
              q.put([42, None, 'hello'])

          if __name__ == '__main__':
              q = Queue()
              p = Process(target=f, args=(q,))
              p.start()
              print(q.get())    # prints "[42, None, 'hello']"
              p.join()

     队列是线程和进程安全的。

`管道'

     *note Pipe(): 239f. 函数返回一个由管道连接的连接对象，默认情况下是
     双工（双向）。例如:

          from multiprocessing import Process, Pipe

          def f(conn):
              conn.send([42, None, 'hello'])
              conn.close()

          if __name__ == '__main__':
              parent_conn, child_conn = Pipe()
              p = Process(target=f, args=(child_conn,))
              p.start()
              print(parent_conn.recv())   # prints "[42, None, 'hello']"
              p.join()

     返回的两个连接对象 *note Pipe(): 239f. 表示管道的两端。每个连接对象
     都有 ‘send()’ 和 ‘recv()’ 方法（相互之间的）。请注意，如果两个进程
     （或线程）同时尝试读取或写入管道的 `同一' 端，则管道中的数据可能会
     损坏。当然，在不同进程中同时使用管道的不同端的情况下不存在损坏的风
     险。


File: python.info,  Node: 进程间同步,  Next: 进程间共享状态,  Prev: 在进程之间交换对象,  Up: 概述<9>

5.17.2.5 进程间同步
...................

*note multiprocessing: b8. 包含来自 *note threading: 10a. 的所有同步原语
的等价物。例如，可以使用锁来确保一次只有一个进程打印到标准输出:

     from multiprocessing import Process, Lock

     def f(l, i):
         l.acquire()
         try:
             print('hello world', i)
         finally:
             l.release()

     if __name__ == '__main__':
         lock = Lock()

         for num in range(10):
             Process(target=f, args=(lock, num)).start()

不使用锁的情况下，来自于多进程的输出很容易产生混淆。


File: python.info,  Node: 进程间共享状态,  Next: 使用工作进程,  Prev: 进程间同步,  Up: 概述<9>

5.17.2.6 进程间共享状态
.......................

如上所述，在进行并发编程时，通常最好尽量避免使用共享状态。使用多个进程时
尤其如此。

但是，如果你真的需要使用一些共享数据，那么 *note multiprocessing: b8. 提
供了两种方法。

`共享内存'

     可以使用 *note Value: 23a2. 或 *note Array: 23a3. 将数据存储在共享
     内存映射中。例如，以下代码:

          from multiprocessing import Process, Value, Array

          def f(n, a):
              n.value = 3.1415927
              for i in range(len(a)):
                  a[i] = -a[i]

          if __name__ == '__main__':
              num = Value('d', 0.0)
              arr = Array('i', range(10))

              p = Process(target=f, args=(num, arr))
              p.start()
              p.join()

              print(num.value)
              print(arr[:])

     将打印

          3.1415927
          [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

     创建 ‘num’ 和 ‘arr’ 时使用的 ‘'d'’ 和 ‘'i'’ 参数是 *note array: 7.
     模块使用的类型的 typecode ： ‘'d'’ 表示双精度浮点数， ‘'i'’ 表示有
     符号整数。这些共享对象将是进程和线程安全的。

     为了更灵活地使用共享内存，可以使用 *note
     multiprocessing.sharedctypes: be. 模块，该模块支持创建从共享内存分
     配的任意ctypes对象。

`服务进程'

     由 ‘Manager()’ 返回的管理器对象控制一个服务进程，该进程保存Python对
     象并允许其他进程使用代理操作它们。

     ‘Manager()’ 返回的管理器支持类型： *note list: 263. 、 *note dict:
     1b9. 、 *note Namespace: 23a4. 、 *note Lock: 23a5. 、 *note RLock:
     23a6. 、 *note Semaphore: 23a7. 、 *note BoundedSemaphore: 23a8. 、
     *note Condition: 23a9. 、 *note Event: 23aa. 、 *note Barrier:
     23ab. 、 *note Queue: 239e. 、 *note Value: 23a2. 和 *note Array:
     23a3. 。例如

          from multiprocessing import Process, Manager

          def f(d, l):
              d[1] = '1'
              d['2'] = 2
              d[0.25] = None
              l.reverse()

          if __name__ == '__main__':
              with Manager() as manager:
                  d = manager.dict()
                  l = manager.list(range(10))

                  p = Process(target=f, args=(d, l))
                  p.start()
                  p.join()

                  print(d)
                  print(l)

     将打印

          {0.25: None, 1: '1', '2': 2}
          [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

     使用服务进程的管理器比使用共享内存对象更灵活，因为它们可以支持任意
     对象类型。此外，单个管理器可以通过网络由不同计算机上的进程共享。但
     是，它们比使用共享内存慢。


File: python.info,  Node: 使用工作进程,  Prev: 进程间共享状态,  Up: 概述<9>

5.17.2.7 使用工作进程
.....................

*note Pool: 884. 类表示一个工作进程池。它具有允许以几种不同方式将任务分
配到工作进程的方法。

例如

     from multiprocessing import Pool, TimeoutError
     import time
     import os

     def f(x):
         return x*x

     if __name__ == '__main__':
         # start 4 worker processes
         with Pool(processes=4) as pool:

             # print "[0, 1, 4,..., 81]"
             print(pool.map(f, range(10)))

             # print same numbers in arbitrary order
             for i in pool.imap_unordered(f, range(10)):
                 print(i)

             # evaluate "f(20)" asynchronously
             res = pool.apply_async(f, (20,))      # runs in *only* one process
             print(res.get(timeout=1))             # prints "400"

             # evaluate "os.getpid()" asynchronously
             res = pool.apply_async(os.getpid, ()) # runs in *only* one process
             print(res.get(timeout=1))             # prints the PID of that process

             # launching multiple evaluations asynchronously *may* use more processes
             multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)]
             print([res.get(timeout=1) for res in multiple_results])

             # make a single worker sleep for 10 secs
             res = pool.apply_async(time.sleep, (10,))
             try:
                 print(res.get(timeout=1))
             except TimeoutError:
                 print("We lacked patience and got a multiprocessing.TimeoutError")

             print("For the moment, the pool remains available for more work")

         # exiting the 'with'-block has stopped the pool
         print("Now the pool is closed and no longer available")

请注意，进程池的方法只能由创建它的进程使用。

     注解: 这个包中的功能要求子进程可以导入 ‘__main__’ 模块。虽然这在
     *note 编程指导: 2399. 中有描述，但还是需要提前说明一下。这意味着一
     些示例在交互式解释器中不起作用，比如 *note
     multiprocessing.pool.Pool: 884. 示例。例如:

          >>> from multiprocessing import Pool
          >>> p = Pool(5)
          >>> def f(x):
          ...     return x*x
          ...
          >>> with p:
          ...   p.map(f, [1,2,3])
          Process PoolWorker-1:
          Process PoolWorker-2:
          Process PoolWorker-3:
          Traceback (most recent call last):
          Traceback (most recent call last):
          Traceback (most recent call last):
          AttributeError: 'module' object has no attribute 'f'
          AttributeError: 'module' object has no attribute 'f'
          AttributeError: 'module' object has no attribute 'f'

     （如果尝试执行上面的代码，它会以一种半随机的方式将三个完整的堆栈内
     容交替输出，然后你只能以某种方式停止父进程。)


File: python.info,  Node: 参考,  Next: 编程指导,  Prev: 概述<9>,  Up: multiprocessing --- 基于进程的并行

5.17.2.8 参考
.............

*note multiprocessing: b8. 包主要复制了 *note threading: 10a. 模块的
API。

* Menu:

* Process 和异常::
* 管道和队列::
* 杂项: 杂项<3>.
* 连接对象（Connection）: 连接对象（Connection）<2>.
* 同步原语::
* 共享 ctypes 对象::
* 管理器::
* 代理对象::
* 进程池::
* 监听器及客户端::
* 认证密码::
* 日志记录: 日志记录<2>.
* multiprocessing.dummy 模块: multiprocessing dummy 模块.


File: python.info,  Node: Process 和异常,  Next: 管道和队列,  Up: 参考

5.17.2.9 ‘Process’ 和异常
.........................

 -- 类: multiprocessing.Process (group=None, target=None, name=None,
          args=(), kwargs={}, *, daemon=None)

     进程对象表示在单独进程中运行的活动。 *note Process: 3ba. 类拥有和
     *note threading.Thread: 235. 等价的大部分方法。

     应始终使用关键字参数调用构造函数。 `group' 应该始终是 ‘None’ ；它仅
     用于兼容 *note threading.Thread: 235. 。 `target' 是由 *note run():
     239b. 方法调用的可调用对象。它默认为 ‘None’ ，意味着什么都没有被调
     用。 `name' 是进程名称（有关详细信息，请参阅 *note name: 23af. ）。
     `args' 是目标调用的参数元组。 `kwargs' 是目标调用的关键字参数字典。
     如果提供，则键参数 `daemon' 将进程 *note daemon: 23b0. 标志设置为
     ‘True’ 或 ‘False’ 。如果是 ‘None’ （默认值），则该标志将从创建的进
     程继承。

     默认情况下，不会将任何参数传递给 `target' 。

     如果子类重写构造函数，它必须确保它在对进程执行任何其他操作之前调用
     基类构造函数（ ‘Process.__init__()’ ）。

     在 3.3 版更改: 加入 `daemon' 参数。

      -- 方法: run ()

          表示进程活动的方法。

          你可以在子类中重载此方法。标准 *note run(): 239b. 方法调用传递
          给对象构造函数的可调用对象作为目标参数（如果有），分别从
          `args' 和 `kwargs' 参数中获取顺序和关键字参数。

      -- 方法: start ()

          启动进程活动。

          这个方法每个进程对象最多只能调用一次。它会将对象的 *note
          run(): 239b. 方法安排在一个单独的进程中调用。

      -- 方法: join ([timeout])

          如果可选参数 `timeout' 是 ‘None’ （默认值），则该方法将阻塞，
          直到调用 *note join(): 23b2. 方法的进程终止。如果 `timeout' 是
          一个正数，它最多会阻塞 `timeout' 秒。请注意，如果进程终止或方
          法超时，则该方法返回 ‘None’ 。检查进程的 *note exitcode: 23b3.
          以确定它是否终止。

          一个进程可以被 join 多次。

          进程无法join自身，因为这会导致死锁。尝试在启动进程之前join进程
          是错误的。

      -- 属性: name

          进程的名称。该名称是一个字符串，仅用于识别目的。它没有语义。可
          以为多个进程指定相同的名称。

          初始名称由构造器设定。 如果没有为构造器提供显式名称，则会构造
          一个形式为 ’Process-N[1]:N[2]:...:N[k]’ 的名称，其中每个 N[k]
          是其父亲的第 N 个孩子。

      -- 方法: is_alive ()

          返回进程是否还活着。

          粗略地说，从 *note start(): 23b1. 方法返回到子进程终止之前，进
          程对象仍处于活动状态。

      -- 属性: daemon

          进程的守护标志，一个布尔值。这必须在 *note start(): 23b1. 被调
          用之前设置。

          初始值继承自创建进程。

          当进程退出时，它会尝试终止其所有守护进程子进程。

          请注意，不允许在守护进程中创建子进程。这是因为当守护进程由于父
          进程退出而中断时，其子进程会变成孤儿进程。 另外，这些 `不是'
          Unix 守护进程或服务，它们是正常进程，如果非守护进程已经退出，
          它们将被终止（并且不被合并）。

     除了 *note threading.Thread: 235. API ，*note Process: 3ba. 对象还
     支持以下属性和方法：

      -- 属性: pid

          返回进程ID。在生成该进程之前，这将是 ‘None’ 。

      -- 属性: exitcode

          子进程的退出代码。如果进程尚未终止，这将是 ‘None’ 。负值 `-N'
          表示子进程被信号 `N' 终止。

      -- 属性: authkey

          进程的身份验证密钥（字节字符串）。

          当 *note multiprocessing: b8. 初始化时，主进程使用 *note
          os.urandom(): 4d9. 分配一个随机字符串。

          当创建 *note Process: 3ba. 对象时，它将继承其父进程的身份验证
          密钥，尽管可以通过将 *note authkey: 23b6. 设置为另一个字节字符
          串来更改。

          参见 *note 认证密码: 23b7. 。

      -- 属性: sentinel

          系统对象的数字句柄，当进程结束时将变为 "ready" 。

          如果要使用 *note multiprocessing.connection.wait(): a2c. 一次
          等待多个事件，可以使用此值。否则调用 *note join(): 23b2. 更简
          单。

          在Windows上，这是一个操作系统句柄，可以与
          ‘WaitForSingleObject’ 和 ‘WaitForMultipleObjects’ 系列API调用
          一起使用。在Unix上，这是一个文件描述符，可以使用来自 *note
          select: e6. 模块的原语。

          3.3 新版功能.

      -- 方法: terminate ()

          终止进程。 在Unix上，这是使用 ‘SIGTERM’ 信号完成的；在
          Windows上使用 ‘TerminateProcess()’ 。 请注意，不会执行退出处理
          程序和finally子句等。

          请注意，进程的后代进程将不会被终止 —— 它们将简单地变成孤立的。

               警告: 如果在关联进程使用管道或队列时使用此方法，则管道或
               队列可能会损坏，并可能无法被其他进程使用。类似地，如果进
               程已获得锁或信号量等，则终止它可能导致其他进程死锁。

      -- 方法: kill ()

          与 *note terminate(): 23b8. 相同，但在Unix上使用 ‘SIGKILL’ 信
          号。

          3.7 新版功能.

      -- 方法: close ()

          关闭 *note Process: 3ba. 对象，释放与之关联的所有资源。如果底
          层进程仍在运行，则会引发 *note ValueError: 1fc. 。一旦 *note
          close(): 3b8. 成功返回， *note Process: 3ba. 对象的大多数其他
          方法和属性将引发 *note ValueError: 1fc. 。

          3.7 新版功能.

     注意 *note start(): 23b1. 、 *note join(): 23b2. 、 *note
     is_alive(): 23b4. 、 *note terminate(): 23b8. 和 *note exitcode:
     23b3. 方法只能由创建进程对象的进程调用。

     *note Process: 3ba. 一些方法的示例用法：

           >>> import multiprocessing, time, signal
           >>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
           >>> print(p, p.is_alive())
           <Process ... initial> False
           >>> p.start()
           >>> print(p, p.is_alive())
           <Process ... started> True
           >>> p.terminate()
           >>> time.sleep(0.1)
           >>> print(p, p.is_alive())
           <Process ... stopped exitcode=-SIGTERM> False
           >>> p.exitcode == -signal.SIGTERM
           True

 -- 例外: multiprocessing.ProcessError

     所有 *note multiprocessing: b8. 异常的基类。

 -- 例外: multiprocessing.BufferTooShort

     当提供的缓冲区对象太小而无法读取消息时，
     ‘Connection.recv_bytes_into()’ 引发的异常。

     如果 ‘e’ 是一个 *note BufferTooShort: 23ba. 实例，那么 ‘e.args[0]’
     将把消息作为字节字符串给出。

 -- 例外: multiprocessing.AuthenticationError

     出现身份验证错误时引发。

 -- 例外: multiprocessing.TimeoutError

     有超时的方法超时时引发。


File: python.info,  Node: 管道和队列,  Next: 杂项<3>,  Prev: Process 和异常,  Up: 参考

5.17.2.10 管道和队列
....................

使用多进程时，一般使用消息机制实现进程间通信，尽可能避免使用同步原语，例
如锁。

消息机制包含： *note Pipe(): 239f. (可以用于在两个进程间传递消息)，以及
队列(能够在多个生产者和消费者之间通信)。

*note Queue: 239e, *note SimpleQueue: 23be. 以及 *note JoinableQueue:
23bf. 都是多生产者，多消费者，并且实现了 FIFO 的队列类型，其表现与标准库
中的 *note queue.Queue: d20. 类相似。 不同之处在于 *note Queue: 239e. 缺
少标准库的 *note queue.Queue: d20. 从 Python 2.5 开始引入的 *note
task_done(): 23c0. 和 *note join(): 23c1. 方法。

如果你使用了 *note JoinableQueue: 23bf. ，那么你 `必须' 对每个已经移出队
列的任务调用 *note JoinableQueue.task_done(): 23c2.。 不然的话用于统计未
完成任务的信号量最终会溢出并抛出异常。

另外还可以通过使用一个管理器对象创建一个共享队列，详见 *note 管理器:
23c3. 。

     注解: *note multiprocessing: b8. 使用了普通的 *note queue.Empty:
     23c4. 和 *note queue.Full: 23c5. 异常去表示超时。 你需要从 *note
     queue: db. 中导入它们，因为它们并不在 *note multiprocessing: b8. 的
     命名空间中。

     注解: 当一个对象被放入一个队列中时，这个对象首先会被一个后台线程用
     pickle 序列化，并将序列化后的数据通过一个底层管道的管道传递到队列中
     。 这种做法会有点让人惊讶，但一般不会出现什么问题。 如果它们确实妨
     碍了你，你可以使用一个由管理器 *note manager: 23c3. 创建的队列替换
     它。

       1. 将一个对象放入一个空队列后，可能需要极小的延迟，队列的方法
          *note empty(): 23c6.  才会返回 *note False: 390. 。而 *note
          get_nowait(): 23c7. 可以不抛出 *note queue.Empty: 23c4. 直接返
          回。

       2. 如果有多个进程同时将对象放入队列，那么在队列的另一端接受到的对
          象可能是无序的。但是由同一个进程放入的多个对象的顺序在另一端输
          出时总是一样的。

     警告: 如果一个进程在尝试使用 *note Queue: 239e. 期间被 *note
     Process.terminate(): 23b8. 或 *note os.kill(): cfb. 调用终止了，那
     么队列中的数据很可能被破坏。 这可能导致其他进程在尝试使用该队列时发
     生异常。

     警告: 正如刚才提到的，如果一个子进程将一些对象放进队列中 (并且它没
     有用 *note JoinableQueue.cancel_join_thread: 23c8. 方法)，那么这个
     进程在所有缓冲区的对象被刷新进管道之前，是不会终止的。

     这意味着，除非你确定所有放入队列中的对象都已经被消费了，否则如果你
     试图等待这个进程，你可能会陷入死锁中。相似地，如果该子进程不是后台
     进程，那么父进程可能在试图等待所有非后台进程退出时挂起。

     注意用管理器创建的队列不存在这个问题，详见 *note 编程指导: 2399. 。

该 *note 例子: 23c9. 展示了如何使用队列实现进程间通信。

 -- 函数: multiprocessing.Pipe ([duplex])

     返回一对 ‘Connection`对象 ``(conn1, conn2)`’ ， 分别表示管道的两端
     。

     如果 `duplex' 被置为 ‘True’ (默认值)，那么该管道是双向的。如果
     `duplex' 被置为 ‘False’ ，那么该管道是单向的，即 ‘conn1’ 只能用于接
     收消息，而 ‘conn2’ 仅能用于发送消息。

 -- 类: multiprocessing.Queue ([maxsize])

     返回一个使用一个管道和少量锁和信号量实现的共享队列实例。当一个进程
     将一个对象放进队列中时，一个写入线程会启动并将对象从缓冲区写入管道
     中。

     一旦超时，将抛出标准库 *note queue: db. 模块中常见的异常 *note
     queue.Empty: 23c4. 和 *note queue.Full: 23c5.。

     除了 *note task_done(): 23c0. 和 *note join(): 23c1. 之外，*note
     Queue: 239e.  实现了标准库类 *note queue.Queue: d20. 中所有的方法。

      -- 方法: qsize ()

          返回队列的大致长度。由于多线程或者多进程的上下文，这个数字是不
          可靠的。

          注意，在 Unix 平台上，例如 Mac OS X ，这个方法可能会抛出 *note
          NotImplementedError: 617.  异常，因为该平台没有实现
          ‘sem_getvalue()’ 。

      -- 方法: empty ()

          如果队列是空的，返回 ‘True’ ，反之返回 ‘False’ 。 由于多线程或
          多进程的环境，该状态是不可靠的。

      -- 方法: full ()

          如果队列是满的，返回 ‘True’ ，反之返回 ‘False’ 。 由于多线程或
          多进程的环境，该状态是不可靠的。

      -- 方法: put (obj[, block[, timeout]])

          将 obj 放入队列。如果可选参数 `block' 是 ‘True’ (默认值) 而且
          `timeout' 是 ‘None’ (默认值), 将会阻塞当前进程，直到有空的缓冲
          槽。如果 `timeout' 是正数，将会在阻塞了最多 `timeout' 秒之后还
          是没有可用的缓冲槽时抛出 *note queue.Full: 23c5.  异常。反之
          (`block' 是 ‘False’ 时)，仅当有可用缓冲槽时才放入对象，否则抛
          出 *note queue.Full: 23c5. 异常 (在这种情形下 `timeout' 参数会
          被忽略)。

          在 3.8 版更改: 如果队列已经关闭，会抛出 *note ValueError: 1fc.
          而不是 *note AssertionError: 103e. 。

      -- 方法: put_nowait (obj)

          相当于 ‘put(obj, False)’。

      -- 方法: get ([block[, timeout]])

          从队列中取出并返回对象。如果可选参数 `block' 是 ‘True’ (默认值
          ) 而且 `timeout' 是 ‘None’ (默认值), 将会阻塞当前进程，直到队
          列中出现可用的对象。如果 `timeout' 是正数，将会在阻塞了最多
          `timeout' 秒之后还是没有可用的对象时抛出 *note queue.Empty:
          23c4. 异常。反之 (`block' 是 ‘False’ 时)，仅当有可用对象能够取
          出时返回，否则抛出 *note queue.Empty: 23c4. 异常 (在这种情形下
          `timeout' 参数会被忽略)。

          在 3.8 版更改: 如果队列已经关闭，会抛出 *note ValueError: 1fc.
          而不是 *note OSError: 1d4. 。

      -- 方法: get_nowait ()

          相当于 ‘get(False)’ 。

     *note multiprocessing.Queue: 239e. 类有一些在 *note queue.Queue:
     d20. 类中没有出现的方法。这些方法在大多数情形下并不是必须的。

      -- 方法: close ()

          指示当前进程将不会再往队列中放入对象。一旦所有缓冲区中的数据被
          写入管道之后，后台的线程会退出。这个方法在队列被gc回收时会自动
          调用。

      -- 方法: join_thread ()

          等待后台线程。这个方法仅在调用了 *note close(): 23cd. 方法之后
          可用。这会阻塞当前进程，直到后台线程退出，确保所有缓冲区中的数
          据都被写入管道中。

          默认情况下，如果一个不是队列创建者的进程试图退出，它会尝试等待
          这个队列的后台线程。这个进程可以使用 *note
          cancel_join_thread(): 23c8. 让 *note join_thread(): 23ce. 方法
          什么都不做直接跳过。

      -- 方法: cancel_join_thread ()

          防止 *note join_thread(): 23ce. 方法阻塞当前进程。具体而言，这
          防止进程退出时自动等待后台线程退出。详见 *note join_thread():
          23ce.。

          可能这个方法称为”‘allow_exit_without_flush()’“ 会更好。这有可
          能会导致正在排队进入队列的数据丢失，大多数情况下你不需要用到这
          个方法，仅当你不关心底层管道中可能丢失的数据，只是希望进程能够
          马上退出时使用。

          注解: 该类的功能依赖于宿主操作系统具有可用的共享信号量实现。否
          则该类将被禁用，任何试图实例化一个 *note Queue: 239e. 对象的操
          作都会抛出 *note ImportError: 33d. 异常，更多信息详见
          bpo-3770(1) 。后续说明的任何专用队列对象亦如此。

 -- 类: multiprocessing.SimpleQueue

     这是一个简化的 *note Queue: 239e. 类的实现，很像带锁的 *note Pipe:
     239f. 。

      -- 方法: empty ()

          如果队列为空返回 ‘True’ ，否则返回 ‘False’ 。

      -- 方法: get ()

          从队列中移出并返回一个对象。

      -- 方法: put (item)

          将 `item' 放入队列。

 -- 类: multiprocessing.JoinableQueue ([maxsize])

     *note JoinableQueue: 23bf. 类是 *note Queue: 239e. 的子类，额外添加
     了 *note task_done(): 23c2. 和 *note join(): 23d2. 方法。

      -- 方法: task_done ()

          指出之前进入队列的任务已经完成。由队列的消费者进程使用。对于每
          次调用 *note get(): 103d. 获取的任务，执行完成后调用 *note
          task_done(): 23c2. 告诉队列该任务已经处理完成。

          如果 *note join(): 23c1. 方法正在阻塞之中，该方法会在所有对象
          都被处理完的时候返回 (即对之前使用 *note put(): 103c. 放进队列
          中的所有对象都已经返回了对应的 *note task_done(): 23c2. ) 。

          如果被调用的次数多于放入队列中的项目数量，将引发 *note
          ValueError: 1fc. 异常 。

      -- 方法: join ()

          阻塞至队列中所有的元素都被接收和处理完毕。

          当条目添加到队列的时候，未完成任务的计数就会增加。每当消费者进
          程调用 *note task_done(): 23c2. 表示这个条目已经被回收，该条目
          所有工作已经完成，未完成计数就会减少。当未完成计数降到零的时候
          ， ‘join()’ 阻塞被解除。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3770


File: python.info,  Node: 杂项<3>,  Next: 连接对象（Connection）<2>,  Prev: 管道和队列,  Up: 参考

5.17.2.11 杂项
..............

 -- 函数: multiprocessing.active_children ()

     返回当前进程存活的子进程的列表。

     调用该方法有“等待”已经结束的进程的副作用。

 -- 函数: multiprocessing.cpu_count ()

     返回系统的CPU数量。

     该数量不同于当前进程可以使用的CPU数量。可用的CPU数量可以由
     ‘len(os.sched_getaffinity(0))’ 方法获得。

     可能引发 *note NotImplementedError: 617. 。

     参见
     ....

     *note os.cpu_count(): 888.

 -- 函数: multiprocessing.current_process ()

     返回与当前进程相对应的 *note Process: 3ba. 对象。

     和 *note threading.current_thread(): 2360. 相同。

 -- 函数: multiprocessing.parent_process ()

     返回父进程 *note Process: 3ba.  对象，和父进程调用 *note
     current_process(): 23d5. 返回的对象一样。如果一个进程已经是主进程，
     ‘parent_process’ 会返回 ‘None’.

     3.8 新版功能.

 -- 函数: multiprocessing.freeze_support ()

     为使用了 *note multiprocessing: b8.  的程序，提供冻结以产生 Windows
     可执行文件的支持。(在 `py2exe', `PyInstaller' 和 `cx_Freeze' 上测试
     通过)

     需要在 main 模块的 ‘if __name__ == '__main__'’ 该行之后马上调用该函
     数。例如：

          from multiprocessing import Process, freeze_support

          def f():
              print('hello world!')

          if __name__ == '__main__':
              freeze_support()
              Process(target=f).start()

     如果没有调用 ‘freeze_support()’ 在尝试运行被冻结的可执行文件时会抛
     出 *note RuntimeError: 2bb. 异常。

     对 ‘freeze_support()’ 的调用在非 Windows 平台上是无效的。如果该模块
     在 Windows 平台的 Python 解释器中正常运行 (该程序没有被冻结)， 调用
     ‘‘freeze_support()‘‘ 也是无效的。

 -- 函数: multiprocessing.get_all_start_methods ()

     返回支持的启动方法的列表，该列表的首项即为默认选项。可能的启动方法
     有 ‘'fork'’, ‘'spawn'’ 和‘‘’forkserver’‘。在 Windows 中，只有
     ``'spawn'’ 是可用的。Unix平台总是支持‘‘’fork’‘‘ 和‘‘’spawn’‘，且
     ``'fork'’ 是默认值。

     3.4 新版功能.

 -- 函数: multiprocessing.get_context (method=None)

     返回一个 Context 对象。该对象具有和 *note multiprocessing: b8. 模块
     相同的API。

     如果 `method' 设置成 ‘None’ 那么将返回默认上下文对象。否则
     `method'  应该是 ‘'fork'’, ‘'spawn'’, ‘'forkserver'’ 。 如果指定的
     启动方法不存在，将抛出 *note ValueError: 1fc.  异常。

     3.4 新版功能.

 -- 函数: multiprocessing.get_start_method (allow_none=False)

     返回启动进程时使用的启动方法名。

     如果启动方法已经固定，并且 `allow_none' 被设置成 False ，那么启动方
     法将被固定为默认的启动方法，并且返回其方法名。如果启动方法没有设定
     ，并且 `allow_none' 被设置成 True ，那么将返回 ‘None’  。

     返回值将为 ‘'fork'’ , ‘'spawn'’ , ‘'forkserver'’ 或者 ‘None’ 。
     ‘'fork'``是 Unix 的默认值， ``'spawn'’ 是 Windows 的默认值。

     3.4 新版功能.

 -- 函数: multiprocessing.set_executable ()

     设置在启动子进程时使用的 Python 解释器路径。 ( 默认使用 *note
     sys.executable: 275. ) 嵌入式编程人员可能需要这样做：

          set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))

     以使他们可以创建子进程。

     在 3.4 版更改: 现在在 Unix 平台上使用 ‘'spawn'’ 启动方法时支持调用
     该方法。

 -- 函数: multiprocessing.set_start_method (method)

     设置启动子进程的方法。 `method' 可以是 ‘'fork'’ , ‘'spawn'’ 或者
     ‘'forkserver'’ 。

     注意这最多只能调用一次，并且需要藏在 main 模块中，由 ‘if __name__
     == '__main__'’ 保护着。

     3.4 新版功能.

     注解: *note multiprocessing: b8. 并没有包含类似 *note
     threading.active_count(): 235e. , *note threading.enumerate():
     235f. , *note threading.settrace(): 2361. , *note
     threading.setprofile(): 2362, *note threading.Timer: ab6. , 或者
     *note threading.local: 2302. 的方法和类。


File: python.info,  Node: 连接对象（Connection）<2>,  Next: 同步原语,  Prev: 杂项<3>,  Up: 参考

5.17.2.12 连接对象（Connection）
................................

Connection 对象允许收发可以序列化的对象或字符串。它们可以看作面向消息的
连接套接字。

通常使用 *note Pipe: 239f. 创建 Connection 对象。详见 ： *note
监听器及客户端: 23da.

 -- 类: multiprocessing.connection.Connection

      -- 方法: send (obj)

          将一个对象发送到连接的另一端，可以用 *note recv(): 23dd. 读取
          。

          发送的对象必须是可以序列化的，过大的对象 ( 接近 32MiB+ ，这个
          值取决于操作系统 ) 有可能引发 *note ValueError: 1fc.  异常。

      -- 方法: recv ()

          返回一个由另一端使用 *note send(): 23dc. 发送的对象。该方法会
          一直阻塞直到接收到对象。 如果对端关闭了连接或者没有东西可接收
          ，将抛出 *note EOFError: c74. 异常。

      -- 方法: fileno ()

          返回由连接对象使用的描述符或者句柄。

      -- 方法: close ()

          关闭连接对象。

          当连接对象被垃圾回收时会自动调用。

      -- 方法: poll ([timeout])

          返回连接对象中是否有可以读取的数据。

          如果未指定 `timeout' ，此方法会马上返回。如果 `timeout' 是一个
          数字，则指定了最大阻塞的秒数。如果 `timeout' 是 ‘None’，那么将
          一直等待，不会超时。

          注意通过使用 *note multiprocessing.connection.wait(): a2c. 可
          以一次轮询多个连接对象。

      -- 方法: send_bytes (buffer[, offset[, size]])

          从一个 *note bytes-like object: 5f1. 对象中取出字节数组并作为
          一条完整消息发送。

          如果由 `offset'  给定了在 `buffer' 中读取数据的位置。 如果给定
          了 `size' ，那么将会从缓冲区中读取多个字节。 过大的缓冲区 ( 接
          近 32MiB+ ，此值依赖于操作系统 ) 有可能引发 *note ValueError:
          1fc.  异常。

      -- 方法: recv_bytes ([maxlength])

          以字符串形式返回一条从连接对象另一端发送过来的字节数据。此方法
          在接收到数据前将一直阻塞。 如果连接对象被对端关闭或者没有数据
          可读取，将抛出 *note EOFError: c74. 异常。

          如果给定了 `maxlength' 并且消息长于 `maxlength' 那么将抛出
          *note OSError: 1d4. 并且该连接对象将不再可读。

          在 3.3 版更改: 曾经该函数抛出 *note IOError: 99a. ，现在这是
          *note OSError: 1d4. 的别名。

      -- 方法: recv_bytes_into (buffer[, offset])

          将一条完整的字节数据消息读入 `buffer' 中并返回消息的字节数。 此
          方法在接收到数据前将一直阻塞。 如果连接对象被对端关闭或者没有
          数据可读取，将抛出 *note EOFError: c74.  异常。

          `buffer' must be a writable *note bytes-like object: 5f1.  If
          `offset' is given then the message will be written into the
          buffer from that position.  Offset must be a non-negative
          integer less than the length of `buffer' (in bytes).

          如果缓冲区太小，则将引发 ‘BufferTooShort’  异常，并且完整的消
          息将会存放在异常实例 ‘e’ 的 ‘e.args[0]’ 中。

     在 3.3 版更改: 现在连接对象自身可以通过 *note Connection.send():
     23dc. 和 *note Connection.recv(): 23dd. 在进程之间传递。

     3.3 新版功能: 连接对象现已支持上下文管理协议 – 参见 see *note
     上下文管理器类型: 1498. 。 *note __enter__(): 16ec. 返回连接对象，
     *note __exit__(): 16ee. 会调用 *note close(): 23df. 。

例如:

     >>> from multiprocessing import Pipe
     >>> a, b = Pipe()
     >>> a.send([1, 'hello', None])
     >>> b.recv()
     [1, 'hello', None]
     >>> b.send_bytes(b'thank you')
     >>> a.recv_bytes()
     b'thank you'
     >>> import array
     >>> arr1 = array.array('i', range(5))
     >>> arr2 = array.array('i', [0] * 10)
     >>> a.send_bytes(arr1)
     >>> count = b.recv_bytes_into(arr2)
     >>> assert count == len(arr1) * arr1.itemsize
     >>> arr2
     array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])

     警告: *note Connection.recv(): 23dd. 方法会自动解封它收到的数据，除
     非你能够信任发送消息的进程，否则此处可能有安全风险。

     因此， 除非连接对象是由 ‘Pipe()’ 产生的，否则你应该仅在使用了某种认
     证手段之后才使用 *note recv(): 23dd. 和 *note send(): 23dc. 方法。
     参考 *note 认证密码: 23b7.。

     警告: 如果一个进程在试图读写管道时被终止了，那么管道中的数据很可能
     是不完整的，因为此时可能无法确定消息的边界。


File: python.info,  Node: 同步原语,  Next: 共享 ctypes 对象,  Prev: 连接对象（Connection）<2>,  Up: 参考

5.17.2.13 同步原语
..................

通常来说同步原语在多进程环境中并不像它们在多线程环境中那么必要。参考
*note threading: 10a. 模块的文档。

注意可以使用管理器对象创建同步原语，参考 *note 管理器: 23c3. 。

 -- 类: multiprocessing.Barrier (parties[, action[, timeout]])

     类似 *note threading.Barrier: b67. 的栅栏对象。

     3.3 新版功能.

 -- 类: multiprocessing.BoundedSemaphore ([value])

     非常类似 *note threading.BoundedSemaphore: ab4. 的有界信号量对象。

     一个小小的不同在于，它的 ‘acquire’  方法的第一个参数名是和 *note
     Lock.acquire(): 23e5. 一样的 `block' 。

          注解: 在 Mac OS X 平台上， 该对象于 *note Semaphore: 23a7.  不
          同在于 ‘sem_getvalue()’ 方法并没有在该平台上实现。

 -- 类: multiprocessing.Condition ([lock])

     条件变量： *note threading.Condition: ab2. 的别名。

     指定的 `lock' 参数应该是 *note multiprocessing: b8. 模块中的 *note
     Lock: 23a5. 或者 *note RLock: 23a6. 对象。

     在 3.3 版更改: 新增了 *note wait_for(): 237f.  方法。

 -- 类: multiprocessing.Event

     A clone of *note threading.Event: ab5.

 -- 类: multiprocessing.Lock

     原始锁（非递归锁）对象，类似于 *note threading.Lock: 2374. 。一旦一
     个进程或者线程拿到了锁，后续的任何其他进程或线程的其他请求都会被阻
     塞直到锁被释放。任何进程或线程都可以释放锁。除非另有说明，否则
     *note multiprocessing.Lock: 23a5.  用于进程或者线程的概念和行为都和
     *note threading.Lock: 2374.  一致。

     注意 *note Lock: 23a5. 实际上是一个工厂函数。它返回由默认上下文初始
     化的 ‘multiprocessing.synchronize.Lock’  对象。

     *note Lock: 23a5. supports the *note context manager: 571. protocol
     and thus may be used in *note with: 6f2. statements.

      -- 方法: acquire (block=True, timeout=None)

          可以阻塞或非阻塞地获得锁。

          如果 `block' 参数被设为 ‘True’ ( 默认值 ) ， 对该方法的调用在
          锁处于释放状态之前都会阻塞，然后将锁设置为锁住状态并返回
          ‘True’ 。需要注意的是第一个参数名与 *note
          threading.Lock.acquire(): 775. 的不同。

          如果 `block' 参数被设置成 ‘False’ ，方法的调用将不会阻塞。 如
          果锁当前处于锁住状态，将返回 ‘False’ ； 否则将锁设置成锁住状态
          ，并返回 ‘True’ 。

          当 `timeout' 是一个正浮点数时，会在等待锁的过程中最多阻塞等待
          `timeout' 秒，当 `timeout' 是负数时，效果和 `timeout' 为0时一
          样，当 `timeout' 是 ‘None’ （默认值）时，等待时间是无限长。需
          要注意的是，对于 `timeout' 参数是负数和 ‘None’ 的情况, 其行为
          与 *note threading.Lock.acquire(): 775. 是不一样的。当 `block'
          参数 为 ‘False’ 时， `timeout' 并没有实际用处，会直接忽略。否
          则，函数会在拿到锁后返回 ‘True’ 或者 超时没拿到锁后返回
          ‘False’ 。

      -- 方法: release ()

          释放锁，可以在任何进程、线程使用，并不限于锁的拥有者。

          当尝试释放一个没有被持有的锁时，会抛出 *note ValueError: 1fc.
          异常，除此之外其行为与 *note threading.Lock.release(): 2372. 一
          样。

 -- 类: multiprocessing.RLock

     递归锁对象: 类似于 *note threading.RLock: bf7. 。递归锁必须由持有线
     程、进程亲自释放。如果某个进程或者线程拿到了递归锁，这个进程或者线
     程可以再次拿到这个锁而不需要等待。但是这个进程或者线程的拿锁操作和
     释放锁操作的次数必须相同。

     注意 *note RLock: 23a6. 是一个工厂函数，调用后返回一个使用默认
     context 初始化的 ‘multiprocessing.synchronize.RLock’ 实例。

     *note RLock: 23a6. 支持 *note context manager: 571. 协议，因此可在
     *note with: 6f2. 语句内使用。

      -- 方法: acquire (block=True, timeout=None)

          可以阻塞或非阻塞地获得锁。

          当 `block' 参数设置为 ‘True’ 时，会一直阻塞直到锁处于空闲状态
          （没有被任何进程、线程拥有），除非当前进程或线程已经拥有了这把
          锁。然后当前进程/线程会持有这把锁（在锁没有其他持有者的情况下
          ），锁内的递归等级加一，并返回 ‘True’ . 注意， 这个函数第一个
          参数的行为和 *note threading.RLock.acquire(): 776. 的实现有几
          个不同点，包括参数名本身。

          当 `block' 参数是 ‘False’ , 将不会阻塞，如果此时锁被其他进程或
          者线程持有，当前进程、线程获取锁操作失败，锁的递归等级也不会改
          变，函数返回 ‘False’ , 如果当前锁已经处于释放状态，则当前进程
          、线程则会拿到锁，并且锁内的递归等级加一，函数返回 ‘True’ 。

          `timeout' 参数的使用方法及行为与 *note Lock.acquire(): 23e5. 一
          样。但是要注意 `timeout' 的其中一些行为和 *note
          threading.RLock.acquire(): 776. 中实现的行为是不同的。

      -- 方法: release ()

          释放锁，使锁内的递归等级减一。如果释放后锁内的递归等级降低为
          0，则会重置锁的状态为释放状态（即没有被任何进程、线程持有），
          重置后如果有有其他进程和线程在等待这把锁，他们中的一个会获得这
          个锁而继续运行。如果释放后锁内的递归等级还没到达0，则这个锁仍
          将保持未释放状态且当前进程和线程仍然是持有者。

          只有当前进程或线程是锁的持有者时，才允许调用这个方法。如果当前
          进程或线程不是这个锁的拥有者，或者这个锁处于已释放的状态(即没
          有任何拥有者)，调用这个方法会抛出 *note AssertionError: 103e.
          异常。注意这里抛出的异常类型和 *note
          threading.RLock.release(): 2378. 中实现的行为不一样。

 -- 类: multiprocessing.Semaphore ([value])

     一种信号量对象: 类似于 *note threading.Semaphore: ab3.

     一个小小的不同在于，它的 ‘acquire’  方法的第一个参数名是和 *note
     Lock.acquire(): 23e5. 一样的 `block' 。

     注解: 在 Mac OS X 上，不支持 ‘sem_timedwait’ ，所以，调用
     ‘acquire()’ 时如果使用 timeout 参数，会通过循环sleep来模拟这个函数
     的行为。

     注解: 假如信号 SIGINT 是来自于 ‘Ctrl-C’ ，并且主线程被
     ‘BoundedSemaphore.acquire()’, *note Lock.acquire(): 23e5, *note
     RLock.acquire(): 23e7, ‘Semaphore.acquire()’, ‘Condition.acquire()’
     或 ‘Condition.wait()’ 阻塞，则调用会立即中断同时抛出 *note
     KeyboardInterrupt: 198. 异常。

     这和 *note threading: 10a. 的行为不同，此模块中当执行对应的阻塞式调
     用时，SIGINT 会被忽略。

     注解: 这个包的某些功能依赖于宿主机系统的共享信号量的实现，如果系统
     没有这个特性， ‘multiprocessing.synchronize’ 会被禁用，尝试导入这个
     模块会引发 *note ImportError: 33d. 异常，详细信息请查看 bpo-3770(1)
     。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3770


File: python.info,  Node: 共享 ctypes 对象,  Next: 管理器,  Prev: 同步原语,  Up: 参考

5.17.2.14 共享 ‘ctypes’ 对象
............................

在共享内存上创建可被子进程继承的共享对象时是可行的。

 -- 函数: multiprocessing.Value (typecode_or_type, *args, lock=True)

     返回一个从共享内存上创建的 *note ctypes: 2b. 对象。默认情况下返回的
     对象实际上是经过了同步器包装过的。可以通过 *note Value: 23a2. 的
     `value' 属性访问这个对象本身。

     `typecode_or_type' 指明了返回的对象类型: 它可能是一个 ctypes 类型或
     者 *note array: 7.  模块中每个类型对应的单字符长度的字符串。
     `*args' 会透传给这个类的构造函数。

     如果 `lock' 参数是 ‘True’ （默认值）, 将会新建一个递归锁用于同步对
     于此值的访问操作。 如果 `lock' 是 *note Lock: 23a5. 或者 *note
     RLock: 23a6. 对象，那么这个传入的锁将会用于同步对这个值的访问操作，
     如果 `lock' 是 ‘False’ , 那么对这个对象的访问将没有锁保护，也就是说
     这个变量不是进程安全的。

     诸如 ‘+=’ 这类的操作会引发独立的读操作和写操作，也就是说这类操作符
     并不具有原子性。所以，如果你想让递增共享变量的操作具有原子性，仅仅
     以这样的方式并不能达到要求:

          counter.value += 1

     共享对象内部关联的锁是递归锁(默认情况下就是)的情况下， 你可以采用这
     种方式

          with counter.get_lock():
              counter.value += 1

     注意 `lock' 只能是命名参数。

 -- 函数: multiprocessing.Array (typecode_or_type, size_or_initializer,
          *, lock=True)

     从共享内存中申请并返回一个具有ctypes类型的数组对象。默认情况下返回
     值实际上是被同步器包装过的数组对象。

     `typecode_or_type' 指明了返回的数组中的元素类型: 它可能是一个
     ctypes 类型或者 *note array: 7. 模块中每个类型对应的单字符长度的字
     符串。 如果 `size_or_initializer' 是一个整数，那就会当做数组的长度
     ，并且整个数组的内存会初始化为0。否则，如果 `size_or_initializer' 会
     被当成一个序列用于初始化数组中的每一个元素，并且会根据元素个数自动
     判断数组的长度。

     如果 `lock' 为 ‘True’ (默认值) 则将创建一个新的锁对象用于同步对值的
     访问。 如果 `lock' 为一个 *note Lock: 23a5. 或 *note RLock: 23a6. 对
     象则该对象将被用于同步对值的访问。 如果 `lock' 为 ‘False’ 则对返回
     对象的访问将不会自动得到锁的保护，也就是说它不是“进程安全的”。

     请注意 `lock' 是一个仅限关键字参数。

     请注意 *note ctypes.c_char: 22ce. 的数组具有 `value' 和 `raw' 属性
     ，允许被用来保存和提取字符串。

* Menu:

* multiprocessing.sharedctypes 模块: multiprocessing sharedctypes 模块.


File: python.info,  Node: multiprocessing sharedctypes 模块,  Up: 共享 ctypes 对象

5.17.2.15 ‘multiprocessing.sharedctypes’ 模块
.............................................

*note multiprocessing.sharedctypes: be. 模块提供了一些函数，用于分配来自
共享内存的、可被子进程继承的 *note ctypes: 2b. 对象。

     注解: 虽然可以将指针存储在共享内存中，但请记住它所引用的是特定进程
     地址空间中的位置。 而且，指针很可能在第二个进程的上下文中无效，尝试
     从第二个进程对指针进行解引用可能会导致崩溃。

 -- 函数: multiprocessing.sharedctypes.RawArray (typecode_or_type,
          size_or_initializer)

     从共享内存中申请并返回一个 ctypes 数组。

     `typecode_or_type' 指明了返回的数组中的元素类型: 它可能是一个
     ctypes 类型或者 *note array: 7. 模块中使用的类型字符。 如果
     `size_or_initializer' 是一个整数，那就会当做数组的长度，并且整个数
     组的内存会初始化为0。否则，如果 `size_or_initializer' 会被当成一个
     序列用于初始化数组中的每一个元素，并且会根据元素个数自动判断数组的
     长度。

     注意对元素的访问、赋值操作可能是非原子操作 - 使用 *note Array():
     23ec. , 从而借助其中的锁保证操作的原子性。

 -- 函数: multiprocessing.sharedctypes.RawValue (typecode_or_type,
          *args)

     从共享内存中申请并返回一个 ctypes 对象。

     `typecode_or_type' 指明了返回的对象类型: 它可能是一个 ctypes 类型或
     者 *note array: 7.  模块中每个类型对应的单字符长度的字符串。
     `*args' 会透传给这个类的构造函数。

     注意对 value 的访问、赋值操作可能是非原子操作 - 使用 *note Value():
     23ee. ，从而借助其中的锁保证操作的原子性。

     请注意 *note ctypes.c_char: 22ce. 的数组具有 `value' 和 `raw' 属性
     ，允许被用来保存和提取字符串 - 请查看 *note ctypes: 2b. 文档。

 -- 函数: multiprocessing.sharedctypes.Array (typecode_or_type,
          size_or_initializer, *, lock=True)

     返回一个纯 ctypes 数组, 或者在此之上经过同步器包装过的进程安全的对
     象，这取决于 `lock' 参数的值，除此之外，和 *note RawArray(): 23eb.
     一样。

     如果 `lock' 为 ‘True’ (默认值) 则将创建一个新的锁对象用于同步对值的
     访问。 如果 `lock' 为一个 *note Lock: 23a5. 或 *note RLock: 23a6. 对
     象则该对象将被用于同步对值的访问。 如果 `lock' 为 ‘False’ 则对所返
     回对象的访问将不会自动得到锁的保护，也就是说它将不是“进程安全的”。

     注意 `lock' 只能是命名参数。

 -- 函数: multiprocessing.sharedctypes.Value (typecode_or_type, *args,
          lock=True)

     返回一个纯 ctypes 数组, 或者在此之上经过同步器包装过的进程安全的对
     象，这取决于 `lock' 参数的值，除此之外，和 ‘RawArray()’ 一样。

     如果 `lock' 为 ‘True’ (默认值) 则将创建一个新的锁对象用于同步对值的
     访问。 如果 `lock' 为一个 *note Lock: 23a5. 或 *note RLock: 23a6. 对
     象则该对象将被用于同步对值的访问。 如果 `lock' 为 ‘False’ 则对所返
     回对象的访问将不会自动得到锁的保护，也就是说它将不是“进程安全的”。

     注意 `lock' 只能是命名参数。

 -- 函数: multiprocessing.sharedctypes.copy (obj)

     从共享内存中申请一片空间将 ctypes 对象 `obj' 过来，然后返回一个新的
     ctypes 对象。

 -- 函数: multiprocessing.sharedctypes.synchronized (obj[, lock])

     将一个 ctypes 对象包装为进程安全的对象并返回，使用 `lock' 同步对于
     它的操作。如果 `lock' 是 ‘None’ (默认值) ，则会自动创建一个 *note
     multiprocessing.RLock: 23a6. 对象。

     同步器包装后的对象会在原有对象基础上额外增加两个方法: ‘get_obj()’ 返
     回被包装的对象， ‘get_lock()’ 返回内部用于同步的锁。

     需要注意的是，访问包装后的ctypes对象会比直接访问原来的纯 ctypes 对
     象慢得多。

     在 3.5 版更改: 同步器包装后的对象支持 *note context manager: 571. 协
     议。

下面的表格对比了创建普通ctypes对象和基于共享内存上创建共享ctypes对象的语
法。（表格中的 ‘MyStruct’ 是 *note ctypes.Structure: 22ec. 的子类）

ctypes                   使用类型的共享ctypes           使用 typecode 的共享 ctypes
                                                        
----------------------------------------------------------------------------------------
                                                        
c_double(2.4)            RawValue(c_double, 2.4)        RawValue(’d’, 2.4)
                                                        
                                                        
MyStruct(4, 6)           RawValue(MyStruct, 4, 6)
                         
                                                        
(c_short * 7)()          RawArray(c_short, 7)           RawArray(’h’, 7)
                                                        
                                                        
(c_int * 3)(9, 2, 8)     RawArray(c_int, (9, 2, 8))     RawArray(’i’, (9, 2, 8))
                                                        

下面是一个在子进程中修改多个ctypes对象的例子。

     from multiprocessing import Process, Lock
     from multiprocessing.sharedctypes import Value, Array
     from ctypes import Structure, c_double

     class Point(Structure):
         _fields_ = [('x', c_double), ('y', c_double)]

     def modify(n, x, s, A):
         n.value **= 2
         x.value **= 2
         s.value = s.value.upper()
         for a in A:
             a.x **= 2
             a.y **= 2

     if __name__ == '__main__':
         lock = Lock()

         n = Value('i', 7)
         x = Value(c_double, 1.0/3.0, lock=False)
         s = Array('c', b'hello world', lock=lock)
         A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)

         p = Process(target=modify, args=(n, x, s, A))
         p.start()
         p.join()

         print(n.value)
         print(x.value)
         print(s.value)
         print([(a.x, a.y) for a in A])

输出如下

     49
     0.1111111111111111
     HELLO WORLD
     [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]


File: python.info,  Node: 管理器,  Next: 代理对象,  Prev: 共享 ctypes 对象,  Up: 参考

5.17.2.16 管理器
................

管理器提供了一种创建共享数据的方法，从而可以在不同进程中共享，甚至可以通
过网络跨机器共享数据。管理器维护一个用于管理 `共享对象' 的服务。其他进程
可以通过代理访问这些共享对象。

 -- 函数: multiprocessing.Manager ()

     返回一个已启动的 *note SyncManager: 23f2. 管理器对象，这个对象可以
     用于在不同进程中共享数据。返回的管理器对象对应了一个已经启动的子进
     程，并且拥有一系列方法可以用于创建共享对象、返回对应的代理。

当管理器被垃圾回收或者父进程退出时，管理器进程会立即退出。管理器类定义在
*note multiprocessing.managers: bb. 模块:

 -- 类: multiprocessing.managers.BaseManager ([address[, authkey]])

     创建一个 BaseManager 对象。

     一旦创建，应该及时调用 *note start(): 23f4. 或者
     ‘get_server().serve_forever()’ 以确保管理器对象对应的管理进程已经启
     动。

     `address' 是管理器服务进程监听的地址。如果 `address' 是 ‘None’ ,则
     允许和任意主机的请求建立连接。

     `authkey' 是认证标识，用于检查连接服务进程的请求合法性。如果
     `authkey' 是 ‘None’, 则会使用 ‘current_process().authkey’ , 否则，
     就使用 `authkey' , 需要保证它必须是 byte 类型的字符串。

      -- 方法: start ([initializer[, initargs]])

          为管理器开启一个子进程，如果 `initializer' 不是 ‘None’ , 子进
          程在启动时将会调用 ‘initializer(*initargs)’ 。

      -- 方法: get_server ()

          返回一个 ‘Server’  对象，它是管理器在后台控制的真实的服务。
          ‘Server’  对象拥有 ‘serve_forever()’ 方法。

               >>> from multiprocessing.managers import BaseManager
               >>> manager = BaseManager(address=('', 50000), authkey=b'abc')
               >>> server = manager.get_server()
               >>> server.serve_forever()

          ‘Server’ 额外拥有一个 *note address: 23f6. 属性。

      -- 方法: connect ()

          将本地管理器对象连接到一个远程管理器进程:

               >>> from multiprocessing.managers import BaseManager
               >>> m = BaseManager(address=('127.0.0.1', 50000), authkey=b'abc')
               >>> m.connect()

      -- 方法: shutdown ()

          停止管理器的进程。这个方法只能用于已经使用 *note start():
          23f4. 启动的服务进程。

          它可以被多次调用。

      -- 方法: register (typeid[, callable[, proxytype[, exposed[,
               method_to_typeid[, create_method]]]]])

          一个 classmethod，可以将一个类型或者可调用对象注册到管理器类。

          `typeid' 是一种 "类型标识符"，用于唯一表示某种共享对象类型，必
          须是一个字符串。

          `callable' 是一个用来为此类型标识符创建对象的可调用对象。如果
          一个管理器实例将使用 *note connect(): 23f7. 方法连接到服务器，
          或者 `create_method' 参数为 ‘False’，那么这里可留下 ‘None’。

          `proxytype' 是 *note BaseProxy: 23fa.  的子类，可以根据
          `typeid' 为共享对象创建一个代理，如果是 ‘None’ , 则会自动创建
          一个代理类。

          `exposed' 是一个函数名组成的序列，用来指明只有这些方法可以使用
          *note BaseProxy._callmethod(): 23fb. 代理。(如果 `exposed' 是
          ‘None’, 则会在 ‘proxytype._exposed_’ 存在的情况下转而使用它) 当
          暴露的方法列表没有指定的时候，共享对象的所有 “公共方法” 都会被
          代理。（这里的“公共方法”是指所有拥有 *note __call__(): 143e. 方
          法并且不是以 ‘'_'’ 开头的属性）

          `method_to_typeid' 是一个映射，用来指定那些应该返回代理对象的
          暴露方法所返回的类型。（如果 `method_to_typeid' 是 ‘None’, 则
          ‘proxytype._method_to_typeid_’ 会在存在的情况下被使用）如果方
          法名称不在这个映射中或者映射是 ‘None’ ,则方法返回的对象会是一
          个值拷贝。

          `create_method' 指明，是否要创建一个以 `typeid' 命名并返回一个
          代理对象的方法，这个函数会被服务进程用于创建共享对象，默认为
          ‘True’ 。

     *note BaseManager: 23f3. 实例也有一个只读属性。

      -- 属性: address

          管理器所用的地址。

     在 3.3 版更改: 管理器对象支持上下文管理协议 - 查看 *note
     上下文管理器类型: 1498. 。*note __enter__(): 16ec. 启动服务进程（如
     果它还没有启动）并且返回管理器对象， *note __exit__(): 16ee. 会调用
     *note shutdown(): 23f8. 。

     在之前的版本中，如果管理器服务进程没有启动， *note __enter__():
     16ec. 不会负责启动它。

 -- 类: multiprocessing.managers.SyncManager

     *note BaseManager: 23f3. 的子类，可用于进程的同步。这个类型的对象使
     用 ‘multiprocessing.Manager()’ 创建。

     它拥有一系列方法，可以为大部分常用数据类型创建并返回 *note
     代理对象: 56e. 代理，用于进程间同步。甚至包括共享列表和字典。

      -- 方法: Barrier (parties[, action[, timeout]])

          创建一个共享的 *note threading.Barrier: b67. 对象并返回它的代
          理。

          3.3 新版功能.

      -- 方法: BoundedSemaphore ([value])

          创建一个共享的 *note threading.BoundedSemaphore: ab4. 对象并返
          回它的代理。

      -- 方法: Condition ([lock])

          创建一个共享的 *note threading.Condition: ab2. 对象并返回它的
          代理。

          如果提供了 `lock' 参数，那它必须是 *note threading.Lock: 2374.
          或 *note threading.RLock: bf7. 的代理对象。

          在 3.3 版更改: 新增了 *note wait_for(): 237f.  方法。

      -- 方法: Event ()

          创建一个共享的 *note threading.Event: ab5. 对象并返回它的代理
          。

      -- 方法: Lock ()

          创建一个共享的 *note threading.Lock: 2374. 对象并返回它的代理
          。

      -- 方法: Namespace ()

          创建一个共享的 *note Namespace: 23a4. 对象并返回它的代理。

      -- 方法: Queue ([maxsize])

          创建一个共享的 *note queue.Queue: d20. 对象并返回它的代理。

      -- 方法: RLock ()

          创建一个共享的 *note threading.RLock: bf7. 对象并返回它的代理
          。

      -- 方法: Semaphore ([value])

          创建一个共享的 *note threading.Semaphore: ab3. 对象并返回它的
          代理。

      -- 方法: Array (typecode, sequence)

          创建一个数组并返回它的代理。

      -- 方法: Value (typecode, value)

          创建一个具有可写 ‘value’ 属性的对象并返回它的代理。

      -- 方法: dict ()

      -- 方法: dict (mapping)

      -- 方法: dict (sequence)

          创建一个共享的 *note dict: 1b9. 对象并返回它的代理。

      -- 方法: list ()

      -- 方法: list (sequence)

          创建一个共享的 *note list: 263. 对象并返回它的代理。

     在 3.6 版更改: 共享对象能够嵌套。例如, 共享的容器对象如共享列表，可
     以包含另一个共享对象，他们全都会在 *note SyncManager: 23f2. 中进行
     管理和同步。

 -- 类: multiprocessing.managers.Namespace

     一个可以注册到 *note SyncManager: 23f2. 的类型。

     命名空间对象没有公共方法，但是拥有可写的属性。直接print会显示所有属
     性的值。

     值得一提的是，当对命名空间对象使用代理的时候，访问所有名称以 ‘'_'’
     开头的属性都只是代理器上的属性，而不是命名空间对象的属性。

          >>> manager = multiprocessing.Manager()
          >>> Global = manager.Namespace()
          >>> Global.x = 10
          >>> Global.y = 'hello'
          >>> Global._z = 12.3    # this is an attribute of the proxy
          >>> print(Global)
          Namespace(x=10, y='hello')

* Menu:

* 自定义管理器::
* 使用远程管理器::


File: python.info,  Node: 自定义管理器,  Next: 使用远程管理器,  Up: 管理器

5.17.2.17 自定义管理器
......................

要创建一个自定义的管理器，需要新建一个 *note BaseManager: 23f3. 的子类，
然后使用这个管理器类上的 *note register(): 23f9. 类方法将新类型或者可调
用方法注册上去。例如:

     from multiprocessing.managers import BaseManager

     class MathsClass:
         def add(self, x, y):
             return x + y
         def mul(self, x, y):
             return x * y

     class MyManager(BaseManager):
         pass

     MyManager.register('Maths', MathsClass)

     if __name__ == '__main__':
         with MyManager() as manager:
             maths = manager.Maths()
             print(maths.add(4, 3))         # prints 7
             print(maths.mul(7, 8))         # prints 56


File: python.info,  Node: 使用远程管理器,  Prev: 自定义管理器,  Up: 管理器

5.17.2.18 使用远程管理器
........................

可以将管理器服务运行在一台机器上，然后使用客户端从其他机器上访问。(假设
它们的防火墙允许)

运行下面的代码可以启动一个服务，此付包含了一个共享队列，允许远程客户端访
问:

     >>> from multiprocessing.managers import BaseManager
     >>> from queue import Queue
     >>> queue = Queue()
     >>> class QueueManager(BaseManager): pass
     >>> QueueManager.register('get_queue', callable=lambda:queue)
     >>> m = QueueManager(address=('', 50000), authkey=b'abracadabra')
     >>> s = m.get_server()
     >>> s.serve_forever()

远程客户端可以通过下面的方式访问服务:

     >>> from multiprocessing.managers import BaseManager
     >>> class QueueManager(BaseManager): pass
     >>> QueueManager.register('get_queue')
     >>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra')
     >>> m.connect()
     >>> queue = m.get_queue()
     >>> queue.put('hello')

也可以通过下面的方式:

     >>> from multiprocessing.managers import BaseManager
     >>> class QueueManager(BaseManager): pass
     >>> QueueManager.register('get_queue')
     >>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra')
     >>> m.connect()
     >>> queue = m.get_queue()
     >>> queue.get()
     'hello'

本地进程也可以访问这个队列，利用上面的客户端代码通过远程方式访问:

     >>> from multiprocessing import Process, Queue
     >>> from multiprocessing.managers import BaseManager
     >>> class Worker(Process):
     ...     def __init__(self, q):
     ...         self.q = q
     ...         super().__init__()
     ...     def run(self):
     ...         self.q.put('local hello')
     ...
     >>> queue = Queue()
     >>> w = Worker(queue)
     >>> w.start()
     >>> class QueueManager(BaseManager): pass
     ...
     >>> QueueManager.register('get_queue', callable=lambda: queue)
     >>> m = QueueManager(address=('', 50000), authkey=b'abracadabra')
     >>> s = m.get_server()
     >>> s.serve_forever()


File: python.info,  Node: 代理对象,  Next: 进程池,  Prev: 管理器,  Up: 参考

5.17.2.19 代理对象
..................

代理是一个 `指向' 其他共享对象的对象，这个对象(很可能)在另外一个进程中。
共享对象也可以说是代理 `指涉' 的对象。多个代理对象可能指向同一个指涉对象
。

代理对象代理了指涉对象的一系列方法调用(虽然并不是指涉对象的每个方法都有
必要被代理)。通过这种方式，代理的使用方法可以和它的指涉对象一样:

     >>> from multiprocessing import Manager
     >>> manager = Manager()
     >>> l = manager.list([i*i for i in range(10)])
     >>> print(l)
     [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
     >>> print(repr(l))
     <ListProxy object, typeid 'list' at 0x...>
     >>> l[4]
     16
     >>> l[2:5]
     [4, 9, 16]

注意，对代理使用 *note str(): 339. 函数会返回指涉对象的字符串表示，但是
*note repr(): 7d5. 却会返回代理本身的内部字符串表示。

被代理的对象很重要的一点是必须可以被序列化，这样才能允许他们在进程间传递
。因此，指涉对象可以包含 *note 代理对象: 56e. 。这允许管理器中列表、字典
或者其他 *note 代理对象: 56e. 对象之间的嵌套。

     >>> a = manager.list()
     >>> b = manager.list()
     >>> a.append(b)         # referent of a now contains referent of b
     >>> print(a, b)
     [<ListProxy object, typeid 'list' at ...>] []
     >>> b.append('hello')
     >>> print(a[0], b)
     ['hello'] ['hello']

类似地，字典和列表代理也可以相互嵌套:

     >>> l_outer = manager.list([ manager.dict() for i in range(2) ])
     >>> d_first_inner = l_outer[0]
     >>> d_first_inner['a'] = 1
     >>> d_first_inner['b'] = 2
     >>> l_outer[1]['c'] = 3
     >>> l_outer[1]['z'] = 26
     >>> print(l_outer[0])
     {'a': 1, 'b': 2}
     >>> print(l_outer[1])
     {'c': 3, 'z': 26}

如果指涉对象包含了普通 *note list: 263. 或 *note dict: 1b9. 对象，对这些
内部可变对象的修改不会通过管理器传播，因为代理无法得知被包含的值什么时候
被修改了。但是把存放在容器代理中的值本身是会通过管理器传播的（会触发代理
对象中的 ‘__setitem__’ ）从而有效修改这些对象，所以可以把修改过的值重新
赋值给容器代理:

     # create a list proxy and append a mutable object (a dictionary)
     lproxy = manager.list()
     lproxy.append({})
     # now mutate the dictionary
     d = lproxy[0]
     d['a'] = 1
     d['b'] = 2
     # at this point, the changes to d are not yet synced, but by
     # updating the dictionary, the proxy is notified of the change
     lproxy[0] = d

在大多是使用情形下，这种实现方式并不比嵌套 *note 代理对象: 56e. 方便，但
是依然演示了对于同步的一种控制级别。

     注解: *note multiprocessing: b8. 中的代理类并没有提供任何对于代理值
     比较的支持。所以，我们会得到如下结果:

          >>> manager.list([1,2,3]) == [1,2,3]
          False

     当需要比较值的时候，应该替换为使用指涉对象的拷贝。

 -- 类: multiprocessing.managers.BaseProxy

     代理对象是 *note BaseProxy: 23fa. 派生类的实例。

      -- 方法: _callmethod (methodname[, args[, kwds]])

          调用指涉对象的方法并返回结果。

          如果 ‘proxy’ 是一个代理且其指涉的是 ‘obj’ , 那么下面的表达式:

               proxy._callmethod(methodname, args, kwds)

          相当于求取以下表达式的值:

               getattr(obj, methodname)(*args, **kwds)

          于管理器进程。

          返回结果会是一个值拷贝或者一个新的共享对象的代理 - 见函数
          *note BaseManager.register(): 23f9. 中关于参数
          `method_to_typeid' 的文档。

          如果这个调用熬出了异常，则这个异常会被 *note _callmethod():
          23fb. 透传出来。如果是管理器进程本身抛出的一些其他异常，则会被
          *note _callmethod(): 23fb. 转换为 ‘RemoteError’ 异常重新抛出。

          特别注意，如果 `methodname' 没有 `暴露' 出来，将会引发一个异常
          。

          *note _callmethod(): 23fb. 的一个使用示例:

               >>> l = manager.list(range(10))
               >>> l._callmethod('__len__')
               10
               >>> l._callmethod('__getitem__', (slice(2, 7),)) # equivalent to l[2:7]
               [2, 3, 4, 5, 6]
               >>> l._callmethod('__getitem__', (20,))          # equivalent to l[20]
               Traceback (most recent call last):
               ...
               IndexError: list index out of range

      -- 方法: _getvalue ()

          返回指涉对象的一份拷贝。

          如果指涉对象无法序列化，则会抛出一个异常。

      -- 方法: __repr__ ()

          返回代理对象的内部字符串表示。

      -- 方法: __str__ ()

          返回指涉对象的内部字符串表示。

* Menu:

* 清理::


File: python.info,  Node: 清理,  Up: 代理对象

5.17.2.20 清理
..............

代理对象使用了一个弱引用回调函数，当它被垃圾回收时，会将自己从拥有此指涉
对象的管理器上反注册，

当共享对象没有被任何代理器引用时，会被管理器进程删除。


File: python.info,  Node: 进程池,  Next: 监听器及客户端,  Prev: 代理对象,  Up: 参考

5.17.2.21 进程池
................

可以创建一个进程池，它将使用 *note Pool: 884. 类执行提交给它的任务。

 -- 类: multiprocessing.pool.Pool ([processes[, initializer[, initargs[,
          maxtasksperchild[, context]]]]])

     一个进程池对象，它控制可以提交作业的工作进程池。它支持带有超时和回
     调的异步结果，以及一个并行的 map 实现。

     `processes' 是要使用的工作进程数目。如果 `processes' 为 ‘None’，则
     使用 *note os.cpu_count(): 888. 返回的值。

     如果 `initializer' 不为 ‘None’，则每个工作进程将会在启动时调用
     ‘initializer(*initargs)’。

     `maxtasksperchild' 是一个工作进程在它退出或被一个新的工作进程代替之
     前能完成的任务数量，为了释放未使用的资源。默认的 `maxtasksperchild'
     是 ‘None’，意味着工作进程寿与池齐。

     `context' 可被用于指定启动的工作进程的上下文。通常一个进程池是使用
     函数 ‘multiprocessing.Pool()’ 或者一个上下文对象的 *note Pool():
     884. 方法创建的。在这两种情况下， `context' 都是适当设置的。

     注意，进程池对象的方法只有创建它的进程能够调用。

          警告: *note multiprocessing.pool: bc. 对象具有需要正确管理的内
          部资源 （像任何其他资源一样），具体方式是将进程池用作上下文管
          理器，或者手动调用 *note close(): 2411. 和 *note terminate():
          2412.。 未做此类操作将导致进程在终结阶段挂起。

          请注意依赖垃圾回收器来销毁进程池是 `不正确' 的做法，因为
          CPython 并不保证会调用进程池终结程序（请参阅 *note
          object.__del__(): 927. 来了解详情）。

     3.2 新版功能: `maxtasksperchild'

     3.4 新版功能: `context'

          注解: 通常来说，*note Pool: 884. 中的 Worker 进程的生命周期和
          进程池的工作队列一样长。一些其他系统中（如 Apache, mod_wsgi 等
          ）也可以发现另一种模式，他们会让工作进程在完成一些任务后退出，
          清理、释放资源，然后启动一个新的进程代替旧的工作进程。 *note
          Pool: 884. 的 `maxtasksperchild' 参数给用户提供了这种能力。

      -- 方法: apply (func[, args[, kwds]])

          使用 `args' 参数以及 `kwds' 命名参数调用 `func' , 它会返回结果
          前阻塞。这种情况下，*note apply_async(): 2414. 更适合并行化工
          作。另外 `func' 只会在一个进程池中的一个工作进程中执行。

      -- 方法: apply_async (func[, args[, kwds[, callback[,
               error_callback]]]])

          *note apply(): 2413. 方法的一个变种，返回一个 *note
          AsyncResult: 2415. 对象。

          如果指定了 `callback' , 它必须是一个接受单个参数的可调用对象。
          当执行成功时， `callback' 会被用于处理执行后的返回结果，否则，
          调用 `error_callback' 。

          如果指定了 `error_callback' , 它必须是一个接受单个参数的可调用
          对象。当目标函数执行失败时， 会将抛出的异常对象作为参数传递给
          `error_callback' 执行。

          回调函数应该立即执行完成，否则会阻塞负责处理结果的线程。

      -- 方法: map (func, iterable[, chunksize])

          内置 *note map(): c35. 函数的并行版本 (但它只支持一个
          `iterable' 参数，对于多个可迭代对象请参阅 *note starmap():
          a2e.)。 它会保持阻塞直到获得结果。

          这个方法会将可迭代对象分割为许多块，然后提交给进程池。可以将
          `chunksize' 设置为一个正整数从而（近似）指定每个块的大小可以。

          注意对于很长的迭代对象，可能消耗很多内存。可以考虑使用 *note
          imap(): 2416. 或 *note imap_unordered(): 2417. 并且显示指定
          `chunksize' 以提升效率。

      -- 方法: map_async (func, iterable[, chunksize[, callback[,
               error_callback]]])

          *note map(): a31. 方法的一个变种，返回一个 *note AsyncResult:
          2415. 对象。

          如果指定了 `callback' , 它必须是一个接受单个参数的可调用对象。
          当执行成功时， `callback' 会被用于处理执行后的返回结果，否则，
          调用 `error_callback' 。

          如果指定了 `error_callback' , 它必须是一个接受单个参数的可调用
          对象。当目标函数执行失败时， 会将抛出的异常对象作为参数传递给
          `error_callback' 执行。

          回调函数应该立即执行完成，否则会阻塞负责处理结果的线程。

      -- 方法: imap (func, iterable[, chunksize])

          *note map(): a31. 的延迟执行版本。

          `chunksize' 参数的作用和 *note map(): a31. 方法的一样。对于很
          长的迭代器，给 `chunksize' 设置一个很大的值会比默认值 ‘1’ `极
          大' 地加快执行速度。

          同样，如果 `chunksize' 是 ‘1’ , 那么 *note imap(): 2416. 方法
          所返回的迭代器的 ‘next()’ 方法拥有一个可选的 `timeout' 参数：
          如果无法在 `timeout' 秒内执行得到结果，则‘‘next(timeout)‘‘ 会
          抛出 *note multiprocessing.TimeoutError: 23bc. 异常。

      -- 方法: imap_unordered (func, iterable[, chunksize])

          和 *note imap(): 2416. 相同，只不过通过迭代器返回的结果是任意
          的。（当进程池中只有一个工作进程的时候，返回结果的顺序才能认为
          是"有序"的）

      -- 方法: starmap (func, iterable[, chunksize])

          和 *note map(): c35. 类似，不过 `iterable' 中的每一项会被解包
          再作为函数参数。

          比如可迭代对象 ‘[(1,2), (3, 4)]’ 会转化为等价于 ‘[func(1,2),
          func(3,4)]’ 的调用。

          3.3 新版功能.

      -- 方法: starmap_async (func, iterable[, chunksize[, callback[,
               error_callback]]])

          相当于 *note starmap(): a2e. 与 *note map_async(): a32. 的结合
          ，迭代 `iterable' 的每一项，解包作为 `func' 的参数并执行，返回
          用于获取结果的对象。

          3.3 新版功能.

      -- 方法: close ()

          阻止后续任务提交到进程池，当所有任务执行完成后，工作进程会退出
          。

      -- 方法: terminate ()

          不必等待未完成的任务，立即停止工作进程。当进程池对象呗垃圾回收
          时， 会立即调用 *note terminate(): 2412. 。

      -- 方法: join ()

          等待工作进程结束。调用 *note join(): 2418. 前必须先调用 *note
          close(): 2411. 或者 *note terminate(): 2412. 。

     3.3 新版功能: 进程池对象现在支持上下文管理器协议 - 参见 *note
     上下文管理器类型: 1498. 。*note __enter__(): 16ec. 返回进程池对象,
     *note __exit__(): 16ee. 会调用 *note terminate(): 2412. 。

 -- 类: multiprocessing.pool.AsyncResult

     *note Pool.apply_async(): 2414. 和 *note Pool.map_async(): a32. 返
     回对象所属的类。

      -- 方法: get ([timeout])

          用于获取执行结果。如果 `timeout' 不是 ‘None’ 并且在 `timeout'
          秒内仍然没有执行完得到结果，则抛出 *note
          multiprocessing.TimeoutError: 23bc. 异常。如果远程调用发生异常
          ，这个异常会通过 *note get(): 2419. 重新抛出。

      -- 方法: wait ([timeout])

          阻塞，直到返回结果，或者 `timeout' 秒后超时。

      -- 方法: ready ()

          返回执行状态，是否已经完成。

      -- 方法: successful ()

          判断调用是否已经完成并且未引发异常。 如果还未获得结果则将引发
          *note ValueError: 1fc.。

          在 3.7 版更改: 如果没有执行完，会抛出 *note ValueError: 1fc. 
          异常而不是 *note AssertionError: 103e. 。

下面的例子演示了进程池的用法:

     from multiprocessing import Pool
     import time

     def f(x):
         return x*x

     if __name__ == '__main__':
         with Pool(processes=4) as pool:         # start 4 worker processes
             result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process
             print(result.get(timeout=1))        # prints "100" unless your computer is *very* slow

             print(pool.map(f, range(10)))       # prints "[0, 1, 4,..., 81]"

             it = pool.imap(f, range(10))
             print(next(it))                     # prints "0"
             print(next(it))                     # prints "1"
             print(it.next(timeout=1))           # prints "4" unless your computer is *very* slow

             result = pool.apply_async(time.sleep, (10,))
             print(result.get(timeout=1))        # raises multiprocessing.TimeoutError


File: python.info,  Node: 监听器及客户端,  Next: 认证密码,  Prev: 进程池,  Up: 参考

5.17.2.22 监听器及客户端
........................

通常情况下，进程间通过队列或者 *note Pipe(): 239f. 返回的 *note
Connection: 23db. 传递消息。

不过，*note multiprocessing.connection: b9. 模块其实提供了一些更灵活的特
性。最基础的用法是通过它抽象出来的高级API来操作socket或者Windows命名管道
。也提供一些高级用法，如通过 *note hmac: 8f. 模块来支持 `摘要认证'，以及
同时监听多个管道连接。

 -- 函数: multiprocessing.connection.deliver_challenge (connection,
          authkey)

     发送一个随机生成的消息到另一端，并等待回复。

     如果收到的回复与使用 `authkey' 作为键生成的信息摘要匹配成功，就会发
     送一个欢迎信息给管道另一端。否则抛出 *note AuthenticationError:
     23bb. 异常。

 -- 函数: multiprocessing.connection.answer_challenge (connection,
          authkey)

     接收一条信息，使用 `authkey' 作为键计算信息摘要，然后将摘要发送回去
     。

     如果没有收到欢迎消息，就抛出 *note AuthenticationError: 23bb. 异常
     。

 -- 函数: multiprocessing.connection.Client (address[, family[,
          authkey]])

     尝试使用 `address' 地址上的监听器建立一个连接，返回 *note
     Connection: 23db. 。

     连接的类型取决于 `family' 参数，但是通常可以省略，因为可以通过
     `address' 的格式推导出来。(查看 *note 地址格式: 2421. )

     如果提供了 `authkey' 参数并且不是 None，那它必须是一个字符串并且会
     被当做基于 HMAC 认证的密钥。如果 `authkey' 是None 则不会有认证行为
     。认证失败抛出 *note AuthenticationError: 23bb. 异常，请查看 See
     *note 认证密码: 23b7. 。

 -- 类: multiprocessing.connection.Listener ([address[, family[,
          backlog[, authkey]]]])

     可以监听连接请求，是对于绑定套接字或者 Windows 命名管道的封装。

     `address' 是监听器对象中的绑定套接字或命名管道使用的地址。

          注解: 如果使用 ’0.0.0.0’ 作为监听地址，那么在Windows上这个地址
          无法建立连接。想要建立一个可连接的端点，应该使用 ’127.0.0.1’ 。

     `family' 是套接字(或者命名管道)使用的类型。它可以是以下一种:
     ‘'AF_INET'’ ( TCP 套接字类型), ‘'AF_UNIX'’ ( Unix 域套接字) 或者
     ‘'AF_PIPE'’ ( Windows 命名管道)。其中只有第一个保证各平台可用。如果
     `family' 是 ‘None’ ,那么 family 会根据 `address' 的格式自动推导出来
     。如果 `address' 也是 ‘None’ , 则取默认值。默认值为可用类型中速度最
     快的。见 *note 地址格式: 2421. 。注意，如果 `family' 是 ‘'AF_UNIX'’
     而address是‘‘None‘‘ ,套接字会在一个 *note tempfile.mkstemp(): 1c78.
     创建的私有临时目录中创建。

     如果监听器对象使用了套接字，`backlog' (默认值为1) 会在套接字绑定后
     传递给它的 *note listen(): 754. 方法。

     如果提供了 `authkey' 参数并且不是 None，那它必须是一个字符串并且会
     被当做基于 HMAC 认证的密钥。如果 `authkey' 是None 则不会有认证行为
     。认证失败抛出 *note AuthenticationError: 23bb. 异常，请查看 See
     *note 认证密码: 23b7. 。

      -- 方法: accept ()

          接受一个连接并返回一个 *note Connection: 23db. 对象，其连接到
          的监听器对象已绑定套接字或者命名管道。如果已经尝试过认证并且失
          败了，则会抛出 *note AuthenticationError: 23bb. 异常。

      -- 方法: close ()

          关闭监听器对象上的绑定套接字或者命名管道。此函数会在监听器被垃
          圾回收后自动调用。不过仍然建议显式调用函数关闭。

     监听器对象拥有下列只读属性:

      -- 属性: address

          监听器对象使用的地址。

      -- 属性: last_accepted

          最后一个连接所使用的地址。如果没有的话就是 ‘None’ 。

     3.3 新版功能: 监听器对象现在支持了上下文管理协议 - 见 *note
     上下文管理器类型: 1498. 。 *note __enter__(): 16ec. 返回一个监听器
     对象, *note __exit__(): 16ee. 会调用 *note close(): 2424. 。

 -- 函数: multiprocessing.connection.wait (object_list, timeout=None)

     一直等待直到 `object_list' 中某个对象处于就绪状态。返回
     `object_list' 中处于就绪状态的对象。如果 `timeout' 是一个浮点型，该
     方法会最多阻塞这么多秒。如果 `timeout' 是 ‘None’ ，则会允许阻塞的事
     件没有限制。timeout为负数的情况下和为0的情况相同。

     对于 Unix 和 Windows ，满足下列条件的对象可以出现在 `object_list' 中

        * 可读的 *note Connection: 23db. 对象；

        * 一个已连接并且可读的 *note socket.socket: 67d. 对象；或者

        * *note Process: 3ba. 对象中的 *note sentinel: a2d. 属性。

     当一个连接或者套接字对象拥有有效的数据可被读取的时候，或者另一端关
     闭后，这个对象就处于就绪状态。

     `Unix': ‘wait(object_list, timeout)’ 和 ‘select.select(object_list,
     [], [], timeout)’ 几乎相同。差别在于，如果 *note select.select():
     67c. 被信号中断，它会抛出一个附带错误号为 ‘EINTR’ 的 *note OSError:
     1d4. 异常，而 *note wait(): a2c. 不会。

     `Windows': `object_list' 中的元素必须是一个表示为整数的可等待的句柄
     (按照 Win32 函数 ‘WaitForMultipleObjects()’ 的文档中所定义) 或者一
     个拥有 ‘fileno()’ 方法的对象，这个对象返回一个套接字句柄或者管道句
     柄。（注意管道和套接字两种句柄 `不是' 可等待的句柄）

     3.3 新版功能.

`示例'

下面的服务代码创建了一个使用 ‘'secret password'’ 作为认证密码的监听器。
它会等待连接然后发送一些数据给客户端:

     from multiprocessing.connection import Listener
     from array import array

     address = ('localhost', 6000)     # family is deduced to be 'AF_INET'

     with Listener(address, authkey=b'secret password') as listener:
         with listener.accept() as conn:
             print('connection accepted from', listener.last_accepted)

             conn.send([2.25, None, 'junk', float])

             conn.send_bytes(b'hello')

             conn.send_bytes(array('i', [42, 1729]))

下面的代码连接到服务然后从服务器上j接收一些数据:

     from multiprocessing.connection import Client
     from array import array

     address = ('localhost', 6000)

     with Client(address, authkey=b'secret password') as conn:
         print(conn.recv())                  # => [2.25, None, 'junk', float]

         print(conn.recv_bytes())            # => 'hello'

         arr = array('i', [0, 0, 0, 0, 0])
         print(conn.recv_bytes_into(arr))    # => 8
         print(arr)                          # => array('i', [42, 1729, 0, 0, 0])

下面的代码使用了 *note wait(): a2c. ，以便在同时等待多个进程发来消息。

     import time, random
     from multiprocessing import Process, Pipe, current_process
     from multiprocessing.connection import wait

     def foo(w):
         for i in range(10):
             w.send((i, current_process().name))
         w.close()

     if __name__ == '__main__':
         readers = []

         for i in range(4):
             r, w = Pipe(duplex=False)
             readers.append(r)
             p = Process(target=foo, args=(w,))
             p.start()
             # We close the writable end of the pipe now to be sure that
             # p is the only process which owns a handle for it.  This
             # ensures that when p closes its handle for the writable end,
             # wait() will promptly report the readable end as being ready.
             w.close()

         while readers:
             for r in wait(readers):
                 try:
                     msg = r.recv()
                 except EOFError:
                     readers.remove(r)
                 else:
                     print(msg)

* Menu:

* 地址格式::


File: python.info,  Node: 地址格式,  Up: 监听器及客户端

5.17.2.23 地址格式
..................

   * ‘'AF_INET'’ 地址是 ‘(hostname, port)’ 形式的元组类型，其中
     `hostname' 是一个字符串，`port' 是整数。

   * ‘'AF_UNIX'’ 地址是文件系统上文件名的字符串。

   * ‘'AF_PIPE'’ 地址是一个 ‘r'\.\pipe{PipeName}'’ 形式的字符串。 要使用
     *note Client(): 2420. 来连接到远程计算机上一个名为 `ServerName' 的
     命名管道，则应当改用 ‘r'\`ServerName'\pipe{PipeName}'’ 形式的地址。

注意，使用两个反斜线开头的字符串默认被当做 ‘'AF_PIPE'’ 地址而不是
‘'AF_UNIX'’  。


File: python.info,  Node: 认证密码,  Next: 日志记录<2>,  Prev: 监听器及客户端,  Up: 参考

5.17.2.24 认证密码
..................

当使用 *note Connection.recv: 23dd. 接收数据时，数据会自动被反序列化。不
幸的是，对于一个不可信的数据源发来的数据，反序列化是存在安全风险的。所以
*note Listener: 2422. 和 *note Client(): 2420. 之间使用 *note hmac: 8f.
模块进行摘要认证。

认证密钥是一个 byte 类型的字符串，可以认为是和密码一样的东西，连接建立好
后，双方都会要求另一方证明知道认证密钥。（这个证明过程不会通过连接发送密
钥）

如果要求认证但是没有指定认证密钥，则会使用 ‘current_process().authkey’ 的
返回值 (参见 *note Process: 3ba.)。 这个值将被当前进程所创建的任何 *note
Process: 3ba. 对象自动继承。 这意味着 (在默认情况下) 一个包含多进程的程
序中的所有进程会在相互间建立连接的时候共享单个认证密钥。

*note os.urandom(): 4d9. 也可以用来生成合适的认证密钥。


File: python.info,  Node: 日志记录<2>,  Next: multiprocessing dummy 模块,  Prev: 认证密码,  Up: 参考

5.17.2.25 日志记录
..................

当前模块也提供了一些对 logging 的支持。注意， *note logging: ab. 模块本
身并没有使用进程间共享的锁，所以来自于多个进程的日志可能（具体取决于使用
的日志 handler 类型）相互覆盖或者混杂。

 -- 函数: multiprocessing.get_logger ()

     返回 *note multiprocessing: b8. 使用的 logger，必要的话会创建一个新
     的。

     如果创建的首个 logger 日志级别为 ‘logging.NOTSET’ 并且没有默认
     handler。通过这个 logger 打印的消息不会传递到根 logger。

     注意在 Windows 上，子进程只会继承父进程 logger 的日志级别 - 对于
     logger的其他自定义项不会继承。

 -- 函数: multiprocessing.log_to_stderr ()

     此函数会调用 *note get_logger(): 242a. 但是会在返回的 logger 上增加
     一个 handler，将所有输出都使用 ‘'[%(levelname)s/%(processName)s]
     %(message)s'’ 的格式发送到 *note sys.stderr: 318. 。

下面是一个在交互式解释器中打开日志功能的例子:

     >>> import multiprocessing, logging
     >>> logger = multiprocessing.log_to_stderr()
     >>> logger.setLevel(logging.INFO)
     >>> logger.warning('doomed')
     [WARNING/MainProcess] doomed
     >>> m = multiprocessing.Manager()
     [INFO/SyncManager-...] child process calling self.run()
     [INFO/SyncManager-...] created temp directory /.../pymp-...
     [INFO/SyncManager-...] manager serving at '/.../listener-...'
     >>> del m
     [INFO/MainProcess] sending shutdown message to manager
     [INFO/SyncManager-...] manager exiting with exitcode 0

要查看日志等级的完整列表，见 *note logging: ab. 模块。


File: python.info,  Node: multiprocessing dummy 模块,  Prev: 日志记录<2>,  Up: 参考

5.17.2.26 ‘multiprocessing.dummy’ 模块
......................................

*note multiprocessing.dummy: ba. 复制了 *note multiprocessing: b8. 的
API，不过是在 *note threading: 10a. 模块之上包装了一层。

特别地，*note multiprocessing.dummy: ba. 所提供的 ‘Pool’ 函数会返回一个
*note ThreadPool: edd. 的实例，该类是 *note Pool: 884. 的子类，它支持所
有相同的方法调用但会使用一个工作线程池而非工作进程池。

 -- 类: multiprocessing.pool.ThreadPool ([processes[, initializer[,
          initargs]]])

     一个线程池对象，用来控制可向其提交任务的工作线程池。 *note
     ThreadPool: edd. 实例与 *note Pool: 884. 实例是完全接口兼容的，并且
     它们的资源也必须被正确地管理，或者是将线程池作为上下文管理器来使用
     ，或者是通过手动调用 *note close(): 2411. 和 *note terminate():
     2412.。

     `processes' 是要使用的工作线程数目。 如果 `processes' 为 ‘None’，则
     使用 *note os.cpu_count(): 888. 返回的值。

     如果 `initializer' 不为 ‘None’，则每个工作进程将会在启动时调用
     ‘initializer(*initargs)’。

     不同于 *note Pool: 884.，`maxtasksperchild' 和 `context' 不可被提供
     。

               注解: *note ThreadPool: edd. 具有与 *note Pool: 884. 相同
               的接口，它围绕一个进程池进行设计并且先于 *note
               concurrent.futures: 22. 模块的引入。 因此，它继承了一些对
               于基于线程的池来说没有意义的操作，并且它具有自己的用于表
               示异步任务状态的类型 *note AsyncResult: 2415.，该类型不为
               任何其他库所知。

               用户通常应该倾向于使用 *note
               concurrent.futures.ThreadPoolExecutor: 27b.，它拥有从一开
               始就围绕线程进行设计的更简单接口，并且返回与许多其他库相
               兼容的 *note concurrent.futures.Future: b35. 实例，包括
               *note asyncio: a. 库。


File: python.info,  Node: 编程指导,  Next: 例子<10>,  Prev: 参考,  Up: multiprocessing --- 基于进程的并行

5.17.2.27 编程指导
..................

使用 *note multiprocessing: b8. 时，应遵循一些指导原则和习惯用法。

* Menu:

* 所有start方法::
* spawn 和 forkserver 启动方式::


File: python.info,  Node: 所有start方法,  Next: spawn 和 forkserver 启动方式,  Up: 编程指导

5.17.2.28 所有start方法
.......................

下面这些适用于所有start方法。

避免共享状态

     应该尽可能避免在进程间传递大量数据，越少越好。

     最好坚持使用队列或者管道进行进程间通信，而不是底层的同步原语。

可序列化

     保证所代理的方法的参数是可以序列化的。

代理的线程安全性

     不要在多线程中同时使用一个代理对象，除非你用锁保护它。

     （而在不同进程中使用 `相同' 的代理对象却没有问题。）

使用 Join 避免僵尸进程

     在 Unix 上，如果一个进程执行完成但是没有被 join，就会变成僵尸进程。
     一般来说，僵尸进程不会很多，因为每次新启动进程（或者 *note
     active_children(): 23d4. 被调用）时，所有已执行完成且没有被 join 的
     进程都会自动被 join，而且对一个执行完的进程调用 *note
     Process.is_alive: 23b4. 也会 join 这个进程。尽管如此，对自己启动的
     进程显式调用 join 依然是最佳实践。

继承优于序列化、反序列化

     当使用 `spawn' 或者 `forkserver' 的启动方式时，*note
     multiprocessing: b8. 中的许多类型都必须是可序列化的，这样子进程才能
     使用它们。但是通常我们都应该避免使用管道和队列发送共享对象到另外一
     个进程，而是重新组织代码，对于其他进程创建出来的共享对象，让那些需
     要访问这些对象的子进程可以直接将这些对象从父进程继承过来。

避免杀死进程

     听过 *note Process.terminate: 23b8.  停止一个进程很容易导致这个进程
     正在使用的共享资源（如锁、信号量、管道和队列）损坏或者变得不可用，
     无法在其他进程中继续使用。

     所以，最好只对那些从来不使用共享资源的进程调用 *note
     Process.terminate: 23b8. 。

Join 使用队列的进程

     记住，往队列放入数据的进程会一直等待直到队列中所有项被"feeder" 线程
     传给底层管道。（子进程可以调用队列的 *note
     Queue.cancel_join_thread: 23c8. 方法禁止这种行为）

     这意味着，任何使用队列的时候，你都要确保在进程join之前，所有存放到
     队列中的项将会被其他进程、线程完全消费。否则不能保证这个写过队列的
     进程可以正常终止。记住非精灵进程会自动 join 。

     下面是一个会导致死锁的例子:

          from multiprocessing import Process, Queue

          def f(q):
              q.put('X' * 1000000)

          if __name__ == '__main__':
              queue = Queue()
              p = Process(target=f, args=(queue,))
              p.start()
              p.join()                    # this deadlocks
              obj = queue.get()

     交换最后两行可以修复这个问题（或者直接删掉 ‘p.join()’）。

显式传递资源给子进程

     在Unix上，使用 `fork' 方式启动的子进程可以使用父进程中全局创建的共
     享资源。不过，最好是显式将资源对象通过参数的形式传递给子进程。

     除了（部分原因）让代码兼容 Windows 以及其他的进程启动方式外，这种形
     式还保证了在子进程生命期这个对象是不会被父进程垃圾回收的。如果父进
     程中的某些对象被垃圾回收会导致资源释放，这就变得很重要。

     所以对于实例：

          from multiprocessing import Process, Lock

          def f():
              ... do something using "lock" ...

          if __name__ == '__main__':
              lock = Lock()
              for i in range(10):
                  Process(target=f).start()

     应当重写成这样：

          from multiprocessing import Process, Lock

          def f(l):
              ... do something using "l" ...

          if __name__ == '__main__':
              lock = Lock()
              for i in range(10):
                  Process(target=f, args=(lock,)).start()

谨防将 *note sys.stdin: 316. 数据替换为 “类似文件的对象”

     *note multiprocessing: b8. 原本会无条件地这样调用:

          os.close(sys.stdin.fileno())

     在 ‘multiprocessing.Process._bootstrap()’  方法中 —— 这会导致与"进
     程中的进程"相关的一些问题。这已经被修改成了:

          sys.stdin.close()
          sys.stdin = open(os.open(os.devnull, os.O_RDONLY), closefd=False)

     它解决了进程相互冲突导致文件描述符错误的根本问题，但是对使用带缓冲
     的“文件类对象”替换 *note sys.stdin(): 316. 作为输出的应用程序造成了
     潜在的危险。如果多个进程调用了此文件类对象的 *note close(): 101e. 方
     法，会导致相同的数据多次刷写到此对象，损坏数据。

     如果你写入文件类对象并实现了自己的缓存，可以在每次追加缓存数据时记
     录当前进程id，从而将其变成 fork 安全的，当发现进程id变化后舍弃之前
     的缓存，例如:

          @property
          def cache(self):
              pid = os.getpid()
              if pid != self._pid:
                  self._pid = pid
                  self._cache = []
              return self._cache

     需要更多信息，请查看 bpo-5155(1), bpo-5313(2) 以及 bpo-5331(3)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5155

   (2) https://bugs.python.org/issue5313

   (3) https://bugs.python.org/issue5331


File: python.info,  Node: spawn 和 forkserver 启动方式,  Prev: 所有start方法,  Up: 编程指导

5.17.2.29 `spawn' 和 `forkserver' 启动方式
..........................................

相对于 `fork' 启动方式，有一些额外的限制。

更依赖序列化

     ‘Process.__init__()’ 的所有参数都必须可序列化。同样的，当你继承
     *note Process: 3ba. 时，需要保证当调用 *note Process.start: 23b1. 方
     法时，实例可以被序列化。

全局变量

     记住，如果子进程中的代码尝试访问一个全局变量，它所看到的值（如果有
     ）可能和父进程中执行 *note Process.start: 23b1. 那一刻的值不一样。

     当全局变量知识模块级别的常量时，是不会有问题的。

安全导入主模块

     确保主模块可以被新启动的Python解释器安全导入而不会引发什么副作用（
     比如又启动了一个子进程）

     例如，使用 `spawn' 或 `forkserver' 启动方式执行下面的模块，会引发
     *note RuntimeError: 2bb. 异常而失败。

          from multiprocessing import Process

          def foo():
              print('hello')

          p = Process(target=foo)
          p.start()

     应该通过下面的方法使用 ‘if __name__ == '__main__':’ ，从而保护程序
     "入口点":

          from multiprocessing import Process, freeze_support, set_start_method

          def foo():
              print('hello')

          if __name__ == '__main__':
              freeze_support()
              set_start_method('spawn')
              p = Process(target=foo)
              p.start()

     （如果程序将正常运行而不是冻结，则可以省略 ‘freeze_support()’ 行）

     这允许新启动的 Python 解释器安全导入模块然后运行模块中的 ‘foo()’ 函
     数。

     如果主模块中创建了进程池或者管理器，这个规则也适用。


File: python.info,  Node: 例子<10>,  Prev: 编程指导,  Up: multiprocessing --- 基于进程的并行

5.17.2.30 例子
..............

创建和使用自定义管理器、代理的示例:

     from multiprocessing import freeze_support
     from multiprocessing.managers import BaseManager, BaseProxy
     import operator

     ##

     class Foo:
         def f(self):
             print('you called Foo.f()')
         def g(self):
             print('you called Foo.g()')
         def _h(self):
             print('you called Foo._h()')

     # A simple generator function
     def baz():
         for i in range(10):
             yield i*i

     # Proxy type for generator objects
     class GeneratorProxy(BaseProxy):
         _exposed_ = ['__next__']
         def __iter__(self):
             return self
         def __next__(self):
             return self._callmethod('__next__')

     # Function to return the operator module
     def get_operator_module():
         return operator

     ##

     class MyManager(BaseManager):
         pass

     # register the Foo class; make `f()` and `g()` accessible via proxy
     MyManager.register('Foo1', Foo)

     # register the Foo class; make `g()` and `_h()` accessible via proxy
     MyManager.register('Foo2', Foo, exposed=('g', '_h'))

     # register the generator function baz; use `GeneratorProxy` to make proxies
     MyManager.register('baz', baz, proxytype=GeneratorProxy)

     # register get_operator_module(); make public functions accessible via proxy
     MyManager.register('operator', get_operator_module)

     ##

     def test():
         manager = MyManager()
         manager.start()

         print('-' * 20)

         f1 = manager.Foo1()
         f1.f()
         f1.g()
         assert not hasattr(f1, '_h')
         assert sorted(f1._exposed_) == sorted(['f', 'g'])

         print('-' * 20)

         f2 = manager.Foo2()
         f2.g()
         f2._h()
         assert not hasattr(f2, 'f')
         assert sorted(f2._exposed_) == sorted(['g', '_h'])

         print('-' * 20)

         it = manager.baz()
         for i in it:
             print('<%d>' % i, end=' ')
         print()

         print('-' * 20)

         op = manager.operator()
         print('op.add(23, 45) =', op.add(23, 45))
         print('op.pow(2, 94) =', op.pow(2, 94))
         print('op._exposed_ =', op._exposed_)

     ##

     if __name__ == '__main__':
         freeze_support()
         test()

使用 *note Pool: 884.:

     import multiprocessing
     import time
     import random
     import sys

     #
     # Functions used by test code
     #

     def calculate(func, args):
         result = func(*args)
         return '%s says that %s%s = %s' % (
             multiprocessing.current_process().name,
             func.__name__, args, result
             )

     def calculatestar(args):
         return calculate(*args)

     def mul(a, b):
         time.sleep(0.5 * random.random())
         return a * b

     def plus(a, b):
         time.sleep(0.5 * random.random())
         return a + b

     def f(x):
         return 1.0 / (x - 5.0)

     def pow3(x):
         return x ** 3

     def noop(x):
         pass

     #
     # Test code
     #

     def test():
         PROCESSES = 4
         print('Creating pool with %d processes\n' % PROCESSES)

         with multiprocessing.Pool(PROCESSES) as pool:
             #
             # Tests
             #

             TASKS = [(mul, (i, 7)) for i in range(10)] + \
                     [(plus, (i, 8)) for i in range(10)]

             results = [pool.apply_async(calculate, t) for t in TASKS]
             imap_it = pool.imap(calculatestar, TASKS)
             imap_unordered_it = pool.imap_unordered(calculatestar, TASKS)

             print('Ordered results using pool.apply_async():')
             for r in results:
                 print('\t', r.get())
             print()

             print('Ordered results using pool.imap():')
             for x in imap_it:
                 print('\t', x)
             print()

             print('Unordered results using pool.imap_unordered():')
             for x in imap_unordered_it:
                 print('\t', x)
             print()

             print('Ordered results using pool.map() --- will block till complete:')
             for x in pool.map(calculatestar, TASKS):
                 print('\t', x)
             print()

             #
             # Test error handling
             #

             print('Testing error handling:')

             try:
                 print(pool.apply(f, (5,)))
             except ZeroDivisionError:
                 print('\tGot ZeroDivisionError as expected from pool.apply()')
             else:
                 raise AssertionError('expected ZeroDivisionError')

             try:
                 print(pool.map(f, list(range(10))))
             except ZeroDivisionError:
                 print('\tGot ZeroDivisionError as expected from pool.map()')
             else:
                 raise AssertionError('expected ZeroDivisionError')

             try:
                 print(list(pool.imap(f, list(range(10)))))
             except ZeroDivisionError:
                 print('\tGot ZeroDivisionError as expected from list(pool.imap())')
             else:
                 raise AssertionError('expected ZeroDivisionError')

             it = pool.imap(f, list(range(10)))
             for i in range(10):
                 try:
                     x = next(it)
                 except ZeroDivisionError:
                     if i == 5:
                         pass
                 except StopIteration:
                     break
                 else:
                     if i == 5:
                         raise AssertionError('expected ZeroDivisionError')

             assert i == 9
             print('\tGot ZeroDivisionError as expected from IMapIterator.next()')
             print()

             #
             # Testing timeouts
             #

             print('Testing ApplyResult.get() with timeout:', end=' ')
             res = pool.apply_async(calculate, TASKS[0])
             while 1:
                 sys.stdout.flush()
                 try:
                     sys.stdout.write('\n\t%s' % res.get(0.02))
                     break
                 except multiprocessing.TimeoutError:
                     sys.stdout.write('.')
             print()
             print()

             print('Testing IMapIterator.next() with timeout:', end=' ')
             it = pool.imap(calculatestar, TASKS)
             while 1:
                 sys.stdout.flush()
                 try:
                     sys.stdout.write('\n\t%s' % it.next(0.02))
                 except StopIteration:
                     break
                 except multiprocessing.TimeoutError:
                     sys.stdout.write('.')
             print()
             print()


     if __name__ == '__main__':
         multiprocessing.freeze_support()
         test()

一个演示如何使用队列来向一组工作进程提供任务并收集结果的例子：

     import time
     import random

     from multiprocessing import Process, Queue, current_process, freeze_support

     #
     # Function run by worker processes
     #

     def worker(input, output):
         for func, args in iter(input.get, 'STOP'):
             result = calculate(func, args)
             output.put(result)

     #
     # Function used to calculate result
     #

     def calculate(func, args):
         result = func(*args)
         return '%s says that %s%s = %s' % \
             (current_process().name, func.__name__, args, result)

     #
     # Functions referenced by tasks
     #

     def mul(a, b):
         time.sleep(0.5*random.random())
         return a * b

     def plus(a, b):
         time.sleep(0.5*random.random())
         return a + b

     #
     #
     #

     def test():
         NUMBER_OF_PROCESSES = 4
         TASKS1 = [(mul, (i, 7)) for i in range(20)]
         TASKS2 = [(plus, (i, 8)) for i in range(10)]

         # Create queues
         task_queue = Queue()
         done_queue = Queue()

         # Submit tasks
         for task in TASKS1:
             task_queue.put(task)

         # Start worker processes
         for i in range(NUMBER_OF_PROCESSES):
             Process(target=worker, args=(task_queue, done_queue)).start()

         # Get and print results
         print('Unordered results:')
         for i in range(len(TASKS1)):
             print('\t', done_queue.get())

         # Add more tasks using `put()`
         for task in TASKS2:
             task_queue.put(task)

         # Get and print some more results
         for i in range(len(TASKS2)):
             print('\t', done_queue.get())

         # Tell child processes to stop
         for i in range(NUMBER_OF_PROCESSES):
             task_queue.put('STOP')


     if __name__ == '__main__':
         freeze_support()
         test()


File: python.info,  Node: multiprocessing shared_memory --- 可从进程直接访问的共享内存,  Next: concurrent 包,  Prev: multiprocessing --- 基于进程的并行,  Up: 并发执行

5.17.3 ‘multiprocessing.shared_memory’ — 可从进程直接访问的共享内存
-------------------------------------------------------------------

`源代码:' Lib/multiprocessing/shared_memory.py(1)

3.8 新版功能.

__________________________________________________________________

该模块提供了一个 *note SharedMemory: 239c. 类，用于分配和管理多核或对称
多处理器（SMP）机器上进程间的共享内存。为了协助管理不同进程间的共享内存
生命周期，‘multiprocessing.managers’ 模块也提供了一个 *note BaseManager:
23f3. 的子类： ‘SharedMemoryManager’。

本模块中，共享内存是指 "System V 类型" 的共享内存块（虽然可能和它实现方
式不完全一致）而不是 “分布式共享内存”。这种类型的的共享内存允许不同进程
读写一片公共（或者共享）的易失性存储区域。一般来说，进程被限制只能访问属
于自己进程空间的内存，但是共享内存允许跨进程共享数据，从而避免通过进程间
发送消息的形式传递数据。相比通过磁盘、套接字或者其他要求序列化、反序列化
和复制数据的共享形式，直接通过内存共享数据拥有更出色性能。

 -- 类: multiprocessing.shared_memory.SharedMemory (name=None,
          create=False, size=0)

     创建一个新的共享内存块或者连接到一片已经存在的共享内存块。每个共享
     内存块都被指定了一个全局唯一的名称。通过这种方式，一个进程可以通过
     提供一个特定的名字创建一个共享内存区块，然后其他进程使用同样的名字
     连接到这个共享内存块。

     作为一种跨进程共享数据的方式，共享内存块的寿命可能超过创建它的原始
     进程。一个共享内存块可能同时被多个进程使用，当一个进程不再需要访问
     这个共享内存块的时候，应该调用 *note close(): 2433. 方法。当一个共
     享内存块不被任何进程使用的时候，应该调用 *note unlink(): 2434. 方法
     以执行必要的清理。

     `name' 是共享内存的唯一名称，字符串类型。如果创建一个新共享内存块的
     时候，名称指定为 ‘None’ (默认值)，将会随机产生一个新名称。

     `create' 指定创建一个新的共享内存块 (‘True’) 还是连接到已存在的共享
     内存块 (‘False’) 。

     如果是新创建共享内存块则 `size' 用于指定块的大小为多少字节。由于某
     些平台是使用特定内存页大小为最小单位来分配的，最终得到的内存块大小
     可能大于或等于要求的大小。如果是连接到已经存在的共享内存块， ‘size’
     参数会被忽略。

      -- 方法: close ()

          关闭实例对于共享内存的访问连接。所有实例确认自己不再需要使用共
          享内存的时候都应该调用 ‘close()’ ，以保证必要的资源清理。调用
          ‘close()’ 并不会销毁共享内存区域。

      -- 方法: unlink ()

          请求销毁底层的共享内存块。为了执行必要的资源清理， 在所有使用
          这个共享内存块的进程中， ‘unlink()’ 应该调用一次(且只能调用一
          次) 。发出此销毁请求后，共享内存块可能会、也可能不会立即销毁，
          且此行为在不同操作系统之间可能不同。调用 ‘unlink()’ 后再尝试方
          位其中的数据可能导致内存错误。注意: 最后一个关闭共享内存访问权
          限的进程可以以任意顺序调用 ‘unlink()’ 和 *note close(): 2433.
          。

      -- 属性: buf

          共享内存块内容的 memoryview 。

      -- 属性: name

          共享内存块的唯一标识，只读属性。

      -- 属性: size

          共享内存块的字节大小，只读属性

以下示例展示了 *note SharedMemory: 239c. 的底层的用法:

     >>> from multiprocessing import shared_memory
     >>> shm_a = shared_memory.SharedMemory(create=True, size=10)
     >>> type(shm_a.buf)
     <class 'memoryview'>
     >>> buffer = shm_a.buf
     >>> len(buffer)
     10
     >>> buffer[:4] = bytearray([22, 33, 44, 55])  # Modify multiple at once
     >>> buffer[4] = 100                           # Modify single byte at a time
     >>> # Attach to an existing shared memory block
     >>> shm_b = shared_memory.SharedMemory(shm_a.name)
     >>> import array
     >>> array.array('b', shm_b.buf[:5])  # Copy the data into a new array.array
     array('b', [22, 33, 44, 55, 100])
     >>> shm_b.buf[:5] = b'howdy'  # Modify via shm_b using bytes
     >>> bytes(shm_a.buf[:5])      # Access via shm_a
     b'howdy'
     >>> shm_b.close()   # Close each SharedMemory instance
     >>> shm_a.close()
     >>> shm_a.unlink()  # Call unlink only once to release the shared memory

以下示例展示了一个现实中的例子，使用 *note SharedMemory: 239c. 类和
‘NumPy arrays <‘https://www.numpy.org/’>‘_ 结合, 从两个 Python shell 中
访问同一个 ‘numpy.ndarray’ :

     >>> # In the first Python interactive shell
     >>> import numpy as np
     >>> a = np.array([1, 1, 2, 3, 5, 8])  # Start with an existing NumPy array
     >>> from multiprocessing import shared_memory
     >>> shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
     >>> # Now create a NumPy array backed by shared memory
     >>> b = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf)
     >>> b[:] = a[:]  # Copy the original data into shared memory
     >>> b
     array([1, 1, 2, 3, 5, 8])
     >>> type(b)
     <class 'numpy.ndarray'>
     >>> type(a)
     <class 'numpy.ndarray'>
     >>> shm.name  # We did not specify a name so one was chosen for us
     'psm_21467_46075'

     >>> # In either the same shell or a new Python shell on the same machine
     >>> import numpy as np
     >>> from multiprocessing import shared_memory
     >>> # Attach to the existing shared memory block
     >>> existing_shm = shared_memory.SharedMemory(name='psm_21467_46075')
     >>> # Note that a.shape is (6,) and a.dtype is np.int64 in this example
     >>> c = np.ndarray((6,), dtype=np.int64, buffer=existing_shm.buf)
     >>> c
     array([1, 1, 2, 3, 5, 8])
     >>> c[-1] = 888
     >>> c
     array([  1,   1,   2,   3,   5, 888])

     >>> # Back in the first Python interactive shell, b reflects this change
     >>> b
     array([  1,   1,   2,   3,   5, 888])

     >>> # Clean up from within the second Python shell
     >>> del c  # Unnecessary; merely emphasizing the array is no longer used
     >>> existing_shm.close()

     >>> # Clean up from within the first Python shell
     >>> del b  # Unnecessary; merely emphasizing the array is no longer used
     >>> shm.close()
     >>> shm.unlink()  # Free and release the shared memory block at the very end

 -- 类: multiprocessing.managers.SharedMemoryManager ([address[,
          authkey]])

     *note BaseManager: 23f3. 的子类，可用于管理跨进程的共享内存块。

     调用 *note SharedMemoryManager: 2438. 实例上的 *note start():
     23f4.  方法会启动一个新进程。这个新进程的唯一目的就是管理所有由它创
     建的共享内存块的生命周期。想要释放此进程管理的所有共享内存块，可以
     调用实例的 *note shutdown(): 23f8.  方法。这会触发执行它管理的所有
     *note SharedMemory: 2439. 对象的 ‘SharedMemory.unlink()’ 方法，然后
     停止这个进程。通过 ‘SharedMemoryManager’ 创建 ‘SharedMemory’ 实例，
     我们可以避免手动跟踪和释放共享内存资源。

     这个类提供了创建和返回 *note SharedMemory: 2439. 实例的方法，以及以
     共享内存为基础创建一个列表类对象 (*note ShareableList: 243a.) 的方
     法。

     有关继承的可选输入参数 `address' 和 `authkey' 以及他们如何用于从进
     程连接已经存在的 ‘SharedMemoryManager’ 服务，参见 *note
     multiprocessing.managers.BaseManager: 23f3.

      -- 方法: SharedMemory (size)

          使用 ‘size’ 参数，创建一个新的指定字节大小的 *note
          SharedMemory: 2439. 对象并返回。

      -- 方法: ShareableList (sequence)

          创建并返回一个新的 *note ShareableList: 243a. 对象，通过输入参
          数 ‘sequence’ 初始化。

下面的案例展示了 ‘SharedMemoryManager’ 的基础机制:

     >>> from multiprocessing.managers import SharedMemoryManager
     >>> smm = SharedMemoryManager()
     >>> smm.start()  # Start the process that manages the shared memory blocks
     >>> sl = smm.ShareableList(range(4))
     >>> sl
     ShareableList([0, 1, 2, 3], name='psm_6572_7512')
     >>> raw_shm = smm.SharedMemory(size=128)
     >>> another_sl = smm.ShareableList('alpha')
     >>> another_sl
     ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
     >>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl

以下案例展示了 ‘SharedMemoryManager’ 对象的一种可能更方便的使用方式，通
过 *note with: 6f2. 语句来保证所有共享内存块在使用完后被释放。

     >>> with SharedMemoryManager() as smm:
     ...     sl = smm.ShareableList(range(2000))
     ...     # Divide the work among two processes, storing partial results in sl
     ...     p1 = Process(target=do_work, args=(sl, 0, 1000))
     ...     p2 = Process(target=do_work, args=(sl, 1000, 2000))
     ...     p1.start()
     ...     p2.start()  # A multiprocessing.Pool might be more efficient
     ...     p1.join()
     ...     p2.join()   # Wait for all work to complete in both processes
     ...     total_result = sum(sl)  # Consolidate the partial results now in sl

当在 *note with: 6f2. 语句中使用 ‘SharedMemoryManager’  对象的时候，使用
这个管理器创建的共享内存块会在 *note with: 6f2. 语句代码块结束后被释放。

 -- 类: multiprocessing.shared_memory.ShareableList (sequence=None, *,
          name=None)

     提供一个可修改的类 list 对象，其中所有值都存放在共享内存块中。这限
     制了可被存储在其中的值只能是 ‘int’, ‘float’, ‘bool’, ‘str’ （每条数
     据小于10M）, ‘bytes’ （每条数据小于10M）以及 ‘None’ 这些内置类型。
     它另一个显著区别于内置 ‘list’ 类型的地方在于它的长度无法修改（比如
     ，没有 append, insert 等操作）且不支持通过切片操作动态创建新的
     *note ShareableList: 243b.  实例。

     `sequence' 会被用来为一个新的 ‘ShareableList’ 填充值。 设为 ‘None’
     则会基于共享内存名称关联到一个已经存在的 ‘ShareableList’。

     `name' 是所请求的共享内存的唯一名称，与 *note SharedMemory: 239c. 的
     定义中所描述的一致。 当关联到现有的 ‘ShareableList’ 时，则指明其共
     享内存块的唯一名称并将 ‘sequence’ 设为 ‘None’。

      -- 方法: count (value)

          返回 ‘value’ 出现的次数。

      -- 方法: index (value)

          返回 ‘value’ 首次出现的位置，如果 ‘value’ 不存在, 则抛出 *note
          ValueError: 1fc. 异常。

      -- 属性: format

          包含由所有当前存储值所使用的 *note struct: f9. 打包格式的只读
          属性。

      -- 属性: shm

          存储了值的 *note SharedMemory: 239c. 实例。

下面的例子演示了 *note ShareableList: 243b. 实例的基本用法:

     >>> from multiprocessing import shared_memory
     >>> a = shared_memory.ShareableList(['howdy', b'HoWdY', -273.154, 100, None, True, 42])
     >>> [ type(entry) for entry in a ]
     [<class 'str'>, <class 'bytes'>, <class 'float'>, <class 'int'>, <class 'NoneType'>, <class 'bool'>, <class 'int'>]
     >>> a[2]
     -273.154
     >>> a[2] = -78.5
     >>> a[2]
     -78.5
     >>> a[2] = 'dry ice'  # Changing data types is supported as well
     >>> a[2]
     'dry ice'
     >>> a[2] = 'larger than previously allocated storage space'
     Traceback (most recent call last):
       ...
     ValueError: exceeds available storage for existing str
     >>> a[2]
     'dry ice'
     >>> len(a)
     7
     >>> a.index(42)
     6
     >>> a.count(b'howdy')
     0
     >>> a.count(b'HoWdY')
     1
     >>> a.shm.close()
     >>> a.shm.unlink()
     >>> del a  # Use of a ShareableList after call to unlink() is unsupported

下面的例子演示了一个、两个或多个进程如何通过提供下层的共享内存块名称来访
问同一个 *note ShareableList: 243b.:

     >>> b = shared_memory.ShareableList(range(5))         # In a first process
     >>> c = shared_memory.ShareableList(name=b.shm.name)  # In a second process
     >>> c
     ShareableList([0, 1, 2, 3, 4], name='...')
     >>> c[-1] = -999
     >>> b[-1]
     -999
     >>> b.shm.close()
     >>> c.shm.close()
     >>> c.shm.unlink()

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/multiprocessing/shared_memory.py


File: python.info,  Node: concurrent 包,  Next: concurrent futures --- 启动并行任务,  Prev: multiprocessing shared_memory --- 可从进程直接访问的共享内存,  Up: 并发执行

5.17.4 ‘concurrent’ 包
----------------------

目前，此包中只有一个模块：

   * *note concurrent.futures: 22. —— 启动并行任务


File: python.info,  Node: concurrent futures --- 启动并行任务,  Next: subprocess --- 子进程管理,  Prev: concurrent 包,  Up: 并发执行

5.17.5 ‘concurrent.futures’ — 启动并行任务
------------------------------------------

3.2 新版功能.

`源码:' Lib/concurrent/futures/thread.py(1) 和
Lib/concurrent/futures/process.py(2)

__________________________________________________________________

*note concurrent.futures: 22. 模块提供异步执行可调用对象高层接口。

异步执行可以由 *note ThreadPoolExecutor: 27b. 使用线程或由 *note
ProcessPoolExecutor: 2a4. 使用单独的进程来实现。 两者都是实现抽像类
*note Executor: 2444. 定义的接口。

* Menu:

* Executor 对象::
* ThreadPoolExecutor::
* ProcessPoolExecutor::
* Future 对象::
* 模块函数::
* Exception类::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/concurrent/futures/thread.py

   (2) 
https://github.com/python/cpython/tree/3.8/Lib/concurrent/futures/process.py


File: python.info,  Node: Executor 对象,  Next: ThreadPoolExecutor,  Up: concurrent futures --- 启动并行任务

5.17.5.1 Executor 对象
......................

 -- 类: concurrent.futures.Executor

     抽象类提供异步执行调用方法。要通过它的子类调用，而不是直接调用。

           -- 方法: submit (fn, *args, **kwargs)

               调度可调用对象 `fn'，以 ‘fn(*args **kwargs)’ 方式执行并返
               回 *note Future: b35. 对像代表可调用对象的执行。:

                    with ThreadPoolExecutor(max_workers=1) as executor:
                        future = executor.submit(pow, 323, 1235)
                        print(future.result())

           -- 方法: map (func, *iterables, timeout=None, chunksize=1)

               类似于 *note map(func, *iterables): c35. 函数，除了以下两
               点：

                  * `iterables' 是立即执行而不是延迟执行的；

                  * `func' 是异步执行的，对 `func' 的多个调用可以并发执
                    行。

               如果从原始调用到 *note Executor.map(): 6c7. 经过
               `timeout' 秒后， *note __next__(): c6c. 已被调用且返回的
               结果还不可用，那么已返回的迭代器将触发 *note
               concurrent.futures.TimeoutError: 2446. 。 `timeout' 可以
               是整数或浮点数。如果 `timeout' 没有指定或为 ‘None’ ，则没
               有超时限制。

               如果 `func' 调用引发一个异常，当从迭代器中取回它的值时这
               个异常将被引发。

               使用 *note ProcessPoolExecutor: 2a4. 时，这个方法会将
               `iterables' 分割任务块并作为独立的任务并提交到执行池中。
               这些块的大概数量可以由 `chunksize' 指定正整数设置。 对很
               长的迭代器来说，使用大的 `chunksize' 值比默认值 1 能显著
               地提高性能。 `chunksize' 对 *note ThreadPoolExecutor:
               27b. 没有效果。

               在 3.5 版更改: 加入 `chunksize' 参数。

           -- 方法: shutdown (wait=True)

               当待执行的 future 对象完成执行后向执行者发送信号，它就会
               释放正在使用的任何资源。 在关闭后调用 *note
               Executor.submit(): 2a5. 和 *note Executor.map(): 6c7. 将
               会引发 *note RuntimeError: 2bb.。

               如果 `wait' 为 ‘True’ 则此方法只有在所有待执行的 future 对
               象完成执行且释放已分配的资源后才会返回。 如果 `wait' 为
               ‘False’，方法立即返回，所有待执行的 future 对象完成执行后
               会释放已分配的资源。 不管 `wait' 的值是什么，整个 Python
               程序将等到所有待执行的 future 对象完成执行后才退出。

               如果使用 *note with: 6f2. 语句，你就可以避免显式调用这个
               方法，它将会停止 *note Executor: 2444. (就好像 *note
               Executor.shutdown(): b36. 调用时 `wait' 设为 ‘True’ 一样
               等待):

                    import shutil
                    with ThreadPoolExecutor(max_workers=4) as e:
                        e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
                        e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
                        e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
                        e.submit(shutil.copy, 'src4.txt', 'dest4.txt')


File: python.info,  Node: ThreadPoolExecutor,  Next: ProcessPoolExecutor,  Prev: Executor 对象,  Up: concurrent futures --- 启动并行任务

5.17.5.2 ThreadPoolExecutor
...........................

*note ThreadPoolExecutor: 27b. 是 *note Executor: 2444. 的子类，它使用线
程池来异步执行调用。

当回调已关联了一个 *note Future: b35. 然后再等待另一个 *note Future:
b35. 的结果时就会发产死锁情况。例如:

     import time
     def wait_on_b():
         time.sleep(5)
         print(b.result())  # b will never complete because it is waiting on a.
         return 5

     def wait_on_a():
         time.sleep(5)
         print(a.result())  # a will never complete because it is waiting on b.
         return 6


     executor = ThreadPoolExecutor(max_workers=2)
     a = executor.submit(wait_on_b)
     b = executor.submit(wait_on_a)

与:

     def wait_on_future():
         f = executor.submit(pow, 5, 2)
         # This will never complete because there is only one worker thread and
         # it is executing this function.
         print(f.result())

     executor = ThreadPoolExecutor(max_workers=1)
     executor.submit(wait_on_future)

 -- 类: concurrent.futures.ThreadPoolExecutor (max_workers=None,
          thread_name_prefix='', initializer=None, initargs=())

     *note Executor: 2444. 子类使用最多 `max_workers' 个线程的线程池来异
     步执行调用。

     `initializer' 是在每个工作者线程开始处调用的一个可选可调用对象。
     `initargs' 是传递给初始化器的元组参数。任何向池提交更多工作的尝试，
     `initializer' 都将引发一个异常，当前所有等待的工作都会引发一个
     *note BrokenThreadPool: 2448.。

     在 3.5 版更改: 如果 `max_workers' 为 ‘None’ 或没有指定，将默认为机
     器处理器的个数，假如 *note ThreadPoolExecutor: 27b. 侧重于 I/O 操作
     而不是 CPU 运算，那么可以乘以 ‘5’，同时工作线程的数量可以比 *note
     ProcessPoolExecutor: 2a4. 的数量高。

     3.6 新版功能: 添加 `thread_name_prefix' 参数允许用户控制由线程池创
     建的 *note threading.Thread: 235. 工作线程名称以方便调试。

     在 3.7 版更改: 加入 `initializer' 和*initargs* 参数。

     在 3.8 版更改: `max_workers' 的默认值已改为 ‘min(32, os.cpu_count()
     + 4)’。 这个默认值会保留至少 5 个工作线程用于 I/O 密集型任务。 对于
     那些释放了 GIL 的 CPU 密集型任务，它最多会使用 32 个 CPU 核心。这样
     能够避免在多核机器上不知不觉地使用大量资源。

     现在 ThreadPoolExecutor 在启动 `max_workers' 个工作线程之前也会重用
     空闲的工作线程。

* Menu:

* ThreadPoolExecutor 例子::


File: python.info,  Node: ThreadPoolExecutor 例子,  Up: ThreadPoolExecutor

5.17.5.3 ThreadPoolExecutor 例子
................................

     import concurrent.futures
     import urllib.request

     URLS = ['http://www.foxnews.com/',
             'http://www.cnn.com/',
             'http://europe.wsj.com/',
             'http://www.bbc.co.uk/',
             'http://some-made-up-domain.com/']

     # Retrieve a single page and report the URL and contents
     def load_url(url, timeout):
         with urllib.request.urlopen(url, timeout=timeout) as conn:
             return conn.read()

     # We can use a with statement to ensure threads are cleaned up promptly
     with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
         # Start the load operations and mark each future with its URL
         future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
         for future in concurrent.futures.as_completed(future_to_url):
             url = future_to_url[future]
             try:
                 data = future.result()
             except Exception as exc:
                 print('%r generated an exception: %s' % (url, exc))
             else:
                 print('%r page is %d bytes' % (url, len(data)))


File: python.info,  Node: ProcessPoolExecutor,  Next: Future 对象,  Prev: ThreadPoolExecutor,  Up: concurrent futures --- 启动并行任务

5.17.5.4 ProcessPoolExecutor
............................

*note ProcessPoolExecutor: 2a4. 类是 *note Executor: 2444. 的子类，它使
用进程池来异步地执行调用。 *note ProcessPoolExecutor: 2a4. 会使用 *note
multiprocessing: b8. 模块，这允许它绕过 *note 全局解释器锁: 50e. 但也意
味着只可以处理和返回可封存的对象。

‘__main__’ 模块必须可以被工作者子进程导入。这意味着 *note
ProcessPoolExecutor: 2a4. 不可以工作在交互式解释器中。

从可调用对象中调用 *note Executor: 2444. 或 *note Future: b35. 的方法提
交给 *note ProcessPoolExecutor: 2a4. 会导致死锁。

 -- 类: concurrent.futures.ProcessPoolExecutor (max_workers=None,
          mp_context=None, initializer=None, initargs=())

     异步地执行调用的 *note Executor: 2444. 子类使用最多具有
     `max_workers' 个进程的进程池。 如果 `max_workers' 为 ‘None’ 或未给
     出，它将默认为机器的处理器个数。 如果 `max_workers' 小于等于 ‘0’，
     则将引发 *note ValueError: 1fc.。 在 Windows 上，`max_workers' 必须
     小于等于 ‘61’，否则将引发 *note ValueError: 1fc.。 如果
     `max_workers' 为 ‘None’，则所选择的默认值最多为 ‘61’，即使存在更多
     的处理器。 `mp_context' 可以是一个多进程上下文或是 None。 它将被用
     来启动工作进程。 如果 `mp_context' 为 ‘None’ 或未给出，则将使用默认
     的多进程上下文。

     `initializer' 是一个可选的可调用对象，它会在每个工作进程启动时被调
     用；`initargs' 是传给 initializer 的参数元组。 如果 `initializer' 引
     发了异常，则所有当前在等待的任务以及任何向进程池提交更多任务的尝试
     都将引发 *note BrokenProcessPool: 244b.。

     在 3.3 版更改: 如果其中一个工作进程被突然终止，‘BrokenProcessPool’
     就会马上触发。 可预计的行为没有定义，但执行器上的操作或它的 future
     对象会被冻结或死锁。

     在 3.7 版更改: 添加 `mp_context' 参数允许用户控制由进程池创建给工作
     者进程的开始方法 。

     加入 `initializer' 和*initargs* 参数。

* Menu:

* ProcessPoolExecutor 例子::


File: python.info,  Node: ProcessPoolExecutor 例子,  Up: ProcessPoolExecutor

5.17.5.5 ProcessPoolExecutor 例子
.................................

     import concurrent.futures
     import math

     PRIMES = [
         112272535095293,
         112582705942171,
         112272535095293,
         115280095190773,
         115797848077099,
         1099726899285419]

     def is_prime(n):
         if n < 2:
             return False
         if n == 2:
             return True
         if n % 2 == 0:
             return False

         sqrt_n = int(math.floor(math.sqrt(n)))
         for i in range(3, sqrt_n + 1, 2):
             if n % i == 0:
                 return False
         return True

     def main():
         with concurrent.futures.ProcessPoolExecutor() as executor:
             for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
                 print('%d is prime: %s' % (number, prime))

     if __name__ == '__main__':
         main()


File: python.info,  Node: Future 对象,  Next: 模块函数,  Prev: ProcessPoolExecutor,  Up: concurrent futures --- 启动并行任务

5.17.5.6 Future 对象
....................

*note Future: b35. 类将可调用对象封装为异步执行。*note Future: b35. 实例
由 *note Executor.submit(): 2a5. 创建。

 -- 类: concurrent.futures.Future

     将可调用对象封装为异步执行。*note Future: b35. 实例由 *note
     Executor.submit(): 2a5. 创建，除非测试，不应直接创建。

           -- 方法: cancel ()

               尝试取消调用。 如果调用正在执行或已结束运行不能被取消则该
               方法将返回 ‘False’，否则调用会被取消并且该方法将返回
               ‘True’。

           -- 方法: cancelled ()

               如果调用成功取消返回 ‘True’。

           -- 方法: running ()

               如果调用正在执行而且不能被取消那么返回 ‘True’ 。

           -- 方法: done ()

               如果调用已被取消或正常结束那么返回 ‘True’。

           -- 方法: result (timeout=None)

               返回调用返回的值。如果调用还没完成那么这个方法将等待
               `timeout' 秒。如果在 `timeout' 秒内没有执行完成，*note
               concurrent.futures.TimeoutError: 2446. 将会被触发。
               `timeout' 可以是整数或浮点数。如果 `timeout' 没有指定或为
               ‘None’，那么等待时间就没有限制。

               如果 futrue 在完成前被取消则 *note CancelledError: 1ab. 将
               被触发。

               如果调用引发了一个异常，这个方法也会引发同样的异常。

           -- 方法: exception (timeout=None)

               返回由调用引发的异常。如果调用还没完成那么这个方法将等待
               `timeout' 秒。如果在 `timeout' 秒内没有执行完成，*note
               concurrent.futures.TimeoutError: 2446. 将会被触发。
               `timeout' 可以是整数或浮点数。如果 `timeout' 没有指定或为
               ‘None’，那么等待时间就没有限制。

               如果 futrue 在完成前被取消则 *note CancelledError: 1ab. 将
               被触发。

               如果调用正常完成那么返回 ‘None’。

           -- 方法: add_done_callback (fn)

               附加可调用 `fn' 到 future 对象。当 future 对象被取消或完
               成运行时，将会调用 `fn'，而这个 future 对象将作为它唯一的
               参数。

               加入的可调用对象总被属于添加它们的进程中的线程按加入的顺
               序调用。如果可调用对象引发一个 *note Exception: 1aa. 子类
               ，它会被记录下来并被忽略掉。如果可调用对象引发一个 *note
               BaseException: 1a9. 子类，这个行为没有定义。

               如果 future 对象已经完成或已取消，`fn' 会被立即调用。

     下面这些 *note Future: b35. 方法用于单元测试和 *note Executor:
     2444. 实现。

           -- 方法: set_running_or_notify_cancel ()

               这个方法只可以在执行关联 *note Future: b35. 工作之前由
               *note Executor: 2444. 实现调用或由单测试调用。

               如果这个方法返回 ‘False’ 那么 *note Future: b35. 已被取消
               ，即 *note Future.cancel(): 244e. 已被调用并返回 ‘True’ 。
               等待 *note Future: b35. 完成 (即通过 *note
               as_completed(): 10fe. 或 *note wait(): 2456.) 的线程将被
               唤醒。

               如果这个方法返回 ‘True’ 那么 *note Future: b35. 不会被取
               消并已将它变为正在运行状态，也就是说调用 *note
               Future.running(): 2450. 时将返回 ‘True’。

               这个方法只可以被调用一次并且不能在调用 *note
               Future.set_result(): 2457. 或 *note
               Future.set_exception(): 2458. 之后再调用。

           -- 方法: set_result (result)

               设置将 *note Future: b35. 关联工作的结果给 `result' 。

               这个方法只可以由 *note Executor: 2444. 实现和单元测试使用
               。

               在 3.8 版更改: 如果 *note Future: b35. 已经完成则此方法会
               引发 *note concurrent.futures.InvalidStateError: 2459.。

           -- 方法: set_exception (exception)

               设置 *note Future: b35. 关联工作的结果给 *note Exception:
               1aa. `exception' 。

               这个方法只可以由 *note Executor: 2444. 实现和单元测试使用
               。

               在 3.8 版更改: 如果 *note Future: b35. 已经完成则此方法会
               引发 *note concurrent.futures.InvalidStateError: 2459.。


File: python.info,  Node: 模块函数,  Next: Exception类,  Prev: Future 对象,  Up: concurrent futures --- 启动并行任务

5.17.5.7 模块函数
.................

 -- 函数: concurrent.futures.wait (fs, timeout=None,
          return_when=ALL_COMPLETED)

     等待 `fs' 指定的 *note Future: b35. 实例（可能由不同的 *note
     Executor: 2444. 实例创建）完成。 返回一个由集合构成的具名 2 元组。
     第一个集合名称为 ‘done’，包含在等待完成之前已完成的期程（包括正常结
     束或被取消的 future 对象）。 第二个集合名称为 ‘not_done’，包含未完
     成的 future 对象（包括挂起的或正在运行的 future 对象）。

     `timeout' 可以用来控制返回前最大的等待秒数。 `timeout' 可以为 int 或
     float 类型。 如果 `timeout' 未指定或为 ‘None’ ，则不限制等待时间。

     `return_when' 指定此函数应在何时返回。它必须为以下常数之一:

     常数                              描述
                                       
     -------------------------------------------------------------------------------
                                       
     ‘FIRST_COMPLETED’                 函数将在任意可等待对象结束或取消时返回。
                                       
                                       
     ‘FIRST_EXCEPTION’                 函数将在任意可等待对象因引发异常而结束时返
                                       回。当没有引发任何异常时它就相当于
                                       ‘ALL_COMPLETED’。
                                       
                                       
     ‘ALL_COMPLETED’                   函数将在所有可等待对象结束或取消时返回。
                                       

 -- 函数: concurrent.futures.as_completed (fs, timeout=None)

     返回一个包含 `fs' 所指定的 *note Future: b35. 实例（可能由不同的
     *note Executor: 2444. 实例创建）的迭代器，这些实例会在完成时生成
     future 对象（包括正常结束或被取消的 future 对象）。 任何由 `fs' 所
     指定的重复 future 对象将只被返回一次。 任何在 *note as_completed():
     10fe. 被调用之前完成的 future 对象将优先被生成。 如果 *note
     __next__(): c6c. 被调用并且在对 *note as_completed(): 10fe. 的原始
     调用 `timeout' 秒之后结果仍不可用，则返回的迭代器将引发 *note
     concurrent.futures.TimeoutError: 2446.。 `timeout' 可以为整数或浮点
     数。 如果 `timeout' 未指定或为 ‘None’，则不限制等待时间。

参见
....

PEP 3148(1) – future 对象 - 异步执行指令。

     该提案描述了Python标准库中包含的这个特性。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3148


File: python.info,  Node: Exception类,  Prev: 模块函数,  Up: concurrent futures --- 启动并行任务

5.17.5.8 Exception类
....................

 -- 例外: concurrent.futures.CancelledError

     future 对象被取消时会触发。

 -- 例外: concurrent.futures.TimeoutError

     future 对象执行超出给定的超时数值时引发。

 -- 例外: concurrent.futures.BrokenExecutor

     当执行器被某些原因中断而且不能用来提交或执行新任务时就会被引发派生
     于 *note RuntimeError: 2bb. 的异常类。

     3.7 新版功能.

 -- 例外: concurrent.futures.InvalidStateError

     当某个操作在一个当前状态所不允许的 future 上执行时将被引发。

     3.8 新版功能.

 -- 例外: concurrent.futures.thread.BrokenThreadPool

     当 ‘ThreadPoolExecutor’ 中的其中一个工作者初始化失败时会引发派生于
     *note BrokenExecutor: 245c. 的异常类。

     3.7 新版功能.

 -- 例外: concurrent.futures.process.BrokenProcessPool

     当 ‘ThreadPoolExecutor’ 中的其中一个工作者不完整终止时(比如，被外部
     杀死)会引发派生于 *note BrokenExecutor: 245c. ( 原名 *note
     RuntimeError: 2bb. ) 的异常类。

     3.3 新版功能.


File: python.info,  Node: subprocess --- 子进程管理,  Next: sched --- 事件调度器,  Prev: concurrent futures --- 启动并行任务,  Up: 并发执行

5.17.6 ‘subprocess’ — 子进程管理
--------------------------------

`源代码:' Lib/subprocess.py(1)

__________________________________________________________________

*note subprocess: fa. 模块允许你生成新的进程，连接它们的输入、输出、错误
管道，并且获取它们的返回码。此模块打算代替一些老旧的模块与功能：

     os.system
     os.spawn*

在下面的段落中，你可以找到关于 *note subprocess: fa. 模块如何代替这些模
块和功能的相关信息。

参见
....

PEP 324(2) – 提出 subprocess 模块的 PEP

* Menu:

* 使用 subprocess 模块::
* 安全考量::
* Popen 对象::
* Windows Popen 助手::
* 较旧的高阶 API::
* 使用 subprocess 模块替换旧函数::
* 旧式的 Shell 发起函数::
* 注释: 注释<2>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/subprocess.py

   (2) https://www.python.org/dev/peps/pep-0324


File: python.info,  Node: 使用 subprocess 模块,  Next: 安全考量,  Up: subprocess --- 子进程管理

5.17.6.1 使用 ‘subprocess’ 模块
...............................

推荐的调用子进程的方式是在任何它支持的用例中使用 *note run(): 3f5. 函数
。对于更进阶的用例，也可以使用底层的 *note Popen: 2ba. 接口。

*note run(): 3f5. 函数是在 Python 3.5 被添加的；如果你需要与旧版本保持兼
容，查看 *note 较旧的高阶 API: 2460. 段落。

 -- 函数: subprocess.run (args, *, stdin=None, input=None, stdout=None,
          stderr=None, capture_output=False, shell=False, cwd=None,
          timeout=None, check=False, encoding=None, errors=None,
          text=None, env=None, universal_newlines=None,
          **other_popen_kwargs)

     运行被 `arg' 描述的指令. 等待指令完成, 然后返回一个 *note
     CompletedProcess: 769. 实例.

     以上显示的参数仅仅是最简单的一些，下面 *note 常用参数: 2461. 描述（
     因此在缩写签名中使用仅关键字标示）。完整的函数头和 *note Popen:
     2ba. 的构造函数一样，此函数接受的大多数参数都被传递给该接口。（
     `timeout', `input', `check' 和 `capture_output' 除外）。

     如果 `capture_output' 设为 true，stdout 和 stderr 将会被捕获。在使
     用时，内置的 *note Popen: 2ba. 对象将自动用 ‘stdout=PIPE’ 和
     ‘stderr=PIPE’ 创建。`stdout' 和 `stderr' 参数不应当与
     `capture_output' 同时提供。如果你希望捕获并将两个流合并在一起，使用
     ‘stdout=PIPE’ 和 ‘stderr=STDOUT’ 来代替 `capture_output'。

     `timeout' 参数将被传递给 *note Popen.communicate(): 2462.。如果发生
     超时，子进程将被杀死并等待。 *note TimeoutExpired: 2463. 异常将在子
     进程中断后被抛出。

     `input' 参数将被传递给 *note Popen.communicate(): 2462. 以及子进程
     的 stdin。 如果使用此参数，它必须是一个字节序列。 如果指定了
     `encoding' 或 `errors' 或者将 `text' 设置为 ‘True’，那么也可以是一
     个字符串。 当使用此参数时，在创建内部 *note Popen: 2ba. 对象时将自
     动带上 ‘stdin=PIPE’，并且不能再手动指定 `stdin' 参数。

     如果 `check' 设为 True, 并且进程以非零状态码退出, 一个 *note
     CalledProcessError: cbd. 异常将被抛出. 这个异常的属性将设置为参数,
     退出码, 以及标准输出和标准错误, 如果被捕获到.

     如果 `encoding' 或者 `error' 被指定, 或者 `text' 被设为 True, 标准
     输入, 标准输出和标准错误的文件对象将通过指定的 `encoding' 和
     `errors' 以文本模式打开, 否则以默认的 *note io.TextIOWrapper: 5fc.
     打开.  `universal_newline' 参数等同于 `text' 并且提供了向后兼容性.
     默认情况下, 文件对象是以二进制模式打开的.

     如果 `env' 不是 ‘None’, 它必须是一个字典, 为新的进程设置环境变量; 它
     用于替换继承的当前进程的环境的默认行为. 它将直接被传递给 *note
     Popen: 2ba.

     示例:

          >>> subprocess.run(["ls", "-l"])  # doesn't capture output
          CompletedProcess(args=['ls', '-l'], returncode=0)

          >>> subprocess.run("exit 1", shell=True, check=True)
          Traceback (most recent call last):
            ...
          subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

          >>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
          CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
          stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')

     3.5 新版功能.

     在 3.6 版更改: 添加了 `encoding' 和 `errors' 形参.

     在 3.7 版更改: 添加了 `text' 形参, 作为 `universal_newlines' 的一个
     更好理解的别名. 添加了 `capture_output' 形参.

 -- 类: subprocess.CompletedProcess

     *note run(): 3f5. 的返回值, 代表一个进程已经结束.

      -- 属性: args

          被用作启动进程的参数. 可能是一个列表或字符串.

      -- 属性: returncode

          子进程的退出状态码. 通常来说, 一个为 0 的退出码表示进程运行正
          常.

          一个负值 ‘-N’ 表示子进程被信号 ‘N’ 中断 (仅 POSIX).

      -- 属性: stdout

          从子进程捕获到的标准输出. 一个字节序列, 或一个字符串, 如果
          *note run(): 3f5. 是设置了 `encoding', `errors' 或者
          ‘text=True’ 来运行的. 如果未有捕获, 则为 ‘None’.

          如果你通过 ‘stderr=subprocess.STDOUT’ 运行进程，标准输入和标准
          错误将被组合在这个属性中，并且 *note stderr: 2467. 将为
          ‘None’。

      -- 属性: stderr

          捕获到的子进程的标准错误. 一个字节序列, 或者一个字符串, 如果
          *note run(): 3f5. 是设置了参数 `encoding', `errors' 或者
          ‘text=True’ 运行的. 如果未有捕获, 则为 ‘None’.

      -- 方法: check_returncode ()

          如果 *note returncode: 2465. 非零, 抛出 *note
          CalledProcessError: cbd.

     3.5 新版功能.

 -- 数据: subprocess.DEVNULL

     可被 *note Popen: 2ba. 的 `stdin', `stdout' 或者 `stderr' 参数使用
     的特殊值, 表示使用特殊文件 *note os.devnull: 102a.

     3.3 新版功能.

 -- 数据: subprocess.PIPE

     可被 *note Popen: 2ba. 的 `stdin', `stdout' 或者 `stderr' 参数使用
     的特殊值, 表示打开标准流的管道. 常用于 *note Popen.communicate():
     2462.

 -- 数据: subprocess.STDOUT

     可被 *note Popen: 2ba. 的 `stdin' ， `stdout' 或者 `stderr' 参数使
     用的特殊值， 表示标准错误与标准输出使用同一句柄。

 -- 例外: subprocess.SubprocessError

     此模块的其他异常的基类。

     3.3 新版功能.

 -- 例外: subprocess.TimeoutExpired

     *note SubprocessError: 246a. 的子类，等待子进程的过程中发生超时时被
     抛出。

      -- 属性: cmd

          用于创建子进程的指令。

      -- 属性: timeout

          超时秒数。

      -- 属性: output

          子进程的输出， 如果被 *note run(): 3f5. 或 *note
          check_output(): 8e3. 捕获。否则为 ‘None’。

      -- 属性: stdout

          对 output 的别名，对应的有 *note stderr: 246f.。

      -- 属性: stderr

          子进程的标准错误输出，如果被 *note run(): 3f5. 捕获。 否则为
          ‘None’。

     3.3 新版功能.

     在 3.5 版更改: 添加了 `stdout' 和 `stderr' 属性。

 -- 例外: subprocess.CalledProcessError

     *note SubprocessError: 246a. 的子类，当一个被 *note check_call():
     2470. 或 *note check_output(): 8e3. 函数运行的子进程返回了非零退出
     码时被抛出。

      -- 属性: returncode

          子进程的退出状态。如果程序由一个信号终止，这将会被设为一个负的
          信号码。

      -- 属性: cmd

          用于创建子进程的指令。

      -- 属性: output

          子进程的输出， 如果被 *note run(): 3f5. 或 *note
          check_output(): 8e3. 捕获。否则为 ‘None’。

      -- 属性: stdout

          对 output 的别名，对应的有 *note stderr: 2475.。

      -- 属性: stderr

          子进程的标准错误输出，如果被 *note run(): 3f5. 捕获。 否则为
          ‘None’。

     在 3.5 版更改: 添加了 `stdout' 和 `stderr' 属性。

* Menu:

* 常用参数::
* Popen 构造函数::
* 异常: 异常<7>.


File: python.info,  Node: 常用参数,  Next: Popen 构造函数,  Up: 使用 subprocess 模块

5.17.6.2 常用参数
.................

为了支持丰富的使用案例， *note Popen: 2ba. 的构造函数（以及方便的函数）
接受大量可选的参数。对于大多数典型的用例，许多参数可以被安全地留以它们的
默认值。通常需要的参数有：

     `args' 被所有调用需要，应当为一个字符串，或者一个程序参数序列。提供
     一个参数序列通常更好，它可以更小心地使用参数中的转义字符以及引用（
     例如允许文件名中的空格）。如果传递一个简单的字符串，则 `shell' 参数
     必须为 *note True: 4a1. （见下文）或者该字符串中将被运行的程序名必
     须用简单的命名而不指定任何参数。

     `stdin'， `stdout' 和 `stderr' 分别指定了执行的程序的标准输入、输出
     和标准错误文件句柄。合法的值有 *note PIPE: 3f6. 、 *note DEVNULL:
     aa8. 、 一个现存的文件描述符（一个正整数）、一个现存的文件对象以及
     ‘None’。 *note PIPE: 3f6. 表示应该新建一个对子进程的管道。 *note
     DEVNULL: aa8. 表示使用特殊的文件 *note os.devnull: 102a.。当使用默
     认设置 ‘None’ 时，将不会进行重定向，子进程的文件流将继承自父进程。
     另外， `stderr' 可能为 *note STDOUT: 2469.，表示来自于子进程的标准
     错误数据应该被 `stdout' 相同的句柄捕获。

     如果 `encoding' 或 `errors' 被指定，或者 `text' （也名为
     `universal_newlines'）为真，则文件对象 `stdin' 、 `stdout' 与
     `stderr' 将会使用在此次调用中指定的 `encoding' 和 `errors' 以文本模
     式打开或者为默认的 *note io.TextIOWrapper: 5fc.。

     当构造函数的 `newline' 参数为 ‘None’ 时。对于 `stdin'， 输入的换行
     符 ‘'\n'’ 将被转换为默认的换行符 *note os.linesep: 160c.。对于
     `stdout' 和 `stderr'， 所有输出的换行符都被转换为 ‘'\n'’。更多信息
     ，查看 *note io.TextIOWrapper: 5fc. 类的文档。

     如果文本模式未被使用， `stdin'， `stdout' 和 `stderr' 将会以二进制
     流模式打开。没有编码与换行符转换发生。

     3.6 新版功能: 添加了 `encoding' 和 `errors' 形参。

     3.7 新版功能: 添加了 `text' 形参作为 `universal_newlines' 的别名。

          注解: 文件对象 *note Popen.stdin: 2477. 、 *note Popen.stdout:
          2478. 和 *note Popen.stderr: 2479. 的换行符属性不会被 *note
          Popen.communicate(): 2462. 方法更新。

     如果 `shell' 设为 ‘True’,，则使用 shell 执行指定的指令。如果您主要
     使用 Python 增强的控制流（它比大多数系统 shell 提供的强大），并且仍
     然希望方便地使用其他 shell 功能，如 shell 管道、文件通配符、环境变
     量展开以及 ‘~’ 展开到用户家目录，这将非常有用。但是，注意 Python 自
     己也实现了许多类似 shell 的特性（例如 *note glob: 8a, *note
     fnmatch: 81, *note os.walk(): 65d, *note os.path.expandvars(): d4c,
     *note os.path.expanduser(): 1ff. 和 *note shutil: ea.）。

     在 3.3 版更改: 当 `universal_newline' 被设为 ‘True’，则类使用 *note
     locale.getpreferredencoding(False): 3ad. 编码来代替
     ‘locale.getpreferredencoding()’。关于它们的区别的更多信息，见 *note
     io.TextIOWrapper: 5fc.。

          注解: 在使用 ‘shell=True’ 之前， 请阅读 *note Security
          Considerations: 247a. 段落。

这些选项以及所有其他选项在 *note Popen: 2ba. 构造函数文档中有更详细的描
述。


File: python.info,  Node: Popen 构造函数,  Next: 异常<7>,  Prev: 常用参数,  Up: 使用 subprocess 模块

5.17.6.3 Popen 构造函数
.......................

此模块的底层的进程创建与管理由 *note Popen: 2ba. 类处理。它提供了很大的
灵活性，因此开发者能够处理未被便利函数覆盖的不常见用例。

 -- 类: subprocess.Popen (args, bufsize=-1, executable=None, stdin=None,
          stdout=None, stderr=None, preexec_fn=None, close_fds=True,
          shell=False, cwd=None, env=None, universal_newlines=None,
          startupinfo=None, creationflags=0, restore_signals=True,
          start_new_session=False, pass_fds=(), *, encoding=None,
          errors=None, text=None)

     在一个新的进程中执行子程序。在 POSIX，此类使用类似于 *note
     os.execvp(): 1f9e. 的行为来执行子程序。在 Windows，此类使用了
     Windows ‘CreateProcess()’ 函数。 *note Popen: 2ba. 的参数如下：

     `args' 应当是一个程序参数的序列或者是一个单独的字符串或 *note
     path-like object: 373.。 默认情况下，如果 `args' 是序列则要运行的程
     序为 `args' 中的第一项。 如果 `args' 是字符串，则其解读依赖于具体平
     台，如下所述。 请查看 `shell' 和 `executable' 参数了解其与默认行为
     的其他差异。 除非另有说明，否则推荐以序列形式传入 `args'。

     向外部函数传入序列形式参数的一个例子如下:

          Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])

     在 POSIX，如果 `args' 是一个字符串，此字符串被作为将被执行的程序的
     命名或路径解释。但是，只有在不传递任何参数给程序的情况下才能这么做
     。

          注解: 将 shell 命令拆分为参数序列的方式可能并不很直观，特别是
          在复杂的情况下。 *note shlex.split(): 219. 可以演示如何确定
          `args' 适当的拆分形式:

               >>> import shlex, subprocess
               >>> command_line = input()
               /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
               >>> args = shlex.split(command_line)
               >>> print(args)
               ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
               >>> p = subprocess.Popen(args) # Success!

          特别注意，由 shell 中的空格分隔的选项（例如 `-input'）和参数（
          例如 `eggs.txt' ）位于分开的列表元素中，而在需要时使用引号或反
          斜杠转义的参数在 shell （例如包含空格的文件名或上面显示的
          `echo' 命令）是单独的列表元素。

     在 Windows，如果 `args' 是一个序列，他将通过一个在 *note 在 Windows
     上将参数列表转换为一个字符串: 247c. 描述的方式被转换为一个字符串。
     这是因为底层的 ‘CreateProcess()’ 只处理字符串。

     在 3.6 版更改: 如果 `shell' 为 ‘False’ 并且序列包含 POSIX 上的路径
     类对象则 `args' 形参可以接受一个 *note path-like object: 373.。

     在 3.8 版更改: 如果在Windows 上 `shell' 为 ‘False’ 并且序列包含字节
     串和路径类对象则 `args' 形参可以接受一个 *note path-like object:
     373.。

     参数 `shell' （默认为 ‘False’）指定是否使用 shell 执行程序。如果
     `shell' 为 ‘True’，更推荐将 `args' 作为字符串传递而非序列。

     在 POSIX，当 ‘shell=True’， shell 默认为 ‘/bin/sh’。如果 `args' 是
     一个字符串，此字符串指定将通过 shell 执行的命令。这意味着字符串的格
     式必须和在命令提示符中所输入的完全相同。这包括，例如，引号和反斜杠
     转义包含空格的文件名。如果 `args' 是一个序列，第一项指定了命令，另
     外的项目将作为传递给 shell （而非命令） 的参数对待。也就是说，
     *note Popen: 2ba. 等同于:

          Popen(['/bin/sh', '-c', args[0], args[1], ...])

     在 Windows，使用 ‘shell=True’，环境变量 ‘COMSPEC’ 指定了默认 shell。
     在 Windows 你唯一需要指定 ‘shell=True’ 的情况是你想要执行内置在
     shell 中的命令（例如 ‘dir’ 或者 ‘copy’）。在运行一个批处理文件或者
     基于控制台的可执行文件时，不需要 ‘shell=True’。

          注解: 在使用 ‘shell=True’ 之前， 请阅读 *note Security
          Considerations: 247a. 段落。

     `bufsize' 将在 *note open(): 4f8. 函数创建了 stdin/stdout/stderr 管
     道文件对象时作为对应的参数供应:

        - ‘0’ 表示不使用缓冲区 （读取与写入是一个系统调用并且可以返回短
          内容）

        - ‘1’ 表示行缓冲（只有 ‘universal_newlines=True’ 时才有用，例如
          ，在文本模式中）

        - 任何其他正值表示使用一个约为对应大小的缓冲区

        - 负的 `bufsize' （默认）表示使用系统默认的
          io.DEFAULT_BUFFER_SIZE。

     在 3.3.1 版更改: `bufsize' 现在默认为 -1 来启用缓冲，以符合大多数代
     码所期望的行为。在 Python 3.2.4 和 3.3.1 之前的版本中，它错误地将默
     认值设为了为 ‘0’，这是无缓冲的并且允许短读取。这是无意的，并且与大
     多数代码所期望的 Python 2 的行为不一致。

     `executable' 参数指定一个要执行的替换程序。这很少需要。当
     ‘shell=True’， `executable' 替换 `args' 指定运行的程序。但是，原始
     的 `args' 仍然被传递给程序。大多数程序将被 `args' 指定的程序作为命
     令名对待，这可以与实际运行的程序不同。在 POSIX， `args' 名作为实际
     调用程序中可执行文件的显示名称，例如 ‘ps’。如果 ‘shell=True’，在
     POSIX， `executable' 参数指定用于替换默认 shell ‘/bin/sh’ 的 shell。

     在 3.6 版更改: 在POSIX 上 `executable' 形参可以接受一个 *note
     path-like object: 373.。

     在 3.8 版更改: 在Windows 上 `executable' 形参可以接受一个字节串和
     *note path-like object: 373.。

     `stdin', `stdout' 和 `stderr' 分别指定被运行的程序的标准输入、输出
     和标准错误的文件句柄。合法的值有 *note PIPE: 3f6. ， *note DEVNULL:
     aa8. ， 一个存在的文件描述符（一个正整数），一个存在的 *note
     文件对象: b4a. 以及 ‘None’。 *note PIPE: 3f6. 表示应创建一个新的对
     子进程的管道。 *note DEVNULL: aa8. 表示使用特殊的 *note os.devnull:
     102a. 文件。使用默认的 ‘None’，则不进行成定向；子进程的文件流将继承
     自父进程。另外， `stderr' 可设为 *note STDOUT: 2469.，表示应用程序
     的标准错误数据应和标准输出一同捕获。

     如果 `preexec_fn' 被设为一个可调用对象，此对象将在子进程刚创建时被
     调用。（仅 POSIX）

          警告: `preexec_fn' 形参在应用程序中存在多线程时是不安全的。子
          进程在调用前可能死锁。如果你必须使用它，保持警惕！最小化你调用
          的库的数量。

          注解: 如果你需要修改子进程环境，使用 `env' 形参而非在
          `preexec_fn' 中进行。 `start_new_session' 形参可以代替之前常用
          的 `preexec_fn' 来在子进程中调用 os.setsid()。

     在 3.8 版更改: `preexec_fn' 形参在子解释器中已不再受支持。 在子解释
     器中使用此形参将引发 *note RuntimeError: 2bb.。 这个新限制可能会影
     响部署在 mod_wsgi, uWSGI 和其他嵌入式环境中的应用。

     如果 `close_fds' 为真，所有文件描述符除了 ‘0’, ‘1’, ‘2’ 之外都会在
     子进程执行前关闭。而当 `close_fds' 为假时，文件描述符遵守它们继承的
     标志，如 *note 文件描述符的继承: 803. 所述。

     在 Windows，如果 `close_fds' 为真， 则子进程不会继承任何句柄，除非
     在 ‘STARTUPINFO.IpAttributeList’ 的 ‘handle_list’ 的键中显式传递，
     或者通过标准句柄重定向传递。

     在 3.2 版更改: `close_fds' 的默认值已经从 *note False: 390. 修改为
     上述值。

     在 3.7 版更改: 在 Windows，当重定向标准句柄时 `close_fds' 的默认值
     从 *note False: 390. 变为 *note True: 4a1.。现在重定向标准句柄时有
     可能设置 `close_fds' 为 *note True: 4a1.。（标准句柄指三个 stdio 的
     句柄）

     `pass_fds' 是一个可选的在父子进程间保持打开的文件描述符序列。提供任
     何 `pass_fds' 将强制 `close_fds' 为 *note True: 4a1.。（仅 POSIX）

     在 3.2 版更改: 加入了 `pass_fds' 形参。

     如果 `cwd' 不为 ‘None’，此函数在执行子进程前会将当前工作目录改为
     `cwd'。 `cwd' 可以是一个字符串、字节串或 *note 路径类对象: 373. 。
     特别地，当可执行文件的路径为相对路径时，此函数会相对于*cwd* 来查找
     `executable' (或 `args' 中的第一个条目)。

     在 3.6 版更改: 在 POSIX 上 `cwd' 形参接受一个 *note path-like
     object: 373.。

     在 3.7 版更改: 在 Windows 上 `cwd' 形参接受一个 *note path-like
     object: 373.。

     在 3.8 版更改: 在 Windows 上 `cwd' 形参接受一个字节串对象。

     如果 `restore_signals' 为 true（默认值），则 Python 设置为 SIG_IGN
     的所有信号将在 exec 之前的子进程中恢复为 SIG_DFL。目前，这包括
     SIGPIPE ，SIGXFZ 和 SIGXFSZ 信号。 （仅 POSIX）

     在 3.2 版更改: `restore_signals' 被加入。

     如果 `start_new_session' 为 true，则 setsid() 系统调用将在子进程执
     行之前被执行。（仅 POSIX）

     在 3.2 版更改: `start_new_session' 被添加。

     如果 `env' 不为 ‘None’，则必须为一个为新进程定义了环境变量的字典；
     这些用于替换继承的当前进程环境的默认行为。

          注解: 如果指定， `env' 必须提供所有被子进程需求的变量。在
          Windows，为了运行一个 side-by-side assembly(1) ，指定的 `env'
          `必须' 包含一个有效的 ‘SystemRoot’。

     如果 `encoding' 或 `errors' 被指定，或者 `text' 为 true，则文件对象
     `stdin', `stdout' 和 `stderr' 将会以指定的编码和 `errors' 以文本模
     式打开，如同 *note 常用参数: 2461. 所述。 `universal_newlines' 参数
     等同于 `text' 并且提供向后兼容性。默认情况下，文件对象都以二进制模
     式打开。

     3.6 新版功能: `encoding' 和 `errors' 被添加。

     3.7 新版功能: `text' 作为 `universal_newlines' 的一个更具可读性的别
     名被添加。

     如果给出， `startupinfo' 将是一个将被传递给底层的 ‘CreateProcess’ 函
     数的 *note STARTUPINFO: 247d. 对象。 `creationflags'，如果给出，可
     以是一个或多个以下标志之一：

             * *note CREATE_NEW_CONSOLE: 247e.

             * *note CREATE_NEW_PROCESS_GROUP: 247f.

             * *note ABOVE_NORMAL_PRIORITY_CLASS: 2480.

             * *note BELOW_NORMAL_PRIORITY_CLASS: 2481.

             * *note HIGH_PRIORITY_CLASS: 2482.

             * *note IDLE_PRIORITY_CLASS: 2483.

             * *note NORMAL_PRIORITY_CLASS: 2484.

             * *note REALTIME_PRIORITY_CLASS: 2485.

             * *note CREATE_NO_WINDOW: 2486.

             * *note DETACHED_PROCESS: 2487.

             * *note CREATE_DEFAULT_ERROR_MODE: 2488.

             * *note CREATE_BREAKAWAY_FROM_JOB: 2489.

     Popen 对象支持通过 *note with: 6f2. 语句作为上下文管理器，在退出时
     关闭文件描述符并等待进程:

          with Popen(["ifconfig"], stdout=PIPE) as proc:
              log.write(proc.stdout.read())

     引发一个 *note 审计事件: ea1. ‘subprocess.Popen’，附带参数
     ‘executable’, ‘args’, ‘cwd’, ‘env’。

     在 3.2 版更改: 添加了上下文管理器支持。

     在 3.6 版更改: 现在，如果 Popen 析构时子进程仍然在运行，则析构器会
     发送一个 *note ResourceWarning: 4d8. 警告。

     在 3.8 版更改: 在某些情况下 Popen 可以使用 *note os.posix_spawn():
     258. 以获得更好的性能。在适用于 Linux 的 Windows 子系统和 QEMU 用户
     模拟器上，使用 *note os.posix_spawn(): 258. 的 Popen 构造器不再会因
     找不到程序等错误而引发异常，而是上下级进程失败并返回一个非零的
     *note returncode: 248a.。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Side-by-Side_Assembly


File: python.info,  Node: 异常<7>,  Prev: Popen 构造函数,  Up: 使用 subprocess 模块

5.17.6.4 异常
.............

在子进程中抛出的异常，在新的进程开始执行前，将会被再次在父进程中抛出。

最常见的被抛出异常是 *note OSError: 1d4.。例如，当尝试执行一个不存在的文
件时就会发生。应用程序需要为 *note OSError: 1d4. 异常做好准备。

如果 *note Popen: 2ba. 调用时有无效的参数，则一个 *note ValueError: 1fc.
将被抛出。

*note check_call(): 2470. 与 *note check_output(): 8e3. 在调用的进程返回
非零退出码时将抛出 *note CalledProcessError: cbd.。

所有接受 `timeout' 形参的函数与方法，例如 *note call(): 3f7. 和 *note
Popen.communicate(): 2462. 将会在进程退出前超时到期时抛出 *note
TimeoutExpired: 2463.。

此模块中定义的异常都继承自 *note SubprocessError: 246a.。

     3.3 新版功能: 基类 *note SubprocessError: 246a. 被添加。


File: python.info,  Node: 安全考量,  Next: Popen 对象,  Prev: 使用 subprocess 模块,  Up: subprocess --- 子进程管理

5.17.6.5 安全考量
.................

不像一些其他的 popen 功能，此实现绝不会隐式调用一个系统 shell。这意味着
任何字符，包括 shell 元字符，可以安全地被传递给子进程。如果 shell 被明确
地调用，通过 ‘shell=True’ 设置，则确保所有空白字符和元字符被恰当地包裹在
引号内以避免 shell 注入(1) 漏洞就由应用程序负责了。

当使用 ‘shell=True’， *note shlex.quote(): a7b. 函数可以作为在将被用于构
造 shell 指令的字符串中转义空白字符以及 shell 元字符的方案。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Shell_injection#Shell_injection


File: python.info,  Node: Popen 对象,  Next: Windows Popen 助手,  Prev: 安全考量,  Up: subprocess --- 子进程管理

5.17.6.6 Popen 对象
...................

*note Popen: 2ba. 类的实例拥有以下方法：

 -- 方法: Popen.poll ()

     检查子进程是否已被终止。设置并返回 *note returncode: 248a. 属性。否
     则返回 ‘None’。

 -- 方法: Popen.wait (timeout=None)

     等待子进程被终止。设置并返回 *note returncode: 248a. 属性。

     如果进程在 `timeout' 秒后未中断，抛出一个 *note TimeoutExpired:
     2463. 异常，可以安全地捕获此异常并重新等待。

          注解: 当 ‘stdout=PIPE’ 或者 ‘stderr=PIPE’ 并且子进程产生了足以
          阻塞 OS 管道缓冲区接收更多数据的输出到管道时，将会发生死锁。当
          使用管道时用 *note Popen.communicate(): 2462. 来规避它。

          注解: 此函数使用了一个 busy loop （非阻塞调用以及短睡眠） 实现
          。使用 *note asyncio: a. 模块进行异步等待： 参阅 *note
          asyncio.create_subprocess_exec: 292.。

     在 3.3 版更改: `timeout' 被添加

 -- 方法: Popen.communicate (input=None, timeout=None)

     与进程交互：将数据发送到 stdin。 从 stdout 和 stderr 读取数据，直到
     抵达文件结尾。 等待进程终止并设置 *note returncode: 248a. 属性。 可
     选的 `input' 参数应为要发送到下级进程的数据，或者如果没有要发送到下
     级进程的数据则为 ‘None’。 如果流是以文本模式打开的，则 `input' 必须
     为字符串。 在其他情况下，它必须为字节串。

     *note communicate(): 2462. 返回一个 ‘(stdout_data, stderr_data)’ 元
     组。如果文件以文本模式打开则为字符串；否则字节。

     注意如果你想要向进程的 stdin 传输数据，你需要通过 ‘stdin=PIPE’ 创建
     此 Popen 对象。类似的，要从结果元组获取任何非 ‘None’ 值，你同样需要
     设置 ‘stdout=PIPE’ 或者 ‘stderr=PIPE’。

     如果进程在 `timeout' 秒后未终止，一个 *note TimeoutExpired: 2463. 异
     常将被抛出。捕获此异常并重新等待将不会丢失任何输出。

     如果超时到期，子进程不会被杀死，所以为了正确清理一个行为良好的应用
     程序应该杀死子进程并完成通讯。

          proc = subprocess.Popen(...)
          try:
              outs, errs = proc.communicate(timeout=15)
          except TimeoutExpired:
              proc.kill()
              outs, errs = proc.communicate()

          注解: 内存里数据读取是缓冲的，所以如果数据尺寸过大或无限，不要
          使用此方法。

     在 3.3 版更改: `timeout' 被添加

 -- 方法: Popen.send_signal (signal)

     将信号 `signal' 发送给子进程。

          注解: 在 Windows， SIGTERM 是一个 *note terminate(): 248f. 的
          别名。 CTRL_C_EVENT 和 CTRL_BREAK_EVENT 可以被发送给以包含
          ‘CREATE_NEW_PROCESS’ 的 `creationflags' 形参启动的进程。

 -- 方法: Popen.terminate ()

     停止下级进程。 在 POSIX 操作系统上，此方法会发送 SIGTERM 给下级进程
     。 在 Windows 上则会调用 Win32 API 函数 ‘TerminateProcess()’ 来停止
     下级进程。

 -- 方法: Popen.kill ()

     杀死子进程。 在 POSIX 操作系统上，此函数会发送 SIGKILL 给子进程。 在
     Windows 上 *note kill(): 2490. 则是 *note terminate(): 248f. 的别名
     。

以下属性也是可用的：

 -- 属性: Popen.args

     `args' 参数传递给 *note Popen: 2ba. – 一个程序参数的序列或者一个简
     单字符串。

     3.3 新版功能.

 -- 属性: Popen.stdin

     如果 `stdin' 参数为 *note PIPE: 3f6.，此属性是一个类似 *note
     open(): 4f8. 返回的可写的流对象。如果 `encoding' 或 `errors' 参数被
     指定或者 `universal_newlines' 参数为 ‘True’，则此流是一个文本流，否
     则是字节流。如果 `stdin' 参数非 *note PIPE: 3f6.， 此属性为 ‘None’。

 -- 属性: Popen.stdout

     如果 `stdout' 参数是 *note PIPE: 3f6.，此属性是一个类似 *note
     open(): 4f8. 返回的可读流。从流中读取子进程提供的输出。如果
     `encoding' 或 `errors' 参数被指定或者 `universal_newlines' 参数为
     ‘True’，此流为文本流，否则为字节流。如果 `stdout' 参数非 *note
     PIPE: 3f6.，此属性为 ‘None’。

 -- 属性: Popen.stderr

     如果 `stderr' 参数是 *note PIPE: 3f6.，此属性是一个类似 *note
     open(): 4f8. 返回的可读流。从流中读取子进程提供的输出。如果
     `encoding' 或 `errors' 参数被指定或者 `universal_newlines' 参数为
     ‘True’，此流为文本流，否则为字节流。如果 `stderr' 参数非 *note
     PIPE: 3f6.，此属性为 ‘None’。

     警告: 使用 *note communicate(): 2462. 而非 *note .stdin.write:
     2477.， *note .stdout.read: 2478. 或者 *note .stderr.read: 2479. 来
     避免由于任意其他 OS 管道缓冲区被子进程填满阻塞而导致的死锁。

 -- 属性: Popen.pid

     子进程的进程号。

     注意如果你设置了 `shell' 参数为 ‘True’，则这是生成的子 shell 的进程
     号。

 -- 属性: Popen.returncode

     此进程的退出码，由 *note poll(): 248d. 和 *note wait(): 59b. 设置（
     以及直接由 *note communicate(): 2462. 设置）。一个 ‘None’ 值 表示此
     进程仍未结束。

     一个负值 ‘-N’ 表示子进程被信号 ‘N’ 中断 (仅 POSIX).


File: python.info,  Node: Windows Popen 助手,  Next: 较旧的高阶 API,  Prev: Popen 对象,  Up: subprocess --- 子进程管理

5.17.6.7 Windows Popen 助手
...........................

*note STARTUPINFO: 247d. 类和以下常数仅在 Windows 有效。

 -- 类: subprocess.STARTUPINFO (*, dwFlags=0, hStdInput=None,
          hStdOutput=None, hStdError=None, wShowWindow=0,
          lpAttributeList=None)

     在 *note Popen: 2ba. 创建时部分支持 Windows 的 STARTUPINFO(1) 结构
     。接下来的属性仅能通过关键词参数设置。

     在 3.7 版更改: 仅关键词参数支持被加入。

      -- 属性: dwFlags

          一个位字段，用于确定进程在创建窗口时是否使用某些 *note
          STARTUPINFO: 247d. 属性。

               si = subprocess.STARTUPINFO()
               si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW

      -- 属性: hStdInput

          如果 *note dwFlags: 2494. 被指定为 *note STARTF_USESTDHANDLES:
          2496.，则此属性是进程的标准输入句柄，如果 *note
          STARTF_USESTDHANDLES: 2496. 未指定，则默认的标准输入是键盘缓冲
          区。

      -- 属性: hStdOutput

          如果 *note dwFlags: 2494. 被指定为 *note STARTF_USESTDHANDLES:
          2496.，则此属性是进程的标准输出句柄。除此之外，此此属性将被忽
          略并且默认标准输出是控制台窗口缓冲区。

      -- 属性: hStdError

          如果 *note dwFlags: 2494. 被指定为 *note STARTF_USESTDHANDLES:
          2496.，则此属性是进程的标准错误句柄。除此之外，此属性将被忽略
          并且默认标准错误为控制台窗口的缓冲区。

      -- 属性: wShowWindow

          如果 *note dwFlags: 2494. 指定了 *note STARTF_USESHOWWINDOW:
          249a.，此属性可为能被指定为 函数 ShowWindow(2) 的nCmdShow 的形
          参的任意值，除了 ‘SW_SHOWDEFAULT’。如此之外，此属性被忽略。

          *note SW_HIDE: 249b. 被提供给此属性。它在 *note Popen: 2ba. 由
          ‘shell=True’ 调用时使用。

      -- 属性: lpAttributeList

          ‘STARTUPINFOEX’ 给出的用于进程创建的额外属性字典，参阅
          UpdateProcThreadAttribute(3)。

          支持的属性：

          `handle_list'

               将被继承的句柄的序列。如果非空， `close_fds' 必须为 true。

               当传递给 *note Popen: 2ba. 构造函数时，这些句柄必须暂时地
               能被 *note os.set_handle_inheritable(): 807. 继承，否则
               *note OSError: 1d4. 将以 Windows error
               ‘ERROR_INVALID_PARAMETER’ (87) 抛出。

                    警告: 在多线程进程中，请谨慎使用，以便在将此功能与对
                    继承所有句柄的其他进程创建函数——例如 *note
                    os.system(): dc9. 的并发调用——相结合时，避免泄漏标记
                    为可继承的句柄。这也应用于临时性创建可继承句柄的标准
                    句柄重定向。

          3.7 新版功能.

* Menu:

* Windows 常数::

   ---------- Footnotes ----------

   (1) https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx

   (2) https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/ms686880(v=vs.85).aspx


File: python.info,  Node: Windows 常数,  Up: Windows Popen 助手

5.17.6.8 Windows 常数
.....................

*note subprocess: fa. 模块曝出以下常数。

 -- 数据: subprocess.STD_INPUT_HANDLE

     标准输入设备，这是控制台输入缓冲区 ‘CONIN$’。

 -- 数据: subprocess.STD_OUTPUT_HANDLE

     标准输出设备。最初，这是活动控制台屏幕缓冲区 ‘CONOUT$’。

 -- 数据: subprocess.STD_ERROR_HANDLE

     标准错误设备。最初，这是活动控制台屏幕缓冲区 ‘CONOUT$’。

 -- 数据: subprocess.SW_HIDE

     隐藏窗口。另一个窗口将被激活。

 -- 数据: subprocess.STARTF_USESTDHANDLES

     指明 *note STARTUPINFO.hStdInput: 2495, *note
     STARTUPINFO.hStdOutput: 2497. 和 *note STARTUPINFO.hStdError: 2498.
     属性包含额外的信息。

 -- 数据: subprocess.STARTF_USESHOWWINDOW

     指明 *note STARTUPINFO.wShowWindow: 2499. 属性包含额外的信息。

 -- 数据: subprocess.CREATE_NEW_CONSOLE

     新的进程将有新的控制台，而不是继承父进程的（默认）控制台。

 -- 数据: subprocess.CREATE_NEW_PROCESS_GROUP

     *note Popen: 2ba. ‘creationflags’ 形参用于指明将创建一个新的进程组
     。 这个旗标对于在子进程上使用 *note os.kill(): cfb. 来说是必须的。

     如果指定了 *note CREATE_NEW_CONSOLE: 247e. 则这个旗标会被忽略。

 -- 数据: subprocess.ABOVE_NORMAL_PRIORITY_CLASS

     *note Popen: 2ba. ‘creationflags’ 形参用于指明一个新进程将具有上述
     的平均优先级。

     3.7 新版功能.

 -- 数据: subprocess.BELOW_NORMAL_PRIORITY_CLASS

     *note Popen: 2ba. ‘creationflags’ 形参用于指明一个新进程将具有低于
     平均的优先级。

     3.7 新版功能.

 -- 数据: subprocess.HIGH_PRIORITY_CLASS

     用于指明一个新进程将具有高优先级的 *note Popen: 2ba.
     ‘creationflags’ 形参。

     3.7 新版功能.

 -- 数据: subprocess.IDLE_PRIORITY_CLASS

     用于指明一个新进程将具有空闲（最低）优先级的 *note Popen: 2ba.
     ‘creationflags’ 形参。

     3.7 新版功能.

 -- 数据: subprocess.NORMAL_PRIORITY_CLASS

     用于指明一个新进程将具有正常（默认）优先级的 *note Popen: 2ba.
     ‘creationflags’ 形参。

     3.7 新版功能.

 -- 数据: subprocess.REALTIME_PRIORITY_CLASS

     用于指明一个新进程将具有实时优先级的 *note Popen: 2ba.
     ‘creationflags’ 形参。 你应当几乎永远不使用
     REALTIME_PRIORITY_CLASS，因为这会中断管理鼠标输入、键盘输入以及后台
     磁盘刷新的系统线程。 这个类只适用于直接与硬件“对话”，或者执行短暂任
     务具有受限中断的应用。

     3.7 新版功能.

 -- 数据: subprocess.CREATE_NO_WINDOW

     指明一个新进程将不会创建窗口的 *note Popen: 2ba. ‘creationflags’ 形
     参。

     3.7 新版功能.

 -- 数据: subprocess.DETACHED_PROCESS

     指明一个新进程将不会继承其父控制台的 *note Popen: 2ba.
     ‘creationflags’ 形参。 这个值不能与 CREATE_NEW_CONSOLE 一同使用。

     3.7 新版功能.

 -- 数据: subprocess.CREATE_DEFAULT_ERROR_MODE

     指明一个新进程不会继承调用方进程的错误模式的 *note Popen: 2ba.
     ‘creationflags’ 形参。 新进程会转为采用默认的错误模式。 这个特性特
     别适用于运行时禁用硬错误的多线程 shell 应用。

     3.7 新版功能.

 -- 数据: subprocess.CREATE_BREAKAWAY_FROM_JOB

     指明一个新进程不会关联到任务的 *note Popen: 2ba. ‘creationflags’ 形
     参。

     3.7 新版功能.


File: python.info,  Node: 较旧的高阶 API,  Next: 使用 subprocess 模块替换旧函数,  Prev: Windows Popen 助手,  Up: subprocess --- 子进程管理

5.17.6.9 较旧的高阶 API
.......................

在 Python 3.5 之前，这三个函数组成了 subprocess 的高阶 API。 现在你可以
在许多情况下使用 *note run(): 3f5.，但有大量现在代码仍会调用这些函数。

 -- 函数: subprocess.call (args, *, stdin=None, stdout=None,
          stderr=None, shell=False, cwd=None, timeout=None,
          **other_popen_kwargs)

     运行由 `args' 所描述的命令。 等待命令完成，然后返回 *note
     returncode: 248a. 属性。

     需要捕获 stdout 或 stderr 的代码应当改用 *note run(): 3f5.:

          run(...).returncode

     要屏蔽 stdout 或 stderr，可提供 *note DEVNULL: aa8. 这个值。

     上面显示的参数只是常见的一些。 完整的函数签名与 *note Popen: 2ba. 构
     造器的相同 —— 此函数会将所提供的 `timeout' 之外的全部参数直接传递给
     目标接口。

          注解: 请不要在此函数中使用 ‘stdout=PIPE’ 或 ‘stderr=PIPE’。 如
          果子进程向管道生成了足以填满 OS 管理缓冲区的输出而管道还未被读
          取时它将会阻塞。

     在 3.3 版更改: `timeout' 被添加

 -- 函数: subprocess.check_call (args, *, stdin=None, stdout=None,
          stderr=None, shell=False, cwd=None, timeout=None,
          **other_popen_kwargs)

     附带参数运行命令。 等待命令完成。 如果返回码为零则正常返回，否则引
     发 *note CalledProcessError: cbd.。 *note CalledProcessError: cbd.
     对象将在 *note returncode: 2471. 属性中保存返回码。

     需要捕获 stdout 或 stderr 的代码应当改用 *note run(): 3f5.:

          run(..., check=True)

     要屏蔽 stdout 或 stderr，可提供 *note DEVNULL: aa8. 这个值。

     上面显示的参数只是常见的一些。 完整的函数签名与 *note Popen: 2ba. 构
     造器的相同 —— 此函数会将所提供的 `timeout' 之外的全部参数直接传递给
     目标接口。

          注解: 请不要在此函数中使用 ‘stdout=PIPE’ 或 ‘stderr=PIPE’。 如
          果子进程向管道生成了足以填满 OS 管理缓冲区的输出而管道还未被读
          取时它将会阻塞。

     在 3.3 版更改: `timeout' 被添加

 -- 函数: subprocess.check_output (args, *, stdin=None, stderr=None,
          shell=False, cwd=None, encoding=None, errors=None,
          universal_newlines=None, timeout=None, text=None,
          **other_popen_kwargs)

     附带参数运行命令并返回其输出。

     如果返回码非零则会引发 *note CalledProcessError: cbd.。 *note
     CalledProcessError: cbd. 对象将在 *note returncode: 2471. 属性中保
     存返回码并在 *note output: 2473. 属性中保存所有输出。

     这相当于:

          run(..., check=True, stdout=PIPE).stdout

     上面显示的参数只是常见的一些。 完整的函数签名与 *note run(): 3f5. 的
     大致相同 —— 大部分参数会通过该接口直接传递。 存在一个与 *note
     run(): 3f5. 行为不同的 API 差异：传递 ‘input=None’ 的行为将与
     ‘input=b''’ (或 ‘input=''’，具体取决于其他参数) 一样而不是使用父对
     象的标准输入文件处理。

     默认情况下，此函数将把数据返回为已编码的字节串。 输出数据的实际编码
     格式将取决于发起调用的命令，因此解码为文本的操作往往需要在应用程序
     层级上进行处理。

     此行为可以通过设置 `text', `encoding', `errors' 或将
     `universal_newlines' 设为 ‘True’ 来重载，具体描述见 *note 常用参数:
     2461. 和 *note run(): 3f5.。

     要在结果中同时捕获标准错误，请使用 ‘stderr=subprocess.STDOUT’:

          >>> subprocess.check_output(
          ...     "ls non_existent_file; exit 0",
          ...     stderr=subprocess.STDOUT,
          ...     shell=True)
          'ls: non_existent_file: No such file or directory\n'

     3.1 新版功能.

     在 3.3 版更改: `timeout' 被添加

     在 3.4 版更改: 增加了对 `input' 关键字参数的支持。

     在 3.6 版更改: 增加了 `encoding' 和 `errors'。 详情参见 *note
     run(): 3f5.。

     3.7 新版功能: `text' 作为 `universal_newlines' 的一个更具可读性的别
     名被添加。


File: python.info,  Node: 使用 subprocess 模块替换旧函数,  Next: 旧式的 Shell 发起函数,  Prev: 较旧的高阶 API,  Up: subprocess --- 子进程管理

5.17.6.10 使用 ‘subprocess’ 模块替换旧函数
..........................................

在这一节中，"a 改为 b" 意味着 b 可以被用作 a 的替代。

     注解: 在这一节中的所有 "a" 函数会在找不到被执行的程序时（差不多）静
     默地失败；"b" 替代则会改为引发 *note OSError: 1d4.。

     此外，在使用 *note check_output(): 8e3. 时如果替代函数所请求的操作
     产生了非零返回值则将失败并引发 *note CalledProcessError: cbd.。 操
     作的输出仍能以所引发异常的 *note output: 2473. 属性的方式被访问。

在下列例子中，我们假定相关的函数都已从 *note subprocess: fa. 模块中导入
了。

* Menu:

* 替代 /bin/sh shell 命令替换::
* 替代 shell 管道::
* 替代 os.system(): 替代 os system.
* 替代 os.spawn 函数族: 替代 os spawn 函数族.
* 替代 os.popen(), os.popen2(), os.popen3(): 替代 os popen os popen2 os popen3.
* 来自 popen2 模块的替代函数::


File: python.info,  Node: 替代 /bin/sh shell 命令替换,  Next: 替代 shell 管道,  Up: 使用 subprocess 模块替换旧函数

5.17.6.11 替代 ‘/bin/sh’ shell 命令替换
.......................................

     output=$(mycmd myarg)

改为:

     output = check_output(["mycmd", "myarg"])


File: python.info,  Node: 替代 shell 管道,  Next: 替代 os system,  Prev: 替代 /bin/sh shell 命令替换,  Up: 使用 subprocess 模块替换旧函数

5.17.6.12 替代 shell 管道
.........................

     output=$(dmesg | grep hda)

改为:

     p1 = Popen(["dmesg"], stdout=PIPE)
     p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
     p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
     output = p2.communicate()[0]

启动 p2 之后再执行 ‘p1.stdout.close()’ 调用很重要，这是为了让 p1 能在 p2
先于 p1 退出时接收到 SIGPIPE。

另外，对于受信任的输入，shell 本身的管道支持仍然可被直接使用:

     output=$(dmesg | grep hda)

改为:

     output=check_output("dmesg | grep hda", shell=True)


File: python.info,  Node: 替代 os system,  Next: 替代 os spawn 函数族,  Prev: 替代 shell 管道,  Up: 使用 subprocess 模块替换旧函数

5.17.6.13 替代 ‘os.system()’
............................

     sts = os.system("mycmd" + " myarg")
     # becomes
     sts = call("mycmd" + " myarg", shell=True)

注释:

   * 通过 shell 来调用程序通常是不必要的。

一个更现实的例子如下所示:

     try:
         retcode = call("mycmd" + " myarg", shell=True)
         if retcode < 0:
             print("Child was terminated by signal", -retcode, file=sys.stderr)
         else:
             print("Child returned", retcode, file=sys.stderr)
     except OSError as e:
         print("Execution failed:", e, file=sys.stderr)


File: python.info,  Node: 替代 os spawn 函数族,  Next: 替代 os popen os popen2 os popen3,  Prev: 替代 os system,  Up: 使用 subprocess 模块替换旧函数

5.17.6.14 替代 ‘os.spawn’ 函数族
................................

P_NOWAIT 示例:

     pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
     ==>
     pid = Popen(["/bin/mycmd", "myarg"]).pid

P_WAIT 示例:

     retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
     ==>
     retcode = call(["/bin/mycmd", "myarg"])

Vector 示例:

     os.spawnvp(os.P_NOWAIT, path, args)
     ==>
     Popen([path] + args[1:])

Environment 示例:

     os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
     ==>
     Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})


File: python.info,  Node: 替代 os popen os popen2 os popen3,  Next: 来自 popen2 模块的替代函数,  Prev: 替代 os spawn 函数族,  Up: 使用 subprocess 模块替换旧函数

5.17.6.15 替代 ‘os.popen()’, ‘os.popen2()’, ‘os.popen3()’
.........................................................

     (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
     ==>
     p = Popen(cmd, shell=True, bufsize=bufsize,
               stdin=PIPE, stdout=PIPE, close_fds=True)
     (child_stdin, child_stdout) = (p.stdin, p.stdout)

     (child_stdin,
      child_stdout,
      child_stderr) = os.popen3(cmd, mode, bufsize)
     ==>
     p = Popen(cmd, shell=True, bufsize=bufsize,
               stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
     (child_stdin,
      child_stdout,
      child_stderr) = (p.stdin, p.stdout, p.stderr)

     (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
     ==>
     p = Popen(cmd, shell=True, bufsize=bufsize,
               stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
     (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)

返回码以如下方式处理转写:

     pipe = os.popen(cmd, 'w')
     ...
     rc = pipe.close()
     if rc is not None and rc >> 8:
         print("There were some errors")
     ==>
     process = Popen(cmd, stdin=PIPE)
     ...
     process.stdin.close()
     if process.wait() != 0:
         print("There were some errors")


File: python.info,  Node: 来自 popen2 模块的替代函数,  Prev: 替代 os popen os popen2 os popen3,  Up: 使用 subprocess 模块替换旧函数

5.17.6.16 来自 ‘popen2’ 模块的替代函数
......................................

     注解: 如果 popen2 函数的 cmd 参数是一个字符串，命令会通过 /bin/sh 来
     执行。 如果是一个列表，命令会被直接执行。

     (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
     ==>
     p = Popen("somestring", shell=True, bufsize=bufsize,
               stdin=PIPE, stdout=PIPE, close_fds=True)
     (child_stdout, child_stdin) = (p.stdout, p.stdin)

     (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
     ==>
     p = Popen(["mycmd", "myarg"], bufsize=bufsize,
               stdin=PIPE, stdout=PIPE, close_fds=True)
     (child_stdout, child_stdin) = (p.stdout, p.stdin)

‘popen2.Popen3’ 和 ‘popen2.Popen4’ 基本上类似于 *note subprocess.Popen:
2ba.，不同之处在于:

   * *note Popen: 2ba. 如果执行失败会引发一个异常。

   * `capturestderr' 参数被替换为 `stderr' 参数。

   * 必须指定 ‘stdin=PIPE’ 和 ‘stdout=PIPE’。

   * popen2 默认会关闭所有文件描述符，但对于 *note Popen: 2ba. 你必须指
     明 ‘close_fds=True’ 以才能在所有平台或较旧的 Python 版本中确保此行
     为。


File: python.info,  Node: 旧式的 Shell 发起函数,  Next: 注释<2>,  Prev: 使用 subprocess 模块替换旧函数,  Up: subprocess --- 子进程管理

5.17.6.17 旧式的 Shell 发起函数
...............................

此模块还提供了以下来自 2.x ‘commands’ 模块的旧版函数。 这些操作会隐式地
发起调用系统 shell 并且上文所描述的有关安全与异常处理一致性保证都不适用
于这些函数。

 -- 函数: subprocess.getstatusoutput (cmd)

     返回在 shell 中执行 `cmd' 产生的 ‘(exitcode, output)’。

     在 shell 中以 ‘Popen.check_output()’ 执行字符串 `cmd' 并返回一个 2
     元组 ‘(exitcode, output)’。 会使用当前区域设置的编码格式；请参阅
     *note 常用参数: 2461. 中的说明来了解详情。

     末尾的一个换行符会从输出中被去除。 命令的退出码可被解读为子进程的返
     回码。 例如:

          >>> subprocess.getstatusoutput('ls /bin/ls')
          (0, '/bin/ls')
          >>> subprocess.getstatusoutput('cat /bin/junk')
          (1, 'cat: /bin/junk: No such file or directory')
          >>> subprocess.getstatusoutput('/bin/junk')
          (127, 'sh: /bin/junk: not found')
          >>> subprocess.getstatusoutput('/bin/kill $$')
          (-15, '')

     *note 可用性: 136f.: POSIX 和 Windows。

     在 3.3.4 版更改: 添加了 Windows 支持。

     此函数现在返回 (exitcode, output) 而不是像 Python 3.3.3 及更早的版
     本那样返回 (status, output)。 exitcode 的值与 *note returncode:
     248a. 相同。

 -- 函数: subprocess.getoutput (cmd)

     返回在 shell 中执行 `cmd' 产生的输出（stdout 和 stderr）。

     类似于 *note getstatusoutput(): 8e4.，但退出码会被忽略并且返回值为
     包含命令输出的字符串。 例如:

          >>> subprocess.getoutput('ls /bin/ls')
          '/bin/ls'

     *note 可用性: 136f.: POSIX 和 Windows。

     在 3.3.4 版更改: 添加了 Windows 支持


File: python.info,  Node: 注释<2>,  Prev: 旧式的 Shell 发起函数,  Up: subprocess --- 子进程管理

5.17.6.18 注释
..............

* Menu:

* 在 Windows 上将参数列表转换为一个字符串::


File: python.info,  Node: 在 Windows 上将参数列表转换为一个字符串,  Up: 注释<2>

5.17.6.19 在 Windows 上将参数列表转换为一个字符串
.................................................

在 Windows 上，`args' 序列会被转换为可使用以下规则来解析的字符串（对应于
MS C 运行时所使用的规则）:

  1. 参数以空白符分隔，即空格符或制表符。

  2. 用双引号标示的字符串会被解读为单个参数，而不再考虑其中的空白符。 一
     个参数可以嵌套用引号标示的字符串。

  3. 带有一个反斜杠前缀的双引号会被解读为双引号字面值。

  4. 反斜杠会按字面值解读，除非它是作为双引号的前缀。

  5. 如果反斜杠被作为双引号的前缀，则每个反斜杠对会被解读为一个反斜杠字
     面值。 如果反斜杠数量为奇数，则最后一个反斜杠会如规则 3 所描述的那
     样转义下一个双引号。

参见
....

*note shlex: e9.

     此模块提供了用于解析和转义命令行的函数。


File: python.info,  Node: sched --- 事件调度器,  Next: queue --- 一个同步的队列类,  Prev: subprocess --- 子进程管理,  Up: 并发执行

5.17.7 ‘sched’ — 事件调度器
---------------------------

`源码：' Lib/sched.py(1)

__________________________________________________________________

*note sched: e4. 模块定义了一个实现通用事件调度程序的类：

 -- 类: sched.scheduler (timefunc=time.monotonic, delayfunc=time.sleep)

     *note scheduler: a76. 类定义了一个调度事件的通用接口。 它需要两个函
     数来实际处理“外部世界” —— `timefunc' 应当不带参数地调用，并返回一个
     数字（“时间”，可以为任意单位）。 `delayfunc' 函数应当带一个参数调用
     ，与 `timefunc' 的输出相兼容，并且应当延迟其所指定的时间单位。 每个
     事件运行后还将调用 `delayfunc' 并传入参数 ‘0’ 以允许其他线程有机会
     在多线程应用中运行。

     在 3.3 版更改: `timefunc' 和 `delayfunc' 参数是可选的。

     在 3.3 版更改: *note scheduler: a76. 类可以安全的在多线程环境中使用
     。

示例:

     >>> import sched, time
     >>> s = sched.scheduler(time.time, time.sleep)
     >>> def print_time(a='default'):
     ...     print("From print_time", time.time(), a)
     ...
     >>> def print_some_times():
     ...     print(time.time())
     ...     s.enter(10, 1, print_time)
     ...     s.enter(5, 2, print_time, argument=('positional',))
     ...     s.enter(5, 1, print_time, kwargs={'a': 'keyword'})
     ...     s.run()
     ...     print(time.time())
     ...
     >>> print_some_times()
     930343690.257
     From print_time 930343695.274 positional
     From print_time 930343695.275 keyword
     From print_time 930343700.273 default
     930343700.276

* Menu:

* 调度器对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/sched.py


File: python.info,  Node: 调度器对象,  Up: sched --- 事件调度器

5.17.7.1 调度器对象
...................

*note scheduler: a76. 实例拥有以下方法和属性：

 -- 方法: scheduler.enterabs (time, priority, action, argument=(),
          kwargs={})

     安排一个新事件。 `time' 参数应该有一个数字类型兼容的返回值，与传递
     给构造函数的 `timefunc' 函数的返回值兼容。 计划在相同 `time' 的事件
     将按其 `priority' 的顺序执行。 数字越小表示优先级越高。

     执行事件意为执行 ‘action(*argument, **kwargs)’。 `argument' 是包含
     有 `action' 的位置参数的序列。 `kwargs' 是包含 `action' 的关键字参
     数的字典。

     返回值是一个事件，可用于以后取消事件（ 参见 *note cancel(): 24b0. ）
     。

     在 3.3 版更改: `argument' 参数是可选的。

     在 3.3 版更改: 添加了 `kwargs' 形参。

 -- 方法: scheduler.enter (delay, priority, action, argument=(),
          kwargs={})

     安排延后 `delay' 时间单位的事件。 除了相对时间，其他参数、效果和返
     回值与 *note enterabs(): a78. 的相同。

     在 3.3 版更改: `argument' 参数是可选的。

     在 3.3 版更改: 添加了 `kwargs' 形参。

 -- 方法: scheduler.cancel (event)

     从队列中删除事件。 如果 `event' 不是当前队列中的事件，则此方法将引
     发 *note ValueError: 1fc.。

 -- 方法: scheduler.empty ()

     如果事件队列为空则返回 ‘True’。

 -- 方法: scheduler.run (blocking=True)

     运行所有预定事件。 此方法将等待（使用传递给构造函数的 ‘delayfunc()’
     函数）进行下一个事件，然后执行它，依此类推，直到没有更多的计划事件
     。

     如果 `blocking' 为false，则执行由于最快到期（如果有）的预定事件，然
     后在调度程序中返回下一个预定调用的截止时间（如果有）。

     `action' 或 `delayfunc' 都可以引发异常。 在任何一种情况下，调度程序
     都将保持一致状态并传播异常。 如果 `action' 引发异常，则在将来调用
     *note run(): a75. 时不会尝试该事件。

     如果一系列事件的运行时间比下一个事件之前的可用时间长，那么调度程序
     将完全落后。 不会发生任何事件；调用代码负责取消不再相关的事件。

     在 3.3 版更改: 添加了 `blocking' 形参。

 -- 属性: scheduler.queue

     只读属性按照将要运行的顺序返回即将发生的事件列表。 每个事件都显示为
     *note named tuple: aab. ，包含以下字段：time、priority、action、
     argument、kwargs。


File: python.info,  Node: queue --- 一个同步的队列类,  Next: contextvars 上下文变量,  Prev: sched --- 事件调度器,  Up: 并发执行

5.17.8 ‘queue’ — 一个同步的队列类
---------------------------------

`源代码:' Lib/queue.py(1)

__________________________________________________________________

*note queue: db. 模块实现了多生产者、多消费者队列。这特别适用于消息必须
安全地在多线程间交换的线程编程。模块中的 *note Queue: d20. 类实现了所有
所需的锁定语义。

模块实现了三种类型的队列，它们的区别仅仅是条目取回的顺序。在 FIFO 队列中
，先添加的任务先取回。在 LIFO 队列中，最近被添加的条目先取回(操作类似一
个堆栈)。优先级队列中，条目将保持排序( 使用 *note heapq: 8e. 模块 ) 并且
最小值的条目第一个返回。

在内部，这三个类型的队列使用锁来临时阻塞竞争线程；然而，它们并未被设计用
于线程的重入性处理。

此外，模块实现了一个 "简单的" FIFO 队列类型， *note SimpleQueue: 3ce. ，
这个特殊实现为小功能在交换中提供额外的保障。

*note queue: db. 模块定义了下列类和异常：

 -- 类: queue.Queue (maxsize=0)

     Constructor for a FIFO queue.  `maxsize' is an integer that sets
     the upperbound limit on the number of items that can be placed in
     the queue.  Insertion will block once this size has been reached,
     until queue items are consumed.  If `maxsize' is less than or equal
     to zero, the queue size is infinite.

 -- 类: queue.LifoQueue (maxsize=0)

     LIFO 队列构造函数。 `maxsize' 是个整数，用于设置可以放入队列中的项
     目数的上限。当达到这个大小的时候，插入操作将阻塞至队列中的项目被消
     费掉。如果 `maxsize' 小于等于零，队列尺寸为无限大。

 -- 类: queue.PriorityQueue (maxsize=0)

     优先级队列构造函数。 `maxsize' 是个整数，用于设置可以放入队列中的项
     目数的上限。当达到这个大小的时候，插入操作将阻塞至队列中的项目被消
     费掉。如果 `maxsize' 小于等于零，队列尺寸为无限大。

     最小值先被取出( 最小值条目是由 ‘sorted(list(entries))[0]’ 返回的条
     目)。条目的典型模式是一个以下形式的元组： ‘(priority_number, data)’
     。

     如果 `data' 元素没有可比性，数据将被包装在一个类中，忽略数据值，仅
     仅比较优先级数字 ：

          from dataclasses import dataclass, field
          from typing import Any

          @dataclass(order=True)
          class PrioritizedItem:
              priority: int
              item: Any=field(compare=False)

 -- 类: queue.SimpleQueue

     无界的 FIFO 队列构造函数。简单的队列，缺少任务跟踪等高级功能。

     3.7 新版功能.

 -- 例外: queue.Empty

     对空的 *note Queue: d20. 对象，调用非阻塞的 *note get(): 24b7. (or
     *note get_nowait(): 24b8.) 时，引发的异常。

 -- 例外: queue.Full

     对满的 *note Queue: d20. 对象，调用非阻塞的 *note put(): 24b9. (or
     *note put_nowait(): 24ba.) 时，引发的异常。

* Menu:

* Queue对象::
* SimpleQueue 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/queue.py


File: python.info,  Node: Queue对象,  Next: SimpleQueue 对象,  Up: queue --- 一个同步的队列类

5.17.8.1 Queue对象
..................

队列对象 (*note Queue: d20, *note LifoQueue: 24b5, 或者 *note
PriorityQueue: 24b6.) 提供下列描述的公共方法。

 -- 方法: Queue.qsize ()

     返回队列的大致大小。注意，qsize() > 0 不保证后续的 get() 不被阻塞，
     qsize() < maxsize 也不保证 put() 不被阻塞。

 -- 方法: Queue.empty ()

     如果队列为空，返回 ‘True’ ，否则返回 ‘False’ 。如果 empty() 返回
     ‘True’ ，不保证后续调用的 put() 不被阻塞。类似的，如果 empty() 返回
     ‘False’ ，也不保证后续调用的 get() 不被阻塞。

 -- 方法: Queue.full ()

     如果队列是满的返回 ‘True’ ，否则返回 ‘False’ 。如果 full() 返回
     ‘True’ 不保证后续调用的 get() 不被阻塞。类似的，如果 full() 返回
     ‘False’ 也不保证后续调用的 put() 不被阻塞。

 -- 方法: Queue.put (item, block=True, timeout=None)

     将 `item' 放入队列。如果可选参数 `block' 是 true 并且 `timeout' 是
     ‘None’ (默认)，则在必要时阻塞至有空闲插槽可用。如果 `timeout' 是个
     正数，将最多阻塞 `timeout' 秒，如果在这段时间没有可用的空闲插槽，将
     引发 *note Full: 23c5. 异常。反之 (`block' 是 false)，如果空闲插槽
     立即可用，则把 `item' 放入队列，否则引发 *note Full: 23c5. 异常 ( 在
     这种情况下，`timeout' 将被忽略)。

 -- 方法: Queue.put_nowait (item)

     相当于 ‘put(item, False)’ 。

 -- 方法: Queue.get (block=True, timeout=None)

     从队列中移除并返回一个项目。如果可选参数 `block' 是 true 并且
     `timeout' 是 ‘None’ (默认值)，则在必要时阻塞至项目可得到。如果
     `timeout' 是个正数，将最多阻塞 `timeout' 秒，如果在这段时间内项目不
     能得到，将引发 *note Empty: 23c4. 异常。反之 (`block' 是 false) , 如
     果一个项目立即可得到，则返回一个项目，否则引发 *note Empty: 23c4. 异
     常 (这种情况下，`timeout' 将被忽略)。

     POSIX系统3.0之前，以及所有版本的Windows系统中，如果 `block' 是 true
     并且 `timeout' 是 ‘None’ ， 这个操作将进入基础锁的不间断等待。这意
     味着，没有异常能发生，尤其是 SIGINT 将不会触发 *note
     KeyboardInterrupt: 198. 异常。

 -- 方法: Queue.get_nowait ()

     相当于 ‘get(False)’ 。

提供了两个方法，用于支持跟踪 排队的任务 是否 被守护的消费者线程 完整的处
理。

 -- 方法: Queue.task_done ()

     表示前面排队的任务已经被完成。被队列的消费者线程使用。每个 *note
     get(): 24b7. 被用于获取一个任务， 后续调用 *note task_done(): 23c0.
     告诉队列，该任务的处理已经完成。

     如果 *note join(): 23c1. 当前正在阻塞，在所有条目都被处理后，将解除
     阻塞(意味着每个 *note put(): 24b9. 进队列的条目的 *note
     task_done(): 23c0. 都被收到)。

     如果被调用的次数多于放入队列中的项目数量，将引发 *note ValueError:
     1fc. 异常 。

 -- 方法: Queue.join ()

     阻塞至队列中所有的元素都被接收和处理完毕。

     当条目添加到队列的时候，未完成任务的计数就会增加。每当消费者线程调
     用 *note task_done(): 23c0. 表示这个条目已经被回收，该条目所有工作
     已经完成，未完成计数就会减少。当未完成计数降到零的时候， *note
     join(): 23c1. 阻塞被解除。

如何等待排队的任务被完成的示例：

     import threading, queue

     q = queue.Queue()

     def worker():
         while True:
             item = q.get()
             print(f'Working on {item}')
             print(f'Finished {item}')
             q.task_done()

     # turn-on the worker thread
     threading.Thread(target=worker, daemon=True).start()

     # send thirty task requests to the worker
     for item in range(30):
         q.put(item)
     print('All task requests sent\n', end='')

     # block until all tasks are done
     q.join()
     print('All work completed')


File: python.info,  Node: SimpleQueue 对象,  Prev: Queue对象,  Up: queue --- 一个同步的队列类

5.17.8.2 SimpleQueue 对象
.........................

*note SimpleQueue: 3ce. 对象提供下列描述的公共方法。

 -- 方法: SimpleQueue.qsize ()

     返回队列的大致大小。注意，qsize() > 0 不保证后续的 get() 不被阻塞。

 -- 方法: SimpleQueue.empty ()

     如果队列为空，返回 ‘True’ ，否则返回 ‘False’ 。如果 empty() 返回
     ‘False’ ，不保证后续调用的 get() 不被阻塞。

 -- 方法: SimpleQueue.put (item, block=True, timeout=None)

     将 `item' 放入队列。此方法永不阻塞，始终成功（除了潜在的低级错误，
     例如内存分配失败）。可选参数 `block' 和 `timeout' 仅仅是为了保持
     *note Queue.put(): 24b9. 的兼容性而提供，其值被忽略。

     `CPython implementation detail:' This method has a C implementation
     which is reentrant.  That is, a ‘put()’ or ‘get()’ call can be
     interrupted by another ‘put()’ call in the same thread without
     deadlocking or corrupting internal state inside the queue.  This
     makes it appropriate for use in destructors such as ‘__del__’
     methods or *note weakref: 129. callbacks.

 -- 方法: SimpleQueue.put_nowait (item)

     相当于 ‘put(item)’ ，仅为保持 *note Queue.put_nowait(): 24ba. 兼容
     性而提供。

 -- 方法: SimpleQueue.get (block=True, timeout=None)

     从队列中移除并返回一个项目。如果可选参数 `block' 是 true 并且
     `timeout' 是 ‘None’ (默认值)，则在必要时阻塞至项目可得到。如果
     `timeout' 是个正数，将最多阻塞 `timeout' 秒，如果在这段时间内项目不
     能得到，将引发 *note Empty: 23c4. 异常。反之 (`block' 是 false) , 如
     果一个项目立即可得到，则返回一个项目，否则引发 *note Empty: 23c4. 异
     常 (这种情况下，`timeout' 将被忽略)。

 -- 方法: SimpleQueue.get_nowait ()

     相当于 ‘get(False)’ 。

参见
....

类 *note multiprocessing.Queue: 239e.

     一个用于多进程上下文的队列类（而不是多线程）。

*note collections.deque: 539. 是无界队列的一个替代实现，具有快速的不需要
锁并且支持索引的原子化 *note append(): 1940. 和 *note popleft(): 1946. 操
作。


File: python.info,  Node: contextvars 上下文变量,  Next: _thread --- 底层多线程 API,  Prev: queue --- 一个同步的队列类,  Up: 并发执行

5.17.9 ‘contextvars’ 上下文变量
-------------------------------

__________________________________________________________________

本模块提供了相关API用于管理、存储和访问上下文相关的状态。 *note
ContextVar: 24c9. 类用于声明 `上下文变量' 并与其一起使用。函数 *note
copy_context(): 24ca.  和类 *note Context: 24cb. 用于管理当前上下文和异
步框架中。

在多并发环境中，有状态上下文管理器应该使用上下文变量，而不是 *note
threading.local(): 2302. 来防止他们的状态意外泄露到其他代码。

更多信息参见 PEP 567(1) 。

3.7 新版功能.

* Menu:

* 上下文变量::
* 手动上下文管理::
* asyncio 支持::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0567


File: python.info,  Node: 上下文变量,  Next: 手动上下文管理,  Up: contextvars 上下文变量

5.17.9.1 上下文变量
...................

 -- 类: contextvars.ContextVar (name[, *, default])

     此类用于声明一个新的上下文变量，如:

          var: ContextVar[int] = ContextVar('var', default=42)

     `name' 参数用于内省和调试，必需。

     调用 *note ContextVar.get(): 24cd. 时，如果上下文中没有找到此变量的
     值，则返回可选的仅命名参数 `default' 。

     `重要：' 上下文变量应该在顶级模块中创建，且永远不要在闭包中创建。
     *note Context: 24cb. 对象拥有对上下文变量的强引用，这可以让上下文变
     量被垃圾收集器正确回收。

      -- 属性: name

          上下文变量的名称，只读属性。

          3.7.1 新版功能.

      -- 方法: get ([default])

          返回当前上下文中此上下文变量的值。

          如果当前上下文中此变量没有值，则此方法会:

             * 如果提供了得 话，返回传入的 `default' 值；或者

             * 返回上下文变量本身的默认值， 如果创建此上下文变量时提供了
               默认值；或者

             * 抛出 *note LookupError: 166d. 异常。

      -- 方法: set (value)

          调用此方法设置上下文变量在当前上下文环境中的值。

          必选参数 `value' 是上下文变量的新值。

          返回一个 *note Token: 24d0.  对象，可通过 *note
          ContextVar.reset(): 24d1. 方法将上下文变量还原为之前某个状态。

      -- 方法: reset (token)

          将上下文变量重置为调用 *note ContextVar.set(): 24cf. 之前、创
          建 `token' 时候的状态。

          例如

               var = ContextVar('var')

               token = var.set('new value')
               # code that uses 'var'; var.get() returns 'new value'.
               var.reset(token)

               # After the reset call the var has no value again, so
               # var.get() would raise a LookupError.

 -- 类: contextvars.Token

     *note ContextVar.set(): 24cf. 方法返回 `Token' 对象。此对象可以传递
     给 *note ContextVar.reset(): 24d1. 方法用于将上下文变量还原为调用
     `set' 前的状态。

      -- 属性: Token.var

          只读属性。指向创建此 token 的 *note ContextVar: 24c9. 对象。

      -- 属性: Token.old_value

          一个只读属性。 会被设为在创建此令牌的 *note ContextVar.set():
          24cf. 方法调用之前该变量所具有的值。 它指向的 ‘Token.MISSING’
          是在调用之前未设置的变量。

      -- 属性: Token.MISSING

          ‘Token.old_value’ 会用到的一个标记对象。


File: python.info,  Node: 手动上下文管理,  Next: asyncio 支持,  Prev: 上下文变量,  Up: contextvars 上下文变量

5.17.9.2 手动上下文管理
.......................

 -- 函数: contextvars.copy_context ()

     返回当前上下文中 *note Context: 24cb. 对象的拷贝。

     以下代码片段会获取当前上下文的拷贝并打印设置到其中的所有变量及其值:

          ctx: Context = copy_context()
          print(list(ctx.items()))

     此函数复杂度为 O(1) ，也就是说对于只包含几个上下文变量和很多上下文
     变量的情况，他们是一样快的。

 -- 类: contextvars.Context

     *note ContextVars: 24c9. 中所有值的映射。

     ‘Context()’ 创建一个不包含任何值的空上下文。如果要获取当前上下文的
     拷贝，使用 *note copy_context(): 24ca. 函数。

     Context 实现了 *note collections.abc.Mapping: 1954. 接口。

      -- 方法: run (callable, *args, **kwargs)

          按照 `run' 方法中的参数在上下文对象中执行 ‘callable(*args,
          **kwargs)’ 代码。返回执行结果，如果发生异常，则将异常透传出来
          。

          `callable' 中队上下文变量做出的任何修改会保留在上下文对象中:

               var = ContextVar('var')
               var.set('spam')

               def main():
                   # 'var' was set to 'spam' before
                   # calling 'copy_context()' and 'ctx.run(main)', so:
                   # var.get() == ctx[var] == 'spam'

                   var.set('ham')

                   # Now, after setting 'var' to 'ham':
                   # var.get() == ctx[var] == 'ham'

               ctx = copy_context()

               # Any changes that the 'main' function makes to 'var'
               # will be contained in 'ctx'.
               ctx.run(main)

               # The 'main()' function was run in the 'ctx' context,
               # so changes to 'var' are contained in it:
               # ctx[var] == 'ham'

               # However, outside of 'ctx', 'var' is still set to 'spam':
               # var.get() == 'spam'

          当在多个系统线程或者递归调用同一个上下文对象的此方法，抛出
          *note RuntimeError: 2bb. 异常。

      -- 方法: copy ()

          返回此上下文对象的浅拷贝。

      -- Describe: var in context

          如果 `var' 在 `context' 中，返回 ‘True’ ， 否则返回 ‘False’ 。

      -- Describe: context[var]

          返回名称为 `var' 的 *note ContextVar: 24c9. 变量。如果上下文对
          象中不包含这个变量，则抛出 *note KeyError: 2c8. 异常。

      -- 方法: get (var[, default])

          如果 `var' 在上下文对象中具有值则返回 `var' 的值。 在其他情况
          下返回 `default'。 如果未给出 `default' 则返回 ‘None’。

      -- Describe: iter(context)

          返回一个存储在上下文对象中的变量的迭代器。

      -- Describe: len(proxy)

          返回上下文对象中所设的变量的数量。

      -- 方法: keys ()

          返回上下文对象中的所有变量的列表。

      -- 方法: values ()

          返回上下文对象中所有变量值的列表。

      -- 方法: items ()

          返回包含上下文对象中所有变量及其值的 2 元组的列表。


File: python.info,  Node: asyncio 支持,  Prev: 手动上下文管理,  Up: contextvars 上下文变量

5.17.9.3 asyncio 支持
.....................

上下文变量在 *note asyncio: a. 中有原生的支持并且无需任何额外配置即可被
使用。 例如，以下是一个简单的回显服务器，它使用上下文变量来让远程客户端
的地址在处理该客户端的 Task 中可用:

     import asyncio
     import contextvars

     client_addr_var = contextvars.ContextVar('client_addr')

     def render_goodbye():
         # The address of the currently handled client can be accessed
         # without passing it explicitly to this function.

         client_addr = client_addr_var.get()
         return f'Good bye, client @ {client_addr}\n'.encode()

     async def handle_request(reader, writer):
         addr = writer.transport.get_extra_info('socket').getpeername()
         client_addr_var.set(addr)

         # In any code that we call is now possible to get
         # client's address by calling 'client_addr_var.get()'.

         while True:
             line = await reader.readline()
             print(line)
             if not line.strip():
                 break
             writer.write(line)

         writer.write(render_goodbye())
         writer.close()

     async def main():
         srv = await asyncio.start_server(
             handle_request, '127.0.0.1', 8081)

         async with srv:
             await srv.serve_forever()

     asyncio.run(main())

     # To test it you can use telnet:
     #     telnet 127.0.0.1 8081

以下是上述某些服务的支持模块：


File: python.info,  Node: _thread --- 底层多线程 API,  Next: _dummy_thread --- _thread 的替代模块,  Prev: contextvars 上下文变量,  Up: 并发执行

5.17.10 ‘_thread’ — 底层多线程 API
----------------------------------

__________________________________________________________________

该模块提供了操作多个线程（也被称为 `轻量级进程' 或 `任务'）的底层原语 ——
多个控制线程共享全局数据空间。为了处理同步问题，也提供了简单的锁机制（也
称为 `互斥锁' 或 `二进制信号'）。*note threading: 10a. 模块基于该模块提
供了更易用的高级多线程 API。

在 3.7 版更改: 这个模块曾经为可选项，但现在总是可用。

这个模块定义了以下常量和函数：

 -- 例外: _thread.error

     发生线程相关错误时抛出。

     在 3.3 版更改: 现在是内建异常 *note RuntimeError: 2bb. 的别名。

 -- 数据: _thread.LockType

     锁对象的类型。

 -- 函数: _thread.start_new_thread (function, args[, kwargs])

     开启一个新线程并返回其标识。 线程执行函数 `function' 并附带参数列表
     `args' (必须是元组)。 可选的 `kwargs' 参数指定一个关键字参数字典。

     当函数返回时，线程会静默地退出。

     当函数因某个未处理异常而终结时，*note sys.unraisablehook(): 22e. 会
     被调用以处理异常。 钩子参数的 `object' 属性为 `function'。 在默认情
     况下，会打印堆栈回溯然后该线程将退出（但其他线程会继续运行）。

     当函数引发 *note SystemExit: 605. 异常时，它会被静默地忽略。

     在 3.8 版更改: 现在会使用 *note sys.unraisablehook(): 22e. 来处理未
     处理的异常。

 -- 函数: _thread.interrupt_main ()

     模拟一个 *note signal.SIGINT: 24e2. 信号到达主线程的效果。 线程可以
     使用这个函数来中断主线程。

     如果 Python 没有处理 *note signal.SIGINT: 24e2. (将它设为 *note
     signal.SIG_DFL: 24e3. 或 *note signal.SIG_IGN: 24e4.)，此函数将不做
     任何事。

 -- 函数: _thread.exit ()

     抛出 *note SystemExit: 605. 异常。如果没有捕获的话，这个异常会使线
     程退出。

 -- 函数: _thread.allocate_lock ()

     返回一个新的锁对象。锁中的方法在后面描述。初始情况下锁处于解锁状态
     。

 -- 函数: _thread.get_ident ()

     返回当前线程的 “线程标识符”。它是一个非零的整数。它的值没有直接含义
     ，主要是用作 magic cookie，比如作为含有线程相关数据的字典的索引。线
     程标识符可能会在线程退出，新线程创建时被复用。

 -- 函数: _thread.get_native_id ()

     返回内核分配给当前线程的原生集成线程 ID。 这是一个非负整数。 它的值
     可被用来在整个系统中唯一地标识这个特定线程（直到线程终结，在那之后
     该值可能会被 OS 回收再利用）。

     *note 可用性: 136f.: Windows, FreeBSD, Linux, macOS, OpenBSD,
     NetBSD, AIX。

     3.8 新版功能.

 -- 函数: _thread.stack_size ([size])

     返回创建线程时使用的堆栈大小。可选参数 `size' 指定之后新建的线程的
     堆栈大小，而且一定要是0（根据平台或者默认配置）或者最小是
     32,768(32KiB)的一个正整数。如果 `size' 没有指定，默认是0。如果不支
     持改变线程堆栈大小，会抛出 *note RuntimeError: 2bb. 错误。如果指定
     的堆栈大小不合法，会抛出 *note ValueError: 1fc. 错误并且不会修改堆
     栈大小。32KiB是当前最小的能保证解释器有足够堆栈空间的堆栈大小。需要
     注意的是部分平台对于堆栈大小会有特定的限制，例如要求大于32KiB的堆栈
     大小或者需要根据系统内存页面的整数倍进行分配 - 应当查阅平台文档有关
     详细信息（4KiB页面比较普遍，在没有更具体信息的情况下，建议的方法是
     使用4096的倍数作为堆栈大小）。

     *note 适用于: 136f.: Windows，具有 POSIX 线程的系统。

 -- 数据: _thread.TIMEOUT_MAX

     ‘Lock.acquire()’ 方法中 `timeout' 参数允许的最大值。传入超过这个值
     的 timeout 会抛出 *note OverflowError: 968. 异常。

     3.2 新版功能.

锁对象有以下方法：

 -- 方法: lock.acquire (waitflag=1, timeout=-1)

     没有任何可选参数时，该方法无条件申请获得锁，有必要的话会等待其他线
     程释放锁（同时只有一个线程能获得锁 —— 这正是锁存在的原因）。

     如果传入了整型参数 `waitflag'，具体的行为取决于传入的值：如果是 0 的
     话，只会在能够立刻获取到锁时才获取，不会等待，如果是非零的话，会像
     之前提到的一样，无条件获取锁。

     如果传入正浮点数参数 `timeout'，相当于指定了返回之前等待得最大秒数
     。如果传入负的 `timeout'，相当于无限期等待。如果 `waitflag' 是 0 的
     话，不能指定 `timeout'。

     如果成功获取到所会返回 ‘True’，否则返回 ‘False’。

     在 3.2 版更改: 新的 `timeout' 形参。

     在 3.2 版更改: 现在获取锁的操作可以被 POSIX 信号中断。

 -- 方法: lock.release ()

     释放锁。锁必须已经被获取过，但不一定是同一个线程获取的。

 -- 方法: lock.locked ()

     返回锁的状态：如果已被某个线程获取，返回 ‘True’，否则返回 ‘False’。

除了这些方法之外，锁对象也可以通过 *note with: 6f2. 语句使用，例如：

     import _thread

     a_lock = _thread.allocate_lock()

     with a_lock:
         print("a_lock is locked while this executes")

`注意事项：'

   * 线程与中断奇怪地交互：*note KeyboardInterrupt: 198. 异常可能会被任
     意一个线程捕获。（如果 *note signal: eb. 模块可用的话，中断总是会进
     入主线程。）

   * 调用 *note sys.exit(): cea. 或是抛出 *note SystemExit: 605. 异常等
     效于调用 *note _thread.exit(): 24e5.。

   * 不可能中断锁的 ‘acquire()’ 方法 —— *note KeyboardInterrupt: 198. 一
     场会在锁获取到之后发生。

   * 当主线程退出时，由系统决定其他线程是否存活。在大多数系统中，这些线
     程会直接被杀掉，不会执行 *note try: d7a. ...  *note finally: 183. 语
     句，也不会执行对象析构函数。

   * 当主线程退出时，不会进行正常的清理工作（除非使用了 *note try: d7a.
     ...  *note finally: 183. 语句），标准 I/O 文件也不会刷新。


File: python.info,  Node: _dummy_thread --- _thread 的替代模块,  Next: dummy_threading --- 可直接替代 threading 模块。,  Prev: _thread --- 底层多线程 API,  Up: 并发执行

5.17.11 ‘_dummy_thread’ — ‘_thread’ 的替代模块
----------------------------------------------

`源代码：' Lib/_dummy_thread.py(1)

3.7 版后已移除: Python 现在总是会启用多线程。请改用 *note _thread: 3. (或
者用 *note threading: 10a. 更好)。

__________________________________________________________________

这个模块提供与 *note _thread: 3. 相同的接口。它主要用于在没有提供 *note
_thread: 3. 模块的平台上被导入。

如果线程需要阻塞等待另一个线程被创建的话，可能会造成死锁，这通常是由于阻
塞 I/O 引起的。这种场景下请不要使用这个模块。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/_dummy_thread.py


File: python.info,  Node: dummy_threading --- 可直接替代 threading 模块。,  Prev: _dummy_thread --- _thread 的替代模块,  Up: 并发执行

5.17.12 ‘dummy_threading’ — 可直接替代 ‘threading’ 模块。
---------------------------------------------------------

`源代码：' Lib/dummy_threading.py(1)

3.7 版后已移除: 现在Python总是启用多线程。请使用 *note threading: 10a. 代
替。

__________________________________________________________________

这个模块提供了一个和 *note threading: 10a. 模块重复的接口。当平台不提供
*note _thread: 3. 模块时，应导入这个模块。

如果线程需要阻塞等待另一个线程被创建的话，可能会造成死锁，这通常是由于阻
塞 I/O 引起的。这种场景下请不要使用这个模块。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/dummy_threading.py


File: python.info,  Node: 网络和进程间通信,  Next: 互联网数据处理,  Prev: 并发执行,  Up: Python 标准库

5.18 网络和进程间通信
=====================

本章介绍的模块提供了网络和进程间通信的机制。

某些模块仅适用于同一台机器上的两个进程，例如 *note signal: eb. 和 *note
mmap: b4. 。 其他模块支持两个或多个进程可用于跨机器通信的网络协议。

本章中描述的模块列表是：

* Menu:

* asyncio: asyncio --- 异步 I/O. 异步 I/O
* socket: socket --- 底层网络接口. 底层网络接口
* ssl: ssl --- 套接字对象的TLS/SSL封装. 套接字对象的TLS/SSL封装
* select: select --- 等待 I/O 完成. 等待 I/O 完成
* selectors: selectors --- 高级 I/O 复用库. 高级 I/O 复用库
* asyncore: asyncore --- 异步socket处理器. 异步socket处理器
* asynchat: asynchat --- 异步 socket 指令/响应 处理器. 异步 socket 指令/响应 处理器
* signal: signal --- 设置异步事件处理程序. 设置异步事件处理程序
* mmap: mmap --- 内存映射文件支持. 内存映射文件支持


File: python.info,  Node: asyncio --- 异步 I/O,  Next: socket --- 底层网络接口,  Up: 网络和进程间通信

5.18.1 ‘asyncio’ — 异步 I/O
---------------------------

__________________________________________________________________

Hello World!
............

     import asyncio

     async def main():
         print('Hello ...')
         await asyncio.sleep(1)
         print('... World!')

     # Python 3.7+
     asyncio.run(main())

asyncio 是用来编写 `并发' 代码的库，使用 `async/await' 语法。

asyncio 被用作多个提供高性能 Python 异步框架的基础，包括网络和网站服务，
数据库连接库，分布式任务队列等等。

asyncio 往往是构建 IO 密集型和高层级 `结构化' 网络代码的最佳选择。

asyncio 提供一组 `高层级' API 用于:

   * 并发地 *note 运行 Python 协程: 24f7. 并对其执行过程实现完全控制;

   * 执行 *note 网络 IO 和 IPC: 24f8.;

   * 控制 *note 子进程: 24f9.;

   * 通过 *note 队列: 24fa. 实现分布式任务;

   * *note 同步: 24fb. 并发代码;

此外，还有一些 `低层级' API 以支持 `库和框架的开发者' 实现:

   * 创建和管理 *note 事件循环: 64d.，以提供异步 API 用于 *note 网络化:
     366, 运行 *note 子进程: 24fc.，处理 *note OS 信号: 24fd. 等等;

   * 使用 *note transports: 24fe. 实现高效率协议;

   * 通过 async/await 语法 *note 桥接: 24ff. 基于回调的库和代码。

参考
....

* Menu:

* 协程与任务::
* 流::
* 同步原语: 同步原语<2>.
* 子进程集::
* 队列集::
* 异常: 异常<9>.
* 事件循环::
* Futures::
* 传输和协议::
* 策略::
* 平台支持::
* 高级API索引::
* 底层API目录::
* 用 asyncio 开发::


File: python.info,  Node: 协程与任务,  Next: 流,  Up: asyncio --- 异步 I/O

5.18.1.1 协程与任务
...................

本节将简述用于协程与任务的高层级 API。

* Menu:

* 协程: 协程<3>.
* 可等待对象: 可等待对象<2>.
* 运行 asyncio 程序::
* 创建任务::
* 休眠::
* 并发运行任务::
* 屏蔽取消操作::
* 超时::
* 简单等待::
* 来自其他线程的日程安排::
* 内省::
* Task 对象::
* 基于生成器的协程::


File: python.info,  Node: 协程<3>,  Next: 可等待对象<2>,  Up: 协程与任务

5.18.1.2 协程
.............

*note 协程: 1a7. 通过 async/await 语法进行声明，是编写 asyncio 应用的推
荐方式。 例如，以下代码段（需要 Python 3.7+）会打印 "hello"，等待 1 秒，
再打印 "world":

     >>> import asyncio

     >>> async def main():
     ...     print('hello')
     ...     await asyncio.sleep(1)
     ...     print('world')

     >>> asyncio.run(main())
     hello
     world

注意：简单地调用一个协程并不会将其加入执行日程:

     >>> main()
     <coroutine object main at 0x1053bb7c8>

要真正运行一个协程，asyncio 提供了三种主要机制:

   * *note asyncio.run(): 1a6. 函数用来运行最高层级的入口点 "main()" 函
     数 (参见上面的示例。)

   * 等待一个协程。以下代码段会在等待 1 秒后打印 "hello"，然后 `再次' 等
     待 2 秒后打印 "world":

          import asyncio
          import time

          async def say_after(delay, what):
              await asyncio.sleep(delay)
              print(what)

          async def main():
              print(f"started at {time.strftime('%X')}")

              await say_after(1, 'hello')
              await say_after(2, 'world')

              print(f"finished at {time.strftime('%X')}")

          asyncio.run(main())

     预期的输出:

          started at 17:13:52
          hello
          world
          finished at 17:13:55

   * *note asyncio.create_task(): 1af. 函数用来并发运行作为 asyncio
     *note 任务: 1ae. 的多个协程。

     让我们修改以上示例，`并发' 运行两个 ‘say_after’ 协程:

          async def main():
              task1 = asyncio.create_task(
                  say_after(1, 'hello'))

              task2 = asyncio.create_task(
                  say_after(2, 'world'))

              print(f"started at {time.strftime('%X')}")

              # Wait until both tasks are completed (should take
              # around 2 seconds.)
              await task1
              await task2

              print(f"finished at {time.strftime('%X')}")

     注意，预期的输出显示代码段的运行时间比之前快了 1 秒:

          started at 17:14:32
          hello
          world
          finished at 17:14:34


File: python.info,  Node: 可等待对象<2>,  Next: 运行 asyncio 程序,  Prev: 协程<3>,  Up: 协程与任务

5.18.1.3 可等待对象
...................

如果一个对象可以在 *note await: 1a4. 语句中使用，那么它就是 `可等待' 对
象。许多 asyncio API 都被设计为接受可等待对象。

`可等待' 对象有三种主要类型: `协程', `任务' 和 `Future'.

协程
....

Python 协程属于 `可等待' 对象，因此可以在其他协程中被等待:

     import asyncio

     async def nested():
         return 42

     async def main():
         # Nothing happens if we just call "nested()".
         # A coroutine object is created but not awaited,
         # so it *won't run at all*.
         nested()

         # Let's do it differently now and await it:
         print(await nested())  # will print "42".

     asyncio.run(main())

     重要: 在本文档中 "协程" 可用来表示两个紧密关联的概念:

        * `协程函数': 定义形式为 *note async def: 285. 的函数;

        * `协程对象': 调用 `协程函数' 所返回的对象。

asyncio 也支持旧式的 *note 基于生成器的: 2505. 协程。

任务
....

`任务' 被用来设置日程以便 `并发' 执行协程。

当一个协程通过 *note asyncio.create_task(): 1af. 等函数被打包为一个 `任
务'，该协程将自动排入日程准备立即运行:

     import asyncio

     async def nested():
         return 42

     async def main():
         # Schedule nested() to run soon concurrently
         # with "main()".
         task = asyncio.create_task(nested())

         # "task" can now be used to cancel "nested()", or
         # can simply be awaited to wait until it is complete:
         await task

     asyncio.run(main())

Futures
.......

*note Future: 44b. 是一种特殊的 `低层级' 可等待对象，表示一个异步操作的
`最终结果'。

当一个 Future 对象 `被等待'，这意味着协程将保持等待直到该 Future 对象在
其他地方操作完毕。

在 asyncio 中需要 Future 对象以便允许通过 async/await 使用基于回调的代码
。

通常情况下 `没有必要' 在应用层级的代码中创建 Future 对象。

Future 对象有时会由库和某些 asyncio API 暴露给用户，用作可等待对象:

     async def main():
         await function_that_returns_a_future_object()

         # this is also valid:
         await asyncio.gather(
             function_that_returns_a_future_object(),
             some_python_coroutine()
         )

一个很好的返回对象的低层级函数的示例是 *note loop.run_in_executor():
2506.。


File: python.info,  Node: 运行 asyncio 程序,  Next: 创建任务,  Prev: 可等待对象<2>,  Up: 协程与任务

5.18.1.4 运行 asyncio 程序
..........................

 -- 函数: asyncio.run (coro, *, debug=False)

     执行 *note coroutine: 1a7. `coro' 并返回结果。

     此函数运行传入的协程，负责管理 asyncio 事件循环并 `完结异步生成器
     '。

     当有其他 asyncio 事件循环在同一线程中运行时，此函数不能被调用。

     如果 `debug' 为 ‘True’，事件循环将以调试模式运行。

     此函数总是会创建一个新的事件循环并在结束时关闭之。它应当被用作
     asyncio 程序的主入口点，理想情况下应当只被调用一次。

     示例:

          async def main():
              await asyncio.sleep(1)
              print('hello')

          asyncio.run(main())

     3.7 新版功能.

          注解: ‘asyncio.run()’ 的源代码可以在 Lib/asyncio/runners.py(1)
          中找到。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/asyncio/runners.py


File: python.info,  Node: 创建任务,  Next: 休眠,  Prev: 运行 asyncio 程序,  Up: 协程与任务

5.18.1.5 创建任务
.................

 -- 函数: asyncio.create_task (coro, *, name=None)

     将 `coro' *note 协程: 24f7. 打包为一个 *note Task: 1ae. 排入日程准
     备执行。返回 Task 对象。

     `name' 不为 ‘None’，它将使用 *note Task.set_name(): 1b1. 来设为任务
     的名称。

     该任务会在 *note get_running_loop(): 35d. 返回的循环中执行，如果当
     前线程没有在运行的循环则会引发 *note RuntimeError: 2bb.。

     此函数 `在 Python 3.7 中被加入'。在 Python 3.7 之前，可以改用低层级
     的 *note asyncio.ensure_future(): 51f. 函数。

          async def coro():
              ...

          # In Python 3.7+
          task = asyncio.create_task(coro())
          ...

          # This works in all Python versions but is less readable
          task = asyncio.ensure_future(coro())
          ...

     3.7 新版功能.

     在 3.8 版更改: 添加了 ‘name’ 形参。


File: python.info,  Node: 休眠,  Next: 并发运行任务,  Prev: 创建任务,  Up: 协程与任务

5.18.1.6 休眠
.............

 -- 函数: coroutine asyncio.sleep (delay, result=None, *, loop=None)

     阻塞 `delay' 指定的秒数。

     如果指定了 `result'，则当协程完成时将其返回给调用者。

     ‘sleep()’ 总是会挂起当前任务，以允许其他任务运行。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     以下协程示例运行 5 秒，每秒显示一次当前日期:

          import asyncio
          import datetime

          async def display_date():
              loop = asyncio.get_running_loop()
              end_time = loop.time() + 5.0
              while True:
                  print(datetime.datetime.now())
                  if (loop.time() + 1.0) >= end_time:
                      break
                  await asyncio.sleep(1)

          asyncio.run(display_date())


File: python.info,  Node: 并发运行任务,  Next: 屏蔽取消操作,  Prev: 休眠,  Up: 协程与任务

5.18.1.7 并发运行任务
.....................

 -- 函数: awaitable asyncio.gather (*aws, loop=None,
          return_exceptions=False)

     `并发' 运行 `aws' 序列中的 *note 可等待对象: 2503.。

     如果 `aws' 中的某个可等待对象为协程，它将自动作为一个任务加入日程。

     如果所有可等待对象都成功完成，结果将是一个由所有返回值聚合而成的列
     表。结果值的顺序与 `aws' 中可等待对象的顺序一致。

     如果 `return_exceptions' 为 ‘False’ (默认)，所引发的首个异常会立即
     传播给等待 ‘gather()’ 的任务。`aws' 序列中的其他可等待对象 `不会被
     取消' 并将继续运行。

     如果 `return_exceptions' 为 ‘True’，异常会和成功的结果一样处理，并
     聚合至结果列表。

     如果 ‘gather()’ `被取消'，所有被提交 (尚未完成) 的可等待对象也会 `被
     取消'。

     如果 `aws' 序列中的任一 Task 或 Future 对象 `被取消'，它将被当作引
     发了 *note CancelledError: 1a8. 一样处理 – 在此情况下 ‘gather()’ 调
     用 `不会' 被取消。这是为了防止一个已提交的 Task/Future 被取消导致其
     他 Tasks/Future 也被取消。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     示例:

          import asyncio

          async def factorial(name, number):
              f = 1
              for i in range(2, number + 1):
                  print(f"Task {name}: Compute factorial({i})...")
                  await asyncio.sleep(1)
                  f *= i
              print(f"Task {name}: factorial({number}) = {f}")

          async def main():
              # Schedule three calls *concurrently*:
              await asyncio.gather(
                  factorial("A", 2),
                  factorial("B", 3),
                  factorial("C", 4),
              )

          asyncio.run(main())

          # Expected output:
          #
          #     Task A: Compute factorial(2)...
          #     Task B: Compute factorial(2)...
          #     Task C: Compute factorial(2)...
          #     Task A: factorial(2) = 2
          #     Task B: Compute factorial(3)...
          #     Task C: Compute factorial(3)...
          #     Task B: factorial(3) = 6
          #     Task C: Compute factorial(4)...
          #     Task C: factorial(4) = 24

          注解: 如果 `return_exceptions' 为 False，则在 gather() 被标记
          为已完成后取消它将不会取消任何已提交的可等待对象。 例如，在将
          一个异常传播给调用者之后，gather 可被标记为已完成，因此，在从
          gather 捕获一个（由可等待对象所引发的）异常之后调用
          ‘gather.cancel()’ 将不会取消任何其他可等待对象。

     在 3.7 版更改: 如果 `gather' 本身被取消，则无论 `return_exceptions'
     取值为何，消息都会被传播。


File: python.info,  Node: 屏蔽取消操作,  Next: 超时,  Prev: 并发运行任务,  Up: 协程与任务

5.18.1.8 屏蔽取消操作
.....................

 -- 函数: awaitable asyncio.shield (aw, *, loop=None)

     保护一个 *note 可等待对象: 2503. 防止其被 *note 取消: 250e.。

     如果 `aw' 是一个协程，它将自动作为任务加入日程。

     以下语句:

          res = await shield(something())

     相当于:

          res = await something()

     `不同之处' 在于如果包含它的协程被取消，在 ‘something()’ 中运行的任
     务不会被取消。从 ‘something()’ 的角度看来，取消操作并没有发生。然而
     其调用者已被取消，因此 "await" 表达式仍然会引发 *note
     CancelledError: 1a8.。

     如果通过其他方式取消 ‘something()’ (例如在其内部操作) 则 ‘shield()’
     也会取消。

     如果希望完全忽略取消操作 (不推荐) 则 ‘shield()’ 函数需要配合一个
     try/except 代码段，如下所示:

          try:
              res = await shield(something())
          except CancelledError:
              res = None

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。


File: python.info,  Node: 超时,  Next: 简单等待,  Prev: 屏蔽取消操作,  Up: 协程与任务

5.18.1.9 超时
.............

 -- 函数: coroutine asyncio.wait_for (aw, timeout, *, loop=None)

     等待 `aw' *note 可等待对象: 2503. 完成，指定 timeout 秒数后超时。

     如果 `aw' 是一个协程，它将自动作为任务加入日程。

     `timeout' 可以为 ‘None’，也可以为 float 或 int 型数值表示的等待秒数
     。如果 `timeout' 为 ‘None’，则等待直到完成。

     如果发生超时，任务将取消并引发 *note asyncio.TimeoutError: 2510.

     要避免任务 *note 取消: 250e.，可以加上 *note shield(): 288.。

     函数将等待直到目标对象确实被取消，所以总等待时间可能超过 `timeout'
     指定的秒数。

     如果等待被取消，则 `aw' 指定的对象也会被取消。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     示例:

          async def eternity():
              # Sleep for one hour
              await asyncio.sleep(3600)
              print('yay!')

          async def main():
              # Wait for at most 1 second
              try:
                  await asyncio.wait_for(eternity(), timeout=1.0)
              except asyncio.TimeoutError:
                  print('timeout!')

          asyncio.run(main())

          # Expected output:
          #
          #     timeout!

     在 3.7 版更改: 当 `aw' 因超时被取消，‘wait_for’ 会等待 `aw' 被取消
     。之前版本则将立即引发 *note asyncio.TimeoutError: 2510.。


File: python.info,  Node: 简单等待,  Next: 来自其他线程的日程安排,  Prev: 超时,  Up: 协程与任务

5.18.1.10 简单等待
..................

 -- 函数: coroutine asyncio.wait (aws, *, loop=None, timeout=None,
          return_when=ALL_COMPLETED)

     并发地运行 `aws' 可迭代对象中的 *note 可等待对象: 2503. 并进入阻塞
     状态直到满足 `return_when' 所指定的条件。

     返回两个 Task/Future 集合: ‘(done, pending)’。

     用法:

          done, pending = await asyncio.wait(aws)

     如指定 `timeout' (float 或 int 类型) 则它将被用于控制返回之前等待的
     最长秒数。

     请注意此函数不会引发 *note asyncio.TimeoutError: 2510.。当超时发生
     时，未完成的 Future 或 Task 将在指定秒数后被返回。

     `return_when' 指定此函数应在何时返回。它必须为以下常数之一:

     常数                              描述
                                       
     -------------------------------------------------------------------------------
                                       
     ‘FIRST_COMPLETED’                 函数将在任意可等待对象结束或取消时返回。
                                       
                                       
     ‘FIRST_EXCEPTION’                 函数将在任意可等待对象因引发异常而结束时返
                                       回。当没有引发任何异常时它就相当于
                                       ‘ALL_COMPLETED’。
                                       
                                       
     ‘ALL_COMPLETED’                   函数将在所有可等待对象结束或取消时返回。
                                       

     与 *note wait_for(): 289. 不同，‘wait()’ 在超时发生时不会取消可等待
     对象。

     3.8 版后已移除: 如果 `aws' 中的某个可等待对象为协程，它将自动作为任
     务加入日程。直接向 ‘wait()’ 传入协程对象已弃用，因为这会导致 *note
     令人迷惑的行为: 2513.。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

          注解: ‘wait()’ 会自动将协程作为任务加入日程，以后将以 ‘(done,
          pending)’ 集合形式返回显式创建的任务对象。因此以下代码并不会有
          预期的行为:

               async def foo():
                   return 42

               coro = foo()
               done, pending = await asyncio.wait({coro})

               if coro in done:
                   # This branch will never be run!

          以上代码段的修正方法如下:

               async def foo():
                   return 42

               task = asyncio.create_task(foo())
               done, pending = await asyncio.wait({task})

               if task in done:
                   # Everything will work as expected now.

     3.8 版后已移除: 直接向 ‘wait()’ 传入协程对象的方式已弃用。

 -- 函数: asyncio.as_completed (aws, *, loop=None, timeout=None)

     并发地运行 `aws' 可迭代对象中的 *note 可等待对象: 2503.。 返回一个
     协程的迭代器。 所返回的每个协程可被等待以从剩余的可等待对象的可迭代
     对象中获得最早的下一个结果。

     如果在所有 Future 对象完成前发生超时则将引发 *note
     asyncio.TimeoutError: 2510.。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     示例:

          for coro in as_completed(aws):
              earliest_result = await coro
              # ...


File: python.info,  Node: 来自其他线程的日程安排,  Next: 内省,  Prev: 简单等待,  Up: 协程与任务

5.18.1.11 来自其他线程的日程安排
................................

 -- 函数: asyncio.run_coroutine_threadsafe (coro, loop)

     向指定事件循环提交一个协程。线程安全。

     返回一个 *note concurrent.futures.Future: b35. 以等待来自其他 OS 线
     程的结果。

     此函数应该从另一个 OS 线程中调用，而非事件循环运行所在线程。示例:

          # Create a coroutine
          coro = asyncio.sleep(1, result=3)

          # Submit the coroutine to a given loop
          future = asyncio.run_coroutine_threadsafe(coro, loop)

          # Wait for the result with an optional timeout argument
          assert future.result(timeout) == 3

     如果在协程内产生了异常，将会通知返回的 Future 对象。它也可被用来取
     消事件循环中的任务:

          try:
              result = future.result(timeout)
          except asyncio.TimeoutError:
              print('The coroutine took too long, cancelling the task...')
              future.cancel()
          except Exception as exc:
              print(f'The coroutine raised an exception: {exc!r}')
          else:
              print(f'The coroutine returned: {result!r}')

     参见 *note concurrency and multithreading: 2515. 部分的文档。

     不同与其他 asyncio 函数，此函数要求显式地传入 `loop' 参数。

     3.5.1 新版功能.


File: python.info,  Node: 内省,  Next: Task 对象,  Prev: 来自其他线程的日程安排,  Up: 协程与任务

5.18.1.12 内省
..............

 -- 函数: asyncio.current_task (loop=None)

     返回当前运行的 *note Task: 1ae. 实例，如果没有正在运行的任务则返回
     ‘None’。

     如果 `loop' 为 ‘None’ 则会使用 *note get_running_loop(): 35d. 获取
     当前事件循环。

     3.7 新版功能.

 -- 函数: asyncio.all_tasks (loop=None)

     返回事件循环所运行的未完成的 *note Task: 1ae. 对象的集合。

     如果 `loop' 为 ‘None’，则会使用 *note get_running_loop(): 35d. 获取
     当前事件循环。

     3.7 新版功能.


File: python.info,  Node: Task 对象,  Next: 基于生成器的协程,  Prev: 内省,  Up: 协程与任务

5.18.1.13 Task 对象
...................

 -- 类: asyncio.Task (coro, *, loop=None, name=None)

     一个与 *note Future 类似: 44b. 的对象，可运行 Python *note 协程:
     24f7.。非线程安全。

     Task 对象被用来在事件循环中运行协程。如果一个协程在等待一个 Future
     对象，Task 对象会挂起该协程的执行并等待该 Future 对象完成。当该
     Future 对象 `完成'，被打包的协程将恢复执行。

     事件循环使用协同日程调度: 一个事件循环每次运行一个 Task 对象。而一
     个 Task 对象会等待一个 Future 对象完成，该事件循环会运行其他 Task、
     回调或执行 IO 操作。

     使用高层级的 *note asyncio.create_task(): 1af. 函数来创建 Task 对象
     ，也可用低层级的 *note loop.create_task(): 1b0. 或 *note
     ensure_future(): 51f. 函数。不建议手动实例化 Task 对象。

     要取消一个正在运行的 Task 对象可使用 *note cancel(): 250e. 方法。调
     用此方法将使该 Task 对象抛出一个 *note CancelledError: 1a8. 异常给
     打包的协程。如果取消期间一个协程正在等待一个 Future 对象，该 Future
     对象也将被取消。

     *note cancelled(): 2518. 可被用来检测 Task 对象是否被取消。如果打包
     的协程没有抑制 *note CancelledError: 1a8. 异常并且确实被取消，该方
     法将返回 ‘True’。

     *note asyncio.Task: 1ae. 从 *note Future: 44b. 继承了其除 *note
     Future.set_result(): 2519. 和 *note Future.set_exception(): 251a. 以
     外的所有 API。

     Task 对象支持 *note contextvars: 25. 模块。当一个 Task 对象被创建，
     它将复制当前上下文，然后在复制的上下文中运行其协程。

     在 3.7 版更改: 加入对 *note contextvars: 25. 模块的支持。

     在 3.8 版更改: 添加了 ‘name’ 形参。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

      -- 方法: cancel ()

          请求取消 Task 对象。

          这将安排在下一轮事件循环中抛出一个 *note CancelledError: 1a8.
          异常给被封包的协程。

          协程在之后有机会进行清理甚至使用 *note try: d7a. ...  ...
          ‘except CancelledError’ ...  *note finally: 183. 代码块抑制异
          常来拒绝请求。不同于 *note Future.cancel(): 251b.，*note
          Task.cancel(): 250e. 不保证 Task 会被取消，虽然抑制完全取消并
          不常见，也很不鼓励这样做。 以下示例演示了协程是如何侦听取消请
          求的:

               async def cancel_me():
                   print('cancel_me(): before sleep')

                   try:
                       # Wait for 1 hour
                       await asyncio.sleep(3600)
                   except asyncio.CancelledError:
                       print('cancel_me(): cancel sleep')
                       raise
                   finally:
                       print('cancel_me(): after sleep')

               async def main():
                   # Create a "cancel_me" Task
                   task = asyncio.create_task(cancel_me())

                   # Wait for 1 second
                   await asyncio.sleep(1)

                   task.cancel()
                   try:
                       await task
                   except asyncio.CancelledError:
                       print("main(): cancel_me is cancelled now")

               asyncio.run(main())

               # Expected output:
               #
               #     cancel_me(): before sleep
               #     cancel_me(): cancel sleep
               #     cancel_me(): after sleep
               #     main(): cancel_me is cancelled now

      -- 方法: cancelled ()

          如果 Task 对象 `被取消' 则返回 ‘True’。

          当使用 *note cancel(): 250e. 发出取消请求时 Task 会被 `取消'，
          其封包的协程将传播被抛入的 *note CancelledError: 1a8. 异常。

      -- 方法: done ()

          如果 Task 对象 `已完成' 则返回 ‘True’。

          当 Task 所封包的协程返回一个值、引发一个异常或 Task 本身被取消
          时，则会被认为 `已完成'。

      -- 方法: result ()

          返回 Task 的结果。

          如果 Task 对象 `已完成'，其封包的协程的结果会被返回 (或者当协
          程引发异常时，该异常会被重新引发。)

          如果 Task 对象 `被取消'，此方法会引发一个 *note
          CancelledError: 1a8. 异常。

          如果 Task 对象的结果还不可用，此方法会引发一个 *note
          InvalidStateError: 251f. 异常。

      -- 方法: exception ()

          返回 Task 对象的异常。

          如果所封包的协程引发了一个异常，该异常将被返回。如果所封包的协
          程正常返回则该方法将返回 ‘None’。

          如果 Task 对象 `被取消'，此方法会引发一个 *note
          CancelledError: 1a8. 异常。

          如果 Task 对象尚未 `完成'，此方法将引发一个 *note
          InvalidStateError: 251f. 异常。

      -- 方法: add_done_callback (callback, *, context=None)

          添加一个回调，将在 Task 对象 `完成' 时被运行。

          此方法应该仅在低层级的基于回调的代码中使用。

          要了解更多细节请查看 *note Future.add_done_callback(): 356. 的
          文档。

      -- 方法: remove_done_callback (callback)

          从回调列表中移除 `callback' 。

          此方法应该仅在低层级的基于回调的代码中使用。

          要了解更多细节请查看 *note Future.remove_done_callback():
          2523. 的文档。

      -- 方法: get_stack (*, limit=None)

          返回此 Task 对象的栈框架列表。

          如果所封包的协程未完成，这将返回其挂起所在的栈。如果协程已成功
          完成或被取消，这将返回一个空列表。如果协程被一个异常终止，这将
          返回回溯框架列表。

          框架总是从按从旧到新排序。

          每个被挂起的协程只返回一个栈框架。

          可选的 `limit' 参数指定返回框架的数量上限；默认返回所有框架。
          返回列表的顺序要看是返回一个栈还是一个回溯：栈返回最新的框架，
          回溯返回最旧的框架。(这与 traceback 模块的行为保持一致。)

      -- 方法: print_stack (*, limit=None, file=None)

          打印此 Task 对象的栈或回溯。

          此方法产生的输出类似于 traceback 模块通过 *note get_stack():
          2524. 所获取的框架。

          `limit' 参数会直接传递给 *note get_stack(): 2524.。

          `file' 参数是输出所写入的 I/O 流；默认情况下输出会写入 *note
          sys.stderr: 318.。

      -- 方法: get_coro ()

          返回由 *note Task: 1ae. 包装的协程对象。

          3.8 新版功能.

      -- 方法: get_name ()

          返回 Task 的名称。

          如果没有一个 Task 名称被显式地赋值，默认的 asyncio Task 实现会
          在实例化期间生成一个默认名称。

          3.8 新版功能.

      -- 方法: set_name (value)

          设置 Task 的名称。

          `value' 参数可以为任意对象，它随后会被转换为字符串。

          在默认的 Task 实现中，名称将在任务对象的 *note repr(): 7d5. 输
          出中可见。

          3.8 新版功能.

      -- 方法: classmethod all_tasks (loop=None)

          返回一个事件循环中所有任务的集合。

          默认情况下将返回当前事件循环中所有任务。如果 `loop' 为 ‘None’，
          则会使用 *note get_event_loop(): 35e. 函数来获取当前事件循环。

          Deprecated since version 3.7, will be removed in version 3.9:
          请不要将此方法作为任务方法来调用。 应当改用 *note
          asyncio.all_tasks(): 35a. 函数。

      -- 方法: classmethod current_task (loop=None)

          返回当前运行任务或 ‘None’。

          如果 `loop' 为 ‘None’，则会使用 *note get_event_loop(): 35e. 函
          数来获取当前事件循环。

          Deprecated since version 3.7, will be removed in version 3.9:
          请不要将此方法作为任务方法来调用。 应当改用 *note
          asyncio.current_task(): 359. 函数。


File: python.info,  Node: 基于生成器的协程,  Prev: Task 对象,  Up: 协程与任务

5.18.1.14 基于生成器的协程
..........................

     注解: 对基于生成器的协程的支持 `已弃用' 并计划在 Python 3.10 中移除
     。

基于生成器的协程是 async/await 语法的前身。它们是使用 ‘yield from’ 语句
创建的 Python 生成器，可以等待 Future 和其他协程。

基于生成器的协程应该使用 *note @asyncio.coroutine: 283. 装饰，虽然这并非
强制。

 -- 函数: @asyncio.coroutine

     用来标记基于生成器的协程的装饰器。

     此装饰器使得旧式的基于生成器的协程能与 async/await 代码相兼容:

          @asyncio.coroutine
          def old_style_coroutine():
              yield from asyncio.sleep(1)

          async def main():
              await old_style_coroutine()

     此装饰器不应该被用于 *note async def: 285. 协程。

     Deprecated since version 3.8, will be removed in version 3.10: 请改
     用 *note async def: 285.。

 -- 函数: asyncio.iscoroutine (obj)

     如果 `obj' 是一个 *note 协程对象: 24f7. 则返回 ‘True’。

     此方法不同于 *note inspect.iscoroutine(): 700. 因为它对基于生成器的
     协程返回 ‘True’。

 -- 函数: asyncio.iscoroutinefunction (func)

     如果 `func' 是一个 *note 协程函数: 24f7. 则返回 ‘True’。

     此方法不同于 *note inspect.iscoroutinefunction(): 701. 因为它对以
     *note @coroutine: 283. 装饰的基于生成器的协程函数返回 ‘True’。


File: python.info,  Node: 流,  Next: 同步原语<2>,  Prev: 协程与任务,  Up: asyncio --- 异步 I/O

5.18.1.15 流
............

`源码:' Lib/asyncio/streams.py(1)

__________________________________________________________________

流是用于处理网络连接的高级 async/await-ready 原语。流允许发送和接收数据
，而不需要使用回调或低级协议和传输。 下面是一个使用 asyncio streams 编写
的 TCP echo 客户端示例:

     import asyncio

     async def tcp_echo_client(message):
         reader, writer = await asyncio.open_connection(
             '127.0.0.1', 8888)

         print(f'Send: {message!r}')
         writer.write(message.encode())
         await writer.drain()

         data = await reader.read(100)
         print(f'Received: {data.decode()!r}')

         print('Close the connection')
         writer.close()
         await writer.wait_closed()

     asyncio.run(tcp_echo_client('Hello World!'))

参见下面的 *note Examples: 252c. 部分。

Stream 函数
...........

下面的高级 asyncio 函数可以用来创建和处理流:

 -- 函数: coroutine asyncio.open_connection (host=None, port=None, *,
          loop=None, limit=None, ssl=None, family=0, proto=0, flags=0,
          sock=None, local_addr=None, server_hostname=None,
          ssl_handshake_timeout=None)

     建立网络连接并返回一对 ‘(reader, writer)’ 对象。

     返回的 `reader' 和 `writer' 对象是 *note StreamReader: fda. 和
     *note StreamWriter: fdb. 类的实例。

     `loop' 参数是可选的，当从协程中等待该函数时，总是可以自动确定。

     `limit' 确定返回的 *note StreamReader: fda. 实例使用的缓冲区大小限
     制。默认情况下，`limit' 设置为 64 KiB 。

     其余的参数直接传递到 *note loop.create_connection(): 1b3. 。

     3.7 新版功能: `ssl_handshake_timeout' 形参。

 -- 函数: coroutine asyncio.start_server (client_connected_cb,
          host=None, port=None, *, loop=None, limit=None,
          family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None,
          backlog=100, ssl=None, reuse_address=None, reuse_port=None,
          ssl_handshake_timeout=None, start_serving=True)

     启动套接字服务。

     当一个新的客户端连接被建立时，回调函数 `client_connected_cb' 会被调
     用。该函数会接收到一对参数 ‘(reader, writer)’ ，reader是类 *note
     StreamReader: fda. 的实例，而writer是类 *note StreamWriter: fdb. 的
     实例。

     `client_connected_cb' 即可以是普通的可调用对象也可以是一个 *note
     协程函数: 24f7.; 如果它是一个协程函数，它将自动作为 *note Task:
     1ae. 被调度。

     `loop' 参数是可选的。当在一个协程中await该方法时，该参数始终可以自
     动确定。

     `limit' 确定返回的 *note StreamReader: fda. 实例使用的缓冲区大小限
     制。默认情况下，`limit' 设置为 64 KiB 。

     余下的参数将会直接传递给 *note loop.create_server(): 366.

     3.7 新版功能: The `ssl_handshake_timeout' and `start_serving'
     parameters.

Unix 套接字
...........

 -- 函数: coroutine asyncio.open_unix_connection (path=None, *,
          loop=None, limit=None, ssl=None, sock=None,
          server_hostname=None, ssl_handshake_timeout=None)

     建立一个 Unix 套接字连接并返回 ‘(reader, writer)’ 这对返回值。

     与 *note open_connection(): 36c. 相似，但是操作在 Unix 套接字上

     请看文档 *note loop.create_unix_connection(): 252e.

     *note 可用性: 136f.: Unix。

     3.7 新版功能: `ssl_handshake_timeout' 形参。

     在 3.7 版更改: `path' 现在是一个 *note path-like object: 373.

 -- 函数: coroutine asyncio.start_unix_server (client_connected_cb,
          path=None, *, loop=None, limit=None, sock=None, backlog=100,
          ssl=None, ssl_handshake_timeout=None, start_serving=True)

     启动一个Unix socket服务。

     与 *note start_server(): 36d. 相似，但是是在 Unix 套接字上的操作。

     请看文档 *note loop.create_unix_server(): 367.

     *note 可用性: 136f.: Unix。

     3.7 新版功能: The `ssl_handshake_timeout' and `start_serving'
     parameters.

     在 3.7 版更改: `path' 形参现在可以是 *note path-like object: 373. 对
     象。

* Menu:

* StreamReader::
* StreamWriter::
* 例子: 例子<11>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/asyncio/streams.py


File: python.info,  Node: StreamReader,  Next: StreamWriter,  Up: 流

5.18.1.16 StreamReader
......................

 -- 类: asyncio.StreamReader

     这个类表示一个提供api来从IO流中读取数据的读取器对象。

     不推荐直接实例化 `StreamReader' 对象，建议使用 *note
     open_connection(): 36c. 和 *note start_server(): 36d. 来获取
     `StreamReader' 实例。

      -- 方法: coroutine read (n=-1)

          读取 `n' 个byte.  如果没有设置 `n' , 则自动置为 ‘-1’ ，读至
          EOF 并返回所有读取的byte。

          如果读到EOF，且内部缓冲区为空，则返回一个空的 ‘bytes’ 对象。

      -- 方法: coroutine readline ()

          读取一行，其中“行”指的是以 ‘\n’ 结尾的字节序列。

          如果读到EOF而没有找到 ‘\n’ ，该方法返回部分读取的数据。

          如果读到EOF，且内部缓冲区为空，则返回一个空的 ‘bytes’ 对象。

      -- 方法: coroutine readexactly (n)

          精准读取 `n' 个 bytes，不能超过也不能少于。

          如果在读取完 `n' 个byte之前读取到EOF，则会抛出 *note
          IncompleteReadError: ee9. 异常。使用 *note
          IncompleteReadError.partial: 2533. 属性来获取到达流结束之前读
          取的 bytes 字符串。

      -- 方法: coroutine readuntil (separator=b'\n')

          从流中读取数据直至遇到 `分隔符'

          成功后，数据和指定的separator将从内部缓冲区中删除(或者说被消费
          掉)。返回的数据将包括在末尾的指定separator。

          如果读取的数据量超过了配置的流限制，将引发 *note
          LimitOverrunError: 2534. 异常，数据将留在内部缓冲区中并可以再
          次读取。

          如果在找到完整的separator之前到达EOF，则会引发 *note
          IncompleteReadError: ee9. 异常，并重置内部缓冲区。 *note
          IncompleteReadError.partial: 2533. 属性可能包含指定separator的
          一部分。

          3.5.2 新版功能.

      -- 方法: at_eof ()

          如果缓冲区为空并且 ‘feed_eof()’ 被调用，则返回 ‘True’ 。


File: python.info,  Node: StreamWriter,  Next: 例子<11>,  Prev: StreamReader,  Up: 流

5.18.1.17 StreamWriter
......................

 -- 类: asyncio.StreamWriter

     这个类表示一个写入器对象，该对象提供api以便于写数据至IO流中。

     不建议直接实例化 `StreamWriter'；而应改用 *note open_connection():
     36c. 和 *note start_server(): 36d.。

      -- 方法: write (data)

          此方法会尝试立即将 `data' 写入到下层的套接字。 如果写入失败，
          数据会被排入内部写缓冲队列直到可以被发送。

          此方法应当与 ‘drain()’ 方法一起使用:

               stream.write(data)
               await stream.drain()

      -- 方法: writelines (data)

          此方法会立即尝试将一个字节串列表（或任何可迭代对象）写入到下层
          的套接字。 如果写入失败，数据会被排入内部写缓冲队列直到可以被
          发送。

          此方法应当与 ‘drain()’ 方法一起使用:

               stream.writelines(lines)
               await stream.drain()

      -- 方法: close ()

          此方法会关闭流以及下层的套接字。

          此方法应与 ‘wait_closed()’ 方法一起使用:

               stream.close()
               await stream.wait_closed()

      -- 方法: can_write_eof ()

          如果下层的传输支持 *note write_eof(): 253b. 方法则返回
          ‘‘True‘‘，否则返回 ‘False’。

      -- 方法: write_eof ()

          在已缓冲的写入数据被刷新后关闭流的写入端。

      -- 属性: transport

          返回下层的 asyncio 传输。

      -- 方法: get_extra_info (name, default=None)

          访问可选的传输信息；详情参见 *note
          BaseTransport.get_extra_info(): 2c9.。

      -- 方法: coroutine drain ()

          等待直到可以适当地恢复写入到流。 示例:

               writer.write(data)
               await writer.drain()

          这是一个与下层的 IO 写缓冲区进行交互的流程控制方法。 当缓冲区
          大小达到最高水位（最大上限）时，`drain()' 会阻塞直到缓冲区大小
          减少至最低水位以便恢复写入。 当没有要等待的数据时，*note
          drain(): 253e. 会立即返回。

      -- 方法: is_closing ()

          如果流已被关闭或正在被关闭则返回 ‘True’。

          3.7 新版功能.

      -- 方法: coroutine wait_closed ()

          等待直到流被关闭。

          应当在 *note close(): 2539. 之后被调用以便等待直到下层的连接被
          关闭。

          3.7 新版功能.


File: python.info,  Node: 例子<11>,  Prev: StreamWriter,  Up: 流

5.18.1.18 例子
..............

* Menu:

* 使用流的 TCP 回显客户端::
* 使用流的 TCP 回显服务器::
* 获取 HTTP 标头::
* 注册一个打开的套接字以等待使用流的数据::


File: python.info,  Node: 使用流的 TCP 回显客户端,  Next: 使用流的 TCP 回显服务器,  Up: 例子<11>

5.18.1.19 使用流的 TCP 回显客户端
.................................

使用 *note asyncio.open_connection(): 36c. 函数的 TCP 回显客户端:

     import asyncio

     async def tcp_echo_client(message):
         reader, writer = await asyncio.open_connection(
             '127.0.0.1', 8888)

         print(f'Send: {message!r}')
         writer.write(message.encode())

         data = await reader.read(100)
         print(f'Received: {data.decode()!r}')

         print('Close the connection')
         writer.close()

     asyncio.run(tcp_echo_client('Hello World!'))

参见
....

*note TCP 回显客户端协议: 2541. 示例使用底层级的 *note
loop.create_connection(): 1b3. 方法。


File: python.info,  Node: 使用流的 TCP 回显服务器,  Next: 获取 HTTP 标头,  Prev: 使用流的 TCP 回显客户端,  Up: 例子<11>

5.18.1.20 使用流的 TCP 回显服务器
.................................

TCP 回显服务器使用 *note asyncio.start_server(): 36d. 函数:

     import asyncio

     async def handle_echo(reader, writer):
         data = await reader.read(100)
         message = data.decode()
         addr = writer.get_extra_info('peername')

         print(f"Received {message!r} from {addr!r}")

         print(f"Send: {message!r}")
         writer.write(data)
         await writer.drain()

         print("Close the connection")
         writer.close()

     async def main():
         server = await asyncio.start_server(
             handle_echo, '127.0.0.1', 8888)

         addr = server.sockets[0].getsockname()
         print(f'Serving on {addr}')

         async with server:
             await server.serve_forever()

     asyncio.run(main())

参见
....

使用 *note loop.create_server(): 366. 方法的 *note TCP 回显服务器协议:
2544. 示例。


File: python.info,  Node: 获取 HTTP 标头,  Next: 注册一个打开的套接字以等待使用流的数据,  Prev: 使用流的 TCP 回显服务器,  Up: 例子<11>

5.18.1.21 获取 HTTP 标头
........................

查询命令行传入 URL 的 HTTP 标头的简单示例:

     import asyncio
     import urllib.parse
     import sys

     async def print_http_headers(url):
         url = urllib.parse.urlsplit(url)
         if url.scheme == 'https':
             reader, writer = await asyncio.open_connection(
                 url.hostname, 443, ssl=True)
         else:
             reader, writer = await asyncio.open_connection(
                 url.hostname, 80)

         query = (
             f"HEAD {url.path or '/'} HTTP/1.0\r\n"
             f"Host: {url.hostname}\r\n"
             f"\r\n"
         )

         writer.write(query.encode('latin-1'))
         while True:
             line = await reader.readline()
             if not line:
                 break

             line = line.decode('latin1').rstrip()
             if line:
                 print(f'HTTP header> {line}')

         # Ignore the body, close the socket
         writer.close()

     url = sys.argv[1]
     asyncio.run(print_http_headers(url))

用法:

     python example.py http://example.com/path/page.html

或使用 HTTPS:

     python example.py https://example.com/path/page.html


File: python.info,  Node: 注册一个打开的套接字以等待使用流的数据,  Prev: 获取 HTTP 标头,  Up: 例子<11>

5.18.1.22 注册一个打开的套接字以等待使用流的数据
................................................

使用 *note open_connection(): 36c. 函数实现等待直到套接字接收到数据的协
程:

     import asyncio
     import socket

     async def wait_for_data():
         # Get a reference to the current event loop because
         # we want to access low-level APIs.
         loop = asyncio.get_running_loop()

         # Create a pair of connected sockets.
         rsock, wsock = socket.socketpair()

         # Register the open socket to wait for data.
         reader, writer = await asyncio.open_connection(sock=rsock)

         # Simulate the reception of data from the network
         loop.call_soon(wsock.send, 'abc'.encode())

         # Wait for data
         data = await reader.read(100)

         # Got data, we are done: close the socket
         print("Received:", data.decode())
         writer.close()

         # Close the second socket
         wsock.close()

     asyncio.run(wait_for_data())

参见
....

使用低层级协议以及 *note loop.create_connection(): 1b3. 方法的 *note
注册一个打开的套接字以等待使用协议的数据: 2548. 示例。

使用低层级的 *note loop.add_reader(): 2549. 方法来监视文件描述符的 *note
监视文件描述符以读取事件: 254a. 示例。


File: python.info,  Node: 同步原语<2>,  Next: 子进程集,  Prev: 流,  Up: asyncio --- 异步 I/O

5.18.1.23 同步原语
..................

`源代码:' Lib/asyncio/locks.py(1)

__________________________________________________________________

asyncio 同步原语被设计为与 *note threading: 10a. 模块的类似，但有两个关
键注意事项:

   * asyncio 原语不是线程安全的，因此它们不应被用于 OS 线程同步 (而应当
     使用 *note threading: 10a.)；

   * 这些同步原语的方法不接受 `timeout' 参数；请使用 *note
     asyncio.wait_for(): 289. 函数来执行带有超时的操作。

asyncio 具有下列基本同步原语:

   * *note Lock: 28c.

   * *note Event: 28d.

   * *note Condition: 28e.

   * *note Semaphore: 28f.

   * *note BoundedSemaphore: 290.

__________________________________________________________________

* Menu:

* Lock::
* Event::
* Condition::
* Semaphore::
* BoundedSemaphore::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/asyncio/locks.py


File: python.info,  Node: Lock,  Next: Event,  Up: 同步原语<2>

5.18.1.24 Lock
..............

 -- 类: asyncio.Lock (*, loop=None)

     实现一个用于 asyncio 任务的互斥锁。 非线程安全。

     asyncio 锁可被用来保证对共享资源的独占访问。

     使用 Lock 的推荐方式是通过 *note async with: 64c. 语句:

          lock = asyncio.Lock()

          # ... later
          async with lock:
              # access shared state

     这等价于:

          lock = asyncio.Lock()

          # ... later
          await lock.acquire()
          try:
              # access shared state
          finally:
              lock.release()

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

      -- 方法: coroutine acquire ()

          获取锁。

          此方法会等待直至锁为 `unlocked'，将其设为 `locked' 并返回
          ‘True’。

          当有一个以上的协程在 *note acquire(): 254e. 中被阻塞则会等待解
          锁，最终只有一个协程会被执行。

          锁的获取是 `公平的': 被执行的协程将是第一个开始等待锁的协程。

      -- 方法: release ()

          释放锁。

          当锁为 `locked' 时，将其设为 `unlocked' 并返回。

          如果锁为 `unlocked'，则会引发 *note RuntimeError: 2bb.。

      -- 方法: locked ()

          如果锁为 `locked' 则返回 ‘True’。


File: python.info,  Node: Event,  Next: Condition,  Prev: Lock,  Up: 同步原语<2>

5.18.1.25 Event
...............

 -- 类: asyncio.Event (*, loop=None)

     事件对象。 该对象不是线程安全的。

     asyncio 事件可被用来通知多个 asyncio 任务已经有事件发生。

     Event 对象会管理一个内部旗标，可通过 *note set(): 2552. 方法将其设
     为 `true' 并通过 *note clear(): 2553. 方法将其重设为 `false'。
     *note wait(): 2554. 方法会阻塞直至该旗标被设为 `true'。 该旗标初始
     时会被设为 `false'。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     示例:

          async def waiter(event):
              print('waiting for it ...')
              await event.wait()
              print('... got it!')

          async def main():
              # Create an Event object.
              event = asyncio.Event()

              # Spawn a Task to wait until 'event' is set.
              waiter_task = asyncio.create_task(waiter(event))

              # Sleep for 1 second and set the event.
              await asyncio.sleep(1)
              event.set()

              # Wait until the waiter task is finished.
              await waiter_task

          asyncio.run(main())

      -- 方法: coroutine wait ()

          等待直至事件被设置。

          如果事件已被设置，则立即返回 ‘True’。 否则将阻塞直至另一个任务
          调用 *note set(): 2552.。

      -- 方法: set ()

          设置事件。

          所有等待事件被设置的任务将被立即唤醒。

      -- 方法: clear ()

          清空（取消设置）事件.

          通过 *note wait(): 2554. 进行等待的任务现在将会阻塞直至 *note
          set(): 2552. 方法被再次调用。

      -- 方法: is_set ()

          如果事件已被设置则返回 ‘True’。


File: python.info,  Node: Condition,  Next: Semaphore,  Prev: Event,  Up: 同步原语<2>

5.18.1.26 Condition
...................

 -- 类: asyncio.Condition (lock=None, *, loop=None)

     条件对象。 该对象不是线程安全的。

     asyncio 条件原语可被任务用于等待某个事件发生，然后获取对共享资源的
     独占访问。

     在本质上，Condition 对象合并了 *note Event: 28d. 和 *note Lock:
     28c. 的功能。 多个 Condition 对象有可能共享一个 Lock，这允许关注于
     共享资源的特定状态的不同任务实现对共享资源的协同独占访问。

     可选的 `lock' 参数必须为 *note Lock: 28c. 对象或 ‘None’。 在后一种
     情况下会自动创建一个新的 Lock 对象。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     使用 Condition 的推荐方式是通过 *note async with: 64c. 语句:

          cond = asyncio.Condition()

          # ... later
          async with cond:
              await cond.wait()

     这等价于:

          cond = asyncio.Condition()

          # ... later
          await cond.acquire()
          try:
              await cond.wait()
          finally:
              cond.release()

      -- 方法: coroutine acquire ()

          获取下层的锁。

          此方法会等待直至下层的锁为 `unlocked'，将其设为 `locked' 并返
          回 returns ‘True’。

      -- 方法: notify (n=1)

          唤醒最多 `n' 个正在等待此条件的任务（默认为 1 个）。 如果没有
          任务正在等待则此方法为空操作。

          锁必须在此方法被调用前被获取并在随后被快速释放。 如果通过一个
          `unlocked' 锁调用则会引发 *note RuntimeError: 2bb.。

      -- 方法: locked ()

          如果下层的锁已被获取则返回 ‘True’。

      -- 方法: notify_all ()

          唤醒所有正在等待此条件的任务。

          此方法的行为类似于 *note notify(): 2559.，但会唤醒所有正在等待
          的任务。

          锁必须在此方法被调用前被获取并在随后被快速释放。 如果通过一个
          `unlocked' 锁调用则会引发 *note RuntimeError: 2bb.。

      -- 方法: release ()

          释放下层的锁。

          在未锁定的锁调用时，会引发 *note RuntimeError: 2bb. 异常。

      -- 方法: coroutine wait ()

          等待直至收到通知。

          当此方法被调用时如果调用方任务未获得锁，则会引发 *note
          RuntimeError: 2bb.。

          这个方法会释放下层的锁，然后保持阻塞直到被 *note notify():
          2559. 或 *note notify_all(): 255b. 调用所唤醒。 一旦被唤醒，
          Condition 会重新获取它的锁并且此方法将返回 ‘True’。

      -- 方法: coroutine wait_for (predicate)

          等待直到目标值变为 `true'。

          目标必须为一个可调用对象，其结果将被解读为一个布尔值。 最终的
          值将为返回值。


File: python.info,  Node: Semaphore,  Next: BoundedSemaphore,  Prev: Condition,  Up: 同步原语<2>

5.18.1.27 Semaphore
...................

 -- 类: asyncio.Semaphore (value=1, *, loop=None)

     信号量对象。 该对象不是线程安全的。

     信号量会管理一个内部计数器，该计数器会随每次 *note acquire(): 2560.
     调用递减并随每次 *note release(): 2561. 调用递增。 计数器的值永远不
     会降到零以下；当 *note acquire(): 2560. 发现其值为零时，它将保持阻
     塞直到有某个任务调用了 *note release(): 2561.。

     可选的 `value' 参数用来为内部计数器赋初始值 (默认值为 ‘1’)。 如果给
     定的值小于 ‘0’ 则会引发 *note ValueError: 1fc.。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     使用 Semaphore 的推荐方式是通过 *note async with: 64c. 语句。:

          sem = asyncio.Semaphore(10)

          # ... later
          async with sem:
              # work with shared resource

     这等价于:

          sem = asyncio.Semaphore(10)

          # ... later
          await sem.acquire()
          try:
              # work with shared resource
          finally:
              sem.release()

      -- 方法: coroutine acquire ()

          获取一个信号量。

          如果内部计数器的值大于零，则将其减一并立即返回 ‘True’。 如果其
          值为零，则会等待直到 *note release(): 2561. 并调用并返回
          ‘True’。

      -- 方法: locked ()

          如果信号量对象无法被立即获取则返回 ‘True’。

      -- 方法: release ()

          释放一个信号量对象，将内部计数器的值加一。 可以唤醒一个正在等
          待获取信号量对象的任务。

          不同于 *note BoundedSemaphore: 290.，*note Semaphore: 28f. 允
          许执行的 ‘release()’ 调用多于 ‘acquire()’ 调用。


File: python.info,  Node: BoundedSemaphore,  Prev: Semaphore,  Up: 同步原语<2>

5.18.1.28 BoundedSemaphore
..........................

 -- 类: asyncio.BoundedSemaphore (value=1, *, loop=None)

     绑定的信号量对象。 该对象不是线程安全的。

     BoundedSemaphore 是特殊版本的 *note Semaphore: 28f.，如果在 *note
     release(): 2561. 中内部计数器值增加到初始 `value' 以上它将引发一个
     *note ValueError: 1fc.。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

__________________________________________________________________

3.7 版后已移除: Acquiring a lock using ‘await lock’ or ‘yield from lock’
and/or *note with: 6f2. statement (‘with await lock’, ‘with (yield from
lock)’) is deprecated.  Use ‘async with lock’ instead.


File: python.info,  Node: 子进程集,  Next: 队列集,  Prev: 同步原语<2>,  Up: asyncio --- 异步 I/O

5.18.1.29 子进程集
..................

`源代码:' Lib/asyncio/subprocess.py(1),
Lib/asyncio/base_subprocess.py(2)

__________________________________________________________________

本节介绍了用于创建和管理子进程的高层级 async/await asyncio API。 下面的
例子演示了如何用 asyncio 运行一个 shell 命令并获取其结果:

     import asyncio

     async def run(cmd):
         proc = await asyncio.create_subprocess_shell(
             cmd,
             stdout=asyncio.subprocess.PIPE,
             stderr=asyncio.subprocess.PIPE)

         stdout, stderr = await proc.communicate()

         print(f'[{cmd!r} exited with {proc.returncode}]')
         if stdout:
             print(f'[stdout]\n{stdout.decode()}')
         if stderr:
             print(f'[stderr]\n{stderr.decode()}')

     asyncio.run(run('ls /zzz'))

将打印:

     ['ls /zzz' exited with 1]
     [stderr]
     ls: /zzz: No such file or directory

由于所有 asyncio 子进程函数都是异步的并且 asyncio 提供了许多工具用来配合
这些函数使用，因此并行地执行和监视多个子进程十分容易。 要修改上面的例子
来同时运行多个命令确实是非常简单的:

     async def main():
         await asyncio.gather(
             run('ls /zzz'),
             run('sleep 1; echo "hello"'))

     asyncio.run(main())

另请参阅 *note Examples: 2567. 小节。

* Menu:

* 创建子进程::
* 常量: 常量<7>.
* 与子进程交互::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/asyncio/subprocess.py

   (2) 
https://github.com/python/cpython/tree/3.8/Lib/asyncio/base_subprocess.py


File: python.info,  Node: 创建子进程,  Next: 常量<7>,  Up: 子进程集

5.18.1.30 创建子进程
....................

 -- 函数: coroutine asyncio.create_subprocess_exec (program, *args,
          stdin=None, stdout=None, stderr=None, loop=None, limit=None,
          **kwds)

     创建一个子进程。

     `limit' 参数为 ‘Process.stdout’ 和 ‘Process.stderr’ 设置 *note
     StreamReader: fda. 包装器的缓冲区上限（如果将 *note
     subprocess.PIPE: 3f6. 传给了 `stdout' 和 `stderr' 参数）。

     返回一个 *note Process: 2569. 实例。

     有关其他形参的说明请查阅 *note loop.subprocess_exec(): 24fc. 的文档
     。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

 -- 函数: coroutine asyncio.create_subprocess_shell (cmd, stdin=None,
          stdout=None, stderr=None, loop=None, limit=None, **kwds)

     运行 `cmd' shell 命令。

     `limit' 参数为 ‘Process.stdout’ 和 ‘Process.stderr’ 设置 *note
     StreamReader: fda. 包装器的缓冲区上限（如果将 *note
     subprocess.PIPE: 3f6. 传给了 `stdout' 和 `stderr' 参数）。

     返回一个 *note Process: 2569. 实例。

     有关其他形参的说明请查阅 *note loop.subprocess_shell(): 256a. 的文
     档。

          重要: 应用程序要负责确保正确地转义所有空白字符和特殊字符以防止
          shell 注入(1) 漏洞。 *note shlex.quote(): a7b. 函数可以被用来
          正确地转义字符串中可以被用来构造 shell 命令的空白字符和特殊
          shell 字符。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     注解: 如果使用了 *note ProactorEventLoop: 1ac. 则子进程将在 Windows
     中可用。 详情参见 *note Windows 上的子进程支持: 256b.。

参见
....

asyncio 还有下列 `低层级' API 可配合子进程使用: *note
loop.subprocess_exec(): 24fc, *note loop.subprocess_shell(): 256a, *note
loop.connect_read_pipe(): 256c, *note loop.connect_write_pipe(): 256d. 以
及 *note 子进程传输: 256e. 和 *note 子进程协议: 256f.。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Shell_injection#Shell_injection


File: python.info,  Node: 常量<7>,  Next: 与子进程交互,  Prev: 创建子进程,  Up: 子进程集

5.18.1.31 常量
..............

 -- 数据: asyncio.subprocess.PIPE

     可以被传递给 `stdin', `stdout' 或 `stderr' 形参。

     如果 `PIPE' 被传递给 `stdin' 参数，则 *note Process.stdin: 2572. 属
     性将会指向一个 *note StreamWriter: fdb. 实例。

     如果 `PIPE' 被传递给 `stdout' 或 `stderr' 参数，则 *note
     Process.stdout: 2573. 和 *note Process.stderr: 2574. 属性将会指向
     *note StreamReader: fda. 实例。

 -- 数据: asyncio.subprocess.STDOUT

     可以用作 `stderr' 参数的特殊值，表示标准错误应当被重定向到标准输出
     。

 -- 数据: asyncio.subprocess.DEVNULL

     可以用作 `stdin', `stdout' 或 `stderr' 参数来处理创建函数的特殊值。
     它表示将为相应的子进程流使用特殊文件 *note os.devnull: 102a.。


File: python.info,  Node: 与子进程交互,  Prev: 常量<7>,  Up: 子进程集

5.18.1.32 与子进程交互
......................

*note create_subprocess_exec(): 292. 和 *note create_subprocess_shell():
293. 函数都返回 `Process' 类的实例。 `Process' 是一个高层级包装器，它允
许与子进程通信并监视其完成情况。

 -- 类: asyncio.subprocess.Process

     一个用于包装 *note create_subprocess_exec(): 292. and *note
     create_subprocess_shell(): 293. 函数创建的 OS 进程的对象。

     这个类被设计为具有与 *note subprocess.Popen: 2ba. 类相似的 API，但
     两者有一些重要的差异:

        * 不同于 Popen，Process 实例没有与 *note poll(): 248d. 方法等价
          的方法；

        * *note communicate(): 2578. 和 *note wait(): 2579. 方法没有
          `timeout' 形参；要使用 *note wait_for(): 289. 函数；

        * *note Process.wait(): 2579. 方法是异步的，而 *note
          subprocess.Popen.wait(): 59b. 方法则被实现为阻塞型忙循环；

        * `universal_newlines' 形参不被支持。

     这个类不是线程安全的（*note not thread safe: 2515.）。

     请参阅 *note 子进程和线程: 257a. 部分。

      -- 方法: coroutine wait ()

          等待子进程终结。

          设置并返回 *note returncode: 257b. 属性。

               注解: 当使用 ‘stdout=PIPE’ 或 ‘stderr=PIPE’ 并且子进程产
               生了足以阻塞 OS 管道缓冲区等待接收更多的数据的输出时，此
               方法会发生死锁。 当使用管道时请使用 *note communicate():
               2578. 方法来避免这种情况。

      -- 方法: coroutine communicate (input=None)

          与进程交互:

            1. 发送数据到 `stdin' (如果 `input' 不为 ‘None’)；

            2. 从 `stdout' 和 `stderr' 读取数据，直至到达 EOF；

            3. 等待进程终结。

          可选的 `input' 参数为将被发送到子进程的数据 (*note bytes: 33a.
          对象)。

          返回一个元组 ‘(stdout_data, stderr_data)’。

          如果在将 `input' 写入到 `stdin' 时引发了 *note
          BrokenPipeError: 9a5. 或 *note ConnectionResetError: 9a8. 异常
          ，异常会被忽略。 此条件会在进程先于所有数据被写入到 `stdin' 之
          前退出时发生。

          如果想要将数据发送到进程的 `stdin'，则创建进程时必须使用
          ‘stdin=PIPE’。 类似地，要在结果元组中获得任何不为 ‘None’ 的值
          ，则创建进程时必须使用 ‘stdout=PIPE’ 和/或 ‘stderr=PIPE’ 参数
          。

          注意，数据读取在内存中是带缓冲的，因此如果数据量过大或不受则不
          要使用此方法。

      -- 方法: send_signal (signal)

          将信号 `signal' 发送给子进程。

               注解: 在 Windows 上，‘SIGTERM’ 是 *note terminate():
               257d. 的别名。 ‘CTRL_C_EVENT’ 和 ‘CTRL_BREAK_EVENT’ 可被
               发送给创建时附带 `creationflags' 形参且其中包括
               ‘CREATE_NEW_PROCESS_GROUP’ 的进程。

      -- 方法: terminate ()

          停止子进程。

          在 POSIX 系统中此方法会发送 *note signal.SIGTERM: 257e. 给子进
          程。

          在 Windows 上会调用 Win32 API 函数 ‘TerminateProcess()’ 以停止
          子进程。

      -- 方法: kill ()

          杀掉子进程。

          在 POSIX 系统中此方法会发送 ‘SIGKILL’ 给子进程。

          在 Windows 上此方法是 *note terminate(): 257d. 的别名。

      -- 属性: stdin

          标准输入流 (*note StreamWriter: fdb.) 或者如果进程创建时设置了
          ‘‘stdin=None‘‘ 则为 ‘None’。

      -- 属性: stdout

          标准输出流 (*note StreamReader: fda.) 或者如果进程创建时设置了
          ‘stdout=None’ 则为 ‘None’。

      -- 属性: stderr

          标准错误流 (*note StreamReader: fda.) 或者如果进程创建时设置了
          ‘stderr=None’ 则为 ‘None’。

          警告: 使用 *note communicate(): 2578. 方法而非 *note
          process.stdin.write(): 2572, *note await
          process.stdout.read(): 2573. 或 *note await
          process.stderr.read: 2574.。 这可以避免由于流暂停读取或写入并
          阻塞子进程而导致的死锁。

      -- 属性: pid

          进程标识号（PID）。

          注意对于由Note that for processes created by the *note
          create_subprocess_shell(): 293. 函数所创建的进程，这个属性将是
          所生成的 shell 的 PID。

      -- 属性: returncode

          当进程退出时返回其代号。

          ‘None’ 值表示进程尚未终止。

          一个负值 ‘-N’ 表示子进程被信号 ‘N’ 中断 (仅 POSIX).

* Menu:

* 子进程和线程::
* 例子: 例子<12>.


File: python.info,  Node: 子进程和线程,  Next: 例子<12>,  Up: 与子进程交互

5.18.1.33 子进程和线程
......................

标准 asyncio 事件循环默认支持从不同线程中运行子进程。

在 Windows 上子进程（默认）只由 *note ProactorEventLoop: 1ac. 提供，
*note SelectorEventLoop: 2582. 没有子进程支持。

在 UNIX 上会使用 `child watchers' 来让子进程结束等待，详情请参阅 *note
进程监视器: 2583.。

在 3.8 版更改: UNIX 对于从不同线程中无限制地生成子进程会切换为使用 *note
ThreadedChildWatcher: 2584.。

使用 `不活动的' 当前子监视器生成子进程将引发 *note RuntimeError: 2bb.。

请注意其他的事件循环实现可能有其本身的限制；请查看它们各自的文档。

参见
....

*note asyncio 中的并发和多线程: 2515. 章节。


File: python.info,  Node: 例子<12>,  Prev: 子进程和线程,  Up: 与子进程交互

5.18.1.34 例子
..............

一个使用 *note Process: 2569. 类来控制子进程并用 *note StreamReader:
fda. 类来从其标准输出读取信息的例子。 这个子进程是由 *note
create_subprocess_exec(): 292. 函数创建的:

     import asyncio
     import sys

     async def get_date():
         code = 'import datetime; print(datetime.datetime.now())'

         # Create the subprocess; redirect the standard output
         # into a pipe.
         proc = await asyncio.create_subprocess_exec(
             sys.executable, '-c', code,
             stdout=asyncio.subprocess.PIPE)

         # Read one line of output.
         data = await proc.stdout.readline()
         line = data.decode('ascii').rstrip()

         # Wait for the subprocess exit.
         await proc.wait()
         return line

     date = asyncio.run(get_date())
     print(f"Current date: {date}")

另请参阅使用低层级 API 编写的 *note 相同示例: 2586.。


File: python.info,  Node: 队列集,  Next: 异常<9>,  Prev: 子进程集,  Up: asyncio --- 异步 I/O

5.18.1.35 队列集
................

`源代码:' Lib/asyncio/queues.py(1)

__________________________________________________________________

asyncio 队列被设计成与 *note queue: db. 模块类似。尽管 asyncio队列不是线
程安全的，但是他们是被设计专用于 async/await 代码。

注意asyncio 的队列没有 `timeout' 形参；请使用 *note asyncio.wait_for():
289. 函数为队列添加超时操作。

参见下面的 *note Examples: 2589. 部分。

* Menu:

* Queue::
* 优先级队列::
* 后进先出队列::
* 异常: 异常<8>.
* 例子: 例子<13>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/asyncio/queues.py


File: python.info,  Node: Queue,  Next: 优先级队列,  Up: 队列集

5.18.1.36 Queue
...............

 -- 类: asyncio.Queue (maxsize=0, *, loop=None)

     先进，先出（FIFO）队列

     如果 `maxsize' 小于等于零，则队列尺寸是无限的。如果是大于 ‘0’ 的整
     数，则当队列达到 `maxsize' 时， ‘await put()’ 将阻塞至某个元素被
     *note get(): 258b. 取出。

     不像标准库中的并发型 *note queue: db. ，队列的尺寸一直是已知的，可
     以通过调用 *note qsize(): 258c. 方法返回。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     这个类不是线程安全的（*note not thread safe: 2515.）。

      -- 属性: maxsize

          队列中可存放的元素数量。

      -- 方法: empty ()

          如果队列为空返回 ‘True’ ，否则返回 ‘False’ 。

      -- 方法: full ()

          如果有 *note maxsize: 258d. 个条目在队列中，则返回 ‘True’ 。

          如果队列用 ‘maxsize=0’ （默认）初始化，则 *note full(): 258f.
          永远不会返回 ‘True’ 。

      -- 方法: coroutine get ()

          从队列中删除并返回一个元素。如果队列为空，则等待，直到队列中有
          元素。

      -- 方法: get_nowait ()

          立即返回一个队列中的元素，如果队列内有值，否则引发异常 *note
          QueueEmpty: 2591. 。

      -- 方法: coroutine join ()

          阻塞至队列中所有的元素都被接收和处理完毕。

          当条目添加到队列的时候，未完成任务的计数就会增加。每当消费协程
          调用 *note task_done(): 6a9. 表示这个条目已经被回收，该条目所
          有工作已经完成，未完成计数就会减少。当未完成计数降到零的时候，
          *note join(): 6a8. 阻塞被解除。

      -- 方法: coroutine put (item)

          添加一个元素进队列。如果队列满了，在添加元素之前，会一直等待空
          闲插槽可用。

      -- 方法: put_nowait (item)

          不阻塞的放一个元素入队列。

          如果没有立即可用的空闲槽，引发 *note QueueFull: 2594. 异常。

      -- 方法: qsize ()

          返回队列用的元素数量。

      -- 方法: task_done ()

          表明前面排队的任务已经完成，即get出来的元素相关操作已经完成。

          由队列使用者控制。每个 *note get(): 258b. 用于获取一个任务，任
          务最后调用 *note task_done(): 6a9. 告诉队列，这个任务已经完成
          。

          如果 *note join(): 6a8. 当前正在阻塞，在所有条目都被处理后，将
          解除阻塞(意味着每个 *note put(): 2592. 进队列的条目的 *note
          task_done(): 6a9. 都被收到)。

          如果被调用的次数多于放入队列中的项目数量，将引发 *note
          ValueError: 1fc. 。


File: python.info,  Node: 优先级队列,  Next: 后进先出队列,  Prev: Queue,  Up: 队列集

5.18.1.37 优先级队列
....................

 -- 类: asyncio.PriorityQueue

     *note Queue: 291. 的变体；按优先级顺序取出条目 (最小的先取出)。

     条目通常是 ‘(priority_number, data)’ 形式的元组。


File: python.info,  Node: 后进先出队列,  Next: 异常<8>,  Prev: 优先级队列,  Up: 队列集

5.18.1.38 后进先出队列
......................

 -- 类: asyncio.LifoQueue

     *note Queue: 291. 的变体，先取出最近添加的条目（后进，先出）。


File: python.info,  Node: 异常<8>,  Next: 例子<13>,  Prev: 后进先出队列,  Up: 队列集

5.18.1.39 异常
..............

 -- 例外: asyncio.QueueEmpty

     当队列为空的时候，调用 *note get_nowait(): 2590. 方法而引发这个异常
     。

 -- 例外: asyncio.QueueFull

     当队列中条目数量已经达到它的 `maxsize' 的时候，调用 *note
     put_nowait(): 2593. 方法而引发的异常。


File: python.info,  Node: 例子<13>,  Prev: 异常<8>,  Up: 队列集

5.18.1.40 例子
..............

队列能被用于多个的并发任务的工作量分配：

     import asyncio
     import random
     import time


     async def worker(name, queue):
         while True:
             # Get a "work item" out of the queue.
             sleep_for = await queue.get()

             # Sleep for the "sleep_for" seconds.
             await asyncio.sleep(sleep_for)

             # Notify the queue that the "work item" has been processed.
             queue.task_done()

             print(f'{name} has slept for {sleep_for:.2f} seconds')


     async def main():
         # Create a queue that we will use to store our "workload".
         queue = asyncio.Queue()

         # Generate random timings and put them into the queue.
         total_sleep_time = 0
         for _ in range(20):
             sleep_for = random.uniform(0.05, 1.0)
             total_sleep_time += sleep_for
             queue.put_nowait(sleep_for)

         # Create three worker tasks to process the queue concurrently.
         tasks = []
         for i in range(3):
             task = asyncio.create_task(worker(f'worker-{i}', queue))
             tasks.append(task)

         # Wait until the queue is fully processed.
         started_at = time.monotonic()
         await queue.join()
         total_slept_for = time.monotonic() - started_at

         # Cancel our worker tasks.
         for task in tasks:
             task.cancel()
         # Wait until all worker tasks are cancelled.
         await asyncio.gather(*tasks, return_exceptions=True)

         print('====')
         print(f'3 workers slept in parallel for {total_slept_for:.2f} seconds')
         print(f'total expected sleep time: {total_sleep_time:.2f} seconds')


     asyncio.run(main())


File: python.info,  Node: 异常<9>,  Next: 事件循环,  Prev: 队列集,  Up: asyncio --- 异步 I/O

5.18.1.41 异常
..............

`源代码:' Lib/asyncio/exceptions.py(1)

__________________________________________________________________

 -- 例外: asyncio.TimeoutError

     该操作已超过规定的截止日期。

          重要: 这个异常与内置 *note TimeoutError: 9a4. 异常不同。

 -- 例外: asyncio.CancelledError

     该操作已被取消。

     取消asyncio任务时，可以捕获此异常以执行自定义操作。在几乎所有情况下
     ，都必须重新引发异常。

     在 3.8 版更改: *note CancelledError: 1a8. 现在是 *note
     BaseException: 1a9. 的子类。

 -- 例外: asyncio.InvalidStateError

     *note Task: 1ae. 或 *note Future: 44b. 的内部状态无效。

     在为已设置结果值的未来对象设置结果值等情况下，可以引发此问题。

 -- 例外: asyncio.SendfileNotAvailableError

     "sendfile" 系统调用不适用于给定的套接字或文件类型。

     子类 *note RuntimeError: 2bb. 。

 -- 例外: asyncio.IncompleteReadError

     请求的读取操作未完全完成。

     由 *note asyncio stream APIs: 24f8. 提出

     此异常是 *note EOFError: c74. 的子类。

      -- 属性: expected

          预期字节的总数（ *note int: 185. ）。

      -- 属性: partial

          到达流结束之前读取的 *note bytes: 33a. 字符串。

 -- 例外: asyncio.LimitOverrunError

     在查找分隔符时达到缓冲区大小限制。

     由 *note asyncio stream APIs: 24f8. 提出

      -- 属性: consumed

          要消耗的字节总数。

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/asyncio/exceptions.py


File: python.info,  Node: 事件循环,  Next: Futures,  Prev: 异常<9>,  Up: asyncio --- 异步 I/O

5.18.1.42 事件循环
..................

`源代码:' Lib/asyncio/events.py(1), Lib/asyncio/base_events.py(2)

__________________________________________________________________

前言
....

事件循环是每个 asyncio 应用的核心。 事件循环会运行异步任务和回调，执行网
络 IO 操作，以及运行子进程。

应用开发者通常应当使用高层级的 asyncio 函数，例如 *note asyncio.run():
1a6.，应当很少有必要引用循环对象或调用其方法。 本节所针对的主要是低层级
代码、库和框架的编写者，他们需要更细致地控制事件循环行为。

获取事件循环
............

以下低层级函数可被用于获取、设置或创建事件循环:

 -- 函数: asyncio.get_running_loop ()

     返回当前 OS 线程中正在运行的事件循环。

     如果没有正在运行的事件循环则会引发 *note RuntimeError: 2bb.。 此函
     数只能由协程或回调来调用。

     3.7 新版功能.

 -- 函数: asyncio.get_event_loop ()

     获取当前事件循环。

     如果当前 OS 线程没有设置当前事件循环，该 OS 线程为主线程，并且
     *note set_event_loop(): 25a3. 还没有被调用，则 asyncio 将创建一个新
     的事件循环并将其设为当前事件循环。

     由于此函数具有相当复杂的行为（特别是在使用了自定义事件循环策略的时
     候），更推荐在协程和回调中使用 *note get_running_loop(): 35d. 函数
     而非 *note get_event_loop(): 35e.。

     应该考虑使用 *note asyncio.run(): 1a6. 函数而非使用低层级函数来手动
     创建和关闭事件循环。

 -- 函数: asyncio.set_event_loop (loop)

     将 `loop' 设置为当前 OS 线程的当前事件循环。

 -- 函数: asyncio.new_event_loop ()

     创建一个新的事件循环。

请注意 *note get_event_loop(): 35e, *note set_event_loop(): 25a3. 以及
*note new_event_loop(): 25a4. 函数的行为可以通过 *note
设置自定义事件循环策略: 25a5. 来改变。

目录
....

本文档包含下列小节:

   * *note 事件循环方法集: 25a6. 章节是事件循环APIs的参考文档；

   * *note 回调处理: 25a7. 章节是从调度方法 例如 *note loop.call_soon():
     352. 和 *note loop.call_later(): 354. 中返回 *note Handle: 10b2. 和
     *note TimerHandle: 25a8. 实例的文档。

   * *note Server Objects: 25a9. 章节记录了从事件循环方法返回的类型，比
     如 *note loop.create_server(): 366. ；

   * *note Event Loop Implementations: 25aa. 章节记录了 *note
     SelectorEventLoop: 2582. 和 *note ProactorEventLoop: 1ac. 类；

   * *note Examples: 25ab. 章节展示了如何使用某些事件循环API。

* Menu:

* 事件循环方法集::
* 回调处理::
* Server 对象::
* 事件循环实现::
* 例子: 例子<14>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/asyncio/events.py

   (2) 
https://github.com/python/cpython/tree/3.8/Lib/asyncio/base_events.py


File: python.info,  Node: 事件循环方法集,  Next: 回调处理,  Up: 事件循环

5.18.1.43 事件循环方法集
........................

事件循环有下列 `低级' APIs：

* Menu:

* 运行和停止循环::
* 调度回调::
* 调度延迟回调::
* 创建 Futures 和 Tasks::
* 打开网络连接::
* 创建网络服务::
* 传输文件::
* TLS 升级::
* 监控文件描述符::
* 直接使用 socket 对象::
* DNS::
* 使用管道::
* Unix 信号::
* 在线程或者进程池中执行代码。::
* 错误处理API::
* 开启调试模式::
* 运行子进程::


File: python.info,  Node: 运行和停止循环,  Next: 调度回调,  Up: 事件循环方法集

5.18.1.44 运行和停止循环
........................

 -- 方法: loop.run_until_complete (future)

     运行直到 `future' ( *note Future: 44b. 的实例 ) 被完成。

     如果参数是 *note coroutine object: 24f7. ，将被隐式调度为 *note
     asyncio.Task: 1ae. 来运行。

     返回 Future 的结果 或者引发相关异常。

 -- 方法: loop.run_forever ()

     运行事件循环直到 *note stop(): 528. 被调用。

     如果 *note stop(): 528. 在调用 *note run_forever(): 25ad. 之前被调
     用，循环将轮询一次 I/O 选择器并设置超时为零，再运行所有已加入计划任
     务的回调来响应 I/O 事件（以及已加入计划任务的事件），然后退出。

     如果 *note stop(): 528. 在 *note run_forever(): 25ad. 运行期间被调
     用，循环将运行当前批次的回调然后退出。 请注意在此情况下由回调加入计
     划任务的新回调将不会运行；它们将会在下次 *note run_forever(): 25ad.
     或 *note run_until_complete(): 520. 被调用时运行。

 -- 方法: loop.stop ()

     停止事件循环。

 -- 方法: loop.is_running ()

     返回 ‘True’ 如果事件循环当前正在运行。

 -- 方法: loop.is_closed ()

     如果事件循环已经被关闭，返回 ‘True’ 。

 -- 方法: loop.close ()

     关闭事件循环。

     当这个函数被调用的时候，循环必须处于非运行状态。pending状态的回调将
     被丢弃。

     此方法清除所有的队列并立即关闭执行器，不会等待执行器完成。

     这个方法是幂等的和不可逆的。事件循环关闭后，不应调用其他方法。

 -- 方法: coroutine loop.shutdown_asyncgens ()

     安排所有当前打开的 *note asynchronous generator: 1513. 对象通过
     *note aclose(): 151b. 调用来关闭。 在调用此方法后，如果有新的异步生
     成器被迭代事件循环将会发出警告。 这应当被用来可靠地完成所有已加入计
     划任务的异步生成器。

     运行请注意，当使用 *note asyncio.run(): 1a6. 时，无需调用此函数。

     示例:

          try:
              loop.run_forever()
          finally:
              loop.run_until_complete(loop.shutdown_asyncgens())
              loop.close()

     3.6 新版功能.


File: python.info,  Node: 调度回调,  Next: 调度延迟回调,  Prev: 运行和停止循环,  Up: 事件循环方法集

5.18.1.45 调度回调
..................

 -- 方法: loop.call_soon (callback, *args, context=None)

     安排 `callback' *note callback: 25b1. 在事件循环的下一次迭代时附带
     `args' 参数被调用。

     回调按其注册顺序被调用。每个回调仅被调用一次。

     可选键值类的参数 `context' 允许 `callback' 运行在一个指定的自定义
     *note contextvars.Context: 24cb. 对象中。如果没有提供 `context' ，
     则使用当前上下文。

     返回一个能用来取消回调的 *note asyncio.Handle: 10b2. 实例。

     这个方法不是线程安全的。

 -- 方法: loop.call_soon_threadsafe (callback, *args, context=None)

     *note call_soon(): 352. 的线程安全变体。必须被用于安排 `来自其他线
     程' 的回调。

     参见 *note concurrency and multithreading: 2515. 部分的文档。

在 3.7 版更改: 加入键值类形参 `context'。请参阅 PEP 567(1) 查看更多细节
。

     注解: 大多数 *note asyncio: a. 的调度函数不让传递关键字参数。为此，
     请使用 *note functools.partial(): 7d1. ：

          # will schedule "print("Hello", flush=True)"
          loop.call_soon(
              functools.partial(print, "Hello", flush=True))

     使用 partial 对象通常比使用lambda更方便，asyncio 在调试和错误消息中
     能更好的呈现 partial 对象。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0567


File: python.info,  Node: 调度延迟回调,  Next: 创建 Futures 和 Tasks,  Prev: 调度回调,  Up: 事件循环方法集

5.18.1.46 调度延迟回调
......................

事件循环提供安排调度函数在将来某个时刻调用的机制。事件循环使用单调时钟来
跟踪时间。

 -- 方法: loop.call_later (delay, callback, *args, context=None)

     安排 `callback' 在给定的 `delay' 秒（可以是 int 或者 float）后被调
     用。

     返回一个 *note asyncio.TimerHandle: 25a8. 实例，该实例能用于取消回
     调。

     `callback' 只被调用一次。如果两个回调被安排在同样的时间点，执行顺序
     未限定。

     可选的位置参数 `args' 在被调用的时候传递给 `callback'  。 如果你想
     把关键字参数传递给 `callback' ，请使用 *note functools.partial():
     7d1. 。

     可选键值类的参数 `context' 允许 `callback' 运行在一个指定的自定义
     *note contextvars.Context: 24cb. 对象中。如果没有提供 `context' ，
     则使用当前上下文。

     在 3.7 版更改: 加入键值类形参 `context'。请参阅 PEP 567(1) 查看更多
     细节。

     在 3.8 版更改: 在 Python 3.7 和更早版本的默认事件循环实现中，
     `delay' 不能超过一天。 这在 Python 3.8 中已被修复。

 -- 方法: loop.call_at (when, callback, *args, context=None)

     安排 `callback' 在给定的绝对时间戳的 `时间' （一个 int 或者 float）
     被调用，使用与 *note loop.time(): 25b5. 同样的时间参考。

     本方法的行为和 *note call_later(): 354. 方法相同。

     返回一个 *note asyncio.TimerHandle: 25a8. 实例，该实例能用于取消回
     调。

     在 3.7 版更改: 加入键值类形参 `context'。请参阅 PEP 567(2) 查看更多
     细节。

     在 3.8 版更改: 在 Python 3.7 和更早版本的默认事件循环实现中，`when'
     和当前时间相差不能超过一天。 在这 Python 3.8 中已被修复。

 -- 方法: loop.time ()

     根据时间循环内部的单调时钟，返回当前时间， *note float: 188. 值。

     注解: 
     在 3.8 版更改: 在 Python 3.7 和更早版本中超时 (相对的 `delay' 或绝
     对的 `when') 不能超过一天。 这在 Python 3.8 中已被修复。

参见
....

*note asyncio.sleep(): 286. 函数。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0567

   (2) https://www.python.org/dev/peps/pep-0567


File: python.info,  Node: 创建 Futures 和 Tasks,  Next: 打开网络连接,  Prev: 调度延迟回调,  Up: 事件循环方法集

5.18.1.47 创建 Futures 和 Tasks
...............................

 -- 方法: loop.create_future ()

     创建一个附加到事件循环中的 *note asyncio.Future: 44b. 对象。

     这是在asyncio中创建Futures的首选方式。这让第三方事件循环可以提供
     Future 对象的替代实现(更好的性能或者功能)。

     3.5.2 新版功能.

 -- 方法: loop.create_task (coro, *, name=None)

     安排一个 *note 协程: 24f7. 的执行。返回一个 *note Task: 1ae. 对象。

     第三方的事件循环可以使用它们自己的 *note Task: 1ae. 子类来满足互操
     作性。这种情况下结果类型是一个 *note Task: 1ae. 的子类。

     如果提供了 `name' 参数且不为 ‘None’，它会使用 *note
     Task.set_name(): 1b1. 来设为任务的名称。

     在 3.8 版更改: 添加了 ‘name’ 形参。

 -- 方法: loop.set_task_factory (factory)

     设置一个 task 工厂 ， 被用于 *note loop.create_task(): 1b0. 。

     如果 `factory' 为 ‘None’ 则将设置默认的任务工厂。 在其他情况下，
     `factory' 必须为一个 `可调用对象' 且签名匹配 ‘(loop, coro)’，其中
     `loop' 是对活动事件循环的引用，而 `coro' 是一个协程对象。 该可调用
     对象必须返回一个兼容 *note asyncio.Future: 44b. 的对象。

 -- 方法: loop.get_task_factory ()

     返回一个任务工厂，或者如果是使用默认值则返回 ‘None’。


File: python.info,  Node: 打开网络连接,  Next: 创建网络服务,  Prev: 创建 Futures 和 Tasks,  Up: 事件循环方法集

5.18.1.48 打开网络连接
......................

 -- 方法: coroutine loop.create_connection (protocol_factory, host=None,
          port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None,
          local_addr=None, server_hostname=None,
          ssl_handshake_timeout=None, happy_eyeballs_delay=None,
          interleave=None)

     打开一个流式传输连接，连接到由 `host' 和 `port' 指定的地址。

     套接字族可以是 *note AF_INET: 25b8. 或 *note AF_INET6: 25b9.，具体
     取决于 `host' (或 `family' 参数，如果有提供的话)。

     套接字类型将为 *note SOCK_STREAM: c92.。

     `protocol_factory' 必须为一个返回 *note asyncio 协议: 25ba. 实现的
     可调用对象。

     这个方法会尝试在后台创建连接。当创建成功，返回 ‘(transport,
     protocol)’ 组合。

     底层操作的大致的执行顺序是这样的：

       1. 创建连接并为其创建一个 *note 传输: 25bb.。

       2. 不带参数地调用 `protocol_factory' 并预期返回一个 *note 协议:
          25ba. 实例。

       3. 协议实例通过调用其 *note connection_made(): 25bc. 方法与传输进
          行配对。

       4. 成功时返回一个 ‘(transport, protocol)’ 元组。

     被创建的传输对象是一个实现相关的双向流。

     其他参数：

        * `ssl': 如果给定该参数且不为假值，则会创建一个 SSL/TLS 传输（默
          认创建一个纯 TCP 传输）。 如果 `ssl' 是一个 *note
          ssl.SSLContext: 3ec. 对象，则会使用此上下文来创建传输对象；如
          果 `ssl' 为 *note True: 4a1.，则会使用从 *note
          ssl.create_default_context(): 8c9. 返回的默认上下文。

          参见
          ....

          *note SSL/TLS security considerations: 25bd.

        * `server_hostname' 设置或重载目标服务器的证书将要匹配的主机名。
          应当只在 `ssl' 不为 ‘None’ 时传入。 默认情况下会使用 `host' 参
          数的值。 如果 `host' 为空那就没有默认值，你必须为
          `server_hostname' 传入一个值。 如果 `server_hostname' 为空字符
          串，则主机名匹配会被禁用（这是一个严重的安全风险，使得潜在的中
          间人攻击成为可能）。

        * `family', `proto', `flags' 是可选的地址族、协议和标志，它们会
          被传递给 getaddrinfo() 来对 `host' 进行解析。如果要指定的话，
          这些都应该是来自于 *note socket: f0. 模块的对应常量。

        * 如果给出 `happy_eyeballs_delay'，它将为此链接启用 Happy
          Eyeballs。 该函数应当为一个表示在开始下一个并行尝试之前要等待
          连接尝试完成的秒数的浮点数。 这也就是在 RFC 8305(1) 中定义的
          "连接尝试延迟"。 该 RFC 所推荐的合理默认值为 ‘0.25’ (250 毫秒
          )。

        * `interleave' 控制当主机名解析为多个 IP 地址时的地址重排序。 如
          果该参数为 ‘0’ 或未指定，则不会进行重排序，这些地址会按 *note
          getaddrinfo(): 4a9. 所返回的顺序进行尝试。 如果指定了一个正整
          数，这些地址会按地址族交错排列，而指定的整数会被解读为 RFC
          8305(2) 所定义的 "首个地址族计数"。 如果
          `happy_eyeballs_delay' 未指定则默认值为 ‘0’，否则为 ‘1’。

        * 如果给出 `sock'，它应当是一个已存在、已连接并将被传输所使用的
          *note socket.socket: 67d. 对象。 如果给出了 `sock'，则 `host',
          `port', `family', `proto', `flags', `happy_eyeballs_delay',
          `interleave' 和 `local_addr' 都不应当被指定。

        * 如果给出 `local_addr'，它应当是一个用来在本地绑定套接字的
          ‘(local_host, local_port)’ 元组。 `local_host' 和 `local_port'
          会使用 ‘getaddrinfo()’ 来查找，这与 `host' 和 `port' 类似。

        * `ssl_handshake_timeout' 是（用于 TLS 连接的）在放弃连接之前要
          等待 TLS 握手完成的秒数。 如果参数为 ‘None’ 则使用 (默认的)
          ‘60.0’。

     3.8 新版功能: 增加了 `happy_eyeballs_delay' 和 `interleave' 形参。

     Happy Eyeballs 算法：成功使用双栈主机。 当服务器的 IPv4 路径和协议
     工作正常，但服务器的 IPv6 路径和协议工作不正常时，双栈客户端应用程
     序相比单独 IPv4 客户端会感受到明显的连接延迟。 这是不可接受的因为它
     会导致双栈客户端糟糕的用户体验。 此文档指明了减少这种用户可见延迟的
     算法要求并提供了具体的算法。

     详情参见: ‘https://tools.ietf.org/html/rfc6555’

     3.7 新版功能: `ssl_handshake_timeout' 形参。

     在 3.6 版更改: 套接字选项 ‘TCP_NODELAY’ 默认已为所有 TCP 连接进行了
     设置。

     在 3.5 版更改: *note ProactorEventLoop: 1ac. 类中添加 SSL/TLS 支持
     。

     参见
     ....

     *note open_connection(): 36c. 函数是一个高层级的替代 API。 它返回一
     对 (*note StreamReader: fda, *note StreamWriter: fdb.)，可在
     async/await 代码中直接使用。

 -- 方法: coroutine loop.create_datagram_endpoint (protocol_factory,
          local_addr=None, remote_addr=None, *, family=0, proto=0,
          flags=0, reuse_address=None, reuse_port=None,
          allow_broadcast=None, sock=None)

          注解: 形参 `reuse_address' 已不再受支持，因为使用
          ‘SO_REUSEADDR’ 会对 UDP 造成显著的安全问题。 显式地传入
          ‘reuse_address=True’ 将会引发异常。

          当具有不同 UID 的多个进程将套接字赋给具有 ‘SO_REUSEADDR’ 的相
          同 UDP 套接字地址时，传入的数据包可能会在套接字间随机分配。

          对于受支持的平台，`reuse_port' 可以被用作类似功能的替代。 通过
          `reuse_port' 将改用 ‘SO_REUSEPORT’，它能够防止具有不同 UID 的
          进程将套接字赋给相同的套接字地址。

     创建一个数据报连接。

     套接字族可以是 *note AF_INET: 25b8, *note AF_INET6: 25b9. 或 *note
     AF_UNIX: 25be.，具体取决于 `host' (或 `family' 参数，如果有提供的话
     )。

     socket类型将是 *note SOCK_DGRAM: c91. 。

     `protocol_factory' 必须为一个返回 *note 协议: 25ba. 实现的可调用对
     象。

     成功时返回一个 ‘(transport, protocol)’ 元组。

     其他参数：

        * `local_addr'，如果指定的话，就是一个 ‘(local_host,
          local_port)’ 元组，用于在本地绑定套接字。 `local_host' 和
          `local_port' 是使用 *note getaddrinfo(): 4a9. 来查找的。

        * `remote_addr'，如果指定的话，就是一个 ‘(remote_host,
          remote_port)’ 元组，用于同一个远程地址连接。`remote_host' 和
          `remote_port' 是使用 *note getaddrinfo(): 4a9. 来查找的。

        * `family', `proto', `flags' 是可选的地址族，协议和标志，其会被
          传递给 *note getaddrinfo(): 4a9. 来完成 `host' 的解析。如果要
          指定的话，这些都应该是来自于 *note socket: f0. 模块的对应常量
          。

        * `reuse_port' 告知内核，只要在创建时都设置了这个旗标，就允许此
          端点绑定到其他现有端点所绑定的相同端口上。 这个选项在 Windows
          和某些 Unix 上不受支持。 如果 ‘SO_REUSEPORT’ 常量未定义则此功
          能就是不受支持的。

        * `allow_broadcast' 告知内核允许此端点向广播地址发送消息。

        * `sock' 可选择通过指定此值用于使用一个预先存在的，已经处于连接
          状态的 *note socket.socket: 67d. 对象，并将其提供给此传输对象
          使用。如果指定了这个值， `local_addr' 和 `remote_addr' 就应该
          被忽略 (必须为 *note None: 158.)。

     参见 *note UDP echo 客户端协议: 25bf. 和 *note UDP echo 服务端协议:
     25c0. 的例子。

     在 3.4.4 版更改: 添加了 `family', `proto', `flags',
     `reuse_address', `reuse_port', `allow_broadcast' 和 `sock' 等参数。

     在 3.8.1 版更改: 出于安全考虑，`reuse_address' 形参已不再受支持。

     在 3.8 版更改: 添加WIndows的支持。

 -- 方法: coroutine loop.create_unix_connection (protocol_factory,
          path=None, *, ssl=None, sock=None, server_hostname=None,
          ssl_handshake_timeout=None)

     创建Unix 连接

     套接字族将为 *note AF_UNIX: 25be.；套接字类型将为 *note
     SOCK_STREAM: c92.。

     成功时返回一个 ‘(transport, protocol)’ 元组。

     `path' 是所要求的 Unix 域套接字的名字，除非指定了 `sock' 形参。 抽
     象的 Unix 套接字, *note str: 339, *note bytes: 33a. 和 *note Path:
     202. 路径都是受支持的。

     请查看 *note loop.create_connection(): 1b3. 方法的文档了解有关此方
     法的参数的信息。

     *note 可用性: 136f.: Unix。

     3.7 新版功能: `ssl_handshake_timeout' 形参。

     在 3.7 版更改: `path' 形参现在可以是 *note path-like object: 373. 对
     象。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc8305.html

   (2) https://tools.ietf.org/html/rfc8305.html


File: python.info,  Node: 创建网络服务,  Next: 传输文件,  Prev: 打开网络连接,  Up: 事件循环方法集

5.18.1.49 创建网络服务
......................

 -- 方法: coroutine loop.create_server (protocol_factory, host=None,
          port=None, *, family=socket.AF_UNSPEC,
          flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None,
          reuse_address=None, reuse_port=None,
          ssl_handshake_timeout=None, start_serving=True)

     创建TCP服务 (socket 类型 *note SOCK_STREAM: c92. ) 监听 `host' 地址
     的 `port' 端口。

     返回一个 *note Server: 365. 对象。

     参数：

        * `protocol_factory' 必须为一个返回 *note 协议: 25ba. 实现的可调
          用对象。

        * `host' 形参可被设为几种类型，它确定了服务器所应监听的位置:

             - 如果 `host' 是一个字符串，则 TCP 服务器会被绑定到 `host'
               所指明的单一网络接口。

             - 如果 `host' 是一个字符串序列，则 TCP 服务器会被绑定到序列
               所指明的所有网络接口。

             - 如果 `host' 是一个空字符串或 ‘None’，则会应用所有接口并将
               返回包含多个套接字的列表（通常是一个 IPv4 的加一个 IPv6 的
               ）。

        * `family' 可被设为 *note socket.AF_INET: 25b8. 或 *note
          AF_INET6: 25b9. 以强制此套接字使用 IPv4 或 IPv6。 如果未设定，
          则 `family' 将通过主机名称来确定 (默认为 ‘AF_UNSPEC’)。

        * `flags' 是用于 *note getaddrinfo(): 4a9. 的位掩码。

        * 可以选择指定 `sock' 以便使用预先存在的套接字对象。 如果指定了
          此参数，则不可再指定 `host' 和 `port'。

        * `backlog' 是传递给 *note listen(): 754. 的最大排队连接的数量（
          默认为100）。

        * `ssl' 可被设置为一个 *note SSLContext: 3ec. 实例以在所接受的连
          接上启用 TLS。

        * `reuse_address' 告知内核要重用一个处于 ‘TIME_WAIT’ 状态的本地
          套接字，而不是等待其自然超时失效。 如果未指定此参数则在 Unix 上
          将自动设置为 ‘True’。

        * `reuse_port' 告知内核，只要在创建的时候都设置了这个标志，就允
          许此端点绑定到其它端点列表所绑定的同样的端口上。这个选项在
          Windows 上是不支持的。

        * `ssl_handshake_timeout' 是（用于 TLS 服务器的）在放弃连接之前
          要等待 TLS 握手完成的秒数。 如果参数为 (默认值) ‘None’ 则为
          ‘60.0’ 秒。

        * `start_serving' 设置成 ‘True’ (默认值) 会导致创建server并立即
          开始接受连接。设置成 ‘False’ ，用户需要等待 *note
          Server.start_serving(): 368. 或者 *note
          Server.serve_forever(): 369. 以使server开始接受连接。

     3.7 新版功能: 增加了 `ssl_handshake_timeout' 和 `start_serving' 形
     参。

     在 3.6 版更改: 套接字选项 ‘TCP_NODELAY’ 默认已为所有 TCP 连接进行了
     设置。

     在 3.5 版更改: *note ProactorEventLoop: 1ac. 类中添加 SSL/TLS 支持
     。

     在 3.5.1 版更改: `host' 形参可以是一个字符串的序列。

     参见
     ....

     *note start_server(): 36d. 函数是一个高层级的替代 API，它返回一对
     *note StreamReader: fda. 和 *note StreamWriter: fdb.，可在
     async/await 代码中使用。

 -- 方法: coroutine loop.create_unix_server (protocol_factory,
          path=None, *, sock=None, backlog=100, ssl=None,
          ssl_handshake_timeout=None, start_serving=True)

     与 *note loop.create_server(): 366. 类似但是专用于 *note AF_UNIX:
     25be. 套接字族。

     `path' 是必要的 Unix 域套接字名称，除非提供了 `sock' 参数。 抽象的
     Unix 套接字, *note str: 339, *note bytes: 33a. 和 *note Path: 202.
     路径都是受支持的。

     请查看 *note loop.create_server(): 366. 方法的文档了解有关此方法的
     参数的信息。

     *note 可用性: 136f.: Unix。

     3.7 新版功能: The `ssl_handshake_timeout' and `start_serving'
     parameters.

     在 3.7 版更改: `path' 形参现在可以是 *note Path: 202. 对象。

 -- 方法: coroutine loop.connect_accepted_socket (protocol_factory,
          sock, *, ssl=None, ssl_handshake_timeout=None)

     将已被接受的连接包装成一个传输/协议对。

     此方法可被服务器用来接受 asyncio 以外的连接，但是使用 asyncio 来处
     理它们。

     参数：

        * `protocol_factory' 必须为一个返回 *note 协议: 25ba. 实现的可调
          用对象。

        * `sock' 是一个预先存在的套接字对象，它是由 *note socket.accept:
          67e. 返回的。

        * `ssl' 可被设置为一个 *note SSLContext: 3ec. 以在接受的连接上启
          用 SSL。

        * `ssl_handshake_timeout' 是(为一个SSL连接)在中止连接前，等待
          SSL握手完成的时间【单位秒】。如果为 ‘None’ (缺省) 则是 ‘60.0’
          秒。

     返回一个 ‘(transport, protocol)’ 对。

     3.7 新版功能: `ssl_handshake_timeout' 形参。

     3.5.3 新版功能.


File: python.info,  Node: 传输文件,  Next: TLS 升级,  Prev: 创建网络服务,  Up: 事件循环方法集

5.18.1.50 传输文件
..................

 -- 方法: coroutine loop.sendfile (transport, file, offset=0,
          count=None, *, fallback=True)

     将 `file' 通过 `transport' 发送。 返回所发送的字节总数。

     如果可用的话，该方法将使用高性能的 *note os.sendfile(): 362.。

     `file' 必须是个二进制模式打开的常规文件对象。

     `offset' 指明从何处开始读取文件。 如果指定了 `count'，它是要传输的
     字节总数而不再一直发送文件直至抵达 EOF。 文件位置总是会被更新，即使
     此方法引发了错误，并可以使用 *note file.tell(): 1da8. 来获取实际发
     送的字节总数。

     `fallback' 设为 ‘True’ 会使得 asyncio 在平台不支持 sendfile 系统调
     用时手动读取并发送文件（例如 Windows 或 Unix 上的 SSL 套接字）。

     如果系统不支持 `sendfile' 系统调用且 `fallback' 为 ‘False’ 则会引发
     *note SendfileNotAvailableError: 259e.。

     3.7 新版功能.


File: python.info,  Node: TLS 升级,  Next: 监控文件描述符,  Prev: 传输文件,  Up: 事件循环方法集

5.18.1.51 TLS 升级
..................

 -- 方法: coroutine loop.start_tls (transport, protocol, sslcontext, *,
          server_side=False, server_hostname=None,
          ssl_handshake_timeout=None)

     将现有基于传输的连接升级到 TLS。

     返回一个新的传输实例，其中 `protocol' 必须在 `await' 之后立即开始使
     用。 传给 `start_tls' 方法的 `transport' 实例应永远不会被再次使用。

     参数：

        * `transport' 和 `protocol' 实例的方法与 *note create_server():
          366. 和 *note create_connection(): 1b3. 所返回的类似。

        * `sslcontext' ：一个已经配置好的 *note SSLContext: 3ec. 实例。

        * 当服务端连接已升级时 (如 *note create_server(): 366. 所创建的
          对象) `server_side' 会传入 ‘True’。

        * `server_hostname' ：设置或者覆盖目标服务器证书中相对应的主机名
          。

        * `ssl_handshake_timeout' 是（用于 TLS 连接的）在放弃连接之前要
          等待 TLS 握手完成的秒数。 如果参数为 ‘None’ 则使用 (默认的)
          ‘60.0’。

     3.7 新版功能.


File: python.info,  Node: 监控文件描述符,  Next: 直接使用 socket 对象,  Prev: TLS 升级,  Up: 事件循环方法集

5.18.1.52 监控文件描述符
........................

 -- 方法: loop.add_reader (fd, callback, *args)

     开始监视 `fd' 文件描述符以获取读取的可用性，一旦 `fd' 可用于读取，
     使用指定的参数调用 `callback' 。

 -- 方法: loop.remove_reader (fd)

     停止对文件描述符 `fd' 读取可用性的监视。

 -- 方法: loop.add_writer (fd, callback, *args)

     开始监视 `fd' 文件描述符的写入可用性，一旦 `fd' 可用于写入，使用指
     定的参数调用 `callback' 。

     使用 *note functools.partial(): 7d1. *note 传递关键字参数: 25b2. 给
     `callback'.

 -- 方法: loop.remove_writer (fd)

     停止对文件描述符 `fd' 的写入可用性监视。

另请查看 *note 平台支持: 25c9. 一节了解以上方法的某些限制。


File: python.info,  Node: 直接使用 socket 对象,  Next: DNS,  Prev: 监控文件描述符,  Up: 事件循环方法集

5.18.1.53 直接使用 socket 对象
..............................

通常，使用基于传输的 API 的协议实现，例如 *note
loop.create_connection(): 1b3. 和 *note loop.create_server(): 366. 比直
接使用套接字的实现更快。 但是，在某些应用场景下性能并不非常重要，直接使
用 *note socket: 67d. 对象会更方便。

 -- 方法: coroutine loop.sock_recv (sock, nbytes)

     从 `sock' 接收至多 `nbytes'。 *note socket.recv(): 680. 的异步版本
     。

     返回接收到的数据【bytes对象类型】。

     `sock' 必须是个非阻塞socket。

     在 3.7 版更改: 虽然这个方法总是被记录为协程方法，但它在 Python 3.7
     之前的发行版中会返回一个 *note Future: 44b.。 从 Python 3.7 开始它
     则是一个 ‘async def’ 方法。

 -- 方法: coroutine loop.sock_recv_into (sock, buf)

     从 `sock' 接收数据放入 `buf' 缓冲区。 模仿了阻塞型的 *note
     socket.recv_into(): cba. 方法。

     返回写入缓冲区的字节数。

     `sock' 必须是个非阻塞socket。

     3.7 新版功能.

 -- 方法: coroutine loop.sock_sendall (sock, data)

     将 `data' 发送到 `sock' 套接字。 *note socket.sendall(): 684. 的异
     步版本。

     此方法会持续发送数据到套接字直至 `data' 中的所有数据发送完毕或是有
     错误发生。 当成功时会返回 ‘None’。 当发生错误时，会引发一个异常。 此
     外，没有办法能确定有多少数据或是否有数据被连接的接收方成功处理。

     `sock' 必须是个非阻塞socket。

     在 3.7 版更改: 虽然这个方法一直被标记为协程方法。但是，Python 3.7 之
     前，该方法返回 *note Future: 44b. ，从Python 3.7 开始，这个方法是
     ‘async def’ 方法。

 -- 方法: coroutine loop.sock_connect (sock, address)

     将 `sock' 连接到位于 `address' 的远程套接字。

     *note socket.connect(): 67f. 的异步版本。

     `sock' 必须是个非阻塞socket。

     在 3.5.2 版更改: ‘address’ 不再需要被解析。 ‘sock_connect’ 将尝试检
     查 `address' 是否已通过调用 *note socket.inet_pton(): 2f9. 被解析。
     如果没有，则将使用 *note loop.getaddrinfo(): 4a9. 来解析 `address'。

     参见
     ....

     *note loop.create_connection(): 1b3. 和 *note
     asyncio.open_connection(): 36c. 。

 -- 方法: coroutine loop.sock_accept (sock)

     接受一个连接。 模仿了阻塞型的 *note socket.accept(): 67e. 方法。

     此 `scoket' 必须绑定到一个地址上并且监听连接。返回值是一个 ‘(conn,
     address)’ 对，其中 `conn' 是一个 `新*的套接字对象，用于在此连接上收
     发数据，*address' 是连接的另一端的套接字所绑定的地址。

     `sock' 必须是个非阻塞socket。

     在 3.7 版更改: 虽然这个方法一直被标记为协程方法。但是，Python 3.7 之
     前，该方法返回 *note Future: 44b. ，从Python 3.7 开始，这个方法是
     ‘async def’ 方法。

     参见
     ....

     *note loop.create_server(): 366. 和 *note start_server(): 36d.。

 -- 方法: coroutine loop.sock_sendfile (sock, file, offset=0,
          count=None, *, fallback=True)

     在可能的情况下使用高性能的 *note os.sendfile: 362. 发送文件。 返回
     所发送的字节总数。

     *note socket.sendfile(): 753. 的异步版本。

     `sock' 必须为非阻塞型的 *note socket.SOCK_STREAM: c92. *note
     socket: 67d.。

     `file' 必须是个用二进制方式打开的常规文件对象。

     `offset' 指明从何处开始读取文件。 如果指定了 `count'，它是要传输的
     字节总数而不再一直发送文件直至抵达 EOF。 文件位置总是会被更新，即使
     此方法引发了错误，并可以使用 *note file.tell(): 1da8. 来获取实际发
     送的字节总数。

     当 `fallback' 被设为 ‘True’ 时，会使用 asyncio 在平台不支持
     sendfile 系统调用时手动读取并发送文件（例如 Windows 或 Unix 上的
     SSL 套接字）。

     如果系统不支持 `sendfile' 并且 `fallback' 为 ‘False’ ，引发 *note
     SendfileNotAvailableError: 259e. 异常。

     `sock' 必须是个非阻塞socket。

     3.7 新版功能.


File: python.info,  Node: DNS,  Next: 使用管道,  Prev: 直接使用 socket 对象,  Up: 事件循环方法集

5.18.1.54 DNS
.............

 -- 方法: coroutine loop.getaddrinfo (host, port, *, family=0, type=0,
          proto=0, flags=0)

     异步版的 *note socket.getaddrinfo(): 25cc. 。

 -- 方法: coroutine loop.getnameinfo (sockaddr, flags=0)

     异步版的 *note socket.getnameinfo(): 25cd. 。

在 3.7 版更改: `getaddrinfo' 和 `getnameinfo' 方法一直被标记返回一个协程
，但是Python 3.7之前，实际返回的是 *note asyncio.Future: 44b. 对象。从
Python 3.7 开始，这两个方法是协程。


File: python.info,  Node: 使用管道,  Next: Unix 信号,  Prev: DNS,  Up: 事件循环方法集

5.18.1.55 使用管道
..................

 -- 方法: coroutine loop.connect_read_pipe (protocol_factory, pipe)

     在事件循环中注册 `pipe' 的读取端。

     `protocol_factory' 必须为一个返回 *note asyncio 协议: 25ba. 实现的
     可调用对象。

     `pipe' 是个 *note 类似文件型对象: b4a.

     返回一对 ‘(transport, protocol)’，其中 `transport' 支持 *note
     ReadTransport: 25cf. 接口而 `protocol' 是由 `protocol_factory' 所实
     例化的对象。

     使用 *note SelectorEventLoop: 2582. 事件循环， `pipe' 被设置为非阻
     塞模式。

 -- 方法: coroutine loop.connect_write_pipe (protocol_factory, pipe)

     在事件循环中注册 `pipe' 的写入端。

     `protocol_factory' 必须为一个返回 *note asyncio 协议: 25ba. 实现的
     可调用对象。

     `pipe' 是个 *note 类似文件型对象: b4a.

     返回一对 ‘(transport, protocol)’，其中 `transport' 支持 *note
     WriteTransport: 25d0. 接口而 `protocol' 是由 `protocol_factory' 所
     实例化的对象。

     使用 *note SelectorEventLoop: 2582. 事件循环， `pipe' 被设置为非阻
     塞模式。

     注解: 在 Windows 中 *note SelectorEventLoop: 2582. 不支持上述方法。
     对于 Windows 请改用 *note ProactorEventLoop: 1ac.。

参见
....

*note loop.subprocess_exec(): 24fc. 和 *note loop.subprocess_shell():
256a. 方法。


File: python.info,  Node: Unix 信号,  Next: 在线程或者进程池中执行代码。,  Prev: 使用管道,  Up: 事件循环方法集

5.18.1.56 Unix 信号
...................

 -- 方法: loop.add_signal_handler (signum, callback, *args)

     设置 `callback' 作为 `signum' 信号的处理程序。

     此回调将与该事件循环中其他加入队列的回调和可运行协程一起由 `loop' 发
     起调用。 不同与使用 *note signal.signal(): a85. 注册的信号处理程序
     ，使用此函数注册的回调可以与事件循环进行交互。

     如果信号数字非法或者不可捕获，就抛出一个 *note ValueError: 1fc. 。
     如果建立处理器的过程中出现问题，会抛出一个 *note RuntimeError: 2bb.
     。

     使用 *note functools.partial(): 7d1. *note 传递关键字参数: 25b2. 给
     `callback'.

     和 *note signal.signal(): a85. 一样，这个函数只能在主线程中调用。

 -- 方法: loop.remove_signal_handler (sig)

     移除 `sig' 信号的处理程序。

     如果信号处理程序被移除则返回 ‘True’，否则如果给定信号未设置处理程序
     则返回 ‘False’。

     *note 可用性: 136f.: Unix。

参见
....

*note signal: eb. 模块。


File: python.info,  Node: 在线程或者进程池中执行代码。,  Next: 错误处理API,  Prev: Unix 信号,  Up: 事件循环方法集

5.18.1.57 在线程或者进程池中执行代码。
......................................

 -- 方法: awaitable loop.run_in_executor (executor, func, *args)

     安排在指定的执行器中调用 `func' 。

     The `executor' argument should be an *note
     concurrent.futures.Executor: 2444. instance.  The default executor
     is used if `executor' is ‘None’.

     示例:

          import asyncio
          import concurrent.futures

          def blocking_io():
              # File operations (such as logging) can block the
              # event loop: run them in a thread pool.
              with open('/dev/urandom', 'rb') as f:
                  return f.read(100)

          def cpu_bound():
              # CPU-bound operations will block the event loop:
              # in general it is preferable to run them in a
              # process pool.
              return sum(i * i for i in range(10 ** 7))

          async def main():
              loop = asyncio.get_running_loop()

              ## Options:

              # 1. Run in the default loop's executor:
              result = await loop.run_in_executor(
                  None, blocking_io)
              print('default thread pool', result)

              # 2. Run in a custom thread pool:
              with concurrent.futures.ThreadPoolExecutor() as pool:
                  result = await loop.run_in_executor(
                      pool, blocking_io)
                  print('custom thread pool', result)

              # 3. Run in a custom process pool:
              with concurrent.futures.ProcessPoolExecutor() as pool:
                  result = await loop.run_in_executor(
                      pool, cpu_bound)
                  print('custom process pool', result)

          asyncio.run(main())

     这个方法返回一个 *note asyncio.Future: 44b. 对象。

     使用 *note functools.partial(): 7d1. *note 传递关键字参数: 25b2. 给
     `func' 。

     在 3.5.3 版更改: *note loop.run_in_executor(): 2506. 不会再配置它所
     创建的线程池执行器的 ‘max_workers’，而是将其留给线程池执行器 (*note
     ThreadPoolExecutor: 27b.) 来设置默认值。

 -- 方法: loop.set_default_executor (executor)

     将 `executor' 设为 *note run_in_executor(): 2506. 所使用的默认执行
     器。 `executor' 应当是 *note ThreadPoolExecutor: 27b. 的实例。

     3.8 版后已移除: 使用不是Using an executor that is not an instance
     of *note ThreadPoolExecutor: 27b. 实例的执行器的做法已被弃用并将在
     Python 3.9 中引起错误。

     `executor' 必须是个 *note concurrent.futures.ThreadPoolExecutor:
     27b. 的实例。


File: python.info,  Node: 错误处理API,  Next: 开启调试模式,  Prev: 在线程或者进程池中执行代码。,  Up: 事件循环方法集

5.18.1.58 错误处理API
.....................

允许自定义事件循环中如何去处理异常。

 -- 方法: loop.set_exception_handler (handler)

     将 `handler' 设置为新的事件循环异常处理器。

     如果 `handler' 为 ‘None’，将设置默认的异常处理程序。 在其他情况下，
     `handler' 必须是一个可调用对象且签名匹配 ‘(loop, context)’，其中
     ‘loop’ 是对活动事件循环的引用，而 ‘context’ 是一个包含异常详情的
     ‘dict’ (请查看 *note call_exception_handler(): 25d6. 文档来获取关于
     上下文的更多信息)。

 -- 方法: loop.get_exception_handler ()

     返回当前的异常处理器，如果没有设置异常处理器，则返回 ‘None’ 。

     3.5.2 新版功能.

 -- 方法: loop.default_exception_handler (context)

     默认的异常处理器。

     此方法会在发生异常且未设置异常处理程序时被调用。 此方法也可以由想要
     具有不同于默认处理程序的行为的自定义异常处理程序来调用。

     `context' 参数和 *note call_exception_handler(): 25d6. 中的同名参数
     完全相同。

 -- 方法: loop.call_exception_handler (context)

     调用当前事件循环的异常处理器。

     `context' 是个包含下列键的 ‘dict’ 对象(未来版本的Python可能会引入新
     键)：

        * ’message’: 错误消息；

        * ’exception’ （可选）: 异常对象；

        * ’future’ （可选）: *note asyncio.Future: 44b. 实例；

        * ’handle’ （可选）: *note asyncio.Handle: 10b2. 实例；

        * ’protocol’ （可选）: *note Protocol: 25ba. 实例；

        * ’transport’ （可选）: *note Transport: 25bb. 实例；

        * ’socket’ （可选）： *note socket.socket: 67d. 实例。

          注解: 此方法不应在子类化的事件循环中被重载。 对于自定义的异常
          处理，请使用 *note set_exception_handler(): 25d5. 方法。


File: python.info,  Node: 开启调试模式,  Next: 运行子进程,  Prev: 错误处理API,  Up: 事件循环方法集

5.18.1.59 开启调试模式
......................

 -- 方法: loop.get_debug ()

     获取事件循环调试模式设置（*note bool: 184.）。

     如果环境变量 *note PYTHONASYNCIODEBUG: 136c. 是一个非空字符串，就返
     回 ‘True’ ，否则就返回 ‘False’ 。

 -- 方法: loop.set_debug (enabled: bool)

     设置事件循环的调试模式。

     在 3.7 版更改: The new ‘-X dev’ command line option can now also be
     used to enable the debug mode.

参见
....

*note debug mode of asyncio: 1360.


File: python.info,  Node: 运行子进程,  Prev: 开启调试模式,  Up: 事件循环方法集

5.18.1.60 运行子进程
....................

本小节所描述的方法都是低层级的。 在常规 async/await 代码中请考虑改用高层
级的 *note asyncio.create_subprocess_shell(): 293. 和 *note
asyncio.create_subprocess_exec(): 292. 便捷函数。

     注解: 在 `Windows' 中默认的 asyncio 事件循环不支持子进程。 详情参见
     *note Windows 上的子进程支持: 256b.。

 -- 方法: coroutine loop.subprocess_exec (protocol_factory, *args,
          stdin=subprocess.PIPE, stdout=subprocess.PIPE,
          stderr=subprocess.PIPE, **kwargs)

     用 `args' 指定的一个或者多个字符串型参数创建一个子进程。

     `args' 必须是个由下列形式的字符串组成的列表：

        * *note str: 339.;

        * 或者由 *note 文件系统编码格式: 1ef1. 编码的 *note bytes: 33a.。

     第一个字符串指定可执行程序，其余的字符串指定其参数。 所有字符串参数
     共同组成了程序的 ‘argv’。

     此方法类似于调用标准库 *note subprocess.Popen: 2ba. 类，设置
     ‘shell=False’ 并将字符串列表作为第一个参数传入；但是，*note Popen:
     2ba. 只接受一个单独的字符串列表参数，而 `subprocess_exec' 接受多个
     字符串参数。

     `protocol_factory' 必须为一个返回 *note asyncio.SubprocessProtocol:
     25da. 类的子类的可调用对象。

     其他参数：

        * `stdin' 可以是以下对象之一:

             * 一个代表要使用 *note connect_write_pipe(): 256d. 连接到子
               进程的标准输入流的管道的文件类对象。

             * *note subprocess.PIPE: 3f6. 常量（默认），将创建并连接一
               个新的管道。

             * ‘None’ 值，这将使得子进程继承来自此进程的文件描述符

             * *note subprocess.DEVNULL: aa8. 常量，这表示将使用特殊的
               *note os.devnull: 102a. 文件

        * `stdout' 可以是以下对象之一:

             * 一个文件类对象，表示要使用 *note connect_write_pipe():
               256d. 连接到子进程的标准输出流的管道

             * *note subprocess.PIPE: 3f6. 常量（默认），将创建并连接一
               个新的管道。

             * ‘None’ 值，这将使得子进程继承来自此进程的文件描述符

             * *note subprocess.DEVNULL: aa8. 常量，这表示将使用特殊的
               *note os.devnull: 102a. 文件

        * `stderr' 可以是以下对象之一:

             * 一个文件类对象，表示要使用 *note connect_write_pipe():
               256d. 连接到子进程的标准错误流的管道

             * *note subprocess.PIPE: 3f6. 常量（默认），将创建并连接一
               个新的管道。

             * ‘None’ 值，这将使得子进程继承来自此进程的文件描述符

             * *note subprocess.DEVNULL: aa8. 常量，这表示将使用特殊的
               *note os.devnull: 102a. 文件

             * *note subprocess.STDOUT: 2469. 常量，将把标准错误流连接到
               进程的标准输出流

        * 所有其他关键字参数会被不加解释地传给 *note subprocess.Popen:
          2ba.，除了 `bufsize', `universal_newlines', `shell', `text',
          `encoding' 和 `errors'，它们都不应当被指定。

          ‘asyncio’ 子进程 API 不支持将流解码为文本。 可以使用 *note
          bytes.decode(): c40. 来将从流返回的字节串转换为文本。

     其他参数的文档，请参阅 *note subprocess.Popen: 2ba. 类的构造函数。

     返回一对 ‘(transport, protocol)’，其中 `transport' 来自 *note
     asyncio.SubprocessTransport: 25db. 基类而 `protocol' 是由
     `protocol_factory' 所实例化的对象。

 -- 方法: coroutine loop.subprocess_shell (protocol_factory, cmd, *,
          stdin=subprocess.PIPE, stdout=subprocess.PIPE,
          stderr=subprocess.PIPE, **kwargs)

     基于 `cmd' 创建一个子进程，该参数可以是一个 *note str: 339. 或者按
     *note 文件系统编码格式: 1ef1. 编码得到的 *note bytes: 33a. ，使用平
     台的 "shell" 语法。

     这类似与用 ‘shell=True’ 调用标准库的 *note subprocess.Popen: 2ba. 类
     。

     `protocol_factory' 必须为一个返回 *note SubprocessProtocol: 25da. 类
     的子类的可调用对象。

     请参阅 *note subprocess_exec(): 24fc. 了解有关其余参数的详情。

     返回一对 ‘(transport, protocol)’，其中 `transport' 来自 *note
     SubprocessTransport: 25db. 基类而 `protocol' 是由
     `protocol_factory' 所实例化的对象。

     注解: 应用程序要负责确保正确地转义所有空白字符和特殊字符以防止
     shell 注入(1) 漏洞。 *note shlex.quote(): a7b. 函数可以被用来正确地
     转义字符串中可能被用来构造 shell 命令的空白字符和特殊字符。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Shell_injection#Shell_injection


File: python.info,  Node: 回调处理,  Next: Server 对象,  Prev: 事件循环方法集,  Up: 事件循环

5.18.1.61 回调处理
..................

 -- 类: asyncio.Handle

     由 *note loop.call_soon(): 352, *note loop.call_soon_threadsafe():
     353. 所返回的回调包装器对象。

      -- 方法: cancel ()

          取消回调。 如果此回调已被取消或已被执行，此方法将没有任何效果
          。

      -- 方法: cancelled ()

          如果此回调已被取消则返回 ‘True’。

          3.7 新版功能.

 -- 类: asyncio.TimerHandle

     由 *note loop.call_later(): 354. 和 *note loop.call_at(): 355. 所返
     回的回调包装器对象。

     这个类是 *note Handle: 10b2. 的子类。

      -- 方法: when ()

          返回加入计划任务的回调时间，以 *note float: 188. 值表示的秒数
          。

          时间值是一个绝对时间戳，使用与 *note loop.time(): 25b5. 相同的
          时间引用。

          3.7 新版功能.


File: python.info,  Node: Server 对象,  Next: 事件循环实现,  Prev: 回调处理,  Up: 事件循环

5.18.1.62 Server 对象
.....................

Server 对象可使用 *note loop.create_server(): 366, *note
loop.create_unix_server(): 367, *note start_server(): 36d. 和 *note
start_unix_server(): 252f. 等函数来创建。

请不要直接实例化该类。

 -- 类: asyncio.Server

     `Server' 对象是异步上下文管理器。当用于 ‘async with’ 语句时，异步上
     下文管理器可以确保 Server 对象被关闭，并且在 ‘async with’ 语句完成
     后，不接受新的连接。

          srv = await loop.create_server(...)

          async with srv:
              # some code

          # At this point, srv is closed and no longer accepts new connections.

     在 3.7 版更改: Python3.7 开始，Server 对象是一个异步上下文管理器。

      -- 方法: close ()

          停止服务：关闭监听的套接字并且设置 *note sockets: 4ab. 属性为
          ‘None’ 。

          用于表示已经连进来的客户端连接会保持打开的状态。

          服务器是被异步关闭的，使用 *note wait_closed(): 25de. 协程来等
          待服务器关闭。

      -- 方法: get_loop ()

          返回与服务器对象相关联的事件循环。

          3.7 新版功能.

      -- 方法: coroutine start_serving ()

          开始接受连接。

          这个方法是幂等的【相同参数重复执行，能获得相同的结果】，所以此
          方法能在服务已经运行的时候调用。

          传给 *note loop.create_server(): 366. 和 *note
          asyncio.start_server(): 36d. 的 `start_serving' 仅限关键字形参
          允许创建不接受初始连接的 Server 对象。 在此情况下可以使用
          ‘Server.start_serving()’ 或 *note Server.serve_forever(): 369.
          让 Server 对象开始接受连接。

          3.7 新版功能.

      -- 方法: coroutine serve_forever ()

          开始接受连接，直到协程被取消。 ‘serve_forever’ 任务的取消将导
          致服务器被关闭。

          如果服务器已经在接受连接了，这个方法可以被调用。每个 `Server'
          对象，仅能有一个 ‘serve_forever’ 任务。

          示例:

               async def client_connected(reader, writer):
                   # Communicate with the client with
                   # reader/writer streams.  For example:
                   await reader.readline()

               async def main(host, port):
                   srv = await asyncio.start_server(
                       client_connected, host, port)
                   await srv.serve_forever()

               asyncio.run(main('127.0.0.1', 0))

          3.7 新版功能.

      -- 方法: is_serving ()

          如果服务器正在接受新连接的状态，返回 ‘True’ 。

          3.7 新版功能.

      -- 方法: coroutine wait_closed ()

          等待 *note close(): 25dd. 方法执行完毕。

      -- 属性: sockets

          服务器监听的 *note socket.socket: 67d. 对象列表。

          在 3.7 版更改: 在 Python 3.7 之前 ‘Server.sockets’ 会直接返回
          内部的服务器套接字列表。 在 3.7 版则会返回该列表的副本。


File: python.info,  Node: 事件循环实现,  Next: 例子<14>,  Prev: Server 对象,  Up: 事件循环

5.18.1.63 事件循环实现
......................

asyncio 带有两种不同的事件循环实现: *note SelectorEventLoop: 2582. 和
*note ProactorEventLoop: 1ac.。

默认情况下 asyncio 被配置为在 Unix 上使用 *note SelectorEventLoop: 2582.
而在 Windows 上使用 *note ProactorEventLoop: 1ac.。

 -- 类: asyncio.SelectorEventLoop

     基于 *note selectors: e7. 模块的事件循环。

     使用给定平台中最高效的可用 `selector'。 也可以手动配置要使用的特定
     selector:

          import asyncio
          import selectors

          selector = selectors.SelectSelector()
          loop = asyncio.SelectorEventLoop(selector)
          asyncio.set_event_loop(loop)

     *note 可用性: 136f.: Unix, Windows。

 -- 类: asyncio.ProactorEventLoop

     用 "I/O Completion Ports" (IOCP) 构建的专为Windows 的事件循环。

     *note 可用性: 136f.: Windows。

     参见
     ....

     有关 I/O 完成端口的 MSDN 文档(1)。

 -- 类: asyncio.AbstractEventLoop

     asyncio 兼容事件循环的抽象基类。

     *note 事件循环方法: 64d. 一节列出了 ‘AbstractEventLoop’ 的替代实现
     应当定义的所有方法。

   ---------- Footnotes ----------

   (1) 
https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports


File: python.info,  Node: 例子<14>,  Prev: 事件循环实现,  Up: 事件循环

5.18.1.64 例子
..............

请注意本节中的所有示例都 `有意地' 演示了如何使用低层级的事件循环 API，例
如 *note loop.run_forever(): 25ad. 和 *note loop.call_soon(): 352.。 现
代的 asyncio 应用很少需要以这样的方式编写；请考虑使用高层级的函数例如
*note asyncio.run(): 1a6.。

* Menu:

* call_soon() 的 Hello World 示例。: call_soon 的 Hello World 示例。.
* 使用 call_later() 来展示当前的日期: 使用 call_later 来展示当前的日期.
* 监控一个文件描述符的读事件::
* 为SIGINT和SIGTERM设置信号处理器::


File: python.info,  Node: call_soon 的 Hello World 示例。,  Next: 使用 call_later 来展示当前的日期,  Up: 例子<14>

5.18.1.65 call_soon() 的 Hello World 示例。
...........................................

一个使用 *note loop.call_soon(): 352. 方法来安排回调的示例。 回调会显示
‘"Hello World"’ 然后停止事件循环:

     import asyncio

     def hello_world(loop):
         """A callback to print 'Hello World' and stop the event loop"""
         print('Hello World')
         loop.stop()

     loop = asyncio.get_event_loop()

     # Schedule a call to hello_world()
     loop.call_soon(hello_world, loop)

     # Blocking call interrupted by loop.stop()
     try:
         loop.run_forever()
     finally:
         loop.close()

参见
....

一个类似的 *note Hello World: 24f7. 示例，使用协程和 *note run(): 1a6. 函
数创建。


File: python.info,  Node: 使用 call_later 来展示当前的日期,  Next: 监控一个文件描述符的读事件,  Prev: call_soon 的 Hello World 示例。,  Up: 例子<14>

5.18.1.66 使用 call_later() 来展示当前的日期
............................................

一个每秒刷新显示当前日期的示例。 回调使用 *note loop.call_later(): 354.
方法在 5 秒后将自身重新加入计划日程，然后停止事件循环:

     import asyncio
     import datetime

     def display_date(end_time, loop):
         print(datetime.datetime.now())
         if (loop.time() + 1.0) < end_time:
             loop.call_later(1, display_date, end_time, loop)
         else:
             loop.stop()

     loop = asyncio.get_event_loop()

     # Schedule the first call to display_date()
     end_time = loop.time() + 5.0
     loop.call_soon(display_date, end_time, loop)

     # Blocking call interrupted by loop.stop()
     try:
         loop.run_forever()
     finally:
         loop.close()

参见
....

一个类似的 *note current date: 250a. 示例，使用协程和 *note run(): 1a6.
函数创建。


File: python.info,  Node: 监控一个文件描述符的读事件,  Next: 为SIGINT和SIGTERM设置信号处理器,  Prev: 使用 call_later 来展示当前的日期,  Up: 例子<14>

5.18.1.67 监控一个文件描述符的读事件
....................................

使用 *note loop.add_reader(): 2549. 方法，等到文件描述符收到一些数据，然
后关闭事件循环：

     import asyncio
     from socket import socketpair

     # Create a pair of connected file descriptors
     rsock, wsock = socketpair()

     loop = asyncio.get_event_loop()

     def reader():
         data = rsock.recv(100)
         print("Received:", data.decode())

         # We are done: unregister the file descriptor
         loop.remove_reader(rsock)

         # Stop the event loop
         loop.stop()

     # Register the file descriptor for read event
     loop.add_reader(rsock, reader)

     # Simulate the reception of data from the network
     loop.call_soon(wsock.send, 'abc'.encode())

     try:
         # Run the event loop
         loop.run_forever()
     finally:
         # We are done. Close sockets and the event loop.
         rsock.close()
         wsock.close()
         loop.close()

参见
....

   * 一个类似的 *note 示例: 2548.，使用传输、协议和 *note
     loop.create_connection(): 1b3. 方法创建。

   * 另一个类似的 *note 示例: 2546.，使用了高层级的 *note
     asyncio.open_connection(): 36c. 函数和流。


File: python.info,  Node: 为SIGINT和SIGTERM设置信号处理器,  Prev: 监控一个文件描述符的读事件,  Up: 例子<14>

5.18.1.68 为SIGINT和SIGTERM设置信号处理器
.........................................

（这个 ‘signals’ 示例只适用于 Unix。）

使用 *note loop.add_signal_handler(): 24fd. 方法为信号 ‘SIGINT’ 和
‘SIGTERM’ 注册处理程序:

     import asyncio
     import functools
     import os
     import signal

     def ask_exit(signame, loop):
         print("got signal %s: exit" % signame)
         loop.stop()

     async def main():
         loop = asyncio.get_running_loop()

         for signame in {'SIGINT', 'SIGTERM'}:
             loop.add_signal_handler(
                 getattr(signal, signame),
                 functools.partial(ask_exit, signame, loop))

         await asyncio.sleep(3600)

     print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
     print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")

     asyncio.run(main())


File: python.info,  Node: Futures,  Next: 传输和协议,  Prev: 事件循环,  Up: asyncio --- 异步 I/O

5.18.1.69 Futures
.................

`源代码:' Lib/asyncio/futures.py(1), Lib/asyncio/base_futures.py(2)

__________________________________________________________________

`Future' 对象用来链接 `底层回调式代码' 和高层异步/等待式代码。

* Menu:

* Future 函数::
* Future 对象: Future 对象<2>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/asyncio/futures.py

   (2) 
https://github.com/python/cpython/tree/3.8/Lib/asyncio/base_futures.py


File: python.info,  Node: Future 函数,  Next: Future 对象<2>,  Up: Futures

5.18.1.70 Future 函数
.....................

 -- 函数: asyncio.isfuture (obj)

     如果 `obj' 为下面任意对象，返回 ‘True’：

        * 一个 *note asyncio.Future: 44b. 类的实例，

        * 一个 *note asyncio.Task: 1ae. 类的实例，

        * 带有 ‘_asyncio_future_blocking’ 属性的类似 Future 的对象。

     3.5 新版功能.

 -- 函数: asyncio.ensure_future (obj, *, loop=None)

     返回：

        * `obj' 参数会是保持原样，如果 `obj' 是 *note Future: 44b.、
          *note Task: 1ae. 或 类似 Future 的对象( *note isfuture():
          25eb. 用于测试。)

        * 封装了 `obj' 的 *note Task: 1ae. 对象，如果 `obj' 是一个协程
          (使用 *note iscoroutine(): 2527. 进行检测)；在此情况下该协程将
          通过 ‘ensure_future()’ 加入执行计划。

        * 等待 `obj' 的 *note Task: 1ae. 对象，如果 `obj' 是一个可等待对
          象( *note inspect.isawaitable(): 702. 用于测试)

     如果 `obj' 不是上述对象会引发一个 *note TypeError: 193. 异常。

          重要: 查看 *note create_task(): 1af. 函数，它是创建新任务的首
          选途径。

     在 3.5.1 版更改: 这个函数接受任意 *note awaitable: 521. 对象。

 -- 函数: asyncio.wrap_future (future, *, loop=None)

     将一个 *note concurrent.futures.Future: b35. 对象封装到 *note
     asyncio.Future: 44b. 对象中。


File: python.info,  Node: Future 对象<2>,  Prev: Future 函数,  Up: Futures

5.18.1.71 Future 对象
.....................

 -- 类: asyncio.Future (*, loop=None)

     一个 Future 代表一个异步运算的最终结果。线程不安全。

     Future 是一个 *note awaitable: 521. 对象。协程可以等待 Future 对象
     直到它们有结果或异常集合或被取消。

     通常 Future 用于支持底层回调式代码(例如在协议实现中使用asyncio
     *note transports: 24fe.) 与高层异步/等待式代码交互。

     经验告诉我们永远不要面向用户的接口暴露 Future 对象，同时建议使用
     *note loop.create_future(): 524. 来创建 Future 对象。这种方法可以让
     Future 对象使用其它的事件循环实现，它可以注入自己的优化实现。

     在 3.7 版更改: 加入对 *note contextvars: 25. 模块的支持。

      -- 方法: result ()

          返回 Future 的结果。

          如果 Future 状态为 `完成' ，并由 *note set_result(): 2519. 方
          法设置一个结果，则返回这个结果。

          如果 Future 状态为 `完成' ，并由 *note set_exception(): 251a.
          方法设置一个异常，那么这个方法会引发异常。

          如果 Future 已 `取消'，方法会引发一个 *note CancelledError:
          1a8. 异常。

          如果 Future 的结果还不可用，此方法会引发一个 *note
          InvalidStateError: 251f. 异常。

      -- 方法: set_result (result)

          将 Future 标记为 `完成' 并设置结果。

          如果 Future 已经 `完成' 则抛出一个 *note InvalidStateError:
          251f. 错误。

      -- 方法: set_exception (exception)

          将 Future 标记为 `完成' 并设置一个异常。

          如果 Future 已经 `完成' 则抛出一个 *note InvalidStateError:
          251f. 错误。

      -- 方法: done ()

          如果 Future 为已 `完成' 则返回 ‘True’ 。

          如果 Future 为 `取消' 或调用 *note set_result(): 2519. 设置了
          结果或调用 *note set_exception(): 251a. 设置了异常，那么它就是
          `完成' 。

      -- 方法: cancelled ()

          如果 Future 已 `取消' 则返回 ‘True’

          这个方法通常在设置结果或异常前用来检查 Future 是否已 `取消' 。

               if not fut.cancelled():
                   fut.set_result(42)

      -- 方法: add_done_callback (callback, *, context=None)

          添加一个在 Future `完成' 时运行的回调函数。

          调用 `callback' 时，Future 对象是它的唯一参数。

          调用这个方法时 Future 已经 `完成' , 回调函数已被 *note
          loop.call_soon(): 352. 调度。

          可选键值类的参数 `context' 允许 `callback' 运行在一个指定的自
          定义 *note contextvars.Context: 24cb. 对象中。如果没有提供
          `context' ，则使用当前上下文。

          可以用 *note functools.partial(): 7d1. 给回调函数传递参数，例
          如:

               # Call 'print("Future:", fut)' when "fut" is done.
               fut.add_done_callback(
                   functools.partial(print, "Future:"))

          在 3.7 版更改: 加入键值类形参 `context'。请参阅 PEP 567(1) 查
          看更多细节。

      -- 方法: remove_done_callback (callback)

          从回调列表中移除 `callback' 。

          返回被移除的回调函数的数量，通常为1，除非一个回调函数被添加多
          次。

      -- 方法: cancel ()

          取消 Future 并调度回调函数。

          如果 Future 已经 `完成' 或 `取消' ，返回 ‘False’ 。否则将
          Future 状态改为 `取消' 并在调度回调函数后返回 ‘True’ 。

      -- 方法: exception ()

          返回 Future 已设置的异常。

          只有 Future 在 `完成' 时才返回异常（或者 ‘None’ ，如果没有设置
          异常）。

          如果 Future 已 `取消'，方法会引发一个 *note CancelledError:
          1a8. 异常。

          如果 Future 还没 `完成' ，这个方法会引发一个 *note
          InvalidStateError: 251f. 异常。

      -- 方法: get_loop ()

          返回 Future 对象已绑定的事件循环。

          3.7 新版功能.

这个例子创建一个 Future 对象，创建和调度一个异步任务去设置 Future 结果，
然后等待其结果:

     async def set_after(fut, delay, value):
         # Sleep for *delay* seconds.
         await asyncio.sleep(delay)

         # Set *value* as a result of *fut* Future.
         fut.set_result(value)

     async def main():
         # Get the current event loop.
         loop = asyncio.get_running_loop()

         # Create a new Future object.
         fut = loop.create_future()

         # Run "set_after()" coroutine in a parallel Task.
         # We are using the low-level "loop.create_task()" API here because
         # we already have a reference to the event loop at hand.
         # Otherwise we could have just used "asyncio.create_task()".
         loop.create_task(
             set_after(fut, 1, '... world'))

         print('hello ...')

         # Wait until *fut* has a result (1 second) and print it.
         print(await fut)

     asyncio.run(main())

     重要: 该 Future 对象是为了模仿 *note concurrent.futures.Future:
     b35. 类。主要差异包含：

        - 与 asyncio 的 Future 不同，*note concurrent.futures.Future:
          b35. 实例不是可等待对象。

        - *note asyncio.Future.result(): 25ee. 和 *note
          asyncio.Future.exception(): 25f1. 不接受 `timeout' 参数。

        - Future 没有 `完成' 时 *note asyncio.Future.result(): 25ee. 和
          *note asyncio.Future.exception(): 25f1. 抛出一个 *note
          InvalidStateError: 251f. 异常。

        - 使用 *note asyncio.Future.add_done_callback(): 356. 注册的回调
          函数不会立即调用，而是被 *note loop.call_soon(): 352. 调度。

        - asyncio Future 不能兼容 *note concurrent.futures.wait(): 2456.
          和 *note concurrent.futures.as_completed(): 10fe. 函数。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0567


File: python.info,  Node: 传输和协议,  Next: 策略,  Prev: Futures,  Up: asyncio --- 异步 I/O

5.18.1.72 传输和协议
....................

前言
....

传输和协议会被像 *note loop.create_connection(): 1b3. 这类 `底层' 事件循
环接口使用。它们使用基于回调的编程风格支持网络或IPC协议（如HTTP）的高性
能实现。

基本上，传输和协议应只在库和框架上使用，而不应该在高层的异步应用中使用它
们。

本文档包含 *note Transports: 25f5. 和 *note Protocols: 25f6. 。

概述
....

在最顶层，传输只关心 `怎样' 传送字节内容，而协议决定传送 `哪些' 字节内容
(还要在一定程度上考虑何时)。

也可以这样说：从传输的角度来看，传输是套接字(或类似的I/O终端)的抽象，而
协议是应用程序的抽象。

换另一种说法，传输和协议一起定义网络I/0和进程间I/O的抽象接口。

传输对象和协议对象总是一对一关系：协议调用传输方法来发送数据，而传输在接
收到数据时调用协议方法传递数据。

大部分面向连接的事件循环方法(如 *note loop.create_connection(): 1b3. ) 通
常接受 `protocol_factory' 参数为接收到的链接创建 `协议' 对象，并用 `传输
' 对象来表示。这些方法一般会返回 ‘(transport, protocol)’ 元组。

目录
....

本文档包含下列小节:

   * *note 传输: 25f5. 部分记载异步IO *note BaseTransport: 25f7. 、
     *note ReadTransport: 25cf. 、 *note WriteTransport: 25d0. 、 *note
     Transport: 25f8. 、 *note DatagramTransport: 25f9. 和 *note
     SubprocessTransport: 25db. 等类。

   * The *note Protocols: 25f6. section documents asyncio *note
     BaseProtocol: 25fa, *note Protocol: 25fb, *note BufferedProtocol:
     2ca, *note DatagramProtocol: 25fc, and *note SubprocessProtocol:
     25da. classes.

   * *note 例子: 25fd. 部分展示怎样使用传输、协议和底层事件循环接口。

* Menu:

* 传输::
* 协议::
* 例子: 例子<15>.


File: python.info,  Node: 传输,  Next: 协议,  Up: 传输和协议

5.18.1.73 传输
..............

`源码:' Lib/asyncio/transports.py(1)

__________________________________________________________________

传输属于 *note asyncio: a. 模块中的类，用来抽象各种通信通道。

传输对象总是由 *note 异步IO事件循环: 64d. 实例化。

异步IO实现TCP、UDP、SSL和子进程管道的传输。传输上可用的方法由传输的类型
决定。

传输类属于 *note 线程不安全: 2515. 。

* Menu:

* 传输层级::
* 基础传输::
* 只读传输::
* 只写传输::
* 数据报传输::
* 子进程传输::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/asyncio/transports.py


File: python.info,  Node: 传输层级,  Next: 基础传输,  Up: 传输

5.18.1.74 传输层级
..................

 -- 类: asyncio.BaseTransport

     所有传输的基类。包含所有异步IO传输共用的方法。

 -- 类: asyncio.WriteTransport (BaseTransport)

     只写链接的基础传输。

     Instances of the `WriteTransport' class are returned from the *note
     loop.connect_write_pipe(): 256d. event loop method and are also
     used by subprocess-related methods like *note
     loop.subprocess_exec(): 24fc.

 -- 类: asyncio.ReadTransport (BaseTransport)

     只读链接的基础传输。

     Instances of the `ReadTransport' class are returned from the *note
     loop.connect_read_pipe(): 256c. event loop method and are also used
     by subprocess-related methods like *note loop.subprocess_exec():
     24fc.

 -- 类: asyncio.Transport (WriteTransport, ReadTransport)

     接口代表一个双向传输，如TCP链接。

     用户不用直接实例化传输；调用一个功能函数，给它传递协议工厂和其它需
     要的信息就可以创建传输和协议。

     `传输' 类实例由如 *note loop.create_connection(): 1b3. 、 *note
     loop.create_unix_connection(): 252e. 、 *note loop.create_server():
     366. 、 *note loop.sendfile(): 25c3. 等这类事件循环方法使用或返回。

 -- 类: asyncio.DatagramTransport (BaseTransport)

     数据报(UDP)传输链接。

     `DatagramTransport' 类实例由事件循环方法 *note
     loop.create_datagram_endpoint(): 2e8. 返回。

 -- 类: asyncio.SubprocessTransport (BaseTransport)

     表示父进程和子进程之间连接的抽象。

     `SubprocessTransport' 类的实例由事件循环方法 *note
     loop.subprocess_shell(): 256a. 和 *note loop.subprocess_exec():
     24fc. 返回。


File: python.info,  Node: 基础传输,  Next: 只读传输,  Prev: 传输层级,  Up: 传输

5.18.1.75 基础传输
..................

 -- 方法: BaseTransport.close ()

     关闭传输。

     如果传输具有发送数据缓冲区，将会异步发送已缓存的数据。在所有已缓存
     的数据都已处理后，就会将 *note None: 158. 作为协议 *note
     protocol.connection_lost(): 2601. 方法的参数并进行调用。在这之后，
     传输不再接收任何数据。

 -- 方法: BaseTransport.is_closing ()

     返回 ‘True’ ，如果传输正在关闭或已经关闭。

 -- 方法: BaseTransport.get_extra_info (name, default=None)

     返回 传输或它使用的相关资源信息。

     `name' 是表示要获取传输特定信息的字符串。

     `default' 是在信息不可用或传输不支持第三方事件循环实现或当前平台查
     询时返回的值。

     例如下面代码尝试获取传输相关套接字对象:

          sock = transport.get_extra_info('socket')
          if sock is not None:
              print(sock.getsockopt(...))

     传输可查询信息类别:

        * 套接字:

             - ‘'peername'’: 套接字链接时的远端地址，*note
               socket.socket.getpeername(): 2602. 方法的结果 (出错时为
               ‘None’ )

             - ‘'socket'’: *note socket.socket: 67d. 实例

             - ‘'sockname'’: 套接字本地地址， *note
               socket.socket.getsockname(): 2603. 方法的结果

        * SSL套接字

             - ‘'compression'’: 用字符串指定压缩算法，或者链接没有压缩时
               为 ‘None’ ；*note ssl.SSLSocket.compression(): a9d. 的结
               果。

             - ‘'cipher'’: 一个三值的元组，包含使用密码的名称，定义使用
               的SSL协议的版本，使用的加密位数。 *note
               ssl.SSLSocket.cipher(): 2604. 的结果。

             - ‘'peercert'’: 远端凭证； *note
               ssl.SSLSocket.getpeercert(): 8d9. 结果。

             - ‘'sslcontext'’: *note ssl.SSLContext: 3ec. 实例

             - ‘'ssl_object'’: *note ssl.SSLObject: 3eb. 或 *note
               ssl.SSLSocket: 3ea. 实例

        * 管道：

             - ‘'pipe'’: 管道对象

        * 子进程：

             - ‘'subprocess'’: *note subprocess.Popen: 2ba. 实例

 -- 方法: BaseTransport.set_protocol (protocol)

     设置一个新协议。

     只有两种协议都写明支持切换才能完成切换协议。

 -- 方法: BaseTransport.get_protocol ()

     返回当前协议。


File: python.info,  Node: 只读传输,  Next: 只写传输,  Prev: 基础传输,  Up: 传输

5.18.1.76 只读传输
..................

 -- 方法: ReadTransport.is_reading ()

     如果传输接收到新数据时返回 ‘True’ 。

     3.7 新版功能.

 -- 方法: ReadTransport.pause_reading ()

     暂停传输的接收端。*note protocol.data_received(): 2608. 方法将不会
     收到数据，除非 *note resume_reading(): 371.  被调用。

     在 3.7 版更改: 这个方法幂等的， 它可以在传输已经暂停或关闭时调用。

 -- 方法: ReadTransport.resume_reading ()

     恢复接收端。如果有数据可读取时，协议方法 *note
     protocol.data_received(): 2608. 将再次被调用。

     在 3.7 版更改: 这个方法幂等的， 它可以在传输已经准备好读取数据时调
     用。


File: python.info,  Node: 只写传输,  Next: 数据报传输,  Prev: 只读传输,  Up: 传输

5.18.1.77 只写传输
..................

 -- 方法: WriteTransport.abort ()

     立即关闭传输，不会等待已提交的操作处理完毕。已缓存的数据将会丢失。
     不会接收更多数据。 最终 *note None: 158. 将作为协议的 *note
     protocol.connection_lost(): 2601. 方法的参数被调用。

 -- 方法: WriteTransport.can_write_eof ()

     如果传输支持 *note write_eof(): 260c. 返回 *note True: 4a1. 否则返
     回 *note False: 390. 。

 -- 方法: WriteTransport.get_write_buffer_size ()

     返回传输使用输出缓冲区的当前大小。

 -- 方法: WriteTransport.get_write_buffer_limits ()

     获取写入流控制 `high' 和 `low' 高低标记位。返回元组 ‘(low, high)’ ，
     `low' 和 `high' 为正字节数。

     使用 *note set_write_buffer_limits(): 260e. 设置限制。

     3.4.2 新版功能.

 -- 方法: WriteTransport.set_write_buffer_limits (high=None, low=None)

     设置写入流控制 `high' 和 `low' 高低标记位。

     这两个值（以字节数表示）控制何时调用协议的 *note
     protocol.pause_writing(): 260f. 和 *note protocol.resume_writing():
     2610. 方法。 如果指明，则低水位必须小于或等于高水位。 `high' 和
     `low' 都不能为负值。

     *note pause_writing(): 260f. 会在缓冲区尺寸大于或等于 `high' 值时被
     调用。 如果写入已经被暂停，*note resume_writing(): 2610. 会在缓冲区
     尺寸小于或等于 `low' 值时被调用。

     默认值是实现专属的。 如果只给出了高水位值，则低水位值默认为一个小于
     或等于高水位值的实现传属值。 将 `high' 设为零会强制将 `low' 也设为
     零，并使得 *note pause_writing(): 260f. 在缓冲区变为非空的任何时刻
     被调用。 将 `low' 设为零会使得 *note resume_writing(): 2610. 在缓冲
     区为空时只被调用一次。 对于上下限都使用零值通常是不够优化的，因为它
     减少了并发执行 I/O 和计算的机会。

     可使用 *note get_write_buffer_limits(): 6a5. 来获取上下限值。

 -- 方法: WriteTransport.write (data)

     将一些 `data' 字节串写入传输。

     此方法不会阻塞；它会缓冲数据并安排其被异步地发出。

 -- 方法: WriteTransport.writelines (list_of_data)

     将数据字节串的列表（或任意可迭代对象）写入传输。 这在功能上等价于在
     可迭代对象产生的每个元素上调用 *note write(): 2611.，但其实现可能更
     为高效。

 -- 方法: WriteTransport.write_eof ()

     在刷新所有已缓冲数据之后关闭传输的写入端。 数据仍可以被接收。

     如果传输（例如 SSL）不支持半关闭的连接，此方法会引发 *note
     NotImplementedError: 617.。


File: python.info,  Node: 数据报传输,  Next: 子进程传输,  Prev: 只写传输,  Up: 传输

5.18.1.78 数据报传输
....................

 -- 方法: DatagramTransport.sendto (data, addr=None)

     将 `data' 字节串发送到 `addr' (基于传输的目标地址) 所给定的远端对等
     方。 如果 `addr' 为 *note None: 158.，则将数据发送到传输创建时给定
     的目标地址。

     此方法不会阻塞；它会缓冲数据并安排其被异步地发出。

 -- 方法: DatagramTransport.abort ()

     立即关闭传输，不会等待已提交的操作执行完毕。 已缓存的数据将会丢失。
     不会接收更多的数据。 协议的 *note protocol.connection_lost(): 2601.
     方法最终将附带 *note None: 158. 作为参数被调用。


File: python.info,  Node: 子进程传输,  Prev: 数据报传输,  Up: 传输

5.18.1.79 子进程传输
....................

 -- 方法: SubprocessTransport.get_pid ()

     将子进程的进程 ID 以整数形式返回。

 -- 方法: SubprocessTransport.get_pipe_transport (fd)

     返回对应于整数文件描述符 `fd' 的通信管道的传输:

        * ‘0’: 标准输入 (`stdin') 的可读流式传输，如果子进程创建时未设置
          ‘stdin=PIPE’ 则为 *note None: 158.。

        * ‘1’: 标准输出writable streaming transport of the standard
          output (`stdout') 的可写流式传输，如果子进程创建时未设置
          ‘stdout=PIPE’ 则为 *note None: 158.。

        * ‘2’: 标准错误 (`stderr') 的可写流式传输，如果子进程创建时未设
          置 ‘stderr=PIPE’ 则为 *note None: 158.

        * 其他 `fd': *note None: 158.

 -- 方法: SubprocessTransport.get_returncode ()

     返回整数形式的进程返回码，或者如果还未返回则为 *note None: 158.，这
     类似于 *note subprocess.Popen.returncode: 248a. 属性。

 -- 方法: SubprocessTransport.kill ()

     杀死子进程。

     在 POSIX 系统中，函数会发送 SIGKILL 到子进程。 在 Windows 中，此方
     法是 *note terminate(): 261b. 的别名。

     另请参见 *note subprocess.Popen.kill(): 2490.。

 -- 方法: SubprocessTransport.send_signal (signal)

     发送 `signal' 编号到子进程，与 *note
     subprocess.Popen.send_signal(): 248e. 一样。

 -- 方法: SubprocessTransport.terminate ()

     停止子进程。

     在 POSIX 系统中，此方法会发送 SIGTERM 到子进程。 在 Windows 中，则
     会调用 Windows API 函数 TerminateProcess() 来停止子进程。

     另请参见 *note subprocess.Popen.terminate(): 248f.。

 -- 方法: SubprocessTransport.close ()

     通过调用 *note kill(): 261a. 方法来杀死子进程。

     如果子进程尚未返回，并关闭 `stdin', `stdout' 和 `stderr' 管道的传输
     。


File: python.info,  Node: 协议,  Next: 例子<15>,  Prev: 传输,  Up: 传输和协议

5.18.1.80 协议
..............

`源码:' Lib/asyncio/protocols.py(1)

__________________________________________________________________

asyncio 提供了一组抽象基类，它们应当被用于实现网络协议。 这些类被设计为
与 *note 传输: 25bb. 配合使用。

抽象基础协议类的子类可以实现其中的部分或全部方法。 所有这些方法都是回调
：它们由传输或特定事件调用，例如当数据被接收的时候。 基础协议方法应当由
相应的传输来调用。

* Menu:

* 基础协议::
* 基础协议: 基础协议<2>.
* 流协议::
* 缓冲流协议::
* 数据报协议::
* 子进程协议::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/asyncio/protocols.py


File: python.info,  Node: 基础协议,  Next: 基础协议<2>,  Up: 协议

5.18.1.81 基础协议
..................

 -- 类: asyncio.BaseProtocol

     带有所有协议的共享方法的基础协议。

 -- 类: asyncio.Protocol (BaseProtocol)

     用于实现流式协议（TCP, Unix 套接字等等）的基类。

 -- 类: asyncio.BufferedProtocol (BaseProtocol)

     用于实现可对接收缓冲区进行手动控制的流式协议的基类。

 -- 类: asyncio.DatagramProtocol (BaseProtocol)

     用于实现数据报（UDP）协议的基类。

 -- 类: asyncio.SubprocessProtocol (BaseProtocol)

     用于实现与子进程通信（单向管道）的协议的基类。


File: python.info,  Node: 基础协议<2>,  Next: 流协议,  Prev: 基础协议,  Up: 协议

5.18.1.82 基础协议
..................

所有 asyncio 协议均可实现基础协议回调。

链接回调函数
............

连接回调会在所有协议上被调用，每个成功的连接将恰好调用一次。 所有其他协
议回调只能在以下两个方法之间被调用。

 -- 方法: BaseProtocol.connection_made (transport)

     链接建立时被调用。

     `transport' 参数是代表连接的传输。 此协议负责将引用保存至对应的传输
     。

 -- 方法: BaseProtocol.connection_lost (exc)

     链接丢失或关闭时被调用。

     方法的参数是一个异常对象或为 *note None: 158.。 后者意味着收到了常
     规的 EOF，或者连接被连接的一端取消或关闭。

流控制回调函数
..............

流程控制回调可由传输来调用以暂停或恢复协议所执行的写入操作。

请查看 *note set_write_buffer_limits(): 260e. 方法的文档了解详情。

 -- 方法: BaseProtocol.pause_writing ()

     当传输的缓冲区超出高水位时将被调用。

 -- 方法: BaseProtocol.resume_writing ()

     当传输的缓冲区降到低水位以下时将被调用。

如果缓冲区大小等于高水位值，则 *note pause_writing(): 260f. 不会被调用：
缓冲区大小必须要高于该值。

相反地，*note resume_writing(): 2610. 会在缓冲区大小等于或小于低水位值时
被调用。 这些结束条件对于当两个水位取零值时也能确保符合预期的行为是很重
要的。


File: python.info,  Node: 流协议,  Next: 缓冲流协议,  Prev: 基础协议<2>,  Up: 协议

5.18.1.83 流协议
................

事件方法，例如 *note loop.create_server(): 366, *note
loop.create_unix_server(): 367, *note loop.create_connection(): 1b3,
*note loop.create_unix_connection(): 252e, *note
loop.connect_accepted_socket(): 36e, *note loop.connect_read_pipe():
256c. 和 *note loop.connect_write_pipe(): 256d. 都接受返回流式协议的工厂
。

 -- 方法: Protocol.data_received (data)

     当收到数据时被调用。 `data' 为包含入站数据的非空字节串对象。

     数据是否会被缓冲、分块或重组取决于具体传输。 通常，你不应依赖于特定
     的语义而应使你的解析具有通用性和灵活性。 但是，数据总是要以正确的顺
     序被接收。

     此方法在连接打开期间可以被调用任意次数。

     但是，*note protocol.eof_received(): 2621. 最多只会被调用一次。 一
     旦 ‘eof_received()’ 被调用，‘data_received()’ 就不会再被调用。

 -- 方法: Protocol.eof_received ()

     当发出信号的另一端不再继续发送数据时（例如通过调用 *note
     transport.write_eof(): 260c.，如果另一端也使用 asyncio 的话）被调用
     。

     此方法可能返回假值 (包括 ‘None’)，在此情况下传输将会自行关闭。 相反
     地，如果此方法返回真值，将以所用的协议来确定是否要关闭传输。 由于默
     认实现是返回 ‘None’，因此它会隐式地关闭连接。

     某些传输，包括 SSL 在内，并不支持半关闭的连接，在此情况下从该方法返
     回真值将导致连接被关闭。

状态机：

     start -> connection_made
         [-> data_received]*
         [-> eof_received]?
     -> connection_lost -> end


File: python.info,  Node: 缓冲流协议,  Next: 数据报协议,  Prev: 流协议,  Up: 协议

5.18.1.84 缓冲流协议
....................

3.7 新版功能: `Important:' this has been added to asyncio in Python 3.7
`on a provisional basis'!  This is as an experimental API that might be
changed or removed completely in Python 3.8.

带缓冲的协议可与任何支持 *note 流式协议: 2620. 的事件循环方法配合使用。

‘BufferedProtocol’ 实现允许显式手动分配和控制接收缓冲区。 随后事件循环可
以使用协议提供的缓冲区来避免不必要的数据复制。 这对于接收大量数据的协议
来说会有明显的性能提升。 复杂的协议实现能显著地减少缓冲区分配的数量。

以下回调是在 *note BufferedProtocol: 2ca. 实例上被调用的:

 -- 方法: BufferedProtocol.get_buffer (sizehint)

     调用后会分配新的接收缓冲区。

     `sizehint' 是推荐的返回缓冲区最小尺寸。 返回小于或大于 `sizehint' 推
     荐尺寸的缓冲区也是可接受的。 当设为 -1 时，缓冲区尺寸可以是任意的。
     返回尺寸为零的缓冲区则是错误的。

     ‘get_buffer()’ 必须返回一个实现了 *note 缓冲区协议: 15f7. 的对象。

 -- 方法: BufferedProtocol.buffer_updated (nbytes)

     用接收的数据更新缓冲区时被调用。

     `nbytes' 是被写入到缓冲区的字节总数。

 -- 方法: BufferedProtocol.eof_received ()

     请查看 *note protocol.eof_received(): 2621. 方法的文档。

在连接期间 *note get_buffer(): 2623. 可以被调用任意次数。 但是，*note
protocol.eof_received(): 2621. 最多只能被调用一次，如果被调用，则在此之
后 *note get_buffer(): 2623. 和 *note buffer_updated(): 2624. 不能再被调
用。

状态机：

     start -> connection_made
         [-> get_buffer
             [-> buffer_updated]?
         ]*
         [-> eof_received]?
     -> connection_lost -> end


File: python.info,  Node: 数据报协议,  Next: 子进程协议,  Prev: 缓冲流协议,  Up: 协议

5.18.1.85 数据报协议
....................

数据报协议实例应当由传递给 *note loop.create_datagram_endpoint(): 2e8. 方
法的协议工厂来构造。

 -- 方法: DatagramProtocol.datagram_received (data, addr)

     当接收到数据报时被调用。 `data' 是包含传入数据的字节串对象。 `addr'
     是发送数据的对等端地址；实际的格式取决于具体传输。

 -- 方法: DatagramProtocol.error_received (exc)

     当前一个发送或接收操作引发 *note OSError: 1d4. 时被调用。 `exc' 是
     *note OSError: 1d4. 的实例。

     此方法会在当传输（例如UDP）检测到无法将数据报传给接收方等极少数情况
     下被调用。 而在大多数情况下，无法送达的数据报将被静默地丢弃。

     注解: 在 BSD 系统（macOS, FreeBSD 等等）上，数据报协议不支持流控制
     ，因为没有可靠的方式来检测因写入多过包所导致的发送失败。

     套接字总是显示为 ’ready’ 且多余的包会被丢弃。 有一定的可能性会引发
     *note OSError: 1d4. 并设置 ‘errno’ 为 *note errno.ENOBUFS: 22ad.；
     如果此异常被引发，它将被报告给 *note
     DatagramProtocol.error_received(): 2628.，在其他情况下则会被忽略。


File: python.info,  Node: 子进程协议,  Prev: 数据报协议,  Up: 协议

5.18.1.86 子进程协议
....................

数据报协议实例应当由传递给 *note loop.subprocess_exec(): 24fc. 和 *note
loop.subprocess_shell(): 256a. 方法的协议工厂来构造。

 -- 方法: SubprocessProtocol.pipe_data_received (fd, data)

     当子进程向其 stdout 或 stderr 管道写入数据时被调用。

     `fd' 是以整数表示的管道文件描述符。

     `data' 是包含已接收数据的非空字节串对象。

 -- 方法: SubprocessProtocol.pipe_connection_lost (fd, exc)

     与子进程通信的其中一个管道关闭时被调用。

     `fd' 以整数表示的已关闭文件描述符。

 -- 方法: SubprocessProtocol.process_exited ()

     子进程退出时被调用。


File: python.info,  Node: 例子<15>,  Prev: 协议,  Up: 传输和协议

5.18.1.87 例子
..............

* Menu:

* TCP回应服务器::
* TCP回应客户端::
* UDP回应服务器::
* UDP回应客户端::
* 链接已存在的套接字::
* loop.subprocess_exec() 与 SubprocessProtocol: loop subprocess_exec 与 SubprocessProtocol.


File: python.info,  Node: TCP回应服务器,  Next: TCP回应客户端,  Up: 例子<15>

5.18.1.88 TCP回应服务器
.......................

使用 *note loop.create_server(): 366. 方法创建 TCP 回显服务器，发回已接
收的数据，并关闭连接:

     import asyncio


     class EchoServerProtocol(asyncio.Protocol):
         def connection_made(self, transport):
             peername = transport.get_extra_info('peername')
             print('Connection from {}'.format(peername))
             self.transport = transport

         def data_received(self, data):
             message = data.decode()
             print('Data received: {!r}'.format(message))

             print('Send: {!r}'.format(message))
             self.transport.write(data)

             print('Close the client socket')
             self.transport.close()


     async def main():
         # Get a reference to the event loop as we plan to use
         # low-level APIs.
         loop = asyncio.get_running_loop()

         server = await loop.create_server(
             lambda: EchoServerProtocol(),
             '127.0.0.1', 8888)

         async with server:
             await server.serve_forever()


     asyncio.run(main())

参见
....

*note 使用流的 TCP 回显服务器: 2542. 示例，使用了高层级的 *note
asyncio.start_server(): 36d. 函数。


File: python.info,  Node: TCP回应客户端,  Next: UDP回应服务器,  Prev: TCP回应服务器,  Up: 例子<15>

5.18.1.89 TCP回应客户端
.......................

使用 *note loop.create_connection(): 1b3. 方法的 TCP 回显客户端，发送数
据并等待，直到连接被关闭:

     import asyncio


     class EchoClientProtocol(asyncio.Protocol):
         def __init__(self, message, on_con_lost):
             self.message = message
             self.on_con_lost = on_con_lost

         def connection_made(self, transport):
             transport.write(self.message.encode())
             print('Data sent: {!r}'.format(self.message))

         def data_received(self, data):
             print('Data received: {!r}'.format(data.decode()))

         def connection_lost(self, exc):
             print('The server closed the connection')
             self.on_con_lost.set_result(True)


     async def main():
         # Get a reference to the event loop as we plan to use
         # low-level APIs.
         loop = asyncio.get_running_loop()

         on_con_lost = loop.create_future()
         message = 'Hello World!'

         transport, protocol = await loop.create_connection(
             lambda: EchoClientProtocol(message, on_con_lost),
             '127.0.0.1', 8888)

         # Wait until the protocol signals that the connection
         # is lost and close the transport.
         try:
             await on_con_lost
         finally:
             transport.close()


     asyncio.run(main())

参见
....

*note 使用流的 TCP 回显客户端: 253f. 示例，使用了高层级的 *note
asyncio.open_connection(): 36c. 函数。


File: python.info,  Node: UDP回应服务器,  Next: UDP回应客户端,  Prev: TCP回应客户端,  Up: 例子<15>

5.18.1.90 UDP回应服务器
.......................

使用 *note loop.create_datagram_endpoint(): 2e8. 方法的 UDB 回显服务器，
发回已接收的数据:

     import asyncio


     class EchoServerProtocol:
         def connection_made(self, transport):
             self.transport = transport

         def datagram_received(self, data, addr):
             message = data.decode()
             print('Received %r from %s' % (message, addr))
             print('Send %r to %s' % (message, addr))
             self.transport.sendto(data, addr)


     async def main():
         print("Starting UDP server")

         # Get a reference to the event loop as we plan to use
         # low-level APIs.
         loop = asyncio.get_running_loop()

         # One protocol instance will be created to serve all
         # client requests.
         transport, protocol = await loop.create_datagram_endpoint(
             lambda: EchoServerProtocol(),
             local_addr=('127.0.0.1', 9999))

         try:
             await asyncio.sleep(3600)  # Serve for 1 hour.
         finally:
             transport.close()


     asyncio.run(main())


File: python.info,  Node: UDP回应客户端,  Next: 链接已存在的套接字,  Prev: UDP回应服务器,  Up: 例子<15>

5.18.1.91 UDP回应客户端
.......................

使用 *note loop.create_datagram_endpoint(): 2e8. 方法的 UDP 回显客户端，
发送数据并在收到回应时关闭传输:

     import asyncio


     class EchoClientProtocol:
         def __init__(self, message, on_con_lost):
             self.message = message
             self.on_con_lost = on_con_lost
             self.transport = None

         def connection_made(self, transport):
             self.transport = transport
             print('Send:', self.message)
             self.transport.sendto(self.message.encode())

         def datagram_received(self, data, addr):
             print("Received:", data.decode())

             print("Close the socket")
             self.transport.close()

         def error_received(self, exc):
             print('Error received:', exc)

         def connection_lost(self, exc):
             print("Connection closed")
             self.on_con_lost.set_result(True)


     async def main():
         # Get a reference to the event loop as we plan to use
         # low-level APIs.
         loop = asyncio.get_running_loop()

         on_con_lost = loop.create_future()
         message = "Hello World!"

         transport, protocol = await loop.create_datagram_endpoint(
             lambda: EchoClientProtocol(message, on_con_lost),
             remote_addr=('127.0.0.1', 9999))

         try:
             await on_con_lost
         finally:
             transport.close()


     asyncio.run(main())


File: python.info,  Node: 链接已存在的套接字,  Next: loop subprocess_exec 与 SubprocessProtocol,  Prev: UDP回应客户端,  Up: 例子<15>

5.18.1.92 链接已存在的套接字
............................

附带一个协议使用 *note loop.create_connection(): 1b3. 方法，等待直到套接
字接收数据:

     import asyncio
     import socket


     class MyProtocol(asyncio.Protocol):

         def __init__(self, on_con_lost):
             self.transport = None
             self.on_con_lost = on_con_lost

         def connection_made(self, transport):
             self.transport = transport

         def data_received(self, data):
             print("Received:", data.decode())

             # We are done: close the transport;
             # connection_lost() will be called automatically.
             self.transport.close()

         def connection_lost(self, exc):
             # The socket has been closed
             self.on_con_lost.set_result(True)


     async def main():
         # Get a reference to the event loop as we plan to use
         # low-level APIs.
         loop = asyncio.get_running_loop()
         on_con_lost = loop.create_future()

         # Create a pair of connected sockets
         rsock, wsock = socket.socketpair()

         # Register the socket to wait for data.
         transport, protocol = await loop.create_connection(
             lambda: MyProtocol(on_con_lost), sock=rsock)

         # Simulate the reception of data from the network.
         loop.call_soon(wsock.send, 'abc'.encode())

         try:
             await protocol.on_con_lost
         finally:
             transport.close()
             wsock.close()

     asyncio.run(main())

参见
....

使用低层级的 *note loop.add_reader(): 2549. 方法来注册一个 FD 的 *note
监视文件描述符以读取事件: 254a. 示例。

使用在协程中通过 *note open_connection(): 36c. 函数创建的高层级流的
*note 注册一个打开的套接字以等待使用流的数据: 2546. 示例。


File: python.info,  Node: loop subprocess_exec 与 SubprocessProtocol,  Prev: 链接已存在的套接字,  Up: 例子<15>

5.18.1.93 loop.subprocess_exec() 与 SubprocessProtocol
......................................................

一个使用子进程协议来获取子进程的输出并等待子进程退出的示例。

这个子进程是由 *note loop.subprocess_exec(): 24fc. 方法创建的:

     import asyncio
     import sys

     class DateProtocol(asyncio.SubprocessProtocol):
         def __init__(self, exit_future):
             self.exit_future = exit_future
             self.output = bytearray()

         def pipe_data_received(self, fd, data):
             self.output.extend(data)

         def process_exited(self):
             self.exit_future.set_result(True)

     async def get_date():
         # Get a reference to the event loop as we plan to use
         # low-level APIs.
         loop = asyncio.get_running_loop()

         code = 'import datetime; print(datetime.datetime.now())'
         exit_future = asyncio.Future(loop=loop)

         # Create the subprocess controlled by DateProtocol;
         # redirect the standard output into a pipe.
         transport, protocol = await loop.subprocess_exec(
             lambda: DateProtocol(exit_future),
             sys.executable, '-c', code,
             stdin=None, stderr=None)

         # Wait for the subprocess exit using the process_exited()
         # method of the protocol.
         await exit_future

         # Close the stdout pipe.
         transport.close()

         # Read the output which was collected by the
         # pipe_data_received() method of the protocol.
         data = bytes(protocol.output)
         return data.decode('ascii').rstrip()

     date = asyncio.run(get_date())
     print(f"Current date: {date}")

另请参阅使用高层级 API 编写的 *note 相同示例: 2585.。


File: python.info,  Node: 策略,  Next: 平台支持,  Prev: 传输和协议,  Up: asyncio --- 异步 I/O

5.18.1.94 策略
..............

事件循环策略是各个进程的全局对象 ，它控制事件循环的管理。每个事件循环都
有一个默认策略，可以使用策略API更改和定制该策略。

策略定义了“上下文”的概念，每个上下文管理一个单独的事件循环。默认策略将
*context*定义为当前线程。

通过使用自定义事件循环策略，可以自定义 *note get_event_loop(): 35e. 、
*note set_event_loop(): 25a3. 和 *note new_event_loop(): 25a4. 函数的行
为。

策略对象应该实现 *note AbstractEventLoopPolicy: 2635. 抽象基类中定义的
API。

* Menu:

* 获取和设置策略::
* 策略对象::
* 进程监视器::
* 自定义策略::


File: python.info,  Node: 获取和设置策略,  Next: 策略对象,  Up: 策略

5.18.1.95 获取和设置策略
........................

可以使用下面函数获取和设置当前进程的策略:

 -- 函数: asyncio.get_event_loop_policy ()

     返回当前进程域的策略。

 -- 函数: asyncio.set_event_loop_policy (policy)

     将 `policy' 设置为当前进程域策略。

     如果 `policy' 设为 ‘None’ 将恢复默认策略。


File: python.info,  Node: 策略对象,  Next: 进程监视器,  Prev: 获取和设置策略,  Up: 策略

5.18.1.96 策略对象
..................

抽象事件循环策略基类定义如下:

 -- 类: asyncio.AbstractEventLoopPolicy

     异步策略的抽象基类。

      -- 方法: get_event_loop ()

          为当前上下文获取事件循环。

          返回一个实现 *note AbstractEventLoop: 25e0. 接口的事件循环对象
          。

          该方法永远不应返回 ‘None’。

          在 3.6 版更改.

      -- 方法: set_event_loop (loop)

          将当前上下文的事件循环设置为 `loop' 。

      -- 方法: new_event_loop ()

          创建并返回一个新的事件循环对象。

          该方法永远不应返回 ‘None’。

      -- 方法: get_child_watcher ()

          获取子进程监视器对象。

          返回一个实现 *note AbstractChildWatcher: 263e. 接口的监视器对
          象。

          该函数仅支持Unix。

      -- 方法: set_child_watcher (watcher)

          将当前子进程监视器设置为 `watcher' 。

          该函数仅支持Unix。

asyncio附带下列内置策略:

 -- 类: asyncio.DefaultEventLoopPolicy

     默认的 asyncio 策略。 在 Unix 上使用 *note SelectorEventLoop: 2582.
     而在 Windows 上使用 *note ProactorEventLoop: 1ac.。

     不需要手动安装默认策略。asyncio已配置成自动使用默认策略。

     在 3.8 版更改: 在 Windows 上，现在默认会使用 *note
     ProactorEventLoop: 1ac.。

 -- 类: asyncio.WindowsSelectorEventLoopPolicy

     一个使用 *note SelectorEventLoop: 2582. 事件循环实现的替代事件循环
     策略。

     *note 可用性: 136f.: Windows。

 -- 类: asyncio.WindowsProactorEventLoopPolicy

     使用 *note ProactorEventLoop: 1ac. 事件循环实现的另一种事件循环策略
     。

     *note 可用性: 136f.: Windows。


File: python.info,  Node: 进程监视器,  Next: 自定义策略,  Prev: 策略对象,  Up: 策略

5.18.1.97 进程监视器
....................

进程监视器允许定制事件循环如何监视Unix子进程。具体来说，事件循环需要知道
子进程何时退出。

在asyncio中子进程由 *note create_subprocess_exec(): 292. 和 *note
loop.subprocess_exec(): 24fc. 函数创建。

asyncio 定义了 *note AbstractChildWatcher: 263e. 抽象基类，子监视器必须
要实现它，并具有四种不同实现: *note ThreadedChildWatcher: 2584. (已配置
为默认使用), *note MultiLoopChildWatcher: 2644, *note SafeChildWatcher:
2645. 和 *note FastChildWatcher: 2646.。

请参阅 *note 子进程和线程: 257a. 部分。

以下两个函数可用于自定义子进程监视器实现，它将被asyncio事件循环使用:

 -- 函数: asyncio.get_child_watcher ()

     返回当前策略的当前子监视器。

 -- 函数: asyncio.set_child_watcher (watcher)

     将当前策略的子监视器设置为 `watcher' 。`watcher' 必须实现 *note
     AbstractChildWatcher: 263e. 基类定义的方法。

     注解: 第三方事件循环实现可能不支持自定义子监视器。对于这样的事件循
     环，禁止使用 *note set_child_watcher(): 2648. 或不起作用。

 -- 类: asyncio.AbstractChildWatcher

      -- 方法: add_child_handler (pid, callback, *args)

          注册一个新的子处理回调函数。

          安排 ‘callback(pid, returncode, *args)’ 在进程的PID与 `pid' 相
          等时调用。指定另一个同进程的回调函数替换之前的回调处理函数。

          回调函数 `callback' 必须是线程安全。

      -- 方法: remove_child_handler (pid)

          删除进程PID与 `pid' 相等的进程的处理函数。

          处理函数成功删除时返回 ‘True’ ，没有删除时返回 ‘False’ 。

      -- 方法: attach_loop (loop)

          给一个事件循环绑定监视器。

          如果监视器之前已绑定另一个事件循环，那么在绑定新循环前会先解绑
          原来的事件循环。

          注意：循环有可能是 ‘None’ 。

      -- 方法: is_active ()

          如果监视器已准备好使用则返回 ‘True’。

          使用 `不活动的' 当前子监视器生成子进程将引发 *note
          RuntimeError: 2bb.。

          3.8 新版功能.

      -- 方法: close ()

          关闭监视器。

          必须调用这个方法以确保相关资源会被清理。

 -- 类: asyncio.ThreadedChildWatcher

     此实现会为每个生成的子进程启动一具新的等待线程。

     即使是当 asyncio 事件循环运行在非主 OS 线程上时它也能可靠地工作。

     当处理大量子进程时不存在显著的开销 (每次子进程结束时为 `O(1)')，但
     当每个进程启动一个线程时则需要额外的内存。

     此监视器会默认被使用。

     3.8 新版功能.

 -- 类: asyncio.MultiLoopChildWatcher

     此实现会在实例化时注册一个 ‘SIGCHLD’ 信号处理程序。 这可能会破坏为
     ‘SIGCHLD’ 信号安装自定义处理程序的第三方代码。

     此监视器会在收到 ‘SIGCHLD’ 信号时通过显式地轮询每个进程来避免干扰其
     他代码生成的进程。

     该监视器一旦被安装就不会限制从不同线程运行子进程。

     该解决方案是安全的，但在处理大量进程时会有显著的开销 (每收到一个
     ‘SIGCHLD’ 时为 `O(n)')。

     3.8 新版功能.

 -- 类: asyncio.SafeChildWatcher

     该实现会使用主线程中的活动事件循环来处理 ‘SIGCHLD’ 信号。 如果主线
     程没有正在运行的事件循环，则其他线程无法生成子进程 (会引发 *note
     RuntimeError: 2bb.)。

     此监视器会在收到 ‘SIGCHLD’ 信号时通过显式地轮询每个进程来避免干扰其
     他代码生成的进程。

     该解决方案与 *note MultiLoopChildWatcher: 2644. 同样安全并同样具有
     `O(N)' 复杂度，但需要主线程有正在运行的事件循环才能工作。

 -- 类: asyncio.FastChildWatcher

     这种实现直接调用 ‘os.waitpid(-1)’ 来获取所有已结束的进程，可能会中
     断其它代码洐生进程并等待它们结束。

     在处理大量子监视器时没有明显的开销( `O(1)' 每次子监视器结束)。

     该解决方案需要主线程有正在运行的事件循环才能工作，这与 *note
     SafeChildWatcher: 2645. 一样。


File: python.info,  Node: 自定义策略,  Prev: 进程监视器,  Up: 策略

5.18.1.98 自定义策略
....................

要实现一个新的事件循环策略，建议子类化 *note DefaultEventLoopPolicy:
2640. 并重写需要定制行为的方法，例如:

     class MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):

         def get_event_loop(self):
             """Get the event loop.

             This may be None or an instance of EventLoop.
             """
             loop = super().get_event_loop()
             # Do something with loop ...
             return loop

     asyncio.set_event_loop_policy(MyEventLoopPolicy())


File: python.info,  Node: 平台支持,  Next: 高级API索引,  Prev: 策略,  Up: asyncio --- 异步 I/O

5.18.1.99 平台支持
..................

*note asyncio: a. 模块被设计为可移植的,但由于平台的底层架构和功能，一些
平台存在细微的差异和限制。

* Menu:

* 所有平台::
* Windows: Windows<53>.
* macOS: macOS<26>.


File: python.info,  Node: 所有平台,  Next: Windows<53>,  Up: 平台支持

5.18.1.100 所有平台
...................

   * *note loop.add_reader(): 2549. 和 *note loop.add_writer(): 25c7. 不
     能用来监视文件I/O。


File: python.info,  Node: Windows<53>,  Next: macOS<26>,  Prev: 所有平台,  Up: 平台支持

5.18.1.101 Windows
..................

`源代码:' Lib/asyncio/proactor_events.py(1),
Lib/asyncio/windows_events.py(2), Lib/asyncio/windows_utils.py(3)

__________________________________________________________________

在 3.8 版更改: 在 Windows 上，*note ProactorEventLoop: 1ac. 现在是默认的
事件循环。

Windows上的所有事件循环都不支持以下方法:

   * 不支持 *note loop.create_unix_connection(): 252e. 和 *note
     loop.create_unix_server(): 367. 。 *note socket.AF_UNIX: 25be. 套接
     字相关参数仅限于Unix。

   * 不支持 *note loop.add_signal_handler(): 24fd. 和 *note
     loop.remove_signal_handler(): 25d2. 。

*note SelectorEventLoop: 2582. 有下列限制:

   * *note SelectSelector: 2653. 只被用于等待套接字事件：它支持套接字且
     最多支持512个套接字。

   * *note loop.add_reader(): 2549. 和 *note loop.add_writer(): 25c7. 只
     接受套接字处理回调函数(如管道、文件描述符等都不支持)。

   * 因为不支持管道，所以 *note loop.connect_read_pipe(): 256c. 和 *note
     loop.connect_write_pipe(): 256d. 方法没有实现。

   * 不支持 *note Subprocesses: 24f9. ，也就是 *note
     loop.subprocess_exec(): 24fc. 和 *note loop.subprocess_shell():
     256a. 方法没有实现。

*note ProactorEventLoop: 1ac. 有下列限制:

   * 不支持 *note loop.add_reader(): 2549. 和 *note loop.add_writer():
     25c7. 方法。

Windows上单调时钟的分辨率大约为 15.6 毫秒。最佳的分辨率是 0.5 毫秒。分辨
率依赖于具体的硬件（HPET(4)）和Windows的设置。

* Menu:

* Windows的子进程支持::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/asyncio/proactor_events.py

   (2) 
https://github.com/python/cpython/tree/3.8/Lib/asyncio/windows_events.py

   (3) 
https://github.com/python/cpython/tree/3.8/Lib/asyncio/windows_utils.py

   (4) https://zh.wikipedia.org/wiki/高精度事件计时器


File: python.info,  Node: Windows的子进程支持,  Up: Windows<53>

5.18.1.102 Windows的子进程支持
..............................

在 Windows 上，默认的事件循环 *note ProactorEventLoop: 1ac. 支持子进程，
而 *note SelectorEventLoop: 2582. 则不支持。

也不支持 *note policy.set_child_watcher(): 263f. 函数，*note
ProactorEventLoop: 1ac. 有不同的机制来监视子进程。


File: python.info,  Node: macOS<26>,  Prev: Windows<53>,  Up: 平台支持

5.18.1.103 macOS
................

完整支持流行的macOS版本。

macOS <= 10.8
.............

在 macOS 10.6, 10.7 和 10.8 上，默认的事件循环使用 *note
selectors.KqueueSelector: 2656.，在这些版本上它并不支持字符设备。 可以手
工配置 *note SelectorEventLoop: 2582. 来使用 *note SelectSelector: 2653.
或 *note PollSelector: 454. 以在这些较老版本的 macOS 上支持字符设备。 例
如:

     import asyncio
     import selectors

     selector = selectors.SelectSelector()
     loop = asyncio.SelectorEventLoop(selector)
     asyncio.set_event_loop(loop)


File: python.info,  Node: 高级API索引,  Next: 底层API目录,  Prev: 平台支持,  Up: asyncio --- 异步 I/O

5.18.1.104 高级API索引
......................

这个页面列举了所有能用于 async/wait 的高级asyncio API 集。

* Menu:

* 任务::
* 队列集: 队列集<2>.
* 子进程集: 子进程集<2>.
* 流: 流<2>.
* 同步::
* 异常: 异常<10>.


File: python.info,  Node: 任务,  Next: 队列集<2>,  Up: 高级API索引

5.18.1.105 任务
...............

运行异步程序，创建Task对象，等待多件事运行超时的公共集。

*note run(): 1a6.                                      创建事件循环，运行一个协程，关闭事件循环。
                                                       
                                                       
*note create_task(): 1af.                              启动一个asyncio的Task对象。
                                                       
                                                       
‘await’ *note sleep(): 286.                            休眠几秒。
                                                       
                                                       
‘await’ *note gather(): 287.                           并发执行所有事件的调度和等待。
                                                       
                                                       
‘await’ *note wait_for(): 289.                         有超时控制的运行。
                                                       
                                                       
‘await’ *note shield(): 288.                           屏蔽取消操作
                                                       
                                                       
‘await’ *note wait(): 28a.                             完成情况的监控器
                                                       
                                                       
*note current_task(): 359.                             返回当前Task对象
                                                       
                                                       
*note all_tasks(): 35a.                                返回事件循环中所有的task对象。
                                                       
                                                       
*note Task: 1ae.                                       Task对象
                                                       
                                                       
*note run_coroutine_threadsafe(): 522.                 从其他OS线程中调度一个协程。
                                                       
                                                       
‘for in’ *note as_completed(): 28b.                    用 ‘for’ 循环监控完成情况。
                                                       

例子
....

   * *note 使用 asyncio.gather() 并行运行: 250c.

   * *note 使用 asyncio.wait_for() 强制超时: 2511.

   * *note 撤销协程: 251c.

   * *note asyncio.sleep() 的用法: 250a.

   * 请主要参阅 *note 协程与任务文档: 24f7.


File: python.info,  Node: 队列集<2>,  Next: 子进程集<2>,  Prev: 任务,  Up: 高级API索引

5.18.1.106 队列集
.................

队列集被用于多个异步Task对象的运行调度，实现连接池以及发布/订阅模式。

*note Queue: 291.                                      先进先出队列
                                                       
                                                       
*note PriorityQueue: 2596.                             优先级队列。
                                                       
                                                       
*note LifoQueue: 2598.                                 后进先出队列。
                                                       

例子
....

   * *note 使用 asyncio.Queue 在多个并发任务间分配工作量: 259a.

   * 请参阅 *note 队列集文档: 24fa.


File: python.info,  Node: 子进程集<2>,  Next: 流<2>,  Prev: 队列集<2>,  Up: 高级API索引

5.18.1.107 子进程集
...................

用于生成子进程和运行shell命令的工具包。

‘await’ *note create_subprocess_exec(): 292.           创建一个子进程。
                                                       
                                                       
‘await’ *note create_subprocess_shell(): 293.          运行一个shell命令。
                                                       

例子
....

   * *note 执行一个shell命令: 2566.

   * 请参阅 *note 子进程 APIs: 24f9. 相关文档.


File: python.info,  Node: 流<2>,  Next: 同步,  Prev: 子进程集<2>,  Up: 高级API索引

5.18.1.108 流
.............

用于网络IO处理的高级API集。

‘await’ *note open_connection(): 36c.                  建立一个TCP连接。
                                                       
                                                       
‘await’ *note open_unix_connection(): 252d.            建立一个Unix socket连接。
                                                       
                                                       
‘await’ *note start_server(): 36d.                     启动TCP服务。
                                                       
                                                       
‘await’ *note start_unix_server(): 252f.               启动一个Unix socket服务。
                                                       
                                                       
*note StreamReader: fda.                               接收网络数据的高级async/await对象。
                                                       
                                                       
*note StreamWriter: fdb.                               发送网络数据的高级async/await对象。
                                                       

例子
....

   * *note TCP 客户端样例: 252b.

   * 请参阅 *note streams APIs: 24f8. 文档。


File: python.info,  Node: 同步,  Next: 异常<10>,  Prev: 流<2>,  Up: 高级API索引

5.18.1.109 同步
...............

能被用于Task对象集的，类似线程的同步基元组件。

*note Lock: 28c.                                       互斥锁。
                                                       
                                                       
*note Event: 28d.                                      事件对象。
                                                       
                                                       
*note Condition: 28e.                                  条件对象
                                                       
                                                       
*note Semaphore: 28f.                                  信号量
                                                       
                                                       
*note BoundedSemaphore: 290.                           有界的信号量。
                                                       

例子
....

   * *note asyncio.Event 的用法: 2555.

   * 请参阅asyncio文档 *note synchronization primitives: 24fb.


File: python.info,  Node: 异常<10>,  Prev: 同步,  Up: 高级API索引

5.18.1.110 异常
...............

*note asyncio.TimeoutError: 2510.                      类似 *note wait_for(): 289. 等函数在超时时候被引发。
                                                       请注意 ‘asyncio.TimeoutError’ 与内建异常
                                                       *note TimeoutError: 9a4. 无关。
                                                       
                                                       
*note asyncio.CancelledError: 1a8.                     当一个Task对象被取消的时候被引发。请参阅
                                                       *note Task.cancel(): 250e.。
                                                       

例子
....

   * *note 在取消请求发生的运行代码中如何处理CancelledError异常: 251c.

   * 请参阅完整的 *note asyncio 专用异常: 259c. 列表.


File: python.info,  Node: 底层API目录,  Next: 用 asyncio 开发,  Prev: 高级API索引,  Up: asyncio --- 异步 I/O

5.18.1.111 底层API目录
......................

本页列出所有底层asyncio API。

* Menu:

* 获取事件循环::
* 事件循环方法集: 事件循环方法集<2>.
* 传输: 传输<2>.
* 协议: 协议<2>.
* 事件循环策略::


File: python.info,  Node: 获取事件循环,  Next: 事件循环方法集<2>,  Up: 底层API目录

5.18.1.112 获取事件循环
.......................

*note asyncio.get_running_loop(): 35d.                 获取当前运行的事件循环 `首选' 函数。
                                                       
                                                       
*note asyncio.get_event_loop(): 35e.                   获得一个事件循环实例(当前或通过策略)。
                                                       
                                                       
*note asyncio.set_event_loop(): 25a3.                  通过当前策略将事件循环设置当前事件循环。
                                                       
                                                       
*note asyncio.new_event_loop(): 25a4.                  创建一个新的事件循环。
                                                       

例子
....

   * *note 使用asyncio.get_running_loop(): 25f2.。


File: python.info,  Node: 事件循环方法集<2>,  Next: 传输<2>,  Prev: 获取事件循环,  Up: 底层API目录

5.18.1.113 事件循环方法集
.........................

查阅 *note 事件循环方法: 64d. 相关的主要文档段落 。

生命周期
........

*note loop.run_until_complete(): 520.                  运行一个期程/任务/可等待对象直到完成。
                                                       
                                                       
*note loop.run_forever(): 25ad.                        一直运行事件循环。
                                                       
                                                       
*note loop.stop(): 528.                                停止事件循环。
                                                       
                                                       
*note loop.close(): 25af.                              关闭事件循环。
                                                       
                                                       
*note loop.is_running(): 25ae.                         返回 ‘True’ ， 如果事件循环正在运行。
                                                       
                                                       
*note loop.is_closed(): 6a4.                           返回 ‘True’ ，如果事件循环已经被关闭 。
                                                       
                                                       
‘await’ *note loop.shutdown_asyncgens(): 529.          关闭异步生成器。
                                                       

调试
....

*note loop.set_debug(): 6a2.                           开启或禁用调试模式。
                                                       
                                                       
*note loop.get_debug(): 6a3.                           获取当前测试模式。
                                                       

调度回调函数
............

*note loop.call_soon(): 352.                           尽快调用回调。
                                                       
                                                       
*note loop.call_soon_threadsafe(): 353.                *note loop.call_soon(): 352. 方法线程安全的变体。
                                                       
                                                       
*note loop.call_later(): 354.                          在给定时间 `之后' 调用回调函数。
                                                       
                                                       
*note loop.call_at(): 355.                             在 `指定' 时间调用回调函数。
                                                       

线程/进程池
...........

‘await’ *note loop.run_in_executor(): 2506.            在 *note concurrent.futures: 22. 执行器中运行一个独
                                                       占CPU或其它阻塞函数。
                                                       
                                                       
*note loop.set_default_executor(): 27c.                设置 *note loop.run_in_executor(): 2506. 默认执行器
                                                       。
                                                       

任务与期程
..........

*note loop.create_future(): 524.                       创建一个 *note Future: 44b. 对象。
                                                       
                                                       
*note loop.create_task(): 1b0.                         将协程当作 *note Task: 1ae. 一样调度。
                                                       
                                                       
*note loop.set_task_factory(): 6a6.                    设置 *note loop.create_task(): 1b0. 使用的工厂，它将
                                                       用来创建 *note Tasks: 1ae. 。
                                                       
                                                       
*note loop.get_task_factory(): 6a7.                    获取 *note loop.create_task(): 1b0. 使用的工厂，它用
                                                       来创建 *note Tasks: 1ae. 。
                                                       

DNS
...

‘await’ *note loop.getaddrinfo(): 4a9.                 异步版的 *note socket.getaddrinfo(): 25cc. 。
                                                       
                                                       
‘await’ *note loop.getnameinfo(): 4aa.                 异步版的 *note socket.getnameinfo(): 25cd. 。
                                                       

网络和IPC
.........

‘await’ *note loop.create_connection(): 1b3.           打开一个TCP链接。
                                                       
                                                       
‘await’ *note loop.create_server(): 366.               创建一个TCP服务。
                                                       
                                                       
‘await’ *note loop.create_unix_connection(): 252e.     打开一个Unix socket连接。
                                                       
                                                       
‘await’ *note loop.create_unix_server(): 367.          创建一个Unix socket服务。
                                                       
                                                       
‘await’ *note loop.connect_accepted_socket(): 36e.     将 *note socket: 67d. 包装成 ‘(transport, protocol)’
                                                       对。
                                                       
                                                       
‘await’ *note loop.create_datagram_endpoint(): 2e8.    打开一个数据报(UDP)连接。
                                                       
                                                       
‘await’ *note loop.sendfile(): 25c3.                   通过传输通道发送一个文件。
                                                       
                                                       
‘await’ *note loop.start_tls(): 357.                   将一个已建立的链接升级到TLS。
                                                       
                                                       
‘await’ *note loop.connect_read_pipe(): 256c.          将管道读取端包装成 ‘(transport, protocol)’ 对。
                                                       
                                                       
‘await’ *note loop.connect_write_pipe(): 256d.         将管道写入端包装成 ‘(transport, protocol)’ 对。
                                                       

套接字
......

‘await’ *note loop.sock_recv(): 4a6.                   从 *note socket: 67d. 接收数据。
                                                       
                                                       
‘await’ *note loop.sock_recv_into(): 358.              从 *note socket: 67d. 接收数据到一个缓冲区中。
                                                       
                                                       
‘await’ *note loop.sock_sendall(): 4a7.                发送数据到 *note socket: 67d. 。
                                                       
                                                       
‘await’ *note loop.sock_connect(): 6aa.                链接 ‘await’ *note loop.sock_connect(): 6aa. 。
                                                       
                                                       
‘await’ *note loop.sock_accept(): 4a8.                 接受一个 *note socket: 67d. 链接。
                                                       
                                                       
‘await’ *note loop.sock_sendfile(): 361.               利用 *note socket: 67d. 发送一个文件。
                                                       
                                                       
*note loop.add_reader(): 2549.                         开始对一个文件描述符的可读性的监视。
                                                       
                                                       
*note loop.remove_reader(): 25c6.                      停止对一个文件描述符的可读性的监视。
                                                       
                                                       
*note loop.add_writer(): 25c7.                         开始对一个文件描述符的可写性的监视。
                                                       
                                                       
*note loop.remove_writer(): 25c8.                      停止对一个文件描述符的可写性的监视。
                                                       

Unix信号
........

*note loop.add_signal_handler(): 24fd.                 给 *note signal: eb. 添加一个处理回调函数。
                                                       
                                                       
*note loop.remove_signal_handler(): 25d2.              删除 *note signal: eb. 的处理回调函数。
                                                       

子进程集
........

*note loop.subprocess_exec(): 24fc.                    衍生一个子进程
                                                       
                                                       
*note loop.subprocess_shell(): 256a.                   从终端命令衍生一个子进程。
                                                       

错误处理
........

*note loop.call_exception_handler(): 25d6.             调用异常处理器。
                                                       
                                                       
*note loop.set_exception_handler(): 25d5.              设置一个新的异常处理器。
                                                       
                                                       
*note loop.get_exception_handler(): 525.               获取当前异常处理器。
                                                       
                                                       
*note loop.default_exception_handler(): 25d7.          默认异常处理器实现。
                                                       

例子
....

   * *note 使用 asyncio.get_event_loop() 和 loop.run_forever(): 25e1.

   * *note 使用 loop.call_later(): 25e3.

   * 使用 ‘loop.create_connection()’ 实现 *note echo客户端: 2541.

   * 使用 ‘loop.create_connection()’ 去 *note 链接socket: 2548.

   * *note 使用add_reader()监听FD(文件描述符)的读取事件: 254a.

   * *note 使用loop.add_signal_handler(): 25e6.

   * *note 使用loop.add_signal_handler(): 2586.。


File: python.info,  Node: 传输<2>,  Next: 协议<2>,  Prev: 事件循环方法集<2>,  Up: 底层API目录

5.18.1.114 传输
...............

所有传输都实现以下方法:

*note transport.close(): 2600.                         关闭传输。
                                                       
                                                       
*note transport.is_closing(): 523.                     返回 ‘True’ ，如果传输正在关闭或已经关闭。
                                                       
                                                       
*note transport.get_extra_info(): 2c9.                 请求传输的相关信息。
                                                       
                                                       
*note transport.set_protocol(): 2605.                  设置一个新协议。
                                                       
                                                       
*note transport.get_protocol(): 2606.                  返回当前协议。
                                                       

传输可以接收数据(TCP和Unix链接，管道等)。它通过 *note
loop.create_connection(): 1b3, *note loop.create_unix_connection():
252e, *note loop.connect_read_pipe(): 256c. 等方法返回。

读取传输
........

*note transport.is_reading(): 370.                     返回 ‘True’ ，如果传输正在接收。
                                                       
                                                       
*note transport.pause_reading(): 372.                  暂停接收。
                                                       
                                                       
*note transport.resume_reading(): 371.                 继续接收。
                                                       

传输可以发送数据(TCP和Unix链接，管道等)。它通过 *note
loop.create_connection(): 1b3, *note loop.create_unix_connection():
252e, *note loop.connect_write_pipe(): 256d. 等方法返回。

写入传输
........

*note transport.write(): 2611.                         向传输写入数据。
                                                       
                                                       
*note transport.write(): 2611.                         向传输写入缓冲。
                                                       
                                                       
*note transport.can_write_eof(): 260b.                 返回 *note True: 4a1. ，如果传输支持发送 EOF。
                                                       
                                                       
*note transport.write_eof(): 260c.                     在冲洗已缓冲的数据后关闭传输和发送EOF。
                                                       
                                                       
*note transport.abort(): 260a.                         立即关闭传输。
                                                       
                                                       
*note transport.get_write_buffer_size(): 260d.         返回写入流控制的高位标记位和低位标记位。
                                                       
                                                       
*note transport.set_write_buffer_limits(): 260e.       设置新的写入流控制的高位标记位和低位标记位。
                                                       

由 *note loop.create_datagram_endpoint(): 2e8. 返回的传输:

数据报传输
..........

*note transport.sendto(): 2614.                        发送数据到远程链接端。
                                                       
                                                       
*note transport.abort(): 2615.                         立即关闭传输。
                                                       

基于子进程的底层抽象传输，它由 *note loop.subprocess_exec(): 24fc. 和
*note loop.subprocess_shell(): 256a. 返回:

子进程传输
..........

*note transport.get_pid(): 2617.                       返回子进程的进程ID。
                                                       
                                                       
*note transport.get_pipe_transport(): 2618.            返回请求通信管道 (`stdin', `stdout', 或 `stderr')的
                                                       传输。
                                                       
                                                       
*note transport.get_returncode(): 2619.                返回子进程的返回代号。
                                                       
                                                       
*note transport.kill(): 261a.                          杀死子进程。
                                                       
                                                       
*note transport.send_signal(): 261c.                   发送一个信号到子进程。
                                                       
                                                       
*note transport.terminate(): 261b.                     停止子进程。
                                                       
                                                       
*note transport.close(): 261d.                         杀死子进程并关闭所有管道。
                                                       


File: python.info,  Node: 协议<2>,  Next: 事件循环策略,  Prev: 传输<2>,  Up: 底层API目录

5.18.1.115 协议
...............

协议类可以由下面 `回调方法' 实现：

‘callback’ *note connection_made(): 25bc.              链接建立时被调用。
                                                       
                                                       
‘callback’ *note connection_lost(): 2601.              链接丢失或关闭时被调用。
                                                       
                                                       
‘callback’ *note pause_writing(): 260f.                传输的缓冲区超过高位标记位时被调用。
                                                       
                                                       
‘callback’ *note resume_writing(): 2610.               传输的缓冲区传送到低位标记位时被调用。
                                                       

流协议 (TCP, Unix 套接字, 管道)
...............................

‘callback’ *note data_received(): 2608.                接收到数据时被调用。
                                                       
                                                       
‘callback’ *note eof_received(): 2621.                 接收到EOF时被调用。
                                                       

缓冲流协议
..........

‘callback’ *note get_buffer(): 2623.                   调用后会分配新的接收缓冲区。
                                                       
                                                       
‘callback’ *note buffer_updated(): 2624.               用接收的数据更新缓冲区时被调用。
                                                       
                                                       
‘callback’ *note eof_received(): 2625.                 接收到EOF时被调用。
                                                       

数据报协议
..........

‘callback’ *note datagram_received(): 2627.            接收到数据报时被调用。
                                                       
                                                       
‘callback’ *note error_received(): 2628.               前一个发送或接收操作引发 *note OSError: 1d4. 时被调
                                                       用。
                                                       

子进程协议
..........

‘callback’ *note pipe_data_received(): 262a.           子进程向 `stdout' 或 `stderr' 管道写入数据时被调用。
                                                       
                                                       
‘callback’ *note pipe_connection_lost(): 262b.         与子进程通信的其中一个管道关闭时被调用。
                                                       
                                                       
‘callback’ *note process_exited(): 262c.               子进程退出时被调用。
                                                       


File: python.info,  Node: 事件循环策略,  Prev: 协议<2>,  Up: 底层API目录

5.18.1.116 事件循环策略
.......................

策略是改变 *note asyncio.get_event_loop(): 35e. 这类函数行为的一个底层机
制。更多细节可以查阅 *note 策略部分: 25a5.。

访问策略
........

*note asyncio.get_event_loop_policy(): 2637.           返回当前进程域的策略。
                                                       
                                                       
*note asyncio.set_event_loop_policy(): 2638.           设置一个新的进程域策略。
                                                       
                                                       
*note AbstractEventLoopPolicy: 2635.                   策略对象的基类。
                                                       


File: python.info,  Node: 用 asyncio 开发,  Prev: 底层API目录,  Up: asyncio --- 异步 I/O

5.18.1.117 用 asyncio 开发
..........................

异步编程与传统的“顺序”编程不同。

本页列出常见的错误和陷阱，并解释如何避免它们。

* Menu:

* Debug 模式::
* 并发性和多线程::
* 运行阻塞的代码::
* 日志记录: 日志记录<3>.
* 检测 never-awaited 协同程序::
* 检测就再也没异常::


File: python.info,  Node: Debug 模式,  Next: 并发性和多线程,  Up: 用 asyncio 开发

5.18.1.118 Debug 模式
.....................

默认情况下，asyncio以生产模式运行。为了简化开发，asyncio还有一种*debug 模
式* 。

有几种方法可以启用异步调试模式:

   * 将 *note PYTHONASYNCIODEBUG: 136c. 环境变量设置为 ‘1’ 。

   * 使用 *note -X: 156. ‘dev’ Python 命令行选项。

   * 将 ‘debug=True’ 传递给 *note asyncio.run(): 1a6. 。

   * 调用 *note loop.set_debug(): 6a2. 。

除了启用调试模式外，还要考虑:

   * 将 *note asyncio logger: 266a. 的日志级别设置为 ‘logging.DEBUG’，例
     如，下面的代码片段可以在应用程序启动时运行:

          logging.basicConfig(level=logging.DEBUG)

   * 配置 *note warnings: 127. 模块以显示 *note ResourceWarning: 4d8. 警
     告。一种方法是使用 *note -W: 41f. ‘default’ 命令行选项。

启用调试模式时:

   * asyncio 检查 *note 未被等待的协程: 266b. 并记录他们；这将消除“被遗
     忘的等待”问题。

   * 许多非线程安全的异步 APIs (例如 *note loop.call_soon(): 352. 和
     *note loop.call_at(): 355. 方法)，如果从错误的线程调用，则会引发异
     常。

   * 如果执行I/O操作花费的时间太长，则记录I/O选择器的执行时间。

   * 执行时间超过100毫秒的回调将会载入日志。 属性
     ‘loop.slow_callback_duration’ 可用于设置以秒为单位的最小执行持续时
     间，这被视为“缓慢”。


File: python.info,  Node: 并发性和多线程,  Next: 运行阻塞的代码,  Prev: Debug 模式,  Up: 用 asyncio 开发

5.18.1.119 并发性和多线程
.........................

事件循环在线程中运行(通常是主线程)，并在其线程中执行所有回调和任务。当一
个任务在事件循环中运行时，没有其他任务可以在同一个线程中运行。当一个任务
执行一个 ‘await’ 表达式时，正在运行的任务被挂起，事件循环执行下一个任务
。

要调度来自另一 OS 线程的 *note callback: 25b1.，应该使用 *note
loop.call_soon_threadsafe(): 353. 方法。 例如:

     loop.call_soon_threadsafe(callback, *args)

几乎所有异步对象都不是线程安全的，这通常不是问题，除非在任务或回调函数之
外有代码可以使用它们。如果需要这样的代码来调用低级异步API，应该使用
*note loop.call_soon_threadsafe(): 353. 方法，例如:

     loop.call_soon_threadsafe(fut.cancel)

要从不同的OS线程调度一个协程对象，应该使用 *note
run_coroutine_threadsafe(): 522. 函数。它返回一个 *note
concurrent.futures.Future: b35. 。查询结果:

     async def coro_func():
          return await asyncio.sleep(1, 42)

     # Later in another OS thread:

     future = asyncio.run_coroutine_threadsafe(coro_func(), loop)
     # Wait for the result:
     result = future.result()

为了能够处理信号和执行子进程，事件循环必须运行于主线程中。

方法 *note loop.run_in_executor(): 2506. 可以和 *note
concurrent.futures.ThreadPoolExecutor: 27b. 一起使用，用于在一个不同的操
作系统线程中执行阻塞代码，并避免阻塞运行事件循环的那个操作系统线程。

目前没有什么办法能直接从另一个进程 (例如通过 *note multiprocessing: b8.
启动的进程) 安排协程或回调。 *note 事件循环方法: 64d. 小节列出了可以从管
道读取并监视文件描述符而不会阻塞事件循环的 API。 此外，asyncio 的 *note
子进程: 24f9. API 提供了一种启动进程并从事件循环与其通信的办法。 最后，
之前提到的 *note loop.run_in_executor(): 2506. 方法也可配合 *note
concurrent.futures.ProcessPoolExecutor: 2a4. 使用以在另一个进程中执行代
码。


File: python.info,  Node: 运行阻塞的代码,  Next: 日志记录<3>,  Prev: 并发性和多线程,  Up: 用 asyncio 开发

5.18.1.120 运行阻塞的代码
.........................

不应该直接调用阻塞( CPU 绑定)代码。例如，如果一个函数执行1秒的 CPU 密集
型计算，那么所有并发异步任务和 IO 操作都将延迟1秒。

可以用执行器在不同的线程甚至不同的进程中运行任务，以避免使用事件循环阻塞
OS 线程。 请参阅 *note loop.run_in_executor(): 2506. 方法了解详情。


File: python.info,  Node: 日志记录<3>,  Next: 检测 never-awaited 协同程序,  Prev: 运行阻塞的代码,  Up: 用 asyncio 开发

5.18.1.121 日志记录
...................

asyncio使用 *note logging: ab. 模块，所有日志记录都是通过 ‘"asyncio"’
logger执行的。

默认日志级别是 ‘logging.INFO’ 。可以很容易地调整:

     logging.getLogger("asyncio").setLevel(logging.WARNING)


File: python.info,  Node: 检测 never-awaited 协同程序,  Next: 检测就再也没异常,  Prev: 日志记录<3>,  Up: 用 asyncio 开发

5.18.1.122 检测 never-awaited 协同程序
......................................

当协程函数被调用而不是被等待时 (即执行 ‘coro()’ 而不是 ‘await coro()’) 或
者协程没有通过 *note asyncio.create_task(): 1af. 被排入计划日程，asyncio
将会发出一条 *note RuntimeWarning: 2c1.:

     import asyncio

     async def test():
         print("never scheduled")

     async def main():
         test()

     asyncio.run(main())

输出:

     test.py:7: RuntimeWarning: coroutine 'test' was never awaited
       test()

调试模式的输出:

     test.py:7: RuntimeWarning: coroutine 'test' was never awaited
     Coroutine created at (most recent call last)
       File "../t.py", line 9, in <module>
         asyncio.run(main(), debug=True)

       < .. >

       File "../t.py", line 7, in main
         test()
       test()

通常的修复方法是等待协程或者调用 *note asyncio.create_task(): 1af. 函数:

     async def main():
         await test()


File: python.info,  Node: 检测就再也没异常,  Prev: 检测 never-awaited 协同程序,  Up: 用 asyncio 开发

5.18.1.123 检测就再也没异常
...........................

如果调用 *note Future.set_exception(): 251a. ，但不等待 Future 对象，将
异常传播到用户代码。在这种情况下，当 Future 对象被垃圾收集时，asyncio将
发出一条日志消息。

未处理异常的例子:

     import asyncio

     async def bug():
         raise Exception("not consumed")

     async def main():
         asyncio.create_task(bug())

     asyncio.run(main())

输出:

     Task exception was never retrieved
     future: <Task finished coro=<bug() done, defined at test.py:3>
       exception=Exception('not consumed')>

     Traceback (most recent call last):
       File "test.py", line 4, in bug
         raise Exception("not consumed")
     Exception: not consumed

*note 激活调试模式: 1360. 以获取任务创建处的跟踪信息:

     asyncio.run(main(), debug=True)

调试模式的输出:

     Task exception was never retrieved
     future: <Task finished coro=<bug() done, defined at test.py:3>
         exception=Exception('not consumed') created at asyncio/tasks.py:321>

     source_traceback: Object created at (most recent call last):
       File "../t.py", line 9, in <module>
         asyncio.run(main(), debug=True)

     < .. >

     Traceback (most recent call last):
       File "../t.py", line 4, in bug
         raise Exception("not consumed")
     Exception: not consumed

     注解: asyncio 的源代码可以在 Lib/asyncio/(1) 中找到。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/asyncio/


File: python.info,  Node: socket --- 底层网络接口,  Next: ssl --- 套接字对象的TLS/SSL封装,  Prev: asyncio --- 异步 I/O,  Up: 网络和进程间通信

5.18.2 ‘socket’ — 底层网络接口
------------------------------

`源代码:' Lib/socket.py(1)

__________________________________________________________________

这个模块提供了访问 BSD `套接字' 的接口。在所有现代 Unix 系统、Windows、
macOS 和其他一些平台上可用。

     注解: 一些行为可能因平台不同而异，因为调用的是操作系统的套接字API。

这个Python接口是用Python的面向对象风格对Unix系统调用和套接字库接口的直译
：函数 *note socket(): 67d. 返回一个 `套接字对象' ，其方法是对各种套接字
系统调用的实现。形参类型一般与C接口相比更高级：例如在Python文件 ‘read()’
和 ‘write()’ 操作中，接收操作的缓冲区分配是自动的，发送操作的缓冲区长度
是隐式的。

参见
....

模块 *note socketserver: f1.

     用于简化网络服务端编写的类。

模块 *note ssl: f4.

     套接字对象的TLS/SSL封装。

* Menu:

* 套接字协议族::
* 模块内容: 模块内容<4>.
* 套接字对象::
* 关于套接字超时的说明::
* 示例: 示例<8>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/socket.py


File: python.info,  Node: 套接字协议族,  Next: 模块内容<4>,  Up: socket --- 底层网络接口

5.18.2.1 套接字协议族
.....................

根据系统以及构建选项，此模块提供了各种套接字协议簇。

特定的套接字对象需要的地址格式将根据此套接字对象被创建时指定的地址族被自
动选择。套接字地址表示如下：

   - 一个绑定在文件系统节点上的 *note AF_UNIX: 25be. 套接字的地址表示为
     一个字符串，使用文件系统字符编码和 ‘'surrogateescape'’ 错误回调方法
     （see PEP 383(1)）。一个地址在 Linux 的抽象命名空间被返回为带有初始
     的 null 字节的 *note 字节类对象: 5f1. ；注意在这个命名空间种的套接
     字可能与普通文件系统套接字通信，所以打算运行在 Linux 上的程序可能需
     要解决两种地址类型。当传递为参数时，一个字符串或字节类对象可以用于
     任一类型的地址。

     在 3.3 版更改: 之前，*note AF_UNIX: 25be. 套接字路径被假设使用
     UTF-8 编码。

     在 3.5 版更改: 现在支持可写的 *note 字节类对象: 5f1.。

   - 一对 ‘(host, port)’ 被用于 *note AF_INET: 25b8. 地址族，`host' 是一
     个表示为互联网域名表示法之内的主机名或者一个 IPv4 地址的字符串，例
     如 ‘'daring.cwi.nl'’ 或 ‘'100.50.200.5'’，`port' 是一个整数。

        - 对于 IPv4 地址，有两种可接受的特殊形式被用来代替一个主机地址：
          ‘''’ 代表 ‘INADDR_ANY’，用来绑定到所有接口；字符串
          ‘'<broadcast>'’ 代表 ‘INADDR_BROADCAST’。此行为不兼容 IPv6，因
          此，如果你的 Python 程序打算支持 IPv6，则可能需要避开这些。

   - 对于 *note AF_INET6: 25b9. 地址族，使用一个四元组 ‘(host, port,
     flowinfo, scopeid)’，其中 `flowinfo' 和 `scopeid' 代表了 C 库
     ‘struct sockaddr_in6’ 中的 ‘sin6_flowinfo’ 和 ‘sin6_scope_id’ 成员
     。对于 *note socket: f0. 模块中的方法， `flowinfo' 和 `scopeid' 可
     以被省略，只为了向后兼容。注意，省略 `scopeid' 可能会导致操作带有领
     域 (Scope) 的 IPv6 地址时出错。

     在 3.7 版更改: 对于多播地址（其 `scopeid' 起作用），`地址' 中可以不
     包含 ‘%scope’ （或 ‘zone id’ ）部分，这部分是多余的，可以放心省略（
     推荐）。

   - ‘AF_NETLINK’ 套接字由一对 ‘(pid, groups)’ 表示。

   - 指定 ‘AF_TIPC’ 地址族可以使用仅 Linux 支持的 TIPC 协议。TIPC 是一种
     开放的、非基于 IP 的网络协议，旨在用于集群计算环境。其地址用元组表
     示，其中的字段取决于地址类型。一般元组形式为 ‘(addr_type, v1, v2,
     v3 [, scope])’，其中：

        - `addr_type' 取 ‘TIPC_ADDR_NAMESEQ’、‘TIPC_ADDR_NAME’ 或
          ‘TIPC_ADDR_ID’ 中的一个。

        - `scope' 取 ‘TIPC_ZONE_SCOPE’、‘TIPC_CLUSTER_SCOPE’ 和
          ‘TIPC_NODE_SCOPE’ 中的一个。

        - 如果 `addr_type' 为 ‘TIPC_ADDR_NAME’，那么 `v1' 是服务器类型，
          `v2' 是端口标识符，`v3' 应为 0。

          如果 `addr_type' 为 ‘TIPC_ADDR_NAMESEQ’，那么 `v1' 是服务器类
          型，`v2' 是端口号下限，而 `v3' 是端口号上限。

          如果 `addr_type' 为 ‘TIPC_ADDR_ID’，那么 `v1' 是节点 (node)，
          `v2' 是 ref，`v3' 应为 0。

   - *note AF_CAN: 2676. 地址族使用元组 ‘(interface, )’，其中
     `interface' 是表示网络接口名称的字符串，如 ‘'can0'’。网络接口名
     ‘''’ 可以用于接收本族所有网络接口的数据包。

        - *note CAN_ISOTP: 2677. 协议接受一个元组 ‘(interface, rx_addr,
          tx_addr)’，其中两个额外参数都是无符号长整数，都表示 CAN 标识符
          （标准或扩展标识符）。

   - ‘PF_SYSTEM’ 协议簇的 ‘SYSPROTO_CONTROL’ 协议接受一个字符串或元组
     ‘(id, unit)’。其中字符串是内核控件的名称，该控件使用动态分配的 ID。
     而如果 ID 和内核控件的单元 (unit) 编号都已知，或使用了已注册的 ID，
     可以采用元组。

     3.3 新版功能.

   - ‘AF_BLUETOOTH’ 支持以下协议和地址格式：

        - ‘BTPROTO_L2CAP’ 接受 ‘(bdaddr, psm)’，其中 ‘bdaddr’ 为字符串格
          式的蓝牙地址，‘psm’ 是一个整数。

        - ‘BTPROTO_RFCOMM’ 接受 ‘(bdaddr, channel)’，其中 ‘bdaddr’ 为字
          符串格式的蓝牙地址，‘channel’ 是一个整数。

        - ‘BTPROTO_HCI’ 接受 ‘(device_id,)’，其中 ‘device_id’ 为整数或字
          符串，它表示接口对应的蓝牙地址（具体取决于你的系统，NetBSD 和
          DragonFlyBSD 需要蓝牙地址字符串，其他系统需要整数）。

          在 3.2 版更改: 添加了对 NetBSD 和 DragonFlyBSD 的支持。

        - ‘BTPROTO_SCO’ 接受 ‘bdaddr’，其中 ‘bdaddr’ 是 *note bytes:
          33a. 对象，其中含有字符串格式的蓝牙地址（如
          ‘b'12:23:34:45:56:67'’ ），FreeBSD 不支持此协议。

   - *note AF_ALG: 58d. 是一个仅 Linux 可用的、基于套接字的接口，用于连
     接内核加密算法。算法套接字可用包括 2 至 4 个元素的元组来配置
     ‘(type, name [, feat [, mask]])’，其中：

        - `type' 是表示算法类型的字符串，如 ‘aead’、‘hash’、‘skcipher’ 或
          ‘rng’。

        - `name' 是表示算法类型和操作模式的字符串，如 ‘sha256’、
          ‘hmac(sha256)’、‘cbc(aes)’ 或 ‘drbg_nopr_ctr_aes256’。

        - `feat' 和 `mask' 是无符号 32 位整数。

     *note Availability: 136f.: Linux 2.6.38, some algorithm types
     require more recent Kernels.

     3.6 新版功能.

   - *note AF_VSOCK: 3db. 用于支持虚拟机与宿主机之间的通讯。该套接字用
     ‘(CID, port)’ 元组表示，其中 Context ID (CID) 和 port 都是整数。

     *note Availability: 136f.: Linux >= 4.8 QEMU >= 2.8 ESX >= 4.0 ESX
     Workstation >= 6.5.

     3.7 新版功能.

   - *note AF_PACKET: 2678. 是一个底层接口，直接连接至网卡。数据包使用元
     组 ‘(ifname, proto[, pkttype[, hatype[, addr]]])’ 表示，其中：

        - `ifname' - 指定设备名称的字符串。

        - `proto' - 一个用网络字节序表示的整数，指定以太网协议版本号。

        - `pkttype' - 指定数据包类型的整数（可选）：

             - ‘PACKET_HOST’ （默认） - 寻址到本地主机的数据包。

             - ‘PACKET_BROADCAST’ - 物理层广播的数据包。

             - ‘PACKET_MULTIHOST’ - 发送到物理层多播地址的数据包。

             - ‘PACKET_OTHERHOST’ - 被（处于混杂模式的）网卡驱动捕获的、
               发送到其他主机的数据包。

             - ‘PACKET_OUTGOING’ - 来自本地主机的、回环到一个套接字的数
               据包。

        - `hatype' - 可选整数，指定 ARP 硬件地址类型。

        - `addr' - 可选的类字节串对象，用于指定硬件物理地址，其解释取决
          于各设备。

   - *note AF_QIPCRTR: 2679. 是一个仅 Linux 可用的、基于套接字的接口，用
     于与高通平台中协处理器上运行的服务进行通信。该地址簇用一个 ‘(node,
     port)’ 元组表示，其中 `node' 和 `port' 为非负整数。

     3.8 新版功能.

如果你在 IPv4/v6 套接字地址的 `host' 部分中使用了一个主机名，此程序可能
会表现不确定行为，因为 Python 使用 DNS 解析返回的第一个地址。套接字地址
在实际的 IPv4/v6 中以不同方式解析，根据 DNS 解析和/或 host 配置。为了确
定行为，在 `host' 部分中使用数字的地址。

所有的错误都抛出异常。对于无效的参数类型和内存溢出异常情况可能抛出普通异
常；从 Python 3.3 开始，与套接字或地址语义有关的错误抛出 *note OSError:
1d4. 或它的子类之一（常用 *note socket.error: 99d.）。

可以用 *note setblocking(): 1f20. 设置非阻塞模式。一个基于超时的
generalization 通过 *note settimeout(): 267a. 支持。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0383


File: python.info,  Node: 模块内容<4>,  Next: 套接字对象,  Prev: 套接字协议族,  Up: socket --- 底层网络接口

5.18.2.2 模块内容
.................

*note socket: f0. 模块导出以下元素。

* Menu:

* 异常: 异常<11>.
* 常量: 常量<8>.
* 函数: 函数<5>.


File: python.info,  Node: 异常<11>,  Next: 常量<8>,  Up: 模块内容<4>

5.18.2.3 异常
.............

 -- 例外: socket.error

     一个被弃用的 *note OSError: 1d4. 的别名。

     在 3.3 版更改: 根据 PEP 3151(1)，这个类是 *note OSError: 1d4. 的别
     名。

 -- 例外: socket.herror

     *note OSError: 1d4. 的子类，本异常通常表示与地址相关的错误，比如那
     些在 POSIX C API 中使用了 `h_errno' 的函数，包括 *note
     gethostbyname_ex(): eae. 和 *note gethostbyaddr(): ead.。附带的值是
     一对 ‘(h_errno, string)’，代表库调用返回的错误。`h_errno' 是一个数
     字，而 `string' 表示 `h_errno' 的描述，它们由 C 函数 ‘hstrerror()’
     返回。

     在 3.3 版更改: 此类是 *note OSError: 1d4. 的子类。

 -- 例外: socket.gaierror

     *note OSError: 1d4. 的子类，本异常来自 *note getaddrinfo(): 25cc. 和
     *note getnameinfo(): 25cd.，表示与地址相关的错误。附带的值是一对
     ‘(error, string)’，代表库调用返回的错误。`string' 表示 `error' 的描
     述，它由 C 函数 ‘gai_strerror()’ 返回。数字值 `error' 与本模块中定
     义的 ‘EAI_*’ 常量之一匹配。

     在 3.3 版更改: 此类是 *note OSError: 1d4. 的子类。

 -- 例外: socket.timeout

     *note OSError: 1d4. 的子类，当套接字发生超时，且事先已调用过 *note
     settimeout(): 267a. （或隐式地通过 *note setdefaulttimeout(): 267f.
     ）启用了超时，则会抛出此异常。附带的值是一个字符串，其值总是 "timed
     out"。

     在 3.3 版更改: 此类是 *note OSError: 1d4. 的子类。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3151


File: python.info,  Node: 常量<8>,  Next: 函数<5>,  Prev: 异常<11>,  Up: 模块内容<4>

5.18.2.4 常量
.............

     AF_* 和 SOCK_* 常量现在都在 ‘AddressFamily’ 和 ‘SocketKind’ 这两个
     *note IntEnum: 596. 集合内。

     3.4 新版功能.

 -- 数据: socket.AF_UNIX
 -- 数据: socket.AF_INET
 -- 数据: socket.AF_INET6

     这些常量表示地址（和协议）簇，用于 *note socket(): 67d. 的第一个参
     数。如果 *note AF_UNIX: 25be. 常量未定义，即表示不支持该协议。不同
     系统可能会有更多其他常量可用。

 -- 数据: socket.SOCK_STREAM
 -- 数据: socket.SOCK_DGRAM
 -- 数据: socket.SOCK_RAW
 -- 数据: socket.SOCK_RDM
 -- 数据: socket.SOCK_SEQPACKET

     这些常量表示套接字类型，用于 *note socket(): 67d. 的第二个参数。不
     同系统可能会有更多其他常量可用。（一般只有 *note SOCK_STREAM: c92.
     和 *note SOCK_DGRAM: c91. 可用）

 -- 数据: socket.SOCK_CLOEXEC
 -- 数据: socket.SOCK_NONBLOCK

     这两个常量（如果已定义）可以与上述套接字类型结合使用，允许你设置这
     些原子性相关的 flags （从而避免可能的竞争条件和单独调用的需要）。

     参见
     ....

     Secure File Descriptor Handling （安全地处理文件描述符）(1) 提供了
     更详尽的解释。

     *note 可用性: 136f.： Linux >= 2.6.27。

     3.2 新版功能.

 -- 数据: SO_*
 -- 数据: socket.SOMAXCONN

 -- 数据: MSG_*

 -- 数据: SOL_*

 -- 数据: SCM_*

 -- 数据: IPPROTO_*

 -- 数据: IPPORT_*

 -- 数据: INADDR_*

 -- 数据: IP_*

 -- 数据: IPV6_*

 -- 数据: EAI_*

 -- 数据: AI_*

 -- 数据: NI_*

 -- 数据: TCP_*

     此列表内的许多常量，记载在 Unix 文档中的套接字和/或 IP 协议部分，同
     时也定义在本 socket 模块中。它们通常用于套接字对象的 ‘setsockopt()’
     和 ‘getsockopt()’ 方法的参数中。在大多数情况下，仅那些在 Unix 头文
     件中有定义的符号会在本模块中定义，部分符号提供了默认值。

     在 3.6 版更改: 添加了 ‘SO_DOMAIN’, ‘SO_PROTOCOL’, ‘SO_PEERSEC’,
     ‘SO_PASSSEC’, ‘TCP_USER_TIMEOUT’, ‘TCP_CONGESTION’。

     在 3.6.5 版更改: 在 Windows 上，如果 Windows 运行时支持，则
     ‘TCP_FASTOPEN’、‘TCP_KEEPCNT’ 可用。

     在 3.7 版更改: 添加了 ‘TCP_NOTSENT_LOWAT’。

     在 Windows 上，如果 Windows 运行时支持，则 ‘TCP_KEEPIDLE’、
     ‘TCP_KEEPINTVL’ 可用。

 -- 数据: socket.AF_CAN
 -- 数据: socket.PF_CAN

 -- 数据: SOL_CAN_*

 -- 数据: CAN_*

     此列表内的许多常量，记载在 Linux 文档中，同时也定义在本 socket 模块
     中。

     *note 可用性: 136f.： Linux >= 2.6.25。

     3.3 新版功能.

 -- 数据: socket.CAN_BCM

 -- 数据: CAN_BCM_*

     CAN 协议簇内的 CAN_BCM 是广播管理器（Bbroadcast Manager – BCM）协议
     ，广播管理器常量在 Linux 文档中有所记载，在本 socket 模块中也有定义
     。

     *note 可用性: 136f.： Linux >= 2.6.25。

          注解: ‘CAN_BCM_CAN_FD_FRAME’ 旗标仅在 Linux >= 4.8 时可用。

     3.4 新版功能.

 -- 数据: socket.CAN_RAW_FD_FRAMES

     在 CAN_RAW 套接字中启用 CAN FD 支持，默认是禁用的。它使应用程序可以
     发送 CAN 和 CAN FD 帧。但是，从套接字读取时，也必须同时接受 CAN 和
     CAN FD 帧。

     此常量在 Linux 文档中有所记载。

     *note 可用性: 136f.： Linux >= 3.6。

     3.5 新版功能.

 -- 数据: socket.CAN_ISOTP

     CAN 协议簇中的 CAN_ISOTP 就是 ISO-TP (ISO 15765-2) 协议。ISO-TP 常
     量在 Linux 文档中有所记载。

     *note 可用性: 136f.： Linux >= 2.6.25。

     3.7 新版功能.

 -- 数据: socket.AF_PACKET
 -- 数据: socket.PF_PACKET

 -- 数据: PACKET_*

     此列表内的许多常量，记载在 Linux 文档中，同时也定义在本 socket 模块
     中。

     *note 可用性: 136f.： Linux >= 2.2。

 -- 数据: socket.AF_RDS
 -- 数据: socket.PF_RDS
 -- 数据: socket.SOL_RDS

 -- 数据: RDS_*

     此列表内的许多常量，记载在 Linux 文档中，同时也定义在本 socket 模块
     中。

     *note 可用性: 136f.： Linux >= 2.6.30。

     3.3 新版功能.

 -- 数据: socket.SIO_RCVALL
 -- 数据: socket.SIO_KEEPALIVE_VALS
 -- 数据: socket.SIO_LOOPBACK_FAST_PATH

 -- 数据: RCVALL_*

     Windows 的 WSAIoctl() 的常量。这些常量用于套接字对象的 *note
     ioctl(): 589. 方法的参数。

     在 3.6 版更改: 添加了 ‘SIO_LOOPBACK_FAST_PATH’。

 -- 数据: TIPC_*

     TIPC 相关常量，与 C socket API 导出的常量一致。更多信息请参阅 TIPC
     文档。

 -- 数据: socket.AF_ALG
 -- 数据: socket.SOL_ALG

 -- 数据: ALG_*

     用于 Linux 内核加密算法的常量。

     *note 可用性: 136f.： Linux >= 2.6.38。

     3.6 新版功能.

 -- 数据: socket.AF_VSOCK
 -- 数据: socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID

 -- 数据: VMADDR*

 -- 数据: SO_VM*

     用于 Linux 宿主机/虚拟机通讯的常量。

     *note 可用性: 136f.： Linux >= 4.8。

     3.7 新版功能.

 -- 数据: socket.AF_LINK

     *note 可用性: 136f.： BSD、OSX。

     3.4 新版功能.

 -- 数据: socket.has_ipv6

     本常量为一个布尔值，该值指示当前平台是否支持 IPv6。

 -- 数据: socket.BDADDR_ANY
 -- 数据: socket.BDADDR_LOCAL

     这些是字符串常量，包含蓝牙地址，这些地址具有特殊含义。例如，当用
     ‘BTPROTO_RFCOMM’ 指定绑定套接字时， *note BDADDR_ANY: 268e. 表示“任
     何地址”。

 -- 数据: socket.HCI_FILTER
 -- 数据: socket.HCI_TIME_STAMP
 -- 数据: socket.HCI_DATA_DIR

     与 ‘BTPROTO_HCI’ 一起使用。 *note HCI_FILTER: 2690. 在 NetBSD 或
     DragonFlyBSD 上不可用。 *note HCI_TIME_STAMP: 2691. 和 *note
     HCI_DATA_DIR: 2692. 在 FreeBSD、NetBSD 或 DragonFlyBSD 上不可用。

 -- 数据: socket.AF_QIPCRTR

     高通 IPC 路由协议的常数，用于与提供远程处理器的服务进行通信。

     *note 可用性: 136f.： Linux >= 4.7。

   ---------- Footnotes ----------

   (1) http://udrepper.livejournal.com/20407.html


File: python.info,  Node: 函数<5>,  Prev: 常量<8>,  Up: 模块内容<4>

5.18.2.5 函数
.............

* Menu:

* 创建套接字::
* 其他功能: 其他功能<2>.


File: python.info,  Node: 创建套接字,  Next: 其他功能<2>,  Up: 函数<5>

5.18.2.6 创建套接字
...................

下列函数都能创建 *note 套接字对象: 2695.

 -- 函数: socket.socket (family=AF_INET, type=SOCK_STREAM, proto=0,
          fileno=None)

     使用给定的地址簇、套接字类型和协议号创建一个新的套接字。地址簇应为
     *note AF_INET: 25b8. （默认）、*note AF_INET6: 25b9.、*note
     AF_UNIX: 25be.、*note AF_CAN: 2676.、*note AF_PACKET: 2678. 或
     *note AF_RDS: 2686. 其中之一。套接字类型应为 *note SOCK_STREAM:
     c92. （默认）、*note SOCK_DGRAM: c91.、*note SOCK_RAW: 2681. 或其他
     ‘SOCK_’ 常量之一。协议号通常为零，可以省略，或者在地址簇为 *note
     AF_CAN: 2676. 的情况下，协议号应为 ‘CAN_RAW’、*note CAN_BCM: 8c2. 或
     *note CAN_ISOTP: 2677. 之一。

     如果指定了 `fileno'，那么将从这一指定的文件描述符中自动检测
     `family'、`type' 和 `proto' 的值。如果调用本函数时显式指定了
     `family'、`type' 或 `proto' 参数，可以覆盖自动检测的值。这只会影响
     Python 表示诸如 *note socket.getpeername(): 2602. 一类函数的返回值
     的方式，而不影响实际的操作系统资源。与 *note socket.fromfd(): 2696.
     不同，`fileno' 将返回原先的套接字，而不是复制出新的套接字。这有助于
     在分离的套接字上调用 *note socket.close(): 3d9. 来关闭它。

     新创建的套接字是 *note 不可继承的: 803.。

     引发一个 *note 审计事件: ea1. ‘socket.__new__’ 附带参数 ‘self’、
     ‘family’、‘type’、‘protocol’。

     在 3.3 版更改: 添加了 AF_CAN 簇。添加了 AF_RDS 簇。

     在 3.4 版更改: 添加了 CAN_BCM 协议。

     在 3.4 版更改: 返回的套接字现在是不可继承的。

     在 3.7 版更改: 添加了 CAN_ISOTP 协议。

     在 3.7 版更改: 当将 *note SOCK_NONBLOCK: 49e. 或 *note
     SOCK_CLOEXEC: 49f. 标志位应用于 `type' 上时，它们会被清除，且 *note
     socket.type: 4a0. 反映不出它们。但它们仍将传递给底层系统的
     ‘socket()’ 调用。因此，

          sock = socket.socket(
              socket.AF_INET,
              socket.SOCK_STREAM | socket.SOCK_NONBLOCK)

     仍将在支持 ‘SOCK_NONBLOCK’ 的系统上创建一个非阻塞的套接字，但是
     ‘sock.type’ 会被置为 ‘socket.SOCK_STREAM’。

 -- 函数: socket.socketpair ([family[, type[, proto]]])

     构建一对已连接的套接字对象，使用给定的地址簇、套接字类型和协议号。
     地址簇、套接字类型和协议号与上述 *note socket(): 67d. 函数相同。默
     认地址簇为 *note AF_UNIX: 25be. （需要当前平台支持，不支持则默认为
     *note AF_INET: 25b8. ）。

     新创建的套接字都是 *note 不可继承的: 803.。

     在 3.2 版更改: 现在，返回的套接字对象支持全部套接字 API，而不是全部
     API 的一个子集。

     在 3.4 版更改: 返回的套接字现在都是不可继承的。

     在 3.5 版更改: 添加了 Windows 支持。

 -- 函数: socket.create_connection (address[, timeout[,
          source_address]])

     连接到一个 TCP 服务，该服务正在侦听 Internet `address' （用二元组
     ‘(host, port)’ 表示）。连接后返回套接字对象。这是比 *note
     socket.connect(): 67f. 更高级的函数：如果 `host' 是非数字主机名，它
     将尝试从 *note AF_INET: 25b8. 和 *note AF_INET6: 25b9. 解析它，然后
     依次尝试连接到所有可能的地址，直到连接成功。这使得编写兼容 IPv4 和
     IPv6 的客户端变得容易。

     传入可选参数 `timeout' 可以在套接字实例上设置超时（在尝试连接前）。
     如果未提供 `timeout'，则使用由 *note getdefaulttimeout(): 2697. 返
     回的全局默认超时设置。

     如果提供了 `source_address'，它必须为二元组 ‘(host, port)’，以便套
     接字在连接之前绑定为其源地址。如果 host 或 port 分别为 ’’ 或 0，则
     使用操作系统默认行为。

     在 3.2 版更改: 添加了*source_address* 参数

 -- 函数: socket.create_server (address, *, family=AF_INET,
          backlog=None, reuse_port=False, dualstack_ipv6=False)

     便捷函数，创建绑定到 `address' （二元组 ‘(host, port)’ ）的 TCP 套
     接字，返回套接字对象。

     `family' 应设置为 *note AF_INET: 25b8. 或 *note AF_INET6: 25b9.。
     `backlog' 是传递给 *note socket.listen(): 754. 的队列大小，当它为
     ‘0’ 则表示默认的合理值。`reuse_port' 表示是否设置 ‘SO_REUSEPORT’ 套
     接字选项。

     如果 `dualstack_ipv6' 为 true 且平台支持，则套接字能接受 IPv4 和
     IPv6 连接，否则将抛出 *note ValueError: 1fc. 异常。大多数 POSIX 平
     台和 Windows 应该支持此功能。启用此功能后，*note
     socket.getpeername(): 2602. 在进行 IPv4 连接时返回的地址将是一个（
     映射到 IPv4 的）IPv6 地址。在默认启用该功能的平台上（如 Linux），如
     果 `dualstack_ipv6' 为 false，即显式禁用此功能。该参数可以与 *note
     has_dualstack_ipv6(): 220. 结合使用：

          import socket

          addr = ("", 8080)  # all interfaces, port 8080
          if socket.has_dualstack_ipv6():
              s = socket.create_server(addr, family=socket.AF_INET6, dualstack_ipv6=True)
          else:
              s = socket.create_server(addr)

          注解: 在 POSIX 平台上，设置 ‘SO_REUSEADDR’ 套接字选项是为了立
          即重用以前绑定在同一 `address' 上并保持 TIME_WAIT 状态的套接字
          。

     3.8 新版功能.

 -- 函数: socket.has_dualstack_ipv6 ()

     如果平台支持创建 IPv4 和 IPv6 连接都可以处理的 TCP 套接字，则返回
     ‘True’。

     3.8 新版功能.

 -- 函数: socket.fromfd (fd, family, type, proto=0)

     复制文件描述符 `fd' （一个由文件对象的 ‘fileno()’ 方法返回的整数）
     ，然后从结果中构建一个套接字对象。地址簇、套接字类型和协议号与上述
     *note socket(): 67d. 函数相同。文件描述符应指向一个套接字，但不会专
     门去检查——如果文件描述符是无效的，则对该对象的后续操作可能会失败。
     本函数很少用到，但是在将套接字作为标准输入或输出传递给程序（如 Unix
     inet 守护程序启动的服务器）时，可以使用本函数获取或设置套接字选项。
     套接字将处于阻塞模式。

     新创建的套接字是 *note 不可继承的: 803.。

     在 3.4 版更改: 返回的套接字现在是不可继承的。

 -- 函数: socket.fromshare (data)

     根据 *note socket.share(): 49b. 方法获得的数据实例化套接字。套接字
     将处于阻塞模式。

     *note 可用性: 136f.: Windows。

     3.3 新版功能.

 -- 数据: socket.SocketType

     这是一个 Python 类型对象，表示套接字对象的类型。它等同于
     ‘type(socket(...))’。


File: python.info,  Node: 其他功能<2>,  Prev: 创建套接字,  Up: 函数<5>

5.18.2.7 其他功能
.................

*note socket: f0. 模块还提供多种网络相关服务：

 -- 函数: socket.close (fd)

     关闭一个套接字文件描述符。它类似于 *note os.close(): 3da.，但专用于
     套接字。在某些平台上（特别是在 Windows 上），*note os.close(): 3da.
     对套接字文件描述符无效。

     3.7 新版功能.

 -- 函数: socket.getaddrinfo (host, port, family=0, type=0, proto=0,
          flags=0)

     将 `host'/`port' 参数转换为 5 元组的序列，其中包含创建（连接到某服
     务的）套接字所需的所有参数。`host' 是域名，是字符串格式的 IPv4/v6 地
     址或 ‘None’。`port' 是字符串格式的服务名称，如 ‘'http'’ 、端口号（
     数字）或 ‘None’。传入 ‘None’ 作为 `host' 和 `port' 的值，相当于将
     ‘NULL’ 传递给底层 C API。

     可以指定 `family'、`type' 和 `proto' 参数，以缩小返回的地址列表。向
     这些参数分别传入 0 表示保留全部结果范围。`flags' 参数可以是 ‘AI_*’
     常量中的一个或多个，它会影响结果的计算和返回。例如，
     ‘AI_NUMERICHOST’ 会禁用域名解析，此时如果 `host' 是域名，则会抛出错
     误。

     本函数返回一个列表，其中的 5 元组具有以下结构：

     ‘(family, type, proto, canonname, sockaddr)’

     在这些元组中，`family'、`type'、`proto' 都是整数，可以用于传递给
     *note socket(): 67d. 函数。如果 `flags' 参数有一部分是
     ‘AI_CANONNAME’，那么 `canonname' 将是表示 `host' 的规范名称的字符串
     。否则 `canonname' 将为空。`sockaddr' 是一个表示套接字地址的元组，
     具体格式取决于返回的 `family' （对于 *note AF_INET: 25b8.，是一个
     ‘(address, port)’ 二元组，对于 *note AF_INET6: 25b9.，是一个
     ‘(address, port, flow info, scope id)’ 四元组），可以用于传递给
     *note socket.connect(): 67f. 方法。

     引发一个 *note 审计事件: ea1. ‘socket.getaddrinfo’ 附带参数 ‘host’、
     ‘port’、‘family’、‘type’、‘protocol’。

     下面的示例获取了 TCP 连接地址信息，假设该连接通过 80 端口连接至
     ‘example.org’ （如果系统未启用 IPv6，则结果可能会不同）:

          >>> socket.getaddrinfo("example.org", 80, proto=socket.IPPROTO_TCP)
          [(<AddressFamily.AF_INET6: 10>, <SocketType.SOCK_STREAM: 1>,
           6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),
           (<AddressFamily.AF_INET: 2>, <SocketType.SOCK_STREAM: 1>,
           6, '', ('93.184.216.34', 80))]

     在 3.2 版更改: 现在可以使用关键字参数的形式来传递参数。

     在 3.7 版更改: 对于 IPv6 多播地址，表示地址的字符串将不包含
     ‘%scope’ 部分。

 -- 函数: socket.getfqdn ([name])

     返回 `name' 的全限定域名 (Fully Qualified Domain Name – FQDN)。如果
     `name' 省略或为空，则将其解释为本地主机。为了查找全限定名称，首先将
     检查由 *note gethostbyaddr(): ead. 返回的主机名，然后是主机的别名（
     如果存在）。选中第一个包含句点的名字。如果无法获取全限定域名，则返
     回由 *note gethostname(): 1f14. 返回的主机名。

 -- 函数: socket.gethostbyname (hostname)

     将主机名转换为 IPv4 地址格式。IPv4 地址以字符串格式返回，如
     ‘'100.50.200.5'’。如果主机名本身是 IPv4 地址，则原样返回。更完整的
     接口请参考 *note gethostbyname_ex(): eae.。 *note gethostbyname():
     269b. 不支持 IPv6 名称解析，应使用 *note getaddrinfo(): 25cc. 来支
     持 IPv4/v6 双协议栈。

     引发一个 *note 审计事件: ea1. ‘socket.gethostbyname’，附带参数
     ‘hostname’。

 -- 函数: socket.gethostbyname_ex (hostname)

     将主机名转换为 IPv4 地址格式的扩展接口。返回三元组 ‘(hostname,
     aliaslist, ipaddrlist)’，其中 `hostname' 是响应给定 `ip_address' 的
     主要主机名，`aliaslist' 是相同地址的其他可用主机名的列表（可能为空
     ），而 `ipaddrlist' 是 IPv4 地址列表，包含相同主机名、相同接口的不
     同地址（通常是一个地址，但不总是如此）。*note gethostbyname_ex():
     eae. 不支持 IPv6 名称解析，应使用 *note getaddrinfo(): 25cc. 来支持
     IPv4/v6 双协议栈。

     引发一个 *note 审计事件: ea1. ‘socket.gethostbyname’，附带参数
     ‘hostname’。

 -- 函数: socket.gethostname ()

     返回一个字符串，包含当前正在运行 Python 解释器的机器的主机名。

     引发一个 *note 审计事件: ea1. ‘socket.gethostname’，没有附带参数。

     注意： *note gethostname(): 1f14. 并不总是返回全限定域名，必要的话
     请使用 *note getfqdn(): 269a.。

 -- 函数: socket.gethostbyaddr (ip_address)

     返回三元组 ‘(hostname, aliaslist, ipaddrlist)’，其中 `hostname' 是
     响应给定 `ip_address' 的主要主机名，`aliaslist' 是相同地址的其他可
     用主机名的列表（可能为空），而 `ipaddrlist' 是 IPv4/v6 地址列表，包
     含相同主机名、相同接口的不同地址（很可能仅包含一个地址）。要查询全
     限定域名，请使用函数 *note getfqdn(): 269a.。*note gethostbyaddr():
     ead. 支持 IPv4 和 IPv6。

     引发一个 *note 审计事件: ea1. ‘socket.gethostbyaddr’，附带参数
     ‘ip_address’。

 -- 函数: socket.getnameinfo (sockaddr, flags)

     将套接字地址 `sockaddr' 转换为二元组 ‘(host, port)’。`host' 的形式
     可能是全限定域名，或是由数字表示的地址，具体取决于 `flags' 的设置。
     同样，`port' 可以包含字符串格式的端口名称或数字格式的端口号。

     对于 IPv6 地址，如果 `sockaddr' 包含有意义的 `scopeid'，则将
     ‘%scope’ 附加到 host 部分。这种情况通常发生在多播地址上。

     关于 `flags' 的更多信息可参阅 ‘getnameinfo(3)’。

     引发一个 *note 审计事件: ea1. ‘socket.getnameinfo’，附带参数
     ‘sockaddr’。

 -- 函数: socket.getprotobyname (protocolname)

     将 Internet 协议名称（如 ‘'icmp'’ ）转换为常量，该常量适用于 *note
     socket(): 67d. 函数的第三个（可选）参数。通常只有在 "raw" 模式
     (*note SOCK_RAW: 2681.) 中打开的套接字才需要使用该常量。在正常的套
     接字模式下，协议省略或为零时，会自动选择正确的协议。

 -- 函数: socket.getservbyname (servicename[, protocolname])

     将 Internet 服务名称和协议名称转换为该服务的端口号。协议名称是可选
     的，如果提供的话应为 ‘'tcp'’ 或 ‘'udp'’，否则将匹配出所有协议。

     引发一个 *note 审计事件: ea1. ‘socket.getservbyname’，附带参数
     ‘servicename’、‘protocolname’。

 -- 函数: socket.getservbyport (port[, protocolname])

     将 Internet 端口号和协议名称转换为该服务的服务名称。协议名称是可选
     的，如果提供的话应为 ‘'tcp'’ 或 ‘'udp'’，否则将匹配出所有协议。

     引发一个 *note 审计事件: ea1. ‘socket.getservbyport’，附带参数
     ‘port’、‘protocolname’。

 -- 函数: socket.ntohl (x)

     将 32 位正整数从网络字节序转换为主机字节序。在主机字节序与网络字节
     序相同的计算机上，这是一个空操作。字节序不同将执行 4 字节交换操作。

 -- 函数: socket.ntohs (x)

     将 16 位正整数从网络字节序转换为主机字节序。在主机字节序与网络字节
     序相同的计算机上，这是一个空操作。字节序不同将执行 2 字节交换操作。

     3.7 版后已移除: 如果 `x' 不符合 16 位无符号整数，但符合 C 语言的正
     整数，则它会被静默截断为 16 位无符号整数。此静默截断功能已弃用，未
     来版本的 Python 将对此抛出异常。

 -- 函数: socket.htonl (x)

     将 32 位正整数从主机字节序转换为网络字节序。在主机字节序与网络字节
     序相同的计算机上，这是一个空操作。字节序不同将执行 4 字节交换操作。

 -- 函数: socket.htons (x)

     将 16 位正整数从主机字节序转换为网络字节序。在主机字节序与网络字节
     序相同的计算机上，这是一个空操作。字节序不同将执行 2 字节交换操作。

     3.7 版后已移除: 如果 `x' 不符合 16 位无符号整数，但符合 C 语言的正
     整数，则它会被静默截断为 16 位无符号整数。此静默截断功能已弃用，未
     来版本的 Python 将对此抛出异常。

 -- 函数: socket.inet_aton (ip_string)

     将 IPv4 地址从点分十进制字符串格式（如 ’123.45.67.89’ ）转换为 32 位
     压缩二进制格式，转换后为字节对象，长度为四个字符。与那些使用标准 C
     库，且需要 ‘struct in_addr’ 类型的对象的程序交换信息时，此功能很有
     用。 该类型即此函数返回的 32 位压缩二进制的 C 类型。

     *note inet_aton(): 2f8. 也接受句点数少于三的字符串，详情请参阅 Unix
     手册 ‘inet(3)’。

     如果传入本函数的 IPv4 地址字符串无效，则抛出 *note OSError: 1d4.。
     注意，具体什么样的地址有效取决于 ‘inet_aton()’ 的底层 C 实现。

     *note inet_aton(): 2f8. 不支持 IPv6，在 IPv4/v6 双协议栈下应使用
     *note inet_pton(): 2f9. 来代替。

 -- 函数: socket.inet_ntoa (packed_ip)

     将 32 位压缩 IPv4 地址（一个 *note 类字节对象: 5f1.，长 4 个字节）
     转换为标准的点分十进制字符串形式（如 ’123.45.67.89’ ）。与那些使用
     标准 C 库，且需要 ‘struct in_addr’ 类型的对象的程序交换信息时，本函
     数很有用。 该类型即是本函数参数中的 32 位压缩二进制数据的 C 类型。

     如果传入本函数的字节序列长度不是 4 个字节，则抛出 *note OSError:
     1d4.。*note inet_ntoa(): 26a1. 不支持 IPv6，在 IPv4/v6 双协议栈下应
     使用 *note inet_ntop(): 8c4. 来代替。

     在 3.5 版更改: 现在支持可写的 *note 字节类对象: 5f1.。

 -- 函数: socket.inet_pton (address_family, ip_string)

     将特定地址簇的 IP 地址（字符串）转换为压缩二进制格式。当库或网络协
     议需要接受 ‘struct in_addr’ 类型的对象（类似 *note inet_aton():
     2f8. ）或 ‘struct in6_addr’ 类型的对象时，*note inet_pton(): 2f9. 很
     有用。

     目前 `address_family' 支持 *note AF_INET: 25b8. 和 *note AF_INET6:
     25b9.。如果 IP 地址字符串 `ip_string' 无效，则抛出 *note OSError:
     1d4.。注意，具体什么地址有效取决于 `address_family' 的值和
     ‘inet_pton()’ 的底层实现。

     *note 可用性: 136f.： Unix（可能非所有平台都可用）、Windows。

     在 3.4 版更改: 添加了 Windows 支持

 -- 函数: socket.inet_ntop (address_family, packed_ip)

     将压缩 IP 地址（一个 *note 类字节对象: 5f1.，数个字节长）转换为标准
     的、特定地址簇的字符串形式（如 ‘'7.10.0.5'’ 或 ‘'5aef:2b::8'’ ）。
     当库或网络协议返回 ‘struct in_addr’ 类型的对象（类似 *note
     inet_ntoa(): 26a1. ）或 ‘struct in6_addr’ 类型的对象时，*note
     inet_ntop(): 8c4. 很有用。

     目前 `address_family' 支持 *note AF_INET: 25b8. 和 *note AF_INET6:
     25b9.。如果字节对象 `packed_ip' 与指定的地址簇长度不符，则抛出
     *note ValueError: 1fc.。针对 *note inet_ntop(): 8c4. 调用的错误则抛
     出 *note OSError: 1d4.。

     *note 可用性: 136f.： Unix（可能非所有平台都可用）、Windows。

     在 3.4 版更改: 添加了 Windows 支持

     在 3.5 版更改: 现在支持可写的 *note 字节类对象: 5f1.。

 -- 函数: socket.CMSG_LEN (length)

     返回给定 `length' 所关联数据的辅助数据项的总长度（不带尾部填充）。
     此值通常用作 *note recvmsg(): 682. 接收一个辅助数据项的缓冲区大小，
     但是 RFC 3542(1) 要求可移植应用程序使用 *note CMSG_SPACE(): 1030.，
     以此将尾部填充的空间计入，即使该项在缓冲区的最后。如果 `length' 超
     出允许范围，则抛出 *note OverflowError: 968.。

     *note 可用性: 136f.： 大多数 Unix 平台，其他平台也可能可用。

     3.3 新版功能.

 -- 函数: socket.CMSG_SPACE (length)

     返回 *note recvmsg(): 682. 所需的缓冲区大小，以接收给定 `length' 所
     关联数据的辅助数据项，带有尾部填充。接收多个项目所需的缓冲区空间是
     关联数据长度的 *note CMSG_SPACE(): 1030. 值的总和。如果 `length' 超
     出允许范围，则抛出 *note OverflowError: 968.。

     请注意，某些系统可能支持辅助数据，但不提供本函数。还需注意，如果使
     用本函数的结果来设置缓冲区大小，可能无法精确限制可接收的辅助数据量
     ，因为可能会有其他数据写入尾部填充区域。

     *note 可用性: 136f.： 大多数 Unix 平台，其他平台也可能可用。

     3.3 新版功能.

 -- 函数: socket.getdefaulttimeout ()

     返回用于新套接字对象的默认超时（以秒为单位的浮点数）。值 ‘None’ 表
     示新套接字对象没有超时。首次导入 socket 模块时，默认值为 ‘None’。

 -- 函数: socket.setdefaulttimeout (timeout)

     设置用于新套接字对象的默认超时（以秒为单位的浮点数）。首次导入
     socket 模块时，默认值为 ‘None’。可能的取值及其各自的含义请参阅
     *note settimeout(): 267a.。

 -- 函数: socket.sethostname (name)

     将计算机的主机名设置为 `name'。如果权限不足将抛出 *note OSError:
     1d4.。

     引发一个 *note 审计事件: ea1. ‘socket.sethostname’，附带参数
     ‘name’。

     *note 可用性: 136f.: Unix。

     3.3 新版功能.

 -- 函数: socket.if_nameindex ()

     返回一个列表，包含网络接口（网卡）信息二元组（整数索引，名称字符串
     ）。系统调用失败则抛出 *note OSError: 1d4.。

     *note 可用性: 136f.: Unix, Windows。

     3.3 新版功能.

     在 3.8 版更改: 添加了 Windows 支持。

          注解: 在 Windows 中网络接口在不同上下文中具有不同的名称（所有
          名称见对应示例）:

             * UUID: ‘{FB605B73-AAC2-49A6-9A2F-25416AEA0573}’

             * 名称: ‘ethernet_32770’

             * 友好名称: ‘vEthernet (nat)’

             * 描述: ‘Hyper-V Virtual Ethernet Adapter’

          此函数返回列表中第二种形式的名称，在此示例中为
          ‘ethernet_32770’。

 -- 函数: socket.if_nametoindex (if_name)

     返回网络接口名称相对应的索引号。如果没有所给名称的接口，则抛出
     *note OSError: 1d4.。

     *note 可用性: 136f.: Unix, Windows。

     3.3 新版功能.

     在 3.8 版更改: 添加了 Windows 支持。

     参见
     ....

     "Interface name" 为 *note if_nameindex(): 221. 中所描述的名称。

 -- 函数: socket.if_indextoname (if_index)

     返回网络接口索引号相对应的接口名称。如果没有所给索引号的接口，则抛
     出 *note OSError: 1d4.。

     *note 可用性: 136f.: Unix, Windows。

     3.3 新版功能.

     在 3.8 版更改: 添加了 Windows 支持。

     参见
     ....

     "Interface name" 为 *note if_nameindex(): 221. 中所描述的名称。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3542.html


File: python.info,  Node: 套接字对象,  Next: 关于套接字超时的说明,  Prev: 模块内容<4>,  Up: socket --- 底层网络接口

5.18.2.8 套接字对象
...................

套接字对象具有以下方法。除了 *note makefile(): b21.，其他都与套接字专用
的 Unix 系统调用相对应。

在 3.2 版更改: 添加了对 *note 上下文管理器: 571. 协议的支持。退出上下文
管理器与调用 *note close(): 3d9. 等效。

 -- 方法: socket.accept ()

     接受一个连接。此 socket 必须绑定到一个地址上并且监听连接。返回值是
     一个 ‘(conn, address)’ 对，其中 `conn' 是一个 `新' 的套接字对象，用
     于在此连接上收发数据，`address' 是连接另一端的套接字所绑定的地址。

     新创建的套接字是 *note 不可继承的: 803.。

     在 3.4 版更改: 该套接字现在是不可继承的。

     在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方
     法现在会重试系统调用，而不是触发 *note InterruptedError: 662. 异常
     (原因详见 PEP 475(1))。

 -- 方法: socket.bind (address)

     将套接字绑定到 `address'。套接字必须尚未绑定。（ `address' 的格式取
     决于地址簇 —— 参见上文）

     引发一个 *note 审计事件: ea1. ‘socket.bind’，附带参数 ‘self’、
     ‘address’。

 -- 方法: socket.close ()

     将套接字标记为关闭。当 *note makefile(): b21. 创建的所有文件对象都
     关闭时，底层系统资源（如文件描述符）也将关闭。一旦上述情况发生，将
     来对套接字对象的所有操作都会失败。对端将接收不到任何数据（清空队列
     数据后）。

     垃圾回收时，套接字会自动关闭，但建议显式 *note close(): 3d9. 它们，
     或在它们周围使用 *note with: 6f2. 语句。

     在 3.6 版更改: 现在，如果底层的 ‘close()’ 调用出错，会抛出 *note
     OSError: 1d4.。

          注解: *note close(): 3d9. 释放与连接相关联的资源，但不一定立即
          关闭连接。如果需要及时关闭连接，请在调用 *note close(): 3d9. 之
          前调用 *note shutdown(): 26a4.。

 -- 方法: socket.connect (address)

     连接到 `address' 处的远程套接字。（ `address' 的格式取决于地址簇 ——
     参见上文）

     如果连接被信号中断，则本方法将等待，直到连接完成。如果信号处理程序
     未抛出异常，且套接字阻塞中或已超时，则在超时后抛出 *note
     socket.timeout: c16.。对于非阻塞套接字，如果连接被信号中断，则本方
     法将抛出 *note InterruptedError: 662. 异常（或信号处理程序抛出的异
     常）。

     引发一个 *note 审计事件: ea1. ‘socket.connect’，附带参数 ‘self’、
     ‘address’。

     在 3.5 版更改: 本方法现在将等待，直到连接完成，而不是在以下情况抛出
     *note InterruptedError: 662. 异常。该情况为，连接被信号中断，信号处
     理程序未抛出异常，且套接字阻塞中或已超时（具体解释请参阅 PEP 475(2)
     ）。

 -- 方法: socket.connect_ex (address)

     类似于 ‘connect(address)’，但是对于 C 级别的 ‘connect()’ 调用返回的
     错误，本函数将返回错误指示器，而不是抛出异常（对于其他问题，如“找不
     到主机”，仍然可以抛出异常）。如果操作成功，则错误指示器为 ‘0’，否则
     为 ‘errno’ 变量的值。这对支持如异步连接很有用。

     引发一个 *note 审计事件: ea1. ‘socket.connect’，附带参数 ‘self’、
     ‘address’。

 -- 方法: socket.detach ()

     将套接字对象置于关闭状态，而底层的文件描述符实际并不关闭。返回该文
     件描述符，使其可以重新用于其他目的。

     3.2 新版功能.

 -- 方法: socket.dup ()

     创建套接字的副本。

     新创建的套接字是 *note 不可继承的: 803.。

     在 3.4 版更改: 该套接字现在是不可继承的。

 -- 方法: socket.fileno ()

     返回套接字的文件描述符（一个小整数），失败返回 -1。配合 *note
     select.select(): 67c. 使用很有用。

     在 Windows 下，此方法返回的小整数在允许使用文件描述符的地方无法使用
     （如 *note os.fdopen(): 1441. ）。Unix 无此限制。

 -- 方法: socket.get_inheritable ()

     获取套接字文件描述符或套接字句柄的 *note 可继承标志: 803. ：如果子
     进程可以继承套接字则为 ‘True’，否则为 ‘False’。

     3.4 新版功能.

 -- 方法: socket.getpeername ()

     返回套接字连接到的远程地址。举例而言，这可以用于查找远程 IPv4/v6 套
     接字的端口号。（返回的地址格式取决于地址簇 —— 参见上文。）部分系统
     不支持此函数。

 -- 方法: socket.getsockname ()

     返回套接字本身的地址。举例而言，这可以用于查找 IPv4/v6 套接字的端口
     号。（返回的地址格式取决于地址簇 —— 参见上文。）

 -- 方法: socket.getsockopt (level, optname[, buflen])

     返回指定套接字选项的值（参阅 Unix 手册页 ‘getsockopt(2)’ ）。所需的
     符号常量（ ‘SO_*’ 等）已定义在本模块中。如果未指定 `buflen'，则认为
     该选项值为整数，由本函数返回该整数值。如果指定 `buflen'，则它定义了
     用于存放选项值的缓冲区的最大长度，且该缓冲区将作为字节对象返回。对
     缓冲区的解码工作由调用者自行完成（针对编码为字节串的 C 结构，其解码
     方法请参阅可选的内置模块 *note struct: f9. ）。

 -- 方法: socket.getblocking ()

     如果套接字处于阻塞模式，返回 ‘True’，非阻塞模式返回 ‘False’。

     这相当于检测 ‘socket.gettimeout() == 0’。

     3.7 新版功能.

 -- 方法: socket.gettimeout ()

     返回套接字操作相关的超时秒数（浮点数），未设置超时则返回 ‘None’。它
     反映最后一次调用 *note setblocking(): 1f20. 或 *note settimeout():
     267a. 后的设置。

 -- 方法: socket.ioctl (control, option)


     平台: Windows

     *note ioctl(): 589. 方法是 WSAIoctl 系统接口的有限接口。请参考
     Win32 文档(3) 以获取更多信息。

     在其他平台上，可以使用通用的 *note fcntl.fcntl(): 26a9. 和 *note
     fcntl.ioctl(): de6. 函数，它们接受套接字对象作为第一个参数。

     当前仅支持以下控制码： ‘SIO_RCVALL’、‘SIO_KEEPALIVE_VALS’ 和
     ‘SIO_LOOPBACK_FAST_PATH’。

     在 3.6 版更改: 添加了 ‘SIO_LOOPBACK_FAST_PATH’。

 -- 方法: socket.listen ([backlog])

     启动一个服务器用于接受连接。如果指定 `backlog'，则它最低为 0（小于
     0 会被置为 0），它指定系统允许暂未 accept 的连接数，超过后将拒绝新
     连接。未指定则自动设为合理的默认值。

     在 3.5 版更改: `backlog' 参数现在是可选的。

 -- 方法: socket.makefile (mode='r', buffering=None, *, encoding=None,
          errors=None, newline=None)

     返回与套接字关联的 *note 文件对象: b4a.。返回的对象的具体类型取决于
     *note makefile(): b21. 的参数。这些参数的解释方式与内置的 *note
     open(): 4f8. 函数相同，其中 `mode' 的值仅支持 ‘'r'’ （默认），‘'w'’
     和 ‘'b'’。

     套接字必须处于阻塞模式，它可以有超时，但是如果发生超时，文件对象的
     内部缓冲区可能会以不一致的状态结尾。

     关闭 *note makefile(): b21. 返回的文件对象不会关闭原始套接字，除非
     所有其他文件对象都已关闭且在套接字对象上调用了 *note
     socket.close(): 3d9.。

          注解: 在 Windows 上，由 *note makefile(): b21. 创建的文件类对
          象无法作为带文件描述符的文件对象使用，如无法作为 *note
          subprocess.Popen(): 2ba. 的流参数。

 -- 方法: socket.recv (bufsize[, flags])

     从套接字接收数据。返回值是一个字节对象，表示接收到的数据。`bufsize'
     指定一次接收的最大数据量。可选参数 `flags' 的含义请参阅 Unix 手册页
     ‘recv(2)’，它默认为零。

          注解: 为了最佳匹配硬件和网络的实际情况，`bufsize' 的值应为 2 的
          相对较小的幂，如 4096。

     在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方
     法现在会重试系统调用，而不是触发 *note InterruptedError: 662. 异常
     (原因详见 PEP 475(4))。

 -- 方法: socket.recvfrom (bufsize[, flags])

     从套接字接收数据。返回值是一对 ‘(bytes, address)’，其中 `bytes' 是
     字节对象，表示接收到的数据，`address' 是发送端套接字的地址。可选参
     数 `flags' 的含义请参阅 Unix 手册页 ‘recv(2)’，它默认为零。（
     `address' 的格式取决于地址簇 —— 参见上文）

     在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方
     法现在会重试系统调用，而不是触发 *note InterruptedError: 662. 异常
     (原因详见 PEP 475(5))。

     在 3.7 版更改: 对于多播 IPv6 地址，`address' 的第一项不再包含
     ‘%scope’ 部分。要获得完整的 IPv6 地址，请使用 *note getnameinfo():
     25cd.。

 -- 方法: socket.recvmsg (bufsize[, ancbufsize[, flags]])

     从套接字接收普通数据（至多 `bufsize' 字节）和辅助数据。`ancbufsize'
     参数设置用于接收辅助数据的内部缓冲区的大小（以字节为单位），默认为
     0，表示不接收辅助数据。可以使用 *note CMSG_SPACE(): 1030. 或 *note
     CMSG_LEN(): 1031. 计算辅助数据缓冲区的合适大小，无法放入缓冲区的项
     目可能会被截断或丢弃。`flags' 参数默认为 0，其含义与 *note recv():
     680. 中的相同。

     返回值是一个四元组： ‘(data, ancdata, msg_flags, address)’。`data'
     项是一个 *note bytes: 33a. 对象，用于保存接收到的非辅助数据。
     `ancdata' 项是零个或多个元组 ‘(cmsg_level, cmsg_type, cmsg_data)’ 组
     成的列表，表示接收到的辅助数据（控制消息）：`cmsg_level' 和
     `cmsg_type' 是分别表示协议级别和协议类型的整数，而 `cmsg_data' 是保
     存相关数据的 *note bytes: 33a. 对象。`msg_flags' 项由各种标志按位或
     组成，表示接收消息的情况，详细信息请参阅系统文档。如果接收端套接字
     断开连接，则 `address' 是发送端套接字的地址（如果有），否则该值无指
     定。

     某些系统上可以利用 *note AF_UNIX: 25be. 套接字通过 *note sendmsg():
     685. 和 *note recvmsg(): 682. 在进程之间传递文件描述符。使用此功能
     时（通常仅限于 *note SOCK_STREAM: c92. 套接字），*note recvmsg():
     682. 将在其辅助数据中返回以下格式的项 ‘(socket.SOL_SOCKET,
     socket.SCM_RIGHTS, fds)’，其中 `fds' 是一个 *note bytes: 33a. 对象
     ，是新文件描述符表示为原生 C ‘int’ 类型的二进制数组。如果 *note
     recvmsg(): 682. 在系统调用返回后抛出异常，它将首先关闭此机制接收到
     的所有文件描述符。

     对于仅接收到一部分的辅助数据项，一些系统没有指示其截断长度。如果某
     个项目可能超出了缓冲区的末尾，*note recvmsg(): 682. 将发出 *note
     RuntimeWarning: 2c1.，并返回其在缓冲区内的部分，前提是该对象被截断
     于关联数据开始后。

     在支持 ‘SCM_RIGHTS’ 机制的系统上，下方的函数将最多接收 `maxfds' 个
     文件描述符，返回消息数据和包含描述符的列表（同时忽略意外情况，如接
     收到无关的控制消息）。另请参阅 *note sendmsg(): 685.。

          import socket, array

          def recv_fds(sock, msglen, maxfds):
              fds = array.array("i")   # Array of ints
              msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfds * fds.itemsize))
              for cmsg_level, cmsg_type, cmsg_data in ancdata:
                  if cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS:
                      # Append data, ignoring any truncated integers at the end.
                      fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
              return msg, list(fds)

     *note 可用性: 136f.： 大多数 Unix 平台，其他平台也可能可用。

     3.3 新版功能.

     在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方
     法现在会重试系统调用，而不是触发 *note InterruptedError: 662. 异常
     (原因详见 PEP 475(6))。

 -- 方法: socket.recvmsg_into (buffers[, ancbufsize[, flags]])

     从套接字接收普通数据和辅助数据，其行为与 *note recvmsg(): 682. 相同
     ，但将非辅助数据分散到一系列缓冲区中，而不是返回新的字节对象。
     `buffers' 参数必须是可迭代对象，它迭代出可供写入的缓冲区（如 *note
     bytearray: 33b. 对象），这些缓冲区将被连续的非辅助数据块填充，直到
     数据全部写完或缓冲区用完为止。在允许使用的缓冲区数量上，操作系统可
     能会有限制（ *note sysconf(): 1f46. 的 ‘SC_IOV_MAX’ 值）。
     `ancbufsize' 和 `flags' 参数的含义与 *note recvmsg(): 682. 中的相同
     。

     返回值为四元组： ‘(nbytes, ancdata, msg_flags, address)’，其中
     `nbytes' 是写入缓冲区的非辅助数据的字节总数，而 `ancdata'、
     `msg_flags' 和 `address' 与 *note recvmsg(): 682. 中的相同。

     示例:

          >>> import socket
          >>> s1, s2 = socket.socketpair()
          >>> b1 = bytearray(b'----')
          >>> b2 = bytearray(b'0123456789')
          >>> b3 = bytearray(b'--------------')
          >>> s1.send(b'Mary had a little lamb')
          22
          >>> s2.recvmsg_into([b1, memoryview(b2)[2:9], b3])
          (22, [], 0, None)
          >>> [b1, b2, b3]
          [bytearray(b'Mary'), bytearray(b'01 had a 9'), bytearray(b'little lamb---')]

     *note 可用性: 136f.： 大多数 Unix 平台，其他平台也可能可用。

     3.3 新版功能.

 -- 方法: socket.recvfrom_into (buffer[, nbytes[, flags]])

     从套接字接收数据，将其写入 `buffer' 而不是创建新的字节串。返回值是
     一对 ‘(nbytes, address)’，其中 `nbytes' 是收到的字节数，`address' 是
     发送端套接字的地址。可选参数 `flags' 的含义请参阅 Unix 手册页
     ‘recv(2)’，它默认为零。（ `address' 的格式取决于地址簇 —— 参见上文
     ）

 -- 方法: socket.recv_into (buffer[, nbytes[, flags]])

     从套接字接收至多 `nbytes' 个字节，将其写入缓冲区而不是创建新的字节
     串。如果 `nbytes' 未指定（或指定为 0），则接收至所给缓冲区的最大可
     用大小。返回接收到的字节数。可选参数 `flags' 的含义请参阅 Unix 手册
     页 ‘recv(2)’，它默认为零。

 -- 方法: socket.send (bytes[, flags])

     发送数据给套接字。本套接字必须已连接到远程套接字。可选参数
     `flags' 的含义与上述 *note recv(): 680. 中的相同。本方法返回已发送
     的字节数。应用程序要负责检查所有数据是否已发送，如果仅传输了部分数
     据，程序需要自行尝试传输其余数据。有关该主题的更多信息，请参考
     *note 套接字编程指南: 26aa.。

     在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方
     法现在会重试系统调用，而不是触发 *note InterruptedError: 662. 异常
     (原因详见 PEP 475(7))。

 -- 方法: socket.sendall (bytes[, flags])

     发送数据给套接字。本套接字必须已连接到远程套接字。可选参数 `flags'
     的含义与上述 *note recv(): 680. 中的相同。与 *note send(): 683. 不
     同，本方法持续从 `bytes' 发送数据，直到所有数据都已发送或发生错误为
     止。成功后会返回 ‘None’。出错后会抛出一个异常，此时并没有办法确定成
     功发送了多少数据。

     在 3.5 版更改: 每次成功发送数据后，套接字超时不再重置。现在，套接字
     超时是发送所有数据的最大总持续时间。

     在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方
     法现在会重试系统调用，而不是触发 *note InterruptedError: 662. 异常
     (原因详见 PEP 475(8))。

 -- 方法: socket.sendto (bytes, address)

 -- 方法: socket.sendto (bytes, flags, address)

     发送数据给套接字。本套接字不应连接到远程套接字，而应由 `address' 指
     定目标套接字。可选参数 `flags' 的含义与上述 *note recv(): 680. 中的
     相同。本方法返回已发送的字节数。（ `address' 的格式取决于地址簇 ——
     参见上文。）

     引发一个 *note 审计事件: ea1. ‘socket.sendto’，附带参数 ‘self’、
     ‘address’。

     在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方
     法现在会重试系统调用，而不是触发 *note InterruptedError: 662. 异常
     (原因详见 PEP 475(9))。

 -- 方法: socket.sendmsg (buffers[, ancdata[, flags[, address]]])

     将普通数据和辅助数据发送给套接字，将从一系列缓冲区中收集非辅助数据
     ，并将其拼接为一条消息。`buffers' 参数指定的非辅助数据应为可迭代的
     *note 字节类对象: 5f1. （如 *note bytes: 33a. 对象），在允许使用的
     缓冲区数量上，操作系统可能会有限制（ *note sysconf(): 1f46. 的
     ‘SC_IOV_MAX’ 值）。`ancdata' 参数指定的辅助数据（控制消息）应为可迭
     代对象，迭代出零个或多个 ‘(cmsg_level, cmsg_type, cmsg_data)’ 元组
     ，其中 `cmsg_level' 和 `cmsg_type' 是分别指定协议级别和协议类型的整
     数，而 `cmsg_data' 是保存相关数据的字节类对象。请注意，某些系统（特
     别是没有 *note CMSG_SPACE(): 1030. 的系统）可能每次调用仅支持发送一
     条控制消息。`flags' 参数默认为 0，与 *note send(): 683. 中的含义相
     同。如果 `address' 指定为除 ‘None’ 以外的值，它将作为消息的目标地址
     。返回值是已发送的非辅助数据的字节数。

     在支持 ‘SCM_RIGHTS’ 机制的系统上，下方的函数通过一个 *note AF_UNIX:
     25be. 套接字来发送文件描述符列表 `fds'。另请参阅 *note recvmsg():
     682.。

          import socket, array

          def send_fds(sock, msg, fds):
              return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])

     *note 可用性: 136f.： 大多数 Unix 平台，其他平台也可能可用。

     引发一个 *note 审计事件: ea1. ‘socket.sendmsg’，附带参数 ‘self’、
     ‘address’。

     3.3 新版功能.

     在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方
     法现在会重试系统调用，而不是触发 *note InterruptedError: 662. 异常
     (原因详见 PEP 475(10))。

 -- 方法: socket.sendmsg_afalg ([msg], *, op[, iv[, assoclen[, flags]]])

     为 *note AF_ALG: 58d. 套接字定制的 *note sendmsg(): 685. 版本。可为
     *note AF_ALG: 58d. 套接字设置模式、IV、AEAD 关联数据的长度和标志位
     。

     *note 可用性: 136f.： Linux >= 2.6.38。

     3.6 新版功能.

 -- 方法: socket.sendfile (file, offset=0, count=None)

     使用高性能的 *note os.sendfile: 362. 发送文件，直到达到文件的 EOF 为
     止，返回已发送的字节总数。`file' 必须是一个以二进制模式打开的常规文
     件对象。如果 *note os.sendfile: 362. 不可用（如 Windows）或 `file'
     不是常规文件，将使用 *note send(): 683. 代替。`offset' 指示从哪里开
     始读取文件。如果指定了 `count'，它确定了要发送的字节总数，而不会持
     续发送直到达到文件的 EOF。返回时或发生错误时，文件位置将更新，在这
     种情况下，*note file.tell(): 1da8. 可用于确定已发送的字节数。套接字
     必须为 *note SOCK_STREAM: c92. 类型。不支持非阻塞的套接字。

     3.5 新版功能.

 -- 方法: socket.set_inheritable (inheritable)

     设置套接字文件描述符或套接字句柄的 *note 可继承标志: 803.。

     3.4 新版功能.

 -- 方法: socket.setblocking (flag)

     设置套接字为阻塞或非阻塞模式：如果 `flag' 为 false，则将套接字设置
     为非阻塞，否则设置为阻塞。

     本方法是某些 *note settimeout(): 267a. 调用的简写：

        * ‘sock.setblocking(True)’ 相当于 ‘sock.settimeout(None)’

        * ‘sock.setblocking(False)’ 相当于 ‘sock.settimeout(0.0)’

     在 3.7 版更改: 本方法不再对 *note socket.type: 4a0. 属性设置 *note
     SOCK_NONBLOCK: 49e. 标志。

 -- 方法: socket.settimeout (value)

     为阻塞套接字的操作设置超时。`value' 参数可以是非负浮点数，表示秒，
     也可以是 ‘None’。如果赋为一个非零值，那么如果在操作完成前超过了超时
     时间 `value'，后续的套接字操作将抛出 *note timeout: c16. 异常。如果
     赋为 0，则套接字将处于非阻塞模式。如果指定为 ‘None’，则套接字将处于
     阻塞模式。

     更多信息请查阅 *note 关于套接字超时的说明: 26ab.。

     在 3.7 版更改: 本方法不再修改 *note socket.type: 4a0. 属性的 *note
     SOCK_NONBLOCK: 49e. 标志。

 -- 方法: socket.setsockopt (level, optname, value: int)

 -- 方法: socket.setsockopt (level, optname, value: buffer)

 -- 方法: socket.setsockopt (level, optname, None, optlen: int)

     设置给定套接字选项的值（参阅 Unix 手册页 ‘setsockopt(2)’ ）。所需的
     符号常量（ ‘SO_*’ 等）已定义在本 *note socket: f0. 模块中。该值可以
     是整数、‘None’ 或表示缓冲区的 *note 字节类对象: 5f1.。在后一种情况
     下，由调用者确保字节串中包含正确的数据位（关于将 C 结构体编码为字节
     串的方法，请参阅可选的内置模块 *note struct: f9. ）。当 `value' 设
     置为 ‘None’ 时，必须设置 `optlen' 参数。这相当于调用 ‘setsockopt()’
     C 函数时使用了 ‘optval=NULL’ 和 ‘optlen=optlen’ 参数。

     在 3.5 版更改: 现在支持可写的 *note 字节类对象: 5f1.。

     在 3.6 版更改: 添加了 setsockopt(level, optname, None, optlen: int)
     调用形式。

 -- 方法: socket.shutdown (how)

     关闭一半或全部的连接。如果 `how' 为 ‘SHUT_RD’，则后续不再允许接收。
     如果 `how' 为 ‘SHUT_WR’，则后续不再允许发送。如果 `how' 为
     ‘SHUT_RDWR’，则后续的发送和接收都不允许。

 -- 方法: socket.share (process_id)

     复制套接字，并准备将其与目标进程共享。目标进程必须以 `process_id' 形
     式提供。然后可以利用某种形式的进程间通信，将返回的字节对象传递给目
     标进程，还可以使用 *note fromshare(): 49c. 在新进程中重新创建套接字
     。一旦本方法调用完毕，就可以安全地将套接字关闭，因为操作系统已经为
     目标进程复制了该套接字。

     *note 可用性: 136f.: Windows。

     3.3 新版功能.

注意此处没有 ‘read()’ 或 ‘write()’ 方法，请使用不带 `flags' 参数的 *note
recv(): 680. 和 *note send(): 683. 来替代。

套接字对象还具有以下（只读）属性，这些属性与传入 *note socket: 67d. 构造
函数的值相对应。

 -- 属性: socket.family

     套接字的协议簇。

 -- 属性: socket.type

     套接字的类型。

 -- 属性: socket.proto

     套接字的协议。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475

   (2) https://www.python.org/dev/peps/pep-0475

   (3) https://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx

   (4) https://www.python.org/dev/peps/pep-0475

   (5) https://www.python.org/dev/peps/pep-0475

   (6) https://www.python.org/dev/peps/pep-0475

   (7) https://www.python.org/dev/peps/pep-0475

   (8) https://www.python.org/dev/peps/pep-0475

   (9) https://www.python.org/dev/peps/pep-0475

   (10) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: 关于套接字超时的说明,  Next: 示例<8>,  Prev: 套接字对象,  Up: socket --- 底层网络接口

5.18.2.9 关于套接字超时的说明
.............................

一个套接字对象可以处于以下三种模式之一：阻塞、非阻塞或超时。套接字默认以
阻塞模式创建，但是可以调用 *note setdefaulttimeout(): 267f. 来更改。

   * 在 `blocking mode' （阻塞模式）中，操作将阻塞，直到操作完成或系统返
     回错误（如连接超时）。

   * 在 `non-blocking mode' （非阻塞模式）中，如果操作无法立即完成，则操
     作将失败（不幸的是，不同系统返回的错误不同）：位于 *note select:
     e6. 中的函数可用于了解套接字何时以及是否可以读取或写入。

   * 在 `timeout mode' （超时模式）下，如果无法在指定的超时内完成操作（
     抛出 *note timeout: c16. 异常），或如果系统返回错误，则操作将失败。

     注解: 在操作系统层面上，`超时模式' 下的套接字在内部都设置为非阻塞模
     式。同时，阻塞和超时模式在文件描述符和套接字对象之间共享，这些描述
     符和对象均应指向同一个网络端点。如果，比如你决定使用套接字的 *note
     fileno(): 26a7.，这一实现细节可能导致明显的结果。

* Menu:

* 超时与 connect 方法::
* 超时与 accept 方法::


File: python.info,  Node: 超时与 connect 方法,  Next: 超时与 accept 方法,  Up: 关于套接字超时的说明

5.18.2.10 超时与 ‘connect’ 方法
...............................

*note connect(): 67f. 操作也受超时设置的约束，通常建议在调用 *note
connect(): 67f. 之前调用 *note settimeout(): 267a.，或将超时参数直接传递
给 *note create_connection(): ba6.。但是，无论 Python 套接字超时设置如何
，系统网络栈都有可能返回自带的连接超时错误。


File: python.info,  Node: 超时与 accept 方法,  Prev: 超时与 connect 方法,  Up: 关于套接字超时的说明

5.18.2.11 超时与 ‘accept’ 方法
..............................

如果 *note getdefaulttimeout(): 2697. 的值不是 *note None: 158.，则
*note accept(): 67e. 方法返回的套接字将继承该超时值。若是 None，返回的套
接字行为取决于侦听套接字的设置：

   * 如果侦听套接字处于 `阻塞模式' 或 `超时模式'，则 *note accept():
     67e. 返回的套接字处于 `阻塞模式'；

   * 如果侦听套接字处于 `非阻塞模式'，那么 *note accept(): 67e. 返回的套
     接字是阻塞还是非阻塞取决于操作系统。如果要确保跨平台时的正确行为，
     建议手动覆盖此设置。


File: python.info,  Node: 示例<8>,  Prev: 关于套接字超时的说明,  Up: socket --- 底层网络接口

5.18.2.12 示例
..............

以下是 4 个使用 TCP/IP 协议的最小示例程序：一台服务器，它将收到的所有数
据原样返回（仅服务于一个客户端），还有一个使用该服务器的客户端。注意，服
务器必须按序执行 *note socket(): 67d, *note bind(): 26a3, *note
listen(): 754, *note accept(): 67e. （可能需要重复执行 *note accept():
67e. 以服务多个客户端），而客户端仅需要按序执行 *note socket(): 67d,
*note connect(): 67f.。还须注意，服务器不在侦听套接字上发送 *note
sendall(): 684./*note recv(): 680.，而是在 *note accept(): 67e. 返回的新
套接字上发送。

前两个示例仅支持 IPv4。

     # Echo server program
     import socket

     HOST = ''                 # Symbolic name meaning all available interfaces
     PORT = 50007              # Arbitrary non-privileged port
     with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
         s.bind((HOST, PORT))
         s.listen(1)
         conn, addr = s.accept()
         with conn:
             print('Connected by', addr)
             while True:
                 data = conn.recv(1024)
                 if not data: break
                 conn.sendall(data)

     # Echo client program
     import socket

     HOST = 'daring.cwi.nl'    # The remote host
     PORT = 50007              # The same port as used by the server
     with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
         s.connect((HOST, PORT))
         s.sendall(b'Hello, world')
         data = s.recv(1024)
     print('Received', repr(data))

下两个例子与上两个很像，但是同时支持 IPv4 和 IPv6。 服务端将监听第一个可
用的地址族（它本应同时监听两个）。 在大多数支持 IPv6 的系统上，IPv6 将有
优先权并且服务端可能不会接受 IPv4 流量。 客户端将尝试连接到作为名称解析
结果被返回的所有地址，并将流量发送给连接成功的第一个地址。

     # Echo server program
     import socket
     import sys

     HOST = None               # Symbolic name meaning all available interfaces
     PORT = 50007              # Arbitrary non-privileged port
     s = None
     for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
                                   socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
         af, socktype, proto, canonname, sa = res
         try:
             s = socket.socket(af, socktype, proto)
         except OSError as msg:
             s = None
             continue
         try:
             s.bind(sa)
             s.listen(1)
         except OSError as msg:
             s.close()
             s = None
             continue
         break
     if s is None:
         print('could not open socket')
         sys.exit(1)
     conn, addr = s.accept()
     with conn:
         print('Connected by', addr)
         while True:
             data = conn.recv(1024)
             if not data: break
             conn.send(data)

     # Echo client program
     import socket
     import sys

     HOST = 'daring.cwi.nl'    # The remote host
     PORT = 50007              # The same port as used by the server
     s = None
     for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
         af, socktype, proto, canonname, sa = res
         try:
             s = socket.socket(af, socktype, proto)
         except OSError as msg:
             s = None
             continue
         try:
             s.connect(sa)
         except OSError as msg:
             s.close()
             s = None
             continue
         break
     if s is None:
         print('could not open socket')
         sys.exit(1)
     with s:
         s.sendall(b'Hello, world')
         data = s.recv(1024)
     print('Received', repr(data))

下面的例子演示了如何在 Windows 上使用原始套接字编写一个非常简单的网络嗅
探器。 这个例子需要管理员权限来修改接口:

     import socket

     # the public network interface
     HOST = socket.gethostbyname(socket.gethostname())

     # create a raw socket and bind it to the public interface
     s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
     s.bind((HOST, 0))

     # Include IP headers
     s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

     # receive all packages
     s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

     # receive a package
     print(s.recvfrom(65565))

     # disabled promiscuous mode
     s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)

下面的例子演示了如何使用 socket 接口与采用原始套接字协议的 CAN 网络进行
通信。 要改为通过广播管理器协议来使用 CAN，则要用以下方式打开一个
socket:

     socket.socket(socket.AF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)

在绑定 (‘CAN_RAW’) 或连接 (*note CAN_BCM: 8c2.) socket 之后，你将可以在
socket 对象上正常使用 *note socket.send(): 683. 以及 *note
socket.recv(): 680. 操作（及同类操作）。

最后一个例子可能需要特别的权限:

     import socket
     import struct


     # CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>)

     can_frame_fmt = "=IB3x8s"
     can_frame_size = struct.calcsize(can_frame_fmt)

     def build_can_frame(can_id, data):
         can_dlc = len(data)
         data = data.ljust(8, b'\x00')
         return struct.pack(can_frame_fmt, can_id, can_dlc, data)

     def dissect_can_frame(frame):
         can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame)
         return (can_id, can_dlc, data[:can_dlc])


     # create a raw socket and bind it to the 'vcan0' interface
     s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
     s.bind(('vcan0',))

     while True:
         cf, addr = s.recvfrom(can_frame_size)

         print('Received: can_id=%x, can_dlc=%x, data=%s' % dissect_can_frame(cf))

         try:
             s.send(cf)
         except OSError:
             print('Error sending CAN frame')

         try:
             s.send(build_can_frame(0x01, b'\x01\x02\x03'))
         except OSError:
             print('Error sending CAN frame')

多次运行一个示例，且每次执行之间等待时间过短，可能导致这个错误:

     OSError: [Errno 98] Address already in use

这是因为前一次运行使套接字处于 ‘TIME_WAIT’ 状态，无法立即重用。

要防止这种情况，需要设置一个 *note socket: f0. 标志
‘socket.SO_REUSEADDR’:

     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     s.bind((HOST, PORT))

‘SO_REUSEADDR’ 标志告诉内核将处于 ‘TIME_WAIT’ 状态的本地套接字重新使用，
而不必等到固有的超时到期。

参见
....

关于套接字编程（C 语言）的介绍，请参阅以下文章：

   - `An Introductory 4.3BSD Interprocess Communication Tutorial'，作者
     Stuart Sechrest

   - `An Advanced 4.3BSD Interprocess Communication Tutorial'，作者
     Samuel J. Leffler et al,

两篇文章都在 UNIX 开发者手册，补充文档 1（第 PS1:7 和 PS1:8 节）中。那些
特定于平台的参考资料，它们包含与套接字有关的各种系统调用，也是套接字语义
细节的宝贵信息来源。对于 Unix，请参考手册页。对于 Windows，请参阅
WinSock（或 Winsock 2）规范。如果需要支持 IPv6 的 API，读者可能希望参考
RFC 3493(1)，标题为 Basic Socket Interface Extensions for IPv6。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3493.html


File: python.info,  Node: ssl --- 套接字对象的TLS/SSL封装,  Next: select --- 等待 I/O 完成,  Prev: socket --- 底层网络接口,  Up: 网络和进程间通信

5.18.3 ‘ssl’ — 套接字对象的TLS/SSL封装
--------------------------------------

`源代码:' Lib/ssl.py(1)

__________________________________________________________________

本模块保证了对传安全传输层协议"TLS"的访问 (SSL)加密，并且提供客户端和服
务端层面的网络嵌套字层面的对等连接认证技术。本模块使用OpenSSL库。适用于
所有现代Unix系统、Windows以及Mac OS X。只要Open SSL存在的系统，都有机会
正常使用。

     注解: 行为某些 行为可能具有平台依赖，因为调用是根据操作系统的套接字
     API。不同版本的Open SSL也会引起差异：例如Open SSL版本1.0.1 自带
     TLSv1.1 和 TLSv1.2

     警告: 在阅读 *note 安全考量: 25bd. 前不要使用此模块。 这样做可能会
     导致虚假的安全感，因为ssl模块的默认设置不一定适合你的应用程序。

文档本文档记录‘‘ssl‘‘ 模块的对象和函数；更多关于TLS,SSL,和证书的信息，请
参阅下方的“详情”选项

本模块提供了一个类 *note ssl.SSLSocket: 3ea.，它派生自 *note
socket.socket: 67d. 类型，并提供类似套接字的包装器，也能够对通过带 SSL 套
接字的数据进行加密和解密。 它支持一些额外方法例如 ‘getpeercert()’，该方
法可从连接的另一端获取证书，还有 ‘cipher()’，该方法可获取安全连接所使用
的密码。

对于更复杂的应用程序，*note ssl.SSLContext: 3ec. 类有助于管理设置项和证
书，进而可以被使用 *note SSLContext.wrap_socket(): 3ed. 方法创建的 SSL 套
接字继承。

在 3.5.3 版更改: 更新以支持和 OpenSSL 1.1.0 的链接

在 3.6 版更改: OpenSSL 0.9.8、1.0.0 和 1.0.1 已过时，将不再被支持。在
ssl 模块未来的版本中，最低需要 OpenSSL 1.0.2 或 1.1.0。

* Menu:

* 方法、常量和异常处理::
* SSL 套接字::
* SSL 上下文::
* 证书::
* 例子: 例子<16>.
* 关于非阻塞套接字的说明::
* 内存 BIO 支持: 内存 BIO 支持<2>.
* SSL 会话::
* 安全考量: 安全考量<2>.
* TLS 1.3: TLS 1 3.
* LibreSSL 支持::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/ssl.py


File: python.info,  Node: 方法、常量和异常处理,  Next: SSL 套接字,  Up: ssl --- 套接字对象的TLS/SSL封装

5.18.3.1 方法、常量和异常处理
.............................

* Menu:

* 套接字创建::
* 上下文创建::
* 异常: 异常<12>.
* 随机生成::
* 证书处理::
* 常量: 常量<9>.


File: python.info,  Node: 套接字创建,  Next: 上下文创建,  Up: 方法、常量和异常处理

5.18.3.2 套接字创建
...................

从 Python 3.2 和 2.7.9 开始，建议使用 *note SSLContext: 3ec. 实例的
*note SSLContext.wrap_socket(): 3ed. 来将套接字包装为 *note SSLSocket:
3ea. 对象。 辅助函数 *note create_default_context(): 8c9. 会返回一个新的
带有安全默认设置的上下文。 旧的 *note wrap_socket(): 477. 函数已被弃用，
因为它效率较差并且不支持服务器名称提示（SNI）和主机匹配。

客户端套接字实例，采用默认上下文和IPv4/IPv6双栈:

     import socket
     import ssl

     hostname = 'www.python.org'
     context = ssl.create_default_context()

     with socket.create_connection((hostname, 443)) as sock:
         with context.wrap_socket(sock, server_hostname=hostname) as ssock:
             print(ssock.version())

客户端套接字示例，带有自定义上下文和IPv4:

     hostname = 'www.python.org'
     # PROTOCOL_TLS_CLIENT requires valid cert chain and hostname
     context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
     context.load_verify_locations('path/to/cabundle.pem')

     with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
         with context.wrap_socket(sock, server_hostname=hostname) as ssock:
             print(ssock.version())

服务器套接字实例，在localhost上监听IPv4:

     context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
     context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key')

     with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
         sock.bind(('127.0.0.1', 8443))
         sock.listen(5)
         with context.wrap_socket(sock, server_side=True) as ssock:
             conn, addr = ssock.accept()
             ...


File: python.info,  Node: 上下文创建,  Next: 异常<12>,  Prev: 套接字创建,  Up: 方法、常量和异常处理

5.18.3.3 上下文创建
...................

便捷函数，可以帮助创建 *note SSLContext: 3ec. 对象，用于常见的目的。

 -- 函数: ssl.create_default_context (purpose=Purpose.SERVER_AUTH,
          cafile=None, capath=None, cadata=None)

     返回一个新的 *note SSLContext: 3ec. 对象，使用给定 `purpose' 的默认
     设置。 该设置由 *note ssl: f4. 模块选择，并且通常是代表一个比直接调
     用 *note SSLContext: 3ec. 构造器时更高的安全等级。

     `cafile', `capath', `cadata' 代表用于进行证书核验的可选受信任 CA 证
     书，与 *note SSLContext.load_verify_locations(): 7f4. 的一致。 如果
     三个参数均为 *note None: 158.，此函数可以转而选择信任系统的默认 CA
     证书。

     设置包括: *note PROTOCOL_TLS: 26b8, *note OP_NO_SSLv2: ba8. 以及
     *note OP_NO_SSLv3: 26b9.，具有不带 RC4 和不带无身份验证密码套件的高
     度加密密码套件。 传入 *note SERVER_AUTH: 8d4. 作为 `purpose' 会把
     *note verify_mode: 26ba. 设为 *note CERT_REQUIRED: 26bb. 并且加载指
     定 CA 证书（当给出 `cafile', `capath' 和 `cadata' 中的至少一个）或
     者使用 *note SSLContext.load_default_certs(): 8d3. 来加载默认 CA 证
     书。

     当 *note keylog_filename: 26bc. 受支持并且设置了环境变量
     ‘SSLKEYLOGFILE’ 时，*note create_default_context(): 8c9. 会启用密钥
     日志记录。

          注解: 协议、选项、密码和其他设置可随时更改为更具约束性的值而无
          须事先弃用。 这些值代表了兼容性和安全性之间的合理平衡。

          如果你的应用需要特定的设置，你应当创建一个 *note SSLContext:
          3ec. 并自行应用设置。

          注解: 如果你发现当某些较旧的客户端或服务器尝试与用此函数创建的
          *note SSLContext: 3ec. 进行连接时收到了报错提示 "Protocol or
          cipher suite mismatch"，这可能是因为它们只支持 SSL3.0 而它被此
          函数用 *note OP_NO_SSLv3: 26b9. 排除掉了。 SSL3.0 被广泛认为 完
          全不可用(1)。 如果你仍希望继续使用此函数但仍允许 SSL 3.0 连接
          ，你可以使用以下代码重新启用它们:

               ctx = ssl.create_default_context(Purpose.CLIENT_AUTH)
               ctx.options &= ~ssl.OP_NO_SSLv3

     3.4 新版功能.

     在 3.4.4 版更改: RC4 被从默认密码字符串中丢弃。

     在 3.6 版更改: ChaCha20/Poly1305 被添加到默认密码字符串中。

     3DES 被从默认密码字符串中丢弃。

     在 3.8 版更改: 增加了对密钥日志记录至 ‘SSLKEYLOGFILE’ 的支持。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/POODLE


File: python.info,  Node: 异常<12>,  Next: 随机生成,  Prev: 上下文创建,  Up: 方法、常量和异常处理

5.18.3.4 异常
.............

 -- 例外: ssl.SSLError

     引发此异常以提示来自下层 SSL 实现（目前由 OpenSSL 库提供）的错误。
     它表示在下层网络连接之上叠加的高层级加密和验证层存在某种问题。 此错
     误是 *note OSError: 1d4. 的一个子类型。 *note SSLError: c17. 实例的
     错误和消息是由 OpenSSL 库提供的。

     在 3.3 版更改: *note SSLError: c17. 曾经是 *note socket.error: 99d.
     的一个子类型。

      -- 属性: library

          一个字符串形式的助词符，用来指明发生错误的 OpenSSL 子模块，例
          如 ‘SSL’, ‘PEM’ 或 ‘X509’。 可能的取值范围依赖于 OpenSSL 的版
          本。

          3.3 新版功能.

      -- 属性: reason

          一个字符串形式的助记符，用来指明发生错误的原因，例如
          ‘CERTIFICATE_VERIFY_FAILED’。 可能的取值范围依赖于 OpenSSL 的
          版本。

          3.3 新版功能.

 -- 例外: ssl.SSLZeroReturnError

     *note SSLError: c17. 的一个子类，当尝试读取或写入且 SSL 连接已被完
     全关闭时会被引发。 请注意这并不意味着下层的传输（读取 TCP）已被关闭
     。

     3.3 新版功能.

 -- 例外: ssl.SSLWantReadError

     *note SSLError: c17. 的一个子类，当尝试读取或写入但，并在请求被满足
     之前还需要在下层的 TCP 传输上接收更多数据时会被 *note 非阻塞型 SSL
     套接字: 26bf. 引发。

     3.3 新版功能.

 -- 例外: ssl.SSLWantWriteError

     *note SSLError: c17. 的一个子类，当尝试读取或写入数据，但在请求被满
     足之前还需要在下层的 TCP 传输上发送更多数据时会被 *note 非阻塞型
     SSL 套接字: 26bf. 引发。

     3.3 新版功能.

 -- 例外: ssl.SSLSyscallError

     *note SSLError: c17. 的子类，当尝试在 SSL 套接字上执行操作时遇到系
     统错误时会被引发。 不幸的是，没有简单的方式能检查原始 errno 编号。

     3.3 新版功能.

 -- 例外: ssl.SSLEOFError

     *note SSLError: c17. 的子类，当 SSL 连接被突然终止时会被引发。 通常
     ，当遇到此错误时你不应再尝试重用下层的传输。

     3.3 新版功能.

 -- 例外: ssl.SSLCertVerificationError

     *note SSLError: c17. 的子类，当证书验证失败时会被引发。

     3.7 新版功能.

      -- 属性: verify_code

          一个数字形式的错误编号，用于表示验证错误。

      -- 属性: verify_message

          用于表示验证错误的人类可读的字符串。

 -- 例外: ssl.CertificateError

     *note SSLCertVerificationError: 3e5. 的别名。

     在 3.7 版更改: 此异常现在是 *note SSLCertVerificationError: 3e5. 的
     别名。


File: python.info,  Node: 随机生成,  Next: 证书处理,  Prev: 异常<12>,  Up: 方法、常量和异常处理

5.18.3.5 随机生成
.................

 -- 函数: ssl.RAND_bytes (num)

     返回 `num' 个高加密强度伪随机字节数据。 如果 PRNG 未使用足够的数据
     作为随机种子或者如果当前 RAND 方法不支持该操作则会引发 *note
     SSLError: c17.。 *note RAND_status(): 26c6. 可被用来检查 PRNG 的状
     态而 *note RAND_add(): 26c7. 可被用来为 PRNG 设置随机种子。

     对于几乎所有应用程序都更推荐使用 *note os.urandom(): 4d9.。

     Read the Wikipedia article, Cryptographically secure pseudorandom
     number generator (CSPRNG)(1), to get the requirements of a
     cryptographically generator.

     3.3 新版功能.

 -- 函数: ssl.RAND_pseudo_bytes (num)

     返回 (bytes, is_cryptographic): bytes 是 `num' 个伪随机字节数据，如
     果所生成的字节数据为高加密强度则 is_cryptographic 为 ‘True’。 如果
     当前 RAND 方法不支持此操作则会引发 *note SSLError: c17.。

     所生成的伪随机字节序列如果具有足够的长度则将会具有唯一性，并是并非
     不可预测。 它们可被用于非加密目的以及加密协议中的特定目的，但通常不
     可被用于密钥生成等目的。

     对于几乎所有应用程序都更推荐使用 *note os.urandom(): 4d9.。

     3.3 新版功能.

     3.6 版后已移除: OpenSSL 已弃用了 *note ssl.RAND_pseudo_bytes():
     a98.，请改用 *note ssl.RAND_bytes(): a97.。

 -- 函数: ssl.RAND_status ()

     如果 SSL 伪随机数生成器已使用‘足够的’随机性作为种子则返回 ‘True’，
     否则返回 ‘False’。 你可以使用 *note ssl.RAND_egd(): 26c8. 和 *note
     ssl.RAND_add(): 26c7. 来增加伪随机数生成器的随机性。

 -- 函数: ssl.RAND_egd (path)

     如果你在某处运行了一个熵收集守护程序（EGD），且 `path' 是向其打开的
     套接字连接路径名，此函数将从该套接字读取 256 个字节的随机性数据，并
     将其添加到 SSL 伪随机数生成器以增加所生成密钥的安全性。 此操作通常
     只在没有更好随机性源的系统上才是必要的。

     请查看 ‘http://egd.sourceforge.net/’ 或
     ‘http://prngd.sourceforge.net/’ 来了解有关熵收集守护程序源的信息。

     *note 可用性: 136f.: 对于 LibreSSL 和 OpenSSL > 1.1.0 不可用。

 -- 函数: ssl.RAND_add (bytes, entropy)

     将给定的 `bytes' 混合到 SSL 伪随机数生成器中。 形参 `entropy'
     (float 类型) 是数据所包含的熵的下界 (因此你可以总是使用 ‘0.0’)。 请
     查看 RFC 1750(2) 了解有关熵源的更多信息。

     在 3.5 版更改: 现在支持可写的 *note 字节类对象: 5f1.。

   ---------- Footnotes ----------

   (1) 
https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator

   (2) https://tools.ietf.org/html/rfc1750.html


File: python.info,  Node: 证书处理,  Next: 常量<9>,  Prev: 随机生成,  Up: 方法、常量和异常处理

5.18.3.6 证书处理
.................

 -- 函数: ssl.match_hostname (cert, hostname)

     验证 `cert' (使用 *note SSLSocket.getpeercert(): 8d9. 所返回的已解
     码格式) 是否匹配给定的 `hostname'。 所应用的规则是在 RFC 2818(1),
     RFC 5280(2) 和 RFC 6125(3) 中描述的检查 HTTPS 服务器身份的规则。 除
     了 HTTPS，此函数还应当适用于各种基于 SSL 协议的服务器身份检查操作，
     例如 FTPS, IMAPS, POPS 等等。

     失败时引发 *note CertificateError: 26c4.。 成功时此函数无返回值:

          >>> cert = {'subject': ((('commonName', 'example.com'),),)}
          >>> ssl.match_hostname(cert, "example.com")
          >>> ssl.match_hostname(cert, "example.org")
          Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
            File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
          ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'

     3.2 新版功能.

     在 3.3.3 版更改: 此函数现在遵循 RFC 6125(4), 6.4.3 小节，它不会匹配
     多个通配符 (例如 ‘*.*.com’ 或 ‘*a*.example.org’) 也不匹配国际化域名
     (IDN) 片段内部的通配符。 IDN A 标签例如 ‘www*.xn--pthon-kva.org’ 仍
     然受支持，但 ‘x*.python.org’ 不再能匹配 ‘xn--tda.python.org’。

     在 3.5 版更改: 现在支持匹配存在于证书的 subjectAltName 字段中的 IP
     地址。

     在 3.7 版更改: 此函数不再被用于 TLS 连接。 主机匹配现在是由 OpenSSL
     执行的。

     允许位于段的最左端且为唯一字符的通配符。 部分通配符例如
     ‘www*.example.com’ 已不再受支持。

     3.7 版后已移除.

 -- 函数: ssl.cert_time_to_seconds (cert_time)

     返回距离 Unix 纪元零时的秒数，给定的 ‘cert_time’ 字符串代表来自证书
     的 "notBefore" 或 "notAfter" 日期值，采用 ‘"%b %d %H:%M:%S %Y %Z"’
     strptime 格式（C 区域）。

     以下为示例代码:

          >>> import ssl
          >>> timestamp = ssl.cert_time_to_seconds("Jan  5 09:34:43 2018 GMT")
          >>> timestamp
          1515144883
          >>> from datetime import datetime
          >>> print(datetime.utcfromtimestamp(timestamp))
          2018-01-05 09:34:43

     "notBefore" 或 "notAfter" 日期值必须使用 GMT ( RFC 5280(5))。

     在 3.5 版更改: 将输入时间解读为 UTC 时间，基于输入字符串中指明的
     ’GMT’ 时区。 在之前使用的是本地时区。 返回一个整数（不带输入格式中
     秒的分数部分）

 -- 函数: ssl.get_server_certificate (addr, ssl_version=PROTOCOL_TLS,
          ca_certs=None)

     带 SSL 保护的服务器的地址 ‘addr’ 以 (`hostname', `port-number') 对
     的形式给出，获取服务器的证书，并将其以 PEM 编码字符串的形式返回。 如
     果指定了 ‘ssl_version’，则使用该版本的 SSL 协议尝试连接服务器。 如
     果指定了 ‘ca_certs’，它应当是一个包含根证书列表的文件，使用与 *note
     SSLContext.wrap_socket(): 3ed. 中同名形参一致的格式。 该调用将尝试
     根据指定的根证书集来验证服务器证书，如果验证失败则该调用也将失败。

     在 3.3 版更改: 此函数现在是 IPv6 兼容的。-compatible.

     在 3.5 版更改: 默认的 `ssl_version' 从 *note PROTOCOL_SSLv3: 26ca.
     改为 *note PROTOCOL_TLS: 26b8. 以保证与现代服务器的最大兼容性。

 -- 函数: ssl.DER_cert_to_PEM_cert (DER_cert_bytes)

     根据给定的 DER 编码字节块形式的证书，返回同一证书的 PEM 编码字符串
     版本。

 -- 函数: ssl.PEM_cert_to_DER_cert (PEM_cert_string)

     根据给定的 ASCII PEM 字符串形式的证书，返回同一证书的 DER 编码字节
     序列。

 -- 函数: ssl.get_default_verify_paths ()

     返回包含 OpenSSL 的默认 cafile 和 capath 的路径的命名元组。 此路径
     与 *note SSLContext.set_default_verify_paths(): 8cb. 所使用的相同。
     返回值是一个 *note named tuple: aab. ‘DefaultVerifyPaths’:

        * ‘cafile’ - 解析出的 cafile 路径或者如果文件不存在则为 ‘None’,

        * ‘capath’ - 解析出的 capath 路径或者如果目录不存在则为 ‘None’,

        * ‘openssl_cafile_env’ - 指向一个 cafile 的 OpenSSL 环境键,

        * ‘openssl_cafile’ - 一个 cafile 的硬编码路径,

        * ‘openssl_capath_env’ - 指向一个 capath 的 OpenSSL 环境键,

        * ‘openssl_capath’ - 一个 capath 目录的硬编码路径

     *note 可用性: 136f.: LibreSSL 会忽略环境变量 ‘openssl_cafile_env’ 和
     ‘openssl_capath_env’。

     3.4 新版功能.

 -- 函数: ssl.enum_certificates (store_name)

     从 Windows 的系统证书库中检索证书。 `store_name' 可以是 ‘CA’,
     ‘ROOT’ 或 ‘MY’ 中的一个。 Windows 也可能会提供额外的证书库。

     此函数返回一个包含 (cert_bytes, encoding_type, trust) 元组的列表。
     encoding_type 指明 cert_bytes 的编码格式。 它可以为 ‘x509_asn’ 以表
     示 X.509 ASN.1 数据或是 ‘pkcs_7_asn’ 以表示 PKCS#7 ASN.1 数据。
     trust 以 OIDS 集合的形式指明证书的目的，或者如果证书对于所有目的都
     可以信任则为 ‘True’。

     示例:

          >>> ssl.enum_certificates("CA")
          [(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}),
           (b'data...', 'x509_asn', True)]

     *note 可用性: 136f.: Windows。

     3.4 新版功能.

 -- 函数: ssl.enum_crls (store_name)

     Windows 的系统证书库中检索 CRL。 `store_name' 可以是 ‘CA’, ‘ROOT’ 或
     ‘MY’ 中的一个。 Windows 也可能会提供额外的证书库。

     此函数返回一个包含 (cert_bytes, encoding_type, trust) 元组的列表。
     encoding_type 指明 cert_bytes 的编码格式。 它可以为 ‘x509_asn’ 以表
     示 X.509 ASN.1 数据或是 ‘pkcs_7_asn’ 以表示 PKCS#7 ASN.1 数据。

     *note 可用性: 136f.: Windows。

     3.4 新版功能.

 -- 函数: ssl.wrap_socket (sock, keyfile=None, certfile=None,
          server_side=False, cert_reqs=CERT_NONE,
          ssl_version=PROTOCOL_TLS, ca_certs=None,
          do_handshake_on_connect=True, suppress_ragged_eofs=True,
          ciphers=None)

     接受一个 *note socket.socket: 67d. 的实例 ‘sock’，并返回一个 *note
     ssl.SSLSocket: 3ea. 的实例，该类型是 *note socket.socket: 67d. 的子
     类型，它将下层的套接字包装在一个 SSL 上下文中。 ‘sock’ 必须是一个
     *note SOCK_STREAM: c92. 套接字；其他套接字类型不被支持。

     在内部，该函数会创建一个 *note SSLContext: 3ec.，其协议版本为
     `ssl_version' 且 *note SSLContext.options: 26cd. 设为 `cert_reqs'。
     如果设置了 `keyfile', `certfile', `ca_certs' 或 `ciphers' 等形参，
     则参数值会被传给 *note SSLContext.load_cert_chain(): a99, *note
     SSLContext.load_verify_locations(): 7f4. 以及 *note
     SSLContext.set_ciphers(): 26ce.。

     参数 `server_side', `do_handshake_on_connect' 和
     `suppress_ragged_eofs' 具有与 *note SSLContext.wrap_socket(): 3ed.
     相同的含义。

     3.7 版后已移除: 从 Python 3.2 和 2.7.9 开始，建议使用 *note
     SSLContext.wrap_socket(): 3ed. 来代替 *note wrap_socket(): 477.。 模
     块级函数的功能受限并且将创建不安全的客户端套接字，不带服务器名称提
     示或主机名匹配。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2818.html

   (2) https://tools.ietf.org/html/rfc5280.html

   (3) https://tools.ietf.org/html/rfc6125.html

   (4) https://tools.ietf.org/html/rfc6125.html

   (5) https://tools.ietf.org/html/rfc5280.html


File: python.info,  Node: 常量<9>,  Prev: 证书处理,  Up: 方法、常量和异常处理

5.18.3.7 常量
.............

     所有常量现在都是 *note enum.IntEnum: 596. 或 *note enum.IntFlag:
     176b. 多项集的成员。

     3.6 新版功能.

 -- 数据: ssl.CERT_NONE

     *note SSLContext.verify_mode: 26ba. 或 *note wrap_socket(): 477. 的
     ‘cert_reqs’ 形参可能的取值。 *note PROTOCOL_TLS_CLIENT: 26d1. 除外
     ，这是默认的模式。 对于客户端套接字，几乎任何证书都是可接受的。 验
     证错误例如不受信任或过期的证书错误会被忽略并且不会中止 TLS/SSL 握手
     。

     在服务器模式下，不会从客户端请求任何证书，因此客户端不会发送任何用
     于客户端证书身份验证的证书。

     参见下文对于 *note 安全考量: 25bd. 的讨论。

 -- 数据: ssl.CERT_OPTIONAL

     *note SSLContext.verify_mode: 26ba. 或 *note wrap_socket(): 477. 的
     ‘cert_reqs’ 形参可能的取值。 *note CERT_OPTIONAL: 26d2. 具有与
     *note CERT_REQUIRED: 26bb. 相同的含义。 对于客户端套接字推荐改用
     *note CERT_REQUIRED: 26bb.。

     在服务器模式下，客户端证书请求会被发送给客户端。 客户端可以忽略请求
     也可以发送一个证书以执行 TLS 客户端证书身份验证。 如果客户端选择发
     送证书，则将对其执行验证。 任何验证错误都将立即中止 TLS 握手。

     使用此设置要求将一组有效的 CA 证书传递给 *note
     SSLContext.load_verify_locations(): 7f4. 或是作为 *note
     wrap_socket(): 477. 的 ‘ca_certs’ 形参值。

 -- 数据: ssl.CERT_REQUIRED

     *note SSLContext.verify_mode: 26ba. 或 *note wrap_socket(): 477. 的
     ‘cert_reqs’ 形参可能的取值。 在此模式下，需要从套接字连接的另一端获
     取证书；如果未提供证书或验证失败则将引发 *note SSLError: c17.。 此
     模式 `不能' 在客户端模式下对证书进行验证，因为它不会匹配主机名。
     *note check_hostname: 26d3. 也必须被启用以验证证书的真实性。 *note
     PROTOCOL_TLS_CLIENT: 26d1. 会使用 *note CERT_REQUIRED: 26bb. 并默认
     启用 *note check_hostname: 26d3.。

     对于服务器套接字，此模式会提供强制性的 TLS 客户端证书验证。 客户端
     证书请求会被发送给客户端并且客户端必须提供有效且受信任的证书。

     使用此设置要求将一组有效的 CA 证书传递给 *note
     SSLContext.load_verify_locations(): 7f4. 或是作为 *note
     wrap_socket(): 477. 的 ‘ca_certs’ 形参值。

 -- 类: ssl.VerifyMode

     CERT_* 常量的 *note enum.IntEnum: 596. 多项集。

     3.6 新版功能.

 -- 数据: ssl.VERIFY_DEFAULT

     *note SSLContext.verify_flags: 8ce. 可能的取值。 在此模式下，证书吊
     销列表（CRL）并不会被检查。 OpenSSL 默认不要求也不验证 CRL。

     3.4 新版功能.

 -- 数据: ssl.VERIFY_CRL_CHECK_LEAF

     *note SSLContext.verify_flags: 8ce. 可能的取值。 在此模式下， 只会
     检查对等证书而不检查任何中间 CA 证书。 此模式要求提供由对等证书颁发
     者（其直接上级 CA）签名的有效 CRL。 如果未使用 *note
     SSLContext.load_verify_locations: 7f4. 加载正确的 CRL，则验证将失败
     。

     3.4 新版功能.

 -- 数据: ssl.VERIFY_CRL_CHECK_CHAIN

     *note SSLContext.verify_flags: 8ce. 可能的取值。 在此模式下，会检查
     对等证书链中所有证书的 CRL。

     3.4 新版功能.

 -- 数据: ssl.VERIFY_X509_STRICT

     *note SSLContext.verify_flags: 8ce. 可能的取值，用于禁用已损坏
     X.509 证书的绕过操作。

     3.4 新版功能.

 -- 数据: ssl.VERIFY_X509_TRUSTED_FIRST

     *note SSLContext.verify_flags: 8ce. 可能的取值。 它指示 OpenSSL 在
     构建用于验证某个证书的信任链时首选受信任的证书。 此旗标将默认被启用
     。

     3.4.4 新版功能.

 -- 类: ssl.VerifyFlags

     VERIFY_* 常量的 *note enum.IntFlag: 176b. 多项集。

     3.6 新版功能.

 -- 数据: ssl.PROTOCOL_TLS

     选择客户端和服务器均支持的最高协议版本。 此选项名称并不准确，实际上
     "SSL" 和 "TLS" 协议均可被选择。

     3.6 新版功能.

 -- 数据: ssl.PROTOCOL_TLS_CLIENT

     像 *note PROTOCOL_TLS: 26b8. 一样地自动协商最高协议版本，但是只支持
     客户端 *note SSLSocket: 3ea. 连接。 此协议默认会启用 *note
     CERT_REQUIRED: 26bb. 和 *note check_hostname: 26d3.。

     3.6 新版功能.

 -- 数据: ssl.PROTOCOL_TLS_SERVER

     像 *note PROTOCOL_TLS: 26b8. 一样地自动协商最高协议版本，但是只支持
     服务器 *note SSLSocket: 3ea. 连接。

     3.6 新版功能.

 -- 数据: ssl.PROTOCOL_SSLv23

     *note PROTOCOL_TLS: 26b8. 的别名。

     3.6 版后已移除: 请改用 *note PROTOCOL_TLS: 26b8.。

 -- 数据: ssl.PROTOCOL_SSLv2

     选择 SSL 版本 2 作为通道加密协议。

     如果 OpenSSL 编译时附带了 ‘OPENSSL_NO_SSL2’ 旗标则此协议将不可用。

          警告: SSL 版本 2 并不安全。 极不建议使用它。

     3.6 版后已移除: OpenSSL 已经移除了对 SSLv2 的支持。

 -- 数据: ssl.PROTOCOL_SSLv3

     选择 SSL 版本 3 作为通道加密协议。

     如果 OpenSSL 编译时使用了 ‘OPENSSL_NO_SSLv3’ 旗标则此协议将不可用。

          警告: SSL 版本 3 并不安全。 极不建议使用它。

     3.6 版后已移除: OpenSSL 已经弃用了所有带有特定版本号的协议。 请改用
     默认协议 *note PROTOCOL_TLS: 26b8. 并附带 *note OP_NO_SSLv3: 26b9.
     等旗标。

 -- 数据: ssl.PROTOCOL_TLSv1

     选择 TLS 版本 1.0 作为通道加密协议。

     3.6 版后已移除: OpenSSL 已经弃用了所有带有特定版本号的协议。 请改用
     默认协议 *note PROTOCOL_TLS: 26b8. 并附带 *note OP_NO_SSLv3: 26b9.
     等旗标。

 -- 数据: ssl.PROTOCOL_TLSv1_1

     选择 TLS 版本 1.1 作为通道加密协议。 仅适用于 openssl 版本 1.0.1+。

     3.4 新版功能.

     3.6 版后已移除: OpenSSL 已经弃用了所有带有特定版本号的协议。 请改用
     默认协议 *note PROTOCOL_TLS: 26b8. 并附带 *note OP_NO_SSLv3: 26b9.
     等旗标。

 -- 数据: ssl.PROTOCOL_TLSv1_2

     选译 TLS 版本 1.2 作为通道加密协议。 这是最新的版本，也应是能提供最
     大保护的最佳选择，如果通信双方都支持它的话。 仅适用于 openssl 版本
     1.0.1+。

     3.4 新版功能.

     3.6 版后已移除: OpenSSL 已经弃用了所有带有特定版本号的协议。 请改用
     默认协议 *note PROTOCOL_TLS: 26b8. 并附带 *note OP_NO_SSLv3: 26b9.
     等旗标。

 -- 数据: ssl.OP_ALL

     对存在于其他 SSL 实现中的各种缺陷启用绕过操作。 默认会设置此选项。
     没有必要设置与 OpenSSL 的 ‘SSL_OP_ALL’ 常量同名的旗标。

     3.2 新版功能.

 -- 数据: ssl.OP_NO_SSLv2

     阻止 SSLv2 连接。 此选项仅可与 *note PROTOCOL_TLS: 26b8. 结合使用。
     它会阻止对等方选择 SSLv2 作为协议版本。

     3.2 新版功能.

     3.6 版后已移除: SSLv2 已被弃用。

 -- 数据: ssl.OP_NO_SSLv3

     阻止 SSLv3 连接。 此选项仅可与 *note PROTOCOL_TLS: 26b8. 结合使用。
     它会阻止对等方选择 SSLv3 作为协议版本。

     3.2 新版功能.

     3.6 版后已移除: SSLv3 已被弃用

 -- 数据: ssl.OP_NO_TLSv1

     阻止 TLSv1 连接。 此选项仅可与 *note PROTOCOL_TLS: 26b8. 结合使用。
     它会阻止对等方选择 TLSv1 作为协议版本。

     3.2 新版功能.

     3.7 版后已移除: 此选项自 OpenSSL 1.1.0 起已被弃用，请改用新的 *note
     SSLContext.minimum_version: 3ef. 和 *note
     SSLContext.maximum_version: 3f0.。

 -- 数据: ssl.OP_NO_TLSv1_1

     阻止 TLSv1.1 连接。 此选项仅可与 *note PROTOCOL_TLS: 26b8. 结合使用
     。 它会阻止对等方选择 TLSv1.1 作为协议版本。 仅适用于 openssl 版本
     1.0.1+。

     3.4 新版功能.

     3.7 版后已移除: 此选项自 OpenSSL 1.1.0 起已被弃用。

 -- 数据: ssl.OP_NO_TLSv1_2

     阻止 TLSv1.2 连接。 此选项仅可与 *note PROTOCOL_TLS: 26b8. 结合使用
     。 它会阻止对等方选择 TLSv1.2 作为协议版本。 仅适用于 openssl 版本
     1.0.1+。

     3.4 新版功能.

     3.7 版后已移除: 此选项自 OpenSSL 1.1.0 起已被弃用。

 -- 数据: ssl.OP_NO_TLSv1_3

     阻止 TLSv1.3 连接。 此选项仅可与 *note PROTOCOL_TLS: 26b8. 结合使用
     。 它会阻止对等方选择 TLSv1.3 作为协议版本。 TLS 1.3 适用于 OpenSSL
     1.1.1 或更新的版本。 当 Python 编译是基于较旧版本的 OpenSSL 时，该
     旗标默认为 `0'。

     3.7 新版功能.

     3.7 版后已移除: 此选项自 OpenSSL 1.1.0 起已被弃用。 它被添加到
     2.7.15, 3.6.3 和 3.7.0 是为了向下兼容 OpenSSL 1.0.2。

 -- 数据: ssl.OP_NO_RENEGOTIATION

     禁用所有 TLSv1.2 和更早版本的重协商操作。 不发送 HelloRequest 消息
     ，并忽略通过 ClientHello 发起的重协商请求。

     此选项仅适用于 OpenSSL 1.1.0h 及更新的版本。

     3.7 新版功能.

 -- 数据: ssl.OP_CIPHER_SERVER_PREFERENCE

     使用服务器的密码顺序首选项，而不是客户端的首选项。 此选项在客户端套
     接字和 SSLv2 服务器套接字上无效。

     3.3 新版功能.

 -- 数据: ssl.OP_SINGLE_DH_USE

     阻止对于单独的 SSL 会话重用相同的 DH 密钥。 这会提升前向保密性但需
     要更多的计算资源。 此选项仅适用于服务器套接字。

     3.3 新版功能.

 -- 数据: ssl.OP_SINGLE_ECDH_USE

     阻止对于单独的 SSL 会话重用相同的 ECDH 密钥。 这会提升前向保密性但
     需要更多的计算资源。 此选项仅适用于服务器套接字。

     3.3 新版功能.

 -- 数据: ssl.OP_ENABLE_MIDDLEBOX_COMPAT

     在 TLS 1.3 握手中发送虚拟更改密码规格（CCS）消息以使得 TLS 1.3 连接
     看起来更像是 TLS 1.2 连接。

     此选项仅适用于 OpenSSL 1.1.1 及更新的版本。

     3.8 新版功能.

 -- 数据: ssl.OP_NO_COMPRESSION

     在 SSL 通道上禁用压缩。 这适用于应用协议支持自己的压缩方案的情况。

     此选项仅适用于 OpenSSL 1.0.0 及更新的版本。

     3.3 新版功能.

 -- 类: ssl.Options

     OP_* 常量的 *note enum.IntFlag: 176b. 多项集。

 -- 数据: ssl.OP_NO_TICKET

     阻止客户端请求会话凭据。

     3.6 新版功能.

 -- 数据: ssl.OP_IGNORE_UNEXPECTED_EOF

     忽略 TLS 连接的意外关闭。

     此选项仅适用于 OpenSSL 3.0.0 及更新的版本。

     3.10 新版功能.

 -- 数据: ssl.HAS_ALPN

     OpenSSL 库是否具有对 RFC 7301(1) 中描述的 `应用层协议协商' TLS 扩展
     的内置支持。

     3.5 新版功能.

 -- 数据: ssl.HAS_NEVER_CHECK_COMMON_NAME

     OpenSSL 库是否具有对不检测目标通用名称的内置支持且 *note
     SSLContext.hostname_checks_common_name: 3e6. 为可写状态。

     3.7 新版功能.

 -- 数据: ssl.HAS_ECDH

     OpenSSL 库是否具有对基于椭圆曲线的 Diffie-Hellman 密钥交换的内置支
     持。 此常量应当为真值，除非发布者明确地禁用了此功能。

     3.3 新版功能.

 -- 数据: ssl.HAS_SNI

     OpenSSL 库是否具有对 `服务器名称提示' 扩展（在 RFC 6066(2) 中定义）
     的内置支持。

     3.2 新版功能.

 -- 数据: ssl.HAS_NPN

     OpenSSL 库是否具有对 应用层协议协商(3) 中描述的 `下一协议协商' 的内
     置支持。 当此常量为真值时，你可以使用 *note
     SSLContext.set_npn_protocols(): a9f. 方法来公告你想要支持的协议。

     3.3 新版功能.

 -- 数据: ssl.HAS_SSLv2

     OpenSSL 库是否具有对 SSL 2.0 协议的内置支持。

     3.7 新版功能.

 -- 数据: ssl.HAS_SSLv3

     OpenSSL 库是否具有对 SSL 3.0 协议的内置支持。

     3.7 新版功能.

 -- 数据: ssl.HAS_TLSv1

     OpenSSL 库是否具有对 TLS 1.0 协议的内置支持。

     3.7 新版功能.

 -- 数据: ssl.HAS_TLSv1_1

     OpenSSL 库是否具有对 TLS 1.1 协议的内置支持。

     3.7 新版功能.

 -- 数据: ssl.HAS_TLSv1_2

     OpenSSL 库是否具有对 TLS 1.2 协议的内置支持。

     3.7 新版功能.

 -- 数据: ssl.HAS_TLSv1_3

     OpenSSL 库是否具有对 TLS 1.3 协议的内置支持。

     3.7 新版功能.

 -- 数据: ssl.CHANNEL_BINDING_TYPES

     受支持的 TLS 通道绑定类型组成的列表。 此列表中的字符串可被用作传给
     *note SSLSocket.get_channel_binding(): a9c. 的参数。

     3.3 新版功能.

 -- 数据: ssl.OPENSSL_VERSION

     解释器所加载的 OpenSSL 库的版本字符串:

          >>> ssl.OPENSSL_VERSION
          'OpenSSL 1.0.2k  26 Jan 2017'

     3.2 新版功能.

 -- 数据: ssl.OPENSSL_VERSION_INFO

     代表 OpenSSL 库的版本信息的五个整数所组成的元组:

          >>> ssl.OPENSSL_VERSION_INFO
          (1, 0, 2, 11, 15)

     3.2 新版功能.

 -- 数据: ssl.OPENSSL_VERSION_NUMBER

     OpenSSL 库的原始版本号，以单个整数表示:

          >>> ssl.OPENSSL_VERSION_NUMBER
          268443839
          >>> hex(ssl.OPENSSL_VERSION_NUMBER)
          '0x100020bf'

     3.2 新版功能.

 -- 数据: ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE
 -- 数据: ssl.ALERT_DESCRIPTION_INTERNAL_ERROR

 -- 数据: ALERT_DESCRIPTION_*

     来自 RFC 5246(4) 等文档的警报描述。 IANA TLS Alert Registry(5) 中包
     含了这个列表及对定义其含义的 RFC 引用。

     被用作 *note SSLContext.set_servername_callback(): 8d8. 中的回调函
     数的返回值。

     3.4 新版功能.

 -- 类: ssl.AlertDescription

     ALERT_DESCRIPTION_* 常量的 *note enum.IntEnum: 596. 多项集。

     3.6 新版功能.

 -- 数据: Purpose.SERVER_AUTH

     *note create_default_context(): 8c9. 和 *note
     SSLContext.load_default_certs(): 8d3. 的选项值。 这个值表明此上下文
     可以被用来验证 Web 服务器（因此，它将被用来创建客户端套接字）。

     3.4 新版功能.

 -- 数据: Purpose.CLIENT_AUTH

     *note create_default_context(): 8c9. 和 *note
     SSLContext.load_default_certs(): 8d3. 的选项值。 这个值表明此上下文
     可以被用来验证 Web 客户端（因此，它将被用来创建服务器端套接字）。

     3.4 新版功能.

 -- 类: ssl.SSLErrorNumber

     SSL_ERROR_* 常量的 *note enum.IntEnum: 596. 多项集。

     3.6 新版功能.

 -- 类: ssl.TLSVersion

     *note SSLContext.maximum_version: 3f0. 和 *note
     SSLContext.minimum_version: 3ef. 中的 SSL 和 TLS 版本的 *note
     enum.IntEnum: 596. 多项集。

     3.7 新版功能.

 -- 属性: TLSVersion.MINIMUM_SUPPORTED

 -- 属性: TLSVersion.MAXIMUM_SUPPORTED

     受支持的最低和最高 SSL 或 TLS 版本。 这些常量被称为魔术常量。 它们
     的值并不反映可用的最低和最高 TLS/SSL 版本。

 -- 属性: TLSVersion.SSLv3

 -- 属性: TLSVersion.TLSv1

 -- 属性: TLSVersion.TLSv1_1

 -- 属性: TLSVersion.TLSv1_2

 -- 属性: TLSVersion.TLSv1_3

     SSL 3.0 至 TLS 1.3。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc7301.html

   (2) https://tools.ietf.org/html/rfc6066.html

   (3) 
https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation

   (4) https://tools.ietf.org/html/rfc5246.html

   (5) 
https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6


File: python.info,  Node: SSL 套接字,  Next: SSL 上下文,  Prev: 方法、常量和异常处理,  Up: ssl --- 套接字对象的TLS/SSL封装

5.18.3.8 SSL 套接字
...................

 -- 类: ssl.SSLSocket (socket.socket)

     SSL 套接字提供了 *note 套接字对象: 2695. 的下列方法:

        - *note accept(): 67e.

        - *note bind(): 26a3.

        - *note close(): 609.

        - *note connect(): 67f.

        - *note detach(): ba5.

        - *note fileno(): 26a7.

        - *note getpeername(): 2602, *note getsockname(): 2603.

        - *note getsockopt(): 58b, *note setsockopt(): 58c.

        - *note gettimeout(): 26a8, *note settimeout(): 267a, *note
          setblocking(): 1f20.

        - *note listen(): 754.

        - *note makefile(): b21.

        - *note recv(): 680, *note recv_into(): cba. (but passing a
          non-zero ‘flags’ argument is not allowed)

        - *note send(): 683, *note sendall(): 684. (with the same
          limitation)

        - *note sendfile(): 753. (but *note os.sendfile: 362. will be
          used for plain-text sockets only, else *note send(): 683. will
          be used)

        - *note shutdown(): 26a4.

     但是，由于 SSL（和 TLS）协议在 TCP 之上具有自己的框架，因此 SSL 套
     接字抽象在某些方面可能与常规的 OS 层级套接字存在差异。 特别是要查看
     *note 非阻塞型套接字说明: 26bf.。

     *note SSLSocket: 3ea. 的实例必须使用 *note
     SSLContext.wrap_socket(): 3ed. 方法来创建。

     在 3.5 版更改: 新增了 ‘sendfile()’ 方法。

     在 3.5 版更改: ‘shutdown()’ 不会在每次接收或发送字节数据后重置套接
     字超时。 现在套接字超时为关闭的最大总持续时间。

     3.6 版后已移除: 直接创建 *note SSLSocket: 3ea. 实例的做法已被弃用，
     请使用 *note SSLContext.wrap_socket(): 3ed. 来包装套接字。

     在 3.7 版更改: *note SSLSocket: 3ea. 的实例必须使用 *note
     wrap_socket(): 3ed. 来创建。 在较早的版本中，直接创建实例是可能的。
     但这从未被记入文档或是被正式支持。

SSL 套接字还具有下列方法和属性:

 -- 方法: SSLSocket.read (len=1024, buffer=None)

     从 SSL 套接字读取至多 `len' 个字节的数据并将结果作为 ‘bytes’ 实例返
     回。 如果指定了 `buffer'，则改为读取到缓冲区，并返回所读取的字节数
     。

     如果套接字为 *note 非阻塞型: 26bf. 则会引发 *note SSLWantReadError:
     75f. 或 *note SSLWantWriteError: 760. 且读取将阻塞。

     由于在任何时候重新协商都是可能的，因此调用 *note read(): 764. 也可
     能导致写入操作。

     在 3.5 版更改: 套接字超时在每次接收或发送字节数据后不会再被重置。 现
     在套接字超时为读取至多 `len' 个字节数据的最大总持续时间。

     3.6 版后已移除: 请使用 ‘recv()’ 来代替 *note read(): 764.。

 -- 方法: SSLSocket.write (buf)

     将 `buf' 写入到 SSL 套接字并返回所写入的字节数。 `buf' 参数必须为支
     持缓冲区接口的对象。

     如果套接字为 *note 非阻塞型: 26bf. 则会引发 *note SSLWantReadError:
     75f. 或 *note SSLWantWriteError: 760. 且读取将阻塞。

     由于在任何时候重新协商都是可能的，因此调用 *note write(): 765. 也可
     能导致读取操作。

     在 3.5 版更改: 套接字超时在每次接收或发送字节数据后不会再被重置。 现
     在套接字超时为写入 `buf' 的最大总持续时间。

     3.6 版后已移除: 请使用 ‘send()’ 来代替 *note write(): 765.。

     注解: *note read(): 764. 和 *note write(): 765. 方法是读写未加密的
     应用级数据，并将其解密/加密为带加密的线路级数据的低层级方法。 这些
     方法需要有激活的 SSL 连接，即握手已完成而 *note SSLSocket.unwrap():
     26fd. 尚未被调用。

     通常你应当使用套接字 API 方法例如 *note recv(): 680. 和 *note
     send(): 683. 来代替这些方法。

 -- 方法: SSLSocket.do_handshake ()

     执行 SSL 设置握手。

     在 3.4 版更改: 当套接字的 *note context: 26fe. 的 *note
     check_hostname: 26d3. 属性为真值时此握手方法还会执行 *note
     match_hostname(): 3e4.。

     在 3.5 版更改: 套接字超时在每次接收或发送字节数据时不会再被重置。 现
     在套接字超时为握手的最大总持续时间。

     在 3.7 版更改: 主机名或 IP 地址会在握手期间由 OpenSSL 进行匹配。 函
     数 *note match_hostname(): 3e4. 将不再被使用。 在 OpenSSL 拒绝主机
     名和 IP 地址的情况下，握手将提前被中止并向对等方发送 TLS 警告消息。

 -- 方法: SSLSocket.getpeercert (binary_form=False)

     如果连接另一端的对等方没有证书，则返回 ‘None’。 如果 SSL 握手还未完
     成，则会引发 *note ValueError: 1fc.。

     如果 ‘binary_form’ 形参为 *note False: 390.，并且从对等方接收到了证
     书，此方法将返回一个 *note dict: 1b9. 实例。 如果证书未通过验证，则
     字典将为空。 如果证书通过验证，它将返回由多个密钥组成的字典，其中包
     括 ‘subject’ (证书颁发给的主体) 和 ‘issuer’ (颁发证书的主体)。 如果
     证书包含一个 `Subject Alternative Name' 扩展的实例 (see RFC
     3280(1))，则字典中还将有一个 ‘subjectAltName’ 键。

     ‘subject’ 和 ‘issuer’ 字段都是包含在证书中相应字段的数据结构中给出
     的相对专有名称（RDN）序列的元组，每个 RDN 均为 name-value 对的序列
     。 这里是一个实际的示例:

          {'issuer': ((('countryName', 'IL'),),
                      (('organizationName', 'StartCom Ltd.'),),
                      (('organizationalUnitName',
                        'Secure Digital Certificate Signing'),),
                      (('commonName',
                        'StartCom Class 2 Primary Intermediate Server CA'),)),
           'notAfter': 'Nov 22 08:15:19 2013 GMT',
           'notBefore': 'Nov 21 03:09:52 2011 GMT',
           'serialNumber': '95F0',
           'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
                       (('countryName', 'US'),),
                       (('stateOrProvinceName', 'California'),),
                       (('localityName', 'San Francisco'),),
                       (('organizationName', 'Electronic Frontier Foundation, Inc.'),),
                       (('commonName', '*.eff.org'),),
                       (('emailAddress', 'hostmaster@eff.org'),)),
           'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
           'version': 3}

          注解: 要验证特定服务的证书，你可以使用 *note match_hostname():
          3e4. 函数。

     如果 ‘binary_form’ 形参为 *note True: 4a1.，并且提供了证书，此方法
     会将整个证书的 DER 编码形式作为字节序列返回，或者如果对等方未提供证
     书则返回 *note None: 158.。 对等方是否提供证书取决于 SSL 套接字的角
     色:

        * 对于客户端 SSL 套接字，服务器将总是提供证书，无论是否需要进行
          验证;

        * 对于服务器 SSL 套接字，客户端将仅在服务器要求时才提供证书；因
          此如果你使用了 *note CERT_NONE: 26d0. (而不是 *note
          CERT_OPTIONAL: 26d2. 或 *note CERT_REQUIRED: 26bb.) 则 *note
          getpeercert(): 8d9. 将返回 *note None: 158.。

     在 3.2 版更改: 返回的字典包括额外的条目例如 ‘issuer’ 和
     ‘notBefore’。

     在 3.4 版更改: 如果握手未完成则会引发 *note ValueError: 1fc.。 返回
     的字典包括额外的 X509v3 扩展条目例如 ‘crlDistributionPoints’,
     ‘caIssuers’ 和 ‘OCSP’ URI。

     在 3.8.1 版更改: IPv6 地址字符串不再附带末尾换行符。

 -- 方法: SSLSocket.cipher ()

     返回由三个值组成的元组，其中包含所使用的密码名称，定义其使用方式的
     SSL 协议，以及所使用的加密比特位数。 如果尚未建立连接，则返回
     ‘None’。

 -- 方法: SSLSocket.shared_ciphers ()

     返回在握手期间由客户端共享的密码列表。 所返回列表的每个条目都是由三
     个值组成的元组，其中包括密码名称，定义其使用方式的 SSL 协议版本，以
     及密码所使用的加密比特位数。 如果尚未建立连接或套接字为客户端套接字
     则 *note shared_ciphers(): 762. 将返回 ‘None’。

     3.5 新版功能.

 -- 方法: SSLSocket.compression ()

     以字符串形式返回所使用的压缩算法，或者如果连接没有使用压缩则返回
     ‘None’。

     如果高层级的协议支持自己的压缩机制，你可以使用 *note
     OP_NO_COMPRESSION: a9e. 来禁用 SSL 层级的压缩。

     3.3 新版功能.

 -- 方法: SSLSocket.get_channel_binding (cb_type="tls-unique")

     为当前连接获取字节串形式的通道绑定数据。 如果尚未连接或握手尚未完成
     则返回 ‘None’。

     `cb_type' 形参允许选择需要的通道绑定类型。 有效的通道绑定类型在
     *note CHANNEL_BINDING_TYPES: 26ef. 列表中列出。 目前只支持由 RFC
     5929(2) 所定义的 ’tls-unique’ 通道绑定。 如果请求了一个不受支持的通
     道绑定类型则将引发 *note ValueError: 1fc.。

     3.3 新版功能.

 -- 方法: SSLSocket.selected_alpn_protocol ()

     返回在 TLS 握手期间所选择的协议。 如果 *note
     SSLContext.set_alpn_protocols(): 75a. 未被调用，如果另一方不支持
     ALPN，如果此套接字不支持任何客户端所用的协议，或者如果握手尚未发生
     ，则将返回 ‘None’。

     3.5 新版功能.

 -- 方法: SSLSocket.selected_npn_protocol ()

     返回在Return the higher-level protocol that was selected during the
     TLS/SSL 握手期间所选择的高层级协议。 如果 *note
     SSLContext.set_npn_protocols(): a9f. 未被调用，或者如果另一方不支持
     NPN，或者如果握手尚未发生，则将返回 ‘None’。

     3.3 新版功能.

 -- 方法: SSLSocket.unwrap ()

     执行 SSL 关闭握手，这会从下层的套接字中移除 TLS 层，并返回下层的套
     接字对象。 这可被用来通过一个连接将加密操作转为非加密。 返回的套接
     字应当总是被用于同连接另一方的进一步通信，而不是原始的套接字。

 -- 方法: SSLSocket.verify_client_post_handshake ()

     向一个 TLS 1.3 客户端请求握手后身份验证（PHA）。 只有在初始 TLS 握
     手之后且双方都启用了 PHA 的情况下才能为服务器端套接字的 TLS 1.3 连
     接启用 PHA，参见 *note SSLContext.post_handshake_auth: 225.。

     此方法不会立即执行证书交换。 服务器端会在下一次写入事件期间发送
     CertificateRequest 并期待客户端在下一次读取事件期间附带证书进行响应
     。

     如果有任何前置条件未被满足（例如非 TLS 1.3，PHA 未启用），则会引发
     *note SSLError: c17.。

          注解: 仅在 OpenSSL 1.1.1 且 TLS 1.3 被启用时可用。 没有 TLS
          1.3 支持，此方法将引发 *note NotImplementedError: 617.。

     3.8 新版功能.

 -- 方法: SSLSocket.version ()

     以字符串形式返回由连接协商确定的实际 SSL 协议版本，或者如果未建立安
     全连接则返回 ‘None’。 在撰写本文档时，可能的返回值包括 ‘"SSLv2"’,
     ‘"SSLv3"’, ‘"TLSv1"’, ‘"TLSv1.1"’ 和 ‘"TLSv1.2"’。 最新的 OpenSSL 版
     本可能会定义更多的返回值。

     3.5 新版功能.

 -- 方法: SSLSocket.pending ()

     返回在连接上等待被读取的已解密字节数。

 -- 属性: SSLSocket.context

     此 SSL 套接字所联结的 *note SSLContext: 3ec. 对象。 如果 SSL 套接字
     是使用已弃用的 *note wrap_socket(): 477. 函数 (而非 *note
     SSLContext.wrap_socket(): 3ed.) 创建的，则这将是为此 SSL 套接字创建
     的自定义上下文对象。

     3.2 新版功能.

 -- 属性: SSLSocket.server_side

     一个布尔值，对于服务器端套接字为 ‘True’ 而对于客户端套接字则为
     ‘False’。

     3.2 新版功能.

 -- 属性: SSLSocket.server_hostname

     服务器的主机名: *note str: 339. 类型，对于服务器端套接字或者如果构
     造器中未指定主机名则为 ‘None’。

     3.2 新版功能.

     在 3.7 版更改: 现在该属性将始终为 ASCII 文本。 当 ‘server_hostname’
     为一个国际化域名（IDN）时，该属性现在会保存为 A 标签形式
     (‘"xn--pythn-mua.org"’) 而非 U 标签形式 (‘"pythön.org"’)。

 -- 属性: SSLSocket.session

     用于 SSL 连接的 *note SSLSession: 594.。 该会话将在执行 TLS 握手后
     对客户端和服务器端套接字可用。 对于客户端套接字该会话可以在调用
     *note do_handshake(): 763. 之前被设置以重用一个会话。

     3.6 新版功能.

 -- 属性: SSLSocket.session_reused

     3.6 新版功能.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3280.html

   (2) https://tools.ietf.org/html/rfc5929.html


File: python.info,  Node: SSL 上下文,  Next: 证书,  Prev: SSL 套接字,  Up: ssl --- 套接字对象的TLS/SSL封装

5.18.3.9 SSL 上下文
...................

3.2 新版功能.

SSL 上下文可保存各种比单独 SSL 连接寿命更长的数据，例如 SSL 配置选项，证
书和私钥等。 它还可为服务器端套接字管理缓存，以加快来自相同客户端的重复
连接。

 -- 类: ssl.SSLContext (protocol=PROTOCOL_TLS)

     创建一个新的 SSL 上下文。 你可以传入 `protocol'，它必须为此模块中定
     义的 ‘PROTOCOL_*’ 常量之一。 该形参指定要使用哪个 SSL 协议版本。 通
     常，服务器会选择一个特定的协议版本，而客户端必须适应服务器的选择。
     大多数版本都不能与其他版本互操作。 如果未指定，则默认值为 *note
     PROTOCOL_TLS: 26b8.；它提供了与其他版本的最大兼容性。

     这个表显示了客户端（横向）的哪个版本能够连接服务器（纵向）的哪个版
     本。

          `客户端' / `服务器'          `SSLv2'          `SSLv3'          `TLS' (1)         `TLSv1'       `TLSv1.1'       `TLSv1.2'
                                                                                                                         
                                                                                                                         
          `SSLv2'                      是               否               否 (2)            否            否              否
                                                                                                                         
                                                                                                                         
          `SSLv3'                      否               是               否 (3)            否            否              否
                                                                                                                         
                                                                                                                         
          `TLS' (`SSLv23') (4)         否 (5)           否 (6)           是                是            是              是
                                                                                                                         
                                                                                                                         
          `TLSv1'                      否               否               是                是            否              否
                                                                                                                         
                                                                                                                         
          `TLSv1.1'                    否               否               是                否            是              否
                                                                                                                         
                                                                                                                         
          `TLSv1.2'                    否               否               是                否            否              是
                                                                                                                         

     备注
     ....

     参见
     ....

     *note create_default_context(): 8c9. 让 *note ssl: f4. 为特定目标选
     择安全设置。

     在 3.6 版更改: 上下文会使用安全默认值来创建。 默认设置的选项有
     *note OP_NO_COMPRESSION: a9e, *note OP_CIPHER_SERVER_PREFERENCE:
     aa3, *note OP_SINGLE_DH_USE: 26e1, *note OP_SINGLE_ECDH_USE: 26e2,
     *note OP_NO_SSLv2: ba8. (except for *note PROTOCOL_SSLv2: 26d9.) 和
     *note OP_NO_SSLv3: 26b9. (except for *note PROTOCOL_SSLv3: 26ca.)。
     初始密码集列表只包含 ‘HIGH’ 密码，不包含 ‘NULL’ 密码和 ‘MD5’ 密码
     (*note PROTOCOL_SSLv2: 26d9. 除外)。

*note SSLContext: 3ec. 对象具有以下方法和属性:

 -- 方法: SSLContext.cert_store_stats ()

     获取以字典表示的有关已加载的 X.509 证书数量，被标记为 CA 证书的
     X.509 证书数量以及证书吊销列表的的统计信息。

     具有一个 CA 证书和一个其他证书的上下文示例:

          >>> context.cert_store_stats()
          {'crl': 0, 'x509_ca': 1, 'x509': 2}

     3.4 新版功能.

 -- 方法: SSLContext.load_cert_chain (certfile, keyfile=None,
          password=None)

     加载一个私钥及对应的证书。 `certfile' 字符串必须为以 PEM 格式表示的
     单个文件路径，该文件中包含证书以及确立证书真实性所需的任意数量的 CA
     证书。 如果存在 `keyfile' 字符串，它必须指向一个包含私钥的文件。 否
     则私钥也将从 `certfile' 中提取。 请参阅 *note 证书: 2705. 中的讨论
     来了解有关如何将证书存储至 `certfile' 的更多信息。

     `password' 参数可以是一个函数，调用时将得到用于解密私钥的密码。 它
     在私钥被加密且需要密码时才会被调用。 它调用时将不带任何参数，并且应
     当返回一个字符串、字节串或字节数组。 如果返回值是一个字符串，在用它
     解密私钥之前它将以 UTF-8 进行编码。 或者也可以直接将字符串、字节串
     或字节数组值作为 `password' 参数提供。 如果私钥未被加密且不需要密码
     则它将被忽略。

     如果未指定 `password' 参数且需要一个密码，将会使用 OpenSSL 内置的密
     码提示机制来交互式地提示用户输入密码。

     如果私钥不能匹配证书则会引发 *note SSLError: c17.。

     在 3.3 版更改: 新增可选参数 `password'。

 -- 方法: SSLContext.load_default_certs (purpose=Purpose.SERVER_AUTH)

     从默认位置加载一组默认的 "证书颁发机构" (CA) 证书。 在 Windows 上它
     将从 ‘CA’ 和 ‘ROOT’ 系统存储中加载 CA 证书。 在其他系统上它会调用
     *note SSLContext.set_default_verify_paths(): 8cb.。 将来该方法也可
     能会从其他位置加载 CA 证书。

     `purpose' 旗标指明要加载哪一类 CA 证书。 默认设置 *note
     Purpose.SERVER_AUTH: 8d4. 加载被标记且被信任用于 TLS Web 服务器验证
     （客户端套接字）的证书。 *note Purpose.CLIENT_AUTH: 8d5. 则加载用于
     在服务器端进行客户端证书验证的 CA 证书。

     3.4 新版功能.

 -- 方法: SSLContext.load_verify_locations (cafile=None, capath=None,
          cadata=None)

     当 *note verify_mode: 26ba. 不为 *note CERT_NONE: 26d0. 时加载一组
     用于验证其他对等方证书的 "证书颁发机构" (CA) 证书。 必须至少指定
     `cafile' 或 `capath' 中的一个。

     此方法还可加载 PEM 或 DER 格式的证书吊销列表 (CRL)，为此必须正确配
     置 *note SSLContext.verify_flags: 8ce.。

     如果存在 `cafile' 字符串，它应为 PEM 格式的级联 CA 证书文件的路径。
     请参阅 *note 证书: 2705. 中的讨论来了解有关如何处理此文件中的证书的
     更多信息。

     如果存在 `capath' 字符串，它应为包含多个 PEM 格式的 CA 证书的目录的
     路径，并遵循 OpenSSL 专属布局(7)。

     如果存在 `cadata' 对象，它应为一个或多个 PEM 编码的证书的 ASCII 字
     符串或者 DER 编码的证书的 *note bytes-like object: 5f1.。 与
     `capath' 一样 PEM 编码的证书之外的多余行会被忽略，但至少要有一个证
     书。

     在 3.4 版更改: 新增可选参数 `cadata'

 -- 方法: SSLContext.get_ca_certs (binary_form=False)

     获取已离开法人 "证书颁发机构" (CA) 证书列表。 如果 ‘binary_form’ 形
     参为 *note False: 390. 则每个列表条目都是一个类似于 *note
     SSLSocket.getpeercert(): 8d9. 输出的字典。 在其他情况下此方法将返回
     一个 DER 编码的证书的列表。 返回的列表不包含来自 `capath' 的证书，
     除非 SSL 连接请求并加载了一个证书。

          注解: capath 目录中的证书不会被加载，除非它们已至少被使用过一
          次。

     3.4 新版功能.

 -- 方法: SSLContext.get_ciphers ()

     获取已启用密码的列表。 该列表将按密码的优先级排序。 参见 *note
     SSLContext.set_ciphers(): 26ce.。

     示例:

          >>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
          >>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA')
          >>> ctx.get_ciphers()  # OpenSSL 1.0.x
          [{'alg_bits': 256,
            'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH     Au=RSA  '
                           'Enc=AESGCM(256) Mac=AEAD',
            'id': 50380848,
            'name': 'ECDHE-RSA-AES256-GCM-SHA384',
            'protocol': 'TLSv1/SSLv3',
            'strength_bits': 256},
           {'alg_bits': 128,
            'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH     Au=RSA  '
                           'Enc=AESGCM(128) Mac=AEAD',
            'id': 50380847,
            'name': 'ECDHE-RSA-AES128-GCM-SHA256',
            'protocol': 'TLSv1/SSLv3',
            'strength_bits': 128}]

     在 OpenSSL 1.1 及更新的版本中密码字典会包含额外的字段:

          >>> ctx.get_ciphers()  # OpenSSL 1.1+
          [{'aead': True,
            'alg_bits': 256,
            'auth': 'auth-rsa',
            'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH     Au=RSA  '
                           'Enc=AESGCM(256) Mac=AEAD',
            'digest': None,
            'id': 50380848,
            'kea': 'kx-ecdhe',
            'name': 'ECDHE-RSA-AES256-GCM-SHA384',
            'protocol': 'TLSv1.2',
            'strength_bits': 256,
            'symmetric': 'aes-256-gcm'},
           {'aead': True,
            'alg_bits': 128,
            'auth': 'auth-rsa',
            'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH     Au=RSA  '
                           'Enc=AESGCM(128) Mac=AEAD',
            'digest': None,
            'id': 50380847,
            'kea': 'kx-ecdhe',
            'name': 'ECDHE-RSA-AES128-GCM-SHA256',
            'protocol': 'TLSv1.2',
            'strength_bits': 128,
            'symmetric': 'aes-128-gcm'}]

     *note 可用性: 136f.: OpenSSL 1.0.2+。

     3.6 新版功能.

 -- 方法: SSLContext.set_default_verify_paths ()

     从构建 OpenSSL 库时定义的文件系统路径中加载一组默认的 "证书颁发机构
     " (CA) 证书。 不幸的是，没有一种简单的方式能知道此方法是否执行成功
     ：如果未找到任何证书也不会返回错误。 不过，当 OpenSSL 库是作为操作
     系统的一部分被提供时，它的配置应当是正确的。

 -- 方法: SSLContext.set_ciphers (ciphers)

     为使用此上下文创建的套接字设置可用密码。 它应当为 OpenSSL 密码列表
     格式(8) 的字符串。 如果没有可被选择的密码（由于编译时选项或其他配置
     禁止使用所指定的任何密码），则将引发 *note SSLError: c17.。

          注解: 在连接后，SSL 套接字的 *note SSLSocket.cipher(): 2604. 方
          法将给出当前所选择的密码。

          在默认情况下 OpenSSL 1.1.1 会启用 TLS 1.3 密码套件。 该套件不
          能通过 *note set_ciphers(): 26ce. 来禁用。

 -- 方法: SSLContext.set_alpn_protocols (protocols)

     指定在 SSL/TLS 握手期间套接字应当通告的协议。 它应为由 ASCII 字符串
     组成的列表，例如 ‘['http/1.1', 'spdy/2']’，按首选顺序排列。 协议的
     选择将在握手期间发生，并依据 RFC 7301(9) 来执行。 在握手成功后，
     *note SSLSocket.selected_alpn_protocol(): 75b. 方法将返回已达成一致
     的协议。

     如果 *note HAS_ALPN: 75c. 为 ‘False’ 则此方法将引发 *note
     NotImplementedError: 617.。

     当双方都支持 ALPN 但不能就协议达成一致时 OpenSSL 1.1.0 至 1.1.0e 将
     中止并引发 *note SSLError: c17.。 1.1.0f+ 的行为类似于 1.0.2，*note
     SSLSocket.selected_alpn_protocol(): 75b. 返回 None。

     3.5 新版功能.

 -- 方法: SSLContext.set_npn_protocols (protocols)

     指定在Specify which protocols the socket should advertise during
     the SSL/TLS 握手期间套接字应当通告的协议。 它应为由字符串组成的列表
     ，例如 ‘['http/1.1', 'spdy/2']’，按首选顺序排列。 协议的选择将在握
     手期间发生，并将依据 应用层协议协商(10) 来执行。 在握手成功后，
     *note SSLSocket.selected_npn_protocol(): 26ff. 方法将返回已达成一致
     的协议。

     如果 *note HAS_NPN: 26e9. 为 ‘False’ 则此方法将引发 *note
     NotImplementedError: 617.。

     3.3 新版功能.

 -- 属性: SSLContext.sni_callback

     注册一个回调函数，当 TLS 客户端指定了一个服务器名称提示时，该回调函
     数将在 SSL/TLS 服务器接收到 TLS Client Hello 握手消息后被调用。 服
     务器名称提示机制的定义见 RFC 6066(11) section 3 - Server Name
     Indication。

     每个 ‘SSLContext’ 只能设置一个回调。 如果 `sni_callback' 被设置为
     ‘None’ 则会禁用回调。 对该函数的后续调用将禁用之前注册的回调。

     此回调函数将附带三个参数来调用；第一个参数是 *note ssl.SSLSocket:
     3ea.，第二个参数是代表客户端准备与之通信的服务器的字符串 (或者如果
     TLS Client Hello 不包含服务器名称则为 *note None: 158.) 而第三个参
     数是原来的 *note SSLContext: 3ec.。 服务器名称参数为文本形式。 对于
     国际化域名，服务器名称是一个 IDN A 标签 (‘"xn--pythn-mua.org"’)。

     此回调的一个典型用法是将 *note ssl.SSLSocket: 3ea. 的 *note
     SSLSocket.context: 26fe. 属性修改为一个 *note SSLContext: 3ec. 类型
     的新对象，该对象代表与服务器相匹配的证书链。

     由于 TLS 连接处于早期协商阶段，因此仅能使用有限的方法和属性例如
     *note SSLSocket.selected_alpn_protocol(): 75b. 和 *note
     SSLSocket.context: 26fe.。 *note SSLSocket.getpeercert(): 8d9,
     *note SSLSocket.getpeercert(): 8d9, *note SSLSocket.cipher(): 2604.
     和 ‘SSLSocket.compress()’ 方法要求 TLS 连接已经过 TLS Client Hello
     因而将既不包含返回有意义的值，也不能安全地调用它们。

     `sni_callback' 函数必须返回 ‘None’ 以允许 TLS 协商继续进行。 如果想
     要 TLS 失败，则可以返回常量 *note ALERT_DESCRIPTION_*: 26f1.。 其他
     返回值将导致 TLS 的致命错误 *note ALERT_DESCRIPTION_INTERNAL_ERROR:
     26f1.

     如果从 `sni_callback' 函数引发了异常，则 TLS 连接将终止并发出 TLS 致
     命警告消息 *note ALERT_DESCRIPTION_HANDSHAKE_FAILURE: 26f0.。

     如果 OpenSSL library 库在构建时定义了 OPENSSL_NO_TLSEXT 则此方法将
     返回 *note NotImplementedError: 617.。

     3.7 新版功能.

 -- 属性: SSLContext.set_servername_callback (server_name_callback)

     这是被保留用于向下兼容的旧式 API。 在可能的情况下，你应当改用 *note
     sni_callback: eb8.。 给出的 `server_name_callback' 类似于
     `sni_callback'，不同之处在于当服务器主机名是 IDN 编码的国际化域名时
     ，`server_name_callback' 会接收到一个已编码的 U 标签
     (‘"pythön.org"’)。

     如果发生了服务器名称解码错误。 TLS 连接将终止并向客户端发出 *note
     ALERT_DESCRIPTION_INTERNAL_ERROR: 26f1. 致命的 TLS 警告消息。

     3.4 新版功能.

 -- 方法: SSLContext.load_dh_params (dhfile)

     加载密钥生成参数用于 Diffie-Hellman (DH) 密钥交换。 使用 DH 密钥交
     换能以消耗（服务器和客户端的）计算资源为代价提升前向保密性。
     `dhfile' 参数应当为指向一个包含 PEM 格式的 DH 形参的文件的路径。

     此设置不会应用于客户端套接字。 你还可以使用 *note OP_SINGLE_DH_USE:
     26e1. 选项来进一步提升安全性。

     3.3 新版功能.

 -- 方法: SSLContext.set_ecdh_curve (curve_name)

     为基于椭圆曲线的 Elliptic Curve-based Diffie-Hellman (ECDH) 密钥交
     换设置曲线名称。 ECDH 显著快于常规 DH 同时据信同样安全。
     `curve_name' 形参应为描述某个知名椭圆曲线的字符串，例如受到广泛支持
     的曲线 ‘prime256v1’。

     此设置不会应用于客户端套接字。 你还可以使用 *note
     OP_SINGLE_ECDH_USE: 26e2. 选项来进一步提升安全性。

     如果 *note HAS_ECDH: 26e7. 为 ‘False’ 则此方法将不可用。

     3.3 新版功能.

     参见
     ....

     SSL/TLS 与完美的前向保密性(12)

          Vincent Bernat。

 -- 方法: SSLContext.wrap_socket (sock, server_side=False,
          do_handshake_on_connect=True, suppress_ragged_eofs=True,
          server_hostname=None, session=None)

     包装一个现有的 Python 套接字 `sock' 并返回一个 *note
     SSLContext.sslsocket_class: 2706. 的实例 (默认为 *note SSLSocket:
     3ea.)。 返回的 SSL 套接字会绑定上下文、设置以及证书。 `sock' 必须是
     一个 *note SOCK_STREAM: c92. 套接字；其他套接字类型不被支持。

     形参 ‘server_side’ 是一个布尔值，它标明希望从该套接字获得服务器端行
     为还是客户端行为。

     对于客户端套接字，上下文的构造会延迟执行；如果下层的套接字尚未连接
     ，上下文的构造将在对套接字调用 ‘connect()’ 之后执行。 对于服务器端
     套接字，如果套接字没有远端对等方，它会被视为一个监听套接字，并且服
     务器端 SSL 包装操作会在通过 ‘accept()’ 方法所接受的客户端连接上自动
     执行。 此方法可能会引发 *note SSLError: c17.。

     在客户端连接上，可选形参 `server_hostname' 指定所要连接的服务的主机
     名。 这允许单个服务器托管具有单独证书的多个基于 SSL 的服务，很类似
     于 HTTP 虚拟主机。 如果 `server_side' 为真值则指定
     `server_hostname' 将引发 *note ValueError: 1fc.。

     形参 ‘do_handshake_on_connect’ 指明是否要在调用 ‘socket.connect()’
     之后自动执行 SSL 握手，还是要通过发起调用 *note
     SSLSocket.do_handshake(): 763. 方法让应用程序显式地调用它。 显式地
     调用 *note SSLSocket.do_handshake(): 763. 可给予程序对握手中所涉及
     的套接字 I/O 阻塞行为的控制。

     形参 ‘suppress_ragged_eofs’ 指明 ‘SSLSocket.recv()’ 方法应当如何从
     连接的另一端发送非预期的 EOF 信号。 如果指定为 *note True: 4a1. (默
     认值)，它将返回正常的 EOF (空字节串对象) 来响应从下层套接字引发的非
     预期的 EOF 错误；如果指定为 *note False: 390.，它将向调用方引发异常
     。

     `session'，参见 *note session: 2702.。

     在 3.5 版更改: 总是允许传送 server_hostname，即使 OpenSSL 没有 SNI。

     在 3.6 版更改: 增加了 `session' 参数。

     在 3.7 版更改: 此方法返回 *note SSLContext.sslsocket_class: 2706. 的
     实例而非硬编码的 *note SSLSocket: 3ea.。

 -- 属性: SSLContext.sslsocket_class

     *note SSLContext.wrap_socket(): 3ed. 的返回类型，默认为 *note
     SSLSocket: 3ea.。 该属性可以在类实例上被重载以便返回自定义的 *note
     SSLSocket: 3ea. 的子类。

     3.7 新版功能.

 -- 方法: SSLContext.wrap_bio (incoming, outgoing, server_side=False,
          server_hostname=None, session=None)

     包装 BIO 对象 `incoming' 和 `outgoing' 并返回一个 *note
     SSLContext.sslobject_class: 2707. (默认为 *note SSLObject: 3eb.) 的
     实例。 SSL 例程将从 BIO 中读取输入数据并将数据写入到 outgoing BIO。

     `server_side', `server_hostname' 和 `session' 形参具有与 *note
     SSLContext.wrap_socket(): 3ed. 中相同的含义。

     在 3.6 版更改: 增加了 `session' 参数。

     在 3.7 版更改: 此方法返回 *note SSLContext.sslobject_class: 2707. 的
     实例则非硬编码的 *note SSLObject: 3eb.。

 -- 属性: SSLContext.sslobject_class

     *note SSLContext.wrap_bio(): 3ee. 的返回类型，默认为 *note
     SSLObject: 3eb.。 该属性可以在类实例上被重载以便返回自定义的 *note
     SSLObject: 3eb. 的子类。

     3.7 新版功能.

 -- 方法: SSLContext.session_stats ()

     获取由此上下文所创建或管理的 SSL 会话的相关统计信息。 返回将每个 信
     息片(13) 的名称映射到其数字值的字典。 例如，以下是自上下文被创建以
     来会话缓存中命中和未命中的总数:

          >>> stats = context.session_stats()
          >>> stats['hits'], stats['misses']
          (0, 0)

 -- 属性: SSLContext.check_hostname

     是否要将匹配 *note SSLSocket.do_handshake(): 763. 中对等方证书的主
     机名。 该上下文的 *note verify_mode: 26ba. 必须被设为 *note
     CERT_OPTIONAL: 26d2. 或 *note CERT_REQUIRED: 26bb.，并且你必须将
     `server_hostname' 传给 *note wrap_socket(): 3ed. 以便匹配主机名。 启
     用主机名检查会自动将 *note verify_mode: 26ba. 从 *note CERT_NONE:
     26d0. 设为 *note CERT_REQUIRED: 26bb.。 只要启用了主机名检查就无法
     将其设回 *note CERT_NONE: 26d0.。 *note PROTOCOL_TLS_CLIENT: 26d1.
     协议默认启用主机名检查。 对于其他协议，则必须显式地启用主机名检查。

     示例:

          import socket, ssl

          context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
          context.verify_mode = ssl.CERT_REQUIRED
          context.check_hostname = True
          context.load_default_certs()

          s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
          ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com')
          ssl_sock.connect(('www.verisign.com', 443))

     3.4 新版功能.

     在 3.7 版更改: 现在当主机名检查被启用且 *note verify_mode: 26ba. 为
     *note CERT_NONE: 26d0. 时 *note verify_mode: 26ba. 会自动更改为
     *note CERT_REQUIRED: 26bb.。 在之前版本中同样的操作将失败并引发
     *note ValueError: 1fc.。

          注解: 此特性要求 OpenSSL 0.9.8f 或更新的版本。

 -- 属性: SSLContext.keylog_filename

     每当生成或接收到密钥时，将 TLS 密钥写入到一个密钥日志文件。 密钥日
     志文件的设计仅适用于调试目的。 文件的格式由 NSS 指明并为许多流量分
     析工具例如 Wireshark 所使用。 日志文件会以追加模式打开。 写入操作会
     在线程之间同步，但不会在进程之间同步。

     3.8 新版功能.

          注解: 此特性要求 OpenSSL 1.1.1 或更新的版本。

 -- 属性: SSLContext.maximum_version

     一个代表所支持的最高 TLS 版本的 *note TLSVersion: 26f4. 枚举成员。
     该值默认为 *note TLSVersion.MAXIMUM_SUPPORTED: 26f6.。 这个属性对于
     *note PROTOCOL_TLS: 26b8, *note PROTOCOL_TLS_CLIENT: 26d1. 和 *note
     PROTOCOL_TLS_SERVER: 26d7. 以外的其他协议来说都是只读的。

     *note maximum_version: 3f0, *note minimum_version: 3ef. 和 *note
     SSLContext.options: 26cd. 等属性都会影响上下文所支持的 SSL 和 TLS 版
     本。 这个实现不会阻止无效的组合。 例如一个 *note options: 26cd. 为
     *note OP_NO_TLSv1_2: 26de. 而 *note maximum_version: 3f0. 设为
     *note TLSVersion.TLSv1_2: 26fa. 的上下文将无法建立 TLS 1.2 连接。

          注解: 除非 ssl 模块使用 OpenSSL 1.1.0g 或更新的版本编译否则这
          个属性将不可用。

     3.7 新版功能.

 -- 属性: SSLContext.minimum_version

     与 *note SSLContext.maximum_version: 3f0. 类似，区别在于它是所支持
     的最低版本或为 *note TLSVersion.MINIMUM_SUPPORTED: 26f5.。

          注解: 除非 ssl 模块使用 OpenSSL 1.1.0g 或更新的版本编译否则这
          个属性将不可用。

     3.7 新版功能.

 -- 属性: SSLContext.num_tickets

     控制 ‘TLS_PROTOCOL_SERVER’ 上下文的 TLS 1.3 会话凭据数量。 这个设置
     不会影响 TLS 1.0 到 1.2 连接。

          注解: 除非 ssl 模块使用 OpenSSL 1.1.1 或更新的版本编译否则这个
          属性将不可用。

     3.8 新版功能.

 -- 属性: SSLContext.options

     一个代表此上下文中所启用的 SSL 选项集的整数。 默认值为 *note
     OP_ALL: 26db.，但你也可以通过在选项间进行 OR 运算来指定其他选项例如
     *note OP_NO_SSLv2: ba8.。

          注解: 对于 0.9.8m 之前的 OpenSSL 版本，只能设置选项，而不能清
          除它们。 尝试（通过重置相应比特位）清除选项将会引发 *note
          ValueError: 1fc.。

     在 3.6 版更改: *note SSLContext.options: 26cd. 返回 *note Options:
     26e4. 旗标:

          >>> ssl.create_default_context().options
          <Options.OP_ALL|OP_NO_SSLv3|OP_NO_SSLv2|OP_NO_COMPRESSION: 2197947391>

 -- 属性: SSLContext.post_handshake_auth

     启用 TLS 1.3 握手后客户端身份验证。 握手后验证默认是被禁用的，服务
     器只能在初始握手期间请求 TLS 客户端证书。 当启用时，服务器可以在握
     手之后的任何时候请求 TLS 客户端证书。

     当在客户端套接字上启用时，客户端会向服务器发信号说明它支持握手后身
     份验证。

     当在服务器端套接字上启用时，*note SSLContext.verify_mode: 26ba. 也
     必须被设为 *note CERT_OPTIONAL: 26d2. 或 *note CERT_REQUIRED:
     26bb.。 实际的客户端证书交换会被延迟直至 *note
     SSLSocket.verify_client_post_handshake(): 226. 被调用并执行了一些
     I/O 操作后再进行。

          注解: 仅在 OpenSSL 1.1.1 且 TLS 1.3 被启用时可用。 如果没有
          TLS 1.3 支持，该属性值将为 None 且不可被更改

     3.8 新版功能.

 -- 属性: SSLContext.protocol

     构造上下文时所选择的协议版本。 这个属性是只读的。

 -- 属性: SSLContext.hostname_checks_common_name

     在没有目标替代名称扩展的情况下 *note check_hostname: 26d3. 是否要回
     退为验证证书的通用名称（默认为真值）。

          注解: 仅在 OpenSSL 1.1.0 或更新的版本上可写。

     3.7 新版功能.

     在 3.9.3 版更改: 此旗标在 OpenSSL 1.1.1k 之前的版本上不起作用。
     Python 3.8.9, 3.9.3, 和 3.10 包含了针对之前版本的变通处理。

 -- 属性: SSLContext.verify_flags

     证书验证操作的旗标。 你可以通过对 *note VERIFY_CRL_CHECK_LEAF: 8d0.
     等值执行 OR 运算来设置组合旗标。 在默认情况下 OpenSSL 不会要求也不
     会验证证书吊销列表（CRL）。 仅在 openssl 版本 0.9.8+ 上可用。

     3.4 新版功能.

     在 3.6 版更改: *note SSLContext.verify_flags: 8ce. 返回 *note
     VerifyFlags: 26d6. 旗标:

          >>> ssl.create_default_context().verify_flags
          <VerifyFlags.VERIFY_X509_TRUSTED_FIRST: 32768>

 -- 属性: SSLContext.verify_mode

     是否要尝试验证其他对等方的证书以及如果验证失败应采取何种行为。 该属
     性值必须为 *note CERT_NONE: 26d0, *note CERT_OPTIONAL: 26d2. 或
     *note CERT_REQUIRED: 26bb. 之一。

     在 3.6 版更改: *note SSLContext.verify_mode: 26ba. 返回 *note
     VerifyMode: 26d4. 枚举:

          >>> ssl.create_default_context().verify_mode
          <VerifyMode.CERT_REQUIRED: 2>

   ---------- Footnotes ----------

   (1) (3) TLS 1.3 协议在 OpenSSL >= 1.1.1 中设置 *note PROTOCOL_TLS:
26b8. 时可用。 没有专门针对 TLS 1.3 的 PROTOCOL 常量。

   (2) (1) *note SSLContext: 3ec. 默认设置 *note OP_NO_SSLv2: ba8. 以禁
用 SSLv2。

   (3) (2) *note SSLContext: 3ec. 默认设置 *note OP_NO_SSLv3: 26b9. 以禁
用 SSLv3。

   (4) (3) TLS 1.3 协议在 OpenSSL >= 1.1.1 中设置 *note PROTOCOL_TLS:
26b8. 时可用。 没有专门针对 TLS 1.3 的 PROTOCOL 常量。

   (5) (1) *note SSLContext: 3ec. 默认设置 *note OP_NO_SSLv2: ba8. 以禁
用 SSLv2。

   (6) (2) *note SSLContext: 3ec. 默认设置 *note OP_NO_SSLv3: 26b9. 以禁
用 SSLv3。

   (7) 
https://www.openssl.org/docs/manmaster/man3/SSL_CTX_load_verify_locations.html

   (8) https://www.openssl.org/docs/manmaster/man1/ciphers.html

   (9) https://tools.ietf.org/html/rfc7301.html

   (10) 
https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation

   (11) https://tools.ietf.org/html/rfc6066.html

   (12) 
https://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy

   (13) 
https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_sess_number.html


File: python.info,  Node: 证书,  Next: 例子<16>,  Prev: SSL 上下文,  Up: ssl --- 套接字对象的TLS/SSL封装

5.18.3.10 证书
..............

总的来说证书是公钥/私钥系统的一个组成部分。 在这个系统中，每 个 `主体'
(可能是一台机器、一个人或者一个组织) 都会分配到唯一的包含两部分的加密密
钥。 一部分密钥是公开的，称为 `公钥'；另一部分密钥是保密的，称为 `私钥
'。 这两个部分是互相关联的，就是说如果你用其中一个部分来加密一条消息，你
将能用并且 `只能' 用另一个部分来解密它。

在一个证书中包含有两个主体的相关信息。 它包含 `目标方' 的名称和目标方的
公钥。 它还包含由第二个主体 `颁发方' 所发布的声明：目标方的身份与他们所
宣称的一致，包含的公钥也确实是目标方的公钥。 颁发方的声明使用颁发方的私
钥进行签名，该私钥的内容只有颁发方自己才知道。 但是，任何人都可以找到颁
发方的公钥，用它来解密这个声明，并将其与证书中的其他信息进行比较来验证颁
发方声明的真实性。 证书还包含有关其有效期限的信息。 这被表示为两个字段，
即 "notBefore" 和 "notAfter"。

在 Python 中应用证书时，客户端或服务器可以用证书来证明自己的身份。 还可
以要求网络连接的另一方提供证书，提供的证书可以用于验证以满足客户端或服务
器的验证要求。 如果验证失败，连接尝试可被设置为引发一个异常。 验证是由下
层的 OpenSSL 框架来自动执行的；应用程序本身不必关注其内部的机制。 但是应
用程序通常需要提供一组证书以允许此过程的发生。

Python 使用文件来包含证书。 它们应当采用 "PEM" 格式 (参见 RFC 1422(1))，
这是一种带有头部行和尾部行的 base-64 编码包装形式:

     -----BEGIN CERTIFICATE-----
     ... (certificate in base64 PEM encoding) ...
     -----END CERTIFICATE-----

* Menu:

* 证书链::
* CA 证书::
* 合并的密钥和证书::
* 自签名证书::

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc1422.html


File: python.info,  Node: 证书链,  Next: CA 证书,  Up: 证书

5.18.3.11 证书链
................

包含证书的 Python 文件可以包含一系列的证书，有时被称为 `证书链'。 这个证
书链应当以 "作为" 客户端或服务器的主体的专属证书打头，然后是证书颁发方的
证书，然后是 `上述' 证书的颁发方的证书，证书链就这样不断上溯直到你得到一
个 `自签名' 的证书，即具有相同目标方和颁发方的证书，有时也称为 `根证书
'。 在证书文件中这些证书应当被拼接为一体。 例如，假设我们有一个包含三个
证书的证书链，以我们的服务器证书打头，然后是为我们的服务器证书签名的证书
颁发机构的证书，最后是为证书颁发机构的证书颁发证书的机构的根证书:

     -----BEGIN CERTIFICATE-----
     ... (certificate for your server)...
     -----END CERTIFICATE-----
     -----BEGIN CERTIFICATE-----
     ... (the certificate for the CA)...
     -----END CERTIFICATE-----
     -----BEGIN CERTIFICATE-----
     ... (the root certificate for the CA's issuer)...
     -----END CERTIFICATE-----


File: python.info,  Node: CA 证书,  Next: 合并的密钥和证书,  Prev: 证书链,  Up: 证书

5.18.3.12 CA 证书
.................

如果你想要求对连接的另一方的证书进行验证，你必须提供一个 "CA 证书" 文件
，其中包含了你愿意信任的每个颁发方的证书链。 同样地，这个文件的内容就是
这些证书链拼接在一起的结果。 为了进行验证，Python 将使用它在文件中找到的
第一个匹配的证书链。 可以通过调用 *note SSLContext.load_default_certs():
8d3. 来使用系统平台的证书文件，这可以由 *note create_default_context():
8c9. 自动完成。


File: python.info,  Node: 合并的密钥和证书,  Next: 自签名证书,  Prev: CA 证书,  Up: 证书

5.18.3.13 合并的密钥和证书
..........................

私钥往往与证书存储在相同的文件中；在此情况下，只需要将 ‘certfile’ 形参传
给 *note SSLContext.load_cert_chain(): a99. 和 *note wrap_socket():
477.。 如果私钥是与证书一起存储的，则它应当放在证书链的第一个证书之前:

     -----BEGIN RSA PRIVATE KEY-----
     ... (private key in base64 encoding) ...
     -----END RSA PRIVATE KEY-----
     -----BEGIN CERTIFICATE-----
     ... (certificate in base64 PEM encoding) ...
     -----END CERTIFICATE-----


File: python.info,  Node: 自签名证书,  Prev: 合并的密钥和证书,  Up: 证书

5.18.3.14 自签名证书
....................

如果你准备创建一个提供 SSL 加密连接服务的服务器，你需要为该服务获取一份
证书。 有许多方式可以获取合适的证书，例如从证书颁发机构购买。 另一种常见
做法是生成自签名证书。 生成自签名证书的最简单方式是使用 OpenSSL 软件包，
代码如下所示:

     % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
     Generating a 1024 bit RSA private key
     .......++++++
     .............................++++++
     writing new private key to 'cert.pem'
     -----
     You are about to be asked to enter information that will be incorporated
     into your certificate request.
     What you are about to enter is what is called a Distinguished Name or a DN.
     There are quite a few fields but you can leave some blank
     For some fields there will be a default value,
     If you enter '.', the field will be left blank.
     -----
     Country Name (2 letter code) [AU]:US
     State or Province Name (full name) [Some-State]:MyState
     Locality Name (eg, city) []:Some City
     Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
     Organizational Unit Name (eg, section) []:My Group
     Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
     Email Address []:ops@myserver.mygroup.myorganization.com
     %

自签名证书的缺点在于它是它自身的根证书，因此不会存在于别人的已知（且信任
的）根证书缓存当中。


File: python.info,  Node: 例子<16>,  Next: 关于非阻塞套接字的说明,  Prev: 证书,  Up: ssl --- 套接字对象的TLS/SSL封装

5.18.3.15 例子
..............

* Menu:

* 检测 SSL 支持::
* 客户端操作::
* 服务器端操作::


File: python.info,  Node: 检测 SSL 支持,  Next: 客户端操作,  Up: 例子<16>

5.18.3.16 检测 SSL 支持
.......................

要检测一个 Python 安装版中是否带有 SSL 支持，用户代码应当使用以下例程:

     try:
         import ssl
     except ImportError:
         pass
     else:
         ...  # do something that requires SSL support


File: python.info,  Node: 客户端操作,  Next: 服务器端操作,  Prev: 检测 SSL 支持,  Up: 例子<16>

5.18.3.17 客户端操作
....................

这个例子创建了一个 SSL 上下文并使用客户端套接字的推荐安全设置，包括自动
证书验证:

     >>> context = ssl.create_default_context()

如果你喜欢自行调整安全设置，你可能需要从头创建一个上下文（但是请请注意避
免不正确的设置）:

     >>> context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
     >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")

(这段代码假定你的操作系统将所有 CA 证书打包存放于
‘/etc/ssl/certs/ca-bundle.crt’；如果不是这样，你将收到报错信息，必须修改
此位置)

*note PROTOCOL_TLS_CLIENT: 26d1. 协议配置用于证书验证和主机名验证的上下
文。 *note verify_mode: 26ba. 设为 *note CERT_REQUIRED: 26bb. 而 *note
check_hostname: 26d3. 设为 ‘True’。 所有其他协议都会使用不安全的默认值创
建 SSL 上下文。

当你使用此上下文去连接服务器时，*note CERT_REQUIRED: 26bb. 和 *note
check_hostname: 26d3. 会验证服务器证书；它将确认服务器证书使用了某个 CA
证书进行签名，检查签名是否正确，并验证其他属性例如主机名的有效性和身份真
实性:

     >>> conn = context.wrap_socket(socket.socket(socket.AF_INET),
     ...                            server_hostname="www.python.org")
     >>> conn.connect(("www.python.org", 443))

你可以随后获取该证书:

     >>> cert = conn.getpeercert()

可视化检查显示证书能够证明目标服务 (即 HTTPS 主机 ‘www.python.org’) 的身
份:

     >>> pprint.pprint(cert)
     {'OCSP': ('http://ocsp.digicert.com',),
      'caIssuers': ('http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt',),
      'crlDistributionPoints': ('http://crl3.digicert.com/sha2-ev-server-g1.crl',
                                'http://crl4.digicert.com/sha2-ev-server-g1.crl'),
      'issuer': ((('countryName', 'US'),),
                 (('organizationName', 'DigiCert Inc'),),
                 (('organizationalUnitName', 'www.digicert.com'),),
                 (('commonName', 'DigiCert SHA2 Extended Validation Server CA'),)),
      'notAfter': 'Sep  9 12:00:00 2016 GMT',
      'notBefore': 'Sep  5 00:00:00 2014 GMT',
      'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26',
      'subject': ((('businessCategory', 'Private Organization'),),
                  (('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
                  (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
                  (('serialNumber', '3359300'),),
                  (('streetAddress', '16 Allen Rd'),),
                  (('postalCode', '03894-4801'),),
                  (('countryName', 'US'),),
                  (('stateOrProvinceName', 'NH'),),
                  (('localityName', 'Wolfeboro'),),
                  (('organizationName', 'Python Software Foundation'),),
                  (('commonName', 'www.python.org'),)),
      'subjectAltName': (('DNS', 'www.python.org'),
                         ('DNS', 'python.org'),
                         ('DNS', 'pypi.org'),
                         ('DNS', 'docs.python.org'),
                         ('DNS', 'testpypi.org'),
                         ('DNS', 'bugs.python.org'),
                         ('DNS', 'wiki.python.org'),
                         ('DNS', 'hg.python.org'),
                         ('DNS', 'mail.python.org'),
                         ('DNS', 'packaging.python.org'),
                         ('DNS', 'pythonhosted.org'),
                         ('DNS', 'www.pythonhosted.org'),
                         ('DNS', 'test.pythonhosted.org'),
                         ('DNS', 'us.pycon.org'),
                         ('DNS', 'id.python.org')),
      'version': 3}

现在 SSL 通道已建立并已验证了证书，你可以继续与服务器对话了:

     >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
     >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
     [b'HTTP/1.1 200 OK',
      b'Date: Sat, 18 Oct 2014 18:27:20 GMT',
      b'Server: nginx',
      b'Content-Type: text/html; charset=utf-8',
      b'X-Frame-Options: SAMEORIGIN',
      b'Content-Length: 45679',
      b'Accept-Ranges: bytes',
      b'Via: 1.1 varnish',
      b'Age: 2188',
      b'X-Served-By: cache-lcy1134-LCY',
      b'X-Cache: HIT',
      b'X-Cache-Hits: 11',
      b'Vary: Cookie',
      b'Strict-Transport-Security: max-age=63072000; includeSubDomains',
      b'Connection: close',
      b'',
      b'']

参见下文对于 *note 安全考量: 25bd. 的讨论。


File: python.info,  Node: 服务器端操作,  Prev: 客户端操作,  Up: 例子<16>

5.18.3.18 服务器端操作
......................

对于服务器操作，通常你需要在文件中存放服务器证书和私钥各一份。 你将首先
创建一个包含密钥和证书的上下文，这样客户端就能检查你的身份真实性。 然后
你将打开一个套接字，将其绑定到一个端口，在其上调用 ‘listen()’，并开始等
待客户端连接:

     import socket, ssl

     context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
     context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")

     bindsocket = socket.socket()
     bindsocket.bind(('myaddr.mydomain.com', 10023))
     bindsocket.listen(5)

当有客户端连接时，你将在套接字上调用 ‘accept()’ 以从另一端获取新的套接字
，并使用上下文的 *note SSLContext.wrap_socket(): 3ed. 方法来为连接创建一
个服务器端 SSL 套接字:

     while True:
         newsocket, fromaddr = bindsocket.accept()
         connstream = context.wrap_socket(newsocket, server_side=True)
         try:
             deal_with_client(connstream)
         finally:
             connstream.shutdown(socket.SHUT_RDWR)
             connstream.close()

随后你将从 ‘connstream’ 读取数据并对其进行处理，直至你结束与客户端的会话
（或客户端结束与你的会话）:

     def deal_with_client(connstream):
         data = connstream.recv(1024)
         # empty data means the client is finished with us
         while data:
             if not do_something(connstream, data):
                 # we'll assume do_something returns False
                 # when we're finished with client
                 break
             data = connstream.recv(1024)
         # finished with client

并返回至监听新的客户端连接（当然，真正的服务器应当会在单独的线程中处理每
个客户端连接，或者将套接字设为 *note 非阻塞模式: 26bf. 并使用事件循环）
。


File: python.info,  Node: 关于非阻塞套接字的说明,  Next: 内存 BIO 支持<2>,  Prev: 例子<16>,  Up: ssl --- 套接字对象的TLS/SSL封装

5.18.3.19 关于非阻塞套接字的说明
................................

在非阻塞模式下 SSL 套接字的行为与常规套接字略有不同。 当使用非阻塞模式时
，你需要注意下面这些事情:

   - 如果一个 I/O 操作会阻塞，大多数 *note SSLSocket: 3ea. 方法都将引发
     *note SSLWantWriteError: 760. 或 *note SSLWantReadError: 75f. 而非
     *note BlockingIOError: 99f.。 如果有必要在下层套接字上执行读取操作
     将引发 *note SSLWantReadError: 75f.，在下层套接字上执行写入操作则将
     引发 *note SSLWantWriteError: 760.。 请注意尝试 `写入' 到 SSL 套接
     字可能需要先从下层套接字 `读取'，而尝试从 SSL 套接字 `读取' 则可能
     需要先向下层套接字 `写入'。

     在 3.5 版更改: 在较早的 Python 版本中，‘SSLSocket.send()’ 方法会返
     回零值而非引发 *note SSLWantWriteError: 760. 或 *note
     SSLWantReadError: 75f.。

   - 调用 *note select(): 67c. 将告诉你可以从 OS 层级的套接字读取（或向
     其写入），但这并不意味着在上面的 SSL 层有足够的数据。 例如，可能只
     有部分 SSL 帧已经到达。 因此，你必须准备好处理 ‘SSLSocket.recv()’ 和
     ‘SSLSocket.send()’ 失败的情况，并在再次调用 *note select(): 67c. 之
     后重新尝试。

   - 相反地，由于 SSL 层具有自己的帧机制，一个 SSL 套接字可能仍有可读取
     的数据而 *note select(): 67c. 并不知道这一点。 因此，你应当先调用
     ‘SSLSocket.recv()’ 取走所有潜在的可用数据，然后只在必要时对 *note
     select(): 67c. 调用执行阻塞。

     (当然，类似的保留规则在使用其他原语例如 *note poll(): 2715.，或
     *note selectors: e7. 模块中的原语时也适用)

   - SSL 握手本身将是非阻塞的: *note SSLSocket.do_handshake(): 763. 方法
     必须不断重试直至其成功返回。 下面是一个使用 *note select(): 67c. 来
     等待套接字就绪的简短例子:

          while True:
              try:
                  sock.do_handshake()
                  break
              except ssl.SSLWantReadError:
                  select.select([sock], [], [])
              except ssl.SSLWantWriteError:
                  select.select([], [sock], [])

参见
....

*note asyncio: a. 模块支持 *note 非阻塞 SSL 套接字: 26bf. 并提供了更高层
级的 API。 它会使用 *note selectors: e7. 模块来轮询事件并处理 *note
SSLWantWriteError: 760, *note SSLWantReadError: 75f. 和 *note
BlockingIOError: 99f. 等异常。 它还会异步地执行 SSL 握手。


File: python.info,  Node: 内存 BIO 支持<2>,  Next: SSL 会话,  Prev: 关于非阻塞套接字的说明,  Up: ssl --- 套接字对象的TLS/SSL封装

5.18.3.20 内存 BIO 支持
.......................

3.5 新版功能.

自从 SSL 模块在 Python 2.6 起被引入之后，*note SSLSocket: 3ea. 类提供了
两个互相关联但彼此独立的功能分块:

   - SSL 协议处理

   - 网络 IO

网络 IO API 与 *note socket.socket: 67d. 所提供的功能一致，*note
SSLSocket: 3ea. 也是从那里继承而来的。 这允许 SSL 套接字被用作常规套接字
的替代，使得向现有应用程序添加 SSL 支持变得非常容易。

将 SSL 协议处理与网络 IO 结合使用通常都能运行良好，但在某些情况下则不能
。 此情况的一个例子是 async IO 框架，该框架要使用不同的 IO 多路复用模型
而非 (基于就绪状态的) "在文件描述器上执行选择/轮询" 模型，该模型是 *note
socket.socket: 67d. 和内部 OpenSSL 套接字 IO 例程正常运行的假设前提。 这
种情况在该模型效率不高的 Windows 平台上最为常见。 为此还提供了一个 *note
SSLSocket: 3ea. 的简化形式，称为 *note SSLObject: 3eb.。

 -- 类: ssl.SSLObject

     *note SSLSocket: 3ea. 的简化形式，表示一个不包含任何网络 IO 方法的
     SSL 协议实例。 这个类通常由想要通过内存缓冲区为 SSL 实现异步 IO 的
     框架作者来使用。

     这个类在低层级 SSL 对象上实现了一个接口，与 OpenSSL 所实现的类似。
     此对象会捕获 SSL 连接的状态但其本身不提供任何网络 IO。 IO 需要通过
     单独的 "BIO" 对象来执行，该对象是 OpenSSL 的 IO 抽象层。

     这个类没有公有构造器。 *note SSLObject: 3eb. 实例必须使用 *note
     wrap_bio(): 3ee. 方法来创建。 此方法将创建 *note SSLObject: 3eb. 实
     例并将其绑定到一个 BIO 对。 其中 `incoming' BIO 用来将数据从 Python
     传递到 SSL 协议实例，而 `outgoing' BIO 用来进行数据反向传递。

     可以使用以下方法：

        - *note context: 26fe.

        - *note server_side: 2701.

        - *note server_hostname: 3e8.

        - *note session: 2702.

        - *note session_reused: 2703.

        - *note read(): 764.

        - *note write(): 765.

        - *note getpeercert(): 8d9.

        - *note selected_alpn_protocol(): 75b.

        - *note selected_npn_protocol(): 26ff.

        - *note cipher(): 2604.

        - *note shared_ciphers(): 762.

        - *note compression(): a9d.

        - *note pending(): 2700.

        - *note do_handshake(): 763.

        - *note verify_client_post_handshake(): 226.

        - *note unwrap(): 26fd.

        - *note get_channel_binding(): a9c.

        - *note version(): 75e.

     与 *note SSLSocket: 3ea. 相比，此对象缺少下列特性:

        - 任何形式的网络 IO; ‘recv()’ 和 ‘send()’ 仅对下层的 *note
          MemoryBIO: 758. 缓冲区执行读取和写入。

        - 不存在 `do_handshake_on_connect' 机制。 你必须总是手动调用
          *note do_handshake(): 763. 来开始握手操作。

        - 不存在对 `suppress_ragged_eofs' 的处理。 所有违反协议的文件结
          束条件将通过 *note SSLEOFError: 26c1. 异常来报告。

        - 方法 *note unwrap(): 26fd. 的调用不返回任何东西，不会如 SSL 套
          接字那样返回下层的套接字。

        - `server_name_callback' 回调被传给 *note
          SSLContext.set_servername_callback(): 8d8. 时将获得一个 *note
          SSLObject: 3eb. 实例而非 *note SSLSocket: 3ea. 实例作为其第一
          个形参。

     有关 *note SSLObject: 3eb. 用法的一些说明:

        - 在 *note SSLObject: 3eb. 上的所有 IO 都是 *note 非阻塞的:
          26bf.。 这意味着例如 *note read(): 764. 在其需要比 incoming
          BIO 可用的更多数据时将会引发 *note SSLWantReadError: 75f.。

        - 不存在模块层级的 ‘wrap_bio()’ 调用，就像 *note wrap_socket():
          3ed. 那样。 *note SSLObject: 3eb. 总是通过 *note SSLContext:
          3ec. 来创建。

     在 3.7 版更改: *note SSLObject: 3eb. 的实例必须使用 *note
     wrap_bio(): 3ee. 来创建。 在较早的版本中，直接创建实例是可能的。 但
     这从未被记入文档或是被正式支持。

SSLObject 会使用内存缓冲区与外部世界通信。 *note MemoryBIO: 758. 类提供
了可被用于此目的的内存缓冲区。 它包装了一个 OpenSSL 内存 BIO (Basic IO)
对象:

 -- 类: ssl.MemoryBIO

     一个可被用来在 Python 和 SSL 协议实例之间传递数据的内存缓冲区。

      -- 属性: pending

          返回当前存在于内存缓冲区的字节数。

      -- 属性: eof

          一个表明内存 BIO 目前是否位于文件末尾的布尔值。

      -- 方法: read (n=-1)

          从内存缓冲区读取至多 `n' 个字节。 如果 `n' 未指定或为负值，则
          返回全部字节数据。

      -- 方法: write (buf)

          将字节数据从 `buf' 写入到内存 BIO。 `buf' 参数必须为支持缓冲区
          协议的对象。

          返回值为写入的字节数，它总是与 `buf' 的长度相等。

      -- 方法: write_eof ()

          将一个 EOF 标记写入到内存 BIO。 在此方法被调用以后，再调用
          *note write(): 271a. 将是非法的。 属性 *note eof: 2718. will 在
          缓冲区当前的所有数据都被读取之后将变为真值。


File: python.info,  Node: SSL 会话,  Next: 安全考量<2>,  Prev: 内存 BIO 支持<2>,  Up: ssl --- 套接字对象的TLS/SSL封装

5.18.3.21 SSL 会话
..................

3.6 新版功能.

 -- 类: ssl.SSLSession

     *note session: 2702. 所使用的会话对象。

      -- 属性: id

      -- 属性: time

      -- 属性: timeout

      -- 属性: ticket_lifetime_hint

      -- 属性: has_ticket


File: python.info,  Node: 安全考量<2>,  Next: TLS 1 3,  Prev: SSL 会话,  Up: ssl --- 套接字对象的TLS/SSL封装

5.18.3.22 安全考量
..................

* Menu:

* 最佳默认值::
* 手动设置::
* 多进程::


File: python.info,  Node: 最佳默认值,  Next: 手动设置,  Up: 安全考量<2>

5.18.3.23 最佳默认值
....................

针对 `客户端使用'，如果你对于安全策略没有任何特殊要求，则强烈推荐你使用
*note create_default_context(): 8c9. 函数来创建你的 SSL 上下文。 它将加
载系统的受信任 CA 证书，启用证书验证和主机名检查，并尝试合理地选择安全的
协议和密码设置。

例如，以下演示了你应当如何使用 *note smtplib.SMTP: a89. 类来创建指向一个
SMTP 服务器的受信任且安全的连接:

     >>> import ssl, smtplib
     >>> smtp = smtplib.SMTP("mail.python.org", port=587)
     >>> context = ssl.create_default_context()
     >>> smtp.starttls(context=context)
     (220, b'2.0.0 Ready to start TLS')

如果连接需要客户端证书，可使用 *note SSLContext.load_cert_chain(): a99.
来添加。

作为对比，如果你通过自行调用 *note SSLContext: 3ec. 构造器来创建 SSL 上
下文，它默认将不会启用证书验证和主机名检查。 如果你这样做，请阅读下面的
段落以达到良好的安全级别。


File: python.info,  Node: 手动设置,  Next: 多进程,  Prev: 最佳默认值,  Up: 安全考量<2>

5.18.3.24 手动设置
..................

* Menu:

* 验证证书::
* 协议版本::
* 密码选择::


File: python.info,  Node: 验证证书,  Next: 协议版本,  Up: 手动设置

5.18.3.25 验证证书
..................

当直接调用 *note SSLContext: 3ec. 构造器时，默认会使用 *note CERT_NONE:
26d0.。 由于它不会验证对等方的身份真实性，因此是不安全的，特别是在客户端
模式下，大多数时候你都希望能保证你所连接的服务器的身份真实性。 因此，当
处于客户端模式时，强烈推荐使用 *note CERT_REQUIRED: 26bb.。 但是，光这样
还不够；你还必须检查服务器证书，这可以通过调用 *note
SSLSocket.getpeercert(): 8d9. 来获取并匹配目标服务。 对于许多协议和应用
来说，服务可通过主机名来标识；在此情况下，可以使用 *note
match_hostname(): 3e4. 函数。 这种通用检测会在 *note
SSLContext.check_hostname: 26d3. 被启用时自动执行。

在 3.7 版更改: 主机名匹配现在是由 OpenSSL 来执行的。 Python 不会再使用
*note match_hostname(): 3e4.。

在服务器模式下，如果你想要使用 SSL 层来验证客户端（而不是使用更高层级的
验证机制），你也必须要指定 *note CERT_REQUIRED: 26bb. 并以类似方式检查客
户端证书。


File: python.info,  Node: 协议版本,  Next: 密码选择,  Prev: 验证证书,  Up: 手动设置

5.18.3.26 协议版本
..................

SSL 版本 2 和 3 被认为是不安全的因而使用它们会有风险。 如果你想要客户端
和服务器之间有最大的兼容性，推荐使用 *note PROTOCOL_TLS_CLIENT: 26d1. 或
*note PROTOCOL_TLS_SERVER: 26d7. 作为协议版本。 SSLv2 和 SSLv3 默认会被
禁用。

     >>> client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
     >>> client_context.options |= ssl.OP_NO_TLSv1
     >>> client_context.options |= ssl.OP_NO_TLSv1_1

前面创建的 SSL 上下文将只允许 TLSv1.2 及更新版本（如果你的系统支持）的服
务器连接。 *note PROTOCOL_TLS_CLIENT: 26d1. 默认会使用证书验证和主机名检
查。 你必须将证书加载到上下文中。


File: python.info,  Node: 密码选择,  Prev: 协议版本,  Up: 手动设置

5.18.3.27 密码选择
..................

如果你有更高级的安全要求，也可以通过 *note SSLContext.set_ciphers():
26ce. 方法在协商 SSL 会话时对所启用的加密进行微调。 从 Python 3.2.3 开始
，ssl 默认会禁用某些较弱的加密，但你还可能希望进一步限制加密选项。 请确
保仔细阅读 OpenSSL 文档中有关 加密列表格式(1) 的部分。 如果你想要检查给
定的加密列表启用了哪些加密，可以使用 *note SSLContext.get_ciphers():
595. 或所在系统的 ‘openssl ciphers’ 命令。

   ---------- Footnotes ----------

   (1) 
https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT


File: python.info,  Node: 多进程,  Prev: 手动设置,  Up: 安全考量<2>

5.18.3.28 多进程
................

如果使用此模块作为多进程应用的一部分（例如使用 *note multiprocessing:
b8. 或 *note concurrent.futures: 22. 模块），请注意 OpenSSL 的内部随机数
字生成器并不能正确处理分支进程。 应用程序必须修改父进程的 PRNG 状态，如
果它们要使用任何包含 *note os.fork(): 969. 的 SSL 特性的话。 任何对
*note RAND_add(): 26c7, *note RAND_bytes(): a97. 或 *note
RAND_pseudo_bytes(): a98. 都可以 。


File: python.info,  Node: TLS 1 3,  Next: LibreSSL 支持,  Prev: 安全考量<2>,  Up: ssl --- 套接字对象的TLS/SSL封装

5.18.3.29 TLS 1.3
.................

3.7 新版功能.

Python 通过 OpenSSL 1.1.1 提供了临时性和实验性的 TLS 1.3 支持。 这个新协
议的行为与之前版本的 TLS/SSL 略有不同。 某些新的 TLS 1.3 特性暂时还不可
用。

   - TLS 1.3 使用一组不同的加密套件集。 默认情况下所有 AES-GCM 和
     ChaCha20 加密套件都会被启用。 *note SSLContext.set_ciphers(): 26ce.
     方法还不能启用或禁用任何 TLS 1.3 加密，但 *note
     SSLContext.get_ciphers(): 595. 会返回它们。

   - 会话凭据不再会作为初始握手的组成部分被发送而是以不同的方式来处理。
     *note SSLSocket.session: 2702. 和 *note SSLSession: 594. 与 TLS 1.3
     不兼容。

   - 客户端证书在初始握手期间也不会再被验证。 服务器可以在任何时候请求证
     书。 客户端会在它们从服务器发送或接收应用数据时处理证书请求。

   - 早期数据、延迟的 TLS 客户端证书请求、签名算法配置和密钥重生成等 TLS
     1.3 特性尚未被支持。


File: python.info,  Node: LibreSSL 支持,  Prev: TLS 1 3,  Up: ssl --- 套接字对象的TLS/SSL封装

5.18.3.30 LibreSSL 支持
.......................

LibreSSL 是 OpenSSL 1.0.1 的一个分支。 ssl 模块包含对 LibreSSL 的有限支
持。 当 ssl 模块使用 LibreSSL 进行编译时某些特性将不可用。

   * LibreSSL >= 2.6.1 不再支持 NPN。 *note
     SSLContext.set_npn_protocols(): a9f. 和 *note
     SSLSocket.selected_npn_protocol(): 26ff. 方法将不可用。

   * *note SSLContext.set_default_verify_paths(): 8cb. 会忽略环境变量
     ‘SSL_CERT_FILE’ 和 ‘SSL_CERT_PATH’，虽然 *note
     get_default_verify_paths(): 8ca. 仍然支持它们。

参见
....

Class *note socket.socket: 67d.

     下层 *note socket: f0. 类的文档

SSL/TLS 高强度加密：概述(1)

     Apache HTTP Server文档介绍

RFC 1422: 因特网电子邮件的隐私加强：第二部分：基于证书的密钥管理(2)

     Steve Kent

RFC 4086: 确保安全的随机性要求(3)

     Donald E., Jeffrey I. Schiller

RFC 5280: 互联网 X.509 公钥基础架构证书和证书吊销列表 (CRL) 配置文件(4)

     D. Cooper

RFC 5246: 传输层安全性 (TLS) 协议版本 1.2(5)

     T. Dierks et.  al.

RFC 6066: 传输层安全性 (TLS) 的扩展(6)

     D. Eastlake

IANA TLS: 传输层安全性 (TLS) 的参数(7)

     IANA

RFC 7525: 传输层安全性 (TLS) 和数据报传输层安全性 (DTLS) 的安全使用建议(8)

     IETF

Mozilla 的服务器端 TLS 建议(9)

     Mozilla

   ---------- Footnotes ----------

   (1) https://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html

   (2) https://tools.ietf.org/html/rfc1422.html

   (3) https://tools.ietf.org/html/rfc4086.html

   (4) https://tools.ietf.org/html/rfc5280.html

   (5) https://tools.ietf.org/html/rfc5246.html

   (6) https://tools.ietf.org/html/rfc6066.html

   (7) 
https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

   (8) https://tools.ietf.org/html/rfc7525.html

   (9) https://wiki.mozilla.org/Security/Server_Side_TLS


File: python.info,  Node: select --- 等待 I/O 完成,  Next: selectors --- 高级 I/O 复用库,  Prev: ssl --- 套接字对象的TLS/SSL封装,  Up: 网络和进程间通信

5.18.4 ‘select’ — 等待 I/O 完成
-------------------------------

__________________________________________________________________

该模块提供了对 ‘select()’ 和 ‘poll()’ 函数的访问，这些函数在大多数操作系
统中是可用的。在 Solaris 及其衍生版本上可用 ‘devpoll()’，在 Linux 2.5+ 上
可用 ‘epoll()’，在大多数 BSD 上可用 ‘kqueue()’。注意，在 Windows 上，本
模块仅适用于套接字；在其他操作系统上，本模块也适用于其他文件类型（特别地
，在 Unix 上也适用于管道）。本模块不能用于常规文件，不能检测出（自上次读
取文件后）文件是否有新数据写入。

     注解: *note selectors: e7. 模块是在 *note select: e6. 模块原型的基
     础上进行高级且高效的 I/O 复用。推荐用户改用 *note selectors: e7. 模
     块，除非用户希望对 OS 级的函数原型进行精确控制。

该模块定义以下内容：

 -- 例外: select.error

     一个被弃用的 *note OSError: 1d4. 的别名。

     在 3.3 版更改: 根据 PEP 3151(1)，这个类是 *note OSError: 1d4. 的别
     名。

 -- 函数: select.devpoll ()

     （仅支持 Solaris 及其衍生版本）返回一个 ‘/dev/poll’ 轮询对象，请参
     阅下方 *note /dev/poll 轮询对象: 272e. 获取 devpoll 对象所支持的方
     法。

     ‘devpoll()’ 对象与实例化时允许的文件描述符数量有关，如果在程序中降
     低了此数值，‘devpoll()’ 调用将失败。如果程序提高了此数值，
     ‘devpoll()’ 可能会返回一个不完整的活动文件描述符列表。

     新的文件描述符是 *note 不可继承的: 803.。

     3.3 新版功能.

     在 3.4 版更改: 新的文件描述符现在是不可继承的。

 -- 函数: select.epoll (sizehint=-1, flags=0)

     （仅支持 Linux 2.5.44 或更高版本）返回一个 edge poll 对象，该对象可
     作为 I/O 事件的边缘触发或水平触发接口。

     `sizehint' 指示 epoll 预计需要注册的事件数。它必须为正数，或为 ‘-1’
     以使用默认值。它仅在 ‘epoll_create1()’ 不可用的旧系统上会被用到，其
     他情况下它没有任何作用（尽管仍会检查其值）。

     `flags' 已经弃用且完全被忽略。但是，如果提供该值，则它必须是 ‘0’ 或
     ‘select.EPOLL_CLOEXEC’，否则会抛出 ‘OSError’ 异常。

     请参阅下方 *note 边缘触发和水平触发的轮询 (epoll) 对象: 272f. 获取
     epoll 对象所支持的方法。

     ‘epoll’ 对象支持上下文管理器：当在 *note with: 6f2. 语句中使用时，
     新建的文件描述符会在运行至语句块结束时自动关闭。

     新的文件描述符是 *note 不可继承的: 803.。

     在 3.3 版更改: 增加了 `flags' 参数。

     在 3.4 版更改: 增加了对 *note with: 6f2. 语句的支持。新的文件描述符
     现在是不可继承的。

     3.4 版后已移除: `flags' 参数。现在默认采用 ‘select.EPOLL_CLOEXEC’ 标
     志。使用 *note os.set_inheritable(): 805. 来让文件描述符可继承。

 -- 函数: select.poll ()

     （部分操作系统不支持）返回一个 poll 对象，该对象支持注册和注销文件
     描述符，支持对描述符进行轮询以获取 I/O 事件。请参阅下方 *note Poll
     对象: 2730. 获取 poll 对象所支持的方法。

 -- 函数: select.kqueue ()

     （仅支持 BSD）返回一个内核队列对象，请参阅下方 *note Kqueue 对象:
     2732. 获取 kqueue 对象所支持的方法。

     新的文件描述符是 *note 不可继承的: 803.。

     在 3.4 版更改: 新的文件描述符现在是不可继承的。

 -- 函数: select.kevent (ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD,
          fflags=0, data=0, udata=0)

     （仅支持 BSD）返回一个内核事件对象，请参阅下方 *note Kevent 对象:
     2734. 获取 kevent 对象所支持的方法。

 -- 函数: select.select (rlist, wlist, xlist[, timeout])

     这是一个明白直观的 Unix ‘select()’ 系统调用接口。 前三个参数是由‘可
     等待对象’组成的序列：可以是代表文件描述符的整数，或是带有名为 *note
     fileno(): 1f19. 的返回这样的整数的无形参方法的对象:

        * `rlist'：等待，直到可以开始读取

        * `wlist'：等待，直到可以开始写入

        * `xlist'：等待“异常情况”（请参阅当前系统的手册，以获取哪些情况
          称为异常情况）

     允许空的可迭代对象，但是否接受三个空的可迭代对象则取决于具体平台。
     （已知在 Unix 上可行但在 Windows 上不可行。） 可选的 `timeout' 参数
     以一个浮点数表示超时秒数。 当省略 `timeout' 参数时该函数将阻塞直到
     至少有一个文件描述符准备就绪。 超时值为零表示执行轮询且永不阻塞。

     返回值是三个列表，包含已就绪对象，返回的三个列表是前三个参数的子集
     。当超时时间已到且没有文件描述符就绪时，返回三个空列表。

     可迭代对象中可接受的对象类型有 Python *note 文件对象: b4a. (例如
     ‘sys.stdin’ 以及 *note open(): 4f8. 或 *note os.popen(): 2aa. 所返
     回的对象)，由 *note socket.socket(): 67d. 返回的套接字对象等。 你也
     可以自定义一个 `wrapper' 类，只要它具有适当的 *note fileno(): 1f19.
     方法（该方法要确实返回一个文件描述符，而不能只是一个随机整数）。

          注解: 
          Windows 上不接受文件对象，但接受套接字。在 Windows 上，底层的
          ‘select()’ 函数由 WinSock 库提供，且不处理不是源自 WinSock 的
          文件描述符。

     在 3.5 版更改: 现在，当本函数被信号中断时，重试超时将从头开始计时，
     不会抛出 *note InterruptedError: 662. 异常。除非信号处理程序抛出异
     常（相关原理请参阅 PEP 475(2)）。

 -- 属性: select.PIPE_BUF

     当一个管道已经被 *note select(): 67c.、*note poll(): 2715. 或本模块
     中的某个接口报告为可写入时，可以在不阻塞该管道的情况下写入的最小字
     节数。它不适用于套接字等其他类型的文件类对象。

     POSIX 上须保证该值不小于 512。

     *note 可用性: 136f.: Unix

     3.2 新版功能.

* Menu:

* /dev/poll 轮询对象::
* 边缘触发和水平触发的轮询 (epoll) 对象: 边缘触发和水平触发的轮询 epoll 对象.
* Poll 对象::
* Kqueue 对象::
* Kevent 对象::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3151

   (2) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: /dev/poll 轮询对象,  Next: 边缘触发和水平触发的轮询 epoll 对象,  Up: select --- 等待 I/O 完成

5.18.4.1 ‘/dev/poll’ 轮询对象
.............................

Solaris 及其衍生版本具备 ‘/dev/poll’。‘select()’ 复杂度为 O（最高文件描
述符），‘poll()’ 为 O（文件描述符数量），而 ‘/dev/poll’ 为 O（活动的文件
描述符）。

‘/dev/poll’ 的行为与标准 ‘poll()’ 对象十分类似。

 -- 方法: devpoll.close ()

     关闭轮询对象的文件描述符。

     3.4 新版功能.

 -- 属性: devpoll.closed

     如果轮询对象已关闭，则返回 ‘True’。

     3.4 新版功能.

 -- 方法: devpoll.fileno ()

     返回轮询对象的文件描述符对应的数字。

     3.4 新版功能.

 -- 方法: devpoll.register (fd[, eventmask])

     在轮询对象中注册文件描述符。这样，将来调用 *note poll(): 2715. 方法
     时将检查文件描述符是否有未处理的 I/O 事件。`fd' 可以是整数，也可以
     是带有 *note fileno(): 1f19. 方法的对象（该方法返回一个整数）。文件
     对象已经实现了 ‘fileno()’，因此它们也可以用作参数。

     `eventmask' 是可选的位掩码，用于指定要检查的事件类型。这些常量与
     ‘poll()’ 对象所用的相同。本参数的默认值是常量 ‘POLLIN’、‘POLLPRI’ 和
     ‘POLLOUT’ 的组合。

          警告: 注册已注册过的文件描述符不会报错，但是结果是不确定的。正
          确的操作是先注销或直接修改它。与 ‘poll()’ 相比，这是一个重要的
          区别。

 -- 方法: devpoll.modify (fd[, eventmask])

     此方法先执行 *note unregister(): 2738. 后执行 *note register():
     2736.。直接执行此操作效率（稍微）高一些。

 -- 方法: devpoll.unregister (fd)

     删除轮询对象正在跟踪的某个文件描述符。与 *note register(): 2736. 方
     法类似，`fd' 可以是整数，也可以是带有 *note fileno(): 1f19. 方法的
     对象（该方法返回一个整数）。

     尝试删除从未注册过的文件描述符将被安全地忽略。

 -- 方法: devpoll.poll ([timeout])

     轮询已注册的文件描述符的集合，并返回一个列表，列表可能为空，也可能
     有多个 ‘(fd, event)’ 二元组，其中包含了要报告事件或错误的描述符。
     `fd' 是文件描述符，`event' 是一个位掩码，表示该描述符所报告的事件 —
     ‘POLLIN’ 表示可以读取，‘POLLOUT’ 表示该描述符可以写入，依此类推。空
     列表表示调用超时，没有任何文件描述符报告事件。如果指定了 `timeout'，
     它将指定系统等待事件时，等待多长时间后返回（以毫秒为单位）。如果
     `timeout' 为空，-1 或 *note None: 158.，则本调用将阻塞，直到轮询对
     象发生事件为止。

     在 3.5 版更改: 现在，当本函数被信号中断时，重试超时将从头开始计时，
     不会抛出 *note InterruptedError: 662. 异常。除非信号处理程序抛出异
     常（相关原理请参阅 PEP 475(1)）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: 边缘触发和水平触发的轮询 epoll 对象,  Next: Poll 对象,  Prev: /dev/poll 轮询对象,  Up: select --- 等待 I/O 完成

5.18.4.2 边缘触发和水平触发的轮询 (epoll) 对象
..............................................

     ‘https://linux.die.net/man/4/epoll’

     `eventmask'

     常数                          含义
                                   
     ----------------------------------------------------------------------------------
                                   
     ‘EPOLLIN’                     可读
                                   
                                   
     ‘EPOLLOUT’                    可写
                                   
                                   
     ‘EPOLLPRI’                    紧急数据读取
                                   
                                   
     ‘EPOLLERR’                    在关联的文件描述符上有错误情况发生
                                   
                                   
     ‘EPOLLHUP’                    关联的文件描述符已挂起
                                   
                                   
     ‘EPOLLET’                     设置触发方式为边缘触发，默认为水平触发
                                   
                                   
     ‘EPOLLONESHOT’                设置 one-shot 模式。触发一次事件后，该描述符会在
                                   轮询对象内部被禁用。
                                   
                                   
     ‘EPOLLEXCLUSIVE’              当已关联的描述符发生事件时，仅唤醒一个 epoll 对象
                                   。默认（如果未设置此标志）是唤醒所有轮询该描述符
                                   的 epoll 对象。
                                   
                                   
     ‘EPOLLRDHUP’                  流套接字的对侧关闭了连接或关闭了写入到一半的连接
                                   。
                                   
                                   
     ‘EPOLLRDNORM’                 等同于 ‘EPOLLIN’
                                   
                                   
     ‘EPOLLRDBAND’                 可以读取优先数据带。
                                   
                                   
     ‘EPOLLWRNORM’                 等同于 ‘EPOLLOUT’
                                   
                                   
     ‘EPOLLWRBAND’                 可以写入优先级数据。
                                   
                                   
     ‘EPOLLMSG’                    忽略
                                   

     3.6 新版功能: 增加了 ‘EPOLLEXCLUSIVE’。仅支持 Linux Kernel 4.5 或更
     高版本。

 -- 方法: epoll.close ()

     关闭用于控制 epoll 对象的文件描述符。

 -- 属性: epoll.closed

     如果 epoll 对象已关闭，则返回 ‘True’。

 -- 方法: epoll.fileno ()

     返回文件描述符对应的数字，该描述符用于控制 epoll 对象。

 -- 方法: epoll.fromfd (fd)

     根据给定的文件描述符创建 epoll 对象。

 -- 方法: epoll.register (fd[, eventmask])

     在 epoll 对象中注册一个文件描述符。

 -- 方法: epoll.modify (fd, eventmask)

     修改一个已注册的文件描述符。

 -- 方法: epoll.unregister (fd)

     从 epoll 对象中删除一个已注册的文件描述符。

 -- 方法: epoll.poll (timeout=None, maxevents=-1)

     等待事件发生，timeout 是浮点数，单位为秒。

     在 3.5 版更改: 现在，当本函数被信号中断时，重试超时将从头开始计时，
     不会抛出 *note InterruptedError: 662. 异常。除非信号处理程序抛出异
     常（相关原理请参阅 PEP 475(1)）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: Poll 对象,  Next: Kqueue 对象,  Prev: 边缘触发和水平触发的轮询 epoll 对象,  Up: select --- 等待 I/O 完成

5.18.4.3 Poll 对象
..................

大多数 Unix 系统支持 ‘poll()’ 系统调用，为服务器提供了更好的可伸缩性，使
服务器可以同时服务于大量客户端。‘poll()’ 的伸缩性更好，因为该调用内部仅
列出所关注的文件描述符，而 ‘select()’ 会构造一个 bitmap，在其中将所关注
的描述符所对应的 bit 打开，然后重新遍历整个 bitmap。因此 ‘select()’ 复杂
度是 O（最高文件描述符），而 ‘poll()’ 是 O（文件描述符数量）。

 -- 方法: poll.register (fd[, eventmask])

     在轮询对象中注册文件描述符。这样，将来调用 *note poll(): 2715. 方法
     时将检查文件描述符是否有未处理的 I/O 事件。`fd' 可以是整数，也可以
     是带有 *note fileno(): 1f19. 方法的对象（该方法返回一个整数）。文件
     对象已经实现了 ‘fileno()’，因此它们也可以用作参数。

     `eventmask' 是可选的位掩码，用于指定要检查的事件类型，它可以是常量
     ‘POLLIN’、‘POLLPRI’ 和 ‘POLLOUT’ 的组合，如下表所述。如果未指定本参
     数，默认将会检查所有 3 种类型的事件。

     常数                    含义
                             
     -----------------------------------------------------------------------
                             
     ‘POLLIN’                有要读取的数据
                             
                             
     ‘POLLPRI’               有紧急数据需要读取
                             
                             
     ‘POLLOUT’               准备输出：写不会阻塞
                             
                             
     ‘POLLERR’               某种错误条件
                             
                             
     ‘POLLHUP’               挂起
                             
                             
     ‘POLLRDHUP’             流套接字的对侧关闭了连接，或关闭了写入到一半
                             的连接
                             
                             
     ‘POLLNVAL’              无效的请求：描述符未打开
                             

     注册已注册过的文件描述符不会报错，且等同于只注册一次该描述符。

 -- 方法: poll.modify (fd, eventmask)

     修改一个已注册的文件描述符，等同于 ‘register(fd, eventmask)’。尝试
     修改未注册的文件描述符会抛出 *note OSError: 1d4. 异常，错误码为
     ‘ENOENT’。

 -- 方法: poll.unregister (fd)

     删除轮询对象正在跟踪的某个文件描述符。与 *note register(): 2741. 方
     法类似，`fd' 可以是整数，也可以是带有 *note fileno(): 1f19. 方法的
     对象（该方法返回一个整数）。

     尝试删除从未注册过的文件描述符会抛出 *note KeyError: 2c8. 异常。

 -- 方法: poll.poll ([timeout])

     轮询已注册的文件描述符的集合，并返回一个列表，列表可能为空，也可能
     有多个 ‘(fd, event)’ 二元组，其中包含了要报告事件或错误的描述符。
     `fd' 是文件描述符，`event' 是一个位掩码，表示该描述符所报告的事件 —
     ‘POLLIN’ 表示可以读取，‘POLLOUT’ 表示该描述符可以写入，依此类推。空
     列表表示调用超时，没有任何文件描述符报告事件。如果指定了 `timeout'，
     它将指定系统等待事件时，等待多长时间后返回（以毫秒为单位）。如果
     `timeout' 为空、负数 或 *note None: 158.，则本调用将阻塞，直到轮询
     对象发生事件为止。

     在 3.5 版更改: 现在，当本函数被信号中断时，重试超时将从头开始计时，
     不会抛出 *note InterruptedError: 662. 异常。除非信号处理程序抛出异
     常（相关原理请参阅 PEP 475(1)）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: Kqueue 对象,  Next: Kevent 对象,  Prev: Poll 对象,  Up: select --- 等待 I/O 完成

5.18.4.4 Kqueue 对象
....................

 -- 方法: kqueue.close ()

     关闭用于控制 kqueue 对象的文件描述符。

 -- 属性: kqueue.closed

     如果 kqueue 对象已关闭，则返回 ‘True’。

 -- 方法: kqueue.fileno ()

     返回文件描述符对应的数字，该描述符用于控制 epoll 对象。

 -- 方法: kqueue.fromfd (fd)

     根据给定的文件描述符创建 kqueue 对象。

 -- 方法: kqueue.control (changelist, max_events[, timeout]) ->
          eventlist

     Kevent 的低级接口

        - changelist 必须是一个可迭代对象，迭代出 kevent 对象，否则置为
          ‘None’。

        - max_events 必须是 0 或一个正整数。

        - timeout 单位为秒（一般为浮点数），默认为 ‘None’，即永不超时。

     在 3.5 版更改: 现在，当本函数被信号中断时，重试超时将从头开始计时，
     不会抛出 *note InterruptedError: 662. 异常。除非信号处理程序抛出异
     常（相关原理请参阅 PEP 475(1)）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: Kevent 对象,  Prev: Kqueue 对象,  Up: select --- 等待 I/O 完成

5.18.4.5 Kevent 对象
....................

‘https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2’

 -- 属性: kevent.ident

     用于区分事件的标识值。其解释取决于筛选器，但该值通常是文件描述符。
     在构造函数中，该标识值可以是整数或带有 *note fileno(): 1f19. 方法的
     对象。kevent 在内部存储整数。

 -- 属性: kevent.filter

     内核筛选器的名称。

     常数                            含义
                                     
     ----------------------------------------------------------------------------------
                                     
     ‘KQ_FILTER_READ’                获取描述符，并在有数据可读时返回
                                     
                                     
     ‘KQ_FILTER_WRITE’               获取描述符，并在有数据可写时返回
                                     
                                     
     ‘KQ_FILTER_AIO’                 AIO 请求
                                     
                                     
     ‘KQ_FILTER_VNODE’               当在 `fflag' 中监视的一个或多个请求事件发生时返
                                     回
                                     
                                     
     ‘KQ_FILTER_PROC’                监视进程ID上的事件
                                     
                                     
     ‘KQ_FILTER_NETDEV’              观察网络设备上的事件[在Mac OS X上不可用]
                                     
                                     
     ‘KQ_FILTER_SIGNAL’              每当监视的信号传递到进程时返回
                                     
                                     
     ‘KQ_FILTER_TIMER’               建立一个任意的计时器
                                     

 -- 属性: kevent.flags

     筛选器操作。

     常数                            含义
                                     
     ----------------------------------------------------------------------------------
                                     
     ‘KQ_EV_ADD’                     添加或修改事件
                                     
                                     
     ‘KQ_EV_DELETE’                  从队列中删除事件
                                     
                                     
     ‘KQ_EV_ENABLE’                  Permitscontrol() 返回事件
                                     
                                     
     ‘KQ_EV_DISABLE’                 禁用事件
                                     
                                     
     ‘KQ_EV_ONESHOT’                 在第一次发生后删除事件
                                     
                                     
     ‘KQ_EV_CLEAR’                   检索事件后重置状态
                                     
                                     
     ‘KQ_EV_SYSFLAGS’                内部事件
                                     
                                     
     ‘KQ_EV_FLAG1’                   内部事件
                                     
                                     
     ‘KQ_EV_EOF’                     筛选特定EOF条件
                                     
                                     
     ‘KQ_EV_ERROR’                   请参阅返回值
                                     

 -- 属性: kevent.fflags

     筛选特定标志。

     ‘KQ_FILTER_READ’ 和 ‘KQ_FILTER_WRITE’ 筛选标志：

     常数                             含义
                                      
     ----------------------------------------------------------------------------------
                                      
     ‘KQ_NOTE_LOWAT’                  套接字缓冲区的低水线
                                      

     ‘KQ_FILTER_VNODE’ 筛选标志：

     常数                             含义
                                      
     ----------------------------------------------------------------------------------
                                      
     ‘KQ_NOTE_DELETE’                 已调用 `unlink()'
                                      
                                      
     ‘KQ_NOTE_WRITE’                  发生写入
                                      
                                      
     ‘KQ_NOTE_EXTEND’                 文件已扩展
                                      
                                      
     ‘KQ_NOTE_ATTRIB’                 属性已更改
                                      
                                      
     ‘KQ_NOTE_LINK’                   链接计数已更改
                                      
                                      
     ‘KQ_NOTE_RENAME’                 文件已重命名
                                      
                                      
     ‘KQ_NOTE_REVOKE’                 对文件的访问权限已被撤销
                                      

     ‘KQ_FILTER_PROC’ filter flags:

     常数                             含义
                                      
     ----------------------------------------------------------------------------------
                                      
     ‘KQ_NOTE_EXIT’                   进程已退出
                                      
                                      
     ‘KQ_NOTE_FORK’                   该进程调用了 `fork()'
                                      
                                      
     ‘KQ_NOTE_EXEC’                   进程已执行新进程
                                      
                                      
     ‘KQ_NOTE_PCTRLMASK’              内部筛选器标志
                                      
                                      
     ‘KQ_NOTE_PDATAMASK’              内部筛选器标志
                                      
                                      
     ‘KQ_NOTE_TRACK’                  跨 `fork()' 执行进程
                                      
                                      
     ‘KQ_NOTE_CHILD’                  在 `NOTE_TRACK' 的子进程上返回
                                      
                                      
     ‘KQ_NOTE_TRACKERR’               无法附加到子对象
                                      

     ‘KQ_FILTER_NETDEV’ 筛选器标志（在 Mac OS X 上不可用）：

     常数                             含义
                                      
     ----------------------------------------------------------------------------------
                                      
     ‘KQ_NOTE_LINKUP’                 链接已建立
                                      
                                      
     ‘KQ_NOTE_LINKDOWN’               链接已断开
                                      
                                      
     ‘KQ_NOTE_LINKINV’                链接状态无效
                                      

 -- 属性: kevent.data

     筛选特定数据。

 -- 属性: kevent.udata

     用户自定义值。


File: python.info,  Node: selectors --- 高级 I/O 复用库,  Next: asyncore --- 异步socket处理器,  Prev: select --- 等待 I/O 完成,  Up: 网络和进程间通信

5.18.5 ‘selectors’ — 高级 I/O 复用库
------------------------------------

3.4 新版功能.

`源码:' Lib/selectors.py(1)

__________________________________________________________________

* Menu:

* 概述: 概述<10>.
* 类: 类<3>.
* 例子: 例子<17>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/selectors.py


File: python.info,  Node: 概述<10>,  Next: 类<3>,  Up: selectors --- 高级 I/O 复用库

5.18.5.1 概述
.............

此模块允许高层级且高效率的 I/O 复用，它建立在 *note select: e6. 模块原型
的基础之上。 推荐用户改用此模块，除非他们希望对所使用的 OS 层级原型进行
精确控制。

它定义了一个 *note BaseSelector: 2753. 抽象基类，以及多个实际的实现
(*note KqueueSelector: 2656, *note EpollSelector: 453...)，它们可被用于
在多个文件对象上等待 I/O 就绪通知。 在下文中，"文件对象" 是指任何具有
‘fileno()’ 方法的对象，或是一个原始文件描述器。 参见 *note file object:
b4a.。

*note DefaultSelector: 2754. 是一个指向当前平台上可用的最高效实现的别名
：这应为大多数用户的默认选择。

     注解: 受支持的文件对象类型取决于具体平台：在 Windows 上，支持套接字
     但不支持管道，而在 Unix 上两者均受支持（某些其他类型也可能受支持，
     例如 fifo 或特殊文件设备等）。

参见
....

*note select: e6.

     低层级的 I/O 多路复用模块。


File: python.info,  Node: 类<3>,  Next: 例子<17>,  Prev: 概述<10>,  Up: selectors --- 高级 I/O 复用库

5.18.5.2 类
...........

类的层次结构:

     BaseSelector
     +-- SelectSelector
     +-- PollSelector
     +-- EpollSelector
     +-- DevpollSelector
     +-- KqueueSelector

下文中，`events' 一个位掩码，指明哪些 I/O 事件要在给定的文件对象上执行等
待。 它可以是以下模块级常量的组合:

     常数                        含义
                                 
     --------------------------------------------------------------------------------
                                 
     ‘EVENT_READ’                可读
                                 
                                 
     ‘EVENT_WRITE’               可写
                                 

 -- 类: selectors.SelectorKey

     *note SelectorKey: 2756. 是一个 *note namedtuple: 1b7.，用来将文件
     对象关联到其下层的文件描述器、选定事件掩码和附加数据等。 它会被某些
     *note BaseSelector: 2753. 方法返回。

      -- 属性: fileobj

          已注册的文件对象。

      -- 属性: fd

          下层的文件描述器。

      -- 属性: events

          必须在此文件对象上被等待的事件。

      -- 属性: data

          可选的关联到此文件对象的不透明数据：例如，这可被用来存储各个客
          户端的会话 ID。

 -- 类: selectors.BaseSelector

     一个 *note BaseSelector: 2753.，用来在多个文件对象上等待 I/O 事件就
     绪。 它支持文件流注册、注销，以及在这些流上等待 I/O 事件的方法。 它
     是一个抽象基类，因此不能被实例化。 请改用 *note DefaultSelector:
     2754.，或者 *note SelectSelector: 2653, *note KqueueSelector: 2656.
     等。 如果你想要指明使用某个实现，并且你的平台支持它的话。 *note
     BaseSelector: 2753. 及其具体实现支持 *note context manager: 571. 协
     议。

      -- 方法: abstractmethod register (fileobj, events, data=None)

          注册一个用于选择的文件对象，在其上监视 I/O 事件。

          `fileobj' 是要监视的文件对象。 它可以是整数形式的文件描述符或
          者具有 ‘fileno()’ 方法的对象。 `events' 是要监视的事件的位掩码
          。 `data' 是一个不透明对象。

          这将返回一个新的 *note SelectorKey: 2756. 实例，或在出现无效事
          件掩码或文件描述符时引发 *note ValueError: 1fc.，或在文件对象
          已被注册时引发 *note KeyError: 2c8.。

      -- 方法: abstractmethod unregister (fileobj)

          注销对一个文件对象的选择，移除对它的监视。 在文件对象被关闭之
          前应当先将其注销。

          `fileobj' 必须是之前已注册的文件对象。

          这将返回已关联的 *note SelectorKey: 2756. 实例，或者如果
          `fileobj' 未注册则会引发 *note KeyError: 2c8.。 It will raise
          *note ValueError: 1fc. 如果 `fileobj' 无效（例如它没有
          ‘fileno()’ 方法或其 ‘fileno()’ 方法返回无效值）。

      -- 方法: modify (fileobj, events, data=None)

          更改已注册文件对象所监视的事件或所附带的数据。

          这等价于 ‘BaseSelector.unregister(fileobj)()’ 加
          ‘BaseSelector.register(fileobj, events, data)()’，区别在于它可
          以被更高效地实现。

          这将返回一个新的 *note SelectorKey: 2756. 实例，或在出现无效事
          件掩码或文件描述符时引发 *note ValueError: 1fc.，或在文件对象
          未被注册时引发 *note KeyError: 2c8.。

      -- 方法: abstractmethod select (timeout=None)

          等待直到有已注册的文件对象就绪，或是超过时限。

          如果 ‘timeout > 0’，这指定以秒数表示的最大等待时间。 如果
          ‘timeout <= 0’，调用将不会阻塞，并将报告当前就绪的文件对象。 如
          果 `timeout' 为 ‘None’，调用将阻塞直到某个被监视的文件对象就绪
          。

          这将返回由 ‘(key, events)’ 元组构成的列表，每项各表示一个就绪
          的文件对象。

          `key' 是对应于就绪文件对象的 *note SelectorKey: 2756. 实例。
          `events' 是在此文件对象上等待的事件位掩码。

               注解: 如果当前进程收到一个信号，此方法可在任何文件对象就
               绪之前或超出时限时返回：在此情况下，将返回一个空列表。

          在 3.5 版更改: 现在当被某个信号中断时，如果信号处理程序没有引
          发异常，选择器会用重新计算的超时值进行重试（请查看 PEP 475(1)
          其理由），而不是在超时之前返回空的事件列表。

      -- 方法: close ()

          关闭选择器。

          必须调用这个方法以确保下层资源会被释放。 选择器被关闭后将不可
          再使用。

      -- 方法: get_key (fileobj)

          返回关联到某个已注册文件对象的键。

          此方法将返回关联到文件对象的 *note SelectorKey: 2756. 实例，或
          在文件对象未注册时引发 *note KeyError: 2c8.。

      -- 方法: abstractmethod get_map ()

          返回从文件对象到选择器键的映射。

          这将返回一个将已注册文件对象映射到与其相关联的 *note
          SelectorKey: 2756. 实例的 *note Mapping: 1954. 实例。

 -- 类: selectors.DefaultSelector

     默认的选择器类，使用当前平台上可用的最高效实现。 这应为大多数用户的
     默认选择。

 -- 类: selectors.SelectSelector

     基于 *note select.select(): 67c. 的选择器。

 -- 类: selectors.PollSelector

     基于 *note select.poll(): 2715. 的选择器。

 -- 类: selectors.EpollSelector

     基于 *note select.epoll(): 8b2. 的选择器。

      -- 方法: fileno ()

          此方法将返回由下层 *note select.epoll(): 8b2. 对象所使用的文件
          描述符。

 -- 类: selectors.DevpollSelector

     基于 *note select.devpoll(): 8b4. 的选择器。

      -- 方法: fileno ()

          此方法将返回由下层 *note select.devpoll(): 8b4. 对象所使用的文
          件描述符。

     3.5 新版功能.

 -- 类: selectors.KqueueSelector

     基于 *note select.kqueue(): 2731. 的选择器。

      -- 方法: fileno ()

          此方法将返回由下层 *note select.kqueue(): 2731. 对象所使用的文
          件描述符。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: 例子<17>,  Prev: 类<3>,  Up: selectors --- 高级 I/O 复用库

5.18.5.3 例子
.............

下面是一个简单的回显服务器实现:

     import selectors
     import socket

     sel = selectors.DefaultSelector()

     def accept(sock, mask):
         conn, addr = sock.accept()  # Should be ready
         print('accepted', conn, 'from', addr)
         conn.setblocking(False)
         sel.register(conn, selectors.EVENT_READ, read)

     def read(conn, mask):
         data = conn.recv(1000)  # Should be ready
         if data:
             print('echoing', repr(data), 'to', conn)
             conn.send(data)  # Hope it won't block
         else:
             print('closing', conn)
             sel.unregister(conn)
             conn.close()

     sock = socket.socket()
     sock.bind(('localhost', 1234))
     sock.listen(100)
     sock.setblocking(False)
     sel.register(sock, selectors.EVENT_READ, accept)

     while True:
         events = sel.select()
         for key, mask in events:
             callback = key.data
             callback(key.fileobj, mask)


File: python.info,  Node: asyncore --- 异步socket处理器,  Next: asynchat --- 异步 socket 指令/响应 处理器,  Prev: selectors --- 高级 I/O 复用库,  Up: 网络和进程间通信

5.18.6 ‘asyncore’ — 异步socket处理器
------------------------------------

`源码：' Lib/asyncore.py(1)

3.6 版后已移除: 请使用 *note asyncio: a. 替代。

__________________________________________________________________

     注解: 该模块仅为提供向后兼容。我们推荐在新代码中使用 *note asyncio:
     a. 。

该模块提供用于编写异步套接字服务客户端与服务端的基础构件。

只有两种方法让单个处理器上的程序“同一时间完成不止一件事”。 多线程编程是
最简单和最流行的方法，但是还有另一种非常不同的技术，它可以让你拥有多线程
的几乎所有优点，而无需实际使用多线程。 它仅仅在你的程序主要受 I/O 限制时
有用，那么。 如果你的程序受处理器限制，那么先发制人的预定线程可能就是你
真正需要的。 但是，网络服务器很少受处理器限制。

如果你的操作系统在其 I/O 库中支持 ‘select()’ 系统调用（几乎所有操作系统
），那么你可以使用它来同时处理多个通信通道；在 I/O 正在“后台”时进行其他
工作。 虽然这种策略看起来很奇怪和复杂，特别是起初，它在很多方面比多线程
编程更容易理解和控制。 *note asyncore: b. 模块为您解决了许多难题，使得构
建复杂的高性能网络服务器和客户端的任务变得轻而易举。 对于“会话”应用程序
和协议，伴侣 *note asynchat: 9. 模块是非常宝贵的。

这两个模块背后的基本思想是创建一个或多个网络 `通道' ，类的实例 *note
asyncore.dispatcher: bcb. 和 *note asynchat.async_chat: 8be. 。 创建通道
会将它们添加到全局映射中，如果你不为它提供自己的 `映射' ，则由 *note
loop(): 2767. 函数使用。

一旦创建了初始通道，调用 *note loop(): 2767. 函数将激活通道服务，该服务
将一直持续到最后一个通道（包括在异步服务期间已添加到映射中的任何通道）关
闭。

 -- 函数: asyncore.loop ([timeout[, use_poll[, map[, count]]]])

     进入一个轮询循环，其在循环计数超出或所有打开的通道关闭后终止。 所有
     参数都是可选的。 `count' 形参默认为 ‘None’ ，导致循环仅在所有通道关
     闭时终止。 `timeout' 形参为适当的 *note select(): 67c. 或 *note
     poll(): 2715. 调用设置超时参数，以秒为单位; 默认值为30秒。
     `use_poll' 形参，如果为 True ，则表示 *note poll(): 2715. 应优先使
     用 *note select(): 67c. (默认为‘‘False‘‘)。

     `map' 形参是一个条目为所监视通道的字典。 当通道关闭时它们会被从映射
     中删除。 如果省略 `map'，则会使用一个全局映射。 通道 (*note
     asyncore.dispatcher: bcb, *note asynchat.async_chat: 8be. 及其子类
     的实例) 可以在映射中任意混合。

 -- 类: asyncore.dispatcher

     *note dispatcher: bcb. 类是对低层级套接字对象的轻量包装器。 要让它
     更有用处，可以从异步循环调用一些事件处理方法。 在其他方面，它可以被
     当作是普通的非阻塞型套接字对象。

     在特定时间或特定连接状态下触发的低层级事件可通知异步循环发生了特定
     的高层级事件。 例如，如果我们请求了一个套接字以连接到另一台主机，我
     们会在套接字首次变得可写时得知连接已建立（在此刻你将知道可以向其写
     入并预期能够成功）。 包含的高层级事件有:

     Event                      描述
                                
     ------------------------------------------------------------------------
                                
     ‘handle_connect()’         由首个读取或写入事件所包含
                                
                                
     ‘handle_close()’           由不带可用数据的读取事件引起
                                
                                
     ‘handle_accepted()’        由在监听套接字上的读取事件引起
                                

     在异步处理过程中，每个已映射通道的 *note readable(): 2768. 和 *note
     writable(): 2769. 方法会被用来确定是否要将通道的套接字添加到已执行
     ‘select()’ 或 ‘poll()’ 用于读取和写入事件的通道列表中。

     因此，通道事件的集合要大于基本套接字事件。 可以在你的子类中被重载的
     全部方法集合如下:

      -- 方法: handle_read ()

          当异步循环检测到通道的套接字上的 ‘read()’ 调用将要成功时会被调
          用。

      -- 方法: handle_write ()

          当异步循环检测到一个可写套接字可以被写入时会被调用。 通常此方
          法将实现必要的缓冲机制以保证运行效率。 例如:

               def handle_write(self):
                   sent = self.send(self.buffer)
                   self.buffer = self.buffer[sent:]

      -- 方法: handle_expt ()

          当一个套接字连接存在带外（OOB）数据时会被调用。 这几乎从来不会
          发生，因为 OOB 虽然受支持但很少被使用。

      -- 方法: handle_connect ()

          当活动打开方的套接字实际建立连接时会被调用。 可能会发送一条“欢
          迎”消息，或者向远程端点发起协议协商等。

      -- 方法: handle_close ()

          当套接字关闭时会被调用。

      -- 方法: handle_error ()

          当一个异常被引发并且未获得其他处理时会被调用。 默认版本将打印
          精简的回溯信息。

      -- 方法: handle_accept ()

          当可以与发起对本地端点的 *note connect(): 2770. 调用的新远程端
          点建立连接时会在侦听通道（被动打开方）上被调用。 在 3.2 版中已
          被弃用；请改用 *note handle_accepted(): bcc.。

          3.2 版后已移除.

      -- 方法: handle_accepted (sock, addr)

          当与发起对本地端点的 *note connect(): 2770. 调用的新远程端点已
          建立连接时会在侦听通道（被动打开方）上被调用。 `sock' 是可被用
          于在连接上发送和接收数据的 `新建' 套接字对象，而 `addr' 是绑定
          到连接另一端的套接字的地址。

          3.2 新版功能.

      -- 方法: readable ()

          每次在异步循环之外被调用以确定是否应当将一个通道的套接字添加到
          可能在其上发生读取事件的列表中。 默认方法会简单地返回 ‘True’，
          表示在默认情况下，所有通道都希望能读取事件。

      -- 方法: writable ()

          每次在异步循环之外被调用以确定是否应当将一个通道的套接字添加到
          可能在其上发生写入事件的列表中。 默认方法会简单地返回 ‘True’，
          表示在默认情况下，所有通道都希望能写入事件。

     此外，每个通道都委托或扩展了许多套接字方法。 它们大部分都与其套接字
     的对应方法几乎一样。

      -- 方法: create_socket (family=socket.AF_INET,
               type=socket.SOCK_STREAM)

          这与普通套接字的创建相同，并会使用同样的创建选项。 请参阅
          *note socket: f0. 文档了解有关创建套接字的信息。

          在 3.3 版更改: `family' 和 `type' 参数可以被省略。

      -- 方法: connect (address)

          与普通套接字对象一样，`address' 是一个元组，它的第一个元素是要
          连接的主机，第二个元素是端口号。

      -- 方法: send (data)

          将 `data' 发送到套接字的远程端点。

      -- 方法: recv (buffer_size)

          从套接字的远程端点读取至多 `buffer_size' 个字节。 读到空字节串
          表明通道已从另一端被关闭。

          请注意 *note recv(): 2773. 可能会引发 *note BlockingIOError:
          99f.，即使 *note select.select(): 67c. 或 *note select.poll():
          2715. 报告套接字已准备好被读取。

      -- 方法: listen (backlog)

          侦听与套接字的连接。 `backlog' 参数指明排入连接队列的最大数量
          且至少应为 1；最大值取决于具体系统（通常为 5）。

      -- 方法: bind (address)

          将套接字绑定到 `address'。 套接字必须尚未被绑定。 (`address' 的
          格式取决于具体的地址族 — 请参阅 *note socket: f0. 文档了解更多
          信息。) 要将套接字标记为可重用的 (设置 ‘SO_REUSEADDR’ 选项)，
          请调用 *note dispatcher: bcb. 对象的 ‘set_reuse_addr()’ 方法。

      -- 方法: accept ()

          接受一个连接。 此套接字必须绑定到一个地址上并且侦听连接。 返回
          值可以是 ‘None’ 或一个 ‘(conn, address)’ 对，其中 `conn' 是一
          个可用来在此连接上发送和接收数据的 `新的' 套接字对象，而
          `address' 是绑定到连接另一端套接字的地址。 当返回 ‘None’ 时意
          味着连接没有建立，在此情况下服务器应当忽略此事件并继续侦听后续
          的入站连接。

      -- 方法: close ()

          关闭套接字。 在此套接字对象上的后续操作都将失败。 远程端点将不
          再接收任何数据（在排入队列的数据被清空之后）。 当套接字被垃圾
          回收时会自动关闭。

 -- 类: asyncore.dispatcher_with_send

     *note dispatcher: bcb. 的一个添加了简单缓冲输出功能的子类，适用于简
     单客户端。 对于更复杂的用法请使用 *note asynchat.async_chat: 8be.。

 -- 类: asyncore.file_dispatcher

     file_dispatcher 接受一个文件描述符或 *note file object: b4a. 以及一
     个可选的 map 参数，并对其进行包装以配合 ‘poll()’ 或 ‘loop()’ 函数使
     用。 如果提供一个文件对象或任何具有 ‘fileno()’ 方法的对象，其方法将
     被调用并传递给 *note file_wrapper: 2779. 构造器。

     *note 可用性: 136f.: Unix。

 -- 类: asyncore.file_wrapper

     file_wrapper 接受一个整数形式的文件描述符并调用 *note os.dup():
     fa4. 来复制其句柄，以便原始句柄可以独立于 file_wrapper 被关闭。 这
     个类实现了足够的方法来模拟套接字以供 *note file_dispatcher: 2778. 类
     来使用。

     *note 可用性: 136f.: Unix。

* Menu:

* asyncore 示例基本 HTTP 客户端::
* asyncore 示例基本回显服务器::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/asyncore.py


File: python.info,  Node: asyncore 示例基本 HTTP 客户端,  Next: asyncore 示例基本回显服务器,  Up: asyncore --- 异步socket处理器

5.18.6.1 asyncore 示例基本 HTTP 客户端
......................................

下面是一个非常基本的 HTTP 客户端，它使用了 *note dispatcher: bcb. 类来实
现套接字处理:

     import asyncore

     class HTTPClient(asyncore.dispatcher):

         def __init__(self, host, path):
             asyncore.dispatcher.__init__(self)
             self.create_socket()
             self.connect( (host, 80) )
             self.buffer = bytes('GET %s HTTP/1.0\r\nHost: %s\r\n\r\n' %
                                 (path, host), 'ascii')

         def handle_connect(self):
             pass

         def handle_close(self):
             self.close()

         def handle_read(self):
             print(self.recv(8192))

         def writable(self):
             return (len(self.buffer) > 0)

         def handle_write(self):
             sent = self.send(self.buffer)
             self.buffer = self.buffer[sent:]


     client = HTTPClient('www.python.org', '/')
     asyncore.loop()


File: python.info,  Node: asyncore 示例基本回显服务器,  Prev: asyncore 示例基本 HTTP 客户端,  Up: asyncore --- 异步socket处理器

5.18.6.2 asyncore 示例基本回显服务器
....................................

下面是一个基本的回显服务器，它使用了 *note dispatcher: bcb. 类来接受连接
并将入站连接发送给处理程序:

     import asyncore

     class EchoHandler(asyncore.dispatcher_with_send):

         def handle_read(self):
             data = self.recv(8192)
             if data:
                 self.send(data)

     class EchoServer(asyncore.dispatcher):

         def __init__(self, host, port):
             asyncore.dispatcher.__init__(self)
             self.create_socket()
             self.set_reuse_addr()
             self.bind((host, port))
             self.listen(5)

         def handle_accepted(self, sock, addr):
             print('Incoming connection from %s' % repr(addr))
             handler = EchoHandler(sock)

     server = EchoServer('localhost', 8080)
     asyncore.loop()


File: python.info,  Node: asynchat --- 异步 socket 指令/响应 处理器,  Next: signal --- 设置异步事件处理程序,  Prev: asyncore --- 异步socket处理器,  Up: 网络和进程间通信

5.18.7 ‘asynchat’ — 异步 socket 指令/响应 处理器
------------------------------------------------

`源代码:' Lib/asynchat.py(1)

3.6 版后已移除: 请使用 *note asyncio: a. 替代。

__________________________________________________________________

     注解: 该模块仅为提供向后兼容。我们推荐在新代码中使用 *note asyncio:
     a. 。

此模块在 *note asyncore: b. 框架之上构建，简化了异步客户端和服务器并使得
处理元素为以任意字符串结束或者为可变长度的协议更加容易。 *note asynchat:
9. 定义了一个可以由你来子类化的抽象类 *note async_chat: 8be.，提供了
‘collect_incoming_data()’ 和 ‘found_terminator()’ 等方法的实现。 它使用
与 *note asyncore: b. 相同的异步循环，并且可以在通道映射中自由地混合
*note asyncore.dispatcher: bcb. 和 *note asynchat.async_chat: 8be. 这两
种类型的通道。 一般来说 *note asyncore.dispatcher: bcb. 服务器通道在接收
到传入的连接请求时会生成新的 *note asynchat.async_chat: 8be. 通道对象。

 -- 类: asynchat.async_chat

     这个类是 *note asyncore.dispatcher: bcb. 的抽象子类。 对于实际使用
     的代码你必须子类化 *note async_chat: 8be.，提供有意义的 *note
     collect_incoming_data(): 2780. 和 *note found_terminator(): 2781. 方
     法。 *note asyncore.dispatcher: bcb. 的方法也可以被使用，但它们在消
     息/响应上下文中并不是全都有意义。

     与 *note asyncore.dispatcher: bcb. 类似，*note async_chat: 8be. 也
     定义了一组通过对 ‘select()’ 调用之后的套接字条件进行分析所生成的事
     件。 一旦启动轮询循环 *note async_chat: 8be. 对象的方法就会被事件处
     理框架调用而无须程序员方面做任何操作。

     两个可被修改的类属性，用以提升性能，甚至也可能会节省内存。

      -- 数据: ac_in_buffer_size

          异步输入缓冲区大小 (默认为 ‘4096’)。

      -- 数据: ac_out_buffer_size

          异步输出缓冲区大小 (默认为 ‘4096’)。

     与 *note asyncore.dispatcher: bcb. 不同，*note async_chat: 8be. 允
     许你定义一个 FIFO 队列 `producers'。 其中的生产者只需要一个方法
     ‘more()’，该方法应当返回要在通道上传输的数据。 生产者通过让其
     ‘more()’ 方法返回空字节串对象来表明其处于耗尽状态 (`意即' 它已不再
     包含数据)。 此时 *note async_chat: 8be. 对象会将该生产者从队列中移
     除并开始使用下一个生产者，如果有下一个的话。 当生产者队列为空时
     ‘handle_write()’ 方法将不执行任何操作。 你要使用通道对象的 *note
     set_terminator(): 2784. 方法来描述如何识别来自远程端点的入站传输的
     结束或是重要的中断点。

     要构建一个可用的 *note async_chat: 8be. 子类，你的输入方法 *note
     collect_incoming_data(): 2780. 和 *note found_terminator(): 2781. 必
     须要处理通道异步接收的数据。 这些参数的描述见下文。

 -- 方法: async_chat.close_when_done ()

     将 ‘None’ 推入生产者队列。 当此生产者被弹出队列时它将导致通道被关闭
     。

 -- 方法: async_chat.collect_incoming_data (data)

     调用时附带 `data'，其中包含任意数量的已接收数据。 必须被重载的默认
     方法将引发一个 *note NotImplementedError: 617. 异常。

 -- 方法: async_chat.discard_buffers ()

     在紧急情况下此方法将丢弃输入和/或输出缓冲区以及生产者队列中的任何数
     据。

 -- 方法: async_chat.found_terminator ()

     当输入数据流能匹配 *note set_terminator(): 2784. 所设定的终结条件时
     会被调用。 必须被重载的默认方法将引发一个 *note
     NotImplementedError: 617. 异常。 被缓冲的输入数据应当可以通过实例属
     性来获取。

 -- 方法: async_chat.get_terminator ()

     返回通道的当前终结器。

 -- 方法: async_chat.push (data)

     将数据推入通道的队列以确保其被传输。 要让通道将数据写到网络中你只需
     要这样做就足够了，虽然以更复杂的方式使用你自己的生产者也是有可能的
     ，例如为了实现加密和分块。

 -- 方法: async_chat.push_with_producer (producer)

     获取一个生产者对象并将其加入到与通道相关联的生产者队列中。 当所有当
     前已推入的生产者都已被耗尽时通道将通过调用其 ‘more()’ 方法来耗用此
     生产者的数据并将数据发送至远程端点。

 -- 方法: async_chat.set_terminator (term)

     设置可在通道上被识别的终结条件。 ‘term’ 可以是三种类型值中的任意一
     种 ，对应于处理入站协议数据的三种不同方式。

     term            描述
                     
     ------------------------------------------------------------------
                     
     `string'        当在输入流中发现该字符串时将会调用
                     *note found_terminator(): 2781.
                     
                     
     `integer'       当接收到指定数量的字符时将会调用
                     *note found_terminator(): 2781.
                     
                     
     ‘None’          通道会不断地持续收集数据
                     

     请注意终结器之后的任何数据将可在 *note found_terminator(): 2781. 被
     调用后由通道来读取。

* Menu:

* asynchat 示例::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/asynchat.py


File: python.info,  Node: asynchat 示例,  Up: asynchat --- 异步 socket 指令/响应 处理器

5.18.7.1 asynchat 示例
......................

下面的例子片段显示了如何通过 *note async_chat: 8be. 来读取 HTTP 请求。
Web 服务器可以为每个入站的客户端连接创建 ‘http_request_handler’ 对象。 请
注意在初始时通道终结器会被设置为匹配 HTTP 请求头末尾的空行，并且会用一个
旗标来指明请求头正在被读取。

一旦完成了标头的读取，如果请求类型为 POST (表明输入流中存在更多的数据) 则
会使用 ‘Content-Length:’ 标头来设置一个数值终结器以从通道读取适当数量的
数据。

一旦完成了对所有相关输入的处理，将会在设置通道终结器为 ‘None’ 以确保忽略
掉 Web 客户端所发送的任何无关数据之后调用 ‘handle_request()’ 方法。

     import asynchat

     class http_request_handler(asynchat.async_chat):

         def __init__(self, sock, addr, sessions, log):
             asynchat.async_chat.__init__(self, sock=sock)
             self.addr = addr
             self.sessions = sessions
             self.ibuffer = []
             self.obuffer = b""
             self.set_terminator(b"\r\n\r\n")
             self.reading_headers = True
             self.handling = False
             self.cgi_data = None
             self.log = log

         def collect_incoming_data(self, data):
             """Buffer the data"""
             self.ibuffer.append(data)

         def found_terminator(self):
             if self.reading_headers:
                 self.reading_headers = False
                 self.parse_headers(b"".join(self.ibuffer))
                 self.ibuffer = []
                 if self.op.upper() == b"POST":
                     clen = self.headers.getheader("content-length")
                     self.set_terminator(int(clen))
                 else:
                     self.handling = True
                     self.set_terminator(None)
                     self.handle_request()
             elif not self.handling:
                 self.set_terminator(None)  # browsers sometimes over-send
                 self.cgi_data = parse(self.headers, b"".join(self.ibuffer))
                 self.handling = True
                 self.ibuffer = []
                 self.handle_request()


File: python.info,  Node: signal --- 设置异步事件处理程序,  Next: mmap --- 内存映射文件支持,  Prev: asynchat --- 异步 socket 指令/响应 处理器,  Up: 网络和进程间通信

5.18.8 ‘signal’ — 设置异步事件处理程序
--------------------------------------

__________________________________________________________________

该模块提供了在 Python 中使用信号处理程序的机制。

* Menu:

* 一般规则::
* 模块内容: 模块内容<5>.
* 示例: 示例<9>.
* 对于 SIGPIPE 的说明::


File: python.info,  Node: 一般规则,  Next: 模块内容<5>,  Up: signal --- 设置异步事件处理程序

5.18.8.1 一般规则
.................

*note signal.signal(): a85. 函数允许定义在接收到信号时执行的自定义处理程
序。少量的默认处理程序已经设置： *note SIGPIPE: 278f. 被忽略（因此管道和
套接字上的写入错误可以报告为普通的 Python 异常）以及如果父进程没有更改
*note SIGINT: 24e2. ，则其会被翻译成 *note KeyboardInterrupt: 198. 异常
。

一旦设置，特定信号的处理程序将保持安装，直到它被显式重置（ Python 模拟
BSD 样式接口而不管底层实现），但 *note SIGCHLD: 2790. 的处理程序除外，它
遵循底层实现。

* Menu:

* 执行 Python 信号处理程序::
* 信号与线程::


File: python.info,  Node: 执行 Python 信号处理程序,  Next: 信号与线程,  Up: 一般规则

5.18.8.2 执行 Python 信号处理程序
.................................

Python 信号处理程序不会在低级（ C ）信号处理程序中执行。相反，低级信号处
理程序设置一个标志，告诉 *note virtual machine: 2792. 稍后执行相应的
Python 信号处理程序（例如在下一个 *note bytecode: 61d. 指令）。这会导致
：

   * 捕获同步错误是没有意义的，例如 *note SIGFPE: 2793. 或 *note
     SIGSEGV: 2794. ，它们是由 C 代码中的无效操作引起的。Python 将从信号
     处理程序返回到 C 代码，这可能会再次引发相同的信号，导致 Python 显然
     的挂起。 从Python 3.3开始，你可以使用 *note faulthandler: 7d. 模块
     来报告同步错误。

   * 纯 C 中实现的长时间运行的计算（例如在大量文本上的正则表达式匹配）可
     以在任意时间内不间断地运行，而不管接收到任何信号。计算完成后将调用
     Python 信号处理程序。


File: python.info,  Node: 信号与线程,  Prev: 执行 Python 信号处理程序,  Up: 一般规则

5.18.8.3 信号与线程
...................

Python 信号处理程序总是在主 Python 线程中执行，即使信号是在另一个线程中
接收的。这意味着信号不能用作线程间通信的手段。 你可以使用 *note
threading: 10a. 模块中的同步原函数。

此外，只允许主线程设置新的信号处理程序。


File: python.info,  Node: 模块内容<5>,  Next: 示例<9>,  Prev: 一般规则,  Up: signal --- 设置异步事件处理程序

5.18.8.4 模块内容
.................

在 3.5 版更改: 信号（ SIG* ），处理程序（ *note SIG_DFL: 24e3. ， *note
SIG_IGN: 24e4.）和 sigmask（ *note SIG_BLOCK: 2798. ， *note
SIG_UNBLOCK: 2799. ， *note SIG_SETMASK: 279a. ）下面列出的相关常量变成
了 *note enums: 596. 。 *note getsignal(): 279b. ， *note
pthread_sigmask(): a81. ， *note sigpending(): a83. 和 *note sigwait():
a84. 函数返回人类可读的 *note enums: 596. 。

在 *note signal: eb. 模块中定义的变量是：

 -- 数据: signal.SIG_DFL

     这是两种标准信号处理选项之一；它只会执行信号的默认函数。 例如，在大
     多数系统上，对于 ‘SIGQUIT’ 的默认操作是转储核心并退出，而对于 *note
     SIGCHLD: 2790. 的默认操作是简单地忽略它。

 -- 数据: signal.SIG_IGN

     这是另一个标准信号处理程序，它将简单地忽略给定的信号。

 -- 数据: signal.SIGABRT

     来自 ‘abort(3)’ 的中止信号。

 -- 数据: signal.SIGALRM

     来自 ‘alarm(2)’ 的计时器信号。

     *note 可用性: 136f.: Unix。

 -- 数据: signal.SIGBREAK

     来自键盘 (CTRL + BREAK) 的中断。

     *note 可用性: 136f.: Windows。

 -- 数据: signal.SIGBUS

     总线错误 (非法的内存访问)。

     *note 可用性: 136f.: Unix。

 -- 数据: signal.SIGCHLD

     子进程被停止或终结。

     *note 可用性: 136f.: Unix。

 -- 数据: signal.SIGCLD

     *note SIGCHLD: 2790. 的别名。

 -- 数据: signal.SIGCONT

     如果进程当前已停止则继续执行它

     *note 可用性: 136f.: Unix。

 -- 数据: signal.SIGFPE

     浮点异常。 例如除以零。

     参见
     ....

     当除法或求余运算的第二个参数为零时会引发 *note ZeroDivisionError:
     12bd. 。

 -- 数据: signal.SIGHUP

     在控制终端上检测到挂起或控制进程的终止。

     *note 可用性: 136f.: Unix。

 -- 数据: signal.SIGILL

     非法指令。

 -- 数据: signal.SIGINT

     来自键盘的中断 (CTRL + C)。

     默认的动作是引发 *note KeyboardInterrupt: 198.。

 -- 数据: signal.SIGKILL

     终止信号。

     它不能被捕获、阻塞或忽略。

     *note 可用性: 136f.: Unix。

 -- 数据: signal.SIGPIPE

     损坏的管道：写入到没有读取器的管道。

     默认的动作是忽略此信号。

     *note 可用性: 136f.: Unix。

 -- 数据: signal.SIGSEGV

     段错误：无效的内存引用。

 -- 数据: signal.SIGTERM

     终结信号。

 -- 数据: signal.SIGUSR1

     用户自定义信号 1。

     *note 可用性: 136f.: Unix。

 -- 数据: signal.SIGUSR2

     用户自定义信号 2。

     *note 可用性: 136f.: Unix。

 -- 数据: signal.SIGWINCH

     窗口调整大小信号。

     *note 可用性: 136f.: Unix。

 -- 数据: SIG*

     所有信号编号都是符号化定义的。 例如，挂起信号被定义为 *note
     signal.SIGHUP: 27a1.；变量的名称与 C 程序中使用的名称相同，具体见
     ‘<signal.h>’。 ’‘signal()’’ 的 Unix 手册页面列出了现有的信号 (在某
     些系统上这是 ‘signal(2)’，在其他系统中此列表则是在 ‘signal(7)’ 中
     )。 请注意并非所有系统都会定义相同的信号名称集；只有系统所定义的名
     称才会由此模块来定义。

 -- 数据: signal.CTRL_C_EVENT

     对应于 ‘Ctrl+C’ 击键事件的信号。此信号只能用于 *note os.kill():
     cfb. 。

     *note 可用性: 136f.: Windows。

     3.2 新版功能.

 -- 数据: signal.CTRL_BREAK_EVENT

     对应于 ‘Ctrl+Break’ 击键事件的信号。此信号只能用于 *note os.kill():
     cfb. 。

     *note 可用性: 136f.: Windows。

     3.2 新版功能.

 -- 数据: signal.NSIG

     比最高信号数多一。

 -- 数据: signal.ITIMER_REAL

     实时递减间隔计时器，并在到期时发送 *note SIGALRM: 279d. 。

 -- 数据: signal.ITIMER_VIRTUAL

     仅在进程执行时递减间隔计时器，并在到期时发送 SIGVTALRM 。

 -- 数据: signal.ITIMER_PROF

     当进程执行时以及当系统替进程执行时都会减小间隔计时器。 这个计时器与
     ITIMER_VIRTUAL 相配结，通常被用于分析应用程序在用户和内核空间中花费
     的时间。 SIGPROF 会在超期时被发送。

 -- 数据: signal.SIG_BLOCK

     *note pthread_sigmask(): a81. 的 `how' 形参的一个可能的值，表明信号
     将会被阻塞。

     3.3 新版功能.

 -- 数据: signal.SIG_UNBLOCK

     *note pthread_sigmask(): a81. 的 `how' 形参的是个可能的值，表明信号
     将被解除阻塞。

     3.3 新版功能.

 -- 数据: signal.SIG_SETMASK

     *note pthread_sigmask(): a81. 的 `how' 形参的一个可能的值，表明信号
     掩码将要被替换。

     3.3 新版功能.

*note signal: eb. 模块定义了一个异常:

 -- 例外: signal.ItimerError

     作为来自下层 *note setitimer(): 27ac. 或 *note getitimer(): 27ad. 实
     现错误的信号被引发。 如果将无效的定时器或负的时间值传给 *note
     setitimer(): 27ac. 就导致这个错误。 此错误是 *note OSError: 1d4. 的
     子类型。

     3.3 新版功能: 此错误是 *note IOError: 99a. 的子类型，现在则是 *note
     OSError: 1d4. 的别名。

*note signal: eb. 模块定义了以下函数:

 -- 函数: signal.alarm (time)

     如果 `time' 值非零，则此函数将要求将一个 *note SIGALRM: 279d. 信号
     在 `time' 秒内发往进程。 任何在之前排入计划的警报都会被取消（在任何
     时刻都只能有一个警报被排入计划）。 后续的返回值将是任何之前设置的警
     报被传入之前的秒数。 如果 `time' 值为零，则不会将任何警报排入计划，
     并且任何已排入计划的警报都会被取消。 如果返回值为零，则目前没有任何
     警报被排入计划。

     *note 可用性: 136f.: Unix。 更多信息请参见手册页面 ‘alarm(2)’。

 -- 函数: signal.getsignal (signalnum)

     返回当前用于信号 `signalnum' 的信号处理程序。 返回值可以是一个
     Python 可调用对象，或是特殊值 *note signal.SIG_IGN: 24e4, *note
     signal.SIG_DFL: 24e3. 或 *note None: 158. 之一。 在这里，*note
     signal.SIG_IGN: 24e4. 表示信号在之前被忽略，*note signal.SIG_DFL:
     24e3. 表示之前在使用默认的信号处理方式，而 ‘None’ 表示之前的信号处
     理程序未由 Python 安装。

 -- 函数: signal.strsignal (signalnum)

     返回信号 `signalnum' 的系统描述，例如 "Interrupt", "Segmentation
     fault" 等等。 如果信号无法被识别则返回 *note None: 158.。

     3.8 新版功能.

 -- 函数: signal.valid_signals ()

     返回本平台上的有效信号编号集。 这可能会少于 ‘range(1, NSIG)’，如果
     某些信号被系统保留作为内部使用的话。

     3.8 新版功能.

 -- 函数: signal.pause ()

     使进程休眠直至接收到一个信号；然后将会调用适当的处理程序。 返回空值
     。

     *note 可用性: 136f.: Unix。 更多信息请参见手册页面 ‘signal(2)’。

     另请参阅 *note sigwait(): a84, *note sigwaitinfo(): 688, *note
     sigtimedwait(): 687. 和 *note sigpending(): a83.。

 -- 函数: signal.raise_signal (signum)

     向调用方进程发送一个信号。 返回空值。

     3.8 新版功能.

 -- 函数: signal.pthread_kill (thread_id, signalnum)

     Send the signal `signalnum' to the thread `thread_id', another
     thread in the same process as the caller.  The target thread can be
     executing any code (Python or not).  However, if the target thread
     is executing the Python interpreter, the Python signal handlers
     will be *note executed by the main thread: 2796.  Therefore, the
     only point of sending a signal to a particular Python thread would
     be to force a running system call to fail with *note
     InterruptedError: 662.

     使用 *note threading.get_ident(): ab7. 或 *note threading.Thread:
     235. 对象的 *note ident: 2028. 属性为 `thread_id' 获取合适的值。

     如果 `signalnum' 为 0，则不会发送信号，但仍然会执行错误检测；这可被
     用来检测目标线程是否仍在运行。

     引发一个 *note 审计事件: ea1. ‘signal.pthread_kill’，附带参数
     ‘thread_id’, ‘signalnum’。

     *note 可用性: 136f.: Unix。 更多信息请参见手册页面
     ‘pthread_kill(3)’。

     另请参阅 *note os.kill(): cfb.。

     3.3 新版功能.

 -- 函数: signal.pthread_sigmask (how, mask)

     获取和/或修改调用方线程的信号掩码。 信号掩码是一组传送过程目前为调
     用者而阻塞的信号集。 返回旧的信号掩码作为一组信号。

     该调用的行为取决于 `how' 的值，具体见下。

        * *note SIG_BLOCK: 2798.: 被阻塞的信号集是当前集与 `mask' 参数的
          并集。

        * *note SIG_UNBLOCK: 2799.: `mask' 中的信号会从当前已阻塞信号集
          中被移除。 允许尝试取消对一个非阻塞信号的阻塞。

        * *note SIG_SETMASK: 279a.: 已阻塞信号集会被设为 `mask' 参数的值
          。

     `mask' 是一个信号编号集合 (例如 {*note signal.SIGINT: 24e2, *note
     signal.SIGTERM: 257e.})。 请使用 *note valid_signals(): 27af. 表示
     包含所有信号的完全掩码。

     例如，‘signal.pthread_sigmask(signal.SIG_BLOCK, [])’ 会读取调用方线
     程的信号掩码。

     *note SIGKILL: 27a3. 和 ‘SIGSTOP’ 不能被阻塞。

     *note 可用性: 136f.: Unix。 更多信息请参见手册页面 ‘sigprocmask(3)’
     和 ‘pthread_sigmask(3)’。

     另请参阅 *note pause(): 27b0, *note sigpending(): a83. 和 *note
     sigwait(): a84.。

     3.3 新版功能.

 -- 函数: signal.setitimer (which, seconds, interval=0.0)

     设置由 `which' 指明的给定间隔计时器 (*note signal.ITIMER_REAL:
     27a8, *note signal.ITIMER_VIRTUAL: 27a9. 或 *note
     signal.ITIMER_PROF: 27aa. 之一) 在 `seconds' 秒 (接受浮点数值，为与
     *note alarm(): 27ae. 之差) 之后开始并在每 `interval' 秒间隔时 (如果
     `interval' 不为零) 启动。 由 `which' 指明的间隔计时器可通过将
     `seconds' 设为零来清空。

     当一个间隔计时器启动时，会有信号发送至进程。 所发送的具体信号取决于
     所使用的计时器；*note signal.ITIMER_REAL: 27a8. 将发送 *note
     SIGALRM: 279d, *note signal.ITIMER_VIRTUAL: 27a9. 将发送
     ‘SIGVTALRM’, 而 *note signal.ITIMER_PROF: 27aa. 将发送 ‘SIGPROF’.

     原有的值会以元组: (delay, interval) 的形式被返回。

     尝试传入无效的计时器将导致 *note ItimerError: 27ab.。

     *note 可用性: 136f.: Unix。

 -- 函数: signal.getitimer (which)

     返回由 `which' 指明的给定间隔计时器当前的值。

     *note 可用性: 136f.: Unix。

 -- 函数: signal.set_wakeup_fd (fd, *, warn_on_full_buffer=True)

     将唤醒文件描述符设为 `fd'。 当接收到信号时，会将信号编号以单个字节
     的形式写入 fd。 这可被其它库用来唤醒一次 poll 或 select 调用，以允
     许该信号被完全地处理。

     原有的唤醒 fd 会被返回（或者如果未启用文件描述符唤醒则返回 -1）。 如
     果 `fd' 为 -1，文件描述符唤醒会被禁用。 如果不为 -1，则 `fd' 必须为
     非阻塞型。 需要由库来负责在重新调用 poll 或 select 之前从 `fd' 移除
     任何字节数据。

     When threads are enabled, this function can only be called from the
     main thread; attempting to call it from other threads will cause a
     *note ValueError: 1fc. exception to be raised.

     使用此函数有两种通常的方式。 在两种方式下，当有信号到达时你都是用
     fd 来唤醒，但之后它们在确定达到的一个或多个信号 `which' 时存在差异
     。

     在第一种方式下，我们从 fd 的缓冲区读取数据，这些字节值会给你信号编
     号。 这种方式很简单，但在少数情况下会发生问题：通常 fd 将有缓冲区空
     间大小限制，如果信号到达得太多且太快，缓冲区可能会爆满，有些信号可
     能丢失。 如果你使用此方式，则你应当设置 ‘warn_on_full_buffer=True’，
     当信号丢失时这至少能将警告消息打印到 stderr。

     在第二种方式下，我们 `只会' 将唤醒 fd 用于唤醒，而忽略实际的字节值
     。 在此情况下，我们所关心的只有 fd 的缓冲区为空还是不为空；爆满的缓
     冲区完全不会导致问题。 如果你使用此方式，则你应当设置
     ‘warn_on_full_buffer=False’，这样你的用户就不会被虚假的警告消息所迷
     惑。

     在 3.5 版更改: 在 Windows 上，此函数现在也支持套接字处理。

     在 3.7 版更改: 添加了 ‘warn_on_full_buffer’ 形参。

 -- 函数: signal.siginterrupt (signalnum, flag)

     更改系统调用重启行为：如果 `flag' 为 *note False: 390.，系统调用将
     在被信号 `signalnum' 中断时重启，否则系统调用将被中断。 返回空值。

     *note 可用性: 136f.: Unix。 更多信息请参见手册页面
     ‘siginterrupt(3)’。

     请注意用 *note signal(): eb. 安装信号处理程序将重启行为重置为可通过
     显式调用 ‘siginterrupt()’ 并为给定信号的 `flag' 设置真值来实现中断
     。

 -- 函数: signal.signal (signalnum, handler)

     将信号 `signalnum' 的处理程序设为函数 `handler'。 `handler' 可以为
     接受两个参数（见下）的 Python 可调用对象，或者为特殊值 *note
     signal.SIG_IGN: 24e4. 或 *note signal.SIG_DFL: 24e3. 之一。 之前的
     信号处理程序将被返回（参见上文 *note getsignal(): 279b. 的描述）。
     （更多信息请参阅 Unix 手册页面 ‘signal(2)’。）

     When threads are enabled, this function can only be called from the
     main thread; attempting to call it from other threads will cause a
     *note ValueError: 1fc. exception to be raised.

     `handler' 将附带两个参数调用：信号编号和当前堆栈帧 (‘None’ 或一个帧
     对象；有关帧对象的描述请参阅 *note 类型层级结构描述: 1442. 或者参阅
     *note inspect: a1. 模块中的属性描述)。

     在 Windows 上，*note signal(): eb. 调用只能附带 *note SIGABRT:
     279c, *note SIGFPE: 2793, *note SIGILL: 27a2, *note SIGINT: 24e2,
     *note SIGSEGV: 2794, *note SIGTERM: 257e. 或 *note SIGBREAK: 279e.。
     任何其他值都将引发 *note ValueError: 1fc.。 请注意不是所有系统都定
     义了同样的信号名称集合；如果一个信号名称未被定义为 ‘SIG*’ 模块层级
     常量则将引发 *note AttributeError: 3a3.。

 -- 函数: signal.sigpending ()

     检查正在等待传送给调用方线程的信号集合（即在阻塞期间被引发的信号）
     。 返回正在等待的信号集合。

     *note 可用性: 136f.: Unix。 更多信息请参见手册页面 ‘sigpending(2)’。

     另请参阅 *note pause(): 27b0, *note pthread_sigmask(): a81. 和
     *note sigwait(): a84.。

     3.3 新版功能.

 -- 函数: signal.sigwait (sigset)

     挂起调用方线程的执行直到信号集合 `sigset' 中指定的信号之一被传送。
     此函数会接受该信号（将其从等待信号列表中移除），并返回信号编号。

     *note 可用性: 136f.: Unix。 更多信息请参见手册页面 ‘sigwait(3)’。

     另请参阅 *note pause(): 27b0, *note pthread_sigmask(): a81, *note
     sigpending(): a83, *note sigwaitinfo(): 688. 和 *note
     sigtimedwait(): 687.。

     3.3 新版功能.

 -- 函数: signal.sigwaitinfo (sigset)

     挂起调用方线程的执行直到信号集合 `sigset' 中指定的信号之一被传送。
     此函数会接受该信号并将其从等待信号列表中移除。 如果 `sigset' 中的信
     号之一已经在等待调用方线程，此函数将立即返回并附带有关该信号的信息
     。 被传送信号的信号处理程序不会被调用。 如果该函数被某个不在
     `sigset' 中的信号中断则会引发 *note InterruptedError: 662.。

     返回值是一个代表 ‘siginfo_t’ 结构体所包含数据的对象，具体为:
     ‘si_signo’, ‘si_code’, ‘si_errno’, ‘si_pid’, ‘si_uid’, ‘si_status’,
     ‘si_band’。

     *note 可用性: 136f.: Unix。 更多信息请参见手册页面
     ‘sigwaitinfo(2)’。

     另请参阅 *note pause(): 27b0, *note sigwait(): a84. 和 *note
     sigtimedwait(): 687.。

     3.3 新版功能.

     在 3.5 版更改: 当被某个 不在 `sigset' 中的信号中断时本函数将结束并
     且信号处理程序不会引发异常 (其理由参见 PEP 475(1))。

 -- 函数: signal.sigtimedwait (sigset, timeout)

     类似于 *note sigwaitinfo(): 688.，但会接受一个额外的 `timeout' 参数
     来指定超时限制。 如果将 `timeout' 指定为 ‘0’，则会执行轮询。 如果发
     生超时则返回 *note None: 158.。

     *note 可用性: 136f.: Unix。 更多信息请参见手册页面
     ‘sigtimedwait(2)’。

     另请参阅 *note pause(): 27b0, *note sigwait(): a84. 和 *note
     sigwaitinfo(): 688.。

     3.3 新版功能.

     在 3.5 版更改: 现在当此函数被某个不在 `sigset' 中的信号中断时将以计
     算出的 `timeout' 进行重试并且信号处理程序不会引发异常（请参阅 PEP
     475(2) 了解其理由）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475

   (2) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: 示例<9>,  Next: 对于 SIGPIPE 的说明,  Prev: 模块内容<5>,  Up: signal --- 设置异步事件处理程序

5.18.8.5 示例
.............

这是一个最小示例程序。 它使用 *note alarm(): 27ae. 函数来限制等待打开一
个文件所花费的时间；这在文件为无法开启的串行设备时会很有用处，此情况通常
会导致 *note os.open(): 66e. 无限期地挂起。 解决办法是在打开文件之前设置
5 秒钟的 alarm；如果操作耗时过长，将会发送 alarm 信号，并且处理程序会引
发一个异常。

     import signal, os

     def handler(signum, frame):
         print('Signal handler called with signal', signum)
         raise OSError("Couldn't open device!")

     # Set the signal handler and a 5-second alarm
     signal.signal(signal.SIGALRM, handler)
     signal.alarm(5)

     # This open() may hang indefinitely
     fd = os.open('/dev/ttyS0', os.O_RDWR)

     signal.alarm(0)          # Disable the alarm


File: python.info,  Node: 对于 SIGPIPE 的说明,  Prev: 示例<9>,  Up: signal --- 设置异步事件处理程序

5.18.8.6 对于 SIGPIPE 的说明
............................

将你的程序用管道输出到工具例如 ‘head(1)’ 将会导致 *note SIGPIPE: 278f. 信
号在其标准输出的接收方提前关闭时被发送到你的进程。 这将引发一个异常例如
‘BrokenPipeError: [Errno 32] Broken pipe’。 要处理这种情况，请对你的入口
点进行包装以捕获此异常，如下所示:

     import os
     import sys

     def main():
         try:
             # simulate large output (your code replaces this loop)
             for x in range(10000):
                 print("y")
             # flush output here to force SIGPIPE to be triggered
             # while inside this try block.
             sys.stdout.flush()
         except BrokenPipeError:
             # Python flushes standard streams on exit; redirect remaining output
             # to devnull to avoid another BrokenPipeError at shutdown
             devnull = os.open(os.devnull, os.O_WRONLY)
             os.dup2(devnull, sys.stdout.fileno())
             sys.exit(1)  # Python exits with error code 1 on EPIPE

     if __name__ == '__main__':
         main()

不要将 *note SIGPIPE: 278f. 的处置方式设为 *note SIG_DFL: 24e3. 以避免
*note BrokenPipeError: 9a5.。 这样做还会在你的程序所写入的任何套接字连接
中断时导致你的程序异常退出。


File: python.info,  Node: mmap --- 内存映射文件支持,  Prev: signal --- 设置异步事件处理程序,  Up: 网络和进程间通信

5.18.9 ‘mmap’ — 内存映射文件支持
--------------------------------

__________________________________________________________________

内存映射文件对象的行为既像 *note bytearray: 33b. 又像 *note 文件对象:
b4a.。 你可以在大部分接受 *note bytearray: 33b. 的地方使用 mmap 对象；例
如，你可以使用 *note re: de. 模块来搜索一个内存映射文件。 你也可以通过执
行 ‘obj[index] = 97’ 来修改单个字节，或者通过对切片赋值来修改一个子序列:
‘obj[i1:i2] = b'...'’。 你还可以在文件的当前位置开始读取和写入数据，并使
用 ‘seek()’ 前往另一个位置。

内存映射文件是由 *note mmap: 1ed. 构造函数创建的，其在 Unix 和 Windows 上
是不同的。 无论哪种情况，你都必须为一个打开的文件提供文件描述符以进行更
新。 如果你希望映射一个已有的 Python 文件对象，请使用该对象的 ‘fileno()’
方法来获取 `fileno' 参数的正确值。 否则，你可以使用 *note os.open():
66e. 函数来打开这个文件，这会直接返回一个文件描述符（结束时仍然需要关闭
该文件）。

     注解: 如果要为可写的缓冲文件创建内存映射，则应当首先 *note flush():
     1ffc. 该文件。 这确保了对缓冲区的本地修改在内存映射中可用。

对于 Unix 和 Windows 版本的构造函数，可以将 `access' 指定为可选的关键字
参数。 `access' 接受以下四个值之一： ‘ACCESS_READ’ ， ‘ACCESS_WRITE’ 或
‘ACCESS_COPY’ 分别指定只读，直写或写时复制内存，或 ‘ACCESS_DEFAULT’ 推迟
到 `prot' 。 `access' 可以在 Unix 和 Windows 上使用。如果未指定 `access'
，则 Windows mmap 返回直写映射。这三种访问类型的初始内存值均取自指定的文
件。向 ‘ACCESS_READ’ 内存映射赋值会引发 *note TypeError: 193. 异常。 向
‘ACCESS_WRITE’ 内存映射赋值会影响内存和底层的文件。 向 ‘ACCESS_COPY’ 内
存映射赋值会影响内存，但不会更新底层的文件。

在 3.7 版更改: 添加了 ‘ACCESS_DEFAULT’ 常量。

要映射匿名内存，应将 -1 作为 fileno 和 length 一起传递。

 -- 类: mmap.mmap (fileno, length, tagname=None, access=ACCESS_DEFAULT[,
          offset])

     `（ Windows 版本）' 映射被文件句柄 `fileno' 指定的文件的 `length' 个
     字节，并创建一个 mmap 对象。如果 `length' 大于当前文件大小，则文件
     将扩展为包含 `length' 个字节。如果 `length' 为 ‘0’，则映射的最大长
     度为当前文件大小。如果文件为空， Windows 会引发异常（你无法在
     Windows上创建空映射）。

     如果 `tagname' 被指定且不是 ‘None’ ，则是为映射提供标签名称的字符串
     。 Windows 允许你对同一文件拥有许多不同的映射。如果指定现有标签的名
     称，则会打开该标签，否则将创建该名称的新标签。如果省略此参数或设置
     为 ‘None’ ，则创建的映射不带名称。避免使用 tag 参数将有助于使代码在
     Unix和Windows之间可移植。

     `offset' 可以被指定为非负整数偏移量。 mmap 引用将相对于从文件开头的
     偏移。 `offset' 默认为0。 `offeset' 必须是 ‘ALLOCATIONGRANULARITY’
     的倍数。

     引发一个 *note 审计事件: ea1. ‘mmap.__new__’ 附带参数 ‘fileno’,
     ‘length’, ‘access’, ‘offset’。

 -- 类: mmap.mmap (fileno, length, flags=MAP_SHARED,
          prot=PROT_WRITE|PROT_READ, access=ACCESS_DEFAULT[, offset])

     `(Unix 版本)' 映射文件描述符 `fileno' 指定的文件的 `length' 个字节
     ，并返回一个 mmap 对象。如果 `length' 为 ‘0’ ，则当调用 *note mmap:
     1ed. 时，映射的最大长度将为文件的当前大小。

     `flags' 指明映射的性质。 ‘MAP_PRIVATE’ 会创建私有的写入时拷贝映射，
     因此对 mmap 对象内容的修改将为该进程所私有，而 ‘MAP_SHARED’ 会创建
     与其他映射同一文件区域的进程所共享的映射。 默认值为 ‘MAP_SHARED’。

     如果指明了 `prot'，它将给出所需的内存保护方式；最有用的两个值是
     ‘PROT_READ’ 和 ‘PROT_WRITE’，分别指明页面为可读或可写。 `prot' 默认
     为 ‘PROT_READ | PROT_WRITE’。

     可以指定 `access' 作为替代 `flags' 和 `prot' 的可选关键字形参。 同
     时指定 `flags', `prot' 和 `access' 将导致错误。 请参阅上文中
     `access' 的描述了解有关如何使用此形参的信息。

     `offset' 可以被指定为非负整数偏移量。 mmap 引用将相对于从文件开头的
     偏移。 `offset' 默认为 0。 `offset' 必须是 ‘ALLOCATIONGRANULARITY’
     的倍数，它在 Unix 系统上等价于 ‘PAGESIZE’。

     要确保已创建内存映射的有效性，描述符 `fileno' 所指定的文件在 Mac OS
     X 和 OpenVMS 上会与物理后备存储进行内部自动同步。

     这个例子演示了使用 *note mmap: 1ed. 的简单方式:

          import mmap

          # write a simple example file
          with open("hello.txt", "wb") as f:
              f.write(b"Hello Python!\n")

          with open("hello.txt", "r+b") as f:
              # memory-map the file, size 0 means whole file
              mm = mmap.mmap(f.fileno(), 0)
              # read content via standard file methods
              print(mm.readline())  # prints b"Hello Python!\n"
              # read content via slice notation
              print(mm[:5])  # prints b"Hello"
              # update content using slice notation;
              # note that new content must have same size
              mm[6:] = b" world!\n"
              # ... and read again using standard file methods
              mm.seek(0)
              print(mm.readline())  # prints b"Hello  world!\n"
              # close the map
              mm.close()

     *note mmap: 1ed. 也可以在 *note with: 6f2. 语句中被用作上下文管理器
     :

          import mmap

          with mmap.mmap(-1, 13) as mm:
              mm.write(b"Hello world!")

     3.2 新版功能: 上下文管理器支持。

     下面的例子演示了如何创建一个匿名映射并在父进程和子进程之间交换数据
     。:

          import mmap
          import os

          mm = mmap.mmap(-1, 13)
          mm.write(b"Hello world!")

          pid = os.fork()

          if pid == 0:  # In a child process
              mm.seek(0)
              print(mm.readline())

              mm.close()

     引发一个 *note 审计事件: ea1. ‘mmap.__new__’ 附带参数 ‘fileno’,
     ‘length’, ‘access’, ‘offset’。

     映射内存的文件对象支持以下方法:

      -- 方法: close ()

          关闭 mmap。 后续调用该对象的其他方法将导致引发 ValueError 异常
          。 此方法将不会关闭打开的文件。

      -- 属性: closed

          如果文件已关闭则返回 ‘True’。

          3.2 新版功能.

      -- 方法: find (sub[, start[, end]])

          返回子序列 `sub' 在对象内被找到的最小索引号，使得 `sub' 被包含
          在 [`start', `end'] 范围中。 可选参数 `start' 和 `end' 会被解
          读为切片表示法。 如果未找到则返回 ‘-1’。

          在 3.5 版更改: 现在支持可写的 *note 字节类对象: 5f1.。

      -- 方法: flush ([offset[, size]])

          将对文件的内存副本的修改刷新至磁盘。 如果不使用此调用则无法保
          证在对象被销毁前将修改写回存储。 如果指定了 `offset' 和
          `size'，则只将对指定范围内字节的修改刷新至磁盘；在其他情况下，
          映射的全部范围都会被刷新。 `offset' 必须为 ‘PAGESIZE’ 或
          ‘ALLOCATIONGRANULARITY’ 的倍数。

          返回 ‘None’ 以表示成功。 当调用失败时将引发异常。

          在 3.8 版更改: 在之前版本中，成功时将返回非零值；在 Windows 下
          当发生错误时将返回零。 在 Unix 下 成功时将返回零值；当发生错误
          时将引发异常。

      -- 方法: madvise (option[, start[, length]])

          将有关内存区域的建议 `option' 发送至内核，从 `start' 开始扩展
          `length' 个字节。 `option' 必须为系统中可用的 *note MADV_*
          常量: 27ba. 之一。 如果省略 `start' 和 `length'，则会包含整个
          映射。 在某些系统中（包括 Linux），`start' 必须为 ‘PAGESIZE’ 的
          倍数。

          可用性: 具有 ‘madvise()’ 系统调用的系统。

          3.8 新版功能.

      -- 方法: move (dest, src, count)

          将从偏移量 `src' 开始的 `count' 个字节拷贝到目标索引号 `dest'。
          如果 mmap 创建时设置了 ‘ACCESS_READ’，则调用 move 将引发 *note
          TypeError: 193. 异常。

      -- 方法: read ([n])

          返回一个 *note bytes: 33a.，其中包含从当前文件位置开始的至多
          `n' 个字节。 如果参数省略，为 ‘None’ 或负数，则返回从当前文件
          位置开始直至映射结尾的所有字节。 文件位置会被更新为返回字节数
          据之后的位置。

          在 3.3 版更改: 参数可被省略或为 ‘None’。

      -- 方法: read_byte ()

          将当前文件位置上的一个字节以整数形式返回，并让文件位置前进 1。

      -- 方法: readline ()

          Returns a single line, starting at the current file position
          and up to the next newline.

      -- 方法: resize (newsize)

          改变映射以及下层文件的大小，如果存在的话。 如果 mmap 创建时设
          置了 ‘ACCESS_READ’ 或 ‘ACCESS_COPY’，则改变映射大小将引发
          *note TypeError: 193. 异常。

      -- 方法: rfind (sub[, start[, end]])

          返回子序列 `sub' 在对象内被找到的最大索引号，使得 `sub' 被包含
          在 [`start', `end'] 范围中。 可选参数 `start' 和 `end' 会被解
          读为切片表示法。 如果未找到则返回 ‘-1’。

          在 3.5 版更改: 现在支持可写的 *note 字节类对象: 5f1.。

      -- 方法: seek (pos[, whence])

          设置文件的当前位置。 `whence' 参数为可选项并且默认为
          ‘os.SEEK_SET’ 或 ‘0’ (绝对文件定位)；其他值还有 ‘os.SEEK_CUR’
          或 ‘1’ (相对当前位置查找) 和 ‘os.SEEK_END’ 或 ‘2’ (相对文件末
          尾查找)。

      -- 方法: size ()

          返回文件的长度，该数值可以大于内存映射区域的大小。

      -- 方法: tell ()

          返回文件指针的当前位置。

      -- 方法: write (bytes)

          将 `bytes' 中的字节数据写入文件指针当前位置的内存并返回写入的
          字节总数 (一定不小于 ‘len(bytes)’，因为如果写入失败，将会引发
          *note ValueError: 1fc.)。 在字节数据被写入后文件位置将会更新。
          如果 mmap 创建时设置了 ‘ACCESS_READ’，则向其写入将引发 *note
          TypeError: 193. 异常。

          在 3.5 版更改: 现在支持可写的 *note 字节类对象: 5f1.。

          在 3.6 版更改: 现在会返回写入的字节总数。

      -- 方法: write_byte (byte)

          将整数值 `byte' 写入文件指针当前位置的内存；文件位置前进 ‘1’。
          如果 mmap 创建时设置了 ‘ACCESS_READ’，则向其写入将引发 *note
          TypeError: 193. 异常。

* Menu:

* MADV_* 常量::


File: python.info,  Node: MADV_* 常量,  Up: mmap --- 内存映射文件支持

5.18.9.1 MADV_* 常量
....................

 -- 数据: mmap.MADV_NORMAL
 -- 数据: mmap.MADV_RANDOM
 -- 数据: mmap.MADV_SEQUENTIAL
 -- 数据: mmap.MADV_WILLNEED
 -- 数据: mmap.MADV_DONTNEED
 -- 数据: mmap.MADV_REMOVE
 -- 数据: mmap.MADV_DONTFORK
 -- 数据: mmap.MADV_DOFORK
 -- 数据: mmap.MADV_HWPOISON
 -- 数据: mmap.MADV_MERGEABLE
 -- 数据: mmap.MADV_UNMERGEABLE
 -- 数据: mmap.MADV_SOFT_OFFLINE
 -- 数据: mmap.MADV_HUGEPAGE
 -- 数据: mmap.MADV_NOHUGEPAGE
 -- 数据: mmap.MADV_DONTDUMP
 -- 数据: mmap.MADV_DODUMP
 -- 数据: mmap.MADV_FREE
 -- 数据: mmap.MADV_NOSYNC
 -- 数据: mmap.MADV_AUTOSYNC
 -- 数据: mmap.MADV_NOCORE
 -- 数据: mmap.MADV_CORE
 -- 数据: mmap.MADV_PROTECT

     这些选项可被传给 *note mmap.madvise(): 1ee.。 不是每个选项都存在于
     每个系统中。

     可用性: 具有 madvise() 系统调用的系统。

     3.8 新版功能.


File: python.info,  Node: 互联网数据处理,  Next: 结构化标记处理工具,  Prev: 网络和进程间通信,  Up: Python 标准库

5.19 互联网数据处理
===================

本章介绍了支持处理互联网上常用数据格式的模块。

* Menu:

* email: email --- 电子邮件与 MIME 处理包. 电子邮件与 MIME 处理包
* json: json --- JSON 编码和解码器. JSON 编码和解码器
* mailcap: mailcap --- Mailcap 文件处理. Mailcap 文件处理
* mailbox: mailbox --- 操作多种格式的邮箱. 操作多种格式的邮箱
* mimetypes: mimetypes --- 映射文件夹到 MIME 类型. 映射文件夹到 MIME 类型
* base64: base64 --- Base16 Base32 Base64 Base85 数据编码. Base16, Base32, Base64, Base85 数据编码
* binhex: binhex --- 对binhex4文件进行编码和解码. 对binhex4文件进行编码和解码
* binascii: binascii --- 二进制和 ASCII 码互转. 二进制和 ASCII 码互转
* quopri: quopri --- 编码与解码经过 MIME 转码的可打印数据. 编码与解码经过 MIME 转码的可打印数据
* uu: uu --- 对 uuencode 文件进行编码与解码. 对 uuencode 文件进行编码与解码


File: python.info,  Node: email --- 电子邮件与 MIME 处理包,  Next: json --- JSON 编码和解码器,  Up: 互联网数据处理

5.19.1 ‘email’ — 电子邮件与 MIME 处理包
---------------------------------------

`源码:' Lib/email/__init__.py(1)

__________________________________________________________________

*note email: 69. 包是一个用于管理电子邮件消息的库。 它 `并非' 被设计为执
行向 SMTP ( RFC 2821(2)), NNTP 或其他服务器发送电子邮件消息的操作；这些
是 *note smtplib: ee. 和 *note nntplib: c1. 等模块的功能。 *note email:
69. 包试图尽可能地遵循 RFC，支持 RFC 5322(3) 和 RFC 6532(4)，以及与 MIME
相关的各个 RFC 例如 RFC 2045(5), RFC 2046(6), RFC 2047(7), RFC 2183(8) 和
RFC 2231(9)。

email 包的总体结构可以分为三个主要部分，另外还有第四个部分用于控制其他部
分的行为。

这个包的中心组件是代表电子邮件消息的“对象模型”。 应用程序主要通过在
*note message: 72. 子模块中定义的对象模型接口与这个包进行交互。 应用程序
可以使用此 API 来询问有关现有电子邮件的问题、构造新的电子邮件，或者添加
或移除自身也使用相同对象模型接口的电子邮件子组件。 也就是说，遵循电子邮
件消息及其 MIME 子组件的性质，电子邮件对象模型是所有提供 *note
EmailMessage: 54b. API 的对象所构成的树状结构。

这个包的另外两个主要组件是 *note parser: 74. 和 *note generator: 6e.。
parser 接受电子邮件消息的序列化版本（字节流）并将其转换为 *note
EmailMessage: 54b. 对象树。 generator 接受 *note EmailMessage: 54b. 并将
其转回序列化的字节流。 (parser 和 generator 还能处理文本字符流，但不建议
这种用法，因为这很容易导致某种形式的无效消息。

控制组件是 *note policy: 75. 模块。 每一个 *note EmailMessage: 54b.、每
一个 *note generator: 6e. 和每一个 *note parser: 74. 都有一个相关联的
*note policy: 75. 对象来控制其行为。 通常应用程序只有在 *note
EmailMessage: 54b. 被创建时才需要指明控制策略，或者通过直接实例代 *note
EmailMessage: 54b. 来新建电子邮件，或者通过使用 *note parser: 74. 来解析
输入流。 但是策略也可以在使用 *note generator: 6e. 序列化消息时被更改。
例如，这允许从磁盘解析通用电子邮件消息，而在将消息发送到电子邮件服务器时
使用标准 SMTP 设置对其进行序列化。

email 包会尽量地对应用程序隐藏各种控制类 RFC 的细节。 从概念上讲应用程序
应当能够将电子邮件消息视为 Unicode 文本和二进制附件的结构化树，而不必担
心在序列化时要如何表示它们。 但在实际中，经常有必要至少了解一部分控制类
MIME 消息及其结构的规划，特别是 MIME "内容类型" 的名称和性质以及它们是如
何标识多部分文档的。 在大多数情况下这些知识应当仅对于更复杂的应用程序来
说才是必需的，并且即便在那时它也应当仅是特定的高层级结构，而不是如何表示
这些结构的细节信息。 由于 MIME 内容类型被广泛应用于现代因特网软件（而非
只是电子邮件），因此这对许多程序员来说将是很熟悉的概念。

以下小节描述了 *note email: 69. 包的具体功能。 我们会从 *note message:
72. 对象模型开始，它是应用程序将要使用的主要接口，之后是 *note parser:
74. 和 *note generator: 6e. 组件。 然后我们会介绍 *note policy: 75. 控制
组件，它将完成对这个库的主要组件的处理。

接下来的三个小节会介绍这个包可能引发的异常以及 *note parser: 74. 可能检
测到的缺陷（即与 RFC 不相符）。 然后我们会介绍 *note headerregistry: 70.
和 *note contentmanager: 6b. 子组件，它们分别提供了用于更精细地操纵标题
和载荷的工具。 这两个组件除了包含使用与生成非简单消息的相关特性，还记录
了它们的可扩展性 API，这将是高级应用程序所感兴趣的内容。

在此之后是一组使用之前小节所介绍的 API 的基本部分的示例。

前面的内容是 email 包的现代（对 Unicode 支持良好）API。 从 *note
Message: 54a. 类开始的其余小节则介绍了旧式 *note compat32: 549. API，它
会更直接地处理如何表示电子邮件消息的细节。 *note compat32: 549. API `不
会' 向应用程序隐藏 RFC 的相关细节，但对于需要进行此种层级操作的应用程序
来说将是很有用的工具。 此文档对于因向下兼容理由而仍然使用 *note
compat32: 549. API 的应用程序也是很适合的。

在 3.6 版更改: 文档经过重新组织和撰写以鼓励使用新的 *note EmailMessage:
54b./*note EmailPolicy: a00. API。

*note email: 69. 包文档的内容:

* Menu:

* email.message; 表示一封电子邮件信息: email message 表示一封电子邮件信息.
* email.parser; 解析电子邮件信息: email parser 解析电子邮件信息.
* email.generator; 生成 MIME 文档: email generator 生成 MIME 文档.
* email.policy; 策略对象: email policy 策略对象.
* email.errors; 异常和缺陷类: email errors 异常和缺陷类.
* email.headerregistry; 自定义标头对象: email headerregistry 自定义标头对象.
* email.contentmanager; 管理 MIME 内容: email contentmanager 管理 MIME 内容.
* email; 示例: email 示例.
* email.message.Message; 使用 compat32 API 来表示电子邮件消息: email message Message 使用 compat32 API 来表示电子邮件消息.
* email.mime; 从头创建电子邮件和 MIME 对象: email mime 从头创建电子邮件和 MIME 对象.
* email.header; 国际化标头: email header 国际化标头.
* email.charset; 表示字符集: email charset 表示字符集.
* email.encoders; 编码器: email encoders 编码器.
* email.utils; 其他工具: email utils 其他工具.
* email.iterators; 迭代器: email iterators 迭代器.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/email/__init__.py

   (2) https://tools.ietf.org/html/rfc2821.html

   (3) https://tools.ietf.org/html/rfc5322.html

   (4) https://tools.ietf.org/html/rfc6532.html

   (5) https://tools.ietf.org/html/rfc2045.html

   (6) https://tools.ietf.org/html/rfc2046.html

   (7) https://tools.ietf.org/html/rfc2047.html

   (8) https://tools.ietf.org/html/rfc2183.html

   (9) https://tools.ietf.org/html/rfc2231.html


File: python.info,  Node: email message 表示一封电子邮件信息,  Next: email parser 解析电子邮件信息,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.1 ‘email.message’: 表示一封电子邮件信息
..............................................

`源代码:' Lib/email/message.py(1)

__________________________________________________________________

3.6 新版功能: (2)

位于 *note email: 69. 包的中心的类就是 *note EmailMessage: 54b. 类。这个
类导入自 *note email.message: 72. 模块。它是 *note email: 69. 对象模型的
基类。*note EmailMessage: 54b. 为设置和查询头字段内容、访问信息体的内容
、以及创建和修改结构化信息提供了核心功能。

一份电子邮件信息由 `头' 和 `负载' （又被称为 `内容' ）组成。头遵循 RFC
5322(3) 或者 RFC 6532(4) 风格的字段名和值，字段名和字段值之间由一个冒号
隔开。这个冒号既不属于字段名，也不属于字段值。信息的负载可能是一段简单的
文字消息，也可能是一个二进制的对象，更可能是由多个拥有各自头和负载的子信
息组成的结构化子信息序列。对于后者类型的负载，信息的 MIME 类型将会被指明
为诸如 ‘multipart/*’ 或 ‘message/rfc822’ 的类型。

*note EmailMessage: 54b. 对象所提供的抽象概念模型是一个头字段组成的有序
字典加一个代表 RFC 5322(5) 标准的信息体的 `负载' 。负载有可能是一系列子
‘EmailMessage’ 对象的列表。你除了可以通过一般的字典方法来访问头字段名和
值，还可以使用特制方法来访问头的特定字段（比如说 MIME 内容类型字段）、操
纵负载、生成信息的序列化版本、递归遍历对象树。

*note EmailMessage: 54b. 的类字典接口的字典索引是头字段名，头字段名必须
是ASCII值。字典值是带有一些附加方法的字符串。虽然头字段的存储和获取都是
保留其原始大小写的，但是字段名的匹配是大小写不敏感的。与真正的字典不同，
键与键之间不但存在顺序关系，还可以重复。我们提供了额外的方法来处理含有重
复键的头。

`负载' 是多样的。对于简单的信息对象，它是字符串或字节对象；对于诸如
‘multipart/*’ 和 ‘message/rfc822’ 信息对象的 MIME 容器文档，它是一个
*note EmailMessage: 54b. 对象列表。

 -- 类: email.message.EmailMessage (policy=default)

     如果指定了 `policy' ，消息将由这个 `policy' 所指定的规则来更新和序
     列化信息的表达。如果没有指定 `policy' ，其将默认使用 *note default:
     27e4. 策略。这个策略遵循电子邮件的RFC标准，除了行终止符号（RFC要求
     使用 ‘\r\n’ ，此策略使用Python标准的 ‘\n’ 行终止符）。请前往 *note
     policy: 75. 的文档获取更多信息。

      -- 方法: as_string (unixfrom=False, maxheaderlen=None,
               policy=None)

          以一段扁平的字符串的形式返回整个信息对象。若可选的 `unixform'
          参数为真，返回的字符串会包含信封头。 `unixform' 的默认值是
          ‘False’ 。为了保持与基类 *note Message: 54a. 的兼容性，
          `maxheaderlen' 是被接受的，但是其默认值是 ‘None’ 。这个默认值
          表示行长度由策略的 ‘max_line_length’ 属性所控制。从信息实例所
          获取到的策略可以通过 `policy' 参数重写。这样可以对该方法所产生
          的输出进行略微的控制，因为指定的 `policy' 会被传递到 *note
          Generator: b54. 当中。

          扁平化信息可能会对 *note EmailMessage: 54b. 做出修改。这是因为
          为了完成向字符串的转换，一些内容需要使用默认值填入（举个例子，
          MIME 边界字段可能会被生成或被修改）。

          请注意，这个方法是为了便利而提供，不一定是适合你的应用程序的最
          理想的序列化信息的方法。这在你处理多封信息的时候尤甚。如果你需
          要使用更加灵活的API来序列化信息，请参见 *note
          email.generator.Generator: b54. 。同时请注意，当 *note utf8:
          6db. 属性为其默认值 ‘False’ 的时候，本方法将限制其行为为生成以
          “7 bit clean”方式序列化的信息。

          在 3.6 版更改: `maxheaderlen' 没有被指定时的默认行为从默认为
          0修改为默认为策略的 `max_line_length' 值。

      -- 方法: __str__ ()

          与 ‘as_string(policy=self.policy.clone(utf8=True))’ 等价。这将
          让 ‘str(msg)’ 产生的字符串包含人类可读的的序列化信息内容。

          在 3.4 版更改: 本方法开始使用 ‘utf8=True’ ，而非 *note
          as_string(): 27e5. 的直接替身。使用 ‘utf8=True’ 会产生类似于
          RFC 6531(6) 的信息表达。

      -- 方法: as_bytes (unixfrom=False, policy=None)

          以字节串对象的形式返回整个扁平化后的消息。 当可选的 `unixfrom'
          为真值时，返回的字符串会包含信封标头。 `unixfrom' 的默认值为
          ‘False’。 `policy' 参数可被用于重载从消息实例获取的默认
          policy。 这可被用来控制该方法所产生的部分格式效果，因为指定的
          `policy' 将被传递给 *note BytesGenerator: b55.。

          扁平化信息可能会对 *note EmailMessage: 54b. 做出修改。这是因为
          为了完成向字符串的转换，一些内容需要使用默认值填入（举个例子，
          MIME 边界字段可能会被生成或被修改）。

          请注意，这个方法是为了便利而提供，不一定是适合你的应用程序的最
          理想的序列化信息的方法。这在你处理多封信息的时候尤甚。如果你需
          要使用更加灵活的API来序列化信息，请参见 *note
          email.generator.BytesGenerator: b55. 。

      -- 方法: __bytes__ ()

          与 *note as_bytes(): 27e7. 等价。这将让 ‘bytes(msg)’ 产生一个
          包含序列化信息内容的字节序列对象。

      -- 方法: is_multipart ()

          如果该信息的负载是一个子 *note EmailMessage: 54b. 对象列表，返
          回 ‘True’ ；否则返回 ‘False’ 。在 *note is_multipart(): 27e9.
          返回 ‘True’ 的场合下，负载应当是一个字符串对象（有可能是一个使
          用了内容传输编码进行编码的二进制负载）。请注意， *note
          is_multipart(): 27e9. 返回 ‘True’ 不意味着
          ‘msg.get_content_maintype() == 'multipart'’ 也会返回 ‘True’ 。
          举个例子， ‘is_multipart’ 在 *note EmailMessage: 54b. 是
          ‘message/rfc822’ 类型的信息的情况下，其返回值也是 ‘True’ 。

      -- 方法: set_unixfrom (unixfrom)

          将信息的信封头设置为 `unixform' ，这应当是一个字符串。（在
          *note mboxMessage: 27eb. 中有关于这个头的一段简短介绍。）

      -- 方法: get_unixfrom ()

          返回消息的信封头。如果信封头从未被设置过，默认返回 ‘None’ 。

     以下方法实现了对信息的头字段进行访问的类映射接口。请留意，只是类映
     射接口，这与平常的映射接口（比如说字典映射）有一些语义上的不同。举
     个例子，在一个字典当中，键之间不可重复，但是信息头字段是可以重复的
     。不光如此，在字典当中调用 *note keys(): 27ed. 方法返回的结果，其顺
     序没有保证；但是在一个 *note EmailMessage: 54b. 对象当中，返回的头
     字段永远以其在原信息当中出现的顺序，或以其加入信息的顺序为序。任何
     删了后又重新加回去的头字段总是添加在当时列表的末尾。

     这些语义上的不同是刻意而为之的，是出于在绝大多数常见使用情景中都方
     便的初衷下设计的。

     还请留意，无论在什么情况下，消息当中的任何信封头字段都不会包含在映
     射接口当中。

      -- 方法: __len__ ()

          返回头字段的总数，重复的也计算在内。

      -- 方法: __contains__ (name)

          如果消息对象中有一个名为 `name' 的字段，其返回值为 ‘True’ 。匹
          配无视大小写差异， `name' 也不包含末尾的的冒号。 ‘in’ 操作符的
          实现中用到了这个方法，比如说：

               if 'message-id' in myMessage:
                  print('Message-ID:', myMessage['message-id'])

      -- 方法: __getitem__ (name)

          返回头字段名对应的字段值。 `name' 不含冒号分隔符。如果字段未找
          到，返回 ‘None’ 。 *note KeyError: 2c8. 异常永不抛出。

          请注意，如果对应名字的字段找到了多个，具体返回哪个字段值是未定
          义的。请使用 *note get_all(): 27f1. 方法获取匹配字段名的所有字
          段值。

          使用标准策略（非 ‘compat32’）时，返回值是 *note
          email.headerregistry.BaseHeader: 27f2. 的某个子类的一个实例。

      -- 方法: __setitem__ (name, val)

          在信息头中添加名为 `name' 值为 `val' 的字段。这个字段会被添加
          在已有字段列表的结尾处。

          请注意，这个方法 `既不会' 覆盖 `也不会' 删除任何字段名重名的已
          有字段。如果你确实想保证新字段是整个信息头当中唯一拥有 `name'
          字段名的字段，你需要先把旧字段删除。例如：

               del msg['subject']
               msg['subject'] = 'Python roolz!'

          如果 ‘policy’ 明确要求某些字段是唯一的（至少标准策略就有这么做
          ），对这些字段在已有同名字段的情况下仍然尝试为字段名赋值会引发
          *note ValueError: 1fc. 异常。这是为了一致性而刻意设计出的行为
          ，不过我们随时可能会突然觉得“还是在这种情况下自动把旧字段删除
          比较好吧”而把这个行为改掉，所以不要以为这是特性而依赖这个行为
          。

      -- 方法: __delitem__ (name)

          删除信息头当中字段名匹配 `name' 的所有字段。如果匹配指定名称的
          字段没有找到，也不会抛出任何异常。

      -- 方法: keys ()

          以列表形式返回消息头中所有的字段名。

      -- 方法: values ()

          以列表形式返回消息头中所有的字段值。

      -- 方法: items ()

          以二元元组的列表形式返回消息头中所有的字段名和字段值。

      -- 方法: get (name, failobj=None)

          返回对应字段名的字段值。这个方法与 *note __getitem__(): 27f0.
          是一样的，只不过如果对应字段名的字段没有找到，该方法会返回
          `failobj' 。这个参数是可选的（默认值为 ‘None’ ）。

     以下是一些与头有关的更多有用方法：

      -- 方法: get_all (name, failobj=None)

          返回字段名为 `name' 的所有字段值的列表。如果信息内不存在匹配的
          字段，返回 `failobj' （其默认值为 ‘None’ ）。

      -- 方法: add_header (_name, _value, **_params)

          高级头字段设定。这个方法与 *note __setitem__(): 27f3. 类似，不
          过你可以使用关键字参数为字段提供附加参数。 `_name' 是字段名，
          `_value' 是字段 `主' 值。

          对于关键字参数字典 `_params' 的每个键值对而言，它的键被用作参
          数的名字，其中下划线被替换为短横杠（毕竟短横杠不是合法的
          Python标识符）。一般来讲，参数以 ‘键="值"’ 的方式添加，除非值
          是 ‘None’ 。要真的是这样的话，只有键会被添加。

          如果值含有非ASCII字符，你可以将值写成 ‘(CHARSET, LANGUAGE,
          VALUE)’ 形式的三元组，这样你可以人为控制字符的字符集和语言。
          ‘CHARSET’ 是一个字符串，它为你的值的编码命名； ‘LANGUAGE’ 一般
          可以直接设为 ‘None’ ，也可以直接设为空字符串（其他可能取值参见
          :rfc‘2231‘ ）； ‘`VALUE’ 是一个字符串值，其包含非ASCII的码点。
          如果你没有使用三元组，你的字符串又含有非ASCII字符，那么它就会
          使用 RFC 2231(7) 中， ‘CHARSET’ 为 ‘utf-8’ ， ‘LANGUAGE’ 为
          ‘None’ 的格式编码。

          例如：

               msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')

          会添加一个形如下文的头字段：

               Content-Disposition: attachment; filename="bud.gif"

          带有非ASCII字符的拓展接口：

               msg.add_header('Content-Disposition', 'attachment',
                              filename=('iso-8859-1', '', 'Fußballer.ppt'))

      -- 方法: replace_header (_name, _value)

          替换头字段。只会替换掉信息内找到的第一个字段名匹配 `_name' 的
          字段值。字段的顺序不变，原字段名的大小写也不变。如果没有找到匹
          配的字段，抛出 *note KeyError: 2c8. 异常。

      -- 方法: get_content_type ()

          返回信息的内容类型，其形如 ‘maintype/subtype’ ，强制全小写。如
          果信息的 ‘Content-Type’ 头字段不存在则返回 *note
          get_default_type(): 27fb. 的返回值；如果信息的 ‘Content-Type’
          头字段无效则返回 ‘text/plain’ 。

          （根据 RFC 2045(8) 所述，信息永远都有一个默认类型，所以 *note
          get_content_type(): 27fa. 一定会返回一个值。 RFC 2045(9) 定义
          信息的默认类型为 ‘text/plain’ 或 ‘message/rfc822’ ，其中后者仅
          出现在消息头位于一个 ‘multipart/digest’ 容器中的场合中。如果消
          息头的 ‘Content-Type’ 字段所指定的类型是无效的， RFC 2045(10)
          令其默认类型为 ‘text/plain’ 。）

      -- 方法: get_content_maintype ()

          返回信息的主要内容类型。准确来说，此方法返回的是 *note
          get_content_type(): 27fa. 方法所返回的形如 ‘maintype/subtype’
          的字符串当中的 ‘maintype’ 部分。

      -- 方法: get_content_subtype ()

          返回信息的子内容类型。准确来说，此方法返回的是 *note
          get_content_type(): 27fa. 方法所返回的形如 ‘maintype/subtype’
          的字符串当中的 ‘subtype’ 部分。

      -- 方法: get_default_type ()

          返回默认的内容类型。绝大多数的信息，其默认内容类型都是
          ‘text/plain’ 。作为 ‘multipart/digest’ 容器内子部分的信息除外
          ，它们的默认内容类型是 ‘message/rfc822’ 。

      -- 方法: set_default_type (ctype)

          设置默认的内容类型。 尽管并非强制，但是 `ctype' 仍应当是
          ‘text/plain’ 或 ‘message/rfc822’ 二者取一。默认内容类型并不存
          储在 ‘Content-Type’ 头字段当中，所以设置此项的唯一作用就是决定
          当 ‘Content-Type’ 头字段在信息中不存在时，‘get_content_type’ 方
          法的返回值。

      -- 方法: set_param (param, value, header='Content-Type',
               requote=True, charset=None, language='', replace=False)

          在 ‘Content-Type’ 头字段当中设置一个参数。如果该参数已于字段中
          存在，将其旧值替换为 `value' 。如果 `header' 是 ‘Content-Type’
          （默认值），并且该头字段于信息中尚未存在，则会先添加该字段，将
          其值设置为 ‘text/plain’ ，并附加参数值。可选的 `header' 可以让
          你指定 ‘Content-Type’ 之外的另一个头字段。

          如果值包含非ASCII字符，其字符集和语言可以通过可选参数
          `charset' 和 `language' 显式指定。可选参数 `language' 指定 RFC
          2231(11) 当中的语言，其默认值是空字符串。 `charset' 和
          `language' 都应当字符串。默认使用的是 ‘utf8’ `charset' ，
          `language' 为 ‘None’ 。

          如果 `replace' 为 ‘False’ （默认值），该头字段会被移动到所有头
          字段的末尾。如果 `replace' 为 ‘True’ ，字段会被原地更新。

          于 *note EmailMessage: 54b. 对象而言， `requote' 参数已被弃用
          。

          请注意，头字段已有的参数值可以通过头字段的 ‘params’ 属性来访问
          （举例： ‘msg['Content-Type'].params['charset']’ ）。

          在 3.4 版更改: 添加了 ‘replace’ 关键字。

      -- 方法: del_param (param, header='content-type', requote=True)

          从 ‘Content-Type’ 头字段中完全移去给定的参数。头字段会被原地重
          写，重写后的字段不含参数和值。可选的 `header' 可以让你指定
          ‘Content-Type’ 之外的另一个字段。

          于 *note EmailMessage: 54b. 对象而言， `requote' 参数已被弃用
          。

      -- 方法: get_filename (failobj=None)

          返回信息头当中 ‘Content-Disposition’ 字段当中名为 ‘filename’ 的
          参数值。如果该字段当中没有此参数，该方法会退而寻找
          ‘Content-Type’ 字段当中的 ‘name’ 参数值。如果这个也没有找到，
          或者这些个字段压根就不存在，返回 `failobj' 。返回的字符串永远
          按照 *note email.utils.unquote(): 2802. 方法去除引号。

      -- 方法: get_boundary (failobj=None)

          返回信息头当中 ‘Content-Type’ 字段当中名为 ‘boundary’ 的参数值
          。如果字段当中没有此参数，或者这些个字段压根就不存在，返回
          `failobj' 。返回的字符串永远按照 *note email.utils.unquote():
          2802. 方法去除引号。

      -- 方法: set_boundary (boundary)

          将 ‘Content-Type’ 头字段的 ‘boundary’ 参数设置为 `boundary' 。
          *note set_boundary(): 2804. 方法永远都会在必要的时候为
          `boundary' 添加引号。如果信息对象中没有 ‘Content-Type’ 头字段
          ，抛出 *note HeaderParseError: 2805. 异常。

          请注意使用这个方法与直接删除旧的 ‘Content-Type’ 头字段然后使用
          *note add_header(): 27f8. 方法添加一个带有新边界值参数的
          ‘Content-Type’ 头字段有细微差距。 *note set_boundary(): 2804.
          方法会保留 ‘Content-Type’ 头字段在原信息头当中的位置。

      -- 方法: get_content_charset (failobj=None)

          返回 ‘Content-Type’ 头字段中的 ‘charset’ 参数，强制小写。如果
          字段当中没有此参数，或者这个字段压根不存在，返回 `failobj' 。

      -- 方法: get_charsets (failobj=None)

          返回一个包含了信息内所有字符集名字的列表。如果信息是
          ‘multipart’ 类型的，那么列表当中的每一项都对应其负载的子部分的
          字符集名字。否则，该列表是一个长度为1的列表。

          列表当中的每一项都是一个字符串，其值为对应子部分的
          ‘Content-Type’ 头字段的 ‘charset’ 参数值。如果该子部分没有此头
          字段，或者没有此参数，或者其主要 MIME 类型并非 ‘text’ ，那么列
          表中的那一项即为 `failobj' 。

      -- 方法: is_attachment ()

          如果信息头当中存在一个名为 ‘Content-Disposition’ 的字段，且该
          字段的值为 ‘attachment’ （大小写无关），返回 ‘True’ 。否则，返
          回 ‘False’ 。

          在 3.4.2 版更改: 为了与 *note is_multipart(): 2809. 方法一致，
          is_attachment 现在是一个方法，不再是属性了。

      -- 方法: get_content_disposition ()

          如果信息的 ‘Content-Disposition’ 头字段存在，返回其字段值；否
          则返回 ‘None’ 。返回的值均为小写，不包含参数。如果信息遵循 RFC
          2183(12) 标准，则返回值只可能在 `inline' 、 `attachment' 和
          ‘None’ 之间选择。

          3.5 新版功能.

     下列方法与信息内容（负载）之访问与操控有关。

      -- 方法: walk ()

          *note walk(): 280b. 方法是一个多功能生成器。它可以被用来以深度
          优先顺序遍历信息对象树的所有部分和子部分。一般而言， *note
          walk(): 280b. 会被用作 ‘for’ 循环的迭代器，每一次迭代都返回其
          下一个子部分。

          以下例子会打印出一封具有多部分结构之信息的每个部分的 MIME 类型
          。

               >>> for part in msg.walk():
               ...     print(part.get_content_type())
               multipart/report
               text/plain
               message/delivery-status
               text/plain
               text/plain
               message/rfc822
               text/plain

          ‘walk’ 会遍历所有 *note is_multipart(): 27e9. 方法返回 ‘True’
          的部分之子部分，哪怕 ‘msg.get_content_maintype() ==
          'multipart'’ 返回的是 ‘False’ 。使用 ‘_structure’ 除错帮助函数
          可以帮助我们在下面这个例子当中看清楚这一点：

               >>> from email.iterators import _structure
               >>> for part in msg.walk():
               ...     print(part.get_content_maintype() == 'multipart',
               ...           part.is_multipart())
               True True
               False False
               False True
               False False
               False False
               False True
               False False
               >>> _structure(msg)
               multipart/report
                   text/plain
                   message/delivery-status
                       text/plain
                       text/plain
                   message/rfc822
                       text/plain

          在这里， ‘message’ 的部分并非 ‘multiparts’ ，但是它们真的包含
          子部分！ ‘is_multipart()’ 返回 ‘True’ ， ‘walk’ 也深入进这些子
          部分中。

      -- 方法: get_body (preferencelist=('related', 'html', 'plain'))

          返回信息的 MIME 部分。这个部分是最可能成为信息体的部分。

          `preferencelist' 必须是一个字符串序列，其内容从 ‘related’ 、
          ‘html’ 和 ‘plain’ 这三者组成的集合中选取。这个序列代表着返回的
          部分的内容类型之偏好。

          在 ‘get_body’ 方法被调用的对象上寻找匹配的候选者。

          如果 ‘related’ 未包括在 `preferencelist' 中，可考虑将所遇到的
          任意相关的根部分（或根部分的子部分）在该（子）部分与一个首选项
          相匹配时作为候选项。

          当遇到一个 ‘multipart/related’ 时，将检查 ‘start’ 形参并且如果
          找到了一个匹配 ‘Content-ID’ 的部分，在查找候选匹配时只考虑它。
          在其他情况下则只考虑 ‘multipart/related’ 的第一个（默认的根）
          部分。

          如果一个部分具有 ‘Content-Disposition’ 标头，则当标头值为
          ‘inline’ 时将只考虑将该部分作为候选匹配。

          如果没有任何候选部分匹配 `preferencelist' 中的任何首选项，则返
          回 ‘None’。

          注: (1) 对于大多数应用来说有意义的 `preferencelist' 组合仅有
          ‘('plain',)’, ‘('html', 'plain')’ 以及默认的 ‘('related',
          'html', 'plain')’。 (2) 由于匹配是从调用 ‘get_body’ 的对象开始
          的，因此在 ‘multipart/related’ 上调用 ‘get_body’ 将返回对象本
          身，除非 `preferencelist' 具有非默认值。 (3) 未指定
          ‘Content-Type’ 或者 ‘Content-Type’ 标头无效的消息（或消息部分
          ）将被当作具有 ‘text/plain’ 类型来处理，这有时可能导致
          ‘get_body’ 返回非预期的结果。

      -- 方法: iter_attachments ()

          返回包含所有不是候选 "body" 部分的消息的直接子部分的迭代器。 也
          就是说，跳过首次出现的每个 ‘text/plain’, ‘text/html’,
          ‘multipart/related’ 或 ‘multipart/alternative’ (除非通过
          ‘Content-Disposition: attachment’ 将它们显式地标记为附件)，并
          返回所有的其余部分。 当直接应用于 ‘multipart/related’ 时，将返
          回包含除根部分之外所有相关部分的迭代器（即由 ‘start’ 形参所指
          向的部分，或者当没有 ‘start’ 形参或 ‘start’ 形参不能匹配任何部
          分的 ‘Content-ID’ 时则为第一部分）。 当直接应用于
          ‘multipart/alternative’ 或非 ‘multipart’ 时，将返回一个空迭代
          器。

      -- 方法: iter_parts ()

          返回包含消息的所有直接子部分的迭代器，对于非 ‘multipart’ 将为
          空对象。 （另请参阅 *note walk(): 280b.。）

      -- 方法: get_content (*args, content_manager=None, **kw)

          调用 `content_manager' 的 *note get_content(): 2810. 方法，将
          自身作为消息对象传入，并将其他参数或关键字作为额外参数传入。 如
          果未指定 `content_manager'，则会使用当前 *note policy: 75. 所
          指定的 ‘content_manager’。

      -- 方法: set_content (*args, content_manager=None, **kw)

          调用 `content_manager' 的 *note set_content(): 2812. 方法，将
          自身作为消息传入，并将其他参数或关键字作为额外参数传入。 如果
          未指定 `content_manager'，则会使用当前 *note policy: 75. 所指
          定的 ‘content_manager’。

      -- 方法: make_related (boundary=None)

          将非 ‘multipart’ 消息转换为 ‘multipart/related’ 消息，将任何现
          有的 ‘Content-’ 标头和载荷移入 ‘multipart’ 的（新加）首部分。
          如果指定了 `boundary'，会用它作为 multipart 中的分界字符串，否
          则会在必要时自动创建分界（例如当消息被序列化时）。

      -- 方法: make_alternative (boundary=None)

          将非 ‘multipart’ 或 ‘multipart/related’ 转换为
          ‘multipart/alternative’，将任何现有的 ‘Content-’ 标头和载荷移
          入 ‘multipart’ 的（新加）首部分。 如果指定了 `boundary'，会用
          它作为 multipart 中的分界字符串，否则会在必要时自动创建分界（
          例如当消息被序列化时）。

      -- 方法: make_mixed (boundary=None)

          将非 ‘multipart’, ‘multipart/related’ 或
          ‘multipart-alternative’ 转换为 ‘multipart/mixed’，将任何现有的
          ‘Content-’ 标头和载荷移入 ‘multipart’ 的（新加）首部分。 如果
          指定了 `boundary'，会用它作为 multipart 中的分界字符串，否则会
          在必要时自动创建分界（例如当消息被序列化时）。

      -- 方法: add_related (*args, content_manager=None, **kw)

          如果消息为 ‘multipart/related’，则创建一个新的消息对象，将所有
          参数传给其 *note set_content(): 2811. 方法，并将其 *note
          attach(): 2817. 到 ‘multipart’。 如果消息为非 ‘multipart’，则
          先调用 *note make_related(): 2813. 然后再继续上述步骤。 如果消
          息为任何其他类型的 ‘multipart’，则会引发 *note TypeError:
          193.。 如果未指定 `content_manager'，则使用当前 *note policy:
          75. 所指定的 ‘content_manager’。 如果添加的部分没有
          ‘Content-Disposition’ 标头，则会添加一个值为 ‘inline’ 的标头。

      -- 方法: add_alternative (*args, content_manager=None, **kw)

          如果消息为 ‘multipart/alternative’，则创建一个新的消息对象，将
          所有参数传给其 *note set_content(): 2811. 方法，并将其 *note
          attach(): 2817. 到 ‘multipart’。 如果消息为非 ‘multipart’ 或
          ‘multipart/related’，则先调用 *note make_alternative(): 2814.
          然后再继续上述步骤。 如果消息为任何其他类型的 ‘multipart’，则
          会引发 *note TypeError: 193.。 如果未指定 `content_manager'，
          则会使用当前 *note policy: 75. 所指定的 ‘content_manager’。

      -- 方法: add_attachment (*args, content_manager=None, **kw)

          如果消息为 ‘multipart/mixed’，则创建一个新的消息对象，将所有参
          数传给其 *note set_content(): 2811. 方法，并将其 *note
          attach(): 2817. 到 ‘multipart’。 如果消息为非 ‘multipart’,
          ‘multipart/related’ 或 ‘multipart/alternative’，则先调用 *note
          make_mixed(): 2815. 然后再继续上述步骤。 如果未指定
          `content_manager'，则使用当前 *note policy: 75. 所指定的
          ‘content_manager’。 如果添加的部分没有 ‘Content-Disposition’ 标
          头，则会添加一个值为 ‘attachment’ 的标头。 此方法对于显式附件
          (‘Content-Disposition: attachment’) 和 ‘inline’ 附件
          (‘Content-Disposition: inline’) 均可使用，只须向
          ‘content_manager’ 传入适当的选项即可。

      -- 方法: clear ()

          移除所有载荷和所有标头。

      -- 方法: clear_content ()

          移除载荷以及所有 ‘Content-’ 标头，其他标头不加改变并且保持其原
          有顺序。

     *note EmailMessage: 54b. 对象具有下列实例属性:

      -- 属性: preamble

          MIME 文档格式在标头之后的空白行以及第一个多部分的分界字符串之
          间允许添加一些文本， 通常，此文本在支持 MIME 的邮件阅读器中永
          远不可见，因为它处在标准 MIME 防护范围之外。 但是，当查看消息
          的原始文本，或当在不支持 MIME 的阅读器中查看消息时，此文本会变
          得可见。

          `preamble' 属性包含 MIME 文档开头部分的这些处于保护范围之外的
          文本。 当 *note Parser: b20. 在标头之后及第一个分界字符串之前
          发现一些文本时，它会将这些文本赋值给消息的 `preamble' 属性。 当
          *note Generator: b54. 写出 MIME 消息的纯文本表示形式时，如果它
          发现消息具有 `preamble' 属性，它将在标头及第一个分界之间区域写
          出这些文本。 请参阅 *note email.parser: 74. 和 *note
          email.generator: 6e. 了解更多细节。

          请注意如果消息对象没有前导文本，则 `preamble' 属性将为 ‘None’。

      -- 属性: epilogue

          `epilogue' 属性的作用方式与 `preamble' 相同，区别在于它包含在
          最后一个分界及消息结尾之间出现的文本。 与 *note preamble:
          281c. 类似，如果没有附加文本，则此属性将为 ‘None’。

      -- 属性: defects

          `defects' 属性包含在解析消息时发现的所有问题的列表。 请参阅
          *note email.errors: 6d. 了解可能的解析缺陷的详细描述。

 -- 类: email.message.MIMEPart (policy=default)

     这个类代表 MIME 消息的子部分。 它与 *note EmailMessage: 54b. 相似，
     不同之处在于当 *note set_content(): 2811. 被调用时不会添加
     ‘MIME-Version’ 标头，因为子部分不需要有它们自己的 ‘MIME-Version’ 标
     头。

备注
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/email/message.py

   (2) (1) 原先在3.4版本中以 *note provisional module: 988. 添加。过时的
文档被移动至 *note email.message.Message; 使用 compat32 API
来表示电子邮件消息: 27e3. 。

   (3) https://tools.ietf.org/html/rfc5322.html

   (4) https://tools.ietf.org/html/rfc6532.html

   (5) https://tools.ietf.org/html/rfc5322.html

   (6) https://tools.ietf.org/html/rfc6531.html

   (7) https://tools.ietf.org/html/rfc2231.html

   (8) https://tools.ietf.org/html/rfc2045.html

   (9) https://tools.ietf.org/html/rfc2045.html

   (10) https://tools.ietf.org/html/rfc2045.html

   (11) https://tools.ietf.org/html/rfc2231.html

   (12) https://tools.ietf.org/html/rfc2183.html


File: python.info,  Node: email parser 解析电子邮件信息,  Next: email generator 生成 MIME 文档,  Prev: email message 表示一封电子邮件信息,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.2 ‘email.parser’: 解析电子邮件信息
.........................................

`源代码': Lib/email/parser.py(1)

__________________________________________________________________

使用以下两种方法的其中一种以创建消息对象结构：直接创建一个 *note
EmailMessage: 54b. 对象，使用字典接口添加消息头，并且使用 *note
set_content(): 2811. 和其他相关方法添加消息负载；或者通过解析一个电子邮
件消息的序列化表达来创建消息对象结构。

*note email: 69. 包提供了一个可以理解包含 MIME 文档在内的绝大多数电子邮
件文档结构的标准语法分析程序。 你可以传递给语法分析程序一个字节串、字符
串或者文件对象，语法分析程序会返回给你对应于该对象结构的根 *note
EmailMessage: 54b. 实例。 对于简单的、非 MIME 的消息，这个根对象的负载很
可能就是一个包含了该消息文字内容的字符串。 对于 MIME 消息，调用根对象的
*note is_multipart(): 27e9. 方法会返回 ‘True’，其子项可以通过负载操纵方
法来进行访问，例如 *note get_body(): 280c.、*note iter_parts(): 280e. 还
有 *note walk(): 280b.。

事实上你可以使用的语法分析程序接口有两种: *note Parser: b20. API 和增量
式的 *note FeedParser: 2821. API。当你的全部消息内容都在内存当中，或者整
个消息都保存在文件系统内的一个文件当中的时候，*note Parser: b20. API非常
有用。当你从可能会为了等待更多输入而阻塞的数据流当中读取消息（比如从套接
字当中读取电子邮件消息）的时候，*note FeedParser: 2821. 会更合适。*note
FeedParser: 2821. 会增量读取并解析消息，并且只有在你关闭语法分析程序的时
候才会返回根对象。

请注意，语法分析程序可以进行有限的拓展，你当然也可以完全从零开始实现你自
己的语法分析程序。将 *note email: 69. 包中内置的语法分析程序和 *note
EmailMessage: 54b. 类连接起来的所有逻辑代码都包含在 ‘policy’ 类当中，所
以如有必要，自定义的语法分析程序可以通过实现自定义的对应 ‘policy’ 方法来
创建对应的消息对象树。

* Menu:

* FeedParser API::
* Parser API::
* 附加说明::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/email/parser.py


File: python.info,  Node: FeedParser API,  Next: Parser API,  Up: email parser 解析电子邮件信息

5.19.1.3 FeedParser API
.......................

从 ‘email.feedparser’ 模块导入的 *note BytesFeedParser: b51. 类提供了一
个适合于增量解析电子邮件消息的API，比如说在从一个可能会阻塞（例如套接字
）的源当中读取消息文字的场合中它就会变得很有用。当然， *note
BytesFeedParser: b51. 也可以用来解析一个已经完整包含在一个 *note
bytes-like object: 5f1. 、字符串或文件内的电子邮件消息，但是在这些场合下
使用 *note BytesParser: b52. API可能会更加方便。这两个语法分析程序API的
语义和最终结果是一致的。

*note BytesFeedParser: b51. 的API十分简洁易懂：你创建一个语法分析程序的
实例，向它不断输入大量的字节直到尽头，然后关闭这个语法分析程序就可以拿到
根消息对象了。 在处理符合标准的消息的时候 *note BytesFeedParser: b51. 非
常准确；在处理不符合标准的消息的时候它做的也不差，但这视消息损坏的程度而
定。它会向消息对象的 *note defects: 281e. 属性中写入它从消息中找到的问题
列表。关于它能找到的所有问题类型的列表，详见 *note email.errors: 6d. 模
块。

这里是 *note BytesFeedParser: b51. 的 API：

 -- 类: email.parser.BytesFeedParser (_factory=None, *,
          policy=policy.compat32)

     创建一个 *note BytesFeedParser: b51. 实例。可选的 `_factory' 参数是
     一个不带参数的可调用对象；如果没有被指定，就会使用 `policy' 参数的
     *note message_factory: 548. 属性。 每当需要一个新的消息对象的时候，
     `_factory' 都会被调用。

     如果指定了 `policy' 参数，它就会使用这个参数所指定的规则来更新消息
     的表达方式。 如果没有设定 `policy' 参数，它就会使用 *note compat32:
     9fd. 策略。 这个策略维持了对 Python 3.2 版本的 email 包的后向兼容性
     ，并且使用 *note Message: 54a. 作为默认的工厂。 其他策略使用 *note
     EmailMessage: 54b. 作为默认的 `_factory'。 关于 `policy' 还会控制什
     么，参见 *note policy: 75. 的文档。

     注: `一定要指定policy关键字'。 在未来版本的 Python 当中，它的默认值
     会变成 *note email.policy.default: 27e4.。

     3.2 新版功能.

     在 3.3 版更改: 添加了*policy*关键字。

     在 3.6 版更改: `_factory' 默认为策略 ‘message_factory’。

      -- 方法: feed (data)

          向语法分析程序输入更多数据。`data' 应当是一个包含一行或多行内
          容的 *note bytes-like object: 5f1.。 行内容可以是不完整的，语
          法分析程序会妥善的将这些不完整的行缝合在一起。每一行可以使用以
          下三种常见的终止符号的其中一种：回车符、换行符或回车符加换行符
          （三者甚至可以混合使用）。

      -- 方法: close ()

          完成之前输入的所有数据的解析并返回根消息对象。 如果在这个方法
          被调用之后仍然调用 *note feed(): 2823. 方法，结果是未定义的。

 -- 类: email.parser.FeedParser (_factory=None, *,
          policy=policy.compat32)

     行为跟 *note BytesFeedParser: b51. 类一致，只不过向 *note feed():
     2823. 方法输入的内容必须是字符串。 它的实用性有限，因为这种消息只有
     在其只含有 ASCII 文字，或者 ‘utf8’ 被设置为 ‘True’ 且没有二进制格式
     的附件的时候，才会有效。

     在 3.3 版更改: 添加了*policy*关键字。


File: python.info,  Node: Parser API,  Next: 附加说明,  Prev: FeedParser API,  Up: email parser 解析电子邮件信息

5.19.1.4 Parser API
...................

*note BytesParser: b52. 类从 *note email.parser: 74. 模块导入，当消息的
完整内容包含在一个 *note bytes-like object: 5f1. 或文件中时它提供了可用
于解析消息的 API。 *note email.parser: 74. 模块还提供了 *note Parser:
b20. 用来解析字符串，以及只用来解析消息头的 *note BytesHeaderParser:
a04. 和 *note HeaderParser: a05.，如果你只对消息头感兴趣就可以使用后两者
。 在这种场合下 *note BytesHeaderParser: a04. 和 *note HeaderParser:
a05. 速度非常快，因为它们并不会尝试解析消息体，而是将载荷设为原始数据。

 -- 类: email.parser.BytesParser (_class=None, *,
          policy=policy.compat32)

     创建一个 *note BytesParser: b52. 实例。 `_class' 和 `policy' 参数在
     含义和语义上与 *note BytesFeedParser: b51. 的 `_factory' 和
     `policy' 参数一致。

     注: `一定要指定policy关键字'。 在未来版本的 Python 当中，它的默认值
     会变成 *note email.policy.default: 27e4.。

     在 3.3 版更改: 移除了在2.4版本中被弃用的*strict*参数。新增了
     *policy*关键字。

     在 3.6 版更改: `_class' 默认为策略 ‘message_factory’。

      -- 方法: parse (fp, headersonly=False)

          从二进制的类文件对象 `fp' 中读取全部数据、解析其字节内容、并返
          回消息对象。 `fp' 必须同时支持 *note readline(): 1713. 方法和
          ‘read()’ 方法。

          `fp' 内包含的字节内容必须是一块遵循 RFC 5322(1) （如果 ‘utf8’
          为 ‘True’，则为 RFC 6532(2) ）格式风格的消息头和消息头延续行，
          并可能紧跟一个信封头。 头块要么以数据结束，要么以一个空行为终
          止。 跟着头块的是消息体（消息体内可能包含 MIME 编码的子部分，
          这也包括 ‘Content-Transfer-Encoding’ 字段为 ‘8bit’ 的子部分）
          。

          可选的*headersonly*指示了是否应当在读取完消息头后就终止。默认
          值为‘‘False‘‘，意味着它会解析整个文件的全部内容。

      -- 方法: parsebytes (bytes, headersonly=False)

          与 *note parse(): 2826. 方法类似，只不过它要求输入为一个 *note
          bytes-like object: 5f1. 而不是类文件对象。于一个 *note
          bytes-like object: 5f1. 调用此方法相当于先将这些字节包装于一个
          *note BytesIO: 7a4. 实例中，然后调用 *note parse(): 2826. 方法
          。

          可选的 `headersonly' 与 *note parse(): 2826. 方法中的
          `headersonly' 是一致的。

     3.2 新版功能.

 -- 类: email.parser.BytesHeaderParser (_class=None, *,
          policy=policy.compat32)

     除了 `headersonly' 默认为 ‘True’，其他与 *note BytesParser: b52. 类
     完全一样。

     3.3 新版功能.

 -- 类: email.parser.Parser (_class=None, *, policy=policy.compat32)

     这个类与 *note BytesParser: b52. 一样，但是处理字符串输入。

     在 3.3 版更改: 移除了*strict*参数。添加了*policy*关键字。

     在 3.6 版更改: `_class' 默认为策略 ‘message_factory’。

      -- 方法: parse (fp, headersonly=False)

          从文本模式的文件类对象 `fp' 读取所有数据，解析所读取的文本，并
          返回根消息对象。 `fp' 必须同时支持文件类对象上的 *note
          readline(): 1c0e. 和 *note read(): 2015. 方法。

          除了文字模式的要求外，这个方法跟 *note BytesParser.parse():
          2826. 的运行方式一致。

      -- 方法: parsestr (text, headersonly=False)

          与 *note parse(): 2828. 方法类似，只不过它要求输入为一个字符串
          而不是类文件对象。 于一个字符串对象调用此方法相当于先将 `text'
          包装于一个 *note StringIO: 836. 实例中，然后调用 *note
          parse(): 2828. 方法。

          可选的 `headersonly' 与 *note parse(): 2828. 方法中的
          `headersonly' 是一致的。

 -- 类: email.parser.HeaderParser (_class=None, *,
          policy=policy.compat32)

     除了 `headersonly' 默认为 ‘True’，其他与 *note Parser: b20. 类完全
     一样。

考虑到从一个字符串或一个文件对象中创建一个消息对象是非常常见的任务，我们
提供了四个方便的函数。它们于顶层 *note email: 69. 包命名空间内可用。

 -- 函数: email.message_from_bytes (s, _class=None, *,
          policy=policy.compat32)

     从一个 *note bytes-like object: 5f1. 中返回消息对象。 这与
     ‘BytesParser().parsebytes(s)’ 等价。 可选的 `_class' 和 `policy' 参
     数与 *note BytesParser: b52. 类的构造函数的参数含义一致。

     3.2 新版功能.

     在 3.3 版更改: 移除了*strict*参数。添加了*policy*关键字。

 -- 函数: email.message_from_binary_file (fp, _class=None, *,
          policy=policy.compat32)

     从打开的二进制 *note file object: b4a. 中返回消息对象。 这与
     ‘BytesParser().parse(fp)’ 等价。 `_class' 和 `policy' 参数与 *note
     BytesParser: b52. 类的构造函数的参数含义一致。

     3.2 新版功能.

     在 3.3 版更改: 移除了*strict*参数。添加了*policy*关键字。

 -- 函数: email.message_from_string (s, _class=None, *,
          policy=policy.compat32)

     从一个字符串中返回消息对象。 这与 ‘Parser().parsestr(s)’ 等价。
     `_class' 和 `policy' 参数与 *note Parser: b20. 类的构造函数的参数含
     义一致。

     在 3.3 版更改: 移除了*strict*参数。添加了*policy*关键字。

 -- 函数: email.message_from_file (fp, _class=None, *,
          policy=policy.compat32)

     从一个打开的 *note file object: b4a. 中返回消息对象。 这与
     ‘Parser().parse(fp)’ 等价。 `_class' 和 `policy' 参数与 *note
     Parser: b20. 类的构造函数的参数含义一致。

     在 3.3 版更改: 移除了*strict*参数。添加了*policy*关键字。

     在 3.6 版更改: `_class' 默认为策略 ‘message_factory’。

这里是一个展示了你如何在Python交互式命令行中使用 *note
message_from_bytes(): b4f. 的例子：

     >>> import email
     >>> msg = email.message_from_bytes(myBytes)

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc5322.html

   (2) https://tools.ietf.org/html/rfc6532.html


File: python.info,  Node: 附加说明,  Prev: Parser API,  Up: email parser 解析电子邮件信息

5.19.1.5 附加说明
.................

在解析语义的时候请注意：

   * 大多数非 ‘multipart’ 类型的消息都会被解析为一个带有字符串负载的消息
     对象。这些对象在调用 *note is_multipart(): 27e9. 的时候会返回
     ‘‘False‘‘，调用 *note iter_parts(): 280e. 的时候会返回一个空列表。

   * 所有 ‘multipart’ 类型的消息都会被解析成一个容器消息对象。该对象的负
     载是一个子消息对象列表。外层的容器消息在调用 *note is_multipart():
     27e9. 的时候会返回‘‘True‘‘，在调用 *note iter_parts(): 280e. 的时候
     会产生一个子部分列表。

   * 大多数内容类型为 ‘message/*’ （例如 ‘message/delivery-status’ 和
     ‘message/rfc822’ ）的消息也会被解析为一个负载是长度为1的列表的容器
     对象。在它们身上调用 *note is_multipart(): 27e9. 方法会返回
     ‘‘True‘‘，调用 *note iter_parts(): 280e. 所产生的单个元素会是一个子
     消息对象。

   * 一些不遵循标准的消息在其内部关于它是否为 ‘multipart’ 类型前后不一。
     这些消息可能在消息头的 ‘Content-Type’ 字段中写明为 ‘multipart’ ，但
     它们的 *note is_multipart(): 27e9. 方法的返回值可能是‘‘False‘‘。如
     果这种消息被 *note FeedParser: 2821. 类解析，它们的*defects*属性列
     表当中会有一个 ‘MultipartInvariantViolationDefect’ 类的实例。关于更
     多信息，详见 *note email.errors: 6d. 。


File: python.info,  Node: email generator 生成 MIME 文档,  Next: email policy 策略对象,  Prev: email parser 解析电子邮件信息,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.6 ‘email.generator’: 生成 MIME 文档
..........................................

`源代码:' Lib/email/generator.py(1)

__________________________________________________________________

最普通的一种任务是生成由消息对象结构体表示的电子邮件消息的扁平（序列化）
版本。 如果你想通过 *note smtplib.SMTP.sendmail(): 74d. 或 *note
nntplib: c1. 模块来发送你的消息或是将消息打印到控制台就将需要这样做。 接
受一个消息对象结构体并生成其序列化表示就是这些生成器类的工作。

与 *note email.parser: 74. 模块一样，你并不会受限于已捆绑生成器的功能；
你可以自己从头写一个。 不过，已捆绑生成器知道如何以符合标准的方式来生成
大多数电子邮件，应该能够很好地处理 MIME 和非 MIME 电子邮件消息，并且被设
计为面向字节的解析和生成操作是互逆的，它假定两者都使用同样的非转换型
*note policy: 75.。 也就是说，通过 *note BytesParser: b52. 类来解析序列
化字节流然后再使用 *note BytesGenerator: b55. 来重新生成序列化字节流应当
得到与输入相同的结果 (2)。 （而另一方面，在由程序所构造的 *note
EmailMessage: 54b. 上使用生成器可能导致对默认填入的 *note EmailMessage:
54b. 对象的改变。。）

可以使用 *note Generator: b54. 类将消息扁平化为文本（而非二进制数据）的
序列化表示形式，但是由于 Unicode 无法直接表示二进制数据，因此消息有必要
被转换为仅包含 ASCII 字符的数据，这将使用标准电子邮件 RFC 内容传输编码格
式技术来编码电子邮件消息以便通过非 “8 比特位兼容”的信道来传输。

为了适应 SMIME 签名消息的可重现处理过程，*note Generator: b54. 禁用了针
对 ‘multipart/signed’ 类型的消息部分及所有子部分的标头折叠。

 -- 类: email.generator.BytesGenerator (outfp, mangle_from_=None,
          maxheaderlen=None, *, policy=None)

     返回一个 *note BytesGenerator: b55. 对象，该对象将把提供给 *note
     flatten(): 282f. 方法的任何消息或者提供给 *note write(): 2830. 方法
     的任何经过代理转义编码的文本写入到 *note file-like object: 1c7a.
     `outfp'。 `outfp' 必须支持接受二进制数据的 ‘write’ 方法。

     如果可选的 `mangle_from_' 为 ‘True’，则会将一个 ‘>’ 字符放到恰好以
     字符串 ‘"From "’ 打头，即开头文本为 ‘From’ 加一个空格的的行前面。
     `mangle_from_' 默认为 `policy' 的 *note mangle_from_: 6d9. 设置值
     (对于 *note compat32: 549. 策略为 ‘True’，对于所有其他策略则为
     ‘False’)。 `mangle_from_' 被设计为在当消息以 unix mbox 格式存储时使
     用 (参见 *note mailbox: af. 和 WHY THE CONTENT-LENGTH FORMAT IS
     BAD(3))。

     如果 `maxheaderlen' 不为 ‘None’，则重新折叠任何长于 `maxheaderlen'
     的标头行，或者如果为 ‘0’，则不重新包装任何标头。 如果
     `manheaderlen' 为 ‘None’ (默认值)，则根据 `policy' 设置包装标头和其
     他消息行。

     如果指定了 `policy'，则使用该策略来控制消息的生成。 如果 `policy' 为
     ‘None’ (默认值)，则使用与传递给 ‘flatten’ 的 *note Message: 54a. 或
     *note EmailMessage: 54b. 对象相关联的策略来控制消息的生成。 请参阅
     *note email.policy: 75. 了解有关 `policy' 所控制内容的详情。

     3.2 新版功能.

     在 3.3 版更改: 添加了*policy*关键字。

     在 3.6 版更改: `mangle_from_' 和 `maxheaderlen' 形参的默认行为是遵
     循策略。

      -- 方法: flatten (msg, unixfrom=False, linesep=None)

          将将以 `msg' 为根的消息对象结构体的文本表示形式打印到创建
          *note BytesGenerator: b55. 实例时指定的输出文件。

          如果 *note policy: 75. 选项 *note cte_type: 2831. 为 ‘8bit’ (默
          认值)，则会将未被修改的原始已解析消息中的任何标头拷贝到输出，
          其中会重新生成与原始数据相同的高比特位组字节数据，并保留具有它
          们的任何消息体部分的非 ASCII ‘Content-Transfer-Encoding’。 如
          果 ‘cte_type’ 为 ‘7bit’，则会根据需要使用兼容 ASCII 的
          ‘Content-Transfer-Encoding’ 来转换高比特位组字节数据。 也就是
          说，将具有非 ASCII ‘Content-Transfer-Encoding’
          (‘Content-Transfer-Encoding: 8bit’) 的部分转换为兼容 ASCII 的
          ‘Content-Transfer-Encoding’，并使用 MIME ‘unknown-8bit’ 字符集
          来编码标头中不符合 RFC 的非 ASCII 字节数据，以使其符合 RFC。

          如果 `unixfrom' 为 ‘True’，则会在根消息对象的第一个 RFC
          5322(4) 标头之前打印 Unix mailbox 格式 (参见 *note mailbox:
          af.) 所使用的封包标头分隔符。 如果根对象没有封包标头，则会创建
          一个标准标头。 默认值为 ‘False’。 请注意对于子部分来说，不会打
          印任何封包标头。

          如果 `linesep' 不为 ‘None’，则会将其用作扁平化消息的所有行之间
          的分隔符。 如果 `linesep' 为 ‘None’ (默认值)，则使用在
          `policy' 中指定的值。

      -- 方法: clone (fp)

          返回此Return an independent clone of this *note
          BytesGenerator: b55. 实例的独立克隆，具有完全相同的选项设置，
          而 `fp' 为新的 `outfp'。

      -- 方法: write (s)

          使用 ‘ASCII’ 编解码器和 ‘surrogateescape’ 错误处理程序编码
          `s'，并将其传递给传入到 *note BytesGenerator: b55. 的构造器的
          `outfp' 的 `write' 方法 。

作为一个便捷工具，*note EmailMessage: 54b. 提供了 *note as_bytes():
27e7. 和 ‘bytes(aMessage)’ (即 *note __bytes__(): 27e8.) 等方法，它们简
单地生成一个消息对象的序列化二进制表示形式。 更多细节请参阅 *note
email.message: 72.。

因为字符串无法表示二进制数据，*note Generator: b54. 类必须将任何消息中扁
平化的任何二进制数据转换为兼容 ASCII 的格式，具体将其转换为兼容 ASCII 的
‘Content-Transfer_Encoding’。 使用电子邮件 RFC 的术语，你可以将其视作
*note Generator: b54. 序列化为不 "支持 8 比特" 的 I/O 流。 换句话说，大
部分应用程序将需要使用 *note BytesGenerator: b55.，而非 *note Generator:
b54.。

 -- 类: email.generator.Generator (outfp, mangle_from_=None,
          maxheaderlen=None, *, policy=None)

     返回一个 *note Generator: b54.，它将把提供给 *note flatten(): 2833.
     方法的任何消息，或者提供给 *note write(): 2834. 方法的任何文本写入
     到 *note file-like object: 1c7a. `outfp'。 `outfp' 必须支持接受字符
     串数据的 ‘write’ 方法。

     如果可选的 `mangle_from_' 为 ‘True’，则会将一个 ‘>’ 字符放到恰好以
     字符串 ‘"From "’ 打头，即开头文本为 ‘From’ 加一个空格的的行前面。
     `mangle_from_' 默认为 `policy' 的 *note mangle_from_: 6d9. 设置值
     (对于 *note compat32: 549. 策略为 ‘True’，对于所有其他策略则为
     ‘False’)。 `mangle_from_' 被设计为在当消息以 unix mbox 格式存储时使
     用 (参见 *note mailbox: af. 和 WHY THE CONTENT-LENGTH FORMAT IS
     BAD(5))。

     如果 `maxheaderlen' 不为 ‘None’，则重新折叠任何长于 `maxheaderlen'
     的标头行，或者如果为 ‘0’，则不重新包装任何标头。 如果
     `manheaderlen' 为 ‘None’ (默认值)，则根据 `policy' 设置包装标头和其
     他消息行。

     如果指定了 `policy'，则使用该策略来控制消息的生成。 如果 `policy' 为
     ‘None’ (默认值)，则使用与传递给 ‘flatten’ 的 *note Message: 54a. 或
     *note EmailMessage: 54b. 对象相关联的策略来控制消息的生成。 请参阅
     *note email.policy: 75. 了解有关 `policy' 所控制内容的详情。

     在 3.3 版更改: 添加了*policy*关键字。

     在 3.6 版更改: `mangle_from_' 和 `maxheaderlen' 形参的默认行为是遵
     循策略。

      -- 方法: flatten (msg, unixfrom=False, linesep=None)

          将以 `msg' 为根的消息对象结构体的文本表示形式打印到当 *note
          Generator: b54. 实例被创建时所指定的输出文件。

          如果 *note policy: 75. 选项 *note cte_type: 2831. 为 ‘8bit’，
          则视同选项被设为 ‘7bit’ 来生成消息。 （这是必需的，因为字符串
          无法表示非 ASCII 字节数据。） 将使用兼容 ASCII 的
          ‘Content-Transfer-Encoding’ 按需转换任何具有高比特位组的字节数
          据。 也就是说，将具有非 ASCII ‘Content-Transfer-Encoding’
          (‘Content-Transfer-Encoding: 8bit’) 的部分转换为兼容 ASCII 的
          ‘Content-Transfer-Encoding’，并使用 MIME ‘unknown-8bit’ 字符集
          来编码标头中不符合 RFC 的非 ASCII 字节数据，以使其符合 RFC。

          如果 `unixfrom' 为 ‘True’，则会在根消息对象的第一个 RFC
          5322(6) 标头之前打印 Unix mailbox 格式 (参见 *note mailbox:
          af.) 所使用的封包标头分隔符。 如果根对象没有封包标头，则会创建
          一个标准标头。 默认值为 ‘False’。 请注意对于子部分来说，不会打
          印任何封包标头。

          如果 `linesep' 不为 ‘None’，则会将其用作扁平化消息的所有行之间
          的分隔符。 如果 `linesep' 为 ‘None’ (默认值)，则使用在
          `policy' 中指定的值。

          在 3.2 版更改: 添加了对重编码 ‘8bit’ 消息体的支持，以及
          `linesep' 参数。

      -- 方法: clone (fp)

          返回此 *note Generator: b54. 实例的独立克隆，具有完全相同的选
          项设置，而 `fp' 为新的 `outfp'。

      -- 方法: write (s)

          将 `s' 写入到传给 *note Generator: b54. 的构造器的 `outfp' 的
          `write' 方法。 这足够为 *note Generator: b54. 实际提供可用于
          *note print(): 88f. 函数的文件类 API。

作为一个便捷工具，*note EmailMessage: 54b. 提供了 *note as_string():
27e5. 和 ‘str(aMessage)’ (即 *note __str__(): 27e6.) 等方法，它们简单地
生成一个消息对象的已格式化字符串表示形式。 更多细节请参阅 *note
email.message: 72.。

*note email.generator: 6e. 模块还提供了一个派生类 *note
DecodedGenerator: 547.，它类似于 *note Generator: b54. 基类，不同之处在
于非 ‘text’ 部分不会被序列化，而是被表示为 基于模板并填写了有关该部分的
信息的字符串输出流的形式。

 -- 类: email.generator.DecodedGenerator (outfp, mangle_from_=None,
          maxheaderlen=None, fmt=None, *, policy=None)

     行为类似于 *note Generator: b54.，不同之处在于对传给 *note
     Generator.flatten(): 2833. 的消息的任何子部分，如果该子部分的主类型
     为 ‘text’，则打印该子部分的已解码载荷，而如果其主类型不为 ‘text’，
     则不直接打印它而是使用来自该部分的信息填入字符串 `fmt' 并将填写完成
     的字符串打印出来。

     要填入 `fmt'，则执行 ‘fmt % part_info’，其中 ‘part_info’ 是由下列键
     和值组成的字典:

        * ‘type’ – 非 ‘text’ 部分的完整 MIME 类型

        * ‘maintype’ – 非 ‘text’ 部分的主 MIME 类型

        * ‘subtype’ – 非 ‘text’ 部分的子 MIME 类型

        * ‘filename’ – 非 ‘text’ 部分的文件名

        * ‘description’ – 与非 ‘text’ 部分相关联的描述

        * ‘encoding’ – 非 ‘text’ 部分的内容转换编码格式

     如果 `fmt' 为 ‘None’，则使用下列默认 `fmt':

          "[忽略消息的非文本 (%(type)s) 部分，文件名 %(filename)s]"

     可选的 `_mangle_from_' 和 `maxheaderlen' 与 *note Generator: b54. 基
     类的相同。

备注
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/email/generator.py

   (2) (1) 此语句假定你使用了正确的 ‘unixfrom’ 设置，并且没有用于自动调
整的 ‘policy’ 设置调用（例如 ‘refold_source’ 必须为 ‘none’，这 `不是' 默
认值）。 这也不是 100% 为真，因为如果消息不遵循 RFC 标准则有时实际原始文
本的信息会在解析错误恢复时丢失。 它的目标是在可能的情况下修复这些后续边
缘情况。

   (3) https://www.jwz.org/doc/content-length.html

   (4) https://tools.ietf.org/html/rfc5322.html

   (5) https://www.jwz.org/doc/content-length.html

   (6) https://tools.ietf.org/html/rfc5322.html


File: python.info,  Node: email policy 策略对象,  Next: email errors 异常和缺陷类,  Prev: email generator 生成 MIME 文档,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.7 ‘email.policy’: 策略对象
.................................

3.3 新版功能.

`源代码:' Lib/email/policy.py(1)

__________________________________________________________________

*note email: 69. 的主要焦点是按照各种电子邮件和 MIME RFC 的描述来处理电
子邮件消息。 但是电子邮件消息的基本格式（一个由名称加冒号加值的标头字段
构成的区块，后面再加一个空白行和任意的‘消息体’）是在电子邮件领域以外也获
得应用的格式。 这些应用的规则有些与主要电子邮件 RFC 十分接近，有些则很不
相同。 即使是操作电子邮件，有时也可能需要打破严格的 RFC 规则，例如生成可
与某些并不遵循标准的电子邮件服务器互联的电子邮件，或者是实现希望应用某些
破坏标准的操作方式的扩展。

策略对象给予 email 包处理这些不同用例的灵活性。

*note Policy: 9fc. 对象封装了一组属性和方法用来在使用期间控制 email 包中
各个组件的行为。 *note Policy: 9fc. 实例可以被传给 email 包中的多个类和
方法以更改它们的默认行为。 可设置的值及其默认值如下所述。

在 email 包中的所有类会使用一个默认的策略。 对于所有 *note parser: 74. 类
及相关的便捷函数，还有对于 *note Message: 54a. 类来说，它是 *note
Compat32: 9fd. 策略，通过其对应的预定义实例 *note compat32: 549. 来使用
。 这个策略提供了与 Python3.3 版之前的 email 包的完全向下兼容性（在某些
情况下，也包括对缺陷的兼容性）。

传给 *note EmailMessage: 54b. 的 `policy' 关键字的默认值是 *note
EmailPolicy: a00. 策略，表示为其预定义的实例 *note default: 27e4.。

在创建 *note Message: 54a. 或 *note EmailMessage: 54b. 对象时，它需要一
个策略。 如果消息是由 *note parser: 74. 创建的，则传给该解析器的策略将是
它所创建的消息所使用的策略。 如果消息是由程序创建的，则该策略可以在创建
它的时候指定。 当消息被传递给 *note generator: 6e. 时，生成器默认会使用
来自该消息的策略，但你也可以将指定的策略传递给生成器，这将覆盖存储在消息
对象上的策略。

*note email.parser: 74. 类和解析器便捷函数的 `policy' 关键字的默认值在未
来的 Python 版本中 `将会改变'。 因此在调用任何 *note parser: 74. 模块所
描述的类和函数时你应当 `总是显式地指定你想要使用的策略'。

本文档的第一部分介绍了 *note Policy: 9fc. 的特性，它是一个 *note
abstract base class: b3b.，定义了所有策略对象包括 *note compat32: 549. 的
共有特性。 这些特性包括一些由 email 包内部调用的特定钩子方法，自定义策略
可以重载这些方法以获得不同行为。 第二部分描述了实体类 *note EmailPolicy:
a00. 和 *note Compat32: 9fd.，它们分别实现了提供标准行为和向下兼容行为与
特性的钩子。

*note Policy: 9fc. 实例是不可变的，但它们可以被克隆，接受与类构造器一致
的关键字参数并返回一个新的 *note Policy: 9fc. 实例，新实例是原实例的副本
，但具有被改变的指定属性。

例如，以下代码可以被用来从一个 Unix 系统的磁盘文件中读取电子邮件消息并将
其传递给系统的 ‘sendmail’ 程序:

     >>> from email import message_from_binary_file
     >>> from email.generator import BytesGenerator
     >>> from email import policy
     >>> from subprocess import Popen, PIPE
     >>> with open('mymsg.txt', 'rb') as f:
     ...     msg = message_from_binary_file(f, policy=policy.default)
     >>> p = Popen(['sendmail', msg['To'].addresses[0]], stdin=PIPE)
     >>> g = BytesGenerator(p.stdin, policy=msg.policy.clone(linesep='\r\n'))
     >>> g.flatten(msg)
     >>> p.stdin.close()
     >>> rc = p.wait()

这里我们让 *note BytesGenerator: b55. 在创建要送入 ‘sendmail's’ ‘stdin’
的二进制字串时使用符合 RFC 的行分隔字符，默认的策略将会使用 ‘\n’ 行分隔
符。

某些 email 包的方法接受一个 `policy' 关键字参数，允许为该方法重载策略。
例如，以下代码使用了来自之前示例的 `msg' 对象的 *note as_bytes(): 849. 方
法并使用其运行所在平台的本机行分隔符将消息写入一个文件:

     >>> import os
     >>> with open('converted.txt', 'wb') as f:
     ...     f.write(msg.as_bytes(policy=msg.policy.clone(linesep=os.linesep)))
     17

Policy 对象也可使用附加运算符进行组合来产生一个新策略对象，其设置是被加
总对象的非默认值的组合:

     >>> compat_SMTP = policy.compat32.clone(linesep='\r\n')
     >>> compat_strict = policy.compat32.clone(raise_on_defect=True)
     >>> compat_strict_SMTP = compat_SMTP + compat_strict

此运算不满足交换律；也就是说对象的添加顺序很重要。 见以下演示:

     >>> policy100 = policy.compat32.clone(max_line_length=100)
     >>> policy80 = policy.compat32.clone(max_line_length=80)
     >>> apolicy = policy100 + policy80
     >>> apolicy.max_line_length
     80
     >>> apolicy = policy80 + policy100
     >>> apolicy.max_line_length
     100

 -- 类: email.policy.Policy (**kw)

     这是所有策略类的 *note abstract base class: b3b.。 它提供了一些简单
     方法的默认实现，以及不可变特征属性，*note clone(): 9fe. 方法以及构
     造器语义的实现。

     可以向策略类的构造器传入各种关键字参数。 可以指定的参数是该类的任何
     非方法特征属性，以及实体类的任何额外非方法特征属性。 在构造器中指定
     的值将覆盖相应属性的默认值。

     这个类定义了下列特征属性，因此下列值可以被传给任何策略类的构造器:

      -- 属性: max_line_length

          序列化输出中任何行的最大长度，不计入行字符的末尾。 默认值为
          78，基于 RFC 5322(2)。 值为 ‘0’ 或 *note None: 158. 表示完全没
          有行包装。

      -- 属性: linesep

          用来在序列化输出中确定行的字符串。 默认值为 ‘\n’ 因为这是
          Python 所使用的内部行结束符规范，但 RFC 的要求是 ‘\r\n’。

      -- 属性: cte_type

          控制可能要求使用的内容传输编码格式类型。 可能的值包括:

          ‘7bit’       所有数据必须为 "纯 7 比特位" (仅 ASCII)。 这意味着在必要情况下数
                       据将使用可打印引用形式或 base64 编码格式进行编码。
                       
                       
          ‘8bit’       数据不会被限制为纯 7 比特位。 标头中的数据仍要求仅 ASCII 因此将被
                       编码（参阅下文的 *note fold_binary(): 283a. 和 *note utf8: 6db. 了
                       解例外情况），但消息体部分可能使用 ‘8bit’ CTE。
                       

          ‘cte_type’ 值为 ‘8bit’ 仅适用于 ‘BytesGenerator’ 而非
          ‘Generator’，因为字符串不能包含二进制数据。 如果 ‘Generator’ 运
          行于指定了 ‘cte_type=8bit’ 的策略，它的行为将与 ‘cte_type’ 为
          ‘7bit’ 相同。

      -- 属性: raise_on_defect

          如为 *note True: 4a1.，则遇到的任何缺陷都将引发错误。 如为
          *note False: 390. (默认值)，则缺陷将被传递给 *note
          register_defect(): 283c. 方法。

      -- 属性: mangle_from_

          如为 *note True: 4a1.，则消息体中以 `"From "' 开头的行会通过在
          其前面放一个 ‘>’ 来进行转义。 当消息被生成器执行序列化时会使用
          此形参。 默认值t: *note False: 390.。

          3.5 新版功能: `mangle_from_' 形参。

      -- 属性: message_factory

          用来构造新的空消息对象的工厂函数。 在构建消息时由解析器使用。
          默认为 ‘None’，在此情况下会使用 *note Message: 54a.。

          3.6 新版功能.

     下列 *note Policy: 9fc. 方法是由使用 email 库的代码来调用以创建具有
     自室外设置的策略实例:

      -- 方法: clone (**kw)

          返回一个新的 *note Policy: 9fc. 实例，其属性与当前实例具有相同
          的值，除非是那些由关键字参数给出了新值的属性。

     其余的 *note Policy: 9fc. 方法是由 email 包代码来调用的，而不应当被
     使用 email 包的应用程序所调用。 自定义的策略必须实现所有这些方法。

      -- 方法: handle_defect (obj, defect)

          处理在 `obj' 上发现的 `defect'。 当 email 包调用此方法时，
          `defect' 将总是 ‘Defect’ 的一个子类。

          默认实现会检查 *note raise_on_defect: 283b. 旗标。 如果其为
          ‘True’，则 `defect' 会被作为异常来引发。 如果其为 ‘False’ (默
          认值)，则 `obj' 和 `defect' 会被传递给 *note
          register_defect(): 283c.。

      -- 方法: register_defect (obj, defect)

          在 `obj' 上注册一个 `defect'。 在 email 包中，`defect' 将总是
          ‘Defect’ 的一个子类。

          默认实现会调用 `obj' 的 ‘defects’ 属性的 ‘append’ 方法。 当
          email 包调用 *note handle_defect: 283d. 时，`obj' 通常将具有一
          个带 ‘append’ 方法的 ‘defects’ 属性。 配合 email 包使用的自定
          义对象类型（例如自定义的 ‘Message’ 对象）也应当提供这样的属性
          ，否则在被解析消息中的缺陷将引发非预期的错误。

      -- 方法: header_max_count (name)

          返回名为 `name' 的标头的最大允许数量。

          当添加一个标头到 *note EmailMessage: 54b. 或 *note Message:
          54a. 对象时被调用。 如果返回值不为 ‘0’ 或 ‘None’，并且已有的名
          称为 `name' 的标头数量大于等于所返回的值，则会引发 *note
          ValueError: 1fc.。

          由于 ‘Message.__setitem__’ 的默认行为是将值添加到标头列表，因
          此很容易不知情地创建重复的标头。 此方法允许在程序中限制可以被
          添加到 ‘Message’ 中的特定标头的实例数量。 （解析器不会考虑此限
          制，它将忠实地产生被解析消息中存在的任意数量的标头。）

          默认实现对于所有标头名称都返回 ‘None’。

      -- 方法: header_source_parse (sourcelines)

          email 包调用此方法时将传入一个字符串列表，其中每个字符串以在被
          解析源中找到的行分隔符结束。 第一行包括字段标头名称和分隔符。
          源中的所有空白符都会被保留。 此方法应当返回 ‘(name, value)’ 元
          组以保存至 ‘Message’ 中来代表被解析的标头。

          如果一个实现希望保持与现有 email 包策略的兼容性，则 `name' 应
          当为保留大小写形式的名称（所有字符直至 ’‘:’’ 分隔符），而
          `value' 应当为展开后的值（移除所有行分隔符，但空白符保持不变）
          ，并移除开头的空白符。

          `sourcelines' 可以包含经替代转义的二进制数据。

          此方法没有默认实现

      -- 方法: header_store_parse (name, value)

          当一个应用通过程序代码修改 ‘Message’ (而不是由解析器创建
          ‘Message’) 时，email 包会调用此方法时并附带应用程序所提供的名
          称和值。 此方法应当返回 ‘(name, value)’ 元组以保存至 ‘Message’
          中用来表示标头。

          如果一个实现希望保持与现有 email 包策略的兼容性，则 `name' 和
          `value' 应当为字符串或字符串的子类，它们不会修改在参数中传入的
          内容。

          此方法没有默认实现

      -- 方法: header_fetch_parse (name, value)

          当标头被应用程序所请求时，email 包会调用此方法并附带当前保存在
          ‘Message’ 中的 `name' 和 `value'，并且无论此方法返回什么它都会
          被回传给应用程序作为被提取标头的值。 请注意可能会有多个相同名
          称的标头被保存在 ‘Message’ 中；此方法会将指定标头的名称和值返
          回给应用程序。

          `value' 可能包含经替代转义的二进制数据。 此方法所返回的值应当
          没有经替代转义的二进制数据。

          此方法没有默认实现

      -- 方法: fold (name, value)

          email 包调用此方法时会附带当前保存在 ‘Message’ 中的给定标头的
          `name' 和 `value'。 此方法应当返回一个代表该标头的（根据策略设
          置）通过处理 `name' 和 `value' 并在适当位置插入 *note linesep:
          2839. 字符来正确地“折叠”的字符串。 请参阅 RFC 5322(3) 了解有关
          折叠电子邮件标头的规则的讨论。

          `value' 可能包含经替代转义的二进制数据。 此方法所返回的字符串
          应当没有经替代转义的二进制数据。

      -- 方法: fold_binary (name, value)

          与 *note fold(): 2842. 类似，不同之处在于返回的值应当为字节串
          对象而非字符串。

          `value' 可能包含经替代转义的二进制数据。 这些数据可以在被返回
          的字节串对象中被转换回二进制数据。

 -- 类: email.policy.EmailPolicy (**kw)

     这个实体 *note Policy: 9fc. 提供了完全遵循当前电子邮件 RFC 的行为。
     这包括 (但不限于) RFC 5322(4), RFC 2047(5) 以及当前的各种 MIME RFC。

     此策略添加了新的标头解析和折叠算法。 标头不是简单的字符串，而是带有
     依赖于字段类型的属性的 ‘str’ 的子类。 这个解析和折叠算法完整实现了
     RFC 2047(6) 和 RFC 5322(7)。

     *note message_factory: 548. 属性的默认值为 *note EmailMessage:
     54b.。

     除了上面列出的适用于所有策略的可设置属性，此策略还添加了下列额外属
     性:

     3.6 新版功能: (8)

      -- 属性: utf8

          如为 ‘False’，则遵循 RFC 5322(9)，通过编码为“已编码字”来支持标
          头中的非 ASCII 字符。 如为 ‘True’，则遵循 RFC 6532(10) 并对标
          头使用 ‘utf-8’ 编码格式。 以此方式格式化的消息可被传递给支持
          ‘SMTPUTF8’ 扩展 ( RFC 6531(11)) 的 SMTP 服务器。

      -- 属性: refold_source

          如果 ‘Message’ 对象中标头的值源自 *note parser: 74. (而非由程
          序设置)，此属性会表明当将消息转换回序列化形式时是否应当由生成
          器来重新折叠该值。 可能的值如下:

          ‘none’       所有源值使用原始折叠
                       
                       
          ‘long’       具有任何长度超过 ‘max_line_length’ 的行的源值将被折叠
                       
                       
          ‘all’        所有值会被重新折叠。
                       

          默认值为 ‘long’。

      -- 属性: header_factory

          该可调用对象接受两个参数，‘name’ 和 ‘value’，其中 ‘name’ 为标
          头字段名而 ‘value’ 为展开后的标头字段值，并返回一个表示该标头
          的字符串子类。 已提供的默认 ‘header_factory’ (参见 *note
          headerregistry: 70.) 支持对各种地址和日期 RFC 5322(12) 标头字
          段类型及主要 MIME 标头字段类型的自定义解析。 未来还将添加对其
          他自定义解析的支持。

      -- 属性: content_manager

          此对象至少有两个方法: get_content 和 set_content。 当一个
          *note EmailMessage: 54b. 对象的 *note get_content(): 280f. 或
          *note set_content(): 2811. 方法被调用时，它会调用此对象的相应
          方法，将消息对象作为其第一个参数，并将传给它的任何参数或关键字
          作为附加参数传入。 默认情况下 ‘content_manager’ 会被设为 *note
          raw_data_manager: 2845.。

          3.4 新版功能.

     这个类提供了下列对 *note Policy: 9fc. 的抽象方法的具体实现:

      -- 方法: header_max_count (name)

          返回用来表示具有给定名称的标头的专用类的 *note max_count:
          2847. 属性的值。

      -- 方法: header_source_parse (sourcelines)

          此名称会被作为到 ’‘:’’ 止的所有内容来解析。 该值是通过从第一行
          的剩余部分去除前导空格，再将所有后续行连接到一起，并去除所有末
          尾回车符或换行符来确定的。

      -- 方法: header_store_parse (name, value)

          name 将会被原样返回。 如果输入值具有 ‘name’ 属性并可在忽略大小
          写的情况下匹配 `name'，则 value 也会被原样返回。 在其他情况下
          `name' 和 `value' 会被传递给 ‘header_factory’，并将结果标头对
          象作为值返回。 在此情况下如果输入值包含 CR 或 LF 字符则会引发
          ‘ValueError’。

      -- 方法: header_fetch_parse (name, value)

          如果值具有 ‘name’ 属性，它会被原样返回。 在其他情况下 `name' 和
          移除了所有 CR 和 LF 字符的 `value' 会被传递给
          ‘header_factory’，并返回结果标头对象。 任何经替代转义的字节串
          会被转换为 unicode 未知字符字形。

      -- 方法: fold (name, value)

          标头折叠是由 *note refold_source: 2843. 策略设置来控制的。 当
          且仅当一个值没有 ‘name’ 属性（具有 ‘name’ 属性就意味着它是某种
          标头对象）它才会被当作是“源值”。 如果一个原值需要按照策略来重
          新折叠，则会通过将 `name' 和去除了所有 CR 和 LF 字符的 `value'
          传递给 ‘header_factory’ 来将其转换为标头对象。 标头对象的折叠
          是通过调用其 ‘fold’ 方法并附带当前策略来完成的。

          源值会使用 *note splitlines(): 1669. 来拆分成多行。 如果该值不
          被重新折叠，则会使用策略中的 ‘linesep’ 重新合并这些行并将其返
          回。 例外的是包含非 ascii 二进制数据的行。 在此情况下无论
          ‘refold_source’ 如何设置该值都会被重新折叠，这会导致二进制数据
          使用 ‘unknown-8bit’ 字符集进行 CTE 编码。

      -- 方法: fold_binary (name, value)

          如果 *note cte_type: 2831. 为 ‘7bit’ 则与 *note fold(): 284b.
          类似，不同之处在于返回的值是字节串。

          如果 *note cte_type: 2831. 为 ‘8bit’，则将非 ASCII 二进制数据
          转换回字节串。 带有二进制数据的标头不会被重新折叠，无论
          ‘refold_header’ 设置如何，因为无法知晓该二进制数据是由单字节字
          符还是多字节字符组成的。

以下 *note EmailPolicy: a00. 的实例提供了适用于特定应用领域的默认值。 请
注意在未来这些实例（特别是 ‘HTTP’ 实例）的行为可能会被调整以便更严格地遵
循与其领域相关的 RFC。

 -- 数据: email.policy.default

     一个未改变任何默认值的 ‘EmailPolicy’ 实例。 此策略使用标准的 Python
     ‘\n’ 行结束符而非遵循 RFC 的 ‘\r\n’。

 -- 数据: email.policy.SMTP

     适用于按照符合电子邮件 RFC 的方式来序列化消息。 与 ‘default’ 类似，
     但 ‘linesep’ 被设为遵循 RFC 的 ‘\r\n’。

 -- 数据: email.policy.SMTPUTF8

     与 ‘SMTP’ 类似但是 *note utf8: 6db. 为 ‘True’。 适用于在不使用标头
     内已编码字的情况下对消息进行序列化。 如果发送方或接收方地址具有非
     ASCII 字符则应当只被用于 SMTP 传输 (*note
     smtplib.SMTP.send_message(): 74e. 方法会自动如此处理)。

 -- 数据: email.policy.HTTP

     适用于序列化标头以在 HTTP 通信中使用。 与 ‘SMTP’ 类似但是
     ‘max_line_length’ 被设为 ‘None’ (无限制)。

 -- 数据: email.policy.strict

     便捷实例。 与 ‘default’ 类似但是 ‘raise_on_defect’ 被设为 ‘True’。
     这样可以允许通过以下写法来严格地设置任何策略:

          somepolicy + policy.strict

因为所有这些 *note EmailPolicies: a00.，email 包的高效 API 相比 Python
3.2 API 发生了以下几方面变化:

        * 在 *note Message: 54a. 中设置标头将使得该标头被解析并创建一个
          标头对象。

        * 从 *note Message: 54a. 提取标头将使得该标头被解析并创建和返回
          一个标头对象。

        * 任何标头对象或任何由于策略设置而被重新折叠的标头都会使用一种完
          全实现了 RFC 折叠算法的算法来进行折叠，包括知道在休息需要并允
          许已编码字。

从应用程序的视角来看，这意味着任何通过 *note EmailMessage: 54b. 获得的标
头都是具有附加属性的标头对象，其字符串值都是该标头的完全解码后的 unicode
值。 类似地，可以使用 unicode 对象为一个标头赋予新的值，或创建一个新的标
头对象，并且该策略将负责把该 unicode 字符串转换为正确的 RFC 已编码形式。

标头对象及其属性的描述见 *note headerregistry: 70.。

 -- 类: email.policy.Compat32 (**kw)

     这个实体 *note Policy: 9fc. 为向下兼容策略。 它复制了 Python 3.2 中
     email 包的行为。 *note policy: 75. 模块还定义了该类的一个实例 *note
     compat32: 549.，用来作为默认策略。 因此 email 包的默认行为会保持与
     Python 3.2 的兼容性。

     下列属性具有与 *note Policy: 9fc. 默认值不同的值:

      -- 属性: mangle_from_

          默认值为 ‘True’。

     这个类提供了下列对 *note Policy: 9fc. 的抽象方法的具体实现:

      -- 方法: header_source_parse (sourcelines)

          此名称会被作为到 ’‘:’’ 止的所有内容来解析。 该值是通过从第一行
          的剩余部分去除前导空格，再将所有后续行连接到一起，并去除所有末
          尾回车符或换行符来确定的。

      -- 方法: header_store_parse (name, value)

          name 和 value 会被原样返回。

      -- 方法: header_fetch_parse (name, value)

          如果 value 包含二进制数据，则会使用 ‘unknown-8bit’ 字符集来将
          其转换为 *note Header: 2855. 对象。 在其他情况下它会被原样返回
          。

      -- 方法: fold (name, value)

          标头会使用 *note Header: 2855. 折叠算法进行折叠，该算法保留
          value 中现有的换行，并将结果行长度折叠至 ‘max_line_length’。 非
          ASCII 二进制数据会使用 ‘unknown-8bit’ 字符串进行 CTE 编码。

      -- 方法: fold_binary (name, value)

          标头会使用 *note Header: 2855. 折叠算法进行折叠，该算法保留
          value 中现有的换行，并将每个结果行的长度折叠至
          ‘max_line_length’。 如果 ‘cte_type’ 为 ‘7bit’，则非 ascii 二进
          制数据会使用 ‘unknown-8bit’ 字符集进行 CTE 编码。 在其他情况下
          则会使用原始的源标头，这将保留其现有的换行和所包含的任何（不符
          合 RFC 的）二进制数据。

 -- 数据: email.policy.compat32

     *note Compat32: 9fd. 的实例，提供与 Python 3.2 中的 email 包行为的
     向下兼容性。

备注
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/email/policy.py

   (2) https://tools.ietf.org/html/rfc5322.html

   (3) https://tools.ietf.org/html/rfc5322.html

   (4) https://tools.ietf.org/html/rfc5322.html

   (5) https://tools.ietf.org/html/rfc2047.html

   (6) https://tools.ietf.org/html/rfc2047.html

   (7) https://tools.ietf.org/html/rfc5322.html

   (8) (1) 最初在 3.3 中作为 *note 暂定特性: 988. 添加。

   (9) https://tools.ietf.org/html/rfc5322.html

   (10) https://tools.ietf.org/html/rfc6532.html

   (11) https://tools.ietf.org/html/rfc6531.html

   (12) https://tools.ietf.org/html/rfc5322.html


File: python.info,  Node: email errors 异常和缺陷类,  Next: email headerregistry 自定义标头对象,  Prev: email policy 策略对象,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.8 ‘email.errors’: 异常和缺陷类
.....................................

`源代码:' Lib/email/errors.py(1)

__________________________________________________________________

以下异常类在 *note email.errors: 6d. 模块中定义：

 -- 例外: email.errors.MessageError

     这是 *note email: 69. 包可以引发的所有异常的基类。 它源自标准异常
     *note Exception: 1aa. 类，这个类没有定义其他方法。

 -- 例外: email.errors.MessageParseError

     这是由 *note Parser: b20. 类引发的异常的基类。它派生自 *note
     MessageError: 285a.。 *note headerregistry: 70. 使用的解析器也在内
     部使用这个类。

 -- 例外: email.errors.HeaderParseError

     在解析消息的 RFC 5322(2) 标头时，某些错误条件下会触发，此类派生自
     *note MessageParseError: 285b.。 如果在调用方法时内容类型未知，则
     *note set_boundary(): 2804. 方法将引发此错误。 当尝试创建一个看起来
     包含嵌入式标头的标头时 *note Header: 2855. 可能会针对某些 base64 解
     码错误引发此错误（也就是说，应该是一个 没有前导空格并且看起来像标题
     的延续行）。

 -- 例外: email.errors.BoundaryError

     已弃用和不再使用的。

 -- 例外: email.errors.MultipartConversionError

     当使用 ‘add_payload()’ 将有效负载添加到 *note Message: 54a. 对象时
     ，有效负载已经是一个标量，而消息的 ‘Content-Type’ 主类型不是
     ‘multipart’ 或者缺少时触发该异常。 *note MultipartConversionError:
     285d. 多重继承自 *note MessageError: 285a. 和内置的 *note
     TypeError: 193.。

     由于 ‘Message.add_payload()’ 已被弃用，此异常实际上极少会被引发。 但
     是如果在派生自 *note MIMENonMultipart: 285e. 的类 (例如 *note
     MIMEImage: 285f.) 的实例上调用 *note attach(): 2817. 方法也可以引发
     此异常。

以下是 *note FeedParser: 2821. 在解析消息时可发现的缺陷列表。 请注意这些
缺陷会在问题被发现时加入到消息中，因此举例来说，如果某条嵌套在
‘multipart/alternative’ 中的消息具有错误的标头，该嵌套消息对象就会有一条
缺陷，但外层消息对象则没有。

所有缺陷类都是 ‘email.errors.MessageDefect’ 的子类。

   * ‘NoBoundaryInMultipartDefect’ – 一条消息宣称有多个部分，但却没有
     ‘boundary’ 形参。

   * ‘StartBoundaryNotFoundDefect’ – 在 ‘Content-Type’ 标头中宣称的开始
     边界无法被找到。

   * ‘CloseBoundaryNotFoundDefect’ – 找到了开始边界，但相应的结束边界无
     法被找到。

     3.3 新版功能.

   * ‘FirstHeaderLineIsContinuationDefect’ – 消息以一个继续行作为其第一
     个标头行。

   * ‘MisplacedEnvelopeHeaderDefect’ - 在标头块中间发现了一个 "Unix
     From" 标头。

   * ‘MissingHeaderBodySeparatorDefect’ - 在解析没有前缀空格但又不包含
     ’:’ 的标头期间找到一行内容。 解析将假定该行表示消息体的第一行以继续
     执行。

     3.3 新版功能.

   * ‘MalformedHeaderDefect’ – 找到一个缺失了冒号或格式错误的标头。

     3.3 版后已移除: 此缺陷在近几个 Python 版本中已不再使用。

   * ‘MultipartInvariantViolationDefect’ – 一条消息宣称为 ‘multipart’，
     但无法找到任何子部分。 请注意当一条消息有此缺陷时，其 *note
     is_multipart(): 2809. 方法可能返回 ‘False’，即使其内容类型宣称为
     ‘multipart’。

   * ‘InvalidBase64PaddingDefect’ – 当解码一个 base64 编码的字节分块时，
     填充的数据不正确。 虽然添加了足够的填充数据以执行解码，但作为结果的
     已解码字节串可能无效。

   * ‘InvalidBase64CharactersDefect’ – 当解码一个 base64 编码的字节分块
     时，遇到了 base64 字符表以外的字符。 这些字符会被忽略，但作为结果的
     已解码字节串可能无效。

   * ‘InvalidBase64LengthDefect’ – 当解码一个 base64 编码的字节分块时，
     非填充 base64 字符的数量无效（比 4 的倍数多 1）。 已编码分块会保持
     原样。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/email/errors.py

   (2) https://tools.ietf.org/html/rfc5322.html


File: python.info,  Node: email headerregistry 自定义标头对象,  Next: email contentmanager 管理 MIME 内容,  Prev: email errors 异常和缺陷类,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.9 ‘email.headerregistry’: 自定义标头对象
...............................................

`源代码:' Lib/email/headerregistry.py(1)

__________________________________________________________________

3.6 新版功能: (2)

标头是由 *note str: 339. 的自定义子类来表示的。 用于表示给定标头的特定类
则由创建标头时生效的 *note policy: 75. 的 *note header_factory: 2844. 确
定。 这一节记录了 email 包为处理兼容 RFC 5322(3) 的电子邮件消息所实现的
特定 ‘header_factory’，它不仅为各种标头类型提供了自定义的标头对象，还为
应用程序提供了添加其自定义标头类型的扩展机制。

当使用派生自 *note EmailPolicy: a00. 的任何策略对象时，所有标头都通过
*note HeaderRegistry: 2862. 产生并且以 *note BaseHeader: 27f2. 作为其最
后一个基类。 每个标头类都有一个由该标头类型确定的附加基类。 例如，许多标
头都以 *note UnstructuredHeader: 2863. 类作为其另一个基类。 一个标头专用
的第二个类是由标头名称使用存储在 *note HeaderRegistry: 2862. 中的查找表
来确定的。 所有这些都针对典型应用程序进行透明的管理，但也为修改默认行为
提供了接口，以便由更复杂的应用使用。

以下各节首先记录了标头基类及其属性，然后是用于修改 *note HeaderRegistry:
2862. 行为的 API，最后是用于表示从结构化标头解析的数据的支持类。

 -- 类: email.headerregistry.BaseHeader (name, value)

     `name' 和 `value' 会从 *note header_factory: 2844. 调用传递给
     ‘BaseHeader’。 任何标头对象的字符串值都是完成解码为 unicode 的
     `value'。

     这个基类定义了下列只读属性:

      -- 属性: name

          标头的名称（字段在 ’:’ 之前的部分）。 这就是 `name' 的 *note
          header_factory: 2844. 调用所传递的值；也就是说会保持大小写形式
          。

      -- 属性: defects

          一个包含 ‘HeaderDefect’ 实例的元组，这些实例报告了在解析期间发
          现的任何 RFC 合规性问题。 email 包会尝试尽可能地检测合规性问题
          。 请参阅 *note errors: 6d. 模块了解可能被报告的缺陷类型的相关
          讨论。

      -- 属性: max_count

          此类型标头可具有相同 ‘name’ 的最大数量。 ‘None’ 值表示无限制。
          此属性的 ‘BaseHeader’ 值为 ‘None’；专用的标头类预期将根据需要
          重载这个值。

     ‘BaseHeader’ 还提供了以下方法，它由 email 库代码调用，通常不应当由
     应用程序来调用。

      -- 方法: fold (*, policy)

          返回一个字符串，其中包含用来根据 `policy' 正确地折叠标头的
          *note linesep: 2839. 字符。 *note cte_type: 2831. 为 ‘8bit’ 时
          将被作为 ‘7bit’ 来处理，因为标头不能包含任意二进制数据。 如果
          *note utf8: 6db. 为 ‘False’，则非 ASCII 数据将根据 RFC 2047(4)
          来编码。

     ‘BaseHeader’ 本身不能被用于创建标头对象。 它定义了一个与每个专用标
     头相配合的协议以便生成标头对象。 具体来说，‘BaseHeader’ 要求专用类
     提供一个名为 ‘parse’ 的 *note classmethod(): 1d9.。 此方法的调用形
     式如下:

          parse(string, kwds)

     ‘kwds’ 是包含了一个预初始化键 ‘defects’ 的字典。 ‘defects’ 是一个空
     列表。 parse 方法应当将任何已检测到的缺陷添加到此列表中。 在返回时
     ，‘kwds’ 字典 `必须' 至少包含 ‘decoded’ 和 ‘defects’ 等键的值。
     ‘decoded’ 应当是标头的字符串值（即完全解码为 unicode 的标头值）。
     parse 方法应当假定 `string' 可能包含 content-transfer-encoded 部分
     ，但也应当正确地处理全部有效的 unicode 字符以便它能解析未经编码的标
     头值。

     随后 ‘BaseHeader’ 的 ‘__new__’ 会创建标头实例，并调用其 ‘init’ 方法
     。 专属类如果想要设置 ‘BaseHeader’ 自身所提供的属性之外的附加属性，
     只需提供一个 ‘init’ 方法。 这样的 ‘init’ 看起来应该是这样:

          def init(self, /, *args, **kw):
              self._myattr = kw.pop('myattr')
              super().init(*args, **kw)

     也就是说，专属类放入 ‘kwds’ 字典的任何额外内容都应当被移除和处理，
     并且 ‘kw’ (和 ‘args’) 的剩余内容会被传递给 ‘BaseHeader’ ‘init’ 方法
     。

 -- 类: email.headerregistry.UnstructuredHeader

     "非结构化" 标头是 RFC 5322(5) 中默认的标头类型。 任何没有指定语法的
     标头都会被视为是非结构化的。 非结构化标头的经典例子是 ‘Subject’ 标
     头。

     在 RFC 5322(6) 中，非结构化标头是指一段以 ASCII 字符集表示的任意文
     本。 但是 RFC 2047(7) 具有一个 RFC 5322(8) 兼容机制用来将标头值中的
     非 ASCII 文本编码为 ASCII 字符。 当包含已编码字的 `value' 被传递给
     构造器时，‘UnstructuredHeader’ 解析器会按照非结构化文本的 RFC
     2047(9) 规则将此类已编码字转换为 unicode。 解析器会使用启发式机制来
     尝试解码一些不合规的已编码字。 在此种情况下各类缺陷，例如已编码字或
     未编码文本中的无效字符问题等缺陷将会被注册。

     此标头类型未提供附加属性。

 -- 类: email.headerregistry.DateHeader

     RFC 5322(10) 为电子邮件标头内的日期指定了非常明确的格式。
     ‘DateHeader’ 解析器会识别该日期格式，并且也能识别间或出现的一些“不
     规范”变种形式。

     这个标头类型提供了以下附加属性。

      -- 属性: datetime

          如果标头值能被识别为某一种有效的日期形式，此属性将包含一个代表
          该日期的 *note datetime: 195. 实例。 如果输入日期的时区被指定
          为 ‘-0000’ (表示为 UTC 但不包含源时区的相关信息)，则 *note
          datetime: 2868. 将为简单型 *note datetime: 195.。 如果找到了特
          定的时区时差值 (包括 ‘+0000’)，则 *note datetime: 2868. 将包含
          使用 *note datetime.timezone: a09. 来记录时区时差时的感知型
          ‘datetime’。

     标头的 ‘decoded’ 值是由按照 RFC 5322(11) 对 ‘datetime’ 进行格式化来
     确定的；也就是说，它会被设为:

          email.utils.format_datetime(self.datetime)

     当创建 ‘DateHeader’ 时，`value' 可以为 *note datetime: 195. 实例。
     例如这意味着以下代码是有效的并能实现人们预期的行为:

          msg['Date'] = datetime(2011, 7, 15, 21)

     因为这是个简单型 ‘datetime’ 它将被解读为 UTC 时间戳，并且结果值的时
     区将为 ‘-0000’。 使用来自 *note utils: 76. 模块的 *note
     localtime(): a08. 函数会更有用:

          msg['Date'] = utils.localtime()

     这个例子将日期标头设为使用当前时区时差值的当前时间和日期。

 -- 类: email.headerregistry.AddressHeader

     地址标头是最复杂的结构化标头类型之一。 ‘AddressHeader’ 类提供了适合
     任何地址标头的泛用型接口。

     这个标头类型提供了以下附加属性。

      -- 属性: groups

          编码了在标头值中找到的地址和分组的 *note Group: 286b. 对象的元
          组。 非分组成员的地址在此列表中表示为 *note display_name:
          286c. 为 ‘None’ 的单地址 ‘Groups’。

      -- 属性: addresses

          编码了来自标头值的所有单独地址的 *note Address: 286e. 对象的元
          组。 如果标头值包含任何分组，则来自分组的单个地址将包含在该分
          组出现在值中的点上列出（也就是说，地址列表会被“展平”为一维列表
          ）。

     标头的 ‘decoded’ 值将为所有已编码字解码为 unicode 的结果。 *note
     idna: 77. 编码的域名也将被解码为 unicode。 ‘decoded’ 值是通过对
     ‘groups’ 属性的元素的 *note str: 339. 值使用 ‘', '’ 进行 *note
     join: 1642. 来设置的。

     可以使用 *note Address: 286e. 与 *note Group: 286b. 对象的任意组合
     的列表来设置一个地址标头的值。 ‘display_name’ 为 ‘None’ 的 ‘Group’
     对象将被解读为单独地址，这允许一个地址列表可以附带通过使用从源标头
     的 ‘groups’ 属性获取的列表而保留原分组。

 -- 类: email.headerregistry.SingleAddressHeader

     *note AddressHeader: 2869. 的子类，添加了一个额外的属性:

      -- 属性: address

          由标头值编码的单个地址。 如果标头值实际上包含一个以上的地址（
          这在默认 *note policy: 75. 下将违反 RFC），则访问此属性将导致
          *note ValueError: 1fc.。

上述类中许多还具有一个 ‘Unique’ 变体 (例如 ‘UniqueUnstructuredHeader’)。
其唯一差别是在 ‘Unique’ 变体中 *note max_count: 2847. 被设为 1。

 -- 类: email.headerregistry.MIMEVersionHeader

     实际上 ‘MIME-Version’ 标头只有一个有效的值，即 ‘1.0’。 为了将来的扩
     展，这个标头类还支持其他的有效版本号。 如果一个版本号是 RFC
     2045(12) 的有效值，则标头对象的以下属性将具有不为 ‘None’ 的值:

      -- 属性: version

          字符串形式的版本号。 任何空格和/或注释都会被移除。

      -- 属性: major

          整数形式的主版本号

      -- 属性: minor

          整数形式的次版本号

 -- 类: email.headerregistry.ParameterizedMIMEHeader

     MIME 标头都以前缀 ’Content-’ 打头。 每个特定标头都具有特定的值，其
     描述在该标头的类之中。 有些也可以接受一个具有通用格式的补充形参形表
     。 这个类被用作所有接受形参的 MIME 标头的基类。

      -- 属性: params

          一个将形参名映射到形参值的字典。

 -- 类: email.headerregistry.ContentTypeHeader

     处理 ‘Content-Type’ 标头的 *note ParameterizedMIMEHeader: 2875. 类
     。

      -- 属性: content_type

          ‘maintype/subtype’ 形式的内容类型字符串。

      -- 属性: maintype

      -- 属性: subtype

 -- 类: email.headerregistry.ContentDispositionHeader

     处理 ‘Content-Disposition’ 标头的 *note ParameterizedMIMEHeader:
     2875. 类。

      -- 属性: content_disposition

          ‘inline’ 和 ‘attachment’ 是仅有的常用有效值。

 -- 类: email.headerregistry.ContentTransferEncoding

     处理 ‘Content-Transfer-Encoding’ 标头。

      -- 属性: cte

          可用的有效值为 ‘7bit’, ‘8bit’, ‘base64’ 和 ‘quoted-printable’。
          更多信息请参阅 RFC 2045(13)。

 -- 类: email.headerregistry.HeaderRegistry (base_class=BaseHeader,
          default_class=UnstructuredHeader, use_default_map=True)

     这是由 *note EmailPolicy: a00. 在默认情况下使用的工厂函数。
     ‘HeaderRegistry’ 会使用 `base_class' 和从它所保存的注册表中获取的专
     用类来构建用于动态地创建标头实例的类。 当给定的标头名称未在注册表中
     出现时，则会使用由 `default_class' 所指定的类作为专用类。 当
     `use_default_map' 为 ‘True’ (默认值) 时，则会在初始化期间把将标头名
     称与类的标准映射拷贝到注册表中。 `base_class' 始终会是所生成类的
     ‘__bases__’ 列表中的最后一个类。

     默认的映射有:


          subject: UniqueUnstructuredHeader


          date: UniqueDateHeader


          resent-date: DateHeader


          orig-date: UniqueDateHeader


          sender: UniqueSingleAddressHeader


          resent-sender: SingleAddressHeader


          到: UniqueAddressHeader


          resent-to: AddressHeader


          cc: UniqueAddressHeader


          resent-cc: AddressHeader


          bcc: UniqueAddressHeader


          resent-bcc: AddressHeader


          从: UniqueAddressHeader


          resent-from: AddressHeader


          reply-to: UniqueAddressHeader


          mime-version: MIMEVersionHeader


          content-type: ContentTypeHeader


          content-disposition: ContentDispositionHeader


          content-transfer-encoding: ContentTransferEncodingHeader


          message-id: MessageIDHeader

     ‘HeaderRegistry’ 具有下列方法:

      -- 方法: map_to_type (self, name, cls)

          `name' 是要映射的标头名称。 它将在注册表中被转换为小写形式。
          `cls' 是要与 `base_class' 一起被用来创建用于实例化与 `name' 相
          匹配的标头的类的专用类。

      -- 方法: __getitem__ (name)

          构造并返回一个类来处理 `name' 标头的创建。

      -- 方法: __call__ (name, value)

          从注册表获得与 `name' 相关联的专用标头 (如果 `name' 未在注册表
          中出现则使用 `default_class') 并将其与 `base_class' 相组合以产
          生类，调用被构造类的构造器，传入相同的参数列表，并最终返回由此
          创建的类实例。

以下的类是用于表示从结构化标头解析的数据的类，并且通常会由应用程序使用以
构造结构化的值并赋给特定的标头。

 -- 类: email.headerregistry.Address (display_name='', username='',
          domain='', addr_spec=None)

     用于表示电子邮件地址的类。 地址的一般形式为:

          [display_name] <username@domain>

     或者：

          username@domain

     其中每个部分都必须符合在 RFC 5322(14) 中阐述的特定语法规则。

     为了方便起见可以指定 `addr_spec' 来替代 `username' 和 `domain'，在
     此情况下 `username' 和 `domain' 将从 `addr_spec' 中解析。
     `addr_spec' 应当是一个正确地引用了 RFC 的字符串；如果它不是
     ‘Address’ 则将引发错误。 Unicode 字符也允许使用并将在序列化时被正确
     地编码。 但是，根据 RFC，地址的 username 部分 `不允许' 有 unicode。

      -- 属性: display_name

          地址的显示名称部分（如果有的话）并去除所有引用项。 如果地址没
          有显示名称，则此属性将为空字符串。

      -- 属性: username

          地址的 ‘username’ 部分，去除所有引用项。

      -- 属性: domain

          地址的 ‘domain’ 部分。

      -- 属性: addr_spec

          地址的 ‘username@domain’ 部分，经过正确引用处理以作为纯地址使
          用（上面显示的第二种形式）。 此属性不可变。

      -- 方法: __str__ ()

          对象的 ‘str’ 值是根据 RFC 5322(15) 规则进行引用处理的地址，但
          不带任何非 ASCII 字符的 Content Transfer Encoding。

     为了支持 SMTP ( RFC 5321(16))，‘Address’ 会处理一种特殊情况：如果
     ‘username’ 和 ‘domain’ 均为空字符串 (或为 ‘None’)，则 ‘Address’ 的
     字符串值为 ‘<>’。

 -- 类: email.headerregistry.Group (display_name=None, addresses=None)

     用于表示地址组的类。 地址组的一般形式为:

          display_name: [address-list];

     作为处理由组和单个地址混合构成的列表的便捷方式，‘Group’ 也可以通过
     将 `display_name' 设为 ‘None’ 以用来表示不是某个组的一部分的单个地
     址并提供单个地址的列表作为 `addresses'。

      -- 属性: display_name

          组的 ‘display_name’。 如果其为 ‘None’ 并且恰好有一个 ‘Address’
          在 ‘addresses’ 中，则 ‘Group’ 表示一个不在某个组中的单独地址。

      -- 属性: addresses

          一个可能为空的表示组中地址的包含 *note Address: 286e. 对象的元
          组。

      -- 方法: __str__ ()

          ‘Group’ 的 ‘str’ 值会根据 RFC 5322(17) 进行格式化，但不带任何
          非 ASCII 字符的 Content Transfer Encoding。 如果
          ‘display_name’ 为空值且只有一个单独 ‘Address’ 在 ‘addresses’ 列
          表中，则 ‘str’ 值将与该单独 ‘Address’ 的 ‘str’ 相同。

备注
....

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/email/headerregistry.py

   (2) (1) 最初在 3.3 中作为 *note 暂定模块: 988. 添加

   (3) https://tools.ietf.org/html/rfc5322.html

   (4) https://tools.ietf.org/html/rfc2047.html

   (5) https://tools.ietf.org/html/rfc5322.html

   (6) https://tools.ietf.org/html/rfc5322.html

   (7) https://tools.ietf.org/html/rfc2047.html

   (8) https://tools.ietf.org/html/rfc5322.html

   (9) https://tools.ietf.org/html/rfc2047.html

   (10) https://tools.ietf.org/html/rfc5322.html

   (11) https://tools.ietf.org/html/rfc5322.html

   (12) https://tools.ietf.org/html/rfc2045.html

   (13) https://tools.ietf.org/html/rfc2045.html

   (14) https://tools.ietf.org/html/rfc5322.html

   (15) https://tools.ietf.org/html/rfc5322.html

   (16) https://tools.ietf.org/html/rfc5321.html

   (17) https://tools.ietf.org/html/rfc5322.html


File: python.info,  Node: email contentmanager 管理 MIME 内容,  Next: email 示例,  Prev: email headerregistry 自定义标头对象,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.10 ‘email.contentmanager’: 管理 MIME 内容
................................................

`源代码:' Lib/email/contentmanager.py(1)

__________________________________________________________________

3.6 新版功能: (2)

 -- 类: email.contentmanager.ContentManager

     内容管理器的基类。 提供注册 MIME 内容和其他表示形式间转换器的标准注
     册机制，以及 ‘get_content’ 和 ‘set_content’ 发送方法。

      -- 方法: get_content (msg, *args, **kw)

          基于 `msg' 的 ‘mimetype’ 查找处理函数（参见下一段），调用该函
          数，传递所有参数，并返回调用的结果。 期望的效果是处理程序将从
          `msg' 中提取有效载荷并返回编码了有关被提取数据信息的对象。

          要找到处理程序，将在注册表中查找以下键，找到第一个键即停止:

                  * 表示完整 MIME 类型的字符串 (‘maintype/subtype’)

                  * 表示 ‘maintype’ 的字符串

                  * 空字符串

          如果这些键都没有产生处理程序，则为完整 MIME 类型引发一个 *note
          KeyError: 2c8.。

      -- 方法: set_content (msg, obj, *args, **kw)

          如果 ‘maintype’ 为 ‘multipart’，则引发 *note TypeError: 193.；
          否则基于 `obj' 的类型（参见下一段）查找处理函数，在 `msg' 上调
          用 *note clear_content(): 281b.，并调用处理函数，传递所有参数
          。 预期的效果是处理程序将转换 `obj' 并存入 `msg'，并可能对
          `msg' 进行其他更改，例如添加各种 MIME 标头来编码需要用来解释所
          存储数据的信息。

          要找到处理程序，将获取 `obj' 的类型 (‘typ = type(obj)’)，并在
          注册表中查找以下键，找到第一个键即停止:

                  * 类型本身 (‘typ’)

                  * 类型的完整限定名称 (‘typ.__module__ + '.' +
                    typ.__qualname__’)。

                  * 类型的 qualname (‘typ.__qualname__’)

                  * 类型的 name (‘typ.__name__’)。

          如果未匹配到上述的任何一项，则在 *note MRO: 288c.
          (‘typ.__mro__’) 中为每个类型重复上述的所有检测。 最后，如果没
          有其他键产生处理程序，则为 ‘None’ 键检测处理程序。 如果也没有
          ‘None’ 的处理程序，则为该类型的完整限定名称引发 *note
          KeyError: 2c8.。

          并会添加一个 ‘MIME-Version’ 标头，如果没有的话 (另请参见 *note
          MIMEPart: 84c.)。

      -- 方法: add_get_handler (key, handler)

          将 `handler' 函数记录为 `key' 的处理程序。 对于可能的 `key' 键
          ，请参阅 *note get_content(): 288e.。

      -- 方法: add_set_handler (typekey, handler)

          将 `handler' 记录为当一个匹配 `typekey' 的类型对象被传递给
          *note set_content(): 2890. 时所要调用的函数。 对于可能的
          `typekey' 值，请参阅 *note set_content(): 2890.。

* Menu:

* 内容管理器实例::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/email/contentmanager.py

   (2) (1) 最初在 3.4 中作为 *note 暂定模块: 988. 添加


File: python.info,  Node: 内容管理器实例,  Up: email contentmanager 管理 MIME 内容

5.19.1.11 内容管理器实例
........................

目前 email 包只提供了一个实体内容管理器 *note raw_data_manager: 2845.，
不过在未来可能会添加更多。 *note raw_data_manager: 2845. 是由 *note
EmailPolicy: a00. 及其衍生工具所提供的 *note content_manager: 84d.。

 -- 数据: email.contentmanager.raw_data_manager

     这个内容管理器仅提供了超出 *note Message: 54a. 本身提供内容的最小接
     口：它只处理文本、原始字节串和 *note Message: 54a. 对象。 不过相比
     基础 API，它具有显著的优势：在文本部分上执行 ‘get_content’ 将返回一
     个 unicode 字符串而无需由应用程序来手动解码，‘set_content’ 为控制添
     加到一个部分的标头和控制内容传输编码格式提供了丰富的选项集合，并且
     它还启用了多种 ‘add_’ 方法，从而简化了多部分消息的创建过程。

      -- 方法: email.contentmanager.get_content (msg, errors='replace')

          将指定部分的有效载荷作为字符串（对于 ‘text’ 部分）, *note
          EmailMessage: 54b. 对象（对于 ‘message/rfc822’ 部分）或
          ‘bytes’ 对象（对于所有其他非多部分类型）返回。 如果是在
          ‘multipart’ 上调用则会引发 *note KeyError: 2c8.。 如果指定部分
          是一个 ‘text’ 部分并且指明了 `errors'，则会在将载荷解码为
          unicode 时将其用作错误处理程序。 默认的错误处理程序是
          ‘replace’。

      -- 方法: email.contentmanager.set_content (msg, <'str'>,
               subtype="plain", charset='utf-8', cte=None,
               disposition=None, filename=None, cid=None, params=None,
               headers=None)

      -- 方法: email.contentmanager.set_content (msg, <'bytes'>,
               maintype, subtype, cte="base64", disposition=None,
               filename=None, cid=None, params=None, headers=None)

      -- 方法: email.contentmanager.set_content (msg, <'EmailMessage'>,
               cte=None, disposition=None, filename=None, cid=None,
               params=None, headers=None)

          向 `msg' 添加标头和有效载荷:

          添加一个带有 ‘maintype/subtype’ 值的 ‘Content-Type’ 标头。

                  * 对于 ‘str’，将 MIME ‘maintype’ 设为 ‘text’，如果指定
                    了子类型 `subtype' 则设为指定值，否则设为 ‘plain’。

                  * 对于 ‘bytes’，将使用指定的 `maintype' 和 `subtype'，
                    如果未指定则会引发 *note TypeError: 193.。

                  * 对于 *note EmailMessage: 54b. 对象，将 maintype 设为
                    ‘message’，并将指定的 subtype 设为 `subtype'，如果未
                    指定则设为 ‘rfc822’。 如果 `subtype' 为 ‘partial’，
                    则引发一个错误（必须使用 ‘bytes’ 对象来构造
                    ‘message/partial’ 部分）。

          如果提供了 `charset' (这只对 ‘str’ 适用)，则使用指定的字符集将
          字符串编码为字节串。 默认值为 ‘utf-8’。 如果指定的 `charset' 是
          某个标准 MIME 字符集名称的已知别名，则会改用该标准字符集。

          如果设置了 `cte'，则使用指定的内容传输编码格式对有效载荷进行编
          码，并将 ‘Content-Transfer-Encoding’ 标头设为该值。 可能的
          `cte' 值有 ‘quoted-printable’, ‘base64’, ‘7bit’, ‘8bit’ 和
          ‘binary’。 如果输入无法以指定的编码格式被编码 (例如，对于包含
          非 ASCII 值的输入指定 `cte' 值为 ‘7bit’)，则会引发 *note
          ValueError: 1fc.。

                  * 对于 ‘str’ 对象，如果 `cte' 未设置则会使用启发方式来
                    确定最紧凑的编码格式。

                  * 对于 *note EmailMessage: 54b.，按照 RFC 2046(1)，如
                    果为 `subtype' ‘rfc822’ 请求的 `cte' 为
                    ‘quoted-printable’ 或 ‘base64’ ，而为 ‘7bit’ 以外的
                    任何 `cte' 为 `subtype' ‘external-body’ 则会引发一个
                    错误。 对于 ‘message/rfc822’，如果 `cte' 未指定则会
                    使用 ‘8bit’。 对于所有其他 `subtype' 值，都会使用
                    ‘7bit’。

               注解: `cte' 值为 ‘binary’ 实际上还不能正确工作。 由
               ‘set_content’ 所修改的 ‘EmailMessage’ 对象是正确的，但
               *note BytesGenerator: b55. 不会正确地将其序列化。

          如果设置了 `disposition'，它会被用作 ‘Content-Disposition’ 标
          头的值。 如果未设置，并且指定了 `filename'，则添加值为
          ‘attachment’ 的标头。 如果未设置 `disposition' 并且也未指定
          `filename'，则不添加标头。 `disposition' 的有效值仅有
          ‘attachment’ 和 ‘inline’。

          如果设置了 `filename'，则将其用作 ‘Content-Disposition’ 标头的
          ‘filename’ 参数的值。

          如果设置了 `cid'，则添加一个 ‘Content-ID’ 标头并将其值设为
          `cid'。

          如果设置了 `params'，则迭代其 ‘items’ 方法并使用输出的 ‘(key,
          value)’ 结果对在 ‘Content-Type’ 标头上设置附加参数。

          如果设置了 `headers' 并且为 ‘headername: headervalue’ 形式的字
          符串的列表或为 ‘header’ 对象的列表（通过一个 ‘name’ 属性与字符
          串相区分），则将标头添加到 `msg'。

备注
....

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2046.html


File: python.info,  Node: email 示例,  Next: email message Message 使用 compat32 API 来表示电子邮件消息,  Prev: email contentmanager 管理 MIME 内容,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.12 ‘email’: 示例
.......................

以下是一些如何使用 *note email: 69. 包来读取、写入和发送简单电子邮件以及
更复杂的MIME邮件的示例。

首先，让我们看看如何创建和发送简单的文本消息（文本内容和地址都可能包含
unicode字符）：

     # Import smtplib for the actual sending function
     import smtplib

     # Import the email modules we'll need
     from email.message import EmailMessage

     # Open the plain text file whose name is in textfile for reading.
     with open(textfile) as fp:
         # Create a text/plain message
         msg = EmailMessage()
         msg.set_content(fp.read())

     # me == the sender's email address
     # you == the recipient's email address
     msg['Subject'] = f'The contents of {textfile}'
     msg['From'] = me
     msg['To'] = you

     # Send the message via our own SMTP server.
     s = smtplib.SMTP('localhost')
     s.send_message(msg)
     s.quit()

解析 RFC 822(1) 标题可以通过使用 *note parser: 74. 模块中的类来轻松完成
：

     # Import the email modules we'll need
     from email.parser import BytesParser, Parser
     from email.policy import default

     # If the e-mail headers are in a file, uncomment these two lines:
     # with open(messagefile, 'rb') as fp:
     #     headers = BytesParser(policy=default).parse(fp)

     #  Or for parsing headers in a string (this is an uncommon operation), use:
     headers = Parser(policy=default).parsestr(
             'From: Foo Bar <user@example.com>\n'
             'To: <someone_else@example.com>\n'
             'Subject: Test message\n'
             '\n'
             'Body would go here\n')

     #  Now the header items can be accessed as a dictionary:
     print('To: {}'.format(headers['to']))
     print('From: {}'.format(headers['from']))
     print('Subject: {}'.format(headers['subject']))

     # You can also access the parts of the addresses:
     print('Recipient username: {}'.format(headers['to'].addresses[0].username))
     print('Sender name: {}'.format(headers['from'].addresses[0].display_name))

以下是如何发送包含可能在目录中的一系列家庭照片的MIME消息示例：

     # Import smtplib for the actual sending function
     import smtplib

     # And imghdr to find the types of our images
     import imghdr

     # Here are the email package modules we'll need
     from email.message import EmailMessage

     # Create the container email message.
     msg = EmailMessage()
     msg['Subject'] = 'Our family reunion'
     # me == the sender's email address
     # family = the list of all recipients' email addresses
     msg['From'] = me
     msg['To'] = ', '.join(family)
     msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

     # Open the files in binary mode.  Use imghdr to figure out the
     # MIME subtype for each specific image.
     for file in pngfiles:
         with open(file, 'rb') as fp:
             img_data = fp.read()
         msg.add_attachment(img_data, maintype='image',
                                      subtype=imghdr.what(None, img_data))

     # Send the email via our own SMTP server.
     with smtplib.SMTP('localhost') as s:
         s.send_message(msg)

以下是如何将目录的全部内容作为电子邮件消息发送的示例： (2)

     #!/usr/bin/env python3

     """Send the contents of a directory as a MIME message."""

     import os
     import smtplib
     # For guessing MIME type based on file name extension
     import mimetypes

     from argparse import ArgumentParser

     from email.message import EmailMessage
     from email.policy import SMTP


     def main():
         parser = ArgumentParser(description="""\
     Send the contents of a directory as a MIME message.
     Unless the -o option is given, the email is sent by forwarding to your local
     SMTP server, which then does the normal delivery process.  Your local machine
     must be running an SMTP server.
     """)
         parser.add_argument('-d', '--directory',
                             help="""Mail the contents of the specified directory,
                             otherwise use the current directory.  Only the regular
                             files in the directory are sent, and we don't recurse to
                             subdirectories.""")
         parser.add_argument('-o', '--output',
                             metavar='FILE',
                             help="""Print the composed message to FILE instead of
                             sending the message to the SMTP server.""")
         parser.add_argument('-s', '--sender', required=True,
                             help='The value of the From: header (required)')
         parser.add_argument('-r', '--recipient', required=True,
                             action='append', metavar='RECIPIENT',
                             default=[], dest='recipients',
                             help='A To: header value (at least one required)')
         args = parser.parse_args()
         directory = args.directory
         if not directory:
             directory = '.'
         # Create the message
         msg = EmailMessage()
         msg['Subject'] = f'Contents of directory {os.path.abspath(directory)}'
         msg['To'] = ', '.join(args.recipients)
         msg['From'] = args.sender
         msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

         for filename in os.listdir(directory):
             path = os.path.join(directory, filename)
             if not os.path.isfile(path):
                 continue
             # Guess the content type based on the file's extension.  Encoding
             # will be ignored, although we should check for simple things like
             # gzip'd or compressed files.
             ctype, encoding = mimetypes.guess_type(path)
             if ctype is None or encoding is not None:
                 # No guess could be made, or the file is encoded (compressed), so
                 # use a generic bag-of-bits type.
                 ctype = 'application/octet-stream'
             maintype, subtype = ctype.split('/', 1)
             with open(path, 'rb') as fp:
                 msg.add_attachment(fp.read(),
                                    maintype=maintype,
                                    subtype=subtype,
                                    filename=filename)
         # Now send or store the message
         if args.output:
             with open(args.output, 'wb') as fp:
                 fp.write(msg.as_bytes(policy=SMTP))
         else:
             with smtplib.SMTP('localhost') as s:
                 s.send_message(msg)


     if __name__ == '__main__':
         main()

以下是如何将上述MIME消息解压缩到文件目录中的示例：

     #!/usr/bin/env python3

     """Unpack a MIME message into a directory of files."""

     import os
     import email
     import mimetypes

     from email.policy import default

     from argparse import ArgumentParser


     def main():
         parser = ArgumentParser(description="""\
     Unpack a MIME message into a directory of files.
     """)
         parser.add_argument('-d', '--directory', required=True,
                             help="""Unpack the MIME message into the named
                             directory, which will be created if it doesn't already
                             exist.""")
         parser.add_argument('msgfile')
         args = parser.parse_args()

         with open(args.msgfile, 'rb') as fp:
             msg = email.message_from_binary_file(fp, policy=default)

         try:
             os.mkdir(args.directory)
         except FileExistsError:
             pass

         counter = 1
         for part in msg.walk():
             # multipart/* are just containers
             if part.get_content_maintype() == 'multipart':
                 continue
             # Applications should really sanitize the given filename so that an
             # email message can't be used to overwrite important files
             filename = part.get_filename()
             if not filename:
                 ext = mimetypes.guess_extension(part.get_content_type())
                 if not ext:
                     # Use a generic bag-of-bits extension
                     ext = '.bin'
                 filename = f'part-{counter:03d}{ext}'
             counter += 1
             with open(os.path.join(args.directory, filename), 'wb') as fp:
                 fp.write(part.get_payload(decode=True))


     if __name__ == '__main__':
         main()

以下是如何使用备用纯文本版本创建 HTML 消息的示例。 为了让事情变得更有趣
，我们在 html 部分中包含了一个相关的图像，我们保存了一份我们要发送的内容
到硬盘中，然后发送它。

     #!/usr/bin/env python3

     import smtplib

     from email.message import EmailMessage
     from email.headerregistry import Address
     from email.utils import make_msgid

     # Create the base text message.
     msg = EmailMessage()
     msg['Subject'] = "Ayons asperges pour le déjeuner"
     msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
     msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
                  Address("Fabrette Pussycat", "fabrette", "example.com"))
     msg.set_content("""\
     Salut!

     Cela ressemble à un excellent recipie[1] déjeuner.

     [1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718

     --Pepé
     """)

     # Add the html version.  This converts the message into a multipart/alternative
     # container, with the original text message as the first part and the new html
     # message as the second part.
     asparagus_cid = make_msgid()
     msg.add_alternative("""\
     <html>
       <head></head>
       <body>
         <p>Salut!</p>
         <p>Cela ressemble à un excellent
             <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
                 recipie
             </a> déjeuner.
         </p>
         <img src="cid:{asparagus_cid}" />
       </body>
     </html>
     """.format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
     # note that we needed to peel the <> off the msgid for use in the html.

     # Now add the related image to the html part.
     with open("roasted-asparagus.jpg", 'rb') as img:
         msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                          cid=asparagus_cid)

     # Make a local copy of what we are going to send.
     with open('outgoing.msg', 'wb') as f:
         f.write(bytes(msg))

     # Send the message via local SMTP server.
     with smtplib.SMTP('localhost') as s:
         s.send_message(msg)

如果我们发送最后一个示例中的消息，这是我们可以处理它的一种方法：

     import os
     import sys
     import tempfile
     import mimetypes
     import webbrowser

     # Import the email modules we'll need
     from email import policy
     from email.parser import BytesParser

     # An imaginary module that would make this work and be safe.
     from imaginary import magic_html_parser

     # In a real program you'd get the filename from the arguments.
     with open('outgoing.msg', 'rb') as fp:
         msg = BytesParser(policy=policy.default).parse(fp)

     # Now the header items can be accessed as a dictionary, and any non-ASCII will
     # be converted to unicode:
     print('To:', msg['to'])
     print('From:', msg['from'])
     print('Subject:', msg['subject'])

     # If we want to print a preview of the message content, we can extract whatever
     # the least formatted payload is and print the first three lines.  Of course,
     # if the message has no plain text part printing the first three lines of html
     # is probably useless, but this is just a conceptual example.
     simplest = msg.get_body(preferencelist=('plain', 'html'))
     print()
     print(''.join(simplest.get_content().splitlines(keepends=True)[:3]))

     ans = input("View full message?")
     if ans.lower()[0] == 'n':
         sys.exit()

     # We can extract the richest alternative in order to display it:
     richest = msg.get_body()
     partfiles = {}
     if richest['content-type'].maintype == 'text':
         if richest['content-type'].subtype == 'plain':
             for line in richest.get_content().splitlines():
                 print(line)
             sys.exit()
         elif richest['content-type'].subtype == 'html':
             body = richest
         else:
             print("Don't know how to display {}".format(richest.get_content_type()))
             sys.exit()
     elif richest['content-type'].content_type == 'multipart/related':
         body = richest.get_body(preferencelist=('html'))
         for part in richest.iter_attachments():
             fn = part.get_filename()
             if fn:
                 extension = os.path.splitext(part.get_filename())[1]
             else:
                 extension = mimetypes.guess_extension(part.get_content_type())
             with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f:
                 f.write(part.get_content())
                 # again strip the <> to go from email form of cid to html form.
                 partfiles[part['content-id'][1:-1]] = f.name
     else:
         print("Don't know how to display {}".format(richest.get_content_type()))
         sys.exit()
     with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
         # The magic_html_parser has to rewrite the href="cid:...." attributes to
         # point to the filenames in partfiles.  It also has to do a safety-sanitize
         # of the html.  It could be written using html.parser.
         f.write(magic_html_parser(body.get_content(), partfiles))
     webbrowser.open(f.name)
     os.remove(f.name)
     for fn in partfiles.values():
         os.remove(fn)

     # Of course, there are lots of email messages that could break this simple
     # minded program, but it will handle the most common ones.

直到输出提示，上面的输出是：

     To: Penelope Pussycat <penelope@example.com>, Fabrette Pussycat <fabrette@example.com>
     From: Pepé Le Pew <pepe@example.com>
     Subject: Ayons asperges pour le déjeuner

     Salut!

     Cela ressemble à un excellent recipie[1] déjeuner.

备注
....

旧式 API:

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc822.html

   (2) (1) 感谢 Matthew Dixon Cowles 提供最初的灵感和示例。


File: python.info,  Node: email message Message 使用 compat32 API 来表示电子邮件消息,  Next: email mime 从头创建电子邮件和 MIME 对象,  Prev: email 示例,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.13 ‘email.message.Message’: 使用 ‘compat32’ API 来表示电子邮件消息
.........................................................................

*note Message: 54a. 类与 *note EmailMessage: 54b. 类非常相似，但没有该类
所添加的方法，并且某些方法的默认行为也略有不同。 我们还在这里记录了一些
虽然被 *note EmailMessage: 54b. 类所支持但并不推荐的方法，除非你是在处理
旧有代码。

在其他情况下这两个类的理念和结构都是相同的。

本文档描述了默认 (对于 *note Message: 54a.) 策略 *note Compat32: 9fd. 之
下的行为。 如果你要使用其他策略，你应当改用 *note EmailMessage: 54b. 类
。

电子邮件消息由多个 `标头' 和一个 `载荷' 组成。 标头必须为 RFC 5322(1) 风
格的名称和值，其中字典名和值由冒号分隔。 冒号不是字段名或字段值的组成部
分。 载荷可以是简单的文本消息，或是二进制对象，或是多个子消息的结构化序
列，每个子消息都有自己的标头集合和自己的载荷。 后一种类型的载荷是由具有
‘multipart/*’ 或 ‘message/rfc822’ 等 MIME 类型的消息来指明的。

*note Message: 54a. 对象所提供了概念化模型是由标头组成的有序字典，加上用
于访问标头中的特殊信息以及访问载荷的额外方法，以便能生成消息的序列化版本
，并递归地遍历对象树。 请注意重复的标头是受支持的，但必须使用特殊的方法
来访问它们。

*note Message: 54a. 伪字典以标头名作为索引，标头名必须为 ASCII 值。 字典
的值为应当只包含 ASCII 字符的字符串；对于非 ASCII 输入有一些特殊处理，但
这并不总能产生正确的结果。 标头以保留原大小写的形式存储和返回，但字段名
称匹配对大小写不敏感。 还可能会有一个单独的封包标头，也称 `Unix-From' 标
头或 ‘From_’ 标头。 `载荷' 对于简单消息对象的情况是一个字符串或字节串，
对于 MIME 容器文档的情况 (例如 ‘multipart/*’ 和 ‘message/rfc822’) 则是一
个 *note Message: 54a. 对象。

以下是 *note Message: 54a. 类的方法:

 -- 类: email.message.Message (policy=compat32)

     如果指定了 `policy' (它必须为 *note policy: 75. 类的实例) 则使用它
     所设置的规则来更新和序列化消息的表示形式。 如果未设置 `policy'，则
     使用 *note compat32: 9fd. 策略，该策略会保持对 Python 3.2 版 email
     包的向下兼容性。 更多信息请参阅 *note policy: 75. 文档。

     在 3.3 版更改: 增加了 `policy' 关键字参数。

      -- 方法: as_string (unixfrom=False, maxheaderlen=0, policy=None)

          以展平的字符串形式返回整个消息对象。 或可选的 `unixfrom' 为真
          值，返回的字符串会包括封包标头。 `unixfrom' 的默认值是
          ‘False’。 出于保持向下兼容性的原因，`maxheaderlen' 的默认值是
          ‘0’，因此如果你想要不同的值你必须显式地重载它（在策略中为
          `max_line_length' 指定的值将被此方法忽略）。 `policy' 参数可被
          用于覆盖从消息实例获取的默认策略。 这可以用来对该方法所输出的
          格式进行一些控制，因为指定的 `policy' 将被传递给 ‘Generator’。

          如果需要填充默认值以完成对字符串的转换则展平消息可能触发对
          *note Message: 54a. 的修改（例如，MIME 边界可能会被生成或被修
          改）。

          请注意此方法是出于便捷原因提供的，可能无法总是以你想要的方式格
          式化消息。 例如，在默认情况下它不会按 unix mbox 格式的要求对以
          ‘From’ 打头的行执行调整。 为了获得更高灵活性，请实例化一个
          *note Generator: b54. 实例并直接使用其 *note flatten(): 2833.
          方法。 例如:

               from io import StringIO
               from email.generator import Generator
               fp = StringIO()
               g = Generator(fp, mangle_from_=True, maxheaderlen=60)
               g.flatten(msg)
               text = fp.getvalue()

          如果消息对象包含未按照 RFC 标准进行编码的二进制数据，则这些不
          合规数据将被 unicode "unknown character" 码位值所替代。 （另请
          参阅 *note as_bytes(): 849. 和 *note BytesGenerator: b55.。）

          在 3.4 版更改: 增加了 `policy' 关键字参数。

      -- 方法: __str__ ()

          与 *note as_string(): 848. 等价。 这将让 ‘str(msg)’ 产生一个包
          含已格式化消息的字符号。

      -- 方法: as_bytes (unixfrom=False, policy=None)

          以字节串对象的形式返回整个扁平化后的消息。 当可选的 `unixfrom'
          为真值时，返回的字符串会包括封包标头。 `unixfrom' 的默认值为
          ‘False’。 `policy' 参数可被用于重载从消息实例获取的默认策略。
          这可被用来控制该方法所产生的部分格式化效果，因为指定的
          `policy' 将被传递给 ‘BytesGenerator’。

          如果需要填充默认值以完成对字符串的转换则展平消息可能触发对
          *note Message: 54a. 的修改（例如，MIME 边界可能会被生成或被修
          改）。

          请注意此方法是出于便捷原因提供的，可能无法总是以你想要的方式格
          式化消息。 例如，在默认情况下它不会按 unix mbox 格式的要求对以
          ‘From’ 打头的行执行调整。 为了获得更高灵活性，请实例化一个
          *note BytesGenerator: b55. 实例并直接使用其 *note flatten():
          282f. 方法。 例如:

               from io import BytesIO
               from email.generator import BytesGenerator
               fp = BytesIO()
               g = BytesGenerator(fp, mangle_from_=True, maxheaderlen=60)
               g.flatten(msg)
               text = fp.getvalue()

          3.4 新版功能.

      -- 方法: __bytes__ ()

          与 *note as_bytes(): 849. 等价。 这将让 ‘bytes(msg)’ 产生一个
          包含已格式化消息的字节串对象。

          3.4 新版功能.

      -- 方法: is_multipart ()

          如果该消息的载荷是一个子 *note Message: 54a. 对象列表则返回
          ‘True’，否则返回 ‘False’。 当 *note is_multipart(): 2809. 返回
          ‘False’ 时，载荷应当是一个字符串对象（有可能是一个 CTE 编码的
          二进制载荷）。 （请注意 *note is_multipart(): 2809. 返回
          ‘True’ 并不意味着 "msg.get_content_maintype() == ’multipart’"
          将返回 ‘True’。 例如，‘is_multipart’ 在 *note Message: 54a. 类
          型为 ‘message/rfc822’ 时也将返回 ‘True’。）

      -- 方法: set_unixfrom (unixfrom)

          将消息的封包标头设为 `unixfrom'，这应当是一个字符串。

      -- 方法: get_unixfrom ()

          返回消息的信封头。如果信封头从未被设置过，默认返回 ‘None’ 。

      -- 方法: attach (payload)

          将给定的 `payload' 添加到当前载荷中，当前载荷在该调用之前必须
          为 ‘None’ 或是一个 *note Message: 54a. 对象列表。 在调用之后，
          此载荷将总是一个 *note Message: 54a. 对象列表。 如果你想将此载
          荷设为一个标量对象（如字符串），请改用 *note set_payload():
          2899.。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它的功能已被 *note
          set_content(): 2811. 及相应的 ‘make’ 和 ‘add’ 方法所替代。

      -- 方法: get_payload (i=None, decode=False)

          返回当前的载荷，它在 *note is_multipart(): 2809. 为 ‘True’ 时
          将是一个 *note Message: 54a. 对象列表，在 *note
          is_multipart(): 2809. 为 ‘False’ 时则是一个字符串。 如果该载荷
          是一个列表且你修改了这个列表对象，那么你就是原地修改了消息的载
          荷。

          传入可选参数 `i' 时，如果 *note is_multipart(): 2809. 为
          ‘True’，*note get_payload(): b53. 将返回载荷从零开始计数的第
          `i' 个元素。 如果 `i' 小于 0 或大于等于载荷中的条目数则将引发
          *note IndexError: e7d.。 如果载荷是一个字符串 (即 *note
          is_multipart(): 2809. 为 ‘False’) 且给出了 `i'，则会引发 *note
          TypeError: 193.。

          可选的 `decode' 是一个指明载荷是否应根据
          ‘Content-Transfer-Encoding’ 标头被解码的旗标。 当其值为 ‘True’
          且消息没有多个部分时，如果此标头值为 ‘quoted-printable’ 或
          ‘base64’ 则载荷将被解码。 如果使用了其他编码格式，或者找不到
          ‘Content-Transfer-Encoding’ 标头时，载荷将被原样返回（不编码）
          。 在所有情况下返回值都是二进制数据。 如果消息有多个部分且
          `decode' 旗标为 ‘True’，则将返回 ‘None’。 如果载荷为 base64 但
          内容不完全正确（如缺少填充符、存在 base64 字母表以外的字符等）
          ，则将在消息的缺陷属性中添加适当的缺陷值 (分别为
          ‘InvalidBase64PaddingDefect’ 或
          ‘InvalidBase64CharactersDefect’)。

          当 `decode' 为 ‘False’ (默认值) 时消息体会作为字符串返回而不解
          码 ‘Content-Transfer-Encoding’。 但是，对于
          ‘Content-Transfer-Encoding’ 为 8bit 的情况，会尝试使用
          ‘Content-Type’ 标头指定的 ‘charset’ 来解码原始字节串，并使用
          ‘replace’ 错误处理程序。 如果未指定 ‘charset’，或者如果指定的
          ‘charset’ 未被 email 包所识别，则会使用默认的 ASCII 字符集来解
          码消息体。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它的功能已被 *note
          get_content(): 280f. 和 *note iter_parts(): 280e. 方法所替代。

      -- 方法: set_payload (payload, charset=None)

          将整个消息对象的载荷设为 `payload'。 客户端要负责确保载荷的不
          变性。 可选的 `charset' 用于设置消息的默认字符集；详情请参阅
          *note set_charset(): 289a.。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它的功能已被 *note
          set_content(): 2811. 方法所替代。

      -- 方法: set_charset (charset)

          将载荷的字符集设为 `charset'，它可以是 *note Charset: 6dd. 实
          例 (参见 *note email.charset: 6a.)、字符集名称字符串或 ‘None’。
          如果是字符串，它将被转换为一个 *note Charset: 6dd. 实例。 如果
          `charset' 是 ‘None’，‘charset’ 形参将从 ‘Content-Type’ 标头中
          被删除（消息将不会进行其他修改）。 任何其他值都将导致 *note
          TypeError: 193.。

          如果 ‘MIME-Version’ 标头不存在则将被添加。 如果 ‘Content-Type’
          标头不存在，则将添加一个值为 ‘text/plain’ 的该标头。 无论
          ‘Content-Type’ 标头是否已存在，其 ‘charset’ 形参都将被设为
          `charset.output_charset'。 如果 `charset.input_charset' 和
          `charset.output_charset' 不同，则载荷将被重编码为
          `output_charset'。 如果 ‘Content-Transfer-Encoding’ 标头不存在
          ，则载荷将在必要时使用指定的 *note Charset: 6dd. 来转换编码，
          并将添加一个具有相应值的标头。 如果
          ‘Content-Transfer-Encoding’ 标头已存在，则会假定载荷已使用该
          ‘Content-Transfer-Encoding’ 进行正确编码并不会再被修改。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它的功能已被
          ‘email.emailmessage.EmailMessage.set_content()’ 方法的
          `charset' 形参所替代。

      -- 方法: get_charset ()

          返回与消息的载荷相关联的 *note Charset: 6dd. 实例。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它将总是返回
          ‘None’。

     以下方法实现了用于访问消息的 RFC 2822(2) 标头的类映射接口。 请注意
     这些方法和普通映射（例如字典）接口之间存在一些语义上的不同。 举例来
     说，在一个字典中不能有重复的键，但消息标头则可能有重复。 并且，在字
     典中由 *note keys(): 289c. 返回的键的顺序是没有保证的，但在 *note
     Message: 54a. 对象中，标头总是会按它们在原始消息中的出现或后继加入
     顺序返回。 任何已删除再重新加入的标头总是会添加到标头列表的末尾。

     这些语义上的差异是有意为之且其目的是为了提供最大的便利性。

     还请留意，无论在什么情况下，消息当中的任何信封头字段都不会包含在映
     射接口当中。

     在由字节串生成的模型中，任何包含非 ASCII 字节数据（违反 RFC）的标头
     值当通过此接口来获取时，将被表示为使用 ‘unknown-8bit’ 字符集的
     *note Header: 2855. 对象。

      -- 方法: __len__ ()

          返回头字段的总数，重复的也计算在内。

      -- 方法: __contains__ (name)

          如果消息对象中有一个名为 `name' 的字段则返回 ‘True’。 匹配操作
          对大小写不敏感并且 `name' 不应包括末尾的冒号。 用于 ‘in’ 运算
          符，例如:

               if 'message-id' in myMessage:
                  print('Message-ID:', myMessage['message-id'])

      -- 方法: __getitem__ (name)

          返回指定名称标头字段的值。 `name' 不应包括作为字段分隔符的冒号
          。 如果标头未找到，则返回 ‘None’；*note KeyError: 2c8. 永远不
          会被引发。

          请注意如果指定名称的字段在消息标头中多次出现，具体将返回哪个字
          段值是未定义的。 请使用 *note get_all(): 28a0. 方法来获取所有
          指定名称标头的值。

      -- 方法: __setitem__ (name, val)

          将具有字段名 `name' 和值 `val' 的标头添加到消息中。 字段会被添
          加到消息的现有字段的末尾。

          请注意，这个方法 `既不会' 覆盖 `也不会' 删除任何字段名重名的已
          有字段。如果你确实想保证新字段是整个信息头当中唯一拥有 `name'
          字段名的字段，你需要先把旧字段删除。例如：

               del msg['subject']
               msg['subject'] = 'Python roolz!'

      -- 方法: __delitem__ (name)

          删除信息头当中字段名匹配 `name' 的所有字段。如果匹配指定名称的
          字段没有找到，也不会抛出任何异常。

      -- 方法: keys ()

          以列表形式返回消息头中所有的字段名。

      -- 方法: values ()

          以列表形式返回消息头中所有的字段值。

      -- 方法: items ()

          以二元元组的列表形式返回消息头中所有的字段名和字段值。

      -- 方法: get (name, failobj=None)

          返回指定名称标头字段的值。 这与 *note __getitem__(): 289f. 是
          一样的，不同之处在于如果指定名称标头未找到则会返回可选的
          `failobj' (默认为 ‘None’)。

     以下是一些有用的附加方法:

      -- 方法: get_all (name, failobj=None)

          返回字段名为 `name' 的所有字段值的列表。如果信息内不存在匹配的
          字段，返回 `failobj' （其默认值为 ‘None’ ）。

      -- 方法: add_header (_name, _value, **_params)

          高级头字段设定。这个方法与 *note __setitem__(): 28a1. 类似，不
          过你可以使用关键字参数为字段提供附加参数。 `_name' 是字段名，
          `_value' 是字段 `主' 值。

          对于关键字参数字典 `_params' 中的每一项，其键会被当作形参名，
          并执行下划线和连字符间的转换（因为连字符不是合法的 Python 标识
          符）。 通常，形参将以 ‘key="value"’ 的形式添加，除非值为
          ‘None’，在这种情况下将只添加键。 如果值包含非 ASCII 字符，可将
          其指定为格式为 ‘(CHARSET, LANGUAGE, VALUE)’ 的三元组，其中
          ‘CHARSET’ 为要用来编码值的字符集名称字符串，‘LANGUAGE’ 通常可
          设为 ‘None’ 或空字符串（请参阅 RFC 2231(3) 了解其他可能的取值
          ），而 ‘VALUE’ 为包含非 ASCII 码位的字符串值。 如果不是传入一
          个三元组且值包含非 ASCII 字符，则会自动以 RFC 2231(4) 格式使用
          ‘CHARSET’ 为 ‘utf-8’ 和 ‘LANGUAGE’ 为 ‘None’ 对其进行编码。

          以下是为示例代码:

               msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')

          会添加一个形如下文的头字段：

               Content-Disposition: attachment; filename="bud.gif"

          使用非 ASCII 字符的示例代码:

               msg.add_header('Content-Disposition', 'attachment',
                              filename=('iso-8859-1', '', 'Fußballer.ppt'))

          它的输出结果为

               Content-Disposition: attachment; filename*="iso-8859-1''Fu%DFballer.ppt"

      -- 方法: replace_header (_name, _value)

          替换一个标头。 将替换在匹配 `_name' 的消息中找到的第一个标头，
          标头顺序和字段名大小写保持不变。 如果未找到匹配的标头，则会引
          发 *note KeyError: 2c8.。

      -- 方法: get_content_type ()

          返回消息的内容类型。 返回的字符串会强制转换为
          ‘maintype/subtype’ 的全小写形式。 如果消息中没有
          ‘Content-Type’ 标头则将返回由 *note get_default_type(): 28a9.
          给出的默认类型。 因为根据 RFC 2045(5)，消息总是要有一个默认类
          型，所以 *note get_content_type(): 28a8. 将总是返回一个值。

          RFC 2045(6) 将消息的默认类型定义为 ‘text/plain’，除非它是出现
          在 ‘multipart/digest’ 容器内，在这种情况下其类型应为
          ‘message/rfc822’。 如果 ‘Content-Type’ 标头指定了无效的类型，
          RFC 2045(7) 规定其默认类型应为 ‘text/plain’。

      -- 方法: get_content_maintype ()

          返回信息的主要内容类型。准确来说，此方法返回的是 *note
          get_content_type(): 28a8. 方法所返回的形如 ‘maintype/subtype’
          的字符串当中的 ‘maintype’ 部分。

      -- 方法: get_content_subtype ()

          返回信息的子内容类型。准确来说，此方法返回的是 *note
          get_content_type(): 28a8. 方法所返回的形如 ‘maintype/subtype’
          的字符串当中的 ‘subtype’ 部分。

      -- 方法: get_default_type ()

          返回默认的内容类型。绝大多数的信息，其默认内容类型都是
          ‘text/plain’ 。作为 ‘multipart/digest’ 容器内子部分的信息除外
          ，它们的默认内容类型是 ‘message/rfc822’ 。

      -- 方法: set_default_type (ctype)

          设置默认的内容类型。 `ctype' 应当为 ‘text/plain’ 或者
          ‘message/rfc822’，尽管这并非强制。 默认的内容类型不会存储在
          ‘Content-Type’ 标头中。

      -- 方法: get_params (failobj=None, header='content-type',
               unquote=True)

          将消息的 ‘Content-Type’ 形参作为列表返回。 所返回列表的元素为
          以 ‘'='’ 号拆分出的键/值对 2 元组。 ‘'='’ 左侧的为键，右侧的为
          值。 如果形参值中没有 ‘'='’ 号，否则该将值如 *note
          get_param(): 28ae. 描述并且在可选 `unquote' 为 ‘True’ (默认值)
          时会被取消转义。

          可选的 `failobj' 是在没有 ‘Content-Type’ 标头时要返回的对象。
          可选的 `header' 是要替代 ‘Content-Type’ 被搜索的标头。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它的功能已被标头访
          问方法所返回的单独标头对象的 `params' 特征属性所替代。

      -- 方法: get_param (param, failobj=None, header='content-type',
               unquote=True)

          将 ‘Content-Type’ 标头的形参 `param' 作为字符串返回。 如果消息
          没有 ‘Content-Type’ 标头或者没有这样的形参，则返回 `failobj'
          (默认为 ‘None’)。

          如果给出可选的 `header'，它会指定要替代 ‘Content-Type’ 来使用
          的消息标头。

          形参的键总是以大小写不敏感的方式来比较的。 返回值可以是一个字
          符串，或者如果形参以 RFC 2231(8) 编码则是一个 3 元组。 当为 3
          元组时，值中的元素采用 ‘(CHARSET, LANGUAGE, VALUE)’ 的形式。 请
          注意 ‘CHARSET’ 和 ‘LANGUAGE’ 都可以为 ‘None’，在此情况下你应当
          将 ‘VALUE’ 当作以 ‘us-ascii’ 字符集来编码。 你可以总是忽略
          ‘LANGUAGE’。

          如果你的应用不关心形参是否以 RFC 2231(9) 来编码，你可以通过调
          用 *note email.utils.collapse_rfc2231_value(): 28af. 来展平形
          参值，传入来自 *note get_param(): 28ae. 的返回值。 当值为元组
          时这将返回一个经适当编码的 Unicode 字符串，否则返回未经转义的
          原字符串。 例如:

               rawparam = msg.get_param('foo')
               param = email.utils.collapse_rfc2231_value(rawparam)

          无论在哪种情况下，形参值（或为返回的字符串，或为 3 元组形式的
          ‘VALUE’ 条目）总是未经转换的，除非 `unquote' 被设为 ‘False’。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它的功能已被标头访
          问方法所返回的单独标头对象的 `params' 特征属性所替代。

      -- 方法: set_param (param, value, header='Content-Type',
               requote=True, charset=None, language='', replace=False)

          在 ‘Content-Type’ 标头中设置一个形参。 如果该形参已存在于标头
          中，它的值将被替换为 `value'。 如果此消息还未定义
          ‘Content-Type’ 标头，它将被设为 ‘text/plain’ 且新的形参值将按
          RFC 2045(10) 的要求添加。

          可选的 `header' 指定一个 ‘Content-Type’ 的替代标头，并且所有形
          参将根据需要被转换，除非可选的 `requote' 为 ‘False’ (默认为
          ‘True’)。

          如果指定了可选的 `charset'，形参将按照 RFC 2231(11) 来编码。 可
          选的 `language' 指定了 RFC 2231 的语言，默认为空字符串。
          `charset' 和 `language' 都应为字符串。

          如果 `replace' 为 ‘False’ （默认值），该头字段会被移动到所有头
          字段的末尾。如果 `replace' 为 ‘True’ ，字段会被原地更新。

          在 3.4 版更改: 添加了 ‘replace’ 关键字。

      -- 方法: del_param (param, header='content-type', requote=True)

          从 ‘Content-Type’ 标头中完全移除给定的形参。 标头将被原地重写
          并不带该形参或它的值。 所有的值将根据需要被转换，除非
          `requote' 为 ‘False’ (默认为 ‘True’)。 可选的 `header' 指定
          ‘Content-Type’ 的一个替代项。

      -- 方法: set_type (type, header='Content-Type', requote=True)

          设置 ‘Content-Type’ 标头的主类型和子类型。 `type' 必须为
          ‘maintype/subtype’ 形式的字符串，否则会引发 *note ValueError:
          1fc.。

          此方法可替换 ‘Content-Type’ 标头，并保持所有形参不变。 如果
          `requote' 为 ‘False’，这会保持原有标头引用转换不变，否则形参将
          被引用转换（默认行为）。

          可以在 `header' 参数中指定一个替代标头。 当 ‘Content-Type’ 标
          头被设置时也会添加一个 ‘MIME-Version’ 标头。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它的功能已被
          ‘make_’ 和 ‘add_’ 方法所替代。

      -- 方法: get_filename (failobj=None)

          返回信息头当中 ‘Content-Disposition’ 字段当中名为 ‘filename’ 的
          参数值。如果该字段当中没有此参数，该方法会退而寻找
          ‘Content-Type’ 字段当中的 ‘name’ 参数值。如果这个也没有找到，
          或者这些个字段压根就不存在，返回 `failobj' 。返回的字符串永远
          按照 *note email.utils.unquote(): 2802. 方法去除引号。

      -- 方法: get_boundary (failobj=None)

          返回信息头当中 ‘Content-Type’ 字段当中名为 ‘boundary’ 的参数值
          。如果字段当中没有此参数，或者这些个字段压根就不存在，返回
          `failobj' 。返回的字符串永远按照 *note email.utils.unquote():
          2802. 方法去除引号。

      -- 方法: set_boundary (boundary)

          将 ‘Content-Type’ 头字段的 ‘boundary’ 参数设置为 `boundary' 。
          *note set_boundary(): 28b4. 方法永远都会在必要的时候为
          `boundary' 添加引号。如果信息对象中没有 ‘Content-Type’ 头字段
          ，抛出 *note HeaderParseError: 2805. 异常。

          请注意使用这个方法与删除旧的 ‘Content-Type’ 标头并通过 *note
          add_header(): 28a6. 添加一个带有新边界的新标头有细微的差异，因
          为 *note set_boundary(): 28b4. 会保留 ‘Content-Type’ 标头在原
          标头列表中的顺序。 但是，它 `不会' 保留原 ‘Content-Type’ 标头
          中可能存在的任何连续的行。

      -- 方法: get_content_charset (failobj=None)

          返回 ‘Content-Type’ 头字段中的 ‘charset’ 参数，强制小写。如果
          字段当中没有此参数，或者这个字段压根不存在，返回 `failobj' 。

          请注意此方法不同于 *note get_charset(): 289b.，后者会返回
          *note Charset: 6dd. 实例作为消息体的默认编码格式。

      -- 方法: get_charsets (failobj=None)

          返回一个包含了信息内所有字符集名字的列表。如果信息是
          ‘multipart’ 类型的，那么列表当中的每一项都对应其负载的子部分的
          字符集名字。否则，该列表是一个长度为1的列表。

          列表中的每一项都是字符串，它们是其所表示的子部分的
          ‘Content-Type’ 标头中 ‘charset’ 形参的值。 但是，如果该子部分
          没有 ‘Content-Type’ 标头，或没有 ‘charset’ 形参，或者主 MIME 类
          型不是 ‘text’，则所返回列表中的对应项将为 `failobj'。

      -- 方法: get_content_disposition ()

          如果信息的 ‘Content-Disposition’ 头字段存在，返回其字段值；否
          则返回 ‘None’ 。返回的值均为小写，不包含参数。如果信息遵循 RFC
          2183(12) 标准，则返回值只可能在 `inline' 、 `attachment' 和
          ‘None’ 之间选择。

          3.5 新版功能.

      -- 方法: walk ()

          *note walk(): 28b7. 方法是一个多功能生成器。它可以被用来以深度
          优先顺序遍历信息对象树的所有部分和子部分。一般而言， *note
          walk(): 28b7. 会被用作 ‘for’ 循环的迭代器，每一次迭代都返回其
          下一个子部分。

          以下例子会打印出一封具有多部分结构之信息的每个部分的 MIME 类型
          。

               >>> for part in msg.walk():
               ...     print(part.get_content_type())
               multipart/report
               text/plain
               message/delivery-status
               text/plain
               text/plain
               message/rfc822
               text/plain

          ‘walk’ 会遍历所有 *note is_multipart(): 2809. 方法返回 ‘True’
          的部分之子部分，哪怕 ‘msg.get_content_maintype() ==
          'multipart'’ 返回的是 ‘False’ 。使用 ‘_structure’ 除错帮助函数
          可以帮助我们在下面这个例子当中看清楚这一点：

               >>> for part in msg.walk():
               ...     print(part.get_content_maintype() == 'multipart',
               ...           part.is_multipart())
               True True
               False False
               False True
               False False
               False False
               False True
               False False
               >>> _structure(msg)
               multipart/report
                   text/plain
                   message/delivery-status
                       text/plain
                       text/plain
                   message/rfc822
                       text/plain

          在这里， ‘message’ 的部分并非 ‘multiparts’ ，但是它们真的包含
          子部分！ ‘is_multipart()’ 返回 ‘True’ ， ‘walk’ 也深入进这些子
          部分中。

     *note Message: 54a. 对象也可以包含两个可选的实例属性，它们可被用于
     生成纯文本的 MIME 消息。

      -- 属性: preamble

          MIME 文档格式在标头之后的空白行以及第一个多部分的分界字符串之
          间允许添加一些文本， 通常，此文本在支持 MIME 的邮件阅读器中永
          远不可见，因为它处在标准 MIME 防护范围之外。 但是，当查看消息
          的原始文本，或当在不支持 MIME 的阅读器中查看消息时，此文本会变
          得可见。

          `preamble' 属性包含 MIME 文档开头部分的这些处于保护范围之外的
          文本。 当 *note Parser: b20. 在标头之后及第一个分界字符串之前
          发现一些文本时，它会将这些文本赋值给消息的 `preamble' 属性。 当
          *note Generator: b54. 写出 MIME 消息的纯文本表示形式时，如果它
          发现消息具有 `preamble' 属性，它将在标头及第一个分界之间区域写
          出这些文本。 请参阅 *note email.parser: 74. 和 *note
          email.generator: 6e. 了解更多细节。

          请注意如果消息对象没有前导文本，则 `preamble' 属性将为 ‘None’。

      -- 属性: epilogue

          `epilogue' 属性的作用方式与 `preamble' 属性相同，区别在于它包
          含出现于最后一个分界与消息结尾之间的文本。

          你不需要将 epilogue 设为空字符串以便让 *note Generator: b54. 在
          文件末尾打印一个换行符。

      -- 属性: defects

          `defects' 属性包含在解析消息时发现的所有问题的列表。 请参阅
          *note email.errors: 6d. 了解可能的解析缺陷的详细描述。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc5322.html

   (2) https://tools.ietf.org/html/rfc2822.html

   (3) https://tools.ietf.org/html/rfc2231.html

   (4) https://tools.ietf.org/html/rfc2231.html

   (5) https://tools.ietf.org/html/rfc2045.html

   (6) https://tools.ietf.org/html/rfc2045.html

   (7) https://tools.ietf.org/html/rfc2045.html

   (8) https://tools.ietf.org/html/rfc2231.html

   (9) https://tools.ietf.org/html/rfc2231.html

   (10) https://tools.ietf.org/html/rfc2045.html

   (11) https://tools.ietf.org/html/rfc2231.html

   (12) https://tools.ietf.org/html/rfc2183.html


File: python.info,  Node: email mime 从头创建电子邮件和 MIME 对象,  Next: email header 国际化标头,  Prev: email message Message 使用 compat32 API 来表示电子邮件消息,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.14 ‘email.mime’: 从头创建电子邮件和 MIME 对象
....................................................

`源代码:' Lib/email/mime/(1)

__________________________________________________________________

此模块是旧版 (‘Compat32’) 电子邮件 API 的组成部分。 它的功能在新版 API 中
被 *note contentmanager: 6b. 部分替代，但在某些应用中这些类仍可能有用，
即使是在非旧版代码中。

通常，你是通过传递一个文件或一些文本到解析器来获得消息对象结构体的，解析
器会解析文本并返回根消息对象。 不过你也可以从头开始构建一个完整的消息结
构体，甚至是手动构建单独的 *note Message: 54a. 对象。 实际上，你也可以接
受一个现有的结构体并添加新的 *note Message: 54a. 对象并移动它们。 这为切
片和分割 MIME 消息提供了非常方便的接口。

你可以通过创建 *note Message: 54a. 实例并手动添加附件和所有适当的标头来
创建一个新的对象结构体。 不过对于 MIME 消息来说，*note email: 69. 包提供
了一些便捷子类来让事情变得更容易。

这些类列示如下:

 -- 类: email.mime.base.MIMEBase (_maintype, _subtype, *,
          policy=compat32, **_params)

     模块: ‘email.mime.base’

     这是 *note Message: 54a. 的所有 MIME 专属子类。 通常你不会创建专门
     的 *note MIMEBase: 28bd. 实例，尽管你可以这样做。 *note MIMEBase:
     28bd. 主要被提供用来作为更具体的 MIME 感知子类的便捷基类。

     `_maintype' 是 ‘Content-Type’ 的主类型 (例如 ‘text’ 或 ‘image’)，而
     `_subtype' 是 ‘Content-Type’ 的次类型 (例如 ‘plain’ 或 ‘gif’)。
     `_params' 是一个形参键/值字典并会被直接传递给 *note
     Message.add_header: 28a6.。

     如果指定了 `policy' (默认为 *note compat32: 9fd. 策略)，它将被传递
     给 *note Message: 54a.。

     *note MIMEBase: 28bd. 类总是会添加一个 ‘Content-Type’ 标头 (基于
     `_maintype', `_subtype' 和 `_params')，以及一个 ‘MIME-Version’ 标头
     (总是设为 ‘1.0’)。

     在 3.6 版更改: 添加了 `policy' 仅限关键字形参。

 -- 类: email.mime.nonmultipart.MIMENonMultipart

     模块: ‘email.mime.nonmultipart’

     *note MIMEBase: 28bd. 的子类，这是用于非 ‘multipart’ MIME 消息的中
     间基类。 这个类的主要目标是避免使用 *note attach(): 2817. 方法，该
     方法仅对 ‘multipart’ 消息有意义。 如果 *note attach(): 2817. 被调用
     ，则会引发 *note MultipartConversionError: 285d. 异常。

 -- 类: email.mime.multipart.MIMEMultipart (_subtype='mixed',
          boundary=None, _subparts=None, *, policy=compat32, **_params)

     模块: ‘email.mime.multipart’

     *note MIMEBase: 28bd. 的子类，这是用于 ‘multipart’ MIME 消息的中间
     基类。 可选的 `_subtype' 默认为 ‘mixed’，但可被用来指定消息的子类型
     。 将会在消息对象中添加一个:mimetype:‘multipart/_subtype’ 的
     ‘Content-Type’ 标头。 并还将添加一个 ‘MIME-Version’ 标头。

     可选的 `boundary' 是多部分边界字符串。 当为 ‘None’ (默认值) 时，则
     会在必要时（例如当消息被序列化时）计算边界。

     `_subparts' 是载荷初始子部分的序列。 此序列必须可以被转换为列表。 你
     总是可以使用 *note Message.attach: 2817. 方法将新的子部分附加到消息
     中。

     可选的 `policy' 参数默认为 *note compat32: 9fd.。

     用于 ‘Content-Type’ 标头的附加形参会从关键字参数中获取，或者传入到
     `_params' 参数，该参数是一个关键字的字典。

     在 3.6 版更改: 添加了 `policy' 仅限关键字形参。

 -- 类: email.mime.application.MIMEApplication (_data,
          _subtype='octet-stream',
          _encoder=email.encoders.encode_base64, *, policy=compat32,
          **_params)

     模块: ‘email.mime.application’

     *note MIMENonMultipart: 285e. 的子类，*note MIMEApplication: 28bf.
     类被用来表示主类型为 ‘application’ 的 MIME 消息。 `_data' 是包含原
     始字节数据的字符串。 可选的 `_subtype' 指定 MIME 子类型并默认为
     ‘octet-stream’。

     可选的 `_encoder' 是一个可调用对象（即函数），它将执行实际的数据编
     码以便传输。 这个可调用对象接受一个参数，该参数是 *note
     MIMEApplication: 28bf. 的实例。 它应当使用 *note get_payload():
     b53. 和 *note set_payload(): 2899. 来将载荷改为已编码形式。 它还应
     根据需要将任何 ‘Content-Transfer-Encoding’ 或其他标头添加到消息对象
     中。 默认编码格式为 base64。 请参阅 *note email.encoders: 6c. 模块
     来查看内置编码器列表。

     可选的 `policy' 参数默认为 *note compat32: 9fd.。

     `_params' 会被直接传递给基类的构造器。

     在 3.6 版更改: 添加了 `policy' 仅限关键字形参。

 -- 类: email.mime.audio.MIMEAudio (_audiodata, _subtype=None,
          _encoder=email.encoders.encode_base64, *, policy=compat32,
          **_params)

     模块: ‘email.mime.audio’

     *note MIMENonMultipart: 285e. 的子类，*note MIMEAudio: 28c0. 类被用
     来创建主类型为 ‘audio’ 的 MIME 消息。 `_audiodata' 是包含原始音频数
     据的字符串。 如果此数据可由标准 Python 模块 *note sndhdr: ef. 来编
     码，则其子类型将被自动包括在 ‘Content-Type’ 标头。 在其他情况下你可
     以通过 `_subtype' 参数显式地指定音频子类型 。 如果无法猜测出主类型
     并且未给出 `_subtype'，则会引发 *note TypeError: 193.。

     可选的 `_encoder' 是一个可调用对象（即函数），它将执行实际的音频数
     据编码以便传输。 这个可调用对象接受一个参数，该参数是 *note
     MIMEAudio: 28c0. 的实例。 它应当使用 *note get_payload(): b53. 和
     *note set_payload(): 2899. 来将载荷改为已编码形式。 它还应根据需要
     将任何 ‘Content-Transfer-Encoding’ 或其他标头添加到消息对象中。 默
     认编码格式为 base64。 请参阅 *note email.encoders: 6c. 模块来查看内
     置编码器列表。

     可选的 `policy' 参数默认为 *note compat32: 9fd.。

     `_params' 会被直接传递给基类的构造器。

     在 3.6 版更改: 添加了 `policy' 仅限关键字形参。

 -- 类: email.mime.image.MIMEImage (_imagedata, _subtype=None,
          _encoder=email.encoders.encode_base64, *, policy=compat32,
          **_params)

     模块: ‘email.mime.image’

     *note MIMENonMultipart: 285e. 的子类，*note MIMEImage: 285f. 类被用
     来创建主类型为 ‘image’ 的 MIME 消息对象。 `_imagedata' 是包含原始图
     像数据的字符串。 如果此数据可由标准 Python 模块 *note imghdr: 99. 来
     解码，则其子类型将被自动包括在 ‘Content-Type’ 标头中。 在其他情况下
     你可以通过 `_subtype' 参数显式地指定图像子类型。 如果无法猜测出主类
     型并且未给出 `_subtype'，则会引发 *note TypeError: 193.。

     可选的 `_encoder' 是一个可调用对象（即函数），它将执行实际的图像数
     据编码以便传输。 这个可调用对象接受一个参数，该参数是 *note
     MIMEImage: 285f. 的实例。 它应当使用 *note get_payload(): b53. 和
     *note set_payload(): 2899. 来将载荷改为已编码形式。 它还应根据需要
     将任何 ‘Content-Transfer-Encoding’ 或其他标头添加到消息对象中。 默
     认编码格式为 base64。 请参阅 *note email.encoders: 6c. 模块来查看内
     置编码器列表。

     可选的 `policy' 参数默认为 *note compat32: 9fd.。

     `_params' 会被直接传递给 *note MIMEBase: 28bd. 构造器。

     在 3.6 版更改: 添加了 `policy' 仅限关键字形参。

 -- 类: email.mime.message.MIMEMessage (_msg, _subtype='rfc822', *,
          policy=compat32)

     模块: ‘email.mime.message’

     *note MIMENonMultipart: 285e. 的子类，*note MIMEMessage: 28c1. 类被
     用来创建主类型为 ‘message’ 的 MIME 对象。 `_msg' 将被用作载荷，并且
     必须为 *note Message: 54a. 类（或其子类）的实例，否则会引发 *note
     TypeError: 193.。

     可选的 `_subtype' 设置消息的子类型；它的默认值为 ‘rfc822’。

     可选的 `policy' 参数默认为 *note compat32: 9fd.。

     在 3.6 版更改: 添加了 `policy' 仅限关键字形参。

 -- 类: email.mime.text.MIMEText (_text, _subtype='plain',
          _charset=None, *, policy=compat32)

     模块: ‘email.mime.text’

     *note MIMENonMultipart: 285e. 的子类，*note MIMEText: 6dc. 类被用来
     创建主类型为 ‘text’ 的 MIME 对象。 `_text' 是用作载荷的字符串。
     `_subtype' 指定子类型并且默认为 ‘plain’。 `_charset' 是文本的字符集
     并会作为参数传递给 *note MIMENonMultipart: 285e. 构造器；如果该字符
     串仅包含 ‘ascii’ 码位则其默认值为 ‘us-ascii’，否则为 ‘utf-8’。
     `_charset' 形参接受一个字符串或是一个 *note Charset: 6dd. 实例。

     除非 `_charset' 参数被显式地设为 ‘None’，否则所创建的 MIMEText 对象
     将同时具有附带 ‘charset’ 形参的 ‘Content-Type’ 标头，以及
     ‘Content-Transfer-Encoding’ 标头。 这意味着后续的 ‘set_payload’ 调
     用将不再产生已编码的载荷，即使它在 ‘set_payload’ 命令中被传入。 你
     可以通过删除 ‘Content-Transfer-Encoding’ 标头来“重置”此行为，在此之
     后的 ‘set_payload’ 调用将自动编码新的载荷（并添加新的
     ‘Content-Transfer-Encoding’ 标头）。

     可选的 `policy' 参数默认为 *note compat32: 9fd.。

     在 3.5 版更改: `_charset' 也可接受 *note Charset: 6dd. 实例。

     在 3.6 版更改: 添加了 `policy' 仅限关键字形参。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/email/mime/


File: python.info,  Node: email header 国际化标头,  Next: email charset 表示字符集,  Prev: email mime 从头创建电子邮件和 MIME 对象,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.15 ‘email.header’: 国际化标头
....................................

`源代码:' Lib/email/header.py(1)

__________________________________________________________________

此模块是旧式 (‘Compat32’) email API 的一部分。 在当前的 API 中标头的编码
和解码是由 *note EmailMessage: 54b. 类的字典型 API 来透明地处理的。 除了
在旧有代码中使用，此模块在需要完全控制当编码标头时所使用的字符集时也很有
用处。

本段落中的剩余文本是该模块的原始文档。

RFC 2822(2) 是描述电子邮件消息格式的基础标准。 它派生自更早的 RFC 822(3)
标准，该标准在大多数电子邮件仅由 ASCII 字符组成时已被广泛使用。 RFC
2822(4) 所描述的规范假定电子邮件都只包含 7 位 ASCII 字符。

当然，随着电子邮件在全球部署，它已经变得国际化了，例如电子邮件消息中现在
可以使用特定语言的专属字符集。 这个基础标准仍然要求电子邮件消息只使用 7
位 ASCII 字符来进行传输，为此编写了大量 RFC 来描述如何将包含非 ASCII 字
符的电子邮件编码为符合 RFC 2822(5) 的格式。 这些 RFC 包括 RFC 2045(6),
RFC 2046(7), RFC 2047(8) 和 RFC 2231(9)。 *note email: 69. 包在其 *note
email.header: 6f. 和 *note email.charset: 6a. 模块中支持了这些标准。

如果你想在你的电子邮件标头中包括非 ASCII 字符，比如说是在 ‘Subject’ 或
‘To’ 字段中，你应当使用 *note Header: 2855. 类并将 *note Message: 54a. 对
象中的字段赋值为 *note Header: 2855. 的实例而不是使用字符串作为字段值。
请从 *note email.header: 6f. 模块导入 *note Header: 2855. 类。 例如:

     >>> from email.message import Message
     >>> from email.header import Header
     >>> msg = Message()
     >>> h = Header('p\xf6stal', 'iso-8859-1')
     >>> msg['Subject'] = h
     >>> msg.as_string()
     'Subject: =?iso-8859-1?q?p=F6stal?=\n\n'

是否注意到这里我们是如何希望 ‘Subject’ 字段包含非 ASCII 字符的？ 我们通
过创建一个 *note Header: 2855. 实例并传入字节串编码所用的字符集来做到这
一点。 当后续的 *note Message: 54a. 实例被展平时，‘Subject’ 字段会正确地
按 RFC 2047(10) 来编码。 可感知 MIME 的电子邮件阅读器将会使用嵌入的
ISO-8859-1 字符来显示此标头。

以下是 *note Header: 2855. 类描述:

 -- 类: email.header.Header (s=None, charset=None, maxlinelen=None,
          header_name=None, continuation_ws=' ', errors='strict')

     创建符合 MIME 要求的标头，其中可包含不同字符集的字符串。

     可选的 `s' 是初始标头值。 如果为 ‘None’ (默认值)，则表示初始标头值
     未设置。 你可以在稍后使用 *note append(): 28c4. 方法调用向标头添加
     新值。 `s' 可以是 *note bytes: 33a. 或 *note str: 339. 的实例，注意
     参阅 *note append(): 28c4. 文档了解相关语义。

     可选的 `charset' 用于两种目的：它的含义与 *note append(): 28c4. 方
     法的 `charset' 参数相同。 它还会为所有省略了 `charset' 参数的后续
     *note append(): 28c4. 调用设置默认字符集。 如果 `charset' 在构造器
     中未提供（默认设置），则会将 ‘us-ascii’ 字符集用作 `s' 的初始字符集
     以及后续 *note append(): 28c4. 调用的默认字符集。

     通过 `maxlinelen' 可以显式指定最大行长度。 要将第一行拆分为更短的值
     (以适应未被包括在to account for the field header which isn’t
     included in `s' 中的字段标头，例如 ‘Subject’)，则将字段名称作为
     `header_name' 传入。 `maxlinelen' 默认值为 76，而 `header_name' 默
     认值为 ‘None’，表示不考虑拆分超长标头的第一行。

     可选的 `continuation_ws' 必须为符合 RFC 2822(11) 的折叠用空白符，通
     常是空格符或硬制表符。 这个字符将被加缀至连续行的开头。
     `continuation_ws' 默认为一个空格符。

     可选的 `errors' 会被直接传递给 *note append(): 28c4. 方法。

      -- 方法: append (s, charset=None, errors='strict')

          将字符串 `s' 添加到 MIME 标头。

          如果给出可选的 `charset'，它应当是一个 *note Charset: 6dd. 实
          例 (参见 *note email.charset: 6a.) 或字符集名称，该参数将被转
          换为一个 *note Charset: 6dd. 实例。 如果为 ‘None’ (默认值) 则
          表示会使用构造器中给出的 `charset'。

          `s' 可以是 *note bytes: 33a. 或 *note str: 339. 的实例。 如果
          它是 *note bytes: 33a. 的实例，则 `charset' 为该字节串的编码格
          式，如果字节串无法用该字符集来解码则将引发 *note UnicodeError:
          c43.。

          如果 `s' 是 *note str: 339. 的实例，则 `charset' 是用来指定字
          符串中字符字符集的提示。

          在这两种情况下，当使用 RFC 2047(12) 规则产生符合 RFC 2822(13)
          的标头时，将使用指定字符集的输出编解码器来编码字符串。 如果字
          符串无法使用该输出编解码器来编码，则将引发 UnicodeError。

          可选的 `errors' 会在 `s' 为字节串时被作为 errors 参数传递给
          decode 调用。

      -- 方法: encode (splitchars=';, \t', maxlinelen=None,
               linesep='\n')

          将消息标头编码为符合 RFC 的格式，可能会对过长的行采取折行并将
          非 ASCII 部分以 base64 或 quoted-printable 编码格式进行封装。

          可选的 `splitchars' 是一个字符串，其中包含应在正常的标头折行处
          理期间由拆分算法赋予额外权重的字符。 这是对于 RFC 2822(14) 中
          ’更高层级语法拆分’ 的很粗略的支持：在拆分期间会首选在
          splitchar 之前的拆分点，字符的优先级是基于它们在字符串中的出现
          顺序。 字符串中可包含空格和制表符以指明当其他拆分字符未在被拆
          分行中出现时是否要将某个字符作为优先于另一个字符的首选拆分点。
          拆分字符不会影响以 RFC 2047(15) 编码的行。

          如果给出 `maxlinelen'，它将覆盖实例的最大行长度值。

          `linesep' 指定用来分隔已折叠标头行的字符。 它默认为 Python 应
          用程序代码中最常用的值 (‘\n’)，但也可以指定为 ‘\r\n’ 以便产生
          带有符合 RFC 的行分隔符的标头。

          在 3.2 版更改: 增加了 `linesep' 参数。

     *note Header: 2855. 类还提供了一些方法以支持标准运算符和内置函数。

      -- 方法: __str__ ()

          以字符串形式返回 *note Header: 2855. 的近似表示，使用不受限制
          的行长度。 所有部分都会使用指定编码格式转换为 unicode 并适当地
          连接起来。 任何带有 ‘'unknown-8bit'’ 字符集的部分都会使用
          ‘'replace'’ 错误处理程序解码为 ASCII。

          在 3.2 版更改: 增加对 ‘'unknown-8bit'’ 字符集的处理。

      -- 方法: __eq__ (other)

          这个方法允许你对两个 *note Header: 2855. 实例进行相等比较。

      -- 方法: __ne__ (other)

          这个方法允许你对两个 *note Header: 2855. 实例进行不等比较。

*note email.header: 6f. 模块还提供了下列便捷函数。

 -- 函数: email.header.decode_header (header)

     在不转换字符集的情况下对消息标头值进行解码。 `header' 为标头值。

     这个函数返回一个 ‘(decoded_string, charset)’ 对的列表，其中包含标头
     的每个已解码部分。 对于标头的未编码部分 `charset' 为 ‘None’，在其他
     情况下则为一个包含已编码字符串中所指定字符集名称的小写字符串。

     以下是为示例代码:

          >>> from email.header import decode_header
          >>> decode_header('=?iso-8859-1?q?p=F6stal?=')
          [(b'p\xf6stal', 'iso-8859-1')]

 -- 函数: email.header.make_header (decoded_seq, maxlinelen=None,
          header_name=None, continuation_ws=' ')

     基于 *note decode_header(): a01. 所返回的数据对序列创建一个 *note
     Header: 2855. 实例。

     *note decode_header(): a01. 接受一个标头值字符串并返回格式为
     ‘(decoded_string, charset)’ 的数据对序列，其中 `charset' 是字符集名
     称。

     这个函数接受这样的数据对序列并返回一个 *note Header: 2855. 实例。 可
     选的 `maxlinelen', `header_name' 和 `continuation_ws' 与 *note
     Header: 2855. 构造器中的含义相同。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/email/header.py

   (2) https://tools.ietf.org/html/rfc2822.html

   (3) https://tools.ietf.org/html/rfc822.html

   (4) https://tools.ietf.org/html/rfc2822.html

   (5) https://tools.ietf.org/html/rfc2822.html

   (6) https://tools.ietf.org/html/rfc2045.html

   (7) https://tools.ietf.org/html/rfc2046.html

   (8) https://tools.ietf.org/html/rfc2047.html

   (9) https://tools.ietf.org/html/rfc2231.html

   (10) https://tools.ietf.org/html/rfc2047.html

   (11) https://tools.ietf.org/html/rfc2822.html

   (12) https://tools.ietf.org/html/rfc2047.html

   (13) https://tools.ietf.org/html/rfc2822.html

   (14) https://tools.ietf.org/html/rfc2822.html

   (15) https://tools.ietf.org/html/rfc2047.html


File: python.info,  Node: email charset 表示字符集,  Next: email encoders 编码器,  Prev: email header 国际化标头,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.16 ‘email.charset’: 表示字符集
.....................................

`源代码:' Lib/email/charset.py(1)

__________________________________________________________________

此模块是旧版 (‘Compat32’) email API 的组成部分。 在新版 API 中只会使用其
中的别名表。

本段落中的剩余文本是该模块的原始文档。

此模块提供了一个 *note Charset: 6dd. 类用来表示电子邮件消息中的字符集和
字符集转换操作，以及一个字符集注册表和几个用于操作此注册表的便捷方法。
*note Charset: 6dd. 的实例在 *note email: 69. 包的其他几个模块中也有使用
。

请从 *note email.charset: 6a. 模块导入这个类。

 -- 类: email.charset.Charset (input_charset=DEFAULT_CHARSET)

     将字符集映射到其 email 特征属性。

     这个类提供了特定字符集对于电子邮件的要求的相关信息。 考虑到适用编解
     码器的可用性，它还为字符集之间的转换提供了一些便捷例程。 在给定字符
     集的情况下，它将尽可能地以符合 RFC 的方式在电子邮件消息中提供有关如
     何使用该字符集的信息。

     特定字符集当在电子邮件标头或消息体中使用时必须以 quoted-printable 或
     base64 来编码。 某些字符集则必须被立即转换，不允许在电子邮件中使用
     。

     可选的 `input_charset' 说明如下；它总是会被强制转为小写。 在进行别
     名正规化后它还会被用来查询字符集注册表以找出用于该字符集的标头编码
     格式、消息体编码格式和输出转换编解码器。 举例来说，如果
     `input_charset' 为 ‘iso-8859-1’，则标头和消息体将会使用
     quoted-printable 来编码并且不需要输出转换编解码器。 如果
     `input_charset' 为 ‘euc-jp’，则标头将使用 base64 来编码，消息体将不
     会被编码，但输出文本将从 ‘euc-jp’ 字符集转换为 ‘iso-2022-jp’ 字符集
     。

     *note Charset: 6dd. 实例具有下列数据属性:

      -- 属性: input_charset

          指定的初始字符集。 通用别名会被转换为它们的 `官方' 电子邮件名
          称 (例如 ‘latin_1’ 会被转换为 ‘iso-8859-1’)。 默认值为 7 位
          ‘us-ascii’。

      -- 属性: header_encoding

          如果字符集在用于电子邮件标头之前必须被编码，此属性将被设为
          ‘Charset.QP’ (表示 quoted-printable 编码格式),
          ‘Charset.BASE64’ (表示 base64 编码格式) 或 ‘Charset.SHORTEST’
          表示 QP 或 BASE64 编码格式中最简短的一个。 在其他情况下，该属
          性将为 ‘None’.

      -- 属性: body_encoding

          与 `header_encoding' 一样，但是用来描述电子邮件消息体的编码格
          式，它实际上可以与标头编码格式不同。 ‘Charset.SHORTEST’ 不允许
          被用作 `body_encoding'。

      -- 属性: output_charset

          某些字符集在用于电子邮件标头或消息体之前必须被转换。 如果
          `input_charset' 是这些字符集之一，该属性将包含输出将要转换的字
          符集名称。 在其他情况下，该属性将为 ‘None’。

      -- 属性: input_codec

          用于将 `input_charset' 转换为 Unicode 的 Python 编解码器名称。
          如果不需要任何转换编解码器，该属性将为 ‘None’。

      -- 属性: output_codec

          用于将 Unicode 转换为 `output_charset' 的 Python 编解码器名称
          。 如果不需要任何转换编解码器，该属性将具有与 `input_codec' 相
          同的值。

     *note Charset: 6dd. 实例还有下列方法:

      -- 方法: get_body_encoding ()

          返回用于消息体编码的内容转换编码格式。

          根据所使用的编码格式返回 ‘quoted-printable’ 或 ‘base64’，或是
          返回一个函数，在这种情况下你应当调用该函数并附带一个参数，即被
          编码的消息对象。 该函数应当自行将 ‘Content-Transfer-Encoding’
          标头设为适当的值。

          如果 `body_encoding' 为 ‘QP’ 则返回字符串 ‘quoted-printable’，
          如果 `body_encoding' 为 ‘BASE64’ 则返回字符串 ‘base64’，并在其
          他情况下返回字符串 ‘7bit’。

      -- 方法: get_output_charset ()

          返回输出字符集。

          如果 `output_charset' 属性不为 ‘None’ 则返回该属性，否则返回
          `input_charset'。

      -- 方法: header_encode (string)

          对字符串 `string' 执行标头编码。

          编码格式的类型 (base64 或 quoted-printable) 将取决于
          `header_encoding' 属性。

      -- 方法: header_encode_lines (string, maxlengths)

          通过先将 `string' 转换为字节串来对其执行标头编码。

          这类似于 *note header_encode(): 28d3.，区别是字符串会被调整至
          参数 `maxlengths' 所给出的最大行长度，它应当是一个迭代器：该迭
          代器返回的每个元素将提供下一个最大行长度。

      -- 方法: body_encode (string)

          对字符串 `string' 执行消息体编码。

          编码格式的类型 (base64 或 quoted-printable) 将取决于
          `body_encoding' 属性。

     *note Charset: 6dd. 类还提供了一些方法以支持标准运算和内置函数。

      -- 方法: __str__ ()

          将 `input_charset' 以强制转为小写的字符串形式返回。 *note
          __repr__(): 347. 是 *note __str__(): 28d6. 的别名。

      -- 方法: __eq__ (other)

          这个方法允许你对两个 *note Charset: 6dd. 实例进行相等比较。

      -- 方法: __ne__ (other)

          这个方法允许你对两个 *note Charset: 6dd. 实例进行相等比较。

*note email.charset: 6a. 模块还提供了下列函数用于向全局字符集、别名以及
编解码器注册表添加新条目:

 -- 函数: email.charset.add_charset (charset, header_enc=None,
          body_enc=None, output_charset=None)

     向全局注册表添加字符特征属性。

     `charset' 是输入字符集，它必须为某个字符集的正规名称。

     可选的 `header_enc' 和 `body_enc' 可以是 ‘Charset.QP’ 表示
     quoted-printable, ‘Charset.BASE64’ 表示 base64 编码格式,
     ‘Charset.SHORTEST’ 表示 quoted-printable 或 base64 编码格式中较短的
     一个，或者为 ‘None’ 表示没有编码格式。 ‘SHORTEST’ 是 `header_enc' 的
     唯一有效值。 默认值为 ‘None’ 表示没有编码格式。

     可选的 `output_charset' 是输出所应当采用的字符集。 当
     ‘Charset.convert()’ 方法被调用时将会执行从输入字符集到输出字符集的
     转换。 默认情况下输出字符集将与输入字符集相同。

     `input_charset' 和 `output_charset' 都必须在模块的字符集-编解码器映
     射中具有 Unicode 编解码器条目；使用 *note add_codec(): 28da. 可添加
     本模块还不知道的编解码器。 请参阅 *note codecs: 1c. 模块的文档来了
     解更多信息。

     全局字符集注册表保存在模块全局字典 ‘CHARSETS’ 中。

 -- 函数: email.charset.add_alias (alias, canonical)

     添加一个字符集别名。 `alias' 为特定的别名，例如 ‘latin-1’。
     `canonical' 是字符集的正规名称，例如 ‘iso-8859-1’。

     全局字符集注册表保存在模块全局字典 ‘ALIASES’ 中。

 -- 函数: email.charset.add_codec (charset, codecname)

     添加在给定字符集的字符和 Unicode 之间建立映射的编解码器。

     `charset' 是某个字符集的正规名称。 `codecname' 是某个 Python 编解码
     器的名称，可以被用来作为 *note str: 339. 的 *note encode(): c3f. 方
     法的第二个参数。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/email/charset.py


File: python.info,  Node: email encoders 编码器,  Next: email utils 其他工具,  Prev: email charset 表示字符集,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.17 ‘email.encoders’: 编码器
..................................

`源代码:' Lib/email/encoders.py(1)

__________________________________________________________________

此模块是旧版 (‘Compat32’) email API 的组成部分。 在新版 API 中将由 *note
set_content(): 2811. 方法的 `cte' 形参提供该功能。

此模块在 Python 3 中已弃用。 这里提供的函数不应被显式地调用，因为 *note
MIMEText: 6dc. 类会在类实例化期间使用 `_subtype' 和 `_charset' 值来设置
内容类型和 CTE 头。

本段落中的剩余文本是该模块的原始文档。

当创建全新的 *note Message: 54a. 对象时，你经常需要对载荷编码以便通过兼
容的邮件服务器进行传输。 对于包含二进制数据的 ‘image/*’ 和 ‘text/*’ 类型
的消息来说尤其如此。

*note email: 69. 包在其 ‘encoders’ 模块中提供了一些方便的编码器。 这些编
码器实际上由 *note MIMEAudio: 28c0. 和 *note MIMEImage: 285f. 类构造器所
使用以提供默认编码格式。 所有编码器函数都只接受一个参数，即要编码的消息
对象。 它们通常会提取有效载荷，对其进行编码，并将载荷重置为这种新编码的
值。 它们还应当相应地设置 ‘Content-Transfer-Encoding’ 标头。

请注意，这些函数对于多段消息没有意义。 它们必须应用到各个单独的段上面，
而不是整体。如果直接传递一个多段类型的消息，会产生一个 *note TypeError:
193. 错误。

下面是提供的编码函数：

 -- 函数: email.encoders.encode_quopri (msg)

     将有效数据编码为经转换的可打印形式，并将
     ‘Content-Transfer-Encoding’ 标头设置为 ‘quoted-printable’ (2)。 当
     大多数实际的数据是普通的可打印数据但包含少量不可打印的字符时，这是
     一个很好的编码。

 -- 函数: email.encoders.encode_base64 (msg)

     将有效载荷编码为 base64 形式，并将 ‘Content-Transfer-Encoding’ 标头
     设为 ‘base64’。 当你的载荷主要包含不可打印数据时这是一种很好用的编
     码格式，因为它比 quoted-printable 更紧凑。 base64 编码格式的缺点是
     它会使文本变成人类不可读的形式。

 -- 函数: email.encoders.encode_7or8bit (msg)

     此函数并不实际改变消息的有效载荷，但它会基于载荷数据将
     ‘Content-Transfer-Encoding’ 标头相应地设为 ‘7bit’ 或 ‘8bit’。

 -- 函数: email.encoders.encode_noop (msg)

     此函数什么都不会做；它甚至不会设置 ‘Content-Transfer-Encoding’ 标头
     。

备注
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/email/encoders.py

   (2) (1) 请注意使用 *note encode_quopri(): 28de. 编码格式还会对数据中
的所有制表符和空格符进行编码。


File: python.info,  Node: email utils 其他工具,  Next: email iterators 迭代器,  Prev: email encoders 编码器,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.18 ‘email.utils’: 其他工具
.................................

`源代码:' Lib/email/utils.py(1)

__________________________________________________________________

*note email.utils: 76. 模块提供如下几个工具

 -- 函数: email.utils.localtime (dt=None)

     以感知型 datetime 对象返回当地时间。 如果调用时参数为空，则返回当前
     时间。 否则 `dt' 参数应该是一个 *note datetime: 195. 实例，并根据系
     统时区数据库转换为当地时区。 如果 `dt' 是简单型的 (即 ‘dt.tzinfo’ 是
     ‘None’ )，则假定为当地时间。 在这种情况下，为正值或零的 `isdst' 会
     使 ‘localtime’ 假定夏季时间（例如，夏令时）对指定时间生效或不生效。
     负值 `isdst' 会使 ‘localtime’ 预测夏季时间对指定时间是否生效。

     3.3 新版功能.

 -- 函数: email.utils.make_msgid (idstring=None, domain=None)

     返回一个适合作为兼容 RFC 2822(2) 的 ‘Message-ID’ 标头的字符串。可选
     参数 `idstring' 可传入一字符串以增强该消息 ID 的唯一性。可选参数
     `domain' 可用于提供消息 ID 中字符 ’@’ 之后的部分，其默认值是本机的
     主机名。正常情况下无需覆盖此默认值，但在特定情况下覆盖默认值可能会
     有用，比如构建一个分布式系统，在多台主机上采用一致的域名。

     在 3.2 版更改: 增加了关键字 `domain'

下列函数是旧（‘Compat32’）电子邮件 API 的一部分。新 API 提供的解析和格式
化在标头解析机制中已经被自动完成，故在使用新 API 时没有必要直接使用它们
函数。

 -- 函数: email.utils.quote (str)

     返回一个新的字符串， `str' 中的反斜杠被替换为两个反斜杠，并且双引号
     被替换为反斜杠加双引号。

 -- 函数: email.utils.unquote (str)

     返回 `str' 被去除引用后的字符串。如果 `str' 开头和结尾均是双引号，
     则这对双引号被去除。类似地，如果 `str' 开头和结尾都是尖角括号，这对
     尖角括号会被去除。

 -- 函数: email.utils.parseaddr (address)

     将地址（应为诸如 ‘To’ 或者 ‘Cc’ 之类包含地址的字段值）解析为构成之
     的 `真实名字' 和 `电子邮件地址' 部分。返回包含这两个信息的一个元组
     ；如若解析失败，则返回一个二元组 ‘('', '')’ 。

 -- 函数: email.utils.formataddr (pair, charset='utf-8')

     是 *note parseaddr(): 28e6. 的逆操作，接受一个 ‘(真实名字, 电子邮件
     地址)’ 的二元组，并返回适合于 ‘To’ or ‘Cc’ 标头的字符串。如果第一个
     元素为假性值，则第二个元素将被原样返回。

     可选地，如果指定 `charset'，则被视为一符合 RFC 2047(3) 的编码字符集
     ，用于编码 ‘真实名字’ 中的非 ASCII 字符。可以是一个 *note str: 339.
     类的实例，或者一个 *note Charset: 6dd. 类。默认为 ‘utf-8’ 。

     在 3.3 版更改: 添加了 `charset' 选项。

 -- 函数: email.utils.getaddresses (fieldvalues)

     该方法返回一个形似 ‘parseaddr()’ 返回的二元组的列表。 `fieldvalues'
     是一个序列，包含了形似 *note Message.get_all: 28a0. 返回值的标头字
     段值。获取了一消息的所有收件人的简单示例如下：

          from email.utils import getaddresses

          tos = msg.get_all('to', [])
          ccs = msg.get_all('cc', [])
          resent_tos = msg.get_all('resent-to', [])
          resent_ccs = msg.get_all('resent-cc', [])
          all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)

 -- 函数: email.utils.parsedate (date)

     尝试根据 RFC 2822(4) 的规则解析一个日期。然而，有些寄信人不严格遵守
     这一格式，所以这种情况下 *note parsedate(): 28e8. 会尝试猜测其形式
     。`date' 是一个字符串包含了一个形如 ‘"Mon, 20 Nov 1995 19:12:08
     -0500"’ 的 RFC 2822(5) 格式日期。如果日期解析成功， *note
     parsedate(): 28e8. 将返回一个九元组，可直接传递给 *note
     time.mktime(): b6c.；否则返回 ‘None’。注意返回的元组中下标为 6、7、
     8 的部分是无用的。

 -- 函数: email.utils.parsedate_tz (date)

     执行与 *note parsedate(): 28e8. 相同的功能，但会返回 ‘None’ 或是一
     个 10 元组；前 9 个元素构成一个可以直接传给 *note time.mktime():
     b6c. 的元组，而第十个元素则是该日期的时区与 UTC (格林威治平均时 GMT
     的正式名称) (6) 的时差。 如果输入字符串不带时区，则所返回元组的最后
     一个元素将为 ‘0’，这表示 UTC。 请注意结果元组的索引号 6, 7 和 8 是
     不可用的。

 -- 函数: email.utils.parsedate_to_datetime (date)

     *note format_datetime(): a06. 的逆操作。 执行与 *note parsedate():
     28e8. 相同的功能，但会在成功时返回一个 *note datetime: 195.。 如果
     输入日期的时区值为 ‘-0000’，则 ‘datetime’ 将为一个简单型
     ‘datetime’，而如果日期符合 RFC 标准则它将代表一个 UTC 时间，但是并
     不指明日期所在消息的实际源时区。 如果输入日期具有任何其他有效的时区
     差值，则 ‘datetime’ 将为一个感知型 ‘datetime’ 并与 *note timezone:
     a09. *note tzinfo: 388. 相对应。

     3.3 新版功能.

 -- 函数: email.utils.mktime_tz (tuple)

     将 *note parsedate_tz(): 28e9. 所返回的 10 元组转换为一个 UTC 时间
     戳（相距 Epoch 纪元初始的秒数）。 如果元组中的时区项为 ‘None’，则视
     为当地时间。

 -- 函数: email.utils.formatdate (timeval=None, localtime=False,
          usegmt=False)

     返回 RFC 2822(7) 标准的日期字符串，例如:

          Fri, 09 Nov 2001 01:08:47 -0000

     可选的 `timeval' 如果给出，则是一个可被 *note time.gmtime(): b47. 和
     *note time.localtime(): f5d. 接受的浮点数时间值，否则会使得当前时间
     。

     可选的 `localtime' 是一个旗标，当为 ‘True’ 时，将会解析 `timeval'，
     并返回一个相对于当地时区而非 UTC 的日期值，并会适当地考虑夏令时。 默
     认值 ‘False’ 表示使用 UTC。

     可选的 `usegmt' 是一个旗标，当为 ‘True’ 时，将会输出一个日期字符串
     ，其中时区表示为 ascii 字符串 ‘GMT’ 而非数字形式的 ‘-0000’。 这对某
     些协议（例如 HTTP）来说是必要的。 这仅在 `localtime' 为 ‘False’ 时
     应用。 默认值为 ‘False’。

 -- 函数: email.utils.format_datetime (dt, usegmt=False)

     类似于 ‘formatdate’，但输入的是一个 *note datetime: 31. 实例。 如果
     实例是一个简单型 datetime，它会被视为 "不带源时区信息的 UTC"，并且
     使用传统的 ‘-0000’ 作为时区。 如果实例是一个感知型 ‘datetime’，则会
     使用数字形式的时区时差。 如果实例是感知型且时区时差为零，则
     `usegmt' 可能会被设为 ‘True’，在这种情况下将使用字符串 ‘GMT’ 而非数
     字形式的时区时差。 这提供了一种生成符合标准 HTTP 日期标头的方式。

     3.3 新版功能.

 -- 函数: email.utils.decode_rfc2231 (s)

     根据 RFC 2231(8) 解码字符串 `s'。

 -- 函数: email.utils.encode_rfc2231 (s, charset=None, language=None)

     根据 RFC 2231(9) 对字符串 `s' 进行编码。 可选的 `charset' 和
     `language' 如果给出，则为指明要使用的字符集名称和语言名称。 如果两
     者均未给出，则会原样返回 `s'。 如果给出 `charset' 但未给出
     `language'，则会使用空字符串作为 `language' 值来对字符串进行编码。

 -- 函数: email.utils.collapse_rfc2231_value (value, errors='replace',
          fallback_charset='us-ascii')

     当以 RFC 2231(10) 格式来编码标头形参时，*note Message.get_param:
     28ae. 可能返回一个包含字符集、语言和值的 3 元组。 *note
     collapse_rfc2231_value(): 28af. 会将此返回为一个 unicode 字符串。 可
     选的 `errors' 会被传递给 *note str: 339. 的 *note encode(): c3f. 方
     法的 `errors' 参数；它的默认值为 ‘'replace'’。 可选的
     `fallback_charset' 指定当 RFC 2231(11) 标头中的字符集无法被 Python
     识别时要使用的字符集；它的默认值为 ‘'us-ascii'’。

     为方便起见，如果传给 *note collapse_rfc2231_value(): 28af. 的
     `value' 不是一个元组，则应为一个字符串并会将其原样返回。

 -- 函数: email.utils.decode_params (params)

     根据 RFC 2231(12) 解码参数列表。 `params' 是一个包含
     ‘(content-type, string-value)’ 形式的元素的 2 元组的序列。

备注
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/email/utils.py

   (2) https://tools.ietf.org/html/rfc2822.html

   (3) https://tools.ietf.org/html/rfc2047.html

   (4) https://tools.ietf.org/html/rfc2822.html

   (5) https://tools.ietf.org/html/rfc2822.html

   (6) (1) 请注意时区时差的符号与同一时区的 ‘time.timezone’ 变量的符号相
反；后者遵循 POSIX 标准而此模块遵循 RFC 2822
(https://tools.ietf.org/html/rfc2822.html)。

   (7) https://tools.ietf.org/html/rfc2822.html

   (8) https://tools.ietf.org/html/rfc2231.html

   (9) https://tools.ietf.org/html/rfc2231.html

   (10) https://tools.ietf.org/html/rfc2231.html

   (11) https://tools.ietf.org/html/rfc2231.html

   (12) https://tools.ietf.org/html/rfc2231.html


File: python.info,  Node: email iterators 迭代器,  Prev: email utils 其他工具,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.19 ‘email.iterators’: 迭代器
...................................

`源代码:' Lib/email/iterators.py(1)

__________________________________________________________________

通过 *note Message.walk: 28b7. 方法来迭代消息对象树是相当容易的。 *note
email.iterators: 71. 模块提供了一些适用于消息对象树的高层级迭代器。

 -- 函数: email.iterators.body_line_iterator (msg, decode=False)

     此函数会迭代 `msg' 的所有子部分中的所有载荷，逐行返回字符串载荷。 它
     会跳过所有子部分的标头，并且它也会跳过任何包含不为 Python 字符串的
     载荷的子部分。 这基本上等价于使用 *note readline(): 1c0e. 从一个文
     件读取消息的纯文本表示形式，并跳过所有中间的标头。

     可选的 `decode' 会被传递给 *note Message.get_payload: b53.。

 -- 函数: email.iterators.typed_subpart_iterator (msg, maintype='text',
          subtype=None)

     此函数会迭代 `msg' 的所有子部分，只返回其中与 `maintype' 和
     `subtype' 所指定的 MIME 类型相匹配的子部分。

     请注意 `subtype' 是可选项；如果省略，则仅使用主类型来进行子部分
     MIME 类型的匹配。 `maintype' 也是可选项；它的默认值为 ‘text’。

     因此，在默认情况下 *note typed_subpart_iterator(): 28f2. 会返回每一
     个 MIME 类型为 ‘text/*’ 的子部分。

增加了以下函数作为有用的调试工具。 它 `不应当' 被视为该包所支持的公共接
口的组成部分。

 -- 函数: email.iterators._structure (msg, fp=None, level=0,
          include_default=False)

     打印消息对象结构的内容类型的缩进表示形式。 例如:

          >>> msg = email.message_from_file(somefile)
          >>> _structure(msg)
          multipart/mixed
              text/plain
              text/plain
              multipart/digest
                  message/rfc822
                      text/plain
                  message/rfc822
                      text/plain
                  message/rfc822
                      text/plain
                  message/rfc822
                      text/plain
                  message/rfc822
                      text/plain
              text/plain

     可选项 `fp' 是一个作为打印输出目标的文件类对象。 它必须适用于
     Python 的 *note print(): 88f. 函数。 `level' 是供内部使用的。
     `include_default' 如果为真值，则会同时打印默认类型。

参见
....

*note smtplib: ee. 模块

     SMTP (简单邮件传输协议) 客户端

*note poplib: d1. 模块

     POP (邮局协议) 客户端

*note imaplib: 98. 模块

     IMAP (互联网消息访问协议) 客户端

*note nntplib: c1. 模块

     NNTP (网络新闻传输协议) 客户端

*note mailbox: af. 模块

     创建、读取和管理使用保存在磁盘中的多种标准格式的消息集的工具。

*note smtpd: ed. 模块

     SMTP 服务器框架 (主要适用于测试)

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/email/iterators.py


File: python.info,  Node: json --- JSON 编码和解码器,  Next: mailcap --- Mailcap 文件处理,  Prev: email --- 电子邮件与 MIME 处理包,  Up: 互联网数据处理

5.19.2 ‘json’ — JSON 编码和解码器
---------------------------------

`源代码:' Lib/json/__init__.py(1)

__________________________________________________________________

JSON (JavaScript Object Notation)(2)，由 RFC 7159(3) (which obsoletes
RFC 4627(4)) 和 ECMA-404(5) 指定，是一个受 JavaScript(6) 的对象字面量语
法启发的轻量级数据交换格式，尽管它不仅仅是一个严格意义上的 JavaScript 的
字集 (7)。

*note json: a5. 提供了与标准库 *note marshal: b1. 和 *note pickle: cb. 相
似的API接口。

对基本的 Python 对象层次结构进行编码：

     >>> import json
     >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
     '["foo", {"bar": ["baz", null, 1.0, 2]}]'
     >>> print(json.dumps("\"foo\bar"))
     "\"foo\bar"
     >>> print(json.dumps('\u1234'))
     "\u1234"
     >>> print(json.dumps('\\'))
     "\\"
     >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
     {"a": 0, "b": 0, "c": 0}
     >>> from io import StringIO
     >>> io = StringIO()
     >>> json.dump(['streaming API'], io)
     >>> io.getvalue()
     '["streaming API"]'

紧凑编码：

     >>> import json
     >>> json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':'))
     '[1,2,3,{"4":5,"6":7}]'

美化输出：

     >>> import json
     >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
     {
         "4": 5,
         "6": 7
     }

JSON解码：

     >>> import json
     >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
     ['foo', {'bar': ['baz', None, 1.0, 2]}]
     >>> json.loads('"\\"foo\\bar"')
     '"foo\x08ar'
     >>> from io import StringIO
     >>> io = StringIO('["streaming API"]')
     >>> json.load(io)
     ['streaming API']

特殊 JSON 对象解码：

     >>> import json
     >>> def as_complex(dct):
     ...     if '__complex__' in dct:
     ...         return complex(dct['real'], dct['imag'])
     ...     return dct
     ...
     >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
     ...     object_hook=as_complex)
     (1+2j)
     >>> import decimal
     >>> json.loads('1.1', parse_float=decimal.Decimal)
     Decimal('1.1')

扩展 *note JSONEncoder: 60f.：

     >>> import json
     >>> class ComplexEncoder(json.JSONEncoder):
     ...     def default(self, obj):
     ...         if isinstance(obj, complex):
     ...             return [obj.real, obj.imag]
     ...         # Let the base class default method raise the TypeError
     ...         return json.JSONEncoder.default(self, obj)
     ...
     >>> json.dumps(2 + 1j, cls=ComplexEncoder)
     '[2.0, 1.0]'
     >>> ComplexEncoder().encode(2 + 1j)
     '[2.0, 1.0]'
     >>> list(ComplexEncoder().iterencode(2 + 1j))
     ['[2.0', ', 1.0', ']']

从命令行使用 *note json.tool: a6. 来验证并美化输出：

     $ echo '{"json":"obj"}' | python -m json.tool
     {
         "json": "obj"
     }
     $ echo '{1.2:3.4}' | python -m json.tool
     Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

详细文档请参见 *note 命令行界面: 28f6.。

     注解: JSON 是 YAML(8) 1.2 的一个子集。由该模块的默认设置生成的 JSON
     （尤其是默认的 “分隔符” 设置值）也是 YAML 1.0 and 1.1 的一个子集。
     因此该模块也能够用于序列化为 YAML。

     注解: 这个模块的编码器和解码器默认保护输入和输出的顺序。仅当底层的
     容器未排序时才会失去顺序。

     在 Python 3.7 之前，*note dict: 1b9. 并不保证有序，因此输入和输出通
     常都是乱序的，除非是明确地请求 *note collections.OrderedDict: 1ba.。
     从 Python 3.7 开始，普通的 *note dict: 1b9. 会保留顺序，因此不必再
     为 JSON 的生成和解析指定使用 *note collections.OrderedDict: 1ba.。

* Menu:

* 基本使用::
* 编码器和解码器::
* 异常: 异常<13>.
* 标准符合性和互操作性::
* 命令行界面: 命令行界面<4>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/json/__init__.py

   (2) http://json.org

   (3) https://tools.ietf.org/html/rfc7159.html

   (4) https://tools.ietf.org/html/rfc4627.html

   (5) 
http://www.ecma-international.org/publications/standards/Ecma-404.htm

   (6) https://en.wikipedia.org/wiki/JavaScript

   (7) (1) 正如 RFC 7159 的勘误表
(https://www.rfc-editor.org/errata_search.php?rfc=7159) 所说明的，JSON 允
许以字符串表示字面值字符 U+2028 (LINE SEPARATOR) 和 U+2029 (PARAGRAPH
SEPARATOR)，而 JavaScript (在 ECMAScript 5.1 版中) 不允许。

   (8) http://yaml.org/


File: python.info,  Node: 基本使用,  Next: 编码器和解码器,  Up: json --- JSON 编码和解码器

5.19.2.1 基本使用
.................

 -- 函数: json.dump (obj, fp, *, skipkeys=False, ensure_ascii=True,
          check_circular=True, allow_nan=True, cls=None, indent=None,
          separators=None, default=None, sort_keys=False, **kw)

     使用这个 *note 转换表: 28f8. 将 `obj' 序列化为 JSON 格式化流形式的
     `fp' (支持 ‘.write()’ 的 *note file-like object: 1c7a.)。

     如果 `skipkeys' 是 true （默认为 ‘False’），那么那些不是基本对象（
     包括 *note str: 339, *note int: 185.、*note float: 188.、*note
     bool: 184.、‘None’）的字典的键会被跳过；否则引发一个 *note
     TypeError: 193.。

     *note json: a5. 模块始终产生 *note str: 339. 对象而非 *note bytes:
     33a. 对象。因此，‘fp.write()’ 必须支持 *note str: 339. 输入。

     如果 `ensure_ascii' 是 true （即默认值），输出保证将所有输入的非
     ASCII 字符转义。如果 `ensure_ascii' 是 false，这些字符会原样输出。

     如果 `check_circular' 是为假值 (默认为 ‘True’)，那么容器类型的循环
     引用检验会被跳过并且循环引用会引发一个 *note OverflowError: 968. (或
     者更糟的情况)。

     如果 `allow_nan' 是 false（默认为 ‘True’），那么在对严格 JSON 规格
     范围外的 *note float: 188. 类型值（‘nan’、‘inf’ 和 ‘-inf’）进行序列
     化时会引发一个 *note ValueError: 1fc.。如果 `allow_nan' 是 true，则
     使用它们的 JavaScript 等价形式（‘NaN’、‘Infinity’ 和 ‘-Infinity’）
     。

     如果 `indent' 是一个非负整数或者字符串，那么 JSON 数组元素和对象成
     员会被美化输出为该值指定的缩进等级。 如果缩进等级为零、负数或者
     ‘""’，则只会添加换行符。 ‘None’ (默认值) 选择最紧凑的表达。 使用一
     个正整数会让每一层缩进同样数量的空格。 如果 `indent' 是一个字符串
     (比如 ‘"\t"’)，那个字符串会被用于缩进每一层。

     在 3.2 版更改: 现允许使用字符串作为 `indent' 而不再仅仅是整数。

     当被指定时，`separators' 应当是一个 ‘(item_separator,
     key_separator)’ 元组。当 `indent' 为 ‘None’ 时，默认值取 ‘(', ', ':
     ')’，否则取 ‘(',', ': ')’。为了得到最紧凑的 JSON 表达式，你应该指定
     其为 ‘(',', ':')’ 以消除空白字符。

     在 3.4 版更改: 现当 `indent' 不是 ‘None’ 时，采用 ‘(',', ': ')’ 作
     为默认值。

     当 `default' 被指定时，其应该是一个函数，每当某个对象无法被序列化时
     它会被调用。它应该返回该对象的一个可以被 JSON 编码的版本或者引发一
     个 *note TypeError: 193.。如果没有被指定，则会直接引发 *note
     TypeError: 193.。

     如果 `sort_keys' 是 true（默认为 ‘False’），那么字典的输出会以键的
     顺序排序。

     为了使用一个自定义的 *note JSONEncoder: 60f. 子类（比如：覆盖了
     ‘default()’ 方法来序列化额外的类型）， 通过 `cls' 关键字参数来指定
     ；否则将使用 *note JSONEncoder: 60f.。

     在 3.6 版更改: 所有可选形参现在都是 *note 仅限关键字参数: 2ad.。

          注解: 与 *note pickle: cb. 和 *note marshal: b1. 不同，JSON 不
          是一个具有框架的协议，所以尝试多次使用同一个 `fp' 调用 *note
          dump(): 60d. 来序列化多个对象会产生一个不合规的 JSON 文件。

 -- 函数: json.dumps (obj, *, skipkeys=False, ensure_ascii=True,
          check_circular=True, allow_nan=True, cls=None, indent=None,
          separators=None, default=None, sort_keys=False, **kw)

     使用这个 *note 转换表: 28f8. 将 `obj' 序列化为 JSON 格式的 *note
     str: 339.。 其参数的含义与 *note dump(): 60d. 中的相同。

          注解: JSON 中的键-值对中的键永远是 *note str: 339. 类型的。当
          一个对象被转化为 JSON 时，字典中所有的键都会被强制转换为字符串
          。这所造成的结果是字典被转换为 JSON 然后转换回字典时可能和原来
          的不相等。换句话说，如果 x 具有非字符串的键，则有
          ‘loads(dumps(x)) != x’。

 -- 函数: json.load (fp, *, cls=None, object_hook=None,
          parse_float=None, parse_int=None, parse_constant=None,
          object_pairs_hook=None, **kw)

     使用这个 *note 转换表: 28f9. 将 `fp' (一个支持 ‘.read()’ 并包含一个
     JSON 文档的 *note text file: 12b5. 或者 *note binary file: 1cb4.) 反
     序列化为一个 Python 对象。

     `object_hook' 是一个可选的函数，它会被调用于每一个解码出的对象字面
     量（即一个 *note dict: 1b9.）。`object_hook' 的返回值会取代原本的
     *note dict: 1b9.。这一特性能够被用于实现自定义解码器（如
     JSON-RPC(1) 的类型提示)。

     `object_pairs_hook' 是一个可选的函数，它会被调用于每一个有序列表对
     解码出的对象字面量。 `object_pairs_hook' 的返回值将会取代原本的
     *note dict: 1b9. 。这一特性能够被用于实现自定义解码器。如果
     `object_hook' 也被定义， `object_pairs_hook' 优先。

     在 3.1 版更改: 添加了对 `object_pairs_hook' 的支持。

     `parse_float' ，如果指定，将与每个要解码 JSON 浮点数的字符串一同调
     用。默认状态下，相当于 ‘float(num_str)’ 。可以用于对 JSON 浮点数使
     用其它数据类型和语法分析程序 （比如 *note decimal.Decimal: 189. ）
     。

     `parse_int' ，如果指定，将与每个要解码 JSON 整数的字符串一同调用。
     默认状态下，相当于 ‘int(num_str)’ 。可以用于对 JSON 整数使用其它数
     据类型和语法分析程序 （比如 *note float: 188. ）。

     `parse_constant' ，如果指定，将要与以下字符串中的一个一同调用：
     ‘'-Infinity'’ ， ‘'Infinity'’ ， ‘'NaN'’ 。如果遇到无效的 JSON 数字
     则可以使用它引发异常。

     在 3.1 版更改: `parse_constant' 不再调用 ’null’ ， ’true’ ，
     ’false’ 。

     要使用自定义的 *note JSONDecoder: 610. 子类，用 ‘cls’ 指定他；否则
     使用 *note JSONDecoder: 610. 。额外的关键词参数会通过类的构造函数传
     递。

     如果反序列化的数据不是有效 JSON 文档，引发 *note JSONDecodeError:
     70f. 错误。

     在 3.6 版更改: 所有可选形参现在都是 *note 仅限关键字参数: 2ad.。

     在 3.6 版更改: `fp' 现在可以是 *note binary file: 1cb4. 。输入编码
     应当是 UTF-8 ， UTF-16 或者 UTF-32 。

 -- 函数: json.loads (s, *, cls=None, object_hook=None,
          parse_float=None, parse_int=None, parse_constant=None,
          object_pairs_hook=None, **kw)

     使用这个 *note 转换表: 28f9. 将 `s' (一个包含 JSON 文档的 *note
     str: 339, *note bytes: 33a. 或 *note bytearray: 33b. 实例) 反序列化
     为 Python 对象。

     除了*encoding*被忽略和弃用自 Python 3.1 以来，其他参数的含义与
     *note load(): 568. 中相同。

     如果反序列化的数据不是有效 JSON 文档，引发 *note JSONDecodeError:
     70f. 错误。

     Deprecated since version 3.1, will be removed in version 3.9:
     `encoding' 关键字参数。

     在 3.6 版更改: `s' 现在可以为 *note bytes: 33a. 或 *note bytearray:
     33b. 类型。 输入编码应为 UTF-8, UTF-16 或 UTF-32。

   ---------- Footnotes ----------

   (1) http://www.jsonrpc.org


File: python.info,  Node: 编码器和解码器,  Next: 异常<13>,  Prev: 基本使用,  Up: json --- JSON 编码和解码器

5.19.2.2 编码器和解码器
.......................

 -- 类: json.JSONDecoder (*, object_hook=None, parse_float=None,
          parse_int=None, parse_constant=None, strict=True,
          object_pairs_hook=None)

     简单的JSON解码器。

     默认情况下，解码执行以下翻译:

     JSON                Python
                         
     --------------------------------------------
                         
     object              dict
                         
                         
     array               list
                         
                         
     string              str
                         
                         
     number (int)        int
                         
                         
     number (real)       float
                         
                         
     true                True
                         
                         
     false               False
                         
                         
     null                None
                         

     它还将“NaN”、“Infinity”和“-Infinity”理解为它们对应的“float”值，这超
     出了JSON规范。

     `object_hook' ，如果指定，会被每个解码的 JSON 对象的结果调用，并且
     返回值会替代给定 *note dict: 1b9. 。它可被用于提供自定义反序列化（
     比如去支持 JSON-RPC 类的暗示）。

     如果指定了 `object_pairs_hook' 则它将被调用并传入以对照值有序列表进
     行解码的每个 JSON 对象的结果。 `object_pairs_hook' 的结果值将被用来
     替代 *note dict: 1b9.。 这一特性可被用于实现自定义解码器。 如果还定
     义了 `object_hook'，则 `object_pairs_hook' 的优先级更高。

     在 3.1 版更改: 添加了对 `object_pairs_hook' 的支持。

     `parse_float' ，如果指定，将与每个要解码 JSON 浮点数的字符串一同调
     用。默认状态下，相当于 ‘float(num_str)’ 。可以用于对 JSON 浮点数使
     用其它数据类型和语法分析程序 （比如 *note decimal.Decimal: 189. ）
     。

     `parse_int' ，如果指定，将与每个要解码 JSON 整数的字符串一同调用。
     默认状态下，相当于 ‘int(num_str)’ 。可以用于对 JSON 整数使用其它数
     据类型和语法分析程序 （比如 *note float: 188. ）。

     `parse_constant' ，如果指定，将要与以下字符串中的一个一同调用：
     ‘'-Infinity'’ ， ‘'Infinity'’ ， ‘'NaN'’ 。如果遇到无效的 JSON 数字
     则可以使用它引发异常。

     如果 `strict' 为 false （默认为 ‘True’ ），那么控制字符将被允许在字
     符串内。在此上下文中的控制字符编码在范围 0–31 内的字符，包括 ‘'\t'’
     (制表符）， ‘'\n'’ ， ‘'\r'’ 和 ‘'\0'’ 。

     如果反序列化的数据不是有效 JSON 文档，引发 *note JSONDecodeError:
     70f. 错误。

     在 3.6 版更改: 所有形参现在都是 *note 仅限关键字参数: 2ad.。

      -- 方法: decode (s)

          返回 `s' 的 Python 表示形式（包含一个 JSON 文档的 *note str:
          339. 实例）。

          如果给定的 JSON 文档无效则将引发 *note JSONDecodeError: 70f.。

      -- 方法: raw_decode (s)

          从 `s' 中解码出 JSON 文档（以 JSON 文档开头的一个 *note str:
          339. 对象）并返回一个 Python 表示形式为 2 元组以及指明该文档在
          `s' 中结束位置的序号。

          这可以用于从一个字符串解码JSON文档，该字符串的末尾可能有无关的
          数据。

 -- 类: json.JSONEncoder (*, skipkeys=False, ensure_ascii=True,
          check_circular=True, allow_nan=True, sort_keys=False,
          indent=None, separators=None, default=None)

     用于Python数据结构的可扩展JSON编码器。

     默认支持以下对象和类型：

     Python                                       JSON
                                                  
     -----------------------------------------------------------------
                                                  
     dict                                         object
                                                  
                                                  
     list, tuple                                  array
                                                  
                                                  
     str                                          string
                                                  
                                                  
     int, float, int 和 float 派生的枚举          number
                                                  
                                                  
     True                                         true
                                                  
                                                  
     False                                        false
                                                  
                                                  
     None                                         null
                                                  

     在 3.4 版更改: 添加了对 int 和 float 派生的枚举类的支持

     为了将其拓展至识别其他对象，需要子类化并实现 *note default(): 28fd.
     方法于另一种返回 ‘o’ 的可序列化对象的方法如果可行，否则它应该调用超
     类实现（来引发 *note TypeError: 193. ）。

     如果 `skipkeys' 为假值（默认），则尝试对不是 *note str: 339, *note
     int: 185, *note float: 188. 或 ‘None’ 的键进行编码将会引发 *note
     TypeError: 193.。 如果 `skipkeys' 为真值，这些条目将被直接跳过。

     如果 `ensure_ascii' 是 true （即默认值），输出保证将所有输入的非
     ASCII 字符转义。如果 `ensure_ascii' 是 false，这些字符会原样输出。

     如果 `check_circular' 为 true （默认），那么列表，字典，和自定义编
     码的对象在编码期间会被检查重复循环引用防止无限递归（无限递归将导致
     *note OverflowError: 968. ）。否则，这样进行检查。

     如果 `allow_nan' 为 true （默认），那么 ‘NaN’ ， ‘Infinity’ ，和
     ‘-Infinity’ 进行编码。此行为不符合 JSON 规范，但与大多数的基于
     Javascript 的编码器和解码器一致。否则，它将是一个 *note ValueError:
     1fc. 来编码这些浮点数。

     如果 `sort_keys' 为 true （默认为： ‘False’ ），那么字典的输出是按
     照键排序；这对回归测试很有用，以确保可以每天比较 JSON 序列化。

     如果 `indent' 是一个非负整数或者字符串，那么 JSON 数组元素和对象成
     员会被美化输出为该值指定的缩进等级。 如果缩进等级为零、负数或者
     ‘""’，则只会添加换行符。 ‘None’ (默认值) 选择最紧凑的表达。 使用一
     个正整数会让每一层缩进同样数量的空格。 如果 `indent' 是一个字符串
     (比如 ‘"\t"’)，那个字符串会被用于缩进每一层。

     在 3.2 版更改: 现允许使用字符串作为 `indent' 而不再仅仅是整数。

     当被指定时，`separators' 应当是一个 ‘(item_separator,
     key_separator)’ 元组。当 `indent' 为 ‘None’ 时，默认值取 ‘(', ', ':
     ')’，否则取 ‘(',', ': ')’。为了得到最紧凑的 JSON 表达式，你应该指定
     其为 ‘(',', ':')’ 以消除空白字符。

     在 3.4 版更改: 现当 `indent' 不是 ‘None’ 时，采用 ‘(',', ': ')’ 作
     为默认值。

     当 `default' 被指定时，其应该是一个函数，每当某个对象无法被序列化时
     它会被调用。它应该返回该对象的一个可以被 JSON 编码的版本或者引发一
     个 *note TypeError: 193.。如果没有被指定，则会直接引发 *note
     TypeError: 193.。

     在 3.6 版更改: 所有形参现在都是 *note 仅限关键字参数: 2ad.。

      -- 方法: default (o)

          在子类中实现这种方法使其返回 `o' 的可序列化对象，或者调用基础
          实现（引发 *note TypeError: 193. ）。

          比如说，为了支持任意迭代器，你可以像这样实现默认设置:

               def default(self, o):
                  try:
                      iterable = iter(o)
                  except TypeError:
                      pass
                  else:
                      return list(iterable)
                  # Let the base class default method raise the TypeError
                  return json.JSONEncoder.default(self, o)

      -- 方法: encode (o)

          返回 Python `o' 数据结构的 JSON 字符串表达方式。例如:

               >>> json.JSONEncoder().encode({"foo": ["bar", "baz"]})
               '{"foo": ["bar", "baz"]}'

      -- 方法: iterencode (o)

          编码给定对象 `o' ，并且让每个可用的字符串表达方式。例如:

               for chunk in json.JSONEncoder().iterencode(bigobject):
                   mysocket.write(chunk)


File: python.info,  Node: 异常<13>,  Next: 标准符合性和互操作性,  Prev: 编码器和解码器,  Up: json --- JSON 编码和解码器

5.19.2.3 异常
.............

 -- 例外: json.JSONDecodeError (msg, doc, pos)

     拥有以下附加属性的 *note ValueError: 1fc. 的子类：

      -- 属性: msg

          未格式化的错误消息。

      -- 属性: doc

          正在解析的 JSON 文档。

      -- 属性: pos

          The start index of `doc' where parsing failed.

      -- 属性: lineno

          The line corresponding to `pos'.

      -- 属性: colno

          The column corresponding to `pos'.

     3.5 新版功能.


File: python.info,  Node: 标准符合性和互操作性,  Next: 命令行界面<4>,  Prev: 异常<13>,  Up: json --- JSON 编码和解码器

5.19.2.4 标准符合性和互操作性
.............................

JSON 格式由 RFC 7159(1) 和 ECMA-404(2) 指定。此段落详细讲了这个模块符合
RFC 的级别。简单来说， *note JSONEncoder: 60f. 和 *note JSONDecoder:
610. 子类，和明确提到的参数以外的参数，不作考虑。

此模块不严格遵循于 RFC ，它实现了一些扩展是有效的 Javascript 但不是有效
的 JSON。尤其是：

   - 无限和 NaN 数值是被接受并输出；

   - 对象内的重复名称是接受的，并且仅使用最后一对属性-值对的值。

自从 RFC 允许符合 RFC 的语法分析程序接收 不符合 RFC 的输入文本以来，这个
模块的解串器在默认状态下默认符合 RFC 。

* Menu:

* 字符编码::
* Infinite 和 NaN 数值::
* 对象中的重复名称::
* 顶级非对象，非数组值::
* 实现限制::

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc7159.html

   (2) 
http://www.ecma-international.org/publications/standards/Ecma-404.htm


File: python.info,  Node: 字符编码,  Next: Infinite 和 NaN 数值,  Up: 标准符合性和互操作性

5.19.2.5 字符编码
.................

RFC 要求使用 UTF-8 ， UTF-16 ，或 UTF-32 之一来表示 JSON ，为了最大互通
性推荐使用 UTF-8 。

RFC允许，尽管不是必须的，这个模块的序列化默认设置为 `ensure_ascii=True'
，这样消除输出以便结果字符串至容纳 ASCII 字符。

`ensure_ascii' 参数以外，此模块是严格的按照在 Python 对象和 *note
Unicode strings: 339. 间的转换定义的，并且因此不能直接解决字符编码的问题
。

RFC 禁止添加字符顺序标记（ BOM ）在 JSON 文本的开头，这个模块的序列化器
不添加 BOM 标记在它的输出上。 RFC，准许 JSON 反序列化器忽略它们输入中的
初始 BOM 标记，但不要求。此模块的反序列化器引发 *note ValueError: 1fc. 当
存在初始 BOM 标记。

RFC 不会明确禁止包含字节序列的 JSON 字符串这不对应有效的 Unicode 字符（
比如 不成对的 UTF-16 的替代物），但是它确实指出它们可能会导致互操作性问
题。默认下，模块对这样的序列接受和输出（当在原始 *note str: 339. 存在时
）代码点。


File: python.info,  Node: Infinite 和 NaN 数值,  Next: 对象中的重复名称,  Prev: 字符编码,  Up: 标准符合性和互操作性

5.19.2.6 Infinite 和 NaN 数值
.............................

RFC 不允许 infinite 或者 NaN 数值的表达方式。尽管这样，默认情况下，此模
块接受并且输出 ‘Infinity’ ， ‘-Infinity’，和 ‘NaN’ 好像它们是有效的
JSON数字字面值

     >>> # Neither of these calls raises an exception, but the results are not valid JSON
     >>> json.dumps(float('-inf'))
     '-Infinity'
     >>> json.dumps(float('nan'))
     'NaN'
     >>> # Same when deserializing
     >>> json.loads('-Infinity')
     -inf
     >>> json.loads('NaN')
     nan

序列化器中， `allow_nan' 参数可用于替代这个行为。反序列化器中，
`parse_constant' 参数，可用于替代这个行为。


File: python.info,  Node: 对象中的重复名称,  Next: 顶级非对象，非数组值,  Prev: Infinite 和 NaN 数值,  Up: 标准符合性和互操作性

5.19.2.7 对象中的重复名称
.........................

RFC 具体说明了 在 JSON对象里的名字应该是唯一的，但没有规定如何处理JSON对
象中的重复名称。默认下，此模块不引发异常；作为替代，对于给定名它将忽略除
姓-值对之外的所有对:

     >>> weird_json = '{"x": 1, "x": 2, "x": 3}'
     >>> json.loads(weird_json)
     {'x': 3}

The `object_pairs_hook' parameter can be used to alter this behavior.


File: python.info,  Node: 顶级非对象，非数组值,  Next: 实现限制,  Prev: 对象中的重复名称,  Up: 标准符合性和互操作性

5.19.2.8 顶级非对象，非数组值
.............................

过时的 RFC 4627(1) 指定的旧版本 JSON 要求 JSON 文本顶级值必须是 JSON 对
象或数组（ Python *note dict: 1b9. 或 *note list: 263. ），并且不能是
JSON null 值，布尔值，数值或者字符串值。 RFC 7159(2) 移除这个限制，此模
块没有并且从未在序列化器和反序列化器中实现这个限制。

无论如何，为了最大化地获取互操作性，你可能希望自己遵守该原则。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc4627.html

   (2) https://tools.ietf.org/html/rfc7159.html


File: python.info,  Node: 实现限制,  Prev: 顶级非对象，非数组值,  Up: 标准符合性和互操作性

5.19.2.9 实现限制
.................

一些 JSON 反序列化器的实现应该在以下方面做出限制：

   * 可接受的 JSON 文本大小

   * 嵌套 JSON 对象和数组的最高水平

   * JSON 数字的范围和精度

   * JSON 字符串的内容和最大长度

此模块不强制执行任何上述限制，除了相关的 Python 数据类型本身或者 Python
解释器本身的限制以外。

当序列化为 JSON ，在应用中当心此类限制这可能破坏你的 JSON 。特别是，通常
将 JSON 数字反序列化为 IEEE 754 双精度数字，从而受到该表示方式的范围和精
度限制。这是特别相关的，当序列化非常大的 Python *note int: 185. 值时，或
者当序列化 "exotic" 数值类型的实例时比如 *note decimal.Decimal: 189. 。


File: python.info,  Node: 命令行界面<4>,  Prev: 标准符合性和互操作性,  Up: json --- JSON 编码和解码器

5.19.2.10 命令行界面
....................

`源代码：' Lib/json/tool.py(1)

__________________________________________________________________

The *note json.tool: a6. module provides a simple command line interface
to validate and pretty-print JSON objects.

如果未指定可选的 ‘infile’ 和 ‘outfile’ 参数，则将分别使用 *note
sys.stdin: 316. 和 *note sys.stdout: 317.:

     $ echo '{"json": "obj"}' | python -m json.tool
     {
         "json": "obj"
     }
     $ echo '{1.2:3.4}' | python -m json.tool
     Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

在 3.5 版更改: 输出现在将与输入顺序保持一致。 请使用 *note –sort-keys:
290d. 选项来将输出按照键的字母顺序排序。

* Menu:

* 命令行选项: 命令行选项<4>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/json/tool.py


File: python.info,  Node: 命令行选项<4>,  Up: 命令行界面<4>

5.19.2.11 命令行选项
....................

 -- 程序选项: infile

     要被验证或美化打印的 JSON 文件：

          $ python -m json.tool mp_films.json
          [
              {
                  "title": "And Now for Something Completely Different",
                  "year": 1971
              },
              {
                  "title": "Monty Python and the Holy Grail",
                  "year": 1975
              }
          ]

     如果 `infile' 未指定，则从 *note sys.stdin: 316. 读取。

 -- 程序选项: outfile

     将 `infile' 输出写入到给定的 `outfile'。 在其他情况下写入到 *note
     sys.stdout: 317.。

 -- 程序选项: --sort-keys

     将字典输出按照键的字母顺序排序。

     3.5 新版功能.

 -- 程序选项: --json-lines

     将每个输入行解析为单独的 JSON 对象。

     3.8 新版功能.

 -- 程序选项: -h, --help

     显示帮助消息。

备注
....


File: python.info,  Node: mailcap --- Mailcap 文件处理,  Next: mailbox --- 操作多种格式的邮箱,  Prev: json --- JSON 编码和解码器,  Up: 互联网数据处理

5.19.3 ‘mailcap’ — Mailcap 文件处理
-----------------------------------

`源代码:' Lib/mailcap.py(1)

__________________________________________________________________

Mailcap 文件可用来配置支持 MIME 的应用例如邮件阅读器和 Web 浏览器如何响
应具有不同 MIME 类型的文件。 （"mailcap" 这个名称源自短语"mail
capability"。） 例如，一个 mailcap 文件可能包含 ‘video/mpeg; xmpeg %s’ 这
样的行。 然后，如果用户遇到 MIME 类型为 ‘video/mpeg’ 的邮件消息或 Web 文
档时，‘%s’ 将被替换为一个文件名（通常是一个临时文件）并且将自动启动
‘xmpeg’ 程序来查看该文件。

mailcap 格式的文档见 RFC 1524(2), "A User Agent Configuration Mechanism
For Multimedia Mail Format Information"，但它并不是一个因特网标准。 不过
，mailcap 文件在大多数 Unix 系统上都受到支持。

 -- 函数: mailcap.findmatch (caps, MIMEtype, key='view',
          filename='/dev/null', plist=[])

     返回一个 2 元组；其中第一个元素是包含所要执行命令的字符串 (它可被传
     递给 *note os.system(): dc9.)，第二个元素是对应于给定 MIME 类型的
     mailcap 条目。 如果找不到匹配的 MIME 类型，则将返回 ‘(None, None)’。

     `key' 是所需字段的名称，它代表要执行的活动类型；默认值是 ’view’，因
     为在最通常的情况下你只是想要查看 MIME 类型数据的正文。 其他可能的值
     还有 ’compose’ 和 ’edit’，分别用于想要创建给定 MIME 类型正文或修改
     现有正文数据的情况。 请参阅 RFC 1524(3) 获取这些字段的完整列表。

     `filename' 是在命令行中用来替换 ‘%s’ 的文件名；默认值 ‘'/dev/null'’
     几乎肯定不是你想要的，因此通常你要通过指定一个文件名来重载它。

     `plist' 可以是一个包含命名形参的列表；默认值只是一个空列表。 列表中
     的每个条目必须为包含形参名称的字符串、等于号 (‘'='’) 以及形参的值。
     Mailcap 条目可以包含形如 ‘%{foo}’ 的命名形参，它将由名为 ’foo’ 的形
     参的值所替换。 例如，如果命令行 ‘showpartial %{id} %{number}
     %{total}’ 是在一个 mailcap 文件中，并且 `plist' 被设为 ‘['id=1',
     'number=2', 'total=3']’，则结果命令行将为 ‘'showpartial 1 2 3'’。

     在 mailcap 文件中，可以指定可选的 "test" 字段来检测某些外部条件（例
     如所使用的机器架构或窗口系统）来确定是否要应用 mailcap 行。 *note
     findmatch(): 2915. 将自动检查此类条件并在检查未通过时跳过条目。

 -- 函数: mailcap.getcaps ()

     返回一个将 MIME 类型映射到 mailcap 文件条目列表的字典。 此字典必须
     被传给 *note findmatch(): 2915. 函数。 条目会被存储为字典列表，但并
     不需要了解此表示形式的细节。

     此信息来自在系统中找到的所有 mailcap 文件。 用户的 mailcap 文件
     ‘$HOME/.mailcap’ 中的设置将覆盖系统 mailcap 文件 ‘/etc/mailcap’,
     ‘/usr/etc/mailcap’ 和 ‘/usr/local/etc/mailcap’ 中的设置。

一个用法示例:

     >>> import mailcap
     >>> d = mailcap.getcaps()
     >>> mailcap.findmatch(d, 'video/mpeg', filename='tmp1223')
     ('xmpeg tmp1223', {'view': 'xmpeg %s'})

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/mailcap.py

   (2) https://tools.ietf.org/html/rfc1524.html

   (3) https://tools.ietf.org/html/rfc1524.html


File: python.info,  Node: mailbox --- 操作多种格式的邮箱,  Next: mimetypes --- 映射文件夹到 MIME 类型,  Prev: mailcap --- Mailcap 文件处理,  Up: 互联网数据处理

5.19.4 ‘mailbox’ — 操作多种格式的邮箱
-------------------------------------

`源代码：' Lib/mailbox.py(1)

__________________________________________________________________

本模块定义了两个类，*note Mailbox: beb. 和 *note Message: bef.，用于访问
和操作磁盘中的邮箱及其所包含的电子邮件。 *note Mailbox: beb. 提供了类似
字典的从键到消息的映射。 *note Message: bef. 为 *note email.message: 72.
模块的 *note Message: 54a. 类增加了特定格式专属的状态和行为。 支持的邮箱
格式有 Maildir, mbox, MH, Babyl 以及 MMDF。

参见
....

模块 *note email: 69.

     表示和操作邮件消息。

* Menu:

* Mailbox 对象::
* Message 对象::
* 异常: 异常<14>.
* 例子: 例子<18>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/mailbox.py


File: python.info,  Node: Mailbox 对象,  Next: Message 对象,  Up: mailbox --- 操作多种格式的邮箱

5.19.4.1 ‘Mailbox’ 对象
.......................

 -- 类: mailbox.Mailbox

     一个邮箱，它可以被检视和修改。

     *note Mailbox: beb. 类定义了一个接口并且它不应被实例化。 而是应该让
     格式专属的子类继承 *note Mailbox: beb. 并且你的代码应当实例化一个特
     定的子类。

     *note Mailbox: beb. 接口类似于字典，其中每个小键都有对应的消息。 键
     是由 *note Mailbox: beb. 实例发出的，它们将由实例来使用并且只对该
     *note Mailbox: beb. 实例有意义。 键会持续标识一条消息，即使对应的消
     息已被修改，例如被另一条消息所替代。

     可以使用 set 型方法 *note add(): bea. 将消息添加到 *note Mailbox:
     beb. 并可以使用 ‘del’ 语句或 set 型方法 *note remove(): 291b. 和
     *note discard(): 291c. 将其移除。

     *note Mailbox: beb. 接口语义在某些值得注意的方面与字典语义有所不同
     。 每次请求消息时，都会基于邮箱的当前状态生成一个新的表示形式（通常
     为 *note Message: bef. 实例）。 类似地，当向 *note Mailbox: beb. 实
     例添加消息时，所提供的消息表示形式的内容将被复制。 无论在哪种情况下
     *note Mailbox: beb. 实例都不会保留对消息表示形式的引用。

     默认的 *note Mailbox: beb. 迭代器会迭代消息表示形式，而不像默认的字
     典迭代器那样迭代键。 此外，在迭代期间修改邮箱是安全且有明确定义的。
     在创建迭代器之后被添加到邮箱的消息将对该迭代不可见。 在迭代器产出消
     息之前被从邮箱移除的消息将被静默地跳过，但是使用来自迭代器的键也有
     可能导致 *note KeyError: 2c8. 异常，如果对应的消息后来被移除的话。

          警告: 在修改可能同时被其他某个进程修改的邮箱时要非常小心。 用
          于此种任务的最安全邮箱格式是 Maildir；请尽量避免使用 mbox 之类
          的单文件格式进行并发写入。 如果你正在修改一个邮箱，你 `必须' 在
          读取文件中的任何消息或者执行添加或删除消息等修改操作 `之前' 通
          过调用 *note lock(): 291d. 以及 *note unlock(): 291e. 方法来锁
          定它。 如果未锁定邮箱则可能导致丢失消息或损坏整个邮箱的风险。

     *note Mailbox: beb. 实例具有下列方法:

      -- 方法: add (message)

          将 `message' 添加到邮箱并返回分配给它的键。

          形参 `message' 可以是 *note Message: bef. 实例、*note
          email.message.Message: 54a. 实例、字符串、字节串或文件类对象（
          应当以二进制模式打开）。 如果 `message' 是适当的格式专属 *note
          Message: bef. 子类的实例（例如，如果它是一个 *note
          mboxMessage: 27eb. 实例而这是一个 *note mbox: 291f. 实例），将
          使用其格式专属的信息。 在其他情况下，则会使用合理的默认值作为
          格式专属的信息。

          在 3.2 版更改: 增加了对二进制输入的支持。

      -- 方法: remove (key)
      -- 方法: __delitem__ (key)
      -- 方法: discard (key)

          从邮箱中删除对应于 `key' 的消息。

          当消息不存在时，如果此方法是作为 *note remove(): 291b. 或
          *note __delitem__(): 2920. 调用则会引发 *note KeyError: 2c8. 异
          常，而如果此方法是作为 *note discard(): 291c. 调用则不会引发异
          常。 如果下层邮箱格式支持来自其他进程的并发修改则 *note
          discard(): 291c. 的行为可能是更为适合的。

      -- 方法: __setitem__ (key, message)

          将 `key' 所对应的消息替换为 `message'。 如果没有与 `key' 所对
          应的消息则会引发 *note KeyError: 2c8. 异常。

          与 *note add(): bea. 一样，形参 `message' 可以是 *note
          Message: bef. 实例、*note email.message.Message: 54a. 实例、字
          符串、字节串或文件类对象（应当以二进制模式打开）。 如果
          `message' 是适当的格式专属 *note Message: bef. 子类的实例（举
          例来说，如果它是一个 *note mboxMessage: 27eb. 实例而这是一个
          *note mbox: 291f. 实例），将使用其格式专属的信息。 在其他情况
          下，当前与 `key' 所对应的消息的格式专属信息则会保持不变。

      -- 方法: iterkeys ()
      -- 方法: keys ()

          如果通过 *note iterkeys(): 2922. 调用则返回一个迭代所有键的迭
          代器，或者如果通过 *note keys(): 2923. 调用则返回一个键列表。

      -- 方法: itervalues ()
      -- 方法: __iter__ ()
      -- 方法: values ()

          如果通过 *note itervalues(): 2924. 或 *note __iter__(): 2925.
          调用则返回一个迭代所有消息的表示形式的迭代器，或者如果通过
          *note values(): 2926. 调用则返回一个由这些表示形式组成的列表。
          消息会被表示为适当的格式专属 *note Message: bef. 子类的实例，
          除非当 *note Mailbox: beb. 实际被初始化时指定了自定义的消息工
          厂函数。

               注解: *note __iter__(): 2925. 的行为与字典不同，后者是对
               键进行迭代。

      -- 方法: iteritems ()
      -- 方法: items ()

          如果通过 *note iteritems(): 2927. 调用则返回一个迭代 (`key',
          `message') 对的迭代器，其中 `key' 为键而 `message' 为消息的表
          示形式，或者如果通过or return a list of such pairs if called
          as *note items(): 2928. 调用则返回一个由这种键值对组成的列表。
          消息会被表示为适当的格式专属 *note Message: bef. 子类的实例，
          除非当 *note Mailbox: beb. 实例被初始化时指定了自定义的消息工
          厂函数。

      -- 方法: get (key, default=None)
      -- 方法: __getitem__ (key)

          返回对应于 `key' 的消息的表示形式。 当对应的消息不存在时，如果
          通过 *note get(): 2929. 调用则返回 `default' 而如果通过 *note
          __getitem__(): 292a. 调用此方法则会引发 *note KeyError: 2c8. 异
          常。 消息会被表示为适当的格式专属 *note Message: bef. 子类的实
          例，除非当 *note Mailbox: beb. 实例被初始化时指定了自定义的消
          息工厂函数。

      -- 方法: get_message (key)

          将对应于 `key' 的消息的表示形式作为适当的格式专属 *note
          Message: bef. 子类的实例返回，或者如果对应的消息不存在则会引发
          *note KeyError: 2c8. 异常。

      -- 方法: get_bytes (key)

          返回对应于 `key' 的消息的字节表示形式，或者如果对应的消息不存
          在则会引发 *note KeyError: 2c8. 异常。

          3.2 新版功能.

      -- 方法: get_string (key)

          返回对应于 `key' 的消息的字符串表示形式，或者如果对应的消息不
          存在则会引发 *note KeyError: 2c8. 异常。 消息是通过 *note
          email.message.Message: 54a. 处理来将其转换为纯 7bit 表示形式的
          。

      -- 方法: get_file (key)

          返回对应于 `key' 的消息的文件类表示形式，或者如果对应的消息不
          存在则会引发 *note KeyError: 2c8. 异常。 文件类对象的行为相当
          于以二进制模式打开。 当不再需要此文件时应当将其关闭。

          在 3.2 版更改: 此文件对象实际上是二进制文件；之前它被不正确地
          以文本模式返回。 并且，此文件类对象现在还支持上下文管理协议：
          你可以使用 *note with: 6f2. 语句来自动关闭它。

               注解: 不同于其他消息表示形式，文件类表示形式并不一定独立
               于创建它们的 *note Mailbox: beb. 实例或下层的邮箱。 每个
               子类都会提供更具体的文档。

      -- 方法: __contains__ (key)

          如果 `key' 有对应的消息则返回 ‘True’，否则返回 ‘False’。

      -- 方法: __len__ ()

          返回邮箱中消息的数量。

      -- 方法: clear ()

          从邮箱中删除所有消息。

      -- 方法: pop (key, default=None)

          返回对应于 `key' 的消息的表示形式并删除该消息。 如果对应的消息
          不存在则返回 `default'。 消息会被表示为适当的格式专属 *note
          Message: bef. 子类的实例，除非当 *note Mailbox: beb. 实例被初
          始化时指定了自定义的消息工厂函数。

      -- 方法: popitem ()

          返回一个任意的 (`key', `message') 对，其中 `key' 为键而
          `message' 为消息的表示形式，并删除对应的消息。 如果邮箱为空，
          则会引发 *note KeyError: 2c8. 异常。 消息会被表示为适当的格式
          专属 *note Message: bef. 子类的实例，除非当 *note Mailbox:
          beb. 实例被初始化时指定了自定义的消息工厂函数。

      -- 方法: update (arg)

          形参 `arg' 应当是 `key' 到 `message' 的映射或 (`key',
          `message') 对的可迭代对象。 用来更新邮箱以使得对于每个给定的
          `key' 和 `message'，与 `key' 相对应的消息会被设为 `message'，
          就像通过使用 *note __setitem__(): 2921. 一样。 类似于 *note
          __setitem__(): 2921.，每个 `key' 都必须在邮箱中有一个对应的消
          息否则将会引发 *note KeyError: 2c8. 异常，因此在通常情况下将
          `arg' 设为 *note Mailbox: beb. 实例是不正确的。

               注解: 与字典不同，关键字参数是不受支持的。

      -- 方法: flush ()

          将所有待定的更改写入到文件系统。 对于某些 *note Mailbox: beb.
          子类来说，更改总是被立即写入因而 *note flush(): 2932. 并不会做
          任何事，但您仍然应当养成调用此方法的习惯。

      -- 方法: lock ()

          在邮箱上获取一个独占式咨询锁以使其他进程知道不能修改它。 如果
          锁无法被获取则会引发 *note ExternalClashError: 2933.。 所使用
          的具体锁机制取决于邮箱的格式。 在对邮箱内容进行任何修改之前你
          应当 `总是' 锁定它。

      -- 方法: unlock ()

          释放邮箱上的锁，如果存在的话。

      -- 方法: close ()

          刷新邮箱，如果必要则将其解锁。 并关闭所有打开的文件。 对于某些
          *note Mailbox: beb. 子类来说，此方法并不会做任何事。

* Menu:

* Maildir::
* mbox::
* MH::
* Babyl::
* MMDF::


File: python.info,  Node: Maildir,  Next: mbox,  Up: Mailbox 对象

5.19.4.2 ‘Maildir’
..................

 -- 类: mailbox.Maildir (dirname, factory=None, create=True)

     *note Mailbox: beb. 的一个子类，用于 Maildir 格式的邮箱。 形参
     `factory' 是一个可调用对象，它接受一个文件类消息表示形式（其行为相
     当于以二进制模式打开）并返回一个自定义的表示形式。 如果 `factory' 为
     ‘None’，则会使用 *note MaildirMessage: 2937. 作为默认的消息表示形式
     。 如果 `create' 为 ‘True’，则当邮箱不存在时会创建它。

     如果 `create' 为 ‘True’ 且 `dirname' 路径存在，它将被视为已有的
     maildir 而无需尝试验证其目录布局。

     使用 `dirname' 这个名称而不使用 `path' 是出于历史原因。

     Maildir 是一种基于目录的邮箱格式，它是针对 qmail 邮件传输代理而发明
     的，现在也得到了其他程序的广泛支持。 Maildir 邮箱中的消息存储在一个
     公共目录结构中的单独文件内。 这样的设计允许 Maildir 邮箱被多个彼此
     无关的程序访问和修改而不会导致数据损坏，因此文件锁定操作是不必要的
     。

     Maildir 邮箱包含三个子目录，分别是: ‘tmp’, ‘new’ 和 ‘cur’。 消息会
     不时地在 ‘tmp’ 子目录中创建然后移至 ‘new’ 子目录来结束投递。 后续电
     子邮件客户端可能将消息移至 ‘cur’ 子目录并将有关消息状态的信息存储在
     附带到其文件名的特殊 "info" 小节中。

     Courier 电子邮件传输代理所引入的文件夹风格也是受支持的。 主邮箱中任
     何子目录只要其名称的第一个字符是 ‘'.'’ 就会被视为文件夹。 文件夹名
     称会被 *note Maildir: cb0. 表示为不带前缀 ‘'.'’ 的形式。 每个文件夹
     自身都是一个 Maildir 邮箱但不应包含其他文件夹。 逻辑嵌套关系是使用
     ‘'.'’ 来划定层级，例如 "Archived.2005.07"。

          注解: Maildir 规范要求使用在特定消息文件名中使用冒号 (‘':'’)。
          但是，某些操作系统不允许将此字符用于文件名，如果你希望在这些操
          作系统上使用类似 Maildir 的格式，你应当指定改用另一个字符。 叹
          号 (‘'!'’) 是一个受欢迎的选择。 例如:

               import mailbox
               mailbox.Maildir.colon = '!'

          ‘colon’ 属性也可以在每个实例上分别设置。

     *note Maildir: cb0. 实例具有 *note Mailbox: beb. 的所有方法及下列附
     加方法:

      -- 方法: list_folders ()

          返回所有文件夹名称的列表。

      -- 方法: get_folder (folder)

          返回表示名称为 `folder' 的文件夹的 *note Maildir: cb0. 实例。
          如果文件夹不存在则会引发 *note NoSuchMailboxError: 293a. 异常
          。

      -- 方法: add_folder (folder)

          创建名称为 `folder' 的文件夹并返回表示它的 *note Maildir: cb0.
          实例。

      -- 方法: remove_folder (folder)

          删除名称为 `folder' 的文件夹。 如果文件夹包含任何消息，则将引
          发 *note NotEmptyError: 293d. 异常且该文件夹将不会被删除。

      -- 方法: clean ()

          从邮箱中删除最近 36 小时内未被访问过的临时文件。 Maildir 规范
          要求邮件阅读程序应当时常进行此操作。

     *note Maildir: cb0. 所实现的某些方法 *note Mailbox: beb. 值得进行特
     别的说明:

      -- 方法: add (message)
      -- 方法: __setitem__ (key, message)
      -- 方法: update (arg)

               警告: 这些方法会基于当前进程 ID 来生成唯一文件名。 当使用
               多线程时，可能发生未被检测到的名称冲突并导致邮箱损坏，除
               非是对线程进行协调以避免使用这些方法同时操作同一个邮箱。

      -- 方法: flush ()

          对 Maildir 邮箱的所有更改都会立即被应用，所以此方法并不会做任
          何事情。

      -- 方法: lock ()
      -- 方法: unlock ()

          Maildir 邮箱不支持（或要求）锁定操作，所以此方法并不会做任何事
          情。

      -- 方法: close ()

          *note Maildir: cb0. 实例不保留任何打开的文件并且下层的邮箱不支
          持锁定操作，所以此方法不会做任何事情。

      -- 方法: get_file (key)

          根据主机平台的不同，当返回的文件保持打开状态时可能无法修改或移
          除下层的消息。

参见
....

Courier 上的 maildir 指南页面(1)

     该格式的规格说明。 描述了用于支持文件夹的通用扩展。

使用 maildir 格式(2)

     Maildir 发明者对它的说明。 包括已更新的名称创建方案和 "info" 语义的
     相关细节。

   ---------- Footnotes ----------

   (1) http://www.courier-mta.org/maildir.html

   (2) https://cr.yp.to/proto/maildir.html


File: python.info,  Node: mbox,  Next: MH,  Prev: Maildir,  Up: Mailbox 对象

5.19.4.3 ‘mbox’
...............

 -- 类: mailbox.mbox (path, factory=None, create=True)

     *note Mailbox: beb. 的子类，用于 mbox 格式的邮箱。 形参 `factory' 是
     一个可调用对象，它接受一个文件类消息表示形式（其行为相当于以二进制
     模式打开）并返回一个自定义的表示形式。 如果 `factory' 为 ‘None’，则
     会使用 *note mboxMessage: 27eb. 作为默认的消息表示形式。 如果
     `create' 为 ‘True’，则当邮箱不存在时会创建它。

     mbox 格式是在 Unix 系统上存储电子邮件的经典格式。 mbox 邮箱中的所有
     消息都存储在一个单独文件中，每条消息的开头由前五个字符为 "From " 的
     行来指明。

     还有一些 mbox 格式变种对原始格式中发现的缺点做了改进，*note mbox:
     291f. 只实现原始格式，有时被称为 `mboxo'。 这意味着当存储消息时
     ‘Content-Length’ 标头如果存在则会被忽略并且消息体中出现于行开头的任
     何 "From " 会被转换为 ">From "，但是当读取消息时 ">From " 则不会被
     转换为 "From "。

     *note mbox: 291f. 所实现的某些 *note Mailbox: beb. 方法值得进行特别
     的说明:

      -- 方法: get_file (key)

          在 *note mbox: 291f. 实例上调用 ‘flush()’ 或 ‘close()’ 之后再
          使用文件可能产生无法预料的结果或者引发异常。

      -- 方法: lock ()
      -- 方法: unlock ()

          使用三种锁机制 — dot 锁，以及可能情况下的 ‘flock()’ 和
          ‘lockf()’ 系统调用。

参见
....

tin 上的 mbox 指南页面(1)

     该格式的规格说明，包括有关锁的详情。

在 Unix 上配置 Netscape Mail: 为何 Content-Length 格式是不好的(2)

     使用原始 mbox 格式而非其变种的一些理由。

"mbox" 是由多个彼此不兼容的邮箱格式构成的家族(3)

     有关 mbox 变种的历史。

   ---------- Footnotes ----------

   (1) http://www.tin.org/bin/man.cgi?section=5&topic=mbox

   (2) https://www.jwz.org/doc/content-length.html

   (3) 
https://www.loc.gov/preservation/digital/formats/fdd/fdd000383.shtml


File: python.info,  Node: MH,  Next: Babyl,  Prev: mbox,  Up: Mailbox 对象

5.19.4.4 ‘MH’
.............

 -- 类: mailbox.MH (path, factory=None, create=True)

     *note Mailbox: beb. 的子类，用于 MH 格式的邮箱。 形参 `factory' 是
     一个可调用对象，它接受一个文件类消息表示形式（其行为相当于以二进制
     模式打开）并返回一个自定义的表示形式。 如果 `factory' 为 ‘None’，则
     会使用 *note MHMessage: 294f. 作为默认的消息表示形式。 如果
     `create' 为 ‘True’，则当邮箱不存在时会创建它。

     MH 是一种基于目录的邮箱格式，它是针对 MH Message Handling System 电
     子邮件用户代理而发明的。 在 MH 邮箱的每条消息都放在单独文件中。 MH
     邮箱中除了邮件消息还可以包含其他 MH 邮箱 (称为 `文件夹')。 文件夹可
     以无限嵌套。 MH 邮箱还支持 `序列'，这是一种命名列表，用来对消息进行
     逻辑分组而不必将其移入子文件夹。 序列是在每个文件夹中名为
     ‘.mh_sequences’ 的文件内定义的。

     *note MH: 294e. 类可以操作 MH 邮箱，但它并不试图模拟 ‘mh’ 的所有行
     为。 特别地，它并不会修改 ‘context’ 或 ‘.mh_profile’ 文件也不会受其
     影响，这两个文件是 ‘mh’ 用来存储状态和配置数据的。

     *note MH: 294e. 实例具有 *note Mailbox: beb. 的所有方法及下列附加方
     法:

      -- 方法: list_folders ()

          返回所有文件夹名称的列表。

      -- 方法: get_folder (folder)

          返回表示名称为 `folder' 的文件夹的 *note MH: 294e. 实例。 如果
          文件夹不存在则会引发 *note NoSuchMailboxError: 293a. 异常。

      -- 方法: add_folder (folder)

          创建名称为 `folder' 的文件夹并返回表示它的 *note MH: 294e. 实
          例。

      -- 方法: remove_folder (folder)

          删除名称为 `folder' 的文件夹。 如果文件夹包含任何消息，则将引
          发 *note NotEmptyError: 293d. 异常且该文件夹将不会被删除。

      -- 方法: get_sequences ()

          返回映射到键列表的序列名称字典。 如果不存在任何序列，则返回空
          字典。

      -- 方法: set_sequences (sequences)

          根据由映射到键列表的名称组成的字典 `sequences' 来重新定义邮箱
          中的序列，该字典与 *note get_sequences(): 2954. 返回值的形式一
          样。

      -- 方法: pack ()

          根据需要重命名邮箱中的消息以消除序号中的空缺。 序列列表中的条
          目会做相应的修改。

               注解: 已发送的键会因此操作而失效并且不应当被继续使用。

     *note MH: 294e. 所实现的某些 *note Mailbox: beb. 方法值得进行特别的
     说明:

      -- 方法: remove (key)
      -- 方法: __delitem__ (key)
      -- 方法: discard (key)

          这些方法会立即删除消息。 通过在名称前加缀一个冒号作为消息删除
          标记的 MH 惯例不会被使用。

      -- 方法: lock ()
      -- 方法: unlock ()

          使用三种锁机制 — dot 锁，以及可能情况下下 ‘flock()’ 和
          ‘lockf()’ 系统调用。 对于 MH 邮箱来说，锁定邮箱意味着锁定
          ‘.mh_sequences’ 文件，并且仅在执行会影响单独消息文件的操作期间
          锁定单独消息文件。

      -- 方法: get_file (key)

          根据主机平台的不同，当返回的文件保持打开状态时可能无法移除下层
          的消息。

      -- 方法: flush ()

          对 MH 邮箱的所有更改都会立即被应用，所以此方法并不会做任何事情
          。

      -- 方法: close ()

          *note MH: 294e. 实例不保留任何打开的文件，所以此方法等价于
          *note unlock(): 295b.。

参见
....

nmh - Message Handling System(1)

     ‘nmh’ 的主页，这是原始 ‘mh’ 的更新版本。

MH & nmh: Email for Users & Programmers(2)

     使用 GPL 许可证的介绍 ‘mh’ 与 ‘nmh’ 的图书，包含有关该邮箱格式的各
     种信息。

   ---------- Footnotes ----------

   (1) http://www.nongnu.org/nmh/

   (2) https://rand-mh.sourceforge.io/book/


File: python.info,  Node: Babyl,  Next: MMDF,  Prev: MH,  Up: Mailbox 对象

5.19.4.5 ‘Babyl’
................

 -- 类: mailbox.Babyl (path, factory=None, create=True)

     *note Mailbox: beb. 的子类，用于 Babyl 格式的邮箱。 形参 `factory'
     是一个可调用对象，它接受一个文件类表示形式（其行为相当于以二进制模
     式打开）并返回一个自定义的表示形式。 如果 `factory' 为 ‘None’，则会
     使用 *note BabylMessage: 2962. 作为默认的消息表示形式。 如果
     `create' 为 ‘True’，则当邮箱不存在时会创建它。

     Babyl 是 Rmail 电子邮箱用户代理所使用单文件邮箱格式，包括在 Emacs 中
     。 每条消息的开头由一个包含 Control-Underscore (‘'\037'’) 和
     Control-L (‘'\014'’) 这两个字符的行来指明。 消息的结束由下一条消息
     的开头来指明，或者当为最后一条消息时则由一个包含 Control-Underscore
     (‘'\037'’) 字符的行来指明。

     Babyl 邮箱中的消息带有两组标头：原始标头和所谓的可见标头。 可见标头
     通常为原始标头经过重格式化和删减以更易读的子集。 Babyl 邮箱中的每条
     消息都附带了一个 `标签' 列表，即记录消息相关额外信息的短字符串，邮
     箱中所有的用户定义标签列表会存储于 Babyl 的选项部分。

     *note Babyl: 2961. 实例具有 *note Mailbox: beb. 的所有方法及下列附
     加方法:

      -- 方法: get_labels ()

          返回邮箱中使用的所有用户定义标签名称的列表。

               注解: 邮箱中存在哪些标签会通过检查实际的消息而非查询
               Babyl 选项部分的标签列表，但 Babyl 选项部分会在邮箱被修改
               时更新。

     *note Babyl: 2961. 所实现的某些 *note Mailbox: beb. 方法使得进行特
     别的说明:

      -- 方法: get_file (key)

          在 Babyl 邮箱中，消息的标头并不是与消息体存储在一起的。 要生成
          文件类表示形式，标头和消息体会被一起拷贝到一个 *note
          io.BytesIO: 7a4. 实例中，它具有与文件相似的 API。 因此，文件类
          对象实际上独立于下层邮箱，但与字符串表达形式相比并不会更节省内
          存。

      -- 方法: lock ()
      -- 方法: unlock ()

          使用三种锁机制 — dot 锁，以及可能情况下的 ‘flock()’ 和
          ‘lockf()’ 系统调用。

参见
....

Format of Version 5 Babyl Files(1)

     Babyl 格式的规格说明。

Reading Mail with Rmail(2)

     Rmail 的帮助手册，包含了有关 Babyl 语义的一些信息。

   ---------- Footnotes ----------

   (1) https://quimby.gnus.org/notes/BABYL

   (2) 
https://www.gnu.org/software/emacs/manual/html_node/emacs/Rmail.html


File: python.info,  Node: MMDF,  Prev: Babyl,  Up: Mailbox 对象

5.19.4.6 ‘MMDF’
...............

 -- 类: mailbox.MMDF (path, factory=None, create=True)

     *note Mailbox: beb. 的子类，用于 MMDF 格式的邮箱。 形参 `factory' 是
     一个可调用对象，它接受一个文件类消息表示形式（其行为相当于以二进制
     模式打开）并返回一个自定义的表示形式。 如果 `factory' 为 ‘None’，则
     会使用 *note MMDFMessage: 296a. 作为默认的消息表示形式。 如果
     `create' 为 ‘True’，则当邮箱不存在时会创建它。

     MMDF 是一种专用于电子邮件传输代理 Multichannel Memorandum
     Distribution Facility 的单文件邮箱格式。 每条消息使用与 mbox 消息相
     同的形式，但其前后各有包含四个 Control-A (‘'\001'’) 字符的行。 与
     mbox 格式一样，每条消息的开头由一个前五个字符为 "From " 的行来指明
     ，但当存储消息时额外出现的 "From " 不会被转换为 ">From " 因为附加的
     消息分隔符可防止将这些内容误认为是后续消息的开头。

     *note MMDF: 2969. 所实现的某些 *note Mailbox: beb. 方法值得进行特别
     的说明:

      -- 方法: get_file (key)

          在 *note MMDF: 2969. 实例上调用 ‘flush()’ 或 ‘close()’ 之后再
          使用文件可能产生无法预料的结果或者引发异常。

      -- 方法: lock ()
      -- 方法: unlock ()

          使用三种锁机制 — dot 锁，以及可能情况下的 ‘flock()’ 和
          ‘lockf()’ 系统调用。

参见
....

tin 上的 mmdf 指南页面(1)

     MMDF 格式的规格说明，来自新闻阅读器 tin 的文档。

MMDF(2)

     一篇描述 Multichannel Memorandum Distribution Facility 的维基百科文
     章。

   ---------- Footnotes ----------

   (1) http://www.tin.org/bin/man.cgi?section=5&topic=mmdf

   (2) https://en.wikipedia.org/wiki/MMDF


File: python.info,  Node: Message 对象,  Next: 异常<14>,  Prev: Mailbox 对象,  Up: mailbox --- 操作多种格式的邮箱

5.19.4.7 ‘Message’ 对象
.......................

 -- 类: mailbox.Message (message=None)

     *note email.message: 72. 模块的 *note Message: 54a. 的子类。 *note
     mailbox.Message: bef. 的子类添加了特定邮箱格式专属的状态和行为。

     如果省略了 `message'，则新实例会以默认的空状态被创建。 如果
     `message' 是一个 *note email.message.Message: 54a. 实例，其内容会被
     拷贝；此外，如果 `message' 是一个 *note Message: bef. 实例，则任何
     格式专属信息会尽可能地被拷贝。 如果 `message' 是一个字符串、字节串
     或文件，则它应当包含兼容 RFC 2822(1) 的消息，该消息会被读取和解析。
     文档应当以二进制模式打开，但文本模式的文件也会被接受以向下兼容。

     各个子类所提供的格式专属状态和行为各有不同，但总的来说只有那些不仅
     限于特定邮箱的特性才会被支持（虽然这些特性可能专属于特定邮箱格式）
     。 例如，例如，单文件邮箱格式的文件偏移量和基于目录的邮箱格式的文件
     名都不会被保留，因为它们都仅适用于对应的原始邮箱。 但消息是否已被用
     户读取或标记为重要等状态则会被保留，因为它们适用于消息本身。

     不要求用 *note Message: bef. 实例来表示使用 *note Mailbox: beb. 实
     例所提取到的消息。 在某些情况下，生成 *note Message: bef. 表示形式
     所需的时间和内存空间可能是不可接受的。 对于此类情况，*note Mailbox:
     beb. 实例还提供了字符串和文件类表示形式，并可在初始化 *note
     Mailbox: beb. 实例时指定自定义的消息工厂函数。

* Menu:

* MaildirMessage::
* mboxMessage::
* MHMessage::
* BabylMessage::
* MMDFMessage::

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2822.html


File: python.info,  Node: MaildirMessage,  Next: mboxMessage,  Up: Message 对象

5.19.4.8 ‘MaildirMessage’
.........................

 -- 类: mailbox.MaildirMessage (message=None)

     具有 Maildir 专属行为的消息。 形参 `message' 的含义与 *note
     Message: bef. 构造器一致。

     通常，邮件用户代理应用程序会在用户第一次打开并关闭邮箱之后将 ‘new’
     子目录中的所有消息移至 ‘cur’ 子目录，将这些消息记录为旧消息，无论它
     们是否真的已被阅读。 ‘cur’ 下的每条消息都有一个 "info" 部分被添加到
     其文件名中以存储有关其状态的信息。 （某些邮件阅读器还会把 "info" 部
     分也添加到 ‘new’ 下的消息中。） "info" 部分可以采用两种形式之一：它
     可能包含 "2," 后面跟一个经标准化的旗标列表（例如 "2,FR"）或者它可能
     包含 "1," 后面跟所谓的实验性信息。 Maildir 消息的标准旗标如下:

     Flag       含义          说明
                              
     --------------------------------------------------------------
                              
     D          草稿          正在撰写中
                              
                              
     F          已标记        标记为重要
                              
                              
     P          已读          转发，重新发送或退回
                              
                              
     R          已回复        回复给
                              
                              
     S          查看          读取
                              
                              
     T          已删除        标记为以后删除
                              

     *note MaildirMessage: 2937. 实例提供以下方法：

      -- 方法: get_subdir ()

          返回 "new" (如果消息应当被存储在 ‘new’ 子目录下) 或者 "cur" (如
          果消息应当被存储在 ‘cur’ 子目录下)。

               注解: 消息通常会在其邮箱被访问后被从 ‘new’ 移至 ‘cur’，无
               论该消息是否已被阅读。 如果 msg.get_flags()‘‘ 中的 ‘"S" 为
               ``True’ 则说明消息 ‘msg’ 已被阅读。

      -- 方法: set_subdir (subdir)

          设置消息应当被存储到的子目录。 形参 `subdir' 必须为 "new" 或
          "cur"。

      -- 方法: get_flags ()

          返回一个指明当前所设旗标的字符串。 如果消息符合标准的 Maildir
          格式，则结果为零或按字母顺序各自出现一次的 ‘'D'’, ‘'F'’,
          ‘'P'’, ‘'R'’, ‘'S'’ 和 ‘'T'’ 的拼接。 如果未设任何旗标或者如果
          "info" 包含实验性语义则返回空字符串。

      -- 方法: set_flags (flags)

          设置由 `flags' 所指定的旗标并重置所有其它旗标。

      -- 方法: add_flag (flag)

          设置由 `flag' 所指明的旗标而不改变其他旗标。 要一次性添加一个
          以上的旗标，`flag' 可以为包含一个以上字符的字符串。 当前
          "info" 会被覆盖，无论它是否只包含实验性信息而非旗标。

      -- 方法: remove_flag (flag)

          重置由 `flag' 所指明的旗标而不改变其他旗标。 要一次性移除一个
          以上的旗标，`flag' 可以为包含一个以上字符的字符串。 如果
          "info" 包含实验性信息而非旗标，则当前的 "info" 不会被修改。

      -- 方法: get_date ()

          以表示 Unix 纪元秒数的浮点数形式返回消息的发送日期。

      -- 方法: set_date (date)

          将消息的发送日期设为 `date'，一个表示 Unix 纪元秒数的浮点数。

      -- 方法: get_info ()

          返回一个包含消息的 "info" 的字符串。 这适用于访问和修改实验性
          的 "info" (即不是由旗标组成的列表)。

      -- 方法: set_info (info)

          将 "info" 设为 `info'，这应当是一个字符串。

当一个 *note MaildirMessage: 2937. 实例基于 *note mboxMessage: 27eb. 或
*note MMDFMessage: 296a. 实例被创建时，将会忽略 ‘Status’ 和 ‘X-Status’ 标
头并进行下列转换:

结果状态                 *note mboxMessage: 27eb. 或
                         *note MMDFMessage: 296a. 状态
                         
----------------------------------------------------------------------------
                         
"cur" 子目录             O 标记
                         
                         
F 标记                   F 标记
                         
                         
R 标记                   A 标记
                         
                         
S 标记                   R 标记
                         
                         
T 标记                   D 标记
                         

当一个 *note MaildirMessage: 2937. 实例基于 *note MHMessage: 294f. 实例
被创建时，将进行下列转换:

结果状态                            *note MHMessage: 294f. 状态
                                    
-------------------------------------------------------------------
                                    
"cur" 子目录                        "unseen" 序列
                                    
                                    
"cur" 子目录和 S 旗标               非 "unseen" 序列
                                    
                                    
F 标记                              "flagged" 序列
                                    
                                    
R 标记                              "replied" 序列
                                    

当一个 *note MaildirMessage: 2937. 实例基于 *note BabylMessage: 2962. 实
例被创建时，将进行下列转换:

结果状态                            *note BabylMessage: 2962. 状态
                                    
------------------------------------------------------------------------
                                    
"cur" 子目录                        "unseen" 标签
                                    
                                    
"cur" 子目录和 S 旗标               非 "unseen" 标签
                                    
                                    
P 标记                              "forwarded" 或 "resent" 标签
                                    
                                    
R 标记                              "answered" 标签
                                    
                                    
T 标记                              "deleted" 标签
                                    


File: python.info,  Node: mboxMessage,  Next: MHMessage,  Prev: MaildirMessage,  Up: Message 对象

5.19.4.9 ‘mboxMessage’
......................

 -- 类: mailbox.mboxMessage (message=None)

     具有 mbox 专属行为的消息。 形参 `message' 的含义与 *note Message:
     bef. 构造器一致。

     mbox 邮箱中的消息会一起存储在单个文件中。 发件人的信封地址和发送时
     间通常存储在指明每条消息的起始的以 "From " 打头的行中，不过在 mbox
     的各种实现之间此数据的确切格式具有相当大的差异。 指明消息状态的各种
     旗标，例如是否已读或标记为重要等等通常存储在 ‘Status’ 和 ‘X-Status’
     标头中。

     传统的 mbox 消息旗标如下:

     Flag       含义           说明
                               
     ---------------------------------------------------------------
                               
     R          读取           读取
                               
                               
     O          旧的           以前由MUA检测
                               
                               
     D          已删除         标记为以后删除
                               
                               
     F          已标记         标记为重要
                               
                               
     A          已回复         回复给
                               

     "R" 和 "O" 旗标存储在 ‘Status’ 标头中，而 "D", "F" 和 "A" 旗标存储
     在 ‘X-Status’ 标头中。 旗标和标头通常会按上述顺序显示。

     *note mboxMessage: 27eb. 实例提供了下列方法:

      -- 方法: get_from ()

          返回一个表示在 mbox 邮箱中标记消息起始的 "From " 行的字符串。
          开头的 "From " 和末尾的换行符会被去除。

      -- 方法: set_from (from_, time_=None)

          将 "From " 行设为 `from_'，这应当被指定为不带开头的 "From " 或
          末尾的换行符。 为方便起见，可以指定 `time_' 并将经过适当的格式
          化再添加到 `from_'。 如果指定了 `time_'，它应当是一个 *note
          time.struct_time: 5a2. 实例，适合传入 *note time.strftime():
          b6d. 的元组或者 ‘True’ (以使用 *note time.gmtime(): b47.)。

      -- 方法: get_flags ()

          返回一个指明当前所设旗标的字符串。 如果消息符合规范格式，则结
          果为零或各自出现一次的 ‘'R'’, ‘'O'’, ‘'D'’, ‘'F'’ 和 ‘'A'’ 按
          上述顺序的拼接。

      -- 方法: set_flags (flags)

          设置由 `flags' 所指明的旗标并重启所有其他旗标。 形参 `flags' 应
          当为零或各自出现多次的 ‘'R'’, ‘'O'’, ‘'D'’, ‘'F'’ 和 ‘'A'’ 按
          任意顺序的拼接。

      -- 方法: add_flag (flag)

          设置由 `flag' 所指明的旗标而不改变其他旗标。 要一次性添加一个
          以上的旗标，`flag' 可以为包含一个以上字符的字符串。

      -- 方法: remove_flag (flag)

          重置由 `flag' 所指明的旗标而不改变其他旗标。 要一次性移除一个
          以上的旗标，`flag' 可以为包含一个以上字符的字符串。

当一个 *note mboxMessage: 27eb. 实例基于 *note MaildirMessage: 2937. 实
例被创建时，"From " 行会基于 *note MaildirMessage: 2937. 实例的发送时间
被生成，并进行下列转换:

结果状态              *note MaildirMessage: 2937. 状态
                      
----------------------------------------------------------
                      
R 标记                S 标记
                      
                      
O 标记                "cur" 子目录
                      
                      
D 标记                T 标记
                      
                      
F 标记                F 标记
                      
                      
A 标记                R 标记
                      

当一个 *note mboxMessage: 27eb. 实例基于 *note MHMessage: 294f. 实例被创
建时，将进行下列转换:

结果状态                *note MHMessage: 294f. 状态
                        
-------------------------------------------------------
                        
R 标记 和 O 标记        非 "unseen" 序列
                        
                        
O 标记                  "unseen" 序列
                        
                        
F 标记                  "flagged" 序列
                        
                        
A 标记                  "replied" 序列
                        

当一个 *note mboxMessage: 27eb. 实例基于 *note BabylMessage: 2962. 实例
被创建时，将进行下列转换:

结果状态                *note BabylMessage: 2962. 状态
                        
----------------------------------------------------------
                        
R 标记 和 O 标记        非 "unseen" 标签
                        
                        
O 标记                  "unseen" 标签
                        
                        
D 标记                  "deleted" 标签
                        
                        
A 标记                  "answered" 标签
                        

当一个 *note Message: bef. 实例基于 *note MMDFMessage: 296a. 实例被创建
时，"From " 行会被拷贝并直接对应所有旗标。

结果状态              *note MMDFMessage: 296a. 状态
                      
-------------------------------------------------------
                      
R 标记                R 标记
                      
                      
O 标记                O 标记
                      
                      
D 标记                D 标记
                      
                      
F 标记                F 标记
                      
                      
A 标记                A 标记
                      


File: python.info,  Node: MHMessage,  Next: BabylMessage,  Prev: mboxMessage,  Up: Message 对象

5.19.4.10 ‘MHMessage’
.....................

 -- 类: mailbox.MHMessage (message=None)

     具有 MH 专属行为的消息。 形参 `message' 的含义与 *note Message:
     bef. 构造器一致。

     MH 消息不支持传统意义上的标记或旗标，但它们支持序列，即对任意消息的
     逻辑分组。 某些邮件阅读程序 (但不包括标准 ‘mh’ 和 ‘nmh’) 以与其他格
     式使用旗标类似的方式来使用序列，如下所示:

     序列           说明
                    
     --------------------------------------------------------------
                    
     未读           未读取，但先前被MUA检测到
                    
                    
     已回复         回复给
                    
                    
     已标记         标记为重要
                    

     *note MHMessage: 294f. 实例提供了下列方法:

      -- 方法: get_sequences ()

          返回一个包含此消息的序列的名称的列表。

      -- 方法: set_sequences (sequences)

          设置包含此消息的序列的列表。

      -- 方法: add_sequence (sequence)

          将 `sequence' 添加到包含此消息的序列的列表。

      -- 方法: remove_sequence (sequence)

          将 `sequence' 从包含此消息的序列的列表中移除。

当一个 *note MHMessage: 294f. 实例基于 *note MaildirMessage: 2937. 实例
被创建时，将进行下列转换:

结果状态                 *note MaildirMessage: 2937. 状态
                         
-------------------------------------------------------------
                         
"unseen" 序列            非 S 标记
                         
                         
"replied" 序列           R 标记
                         
                         
"flagged" 序列           F 标记
                         

当一个 *note MHMessage: 294f. 实例基于 *note mboxMessage: 27eb. 或 *note
MMDFMessage: 296a. 实例被创建时，将会忽略 ‘Status’ 和 ‘X-Status’ 标头并
进行下列转换:

结果状态                 *note mboxMessage: 27eb. 或
                         *note MMDFMessage: 296a. 状态
                         
----------------------------------------------------------------------------
                         
"unseen" 序列            非 R 标记
                         
                         
"replied" 序列           A 标记
                         
                         
"flagged" 序列           F 标记
                         

当一个 *note MHMessage: 294f. 实例基于 *note BabylMessage: 2962. 实例被
创建时，将进入下列转换:

结果状态                 *note BabylMessage: 2962. 状态
                         
-----------------------------------------------------------
                         
"unseen" 序列            "unseen" 标签
                         
                         
"replied" 序列           "answered" 标签
                         


File: python.info,  Node: BabylMessage,  Next: MMDFMessage,  Prev: MHMessage,  Up: Message 对象

5.19.4.11 ‘BabylMessage’
........................

 -- 类: mailbox.BabylMessage (message=None)

     具有 Babyl 专属行为的消息。 形参 `message' 的含义与 *note Message:
     bef. 构造器一致。

     某些消息标签被称为 `属性'，根据惯例被定义为具有特殊的含义。 这些属
     性如下所示:

     标签            说明
                     
     ---------------------------------------------------------------
                     
     未读            未读取，但先前被MUA检测到
                     
                     
     deleted         标记为以后删除
                     
                     
     filed           复制到另一个文件或邮箱
                     
                     
     answered        回复给
                     
                     
     forwarded       已转发
                     
                     
     edited          由用户修改
                     
                     
     resent          已重发
                     

     默认情况下，Rmail 只显示可见标头。 不过 *note BabylMessage: 2962. 类
     会使用原始标头因为它们更完整。 如果需要可以显式地访问可见标头。

     *note BabylMessage: 2962. 实例提供了下列方法:

      -- 方法: get_labels ()

          返回邮件上的标签列表。

      -- 方法: set_labels (labels)

          将消息上的标签列表设置为 `labels' 。

      -- 方法: add_label (label)

          将 `label' 添加到消息上的标签列表中。

      -- 方法: remove_label (label)

          从消息上的标签列表中删除 `label' 。

      -- 方法: get_visible ()

          返回一个 *note Message: bef. 实例，其标头为消息的可见标头而其
          消息体为空。

      -- 方法: set_visible (visible)

          将消息的可见标头设为与 `message' 中的标头一致。 形参 `visible'
          应当是一个 *note Message: bef. 实例，*note
          email.message.Message: 54a. 实例，字符串或文件类对象（且应当以
          文本模式打开）。

      -- 方法: update_visible ()

          当一个 *note BabylMessage: 2962. 实例的原始标头被修改时，可见
          标头不会自动进行对应修改。 此方法将按以下方式更新可见标头：每
          个具有对应原始标头的可见标头会被设为原始标头的值，每个没有对应
          原始标头的可见标头会被移除，而任何存在于原始标头但不存在于可见
          标头中的 ‘Date’, ‘From’, ‘Reply-To’, ‘To’, ‘CC’ 和 ‘Subject’ 会
          被添加至可见标头。

当一个 *note BabylMessage: 2962. 实例基于 *note MaildirMessage: 2937. 实
例被创建时，将进行下列转换:

结果状态                *note MaildirMessage: 2937. 状态
                        
------------------------------------------------------------
                        
"unseen" 标签           非 S 标记
                        
                        
"deleted" 标签          T 标记
                        
                        
"answered" 标签         R 标记
                        
                        
"forwarded" 标签        P 标记
                        

当一个 *note BabylMessage: 2962. 实例基于 *note mboxMessage: 27eb. 或
*note MMDFMessage: 296a. 实例被创建时，将会忽略 ‘Status’ 和 ‘X-Status’ 标
头并进入下列转换:

结果状态               *note mboxMessage: 27eb. 或
                       *note MMDFMessage: 296a. 状态
                       
--------------------------------------------------------------------------
                       
"unseen" 标签          非 R 标记
                       
                       
"deleted" 标签         D 标记
                       
                       
"answered" 标签        A 标记
                       

当一个 *note BabylMessage: 2962. 实例基于 *note MHMessage: 294f. 实例被
创建时，将进入下列转换:

结果状态               *note MHMessage: 294f. 状态
                       
------------------------------------------------------
                       
"unseen" 标签          "unseen" 序列
                       
                       
"answered" 标签        "replied" 序列
                       


File: python.info,  Node: MMDFMessage,  Prev: BabylMessage,  Up: Message 对象

5.19.4.12 ‘MMDFMessage’
.......................

 -- 类: mailbox.MMDFMessage (message=None)

     具有 MMDF 专属行为的消息。 形参 `message' 的含义与 *note Message:
     bef. 构造器一致。

     与 mbox 邮箱中的消息类似，MMDF 消息会与将发件人的地址和发送日期作为
     以 "From " 打头的初始行一起存储。 同样地，指明消息状态的旗标通常存
     储在 ‘Status’ 和 ‘X-Status’ 标头中。

     传统的 MMDF 消息旗标与 mbox 消息的类似，如下所示:

     Flag       含义           说明
                               
     ---------------------------------------------------------------
                               
     R          读取           读取
                               
                               
     O          旧的           以前由MUA检测
                               
                               
     D          已删除         标记为以后删除
                               
                               
     F          已标记         标记为重要
                               
                               
     A          已回复         回复给
                               

     "R" 和 "O" 旗标存储在 ‘Status’ 标头中，而 "D", "F" 和 "A" 旗标存储
     在 ‘X-Status’ 标头中。 旗标和标头通常会按上述顺序显示。

     *note MMDFMessage: 296a. 实例提供了下列方法，与 *note mboxMessage:
     27eb. 所提供的类似:

      -- 方法: get_from ()

          返回一个表示在 mbox 邮箱中标记消息起始的 "From " 行的字符串。
          开头的 "From " 和末尾的换行符会被去除。

      -- 方法: set_from (from_, time_=None)

          将 "From " 行设为 `from_'，这应当被指定为不带开头的 "From " 或
          末尾的换行符。 为方便起见，可以指定 `time_' 并将经过适当的格式
          化再添加到 `from_'。 如果指定了 `time_'，它应当是一个 *note
          time.struct_time: 5a2. 实例，适合传入 *note time.strftime():
          b6d. 的元组或者 ‘True’ (以使用 *note time.gmtime(): b47.)。

      -- 方法: get_flags ()

          返回一个指明当前所设旗标的字符串。 如果消息符合规范格式，则结
          果为零或各自出现一次的 ‘'R'’, ‘'O'’, ‘'D'’, ‘'F'’ 和 ‘'A'’ 按
          上述顺序的拼接。

      -- 方法: set_flags (flags)

          设置由 `flags' 所指明的旗标并重启所有其他旗标。 形参 `flags' 应
          当为零或各自出现多次的 ‘'R'’, ‘'O'’, ‘'D'’, ‘'F'’ 和 ‘'A'’ 按
          任意顺序的拼接。

      -- 方法: add_flag (flag)

          设置由 `flag' 所指明的旗标而不改变其他旗标。 要一次性添加一个
          以上的旗标，`flag' 可以为包含一个以上字符的字符串。

      -- 方法: remove_flag (flag)

          重置由 `flag' 所指明的旗标而不改变其他旗标。 要一次性移除一个
          以上的旗标，`flag' 可以为包含一个以上字符的字符串。

当一个 *note MMDFMessage: 296a. 实例基于 *note MaildirMessage: 2937. 实
例被创建时，"From " 行会基于 *note MaildirMessage: 2937. 实例的发送日期
被生成，并进入下列转换:

结果状态              *note MaildirMessage: 2937. 状态
                      
----------------------------------------------------------
                      
R 标记                S 标记
                      
                      
O 标记                "cur" 子目录
                      
                      
D 标记                T 标记
                      
                      
F 标记                F 标记
                      
                      
A 标记                R 标记
                      

当一个 *note MMDFMessage: 296a. 实例基于 *note MHMessage: 294f. 实例被创
建时，将进入下列转换:

结果状态                *note MHMessage: 294f. 状态
                        
-------------------------------------------------------
                        
R 标记 和 O 标记        非 "unseen" 序列
                        
                        
O 标记                  "unseen" 序列
                        
                        
F 标记                  "flagged" 序列
                        
                        
A 标记                  "replied" 序列
                        

当一个 *note MMDFMessage: 296a. 实例基于 *note BabylMessage: 2962. 实例
被创建时，将进行下列转换:

结果状态                *note BabylMessage: 2962. 状态
                        
----------------------------------------------------------
                        
R 标记 和 O 标记        非 "unseen" 标签
                        
                        
O 标记                  "unseen" 标签
                        
                        
D 标记                  "deleted" 标签
                        
                        
A 标记                  "answered" 标签
                        

当一个 *note MMDFMessage: 296a. 实例基于 *note mboxMessage: 27eb. 实例被
创建时，"From " 行会被拷贝并直接对应所有旗标:

结果状态              *note mboxMessage: 27eb. 状态
                      
-------------------------------------------------------
                      
R 标记                R 标记
                      
                      
O 标记                O 标记
                      
                      
D 标记                D 标记
                      
                      
F 标记                F 标记
                      
                      
A 标记                A 标记
                      


File: python.info,  Node: 异常<14>,  Next: 例子<18>,  Prev: Message 对象,  Up: mailbox --- 操作多种格式的邮箱

5.19.4.13 异常
..............

*note mailbox: af. 模块中定义了下列异常类:

 -- 例外: mailbox.Error

     所有其他模块专属异常的基类。

 -- 例外: mailbox.NoSuchMailboxError

     在期望获得一个邮箱但未找到时被引发，例如当使用不存在的路径来实例化
     一个 *note Mailbox: beb. 子类时 (且将 `create' 形参设为 ‘False’)，
     或是当打开一个不存在的路径时。

 -- 例外: mailbox.NotEmptyError

     在期望一个邮箱为空但不为空时被引发，例如当删除一个包含消息的文件夹
     时。

 -- 例外: mailbox.ExternalClashError

     在某些邮箱相关条件超出了程序控制范围导致其无法继续运行时被引发，例
     如当要获取的锁已被另一个程序获取时，或是当要生成的唯一性文件名已存
     在时。

 -- 例外: mailbox.FormatError

     在某个文件中的数据无法被解析时被引发，例如当一个 *note MH: 294e. 实
     例尝试读取已损坏的 ‘.mh_sequences’ 文件时。


File: python.info,  Node: 例子<18>,  Prev: 异常<14>,  Up: mailbox --- 操作多种格式的邮箱

5.19.4.14 例子
..............

一个打印指定邮箱中所有消息的主题的简单示例:

     import mailbox
     for message in mailbox.mbox('~/mbox'):
         subject = message['subject']       # Could possibly be None.
         if subject and 'python' in subject.lower():
             print(subject)

要将所有邮件从 Babyl 邮箱拷贝到 MH 邮箱，请转换所有可转换的格式专属信息:

     import mailbox
     destination = mailbox.MH('~/Mail')
     destination.lock()
     for message in mailbox.Babyl('~/RMAIL'):
         destination.add(mailbox.MHMessage(message))
     destination.flush()
     destination.unlock()

这个示例将来自多个邮件列表的邮件分类放入不同的邮箱，小心避免由于其他程序
的并发修改导致的邮件损坏，由于程序中断导致的邮件丢失，或是由于邮箱中消息
格式错误导致的意外终止:

     import mailbox
     import email.errors

     list_names = ('python-list', 'python-dev', 'python-bugs')

     boxes = {name: mailbox.mbox('~/email/%s' % name) for name in list_names}
     inbox = mailbox.Maildir('~/Maildir', factory=None)

     for key in inbox.iterkeys():
         try:
             message = inbox[key]
         except email.errors.MessageParseError:
             continue                # The message is malformed. Just leave it.

         for name in list_names:
             list_id = message['list-id']
             if list_id and name in list_id:
                 # Get mailbox to use
                 box = boxes[name]

                 # Write copy to disk before removing original.
                 # If there's a crash, you might duplicate a message, but
                 # that's better than losing a message completely.
                 box.lock()
                 box.add(message)
                 box.flush()
                 box.unlock()

                 # Remove original message
                 inbox.lock()
                 inbox.discard(key)
                 inbox.flush()
                 inbox.unlock()
                 break               # Found destination, so stop looking.

     for box in boxes.itervalues():
         box.close()


File: python.info,  Node: mimetypes --- 映射文件夹到 MIME 类型,  Next: base64 --- Base16 Base32 Base64 Base85 数据编码,  Prev: mailbox --- 操作多种格式的邮箱,  Up: 互联网数据处理

5.19.5 ‘mimetypes’ — 映射文件夹到 MIME 类型
-------------------------------------------

`源代码:' Lib/mimetypes.py(1)

__________________________________________________________________

*note mimetypes: b3. 模块可以在文件名或 URL 和关联到文件扩展名的 MIME 类
型之间执行转换。 所提供的转换包括从文件名到 MIME 类型和从 MIME 类型到文
件扩展名；后一种转换不支持编码格式。

该模块提供了一个类和一些便捷函数。 这些函数是该模块通常的接口，但某些应
用程序可能也会希望使用类。

下列函数提供了此模块的主要接口。 如果此模块尚未被初始化，它们将会调用
*note init(): 29a2.，如果它们依赖于 *note init(): 29a2. 所设置的信息的话
。

 -- 函数: mimetypes.guess_type (url, strict=True)

     根据 `url' 给出的文件名、路径或 URL 来猜测文件的类型，URL 可以为字
     符串或 *note path-like object: 373.。

     返回值是一个元组 ‘(type, encoding)’ 其中 `type' 在无法猜测（后缀不
     存在或者未知）时为 ‘None’，或者为 ‘'type/subtype'’ 形式的字符串，可
     以作为 MIME ‘content-type’ 标头。

     `encoding' 在无编码格式时为 ‘None’，或者为程序所用的编码格式 (例如
     ‘compress’ 或 ‘gzip’)。 它可以作为 ‘Content-Encoding’ 标头，但 `不
     可' 作为 ‘Content-Transfer-Encoding’ 标头。 映射是表格驱动的。 编码
     格式前缀对大小写敏感；类型前缀会先以大小写敏感方式检测再以大小写不
     敏感方式检测。

     可选的 `strict' 参数是一个旗标，指明要将已知 MIME 类型限制在 IANA 已
     注册(2) 的官方类型之内。 当 `strict' 为 ‘True’ 时（默认值），则仅支
     持 IANA 类型；当 `strict' 为 ‘False’ 时，则还支持某些附加的非标准但
     常用的 MIME 类型。

     在 3.8 版更改: 增加了 *note path-like object: 373. 作为 url 的支持
     。

 -- 函数: mimetypes.guess_all_extensions (type, strict=True)

     根据由 `type' 给出的文件 MIME 类型猜测其扩展名。 返回值是由所有可能
     的文件扩展名组成的字符串列表，包括开头的点号 (‘'.'’)。 这些扩展名不
     保证能关联到任何特定的数据流，但是将会由 *note guess_type(): f79.
     MIME 类型 `type'。

     可选的 `strict' 参数具有与 *note guess_type(): f79. 函数一致的含义
     。

 -- 函数: mimetypes.guess_extension (type, strict=True)

     根据由 `type' 给出的文件 MIME 类型猜测其扩展名。 返回值是一个表示文
     件扩展名的字符串，包括开头的点号 (‘'.'’)。 该扩展名不保证能关联到任
     何特定的数据流，但是将会由 *note guess_type(): f79. 映射到 MIME 类
     型 `type'。 如果不能猜测出 `type' 的扩展名，则将返回 ‘None’。

     可选的 `strict' 参数具有与 *note guess_type(): f79. 函数一致的含义
     。

有一些附加函数和数据项可被用于控制此模块的行为。

 -- 函数: mimetypes.init (files=None)

     初始化内部数据结构。 `files' 如果给出则必须是一个文件名序列，它应当
     被用于协助默认的类型映射。 如果省略则要使用的文件名会从 *note
     knownfiles: 29a5. 中获取； 在 Windows 上，将会载入当前注册表设置。
     在 `files' 或 *note knownfiles: 29a5. 中指定的每个文件名的优先级将
     高于在它之前的文件名。 *note init(): 29a2. 允许被重复调用。

     为 `files' 指定一个空列表将防止应用系统默认选项：将只保留来自内置列
     表的常用值。

     如果 `files' 为 ‘None’ 则内部数据结构会完全重建为其初始默认值。 这
     是一个稳定操作并将在多次调用时产生相同的结果。

     在 3.2 版更改: 在之前版本中，Windows 注册表设置会被忽略。

 -- 函数: mimetypes.read_mime_types (filename)

     载入在文件 `filename' 中给定的类型映射，如果文件存在的话。 返回的类
     型映射会是一个字典，其中的键值对为文件扩展名包括开头的点号 (‘'.'’)
     与 ‘'type/subtype'’ 形式的字符串。 如果文件 `filename' 不存在或无法
     被读取，则返回 ‘None’。

 -- 函数: mimetypes.add_type (type, ext, strict=True)

     添加一个从 MIME 类型 `type' 到扩展名 `ext' 的映射。 当扩展名已知时
     ，新类型将替代旧类型。 当类型已知时，扩展名将被添加到已知扩展名列表
     。

     当 `strict' 为 ‘True’ 时（默认值），映射将被添加到官方 MIME 类型，
     否则添加到非标准类型。

 -- 数据: mimetypes.inited

     指明全局数据结构是否已被初始化的旗标。 这会由 *note init(): 29a2. 设
     为 ‘True’。

 -- 数据: mimetypes.knownfiles

     通常安装的类型映射文件名列表。 这些文件一般被命名为 ‘mime.types’ 并
     会由不同的包安装在不同的位置。

 -- 数据: mimetypes.suffix_map

     将后缀映射到其他后缀的字典。 它被用来允许识别已编码的文件，其编码格
     式和类型是由相同的扩展名来指明的。 例如，‘.tgz’ 扩展名被映射到
     ‘.tar.gz’ 以允许编码格式和类型被分别识别。

 -- 数据: mimetypes.encodings_map

     映射扩展名到编码格式类型的字典。

 -- 数据: mimetypes.types_map

     映射文件扩展名到 MIME 类型的字典。

 -- 数据: mimetypes.common_types

     映射文件扩展名到非标准但常见的 MIME 类型的字典。

此模块一个使用示例:

     >>> import mimetypes
     >>> mimetypes.init()
     >>> mimetypes.knownfiles
     ['/etc/mime.types', '/etc/httpd/mime.types', ... ]
     >>> mimetypes.suffix_map['.tgz']
     '.tar.gz'
     >>> mimetypes.encodings_map['.gz']
     'gzip'
     >>> mimetypes.types_map['.tgz']
     'application/x-tar-gz'

* Menu:

* MimeTypes 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/mimetypes.py

   (2) https://www.iana.org/assignments/media-types/media-types.xhtml


File: python.info,  Node: MimeTypes 对象,  Up: mimetypes --- 映射文件夹到 MIME 类型

5.19.5.1 MimeTypes 对象
.......................

*note MimeTypes: 29ae. 类可以被用于那些需要多个 MIME 类型数据库的应用程
序；它提供了与 *note mimetypes: b3. 模块所提供的类似接口。

 -- 类: mimetypes.MimeTypes (filenames=(), strict=True)

     这个类表示 MIME 类型数据库。 默认情况下，它提供了对与此模块其余部分
     一致的数据库的访问权限。 这个初始数据库是此模块所提供数据库的一个副
     本，并可以通过使用 *note read(): 29af. 或 *note readfp(): 29b0. 方
     法将附加的 ‘mime.types’ 样式文载入到数据库中来进行扩展。 如果不需要
     默认数据的话这个映射字典也可以在载入附加数据之前先被清空。

     可选的 `filenames' 形参可被用来让附加文件被载入到默认数据库“之上”。

      -- 属性: suffix_map

          将后缀映射到其他后缀的字典。 它被用来允许识别已编码的文件，其
          编码格式和类型是由相同的扩展名来指明的。 例如，‘.tgz’ 扩展名被
          映射到 ‘.tar.gz’ 以允许编码格式和类型被分别识别。 这是在模块中
          定义的全局 *note suffix_map: 29a8. 的一个副本。

      -- 属性: encodings_map

          映射文件扩展名到编码格式类型的字典。 这是在模块中定义的全局
          *note encodings_map: 29a9. 的一个副本。

      -- 属性: types_map

          包含两个字典的元组，将文件扩展名映射到 MIME 类型：第一个字典针
          对非标准类型而第二个字典针对标准类型。 它们会由 *note
          common_types: 29ab. 和 *note types_map: 29aa. 来初始化。

      -- 属性: types_map_inv

          包含两个字典的元组，将 MIME 类型映射到文件扩展名列表：第一个字
          典针对非标准类型而第二个字典针对标准类型。 它们会由 *note
          common_types: 29ab. 和 *note types_map: 29aa. 来初始化。

      -- 方法: guess_extension (type, strict=True)

          类似于 *note guess_extension(): 29a4. 函数，使用存储的表作为对
          象的一部分。

      -- 方法: guess_type (url, strict=True)

          类似于 *note guess_type(): f79. 函数，使用存储的表作为对象的一
          部分。

      -- 方法: guess_all_extensions (type, strict=True)

          类似于 *note guess_all_extensions(): 29a3. 函数，使用存储的表
          作为对象的一部分。

      -- 方法: read (filename, strict=True)

          从名称为 `filename' 的文件载入 MIME 信息。 此方法使用 *note
          readfp(): 29b0. 来解析文件。

          如果 `strict' 为 ‘True’，信息将被添加到标准类型列表，否则添加
          到非标准类型列表。

      -- 方法: readfp (fp, strict=True)

          从打开的文件 `fp' 载入 MIME 类型信息。 文件必须具有标准
          ‘mime.types’ 文件的格式。

          如果 `strict' 为 ‘True’，信息将被添加到标准类型列表，否则添加
          到非标准类型列表。

      -- 方法: read_windows_registry (strict=True)

          从 Windows 注册表载入 MIME 类型信息。

          *note 可用性: 136f.: Windows。

          如果 `strict' 为 ‘True’，信息将被添加到标准类型列表，否则添加
          到非标准类型列表。

          3.2 新版功能.


File: python.info,  Node: base64 --- Base16 Base32 Base64 Base85 数据编码,  Next: binhex --- 对binhex4文件进行编码和解码,  Prev: mimetypes --- 映射文件夹到 MIME 类型,  Up: 互联网数据处理

5.19.6 ‘base64’ — Base16, Base32, Base64, Base85 数据编码
---------------------------------------------------------

`源代码：' Lib/base64.py(1)

__________________________________________________________________

此模块提供了将二进制数据编码为可打印的 ASCII 字符以及将这些编码解码回二
进制数据的函数。它为 RFC 3548(2) 指定的 Base16, Base32 和 Base64 编码以
及已被广泛接受的 Ascii85 和 Base85 编码提供了编码和解码函数。

RFC 3548(3) 编码的目的是使得二进制数据可以作为电子邮件的内容正确地发送，
用作 URL 的一部分，或者作为 HTTP POST 请求的一部分。其中的编码算法和
‘uuencode’ 程序是不同的。

此模块提供了两个接口。新的接口提供了从 *note 类字节对象: 5f1. 到 ASCII 字
节 *note bytes: 33a. 的编码，以及将 ASCII 的 *note 类字节对象: 5f1. 或字
符串解码到 *note bytes: 33a. 的操作。此模块支持定义在 RFC 3548(4) 中的所
有 base-64 字母表 （普通的、URL 安全的和文件系统安全的）。

旧的接口不提供从字符串的解码操作，但提供了操作 *note 文件对象: b4a. 的编
码和解码函数。旧接口只支持标准的 Base64 字母表，并且按照 RFC 2045(5) 的
规范每 76 个字符增加一个换行符。注意：如果你需要支持 RFC 2045(6)，那么使
用 *note email: 69. 模块可能更加合适。

在 3.3 版更改: 新的接口提供的解码函数现在已经支持只包含 ASCII 的 Unicode
字符串。

在 3.4 版更改: 所有 *note 类字节对象: 5f1. 现在已经被所有编码和解码函数
接受。添加了对 Ascii85/Base85 的支持。

新的接口提供：

 -- 函数: base64.b64encode (s, altchars=None)

     对 *note bytes-like object: 5f1. `s' 进行 Base64 编码，并返回编码后
     的 *note bytes: 33a.。

     可选项 `altchars' 必须是一个长 2 字节的 *note bytes-like object:
     5f1.，它指定了用于替换 ‘+’ 和 ‘/’ 的字符。这允许应用程序生成 URL 或
     文件系统安全的 Base64 字符串。默认值是 ‘None’，使用标准 Base64 字母
     表。

 -- 函数: base64.b64decode (s, altchars=None, validate=False)

     解码 Base64 编码过的 *note bytes-like object: 5f1. 或 ASCII 字符串
     `s' 并返回解码过的 *note bytes: 33a.。

     可选项 `altchars' 必须是一个长 2 字节的 *note bytes-like object:
     5f1.，它指定了用于替换 ‘+’ 和 ‘/’ 的字符。

     如果 `s' 被不正确地填写，一个 *note binascii.Error: 966. 错误将被抛
     出。

     如果 `validate' 值为 ‘False’ （默认情况），则在填充检查前，将丢弃既
     不在标准 base-64 字母表之中也不在备用字母表中的字符。如果
     `validate' 为 ‘True’，这些非 base64 字符将导致 *note
     binascii.Error: 966.。

 -- 函数: base64.standard_b64encode (s)

     编码 *note bytes-like object: 5f1. `s'，使用标准 Base64 字母表并返
     回编码过的 *note bytes: 33a.。

 -- 函数: base64.standard_b64decode (s)

     解码 *note bytes-like object: 5f1. 或 ASCII 字符串 `s'，使用标准
     Base64 字母表并返回编码过的 *note bytes: 33a.。

 -- 函数: base64.urlsafe_b64encode (s)

     编码 *note bytes-like object: 5f1. `s'，使用 URL 与文件系统安全的字
     母表，使用 ‘-’ 以及 ‘_’ 代替标准 Base64 字母表中的 ‘+’ 和 ‘/’。返回
     编码过的 *note bytes: 33a.。结果中可能包含 ‘=’。

 -- 函数: base64.urlsafe_b64decode (s)

     解码 *note bytes-like object: 5f1. 或 ASCII 字符串 `s'，使用 URL 与
     文件系统安全的字母表，使用 ‘-’ 以及 ‘_’ 代替标准 Base64 字母表中的
     ‘+’ 和 ‘/’。返回解码过的 *note bytes: 33a.

 -- 函数: base64.b32encode (s)

     用 Base32 编码 *note bytes-like object: 5f1. `s' 并返回编码过的
     *note bytes: 33a.

 -- 函数: base64.b32decode (s, casefold=False, map01=None)

     解码 Base32 编码过的 *note bytes-like object: 5f1. 或 ASCII 字符串
     `s' 并返回解码过的 *note bytes: 33a.。

     可选的 `casefold' 是一个指定小写字幕是否可接受为输入的标志。为了安
     全考虑，默认值为 ‘False’。

     RFC 3548(7) 允许将字母 0(zero) 映射为字母 O(oh)，并可以选择是否将字
     母 1(one) 映射为 I(eye) 或 L(el)。可选参数 `map01' 不是 ‘None’ 时，
     它的值指定 1 的映射目标 (I 或 l)，当 `map01' 非 ‘None’ 时， 0 总是
     被映射为 O。为了安全考虑，默认值被设为 ‘None’，如果是这样， 0 和 1
     不允许被作为输入。

     如果 `s' 被错误地填写或输入中存在字母表之外的字符，将抛出 *note
     binascii.Error: 966.。

 -- 函数: base64.b16encode (s)

     用 Base16 编码 *note bytes-like object: 5f1. `s' 并返回编码过的
     *note bytes: 33a.

 -- 函数: base64.b16decode (s, casefold=False)

     解码 Base16 编码过的 *note bytes-like object: 5f1. 或 ASCII 字符串
     `s' 并返回解码过的 *note bytes: 33a.。

     可选的 `casefold' 是一个指定小写字幕是否可接受为输入的标志。为了安
     全考虑，默认值为 ‘False’。

     如果 `s' 被错误地填写或输入中存在字母表之外的字符，将抛出 *note
     binascii.Error: 966.。

 -- 函数: base64.a85encode (b, *, foldspaces=False, wrapcol=0,
          pad=False, adobe=False)

     用 Ascii85 编码 *note bytes-like object: 5f1. `s' 并返回编码过的
     *note bytes: 33a.

     `foldspaces' 是一个可选的标志，使用特殊的短序列 ’y’ 代替 ’btoa’ 提
     供的 4 个连续空格 (ASCII 0x20)。这个特性不被 "标准" Ascii85 编码支
     持。

     `wrapcol' 控制了输出是否包含换行符 (‘b'\n'’). 如果该值非零, 则每一
     行只有该值所限制的字符长度.

     `pad' 控制在编码之前输入是否填充为4的倍数。请注意，‘btoa’ 实现总是
     填充。

     `adobe' 控制编码后的字节序列是否要加上 ‘<~’ 和 ‘~>’，这是 Adobe 实
     现所使用的。

     3.4 新版功能.

 -- 函数: base64.a85decode (b, *, foldspaces=False, adobe=False,
          ignorechars=b' \t\n\r\v')

     解码 Ascii85 编码过的 *note bytes-like object: 5f1. 或 ASCII 字符串
     `s' 并返回解码过的 *note bytes: 33a.。

     `foldspaces' 旗标指明是否应接受 ’y’ 短序列作为 4 个连续空格 (ASCII
     0x20) 的快捷方式。 此特性不被 "标准" Ascii85 编码格式所支持。

     `adobe' 控制输入序列是否为 Adobe Ascii85 格式 (即附加 <~ 和 ~>)。

     `ignorechars' 应当是一个 *note bytes-like object: 5f1. 或 ASCII 字
     符串，其中包含要从输入中忽略的字符。 这应当只包含空白字符，并且默认
     包含 ASCII 中所有的空白字符。

     3.4 新版功能.

 -- 函数: base64.b85encode (b, pad=False)

     用 base85（如 git 风格的二进制 diff 数据所用格式）编码 *note
     bytes-like object: 5f1. `b' 并返回编码后的 *note bytes: 33a.。

     如果 `pad' 为真值，输入将以 ‘b'\0'’ 填充以使其编码前长度为 4 字节的
     倍数。

     3.4 新版功能.

 -- 函数: base64.b85decode (b)

     解码 base85 编码过的 *note bytes-like object: 5f1. 或 ASCII 字符串
     `b' 并返回解码过的 *note bytes: 33a.。 如有必要，填充会被隐式地移除
     。

     3.4 新版功能.

旧式接口:

 -- 函数: base64.decode (input, output)

     解码二进制 `input' 文件的内容并将结果二进制数据写入 `output' 文件。
     `input' 和 `output' 必须为 *note 文件对象: b4a.  `input' 将被读取直
     至 ‘input.readline()’ 返回空字节串对象。

 -- 函数: base64.decodebytes (s)

     解码 *note bytes-like object: 5f1. `s'，该对象必须包含一行或多行
     base64 编码的数据，并返回已解码的 *note bytes: 33a.。

     3.1 新版功能.

 -- 函数: base64.decodestring (s)

     已弃用的 *note decodebytes(): 1885. 的别名。

     3.1 版后已移除.

 -- 函数: base64.encode (input, output)

     编码二进制 `input' 文件的内容并将经 base64 编码的数据写入 `output'
     文件。 `input' 和 `output' 必须为 *note 文件对象: b4a.。 `input' 将
     被读取直到 ‘input.read()’ 返回空字节串对象。 *note encode(): 29c4.
     会在每输出 76 个字节之后插入一个换行符 (‘b'\n'’)，并会确保输出总是
     以换行符来结束，如 RFC 2045(8) (MIME) 所规定的那样。

 -- 函数: base64.encodebytes (s)

     编码 *note bytes-like object: 5f1. `s'，其中可以包含任意二进制数据
     ，并返回包含经 base64 编码数据的 *note bytes: 33a.，每输出 76 个字
     节之后将带一个换行符 (‘b'\n'’)，并会确保在末尾也有一个换行符，如
     RFC 2045(9) (MIME) 所规定的那样。

     3.1 新版功能.

 -- 函数: base64.encodestring (s)

     一个被弃用的 *note encodebytes(): 1884. 的别名。

     3.1 版后已移除.

此模块的一个使用示例:

     >>> import base64
     >>> encoded = base64.b64encode(b'data to be encoded')
     >>> encoded
     b'ZGF0YSB0byBiZSBlbmNvZGVk'
     >>> data = base64.b64decode(encoded)
     >>> data
     b'data to be encoded'

参见
....

模块 *note binascii: 10.

     支持模块，包含ASCII到二进制和二进制到ASCII转换。

RFC 1521(10) - MIME (Multipurpose Internet Mail Extensions) 第一部分：规定并描述因特网消息体的格式的机制。

     第 5.2 节，“Base64 内容转换编码格式” 提供了 base64 编码格式的定义。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/base64.py

   (2) https://tools.ietf.org/html/rfc3548.html

   (3) https://tools.ietf.org/html/rfc3548.html

   (4) https://tools.ietf.org/html/rfc3548.html

   (5) https://tools.ietf.org/html/rfc2045.html

   (6) https://tools.ietf.org/html/rfc2045.html

   (7) https://tools.ietf.org/html/rfc3548.html

   (8) https://tools.ietf.org/html/rfc2045.html

   (9) https://tools.ietf.org/html/rfc2045.html

   (10) https://tools.ietf.org/html/rfc1521.html


File: python.info,  Node: binhex --- 对binhex4文件进行编码和解码,  Next: binascii --- 二进制和 ASCII 码互转,  Prev: base64 --- Base16 Base32 Base64 Base85 数据编码,  Up: 互联网数据处理

5.19.7 ‘binhex’ — 对binhex4文件进行编码和解码
---------------------------------------------

`源代码:' Lib/binhex.py(1)

__________________________________________________________________

此模块以binhe4格式对文件进行编码和解码，该格式允许Macintosh文件以ASCII格
式表示。仅处理数据分支。

*note binhex: 11. 模块定义了以下功能：

 -- 函数: binhex.binhex (input, output)

     将带有文件名 `输入' 的二进制文件转换为binhex文件 `输出' 。输出参数
     可以是文件名或类文件对象（ ‘write()’ 和 ‘close()’ 方法的任何对象）
     。

 -- 函数: binhex.hexbin (input, output)

     解码binhex文件输入。 `输入' 可以是支持 ‘read()’ 和 ‘close()’ 方法的
     文件名或类文件对象。生成的文件将写入名为 `output' 的文件，除非参数
     为 ‘None’ ，在这种情况下，从binhex文件中读取输出文件名。

还定义了以下异常：

 -- 例外: binhex.Error

     当无法使用binhex格式编码某些内容时（例如，文件名太长而无法放入文件
     名字段中），或者输入未正确编码的binhex数据时，会引发异常。

参见
....

模块 *note binascii: 10.

     支持模块，包含ASCII到二进制和二进制到ASCII转换。

* Menu:

* 注释: 注释<3>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/binhex.py


File: python.info,  Node: 注释<3>,  Up: binhex --- 对binhex4文件进行编码和解码

5.19.7.1 注释
.............

还有一个替代的、功能更强大的编码器和解码器接口，详细信息请参见源代码。

如果您在非Macintosh平台上编码或解码文本文件，它们仍将使用旧的Macintosh换
行符约定（回车符作为行尾）。


File: python.info,  Node: binascii --- 二进制和 ASCII 码互转,  Next: quopri --- 编码与解码经过 MIME 转码的可打印数据,  Prev: binhex --- 对binhex4文件进行编码和解码,  Up: 互联网数据处理

5.19.8 ‘binascii’ — 二进制和 ASCII 码互转
-----------------------------------------

__________________________________________________________________

*note binascii: 10. 模块包含很多在二进制和二进制表示的各种ASCII码之间转
换的方法。 通常情况不会直接使用这些函数，而是使用像 *note uu: 124. ，
*note base64: e. ，或 *note binhex: 11. 这样的封装模块。 为了执行效率高
，*note binascii: 10. 模块含有许多用 C 写的低级函数，这些底层函数被一些
高级模块所使用。

     注解: ‘a2b_*’ 函数接受只含有 ASCII 码的Unicode 字符串。其他函数只接
     受 *note 字节类对象: 5f1. （例如 *note bytes: 33a.，*note
     bytearray: 33b. 和其他支持缓冲区协议的对象）。

     在 3.3 版更改: ASCII-only unicode strings are now accepted by the
     ‘a2b_*’ functions.

*note binascii: 10. 模块定义了以下函数：

 -- 函数: binascii.a2b_uu (string)

     将单行 uu 编码数据转换成二进制数据并返回。uu 编码每行的数据通常包含
     45 个（二进制）字节，最后一行除外。每行数据后面可能跟有空格。

 -- 函数: binascii.b2a_uu (data, *, backtick=False)

     将二进制数据转换为 ASCII 编码字符，返回值是转换后的行数据，包括换行
     符。 `data' 的长度最多为45。如果 `backtick' 为ture，则零由 ‘'`'’ 而
     不是空格表示。

     在 3.7 版更改: 增加 `backtick' 形参。

 -- 函数: binascii.a2b_base64 (string)

     将 base64 数据块转换成二进制并以二进制数据形式返回。一次可以传递多
     行数据。

 -- 函数: binascii.b2a_base64 (data, *, newline=True)

     将二进制数据转换为一行用 base64 编码的ASCII字符串。返回值是转换后的
     行数据，如果 `newline' 为true，则返回值包括换行符。该函数的输出符合
     ：rfc：‘3548’。

     在 3.6 版更改: 增加 `newline' 形参。

 -- 函数: binascii.a2b_qp (data, header=False)

     将一个引号可打印的数据块转换成二进制数据并返回。一次可以转换多行。
     如果可选参数 `header' 存在且为true，则数据中的下划线将被解码成空格
     。

 -- 函数: binascii.b2a_qp (data, quotetabs=False, istext=True,
          header=False)

     将二进制数据转换为一行或多行带引号可打印编码的ASCII字符串。返回值是
     转换后的行数据。如果可选参数 `quotetabs' 存在且为真值，则对所有制表
     符和空格进行编码。如果可选参数 `istext' 存在且为真值，则不对新行进
     行编码，但将对尾随空格进行编码。如果可选参数 `header' 存在且为
     true，则空格将被编码为下划线 RFC 1522(1)。如果可选参数 `header' 存
     在且为假值，则也会对换行符进行编码;不进行换行转换编码可能会破坏二进
     制数据流。

 -- 函数: binascii.a2b_hqx (string)

     将 binhex4 格式的 ASCII 数据不进行 RLE 解压缩直接转换为二进制数据。
     该字符串应包含完整数量的二进制字节，或者（在binhex4 数据最后部分）
     剩余位为零。

 -- 函数: binascii.rledecode_hqx (data)

     根据 binhex4 标准对数据执行 RLE 解压缩。该算法在一个字节的数据后使
     用 ‘0x90’ 作为重复指示符，然后计数。计数 ‘0’ 指定字节值 ‘0x90’ 。该
     例程返回解压缩的数据，输入数据以孤立的重复指示符结束的情况下，将引
     发 *note Incomplete: 29d5. 异常。

     在 3.2 版更改: 仅接受 bytestring 或 bytearray 对象作为输入。

 -- 函数: binascii.rlecode_hqx (data)

     在 `data' 上执行 binhex4 游程编码压缩并返回结果。

 -- 函数: binascii.b2a_hqx (data)

     执行 hexbin4 类型二进制到 ASCII 码的转换并返回结果字符串。输入数据
     应经过 RLE 编码，且数据长度可被3整除（除了最后一个片段）。

 -- 函数: binascii.crc_hqx (data, value)

     以 `value' 作为初始 CRC 计算 `data' 的16位 CRC 值，返回其结果。这里
     使用 CRC-CCITT 生成多项式 `x'^16 + `x'^12 + `x'^5 + 1 ，通常表示为
     0x1021。该 CRC 被用于 binhex4 格式。

 -- 函数: binascii.crc32 (data[, value])

     计算 CRC-32 ，从 `value' 的初始 CRC 开始计算 `data' 的32位校验和。
     默认初始 CRC 为零。该算法与 ZIP 文件校验和一致。由于该算法被设计用
     作校验和算法，因此不适合用作通用散列算法。使用方法如下：

          print(binascii.crc32(b"hello world"))
          # Or, in two pieces:
          crc = binascii.crc32(b"hello")
          crc = binascii.crc32(b" world", crc)
          print('crc32 = {:#010x}'.format(crc))

     在 3.0 版更改: 校验结果始终是无符号类型的。要在所有Python版本和平台
     上生成相同的数值，请使用 ‘crc32(data) & 0xffffffff’ 。

 -- 函数: binascii.b2a_hex (data[, sep[, bytes_per_sep=1]])
 -- 函数: binascii.hexlify (data[, sep[, bytes_per_sep=1]])

     返回二进制数据 `data' 的十六进制表示形式。 `data' 的每个字节都被转
     换为相应的2位十六进制表示形式。因此返回的字节对象的长度是 `data' 的
     两倍。

     使用：*note bytes.hex(): 63a. 方法也可以方便地实现相似的功能（但仅
     返回文本字符串）。

     如果指定了 `sep'，它必须为单字符 str 或 bytes 对象。 它将被插入每个
     `bytes_per_sep' 输入字节之后。 分隔符位置默认从输出的右端开始计数，
     如果你希望从左端开始计数，请提供一个负的 `bytes_per_sep' 值。

          >>> import binascii
          >>> binascii.b2a_hex(b'\xb9\x01\xef')
          b'b901ef'
          >>> binascii.hexlify(b'\xb9\x01\xef', '-')
          b'b9-01-ef'
          >>> binascii.b2a_hex(b'\xb9\x01\xef', b'_', 2)
          b'b9_01ef'
          >>> binascii.b2a_hex(b'\xb9\x01\xef', b' ', -2)
          b'b901 ef'

     在 3.8 版更改: 添加了 `sep' 和 `bytes_per_sep' 形参。

 -- 函数: binascii.a2b_hex (hexstr)
 -- 函数: binascii.unhexlify (hexstr)

     返回由十六进制字符串 `hexstr' 表示的二进制数据。此函数功能与 *note
     b2a_hex(): 1887. 相反。 `hexstr' 必须包含偶数个十六进制数字（可以是
     大写或小写），否则会引发 *note Error: 966. 异常。

     使用：*note bytes.fromhex(): 337. 类方法也实现相似的功能（仅接受文
     本字符串参数，不限制其中的空白字符）。

 -- 例外: binascii.Error

     通常是因为编程错误引发的异常。

 -- 例外: binascii.Incomplete

     数据不完整引发的异常。通常不是编程错误导致的，可以通过读取更多的数
     据并再次尝试来处理该异常。

参见
....

模块 *note base64: e.

     支持在16，32，64，85进制中进行符合 RFC 协议的 base64 样式编码。

模块 *note binhex: 11.

     支持在 Macintosh 上使用的 binhex 格式。

模块 *note uu: 124.

     支持在 Unix 上使用的 UU 编码。

模块 *note quopri: dc.

     支持在 MIME 版本电子邮件中使用引号可打印编码。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc1522.html


File: python.info,  Node: quopri --- 编码与解码经过 MIME 转码的可打印数据,  Next: uu --- 对 uuencode 文件进行编码与解码,  Prev: binascii --- 二进制和 ASCII 码互转,  Up: 互联网数据处理

5.19.9 ‘quopri’ — 编码与解码经过 MIME 转码的可打印数据
------------------------------------------------------

`源代码:' Lib/quopri.py(1)

__________________________________________________________________

此模块会执行转换后可打印的传输编码与解码，具体定义见 RFC 1521(2): "MIME
(Multipurpose Internet Mail Extensions) Part One: Mechanisms for
Specifying and Describing the Format of Internet Message Bodies"。 转换
后可打印的编码格式被设计用于只包含相对较少的不可打印字符的数据；如果存在
大量这样的字符，通过 *note base64: e. 模块所提供的 base64 编码方案会更为
紧凑，例如当发送图片文件时。

 -- 函数: quopri.decode (input, output, header=False)

     解码 `input' 文件的内容并将已解码二进制数据结果写入 `output' 文件。
     `input' 和 `output' 必须为 *note 二进制文件对象: b4a.。 如果提供了
     可选参数 `header' 且为真值，下划线将被解码为空格。 此函数可用于解码
     “Q”编码的头数据，具体描述见 RFC 1522(3): "MIME (Multipurpose
     Internet Mail Extensions) Part Two: Message Header Extensions for
     Non-ASCII Text"。

 -- 函数: quopri.encode (input, output, quotetabs, header=False)

     编码 `input' 文件的内容并将转换后可打印的数据结果写入 `output' 文件
     。 `input' 和 `output' 必须为 *note 二进制文件对象: b4a.
     `quotetabs' 是一个非可选的旗标，它控制是否要编码内嵌的空格与制表符
     ；当为真值时将编码此类内嵌空白符，当为假值时则保持原样不进行编码。
     请注意出现在行尾的空格与制表符总是会被编码，具体描述见 RFC 1521(4)。
     `header' 旗标控制空格符是否要编码为下划线，具体描述见 RFC 1522(5)。

 -- 函数: quopri.decodestring (s, header=False)

     类似 *note decode(): 188a.，区别在于它接受一个源 *note bytes: 33a.
     并返回对应的已解码 *note bytes: 33a.。

 -- 函数: quopri.encodestring (s, quotetabs=False, header=False)

     类型 *note encode(): 1889.，区别在于它接受一个源 *note bytes: 33a.
     并返回对应的已编码 *note bytes: 33a.。 在默认情况下，它会发送
     ‘False’ 值给 *note encode(): 1889. 函数的 `quotetabs' 形参。

参见
....

模块 *note base64: e.

     编码与解码 MIME base64 数据

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/quopri.py

   (2) https://tools.ietf.org/html/rfc1521.html

   (3) https://tools.ietf.org/html/rfc1522.html

   (4) https://tools.ietf.org/html/rfc1521.html

   (5) https://tools.ietf.org/html/rfc1522.html


File: python.info,  Node: uu --- 对 uuencode 文件进行编码与解码,  Prev: quopri --- 编码与解码经过 MIME 转码的可打印数据,  Up: 互联网数据处理

5.19.10 ‘uu’ — 对 uuencode 文件进行编码与解码
---------------------------------------------

`源代码:' Lib/uu.py(1)

__________________________________________________________________

此模块使用 uuencode 格式来编码和解码文件，以便任意二进制数据可通过仅限
ASCII 码的连接进行传输。 在任何要求文件参数的地方，这些方法都接受文件类
对象。 为了保持向下兼容，也接受包含路径名称的字符串，并且将打开相应的文
件进行读写；路径名称 ‘'-'’ 被解读为标准输入或输出。 但是，此接口已被弃用
；在 Windows 中调用者最好是自行打开文件，并在需要时确保模式为 ‘'rb'’ or
‘'wb'’。

此代码由 Lance Ellinghouse 贡献，并由 Jack Jansen 修改。

*note uu: 124. 模块定义了以下函数：

 -- 函数: uu.encode (in_file, out_file, name=None, mode=None, *,
          backtick=False)

     使用 uuencode 将 `in_file' 文件编码为 `out_file' 文件。 经过
     uuencoded 编码的文件将具有指定 `name' 和 `mode' 作为解码该文件默认
     结果的标头。 默认值会相应地从 `in_file' 或 ‘'-'’ 以及 ‘0o666’ 中提
     取。 如果 `backtick' 为真值，零会用 ‘'`'’ 而不是空格来表示。

     在 3.7 版更改: 增加 `backtick' 形参。

 -- 函数: uu.decode (in_file, out_file=None, mode=None, quiet=False)

     调用此函数会解码 uuencod 编码的 `in_file' 文件并将结果放入
     `out_file' 文件。 如果 `out_file' 是一个路径名称，`mode' 会在必须创
     建文件时用于设置权限位。 `out_file' 和 `mode' 的默认值会从 uuencode
     标头中提取。 但是，如果标头中指定的文件已存在，则会引发 *note
     uu.Error: 29e0.。

     如果输入由不正确的 uuencode 编码器生成，*note decode(): 188b. 可能
     会打印一条警告到标准错误 ，这样 Python 可以从该错误中恢复。 将
     `quiet' 设为真值可以屏蔽此警告。

 -- 例外: uu.Error

     *note Exception: 1aa. 的子类，此异常可由 *note uu.decode(): 188b. 在
     多种情况下引发，如上文所述，此外还包括格式错误的标头或被截断的输入
     文件等。

参见
....

模块 *note binascii: 10.

     支持模块，包含ASCII到二进制和二进制到ASCII转换。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/uu.py


File: python.info,  Node: 结构化标记处理工具,  Next: 互联网协议和支持,  Prev: 互联网数据处理,  Up: Python 标准库

5.20 结构化标记处理工具
=======================

Python 支持各种模块，以处理各种形式的结构化数据标记。 这包括使用标准通用
标记语言（SGML）和超文本标记语言（HTML）的模块，以及使用可扩展标记语言（
XML）的几个接口。

* Menu:

* html: html --- 超文本标记语言支持. 超文本标记语言支持
* html.parser: html parser --- 简单的 HTML 和 XHTML 解析器. 简单的 HTML 和 XHTML 解析器
* html.entities: html entities --- HTML 一般实体的定义. HTML 一般实体的定义
* XML处理模块::
* xml.etree.ElementTree: xml etree ElementTree --- ElementTree XML API. ElementTree XML API
* xml.dom: xml dom --- 文档对象模型 API. 文档对象模型 API
* xml.dom.minidom: xml dom minidom --- 最小化的 DOM 实现. 最小化的 DOM 实现
* xml.dom.pulldom: xml dom pulldom --- 支持构建部分 DOM 树. 支持构建部分 DOM 树
* xml.sax: xml sax --- 支持 SAX2 解析器. 支持 SAX2 解析器
* xml.sax.handler: xml sax handler --- SAX 处理程序的基类. SAX 处理程序的基类
* xml.sax.saxutils: xml sax saxutils --- SAX 工具集. SAX 工具集
* xml.sax.xmlreader: xml sax xmlreader --- 用于 XML 解析器的接口. 用于 XML 解析器的接口
* xml.parsers.expat: xml parsers expat --- 使用 Expat 的快速 XML 解析. 使用 Expat 的快速 XML 解析


File: python.info,  Node: html --- 超文本标记语言支持,  Next: html parser --- 简单的 HTML 和 XHTML 解析器,  Up: 结构化标记处理工具

5.20.1 ‘html’ — 超文本标记语言支持
----------------------------------

`源码：' Lib/html/__init__.py(1)

__________________________________________________________________

该模块定义了操作HTML的工具。

 -- 函数: html.escape (s, quote=True)

     将字符串 `s' 中的字符‘‘&‘‘ 、 ‘<’ 和 ‘>’ 转换为安全的HTML序列。 如
     果需要在 HTML 中显示可能包含此类字符的文本，请使用此选项。 如果可选
     的标志 `quote' 为真值，则字符 (‘"’) 和 (‘'’) 也被转换；这有助于包含
     在由引号分隔的 HTML 属性中，如 ‘<a href="...">’。

     3.2 新版功能.

 -- 函数: html.unescape (s)

     将字符串 `s' 中的所有命名和数字字符引用 (例如 ‘&gt;’, ‘&#62;’,
     ‘&#x3e;’) 转换为相应的Unicode字符。 此函数使用HTML 5标准为有效和无
     效字符引用定义的规则，以及 *note HTML 5 命名字符引用列表: a1d.。

     3.4 新版功能.

__________________________________________________________________

‘html’ 包中的子模块是：

   * *note html.parser: 92. —— 具有宽松解析模式的HTML / XHTML解析器

   * *note html.entities: 91. – HTML 实体定义

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/html/__init__.py


File: python.info,  Node: html parser --- 简单的 HTML 和 XHTML 解析器,  Next: html entities --- HTML 一般实体的定义,  Prev: html --- 超文本标记语言支持,  Up: 结构化标记处理工具

5.20.2 ‘html.parser’ — 简单的 HTML 和 XHTML 解析器
--------------------------------------------------

`源代码：' Lib/html/parser.py(1)

__________________________________________________________________

这个模块定义了一个 *note HTMLParser: 7c8. 类，为 HTML（超文本标记语言）
和 XHTML 文本文件解析提供基础。

 -- 类: html.parser.HTMLParser (*, convert_charrefs=True)

     创建一个能解析无效标记的解析器实例。

     如果 `convert_charrefs' 为 ‘True’ (默认值)，则所有字符引用(
     ‘script’/‘style’ 元素中的除外)都会自动转换为相应的 Unicode 字符。

     一个 *note HTMLParser: 7c8. 类的实例用来接受 HTML 数据，并在标记开
     始、标记结束、文本、注释和其他元素标记出现的时候调用对应的方法。要
     实现具体的行为，请使用 *note HTMLParser: 7c8. 的子类并重载其方法。

     这个解析器不检查结束标记是否与开始标记匹配，也不会因外层元素完毕而
     隐式关闭了的元素引发结束标记处理。

     在 3.4 版更改: `convert_charrefs' 关键字参数被添加。

     在 3.5 版更改: `convert_charrefs' 参数的默认值现在为 ‘True’。

* Menu:

* HTML 解析器的示例程序::
* HTMLParser 方法::
* 例子: 例子<19>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/html/parser.py


File: python.info,  Node: HTML 解析器的示例程序,  Next: HTMLParser 方法,  Up: html parser --- 简单的 HTML 和 XHTML 解析器

5.20.2.1 HTML 解析器的示例程序
..............................

下面是简单的 HTML 解析器的一个基本示例，使用 *note HTMLParser: 7c8. 类，
当遇到开始标记、结束标记以及数据的时候将内容打印出来。

     from html.parser import HTMLParser

     class MyHTMLParser(HTMLParser):
         def handle_starttag(self, tag, attrs):
             print("Encountered a start tag:", tag)

         def handle_endtag(self, tag):
             print("Encountered an end tag :", tag)

         def handle_data(self, data):
             print("Encountered some data  :", data)

     parser = MyHTMLParser()
     parser.feed('<html><head><title>Test</title></head>'
                 '<body><h1>Parse me!</h1></body></html>')

输出是:

     Encountered a start tag: html
     Encountered a start tag: head
     Encountered a start tag: title
     Encountered some data  : Test
     Encountered an end tag : title
     Encountered an end tag : head
     Encountered a start tag: body
     Encountered a start tag: h1
     Encountered some data  : Parse me!
     Encountered an end tag : h1
     Encountered an end tag : body
     Encountered an end tag : html


File: python.info,  Node: HTMLParser 方法,  Next: 例子<19>,  Prev: HTML 解析器的示例程序,  Up: html parser --- 简单的 HTML 和 XHTML 解析器

5.20.2.2 ‘HTMLParser’ 方法
..........................

*note HTMLParser: 7c8. 实例有下列方法：

 -- 方法: HTMLParser.feed (data)

     填充一些文本到解析器中。如果包含完整的元素，则被处理；如果数据不完
     整，将被缓冲直到更多的数据被填充，或者 *note close(): 29eb. 被调用
     。`data' 必须为 *note str: 339. 类型。

 -- 方法: HTMLParser.close ()

     如同后面跟着一个文件结束标记一样，强制处理所有缓冲数据。这个方法能
     被派生类重新定义，用于在输入的末尾定义附加处理，但是重定义的版本应
     当始终调用基类 *note HTMLParser: 7c8. 的 *note close(): 29eb. 方法
     。

 -- 方法: HTMLParser.reset ()

     重置实例。丢失所有未处理的数据。在实例化阶段被隐式调用。

 -- 方法: HTMLParser.getpos ()

     返回当前行号和偏移值。

 -- 方法: HTMLParser.get_starttag_text ()

     返回最近打开的开始标记中的文本。 结构化处理时通常应该不需要这个，但
     在处理“已部署”的 HTML 或是在以最小改变来重新生成输入时可能会有用处
     （例如可以保留属性间的空格等）。

下列方法将在遇到数据或者标记元素的时候被调用。他们需要在子类中重载。基类
的实现中没有任何实际操作（除了 *note handle_startendtag(): 29ef. ）：

 -- 方法: HTMLParser.handle_starttag (tag, attrs)

     这个方法在标签开始的时候被调用（例如： ‘<div id="main">’ ）。

     `tag' 参数是小写的标记名。`attrs' 参数是一个 ‘(name, value)’ 形式的
     列表，包含了所有在标记的 ‘<>’ 括号中找到的属性。`name' 转换为小写，
     `value' 的引号被去除，字符和实体引用都会被替换。

     实例中，对于标签 ‘<A HREF="https://www.cwi.nl/">’，这个方法将以下列
     形式被调用 ‘handle_starttag('a', [('href',
     'https://www.cwi.nl/')])’ 。

     *note html.entities: 91. 中的所有实体引用，会被替换为属性值。

 -- 方法: HTMLParser.handle_endtag (tag)

     此方法被用来处理元素的结束标记（例如： ‘</div>’ ）。

     `tag' 参数是小写的标签名。

 -- 方法: HTMLParser.handle_startendtag (tag, attrs)

     类似于 *note handle_starttag(): 29f0, 只是在解析器遇到 XHTML 样式的
     空标记时被调用（ ‘<img ... />’）。这个方法能被需要这种特殊词法信息
     的子类重载；默认实现仅简单调用 *note handle_starttag(): 29f0. 和
     *note handle_endtag(): 29f1. 。

 -- 方法: HTMLParser.handle_data (data)

     这个方法被用来处理任意数据（例如：文本节点和 ‘<script>...</script>’
     以及 ‘<style>...</style>’ 中的内容）。

 -- 方法: HTMLParser.handle_entityref (name)

     这个方法被用于处理 ‘&name;’ 形式的命名字符引用（例如 ‘&gt;’），其中
     `name' 是通用的实体引用（例如： ‘'gt'’）。如果 `convert_charrefs' 为
     ‘True’，该方法永远不会被调用。

 -- 方法: HTMLParser.handle_charref (name)

     这个方法被用来处理 ‘&#NNN;’ 和 ‘&#xNNN;’ 形式的十进制和十六进制字符
     引用。例如，‘&gt;’ 等效的十进制形式为 ‘&#62;’ ，而十六进制形式为
     ‘&#x3E;’ ；在这种情况下，方法将收到 ‘'62'’ 或 ‘'x3E'’ 。如果
     `convert_charrefs' 为 ‘True’ ，则该方法永远不会被调用。

 -- 方法: HTMLParser.handle_comment (data)

     这个方法在遇到注释的时候被调用（例如： ‘<!--comment-->’ ）。

     例如， ‘<!-- comment -->’ 这个注释会用 ‘' comment '’ 作为参数调用此
     方法。

     Internet Explorer 条件注释（condcoms）的内容也被发送到这个方法，因
     此，对于 ‘<!--[if IE 9]>IE9-specific content<![endif]-->’ ，这个方
     法将接收到 ‘'[if IE 9]>IE9-specific content<![endif]'’ 。

 -- 方法: HTMLParser.handle_decl (decl)

     这个方法用来处理 HTML doctype 申明（例如 ‘<!DOCTYPE html>’ ）。

     `decl' 形参为 ‘<!...>’ 标记中的所有内容（例如： ‘'DOCTYPE html'’ ）
     。

 -- 方法: HTMLParser.handle_pi (data)

     此方法在遇到处理指令的时候被调用。`data' 形参将包含整个处理指令。例
     如，对于处理指令 ‘<?proc color='red'>’ ，这个方法将以
     ‘handle_pi("proc color='red'")’ 形式被调用。它旨在被派生类重载；基
     类实现中无任何实际操作。

          注解: *note HTMLParser: 7c8. 类使用 SGML 语法规则处理指令。使
          用 ‘'?'’ 结尾的 XHTML 处理指令将导致 ‘'?'’ 包含在 `data' 中。

 -- 方法: HTMLParser.unknown_decl (data)

     当解析器读到无法识别的声明时，此方法被调用。

     `data' 形参为 ‘<![...]>’ 标记中的所有内容。某些时候对派生类的重载很
     有用。基类实现中无任何实际操作。


File: python.info,  Node: 例子<19>,  Prev: HTMLParser 方法,  Up: html parser --- 简单的 HTML 和 XHTML 解析器

5.20.2.3 例子
.............

下面的类实现了一个解析器，用于更多示例的演示:

     from html.parser import HTMLParser
     from html.entities import name2codepoint

     class MyHTMLParser(HTMLParser):
         def handle_starttag(self, tag, attrs):
             print("Start tag:", tag)
             for attr in attrs:
                 print("     attr:", attr)

         def handle_endtag(self, tag):
             print("End tag  :", tag)

         def handle_data(self, data):
             print("Data     :", data)

         def handle_comment(self, data):
             print("Comment  :", data)

         def handle_entityref(self, name):
             c = chr(name2codepoint[name])
             print("Named ent:", c)

         def handle_charref(self, name):
             if name.startswith('x'):
                 c = chr(int(name[1:], 16))
             else:
                 c = chr(int(name))
             print("Num ent  :", c)

         def handle_decl(self, data):
             print("Decl     :", data)

     parser = MyHTMLParser()

解析一个文档类型声明:

     >>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
     ...             '"http://www.w3.org/TR/html4/strict.dtd">')
     Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"

解析一个具有一些属性和标题的元素:

     >>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
     Start tag: img
          attr: ('src', 'python-logo.png')
          attr: ('alt', 'The Python logo')
     >>>
     >>> parser.feed('<h1>Python</h1>')
     Start tag: h1
     Data     : Python
     End tag  : h1

‘script’ 和 ‘style’ 元素中的内容原样返回，无需进一步解析:

     >>> parser.feed('<style type="text/css">#python { color: green }</style>')
     Start tag: style
          attr: ('type', 'text/css')
     Data     : #python { color: green }
     End tag  : style

     >>> parser.feed('<script type="text/javascript">'
     ...             'alert("<strong>hello!</strong>");</script>')
     Start tag: script
          attr: ('type', 'text/javascript')
     Data     : alert("<strong>hello!</strong>");
     End tag  : script

解析注释:

     >>> parser.feed('<!-- a comment -->'
     ...             '<!--[if IE 9]>IE-specific content<![endif]-->')
     Comment  :  a comment
     Comment  : [if IE 9]>IE-specific content<![endif]

解析命名或数字形式的字符引用，并把他们转换到正确的字符（注意：这 3 种转
义都是 ‘'>'’ ）:

     >>> parser.feed('&gt;&#62;&#x3E;')
     Named ent: >
     Num ent  : >
     Num ent  : >

填充不完整的块给 *note feed(): 29ea. 执行，*note handle_data(): 29f2. 可
能会多次调用（除非 `convert_charrefs' 被设置为 ‘True’ ）:

     >>> for chunk in ['<sp', 'an>buff', 'ered ', 'text</s', 'pan>']:
     ...     parser.feed(chunk)
     ...
     Start tag: span
     Data     : buff
     Data     : ered
     Data     : text
     End tag  : span

解析无效的 HTML (例如：未引用的属性）也能正常运行:

     >>> parser.feed('<p><a class=link href=#main>tag soup</p ></a>')
     Start tag: p
     Start tag: a
          attr: ('class', 'link')
          attr: ('href', '#main')
     Data     : tag soup
     End tag  : p
     End tag  : a


File: python.info,  Node: html entities --- HTML 一般实体的定义,  Next: XML处理模块,  Prev: html parser --- 简单的 HTML 和 XHTML 解析器,  Up: 结构化标记处理工具

5.20.3 ‘html.entities’ — HTML 一般实体的定义
--------------------------------------------

`源码：' Lib/html/entities.py(1)

__________________________________________________________________

该模块定义了四个词典， *note html5: a1d.、 *note name2codepoint: 29fd.、
*note codepoint2name: 29fe.、以及 *note entitydefs: 29ff.。

 -- 数据: html.entities.html5

     将 HTML5 命名字符引用 (2) 映射到等效的 Unicode 字符的字典，例如
     ‘html5['gt;'] == '>'’。 请注意，尾随的分号包含在名称中（例如
     ‘'gt;'’ ），但是即使没有分号，一些名称也会被标准接受，在这种情况下
     ，名称出现时带有和不带有 ‘';'’。另见 *note html.unescape(): 863.。

     3.3 新版功能.

 -- 数据: html.entities.entitydefs

     将 XHTML 1.0 实体定义映射到 ISO Latin-1 中的替换文本的字典。

 -- 数据: html.entities.name2codepoint

     将 HTML 实体名称映射到 Unicode 代码点的字典。

 -- 数据: html.entities.codepoint2name

     将 Unicode 代码点映射到 HTML 实体名称的字典。

备注
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/html/entities.py

   (2) (1) 参见
‘https://www.w3.org/TR/html5/syntax.html#named-character-references’


File: python.info,  Node: XML处理模块,  Next: xml etree ElementTree --- ElementTree XML API,  Prev: html entities --- HTML 一般实体的定义,  Up: 结构化标记处理工具

5.20.4 XML处理模块
------------------

`源码：' Lib/xml/(1)

__________________________________________________________________

用于处理XML的Python接口分组在 ‘xml’ 包中。

     警告: XML 模块对于错误或恶意构造的数据是不安全的。 如果你需要解析不
     受信任或未经身份验证的数据，请参阅 *note XML 漏洞: 2a03. 和 *note
     defusedxml 包: 2a04. 部分。

值得注意的是 *note xml: 134. 包中的模块要求至少有一个 SAX 兼容的 XML 解
析器可用。在 Python 中包含 Expat 解析器，因此 *note xml.parsers.expat:
139. 模块将始终可用。

*note xml.dom: 135. 和 *note xml.sax: 13c. 包的文档是 DOM 和 SAX 接口的
Python 绑定的定义。

XML 处理子模块包括:

   * *note xml.etree.ElementTree: 138.： ElementTree API，一个简单而轻量
     级的XML处理器

   * *note xml.dom: 135.：DOM API 定义

   * *note xml.dom.minidom: 136.：最小的 DOM 实现

   * *note xml.dom.pulldom: 137.：支持构建部分 DOM 树

   * *note xml.sax: 13c.：SAX2 基类和便利函数

   * *note xml.parsers.expat: 139.：Expat解析器绑定

* Menu:

* XML 漏洞::
* defusedxml 包::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/xml/


File: python.info,  Node: XML 漏洞,  Next: defusedxml 包,  Up: XML处理模块

5.20.4.1 XML 漏洞
.................

XML 处理模块对于恶意构造的数据是不安全的。 攻击者可能滥用 XML 功能来执行
拒绝服务攻击、访问本地文件、生成与其它计算机的网络连接或绕过防火墙。

下表概述了已知的攻击以及各种模块是否容易受到攻击。

种类                          sax                    etree                  minidom                pulldom                xmlrpc
                                                                                                                          
-------------------------------------------------------------------------------------------------------------------------------------------------
                                                                                                                          
billion laughs                `Vulnerable' (1)       `Vulnerable' (1)       `Vulnerable' (1)       `Vulnerable' (1)       `Vulnerable' (1)
                                                                                                                          
                                                                                                                          
quadratic blowup              `Vulnerable' (1)       `Vulnerable' (1)       `Vulnerable' (1)       `Vulnerable' (1)       `Vulnerable' (1)
                                                                                                                          
                                                                                                                          
external entity expansion     Safe (5)               Safe (2)               Safe (3)               Safe (5)               安全 (4)
                                                                                                                          
                                                                                                                          
DTD(1) retrieval              Safe (5)               安全                   安全                   Safe (5)               安全
                                                                                                                          
                                                                                                                          
decompression bomb            安全                   安全                   安全                   安全                   `易受攻击'
                                                                                                                          

  1. Expat 2.4.1 and newer is not vulnerable to the "billion laughs" and
     "quadratic blowup" vulnerabilities.  Items still listed as
     vulnerable due to potential reliance on system-provided libraries.
     Check ‘pyexpat.EXPAT_VERSION’.

  2. *note xml.etree.ElementTree: 138. 不会扩展外部实体并在实体发生时引
     发 ‘ParserError’。

  3. *note xml.dom.minidom: 136. 不会扩展外部实体，只是简单地返回未扩展
     的实体。

  4. ‘xmlrpclib’ 不扩展外部实体并省略它们。

  5. 从 Python 3.7.1 开始，默认情况下不再处理外部通用实体。

billion laughs / exponential entity expansion （狂笑/递归实体扩展）

     Billion Laughs(2) 攻击 – 也称为递归实体扩展 – 使用多级嵌套实体。 每
     个实体多次引用另一个实体，最终实体定义包含一个小字符串。 指数级扩展
     导致几千 GB 的文本，并消耗大量内存和 CPU 时间。

quadratic blowup entity expansion（二次爆炸实体扩展）

     二次爆炸攻击类似于 Billion Laughs(3) 攻击，它也滥用实体扩展。 它不
     是嵌套实体，而是一遍又一遍地重复一个具有几千个字符的大型实体。攻击
     不如递归情况有效，但它避免触发禁止深度嵌套实体的解析器对策。

external entity expansion

     实体声明可以包含的不仅仅是替换文本。 它们还可以指向外部资源或本地文
     件。 XML 解析器访问资源并将内容嵌入到 XML 文档中。

DTD(4) retrieval

     Python 的一些 XML 库 *note xml.dom.pulldom: 137. 从远程或本地位置检
     索文档类型定义。 该功能与外部实体扩展问题具有相似的含义。

decompression bomb

     Decompression bombs（解压炸弹，又名 ZIP bomb(5)）适用于所有可以解析
     压缩 XML 流（例如 gzip 压缩的 HTTP 流或 LZMA 压缩的文件）的 XML 库
     。 对于攻击者来说，它可以将传输的数据量减少三个量级或更多。

PyPI上 defusedxml(6) 的文档包含有关所有已知攻击向量的更多信息以及示例和
参考。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Document_type_definition

   (2) https://en.wikipedia.org/wiki/Billion_laughs

   (3) https://en.wikipedia.org/wiki/Billion_laughs

   (4) https://en.wikipedia.org/wiki/Document_type_definition

   (5) https://en.wikipedia.org/wiki/Zip_bomb

   (6) https://pypi.org/project/defusedxml/


File: python.info,  Node: defusedxml 包,  Prev: XML 漏洞,  Up: XML处理模块

5.20.4.2 ‘defusedxml’ 包
........................

defusedxml(1) 是一个纯 Python 软件包，它修改了所有标准库 XML 解析器的子
类，可以防止任何潜在的恶意操作。 对于解析不受信任的XML数据的任何服务器代
码，建议使用此程序包。 该软件包还提供了有关更多 XML 漏洞（如 XPath 注入
）的示例漏洞和扩展文档。

   ---------- Footnotes ----------

   (1) https://pypi.org/project/defusedxml/


File: python.info,  Node: xml etree ElementTree --- ElementTree XML API,  Next: xml dom --- 文档对象模型 API,  Prev: XML处理模块,  Up: 结构化标记处理工具

5.20.5 ‘xml.etree.ElementTree’ — ElementTree XML API
----------------------------------------------------

`源代码：' Lib/xml/etree/ElementTree.py(1)

__________________________________________________________________

*note xml.etree.ElementTree: 138. 模块实现了一个简单高效的API，用于解析
和创建XML数据。

在 3.3 版更改: 只要有可能，这个模块将使用快速实现。
‘xml.etree.cElementTree’ 模块已弃用。

     警告: *note xml.etree.ElementTree: 138. 模块对于恶意构建的数据是不
     安全的。如果需要解析不可信或未经身份验证的数据，请参见 *note XML
     漏洞: 2a03. 。

* Menu:

* 教程::
* XPath支持::
* 参考: 参考<2>.
* XInclude 支持::
* 参考: 参考<3>.

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/xml/etree/ElementTree.py


File: python.info,  Node: 教程,  Next: XPath支持,  Up: xml etree ElementTree --- ElementTree XML API

5.20.5.1 教程
.............

这是一个使用 *note xml.etree.ElementTree: 138. （简称 ‘ET’ ）的简短教程
。目标是演示模块的一些构建块和基本概念。

* Menu:

* XML树和元素::
* 解析XML::
* Pull API进行非阻塞解析::
* 查找感兴趣的元素::
* 修改XML文件::
* 构建XML文档::
* 使用命名空间解析XML::
* 其他资源: 其他资源<2>.


File: python.info,  Node: XML树和元素,  Next: 解析XML,  Up: 教程

5.20.5.2 XML树和元素
....................

XML是一种固有的分层数据格式，最自然的表示方法是使用树。为此， ‘ET’ 有两
个类： *note ElementTree: 91f. 将整个XML文档表示为一个树， *note
Element: acc. 表示该树中的单个节点。与整个文档的交互（读写文件）通常在
*note ElementTree: 91f. 级别完成。与单个XML元素及其子元素的交互是在
*note Element: acc. 级别完成的。


File: python.info,  Node: 解析XML,  Next: Pull API进行非阻塞解析,  Prev: XML树和元素,  Up: 教程

5.20.5.3 解析XML
................

我们将使用以下XML文档作为本节的示例数据：

     <?xml version="1.0"?>
     <data>
         <country name="Liechtenstein">
             <rank>1</rank>
             <year>2008</year>
             <gdppc>141100</gdppc>
             <neighbor name="Austria" direction="E"/>
             <neighbor name="Switzerland" direction="W"/>
         </country>
         <country name="Singapore">
             <rank>4</rank>
             <year>2011</year>
             <gdppc>59900</gdppc>
             <neighbor name="Malaysia" direction="N"/>
         </country>
         <country name="Panama">
             <rank>68</rank>
             <year>2011</year>
             <gdppc>13600</gdppc>
             <neighbor name="Costa Rica" direction="W"/>
             <neighbor name="Colombia" direction="E"/>
         </country>
     </data>

可以通过从文件中读取来导入此数据：

     import xml.etree.ElementTree as ET
     tree = ET.parse('country_data.xml')
     root = tree.getroot()

或直接从字符串中解析：

     root = ET.fromstring(country_data_as_string)

*note fromstring(): 2a0e. 将XML从字符串直接解析为 *note Element: acc. ，
该元素是已解析树的根元素。其他解析函数可能会创建一个 *note ElementTree:
91f. 。确切信息请查阅文档。

作为 *note Element: acc. ， ‘root’ 具有标签和属性字典:

     >>> root.tag
     'data'
     >>> root.attrib
     {}

还有可以迭代的子节点：

     >>> for child in root:
     ...     print(child.tag, child.attrib)
     ...
     country {'name': 'Liechtenstein'}
     country {'name': 'Singapore'}
     country {'name': 'Panama'}

子级是可以嵌套的，我们可以通过索引访问特定的子级节点：

     >>> root[0][1].text
     '2008'

     注解: 并非XML输入的所有元素都将作为解析树的元素结束。目前，此模块跳
     过输入中的任何XML注释、处理指令和文档类型声明。然而，使用这个模块的
     API而不是从XML文本解析构建的树可以包含注释和处理指令，生成XML输出时
     同样包含这些注释和处理指令。可以通过将自定义 *note TreeBuilder:
     254. 实例传递给 *note XMLParser: 253. 构造函数来访问文档类型声明。


File: python.info,  Node: Pull API进行非阻塞解析,  Next: 查找感兴趣的元素,  Prev: 解析XML,  Up: 教程

5.20.5.4 Pull API进行非阻塞解析
...............................

此模块所提供了大多数解析函数都要求在返回任何结果之前一次性读取整个文档。
可以使用 *note XMLParser: 253. 并以渐进方式添加数据，但这是在回调目标上
调用方法的推送式 API。 有时用户真正想要的是能够以渐进方式解析 XML 而无需
阻塞操作，同时享受完整的已构造 *note Element: acc. 对象。

针对此需求的最强大工具是 *note XMLPullParser: 91b.。 它不要求通过阻塞式
读取来获得 XML 数据，而是通过执行 *note XMLPullParser.feed(): 2a10. 调用
来渐进式地添加数据。 要获得已解析的 XML 元素，应调用 *note
XMLPullParser.read_events(): 2a11.。 下面是一个示例:

     >>> parser = ET.XMLPullParser(['start', 'end'])
     >>> parser.feed('<mytag>sometext')
     >>> list(parser.read_events())
     [('start', <Element 'mytag' at 0x7fa66db2be58>)]
     >>> parser.feed(' more text</mytag>')
     >>> for event, elem in parser.read_events():
     ...     print(event)
     ...     print(elem.tag, 'text=', elem.text)
     ...
     end

常见的用例是针对以非阻塞方式进行的应用程序，其中 XML 是从套接字接收或从
某些存储设备渐进式读取的。 在这些用例中，阻塞式读取是不可接受的。

因为其非常灵活，*note XMLPullParser: 91b. 在更简单的用例中使用起来可能并
不方便。 如果你不介意你的应用程序在读取 XML 数据时造成阻塞但仍希望具有增
量解析能力，可以考虑 *note iterparse(): 950.。 它在你读取大型 XML 文档并
且不希望将它完全放去内存时会很适用。


File: python.info,  Node: 查找感兴趣的元素,  Next: 修改XML文件,  Prev: Pull API进行非阻塞解析,  Up: 教程

5.20.5.5 查找感兴趣的元素
.........................

*note Element: acc. 有一些很有效的方法，可帮助递归遍历其下的所有子树（包
括子级，子级的子级，等等）。例如 *note Element.iter(): cef.:

     >>> for neighbor in root.iter('neighbor'):
     ...     print(neighbor.attrib)
     ...
     {'name': 'Austria', 'direction': 'E'}
     {'name': 'Switzerland', 'direction': 'W'}
     {'name': 'Malaysia', 'direction': 'N'}
     {'name': 'Costa Rica', 'direction': 'W'}
     {'name': 'Colombia', 'direction': 'E'}

*note Element.findall(): 2a13. 仅查找当前元素的直接子元素中带有指定标签
的元素。 *note Element.find(): 2a14. 找带有特定标签的 `第一个' 子级，然
后可以用 *note Element.text: 2a15. 访问元素的文本内容。 *note
Element.get: 2a16. 访问元素的属性:

     >>> for country in root.findall('country'):
     ...     rank = country.find('rank').text
     ...     name = country.get('name')
     ...     print(name, rank)
     ...
     Liechtenstein 1
     Singapore 4
     Panama 68

通过使用 *note XPath: 422. ，可以更精确地指定要查找的元素。


File: python.info,  Node: 修改XML文件,  Next: 构建XML文档,  Prev: 查找感兴趣的元素,  Up: 教程

5.20.5.6 修改XML文件
....................

*note ElementTree: 91f. 提供了一种构建XML文档并将其写入文件的简单方法。
调用 *note ElementTree.write(): 920. 方法就可以实现。

创建后可以直接操作 *note Element: acc. 对象。例如：使用 *note
Element.text: 2a15. 修改文本字段，使用 *note Element.set(): 2a18. 方法添
加和修改属性，以及使用 *note Element.append(): 2a19. 添加新的子元素。

假设我们要为每个国家/地区的中添加一个排名，并在排名元素中添加一个
‘updated’ 属性：

     >>> for rank in root.iter('rank'):
     ...     new_rank = int(rank.text) + 1
     ...     rank.text = str(new_rank)
     ...     rank.set('updated', 'yes')
     ...
     >>> tree.write('output.xml')

生成的XML现在看起来像这样：

     <?xml version="1.0"?>
     <data>
         <country name="Liechtenstein">
             <rank updated="yes">2</rank>
             <year>2008</year>
             <gdppc>141100</gdppc>
             <neighbor name="Austria" direction="E"/>
             <neighbor name="Switzerland" direction="W"/>
         </country>
         <country name="Singapore">
             <rank updated="yes">5</rank>
             <year>2011</year>
             <gdppc>59900</gdppc>
             <neighbor name="Malaysia" direction="N"/>
         </country>
         <country name="Panama">
             <rank updated="yes">69</rank>
             <year>2011</year>
             <gdppc>13600</gdppc>
             <neighbor name="Costa Rica" direction="W"/>
             <neighbor name="Colombia" direction="E"/>
         </country>
     </data>

可以使用 *note Element.remove(): 2a1a. 删除元素。假设我们要删除排名高于
50的所有国家/地区:

     >>> for country in root.findall('country'):
     ...     # using root.findall() to avoid removal during traversal
     ...     rank = int(country.find('rank').text)
     ...     if rank > 50:
     ...         root.remove(country)
     ...
     >>> tree.write('output.xml')

请注意在迭代时进行并发修改可能会导致问题，就像在迭代并修改 Python 列表或
字典时那样。 因此，这个示例先通过 ‘root.findall()’ 收集了所有匹配的元素
，在此之后再对匹配项列表进行迭代。

生成的XML现在看起来像这样：

     <?xml version="1.0"?>
     <data>
         <country name="Liechtenstein">
             <rank updated="yes">2</rank>
             <year>2008</year>
             <gdppc>141100</gdppc>
             <neighbor name="Austria" direction="E"/>
             <neighbor name="Switzerland" direction="W"/>
         </country>
         <country name="Singapore">
             <rank updated="yes">5</rank>
             <year>2011</year>
             <gdppc>59900</gdppc>
             <neighbor name="Malaysia" direction="N"/>
         </country>
     </data>


File: python.info,  Node: 构建XML文档,  Next: 使用命名空间解析XML,  Prev: 修改XML文件,  Up: 教程

5.20.5.7 构建XML文档
....................

*note SubElement(): 2a1c. 函数还提供了一种便捷方法来为给定元素创建新的子
元素:

     >>> a = ET.Element('a')
     >>> b = ET.SubElement(a, 'b')
     >>> c = ET.SubElement(a, 'c')
     >>> d = ET.SubElement(c, 'd')
     >>> ET.dump(a)
     <a><b /><c><d /></c></a>


File: python.info,  Node: 使用命名空间解析XML,  Next: 其他资源<2>,  Prev: 构建XML文档,  Up: 教程

5.20.5.8 使用命名空间解析XML
............................

如果 XML 输入带有 命名空间(1)，则具有前缀的 ‘prefix:sometag’ 形式的标记
和属性将被扩展为 ‘{uri}sometag’，其中 `prefix' 会被完整 `URI' 所替换。 并
且，如果存在 默认命名空间(2)，则完整 URI 会被添加到所有未加前缀的标记之
前。

下面的 XML 示例包含两个命名空间，一个具有前缀 "fictional" 而另一个则作为
默认命名空间:

     <?xml version="1.0"?>
     <actors xmlns:fictional="http://characters.example.com"
             xmlns="http://people.example.com">
         <actor>
             <name>John Cleese</name>
             <fictional:character>Lancelot</fictional:character>
             <fictional:character>Archie Leach</fictional:character>
         </actor>
         <actor>
             <name>Eric Idle</name>
             <fictional:character>Sir Robin</fictional:character>
             <fictional:character>Gunther</fictional:character>
             <fictional:character>Commander Clement</fictional:character>
         </actor>
     </actors>

搜索和探查这个 XML 示例的一种方式是手动为 *note find(): 2a14. 或 *note
findall(): 2a13. 的 xpath 中的每个标记或属性添加 URI:

     root = fromstring(xml_text)
     for actor in root.findall('{http://people.example.com}actor'):
         name = actor.find('{http://people.example.com}name')
         print(name.text)
         for char in actor.findall('{http://characters.example.com}character'):
             print(' |-->', char.text)

一种更好的方式是搜索带命名空间的 XML 示例创建一个字典来存放你自己的前缀
并在搜索函数中使用它们:

     ns = {'real_person': 'http://people.example.com',
           'role': 'http://characters.example.com'}

     for actor in root.findall('real_person:actor', ns):
         name = actor.find('real_person:name', ns)
         print(name.text)
         for char in actor.findall('role:character', ns):
             print(' |-->', char.text)

这两种方式都会输出:

     John Cleese
      |--> Lancelot
      |--> Archie Leach
     Eric Idle
      |--> Sir Robin
      |--> Gunther
      |--> Commander Clement

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/XML_namespace

   (2) https://www.w3.org/TR/xml-names/#defaulting


File: python.info,  Node: 其他资源<2>,  Prev: 使用命名空间解析XML,  Up: 教程

5.20.5.9 其他资源
.................

请访问 ‘http://effbot.org/zone/element-index.htm’ 获取教程和其他文档的链
接。


File: python.info,  Node: XPath支持,  Next: 参考<2>,  Prev: 教程,  Up: xml etree ElementTree --- ElementTree XML API

5.20.5.10 XPath支持
...................

此模块提供了对 XPath 表达式(1) 的有限支持用于在树中定位元素。 其目标是支
持一个简化语法的较小子集；完整的 XPath 引擎超出了此模块的适用范围。

* Menu:

* 示例: 示例<10>.
* 支持的XPath语法::

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/xpath


File: python.info,  Node: 示例<10>,  Next: 支持的XPath语法,  Up: XPath支持

5.20.5.11 示例
..............

下面是一个演示此模块的部分 XPath 功能的例子。 我们将使用来自 *note 解析
XML: 2a0c. 小节的 ‘countrydata’ XML 文档:

     import xml.etree.ElementTree as ET

     root = ET.fromstring(countrydata)

     # Top-level elements
     root.findall(".")

     # All 'neighbor' grand-children of 'country' children of the top-level
     # elements
     root.findall("./country/neighbor")

     # Nodes with name='Singapore' that have a 'year' child
     root.findall(".//year/..[@name='Singapore']")

     # 'year' nodes that are children of nodes with name='Singapore'
     root.findall(".//*[@name='Singapore']/year")

     # All 'neighbor' nodes that are the second child of their parent
     root.findall(".//neighbor[2]")

对于带有命名空间的 XML，应使用通常的限定 ‘{namespace}tag’ 标记法:

     # All dublin-core "title" tags in the document
     root.findall(".//{http://purl.org/dc/elements/1.1/}title")


File: python.info,  Node: 支持的XPath语法,  Prev: 示例<10>,  Up: XPath支持

5.20.5.12 支持的XPath语法
.........................

语法                        含义
                            
---------------------------------------------------------------------------------------
                            
‘tag’                       选择具有给定标记的所有子元素。 例如，‘spam’ 是选择名为
                            ‘spam’ 的所有子元素，而 ‘spam/egg’ 是在名为 ‘spam’ 的子
                            元素中选择所有名为 ‘egg’ 的孙元素，‘{*}spam’ 是在任意（
                            或无）命名空间中选择名为 ‘spam’ 的标记，而 ‘{}*’ 是只选
                            择不在一个命名空间中的标记。
                            
                            在 3.8 版更改: 增加了对星号通配符的支持。
                            
                            
‘*’                         选择所有子元素，包括注释和处理说明。例如 ‘*/egg’ 选择所
                            有名为 ‘egg’ 的孙元素。
                            
                            
‘.’                         选择当前节点。这在路径的开头非常有用，用于指示它是相对路
                            径。
                            
                            
‘//’                        选择所有子元素 在当前元素的所有下级中选择所有下级元素。
                            例如，‘.//egg’ 是在整个树中选择所有 ‘egg’ 元素。
                            
                            
‘..’                        选择父元素。 如果路径试图前往起始元素的上级（元素的
                            ‘find’ 被调用）则返回 ‘None’。
                            
                            
‘[@attrib]’                 选择具有给定属性的所有元素。
                            
                            
‘[@attrib='value']’         选择给定属性具有给定值的所有元素。该值不能包含引号。
                            
                            
‘[tag]’                     选择所有包含 ‘tag’ 子元素的元素。只支持直系子元素。
                            
                            
‘[.='text']’                选择完整文本内容等于 ‘text’ 的所有元素（包括后代）。
                            
                            3.7 新版功能.
                            
                            
‘[tag='text']’              选择所有包含名为 ‘tag’ 的子元素的元素，这些子元素（包括
                            后代）的完整文本内容等于给定的 ‘text’ 。
                            
                            
‘[position]’                选择位于给定位置的所有元素。 位置可以是一个整数 (1 表示
                            首位)，表达式 ‘last()’ (表示末位)，或者相对于末位的位置
                            (例如 ‘last()-1’)。
                            

谓词（方括号内的表达式）之前必须带有标签名称，星号或其他谓词。‘position’
谓词前必须有标签名称。


File: python.info,  Node: 参考<2>,  Next: XInclude 支持,  Prev: XPath支持,  Up: xml etree ElementTree --- ElementTree XML API

5.20.5.13 参考
..............

* Menu:

* 函数: 函数<6>.


File: python.info,  Node: 函数<6>,  Up: 参考<2>

5.20.5.14 函数
..............

 -- 函数: xml.etree.ElementTree.canonicalize (xml_data=None, *,
          out=None, from_file=None, **options)

     C14N 2.0(1) 转换功能。.

     规整化是标准化 XML 输出的一种方式，该方式允许按字节比较和数字签名。
     它降低了 XML 序列化器所具有的自由度并改为生成更受约束的 XML 表示形
     式。 主要限制涉及命名空间声明的位置、属性的顺序和可忽略的空白符等。

     此函数接受一个 XML 数字字符串 (`xml_data') 或文件路径或者文件类对象
     (`from_file') 作为输入，将其转换为规整形式，并在提供了 `out' 文件（
     类）对象的情况下将其写到该对象的话，或者如果未提供则将其作为文本字
     符串返回。 输出文件接受文本而非字节数据。 因此它应当以使用 ‘utf-8’
     编码格式的文本模式来打开。

     典型使用:

          xml_data = "<root>...</root>"
          print(canonicalize(xml_data))

          with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file:
              canonicalize(xml_data, out=out_file)

          with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file:
              canonicalize(from_file="inputfile.xml", out=out_file)

     配置选项 `options' 如下:

        - `with_comments': 设为真值以包括注释 (默认为假值)

        - 
          `strip_text': 设为真值以去除文本内容前后的空白符

               （默认值：否）

        - 
          `rewrite_prefixes': 设为真值以替换带有 "n{number}" 前缀的命名空间

               （默认值：否）

        - 
          `qname_aware_tags': 一组可感知限定名称的标记名称，其中的前缀

               应当在文本内容中被替换 (默认为空值)

        - 
          `qname_aware_attrs': 一组可感知限定名称的属性名称，其中的前缀

               应当在文本内容中被替换 (默认为空值)

        - `exclude_attrs': 一组不应当被序列化的属性名称

        - `exclude_tags': 一组不应当被序列化的标记名称

     在上面的选项列表中，"一组" 是指任意多项集或包含字符串的可迭代对象，
     排序是不必要的。

     3.8 新版功能.

 -- 函数: xml.etree.ElementTree.Comment (text=None)

     注释元素工厂函数。 这个工厂函数可创建一个特殊元素，它将被标准序列化
     器当作 XML 注释来进行序列化。 注释字串可以是字节串或是 Unicode 字符
     串。 `text' 是包含注释字串的字符串。 返回一个表示注释的元素实例。

     请注意 *note XMLParser: 253. 会跳过输入中的注释而不会为其创建注释对
     象。 *note ElementTree: 91f. 将只在当使用某个 *note Element: acc. 方
     法向树插入了注释节点时才会包含注释节点。

 -- 函数: xml.etree.ElementTree.dump (elem)

     将一个元素树或元素结构体写入到 sys.stdout。 此函数应当只被用于调试
     。

     实际输出格式是依赖于具体实现的。 在这个版本中，它将以普通 XML 文件
     的格式写入。

     `elem' 是一个元素树或单独元素。

     在 3.8 版更改: *note dump(): 2a27. 函数现在会保留用户指定的属性顺序
     。

 -- 函数: xml.etree.ElementTree.fromstring (text, parser=None)

     根据一个字符串常量解析 XML 的节。 与 *note XML(): 2a28. 类似。
     `text' 是包含 XML 数据的字符串。 `parser' 是可选的解析器实例。 如果
     未给出，则会使用标准 *note XMLParser: 253.。 返回一个 *note
     Element: acc. 实例。

 -- 函数: xml.etree.ElementTree.fromstringlist (sequence, parser=None)

     根据一个字符串片段序列解析 XML 文档。 `sequence' 是包含 XML 数据片
     段的列表或其他序列对象。 `parser' 是可选的解析器实例。 如果未给出，
     则会使用标准的 *note XMLParser: 253. 解析器。 返回一个 *note
     Element: acc. 实例。

     3.2 新版功能.

 -- 函数: xml.etree.ElementTree.iselement (element)

     检测一个对象是否为有效的元素对象。 `element' 是一个元素实例。 如果
     对象是一个元素对象则返回 ‘True’。

 -- 函数: xml.etree.ElementTree.iterparse (source, events=None,
          parser=None)

     以增量方式将一个 XML 节解析为元素树，并向用户报告执行情况。
     `source' 是包含 XML 数据的文件名或 *note file object: b4a.。
     `events' 是要报告的事件序列。 所支持的事件字符串有 ‘"start"’,
     ‘"end"’, ‘"comment"’, ‘"pi"’, ‘"start-ns"’ 和 ‘"end-ns"’ ("ns" 事件
     用于获取详细的命名空间信息)。 如果 `events' 被省略，则只有 ‘"end"’
     事件会被报告。 `parser' 是可选的解析器实例。 如果未给出，则会使用标
     准的 *note XMLParser: 253. 解析器。 `parser' 必须为 *note
     XMLParser: 253. 的子类并且只能使用默认的 *note TreeBuilder: 254. 作
     为目标。 返回一个提供 ‘(event, elem)’ 对的 *note iterator: 104b.。

     请注意虽然 *note iterparse(): 950. 是以增量方式构建树，但它会对
     `source' (或其所指定的文件) 发出阻塞式读取。 因此，它不适用于不可执
     行阻塞式读取的应用。 对于完全非阻塞式的解析，请参看 *note
     XMLPullParser: 91b.。

          注解: *note iterparse(): 950. 只会确保当发出 "start" 事件时看
          到了开始标记的 ">" 字符，因而在这个点上属性已被定义，但文本容
          和末尾属性还未被定义。 这同样适用于元素的下级；它们可能存在也
          可能不存在。

          如果你需要已完全填充的元素，请改为查找 "end" 事件。

     3.4 版后已移除: `parser' 参数。

     在 3.8 版更改: 增加了 ‘comment’ 和 ‘pi’ 事件。

 -- 函数: xml.etree.ElementTree.parse (source, parser=None)

     将一个 XML 的节解析为元素树。 `source' 是包含 XML 数据的文件名或文
     件对象。 `parser' 是可选的解析器实例。 如果未给出，则会使用标准的
     *note XMLParser: 253. 解析器。 返回一个 *note ElementTree: 91f. 实
     例。

 -- 函数: xml.etree.ElementTree.ProcessingInstruction (target,
          text=None)

     PI 元素工厂函数。 这个工厂函数可创建一个特殊元素，它将被当作 XML 处
     理指令来进行序列化。 `target' 是包含 PI 目标的字符串。 `text' 如果
     给出则是包含 PI 内容的字符串。 返回一个表示处理指令的元素实例。

     请注意 *note XMLParser: 253. 会跳过输入中的处理指令而不会为其创建注
     释对象。 *note ElementTree: 91f. 将只在当使用某个 *note Element:
     acc. 方法向树插入了处理指令节点时才会包含处理指令节点。

 -- 函数: xml.etree.ElementTree.register_namespace (prefix, uri)

     注册一个命名空间前缀。 这个注册表是全局的，并且任何对应给定前缀或命
     名空间 URI 的现有映射都会被移除。 `prefix' 是命名空间前缀。 `uri' 是
     命名空间 URI。 如果可能的话，这个命名空间中的标记和属性将附带给定的
     前缀来进行序列化。

     3.2 新版功能.

 -- 函数: xml.etree.ElementTree.SubElement (parent, tag, attrib={},
          **extra)

     子元素工厂函数。 这个函数会创建一个元素实例，并将其添加到现有的元素
     。

     元素名、属性名和属性值可以是字节串或 Unicode 字符串。 `parent' 是父
     元素。 `tag' 是子元素名。 `attrib' 是一个可选的字典，其中包含元素属
     性。 `extra' 包含额外的属性，以关键字参数形式给出。 返回一个元素实
     例。

 -- 函数: xml.etree.ElementTree.tostring (element, encoding="us-ascii",
          method="xml", *, xml_declaration=None, default_namespace=None,
          short_empty_elements=True)

     生成一个 XML 元素的字符串表示形式，包括所有子元素。 `element' 是一
     个 *note Element: acc. 实例。 `encoding' (2) 是输出编码格式（默认为
     US-ASCII）。 请使用 ‘encoding="unicode"’ 来生成 Unicode 字符串（否
     则生成字节串）。 `method' 是 ‘"xml"’, ‘"html"’ 或 ‘"text"’ (默认为
     ‘"xml"’)。 `xml_declaration', `default_namespace' 和
     `short_empty_elements' 具有与 *note ElementTree.write(): 920. 中一
     致的含义。 返回一个包含 XML 数据（可选）已编码的字符串。

     3.4 新版功能: `short_empty_elements' 形参。

     3.8 新版功能: `xml_declaration' 和 `default_namespace' 形参。

     在 3.8 版更改: *note tostring(): 91d. 函数现在会保留用户指定的属性
     顺序。

 -- 函数: xml.etree.ElementTree.tostringlist (element,
          encoding="us-ascii", method="xml", *, xml_declaration=None,
          default_namespace=None, short_empty_elements=True)

     生成一个 XML 元素的字符串表示形式，包括所有子元素。 `element' 是一
     个 *note Element: acc. 实例。 `encoding' (3) 是输出编码格式（默认为
     US-ASCII）。 请使用 ‘encoding="unicode"’ 来生成 Unicode 字符串（否
     则生成字节串）。 `method' 是 ‘"xml"’, ‘"html"’ 或 ‘"text"’ (默认为
     ‘"xml"’)。 `xml_declaration', `default_namespace' 和
     `short_empty_elements' 具有与 *note ElementTree.write(): 920. 中一
     致的含义。 返回一个包含 XML 数据（可选）已编码字符串的列表。 它并不
     保证任何特定的序列，除了 ‘b"".join(tostringlist(element)) ==
     tostring(element)’。

     3.2 新版功能.

     3.4 新版功能: `short_empty_elements' 形参。

     3.8 新版功能: `xml_declaration' 和 `default_namespace' 形参。

     在 3.8 版更改: *note tostringlist(): 91e. 函数现在会保留用户指定的
     属性顺序。

 -- 函数: xml.etree.ElementTree.XML (text, parser=None)

     根据一个字符串常量解析 XML 的节。 此函数可被用于在 Python 代码中嵌
     入“XML 字面值”。 `text' 是包含 XML 数据的字符串。 `parser' 是可选的
     解析器实例。 如果未给出，则会使用标准的 *note XMLParser: 253. 解析
     器。 返回一个 *note Element: acc. 实例。

 -- 函数: xml.etree.ElementTree.XMLID (text, parser=None)

     根据一个字符串常量解析 XML 的节，并且还将返回一个将元素的 id:s 映射
     到元素的字典。 `text' 是包含 XML 数据的字符串。 `parser' 是可选的解
     析器实例。 如果未给出，则会使用标准的 *note XMLParser: 253. 解析器
     。 返回一个包含 *note Element: acc. 实例和字典的元组。

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/xml-c14n2/

   (2) (1) 包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如
"UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅
‘https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl’ 和
‘https://www.iana.org/assignments/character-sets/character-sets.xhtml’。

   (3) (1) 包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如
"UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅
‘https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl’ 和
‘https://www.iana.org/assignments/character-sets/character-sets.xhtml’。


File: python.info,  Node: XInclude 支持,  Next: 参考<3>,  Prev: 参考<2>,  Up: xml etree ElementTree --- ElementTree XML API

5.20.5.15 XInclude 支持
.......................

此模块通过 ‘xml.etree.ElementInclude’ 辅助模块提供了对 XInclude 指令(1)
的有限支持，这个模块可被用来根据元素树的信息在其中插入子树和文本字符串。

* Menu:

* 示例: 示例<11>.

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/xinclude/


File: python.info,  Node: 示例<11>,  Up: XInclude 支持

5.20.5.16 示例
..............

以下是一个演示 XInclude 模块用法的例子。 要在当前文本中包括一个 XML 文档
，请使用 ‘{http://www.w3.org/2001/XInclude}include’ 元素并将 `parse' 属
性设为 ‘"xml"’，并使用 `href' 属性来指定要包括的文档。

     <?xml version="1.0"?>
     <document xmlns:xi="http://www.w3.org/2001/XInclude">
       <xi:include href="source.xml" parse="xml" />
     </document>

默认情况下，`href' 属性会被当作文件名来处理。 你可以使用自定义加载器来重
载此行为。 还要注意标准辅助器不支持 XPointer 语法。

要处理这个文件，请正常加载它，并将根元素传给 *note
xml.etree.ElementTree: 138. 模块:

     from xml.etree import ElementTree, ElementInclude

     tree = ElementTree.parse("document.xml")
     root = tree.getroot()

     ElementInclude.include(root)

ElementInclude 模块使用来自 `source.xml' 文档的根元素替代
‘{http://www.w3.org/2001/XInclude}include’ 元素。 结果看起来大概是这样:

     <document xmlns:xi="http://www.w3.org/2001/XInclude">
       <para>This is a paragraph.</para>
     </document>

如果省略了 `parse' 属性，它会取默认的 "xml"。 要求有 href 属性。

要包括文本文档，请使用 ‘{http://www.w3.org/2001/XInclude}include’ 元素，
并将 `parse' 属性设为 "text":

     <?xml version="1.0"?>
     <document xmlns:xi="http://www.w3.org/2001/XInclude">
       Copyright (c) <xi:include href="year.txt" parse="text" />.
     </document>

结果可能如下所示：

     <document xmlns:xi="http://www.w3.org/2001/XInclude">
       Copyright (c) 2003.
     </document>


File: python.info,  Node: 参考<3>,  Prev: XInclude 支持,  Up: xml etree ElementTree --- ElementTree XML API

5.20.5.17 参考
..............

* Menu:

* 函数: 函数<7>.
* 元素对象::
* ElementTree 对象::
* QName 对象::
* TreeBuilder 对象::
* XMLParser对象::
* XMLPullParser对象::
* 异常: 异常<15>.


File: python.info,  Node: 函数<7>,  Next: 元素对象,  Up: 参考<3>

5.20.5.18 函数
..............

 -- 函数: xml.etree.ElementInclude.default_loader (href, parse,
          encoding=None)

     默认的加载器。 这个默认的加载器会从磁盘读取所包括的资源。 `href' 是
     一个 URL。 `parse' 是 "xml" 或 "text" 表示解析模式。 `encoding' 是
     可选的文本编码格式。 如果未给出，则编码格式为 ‘utf-8’。 返回已扩展
     的资源。 如果解析模式为 ‘"xml"’，则它是一个 ElementTree 实例。 如果
     解析模式为 "text"，则它是一个 Unicode 字符串。 如果加载器失败，它可
     以返回 None 或者引发异常。

 -- 函数: xml.etree.ElementInclude.include (elem, loader=None)

     This function expands XInclude directives.  `elem' is the root
     element.  `loader' is an optional resource loader.  If omitted, it
     defaults to *note default_loader(): 2a33.  If given, it should be a
     callable that implements the same interface as *note
     default_loader(): 2a33.  Returns the expanded resource.  If the
     parse mode is ‘"xml"’, this is an ElementTree instance.  If the
     parse mode is "text", this is a Unicode string.  If the loader
     fails, it can return None or raise an exception.


File: python.info,  Node: 元素对象,  Next: ElementTree 对象,  Prev: 函数<7>,  Up: 参考<3>

5.20.5.19 元素对象
..................

 -- 类: xml.etree.ElementTree.Element (tag, attrib={}, **extra)

     元素类。 这个类定义了 Element 接口，并提供了这个接口的引用实现。

     元素名、属性名和属性值可以是字节串或 Unicode 字符串。 `tag' 是元素
     名。 `attrib' 是一个可选的字典，其中包含元素属性。 `extra' 包含额外
     的属性，以关键字参数形式给出。

      -- 属性: tag

          一个标识此元素意味着何种数据的字符串(换句话说，元素类型)。

      -- 属性: text
      -- 属性: tail

          这些属性可被用于存放与元素相关联的额外数据。 它们的值通常为字
          符串但也可以是任何应用专属的对象。 如果元素是基于 XML 文件创建
          的，`text' 属性会存放元素的开始标记及其第一个子元素或结束标记
          之间的文本，或者为 ‘None’，而 `tail' 属性会存放元素的结束标记
          及下一个标记之间的文本，或者为 ‘None’。 对于 XML 数据

               <a><b>1<c>2<d/>3</c></b>4</a>

          `a' 元素的 `text' 和 `tail' 属性均为 ‘None’，`b' 元素的 `text'
          为 ‘"1"’ 而 `tail' 为 ‘"4"’，`c' 元素的 `text' 为 ‘"2"’ 而
          `tail' 为 ‘None’，`d' 元素的 `text' 为 ‘None’ 而 `tail' 为
          ‘"3"’。

          要获取一个元素的内部文本，请参阅 *note itertext(): b5b.，例如
          ‘"".join(element.itertext())’。

          应用程序可以将任意对象存入这些属性。

      -- 属性: attrib

          一个包含元素属性的字典。 请注意虽然 `attrib' 值总是一个真正可
          变的 Python 字典，但 ElementTree 实现可以选择其他内部表示形式
          ，并只在有需要时才创建字典。 为了发挥这种实现的优势，请在任何
          可能情况下使用下列字典方法。

     以下字典类方法可作用于元素属性。

      -- 方法: clear ()

          重设一个元素。 此方法会移除所有子元素，清空所有属性，并将 text
          和 tail 属性设为 ‘None’。

      -- 方法: get (key, default=None)

          获取名为 `key' 的元素属性。

          返回属性的值，或者如果属性未找到则返回 `default'。

      -- 方法: items ()

          将元素属性以 (name, value) 对序列的形式返回。 所返回属性的顺序
          任意。

      -- 方法: keys ()

          将元素属性名称以列表的形式返回。 所返回名称的顺序任意。

      -- 方法: set (key, value)

          将元素的 `key' 属性设为 `value'。

     以下方法作用于元素的下级（子元素）。

      -- 方法: append (subelement)

          将元素 `subelement' 添加到此元素的子元素内部列表。 如果
          `subelement' 不是一个 *note Element: acc. 则会引发 *note
          TypeError: 193.。

      -- 方法: extend (subelements)

          使用具有零个或多个元素的序列对象添加 `subelements'。 如果某个
          子元素不是 *note Element: acc. 则会引发 *note TypeError: 193.。

          3.2 新版功能.

      -- 方法: find (match, namespaces=None)

          查找第一个匹配 `match' 的子元素。 `match' 可以是一个标记名称或
          者 *note 路径: 422.。 返回一个元素实例或 ‘None’。 `namespaces'
          是可选的从命名空间前缀到完整名称的映射。 传入 ‘''’ 作为前缀可
          将表达式中所有无前缀的标记名称移动到给定的命名空间。

      -- 方法: findall (match, namespaces=None)

          根据标记名称或者 *note 路径: 422. 查找所有匹配的子元素。 返回
          一个包含所有匹配元素按文档顺序排序的列表。 `namespaces' 是可选
          的从命名空间前缀到完整名称的映射。 传入 ‘''’ 作为前缀可将表达
          式中所有无前缀的标记名称移动到给定的命名空间。

      -- 方法: findtext (match, default=None, namespaces=None)

          查找第一个匹配 `match' 的子元素的文本。 `match' 可以是一个标记
          名称或者 *note 路径: 422.。 反回第一个匹配的元素的文本内容，或
          者如果元素未找到则返回 `default'。 请注意如果匹配的元素没有文
          本内容则会返回一个空字符串。 `namespaces' 是可选的从命名空间前
          缀到完整名称的映射。 传入 ‘''’ 作为前缀可将表达式中所有无前缀
          的标记名称移动到给定的命名空间。

      -- 方法: getchildren ()

          Deprecated since version 3.2, will be removed in version 3.9:
          Use ‘list(elem)’ or iteration.

      -- 方法: getiterator (tag=None)

          Deprecated since version 3.2, will be removed in version 3.9:
          Use method *note Element.iter(): cef. instead.

      -- 方法: insert (index, subelement)

          将 `subelement' 插入到此元素的给定位置中。 如果 `subelement' 不
          是一个 *note Element: acc. 则会引发 *note TypeError: 193.。

      -- 方法: iter (tag=None)

          创建一个以当前元素为根元素的树的 *note iterator: 104b.。 该迭
          代器将以文档（深度优先）顺序迭代此元素及其所有下级元素。 如果
          `tag' 不为 ‘None’ 或 ‘'*'’，则迭代器只返回标记为 `tag' 的元素
          。 如果树结构在迭代期间被修改，则结果是未定义的。

          3.2 新版功能.

      -- 方法: iterfind (match, namespaces=None)

          根据标记名称或者 *note 路径: 422. 查找所有匹配的子元素。 返回
          一个按文档顺序产生所有匹配元素的可迭代对象。 `namespaces' 是可
          选的从命名空间前缀到完整名称的映射。

          3.2 新版功能.

      -- 方法: itertext ()

          创建一个文本迭代器。 该迭代器将按文档顺序遍历此元素及其所有子
          元素，并返回所有内部文本。

          3.2 新版功能.

      -- 方法: makeelement (tag, attrib)

          创建一个与此元素类型相同的新元素对象。 请不要调用此方法，而应
          改用 *note SubElement(): 2a1c. 工厂函数。

      -- 方法: remove (subelement)

          从元素中移除 `subelement'。 与 find* 方法不同的是此方法会基于
          实例的标识来比较元素，而不是基于标记的值或内容。

     *note Element: acc. 对象还支持下列序列类型方法以配合子元素使用:
     *note __delitem__(): c6b, *note __getitem__(): 280, *note
     __setitem__(): c6a, *note __len__(): dd3.。

     注意：不带子元素的元素将被检测为 ‘False’。 此行为将在未来的版本中发
     生变化。 请改用 ‘len(elem)’ 或 ‘elem is None’ 进行检测。

          element = root.find('foo')

          if not element:  # careful!
              print("element not found, or element has no subelements")

          if element is None:
              print("element not found")

     在 Python 3.8 之前，元素的 XML 属性的序列化顺序会通过按其名称排序来
     强制使其可被预期。 由于现在字典已保证是有序的，这个强制重排序在
     Python 3.8 中已被移除以保留原本由用户代码解析或创建的属性顺序。

     通常，用户代码应当尽量不依赖于特定的属性顺序，因为 XML 信息设定(1)
     明确地排除了用属性顺序转递信息的做法。 代码应当准备好处理任何输入顺
     序。 对于要求确定性的 XML 输出的情况，例如加密签名或检测数据集等，
     可以通过使用 *note canonicalize(): 2a25. 函数来进行传统的序列化。

     对于规范化输出不可用但仍然要求输出特定属性顺序的情况，代码应当设法
     直接按要求的顺序来创建属性，以避免代码阅读者产生不匹配的感觉。 如果
     这一点是难以做到的，可以在序列化之前应用以下写法来强制实现顺序不依
     赖于元素的创建:

          def reorder_attributes(root):
              for el in root.iter():
                  attrib = el.attrib
                  if len(attrib) > 1:
                      # adjust attribute order, e.g. by sorting
                      attribs = sorted(attrib.items())
                      attrib.clear()
                      attrib.update(attribs)

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/xml-infoset/


File: python.info,  Node: ElementTree 对象,  Next: QName 对象,  Prev: 元素对象,  Up: 参考<3>

5.20.5.20 ElementTree 对象
..........................

 -- 类: xml.etree.ElementTree.ElementTree (element=None, file=None)

     ElementTree 包装器类。 这个类表示一个完整的元素层级结构，并添加了一
     些对于标准 XML 序列化的额外支持。

     `element' 是根元素。 如果给出 XML `file' 则将使用其内容来初始化树结
     构。

      -- 方法: _setroot (element)

          替换该树结构的根元素。 这将丢弃该树结构的当前内容，并将其替换
          为给定的元素。 请小心使用。 `element' 是一个元素实例。

      -- 方法: find (match, namespaces=None)

          与 *note Element.find(): 2a14. 类似，从树的根节点开始。

      -- 方法: findall (match, namespaces=None)

          与 *note Element.findall(): 2a13. 类似，从树的根节点开始。

      -- 方法: findtext (match, default=None, namespaces=None)

          与 *note Element.findtext(): 2a3d. 类似，从树的根节点开始。

      -- 方法: getiterator (tag=None)

          Deprecated since version 3.2, will be removed in version 3.9:
          Use method *note ElementTree.iter(): 2a49. instead.

      -- 方法: getroot ()

          返回这个树的根元素。

      -- 方法: iter (tag=None)

          创建并返回根元素的树结构迭代器。 该迭代器会以节顺序遍历这个树
          的所有元素。 `tag' 是要查找的标记（默认返回所有元素）。

      -- 方法: iterfind (match, namespaces=None)

          与 *note Element.iterfind(): b5a. 类似，从树的根节点开始。

          3.2 新版功能.

      -- 方法: parse (source, parser=None)

          将一个外部 XML 节载入到此元素树。 `source' 是一个文件名或
          *note file object: b4a.。 `parser' 是可选的解析器实例。 如果未
          给出，则会使用标准的 *note XMLParser: 253. 解析器。 返回该节的
          根元素。

      -- 方法: write (file, encoding="us-ascii", xml_declaration=None,
               default_namespace=None, method="xml", *,
               short_empty_elements=True)

          将元素树以 XML 格式写入到文件。 `file' 为文件名，或是以写入模
          式打开的 *note file object: b4a.。 `encoding' (1) 为输出编码格
          式 (默认为 US-ASCII)。 `xml_declaration' 控制是否要将 XML 声明
          添加到文件中。 使用 ‘False’ 表示从不添加，‘True’ 表示总是添加
          ，‘None’ 表示仅在非 US-ASCII 或 UTF-8 或 Unicode 时添加 (默认
          为 ‘None’)。 `default_namespace' 设置默认 XML 命名空间 (用于
          "xmlns")。 `method' 为 ‘"xml"’, ‘"html"’ 或 ‘"text"’ (默认为
          ‘"xml"’)。 仅限关键字形参 `short_empty_elements' 控制不包含内
          容的元素的格式。 如为 ‘True’ (默认值)，它们会被输出为单个自结
          束标记，否则它们会被输出为一对开始/结束标记。

          输出是一个字符串 (*note str: 339.) 或字节串 (*note bytes:
          33a.)。 由*encoding* 参数来控制。 如果 `encoding' 为
          ‘"unicode"’，则输出是一个字符串；否则为字节串；请注意这可能与
          `file' 的类型相冲突，如果它是一个打开的 *note file object:
          b4a. 的话；请确保你不会试图写入字符串到二进制流或者反向操作。

          3.4 新版功能: `short_empty_elements' 形参。

          在 3.8 版更改: *note write(): 920. 方法现在会保留用户指定的属
          性顺序。

这是将要被操作的 XML 文件:

     <html>
         <head>
             <title>Example page</title>
         </head>
         <body>
             <p>Moved to <a href="http://example.org/">example.org</a>
             or <a href="http://example.com/">example.com</a>.</p>
         </body>
     </html>

修改第一段中的每个链接的 "target" 属性的示例:

     >>> from xml.etree.ElementTree import ElementTree
     >>> tree = ElementTree()
     >>> tree.parse("index.xhtml")
     <Element 'html' at 0xb77e6fac>
     >>> p = tree.find("body/p")     # Finds first occurrence of tag p in body
     >>> p
     <Element 'p' at 0xb77ec26c>
     >>> links = list(p.iter("a"))   # Returns list of all links
     >>> links
     [<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]
     >>> for i in links:             # Iterates through all found links
     ...     i.attrib["target"] = "blank"
     >>> tree.write("output.xhtml")

   ---------- Footnotes ----------

   (1) (1) 包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如
"UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅
‘https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl’ 和
‘https://www.iana.org/assignments/character-sets/character-sets.xhtml’。


File: python.info,  Node: QName 对象,  Next: TreeBuilder 对象,  Prev: ElementTree 对象,  Up: 参考<3>

5.20.5.21 QName 对象
....................

 -- 类: xml.etree.ElementTree.QName (text_or_uri, tag=None)

     QName 包装器。 这可被用来包装 QName 属性值，以便在输出中获得适当的
     命名空间处理。 `text_or_uri' 是一个包含 QName 值的字符串，其形式为
     {uri}local，或者如果给出了 tag 参数，则为 QName 的 URI 部分。 如果
     给出了 `tag'，则第一个参数会被解读为 URI，而这个参数会被解读为本地
     名称。 *note QName: 2a4f. 实例是不透明的。


File: python.info,  Node: TreeBuilder 对象,  Next: XMLParser对象,  Prev: QName 对象,  Up: 参考<3>

5.20.5.22 TreeBuilder 对象
..........................

 -- 类: xml.etree.ElementTree.TreeBuilder (element_factory=None, *,
          comment_factory=None, pi_factory=None, insert_comments=False,
          insert_pis=False)

     通用元素结构构建器。 此构建器会将包含 start, data, end, comment 和
     pi 方法调用的序列转换为格式良好的元素结构。 你可以通过这个类使用一
     个自定义 XML 解析器或其他 XML 类格式的解析器来构建元素结构。

     如果给出 `element_factory'，它必须为接受两个位置参数的可调用对象：
     一个标记和一个属性字典。 它预期会返回一个新的元素实例。

     如果给出 `comment_factory' 和 `pi_factory' 函数，它们的行为应当像
     *note Comment(): 2a26. 和 *note ProcessingInstruction(): 2a2b. 函数
     一样创建注释和处理指令。 如果未给出，则将使用默认工厂函数。 当
     `insert_comments' 和/或 `insert_pis' 为真值时，如果 comments/pis 在
     根元素之中（但不在其之外）出现则它们将被插入到树中。

      -- 方法: close ()

          刷新构建器缓存，并返回最高层级的文档元素。 返回一个 *note
          Element: acc. 实例。

      -- 方法: data (data)

          将文本添加到当前元素。 `data' 为要添加的文本。 这应当是一个字
          节串或 Unicode 字符串。

      -- 方法: end (tag)

          结束当前元素。 `tag' 是元素名称。 返回已结束的元素。

      -- 方法: start (tag, attrs)

          打开一个新元素。 `tag' 是元素名称。 `attrs' 是包含元素属性的字
          典。 返回打开的元素。

      -- 方法: comment (text)

          使用给定的 `text' 创建一条注释。 如果 ‘insert_comments’ 为真值
          ，这还会将其添加到树结构中。

          3.8 新版功能.

      -- 方法: pi (target, text)

          使用给定的 `target' 名称和 `text' 创建一条注释。 如果
          ‘insert_pis’ 为真值，这还会将其添加到树结构中。

          3.8 新版功能.

     此外，自定义的 *note TreeBuilder: 254. 对象还提供了以下方法:

      -- 方法: doctype (name, pubid, system)

          处理一条 doctype 声明。 `name' 为 doctype 名称。 `pubid' 为公
          有标识。 `system' 为系统标识。 此方法不存在于默认的 *note
          TreeBuilder: 254. 类中。

          3.2 新版功能.

      -- 方法: start_ns (prefix, uri)

          在定义了 ‘start()’ 回调的打开元素的该回调被调用之前，当解析器
          遇到新的命名空间声明时都会被调用。 `prefix' 对于默认命名空间为
          ‘''’ 或者在其他情况下为被声明的命名空间前缀名称。 `uri' 是命名
          空间 URI。

          3.8 新版功能.

      -- 方法: end_ns (prefix)

          在声明了命名空间前缀映射的元素的 ‘end()’ 回调之后被调用，附带
          超出作用域的 `prefix' 的名称。

          3.8 新版功能.

 -- 类: xml.etree.ElementTree.C14NWriterTarget (write, *,
          with_comments=False, strip_text=False, rewrite_prefixes=False,
          qname_aware_tags=None, qname_aware_attrs=None,
          exclude_attrs=None, exclude_tags=None)

     C14N 2.0(1) 写入器。 其参数与 *note canonicalize(): 2a25. 函数的相
     同。 这个类并不会构建树结构而是使用 `write' 函数将回调事件直接转换
     为序列化形式。

     3.8 新版功能.

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/xml-c14n2/


File: python.info,  Node: XMLParser对象,  Next: XMLPullParser对象,  Prev: TreeBuilder 对象,  Up: 参考<3>

5.20.5.23 XMLParser对象
.......................

 -- 类: xml.etree.ElementTree.XMLParser (*, target=None, encoding=None)

     这个类是此模块的低层级构建单元。 它使用 *note xml.parsers.expat:
     139. 来实现高效、基于事件的 XML 解析。 它可以通过 *note feed():
     2a5c. 方法增量式地收受 XML 数据，并且解析事件会被转换为推送式 API
     —— 通过在 `target' 对象上发起对回调的调用。 如果省略 `target'，则会
     使用标准的 *note TreeBuilder: 254.。 如果给出了 `encoding' (1) ，该
     值将覆盖在 XML 文件中指定的编码格式。

     在 3.8 版更改: 所有形参现在都是 *note 仅限关键字形参: 2ad.。 `html'
     参数不再受支持。

      -- 方法: close ()

          结束向解析器提供数据。 返回调用在构造期间传入的 `target' 的
          ‘close()’ 方法的结果；在默认情况下，这是最高层级的文档元素。

      -- 方法: feed (data)

          将数据送入解析器。 `data' 是编码后的数据。

     *note XMLParser.feed(): 2a5c. 会为每个打开的标记调用 `target' 的
     ‘start(tag, attrs_dict)’ 方法，为每个关闭的标记调用它的 ‘end(tag)’
     方法，并通过 ‘data(data)’ 方法来处理数据。 有关更多受支持的回调方法
     ，请参阅 *note TreeBuilder: 254. 类。 *note XMLParser.close():
     2a5d. 会调用 `target' 的 ‘close()’ 方法。 *note XMLParser: 253. 不
     仅仅可被用来构建树结构。 下面是一个统计 XML 文件最大深度的示例:

          >>> from xml.etree.ElementTree import XMLParser
          >>> class MaxDepth:                     # The target object of the parser
          ...     maxDepth = 0
          ...     depth = 0
          ...     def start(self, tag, attrib):   # Called for each opening tag.
          ...         self.depth += 1
          ...         if self.depth > self.maxDepth:
          ...             self.maxDepth = self.depth
          ...     def end(self, tag):             # Called for each closing tag.
          ...         self.depth -= 1
          ...     def data(self, data):
          ...         pass            # We do not need to do anything with data.
          ...     def close(self):    # Called when all data has been parsed.
          ...         return self.maxDepth
          ...
          >>> target = MaxDepth()
          >>> parser = XMLParser(target=target)
          >>> exampleXml = """
          ... <a>
          ...   <b>
          ...   </b>
          ...   <b>
          ...     <c>
          ...       <d>
          ...       </d>
          ...     </c>
          ...   </b>
          ... </a>"""
          >>> parser.feed(exampleXml)
          >>> parser.close()
          4

   ---------- Footnotes ----------

   (1) (1) 包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如
"UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅
‘https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl’ 和
‘https://www.iana.org/assignments/character-sets/character-sets.xhtml’。


File: python.info,  Node: XMLPullParser对象,  Next: 异常<15>,  Prev: XMLParser对象,  Up: 参考<3>

5.20.5.24 XMLPullParser对象
...........................

 -- 类: xml.etree.ElementTree.XMLPullParser (events=None)

     适用于非阻塞应用程序的拉取式解析器。 它的输入侧 API 与 *note
     XMLParser: 253. 的类似，但不是向回调目标推送调用，*note
     XMLPullParser: 91b. 会收集一个解析事件的内部列表并让用户来读取它。
     `events' 是要报告的事件序列。 受支持的事件字符串有 ‘"start"’,
     ‘"end"’, ‘"comment"’, ‘"pi"’, ‘"start-ns"’ 和 ‘"end-ns"’ ("ns" 事件
     被用于获取详细的命名空间信息)。 如果 `events' 被省略，则只报告
     ‘"end"’ 事件。

      -- 方法: feed (data)

          将给定的字节数据送入解析器。

      -- 方法: close ()

          通知解析器数据流已终结。 不同于 *note XMLParser.close():
          2a5d.，此方法总是返回 *note None: 158.。 当解析器被关闭时任何
          还未被获取的事件仍可通过 *note read_events(): 2a11. 被读取。

      -- 方法: read_events ()

          返回包含在送入解析器的数据中遇到的事件的迭代器。 此迭代器会产
          生 ‘(event, elem)’ 对，其中 `event' 是代表事件类型的字符串 (例
          如 ‘"end"’) 而 `elem' 是遇到的 *note Element: acc. 对象，或者
          以下的其他上下文值。

             * ‘start’, ‘end’: 当前元素。

             * ‘comment’, ‘pi’: 当前注释 / 处理指令

             * ‘start-ns’: 一个指定所声明命名空间映射的元组 ‘(prefix,
               uri)’。

             * ‘end-ns’: *note None: 158. (这可能在未来版本中改变)

          在之前对 *note read_events(): 2a11. 的调用中提供的事件将不会被
          再次产生。 事件仅当它们从迭代器中被取出时才会在内部队列中被消
          费，因此多个读取方对获取自 *note read_events(): 2a11. 的迭代器
          进行平行迭代将产生无法预料的结果。

          注解: *note XMLPullParser: 91b. 只会确保当发出 "start" 事件时
          看到了开始标记的 ">" 字符，因而在这个点上属性已被定义，但文本
          内容和末尾属性还未被定义。 这同样适用于元素的下级；它们可能存
          在也可能不存在。

          如果你需要已完全填充的元素，请改为查找 "end" 事件。

     3.4 新版功能.

     在 3.8 版更改: 增加了 ‘comment’ 和 ‘pi’ 事件。


File: python.info,  Node: 异常<15>,  Prev: XMLPullParser对象,  Up: 参考<3>

5.20.5.25 异常
..............

 -- 类: xml.etree.ElementTree.ParseError

     XML 解析器错误，由此模块中的多个解析方法在解析失败时引发。 此异常的
     实例的字符串表示将包含用户友好的错误消息。 此外，它将具有下列可用属
     性:

      -- 属性: code

          来自外部解析器的数字错误代码。 请参阅 *note xml.parsers.expat:
          139. 的文档查看错误代码列表及它们的含义。

      -- 属性: position

          一个包含 `line', `column' 数值的元组，指明错误发生的位置。

备注
....


File: python.info,  Node: xml dom --- 文档对象模型 API,  Next: xml dom minidom --- 最小化的 DOM 实现,  Prev: xml etree ElementTree --- ElementTree XML API,  Up: 结构化标记处理工具

5.20.6 ‘xml.dom’ — 文档对象模型 API
-----------------------------------

`源代码:' Lib/xml/dom/__init__.py(1)

__________________________________________________________________

文档对象模型“DOM”是一个来自万维网联盟（W3C）的跨语言 API，用于访问和修改
XML 文档。 DOM 的实现将 XML 文档以树结构表示，或者允许客户端代码从头构建
这样的结构。 然后它会通过一组提供通用接口的对象赋予对结构的访问权。

DOM 特别适用于进行随机访问的应用。 SAX 仅允许你每次查看文档的一小部分。
如果你正在查看一个 SAX 元素，你将不能访问其他元素。 如果你正在查看一个文
本节点，你将不能访问包含它的元素。 当你编写一个 SAX 应用时，你需要在你自
己的代码的某个地方记住你的程序在文档中的位置。 SAX 不会帮你做这件事。 并
且，如果你想要在 XML 文档中向前查看，你是绝对办不到的。

有些应用程序在不能访问树的事件驱动模型中是根本无法编写的。 当然你可以在
SAX 事件中自行构建某种树，但是 DOM 可以使你避免编写这样的代码。 DOM 是针
对 XML 数据的标准树表示形式。

文档对象模型是由 W3C 分阶段定义的，在其术语中称为“层级”。 Python 中该
API 的映射大致是基于 DOM 第 2 层级的建议。

DOM 应用程序通常从将某些 XML 解析为 DOM 开始。 此操作如何实现完全未被
DOM 第 1 层级所涉及，而第 2 层级也只提供了有限的改进：有一个
‘DOMImplementation’ 对象类，它提供对 ‘Document’ 创建方法的访问，但却没有
办法以不依赖具体实现的方式访问 XML 读取器/解析器/文档创建器。 也没有当不
存在 ‘Document’ 对象的情况下访问这些方法的定义良好的方式。 在 Python 中
，每个 DOM 实现将提供一个函数 *note getDOMImplementation(): 2a66.。 DOM
第 3 层级增加了一个载入/存储规格说明，它定义了与读取器的接口，但这在
Python 标准库中尚不可用。

一旦你得到了 DOM 文档对象，你就可以通过 XML 文档的属性和方法访问它的各个
部分。 这些属性定义在 DOM 规格说明当中；参考指南的这一部分描述了 Python
对此规格说明的解读。

W3C 提供的规格说明定义了适用于 Java, ECMAScript 和 OMG IDL 的 DOM API。
这里定义的 Python 映射很大程度上是基于此规格说明的 IDL 版本，但并不要求
严格映射（但具体实现可以自由地支持对 IDL 的严格映射）。 请参阅 *note
一致性: 2a67. 一节查看有关映射要求的详细讨论。

参见
....

文档对象模型 (DOM) 第 2 层级规格说明(2)

     被 Python DOM API 作为基础的 W3C 建议。

文档对象模型 (DOM) 第 1 层级规格说明(3)

     被 *note xml.dom.minidom: 136. 所支持的 W3C 针对 DOM 的建议。

Python 语言映射规格说明(4)

     此文档指明了从 OMG IDL 到 Python 的映射。

* Menu:

* 模块内容: 模块内容<6>.
* DOM 中的对象::
* 一致性::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/xml/dom/__init__.py

   (2) https://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/

   (3) https://www.w3.org/TR/REC-DOM-Level-1/

   (4) http://www.omg.org/cgi-bin/doc?formal/02-11-05.pdf


File: python.info,  Node: 模块内容<6>,  Next: DOM 中的对象,  Up: xml dom --- 文档对象模型 API

5.20.6.1 模块内容
.................

*note xml.dom: 135. 包含下列函数:

 -- 函数: xml.dom.registerDOMImplementation (name, factory)

     注册 `factory' 函数并使用名称 `name'。 该工厂函数应当返回一个实现了
     ‘DOMImplementation’ 接口的对象。 该工厂函数可每次都返回相同对象，或
     每次调用都返回新的对象，视具体实现的要求而定（例如该实现是否支持某
     些定制功能）。

 -- 函数: xml.dom.getDOMImplementation (name=None, features=())

     返回一个适当的 DOM 实现。 `name' 是通用名称、DOM 实现的模块名称或者
     ‘None’。 如果它不为 ‘None’，则会导入相应模块并在导入成功时返回一个
     ‘DOMImplementation’ 对象。 如果没有给出名称，并且如果设置了
     ‘PYTHON_DOM’ 环境变量，此变量会被用来查找相应的实现。

     如果未给出 name，此函数会检查可用的实现来查找具有所需特性集的一个。
     如果找不到任何实现，则会引发 *note ImportError: 33d.。 features 集
     必须是包含 ‘(feature, version)’ 对的序列，它会被传给可用的
     ‘DOMImplementation’ 对象上的 ‘hasFeature()’ 方法。

还提供了一些便捷常量:

 -- 数据: xml.dom.EMPTY_NAMESPACE

     该值用于指明没有命名空间被关联到 DOM 中的某个节点。 它通常被作为某
     个节点的 ‘namespaceURI’，或者被用作某个命名空间专属方法的
     `namespaceURI' 参数。

 -- 数据: xml.dom.XML_NAMESPACE

     关联到保留前缀 ‘xml’ 的命名空间 URI，如 XML 中的命名空间(1) （第 4
     节） 所定义的。

 -- 数据: xml.dom.XMLNS_NAMESPACE

     命名空间声明的命名空间 URI，如 文档对象模型 (DOM) 第 2 层级核心规格
     说明(2) (第 1.1.8节) 所定义的。

 -- 数据: xml.dom.XHTML_NAMESPACE

     XHTML 命名空间的 URI，如 XHTML 1.0: 扩展超文本标记语言(3) (第 3.1.1
     节) 所定义的。

此外，*note xml.dom: 135. 还包含一个基本 ‘Node’ 类和一些 DOM 异常类。 此
模块提供的 ‘Node’ 类未实现 DOM 规格描述所定义的任何方法和属性；实际的
DOM 实现必须提供它们。 提供 ‘Node’ 类作为此模块的一部分并没有提供用于实
际的 ‘Node’ 对象的 ‘nodeType’ 属性的常量；它们是位于类内而不是位于模块层
级以符合 DOM 规格描述。

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/REC-xml-names/

   (2) https://www.w3.org/TR/DOM-Level-2-Core/core.html

   (3) https://www.w3.org/TR/xhtml1/


File: python.info,  Node: DOM 中的对象,  Next: 一致性,  Prev: 模块内容<6>,  Up: xml dom --- 文档对象模型 API

5.20.6.2 DOM 中的对象
.....................

DOM的权威文档是来自W3C的DOM规范。

请注意，DOM属性也可以作为节点而不是简单的字符串进行操作。然而，必须这样
做的情况相当少见，所以这种用法还没有记录下来。

接口                                 部件                                    目的
                                                                             
-------------------------------------------------------------------------------------------------------------------
                                                                             
‘DOMImplementation’                  *note DOMImplementation 对象: 2a70.     底层实现的接口。
                                                                             
                                                                             
‘Node’                               *note 节点对象: 2a71.                   文档中大多数对象的基本接口。
                                                                             
                                                                             
‘NodeList’                           *note 节点列表对象: 2a72.               节点序列的接口。
                                                                             
                                                                             
‘DocumentType’                       *note 文档类型对象: 2a73.               有关处理文档所需声明的信息。
                                                                             
                                                                             
‘Document’                           *note 文档对象: 2a74.                   表示整个文档的对象。
                                                                             
                                                                             
‘Element’                            *note 元素对象: 2a75.                   文档层次结构中的元素节点。
                                                                             
                                                                             
‘Attr’                               *note Attr 对象: 2a76.                  元素节点上的属性值节点。
                                                                             
                                                                             
‘Comment’                            *note 注释对象: 2a77.                   源文档中注释的表示形式。
                                                                             
                                                                             
‘Text’                               *note Text 和 CDATASection 对象: 2a78.  包含文档中文本内容的节点。
                                                                             
                                                                             
‘ProcessingInstruction’              *note ProcessingInstruction 对象: 2a79. 处理指令表示形式。
                                                                             

另一节描述了在Python中使用DOM定义的异常。

* Menu:

* DOMImplementation 对象::
* 节点对象::
* 节点列表对象::
* 文档类型对象::
* 文档对象::
* 元素对象: 元素对象<2>.
* Attr 对象::
* NamedNodeMap 对象::
* 注释对象::
* Text 和 CDATASection 对象::
* ProcessingInstruction 对象::
* 异常: 异常<16>.


File: python.info,  Node: DOMImplementation 对象,  Next: 节点对象,  Up: DOM 中的对象

5.20.6.3 DOMImplementation 对象
...............................

‘DOMImplementation’ 接口提供了一种让应用程序确定他们所使用的 DOM 中某一
特性可用性的方式。 DOM 第 2 级还添加了使用 ‘DOMImplementation’ 来创建新
的 ‘Document’ 和 ‘DocumentType’ 对象的能力。

 -- 方法: DOMImplementation.hasFeature (feature, version)

     如果字符串对 `feature' 和 `version' 所标识的特性已被实现则返回
     ‘True’。

 -- 方法: DOMImplementation.createDocument (namespaceUri, qualifiedName,
          doctype)

     返回一个新的 ‘Document’ 对象 (DOM 的根节点)，包含一个具有给定
     `namespaceUri' 和 `qualifiedName' 的下级 ‘Element’ 对象。 `doctype'
     必须为由 *note createDocumentType(): 2a7d. 创建的 ‘DocumentType’ 对
     象，或者为 ‘None’。 在 Python DOM API 中，前两个参数也可为 ‘None’ 以
     表示不要创建任何下级 ‘Element’。

 -- 方法: DOMImplementation.createDocumentType (qualifiedName, publicId,
          systemId)

     返回一个新的封装了给定 `qualifiedName', `publicId' 和 `systemId' 字
     符串的 ‘DocumentType’ 对象，它表示包含在 XML 文档类型声明中的信息。


File: python.info,  Node: 节点对象,  Next: 节点列表对象,  Prev: DOMImplementation 对象,  Up: DOM 中的对象

5.20.6.4 节点对象
.................

XML 文档的所有组成部分都是 ‘Node’ 的子类。

 -- 属性: Node.nodeType

     一个代表节点类型的整数。 类型符号常量在 ‘Node’ 对象上:
     ‘ELEMENT_NODE’, ‘ATTRIBUTE_NODE’, ‘TEXT_NODE’,
     ‘CDATA_SECTION_NODE’, ‘ENTITY_NODE’, ‘PROCESSING_INSTRUCTION_NODE’,
     ‘COMMENT_NODE’, ‘DOCUMENT_NODE’, ‘DOCUMENT_TYPE_NODE’,
     ‘NOTATION_NODE’。 这是个只读属性。

 -- 属性: Node.parentNode

     当前节点的上级，或者对于文档节点则为 ‘None’。 该值总是一个 ‘Node’ 对
     象或者 ‘None’。 对于 ‘Element’ 节点，这将为上级元素，但对于根元素例
     外，在此情况下它将为 ‘Document’ 对象。 对于 ‘Attr’ 节点，它将总是为
     ‘None’。 这是个只读属性。

 -- 属性: Node.attributes

     属性对象的 ‘NamedNodeMap’。 这仅对元素才有实际值；其它对象会为该属
     性提供 ‘None’ 值。 这是个只读属性。

 -- 属性: Node.previousSibling

     在此节点之前具有相同上级的相邻节点。 例如结束标记紧接在在 `self' 元
     素的开始标记之前的元素。 当然，XML 文档并非只是由元素组成，因此之前
     相邻节点可以是文本、注释或者其他内容。 如果此节点是上级的第一个子节
     点，则该属性将为 ‘None’。 这是一个只读属性。

 -- 属性: Node.nextSibling

     在此节点之后具有相同上级的相邻节点。 另请参见 *note
     previousSibling: 2a82.。 如果此节点是上级的最后一个子节点，则该属性
     将为 ‘None’。 这是一个只读属性。

 -- 属性: Node.childNodes

     包含在此节点中的节点列表。 这是一个只读属性。

 -- 属性: Node.firstChild

     节点的第一个下级，如果有的话，否则为 ‘None’。 这是个只读属性。

 -- 属性: Node.lastChild

     节点的最后一个下级，如果有的话，否则为 ‘None’。 这是个只读属性。

 -- 属性: Node.localName

     ‘tagName’ 在冒号之后的部分，如果有的话，否则为整个 ‘tagName’。 该值
     为一个字符串。

 -- 属性: Node.prefix

     ‘tagName’ 在冒号之前的部分，如果有冒号的话，否则为空字符串。 该值为
     一个字符串或者为 ‘None’。

 -- 属性: Node.namespaceURI

     关联到元素名称的命名空间。 这将是一个字符串或为 ‘None’。 这是个只读
     属性。

 -- 属性: Node.nodeName

     这对于每种节点类型具有不同的含义；请查看 DOM 规格说明来了解详情。 你
     总是可以从其他特征属性例如元素的 ‘tagName’ 特征属性或属性的 ‘name’
     特征属性获取你能从这里获取的信息。 对于所有节点类型，这个属性的值都
     将是一个字符串或为 ‘None’。 这是一个只读属性。

 -- 属性: Node.nodeValue

     这对于每种节点类型具有不同的含义；请查看 DOM 规格说明来了解详情。 具
     体情况与 *note nodeName: 2a8a. 的类似。 该值是一个字符串或为
     ‘None’。

 -- 方法: Node.hasAttributes ()

     如果该节点具有任何属性则返回 ‘True’。

 -- 方法: Node.hasChildNodes ()

     如果该节点具有任何子节点则返回 ‘True’。

 -- 方法: Node.isSameNode (other)

     如果 `other' 指向的节点就是此节点则返回 ‘True’。 这对于使用了任何代
     理架构的 DOM 实现来说特别有用（因为多个对象可能指向相同节点）。

          注解: 这是基于已提议的 DOM 第 3 等级 API，目前尚处于“起草”阶段
          ，但这个特定接口看来并不存在争议。 来自 W3C 的修改将不会影响
          Python DOM 接口中的这个方法（不过针对它的任何新 W3C API 也将受
          到支持）。

 -- 方法: Node.appendChild (newChild)

     在子节点列表末尾添加一个新的子节点，返回 `newChild'。 如果节点已存
     在于树结构中，它将先被移除。

 -- 方法: Node.insertBefore (newChild, refChild)

     在现有的子节点之前插入一个新的子节点。 它必须属于 `refChild' 是这个
     节点的子节点的情况；如果不是，则会引发 *note ValueError: 1fc.。
     `newChild' 会被返回。 如果 `refChild' 为 ‘None’，它会将 `newChild'
     插入到子节点列表的末尾。

 -- 方法: Node.removeChild (oldChild)

     移除一个子节点。 `oldChild' 必须是这个节点的子节点；如果不是，则会
     引发 *note ValueError: 1fc.。 成功时 `oldChild' 会被返回。 如果
     `oldChild' 将不再被继续使用，则将调用它的 ‘unlink()’ 方法。

 -- 方法: Node.replaceChild (newChild, oldChild)

     将一个现有节点替换为新的节点。 这必须属于 `oldChild' 是该节点的子节
     点的情况；如果不是，则会引发 *note ValueError: 1fc.。

 -- 方法: Node.normalize ()

     合并相邻的文本节点以便将所有文本段存储为单个 ‘Text’ 实例。 这可以简
     化许多应用程序处理来自 DOM 树文本的操作。

 -- 方法: Node.cloneNode (deep)

     克隆此节点。 设置 `deep' 表示也克隆所有子节点。 此方法将返回克隆的
     节点。


File: python.info,  Node: 节点列表对象,  Next: 文档类型对象,  Prev: 节点对象,  Up: DOM 中的对象

5.20.6.5 节点列表对象
.....................

‘NodeList’ 代表一个节点列表。 在 DOM 核心建议中这些对象有两种使用方式: 由
‘Element’ 对象提供作为其子节点列表，以及由 ‘Node’ 的
‘getElementsByTagName()’ 和 ‘getElementsByTagNameNS()’ 方法通过此接口返
回对象来表示查询结果。

DOM 第 2 层级建议为这些对象定义一个方法和一个属性:

 -- 方法: NodeList.item (i)

     从序列中返回第 `i' 项，如果序列不为空的话，否则返回 ‘None’。 索引号
     `i' 不允许小于零或大于等于序列的长度。

 -- 属性: NodeList.length

     序列中的节点数量。

此外，Python DOM 接口还要求提供一些额外支持来允许将 ‘NodeList’ 对象用作
Python 序列。 所有 ‘NodeList’ 实现都必须包括对 *note __len__(): dd3. 和
*note __getitem__(): 280. 的支持；这样 ‘NodeList’ 就允许使用 *note for:
c38. 语句进行迭代并能正确地支持 *note len(): 151. 内置函数。

如果一个 DOM 实现支持文档的修改，则 ‘NodeList’ 实现还必须支持 *note
__setitem__(): c6a. 和 *note __delitem__(): c6b. 方法。


File: python.info,  Node: 文档类型对象,  Next: 文档对象,  Prev: 节点列表对象,  Up: DOM 中的对象

5.20.6.6 文档类型对象
.....................

有关一个文档所声明的标注和实体的信息（包括解析器所使用并能提供信息的外部
子集）可以从 ‘DocumentType’ 对象获取。 文档的 ‘DocumentType’ 可从
‘Document’ 对象的 ‘doctype’ 属性中获取；如果一个文档没有 ‘DOCTYPE’ 声明
，则该文档的 ‘doctype’ 属性将被设为 ‘None’ 而非此接口的一个实例。

‘DocumentType’ 是 ‘Node’ 是专门化，并增加了下列属性:

 -- 属性: DocumentType.publicId

     文档类型定义的外部子集的公有标识。 这将为一个字符串或者为 ‘None’。

 -- 属性: DocumentType.systemId

     文档类型定义的外部子集的系统标识。 这将为一个字符串形式的 URI，或者
     为 ‘None’。

 -- 属性: DocumentType.internalSubset

     一个给出来自文档的完整内部子集的字符串。 这不包括子集外面的圆括号。
     如果文档没有内部子集，则应为 ‘None’。

 -- 属性: DocumentType.name

     ‘DOCTYPE’ 声明中给出的根元素名称，如果有的话。

 -- 属性: DocumentType.entities

     这是给出外部实体定义的 ‘NamedNodeMap’。 对于多次定义的实体名称，则
     只提供第一次的定义（其他的会按照 XML 建议被忽略）。 这可能为
     ‘None’，如果解析器未提供此信息，或者如果未定义任何实体的话。

 -- 属性: DocumentType.notations

     这是给出标注定义的 ‘NamedNodeMap’。 对于多次定义的标注，则只提供第
     一次的定义（其他的会按照 XML 建议被忽略）。 这可能为 ‘None’，如果解
     析器未提供此信息，或者如果未定义任何注释的话。


File: python.info,  Node: 文档对象,  Next: 元素对象<2>,  Prev: 文档类型对象,  Up: DOM 中的对象

5.20.6.7 文档对象
.................

‘Document’ 代表一个完整的 XML 文档，包括其组成元素、属性、处理指令和注释
等。 请记住它会继承来自 ‘Node’ 的属性。

 -- 属性: Document.documentElement

     文档唯一的根元素。

 -- 方法: Document.createElement (tagName)

     创建并返回一个新的元素节点。 当元素被创建时不会被插入到文档中。 你
     需要通过某个其他方法例如 ‘insertBefore()’ 或 ‘appendChild()’ 来显示
     地插入它。

 -- 方法: Document.createElementNS (namespaceURI, tagName)

     创建并返回一个新的带有命名空间的元素。 `tagName' 可以带有前缀。 当
     元素被创建时不会被插入到文档中。 你需要通过某个其他方法例如
     ‘insertBefore()’ 或 ‘appendChild()’ 来显式地插入它。

 -- 方法: Document.createTextNode (data)

     创建并返回一个包含作为形参被传入的数据的文本节点。 与其他创建方法一
     样，此方法不会将节点插入到树中。

 -- 方法: Document.createComment (data)

     创建并返回一个作为形参被传入的数据的注释节点。 与其他创建方法一样，
     此方法不会将节点插入到树中。

 -- 方法: Document.createProcessingInstruction (target, data)

     创建并返回一个包含作为形参被传入的 `target' 和 `data' 的处理指令节
     点。 与其他创建方法一样，此方法不会将节点插入到树中。

 -- 方法: Document.createAttribute (name)

     创建并返回一个属性节点。 此方法不会将属性关联到任何特定的元素。 你
     必须在正确的 ‘Element’ 对象上使用 ‘setAttributeNode()’ 来使用新创建
     的属性实例。

 -- 方法: Document.createAttributeNS (namespaceURI, qualifiedName)

     创建并返回一个带有命名空间的属性节点。 `tagName' 可以带有前缀。 此
     方法不会将属性节点关联到任何特定的元素。 你必须在正确的 ‘Element’ 对
     象上使用 ‘setAttributeNode()’ 来使用新创建的属性实例。

 -- 方法: Document.getElementsByTagName (tagName)

     搜索全部具有特定元素类型名称的后继元素（直接下级、下级的下级等等）
     。

 -- 方法: Document.getElementsByTagNameNS (namespaceURI, localName)

     搜索全部具有特定命名空间 URI 和 localname 的后继元素（直接下级、下
     级的下级等等）。 localname 是命名空间在前缀之后的部分。


File: python.info,  Node: 元素对象<2>,  Next: Attr 对象,  Prev: 文档对象,  Up: DOM 中的对象

5.20.6.8 元素对象
.................

‘Element’ 是 ‘Node’ 的子类，因此会继承该类的全部属性。

 -- 属性: Element.tagName

     元素类型名称。 在使用命名空间的文档中它可能包含冒号。 该值是一个字
     符串。

 -- 方法: Element.getElementsByTagName (tagName)

     与 ‘Document’ 类中的对应方法相同。

 -- 方法: Element.getElementsByTagNameNS (namespaceURI, localName)

     与 ‘Document’ 类中的对应方法相同。

 -- 方法: Element.hasAttribute (name)

     如果元素带有名称为 `name' 的属性则返回 ‘True’。

 -- 方法: Element.hasAttributeNS (namespaceURI, localName)

     如果元素带有名称为 `namespaceURI' 和 `localName' 的属性则返回
     ‘True’。

 -- 方法: Element.getAttribute (name)

     将名称为 `name' 的属性的值作为字符串返回。 如果指定属性不存在，则返
     回空字符串，就像该属性没有对应的值一样。

 -- 方法: Element.getAttributeNode (attrname)

     返回名称为 `attrname' 的属性对应的 ‘Attr’ 节点。

 -- 方法: Element.getAttributeNS (namespaceURI, localName)

     将名称为 `namespaceURI' 加 `localName' 的属性的值作为字符串返回。 如
     果指定属性不存在，则返回空字符串，就像该属性没有对应的值一样。

 -- 方法: Element.getAttributeNodeNS (namespaceURI, localName)

     将给定 `namespaceURI' 加 `localName' 的属性的值作为节点返回。

 -- 方法: Element.removeAttribute (name)

     移除指定名称的节点。 如果没有匹配的属性，则会引发 *note
     NotFoundErr: 2ab5.。

 -- 方法: Element.removeAttributeNode (oldAttr)

     从属性列表中移除并返回 `oldAttr'，如果该属性存在的话。 如果
     `oldAttr' 不存在，则会引发 *note NotFoundErr: 2ab5.。

 -- 方法: Element.removeAttributeNS (namespaceURI, localName)

     移除指定名称的属性。 请注意它是使用 localName 而不是 qname。 如果没
     有匹配的属性也不会引发异常。

 -- 方法: Element.setAttribute (name, value)

     将属性值设为指定的字符串。

 -- 方法: Element.setAttributeNode (newAttr)

     将一个新的属性节点添加到元素，当匹配到 ‘name’ 属性时如有必要会替换
     现有的属性。 如果发生了替换，将返回原有属性节点。 如果 `newAttr' 已
     经被使用，则会引发 *note InuseAttributeErr: 2aba.。

 -- 方法: Element.setAttributeNodeNS (newAttr)

     将一个新的属性节点添加到元素，当匹配到 ‘namespaceURI’ 和
     ‘localName’ 属性时如有必要会替换现有的属性。 如果发生了替换，将返回
     原有属性节点。 如果 `newAttr' 已经被使用，则会引发 *note
     InuseAttributeErr: 2aba.。

 -- 方法: Element.setAttributeNS (namespaceURI, qname, value)

     将属性值设为 `namespaceURI' 和 `qname' 所给出的字符串。 请注意
     qname 是整个属性名称。 这与上面的方法不同。


File: python.info,  Node: Attr 对象,  Next: NamedNodeMap 对象,  Prev: 元素对象<2>,  Up: DOM 中的对象

5.20.6.9 Attr 对象
..................

‘Attr’ 继承自 ‘Node’，因此会继承其全部属性。

 -- 属性: Attr.name

     属性名称。 在使用命名空间的文档中可能会包括冒号。

 -- 属性: Attr.localName

     名称在冒号之后的部分，如果有的话，否则为完整名称。 这是个只读属性。

 -- 属性: Attr.prefix

     名称在冒号之前的部分，如果有冒号的话，否则为空字符串。

 -- 属性: Attr.value

     属性的文本值。 这与 ‘nodeValue’ 属性同义。


File: python.info,  Node: NamedNodeMap 对象,  Next: 注释对象,  Prev: Attr 对象,  Up: DOM 中的对象

5.20.6.10 NamedNodeMap 对象
...........................

‘NamedNodeMap’ `不是' 继承自 ‘Node’。

 -- 属性: NamedNodeMap.length

     属性列表的长度。

 -- 方法: NamedNodeMap.item (index)

     返回特定带有索引号的属性。 获取属性的顺序是强制规定的，但在 DOM 的
     生命期内会保持一致。 其中每一项均为属性节点。 可使用 ‘value’ 属性获
     取其值。

还有一些试验性方法给予这个类更多的映射行为。 你可以使用这些方法或者使用
‘Element’ 对象上标准化的 ‘getAttribute*()’ 方法族。


File: python.info,  Node: 注释对象,  Next: Text 和 CDATASection 对象,  Prev: NamedNodeMap 对象,  Up: DOM 中的对象

5.20.6.11 注释对象
..................

‘Comment’ 代表 XML 文档中的注释。 它是 ‘Node’ 的子类，但不能拥有下级节点
。

 -- 属性: Comment.data

     注释的内容是一个字符串。 该属性包含在开头 ‘<!-’‘-’ 和末尾 ‘-’‘->’ 之
     间的所有字符，但不包括这两个符号。


File: python.info,  Node: Text 和 CDATASection 对象,  Next: ProcessingInstruction 对象,  Prev: 注释对象,  Up: DOM 中的对象

5.20.6.12 Text 和 CDATASection 对象
...................................

‘Text’ 接口代表 XML 文档中的文本。 如果解析器和 DOM 实现支持 DOM 的 XML
扩展，则包裹在 CDATA 标记的节中的部分会被存储到 ‘CDATASection’ 对象中。
这两个接口很相似，但是提供了不同的 ‘nodeType’ 属性值。

这些接口扩展了 ‘Node’ 接口。 它们不能拥有下级节点。

 -- 属性: Text.data

     字符串形式的文本节点内容。

     注解: ‘CDATASection’ 节点的使用并不表示该节点代表一个完整的 CDATA 标
     记节，只是表示该节点的内容是 CDATA 节的一部分。 单个 CDATA 节可以由
     文档树中的多个节点来表示。 没有什么办法能确定两个相邻的
     ‘CDATASection’ 节点是否代表不同的 CDATA 标记节。


File: python.info,  Node: ProcessingInstruction 对象,  Next: 异常<16>,  Prev: Text 和 CDATASection 对象,  Up: DOM 中的对象

5.20.6.13 ProcessingInstruction 对象
....................................

代表 XML 文档中的处理指令。 它继承自 ‘Node’ 接口并且不能拥有下级节点。

 -- 属性: ProcessingInstruction.target

     处理指令的内容至第一个空格符为止。 这是个只读属性。

 -- 属性: ProcessingInstruction.data

     在第一个空格符之后的处理指令内容。


File: python.info,  Node: 异常<16>,  Prev: ProcessingInstruction 对象,  Up: DOM 中的对象

5.20.6.14 异常
..............

DOM 第 2 层级推荐定义一个异常 *note DOMException: 2acf.，以及多个变量用
来允许应用程序确定发生了何种错误。 *note DOMException: 2acf. 实例带有
*note code: 1b. 属性用来提供特定异常的对应值。

Python DOM 接口提供了一些常量，但还扩展了异常集以使 DOM 所定义的每个异常
代码都存在特定的异常。 接口的具体实现必须引发正确的特定异常，它们各自带
有正确的 *note code: 1b. 属性值。

 -- 例外: xml.dom.DOMException

     所有特定 DOM 异常所使用的异常基类。 该异常类不可被直接实例化。

 -- 例外: xml.dom.DomstringSizeErr

     当指定范围的文本不能适配一个字符串时被引发。 此异常在 Python DOM 实
     现中尚不可用，但可从不是以 Python 编写的 DOM 实现中接收。

 -- 例外: xml.dom.HierarchyRequestErr

     当尝试插入一个节点但该节点类型不被允许时被引发。

 -- 例外: xml.dom.IndexSizeErr

     当一个方法的索引或大小参数为负值或超出允许的值范围时被引发。

 -- 例外: xml.dom.InuseAttributeErr

     当尝试插入一个 ‘Attr’ 节点但该节点已存在于文档中的某处时被引发。

 -- 例外: xml.dom.InvalidAccessErr

     当某个参数或操作在底层对象中不受支持时被引发。

 -- 例外: xml.dom.InvalidCharacterErr

     当某个字符串参数包含的字符在使用它的上下文中不被 XML 1.0 标准建议所
     允许时引发。 例如，尝试创建一个元素类型名称中带有空格的 ‘Element’ 节
     点将导致此错误被引发。

 -- 例外: xml.dom.InvalidModificationErr

     当尝试修改某个节点的类型时被引发。

 -- 例外: xml.dom.InvalidStateErr

     当尝试使用未定义或不再可用的的对象时被引发。

 -- 例外: xml.dom.NamespaceErr

     如果试图以 XML 中的命名空间(1) 建议所不允许的方式修改任何对象，则会
     引发此异常。

 -- 例外: xml.dom.NotFoundErr

     当某个节点不存在于被引用的上下文中时引发的异常。 例如，
     ‘NamedNodeMap.removeNamedItem()’ 将在所传入的节点不在于于映射中时引
     发此异常。

 -- 例外: xml.dom.NotSupportedErr

     当具体实现不支持所请求的对象类型或操作时被引发。

 -- 例外: xml.dom.NoDataAllowedErr

     当为某个不支持数据 的节点指定数据时被引发。

 -- 例外: xml.dom.NoModificationAllowedErr

     当尝试修改某个不允许修改的对象（例如只读节点）时被引发。

 -- 例外: xml.dom.SyntaxErr

     当指定了无效或非法的字符串时被引发。

 -- 例外: xml.dom.WrongDocumentErr

     当将某个节点插入非其当前所属的另一个文档，并且具体实现不支持从一个
     文档向一个文档迁移节点时被引发。

DOM 建议映射中针对上述异常而定义的异常代码如下表所示:

常数                                       异常
                                           
---------------------------------------------------------------------------------
                                           
‘DOMSTRING_SIZE_ERR’                       *note DomstringSizeErr: 2ad0.
                                           
                                           
‘HIERARCHY_REQUEST_ERR’                    *note HierarchyRequestErr: 2ad1.
                                           
                                           
‘INDEX_SIZE_ERR’                           *note IndexSizeErr: 2ad2.
                                           
                                           
‘INUSE_ATTRIBUTE_ERR’                      *note InuseAttributeErr: 2aba.
                                           
                                           
‘INVALID_ACCESS_ERR’                       *note InvalidAccessErr: 2ad3.
                                           
                                           
‘INVALID_CHARACTER_ERR’                    *note InvalidCharacterErr: 2ad4.
                                           
                                           
‘INVALID_MODIFICATION_ERR’                 *note InvalidModificationErr: 2ad5.
                                           
                                           
‘INVALID_STATE_ERR’                        *note InvalidStateErr: 2ad6.
                                           
                                           
‘NAMESPACE_ERR’                            *note NamespaceErr: 2ad7.
                                           
                                           
‘NOT_FOUND_ERR’                            *note NotFoundErr: 2ab5.
                                           
                                           
‘NOT_SUPPORTED_ERR’                        *note NotSupportedErr: 2ad8.
                                           
                                           
‘NO_DATA_ALLOWED_ERR’                      *note NoDataAllowedErr: 2ad9.
                                           
                                           
‘NO_MODIFICATION_ALLOWED_ERR’              *note NoModificationAllowedErr: 2ada.
                                           
                                           
‘SYNTAX_ERR’                               *note SyntaxErr: 2adb.
                                           
                                           
‘WRONG_DOCUMENT_ERR’                       *note WrongDocumentErr: 2adc.
                                           

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/REC-xml-names/


File: python.info,  Node: 一致性,  Prev: DOM 中的对象,  Up: xml dom --- 文档对象模型 API

5.20.6.15 一致性
................

本节描述了 Python DOM API、W3C DOM 建议以及 Python 的 OMG IDL 映射之间的
一致性要求和关系。

* Menu:

* 类型映射::
* 访问器方法::


File: python.info,  Node: 类型映射,  Next: 访问器方法,  Up: 一致性

5.20.6.16 类型映射
..................

将根据下表，将DOM规范中使用的IDL类型映射为Python类型。

IDL 类型               Python 类型
                       
-----------------------------------------------------------------------
                       
‘boolean’              ‘bool’ 或 ‘int’
                       
                       
‘int’                  ‘int’
                       
                       
‘long int’             ‘int’
                       
                       
‘unsigned int’         ‘int’
                       
                       
‘DOMString’            ‘str’ 或 ‘bytes’
                       
                       
‘null’                 ‘None’
                       


File: python.info,  Node: 访问器方法,  Prev: 类型映射,  Up: 一致性

5.20.6.17 访问器方法
....................

从 OMG IDL 到 Python 的映射以类似于 Java 映射的方式定义了针对 IDL
‘attribute’ 声明的访问器函数。 映射以下 IDL 声明

     readonly attribute string someValue;
              attribute string anotherValue;

会产生三个访问器函数: ‘someValue’ 的 "get" 方法 (‘_get_someValue()’)，以
及 ‘anotherValue’ 的 "get" 和 "set" 方法 (‘_get_anotherValue()’ 和
‘_set_anotherValue()’)。 特别地，该映射不要求 IDL 属性像普通 Python 属性
那样可访问: ‘object.someValue’ `并非' 必须可用，并可能引发 *note
AttributeError: 3a3.。

但是，Python DOM API 则 `确实' 要求普通属性访问可用。 这意味着由 Python
IDL 解译器生成的典型代理有可能会不可用，如果 DOM 对象是通过 CORBA 来访问
则在客户端可能需要有包装对象。 虽然这确实要求为 CORBA DOM 客户端进行额外
的考虑，但具有从 Python 通过 CORBA 使用 DOM 经验的实现并不会认为这是个问
题。 已经声明了 ‘readonly’ 的属性不必在所有 DOM 实现中限制写入访问。

在 Python DOM API 中，访问器函数不是必须的。 如果提供，则它们应当采用由
Python IDL 映射所定义的形式，但这些方法会被认为不必要，因为这些属性可以
从 Python 直接访问。 永远都不要为 ‘readonly’ 属性提供 "set" 访问器。

IDL 定义没有完全体现 W3C DOM API 的要求，如特定对象的概念，又如
‘getElementsByTagName()’ 的返回值为 "live" 等。 Python DOM API 并不强制
具体实现执行这些要求。


File: python.info,  Node: xml dom minidom --- 最小化的 DOM 实现,  Next: xml dom pulldom --- 支持构建部分 DOM 树,  Prev: xml dom --- 文档对象模型 API,  Up: 结构化标记处理工具

5.20.7 ‘xml.dom.minidom’ — 最小化的 DOM 实现
--------------------------------------------

`源代码:' Lib/xml/dom/minidom.py(1)

__________________________________________________________________

*note xml.dom.minidom: 136. 是文档对象模型接口的最小化实现，具有与其他语
言类似的 API。 它的目标是比完整 DOM 更简单并且更为小巧。 对于 DOM 还不十
分熟悉的用户则应当考虑改用 *note xml.etree.ElementTree: 138. 模块来进行
XML 处理。

     警告: *note xml.dom.minidom: 136. 模块对于恶意构建的数据是不安全的
     。 如果你需要解析不受信任或未经身份验证的数据，请参阅 *note XML
     漏洞: 2a03.。

DOM 应用程序通常会从将某个 XML 解析为 DOM 开始。 使用 *note
xml.dom.minidom: 136. 时，这是通过各种解析函数来完成的:

     from xml.dom.minidom import parse, parseString

     dom1 = parse('c:\\temp\\mydata.xml')  # parse an XML file by name

     datasource = open('c:\\temp\\mydata.xml')
     dom2 = parse(datasource)  # parse an open file

     dom3 = parseString('<myxml>Some data<empty/> some more data</myxml>')

*note parse(): 2ae4. 函数可接受一个文件名或者打开的文件对象。

 -- 函数: xml.dom.minidom.parse (filename_or_file, parser=None,
          bufsize=None)

     根据给定的输入返回一个 ‘Document’。 `filename_or_file' 可以是一个文
     件名，或是一个文件类对象。 如果给定 `parser' 则它必须是一个 SAX2 解
     析器对象。 此函数将修改解析器的处理程序并激活命名空间支持；其他解析
     器配置（例如设置一个实体求解器）必须已经提前完成。

如果你将 XML 存放为字符串，则可以改用 *note parseString(): 2ae5. 函数:

 -- 函数: xml.dom.minidom.parseString (string, parser=None)

     返回一个代表 `string' 的 ‘Document’。 此方法会为指定字符串创建一个
     *note io.StringIO: 836. 对象并将其传递给 *note parse(): 2ae4.。

两个函数均返回一个代表文档内容的 ‘Document’ 对象。object representing
the content of the document.

*note parse(): 2ae4. 和 *note parseString(): 2ae5. 函数所做的是将 XML 解
析器连接到一个 "DOM 构建器"，它可以从任意 SAX 解析器接收解析事件并将其转
换为 DOM 树结构。 这两个函数的名称可能有些误导性，但在学习此接口时是很容
易掌握的。 文档解析操作将在这两个函数返回之前完成；简单地说这两个函数本
身并不提供解析器实现。

你也可以通过在一个 "DOM 实现" 对象上调用方法来创建 ‘Document’。 此对象可
通过调用 *note xml.dom: 135. 包或者 *note xml.dom.minidom: 136. 模块中的
‘getDOMImplementation()’ 函数来获取。 一旦你获得了一个 ‘Document’，你就
可以向它添加子节点来填充 DOM:

     from xml.dom.minidom import getDOMImplementation

     impl = getDOMImplementation()

     newdoc = impl.createDocument(None, "some_tag", None)
     top_element = newdoc.documentElement
     text = newdoc.createTextNode('Some textual content.')
     top_element.appendChild(text)

一旦你得到了 DOM 文档对象，你就可以通过其属性和方法访问对应 XML 文档的各
个部分。 这些属性定义在 DOM 规格说明当中；文档对象的主要特征属性是
‘documentElement’。 它给出了 XML 文档中的主元素：即包含了所有其他元素的
元素。 以下是一个示例程序:

     dom3 = parseString("<myxml>Some data</myxml>")
     assert dom3.documentElement.tagName == "myxml"

当你完成对一个 DOM 树的处理时，你可以选择调用 ‘unlink()’ 方法以鼓励尽早
清除不再需要的对象。 ‘unlink()’ 是 *note xml.dom.minidom: 136. 针对 DOM
API 的专属扩展，它会将特定节点及其下级标记为不再有用。 在其他情况下，
Python 的垃圾回收器将负责最终处理树结构中的对象。

参见
....

文档对象模型 (DOM) 第 1 层级规格说明(2)

     被 *note xml.dom.minidom: 136. 所支持的 W3C 针对 DOM 的建议。

* Menu:

* DOM 对象::
* DOM 示例::
* minidom 和 DOM 标准::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/xml/dom/minidom.py

   (2) https://www.w3.org/TR/REC-DOM-Level-1/


File: python.info,  Node: DOM 对象,  Next: DOM 示例,  Up: xml dom minidom --- 最小化的 DOM 实现

5.20.7.1 DOM 对象
.................

Python 的 DOM API 定义被作为 *note xml.dom: 135. 模块文档的一部分给出。
这一节列出了该 API 和 *note xml.dom.minidom: 136. 之间的差异。

 -- 方法: Node.unlink ()

     破坏 DOM 的内部引用以便它能在没有循环 GC 的 Python 版本上垃圾回收器
     回收。 即使在循环 GC 可用的时候，使用此方法也可让大量内存更快变为可
     用，因此当 DOM 对象不再被需要时尽早调用它们的这个方法是很好的做法。
     此方法只须在 ‘Document’ 对象上调用，但也可以在下级节点上调用以丢弃
     该节点的下级节点。

     你可以通过使用 *note with: 6f2. 语句来避免显式调用此方法。 以下代码
     会在 ‘with’ 代码块退出时自动取消链接 `dom':

          with xml.dom.minidom.parse(datasource) as dom:
              ... # Work with dom.

 -- 方法: Node.writexml (writer, indent="", addindent="", newl="")

     将 XML 写入到写入器对象。 写入器接受文本而非字节串作为输入，它应当
     具有与文件对象接口相匹配的 ‘write()’ 方法。 `indent' 形参是当前节点
     的缩进层级。 `addindent' 形参是用于当前节点的下级节点的缩进量。
     `newl' 形参指定用于一行结束的字符串。

     对于 ‘Document’ 节点，可以使用附加的关键字参数 `encoding' 来指定
     XML 标头的编码格式字段。

     在 3.8 版更改: *note writexml(): 2ae9. 方法现在会保留用户指定的属性
     顺序。

 -- 方法: Node.toxml (encoding=None)

     返回一个包含 XML DOM 节点所代表的 XML 的字符串或字节串。

     带有显式的 `encoding' (1) 参数时，结果为使用指定编码格式的字节串。
     没有 `encoding' 参数时，结果为 Unicode 字符串，并且结果字符串中的
     XML 声明将不指定编码格式。 使用 UTF-8 以外的编码格式对此字符串进行
     编码通常是不正确的，因为 UTF-8 是 XML 的默认编码格式。

     在 3.8 版更改: *note toxml(): 2aea. 方法现在会保留用户指定的属性顺
     序。

 -- 方法: Node.toprettyxml (indent="\t", newl="\n", encoding=None)

     返回文档的美化打印版本。 `indent' 指定缩进字符串并默认为制表符；
     `newl' 指定标示每行结束的字符串并默认为 ‘\n’。

     `encoding' 参数的行为类似于 *note toxml(): 2aea. 的对应参数。

     在 3.8 版更改: *note toprettyxml(): 2aeb. 方法现在会保留用户指定的
     属性顺序。

   ---------- Footnotes ----------

   (1) (1) 包括在 XML 输出中的编码格式名称应当遵循适当的标准。 例如，
"UTF-8" 是有效的，但 "UTF8" 在 XML 文档的声明中是无效的，即使 Python 接
受其作为编码格式名称。 详情参见
‘https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl’ 和
‘https://www.iana.org/assignments/character-sets/character-sets.xhtml’。


File: python.info,  Node: DOM 示例,  Next: minidom 和 DOM 标准,  Prev: DOM 对象,  Up: xml dom minidom --- 最小化的 DOM 实现

5.20.7.2 DOM 示例
.................

此示例程序是个相当实际的简单程序示例。 在这个特定情况中，我们没有过多地
利用 DOM 的灵活性。

     import xml.dom.minidom

     document = """\
     <slideshow>
     <title>Demo slideshow</title>
     <slide><title>Slide title</title>
     <point>This is a demo</point>
     <point>Of a program for processing slides</point>
     </slide>

     <slide><title>Another demo slide</title>
     <point>It is important</point>
     <point>To have more than</point>
     <point>one slide</point>
     </slide>
     </slideshow>
     """

     dom = xml.dom.minidom.parseString(document)

     def getText(nodelist):
         rc = []
         for node in nodelist:
             if node.nodeType == node.TEXT_NODE:
                 rc.append(node.data)
         return ''.join(rc)

     def handleSlideshow(slideshow):
         print("<html>")
         handleSlideshowTitle(slideshow.getElementsByTagName("title")[0])
         slides = slideshow.getElementsByTagName("slide")
         handleToc(slides)
         handleSlides(slides)
         print("</html>")

     def handleSlides(slides):
         for slide in slides:
             handleSlide(slide)

     def handleSlide(slide):
         handleSlideTitle(slide.getElementsByTagName("title")[0])
         handlePoints(slide.getElementsByTagName("point"))

     def handleSlideshowTitle(title):
         print("<title>%s</title>" % getText(title.childNodes))

     def handleSlideTitle(title):
         print("<h2>%s</h2>" % getText(title.childNodes))

     def handlePoints(points):
         print("<ul>")
         for point in points:
             handlePoint(point)
         print("</ul>")

     def handlePoint(point):
         print("<li>%s</li>" % getText(point.childNodes))

     def handleToc(slides):
         for slide in slides:
             title = slide.getElementsByTagName("title")[0]
             print("<p>%s</p>" % getText(title.childNodes))

     handleSlideshow(dom)


File: python.info,  Node: minidom 和 DOM 标准,  Prev: DOM 示例,  Up: xml dom minidom --- 最小化的 DOM 实现

5.20.7.3 minidom 和 DOM 标准
............................

*note xml.dom.minidom: 136. 模块实际上是兼容 DOM 1.0 的 DOM 并带有部分
DOM 2 特性（主要是命名空间特性）。

Python 中 DOM 接口的用法十分直观。 会应用下列映射规则:

   * 接口是通过实例对象来访问的。 应用程序不应实例化这些类本身；它们应当
     使用 ‘Document’ 对象提供的创建器函数。 派生的接口支持上级接口的所有
     操作（和属性），并添加了新的操作。

   * 操作以方法的形式使用。 因由 DOM 只使用 *note in: 7ac. 形参，参数是
     以正常顺序传入的（从左至右）。 不存在可选参数。 ‘void’ 操作返回
     ‘None’。

   * IDL 属性会映射到实例属性。 为了兼容针对 Python 的 OMG IDL 语言映射
     ，属性 ‘foo’ 也可通过访问器方法 ‘_get_foo()’ 和 ‘_set_foo()’ 来访问
     。 ‘readonly’ 属性不可被修改；运行时并不强制要求这一点。

   * ‘short int’, ‘unsigned int’, ‘unsigned long long’ 和 ‘boolean’ 类型
     都会映射到 Python 整数类型。

   * ‘DOMString’ 类型会映射为 Python 字符串。 *note xml.dom.minidom:
     136. 支持字节串或字符串，但通常是产生字符串。 ‘DOMString’ 类型的值
     也可以为 ‘None’，W3C 的 DOM 规格说明允许其具有 IDL ‘null’ 值。

   * ‘const’ 声明会映射为它们各自的作用域内的变量 (例如
     ‘xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE’)；它们不可被修改
     。

   * ‘DOMException’ 目前不被 *note xml.dom.minidom: 136. 所支持。 *note
     xml.dom.minidom: 136. 会改为使用标准 Python 异常例如 *note
     TypeError: 193. 和 *note AttributeError: 3a3.。

   * ‘NodeList’ 对象是使用 Python 内置列表类型来实现的。 这些对象提供了
     DOM 规格说明中定义的接口，但在较早版本的 Python 中它们不支持官方
     API。 相比在 W3C 建议中定义的接口，它们要更加的 "Pythonic"。

下列接口未在 *note xml.dom.minidom: 136. 中实现:

   * ‘DOMTimeStamp’

   * ‘EntityReference’

这些接口所反映的 XML 文档信息对于大多数 DOM 用户来说没有什么帮助。

备注
....


File: python.info,  Node: xml dom pulldom --- 支持构建部分 DOM 树,  Next: xml sax --- 支持 SAX2 解析器,  Prev: xml dom minidom --- 最小化的 DOM 实现,  Up: 结构化标记处理工具

5.20.8 ‘xml.dom.pulldom’ — 支持构建部分 DOM 树
----------------------------------------------

`源代码:' Lib/xml/dom/pulldom.py(1)

__________________________________________________________________

*note xml.dom.pulldom: 137. 模块提供了一个“拉取解析器”，它能在必要时被用
于产生文件的可访问 DOM 的片段。 其基本概念包括从输入的 XML 流拉取“事件
”并处理它们。 与同样地同时应用了事件驱动处理模型加回调函数的 SAX 不同，
拉取解析器的用户要负责显式地从流拉取事件，并循环遍历这些事件直到处理结束
或者发生了错误条件。

     警告: *note xml.dom.pulldom: 137. 模块对于恶意构建的数据是不安全的
     。 如果你需要解析不受信任或未经身份验证的数据，请参阅 *note XML
     漏洞: 2a03.。

在 3.7.1 版更改: SAX 解析器默认不再处理一般外部实体以提升在默认情况下的
安全性。 要启用外部实体处理，请传入一个自定义的解析器实例:

     from xml.dom.pulldom import parse
     from xml.sax import make_parser
     from xml.sax.handler import feature_external_ges

     parser = make_parser()
     parser.setFeature(feature_external_ges, True)
     parse(filename, parser=parser)

示例:

     from xml.dom import pulldom

     doc = pulldom.parse('sales_items.xml')
     for event, node in doc:
         if event == pulldom.START_ELEMENT and node.tagName == 'item':
             if int(node.getAttribute('price')) > 50:
                 doc.expandNode(node)
                 print(node.toxml())

‘event’ 是一个常量，可以取下列值之一:

   * ‘START_ELEMENT’

   * ‘END_ELEMENT’

   * ‘COMMENT’

   * ‘START_DOCUMENT’

   * ‘END_DOCUMENT’

   * ‘CHARACTERS’

   * ‘PROCESSING_INSTRUCTION’

   * ‘IGNORABLE_WHITESPACE’

‘node’ 是一个 ‘xml.dom.minidom.Document’, ‘xml.dom.minidom.Element’ 或
‘xml.dom.minidom.Text’ 类型的对象。

由于文档是被当作“展平”的事件流来处理的，文档“树”会被隐式地遍历并且无论所
需元素在树中的深度如何都会被找到。 换句话说，不需要考虑层级问题，例如文
档节点的递归搜索等，但是如果元素的内容很重要，则有必要保留一些上下文相关
的状态（例如记住任意给定点在文档中的位置）或者使用 *note
DOMEventStream.expandNode(): 2af2. 方法并切换到 DOM 相关的处理过程。

 -- 类: xml.dom.pulldom.PullDom (documentFactory=None)

     *note xml.sax.handler.ContentHandler: 2af4. 的子类。

 -- 类: xml.dom.pulldom.SAX2DOM (documentFactory=None)

     *note xml.sax.handler.ContentHandler: 2af4. 的子类。

 -- 函数: xml.dom.pulldom.parse (stream_or_string, parser=None,
          bufsize=None)

     基于给定的输入返回一个 *note DOMEventStream: 27d.。
     `stream_or_string' 可以是一个文件名，或是一个文件类对象。 `parser'
     如果给出，则必须是一个 *note XMLReader: 2af7. 对象。 此函数将改变解
     析器的文档处理程序并激活命名空间支持；其他解析器配置（例如设置实体
     解析器）必须在之前已完成。

如果你将 XML 存放为字符串，则可以改用 *note parseString(): 2af8. 函数:

 -- 函数: xml.dom.pulldom.parseString (string, parser=None)

     返回一个 *note DOMEventStream: 27d. 来表示 (Unicode) `string'。

 -- 数据: xml.dom.pulldom.default_bufsize

     将 `bufsize' 形参的默认值设为 *note parse(): 2af6.。

     此变量的值可在调用 *note parse(): 2af6. 之前修改并使新值生效。

* Menu:

* DOMEventStream 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/xml/dom/pulldom.py


File: python.info,  Node: DOMEventStream 对象,  Up: xml dom pulldom --- 支持构建部分 DOM 树

5.20.8.1 DOMEventStream 对象
............................

 -- 类: xml.dom.pulldom.DOMEventStream (stream, parser, bufsize)

     3.8 版后已移除: 对 *note 序列协议: 280. 的支持已被弃用。

      -- 方法: getEvent ()

          返回一个元组，其中包含 `event' 和 ‘xml.dom.minidom.Document’ 形
          式的当前 `node' 如果 event 等于 ‘START_DOCUMENT’，包含
          ‘xml.dom.minidom.Element’ 如果 event 等于 ‘START_ELEMENT’ 或
          ‘END_ELEMENT’ 或者 ‘xml.dom.minidom.Text’ 如果 event 等于
          ‘CHARACTERS’。 当前 node 不包含有关其子节点的信息，除非 *note
          expandNode(): 2af2. 被调用。

      -- 方法: expandNode (node)

          将 `node' 的所有子节点扩展到 `node' 中。 例如:

               from xml.dom import pulldom

               xml = '<html><title>Foo</title> <p>Some text <div>and more</div></p> </html>'
               doc = pulldom.parseString(xml)
               for event, node in doc:
                   if event == pulldom.START_ELEMENT and node.tagName == 'p':
                       # Following statement only prints '<p/>'
                       print(node.toxml())
                       doc.expandNode(node)
                       # Following statement prints node with all its children '<p>Some text <div>and more</div></p>'
                       print(node.toxml())

      -- 方法: reset ()


File: python.info,  Node: xml sax --- 支持 SAX2 解析器,  Next: xml sax handler --- SAX 处理程序的基类,  Prev: xml dom pulldom --- 支持构建部分 DOM 树,  Up: 结构化标记处理工具

5.20.9 ‘xml.sax’ — 支持 SAX2 解析器
-----------------------------------

`源代码:' Lib/xml/sax/__init__.py(1)

__________________________________________________________________

*note xml.sax: 13c. 包提供多个模块，它们在 Python 上实现了用于 XML (SAX)
接口的简单 API。 这个包本身为 SAX API 用户提供了一些最常用的 SAX 异常和
便捷函数。

     警告: *note xml.sax: 13c. 模块对于恶意构建的数据是不安全的。 如果你
     需要解析不受信任或未经身份验证的数据，请参阅 *note XML 漏洞: 2a03.。

在 3.7.1 版更改: SAX 解析器默认不会再处理通用外部实体以便提升安全性。 在
此之前，解析器会创建网络连接来获取远程文件或是从 DTD 和实体文件系统中加
载本地文件。 此特性可通过在解析器对象上调用 *note setFeature(): 2b00. 对
象并传入参数 *note feature_external_ges: 2b01. 来重新启用。

可用的便捷函数如下所列:

 -- 函数: xml.sax.make_parser (parser_list=[])

     创建并返回一个 SAX *note XMLReader: 2af7. 对象。 将返回第一个被找到
     的解析器。 如果提供了 `parser_list'，它必须为一个包含字符串的可迭代
     对象，这些字符串指定了具有名为 ‘create_parser()’ 函数的模块。 在
     `parser_list' 中列出的模块将在默认解析器列表中的模块之前被使用。

     在 3.8 版更改: `parser_list' 参数可以是任意可迭代对象，而不一定是列
     表。

 -- 函数: xml.sax.parse (filename_or_stream, handler,
          error_handler=handler.ErrorHandler())

     创建一个 SAX 解析器并用它来解析文档。 用于传入文档的
     `filename_or_stream' 可以是一个文件名或文件对象。 `handler' 形参必
     须是一个 SAX *note ContentHandler: 2af4. 实例。 如果给出了
     `error_handler'，则它必须是一个 SAX *note ErrorHandler: 2b02. 实例
     ；如果省略，则对于任何错误都将引发 *note SAXParseException: 2b03.。
     此函数没有返回值；所有操作必须由传入的 `handler' 来完成。

 -- 函数: xml.sax.parseString (string, handler,
          error_handler=handler.ErrorHandler())

     类似于 *note parse(): ff1.，但解析对象是作为形参传入的缓冲区
     `string'。 `string' 必须为 *note str: 339. 实例或者 *note
     bytes-like object: 5f1.。

     在 3.5 版更改: 增加了对 *note str: 339. 实例的支持。

典型的 SAX 应用程序会使用三种对象：读取器、处理句柄和输入源。 “读取器”在
此上下文中与解析器同义，即某个从输入源读取字节或字符，并产生事件序列的代
码段。 事件随后将被分发给处理句柄对象，即由读取器发起调用处理句柄上的某
个方法。 因此 SAX 应用程序必须获取一个读取器对象，创建或打开输入源，创建
处理句柄，并一起连接到这些对象。 作为准备工作的最后一步，将调用读取器来
解析输入内容。 在解析过程中，会根据来自输入数据的结构化和语义化事件来调
用处理句柄对象上的方法。

就这些对象而言，只有接口部分是需要关注的；它们通常不是由应用程序本身来实
例化。 由于 Python 没有显式的接口标记法，它们的正式引入形式是类，但应用
程序可能会使用并非从已提供的类继承而来的实现。 *note InputSource: 79b,
*note Locator: 2b04, ‘Attributes’, ‘AttributesNS’ 以及 *note XMLReader:
2af7. 接口是在 *note xml.sax.xmlreader: 13f. 模块中定义的。 处理句柄接口
是在 *note xml.sax.handler: 13d. 中定义的。 为了方便起见，*note
InputSource: 79b. (它往往会被直接实例化) 和处理句柄类也可以从 *note
xml.sax: 13c. 获得。 这些接口的描述如下。

除了这些类，*note xml.sax: 13c. 还提供了如下异常类。

 -- 例外: xml.sax.SAXException (msg, exception=None)

     封装某个 XML 错误或警告。 这个类可以包含来自 XML 解析器或应用程序的
     基本错误或警告信息：它可以被子类化以提供额外的功能或是添加本地化信
     息。 请注意虽然在 *note ErrorHandler: 2b02. 接口中定义的处理句柄可
     以接收该异常的实例，但是并不要求实际引发该异常 — 它也可以被用作信息
     的容器。

     当实例化时，`msg' 应当是适合人类阅读的错误描述。 如果给出了可选的
     `exception' 形参，它应当为 ‘None’ 或者解析代码所捕获的异常并会被作
     为信息传递出去。

     这是其他 SAX 异常类的基类。

 -- 例外: xml.sax.SAXParseException (msg, exception, locator)

     *note SAXException: 2b05. 的子类，针对解析错误引发。 这个类的实例会
     被传递给 SAX *note ErrorHandler: 2b02. 接口的方法来提供关于解析错误
     的信息。 这个类支持 SAX *note Locator: 2b04. 接口以及 *note
     SAXException: 2b05. 接口。

 -- 例外: xml.sax.SAXNotRecognizedException (msg, exception=None)

     *note SAXException: 2b05. 的子类，当 SAX *note XMLReader: 2af7. 遇
     到不可识别的特性或属性时引发。 SAX 应用程序和扩展可能会出于类似目的
     而使用这个类。

 -- 例外: xml.sax.SAXNotSupportedException (msg, exception=None)

     *note SAXException: 2b05. 的子类，当 SAX *note XMLReader: 2af7. 被
     要求启用某个不受支持的特性，或者将某个属性设为具体实现不支持的值时
     引发。 SAX 应用程序和扩展可能会出于类似目的而使用这个类。

参见
....

SAX: The Simple API for XML(2)

     这个网站是 SAX API 定义的焦点。 它提供了一个 Java 实现以及在线文档
     。 还包括其他实现的链接和历史信息。

*note xml.sax.handler: 13d. 模块

     应用程序所提供对象的接口定义。

*note xml.sax.saxutils: 13e. 模块

     可在 SAX 应用程序中使用的便捷函数。

*note xml.sax.xmlreader: 13f. 模块

     解析器所提供对象的接口定义。

* Menu:

* SAXException 对象::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/xml/sax/__init__.py

   (2) http://www.saxproject.org/


File: python.info,  Node: SAXException 对象,  Up: xml sax --- 支持 SAX2 解析器

5.20.9.1 SAXException 对象
..........................

*note SAXException: 2b05. 异常类支持下列方法:

 -- 方法: SAXException.getMessage ()

     返回描述错误条件的适合人类阅读的消息。

 -- 方法: SAXException.getException ()

     返回一个封装的异常对象或者 ‘None’。


File: python.info,  Node: xml sax handler --- SAX 处理程序的基类,  Next: xml sax saxutils --- SAX 工具集,  Prev: xml sax --- 支持 SAX2 解析器,  Up: 结构化标记处理工具

5.20.10 ‘xml.sax.handler’ — SAX 处理程序的基类
----------------------------------------------

`源代码:' Lib/xml/sax/handler.py(1)

__________________________________________________________________

SAX API 定类了四种处理句柄：内容句柄、DTD 句柄、错误句柄以及实体解析器。
应用程序通常只需要实现他们感兴趣的事件对应的接口；他们可以在单个对象或多
个对象中实现这些接口。 处理句柄的实现应当继承自在 *note xml.sax.handler:
13d. 模块中提供的基类，以便所有方法都能获得默认的实现。

 -- 类: xml.sax.handler.ContentHandler

     这是 SAX 中的主回调接口，也是对应用程序来说最重要的一个接口。 此接
     口中事件的顺序反映了文档中信息的顺序。

 -- 类: xml.sax.handler.DTDHandler

     处理 DTD 事件。

     这个接口仅指定了基本解析（未解析的实体和属性）所需的那些 DTD 事件。

 -- 类: xml.sax.handler.EntityResolver

     用于解析实体的基本接口。 如果你创建了实现此接口的对象，然后用你的解
     析器注册该对象，该解析器将调用你的对象中的方法来解析所有外部实体。

 -- 类: xml.sax.handler.ErrorHandler

     解析器用来向应用程序表示错误和警告的接口。 这个对象的方法控制错误是
     要立即转换为异常还是以某种其他该来来处理。

除了这些类，*note xml.sax.handler: 13d. 还提供了表示特性和属性名称的符号
常量。

 -- 数据: xml.sax.handler.feature_namespaces

          value: ‘"http://xml.org/sax/features/namespaces"’ 
          true: 执行命名空间处理。 
          false: 可选择不执行命名空间处理 (这意味着 namespace-prefixes; default)。 
          access: (解析) 只读; (不解析) 读/写 

 -- 数据: xml.sax.handler.feature_namespace_prefixes

          value: ‘"http://xml.org/sax/features/namespace-prefixes"’ 
          true: 报告用于命名空间声明的原始带前缀名称和属性。 
          false: 不报告用于命名空间声明的属性，可选择不报告原始带前缀名称（默认）。 
          access: (解析) 只读; (不解析) 读/写 

 -- 数据: xml.sax.handler.feature_string_interning

          value: ‘"http://xml.org/sax/features/string-interning"’ 
          true: 所有元素名称、前缀、属性名称、命名空间 URI 以及本地名称都使用内置的 intern 函数进行内化。 
          false: 名称不要求被内化，但也可以被内化（默认）。 
          access: (解析) 只读; (不解析) 读/写 

 -- 数据: xml.sax.handler.feature_validation

          value: ‘"http://xml.org/sax/features/validation"’ 
          true: 报告所有的验证错误（包括 external-general-entities 和 external-parameter-entities）。 
          false: 不报告验证错误。 
          access: (解析) 只读; (不解析) 读/写 

 -- 数据: xml.sax.handler.feature_external_ges

          value: ‘"http://xml.org/sax/features/external-general-entities"’ 
          true: 包括所有的外部通用（文本）实体。 
          false: 不包括外部通用实体。 
          access: (解析) 只读; (不解析) 读/写 

 -- 数据: xml.sax.handler.feature_external_pes

          value: ‘"http://xml.org/sax/features/external-parameter-entities"’ 
          true: 包括所有的外部参数实体，包括外部 DTD 子集。 
          false: 不包括任何外部参数实体，也不包括外部 DTD 子集。 
          access: (解析) 只读; (不解析) 读/写 

 -- 数据: xml.sax.handler.all_features

     全部特性列表。

 -- 数据: xml.sax.handler.property_lexical_handler

          value: ‘"http://xml.org/sax/properties/lexical-handler"’ 
          数据类型: xml.sax.sax2lib.LexicalHandler (在 Python 2 中不受支持) 
          描述: 可选的扩展处理句柄，用于注释等词法事件。 
          访问: 读/写 

 -- 数据: xml.sax.handler.property_declaration_handler

          值: ‘"http://xml.org/sax/properties/declaration-handler"’ 
          数据类型: xml.sax.sax2lib.DeclHandler (在 Python 2 中不受支持) 
          描述: 可选的扩展处理句柄，用于标注和未解析实体以外的 DTD 相关事件。 
          访问: 读/写 

 -- 数据: xml.sax.handler.property_dom_node

          值: ‘"http://xml.org/sax/properties/dom-node"’ 
          数据类型: org.w3c.dom.Node (在 Python 2 中不受支持) 
          描述: 在解析时，如果这是一个 DOM 迭代器则为当前被访问的 DOM 节点；不在解析时，则将根 DOM 节点用于迭代。 
          access: (解析) 只读; (不解析) 读/写 

 -- 数据: xml.sax.handler.property_xml_string

          值: ‘"http://xml.org/sax/properties/xml-string"’ 
          数据类型: String 
          描述: 作为当前事件来源的字符串字面值。 
          访问: 只读 

 -- 数据: xml.sax.handler.all_properties

     已知属性名称列表。

* Menu:

* ContentHandler 对象::
* DTDHandler 对象::
* EntityResolver 对象::
* ErrorHandler 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/xml/sax/handler.py


File: python.info,  Node: ContentHandler 对象,  Next: DTDHandler 对象,  Up: xml sax handler --- SAX 处理程序的基类

5.20.10.1 ContentHandler 对象
.............................

用户应当子类化 *note ContentHandler: 2af4. 来支持他们的应用程序。 以下方
法会由解析器在输入文档的适当事件上调用:

 -- 方法: ContentHandler.setDocumentLocator (locator)

     由解析器调用来给予应用程序一个定位器以确定文档事件来自何处。

     强烈建议（虽然不是绝对的要求） SAX 解析器提供一个定位器：如果提供的
     话，它必须在发起调用 DocumentHandler 接口的任何其他方法之前通过发起
     调用此方法来提供定位器。

     定位器允许应用程序确定任何文档相关事件的结束位置，即使解析器没有报
     告错误。 通常，应用程序将使用这些信息来报告它自己的错误（例如未匹配
     到应用程序业务规则的字符内容）。 定位器所返回的信息可能不足以与搜索
     引擎配合使用。

     请注意定位器只有在发起调用此接口中的事件时才会返回正确的信息。 应用
     程序不应试图在其他任何时刻使用它。

 -- 方法: ContentHandler.startDocument ()

     接收一个文档开始的通知。

     SAX 解析器将只发起调用这个方法一次，并且会在调用这个接口或
     DTDHandler 中的任何其他方法之前 (*note setDocumentLocator(): 2b1d.
     除外)。

 -- 方法: ContentHandler.endDocument ()

     接收一个文档结束的通知。

     SAX 解析器将只发起调用这个方法一次，并且它将是在解析过程中最后发起
     调用的方法。 解析器在（因不可恢复的错误）放弃解析或到达输入的终点之
     前不应发起调用这个方法。

 -- 方法: ContentHandler.startPrefixMapping (prefix, uri)

     开始一个前缀 URI 命名空间映射的范围。

     来自此事件的信息对于一般命名空间处理来说是不必要的：当
     ‘feature_namespaces’ 特性被启用时（默认）SAX XML 读取器将自动为元素
     和属性名称替换前缀。

     但是也存在一些情况，当应用程序需要在字符数据或属性值中使用前缀，而
     它们无法被安全地自动扩展；*note startPrefixMapping(): 2b20. 和
     *note endPrefixMapping(): 2b21. 事件会向应用程序提供信息以便在这些
     上下文内部扩展前缀，如果有必要的话。

     请注意 *note startPrefixMapping(): 2b20. 和 *note
     endPrefixMapping(): 2b21. 事件并不保证能够相对彼此被正确地嵌套：所
     有 *note startPrefixMapping(): 2b20. 事件都将在对应的 *note
     startElement(): 2b22. 事件之前发生，而所有 *note
     endPrefixMapping(): 2b21. 事件都将在对应的 *note endElement():
     2b23. 事件之后发生，但它们的并不保证一致。

 -- 方法: ContentHandler.endPrefixMapping (prefix)

     结束一个前缀 URI 映射的范围。

     请参看 *note startPrefixMapping(): 2b20. 了解详情。 此事件将总是会
     在对应的 *note endElement(): 2b23. 事件之后发生，但 *note
     endPrefixMapping(): 2b21. 事件的顺序则并没有保证。

 -- 方法: ContentHandler.startElement (name, attrs)

     在非命令空间模式下指示一个元素的开始。

     `name' 形参包含字符串形式的元素类型原始 XML 1.0 名称而 `attrs' 形参
     存放包含元素属性的 ‘Attributes’ 接口对象 (参见 *note Attributes
     接口: 2b24.)。 作为 `attrs' 传入的对象可能被解析器所重用；维持一个
     对它的引用不是保持属性副本的可靠方式。 要保持这些属性的一个副本，请
     使用 `attrs' 对象的 *note copy(): 26. 方法。

 -- 方法: ContentHandler.endElement (name)

     在非命名空间模式下指示一个元素的结束。

     `name' 形参包含元素类型的名称，与 *note startElement(): 2b22. 事件
     的一样。

 -- 方法: ContentHandler.startElementNS (name, qname, attrs)

     在命名空间模式下指示一个元素的开始。

     `name' 形参包含以 ‘(uri, localname)’ 元组表示的元素类型名称，
     `qname' 形参包含源文档中使用的原始 XML 1.0 名称，而 `attrs' 形参存
     放包含元素属性的 ‘AttributesNS’ 接口实例 (参见 *note AttributesNS
     接口: 2b26.)。 如果没有命名空间被关联到元素，则 `name' 的 `uri' 部
     分将为 ‘None’。 作为 `attrs' 传入的对象可能被解析器所重用；维持一个
     对它的引用不是保持属性副本的可靠方式。 要保持这些属性的一个副本，请
     使用 `attrs' 对象的 *note copy(): 26. 方法。

     解析器可将 `qname' 形参设为 ‘None’，除非
     ‘feature_namespace_prefixes’ 特性已被激活。

 -- 方法: ContentHandler.endElementNS (name, qname)

     在命名空间模式下指示一个元素的结束。

     `name' 形参包含元素类型的名称，与 *note startElementNS(): 2b25. 方
     法的一样，`qname' 形参也是类似的。

 -- 方法: ContentHandler.characters (content)

     接收字符数据的通知。

     解析器将调用此方法来报告每一个字符数据分块。 SAX 解析器可以将所有连
     续字符数据返回为一个单独分块，或者将其拆成几个分块；但是，在任意单
     个事件中的所有字符都必须来自同一个外部实体以便定位器提供有用的信息
     。

     `content' 可以是一个字符串或字节串实例；‘expat’ 读取器模块总是会产
     生字符串。

          注解: Python XML 特别关注小组所提供的早期 SAX 1 接口针对此方法
          使用了一个更类似于 Java 的接口。 由于 Python 所使用的大多数解
          析器都没有利用老式的接口，因而选择了更简单的签名来替代它。 要
          将旧代码转换为新接口，请使用 `content' 而不要通过旧的 `offset'
          和 `length' 形参来对内容进行切片。

 -- 方法: ContentHandler.ignorableWhitespace (whitespace)

     接收元素内容中可忽略空白符的通知。

     验证解析器必须使用此方法来报告每个可忽略的空白符分块（参见 W3C XML
     1.0 建议第 2.10 节）：非验证解析器如果能够解析并使用内容模型的话也
     可以使用此方法。

     SAX 解析器可以将所有连续字符数据返回为一个单独分块，或者将其拆成几
     个分块；但是，在任意单个事件中的所有字符都必须来自同一个外部实体以
     便定位器提供有用的信息。

 -- 方法: ContentHandler.processingInstruction (target, data)

     接受一条处理指令的通知。

     解析器将为已找到的每条处理指令发起调用该方法一次：请注意处理指令可
     能出现在主文档元素之前或之后。

     SAX 解析器绝不应当使用此方法来报告 XML 声明（XML 1.0 第 2.8 节）或
     文本声明（XML 1.0 第 4.3.1 节）。

 -- 方法: ContentHandler.skippedEntity (name)

     接收一个已跳过实体的通知。

     解析器将为每个已跳过实体发起调用此方法一次。 非验证处理程序可能会跳
     过未看到声明的实体（例如，由于实体是在一个外部because, for example,
     the entity was declared in an external DTD 子集中声明的）。 所有处
     理程序都可以跳过外部实体，具体取决于 ‘feature_external_ges’ 和
     ‘feature_external_pes’ 属性的值。


File: python.info,  Node: DTDHandler 对象,  Next: EntityResolver 对象,  Prev: ContentHandler 对象,  Up: xml sax handler --- SAX 处理程序的基类

5.20.10.2 DTDHandler 对象
.........................

*note DTDHandler: 2b0e. 实例提供了下列方法:

 -- 方法: DTDHandler.notationDecl (name, publicId, systemId)

     处理标注声明事件。

 -- 方法: DTDHandler.unparsedEntityDecl (name, publicId, systemId,
          ndata)

     处理未解析的实体声明事件。


File: python.info,  Node: EntityResolver 对象,  Next: ErrorHandler 对象,  Prev: DTDHandler 对象,  Up: xml sax handler --- SAX 处理程序的基类

5.20.10.3 EntityResolver 对象
.............................

 -- 方法: EntityResolver.resolveEntity (publicId, systemId)

     求解一个实体的系统标识符并返回一个字符串形式的系统标识符作为读取源
     ，或是一个 InputSource 作为读取源。 默认的实现会返回 `systemId'。


File: python.info,  Node: ErrorHandler 对象,  Prev: EntityResolver 对象,  Up: xml sax handler --- SAX 处理程序的基类

5.20.10.4 ErrorHandler 对象
...........................

带有这个接口的对象被用于接收来自 *note XMLReader: 2af7. 的错误和警告信息
。 如果你创建了一个实现这个接口的对象，然后用你的 *note XMLReader: 2af7.
注册这个对象，则解析器将调用你的对象中的这个方法来报告所有的警告和错误。
有三个可用的错误级别：警告、（或许）可恢复的错误和不可恢复的错误。 所有
方法都接受 ‘SAXParseException’ 作为唯一的形参。 错误和警告可以通过引发所
传入的异常对象来转换为异常。

 -- 方法: ErrorHandler.error (exception)

     当解析器遇到一个可恢复错误时调用。 如果此方法没有引发异常，则解析可
     能会继续，但是应用程序不能预期获得更多的文档信息。 允许解析器继续可
     能会允许在输入文档中发现额外的错误。

 -- 方法: ErrorHandler.fatalError (exception)

     当解析器遇到一个无法恢复的错误时调用；在此方法返回时解析应当终止。

 -- 方法: ErrorHandler.warning (exception)

     当解析器向应用程序提供次要警告信息时调用。 在此方法返回时解析应当继
     续，并且文档信息将继续被传递给应用程序。 在此方法中引发异常将导致解
     析结束。


File: python.info,  Node: xml sax saxutils --- SAX 工具集,  Next: xml sax xmlreader --- 用于 XML 解析器的接口,  Prev: xml sax handler --- SAX 处理程序的基类,  Up: 结构化标记处理工具

5.20.11 ‘xml.sax.saxutils’ — SAX 工具集
---------------------------------------

`源代码:' Lib/xml/sax/saxutils.py(1)

__________________________________________________________________

*note xml.sax.saxutils: 13e. 模块包含一些在创建 SAX 应用程序时十分有用的
类和函数，它们可以被直接使用，或者是作为基类使用。

 -- 函数: xml.sax.saxutils.escape (data, entities={})

     对数据字符串中的 ‘'&'’, ‘'<'’ 和 ‘'>'’ 进行转义。

     你可以通过传入一个字典作为可选的 `entities' 形参来对其他字符串数据
     进行转义。 字典的键和值必须为字符串；每个键将被替换为其所对应的值。
     字符 ‘'&'’, ‘'<'’ 和 ‘'>'’ 总是会被转义，即使提供了 `entities'。

 -- 函数: xml.sax.saxutils.unescape (data, entities={})

     对字符串数据中的 ‘'&amp;'’, ‘'&lt;'’ 和 ‘'&gt;'’ 进行反转义。

     你可以通过传入一个字典作为可选的 `entities' 形参来对其他数据字符串
     进行转义。 字典的键和值必须都为字符串；每个键将被替换为所对应的值。
     ‘'&amp'’, ‘'&lt;'’ 和 ‘'&gt;'’ 将总是保持不被转义，即使提供了
     `entities'。

 -- 函数: xml.sax.saxutils.quoteattr (data, entities={})

     类似于 *note escape(): 2b3a.，但还会对 `data' 进行处理以将其用作属
     性值。 返回值是 `data' 加上任何额外要求的替换的带引号版本。*note
     quoteattr(): 2b3c. 将基于 `data' 的内容选择一个引号字符，以尽量避免
     在字符串中编码任何引号字符。 如果单双引号字符在 `data' 中都存在，则
     双引号字符将被编码并且 `data' 将使用双引号来标记。 结果字符串可被直
     接用作属性值:

          >>> print("<element attr=%s>" % quoteattr("ab ' cd \" ef"))
          <element attr="ab ' cd &quot; ef">

     此函数适用于为 HTML 或任何使用引用实体语法的 SGML 生成属性值。

 -- 类: xml.sax.saxutils.XMLGenerator (out=None, encoding='iso-8859-1',
          short_empty_elements=False)

     这个类通过将 SAX 事件写回到 XML 文档来实现 *note ContentHandler:
     2af4. 接口。 换句话说，使用 *note XMLGenerator: 2b3d. 作为内容处理
     程序将重新产生所解析的原始文档。 `out' 应当为一个文件类对象，它默认
     将为 `sys.stdout'。 `encoding' 为输出流的编码格式，它默认将为
     ‘'iso-8859-1'’。 `short_empty_elements' 控制不包含内容的元素的格式
     化：如为 ‘False’ (默认值) 则它们会以开始/结束标记对的形式被发送，如
     果设为 ‘True’ 则它们会以单个自结束标记的形式被发送。

     3.2 新版功能: `short_empty_elements' 形参。

 -- 类: xml.sax.saxutils.XMLFilterBase (base)

     这个类被设计用来分隔 *note XMLReader: 2af7. 和客户端应用的事件处理
     程序。 在默认情况下，它除了将请求传送给读取器并将事件传送给处理程序
     之外什么都不做，但其子类可以重载特定的方法以在传送它们的时候修改事
     件流或配置请求。

 -- 函数: xml.sax.saxutils.prepare_input_source (source, base='')

     此函数接受一个输入源和一个可选的基准 URL 并返回一个经过完整解析可供
     读取的 *note InputSource: 79b.。 输入源的给出形式可以为字符串、文件
     类对象或 *note InputSource: 79b. 对象；解析器将使用此函数来针对它们
     的 ‘parse()’ 方法实现多态 `source' 参数。

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/xml/sax/saxutils.py


File: python.info,  Node: xml sax xmlreader --- 用于 XML 解析器的接口,  Next: xml parsers expat --- 使用 Expat 的快速 XML 解析,  Prev: xml sax saxutils --- SAX 工具集,  Up: 结构化标记处理工具

5.20.12 ‘xml.sax.xmlreader’ — 用于 XML 解析器的接口
---------------------------------------------------

`源代码:' Lib/xml/sax/xmlreader.py(1)

__________________________________________________________________

SAX 解析器实现了 *note XMLReader: 2af7. 接口。 它们是在一个 Python 模块
中实现的，该模块必须提供一个 ‘create_parser()’ 函数。 该函数由 *note
xml.sax.make_parser(): 1038. 不带参数地发起调用来创建新的解析器对象。

 -- 类: xml.sax.xmlreader.XMLReader

     可由 SAX 解析器继承的基类。

 -- 类: xml.sax.xmlreader.IncrementalParser

     在某些情况下，最好不要一次性地解析输入源，而是在可用的时候分块送入
     。 请注意读取器通常不会读取整个文件，它同样也是分块读取的； 并且
     ‘parse()’ 在处理完整个文档之前不会返回。 所以如果不希望 ‘parse()’ 出
     现阻塞行为则应当使用这些接口。

     当解析器被实例化时它已准备好立即开始接受来自 feed 方法的数据。 在通
     过调用 close 方法结束解析时 reset 方法也必须被调用以使解析器准备好
     接受新的数据，无论它是来自于 feed 还是使用 parse 方法。

     请注意这些方法 `不可' 在解析期间被调用，即在 parse 被调用之后及其返
     回之前。

     默认情况下，该类还使用 IncrementalParser 接口的 feed, close 和
     reset 方法来实现 XMLReader 接口的 parse 方法以方便 SAX 2.0 驱动的编
     写者。

 -- 类: xml.sax.xmlreader.Locator

     用于关联一个 SAX 事件与一个文档位置的接口。 定位器对象只有在调用
     DocumentHandler 的方法期间才会返回有效的结果；在其他任何时候，结果
     都是不可预测的。 如果信息不可用，这些方法可能返回 ‘None’。

 -- 类: xml.sax.xmlreader.InputSource (system_id=None)

     *note XMLReader: 2af7. 读取实体所需信息的封装。

     这个类可能包括了关于公有标识符、系统标识符、字节流（可能带有字符编
     码格式信息）和/或一个实体的字符流的信息。

     应用程序将创建这个类的对象以便在 *note XMLReader.parse(): 2b43. 方
     法中使用或是用于从 EntityResolver.resolveEntity 返回值。

     *note InputSource: 79b. 属于应用程序，*note XMLReader: 2af7. 不能修
     改从应用程序传递给它的 *note InputSource: 79b. 对象，但它可以创建副
     本并进行修改。

 -- 类: xml.sax.xmlreader.AttributesImpl (attrs)

     这是 ‘Attributes’ 接口（参见 *note Attributes 接口: 2b24. 一节）的
     具体实现。 这是一个 ‘startElement()’ 调用中的元素属性的字典类对象。
     除了最有用处的字典操作，它还支持接口所描述的一些其他方法。 该类的对
     象应当由读取器来实例化；`attrs' 必须为包含从属性名到属性值的映射的
     字典类对象。

 -- 类: xml.sax.xmlreader.AttributesNSImpl (attrs, qnames)

     可感知命名空间的 *note AttributesImpl: 2b44. 变体形式，它将被传递给
     ‘startElementNS()’。 它派生自 *note AttributesImpl: 2b44.，但会将属
     性名称解读为 `namespaceURI' 和 `localname' 二元组。 此外，它还提供
     了一些期望接收在原始文档中出现的限定名称的方法。 这个类实现了
     ‘AttributesNS’ 接口（参见 *note AttributesNS 接口: 2b26. 一节）。

* Menu:

* XMLReader 对象::
* IncrementalParser 对象::
* Locator 对象::
* InputSource 对象::
* Attributes 接口::
* AttributesNS 接口::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/xml/sax/xmlreader.py


File: python.info,  Node: XMLReader 对象,  Next: IncrementalParser 对象,  Up: xml sax xmlreader --- 用于 XML 解析器的接口

5.20.12.1 XMLReader 对象
........................

*note XMLReader: 2af7. 接口支持下列方法:

 -- 方法: XMLReader.parse (source)

     处理输入源，产生 SAX 事件。 `source' 对象可以是一个系统标识符（标识
     输入源的字符串 – 通常为文件名或 URL）, *note pathlib.Path: 202. 或
     *note 路径类: 373. 对象，或者是 *note InputSource: 79b. 对象。 当
     *note parse(): 2b43. 返回时，输入会被全部处理完成，解析器对象可以被
     丢弃或重置。

     在 3.5 版更改: 添加了对字符流的支持。

     在 3.8 版更改: 增加了对路径类对象的支持。

 -- 方法: XMLReader.getContentHandler ()

     返回当前的 *note ContentHandler: 2af4.。

 -- 方法: XMLReader.setContentHandler (handler)

     设置当前的 *note ContentHandler: 2af4.。 如果没有设置 *note
     ContentHandler: 2af4.，内容事件将被丢弃。

 -- 方法: XMLReader.getDTDHandler ()

     返回当前的 *note DTDHandler: 2b0e.。

 -- 方法: XMLReader.setDTDHandler (handler)

     设置当前的 *note DTDHandler: 2b0e.。 如果没有设置 *note DTDHandler:
     2b0e.，DTD 事件将被德育。

 -- 方法: XMLReader.getEntityResolver ()

     返回当前的 *note EntityResolver: 2b0f.。

 -- 方法: XMLReader.setEntityResolver (handler)

     设置当前的 *note EntityResolver: 2b0f.。 如果没有设置 *note
     EntityResolver: 2b0f.，尝试解析一个外部实体将导致打开该实体的系统标
     识符，并且如果它不可用则操作将失败。

 -- 方法: XMLReader.getErrorHandler ()

     返回当前的 *note ErrorHandler: 2b02.。

 -- 方法: XMLReader.setErrorHandler (handler)

     设置当前的错误处理句柄。 如果没有设置 *note ErrorHandler: 2b02.，错
     误将作为异常被引发，并将打印警告信息。

 -- 方法: XMLReader.setLocale (locale)

     允许应用程序为错误和警告设置语言区域。

     SAX 解析器不要求为错误和警告提供本地化信息；但是如果它们无法支持所
     请求的语言区域，则必须引发一个 SAX 异常。 应用程序可以在解析的中途
     请求更改语言区域。

 -- 方法: XMLReader.getFeature (featurename)

     返回 `featurename' 特性的当前设置。 如果特性无法被识别，则会引发
     ‘SAXNotRecognizedException’。 在 *note xml.sax.handler: 13d. 模块中
     列出了常见的特性名称。

 -- 方法: XMLReader.setFeature (featurename, value)

     将 `featurename' 设为 `value'。 如果特性无法被识别，则会引发
     ‘SAXNotRecognizedException’。 如果特性或其设置不被解析器所支持，则
     会引发 `SAXNotSupportedException'。

 -- 方法: XMLReader.getProperty (propertyname)

     返回 `propertyname' 属性的当前设置。 如果属性无法被识别，则会引发
     ‘SAXNotRecognizedException’。 在 *note xml.sax.handler: 13d. 模块中
     列出了常见的属性名称。

 -- 方法: XMLReader.setProperty (propertyname, value)

     将 `propertyname' 设为 `value'。 如果属性无法被识别，则会引发
     ‘SAXNotRecognizedException’。 如果属性或其设置不被解析器所支持，则
     会引发 `SAXNotSupportedException'。


File: python.info,  Node: IncrementalParser 对象,  Next: Locator 对象,  Prev: XMLReader 对象,  Up: xml sax xmlreader --- 用于 XML 解析器的接口

5.20.12.2 IncrementalParser 对象
................................

*note IncrementalParser: 2b42. 的实例额外提供了下列方法:

 -- 方法: IncrementalParser.feed (data)

     处理 `data' 的一个分块。

 -- 方法: IncrementalParser.close ()

     确定文档的结尾。 这将检查只能在结尾处检查的格式是否良好的条件，发起
     调用处理程序，并可能会清理在解析期间分配的资源。

 -- 方法: IncrementalParser.reset ()

     此方法会在调用 close 来重置解析器以便其准备好解析新的文档之后被调用
     。 在 close 之后未调用 reset 即调用 parse 或 feed 的结果是未定义的
     。


File: python.info,  Node: Locator 对象,  Next: InputSource 对象,  Prev: IncrementalParser 对象,  Up: xml sax xmlreader --- 用于 XML 解析器的接口

5.20.12.3 Locator 对象
......................

*note Locator: 2b04. 的实例提供了下列方法:

 -- 方法: Locator.getColumnNumber ()

     返回当前事件开始位置的列号。

 -- 方法: Locator.getLineNumber ()

     返回当前事件开始位置的行号。

 -- 方法: Locator.getPublicId ()

     返回当前事件的公有标识符。

 -- 方法: Locator.getSystemId ()

     返回当前事件的系统标识符。


File: python.info,  Node: InputSource 对象,  Next: Attributes 接口,  Prev: Locator 对象,  Up: xml sax xmlreader --- 用于 XML 解析器的接口

5.20.12.4 InputSource 对象
..........................

 -- 方法: InputSource.setPublicId (id)

     设置该 *note InputSource: 79b. 的公有标识符。

 -- 方法: InputSource.getPublicId ()

     返回此 *note InputSource: 79b. 的公有标识符。

 -- 方法: InputSource.setSystemId (id)

     设置此 *note InputSource: 79b. 的系统标识符。

 -- 方法: InputSource.getSystemId ()

     返回此 *note InputSource: 79b. 的系统标识符。

 -- 方法: InputSource.setEncoding (encoding)

     设置此 *note InputSource: 79b. 的字符编码格式。

     编码格式必须是 XML 编码声明可接受的字符串（参见 XML 建议规范第
     4.3.3 节）。

     如果 *note InputSource: 79b. 还包含一个字符流则 *note InputSource:
     79b. 的 encoding 属性会被忽略。

 -- 方法: InputSource.getEncoding ()

     获取此 InputSource 的字符编码格式。

 -- 方法: InputSource.setByteStream (bytefile)

     设置此输入源的字节流（为 *note binary file: 1cb4. 对象）。

     如果还指定了一个字符流被则 SAX 解析器会忽略此设置，但它将优先使用字
     节流而不是自己打开一个 URI 连接。

     如果应用程序知道字节流的字符编码格式，它应当使用 setEncoding 方法来
     设置它。

 -- 方法: InputSource.getByteStream ()

     获取此输入源的字节流。

     getEncoding 方法将返回该字节流的字符编码格式，如果未知则返回
     ‘None’。

 -- 方法: InputSource.setCharacterStream (charfile)

     设置此输入源的字符流 (为 *note text file: 12b5. 对象)。

     如果指定了一个字符流，SAX 解析器将忽略任何字节流并且不会尝试打开一
     个指向系统标识符的 URI 连接。

 -- 方法: InputSource.getCharacterStream ()

     获取此输入源的字符流。


File: python.info,  Node: Attributes 接口,  Next: AttributesNS 接口,  Prev: InputSource 对象,  Up: xml sax xmlreader --- 用于 XML 解析器的接口

5.20.12.5 ‘Attributes’ 接口
...........................

‘Attributes’ 对象实现了一部分 *note 映射协议: b41.，包括 ‘copy()’,
‘get()’, *note __contains__(): d30, ‘items()’, ‘keys()’ 和 ‘values()’ 等
方法。 还提供了下列方法:

 -- 方法: Attributes.getLength ()

     返回属性的数量。

 -- 方法: Attributes.getNames ()

     返回属性的名称。

 -- 方法: Attributes.getType (name)

     返回属性 `name' 的类型，通常为 ‘'CDATA'’。

 -- 方法: Attributes.getValue (name)

     返回属性 `name' 的值。


File: python.info,  Node: AttributesNS 接口,  Prev: Attributes 接口,  Up: xml sax xmlreader --- 用于 XML 解析器的接口

5.20.12.6 ‘AttributesNS’ 接口
.............................

此接口是 ‘Attributes’ 接口（参见 *note Attributes 接口: 2b24. 章节）的一
个子类型。 那个接口所支持的所有方法在 ‘AttributesNS’ 对象上也都可用。

下列方法也是可用的:

 -- 方法: AttributesNS.getValueByQName (name)

     返回一个限定名称的值。

 -- 方法: AttributesNS.getNameByQName (name)

     返回限定名称 `name' 的 ‘(namespace, localname)’ 对。

 -- 方法: AttributesNS.getQNameByName (name)

     返回 ‘(namespace, localname)’ 对的限定名称。

 -- 方法: AttributesNS.getQNames ()

     返回所有属性的限定名称。


File: python.info,  Node: xml parsers expat --- 使用 Expat 的快速 XML 解析,  Prev: xml sax xmlreader --- 用于 XML 解析器的接口,  Up: 结构化标记处理工具

5.20.13 ‘xml.parsers.expat’ — 使用 Expat 的快速 XML 解析
--------------------------------------------------------

__________________________________________________________________

     警告: ‘pyexpat’ 模块对于恶意构建的数据是不安全的。 如果你需要解析不
     受信任或未经身份验证的数据，请参阅 *note XML 漏洞: 2a03.。

*note xml.parsers.expat: 139. 模块是针对 Expat 非验证 XML 解析器的
Python 接口。 此模块提供了一个扩展类型 ‘xmlparser’，它代表一个 XML 解析
器的当前状态。 在创建一个 ‘xmlparser’ 对象之后，该对象的各个属性可被设置
为相应的处理句柄函数。 随后当将一个 XML 文档送入解析器时，就会为该 XML 文
档中的字符数据和标记调用处理句柄函数。

此模块使用 ‘pyexpat’ 模块来提供对 Expat 解析器的访问。 直接使用
‘pyexpat’ 模块的方式已被弃用。

此模块提供了一个异常和一个类型对象:

 -- 例外: xml.parsers.expat.ExpatError

     此异常会在 Expat 报错时被引发。 请参阅 *note ExpatError 异常: 2b77.
     一节了解有关解读 Expat 错误的更多信息。

 -- 例外: xml.parsers.expat.error

     *note ExpatError: c15. 的别名。

 -- 数据: xml.parsers.expat.XMLParserType

     来自 *note ParserCreate(): 2b7a. 函数的返回值的类型。

*note xml.parsers.expat: 139. 模块包含两个函数:

 -- 函数: xml.parsers.expat.ErrorString (errno)

     返回给定错误号 `errno' 的解释性字符串。

 -- 函数: xml.parsers.expat.ParserCreate (encoding=None,
          namespace_separator=None)

     创建并返回一个新的 ‘xmlparser’ 对象。 如果指定了 `encoding'，它必须
     为指定 XML 数据所使用的编码格式名称的字符串。 Expat 支持的编码格式
     没有 Python 那样多，而且它的编码格式库也不能被扩展；它支持 UTF-8,
     UTF-16, ISO-8859-1 (Latin1) 和 ASCII。 如果给出了 `encoding' (1) 则
     它将覆盖隐式或显式指定的文档编码格式。

     可以选择让 Expat 为你做 XML 命名空间处理，这是通过提供
     `namespace_separator' 值来启用的。 该值必须是一个单字符的字符串；如
     果字符串的长度不合法则将引发 *note ValueError: 1fc. (‘None’ 被视为
     等同于省略)。 当命名空间处理被启用时，属于特定命名空间的元素类型名
     称和属性名称将被展开。 传递给The element name passed to the 元素处
     理句柄 ‘StartElementHandler’ 和 ‘EndElementHandler’ 的元素名称将为
     命名空间 URI，命名空间分隔符和名称的本地部分的拼接。 如果命名空间分
     隔符是一个零字节 (‘chr(0)’) 则命名空间 URI 和本地部分将被直接拼接而
     不带任何分隔符。

     举例来说，如果 `namespace_separator' 被设为空格符 (‘' '’) 并对以下
     文档进行解析:

          <?xml version="1.0"?>
          <root xmlns    = "http://default-namespace.org/"
                xmlns:py = "http://www.python.org/ns/">
            <py:elem1 />
            <elem2 xmlns="" />
          </root>

     ‘StartElementHandler’ 将为每个元素获取以下字符串:

          http://default-namespace.org/ root
          http://www.python.org/ns/ elem1
          elem2

     由于 ‘pyexpat’ 所使用的 ‘Expat’ 库的限制，被返回的 ‘xmlparser’ 实例
     只能被用来解析单个 XML 文档。 请为每个文档调用 ‘ParserCreate’ 来提
     供单独的解析器实例。

参见
....

The Expat XML Parser(2)

     Expat 项目的主页。

* Menu:

* XMLParser对象: XMLParser对象<2>.
* ExpatError 异常::
* 示例: 示例<12>.
* 内容模型描述::
* Expat 错误常量::

   ---------- Footnotes ----------

   (1) (1) 包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如
"UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅
‘https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl’ 和
‘https://www.iana.org/assignments/character-sets/character-sets.xhtml’。

   (2) http://www.libexpat.org/


File: python.info,  Node: XMLParser对象<2>,  Next: ExpatError 异常,  Up: xml parsers expat --- 使用 Expat 的快速 XML 解析

5.20.13.1 XMLParser对象
.......................

‘xmlparser’ 对象具有以下方法:

 -- 方法: xmlparser.Parse (data[, isfinal])

     解析字符串 `data' 的内容，调用适当的处理函数来处理解析后的数据。 在
     对此方法的最后一次调用时 `isfinal' 必须为真值；它允许以片段形式解析
     单个文件，而不是提交多个文件。 `data' 在任何时候都可以为空字符串。

 -- 方法: xmlparser.ParseFile (file)

     解析从对象 `file' 读取的 XML 数据。 `file' 仅需提供 ‘read(nbytes)’
     方法，当没有更多数据可读时将返回空字符串。

 -- 方法: xmlparser.SetBase (base)

     设置要用于解析声明中的系统标识符的相对 URI 的基准。 解析相对标识符
     的任务会留给应用程序进行：这个值将作为 `base' 参数传递给 *note
     ExternalEntityRefHandler(): 2b81, *note NotationDeclHandler():
     2b82. 和 *note UnparsedEntityDeclHandler(): 2b83. 函数。

 -- 方法: xmlparser.GetBase ()

     返回包含之前调用 *note SetBase(): 2b80. 所设置的基准位置的字符串，
     或者如果未调用 *note SetBase(): 2b80. 则返回 ‘None’。

 -- 方法: xmlparser.GetInputContext ()

     将生成当前事件的输入数据以字符串形式返回。 数据为包含文本的实体的编
     码格式。 如果被调用时未激活事件处理句柄，则返回值将为 ‘None’。

 -- 方法: xmlparser.ExternalEntityParserCreate (context[, encoding])

     创建一个“子”解析器，可被用来解析由父解析器解析的内容所引用的外部解
     析实体。 `context' 形参应当是传递给 *note
     ExternalEntityRefHandler(): 2b81. 处理函数的字符串，具体如下所述。
     子解析器创建时 *note ordered_attributes: 2b87. 和 *note
     specified_attributes: 2b88. 会被设为此解析器的值。

 -- 方法: xmlparser.SetParamEntityParsing (flag)

     控制参数实体（包括外部 DTD 子集）的解析。 可能的 `flag' 值有
     ‘XML_PARAM_ENTITY_PARSING_NEVER’,
     ‘XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE’ 和
     ‘XML_PARAM_ENTITY_PARSING_ALWAYS’。 如果该旗标设置成功则返回真值。

 -- 方法: xmlparser.UseForeignDTD ([flag])

     调用时将 `flag' 设为真值（默认）将导致 Expat 调用 *note
     ExternalEntityRefHandler: 2b81. 时将所有参数设为 *note None: 158. 以
     允许加载替代的 DTD。 如果文档不包含文档类型声明，*note
     ExternalEntityRefHandler: 2b81. 仍然会被调用，但 *note
     StartDoctypeDeclHandler: 2b8b. 和 *note EndDoctypeDeclHandler:
     2b8c. 将不会被调用。

     为 `flag' 传入假值将将撤消之前传入真值的调用，除此之外没有其他影响
     。

     此方法只能在调用 *note Parse(): 2b7e. 或 *note ParseFile(): 2b7f. 方
     法之前被调用；在已调用过这两个方法之后调用它会导致引发 *note
     ExpatError: c15. 且 *note code: 1b. 属性被设为
     ‘errors.codes[errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING]’。

‘xmlparser’ 对象具有下列属性:

 -- 属性: xmlparser.buffer_size

     当 *note buffer_text: 2b8e. 为真值时所使用的缓冲区大小。 可以通过将
     此属性赋一个新的整数值来设置一个新的缓冲区大小。 当大小发生改变时，
     缓冲区将被刷新。

 -- 属性: xmlparser.buffer_text

     将此属性设为真值会使得 ‘xmlparser’ 对象缓冲 Expat 所返回的文本内容
     以尽可能地避免多次调用 *note CharacterDataHandler(): 2b8f. 回调。 这
     可以显著地提升性能，因为 Expat 通常会将字符数据在每个行结束的位置上
     进行分块。 此属性默认为假值，但可以在任何时候被更改。

 -- 属性: xmlparser.buffer_used

     当 *note buffer_text: 2b8e. 被启用时，缓冲区中存储的字节数。 这些字
     节数据表示以 UTF-8 编码的文本。 当 *note buffer_text: 2b8e. 为假值
     时此属性没有任何实际意义。

 -- 属性: xmlparser.ordered_attributes

     将该属性设为非零整数会使得各个属性被报告为列表而非字典。 各个属性会
     按照在文档文本中的出现顺序显示。 对于每个属性，将显示两个列表条目：
     属性名和属性值。 （该模块的较旧版本也使用了此格式。） 默认情况下，
     该属性为假值；它可以在任何时候被更改。

 -- 属性: xmlparser.specified_attributes

     如果设为非零整数，解析器将只报告在文档实例中指明的属性而不报告来自
     属性声明的属性。 设置此属性的应用程序需要特别小心地使用从声明中获得
     的附加信息以符合 XML 处理程序的行为标准。 默认情况下，该属性为假值
     ；它可以在任何时候被更改。

下列属性包含与 ‘xmlparser’ 对象遇到的最近发生的错误有关联的值，并且一旦
对 ‘Parse()’ 或 ‘ParseFile()’ 的调用引发了 *note
xml.parsers.expat.ExpatError: c15. 异常就将只包含正确的值。

 -- 属性: xmlparser.ErrorByteIndex

     错误发生位置的字节索引号。

 -- 属性: xmlparser.ErrorCode

     指明问题的的数字代码。 该值可被传给 *note ErrorString(): 2b7b. 函数
     ，或是与在 ‘errors’ 对象中定义的常量之一进行比较。

 -- 属性: xmlparser.ErrorColumnNumber

     错误发生位置的列号。

 -- 属性: xmlparser.ErrorLineNumber

     错误发生位置的行号。

下列属性包含 ‘xmlparser’ 对象中关联到当前解析位置的值。 在回调报告解析事
件期间它们将指示生成事件的字符序列的第一个字符的位置。 当在回调的外部被
调用时，所指示的位置将恰好位于最后的解析事件之后（无论是否存在关联的回调
）。

 -- 属性: xmlparser.CurrentByteIndex

     解析器输入的当前字节索引号。

 -- 属性: xmlparser.CurrentColumnNumber

     解析器输入的当前列号。

 -- 属性: xmlparser.CurrentLineNumber

     解析器输入的当前行号。

可被设置的处理句柄列表。 要在一个 ‘xmlparser’ 对象 `o' 上设置处理句柄，
请使用 ‘o.handlername = func’。 `handlername' 必须从下面的列表中获取，而
`func' 必须为接受正确数量参数的可调用对象。 所有参数均为字符串，除非另外
指明。

 -- 方法: xmlparser.XmlDeclHandler (version, encoding, standalone)

     当解析 XML 声明时被调用。 XML 声明是 XML 建议适用版本、文档文本的编
     码格式，以及可选的“独立”声明的（可选）声明。 `version' 和
     `encoding' 将为字符串，而 `standalone' 在文档被声明为独立时将为
     ‘1’，在文档被声明为非独立时将为 ‘0’，或者在 standalone 短语被省略时
     则为 ‘-1’。 这仅适用于 Expat 的 1.95.0 或更新版本。

 -- 方法: xmlparser.StartDoctypeDeclHandler (doctypeName, systemId,
          publicId, has_internal_subset)

     当 Expat 开始解析文档类型声明 (‘<!DOCTYPE ...’) 时被调用。
     `doctypeName' 会完全按所显示的被提供。 `systemId' 和 `publicId' 形
     参给出所指定的系统和公有标识符，如果被省略则为 ‘None’。 如果文档包
     含内部文档声明子集则 `has_internal_subset' 将为真值。 这要求 Expat
     1.2 或更新的版本。

 -- 方法: xmlparser.EndDoctypeDeclHandler ()

     当 Expat 完成解析文档类型声明时被调用。 这要求 Expat 1.2 或更新版本
     。

 -- 方法: xmlparser.ElementDeclHandler (name, model)

     为每个元素类型声明调用一次。 `name' 为元素类型名称，而 `model' 为内
     容模型的表示形式。

 -- 方法: xmlparser.AttlistDeclHandler (elname, attname, type, default,
          required)

     为一个元素类型的每个已声明属性执行调用。 如果一个属性列表声明声明了
     三个属性，这个处理句柄会被调用三次，每个属性一次。 `elname' 是声明
     所适用的元素的名称而 `attname' 是已声明的属性的名称。 属性类型是作
     为 `type' 传入的字符串；可能的值有 ‘'CDATA'’, ‘'ID'’, ‘'IDREF'’,
     ...  `default' 给出了当属性未被文档实例所指明时该属性的默认值，或是
     为 ‘None’，如果没有默认值 (‘#IMPLIED’ 值) 的话。 如果属性必须在文档
     实例中给出，则 `required' 将为真值。 这要求 Expat 1.95.0 或更新的版
     本。

 -- 方法: xmlparser.StartElementHandler (name, attributes)

     在每个元素开始时被调用。 `name' 是包含元素名称的字符串，而
     `attributes' 是元素的属性。 如果 *note ordered_attributes: 2b87. 为
     真值，则属性为列表形式 (完整描述参见 *note ordered_attributes:
     2b87.)。 否则为将名称映射到值的字典。

 -- 方法: xmlparser.EndElementHandler (name)

     在每个元素结束时被调用。

 -- 方法: xmlparser.ProcessingInstructionHandler (target, data)

     在每次处理指令时调用。

 -- 方法: xmlparser.CharacterDataHandler (data)

     针对字符数据调用。 此方法将被用于普通字符数据、CDATA 标记内容以及可
     忽略的空白符。 需要区分这几种情况的应用程序可以使用 *note
     StartCdataSectionHandler: 2b9e, *note EndCdataSectionHandler: 2b9f.
     和 *note ElementDeclHandler: 2b99. 回调来收集必要的信息。

 -- 方法: xmlparser.UnparsedEntityDeclHandler (entityName, base,
          systemId, publicId, notationName)

     针对未解析（NDATA）实体声明调用。 此方法仅存在于 Expat 库的 1.  2 版
     ；对于更新的版本，请改用 *note EntityDeclHandler: 2ba0.。 （下层
     Expat 库中的对应函数已被声明为过时。）

 -- 方法: xmlparser.EntityDeclHandler (entityName, is_parameter_entity,
          value, base, systemId, publicId, notationName)

     针对所有实体声明被调用。 对于形参和内部实体，`value' 将为给出实体的
     声明内容的字符串；对于外部实体将为 ‘None’。 `notationName' 形参对于
     已解析实体将为 ‘None’，对于未解析实体则为标注的名称。 如果实体为形
     参实体则 `is_parameter_entity' 将为真值而如果为普通实体则为假值（大
     多数应用程序只需要关注普通实体）。 此方法仅从 1.95.0 版 Expat 库开
     始才可用。

 -- 方法: xmlparser.NotationDeclHandler (notationName, base, systemId,
          publicId)

     针对标注声明被调用。 `notationName', `base', `systemId' 和
     `publicId' 如果给出则均应为字符串。 如果省略公有标识符，则
     `publicId' 将为 ‘None’。

 -- 方法: xmlparser.StartNamespaceDeclHandler (prefix, uri)

     当一个元素包含命名空间声明时被调用。 命名空间声明会在为声明所在的元
     素调用 *note StartElementHandler: 2b9b. 之前被处理。

 -- 方法: xmlparser.EndNamespaceDeclHandler (prefix)

     当到达包含命名空间声明的元素的关闭标记时被调用。 此方法会按照调用
     *note StartNamespaceDeclHandler: 2ba1. 以指明每个命名空间作用域的开
     始的逆顺序为元素上的每个命名空间声明调用一次。 对这个处理句柄的调用
     是在相应的 *note EndElementHandler: 2b9c. 之后针对元素的结束而进行
     的。

 -- 方法: xmlparser.CommentHandler (data)

     针对注释被调用。 `data' 是注释的文本，不包括开头的 ‘'<!-’‘-'’ 和末
     尾的 ‘'-’‘->'’。

 -- 方法: xmlparser.StartCdataSectionHandler ()

     在一个 CDATA 节的开头被调用。 需要此方法和 *note
     EndCdataSectionHandler: 2b9f. 以便能够标识 CDATA 节的语法开始和结束
     。

 -- 方法: xmlparser.EndCdataSectionHandler ()

     在一个 CDATA 节的末尾被调用。

 -- 方法: xmlparser.DefaultHandler (data)

     针对 XML 文档中没有指定适用处理句柄的任何字符被调用。 这包括了所有
     属于可被报告的结构的一部分，但未提供处理句柄的字符。

 -- 方法: xmlparser.DefaultHandlerExpand (data)

     这与 *note DefaultHandler(): 2ba4. 相同，但不会抑制内部实体的扩展。
     实体引用将不会被传递给默认处理句柄。

 -- 方法: xmlparser.NotStandaloneHandler ()

     当 XML 文档未被声明为独立文档时被调用。 这种情况发生在出现外部子集
     或对参数实体的引用，但 XML 声明没有在 XML 声明中将 standalone 设为
     ‘yes’ 的时候。 如果这个处理句柄返回 ‘0’，那么解析器将引发
     ‘XML_ERROR_NOT_STANDALONE’ 错误。 如果这个处理句柄没有被设置，那么
     解析器就不会为这个条件引发任何异常。

 -- 方法: xmlparser.ExternalEntityRefHandler (context, base, systemId,
          publicId)

     为对外部实体的引用执行调用。 `base' 为当前的基准，由之前对 *note
     SetBase(): 2b80. 的调用设置。 公有和系统标识符 `systemId' 和
     `publicId' 如果给出则圴为字符串；如果公有标识符未给出，则
     `publicId' 将为 ‘None’。 `context' 是仅根据以下说明来使用的不透明值
     。

     对于要解析的外部实体，这个处理句柄必须被实现。 它负责使用
     ‘ExternalEntityParserCreate(context)’ 来创建子解析器，通过适当的回
     调将其初始化，并对实体进行解析。 这个处理句柄应当返回一个整数；如果
     它返回 ‘0’，则解析器将引发 ‘XML_ERROR_EXTERNAL_ENTITY_HANDLING’ 错
     误，否则解析将会继续。

     如果未提供这个处理句柄，外部实体会由 *note DefaultHandler: 2ba4. 回
     调来报告，如果提供了该回调的话。


File: python.info,  Node: ExpatError 异常,  Next: 示例<12>,  Prev: XMLParser对象<2>,  Up: xml parsers expat --- 使用 Expat 的快速 XML 解析

5.20.13.2 ExpatError 异常
.........................

*note ExpatError: c15. 异常包含几个有趣的属性:

 -- 属性: ExpatError.code

     Expat 对于指定错误的内部错误号。 *note errors.messages: 2ba9. 字典
     会将这些错误号映射到 Expat 的错误消息。 例如:

          from xml.parsers.expat import ParserCreate, ExpatError, errors

          p = ParserCreate()
          try:
              p.Parse(some_xml_document)
          except ExpatError as err:
              print("Error:", errors.messages[err.code])

     *note errors: 13a. 模块也提供了一些错误消息常量和一个将这些消息映射
     回错误码的字典 *note codes: 2baa.，参见下文。

 -- 属性: ExpatError.lineno

     检测到错误所在的行号。 首行的行号为 ‘1’。

 -- 属性: ExpatError.offset

     错误发生在行中的字符偏移量。 首列的列号为 ‘0’。


File: python.info,  Node: 示例<12>,  Next: 内容模型描述,  Prev: ExpatError 异常,  Up: xml parsers expat --- 使用 Expat 的快速 XML 解析

5.20.13.3 示例
..............

以下程序定义了三个处理句柄，会简单地打印出它们的参数。:

     import xml.parsers.expat

     # 3 handler functions
     def start_element(name, attrs):
         print('Start element:', name, attrs)
     def end_element(name):
         print('End element:', name)
     def char_data(data):
         print('Character data:', repr(data))

     p = xml.parsers.expat.ParserCreate()

     p.StartElementHandler = start_element
     p.EndElementHandler = end_element
     p.CharacterDataHandler = char_data

     p.Parse("""<?xml version="1.0"?>
     <parent id="top"><child1 name="paul">Text goes here</child1>
     <child2 name="fred">More text</child2>
     </parent>""", 1)

来自这个程序的输出是:

     Start element: parent {'id': 'top'}
     Start element: child1 {'name': 'paul'}
     Character data: 'Text goes here'
     End element: child1
     Character data: '\n'
     Start element: child2 {'name': 'fred'}
     Character data: 'More text'
     End element: child2
     Character data: '\n'
     End element: parent


File: python.info,  Node: 内容模型描述,  Next: Expat 错误常量,  Prev: 示例<12>,  Up: xml parsers expat --- 使用 Expat 的快速 XML 解析

5.20.13.4 内容模型描述
......................

内容模型是使用嵌套的元组来描述的。 每个元素包含四个值：类型、限定符、名
称和一个子元组。 子元组就是附加的内容模型描述。

前两个字段的值是在 *note xml.parsers.expat.model: 13b. 模块中定义的常量
。 这些常量可分为两组：模型类型组和限定符组。

模型类型组中的常量有:

 -- 数据: xml.parsers.expat.model.XML_CTYPE_ANY

     模型名称所指定的元素被声明为具有 ‘ANY’ 内容模型。

 -- 数据: xml.parsers.expat.model.XML_CTYPE_CHOICE

     命名元素允许从几个选项中选择；这被用于内容模型例如 ‘(A | B | C)’。

 -- 数据: xml.parsers.expat.model.XML_CTYPE_EMPTY

     被声明为 ‘EMPTY’ 的元素具有此模型类型。

 -- 数据: xml.parsers.expat.model.XML_CTYPE_MIXED

 -- 数据: xml.parsers.expat.model.XML_CTYPE_NAME

 -- 数据: xml.parsers.expat.model.XML_CTYPE_SEQ

     代表彼此相连的一系列模型的模型用此模型类型来指明。 这被用于 ‘(A, B,
     C)’ 这样的模型。

限定符组中的常量有:

 -- 数据: xml.parsers.expat.model.XML_CQUANT_NONE

     未给出限定符，这样它可以只出现一次，例如 ‘A’。

 -- 数据: xml.parsers.expat.model.XML_CQUANT_OPT

     可选的模型：它可以出现一次或完全不出现，例如 ‘A?’。

 -- 数据: xml.parsers.expat.model.XML_CQUANT_PLUS

     模型必须出现一次或多次 (例如 ‘A+’)。

 -- 数据: xml.parsers.expat.model.XML_CQUANT_REP

     模型必须出现零次或多次，例如 ‘A*’。


File: python.info,  Node: Expat 错误常量,  Prev: 内容模型描述,  Up: xml parsers expat --- 使用 Expat 的快速 XML 解析

5.20.13.5 Expat 错误常量
........................

下列常量是在 *note xml.parsers.expat.errors: 13a. 模块中提供的。 这些常
量在有错误发生时解读被引发的 ‘ExpatError’ 异常对象的某些属性时很有用处。
出于保持向下兼容性的理由，这些常量的值是错误 `消息' 而不是数字形式的错误
`代码'，为此你可以将它的 *note code: 1b. 属性和
‘errors.codes[errors.XML_ERROR_`CONSTANT_NAME']’ 进行比较。

‘errors’ 模块具有以下属性:

 -- 数据: xml.parsers.expat.errors.codes

     将字符串描述映射到其错误代码的字典。

     3.2 新版功能.

 -- 数据: xml.parsers.expat.errors.messages

     将数字形式的错误代码映射到其字符串描述的字典。

     3.2 新版功能.

 -- 数据: xml.parsers.expat.errors.XML_ERROR_ASYNC_ENTITY

 -- 数据:
          xml.parsers.expat.errors.XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF

     属性值中指向一个外部实体而非内部实体的实体引用。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_BAD_CHAR_REF

     指向一个在 XML 不合法的字符的字符引用 (例如，字符 ‘0’ 或 ’‘&#0;’’)。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_BINARY_ENTITY_REF

     指向一个使用标注声明，因而无法被解析的实体的实体引用。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_DUPLICATE_ATTRIBUTE

     一个属性在一个开始标记中被使用超过一次。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_INCORRECT_ENCODING

 -- 数据: xml.parsers.expat.errors.XML_ERROR_INVALID_TOKEN

     当一个输入字节无法被正确分配给一个字符时引发；例如，在 UTF-8 输入流
     中的 NUL 字节 (值为 ‘0’).

 -- 数据: xml.parsers.expat.errors.XML_ERROR_JUNK_AFTER_DOC_ELEMENT

     在文档元素之后出现空白符以外的内容。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_MISPLACED_XML_PI

     在输入数据开始位置以外的地方发现 XML 声明。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS

     文档不包含任何元素（XML 要求所有文档都包含恰好一个最高层级元素）。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_NO_MEMORY

     Expat 无法在内部分配内存。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_PARAM_ENTITY_REF

     在不被允许的位置发现一个参数实体引用。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_PARTIAL_CHAR

     在输入中发出一个不完整的字符。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_RECURSIVE_ENTITY_REF

     一个实体引用包含了对同一实体的另一个引用；可能是通过不同的名称，并
     可能是间接的引用。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_SYNTAX

     遇到了某个未指明的语法错误。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_TAG_MISMATCH

     一个结束标记不能匹配到最内层的未关闭开始标记。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_UNCLOSED_TOKEN

     某些记号（例如开始标记）在流结束或遇到下一个记号之前还未关闭。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_UNDEFINED_ENTITY

     对一个未定义的实体进行了引用。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_UNKNOWN_ENCODING

     文档编码格式不被 Expat 所支持。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_UNCLOSED_CDATA_SECTION

     一个 CDATA 标记节还未关闭。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_EXTERNAL_ENTITY_HANDLING

 -- 数据: xml.parsers.expat.errors.XML_ERROR_NOT_STANDALONE

     解析器确定文档不是“独立的”但它却在 XML 声明中声明自己是独立的，并且
     ‘NotStandaloneHandler’ 被设置为返回 ‘0’。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_UNEXPECTED_STATE

 -- 数据: xml.parsers.expat.errors.XML_ERROR_ENTITY_DECLARED_IN_PE

 -- 数据: xml.parsers.expat.errors.XML_ERROR_FEATURE_REQUIRES_XML_DTD

     请求了一个需要已编译 DTD 支持的操作，但 Expat 被配置为不带 DTD 支持
     。 此错误应当绝对不会被 *note xml.parsers.expat: 139. 模块的标准构
     建版本所报告。

 -- 数据:
          xml.parsers.expat.errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING

     在解析开始之后请求一个只能在解析开始之前执行的行为改变。 此错误（目
     前）只能由 ‘UseForeignDTD()’ 所引发。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_UNBOUND_PREFIX

     当命名空间处理被启用时发现一个未声明的前缀。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_UNDECLARING_PREFIX

     文档试图移除与某个前缀相关联的命名空间声明。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_INCOMPLETE_PE

     一个参数实体包含不完整的标记。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_XML_DECL

     文档完全未包含任何文档元素。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_TEXT_DECL

     解析一个外部实体中的文本声明时出现错误。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_PUBLICID

     在公有 id 中发现不被允许的字符。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_SUSPENDED

     在挂起的解析器上请求执行操作，但未获得允许。 这包括提供额外输入或停
     止解析器的尝试。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_NOT_SUSPENDED

     在解析器未被挂起的时候执行恢复解析器的尝试。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_ABORTED

     此错误不应当被报告给 Python 应用程序。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_FINISHED

     在一个已经完成解析输入的解析器上请求执行操作，但未获得允许。 这包括
     提供额外输入或停止解析器的尝试。

 -- 数据: xml.parsers.expat.errors.XML_ERROR_SUSPEND_PE

备注
....


File: python.info,  Node: 互联网协议和支持,  Next: 多媒体服务,  Prev: 结构化标记处理工具,  Up: Python 标准库

5.21 互联网协议和支持
=====================

本章介绍的模块实现了互联网协议并支持相关技术。 它们都是用 Python 实现的
。 这些模块中的大多数都需要存在依赖于系统的模块 *note socket: f0. ，目前
大多数流行平台都支持它。 这是一个概述：

* Menu:

* webbrowser: webbrowser --- 方便的Web浏览器控制器. 方便的Web浏览器控制器
* cgi: cgi --- 通用网关接口支持. 通用网关接口支持
* cgitb: cgitb --- 用于 CGI 脚本的回溯管理器. 用于 CGI 脚本的回溯管理器
* wsgiref: wsgiref --- WSGI Utilities and Reference Implementation. WSGI Utilities and Reference Implementation
* urllib: urllib --- URL 处理模块. URL 处理模块
* urllib.request: urllib request --- 用于打开 URL 的可扩展库. 用于打开 URL 的可扩展库
* urllib.response: urllib response --- urllib 使用的 Response 类. urllib 使用的 Response 类
* urllib.parse 用于解析 URL: urllib parse 用于解析 URL.
* urllib.error: urllib error --- urllib request 引发的异常类. urllib.request 引发的异常类
* urllib.robotparser: urllib robotparser --- robots txt 语法分析程序. robots.txt 语法分析程序
* http: http --- HTTP 模块. HTTP 模块
* http.client: http client --- HTTP 协议客户端. HTTP 协议客户端
* ftplib: ftplib --- FTP 协议客户端. FTP 协议客户端
* poplib: poplib --- POP3 协议客户端. POP3 协议客户端
* imaplib: imaplib --- IMAP4 协议客户端. IMAP4 协议客户端
* nntplib: nntplib --- NNTP protocol client. NNTP protocol client
* smtplib ---SMTP协议客户端::
* smtpd: smtpd --- SMTP 服务器. SMTP 服务器
* telnetlib: telnetlib -- Telnet 客户端. Telnet 客户端
* uuid: uuid --- UUID objects according to RFC 4122. UUID objects according to RFC 4122
* socketserver: socketserver --- A framework for network servers. A framework for network servers
* http.server: http server --- HTTP 服务器. HTTP 服务器
* http.cookies: http cookies --- HTTP状态管理. HTTP状态管理
* http.cookiejar —— HTTP 客户端的 Cookie 处理: http cookiejar —— HTTP 客户端的 Cookie 处理.
* xmlrpc: xmlrpc --- XMLRPC 服务端与客户端模块. XMLRPC 服务端与客户端模块
* xmlrpc.client: xmlrpc client --- XML-RPC 客户端访问. XML-RPC 客户端访问
* xmlrpc.server: xmlrpc server --- 基本 XML-RPC 服务器. 基本 XML-RPC 服务器
* ipaddress: ipaddress --- IPv4/IPv6 操作库. IPv4/IPv6 操作库


File: python.info,  Node: webbrowser --- 方便的Web浏览器控制器,  Next: cgi --- 通用网关接口支持,  Up: 互联网协议和支持

5.21.1 ‘webbrowser’ — 方便的Web浏览器控制器
-------------------------------------------

`源码：' Lib/webbrowser.py(1)

__________________________________________________________________

*note webbrowser: 12a. 模块提供了一个高级接口，允许向用户显示基于Web的文
档。 在大多数情况下，只需从该模块调用 *note open(): 2bdd. 函数就可以了。

在 Unix 下，图形浏览器在 X11 下是首选，但如果图形浏览器不可用或 X11 显示
不可用，则将使用文本模式浏览器。 如果使用文本模式浏览器，则调用进程将阻
塞，直到用户退出浏览器。

如果存在环境变量 ‘BROWSER’ ，则将其解释为 *note os.pathsep: 1365. 分隔的
浏览器列表，以便在平台默认值之前尝试。 当列表部分的值包含字符串 ‘％s’ 时
，它被解释为一个文字浏览器命令行，用于替换 ‘％s’ 的参数 URL ；如果该部分
不包含 ‘％s’，则它只被解释为要启动的浏览器的名称。 (2)

对于非 Unix 平台，或者当 Unix 上有远程浏览器时，控制过程不会等待用户完成
浏览器，而是允许远程浏览器在显示界面上维护自己的窗口。 如果 Unix 上没有
远程浏览器，控制进程将启动一个新的浏览器并等待。

脚本 ‘webbrowser’ 可以用作模块的命令行界面。它接受一个 URL 作为参数。还
接受以下可选参数：‘-n’ 如果可能，在新的浏览器窗口中打开 URL ； ‘-t’ 在新
的浏览器页面（“标签”）中打开 URL。这些选择当然是相互排斥的。用法示例:

     python -m webbrowser -t "http://www.python.org"

定义了以下异常：

 -- 例外: webbrowser.Error

     发生浏览器控件错误时引发异常。

定义了以下函数：

 -- 函数: webbrowser.open (url, new=0, autoraise=True)

     使用默认浏览器显示 `url'。 如果 `new' 为 0，则尽可能在同一浏览器窗
     口中打开 `url'。 如果 `new' 为 1，则尽可能打开新的浏览器窗口。 如果
     `new' 为 2，则尽可能打开新的浏览器页面（“标签”）。 如果 `autoraise'
     为 “True”，则会尽可能置前窗口（请注意，在许多窗口管理器下，无论此变
     量的设置如何，都会置前窗口）。

     请注意，在某些平台上，尝试使用此函数打开文件名，可能会起作用并启动
     操作系统的关联程序。 但是，这种方式不被支持也不可移植。

     使用 ‘url’ 参数会引发 *note auditing event: ea1. ‘webbrowser.open’
     。

 -- 函数: webbrowser.open_new (url)

     如果可能，在默认浏览器的新窗口中打开 `url'，否则，在唯一的浏览器窗
     口中打开 `url'。

 -- 函数: webbrowser.open_new_tab (url)

     如果可能，在默认浏览器的新页面（“标签”）中打开 `url'，否则等效于
     *note open_new(): 2bdf.。

 -- 函数: webbrowser.get (using=None)

     返回浏览器类型为 `using' 指定的控制器对象。 如果 `using' 为 ‘None’，
     则返回适用于调用者环境的默认浏览器的控制器。

 -- 函数: webbrowser.register (name, constructor, instance=None, *,
          preferred=False)

     注册 `name' 浏览器类型。 注册浏览器类型后， *note get(): 2be1. 函数
     可以返回该浏览器类型的控制器。 如果没有提供 `instance'，或者为
     ‘None’，`constructor' 将在没有参数的情况下被调用，以在需要时创建实
     例。 如果提供了 `instance'，则永远不会调用 `constructor'，并且可能
     是 ‘None’。

     将 `preferred' 设置为 ‘True’ 使得这个浏览器成为 *note get(): 2be1.
     不带参数调用的首选结果。 否则，只有在您计划设置 ‘BROWSER’ 变量，或
     使用与您声明的处理程序的名称相匹配的非空参数调用 *note get(): 2be1.
     时，此入口点才有用。

     在 3.7 版更改: 添加了仅关键字参数 `preferred'。

预定义了许多浏览器类型。 此表给出了可以传递给 *note get(): 2be1. 函数的
类型名称以及控制器类的相应实例化，这些都在此模块中定义。

类型名                       类名                                          注释
                                                                           
---------------------------------------------------------------------------------------
                                                                           
‘'mozilla'’                  ‘Mozilla('mozilla')’
                             
                                                                           
‘'firefox'’                  ‘Mozilla('mozilla')’
                             
                                                                           
‘'netscape'’                 ‘Mozilla('netscape')’
                             
                                                                           
‘'galeon'’                   ‘Galeon('galeon')’
                             
                                                                           
‘'epiphany'’                 ‘Galeon('epiphany')’
                             
                                                                           
‘'skipstone'’                ‘BackgroundBrowser('skipstone')’
                             
                                                                           
‘'kfmclient'’                ‘Konqueror()’                                 (1)
                                                                           
                                                                           
‘'konqueror'’                ‘Konqueror()’                                 (1)
                                                                           
                                                                           
‘'kfm'’                      ‘Konqueror()’                                 (1)
                                                                           
                                                                           
‘'mosaic'’                   ‘BackgroundBrowser('mosaic')’
                             
                                                                           
‘'opera'’                    ‘Opera()’
                             
                                                                           
‘'grail'’                    ‘Grail()’
                             
                                                                           
‘'links'’                    ‘GenericBrowser('links')’
                             
                                                                           
‘'elinks'’                   ‘Elinks('elinks')’
                             
                                                                           
‘'lynx'’                     ‘GenericBrowser('lynx')’
                             
                                                                           
‘'w3m'’                      ‘GenericBrowser('w3m')’
                             
                                                                           
‘'windows-default'’          ‘WindowsDefault’                              (2)
                                                                           
                                                                           
‘'macosx'’                   ‘MacOSX('default')’                           (3)
                                                                           
                                                                           
‘'safari'’                   ‘MacOSX('safari')’                            (3)
                                                                           
                                                                           
‘'google-chrome'’            ‘Chrome('google-chrome')’
                             
                                                                           
‘'chrome'’                   ‘Chrome('chrome')’
                             
                                                                           
‘'chromium'’                 ‘Chromium('chromium')’
                             
                                                                           
‘'chromium-browser'’         ‘Chromium('chromium-browser')’
                             

注释:

  1. “Konqueror” 是 Unix 的 KDE 桌面环境的文件管理器，只有在 KDE 运行时
     才有意义。 一些可靠地检测 KDE 的方法会很好；仅检查 ‘KDEDIR’ 变量是
     不够的。 另请注意，KDE 2的 ‘konqueror’ 命令，会使用名称 “kfm”—此实
     现选择运行的 Konqueror 的最佳策略。

  2. 仅限 Windows 平台。

  3. 仅限 Mac OS X 平台。

3.3 新版功能: 添加了对 Chrome/Chromium 的支持。

以下是一些简单的例子:

     url = 'http://docs.python.org/'

     # Open URL in a new tab, if a browser window is already open.
     webbrowser.open_new_tab(url)

     # Open URL in new window, raising the window if possible.
     webbrowser.open_new(url)

* Menu:

* 浏览器控制器对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/webbrowser.py

   (2) (1) 这里命名的不带完整路径的可执行文件将在 ‘PATH’ 环境变量给出的
目录中搜索。


File: python.info,  Node: 浏览器控制器对象,  Up: webbrowser --- 方便的Web浏览器控制器

5.21.1.1 浏览器控制器对象
.........................

浏览器控制器提供三个与模块级便捷函数相同的方法：

 -- 方法: controller.open (url, new=0, autoraise=True)

     使用此控制器处理的浏览器显示 `url'。 如果 `new' 为 1，则尽可能打开
     新的浏览器窗口。 如果 `new' 为 2，则尽可能打开新的浏览器页面（“标签
     ”）。

 -- 方法: controller.open_new (url)

     如果可能，在此控制器处理的浏览器的新窗口中打开 `url' ，否则，在唯一
     的浏览器窗口中打开 `url' 。 别名 *note open_new(): 2bdf.。

 -- 方法: controller.open_new_tab (url)

     如果可能，在此控制器处理的浏览器的新页面（“标签”）中打开 `url'，否
     则等效于 *note open_new(): 2bdf.。

备注
....


File: python.info,  Node: cgi --- 通用网关接口支持,  Next: cgitb --- 用于 CGI 脚本的回溯管理器,  Prev: webbrowser --- 方便的Web浏览器控制器,  Up: 互联网协议和支持

5.21.2 ‘cgi’ — 通用网关接口支持
-------------------------------

`源代码：' Lib/cgi.py(1)

__________________________________________________________________

通用网关接口 (CGI) 脚本的支持模块

本模块定义了一些工具供以 Python 编写的 CGI 脚本使用。

* Menu:

* 概述: 概述<11>.
* 使用cgi模块。::
* 更高层级的接口::
* 函数: 函数<8>.
* Caring about security::
* Installing your CGI script on a Unix system::
* Testing your CGI script::
* Debugging CGI scripts::
* Common problems and solutions::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/cgi.py


File: python.info,  Node: 概述<11>,  Next: 使用cgi模块。,  Up: cgi --- 通用网关接口支持

5.21.2.1 概述
.............

CGI 脚本是由 HTTP 服务器发起调用，通常用来处理通过 HTML ‘<FORM>’ 或
‘<ISINDEX>’ 元素提交的用户输入。

在大多数情况下，CGI 脚本存放在服务器的 ‘cgi-bin’ 特殊目录下。 HTTP 服务
器将有关请求的各种信息（例如客户端的主机名、所请求的 URL、查询字符串以及
许多其他内容）放在脚本的 shell 环境中，然后执行脚本，并将脚本的输出发回
到客户端。

脚本的输入也会被连接到客户端，并且有时表单数据也会以此方式来读取；在其他
时候表单数据会通过 URL 的“查询字符串”部分来传递。 本模块的目标是处理不同
的应用场景并向 Python 脚本提供一个更为简单的接口。 它还提供了一些工具为
脚本调试提供帮助，而最近增加的还有对通过表单上传文件的支持（如果你的浏览
器支持该功能的话）。

CGI 脚本的输出应当由两部分组成，并由一个空行分隔。 前一部分包含一些标头
，它们告诉客户端后面会提供何种数据。 生成一个最小化标头部分的 Python 代
码如下所示:

     print("Content-Type: text/html")    # HTML is following
     print()                             # blank line, end of headers

后一部分通常为 HTML，提供给客户端软件来显示格式良好包含标题的文本、内联
图片等内容。 下面是打印一段简单 HTML 的 Python 代码:

     print("<TITLE>CGI script output</TITLE>")
     print("<H1>This is my first CGI script</H1>")
     print("Hello, world!")


File: python.info,  Node: 使用cgi模块。,  Next: 更高层级的接口,  Prev: 概述<11>,  Up: cgi --- 通用网关接口支持

5.21.2.2 使用cgi模块。
......................

通过敲下 ‘import cgi’ 来开始。

当你在写一个新脚本时，考虑加上这些语句:

     import cgitb
     cgitb.enable()

This activates a special exception handler that will display detailed
reports in the Web browser if any errors occur.  If you’d rather not
show the guts of your program to users of your script, you can have the
reports saved to files instead, with code like this:

     import cgitb
     cgitb.enable(display=0, logdir="/path/to/logdir")

在脚本开发期间使用此特性会很有帮助。 *note cgitb: 17. 所产生的报告提供了
在追踪程序问题时能为你节省大量时间的信息。 你可以在完成测试你的脚本并确
信它能正确工作之后再移除 ‘cgitb’ 行。

要获取提交的表单数据，请使用 ‘FieldStorage’ 类。 如果表单包含非 ASCII 字
符，请使用 `encoding' 关键字参数并设置为文档所定义的编码格式值。 它通常
包含在 HTML 文档的 HEAD 部分的 META 标签中或者由 ‘Content-Type’ 标头所指
明。 这会从标准输入或环境读取表单内容（取决于根据 CGI 标准设置的多个环境
变量的值）。 由于它可能会消耗标准输入，它应当只被实例化一次。

‘FieldStorage’ 实例可以像 Python 字典一样来检索。 它允许通过 *note in:
7ac. 运算符进行成员检测，也支持标准字典方法 *note keys(): c32. 和内置函
数 *note len(): 151.。 包含空字符串的表单字段会被忽略而不会出现在字典中
；要保留这样的值，请在创建 ‘FieldStorage’ 实例时为可选的
`keep_blank_values' 关键字形参提供一个真值。

举例来说，下面的代码（假定 ‘Content-Type’ 标头和空行已经被打印）会检查字
段 ‘name’ 和 ‘addr’ 是否均被设为非空字符串:

     form = cgi.FieldStorage()
     if "name" not in form or "addr" not in form:
         print("<H1>Error</H1>")
         print("Please fill in the name and addr fields.")
         return
     print("<p>name:", form["name"].value)
     print("<p>addr:", form["addr"].value)
     ...further form processing here...

在这里的字段通过 ‘form[key]’ 来访问，它们本身就是 ‘FieldStorage’ (或
‘MiniFieldStorage’，取决于表单的编码格式) 的实例。 实例的 ‘value’ 属性会
产生字段的字符串值。 ‘getvalue()’ 方法直接返回这个字符串；它还接受可选的
第二个参数作为当请求的键不存在时要返回的默认值。

如果提交的表单数据包含一个以上的同名字段，由 ‘form[key]’ 所提取的对象将
不是一个 ‘FieldStorage’ 或 ‘MiniFieldStorage’ 实例而是由这种实例组成的列
表。 类似地，在这种情况下，‘form.getvalue(key)’ 将会返回一个字符串列表。
如果你预计到这种可能性（当你的 HTML 表单包含多个同名字段时），请使用
*note getlist(): 2bee. 方法，它总是返回一个值的列表（这样你就不需要对只
有单个项的情况进行特别处理）。 例如，这段代码拼接了任意数量的 username 字
段，以逗号进行分隔:

     value = form.getlist("username")
     usernames = ",".join(value)

如果一个字段是代表上传的文件，请通过 ‘value’ 属性访问该值或是通过
‘getvalue()’ 方法以字节形式将整个文件读入内存。 这可能不是你想要的结果。
你可以通过测试 ‘filename’ 属性或 ‘file’ 属性来检测上传的文件。 然后你可
以从 ‘file’ 属性读取数据，直到它作为 ‘FieldStorage’ 实例的垃圾回收的一部
分被自动关闭 (*note read(): 70b. 和 *note readline(): 1713. 方法将返回字
节数据):

     fileitem = form["userfile"]
     if fileitem.file:
         # It's an uploaded file; count lines
         linecount = 0
         while True:
             line = fileitem.file.readline()
             if not line: break
             linecount = linecount + 1

‘FieldStorage’ 对象还支持在 *note with: 6f2. 语句中使用，该语句结束时将
自动关闭它们。

如果在获取上传文件的内容时遇到错误（例如，当用户点击回退或取消按钮中断表
单提交时）该字段中对象的 ‘done’ 属性值将被设为 -1。

文件上传标准草案考虑到了从一个字段上传多个文件的可能性（使用递归的
‘multipart/*’ 编码格式）。 当这种情况发生时，该条目将是一个类似字典的
‘FieldStorage’ 条目。 这可以通过检测它的 ‘type’ 属性来确定，该属性应当是
‘multipart/form-data’ (或者可能是匹配 ‘multipart/*’ 的其他 MIME 类型)。
在这种情况下，它可以像最高层级的表单对象一样被递归地迭代处理。

当一个表单按“旧”格式提交时（即以查询字符串或是单个
‘application/x-www-form-urlencoded’ 类型的数据部分的形式），这些条目实际
上将是 ‘MiniFieldStorage’ 类的实例。 在这种情况下，‘list’, ‘file’ 和
‘filename’ 属性将总是为 ‘None’。

通过 POST 方式提交并且也带有查询字符串的表单将同时包含 ‘FieldStorage’ 和
‘MiniFieldStorage’ 条目。

在 3.4 版更改: ‘file’ 属性会在创建 ‘FieldStorage’ 实例的垃圾回收操作中被
自动关闭。

在 3.5 版更改: 为 ‘FieldStorage’ 类增加了上下文管理协议支持。


File: python.info,  Node: 更高层级的接口,  Next: 函数<8>,  Prev: 使用cgi模块。,  Up: cgi --- 通用网关接口支持

5.21.2.3 更高层级的接口
.......................

前面的部分解释了如何使用 ‘FieldStorage’ 类来读取 CGI 表单数据。 本部分则
会描述一个更高层级的接口，它被添加到此类中以允许人们以更为可读和自然的方
式行事。 这个接口并不会完全取代前面的部分所描述的技巧 — 例如它们在高效处
理文件上传时仍然很有用处。

此接口由两个简单的方法组成。 你可以使用这两个方法以通用的方式处理表单数
据，而无需担心在一个名称下提交的值是只有一个还是有多个。

在前面的部分中，你已学会当你预期用户在一个名称下提交超过一个值的时候编写
以下代码:

     item = form.getvalue("item")
     if isinstance(item, list):
         # The user is requesting more than one item.
     else:
         # The user is requesting only one item.

这种情况很常见，例如当一个表单包含具有相同名称的一组复选框的时候:

     <input type="checkbox" name="item" value="1" />
     <input type="checkbox" name="item" value="2" />

但是在多数情况下，一个表单中的一个特定名称只对应一个表单控件。 因此你可
能会编写包含以下代码的脚本:

     user = form.getvalue("user").upper()

这段代码的问题在于你绝不能预期客户端会向你的脚本提供合法的输入。 举例来
说，如果一个好奇的用户向查询字符串添加了另一个 ‘user=foo’ 对，则该脚本将
会崩溃，因为在这种情况下 ‘getvalue("user")’ 方法调用将返回一个列表而不是
字符串。 在一个列表上调用 *note upper(): 166e. 方法是不合法的（因为列表
并没有这个方法）因而会引发 *note AttributeError: 3a3. 异常。

因此，读取表单数据值的正确方式应当总是使用检查所获取的值是单一值还是值列
表的代码。 这很麻烦并且会使脚本缺乏可读性。

一种更便捷的方式是使用这个更高层级接口所提供的 *note getfirst(): 2bf0. 和
*note getlist(): 2bee. 方法。

 -- 方法: FieldStorage.getfirst (name, default=None)

     此方法总是只返回与表单字段 `name' 相关联的单一值。 此方法在同一名称
     下提交了多个值的情况下将仅返回第一个值。 请注意所接收的值顺序在不同
     浏览器上可能发生变化因而是不确定的。 (1) 如果指定的表单字段或值不存
     在则此方法将返回可选形参 `default' 所指定的值。 如果未指定此形参则
     默认值为 ‘None’。

 -- 方法: FieldStorage.getlist (name)

     此方法总是返回与表单字段 `name' 相关联的值列表。 如果 `name' 指定的
     表单字段或值不存在则此方法将返回一个空列表。 如果指定的表单字段只包
     含一个值则它将返回只有一项的列表。

使用这两个方法你将能写出优雅简洁的代码:

     import cgi
     form = cgi.FieldStorage()
     user = form.getfirst("user", "").upper()    # This way it's safe.
     for item in form.getlist("item"):
         do_something(item)

   ---------- Footnotes ----------

   (1) (1) Note that some recent versions of the HTML specification do
state what order the field values should be supplied in, but knowing
whether a request was received from a conforming browser, or even from a
browser at all, is tedious and error-prone.


File: python.info,  Node: 函数<8>,  Next: Caring about security,  Prev: 更高层级的接口,  Up: cgi --- 通用网关接口支持

5.21.2.4 函数
.............

These are useful if you want more control, or if you want to employ some
of the algorithms implemented in this module in other circumstances.

 -- 函数: cgi.parse (fp=None, environ=os.environ,
          keep_blank_values=False, strict_parsing=False, separator="&")

     Parse a query in the environment or from a file (the file defaults
     to ‘sys.stdin’).  The `keep_blank_values', `strict_parsing' and
     `separator' parameters are passed to *note urllib.parse.parse_qs():
     2ec. unchanged.

     在 3.8.8 版更改: Added the `separator' parameter.

 -- 函数: cgi.parse_multipart (fp, pdict, encoding="utf-8",
          errors="replace", separator="&")

     Parse input of type ‘multipart/form-data’ (for file uploads).
     Arguments are `fp' for the input file, `pdict' for a dictionary
     containing other parameters in the ‘Content-Type’ header, and
     `encoding', the request encoding.

     Returns a dictionary just like *note urllib.parse.parse_qs(): 2ec.:
     keys are the field names, each value is a list of values for that
     field.  For non-file fields, the value is a list of strings.

     This is easy to use but not much good if you are expecting
     megabytes to be uploaded — in that case, use the ‘FieldStorage’
     class instead which is much more flexible.

     在 3.7 版更改: Added the `encoding' and `errors' parameters.  For
     non-file fields, the value is now a list of strings, not bytes.

     在 3.8.8 版更改: Added the `separator' parameter.

 -- 函数: cgi.parse_header (string)

     Parse a MIME header (such as ‘Content-Type’) into a main value and
     a dictionary of parameters.

 -- 函数: cgi.test ()

     Robust test CGI script, usable as main program.  Writes minimal
     HTTP headers and formats all information provided to the script in
     HTML form.

 -- 函数: cgi.print_environ ()

     Format the shell environment in HTML.

 -- 函数: cgi.print_form (form)

     Format a form in HTML.

 -- 函数: cgi.print_directory ()

     Format the current directory in HTML.

 -- 函数: cgi.print_environ_usage ()

     Print a list of useful (used by CGI) environment variables in HTML.


File: python.info,  Node: Caring about security,  Next: Installing your CGI script on a Unix system,  Prev: 函数<8>,  Up: cgi --- 通用网关接口支持

5.21.2.5 Caring about security
..............................

There’s one important rule: if you invoke an external program (via the
*note os.system(): dc9. or *note os.popen(): 2aa. functions.  or others
with similar functionality), make very sure you don’t pass arbitrary
strings received from the client to the shell.  This is a well-known
security hole whereby clever hackers anywhere on the Web can exploit a
gullible CGI script to invoke arbitrary shell commands.  Even parts of
the URL or field names cannot be trusted, since the request doesn’t have
to come from your form!

To be on the safe side, if you must pass a string gotten from a form to
a shell command, you should make sure the string contains only
alphanumeric characters, dashes, underscores, and periods.


File: python.info,  Node: Installing your CGI script on a Unix system,  Next: Testing your CGI script,  Prev: Caring about security,  Up: cgi --- 通用网关接口支持

5.21.2.6 Installing your CGI script on a Unix system
....................................................

Read the documentation for your HTTP server and check with your local
system administrator to find the directory where CGI scripts should be
installed; usually this is in a directory ‘cgi-bin’ in the server tree.

Make sure that your script is readable and executable by "others"; the
Unix file mode should be ‘0o755’ octal (use ‘chmod 0755 filename’).
Make sure that the first line of the script contains ‘#!’ starting in
column 1 followed by the pathname of the Python interpreter, for
instance:

     #!/usr/local/bin/python

Make sure the Python interpreter exists and is executable by "others".

Make sure that any files your script needs to read or write are readable
or writable, respectively, by "others" — their mode should be ‘0o644’
for readable and ‘0o666’ for writable.  This is because, for security
reasons, the HTTP server executes your script as user "nobody", without
any special privileges.  It can only read (write, execute) files that
everybody can read (write, execute).  The current directory at execution
time is also different (it is usually the server’s cgi-bin directory)
and the set of environment variables is also different from what you get
when you log in.  In particular, don’t count on the shell’s search path
for executables ( ‘PATH’) or the Python module search path ( *note
PYTHONPATH: 95b.) to be set to anything interesting.

If you need to load modules from a directory which is not on Python’s
default module search path, you can change the path in your script,
before importing other modules.  For example:

     import sys
     sys.path.insert(0, "/usr/home/joe/lib/python")
     sys.path.insert(0, "/usr/local/lib/python")

(This way, the directory inserted last will be searched first!)

Instructions for non-Unix systems will vary; check your HTTP server’s
documentation (it will usually have a section on CGI scripts).


File: python.info,  Node: Testing your CGI script,  Next: Debugging CGI scripts,  Prev: Installing your CGI script on a Unix system,  Up: cgi --- 通用网关接口支持

5.21.2.7 Testing your CGI script
................................

Unfortunately, a CGI script will generally not run when you try it from
the command line, and a script that works perfectly from the command
line may fail mysteriously when run from the server.  There’s one reason
why you should still test your script from the command line: if it
contains a syntax error, the Python interpreter won’t execute it at all,
and the HTTP server will most likely send a cryptic error to the client.

Assuming your script has no syntax errors, yet it does not work, you
have no choice but to read the next section.


File: python.info,  Node: Debugging CGI scripts,  Next: Common problems and solutions,  Prev: Testing your CGI script,  Up: cgi --- 通用网关接口支持

5.21.2.8 Debugging CGI scripts
..............................

First of all, check for trivial installation errors — reading the
section above on installing your CGI script carefully can save you a lot
of time.  If you wonder whether you have understood the installation
procedure correctly, try installing a copy of this module file
(‘cgi.py’) as a CGI script.  When invoked as a script, the file will
dump its environment and the contents of the form in HTML form.  Give it
the right mode etc, and send it a request.  If it’s installed in the
standard ‘cgi-bin’ directory, it should be possible to send it a request
by entering a URL into your browser of the form:

     http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home

If this gives an error of type 404, the server cannot find the script –
perhaps you need to install it in a different directory.  If it gives
another error, there’s an installation problem that you should fix
before trying to go any further.  If you get a nicely formatted listing
of the environment and form content (in this example, the fields should
be listed as "addr" with value "At Home" and "name" with value "Joe
Blow"), the ‘cgi.py’ script has been installed correctly.  If you follow
the same procedure for your own script, you should now be able to debug
it.

The next step could be to call the *note cgi: 16. module’s *note test():
106. function from your script: replace its main code with the single
statement

     cgi.test()

This should produce the same results as those gotten from installing the
‘cgi.py’ file itself.

When an ordinary Python script raises an unhandled exception (for
whatever reason: of a typo in a module name, a file that can’t be
opened, etc.), the Python interpreter prints a nice traceback and exits.
While the Python interpreter will still do this when your CGI script
raises an exception, most likely the traceback will end up in one of the
HTTP server’s log files, or be discarded altogether.

Fortunately, once you have managed to get your script to execute `some'
code, you can easily send tracebacks to the Web browser using the *note
cgitb: 17. module.  If you haven’t done so already, just add the lines:

     import cgitb
     cgitb.enable()

to the top of your script.  Then try running it again; when a problem
occurs, you should see a detailed report that will likely make apparent
the cause of the crash.

If you suspect that there may be a problem in importing the *note cgitb:
17. module, you can use an even more robust approach (which only uses
built-in modules):

     import sys
     sys.stderr = sys.stdout
     print("Content-Type: text/plain")
     print()
     ...your code here...

This relies on the Python interpreter to print the traceback.  The
content type of the output is set to plain text, which disables all HTML
processing.  If your script works, the raw HTML will be displayed by
your client.  If it raises an exception, most likely after the first two
lines have been printed, a traceback will be displayed.  Because no HTML
interpretation is going on, the traceback will be readable.


File: python.info,  Node: Common problems and solutions,  Prev: Debugging CGI scripts,  Up: cgi --- 通用网关接口支持

5.21.2.9 Common problems and solutions
......................................

   * Most HTTP servers buffer the output from CGI scripts until the
     script is completed.  This means that it is not possible to display
     a progress report on the client’s display while the script is
     running.

   * Check the installation instructions above.

   * Check the HTTP server’s log files.  (‘tail -f logfile’ in a
     separate window may be useful!)

   * Always check a script for syntax errors first, by doing something
     like ‘python script.py’.

   * If your script does not have any syntax errors, try adding ‘import
     cgitb; cgitb.enable()’ to the top of the script.

   * When invoking external programs, make sure they can be found.
     Usually, this means using absolute path names — ‘PATH’ is usually
     not set to a very useful value in a CGI script.

   * When reading or writing external files, make sure they can be read
     or written by the userid under which your CGI script will be
     running: this is typically the userid under which the web server is
     running, or some explicitly specified userid for a web server’s
     ‘suexec’ feature.

   * Don’t try to give a CGI script a set-uid mode.  This doesn’t work
     on most systems, and is a security liability as well.

备注
....


File: python.info,  Node: cgitb --- 用于 CGI 脚本的回溯管理器,  Next: wsgiref --- WSGI Utilities and Reference Implementation,  Prev: cgi --- 通用网关接口支持,  Up: 互联网协议和支持

5.21.3 ‘cgitb’ — 用于 CGI 脚本的回溯管理器
------------------------------------------

`源代码:' Lib/cgitb.py(1)

__________________________________________________________________

*note cgitb: 17. 模块提供了用于 Python 脚本的特殊异常处理程序。 （这个名
称有一点误导性。 它最初是设计用来显示 HTML 格式的 CGI 脚本详细回溯信息。
但后来被一般化为也可显示纯文本格式的回溯信息。） 激活这个模块之后，如果
发生了未被捕获的异常，将会显示详细的已格式化的报告。 报告显示内容包括每
个层级的源代码摘录，还有当前正在运行的函数的参数和局部变量值，以帮助你调
试问题。 你也可以选择将此信息保存至文件而不是将其发送至浏览器。

要启用此特性，只需简单地将此代码添加到你的 CGI 脚本的最顶端:

     import cgitb
     cgitb.enable()

*note enable(): 2c01. 函数的选项可以控制是将报告显示在浏览器中，还是将报
告记录到文件供以后进行分析。

 -- 函数: cgitb.enable (display=1, logdir=None, context=5,
          format="html")

     此函数可通过设置 *note sys.excepthook: e6b. 的值以使 *note cgitb:
     17. 模块接管解释器默认的异常处理机制。

     可选参数 `display' 默认为 ‘1’ 并可被设为 ‘0’ 来停止将回溯发送至浏览
     器。 如果给出了参数 `logdir'，则回溯会被写入文件。 `logdir' 的值应
     当是一个用于存放所写入文件的目录。 可选参数 `context' 是要在回溯中
     的当前源代码行前后显示的上下文行数；默认为 ‘5’。 如果可选参数
     `format' 为 ‘"html"’，输出将为 HTML 格式。 任何其它值都会强制启用纯
     文本输出。 默认取值为 ‘"html"’。

 -- 函数: cgitb.text (info, context=5)

     此函数用于处理 `info' (一个包含 *note sys.exc_info(): c67. 返回结果
     的 3 元组) 所描述的异常，将其回溯格式化为文本并将结果作为字符串返回
     。 可选参数 `context' 是要在回溯中的当前源码行前后显示的上下文行数
     ；默认为 ‘5’。

 -- 函数: cgitb.html (info, context=5)

     此函数用于处理 `info' (一个包含 *note sys.exc_info(): c67. 返回结果
     的 3 元组) 所描述的异常，将其回溯格式化为 HTML 并将结果作为字符串返
     回。 可选参数 `context' 是要在回溯中的当前源码行前后显示的上下文行
     数；默认为 ‘5’。

 -- 函数: cgitb.handler (info=None)

     此函数使用默认设置处理异常（即在浏览器中显示报告，但不记录到文件）
     。 当你捕获了一个异常并希望使用 *note cgitb: 17. 来报告它时可以使用
     此函数。 可选的 `info' 参数应为一个包含异常类型，异常值和回溯对象的
     3 元组，与 *note sys.exc_info(): c67. 所返回的元组完全一致。 如果未
     提供 `info' 参数，则会从 *note sys.exc_info(): c67. 获取当前异常。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/cgitb.py


File: python.info,  Node: wsgiref --- WSGI Utilities and Reference Implementation,  Next: urllib --- URL 处理模块,  Prev: cgitb --- 用于 CGI 脚本的回溯管理器,  Up: 互联网协议和支持

5.21.4 ‘wsgiref’ — WSGI Utilities and Reference Implementation
--------------------------------------------------------------

__________________________________________________________________

The Web Server Gateway Interface (WSGI) is a standard interface between
web server software and web applications written in Python.  Having a
standard interface makes it easy to use an application that supports
WSGI with a number of different web servers.

Only authors of web servers and programming frameworks need to know
every detail and corner case of the WSGI design.  You don’t need to
understand every detail of WSGI just to install a WSGI application or to
write a web application using an existing framework.

*note wsgiref: 12d. is a reference implementation of the WSGI
specification that can be used to add WSGI support to a web server or
framework.  It provides utilities for manipulating WSGI environment
variables and response headers, base classes for implementing WSGI
servers, a demo HTTP server that serves WSGI applications, and a
validation tool that checks WSGI servers and applications for
conformance to the WSGI specification ( PEP 3333(1)).

See wsgi.readthedocs.io(2) for more information about WSGI, and links to
tutorials and other resources.

* Menu:

* wsgiref.util: wsgiref util -- WSGI environment utilities. WSGI environment utilities
* wsgiref.headers: wsgiref headers -- WSGI response header tools. WSGI response header tools
* wsgiref.simple_server: wsgiref simple_server -- a simple WSGI HTTP server. a simple WSGI HTTP server
* wsgiref.validate: wsgiref validate --- WSGI conformance checker. WSGI conformance checker
* wsgiref.handlers: wsgiref handlers -- server/gateway base classes. server/gateway base classes
* 例子: 例子<20>.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3333

   (2) https://wsgi.readthedocs.io/


File: python.info,  Node: wsgiref util -- WSGI environment utilities,  Next: wsgiref headers -- WSGI response header tools,  Up: wsgiref --- WSGI Utilities and Reference Implementation

5.21.4.1 ‘wsgiref.util’ – WSGI environment utilities
....................................................

This module provides a variety of utility functions for working with
WSGI environments.  A WSGI environment is a dictionary containing HTTP
request variables as described in PEP 3333(1).  All of the functions
taking an `environ' parameter expect a WSGI-compliant dictionary to be
supplied; please see PEP 3333(2) for a detailed specification.

 -- 函数: wsgiref.util.guess_scheme (environ)

     Return a guess for whether ‘wsgi.url_scheme’ should be "http" or
     "https", by checking for a ‘HTTPS’ environment variable in the
     `environ' dictionary.  The return value is a string.

     This function is useful when creating a gateway that wraps CGI or a
     CGI-like protocol such as FastCGI. Typically, servers providing
     such protocols will include a ‘HTTPS’ variable with a value of "1",
     "yes", or "on" when a request is received via SSL. So, this
     function returns "https" if such a value is found, and "http"
     otherwise.

 -- 函数: wsgiref.util.request_uri (environ, include_query=True)

     Return the full request URI, optionally including the query string,
     using the algorithm found in the "URL Reconstruction" section of
     PEP 3333(3).  If `include_query' is false, the query string is not
     included in the resulting URI.

 -- 函数: wsgiref.util.application_uri (environ)

     Similar to *note request_uri(): 2c09, except that the ‘PATH_INFO’
     and ‘QUERY_STRING’ variables are ignored.  The result is the base
     URI of the application object addressed by the request.

 -- 函数: wsgiref.util.shift_path_info (environ)

     Shift a single name from ‘PATH_INFO’ to ‘SCRIPT_NAME’ and return
     the name.  The `environ' dictionary is `modified' in-place; use a
     copy if you need to keep the original ‘PATH_INFO’ or ‘SCRIPT_NAME’
     intact.

     If there are no remaining path segments in ‘PATH_INFO’, ‘None’ is
     returned.

     Typically, this routine is used to process each portion of a
     request URI path, for example to treat the path as a series of
     dictionary keys.  This routine modifies the passed-in environment
     to make it suitable for invoking another WSGI application that is
     located at the target URI. For example, if there is a WSGI
     application at ‘/foo’, and the request URI path is ‘/foo/bar/baz’,
     and the WSGI application at ‘/foo’ calls *note shift_path_info():
     2c0b, it will receive the string "bar", and the environment will be
     updated to be suitable for passing to a WSGI application at
     ‘/foo/bar’.  That is, ‘SCRIPT_NAME’ will change from ‘/foo’ to
     ‘/foo/bar’, and ‘PATH_INFO’ will change from ‘/bar/baz’ to ‘/baz’.

     When ‘PATH_INFO’ is just a "/", this routine returns an empty
     string and appends a trailing slash to ‘SCRIPT_NAME’, even though
     empty path segments are normally ignored, and ‘SCRIPT_NAME’ doesn’t
     normally end in a slash.  This is intentional behavior, to ensure
     that an application can tell the difference between URIs ending in
     ‘/x’ from ones ending in ‘/x/’ when using this routine to do object
     traversal.

 -- 函数: wsgiref.util.setup_testing_defaults (environ)

     Update `environ' with trivial defaults for testing purposes.

     This routine adds various parameters required for WSGI, including
     ‘HTTP_HOST’, ‘SERVER_NAME’, ‘SERVER_PORT’, ‘REQUEST_METHOD’,
     ‘SCRIPT_NAME’, ‘PATH_INFO’, and all of the PEP 3333(4)-defined
     ‘wsgi.*’ variables.  It only supplies default values, and does not
     replace any existing settings for these variables.

     This routine is intended to make it easier for unit tests of WSGI
     servers and applications to set up dummy environments.  It should
     NOT be used by actual WSGI servers or applications, since the data
     is fake!

     用法示例：

          from wsgiref.util import setup_testing_defaults
          from wsgiref.simple_server import make_server

          # A relatively simple WSGI application. It's going to print out the
          # environment dictionary after being updated by setup_testing_defaults
          def simple_app(environ, start_response):
              setup_testing_defaults(environ)

              status = '200 OK'
              headers = [('Content-type', 'text/plain; charset=utf-8')]

              start_response(status, headers)

              ret = [("%s: %s\n" % (key, value)).encode("utf-8")
                     for key, value in environ.items()]
              return ret

          with make_server('', 8000, simple_app) as httpd:
              print("Serving on port 8000...")
              httpd.serve_forever()

In addition to the environment functions above, the *note wsgiref.util:
131. module also provides these miscellaneous utilities:

 -- 函数: wsgiref.util.is_hop_by_hop (header_name)

     Return ‘True’ if ’header_name’ is an HTTP/1.1 "Hop-by-Hop" header,
     as defined by RFC 2616(5).

 -- 类: wsgiref.util.FileWrapper (filelike, blksize=8192)

     A wrapper to convert a file-like object to an *note iterator: 104b.
     The resulting objects support both *note __getitem__(): 280. and
     *note __iter__(): 517. iteration styles, for compatibility with
     Python 2.1 and Jython.  As the object is iterated over, the
     optional `blksize' parameter will be repeatedly passed to the
     `filelike' object’s ‘read()’ method to obtain bytestrings to yield.
     When ‘read()’ returns an empty bytestring, iteration is ended and
     is not resumable.

     If `filelike' has a ‘close()’ method, the returned object will also
     have a ‘close()’ method, and it will invoke the `filelike' object’s
     ‘close()’ method when called.

     用法示例：

          from io import StringIO
          from wsgiref.util import FileWrapper

          # We're using a StringIO-buffer for as the file-like object
          filelike = StringIO("This is an example file-like object"*10)
          wrapper = FileWrapper(filelike, blksize=5)

          for chunk in wrapper:
              print(chunk)

     3.8 版后已移除: 对 *note 序列协议: 280. 的支持已被弃用。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3333

   (2) https://www.python.org/dev/peps/pep-3333

   (3) https://www.python.org/dev/peps/pep-3333

   (4) https://www.python.org/dev/peps/pep-3333

   (5) https://tools.ietf.org/html/rfc2616.html


File: python.info,  Node: wsgiref headers -- WSGI response header tools,  Next: wsgiref simple_server -- a simple WSGI HTTP server,  Prev: wsgiref util -- WSGI environment utilities,  Up: wsgiref --- WSGI Utilities and Reference Implementation

5.21.4.2 ‘wsgiref.headers’ – WSGI response header tools
.......................................................

This module provides a single class, *note Headers: 798, for convenient
manipulation of WSGI response headers using a mapping-like interface.

 -- 类: wsgiref.headers.Headers ([headers])

     Create a mapping-like object wrapping `headers', which must be a
     list of header name/value tuples as described in PEP 3333(1).  The
     default value of `headers' is an empty list.

     *note Headers: 798. objects support typical mapping operations
     including *note __getitem__(): 280, ‘get()’, *note __setitem__():
     c6a, ‘setdefault()’, *note __delitem__(): c6b. and *note
     __contains__(): d30.  For each of these methods, the key is the
     header name (treated case-insensitively), and the value is the
     first value associated with that header name.  Setting a header
     deletes any existing values for that header, then adds a new value
     at the end of the wrapped header list.  Headers’ existing order is
     generally maintained, with new headers added to the end of the
     wrapped list.

     Unlike a dictionary, *note Headers: 798. objects do not raise an
     error when you try to get or delete a key that isn’t in the wrapped
     header list.  Getting a nonexistent header just returns ‘None’, and
     deleting a nonexistent header does nothing.

     *note Headers: 798. objects also support ‘keys()’, ‘values()’, and
     ‘items()’ methods.  The lists returned by ‘keys()’ and ‘items()’
     can include the same key more than once if there is a multi-valued
     header.  The ‘len()’ of a *note Headers: 798. object is the same as
     the length of its ‘items()’, which is the same as the length of the
     wrapped header list.  In fact, the ‘items()’ method just returns a
     copy of the wrapped header list.

     Calling ‘bytes()’ on a *note Headers: 798. object returns a
     formatted bytestring suitable for transmission as HTTP response
     headers.  Each header is placed on a line with its value, separated
     by a colon and a space.  Each line is terminated by a carriage
     return and line feed, and the bytestring is terminated with a blank
     line.

     In addition to their mapping interface and formatting features,
     *note Headers: 798. objects also have the following methods for
     querying and adding multi-valued headers, and for adding headers
     with MIME parameters:

      -- 方法: get_all (name)

          Return a list of all the values for the named header.

          The returned list will be sorted in the order they appeared in
          the original header list or were added to this instance, and
          may contain duplicates.  Any fields deleted and re-inserted
          are always appended to the header list.  If no fields exist
          with the given name, returns an empty list.

      -- 方法: add_header (name, value, **_params)

          Add a (possibly multi-valued) header, with optional MIME
          parameters specified via keyword arguments.

          `name' is the header field to add.  Keyword arguments can be
          used to set MIME parameters for the header field.  Each
          parameter must be a string or ‘None’.  Underscores in
          parameter names are converted to dashes, since dashes are
          illegal in Python identifiers, but many MIME parameter names
          include dashes.  If the parameter value is a string, it is
          added to the header value parameters in the form
          ‘name="value"’.  If it is ‘None’, only the parameter name is
          added.  (This is used for MIME parameters without a value.)
          Example usage:

               h.add_header('content-disposition', 'attachment', filename='bud.gif')

          The above will add a header that looks like this:

               Content-Disposition: attachment; filename="bud.gif"

     在 3.5 版更改: `headers' parameter is optional.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3333


File: python.info,  Node: wsgiref simple_server -- a simple WSGI HTTP server,  Next: wsgiref validate --- WSGI conformance checker,  Prev: wsgiref headers -- WSGI response header tools,  Up: wsgiref --- WSGI Utilities and Reference Implementation

5.21.4.3 ‘wsgiref.simple_server’ – a simple WSGI HTTP server
............................................................

This module implements a simple HTTP server (based on *note http.server:
97.) that serves WSGI applications.  Each server instance serves a
single WSGI application on a given host and port.  If you want to serve
multiple applications on a single host and port, you should create a
WSGI application that parses ‘PATH_INFO’ to select which application to
invoke for each request.  (E.g., using the ‘shift_path_info()’ function
from *note wsgiref.util: 131.)

 -- 函数: wsgiref.simple_server.make_server (host, port, app,
          server_class=WSGIServer, handler_class=WSGIRequestHandler)

     Create a new WSGI server listening on `host' and `port', accepting
     connections for `app'.  The return value is an instance of the
     supplied `server_class', and will process requests using the
     specified `handler_class'.  `app' must be a WSGI application
     object, as defined by PEP 3333(1).

     用法示例：

          from wsgiref.simple_server import make_server, demo_app

          with make_server('', 8000, demo_app) as httpd:
              print("Serving HTTP on port 8000...")

              # Respond to requests until process is killed
              httpd.serve_forever()

              # Alternative: serve one request, then exit
              httpd.handle_request()

 -- 函数: wsgiref.simple_server.demo_app (environ, start_response)

     This function is a small but complete WSGI application that returns
     a text page containing the message "Hello world!"  and a list of
     the key/value pairs provided in the `environ' parameter.  It’s
     useful for verifying that a WSGI server (such as *note
     wsgiref.simple_server: 130.) is able to run a simple WSGI
     application correctly.

 -- 类: wsgiref.simple_server.WSGIServer (server_address,
          RequestHandlerClass)

     Create a *note WSGIServer: 2c14. instance.  `server_address' should
     be a ‘(host,port)’ tuple, and `RequestHandlerClass' should be the
     subclass of *note http.server.BaseHTTPRequestHandler: a16. that
     will be used to process requests.

     You do not normally need to call this constructor, as the *note
     make_server(): 2c12. function can handle all the details for you.

     *note WSGIServer: 2c14. is a subclass of *note
     http.server.HTTPServer: 2c15, so all of its methods (such as
     ‘serve_forever()’ and ‘handle_request()’) are available.  *note
     WSGIServer: 2c14. also provides these WSGI-specific methods:

      -- 方法: set_app (application)

          Sets the callable `application' as the WSGI application that
          will receive requests.

      -- 方法: get_app ()

          Returns the currently-set application callable.

     Normally, however, you do not need to use these additional methods,
     as *note set_app(): 2c16. is normally called by *note
     make_server(): 2c12, and the *note get_app(): 2c17. exists mainly
     for the benefit of request handler instances.

 -- 类: wsgiref.simple_server.WSGIRequestHandler (request,
          client_address, server)

     Create an HTTP handler for the given `request' (i.e.  a socket),
     `client_address' (a ‘(host,port)’ tuple), and `server' (*note
     WSGIServer: 2c14. instance).

     You do not need to create instances of this class directly; they
     are automatically created as needed by *note WSGIServer: 2c14.
     objects.  You can, however, subclass this class and supply it as a
     `handler_class' to the *note make_server(): 2c12. function.  Some
     possibly relevant methods for overriding in subclasses:

      -- 方法: get_environ ()

          Returns a dictionary containing the WSGI environment for a
          request.  The default implementation copies the contents of
          the *note WSGIServer: 2c14. object’s ‘base_environ’ dictionary
          attribute and then adds various headers derived from the HTTP
          request.  Each call to this method should return a new
          dictionary containing all of the relevant CGI environment
          variables as specified in PEP 3333(2).

      -- 方法: get_stderr ()

          Return the object that should be used as the ‘wsgi.errors’
          stream.  The default implementation just returns ‘sys.stderr’.

      -- 方法: handle ()

          Process the HTTP request.  The default implementation creates
          a handler instance using a *note wsgiref.handlers: 12e. class
          to implement the actual WSGI application interface.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3333

   (2) https://www.python.org/dev/peps/pep-3333


File: python.info,  Node: wsgiref validate --- WSGI conformance checker,  Next: wsgiref handlers -- server/gateway base classes,  Prev: wsgiref simple_server -- a simple WSGI HTTP server,  Up: wsgiref --- WSGI Utilities and Reference Implementation

5.21.4.4 ‘wsgiref.validate’ — WSGI conformance checker
......................................................

When creating new WSGI application objects, frameworks, servers, or
middleware, it can be useful to validate the new code’s conformance
using *note wsgiref.validate: 132.  This module provides a function that
creates WSGI application objects that validate communications between a
WSGI server or gateway and a WSGI application object, to check both
sides for protocol conformance.

Note that this utility does not guarantee complete PEP 3333(1)
compliance; an absence of errors from this module does not necessarily
mean that errors do not exist.  However, if this module does produce an
error, then it is virtually certain that either the server or
application is not 100% compliant.

This module is based on the ‘paste.lint’ module from Ian Bicking’s
"Python Paste" library.

 -- 函数: wsgiref.validate.validator (application)

     Wrap `application' and return a new WSGI application object.  The
     returned application will forward all requests to the original
     `application', and will check that both the `application' and the
     server invoking it are conforming to the WSGI specification and to
     RFC 2616(2).

     Any detected nonconformance results in an *note AssertionError:
     103e. being raised; note, however, that how these errors are
     handled is server-dependent.  For example, *note
     wsgiref.simple_server: 130. and other servers based on *note
     wsgiref.handlers: 12e. (that don’t override the error handling
     methods to do something else) will simply output a message that an
     error has occurred, and dump the traceback to ‘sys.stderr’ or some
     other error stream.

     This wrapper may also generate output using the *note warnings:
     127. module to indicate behaviors that are questionable but which
     may not actually be prohibited by PEP 3333(3).  Unless they are
     suppressed using Python command-line options or the *note warnings:
     127. API, any such warnings will be written to ‘sys.stderr’ (`not'
     ‘wsgi.errors’, unless they happen to be the same object).

     用法示例：

          from wsgiref.validate import validator
          from wsgiref.simple_server import make_server

          # Our callable object which is intentionally not compliant to the
          # standard, so the validator is going to break
          def simple_app(environ, start_response):
              status = '200 OK'  # HTTP Status
              headers = [('Content-type', 'text/plain')]  # HTTP Headers
              start_response(status, headers)

              # This is going to break because we need to return a list, and
              # the validator is going to inform us
              return b"Hello World"

          # This is the application wrapped in a validator
          validator_app = validator(simple_app)

          with make_server('', 8000, validator_app) as httpd:
              print("Listening on port 8000....")
              httpd.serve_forever()

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3333

   (2) https://tools.ietf.org/html/rfc2616.html

   (3) https://www.python.org/dev/peps/pep-3333


File: python.info,  Node: wsgiref handlers -- server/gateway base classes,  Next: 例子<20>,  Prev: wsgiref validate --- WSGI conformance checker,  Up: wsgiref --- WSGI Utilities and Reference Implementation

5.21.4.5 ‘wsgiref.handlers’ – server/gateway base classes
.........................................................

This module provides base handler classes for implementing WSGI servers
and gateways.  These base classes handle most of the work of
communicating with a WSGI application, as long as they are given a
CGI-like environment, along with input, output, and error streams.

 -- 类: wsgiref.handlers.CGIHandler

     CGI-based invocation via ‘sys.stdin’, ‘sys.stdout’, ‘sys.stderr’
     and ‘os.environ’.  This is useful when you have a WSGI application
     and want to run it as a CGI script.  Simply invoke
     ‘CGIHandler().run(app)’, where ‘app’ is the WSGI application object
     you wish to invoke.

     This class is a subclass of *note BaseCGIHandler: 2c20. that sets
     ‘wsgi.run_once’ to true, ‘wsgi.multithread’ to false, and
     ‘wsgi.multiprocess’ to true, and always uses *note sys: fe. and
     *note os: c5. to obtain the necessary CGI streams and environment.

 -- 类: wsgiref.handlers.IISCGIHandler

     A specialized alternative to *note CGIHandler: 2c1f, for use when
     deploying on Microsoft’s IIS web server, without having set the
     config allowPathInfo option (IIS>=7) or metabase
     allowPathInfoForScriptMappings (IIS<7).

     By default, IIS gives a ‘PATH_INFO’ that duplicates the
     ‘SCRIPT_NAME’ at the front, causing problems for WSGI applications
     that wish to implement routing.  This handler strips any such
     duplicated path.

     IIS can be configured to pass the correct ‘PATH_INFO’, but this
     causes another bug where ‘PATH_TRANSLATED’ is wrong.  Luckily this
     variable is rarely used and is not guaranteed by WSGI. On IIS<7,
     though, the setting can only be made on a vhost level, affecting
     all other script mappings, many of which break when exposed to the
     ‘PATH_TRANSLATED’ bug.  For this reason IIS<7 is almost never
     deployed with the fix (Even IIS7 rarely uses it because there is
     still no UI for it.).

     There is no way for CGI code to tell whether the option was set, so
     a separate handler class is provided.  It is used in the same way
     as *note CGIHandler: 2c1f, i.e., by calling
     ‘IISCGIHandler().run(app)’, where ‘app’ is the WSGI application
     object you wish to invoke.

     3.2 新版功能.

 -- 类: wsgiref.handlers.BaseCGIHandler (stdin, stdout, stderr, environ,
          multithread=True, multiprocess=False)

     Similar to *note CGIHandler: 2c1f, but instead of using the *note
     sys: fe. and *note os: c5. modules, the CGI environment and I/O
     streams are specified explicitly.  The `multithread' and
     `multiprocess' values are used to set the ‘wsgi.multithread’ and
     ‘wsgi.multiprocess’ flags for any applications run by the handler
     instance.

     This class is a subclass of *note SimpleHandler: 2c22. intended for
     use with software other than HTTP "origin servers".  If you are
     writing a gateway protocol implementation (such as CGI, FastCGI,
     SCGI, etc.)  that uses a ‘Status:’ header to send an HTTP status,
     you probably want to subclass this instead of *note SimpleHandler:
     2c22.

 -- 类: wsgiref.handlers.SimpleHandler (stdin, stdout, stderr, environ,
          multithread=True, multiprocess=False)

     Similar to *note BaseCGIHandler: 2c20, but designed for use with
     HTTP origin servers.  If you are writing an HTTP server
     implementation, you will probably want to subclass this instead of
     *note BaseCGIHandler: 2c20.

     This class is a subclass of *note BaseHandler: fdc.  It overrides
     the *note __init__(): d66, ‘get_stdin()’, ‘get_stderr()’,
     ‘add_cgi_vars()’, ‘_write()’, and ‘_flush()’ methods to support
     explicitly setting the environment and streams via the constructor.
     The supplied environment and streams are stored in the ‘stdin’,
     ‘stdout’, ‘stderr’, and ‘environ’ attributes.

     The *note write(): 592. method of `stdout' should write each chunk
     in full, like *note io.BufferedIOBase: 591.

 -- 类: wsgiref.handlers.BaseHandler

     This is an abstract base class for running WSGI applications.  Each
     instance will handle a single HTTP request, although in principle
     you could create a subclass that was reusable for multiple
     requests.

     *note BaseHandler: fdc. instances have only one method intended for
     external use:

      -- 方法: run (app)

          Run the specified WSGI application, `app'.

     All of the other *note BaseHandler: fdc. methods are invoked by
     this method in the process of running the application, and thus
     exist primarily to allow customizing the process.

     The following methods MUST be overridden in a subclass:

      -- 方法: _write (data)

          Buffer the bytes `data' for transmission to the client.  It’s
          okay if this method actually transmits the data; *note
          BaseHandler: fdc. just separates write and flush operations
          for greater efficiency when the underlying system actually has
          such a distinction.

      -- 方法: _flush ()

          Force buffered data to be transmitted to the client.  It’s
          okay if this method is a no-op (i.e., if *note _write(): 2c24.
          actually sends the data).

      -- 方法: get_stdin ()

          Return an input stream object suitable for use as the
          ‘wsgi.input’ of the request currently being processed.

      -- 方法: get_stderr ()

          Return an output stream object suitable for use as the
          ‘wsgi.errors’ of the request currently being processed.

      -- 方法: add_cgi_vars ()

          Insert CGI variables for the current request into the
          ‘environ’ attribute.

     Here are some other methods and attributes you may wish to
     override.  This list is only a summary, however, and does not
     include every method that can be overridden.  You should consult
     the docstrings and source code for additional information before
     attempting to create a customized *note BaseHandler: fdc. subclass.

     Attributes and methods for customizing the WSGI environment:

      -- 属性: wsgi_multithread

          The value to be used for the ‘wsgi.multithread’ environment
          variable.  It defaults to true in *note BaseHandler: fdc, but
          may have a different default (or be set by the constructor) in
          the other subclasses.

      -- 属性: wsgi_multiprocess

          The value to be used for the ‘wsgi.multiprocess’ environment
          variable.  It defaults to true in *note BaseHandler: fdc, but
          may have a different default (or be set by the constructor) in
          the other subclasses.

      -- 属性: wsgi_run_once

          The value to be used for the ‘wsgi.run_once’ environment
          variable.  It defaults to false in *note BaseHandler: fdc, but
          *note CGIHandler: 2c1f. sets it to true by default.

      -- 属性: os_environ

          The default environment variables to be included in every
          request’s WSGI environment.  By default, this is a copy of
          ‘os.environ’ at the time that *note wsgiref.handlers: 12e. was
          imported, but subclasses can either create their own at the
          class or instance level.  Note that the dictionary should be
          considered read-only, since the default value is shared
          between multiple classes and instances.

      -- 属性: server_software

          If the *note origin_server: 2c2e. attribute is set, this
          attribute’s value is used to set the default ‘SERVER_SOFTWARE’
          WSGI environment variable, and also to set a default ‘Server:’
          header in HTTP responses.  It is ignored for handlers (such as
          *note BaseCGIHandler: 2c20. and *note CGIHandler: 2c1f.) that
          are not HTTP origin servers.

          在 3.3 版更改: The term "Python" is replaced with
          implementation specific term like "CPython", "Jython" etc.

      -- 方法: get_scheme ()

          Return the URL scheme being used for the current request.  The
          default implementation uses the ‘guess_scheme()’ function from
          *note wsgiref.util: 131. to guess whether the scheme should be
          "http" or "https", based on the current request’s ‘environ’
          variables.

      -- 方法: setup_environ ()

          Set the ‘environ’ attribute to a fully-populated WSGI
          environment.  The default implementation uses all of the above
          methods and attributes, plus the *note get_stdin(): 2c26,
          *note get_stderr(): 2c27, and *note add_cgi_vars(): 2c28.
          methods and the *note wsgi_file_wrapper: 2c31. attribute.  It
          also inserts a ‘SERVER_SOFTWARE’ key if not present, as long
          as the *note origin_server: 2c2e. attribute is a true value
          and the *note server_software: 2c2d. attribute is set.

     Methods and attributes for customizing exception handling:

      -- 方法: log_exception (exc_info)

          Log the `exc_info' tuple in the server log.  `exc_info' is a
          ‘(type, value, traceback)’ tuple.  The default implementation
          simply writes the traceback to the request’s ‘wsgi.errors’
          stream and flushes it.  Subclasses can override this method to
          change the format or retarget the output, mail the traceback
          to an administrator, or whatever other action may be deemed
          suitable.

      -- 属性: traceback_limit

          The maximum number of frames to include in tracebacks output
          by the default *note log_exception(): 2c32. method.  If
          ‘None’, all frames are included.

      -- 方法: error_output (environ, start_response)

          This method is a WSGI application to generate an error page
          for the user.  It is only invoked if an error occurs before
          headers are sent to the client.

          This method can access the current error information using
          ‘sys.exc_info()’, and should pass that information to
          `start_response' when calling it (as described in the "Error
          Handling" section of PEP 3333(1)).

          The default implementation just uses the *note error_status:
          2c35, *note error_headers: 2c36, and *note error_body: 2c37.
          attributes to generate an output page.  Subclasses can
          override this to produce more dynamic error output.

          Note, however, that it’s not recommended from a security
          perspective to spit out diagnostics to any old user; ideally,
          you should have to do something special to enable diagnostic
          output, which is why the default implementation doesn’t
          include any.

      -- 属性: error_status

          The HTTP status used for error responses.  This should be a
          status string as defined in PEP 3333(2); it defaults to a 500
          code and message.

      -- 属性: error_headers

          The HTTP headers used for error responses.  This should be a
          list of WSGI response headers (‘(name, value)’ tuples), as
          described in PEP 3333(3).  The default list just sets the
          content type to ‘text/plain’.

      -- 属性: error_body

          The error response body.  This should be an HTTP response body
          bytestring.  It defaults to the plain text, "A server error
          occurred.  Please contact the administrator."

     Methods and attributes for PEP 3333(4)’s "Optional
     Platform-Specific File Handling" feature:

      -- 属性: wsgi_file_wrapper

          A ‘wsgi.file_wrapper’ factory, or ‘None’.  The default value
          of this attribute is the *note wsgiref.util.FileWrapper: 27e.
          class.

      -- 方法: sendfile ()

          Override to implement platform-specific file transmission.
          This method is called only if the application’s return value
          is an instance of the class specified by the *note
          wsgi_file_wrapper: 2c31. attribute.  It should return a true
          value if it was able to successfully transmit the file, so
          that the default transmission code will not be executed.  The
          default implementation of this method just returns a false
          value.

     Miscellaneous methods and attributes:

      -- 属性: origin_server

          This attribute should be set to a true value if the handler’s
          *note _write(): 2c24. and *note _flush(): 2c25. are being used
          to communicate directly to the client, rather than via a
          CGI-like gateway protocol that wants the HTTP status in a
          special ‘Status:’ header.

          This attribute’s default value is true in *note BaseHandler:
          fdc, but false in *note BaseCGIHandler: 2c20. and *note
          CGIHandler: 2c1f.

      -- 属性: http_version

          If *note origin_server: 2c2e. is true, this string attribute
          is used to set the HTTP version of the response set to the
          client.  It defaults to ‘"1.0"’.

 -- 函数: wsgiref.handlers.read_environ ()

     Transcode CGI variables from ‘os.environ’ to PEP 3333(5) "bytes in
     unicode" strings, returning a new dictionary.  This function is
     used by *note CGIHandler: 2c1f. and *note IISCGIHandler: 2c21. in
     place of directly using ‘os.environ’, which is not necessarily
     WSGI-compliant on all platforms and web servers using Python 3 –
     specifically, ones where the OS’s actual environment is Unicode
     (i.e.  Windows), or ones where the environment is bytes, but the
     system encoding used by Python to decode it is anything other than
     ISO-8859-1 (e.g.  Unix systems using UTF-8).

     If you are implementing a CGI-based handler of your own, you
     probably want to use this routine instead of just copying values
     out of ‘os.environ’ directly.

     3.2 新版功能.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3333

   (2) https://www.python.org/dev/peps/pep-3333

   (3) https://www.python.org/dev/peps/pep-3333

   (4) https://www.python.org/dev/peps/pep-3333

   (5) https://www.python.org/dev/peps/pep-3333


File: python.info,  Node: 例子<20>,  Prev: wsgiref handlers -- server/gateway base classes,  Up: wsgiref --- WSGI Utilities and Reference Implementation

5.21.4.6 例子
.............

This is a working "Hello World" WSGI application:

     from wsgiref.simple_server import make_server

     # Every WSGI application must have an application object - a callable
     # object that accepts two arguments. For that purpose, we're going to
     # use a function (note that you're not limited to a function, you can
     # use a class for example). The first argument passed to the function
     # is a dictionary containing CGI-style environment variables and the
     # second variable is the callable object.
     def hello_world_app(environ, start_response):
         status = '200 OK'  # HTTP Status
         headers = [('Content-type', 'text/plain; charset=utf-8')]  # HTTP Headers
         start_response(status, headers)

         # The returned object is going to be printed
         return [b"Hello World"]

     with make_server('', 8000, hello_world_app) as httpd:
         print("Serving on port 8000...")

         # Serve until process is killed
         httpd.serve_forever()

Example of a WSGI application serving the current directory, accept
optional directory and port number (default: 8000) on the command line:

     #!/usr/bin/env python3
     '''
     Small wsgiref based web server. Takes a path to serve from and an
     optional port number (defaults to 8000), then tries to serve files.
     Mime types are guessed from the file names, 404 errors are raised
     if the file is not found. Used for the make serve target in Doc.
     '''
     import sys
     import os
     import mimetypes
     from wsgiref import simple_server, util

     def app(environ, respond):

         fn = os.path.join(path, environ['PATH_INFO'][1:])
         if '.' not in fn.split(os.path.sep)[-1]:
             fn = os.path.join(fn, 'index.html')
         type = mimetypes.guess_type(fn)[0]

         if os.path.exists(fn):
             respond('200 OK', [('Content-Type', type)])
             return util.FileWrapper(open(fn, "rb"))
         else:
             respond('404 Not Found', [('Content-Type', 'text/plain')])
             return [b'not found']

     if __name__ == '__main__':
         path = sys.argv[1] if len(sys.argv) > 1 else os.getcwd()
         port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000
         httpd = simple_server.make_server('', port, app)
         print("Serving {} on port {}, control-C to stop".format(path, port))
         try:
             httpd.serve_forever()
         except KeyboardInterrupt:
             print("Shutting down.")
             httpd.server_close()


File: python.info,  Node: urllib --- URL 处理模块,  Next: urllib request --- 用于打开 URL 的可扩展库,  Prev: wsgiref --- WSGI Utilities and Reference Implementation,  Up: 互联网协议和支持

5.21.5 ‘urllib’ — URL 处理模块
------------------------------

`源代码:' Lib/urllib/(1)

__________________________________________________________________

‘urllib’ 是一个收集了多个涉及 URL 的模块的包：

   * *note urllib.request: 121. 打开和读取 URL

   * *note urllib.error: 11f. 包含 *note urllib.request: 121. 抛出的异常

   * *note urllib.parse: 120. 用于解析 URL

   * *note urllib.robotparser: 123. 用于解析 ‘robots.txt’ 文件

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/urllib/


File: python.info,  Node: urllib request --- 用于打开 URL 的可扩展库,  Next: urllib response --- urllib 使用的 Response 类,  Prev: urllib --- URL 处理模块,  Up: 互联网协议和支持

5.21.6 ‘urllib.request’ — 用于打开 URL 的可扩展库
-------------------------------------------------

`源码：' Lib/urllib/request.py(1)

__________________________________________________________________

*note urllib.request: 121. 模块定义了适用于在各种复杂情况下打开 URL（主
要为 HTTP）的函数和类 — 例如基本认证、摘要认证、重定向、cookies 及其它。

参见
....

对于更高级别的 HTTP 客户端接口，建议使用 Requests(2) 。

*note urllib.request: 121. 模块定义了以下函数：

 -- 函数: urllib.request.urlopen (url, data=None[, timeout], *,
          cafile=None, capath=None, cadefault=False, context=None)

     打开统一资源定位地址 `url'，可以是一个字符串或一个 *note Request:
     8fe. 对象。

     `data' 必须是一个对象，用于给出要发送到服务器的附加数据，若不需要发
     送数据则为 ‘None’。详情请参阅 *note Request: 8fe. 。

     urllib.request 模块使用 HTTP/1.1 并且在其 HTTP 请求中包含
     ‘Connection:close’ 头。

     `timeout' 为可选参数，用于指定阻塞操作（如连接尝试）的超时时间，单
     位为秒。如未指定，将使用全局默认超时参数）。本参数实际仅对 HTTP、
     HTTPS 和 FTP 连接有效。

     如果给定了 `context' 参数，则必须是一个 *note ssl.SSLContext: 3ec.
     实例，用于描述各种 SSL 参数。更多详情请参阅 *note HTTPSConnection:
     39b. 。

     `cafile' 和 `capath' 为可选参数，用于为 HTTPS 请求指定一组受信 CA 证
     书。`cafile' 应指向包含CA 证书的单个文件， `capath' 则应指向哈希证
     书文件的目录。更多信息可参阅 *note
     ssl.SSLContext.load_verify_locations(): 7f4. 。

     `cadefault' 将被忽略。

     This function always returns an object which can work as a *note
     context manager: 571. and has methods such as

        * ‘geturl()’ — return the URL of the resource retrieved,
          commonly used to determine if a redirect was followed

        * ‘info()’ — return the meta-information of the page, such as
          headers, in the form of an *note email.message_from_string():
          282a. instance (see Quick Reference to HTTP Headers(3))

        * ‘getcode()’ – return the HTTP status code of the response.

     对于 HTTP 和 HTTPS 的 URL 而言，本函数将返回一个稍经修改的 *note
     http.client.HTTPResponse: a19. 对象。除了上述 3 个新的方法之外，还
     有 msg 属性包含了与 *note reason: 2c3f. 属性相同的信息—服务器返回的
     原因描述文字，而不是 *note HTTPResponse: a19. 的文档所述的响应头部
     信息。

     对于 FTP、文件、数据的URL，以及由传统的 *note URLopener: 2c40.  和
     *note FancyURLopener: 2c41. 类处理的请求，本函数将返回一个
     ‘urllib.response.addinfourl’ 对象。

     协议错误时引发 *note URLError: 2c42.。

     请注意，如果没有处理函数对请求进行处理，则有可能会返回 ‘None’ 。尽
     管默认安装的全局 *note OpenerDirector: 2c43. 会用 *note
     UnknownHandler: 2c44. 来确保不会发生这种情况。

     此外，如果检测到设置了代理（比如设置了 ‘http_proxy’ 之类的环境变量
     ），默认会安装 *note ProxyHandler: f8b. 并确保通过代理处理请求。

     Python 2.6 以下版本中留存的 ‘urllib.urlopen’ 函数已停止使用了；
     *note urllib.request.urlopen(): 795. 对应于传统的 ‘urllib2.urlopen’
     。对代理服务的处理是通过将字典参数传给 ‘urllib.urlopen’ 来完成的，
     可以用 *note ProxyHandler: f8b. 对象获取到代理处理函数。

     默认会触发一条 *note 审计事件: ea1. ‘urllib.Request’ ，参数
     ‘fullurl’ 、 ‘data’ 、‘headers’ 、‘method’ 均取自请求对象。

     在 3.2 版更改: 增加了 `cafile' 与 `capath'。

     在 3.2 版更改: 现在如果可行（指 *note ssl.HAS_SNI: 26e8. 为真），支
     持 HTTPS 虚拟主机

     3.2 新版功能: `data' 可以是一个可迭代对象。

     在 3.3 版更改: 增加了 `cadefault'。

     在 3.4.3 版更改: 增加了 `context'。

     3.6 版后已移除: `cafile' 、 `capath' 和 `cadefault' 已废弃，转而推
     荐使用 `context'。请改用 *note ssl.SSLContext.load_cert_chain():
     a99. 或让 *note ssl.create_default_context(): 8c9. 选取系统信任的
     CA 证书。

 -- 函数: urllib.request.install_opener (opener)

     安装一个 *note OpenerDirector: 2c43. 实例，作为默认的全局打开函数。
     仅当 urlopen 用到该打开函数时才需要安装；否则，只需调用 *note
     OpenerDirector.open(): 902. 而不是 *note urlopen(): 795.。代码不会
     检查是否真的属于 *note OpenerDirector: 2c43. 类，所有具备适当接口的
     类都能适用。

 -- 函数: urllib.request.build_opener ([handler, ...])

     返回一个 *note OpenerDirector: 2c43. 实例，以给定顺序把处理函数串联
     起来。处理函数可以是 *note BaseHandler: 2c47. 的实例，也可以是
     *note BaseHandler: 2c47. 的子类（这时构造函数必须允许不带任何参数的
     调用）。以下类的实例将位于 `处理函数' 之前，除非 `处理函数' 已包含
     这些类、其实例或其子类： *note ProxyHandler: f8b. （如果检测到代理
     设置）、*note UnknownHandler: 2c44. 、*note HTTPHandler: 2c48. 、
     *note HTTPDefaultErrorHandler: 2c49. 、*note HTTPRedirectHandler:
     2c4a. 、 *note FTPHandler: 2c4b. 、 *note FileHandler: 2c4c. 、
     *note HTTPErrorProcessor: 2c4d. 。

     若 Python 安装有 SLL 支持（指可以导入 *note ssl: f4. 模块），亦会加
     入 *note HTTPSHandler: bb0.。

     A *note BaseHandler: 2c47. subclass may also change its
     ‘handler_order’ attribute to modify its position in the handlers
     list.

 -- 函数: urllib.request.pathname2url (path)

     将路径名 `path' 从路径本地写法转换为 URL 路径部件采用的格式。这不会
     生成完整的 URL。返回值将会用 *note quote(): 415. 函数加以编码。

 -- 函数: urllib.request.url2pathname (path)

     从百分号编码的 URL 中将 `path' 部分转换为本地路径的写法。本函数不接
     受完整的 URL。本函数利用 *note unquote(): ee7. 解码 `path' 。

 -- 函数: urllib.request.getproxies ()

     本辅助函数将返回一个字典，表示各方案映射的代理服务器 URL。本函数扫
     描名为 ‘<scheme>_proxy’ 的环境变量，不区分大小写，首先会考虑所有操
     作系统。如果环境变量无法找到，则会 从 Mac OS X 的 Mac OSX 系统配置
     或 Windows 系统的注册表查找代理服务器信息。如果同时存在小写和大写环
     境变量（且内容不一致），则首选小写。

          注解: 如果存在环境变量 ‘REQUEST_METHOD’ ，通常表示脚本运行于
          CGI 环境中，则环境变量 ‘HTTP_PROXY’ （大写的 ‘_PROXY’）将会被
          忽略。这是因其可以由客户端用 HTTP 头部信息 “Proxy:”注入。若要
          在 CGI 环境中使用 HTTP 代理，请显式使用 ‘`ProxyHandler’ ，或确
          保变量名称为小写（或至少是 ‘_proxy’ 后缀）。

提供了以下类：

 -- 类: urllib.request.Request (url, data=None, headers={},
          origin_req_host=None, unverifiable=False, method=None)

     URL 请求的抽象类。

     `url' 应是一个含有一个有效 URL 的字符串。

     `data' 必须是一个对象，用于给定发往服务器的附加数据，若无需此类数据
     则为 ‘None’ 。 目前 唯一用到 `data' 的只有 HTTP 请求。支持的对象类
     型包括字节对象、类文件对象和可遍历的类字节对象。如果没有提供
     ‘Content-Length’ 和 ‘Transfer-Encoding’ 头部字段， *note
     HTTPHandler: 2c48. 会根据 `data' 的类型设置这些头部字段。
     ‘Content-Length’ 将用于发送字节对象，而 RFC 7230(4) 第 3.3.1 节中定
     义的 ‘Transfer-Encoding: chunked’ 将用于发送文件和其他可遍历对象。

     对于 HTTP POST 请求方法而言，`data' 应该是标准
     ‘application/x-www-form-urlencoded’ 格式的缓冲区。 *note
     urllib.parse.urlencode(): 794. 函数的参数为映射对象或二元组序列，并
     返回一个该编码格式的 ASCII 字符串。在用作 `data' 参数之前，应将其编
     码为字节串。

     `headers' 应为字典对象，视同于用每个键和值作为参数去调用 *note
     add_header(): 2c51. 。通常用于 ‘User-Agent’ 头部数据的“伪装” ，浏览
     器用这些头部数据标识自己——某些 HTTP 服务器只允许来自普通浏览器的请
     求，而不接受来自脚本的请求。例如，Mozilla Firefox 可能将自己标识为
     ‘"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127
     Firefox/2.0.0.11"’ ，而 *note urllib: 11e. 的默认 user agent 字符串
     则是 ‘"Python-urllib/2.6"’ （在 Python 2.6 上）。

     如果给出了 `data' 参数，则应当包含合适的 ‘Content-Type’ 头部信息。
     若未提供且 `data' 不是 None，则会把 ‘Content-Type:
     application/x-www-form-urlencoded’ 加入作为默认值。

     接下来的两个参数，只对第三方 HTTP cookie 的处理才有用：

     `origin_req_host' 应为发起初始会话的请求主机，定义参见 RFC 2965(5)
     。默认指为‘‘http.cookiejar.request_host(self)‘‘ 。这是用户发起初始
     请求的主机名或 IP 地址。假设请求是针对 HTML 文档中的图片数据发起的
     ，则本属性应为对包含图像的页面发起请求的主机。

     `unverifiable' 应该标示出请求是否无法验证，定义参见 RFC 2965(6) 。
     默认值为 ‘False’ 。所谓无法验证的请求，是指用户没有机会对请求的 URL
     做验证。例如，如果请求是针对 HTML 文档中的图像，用户没有机会去许可
     能自动读取图像，则本属性应为 True。

     `method' 应为字符串，标示要采用的 HTTP 请求方法（例如 ‘'HEAD'’ ）。
     如果给出本参数，其值会存储在 *note method: 8ff. 属性中，并由 *note
     get_method(): ac9. 使用。如果 `data' 为‘‘None‘‘ 则默认值为 ‘'GET'’
     ，否则为 ‘'POST'’。子类可以设置 *note method: 8ff. 属性来标示不同的
     默认请求方法。

          注解: 如果 data 对象无法分多次传递其内容（比如文件或只能生成一
          次内容的可迭代对象）并且由于 HTTP 重定向或身份验证而发生请求重
          试行为，则该请求不会正常工作。 `data' 是紧挨着头部信息发送给
          HTTP 服务器的。现有库不支持 HTTP 100-continue 的征询。

     在 3.3 版更改: Request 类增加了 *note Request.method: 8ff. 参数。

     在 3.4 版更改: 默认 *note Request.method: 8ff. 可以在类中标明。

     在 3.6 版更改: 如果给出了 ‘Content-Length’ ，且 `data' 既不为
     ‘None’ 也不是字节串对象，则不会触发错误。而会退而求其次采用分块传输
     的编码格式。

 -- 类: urllib.request.OpenerDirector

     *note OpenerDirector: 2c43. 类通过串接在一起的 *note BaseHandler:
     2c47. 打开 URL，并负责管理 handler 链及从错误中恢复。

 -- 类: urllib.request.BaseHandler

     这是所有已注册 handler 的基类，只做了简单的注册机制。

 -- 类: urllib.request.HTTPDefaultErrorHandler

     为 HTTP 错误响应定义的默认 handler，所有响应都会转为 *note
     HTTPError: 904. 异常。

 -- 类: urllib.request.HTTPRedirectHandler

     一个用于处理重定向的类。

 -- 类: urllib.request.HTTPCookieProcessor (cookiejar=None)

     一个用于处理 HTTP Cookies 的类。

 -- 类: urllib.request.ProxyHandler (proxies=None)

     让请求转去代理服务。若给出了 `proxies'，则其必须是一个将协议名称映
     射为代理 URL 的字典对象。默认是从环境变量 ‘<protocol>_proxy’ 中读取
     代理服务的列表。如果没有设置代理环境变量，则 Windows 会从注册表的
     Internet 设置部分获取代理设置，而 Mac OS X 则会从 OS X 系统配置框架
     中读取代理信息。

     若要禁用自动检测出来的代理，请传入空的字典对象。

     环境变量 ‘no_proxy’ 可用于指定不必通过代理访问的主机；应为逗号分隔
     的主机名后缀列表，可加上 ‘:port’ ，例如
     ‘cern.ch,ncsa.uiuc.edu,some.host:8080’ 。

               注解: 如果设置了 ‘REQUEST_METHOD’ 变量，则会忽略
               ‘HTTP_PROXY’ ；参阅 *note getproxies(): 2c50. 文档。

 -- 类: urllib.request.HTTPPasswordMgr

     维护 ‘(realm, uri) -> (user, password)’ 映射数据库。

 -- 类: urllib.request.HTTPPasswordMgrWithDefaultRealm

     维护 ‘(realm, uri) -> (user, password)’ 映射数据库。realm 为 ‘None’
     视作全匹配，若没有其他合适的安全区域就会检索它。

 -- 类: urllib.request.HTTPPasswordMgrWithPriorAuth

     *note HTTPPasswordMgrWithDefaultRealm: 2c54. 的一个变体，也带有
     ‘uri -> is_authenticated’ 映射数据库。可被 BasicAuth 处理函数用于确
     定立即发送身份认证凭据的时机，而不是先等待 ‘401’ 响应。

     3.5 新版功能.

 -- 类: urllib.request.AbstractBasicAuthHandler (password_mgr=None)

     这是一个帮助完成 HTTP 身份认证的混合类，对远程主机和代理都适用。参
     数 `password_mgr' 应与 *note HTTPPasswordMgr: 2c53. 兼容；关于必须
     支持哪些接口，请参阅 *note HTTPPasswordMgr 对象: 2c55. 对象的章节。
     如果 `password_mgr' 还提供 ‘is_authenticated’ 和
     ‘update_authenticated’ 方法（请参阅 *note
     HTTPPasswordMgrWithPriorAuth 对象: 2c56. 对象），则 handler 将对给
     定 URI 用到 ‘is_authenticated’ 的结果，来确定是否随请求发送身份认证
     凭据。如果该 URI 的 ‘is_authenticated’ 返回 ‘True’，则发送凭据。如
     果 ‘is_authenticated’ 为 ‘False’ ，则不发送凭据，然后若收到 ‘401’ 响
     应，则使用身份认证凭据重新发送请求。如果身份认证成功，则调用
     ‘update_authenticated’ 设置该 URI 的 ‘is_authenticated’ 为 ‘True’，
     这样后续对该 URI 或其所有父 URI 的请求将自动包含该身份认证凭据。

     3.5 新版功能: 增加了对 ‘is_authenticated’ 的支持。

 -- 类: urllib.request.HTTPBasicAuthHandler (password_mgr=None)

     处理与远程主机的身份验证。 `password_mgr' 应与 *note
     HTTPPasswordMgr: 2c53. 兼容；有关哪些接口是必须支持的，请参阅 *note
     HTTPPasswordMgr 对象: 2c55. 章节。如果给出错误的身份认证方式，
     HTTPBasicAuthHandler 将会触发 *note ValueError: 1fc. 。

 -- 类: urllib.request.ProxyBasicAuthHandler (password_mgr=None)

     处理有代理服务时的身份验证。 `password_mgr' 应与 *note
     HTTPPasswordMgr: 2c53. 兼容；有关哪些接口是必须支持的，请参阅 *note
     HTTPPasswordMgr 对象: 2c55. 章节。

 -- 类: urllib.request.AbstractDigestAuthHandler (password_mgr=None)

     这是一个帮助完成 HTTP 身份认证的混合类，对远程主机和代理都适用。参
     数 `password_mgr' 应与 *note HTTPPasswordMgr: 2c53. 兼容；关于必须
     支持哪些接口，请参阅 *note HTTPPasswordMgr 对象: 2c55. 的章节。

 -- 类: urllib.request.HTTPDigestAuthHandler (password_mgr=None)

     处理远程主机的身份验证。 `password_mgr' 应与 *note HTTPPasswordMgr:
     2c53. 兼容；有关哪些接口是必须支持的，请参阅 *note HTTPPasswordMgr
     对象: 2c55. 章节。如果同时添加了 digest 身份认证 handler 和basic 身
     份认证 handler，则会首先尝试 digest 身份认证。如果 digest 身份认证
     再返回 40x 响应，会再发送到 basic 身份验证 handler 进行处理。如果给
     出 Digest 和 Basic 之外的身份认证方式， 本 handler 方法将会触发
     *note ValueError: 1fc. 。

     在 3.3 版更改: 碰到不支持的认证方式时，将会触发 *note ValueError:
     1fc. 。

 -- 类: urllib.request.ProxyDigestAuthHandler (password_mgr=None)

     处理有代理服务时的身份验证。 `password_mgr' 应与 *note
     HTTPPasswordMgr: 2c53. 兼容；有关哪些接口是必须支持的，请参阅 *note
     HTTPPasswordMgr 对象: 2c55. 章节。

 -- 类: urllib.request.HTTPHandler

     用于打开 HTTP URL 的 handler 类。

 -- 类: urllib.request.HTTPSHandler (debuglevel=0, context=None,
          check_hostname=None)

     用于打开 HTTPS URL 的 handler 类。`context' 和 `check_hostname' 的
     含义与 *note http.client.HTTPSConnection: 39b. 的一样。

     在 3.2 版更改: 添加 `context' 和 `check_hostname' 参数。

 -- 类: urllib.request.FileHandler

     打开本地文件。

 -- 类: urllib.request.DataHandler

     打开数据 URL。

     3.4 新版功能.

 -- 类: urllib.request.FTPHandler

     打开 FTP URLs。

 -- 类: urllib.request.CacheFTPHandler

     打开 FTP URL，并将打开的 FTP 连接存入缓存，以便最大程度减少延迟。

 -- 类: urllib.request.UnknownHandler

     处理所有未知类型 URL 的兜底类。

 -- 类: urllib.request.HTTPErrorProcessor

     处理出错的 HTTP 响应。

* Menu:

* Request 对象::
* OpenerDirector 对象::
* BaseHandler 对象::
* HTTPRedirectHandler 对象::
* HTTPCookieProcessor 对象::
* ProxyHandler 对象::
* HTTPPasswordMgr 对象::
* HTTPPasswordMgrWithPriorAuth 对象::
* AbstractBasicAuthHandler 对象::
* HTTPBasicAuthHandler 对象::
* ProxyBasicAuthHandler 对象::
* AbstractDigestAuthHandler 对象::
* HTTPDigestAuthHandler 对象::
* ProxyDigestAuthHandler 对象::
* HTTPHandler 对象::
* HTTPSHandler 对象::
* FileHandler 对象::
* DataHandler 对象::
* FTPHandler 对象::
* CacheFTPHandler 对象::
* UnknownHandler 对象::
* HTTPErrorProcessor 对象::
* 例子: 例子<21>.
* 已停用的接口::
* urllib.request Restrictions: urllib request Restrictions.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/urllib/request.py

   (2) https://requests.readthedocs.io/en/master/

   (3) http://jkorpela.fi/http.html

   (4) https://tools.ietf.org/html/rfc7230.html

   (5) https://tools.ietf.org/html/rfc2965.html

   (6) https://tools.ietf.org/html/rfc2965.html


File: python.info,  Node: Request 对象,  Next: OpenerDirector 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.1 Request 对象
.....................

以下方法介绍了 *note Request: 8fe. 的公开接口，因此子类可以覆盖所有这些
方法。这里还定义了几个公开属性，客户端可以利用这些属性了解经过解析的请求
。

 -- 属性: Request.full_url

     传给构造函数的原始 URL。

     在 3.4 版更改.

     Request.full_url 是一个带有 setter、getter 和 deleter 的属性。读取
     *note full_url: 900. 属性将会返回分段的初始请求 URL。

 -- 属性: Request.type

     URI 方式。

 -- 属性: Request.host

     URI 权限，通常是整个主机，但也有可能带有冒号分隔的端口号。

 -- 属性: Request.origin_req_host

     请求的原始主机，不含端口。

 -- 属性: Request.selector

     URI 路径。若 *note Request: 8fe. 使用代理，选择器将会是传给代理的完
     整 URL。

 -- 属性: Request.data

     请求的数据体，未给出则为 ‘None’ 。

     在 3.4 版更改: 现在如果修改 *note Request.data: 901. 的值，则会删除
     之前设置或计算过的“Content-Length”头部信息。

 -- 属性: Request.unverifiable

     布尔，表明请求是否为 RFC 2965(1) 中定义的无法证实的。

 -- 属性: Request.method

     要采用的 HTTP 请求方法。默认为 *note None: 158.，表示 *note
     get_method(): ac9. 将对方法进行正常处理。设置本值可以覆盖 *note
     get_method(): ac9. 中的默认处理过程，设置方式可以是在 *note
     Request: 8fe. 的子类中给出默认值，也可以通过 `method' 参数给 *note
     Request: 8fe. 构造函数传入一个值。

     3.3 新版功能.

     在 3.4 版更改: 现在可以在子类中设置默认值；而之前只能通过构造函数参
     数进行设置。

 -- 方法: Request.get_method ()

     返回表示 HTTP 请求方法的字符串。如果 *note Request.method: 8ff. 不
     为 ，则返回其值。否则若 *note Request.data: 901. 为 ‘None’ 则返回
     ‘'GET'’，不为 ‘None’ 则返回 ‘'POST'’ 。只对 HTTP 请求有效。

     在 3.3 版更改: 现在 get_method 会兼顾 *note Request.method: 8ff. 的
     值。

 -- 方法: Request.add_header (key, val)

     向请求添加一项头部信息。目前只有 HTTP handler 才会处理头部信息，将
     其加入发给服务器的头部信息列表中。请注意，同名的头部信息只能出现一
     次，如果 `key' 发生冲突，后续的调用结果将会覆盖先前的。目前，这并不
     会减少 HTTP 的功能，因为所有多次使用仍有意义的头部信息，都有一种特
     定方式获得与只用一次时相同的功能。

 -- 方法: Request.add_unredirected_header (key, header)

     添加一个不会被加入重定向请求的头部。

 -- 方法: Request.has_header (header)

     返回本实例是否带有命名头部信息（对常规数据和非重定向数据都会检测）
     。

 -- 方法: Request.remove_header (header)

     从本请求实例中移除指定命名的头部信息（对常规数据和非重定向数据都会
     检测）。

     3.4 新版功能.

 -- 方法: Request.get_full_url ()

     返回构造器中给定的 URL。

     在 3.4 版更改.

     返回 *note Request.full_url: 900.

 -- 方法: Request.set_proxy (host, type)

     连接代理服务器，为当前请求做准备。 `host' 和 `type' 将会取代本实例
     中的对应值，selector 将会是构造函数中给出的初始 URL。

 -- 方法: Request.get_header (header_name, default=None)

     返回给定头部信息的数据。如果该头部信息不存在，返回默认值。

 -- 方法: Request.header_items ()

     返回头部信息，形式为（名称, 数据）的元组列表。

在 3.4 版更改: 自 3.3 起已弃用的下列方法已被删除：add_data、has_data、
get_data、get_type、get_host、get_selector、get_origin_req_host 和
is_unverifiable 。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2965.html


File: python.info,  Node: OpenerDirector 对象,  Next: BaseHandler 对象,  Prev: Request 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.2 OpenerDirector 对象
............................

*note OpenerDirector: 2c43. 实例有以下方法：

 -- 方法: OpenerDirector.add_handler (handler)

     `handler' 应为 *note BaseHandler: 2c47. 的实例。将检索以下类型的方
     法，并将其添加到对应的处理链中（注意 HTTP 错误是特殊情况）。请注意
     ，下文中的 `protocol' 应替换为要处理的实际协议，例如
     ‘http_response()’ 将是 HTTP 协议响应处理函数。并且 `type' 也应替换
     为实际的 HTTP 代码，例如 ‘http_error_404()’ 将处理 HTTP 404 错误。

        * ‘<protocol>_open()’ — 句柄知道如何打开 `protocol' URLs 的信号
          。

          查看 *note BaseHandler.<protocol>_open(): 2c6c. 以获取更多信息
          。

        * ‘http_error_<type>()’ — 表明该 handler 知道如何处理代码为
          `type' 的 HTTP 错误。

          查看 *note BaseHandler.http_error_<nnn>(): 2c6d. 以获取更多信
          息。

        * ‘<protocol>_error()’ — 句柄知道如何处理来自（非-‘http’）
          *protocol* 的错误的信号。

        * ‘<protocol>_request()’ — 句柄知道如何预处理 `protocol' 请求的
          信号。

          查看 *note BaseHandler.<protocol>_request(): 2c6e. 以获取更多
          信息。

        * ‘<protocol>_response()’ — 句柄知道如何后处理 `protocol' 响应的
          信号。

          查看 *note BaseHandler.<protocol>_response(): 2c6f. 以获取更多
          信息。

 -- 方法: OpenerDirector.open (url, data=None[, timeout])

     打开给定的 `url*（可以是 request 对象或字符串），可以传入 *data' 。
     参数、返回值和引发的异常均与 *note urlopen(): 795. 相同，其实只是去
     调用了当前安装的全局 *note OpenerDirector: 2c43. 中的 *note open():
     4f8. 方法。可选的 `timeout' 参数指定了阻塞操作（如尝试连接）的超时
     值（以秒为单位）（若未指定则采用全局默认的超时设置）。实际上，超时
     特性仅适用于 HTTP、HTTPS 和 FTP 连接。

 -- 方法: OpenerDirector.error (proto, *args)

     处理给定协议的错误。将用给定的参数（协议相关）调用已注册的给定协议
     的错误处理程序。HTTP 协议是特殊情况，采用 HTTP 响应码来确定具体的错
     误处理程序；请参考 handler 类的 ‘http_error_<type>()’ 方法。

     返回值和异常均与 *note urlopen(): 795. 相同。

OpenerDirector 对象分 3 个阶段打开 URL：

每个阶段中调用这些方法的次序取决于 handler 实例的顺序。

  1. 每个具有 ‘_request()’ 这类方法的 handler 都会调用本方法对请求进行预
     处理。

  2. 调用具有 ‘_open()’ 这类方法的 handler 来处理请求。当 handler 返回非
     *note None: 158. 值（即响应）或引发异常（通常是 *note URLError:
     2c42.）时，本阶段结束。本阶段能够传播异常。

     事实上，以上算法首先会尝试名为 ‘default_open()’ 的方法。 如果这些方
     法全都返回 *note None: 158.，则会对名为 ‘<protocol>_open()’ 的方法
     重复此算法。 如果这些方法也全都返回 *note None: 158.，则会继续对名
     为 ‘unknown_open()’ 的方法重复此算法。

     请注意，这些方法的代码可能会调用 *note OpenerDirector: 2c43. 父实例
     的 *note open(): 902. 和 *note error(): 2c70. 方法。

  3. 每个具有 ‘_response()’ 这类方法的 handler 都会调用这些方法，以对响
     应进行后处理。


File: python.info,  Node: BaseHandler 对象,  Next: HTTPRedirectHandler 对象,  Prev: OpenerDirector 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.3 BaseHandler 对象
.........................

*note BaseHandler: 2c47. 对象提供了一些直接可用的方法，以及其他一些可供
派生类使用的方法。以下是可供直接使用的方法：

 -- 方法: BaseHandler.add_parent (director)

     将 director 加为父 handler。

 -- 方法: BaseHandler.close ()

     移除所有父 OpenerDirector。

以下属性和方法仅供 *note BaseHandler: 2c47. 的子类使用：

     注解: 以下约定已被采纳：定义 ‘<protocol>_request()’ 或
     ‘<protocol>_response()’ 方法的子类应命名为 ‘*Processor’；所有其他子
     类都应命名为 ‘*Handler’ 。

 -- 属性: BaseHandler.parent

     一个可用的 *note OpenerDirector: 2c43.，可用于以其他协议打开 URI，
     或处理错误。

 -- 方法: BaseHandler.default_open (req)

     本方法在 *note BaseHandler: 2c47. 中 `未' 予定义，但其子类若要捕获
     所有 URL 则应进行定义。

     若实现了本方法，则会被父类 *note OpenerDirector: 2c43. 调用。应返回
     一个类文件对象，类似于 *note OpenerDirector: 2c43. 的 *note open():
     4f8. 的返回值，或返回“None”。触发的异常应为 *note URLError: 2c42.，
     除非发生真的异常（比如 *note MemoryError: efc. 就不应变为
     ‘URLError’）。

     本方法将会在所有协议的 open 方法之前被调用。

 -- 方法: BaseHandler.<protocol>_open(req)

     本方法在 *note BaseHandler: 2c47. 中 `未' 予定义，但其子类若要处理
     给定协议的 URL 则应进行定义。

     若定义了本方法，将会被父 *note OpenerDirector: 2c43. 对象调用。返回
     值和 ‘default_open()’ 的一样。

 -- 方法: BaseHandler.unknown_open (req)

     本方法在 *note BaseHandler: 2c47. 中 `未' 予定义，但其子类若要捕获
     并打开所有未注册 handler 的 URL，则应进行定义。

     若实现了本方法，将会被 *note parent: 2c75. 属性指向的父 *note
     OpenerDirector: 2c43. 调用。返回值和 *note default_open(): 2c76. 的
     一样。

 -- 方法: BaseHandler.http_error_default (req, fp, code, msg, hdrs)

     本方法在 *note BaseHandler: 2c47. 中 `未' 予定义，但其子类若要为所
     有未定义 handler 的 HTTP 错误提供一个兜底方法，则应进行覆盖。*note
     OpenerDirector: 2c43. 会自动调用本方法，获取错误信息，而通常在其他
     时候不应去调用。

     `req' 会是一个 *note Request: 8fe. 对象，`fp' 是一个带有 HTTP 错误
     体的文件类对象，`code' 是三位数的错误码，`msg' 是供用户阅读的解释信
     息，`hdrs' 则是一个包含出错头部信息的映射对象。

     返回值和触发的异常应与 *note urlopen(): 795. 的相同。

 -- 方法: BaseHandler.http_error_<nnn>(req, fp, code, msg, hdrs)

     `nnn' 应为三位数的 HTTP 错误码。本方法在 *note BaseHandler: 2c47. 中
     也未予定义，但当子类的实例发生代码为 `nnn' 的 HTTP 错误时，若方法存
     在则会被调用。

     子类应该重写本方法，以便能处理指定的 HTTP 错误。

     参数、返回值和触发的异常应与 ‘http_error_default()’ 相同。

 -- 方法: BaseHandler.<protocol>_request(req)

     本方法在 *note BaseHandler: 2c47. 中 `未' 予定义，但其子类若要对给
     定协议的请求进行预处理，则应进行定义。

     若实现了本方法，将会被父 *note OpenerDirector: 2c43. 调用。`req' 将
     为 *note Request: 8fe. 对象。返回值应为 *note Request: 8fe. 对象。

 -- 方法: BaseHandler.<protocol>_response(req, response)

     本方法在 *note BaseHandler: 2c47. 中 `未' 予定义，但其子类若要对给
     定协议的请求进行后处理，则应进行定义。

     若实现了本方法，将会被父 *note OpenerDirector: 2c43. 调用。`req' 将
     为 *note Request: 8fe. 对象。`response' 应实现与 *note urlopen():
     795. 返回值相同的接口。返回值应实现与 *note urlopen(): 795. 返回值
     相同的接口。


File: python.info,  Node: HTTPRedirectHandler 对象,  Next: HTTPCookieProcessor 对象,  Prev: BaseHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.4 HTTPRedirectHandler 对象
.................................

     注解: 某些 HTTP 重定向操作需要用到本模块的客户端代码。这时会触发
     *note HTTPError: 904.。有关各种重定向代码的确切含义，请参阅 RFC
     2616(1) 。

     如果 HTTPRedirectHandler 呈现的重定向 URL 不是 HTTP、HTTPS 或 FTP
     URL，则出于安全考虑将触发 ‘HTTPError’ 异常。

 -- 方法: HTTPRedirectHandler.redirect_request (req, fp, code, msg,
          hdrs, newurl)

     返回 *note Request: 8fe. 或 ‘None’ 对象作为重定向行为的响应。当服务
     器接收到重定向请求时， ‘http_error_30*()’ 方法的默认实现代码将会调
     用本方法。如果确实应该发生重定向，则返回一个新的 *note Request:
     8fe. 对象，使得 ‘http_error_30*()’ 能重定向至 `newurl'。否则，若没
     有 handler 会处理此 URL，则会引发 *note HTTPError: 904.；或者本方法
     不能处理但或许会有其他 handler 会处理，则返回 ‘None’ 。

          注解: 本方法的默认实现代码并未严格遵循 RFC 2616(2)，即 ‘POST’
          请求的 301 和 302 响应不得在未经用户确认的情况下自动进行重定向
          。现实情况下，浏览器确实允许自动重定向这些响应，将 POST 更改为
          ‘GET’ ，于是默认实现代码就复现了这种处理方式。

 -- 方法: HTTPRedirectHandler.http_error_301 (req, fp, code, msg, hdrs)

     重定向到 ‘Location:’ 或 ‘URI:’ URL。 这个方法会在得到 HTTP ’moved
     permanently’ 响应时由上级 *note OpenerDirector: 2c43. 来调用。

 -- 方法: HTTPRedirectHandler.http_error_302 (req, fp, code, msg, hdrs)

     与 *note http_error_301(): 2c7c. 相同，不过是发生“found”响应时的调
     用。

 -- 方法: HTTPRedirectHandler.http_error_303 (req, fp, code, msg, hdrs)

     与 *note http_error_301(): 2c7c. 相同，不过是发生“see other”响应时
     的调用。

 -- 方法: HTTPRedirectHandler.http_error_307 (req, fp, code, msg, hdrs)

     与 *note http_error_301(): 2c7c. 相同，不过是发生“temporary
     redirect”响应时的调用。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2616.html

   (2) https://tools.ietf.org/html/rfc2616.html


File: python.info,  Node: HTTPCookieProcessor 对象,  Next: ProxyHandler 对象,  Prev: HTTPRedirectHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.5 HTTPCookieProcessor 对象
.................................

*note HTTPCookieProcessor: 2c52. 的实例具备一个属性：

 -- 属性: HTTPCookieProcessor.cookiejar

     cookie 存放在 *note http.cookiejar.CookieJar: 2c83. 中。


File: python.info,  Node: ProxyHandler 对象,  Next: HTTPPasswordMgr 对象,  Prev: HTTPCookieProcessor 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.6 ProxyHandler 对象
..........................

 -- 方法: ProxyHandler.<protocol>_open(request)

     *note ProxyHandler: f8b. 将为每种 `protocol' 准备一个 ‘_open()’ 方
     法，在构造函数给出的 `proxies' 字典中包含对应的代理服务器信息。通过
     调用 ‘request.set_proxy()’，本方法将把请求转为通过代理服务器，并会
     调用 handler 链中的下一个 handler 来完成对应的协议处理。


File: python.info,  Node: HTTPPasswordMgr 对象,  Next: HTTPPasswordMgrWithPriorAuth 对象,  Prev: ProxyHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.7 HTTPPasswordMgr 对象
.............................

以下方法 *note HTTPPasswordMgr: 2c53. 和 *note
HTTPPasswordMgrWithDefaultRealm: 2c54. 对象均有提供。

 -- 方法: HTTPPasswordMgr.add_password (realm, uri, user, passwd)

     `uri' 可以是单个 URI，也可以是 URI 列表。`realm'、`user' 和
     `passwd' 必须是字符串。这使得在为 `realm' 和超级 URI 进行身份认证时
     ，‘(user, passwd)’ 可用作认证令牌。

 -- 方法: HTTPPasswordMgr.find_user_password (realm, authuri)

     为给定 realm 和 URI 获取用户名和密码。如果没有匹配的用户名和密码，
     本方法将会返回 ‘(None, None)’ 。

     对于 *note HTTPPasswordMgrWithDefaultRealm: 2c54. 对象，如果给定
     `realm' 没有匹配的用户名和密码，将搜索 realm ‘None’。


File: python.info,  Node: HTTPPasswordMgrWithPriorAuth 对象,  Next: AbstractBasicAuthHandler 对象,  Prev: HTTPPasswordMgr 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.8 HTTPPasswordMgrWithPriorAuth 对象
..........................................

这是 *note HTTPPasswordMgrWithDefaultRealm: 2c54. 的扩展，以便对那些需要
一直发送认证凭证的 URI 进行跟踪。

 -- 方法: HTTPPasswordMgrWithPriorAuth.add_password (realm, uri, user,
          passwd, is_authenticated=False)

     `realm'、`uri'、`user'、`passwd' 的含义与 *note
     HTTPPasswordMgr.add_password(): 2c87. 的相同。`is_authenticated' 为
     给定 URI 或 URI 列表设置 ‘is_authenticated’ 标志的初始值。如果
     `is_authenticated' 设为 ‘True’ ，则会忽略 `realm'。

 -- 方法: HTTPPasswordMgrWithPriorAuth.find_user_password (realm,
          authuri)

     与 *note HTTPPasswordMgrWithDefaultRealm: 2c54. 对象的相同。

 -- 方法: HTTPPasswordMgrWithPriorAuth.update_authenticated (self, uri,
          is_authenticated=False)

     更新给定 `uri' 或 URI 列表的 ‘is_authenticated’ 标志。

 -- 方法: HTTPPasswordMgrWithPriorAuth.is_authenticated (self, authuri)

     返回给定 URI ‘is_authenticated’ 标志的当前状态。


File: python.info,  Node: AbstractBasicAuthHandler 对象,  Next: HTTPBasicAuthHandler 对象,  Prev: HTTPPasswordMgrWithPriorAuth 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.9 AbstractBasicAuthHandler 对象
......................................

 -- 方法: AbstractBasicAuthHandler.http_error_auth_reqed (authreq, host,
          req, headers)

     通过获取用户名和密码并重新尝试请求，以处理身份认证请求。 `authreq'
     应该是请求中包含 realm 的头部信息名称，`host' 指定了需要进行身份认
     证的 URL 和路径，`req' 应为 (已失败的) *note Request: 8fe. 对象 ,
     `headers' 应该是出错的头部信息。

     `host' 要么是一个认证信息（例如 ‘"python.org"’ ），要么是一个包含认
     证信息的 URL（如‘‘"‘http://python.org/’"‘‘ ）。 不论是哪种格式，认
     证信息中都不能包含用户信息（因此，‘"python.org"’ 和
     ‘"python.org:80"’ 没问题，而 ‘"joe:password@python.org"’ 则不行）。


File: python.info,  Node: HTTPBasicAuthHandler 对象,  Next: ProxyBasicAuthHandler 对象,  Prev: AbstractBasicAuthHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.10 HTTPBasicAuthHandler 对象
...................................

 -- 方法: HTTPBasicAuthHandler.http_error_401 (req, fp, code, msg, hdrs)

     如果可用的话，请用身份认证信息重试请求。


File: python.info,  Node: ProxyBasicAuthHandler 对象,  Next: AbstractDigestAuthHandler 对象,  Prev: HTTPBasicAuthHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.11 ProxyBasicAuthHandler 对象
....................................

 -- 方法: ProxyBasicAuthHandler.http_error_407 (req, fp, code, msg,
          hdrs)

     如果可用的话，请用身份认证信息重试请求。


File: python.info,  Node: AbstractDigestAuthHandler 对象,  Next: HTTPDigestAuthHandler 对象,  Prev: ProxyBasicAuthHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.12 AbstractDigestAuthHandler 对象
........................................

 -- 方法: AbstractDigestAuthHandler.http_error_auth_reqed (authreq,
          host, req, headers)

     `authreq' 应为请求中有关 realm 的头部信息名称，`host' 应为需要进行
     身份认证的主机，`req' 应为（已失败的） *note Request: 8fe. 对象，
     `headers' 则应为出错的头部信息。


File: python.info,  Node: HTTPDigestAuthHandler 对象,  Next: ProxyDigestAuthHandler 对象,  Prev: AbstractDigestAuthHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.13 HTTPDigestAuthHandler 对象
....................................

 -- 方法: HTTPDigestAuthHandler.http_error_401 (req, fp, code, msg,
          hdrs)

     如果可用的话，请用身份认证信息重试请求。


File: python.info,  Node: ProxyDigestAuthHandler 对象,  Next: HTTPHandler 对象,  Prev: HTTPDigestAuthHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.14 ProxyDigestAuthHandler 对象
.....................................

 -- 方法: ProxyDigestAuthHandler.http_error_407 (req, fp, code, msg,
          hdrs)

     如果可用的话，请用身份认证信息重试请求。


File: python.info,  Node: HTTPHandler 对象,  Next: HTTPSHandler 对象,  Prev: ProxyDigestAuthHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.15 HTTPHandler 对象
..........................

 -- 方法: HTTPHandler.http_open (req)

     发送 HTTP 请求，根据 ‘req.has_data()’ 的结果，可能是 GET 或 POST 格
     式。


File: python.info,  Node: HTTPSHandler 对象,  Next: FileHandler 对象,  Prev: HTTPHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.16 HTTPSHandler 对象
...........................

 -- 方法: HTTPSHandler.https_open (req)

     发送 HTTPS 请求，根据 ‘req.has_data()’ 的结果，可能是 GET 或 POST 格
     式。


File: python.info,  Node: FileHandler 对象,  Next: DataHandler 对象,  Prev: HTTPSHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.17 FileHandler 对象
..........................

 -- 方法: FileHandler.file_open (req)

     若无主机名或主机名为 ‘'localhost'’ ，则打开本地文件。

     在 3.2 版更改: 本方法仅适用于本地主机名。如果给出的是远程主机名，将
     会触发 *note URLError: 2c42. 。


File: python.info,  Node: DataHandler 对象,  Next: FTPHandler 对象,  Prev: FileHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.18 DataHandler 对象
..........................

 -- 方法: DataHandler.data_open (req)

     读取内含数据的 URL。这种 URL 本身包含了经过编码的数据。 RFC 2397(1)
     中给出了数据 URL 的语法定义。目前的代码库将忽略经过 base64 编码的数
     据 URL 中的空白符，因此 URL 可以放入任何源码文件中。如果数据 URL 的
     base64 编码尾部缺少填充，即使某些浏览器不介意，但目前的代码库仍会引
     发 *note ValueError: 1fc.。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2397.html


File: python.info,  Node: FTPHandler 对象,  Next: CacheFTPHandler 对象,  Prev: DataHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.19 FTPHandler 对象
.........................

 -- 方法: FTPHandler.ftp_open (req)

     打开由 `req' 给出的 FTP 文件。登录时的用户名和密码总是为空。


File: python.info,  Node: CacheFTPHandler 对象,  Next: UnknownHandler 对象,  Prev: FTPHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.20 CacheFTPHandler 对象
..............................

*note CacheFTPHandler: 2c5b. 对象即为加入以下方法的 *note FTPHandler:
2c4b. 对象：

 -- 方法: CacheFTPHandler.setTimeout (t)

     设置连接超时为 `t' 秒。

 -- 方法: CacheFTPHandler.setMaxConns (m)

     设置已缓存的最大连接数为 `m' 。


File: python.info,  Node: UnknownHandler 对象,  Next: HTTPErrorProcessor 对象,  Prev: CacheFTPHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.21 UnknownHandler 对象
.............................

 -- 方法: UnknownHandler.unknown_open ()

     触发 *note URLError: 2c42. 异常。


File: python.info,  Node: HTTPErrorProcessor 对象,  Next: 例子<21>,  Prev: UnknownHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.22 HTTPErrorProcessor 对象
.................................

 -- 方法: HTTPErrorProcessor.http_response (request, response)

     处理出错的 HTTP 响应。

     对于 200 错误码，响应对象应立即返回。

     对于 200 以外的错误码，只通过 *note OpenerDirector.error(): 2c70. 将
     任务传给 handler 的 ‘http_error_<type>()’ 方法。如果最终没有
     handler 处理错误， *note HTTPDefaultErrorHandler: 2c49. 将触发
     *note HTTPError: 904.。

 -- 方法: HTTPErrorProcessor.https_response (request, response)

     HTTPS 出错响应的处理。

     与 *note http_response(): 2cb8. 方法相同。


File: python.info,  Node: 例子<21>,  Next: 已停用的接口,  Prev: HTTPErrorProcessor 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.23 例子
..............

*note HOWTO 使用 urllib 包获取网络资源: 2cbc. 中给出了更多的示例。

以下示例将读取 python.org 主页并显示前 300 个字节的内容：

     >>> import urllib.request
     >>> with urllib.request.urlopen('http://www.python.org/') as f:
     ...     print(f.read(300))
     ...
     b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
     xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n\n<head>\n
     <meta http-equiv="content-type" content="text/html; charset=utf-8" />\n
     <title>Python Programming '

请注意，urlopen 将返回字节对象。这是因为 urlopen 无法自动确定由 HTTP 服
务器收到的字节流的编码。通常，只要能确定或猜出编码格式，就应将返回的字节
对象解码为字符串。

下述 W3C 文档 ‘https://www.w3.org/International/O-charset’列出了可用于指
明（X）HTML 或 XML 文档编码信息的多种方案。

python.org 网站已在 meta 标签中指明，采用的是 `utf-8' 编码，因此这里将用
同样的格式对字节串进行解码。

     >>> with urllib.request.urlopen('http://www.python.org/') as f:
     ...     print(f.read(100).decode('utf-8'))
     ...
     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtm

不用 *note context manager: 571. 方法也能获得同样的结果：

     >>> import urllib.request
     >>> f = urllib.request.urlopen('http://www.python.org/')
     >>> print(f.read(100).decode('utf-8'))
     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtm

以下示例将会把数据流发送给某 CGI 的 stdin，并读取返回数据。请注意，该示
例只能工作于 Python 装有 SSL 支持的环境。

     >>> import urllib.request
     >>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi',
     ...                       data=b'This data is passed to stdin of the CGI')
     >>> with urllib.request.urlopen(req) as f:
     ...     print(f.read().decode('utf-8'))
     ...
     Got Data: "This data is passed to stdin of the CGI"

上述示例中的 CGI 代码如下所示：

     #!/usr/bin/env python
     import sys
     data = sys.stdin.read()
     print('Content-type: text/plain\n\nGot Data: "%s"' % data)

下面是利用 *note Request: 8fe. 发送‘‘PUT‘‘ 请求的示例：

     import urllib.request
     DATA = b'some data'
     req = urllib.request.Request(url='http://localhost:8080', data=DATA,method='PUT')
     with urllib.request.urlopen(req) as f:
         pass
     print(f.status)
     print(f.reason)

基本 HTTP 认证示例：

     import urllib.request
     # Create an OpenerDirector with support for Basic HTTP Authentication...
     auth_handler = urllib.request.HTTPBasicAuthHandler()
     auth_handler.add_password(realm='PDQ Application',
                               uri='https://mahler:8092/site-updates.py',
                               user='klem',
                               passwd='kadidd!ehopper')
     opener = urllib.request.build_opener(auth_handler)
     # ...and install it globally so it can be used with urlopen.
     urllib.request.install_opener(opener)
     urllib.request.urlopen('http://www.example.com/login.html')

*note build_opener(): 2c46. 默认提供了很多现成的 handler，包括 *note
ProxyHandler: f8b.。 默认情况下，*note ProxyHandler: f8b. 会使用名为
‘<scheme>_proxy’ 的环境变量，其中的 ‘<scheme>’ 是相关的 URL 协议。 例如
，可以读取 ‘http_proxy’ 环境变量来获取 HTTP 代理的 URL。

以下示例将默认的 *note ProxyHandler: f8b. 替换为自己的 handler，由程序提
供代理 URL，并利用 *note ProxyBasicAuthHandler: 2c58. 加入代理认证的支持
：

     proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
     proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
     proxy_auth_handler.add_password('realm', 'host', 'username', 'password')

     opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
     # This time, rather than install the OpenerDirector, we use it directly:
     opener.open('http://www.example.com/login.html')

添加 HTTP 头部信息：

可利用 *note Request: 8fe. 构造函数的 `headers' 参数，或者是：

     import urllib.request
     req = urllib.request.Request('http://www.example.com/')
     req.add_header('Referer', 'http://www.python.org/')
     # Customize the default User-Agent header value:
     req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)')
     r = urllib.request.urlopen(req)

*note OpenerDirector: 2c43. 自动会在每个 *note Request: 8fe. 中加入一项
‘User-Agent’ 头部信息。若要修改，请参见以下语句：

     import urllib.request
     opener = urllib.request.build_opener()
     opener.addheaders = [('User-agent', 'Mozilla/5.0')]
     opener.open('http://www.example.com/')

另请记得，当 *note Request: 8fe. 传给 *note urlopen(): 795. （或 *note
OpenerDirector.open(): 902.）时，会加入一些标准的头部信息（
‘Content-Length’ 、 ‘Content-Type’ 和 ‘Host’）。 以下会话示例用 ‘GET’ 方
法读取包含参数的 URL。

     >>> import urllib.request
     >>> import urllib.parse
     >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
     >>> url = "http://www.musi-cal.com/cgi-bin/query?%s" % params
     >>> with urllib.request.urlopen(url) as f:
     ...     print(f.read().decode('utf-8'))
     ...

以下示例换用 ‘POST’ 方法。请注意 urlencode 输出结果先被编码为字节串
data，再送入 urlopen。

     >>> import urllib.request
     >>> import urllib.parse
     >>> data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
     >>> data = data.encode('ascii')
     >>> with urllib.request.urlopen("http://requestb.in/xrbl82xr", data) as f:
     ...     print(f.read().decode('utf-8'))
     ...

以下示例显式指定了 HTTP 代理，以覆盖环境变量中的设置：

     >>> import urllib.request
     >>> proxies = {'http': 'http://proxy.example.com:8080/'}
     >>> opener = urllib.request.FancyURLopener(proxies)
     >>> with opener.open("http://www.python.org") as f:
     ...     f.read().decode('utf-8')
     ...

以下示例根本不用代理，也覆盖了环境变量中的设置：

     >>> import urllib.request
     >>> opener = urllib.request.FancyURLopener({})
     >>> with opener.open("http://www.python.org/") as f:
     ...     f.read().decode('utf-8')
     ...


File: python.info,  Node: 已停用的接口,  Next: urllib request Restrictions,  Prev: 例子<21>,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.24 已停用的接口
......................

以下函数和类是由 Python 2 模块 ‘urllib``（相对早于 ``urllib2’ ）移植过来
的。将来某个时候可能会停用。

 -- 函数: urllib.request.urlretrieve (url, filename=None,
          reporthook=None, data=None)

     将 URL 形式的网络对象复制为本地文件。如果 URL 指向本地文件，则必须
     提供文件名才会执行复制。返回值为元组 ‘(filename, headers)’ ，其中
     `filename' 是保存网络对象的本地文件名， `headers' 是由 *note
     urlopen(): 795. 返回的远程对象 ‘info()’ 方法的调用结果。可能触发的
     异常与 *note urlopen(): 795. 相同。

     第二个参数指定文件的保存位置（若未给出，则会是名称随机生成的临时文
     件）。第三个参数是个可调用对象，在建立网络连接时将会调用一次，之后
     每次读完数据块后会调用一次。该可调用对象将会传入 3 个参数：已传输的
     块数、块的大小（以字节为单位）和文件总的大小。如果面对的是老旧 FTP
     服务器，文件大小参数可能会是 ‘-1’ ，这些服务器响应读取请求时不会返
     回文件大小。

     以下例子演示了大部分常用场景：

          >>> import urllib.request
          >>> local_filename, headers = urllib.request.urlretrieve('http://python.org/')
          >>> html = open(local_filename)
          >>> html.close()

     If the `url' uses the ‘http:’ scheme identifier, the optional
     `data' argument may be given to specify a ‘POST’ request (normally
     the request type is ‘GET’).  The `data' argument must be a bytes
     object in standard ‘application/x-www-form-urlencoded’ format; see
     the *note urllib.parse.urlencode(): 794. function.

     *note urlretrieve(): 2cbf. will raise ‘ContentTooShortError’ when
     it detects that the amount of data available was less than the
     expected amount (which is the size reported by a `Content-Length'
     header).  This can occur, for example, when the download is
     interrupted.

     The `Content-Length' is treated as a lower bound: if there’s more
     data to read, urlretrieve reads more data, but if less data is
     available, it raises the exception.

     You can still retrieve the downloaded data in this case, it is
     stored in the ‘content’ attribute of the exception instance.

     If no `Content-Length' header was supplied, urlretrieve can not
     check the size of the data it has downloaded, and just returns it.
     In this case you just have to assume that the download was
     successful.

 -- 函数: urllib.request.urlcleanup ()

     Cleans up temporary files that may have been left behind by
     previous calls to *note urlretrieve(): 2cbf.

 -- 类: urllib.request.URLopener (proxies=None, **x509)

     3.3 版后已移除.

     Base class for opening and reading URLs.  Unless you need to
     support opening objects using schemes other than ‘http:’, ‘ftp:’,
     or ‘file:’, you probably want to use *note FancyURLopener: 2c41.

     By default, the *note URLopener: 2c40. class sends a ‘User-Agent’
     header of ‘urllib/VVV’, where `VVV' is the *note urllib: 11e.
     version number.  Applications can define their own ‘User-Agent’
     header by subclassing *note URLopener: 2c40. or *note
     FancyURLopener: 2c41. and setting the class attribute *note
     version: 2cc1. to an appropriate string value in the subclass
     definition.

     The optional `proxies' parameter should be a dictionary mapping
     scheme names to proxy URLs, where an empty dictionary turns proxies
     off completely.  Its default value is ‘None’, in which case
     environmental proxy settings will be used if present, as discussed
     in the definition of *note urlopen(): 795, above.

     Additional keyword parameters, collected in `x509', may be used for
     authentication of the client when using the ‘https:’ scheme.  The
     keywords `key_file' and `cert_file' are supported to provide an SSL
     key and certificate; both are needed to support client
     authentication.

     *note URLopener: 2c40. objects will raise an *note OSError: 1d4.
     exception if the server returns an error code.

      -- 方法: open (fullurl, data=None)

          Open `fullurl' using the appropriate protocol.  This method
          sets up cache and proxy information, then calls the
          appropriate open method with its input arguments.  If the
          scheme is not recognized, *note open_unknown(): 2cc3. is
          called.  The `data' argument has the same meaning as the
          `data' argument of *note urlopen(): 795.

          This method always quotes `fullurl' using *note quote(): 415.

      -- 方法: open_unknown (fullurl, data=None)

          Overridable interface to open unknown URL types.

      -- 方法: retrieve (url, filename=None, reporthook=None, data=None)

          Retrieves the contents of `url' and places it in `filename'.
          The return value is a tuple consisting of a local filename and
          either an *note email.message.Message: 54a. object containing
          the response headers (for remote URLs) or ‘None’ (for local
          URLs).  The caller must then open and read the contents of
          `filename'.  If `filename' is not given and the URL refers to
          a local file, the input filename is returned.  If the URL is
          non-local and `filename' is not given, the filename is the
          output of *note tempfile.mktemp(): e95. with a suffix that
          matches the suffix of the last path component of the input
          URL. If `reporthook' is given, it must be a function accepting
          three numeric parameters: A chunk number, the maximum size
          chunks are read in and the total size of the download (-1 if
          unknown).  It will be called once at the start and after each
          chunk of data is read from the network.  `reporthook' is
          ignored for local URLs.

          If the `url' uses the ‘http:’ scheme identifier, the optional
          `data' argument may be given to specify a ‘POST’ request
          (normally the request type is ‘GET’).  The `data' argument
          must in standard ‘application/x-www-form-urlencoded’ format;
          see the *note urllib.parse.urlencode(): 794. function.

      -- 属性: version

          Variable that specifies the user agent of the opener object.
          To get *note urllib: 11e. to tell servers that it is a
          particular user agent, set this in a subclass as a class
          variable or in the constructor before calling the base
          constructor.

 -- 类: urllib.request.FancyURLopener (...)

     3.3 版后已移除.

     *note FancyURLopener: 2c41. subclasses *note URLopener: 2c40.
     providing default handling for the following HTTP response codes:
     301, 302, 303, 307 and 401.  For the 30x response codes listed
     above, the ‘Location’ header is used to fetch the actual URL. For
     401 response codes (authentication required), basic HTTP
     authentication is performed.  For the 30x response codes, recursion
     is bounded by the value of the `maxtries' attribute, which defaults
     to 10.

     For all other response codes, the method ‘http_error_default()’ is
     called which you can override in subclasses to handle the error
     appropriately.

          注解: According to the letter of RFC 2616(1), 301 and 302
          responses to POST requests must not be automatically
          redirected without confirmation by the user.  In reality,
          browsers do allow automatic redirection of these responses,
          changing the POST to a GET, and *note urllib: 11e. reproduces
          this behaviour.

     The parameters to the constructor are the same as those for *note
     URLopener: 2c40.

          注解: When performing basic authentication, a *note
          FancyURLopener: 2c41. instance calls its *note
          prompt_user_passwd(): 2cc4. method.  The default
          implementation asks the users for the required information on
          the controlling terminal.  A subclass may override this method
          to support more appropriate behavior if needed.

     The *note FancyURLopener: 2c41. class offers one additional method
     that should be overloaded to provide the appropriate behavior:

      -- 方法: prompt_user_passwd (host, realm)

          Return information needed to authenticate the user at the
          given host in the specified security realm.  The return value
          should be a tuple, ‘(user, password)’, which can be used for
          basic authentication.

          The implementation prompts for this information on the
          terminal; an application should override this method to use an
          appropriate interaction model in the local environment.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2616.html


File: python.info,  Node: urllib request Restrictions,  Prev: 已停用的接口,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.25 ‘urllib.request’ Restrictions
.......................................

   * Currently, only the following protocols are supported: HTTP
     (versions 0.9 and 1.0), FTP, local files, and data URLs.

     在 3.4 版更改: Added support for data URLs.

   * The caching feature of *note urlretrieve(): 2cbf. has been disabled
     until someone finds the time to hack proper processing of
     Expiration time headers.

   * There should be a function to query whether a particular URL is in
     the cache.

   * For backward compatibility, if a URL appears to point to a local
     file but the file can’t be opened, the URL is re-interpreted using
     the FTP protocol.  This can sometimes cause confusing error
     messages.

   * The *note urlopen(): 795. and *note urlretrieve(): 2cbf. functions
     can cause arbitrarily long delays while waiting for a network
     connection to be set up.  This means that it is difficult to build
     an interactive Web client using these functions without using
     threads.

   * The data returned by *note urlopen(): 795. or *note urlretrieve():
     2cbf. is the raw data returned by the server.  This may be binary
     data (such as an image), plain text or (for example) HTML. The HTTP
     protocol provides type information in the reply header, which can
     be inspected by looking at the ‘Content-Type’ header.  If the
     returned data is HTML, you can use the module *note html.parser:
     92. to parse it.

   * The code handling the FTP protocol cannot differentiate between a
     file and a directory.  This can lead to unexpected behavior when
     attempting to read a URL that points to a file that is not
     accessible.  If the URL ends in a ‘/’, it is assumed to refer to a
     directory and will be handled accordingly.  But if an attempt to
     read a file leads to a 550 error (meaning the URL cannot be found
     or is not accessible, often for permission reasons), then the path
     is treated as a directory in order to handle the case when a
     directory is specified by a URL but the trailing ‘/’ has been left
     off.  This can cause misleading results when you try to fetch a
     file whose read permissions make it inaccessible; the FTP code will
     try to read it, fail with a 550 error, and then perform a directory
     listing for the unreadable file.  If fine-grained control is
     needed, consider using the *note ftplib: 84. module, subclassing
     *note FancyURLopener: 2c41, or changing `_urlopener' to meet your
     needs.


File: python.info,  Node: urllib response --- urllib 使用的 Response 类,  Next: urllib parse 用于解析 URL,  Prev: urllib request --- 用于打开 URL 的可扩展库,  Up: 互联网协议和支持

5.21.7 ‘urllib.response’ — urllib 使用的 Response 类
----------------------------------------------------

The *note urllib.response: 122. module defines functions and classes
which define a minimal file like interface, including ‘read()’ and
‘readline()’.  The typical response object is an addinfourl instance,
which defines an ‘info()’ method and that returns headers and a
‘geturl()’ method that returns the url.  Functions defined by this
module are used internally by the *note urllib.request: 121. module.


File: python.info,  Node: urllib parse 用于解析 URL,  Next: urllib error --- urllib request 引发的异常类,  Prev: urllib response --- urllib 使用的 Response 类,  Up: 互联网协议和支持

5.21.8 ‘urllib.parse’ 用于解析 URL
----------------------------------

`源代码:' Lib/urllib/parse.py(1)

__________________________________________________________________

该模块定义了一个标准接口，用于URL字符串按组件(协议、网络位置、路径等)分
解，或将组件组合回URL字符串，并将 "相对URL "转换为给定 "基础URL "的绝对
URL。

The module has been designed to match the Internet RFC on Relative
Uniform Resource Locators.  It supports the following URL schemes:
‘file’, ‘ftp’, ‘gopher’, ‘hdl’, ‘http’, ‘https’, ‘imap’, ‘mailto’,
‘mms’, ‘news’, ‘nntp’, ‘prospero’, ‘rsync’, ‘rtsp’, ‘rtspu’, ‘sftp’,
‘shttp’, ‘sip’, ‘sips’, ‘snews’, ‘svn’, ‘svn+ssh’, ‘telnet’, ‘wais’,
‘ws’, ‘wss’.

The *note urllib.parse: 120. module defines functions that fall into two
broad categories: URL parsing and URL quoting.  These are covered in
detail in the following sections.

* Menu:

* URL 解析::
* 解析ASCII编码字节::
* 结构化解析结果::
* URL Quoting::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/urllib/parse.py


File: python.info,  Node: URL 解析,  Next: 解析ASCII编码字节,  Up: urllib parse 用于解析 URL

5.21.8.1 URL 解析
.................

URL解析功能可以将一个URL字符串分割成其组件，或者将URL组件组合成一个URL字
符串。

 -- 函数: urllib.parse.urlparse (urlstring, scheme='',
          allow_fragments=True)

     Parse a URL into six components, returning a 6-item *note named
     tuple: aab.  This corresponds to the general structure of a URL:
     ‘scheme://netloc/path;parameters?query#fragment’.  Each tuple item
     is a string, possibly empty.  The components are not broken up in
     smaller parts (for example, the network location is a single
     string), and % escapes are not expanded.  The delimiters as shown
     above are not part of the result, except for a leading slash in the
     `path' component, which is retained if present.  For example:

          >>> from urllib.parse import urlparse
          >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
          >>> o
          ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
                      params='', query='', fragment='')
          >>> o.scheme
          'http'
          >>> o.port
          80
          >>> o.geturl()
          'http://www.cwi.nl:80/%7Eguido/Python.html'

     Following the syntax specifications in RFC 1808(1), urlparse
     recognizes a netloc only if it is properly introduced by ’//’.
     Otherwise the input is presumed to be a relative URL and thus to
     start with a path component.

          >>> from urllib.parse import urlparse
          >>> urlparse('//www.cwi.nl:80/%7Eguido/Python.html')
          ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
                      params='', query='', fragment='')
          >>> urlparse('www.cwi.nl/%7Eguido/Python.html')
          ParseResult(scheme='', netloc='', path='www.cwi.nl/%7Eguido/Python.html',
                      params='', query='', fragment='')
          >>> urlparse('help/Python.html')
          ParseResult(scheme='', netloc='', path='help/Python.html', params='',
                      query='', fragment='')

     `scheme' 参数给出了默认的协议，只有在 URL 未指定协议的情况下才会被
     使用。 它应该是与 `urlstring' 相同的类型（文本或字节串），除此之外
     默认值 ‘''’ 也总是被允许，并会在适当情况下自动转换为 ‘b''’。

     If the `allow_fragments' argument is false, fragment identifiers
     are not recognized.  Instead, they are parsed as part of the path,
     parameters or query component, and ‘fragment’ is set to the empty
     string in the return value.

     返回值是一个 *note named tuple: aab.，这意味着它的条目可以通过索引
     或作为命名属性来访问，这些属性是：

     属性                   索引        值                             值（如果不存在）
                                                                       
     ---------------------------------------------------------------------------------------------
                                                                       
     ‘scheme’               0           URL方案说明符                  `scheme' parameter
                                                                       
                                                                       
     ‘netloc’               1           网络位置部分                   空字符串
                                                                       
                                                                       
     ‘path’                 2           分层路径                       空字符串
                                                                       
                                                                       
     ‘params’               3           最后路径元素的参数             空字符串
                                                                       
                                                                       
     ‘query’                4           查询组件                       空字符串
                                                                       
                                                                       
     ‘fragment’             5           片段识别                       空字符串
                                                                       
                                                                       
     ‘username’                         用户名                         *note None: 158.
                                                                       
                                                                       
     ‘password’                         密码                           *note None: 158.
                                                                       
                                                                       
     ‘hostname’                         主机名（小写）                 *note None: 158.
                                                                       
                                                                       
     ‘port’                             端口号为整数（如果存在）       *note None: 158.
                                                                       

     如果在 URL 中指定了无效的端口，读取 ‘port’ 属性将引发 *note
     ValueError: 1fc.。 有关结果对象的更多信息请参阅 *note
     结构化解析结果: 2cca. 一节。

     Unmatched square brackets in the ‘netloc’ attribute will raise a
     *note ValueError: 1fc.

     Characters in the ‘netloc’ attribute that decompose under NFKC
     normalization (as used by the IDNA encoding) into any of ‘/’, ‘?’,
     ‘#’, ‘@’, or ‘:’ will raise a *note ValueError: 1fc.  If the URL is
     decomposed before parsing, no error will be raised.

     As is the case with all named tuples, the subclass has a few
     additional methods and attributes that are particularly useful.
     One such method is ‘_replace()’.  The ‘_replace()’ method will
     return a new ParseResult object replacing specified fields with new
     values.

          >>> from urllib.parse import urlparse
          >>> u = urlparse('//www.cwi.nl:80/%7Eguido/Python.html')
          >>> u
          ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
                      params='', query='', fragment='')
          >>> u._replace(scheme='http')
          ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
                      params='', query='', fragment='')

     在 3.2 版更改: 添加了IPv6 URL解析功能。

     在 3.3 版更改: The fragment is now parsed for all URL schemes
     (unless `allow_fragment' is false), in accordance with RFC 3986(2).
     Previously, a whitelist of schemes that support fragments existed.

     在 3.6 版更改: Out-of-range port numbers now raise *note
     ValueError: 1fc, instead of returning *note None: 158.

     在 3.8 版更改: Characters that affect netloc parsing under NFKC
     normalization will now raise *note ValueError: 1fc.

 -- 函数: urllib.parse.parse_qs (qs, keep_blank_values=False,
          strict_parsing=False, encoding='utf-8', errors='replace',
          max_num_fields=None, separator='&')

     Parse a query string given as a string argument (data of type
     ‘application/x-www-form-urlencoded’).  Data are returned as a
     dictionary.  The dictionary keys are the unique query variable
     names and the values are lists of values for each name.

     The optional argument `keep_blank_values' is a flag indicating
     whether blank values in percent-encoded queries should be treated
     as blank strings.  A true value indicates that blanks should be
     retained as blank strings.  The default false value indicates that
     blank values are to be ignored and treated as if they were not
     included.

     The optional argument `strict_parsing' is a flag indicating what to
     do with parsing errors.  If false (the default), errors are
     silently ignored.  If true, errors raise a *note ValueError: 1fc.
     exception.

     The optional `encoding' and `errors' parameters specify how to
     decode percent-encoded sequences into Unicode characters, as
     accepted by the *note bytes.decode(): c40. method.

     The optional argument `max_num_fields' is the maximum number of
     fields to read.  If set, then throws a *note ValueError: 1fc. if
     there are more than `max_num_fields' fields read.

     The optional argument `separator' is the symbol to use for
     separating the query arguments.  It defaults to ‘&’.

     Use the *note urllib.parse.urlencode(): 794. function (with the
     ‘doseq’ parameter set to ‘True’) to convert such dictionaries into
     query strings.

     在 3.2 版更改: Add `encoding' and `errors' parameters.

     在 3.8 版更改: Added `max_num_fields' parameter.

     在 3.8.8 版更改: Added `separator' parameter with the default value
     of ‘&’.  Python versions earlier than Python 3.8.8 allowed using
     both ‘;’ and ‘&’ as query parameter separator.  This has been
     changed to allow only a single separator key, with ‘&’ as the
     default separator.

 -- 函数: urllib.parse.parse_qsl (qs, keep_blank_values=False,
          strict_parsing=False, encoding='utf-8', errors='replace',
          max_num_fields=None, separator='&')

     Parse a query string given as a string argument (data of type
     ‘application/x-www-form-urlencoded’).  Data are returned as a list
     of name, value pairs.

     The optional argument `keep_blank_values' is a flag indicating
     whether blank values in percent-encoded queries should be treated
     as blank strings.  A true value indicates that blanks should be
     retained as blank strings.  The default false value indicates that
     blank values are to be ignored and treated as if they were not
     included.

     The optional argument `strict_parsing' is a flag indicating what to
     do with parsing errors.  If false (the default), errors are
     silently ignored.  If true, errors raise a *note ValueError: 1fc.
     exception.

     The optional `encoding' and `errors' parameters specify how to
     decode percent-encoded sequences into Unicode characters, as
     accepted by the *note bytes.decode(): c40. method.

     The optional argument `max_num_fields' is the maximum number of
     fields to read.  If set, then throws a *note ValueError: 1fc. if
     there are more than `max_num_fields' fields read.

     The optional argument `separator' is the symbol to use for
     separating the query arguments.  It defaults to ‘&’.

     Use the *note urllib.parse.urlencode(): 794. function to convert
     such lists of pairs into query strings.

     在 3.2 版更改: Add `encoding' and `errors' parameters.

     在 3.8 版更改: Added `max_num_fields' parameter.

     在 3.8.8 版更改: Added `separator' parameter with the default value
     of ‘&’.  Python versions earlier than Python 3.8.8 allowed using
     both ‘;’ and ‘&’ as query parameter separator.  This has been
     changed to allow only a single separator key, with ‘&’ as the
     default separator.

 -- 函数: urllib.parse.urlunparse (parts)

     Construct a URL from a tuple as returned by ‘urlparse()’.  The
     `parts' argument can be any six-item iterable.  This may result in
     a slightly different, but equivalent URL, if the URL that was
     parsed originally had unnecessary delimiters (for example, a ‘?’
     with an empty query; the RFC states that these are equivalent).

 -- 函数: urllib.parse.urlsplit (urlstring, scheme='',
          allow_fragments=True)

     This is similar to *note urlparse(): 603, but does not split the
     params from the URL. This should generally be used instead of *note
     urlparse(): 603. if the more recent URL syntax allowing parameters
     to be applied to each segment of the `path' portion of the URL (see
     RFC 2396(3)) is wanted.  A separate function is needed to separate
     the path segments and parameters.  This function returns a 5-item
     *note named tuple: aab.:

          (addressing scheme, network location, path, query, fragment identifier).

     The return value is a *note named tuple: aab, its items can be
     accessed by index or as named attributes:

     属性                   索引        值                            值（如果不存在）
                                                                      
     --------------------------------------------------------------------------------------------
                                                                      
     ‘scheme’               0           URL方案说明符                 `scheme' parameter
                                                                      
                                                                      
     ‘netloc’               1           网络位置部分                  空字符串
                                                                      
                                                                      
     ‘path’                 2           分层路径                      空字符串
                                                                      
                                                                      
     ‘query’                3           查询组件                      空字符串
                                                                      
                                                                      
     ‘fragment’             4           片段识别                      空字符串
                                                                      
                                                                      
     ‘username’                         用户名                        *note None: 158.
                                                                      
                                                                      
     ‘password’                         密码                          *note None: 158.
                                                                      
                                                                      
     ‘hostname’                         主机名（小写）                *note None: 158.
                                                                      
                                                                      
     ‘port’                             端口号为整数（如果存在）      *note None: 158.
                                                                      

     如果在 URL 中指定了无效的端口，读取 ‘port’ 属性将引发 *note
     ValueError: 1fc.。 有关结果对象的更多信息请参阅 *note
     结构化解析结果: 2cca. 一节。

     Unmatched square brackets in the ‘netloc’ attribute will raise a
     *note ValueError: 1fc.

     Characters in the ‘netloc’ attribute that decompose under NFKC
     normalization (as used by the IDNA encoding) into any of ‘/’, ‘?’,
     ‘#’, ‘@’, or ‘:’ will raise a *note ValueError: 1fc.  If the URL is
     decomposed before parsing, no error will be raised.

     Following the WHATWG spec(4) that updates RFC 3986, ASCII newline
     ‘\n’, ‘\r’ and tab ‘\t’ characters are stripped from the URL.

     在 3.6 版更改: Out-of-range port numbers now raise *note
     ValueError: 1fc, instead of returning *note None: 158.

     在 3.8 版更改: Characters that affect netloc parsing under NFKC
     normalization will now raise *note ValueError: 1fc.

     在 3.8.10 版更改: ASCII newline and tab characters are stripped
     from the URL.

 -- 函数: urllib.parse.urlunsplit (parts)

     Combine the elements of a tuple as returned by *note urlsplit():
     602. into a complete URL as a string.  The `parts' argument can be
     any five-item iterable.  This may result in a slightly different,
     but equivalent URL, if the URL that was parsed originally had
     unnecessary delimiters (for example, a ?  with an empty query; the
     RFC states that these are equivalent).

 -- 函数: urllib.parse.urljoin (base, url, allow_fragments=True)

     Construct a full ("absolute") URL by combining a "base URL"
     (`base') with another URL (`url').  Informally, this uses
     components of the base URL, in particular the addressing scheme,
     the network location and (part of) the path, to provide missing
     components in the relative URL. For example:

          >>> from urllib.parse import urljoin
          >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
          'http://www.cwi.nl/%7Eguido/FAQ.html'

     The `allow_fragments' argument has the same meaning and default as
     for *note urlparse(): 603.

          注解: If `url' is an absolute URL (that is, starting with ‘//’
          or ‘scheme://’), the `url'’s host name and/or scheme will be
          present in the result.  For example:

          >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',
          ...         '//www.python.org/%7Eguido')
          'http://www.python.org/%7Eguido'

     If you do not want that behavior, preprocess the `url' with *note
     urlsplit(): 602. and *note urlunsplit(): 2ccc, removing possible
     `scheme' and `netloc' parts.

     在 3.5 版更改: Behaviour updated to match the semantics defined in
     RFC 3986(5).

 -- 函数: urllib.parse.urldefrag (url)

     If `url' contains a fragment identifier, return a modified version
     of `url' with no fragment identifier, and the fragment identifier
     as a separate string.  If there is no fragment identifier in `url',
     return `url' unmodified and an empty string.

     The return value is a *note named tuple: aab, its items can be
     accessed by index or as named attributes:

     属性                   索引        值                            值（如果不存在）
                                                                      
     --------------------------------------------------------------------------------------------
                                                                      
     ‘url’                  0           URL with no fragment          空字符串
                                                                      
                                                                      
     ‘fragment’             1           片段识别                      空字符串
                                                                      

     See section *note 结构化解析结果: 2cca. for more information on the
     result object.

     在 3.2 版更改: Result is a structured object rather than a simple
     2-tuple.

 -- 函数: urllib.parse.unwrap (url)

     Extract the url from a wrapped URL (that is, a string formatted as
     ‘<URL:scheme://host/path>’, ‘<scheme://host/path>’,
     ‘URL:scheme://host/path’ or ‘scheme://host/path’).  If `url' is not
     a wrapped URL, it is returned without changes.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc1808.html

   (2) https://tools.ietf.org/html/rfc3986.html

   (3) https://tools.ietf.org/html/rfc2396.html

   (4) https://url.spec.whatwg.org/#concept-basic-url-parser

   (5) https://tools.ietf.org/html/rfc3986.html


File: python.info,  Node: 解析ASCII编码字节,  Next: 结构化解析结果,  Prev: URL 解析,  Up: urllib parse 用于解析 URL

5.21.8.2 解析ASCII编码字节
..........................

The URL parsing functions were originally designed to operate on
character strings only.  In practice, it is useful to be able to
manipulate properly quoted and encoded URLs as sequences of ASCII bytes.
Accordingly, the URL parsing functions in this module all operate on
*note bytes: 33a. and *note bytearray: 33b. objects in addition to *note
str: 339. objects.

If *note str: 339. data is passed in, the result will also contain only
*note str: 339. data.  If *note bytes: 33a. or *note bytearray: 33b.
data is passed in, the result will contain only *note bytes: 33a. data.

Attempting to mix *note str: 339. data with *note bytes: 33a. or *note
bytearray: 33b. in a single function call will result in a *note
TypeError: 193. being raised, while attempting to pass in non-ASCII byte
values will trigger *note UnicodeDecodeError: 1fe.

To support easier conversion of result objects between *note str: 339.
and *note bytes: 33a, all return values from URL parsing functions
provide either an ‘encode()’ method (when the result contains *note str:
339. data) or a ‘decode()’ method (when the result contains *note bytes:
33a. data).  The signatures of these methods match those of the
corresponding *note str: 339. and *note bytes: 33a. methods (except that
the default encoding is ‘'ascii'’ rather than ‘'utf-8'’).  Each produces
a value of a corresponding type that contains either *note bytes: 33a.
data (for ‘encode()’ methods) or *note str: 339. data (for ‘decode()’
methods).

Applications that need to operate on potentially improperly quoted URLs
that may contain non-ASCII data will need to do their own decoding from
bytes to characters before invoking the URL parsing methods.

The behaviour described in this section applies only to the URL parsing
functions.  The URL quoting functions use their own rules when producing
or consuming byte sequences as detailed in the documentation of the
individual URL quoting functions.

在 3.2 版更改: URL parsing functions now accept ASCII encoded byte
sequences


File: python.info,  Node: 结构化解析结果,  Next: URL Quoting,  Prev: 解析ASCII编码字节,  Up: urllib parse 用于解析 URL

5.21.8.3 结构化解析结果
.......................

The result objects from the *note urlparse(): 603, *note urlsplit():
602. and *note urldefrag(): be6. functions are subclasses of the *note
tuple: 486. type.  These subclasses add the attributes listed in the
documentation for those functions, the encoding and decoding support
described in the previous section, as well as an additional method:

 -- 方法: urllib.parse.SplitResult.geturl ()

     Return the re-combined version of the original URL as a string.
     This may differ from the original URL in that the scheme may be
     normalized to lower case and empty components may be dropped.
     Specifically, empty parameters, queries, and fragment identifiers
     will be removed.

     For *note urldefrag(): be6. results, only empty fragment
     identifiers will be removed.  For *note urlsplit(): 602. and *note
     urlparse(): 603. results, all noted changes will be made to the URL
     returned by this method.

     The result of this method remains unchanged if passed back through
     the original parsing function:

          >>> from urllib.parse import urlsplit
          >>> url = 'HTTP://www.Python.org/doc/#'
          >>> r1 = urlsplit(url)
          >>> r1.geturl()
          'http://www.Python.org/doc/'
          >>> r2 = urlsplit(r1.geturl())
          >>> r2.geturl()
          'http://www.Python.org/doc/'

The following classes provide the implementations of the structured
parse results when operating on *note str: 339. objects:

 -- 类: urllib.parse.DefragResult (url, fragment)

     Concrete class for *note urldefrag(): be6. results containing *note
     str: 339. data.  The ‘encode()’ method returns a *note
     DefragResultBytes: 2cd2. instance.

     3.2 新版功能.

 -- 类: urllib.parse.ParseResult (scheme, netloc, path, params, query,
          fragment)

     Concrete class for *note urlparse(): 603. results containing *note
     str: 339. data.  The ‘encode()’ method returns a *note
     ParseResultBytes: 2cd4. instance.

 -- 类: urllib.parse.SplitResult (scheme, netloc, path, query, fragment)

     Concrete class for *note urlsplit(): 602. results containing *note
     str: 339. data.  The ‘encode()’ method returns a *note
     SplitResultBytes: 2cd6. instance.

The following classes provide the implementations of the parse results
when operating on *note bytes: 33a. or *note bytearray: 33b. objects:

 -- 类: urllib.parse.DefragResultBytes (url, fragment)

     Concrete class for *note urldefrag(): be6. results containing *note
     bytes: 33a. data.  The ‘decode()’ method returns a *note
     DefragResult: 2cd1. instance.

     3.2 新版功能.

 -- 类: urllib.parse.ParseResultBytes (scheme, netloc, path, params,
          query, fragment)

     Concrete class for *note urlparse(): 603. results containing *note
     bytes: 33a. data.  The ‘decode()’ method returns a *note
     ParseResult: 2cd3. instance.

     3.2 新版功能.

 -- 类: urllib.parse.SplitResultBytes (scheme, netloc, path, query,
          fragment)

     Concrete class for *note urlsplit(): 602. results containing *note
     bytes: 33a. data.  The ‘decode()’ method returns a *note
     SplitResult: 2cd5. instance.

     3.2 新版功能.


File: python.info,  Node: URL Quoting,  Prev: 结构化解析结果,  Up: urllib parse 用于解析 URL

5.21.8.4 URL Quoting
....................

The URL quoting functions focus on taking program data and making it
safe for use as URL components by quoting special characters and
appropriately encoding non-ASCII text.  They also support reversing
these operations to recreate the original data from the contents of a
URL component if that task isn’t already covered by the URL parsing
functions above.

 -- 函数: urllib.parse.quote (string, safe='/', encoding=None,
          errors=None)

     Replace special characters in `string' using the ‘%xx’ escape.
     Letters, digits, and the characters ‘'_.-~'’ are never quoted.  By
     default, this function is intended for quoting the path section of
     URL. The optional `safe' parameter specifies additional ASCII
     characters that should not be quoted — its default value is ‘'/'’.

     `string' may be either a *note str: 339. or a *note bytes: 33a.

     在 3.7 版更改: Moved from RFC 2396(1) to RFC 3986(2) for quoting
     URL strings.  "~" is now included in the set of unreserved
     characters.

     The optional `encoding' and `errors' parameters specify how to deal
     with non-ASCII characters, as accepted by the *note str.encode():
     c3f. method.  `encoding' defaults to ‘'utf-8'’.  `errors' defaults
     to ‘'strict'’, meaning unsupported characters raise a *note
     UnicodeEncodeError: 1fd.  `encoding' and `errors' must not be
     supplied if `string' is a *note bytes: 33a, or a *note TypeError:
     193. is raised.

     Note that ‘quote(string, safe, encoding, errors)’ is equivalent to
     ‘quote_from_bytes(string.encode(encoding, errors), safe)’.

     Example: ‘quote('/El Niño/')’ yields ‘'/El%20Ni%C3%B1o/'’.

 -- 函数: urllib.parse.quote_plus (string, safe='', encoding=None,
          errors=None)

     Like *note quote(): 415, but also replace spaces by plus signs, as
     required for quoting HTML form values when building up a query
     string to go into a URL. Plus signs in the original string are
     escaped unless they are included in `safe'.  It also does not have
     `safe' default to ‘'/'’.

     Example: ‘quote_plus('/El Niño/')’ yields ‘'%2FEl+Ni%C3%B1o%2F'’.

 -- 函数: urllib.parse.quote_from_bytes (bytes, safe='/')

     Like *note quote(): 415, but accepts a *note bytes: 33a. object
     rather than a *note str: 339, and does not perform string-to-bytes
     encoding.

     Example: ‘quote_from_bytes(b'a&\xef')’ yields ‘'a%26%EF'’.

 -- 函数: urllib.parse.unquote (string, encoding='utf-8',
          errors='replace')

     Replace ‘%xx’ escapes by their single-character equivalent.  The
     optional `encoding' and `errors' parameters specify how to decode
     percent-encoded sequences into Unicode characters, as accepted by
     the *note bytes.decode(): c40. method.

     `string' must be a *note str: 339.

     `encoding' defaults to ‘'utf-8'’.  `errors' defaults to
     ‘'replace'’, meaning invalid sequences are replaced by a
     placeholder character.

     Example: ‘unquote('/El%20Ni%C3%B1o/')’ yields ‘'/El Niño/'’.

 -- 函数: urllib.parse.unquote_plus (string, encoding='utf-8',
          errors='replace')

     Like *note unquote(): ee7, but also replace plus signs by spaces,
     as required for unquoting HTML form values.

     `string' must be a *note str: 339.

     Example: ‘unquote_plus('/El+Ni%C3%B1o/')’ yields ‘'/El Niño/'’.

 -- 函数: urllib.parse.unquote_to_bytes (string)

     Replace ‘%xx’ escapes by their single-octet equivalent, and return
     a *note bytes: 33a. object.

     `string' may be either a *note str: 339. or a *note bytes: 33a.

     If it is a *note str: 339, unescaped non-ASCII characters in
     `string' are encoded into UTF-8 bytes.

     Example: ‘unquote_to_bytes('a%26%EF')’ yields ‘b'a&\xef'’.

 -- 函数: urllib.parse.urlencode (query, doseq=False, safe='',
          encoding=None, errors=None, quote_via=quote_plus)

     Convert a mapping object or a sequence of two-element tuples, which
     may contain *note str: 339. or *note bytes: 33a. objects, to a
     percent-encoded ASCII text string.  If the resultant string is to
     be used as a `data' for POST operation with the *note urlopen():
     795. function, then it should be encoded to bytes, otherwise it
     would result in a *note TypeError: 193.

     The resulting string is a series of ‘key=value’ pairs separated by
     ‘'&'’ characters, where both `key' and `value' are quoted using the
     `quote_via' function.  By default, *note quote_plus(): be7. is used
     to quote the values, which means spaces are quoted as a ‘'+'’
     character and ’/’ characters are encoded as ‘%2F’, which follows
     the standard for GET requests
     (‘application/x-www-form-urlencoded’).  An alternate function that
     can be passed as `quote_via' is *note quote(): 415, which will
     encode spaces as ‘%20’ and not encode ’/’ characters.  For maximum
     control of what is quoted, use ‘quote’ and specify a value for
     `safe'.

     When a sequence of two-element tuples is used as the `query'
     argument, the first element of each tuple is a key and the second
     is a value.  The value element in itself can be a sequence and in
     that case, if the optional parameter `doseq' is evaluates to
     ‘True’, individual ‘key=value’ pairs separated by ‘'&'’ are
     generated for each element of the value sequence for the key.  The
     order of parameters in the encoded string will match the order of
     parameter tuples in the sequence.

     The `safe', `encoding', and `errors' parameters are passed down to
     `quote_via' (the `encoding' and `errors' parameters are only passed
     when a query element is a *note str: 339.).

     To reverse this encoding process, *note parse_qs(): 2ec. and *note
     parse_qsl(): 2ed. are provided in this module to parse query
     strings into Python data structures.

     Refer to *note urllib examples: 2cbd. to find out how urlencode
     method can be used for generating query string for a URL or data
     for POST.

     在 3.2 版更改: 查询参数支持字节和字符串对象。

     3.5 新版功能: `quote_via' 参数.

参见
....

WHATWG(3) - URL Living standard

     Working Group for the URL Standard that defines URLs, domains, IP
     addresses, the application/x-www-form-urlencoded format, and their
     API.

RFC 3986(4) - 统一资源标识符

     This is the current standard (STD66).  Any changes to urllib.parse
     module should conform to this.  Certain deviations could be
     observed, which are mostly for backward compatibility purposes and
     for certain de-facto parsing requirements as commonly observed in
     major browsers.

RFC 2732(5) - Format for Literal IPv6 Addresses in URL’s.

     This specifies the parsing requirements of IPv6 URLs.

RFC 2396(6) - 统一资源标识符（URI）：通用语法

     Document describing the generic syntactic requirements for both
     Uniform Resource Names (URNs) and Uniform Resource Locators (URLs).

RFC 2368(7) - The mailto URL scheme.

     Parsing requirements for mailto URL schemes.

RFC 1808(8) - Relative Uniform Resource Locators

     This Request For Comments includes the rules for joining an
     absolute and a relative URL, including a fair number of "Abnormal
     Examples" which govern the treatment of border cases.

RFC 1738(9) - Uniform Resource Locators (URL)

     This specifies the formal syntax and semantics of absolute URLs.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2396.html

   (2) https://tools.ietf.org/html/rfc3986.html

   (3) https://url.spec.whatwg.org/

   (4) https://tools.ietf.org/html/rfc3986.html

   (5) https://tools.ietf.org/html/rfc2732.html

   (6) https://tools.ietf.org/html/rfc2396.html

   (7) https://tools.ietf.org/html/rfc2368.html

   (8) https://tools.ietf.org/html/rfc1808.html

   (9) https://tools.ietf.org/html/rfc1738.html


File: python.info,  Node: urllib error --- urllib request 引发的异常类,  Next: urllib robotparser --- robots txt 语法分析程序,  Prev: urllib parse 用于解析 URL,  Up: 互联网协议和支持

5.21.9 ‘urllib.error’ — urllib.request 引发的异常类
---------------------------------------------------

`源代码：' Lib/urllib/error.py(1)

__________________________________________________________________

*note urllib.error: 11f. 模块为 *note urllib.request: 121. 所引发的异常
定义了异常类。 基础异常类是 *note URLError: 2c42.。

下列异常会被 *note urllib.error: 11f. 按需引发：

 -- 例外: urllib.error.URLError

     处理程序在遇到问题时会引发此异常（或其派生的异常）。 它是 *note
     OSError: 1d4. 的一个子类。

      -- 属性: reason

          此错误的原因。 它可以是一个消息字符串或另一个异常实例。

     在 3.3 版更改: *note URLError: 2c42. 已被设为 *note OSError: 1d4. 而
     不是 *note IOError: 99a. 的子类。

 -- 例外: urllib.error.HTTPError

     虽然是一个异常（*note URLError: 2c42. 的一个子类），*note
     HTTPError: 904. 也可以作为一个非异常的文件类返回值（与 *note
     urlopen(): 795. 返所回的对象相同）。 这适用于处理特殊 HTTP 错误例如
     作为认证请求的时候。

      -- 属性: code

          一个 HTTP 状态码，具体定义见 RFC 2616(2)。 这个数字的值对应于
          存放在 *note http.server.BaseHTTPRequestHandler.responses:
          2ce0. 代码字典中的某个值。

      -- 属性: reason

          这通常是一个解释本次错误原因的字符串。

      -- 属性: headers

          导致 *note HTTPError: 904. 的特定 HTTP 请求的 HTTP 响应头。

          3.4 新版功能.

 -- 例外: urllib.error.ContentTooShortError (msg, content)

     此异常会在 *note urlretrieve(): 2cbf. 函数检测到已下载的数据量小于
     期待的数据量（由 `Content-Length' 头给定）时被引发。 ‘content’ 属性
     中将存放已下载（可能被截断）的数据。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/urllib/error.py

   (2) https://tools.ietf.org/html/rfc2616.html


File: python.info,  Node: urllib robotparser --- robots txt 语法分析程序,  Next: http --- HTTP 模块,  Prev: urllib error --- urllib request 引发的异常类,  Up: 互联网协议和支持

5.21.10 ‘urllib.robotparser’ — robots.txt 语法分析程序
------------------------------------------------------

`源代码：' Lib/urllib/robotparser.py(1)

__________________________________________________________________

此模块提供了一个单独的类 *note RobotFileParser: 5b6.，它可以回答关于某个
特定用户代理是否能在 Web 站点获取发布 ‘robots.txt’ 文件的 URL 的问题。 有
关 ‘robots.txt’ 文件结构的更多细节请参阅
‘http://www.robotstxt.org/orig.html’。

 -- 类: urllib.robotparser.RobotFileParser (url='')

     这个类提供了一些可以读取、解析和回答关于 `url' 上的 ‘robots.txt’ 文
     件的问题的方法。

      -- 方法: set_url (url)

          设置指向 ‘robots.txt’ 文件的 URL。

      -- 方法: read ()

          读取 ‘robots.txt’ URL 并将其输入解析器。

      -- 方法: parse (lines)

          解析行参数。

      -- 方法: can_fetch (useragent, url)

          如果允许 `useragent' 按照被解析 ‘robots.txt’ 文件中的规则来获
          取 `url' 则返回 ‘True’。

      -- 方法: mtime ()

          返回最近一次获取 ‘robots.txt’ 文件的时间。 这适用于需要定期检
          查 ‘robots.txt’ 文件更新情况的长时间运行的网页爬虫。

      -- 方法: modified ()

          将最近一次获取 ‘robots.txt’ 文件的时间设置为当前时间。

      -- 方法: crawl_delay (useragent)

          为指定的 `useragent' 从 ‘robots.txt’ 返回 ‘Crawl-delay’ 形参。
          如果此形参不存在或不适用于指定的 `useragent' 或者此形参的
          ‘robots.txt’ 条目存在语法错误，则返回 ‘None’。

          3.6 新版功能.

      -- 方法: request_rate (useragent)

          以 *note named tuple: aab. ‘RequestRate(requests, seconds)’ 的
          形式从 ‘robots.txt’ 返回 ‘Request-rate’ 形参的内容。 如果此形
          参不存在或不适用于指定的 `useragent' 或者此形参的 ‘robots.txt’
          条目存在语法错误，则返回 ‘None’。

          3.6 新版功能.

      -- 方法: site_maps ()

          以 *note list(): 263. 的形式从 ‘robots.txt’ 返回 ‘Sitemap’ 形
          参的内容。 如果此形参不存在或者此形参的 ‘robots.txt’ 条目存在
          语法错误，则返回 ‘None’。

          3.8 新版功能.

下面的例子演示了 *note RobotFileParser: 5b6. 类的基本用法:

     >>> import urllib.robotparser
     >>> rp = urllib.robotparser.RobotFileParser()
     >>> rp.set_url("http://www.musi-cal.com/robots.txt")
     >>> rp.read()
     >>> rrate = rp.request_rate("*")
     >>> rrate.requests
     3
     >>> rrate.seconds
     20
     >>> rp.crawl_delay("*")
     6
     >>> rp.can_fetch("*", "http://www.musi-cal.com/cgi-bin/search?city=San+Francisco")
     False
     >>> rp.can_fetch("*", "http://www.musi-cal.com/")
     True

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/urllib/robotparser.py


File: python.info,  Node: http --- HTTP 模块,  Next: http client --- HTTP 协议客户端,  Prev: urllib robotparser --- robots txt 语法分析程序,  Up: 互联网协议和支持

5.21.11 ‘http’ — HTTP 模块
--------------------------

`源代码:' Lib/http/__init__.py(1)

__________________________________________________________________

*note http: 93. 是一个包，它收集了多个用于处理超文本传输协议的模块:

   * *note http.client: 94. 是一个低层级的 HTTP 协议客户端；对于高层级的
     URL 访问请使用 *note urllib.request: 121.

   * *note http.server: 97. 包含基于 *note socketserver: f1. 的基本 HTTP
     服务类

   * *note http.cookies: 96. 包含一些有用来实现通过 cookies 进行状态管理
     的工具

   * *note http.cookiejar: 95. 提供了 cookies 的持久化

*note http: 93. 也是一个通过 *note http.HTTPStatus: 6eb. 枚举定义了一些
HTTP 状态码以及相关联消息的模块

 -- 类: http.HTTPStatus

     3.5 新版功能.

     *note enum.IntEnum: 596. 的子类，它定义了组 HTTP 状态码，原理短语以
     及用英语书写的长描述文本。

     用法:

          >>> from http import HTTPStatus
          >>> HTTPStatus.OK
          <HTTPStatus.OK: 200>
          >>> HTTPStatus.OK == 200
          True
          >>> HTTPStatus.OK.value
          200
          >>> HTTPStatus.OK.phrase
          'OK'
          >>> HTTPStatus.OK.description
          'Request fulfilled, document follows'
          >>> list(HTTPStatus)
          [<HTTPStatus.CONTINUE: 100>, <HTTPStatus.SWITCHING_PROTOCOLS: 101>, ...]

* Menu:

* HTTP 状态码::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/http/__init__.py


File: python.info,  Node: HTTP 状态码,  Up: http --- HTTP 模块

5.21.11.1 HTTP 状态码
.....................

已支持并且已在 *note http.HTTPStatus: 6eb. IANA 注册(1) 的状态码有：

双字母代    映射名                                  详情
码                                                  

----------------------------------------------------------------------------------------------------------------------------------------
                                                    
‘100’       ‘CONTINUE’：继续                        HTTP/1.1 RFC 7231(2), 6.2.1 节
                                                    
                                                    
‘101’       ‘SWITCHING_PROTOCOLS’                   HTTP/1.1 RFC 7231, 6.2.2 节
                                                    
                                                    
‘102’       ‘PROCESSING’                            WebDAV RFC 2518, 10.1 节
                                                    
                                                    
‘200’       ‘OK’                                    HTTP/1.1 RFC 7231, 6.3.1 节
                                                    
                                                    
‘201’       ‘CREATED’                               HTTP/1.1 RFC 7231, 6.3.2 节
                                                    
                                                    
‘202’       ‘ACCEPTED’                              HTTP/1.1 RFC 7231, 6.3.3 节
                                                    
                                                    
‘203’       ‘NON_AUTHORITATIVE_INFORMATION’         HTTP/1.1 RFC 7231, 6.3.4 节
                                                    
                                                    
‘204’       ‘NO_CONTENT’: 没有内容                  HTTP/1.1 RFC 7231, 6.3.5 节
                                                    
                                                    
‘205’       ‘RESET_CONTENT’                         HTTP/1.1 RFC 7231, 6.3.6 节
                                                    
                                                    
‘206’       ‘PARTIAL_CONTENT’                       HTTP/1.1 RFC 7233, 4.1 节
                                                    
                                                    
‘207’       ‘MULTI_STATUS’                          WebDAV RFC 4918, 11.1 节
                                                    
                                                    
‘208’       ‘ALREADY_REPORTED’                      WebDAV Binding Extensions RFC 5842, 7.1 节（实验性）
                                                    
                                                    
‘226’       ‘IM_USED’                               Delta Encoding in HTTP RFC 3229, 10.4.1 节
                                                    
                                                    
‘300’       ‘MULTIPLE_CHOICES’：有多种资源可选择    HTTP/1.1 RFC 7231, 6.4.1 节
                                                    
                                                    
‘301’       ‘MOVED_PERMANENTLY’：永久移动           HTTP/1.1 RFC 7231, 6.4.2 节
                                                    
                                                    
‘302’       ‘FOUND’：临时移动                       HTTP/1.1 RFC 7231, 6.4.3 节
                                                    
                                                    
‘303’       ‘SEE_OTHER’：已经移动                   HTTP/1.1 RFC 7231, 6.4.4 节
                                                    
                                                    
‘304’       ‘NOT_MODIFIED’：没有修改                HTTP/1.1 RFC 7232, 4.1 节
                                                    
                                                    
‘305’       ‘USE_PROXY’：使用代理                   HTTP/1.1 RFC 7231, 6.4.5 节
                                                    
                                                    
‘307’       ‘TEMPORARY_REDIRECT’：临时重定向        HTTP/1.1 RFC 7231(3), 6.4.7 节
                                                    
                                                    
‘308’       ‘PERMANENT_REDIRECT’：永久重定向        Permanent Redirect RFC 7238(4), Section 3 (Experimental)
                                                    
                                                    
‘400’       ‘BAD_REQUEST’：错误请求                 HTTP/1.1 RFC 7231, 6.5.1 节
                                                    
                                                    
‘401’       ‘UNAUTHORIZED’：未授权                  HTTP/1.1 Authentication RFC 7235, 3.1 节
                                                    
                                                    
‘402’       ‘PAYMENT_REQUIRED’：保留，将来使用      HTTP/1.1 RFC 7231, 6.5.2 节
                                                    
                                                    
‘403’       ‘FORBIDDEN’：禁止                       HTTP/1.1 RFC 7231, 6.5.3 节
                                                    
                                                    
‘404’       ‘NOT_FOUND’：没有找到                   HTTP/1.1 RFC 7231, 6.5.4 节
                                                    
                                                    
‘405’       ‘METHOD_NOT_ALLOWED’：该请求方法不允    HTTP/1.1 RFC 7231, 6.5.5 节
            许                                      
            
                                                    
‘406’       ‘NOT_ACCEPTABLE’：不可接受              HTTP/1.1 RFC 7231, 6.5.6 节
                                                    
                                                    
‘407’       ‘PROXY_AUTHENTICATION_REQUIRED’：要求   HTTP/1.1 Authentication RFC 7235, 3.1 节
            使用代理验明正身                        
            
                                                    
‘408’       ‘REQUEST_TIMEOUT’：请求超时             HTTP/1.1 RFC 7231(5), 6.5.7 节
                                                    
                                                    
‘409’       ‘CONFLICT’：冲突                        HTTP/1.1 RFC 7231, 6.5.8 节
                                                    
                                                    
‘410’       ‘GONE’：已经不在了                      HTTP/1.1 RFC 7231, 6.5.9 节
                                                    
                                                    
‘411’       ‘LENGTH_REQUIRED’：长度要求             HTTP/1.1 RFC 7231, 6.5.10 节
                                                    
                                                    
‘412’       ‘PRECONDITION_FAILED’：前提条件错误     HTTP/1.1 RFC 7232, 4.2 节
                                                    
                                                    
‘413’       ‘REQUEST_ENTITY_TOO_LARGE’：请求体太    HTTP/1.1 RFC 7231, 6.5.11 节
            大了                                    
            
                                                    
‘414’       ‘REQUEST_URI_TOO_LONG’：请求URI太长了   HTTP/1.1 RFC 7231, 6.5.12 节
                                                    
                                                    
‘415’       ‘UNSUPPORTED_MEDIA_TYPE’：不支持的媒    HTTP/1.1 RFC 7231, 6.5.13 节
            体格式                                  
            
                                                    
‘416’       ‘REQUESTED_RANGE_NOT_SATISFIABLE’       HTTP/1.1 Range Requests RFC 7233, 4.4 节
                                                    
                                                    
‘417’       ‘EXPECTATION_FAILED’：期望失败          HTTP/1.1 RFC 7231, 6.5.14 节
                                                    
                                                    
‘421’       ‘MISDIRECTED_REQUEST’                   HTTP/2 RFC 7540(6), 9.1.2 节
                                                    
                                                    
‘422’       ‘UNPROCESSABLE_ENTITY’：可加工实体      WebDAV RFC 4918, 11.2 节
                                                    
                                                    
‘423’       ‘LOCKED’：锁着                          WebDAV RFC 4918, 11.3 节
                                                    
                                                    
‘424’       ‘FAILED_DEPENDENCY’：失败的依赖         WebDAV RFC 4918, 11.4 节
                                                    
                                                    
‘426’       ‘UPGRADE_REQUIRED’：升级需要            HTTP/1.1 RFC 7231, 6.5.15 节
                                                    
                                                    
‘428’       ‘PRECONDITION_REQUIRED’：先决条件要求   Additional HTTP Status Codes RFC 6585
                                                    
                                                    
‘429’       ‘TOO_MANY_REQUESTS’：太多的请求         Additional HTTP Status Codes RFC 6585
                                                    
                                                    
‘431’       ‘REQUEST_HEADER_FIELDS_TOO_LARGE’：请   Additional HTTP Status Codes RFC 6585
            求头太大                                
            
                                                    
‘451’       ‘UNAVAILABLE_FOR_LEGAL_REASONS’         HTTP 状态码用于报告法律障碍 RFC 7725(7)
                                                    
                                                    
‘500’       ‘INTERNAL_SERVER_ERROR’：内部服务错误   HTTP/1.1 RFC 7231, 6.6.1 节
                                                    
                                                    
‘501’       ‘NOT_IMPLEMENTED’：不可执行             HTTP/1.1 RFC 7231, 6.6.2 节
                                                    
                                                    
‘502’       ‘BAD_GATEWAY’：无效网关                 HTTP/1.1 RFC 7231, 6.6.3 节
                                                    
                                                    
‘503’       ‘SERVICE_UNAVAILABLE’：服务不可用       HTTP/1.1 RFC 7231, 6.6.4 节
                                                    
                                                    
‘504’       ‘GATEWAY_TIMEOUT’：网关超时             HTTP/1.1 RFC 7231, 6.6.5 节
                                                    
                                                    
‘505’       ‘HTTP_VERSION_NOT_SUPPORTED’：HTTP版    HTTP/1.1 RFC 7231, 6.6.6 节
            本不支持                                
            
                                                    
‘506’       ‘VARIANT_ALSO_NEGOTIATES’：服务器存在   透明内容协商在： HTTP RFC 2295(8), 8.1 节（实验性）
            内部配置错误                            
            
                                                    
‘507’       ‘INSUFFICIENT_STORAGE’：存储不足        WebDAV RFC 4918, 11.5 节
                                                    
                                                    
‘508’       ‘LOOP_DETECTED’：循环检测               WebDAV Binding Extensions RFC 5842, 7.2 节（实验性）
                                                    
                                                    
‘510’       ‘NOT_EXTENDED’：不扩展                  WebDAV Binding Extensions RFC 5842, 7.2 节（实验性）
                                                    
                                                    
‘511’       ‘NETWORK_AUTHENTICATION_REQUIRED’：要   Additional HTTP Status Codes RFC 6585(9), 6 节
            求网络身份验证                          
            

为了保持向后兼容性，枚举值也以常量形式出现在 *note http.client: 94. 模块
中，。 枚举名等于常量名 (例如 ‘http.HTTPStatus.OK’ 也可以是
‘http.client.OK’)。

在 3.7 版更改: 添加了 ‘421 MISDIRECTED_REQUEST’ 状态码。

3.8 新版功能: 添加了 ‘451 UNAVAILABLE_FOR_LEGAL_REASONS’ 状态码。

   ---------- Footnotes ----------

   (1) 
https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

   (2) https://tools.ietf.org/html/rfc7231.html

   (3) https://tools.ietf.org/html/rfc7231.html

   (4) https://tools.ietf.org/html/rfc7238.html

   (5) https://tools.ietf.org/html/rfc7231.html

   (6) https://tools.ietf.org/html/rfc7540.html

   (7) https://tools.ietf.org/html/rfc7725.html

   (8) https://tools.ietf.org/html/rfc2295.html

   (9) https://tools.ietf.org/html/rfc6585.html


File: python.info,  Node: http client --- HTTP 协议客户端,  Next: ftplib --- FTP 协议客户端,  Prev: http --- HTTP 模块,  Up: 互联网协议和支持

5.21.12 ‘http.client’ — HTTP 协议客户端
---------------------------------------

`源代码：' Lib/http/client.py(1)

__________________________________________________________________

这个模块定义了实现 HTTP 和 HTTPS 协议客户端的类。 它通常不直接使用 — 模
块 *note urllib.request: 121. 用它来处理使用 HTTP 和 HTTPS 的 URL。

参见
....

对于更高级别的 HTTP 客户端接口，建议使用 Requests(2) 。

     注解: HTTPS 支持仅在编译 Python 时启用了 SSL 支持的情况下（通过
     *note ssl: f4. 模块）可用。

该模块支持以下类：

 -- 类: http.client.HTTPConnection (host, port=None[, timeout],
          source_address=None, blocksize=8192)

     *note HTTPConnection: 39a. 的实例代表与 HTTP 的一个连接事务。 它的
     实例化应当传入一个主机和可选的端口号。 如果没有传入端口号，如果主机
     字符串的形式为 ‘主机:端口’ 则会从中提取端口，否则将使用默认的 HTTP
     端口（80）。 如果给出了可选的 `timeout' 参数，则阻塞操作（例如连接
     尝试）将在指定的秒数之后超时（如果未给出，则使用全局默认超时设置）
     。 可选的 `source_address' 参数可以为一个 (主机, 端口) 元组，用作进
     行 HTTP 连接的源地址。 可选的 `blocksize' 参数可以字节为单位设置缓
     冲区的大小，用来发送文件类消息体。

     举个例子，以下调用都是创建连接到同一主机和端口的服务器的实例：

          >>> h1 = http.client.HTTPConnection('www.python.org')
          >>> h2 = http.client.HTTPConnection('www.python.org:80')
          >>> h3 = http.client.HTTPConnection('www.python.org', 80)
          >>> h4 = http.client.HTTPConnection('www.python.org', 80, timeout=10)

     在 3.2 版更改: 添加了*source_address* 参数

     在 3.4 版更改: 删除了 `strict' 参数，不再支持 HTTP 0.9 风格的“简单
     响应”。

     在 3.7 版更改: 添加了 `blocksize' 参数。

 -- 类: http.client.HTTPSConnection (host, port=None, key_file=None,
          cert_file=None[, timeout], source_address=None, *,
          context=None, check_hostname=None, blocksize=8192)

     *note HTTPConnection: 39a. 的子类，使用 SSL 与安全服务器进行通信。
     默认端口为 ‘443’。 如果指定了 `context'，它必须为一个描述 SSL 各选
     项的 *note ssl.SSLContext: 3ec. 实例。

     请参阅 *note 安全考量: 25bd. 了解有关最佳实践的更多信息。

     在 3.2 版更改: 添加了 `source_address', `context' 和
     `check_hostname'。

     在 3.2 版更改: 这个类目前会在可能的情况下（即如果 *note
     ssl.HAS_SNI: 26e8. 为真值）支持 HTTPS 虚拟主机。

     在 3.4 版更改: 删除了 `strict' 参数，不再支持 HTTP 0.9 风格的“简单
     响应”。

     在 3.4.3 版更改: 目前这个类在默认情况下会执行所有必要的证书和主机检
     查。 要回复到先前的非验证行为，可以将
     ‘ssl._create_unverified_context()’ 传递给 `context' 参数。

     在 3.8 版更改: 该类现在对于默认的 `context' 或在传入 `cert_file' 并
     附带自定义 `context' 时会启用 TLS 1.3 *note
     ssl.SSLContext.post_handshake_auth: 225.。

     3.6 版后已移除: `key_file' 和 `cert_file' 已弃用并转而推荐
     `context'。 请改用 *note ssl.SSLContext.load_cert_chain(): a99. 或
     让 *note ssl.create_default_context(): 8c9. 为你选择系统所信任的 CA
     证书。

     `check_hostname' 参数也已弃用；应当改用 `context' 的 *note
     ssl.SSLContext.check_hostname: 26d3. 属性。

 -- 类: http.client.HTTPResponse (sock, debuglevel=0, method=None,
          url=None)

     在成功连接后返回类的实例，而不是由用户直接实例化。

     在 3.4 版更改: 删除了 `strict' 参数，不再支持HTTP 0.9 风格的“简单响
     应”。

这个模块定义了以下函数：

 -- 函数: http.client.parse_headers (fp)

     Parse the headers from a file pointer `fp' representing a HTTP
     request/response.  The file has to be a ‘BufferedIOBase’ reader
     (i.e.  not text) and must provide a valid RFC 2822(3) style header.

     This function returns an instance of ‘http.client.HTTPMessage’ that
     holds the header fields, but no payload (the same as *note
     HTTPResponse.msg: 2cf2. and *note
     http.server.BaseHTTPRequestHandler.headers: 2cf3.).  After
     returning, the file pointer `fp' is ready to read the HTTP body.

          注解: *note parse_headers(): 1050. does not parse the
          start-line of a HTTP message; it only parses the ‘Name: value’
          lines.  The file has to be ready to read these field lines, so
          the first line should already be consumed before calling the
          function.

下列异常可以适当地被引发:

 -- 例外: http.client.HTTPException

     此模块中其他异常的基类。 它是 *note Exception: 1aa. 的一个子类。

 -- 例外: http.client.NotConnected

     *note HTTPException: 2cf4. 的一个子类。

 -- 例外: http.client.InvalidURL

     *note HTTPException: 2cf4. 的一个子类，如果给出了一个非数字或为空值
     的端口就会被引发。

 -- 例外: http.client.UnknownProtocol

     *note HTTPException: 2cf4. 的一个子类。

 -- 例外: http.client.UnknownTransferEncoding

     *note HTTPException: 2cf4. 的一个子类。

 -- 例外: http.client.UnimplementedFileMode

     *note HTTPException: 2cf4. 的一个子类。

 -- 例外: http.client.IncompleteRead

     *note HTTPException: 2cf4. 的一个子类。

 -- 例外: http.client.ImproperConnectionState

     *note HTTPException: 2cf4. 的一个子类。

 -- 例外: http.client.CannotSendRequest

     *note ImproperConnectionState: 2cfb. 的一个子类。

 -- 例外: http.client.CannotSendHeader

     *note ImproperConnectionState: 2cfb. 的一个子类。

 -- 例外: http.client.ResponseNotReady

     *note ImproperConnectionState: 2cfb. 的一个子类。

 -- 例外: http.client.BadStatusLine

     *note HTTPException: 2cf4. 的一个子类。 如果服务器反馈了一个我们不
     理解的 HTTP 状态码就会被引发。

 -- 例外: http.client.LineTooLong

     *note HTTPException: 2cf4. 的一个子类。 如果在 HTTP 协议中从服务器
     接收到过长的行就会被引发。

 -- 例外: http.client.RemoteDisconnected

     *note ConnectionResetError: 9a8. 和 *note BadStatusLine: 2cff. 的一
     个子类。 当尝试读取响应时的结果是未从连接读取到数据时由 *note
     HTTPConnection.getresponse(): 6ed. 引发，表明远端已关闭连接。

     3.5 新版功能: 在此之前引发的异常为 *note BadStatusLine:
     2cff.‘('')’。

此模块中定义的常量为：

 -- 数据: http.client.HTTP_PORT

     HTTP 协议默认的端口号 (总是 ‘80’)。

 -- 数据: http.client.HTTPS_PORT

     HTTPS 协议默认的端口号 (总是 ‘443’)。

 -- 数据: http.client.responses

     这个字典把 HTTP 1.1 状态码映射到 W3C 名称。

     例如：‘http.client.responses[http.client.NOT_FOUND]’ 是 ‘'NOT
     FOUND’ （未发现）。

本模块中可用的 HTTP 状态码常量可以参见 *note HTTP 状态码: 2cee. 。

* Menu:

* HTTPConnection 对象::
* HTTPResponse 对象::
* 例子: 例子<22>.
* HTTPMessage Objects::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/http/client.py

   (2) https://requests.readthedocs.io/en/master/

   (3) https://tools.ietf.org/html/rfc2822.html


File: python.info,  Node: HTTPConnection 对象,  Next: HTTPResponse 对象,  Up: http client --- HTTP 协议客户端

5.21.12.1 HTTPConnection 对象
.............................

*note HTTPConnection: 39a. 实例拥有以下方法：

 -- 方法: HTTPConnection.request (method, url, body=None, headers={}, *,
          encode_chunked=False)

     这会使用 HTTP 请求方法 `method' 和选择器 `url' 向服务器发送请求。

     如果给定 `body'，那么给定的数据会在信息头完成之后发送。它可能是一个
     *note str: 339. 、一个 *note bytes-like object: 5f1. 、一个打开的
     *note file object: b4a.，或者 *note bytes: 33a. 迭代器。如果 `body'
     是字符串，它会按 HTTP 默认的 ISO-8859-1 编码；如果是一个字节类对象
     ，它会按原样发送；如果是 *note file object: b4a. ，文件的内容会被发
     送，这个文件对象应该支持 ‘read()’ 方法。如果这个文件对象是一个
     *note io.TextIOBase: c41. 实例， ‘read()’ 方法返回的数据会按
     ISO-8859-1 编码，否则 ‘read()’ 方法返回的数据会按原样发送；如果
     `body' 是一个迭代器，迭代器中的元素会被发送，直到迭代器耗尽。

     `headers' 参数应是额外的随请求发送的 HTTP 信息头的字典。

     如果 `headers' 既不包含 Content-Length 也没有 Transfer-Encoding，但
     存在请求正文，那么这些头字段中的一个会自动设定。如果 `body' 是
     ‘None’，那么对于要求正文的方法 (‘PUT’，‘POST’，和 ‘PATCH’)，
     Content-Length 头会被设为 ‘0’。如果 `body' 是字符串或者类似字节的对
     象，并且也不是 *note 文件: b4a.，Content-Length 头会设为正文的长度
     。任何其他类型的 `body' （一般是文件或迭代器）会按块编码，这时会自
     动设定 Transfer-Encoding 头以代替 Content-Length。

     在 `headers' 中指定 Transfer-Encoding 时， `encode_chunked' 是唯一
     相关的参数。如果 `encode_chunked' 为 ‘False’，HTTPConnection 对象会
     假定所有的编码都由调用代码处理。如果为 ‘True’，正文会按块编码。

          注解: HTTP 协议在 1.1 版中添加了块传输编码。除非明确知道 HTTP
          服务器可以处理 HTTP 1.1，调用者要么必须指定 Content-Length，要
          么必须传入 *note str: 339. 或字节类对象，注意该对象不能是表达
          body 的文件。

     3.2 新版功能: `body' 现在可以是可迭代对象了。

     在 3.6 版更改: 如果 Content-Length 和 Transfer-Encoding 都没有在
     `headers' 中设置，文件和可迭代的 `body' 对象现在会按块编码。添加了
     `encode_chunked' 参数。不会尝试去确定文件对象的 Content-Length。

 -- 方法: HTTPConnection.getresponse ()

     应当在发送一个请求从服务器获取响应时被调用。 返回一个 *note
     HTTPResponse: a19. 的实例。

          注解: 请注意你必须在读取了整个响应之后才能向服务器发送新的请求
          。

     在 3.5 版更改: 如果引发了 *note ConnectionError: 6ef. 或其子类，
     *note HTTPConnection: 39a. 对象将在发送新的请求时准备好重新连接。

 -- 方法: HTTPConnection.set_debuglevel (level)

     设置调试等级。 默认的调试等级为 ‘0’，意味着不会打印调试输出。 任何
     大于 ‘0’ 的值将使得所有当前定义的调试输出被打印到 stdout。
     ‘debuglevel’ 会被传给任何新创建的 *note HTTPResponse: a19. 对象。

     3.1 新版功能.

 -- 方法: HTTPConnection.set_tunnel (host, port=None, headers=None)

     为 HTTP 连接隧道设置主机和端口。 这将允许通过代理服务器运行连接。

     host 和 port 参数指明隧道连接的位置（即 CONNECT 请求所包含的地址，
     而 `不是' 代理服务器的地址）。

     headers 参数应为一个随 CONNECT 请求发送的额外 HTTP 标头的映射。

     例如，要通过一个运行于本机 8080 端口的 HTTPS 代理服务器隧道，我们应
     当向 *note HTTPSConnection: 39b. 构造器传入代理的地址，并将我们最终
     想要访问的主机地址传给 *note set_tunnel(): bb5. 方法:

          >>> import http.client
          >>> conn = http.client.HTTPSConnection("localhost", 8080)
          >>> conn.set_tunnel("www.python.org")
          >>> conn.request("HEAD","/index.html")

     3.2 新版功能.

 -- 方法: HTTPConnection.connect ()

     当对象被创建后连接到指定的服务器。 默认情况下，如果客户端还未建立连
     接，此函数会在发送请求时自动被调用。

 -- 方法: HTTPConnection.close ()

     关闭到服务器的连接。

 -- 属性: HTTPConnection.blocksize

     用于发送文件类消息体的缓冲区大小。

     3.7 新版功能.

作为对使用上述 ‘request()’ 方法的替代同，你也可以通过使用下面的四个函数
，分步骤发送请的请求。

 -- 方法: HTTPConnection.putrequest (method, url, skip_host=False,
          skip_accept_encoding=False)

     This should be the first call after the connection to the server
     has been made.  It sends a line to the server consisting of the
     `method' string, the `url' string, and the HTTP version
     (‘HTTP/1.1’).  To disable automatic sending of ‘Host:’ or
     ‘Accept-Encoding:’ headers (for example to accept additional
     content encodings), specify `skip_host' or `skip_accept_encoding'
     with non-False values.

 -- 方法: HTTPConnection.putheader (header, argument[, ...])

     Send an RFC 822(1)-style header to the server.  It sends a line to
     the server consisting of the header, a colon and a space, and the
     first argument.  If more arguments are given, continuation lines
     are sent, each consisting of a tab and an argument.

 -- 方法: HTTPConnection.endheaders (message_body=None, *,
          encode_chunked=False)

     Send a blank line to the server, signalling the end of the headers.
     The optional `message_body' argument can be used to pass a message
     body associated with the request.

     If `encode_chunked' is ‘True’, the result of each iteration of
     `message_body' will be chunk-encoded as specified in RFC 7230(2),
     Section 3.3.1.  How the data is encoded is dependent on the type of
     `message_body'.  If `message_body' implements the *note buffer
     interface: 15f7. the encoding will result in a single chunk.  If
     `message_body' is a *note collections.abc.Iterable: 1962, each
     iteration of `message_body' will result in a chunk.  If
     `message_body' is a *note file object: b4a, each call to ‘.read()’
     will result in a chunk.  The method automatically signals the end
     of the chunk-encoded data immediately after `message_body'.

          注解: Due to the chunked encoding specification, empty chunks
          yielded by an iterator body will be ignored by the
          chunk-encoder.  This is to avoid premature termination of the
          read of the request by the target server due to malformed
          encoding.

     3.6 新版功能: Chunked encoding support.  The `encode_chunked'
     parameter was added.

 -- 方法: HTTPConnection.send (data)

     Send data to the server.  This should be used directly only after
     the *note endheaders(): 559. method has been called and before
     *note getresponse(): 6ed. is called.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc822.html

   (2) https://tools.ietf.org/html/rfc7230.html


File: python.info,  Node: HTTPResponse 对象,  Next: 例子<22>,  Prev: HTTPConnection 对象,  Up: http client --- HTTP 协议客户端

5.21.12.2 HTTPResponse 对象
...........................

An *note HTTPResponse: a19. instance wraps the HTTP response from the
server.  It provides access to the request headers and the entity body.
The response is an iterable object and can be used in a with statement.

在 3.5 版更改: The *note io.BufferedIOBase: 591. interface is now
implemented and all of its reader operations are supported.

 -- 方法: HTTPResponse.read ([amt])

     Reads and returns the response body, or up to the next `amt' bytes.

 -- 方法: HTTPResponse.readinto (b)

     Reads up to the next len(b) bytes of the response body into the
     buffer `b'.  Returns the number of bytes read.

     3.3 新版功能.

 -- 方法: HTTPResponse.getheader (name, default=None)

     Return the value of the header `name', or `default' if there is no
     header matching `name'.  If there is more than one header with the
     name `name', return all of the values joined by ’, ’.  If ’default’
     is any iterable other than a single string, its elements are
     similarly returned joined by commas.

 -- 方法: HTTPResponse.getheaders ()

     Return a list of (header, value) tuples.

 -- 方法: HTTPResponse.fileno ()

     Return the ‘fileno’ of the underlying socket.

 -- 属性: HTTPResponse.msg

     A ‘http.client.HTTPMessage’ instance containing the response
     headers.  ‘http.client.HTTPMessage’ is a subclass of *note
     email.message.Message: 54a.

 -- 属性: HTTPResponse.version

     HTTP protocol version used by server.  10 for HTTP/1.0, 11 for
     HTTP/1.1.

 -- 属性: HTTPResponse.status

     由服务器返回的状态码。

 -- 属性: HTTPResponse.reason

     Reason phrase returned by server.

 -- 属性: HTTPResponse.debuglevel

     A debugging hook.  If *note debuglevel: 2d15. is greater than zero,
     messages will be printed to stdout as the response is read and
     parsed.

 -- 属性: HTTPResponse.closed

     Is ‘True’ if the stream is closed.


File: python.info,  Node: 例子<22>,  Next: HTTPMessage Objects,  Prev: HTTPResponse 对象,  Up: http client --- HTTP 协议客户端

5.21.12.3 例子
..............

Here is an example session that uses the ‘GET’ method:

     >>> import http.client
     >>> conn = http.client.HTTPSConnection("www.python.org")
     >>> conn.request("GET", "/")
     >>> r1 = conn.getresponse()
     >>> print(r1.status, r1.reason)
     200 OK
     >>> data1 = r1.read()  # This will return entire content.
     >>> # The following example demonstrates reading data in chunks.
     >>> conn.request("GET", "/")
     >>> r1 = conn.getresponse()
     >>> while chunk := r1.read(200):
     ...     print(repr(chunk))
     b'<!doctype html>\n<!--[if"...
     ...
     >>> # Example of an invalid request
     >>> conn = http.client.HTTPSConnection("docs.python.org")
     >>> conn.request("GET", "/parrot.spam")
     >>> r2 = conn.getresponse()
     >>> print(r2.status, r2.reason)
     404 Not Found
     >>> data2 = r2.read()
     >>> conn.close()

Here is an example session that uses the ‘HEAD’ method.  Note that the
‘HEAD’ method never returns any data.

     >>> import http.client
     >>> conn = http.client.HTTPSConnection("www.python.org")
     >>> conn.request("HEAD", "/")
     >>> res = conn.getresponse()
     >>> print(res.status, res.reason)
     200 OK
     >>> data = res.read()
     >>> print(len(data))
     0
     >>> data == b''
     True

Here is an example session that shows how to ‘POST’ requests:

     >>> import http.client, urllib.parse
     >>> params = urllib.parse.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
     >>> headers = {"Content-type": "application/x-www-form-urlencoded",
     ...            "Accept": "text/plain"}
     >>> conn = http.client.HTTPConnection("bugs.python.org")
     >>> conn.request("POST", "", params, headers)
     >>> response = conn.getresponse()
     >>> print(response.status, response.reason)
     302 Found
     >>> data = response.read()
     >>> data
     b'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
     >>> conn.close()

Client side ‘HTTP PUT’ requests are very similar to ‘POST’ requests.
The difference lies only the server side where HTTP server will allow
resources to be created via ‘PUT’ request.  It should be noted that
custom HTTP methods are also handled in *note urllib.request.Request:
8fe. by setting the appropriate method attribute.  Here is an example
session that shows how to send a ‘PUT’ request using http.client:

     >>> # This creates an HTTP message
     >>> # with the content of BODY as the enclosed representation
     >>> # for the resource http://localhost:8080/file
     ...
     >>> import http.client
     >>> BODY = "***filecontents***"
     >>> conn = http.client.HTTPConnection("localhost", 8080)
     >>> conn.request("PUT", "/file", BODY)
     >>> response = conn.getresponse()
     >>> print(response.status, response.reason)
     200, OK


File: python.info,  Node: HTTPMessage Objects,  Prev: 例子<22>,  Up: http client --- HTTP 协议客户端

5.21.12.4 HTTPMessage Objects
.............................

An ‘http.client.HTTPMessage’ instance holds the headers from an HTTP
response.  It is implemented using the *note email.message.Message: 54a.
class.


File: python.info,  Node: ftplib --- FTP 协议客户端,  Next: poplib --- POP3 协议客户端,  Prev: http client --- HTTP 协议客户端,  Up: 互联网协议和支持

5.21.13 ‘ftplib’ — FTP 协议客户端
---------------------------------

`源代码：' Lib/ftplib.py(1)

__________________________________________________________________

本模块定义了 *note FTP: 2f1. 类和一些相关项目。*note FTP: 2f1. 类实现了
FTP 协议的客户端。可以用该类编写 Python 程序，执行各种自动化的 FTP 任务
，如镜像其他 FTP 服务器。*note urllib.request: 121. 模块也用它来处理使用
了 FTP 的 URL。关于 FTP（文件传输协议）的详情请参阅 Internet RFC 959(2)。

以下是使用 *note ftplib: 84. 模块的会话示例:

     >>> from ftplib import FTP
     >>> ftp = FTP('ftp.debian.org')     # connect to host, default port
     >>> ftp.login()                     # user anonymous, passwd anonymous@
     '230 Login successful.'
     >>> ftp.cwd('debian')               # change into "debian" directory
     >>> ftp.retrlines('LIST')           # list directory contents
     -rw-rw-r--    1 1176     1176         1063 Jun 15 10:18 README
     ...
     drwxr-sr-x    5 1176     1176         4096 Dec 19  2000 pool
     drwxr-sr-x    4 1176     1176         4096 Nov 17  2008 project
     drwxr-xr-x    3 1176     1176         4096 Oct 10  2012 tools
     '226 Directory send OK.'
     >>> with open('README', 'wb') as fp:
     >>>     ftp.retrbinary('RETR README', fp.write)
     '226 Transfer complete.'
     >>> ftp.quit()

这个模块定义了以下内容：

 -- 类: ftplib.FTP (host='', user='', passwd='', acct='', timeout=None,
          source_address=None)

     Return a new instance of the *note FTP: 2f1. class.  When `host' is
     given, the method call ‘connect(host)’ is made.  When `user' is
     given, additionally the method call ‘login(user, passwd, acct)’ is
     made (where `passwd' and `acct' default to the empty string when
     not given).  The optional `timeout' parameter specifies a timeout
     in seconds for blocking operations like the connection attempt (if
     is not specified, the global default timeout setting will be used).
     `source_address' is a 2-tuple ‘(host, port)’ for the socket to bind
     to as its source address before connecting.

     *note FTP: 2f1. 类支持 *note with: 6f2. 语句，例如：

          >>> from ftplib import FTP
          >>> with FTP("ftp1.at.proftpd.org") as ftp:
          ...     ftp.login()
          ...     ftp.dir()
          ...
          '230 Anonymous login ok, restrictions apply.'
          dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 .
          dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 ..
          dr-xr-xr-x   5 ftp      ftp          4096 May  6 10:43 CentOS
          dr-xr-xr-x   3 ftp      ftp            18 Jul 10  2008 Fedora
          >>>

     在 3.2 版更改: 添加了对 *note with: 6f2. 语句的支持。

     在 3.3 版更改: 添加了 `source_address' 参数。

 -- 类: ftplib.FTP_TLS (host='', user='', passwd='', acct='',
          keyfile=None, certfile=None, context=None, timeout=None,
          source_address=None)

     一个 *note FTP: 2f1. 的子类，它为 FTP 添加了 TLS 支持，如 RFC
     4217(3) 所述。它将像通常一样连接到 21 端口，暗中保护在身份验证前的
     FTP 控制连接。而保护数据连接需要用户明确调用 *note prot_p(): 2d1c.
     方法。`context' 是一个 *note ssl.SSLContext: 3ec. 对象，该对象可以
     将 SSL 配置选项、证书和私钥打包放入一个单独的（可以长久存在的）结构
     中。请阅读 *note 安全考量: 25bd. 以获取最佳实践。

     `keyfile' 和 `certfile' 是可以代替 `context' 的传统方案，它们可以分
     别指向 PEM 格式的私钥和证书链文件，用于进行 SSL 连接。

     3.2 新版功能.

     在 3.3 版更改: 添加了 `source_address' 参数。

     在 3.4 版更改: 本类现在支持通过 *note
     ssl.SSLContext.check_hostname: 26d3. 和 `服务器名称提示' （参阅
     *note ssl.HAS_SNI: 26e8.）进行主机名检查。

     3.6 版后已移除: `keyfile' 和 `certfile' 已弃用并转而推荐 `context'。
     请改用 *note ssl.SSLContext.load_cert_chain(): a99. 或让 *note
     ssl.create_default_context(): 8c9. 为你选择系统所信任的 CA 证书。

     以下是使用 *note FTP_TLS: a0b. 类的会话示例:

          >>> ftps = FTP_TLS('ftp.pureftpd.org')
          >>> ftps.login()
          '230 Anonymous user logged in'
          >>> ftps.prot_p()
          '200 Data protection level set to "private"'
          >>> ftps.nlst()
          ['6jack', 'OpenBSD', 'antilink', 'blogbench', 'bsdcam', 'clockspeed', 'djbdns-jedi', 'docs', 'eaccelerator-jedi', 'favicon.ico', 'francotone', 'fugu', 'ignore', 'libpuzzle', 'metalog', 'minidentd', 'misc', 'mysql-udf-global-user-variables', 'php-jenkins-hash', 'php-skein-hash', 'php-webdav', 'phpaudit', 'phpbench', 'pincaster', 'ping', 'posto', 'pub', 'public', 'public_keys', 'pure-ftpd', 'qscan', 'qtc', 'sharedance', 'skycache', 'sound', 'tmp', 'ucarp']

 -- 例外: ftplib.error_reply

     从服务器收到意外答复时，将引发本异常。

 -- 例外: ftplib.error_temp

     收到表示临时错误的错误代码（响应代码在 400–499 范围内）时，将引发本
     异常。

 -- 例外: ftplib.error_perm

     收到表示永久性错误的错误代码（响应代码在 500–599 范围内）时，将引发
     本异常。

 -- 例外: ftplib.error_proto

     从服务器收到不符合 FTP 响应规范的答复，比如以数字 1–5 开头时，将引
     发本异常。

 -- 数据: ftplib.all_errors

     所有异常的集合（一个元组），由于 FTP 连接出现问题（并非调用者的编码
     错误），*note FTP: 2f1. 实例的方法可能会引发这些异常。该集合包括上
     面列出的四个异常以及 *note OSError: 1d4. 和 *note EOFError: c74.。

参见
....

*note netrc: bf. 模块

     ‘.netrc’ 文件格式解析器。FTP 客户端在响应用户之前，通常使用
     ‘.netrc’ 文件来加载用户认证信息。

* Menu:

* FTP 对象::
* FTP_TLS 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/ftplib.py

   (2) https://tools.ietf.org/html/rfc959.html

   (3) https://tools.ietf.org/html/rfc4217.html


File: python.info,  Node: FTP 对象,  Next: FTP_TLS 对象,  Up: ftplib --- FTP 协议客户端

5.21.13.1 FTP 对象
..................

一些方法可以按照两种方式来使用：一种处理文本文件，另一种处理二进制文件。
方法名称与相应的命令相同，文本版中命令后面跟着 ‘lines’，二进制版中命令后
面跟着 ‘binary’。

*note FTP: 2f1. 实例具有下列方法:

 -- 方法: FTP.set_debuglevel (level)

     设置实例的调试级别，它控制着调试信息的数量。默认值 ‘0’ 不产生调试信
     息。值 ‘1’ 产生中等数量的调试信息，通常每个请求产生一行。大于或等于
     ‘2’ 的值产生的调试信息最多，FTP 控制连接上发送和接收的每一行都将被
     记录下来。

 -- 方法: FTP.connect (host='', port=0, timeout=None,
          source_address=None)

     连接到给定的主机和端口。默认端口号由 FTP 协议规范规定，为 ‘21’。偶
     尔才需要指定其他端口号。每个实例只应调用一次本函数，如果在创建实例
     时就传入了 host，则根本不应调用它。所有其他方法只能在建立连接后使用
     。可选参数 `timeout' 指定连接尝试的超时（以秒为单位）。如果没有传入
     `timeout'，将使用全局默认超时设置。`source_address' 是一个 2 元组
     ‘(host, port)’，套接字在连接前绑定它，作为其源地址。

     引发一个 *note 审计事件: ea1. ‘ftplib.connect’，附带参数 ‘self’,
     ‘host’, ‘port’。

     在 3.3 版更改: 添加了 `source_address' 参数。

 -- 方法: FTP.getwelcome ()

     返回服务器发送的欢迎消息，作为连接开始的回复。（该消息有时包含与用
     户有关的免责声明或帮助信息。）

 -- 方法: FTP.login (user='anonymous', passwd='', acct='')

     以 `user' 的身份登录。`passwd' 和 `acct' 是可选参数，默认为空字符串
     。如果没有指定 `user'，则默认为 ‘'anonymous'’。如果 `user' 为
     ‘'anonymous'’，那么默认的 `passwd' 是 ‘'anonymous@'’。连接建立后，
     每个实例只应调用一次本函数；如果在创建实例时传入了 host 和 user，则
     完全不应该调用本函数。在客户端登录后，才允许执行大多数 FTP 命令。
     `acct' 参数提供记账信息 ("accounting information")；仅少数系统实现
     了该特性。

 -- 方法: FTP.abort ()

     中止正在进行的文件传输。本方法并不总是有效，但值得一试。

 -- 方法: FTP.sendcmd (cmd)

     将一条简单的命令字符串发送到服务器，返回响应的字符串。

     引发一个 *note 审计事件: ea1. ‘ftplib.sendcmd’，附带参数 ‘self’,
     ‘cmd’。

 -- 方法: FTP.voidcmd (cmd)

     将一条简单的命令字符串发送到服务器，并处理响应内容。如果收到的响应
     代码表示的是成功（代码范围 200–299），则不返回任何内容。否则将引发
     *note error_reply: 2d1d.。

     引发一个 *note 审计事件: ea1. ‘ftplib.sendcmd’，附带参数 ‘self’,
     ‘cmd’。

 -- 方法: FTP.retrbinary (cmd, callback, blocksize=8192, rest=None)

     以二进制传输模式下载文件。`cmd' 应为恰当的 ‘RETR’ 命令：‘'RETR 文件
     名'’。`callback' 函数会在收到每个数据块时调用，传入的参数是表示数据
     块的一个字节。为执行实际传输，创建了底层套接字对象，可选参数
     `blocksize' 指定了读取该对象时的最大块大小（这也是传入 `callback' 的
     数据块的最大大小）。已经选择了合理的默认值。`rest' 的含义与 *note
     transfercmd(): 2d2c. 方法中的含义相同。

 -- 方法: FTP.retrlines (cmd, callback=None)

     Retrieve a file or directory listing in ASCII transfer mode.  `cmd'
     should be an appropriate ‘RETR’ command (see *note retrbinary():
     2d2b.) or a command such as ‘LIST’ or ‘NLST’ (usually just the
     string ‘'LIST'’).  ‘LIST’ retrieves a list of files and information
     about those files.  ‘NLST’ retrieves a list of file names.  The
     `callback' function is called for each line with a string argument
     containing the line with the trailing CRLF stripped.  The default
     `callback' prints the line to ‘sys.stdout’.

 -- 方法: FTP.set_pasv (val)

     如果 `val' 为 true，则打开“被动”模式，否则禁用被动模式。默认下被动
     模式是打开的。

 -- 方法: FTP.storbinary (cmd, fp, blocksize=8192, callback=None,
          rest=None)

     以二进制传输模式存储文件。 `cmd' 应为恰当的 ‘STOR’ 命令: ‘"STOR
     filename"’。`fp' 是一个 *note 文件对象: b4a. (以二进制模式打开)，将
     使用它的 ‘read()’ 方法读取它，用于提供要存储的数据，直到遇到 EOF，
     读取时的块大小为 `blocksize'。 参数 `blocksize' 的默认值为 8192。 可
     选参数 `callback' 是单参数函数，在每个数据块发送后都会用该数据块调
     用它。`rest' 的含义与 *note transfercmd(): 2d2c. 方法中的含义相同。

     在 3.2 版更改: 添加了 `rest' 参数。

 -- 方法: FTP.storlines (cmd, fp, callback=None)

     Store a file in ASCII transfer mode.  `cmd' should be an
     appropriate ‘STOR’ command (see *note storbinary(): ca7.).  Lines
     are read until EOF from the *note file object: b4a. `fp' (opened in
     binary mode) using its *note readline(): 1713. method to provide
     the data to be stored.  `callback' is an optional single parameter
     callable that is called on each line after it is sent.

 -- 方法: FTP.transfercmd (cmd, rest=None)

     在 FTP 数据连接上开始传输数据。如果传输处于活动状态，传输命令由
     `cmd' 指定，需发送 ‘EPRT’ 或 ‘PORT’ 命令，然后接受连接 (accept)。如
     果服务器是被动服务器，需发送 ‘EPSV’ 或 ‘PASV’ 命令，连接到服务器
     (connect)，然后启动传输命令。两种方式都将返回用于连接的套接字。

     If optional `rest' is given, a ‘REST’ command is sent to the
     server, passing `rest' as an argument.  `rest' is usually a byte
     offset into the requested file, telling the server to restart
     sending the file’s bytes at the requested offset, skipping over the
     initial bytes.  Note however that RFC 959(1) requires only that
     `rest' be a string containing characters in the printable range
     from ASCII code 33 to ASCII code 126.  The *note transfercmd():
     2d2c. method, therefore, converts `rest' to a string, but no check
     is performed on the string’s contents.  If the server does not
     recognize the ‘REST’ command, an *note error_reply: 2d1d. exception
     will be raised.  If this happens, simply call *note transfercmd():
     2d2c. without a `rest' argument.

 -- 方法: FTP.ntransfercmd (cmd, rest=None)

     类似于 *note transfercmd(): 2d2c.，但返回一个元组，包括数据连接和数
     据的预计大小。如果预计大小无法计算，则返回的预计大小为 ‘None’。
     `cmd' 和 `rest' 的含义与 *note transfercmd(): 2d2c. 中的相同。

 -- 方法: FTP.mlsd (path="", facts=[])

     使用 ‘MLSD’ 命令以标准格式列出目录内容 ( RFC 3659(2))。如果省略
     `path' 则使用当前目录。`facts' 是字符串列表，表示所需的信息类型（如
     ‘["type", "size", "perm"]’）。返回一个生成器对象，每个在 path 中找
     到的文件都将在该对象中生成两个元素的元组。第一个元素是文件名，第二
     个元素是该文件的 facts 的字典。该字典的内容受 `facts' 参数限制，但
     不能保证服务器会返回所有请求的 facts。

     3.3 新版功能.

 -- 方法: FTP.nlst (argument[, ...])

     返回一个文件名列表，文件名由 ‘NLST’ 命令返回。可选参数 `argument' 是
     待列出的目录（默认为当前服务器目录）。可以使用多个参数，将非标准选
     项传递给 ‘NLST’ 命令。

          注解: 如果目标服务器支持相关命令，那么 *note mlsd(): a0d. 提供
          的 API 更好。

 -- 方法: FTP.dir (argument[, ...])

     生成目录列表，即 ‘LIST’ 命令所返回的结果，并将其打印到标准输出。可
     选参数 `argument' 是待列出的目录（默认为当前服务器目录）。可以使用
     多个参数，将非标准选项传递给 ‘LIST’ 命令。如果最后一个参数是一个函
     数，它将被用作 `callback' 函数，与 *note retrlines(): 2d2d. 中的相
     同，默认将打印到 ‘sys.stdout’。本方法返回 ‘None’。

          注解: 如果目标服务器支持相关命令，那么 *note mlsd(): a0d. 提供
          的 API 更好。

 -- 方法: FTP.rename (fromname, toname)

     将服务器上的文件 `fromname' 重命名为 `toname'。

 -- 方法: FTP.delete (filename)

     将服务器上名为 `filename' 的文件删除。如果删除成功，返回响应文本，
     如果删除失败，在权限错误时引发 *note error_perm: 2d1f.，在其他错误
     时引发 *note error_reply: 2d1d.。

 -- 方法: FTP.cwd (pathname)

     设置服务器端的当前目录。

 -- 方法: FTP.mkd (pathname)

     在服务器上创建一个新目录。

 -- 方法: FTP.pwd ()

     返回服务器上当前目录的路径。

 -- 方法: FTP.rmd (dirname)

     将服务器上名为 `dirname' 的目录删除。

 -- 方法: FTP.size (filename)

     请求服务器上名为 `filename' 的文件大小。成功后以整数返回文件大小，
     未成功则返回 ‘None’。注意，‘SIZE’ 不是标准命令，但通常许多服务器的
     实现都支持该命令。

 -- 方法: FTP.quit ()

     向服务器发送 ‘QUIT’ 命令并关闭连接。 这是关闭一个连接的“礼貌”方式，
     但是如果服务器对 ‘QUIT’ 命令的响应带有错误消息则这会引发一个异常。
     这意味着对 *note close(): 2d39. 方法的调用，它将使得 *note FTP:
     2f1. 实例对后继调用无效（见下文）。

 -- 方法: FTP.close ()

     单方面关闭连接。 这不该被应用于已经关闭的连接，例如成功调用 *note
     quit(): 2d38. 之后的连接。 在此调用之后 *note FTP: 2f1. 实例不应被
     继续使用（在调用 *note close(): 2d39. 或 *note quit(): 2d38. 之后你
     不能通过再次发起调用 *note login(): 2d27. 方法重新打开连接）。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc959.html

   (2) https://tools.ietf.org/html/rfc3659.html


File: python.info,  Node: FTP_TLS 对象,  Prev: FTP 对象,  Up: ftplib --- FTP 协议客户端

5.21.13.2 FTP_TLS 对象
......................

*note FTP_TLS: a0b. 类继承自 *note FTP: 2f1.，它定义了下述其他对象：

 -- 属性: FTP_TLS.ssl_version

     欲采用的 SSL 版本（默认为 *note ssl.PROTOCOL_SSLv23: 26d8.）。

 -- 方法: FTP_TLS.auth ()

     通过使用 TLS 或 SSL 来设置一个安全控制连接，具体取决于 *note
     ssl_version: 2d3b. 属性是如何设置的。

     在 3.4 版更改: 此方法现在支持使用 *note
     ssl.SSLContext.check_hostname: 26d3. 和 `服务器名称指示' (参见
     *note ssl.HAS_SNI: 26e8.) 进行主机名检查。

 -- 方法: FTP_TLS.ccc ()

     将控制通道回复为纯文本。 这适用于发挥知道如何使用非安全 FTP 处理
     NAT 而无需打开固定端口的防火墙的优势。

     3.3 新版功能.

 -- 方法: FTP_TLS.prot_p ()

     设置加密数据连接。

 -- 方法: FTP_TLS.prot_c ()

     设置明文数据连接。


File: python.info,  Node: poplib --- POP3 协议客户端,  Next: imaplib --- IMAP4 协议客户端,  Prev: ftplib --- FTP 协议客户端,  Up: 互联网协议和支持

5.21.14 ‘poplib’ — POP3 协议客户端
----------------------------------

`源代码：' Lib/poplib.py(1)

__________________________________________________________________

本模块定义了一个 *note POP3: 2d40. 类，该类封装了到 POP3 服务器的连接过
程，并实现了 RFC 1939(2) 中定义的协议。*note POP3: 2d40. 类同时支持 RFC
1939(3) 中最小的和可选的命令集。*note POP3: 2d40. 类还支持在 RFC 2595(4)
中引入的 ‘STLS’ 命令，用于在已建立的连接上启用加密通信。

本模块额外提供一个 *note POP3_SSL: bc9. 类，在连接到 POP3 服务器时，该类
为使用 SSL 作为底层协议层提供了支持。

注意，尽管 POP3 具有广泛的支持，但它已经过时。POP3 服务器的实现质量差异
很大，而且大多很糟糕。如果邮件服务器支持 IMAP，则最好使用 *note
imaplib.IMAP4: 614. 类，因为 IMAP 服务器一般实现得更好。

*note poplib: d1. 模块提供了两个类：

 -- 类: poplib.POP3 (host, port=POP3_PORT[, timeout])

     本类实现实际的 POP3 协议。实例初始化时，连接就会建立。如果省略
     `port'，则使用标准 POP3 端口（110）。可选参数 `timeout' 指定连接尝
     试的超时时间（以秒为单位，如果未指定超时，将使用全局默认超时设置）
     。

     引发一个 *note 审计事件: ea1. ‘poplib.connect’，附带参数 ‘self’,
     ‘host’, ‘port’。

     引发一个 *note 审计事件: ea1. ‘poplib.putline’，附带参数 ‘self’,
     ‘line’。

 -- 类: poplib.POP3_SSL (host, port=POP3_SSL_PORT, keyfile=None,
          certfile=None, timeout=None, context=None)

     一个 *note POP3: 2d40. 的子类，它使用经 SSL 加密的套接字连接到服务
     器。如果端口 `port' 未指定，则使用 995，它是标准的 POP3-over-SSL 端
     口。`timeout' 的作用与 *note POP3: 2d40. 构造函数中的相同。
     `context' 是一个可选的 *note ssl.SSLContext: 3ec. 对象，该对象可以
     将 SSL 配置选项、证书和私钥打包放入一个单独的（可以长久存在的）结构
     中。请阅读 *note 安全考量: 25bd. 以获取最佳实践。

     `keyfile' 和 `certfile' 是可以代替 `context' 的传统方案，它们可以分
     别指向 PEM 格式的私钥和证书链文件，用于进行 SSL 连接。

     引发一个 *note 审计事件: ea1. ‘poplib.connect’，附带参数 ‘self’,
     ‘host’, ‘port’。

     引发一个 *note 审计事件: ea1. ‘poplib.putline’，附带参数 ‘self’,
     ‘line’。

     在 3.2 版更改: 添加了 `context' 参数。

     在 3.4 版更改: 本类现在支持通过 *note
     ssl.SSLContext.check_hostname: 26d3. 和 `服务器名称提示' （参阅
     *note ssl.HAS_SNI: 26e8.）进行主机名检查。

     3.6 版后已移除: `keyfile' 和 `certfile' 已弃用并转而推荐 `context'。
     请改用 *note ssl.SSLContext.load_cert_chain(): a99. 或让 *note
     ssl.create_default_context(): 8c9. 为你选择系统所信任的 CA 证书。

定义了一个异常，它是作为 *note poplib: d1. 模块的属性定义的：

 -- 例外: poplib.error_proto

     此模块的所有错误都将引发本异常（来自 *note socket: f0. 模块的错误不
     会被捕获）。异常的原因将以字符串的形式传递给构造函数。

参见
....

*note imaplib: 98. 模块

     标准的 Python IMAP 模块。

有关 Fetchmail 的常见问题(5)

     ‘fetchmail’ POP/IMAP 客户端的“常见问题”收集了 POP3 服务器之间的差异
     和 RFC 不兼容的信息，如果要编写基于 POP 协议的应用程序，这可能会很
     有用。

* Menu:

* POP3 对象::
* POP3 示例::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/poplib.py

   (2) https://tools.ietf.org/html/rfc1939.html

   (3) https://tools.ietf.org/html/rfc1939.html

   (4) https://tools.ietf.org/html/rfc2595.html

   (5) http://www.catb.org/~esr/fetchmail/fetchmail-FAQ.html


File: python.info,  Node: POP3 对象,  Next: POP3 示例,  Up: poplib --- POP3 协议客户端

5.21.14.1 POP3 对象
...................

所有 POP3 命令均以同名的方法表示，小写，大多数方法返回的是服务器发送的响
应文本。

*note POP3: 2d40. 实例具有下列方法：

 -- 方法: POP3.set_debuglevel (level)

     设置实例的调试级别，它控制着调试信息的数量。默认值 ‘0’ 不产生调试信
     息。值 ‘1’ 产生中等数量的调试信息，通常每个请求产生一行。大于或等于
     ‘2’ 的值产生的调试信息最多，FTP 控制连接上发送和接收的每一行都将被
     记录下来。

 -- 方法: POP3.getwelcome ()

     返回 POP3 服务器发送的问候语字符串。

 -- 方法: POP3.capa ()

     查询服务器支持的功能，这些功能在 RFC 2449(1) 中有说明。返回一个
     ‘{'name': ['param'...]}’ 形式的字典。

     3.4 新版功能.

 -- 方法: POP3.user (username)

     发送 user 命令，返回的响应应该指示需要一个密码。

 -- 方法: POP3.pass_ (password)

     发送密码，响应包括邮件数和邮箱大小。注意：在调用 ‘quit()’ 前，服务
     器上的邮箱都是锁定的。

 -- 方法: POP3.apop (user, secret)

     使用更安全的 APOP 身份验证登录到 POP3 服务器。

 -- 方法: POP3.rpop (user)

     使用 RPOP 身份验证（类似于 Unix r-命令）登录到 POP3 服务器。

 -- 方法: POP3.stat ()

     获取邮箱状态。结果为 2 个整数组成的元组：‘(message count, mailbox
     size)’。

 -- 方法: POP3.list ([which])

     请求消息列表，结果的形式为 ‘(response, ['mesg_num octets', ...],
     octets)’。如果设置了 `which'，它表示需要列出的消息。

 -- 方法: POP3.retr (which)

     检索编号为 `which' 的整条消息，并设置其已读标志位。结果的形式为
     ‘(response, ['line', ...], octets)’。

 -- 方法: POP3.dele (which)

     将编号为 `which' 的消息标记为待删除。在多数服务器上，删除操作直到
     QUIT 才会实际执行（主要例外是 Eudora QPOP，它在断开连接时执行删除，
     故意违反了 RFC）。

 -- 方法: POP3.rset ()

     移除邮箱中的所有待删除标记。

 -- 方法: POP3.noop ()

     什么都不做。可以用于保持活动状态。

 -- 方法: POP3.quit ()

     登出：提交更改，解除邮箱锁定，断开连接。

 -- 方法: POP3.top (which, howmuch)

     检索编号为 `which' 的消息，范围是消息头加上消息头往后数 `howmuch' 行
     。结果的形式为 ‘(response, ['line', ...], octets)’。

     本方法使用 POP3 TOP 命令，不同于 RETR 命令，它不设置邮件的已读标志
     位。不幸的是，TOP 在 RFC 中说明不清晰，且在小众的服务器软件中往往不
     可用。信任并使用它之前，请先手动对目标 POP3 服务器测试本方法。

 -- 方法: POP3.uidl (which=None)

     返回消息摘要（唯一 ID）列表。如果指定了 `which'，那么结果将包含那条
     消息的唯一 ID，形式为 ‘'response mesgnum uid’，如果未指定，那么结果
     为列表 ‘(response, ['mesgnum uid', ...], octets)’。

 -- 方法: POP3.utf8 ()

     尝试切换至 UTF-8 模式。成功则返回服务器的响应，失败则引发 *note
     error_proto: b1f. 异常。在 RFC 6856(2) 中有说明。

     3.5 新版功能.

 -- 方法: POP3.stls (context=None)

     在活动连接上开启 TLS 会话，在 RFC 2595(3) 中有说明。仅在用户身份验
     证前允许这样做。

     `context' 参数是一个 *note ssl.SSLContext: 3ec. 对象，该对象可以将
     SSL 配置选项、证书和私钥打包放入一个单独的（可以长久存在的）结构中
     。请阅读 *note 安全考量: 25bd. 以获取最佳实践。

     此方法支持通过 *note ssl.SSLContext.check_hostname: 26d3. 和 `服务
     器名称指示' (参见 *note ssl.HAS_SNI: 26e8.) 进行主机名检查。

     3.4 新版功能.

*note POP3_SSL: bc9. 实例没有额外方法。该子类的接口与其父类的相同。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2449.html

   (2) https://tools.ietf.org/html/rfc6856.html

   (3) https://tools.ietf.org/html/rfc2595.html


File: python.info,  Node: POP3 示例,  Prev: POP3 对象,  Up: poplib --- POP3 协议客户端

5.21.14.2 POP3 示例
...................

以下是一个最短示例（不带错误检查），该示例将打开邮箱，检索并打印所有消息
:

     import getpass, poplib

     M = poplib.POP3('localhost')
     M.user(getpass.getuser())
     M.pass_(getpass.getpass())
     numMessages = len(M.list()[1])
     for i in range(numMessages):
         for j in M.retr(i+1)[1]:
             print(j)

模块的最后有一段测试，其中包含的用法示例更加广泛。


File: python.info,  Node: imaplib --- IMAP4 协议客户端,  Next: nntplib --- NNTP protocol client,  Prev: poplib --- POP3 协议客户端,  Up: 互联网协议和支持

5.21.15 ‘imaplib’ — IMAP4 协议客户端
------------------------------------

`源代码：' Lib/imaplib.py(1)

__________________________________________________________________

本模块定义了三个类： *note IMAP4: 614. 、 *note IMAP4_SSL: a1f. 和 *note
IMAP4_stream: 2d55. 。这三个类封装了与IMAP4服务器的连接并实现了 RFC
2060(2) 当中定义的大多数IMAP4rev1客户端协议。其与IMAP4（ RFC 1730(3) ）
服务器后向兼容，但是 ‘STATUS’ 指令在IMAP4中不支持。

*note imaplib: 98. 模块提供了三个类，其中 *note IMAP4: 614. 是基类：

 -- 类: imaplib.IMAP4 (host='', port=IMAP4_PORT)

     This class implements the actual IMAP4 protocol.  The connection is
     created and protocol version (IMAP4 or IMAP4rev1) is determined
     when the instance is initialized.  If `host' is not specified, ‘''’
     (the local host) is used.  If `port' is omitted, the standard IMAP4
     port (143) is used.

     The *note IMAP4: 614. class supports the *note with: 6f2.
     statement.  When used like this, the IMAP4 ‘LOGOUT’ command is
     issued automatically when the ‘with’ statement exits.  E.g.:

          >>> from imaplib import IMAP4
          >>> with IMAP4("domain.org") as M:
          ...     M.noop()
          ...
          ('OK', [b'Nothing Accomplished. d25if65hy903weo.87'])

     在 3.5 版更改: 添加了对 *note with: 6f2. 语句的支持。

Three exceptions are defined as attributes of the *note IMAP4: 614.
class:

 -- 例外: IMAP4.error

     Exception raised on any errors.  The reason for the exception is
     passed to the constructor as a string.

 -- 例外: IMAP4.abort

     IMAP4 server errors cause this exception to be raised.  This is a
     sub-class of *note IMAP4.error: 2d56.  Note that closing the
     instance and instantiating a new one will usually allow recovery
     from this exception.

 -- 例外: IMAP4.readonly

     This exception is raised when a writable mailbox has its status
     changed by the server.  This is a sub-class of *note IMAP4.error:
     2d56.  Some other client now has write permission, and the mailbox
     will need to be re-opened to re-obtain write permission.

There’s also a subclass for secure connections:

 -- 类: imaplib.IMAP4_SSL (host='', port=IMAP4_SSL_PORT, keyfile=None,
          certfile=None, ssl_context=None)

     This is a subclass derived from *note IMAP4: 614. that connects
     over an SSL encrypted socket (to use this class you need a socket
     module that was compiled with SSL support).  If `host' is not
     specified, ‘''’ (the local host) is used.  If `port' is omitted,
     the standard IMAP4-over-SSL port (993) is used.  `ssl_context' is a
     *note ssl.SSLContext: 3ec. object which allows bundling SSL
     configuration options, certificates and private keys into a single
     (potentially long-lived) structure.  Please read *note 安全考量:
     25bd. for best practices.

     `keyfile' and `certfile' are a legacy alternative to `ssl_context'
     - they can point to PEM-formatted private key and certificate chain
     files for the SSL connection.  Note that the `keyfile'/`certfile'
     parameters are mutually exclusive with `ssl_context', a *note
     ValueError: 1fc. is raised if `keyfile'/`certfile' is provided
     along with `ssl_context'.

     在 3.3 版更改: `ssl_context' parameter added.

     在 3.4 版更改: 本类现在支持通过 *note
     ssl.SSLContext.check_hostname: 26d3. 和 `服务器名称提示' （参阅
     *note ssl.HAS_SNI: 26e8.）进行主机名检查。

     3.6 版后已移除: `keyfile' and `certfile' are deprecated in favor of
     `ssl_context'.  Please use *note ssl.SSLContext.load_cert_chain():
     a99. instead, or let *note ssl.create_default_context(): 8c9.
     select the system’s trusted CA certificates for you.

The second subclass allows for connections created by a child process:

 -- 类: imaplib.IMAP4_stream (command)

     This is a subclass derived from *note IMAP4: 614. that connects to
     the ‘stdin/stdout’ file descriptors created by passing `command' to
     ‘subprocess.Popen()’.

The following utility functions are defined:

 -- 函数: imaplib.Internaldate2tuple (datestr)

     Parse an IMAP4 ‘INTERNALDATE’ string and return corresponding local
     time.  The return value is a *note time.struct_time: 5a2. tuple or
     ‘None’ if the string has wrong format.

 -- 函数: imaplib.Int2AP (num)

     Converts an integer into a bytes representation using characters
     from the set [‘A’ ..  ‘P’].

 -- 函数: imaplib.ParseFlags (flagstr)

     Converts an IMAP4 ‘FLAGS’ response to a tuple of individual flags.

 -- 函数: imaplib.Time2Internaldate (date_time)

     Convert `date_time' to an IMAP4 ‘INTERNALDATE’ representation.  The
     return value is a string in the form: ‘"DD-Mmm-YYYY HH:MM:SS
     +HHMM"’ (including double-quotes).  The `date_time' argument can be
     a number (int or float) representing seconds since epoch (as
     returned by *note time.time(): 326.), a 9-tuple representing local
     time an instance of *note time.struct_time: 5a2. (as returned by
     *note time.localtime(): f5d.), an aware instance of *note
     datetime.datetime: 195, or a double-quoted string.  In the last
     case, it is assumed to already be in the correct format.

Note that IMAP4 message numbers change as the mailbox changes; in
particular, after an ‘EXPUNGE’ command performs deletions the remaining
messages are renumbered.  So it is highly advisable to use UIDs instead,
with the UID command.

模块的最后有一段测试，其中包含的用法示例更加广泛。

参见
....

Documents describing the protocol, sources for servers implementing it,
by the University of Washington’s IMAP Information Center can all be
found at (`Source Code') ‘https://github.com/uw-imap/imap’ (`Not
Maintained').

* Menu:

* IMAP4 Objects::
* IMAP4 Example::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/imaplib.py

   (2) https://tools.ietf.org/html/rfc2060.html

   (3) https://tools.ietf.org/html/rfc1730.html


File: python.info,  Node: IMAP4 Objects,  Next: IMAP4 Example,  Up: imaplib --- IMAP4 协议客户端

5.21.15.1 IMAP4 Objects
.......................

All IMAP4rev1 commands are represented by methods of the same name,
either upper-case or lower-case.

All arguments to commands are converted to strings, except for
‘AUTHENTICATE’, and the last argument to ‘APPEND’ which is passed as an
IMAP4 literal.  If necessary (the string contains IMAP4
protocol-sensitive characters and isn’t enclosed with either parentheses
or double quotes) each string is quoted.  However, the `password'
argument to the ‘LOGIN’ command is always quoted.  If you want to avoid
having an argument string quoted (eg: the `flags' argument to ‘STORE’)
then enclose the string in parentheses (eg: ‘r'(\Deleted)'’).

Each command returns a tuple: ‘(type, [data, ...])’ where `type' is
usually ‘'OK'’ or ‘'NO'’, and `data' is either the text from the command
response, or mandated results from the command.  Each `data' is either a
‘bytes’, or a tuple.  If a tuple, then the first part is the header of
the response, and the second part contains the data (ie: ’literal’
value).

The `message_set' options to commands below is a string specifying one
or more messages to be acted upon.  It may be a simple message number
(‘'1'’), a range of message numbers (‘'2:4'’), or a group of
non-contiguous ranges separated by commas (‘'1:3,6:9'’).  A range can
contain an asterisk to indicate an infinite upper bound (‘'3:*'’).

An *note IMAP4: 614. instance has the following methods:

 -- 方法: IMAP4.append (mailbox, flags, date_time, message)

     Append `message' to named mailbox.

 -- 方法: IMAP4.authenticate (mechanism, authobject)

     Authenticate command — requires response processing.

     `mechanism' specifies which authentication mechanism is to be used
     - it should appear in the instance variable ‘capabilities’ in the
     form ‘AUTH=mechanism’.

     `authobject' must be a callable object:

          data = authobject(response)

     It will be called to process server continuation responses; the
     `response' argument it is passed will be ‘bytes’.  It should return
     ‘bytes’ `data' that will be base64 encoded and sent to the server.
     It should return ‘None’ if the client abort response ‘*’ should be
     sent instead.

     在 3.5 版更改: string usernames and passwords are now encoded to
     ‘utf-8’ instead of being limited to ASCII.

 -- 方法: IMAP4.check ()

     Checkpoint mailbox on server.

 -- 方法: IMAP4.close ()

     Close currently selected mailbox.  Deleted messages are removed
     from writable mailbox.  This is the recommended command before
     ‘LOGOUT’.

 -- 方法: IMAP4.copy (message_set, new_mailbox)

     Copy `message_set' messages onto end of `new_mailbox'.

 -- 方法: IMAP4.create (mailbox)

     Create new mailbox named `mailbox'.

 -- 方法: IMAP4.delete (mailbox)

     Delete old mailbox named `mailbox'.

 -- 方法: IMAP4.deleteacl (mailbox, who)

     Delete the ACLs (remove any rights) set for who on mailbox.

 -- 方法: IMAP4.enable (capability)

     Enable `capability' (see RFC 5161(1)).  Most capabilities do not
     need to be enabled.  Currently only the ‘UTF8=ACCEPT’ capability is
     supported (see RFC 6855(2)).

     3.5 新版功能: The *note enable(): 6f3. method itself, and RFC
     6855(3) support.

 -- 方法: IMAP4.expunge ()

     Permanently remove deleted items from selected mailbox.  Generates
     an ‘EXPUNGE’ response for each deleted message.  Returned data
     contains a list of ‘EXPUNGE’ message numbers in order received.

 -- 方法: IMAP4.fetch (message_set, message_parts)

     Fetch (parts of) messages.  `message_parts' should be a string of
     message part names enclosed within parentheses, eg: ‘"(UID
     BODY[TEXT])"’.  Returned data are tuples of message part envelope
     and data.

 -- 方法: IMAP4.getacl (mailbox)

     Get the ‘ACL’s for `mailbox'.  The method is non-standard, but is
     supported by the ‘Cyrus’ server.

 -- 方法: IMAP4.getannotation (mailbox, entry, attribute)

     Retrieve the specified ‘ANNOTATION’s for `mailbox'.  The method is
     non-standard, but is supported by the ‘Cyrus’ server.

 -- 方法: IMAP4.getquota (root)

     Get the ‘quota’ `root'’s resource usage and limits.  This method is
     part of the IMAP4 QUOTA extension defined in rfc2087.

 -- 方法: IMAP4.getquotaroot (mailbox)

     Get the list of ‘quota’ ‘roots’ for the named `mailbox'.  This
     method is part of the IMAP4 QUOTA extension defined in rfc2087.

 -- 方法: IMAP4.list ([directory[, pattern]])

     List mailbox names in `directory' matching `pattern'.  `directory'
     defaults to the top-level mail folder, and `pattern' defaults to
     match anything.  Returned data contains a list of ‘LIST’ responses.

 -- 方法: IMAP4.login (user, password)

     Identify the client using a plaintext password.  The `password'
     will be quoted.

 -- 方法: IMAP4.login_cram_md5 (user, password)

     Force use of ‘CRAM-MD5’ authentication when identifying the client
     to protect the password.  Will only work if the server ‘CAPABILITY’
     response includes the phrase ‘AUTH=CRAM-MD5’.

 -- 方法: IMAP4.logout ()

     Shutdown connection to server.  Returns server ‘BYE’ response.

     在 3.8 版更改: The method no longer ignores silently arbitrary
     exceptions.

 -- 方法: IMAP4.lsub (directory='""', pattern='*')

     List subscribed mailbox names in directory matching pattern.
     `directory' defaults to the top level directory and `pattern'
     defaults to match any mailbox.  Returned data are tuples of message
     part envelope and data.

 -- 方法: IMAP4.myrights (mailbox)

     Show my ACLs for a mailbox (i.e.  the rights that I have on
     mailbox).

 -- 方法: IMAP4.namespace ()

     Returns IMAP namespaces as defined in RFC 2342(4).

 -- 方法: IMAP4.noop ()

     Send ‘NOOP’ to server.

 -- 方法: IMAP4.open (host, port)

     Opens socket to `port' at `host'.  This method is implicitly called
     by the *note IMAP4: 614. constructor.  The connection objects
     established by this method will be used in the *note IMAP4.read():
     2d76, *note IMAP4.readline(): 2d77, *note IMAP4.send(): 2d78, and
     *note IMAP4.shutdown(): 2d79. methods.  You may override this
     method.

     Raises an *note auditing event: ea1. ‘imaplib.open’ with arguments
     ‘self’, ‘host’, ‘port’.

 -- 方法: IMAP4.partial (message_num, message_part, start, length)

     Fetch truncated part of a message.  Returned data is a tuple of
     message part envelope and data.

 -- 方法: IMAP4.proxyauth (user)

     Assume authentication as `user'.  Allows an authorised
     administrator to proxy into any user’s mailbox.

 -- 方法: IMAP4.read (size)

     Reads `size' bytes from the remote server.  You may override this
     method.

 -- 方法: IMAP4.readline ()

     Reads one line from the remote server.  You may override this
     method.

 -- 方法: IMAP4.recent ()

     Prompt server for an update.  Returned data is ‘None’ if no new
     messages, else value of ‘RECENT’ response.

 -- 方法: IMAP4.rename (oldmailbox, newmailbox)

     Rename mailbox named `oldmailbox' to `newmailbox'.

 -- 方法: IMAP4.response (code)

     Return data for response `code' if received, or ‘None’.  Returns
     the given code, instead of the usual type.

 -- 方法: IMAP4.search (charset, criterion[, ...])

     Search mailbox for matching messages.  `charset' may be ‘None’, in
     which case no ‘CHARSET’ will be specified in the request to the
     server.  The IMAP protocol requires that at least one criterion be
     specified; an exception will be raised when the server returns an
     error.  `charset' must be ‘None’ if the ‘UTF8=ACCEPT’ capability
     was enabled using the *note enable(): 6f3. command.

     示例:

          # M is a connected IMAP4 instance...
          typ, msgnums = M.search(None, 'FROM', '"LDJ"')

          # or:
          typ, msgnums = M.search(None, '(FROM "LDJ")')

 -- 方法: IMAP4.select (mailbox='INBOX', readonly=False)

     Select a mailbox.  Returned data is the count of messages in
     `mailbox' (‘EXISTS’ response).  The default `mailbox' is ‘'INBOX'’.
     If the `readonly' flag is set, modifications to the mailbox are not
     allowed.

 -- 方法: IMAP4.send (data)

     Sends ‘data’ to the remote server.  You may override this method.

     Raises an *note auditing event: ea1. ‘imaplib.send’ with arguments
     ‘self’, ‘data’.

 -- 方法: IMAP4.setacl (mailbox, who, what)

     Set an ‘ACL’ for `mailbox'.  The method is non-standard, but is
     supported by the ‘Cyrus’ server.

 -- 方法: IMAP4.setannotation (mailbox, entry, attribute[, ...])

     Set ‘ANNOTATION’s for `mailbox'.  The method is non-standard, but
     is supported by the ‘Cyrus’ server.

 -- 方法: IMAP4.setquota (root, limits)

     Set the ‘quota’ `root'’s resource `limits'.  This method is part of
     the IMAP4 QUOTA extension defined in rfc2087.

 -- 方法: IMAP4.shutdown ()

     Close connection established in ‘open’.  This method is implicitly
     called by *note IMAP4.logout(): 2d70.  You may override this
     method.

 -- 方法: IMAP4.socket ()

     Returns socket instance used to connect to server.

 -- 方法: IMAP4.sort (sort_criteria, charset, search_criterion[, ...])

     The ‘sort’ command is a variant of ‘search’ with sorting semantics
     for the results.  Returned data contains a space separated list of
     matching message numbers.

     Sort has two arguments before the `search_criterion' argument(s); a
     parenthesized list of `sort_criteria', and the searching `charset'.
     Note that unlike ‘search’, the searching `charset' argument is
     mandatory.  There is also a ‘uid sort’ command which corresponds to
     ‘sort’ the way that ‘uid search’ corresponds to ‘search’.  The
     ‘sort’ command first searches the mailbox for messages that match
     the given searching criteria using the charset argument for the
     interpretation of strings in the searching criteria.  It then
     returns the numbers of matching messages.

     This is an ‘IMAP4rev1’ extension command.

 -- 方法: IMAP4.starttls (ssl_context=None)

     Send a ‘STARTTLS’ command.  The `ssl_context' argument is optional
     and should be a *note ssl.SSLContext: 3ec. object.  This will
     enable encryption on the IMAP connection.  Please read *note
     安全考量: 25bd. for best practices.

     3.2 新版功能.

     在 3.4 版更改: 此方法现在支持使用 *note
     ssl.SSLContext.check_hostname: 26d3. 和 `服务器名称指示' (参见
     *note ssl.HAS_SNI: 26e8.) 进行主机名检查。

 -- 方法: IMAP4.status (mailbox, names)

     Request named status conditions for `mailbox'.

 -- 方法: IMAP4.store (message_set, command, flag_list)

     Alters flag dispositions for messages in mailbox.  `command' is
     specified by section 6.4.6 of RFC 2060(5) as being one of "FLAGS",
     "+FLAGS", or "-FLAGS", optionally with a suffix of ".SILENT".

     For example, to set the delete flag on all messages:

          typ, data = M.search(None, 'ALL')
          for num in data[0].split():
             M.store(num, '+FLAGS', '\\Deleted')
          M.expunge()

          注解: Creating flags containing ’]’ (for example: "[test]")
          violates RFC 3501(6) (the IMAP protocol).  However, imaplib
          has historically allowed creation of such tags, and popular
          IMAP servers, such as Gmail, accept and produce such flags.
          There are non-Python programs which also create such tags.
          Although it is an RFC violation and IMAP clients and servers
          are supposed to be strict, imaplib nonetheless continues to
          allow such tags to be created for backward compatibility
          reasons, and as of Python 3.6, handles them if they are sent
          from the server, since this improves real-world compatibility.

 -- 方法: IMAP4.subscribe (mailbox)

     Subscribe to new mailbox.

 -- 方法: IMAP4.thread (threading_algorithm, charset, search_criterion[,
          ...])

     The ‘thread’ command is a variant of ‘search’ with threading
     semantics for the results.  Returned data contains a space
     separated list of thread members.

     Thread members consist of zero or more messages numbers, delimited
     by spaces, indicating successive parent and child.

     Thread has two arguments before the `search_criterion' argument(s);
     a `threading_algorithm', and the searching `charset'.  Note that
     unlike ‘search’, the searching `charset' argument is mandatory.
     There is also a ‘uid thread’ command which corresponds to ‘thread’
     the way that ‘uid search’ corresponds to ‘search’.  The ‘thread’
     command first searches the mailbox for messages that match the
     given searching criteria using the charset argument for the
     interpretation of strings in the searching criteria.  It then
     returns the matching messages threaded according to the specified
     threading algorithm.

     This is an ‘IMAP4rev1’ extension command.

 -- 方法: IMAP4.uid (command, arg[, ...])

     Execute command args with messages identified by UID, rather than
     message number.  Returns response appropriate to command.  At least
     one argument must be supplied; if none are provided, the server
     will return an error and an exception will be raised.

 -- 方法: IMAP4.unsubscribe (mailbox)

     Unsubscribe from old mailbox.

 -- 方法: IMAP4.xatom (name[, ...])

     Allow simple extension commands notified by server in ‘CAPABILITY’
     response.

The following attributes are defined on instances of *note IMAP4: 614.:

 -- 属性: IMAP4.PROTOCOL_VERSION

     The most recent supported protocol in the ‘CAPABILITY’ response
     from the server.

 -- 属性: IMAP4.debug

     Integer value to control debugging output.  The initialize value is
     taken from the module variable ‘Debug’.  Values greater than three
     trace each command.

 -- 属性: IMAP4.utf8_enabled

     Boolean value that is normally ‘False’, but is set to ‘True’ if an
     *note enable(): 6f3. command is successfully issued for the
     ‘UTF8=ACCEPT’ capability.

     3.5 新版功能.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc5161.html

   (2) https://tools.ietf.org/html/rfc6855.html

   (3) https://tools.ietf.org/html/rfc6855.html

   (4) https://tools.ietf.org/html/rfc2342.html

   (5) https://tools.ietf.org/html/rfc2060.html

   (6) https://tools.ietf.org/html/rfc3501.html


File: python.info,  Node: IMAP4 Example,  Prev: IMAP4 Objects,  Up: imaplib --- IMAP4 协议客户端

5.21.15.2 IMAP4 Example
.......................

以下是一个最短示例（不带错误检查），该示例将打开邮箱，检索并打印所有消息
:

     import getpass, imaplib

     M = imaplib.IMAP4()
     M.login(getpass.getuser(), getpass.getpass())
     M.select()
     typ, data = M.search(None, 'ALL')
     for num in data[0].split():
         typ, data = M.fetch(num, '(RFC822)')
         print('Message %s\n%s\n' % (num, data[0][1]))
     M.close()
     M.logout()


File: python.info,  Node: nntplib --- NNTP protocol client,  Next: smtplib ---SMTP协议客户端,  Prev: imaplib --- IMAP4 协议客户端,  Up: 互联网协议和支持

5.21.16 ‘nntplib’ — NNTP protocol client
----------------------------------------

`Source code:' Lib/nntplib.py(1)

__________________________________________________________________

This module defines the class *note NNTP: a34. which implements the
client side of the Network News Transfer Protocol.  It can be used to
implement a news reader or poster, or automated news processors.  It is
compatible with RFC 3977(2) as well as the older RFC 977(3) and RFC
2980(4).

Here are two small examples of how it can be used.  To list some
statistics about a newsgroup and print the subjects of the last 10
articles:

     >>> s = nntplib.NNTP('news.gmane.io')
     >>> resp, count, first, last, name = s.group('gmane.comp.python.committers')
     >>> print('Group', name, 'has', count, 'articles, range', first, 'to', last)
     Group gmane.comp.python.committers has 1096 articles, range 1 to 1096
     >>> resp, overviews = s.over((last - 9, last))
     >>> for id, over in overviews:
     ...     print(id, nntplib.decode_header(over['subject']))
     ...
     1087 Re: Commit privileges for Łukasz Langa
     1088 Re: 3.2 alpha 2 freeze
     1089 Re: 3.2 alpha 2 freeze
     1090 Re: Commit privileges for Łukasz Langa
     1091 Re: Commit privileges for Łukasz Langa
     1092 Updated ssh key
     1093 Re: Updated ssh key
     1094 Re: Updated ssh key
     1095 Hello fellow committers!
     1096 Re: Hello fellow committers!
     >>> s.quit()
     '205 Bye!'

To post an article from a binary file (this assumes that the article has
valid headers, and that you have right to post on the particular
newsgroup):

     >>> s = nntplib.NNTP('news.gmane.io')
     >>> f = open('article.txt', 'rb')
     >>> s.post(f)
     '240 Article posted successfully.'
     >>> s.quit()
     '205 Bye!'

The module itself defines the following classes:

 -- 类: nntplib.NNTP (host, port=119, user=None, password=None,
          readermode=None, usenetrc=False[, timeout])

     Return a new *note NNTP: a34. object, representing a connection to
     the NNTP server running on host `host', listening at port `port'.
     An optional `timeout' can be specified for the socket connection.
     If the optional `user' and `password' are provided, or if suitable
     credentials are present in ‘/.netrc’ and the optional flag
     `usenetrc' is true, the ‘AUTHINFO USER’ and ‘AUTHINFO PASS’
     commands are used to identify and authenticate the user to the
     server.  If the optional flag `readermode' is true, then a ‘mode
     reader’ command is sent before authentication is performed.  Reader
     mode is sometimes necessary if you are connecting to an NNTP server
     on the local machine and intend to call reader-specific commands,
     such as ‘group’.  If you get unexpected *note NNTPPermanentError:
     2d93.s, you might need to set `readermode'.  The *note NNTP: a34.
     class supports the *note with: 6f2. statement to unconditionally
     consume *note OSError: 1d4. exceptions and to close the NNTP
     connection when done, e.g.:

          >>> from nntplib import NNTP
          >>> with NNTP('news.gmane.io') as n:
          ...     n.group('gmane.comp.python.committers')
          ...
          ('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp.python.committers')
          >>>

     Raises an *note auditing event: ea1. ‘nntplib.connect’ with
     arguments ‘self’, ‘host’, ‘port’.

     All commands will raise an *note auditing event: ea1.
     ‘nntplib.putline’ with arguments ‘self’ and ‘line’, where ‘line’ is
     the bytes about to be sent to the remote host.

     在 3.2 版更改: `usenetrc' is now ‘False’ by default.

     在 3.3 版更改: 添加了对 *note with: 6f2. 语句的支持。

 -- 类: nntplib.NNTP_SSL (host, port=563, user=None, password=None,
          ssl_context=None, readermode=None, usenetrc=False[, timeout])

     Return a new *note NNTP_SSL: bad. object, representing an encrypted
     connection to the NNTP server running on host `host', listening at
     port `port'.  *note NNTP_SSL: bad. objects have the same methods as
     *note NNTP: a34. objects.  If `port' is omitted, port 563 (NNTPS)
     is used.  `ssl_context' is also optional, and is a *note
     SSLContext: 3ec. object.  Please read *note 安全考量: 25bd. for
     best practices.  All other parameters behave the same as for *note
     NNTP: a34.

     Note that SSL-on-563 is discouraged per RFC 4642(5), in favor of
     STARTTLS as described below.  However, some servers only support
     the former.

     Raises an *note auditing event: ea1. ‘nntplib.connect’ with
     arguments ‘self’, ‘host’, ‘port’.

     All commands will raise an *note auditing event: ea1.
     ‘nntplib.putline’ with arguments ‘self’ and ‘line’, where ‘line’ is
     the bytes about to be sent to the remote host.

     3.2 新版功能.

     在 3.4 版更改: 本类现在支持通过 *note
     ssl.SSLContext.check_hostname: 26d3. 和 `服务器名称提示' （参阅
     *note ssl.HAS_SNI: 26e8.）进行主机名检查。

 -- 例外: nntplib.NNTPError

     Derived from the standard exception *note Exception: 1aa, this is
     the base class for all exceptions raised by the *note nntplib: c1.
     module.  Instances of this class have the following attribute:

      -- 属性: response

          The response of the server if available, as a *note str: 339.
          object.

 -- 例外: nntplib.NNTPReplyError

     从服务器收到意外答复时，将引发本异常。

 -- 例外: nntplib.NNTPTemporaryError

     Exception raised when a response code in the range 400–499 is
     received.

 -- 例外: nntplib.NNTPPermanentError

     Exception raised when a response code in the range 500–599 is
     received.

 -- 例外: nntplib.NNTPProtocolError

     Exception raised when a reply is received from the server that does
     not begin with a digit in the range 1–5.

 -- 例外: nntplib.NNTPDataError

     Exception raised when there is some error in the response data.

* Menu:

* NNTP Objects::
* 工具函数: 工具函数<2>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/nntplib.py

   (2) https://tools.ietf.org/html/rfc3977.html

   (3) https://tools.ietf.org/html/rfc977.html

   (4) https://tools.ietf.org/html/rfc2980.html

   (5) https://tools.ietf.org/html/rfc4642.html


File: python.info,  Node: NNTP Objects,  Next: 工具函数<2>,  Up: nntplib --- NNTP protocol client

5.21.16.1 NNTP Objects
......................

When connected, *note NNTP: a34. and *note NNTP_SSL: bad. objects
support the following methods and attributes.

* Menu:

* Attributes::
* 方法: 方法<3>.


File: python.info,  Node: Attributes,  Next: 方法<3>,  Up: NNTP Objects

5.21.16.2 Attributes
....................

 -- 属性: NNTP.nntp_version

     An integer representing the version of the NNTP protocol supported
     by the server.  In practice, this should be ‘2’ for servers
     advertising RFC 3977(1) compliance and ‘1’ for others.

     3.2 新版功能.

 -- 属性: NNTP.nntp_implementation

     A string describing the software name and version of the NNTP
     server, or *note None: 158. if not advertised by the server.

     3.2 新版功能.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3977.html


File: python.info,  Node: 方法<3>,  Prev: Attributes,  Up: NNTP Objects

5.21.16.3 方法
..............

The `response' that is returned as the first item in the return tuple of
almost all methods is the server’s response: a string beginning with a
three-digit code.  If the server’s response indicates an error, the
method raises one of the above exceptions.

Many of the following methods take an optional keyword-only argument
`file'.  When the `file' argument is supplied, it must be either a *note
file object: b4a. opened for binary writing, or the name of an on-disk
file to be written to.  The method will then write any data returned by
the server (except for the response line and the terminating dot) to the
file; any list of lines, tuples or objects that the method normally
returns will be empty.

在 3.2 版更改: Many of the following methods have been reworked and
fixed, which makes them incompatible with their 3.1 counterparts.

 -- 方法: NNTP.quit ()

     Send a ‘QUIT’ command and close the connection.  Once this method
     has been called, no other methods of the NNTP object should be
     called.

 -- 方法: NNTP.getwelcome ()

     返回服务器发送的欢迎消息，作为连接开始的回复。（该消息有时包含与用
     户有关的免责声明或帮助信息。）

 -- 方法: NNTP.getcapabilities ()

     Return the RFC 3977(1) capabilities advertised by the server, as a
     *note dict: 1b9. instance mapping capability names to (possibly
     empty) lists of values.  On legacy servers which don’t understand
     the ‘CAPABILITIES’ command, an empty dictionary is returned
     instead.

          >>> s = NNTP('news.gmane.io')
          >>> 'POST' in s.getcapabilities()
          True

     3.2 新版功能.

 -- 方法: NNTP.login (user=None, password=None, usenetrc=True)

     Send ‘AUTHINFO’ commands with the user name and password.  If
     `user' and `password' are ‘None’ and `usenetrc' is true,
     credentials from ‘~/.netrc’ will be used if possible.

     Unless intentionally delayed, login is normally performed during
     the *note NNTP: a34. object initialization and separately calling
     this function is unnecessary.  To force authentication to be
     delayed, you must not set `user' or `password' when creating the
     object, and must set `usenetrc' to False.

     3.2 新版功能.

 -- 方法: NNTP.starttls (context=None)

     Send a ‘STARTTLS’ command.  This will enable encryption on the NNTP
     connection.  The `context' argument is optional and should be a
     *note ssl.SSLContext: 3ec. object.  Please read *note 安全考量:
     25bd. for best practices.

     Note that this may not be done after authentication information has
     been transmitted, and authentication occurs by default if possible
     during a *note NNTP: a34. object initialization.  See *note
     NNTP.login(): 2da3. for information on suppressing this behavior.

     3.2 新版功能.

     在 3.4 版更改: 此方法现在支持使用 *note
     ssl.SSLContext.check_hostname: 26d3. 和 `服务器名称指示' (参见
     *note ssl.HAS_SNI: 26e8.) 进行主机名检查。

 -- 方法: NNTP.newgroups (date, *, file=None)

     Send a ‘NEWGROUPS’ command.  The `date' argument should be a *note
     datetime.date: 194. or *note datetime.datetime: 195. object.
     Return a pair ‘(response, groups)’ where `groups' is a list
     representing the groups that are new since the given `date'.  If
     `file' is supplied, though, then `groups' will be empty.

          >>> from datetime import date, timedelta
          >>> resp, groups = s.newgroups(date.today() - timedelta(days=3))
          >>> len(groups)
          85
          >>> groups[0]
          GroupInfo(group='gmane.network.tor.devel', last='4', first='1', flag='m')

 -- 方法: NNTP.newnews (group, date, *, file=None)

     Send a ‘NEWNEWS’ command.  Here, `group' is a group name or ‘'*'’,
     and `date' has the same meaning as for *note newgroups(): 2da4.
     Return a pair ‘(response, articles)’ where `articles' is a list of
     message ids.

     This command is frequently disabled by NNTP server administrators.

 -- 方法: NNTP.list (group_pattern=None, *, file=None)

     Send a ‘LIST’ or ‘LIST ACTIVE’ command.  Return a pair ‘(response,
     list)’ where `list' is a list of tuples representing all the groups
     available from this NNTP server, optionally matching the pattern
     string `group_pattern'.  Each tuple has the form ‘(group, last,
     first, flag)’, where `group' is a group name, `last' and `first'
     are the last and first article numbers, and `flag' usually takes
     one of these values:

        * ‘y’: Local postings and articles from peers are allowed.

        * ‘m’: The group is moderated and all postings must be approved.

        * ‘n’: No local postings are allowed, only articles from peers.

        * ‘j’: Articles from peers are filed in the junk group instead.

        * ‘x’: No local postings, and articles from peers are ignored.

        * ‘=foo.bar’: Articles are filed in the ‘foo.bar’ group instead.

     If `flag' has another value, then the status of the newsgroup
     should be considered unknown.

     This command can return very large results, especially if
     `group_pattern' is not specified.  It is best to cache the results
     offline unless you really need to refresh them.

     在 3.2 版更改: `group_pattern' was added.

 -- 方法: NNTP.descriptions (grouppattern)

     Send a ‘LIST NEWSGROUPS’ command, where `grouppattern' is a wildmat
     string as specified in RFC 3977(2) (it’s essentially the same as
     DOS or UNIX shell wildcard strings).  Return a pair ‘(response,
     descriptions)’, where `descriptions' is a dictionary mapping group
     names to textual descriptions.

          >>> resp, descs = s.descriptions('gmane.comp.python.*')
          >>> len(descs)
          295
          >>> descs.popitem()
          ('gmane.comp.python.bio.general', 'BioPython discussion list (Moderated)')

 -- 方法: NNTP.description (group)

     Get a description for a single group `group'.  If more than one
     group matches (if ’group’ is a real wildmat string), return the
     first match.  If no group matches, return an empty string.

     This elides the response code from the server.  If the response
     code is needed, use *note descriptions(): 2da7.

 -- 方法: NNTP.group (name)

     Send a ‘GROUP’ command, where `name' is the group name.  The group
     is selected as the current group, if it exists.  Return a tuple
     ‘(response, count, first, last, name)’ where `count' is the
     (estimated) number of articles in the group, `first' is the first
     article number in the group, `last' is the last article number in
     the group, and `name' is the group name.

 -- 方法: NNTP.over (message_spec, *, file=None)

     Send an ‘OVER’ command, or an ‘XOVER’ command on legacy servers.
     `message_spec' can be either a string representing a message id, or
     a ‘(first, last)’ tuple of numbers indicating a range of articles
     in the current group, or a ‘(first, None)’ tuple indicating a range
     of articles starting from `first' to the last article in the
     current group, or *note None: 158. to select the current article in
     the current group.

     Return a pair ‘(response, overviews)’.  `overviews' is a list of
     ‘(article_number, overview)’ tuples, one for each article selected
     by `message_spec'.  Each `overview' is a dictionary with the same
     number of items, but this number depends on the server.  These
     items are either message headers (the key is then the lower-cased
     header name) or metadata items (the key is then the metadata name
     prepended with ‘":"’).  The following items are guaranteed to be
     present by the NNTP specification:

        * the ‘subject’, ‘from’, ‘date’, ‘message-id’ and ‘references’
          headers

        * the ‘:bytes’ metadata: the number of bytes in the entire raw
          article (including headers and body)

        * the ‘:lines’ metadata: the number of lines in the article body

     The value of each item is either a string, or *note None: 158. if
     not present.

     It is advisable to use the *note decode_header(): 2dab. function on
     header values when they may contain non-ASCII characters:

          >>> _, _, first, last, _ = s.group('gmane.comp.python.devel')
          >>> resp, overviews = s.over((last, last))
          >>> art_num, over = overviews[0]
          >>> art_num
          117216
          >>> list(over.keys())
          ['xref', 'from', ':lines', ':bytes', 'references', 'date', 'message-id', 'subject']
          >>> over['from']
          '=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?= <martin@v.loewis.de>'
          >>> nntplib.decode_header(over['from'])
          '"Martin v. Löwis" <martin@v.loewis.de>'

     3.2 新版功能.

 -- 方法: NNTP.help (*, file=None)

     Send a ‘HELP’ command.  Return a pair ‘(response, list)’ where
     `list' is a list of help strings.

 -- 方法: NNTP.stat (message_spec=None)

     Send a ‘STAT’ command, where `message_spec' is either a message id
     (enclosed in ‘'<'’ and ‘'>'’) or an article number in the current
     group.  If `message_spec' is omitted or *note None: 158, the
     current article in the current group is considered.  Return a
     triple ‘(response, number, id)’ where `number' is the article
     number and `id' is the message id.

          >>> _, _, first, last, _ = s.group('gmane.comp.python.devel')
          >>> resp, number, message_id = s.stat(first)
          >>> number, message_id
          (9099, '<20030112190404.GE29873@epoch.metaslash.com>')

 -- 方法: NNTP.next ()

     Send a ‘NEXT’ command.  Return as for *note stat(): 2dad.

 -- 方法: NNTP.last ()

     Send a ‘LAST’ command.  Return as for *note stat(): 2dad.

 -- 方法: NNTP.article (message_spec=None, *, file=None)

     Send an ‘ARTICLE’ command, where `message_spec' has the same
     meaning as for *note stat(): 2dad.  Return a tuple ‘(response,
     info)’ where `info' is a *note namedtuple: 1b7. with three
     attributes `number', `message_id' and `lines' (in that order).
     `number' is the article number in the group (or 0 if the
     information is not available), `message_id' the message id as a
     string, and `lines' a list of lines (without terminating newlines)
     comprising the raw message including headers and body.

          >>> resp, info = s.article('<20030112190404.GE29873@epoch.metaslash.com>')
          >>> info.number
          0
          >>> info.message_id
          '<20030112190404.GE29873@epoch.metaslash.com>'
          >>> len(info.lines)
          65
          >>> info.lines[0]
          b'Path: main.gmane.org!not-for-mail'
          >>> info.lines[1]
          b'From: Neal Norwitz <neal@metaslash.com>'
          >>> info.lines[-3:]
          [b'There is a patch for 2.3 as well as 2.2.', b'', b'Neal']

 -- 方法: NNTP.head (message_spec=None, *, file=None)

     Same as *note article(): 2db0, but sends a ‘HEAD’ command.  The
     `lines' returned (or written to `file') will only contain the
     message headers, not the body.

 -- 方法: NNTP.body (message_spec=None, *, file=None)

     Same as *note article(): 2db0, but sends a ‘BODY’ command.  The
     `lines' returned (or written to `file') will only contain the
     message body, not the headers.

 -- 方法: NNTP.post (data)

     Post an article using the ‘POST’ command.  The `data' argument is
     either a *note file object: b4a. opened for binary reading, or any
     iterable of bytes objects (representing raw lines of the article to
     be posted).  It should represent a well-formed news article,
     including the required headers.  The *note post(): 2db3. method
     automatically escapes lines beginning with ‘.’ and appends the
     termination line.

     If the method succeeds, the server’s response is returned.  If the
     server refuses posting, a *note NNTPReplyError: 2d96. is raised.

 -- 方法: NNTP.ihave (message_id, data)

     Send an ‘IHAVE’ command.  `message_id' is the id of the message to
     send to the server (enclosed in ‘'<'’ and ‘'>'’).  The `data'
     parameter and the return value are the same as for *note post():
     2db3.

 -- 方法: NNTP.date ()

     Return a pair ‘(response, date)’.  `date' is a *note datetime: 195.
     object containing the current date and time of the server.

 -- 方法: NNTP.slave ()

     Send a ‘SLAVE’ command.  Return the server’s `response'.

 -- 方法: NNTP.set_debuglevel (level)

     Set the instance’s debugging level.  This controls the amount of
     debugging output printed.  The default, ‘0’, produces no debugging
     output.  A value of ‘1’ produces a moderate amount of debugging
     output, generally a single line per request or response.  A value
     of ‘2’ or higher produces the maximum amount of debugging output,
     logging each line sent and received on the connection (including
     message text).

The following are optional NNTP extensions defined in RFC 2980(3).  Some
of them have been superseded by newer commands in RFC 3977(4).

 -- 方法: NNTP.xhdr (hdr, str, *, file=None)

     Send an ‘XHDR’ command.  The `hdr' argument is a header keyword,
     e.g.  ‘'subject'’.  The `str' argument should have the form
     ‘'first-last'’ where `first' and `last' are the first and last
     article numbers to search.  Return a pair ‘(response, list)’, where
     `list' is a list of pairs ‘(id, text)’, where `id' is an article
     number (as a string) and `text' is the text of the requested header
     for that article.  If the `file' parameter is supplied, then the
     output of the ‘XHDR’ command is stored in a file.  If `file' is a
     string, then the method will open a file with that name, write to
     it then close it.  If `file' is a *note file object: b4a, then it
     will start calling ‘write()’ on it to store the lines of the
     command output.  If `file' is supplied, then the returned `list' is
     an empty list.

 -- 方法: NNTP.xover (start, end, *, file=None)

     Send an ‘XOVER’ command.  `start' and `end' are article numbers
     delimiting the range of articles to select.  The return value is
     the same of for *note over(): 2daa.  It is recommended to use *note
     over(): 2daa. instead, since it will automatically use the newer
     ‘OVER’ command if available.

 -- 方法: NNTP.xpath (id)

     Return a pair ‘(resp, path)’, where `path' is the directory path to
     the article with message ID `id'.  Most of the time, this extension
     is not enabled by NNTP server administrators.

     3.3 版后已移除: The XPATH extension is not actively used.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3977.html

   (2) https://tools.ietf.org/html/rfc3977.html

   (3) https://tools.ietf.org/html/rfc2980.html

   (4) https://tools.ietf.org/html/rfc3977.html


File: python.info,  Node: 工具函数<2>,  Prev: NNTP Objects,  Up: nntplib --- NNTP protocol client

5.21.16.4 工具函数
..................

The module also defines the following utility function:

 -- 函数: nntplib.decode_header (header_str)

     Decode a header value, un-escaping any escaped non-ASCII
     characters.  `header_str' must be a *note str: 339. object.  The
     unescaped value is returned.  Using this function is recommended to
     display some headers in a human readable form:

          >>> decode_header("Some subject")
          'Some subject'
          >>> decode_header("=?ISO-8859-15?Q?D=E9buter_en_Python?=")
          'Débuter en Python'
          >>> decode_header("Re: =?UTF-8?B?cHJvYmzDqG1lIGRlIG1hdHJpY2U=?=")
          'Re: problème de matrice'


File: python.info,  Node: smtplib ---SMTP协议客户端,  Next: smtpd --- SMTP 服务器,  Prev: nntplib --- NNTP protocol client,  Up: 互联网协议和支持

5.21.17 ‘smtplib’ —SMTP协议客户端
---------------------------------

`源代码：' Lib/smtplib.py(1)

__________________________________________________________________

*note smtplib: ee. 模块定义了一个 SMTP 客户端会话对象，该对象可将邮件发
送到 Internet 上带有 SMTP 或 ESMTP 接收程序的计算机。 关于 SMTP 和 ESMTP
操作的详情请参阅 RFC 821(2) (简单邮件传输协议) 和 RFC 1869(3) (SMTP 服务
扩展)。

 -- 类: smtplib.SMTP (host='', port=0, local_hostname=None[, timeout],
          source_address=None)

     一个 *note SMTP: a89. 实例就是一个封装好的 SMTP 连接。该实例具有的
     方法支持所有 SMTP 和 ESMTP 操作。如果传入了可选参数 host 和 port，
     那么将在初始化时使用这些参数调用 SMTP *note connect(): eeb. 方法。
     如果传入了 `local_hostname'，它将在 HELO/EHLO 命令中被用作本地主机
     的 FQDN。否则将使用 *note socket.getfqdn(): 269a. 找到本地主机名。
     如果 *note connect(): eeb. 返回了成功码以外的内容，则引发 *note
     SMTPConnectError: 2dbe. 异常。可选参数 `timeout' 指定阻塞操作（如连
     接尝试）的超时（以秒为单位，如果未指定超时，将使用全局默认超时设置
     ）。到达超时时长后会引发 *note socket.timeout: c16. 异常。可选参数
     source_address 允许在有多张网卡的计算机中绑定到某些特定的源地址，和
     /或绑定到某些特定的源 TCP 端口。在连接前，套接字需要绑定一个 2 元组
     (host, port) 作为其源地址。如果省略，或者是主机为 ‘''’ 和/或端口为
     0，则将使用操作系统默认行为。

     正常使用时，只需要初始化或 connect 方法，*note sendmail(): 74d. 方
     法，再加上 *note SMTP.quit(): 2dbf. 方法即可。下文包括了一个示例。

     *note SMTP: a89. 类支持 *note with: 6f2. 语句。当这样使用时，‘with’
     语句一退出就会自动发出 SMTP ‘QUIT’ 命令。例如:

          >>> from smtplib import SMTP
          >>> with SMTP("domain.org") as smtp:
          ...     smtp.noop()
          ...
          (250, b'Ok')
          >>>

     All commands will raise an *note auditing event: ea1.
     ‘smtplib.SMTP.send’ with arguments ‘self’ and ‘data’, where ‘data’
     is the bytes about to be sent to the remote host.

     在 3.3 版更改: 添加了对 *note with: 6f2. 语句的支持。

     在 3.3 版更改: source_address argument was added.

     3.5 新版功能: The SMTPUTF8 extension ( RFC 6531(4)) is now
     supported.

 -- 类: smtplib.SMTP_SSL (host='', port=0, local_hostname=None,
          keyfile=None, certfile=None[, timeout], context=None,
          source_address=None)

     *note SMTP_SSL: a8a. 实例与 *note SMTP: a89. 实例的行为完全相同。在
     开始连接就需要 SSL，且 ‘starttls()’ 不适合的情况下，应该使用 *note
     SMTP_SSL: a8a.。如果未指定 `host'，则使用 localhost。如果 `port' 为
     0，则使用标准 SMTP-over-SSL 端口（465）。可选参数 `local_hostname'、
     `timeout' 和 `source_address' 的含义与 *note SMTP: a89. 类中的相同
     。可选参数 `context' 是一个 *note SSLContext: 3ec. 对象，可以从多个
     方面配置安全连接。请阅读 *note 安全考量: 25bd. 以获取最佳实践。

     `keyfile' and `certfile' are a legacy alternative to `context', and
     can point to a PEM formatted private key and certificate chain file
     for the SSL connection.

     在 3.3 版更改: 增加了 `context'。

     在 3.3 版更改: source_address argument was added.

     在 3.4 版更改: 本类现在支持通过 *note
     ssl.SSLContext.check_hostname: 26d3. 和 `服务器名称提示' （参阅
     *note ssl.HAS_SNI: 26e8.）进行主机名检查。

     3.6 版后已移除: `keyfile' 和 `certfile' 已弃用并转而推荐 `context'。
     请改用 *note ssl.SSLContext.load_cert_chain(): a99. 或让 *note
     ssl.create_default_context(): 8c9. 为你选择系统所信任的 CA 证书。

 -- 类: smtplib.LMTP (host='', port=LMTP_PORT, local_hostname=None,
          source_address=None)

     LMTP 协议与 ESMTP 非常相似，它很大程度上基于标准的 SMTP 客户端。将
     Unix 套接字用于 LMTP 是很常见的，因此 ‘connect()’ 方法支持 Unix 套
     接字，也支持常规的 host:port 服务器。可选参数 local_hostname 和
     source_address 的含义与 *note SMTP: a89. 类中的相同。要指定 Unix 套
     接字，`host' 必须使用绝对路径，以 ’/’ 开头。

     Authentication is supported, using the regular SMTP mechanism.
     When using a Unix socket, LMTP generally don’t support or require
     any authentication, but your mileage might vary.

A nice selection of exceptions is defined as well:

 -- 例外: smtplib.SMTPException

     Subclass of *note OSError: 1d4. that is the base exception class
     for all the other exceptions provided by this module.

     在 3.4 版更改: SMTPException became subclass of *note OSError: 1d4.

 -- 例外: smtplib.SMTPServerDisconnected

     This exception is raised when the server unexpectedly disconnects,
     or when an attempt is made to use the *note SMTP: a89. instance
     before connecting it to a server.

 -- 例外: smtplib.SMTPResponseException

     Base class for all exceptions that include an SMTP error code.
     These exceptions are generated in some instances when the SMTP
     server returns an error code.  The error code is stored in the
     ‘smtp_code’ attribute of the error, and the ‘smtp_error’ attribute
     is set to the error message.

 -- 例外: smtplib.SMTPSenderRefused

     Sender address refused.  In addition to the attributes set by on
     all *note SMTPResponseException: 2dc1. exceptions, this sets
     ’sender’ to the string that the SMTP server refused.

 -- 例外: smtplib.SMTPRecipientsRefused

     All recipient addresses refused.  The errors for each recipient are
     accessible through the attribute ‘recipients’, which is a
     dictionary of exactly the same sort as *note SMTP.sendmail(): 74d.
     returns.

 -- 例外: smtplib.SMTPDataError

     The SMTP server refused to accept the message data.

 -- 例外: smtplib.SMTPConnectError

     Error occurred during establishment of a connection with the
     server.

 -- 例外: smtplib.SMTPHeloError

     The server refused our ‘HELO’ message.

 -- 例外: smtplib.SMTPNotSupportedError

     The command or option attempted is not supported by the server.

     3.5 新版功能.

 -- 例外: smtplib.SMTPAuthenticationError

     SMTP authentication went wrong.  Most probably the server didn’t
     accept the username/password combination provided.

参见
....

RFC 821(5) - Simple Mail Transfer Protocol

     Protocol definition for SMTP. This document covers the model,
     operating procedure, and protocol details for SMTP.

RFC 1869(6) - SMTP Service Extensions

     Definition of the ESMTP extensions for SMTP. This describes a
     framework for extending SMTP with new commands, supporting dynamic
     discovery of the commands provided by the server, and defines a few
     additional commands.

* Menu:

* SMTP Objects::
* SMTP Example::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/smtplib.py

   (2) https://tools.ietf.org/html/rfc821.html

   (3) https://tools.ietf.org/html/rfc1869.html

   (4) https://tools.ietf.org/html/rfc6531.html

   (5) https://tools.ietf.org/html/rfc821.html

   (6) https://tools.ietf.org/html/rfc1869.html


File: python.info,  Node: SMTP Objects,  Next: SMTP Example,  Up: smtplib ---SMTP协议客户端

5.21.17.1 SMTP Objects
......................

An *note SMTP: a89. instance has the following methods:

 -- 方法: SMTP.set_debuglevel (level)

     Set the debug output level.  A value of 1 or ‘True’ for `level'
     results in debug messages for connection and for all messages sent
     to and received from the server.  A value of 2 for `level' results
     in these messages being timestamped.

     在 3.5 版更改: Added debuglevel 2.

 -- 方法: SMTP.docmd (cmd, args='')

     Send a command `cmd' to the server.  The optional argument `args'
     is simply concatenated to the command, separated by a space.

     This returns a 2-tuple composed of a numeric response code and the
     actual response line (multiline responses are joined into one long
     line.)

     In normal operation it should not be necessary to call this method
     explicitly.  It is used to implement other methods and may be
     useful for testing private extensions.

     If the connection to the server is lost while waiting for the
     reply, *note SMTPServerDisconnected: 2dc0. will be raised.

 -- 方法: SMTP.connect (host='localhost', port=0)

     连接到某个主机的某个端口。默认是连接到 localhost 的标准 SMTP 端口（
     25）上。如果主机名以冒号 (‘':'’) 结尾，后跟数字，则该后缀将被删除，
     且数字将视作要使用的端口号。如果在实例化时指定了 host，则构造函数会
     自动调用本方法。返回包含响应码和响应消息的 2 元组，它们由服务器在其
     连接响应中发送。

     Raises an *note auditing event: ea1. ‘smtplib.connect’ with
     arguments ‘self’, ‘host’, ‘port’.

 -- 方法: SMTP.helo (name='')

     Identify yourself to the SMTP server using ‘HELO’.  The hostname
     argument defaults to the fully qualified domain name of the local
     host.  The message returned by the server is stored as the
     ‘helo_resp’ attribute of the object.

     In normal operation it should not be necessary to call this method
     explicitly.  It will be implicitly called by the *note sendmail():
     74d. when necessary.

 -- 方法: SMTP.ehlo (name='')

     使用 ‘EHLO’ 向 ESMTP 服务器标识自身。hostname 参数默认为 localhost
     的标准域名。使用 *note has_extn(): 2dcc. 来检查响应中的 ESMTP 选项
     ，并将它们保存起来。还给一些信息性的属性赋值：服务器返回的消息存储
     为 ‘ehlo_resp’ 属性；根据服务器是否支持 ESMTP，将 ‘does_esmtp’ 设置
     为 true 或 false；而 ‘esmtp_features’ 是一个字典，包含该服务器支持
     的 SMTP 服务扩展的名称及参数（如果有参数）。

     Unless you wish to use *note has_extn(): 2dcc. before sending mail,
     it should not be necessary to call this method explicitly.  It will
     be implicitly called by *note sendmail(): 74d. when necessary.

 -- 方法: SMTP.ehlo_or_helo_if_needed ()

     This method calls *note ehlo(): 2dcb. and/or *note helo(): 2dca. if
     there has been no previous ‘EHLO’ or ‘HELO’ command this session.
     It tries ESMTP ‘EHLO’ first.

     *note SMTPHeloError: 2dc5.

          The server didn’t reply properly to the ‘HELO’ greeting.

 -- 方法: SMTP.has_extn (name)

     Return *note True: 4a1. if `name' is in the set of SMTP service
     extensions returned by the server, *note False: 390. otherwise.
     Case is ignored.

 -- 方法: SMTP.verify (address)

     Check the validity of an address on this server using SMTP ‘VRFY’.
     Returns a tuple consisting of code 250 and a full RFC 822(1)
     address (including human name) if the user address is valid.
     Otherwise returns an SMTP error code of 400 or greater and an error
     string.

          注解: Many sites disable SMTP ‘VRFY’ in order to foil
          spammers.

 -- 方法: SMTP.login (user, password, *, initial_response_ok=True)

     Log in on an SMTP server that requires authentication.  The
     arguments are the username and the password to authenticate with.
     If there has been no previous ‘EHLO’ or ‘HELO’ command this
     session, this method tries ESMTP ‘EHLO’ first.  This method will
     return normally if the authentication was successful, or may raise
     the following exceptions:

     *note SMTPHeloError: 2dc5.

          The server didn’t reply properly to the ‘HELO’ greeting.

     *note SMTPAuthenticationError: 2dc6.

          The server didn’t accept the username/password combination.

     *note SMTPNotSupportedError: f7d.

          The ‘AUTH’ command is not supported by the server.

     *note SMTPException: 8c0.

          No suitable authentication method was found.

     Each of the authentication methods supported by *note smtplib: ee.
     are tried in turn if they are advertised as supported by the
     server.  See *note auth(): 74b. for a list of supported
     authentication methods.  `initial_response_ok' is passed through to
     *note auth(): 74b.

     Optional keyword argument `initial_response_ok' specifies whether,
     for authentication methods that support it, an "initial response"
     as specified in RFC 4954(2) can be sent along with the ‘AUTH’
     command, rather than requiring a challenge/response.

     在 3.5 版更改: *note SMTPNotSupportedError: f7d. may be raised, and
     the `initial_response_ok' parameter was added.

 -- 方法: SMTP.auth (mechanism, authobject, *, initial_response_ok=True)

     Issue an ‘SMTP’ ‘AUTH’ command for the specified authentication
     `mechanism', and handle the challenge response via `authobject'.

     `mechanism' specifies which authentication mechanism is to be used
     as argument to the ‘AUTH’ command; the valid values are those
     listed in the ‘auth’ element of ‘esmtp_features’.

     `authobject' must be a callable object taking an optional single
     argument:

          data = authobject(challenge=None)

     If optional keyword argument `initial_response_ok' is true,
     ‘authobject()’ will be called first with no argument.  It can
     return the RFC 4954(3) "initial response" ASCII ‘str’ which will be
     encoded and sent with the ‘AUTH’ command as below.  If the
     ‘authobject()’ does not support an initial response (e.g.  because
     it requires a challenge), it should return ‘None’ when called with
     ‘challenge=None’.  If `initial_response_ok' is false, then
     ‘authobject()’ will not be called first with ‘None’.

     If the initial response check returns ‘None’, or if
     `initial_response_ok' is false, ‘authobject()’ will be called to
     process the server’s challenge response; the `challenge' argument
     it is passed will be a ‘bytes’.  It should return ASCII ‘str’
     `data' that will be base64 encoded and sent to the server.

     The ‘SMTP’ class provides ‘authobjects’ for the ‘CRAM-MD5’,
     ‘PLAIN’, and ‘LOGIN’ mechanisms; they are named
     ‘SMTP.auth_cram_md5’, ‘SMTP.auth_plain’, and ‘SMTP.auth_login’
     respectively.  They all require that the ‘user’ and ‘password’
     properties of the ‘SMTP’ instance are set to appropriate values.

     User code does not normally need to call ‘auth’ directly, but can
     instead call the *note login(): 2dcf. method, which will try each
     of the above mechanisms in turn, in the order listed.  ‘auth’ is
     exposed to facilitate the implementation of authentication methods
     not (or not yet) supported directly by *note smtplib: ee.

     3.5 新版功能.

 -- 方法: SMTP.starttls (keyfile=None, certfile=None, context=None)

     Put the SMTP connection in TLS (Transport Layer Security) mode.
     All SMTP commands that follow will be encrypted.  You should then
     call *note ehlo(): 2dcb. again.

     If `keyfile' and `certfile' are provided, they are used to create
     an *note ssl.SSLContext: 3ec.

     Optional `context' parameter is an *note ssl.SSLContext: 3ec.
     object; This is an alternative to using a keyfile and a certfile
     and if specified both `keyfile' and `certfile' should be ‘None’.

     If there has been no previous ‘EHLO’ or ‘HELO’ command this
     session, this method tries ESMTP ‘EHLO’ first.

     3.6 版后已移除: `keyfile' 和 `certfile' 已弃用并转而推荐 `context'。
     请改用 *note ssl.SSLContext.load_cert_chain(): a99. 或让 *note
     ssl.create_default_context(): 8c9. 为你选择系统所信任的 CA 证书。

     *note SMTPHeloError: 2dc5.

          The server didn’t reply properly to the ‘HELO’ greeting.

     *note SMTPNotSupportedError: f7d.

          The server does not support the STARTTLS extension.

     *note RuntimeError: 2bb.

          SSL/TLS support is not available to your Python interpreter.

     在 3.3 版更改: 增加了 `context'。

     在 3.4 版更改: The method now supports hostname check with
     ‘SSLContext.check_hostname’ and `Server Name Indicator' (see *note
     HAS_SNI: 26e8.).

     在 3.5 版更改: The error raised for lack of STARTTLS support is now
     the *note SMTPNotSupportedError: f7d. subclass instead of the base
     *note SMTPException: 8c0.

 -- 方法: SMTP.sendmail (from_addr, to_addrs, msg, mail_options=(),
          rcpt_options=())

     发送邮件。必要参数是一个 RFC 822(4) 发件地址字符串，一个 RFC 822(5)
     收件地址字符串列表（裸字符串将被视为含有 1 个地址的列表），以及一个
     消息字符串。调用者可以将 ESMTP 选项列表（如 ‘8bitmime’）作为
     `mail_options' 传入，用于 ‘MAIL FROM’ 命令。需要与所有 ‘RCPT’ 命令
     一起使用的 ESMTP 选项（如 ‘DSN’ 命令）可以作为 `rcpt_options' 传入
     。（如果需要对不同的收件人使用不同的 ESMTP 选项，则必须使用底层的方
     法来发送消息，如 ‘mail()’, ‘rcpt()’ 和 ‘data()’。）

          注解: The `from_addr' and `to_addrs' parameters are used to
          construct the message envelope used by the transport agents.
          ‘sendmail’ does not modify the message headers in any way.

     `msg' may be a string containing characters in the ASCII range, or
     a byte string.  A string is encoded to bytes using the ascii codec,
     and lone ‘\r’ and ‘\n’ characters are converted to ‘\r\n’
     characters.  A byte string is not modified.

     If there has been no previous ‘EHLO’ or ‘HELO’ command this
     session, this method tries ESMTP ‘EHLO’ first.  If the server does
     ESMTP, message size and each of the specified options will be
     passed to it (if the option is in the feature set the server
     advertises).  If ‘EHLO’ fails, ‘HELO’ will be tried and ESMTP
     options suppressed.

     This method will return normally if the mail is accepted for at
     least one recipient.  Otherwise it will raise an exception.  That
     is, if this method does not raise an exception, then someone should
     get your mail.  If this method does not raise an exception, it
     returns a dictionary, with one entry for each recipient that was
     refused.  Each entry contains a tuple of the SMTP error code and
     the accompanying error message sent by the server.

     If ‘SMTPUTF8’ is included in `mail_options', and the server
     supports it, `from_addr' and `to_addrs' may contain non-ASCII
     characters.

     This method may raise the following exceptions:

     *note SMTPRecipientsRefused: 2dc3.

          All recipients were refused.  Nobody got the mail.  The
          ‘recipients’ attribute of the exception object is a dictionary
          with information about the refused recipients (like the one
          returned when at least one recipient was accepted).

     *note SMTPHeloError: 2dc5.

          The server didn’t reply properly to the ‘HELO’ greeting.

     *note SMTPSenderRefused: 2dc2.

          The server didn’t accept the `from_addr'.

     *note SMTPDataError: 2dc4.

          The server replied with an unexpected error code (other than a
          refusal of a recipient).

     *note SMTPNotSupportedError: f7d.

          ‘SMTPUTF8’ was given in the `mail_options' but is not
          supported by the server.

     Unless otherwise noted, the connection will be open even after an
     exception is raised.

     在 3.2 版更改: `msg' may be a byte string.

     在 3.5 版更改: ‘SMTPUTF8’ support added, and *note
     SMTPNotSupportedError: f7d. may be raised if ‘SMTPUTF8’ is
     specified but the server does not support it.

 -- 方法: SMTP.send_message (msg, from_addr=None, to_addrs=None,
          mail_options=(), rcpt_options=())

     本方法是一种快捷方法，用于带着消息调用 *note sendmail(): 74d.，消息
     由 *note email.message.Message: 54a. 对象表示。参数的含义与 *note
     sendmail(): 74d. 中的相同，除了 `msg'，它是一个 ‘Message’ 对象。

     如果 `from_addr' 为 ‘None’ 或 `to_addrs' 为 ‘None’，那么
     ‘‘send_message‘‘将根据 RFC 5322(6)，从 `msg' 头部提取地址填充下列参
     数：如果头部存在 ‘Sender’ 字段，则用它填充 `from_addr'，不存在则用
     ‘From’ 字段填充 `from_addr'。`to_addrs' 组合了 `msg' 中的 ‘To’,
     ‘Cc’ 和 ‘Bcc’ 字段的值（字段存在的情况下）。如果一组 ‘Resent-*’ 头
     部恰好出现在 message 中，那么就忽略常规的头部，改用 ‘Resent-*’ 头部
     。如果 message 包含多组 ‘Resent-*’ 头部，则引发 *note ValueError:
     1fc.，因为无法明确检测出哪一组 ‘Resent-’ 头部是最新的。

     ‘send_message’ 使用 *note BytesGenerator: b55. 来序列化 `msg'，且将
     ‘\r\n’ 作为 `linesep'，并调用 *note sendmail(): 74d. 来传输序列化后
     的结果。无论 `from_addr' 和 `to_addrs' 的值为何，‘send_message’ 都
     不会传输 `msg' 中可能出现的 ‘Bcc’ 或 ‘Resent-Bcc’ 头部。如果
     `from_addr' 和 `to_addrs' 中的某个地址包含非 ASCII 字符，且服务器没
     有声明支持 ‘SMTPUTF8’，则引发 ‘SMTPNotSupported’ 错误。如果服务器支
     持，则 ‘Message’ 将按新克隆的 *note policy: 75. 进行序列化，其中的
     *note utf8: 6db. 属性被设置为 ‘True’，且 ‘SMTPUTF8’ 和
     ‘BODY=8BITMIME’ 被添加到 `mail_options' 中。

     3.2 新版功能.

     3.5 新版功能: Support for internationalized addresses (‘SMTPUTF8’).

 -- 方法: SMTP.quit ()

     Terminate the SMTP session and close the connection.  Return the
     result of the SMTP ‘QUIT’ command.

Low-level methods corresponding to the standard SMTP/ESMTP commands
‘HELP’, ‘RSET’, ‘NOOP’, ‘MAIL’, ‘RCPT’, and ‘DATA’ are also supported.
Normally these do not need to be called directly, so they are not
documented here.  For details, consult the module code.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc822.html

   (2) https://tools.ietf.org/html/rfc4954.html

   (3) https://tools.ietf.org/html/rfc4954.html

   (4) https://tools.ietf.org/html/rfc822.html

   (5) https://tools.ietf.org/html/rfc822.html

   (6) https://tools.ietf.org/html/rfc5322.html


File: python.info,  Node: SMTP Example,  Prev: SMTP Objects,  Up: smtplib ---SMTP协议客户端

5.21.17.2 SMTP Example
......................

This example prompts the user for addresses needed in the message
envelope (’To’ and ’From’ addresses), and the message to be delivered.
Note that the headers to be included with the message must be included
in the message as entered; this example doesn’t do any processing of the
RFC 822(1) headers.  In particular, the ’To’ and ’From’ addresses must
be included in the message headers explicitly.

     import smtplib

     def prompt(prompt):
         return input(prompt).strip()

     fromaddr = prompt("From: ")
     toaddrs  = prompt("To: ").split()
     print("Enter message, end with ^D (Unix) or ^Z (Windows):")

     # Add the From: and To: headers at the start!
     msg = ("From: %s\r\nTo: %s\r\n\r\n"
            % (fromaddr, ", ".join(toaddrs)))
     while True:
         try:
             line = input()
         except EOFError:
             break
         if not line:
             break
         msg = msg + line

     print("Message length is", len(msg))

     server = smtplib.SMTP('localhost')
     server.set_debuglevel(1)
     server.sendmail(fromaddr, toaddrs, msg)
     server.quit()

     注解: In general, you will want to use the *note email: 69.
     package’s features to construct an email message, which you can
     then send via *note send_message(): 74e.; see *note email; 示例:
     84e.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc822.html


File: python.info,  Node: smtpd --- SMTP 服务器,  Next: telnetlib -- Telnet 客户端,  Prev: smtplib ---SMTP协议客户端,  Up: 互联网协议和支持

5.21.18 ‘smtpd’ — SMTP 服务器
-----------------------------

`源代码:' Lib/smtpd.py(1)

__________________________________________________________________

This module offers several classes to implement SMTP (email) servers.

参见
....

The aiosmtpd(2) package is a recommended replacement for this module.
It is based on *note asyncio: a. and provides a more straightforward
API. *note smtpd: ed. should be considered deprecated.

Several server implementations are present; one is a generic do-nothing
implementation, which can be overridden, while the other two offer
specific mail-sending strategies.

Additionally the SMTPChannel may be extended to implement very specific
interaction behaviour with SMTP clients.

The code supports RFC 5321(3), plus the RFC 1870(4) SIZE and RFC 6531(5)
SMTPUTF8 extensions.

* Menu:

* SMTPServer 对象::
* DebuggingServer 对象::
* PureProxy对象::
* MailmanProxy 对象::
* SMTPChannel 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/smtpd.py

   (2) http://aiosmtpd.readthedocs.io/

   (3) https://tools.ietf.org/html/rfc5321.html

   (4) https://tools.ietf.org/html/rfc1870.html

   (5) https://tools.ietf.org/html/rfc6531.html


File: python.info,  Node: SMTPServer 对象,  Next: DebuggingServer 对象,  Up: smtpd --- SMTP 服务器

5.21.18.1 SMTPServer 对象
.........................

 -- 类: smtpd.SMTPServer (localaddr, remoteaddr,
          data_size_limit=33554432, map=None, enable_SMTPUTF8=False,
          decode_data=False)

     Create a new *note SMTPServer: 60b. object, which binds to local
     address `localaddr'.  It will treat `remoteaddr' as an upstream
     SMTP relayer.  Both `localaddr' and `remoteaddr' should be a *note
     (host, port): 2675. tuple.  The object inherits from *note
     asyncore.dispatcher: bcb, and so will insert itself into *note
     asyncore: b.’s event loop on instantiation.

     `data_size_limit' specifies the maximum number of bytes that will
     be accepted in a ‘DATA’ command.  A value of ‘None’ or ‘0’ means no
     limit.

     `map' is the socket map to use for connections (an initially empty
     dictionary is a suitable value).  If not specified the *note
     asyncore: b. global socket map is used.

     `enable_SMTPUTF8' determines whether the ‘SMTPUTF8’ extension (as
     defined in RFC 6531(1)) should be enabled.  The default is ‘False’.
     When ‘True’, ‘SMTPUTF8’ is accepted as a parameter to the ‘MAIL’
     command and when present is passed to *note process_message(): 60c.
     in the ‘kwargs['mail_options']’ list.  `decode_data' and
     `enable_SMTPUTF8' cannot be set to ‘True’ at the same time.

     `decode_data' specifies whether the data portion of the SMTP
     transaction should be decoded using UTF-8.  When `decode_data' is
     ‘False’ (the default), the server advertises the ‘8BITMIME’
     extension ( RFC 6152(2)), accepts the ‘BODY=8BITMIME’ parameter to
     the ‘MAIL’ command, and when present passes it to *note
     process_message(): 60c. in the ‘kwargs['mail_options']’ list.
     `decode_data' and `enable_SMTPUTF8' cannot be set to ‘True’ at the
     same time.

      -- 方法: process_message (peer, mailfrom, rcpttos, data, **kwargs)

          Raise a *note NotImplementedError: 617. exception.  Override
          this in subclasses to do something useful with this message.
          Whatever was passed in the constructor as `remoteaddr' will be
          available as the ‘_remoteaddr’ attribute.  `peer' is the
          remote host’s address, `mailfrom' is the envelope originator,
          `rcpttos' are the envelope recipients and `data' is a string
          containing the contents of the e-mail (which should be in RFC
          5321(3) format).

          If the `decode_data' constructor keyword is set to ‘True’, the
          `data' argument will be a unicode string.  If it is set to
          ‘False’, it will be a bytes object.

          `kwargs' is a dictionary containing additional information.
          It is empty if ‘decode_data=True’ was given as an init
          argument, otherwise it contains the following keys:

               `mail_options':

                    a list of all received parameters to the ‘MAIL’
                    command (the elements are uppercase strings;
                    example: ‘['BODY=8BITMIME', 'SMTPUTF8']’).

               `rcpt_options':

                    same as `mail_options' but for the ‘RCPT’ command.
                    Currently no ‘RCPT TO’ options are supported, so for
                    now this will always be an empty list.

          Implementations of ‘process_message’ should use the ‘**kwargs’
          signature to accept arbitrary keyword arguments, since future
          feature enhancements may add keys to the kwargs dictionary.

          Return ‘None’ to request a normal ‘250 Ok’ response; otherwise
          return the desired response string in RFC 5321(4) format.

      -- 属性: channel_class

          Override this in subclasses to use a custom *note SMTPChannel:
          60a. for managing SMTP clients.

     3.4 新版功能: The `map' constructor argument.

     在 3.5 版更改: `localaddr' and `remoteaddr' may now contain IPv6
     addresses.

     3.5 新版功能: The `decode_data' and `enable_SMTPUTF8' constructor
     parameters, and the `kwargs' parameter to *note process_message():
     60c. when `decode_data' is ‘False’.

     在 3.6 版更改: `decode_data' is now ‘False’ by default.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc6531.html

   (2) https://tools.ietf.org/html/rfc6152.html

   (3) https://tools.ietf.org/html/rfc5321.html

   (4) https://tools.ietf.org/html/rfc5321.html


File: python.info,  Node: DebuggingServer 对象,  Next: PureProxy对象,  Prev: SMTPServer 对象,  Up: smtpd --- SMTP 服务器

5.21.18.2 DebuggingServer 对象
..............................

 -- 类: smtpd.DebuggingServer (localaddr, remoteaddr)

     Create a new debugging server.  Arguments are as per *note
     SMTPServer: 60b.  Messages will be discarded, and printed on
     stdout.


File: python.info,  Node: PureProxy对象,  Next: MailmanProxy 对象,  Prev: DebuggingServer 对象,  Up: smtpd --- SMTP 服务器

5.21.18.3 PureProxy对象
.......................

 -- 类: smtpd.PureProxy (localaddr, remoteaddr)

     Create a new pure proxy server.  Arguments are as per *note
     SMTPServer: 60b.  Everything will be relayed to `remoteaddr'.  Note
     that running this has a good chance to make you into an open relay,
     so please be careful.


File: python.info,  Node: MailmanProxy 对象,  Next: SMTPChannel 对象,  Prev: PureProxy对象,  Up: smtpd --- SMTP 服务器

5.21.18.4 MailmanProxy 对象
...........................

 -- 类: smtpd.MailmanProxy (localaddr, remoteaddr)

     Create a new pure proxy server.  Arguments are as per *note
     SMTPServer: 60b.  Everything will be relayed to `remoteaddr',
     unless local mailman configurations knows about an address, in
     which case it will be handled via mailman.  Note that running this
     has a good chance to make you into an open relay, so please be
     careful.


File: python.info,  Node: SMTPChannel 对象,  Prev: MailmanProxy 对象,  Up: smtpd --- SMTP 服务器

5.21.18.5 SMTPChannel 对象
..........................

 -- 类: smtpd.SMTPChannel (server, conn, addr, data_size_limit=33554432,
          map=None, enable_SMTPUTF8=False, decode_data=False)

     Create a new *note SMTPChannel: 60a. object which manages the
     communication between the server and a single SMTP client.

     `conn' and `addr' are as per the instance variables described
     below.

     `data_size_limit' specifies the maximum number of bytes that will
     be accepted in a ‘DATA’ command.  A value of ‘None’ or ‘0’ means no
     limit.

     `enable_SMTPUTF8' determines whether the ‘SMTPUTF8’ extension (as
     defined in RFC 6531(1)) should be enabled.  The default is ‘False’.
     `decode_data' and `enable_SMTPUTF8' cannot be set to ‘True’ at the
     same time.

     A dictionary can be specified in `map' to avoid using a global
     socket map.

     `decode_data' specifies whether the data portion of the SMTP
     transaction should be decoded using UTF-8.  The default is ‘False’.
     `decode_data' and `enable_SMTPUTF8' cannot be set to ‘True’ at the
     same time.

     To use a custom SMTPChannel implementation you need to override the
     *note SMTPServer.channel_class: 2dd5. of your *note SMTPServer:
     60b.

     在 3.5 版更改: The `decode_data' and `enable_SMTPUTF8' parameters
     were added.

     在 3.6 版更改: `decode_data' is now ‘False’ by default.

     The *note SMTPChannel: 60a. has the following instance variables:

      -- 属性: smtp_server

          Holds the *note SMTPServer: 60b. that spawned this channel.

      -- 属性: conn

          Holds the socket object connecting to the client.

      -- 属性: addr

          Holds the address of the client, the second value returned by
          *note socket.accept: 67e.

      -- 属性: received_lines

          Holds a list of the line strings (decoded using UTF-8)
          received from the client.  The lines have their ‘"\r\n"’ line
          ending translated to ‘"\n"’.

      -- 属性: smtp_state

          Holds the current state of the channel.  This will be either
          ‘COMMAND’ initially and then ‘DATA’ after the client sends a
          "DATA" line.

      -- 属性: seen_greeting

          Holds a string containing the greeting sent by the client in
          its "HELO".

      -- 属性: mailfrom

          Holds a string containing the address identified in the "MAIL
          FROM:" line from the client.

      -- 属性: rcpttos

          Holds a list of strings containing the addresses identified in
          the "RCPT TO:" lines from the client.

      -- 属性: received_data

          Holds a string containing all of the data sent by the client
          during the DATA state, up to but not including the terminating
          ‘"\r\n.\r\n"’.

      -- 属性: fqdn

          Holds the fully-qualified domain name of the server as
          returned by *note socket.getfqdn(): 269a.

      -- 属性: peer

          Holds the name of the client peer as returned by
          ‘conn.getpeername()’ where ‘conn’ is *note conn: 2dde.

     The *note SMTPChannel: 60a. operates by invoking methods named
     ‘smtp_<command>’ upon reception of a command line from the client.
     Built into the base *note SMTPChannel: 60a. class are methods for
     handling the following commands (and responding to them
     appropriately):

     命令         所采取的行动
                  
     -------------------------------------------------------------------------------------
                  
     HELO         接受来自客户端的问候语，并将其存储在 *note seen_greeting: 2de2. 中。
                  将服务器设置为基本命令模式。
                  
                  
     EHLO         接受来自客户的问候并将其存储在 *note seen_greeting: 2de2. 中。将服务
                  器设置为扩展命令模式。
                  
                  
     NOOP         不采取任何措施。
                  
                  
     QUIT         干净地关闭连接。
                  
                  
     MAIL         Accepts the "MAIL FROM:" syntax and stores the supplied address as
                  *note mailfrom: 2de3.  In extended command mode, accepts the RFC
                  1870(2) SIZE attribute and responds appropriately based on the value
                  of `data_size_limit'.
                  
                  
     RCPT         Accepts the "RCPT TO:" syntax and stores the supplied addresses in
                  the *note rcpttos: 2de4. list.
                  
                  
     RSET         重置 *note mailfrom: 2de3, *note rcpttos: 2de4, 和
                  *note received_data: 2de5. ，但不重置问候语。
                  
                  
     DATA         Sets the internal state to ‘DATA’ and stores remaining lines from the
                  client in *note received_data: 2de5. until the terminator
                  ‘"\r\n.\r\n"’ is received.
                  
                  
     HELP         返回有关命令语法的最少信息
                  
                  
     VRFY         返回代码252（服务器不知道该地址是否有效）
                  
                  
     EXPN         报告该命令未实现。
                  

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc6531.html

   (2) https://tools.ietf.org/html/rfc1870.html


File: python.info,  Node: telnetlib -- Telnet 客户端,  Next: uuid --- UUID objects according to RFC 4122,  Prev: smtpd --- SMTP 服务器,  Up: 互联网协议和支持

5.21.19 ‘telnetlib’ – Telnet 客户端
-----------------------------------

`源代码:' Lib/telnetlib.py(1)

__________________________________________________________________

*note telnetlib: 103. 模块提供一个实现Telnet协议的类 *note Telnet: 5a0.。
关于此协议的细节请参见 RFC 854(2) 。此外，它还为协议字符（见下文）和
telnet 选项提供了对应的符号常量。telnet选项对应的符号名遵循
‘arpa/telnet.h’ 中的定义，但删除了前缀‘‘TELNET_‘‘。对于不在
‘arpa/telnet.h’ 的选项的符号常量名，请参考本模块源码。

telnet命令的符号常量名有： IAC, DONT, DO, WONT, WILL, SE (Subnegotiation
End), NOP (No Operation), DM (Data Mark), BRK (Break), IP (Interrupt
process), AO (Abort output), AYT (Are You There), EC (Erase Character),
EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin).

 -- 类: telnetlib.Telnet (host=None, port=0[, timeout])

     *note Telnet: 5a0. 表示到 Telnet 服务器的连接. 实例初始化后默认不连
     接；必须使用 *note open(): 2dea. 方法来建立连接。或者， 可选参数
     host 和 port 也可以传递给构造函数，在这种情况下，到服务器的连接将在
     构造函数返回前建立。可选参数 `timeout' 为阻塞操作（如连接尝试）指定
     一个以秒为单位的超时时间（如果没有指定，将使用全局默认设置） 。

     不要重新打开一个已经连接的实例。

     这个类有很多 ‘read_*()’ 方法。 请注意，其中一些方法在读取结束时会触
     发 *note EOFError: c74. 异常，这是由于连接对象可能出于其它原因返回
     一个空字符串。 请参阅下面的个别描述。

     *note Telnet: 5a0. 对象一个上下文管理器，可以在 *note with: 6f2. 语
     句中使用。当 ‘with’ 块结束，*note close(): 2deb. 方法会被调用:

          >>> from telnetlib import Telnet
          >>> with Telnet('localhost', 23) as tn:
          ...     tn.interact()
          ...

     在 3.6 版更改: 添加了上下文管理器的支持

参见
....

RFC 854(3) - Telnet 协议规范

     Telnet 协议的定义。

* Menu:

* Telnet 对象::
* Telnet 示例::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/telnetlib.py

   (2) https://tools.ietf.org/html/rfc854.html

   (3) https://tools.ietf.org/html/rfc854.html


File: python.info,  Node: Telnet 对象,  Next: Telnet 示例,  Up: telnetlib -- Telnet 客户端

5.21.19.1 Telnet 对象
.....................

*note Telnet: 5a0. 实例有以下几种方法：

 -- 方法: Telnet.read_until (expected, timeout=None)

     读取直到遇到给定字节串 `expected' 或 `timeout' 秒已经过去。

     当没有找到匹配时，返回可用的内容，也可能返回空字节。如果连接已关闭
     且没有可用的数据，将触发 *note EOFError: c74.。

 -- 方法: Telnet.read_all ()

     读取数据，直到遇到 EOF；连接关闭前都会保持阻塞。

 -- 方法: Telnet.read_some ()

     在达到 EOF 前，读取至少一个字节的熟数据。如果命中 EOF，返回 ‘b''’。
     如果没有立即可用的数据，则阻塞。

 -- 方法: Telnet.read_very_eager ()

     在不阻塞 I/O 的情况下（急切地）读取所有的内容。

     如果连接关闭并且没有可用的熟数据，将会触发 *note EOFError: c74. 。
     如果没有熟数据可用返回 ‘b''’ 。除非在一个 IAC 序列的中间，否则不要
     阻塞。

 -- 方法: Telnet.read_eager ()

     读取现成的数据。

     如果连接关闭并且没有可用的熟数据，将会触发 *note EOFError: c74. 。
     如果没有熟数据可用返回 ‘b''’ 。除非在一个 IAC 序列的中间，否则不要
     阻塞。

 -- 方法: Telnet.read_lazy ()

     处理并返回已经在队列中的数据（lazy）。

     如果连接已关闭并且没有可用的数据，将会触发 *note EOFError: c74. 。
     如果没有熟数据可用则返回 ‘b''’ 。除非在一个 IAC 序列的中间，否则不
     要进行阻塞。

 -- 方法: Telnet.read_very_lazy ()

     返回熟数据队列任何可用的数据（very lazy）。

     如果连接已关闭并且没有可用的数据，将会触发 *note EOFError: c74. 。
     如果没有熟数据可用则返回 ‘b''’ 。该方法永远不会阻塞。

 -- 方法: Telnet.read_sb_data ()

     返回在 SB/SE 对之间收集的数据（子选项 begin/end）。当使用 ‘SE’ 命令
     调用回调函数时，该回调函数应该访问这些数据。该方法永远不会阻塞。

 -- 方法: Telnet.open (host, port=0[, timeout])

     连接主机。第二个可选参数是端口号，默认为标准 Telnet 端口（23）。可
     选参数 `timeout' 指定一个以秒为单位的超时时间用于像连接尝试这样的阻
     塞操作（如果没有指定，将使用全局默认超时设置）。

     不要尝试重新打开一个已经连接的实例。

     触发 *note auditing event: ea1. ‘telnetlib.Telnet.open’ ，参数为
     ‘self’，‘host’，‘port’。

 -- 方法: Telnet.msg (msg, *args)

     当 debug level ‘>’ 0 时打印一条 debug 信息。如果存在额外参数，则它
     们会被替换在使用标准字符串格式化操作符的信息中。

 -- 方法: Telnet.set_debuglevel (debuglevel)

     设置调试级别

 -- 方法: Telnet.close ()

     关闭连接对象。

 -- 方法: Telnet.get_socket ()

     返回内部使用的套接字对象。

 -- 方法: Telnet.fileno ()

     返回内部使用的套接字对象的文件描述符。

 -- 方法: Telnet.write (buffer)

     向套接字写入一个字节字符串，将所有 IAC 字符加倍。如果连接被阻塞，这
     可能也会阻塞。如果连接关闭可能触发 *note OSError: 1d4.。

     触发 *note auditing event: ea1. ‘telnetlib.Telnet.write’ ，参数为
     ‘self’，‘buffer’。

     在 3.3 版更改: 曾经该函数抛出 *note socket.error: 99d.，现在这是
     *note OSError: 1d4. 的别名。

 -- 方法: Telnet.interact ()

     交互函数，模拟一个非常笨拙的 Telnet 客户端。

 -- 方法: Telnet.mt_interact ()

     多线程版的 *note interact(): 2dfb.

 -- 方法: Telnet.expect (list, timeout=None)

     一直读取，直到匹配列表中的某个正则表达式。

     第一个参数是一个正则表达式列表，可以是已编译的 (*note
     正则表达式对象: 8a5.)，也可以是未编译的 (字节串)。 第二个可选参数是
     超时，单位是秒；默认一直阻塞。

     返回一个包含三个元素的元组：列表中的第一个匹配的正则表达式的索引；
     返回的匹配对象；包括匹配在内的读取过的字节。

     如果找到了文件的结尾且没有字节被读取，触发 *note EOFError: c74.。否
     则，当没有匹配时,返回 ‘(-1, None, data)’，其中 `data' 是到目前为止
     接受到的字节（如果发生超时，则可能是空字节）。

     如果一个正则表达式以贪婪匹配结束（例如 ‘.*’），或者多个表达式可以匹
     配同一个输出，则结果是不确定的，可能取决于 I/O 计时。

 -- 方法: Telnet.set_option_negotiation_callback (callback)

     每次在输入流上读取 telnet 选项时，这个带有如下参数的 `callback' （
     如果设置了）会被调用： callback(telnet socket, command
     (DO/DONT/WILL/WONT), option)。telnetlib 之后不会再执行其它操作。


File: python.info,  Node: Telnet 示例,  Prev: Telnet 对象,  Up: telnetlib -- Telnet 客户端

5.21.19.2 Telnet 示例
.....................

一个简单的说明性典型用法例子:

     import getpass
     import telnetlib

     HOST = "localhost"
     user = input("Enter your remote account: ")
     password = getpass.getpass()

     tn = telnetlib.Telnet(HOST)

     tn.read_until(b"login: ")
     tn.write(user.encode('ascii') + b"\n")
     if password:
         tn.read_until(b"Password: ")
         tn.write(password.encode('ascii') + b"\n")

     tn.write(b"ls\n")
     tn.write(b"exit\n")

     print(tn.read_all().decode('ascii'))


File: python.info,  Node: uuid --- UUID objects according to RFC 4122,  Next: socketserver --- A framework for network servers,  Prev: telnetlib -- Telnet 客户端,  Up: 互联网协议和支持

5.21.20 ‘uuid’ — UUID objects according to `RFC 4122'
-----------------------------------------------------

`Source code:' Lib/uuid.py(1)

__________________________________________________________________

这个模块提供了不可变的 *note UUID: 261. 对象 (*note UUID: 261. 类) 和
*note uuid1(): 41b, *note uuid3(): 2e03, *note uuid4(): 2e04, *note
uuid5(): 2e05. 等函数用于生成 RFC 4122(2) 所定义的第 1, 3, 4 和 5 版
UUID。

If all you want is a unique ID, you should probably call *note uuid1():
41b. or *note uuid4(): 2e04.  Note that *note uuid1(): 41b. may
compromise privacy since it creates a UUID containing the computer’s
network address.  *note uuid4(): 2e04. creates a random UUID.

Depending on support from the underlying platform, *note uuid1(): 41b.
may or may not return a "safe" UUID. A safe UUID is one which is
generated using synchronization methods that ensure no two processes can
obtain the same UUID. All instances of *note UUID: 261. have an
‘is_safe’ attribute which relays any information about the UUID’s
safety, using this enumeration:

 -- 类: uuid.SafeUUID

     3.7 新版功能.

      -- 属性: safe

          The UUID was generated by the platform in a
          multiprocessing-safe way.

      -- 属性: unsafe

          The UUID was not generated in a multiprocessing-safe way.

      -- 属性: unknown

          The platform does not provide information on whether the UUID
          was generated safely or not.

 -- 类: uuid.UUID (hex=None, bytes=None, bytes_le=None, fields=None,
          int=None, version=None, *, is_safe=SafeUUID.unknown)

     Create a UUID from either a string of 32 hexadecimal digits, a
     string of 16 bytes in big-endian order as the `bytes' argument, a
     string of 16 bytes in little-endian order as the `bytes_le'
     argument, a tuple of six integers (32-bit `time_low', 16-bit
     `time_mid', 16-bit `time_hi_version', 8-bit `clock_seq_hi_variant',
     8-bit `clock_seq_low', 48-bit `node') as the `fields' argument, or
     a single 128-bit integer as the `int' argument.  When a string of
     hex digits is given, curly braces, hyphens, and a URN prefix are
     all optional.  For example, these expressions all yield the same
     UUID:

          UUID('{12345678-1234-5678-1234-567812345678}')
          UUID('12345678123456781234567812345678')
          UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
          UUID(bytes=b'\x12\x34\x56\x78'*4)
          UUID(bytes_le=b'\x78\x56\x34\x12\x34\x12\x78\x56' +
                        b'\x12\x34\x56\x78\x12\x34\x56\x78')
          UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
          UUID(int=0x12345678123456781234567812345678)

     Exactly one of `hex', `bytes', `bytes_le', `fields', or `int' must
     be given.  The `version' argument is optional; if given, the
     resulting UUID will have its variant and version number set
     according to RFC 4122(3), overriding bits in the given `hex',
     `bytes', `bytes_le', `fields', or `int'.

     Comparison of UUID objects are made by way of comparing their *note
     UUID.int: 2e0a. attributes.  Comparison with a non-UUID object
     raises a *note TypeError: 193.

     ‘str(uuid)’ returns a string in the form
     ‘12345678-1234-5678-1234-567812345678’ where the 32 hexadecimal
     digits represent the UUID.

*note UUID: 261. instances have these read-only attributes:

 -- 属性: UUID.bytes

     The UUID as a 16-byte string (containing the six integer fields in
     big-endian byte order).

 -- 属性: UUID.bytes_le

     The UUID as a 16-byte string (with `time_low', `time_mid', and
     `time_hi_version' in little-endian byte order).

 -- 属性: UUID.fields

     以元组形式存放的UUID的6个整数域，有六个单独的属性和两个派生属性：

     域                                 含义
                                        
     -----------------------------------------------------------------------
                                        
     ‘time_low’                         UUID的前32位
                                        
                                        
     ‘time_mid’                         接前一域的16位
                                        
                                        
     ‘time_hi_version’                  接前一域的16位
                                        
                                        
     ‘clock_seq_hi_variant’             接前一域的8位
                                        
                                        
     ‘clock_seq_low’                    接前一域的8位
                                        
                                        
     ‘node’                             UUID的最后48位
                                        
                                        
     *note time: 10b.                   UUID的总长60位的时间戳
                                        
                                        
     ‘clock_seq’                        14位的序列号
                                        

 -- 属性: UUID.hex

     The UUID as a 32-character hexadecimal string.

 -- 属性: UUID.int

     The UUID as a 128-bit integer.

 -- 属性: UUID.urn

     在 RFC 4122(4) 中定义的 URN 形式的 UUID。

 -- 属性: UUID.variant

     The UUID variant, which determines the internal layout of the UUID.
     This will be one of the constants *note RESERVED_NCS: 2e11, *note
     RFC_4122: 2e12, *note RESERVED_MICROSOFT: 2e13, or *note
     RESERVED_FUTURE: 2e14.

 -- 属性: UUID.version

     The UUID version number (1 through 5, meaningful only when the
     variant is *note RFC_4122: 2e12.).

 -- 属性: UUID.is_safe

     An enumeration of *note SafeUUID: 2e06. which indicates whether the
     platform generated the UUID in a multiprocessing-safe way.

     3.7 新版功能.

The *note uuid: 125. module defines the following functions:

 -- 函数: uuid.getnode ()

     Get the hardware address as a 48-bit positive integer.  The first
     time this runs, it may launch a separate program, which could be
     quite slow.  If all attempts to obtain the hardware address fail,
     we choose a random 48-bit number with the multicast bit (least
     significant bit of the first octet) set to 1 as recommended in RFC
     4122(5).  "Hardware address" means the MAC address of a network
     interface.  On a machine with multiple network interfaces,
     universally administered MAC addresses (i.e.  where the second
     least significant bit of the first octet is `unset') will be
     preferred over locally administered MAC addresses, but with no
     other ordering guarantees.

     在 3.7 版更改: Universally administered MAC addresses are preferred
     over locally administered MAC addresses, since the former are
     guaranteed to be globally unique, while the latter are not.

 -- 函数: uuid.uuid1 (node=None, clock_seq=None)

     Generate a UUID from a host ID, sequence number, and the current
     time.  If `node' is not given, *note getnode(): 41a. is used to
     obtain the hardware address.  If `clock_seq' is given, it is used
     as the sequence number; otherwise a random 14-bit sequence number
     is chosen.

 -- 函数: uuid.uuid3 (namespace, name)

     Generate a UUID based on the MD5 hash of a namespace identifier
     (which is a UUID) and a name (which is a string).

 -- 函数: uuid.uuid4 ()

     Generate a random UUID.

 -- 函数: uuid.uuid5 (namespace, name)

     Generate a UUID based on the SHA-1 hash of a namespace identifier
     (which is a UUID) and a name (which is a string).

The *note uuid: 125. module defines the following namespace identifiers
for use with *note uuid3(): 2e03. or *note uuid5(): 2e05.

 -- 数据: uuid.NAMESPACE_DNS

     When this namespace is specified, the `name' string is a
     fully-qualified domain name.

 -- 数据: uuid.NAMESPACE_URL

     When this namespace is specified, the `name' string is a URL.

 -- 数据: uuid.NAMESPACE_OID

     When this namespace is specified, the `name' string is an ISO OID.

 -- 数据: uuid.NAMESPACE_X500

     When this namespace is specified, the `name' string is an X.500 DN
     in DER or a text output format.

The *note uuid: 125. module defines the following constants for the
possible values of the ‘variant’ attribute:

 -- 数据: uuid.RESERVED_NCS

     Reserved for NCS compatibility.

 -- 数据: uuid.RFC_4122

     Specifies the UUID layout given in RFC 4122(6).

 -- 数据: uuid.RESERVED_MICROSOFT

     为微软的兼容性保留。

 -- 数据: uuid.RESERVED_FUTURE

     Reserved for future definition.

参见
....

RFC 4122(7) - A Universally Unique IDentifier (UUID) URN Namespace

     This specification defines a Uniform Resource Name namespace for
     UUIDs, the internal format of UUIDs, and methods of generating
     UUIDs.

* Menu:

* 示例: 示例<13>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/uuid.py

   (2) https://tools.ietf.org/html/rfc4122.html

   (3) https://tools.ietf.org/html/rfc4122.html

   (4) https://tools.ietf.org/html/rfc4122.html

   (5) https://tools.ietf.org/html/rfc4122.html

   (6) https://tools.ietf.org/html/rfc4122.html

   (7) https://tools.ietf.org/html/rfc4122.html


File: python.info,  Node: 示例<13>,  Up: uuid --- UUID objects according to RFC 4122

5.21.20.1 示例
..............

Here are some examples of typical usage of the *note uuid: 125. module:

     >>> import uuid

     >>> # make a UUID based on the host ID and current time
     >>> uuid.uuid1()
     UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

     >>> # make a UUID using an MD5 hash of a namespace UUID and a name
     >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
     UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

     >>> # make a random UUID
     >>> uuid.uuid4()
     UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

     >>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
     >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
     UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

     >>> # make a UUID from a string of hex digits (braces and hyphens ignored)
     >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')

     >>> # convert a UUID to a string of hex digits in standard form
     >>> str(x)
     '00010203-0405-0607-0809-0a0b0c0d0e0f'

     >>> # get the raw 16 bytes of the UUID
     >>> x.bytes
     b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'

     >>> # make a UUID from a 16-byte string
     >>> uuid.UUID(bytes=x.bytes)
     UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')


File: python.info,  Node: socketserver --- A framework for network servers,  Next: http server --- HTTP 服务器,  Prev: uuid --- UUID objects according to RFC 4122,  Up: 互联网协议和支持

5.21.21 ‘socketserver’ — A framework for network servers
--------------------------------------------------------

`Source code:' Lib/socketserver.py(1)

__________________________________________________________________

The *note socketserver: f1. module simplifies the task of writing
network servers.

There are four basic concrete server classes:

 -- 类: socketserver.TCPServer (server_address, RequestHandlerClass,
          bind_and_activate=True)

     This uses the Internet TCP protocol, which provides for continuous
     streams of data between the client and server.  If
     `bind_and_activate' is true, the constructor automatically attempts
     to invoke *note server_bind(): 2e1f. and *note server_activate():
     2e20.  The other parameters are passed to the *note BaseServer:
     a91. base class.

 -- 类: socketserver.UDPServer (server_address, RequestHandlerClass,
          bind_and_activate=True)

     This uses datagrams, which are discrete packets of information that
     may arrive out of order or be lost while in transit.  The
     parameters are the same as for *note TCPServer: 2e1e.

 -- 类: socketserver.UnixStreamServer (server_address,
          RequestHandlerClass, bind_and_activate=True)
 -- 类: socketserver.UnixDatagramServer (server_address,
          RequestHandlerClass, bind_and_activate=True)

     These more infrequently used classes are similar to the TCP and UDP
     classes, but use Unix domain sockets; they’re not available on
     non-Unix platforms.  The parameters are the same as for *note
     TCPServer: 2e1e.

These four classes process requests `synchronously'; each request must
be completed before the next request can be started.  This isn’t
suitable if each request takes a long time to complete, because it
requires a lot of computation, or because it returns a lot of data which
the client is slow to process.  The solution is to create a separate
process or thread to handle each request; the *note ForkingMixIn: 3dd.
and *note ThreadingMixIn: 3de. mix-in classes can be used to support
asynchronous behaviour.

Creating a server requires several steps.  First, you must create a
request handler class by subclassing the *note BaseRequestHandler: 2e24.
class and overriding its *note handle(): 2e25. method; this method will
process incoming requests.  Second, you must instantiate one of the
server classes, passing it the server’s address and the request handler
class.  It is recommended to use the server in a *note with: 6f2.
statement.  Then call the *note handle_request(): 2e26. or *note
serve_forever(): a93. method of the server object to process one or many
requests.  Finally, call *note server_close(): 2e27. to close the socket
(unless you used a ‘with’ statement).

When inheriting from *note ThreadingMixIn: 3de. for threaded connection
behavior, you should explicitly declare how you want your threads to
behave on an abrupt shutdown.  The *note ThreadingMixIn: 3de. class
defines an attribute `daemon_threads', which indicates whether or not
the server should wait for thread termination.  You should set the flag
explicitly if you would like threads to behave autonomously; the default
is *note False: 390, meaning that Python will not exit until all threads
created by *note ThreadingMixIn: 3de. have exited.

Server classes have the same external methods and attributes, no matter
what network protocol they use.

* Menu:

* Server Creation Notes::
* Server 对象: Server 对象<2>.
* Request Handler Objects::
* 例子: 例子<23>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/socketserver.py


File: python.info,  Node: Server Creation Notes,  Next: Server 对象<2>,  Up: socketserver --- A framework for network servers

5.21.21.1 Server Creation Notes
...............................

There are five classes in an inheritance diagram, four of which
represent synchronous servers of four types:

     +------------+
     | BaseServer |
     +------------+
           |
           v
     +-----------+        +------------------+
     | TCPServer |------->| UnixStreamServer |
     +-----------+        +------------------+
           |
           v
     +-----------+        +--------------------+
     | UDPServer |------->| UnixDatagramServer |
     +-----------+        +--------------------+

Note that *note UnixDatagramServer: 2e23. derives from *note UDPServer:
2e21, not from *note UnixStreamServer: 2e22. — the only difference
between an IP and a Unix stream server is the address family, which is
simply repeated in both Unix server classes.

 -- 类: socketserver.ForkingMixIn
 -- 类: socketserver.ThreadingMixIn

     Forking and threading versions of each type of server can be
     created using these mix-in classes.  For instance, *note
     ThreadingUDPServer: 2e29. is created as follows:

          class ThreadingUDPServer(ThreadingMixIn, UDPServer):
              pass

     The mix-in class comes first, since it overrides a method defined
     in *note UDPServer: 2e21.  Setting the various attributes also
     changes the behavior of the underlying server mechanism.

     *note ForkingMixIn: 3dd. and the Forking classes mentioned below
     are only available on POSIX platforms that support *note fork():
     969.

     ‘socketserver.ForkingMixIn.server_close()’ waits until all child
     processes complete, except if
     ‘socketserver.ForkingMixIn.block_on_close’ attribute is false.

     ‘socketserver.ThreadingMixIn.server_close()’ waits until all
     non-daemon threads complete, except if
     ‘socketserver.ThreadingMixIn.block_on_close’ attribute is false.
     Use daemonic threads by setting ‘ThreadingMixIn.daemon_threads’ to
     ‘True’ to not wait until threads complete.

     在 3.7 版更改: ‘socketserver.ForkingMixIn.server_close()’ and
     ‘socketserver.ThreadingMixIn.server_close()’ now waits until all
     child processes and non-daemonic threads complete.  Add a new
     ‘socketserver.ForkingMixIn.block_on_close’ class attribute to
     opt-in for the pre-3.7 behaviour.

 -- 类: socketserver.ForkingTCPServer
 -- 类: socketserver.ForkingUDPServer
 -- 类: socketserver.ThreadingTCPServer
 -- 类: socketserver.ThreadingUDPServer

     These classes are pre-defined using the mix-in classes.

To implement a service, you must derive a class from *note
BaseRequestHandler: 2e24. and redefine its *note handle(): 2e25. method.
You can then run various versions of the service by combining one of the
server classes with your request handler class.  The request handler
class must be different for datagram or stream services.  This can be
hidden by using the handler subclasses *note StreamRequestHandler: 590.
or *note DatagramRequestHandler: 2e2d.

Of course, you still have to use your head!  For instance, it makes no
sense to use a forking server if the service contains state in memory
that can be modified by different requests, since the modifications in
the child process would never reach the initial state kept in the parent
process and passed to each child.  In this case, you can use a threading
server, but you will probably have to use locks to protect the integrity
of the shared data.

On the other hand, if you are building an HTTP server where all data is
stored externally (for instance, in the file system), a synchronous
class will essentially render the service "deaf" while one request is
being handled – which may be for a very long time if a client is slow to
receive all the data it has requested.  Here a threading or forking
server is appropriate.

In some cases, it may be appropriate to process part of a request
synchronously, but to finish processing in a forked child depending on
the request data.  This can be implemented by using a synchronous server
and doing an explicit fork in the request handler class *note handle():
2e25. method.

Another approach to handling multiple simultaneous requests in an
environment that supports neither threads nor *note fork(): 969. (or
where these are too expensive or inappropriate for the service) is to
maintain an explicit table of partially finished requests and to use
*note selectors: e7. to decide which request to work on next (or whether
to handle a new incoming request).  This is particularly important for
stream services where each client can potentially be connected for a
long time (if threads or subprocesses cannot be used).  See *note
asyncore: b. for another way to manage this.


File: python.info,  Node: Server 对象<2>,  Next: Request Handler Objects,  Prev: Server Creation Notes,  Up: socketserver --- A framework for network servers

5.21.21.2 Server 对象
.....................

 -- 类: socketserver.BaseServer (server_address, RequestHandlerClass)

     This is the superclass of all Server objects in the module.  It
     defines the interface, given below, but does not implement most of
     the methods, which is done in subclasses.  The two parameters are
     stored in the respective *note server_address: 2e2f. and *note
     RequestHandlerClass: 2e30. attributes.

      -- 方法: fileno ()

          Return an integer file descriptor for the socket on which the
          server is listening.  This function is most commonly passed to
          *note selectors: e7, to allow monitoring multiple servers in
          the same process.

      -- 方法: handle_request ()

          Process a single request.  This function calls the following
          methods in order: *note get_request(): 2e32, *note
          verify_request(): 2e33, and *note process_request(): 2e34.  If
          the user-provided *note handle(): 2e25. method of the handler
          class raises an exception, the server’s *note handle_error():
          606. method will be called.  If no request is received within
          *note timeout: 2e35. seconds, *note handle_timeout(): 2e36.
          will be called and *note handle_request(): 2e26. will return.

      -- 方法: serve_forever (poll_interval=0.5)

          Handle requests until an explicit *note shutdown(): 102d.
          request.  Poll for shutdown every `poll_interval' seconds.
          Ignores the *note timeout: 2e35. attribute.  It also calls
          *note service_actions(): a92, which may be used by a subclass
          or mixin to provide actions specific to a given service.  For
          example, the *note ForkingMixIn: 3dd. class uses *note
          service_actions(): a92. to clean up zombie child processes.

          在 3.3 版更改: Added ‘service_actions’ call to the
          ‘serve_forever’ method.

      -- 方法: service_actions ()

          This is called in the *note serve_forever(): a93. loop.  This
          method can be overridden by subclasses or mixin classes to
          perform actions specific to a given service, such as cleanup
          actions.

          3.3 新版功能.

      -- 方法: shutdown ()

          Tell the *note serve_forever(): a93. loop to stop and wait
          until it does.  *note shutdown(): 102d. must be called while
          *note serve_forever(): a93. is running in a different thread
          otherwise it will deadlock.

      -- 方法: server_close ()

          Clean up the server.  May be overridden.

      -- 属性: address_family

          The family of protocols to which the server’s socket belongs.
          Common examples are *note socket.AF_INET: 25b8. and *note
          socket.AF_UNIX: 25be.

      -- 属性: RequestHandlerClass

          The user-provided request handler class; an instance of this
          class is created for each request.

      -- 属性: server_address

          The address on which the server is listening.  The format of
          addresses varies depending on the protocol family; see the
          documentation for the *note socket: f0. module for details.
          For Internet protocols, this is a tuple containing a string
          giving the address, and an integer port number: ‘('127.0.0.1',
          80)’, for example.

      -- 属性: socket

          The socket object on which the server will listen for incoming
          requests.

     The server classes support the following class variables:

      -- 属性: allow_reuse_address

          Whether the server will allow the reuse of an address.  This
          defaults to *note False: 390, and can be set in subclasses to
          change the policy.

      -- 属性: request_queue_size

          The size of the request queue.  If it takes a long time to
          process a single request, any requests that arrive while the
          server is busy are placed into a queue, up to *note
          request_queue_size: 2e3a. requests.  Once the queue is full,
          further requests from clients will get a "Connection denied"
          error.  The default value is usually 5, but this can be
          overridden by subclasses.

      -- 属性: socket_type

          The type of socket used by the server; *note
          socket.SOCK_STREAM: c92. and *note socket.SOCK_DGRAM: c91. are
          two common values.

      -- 属性: timeout

          Timeout duration, measured in seconds, or *note None: 158. if
          no timeout is desired.  If *note handle_request(): 2e26.
          receives no incoming requests within the timeout period, the
          *note handle_timeout(): 2e36. method is called.

     There are various server methods that can be overridden by
     subclasses of base server classes like *note TCPServer: 2e1e.;
     these methods aren’t useful to external users of the server object.

      -- 方法: finish_request (request, client_address)

          Actually processes the request by instantiating *note
          RequestHandlerClass: 2e30. and calling its *note handle():
          2e25. method.

      -- 方法: get_request ()

          Must accept a request from the socket, and return a 2-tuple
          containing the `new' socket object to be used to communicate
          with the client, and the client’s address.

      -- 方法: handle_error (request, client_address)

          This function is called if the *note handle(): 2e25. method of
          a *note RequestHandlerClass: 2e30. instance raises an
          exception.  The default action is to print the traceback to
          standard error and continue handling further requests.

          在 3.6 版更改: Now only called for exceptions derived from the
          *note Exception: 1aa. class.

      -- 方法: handle_timeout ()

          This function is called when the *note timeout: 2e35.
          attribute has been set to a value other than *note None: 158.
          and the timeout period has passed with no requests being
          received.  The default action for forking servers is to
          collect the status of any child processes that have exited,
          while in threading servers this method does nothing.

      -- 方法: process_request (request, client_address)

          Calls *note finish_request(): 2e3c. to create an instance of
          the *note RequestHandlerClass: 2e30.  If desired, this
          function can create a new process or thread to handle the
          request; the *note ForkingMixIn: 3dd. and *note
          ThreadingMixIn: 3de. classes do this.

      -- 方法: server_activate ()

          Called by the server’s constructor to activate the server.
          The default behavior for a TCP server just invokes *note
          listen(): 754. on the server’s socket.  May be overridden.

      -- 方法: server_bind ()

          Called by the server’s constructor to bind the socket to the
          desired address.  May be overridden.

      -- 方法: verify_request (request, client_address)

          Must return a Boolean value; if the value is *note True: 4a1,
          the request will be processed, and if it’s *note False: 390,
          the request will be denied.  This function can be overridden
          to implement access controls for a server.  The default
          implementation always returns *note True: 4a1.

     在 3.6 版更改: Support for the *note context manager: 571. protocol
     was added.  Exiting the context manager is equivalent to calling
     *note server_close(): 2e27.


File: python.info,  Node: Request Handler Objects,  Next: 例子<23>,  Prev: Server 对象<2>,  Up: socketserver --- A framework for network servers

5.21.21.3 Request Handler Objects
.................................

 -- 类: socketserver.BaseRequestHandler

     This is the superclass of all request handler objects.  It defines
     the interface, given below.  A concrete request handler subclass
     must define a new *note handle(): 2e25. method, and can override
     any of the other methods.  A new instance of the subclass is
     created for each request.

      -- 方法: setup ()

          Called before the *note handle(): 2e25. method to perform any
          initialization actions required.  The default implementation
          does nothing.

      -- 方法: handle ()

          This function must do all the work required to service a
          request.  The default implementation does nothing.  Several
          instance attributes are available to it; the request is
          available as ‘self.request’; the client address as
          ‘self.client_address’; and the server instance as
          ‘self.server’, in case it needs access to per-server
          information.

          The type of ‘self.request’ is different for datagram or stream
          services.  For stream services, ‘self.request’ is a socket
          object; for datagram services, ‘self.request’ is a pair of
          string and socket.

      -- 方法: finish ()

          Called after the *note handle(): 2e25. method to perform any
          clean-up actions required.  The default implementation does
          nothing.  If *note setup(): 2e3e. raises an exception, this
          function will not be called.

 -- 类: socketserver.StreamRequestHandler
 -- 类: socketserver.DatagramRequestHandler

     These *note BaseRequestHandler: 2e24. subclasses override the *note
     setup(): 2e3e. and *note finish(): 2e3f. methods, and provide
     ‘self.rfile’ and ‘self.wfile’ attributes.  The ‘self.rfile’ and
     ‘self.wfile’ attributes can be read or written, respectively, to
     get the request data or return data to the client.

     The ‘rfile’ attributes of both classes support the *note
     io.BufferedIOBase: 591. readable interface, and
     ‘DatagramRequestHandler.wfile’ supports the *note
     io.BufferedIOBase: 591. writable interface.

     在 3.6 版更改: ‘StreamRequestHandler.wfile’ also supports the *note
     io.BufferedIOBase: 591. writable interface.


File: python.info,  Node: 例子<23>,  Prev: Request Handler Objects,  Up: socketserver --- A framework for network servers

5.21.21.4 例子
..............

* Menu:

* socketserver.TCPServer Example: socketserver TCPServer Example.
* socketserver.UDPServer Example: socketserver UDPServer Example.
* Asynchronous Mixins::


File: python.info,  Node: socketserver TCPServer Example,  Next: socketserver UDPServer Example,  Up: 例子<23>

5.21.21.5 ‘socketserver.TCPServer’ Example
..........................................

This is the server side:

     import socketserver

     class MyTCPHandler(socketserver.BaseRequestHandler):
         """
         The request handler class for our server.

         It is instantiated once per connection to the server, and must
         override the handle() method to implement communication to the
         client.
         """

         def handle(self):
             # self.request is the TCP socket connected to the client
             self.data = self.request.recv(1024).strip()
             print("{} wrote:".format(self.client_address[0]))
             print(self.data)
             # just send back the same data, but upper-cased
             self.request.sendall(self.data.upper())

     if __name__ == "__main__":
         HOST, PORT = "localhost", 9999

         # Create the server, binding to localhost on port 9999
         with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
             # Activate the server; this will keep running until you
             # interrupt the program with Ctrl-C
             server.serve_forever()

An alternative request handler class that makes use of streams
(file-like objects that simplify communication by providing the standard
file interface):

     class MyTCPHandler(socketserver.StreamRequestHandler):

         def handle(self):
             # self.rfile is a file-like object created by the handler;
             # we can now use e.g. readline() instead of raw recv() calls
             self.data = self.rfile.readline().strip()
             print("{} wrote:".format(self.client_address[0]))
             print(self.data)
             # Likewise, self.wfile is a file-like object used to write back
             # to the client
             self.wfile.write(self.data.upper())

The difference is that the ‘readline()’ call in the second handler will
call ‘recv()’ multiple times until it encounters a newline character,
while the single ‘recv()’ call in the first handler will just return
what has been sent from the client in one ‘sendall()’ call.

This is the client side:

     import socket
     import sys

     HOST, PORT = "localhost", 9999
     data = " ".join(sys.argv[1:])

     # Create a socket (SOCK_STREAM means a TCP socket)
     with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
         # Connect to server and send data
         sock.connect((HOST, PORT))
         sock.sendall(bytes(data + "\n", "utf-8"))

         # Receive data from the server and shut down
         received = str(sock.recv(1024), "utf-8")

     print("Sent:     {}".format(data))
     print("Received: {}".format(received))

The output of the example should look something like this:

Server:

     $ python TCPServer.py
     127.0.0.1 wrote:
     b'hello world with TCP'
     127.0.0.1 wrote:
     b'python is nice'

Client:

     $ python TCPClient.py hello world with TCP
     Sent:     hello world with TCP
     Received: HELLO WORLD WITH TCP
     $ python TCPClient.py python is nice
     Sent:     python is nice
     Received: PYTHON IS NICE


File: python.info,  Node: socketserver UDPServer Example,  Next: Asynchronous Mixins,  Prev: socketserver TCPServer Example,  Up: 例子<23>

5.21.21.6 ‘socketserver.UDPServer’ Example
..........................................

This is the server side:

     import socketserver

     class MyUDPHandler(socketserver.BaseRequestHandler):
         """
         This class works similar to the TCP handler class, except that
         self.request consists of a pair of data and client socket, and since
         there is no connection the client address must be given explicitly
         when sending data back via sendto().
         """

         def handle(self):
             data = self.request[0].strip()
             socket = self.request[1]
             print("{} wrote:".format(self.client_address[0]))
             print(data)
             socket.sendto(data.upper(), self.client_address)

     if __name__ == "__main__":
         HOST, PORT = "localhost", 9999
         with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:
             server.serve_forever()

This is the client side:

     import socket
     import sys

     HOST, PORT = "localhost", 9999
     data = " ".join(sys.argv[1:])

     # SOCK_DGRAM is the socket type to use for UDP sockets
     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

     # As you can see, there is no connect() call; UDP has no connections.
     # Instead, data is directly sent to the recipient via sendto().
     sock.sendto(bytes(data + "\n", "utf-8"), (HOST, PORT))
     received = str(sock.recv(1024), "utf-8")

     print("Sent:     {}".format(data))
     print("Received: {}".format(received))

The output of the example should look exactly like for the TCP server
example.


File: python.info,  Node: Asynchronous Mixins,  Prev: socketserver UDPServer Example,  Up: 例子<23>

5.21.21.7 Asynchronous Mixins
.............................

To build asynchronous handlers, use the *note ThreadingMixIn: 3de. and
*note ForkingMixIn: 3dd. classes.

An example for the *note ThreadingMixIn: 3de. class:

     import socket
     import threading
     import socketserver

     class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):

         def handle(self):
             data = str(self.request.recv(1024), 'ascii')
             cur_thread = threading.current_thread()
             response = bytes("{}: {}".format(cur_thread.name, data), 'ascii')
             self.request.sendall(response)

     class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
         pass

     def client(ip, port, message):
         with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
             sock.connect((ip, port))
             sock.sendall(bytes(message, 'ascii'))
             response = str(sock.recv(1024), 'ascii')
             print("Received: {}".format(response))

     if __name__ == "__main__":
         # Port 0 means to select an arbitrary unused port
         HOST, PORT = "localhost", 0

         server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
         with server:
             ip, port = server.server_address

             # Start a thread with the server -- that thread will then start one
             # more thread for each request
             server_thread = threading.Thread(target=server.serve_forever)
             # Exit the server thread when the main thread terminates
             server_thread.daemon = True
             server_thread.start()
             print("Server loop running in thread:", server_thread.name)

             client(ip, port, "Hello World 1")
             client(ip, port, "Hello World 2")
             client(ip, port, "Hello World 3")

             server.shutdown()

The output of the example should look something like this:

     $ python ThreadedTCPServer.py
     Server loop running in thread: Thread-1
     Received: Thread-2: Hello World 1
     Received: Thread-3: Hello World 2
     Received: Thread-4: Hello World 3

The *note ForkingMixIn: 3dd. class is used in the same way, except that
the server will spawn a new process for each request.  Available only on
POSIX platforms that support *note fork(): 969.


File: python.info,  Node: http server --- HTTP 服务器,  Next: http cookies --- HTTP状态管理,  Prev: socketserver --- A framework for network servers,  Up: 互联网协议和支持

5.21.22 ‘http.server’ — HTTP 服务器
-----------------------------------

`源代码：' Lib/http/server.py(1)

__________________________________________________________________

这个模块定义了实现 HTTP 服务器（ Web 服务器）的类。

     警告: 不推荐在生产环境中使用 *note http.server: 97. 。它只实现了基
     本的安全检查功能。

*note HTTPServer: 2c15. 是 *note socketserver.TCPServer: 2e1e. 的一个子
类。它会创建和侦听 HTTP 套接字，并将请求调度给处理程序。用于创建和运行服
务器的代码看起来像这样：

     def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
         server_address = ('', 8000)
         httpd = server_class(server_address, handler_class)
         httpd.serve_forever()

 -- 类: http.server.HTTPServer (server_address, RequestHandlerClass)

     该类基于 *note TCPServer: 2e1e. 类，并会将服务器地址存入名为
     ‘server_name’ 和 ‘server_port’ 的实例变量中。服务器可被处理程序通过
     ‘server’ 实例变量访问。

 -- 类: http.server.ThreadingHTTPServer (server_address,
          RequestHandlerClass)

     这个类与 HTTPServer 相似，但会通过使用 *note ThreadingMixIn: 3de. 来
     以线程处理请求。 这适用于处理 Web 浏览器预开启套接字，以便 *note
     HTTPServer: 2c15. 无限期地执行等待。

     3.7 新版功能.

*note HTTPServer: 2c15. 和 *note ThreadingHTTPServer: 39e. 必须在实例化
时给定一个 `RequestHandlerClass'，此模块提供了该对象的三种不同形式:

 -- 类: http.server.BaseHTTPRequestHandler (request, client_address,
          server)

     这个类用于处理到达服务器的 HTTP 请求。 它本身无法响应任何实际的
     HTTP 请求；它必须被子类化以处理每个请求方法（例如 GET 或 POST）。
     *note BaseHTTPRequestHandler: a16. 提供了许多供子类使用的类和实例变
     量以及方法。

     这个处理程序将解析请求和标头，然后调用特定请求类型对应的方法。 方法
     名称将根据请求来构造。 例如，对于请求方法 ‘SPAM’，将不带参数地调用
     ‘do_SPAM()’ 方法。 所有相关信息会被保存在该处理程序的实际变量中。 子
     类不需要重载或扩展 *note __init__(): d66. 方法。

     *note BaseHTTPRequestHandler: a16. 具有下列实例变量:

      -- 属性: client_address

          包含 ‘(host, port)’ 形式的指向客户端地址的元组。

      -- 属性: server

          包含服务器实例。

      -- 属性: close_connection

          应当在 *note handle_one_request(): 2e49. 返回之前设定的布尔值
          ，指明是否要期待另一个请求，还是应当关闭连接。

      -- 属性: requestline

          包含 HTTP 请求行的字符串表示。 末尾的 CRLF 会被去除。 该属性应
          当由 *note handle_one_request(): 2e49. 来设定。 如果无有效请求
          行被处理，则它应当被设为空字符串。

      -- 属性: command

          包含具体的命令（请求类型）。 例如 ‘'GET'’。

      -- 属性: path

          Contains the request path.  If query component of the URL is
          present, then ‘path’ includes the query.  Using the
          terminology of RFC 3986(2), ‘path’ here includes ‘hier-part’
          and the ‘query’.

      -- 属性: request_version

          包含请求的版本字符串。 例如 ‘'HTTP/1.0'’。

      -- 属性: headers

          Holds an instance of the class specified by the *note
          MessageClass: 2e4e. class variable.  This instance parses and
          manages the headers in the HTTP request.  The *note
          parse_headers(): 1050. function from *note http.client: 94. is
          used to parse the headers and it requires that the HTTP
          request provide a valid RFC 2822(3) style header.

      -- 属性: rfile

          An *note io.BufferedIOBase: 591. input stream, ready to read
          from the start of the optional input data.

      -- 属性: wfile

          Contains the output stream for writing a response back to the
          client.  Proper adherence to the HTTP protocol must be used
          when writing to this stream in order to achieve successful
          interoperation with HTTP clients.

          在 3.6 版更改: This is an *note io.BufferedIOBase: 591.
          stream.

     *note BaseHTTPRequestHandler: a16. has the following attributes:

      -- 属性: server_version

          Specifies the server software version.  You may want to
          override this.  The format is multiple whitespace-separated
          strings, where each string is of the form name[/version].  For
          example, ‘'BaseHTTP/0.2'’.

      -- 属性: sys_version

          Contains the Python system version, in a form usable by the
          *note version_string: 2e53. method and the *note
          server_version: 2e51. class variable.  For example,
          ‘'Python/1.4'’.

      -- 属性: error_message_format

          Specifies a format string that should be used by *note
          send_error(): 865. method for building an error response to
          the client.  The string is filled by default with variables
          from *note responses: 2ce0. based on the status code that
          passed to *note send_error(): 865.

      -- 属性: error_content_type

          Specifies the Content-Type HTTP header of error responses sent
          to the client.  The default value is ‘'text/html'’.

      -- 属性: protocol_version

          This specifies the HTTP protocol version used in responses.
          If set to ‘'HTTP/1.1'’, the server will permit HTTP persistent
          connections; however, your server `must' then include an
          accurate ‘Content-Length’ header (using *note send_header():
          2e57.) in all of its responses to clients.  For backwards
          compatibility, the setting defaults to ‘'HTTP/1.0'’.

      -- 属性: MessageClass

          Specifies an *note email.message.Message: 54a.-like class to
          parse HTTP headers.  Typically, this is not overridden, and it
          defaults to ‘http.client.HTTPMessage’.

      -- 属性: responses

          This attribute contains a mapping of error code integers to
          two-element tuples containing a short and long message.  For
          example, ‘{code: (shortmessage, longmessage)}’.  The
          `shortmessage' is usually used as the `message' key in an
          error response, and `longmessage' as the `explain' key.  It is
          used by *note send_response_only(): 2e58. and *note
          send_error(): 865. methods.

     A *note BaseHTTPRequestHandler: a16. instance has the following
     methods:

      -- 方法: handle ()

          Calls *note handle_one_request(): 2e49. once (or, if
          persistent connections are enabled, multiple times) to handle
          incoming HTTP requests.  You should never need to override it;
          instead, implement appropriate ‘do_*()’ methods.

      -- 方法: handle_one_request ()

          This method will parse and dispatch the request to the
          appropriate ‘do_*()’ method.  You should never need to
          override it.

      -- 方法: handle_expect_100 ()

          When a HTTP/1.1 compliant server receives an ‘Expect:
          100-continue’ request header it responds back with a ‘100
          Continue’ followed by ‘200 OK’ headers.  This method can be
          overridden to raise an error if the server does not want the
          client to continue.  For e.g.  server can chose to send ‘417
          Expectation Failed’ as a response header and ‘return False’.

          3.2 新版功能.

      -- 方法: send_error (code, message=None, explain=None)

          Sends and logs a complete error reply to the client.  The
          numeric `code' specifies the HTTP error code, with `message'
          as an optional, short, human readable description of the
          error.  The `explain' argument can be used to provide more
          detailed information about the error; it will be formatted
          using the *note error_message_format: 2e54. attribute and
          emitted, after a complete set of headers, as the response
          body.  The *note responses: 2ce0. attribute holds the default
          values for `message' and `explain' that will be used if no
          value is provided; for unknown codes the default value for
          both is the string ‘???’.  The body will be empty if the
          method is HEAD or the response code is one of the following:
          ‘1xx’, ‘204 No Content’, ‘205 Reset Content’, ‘304 Not
          Modified’.

          在 3.4 版更改: The error response includes a Content-Length
          header.  Added the `explain' argument.

      -- 方法: send_response (code, message=None)

          Adds a response header to the headers buffer and logs the
          accepted request.  The HTTP response line is written to the
          internal buffer, followed by `Server' and `Date' headers.  The
          values for these two headers are picked up from the *note
          version_string(): 2e53. and *note date_time_string(): 2e5c.
          methods, respectively.  If the server does not intend to send
          any other headers using the *note send_header(): 2e57. method,
          then *note send_response(): 2e5b. should be followed by an
          *note end_headers(): a17. call.

          在 3.3 版更改: Headers are stored to an internal buffer and
          *note end_headers(): a17. needs to be called explicitly.

      -- 方法: send_header (keyword, value)

          Adds the HTTP header to an internal buffer which will be
          written to the output stream when either *note end_headers():
          a17. or *note flush_headers(): a18. is invoked.  `keyword'
          should specify the header keyword, with `value' specifying its
          value.  Note that, after the send_header calls are done, *note
          end_headers(): a17. MUST BE called in order to complete the
          operation.

          在 3.2 版更改: Headers are stored in an internal buffer.

      -- 方法: send_response_only (code, message=None)

          Sends the response header only, used for the purposes when
          ‘100 Continue’ response is sent by the server to the client.
          The headers not buffered and sent directly the output
          stream.If the `message' is not specified, the HTTP message
          corresponding the response `code' is sent.

          3.2 新版功能.

      -- 方法: end_headers ()

          Adds a blank line (indicating the end of the HTTP headers in
          the response) to the headers buffer and calls *note
          flush_headers(): a18.

          在 3.2 版更改: The buffered headers are written to the output
          stream.

      -- 方法: flush_headers ()

          Finally send the headers to the output stream and flush the
          internal headers buffer.

          3.3 新版功能.

      -- 方法: log_request (code='-', size='-')

          Logs an accepted (successful) request.  `code' should specify
          the numeric HTTP code associated with the response.  If a size
          of the response is available, then it should be passed as the
          `size' parameter.

      -- 方法: log_error (...)

          Logs an error when a request cannot be fulfilled.  By default,
          it passes the message to *note log_message(): 2e5f, so it
          takes the same arguments (`format' and additional values).

      -- 方法: log_message (format, ...)

          Logs an arbitrary message to ‘sys.stderr’.  This is typically
          overridden to create custom error logging mechanisms.  The
          `format' argument is a standard printf-style format string,
          where the additional arguments to *note log_message(): 2e5f.
          are applied as inputs to the formatting.  The client ip
          address and current date and time are prefixed to every
          message logged.

      -- 方法: version_string ()

          Returns the server software’s version string.  This is a
          combination of the *note server_version: 2e51. and *note
          sys_version: 2e52. attributes.

      -- 方法: date_time_string (timestamp=None)

          Returns the date and time given by `timestamp' (which must be
          ‘None’ or in the format returned by *note time.time(): 326.),
          formatted for a message header.  If `timestamp' is omitted, it
          uses the current date and time.

          结果看起来像 ‘'Sun, 06 Nov 1994 08:49:37 GMT'’。

      -- 方法: log_date_time_string ()

          返回当前的日期和时间，为日志格式化

      -- 方法: address_string ()

          返回客户端的地址

          在 3.3 版更改: Previously, a name lookup was performed.  To
          avoid name resolution delays, it now always returns the IP
          address.

 -- 类: http.server.SimpleHTTPRequestHandler (request, client_address,
          server, directory=None)

     这个类为当前目录及以下的文件提供服务，直接映射目录结构到HTTP请求

     A lot of the work, such as parsing the request, is done by the base
     class *note BaseHTTPRequestHandler: a16.  This class implements the
     *note do_GET(): 2e62. and *note do_HEAD(): 2e63. functions.

     The following are defined as class-level attributes of *note
     SimpleHTTPRequestHandler: 39d.:

      -- 属性: server_version

          This will be ‘"SimpleHTTP/" + __version__’, where
          ‘__version__’ is defined at the module level.

      -- 属性: extensions_map

          A dictionary mapping suffixes into MIME types.  The default is
          signified by an empty string, and is considered to be
          ‘application/octet-stream’.  The mapping is used
          case-insensitively, and so should contain only lower-cased
          keys.

      -- 属性: directory

          如果没有指定，要服务 目录是当前工作目录

     The *note SimpleHTTPRequestHandler: 39d. class defines the
     following methods:

      -- 方法: do_HEAD ()

          This method serves the ‘'HEAD'’ request type: it sends the
          headers it would send for the equivalent ‘GET’ request.  See
          the *note do_GET(): 2e62. method for a more complete
          explanation of the possible headers.

      -- 方法: do_GET ()

          这一请求通过把其解释为当前工作目录的相对路径来映射到本地文件

          If the request was mapped to a directory, the directory is
          checked for a file named ‘index.html’ or ‘index.htm’ (in that
          order).  If found, the file’s contents are returned; otherwise
          a directory listing is generated by calling the
          ‘list_directory()’ method.  This method uses *note
          os.listdir(): a49. to scan the directory, and returns a ‘404’
          error response if the *note listdir(): a49. fails.

          If the request was mapped to a file, it is opened.  Any *note
          OSError: 1d4. exception in opening the requested file is
          mapped to a ‘404’, ‘'File not found'’ error.  If there was a
          ‘'If-Modified-Since'’ header in the request, and the file was
          not modified after this time, a ‘304’, ‘'Not Modified'’
          response is sent.  Otherwise, the content type is guessed by
          calling the ‘guess_type()’ method, which in turn uses the
          `extensions_map' variable, and the file contents are returned.

          A ‘'Content-type:'’ header with the guessed content type is
          output, followed by a ‘'Content-Length:'’ header with the
          file’s size and a ‘'Last-Modified:'’ header with the file’s
          modification time.

          Then follows a blank line signifying the end of the headers,
          and then the contents of the file are output.  If the file’s
          MIME type starts with ‘text/’ the file is opened in text mode;
          otherwise binary mode is used.

          For example usage, see the implementation of the *note test():
          106. function invocation in the *note http.server: 97. module.

          在 3.7 版更改: Support of the ‘'If-Modified-Since'’ header.

The *note SimpleHTTPRequestHandler: 39d. class can be used in the
following manner in order to create a very basic webserver serving files
relative to the current directory:

     import http.server
     import socketserver

     PORT = 8000

     Handler = http.server.SimpleHTTPRequestHandler

     with socketserver.TCPServer(("", PORT), Handler) as httpd:
         print("serving at port", PORT)
         httpd.serve_forever()
*note http.server: 97. can also be invoked directly using the *note -m:
340. switch of the interpreter with a ‘port number’ argument.  Similar
to the previous example, this serves files relative to the current
directory:

     python -m http.server 8000

By default, server binds itself to all interfaces.  The option
‘-b/--bind’ specifies a specific address to which it should bind.  Both
IPv4 and IPv6 addresses are supported.  For example, the following
command causes the server to bind to localhost only:

     python -m http.server 8000 --bind 127.0.0.1

3.4 新版功能: ‘--bind’ argument was introduced.

3.8 新版功能: ‘--bind’ argument enhanced to support IPv6

By default, server uses the current directory.  The option
‘-d/--directory’ specifies a directory to which it should serve the
files.  For example, the following command uses a specific directory:

     python -m http.server --directory /tmp/

3.7 新版功能: ‘--directory’ specify alternate directory

 -- 类: http.server.CGIHTTPRequestHandler (request, client_address,
          server)

     This class is used to serve either files or output of CGI scripts
     from the current directory and below.  Note that mapping HTTP
     hierarchic structure to local directory structure is exactly as in
     *note SimpleHTTPRequestHandler: 39d.

          注解: CGI scripts run by the *note CGIHTTPRequestHandler:
          2e67. class cannot execute redirects (HTTP code 302), because
          code 200 (script output follows) is sent prior to execution of
          the CGI script.  This pre-empts the status code.

     The class will however, run the CGI script, instead of serving it
     as a file, if it guesses it to be a CGI script.  Only
     directory-based CGI are used — the other common server
     configuration is to treat special extensions as denoting CGI
     scripts.

     The ‘do_GET()’ and ‘do_HEAD()’ functions are modified to run CGI
     scripts and serve the output, instead of serving files, if the
     request leads to somewhere below the ‘cgi_directories’ path.

     The *note CGIHTTPRequestHandler: 2e67. defines the following data
     member:

      -- 属性: cgi_directories

          This defaults to ‘['/cgi-bin', '/htbin']’ and describes
          directories to treat as containing CGI scripts.

     The *note CGIHTTPRequestHandler: 2e67. defines the following
     method:

      -- 方法: do_POST ()

          This method serves the ‘'POST'’ request type, only allowed for
          CGI scripts.  Error 501, "Can only POST to CGI scripts", is
          output when trying to POST to a non-CGI url.

     Note that CGI scripts will be run with UID of user nobody, for
     security reasons.  Problems with the CGI script will be translated
     to error 403.

*note CGIHTTPRequestHandler: 2e67. can be enabled in the command line by
passing the ‘--cgi’ option:

     python -m http.server --cgi 8000

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/http/server.py

   (2) https://tools.ietf.org/html/rfc3986.html

   (3) https://tools.ietf.org/html/rfc2822.html


File: python.info,  Node: http cookies --- HTTP状态管理,  Next: http cookiejar —— HTTP 客户端的 Cookie 处理,  Prev: http server --- HTTP 服务器,  Up: 互联网协议和支持

5.21.23 ‘http.cookies’ — HTTP状态管理
-------------------------------------

`源代码:' Lib/http/cookies.py(1)

__________________________________________________________________

The *note http.cookies: 96. module defines classes for abstracting the
concept of cookies, an HTTP state management mechanism.  It supports
both simple string-only cookies, and provides an abstraction for having
any serializable data-type as cookie value.

The module formerly strictly applied the parsing rules described in the
RFC 2109(2) and RFC 2068(3) specifications.  It has since been
discovered that MSIE 3.0x doesn’t follow the character rules outlined in
those specs and also many current day browsers and servers have relaxed
parsing rules when comes to Cookie handling.  As a result, the parsing
rules used are a bit less strict.

The character set, *note string.ascii_letters: c64, *note string.digits:
1735. and ‘!#$%&'*+-.^_`|~:’ denote the set of valid characters allowed
by this module in Cookie name (as *note key: 496.).

在 3.3 版更改: Allowed ’:’ as a valid Cookie name character.

     注解: On encountering an invalid cookie, *note CookieError: 2e6c.
     is raised, so if your cookie data comes from a browser you should
     always prepare for invalid data and catch *note CookieError: 2e6c.
     on parsing.

 -- 例外: http.cookies.CookieError

     Exception failing because of RFC 2109(4) invalidity: incorrect
     attributes, incorrect ‘Set-Cookie’ header, etc.

 -- 类: http.cookies.BaseCookie ([input])

     This class is a dictionary-like object whose keys are strings and
     whose values are *note Morsel: 495. instances.  Note that upon
     setting a key to a value, the value is first converted to a *note
     Morsel: 495. containing the key and the value.

     If `input' is given, it is passed to the *note load(): 2e6e.
     method.

 -- 类: http.cookies.SimpleCookie ([input])

     This class derives from *note BaseCookie: 2e6d. and overrides
     ‘value_decode()’ and ‘value_encode()’.  SimpleCookie supports
     strings as cookie values.  When setting the value, SimpleCookie
     calls the builtin *note str(): 339. to convert the value to a
     string.  Values received from HTTP are kept as strings.

参见
....

Module *note http.cookiejar: 95.

     HTTP cookie handling for web `clients'.  The *note http.cookiejar:
     95. and *note http.cookies: 96. modules do not depend on each
     other.

RFC 2109(5) - HTTP State Management Mechanism

     This is the state management specification implemented by this
     module.

* Menu:

* Cookie 对象::
* Morsel 对象::
* 示例: 示例<14>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/http/cookies.py

   (2) https://tools.ietf.org/html/rfc2109.html

   (3) https://tools.ietf.org/html/rfc2068.html

   (4) https://tools.ietf.org/html/rfc2109.html

   (5) https://tools.ietf.org/html/rfc2109.html


File: python.info,  Node: Cookie 对象,  Next: Morsel 对象,  Up: http cookies --- HTTP状态管理

5.21.23.1 Cookie 对象
.....................

 -- 方法: BaseCookie.value_decode (val)

     Return a tuple ‘(real_value, coded_value)’ from a string
     representation.  ‘real_value’ can be any type.  This method does no
     decoding in *note BaseCookie: 2e6d. — it exists so it can be
     overridden.

 -- 方法: BaseCookie.value_encode (val)

     Return a tuple ‘(real_value, coded_value)’.  `val' can be any type,
     but ‘coded_value’ will always be converted to a string.  This
     method does no encoding in *note BaseCookie: 2e6d. — it exists so
     it can be overridden.

     In general, it should be the case that *note value_encode(): 2e72.
     and *note value_decode(): 2e71. are inverses on the range of
     `value_decode'.

 -- 方法: BaseCookie.output (attrs=None, header='Set-Cookie:',
          sep='\r\n')

     Return a string representation suitable to be sent as HTTP headers.
     `attrs' and `header' are sent to each *note Morsel: 495.’s *note
     output(): 2e73. method.  `sep' is used to join the headers
     together, and is by default the combination ‘'\r\n'’ (CRLF).

 -- 方法: BaseCookie.js_output (attrs=None)

     Return an embeddable JavaScript snippet, which, if run on a browser
     which supports JavaScript, will act the same as if the HTTP headers
     was sent.

     The meaning for `attrs' is the same as in *note output(): 2e73.

 -- 方法: BaseCookie.load (rawdata)

     If `rawdata' is a string, parse it as an ‘HTTP_COOKIE’ and add the
     values found there as *note Morsel: 495.s.  If it is a dictionary,
     it is equivalent to:

          for k, v in rawdata.items():
              cookie[k] = v


File: python.info,  Node: Morsel 对象,  Next: 示例<14>,  Prev: Cookie 对象,  Up: http cookies --- HTTP状态管理

5.21.23.2 Morsel 对象
.....................

 -- 类: http.cookies.Morsel

     Abstract a key/value pair, which has some RFC 2109(1) attributes.

     Morsels are dictionary-like objects, whose set of keys is constant
     — the valid RFC 2109(2) attributes, which are

        * ‘expires’

        * ‘path’

        * ‘comment’

        * ‘domain’

        * ‘max-age’

        * ‘secure’

        * ‘version’

        * ‘httponly’

        * ‘samesite’

     The attribute ‘httponly’ specifies that the cookie is only
     transferred in HTTP requests, and is not accessible through
     JavaScript.  This is intended to mitigate some forms of cross-site
     scripting.

     The attribute ‘samesite’ specifies that the browser is not allowed
     to send the cookie along with cross-site requests.  This helps to
     mitigate CSRF attacks.  Valid values for this attribute are
     "Strict" and "Lax".

     The keys are case-insensitive and their default value is ‘''’.

     在 3.5 版更改: ‘__eq__()’ now takes *note key: 496. and *note
     value: 497. into account.

     在 3.7 版更改: Attributes *note key: 496, *note value: 497. and
     *note coded_value: 498. are read-only.  Use *note set(): 499. for
     setting them.

     在 3.8 版更改: Added support for the ‘samesite’ attribute.

 -- 属性: Morsel.value

     Cookie的值。

 -- 属性: Morsel.coded_value

     The encoded value of the cookie — this is what should be sent.

 -- 属性: Morsel.key

     The name of the cookie.

 -- 方法: Morsel.set (key, value, coded_value)

     Set the `key', `value' and `coded_value' attributes.

 -- 方法: Morsel.isReservedKey (K)

     Whether `K' is a member of the set of keys of a *note Morsel: 495.

 -- 方法: Morsel.output (attrs=None, header='Set-Cookie:')

     Return a string representation of the Morsel, suitable to be sent
     as an HTTP header.  By default, all the attributes are included,
     unless `attrs' is given, in which case it should be a list of
     attributes to use.  `header' is by default ‘"Set-Cookie:"’.

 -- 方法: Morsel.js_output (attrs=None)

     Return an embeddable JavaScript snippet, which, if run on a browser
     which supports JavaScript, will act the same as if the HTTP header
     was sent.

     The meaning for `attrs' is the same as in *note output(): 2e78.

 -- 方法: Morsel.OutputString (attrs=None)

     Return a string representing the Morsel, without any surrounding
     HTTP or JavaScript.

     The meaning for `attrs' is the same as in *note output(): 2e78.

 -- 方法: Morsel.update (values)

     Update the values in the Morsel dictionary with the values in the
     dictionary `values'.  Raise an error if any of the keys in the
     `values' dict is not a valid RFC 2109(3) attribute.

     在 3.5 版更改: an error is raised for invalid keys.

 -- 方法: Morsel.copy (value)

     Return a shallow copy of the Morsel object.

     在 3.5 版更改: return a Morsel object instead of a dict.

 -- 方法: Morsel.setdefault (key, value=None)

     Raise an error if key is not a valid RFC 2109(4) attribute,
     otherwise behave the same as *note dict.setdefault(): 9c7.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2109.html

   (2) https://tools.ietf.org/html/rfc2109.html

   (3) https://tools.ietf.org/html/rfc2109.html

   (4) https://tools.ietf.org/html/rfc2109.html


File: python.info,  Node: 示例<14>,  Prev: Morsel 对象,  Up: http cookies --- HTTP状态管理

5.21.23.3 示例
..............

The following example demonstrates how to use the *note http.cookies:
96. module.

     >>> from http import cookies
     >>> C = cookies.SimpleCookie()
     >>> C["fig"] = "newton"
     >>> C["sugar"] = "wafer"
     >>> print(C) # generate HTTP headers
     Set-Cookie: fig=newton
     Set-Cookie: sugar=wafer
     >>> print(C.output()) # same thing
     Set-Cookie: fig=newton
     Set-Cookie: sugar=wafer
     >>> C = cookies.SimpleCookie()
     >>> C["rocky"] = "road"
     >>> C["rocky"]["path"] = "/cookie"
     >>> print(C.output(header="Cookie:"))
     Cookie: rocky=road; Path=/cookie
     >>> print(C.output(attrs=[], header="Cookie:"))
     Cookie: rocky=road
     >>> C = cookies.SimpleCookie()
     >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
     >>> print(C)
     Set-Cookie: chips=ahoy
     Set-Cookie: vienna=finger
     >>> C = cookies.SimpleCookie()
     >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
     >>> print(C)
     Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
     >>> C = cookies.SimpleCookie()
     >>> C["oreo"] = "doublestuff"
     >>> C["oreo"]["path"] = "/"
     >>> print(C)
     Set-Cookie: oreo=doublestuff; Path=/
     >>> C = cookies.SimpleCookie()
     >>> C["twix"] = "none for you"
     >>> C["twix"].value
     'none for you'
     >>> C = cookies.SimpleCookie()
     >>> C["number"] = 7 # equivalent to C["number"] = str(7)
     >>> C["string"] = "seven"
     >>> C["number"].value
     '7'
     >>> C["string"].value
     'seven'
     >>> print(C)
     Set-Cookie: number=7
     Set-Cookie: string=seven


File: python.info,  Node: http cookiejar —— HTTP 客户端的 Cookie 处理,  Next: xmlrpc --- XMLRPC 服务端与客户端模块,  Prev: http cookies --- HTTP状态管理,  Up: 互联网协议和支持

5.21.24 ‘http.cookiejar’ —— HTTP 客户端的 Cookie 处理
-----------------------------------------------------

`源代码：' Lib/http/cookiejar.py(1)

__________________________________________________________________

*note http.cookiejar: 95. 模块定义了用于自动处理 HTTP cookie 的类。这对
访问需要小段数据 —— `cookies' 的网站很有用，这些数据由 Web 服务器的 HTTP
响应在客户端计算机上设置，然后在以后的 HTTP 请求中返回给服务器。

常规的 Netscape Cookie 协议和 RFC 2965(2) 定义的协议都可以处理。RFC 2965
处理默认情况下处于关闭状态。 RFC 2109(3) cookie 被解析为 Netscape
cookie，随后根据有效的 ’policy’ 被视为 Netscape 或 RFC 2965 cookie。 请
注意，Internet 上的大多数 cookie 是 Netscape cookie。 *note
http.cookiejar: 95. 尝试遵循事实上的 Netscape cookie 协议（与原始
Netscape 规范中所设定的协议大不相同），包括注意 ‘max-age’ 和 ‘port’ RFC
2965 引入的 cookie 属性。

     注解: 在 ‘Set-Cookie’ 和 ‘Set-Cookie2’ 头中找到的各种命名参数通常指
     `attributes'。为了不与 Python 属性相混淆，模块文档使用
     `cookie-attribute' 代替。

此模块定义了以下异常：

 -- 例外: http.cookiejar.LoadError

     *note FileCookieJar: 2e81. 实例在从文件加载 cookies 出错时抛出这个
     异常。 *note LoadError: 2e80. 是 *note OSError: 1d4. 的一个子类。

     在 3.3 版更改: LoadError 成为 *note OSError: 1d4. 的子类而不是
     *note IOError: 99a.。

提供了以下类：

 -- 类: http.cookiejar.CookieJar (policy=None)

     `policy' 是实现了 *note CookiePolicy: 2e82. 接口的一个对象。

     *note CookieJar: 2c83. 类储存 HTTP cookies。它从 HTTP 请求提取
     cookies，并在 HTTP 响应中返回它们。 *note CookieJar: 2c83. 实例在必
     要时自动处理包含 cookie 的到期情况。子类还负责储存和从文件或数据库
     中查找 cookies。

 -- 类: http.cookiejar.FileCookieJar (filename, delayload=None,
          policy=None)

     `policy' 是实现了 *note CookiePolicy: 2e82. 接口的一个对象。对于其
     他参数，参考相应属性的文档。

     一个可以从硬盘中文件加载或保存 cookie 的 *note CookieJar: 2c83.。
     Cookies `不' 会在 *note load(): 2e83. 或 *note revert(): 2e84. 方法
     调用前从命名的文件中加载。子类的文档位于段落 *note FileCookieJar
     subclasses and co-operation with web browsers: 2e85.。

     在 3.8 版更改: 文件名形参支持 *note path-like object: 373.。

 -- 类: http.cookiejar.CookiePolicy

     此类负责确定是否应从服务器接受每个 cookie 或将其返回给服务器。

 -- 类: http.cookiejar.DefaultCookiePolicy (blocked_domains=None,
          allowed_domains=None, netscape=True, rfc2965=False,
          rfc2109_as_netscape=None, hide_cookie2=False,
          strict_domain=False, strict_rfc2965_unverifiable=True,
          strict_ns_unverifiable=False,
          strict_ns_domain=DefaultCookiePolicy.DomainLiberal,
          strict_ns_set_initial_dollar=False, strict_ns_set_path=False,
          secure_protocols=("https", "wss"))

     构造参数只能以关键字参数传递，`blocked_domains' 是一个我们既不会接
     受也不会返回 cookie 的域名序列。`allowed_domains' 如果不是 *note
     None: 158.，则是仅有的我们会接受或返回的域名序列。
     `secure_protocols' 是可以添加安全 cookies 的协议序列。默认将
     `https' 和 `wss' （安全 WebSocket）考虑为安全协议。对于其他参数，参
     考 *note CookiePolicy: 2e82. 和 *note DefaultCookiePolicy: ffe. 对
     象的文档。

     *note DefaultCookiePolicy: ffe. implements the standard accept /
     reject rules for Netscape and RFC 2965(4) cookies.  By default, RFC
     2109(5) cookies (ie.  cookies received in a ‘Set-Cookie’ header
     with a version cookie-attribute of 1) are treated according to the
     RFC 2965 rules.  However, if RFC 2965 handling is turned off or
     *note rfc2109_as_netscape: 2e86. is ‘True’, RFC 2109 cookies are
     ’downgraded’ by the *note CookieJar: 2c83. instance to Netscape
     cookies, by setting the ‘version’ attribute of the *note Cookie:
     2e87. instance to 0.  *note DefaultCookiePolicy: ffe. also provides
     some parameters to allow some fine-tuning of policy.

 -- 类: http.cookiejar.Cookie

     This class represents Netscape, RFC 2109(6) and RFC 2965(7)
     cookies.  It is not expected that users of *note http.cookiejar:
     95. construct their own *note Cookie: 2e87. instances.  Instead, if
     necessary, call ‘make_cookies()’ on a *note CookieJar: 2c83.
     instance.

参见
....

Module *note urllib.request: 121.

     URL opening with automatic cookie handling.

Module *note http.cookies: 96.

     HTTP cookie classes, principally useful for server-side code.  The
     *note http.cookiejar: 95. and *note http.cookies: 96. modules do
     not depend on each other.

‘https://curl.haxx.se/rfc/cookie_spec.html’

     The specification of the original Netscape cookie protocol.  Though
     this is still the dominant protocol, the ’Netscape cookie protocol’
     implemented by all the major browsers (and *note http.cookiejar:
     95.) only bears a passing resemblance to the one sketched out in
     ‘cookie_spec.html’.

RFC 2109(8) - HTTP State Management Mechanism

     Obsoleted by RFC 2965(9).  Uses ‘Set-Cookie’ with version=1.

RFC 2965(10) - HTTP State Management Mechanism

     The Netscape protocol with the bugs fixed.  Uses ‘Set-Cookie2’ in
     place of ‘Set-Cookie’.  Not widely used.

‘http://kristol.org/cookie/errata.html’

     Unfinished errata to RFC 2965(11).

RFC 2964(12) - Use of HTTP State Management

* Menu:

* CookieJar 和 FileCookieJar 对象::
* FileCookieJar subclasses and co-operation with web browsers::
* CookiePolicy 对象::
* DefaultCookiePolicy 对象::
* Cookie 对象: Cookie 对象<2>.
* 例子: 例子<24>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/http/cookiejar.py

   (2) https://tools.ietf.org/html/rfc2965.html

   (3) https://tools.ietf.org/html/rfc2109.html

   (4) https://tools.ietf.org/html/rfc2965.html

   (5) https://tools.ietf.org/html/rfc2109.html

   (6) https://tools.ietf.org/html/rfc2109.html

   (7) https://tools.ietf.org/html/rfc2965.html

   (8) https://tools.ietf.org/html/rfc2109.html

   (9) https://tools.ietf.org/html/rfc2965.html

   (10) https://tools.ietf.org/html/rfc2965.html

   (11) https://tools.ietf.org/html/rfc2965.html

   (12) https://tools.ietf.org/html/rfc2964.html


File: python.info,  Node: CookieJar 和 FileCookieJar 对象,  Next: FileCookieJar subclasses and co-operation with web browsers,  Up: http cookiejar —— HTTP 客户端的 Cookie 处理

5.21.24.1 CookieJar 和 FileCookieJar 对象
.........................................

*note CookieJar: 2c83. objects support the *note iterator: 104b.
protocol for iterating over contained *note Cookie: 2e87. objects.

*note CookieJar: 2c83. has the following methods:

 -- 方法: CookieJar.add_cookie_header (request)

     Add correct ‘Cookie’ header to `request'.

     If policy allows (ie.  the ‘rfc2965’ and ‘hide_cookie2’ attributes
     of the *note CookieJar: 2c83.’s *note CookiePolicy: 2e82. instance
     are true and false respectively), the ‘Cookie2’ header is also
     added when appropriate.

     The `request' object (usually a *note urllib.request.Request: 8fe.
     instance) must support the methods ‘get_full_url()’, ‘get_host()’,
     ‘get_type()’, ‘unverifiable()’, ‘has_header()’, ‘get_header()’,
     ‘header_items()’, ‘add_unredirected_header()’ and ‘origin_req_host’
     attribute as documented by *note urllib.request: 121.

     在 3.3 版更改: `request' object needs ‘origin_req_host’ attribute.
     Dependency on a deprecated method ‘get_origin_req_host()’ has been
     removed.

 -- 方法: CookieJar.extract_cookies (response, request)

     Extract cookies from HTTP `response' and store them in the *note
     CookieJar: 2c83, where allowed by policy.

     The *note CookieJar: 2c83. will look for allowable ‘Set-Cookie’ and
     ‘Set-Cookie2’ headers in the `response' argument, and store cookies
     as appropriate (subject to the *note CookiePolicy.set_ok(): 2e8c.
     method’s approval).

     The `response' object (usually the result of a call to *note
     urllib.request.urlopen(): 795, or similar) should support an
     ‘info()’ method, which returns an *note email.message.Message: 54a.
     instance.

     The `request' object (usually a *note urllib.request.Request: 8fe.
     instance) must support the methods ‘get_full_url()’, ‘get_host()’,
     ‘unverifiable()’, and ‘origin_req_host’ attribute, as documented by
     *note urllib.request: 121.  The request is used to set default
     values for cookie-attributes as well as for checking that the
     cookie is allowed to be set.

     在 3.3 版更改: `request' object needs ‘origin_req_host’ attribute.
     Dependency on a deprecated method ‘get_origin_req_host()’ has been
     removed.

 -- 方法: CookieJar.set_policy (policy)

     Set the *note CookiePolicy: 2e82. instance to be used.

 -- 方法: CookieJar.make_cookies (response, request)

     Return sequence of *note Cookie: 2e87. objects extracted from
     `response' object.

     See the documentation for *note extract_cookies(): 2e8b. for the
     interfaces required of the `response' and `request' arguments.

 -- 方法: CookieJar.set_cookie_if_ok (cookie, request)

     Set a *note Cookie: 2e87. if policy says it’s OK to do so.

 -- 方法: CookieJar.set_cookie (cookie)

     Set a *note Cookie: 2e87, without checking with policy to see
     whether or not it should be set.

 -- 方法: CookieJar.clear ([domain[, path[, name]]])

     Clear some cookies.

     If invoked without arguments, clear all cookies.  If given a single
     argument, only cookies belonging to that `domain' will be removed.
     If given two arguments, cookies belonging to the specified `domain'
     and URL `path' are removed.  If given three arguments, then the
     cookie with the specified `domain', `path' and `name' is removed.

     Raises *note KeyError: 2c8. if no matching cookie exists.

 -- 方法: CookieJar.clear_session_cookies ()

     Discard all session cookies.

     Discards all contained cookies that have a true ‘discard’ attribute
     (usually because they had either no ‘max-age’ or ‘expires’
     cookie-attribute, or an explicit ‘discard’ cookie-attribute).  For
     interactive browsers, the end of a session usually corresponds to
     closing the browser window.

     Note that the ‘save()’ method won’t save session cookies anyway,
     unless you ask otherwise by passing a true `ignore_discard'
     argument.

*note FileCookieJar: 2e81. implements the following additional methods:

 -- 方法: FileCookieJar.save (filename=None, ignore_discard=False,
          ignore_expires=False)

     Save cookies to a file.

     This base class raises *note NotImplementedError: 617.  Subclasses
     may leave this method unimplemented.

     `filename' is the name of file in which to save cookies.  If
     `filename' is not specified, ‘self.filename’ is used (whose default
     is the value passed to the constructor, if any); if ‘self.filename’
     is *note None: 158, *note ValueError: 1fc. is raised.

     `ignore_discard': save even cookies set to be discarded.
     `ignore_expires': save even cookies that have expired

     The file is overwritten if it already exists, thus wiping all the
     cookies it contains.  Saved cookies can be restored later using the
     *note load(): 2e83. or *note revert(): 2e84. methods.

 -- 方法: FileCookieJar.load (filename=None, ignore_discard=False,
          ignore_expires=False)

     Load cookies from a file.

     Old cookies are kept unless overwritten by newly loaded ones.

     Arguments are as for *note save(): 2e93.

     The named file must be in the format understood by the class, or
     *note LoadError: 2e80. will be raised.  Also, *note OSError: 1d4.
     may be raised, for example if the file does not exist.

     在 3.3 版更改: 过去触发的 *note IOError: 99a.，现在是 *note
     OSError: 1d4. 的别名。

 -- 方法: FileCookieJar.revert (filename=None, ignore_discard=False,
          ignore_expires=False)

     Clear all cookies and reload cookies from a saved file.

     *note revert(): 2e84. can raise the same exceptions as *note
     load(): 2e83.  If there is a failure, the object’s state will not
     be altered.

*note FileCookieJar: 2e81. instances have the following public
attributes:

 -- 属性: FileCookieJar.filename

     Filename of default file in which to keep cookies.  This attribute
     may be assigned to.

 -- 属性: FileCookieJar.delayload

     If true, load cookies lazily from disk.  This attribute should not
     be assigned to.  This is only a hint, since this only affects
     performance, not behaviour (unless the cookies on disk are
     changing).  A *note CookieJar: 2c83. object may ignore it.  None of
     the *note FileCookieJar: 2e81. classes included in the standard
     library lazily loads cookies.


File: python.info,  Node: FileCookieJar subclasses and co-operation with web browsers,  Next: CookiePolicy 对象,  Prev: CookieJar 和 FileCookieJar 对象,  Up: http cookiejar —— HTTP 客户端的 Cookie 处理

5.21.24.2 FileCookieJar subclasses and co-operation with web browsers
.....................................................................

The following *note CookieJar: 2c83. subclasses are provided for reading
and writing.

 -- 类: http.cookiejar.MozillaCookieJar (filename, delayload=None,
          policy=None)

     A *note FileCookieJar: 2e81. that can load from and save cookies to
     disk in the Mozilla ‘cookies.txt’ file format (which is also used
     by the Lynx and Netscape browsers).

          注解: This loses information about RFC 2965(1) cookies, and
          also about newer or non-standard cookie-attributes such as
          ‘port’.

          警告: Back up your cookies before saving if you have cookies
          whose loss / corruption would be inconvenient (there are some
          subtleties which may lead to slight changes in the file over a
          load / save round-trip).

     Also note that cookies saved while Mozilla is running will get
     clobbered by Mozilla.

 -- 类: http.cookiejar.LWPCookieJar (filename, delayload=None,
          policy=None)

     A *note FileCookieJar: 2e81. that can load from and save cookies to
     disk in format compatible with the libwww-perl library’s
     ‘Set-Cookie3’ file format.  This is convenient if you want to store
     cookies in a human-readable file.

     在 3.8 版更改: 文件名形参支持 *note path-like object: 373.。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2965.html


File: python.info,  Node: CookiePolicy 对象,  Next: DefaultCookiePolicy 对象,  Prev: FileCookieJar subclasses and co-operation with web browsers,  Up: http cookiejar —— HTTP 客户端的 Cookie 处理

5.21.24.3 CookiePolicy 对象
...........................

Objects implementing the *note CookiePolicy: 2e82. interface have the
following methods:

 -- 方法: CookiePolicy.set_ok (cookie, request)

     Return boolean value indicating whether cookie should be accepted
     from server.

     `cookie' is a *note Cookie: 2e87. instance.  `request' is an object
     implementing the interface defined by the documentation for *note
     CookieJar.extract_cookies(): 2e8b.

 -- 方法: CookiePolicy.return_ok (cookie, request)

     Return boolean value indicating whether cookie should be returned
     to server.

     `cookie' is a *note Cookie: 2e87. instance.  `request' is an object
     implementing the interface defined by the documentation for *note
     CookieJar.add_cookie_header(): 2e8a.

 -- 方法: CookiePolicy.domain_return_ok (domain, request)

     Return ‘False’ if cookies should not be returned, given cookie
     domain.

     This method is an optimization.  It removes the need for checking
     every cookie with a particular domain (which might involve reading
     many files).  Returning true from *note domain_return_ok(): 2e9c.
     and *note path_return_ok(): 2e9d. leaves all the work to *note
     return_ok(): 2e9b.

     If *note domain_return_ok(): 2e9c. returns true for the cookie
     domain, *note path_return_ok(): 2e9d. is called for the cookie
     path.  Otherwise, *note path_return_ok(): 2e9d. and *note
     return_ok(): 2e9b. are never called for that cookie domain.  If
     *note path_return_ok(): 2e9d. returns true, *note return_ok():
     2e9b. is called with the *note Cookie: 2e87. object itself for a
     full check.  Otherwise, *note return_ok(): 2e9b. is never called
     for that cookie path.

     Note that *note domain_return_ok(): 2e9c. is called for every
     `cookie' domain, not just for the `request' domain.  For example,
     the function might be called with both ‘".example.com"’ and
     ‘"www.example.com"’ if the request domain is ‘"www.example.com"’.
     The same goes for *note path_return_ok(): 2e9d.

     The `request' argument is as documented for *note return_ok():
     2e9b.

 -- 方法: CookiePolicy.path_return_ok (path, request)

     Return ‘False’ if cookies should not be returned, given cookie
     path.

     See the documentation for *note domain_return_ok(): 2e9c.

In addition to implementing the methods above, implementations of the
*note CookiePolicy: 2e82. interface must also supply the following
attributes, indicating which protocols should be used, and how.  All of
these attributes may be assigned to.

 -- 属性: CookiePolicy.netscape

     Implement Netscape protocol.

 -- 属性: CookiePolicy.rfc2965

     Implement RFC 2965(1) protocol.

 -- 属性: CookiePolicy.hide_cookie2

     Don’t add ‘Cookie2’ header to requests (the presence of this header
     indicates to the server that we understand RFC 2965(2) cookies).

The most useful way to define a *note CookiePolicy: 2e82. class is by
subclassing from *note DefaultCookiePolicy: ffe. and overriding some or
all of the methods above.  *note CookiePolicy: 2e82. itself may be used
as a ’null policy’ to allow setting and receiving any and all cookies
(this is unlikely to be useful).

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2965.html

   (2) https://tools.ietf.org/html/rfc2965.html


File: python.info,  Node: DefaultCookiePolicy 对象,  Next: Cookie 对象<2>,  Prev: CookiePolicy 对象,  Up: http cookiejar —— HTTP 客户端的 Cookie 处理

5.21.24.4 DefaultCookiePolicy 对象
..................................

Implements the standard rules for accepting and returning cookies.

Both RFC 2965(1) and Netscape cookies are covered.  RFC 2965 handling is
switched off by default.

The easiest way to provide your own policy is to override this class and
call its methods in your overridden implementations before adding your
own additional checks:

     import http.cookiejar
     class MyCookiePolicy(http.cookiejar.DefaultCookiePolicy):
         def set_ok(self, cookie, request):
             if not http.cookiejar.DefaultCookiePolicy.set_ok(self, cookie, request):
                 return False
             if i_dont_want_to_store_this_cookie(cookie):
                 return False
             return True

In addition to the features required to implement the *note
CookiePolicy: 2e82. interface, this class allows you to block and allow
domains from setting and receiving cookies.  There are also some
strictness switches that allow you to tighten up the rather loose
Netscape protocol rules a little bit (at the cost of blocking some
benign cookies).

A domain blacklist and whitelist is provided (both off by default).
Only domains not in the blacklist and present in the whitelist (if the
whitelist is active) participate in cookie setting and returning.  Use
the `blocked_domains' constructor argument, and ‘blocked_domains()’ and
‘set_blocked_domains()’ methods (and the corresponding argument and
methods for `allowed_domains').  If you set a whitelist, you can turn it
off again by setting it to *note None: 158.

Domains in block or allow lists that do not start with a dot must equal
the cookie domain to be matched.  For example, ‘"example.com"’ matches a
blacklist entry of ‘"example.com"’, but ‘"www.example.com"’ does not.
Domains that do start with a dot are matched by more specific domains
too.  For example, both ‘"www.example.com"’ and
‘"www.coyote.example.com"’ match ‘".example.com"’ (but ‘"example.com"’
itself does not).  IP addresses are an exception, and must match
exactly.  For example, if blocked_domains contains ‘"192.168.1.2"’ and
‘".168.1.2"’, 192.168.1.2 is blocked, but 193.168.1.2 is not.

*note DefaultCookiePolicy: ffe. implements the following additional
methods:

 -- 方法: DefaultCookiePolicy.blocked_domains ()

     Return the sequence of blocked domains (as a tuple).

 -- 方法: DefaultCookiePolicy.set_blocked_domains (blocked_domains)

     Set the sequence of blocked domains.

 -- 方法: DefaultCookiePolicy.is_blocked (domain)

     Return whether `domain' is on the blacklist for setting or
     receiving cookies.

 -- 方法: DefaultCookiePolicy.allowed_domains ()

     Return *note None: 158, or the sequence of allowed domains (as a
     tuple).

 -- 方法: DefaultCookiePolicy.set_allowed_domains (allowed_domains)

     Set the sequence of allowed domains, or *note None: 158.

 -- 方法: DefaultCookiePolicy.is_not_allowed (domain)

     Return whether `domain' is not on the whitelist for setting or
     receiving cookies.

*note DefaultCookiePolicy: ffe. instances have the following attributes,
which are all initialised from the constructor arguments of the same
name, and which may all be assigned to.

 -- 属性: DefaultCookiePolicy.rfc2109_as_netscape

     If true, request that the *note CookieJar: 2c83. instance downgrade
     RFC 2109(2) cookies (ie.  cookies received in a ‘Set-Cookie’ header
     with a version cookie-attribute of 1) to Netscape cookies by
     setting the version attribute of the *note Cookie: 2e87. instance
     to 0.  The default value is *note None: 158, in which case RFC 2109
     cookies are downgraded if and only if RFC 2965(3) handling is
     turned off.  Therefore, RFC 2109 cookies are downgraded by default.

General strictness switches:

 -- 属性: DefaultCookiePolicy.strict_domain

     Don’t allow sites to set two-component domains with country-code
     top-level domains like ‘.co.uk’, ‘.gov.uk’, ‘.co.nz’.etc.  This is
     far from perfect and isn’t guaranteed to work!

RFC 2965(4) protocol strictness switches:

 -- 属性: DefaultCookiePolicy.strict_rfc2965_unverifiable

     Follow RFC 2965(5) rules on unverifiable transactions (usually, an
     unverifiable transaction is one resulting from a redirect or a
     request for an image hosted on another site).  If this is false,
     cookies are `never' blocked on the basis of verifiability

Netscape protocol strictness switches:

 -- 属性: DefaultCookiePolicy.strict_ns_unverifiable

     Apply RFC 2965(6) rules on unverifiable transactions even to
     Netscape cookies.

 -- 属性: DefaultCookiePolicy.strict_ns_domain

     Flags indicating how strict to be with domain-matching rules for
     Netscape cookies.  See below for acceptable values.

 -- 属性: DefaultCookiePolicy.strict_ns_set_initial_dollar

     Ignore cookies in Set-Cookie: headers that have names starting with
     ‘'$'’.

 -- 属性: DefaultCookiePolicy.strict_ns_set_path

     Don’t allow setting cookies whose path doesn’t path-match request
     URI.

‘strict_ns_domain’ is a collection of flags.  Its value is constructed
by or-ing together (for example,
‘DomainStrictNoDots|DomainStrictNonDomain’ means both flags are set).

 -- 属性: DefaultCookiePolicy.DomainStrictNoDots

     When setting cookies, the ’host prefix’ must not contain a dot (eg.
     ‘www.foo.bar.com’ can’t set a cookie for ‘.bar.com’, because
     ‘www.foo’ contains a dot).

 -- 属性: DefaultCookiePolicy.DomainStrictNonDomain

     Cookies that did not explicitly specify a ‘domain’ cookie-attribute
     can only be returned to a domain equal to the domain that set the
     cookie (eg.  ‘spam.example.com’ won’t be returned cookies from
     ‘example.com’ that had no ‘domain’ cookie-attribute).

 -- 属性: DefaultCookiePolicy.DomainRFC2965Match

     When setting cookies, require a full RFC 2965(7) domain-match.

The following attributes are provided for convenience, and are the most
useful combinations of the above flags:

 -- 属性: DefaultCookiePolicy.DomainLiberal

     Equivalent to 0 (ie.  all of the above Netscape domain strictness
     flags switched off).

 -- 属性: DefaultCookiePolicy.DomainStrict

     Equivalent to ‘DomainStrictNoDots|DomainStrictNonDomain’.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2965.html

   (2) https://tools.ietf.org/html/rfc2109.html

   (3) https://tools.ietf.org/html/rfc2965.html

   (4) https://tools.ietf.org/html/rfc2965.html

   (5) https://tools.ietf.org/html/rfc2965.html

   (6) https://tools.ietf.org/html/rfc2965.html

   (7) https://tools.ietf.org/html/rfc2965.html


File: python.info,  Node: Cookie 对象<2>,  Next: 例子<24>,  Prev: DefaultCookiePolicy 对象,  Up: http cookiejar —— HTTP 客户端的 Cookie 处理

5.21.24.5 Cookie 对象
.....................

*note Cookie: 2e87. instances have Python attributes roughly
corresponding to the standard cookie-attributes specified in the various
cookie standards.  The correspondence is not one-to-one, because there
are complicated rules for assigning default values, because the
‘max-age’ and ‘expires’ cookie-attributes contain equivalent
information, and because RFC 2109(1) cookies may be ’downgraded’ by
*note http.cookiejar: 95. from version 1 to version 0 (Netscape)
cookies.

Assignment to these attributes should not be necessary other than in
rare circumstances in a *note CookiePolicy: 2e82. method.  The class
does not enforce internal consistency, so you should know what you’re
doing if you do that.

 -- 属性: Cookie.version

     Integer or *note None: 158.  Netscape cookies have *note version:
     2eb5. 0.  RFC 2965(2) and RFC 2109(3) cookies have a ‘version’
     cookie-attribute of 1.  However, note that *note http.cookiejar:
     95. may ’downgrade’ RFC 2109 cookies to Netscape cookies, in which
     case *note version: 2eb5. is 0.

 -- 属性: Cookie.name

     Cookie name (a string).

 -- 属性: Cookie.value

     Cookie value (a string), or *note None: 158.

 -- 属性: Cookie.port

     String representing a port or a set of ports (eg.  ’80’, or
     ’80,8080’), or *note None: 158.

 -- 属性: Cookie.path

     Cookie path (a string, eg.  ‘'/acme/rocket_launchers'’).

 -- 属性: Cookie.secure

     ‘True’ if cookie should only be returned over a secure connection.

 -- 属性: Cookie.expires

     Integer expiry date in seconds since epoch, or *note None: 158.
     See also the *note is_expired(): 2ebc. method.

 -- 属性: Cookie.discard

     ‘True’ if this is a session cookie.

 -- 属性: Cookie.comment

     String comment from the server explaining the function of this
     cookie, or *note None: 158.

 -- 属性: Cookie.comment_url

     URL linking to a comment from the server explaining the function of
     this cookie, or *note None: 158.

 -- 属性: Cookie.rfc2109

     ‘True’ if this cookie was received as an RFC 2109(4) cookie (ie.
     the cookie arrived in a ‘Set-Cookie’ header, and the value of the
     Version cookie-attribute in that header was 1).  This attribute is
     provided because *note http.cookiejar: 95. may ’downgrade’ RFC 2109
     cookies to Netscape cookies, in which case *note version: 2eb5. is
     0.

 -- 属性: Cookie.port_specified

     ‘True’ if a port or set of ports was explicitly specified by the
     server (in the ‘Set-Cookie’ / ‘Set-Cookie2’ header).

 -- 属性: Cookie.domain_specified

     ‘True’ if a domain was explicitly specified by the server.

 -- 属性: Cookie.domain_initial_dot

     ‘True’ if the domain explicitly specified by the server began with
     a dot (‘'.'’).

Cookies may have additional non-standard cookie-attributes.  These may
be accessed using the following methods:

 -- 方法: Cookie.has_nonstandard_attr (name)

     Return ‘True’ if cookie has the named cookie-attribute.

 -- 方法: Cookie.get_nonstandard_attr (name, default=None)

     If cookie has the named cookie-attribute, return its value.
     Otherwise, return `default'.

 -- 方法: Cookie.set_nonstandard_attr (name, value)

     Set the value of the named cookie-attribute.

The *note Cookie: 2e87. class also defines the following method:

 -- 方法: Cookie.is_expired (now=None)

     ‘True’ if cookie has passed the time at which the server requested
     it should expire.  If `now' is given (in seconds since the epoch),
     return whether the cookie has expired at the specified time.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2109.html

   (2) https://tools.ietf.org/html/rfc2965.html

   (3) https://tools.ietf.org/html/rfc2109.html

   (4) https://tools.ietf.org/html/rfc2109.html


File: python.info,  Node: 例子<24>,  Prev: Cookie 对象<2>,  Up: http cookiejar —— HTTP 客户端的 Cookie 处理

5.21.24.6 例子
..............

The first example shows the most common usage of *note http.cookiejar:
95.:

     import http.cookiejar, urllib.request
     cj = http.cookiejar.CookieJar()
     opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
     r = opener.open("http://example.com/")

This example illustrates how to open a URL using your Netscape, Mozilla,
or Lynx cookies (assumes Unix/Netscape convention for location of the
cookies file):

     import os, http.cookiejar, urllib.request
     cj = http.cookiejar.MozillaCookieJar()
     cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt"))
     opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
     r = opener.open("http://example.com/")

The next example illustrates the use of *note DefaultCookiePolicy: ffe.
Turn on RFC 2965(1) cookies, be more strict about domains when setting
and returning Netscape cookies, and block some domains from setting
cookies or having them returned:

     import urllib.request
     from http.cookiejar import CookieJar, DefaultCookiePolicy
     policy = DefaultCookiePolicy(
         rfc2965=True, strict_ns_domain=Policy.DomainStrict,
         blocked_domains=["ads.net", ".ads.net"])
     cj = CookieJar(policy)
     opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
     r = opener.open("http://example.com/")

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2965.html


File: python.info,  Node: xmlrpc --- XMLRPC 服务端与客户端模块,  Next: xmlrpc client --- XML-RPC 客户端访问,  Prev: http cookiejar —— HTTP 客户端的 Cookie 处理,  Up: 互联网协议和支持

5.21.25 ‘xmlrpc’ — XMLRPC 服务端与客户端模块
--------------------------------------------

XML-RPC 是一种远程过程调用方法，它使用通过 HTTP 传递的 XML 作为载体。 有
了它，客户端可以在远程服务器上调用带参数的方法（服务器以 URI 命名）并获
取结构化的数据。

‘xmlrpc’ 是一个集合了 XML-RPC 服务端与客户端实现模块的包。 这些模块是:

   * *note xmlrpc.client: 140.

   * *note xmlrpc.server: 141.


File: python.info,  Node: xmlrpc client --- XML-RPC 客户端访问,  Next: xmlrpc server --- 基本 XML-RPC 服务器,  Prev: xmlrpc --- XMLRPC 服务端与客户端模块,  Up: 互联网协议和支持

5.21.26 ‘xmlrpc.client’ — XML-RPC 客户端访问
--------------------------------------------

`源代码:' Lib/xmlrpc/client.py(1)

__________________________________________________________________

XML-RPC 是一种远程过程调用方法，它以使用 HTTP(S) 传递的 XML 作为载体。 通
过它，客户端可以在远程服务器（服务器以 URI 指明）上调用带参数的方法并获
取结构化的数据。 本模块支持编写 XML-RPC 客户端代码；它会处理在通用
Python 对象和 XML 之间进行在线翻译的所有细节。

     警告: *note xmlrpc.client: 140. 模块对于恶意构建的数据是不安全的。
     如果你需要解析不受信任或未经身份验证的数据，请参阅 *note XML 漏洞:
     2a03.。

在 3.5 版更改: 对于 HTTPS URI，现在 *note xmlrpc.client: 140. 默认会执行
所有必要的证书和主机名检查。

 -- 类: xmlrpc.client.ServerProxy (uri, transport=None, encoding=None,
          verbose=False, allow_none=False, use_datetime=False,
          use_builtin_types=False, *, headers=(), context=None)

     A *note ServerProxy: 256. instance is an object that manages
     communication with a remote XML-RPC server.  The required first
     argument is a URI (Uniform Resource Indicator), and will normally
     be the URL of the server.  The optional second argument is a
     transport factory instance; by default it is an internal
     ‘SafeTransport’ instance for https: URLs and an internal HTTP
     ‘Transport’ instance otherwise.  The optional third argument is an
     encoding, by default UTF-8.  The optional fourth argument is a
     debugging flag.

     The following parameters govern the use of the returned proxy
     instance.  If `allow_none' is true, the Python constant ‘None’ will
     be translated into XML; the default behaviour is for ‘None’ to
     raise a *note TypeError: 193.  This is a commonly-used extension to
     the XML-RPC specification, but isn’t supported by all clients and
     servers; see http://ontosys.com/xml-rpc/extensions.php(2) for a
     description.  The `use_builtin_types' flag can be used to cause
     date/time values to be presented as *note datetime.datetime: 195.
     objects and binary data to be presented as *note bytes: 33a.
     objects; this flag is false by default.  *note datetime.datetime:
     195, *note bytes: 33a. and *note bytearray: 33b. objects may be
     passed to calls.  The `headers' parameter is an optional sequence
     of HTTP headers to send with each request, expressed as a sequence
     of 2-tuples representing the header name and value.  (e.g.
     ‘[(’Header-Name’, ’value’)]’).  The obsolete `use_datetime' flag is
     similar to `use_builtin_types' but it applies only to date/time
     values.

在 3.3 版更改: The `use_builtin_types' flag was added.

在 3.8 版更改: The `headers' parameter was added.

Both the HTTP and HTTPS transports support the URL syntax extension for
HTTP Basic Authentication: ‘http://user:pass@host:port/path’.  The
‘user:pass’ portion will be base64-encoded as an HTTP ’Authorization’
header, and sent to the remote server as part of the connection process
when invoking an XML-RPC method.  You only need to use this if the
remote server requires a Basic Authentication user and password.  If an
HTTPS URL is provided, `context' may be *note ssl.SSLContext: 3ec. and
configures the SSL settings of the underlying HTTPS connection.

The returned instance is a proxy object with methods that can be used to
invoke corresponding RPC calls on the remote server.  If the remote
server supports the introspection API, the proxy can also be used to
query the remote server for the methods it supports (service discovery)
and fetch other server-associated metadata.

Types that are conformable (e.g.  that can be marshalled through XML),
include the following (and except where noted, they are unmarshalled as
the same Python type):

XML-RPC类型                Python 类型
                           
---------------------------------------------------------------------------------------
                           
‘boolean’                  *note bool: 184.
                           
                           
‘int’, ‘i1’, ‘i2’, ‘i4’,   *note int: 185. 的范围从 -2147483648 到 2147483647。值将
‘i8’ 或者 ‘biginteger’     获得 ‘<int>’ 标志。
                           
                           
‘double’ 或 ‘float’        *note float: 188.。值将获得 ‘<double>’ 标志。
                           
                           
‘string’                   *note str: 339.
                           
                           
‘array’                    *note list: 263. 或 *note tuple: 486. 包含整合元素。数组
                           以 *note lists: 263. 形式返回。
                           
                           
‘struct’                   *note dict: 1b9.  Keys must be strings, values may be any
                           conformable type.  Objects of user-defined classes can be
                           passed in; only their *note __dict__: 504. attribute is
                           transmitted.
                           
                           
‘dateTime.iso8601’         *note DateTime: 2ecc. 或 *note datetime.datetime: 195.。
                           返回的类型取决于 `use_builtin_types' 和 `use_datetime' 标
                           志的值。
                           
                           
‘base64’                   *note Binary: 2ecd, *note bytes: 33a. 或
                           *note bytearray: 33b.。返回的类型取决于
                           `use_builtin_types' 标志的值。
                           
                           
‘nil’                      ‘None’ 常量。仅当 `allow_none' 为true时才允许传递。
                           
                           
‘bigdecimal’               *note decimal.Decimal: 189.  仅返回类型。
                           

This is the full set of data types supported by XML-RPC. Method calls
may also raise a special *note Fault: 2ece. instance, used to signal
XML-RPC server errors, or *note ProtocolError: 2ecf. used to signal an
error in the HTTP/HTTPS transport layer.  Both *note Fault: 2ece. and
*note ProtocolError: 2ecf. derive from a base class called ‘Error’.
Note that the xmlrpc client module currently does not marshal instances
of subclasses of built-in types.

When passing strings, characters special to XML such as ‘<’, ‘>’, and
‘&’ will be automatically escaped.  However, it’s the caller’s
responsibility to ensure that the string is free of characters that
aren’t allowed in XML, such as the control characters with ASCII values
between 0 and 31 (except, of course, tab, newline and carriage return);
failing to do this will result in an XML-RPC request that isn’t
well-formed XML. If you have to pass arbitrary bytes via XML-RPC, use
*note bytes: 33a. or *note bytearray: 33b. classes or the *note Binary:
2ecd. wrapper class described below.

‘Server’ is retained as an alias for *note ServerProxy: 256. for
backwards compatibility.  New code should use *note ServerProxy: 256.

在 3.5 版更改: Added the `context' argument.

在 3.6 版更改: Added support of type tags with prefixes (e.g.
‘ex:nil’).  Added support of unmarshalling additional types used by
Apache XML-RPC implementation for numerics: ‘i1’, ‘i2’, ‘i8’,
‘biginteger’, ‘float’ and ‘bigdecimal’.  See
‘http://ws.apache.org/xmlrpc/types.html’ for a description.

参见
....

XML-RPC HOWTO(3)

     A good description of XML-RPC operation and client software in
     several languages.  Contains pretty much everything an XML-RPC
     client developer needs to know.

XML-RPC Introspection(4)

     Describes the XML-RPC protocol extension for introspection.

XML-RPC Specification(5)

     The official specification.

Unofficial XML-RPC Errata(6)

     Fredrik Lundh’s "unofficial errata, intended to clarify certain
     details in the XML-RPC specification, as well as hint at ’best
     practices’ to use when designing your own XML-RPC implementations."

* Menu:

* ServerProxy 对象::
* DateTime 对象::
* Binary 对象::
* Fault 对象::
* ProtocolError 对象::
* MultiCall 对象::
* Convenience Functions::
* Example of Client Usage::
* Example of Client and Server Usage::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/xmlrpc/client.py

   (2) 
https://web.archive.org/web/20130120074804/http://ontosys.com/xml-rpc/extensions.php

   (3) http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html

   (4) http://xmlrpc-c.sourceforge.net/introspection.html

   (5) http://xmlrpc.scripting.com/spec.html

   (6) http://effbot.org/zone/xmlrpc-errata.htm


File: python.info,  Node: ServerProxy 对象,  Next: DateTime 对象,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.1 ServerProxy 对象
..........................

A *note ServerProxy: 256. instance has a method corresponding to each
remote procedure call accepted by the XML-RPC server.  Calling the
method performs an RPC, dispatched by both name and argument signature
(e.g.  the same method name can be overloaded with multiple argument
signatures).  The RPC finishes by returning a value, which may be either
returned data in a conformant type or a *note Fault: 2ece. or *note
ProtocolError: 2ecf. object indicating an error.

Servers that support the XML introspection API support some common
methods grouped under the reserved ‘system’ attribute:

 -- 方法: ServerProxy.system.listMethods ()

     This method returns a list of strings, one for each (non-system)
     method supported by the XML-RPC server.

 -- 方法: ServerProxy.system.methodSignature (name)

     This method takes one parameter, the name of a method implemented
     by the XML-RPC server.  It returns an array of possible signatures
     for this method.  A signature is an array of types.  The first of
     these types is the return type of the method, the rest are
     parameters.

     Because multiple signatures (ie.  overloading) is permitted, this
     method returns a list of signatures rather than a singleton.

     Signatures themselves are restricted to the top level parameters
     expected by a method.  For instance if a method expects one array
     of structs as a parameter, and it returns a string, its signature
     is simply "string, array".  If it expects three integers and
     returns a string, its signature is "string, int, int, int".

     If no signature is defined for the method, a non-array value is
     returned.  In Python this means that the type of the returned value
     will be something other than list.

 -- 方法: ServerProxy.system.methodHelp (name)

     This method takes one parameter, the name of a method implemented
     by the XML-RPC server.  It returns a documentation string
     describing the use of that method.  If no such string is available,
     an empty string is returned.  The documentation string may contain
     HTML markup.

在 3.5 版更改: Instances of *note ServerProxy: 256. support the *note
context manager: 571. protocol for closing the underlying transport.

A working example follows.  The server code:

     from xmlrpc.server import SimpleXMLRPCServer

     def is_even(n):
         return n % 2 == 0

     server = SimpleXMLRPCServer(("localhost", 8000))
     print("Listening on port 8000...")
     server.register_function(is_even, "is_even")
     server.serve_forever()

The client code for the preceding server:

     import xmlrpc.client

     with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy:
         print("3 is even: %s" % str(proxy.is_even(3)))
         print("100 is even: %s" % str(proxy.is_even(100)))


File: python.info,  Node: DateTime 对象,  Next: Binary 对象,  Prev: ServerProxy 对象,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.2 DateTime 对象
.......................

 -- 类: xmlrpc.client.DateTime

     This class may be initialized with seconds since the epoch, a time
     tuple, an ISO 8601 time/date string, or a *note datetime.datetime:
     195. instance.  It has the following methods, supported mainly for
     internal use by the marshalling/unmarshalling code:

      -- 方法: decode (string)

          Accept a string as the instance’s new time value.

      -- 方法: encode (out)

          Write the XML-RPC encoding of this *note DateTime: 2ecc. item
          to the `out' stream object.

     It also supports certain of Python’s built-in operators through
     rich comparison and *note __repr__(): 347. methods.

A working example follows.  The server code:

     import datetime
     from xmlrpc.server import SimpleXMLRPCServer
     import xmlrpc.client

     def today():
         today = datetime.datetime.today()
         return xmlrpc.client.DateTime(today)

     server = SimpleXMLRPCServer(("localhost", 8000))
     print("Listening on port 8000...")
     server.register_function(today, "today")
     server.serve_forever()

The client code for the preceding server:

     import xmlrpc.client
     import datetime

     proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")

     today = proxy.today()
     # convert the ISO8601 string to a datetime object
     converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
     print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M"))


File: python.info,  Node: Binary 对象,  Next: Fault 对象,  Prev: DateTime 对象,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.3 Binary 对象
.....................

 -- 类: xmlrpc.client.Binary

     This class may be initialized from bytes data (which may include
     NULs).  The primary access to the content of a *note Binary: 2ecd.
     object is provided by an attribute:

      -- 属性: data

          The binary data encapsulated by the *note Binary: 2ecd.
          instance.  The data is provided as a *note bytes: 33a. object.

     *note Binary: 2ecd. objects have the following methods, supported
     mainly for internal use by the marshalling/unmarshalling code:

      -- 方法: decode (bytes)

          Accept a base64 *note bytes: 33a. object and decode it as the
          instance’s new data.

      -- 方法: encode (out)

          Write the XML-RPC base 64 encoding of this binary item to the
          `out' stream object.

          The encoded data will have newlines every 76 characters as per
          RFC 2045 section 6.8(1), which was the de facto standard
          base64 specification when the XML-RPC spec was written.

     It also supports certain of Python’s built-in operators through
     *note __eq__(): 348. and *note __ne__(): e5e. methods.

Example usage of the binary objects.  We’re going to transfer an image
over XMLRPC:

     from xmlrpc.server import SimpleXMLRPCServer
     import xmlrpc.client

     def python_logo():
         with open("python_logo.jpg", "rb") as handle:
             return xmlrpc.client.Binary(handle.read())

     server = SimpleXMLRPCServer(("localhost", 8000))
     print("Listening on port 8000...")
     server.register_function(python_logo, 'python_logo')

     server.serve_forever()

The client gets the image and saves it to a file:

     import xmlrpc.client

     proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
     with open("fetched_python_logo.jpg", "wb") as handle:
         handle.write(proxy.python_logo().data)

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2045.html#section-6.8


File: python.info,  Node: Fault 对象,  Next: ProtocolError 对象,  Prev: Binary 对象,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.4 Fault 对象
....................

 -- 类: xmlrpc.client.Fault

     A *note Fault: 2ece. object encapsulates the content of an XML-RPC
     fault tag.  Fault objects have the following attributes:

      -- 属性: faultCode

          A string indicating the fault type.

      -- 属性: faultString

          A string containing a diagnostic message associated with the
          fault.

In the following example we’re going to intentionally cause a *note
Fault: 2ece. by returning a complex type object.  The server code:

     from xmlrpc.server import SimpleXMLRPCServer

     # A marshalling error is going to occur because we're returning a
     # complex number
     def add(x, y):
         return x+y+0j

     server = SimpleXMLRPCServer(("localhost", 8000))
     print("Listening on port 8000...")
     server.register_function(add, 'add')

     server.serve_forever()

The client code for the preceding server:

     import xmlrpc.client

     proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
     try:
         proxy.add(2, 5)
     except xmlrpc.client.Fault as err:
         print("A fault occurred")
         print("Fault code: %d" % err.faultCode)
         print("Fault string: %s" % err.faultString)


File: python.info,  Node: ProtocolError 对象,  Next: MultiCall 对象,  Prev: Fault 对象,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.5 ProtocolError 对象
............................

 -- 类: xmlrpc.client.ProtocolError

     A *note ProtocolError: 2ecf. object describes a protocol error in
     the underlying transport layer (such as a 404 ’not found’ error if
     the server named by the URI does not exist).  It has the following
     attributes:

      -- 属性: url

          The URI or URL that triggered the error.

      -- 属性: errcode

          The error code.

      -- 属性: errmsg

          The error message or diagnostic string.

      -- 属性: headers

          A dict containing the headers of the HTTP/HTTPS request that
          triggered the error.

In the following example we’re going to intentionally cause a *note
ProtocolError: 2ecf. by providing an invalid URI:

     import xmlrpc.client

     # create a ServerProxy with a URI that doesn't respond to XMLRPC requests
     proxy = xmlrpc.client.ServerProxy("http://google.com/")

     try:
         proxy.some_method()
     except xmlrpc.client.ProtocolError as err:
         print("A protocol error occurred")
         print("URL: %s" % err.url)
         print("HTTP/HTTPS headers: %s" % err.headers)
         print("Error code: %d" % err.errcode)
         print("Error message: %s" % err.errmsg)


File: python.info,  Node: MultiCall 对象,  Next: Convenience Functions,  Prev: ProtocolError 对象,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.6 MultiCall 对象
........................

The *note MultiCall: 2ee9. object provides a way to encapsulate multiple
calls to a remote server into a single request (1).

 -- 类: xmlrpc.client.MultiCall (server)

     Create an object used to boxcar method calls.  `server' is the
     eventual target of the call.  Calls can be made to the result
     object, but they will immediately return ‘None’, and only store the
     call name and parameters in the *note MultiCall: 2ee9. object.
     Calling the object itself causes all stored calls to be transmitted
     as a single ‘system.multicall’ request.  The result of this call is
     a *note generator: 9aa.; iterating over this generator yields the
     individual results.

A usage example of this class follows.  The server code:

     from xmlrpc.server import SimpleXMLRPCServer

     def add(x, y):
         return x + y

     def subtract(x, y):
         return x - y

     def multiply(x, y):
         return x * y

     def divide(x, y):
         return x // y

     # A simple server with simple arithmetic functions
     server = SimpleXMLRPCServer(("localhost", 8000))
     print("Listening on port 8000...")
     server.register_multicall_functions()
     server.register_function(add, 'add')
     server.register_function(subtract, 'subtract')
     server.register_function(multiply, 'multiply')
     server.register_function(divide, 'divide')
     server.serve_forever()

The client code for the preceding server:

     import xmlrpc.client

     proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
     multicall = xmlrpc.client.MultiCall(proxy)
     multicall.add(7, 3)
     multicall.subtract(7, 3)
     multicall.multiply(7, 3)
     multicall.divide(7, 3)
     result = multicall()

     print("7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d" % tuple(result))

   ---------- Footnotes ----------

   (1) (1) This approach has been first presented in a discussion on
xmlrpc.com
(https://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic).


File: python.info,  Node: Convenience Functions,  Next: Example of Client Usage,  Prev: MultiCall 对象,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.7 Convenience Functions
...............................

 -- 函数: xmlrpc.client.dumps (params, methodname=None,
          methodresponse=None, encoding=None, allow_none=False)

     Convert `params' into an XML-RPC request.  or into a response if
     `methodresponse' is true.  `params' can be either a tuple of
     arguments or an instance of the *note Fault: 2ece. exception class.
     If `methodresponse' is true, only a single value can be returned,
     meaning that `params' must be of length 1.  `encoding', if
     supplied, is the encoding to use in the generated XML; the default
     is UTF-8.  Python’s *note None: 158. value cannot be used in
     standard XML-RPC; to allow using it via an extension, provide a
     true value for `allow_none'.

 -- 函数: xmlrpc.client.loads (data, use_datetime=False,
          use_builtin_types=False)

     Convert an XML-RPC request or response into Python objects, a
     ‘(params, methodname)’.  `params' is a tuple of argument;
     `methodname' is a string, or ‘None’ if no method name is present in
     the packet.  If the XML-RPC packet represents a fault condition,
     this function will raise a *note Fault: 2ece. exception.  The
     `use_builtin_types' flag can be used to cause date/time values to
     be presented as *note datetime.datetime: 195. objects and binary
     data to be presented as *note bytes: 33a. objects; this flag is
     false by default.

     The obsolete `use_datetime' flag is similar to `use_builtin_types'
     but it applies only to date/time values.

     在 3.3 版更改: The `use_builtin_types' flag was added.


File: python.info,  Node: Example of Client Usage,  Next: Example of Client and Server Usage,  Prev: Convenience Functions,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.8 Example of Client Usage
.................................

     # simple test program (from the XML-RPC specification)
     from xmlrpc.client import ServerProxy, Error

     # server = ServerProxy("http://localhost:8000") # local server
     with ServerProxy("http://betty.userland.com") as proxy:

         print(proxy)

         try:
             print(proxy.examples.getStateName(41))
         except Error as v:
             print("ERROR", v)

To access an XML-RPC server through a HTTP proxy, you need to define a
custom transport.  The following example shows how:

     import http.client
     import xmlrpc.client

     class ProxiedTransport(xmlrpc.client.Transport):

         def set_proxy(self, host, port=None, headers=None):
             self.proxy = host, port
             self.proxy_headers = headers

         def make_connection(self, host):
             connection = http.client.HTTPConnection(*self.proxy)
             connection.set_tunnel(host, headers=self.proxy_headers)
             self._connection = host, connection
             return connection

     transport = ProxiedTransport()
     transport.set_proxy('proxy-server', 8080)
     server = xmlrpc.client.ServerProxy('http://betty.userland.com', transport=transport)
     print(server.examples.getStateName(41))


File: python.info,  Node: Example of Client and Server Usage,  Prev: Example of Client Usage,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.9 Example of Client and Server Usage
............................................

See *note SimpleXMLRPCServer Example: 2ef0.

备注
....


File: python.info,  Node: xmlrpc server --- 基本 XML-RPC 服务器,  Next: ipaddress --- IPv4/IPv6 操作库,  Prev: xmlrpc client --- XML-RPC 客户端访问,  Up: 互联网协议和支持

5.21.27 ‘xmlrpc.server’ — 基本 XML-RPC 服务器
---------------------------------------------

`源代码:' Lib/xmlrpc/server.py(1)

__________________________________________________________________

The *note xmlrpc.server: 141. module provides a basic server framework
for XML-RPC servers written in Python.  Servers can either be free
standing, using *note SimpleXMLRPCServer: 2ef3, or embedded in a CGI
environment, using *note CGIXMLRPCRequestHandler: 2ef4.

     警告: The *note xmlrpc.server: 141. module is not secure against
     maliciously constructed data.  If you need to parse untrusted or
     unauthenticated data see *note XML 漏洞: 2a03.

 -- 类: xmlrpc.server.SimpleXMLRPCServer (addr,
          requestHandler=SimpleXMLRPCRequestHandler, logRequests=True,
          allow_none=False, encoding=None, bind_and_activate=True,
          use_builtin_types=False)

     Create a new server instance.  This class provides methods for
     registration of functions that can be called by the XML-RPC
     protocol.  The `requestHandler' parameter should be a factory for
     request handler instances; it defaults to *note
     SimpleXMLRPCRequestHandler: 2ef5.  The `addr' and `requestHandler'
     parameters are passed to the *note socketserver.TCPServer: 2e1e.
     constructor.  If `logRequests' is true (the default), requests will
     be logged; setting this parameter to false will turn off logging.
     The `allow_none' and `encoding' parameters are passed on to *note
     xmlrpc.client: 140. and control the XML-RPC responses that will be
     returned from the server.  The `bind_and_activate' parameter
     controls whether ‘server_bind()’ and ‘server_activate()’ are called
     immediately by the constructor; it defaults to true.  Setting it to
     false allows code to manipulate the `allow_reuse_address' class
     variable before the address is bound.  The `use_builtin_types'
     parameter is passed to the *note loads(): 2eec. function and
     controls which types are processed when date/times values or binary
     data are received; it defaults to false.

     在 3.3 版更改: The `use_builtin_types' flag was added.

 -- 类: xmlrpc.server.CGIXMLRPCRequestHandler (allow_none=False,
          encoding=None, use_builtin_types=False)

     Create a new instance to handle XML-RPC requests in a CGI
     environment.  The `allow_none' and `encoding' parameters are passed
     on to *note xmlrpc.client: 140. and control the XML-RPC responses
     that will be returned from the server.  The `use_builtin_types'
     parameter is passed to the *note loads(): 2eec. function and
     controls which types are processed when date/times values or binary
     data are received; it defaults to false.

     在 3.3 版更改: The `use_builtin_types' flag was added.

 -- 类: xmlrpc.server.SimpleXMLRPCRequestHandler

     Create a new request handler instance.  This request handler
     supports ‘POST’ requests and modifies logging so that the
     `logRequests' parameter to the *note SimpleXMLRPCServer: 2ef3.
     constructor parameter is honored.

* Menu:

* SimpleXMLRPCServer Objects::
* CGIXMLRPCRequestHandler::
* Documenting XMLRPC server::
* DocXMLRPCServer Objects::
* DocCGIXMLRPCRequestHandler::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/xmlrpc/server.py


File: python.info,  Node: SimpleXMLRPCServer Objects,  Next: CGIXMLRPCRequestHandler,  Up: xmlrpc server --- 基本 XML-RPC 服务器

5.21.27.1 SimpleXMLRPCServer Objects
....................................

The *note SimpleXMLRPCServer: 2ef3. class is based on *note
socketserver.TCPServer: 2e1e. and provides a means of creating simple,
stand alone XML-RPC servers.

 -- 方法: SimpleXMLRPCServer.register_function (function=None,
          name=None)

     Register a function that can respond to XML-RPC requests.  If
     `name' is given, it will be the method name associated with
     `function', otherwise ‘function.__name__’ will be used.  `name' is
     a string, and may contain characters not legal in Python
     identifiers, including the period character.

     This method can also be used as a decorator.  When used as a
     decorator, `name' can only be given as a keyword argument to
     register `function' under `name'.  If no `name' is given,
     ‘function.__name__’ will be used.

     在 3.7 版更改: *note register_function(): 2ef8. can be used as a
     decorator.

 -- 方法: SimpleXMLRPCServer.register_instance (instance,
          allow_dotted_names=False)

     Register an object which is used to expose method names which have
     not been registered using *note register_function(): 2ef8.  If
     `instance' contains a ‘_dispatch()’ method, it is called with the
     requested method name and the parameters from the request.  Its API
     is ‘def _dispatch(self, method, params)’ (note that `params' does
     not represent a variable argument list).  If it calls an underlying
     function to perform its task, that function is called as
     ‘func(*params)’, expanding the parameter list.  The return value
     from ‘_dispatch()’ is returned to the client as the result.  If
     `instance' does not have a ‘_dispatch()’ method, it is searched for
     an attribute matching the name of the requested method.

     If the optional `allow_dotted_names' argument is true and the
     instance does not have a ‘_dispatch()’ method, then if the
     requested method name contains periods, each component of the
     method name is searched for individually, with the effect that a
     simple hierarchical search is performed.  The value found from this
     search is then called with the parameters from the request, and the
     return value is passed back to the client.

          警告: Enabling the `allow_dotted_names' option allows
          intruders to access your module’s global variables and may
          allow intruders to execute arbitrary code on your machine.
          Only use this option on a secure, closed network.

 -- 方法: SimpleXMLRPCServer.register_introspection_functions ()

     Registers the XML-RPC introspection functions ‘system.listMethods’,
     ‘system.methodHelp’ and ‘system.methodSignature’.

 -- 方法: SimpleXMLRPCServer.register_multicall_functions ()

     Registers the XML-RPC multicall function system.multicall.

 -- 属性: SimpleXMLRPCRequestHandler.rpc_paths

     An attribute value that must be a tuple listing valid path portions
     of the URL for receiving XML-RPC requests.  Requests posted to
     other paths will result in a 404 "no such page" HTTP error.  If
     this tuple is empty, all paths will be considered valid.  The
     default value is ‘('/', '/RPC2')’.

* Menu:

* SimpleXMLRPCServer Example::


File: python.info,  Node: SimpleXMLRPCServer Example,  Up: SimpleXMLRPCServer Objects

5.21.27.2 SimpleXMLRPCServer Example
....................................

Server code:

     from xmlrpc.server import SimpleXMLRPCServer
     from xmlrpc.server import SimpleXMLRPCRequestHandler

     # Restrict to a particular path.
     class RequestHandler(SimpleXMLRPCRequestHandler):
         rpc_paths = ('/RPC2',)

     # Create server
     with SimpleXMLRPCServer(('localhost', 8000),
                             requestHandler=RequestHandler) as server:
         server.register_introspection_functions()

         # Register pow() function; this will use the value of
         # pow.__name__ as the name, which is just 'pow'.
         server.register_function(pow)

         # Register a function under a different name
         def adder_function(x, y):
             return x + y
         server.register_function(adder_function, 'add')

         # Register an instance; all the methods of the instance are
         # published as XML-RPC methods (in this case, just 'mul').
         class MyFuncs:
             def mul(self, x, y):
                 return x * y

         server.register_instance(MyFuncs())

         # Run the server's main loop
         server.serve_forever()

The following client code will call the methods made available by the
preceding server:

     import xmlrpc.client

     s = xmlrpc.client.ServerProxy('http://localhost:8000')
     print(s.pow(2,3))  # Returns 2**3 = 8
     print(s.add(2,3))  # Returns 5
     print(s.mul(5,2))  # Returns 5*2 = 10

     # Print list of available methods
     print(s.system.listMethods())

‘register_function()’ can also be used as a decorator.  The previous
server example can register functions in a decorator way:

     from xmlrpc.server import SimpleXMLRPCServer
     from xmlrpc.server import SimpleXMLRPCRequestHandler

     class RequestHandler(SimpleXMLRPCRequestHandler):
         rpc_paths = ('/RPC2',)

     with SimpleXMLRPCServer(('localhost', 8000),
                             requestHandler=RequestHandler) as server:
         server.register_introspection_functions()

         # Register pow() function; this will use the value of
         # pow.__name__ as the name, which is just 'pow'.
         server.register_function(pow)

         # Register a function under a different name, using
         # register_function as a decorator. *name* can only be given
         # as a keyword argument.
         @server.register_function(name='add')
         def adder_function(x, y):
             return x + y

         # Register a function under function.__name__.
         @server.register_function
         def mul(x, y):
             return x * y

         server.serve_forever()

The following example included in the ‘Lib/xmlrpc/server.py’ module
shows a server allowing dotted names and registering a multicall
function.

     警告: Enabling the `allow_dotted_names' option allows intruders to
     access your module’s global variables and may allow intruders to
     execute arbitrary code on your machine.  Only use this example only
     within a secure, closed network.

     import datetime

     class ExampleService:
         def getData(self):
             return '42'

         class currentTime:
             @staticmethod
             def getCurrentTime():
                 return datetime.datetime.now()

     with SimpleXMLRPCServer(("localhost", 8000)) as server:
         server.register_function(pow)
         server.register_function(lambda x,y: x+y, 'add')
         server.register_instance(ExampleService(), allow_dotted_names=True)
         server.register_multicall_functions()
         print('Serving XML-RPC on localhost port 8000')
         try:
             server.serve_forever()
         except KeyboardInterrupt:
             print("\nKeyboard interrupt received, exiting.")
             sys.exit(0)

This ExampleService demo can be invoked from the command line:

     python -m xmlrpc.server

The client that interacts with the above server is included in
‘Lib/xmlrpc/client.py’:

     server = ServerProxy("http://localhost:8000")

     try:
         print(server.currentTime.getCurrentTime())
     except Error as v:
         print("ERROR", v)

     multi = MultiCall(server)
     multi.getData()
     multi.pow(2,9)
     multi.add(1,2)
     try:
         for response in multi():
             print(response)
     except Error as v:
         print("ERROR", v)

This client which interacts with the demo XMLRPC server can be invoked
as:

     python -m xmlrpc.client


File: python.info,  Node: CGIXMLRPCRequestHandler,  Next: Documenting XMLRPC server,  Prev: SimpleXMLRPCServer Objects,  Up: xmlrpc server --- 基本 XML-RPC 服务器

5.21.27.3 CGIXMLRPCRequestHandler
.................................

The *note CGIXMLRPCRequestHandler: 2ef4. class can be used to handle
XML-RPC requests sent to Python CGI scripts.

 -- 方法: CGIXMLRPCRequestHandler.register_function (function=None,
          name=None)

     Register a function that can respond to XML-RPC requests.  If
     `name' is given, it will be the method name associated with
     `function', otherwise ‘function.__name__’ will be used.  `name' is
     a string, and may contain characters not legal in Python
     identifiers, including the period character.

     This method can also be used as a decorator.  When used as a
     decorator, `name' can only be given as a keyword argument to
     register `function' under `name'.  If no `name' is given,
     ‘function.__name__’ will be used.

     在 3.7 版更改: *note register_function(): 2eff. can be used as a
     decorator.

 -- 方法: CGIXMLRPCRequestHandler.register_instance (instance)

     Register an object which is used to expose method names which have
     not been registered using *note register_function(): 2eff.  If
     instance contains a ‘_dispatch()’ method, it is called with the
     requested method name and the parameters from the request; the
     return value is returned to the client as the result.  If instance
     does not have a ‘_dispatch()’ method, it is searched for an
     attribute matching the name of the requested method; if the
     requested method name contains periods, each component of the
     method name is searched for individually, with the effect that a
     simple hierarchical search is performed.  The value found from this
     search is then called with the parameters from the request, and the
     return value is passed back to the client.

 -- 方法: CGIXMLRPCRequestHandler.register_introspection_functions ()

     Register the XML-RPC introspection functions ‘system.listMethods’,
     ‘system.methodHelp’ and ‘system.methodSignature’.

 -- 方法: CGIXMLRPCRequestHandler.register_multicall_functions ()

     Register the XML-RPC multicall function ‘system.multicall’.

 -- 方法: CGIXMLRPCRequestHandler.handle_request (request_text=None)

     Handle an XML-RPC request.  If `request_text' is given, it should
     be the POST data provided by the HTTP server, otherwise the
     contents of stdin will be used.

示例:

     class MyFuncs:
         def mul(self, x, y):
             return x * y


     handler = CGIXMLRPCRequestHandler()
     handler.register_function(pow)
     handler.register_function(lambda x,y: x+y, 'add')
     handler.register_introspection_functions()
     handler.register_instance(MyFuncs())
     handler.handle_request()


File: python.info,  Node: Documenting XMLRPC server,  Next: DocXMLRPCServer Objects,  Prev: CGIXMLRPCRequestHandler,  Up: xmlrpc server --- 基本 XML-RPC 服务器

5.21.27.4 Documenting XMLRPC server
...................................

These classes extend the above classes to serve HTML documentation in
response to HTTP GET requests.  Servers can either be free standing,
using *note DocXMLRPCServer: f87, or embedded in a CGI environment,
using *note DocCGIXMLRPCRequestHandler: 2f05.

 -- 类: xmlrpc.server.DocXMLRPCServer (addr,
          requestHandler=DocXMLRPCRequestHandler, logRequests=True,
          allow_none=False, encoding=None, bind_and_activate=True,
          use_builtin_types=True)

     Create a new server instance.  All parameters have the same meaning
     as for *note SimpleXMLRPCServer: 2ef3.; `requestHandler' defaults
     to *note DocXMLRPCRequestHandler: 2f06.

     在 3.3 版更改: The `use_builtin_types' flag was added.

 -- 类: xmlrpc.server.DocCGIXMLRPCRequestHandler

     Create a new instance to handle XML-RPC requests in a CGI
     environment.

 -- 类: xmlrpc.server.DocXMLRPCRequestHandler

     Create a new request handler instance.  This request handler
     supports XML-RPC POST requests, documentation GET requests, and
     modifies logging so that the `logRequests' parameter to the *note
     DocXMLRPCServer: f87. constructor parameter is honored.


File: python.info,  Node: DocXMLRPCServer Objects,  Next: DocCGIXMLRPCRequestHandler,  Prev: Documenting XMLRPC server,  Up: xmlrpc server --- 基本 XML-RPC 服务器

5.21.27.5 DocXMLRPCServer Objects
.................................

The *note DocXMLRPCServer: f87. class is derived from *note
SimpleXMLRPCServer: 2ef3. and provides a means of creating
self-documenting, stand alone XML-RPC servers.  HTTP POST requests are
handled as XML-RPC method calls.  HTTP GET requests are handled by
generating pydoc-style HTML documentation.  This allows a server to
provide its own web-based documentation.

 -- 方法: DocXMLRPCServer.set_server_title (server_title)

     Set the title used in the generated HTML documentation.  This title
     will be used inside the HTML "title" element.

 -- 方法: DocXMLRPCServer.set_server_name (server_name)

     Set the name used in the generated HTML documentation.  This name
     will appear at the top of the generated documentation inside a "h1"
     element.

 -- 方法: DocXMLRPCServer.set_server_documentation
          (server_documentation)

     Set the description used in the generated HTML documentation.  This
     description will appear as a paragraph, below the server name, in
     the documentation.


File: python.info,  Node: DocCGIXMLRPCRequestHandler,  Prev: DocXMLRPCServer Objects,  Up: xmlrpc server --- 基本 XML-RPC 服务器

5.21.27.6 DocCGIXMLRPCRequestHandler
....................................

The *note DocCGIXMLRPCRequestHandler: 2f05. class is derived from *note
CGIXMLRPCRequestHandler: 2ef4. and provides a means of creating
self-documenting, XML-RPC CGI scripts.  HTTP POST requests are handled
as XML-RPC method calls.  HTTP GET requests are handled by generating
pydoc-style HTML documentation.  This allows a server to provide its own
web-based documentation.

 -- 方法: DocCGIXMLRPCRequestHandler.set_server_title (server_title)

     Set the title used in the generated HTML documentation.  This title
     will be used inside the HTML "title" element.

 -- 方法: DocCGIXMLRPCRequestHandler.set_server_name (server_name)

     Set the name used in the generated HTML documentation.  This name
     will appear at the top of the generated documentation inside a "h1"
     element.

 -- 方法: DocCGIXMLRPCRequestHandler.set_server_documentation
          (server_documentation)

     Set the description used in the generated HTML documentation.  This
     description will appear as a paragraph, below the server name, in
     the documentation.


File: python.info,  Node: ipaddress --- IPv4/IPv6 操作库,  Prev: xmlrpc server --- 基本 XML-RPC 服务器,  Up: 互联网协议和支持

5.21.28 ‘ipaddress’ — IPv4/IPv6 操作库
--------------------------------------

`源代码：' Lib/ipaddress.py(1)

__________________________________________________________________

*note ipaddress: a3. 提供了创建、处理和操作 IPv4 和 IPv6 地址和网络的功
能。

该模块中的函数和类可以直接处理与IP地址相关的各种任务，包括检查两个主机是
否在同一个子网中，遍历某个子网中的所有主机，检查一个字符串是否是一个有效
的IP地址或网络定义等等。

这是完整的模块 API 参考—若要查看概述，请见 *note ipaddress模块介绍:
2f12.

3.3 新版功能.

* Menu:

* 方便的工厂函数::
* IP 地址::
* IP网络的定义::
* Interface objects::
* Other Module Level Functions::
* Custom Exceptions::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/ipaddress.py


File: python.info,  Node: 方便的工厂函数,  Next: IP 地址,  Up: ipaddress --- IPv4/IPv6 操作库

5.21.28.1 方便的工厂函数
........................

*note ipaddress: a3. 模块提供来工厂函数来方便地创建 IP 地址，网络和接口
：

 -- 函数: ipaddress.ip_address (address)

     返回一个 *note IPv4Address: 2f15. 或 *note IPv6Address: 2f16. 对象
     ，取决于作为参数传递的 IP 地址。可以提供IPv4或IPv6地址，小于 2**32
     的整数默认被认为是 IPv4。如果 `address' 不是有效的 IPv4 或 IPv6 地
     址，则会抛出 *note ValueError: 1fc.。

          >>> ipaddress.ip_address('192.168.0.1')
          IPv4Address('192.168.0.1')
          >>> ipaddress.ip_address('2001:db8::')
          IPv6Address('2001:db8::')

 -- 函数: ipaddress.ip_network (address, strict=True)

     返回一个 *note IPv4Network: 3a8. 或 *note IPv6Network: 3a7. 对象，
     具体取决于作为参数传入的 IP 地址。 `address' 是表示 IP 网址的字符串
     或整数。 可以提供 IPv4 或 IPv6 网址；小于 2**32 的整数默认被视为
     IPv4。 `strict' 会被传给 *note IPv4Network: 3a8. 或 *note
     IPv6Network: 3a7. 构造器。 如果 `address' 不表示有效的 IPv4 或 IPv6
     网址，或者网络设置了 host 比特位，则会引发 *note ValueError: 1fc.。

          >>> ipaddress.ip_network('192.168.0.0/28')
          IPv4Network('192.168.0.0/28')

 -- 函数: ipaddress.ip_interface (address)

     返回一个 *note IPv4Interface: 2f19. 或 *note IPv6Interface: 2f1a. 对
     象，取决于作为参数传递的 IP 地址。 `address' 是代表 IP 地址的字符串
     或整数。 可以提供 IPv4 或 IPv6 地址，小于 2**32 的整数默认认为是
     IPv4。 如果 `address' 不是有效的IPv4 或 IPv6 地址，则会抛出一个
     *note ValueError: 1fc.。

这些方便的函数的一个缺点是需要同时处理IPv4和IPv6格式，这意味着提供的错误
信息并不精准，因为函数不知道是打算采用IPv4还是IPv6格式。更详细的错误报告
可以通过直接调用相应版本的类构造函数来获得。


File: python.info,  Node: IP 地址,  Next: IP网络的定义,  Prev: 方便的工厂函数,  Up: ipaddress --- IPv4/IPv6 操作库

5.21.28.2 IP 地址
.................

* Menu:

* 地址对象::
* Conversion to Strings and Integers::
* 运算符: 运算符<3>.


File: python.info,  Node: 地址对象,  Next: Conversion to Strings and Integers,  Up: IP 地址

5.21.28.3 地址对象
..................

*note IPv4Address: 2f15. 和 *note IPv6Address: 2f16. 对象有很多共同的属
性。一些只对IPv6 地址有意义的属性也在 *note IPv4Address: 2f15. 对象实现
，以便更容易编写正确处理两种 IP 版本的代码。地址对象是可哈希的 *note
hashable: 1439.，所以它们可以作为字典中的键来使用。

 -- 类: ipaddress.IPv4Address (address)

     构造一个 IPv4 地址。 如果 `address' 不是一个有效的 IPv4 地址，会抛
     出 *note AddressValueError: 2f1d. 。

     以下是有效的 IPv4 地址：

       1. 以十进制小数点表示的字符串，由四个十进制整数组成，范围为
          0–255，用点隔开(例如 ‘192.168.0.1’ )。每个整数代表地址中的八位
          （一个字节）。不允许使用前导零，以免与八进制表示产生歧义。

       2. 一个32位可容纳的整数。

       3. 一个长度为 4 的封装在 *note bytes: 33a. 对象中的整数(高位优先
          )。

          >>> ipaddress.IPv4Address('192.168.0.1')
          IPv4Address('192.168.0.1')
          >>> ipaddress.IPv4Address(3232235521)
          IPv4Address('192.168.0.1')
          >>> ipaddress.IPv4Address(b'\xC0\xA8\x00\x01')
          IPv4Address('192.168.0.1')

     在 3.8 版更改: 前导零可被接受，即使是在可能与八进制表示混淆的情况下
     也会被接受。

     在 3.8.12 版更改: 前导零不再被接受，并且会被视作错误。IPv4地址字符
     串现在严格按照glibc的 *note inet_pton(): 2f9. 函数进行解析。

      -- 属性: version

          合适的版本号：IPv4为 ‘4’ ，IPv6为 ‘6’ 。

      -- 属性: max_prefixlen

          在该版本的地址表示中，比特数的总数：IPv4为 ‘32’ ；IPv6为 ‘128’
          。

          The prefix defines the number of leading bits in an address
          that are compared to determine whether or not an address is
          part of a network.

      -- 属性: compressed

      -- 属性: exploded

          The string representation in dotted decimal notation.  Leading
          zeroes are never included in the representation.

          As IPv4 does not define a shorthand notation for addresses
          with octets set to zero, these two attributes are always the
          same as ‘str(addr)’ for IPv4 addresses.  Exposing these
          attributes makes it easier to write display code that can
          handle both IPv4 and IPv6 addresses.

      -- 属性: packed

          The binary representation of this address - a *note bytes:
          33a. object of the appropriate length (most significant octet
          first).  This is 4 bytes for IPv4 and 16 bytes for IPv6.

      -- 属性: reverse_pointer

          The name of the reverse DNS PTR record for the IP address,
          e.g.:

               >>> ipaddress.ip_address("127.0.0.1").reverse_pointer
               '1.0.0.127.in-addr.arpa'
               >>> ipaddress.ip_address("2001:db8::1").reverse_pointer
               '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'

          This is the name that could be used for performing a PTR
          lookup, not the resolved hostname itself.

          3.5 新版功能.

      -- 属性: is_multicast

          如果该地址被保留用作多播用途，返回 ‘True’ 。关于多播地址，请参
          见 RFC 3171(1) （IPv4）和 RFC 2373(2) （IPv6）。

      -- 属性: is_private

          如果该地址被分配至私有网络，返回 ‘True’ 。关于公共网络，请参见
          iana-ipv4-special-registry(3) （针对IPv4）和
          iana-ipv6-special-registry(4) （针对IPv6）。

      -- 属性: is_global

          如果该地址被分配至公共网络，返回 ‘True’ 。关于公共网络，请参见
          iana-ipv4-special-registry(5) （针对IPv4）和
          iana-ipv6-special-registry(6) （针对IPv6）。

          3.4 新版功能.

      -- 属性: is_unspecified

          ‘True’ if the address is unspecified.  See RFC 5735(7) (for
          IPv4) or RFC 2373(8) (for IPv6).

      -- 属性: is_reserved

          如果该地址属于互联网工程任务组（IETF）所规定的其他保留地址，返
          回 ‘True’ 。

      -- 属性: is_loopback

          如果该地址为一个回环地址，返回 ‘True’ 。关于回环地址，请见 RFC
          3330(9) （IPv4）和 RFC 2373(10) （IPv6）

      -- 属性: is_link_local

          ‘True’ if the address is reserved for link-local usage.  See
          RFC 3927(11).

 -- 类: ipaddress.IPv6Address (address)

     构造一个 IPv6 地址。 如果 `address' 不是一个有效的 IPv6 地址，会抛
     出 *note AddressValueError: 2f1d. 。

     以下是有效的 IPv6 地址：

       1. A string consisting of eight groups of four hexadecimal
          digits, each group representing 16 bits.  The groups are
          separated by colons.  This describes an `exploded' (longhand)
          notation.  The string can also be `compressed' (shorthand
          notation) by various means.  See RFC 4291(12) for details.
          For example, ‘"0000:0000:0000:0000:0000:0abc:0007:0def"’ can
          be compressed to ‘"::abc:7:def"’.

       2. An integer that fits into 128 bits.

       3. An integer packed into a *note bytes: 33a. object of length
          16, big-endian.

          >>> ipaddress.IPv6Address('2001:db8::1000')
          IPv6Address('2001:db8::1000')

      -- 属性: compressed

     The short form of the address representation, with leading zeroes
     in groups omitted and the longest sequence of groups consisting
     entirely of zeroes collapsed to a single empty group.

     This is also the value returned by ‘str(addr)’ for IPv6 addresses.

      -- 属性: exploded

     The long form of the address representation, with all leading
     zeroes and groups consisting entirely of zeroes included.

     For the following attributes, see the corresponding documentation
     of the *note IPv4Address: 2f15. class:

      -- 属性: packed

      -- 属性: reverse_pointer

      -- 属性: version

      -- 属性: max_prefixlen

      -- 属性: is_multicast

      -- 属性: is_private

      -- 属性: is_global

      -- 属性: is_unspecified

      -- 属性: is_reserved

      -- 属性: is_loopback

      -- 属性: is_link_local

          3.4 新版功能: is_global

      -- 属性: is_site_local

          ‘True’ if the address is reserved for site-local usage.  Note
          that the site-local address space has been deprecated by RFC
          3879(13).  Use *note is_private: 2f25. to test if this address
          is in the space of unique local addresses as defined by RFC
          4193(14).

      -- 属性: ipv4_mapped

          For addresses that appear to be IPv4 mapped addresses
          (starting with ‘::FFFF/96’), this property will report the
          embedded IPv4 address.  For any other address, this property
          will be ‘None’.

      -- 属性: sixtofour

          For addresses that appear to be 6to4 addresses (starting with
          ‘2002::/16’) as defined by RFC 3056(15), this property will
          report the embedded IPv4 address.  For any other address, this
          property will be ‘None’.

      -- 属性: teredo

          For addresses that appear to be Teredo addresses (starting
          with ‘2001::/32’) as defined by RFC 4380(16), this property
          will report the embedded ‘(server, client)’ IP address pair.
          For any other address, this property will be ‘None’.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3171.html

   (2) https://tools.ietf.org/html/rfc2373.html

   (3) 
https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml

   (4) 
https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml

   (5) 
https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml

   (6) 
https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml

   (7) https://tools.ietf.org/html/rfc5735.html

   (8) https://tools.ietf.org/html/rfc2373.html

   (9) https://tools.ietf.org/html/rfc3330.html

   (10) https://tools.ietf.org/html/rfc2373.html

   (11) https://tools.ietf.org/html/rfc3927.html

   (12) https://tools.ietf.org/html/rfc4291.html

   (13) https://tools.ietf.org/html/rfc3879.html

   (14) https://tools.ietf.org/html/rfc4193.html

   (15) https://tools.ietf.org/html/rfc3056.html

   (16) https://tools.ietf.org/html/rfc4380.html


File: python.info,  Node: Conversion to Strings and Integers,  Next: 运算符<3>,  Prev: 地址对象,  Up: IP 地址

5.21.28.4 Conversion to Strings and Integers
............................................

To interoperate with networking interfaces such as the socket module,
addresses must be converted to strings or integers.  This is handled
using the *note str(): 339. and *note int(): 185. builtin functions:

     >>> str(ipaddress.IPv4Address('192.168.0.1'))
     '192.168.0.1'
     >>> int(ipaddress.IPv4Address('192.168.0.1'))
     3232235521
     >>> str(ipaddress.IPv6Address('::1'))
     '::1'
     >>> int(ipaddress.IPv6Address('::1'))
     1


File: python.info,  Node: 运算符<3>,  Prev: Conversion to Strings and Integers,  Up: IP 地址

5.21.28.5 运算符
................

Address objects support some operators.  Unless stated otherwise,
operators can only be applied between compatible objects (i.e.  IPv4
with IPv4, IPv6 with IPv6).

* Menu:

* 比较运算符::
* 算术运算符::


File: python.info,  Node: 比较运算符,  Next: 算术运算符,  Up: 运算符<3>

5.21.28.6 比较运算符
....................

Address objects can be compared with the usual set of comparison
operators.  Some examples:

     >>> IPv4Address('127.0.0.2') > IPv4Address('127.0.0.1')
     True
     >>> IPv4Address('127.0.0.2') == IPv4Address('127.0.0.1')
     False
     >>> IPv4Address('127.0.0.2') != IPv4Address('127.0.0.1')
     True


File: python.info,  Node: 算术运算符,  Prev: 比较运算符,  Up: 运算符<3>

5.21.28.7 算术运算符
....................

Integers can be added to or subtracted from address objects.  Some
examples:

     >>> IPv4Address('127.0.0.2') + 3
     IPv4Address('127.0.0.5')
     >>> IPv4Address('127.0.0.2') - 3
     IPv4Address('126.255.255.255')
     >>> IPv4Address('255.255.255.255') + 1
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     ipaddress.AddressValueError: 4294967296 (>= 2**32) is not permitted as an IPv4 address


File: python.info,  Node: IP网络的定义,  Next: Interface objects,  Prev: IP 地址,  Up: ipaddress --- IPv4/IPv6 操作库

5.21.28.8 IP网络的定义
......................

The *note IPv4Network: 3a8. and *note IPv6Network: 3a7. objects provide
a mechanism for defining and inspecting IP network definitions.  A
network definition consists of a `mask' and a `network address', and as
such defines a range of IP addresses that equal the network address when
masked (binary AND) with the mask.  For example, a network definition
with the mask ‘255.255.255.0’ and the network address ‘192.168.1.0’
consists of IP addresses in the inclusive range ‘192.168.1.0’ to
‘192.168.1.255’.

* Menu:

* Prefix, net mask and host mask: Prefix net mask and host mask.
* Network objects::
* 运算符: 运算符<4>.


File: python.info,  Node: Prefix net mask and host mask,  Next: Network objects,  Up: IP网络的定义

5.21.28.9 Prefix, net mask and host mask
........................................

There are several equivalent ways to specify IP network masks.  A
`prefix' ‘/<nbits>’ is a notation that denotes how many high-order bits
are set in the network mask.  A `net mask' is an IP address with some
number of high-order bits set.  Thus the prefix ‘/24’ is equivalent to
the net mask ‘255.255.255.0’ in IPv4, or ‘ffff:ff00::’ in IPv6.  In
addition, a `host mask' is the logical inverse of a `net mask', and is
sometimes used (for example in Cisco access control lists) to denote a
network mask.  The host mask equivalent to ‘/24’ in IPv4 is ‘0.0.0.255’.


File: python.info,  Node: Network objects,  Next: 运算符<4>,  Prev: Prefix net mask and host mask,  Up: IP网络的定义

5.21.28.10 Network objects
..........................

All attributes implemented by address objects are implemented by network
objects as well.  In addition, network objects implement additional
attributes.  All of these are common between *note IPv4Network: 3a8. and
*note IPv6Network: 3a7, so to avoid duplication they are only documented
for *note IPv4Network: 3a8.  Network objects are *note hashable: 1439,
so they can be used as keys in dictionaries.

 -- 类: ipaddress.IPv4Network (address, strict=True)

     Construct an IPv4 network definition.  `address' can be one of the
     following:

       1. A string consisting of an IP address and an optional mask,
          separated by a slash (‘/’).  The IP address is the network
          address, and the mask can be either a single number, which
          means it’s a `prefix', or a string representation of an IPv4
          address.  If it’s the latter, the mask is interpreted as a
          `net mask' if it starts with a non-zero field, or as a `host
          mask' if it starts with a zero field, with the single
          exception of an all-zero mask which is treated as a `net
          mask'.  If no mask is provided, it’s considered to be ‘/32’.

          For example, the following `address' specifications are
          equivalent: ‘192.168.1.0/24’, ‘192.168.1.0/255.255.255.0’ and
          ‘192.168.1.0/0.0.0.255’.

       2. An integer that fits into 32 bits.  This is equivalent to a
          single-address network, with the network address being
          `address' and the mask being ‘/32’.

       3. An integer packed into a *note bytes: 33a. object of length 4,
          big-endian.  The interpretation is similar to an integer
          `address'.

       4. A two-tuple of an address description and a netmask, where the
          address description is either a string, a 32-bits integer, a
          4-bytes packed integer, or an existing IPv4Address object; and
          the netmask is either an integer representing the prefix
          length (e.g.  ‘24’) or a string representing the prefix mask
          (e.g.  ‘255.255.255.0’).

     An *note AddressValueError: 2f1d. is raised if `address' is not a
     valid IPv4 address.  A *note NetmaskValueError: 2f42. is raised if
     the mask is not valid for an IPv4 address.

     If `strict' is ‘True’ and host bits are set in the supplied
     address, then *note ValueError: 1fc. is raised.  Otherwise, the
     host bits are masked out to determine the appropriate network
     address.

     Unless stated otherwise, all network methods accepting other
     network/address objects will raise *note TypeError: 193. if the
     argument’s IP version is incompatible to ‘self’.

     在 3.5 版更改: Added the two-tuple form for the `address'
     constructor parameter.

      -- 属性: version

      -- 属性: max_prefixlen

          Refer to the corresponding attribute documentation in *note
          IPv4Address: 2f15.

      -- 属性: is_multicast

      -- 属性: is_private

      -- 属性: is_unspecified

      -- 属性: is_reserved

      -- 属性: is_loopback

      -- 属性: is_link_local

          These attributes are true for the network as a whole if they
          are true for both the network address and the broadcast
          address.

      -- 属性: network_address

          The network address for the network.  The network address and
          the prefix length together uniquely define a network.

      -- 属性: broadcast_address

          The broadcast address for the network.  Packets sent to the
          broadcast address should be received by every host on the
          network.

      -- 属性: hostmask

          The host mask, as an *note IPv4Address: 2f15. object.

      -- 属性: netmask

          The net mask, as an *note IPv4Address: 2f15. object.

      -- 属性: with_prefixlen

      -- 属性: compressed

      -- 属性: exploded

          A string representation of the network, with the mask in
          prefix notation.

          ‘with_prefixlen’ and ‘compressed’ are always the same as
          ‘str(network)’.  ‘exploded’ uses the exploded form the network
          address.

      -- 属性: with_netmask

          A string representation of the network, with the mask in net
          mask notation.

      -- 属性: with_hostmask

          A string representation of the network, with the mask in host
          mask notation.

      -- 属性: num_addresses

          The total number of addresses in the network.

      -- 属性: prefixlen

          Length of the network prefix, in bits.

      -- 方法: hosts ()

          Returns an iterator over the usable hosts in the network.  The
          usable hosts are all the IP addresses that belong to the
          network, except the network address itself and the network
          broadcast address.  For networks with a mask length of 31, the
          network address and network broadcast address are also
          included in the result.  Networks with a mask of 32 will
          return a list containing the single host address.

               >>> list(ip_network('192.0.2.0/29').hosts())
               [IPv4Address('192.0.2.1'), IPv4Address('192.0.2.2'),
                IPv4Address('192.0.2.3'), IPv4Address('192.0.2.4'),
                IPv4Address('192.0.2.5'), IPv4Address('192.0.2.6')]
               >>> list(ip_network('192.0.2.0/31').hosts())
               [IPv4Address('192.0.2.0'), IPv4Address('192.0.2.1')]
               >>> list(ip_network('192.0.2.1/32').hosts())
               [IPv4Address('192.0.2.1')]

      -- 方法: overlaps (other)

          ‘True’ if this network is partly or wholly contained in
          `other' or `other' is wholly contained in this network.

      -- 方法: address_exclude (network)

          Computes the network definitions resulting from removing the
          given `network' from this one.  Returns an iterator of network
          objects.  Raises *note ValueError: 1fc. if `network' is not
          completely contained in this network.

               >>> n1 = ip_network('192.0.2.0/28')
               >>> n2 = ip_network('192.0.2.1/32')
               >>> list(n1.address_exclude(n2))
               [IPv4Network('192.0.2.8/29'), IPv4Network('192.0.2.4/30'),
                IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.0/32')]

      -- 方法: subnets (prefixlen_diff=1, new_prefix=None)

          The subnets that join to make the current network definition,
          depending on the argument values.  `prefixlen_diff' is the
          amount our prefix length should be increased by.  `new_prefix'
          is the desired new prefix of the subnets; it must be larger
          than our prefix.  One and only one of `prefixlen_diff' and
          `new_prefix' must be set.  Returns an iterator of network
          objects.

               >>> list(ip_network('192.0.2.0/24').subnets())
               [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]
               >>> list(ip_network('192.0.2.0/24').subnets(prefixlen_diff=2))
               [IPv4Network('192.0.2.0/26'), IPv4Network('192.0.2.64/26'),
                IPv4Network('192.0.2.128/26'), IPv4Network('192.0.2.192/26')]
               >>> list(ip_network('192.0.2.0/24').subnets(new_prefix=26))
               [IPv4Network('192.0.2.0/26'), IPv4Network('192.0.2.64/26'),
                IPv4Network('192.0.2.128/26'), IPv4Network('192.0.2.192/26')]
               >>> list(ip_network('192.0.2.0/24').subnets(new_prefix=23))
               Traceback (most recent call last):
                 File "<stdin>", line 1, in <module>
                   raise ValueError('new prefix must be longer')
               ValueError: new prefix must be longer
               >>> list(ip_network('192.0.2.0/24').subnets(new_prefix=25))
               [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]

      -- 方法: supernet (prefixlen_diff=1, new_prefix=None)

          The supernet containing this network definition, depending on
          the argument values.  `prefixlen_diff' is the amount our
          prefix length should be decreased by.  `new_prefix' is the
          desired new prefix of the supernet; it must be smaller than
          our prefix.  One and only one of `prefixlen_diff' and
          `new_prefix' must be set.  Returns a single network object.

               >>> ip_network('192.0.2.0/24').supernet()
               IPv4Network('192.0.2.0/23')
               >>> ip_network('192.0.2.0/24').supernet(prefixlen_diff=2)
               IPv4Network('192.0.0.0/22')
               >>> ip_network('192.0.2.0/24').supernet(new_prefix=20)
               IPv4Network('192.0.0.0/20')

      -- 方法: subnet_of (other)

          Return ‘True’ if this network is a subnet of `other'.

               >>> a = ip_network('192.168.1.0/24')
               >>> b = ip_network('192.168.1.128/30')
               >>> b.subnet_of(a)
               True

          3.7 新版功能.

      -- 方法: supernet_of (other)

          Return ‘True’ if this network is a supernet of `other'.

               >>> a = ip_network('192.168.1.0/24')
               >>> b = ip_network('192.168.1.128/30')
               >>> a.supernet_of(b)
               True

          3.7 新版功能.

      -- 方法: compare_networks (other)

          Compare this network to `other'.  In this comparison only the
          network addresses are considered; host bits aren’t.  Returns
          either ‘-1’, ‘0’ or ‘1’.

               >>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.2/32'))
               -1
               >>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.0/32'))
               1
               >>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.1/32'))
               0

          3.7 版后已移除: It uses the same ordering and comparison
          algorithm as "<", "==", and ">"

 -- 类: ipaddress.IPv6Network (address, strict=True)

     Construct an IPv6 network definition.  `address' can be one of the
     following:

       1. A string consisting of an IP address and an optional prefix
          length, separated by a slash (‘/’).  The IP address is the
          network address, and the prefix length must be a single
          number, the `prefix'.  If no prefix length is provided, it’s
          considered to be ‘/128’.

          Note that currently expanded netmasks are not supported.  That
          means ‘2001:db00::0/24’ is a valid argument while
          ‘2001:db00::0/ffff:ff00::’ not.

       2. An integer that fits into 128 bits.  This is equivalent to a
          single-address network, with the network address being
          `address' and the mask being ‘/128’.

       3. An integer packed into a *note bytes: 33a. object of length
          16, big-endian.  The interpretation is similar to an integer
          `address'.

       4. A two-tuple of an address description and a netmask, where the
          address description is either a string, a 128-bits integer, a
          16-bytes packed integer, or an existing IPv6Address object;
          and the netmask is an integer representing the prefix length.

     An *note AddressValueError: 2f1d. is raised if `address' is not a
     valid IPv6 address.  A *note NetmaskValueError: 2f42. is raised if
     the mask is not valid for an IPv6 address.

     If `strict' is ‘True’ and host bits are set in the supplied
     address, then *note ValueError: 1fc. is raised.  Otherwise, the
     host bits are masked out to determine the appropriate network
     address.

     在 3.5 版更改: Added the two-tuple form for the `address'
     constructor parameter.

      -- 属性: version

      -- 属性: max_prefixlen

      -- 属性: is_multicast

      -- 属性: is_private

      -- 属性: is_unspecified

      -- 属性: is_reserved

      -- 属性: is_loopback

      -- 属性: is_link_local

      -- 属性: network_address

      -- 属性: broadcast_address

      -- 属性: hostmask

      -- 属性: netmask

      -- 属性: with_prefixlen

      -- 属性: compressed

      -- 属性: exploded

      -- 属性: with_netmask

      -- 属性: with_hostmask

      -- 属性: num_addresses

      -- 属性: prefixlen

      -- 方法: hosts ()

          Returns an iterator over the usable hosts in the network.  The
          usable hosts are all the IP addresses that belong to the
          network, except the Subnet-Router anycast address.  For
          networks with a mask length of 127, the Subnet-Router anycast
          address is also included in the result.  Networks with a mask
          of 128 will return a list containing the single host address.

      -- 方法: overlaps (other)

      -- 方法: address_exclude (network)

      -- 方法: subnets (prefixlen_diff=1, new_prefix=None)

      -- 方法: supernet (prefixlen_diff=1, new_prefix=None)

      -- 方法: subnet_of (other)

      -- 方法: supernet_of (other)

      -- 方法: compare_networks (other)

          Refer to the corresponding attribute documentation in *note
          IPv4Network: 3a8.

      -- 属性: is_site_local

          These attribute is true for the network as a whole if it is
          true for both the network address and the broadcast address.


File: python.info,  Node: 运算符<4>,  Prev: Network objects,  Up: IP网络的定义

5.21.28.11 运算符
.................

Network objects support some operators.  Unless stated otherwise,
operators can only be applied between compatible objects (i.e.  IPv4
with IPv4, IPv6 with IPv6).

* Menu:

* Logical operators::
* 迭代: 迭代<2>.
* Networks as containers of addresses::


File: python.info,  Node: Logical operators,  Next: 迭代<2>,  Up: 运算符<4>

5.21.28.12 Logical operators
............................

Network objects can be compared with the usual set of logical operators.
Network objects are ordered first by network address, then by net mask.


File: python.info,  Node: 迭代<2>,  Next: Networks as containers of addresses,  Prev: Logical operators,  Up: 运算符<4>

5.21.28.13 迭代
...............

Network objects can be iterated to list all the addresses belonging to
the network.  For iteration, `all' hosts are returned, including
unusable hosts (for usable hosts, use the *note hosts(): 2f56. method).
An example:

     >>> for addr in IPv4Network('192.0.2.0/28'):
     ...     addr
     ...
     IPv4Address('192.0.2.0')
     IPv4Address('192.0.2.1')
     IPv4Address('192.0.2.2')
     IPv4Address('192.0.2.3')
     IPv4Address('192.0.2.4')
     IPv4Address('192.0.2.5')
     IPv4Address('192.0.2.6')
     IPv4Address('192.0.2.7')
     IPv4Address('192.0.2.8')
     IPv4Address('192.0.2.9')
     IPv4Address('192.0.2.10')
     IPv4Address('192.0.2.11')
     IPv4Address('192.0.2.12')
     IPv4Address('192.0.2.13')
     IPv4Address('192.0.2.14')
     IPv4Address('192.0.2.15')


File: python.info,  Node: Networks as containers of addresses,  Prev: 迭代<2>,  Up: 运算符<4>

5.21.28.14 Networks as containers of addresses
..............................................

Network objects can act as containers of addresses.  Some examples:

     >>> IPv4Network('192.0.2.0/28')[0]
     IPv4Address('192.0.2.0')
     >>> IPv4Network('192.0.2.0/28')[15]
     IPv4Address('192.0.2.15')
     >>> IPv4Address('192.0.2.6') in IPv4Network('192.0.2.0/28')
     True
     >>> IPv4Address('192.0.3.6') in IPv4Network('192.0.2.0/28')
     False


File: python.info,  Node: Interface objects,  Next: Other Module Level Functions,  Prev: IP网络的定义,  Up: ipaddress --- IPv4/IPv6 操作库

5.21.28.15 Interface objects
............................

Interface objects are *note hashable: 1439, so they can be used as keys
in dictionaries.

 -- 类: ipaddress.IPv4Interface (address)

     Construct an IPv4 interface.  The meaning of `address' is as in the
     constructor of *note IPv4Network: 3a8, except that arbitrary host
     addresses are always accepted.

     *note IPv4Interface: 2f19. is a subclass of *note IPv4Address:
     2f15, so it inherits all the attributes from that class.  In
     addition, the following attributes are available:

      -- 属性: ip

          The address (*note IPv4Address: 2f15.) without network
          information.

               >>> interface = IPv4Interface('192.0.2.5/24')
               >>> interface.ip
               IPv4Address('192.0.2.5')

      -- 属性: network

          The network (*note IPv4Network: 3a8.) this interface belongs
          to.

               >>> interface = IPv4Interface('192.0.2.5/24')
               >>> interface.network
               IPv4Network('192.0.2.0/24')

      -- 属性: with_prefixlen

          A string representation of the interface with the mask in
          prefix notation.

               >>> interface = IPv4Interface('192.0.2.5/24')
               >>> interface.with_prefixlen
               '192.0.2.5/24'

      -- 属性: with_netmask

          A string representation of the interface with the network as a
          net mask.

               >>> interface = IPv4Interface('192.0.2.5/24')
               >>> interface.with_netmask
               '192.0.2.5/255.255.255.0'

      -- 属性: with_hostmask

          A string representation of the interface with the network as a
          host mask.

               >>> interface = IPv4Interface('192.0.2.5/24')
               >>> interface.with_hostmask
               '192.0.2.5/0.0.0.255'

 -- 类: ipaddress.IPv6Interface (address)

     Construct an IPv6 interface.  The meaning of `address' is as in the
     constructor of *note IPv6Network: 3a7, except that arbitrary host
     addresses are always accepted.

     *note IPv6Interface: 2f1a. is a subclass of *note IPv6Address:
     2f16, so it inherits all the attributes from that class.  In
     addition, the following attributes are available:

      -- 属性: ip

      -- 属性: network

      -- 属性: with_prefixlen

      -- 属性: with_netmask

      -- 属性: with_hostmask

          Refer to the corresponding attribute documentation in *note
          IPv4Interface: 2f19.

* Menu:

* 运算符: 运算符<5>.


File: python.info,  Node: 运算符<5>,  Up: Interface objects

5.21.28.16 运算符
.................

Interface objects support some operators.  Unless stated otherwise,
operators can only be applied between compatible objects (i.e.  IPv4
with IPv4, IPv6 with IPv6).

* Menu:

* Logical operators: Logical operators<2>.


File: python.info,  Node: Logical operators<2>,  Up: 运算符<5>

5.21.28.17 Logical operators
............................

Interface objects can be compared with the usual set of logical
operators.

For equality comparison (‘==’ and ‘!=’), both the IP address and network
must be the same for the objects to be equal.  An interface will not
compare equal to any address or network object.

For ordering (‘<’, ‘>’, etc) the rules are different.  Interface and
address objects with the same IP version can be compared, and the
address objects will always sort before the interface objects.  Two
interface objects are first compared by their networks and, if those are
the same, then by their IP addresses.


File: python.info,  Node: Other Module Level Functions,  Next: Custom Exceptions,  Prev: Interface objects,  Up: ipaddress --- IPv4/IPv6 操作库

5.21.28.18 Other Module Level Functions
.......................................

The module also provides the following module level functions:

 -- 函数: ipaddress.v4_int_to_packed (address)

     Represent an address as 4 packed bytes in network (big-endian)
     order.  `address' is an integer representation of an IPv4 IP
     address.  A *note ValueError: 1fc. is raised if the integer is
     negative or too large to be an IPv4 IP address.

          >>> ipaddress.ip_address(3221225985)
          IPv4Address('192.0.2.1')
          >>> ipaddress.v4_int_to_packed(3221225985)
          b'\xc0\x00\x02\x01'

 -- 函数: ipaddress.v6_int_to_packed (address)

     Represent an address as 16 packed bytes in network (big-endian)
     order.  `address' is an integer representation of an IPv6 IP
     address.  A *note ValueError: 1fc. is raised if the integer is
     negative or too large to be an IPv6 IP address.

 -- 函数: ipaddress.summarize_address_range (first, last)

     Return an iterator of the summarized network range given the first
     and last IP addresses.  `first' is the first *note IPv4Address:
     2f15. or *note IPv6Address: 2f16. in the range and `last' is the
     last *note IPv4Address: 2f15. or *note IPv6Address: 2f16. in the
     range.  A *note TypeError: 193. is raised if `first' or `last' are
     not IP addresses or are not of the same version.  A *note
     ValueError: 1fc. is raised if `last' is not greater than `first' or
     if `first' address version is not 4 or 6.

          >>> [ipaddr for ipaddr in ipaddress.summarize_address_range(
          ...    ipaddress.IPv4Address('192.0.2.0'),
          ...    ipaddress.IPv4Address('192.0.2.130'))]
          [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), IPv4Network('192.0.2.130/32')]

 -- 函数: ipaddress.collapse_addresses (addresses)

     Return an iterator of the collapsed *note IPv4Network: 3a8. or
     *note IPv6Network: 3a7. objects.  `addresses' is an iterator of
     *note IPv4Network: 3a8. or *note IPv6Network: 3a7. objects.  A
     *note TypeError: 193. is raised if `addresses' contains mixed
     version objects.

          >>> [ipaddr for ipaddr in
          ... ipaddress.collapse_addresses([ipaddress.IPv4Network('192.0.2.0/25'),
          ... ipaddress.IPv4Network('192.0.2.128/25')])]
          [IPv4Network('192.0.2.0/24')]

 -- 函数: ipaddress.get_mixed_type_key (obj)

     Return a key suitable for sorting between networks and addresses.
     Address and Network objects are not sortable by default; they’re
     fundamentally different, so the expression:

          IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')

     doesn’t make sense.  There are some times however, where you may
     wish to have *note ipaddress: a3. sort these anyway.  If you need
     to do this, you can use this function as the `key' argument to
     *note sorted(): 44c.

     `obj' is either a network or address object.


File: python.info,  Node: Custom Exceptions,  Prev: Other Module Level Functions,  Up: ipaddress --- IPv4/IPv6 操作库

5.21.28.19 Custom Exceptions
............................

To support more specific error reporting from class constructors, the
module defines the following exceptions:

 -- 例外: ipaddress.AddressValueError (ValueError)

     Any value error related to the address.

 -- 例外: ipaddress.NetmaskValueError (ValueError)

     Any value error related to the net mask.


File: python.info,  Node: 多媒体服务,  Next: 国际化,  Prev: 互联网协议和支持,  Up: Python 标准库

5.22 多媒体服务
===============

本章描述的模块实现了主要用于多媒体应用的各种算法或接口。 它们可在安装时
自行决定。 这是一个概述：

* Menu:

* audioop: audioop --- 处理原始音频数据. 处理原始音频数据
* aifc: aifc --- 读写 AIFF 和 AIFC 文件. 读写 AIFF 和 AIFC 文件
* sunau: sunau --- 读写 Sun AU 文件. 读写 Sun AU 文件
* wave: wave --- 读写WAV格式文件. 读写WAV格式文件
* chunk: chunk --- 读取 IFF 分块数据. 读取 IFF 分块数据
* colorsys: colorsys --- 颜色系统间的转换. 颜色系统间的转换
* imghdr: imghdr --- 推测图像类型. 推测图像类型
* sndhdr: sndhdr --- 推测声音文件的类型. 推测声音文件的类型
* ossaudiodev: ossaudiodev --- 访问兼容OSS的音频设备. 访问兼容OSS的音频设备


File: python.info,  Node: audioop --- 处理原始音频数据,  Next: aifc --- 读写 AIFF 和 AIFC 文件,  Up: 多媒体服务

5.22.1 ‘audioop’ — 处理原始音频数据
-----------------------------------

__________________________________________________________________

*note audioop: d. 模块包含针对声音片段的一些有用操作。它操作的声音片段由
8、16、24 或 32 位宽的有符号整型样本组成，存储在 *note 类字节串对象:
5f1. 中。除非特别说明，否则所有标量项目均为整数。

在 3.4 版更改: 增加了对 24 位样本的支持。现在，所有函数都接受任何 *note
类字节串对象: 5f1.。而传入字符串会立即导致错误。

本模块提供对 a-LAW、u-LAW 和 Intel/DVI ADPCM 编码的支持。

部分更复杂的操作仅接受 16 位样本，而其他操作始终需要样本大小（以字节为单
位）作为该操作的参数。

此模块定义了下列变量和函数：

 -- 例外: audioop.error

     所有错误都会抛出此异常，比如样本的字节数未知等等。

 -- 函数: audioop.add (fragment1, fragment2, width)

     两个样本作为参数传入，返回一个片段，该片段是两个样本的和。`width' 是
     样本宽度（以字节为单位），可以取 ‘1’, ‘2’, ‘3’ 或 ‘4’。两个片段的长
     度应相同。如果发生溢出，较长的样本将被截断。

 -- 函数: audioop.adpcm2lin (adpcmfragment, width, state)

     将 Intel/DVI ADPCM 编码的片段解码为线性片段。关于 ADPCM 编码的详情
     请参阅 *note lin2adpcm(): 2f96. 的描述。返回一个元组 ‘(sample,
     newstate)’，其中 sample 的位宽由 `width' 指定。

 -- 函数: audioop.alaw2lin (fragment, width)

     将 a-LAW 编码的声音片段转换为线性编码声音片段。由于 a-LAW 编码样本
     始终为 8 位，因此这里的 `width' 仅指输出片段的样本位宽。

 -- 函数: audioop.avg (fragment, width)

     返回片段中所有样本的平均值。

 -- 函数: audioop.avgpp (fragment, width)

     返回片段中所有样本的平均峰峰值。由于没有进行过滤，因此该例程的实用
     性尚存疑。

 -- 函数: audioop.bias (fragment, width, bias)

     返回一个片段，该片段由原始片段中的每个样本加上偏差组成。在溢出时样
     本会回卷 (wrap around)。

 -- 函数: audioop.byteswap (fragment, width)

     “按字节交换”片段中的所有样本，返回修改后的片段。将大端序样本转换为
     小端序样本，反之亦然。

     3.4 新版功能.

 -- 函数: audioop.cross (fragment, width)

     将片段作为参数传入，返回其中过零点的数量。

 -- 函数: audioop.findfactor (fragment, reference)

     返回一个系数 `F' 使得 ‘rms(add(fragment, mul(reference, -F)))’ 最小
     ，即返回乘以 `reference' 后最匹配 `fragment' 的那个乘数。两个片段都
     应包含 2 字节宽的样本。

     本例程所需的时间与 ‘len(fragment)’ 成正比。

 -- 函数: audioop.findfit (fragment, reference)

     尽可能尝试让 `reference' 匹配 `fragment' 的一部分（`fragment' 应较
     长）。从概念上讲，完成这些靠从 `fragment' 中取出切片，使用 *note
     findfactor(): 2f9c. 计算最佳匹配，并最小化结果。两个片段都应包含 2
     字节宽的样本。返回一个元组 ‘(offset, factor)’，其中 `offset' 是在
     `fragment' 中的偏移量（整数），表示从此处开始最佳匹配，而 `factor'
     是由 *note findfactor(): 2f9c. 定义的因数（浮点数）。

 -- 函数: audioop.findmax (fragment, length)

     在 `fragment' 中搜索所有长度为 `length' 的样本切片（不是字节！）中
     ，能量最大的那一个切片，即返回 `i' 使得
     ‘rms(fragment[i*2:(i+length)*2])’ 最大。两个片段都应包含 2 字节宽的
     样本。

     本例程所需的时间与 ‘len(fragment)’ 成正比。

 -- 函数: audioop.getsample (fragment, width, index)

     返回片段中样本索引 `index' 的值。

 -- 函数: audioop.lin2adpcm (fragment, width, state)

     将样本转换为 4 位 Intel/DVI ADPCM 编码。ADPCM 编码是一种自适应编码
     方案，其中每个 4 比特数字是一个采样值与下一个采样值之间的差除以（不
     定的）步长。IMA 已选择使用 Intel/DVI ADPCM 算法，因此它很可能成为标
     准。

     `state' 是一个表示编码器状态的元组。编码器返回一个元组 ‘(adpcmfrag,
     newstate)’，而 `newstate' 要在下一次调用 *note lin2adpcm(): 2f96. 时
     传入。在初始调用中，可以将 ‘None’ 作为 state 传递。`adpcmfrag' 是
     ADPCM 编码的片段，每个字节打包了 2 个 4 比特值。

 -- 函数: audioop.lin2alaw (fragment, width)

     将音频片段中的采样值转换为 a-LAW 编码，并将其作为字节对象返回。
     a-LAW 是一种音频编码格式，仅使用 8 位样本即可获得大约 13 位的动态范
     围。Sun 音频硬件等使用该编码。

 -- 函数: audioop.lin2lin (fragment, width, newwidth)

     将采样在 1、2、3 和 4 字节格式之间转换。

          注解: 在某些音频格式（如 .WAV 文件）中，16、24 和 32 位采样是
          有符号的，但 8 位采样是无符号的。因此，当将这些格式转换为 8 位
          宽采样时，还需使结果加上 128:

               new_frames = audioop.lin2lin(frames, old_width, 1)
               new_frames = audioop.bias(new_frames, 1, 128)

          反之，将 8 位宽的采样转换为 16、24 或 32 位时，必须采用相同的
          处理。

 -- 函数: audioop.lin2ulaw (fragment, width)

     将音频片段中的采样值转换为 u-LAW 编码，并将其作为字节对象返回。
     u-LAW 是一种音频编码格式，仅使用 8 位采样即可获得大约 14 位的动态范
     围。Sun 音频硬件等使用该编码。

 -- 函数: audioop.max (fragment, width)

     返回片段中所有采样值的最大 `绝对值'。

 -- 函数: audioop.maxpp (fragment, width)

     返回声音片段中的最大峰峰值。

 -- 函数: audioop.minmax (fragment, width)

     返回声音片段中所有采样值的最小值和最大值组成的元组。

 -- 函数: audioop.mul (fragment, width, factor)

     返回一个片段，该片段由原始片段中的每个采样值乘以浮点值 `factor' 组
     成。如果发生溢出，采样将被截断。

 -- 函数: audioop.ratecv (fragment, width, nchannels, inrate, outrate,
          state[, weightA[, weightB]])

     转换输入片段的帧速率。

     `state' 是一个表示转换器状态的元组。转换器返回一个元组
     ‘(newfragment, newstate)’，而 `newstate' 要在下一次调用 *note
     ratecv(): 2fa7. 时传入。初始调用应传入 ‘None’ 作为 state。

     参数 `weightA' 和 `weightB' 是简单数字滤波器的参数，默认分别为 ‘1’
     和 ‘0’。

 -- 函数: audioop.reverse (fragment, width)

     将片段中的采样值反转，返回修改后的片段。

 -- 函数: audioop.rms (fragment, width)

     返回片段的均方根值，即 ‘sqrt(sum(S_i^2)/n)’。

     测量音频信号的能量。

 -- 函数: audioop.tomono (fragment, width, lfactor, rfactor)

     将立体声片段转换为单声道片段。左通道乘以 `lfactor'，右通道乘以
     `rfactor'，然后两个通道相加得到单声道信号。

 -- 函数: audioop.tostereo (fragment, width, lfactor, rfactor)

     由单声道片段生成立体声片段。立体声片段中的两对采样都是从单声道计算
     而来的，即左声道是乘以 `lfactor'，右声道是乘以 `rfactor'。

 -- 函数: audioop.ulaw2lin (fragment, width)

     将 u-LAW 编码的声音片段转换为线性编码声音片段。由于 u-LAW 编码采样
     值始终为 8 位，因此这里的 `width' 仅指输出片段的采样位宽。

请注意，诸如 *note mul(): 2fa6. 或 *note max(): 2fa3. 之类的操作在单声道
和立体声间没有区别，即所有采样都作相同处理。如果出现问题，应先将立体声片
段拆分为两个单声道片段，之后再重组。以下是如何进行该操作的示例:

     def mul_stereo(sample, width, lfactor, rfactor):
         lsample = audioop.tomono(sample, width, 1, 0)
         rsample = audioop.tomono(sample, width, 0, 1)
         lsample = audioop.mul(lsample, width, lfactor)
         rsample = audioop.mul(rsample, width, rfactor)
         lsample = audioop.tostereo(lsample, width, 1, 0)
         rsample = audioop.tostereo(rsample, width, 0, 1)
         return audioop.add(lsample, rsample, width)

如果使用 ADPCM 编码器构造网络数据包，并且希望协议是无状态的（即能够容忍
数据包丢失），则不仅需要传输数据，还应该传输状态。请注意，必须将*初始*状
态（传入 *note lin2adpcm(): 2f96. 的状态）发送给解码器，不能发送最终状态
（编码器返回的状态）。如果要使用 *note struct.Struct: 181d. 以二进制保存
状态，可以将第一个元素（预测值）用 16 位编码，将第二个元素（增量索引）用
8 位编码。

本 ADPCM 编码器从不与其他 ADPCM 编码器对立，仅针对自身。本开发者可能会误
读标准，这种情况下它们将无法与相应标准互操作。

乍看之下 ‘find*()’ 例程可能有些可笑。它们主要是用于回声消除，一种快速有
效的方法是选取输出样本中能量最高的片段，在输入样本中定位该片段，然后从输
入样本中减去整个输出样本:

     def echocancel(outputdata, inputdata):
         pos = audioop.findmax(outputdata, 800)    # one tenth second
         out_test = outputdata[pos*2:]
         in_test = inputdata[pos*2:]
         ipos, factor = audioop.findfit(in_test, out_test)
         # Optional (for better cancellation):
         # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
         #              out_test)
         prefill = '\0'*(pos+ipos)*2
         postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
         outputdata = prefill + audioop.mul(outputdata, 2, -factor) + postfill
         return audioop.add(inputdata, outputdata, 2)


File: python.info,  Node: aifc --- 读写 AIFF 和 AIFC 文件,  Next: sunau --- 读写 Sun AU 文件,  Prev: audioop --- 处理原始音频数据,  Up: 多媒体服务

5.22.2 ‘aifc’ — 读写 AIFF 和 AIFC 文件
--------------------------------------

`源代码：' Lib/aifc.py(1)

__________________________________________________________________

本模块提供读写 AIFF 和 AIFF-C 文件的支持。AIFF 是音频交换文件格式 (Audio
Interchange File Format)，一种用于在文件中存储数字音频采样的格式。AIFF-C
是该格式的更新版本，其中包括压缩音频数据的功能。

音频文件内有许多参数，用于描述音频数据。采样率或帧率是每秒对声音采样的次
数。通道数表示音频是单声道，双声道还是四声道。每个通道的每个帧包含一次采
样。采样大小是以字节表示的每次采样的大小。因此，一帧由 ‘nchannels *
samplesize’ （通道数*采样大小）字节组成，而一秒钟的音频包含 ‘nchannels *
samplesize * framerate’ （通道数*采样大小*帧率）字节。

例如，CD 质量的音频采样大小为 2 字节（16位），使用 2 个声道（立体声），
且帧速率为 44,100 帧/秒。这表示帧大小为 4 字节 (2*2)，一秒钟占用
2*2*44100 字节（176,400 字节）。

*note aifc: 5. 模块定义了以下函数：

 -- 函数: aifc.open (file, mode=None)

     打开一个 AIFF 或 AIFF-C 文件并返回一个对象实例，该实例具有下方描述
     的方法。参数 `file' 是文件名称字符串或 *note 文件对象: b4a.。当打开
     文件用于读取时，`mode' 必须为 ‘'r'’ 或 ‘'rb'’，当打开文件用于写入时
     ，`mode' 必须为 ‘'w'’ 或 ‘'wb'’。如果该参数省略，则使用 ‘file.mode’
     的值（如果有），否则使用 ‘'rb'’。当文件用于写入时，文件对象应该支持
     seek 操作，除非提前获知写入的采样总数，并使用 ‘writeframesraw()’ 和
     ‘setnframes()’。*note open(): 463. 函数可以在 *note with: 6f2. 语句
     中使用。当 ‘with’ 块执行完毕，将调用 *note close(): 825. 方法。

     在 3.4 版更改: 添加了对 *note with: 6f2. 语句的支持。

当打开文件用于读取时，由 *note open(): 463. 返回的对象有以下几种方法：

 -- 方法: aifc.getnchannels ()

     返回音频的通道数（单声道为 1，立体声为 2）。

 -- 方法: aifc.getsampwidth ()

     返回以字节表示的单个采样的大小。

 -- 方法: aifc.getframerate ()

     返回采样率（每秒的音频帧数）。

 -- 方法: aifc.getnframes ()

     返回文件中的音频帧总数。

 -- 方法: aifc.getcomptype ()

     返回一个长度为 4 的字节数组，描述了音频文件中使用的压缩类型。对于
     AIFF 文件，返回值为 ‘b'NONE'’。

 -- 方法: aifc.getcompname ()

     返回一个字节数组，可转换为人类可读的描述，描述的是音频文件中使用的
     压缩类型。对于 AIFF 文件，返回值为 ‘b'not compressed'’。

 -- 方法: aifc.getparams ()

     返回一个 *note namedtuple(): 1b7. ‘(nchannels, sampwidth,
     framerate, nframes, comptype, compname)’，与 ‘get*()’ 方法的输出相
     同。

 -- 方法: aifc.getmarkers ()

     返回一个列表，包含音频文件中的所有标记。标记由一个 3 元素的元组组成
     。第一个元素是标记 ID（整数），第二个是标记位置，从数据开头算起的帧
     数（整数），第三个是标记的名称（字符串）。

 -- 方法: aifc.getmark (id)

     根据传入的标记 `id' 返回元组，元组与 *note getmarkers(): 2fb5. 中描
     述的一致。

 -- 方法: aifc.readframes (nframes)

     从音频文件读取并返回后续 `nframes' 个帧。返回的数据是一个字符串，包
     含每个帧所有通道的未压缩采样值。

 -- 方法: aifc.rewind ()

     倒回读取指针。下一次 *note readframes(): 2fb7. 将从头开始。

 -- 方法: aifc.setpos (pos)

     移动读取指针到指定的帧上。

 -- 方法: aifc.tell ()

     返回当前的帧号。

 -- 方法: aifc.close ()

     关闭 AIFF 文件。调用此方法后，对象将无法再使用。

打开文件用于写入时，*note open(): 463. 返回的对象具有上述所有方法，但
‘readframes()’ 和 ‘setpos()’ 除外，并额外具备了以下方法。只有调用了
‘set*()’ 方法之后，才能调用相应的 ‘get*()’ 方法。在首次调用
‘writeframes()’ 或 ‘writeframesraw()’ 之前，必须填写除帧数以外的所有参数
。

 -- 方法: aifc.aiff ()

     创建一个 AIFF 文件，默认创建 AIFF-C 文件，除非文件名以 ‘'.aiff'’ 为
     后缀，在此情况下默认创建 AIFF 文件。

 -- 方法: aifc.aifc ()

     创建一个 AIFF-C 文件。 默认创建 AIFF-C 文件，除非文件名以 ‘'.aiff'’
     为后缀，在此情况下默认创建 AIFF 文件。

 -- 方法: aifc.setnchannels (nchannels)

     指明音频文件中的通道数。

 -- 方法: aifc.setsampwidth (width)

     指明以字节为单位的音频采样大小。

 -- 方法: aifc.setframerate (rate)

     指明以每秒帧数表示的采样频率。

 -- 方法: aifc.setnframes (nframes)

     指明要写入到音频文件的帧数。 如果未设定此形参或者未正确设定，则文件
     需要支持位置查找。

 -- 方法: aifc.setcomptype (type, name)

     指明压缩类型。 如果未指明，则音频数据将不会被压缩。 在 AIFF 文件中
     ，压缩是无法实现的。 name 参数应当为以字节数组表示的人类可读的压缩
     类型描述，type 参数应当为长度为 4 的字节数组。 目前支持的压缩类型如
     下: ‘b'NONE'’, ‘b'ULAW'’, ‘b'ALAW'’, ‘b'G722'’。

 -- 方法: aifc.setparams (nchannels, sampwidth, framerate, comptype,
          compname)

     一次性设置上述所有参数。 该参数是由多个形参组成的元组。 这意味着可
     以使用 *note getparams(): 824. 调用的结果作为 *note setparams():
     2fc2. 的参数。

 -- 方法: aifc.setmark (id, pos, name)

     添加具有给定 id (大于 0)，以及在给定位置上给定名称的标记。 此方法可
     在 *note close(): 825. 之前的任何时候被调用。

 -- 方法: aifc.tell ()

     返回输出文件中的当前写入位置。 适用于与 *note setmark(): 2fc3. 进行
     协同配合。

 -- 方法: aifc.writeframes (data)

     将数据写入到输出文件。 此方法只能在设置了音频文件形参之后被调用。

     在 3.4 版更改: 现在可接受任意 *note bytes-like object: 5f1.。

 -- 方法: aifc.writeframesraw (data)

     类似于 *note writeframes(): 827.，不同之处在于音频文件的标头不会被
     更新。

     在 3.4 版更改: 现在可接受任意 *note bytes-like object: 5f1.。

 -- 方法: aifc.close ()

     关闭 AIFF 文件。 文件的标头会被更新以反映音频数据的实际大小。 在调
     用此方法之后，对象将无法再被使用。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/aifc.py


File: python.info,  Node: sunau --- 读写 Sun AU 文件,  Next: wave --- 读写WAV格式文件,  Prev: aifc --- 读写 AIFF 和 AIFC 文件,  Up: 多媒体服务

5.22.3 ‘sunau’ — 读写 Sun AU 文件
---------------------------------

`源代码:' Lib/sunau.py(1)

__________________________________________________________________

*note sunau: fb. 模拟提供了一个处理 Sun AU 声音格式的便利接口。请注意此
模块与 *note aifc: 5. 和 *note wave: 128. 是兼容接口的。

音频文件由标头和数据组成。标头的字段为：

域                  目录
                    
------------------------------------------------------------------------
                    
magic word          四个字节 ‘.snd’
                    
                    
header size         标头的大小，包括信息，以字节为单位。
                    
                    
data size           数据的物理大小，以字节为单位。
                    
                    
编码                指示音频样本的编码方式。
                    
                    
sample rate         采样率
                    
                    
# of channels       采样中的通道数。
                    
                    
info                提供音频文件描述的ASCII字符串（用空字节填充）。
                    

Apart from the info field, all header fields are 4 bytes in size.  They
are all 32-bit unsigned integers encoded in big-endian byte order.

The *note sunau: fb. module defines the following functions:

 -- 函数: sunau.open (file, mode)

     If `file' is a string, open the file by that name, otherwise treat
     it as a seekable file-like object.  `mode' can be any of

     ‘'r'’

          只读模式。

     ‘'w'’

          只写模式。

     Note that it does not allow read/write files.

     A `mode' of ‘'r'’ returns an ‘AU_read’ object, while a `mode' of
     ‘'w'’ or ‘'wb'’ returns an ‘AU_write’ object.

 -- 函数: sunau.openfp (file, mode)

     同 *note open(): 47a.，用于向后兼容。

     Deprecated since version 3.7, will be removed in version 3.9.

The *note sunau: fb. module defines the following exception:

 -- 例外: sunau.Error

     An error raised when something is impossible because of Sun AU
     specs or implementation deficiency.

The *note sunau: fb. module defines the following data items:

 -- 数据: sunau.AUDIO_FILE_MAGIC

     An integer every valid Sun AU file begins with, stored in
     big-endian form.  This is the string ‘.snd’ interpreted as an
     integer.

 -- 数据: sunau.AUDIO_FILE_ENCODING_MULAW_8
 -- 数据: sunau.AUDIO_FILE_ENCODING_LINEAR_8
 -- 数据: sunau.AUDIO_FILE_ENCODING_LINEAR_16
 -- 数据: sunau.AUDIO_FILE_ENCODING_LINEAR_24
 -- 数据: sunau.AUDIO_FILE_ENCODING_LINEAR_32
 -- 数据: sunau.AUDIO_FILE_ENCODING_ALAW_8

     Values of the encoding field from the AU header which are supported
     by this module.

 -- 数据: sunau.AUDIO_FILE_ENCODING_FLOAT
 -- 数据: sunau.AUDIO_FILE_ENCODING_DOUBLE
 -- 数据: sunau.AUDIO_FILE_ENCODING_ADPCM_G721
 -- 数据: sunau.AUDIO_FILE_ENCODING_ADPCM_G722
 -- 数据: sunau.AUDIO_FILE_ENCODING_ADPCM_G723_3
 -- 数据: sunau.AUDIO_FILE_ENCODING_ADPCM_G723_5

     Additional known values of the encoding field from the AU header,
     but which are not supported by this module.

* Menu:

* AU_read 对象::
* AU_write 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/sunau.py


File: python.info,  Node: AU_read 对象,  Next: AU_write 对象,  Up: sunau --- 读写 Sun AU 文件

5.22.3.1 AU_read 对象
.....................

AU_read objects, as returned by *note open(): 47a. above, have the
following methods:

 -- 方法: AU_read.close ()

     Close the stream, and make the instance unusable.  (This is called
     automatically on deletion.)

 -- 方法: AU_read.getnchannels ()

     Returns number of audio channels (1 for mono, 2 for stereo).

 -- 方法: AU_read.getsampwidth ()

     返回采样字节长度。

 -- 方法: AU_read.getframerate ()

     返回采样频率。

 -- 方法: AU_read.getnframes ()

     返回音频总帧数。

 -- 方法: AU_read.getcomptype ()

     Returns compression type.  Supported compression types are
     ‘'ULAW'’, ‘'ALAW'’ and ‘'NONE'’.

 -- 方法: AU_read.getcompname ()

     Human-readable version of *note getcomptype(): 2fdb.  The supported
     types have the respective names ‘'CCITT G.711 u-law'’, ‘'CCITT
     G.711 A-law'’ and ‘'not compressed'’.

 -- 方法: AU_read.getparams ()

     返回一个 *note namedtuple(): 1b7. ‘(nchannels, sampwidth,
     framerate, nframes, comptype, compname)’，与 ‘get*()’ 方法的输出相
     同。

 -- 方法: AU_read.readframes (n)

     Reads and returns at most `n' frames of audio, as a *note bytes:
     33a. object.  The data will be returned in linear format.  If the
     original data is in u-LAW format, it will be converted.

 -- 方法: AU_read.rewind ()

     重置文件指针至音频开头.

以下两个方法都使用指针，具体实现由其底层决定。

 -- 方法: AU_read.setpos (pos)

     Set the file pointer to the specified position.  Only values
     returned from *note tell(): 2fe1. should be used for `pos'.

 -- 方法: AU_read.tell ()

     Return current file pointer position.  Note that the returned value
     has nothing to do with the actual position in the file.

The following two functions are defined for compatibility with the *note
aifc: 5, and don’t do anything interesting.

 -- 方法: AU_read.getmarkers ()

     返回 ‘None’。

 -- 方法: AU_read.getmark (id)

     引发错误异常。


File: python.info,  Node: AU_write 对象,  Prev: AU_read 对象,  Up: sunau --- 读写 Sun AU 文件

5.22.3.2 AU_write 对象
......................

AU_write objects, as returned by *note open(): 47a. above, have the
following methods:

 -- 方法: AU_write.setnchannels (n)

     设置声道数。

 -- 方法: AU_write.setsampwidth (n)

     Set the sample width (in bytes.)

     在 3.4 版更改: Added support for 24-bit samples.

 -- 方法: AU_write.setframerate (n)

     Set the frame rate.

 -- 方法: AU_write.setnframes (n)

     Set the number of frames.  This can be later changed, when and if
     more frames are written.

 -- 方法: AU_write.setcomptype (type, name)

     Set the compression type and description.  Only ‘'NONE'’ and
     ‘'ULAW'’ are supported on output.

 -- 方法: AU_write.setparams (tuple)

     The `tuple' should be ‘(nchannels, sampwidth, framerate, nframes,
     comptype, compname)’, with values valid for the ‘set*()’ methods.
     Set all parameters.

 -- 方法: AU_write.tell ()

     Return current position in the file, with the same disclaimer for
     the *note AU_read.tell(): 2fe1. and *note AU_read.setpos(): 2fe0.
     methods.

 -- 方法: AU_write.writeframesraw (data)

     写入音频数据但不更新 `nframes'。

     在 3.4 版更改: 现在可接受任意 *note bytes-like object: 5f1.。

 -- 方法: AU_write.writeframes (data)

     写入音频数据并更新 `nframes'。

     在 3.4 版更改: 现在可接受任意 *note bytes-like object: 5f1.。

 -- 方法: AU_write.close ()

     Make sure `nframes' is correct, and close the file.

     This method is called upon deletion.

Note that it is invalid to set any parameters after calling
‘writeframes()’ or ‘writeframesraw()’.


File: python.info,  Node: wave --- 读写WAV格式文件,  Next: chunk --- 读取 IFF 分块数据,  Prev: sunau --- 读写 Sun AU 文件,  Up: 多媒体服务

5.22.4 ‘wave’ — 读写WAV格式文件
-------------------------------

`源代码:' Lib/wave.py(1)

__________________________________________________________________

*note wave: 128. 模块提供了一个处理 WAV 声音格式的便利接口。它不支持压缩
/解压，但是支持单声道/立体声。

*note wave: 128. 模块定义了以下函数和异常:

 -- 函数: wave.open (file, mode=None)

     如果 `file' 是一个字符串，打开对应文件名的文件。否则就把它作为文件
     类对象来处理。`mode' 可以为以下值：

     ‘'rb'’

          只读模式。

     ‘'wb'’

          只写模式。

     注意不支持同时读写WAV文件。

     `mode' 设为 ‘'rb'’ 时返回一个 ‘Wave_read’ 对象，而 `mode' 设为
     ‘'wb'’ 时返回一个 ‘Wave_write’ 对象。如果省略 `mode' 并指定 `file'
     来传入一个文件类对象，则 ‘file.mode’ 会被用作 `mode' 的默认值。

     如果操作的是文件对象，当使用 wave 对象的 ‘close()’ 方法时，并不会真
     正关闭文件对象，这需要调用者负责来关闭文件对象。

     *note open(): 47e. 函数可以在 *note with: 6f2. 语句中使用。 当
     ‘with’ 阻塞结束时，*note Wave_read.close(): 2fef. 或 *note
     Wave_write.close(): 2ff0. 方法会被调用。

     在 3.4 版更改: 添加了对不可搜索文件的支持。

 -- 函数: wave.openfp (file, mode)

     同 *note open(): 47e.，用于向后兼容。

     Deprecated since version 3.7, will be removed in version 3.9.

 -- 例外: wave.Error

     当不符合WAV格式或无法操作时引发的错误。

* Menu:

* Wave_read对象::
* Wave_write 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/wave.py


File: python.info,  Node: Wave_read对象,  Next: Wave_write 对象,  Up: wave --- 读写WAV格式文件

5.22.4.1 Wave_read对象
......................

由 *note open(): 47e. 返回的 Wave_read 对象，有以下几种方法:

 -- 方法: Wave_read.close ()

     关闭 *note wave: 128. 打开的数据流并使对象不可用。当对象销毁时会自
     动调用。

 -- 方法: Wave_read.getnchannels ()

     返回声道数量（‘1’ 为单声道，‘2’ 为立体声）

 -- 方法: Wave_read.getsampwidth ()

     返回采样字节长度。

 -- 方法: Wave_read.getframerate ()

     返回采样频率。

 -- 方法: Wave_read.getnframes ()

     返回音频总帧数。

 -- 方法: Wave_read.getcomptype ()

     返回压缩类型（只支持 ‘'NONE'’ 类型）

 -- 方法: Wave_read.getcompname ()

     *note getcomptype(): 2ff8. 的通俗版本。使用 ‘'not compressed'’ 代替
     ‘'NONE'’。

 -- 方法: Wave_read.getparams ()

     返回一个 *note namedtuple(): 1b7. ‘(nchannels, sampwidth,
     framerate, nframes, comptype, compname)’，与 ‘get*()’ 方法的输出相
     同。

 -- 方法: Wave_read.readframes (n)

     读取并返回以 *note bytes: 33a. 对象表示的最多 `n' 帧音频。

 -- 方法: Wave_read.rewind ()

     重置文件指针至音频开头.

后面两个方法是为了和 *note aifc: 5. 保持兼容，实际不做任何事情。

 -- 方法: Wave_read.getmarkers ()

     返回 ‘None’。

 -- 方法: Wave_read.getmark (id)

     引发错误异常。

以下两个方法都使用指针，具体实现由其底层决定。

 -- 方法: Wave_read.setpos (pos)

     设置文件指针到指定位置。

 -- 方法: Wave_read.tell ()

     返回当前文件指针位置。


File: python.info,  Node: Wave_write 对象,  Prev: Wave_read对象,  Up: wave --- 读写WAV格式文件

5.22.4.2 Wave_write 对象
........................

对于可查找的输出流，‘wave’ 头将自动更新以反映实际写入的帧数。 对于不可查
找的流，当写入第一帧时 `nframes' 值必须准确。 获取准确的 `nframes' 值可
以通过调用 *note setnframes(): 3002. 或 *note setparams(): 3003. 并附带
*note close(): 2ff0. 被调用之前将要写入的帧数，然后使用 *note
writeframesraw(): 914. 来写入帧数据，或者通过调用 *note writeframes():
915. 并附带所有要写入的帧。 在后一种情况下 *note writeframes(): 915. 将
计算数据中的帧数并在写入帧数据之前相应地设置 `nframes'。

由 *note open(): 47e. 返回的 Wave_write 对象，有以下几种方法:

在 3.4 版更改: 添加了对不可搜索文件的支持。

 -- 方法: Wave_write.close ()

     确保 `nframes' 是正确的，并在文件被 *note wave: 128. 打开时关闭它。
     此方法会在对象收集时被调用。 如果输出流不可查找且 `nframes' 与实际
     写入的帧数不匹配时引发异常。

 -- 方法: Wave_write.setnchannels (n)

     设置声道数。

 -- 方法: Wave_write.setsampwidth (n)

     设置采样字节长度为 `n'。

 -- 方法: Wave_write.setframerate (n)

     设置采样频率为 `n'。

     在 3.2 版更改: 对此方法的非整数输入会被舍入到最接近的整数。

 -- 方法: Wave_write.setnframes (n)

     设置总帧数为 `n'。 如果与之后实际写入的帧数不一致此值将会被更改（ 如
     果输出流不可查找则此更改尝试将引发错误）。

 -- 方法: Wave_write.setcomptype (type, name)

     设置压缩格式。目前只支持 ‘NONE’ 即无压缩格式。

 -- 方法: Wave_write.setparams (tuple)

     `tuple' 应该是 ‘(nchannels, sampwidth, framerate, nframes,
     comptype, compname)’，每项的值应可用于 ‘set*()’ 方法。设置所有形参
     。

 -- 方法: Wave_write.tell ()

     返回当前文件指针，其指针含义和 *note Wave_read.tell(): 3000. 以及
     *note Wave_read.setpos(): 2fff. 是一致的。

 -- 方法: Wave_write.writeframesraw (data)

     写入音频数据但不更新 `nframes'。

     在 3.4 版更改: 现在可接受任意 *note bytes-like object: 5f1.。

 -- 方法: Wave_write.writeframes (data)

     写入音频帧并确保 `nframes' 是正确的。 如果输出流不可查找且在 `data'
     被写入之后写入的总帧数与之前设定的has been written does not match
     the previously set value for `nframes' 值不匹配将会引发错误。

     在 3.4 版更改: 现在可接受任意 *note bytes-like object: 5f1.。

注意在调用 ‘writeframes()’ 或 ‘writeframesraw()’ 之后再设置任何格式参数
是无效的，而且任何这样的尝试将引发 *note wave.Error: 2ff1.。


File: python.info,  Node: chunk --- 读取 IFF 分块数据,  Next: colorsys --- 颜色系统间的转换,  Prev: wave --- 读写WAV格式文件,  Up: 多媒体服务

5.22.5 ‘chunk’ — 读取 IFF 分块数据
----------------------------------

`源代码:' Lib/chunk.py(1)

__________________________________________________________________

本模块提供了一个读取使用 EA IFF 85 分块的数据的接口chunks.  (2) 这种格式
使用的场合有 Audio Interchange File Format (AIFF/AIFF-C) 和 Real Media
File Format (RMFF) 等。 与它们密切相关的 WAVE 音频文件也可使用此模块来读
取。

一个分块具有以下结构:

偏移          长度         目录
                           
---------------------------------------------------------------
                           
0             4            区块ID
                           
                           
4             4            大端字节顺序的块大小，不包括头
                           
                           
8             `n'          数据字节，其中 `n' 是前一字段中给
                           出的大小
                           
                           
8 + `n'       0 或 1       如果 `n' 为奇数且使用块对齐，则需
                           要填充字节
                           

ID是一个4字节的字符串，用于标识块的类型。

大小字段（32 位的值，使用大端字节序编码）给出分块数据的大小，不包括 8 字
节的标头。

使用由一个或更多分块组成的 IFF 类型文件。 此处定义的 *note Chunk: 300b.
类的建议使用方式是在每个分块开始时实例化一个实例并从实例读取直到其末尾，
在那之后可以再实例化新的实例。 到达文件末尾时，创建新实例将会失败并引发
*note EOFError: c74. 异常。

 -- 类: chunk.Chunk (file, align=True, bigendian=True, inclheader=False)

     代表一个分块的类。 `file' 参数预期为一个文件类对象。 特别地也允许该
     类的实例。 唯一必需的方法是 ‘read()’。 如果存在 *note seek(): 1da7.
     和 *note tell(): 1da8. 方法并且没有引发异常，它们也会被使用。 如果
     存在这些方法并且引发了异常，则它们不应改变目标对象。 如果可选参数
     `align' 为真值，则分块应当以 2 字节边界对齐。 如果 `align' 为假值，
     则不使用对齐。 此参数默认为真值。 如果可选参数 `bigendian' 为假值，
     分块大小应当为小端序。 这对于 WAVE 音频文件是必须的。 此参数默认为
     真值。 如果可选参数 `inclheader' 为真值，则分块标头中给出的大小将包
     括标头的大小。 此参数默认为假值。

     *note Chunk: 300b. 对象支持下列方法：

      -- 方法: getname ()

          返回分块的名称（ID）。 这是分块的头 4 个字节。

      -- 方法: getsize ()

          返回分块的大小。

      -- 方法: close ()

          关闭并跳转到分块的末尾。 这不会关闭下层的文件。

     在 *note close(): 300e. 方法已被调用后其余方法将会引发 *note
     OSError: 1d4.。 在 Python 3.3 之前，它们曾会引发 *note IOError:
     99a.，现在这是 *note OSError: 1d4. 的一个别名。

      -- 方法: isatty ()

          返回 ‘False’。

      -- 方法: seek (pos, whence=0)

          设置分块的当前位置。 `whence' 参数为可选项并且默认为 ‘0’ (绝对
          文件定位)；其他值还有 ‘1’ (相对当前位置查找) 和 ‘2’ (相对文件
          末尾查找)。 没有返回值。 如果下层文件不支持查找，则只允许向前
          查找。

      -- 方法: tell ()

          将当前位置返回到分块。

      -- 方法: read (size=-1)

          从分块读取至多 `size' 个字节（如果在获得 `size' 个字节之前已到
          达分块末尾则读取的字节会少于此数量）。 如果 `size' 参数为负值
          或被省略，则读取所有字节直到分块末尾。 当立即遇到分块末尾则返
          回空字节串对象。

      -- 方法: skip ()

          跳到分块末尾。此后对分块再次调用 *note read(): 3012. 将返回
          ‘b''’。 如果你对分块的内容不感兴趣，则应当调用此方法以使文件指
          向下一分块的开头。

备注
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/chunk.py

   (2) (1) "EA IFF 85" 交换格式文件标准, Jerry Morrison, Electronic
Arts, 1985 年 1 月。


File: python.info,  Node: colorsys --- 颜色系统间的转换,  Next: imghdr --- 推测图像类型,  Prev: chunk --- 读取 IFF 分块数据,  Up: 多媒体服务

5.22.6 ‘colorsys’ — 颜色系统间的转换
------------------------------------

`源代码：' Lib/colorsys.py(1)

__________________________________________________________________

*note colorsys: 20. 模块定义了计算机显示器所用的 RGB (Red Green Blue) 色
彩空间与三种其他色彩坐标系统 YIQ, HLS (Hue Lightness Saturation) 和 HSV
(Hue Saturation Value) 表示的颜色值之间的双向转换。 所有这些色彩空间的坐
标都使用浮点数值来表示。 在 YIQ 空间中，Y 坐标取值为 0 和 1 之间，而 I 和
Q 坐标均可以为正数或负数。 在所有其他空间中，坐标取值均为 0 和 1 之间。

参见
....

有关色彩空间的更多信息可访问 ‘http://poynton.ca/ColorFAQ.html’ 和
‘https://www.cambridgeincolour.com/tutorials/color-spaces.htm’.

*note colorsys: 20. 模块定义了如下函数：

 -- 函数: colorsys.rgb_to_yiq (r, g, b)

     把颜色从RGB值转为YIQ值。

 -- 函数: colorsys.yiq_to_rgb (y, i, q)

     把颜色从YIQ值转为RGB值。

 -- 函数: colorsys.rgb_to_hls (r, g, b)

     把颜色从RGB值转为HLS值。

 -- 函数: colorsys.hls_to_rgb (h, l, s)

     把颜色从HLS值转为RGB值。

 -- 函数: colorsys.rgb_to_hsv (r, g, b)

     把颜色从RGB值转为HSV值。

 -- 函数: colorsys.hsv_to_rgb (h, s, v)

     把颜色从HSV值转为RGB值。

示例:

     >>> import colorsys
     >>> colorsys.rgb_to_hsv(0.2, 0.4, 0.4)
     (0.5, 0.5, 0.4)
     >>> colorsys.hsv_to_rgb(0.5, 0.5, 0.4)
     (0.2, 0.4, 0.4)

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/colorsys.py


File: python.info,  Node: imghdr --- 推测图像类型,  Next: sndhdr --- 推测声音文件的类型,  Prev: colorsys --- 颜色系统间的转换,  Up: 多媒体服务

5.22.7 ‘imghdr’ — 推测图像类型
------------------------------

`源代码' Lib/imghdr.py(1)

__________________________________________________________________

*note imghdr: 99. 模块推测文件或字节流中的图像的类型。

*note imghdr: 99. 模块定义了以下类型：

 -- 函数: imghdr.what (filename, h=None)

     测试包含在命名为 `filename' 的文件中的图像数据，并且返回描述此类图
     片的字符串。如果可选的 `h' 被提供， `filename' 将被忽略并且 `h' 包
     含将被测试的二进制流。

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

接下来的图像类型是可识别的，返回值来自 *note what(): 6f6.：

值               图像格式
                 
---------------------------------------------------------
                 
‘'rgb'’          SGI 图像库文件
                 
                 
‘'gif'’          GIF 87a 和 89a 文件
                 
                 
‘'pbm'’          便携式位图文件
                 
                 
‘'pgm'’          便携式灰度图文件
                 
                 
‘'ppm'’          便携式像素表文件
                 
                 
‘'tiff'’         TIFF 文件
                 
                 
‘'rast'’         Sun 光栅文件
                 
                 
‘'xbm'’          X 位图文件
                 
                 
‘'jpeg'’         JFIF 或 Exif 格式的 JPEG 数据
                 
                 
‘'bmp'’          BMP 文件
                 
                 
‘'png'’          便携式网络图像
                 
                 
‘'webp'’         WebP 文件
                 
                 
‘'exr'’          OpenEXR 文件
                 

3.5 新版功能: `exr' 和 `webp' 格式被添加。

你可以扩展此 *note imghdr: 99. 可以被追加的这个变量识别的文件格式的列表
：

 -- 数据: imghdr.tests

     执行单个测试的函数列表。每个函数都有两个参数：字节流和类似开放文件
     的对象。当 *note what(): 6f6. 用字节流调用时，类文件对象将是
     ‘None’。

     如果测试成功，这个测试函数应当返回一个描述图像类型的字符串，否则返
     回 ‘None’。

示例:

     >>> import imghdr
     >>> imghdr.what('bass.gif')
     'gif'

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/imghdr.py


File: python.info,  Node: sndhdr --- 推测声音文件的类型,  Next: ossaudiodev --- 访问兼容OSS的音频设备,  Prev: imghdr --- 推测图像类型,  Up: 多媒体服务

5.22.8 ‘sndhdr’ — 推测声音文件的类型
------------------------------------

`源代码' Lib/sndhdr.py(1)

__________________________________________________________________

*note sndhdr: ef. 提供了企图猜测文件中的声音数据类型的功能函数。当这些函
数可以推测出存储在文件中的声音数据的类型是，它们返回一个 *note
collections.namedtuple(): 1b7.，包含了五种属性：（‘filetype’,
‘framerate’, ‘nchannels’, ‘nframes’, ‘sampwidth’）。这些 `type' 的值表示
数据的类型，会是以下字符串之一： ‘'aifc'’, ‘'aiff'’, ‘'au'’, ‘'hcom'’,
‘'sndr'’, ‘'sndt'’, ‘'voc'’, ‘'wav'’, ‘'8svx'’, ‘'sb'’, ‘'ub'’, or
‘'ul'’ 。 `sampling_rate' 可能是实际值或者当未知或者难以解码时的 ‘0’。类
似的， `channels' 也会返回实际值或者在无法推测或者难以解码时返回 ‘0’。
`frames' 则是实际值或 ‘-1’。 元组的最后一项， `bits_per_sample' 将会为比
特表示的 sample 大小或者 A-LAW 时为 ‘'A'’， u-LAW 时为 ‘'U'’。

 -- 函数: sndhdr.what (filename)

     使用 *note whathdr(): 751. 推测存储在 `filename' 文件中的声音数据的
     类型。如果成功，返回上述的命名元组，否则返回 ‘None’。

     在 3.5 版更改: 将结果从元组改为命名元组。

 -- 函数: sndhdr.whathdr (filename)

     基于文件头推测存储在文件中的声音数据类型。文件名由 `filename' 给出
     。这个函数在成功时返回上述命名元组，或者在失败时返回 ‘None’。

     在 3.5 版更改: 将结果从元组改为命名元组。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/sndhdr.py


File: python.info,  Node: ossaudiodev --- 访问兼容OSS的音频设备,  Prev: sndhdr --- 推测声音文件的类型,  Up: 多媒体服务

5.22.9 ‘ossaudiodev’ — 访问兼容OSS的音频设备
--------------------------------------------

__________________________________________________________________

该模块允许您访问 OSS（开放式音响系统）音频接口。 OSS 可用于广泛的开源和
商业 Unices，并且是 Linux 和最新版本的 FreeBSD 的标准音频接口。

在 3.3 版更改: 此模块中过去会引发 *note IOError: 99a. 的操作现在将引发
*note OSError: 1d4.。

参见
....

开放之声系统程序员手册(1)

     OSS C API 的官方文档

该模块定义了大量由OSS设备驱动提供的常量； 请参阅‘‘<sys/soundcard.h>‘‘
Linux 或 FreeBSD 上的列表。

*note ossaudiodev: c7. defines the following variables and functions:

 -- 例外: ossaudiodev.OSSAudioError

     This exception is raised on certain errors.  The argument is a
     string describing what went wrong.

     (If *note ossaudiodev: c7. receives an error from a system call
     such as ‘open()’, ‘write()’, or ‘ioctl()’, it raises *note OSError:
     1d4.  Errors detected directly by *note ossaudiodev: c7. result in
     *note OSSAudioError: 3023.)

     (For backwards compatibility, the exception class is also available
     as ‘ossaudiodev.error’.)

 -- 函数: ossaudiodev.open (mode)

 -- 函数: ossaudiodev.open (device, mode)

     Open an audio device and return an OSS audio device object.  This
     object supports many file-like methods, such as ‘read()’,
     ‘write()’, and ‘fileno()’ (although there are subtle differences
     between conventional Unix read/write semantics and those of OSS
     audio devices).  It also supports a number of audio-specific
     methods; see below for the complete list of methods.

     `device' is the audio device filename to use.  If it is not
     specified, this module first looks in the environment variable
     ‘AUDIODEV’ for a device to use.  If not found, it falls back to
     ‘/dev/dsp’.

     `mode' is one of ‘'r'’ for read-only (record) access, ‘'w'’ for
     write-only (playback) access and ‘'rw'’ for both.  Since many sound
     cards only allow one process to have the recorder or player open at
     a time, it is a good idea to open the device only for the activity
     needed.  Further, some sound cards are half-duplex: they can be
     opened for reading or writing, but not both at once.

     Note the unusual calling syntax: the `first' argument is optional,
     and the second is required.  This is a historical artifact for
     compatibility with the older ‘linuxaudiodev’ module which *note
     ossaudiodev: c7. supersedes.

 -- 函数: ossaudiodev.openmixer ([device])

     Open a mixer device and return an OSS mixer device object.
     `device' is the mixer device filename to use.  If it is not
     specified, this module first looks in the environment variable
     ‘MIXERDEV’ for a device to use.  If not found, it falls back to
     ‘/dev/mixer’.

* Menu:

* Audio Device Objects::
* Mixer Device Objects::

   ---------- Footnotes ----------

   (1) http://www.opensound.com/pguide/oss.pdf


File: python.info,  Node: Audio Device Objects,  Next: Mixer Device Objects,  Up: ossaudiodev --- 访问兼容OSS的音频设备

5.22.9.1 Audio Device Objects
.............................

Before you can write to or read from an audio device, you must call
three methods in the correct order:

  1. ‘setfmt()’ to set the output format

  2. ‘channels()’ to set the number of channels

  3. ‘speed()’ to set the sample rate

Alternately, you can use the ‘setparameters()’ method to set all three
audio parameters at once.  This is more convenient, but may not be as
flexible in all cases.

The audio device objects returned by *note open(): 3024. define the
following methods and (read-only) attributes:

 -- 方法: oss_audio_device.close ()

     Explicitly close the audio device.  When you are done writing to or
     reading from an audio device, you should explicitly close it.  A
     closed device cannot be used again.

 -- 方法: oss_audio_device.fileno ()

     Return the file descriptor associated with the device.

 -- 方法: oss_audio_device.read (size)

     Read `size' bytes from the audio input and return them as a Python
     string.  Unlike most Unix device drivers, OSS audio devices in
     blocking mode (the default) will block *note read(): 302a. until
     the entire requested amount of data is available.

 -- 方法: oss_audio_device.write (data)

     Write a *note bytes-like object: 5f1. `data' to the audio device
     and return the number of bytes written.  If the audio device is in
     blocking mode (the default), the entire data is always written
     (again, this is different from usual Unix device semantics).  If
     the device is in non-blocking mode, some data may not be
     written—see *note writeall(): 302c.

     在 3.5 版更改: 现在支持可写的 *note 字节类对象: 5f1.。

 -- 方法: oss_audio_device.writeall (data)

     Write a *note bytes-like object: 5f1. `data' to the audio device:
     waits until the audio device is able to accept data, writes as much
     data as it will accept, and repeats until `data' has been
     completely written.  If the device is in blocking mode (the
     default), this has the same effect as *note write(): 302b.; *note
     writeall(): 302c. is only useful in non-blocking mode.  Has no
     return value, since the amount of data written is always equal to
     the amount of data supplied.

     在 3.5 版更改: 现在支持可写的 *note 字节类对象: 5f1.。

在 3.2 版更改: Audio device objects also support the context management
protocol, i.e.  they can be used in a *note with: 6f2. statement.

The following methods each map to exactly one ‘ioctl()’ system call.
The correspondence is obvious: for example, ‘setfmt()’ corresponds to
the ‘SNDCTL_DSP_SETFMT’ ioctl, and ‘sync()’ to ‘SNDCTL_DSP_SYNC’ (this
can be useful when consulting the OSS documentation).  If the underlying
‘ioctl()’ fails, they all raise *note OSError: 1d4.

 -- 方法: oss_audio_device.nonblock ()

     Put the device into non-blocking mode.  Once in non-blocking mode,
     there is no way to return it to blocking mode.

 -- 方法: oss_audio_device.getfmts ()

     Return a bitmask of the audio output formats supported by the
     soundcard.  Some of the formats supported by OSS are:

     格式                          描述
                                   
     --------------------------------------------------------------------------------
                                   
     ‘AFMT_MU_LAW’                 a logarithmic encoding (used by Sun ‘.au’ files
                                   and ‘/dev/audio’)
                                   
                                   
     ‘AFMT_A_LAW’                  a logarithmic encoding
                                   
                                   
     ‘AFMT_IMA_ADPCM’              a 4:1 compressed format defined by the
                                   Interactive Multimedia Association
                                   
                                   
     ‘AFMT_U8’                     Unsigned, 8-bit audio
                                   
                                   
     ‘AFMT_S16_LE’                 Signed, 16-bit audio, little-endian byte order
                                   (as used by Intel processors)
                                   
                                   
     ‘AFMT_S16_BE’                 Signed, 16-bit audio, big-endian byte order (as
                                   used by 68k, PowerPC, Sparc)
                                   
                                   
     ‘AFMT_S8’                     Signed, 8 bit audio
                                   
                                   
     ‘AFMT_U16_LE’                 Unsigned, 16-bit little-endian audio
                                   
                                   
     ‘AFMT_U16_BE’                 Unsigned, 16-bit big-endian audio
                                   

     Consult the OSS documentation for a full list of audio formats, and
     note that most devices support only a subset of these formats.
     Some older devices only support ‘AFMT_U8’; the most common format
     used today is ‘AFMT_S16_LE’.

 -- 方法: oss_audio_device.setfmt (format)

     Try to set the current audio format to `format'—see *note
     getfmts(): 302e. for a list.  Returns the audio format that the
     device was set to, which may not be the requested format.  May also
     be used to return the current audio format—do this by passing an
     "audio format" of ‘AFMT_QUERY’.

 -- 方法: oss_audio_device.channels (nchannels)

     Set the number of output channels to `nchannels'.  A value of 1
     indicates monophonic sound, 2 stereophonic.  Some devices may have
     more than 2 channels, and some high-end devices may not support
     mono.  Returns the number of channels the device was set to.

 -- 方法: oss_audio_device.speed (samplerate)

     Try to set the audio sampling rate to `samplerate' samples per
     second.  Returns the rate actually set.  Most sound devices don’t
     support arbitrary sampling rates.  Common rates are:

     采样率      描述
                 
     ------------------------------------------------------------
                 
     8000        ‘/dev/audio’ 的默认采样率
                 
                 
     11025       语音录音
                 
                 
     22050

     44100       CD品质的音频（16位采样和2通道）
                 
                 
     96000       DVD品质的音频（24位采样）
                 

 -- 方法: oss_audio_device.sync ()

     Wait until the sound device has played every byte in its buffer.
     (This happens implicitly when the device is closed.)  The OSS
     documentation recommends closing and re-opening the device rather
     than using *note sync(): 3032.

 -- 方法: oss_audio_device.reset ()

     Immediately stop playing or recording and return the device to a
     state where it can accept commands.  The OSS documentation
     recommends closing and re-opening the device after calling *note
     reset(): 3033.

 -- 方法: oss_audio_device.post ()

     Tell the driver that there is likely to be a pause in the output,
     making it possible for the device to handle the pause more
     intelligently.  You might use this after playing a spot sound
     effect, before waiting for user input, or before doing disk I/O.

The following convenience methods combine several ioctls, or one ioctl
and some simple calculations.

 -- 方法: oss_audio_device.setparameters (format, nchannels,
          samplerate[, strict=False])

     Set the key audio sampling parameters—sample format, number of
     channels, and sampling rate—in one method call.  `format',
     `nchannels', and `samplerate' should be as specified in the *note
     setfmt(): 302f, *note channels(): 3030, and *note speed(): 3031.
     methods.  If `strict' is true, *note setparameters(): 3035. checks
     to see if each parameter was actually set to the requested value,
     and raises *note OSSAudioError: 3023. if not.  Returns a tuple
     (`format', `nchannels', `samplerate') indicating the parameter
     values that were actually set by the device driver (i.e., the same
     as the return values of *note setfmt(): 302f, *note channels():
     3030, and *note speed(): 3031.).

     For example,

          (fmt, channels, rate) = dsp.setparameters(fmt, channels, rate)

     is equivalent to

          fmt = dsp.setfmt(fmt)
          channels = dsp.channels(channels)
          rate = dsp.rate(rate)

 -- 方法: oss_audio_device.bufsize ()

     Returns the size of the hardware buffer, in samples.

 -- 方法: oss_audio_device.obufcount ()

     Returns the number of samples that are in the hardware buffer yet
     to be played.

 -- 方法: oss_audio_device.obuffree ()

     Returns the number of samples that could be queued into the
     hardware buffer to be played without blocking.

Audio device objects also support several read-only attributes:

 -- 属性: oss_audio_device.closed

     Boolean indicating whether the device has been closed.

 -- 属性: oss_audio_device.name

     String containing the name of the device file.

 -- 属性: oss_audio_device.mode

     The I/O mode for the file, either ‘"r"’, ‘"rw"’, or ‘"w"’.


File: python.info,  Node: Mixer Device Objects,  Prev: Audio Device Objects,  Up: ossaudiodev --- 访问兼容OSS的音频设备

5.22.9.2 Mixer Device Objects
.............................

The mixer object provides two file-like methods:

 -- 方法: oss_mixer_device.close ()

     This method closes the open mixer device file.  Any further
     attempts to use the mixer after this file is closed will raise an
     *note OSError: 1d4.

 -- 方法: oss_mixer_device.fileno ()

     Returns the file handle number of the open mixer device file.

在 3.2 版更改: Mixer objects also support the context management
protocol.

The remaining methods are specific to audio mixing:

 -- 方法: oss_mixer_device.controls ()

     This method returns a bitmask specifying the available mixer
     controls ("Control" being a specific mixable "channel", such as
     ‘SOUND_MIXER_PCM’ or ‘SOUND_MIXER_SYNTH’).  This bitmask indicates
     a subset of all available mixer controls—the ‘SOUND_MIXER_*’
     constants defined at module level.  To determine if, for example,
     the current mixer object supports a PCM mixer, use the following
     Python code:

          mixer=ossaudiodev.openmixer()
          if mixer.controls() & (1 << ossaudiodev.SOUND_MIXER_PCM):
              # PCM is supported
              ... code ...

     For most purposes, the ‘SOUND_MIXER_VOLUME’ (master volume) and
     ‘SOUND_MIXER_PCM’ controls should suffice—but code that uses the
     mixer should be flexible when it comes to choosing mixer controls.
     On the Gravis Ultrasound, for example, ‘SOUND_MIXER_VOLUME’ does
     not exist.

 -- 方法: oss_mixer_device.stereocontrols ()

     Returns a bitmask indicating stereo mixer controls.  If a bit is
     set, the corresponding control is stereo; if it is unset, the
     control is either monophonic or not supported by the mixer (use in
     combination with *note controls(): 3040. to determine which).

     See the code example for the *note controls(): 3040. function for
     an example of getting data from a bitmask.

 -- 方法: oss_mixer_device.reccontrols ()

     Returns a bitmask specifying the mixer controls that may be used to
     record.  See the code example for *note controls(): 3040. for an
     example of reading from a bitmask.

 -- 方法: oss_mixer_device.get (control)

     Returns the volume of a given mixer control.  The returned volume
     is a 2-tuple ‘(left_volume,right_volume)’.  Volumes are specified
     as numbers from 0 (silent) to 100 (full volume).  If the control is
     monophonic, a 2-tuple is still returned, but both volumes are the
     same.

     Raises *note OSSAudioError: 3023. if an invalid control is
     specified, or *note OSError: 1d4. if an unsupported control is
     specified.

 -- 方法: oss_mixer_device.set (control, (left, right))

     Sets the volume for a given mixer control to ‘(left,right)’.
     ‘left’ and ‘right’ must be ints and between 0 (silent) and 100
     (full volume).  On success, the new volume is returned as a
     2-tuple.  Note that this may not be exactly the same as the volume
     specified, because of the limited resolution of some soundcard’s
     mixers.

     Raises *note OSSAudioError: 3023. if an invalid mixer control was
     specified, or if the specified volumes were out-of-range.

 -- 方法: oss_mixer_device.get_recsrc ()

     This method returns a bitmask indicating which control(s) are
     currently being used as a recording source.

 -- 方法: oss_mixer_device.set_recsrc (bitmask)

     Call this function to specify a recording source.  Returns a
     bitmask indicating the new recording source (or sources) if
     successful; raises *note OSError: 1d4. if an invalid source was
     specified.  To set the current recording source to the microphone
     input:

          mixer.setrecsrc (1 << ossaudiodev.SOUND_MIXER_MIC)


File: python.info,  Node: 国际化,  Next: 程序框架,  Prev: 多媒体服务,  Up: Python 标准库

5.23 国际化
===========

本章中介绍的模块通过提供选择要在程序信息中使用的语言的机制或通过定制输出
以匹配本地约定来帮助你编写不依赖于语言和区域设置的软件。

本章中描述的模块列表是：

* Menu:

* gettext: gettext --- 多语种国际化服务. 多语种国际化服务
* locale: locale --- 国际化服务. 国际化服务


File: python.info,  Node: gettext --- 多语种国际化服务,  Next: locale --- 国际化服务,  Up: 国际化

5.23.1 ‘gettext’ — 多语种国际化服务
-----------------------------------

`源代码：' Lib/gettext.py(1)

__________________________________________________________________

*note gettext: 89. 模块为 Python 模块和应用程序提供国际化
(Internationalization, I18N) 和本地化 (Localization, L10N) 服务。它同时
支持 GNU ‘gettext’ 消息编目 API 和更高级的、基于类的 API，后者可能更适合
于 Python 文件。下方描述的接口允许用户使用一种自然语言编写模块和应用程序
消息，并提供翻译后的消息编目，以便在不同的自然语言下运行。

同时还给出一些本地化 Python 模块及应用程序的小技巧。

* Menu:

* GNU gettext API::
* 基于类的 API::
* 国际化 (I18N) 你的程序和模块: 国际化 I18N 你的程序和模块.
* 致谢: 致谢<9>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/gettext.py


File: python.info,  Node: GNU gettext API,  Next: 基于类的 API,  Up: gettext --- 多语种国际化服务

5.23.1.1 GNU ‘gettext’ API
..........................

模块 *note gettext: 89. 定义了下列 API，这与 ‘gettext’ API 类似。如果你
使用该 API，将会对整个应用程序产生全局的影响。如果你的应用程序支持多语种
，而语言选择取决于用户的区域设置，这通常正是你所想要的。而如果你正在本地
化某个 Python 模块，或者你的应用程序需要在运行时切换语言，相反你或许想用
基于类的API。

 -- 函数: gettext.bindtextdomain (domain, localedir=None)

     将 `domain' 绑定到本地目录 `localedir'。 更具体地来说，模块 *note
     gettext: 89. 将使用路径 (在 Unix 系统中):
     ‘`localedir'/`language'/LC_MESSAGES/`domain'.mo’ 查找二进制 ‘.mo’ 文
     件，此处对应地查找 `language' 的位置是环境变量 ‘LANGUAGE’,
     ‘LC_ALL’, ‘LC_MESSAGES’ 和 ‘LANG’ 中。

     如果遗漏了 `localedir' 或者设置为 ‘None’，那么将返回当前 `domain' 所
     绑定的值 (1)

 -- 函数: gettext.bind_textdomain_codeset (domain, codeset=None)

     将 `domain' 绑定到 `codeset'，修改 *note lgettext(): 294, *note
     ldgettext(): 295, *note lngettext(): 296. 和 *note ldngettext():
     297. 函数返回的字节串的字符编码。如果省略了 `codeset'，则返回当前绑
     定的编码集。

     Deprecated since version 3.8, will be removed in version 3.10.

 -- 函数: gettext.textdomain (domain=None)

     修改或查询当前的全局域。如果 `domain' 为 ‘None’，则返回当前的全局域
     ，不为 ‘None’ 则将全局域设置为 `domain'，并返回它。

 -- 函数: gettext.gettext (message)

     返回 `message' 的本地化翻译，依据包括当前的全局域、语言和区域目录。
     本函数在本地命名空间中通常有别名 ‘_()’ （参考下面的示例）。

 -- 函数: gettext.dgettext (domain, message)

     与 *note gettext(): dd5. 类似，但在指定的 `domain' 中查找 message。

 -- 函数: gettext.ngettext (singular, plural, n)

     与 *note gettext(): dd5. 类似，但考虑了复数形式。如果找到了翻译，则
     将 `n' 代入复数公式，然后返回得出的消息（某些语言具有两种以上的复数
     形式）。如果未找到翻译，则 `n' 为 1 时返回 `singular'，为其他数时返
     回 `plural'。

     复数公式取自编目头文件。它是 C 或 Python 表达式，有一个自变量 `n'，
     该表达式计算的是所需复数形式在编目中的索引号。关于在 ‘.po’ 文件中使
     用的确切语法和各种语言的公式，请参阅 GNU gettext 文档(2) 。

 -- 函数: gettext.dngettext (domain, singular, plural, n)

     与 *note ngettext(): 3051. 类似，但在指定的 `domain' 中查找
     message。

 -- 函数: gettext.pgettext (context, message)

 -- 函数: gettext.dpgettext (domain, context, message)

 -- 函数: gettext.npgettext (context, singular, plural, n)

 -- 函数: gettext.dnpgettext (domain, context, singular, plural, n)

     与前缀中没有 ‘p’ 的相应函数类似（即 *note gettext(): 89, *note
     dgettext(): 3050, *note ngettext(): 3051, *note dngettext(): 3052.
     ），但是仅翻译给定的 message `context'。

     3.8 新版功能.

 -- 函数: gettext.lgettext (message)

 -- 函数: gettext.ldgettext (domain, message)

 -- 函数: gettext.lngettext (singular, plural, n)

 -- 函数: gettext.ldngettext (domain, singular, plural, n)

     与前缀中没有 ‘l’ 的相应函数等效（ *note gettext(): dd5, *note
     dgettext(): 3050, *note ngettext(): 3051. 和 *note dngettext():
     3052. ），但是如果没有用 *note bind_textdomain_codeset(): 298. 显式
     设置其他编码，则返回的翻译将以首选系统编码来编码字节串。

          警告: 在 Python 3 中应避免使用这些函数，因为它们返回的是编码后
          的字节串。最好使用返回 Unicode 字符串的其他方法，因为大多数
          Python 应用程序都希望将人类可读的文本作为字符串而不是字节来处
          理。此外，如果翻译后的字符串存在编码问题，则可能会意外出现与
          Unicode 相关的异常。

     Deprecated since version 3.8, will be removed in version 3.10.

注意，GNU ‘gettext’ 还定义了 ‘dcgettext()’ 方法，但它被认为不实用，因此
目前没有实现它。

这是该 API 的典型用法示例:

     import gettext
     gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
     gettext.textdomain('myapplication')
     _ = gettext.gettext
     # ...
     print(_('This is a translatable string.'))

   ---------- Footnotes ----------

   (1) (1) 不同系统的默认语言环境目录是不同的；比如在 RedHat Linux 上是
‘/usr/share/locale’，在 Solaris 上是 ‘/usr/lib/locale’。*note gettext:
89. 模块不会支持这些基于不同系统的默认值；而它的默认值为
‘`sys.base_prefix'/share/locale’ （请参阅 *note sys.base_prefix: 304e.）
。基于上述原因，最好每次都在应用程序的开头使用明确的绝对路径来调用 *note
bindtextdomain(): 304d.。

   (2) https://www.gnu.org/software/gettext/manual/gettext.html


File: python.info,  Node: 基于类的 API,  Next: 国际化 I18N 你的程序和模块,  Prev: GNU gettext API,  Up: gettext --- 多语种国际化服务

5.23.1.2 基于类的 API
.....................

与 GNU ‘gettext’ API 相比，*note gettext: 89. 模块的基于类的 API 提供了
更多的灵活性和更强的便利性。这是本地化 Python 应用程序和模块的推荐方法。
‘gettext’ 定义了一个 *note GNUTranslations: 3057. 类，该类实现了 GNU
‘.mo’ 格式文件的解析，并且具有用于返回字符串的方法。本类的实例也可以将自
身作为函数 ‘_()’ 安装到内建命名空间中。

 -- 函数: gettext.find (domain, localedir=None, languages=None,
          all=False)

     本函数实现了标准的 ‘.mo’ 文件搜索算法。它接受一个 `domain'，它与
     *note textdomain(): 304f. 接受的域相同。可选参数 `localedir' 与
     *note bindtextdomain(): 304d. 中的相同。可选参数 `languages' 是多条
     字符串的列表，其中每条字符串都是一种语言代码。

     如果没有传入 `localedir'，则使用默认的系统区域设置目录。 (1) 如果没
     有传入 `languages'，则搜索以下环境变量： ‘LANGUAGE’、 ‘LC_ALL’、
     ‘LC_MESSAGES’ 和 ‘LANG’。从这些变量返回的第一个非空值将用作
     `languages' 变量。环境变量应包含一个语言列表，由冒号分隔，该列表会
     被按冒号拆分，以产生所需的语言代码字符串列表。

     *note find(): 3058. 将扩展并规范化 language，然后遍历它们，搜索由这
     些组件构建的现有文件:

     ‘`localedir'/`language'/LC_MESSAGES/`domain'.mo’

     *note find(): 3058. 返回找到类似的第一个文件名。如果找不到这样的文
     件，则返回 ‘None’。如果传入了 `all'，它将返回一个列表，包含所有文件
     名，并按它们在语言列表或环境变量中出现的顺序排列。

 -- 函数: gettext.translation (domain, localedir=None, languages=None,
          class_=None, fallback=False, codeset=None)

     根据 `domain'、`localedir' 和 `languages'，返回 ‘*Translations’ 实
     例，首先应将前述参数传入 *note find(): 3058. 以获取关联的 ‘.mo’ 文
     件路径的列表。名字与 ‘.mo’ 文件名相同的实例将被缓存。如果传入
     `class_'，它将是实际被实例化的类，否则实例化 *note GNUTranslations:
     3057.。类的构造函数必须只接受一个 *note 文件对象: b4a. 参数。如果传
     入 `codeset'，那么在 *note lgettext(): 3059. 和 *note lngettext():
     305a. 方法中，对翻译后的字符串进行编码的字符集将被改变。

     如果找到多个文件，后找到的文件将用作先前文件的替补。为了设置替补，
     将使用 *note copy.copy(): 3d3. 从缓存中克隆每个 translation 对象。
     实际的实例数据仍在缓存中共享。

     如果 ‘.mo’ 文件未找到，且 `fallback' 为 false（默认值），则本函数引
     发 *note OSError: 1d4. 异常，如果 `fallback' 为 true，则返回一个
     *note NullTranslations: 305b. 实例。

     在 3.3 版更改: 曾经是 *note IOError: 99a. 被引发而不是 *note
     OSError: 1d4. 。

     Deprecated since version 3.8, will be removed in version 3.10:
     `codeset' 参数。

 -- 函数: gettext.install (domain, localedir=None, codeset=None,
          names=None)

     根据传入 *note translation(): 29b. 函数的 `domain'、`localedir' 和
     `codeset'，在 Python 内建命名空间中安装 ‘_()’ 函数。

     `names' 参数的信息请参阅 translation 对象的 *note install(): 305c.
     方法的描述。

     如下所示，通常将字符串包括在 ‘_()’ 函数的调用中，以标记应用程序中待
     翻译的字符串，就像这样:

          print(_('This string will be translated.'))

     为了方便，一般将 ‘_()’ 函数安装在 Python 内建命名空间中，以便在应用
     程序的所有模块中轻松访问它。

     Deprecated since version 3.8, will be removed in version 3.10:
     `codeset' 参数。

* Menu:

* NullTranslations 类::
* GNUTranslations 类::
* Solaris 消息编目支持::
* 编目构造器::

   ---------- Footnotes ----------

   (1) (2) 参阅上方 *note bindtextdomain(): 304d. 的脚注。


File: python.info,  Node: NullTranslations 类,  Next: GNUTranslations 类,  Up: 基于类的 API

5.23.1.3 ‘NullTranslations’ 类
..............................

translation 类实际实现的是，将原始源文件消息字符串转换为已翻译的消息字符
串。所有 translation 类使用的基类为 *note NullTranslations: 305b.，它提
供了基本的接口，可用于编写自己定制的 translation 类。以下是
‘NullTranslations’ 的方法：

 -- 类: gettext.NullTranslations (fp=None)

     接受一个可选参数 *note 文件对象: b4a. `fp'，该参数会被基类忽略。初
     始化由派生类设置的 "protected" （受保护的）实例变量 `_info' 和
     `_charset'，与 `_fallback' 类似，但它是通过 *note add_fallback():
     305e. 来设置的。如果 `fp' 不为 ‘None’，就会调用 ‘self._parse(fp)’。

      -- 方法: _parse (fp)

          在基类中没有操作，本方法接受文件对象 `fp'，从该文件读取数据，
          用来初始化消息编目。如果你手头的消息编目文件的格式不受支持，则
          应重写本方法来解析你的格式。

      -- 方法: add_fallback (fallback)

          添加 `fallback' 为当前 translation 对象的替补对象。如果
          translation 对象无法为指定消息提供翻译，则应向替补查询。

      -- 方法: gettext (message)

          如果设置了替补，则转发 ‘gettext()’ 给替补。否则返回 `message'。
          须在派生类中重写。

      -- 方法: ngettext (singular, plural, n)

          如果设置了替补，则转发 ‘ngettext()’ 给替补。否则，`n' 为 1 时
          返回 `singular'，为其他时返回 `plural'。须在派生类中重写。

      -- 方法: pgettext (context, message)

          如果设置了替补，则转发 *note pgettext(): 1d0. 给替补。否则返回
          已翻译的消息。在派生类中被重写。

          3.8 新版功能.

      -- 方法: npgettext (context, singular, plural, n)

          如果设置了替补，则转发 *note npgettext(): 3054. 给替补。否则返
          回已翻译的消息。在派生类中被重写。

          3.8 新版功能.

      -- 方法: lgettext (message)

      -- 方法: lngettext (singular, plural, n)

          与 *note gettext(): 3060. 和 *note ngettext(): 3061. 等效，但
          是如果没有用 *note set_output_charset(): 29a. 显式设置编码，则
          返回的翻译将以首选系统编码来编码字节串。在派生类中被重写。

               警告: 应避免在 Python 3 中使用这些方法。请参阅 *note
               lgettext(): 294. 函数的警告。

          Deprecated since version 3.8, will be removed in version 3.10.

      -- 方法: info ()

          返回 "protected"（受保护的） ‘_info’ 变量，它是一个字典，包含
          在消息编目文件中找到的元数据。

      -- 方法: charset ()

          返回消息编目文件的编码。

      -- 方法: output_charset ()

          返回由 *note lgettext(): 3059. 和 *note lngettext(): 305a. 翻
          译的消息的编码。

          Deprecated since version 3.8, will be removed in version 3.10.

      -- 方法: set_output_charset (charset)

          更改翻译出的消息的编码。

          Deprecated since version 3.8, will be removed in version 3.10.

      -- 方法: install (names=None)

          本方法将 *note gettext(): 3060. 安装至内建命名空间，并绑定为
          ‘_’。

          如果传入 `names' 参数，该参数必须是一个序列，包含除 ‘_()’ 外其
          他要安装在内建命名空间中的函数的名称。支持的名称有
          ‘'gettext'’, ‘'ngettext'’, ‘'pgettext'’, ‘'npgettext'’,
          ‘'lgettext'’ 和 ‘'lngettext'’。

          注意，这仅仅是使 ‘_()’ 函数在应用程序中生效的一种方法，尽管也
          是最方便的方法。由于它会影响整个应用程序全局，特别是内建命名空
          间，因此已经本地化的模块不应该安装 ‘_()’，而是应该用下列代码使
          ‘_()’ 在各自模块中生效:

               import gettext
               t = gettext.translation('mymodule', ...)
               _ = t.gettext

          这只将 ‘_()’ 放在其模块的全局命名空间中，所以只影响其模块内的
          调用。

          在 3.8 版更改: 添加了 ‘'pgettext'’ 和 ‘'npgettext'’。


File: python.info,  Node: GNUTranslations 类,  Next: Solaris 消息编目支持,  Prev: NullTranslations 类,  Up: 基于类的 API

5.23.1.4 ‘GNUTranslations’ 类
.............................

*note gettext: 89. 模块提供了一个派生自 *note NullTranslations: 305b. 的
其他类：*note GNUTranslations: 3057.。该类重写了 ‘_parse()’，同时能以大
端序和小端序格式读取 GNU ‘gettext’ 格式的 ‘.mo’ 文件。

*note GNUTranslations: 3057. 从翻译编目中解析出可选的元数据。GNU
‘gettext’ 约定，将元数据包括在空字符串的翻译中。该元数据采用 RFC 822(1)
样式的 ‘key: value’ 键值对，且应该包含 ‘Project-Id-Version’ 键。如果找到
‘Content-Type’ 键，那么将用 ‘charset’ 属性去初始化 "protected"（受保护的
） ‘_charset’ 实例变量，而该变量在未找到键的情况下默认为 ‘None’。如果指
定了字符编码，那么从编目中读取的所有消息 ID 和消息字符串都将使用此编码转
换为 Unicode，若未指定编码，则假定编码为 ASCII。

由于消息 ID 也是作为 Unicode 字符串读取的，因此所有 ‘*gettext()’ 方法都
假定消息 ID 为 Unicode 字符串，而不是字节串。

整个键/值对集合将被放入一个字典，并设置为 "protected"（受保护的）
‘_info’ 实例变量。

如果 ‘.mo’ 文件的魔法值 (magic number) 无效，或遇到意外的主版本号，或在
读取文件时发生其他问题，则实例化 *note GNUTranslations: 3057. 类会引发
*note OSError: 1d4.。

 -- 类: gettext.GNUTranslations

     下列方法是根据基类实现重写的：

      -- 方法: gettext (message)

          在编目中查找 `message' ID，并以 Unicode 字符串形式返回相应的消
          息字符串。如果在编目中没有 `message' ID 条目，且配置了替补，则
          查找请求将被转发到替补的 *note gettext(): 3060. 方法。否则，返
          回 `message' ID。

      -- 方法: ngettext (singular, plural, n)

          查找消息 ID 的复数形式。`singular' 用作消息 ID，用于在编目中查
          找，同时 `n' 用于确定使用哪种复数形式。返回的消息字符串是
          Unicode 字符串。

          如果在编目中没有找到消息 ID，且配置了替补，则查找请求将被转发
          到替补的 *note ngettext(): 3061. 方法。否则，当 `n' 为 1 时返
          回 `singular'，其他情况返回 `plural'。

          例如：

               n = len(os.listdir('.'))
               cat = GNUTranslations(somefile)
               message = cat.ngettext(
                   'There is %(num)d file in this directory',
                   'There are %(num)d files in this directory',
                   n) % {'num': n}

      -- 方法: pgettext (context, message)

          在编目中查找 `context' 和 `message' ID，并以 Unicode 字符串形
          式返回相应的消息字符串。如果在编目中没有 `message' ID 和
          `context' 条目，且配置了替补，则查找请求将被转发到替补的 *note
          pgettext(): 1d0. 方法。否则，返回 `message' ID。

          3.8 新版功能.

      -- 方法: npgettext (context, singular, plural, n)

          查找消息 ID 的复数形式。`singular' 用作消息 ID，用于在编目中查
          找，同时 `n' 用于确定使用哪种复数形式。

          如果在编目中没有找到 `context' 对应的消息 ID，且配置了替补，则
          查找请求将被转发到替补的 *note npgettext(): 3054. 方法。否则，
          当 `n' 为 1 时返回 `singular'，其他情况返回 `plural'。

          3.8 新版功能.

      -- 方法: lgettext (message)

      -- 方法: lngettext (singular, plural, n)

          与 *note gettext(): 3067. 和 *note ngettext(): 3068. 等效，但
          是如果没有用 *note set_output_charset(): 29a. 显式设置编码，则
          返回的翻译将以首选系统编码来编码字节串。

               警告: 应避免在 Python 3 中使用这些方法。请参阅 *note
               lgettext(): 294. 函数的警告。

          Deprecated since version 3.8, will be removed in version 3.10.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc822.html


File: python.info,  Node: Solaris 消息编目支持,  Next: 编目构造器,  Prev: GNUTranslations 类,  Up: 基于类的 API

5.23.1.5 Solaris 消息编目支持
.............................

Solaris 操作系统定义了自己的二进制 ‘.mo’ 文件格式，但由于找不到该格式的
文档，因此目前不支持该格式。


File: python.info,  Node: 编目构造器,  Prev: Solaris 消息编目支持,  Up: 基于类的 API

5.23.1.6 编目构造器
...................

GNOME 用的 *note gettext: 89. 模块是 James Henstridge 写的版本，但该版本
的 API 略有不同。它文档中的用法是:

     import gettext
     cat = gettext.Catalog(domain, localedir)
     _ = cat.gettext
     print(_('hello world'))

为了与本模块的旧版本兼容，‘Catalog()’ 函数是上述 *note translation():
29b. 函数的别名。

本模块与 Henstridge 的模块有一个区别：他的编目对象支持通过映射 API 进行
访问，但是该特性似乎从未使用过，因此目前不支持该特性。


File: python.info,  Node: 国际化 I18N 你的程序和模块,  Next: 致谢<9>,  Prev: 基于类的 API,  Up: gettext --- 多语种国际化服务

5.23.1.7 国际化 (I18N) 你的程序和模块
.....................................

国际化 (I18N) 是指使程序可切换多种语言的操作。本地化 (L10N) 是指程序的适
配能力，一旦程序被国际化，就能适配当地的语言和文化习惯。为了向 Python 程
序提供不同语言的消息，需要执行以下步骤：

  1. 准备程序或模块，将可翻译的字符串特别标记起来

  2. 在已标记的文件上运行一套工具，用来生成原始消息编目

  3. 创建不同语言的消息编目翻译

  4. 使用 *note gettext: 89. 模块，以便正确翻译消息字符串

为了准备代码以达成 I18N，需要巡视文件中的所有字符串。所有要翻译的字符串
都应包括在 ‘_('...')’ 内，以此打上标记——也就是调用 ‘_()’ 函数。例如:

     filename = 'mylog.txt'
     message = _('writing a log message')
     with open(filename, 'w') as fp:
         fp.write(message)

在这个例子中，字符串 ‘'writing a log message'’ 被标记为待翻译，而字符串
‘'mylog.txt'’ 和 ‘'w'’ 没有被标记。

有一些工具可以将待翻译的字符串提取出来。原版的 GNU ‘gettext’ 仅支持 C 或
C++ 源代码，但其扩展版 ‘xgettext’ 可以扫描多种语言的代码（包括 Python）
，来找出标记为可翻译的字符串。Babel(1) 是一个 Python 国际化库，其中包含
一个 ‘pybabel’ 脚本，用于提取并编译消息编目。François Pinard 写的称为
‘xpot’ 的程序也能完成类似的工作，可从他的 po-utils 软件包(2) 中获取。

（Python 还包括了这些程序的纯 Python 版本，称为 ‘pygettext.py’ 和
‘msgfmt.py’，某些 Python 发行版已经安装了它们。‘pygettext.py’ 类似于
‘xgettext’，但只能理解 Python 源代码，无法处理诸如 C 或 C++ 的其他编程语
言。‘pygettext.py’ 支持的命令行界面类似于 ‘xgettext’，查看其详细用法请运
行 ‘pygettext.py --help’。‘msgfmt.py’ 与 GNU ‘msgfmt’ 是二进制兼容的。有
了这两个程序，可以不需要 GNU ‘gettext’ 包来国际化 Python 应用程序。）

‘xgettext’、‘pygettext’ 或类似工具生成的 ‘.po’ 文件就是消息编目。它们是
结构化的人类可读文件，包含源代码中所有被标记的字符串，以及这些字符串的翻
译的占位符。

然后把这些 ‘.po’ 文件的副本交给各个人工译者，他们为所支持的每种自然语言
编写翻译。译者以 ‘<语言名称>.po’ 文件的形式发送回翻译完的某个语言的版本
，将该文件用 ‘msgfmt’ 程序编译为机器可读的 ‘.mo’ 二进制编目文件。*note
gettext: 89. 模块使用 ‘.mo’ 文件在运行时进行实际的翻译处理。

如何在代码中使用 *note gettext: 89. 模块取决于国际化单个模块还是整个应用
程序。接下来的两节将讨论每种情况。

* Menu:

* 本地化你的模块::
* 本地化你的应用程序::
* 即时更改语言::
* 延迟翻译::

   ---------- Footnotes ----------

   (1) http://babel.pocoo.org/

   (2) https://github.com/pinard/po-utils


File: python.info,  Node: 本地化你的模块,  Next: 本地化你的应用程序,  Up: 国际化 I18N 你的程序和模块

5.23.1.8 本地化你的模块
.......................

如果要本地化模块，则切忌进行全局性的更改，如更改内建命名空间。不应使用
GNU ‘gettext’ API，而应使用基于类的 API。

假设你的模块叫做 "spam"，并且该模块的各种自然语言翻译 ‘.mo’ 文件存放于
‘/usr/share/locale’，为 GNU ‘gettext’ 格式。以下内容应放在模块顶部:

     import gettext
     t = gettext.translation('spam', '/usr/share/locale')
     _ = t.gettext


File: python.info,  Node: 本地化你的应用程序,  Next: 即时更改语言,  Prev: 本地化你的模块,  Up: 国际化 I18N 你的程序和模块

5.23.1.9 本地化你的应用程序
...........................

如果正在本地化应用程序，可以将 ‘_()’ 函数全局安装到内建命名空间中，通常
在应用程序的主文件中安装。这将使某个应用程序的所有文件都能使用
‘_('...')’，而不必在每个文件中显式安装它。

最简单的情况，就只需将以下代码添加到应用程序的主程序文件中:

     import gettext
     gettext.install('myapplication')

如果需要设置语言环境目录，可以将其传递给 *note install(): 29c. 函数:

     import gettext
     gettext.install('myapplication', '/usr/share/locale')


File: python.info,  Node: 即时更改语言,  Next: 延迟翻译,  Prev: 本地化你的应用程序,  Up: 国际化 I18N 你的程序和模块

5.23.1.10 即时更改语言
......................

如果程序需要同时支持多种语言，则可能需要创建多个翻译实例，然后在它们之间
进行显式切换，如下所示:

     import gettext

     lang1 = gettext.translation('myapplication', languages=['en'])
     lang2 = gettext.translation('myapplication', languages=['fr'])
     lang3 = gettext.translation('myapplication', languages=['de'])

     # start by using language1
     lang1.install()

     # ... time goes by, user selects language 2
     lang2.install()

     # ... more time goes by, user selects language 3
     lang3.install()


File: python.info,  Node: 延迟翻译,  Prev: 即时更改语言,  Up: 国际化 I18N 你的程序和模块

5.23.1.11 延迟翻译
..................

在大多数代码中，字符串会在编写位置进行翻译。但偶尔需要将字符串标记为待翻
译，实际翻译却推迟到后面。一个典型的例子是:

     animals = ['mollusk',
                'albatross',
                'rat',
                'penguin',
                'python', ]
     # ...
     for a in animals:
         print(a)

此处希望将 ‘animals’ 列表中的字符串标记为可翻译，但不希望在打印之前对它
们进行翻译。

这是处理该情况的一种方式:

     def _(message): return message

     animals = [_('mollusk'),
                _('albatross'),
                _('rat'),
                _('penguin'),
                _('python'), ]

     del _

     # ...
     for a in animals:
         print(_(a))

该方法之所以可行，是因为 ‘_()’ 的虚定义只是简单地返回了原本的字符串。并
且该虚定义将临时覆盖内建命名空间中 ‘_()’ 的定义（直到 *note del: 127e. 命
令）。即使先前在本地命名空间中已经有了 ‘_()’ 的定义也请注意。

注意，第二次使用 ‘_()’ 不会认为 "a" 可以传递给 ‘gettext’ 程序去翻译，因
为该参数不是字符串文字。

解决该问题的另一种方法是下面这个例子:

     def N_(message): return message

     animals = [N_('mollusk'),
                N_('albatross'),
                N_('rat'),
                N_('penguin'),
                N_('python'), ]

     # ...
     for a in animals:
         print(_(a))

这种情况下标记可翻译的字符串使用的是函数 ‘N_()’，该函数不会与 ‘_()’ 的任
何定义冲突。但是，需要教会消息提取程序去寻找用 ‘N_()’ 标记的可翻译字符串
。‘xgettext’, ‘pygettext’, ‘pybabel extract’ 和 ‘xpot’ 都支持此功能，使
用 ‘-k’ 命令行开关即可。这里选择 ‘N_()’ 为名称完全是任意的，它也能轻易改
为 ‘MarkThisStringForTranslation()’。


File: python.info,  Node: 致谢<9>,  Prev: 国际化 I18N 你的程序和模块,  Up: gettext --- 多语种国际化服务

5.23.1.12 致谢
..............

以下人员为创建此模块贡献了代码、反馈、设计建议、早期实现和宝贵的经验：

   * Peter Funk

   * James Henstridge

   * Juan David Ibáñez Palomar

   * Marc-André Lemburg

   * Martin von Löwis

   * François Pinard

   * Barry Warsaw

   * Gustavo Niemeyer

备注
....


File: python.info,  Node: locale --- 国际化服务,  Prev: gettext --- 多语种国际化服务,  Up: 国际化

5.23.2 ‘locale’ — 国际化服务
----------------------------

`源代码：' Lib/locale.py(1)

__________________________________________________________________

The *note locale: aa. module opens access to the POSIX locale database
and functionality.  The POSIX locale mechanism allows programmers to
deal with certain cultural issues in an application, without requiring
the programmer to know all the specifics of each country where the
software is executed.

The *note locale: aa. module is implemented on top of the ‘_locale’
module, which in turn uses an ANSI C locale implementation if available.

The *note locale: aa. module defines the following exception and
functions:

 -- 例外: locale.Error

     Exception raised when the locale passed to *note setlocale(): 2019.
     is not recognized.

 -- 函数: locale.setlocale (category, locale=None)

     If `locale' is given and not ‘None’, *note setlocale(): 2019.
     modifies the locale setting for the `category'.  The available
     categories are listed in the data description below.  `locale' may
     be a string, or an iterable of two strings (language code and
     encoding).  If it’s an iterable, it’s converted to a locale name
     using the locale aliasing engine.  An empty string specifies the
     user’s default settings.  If the modification of the locale fails,
     the exception *note Error: 3077. is raised.  If successful, the new
     locale setting is returned.

     If `locale' is omitted or ‘None’, the current setting for
     `category' is returned.

     *note setlocale(): 2019. is not thread-safe on most systems.
     Applications typically start with a call of

          import locale
          locale.setlocale(locale.LC_ALL, '')

     This sets the locale for all categories to the user’s default
     setting (typically specified in the ‘LANG’ environment variable).
     If the locale is not changed thereafter, using multithreading
     should not cause problems.

 -- 函数: locale.localeconv ()

     以字典的形式返回本地约定的数据库。此字典具有以下字符串作为键：

     类别                       键                                        含义
                                                                          
     ----------------------------------------------------------------------------------------------------------
                                                                          
     *note LC_NUMERIC: 3078.    ‘'decimal_point'’                         小数点字符。
                                                                          
                                                                          
                                ‘'grouping'’                              Sequence of numbers specifying
                                                                          which relative positions the
                                                                          ‘'thousands_sep'’ is expected.  If
                                                                          the sequence is terminated with
                                                                          *note CHAR_MAX: 3079, no further
                                                                          grouping is performed.  If the
                                                                          sequence terminates with a ‘0’,
                                                                          the last group size is repeatedly
                                                                          used.
                                                                          
                                                                          
                                ‘'thousands_sep'’                         组之间使用的字符。
                                                                          
                                                                          
     *note LC_MONETARY: 307a.   ‘'int_curr_symbol'’                       国际货币符号。
                                                                          
                                                                          
                                ‘'currency_symbol'’                       当地货币符号。
                                                                          
                                                                          
                                ‘'p_cs_precedes/n_cs_precedes'’           货币符号是否在值之前（对于正值或负
                                                                          值）。
                                                                          
                                                                          
                                ‘'p_sep_by_space/n_sep_by_space'’         货币符号是否通过空格与值分隔（对于
                                                                          正值或负值）。
                                                                          
                                                                          
                                ‘'mon_decimal_point'’                     用于货币金额的小数点。
                                                                          
                                                                          
                                ‘'frac_digits'’                           货币值的本地格式中使用的小数位数。
                                                                          
                                                                          
                                ‘'int_frac_digits'’                       货币价值的国际格式中使用的小数位数
                                                                          。
                                                                          
                                                                          
                                ‘'mon_thousands_sep'’                     用于货币值的组分隔符。
                                                                          
                                                                          
                                ‘'mon_grouping'’                          相当于 ‘'grouping'’ ，用于货币价值
                                                                          。
                                                                          
                                                                          
                                ‘'positive_sign'’                         用于标注正货币价值的符号。
                                                                          
                                                                          
                                ‘'negative_sign'’                         用于注释负货币价值的符号。
                                                                          
                                                                          
                                ‘'p_sign_posn/n_sign_posn'’               符号的位置（对于正值或负值），见下
                                                                          文。
                                                                          

     可以将所有数值设置为 *note CHAR_MAX: 3079. ，以指示此语言环境中未指
     定任何值。

     下面给出了 ‘'p_sign_posn'’ 和 ‘'n_sign_posn'’ 的可能值。

     值                 说明
                        
     -----------------------------------------------------------------
                        
     ‘0’                被括号括起来的货币和金额。
                        
                        
     ‘1’                该标志应位于值和货币符号之前。
                        
                        
     ‘2’                该标志应位于值和货币符号之后。
                        
                        
     ‘3’                标志应该紧跟在值之前。
                        
                        
     ‘4’                标志应该紧跟值项。
                        
                        
     ‘CHAR_MAX’         此语言环境中未指定任何内容。
                        

     The function sets temporarily the ‘LC_CTYPE’ locale to the
     ‘LC_NUMERIC’ locale or the ‘LC_MONETARY’ locale if locales are
     different and numeric or monetary strings are non-ASCII. This
     temporary change affects other threads.

     在 3.7 版更改: The function now sets temporarily the ‘LC_CTYPE’
     locale to the ‘LC_NUMERIC’ locale in some cases.

 -- 函数: locale.nl_langinfo (option)

     Return some locale-specific information as a string.  This function
     is not available on all systems, and the set of possible options
     might also vary across platforms.  The possible argument values are
     numbers, for which symbolic constants are available in the locale
     module.

     The *note nl_langinfo(): 307b. function accepts one of the
     following keys.  Most descriptions are taken from the corresponding
     description in the GNU C library.

      -- 数据: locale.CODESET

          Get a string with the name of the character encoding used in
          the selected locale.

      -- 数据: locale.D_T_FMT

          Get a string that can be used as a format string for *note
          time.strftime(): b6d. to represent date and time in a
          locale-specific way.

      -- 数据: locale.D_FMT

          Get a string that can be used as a format string for *note
          time.strftime(): b6d. to represent a date in a locale-specific
          way.

      -- 数据: locale.T_FMT

          Get a string that can be used as a format string for *note
          time.strftime(): b6d. to represent a time in a locale-specific
          way.

      -- 数据: locale.T_FMT_AMPM

          Get a format string for *note time.strftime(): b6d. to
          represent time in the am/pm format.

      -- 数据: DAY_1 ... DAY_7

          Get the name of the n-th day of the week.

               注解: This follows the US convention of ‘DAY_1’ being
               Sunday, not the international convention (ISO 8601) that
               Monday is the first day of the week.

      -- 数据: ABDAY_1 ... ABDAY_7

          Get the abbreviated name of the n-th day of the week.

      -- 数据: MON_1 ... MON_12

          Get the name of the n-th month.

      -- 数据: ABMON_1 ... ABMON_12

          Get the abbreviated name of the n-th month.

      -- 数据: locale.RADIXCHAR

          Get the radix character (decimal dot, decimal comma, etc.).

      -- 数据: locale.THOUSEP

          Get the separator character for thousands (groups of three
          digits).

      -- 数据: locale.YESEXPR

          Get a regular expression that can be used with the regex
          function to recognize a positive response to a yes/no
          question.

               注解: The expression is in the syntax suitable for the
               ‘regex()’ function from the C library, which might differ
               from the syntax used in *note re: de.

      -- 数据: locale.NOEXPR

          Get a regular expression that can be used with the regex(3)
          function to recognize a negative response to a yes/no
          question.

      -- 数据: locale.CRNCYSTR

          Get the currency symbol, preceded by "-" if the symbol should
          appear before the value, "+" if the symbol should appear after
          the value, or "."  if the symbol should replace the radix
          character.

      -- 数据: locale.ERA

          Get a string that represents the era used in the current
          locale.

          Most locales do not define this value.  An example of a locale
          which does define this value is the Japanese one.  In Japan,
          the traditional representation of dates includes the name of
          the era corresponding to the then-emperor’s reign.

          Normally it should not be necessary to use this value
          directly.  Specifying the ‘E’ modifier in their format strings
          causes the *note time.strftime(): b6d. function to use this
          information.  The format of the returned string is not
          specified, and therefore you should not assume knowledge of it
          on different systems.

      -- 数据: locale.ERA_D_T_FMT

          Get a format string for *note time.strftime(): b6d. to
          represent date and time in a locale-specific era-based way.

      -- 数据: locale.ERA_D_FMT

          Get a format string for *note time.strftime(): b6d. to
          represent a date in a locale-specific era-based way.

      -- 数据: locale.ERA_T_FMT

          Get a format string for *note time.strftime(): b6d. to
          represent a time in a locale-specific era-based way.

      -- 数据: locale.ALT_DIGITS

          Get a representation of up to 100 values used to represent the
          values 0 to 99.

 -- 函数: locale.getdefaultlocale ([envvars])

     Tries to determine the default locale settings and returns them as
     a tuple of the form ‘(language code, encoding)’.

     According to POSIX, a program which has not called
     ‘setlocale(LC_ALL, '')’ runs using the portable ‘'C'’ locale.
     Calling ‘setlocale(LC_ALL, '')’ lets it use the default locale as
     defined by the ‘LANG’ variable.  Since we do not want to interfere
     with the current locale setting we thus emulate the behavior in the
     way described above.

     To maintain compatibility with other platforms, not only the ‘LANG’
     variable is tested, but a list of variables given as envvars
     parameter.  The first found to be defined will be used.  `envvars'
     defaults to the search path used in GNU gettext; it must always
     contain the variable name ‘'LANG'’.  The GNU gettext search path
     contains ‘'LC_ALL'’, ‘'LC_CTYPE'’, ‘'LANG'’ and ‘'LANGUAGE'’, in
     that order.

     Except for the code ‘'C'’, the language code corresponds to RFC
     1766(2).  `language code' and `encoding' may be ‘None’ if their
     values cannot be determined.

 -- 函数: locale.getlocale (category=LC_CTYPE)

     Returns the current setting for the given locale category as
     sequence containing `language code', `encoding'.  `category' may be
     one of the ‘LC_*’ values except *note LC_ALL: 308b.  It defaults to
     *note LC_CTYPE: 308c.

     Except for the code ‘'C'’, the language code corresponds to RFC
     1766(3).  `language code' and `encoding' may be ‘None’ if their
     values cannot be determined.

 -- 函数: locale.getpreferredencoding (do_setlocale=True)

     Return the encoding used for text data, according to user
     preferences.  User preferences are expressed differently on
     different systems, and might not be available programmatically on
     some systems, so this function only returns a guess.

     On some systems, it is necessary to invoke *note setlocale(): 2019.
     to obtain the user preferences, so this function is not
     thread-safe.  If invoking setlocale is not necessary or desired,
     `do_setlocale' should be set to ‘False’.

     On Android or in the UTF-8 mode (*note -X: 156. ‘utf8’ option),
     always return ‘'UTF-8'’, the locale and the `do_setlocale' argument
     are ignored.

     在 3.7 版更改: The function now always returns ‘UTF-8’ on Android
     or if the UTF-8 mode is enabled.

 -- 函数: locale.normalize (localename)

     Returns a normalized locale code for the given locale name.  The
     returned locale code is formatted for use with *note setlocale():
     2019.  If normalization fails, the original name is returned
     unchanged.

     If the given encoding is not known, the function defaults to the
     default encoding for the locale code just like *note setlocale():
     2019.

 -- 函数: locale.resetlocale (category=LC_ALL)

     Sets the locale for `category' to the default setting.

     The default setting is determined by calling *note
     getdefaultlocale(): 1370.  `category' defaults to *note LC_ALL:
     308b.

 -- 函数: locale.strcoll (string1, string2)

     Compares two strings according to the current *note LC_COLLATE:
     3090. setting.  As any other compare function, returns a negative,
     or a positive value, or ‘0’, depending on whether `string1'
     collates before or after `string2' or is equal to it.

 -- 函数: locale.strxfrm (string)

     Transforms a string to one that can be used in locale-aware
     comparisons.  For example, ‘strxfrm(s1) < strxfrm(s2)’ is
     equivalent to ‘strcoll(s1, s2) < 0’.  This function can be used
     when the same string is compared repeatedly, e.g.  when collating a
     sequence of strings.

 -- 函数: locale.format_string (format, val, grouping=False,
          monetary=False)

     Formats a number `val' according to the current *note LC_NUMERIC:
     3078. setting.  The format follows the conventions of the ‘%’
     operator.  For floating point values, the decimal point is modified
     if appropriate.  If `grouping' is true, also takes the grouping
     into account.

     If `monetary' is true, the conversion uses monetary thousands
     separator and grouping strings.

     Processes formatting specifiers as in ‘format % val’, but takes the
     current locale settings into account.

     在 3.7 版更改: The `monetary' keyword parameter was added.

 -- 函数: locale.format (format, val, grouping=False, monetary=False)

     Please note that this function works like *note format_string():
     3ac. but will only work for exactly one ‘%char’ specifier.  For
     example, ‘'%f'’ and ‘'%.0f'’ are both valid specifiers, but ‘'%f
     KiB'’ is not.

     For whole format strings, use *note format_string(): 3ac.

     3.7 版后已移除: Use *note format_string(): 3ac. instead.

 -- 函数: locale.currency (val, symbol=True, grouping=False,
          international=False)

     Formats a number `val' according to the current *note LC_MONETARY:
     307a. settings.

     The returned string includes the currency symbol if `symbol' is
     true, which is the default.  If `grouping' is true (which is not
     the default), grouping is done with the value.  If `international'
     is true (which is not the default), the international currency
     symbol is used.

     Note that this function will not work with the ’C’ locale, so you
     have to set a locale via *note setlocale(): 2019. first.

 -- 函数: locale.str (float)

     Formats a floating point number using the same format as the
     built-in function ‘str(float)’, but takes the decimal point into
     account.

 -- 函数: locale.delocalize (string)

     Converts a string into a normalized number string, following the
     *note LC_NUMERIC: 3078. settings.

     3.5 新版功能.

 -- 函数: locale.atof (string)

     Converts a string to a floating point number, following the *note
     LC_NUMERIC: 3078. settings.

 -- 函数: locale.atoi (string)

     Converts a string to an integer, following the *note LC_NUMERIC:
     3078. conventions.

 -- 数据: locale.LC_CTYPE

     Locale category for the character type functions.  Depending on the
     settings of this category, the functions of module *note string:
     f7. dealing with case change their behaviour.

 -- 数据: locale.LC_COLLATE

     Locale category for sorting strings.  The functions *note
     strcoll(): 308f. and *note strxfrm(): 3091. of the *note locale:
     aa. module are affected.

 -- 数据: locale.LC_TIME

     Locale category for the formatting of time.  The function *note
     time.strftime(): b6d. follows these conventions.

 -- 数据: locale.LC_MONETARY

     Locale category for formatting of monetary values.  The available
     options are available from the *note localeconv(): 492. function.

 -- 数据: locale.LC_MESSAGES

     Locale category for message display.  Python currently does not
     support application specific locale-aware messages.  Messages
     displayed by the operating system, like those returned by *note
     os.strerror(): 1f12. might be affected by this category.

 -- 数据: locale.LC_NUMERIC

     Locale category for formatting numbers.  The functions *note
     format(): 470, *note atoi(): 3095, *note atof(): 3094. and *note
     str(): 3093. of the *note locale: aa. module are affected by that
     category.  All other numeric formatting operations are not
     affected.

 -- 数据: locale.LC_ALL

     Combination of all locale settings.  If this flag is used when the
     locale is changed, setting the locale for all categories is
     attempted.  If that fails for any category, no category is changed
     at all.  When the locale is retrieved using this flag, a string
     indicating the setting for all categories is returned.  This string
     can be later used to restore the settings.

 -- 数据: locale.CHAR_MAX

     This is a symbolic constant used for different values returned by
     *note localeconv(): 492.

示例:

     >>> import locale
     >>> loc = locale.getlocale()  # get current locale
     # use German locale; name might vary with platform
     >>> locale.setlocale(locale.LC_ALL, 'de_DE')
     >>> locale.strcoll('f\xe4n', 'foo')  # compare a string containing an umlaut
     >>> locale.setlocale(locale.LC_ALL, '')   # use user's preferred locale
     >>> locale.setlocale(locale.LC_ALL, 'C')  # use default (C) locale
     >>> locale.setlocale(locale.LC_ALL, loc)  # restore saved locale

* Menu:

* Background, details, hints, tips and caveats: Background details hints tips and caveats.
* For extension writers and programs that embed Python::
* Access to message catalogs::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/locale.py

   (2) https://tools.ietf.org/html/rfc1766.html

   (3) https://tools.ietf.org/html/rfc1766.html


File: python.info,  Node: Background details hints tips and caveats,  Next: For extension writers and programs that embed Python,  Up: locale --- 国际化服务

5.23.2.1 Background, details, hints, tips and caveats
.....................................................

The C standard defines the locale as a program-wide property that may be
relatively expensive to change.  On top of that, some implementation are
broken in such a way that frequent locale changes may cause core dumps.
This makes the locale somewhat painful to use correctly.

Initially, when a program is started, the locale is the ‘C’ locale, no
matter what the user’s preferred locale is.  There is one exception: the
*note LC_CTYPE: 308c. category is changed at startup to set the current
locale encoding to the user’s preferred locale encoding.  The program
must explicitly say that it wants the user’s preferred locale settings
for other categories by calling ‘setlocale(LC_ALL, '')’.

It is generally a bad idea to call *note setlocale(): 2019. in some
library routine, since as a side effect it affects the entire program.
Saving and restoring it is almost as bad: it is expensive and affects
other threads that happen to run before the settings have been restored.

If, when coding a module for general use, you need a locale independent
version of an operation that is affected by the locale (such as certain
formats used with *note time.strftime(): b6d.), you will have to find a
way to do it without using the standard library routine.  Even better is
convincing yourself that using locale settings is okay.  Only as a last
resort should you document that your module is not compatible with
non-‘C’ locale settings.

The only way to perform numeric operations according to the locale is to
use the special functions defined by this module: *note atof(): 3094,
*note atoi(): 3095, *note format(): 470, *note str(): 3093.

There is no way to perform case conversions and character
classifications according to the locale.  For (Unicode) text strings
these are done according to the character value only, while for byte
strings, the conversions and classifications are done according to the
ASCII value of the byte, and bytes whose high bit is set (i.e.,
non-ASCII bytes) are never converted or considered part of a character
class such as letter or whitespace.


File: python.info,  Node: For extension writers and programs that embed Python,  Next: Access to message catalogs,  Prev: Background details hints tips and caveats,  Up: locale --- 国际化服务

5.23.2.2 For extension writers and programs that embed Python
.............................................................

Extension modules should never call *note setlocale(): 2019, except to
find out what the current locale is.  But since the return value can
only be used portably to restore it, that is not very useful (except
perhaps to find out whether or not the locale is ‘C’).

When Python code uses the *note locale: aa. module to change the locale,
this also affects the embedding application.  If the embedding
application doesn’t want this to happen, it should remove the ‘_locale’
extension module (which does all the work) from the table of built-in
modules in the ‘config.c’ file, and make sure that the ‘_locale’ module
is not accessible as a shared library.


File: python.info,  Node: Access to message catalogs,  Prev: For extension writers and programs that embed Python,  Up: locale --- 国际化服务

5.23.2.3 Access to message catalogs
...................................

 -- 函数: locale.gettext (msg)

 -- 函数: locale.dgettext (domain, msg)

 -- 函数: locale.dcgettext (domain, msg, category)

 -- 函数: locale.textdomain (domain)

 -- 函数: locale.bindtextdomain (domain, dir)

The locale module exposes the C library’s gettext interface on systems
that provide this interface.  It consists of the functions ‘gettext()’,
‘dgettext()’, ‘dcgettext()’, ‘textdomain()’, ‘bindtextdomain()’, and
‘bind_textdomain_codeset()’.  These are similar to the same functions in
the *note gettext: 89. module, but use the C library’s binary format for
message catalogs, and the C library’s search algorithms for locating
message catalogs.

Python applications should normally find no need to invoke these
functions, and should use *note gettext: 89. instead.  A known exception
to this rule are applications that link with additional C libraries
which internally invoke ‘gettext()’ or ‘dcgettext()’.  For these
applications, it may be necessary to bind the text domain, so that the
libraries can properly locate their message catalogs.


File: python.info,  Node: 程序框架,  Next: Tk图形用户界面 GUI,  Prev: 国际化,  Up: Python 标准库

5.24 程序框架
=============

本章中描述的模块是很大程度上决定程序结构的框架。 目前，这里描述的模块都
面向编写命令行接口。

本章描述的完整模块列表如下：

* Menu:

* turtle: turtle --- 海龟绘图. 海龟绘图
* cmd: cmd --- 支持面向行的命令解释器. 支持面向行的命令解释器
* shlex: shlex --- Simple lexical analysis. Simple lexical analysis


File: python.info,  Node: turtle --- 海龟绘图,  Next: cmd --- 支持面向行的命令解释器,  Up: 程序框架

5.24.1 ‘turtle’ — 海龟绘图
--------------------------

`源码：' Lib/turtle.py(1)

__________________________________________________________________

* Menu:

* 概述: 概述<12>.
* 可用的 Turtle 和 Screen 方法概览::
* RawTurtle/Turtle 方法和对应函数::
* TurtleScreen/Screen 方法及对应函数::
* 公共类::
* 帮助与配置::
* turtledemo: turtledemo --- 演示脚本集. 演示脚本集
* Python 2.6 之后的变化: Python 2 6 之后的变化.
* Python 3.0 之后的变化: Python 3 0 之后的变化.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/turtle.py


File: python.info,  Node: 概述<12>,  Next: 可用的 Turtle 和 Screen 方法概览,  Up: turtle --- 海龟绘图

5.24.1.1 概述
.............

海龟绘图很适合用来引导孩子学习编程。 最初来自于 Wally Feurzeig, Seymour
Papert 和 Cynthia Solomon 于 1967 年所创造的 Logo 编程语言。

请想象绘图区有一只机器海龟，起始位置在 x-y 平面的 (0, 0) 点。先执行
‘import turtle’，再执行 ‘turtle.forward(15)’，它将(在屏幕上)朝所面对的 x
轴正方向前进 15 像素，随着它的移动画出一条线段。再执行
‘turtle.right(25)’，它将原地右转 25 度。

Turtle star
...........

使用海龟绘图可以编写重复执行简单动作的程序画出精细复杂的形状。

[python-figures/turtle-star]
     from turtle import *
     color('red', 'yellow')
     begin_fill()
     while True:
         forward(200)
         left(170)
         if abs(pos()) < 1:
             break
     end_fill()
     done()

通过组合使用此类命令，可以轻松地绘制出精美的形状和图案。

*note turtle: 117. 模块是基于 Python 标准发行版 2.5 以来的同名模块重新编
写并进行了功能扩展。

新模块尽量保持了原模块的特点，并且(几乎)100%与其兼容。这就意味着初学编程
者能够以交互方式使用模块的所有命令、类和方法——运行 IDLE 时注意加 ‘-n’ 参
数。

turtle 模块提供面向对象和面向过程两种形式的海龟绘图基本组件。由于它使用
*note tkinter: 10d. 实现基本图形界面，因此需要安装了 Tk 支持的 Python 版
本。

面向对象的接口主要使用“2+2”个类：

  1. *note TurtleScreen: 30a8. 类定义图形窗口作为绘图海龟的运动场。它的
     构造器需要一个 ‘tkinter.Canvas’ 或 *note ScrolledCanvas: 30a9. 作为
     参数。应在 *note turtle: 117. 作为某个程序的一部分的时候使用。

     *note Screen(): 30aa. 函数返回一个 *note TurtleScreen: 30a8. 子类的
     单例对象。此函数应在 *note turtle: 117. 作为独立绘图工具时使用。作
     为一个单例对象，其所属的类是不可被继承的。

     TurtleScreen/Screen 的所有方法还存在对应的函数，即作为面向过程的接
     口组成部分。

  2. *note RawTurtle: 30ab. (别名: *note RawPen: 30ac.) 类定义海龟对象在
     *note TurtleScreen: 30a8. 上绘图。它的构造器需要一个 Canvas,
     ScrolledCanvas 或 TurtleScreen 作为参数，以指定 RawTurtle 对象在哪
     里绘图。

     从 RawTurtle 派生出子类 *note Turtle: 30ad. (别名: ‘Pen’)，该类对象
     在 *note Screen: 30aa. 实例上绘图，如果实例不存在则会自动创建。

     RawTurtle/Turtle 的所有方法也存在对应的函数，即作为面向过程的接口组
     成部分。

过程式接口提供与 *note Screen: 30aa. 和 *note Turtle: 30ad. 类的方法相对
应的函数。函数名与对应的方法名相同。当 Screen 类的方法对应函数被调用时会
自动创建一个 Screen 对象。当 Turtle 类的方法对应函数被调用时会自动创建一
个 (匿名的) Turtle 对象。

如果屏幕上需要有多个海龟，就必须使用面向对象的接口。

     注解: 以下文档给出了函数的参数列表。对于方法来说当然还有额外的第一
     个参数 `self'，这里省略了。


File: python.info,  Node: 可用的 Turtle 和 Screen 方法概览,  Next: RawTurtle/Turtle 方法和对应函数,  Prev: 概述<12>,  Up: turtle --- 海龟绘图

5.24.1.2 可用的 Turtle 和 Screen 方法概览
.........................................

* Menu:

* Turtle 方法::
* TurtleScreen/Screen 方法::


File: python.info,  Node: Turtle 方法,  Next: TurtleScreen/Screen 方法,  Up: 可用的 Turtle 和 Screen 方法概览

5.24.1.3 Turtle 方法
....................

海龟动作

     移动和绘制

               *note forward(): 30b0. | *note fd(): 30b1. 前进 
               *note backward(): 30b2. | *note bk(): 30b3. | *note back(): 30b4. 后退 
               *note right(): 30b5. | *note rt(): 30b6. 右转 
               *note left(): 30b7. | *note lt(): 30b8. 左转 
               *note goto(): 30b9. | *note setpos(): 30ba. | *note setposition(): 30bb. 前往/定位 
               *note setx(): 30bc. 设置x坐标 
               *note sety(): 30bd. 设置y坐标 
               *note setheading(): 30be. | *note seth(): 30bf. 设置朝向 
               *note home(): 30c0. 返回原点 
               *note circle(): 30c1. 画圆 
               *note dot(): 30c2. 画点 
               *note stamp(): 30c3. 印章 
               *note clearstamp(): 30c4. 清除印章 
               *note clearstamps(): 30c5. 清除多个印章 
               *note undo(): 30c6. 撤消 
               *note speed(): 30c7. 速度 

     获取海龟的状态

               *note position(): 30c8. | *note pos(): 30c9. 位置 
               *note towards(): 30ca. 目标方向 
               *note xcor(): 30cb. x坐标 
               *note ycor(): 30cc. y坐标 
               *note heading(): 30cd. 朝向 
               *note distance(): 30ce. 距离 

     设置与度量单位

               *note degrees(): 30cf. 角度 
               *note radians(): 30d0. 弧度 

画笔控制

     绘图状态

               *note pendown(): 30d1. | *note pd(): 30d2. | *note down(): 30d3. 画笔落下 
               *note penup(): 30d4. | *note pu(): 30d5. | *note up(): 30d6. 画笔抬起 
               *note pensize(): 30d7. | *note width(): 30d8. 画笔粗细 
               *note pen(): 30d9. 画笔 
               *note isdown(): 30da. 画笔是否落下 

     颜色控制

               *note color(): 30db. 颜色 
               *note pencolor(): 30dc. 画笔颜色 
               *note fillcolor(): 30dd. 填充颜色 

     填充

               *note filling(): 30de. 是否填充 
               *note begin_fill(): 30df. 开始填充 
               *note end_fill(): 30e0. 结束填充 

     更多绘图控制

               *note reset(): 30e1. 重置 
               *note clear(): 30e2. 清空 
               *note write(): 30e3. 书写 

海龟状态

     可见性

               *note showturtle(): 30e4. | *note st(): 30e5. 显示海龟 
               *note hideturtle(): 30e6. | *note ht(): 30e7. 隐藏海龟 
               *note isvisible(): 30e8. 是否可见 

     外观

               *note shape(): 30e9. 形状 
               *note resizemode(): 30ea. 大小调整模式 
               *note shapesize(): 30eb. | *note turtlesize(): 30ec. 形状大小 
               *note shearfactor(): 30ed. 剪切因子 
               *note settiltangle(): 30ee. 设置倾角 
               *note tiltangle(): 30ef. 倾角 
               *note tilt(): 30f0. 倾斜 
               *note shapetransform(): 30f1. 变形 
               *note get_shapepoly(): 30f2. 获取形状多边形 

使用事件

          *note onclick(): 30f3. 当鼠标点击 
          *note onrelease(): 30f4. 当鼠标释放 
          *note ondrag(): 30f5. 当鼠标拖动 

特殊海龟方法

          *note begin_poly(): 30f6. 开始记录多边形 
          *note end_poly(): 30f7. 结束记录多边形 
          *note get_poly(): 30f8. 获取多边形 
          *note clone(): 30f9. 克隆 
          *note getturtle(): 30fa. | *note getpen(): 30fb. 获取海龟画笔 
          *note getscreen(): 30fc. 获取屏幕 
          *note setundobuffer(): 30fd. 设置撤消缓冲区 
          *note undobufferentries(): 30fe. 撤消缓冲区条目数 


File: python.info,  Node: TurtleScreen/Screen 方法,  Prev: Turtle 方法,  Up: 可用的 Turtle 和 Screen 方法概览

5.24.1.4 TurtleScreen/Screen 方法
.................................

窗口控制

          *note bgcolor(): 3100. 背景颜色 
          *note bgpic(): 3101. 背景图片 
          *note clear(): 30e2. | *note clearscreen(): 3102. 清屏 
          *note reset(): 30e1. | *note resetscreen(): 3103. 重置 
          *note screensize(): 3104. 屏幕大小 
          *note setworldcoordinates(): 3105. 设置世界坐标系 

动画控制

          *note delay(): 3106. 延迟 
          *note tracer(): 3107. 追踪 
          *note update(): 3108. 更新 

使用屏幕事件

          *note listen(): 3109. 监听 
          *note onkey(): 310a. | *note onkeyrelease(): 310b. 当键盘按下并释放 
          *note onkeypress(): 310c. 当键盘按下 
          *note onclick(): 30f3. | *note onscreenclick(): 310d. 当点击屏幕 
          *note ontimer(): 310e. 当达到定时 
          *note mainloop(): 310f. | *note done(): 3110. 主循环 

设置与特殊方法

          *note mode(): 3111. 
          *note colormode(): 3112. 颜色模式 
          *note getcanvas(): 3113. 获取画布 
          *note getshapes(): 3114. 获取形状 
          *note register_shape(): 3115. | *note addshape(): 3116. 添加形状 
          *note turtles(): 3117. 所有海龟 
          *note window_height(): 3118. 窗口高度 
          *note window_width(): 3119. 窗口宽度 

输入方法

          *note textinput(): ea6. 文本输入 
          *note numinput(): ea7. 数字输入 

Screen 专有方法

          *note bye(): 311a. 退出 
          *note exitonclick(): 311b. 当点击时退出 
          *note setup(): 311c. 设置 
          *note title(): 311d. 标题 


File: python.info,  Node: RawTurtle/Turtle 方法和对应函数,  Next: TurtleScreen/Screen 方法及对应函数,  Prev: 可用的 Turtle 和 Screen 方法概览,  Up: turtle --- 海龟绘图

5.24.1.5 RawTurtle/Turtle 方法和对应函数
........................................

本节中的大部分示例都使用 Turtle 类的一个实例，命名为 ‘turtle’。

* Menu:

* 海龟动作::
* 获取海龟的状态::
* 度量单位设置::
* 画笔控制::
* 海龟状态::
* 使用事件::
* 特殊海龟方法::
* 复合形状::


File: python.info,  Node: 海龟动作,  Next: 获取海龟的状态,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.6 海龟动作
.................

 -- 函数: turtle.forward (distance)
 -- 函数: turtle.fd (distance)


     参数: ‘distance’ – 一个数值 (整型或浮点型)

     海龟前进 `distance' 指定的距离，方向为海龟的朝向。

          >>> turtle.position()
          (0.00,0.00)
          >>> turtle.forward(25)
          >>> turtle.position()
          (25.00,0.00)
          >>> turtle.forward(-75)
          >>> turtle.position()
          (-50.00,0.00)

 -- 函数: turtle.back (distance)
 -- 函数: turtle.bk (distance)
 -- 函数: turtle.backward (distance)


     参数: ‘distance’ – 一个数值

     海龟后退 `distance' 指定的距离，方向与海龟的朝向相反。不改变海龟的
     朝向。

          >>> turtle.position()
          (0.00,0.00)
          >>> turtle.backward(30)
          >>> turtle.position()
          (-30.00,0.00)

 -- 函数: turtle.right (angle)
 -- 函数: turtle.rt (angle)


     参数: ‘angle’ – 一个数值 (整型或浮点型)

     海龟右转 `angle' 个单位。(单位默认为角度，但可通过 *note degrees():
     30cf. 和 *note radians(): 30d0. 函数改变设置。) 角度的正负由海龟模
     式确定，参见 *note mode(): 3111.。

          >>> turtle.heading()
          22.0
          >>> turtle.right(45)
          >>> turtle.heading()
          337.0

 -- 函数: turtle.left (angle)
 -- 函数: turtle.lt (angle)


     参数: ‘angle’ – 一个数值 (整型或浮点型)

     海龟左转 `angle' 个单位。(单位默认为角度，但可通过 *note degrees():
     30cf. 和 *note radians(): 30d0. 函数改变设置。) 角度的正负由海龟模
     式确定，参见 *note mode(): 3111.。

          >>> turtle.heading()
          22.0
          >>> turtle.left(45)
          >>> turtle.heading()
          67.0

 -- 函数: turtle.goto (x, y=None)
 -- 函数: turtle.setpos (x, y=None)
 -- 函数: turtle.setposition (x, y=None)


     参数:

        * ‘x’ – 一个数值或数值对/向量

        * ‘y’ – 一个数值或 ‘None’

     如果 `y' 为 ‘None’，`x' 应为一个表示坐标的数值对或 *note Vec2D:
     3120. 类对象 (例如 *note pos(): 30c9. 返回的对象).

     海龟移动到一个绝对坐标。如果画笔已落下将会画线。不改变海龟的朝向。

           >>> tp = turtle.pos()
           >>> tp
           (0.00,0.00)
           >>> turtle.setpos(60,30)
           >>> turtle.pos()
           (60.00,30.00)
           >>> turtle.setpos((20,80))
           >>> turtle.pos()
           (20.00,80.00)
           >>> turtle.setpos(tp)
           >>> turtle.pos()
           (0.00,0.00)

 -- 函数: turtle.setx (x)


     参数: ‘x’ – 一个数值 (整型或浮点型)

     设置海龟的横坐标为 `x'，纵坐标保持不变。

          >>> turtle.position()
          (0.00,240.00)
          >>> turtle.setx(10)
          >>> turtle.position()
          (10.00,240.00)

 -- 函数: turtle.sety (y)


     参数: ‘y’ – 一个数值 (整型或浮点型)

     设置海龟的纵坐标为 `y'，横坐标保持不变。

          >>> turtle.position()
          (0.00,40.00)
          >>> turtle.sety(-10)
          >>> turtle.position()
          (0.00,-10.00)

 -- 函数: turtle.setheading (to_angle)
 -- 函数: turtle.seth (to_angle)


     参数: ‘to_angle’ – 一个数值 (整型或浮点型)

     设置海龟的朝向为 `to_angle'。以下是以角度表示的几个常用方向：

     标准模式                logo 模式
                             
     -------------------------------------------------
                             
     0 - 东                  0 - 北
                             
                             
     90 - 北                 90 - 东
                             
                             
     180 - 西                180 - 南
                             
                             
     270 - 南                270 - 西
                             

          >>> turtle.setheading(90)
          >>> turtle.heading()
          90.0

 -- 函数: turtle.home ()

     海龟移至初始坐标 (0,0)，并设置朝向为初始方向 (由海龟模式确定，参见
     *note mode(): 3111.)。

          >>> turtle.heading()
          90.0
          >>> turtle.position()
          (0.00,-10.00)
          >>> turtle.home()
          >>> turtle.position()
          (0.00,0.00)
          >>> turtle.heading()
          0.0

 -- 函数: turtle.circle (radius, extent=None, steps=None)


     参数:

        * ‘radius’ – 一个数值

        * ‘extent’ – 一个数值 (或 ‘None’)

        * ‘steps’ – 一个整型数 (或 ‘None’)

     绘制一个 `radius' 指定半径的圆。圆心在海龟左边 `radius' 个单位；
     `extent' 为一个夹角，用来决定绘制圆的一部分。如未指定 `extent*则绘
     制整个圆。如果 *extent' 不是完整圆周，则以当前画笔位置为一个端点绘
     制圆弧。如果 `radius' 为正值则朝逆时针方向绘制圆弧，否则朝顺时针方
     向。最终海龟的朝向会依据 `extent' 的值而改变。

     圆实际是以其内切正多边形来近似表示的，其边的数量由 `steps' 指定。如
     果未指定边数则会自动确定。此方法也可用来绘制正多边形。

          >>> turtle.home()
          >>> turtle.position()
          (0.00,0.00)
          >>> turtle.heading()
          0.0
          >>> turtle.circle(50)
          >>> turtle.position()
          (-0.00,0.00)
          >>> turtle.heading()
          0.0
          >>> turtle.circle(120, 180)  # draw a semicircle
          >>> turtle.position()
          (0.00,240.00)
          >>> turtle.heading()
          180.0

 -- 函数: turtle.dot (size=None, *color)


     参数:

        * ‘size’ – 一个整型数 >= 1 (如果指定)

        * ‘color’ – 一个颜色字符串或颜色数值元组

     绘制一个直径为 `size'，颜色为 `color' 的圆点。如果 `size' 未指定，
     则直径取 pensize+4 和 2*pensize 中的较大值。

          >>> turtle.home()
          >>> turtle.dot()
          >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
          >>> turtle.position()
          (100.00,-0.00)
          >>> turtle.heading()
          0.0

 -- 函数: turtle.stamp ()

     在海龟当前位置印制一个海龟形状。返回该印章的 stamp_id，印章可以通过
     调用 ‘clearstamp(stamp_id)’ 来删除。

          >>> turtle.color("blue")
          >>> turtle.stamp()
          11
          >>> turtle.fd(50)

 -- 函数: turtle.clearstamp (stampid)


     参数: ‘stampid’ – 一个整型数，必须是之前 *note stamp(): 30c3. 调用
     的返回值

     删除 `stampid' 指定的印章。

          >>> turtle.position()
          (150.00,-0.00)
          >>> turtle.color("blue")
          >>> astamp = turtle.stamp()
          >>> turtle.fd(50)
          >>> turtle.position()
          (200.00,-0.00)
          >>> turtle.clearstamp(astamp)
          >>> turtle.position()
          (200.00,-0.00)

 -- 函数: turtle.clearstamps (n=None)


     参数: ‘n’ – 一个整型数 (或 ‘None’)

     删除全部或前/后 `n' 个海龟印章。如果 `n' 为 ‘None’ 则删除全部印章，
     如果 `n' > 0 则删除前 `n' 个印章，否则如果 `n' < 0 则删除后 `n' 个
     印章。

          >>> for i in range(8):
          ...     turtle.stamp(); turtle.fd(30)
          13
          14
          15
          16
          17
          18
          19
          20
          >>> turtle.clearstamps(2)
          >>> turtle.clearstamps(-2)
          >>> turtle.clearstamps()

 -- 函数: turtle.undo ()

     撤消 (或连续撤消) 最近的一个 (或多个) 海龟动作。可撤消的次数由撤消
     缓冲区的大小决定。

          >>> for i in range(4):
          ...     turtle.fd(50); turtle.lt(80)
          ...
          >>> for i in range(8):
          ...     turtle.undo()

 -- 函数: turtle.speed (speed=None)


     参数: ‘speed’ – 一个 0..10 范围内的整型数或速度字符串 (见下)

     设置海龟移动的速度为 0..10 表示的整型数值。如未指定参数则返回当前速
     度。

     如果输入数值大于 10 或小于 0.5 则速度设为 0。速度字符串与速度值的对
     应关系如下:

        * "fastest": 0 最快

        * "fast": 10 快

        * "normal": 6 正常

        * "slow": 3 慢

        * "slowest": 1 最慢

     速度值从 1 到 10，画线和海龟转向的动画效果逐级加快。

     注意: `speed' = 0 表示 `没有' 动画效果。forward/back 将使海龟向前
     /向后跳跃，同样的 left/right 将使海龟立即改变朝向。

          >>> turtle.speed()
          3
          >>> turtle.speed('normal')
          >>> turtle.speed()
          6
          >>> turtle.speed(9)
          >>> turtle.speed()
          9


File: python.info,  Node: 获取海龟的状态,  Next: 度量单位设置,  Prev: 海龟动作,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.7 获取海龟的状态
.......................

 -- 函数: turtle.position ()
 -- 函数: turtle.pos ()

     返回海龟当前的坐标 (x,y) (为 *note Vec2D: 3120. 矢量类对象)。

          >>> turtle.pos()
          (440.00,-0.00)

 -- 函数: turtle.towards (x, y=None)


     参数:

        * ‘x’ – 一个数值或数值对/矢量，或一个海龟实例

        * ‘y’ – 一个数值——如果 `x' 是一个数值，否则为 ‘None’

     返回从海龟位置到由 (x,y)、矢量或另一海龟所确定位置的连线的夹角。 此
     数值依赖于海龟的初始朝向，这又取决于 "standard"/"world" 或 "logo" 模
     式设置。

          >>> turtle.goto(10, 10)
          >>> turtle.towards(0,0)
          225.0

 -- 函数: turtle.xcor ()

     返回海龟的 x 坐标。

          >>> turtle.home()
          >>> turtle.left(50)
          >>> turtle.forward(100)
          >>> turtle.pos()
          (64.28,76.60)
          >>> print(round(turtle.xcor(), 5))
          64.27876

 -- 函数: turtle.ycor ()

     返回海龟的 y 坐标。

          >>> turtle.home()
          >>> turtle.left(60)
          >>> turtle.forward(100)
          >>> print(turtle.pos())
          (50.00,86.60)
          >>> print(round(turtle.ycor(), 5))
          86.60254

 -- 函数: turtle.heading ()

     返回海龟当前的朝向 (数值依赖于海龟模式参见 *note mode(): 3111.)。

          >>> turtle.home()
          >>> turtle.left(67)
          >>> turtle.heading()
          67.0

 -- 函数: turtle.distance (x, y=None)


     参数:

        * ‘x’ – 一个数值或数值对/矢量，或一个海龟实例

        * ‘y’ – 一个数值——如果 `x' 是一个数值，否则为 ‘None’

     返回从海龟位置到由 (x,y)，适量或另一海龟对应位置的单位距离。

          >>> turtle.home()
          >>> turtle.distance(30,40)
          50.0
          >>> turtle.distance((30,40))
          50.0
          >>> joe = Turtle()
          >>> joe.forward(77)
          >>> turtle.distance(joe)
          77.0


File: python.info,  Node: 度量单位设置,  Next: 画笔控制,  Prev: 获取海龟的状态,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.8 度量单位设置
.....................

 -- 函数: turtle.degrees (fullcircle=360.0)


     参数: ‘fullcircle’ – 一个数值

     设置角度的度量单位，即设置一个圆周为多少 "度"。默认值为 360 度。

          >>> turtle.home()
          >>> turtle.left(90)
          >>> turtle.heading()
          90.0

          Change angle measurement unit to grad (also known as gon,
          grade, or gradian and equals 1/100-th of the right angle.)
          >>> turtle.degrees(400.0)
          >>> turtle.heading()
          100.0
          >>> turtle.degrees(360)
          >>> turtle.heading()
          90.0

 -- 函数: turtle.radians ()

     设置角度的度量单位为弧度。其值等于 ‘degrees(2*math.pi)’。

          >>> turtle.home()
          >>> turtle.left(90)
          >>> turtle.heading()
          90.0
          >>> turtle.radians()
          >>> turtle.heading()
          1.5707963267948966


File: python.info,  Node: 画笔控制,  Next: 海龟状态,  Prev: 度量单位设置,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.9 画笔控制
.................

* Menu:

* 绘图状态::
* 颜色控制::
* 填充::
* 更多绘图控制::


File: python.info,  Node: 绘图状态,  Next: 颜色控制,  Up: 画笔控制

5.24.1.10 绘图状态
..................

 -- 函数: turtle.pendown ()
 -- 函数: turtle.pd ()
 -- 函数: turtle.down ()

     画笔落下 – 移动时将画线。

 -- 函数: turtle.penup ()
 -- 函数: turtle.pu ()
 -- 函数: turtle.up ()

     画笔抬起 – 移动时不画线。

 -- 函数: turtle.pensize (width=None)
 -- 函数: turtle.width (width=None)


     参数: ‘width’ – 一个正数值

     设置线条的粗细为 `width' 或返回该值。如果 resizemode 设为 "auto" 并
     且 turtleshape 为多边形，该多边形也以同样组细的线条绘制。如未指定参
     数，则返回当前的 pensize。

          >>> turtle.pensize()
          1
          >>> turtle.pensize(10)   # from here on lines of width 10 are drawn

 -- 函数: turtle.pen (pen=None, **pendict)


     参数:

        * ‘pen’ – 一个包含部分或全部下列键的字典

        * ‘pendict’ – 一个或多个以下列键为关键字的关键字参数

     返回或设置画笔的属性，以一个包含以下键值对的 "画笔字典" 表示:

        * "shown": True/False

        * "pendown": True/False

        * "pencolor": 颜色字符串或颜色元组

        * "fillcolor": 颜色字符串或颜色元组

        * "pensize": 正数值

        * "speed": 0..10 范围内的数值

        * "resizemode": "auto" 或 "user" 或 "noresize"

        * "stretchfactor": (正数值, 正数值)

        * "outline": 正数值

        * "tilt": 数值

     此字典可作为后续调用 *note pen(): 30d9. 时的参数，以恢复之前的画笔
     状态。另外还可将这些属性作为关键词参数提交。使用此方式可以用一条语
     句设置画笔的多个属性。

          >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
          >>> sorted(turtle.pen().items())
          [('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'),
           ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),
           ('shearfactor', 0.0), ('shown', True), ('speed', 9),
           ('stretchfactor', (1.0, 1.0)), ('tilt', 0.0)]
          >>> penstate=turtle.pen()
          >>> turtle.color("yellow", "")
          >>> turtle.penup()
          >>> sorted(turtle.pen().items())[:3]
          [('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow')]
          >>> turtle.pen(penstate, fillcolor="green")
          >>> sorted(turtle.pen().items())[:3]
          [('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red')]

 -- 函数: turtle.isdown ()

     如果画笔落下返回 ‘True’，如果画笔抬起返回 ‘False’。

          >>> turtle.penup()
          >>> turtle.isdown()
          False
          >>> turtle.pendown()
          >>> turtle.isdown()
          True


File: python.info,  Node: 颜色控制,  Next: 填充,  Prev: 绘图状态,  Up: 画笔控制

5.24.1.11 颜色控制
..................

 -- 函数: turtle.pencolor (*args)

     返回或设置画笔颜色。

     允许以下四种输入格式:

     ‘pencolor()’

          返回以颜色描述字符串或元组 (见示例) 表示的当前画笔颜色。可用作
          其他 color/pencolor/fillcolor 调用的输入。

     ‘pencolor(colorstring)’

          设置画笔颜色为 `colorstring' 指定的 Tk 颜色描述字符串，例如
          ‘"red"’、‘"yellow"’ 或 ‘"#33cc8c"’。

     ‘pencolor((r, g, b))’

          设置画笔颜色为以 `r', `g', `b' 元组表示的 RGB 颜色。`r', `g',
          `b' 的取值范围应为 0..colormode，colormode 的值为 1.0 或 255
          (参见 *note colormode(): 3112.)。

     ‘pencolor(r, g, b)’

          设置画笔颜色为以 `r', `g', `b' 表示的 RGB 颜色。`r', `g', `b'
          的取值范围应为 0..colormode。

     如果 turtleshape 为多边形，该多边形轮廓也以新设置的画笔颜色绘制。

           >>> colormode()
           1.0
           >>> turtle.pencolor()
           'red'
           >>> turtle.pencolor("brown")
           >>> turtle.pencolor()
           'brown'
           >>> tup = (0.2, 0.8, 0.55)
           >>> turtle.pencolor(tup)
           >>> turtle.pencolor()
           (0.2, 0.8, 0.5490196078431373)
           >>> colormode(255)
           >>> turtle.pencolor()
           (51.0, 204.0, 140.0)
           >>> turtle.pencolor('#32c18f')
           >>> turtle.pencolor()
           (50.0, 193.0, 143.0)

 -- 函数: turtle.fillcolor (*args)

     返回或设置填充颜色。

     允许以下四种输入格式:

     ‘fillcolor()’

          返回以颜色描述字符串或元组 (见示例) 表示的当前填充颜色。可用作
          其他 color/pencolor/fillcolor 调用的输入。

     ‘fillcolor(colorstring)’

          设置填充颜色为 `colorstring' 指定的 Tk 颜色描述字符串，例如
          ‘"red"’、‘"yellow"’ 或 ‘"#33cc8c"’。

     ‘fillcolor((r, g, b))’

          设置填充颜色为以 `r', `g', `b' 元组表示的 RGB 颜色。`r', `g',
          `b' 的取值范围应为 0..colormode，colormode 的值为 1.0 或 255
          (参见 *note colormode(): 3112.)。

     ‘fillcolor(r, g, b)’

          设置填充颜色为 `r', `g', `b' 表示的 RGB 颜色。`r', `g', `b' 的
          取值范围应为 0..colormode。

     如果 turtleshape 为多边形，该多边形内部也以新设置的填充颜色填充。

           >>> turtle.fillcolor("violet")
           >>> turtle.fillcolor()
           'violet'
           >>> turtle.pencolor()
           (50.0, 193.0, 143.0)
           >>> turtle.fillcolor((50, 193, 143))  # Integers, not floats
           >>> turtle.fillcolor()
           (50.0, 193.0, 143.0)
           >>> turtle.fillcolor('#ffffff')
           >>> turtle.fillcolor()
           (255.0, 255.0, 255.0)

 -- 函数: turtle.color (*args)

     返回或设置画笔颜色和填充颜色。

     允许多种输入格式。使用如下 0 至 3 个参数:

     ‘color()’

          返回以一对颜色描述字符串或元组表示的当前画笔颜色和填充颜色，两
          者可分别由 *note pencolor(): 30dc. 和 *note fillcolor(): 30dd.
          返回。

     ‘color(colorstring)’, ‘color((r,g,b))’, ‘color(r,g,b)’

          输入格式与 *note pencolor(): 30dc. 相同，同时设置填充颜色和画
          笔颜色为指定的值。

     ‘color(colorstring1, colorstring2)’, ‘color((r1,g1,b1), (r2,g2,b2))’

          相当于 ‘pencolor(colorstring1)’ 加 ‘fillcolor(colorstring2)’，
          使用其他输入格式的方法也与之类似。

     如果 turtleshape 为多边形，该多边形轮廓与填充也使用新设置的颜色。

           >>> turtle.color("red", "green")
           >>> turtle.color()
           ('red', 'green')
           >>> color("#285078", "#a0c8f0")
           >>> color()
           ((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))

另参见: Screen 方法 *note colormode(): 3112.。


File: python.info,  Node: 填充,  Next: 更多绘图控制,  Prev: 颜色控制,  Up: 画笔控制

5.24.1.12 填充
..............

 -- 函数: turtle.filling ()

     返回填充状态 (填充为 ‘True’，否则为 ‘False’)。

           >>> turtle.begin_fill()
           >>> if turtle.filling():
           ...    turtle.pensize(5)
           ... else:
           ...    turtle.pensize(3)

 -- 函数: turtle.begin_fill ()

     在绘制要填充的形状之前调用。

 -- 函数: turtle.end_fill ()

     填充上次调用 *note begin_fill(): 30df. 之后绘制的形状。

     自相交多边形或多个形状间的重叠区域是否填充取决于操作系统的图形引擎
     、重叠的类型以及重叠的层数。 例如上面的 Turtle 多芒星可能会全部填充
     为黄色，也可能会有一些白色区域。

          >>> turtle.color("black", "red")
          >>> turtle.begin_fill()
          >>> turtle.circle(80)
          >>> turtle.end_fill()


File: python.info,  Node: 更多绘图控制,  Prev: 填充,  Up: 画笔控制

5.24.1.13 更多绘图控制
......................

 -- 函数: turtle.reset ()

     从屏幕中删除海龟的绘图，海龟回到原点并设置所有变量为默认值。

          >>> turtle.goto(0,-22)
          >>> turtle.left(100)
          >>> turtle.position()
          (0.00,-22.00)
          >>> turtle.heading()
          100.0
          >>> turtle.reset()
          >>> turtle.position()
          (0.00,0.00)
          >>> turtle.heading()
          0.0

 -- 函数: turtle.clear ()

     从屏幕中删除指定海龟的绘图。不移动海龟。海龟的状态和位置以及其他海
     龟的绘图不受影响。

 -- 函数: turtle.write (arg, move=False, align="left", font=("Arial", 8,
          "normal"))


     参数:

        * ‘arg’ – 要书写到 TurtleScreen 的对象

        * ‘move’ – True/False

        * ‘align’ – 字符串 "left", "center" 或 "right"

        * ‘font’ – 一个三元组 (fontname, fontsize, fonttype)

     基于 `align' ("left", "center" 或 "right") 并使用给定的字体将文本
     —— `arg' 的字符串表示形式 —— 写到当前海龟位置。 如果 `move' 为真值
     ，画笔会移至文本的右下角。 默认情况下 `move' 为 ‘False’。

          >>> turtle.write("Home = ", True, align="center")
          >>> turtle.write((0,0), True)


File: python.info,  Node: 海龟状态,  Next: 使用事件,  Prev: 画笔控制,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.14 海龟状态
..................

* Menu:

* 可见性::
* 外观::


File: python.info,  Node: 可见性,  Next: 外观,  Up: 海龟状态

5.24.1.15 可见性
................

 -- 函数: turtle.hideturtle ()
 -- 函数: turtle.ht ()

     使海龟不可见。当你绘制复杂图形时这是个好主意，因为隐藏海龟可显著加
     快绘制速度。

          >>> turtle.hideturtle()

 -- 函数: turtle.showturtle ()
 -- 函数: turtle.st ()

     使海龟可见。

          >>> turtle.showturtle()

 -- 函数: turtle.isvisible ()

     如果海龟显示返回 ‘True’，如果海龟隐藏返回 ‘False’。

          >>> turtle.hideturtle()
          >>> turtle.isvisible()
          False
          >>> turtle.showturtle()
          >>> turtle.isvisible()
          True


File: python.info,  Node: 外观,  Prev: 可见性,  Up: 海龟状态

5.24.1.16 外观
..............

 -- 函数: turtle.shape (name=None)


     参数: ‘name’ – 一个有效的形状名字符串

     设置海龟形状为 `name' 指定的形状名，如未指定形状名则返回当前的形状
     名。`name' 指定的形状名应存在于 TurtleScreen 的 shape 字典中。多边
     形的形状初始时有以下几种: "arrow", "turtle", "circle", "square",
     "triangle", "classic"。要了解如何处理形状请参看 Screen 方法 *note
     register_shape(): 3115.。

          >>> turtle.shape()
          'classic'
          >>> turtle.shape("turtle")
          >>> turtle.shape()
          'turtle'

 -- 函数: turtle.resizemode (rmode=None)


     参数: ‘rmode’ – 字符串 "auto", "user", "noresize" 其中之一

     设置大小调整模式为以下值之一: "auto", "user", "noresize"。如未指定
     `rmode' 则返回当前的大小调整模式。不同的大小调整模式的效果如下:

        - "auto": 根据画笔粗细值调整海龟的外观。

        - "user": 根据拉伸因子和轮廓宽度 (outline) 值调整海龟的外观，两
          者是由 *note shapesize(): 30eb. 设置的。

        - "noresize": 不调整海龟的外观大小。

     ‘resizemode("user")’ 会由 *note shapesize(): 30eb. 带参数使用时被调
     用。

          >>> turtle.resizemode()
          'noresize'
          >>> turtle.resizemode("auto")
          >>> turtle.resizemode()
          'auto'

 -- 函数: turtle.shapesize (stretch_wid=None, stretch_len=None,
          outline=None)
 -- 函数: turtle.turtlesize (stretch_wid=None, stretch_len=None,
          outline=None)


     参数:

        * ‘stretch_wid’ – 正数值

        * ‘stretch_len’ – 正数值

        * ‘outline’ – 正数值

     返回或设置画笔的属性 x/y-拉伸因子和/或轮廓。设置大小调整模式为
     "user"。当且仅当大小调整模式设为 "user" 时海龟会基于其拉伸因子调整
     外观: `stretch_wid' 为垂直于其朝向的宽度拉伸因子，`stretch_len' 为
     平等于其朝向的长度拉伸因子，决定形状轮廓线的粗细。

          >>> turtle.shapesize()
          (1.0, 1.0, 1)
          >>> turtle.resizemode("user")
          >>> turtle.shapesize(5, 5, 12)
          >>> turtle.shapesize()
          (5, 5, 12)
          >>> turtle.shapesize(outline=8)
          >>> turtle.shapesize()
          (5, 5, 8)

 -- 函数: turtle.shearfactor (shear=None)


     参数: ‘shear’ – 数值 (可选)

     设置或返回当前的剪切因子。根据 share 指定的剪切因子即剪切角度的切线
     来剪切海龟形状。`不' 改变海龟的朝向 (移动方向)。如未指定 shear 参数
     : 返回当前的剪切因子即剪切角度的切线，与海龟朝向平行的线条将被剪切
     。

           >>> turtle.shape("circle")
           >>> turtle.shapesize(5,2)
           >>> turtle.shearfactor(0.5)
           >>> turtle.shearfactor()
           0.5

 -- 函数: turtle.tilt (angle)


     参数: ‘angle’ – 一个数值

     海龟形状自其当前的倾角转动 `angle' 指定的角度，但 `不' 改变海龟的朝
     向 (移动方向)。

          >>> turtle.reset()
          >>> turtle.shape("circle")
          >>> turtle.shapesize(5,2)
          >>> turtle.tilt(30)
          >>> turtle.fd(50)
          >>> turtle.tilt(30)
          >>> turtle.fd(50)

 -- 函数: turtle.settiltangle (angle)


     参数: ‘angle’ – 一个数值

     旋转海龟形状使其指向 `angle' 指定的方向，忽略其当前的倾角，`不' 改
     变海龟的朝向 (移动方向)。

          >>> turtle.reset()
          >>> turtle.shape("circle")
          >>> turtle.shapesize(5,2)
          >>> turtle.settiltangle(45)
          >>> turtle.fd(50)
          >>> turtle.settiltangle(-45)
          >>> turtle.fd(50)

     3.1 版后已移除.

 -- 函数: turtle.tiltangle (angle=None)


     参数: ‘angle’ – 一个数值 (可选)

     设置或返回当前的倾角。如果指定 angle 则旋转海龟形状使其指向 angle 指
     定的方向，忽略其当前的倾角。`不' 改变海龟的朝向 (移动方向)。如果未
     指定 angle: 返回当前的倾角，即海龟形状的方向和海龟朝向 (移动方向) 之
     间的夹角。

          >>> turtle.reset()
          >>> turtle.shape("circle")
          >>> turtle.shapesize(5,2)
          >>> turtle.tilt(45)
          >>> turtle.tiltangle()
          45.0

 -- 函数: turtle.shapetransform (t11=None, t12=None, t21=None, t22=None)


     参数:

        * ‘t11’ – 一个数值 (可选)

        * ‘t12’ – 一个数值 (可选)

        * ‘t21’ – 一个数值 (可选)

        * ‘t12’ – 一个数值 (可选)

     设置或返回海龟形状的当前变形矩阵。

     如未指定任何矩阵元素，则返回以 4 元素元组表示的变形矩阵。 否则就根
     据设置指定元素的矩阵来改变海龟形状，矩阵第一排的值为 t11, t12 而第
     二排的值为 t21, t22。 行列式 t11 * t22 - t12 * t21 必须不为零，否则
     会引发错误。 根据指定矩阵修改拉伸因子 stretchfactor, 剪切因子
     shearfactor 和倾角 tiltangle。

          >>> turtle = Turtle()
          >>> turtle.shape("square")
          >>> turtle.shapesize(4,2)
          >>> turtle.shearfactor(-0.5)
          >>> turtle.shapetransform()
          (4.0, -1.0, -0.0, 2.0)

 -- 函数: turtle.get_shapepoly ()

     返回以坐标值对元组表示的当前形状多边形。这可以用于定义一个新形状或
     一个复合形状的多个组成部分。

          >>> turtle.shape("square")
          >>> turtle.shapetransform(4, -1, 0, 2)
          >>> turtle.get_shapepoly()
          ((50, -20), (30, 20), (-50, 20), (-30, -20))


File: python.info,  Node: 使用事件,  Next: 特殊海龟方法,  Prev: 海龟状态,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.17 使用事件
..................

 -- 函数: turtle.onclick (fun, btn=1, add=None)


     参数:

        * ‘fun’ – 一个函数，调用时将传入两个参数表示在画布上点击的坐标。

        * ‘btn’ – 鼠标按钮编号，默认值为 1 (鼠标左键)

        * ‘add’ – ‘True’ 或 ‘False’ – 如为 ‘True’ 则将添加一个新绑定，否
          则将取代先前的绑定

     将 `fun' 指定的函数绑定到鼠标点击此海龟事件。如果 `fun' 值为
     ‘None’，则移除现有的绑定。以下为使用匿名海龟即过程式的示例:

          >>> def turn(x, y):
          ...     left(180)
          ...
          >>> onclick(turn)  # Now clicking into the turtle will turn it.
          >>> onclick(None)  # event-binding will be removed

 -- 函数: turtle.onrelease (fun, btn=1, add=None)


     参数:

        * ‘fun’ – 一个函数，调用时将传入两个参数表示在画布上点击的坐标。

        * ‘btn’ – 鼠标按钮编号，默认值为 1 (鼠标左键)

        * ‘add’ – ‘True’ 或 ‘False’ – 如为 ‘True’ 则将添加一个新绑定，否
          则将取代先前的绑定

     将 `fun' 指定的函数绑定到在此海龟上释放鼠标按键事件。如果 `fun' 值
     为 ‘None’，则移除现有的绑定。

          >>> class MyTurtle(Turtle):
          ...     def glow(self,x,y):
          ...         self.fillcolor("red")
          ...     def unglow(self,x,y):
          ...         self.fillcolor("")
          ...
          >>> turtle = MyTurtle()
          >>> turtle.onclick(turtle.glow)     # clicking on turtle turns fillcolor red,
          >>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.

 -- 函数: turtle.ondrag (fun, btn=1, add=None)


     参数:

        * ‘fun’ – 一个函数，调用时将传入两个参数表示在画布上点击的坐标。

        * ‘btn’ – 鼠标按钮编号，默认值为 1 (鼠标左键)

        * ‘add’ – ‘True’ 或 ‘False’ – 如为 ‘True’ 则将添加一个新绑定，否
          则将取代先前的绑定

     将 `fun' 指定的函数绑定到在此海龟上移动鼠标事件。如果 `fun' 值为
     ‘None’，则移除现有的绑定。

     注: 在海龟上移动鼠标事件之前应先发生在此海龟上点击鼠标事件。

          >>> turtle.ondrag(turtle.goto)

     在此之后点击并拖动海龟可在屏幕上手绘线条 (如果画笔为落下)。


File: python.info,  Node: 特殊海龟方法,  Next: 复合形状,  Prev: 使用事件,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.18 特殊海龟方法
......................

 -- 函数: turtle.begin_poly ()

     开始记录多边形的顶点。当前海龟位置为多边形的第一个顶点。

 -- 函数: turtle.end_poly ()

     停止记录多边形的顶点。当前海龟位置为多边形的最后一个顶点。它将连线
     到第一个顶点。

 -- 函数: turtle.get_poly ()

     返回最新记录的多边形。

          >>> turtle.home()
          >>> turtle.begin_poly()
          >>> turtle.fd(100)
          >>> turtle.left(20)
          >>> turtle.fd(30)
          >>> turtle.left(60)
          >>> turtle.fd(50)
          >>> turtle.end_poly()
          >>> p = turtle.get_poly()
          >>> register_shape("myFavouriteShape", p)

 -- 函数: turtle.clone ()

     创建并返回海龟的克隆体，具有相同的位置、朝向和海龟属性。

          >>> mick = Turtle()
          >>> joe = mick.clone()

 -- 函数: turtle.getturtle ()
 -- 函数: turtle.getpen ()

     返回海龟对象自身。唯一合理的用法: 作为一个函数来返回 "匿名海龟":

          >>> pet = getturtle()
          >>> pet.fd(50)
          >>> pet
          <turtle.Turtle object at 0x...>

 -- 函数: turtle.getscreen ()

     返回作为海龟绘图场所的 *note TurtleScreen: 30a8. 类对象。该对象将可
     调用 TurtleScreen 方法。

          >>> ts = turtle.getscreen()
          >>> ts
          <turtle._Screen object at 0x...>
          >>> ts.bgcolor("pink")

 -- 函数: turtle.setundobuffer (size)


     参数: ‘size’ – 一个整型数值或 ‘None’

     设置或禁用撤销缓冲区。 如果 `size' 为整数，则开辟一个给定大小的空撤
     销缓冲区。 `size' 给出了可以通过 *note undo(): 30c6. 方法/函数撤销
     海龟动作的最大次数。 如果 `size' 为 ‘None’，则禁用撤销缓冲区。

          >>> turtle.setundobuffer(42)

 -- 函数: turtle.undobufferentries ()

     返回撤销缓冲区里的条目数。

          >>> while undobufferentries():
          ...     undo()


File: python.info,  Node: 复合形状,  Prev: 特殊海龟方法,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.19 复合形状
..................

要使用由多个不同颜色多边形构成的复合海龟形状，你必须明确地使用辅助类
*note Shape: 312f.，具体步骤如下:

  1. 创建一个空 Shape 对象，类型为 "compound"。

  2. 按照需要使用 ‘addcomponent()’ 方法向此对象添加多个部件。

     例如:

          >>> s = Shape("compound")
          >>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5))
          >>> s.addcomponent(poly1, "red", "blue")
          >>> poly2 = ((0,0),(10,-5),(-10,-5))
          >>> s.addcomponent(poly2, "blue", "red")

  3. 接下来将 Shape 对象添加到 Screen 对象的形状列表并使用它:

          >>> register_shape("myshape", s)
          >>> shape("myshape")

     注解: *note Shape: 312f. 类在 *note register_shape(): 3115. 方法的
     内部以多种方式使用。应用程序编写者 `只有' 在使用上述的复合形状时才
     需要处理 Shape 类。


File: python.info,  Node: TurtleScreen/Screen 方法及对应函数,  Next: 公共类,  Prev: RawTurtle/Turtle 方法和对应函数,  Up: turtle --- 海龟绘图

5.24.1.20 TurtleScreen/Screen 方法及对应函数
............................................

本节中的大部分示例都使用 TurtleScreen 类的一个实例，命名为 ‘screen’。

* Menu:

* 窗口控制::
* 动画控制::
* 使用屏幕事件::
* 输入方法::
* 设置与特殊方法::
* Screen 专有方法, 而非继承自 TurtleScreen: Screen 专有方法 而非继承自 TurtleScreen.


File: python.info,  Node: 窗口控制,  Next: 动画控制,  Up: TurtleScreen/Screen 方法及对应函数

5.24.1.21 窗口控制
..................

 -- 函数: turtle.bgcolor (*args)


     参数: ‘args’ – 一个颜色字符串或三个取值范围 0..colormode 内的数值或
     一个取值范围相同的数值3元组

     设置或返回 TurtleScreen 的背景颜色。

          >>> screen.bgcolor("orange")
          >>> screen.bgcolor()
          'orange'
          >>> screen.bgcolor("#800080")
          >>> screen.bgcolor()
          (128.0, 0.0, 128.0)

 -- 函数: turtle.bgpic (picname=None)


     参数: ‘picname’ – 一个字符串, gif-文件名, ‘"nopic"’, 或 ‘None’

     设置背景图片或返回当前背景图片名称。如果 `picname' 为一个文件名，则
     将相应图片设为背景。如果 `picname' 为 ‘"nopic"’，则删除当前背景图片
     。如果 `picname' 为 ‘None’，则返回当前背景图片文件名。:

          >>> screen.bgpic()
          'nopic'
          >>> screen.bgpic("landscape.gif")
          >>> screen.bgpic()
          "landscape.gif"

 -- 函数: turtle.clear ()
 -- 函数: turtle.clearscreen ()

     从中删除所有海龟的全部绘图。将已清空的 TurtleScreen 重置为初始状态:
     白色背景，无背景片，无事件绑定并启用追踪。

          注解: 此 TurtleScreen 方法作为全局函数时只有一个名字
          ‘clearscreen’。全局函数 ‘clear’ 所对应的是 Turtle 方法
          ‘clear’。

 -- 函数: turtle.reset ()
 -- 函数: turtle.resetscreen ()

     重置屏幕上的所有海龟为其初始状态。

          注解: 此 TurtleScreen 方法作为全局函数时只有一个名字
          ‘resetscreen’。全局函数 ‘reset’ 所对应的是 Turtle 方法
          ‘reset’。

 -- 函数: turtle.screensize (canvwidth=None, canvheight=None, bg=None)


     参数:

        * ‘canvwidth’ – 正整型数，以像素表示画布的新宽度值

        * ‘canvheight’ – 正整型数，以像素表示画面的新高度值

        * ‘bg’ – 颜色字符串或颜色元组，新的背景颜色

     如未指定任何参数，则返回当前的 (canvaswidth, canvasheight)。否则改
     变作为海龟绘图场所的画布大小。不改变绘图窗口。要观察画布的隐藏区域
     ，可以使用滚动条。通过此方法可以令之前绘制于画布之外的图形变为可见
     。

          >>> screen.screensize()
          (400, 300)
          >>> screen.screensize(2000,1500)
          >>> screen.screensize()
          (2000, 1500)

     也可以用来寻找意外逃走的海龟 ;-)

 -- 函数: turtle.setworldcoordinates (llx, lly, urx, ury)


     参数:

        * ‘llx’ – 一个数值, 画布左下角的 x-坐标

        * ‘lly’ – 一个数值, 画布左下角的 y-坐标

        * ‘urx’ – 一个数值, 画面右上角的 x-坐标

        * ‘ury’ – 一个数值, 画布右上角的 y-坐标

     设置用户自定义坐标系并在必要时切换模式为 "world"。这会执行一次
     ‘screen.reset()’。如果 "world" 模式已激活，则所有图形将根据新的坐标
     系重绘。

     `注意': 在用户自定义坐标系中，角度可能显得扭曲。

          >>> screen.reset()
          >>> screen.setworldcoordinates(-50,-7.5,50,7.5)
          >>> for _ in range(72):
          ...     left(10)
          ...
          >>> for _ in range(8):
          ...     left(45); fd(2)   # a regular octagon


File: python.info,  Node: 动画控制,  Next: 使用屏幕事件,  Prev: 窗口控制,  Up: TurtleScreen/Screen 方法及对应函数

5.24.1.22 动画控制
..................

 -- 函数: turtle.delay (delay=None)


     参数: ‘delay’ – 正整型数

     设置或返回以毫秒数表示的延迟值 `delay'。(这约等于连续两次画布刷新的
     间隔时间。) 绘图延迟越长，动画速度越慢。

     可选参数:

          >>> screen.delay()
          10
          >>> screen.delay(5)
          >>> screen.delay()
          5

 -- 函数: turtle.tracer (n=None, delay=None)


     参数:

        * ‘n’ – 非负整型数

        * ‘delay’ – 非负整型数

     启用/禁用海龟动画并设置刷新图形的延迟时间。如果指定 `n' 值，则只有
     每第 n 次屏幕刷新会实际执行。(可被用来加速复杂图形的绘制。) 如果调
     用时不带参数，则返回当前保存的 n 值。第二个参数设置延迟值 (参见
     *note delay(): 3106.)。

          >>> screen.tracer(8, 25)
          >>> dist = 2
          >>> for i in range(200):
          ...     fd(dist)
          ...     rt(90)
          ...     dist += 2

 -- 函数: turtle.update ()

     执行一次 TurtleScreen 刷新。在禁用追踪时使用。

另参见 RawTurtle/Turtle 方法 *note speed(): 30c7.。


File: python.info,  Node: 使用屏幕事件,  Next: 输入方法,  Prev: 动画控制,  Up: TurtleScreen/Screen 方法及对应函数

5.24.1.23 使用屏幕事件
......................

 -- 函数: turtle.listen (xdummy=None, ydummy=None)

     设置焦点到 TurtleScreen (以便接收按键事件)。使用两个 Dummy 参数以便
     能够传递 *note listen(): 3109. 给 onclick 方法。

 -- 函数: turtle.onkey (fun, key)
 -- 函数: turtle.onkeyrelease (fun, key)


     参数:

        * ‘fun’ – 一个无参数的函数或 ‘None’

        * ‘key’ – 一个字符串: 键 (例如 "a") 或键标 (例如 "space")

     绑定 `fun' 指定的函数到按键释放事件。如果 `fun' 值为 ‘None’，则移除
     事件绑定。注: 为了能够注册按键事件，TurtleScreen 必须得到焦点。(参
     见 method *note listen(): 3109. 方法。)

          >>> def f():
          ...     fd(50)
          ...     lt(60)
          ...
          >>> screen.onkey(f, "Up")
          >>> screen.listen()

 -- 函数: turtle.onkeypress (fun, key=None)


     参数:

        * ‘fun’ – 一个无参数的函数或 ‘None’

        * ‘key’ – 一个字符串: 键 (例如 "a") 或键标 (例如 "space")

     绑定 `fun' 指定的函数到指定键的按下事件。如未指定键则绑定到任意键的
     按下事件。注: 为了能够注册按键事件，必须得到焦点。(参见 *note
     listen(): 3109. 方法。)

          >>> def f():
          ...     fd(50)
          ...
          >>> screen.onkey(f, "Up")
          >>> screen.listen()

 -- 函数: turtle.onclick (fun, btn=1, add=None)
 -- 函数: turtle.onscreenclick (fun, btn=1, add=None)


     参数:

        * ‘fun’ – 一个函数，调用时将传入两个参数表示在画布上点击的坐标。

        * ‘btn’ – 鼠标按钮编号，默认值为 1 (鼠标左键)

        * ‘add’ – ‘True’ 或 ‘False’ – 如为 ‘True’ 则将添加一个新绑定，否
          则将取代先前的绑定

     绑定 `fun' 指定的函数到鼠标点击屏幕事件。如果 `fun' 值为 ‘None’，则
     移除现有的绑定。

     以下示例使用一个 TurtleScreen 实例 ‘screen’ 和一个 Turtle 实例
     ‘turtle’:

          >>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
          >>>                             # make the turtle move to the clicked point.
          >>> screen.onclick(None)        # remove event binding again

          注解: 此 TurtleScreen 方法作为全局函数时只有一个名字
          ‘onscreenclick’。全局函数 ‘onclick’ 所对应的是 Turtle 方法
          ‘onclick’。

 -- 函数: turtle.ontimer (fun, t=0)


     参数:

        * ‘fun’ – 一个无参数的函数

        * ‘t’ – 一个数值 >= 0

     安装一个计时器，在 `t' 毫秒后调用 `fun' 函数。

          >>> running = True
          >>> def f():
          ...     if running:
          ...         fd(50)
          ...         lt(60)
          ...         screen.ontimer(f, 250)
          >>> f()   ### makes the turtle march around
          >>> running = False

 -- 函数: turtle.mainloop ()
 -- 函数: turtle.done ()

     开始事件循环 - 调用 Tkinter 的 mainloop 函数。必须作为一个海龟绘图
     程序的结束语句。如果一个脚本是在以 -n 模式 (无子进程) 启动的 IDLE 中
     运行时 `不可' 使用 - 用于实现海龟绘图的交互功能。:

          >>> screen.mainloop()


File: python.info,  Node: 输入方法,  Next: 设置与特殊方法,  Prev: 使用屏幕事件,  Up: TurtleScreen/Screen 方法及对应函数

5.24.1.24 输入方法
..................

 -- 函数: turtle.textinput (title, prompt)


     参数:

        * ‘title’ – string

        * ‘prompt’ – string

     弹出一个对话框窗口用来输入一个字符串。形参 title 为对话框窗口的标题
     ，prompt 为一条文本，通常用来提示要输入什么信息。返回输入的字符串。
     如果对话框被取消则返回 ‘None’。:

          >>> screen.textinput("NIM", "Name of first player:")

 -- 函数: turtle.numinput (title, prompt, default=None, minval=None,
          maxval=None)


     参数:

        * ‘title’ – string

        * ‘prompt’ – string

        * ‘default’ – 数值 (可选)

        * ‘minval’ – 数值 (可选)

        * ‘maxval’ – 数值 (可选)

     弹出一个对话框窗口用来输入一个数值。title 为对话框窗口的标题，
     prompt 为一条文本，通常用来描述要输入的数值信息。default: 默认值,
     minval: 可输入的最小值, maxval: 可输入的最大值。输入数值的必须在指
     定的 minval ..  maxval 范围之内，否则将给出一条提示，对话框保持打开
     等待修改。返回输入的数值。如果对话框被取消则返回 ‘None’。:

          >>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)


File: python.info,  Node: 设置与特殊方法,  Next: Screen 专有方法 而非继承自 TurtleScreen,  Prev: 输入方法,  Up: TurtleScreen/Screen 方法及对应函数

5.24.1.25 设置与特殊方法
........................

 -- 函数: turtle.mode (mode=None)


     参数: ‘mode’ – 字符串 "standard", "logo" 或 "world" 其中之一

     设置海龟模式 ("standard", "logo" 或 "world") 并执行重置。如未指定模
     式则返回当前的模式。

     "standard" 模式与旧的 *note turtle: 117. 兼容。"logo" 模式与大部分
     Logo 海龟绘图兼容。"world" 模式使用用户自定义的 "世界坐标系"。`注意
     ': 在此模式下，如果 ‘x/y’ 单位比率不等于 1 则角度会显得扭曲。

     模式             初始海龟朝向                  正数角度
                                                    
     -----------------------------------------------------------------------
                                                    
     "standard"       朝右 (东)                     逆时针
                                                    
                                                    
     "logo"           朝上 (北)                     顺时针
                                                    

          >>> mode("logo")   # resets turtle heading to north
          >>> mode()
          'logo'

 -- 函数: turtle.colormode (cmode=None)


     参数: ‘cmode’ – 数值 1.0 或 255 其中之一

     返回颜色模式或将其设为 1.0 或 255。构成颜色三元组的 `r', `g', `b' 数
     值必须在 0..`cmode' 范围之内。

          >>> screen.colormode(1)
          >>> turtle.pencolor(240, 160, 80)
          Traceback (most recent call last):
               ...
          TurtleGraphicsError: bad color sequence: (240, 160, 80)
          >>> screen.colormode()
          1.0
          >>> screen.colormode(255)
          >>> screen.colormode()
          255
          >>> turtle.pencolor(240,160,80)

 -- 函数: turtle.getcanvas ()

     返回此 TurtleScreen 的 Canvas 对象。供了解 Tkinter 的 Canvas 对象内
     部机理的人士使用。

          >>> cv = screen.getcanvas()
          >>> cv
          <turtle.ScrolledCanvas object ...>

 -- 函数: turtle.getshapes ()

     返回所有当前可用海龟形状的列表。

          >>> screen.getshapes()
          ['arrow', 'blank', 'circle', ..., 'turtle']

 -- 函数: turtle.register_shape (name, shape=None)
 -- 函数: turtle.addshape (name, shape=None)

     调用此函数有三种不同方式:

       1. `name' 为一个 gif 文件的文件名， `shape' 为 ‘None’: 安装相应的
          图像形状。:

               >>> screen.register_shape("turtle.gif")

               注解: 当海龟转向时图像形状 `不会' 转动，因此无法显示海龟
               的朝向!

       2. `name' 为指定的字符串，`shape' 为由坐标值对构成的元组: 安装相
          应的多边形形状。

               >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))

       3. `name' 为指定的字符串， 为一个 (复合) *note Shape: 312f. 类对
          象: 安装相应的复合形状。

     将一个海龟形状加入 TurtleScreen 的形状列表。只有这样注册过的形状才
     能通过执行 ‘shape(shapename)’ 命令来使用。

 -- 函数: turtle.turtles ()

     返回屏幕上的海龟列表。

          >>> for turtle in screen.turtles():
          ...     turtle.color("red")

 -- 函数: turtle.window_height ()

     返回海龟窗口的高度。:

          >>> screen.window_height()
          480

 -- 函数: turtle.window_width ()

     返回海龟窗口的宽度。:

          >>> screen.window_width()
          640


File: python.info,  Node: Screen 专有方法 而非继承自 TurtleScreen,  Prev: 设置与特殊方法,  Up: TurtleScreen/Screen 方法及对应函数

5.24.1.26 Screen 专有方法, 而非继承自 TurtleScreen
..................................................

 -- 函数: turtle.bye ()

     关闭海龟绘图窗口。

 -- 函数: turtle.exitonclick ()

     将 ‘bye()’ 方法绑定到 Screen 上的鼠标点击事件。

     如果配置字典中 "using_IDLE" 的值为 ‘False’ (默认值) 则同时进入主事
     件循环。注: 如果启动 IDLE 时使用了 ‘-n’ 开关 (无子进程)，
     ‘turtle.cfg’ 中此数值应设为 ‘True’。在此情况下 IDLE 本身的主事件循
     环同样会作用于客户脚本。

 -- 函数: turtle.setup (width=_CFG["width"], height=_CFG["height"],
          startx=_CFG["leftright"], starty=_CFG["topbottom"])

     设置主窗口的大小和位置。默认参数值保存在配置字典中，可通过
     ‘turtle.cfg’ 文件进行修改。


     参数:

        * ‘width’ – 如为一个整型数值，表示大小为多少像素，如为一个浮点数
          值，则表示屏幕的占比；默认为屏幕的 50%

        * ‘height’ – 如为一个整型数值，表示高度为多少像素，如为一个浮点
          数值，则表示屏幕的占比；默认为屏幕的 75%

        * ‘startx’ – 如为正值，表示初始位置距离屏幕左边缘多少像素，负值
          表示距离右边缘，‘None’ 表示窗口水平居中

        * ‘starty’ – 如为正值，表示初始位置距离屏幕上边缘多少像素，负值
          表示距离下边缘，‘None’ 表示窗口垂直居中

          >>> screen.setup (width=200, height=200, startx=0, starty=0)
          >>>              # sets window to 200x200 pixels, in upper left of screen
          >>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
          >>>              # sets window to 75% of screen by 50% of screen and centers

 -- 函数: turtle.title (titlestring)


     参数: ‘titlestring’ – 一个字符串，显示为海龟绘图窗口的标题栏文本

     设置海龟窗口标题为 `titlestring' 指定的文本。

          >>> screen.title("Welcome to the turtle zoo!")


File: python.info,  Node: 公共类,  Next: 帮助与配置,  Prev: TurtleScreen/Screen 方法及对应函数,  Up: turtle --- 海龟绘图

5.24.1.27 公共类
................

 -- 类: turtle.RawTurtle (canvas)
 -- 类: turtle.RawPen (canvas)


     参数: ‘canvas’ – 一个 ‘tkinter.Canvas’ , *note ScrolledCanvas:
     30a9. 或 *note TurtleScreen: 30a8. 类对象

     创建一个海龟。海龟对象具有 "Turtle/RawTurtle 方法" 一节所述的全部方
     法。

 -- 类: turtle.Turtle

     RawTurtle 的子类，具有相同的接口，但其绘图场所为默认的 *note
     Screen: 30aa. 类对象，在首次使用时自动创建。

 -- 类: turtle.TurtleScreen (cv)


     参数: ‘cv’ – 一个 ‘tkinter.Canvas’ 类对象

     提供面向屏幕的方法例如 ‘setbg()’ 等。说明见上文。

 -- 类: turtle.Screen

     TurtleScreen 的子类，*note 增加了四个方法: 3137.

 -- 类: turtle.ScrolledCanvas (master)


     参数: ‘master’ – 可容纳 ScrolledCanvas 的 Tkinter 部件，即添加了滚
     动条的 Tkinter-canvas

     由 Screen 类使用，使其能够自动提供一个 ScrolledCanvas 作为海龟的绘
     图场所。

 -- 类: turtle.Shape (type_, data)


     参数: ‘type_’ – 字符串 "polygon", "image", "compound" 其中之一

     实现形状的数据结构。‘(type_, data)’ 必须遵循以下定义:

     `type_'         `data'
                     
     -------------------------------------------------------------------------------
                     
     "polygon"       一个多边形元组，即由坐标值对构成的元组
                     
                     
     "image"         一个图片 (此形式仅限内部使用!)
                     
                     
     "compound"      ‘None’ (复合形状必须使用 *note addcomponent(): 3139. 方法来
                     构建)
                     

      -- 方法: addcomponent (poly, fill, outline=None)


          参数:

             * ‘poly’ – 一个多边形，即由数值对构成的元组

             * ‘fill’ – 一种颜色，将用来填充 `poly' 指定的多边形

             * ‘outline’ – 一种颜色，用于多边形的轮廓 (如有指定)

          示例:

               >>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
               >>> s = Shape("compound")
               >>> s.addcomponent(poly, "red", "blue")
               >>> # ... add more components and then use register_shape()

          参见 *note 复合形状: 312e.。

 -- 类: turtle.Vec2D (x, y)

     一个二维矢量类，用来作为实现海龟绘图的辅助类。也可能在海龟绘图程序
     中使用。派生自元组，因此矢量也属于元组!

     提供的运算 (`a', `b' 为矢量, `k' 为数值):

        * ‘a + b’ 矢量加法

        * ‘a - b’ 矢量减法

        * ‘a * b’ 内积

        * ‘k * a’ 和 ‘a * k’ 与标量相乘

        * ‘abs(a)’ a 的绝对值

        * ‘a.rotate(angle)’ 旋转


File: python.info,  Node: 帮助与配置,  Next: turtledemo --- 演示脚本集,  Prev: 公共类,  Up: turtle --- 海龟绘图

5.24.1.28 帮助与配置
....................

* Menu:

* 如何使用帮助::
* 文档字符串翻译为不同的语言::
* 如何配置 Screen 和 Turtle::


File: python.info,  Node: 如何使用帮助,  Next: 文档字符串翻译为不同的语言,  Up: 帮助与配置

5.24.1.29 如何使用帮助
......................

Screen 和 Turtle 类的公用方法以文档字符串提供了详细的文档。因此可以利用
Python 帮助工具获取这些在线帮助信息:

   - 当使用 IDLE 时，输入函数/方法调用将弹出工具提示显示其签名和文档字符
     串的头几行。

   - 对文法或函数调用 *note help(): 57b. 将显示其文档字符串:

          >>> help(Screen.bgcolor)
          Help on method bgcolor in module turtle:

          bgcolor(self, *args) unbound turtle.Screen method
              Set or return backgroundcolor of the TurtleScreen.

              Arguments (if given): a color string or three numbers
              in the range 0..colormode or a 3-tuple of such numbers.


                >>> screen.bgcolor("orange")
                >>> screen.bgcolor()
                "orange"
                >>> screen.bgcolor(0.5,0,0.5)
                >>> screen.bgcolor()
                "#800080"

          >>> help(Turtle.penup)
          Help on method penup in module turtle:

          penup(self) unbound turtle.Turtle method
              Pull the pen up -- no drawing when moving.

              Aliases: penup | pu | up

              No argument

              >>> turtle.penup()

   - 方法对应函数的文档字符串的形式会有一些修改:

          >>> help(bgcolor)
          Help on function bgcolor in module turtle:

          bgcolor(*args)
              Set or return backgroundcolor of the TurtleScreen.

              Arguments (if given): a color string or three numbers
              in the range 0..colormode or a 3-tuple of such numbers.

              Example::

                >>> bgcolor("orange")
                >>> bgcolor()
                "orange"
                >>> bgcolor(0.5,0,0.5)
                >>> bgcolor()
                "#800080"

          >>> help(penup)
          Help on function penup in module turtle:

          penup()
              Pull the pen up -- no drawing when moving.

              Aliases: penup | pu | up

              No argument

              Example:
              >>> penup()

这些修改版文档字符串是在导入时与方法对应函数的定义一起自动生成的。


File: python.info,  Node: 文档字符串翻译为不同的语言,  Next: 如何配置 Screen 和 Turtle,  Prev: 如何使用帮助,  Up: 帮助与配置

5.24.1.30 文档字符串翻译为不同的语言
....................................

可使用工具创建一个字典，键为方法名，值为 Screen 和 Turtle 类公共方法的文
档字符串。

 -- 函数: turtle.write_docstringdict (filename="turtle_docstringdict")


     参数: ‘filename’ – 一个字符串，表示文件名

     创建文档字符串字典并将其写入 filename 指定的 Python 脚本文件。此函
     数必须显示地调用 (海龟绘图类并不使用此函数)。文档字符串字典将被写入
     到 Python 脚本文件 ‘`filename'.py’。该文件可作为模板用来将文档字符
     串翻译为不同语言。

如果你 (或你的学生) 想使用本国语言版本的 *note turtle: 117. 在线帮助，你
必须翻译文档字符串并保存结果文件，例如 ‘turtle_docstringdict_german.py’.

如果你在 ‘turtle.cfg’ 文件中加入了相应的条目，此字典将在导入模块时被读取
并替代原有的英文版文档字符串。

在撰写本文档时已经有了德语和意大利语版的文档字符串字典。(更多需求请联系
<glingl@aon.at>)


File: python.info,  Node: 如何配置 Screen 和 Turtle,  Prev: 文档字符串翻译为不同的语言,  Up: 帮助与配置

5.24.1.31 如何配置 Screen 和 Turtle
...................................

内置的默认配置是模仿旧 turtle 模块的外观和行为，以便尽可能地与其保持兼容
。

如果你想使用不同的配置，以便更好地反映此模块的特性或是更适合你的需求，例
如在课堂中使用，你可以准备一个配置文件 ‘turtle.cfg’，该文件将在导入模块
时被读取并根据其中的设定修改模块配置。

内置的配置对应以下的 turtle.cfg:

     width = 0.5
     height = 0.75
     leftright = None
     topbottom = None
     canvwidth = 400
     canvheight = 300
     mode = standard
     colormode = 1.0
     delay = 10
     undobuffersize = 1000
     shape = classic
     pencolor = black
     fillcolor = black
     resizemode = noresize
     visible = True
     language = english
     exampleturtle = turtle
     examplescreen = screen
     title = Python Turtle Graphics
     using_IDLE = False

选定条目的简短说明:

   - 开头的四行对应 ‘Screen.setup()’ 方法的参数。

   - 第 5 和 6 行对应 ‘Screen.screensize()’ 方法的参数。

   - `shape' 可以是任何内置形状，即: arrow, turtle 等。更多信息可用
     ‘help(shape)’ 查看。

   - 如果你想使用无填充色 (即令海龟变透明)，你必须写 ‘fillcolor = ""’ (但
     cfg 文件中所有非空字符串都不可加引号)。

   - 如果你想令海龟反映其状态，你必须使用 ‘resizemode = auto’。

   - 如果你设置语言例如 ‘language = italian’ 则文档字符串字典
     ‘turtle_docstringdict_italian.py’ 将在导入模块时被加载 (如果导入路
     径即 *note turtle: 117. 的目录中存在此文件。

   - `exampleturtle' 和 `examplescreen' 条目定义了相应对象在文档字符串中
     显示的名称。方法文档字符串转换为函数文档字符串时将从文档字符串中删
     去这些名称。

   - `using_IDLE': 如果你经常使用 IDLE 并启用其 -n 开关 ("无子进程") 则
     应将此项设为 ‘True’，这将阻止 *note exitonclick(): 311b. 进入主事件
     循环。

‘turtle.cfg’ 文件可以保存于 *note turtle: 117. 所在目录，当前工作目录也
可以有一个同名文件。后者会重载覆盖前者的设置。

‘Lib/turtledemo’ 目录中也有一个 ‘turtle.cfg’ 文件。你可以将其作为示例进
行研究，并在运行演示时查看其作用效果 (但最好不要在演示查看器中运行)。


File: python.info,  Node: turtledemo --- 演示脚本集,  Next: Python 2 6 之后的变化,  Prev: 帮助与配置,  Up: turtle --- 海龟绘图

5.24.1.32 ‘turtledemo’ — 演示脚本集
...................................

*note turtledemo: 118. 包汇集了一组演示脚本。这些脚本可以通过以下命令打
开所提供的演示查看器运行和查看:

     python -m turtledemo

此外，你也可以单独运行其中的演示脚本。例如，:

     python -m turtledemo.bytedesign

*note turtledemo: 118. 包目录中的内容:

   - 一个演示查看器 ‘__main__.py’，可用来查看脚本的源码并即时运行。

   - 多个脚本文件，演示 *note turtle: 117. 模块的不同特性。所有示例可通
     过 Examples 菜单打开。也可以单独运行每个脚本。

   - 一个 ‘turtle.cfg’ 文件，作为说明如何编写并使用模块配置文件的示例模
     板。

演示脚本清单如下:

名称                 描述                               相关特性
                                                        
------------------------------------------------------------------------------------
                                                        
bytedesign           复杂的传统海龟绘图模式             ‘tracer()’, delay,
                                                        ‘update()’
                                                        
                                                        
chaos                绘制 Verhulst 动态模型，演示通过   世界坐标系
                     计算机的运算可能会生成令人惊叹的   
                     结果
                     
                                                        
clock                绘制模拟时钟显示本机的当前时间     海龟作为表针, ontimer
                                                        
                                                        
colormixer           试验 r, g, b 颜色模式              ‘ondrag()’ 当鼠标拖动
                                                        
                                                        
forest               绘制 3 棵广度优先树                随机化
                                                        
                                                        
fractalcurves        绘制 Hilbert & Koch 曲线           递归
                                                        
                                                        
lindenmayer          文化数学 (印度装饰艺术)            L-系统
                                                        
                                                        
minimal_hanoi        汉诺塔                             矩形海龟作为汉诺盘
                                                        (shape, shapesize)
                                                        
                                                        
nim                  玩经典的“尼姆”游戏，开始时有三堆   海龟作为小棒，事件驱动 (鼠
                     小棒，与电脑对战。                 标, 键盘)
                                                        
                                                        
paint                超极简主义绘画程序                 ‘onclick()’ 当鼠标点击
                                                        
                                                        
peace                初级技巧                           海龟: 外观与动画
                                                        
                                                        
penrose              非周期性地使用风筝和飞镖形状铺满   ‘stamp()’ 印章
                     平面                               
                     
                                                        
planet_and_moon      模拟引力系统                       复合开关, ‘Vec2D’ 类
                                                        
                                                        
round_dance          两两相对并不断旋转舞蹈的海龟       复合形状, clone
                                                        shapesize, tilt,
                                                        get_shapepoly, update
                                                        
                                                        
sorting_animate      动态演示不同的排序方法             简单对齐, 随机化
                                                        
                                                        
tree                 一棵 (图形化的) 广度优先树 (使用   ‘clone()’ 克隆
                     生成器)                            
                     
                                                        
two_canvases         简单设计                           两块画布上的海龟
                                                        
                                                        
wikipedia            一个来自介绍海龟绘图的维基百科文   ‘clone()’, ‘undo()’
                     章的图案                           
                     
                                                        
yinyang              另一个初级示例                     ‘circle()’ 画圆
                                                        

祝你玩得开心！


File: python.info,  Node: Python 2 6 之后的变化,  Next: Python 3 0 之后的变化,  Prev: turtledemo --- 演示脚本集,  Up: turtle --- 海龟绘图

5.24.1.33 Python 2.6 之后的变化
...............................

   - ‘Turtle.tracer()’, ‘Turtle.window_width()’ 和
     ‘Turtle.window_height()’ 方法已被去除。具有这些名称和功能的方法现在
     只限于 ‘Screen’ 类的方法。但其对应的函数仍然可用。(实际上在 Python
     2.6 中这些方法就已经只是从对应的 ‘TurtleScreen’/‘Screen’ 类的方法复
     制而来。)

   - ‘Turtle.fill()’ 方法已被去除。‘begin_fill()’ 和 ‘end_fill()’ 的行为
     则有细微改变: 现在每个填充过程必须以一个 ‘end_fill()’ 调用来结束。

   - 新增了一个 ‘Turtle.filling()’ 方法。该方法返回一个布尔值: 如果填充
     过程正在进行为 ‘True’，否则为 ‘False’。此行为相当于 Python 2.6 中不
     带参数的 ‘fill()’ 调用。


File: python.info,  Node: Python 3 0 之后的变化,  Prev: Python 2 6 之后的变化,  Up: turtle --- 海龟绘图

5.24.1.34 Python 3.0 之后的变化
...............................

   - 新增了 ‘Turtle.shearfactor()’, ‘Turtle.shapetransform()’ 和
     ‘Turtle.get_shapepoly()’ 方法。这样就可以使用所有标准线性变换来调整
     海龟形状。‘Turtle.tiltangle()’ 的功能已被加强: 现在可被用来获取或设
     置倾角。‘Turtle.settiltangle()’ 已弃用。

   - 新增了 ‘Screen.onkeypress()’ 方法作为对 ‘Screen.onkey()’ 的补充，实
     际就是将行为绑定到 keyrelease 事件。后者相应增加了一个别名:
     ‘Screen.onkeyrelease()’。

   - 新增了 ‘Screen.mainloop()’ 方法。这样当仅需使用 Screen 和 Turtle 对
     象时不需要再额外导入 ‘mainloop()’。

   - 新增了两个方法 ‘Screen.textinput()’ 和 ‘Screen.numinput()’。用来弹
     出对话框接受输入并分别返回字符串和数值。

   - 两个新的示例脚本 ‘tdemo_nim.py’ 和 ‘tdemo_round_dance.py’ 被加入到
     ‘Lib/turtledemo’ 目录中。


File: python.info,  Node: cmd --- 支持面向行的命令解释器,  Next: shlex --- Simple lexical analysis,  Prev: turtle --- 海龟绘图,  Up: 程序框架

5.24.2 ‘cmd’ — 支持面向行的命令解释器
-------------------------------------

`源代码:' Lib/cmd.py(1)

__________________________________________________________________

*note Cmd: 3144. 类提供简单框架用于编写面向行的命令解释器。 这些通常对测
试工具，管理工具和原型有用，这些工具随后将被包含在更复杂的接口中。

 -- 类: cmd.Cmd (completekey='tab', stdin=None, stdout=None)

     一个 *note Cmd: 3144. 实例或子类实例是面向行的解释器框架结构。 实例
     化 *note Cmd: 3144. 本身是没有充分理由的， 它作为自定义解释器类的超
     类是非常有用的为了继承 *note Cmd: 3144. 的方法并且封装动作方法。

     可选参数 `completekey' 是完成键的 *note readline: df. 名称；默认是
     ‘Tab’ 。如果 `completekey' 不是 *note None: 158. 并且 *note
     readline: df. 是可用的， 命令完成会自动完成。

     可选参数 `stdin' 和 `stdout' 指定了Cmd实例或子类实例将用于输入和输
     出的输入和输出文件对象。如果没有指定，他们将默认为 *note sys.stdin:
     316. 和 *note sys.stdout: 317. 。

     如果你想要使用一个给定的 `stdin' ，确保将实例的 *note use_rawinput:
     3145. 属性设置为 ‘False’ ，否则 `stdin' 将被忽略。

* Menu:

* Cmd 对象::
* Cmd 例子::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/cmd.py


File: python.info,  Node: Cmd 对象,  Next: Cmd 例子,  Up: cmd --- 支持面向行的命令解释器

5.24.2.1 Cmd 对象
.................

*note Cmd: 3144. 实例有下列方法：

 -- 方法: Cmd.cmdloop (intro=None)

     反复发出提示，接受输入，从收到的输入中解析出一个初始前缀，并分派给
     操作方法，将其余的行作为参数传递给它们。

     可选参数是在第一个提示之前发布的横幅或介绍字符串（这将覆盖 *note
     intro: 3149. 类属性）。

     如果 *note readline: df. 继承模块被加载，输入将自动继承类似 ‘bash’的
     历史列表编辑（例如， ‘Control-P’ 滚动回到最后一个命令， ‘Control-N’
     转到下一个命令，以 ‘Control-F’ 非破坏性的方式向右 ‘Control-B’ 移动
     光标，破坏性地等）。

     输入的文件结束符被作为字符串传回 ‘'EOF'’ 。

     解释器实例将会识别命令名称 ‘foo’ 当且仅当它有方法 ‘do_foo()’ 。有一
     个特殊情况，分派始于字符 ‘'?'’ 的行到方法 ‘do_help()’ 。另一种特殊
     情况，分派始于字符 ‘'!'’ 的行到方法 ‘do_shell()’ （如果定义了这个方
     法）

     这个方法将返回当 *note postcmd(): 314a. 方法返回一个真值 。参数
     `stop' 到 *note postcmd(): 314a. 是命令对应的返回值 ‘do_*()’ 的方法
     。

     如果激活了完成，全部命令将会自动完成，并且通过调用 ‘complete_foo()’
     参数 `text' , `line', `begidx' ,和 `endidx' 完成全部命令参数。
     `text' 是我们试图匹配的字符串前缀，所有返回的匹配项必须以它为开头。
     `line' 是删除了前导空格的当前的输入行， `begidx' 和 `endidx' 是前缀
     文本的开始和结束索引。，可以用于根据参数位置提供不同的完成。

     所有 *note Cmd: 3144. 的子类继承一个预定义 ‘do_help()’ 。 这个方法
     使用参数 ‘'bar'’ 调用， 调用对应的方法 ‘help_bar()’ ，如果不存在，
     打印 ‘do_bar()’ 的文档字符串，如果可用。没有参数的情况下，
     ‘do_help()’ 方法会列出所有可用的帮助主题 （即所有具有相应的
     ‘help_*()’ 方法或命令的 文档字符串），也会列举所有未被记录的命令。

 -- 方法: Cmd.onecmd (str)

     解释该参数，就好像它是为响应提示而键入的一样。 这可能会被覆盖，但通
     常不应该被覆盖; 请参阅： *note precmd(): 314c. 和 *note postcmd():
     314a. 方法，用于执行有用的挂钩。 返回值是一个标志，指示解释器对命令
     的解释是否应该停止。 如果命令 `str' 有一个 ‘do_*()’ 方法，则返回该
     方法的返回值，否则返回 *note default(): 314d. 方法的返回值。

 -- 方法: Cmd.emptyline ()

     在响应提示输入空行时调用的方法。如果此方法未被覆盖，则重复输入的最
     后一个非空命令。

 -- 方法: Cmd.default (line)

     当命令前缀不能被识别的时候在输入行调用的方法。如果此方法未被覆盖，
     它将输出一个错误信息并返回。

 -- 方法: Cmd.completedefault (text, line, begidx, endidx)

     当没有特定于命令的 ‘complete_*()’ 方法可用时，调用此方法完成输入行
     。默认情况下，它返回一个空列表。

 -- 方法: Cmd.precmd (line)

     钩方法在命令行 `line' 被解释之前执行，但是在输入提示被生成和发出后
     。这个方法是一个在 *note Cmd: 3144. 中的存根；它的存在是为了被子类
     覆盖。返回值被用作 *note onecmd(): 314b. 方法执行的命令； *note
     precmd(): 314c. 的实现或许会重写命令或者简单的返回 `line' 不变。

 -- 方法: Cmd.postcmd (stop, line)

     钩方法只在命令调度完成后执行。这个方法是一个在 *note Cmd: 3144. 中
     的存根；它的存在是为了子类被覆盖。 `line' 是被执行的命令行， `stop'
     是一个表示在调用 *note postcmd(): 314a. 之后是否终止执行的标志；这
     将作为 *note onecmd(): 314b. 方法的返回值。这个方法的返回值被用作与
     `stop' 相关联的内部标志的新值；返回 false 将导致解释继续。

 -- 方法: Cmd.preloop ()

     钩方法当 *note cmdloop(): 3148. 被调用时执行一次。方法是一个在
     *note Cmd: 3144. 中的存根；它的存在是为了被子类覆盖。

 -- 方法: Cmd.postloop ()

     钩方法在 *note cmdloop(): 3148. 即将返回时执行一次。这个方法是一个
     在 *note Cmd: 3144. 中的存根；它的存在是为了被子类覆盖。

Instances of *note Cmd: 3144. subclasses have some public instance
variables:

 -- 属性: Cmd.prompt

     发出提示以请求输入。

 -- 属性: Cmd.identchars

     接受命令前缀的字符串。

 -- 属性: Cmd.lastcmd

     看到最后一个非空命令前缀。

 -- 属性: Cmd.cmdqueue

     排队的输入行列表。当需要新的输入时，在 *note cmdloop(): 3148. 中检
     查 cmdqueue 列表；如果它不是空的，它的元素将被按顺序处理，就像在提
     示符处输入一样。

 -- 属性: Cmd.intro

     要作为简介或横幅发出的字符串。 可以通过给 *note cmdloop(): 3148. 方
     法一个参数来覆盖它。

 -- 属性: Cmd.doc_header

     如果帮助输出具有记录命令的段落，则发出头文件。

 -- 属性: Cmd.misc_header

     如果帮助输出其他帮助主题的部分（即与 ‘do_*()’ 方法没有关联的
     ‘help_*()’ 方法），则发出头文件。

 -- 属性: Cmd.undoc_header

     如果帮助输出未被记录命令的部分（即与 ‘help_*()’ 方法没有关联的
     ‘do_*()’ 方法），则发出头文件。

 -- 属性: Cmd.ruler

     用于在帮助信息标题的下方绘制分隔符的字符，如果为空，则不绘制标尺线
     。这个字符默认是 ‘'='’ 。

 -- 属性: Cmd.use_rawinput

     这是一个标志，默认为 true 。如果为 true ，, *note cmdloop(): 3148.
     使用 *note input(): c73. 先是提示并且阅读下一个命令；如果为 false ，
     ‘sys.stdout.write()’ 和 ‘sys.stdin.readline()’ 被使用。（这意味着解
     释器将会自动支持类似于 ‘Emacs’的行编辑和命令历史记录按键操作，通过
     导入 *note readline: df. 在支持它的系统上。）


File: python.info,  Node: Cmd 例子,  Prev: Cmd 对象,  Up: cmd --- 支持面向行的命令解释器

5.24.2.2 Cmd 例子
.................

The *note cmd: 1a. module is mainly useful for building custom shells
that let a user work with a program interactively.

这部分提供了一个简单的例子来介绍如何使用一部分在 *note turtle: 117. 模块
中的命令构建一个 shell 。

基础的 turtle 命令比如 *note forward(): 30b0. 被添加进一个 *note Cmd:
3144. 子类，方法名为 ‘do_forward()’ 。参数被转换成数字并且分发至 turtle
模块中。 docstring 是 shell 提供的帮助实用程序。

例子也包含使用 *note precmd(): 314c. 方法实现基础的记录和回放的功能，这
个方法负责将输入转换为小写并且将命令写入文件。 ‘do_playback()’ 方法读取
文件并添加记录命令至 ‘cmdqueue’ 用于即时回放:

     import cmd, sys
     from turtle import *

     class TurtleShell(cmd.Cmd):
         intro = 'Welcome to the turtle shell.   Type help or ? to list commands.\n'
         prompt = '(turtle) '
         file = None

         # ----- basic turtle commands -----
         def do_forward(self, arg):
             'Move the turtle forward by the specified distance:  FORWARD 10'
             forward(*parse(arg))
         def do_right(self, arg):
             'Turn turtle right by given number of degrees:  RIGHT 20'
             right(*parse(arg))
         def do_left(self, arg):
             'Turn turtle left by given number of degrees:  LEFT 90'
             left(*parse(arg))
         def do_goto(self, arg):
             'Move turtle to an absolute position with changing orientation.  GOTO 100 200'
             goto(*parse(arg))
         def do_home(self, arg):
             'Return turtle to the home position:  HOME'
             home()
         def do_circle(self, arg):
             'Draw circle with given radius an options extent and steps:  CIRCLE 50'
             circle(*parse(arg))
         def do_position(self, arg):
             'Print the current turtle position:  POSITION'
             print('Current position is %d %d\n' % position())
         def do_heading(self, arg):
             'Print the current turtle heading in degrees:  HEADING'
             print('Current heading is %d\n' % (heading(),))
         def do_color(self, arg):
             'Set the color:  COLOR BLUE'
             color(arg.lower())
         def do_undo(self, arg):
             'Undo (repeatedly) the last turtle action(s):  UNDO'
         def do_reset(self, arg):
             'Clear the screen and return turtle to center:  RESET'
             reset()
         def do_bye(self, arg):
             'Stop recording, close the turtle window, and exit:  BYE'
             print('Thank you for using Turtle')
             self.close()
             bye()
             return True

         # ----- record and playback -----
         def do_record(self, arg):
             'Save future commands to filename:  RECORD rose.cmd'
             self.file = open(arg, 'w')
         def do_playback(self, arg):
             'Playback commands from a file:  PLAYBACK rose.cmd'
             self.close()
             with open(arg) as f:
                 self.cmdqueue.extend(f.read().splitlines())
         def precmd(self, line):
             line = line.lower()
             if self.file and 'playback' not in line:
                 print(line, file=self.file)
             return line
         def close(self):
             if self.file:
                 self.file.close()
                 self.file = None

     def parse(arg):
         'Convert a series of zero or more numbers to an argument tuple'
         return tuple(map(int, arg.split()))

     if __name__ == '__main__':
         TurtleShell().cmdloop()

这是一个示例会话，其中 turtle shell 显示帮助功能，使用空行重复命令，以及
简单的记录和回放功能：

     Welcome to the turtle shell.   Type help or ? to list commands.

     (turtle) ?

     Documented commands (type help <topic>):
     ========================================
     bye     color    goto     home  playback  record  right
     circle  forward  heading  left  position  reset   undo

     (turtle) help forward
     Move the turtle forward by the specified distance:  FORWARD 10
     (turtle) record spiral.cmd
     (turtle) position
     Current position is 0 0

     (turtle) heading
     Current heading is 0

     (turtle) reset
     (turtle) circle 20
     (turtle) right 30
     (turtle) circle 40
     (turtle) right 30
     (turtle) circle 60
     (turtle) right 30
     (turtle) circle 80
     (turtle) right 30
     (turtle) circle 100
     (turtle) right 30
     (turtle) circle 120
     (turtle) right 30
     (turtle) circle 120
     (turtle) heading
     Current heading is 180

     (turtle) forward 100
     (turtle)
     (turtle) right 90
     (turtle) forward 100
     (turtle)
     (turtle) right 90
     (turtle) forward 400
     (turtle) right 90
     (turtle) forward 500
     (turtle) right 90
     (turtle) forward 400
     (turtle) right 90
     (turtle) forward 300
     (turtle) playback spiral.cmd
     Current position is 0 0

     Current heading is 0

     Current heading is 180

     (turtle) bye
     Thank you for using Turtle


File: python.info,  Node: shlex --- Simple lexical analysis,  Prev: cmd --- 支持面向行的命令解释器,  Up: 程序框架

5.24.3 ‘shlex’ — Simple lexical analysis
----------------------------------------

`Source code:' Lib/shlex.py(1)

__________________________________________________________________

The *note shlex: 583. class makes it easy to write lexical analyzers for
simple syntaxes resembling that of the Unix shell.  This will often be
useful for writing minilanguages, (for example, in run control files for
Python applications) or for parsing quoted strings.

The *note shlex: e9. module defines the following functions:

 -- 函数: shlex.split (s, comments=False, posix=True)

     Split the string `s' using shell-like syntax.  If `comments' is
     *note False: 390. (the default), the parsing of comments in the
     given string will be disabled (setting the *note commenters: 315e.
     attribute of the *note shlex: 583. instance to the empty string).
     This function operates in POSIX mode by default, but uses non-POSIX
     mode if the `posix' argument is false.

          注解: Since the *note split(): 219. function instantiates a
          *note shlex: 583. instance, passing ‘None’ for `s' will read
          the string to split from standard input.

 -- 函数: shlex.join (split_command)

     Concatenate the tokens of the list `split_command' and return a
     string.  This function is the inverse of *note split(): 219.

          >>> from shlex import join
          >>> print(join(['echo', '-n', 'Multiple words']))
          echo -n 'Multiple words'

     The returned value is shell-escaped to protect against injection
     vulnerabilities (see *note quote(): a7b.).

     3.8 新版功能.

 -- 函数: shlex.quote (s)

     Return a shell-escaped version of the string `s'.  The returned
     value is a string that can safely be used as one token in a shell
     command line, for cases where you cannot use a list.

     This idiom would be unsafe:

          >>> filename = 'somefile; rm -rf ~'
          >>> command = 'ls -l {}'.format(filename)
          >>> print(command)  # executed by a shell: boom!
          ls -l somefile; rm -rf ~

     *note quote(): a7b. lets you plug the security hole:

          >>> from shlex import quote
          >>> command = 'ls -l {}'.format(quote(filename))
          >>> print(command)
          ls -l 'somefile; rm -rf ~'
          >>> remote_command = 'ssh home {}'.format(quote(command))
          >>> print(remote_command)
          ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"''

     The quoting is compatible with UNIX shells and with *note split():
     219.:

          >>> from shlex import split
          >>> remote_command = split(remote_command)
          >>> remote_command
          ['ssh', 'home', "ls -l 'somefile; rm -rf ~'"]
          >>> command = split(remote_command[-1])
          >>> command
          ['ls', '-l', 'somefile; rm -rf ~']

     3.3 新版功能.

The *note shlex: e9. module defines the following class:

 -- 类: shlex.shlex (instream=None, infile=None, posix=False,
          punctuation_chars=False)

     A *note shlex: 583. instance or subclass instance is a lexical
     analyzer object.  The initialization argument, if present,
     specifies where to read characters from.  It must be a
     file-/stream-like object with *note read(): 2015. and *note
     readline(): 1c0e. methods, or a string.  If no argument is given,
     input will be taken from ‘sys.stdin’.  The second optional argument
     is a filename string, which sets the initial value of the *note
     infile: 315f. attribute.  If the `instream' argument is omitted or
     equal to ‘sys.stdin’, this second argument defaults to "stdin".
     The `posix' argument defines the operational mode: when `posix' is
     not true (default), the *note shlex: 583. instance will operate in
     compatibility mode.  When operating in POSIX mode, *note shlex:
     583. will try to be as close as possible to the POSIX shell parsing
     rules.  The `punctuation_chars' argument provides a way to make the
     behaviour even closer to how real shells parse.  This can take a
     number of values: the default value, ‘False’, preserves the
     behaviour seen under Python 3.5 and earlier.  If set to ‘True’,
     then parsing of the characters ‘();<>|&’ is changed: any run of
     these characters (considered punctuation characters) is returned as
     a single token.  If set to a non-empty string of characters, those
     characters will be used as the punctuation characters.  Any
     characters in the *note wordchars: 3160. attribute that appear in
     `punctuation_chars' will be removed from *note wordchars: 3160.
     See *note Improved Compatibility with Shells: 584. for more
     information.  `punctuation_chars' can be set only upon *note shlex:
     583. instance creation and can’t be modified later.

     在 3.6 版更改: The `punctuation_chars' parameter was added.

参见
....

Module *note configparser: 23.

     Parser for configuration files similar to the Windows ‘.ini’ files.

* Menu:

* shlex Objects::
* Parsing Rules::
* Improved Compatibility with Shells::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/shlex.py


File: python.info,  Node: shlex Objects,  Next: Parsing Rules,  Up: shlex --- Simple lexical analysis

5.24.3.1 shlex Objects
......................

A *note shlex: 583. instance has the following methods:

 -- 方法: shlex.get_token ()

     Return a token.  If tokens have been stacked using *note
     push_token(): 3164, pop a token off the stack.  Otherwise, read one
     from the input stream.  If reading encounters an immediate
     end-of-file, *note eof: 3165. is returned (the empty string (‘''’)
     in non-POSIX mode, and ‘None’ in POSIX mode).

 -- 方法: shlex.push_token (str)

     Push the argument onto the token stack.

 -- 方法: shlex.read_token ()

     Read a raw token.  Ignore the pushback stack, and do not interpret
     source requests.  (This is not ordinarily a useful entry point, and
     is documented here only for the sake of completeness.)

 -- 方法: shlex.sourcehook (filename)

     When *note shlex: 583. detects a source request (see *note source:
     3168. below) this method is given the following token as argument,
     and expected to return a tuple consisting of a filename and an open
     file-like object.

     Normally, this method first strips any quotes off the argument.  If
     the result is an absolute pathname, or there was no previous source
     request in effect, or the previous source was a stream (such as
     ‘sys.stdin’), the result is left alone.  Otherwise, if the result
     is a relative pathname, the directory part of the name of the file
     immediately before it on the source inclusion stack is prepended
     (this behavior is like the way the C preprocessor handles ‘#include
     "file.h"’).

     The result of the manipulations is treated as a filename, and
     returned as the first component of the tuple, with *note open():
     4f8. called on it to yield the second component.  (Note: this is
     the reverse of the order of arguments in instance initialization!)

     This hook is exposed so that you can use it to implement directory
     search paths, addition of file extensions, and other namespace
     hacks.  There is no corresponding ’close’ hook, but a shlex
     instance will call the *note close(): 101e. method of the sourced
     input stream when it returns EOF.

     For more explicit control of source stacking, use the *note
     push_source(): 3169. and *note pop_source(): 316a. methods.

 -- 方法: shlex.push_source (newstream, newfile=None)

     Push an input source stream onto the input stack.  If the filename
     argument is specified it will later be available for use in error
     messages.  This is the same method used internally by the *note
     sourcehook(): 3167. method.

 -- 方法: shlex.pop_source ()

     Pop the last-pushed input source from the input stack.  This is the
     same method used internally when the lexer reaches EOF on a stacked
     input stream.

 -- 方法: shlex.error_leader (infile=None, lineno=None)

     This method generates an error message leader in the format of a
     Unix C compiler error label; the format is ‘'"%s", line %d: '’,
     where the ‘%s’ is replaced with the name of the current source file
     and the ‘%d’ with the current input line number (the optional
     arguments can be used to override these).

     This convenience is provided to encourage *note shlex: e9. users to
     generate error messages in the standard, parseable format
     understood by Emacs and other Unix tools.

Instances of *note shlex: 583. subclasses have some public instance
variables which either control lexical analysis or can be used for
debugging:

 -- 属性: shlex.commenters

     The string of characters that are recognized as comment beginners.
     All characters from the comment beginner to end of line are
     ignored.  Includes just ‘'#'’ by default.

 -- 属性: shlex.wordchars

     The string of characters that will accumulate into multi-character
     tokens.  By default, includes all ASCII alphanumerics and
     underscore.  In POSIX mode, the accented characters in the Latin-1
     set are also included.  If *note punctuation_chars: f8c. is not
     empty, the characters ‘~-./*?=’, which can appear in filename
     specifications and command line parameters, will also be included
     in this attribute, and any characters which appear in
     ‘punctuation_chars’ will be removed from ‘wordchars’ if they are
     present there.  If *note whitespace_split: 316c. is set to ‘True’,
     this will have no effect.

 -- 属性: shlex.whitespace

     Characters that will be considered whitespace and skipped.
     Whitespace bounds tokens.  By default, includes space, tab,
     linefeed and carriage-return.

 -- 属性: shlex.escape

     Characters that will be considered as escape.  This will be only
     used in POSIX mode, and includes just ‘'\'’ by default.

 -- 属性: shlex.quotes

     Characters that will be considered string quotes.  The token
     accumulates until the same quote is encountered again (thus,
     different quote types protect each other as in the shell.)  By
     default, includes ASCII single and double quotes.

 -- 属性: shlex.escapedquotes

     Characters in *note quotes: 316f. that will interpret escape
     characters defined in *note escape: 316e.  This is only used in
     POSIX mode, and includes just ‘'"'’ by default.

 -- 属性: shlex.whitespace_split

     If ‘True’, tokens will only be split in whitespaces.  This is
     useful, for example, for parsing command lines with *note shlex:
     583, getting tokens in a similar way to shell arguments.  When used
     in combination with *note punctuation_chars: f8c, tokens will be
     split on whitespace in addition to those characters.

     在 3.8 版更改: The *note punctuation_chars: f8c. attribute was made
     compatible with the *note whitespace_split: 316c. attribute.

 -- 属性: shlex.infile

     The name of the current input file, as initially set at class
     instantiation time or stacked by later source requests.  It may be
     useful to examine this when constructing error messages.

 -- 属性: shlex.instream

     The input stream from which this *note shlex: 583. instance is
     reading characters.

 -- 属性: shlex.source

     This attribute is ‘None’ by default.  If you assign a string to it,
     that string will be recognized as a lexical-level inclusion request
     similar to the ‘source’ keyword in various shells.  That is, the
     immediately following token will be opened as a filename and input
     will be taken from that stream until EOF, at which point the *note
     close(): 101e. method of that stream will be called and the input
     source will again become the original input stream.  Source
     requests may be stacked any number of levels deep.

 -- 属性: shlex.debug

     If this attribute is numeric and ‘1’ or more, a *note shlex: 583.
     instance will print verbose progress output on its behavior.  If
     you need to use this, you can read the module source code to learn
     the details.

 -- 属性: shlex.lineno

     Source line number (count of newlines seen so far plus one).

 -- 属性: shlex.token

     The token buffer.  It may be useful to examine this when catching
     exceptions.

 -- 属性: shlex.eof

     Token used to determine end of file.  This will be set to the empty
     string (‘''’), in non-POSIX mode, and to ‘None’ in POSIX mode.

 -- 属性: shlex.punctuation_chars

     A read-only property.  Characters that will be considered
     punctuation.  Runs of punctuation characters will be returned as a
     single token.  However, note that no semantic validity checking
     will be performed: for example, ’>>>’ could be returned as a token,
     even though it may not be recognised as such by shells.

     3.6 新版功能.


File: python.info,  Node: Parsing Rules,  Next: Improved Compatibility with Shells,  Prev: shlex Objects,  Up: shlex --- Simple lexical analysis

5.24.3.2 Parsing Rules
......................

When operating in non-POSIX mode, *note shlex: 583. will try to obey to
the following rules.

   * Quote characters are not recognized within words (‘Do"Not"Separate’
     is parsed as the single word ‘Do"Not"Separate’);

   * Escape characters are not recognized;

   * Enclosing characters in quotes preserve the literal value of all
     characters within the quotes;

   * Closing quotes separate words (‘"Do"Separate’ is parsed as ‘"Do"’
     and ‘Separate’);

   * If *note whitespace_split: 316c. is ‘False’, any character not
     declared to be a word character, whitespace, or a quote will be
     returned as a single-character token.  If it is ‘True’, *note
     shlex: 583. will only split words in whitespaces;

   * EOF is signaled with an empty string (‘''’);

   * It’s not possible to parse empty strings, even if quoted.

When operating in POSIX mode, *note shlex: 583. will try to obey to the
following parsing rules.

   * Quotes are stripped out, and do not separate words
     (‘"Do"Not"Separate"’ is parsed as the single word ‘DoNotSeparate’);

   * Non-quoted escape characters (e.g.  ‘'\'’) preserve the literal
     value of the next character that follows;

   * Enclosing characters in quotes which are not part of *note
     escapedquotes: 3170. (e.g.  ‘"'"’) preserve the literal value of
     all characters within the quotes;

   * Enclosing characters in quotes which are part of *note
     escapedquotes: 3170. (e.g.  ‘'"'’) preserves the literal value of
     all characters within the quotes, with the exception of the
     characters mentioned in *note escape: 316e.  The escape characters
     retain its special meaning only when followed by the quote in use,
     or the escape character itself.  Otherwise the escape character
     will be considered a normal character.

   * EOF is signaled with a *note None: 158. value;

   * Quoted empty strings (‘''’) are allowed.


File: python.info,  Node: Improved Compatibility with Shells,  Prev: Parsing Rules,  Up: shlex --- Simple lexical analysis

5.24.3.3 Improved Compatibility with Shells
...........................................

3.6 新版功能.

The *note shlex: e9. class provides compatibility with the parsing
performed by common Unix shells like ‘bash’, ‘dash’, and ‘sh’.  To take
advantage of this compatibility, specify the ‘punctuation_chars’
argument in the constructor.  This defaults to ‘False’, which preserves
pre-3.6 behaviour.  However, if it is set to ‘True’, then parsing of the
characters ‘();<>|&’ is changed: any run of these characters is returned
as a single token.  While this is short of a full parser for shells
(which would be out of scope for the standard library, given the
multiplicity of shells out there), it does allow you to perform
processing of command lines more easily than you could otherwise.  To
illustrate, you can see the difference in the following snippet:

      >>> import shlex
      >>> text = "a && b; c && d || e; f >'abc'; (def \"ghi\")"
      >>> s = shlex.shlex(text, posix=True)
      >>> s.whitespace_split = True
      >>> list(s)
      ['a', '&&', 'b;', 'c', '&&', 'd', '||', 'e;', 'f', '>abc;', '(def', 'ghi)']
      >>> s = shlex.shlex(text, posix=True, punctuation_chars=True)
      >>> s.whitespace_split = True
      >>> list(s)
      ['a', '&&', 'b', ';', 'c', '&&', 'd', '||', 'e', ';', 'f', '>', 'abc', ';',
      '(', 'def', 'ghi', ')']

Of course, tokens will be returned which are not valid for shells, and
you’ll need to implement your own error checks on the returned tokens.

Instead of passing ‘True’ as the value for the punctuation_chars
parameter, you can pass a string with specific characters, which will be
used to determine which characters constitute punctuation.  For example:

     >>> import shlex
     >>> s = shlex.shlex("a && b || c", punctuation_chars="|")
     >>> list(s)
     ['a', '&', '&', 'b', '||', 'c']

     注解: When ‘punctuation_chars’ is specified, the *note wordchars:
     3160. attribute is augmented with the characters ‘~-./*?=’.  That
     is because these characters can appear in file names (including
     wildcards) and command-line arguments (e.g.  ‘--color=auto’).
     Hence:

          >>> import shlex
          >>> s = shlex.shlex('~/a && b-c --color=auto || d *.py?',
          ...                 punctuation_chars=True)
          >>> list(s)
          ['~/a', '&&', 'b-c', '--color=auto', '||', 'd', '*.py?']

     However, to match the shell as closely as possible, it is
     recommended to always use ‘posix’ and *note whitespace_split: 316c.
     when using *note punctuation_chars: f8c, which will negate *note
     wordchars: 3160. entirely.

For best effect, ‘punctuation_chars’ should be set in conjunction with
‘posix=True’.  (Note that ‘posix=False’ is the default for *note shlex:
583.)


File: python.info,  Node: Tk图形用户界面 GUI,  Next: 开发工具,  Prev: 程序框架,  Up: Python 标准库

5.25 Tk图形用户界面(GUI)
========================

Tcl/Tk集成到Python中已经有一些年头了。Python程序员可以通过 *note
tkinter: 10d. 包和它的扩展， *note tkinter.tix: 10f. 模块和 *note
tkinter.ttk: 110. 模块，来使用这套鲁棒的、平台无关的窗口工具集。

*note tkinter: 10d. 包使用面向对象的方式对Tcl/Tk进行了一层薄包装。使用
*note tkinter: 10d. ，你不需要写Tcl代码，但可能需要参考Tk文档，甚至Tcl文
档。 *note tkinter: 10d. 使用Python类，对Tk的窗体小部件（Widgets）进行了
一系列的封装。除此之外，内部模块 ‘_tkinter’ 针对Python和Tcl之间的交互，
提供了一套线程安全的机制。

*note tkinter: 10d. 最大的优点就一个字：快，再一个，是Python自带的。尽管
官方文档不太完整，但有其他资源可以参考，比如Tk手册，教程等。 *note
tkinter: 10d. 也以比较过时的外观为人所知，但在Tk 8.5中，这一点得到了极大
的改观。除此之外，如果有兴趣，还有其他的一些GUI库可供使用。更多信息，请
参考 *note 其他图形用户界面（GUI）包: 317b. 小节。

* Menu:

* tkinter: tkinter --- Tcl/Tk的Python接口. Tcl/Tk的Python接口
* tkinter.ttk: tkinter ttk --- Tk主题小部件. Tk主题小部件
* tkinter.tix: tkinter tix --- TK扩展包. TK扩展包
* tkinter.scrolledtext: tkinter scrolledtext --- 滚动文字控件. 滚动文字控件
* IDLE: IDLE<54>.
* 其他图形用户界面（GUI）包::


File: python.info,  Node: tkinter --- Tcl/Tk的Python接口,  Next: tkinter ttk --- Tk主题小部件,  Up: Tk图形用户界面 GUI

5.25.1 ‘tkinter’ — Tcl/Tk的Python接口
-------------------------------------

`源代码:' Lib/tkinter/__init__.py(1)

__________________________________________________________________

The *note tkinter: 10d. package ("Tk interface") is the standard Python
interface to the Tk GUI toolkit.  Both Tk and *note tkinter: 10d. are
available on most Unix platforms, as well as on Windows systems.  (Tk
itself is not part of Python; it is maintained at ActiveState.)

在命令行中运行 ‘python -m tkinter’，应该会弹出一个Tk界面的窗口，表明
*note tkinter: 10d. 包已经正确安装，而且告诉你 Tcl/Tk 的版本号，通过这个
版本号，你就可以参考对应的 Tcl/Tk 文档了。

参见
....

Tkinter文档：

Python Tkinter 资源(2)

     The Python Tkinter Topic Guide 提供了在 Python 中使用 Tk 的很多信息
     ， 同时包含了Tk其他信息的链接。

TKDocs(3)

     大量的教程，部分可视化组件的介绍说明。

Tkinter 8.5 参考：一个Python图形用户界面(4)

     在线参考资料。

Tkinter docs from effbot(5)

     effbot.org 提供的 tkinter 在线参考资料。

使用 Python 编程(6)

     由 Mark Lutz 所著的书籍，对 Tkinter 进行了完美的介绍。

为繁忙的 Python 开发者所准备的现代 Tkinter(7)

     由 Mark Rozerman 所著的关于如何使用 Python 和 Tkinter 来搭建有吸引
     力的和现代化的图形用户界面的书籍

Python 和 Tkinter 编程(8)

     作者： John Grayson (ISBN 1-884777-81-3).

Tcl/Tk 文档:

Tk 命令(9)

     多数命令以 *note tkinter: 10d. 或者 *note tkinter.ttk: 110. 类的形
     式存在。改变 ’8.6’ 以匹配所安装的 Tcl/Tk 版本。

Tcl/Tk 最新手册页面(10)

     www.tcl.tk 上面最新的 Tcl/Tk 手册。

ActiveState Tcl 主页(11)

     Tk/Tcl 的多数开发工作发生在 ActiveState 。

Tcl 及 Tk 工具集(12)

     由 Tcl 发明者 John Ousterhout 所著的书籍。

‘ Tcl 和 Tk 编程实战 <‘http://www.beedub.com/book/’>‘_

     Brent Welch 所著的百科全局式书籍。

* Menu:

* Tkinter 模块::
* Tkinter Life Preserver::
* A (Very) Quick Look at Tcl/Tk: A Very Quick Look at Tcl/Tk.
* Mapping Basic Tk into Tkinter::
* How Tk and Tkinter are Related::
* Handy Reference::
* File Handlers::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/tkinter/__init__.py

   (2) https://wiki.python.org/moin/TkInter

   (3) http://www.tkdocs.com/

   (4) https://www.tkdocs.com/shipman/

   (5) http://effbot.org/tkinterbook/

   (6) http://learning-python.com/about-pp4e.html

   (7) 
https://www.amazon.com/Modern-Tkinter-Python-Developers-ebook/dp/B0071QDNLO/

   (8) https://www.manning.com/books/python-and-tkinter-programming

   (9) https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm

   (10) https://www.tcl.tk/doc/

   (11) https://tcl.tk

   (12) https://www.amazon.com/exec/obidos/ASIN/020163337X


File: python.info,  Node: Tkinter 模块,  Next: Tkinter Life Preserver,  Up: tkinter --- Tcl/Tk的Python接口

5.25.1.1 Tkinter 模块
.....................

在大多数时候你只需要 *note tkinter: 10d. 就足够了，但也有一些额外的模块
可供使用。Tk 接口位于一个名字 ‘_tkinter’ 的二进制模块当中。此模块包含了
低层级的 Tk 接口，它不应该被应用程序员所直接使用。它通常是一个共享库（或
DLL），但在某些情况下也可能被静态链接到 Python 解释器。

除了Tk接口， *note tkinter: 10d. 也包含了若干 Python 模块，
‘tkinter.constants’ 是其中最重要的。导入 *note tkinter: 10d. 会自动导入
‘tkinter.constants’ ，所以，要使用 Tkinter 通常你只需要一条简单的 import
语句:

     import tkinter

或者更常用的:

     from tkinter import *

 -- 类: tkinter.Tk (screenName=None, baseName=None, className='Tk',
          useTk=1)

     *note Tk: 317f. 类被初始化时无参数。此时会创建一个 Tk 顶级控件，通
     常是应用程序的主窗口。每个实例都有自己关联的 Tcl 解释器。

 -- 函数: tkinter.Tcl (screenName=None, baseName=None, className='Tk',
          useTk=0)

     *note Tcl(): 3180. 函数是一个工厂函数，它创建的对象与 *note Tk:
     317f. 类创建的对象非常相似，只是它不初始化 Tk 子系统。 在不想创建或
     无法创建（如没有 X Server 的 Unix/Linux 系统）额外的顶层窗口的环境
     中驱动 Tcl 解释器时，这一点非常有用。 由 *note Tcl(): 3180. 对象创
     建的对象可以通过调用其 ‘loadtk()’ 方法来创建顶层窗口（并初始化 Tk 子
     系统）。

提供Tk支持的其他模块包括：

*note tkinter.scrolledtext: 10e.

     Text widget with a vertical scroll bar built in.

‘tkinter.colorchooser’

     让用户选择颜色的对话框。

‘tkinter.commondialog’

     在此处列出的其他模块中定义的对话框的基类。

‘tkinter.filedialog’

     Common dialogs to allow the user to specify a file to open or save.

‘tkinter.font’

     Utilities to help work with fonts.

‘tkinter.messagebox’

     Access to standard Tk dialog boxes.

‘tkinter.simpledialog’

     Basic dialogs and convenience functions.

‘tkinter.dnd’

     Drag-and-drop support for *note tkinter: 10d.  This is experimental
     and should become deprecated when it is replaced with the Tk DND.

*note turtle: 117.

     Turtle graphics in a Tk window.


File: python.info,  Node: Tkinter Life Preserver,  Next: A Very Quick Look at Tcl/Tk,  Prev: Tkinter 模块,  Up: tkinter --- Tcl/Tk的Python接口

5.25.1.2 Tkinter Life Preserver
...............................

This section is not designed to be an exhaustive tutorial on either Tk
or Tkinter.  Rather, it is intended as a stop gap, providing some
introductory orientation on the system.

Credits:

   * Tk was written by John Ousterhout while at Berkeley.

   * Tkinter was written by Steen Lumholt and Guido van Rossum.

   * This Life Preserver was written by Matt Conway at the University of
     Virginia.

   * The HTML rendering, and some liberal editing, was produced from a
     FrameMaker version by Ken Manheimer.

   * Fredrik Lundh elaborated and revised the class interface
     descriptions, to get them current with Tk 4.2.

   * Mike Clarkson converted the documentation to LaTeX, and compiled
     the User Interface chapter of the reference manual.

* Menu:

* How To Use This Section::
* A Simple Hello World Program::


File: python.info,  Node: How To Use This Section,  Next: A Simple Hello World Program,  Up: Tkinter Life Preserver

5.25.1.3 How To Use This Section
................................

This section is designed in two parts: the first half (roughly) covers
background material, while the second half can be taken to the keyboard
as a handy reference.

When trying to answer questions of the form "how do I do blah", it is
often best to find out how to do "blah" in straight Tk, and then convert
this back into the corresponding *note tkinter: 10d. call.  Python
programmers can often guess at the correct Python command by looking at
the Tk documentation.  This means that in order to use Tkinter, you will
have to know a little bit about Tk.  This document can’t fulfill that
role, so the best we can do is point you to the best documentation that
exists.  Here are some hints:

   * The authors strongly suggest getting a copy of the Tk man pages.
     Specifically, the man pages in the ‘manN’ directory are most
     useful.  The ‘man3’ man pages describe the C interface to the Tk
     library and thus are not especially helpful for script writers.

   * Addison-Wesley publishes a book called Tcl and the Tk Toolkit by
     John Ousterhout (ISBN 0-201-63337-X) which is a good introduction
     to Tcl and Tk for the novice.  The book is not exhaustive, and for
     many details it defers to the man pages.

   * ‘tkinter/__init__.py’ is a last resort for most, but can be a good
     place to go when nothing else makes sense.


File: python.info,  Node: A Simple Hello World Program,  Prev: How To Use This Section,  Up: Tkinter Life Preserver

5.25.1.4 A Simple Hello World Program
.....................................

     import tkinter as tk

     class Application(tk.Frame):
         def __init__(self, master=None):
             super().__init__(master)
             self.master = master
             self.pack()
             self.create_widgets()

         def create_widgets(self):
             self.hi_there = tk.Button(self)
             self.hi_there["text"] = "Hello World\n(click me)"
             self.hi_there["command"] = self.say_hi
             self.hi_there.pack(side="top")

             self.quit = tk.Button(self, text="QUIT", fg="red",
                                   command=self.master.destroy)
             self.quit.pack(side="bottom")

         def say_hi(self):
             print("hi there, everyone!")

     root = tk.Tk()
     app = Application(master=root)
     app.mainloop()


File: python.info,  Node: A Very Quick Look at Tcl/Tk,  Next: Mapping Basic Tk into Tkinter,  Prev: Tkinter Life Preserver,  Up: tkinter --- Tcl/Tk的Python接口

5.25.1.5 A (Very) Quick Look at Tcl/Tk
......................................

The class hierarchy looks complicated, but in actual practice,
application programmers almost always refer to the classes at the very
bottom of the hierarchy.

注释:

   * These classes are provided for the purposes of organizing certain
     functions under one namespace.  They aren’t meant to be
     instantiated independently.

   * The *note Tk: 317f. class is meant to be instantiated only once in
     an application.  Application programmers need not instantiate one
     explicitly, the system creates one whenever any of the other
     classes are instantiated.

   * The ‘Widget’ class is not meant to be instantiated, it is meant
     only for subclassing to make "real" widgets (in C++, this is called
     an ’abstract class’).

To make use of this reference material, there will be times when you
will need to know how to read short passages of Tk and how to identify
the various parts of a Tk command.  (See section *note Mapping Basic Tk
into Tkinter: 3185. for the *note tkinter: 10d. equivalents of what’s
below.)

Tk scripts are Tcl programs.  Like all Tcl programs, Tk scripts are just
lists of tokens separated by spaces.  A Tk widget is just its `class',
the `options' that help configure it, and the `actions' that make it do
useful things.

To make a widget in Tk, the command is always of the form:

     classCommand newPathname options

`classCommand'

     denotes which kind of widget to make (a button, a label, a menu...)

`newPathname'

     is the new name for this widget.  All names in Tk must be unique.
     To help enforce this, widgets in Tk are named with `pathnames',
     just like files in a file system.  The top level widget, the
     `root', is called ‘.’ (period) and children are delimited by more
     periods.  For example, ‘.myApp.controlPanel.okButton’ might be the
     name of a widget.

`options'

     configure the widget’s appearance and in some cases, its behavior.
     The options come in the form of a list of flags and values.  Flags
     are preceded by a ’-’, like Unix shell command flags, and values
     are put in quotes if they are more than one word.

例如

     button   .fred   -fg red -text "hi there"
        ^       ^     \______________________/
        |       |                |
      class    new            options
     command  widget  (-opt val -opt val ...)

Once created, the pathname to the widget becomes a new command.  This
new `widget command' is the programmer’s handle for getting the new
widget to perform some `action'.  In C, you’d express this as
someAction(fred, someOptions), in C++, you would express this as
fred.someAction(someOptions), and in Tk, you say:

     .fred someAction someOptions

Note that the object name, ‘.fred’, starts with a dot.

As you’d expect, the legal values for `someAction' will depend on the
widget’s class: ‘.fred disable’ works if fred is a button (fred gets
greyed out), but does not work if fred is a label (disabling of labels
is not supported in Tk).

The legal values of `someOptions' is action dependent.  Some actions,
like ‘disable’, require no arguments, others, like a text-entry box’s
‘delete’ command, would need arguments to specify what range of text to
delete.


File: python.info,  Node: Mapping Basic Tk into Tkinter,  Next: How Tk and Tkinter are Related,  Prev: A Very Quick Look at Tcl/Tk,  Up: tkinter --- Tcl/Tk的Python接口

5.25.1.6 Mapping Basic Tk into Tkinter
......................................

Class commands in Tk correspond to class constructors in Tkinter.

     button .fred                =====>  fred = Button()

The master of an object is implicit in the new name given to it at
creation time.  In Tkinter, masters are specified explicitly.

     button .panel.fred          =====>  fred = Button(panel)

The configuration options in Tk are given in lists of hyphened tags
followed by values.  In Tkinter, options are specified as
keyword-arguments in the instance constructor, and keyword-args for
configure calls or as instance indices, in dictionary style, for
established instances.  See section *note Setting Options: 3187. on
setting options.

     button .fred -fg red        =====>  fred = Button(panel, fg="red")
     .fred configure -fg red     =====>  fred["fg"] = red
                                 OR ==>  fred.config(fg="red")

In Tk, to perform an action on a widget, use the widget name as a
command, and follow it with an action name, possibly with arguments
(options).  In Tkinter, you call methods on the class instance to invoke
actions on the widget.  The actions (methods) that a given widget can
perform are listed in ‘tkinter/__init__.py’.

     .fred invoke                =====>  fred.invoke()

To give a widget to the packer (geometry manager), you call pack with
optional arguments.  In Tkinter, the Pack class holds all this
functionality, and the various forms of the pack command are implemented
as methods.  All widgets in *note tkinter: 10d. are subclassed from the
Packer, and so inherit all the packing methods.  See the *note
tkinter.tix: 10f. module documentation for additional information on the
Form geometry manager.

     pack .fred -side left       =====>  fred.pack(side="left")


File: python.info,  Node: How Tk and Tkinter are Related,  Next: Handy Reference,  Prev: Mapping Basic Tk into Tkinter,  Up: tkinter --- Tcl/Tk的Python接口

5.25.1.7 How Tk and Tkinter are Related
.......................................

From the top down:

Your App Here (Python)

     A Python application makes a *note tkinter: 10d. call.

tkinter (Python Package)

     This call (say, for example, creating a button widget), is
     implemented in the *note tkinter: 10d. package, which is written in
     Python.  This Python function will parse the commands and the
     arguments and convert them into a form that makes them look as if
     they had come from a Tk script instead of a Python script.

_tkinter (C)

     These commands and their arguments will be passed to a C function
     in the ‘_tkinter’ - note the underscore - extension module.

Tk Widgets (C and Tcl)

     This C function is able to make calls into other C modules,
     including the C functions that make up the Tk library.  Tk is
     implemented in C and some Tcl.  The Tcl part of the Tk widgets is
     used to bind certain default behaviors to widgets, and is executed
     once at the point where the Python *note tkinter: 10d. package is
     imported.  (The user never sees this stage).

Tk (C)

     The Tk part of the Tk Widgets implement the final mapping to ...

Xlib (C)

     the Xlib library to draw graphics on the screen.


File: python.info,  Node: Handy Reference,  Next: File Handlers,  Prev: How Tk and Tkinter are Related,  Up: tkinter --- Tcl/Tk的Python接口

5.25.1.8 Handy Reference
........................

* Menu:

* Setting Options::
* The Packer::
* Packer Options::
* Coupling Widget Variables::
* The Window Manager::
* Tk Option Data Types::
* Bindings and Events::
* The index Parameter::
* Images::


File: python.info,  Node: Setting Options,  Next: The Packer,  Up: Handy Reference

5.25.1.9 Setting Options
........................

Options control things like the color and border width of a widget.
Options can be set in three ways:

At object creation time, using keyword arguments

          fred = Button(self, fg="red", bg="blue")

After object creation, treating the option name like a dictionary index

          fred["fg"] = "red"
          fred["bg"] = "blue"

Use the config() method to update multiple attrs subsequent to object creation

          fred.config(fg="red", bg="blue")

For a complete explanation of a given option and its behavior, see the
Tk man pages for the widget in question.

Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC
OPTIONS" for each widget.  The former is a list of options that are
common to many widgets, the latter are the options that are
idiosyncratic to that particular widget.  The Standard Options are
documented on the ‘options(3)’ man page.

No distinction between standard and widget-specific options is made in
this document.  Some options don’t apply to some kinds of widgets.
Whether a given widget responds to a particular option depends on the
class of the widget; buttons have a ‘command’ option, labels do not.

The options supported by a given widget are listed in that widget’s man
page, or can be queried at runtime by calling the ‘config()’ method
without arguments, or by calling the ‘keys()’ method on that widget.
The return value of these calls is a dictionary whose key is the name of
the option as a string (for example, ‘'relief'’) and whose values are
5-tuples.

Some options, like ‘bg’ are synonyms for common options with long names
(‘bg’ is shorthand for "background").  Passing the ‘config()’ method the
name of a shorthand option will return a 2-tuple, not 5-tuple.  The
2-tuple passed back will contain the name of the synonym and the "real"
option (such as ‘('bg', 'background')’).

索引        含义                                  示例
                                                  
---------------------------------------------------------------------
                                                  
0           选项名称                              ‘'relief'’
                                                  
                                                  
1           数据库查找的选项名称                  ‘'relief'’
                                                  
                                                  
2           数据库查找的选项类                    ‘'Relief'’
                                                  
                                                  
3           默认值                                ‘'raised'’
                                                  
                                                  
4           当前值                                ‘'groove'’
                                                  

示例:

     >>> print(fred.config())
     {'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}

Of course, the dictionary printed will include all the options available
and their values.  This is meant only as an example.


File: python.info,  Node: The Packer,  Next: Packer Options,  Prev: Setting Options,  Up: Handy Reference

5.25.1.10 The Packer
....................

The packer is one of Tk’s geometry-management mechanisms.  Geometry
managers are used to specify the relative positioning of widgets within
their container - their mutual `master'.  In contrast to the more
cumbersome `placer' (which is used less commonly, and we do not cover
here), the packer takes qualitative relationship specification -
`above', `to the left of', `filling', etc - and works everything out to
determine the exact placement coordinates for you.

The size of any `master' widget is determined by the size of the "slave
widgets" inside.  The packer is used to control where slave widgets
appear inside the master into which they are packed.  You can pack
widgets into frames, and frames into other frames, in order to achieve
the kind of layout you desire.  Additionally, the arrangement is
dynamically adjusted to accommodate incremental changes to the
configuration, once it is packed.

Note that widgets do not appear until they have had their geometry
specified with a geometry manager.  It’s a common early mistake to leave
out the geometry specification, and then be surprised when the widget is
created but nothing appears.  A widget will appear only after it has
had, for example, the packer’s ‘pack()’ method applied to it.

The pack() method can be called with keyword-option/value pairs that
control where the widget is to appear within its container, and how it
is to behave when the main application window is resized.  Here are some
examples:

     fred.pack()                     # defaults to side = "top"
     fred.pack(side="left")
     fred.pack(expand=1)


File: python.info,  Node: Packer Options,  Next: Coupling Widget Variables,  Prev: The Packer,  Up: Handy Reference

5.25.1.11 Packer Options
........................

For more extensive information on the packer and the options that it can
take, see the man pages and page 183 of John Ousterhout’s book.

anchor

     Anchor type.  Denotes where the packer is to place each slave in
     its parcel.

expand

     Boolean, ‘0’ or ‘1’.

fill

     Legal values: ‘'x'’, ‘'y'’, ‘'both'’, ‘'none'’.

ipadx 和 ipady

     A distance - designating internal padding on each side of the slave
     widget.

padx 和 pady

     A distance - designating external padding on each side of the slave
     widget.

side

     Legal values are: ‘'left'’, ‘'right'’, ‘'top'’, ‘'bottom'’.


File: python.info,  Node: Coupling Widget Variables,  Next: The Window Manager,  Prev: Packer Options,  Up: Handy Reference

5.25.1.12 Coupling Widget Variables
...................................

The current-value setting of some widgets (like text entry widgets) can
be connected directly to application variables by using special options.
These options are ‘variable’, ‘textvariable’, ‘onvalue’, ‘offvalue’, and
‘value’.  This connection works both ways: if the variable changes for
any reason, the widget it’s connected to will be updated to reflect the
new value.

Unfortunately, in the current implementation of *note tkinter: 10d. it
is not possible to hand over an arbitrary Python variable to a widget
through a ‘variable’ or ‘textvariable’ option.  The only kinds of
variables for which this works are variables that are subclassed from a
class called Variable, defined in *note tkinter: 10d.

There are many useful subclasses of Variable already defined:
‘StringVar’, ‘IntVar’, ‘DoubleVar’, and ‘BooleanVar’.  To read the
current value of such a variable, call the ‘get()’ method on it, and to
change its value you call the ‘set()’ method.  If you follow this
protocol, the widget will always track the value of the variable, with
no further intervention on your part.

例如

     import tkinter as tk

     class App(tk.Frame):
         def __init__(self, master):
             super().__init__(master)
             self.pack()

             self.entrythingy = tk.Entry()
             self.entrythingy.pack()

             # Create the application variable.
             self.contents = tk.StringVar()
             # Set it to some value.
             self.contents.set("this is a variable")
             # Tell the entry widget to watch this variable.
             self.entrythingy["textvariable"] = self.contents

             # Define a callback for when the user hits return.
             # It prints the current value of the variable.
             self.entrythingy.bind('<Key-Return>',
                                  self.print_contents)

         def print_contents(self, event):
             print("Hi. The current entry content is:",
                   self.contents.get())

     root = tk.Tk()
     myapp = App(root)
     myapp.mainloop()


File: python.info,  Node: The Window Manager,  Next: Tk Option Data Types,  Prev: Coupling Widget Variables,  Up: Handy Reference

5.25.1.13 The Window Manager
............................

In Tk, there is a utility command, ‘wm’, for interacting with the window
manager.  Options to the ‘wm’ command allow you to control things like
titles, placement, icon bitmaps, and the like.  In *note tkinter: 10d,
these commands have been implemented as methods on the ‘Wm’ class.
Toplevel widgets are subclassed from the ‘Wm’ class, and so can call the
‘Wm’ methods directly.

To get at the toplevel window that contains a given widget, you can
often just refer to the widget’s master.  Of course if the widget has
been packed inside of a frame, the master won’t represent a toplevel
window.  To get at the toplevel window that contains an arbitrary
widget, you can call the ‘_root()’ method.  This method begins with an
underscore to denote the fact that this function is part of the
implementation, and not an interface to Tk functionality.

Here are some examples of typical usage:

     import tkinter as tk

     class App(tk.Frame):
         def __init__(self, master=None):
             super().__init__(master)
             self.pack()

     # create the application
     myapp = App()

     #
     # here are method calls to the window manager class
     #
     myapp.master.title("My Do-Nothing Application")
     myapp.master.maxsize(1000, 400)

     # start the program
     myapp.mainloop()


File: python.info,  Node: Tk Option Data Types,  Next: Bindings and Events,  Prev: The Window Manager,  Up: Handy Reference

5.25.1.14 Tk Option Data Types
..............................

anchor

     Legal values are points of the compass: ‘"n"’, ‘"ne"’, ‘"e"’,
     ‘"se"’, ‘"s"’, ‘"sw"’, ‘"w"’, ‘"nw"’, and also ‘"center"’.

位图

     There are eight built-in, named bitmaps: ‘'error'’, ‘'gray25'’,
     ‘'gray50'’, ‘'hourglass'’, ‘'info'’, ‘'questhead'’, ‘'question'’,
     ‘'warning'’.  To specify an X bitmap filename, give the full path
     to the file, preceded with an ‘@’, as in
     ‘"@/usr/contrib/bitmap/gumby.bit"’.

boolean

     You can pass integers 0 or 1 or the strings ‘"yes"’ or ‘"no"’.

callback – 回调

     This is any Python function that takes no arguments.  For example:

          def print_it():
              print("hi there")
          fred["command"] = print_it

color

     Colors can be given as the names of X colors in the rgb.txt file,
     or as strings representing RGB values in 4 bit: ‘"#RGB"’, 8 bit:
     ‘"#RRGGBB"’, 12 bit" ‘"#RRRGGGBBB"’, or 16 bit ‘"#RRRRGGGGBBBB"’
     ranges, where R,G,B here represent any legal hex digit.  See page
     160 of Ousterhout’s book for details.

cursor

     The standard X cursor names from ‘cursorfont.h’ can be used,
     without the ‘XC_’ prefix.  For example to get a hand cursor
     (‘XC_hand2’), use the string ‘"hand2"’.  You can also specify a
     bitmap and mask file of your own.  See page 179 of Ousterhout’s
     book.

distance

     Screen distances can be specified in either pixels or absolute
     distances.  Pixels are given as numbers and absolute distances as
     strings, with the trailing character denoting units: ‘c’ for
     centimetres, ‘i’ for inches, ‘m’ for millimetres, ‘p’ for printer’s
     points.  For example, 3.5 inches is expressed as ‘"3.5i"’.

font

     Tk uses a list font name format, such as ‘{courier 10 bold}’.  Font
     sizes with positive numbers are measured in points; sizes with
     negative numbers are measured in pixels.

geometry

     This is a string of the form ‘widthxheight’, where width and height
     are measured in pixels for most widgets (in characters for widgets
     displaying text).  For example: ‘fred["geometry"] = "200x100"’.

justify

     Legal values are the strings: ‘"left"’, ‘"center"’, ‘"right"’, and
     ‘"fill"’.

region

     This is a string with four space-delimited elements, each of which
     is a legal distance (see above).  For example: ‘"2 3 4 5"’ and ‘"3i
     2i 4.5i 2i"’ and ‘"3c 2c 4c 10.43c"’ are all legal regions.

relief

     Determines what the border style of a widget will be.  Legal values
     are: ‘"raised"’, ‘"sunken"’, ‘"flat"’, ‘"groove"’, and ‘"ridge"’.

scrollcommand

     This is almost always the ‘set()’ method of some scrollbar widget,
     but can be any widget method that takes a single argument.

wrap:

     Must be one of: ‘"none"’, ‘"char"’, or ‘"word"’.


File: python.info,  Node: Bindings and Events,  Next: The index Parameter,  Prev: Tk Option Data Types,  Up: Handy Reference

5.25.1.15 Bindings and Events
.............................

The bind method from the widget command allows you to watch for certain
events and to have a callback function trigger when that event type
occurs.  The form of the bind method is:

     def bind(self, sequence, func, add=''):

where:

sequence – 序列

     is a string that denotes the target kind of event.  (See the bind
     man page and page 201 of John Ousterhout’s book for details).

func

     is a Python function, taking one argument, to be invoked when the
     event occurs.  An Event instance will be passed as the argument.
     (Functions deployed this way are commonly known as `callbacks'.)

add

     is optional, either ‘''’ or ‘'+'’.  Passing an empty string denotes
     that this binding is to replace any other bindings that this event
     is associated with.  Passing a ‘'+'’ means that this function is to
     be added to the list of functions bound to this event type.

例如

     def turn_red(self, event):
         event.widget["activeforeground"] = "red"

     self.button.bind("<Enter>", self.turn_red)

Notice how the widget field of the event is being accessed in the
‘turn_red()’ callback.  This field contains the widget that caught the X
event.  The following table lists the other event fields you can access,
and how they are denoted in Tk, which can be useful when referring to
the Tk man pages.

Tk       Tkinter Event Field       Tk       Tkinter Event Field
                                            
----------------------------------------------------------------------
                                            
%f       焦点                      %A       char
                                            
                                            
%h       height                    %E       send_event
                                            
                                            
%k       keycode                   %K       keysym
                                            
                                            
%s       状况                      %N       keysym_num
                                            
                                            
%t       time                      %T       type
                                            
                                            
%w       宽度                      %W       widget
                                            
                                            
%x       x                         %X       x_root
                                            
                                            
%y       y                         %Y       y_root
                                            


File: python.info,  Node: The index Parameter,  Next: Images,  Prev: Bindings and Events,  Up: Handy Reference

5.25.1.16 The index Parameter
.............................

A number of widgets require "index" parameters to be passed.  These are
used to point at a specific place in a Text widget, or to particular
characters in an Entry widget, or to particular menu items in a Menu
widget.

Entry widget indexes (index, view index, etc.)

     Entry widgets have options that refer to character positions in the
     text being displayed.  You can use these *note tkinter: 10d.
     functions to access these special points in text widgets:

Text widget indexes

     The index notation for Text widgets is very rich and is best
     described in the Tk man pages.

Menu indexes (menu.invoke(), menu.entryconfig(), etc.)

     Some options and methods for menus manipulate specific menu
     entries.  Anytime a menu index is needed for an option or a
     parameter, you may pass in:

        * an integer which refers to the numeric position of the entry
          in the widget, counted from the top, starting with 0;

        * the string ‘"active"’, which refers to the menu position that
          is currently under the cursor;

        * the string ‘"last"’ which refers to the last menu item;

        * An integer preceded by ‘@’, as in ‘@6’, where the integer is
          interpreted as a y pixel coordinate in the menu’s coordinate
          system;

        * the string ‘"none"’, which indicates no menu entry at all,
          most often used with menu.activate() to deactivate all
          entries, and finally,

        * a text string that is pattern matched against the label of the
          menu entry, as scanned from the top of the menu to the bottom.
          Note that this index type is considered after all the others,
          which means that matches for menu items labelled ‘last’,
          ‘active’, or ‘none’ may be interpreted as the above literals,
          instead.


File: python.info,  Node: Images,  Prev: The index Parameter,  Up: Handy Reference

5.25.1.17 Images
................

Images of different formats can be created through the corresponding
subclass of ‘tkinter.Image’:

   * ‘BitmapImage’ for images in XBM format.

   * ‘PhotoImage’ for images in PGM, PPM, GIF and PNG formats.  The
     latter is supported starting with Tk 8.6.

Either type of image is created through either the ‘file’ or the ‘data’
option (other options are available as well).

The image object can then be used wherever an ‘image’ option is
supported by some widget (e.g.  labels, buttons, menus).  In these
cases, Tk will not keep a reference to the image.  When the last Python
reference to the image object is deleted, the image data is deleted as
well, and Tk will display an empty box wherever the image was used.

参见
....

The Pillow(1) package adds support for formats such as BMP, JPEG, TIFF,
and WebP, among others.

   ---------- Footnotes ----------

   (1) http://python-pillow.org/


File: python.info,  Node: File Handlers,  Prev: Handy Reference,  Up: tkinter --- Tcl/Tk的Python接口

5.25.1.18 File Handlers
.......................

Tk allows you to register and unregister a callback function which will
be called from the Tk mainloop when I/O is possible on a file
descriptor.  Only one handler may be registered per file descriptor.
Example code:

     import tkinter
     widget = tkinter.Tk()
     mask = tkinter.READABLE | tkinter.WRITABLE
     widget.tk.createfilehandler(file, mask, callback)
     ...
     widget.tk.deletefilehandler(file)

This feature is not available on Windows.

Since you don’t know how many bytes are available for reading, you may
not want to use the *note BufferedIOBase: 591. or *note TextIOBase: c41.
*note read(): 1d67. or *note readline(): 1713. methods, since these will
insist on reading a predefined number of bytes.  For sockets, the *note
recv(): 680. or *note recvfrom(): 681. methods will work fine; for other
files, use raw reads or ‘os.read(file.fileno(), maxbytecount)’.

 -- 方法: Widget.tk.createfilehandler (file, mask, func)

     Registers the file handler callback function `func'.  The `file'
     argument may either be an object with a *note fileno(): 1f19.
     method (such as a file or socket object), or an integer file
     descriptor.  The `mask' argument is an ORed combination of any of
     the three constants below.  The callback is called as follows:

          callback(file, mask)

 -- 方法: Widget.tk.deletefilehandler (file)

     Unregisters a file handler.

 -- 数据: tkinter.READABLE
 -- 数据: tkinter.WRITABLE
 -- 数据: tkinter.EXCEPTION

     Constants used in the `mask' arguments.


File: python.info,  Node: tkinter ttk --- Tk主题小部件,  Next: tkinter tix --- TK扩展包,  Prev: tkinter --- Tcl/Tk的Python接口,  Up: Tk图形用户界面 GUI

5.25.2 ‘tkinter.ttk’ — Tk主题小部件
-----------------------------------

`源代码:' Lib/tkinter/ttk.py(1)

__________________________________________________________________

The *note tkinter.ttk: 110. module provides access to the Tk themed
widget set, introduced in Tk 8.5.  If Python has not been compiled
against Tk 8.5, this module can still be accessed if `Tile' has been
installed.  The former method using Tk 8.5 provides additional benefits
including anti-aliased font rendering under X11 and window transparency
(requiring a composition window manager on X11).

The basic idea for *note tkinter.ttk: 110. is to separate, to the extent
possible, the code implementing a widget’s behavior from the code
implementing its appearance.

参见
....

Tk Widget Styling Support(2)

     一份文档介绍Tk支持的主题

* Menu:

* 使用 Ttk::
* Ttk 部件::
* 控件::
* 组合框::
* Spinbox::
* 笔记本::
* Progressbar::
* Separator::
* Sizegrip::
* Treeview::
* Ttk Styling::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/tkinter/ttk.py

   (2) https://core.tcl.tk/tips/doc/trunk/tip/48.md


File: python.info,  Node: 使用 Ttk,  Next: Ttk 部件,  Up: tkinter ttk --- Tk主题小部件

5.25.2.1 使用 Ttk
.................

开始使用 Ttk, 导入模块:

     from tkinter import ttk

重写基础Tk部件,导入应跟随Tk导入:

     from tkinter import *
     from tkinter.ttk import *

That code causes several *note tkinter.ttk: 110. widgets (‘Button’,
‘Checkbutton’, ‘Entry’, ‘Frame’, ‘Label’, ‘LabelFrame’, ‘Menubutton’,
‘PanedWindow’, ‘Radiobutton’, ‘Scale’ and ‘Scrollbar’) to automatically
replace the Tk widgets.

This has the direct benefit of using the new widgets which gives a
better look and feel across platforms; however, the replacement widgets
are not completely compatible.  The main difference is that widget
options such as "fg", "bg" and others related to widget styling are no
longer present in Ttk widgets.  Instead, use the ‘ttk.Style’ class for
improved styling effects.

参见
....

Converting existing applications to use Tile widgets(1)

     A monograph (using Tcl terminology) about differences typically
     encountered when moving applications to use the new widgets.

   ---------- Footnotes ----------

   (1) http://tktable.sourceforge.net/tile/doc/converting.txt


File: python.info,  Node: Ttk 部件,  Next: 控件,  Prev: 使用 Ttk,  Up: tkinter ttk --- Tk主题小部件

5.25.2.2 Ttk 部件
.................

ttk 中有 18 种部件 ，其中十二种已存在于 tkinter 中: ‘Button’,
‘Checkbutton’, ‘Entry’, ‘Frame’, ‘Label’, ‘LabelFrame’, ‘Menubutton’,
‘PanedWindow’, ‘Radiobutton’, ‘Scale’, ‘Scrollbar’ 以及 *note Spinbox:
405.。 另外六种是新增的: *note Combobox: 319e, *note Notebook: 319f,
*note Progressbar: 31a0, ‘Separator’, ‘Sizegrip’ 以及 *note Treeview:
2bd.。 它们全都是 *note Widget: 31a1. 的子类。

Using the Ttk widgets gives the application an improved look and feel.
As discussed above, there are differences in how the styling is coded.

Tk 代码:

     l1 = tkinter.Label(text="Test", fg="black", bg="white")
     l2 = tkinter.Label(text="Test", fg="black", bg="white")

Ttk 代码:

     style = ttk.Style()
     style.configure("BW.TLabel", foreground="black", background="white")

     l1 = ttk.Label(text="Test", style="BW.TLabel")
     l2 = ttk.Label(text="Test", style="BW.TLabel")

有关 *note TtkStyling: 31a2. 的更多信息，请参阅 *note Style: 31a3. 类文
档。


File: python.info,  Node: 控件,  Next: 组合框,  Prev: Ttk 部件,  Up: tkinter ttk --- Tk主题小部件

5.25.2.3 控件
.............

‘ttk.Widget’ 定义了 Tk 主题小部件支持的标准选项和方法，不应该直接实例化
。

* Menu:

* 标准选项::
* 可滚动控件选项::
* 标签选项::
* 兼容性选项::
* 控件状态::
* ttk.Widget: ttk Widget.


File: python.info,  Node: 标准选项,  Next: 可滚动控件选项,  Up: 控件

5.25.2.4 标准选项
.................

所有 ‘ttk’ 小部件接受以下选项：

     选项            描述
                     
     -----------------------------------------------------------------------------------
                     
     class – 类      指定窗口类。在查询选项数据库中窗口的其他选项时，使用该类，确定窗
                     口的默认绑定标签，以及选择窗口小部件的默认布局和样式。此选项仅为
                     只读，并且只能在创建窗口时指定。
                     
                     
     cursor          指定要用于窗口小部件的鼠标光标。如果设置为空字符串（默认值），则
                     为父窗口小部件继承光标.
                     
                     
     takefocus       确定窗口是否在键盘遍历期间接受焦点。返回0或1，返回空字符串。如果
                     返回0，则表示在键盘遍历期间应该跳过该窗口。如果为1，则表示只要可
                     以查看窗口就应该接收输入焦点。并且空字符串意味着遍历脚本决定是否
                     关注窗口。
                     
                     
     style           可用于指定自定义窗口小部件样式。
                     


File: python.info,  Node: 可滚动控件选项,  Next: 标签选项,  Prev: 标准选项,  Up: 控件

5.25.2.5 可滚动控件选项
.......................

控件支持以下选项使用滚动条控制.

     选项                 描述
                          
     -----------------------------------------------------------------------------------
                          
     xscroll命令          用于与垂直滚动条通讯.
                          
                          当视图在部件窗口改变,部件将会基于scroll命令生成Tcl命令.
                          
                          Usually this option consists of the method
                          ‘Scrollbar.set()’ of some scrollbar.  This will cause the
                          scrollbar to be updated whenever the view in the window
                          changes.
                          
                          
     yscroll命令          用于与垂直滚动条通讯.更多信息请参考上面的信息.
                          


File: python.info,  Node: 标签选项,  Next: 兼容性选项,  Prev: 可滚动控件选项,  Up: 控件

5.25.2.6 标签选项
.................

以下选项支持标签,按钮已经其他类按钮的控件.

     选项               描述
                        
     -----------------------------------------------------------------------------------
                        
     文本               Specifies a text string to be displayed inside the widget.
                        
                        
     文本变量           Specifies a name whose value will be used in place of the
                        text option resource.
                        
                        
     下划线             If set, specifies the index (0-based) of a character to
                        underline in the text string.  The underline character is
                        used for mnemonic activation.
                        
                        
     图片               Specifies an image to display.  This is a list of 1 or more
                        elements.  The first element is the default image name.  The
                        rest of the list if a sequence of statespec/value pairs as
                        defined by *note Style.map(): ee6, specifying different
                        images to use when the widget is in a particular state or a
                        combination of states.  All images in the list should have
                        the same size.
                        
                        
     compound           Specifies how to display the image relative to the text, in
                        the case both text and images options are present.  Valid
                        values are:
                        
                           * text: 只显示文本
                        
                           * image: 只显示图片
                        
                           * top, bottom, left, right: 分别显示图片的上,下,左,右的文
                             本.
                        
                           * none: 默认. 如果设置显示图片, 否则文本.
                        
                        
     宽度               If greater than zero, specifies how much space, in character
                        widths, to allocate for the text label, if less than zero,
                        specifies a minimum width.  If zero or unspecified, the
                        natural width of the text label is used.
                        


File: python.info,  Node: 兼容性选项,  Next: 控件状态,  Prev: 标签选项,  Up: 控件

5.25.2.7 兼容性选项
...................

     选项         描述
                  
     ----------------------------------------------------------------------------------
                  
     状况         May be set to "normal" or "disabled" to control the "disabled"
                  state bit.  This is a write-only option: setting it changes the
                  widget state, but the *note Widget.state(): 31a9. method does not
                  affect this option.
                  


File: python.info,  Node: 控件状态,  Next: ttk Widget,  Prev: 兼容性选项,  Up: 控件

5.25.2.8 控件状态
.................

控件状态是无关状态标志的位图.

     Flag             描述
                      
     -----------------------------------------------------------------------------------
                      
     活动             The mouse cursor is over the widget and pressing a mouse button
                      will cause some action to occur
                      
                      
     禁用             在程序控制下控件是禁用的
                      
                      
     焦点             控件有键盘焦点
                      
                      
     按压             Widget is being pressed
                      
                      
     选择             "On", "true", or "current" for things like Checkbuttons and
                      radiobuttons
                      
                      
     背景             Windows and Mac have a notion of an "active" or foreground
                      window.  The `background' state is set for widgets in a
                      background window, and cleared for those in the foreground
                      window
                      
                      
     只读             Widget should not allow user modification
                      
                      
     alternate        A widget-specific alternate display format
                      
                      
     无效的           控件的值是无效的
                      

A state specification is a sequence of state names, optionally prefixed
with an exclamation point indicating that the bit is off.


File: python.info,  Node: ttk Widget,  Prev: 控件状态,  Up: 控件

5.25.2.9 ttk.Widget
...................

Besides the methods described below, the ‘ttk.Widget’ supports the
methods ‘tkinter.Widget.cget()’ and ‘tkinter.Widget.configure()’.

 -- 类: tkinter.ttk.Widget

      -- 方法: identify (x, y)

          Returns the name of the element at position `x' `y', or the
          empty string if the point does not lie within any element.

          `x' and `y' are pixel coordinates relative to the widget.

      -- 方法: instate (statespec, callback=None, *args, **kw)

          Test the widget’s state.  If a callback is not specified,
          returns ‘True’ if the widget state matches `statespec' and
          ‘False’ otherwise.  If callback is specified then it is called
          with args if widget state matches `statespec'.

      -- 方法: state (statespec=None)

          Modify or inquire widget state.  If `statespec' is specified,
          sets the widget state according to it and return a new
          `statespec' indicating which flags were changed.  If
          `statespec' is not specified, returns the currently-enabled
          state flags.

     `statespec' will usually be a list or a tuple.


File: python.info,  Node: 组合框,  Next: Spinbox,  Prev: 控件,  Up: tkinter ttk --- Tk主题小部件

5.25.2.10 组合框
................

The ‘ttk.Combobox’ widget combines a text field with a pop-down list of
values.  This widget is a subclass of ‘Entry’.

Besides the methods inherited from *note Widget: 31a1.: ‘Widget.cget()’,
‘Widget.configure()’, *note Widget.identify(): 31ac, *note
Widget.instate(): 31ad. and *note Widget.state(): 31a9, and the
following inherited from ‘Entry’: ‘Entry.bbox()’, ‘Entry.delete()’,
‘Entry.icursor()’, ‘Entry.index()’, ‘Entry.insert()’,
‘Entry.selection()’, ‘Entry.xview()’, it has some other methods,
described at ‘ttk.Combobox’.

* Menu:

* 选项::
* 虚拟事件::
* ttk.Combobox: ttk Combobox.


File: python.info,  Node: 选项,  Next: 虚拟事件,  Up: 组合框

5.25.2.11 选项
..............

This widget accepts the following specific options:

     选项                  描述
                           
     -----------------------------------------------------------------------------------
                           
     exportselection       Boolean value.  If set, the widget selection is linked to
                           the Window Manager selection (which can be returned by
                           invoking Misc.selection_get, for example).
                           
                           
     justify               Specifies how the text is aligned within the widget.  One
                           of "left", "center", or "right".
                           
                           
     height                Specifies the height of the pop-down listbox, in rows.
                           
                           
     postcommand           A script (possibly registered with Misc.register) that is
                           called immediately before displaying the values.  It may
                           specify which values to display.
                           
                           
     状况                  One of "normal", "readonly", or "disabled".  In the
                           "readonly" state, the value may not be edited directly,
                           and the user can only selection of the values from the
                           dropdown list.  In the "normal" state, the text field is
                           directly editable.  In the "disabled" state, no
                           interaction is possible.
                           
                           
     文本变量              Specifies a name whose value is linked to the widget
                           value.  Whenever the value associated with that name
                           changes, the widget value is updated, and vice versa.  See
                           ‘tkinter.StringVar’.
                           
                           
     值                    Specifies the list of values to display in the drop-down
                           listbox.
                           
                           
     宽度                  Specifies an integer value indicating the desired width of
                           the entry window, in average-size characters of the
                           widget’s font.
                           


File: python.info,  Node: 虚拟事件,  Next: ttk Combobox,  Prev: 选项,  Up: 组合框

5.25.2.12 虚拟事件
..................

The combobox widgets generates a `<<ComboboxSelected>>' virtual event
when the user selects an element from the list of values.


File: python.info,  Node: ttk Combobox,  Prev: 虚拟事件,  Up: 组合框

5.25.2.13 ttk.Combobox
......................

 -- 类: tkinter.ttk.Combobox

      -- 方法: current (newindex=None)

          If `newindex' is specified, sets the combobox value to the
          element position `newindex'.  Otherwise, returns the index of
          the current value or -1 if the current value is not in the
          values list.

      -- 方法: get ()

          Returns the current value of the combobox.

      -- 方法: set (value)

          Sets the value of the combobox to `value'.


File: python.info,  Node: Spinbox,  Next: 笔记本,  Prev: 组合框,  Up: tkinter ttk --- Tk主题小部件

5.25.2.14 Spinbox
.................

The ‘ttk.Spinbox’ widget is a ‘ttk.Entry’ enhanced with increment and
decrement arrows.  It can be used for numbers or lists of string values.
This widget is a subclass of ‘Entry’.

Besides the methods inherited from *note Widget: 31a1.: ‘Widget.cget()’,
‘Widget.configure()’, *note Widget.identify(): 31ac, *note
Widget.instate(): 31ad. and *note Widget.state(): 31a9, and the
following inherited from ‘Entry’: ‘Entry.bbox()’, ‘Entry.delete()’,
‘Entry.icursor()’, ‘Entry.index()’, ‘Entry.insert()’, ‘Entry.xview()’,
it has some other methods, described at ‘ttk.Spinbox’.

* Menu:

* 选项: 选项<2>.
* 虚拟事件: 虚拟事件<2>.
* ttk.Spinbox: ttk Spinbox.


File: python.info,  Node: 选项<2>,  Next: 虚拟事件<2>,  Up: Spinbox

5.25.2.15 选项
..............

This widget accepts the following specific options:

选项                       描述
                           
--------------------------------------------------------------------------------------
                           
从                         Float value.  If set, this is the minimum value to which
                           the decrement button will decrement.  Must be spelled as
                           ‘from_’ when used as an argument, since ‘from’ is a
                           Python keyword.
                           
                           
到                         Float value.  If set, this is the maximum value to which
                           the increment button will increment.
                           
                           
增加                       Float value.  Specifies the amount which the
                           increment/decrement buttons change the value.  Defaults
                           to 1.0.
                           
                           
值                         Sequence of string or float values.  If specified, the
                           increment/decrement buttons will cycle through the items
                           in this sequence rather than incrementing or
                           decrementing numbers.
                           
                           
wrap                       Boolean value.  If ‘True’, increment and decrement
                           buttons will cycle from the ‘to’ value to the ‘from’
                           value or the ‘from’ value to the ‘to’ value,
                           respectively.
                           
                           
format                     String value.  This specifies the format of numbers set
                           by the increment/decrement buttons.  It must be in the
                           form "%W.Pf", where W is the padded width of the value,
                           P is the precision, and ’%’ and ’f’ are literal.
                           
                           
命令                       Python callable.  Will be called with no arguments
                           whenever either of the increment or decrement buttons
                           are pressed.
                           


File: python.info,  Node: 虚拟事件<2>,  Next: ttk Spinbox,  Prev: 选项<2>,  Up: Spinbox

5.25.2.16 虚拟事件
..................

The spinbox widget generates an `<<Increment>>' virtual event when the
user presses <Up>, and a `<<Decrement>>' virtual event when the user
presses <Down>.


File: python.info,  Node: ttk Spinbox,  Prev: 虚拟事件<2>,  Up: Spinbox

5.25.2.17 ttk.Spinbox
.....................

 -- 类: tkinter.ttk.Spinbox

      -- 方法: get ()

          返回spinbox当前值

      -- 方法: set (value)

          设置spinbox的值为*value*.


File: python.info,  Node: 笔记本,  Next: Progressbar,  Prev: Spinbox,  Up: tkinter ttk --- Tk主题小部件

5.25.2.18 笔记本
................

Ttk Notebook widget manages a collection of windows and displays a
single one at a time.  Each child window is associated with a tab, which
the user may select to change the currently-displayed window.

* Menu:

* 选项: 选项<3>.
* Tab 选项::
* Tab Identifiers::
* Virtual Events::
* ttk.Notebook: ttk Notebook.


File: python.info,  Node: 选项<3>,  Next: Tab 选项,  Up: 笔记本

5.25.2.19 选项
..............

This widget accepts the following specific options:

     选项          描述
                   
     -----------------------------------------------------------------------------------
                   
     height        If present and greater than zero, specifies the desired height of
                   the pane area (not including internal padding or tabs).
                   Otherwise, the maximum height of all panes is used.
                   
                   
     padding       Specifies the amount of extra space to add around the outside of
                   the notebook.  The padding is a list up to four length
                   specifications left top right bottom.  If fewer than four elements
                   are specified, bottom defaults to top, right defaults to left, and
                   top defaults to left.
                   
                   
     宽度          If present and greater than zero, specified the desired width of
                   the pane area (not including internal padding).  Otherwise, the
                   maximum width of all panes is used.
                   


File: python.info,  Node: Tab 选项,  Next: Tab Identifiers,  Prev: 选项<3>,  Up: 笔记本

5.25.2.20 Tab 选项
..................

There are also specific options for tabs:

     选项            描述
                     
     -----------------------------------------------------------------------------------
                     
     状况            Either "normal", "disabled" or "hidden".  If "disabled", then
                     the tab is not selectable.  If "hidden", then the tab is not
                     shown.
                     
                     
     sticky          Specifies how the child window is positioned within the pane
                     area.  Value is a string containing zero or more of the
                     characters "n", "s", "e" or "w".  Each letter refers to a side
                     (north, south, east or west) that the child window will stick
                     to, as per the ‘grid()’ geometry manager.
                     
                     
     padding         Specifies the amount of extra space to add between the notebook
                     and this pane.  Syntax is the same as for the option padding
                     used by this widget.
                     
                     
     文本            Specifies a text to be displayed in the tab.
                     
                     
     图片            Specifies an image to display in the tab.  See the option image
                     described in *note Widget: 31a1.
                     
                     
     compound        Specifies how to display the image relative to the text, in the
                     case both options text and image are present.  See
                     *note Label Options: 31a7. for legal values.
                     
                     
     下划线          Specifies the index (0-based) of a character to underline in the
                     text string.  The underlined character is used for mnemonic
                     activation if *note Notebook.enable_traversal(): 31be. is
                     called.
                     


File: python.info,  Node: Tab Identifiers,  Next: Virtual Events,  Prev: Tab 选项,  Up: 笔记本

5.25.2.21 Tab Identifiers
.........................

The tab_id present in several methods of ‘ttk.Notebook’ may take any of
the following forms:

   * An integer between zero and the number of tabs

   * The name of a child window

   * A positional specification of the form "@x,y", which identifies the
     tab

   * The literal string "current", which identifies the
     currently-selected tab

   * The literal string "end", which returns the number of tabs (only
     valid for *note Notebook.index(): 31c0.)


File: python.info,  Node: Virtual Events,  Next: ttk Notebook,  Prev: Tab Identifiers,  Up: 笔记本

5.25.2.22 Virtual Events
........................

This widget generates a `<<NotebookTabChanged>>' virtual event after a
new tab is selected.


File: python.info,  Node: ttk Notebook,  Prev: Virtual Events,  Up: 笔记本

5.25.2.23 ttk.Notebook
......................

 -- 类: tkinter.ttk.Notebook

      -- 方法: add (child, **kw)

          Adds a new tab to the notebook.

          If window is currently managed by the notebook but hidden, it
          is restored to its previous position.

          See *note Tab Options: 31bd. for the list of available
          options.

      -- 方法: forget (tab_id)

          Removes the tab specified by `tab_id', unmaps and unmanages
          the associated window.

      -- 方法: hide (tab_id)

          Hides the tab specified by `tab_id'.

          The tab will not be displayed, but the associated window
          remains managed by the notebook and its configuration
          remembered.  Hidden tabs may be restored with the *note add():
          31c3. command.

      -- 方法: identify (x, y)

          Returns the name of the tab element at position `x', `y', or
          the empty string if none.

      -- 方法: index (tab_id)

          Returns the numeric index of the tab specified by `tab_id', or
          the total number of tabs if `tab_id' is the string "end".

      -- 方法: insert (pos, child, **kw)

          Inserts a pane at the specified position.

          `pos' is either the string "end", an integer index, or the
          name of a managed child.  If `child' is already managed by the
          notebook, moves it to the specified position.

          See *note Tab Options: 31bd. for the list of available
          options.

      -- 方法: select (tab_id=None)

          Selects the specified `tab_id'.

          The associated child window will be displayed, and the
          previously-selected window (if different) is unmapped.  If
          `tab_id' is omitted, returns the widget name of the currently
          selected pane.

      -- 方法: tab (tab_id, option=None, **kw)

          Query or modify the options of the specific `tab_id'.

          If `kw' is not given, returns a dictionary of the tab option
          values.  If `option' is specified, returns the value of that
          `option'.  Otherwise, sets the options to the corresponding
          values.

      -- 方法: tabs ()

          Returns a list of windows managed by the notebook.

      -- 方法: enable_traversal ()

          Enable keyboard traversal for a toplevel window containing
          this notebook.

          This will extend the bindings for the toplevel window
          containing the notebook as follows:

             * ‘Control-Tab’: selects the tab following the currently
               selected one.

             * ‘Shift-Control-Tab’: selects the tab preceding the
               currently selected one.

             * ‘Alt-K’: where `K' is the mnemonic (underlined) character
               of any tab, will select that tab.

          Multiple notebooks in a single toplevel may be enabled for
          traversal, including nested notebooks.  However, notebook
          traversal only works properly if all panes have the notebook
          they are in as master.


File: python.info,  Node: Progressbar,  Next: Separator,  Prev: 笔记本,  Up: tkinter ttk --- Tk主题小部件

5.25.2.24 Progressbar
.....................

The ‘ttk.Progressbar’ widget shows the status of a long-running
operation.  It can operate in two modes: 1) the determinate mode which
shows the amount completed relative to the total amount of work to be
done and 2) the indeterminate mode which provides an animated display to
let the user know that work is progressing.

* Menu:

* 选项: 选项<4>.
* ttk.Progressbar: ttk Progressbar.


File: python.info,  Node: 选项<4>,  Next: ttk Progressbar,  Up: Progressbar

5.25.2.25 选项
..............

This widget accepts the following specific options:

     选项           描述
                    
     -----------------------------------------------------------------------------------
                    
     orient         One of "horizontal" or "vertical".  Specifies the orientation of
                    the progress bar.
                    
                    
     length         Specifies the length of the long axis of the progress bar (width
                    if horizontal, height if vertical).
                    
                    
     模式           One of "determinate" or "indeterminate".
                    
                    
     maximum        A number specifying the maximum value.  Defaults to 100.
                    
                    
     值             The current value of the progress bar.  In "determinate" mode,
                    this represents the amount of work completed.  In "indeterminate"
                    mode, it is interpreted as modulo `maximum'; that is, the
                    progress bar completes one "cycle" when its value increases by
                    `maximum'.
                    
                    
     variable       A name which is linked to the option value.  If specified, the
                    value of the progress bar is automatically set to the value of
                    this name whenever the latter is modified.
                    
                    
     phase          Read-only option.  The widget periodically increments the value
                    of this option whenever its value is greater than 0 and, in
                    determinate mode, less than maximum.  This option may be used by
                    the current theme to provide additional animation effects.
                    


File: python.info,  Node: ttk Progressbar,  Prev: 选项<4>,  Up: Progressbar

5.25.2.26 ttk.Progressbar
.........................

 -- 类: tkinter.ttk.Progressbar

      -- 方法: start (interval=None)

          Begin autoincrement mode: schedules a recurring timer event
          that calls *note Progressbar.step(): 31cf. every `interval'
          milliseconds.  If omitted, `interval' defaults to 50
          milliseconds.

      -- 方法: step (amount=None)

          Increments the progress bar’s value by `amount'.

          `amount' defaults to 1.0 if omitted.

      -- 方法: stop ()

          Stop autoincrement mode: cancels any recurring timer event
          initiated by *note Progressbar.start(): 31ce. for this
          progress bar.


File: python.info,  Node: Separator,  Next: Sizegrip,  Prev: Progressbar,  Up: tkinter ttk --- Tk主题小部件

5.25.2.27 Separator
...................

The ‘ttk.Separator’ widget displays a horizontal or vertical separator
bar.

It has no other methods besides the ones inherited from ‘ttk.Widget’.

* Menu:

* 选项: 选项<5>.


File: python.info,  Node: 选项<5>,  Up: Separator

5.25.2.28 选项
..............

This widget accepts the following specific option:

     选项         描述
                  
     ----------------------------------------------------------------------------------
                  
     orient       One of "horizontal" or "vertical".  Specifies the orientation of
                  the separator.
                  


File: python.info,  Node: Sizegrip,  Next: Treeview,  Prev: Separator,  Up: tkinter ttk --- Tk主题小部件

5.25.2.29 Sizegrip
..................

The ‘ttk.Sizegrip’ widget (also known as a grow box) allows the user to
resize the containing toplevel window by pressing and dragging the grip.

This widget has neither specific options nor specific methods, besides
the ones inherited from ‘ttk.Widget’.

* Menu:

* Platform-specific notes::
* Bugs::


File: python.info,  Node: Platform-specific notes,  Next: Bugs,  Up: Sizegrip

5.25.2.30 Platform-specific notes
.................................

   * On MacOS X, toplevel windows automatically include a built-in size
     grip by default.  Adding a ‘Sizegrip’ is harmless, since the
     built-in grip will just mask the widget.


File: python.info,  Node: Bugs,  Prev: Platform-specific notes,  Up: Sizegrip

5.25.2.31 Bugs
..............

   * If the containing toplevel’s position was specified relative to the
     right or bottom of the screen (e.g.  ....), the ‘Sizegrip’ widget
     will not resize the window.

   * This widget supports only "southeast" resizing.


File: python.info,  Node: Treeview,  Next: Ttk Styling,  Prev: Sizegrip,  Up: tkinter ttk --- Tk主题小部件

5.25.2.32 Treeview
..................

The ‘ttk.Treeview’ widget displays a hierarchical collection of items.
Each item has a textual label, an optional image, and an optional list
of data values.  The data values are displayed in successive columns
after the tree label.

The order in which data values are displayed may be controlled by
setting the widget option ‘displaycolumns’.  The tree widget can also
display column headings.  Columns may be accessed by number or symbolic
names listed in the widget option columns.  See *note Column
Identifiers: 31d7.

Each item is identified by a unique name.  The widget will generate item
IDs if they are not supplied by the caller.  There is a distinguished
root item, named ‘{}’.  The root item itself is not displayed; its
children appear at the top level of the hierarchy.

Each item also has a list of tags, which can be used to associate event
bindings with individual items and control the appearance of the item.

The Treeview widget supports horizontal and vertical scrolling,
according to the options described in *note Scrollable Widget Options:
31a6. and the methods *note Treeview.xview(): 31d8. and *note
Treeview.yview(): 31d9.

* Menu:

* 选项: 选项<6>.
* Item Options::
* Tag Options::
* Column Identifiers::
* Virtual Events: Virtual Events<2>.
* ttk.Treeview: ttk Treeview.


File: python.info,  Node: 选项<6>,  Next: Item Options,  Up: Treeview

5.25.2.33 选项
..............

This widget accepts the following specific options:

     选项                 描述
                          
     ----------------------------------------------------------------------------------
                          
     columns              A list of column identifiers, specifying the number of
                          columns and their names.
                          
                          
     displaycolumns       A list of column identifiers (either symbolic or integer
                          indices) specifying which data columns are displayed and
                          the order in which they appear, or the string "#all".
                          
                          
     height               Specifies the number of rows which should be visible.
                          Note: the requested width is determined from the sum of
                          the column widths.
                          
                          
     padding              Specifies the internal padding for the widget.  The
                          padding is a list of up to four length specifications.
                          
                          
     selectmode           Controls how the built-in class bindings manage the
                          selection.  One of "extended", "browse" or "none".  If set
                          to "extended" (the default), multiple items may be
                          selected.  If "browse", only a single item will be
                          selected at a time.  If "none", the selection will not be
                          changed.
                          
                          Note that the application code and tag bindings can set
                          the selection however they wish, regardless of the value
                          of this option.
                          
                          
     show                 A list containing zero or more of the following values,
                          specifying which elements of the tree to display.
                          
                             * tree: display tree labels in column #0.
                          
                             * headings: display the heading row.
                          
                          The default is "tree headings", i.e., show all elements.
                          
                          `Note': Column #0 always refers to the tree column, even
                          if show="tree" is not specified.
                          


File: python.info,  Node: Item Options,  Next: Tag Options,  Prev: 选项<6>,  Up: Treeview

5.25.2.34 Item Options
......................

The following item options may be specified for items in the insert and
item widget commands.

     选项         描述
                  
     ---------------------------------------------------------------------------------
                  
     文本         The textual label to display for the item.
                  
                  
     图片         A Tk Image, displayed to the left of the label.
                  
                  
     值           The list of values associated with the item.
                  
                  Each item should have the same number of values as the widget
                  option columns.  If there are fewer values than columns, the
                  remaining values are assumed empty.  If there are more values
                  than columns, the extra values are ignored.
                  
                  
     open         ‘True’/‘False’ value indicating whether the item’s children
                  should be displayed or hidden.
                  
                  
     tags         A list of tags associated with this item.
                  


File: python.info,  Node: Tag Options,  Next: Column Identifiers,  Prev: Item Options,  Up: Treeview

5.25.2.35 Tag Options
.....................

The following options may be specified on tags:

     选项             描述
                      
     ---------------------------------------------------------------------------------
                      
     foreground       Specifies the text foreground color.
                      
                      
     背景             Specifies the cell or item background color.
                      
                      
     font             Specifies the font to use when drawing text.
                      
                      
     图片             Specifies the item image, in case the item’s image option is
                      empty.
                      


File: python.info,  Node: Column Identifiers,  Next: Virtual Events<2>,  Prev: Tag Options,  Up: Treeview

5.25.2.36 Column Identifiers
............................

Column identifiers take any of the following forms:

   * A symbolic name from the list of columns option.

   * An integer n, specifying the nth data column.

   * A string of the form #n, where n is an integer, specifying the nth
     display column.

注释:

   * Item’s option values may be displayed in a different order than the
     order in which they are stored.

   * Column #0 always refers to the tree column, even if show="tree" is
     not specified.

A data column number is an index into an item’s option values list; a
display column number is the column number in the tree where the values
are displayed.  Tree labels are displayed in column #0.  If option
displaycolumns is not set, then data column n is displayed in column
#n+1.  Again, `column #0 always refers to the tree column'.


File: python.info,  Node: Virtual Events<2>,  Next: ttk Treeview,  Prev: Column Identifiers,  Up: Treeview

5.25.2.37 Virtual Events
........................

The Treeview widget generates the following virtual events.

     Event                    描述
                              
     --------------------------------------------------------------------------------
                              
     <<TreeviewSelect>>       Generated whenever the selection changes.
                              
                              
     <<TreeviewOpen>>         Generated just before settings the focus item to
                              open=True.
                              
                              
     <<TreeviewClose>>        Generated just after setting the focus item to
                              open=False.
                              

The *note Treeview.focus(): 31de. and *note Treeview.selection(): 2be.
methods can be used to determine the affected item or items.


File: python.info,  Node: ttk Treeview,  Prev: Virtual Events<2>,  Up: Treeview

5.25.2.38 ttk.Treeview
......................

 -- 类: tkinter.ttk.Treeview

      -- 方法: bbox (item, column=None)

          Returns the bounding box (relative to the treeview widget’s
          window) of the specified `item' in the form (x, y, width,
          height).

          If `column' is specified, returns the bounding box of that
          cell.  If the `item' is not visible (i.e., if it is a
          descendant of a closed item or is scrolled offscreen), returns
          an empty string.

      -- 方法: get_children (item=None)

          Returns the list of children belonging to `item'.

          If `item' is not specified, returns root children.

      -- 方法: set_children (item, *newchildren)

          Replaces `item'’s child with `newchildren'.

          Children present in `item' that are not present in
          `newchildren' are detached from the tree.  No items in
          `newchildren' may be an ancestor of `item'.  Note that not
          specifying `newchildren' results in detaching `item'’s
          children.

      -- 方法: column (column, option=None, **kw)

          Query or modify the options for the specified `column'.

          If `kw' is not given, returns a dict of the column option
          values.  If `option' is specified then the value for that
          `option' is returned.  Otherwise, sets the options to the
          corresponding values.

          The valid options/values are:

             * 
               id

                    Returns the column name.  This is a read-only
                    option.

             * 
               anchor: One of the standard Tk anchor values.

                    Specifies how the text in this column should be
                    aligned with respect to the cell.

             * 
               minwidth: width

                    The minimum width of the column in pixels.  The
                    treeview widget will not make the column any smaller
                    than specified by this option when the widget is
                    resized or the user drags a column.

             * 
               stretch: ‘True’/‘False’

                    指明列宽度是否应该在部件大小被改变时进行相应的调整。

             * 
               width: width

                    以像素表示的列宽度。

          要配置树的列，则调用此方法并附带参数 column = "#0"

      -- 方法: delete (*items)

          Delete all specified `items' and all their descendants.

          The root item may not be deleted.

      -- 方法: detach (*items)

          Unlinks all of the specified `items' from the tree.

          The items and all of their descendants are still present, and
          may be reinserted at another point in the tree, but will not
          be displayed.

          The root item may not be detached.

      -- 方法: exists (item)

          Returns ‘True’ if the specified `item' is present in the tree.

      -- 方法: focus (item=None)

          If `item' is specified, sets the focus item to `item'.
          Otherwise, returns the current focus item, or ’’ if there is
          none.

      -- 方法: heading (column, option=None, **kw)

          Query or modify the heading options for the specified
          `column'.

          If `kw' is not given, returns a dict of the heading option
          values.  If `option' is specified then the value for that
          `option' is returned.  Otherwise, sets the options to the
          corresponding values.

          The valid options/values are:

             * 
               text: text

                    The text to display in the column heading.

             * 
               image: imageName

                    Specifies an image to display to the right of the
                    column heading.

             * 
               anchor: anchor

                    Specifies how the heading text should be aligned.
                    One of the standard Tk anchor values.

             * 
               command: callback

                    A callback to be invoked when the heading label is
                    pressed.

          To configure the tree column heading, call this with column =
          "#0".

      -- 方法: identify (component, x, y)

          Returns a description of the specified `component' under the
          point given by `x' and `y', or the empty string if no such
          `component' is present at that position.

      -- 方法: identify_row (y)

          Returns the item ID of the item at position `y'.

      -- 方法: identify_column (x)

          Returns the data column identifier of the cell at position
          `x'.

          The tree column has ID #0.

      -- 方法: identify_region (x, y)

          Returns one of:

          region          meaning
                          
          -----------------------------------------------------------
                          
          heading         Tree heading area.
                          
                          
          separator       Space between two columns headings.
                          
                          
          tree            The tree area.
                          
                          
          cell            A data cell.
                          

          Availability: Tk 8.6.

      -- 方法: identify_element (x, y)

          Returns the element at position `x', `y'.

          Availability: Tk 8.6.

      -- 方法: index (item)

          Returns the integer index of `item' within its parent’s list
          of children.

      -- 方法: insert (parent, index, iid=None, **kw)

          Creates a new item and returns the item identifier of the
          newly created item.

          `parent' is the item ID of the parent item, or the empty
          string to create a new top-level item.  `index' is an integer,
          or the value "end", specifying where in the list of parent’s
          children to insert the new item.  If `index' is less than or
          equal to zero, the new node is inserted at the beginning; if
          `index' is greater than or equal to the current number of
          children, it is inserted at the end.  If `iid' is specified,
          it is used as the item identifier; `iid' must not already
          exist in the tree.  Otherwise, a new unique identifier is
          generated.

          See *note Item Options: 31db. for the list of available
          points.

      -- 方法: item (item, option=None, **kw)

          Query or modify the options for the specified `item'.

          If no options are given, a dict with options/values for the
          item is returned.  If `option' is specified then the value for
          that option is returned.  Otherwise, sets the options to the
          corresponding values as given by `kw'.

      -- 方法: move (item, parent, index)

          Moves `item' to position `index' in `parent'’s list of
          children.

          It is illegal to move an item under one of its descendants.
          If `index' is less than or equal to zero, `item' is moved to
          the beginning; if greater than or equal to the number of
          children, it is moved to the end.  If `item' was detached it
          is reattached.

      -- 方法: next (item)

          Returns the identifier of `item'’s next sibling, or ’’ if
          `item' is the last child of its parent.

      -- 方法: parent (item)

          Returns the ID of the parent of `item', or ’’ if `item' is at
          the top level of the hierarchy.

      -- 方法: prev (item)

          Returns the identifier of `item'’s previous sibling, or ’’ if
          `item' is the first child of its parent.

      -- 方法: reattach (item, parent, index)

          An alias for *note Treeview.move(): 31f0.

      -- 方法: see (item)

          Ensure that `item' is visible.

          Sets all of `item'’s ancestors open option to ‘True’, and
          scrolls the widget if necessary so that `item' is within the
          visible portion of the tree.

      -- 方法: selection ()

          Returns a tuple of selected items.

          在 3.8 版更改: ‘selection()’ no longer takes arguments.  For
          changing the selection state use the following selection
          methods.

      -- 方法: selection_set (*items)

          `items' becomes the new selection.

          在 3.6 版更改: `items' can be passed as separate arguments,
          not just as a single tuple.

      -- 方法: selection_add (*items)

          Add `items' to the selection.

          在 3.6 版更改: `items' can be passed as separate arguments,
          not just as a single tuple.

      -- 方法: selection_remove (*items)

          Remove `items' from the selection.

          在 3.6 版更改: `items' can be passed as separate arguments,
          not just as a single tuple.

      -- 方法: selection_toggle (*items)

          Toggle the selection state of each item in `items'.

          在 3.6 版更改: `items' can be passed as separate arguments,
          not just as a single tuple.

      -- 方法: set (item, column=None, value=None)

          With one argument, returns a dictionary of column/value pairs
          for the specified `item'.  With two arguments, returns the
          current value of the specified `column'.  With three
          arguments, sets the value of given `column' in given `item' to
          the specified `value'.

      -- 方法: tag_bind (tagname, sequence=None, callback=None)

          Bind a callback for the given event `sequence' to the tag
          `tagname'.  When an event is delivered to an item, the
          callbacks for each of the item’s tags option are called.

      -- 方法: tag_configure (tagname, option=None, **kw)

          Query or modify the options for the specified `tagname'.

          If `kw' is not given, returns a dict of the option settings
          for `tagname'.  If `option' is specified, returns the value
          for that `option' for the specified `tagname'.  Otherwise,
          sets the options to the corresponding values for the given
          `tagname'.

      -- 方法: tag_has (tagname, item=None)

          If `item' is specified, returns 1 or 0 depending on whether
          the specified `item' has the given `tagname'.  Otherwise,
          returns a list of all items that have the specified tag.

          Availability: Tk 8.6

      -- 方法: xview (*args)

          Query or modify horizontal position of the treeview.

      -- 方法: yview (*args)

          Query or modify vertical position of the treeview.


File: python.info,  Node: Ttk Styling,  Prev: Treeview,  Up: tkinter ttk --- Tk主题小部件

5.25.2.39 Ttk Styling
.....................

Each widget in ‘ttk’ is assigned a style, which specifies the set of
elements making up the widget and how they are arranged, along with
dynamic and default settings for element options.  By default the style
name is the same as the widget’s class name, but it may be overridden by
the widget’s style option.  If you don’t know the class name of a
widget, use the method ‘Misc.winfo_class()’ (somewidget.winfo_class()).

参见
....

Tcl’2004 conference presentation(1)

     This document explains how the theme engine works

 -- 类: tkinter.ttk.Style

     This class is used to manipulate the style database.

      -- 方法: configure (style, query_opt=None, **kw)

          Query or set the default value of the specified option(s) in
          `style'.

          Each key in `kw' is an option and each value is a string
          identifying the value for that option.

          For example, to change every default button to be a flat
          button with some padding and a different background color:

               from tkinter import ttk
               import tkinter

               root = tkinter.Tk()

               ttk.Style().configure("TButton", padding=6, relief="flat",
                  background="#ccc")

               btn = ttk.Button(text="Sample")
               btn.pack()

               root.mainloop()

      -- 方法: map (style, query_opt=None, **kw)

          Query or sets dynamic values of the specified option(s) in
          `style'.

          Each key in `kw' is an option and each value should be a list
          or a tuple (usually) containing statespecs grouped in tuples,
          lists, or some other preference.  A statespec is a compound of
          one or more states and then a value.

          An example may make it more understandable:

               import tkinter
               from tkinter import ttk

               root = tkinter.Tk()

               style = ttk.Style()
               style.map("C.TButton",
                   foreground=[('pressed', 'red'), ('active', 'blue')],
                   background=[('pressed', '!disabled', 'black'), ('active', 'white')]
                   )

               colored_btn = ttk.Button(text="Test", style="C.TButton").pack()

               root.mainloop()

          Note that the order of the (states, value) sequences for an
          option does matter, if the order is changed to ‘[('active',
          'blue'), ('pressed', 'red')]’ in the foreground option, for
          example, the result would be a blue foreground when the widget
          were in active or pressed states.

      -- 方法: lookup (style, option, state=None, default=None)

          Returns the value specified for `option' in `style'.

          If `state' is specified, it is expected to be a sequence of
          one or more states.  If the `default' argument is set, it is
          used as a fallback value in case no specification for option
          is found.

          To check what font a Button uses by default:

               from tkinter import ttk

               print(ttk.Style().lookup("TButton", "font"))

      -- 方法: layout (style, layoutspec=None)

          Define the widget layout for given `style'.  If `layoutspec'
          is omitted, return the layout specification for given style.

          `layoutspec', if specified, is expected to be a list or some
          other sequence type (excluding strings), where each item
          should be a tuple and the first item is the layout name and
          the second item should have the format described in *note
          Layouts: 3201.

          To understand the format, see the following example (it is not
          intended to do anything useful):

               from tkinter import ttk
               import tkinter

               root = tkinter.Tk()

               style = ttk.Style()
               style.layout("TMenubutton", [
                  ("Menubutton.background", None),
                  ("Menubutton.button", {"children":
                      [("Menubutton.focus", {"children":
                          [("Menubutton.padding", {"children":
                              [("Menubutton.label", {"side": "left", "expand": 1})]
                          })]
                      })]
                  }),
               ])

               mbtn = ttk.Menubutton(text='Text')
               mbtn.pack()
               root.mainloop()

      -- 方法: element_create (elementname, etype, *args, **kw)

          Create a new element in the current theme, of the given
          `etype' which is expected to be either "image", "from" or
          "vsapi".  The latter is only available in Tk 8.6a for Windows
          XP and Vista and is not described here.

          If "image" is used, `args' should contain the default image
          name followed by statespec/value pairs (this is the
          imagespec), and `kw' may have the following options:

                  * 
                    border=padding

                         padding is a list of up to four integers,
                         specifying the left, top, right, and bottom
                         borders, respectively.

                  * 
                    height=height

                         Specifies a minimum height for the element.  If
                         less than zero, the base image’s height is used
                         as a default.

                  * 
                    padding=padding

                         Specifies the element’s interior padding.
                         Defaults to border’s value if not specified.

                  * 
                    sticky=spec

                         Specifies how the image is placed within the
                         final parcel.  spec contains zero or more
                         characters "n", "s", "w", or "e".

                  * 
                    width=width

                         Specifies a minimum width for the element.  If
                         less than zero, the base image’s width is used
                         as a default.

          If "from" is used as the value of `etype', *note
          element_create(): 3202. will clone an existing element.
          `args' is expected to contain a themename, from which the
          element will be cloned, and optionally an element to clone
          from.  If this element to clone from is not specified, an
          empty element will be used.  `kw' is discarded.

      -- 方法: element_names ()

          Returns the list of elements defined in the current theme.

      -- 方法: element_options (elementname)

          Returns the list of `elementname'’s options.

      -- 方法: theme_create (themename, parent=None, settings=None)

          Create a new theme.

          It is an error if `themename' already exists.  If `parent' is
          specified, the new theme will inherit styles, elements and
          layouts from the parent theme.  If `settings' are present they
          are expected to have the same syntax used for *note
          theme_settings(): 3206.

      -- 方法: theme_settings (themename, settings)

          Temporarily sets the current theme to `themename', apply
          specified `settings' and then restore the previous theme.

          Each key in `settings' is a style and each value may contain
          the keys ’configure’, ’map’, ’layout’ and ’element create’ and
          they are expected to have the same format as specified by the
          methods *note Style.configure(): 31fe, *note Style.map(): ee6,
          *note Style.layout(): 3200. and *note Style.element_create():
          3202. respectively.

          As an example, let’s change the Combobox for the default theme
          a bit:

               from tkinter import ttk
               import tkinter

               root = tkinter.Tk()

               style = ttk.Style()
               style.theme_settings("default", {
                  "TCombobox": {
                      "configure": {"padding": 5},
                      "map": {
                          "background": [("active", "green2"),
                                         ("!disabled", "green4")],
                          "fieldbackground": [("!disabled", "green3")],
                          "foreground": [("focus", "OliveDrab1"),
                                         ("!disabled", "OliveDrab2")]
                      }
                  }
               })

               combo = ttk.Combobox().pack()

               root.mainloop()

      -- 方法: theme_names ()

          Returns a list of all known themes.

      -- 方法: theme_use (themename=None)

          If `themename' is not given, returns the theme in use.
          Otherwise, sets the current theme to `themename', refreshes
          all widgets and emits a <<ThemeChanged>> event.

* Menu:

* Layouts::

   ---------- Footnotes ----------

   (1) http://tktable.sourceforge.net/tile/tile-tcl2004.pdf


File: python.info,  Node: Layouts,  Up: Ttk Styling

5.25.2.40 Layouts
.................

A layout can be just ‘None’, if it takes no options, or a dict of
options specifying how to arrange the element.  The layout mechanism
uses a simplified version of the pack geometry manager: given an initial
cavity, each element is allocated a parcel.  Valid options/values are:

        * 
          side: whichside

               Specifies which side of the cavity to place the element;
               one of top, right, bottom or left.  If omitted, the
               element occupies the entire cavity.

        * 
          sticky: nswe

               Specifies where the element is placed inside its
               allocated parcel.

        * 
          unit: 0 or 1

               If set to 1, causes the element and all of its
               descendants to be treated as a single element for the
               purposes of *note Widget.identify(): 31ac. et al.  It’s
               used for things like scrollbar thumbs with grips.

        * 
          children: [sublayout... ]

               Specifies a list of elements to place inside the element.
               Each element is a tuple (or other sequence type) where
               the first item is the layout name, and the other is a
               *note Layout: 3201.


File: python.info,  Node: tkinter tix --- TK扩展包,  Next: tkinter scrolledtext --- 滚动文字控件,  Prev: tkinter ttk --- Tk主题小部件,  Up: Tk图形用户界面 GUI

5.25.3 ‘tkinter.tix’ — TK扩展包
-------------------------------

`源代码:' Lib/tkinter/tix.py(1)

3.6 版后已移除: 这个 TK 扩展已无人维护所以请不要在新代码中使用。 请改用
*note tkinter.ttk: 110.。

__________________________________________________________________

The *note tkinter.tix: 10f. (Tk Interface Extension) module provides an
additional rich set of widgets.  Although the standard Tk library has
many useful widgets, they are far from complete.  The *note tkinter.tix:
10f. library provides most of the commonly needed widgets that are
missing from standard Tk: *note HList: 320d, *note ComboBox: 320e, *note
Control: 320f. (a.k.a.  SpinBox) and an assortment of scrollable
widgets.  *note tkinter.tix: 10f. also includes many more widgets that
are generally useful in a wide range of applications: *note NoteBook:
3210, *note FileEntry: 3211, *note PanedWindow: 3212, etc; there are
more than 40 of them.

With all these new widgets, you can introduce new interaction techniques
into applications, creating more useful and more intuitive user
interfaces.  You can design your application by choosing the most
appropriate widgets to match the special needs of your application and
users.

参见
....

Tix Homepage(2)

     The home page for ‘Tix’.  This includes links to additional
     documentation and downloads.

Tix Man Pages(3)

     On-line version of the man pages and reference material.

Tix Programming Guide(4)

     On-line version of the programmer’s reference material.

Tix Development Applications(5)

     Tix applications for development of Tix and Tkinter programs.  Tide
     applications work under Tk or Tkinter, and include ‘TixInspect’, an
     inspector to remotely modify and debug Tix/Tk/Tkinter applications.

* Menu:

* Using Tix::
* Tix Widgets::
* Tix Commands::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/tkinter/tix.py

   (2) http://tix.sourceforge.net/

   (3) http://tix.sourceforge.net/dist/current/man/

   (4) 
http://tix.sourceforge.net/dist/current/docs/tix-book/tix.book.html

   (5) http://tix.sourceforge.net/Tixapps/src/Tide.html


File: python.info,  Node: Using Tix,  Next: Tix Widgets,  Up: tkinter tix --- TK扩展包

5.25.3.1 Using Tix
..................

 -- 类: tkinter.tix.Tk (screenName=None, baseName=None, className='Tix')

     Toplevel widget of Tix which represents mostly the main window of
     an application.  It has an associated Tcl interpreter.

     Classes in the *note tkinter.tix: 10f. module subclasses the
     classes in the *note tkinter: 10d.  The former imports the latter,
     so to use *note tkinter.tix: 10f. with Tkinter, all you need to do
     is to import one module.  In general, you can just import *note
     tkinter.tix: 10f, and replace the toplevel call to *note
     tkinter.Tk: 317f. with ‘tix.Tk’:

          from tkinter import tix
          from tkinter.constants import *
          root = tix.Tk()

To use *note tkinter.tix: 10f, you must have the Tix widgets installed,
usually alongside your installation of the Tk widgets.  To test your
installation, try the following:

     from tkinter import tix
     root = tix.Tk()
     root.tk.eval('package require Tix')


File: python.info,  Node: Tix Widgets,  Next: Tix Commands,  Prev: Using Tix,  Up: tkinter tix --- TK扩展包

5.25.3.2 Tix Widgets
....................

Tix(1) introduces over 40 widget classes to the *note tkinter: 10d.
repertoire.

* Menu:

* Basic Widgets::
* File Selectors::
* Hierarchical ListBox::
* Tabular ListBox::
* Manager Widgets::
* Image Types::
* Miscellaneous Widgets::
* Form Geometry Manager::

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/TixIntro.htm


File: python.info,  Node: Basic Widgets,  Next: File Selectors,  Up: Tix Widgets

5.25.3.3 Basic Widgets
......................

 -- 类: tkinter.tix.Balloon

     A Balloon(1) that pops up over a widget to provide help.  When the
     user moves the cursor inside a widget to which a Balloon widget has
     been bound, a small pop-up window with a descriptive message will
     be shown on the screen.

 -- 类: tkinter.tix.ButtonBox

     The ButtonBox(2) widget creates a box of buttons, such as is
     commonly used for ‘Ok Cancel’.

 -- 类: tkinter.tix.ComboBox

     The ComboBox(3) widget is similar to the combo box control in MS
     Windows.  The user can select a choice by either typing in the
     entry subwidget or selecting from the listbox subwidget.

 -- 类: tkinter.tix.Control

     The Control(4) 控件又名 ‘SpinBox’ 控件。 用户可通过点按两个方向键或
     直接输入内容来调整数值。 更新的数值将被检查是否在用户定义的上下限之
     内。

 -- 类: tkinter.tix.LabelEntry

     The LabelEntry(5) widget packages an entry widget and a label into
     one mega widget.  It can be used to simplify the creation of
     "entry-form" type of interface.

 -- 类: tkinter.tix.LabelFrame

     The LabelFrame(6) widget packages a frame widget and a label into
     one mega widget.  To create widgets inside a LabelFrame widget, one
     creates the new widgets relative to the ‘frame’ subwidget and
     manage them inside the ‘frame’ subwidget.

 -- 类: tkinter.tix.Meter

     The Meter(7) widget can be used to show the progress of a
     background job which may take a long time to execute.

 -- 类: tkinter.tix.OptionMenu

     The OptionMenu(8) creates a menu button of options.

 -- 类: tkinter.tix.PopupMenu

     The PopupMenu(9) widget can be used as a replacement of the
     ‘tk_popup’ command.  The advantage of the ‘Tix’ *note PopupMenu:
     321d. widget is it requires less application code to manipulate.

 -- 类: tkinter.tix.Select

     The Select(10) widget is a container of button subwidgets.  It can
     be used to provide radio-box or check-box style of selection
     options for the user.

 -- 类: tkinter.tix.StdButtonBox

     The StdButtonBox(11) widget is a group of standard buttons for
     Motif-like dialog boxes.

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixBalloon.htm

   (2) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixButtonBox.htm

   (3) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixComboBox.htm

   (4) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixControl.htm

   (5) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixLabelEntry.htm

   (6) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixLabelFrame.htm

   (7) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixMeter.htm

   (8) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixOptionMenu.htm

   (9) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixPopupMenu.htm

   (10) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixSelect.htm

   (11) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixStdButtonBox.htm


File: python.info,  Node: File Selectors,  Next: Hierarchical ListBox,  Prev: Basic Widgets,  Up: Tix Widgets

5.25.3.4 File Selectors
.......................

 -- 类: tkinter.tix.DirList

     The DirList(1) widget displays a list view of a directory, its
     previous directories and its sub-directories.  The user can choose
     one of the directories displayed in the list or change to another
     directory.

 -- 类: tkinter.tix.DirTree

     The DirTree(2) widget displays a tree view of a directory, its
     previous directories and its sub-directories.  The user can choose
     one of the directories displayed in the list or change to another
     directory.

 -- 类: tkinter.tix.DirSelectDialog

     The DirSelectDialog(3) widget presents the directories in the file
     system in a dialog window.  The user can use this dialog window to
     navigate through the file system to select the desired directory.

 -- 类: tkinter.tix.DirSelectBox

     The *note DirSelectBox: 3224. is similar to the standard Motif(TM)
     directory-selection box.  It is generally used for the user to
     choose a directory.  DirSelectBox stores the directories mostly
     recently selected into a ComboBox widget so that they can be
     quickly selected again.

 -- 类: tkinter.tix.ExFileSelectBox

     The ExFileSelectBox(4) widget is usually embedded in a
     tixExFileSelectDialog widget.  It provides a convenient method for
     the user to select files.  The style of the *note ExFileSelectBox:
     3225. widget is very similar to the standard file dialog on MS
     Windows 3.1.

 -- 类: tkinter.tix.FileSelectBox

     The FileSelectBox(5) is similar to the standard Motif(TM)
     file-selection box.  It is generally used for the user to choose a
     file.  FileSelectBox stores the files mostly recently selected into
     a *note ComboBox: 320e. widget so that they can be quickly selected
     again.

 -- 类: tkinter.tix.FileEntry

     The FileEntry(6) widget can be used to input a filename.  The user
     can type in the filename manually.  Alternatively, the user can
     press the button widget that sits next to the entry, which will
     bring up a file selection dialog.

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirList.htm

   (2) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirTree.htm

   (3) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirSelectDialog.htm

   (4) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixExFileSelectBox.htm

   (5) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixFileSelectBox.htm

   (6) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixFileEntry.htm


File: python.info,  Node: Hierarchical ListBox,  Next: Tabular ListBox,  Prev: File Selectors,  Up: Tix Widgets

5.25.3.5 Hierarchical ListBox
.............................

 -- 类: tkinter.tix.HList

     The HList(1) widget can be used to display any data that have a
     hierarchical structure, for example, file system directory trees.
     The list entries are indented and connected by branch lines
     according to their places in the hierarchy.

 -- 类: tkinter.tix.CheckList

     The CheckList(2) widget displays a list of items to be selected by
     the user.  CheckList acts similarly to the Tk checkbutton or
     radiobutton widgets, except it is capable of handling many more
     items than checkbuttons or radiobuttons.

 -- 类: tkinter.tix.Tree

     The Tree(3) widget can be used to display hierarchical data in a
     tree form.  The user can adjust the view of the tree by opening or
     closing parts of the tree.

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixHList.htm

   (2) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixCheckList.htm

   (3) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixTree.htm


File: python.info,  Node: Tabular ListBox,  Next: Manager Widgets,  Prev: Hierarchical ListBox,  Up: Tix Widgets

5.25.3.6 Tabular ListBox
........................

 -- 类: tkinter.tix.TList

     The TList(1) widget can be used to display data in a tabular
     format.  The list entries of a *note TList: 322b. widget are
     similar to the entries in the Tk listbox widget.  The main
     differences are (1) the *note TList: 322b. widget can display the
     list entries in a two dimensional format and (2) you can use
     graphical images as well as multiple colors and fonts for the list
     entries.

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixTList.htm


File: python.info,  Node: Manager Widgets,  Next: Image Types,  Prev: Tabular ListBox,  Up: Tix Widgets

5.25.3.7 Manager Widgets
........................

 -- 类: tkinter.tix.PanedWindow

     The PanedWindow(1) widget allows the user to interactively
     manipulate the sizes of several panes.  The panes can be arranged
     either vertically or horizontally.  The user changes the sizes of
     the panes by dragging the resize handle between two panes.

 -- 类: tkinter.tix.ListNoteBook

     The ListNoteBook(2) widget is very similar to the ‘TixNoteBook’
     widget: it can be used to display many windows in a limited space
     using a notebook metaphor.  The notebook is divided into a stack of
     pages (windows).  At one time only one of these pages can be shown.
     The user can navigate through these pages by choosing the name of
     the desired page in the ‘hlist’ subwidget.

 -- 类: tkinter.tix.NoteBook

     The NoteBook(3) widget can be used to display many windows in a
     limited space using a notebook metaphor.  The notebook is divided
     into a stack of pages.  At one time only one of these pages can be
     shown.  The user can navigate through these pages by choosing the
     visual "tabs" at the top of the NoteBook widget.

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixPanedWindow.htm

   (2) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixListNoteBook.htm

   (3) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixNoteBook.htm


File: python.info,  Node: Image Types,  Next: Miscellaneous Widgets,  Prev: Manager Widgets,  Up: Tix Widgets

5.25.3.8 Image Types
....................

The *note tkinter.tix: 10f. module adds:

   * pixmap(1) capabilities to all *note tkinter.tix: 10f. and *note
     tkinter: 10d. widgets to create color images from XPM files.

   * Compound(2) image types can be used to create images that consists
     of multiple horizontal lines; each line is composed of a series of
     items (texts, bitmaps, images or spaces) arranged from left to
     right.  For example, a compound image can be used to display a
     bitmap and a text string simultaneously in a Tk ‘Button’ widget.

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/pixmap.htm

   (2) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/compound.htm


File: python.info,  Node: Miscellaneous Widgets,  Next: Form Geometry Manager,  Prev: Image Types,  Up: Tix Widgets

5.25.3.9 Miscellaneous Widgets
..............................

 -- 类: tkinter.tix.InputOnly

     The InputOnly(1) widgets are to accept inputs from the user, which
     can be done with the ‘bind’ command (Unix only).

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixInputOnly.htm


File: python.info,  Node: Form Geometry Manager,  Prev: Miscellaneous Widgets,  Up: Tix Widgets

5.25.3.10 Form Geometry Manager
...............................

In addition, *note tkinter.tix: 10f. augments *note tkinter: 10d. by
providing:

 -- 类: tkinter.tix.Form

     The Form(1) geometry manager based on attachment rules for all Tk
     widgets.

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixForm.htm


File: python.info,  Node: Tix Commands,  Prev: Tix Widgets,  Up: tkinter tix --- TK扩展包

5.25.3.11 Tix Commands
......................

 -- 类: tkinter.tix.tixCommand

     The tix commands(1) provide access to miscellaneous elements of
     ‘Tix’’s internal state and the ‘Tix’ application context.  Most of
     the information manipulated by these methods pertains to the
     application as a whole, or to a screen or display, rather than to a
     particular window.

     To view the current settings, the common usage is:

          from tkinter import tix
          root = tix.Tk()
          print(root.tix_configure())

 -- 方法: tixCommand.tix_configure (cnf=None, **kw)

     Query or modify the configuration options of the Tix application
     context.  If no option is specified, returns a dictionary all of
     the available options.  If option is specified with no value, then
     the method returns a list describing the one named option (this
     list will be identical to the corresponding sublist of the value
     returned if no option is specified).  If one or more option-value
     pairs are specified, then the method modifies the given option(s)
     to have the given value(s); in this case the method returns an
     empty string.  Option may be any of the configuration options.

 -- 方法: tixCommand.tix_cget (option)

     Returns the current value of the configuration option given by
     `option'.  Option may be any of the configuration options.

 -- 方法: tixCommand.tix_getbitmap (name)

     Locates a bitmap file of the name ‘name.xpm’ or ‘name’ in one of
     the bitmap directories (see the *note tix_addbitmapdir(): 3238.
     method).  By using *note tix_getbitmap(): 3237, you can avoid hard
     coding the pathnames of the bitmap files in your application.  When
     successful, it returns the complete pathname of the bitmap file,
     prefixed with the character ‘@’.  The returned value can be used to
     configure the ‘bitmap’ option of the Tk and Tix widgets.

 -- 方法: tixCommand.tix_addbitmapdir (directory)

     Tix maintains a list of directories under which the *note
     tix_getimage(): 3239. and *note tix_getbitmap(): 3237. methods will
     search for image files.  The standard bitmap directory is
     ‘$TIX_LIBRARY/bitmaps’.  The *note tix_addbitmapdir(): 3238. method
     adds `directory' into this list.  By using this method, the image
     files of an applications can also be located using the *note
     tix_getimage(): 3239. or *note tix_getbitmap(): 3237. method.

 -- 方法: tixCommand.tix_filedialog ([dlgclass])

     Returns the file selection dialog that may be shared among
     different calls from this application.  This method will create a
     file selection dialog widget when it is called the first time.
     This dialog will be returned by all subsequent calls to *note
     tix_filedialog(): 323a.  An optional dlgclass parameter can be
     passed as a string to specified what type of file selection dialog
     widget is desired.  Possible options are ‘tix’, ‘FileSelectDialog’
     or ‘tixExFileSelectDialog’.

 -- 方法: tixCommand.tix_getimage (self, name)

     Locates an image file of the name ‘name.xpm’, ‘name.xbm’ or
     ‘name.ppm’ in one of the bitmap directories (see the *note
     tix_addbitmapdir(): 3238. method above).  If more than one file
     with the same name (but different extensions) exist, then the image
     type is chosen according to the depth of the X display: xbm images
     are chosen on monochrome displays and color images are chosen on
     color displays.  By using *note tix_getimage(): 3239, you can avoid
     hard coding the pathnames of the image files in your application.
     When successful, this method returns the name of the newly created
     image, which can be used to configure the ‘image’ option of the Tk
     and Tix widgets.

 -- 方法: tixCommand.tix_option_get (name)

     Gets the options maintained by the Tix scheme mechanism.

 -- 方法: tixCommand.tix_resetoptions (newScheme, newFontSet[,
          newScmPrio])

     Resets the scheme and fontset of the Tix application to `newScheme'
     and `newFontSet', respectively.  This affects only those widgets
     created after this call.  Therefore, it is best to call the
     resetoptions method before the creation of any widgets in a Tix
     application.

     The optional parameter `newScmPrio' can be given to reset the
     priority level of the Tk options set by the Tix schemes.

     Because of the way Tk handles the X option database, after Tix has
     been has imported and inited, it is not possible to reset the color
     schemes and font sets using the ‘tix_config()’ method.  Instead,
     the *note tix_resetoptions(): 323c. method must be used.

   ---------- Footnotes ----------

   (1) http://tix.sourceforge.net/dist/current/man/html/TixCmd/tix.htm


File: python.info,  Node: tkinter scrolledtext --- 滚动文字控件,  Next: IDLE<54>,  Prev: tkinter tix --- TK扩展包,  Up: Tk图形用户界面 GUI

5.25.4 ‘tkinter.scrolledtext’ — 滚动文字控件
--------------------------------------------

`源代码：' Lib/tkinter/scrolledtext.py(1)

__________________________________________________________________

*note tkinter.scrolledtext: 10e. 模块提供一个同名的类，实现了一个带有垂
直滚动条的文字控件。使用 ‘ScrolledText’ 类会比直接配置一个文本控件和滚动
条简单。它的构造函数与 ‘tkinter.Text’ 类相同。

文本控件与滚动条打包在一个 ‘Frame’ 中， ‘Grid’ 方法和 ‘Pack’ 方法的布局
管理器从 ‘Frame’ 对象中获得。这允许 ‘ScrolledText’ 控件可以直接用于实现
大多数正常的布局管理行为。

如果需要更具体的控制，可以使用以下属性：

 -- 属性: ScrolledText.frame

     围绕文本和滚动条控件的框架。

 -- 属性: ScrolledText.vbar

     滚动条控件。

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/tkinter/scrolledtext.py


File: python.info,  Node: IDLE<54>,  Next: 其他图形用户界面（GUI）包,  Prev: tkinter scrolledtext --- 滚动文字控件,  Up: Tk图形用户界面 GUI

5.25.5 IDLE
-----------

`源代码：' Lib/idlelib/(1)

__________________________________________________________________

IDLE 是 Python 所内置的开发与学习环境。

IDLE 具有以下特性：

   * 编码于 100% 纯正的 Python，使用名为 *note tkinter: 10d. 的图形用户
     界面工具

   * 跨平台：在 Windows、Unix 和 macOS 上工作近似。

   * 提供输入输出高亮和错误信息的 Python 命令行窗口 （交互解释器）

   * 提供多次撤销操作、Python 语法高亮、智能缩进、函数调用提示、自动补全
     等功能的多窗口文本编辑器

   * 在多个窗口中检索，在编辑器中替换文本，以及在多个文件中检索（通过
     grep）

   * 提供持久保存的断点调试、单步调试、查看本地和全局命名空间功能的调试
     器

   * 配置、浏览以及其它对话框

* Menu:

* 目录::
* 编辑和导航::
* 启动和代码执行::
* 帮助和偏好::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/idlelib/


File: python.info,  Node: 目录,  Next: 编辑和导航,  Up: IDLE<54>

5.25.5.1 目录
.............

IDEL 具有两个主要窗口类型，分别是命令行窗口和编辑器窗口。用户可以同时打
开多个编辑器窗口。对于 Windows 和 Linux 平台，都有各自的主菜单。如下记录
的每个菜单标识着与之关联的窗口类型。

导出窗口，例如使用 编辑=>在文件中查找 是编辑器窗口的的一个子类型。它们目
前有着相同的主菜单，但是默认标题和上下文菜单不同。

在macOS上，只有一个应用程序菜单。它根据当前选择的窗口动态变化。它具有一
个IDLE菜单，并且下面描述的某些条目已移动到符合Apple准则的位置。

* Menu:

* 文件菜单 （命令行和编辑器）::
* 编辑菜单（命令行和编辑器）::
* 格式菜单（仅 window 编辑器）::
* 运行菜单（仅 window 编辑器）::
* Shell 菜单（仅 window 编辑器）::
* 调试菜单（仅 window 编辑器）::
* 选项菜单（命令行和编辑器）::
* Window 菜单（命令行和编辑器）::
* 帮助菜单（命令行和编辑器）::
* 上下文菜单::


File: python.info,  Node: 文件菜单 （命令行和编辑器）,  Next: 编辑菜单（命令行和编辑器）,  Up: 目录

5.25.5.2 文件菜单 （命令行和编辑器）
....................................

新建文件

     创建一个文件编辑器窗口。

打开...

     使用打开窗口以打开一个已存在的文件。

近期文件

     打开一个近期文件列表，选取一个以打开它。

打开模块...

     打开一个已存在的模块 （搜索 sys.path）

类浏览器

     于当前所编辑的文件中使用树形结构展示函数、类以及方法。在命令行中，
     首先打开一个模块。

路径浏览

     在树状结构中展示 sys.path 目录、模块、函数、类和方法。

保存

     如果文件已经存在，则将当前窗口保存至对应的文件。自打开或上次保存之
     后经过修改的文件的窗口标题栏首尾将出现星号 * 。如果没有对应的文件，
     则使用“另存为”代替。

保存为...

     使用“保存为”对话框保存当前窗口。被保存的文件将作为当前窗口新的对应
     文件。

另存为副本...

     保存当前窗口至另一个文件，而不修改当前对应文件。

打印窗口

     通过默认打印机打印当前窗口。

关闭

     关闭当前窗口（如果未保存则询问）。

退出

     关闭所有窗口并退出 IDLE（如果未保存则询问）


File: python.info,  Node: 编辑菜单（命令行和编辑器）,  Next: 格式菜单（仅 window 编辑器）,  Prev: 文件菜单 （命令行和编辑器）,  Up: 目录

5.25.5.3 编辑菜单（命令行和编辑器）
...................................

撤销操作

     撤销当前窗口的最近一次操作。最高可以撤回 1000 条操作记录。

重做

     重做当前窗口最近一次所撤销的操作。

剪切

     复制选区至系统剪贴板，然后删除选区。

复制

     复制选区至系统剪贴板。

粘贴

     插入系统剪贴板的内容至当前窗口。

剪贴板功能也可用于上下文目录。

全选

     选择当前窗口的全部内容。

查找...

     打开一个提供多选项的查找窗口。

再次查找

     重复上次搜索，如果结果存在。

查找选区

     查找当前选中的字符串，如果存在

在文件中查找...

     打开文件查找对话框。将结果输出至新的输出窗口。

替换...

     打开 查找并替换 对话框。

前往行

     Move the cursor to the beginning of the line requested and make
     that line visible.  A request past the end of the file goes to the
     end.  Clear any selection and update the line and column status.

提示完成

     Open a scrollable list allowing selection of existing names.  See
     *note Completions: 3246. in the Editing and navigation section
     below.

展开文本

     展开键入的前缀以匹配同一窗口中的完整单词；重复以获得不同的扩展。

显示调用贴士

     在函数的右括号后，打开一个带有函数参数提示的小窗口。请参阅下面的“编
     辑和导航”部分中的 *note Calltips: 3247. 。

显示周围括号

     突出显示周围的括号。


File: python.info,  Node: 格式菜单（仅 window 编辑器）,  Next: 运行菜单（仅 window 编辑器）,  Prev: 编辑菜单（命令行和编辑器）,  Up: 目录

5.25.5.4 格式菜单（仅 window 编辑器）
.....................................

增加缩进

     将选定的行右移缩进宽度（默认为4个空格）。

减少缩进

     将选定的行向左移动缩进宽度（默认为4个空格）。

注释

     在所选行的前面插入 ##。

取消注释

     从所选行中删除开头的 ＃ 或 ##。

制表符化

     将 `前导' 空格变成制表符。 （注意：我们建议使用4个空格来缩进
     Python代码。）

取消制表符化

     将 `所有' 制表符转换为正确的空格数。

缩进方式切换

     打开一个对话框，以在制表符和空格之间切换。

缩进宽度调整

     打开一个对话框以更改缩进宽度。 Python社区接受的默认值为4个空格。

格式段落

     在注释块或多行字符串或字符串中的选定行中，重新格式化当前以空行分隔
     的段落。段落中的所有行的格式都将少于N列，其中N默认为72。

删除尾随空格

     通过将 str.rstrip 应用于每行（包括多行字符串中的行），删除行尾非空
     白字符之后的尾随空格和其他空白字符。除Shell窗口外，在文件末尾删除多
     余的换行符。


File: python.info,  Node: 运行菜单（仅 window 编辑器）,  Next: Shell 菜单（仅 window 编辑器）,  Prev: 格式菜单（仅 window 编辑器）,  Up: 目录

5.25.5.5 运行菜单（仅 window 编辑器）
.....................................

运行模块

     执行 *note 检查模块: 324c. 。如果没有错误，重新启动 shell 以清理环
     境，然后执行模块。输出显示在 shell 窗口中。请注意，输出需要使用 “打
     印” 或 “写入”。执行完成后，Shell 将保留焦点并显示提示。此时，可以交
     互地探索执行的结果。这类似于在命令行执行带有 ‘python -i file’ 的文
     件。

运行... 定制

     与 *note 运行模块: 324b. 相同，但使用自定义设置运行该模块。`命令行
     参数' 扩展 *note sys.argv: c03. ，就像在命令行上传递一样。该模块可
     以在命令行管理程序中运行，而无需重新启动。

检查模块

     检查 “编辑器” 窗口中当前打开的模块的语法。如果尚未保存该模块，则
     IDLE会提示用户保存或自动保存，如在 “空闲设置” 对话框的 “常规” 选项
     卡中所选择的那样。如果存在语法错误，则会在 “编辑器” 窗口中指示大概
     位置。

Python Shell

     打开或唤醒Python Shell窗口。


File: python.info,  Node: Shell 菜单（仅 window 编辑器）,  Next: 调试菜单（仅 window 编辑器）,  Prev: 运行菜单（仅 window 编辑器）,  Up: 目录

5.25.5.6 Shell 菜单（仅 window 编辑器）
.......................................

查看最近重启

     将Shell窗口滚动到上一次Shell重启。

重启Shell

     重启 shell 以清理环境，重置显示和异常处理。

上一条历史记录

     循环浏览历史记录中与当前条目匹配的早期命令。

下一条历史记录

     循环浏览历史记录中与当前条目匹配的后续命令。

中断执行

     停止正在运行的程序。


File: python.info,  Node: 调试菜单（仅 window 编辑器）,  Next: 选项菜单（命令行和编辑器）,  Prev: Shell 菜单（仅 window 编辑器）,  Up: 目录

5.25.5.7 调试菜单（仅 window 编辑器）
.....................................

跳转到文件/行

     Look on the current line.  with the cursor, and the line above for
     a filename and line number.  If found, open the file if not already
     open, and show the line.  Use this to view source lines referenced
     in an exception traceback and lines found by Find in Files.  Also
     available in the context menu of the Shell window and Output
     windows.

调试器（切换）

     激活后，在Shell中输入的代码或从编辑器中运行的代码将在调试器下运行。
     在编辑器中，可以使用上下文菜单设置断点。此功能不完整，具有实验性。

堆栈查看器

     在树状目录中显示最后一个异常的堆栈回溯，可以访问本地和全局。

自动打开堆栈查看器

     在未处理的异常上切换自动打开堆栈查看器。


File: python.info,  Node: 选项菜单（命令行和编辑器）,  Next: Window 菜单（命令行和编辑器）,  Prev: 调试菜单（仅 window 编辑器）,  Up: 目录

5.25.5.8 选项菜单（命令行和编辑器）
...................................

配置 IDLE

     打开配置对话框并更改以下各项的首选项：字体、缩进、键绑定、文本颜色
     主题、启动窗口和大小、其他帮助源和扩展名。在MacOS上，通过在应用程序
     菜单中选择首选项来打开配置对话框。有关详细信息，请参阅：帮助和首选
     项下的 *note 首选项设置: 3252.。

大多数配置选项适用于所有窗口或将来的所有窗口。以下选项仅适用于活动窗口。

显示/隐藏代码上下文（仅 window 编辑器）

     Open a pane at the top of the edit window which shows the block
     context of the code which has scrolled above the top of the window.
     See *note Code Context: 3253. in the Editing and Navigation section
     below.

显示/隐藏行号（仅 window 编辑器）

     Open a column to the left of the edit window which shows the number
     of each line of text.  The default is off, which may be changed in
     the preferences (see *note Setting preferences: 3252.).

缩放/还原高度

     Toggles the window between normal size and maximum height.  The
     initial size defaults to 40 lines by 80 chars unless changed on the
     General tab of the Configure IDLE dialog.  The maximum height for a
     screen is determined by momentarily maximizing a window the first
     time one is zoomed on the screen.  Changing screen settings may
     invalidate the saved height.  This toggle has no effect when a
     window is maximized.


File: python.info,  Node: Window 菜单（命令行和编辑器）,  Next: 帮助菜单（命令行和编辑器）,  Prev: 选项菜单（命令行和编辑器）,  Up: 目录

5.25.5.9 Window 菜单（命令行和编辑器）
......................................

列出所有打开的窗口的名称；选择一个将其带到前台（必要时对其进行去符号化）
。


File: python.info,  Node: 帮助菜单（命令行和编辑器）,  Next: 上下文菜单,  Prev: Window 菜单（命令行和编辑器）,  Up: 目录

5.25.5.10 帮助菜单（命令行和编辑器）
....................................

关于 IDLE

     显示版本，版权，许可证，荣誉等。

IDLE 帮助

     显示此 IDLE 文档，详细介绍菜单选项，基本编辑和导航以及其他技巧。

Python 文档

     访问本地Python文档（如果已安装），或启动Web浏览器并打开
     docs.python.org显示最新的Python文档。

海龟演示

     使用示例Python代码和turtle绘图运行turtledemo模块。

可以在“常规”选项卡下的“配置IDLE”对话框中添加其他帮助源。有关“帮助”菜单选
项的更多信息，请参见下面的 *note 帮助源: 3256. 小节。


File: python.info,  Node: 上下文菜单,  Prev: 帮助菜单（命令行和编辑器）,  Up: 目录

5.25.5.11 上下文菜单
....................

Open a context menu by right-clicking in a window (Control-click on
macOS). Context menus have the standard clipboard functions also on the
Edit menu.

剪切

     复制选区至系统剪贴板，然后删除选区。

复制

     复制选区至系统剪贴板。

粘贴

     插入系统剪贴板的内容至当前窗口。

Editor windows also have breakpoint functions.  Lines with a breakpoint
set are specially marked.  Breakpoints only have an effect when running
under the debugger.  Breakpoints for a file are saved in the user’s
‘.idlerc’ directory.

设置断点

     在当前行设置断点

清除断点

     清除当前行断点

shell 和输出窗口还具有以下内容。

跳转到文件/行

     与调试菜单相同。

The Shell window also has an output squeezing facility explained in the
`Python Shell window' subsection below.

压缩

     If the cursor is over an output line, squeeze all the output
     between the code above and the prompt below down to a ’Squeezed
     text’ label.


File: python.info,  Node: 编辑和导航,  Next: 启动和代码执行,  Prev: 目录,  Up: IDLE<54>

5.25.5.12 编辑和导航
....................

* Menu:

* 编辑窗口::
* 按键绑定::
* 自动缩进::
* 完成::
* 提示::
* 代码上下文::
* Python Shell 窗口::
* 文本颜色::


File: python.info,  Node: 编辑窗口,  Next: 按键绑定,  Up: 编辑和导航

5.25.5.13 编辑窗口
..................

IDLE may open editor windows when it starts, depending on settings and
how you start IDLE. Thereafter, use the File menu.  There can be only
one open editor window for a given file.

The title bar contains the name of the file, the full path, and the
version of Python and IDLE running the window.  The status bar contains
the line number (’Ln’) and column number (’Col’).  Line numbers start
with 1; column numbers with 0.

IDLE assumes that files with a known .py* extension contain Python code
and that other files do not.  Run Python code with the Run menu.


File: python.info,  Node: 按键绑定,  Next: 自动缩进,  Prev: 编辑窗口,  Up: 编辑和导航

5.25.5.14 按键绑定
..................

在本节中，’C’ 是指 Windows 和 Unix 上的 ‘Control’ 键，以及 macOS 上的
‘Command’ 键。

   * ‘Backspace’ 向左删除; ‘Del’ 向右删除

   * ‘C-Backspace’ 向左删除单词; ‘C-Del’ 向右删除单词

   * 方向键和 ‘Page Up’/‘Page Down’ 移动

   * ‘C-LeftArrow’ 和 ‘C-RightArrow’ 按单词移动

   * ‘Home’/‘End’ 跳转到行首/尾

   * ‘C-Home’/‘C-End’ 跳转到文档首/尾

   * 一些有用的Emacs绑定是从Tcl / Tk继承的：

             * ‘C-a’ 行首

             * ‘C-e’ 行尾

             * ‘C-k’ 删除行（但未将其放入剪贴板）

             * ‘C-l’ center window around the insertion point

             * ‘C-b’ go backward one character without deleting (usually
               you can also use the cursor key for this)

             * ‘C-f’ go forward one character without deleting (usually
               you can also use the cursor key for this)

             * ‘C-p’ go up one line (usually you can also use the cursor
               key for this)

             * ‘C-d’ 删除下一个字符

Standard keybindings (like ‘C-c’ to copy and ‘C-v’ to paste) may work.
Keybindings are selected in the Configure IDLE dialog.


File: python.info,  Node: 自动缩进,  Next: 完成,  Prev: 按键绑定,  Up: 编辑和导航

5.25.5.15 自动缩进
..................

After a block-opening statement, the next line is indented by 4 spaces
(in the Python Shell window by one tab).  After certain keywords (break,
return etc.)  the next line is dedented.  In leading indentation,
‘Backspace’ deletes up to 4 spaces if they are there.  ‘Tab’ inserts
spaces (in the Python Shell window one tab), number depends on Indent
width.  Currently, tabs are restricted to four spaces due to Tcl/Tk
limitations.

See also the indent/dedent region commands on the *note Format menu:
3248.


File: python.info,  Node: 完成,  Next: 提示,  Prev: 自动缩进,  Up: 编辑和导航

5.25.5.16 完成
..............

Completions are supplied, when requested and available, for module
names, attributes of classes or functions, or filenames.  Each request
method displays a completion box with existing names.  (See tab
completions below for an exception.)  For any box, change the name being
completed and the item highlighted in the box by typing and deleting
characters; by hitting ‘Up’, ‘Down’, ‘PageUp’, ‘PageDown’, ‘Home’, and
‘End’ keys; and by a single click within the box.  Close the box with
‘Escape’, ‘Enter’, and double ‘Tab’ keys or clicks outside the box.  A
double click within the box selects and closes.

One way to open a box is to type a key character and wait for a
predefined interval.  This defaults to 2 seconds; customize it in the
settings dialog.  (To prevent auto popups, set the delay to a large
number of milliseconds, such as 100000000.)  For imported module names
or class or function attributes, type ’.’.  For filenames in the root
directory, type *note os.sep: 1c87. or *note os.altsep: 1c88.
immediately after an opening quote.  (On Windows, one can specify a
drive first.)  Move into subdirectories by typing a directory name and a
separator.

Instead of waiting, or after a box is closed, open a completion box
immediately with Show Completions on the Edit menu.  The default hot key
is ‘C-space’.  If one types a prefix for the desired name before opening
the box, the first match or near miss is made visible.  The result is
the same as if one enters a prefix after the box is displayed.  Show
Completions after a quote completes filenames in the current directory
instead of a root directory.

Hitting ‘Tab’ after a prefix usually has the same effect as Show
Completions.  (With no prefix, it indents.)  However, if there is only
one match to the prefix, that match is immediately added to the editor
text without opening a box.

Invoking ’Show Completions’, or hitting ‘Tab’ after a prefix, outside of
a string and without a preceding ’.’ opens a box with keywords, builtin
names, and available module-level names.

When editing code in an editor (as oppose to Shell), increase the
available module-level names by running your code and not restarting the
Shell thereafter.  This is especially useful after adding imports at the
top of a file.  This also increases possible attribute completions.

Completion boxes intially exclude names beginning with ’_’ or, for
modules, not included in ’__all__’.  The hidden names can be accessed by
typing ’_’ after ’.’, either before or after the box is opened.


File: python.info,  Node: 提示,  Next: 代码上下文,  Prev: 完成,  Up: 编辑和导航

5.25.5.17 提示
..............

A calltip is shown automatically when one types ‘(’ after the name of an
`accessible' function.  A function name expression may include dots and
subscripts.  A calltip remains until it is clicked, the cursor is moved
out of the argument area, or ‘)’ is typed.  Whenever the cursor is in
the argument part of a definition, select Edit and "Show Call Tip" on
the menu or enter its shortcut to display a calltip.

The calltip consists of the function’s signature and docstring up to the
latter’s first blank line or the fifth non-blank line.  (Some builtin
functions lack an accessible signature.)  A ’/’ or ’*’ in the signature
indicates that the preceding or following arguments are passed by
position or name (keyword) only.  Details are subject to change.

In Shell, the accessible functions depends on what modules have been
imported into the user process, including those imported by Idle itself,
and which definitions have been run, all since the last restart.

For example, restart the Shell and enter ‘itertools.count(’.  A calltip
appears because Idle imports itertools into the user process for its own
use.  (This could change.)  Enter ‘turtle.write(’ and nothing appears.
Idle does not itself import turtle.  The menu entry and shortcut also do
nothing.  Enter ‘import turtle’.  Thereafter, ‘turtle.write(’ will
display a calltip.

In an editor, import statements have no effect until one runs the file.
One might want to run a file after writing import statements, after
adding function definitions, or after opening an existing file.


File: python.info,  Node: 代码上下文,  Next: Python Shell 窗口,  Prev: 提示,  Up: 编辑和导航

5.25.5.18 代码上下文
....................

Within an editor window containing Python code, code context can be
toggled in order to show or hide a pane at the top of the window.  When
shown, this pane freezes the opening lines for block code, such as those
beginning with ‘class’, ‘def’, or ‘if’ keywords, that would have
otherwise scrolled out of view.  The size of the pane will be expanded
and contracted as needed to show the all current levels of context, up
to the maximum number of lines defined in the Configure IDLE dialog
(which defaults to 15).  If there are no current context lines and the
feature is toggled on, a single blank line will display.  Clicking on a
line in the context pane will move that line to the top of the editor.

The text and background colors for the context pane can be configured
under the Highlights tab in the Configure IDLE dialog.


File: python.info,  Node: Python Shell 窗口,  Next: 文本颜色,  Prev: 代码上下文,  Up: 编辑和导航

5.25.5.19 Python Shell 窗口
...........................

With IDLE’s Shell, one enters, edits, and recalls complete statements.
Most consoles and terminals only work with a single physical line at a
time.

When one pastes code into Shell, it is not compiled and possibly
executed until one hits ‘Return’.  One may edit pasted code first.  If
one pastes more that one statement into Shell, the result will be a
*note SyntaxError: 460. when multiple statements are compiled as if they
were one.

The editing features described in previous subsections work when
entering code interactively.  IDLE’s Shell window also responds to the
following keys.

   * ‘C-c’ 中断执行命令

   * ‘C-d’ sends end-of-file; closes window if typed at a ‘>>>’ prompt

   * ‘Alt-/’ (Expand word) is also useful to reduce typing

     历史命令

        * ‘Alt-p’ retrieves previous command matching what you have
          typed.  On macOS use ‘C-p’.

        * ‘Alt-n’ retrieves next.  On macOS use ‘C-n’.

        * ‘Return’ while on any previous command retrieves that command


File: python.info,  Node: 文本颜色,  Prev: Python Shell 窗口,  Up: 编辑和导航

5.25.5.20 文本颜色
..................

Idle defaults to black on white text, but colors text with special
meanings.  For the shell, these are shell output, shell error, user
output, and user error.  For Python code, at the shell prompt or in an
editor, these are keywords, builtin class and function names, names
following ‘class’ and ‘def’, strings, and comments.  For any text
window, these are the cursor (when present), found text (when possible),
and selected text.

Text coloring is done in the background, so uncolorized text is
occasionally visible.  To change the color scheme, use the Configure
IDLE dialog Highlighting tab.  The marking of debugger breakpoint lines
in the editor and text in popups and dialogs is not user-configurable.


File: python.info,  Node: 启动和代码执行,  Next: 帮助和偏好,  Prev: 编辑和导航,  Up: IDLE<54>

5.25.5.21 启动和代码执行
........................

Upon startup with the ‘-s’ option, IDLE will execute the file referenced
by the environment variables ‘IDLESTARTUP’ or *note PYTHONSTARTUP: 8ed.
IDLE first checks for ‘IDLESTARTUP’; if ‘IDLESTARTUP’ is present the
file referenced is run.  If ‘IDLESTARTUP’ is not present, IDLE checks
for ‘PYTHONSTARTUP’.  Files referenced by these environment variables
are convenient places to store functions that are used frequently from
the IDLE shell, or for executing import statements to import common
modules.

In addition, ‘Tk’ also loads a startup file if it is present.  Note that
the Tk file is loaded unconditionally.  This additional file is
‘.Idle.py’ and is looked for in the user’s home directory.  Statements
in this file will be executed in the Tk namespace, so this file is not
useful for importing functions to be used from IDLE’s Python shell.

* Menu:

* 命令行语法::
* 启动失败::
* 运行用户代码::
* Shell中的用户输出::
* 开发 tkinter 应用程序::
* 在没有子进程的情况下运行::


File: python.info,  Node: 命令行语法,  Next: 启动失败,  Up: 启动和代码执行

5.25.5.22 命令行语法
....................

     idle.py [-c command] [-d] [-e] [-h] [-i] [-r file] [-s] [-t title] [-] [arg] ...

     -c command  run command in the shell window
     -d          enable debugger and open shell window
     -e          open editor window
     -h          print help message with legal combinations and exit
     -i          open shell window
     -r file     run file in shell window
     -s          run $IDLESTARTUP or $PYTHONSTARTUP first, in shell window
     -t title    set title of shell window
     -           run stdin in shell (- must be last option before args)

如果有参数：

   * If ‘-’, ‘-c’, or ‘r’ is used, all arguments are placed in
     ‘sys.argv[1:...]’ and ‘sys.argv[0]’ is set to ‘''’, ‘'-c'’, or
     ‘'-r'’.  No editor window is opened, even if that is the default
     set in the Options dialog.

   * Otherwise, arguments are files opened for editing and ‘sys.argv’
     reflects the arguments passed to IDLE itself.


File: python.info,  Node: 启动失败,  Next: 运行用户代码,  Prev: 命令行语法,  Up: 启动和代码执行

5.25.5.23 启动失败
..................

IDLE uses a socket to communicate between the IDLE GUI process and the
user code execution process.  A connection must be established whenever
the Shell starts or restarts.  (The latter is indicated by a divider
line that says ’RESTART’).  If the user process fails to connect to the
GUI process, it usually displays a ‘Tk’ error box with a ’cannot
connect’ message that directs the user here.  It then exits.

One specific connection failure on Unix systems results from
misconfigured masquerading rules somewhere in a system’s network setup.
When IDLE is started from a terminal, one will see a message starting
with ‘** Invalid host:’.  The valid value is ‘127.0.0.1
(idlelib.rpc.LOCALHOST)’.  One can diagnose with ‘tcpconnect -irv
127.0.0.1 6543’ in one terminal window and ‘tcplisten <same args>’ in
another.

A common cause of failure is a user-written file with the same name as a
standard library module, such as `random.py' and `tkinter.py'.  When
such a file is located in the same directory as a file that is about to
be run, IDLE cannot import the stdlib file.  The current fix is to
rename the user file.

Though less common than in the past, an antivirus or firewall program
may stop the connection.  If the program cannot be taught to allow the
connection, then it must be turned off for IDLE to work.  It is safe to
allow this internal connection because no data is visible on external
ports.  A similar problem is a network mis-configuration that blocks
connections.

Python installation issues occasionally stop IDLE: multiple versions can
clash, or a single installation might need admin access.  If one undo
the clash, or cannot or does not want to run as admin, it might be
easiest to completely remove Python and start over.

A zombie pythonw.exe process could be a problem.  On Windows, use Task
Manager to check for one and stop it if there is.  Sometimes a restart
initiated by a program crash or Keyboard Interrupt (control-C) may fail
to connect.  Dismissing the error box or using Restart Shell on the
Shell menu may fix a temporary problem.

When IDLE first starts, it attempts to read user configuration files in
‘~/.idlerc/’ (~ is one’s home directory).  If there is a problem, an
error message should be displayed.  Leaving aside random disk glitches,
this can be prevented by never editing the files by hand.  Instead, use
the configuration dialog, under Options.  Once there is an error in a
user configuration file, the best solution may be to delete it and start
over with the settings dialog.

If IDLE quits with no message, and it was not started from a console,
try starting it from a console or terminal (‘python -m idlelib’) and see
if this results in an error message.

On Unix-based systems with tcl/tk older than ‘8.6.11’ (see ‘About IDLE’)
certain characters of certain fonts can cause a tk failure with a
message to the terminal.  This can happen either if one starts IDLE to
edit a file with such a character or later when entering such a
character.  If one cannot upgrade tcl/tk, then re-configure IDLE to use
a font that works better.


File: python.info,  Node: 运行用户代码,  Next: Shell中的用户输出,  Prev: 启动失败,  Up: 启动和代码执行

5.25.5.24 运行用户代码
......................

With rare exceptions, the result of executing Python code with IDLE is
intended to be the same as executing the same code by the default
method, directly with Python in a text-mode system console or terminal
window.  However, the different interface and operation occasionally
affect visible results.  For instance, ‘sys.modules’ starts with more
entries, and ‘threading.active_count()’ returns 2 instead of 1.

By default, IDLE runs user code in a separate OS process rather than in
the user interface process that runs the shell and editor.  In the
execution process, it replaces ‘sys.stdin’, ‘sys.stdout’, and
‘sys.stderr’ with objects that get input from and send output to the
Shell window.  The original values stored in ‘sys.__stdin__’,
‘sys.__stdout__’, and ‘sys.__stderr__’ are not touched, but may be
‘None’.

Sending print output from one process to a text widget in another is
slower than printing to a system terminal in the same process.  This has
the most effect when printing multiple arguments, as the string for each
argument, each separator, the newline are sent separately.  For
development, this is usually not a problem, but if one wants to print
faster in IDLE, format and join together everything one wants displayed
together and then print a single string.  Both format strings and *note
str.join(): 1642. can help combine fields and lines.

IDLE’s standard stream replacements are not inherited by subprocesses
created in the execution process, whether directly by user code or by
modules such as multiprocessing.  If such subprocess use ‘input’ from
sys.stdin or ‘print’ or ‘write’ to sys.stdout or sys.stderr, IDLE should
be started in a command line window.  The secondary subprocess will then
be attached to that window for input and output.

If ‘sys’ is reset by user code, such as with ‘importlib.reload(sys)’,
IDLE’s changes are lost and input from the keyboard and output to the
screen will not work correctly.

When Shell has the focus, it controls the keyboard and screen.  This is
normally transparent, but functions that directly access the keyboard
and screen will not work.  These include system-specific functions that
determine whether a key has been pressed and if so, which.

The IDLE code running in the execution process adds frames to the call
stack that would not be there otherwise.  IDLE wraps
‘sys.getrecursionlimit’ and ‘sys.setrecursionlimit’ to reduce the effect
of the additional stack frames.

When user code raises SystemExit either directly or by calling sys.exit,
IDLE returns to a Shell prompt instead of exiting.


File: python.info,  Node: Shell中的用户输出,  Next: 开发 tkinter 应用程序,  Prev: 运行用户代码,  Up: 启动和代码执行

5.25.5.25 Shell中的用户输出
...........................

When a program outputs text, the result is determined by the
corresponding output device.  When IDLE executes user code, ‘sys.stdout’
and ‘sys.stderr’ are connected to the display area of IDLE’s Shell.
Some of its features are inherited from the underlying Tk Text widget.
Others are programmed additions.  Where it matters, Shell is designed
for development rather than production runs.

For instance, Shell never throws away output.  A program that sends
unlimited output to Shell will eventually fill memory, resulting in a
memory error.  In contrast, some system text windows only keep the last
n lines of output.  A Windows console, for instance, keeps a
user-settable 1 to 9999 lines, with 300 the default.

A Tk Text widget, and hence IDLE’s Shell, displays characters
(codepoints) in the BMP (Basic Multilingual Plane) subset of Unicode.
Which characters are displayed with a proper glyph and which with a
replacement box depends on the operating system and installed fonts.
Tab characters cause the following text to begin after the next tab
stop.  (They occur every 8 ’characters’).  Newline characters cause
following text to appear on a new line.  Other control characters are
ignored or displayed as a space, box, or something else, depending on
the operating system and font.  (Moving the text cursor through such
output with arrow keys may exhibit some surprising spacing behavior.)

     >>> s = 'a\tb\a<\x02><\r>\bc\nd'  # Enter 22 chars.
     >>> len(s)
     14
     >>> s  # Display repr(s)
     'a\tb\x07<\x02><\r>\x08c\nd'
     >>> print(s, end='')  # Display s as is.
     # Result varies by OS and font.  Try it.

The ‘repr’ function is used for interactive echo of expression values.
It returns an altered version of the input string in which control
codes, some BMP codepoints, and all non-BMP codepoints are replaced with
escape codes.  As demonstrated above, it allows one to identify the
characters in a string, regardless of how they are displayed.

Normal and error output are generally kept separate (on separate lines)
from code input and each other.  They each get different highlight
colors.

For SyntaxError tracebacks, the normal ’^’ marking where the error was
detected is replaced by coloring the text with an error highlight.  When
code run from a file causes other exceptions, one may right click on a
traceback line to jump to the corresponding line in an IDLE editor.  The
file will be opened if necessary.

Shell has a special facility for squeezing output lines down to a
’Squeezed text’ label.  This is done automatically for output over N
lines (N = 50 by default).  N can be changed in the PyShell section of
the General page of the Settings dialog.  Output with fewer lines can be
squeezed by right clicking on the output.  This can be useful lines long
enough to slow down scrolling.

Squeezed output is expanded in place by double-clicking the label.  It
can also be sent to the clipboard or a separate view window by
right-clicking the label.


File: python.info,  Node: 开发 tkinter 应用程序,  Next: 在没有子进程的情况下运行,  Prev: Shell中的用户输出,  Up: 启动和代码执行

5.25.5.26 开发 tkinter 应用程序
...............................

IDLE is intentionally different from standard Python in order to
facilitate development of tkinter programs.  Enter ‘import tkinter as
tk; root = tk.Tk()’ in standard Python and nothing appears.  Enter the
same in IDLE and a tk window appears.  In standard Python, one must also
enter ‘root.update()’ to see the window.  IDLE does the equivalent in
the background, about 20 times a second, which is about every 50
milliseconds.  Next enter ‘b = tk.Button(root, text='button');
b.pack()’.  Again, nothing visibly changes in standard Python until one
enters ‘root.update()’.

Most tkinter programs run ‘root.mainloop()’, which usually does not
return until the tk app is destroyed.  If the program is run with
‘python -i’ or from an IDLE editor, a ‘>>>’ shell prompt does not appear
until ‘mainloop()’ returns, at which time there is nothing left to
interact with.

When running a tkinter program from an IDLE editor, one can comment out
the mainloop call.  One then gets a shell prompt immediately and can
interact with the live application.  One just has to remember to
re-enable the mainloop call when running in standard Python.


File: python.info,  Node: 在没有子进程的情况下运行,  Prev: 开发 tkinter 应用程序,  Up: 启动和代码执行

5.25.5.27 在没有子进程的情况下运行
..................................

By default, IDLE executes user code in a separate subprocess via a
socket, which uses the internal loopback interface.  This connection is
not externally visible and no data is sent to or received from the
Internet.  If firewall software complains anyway, you can ignore it.

If the attempt to make the socket connection fails, Idle will notify
you.  Such failures are sometimes transient, but if persistent, the
problem may be either a firewall blocking the connection or
misconfiguration of a particular system.  Until the problem is fixed,
one can run Idle with the -n command line switch.

If IDLE is started with the -n command line switch it will run in a
single process and will not create the subprocess which runs the RPC
Python execution server.  This can be useful if Python cannot create the
subprocess or the RPC socket interface on your platform.  However, in
this mode user code is not isolated from IDLE itself.  Also, the
environment is not restarted when Run/Run Module (F5) is selected.  If
your code has been modified, you must reload() the affected modules and
re-import any specific items (e.g.  from foo import baz) if the changes
are to take effect.  For these reasons, it is preferable to run IDLE
with the default subprocess if at all possible.

3.4 版后已移除.


File: python.info,  Node: 帮助和偏好,  Prev: 启动和代码执行,  Up: IDLE<54>

5.25.5.28 帮助和偏好
....................

* Menu:

* 帮助源::
* 首选项设置::
* macOS 上的IDLE::
* 扩展::


File: python.info,  Node: 帮助源,  Next: 首选项设置,  Up: 帮助和偏好

5.25.5.29 帮助源
................

Help menu entry "IDLE Help" displays a formatted html version of the
IDLE chapter of the Library Reference.  The result, in a read-only
tkinter text window, is close to what one sees in a web browser.
Navigate through the text with a mousewheel, the scrollbar, or up and
down arrow keys held down.  Or click the TOC (Table of Contents) button
and select a section header in the opened box.

Help menu entry "Python Docs" opens the extensive sources of help,
including tutorials, available at ‘docs.python.org/x.y’, where ’x.y’ is
the currently running Python version.  If your system has an off-line
copy of the docs (this may be an installation option), that will be
opened instead.

Selected URLs can be added or removed from the help menu at any time
using the General tab of the Configure IDLE dialog.


File: python.info,  Node: 首选项设置,  Next: macOS 上的IDLE,  Prev: 帮助源,  Up: 帮助和偏好

5.25.5.30 首选项设置
....................

The font preferences, highlighting, keys, and general preferences can be
changed via Configure IDLE on the Option menu.  Non-default user
settings are saved in a ‘.idlerc’ directory in the user’s home
directory.  Problems caused by bad user configuration files are solved
by editing or deleting one or more of the files in ‘.idlerc’.

On the Font tab, see the text sample for the effect of font face and
size on multiple characters in multiple languages.  Edit the sample to
add other characters of personal interest.  Use the sample to select
monospaced fonts.  If particular characters have problems in Shell or an
editor, add them to the top of the sample and try changing first size
and then font.

On the Highlights and Keys tab, select a built-in or custom color theme
and key set.  To use a newer built-in color theme or key set with older
IDLEs, save it as a new custom theme or key set and it well be
accessible to older IDLEs.


File: python.info,  Node: macOS 上的IDLE,  Next: 扩展,  Prev: 首选项设置,  Up: 帮助和偏好

5.25.5.31 macOS 上的IDLE
........................

Under System Preferences: Dock, one can set "Prefer tabs when opening
documents" to "Always".  This setting is not compatible with the
tk/tkinter GUI framework used by IDLE, and it breaks a few IDLE
features.


File: python.info,  Node: 扩展,  Prev: macOS 上的IDLE,  Up: 帮助和偏好

5.25.5.32 扩展
..............

IDLE contains an extension facility.  Preferences for extensions can be
changed with the Extensions tab of the preferences dialog.  See the
beginning of config-extensions.def in the idlelib directory for further
information.  The only current default extension is zzdummy, an example
also used for testing.


File: python.info,  Node: 其他图形用户界面（GUI）包,  Prev: IDLE<54>,  Up: Tk图形用户界面 GUI

5.25.6 其他图形用户界面（GUI）包
--------------------------------

Python 可用的主要跨平台（Windows，Mac OS X，类Unix）GUI 工具：

参见
....

PyGObject(1)

     PyGObject 使用 GObject(2) 提供针对 C 库的内省绑定。 GTK+ 3(3) 可视
     化部件集就是此类函数库中的一个。 GTK+ 附带的部件比 Tkinter 所提供的
     更多。 请在线参阅 Python GTK+ 3 教程(4)。

PyGTK(5)

     PyGTK 提供了对较旧版本的库 GTK+ 2 的绑定。 它使用面向对象接口，比 C
     库的抽象层级略高。 此外也有对 GNOME(6) 的绑定。 请参阅在线 教程
     (7)。

PyQt(8)

     PyQt 是一个针对 Qt 工具集通过 ‘sip’ 包装的绑定。 Qt 是一个庞大的
     C++ GUI 应用开发框架，同时适用于 Unix, Windows 和 Mac OS X。 ‘sip’
     是一个用于为 C++ 库生成 Python 类绑定的库，它是针对 Python 特别设计
     的。

PySide2(9)

     或称为 Qt for Python 项目，PySide2 是一个较新的针对 Qt 工具集的绑定
     。 它由 The Qt Company 发布，旨在提供一个完整的用于 Qt 5 的 PySide
     移植版。 与 PyQt 相比，它的许可方案对非开源应用更为友好。

wxPython(10)

     wxPython 是一个针对 Python 的跨平台 GUI 工具集，它基于热门的
     wxWidgets(11) (原名 wxWindows) C++ 工具集进行构建。 它为 Windows,
     Mac OS X 和 Unix 系统上的应用提供了原生的外观效果，在可能的情况下尽
     量使用各平台的原生可视化部件。 （在类 Unix 系统上使用 GTK+）。 除了
     包含庞大的可视化部件集，wxPython 还提供了许多类用于在线文档和上下文
     感知帮助、打印、HTML 视图、低层级设备上下文绘图、拖放操作、系统剪贴
     板访问、基于 XML 的资源格式等等，并且包含一个不断增长的用户贡献模块
     库。

PyGTK, PyQt, PySide2 和 wxPython 都拥有比 Tkinter 更现代的外观效果和更多
的可视化部件。 此外还存在许多其他适用于 Python 的 GUI 工具集，即有跨平台
的，也有特定平台专属的。 请参阅 Python Wiki 中的 GUI 编程(12) 页面查看更
完整的列表，以及不同 GUI 工具集对比文档的链接。

   ---------- Footnotes ----------

   (1) https://wiki.gnome.org/Projects/PyGObject

   (2) https://developer.gnome.org/gobject/stable/

   (3) https://www.gtk.org/

   (4) https://python-gtk-3-tutorial.readthedocs.io/

   (5) http://www.pygtk.org/

   (6) https://www.gnome.org/

   (7) http://www.pygtk.org/pygtk2tutorial/index.html

   (8) https://riverbankcomputing.com/software/pyqt/intro

   (9) https://doc.qt.io/qtforpython/

   (10) https://www.wxpython.org

   (11) https://www.wxwidgets.org/

   (12) https://wiki.python.org/moin/GuiProgramming


File: python.info,  Node: 开发工具,  Next: 调试和分析,  Prev: Tk图形用户界面 GUI,  Up: Python 标准库

5.26 开发工具
=============

本章中描述的各模块可帮你编写 Python 程序。例如，*note pydoc: da. 模块接
受一个模块并根据该模块的内容来生成文档。*note doctest: 67. 和 *note
unittest: 11c. 这两个模块包含了用于编写单元测试的框架，并可用于自动测试
所编写的代码，验证预期的输出是否产生。‘2to3’ 程序能够将 Python 2.x 源代
码翻译成有效的 Python 3.x 源代码。

本章中描述的模块列表是：

* Menu:

* typing: typing --- 类型标注支持. 类型标注支持
* pydoc: pydoc --- 文档生成器和在线帮助系统. 文档生成器和在线帮助系统
* doctest: doctest --- 测试交互性的Python示例. 测试交互性的Python示例
* unittest: unittest --- 单元测试框架. 单元测试框架
* unittest.mock: unittest mock --- 模拟对象库. 模拟对象库
* unittest.mock 上手指南: unittest mock 上手指南.
* 2to3 - 自动将 Python 2 代码转为 Python 3 代码::
* test: test --- Python回归测试包. Python回归测试包
* test.support: test support --- Utilities for the Python test suite. Utilities for the Python test suite
* test.support.script_helper: test support script_helper --- Utilities for the Python execution tests. Utilities for the Python execution tests


File: python.info,  Node: typing --- 类型标注支持,  Next: pydoc --- 文档生成器和在线帮助系统,  Up: 开发工具

5.26.1 ‘typing’ — 类型标注支持
------------------------------

3.5 新版功能.

`源码：' Lib/typing.py(1)

     注解: Python 运行时并不强制标注函数和变量类型。 类型标注可被用于第
     三方工具，比如类型检查器、集成开发环境、静态检查器等。

__________________________________________________________________

此模块为运行时提供了 PEP 484(2) 、 PEP 526(3) 、 PEP 544(4) 、 PEP
586(5) 、 PEP 589(6) 和 PEP 591(7) 规定的类型提示。最基本的支持由 *note
Any: 65b.，*note Union: 1044.，*note Tuple: 3275.，*note Callable:
3276.，*note TypeVar: f31. 和 *note Generic: 3277. 类型组成。有关完整的
规范，请参阅 PEP 484(8)。有关类型提示的简单介绍，请参阅 PEP 483(9)。

函数接受并返回一个字符串，注释像下面这样:

     def greeting(name: str) -> str:
         return 'Hello ' + name

在函数 ‘greeting’ 中，参数 ‘name’ 预期是 *note str: 339. 类型，并且返回
*note str: 339. 类型。子类型允许作为参数。

* Menu:

* 类型别名::
* NewType::
* Callable::
* 泛型(Generic): 泛型 Generic.
* 用户定义的泛型类型::
* Any 类型::
* 名义性子类型 区别于 结构性子类型::
* 类,函数和修饰器.: 类 函数和修饰器.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/typing.py

   (2) https://www.python.org/dev/peps/pep-0484

   (3) https://www.python.org/dev/peps/pep-0526

   (4) https://www.python.org/dev/peps/pep-0544

   (5) https://www.python.org/dev/peps/pep-0586

   (6) https://www.python.org/dev/peps/pep-0589

   (7) https://www.python.org/dev/peps/pep-0591

   (8) https://www.python.org/dev/peps/pep-0484

   (9) https://www.python.org/dev/peps/pep-0483


File: python.info,  Node: 类型别名,  Next: NewType,  Up: typing --- 类型标注支持

5.26.1.1 类型别名
.................

类型别名通过将类型分配给别名来定义。在这个例子中， ‘Vector’ 和
‘List[float]’ 将被视为可互换的同义词:

     from typing import List
     Vector = List[float]

     def scale(scalar: float, vector: Vector) -> Vector:
         return [scalar * num for num in vector]

     # typechecks; a list of floats qualifies as a Vector.
     new_vector = scale(2.0, [1.0, -4.2, 5.4])

类型别名可用于简化复杂类型签名。例如:

     from typing import Dict, Tuple, Sequence

     ConnectionOptions = Dict[str, str]
     Address = Tuple[str, int]
     Server = Tuple[Address, ConnectionOptions]

     def broadcast_message(message: str, servers: Sequence[Server]) -> None:
         ...

     # The static type checker will treat the previous type signature as
     # being exactly equivalent to this one.
     def broadcast_message(
             message: str,
             servers: Sequence[Tuple[Tuple[str, int], Dict[str, str]]]) -> None:
         ...

请注意，‘None’ 作为类型提示是一种特殊情况，并且由 ‘type(None)’ 取代。


File: python.info,  Node: NewType,  Next: Callable,  Prev: 类型别名,  Up: typing --- 类型标注支持

5.26.1.2 NewType
................

使用 *note NewType(): 5ae. 辅助函数创建不同的类型:

     from typing import NewType

     UserId = NewType('UserId', int)
     some_id = UserId(524313)

静态类型检查器会将新类型视为它是原始类型的子类。这对于帮助捕捉逻辑错误非
常有用:

     def get_user_name(user_id: UserId) -> str:
         ...

     # typechecks
     user_a = get_user_name(UserId(42351))

     # does not typecheck; an int is not a UserId
     user_b = get_user_name(-1)

您仍然可以对 ‘UserId’ 类型的变量执行所有的 ‘int’ 支持的操作，但结果将始
终为 ‘int’ 类型。这可以让你在需要 ‘int’ 的地方传入 ‘UserId’，但会阻止你
以无效的方式无意中创建 ‘UserId’:

     # 'output' is of type 'int', not 'UserId'
     output = UserId(23413) + UserId(54341)

请注意，这些检查仅通过静态类型检查程序来强制。在运行时，‘Derived =
NewType('Derived'，Base)’ 将 ‘Derived’ 一个函数，该函数立即返回您传递它
的任何参数。这意味着表达式 ‘Derived(some_value)’ 不会创建一个新的类或引
入任何超出常规函数调用的开销。

更确切地说，表达式 ‘some_value is Derived(some_value)’ 在运行时总是为真
。

这也意味着无法创建 ‘Derived’ 的子类型，因为它是运行时的标识函数，而不是
实际的类型:

     from typing import NewType

     UserId = NewType('UserId', int)

     # Fails at runtime and does not typecheck
     class AdminUserId(UserId): pass

但是，可以基于’derived’ ‘NewType’ 创建 *note NewType(): 5ae.

     from typing import NewType

     UserId = NewType('UserId', int)

     ProUserId = NewType('ProUserId', UserId)

并且 ‘ProUserId’ 的类型检查将按预期工作。

有关更多详细信息，请参阅 PEP 484(1)。

     注解: 回想一下，使用类型别名声明两种类型彼此 `等效' 。‘Alias =
     Original’ 将使静态类型检查对待所有情况下 ‘Alias’ `完全等同于'
     ‘Original’。当您想简化复杂类型签名时，这很有用。

     相反，‘NewType’ 声明一种类型是另一种类型的子类型。‘Derived =
     NewType('Derived', Original)’ 将使静态类型检查器将 ‘Derived’ 当作
     ‘Original’ 的 `子类' ，这意味着 ‘Original’ 类型的值不能用于
     ‘Derived’ 类型的值需要的地方。当您想以最小的运行时间成本防止逻辑错
     误时，这非常有用。

3.5.2 新版功能.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484


File: python.info,  Node: Callable,  Next: 泛型 Generic,  Prev: NewType,  Up: typing --- 类型标注支持

5.26.1.3 Callable
.................

期望特定签名的回调函数的框架可以将类型标注为 ‘Callable[[Arg1Type,
Arg2Type], ReturnType]’。

例如

     from typing import Callable

     def feeder(get_next_item: Callable[[], str]) -> None:
         # Body

     def async_query(on_success: Callable[[int], None],
                     on_error: Callable[[int, Exception], None]) -> None:
         # Body

通过用文字省略号替换类型提示中的参数列表： ‘Callable[...，ReturnType]’，
可以声明可调用的返回类型，而无需指定调用签名。


File: python.info,  Node: 泛型 Generic,  Next: 用户定义的泛型类型,  Prev: Callable,  Up: typing --- 类型标注支持

5.26.1.4 泛型(Generic)
......................

由于无法以通用方式静态推断有关保存在容器中的对象的类型信息，因此抽象基类
已扩展为支持订阅以表示容器元素的预期类型。

     from typing import Mapping, Sequence

     def notify_by_email(employees: Sequence[Employee],
                         overrides: Mapping[str, str]) -> None: ...

泛型可以通过使用typing模块中名为 *note TypeVar: f31. 的新工厂进行参数化
。

     from typing import Sequence, TypeVar

     T = TypeVar('T')      # Declare type variable

     def first(l: Sequence[T]) -> T:   # Generic function
         return l[0]


File: python.info,  Node: 用户定义的泛型类型,  Next: Any 类型,  Prev: 泛型 Generic,  Up: typing --- 类型标注支持

5.26.1.5 用户定义的泛型类型
...........................

用户定义的类可以定义为泛型类。

     from typing import TypeVar, Generic
     from logging import Logger

     T = TypeVar('T')

     class LoggedVar(Generic[T]):
         def __init__(self, value: T, name: str, logger: Logger) -> None:
             self.name = name
             self.logger = logger
             self.value = value

         def set(self, new: T) -> None:
             self.log('Set ' + repr(self.value))
             self.value = new

         def get(self) -> T:
             self.log('Get ' + repr(self.value))
             return self.value

         def log(self, message: str) -> None:
             self.logger.info('%s: %s', self.name, message)

‘Generic[T]’ 作为基类定义了类 ‘LoggedVar’ 采用单个类型参数 ‘T’。这也使得
‘T’ 作为类体内的一个类型有效。

*note Generic: 3277. 基类定义了 *note __class_getitem__(): 330. ，使得
‘LoggedVar[t]’ 作为类型有效：

     from typing import Iterable

     def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
         for var in vars:
             var.set(0)

泛型类型可以有任意数量的类型变量，并且类型变量可能会受到限制:

     from typing import TypeVar, Generic
     ...

     T = TypeVar('T')
     S = TypeVar('S', int, str)

     class StrangePair(Generic[T, S]):
         ...

*note Generic: 3277. 每个参数的类型变量必须是不同的。这是无效的:

     from typing import TypeVar, Generic
     ...

     T = TypeVar('T')

     class Pair(Generic[T, T]):   # INVALID
         ...

您可以对 *note Generic: 3277. 使用多重继承:

     from typing import TypeVar, Generic, Sized

     T = TypeVar('T')

     class LinkedList(Sized, Generic[T]):
         ...

从泛型类继承时，某些类型变量可能是固定的:

     from typing import TypeVar, Mapping

     T = TypeVar('T')

     class MyDict(Mapping[str, T]):
         ...

在这种情况下，‘MyDict’ 只有一个参数，‘T’。

在不指定类型参数的情况下使用泛型类别会为每个位置假设 *note Any: 65b.。在
下面的例子中，‘MyIterable’ 不是泛型，但是隐式继承自 ‘Iterable[Any]’:

     from typing import Iterable

     class MyIterable(Iterable): # Same as Iterable[Any]

用户定义的通用类型别名也受支持。例子:

     from typing import TypeVar, Iterable, Tuple, Union
     S = TypeVar('S')
     Response = Union[Iterable[S], int]

     # Return type here is same as Union[Iterable[str], int]
     def response(query: str) -> Response[str]:
         ...

     T = TypeVar('T', int, float, complex)
     Vec = Iterable[Tuple[T, T]]

     def inproduct(v: Vec[T]) -> T: # Same as Iterable[Tuple[T, T]]
         return sum(x*y for x, y in v)

在 3.7 版更改: *note Generic: 3277. 不再拥有一个自定义的元类。

一个用户定义的泛型类能够使用抽象基本类作为基类，而不会发生元类冲突。泛型
元类不再被支持。参数化泛型的结果会被缓存，并且在 typing 模块中的大部分类
型是可哈希且可比较相等性的。


File: python.info,  Node: Any 类型,  Next: 名义性子类型 区别于 结构性子类型,  Prev: 用户定义的泛型类型,  Up: typing --- 类型标注支持

5.26.1.6 ‘Any’ 类型
...................

*note Any: 65b. 是一种特殊的类型。静态类型检查器将所有类型视为与 *note
Any: 65b. 兼容，反之亦然， *note Any: 65b. 也与所有类型相兼容。

这意味着可对类型为 *note Any: 65b. 的值执行任何操作或者方法调用并将其赋
值给任意变量:

     from typing import Any

     a = None    # type: Any
     a = []      # OK
     a = 2       # OK

     s = ''      # type: str
     s = a       # OK

     def foo(item: Any) -> int:
         # Typechecks; 'item' could be any type,
         # and that type might have a 'bar' method
         item.bar()
         ...

需要注意的是，将 *note Any: 65b. 类型的值赋值给另一个更具体的类型时，
Python不会执行类型检查。例如，当把 ‘a’ 赋值给 ‘s’ 时，即使 ‘s’ 被声明为
*note str: 339. 类型，在运行时接收到的是 *note int: 185. 值，静态类型检
查器也不会报错。

此外，所有返回值无类型或形参无类型的函数将隐式地默认使用 *note Any: 65b.
类型:

     def legacy_parser(text):
         ...
         return data

     # A static type checker will treat the above
     # as having the same signature as:
     def legacy_parser(text: Any) -> Any:
         ...
         return data

当需要混用动态类型和静态类型的代码时，上述行为可以让 *note Any: 65b. 被
用作 `应急出口' 。

*note Any: 65b. 和 *note object: 2b1. 的行为对比。与 *note Any: 65b. 相
似，所有的类型都是 *note object: 2b1. 的子类型。然而不同于 *note Any:
65b.，反之并不成立： *note object: 2b1. `不是' 其他所有类型的子类型。

这意味着当一个值的类型是 *note object: 2b1. 的时候，类型检查器会拒绝对它
的几乎所有的操作。把它赋值给一个指定了类型的变量（或者当作返回值）是一个
类型错误。比如说：

     def hash_a(item: object) -> int:
         # Fails; an object does not have a 'magic' method.
         item.magic()
         ...

     def hash_b(item: Any) -> int:
         # Typechecks
         item.magic()
         ...

     # Typechecks, since ints and strs are subclasses of object
     hash_a(42)
     hash_a("foo")

     # Typechecks, since Any is compatible with all types
     hash_b(42)
     hash_b("foo")

使用 *note object: 2b1. 示意一个值可以类型安全地兼容任何类型。使用 *note
Any: 65b. 示意一个值地类型是动态定义的。


File: python.info,  Node: 名义性子类型 区别于 结构性子类型,  Next: 类 函数和修饰器,  Prev: Any 类型,  Up: typing --- 类型标注支持

5.26.1.7 名义性子类型 区别于 结构性子类型
.........................................

最初 PEP 484(1) 将 Python 的静态类型系统定义为使用 `名义性子类型'。即是
说，当且仅当 ‘A’ 是 ‘B’ 的子类时，可在需要 ‘B’ 类时提供 ‘A’ 类。

这一要求之前也适用于抽象基类，比如 *note Iterable: 1962. 。这一做法的问
题在于，一个类必须显式地标注为支持他们，这即不 Pythonic，也不太可能在惯
用动态类型的 Python 代码中会有人正常地去用。举例来说，这符合 PEP 484(2)：

     from typing import Sized, Iterable, Iterator

     class Bucket(Sized, Iterable[int]):
         ...
         def __len__(self) -> int: ...
         def __iter__(self) -> Iterator[int]: ...

PEP 544(3) 通过允许用户不必在类定义中显式地标注基类来解决这一问题，允许
静态类型检查器隐含地认为 ‘Bucket’ 既是 ‘Sized’ 的子类型又是
‘Iterable[int]’ 的子类型。这被称为 `结构性子类型' （或者静态鸭子类型）：

     from typing import Iterator, Iterable

     class Bucket:  # Note: no base classes
         ...
         def __len__(self) -> int: ...
         def __iter__(self) -> Iterator[int]: ...

     def collect(items: Iterable[int]) -> int: ...
     result = collect(Bucket())  # Passes type check

此外，通过继承一个特殊的类 *note Protocol: 240. ，用户能够定义新的自定义
协议来充分享受结构化子类型（见下例）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0484

   (3) https://www.python.org/dev/peps/pep-0544


File: python.info,  Node: 类 函数和修饰器,  Prev: 名义性子类型 区别于 结构性子类型,  Up: typing --- 类型标注支持

5.26.1.8 类,函数和修饰器.
.........................

这个模块定义了如下的类,模块和修饰器.

 -- 类: typing.TypeVar

     类型变量

     用法:

          T = TypeVar('T')  # Can be anything
          A = TypeVar('A', str, bytes)  # Must be str or bytes

     Type variables exist primarily for the benefit of static type
     checkers.  They serve as the parameters for generic types as well
     as for generic function definitions.  See class Generic for more
     information on generic types.  Generic functions work as follows:

          def repeat(x: T, n: int) -> Sequence[T]:
              """Return a list containing n references to x."""
              return [x]*n

          def longest(x: A, y: A) -> A:
              """Return the longest of two strings."""
              return x if len(x) >= len(y) else y

     本质上，后例的签名重载了 ‘(str, str) -> str’ 与 ‘(bytes, bytes) ->
     bytes’。注意，参数是 *note str: 339. 子类的实例时，返回类型仍是纯
     *note str: 339.。

     ‘isinstance(x, T)’ 会在运行时抛出 *note TypeError: 193. 异常。一般
     地说， *note isinstance(): 457. 和 *note issubclass(): 458. 不应该
     和类型一起使用。

     通过 ‘covariant=True’ 或 ‘contravariant=True’ 可以把类型变量标记为
     协变量或逆变量。详见 PEP 484(1)。默认情况下，类型变量是不变量。类型
     变量还可以用 ‘bound=<type>’ 指定上限。这里的意思是，（显式或隐式地
     ）取代类型变量的实际类型必须是限定类型的子类，详见 PEP 484(2)。

 -- 类: typing.Generic

     用于泛型类型的抽象基类。

     泛型类型一般通过继承含一个或多个类型变量的类实例进行声明。例如，泛
     型映射类型定义如下：

          class Mapping(Generic[KT, VT]):
              def __getitem__(self, key: KT) -> VT:
                  ...
                  # Etc.

     这个类之后可以被这样用:

          X = TypeVar('X')
          Y = TypeVar('Y')

          def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y:
              try:
                  return mapping[key]
              except KeyError:
                  return default

 -- 类: typing.Protocol (Generic)

     Protocol 类的基类。Protocol 类的定义如下：

          class Proto(Protocol):
              def meth(self) -> int:
                  ...

     这些类主要与静态类型检查器搭配使用，用来识别结构子类型（静态鸭子类
     型），例如：

          class C:
              def meth(self) -> int:
                  return 0

          def func(x: Proto) -> int:
              return x.meth()

          func(C())  # Passes static type check

     详见 PEP 544(3)。Protocol 类用 *note runtime_checkable(): 241. （见
     下文）装饰，忽略类型签名，仅检查给定属性是否存在，充当简要的运行时
     协议。

     Protocol 类可以是泛型，例如：

          class GenProto(Protocol[T]):
              def meth(self) -> T:
                  ...

     3.8 新版功能.

 -- 类: typing.Type (Generic[CT_co])

     一个注解为 ‘C’ 的变量可以接受一个类型为 ‘C’ 的值。相对地，一个注解
     为 ‘Type[C]’ 的变量可以接受本身为类的值 —— 更精确地说它接受 ‘C’ 的
     `类对象' ，例如：

          a = 3         # Has type 'int'
          b = int       # Has type 'Type[int]'
          c = type(a)   # Also has type 'Type[int]'

     注意 ‘Type[C]’ 是协变的：

          class User: ...
          class BasicUser(User): ...
          class ProUser(User): ...
          class TeamUser(User): ...

          # Accepts User, BasicUser, ProUser, TeamUser, ...
          def make_new_user(user_class: Type[User]) -> User:
              # ...
              return user_class()

     ‘Type[C]’ 是协变的这一事实暗示了任何 ‘C’ 的子类应当实现与 ‘C’ 相同
     的构造器签名和类方法签名。类型检查器应当标记违反的情况，但应当也允
     许子类中调用构造器符合指示的基类。类型检查器被要求如何处理这种情况
     可能会在 PEP 484(4) 将来的版本中改变。

     *note Type: 3282. 合法的参数仅有类、 *note Any: 65b. 、*note
     类型变量: 327c. 以及上述类型的联合类型。例如：

          def new_non_team_user(user_class: Type[Union[BasicUser, ProUser]]): ...

     ‘Type[Any]’ 等价于 ‘Type’，因此继而等价于 ‘type’，它是 Python 的元
     类层级的根部。

     3.5.2 新版功能.

 -- 类: typing.Iterable (Generic[T_co])

     *note collections.abc.Iterable: 1962. 的泛型版本。

 -- 类: typing.Iterator (Iterable[T_co])

     *note collections.abc.Iterator: 1963. 的泛型版本。

 -- 类: typing.Reversible (Iterable[T_co])

     *note collections.abc.Reversible: 536. 的泛型版本。

 -- 类: typing.SupportsInt

     含抽象方法 ‘__int__’ 的抽象基类。

 -- 类: typing.SupportsFloat

     含抽象方法 ‘__float__’ 的抽象基类。

 -- 类: typing.SupportsComplex

     含抽象方法 ‘__complex__’ 的抽象基类。

 -- 类: typing.SupportsBytes

     含抽象方法 ‘__bytes__’ 的抽象基类（ABC）

 -- 类: typing.SupportsIndex

     含抽象方法 ‘__index__’ 的抽象基类。

     3.8 新版功能.

 -- 类: typing.SupportsAbs

     含抽象方法 ‘__abs__’ 的抽象基类（ABC）是其返回类型里的协变量。

 -- 类: typing.SupportsRound

     含抽象方法 ‘__round__’ 的抽象基类，是其返回类型的协变量。

 -- 类: typing.Container (Generic[T_co])

     *note collections.abc.Container: 1960. 的泛型版本。

 -- 类: typing.Hashable

     *note collections.abc.Hashable: 1961. 的别名。

 -- 类: typing.Sized

     *note collections.abc.Sized: 1964. 的别名。

 -- 类: typing.Collection (Sized, Iterable[T_co], Container[T_co])

     *note collections.abc.Collection: 535. 的泛型版本。

     3.6.0 新版功能.

 -- 类: typing.AbstractSet (Sized, Collection[T_co])

     *note collections.abc.Set: 16ea. 的泛型版本。

 -- 类: typing.MutableSet (AbstractSet[T])

     *note collections.abc.MutableSet: 1967. 的泛型版本。

 -- 类: typing.Mapping (Sized, Collection[KT], Generic[VT_co])

     *note collections.abc.Mapping: 1954. 的泛型版本。这个类型可以如下使
     用:

          def get_position_in_index(word_list: Mapping[str, int], word: str) -> int:
              return word_list[word]

 -- 类: typing.MutableMapping (Mapping[KT, VT])

     *note collections.abc.MutableMapping: 9f7. 的泛型版本。

 -- 类: typing.Sequence (Reversible[T_co], Collection[T_co])

     *note collections.abc.Sequence: 1640. 的泛型版本。

 -- 类: typing.MutableSequence (Sequence[T])

     *note collections.abc.MutableSequence: 6b5. 的泛型版本。

 -- 类: typing.ByteString (Sequence[int])

     *note collections.abc.ByteString: 1966. 的泛型版本。

     该类型代表了 *note bytes: 33a.、*note bytearray: 33b.、*note
     memoryview: 25d. 等字节序列类型。

     作为该类型的简称，*note bytes: 33a. 可用于标注上述任意类型的参数。

 -- 类: typing.Deque (deque, MutableSequence[T])

     *note collections.deque: 539. 的泛型版本。

     3.5.4 新版功能.

     3.6.1 新版功能.

 -- 类: typing.List (list, MutableSequence[T])

     *note list: 263. 的泛型版本。适用于注解返回类型。注解参数时，最好使
     用 *note Sequence: 3292. 或 *note Iterable: 3283. 等抽象容器类型。

     这个类型可以这样用:

          T = TypeVar('T', int, float)

          def vec2(x: T, y: T) -> List[T]:
              return [x, y]

          def keep_positives(vector: Sequence[T]) -> List[T]:
              return [item for item in vector if item > 0]

 -- 类: typing.Set (set, MutableSet[T])

     *note builtins.set: b77. 的泛型版本。适用于注解返回类型。注解参数时
     ，最好使用 *note AbstractSet: 328e. 等抽象容器类型。

 -- 类: typing.FrozenSet (frozenset, AbstractSet[T_co])

     *note builtins.frozenset: bf6. 的泛型版本。

 -- 类: typing.MappingView (Sized, Iterable[T_co])

     *note collections.abc.MappingView: 1968. 的泛型版本。

 -- 类: typing.KeysView (MappingView[KT_co], AbstractSet[KT_co])

     *note collections.abc.KeysView: 196a. 的泛型版本。

 -- 类: typing.ItemsView (MappingView, Generic[KT_co, VT_co])

     *note collections.abc.ItemsView: 1969. 的泛型版本。

 -- 类: typing.ValuesView (MappingView[VT_co])

     *note collections.abc.ValuesView: 196b. 的泛型版本。

 -- 类: typing.Awaitable (Generic[T_co])

     *note collections.abc.Awaitable: 6bf. 的泛型版本。

     3.5.2 新版功能.

 -- 类: typing.Coroutine (Awaitable[V_co], Generic[T_co, T_contra,
          V_co])

     *note collections.abc.Coroutine: 6c0. 的泛型版本。类型变量的的差异
     和顺序与 *note Generator: 329e. 的内容相对应，例如：

          from typing import List, Coroutine
          c = None # type: Coroutine[List[str], str, int]
          ...
          x = c.send('hi') # type: List[str]
          async def bar() -> None:
              x = await c # type: int

     3.5.3 新版功能.

 -- 类: typing.AsyncIterable (Generic[T_co])

     *note collections.abc.AsyncIterable: 6c2. 的泛型版本。

     3.5.2 新版功能.

 -- 类: typing.AsyncIterator (AsyncIterable[T_co])

     *note collections.abc.AsyncIterator: 6c1. 的泛型版本。

     3.5.2 新版功能.

 -- 类: typing.ContextManager (Generic[T_co])

     *note contextlib.AbstractContextManager: 53c. 的泛型版本。

     3.5.4 新版功能.

     3.6.0 新版功能.

 -- 类: typing.AsyncContextManager (Generic[T_co])

     *note contextlib.AbstractAsyncContextManager: 381. 的泛型版本。

     3.5.4 新版功能.

     3.6.2 新版功能.

 -- 类: typing.Dict (dict, MutableMapping[KT, VT])

     *note dict: 1b9. 的泛型版本。对标注返回类型比较有用。如果要标注参数
     的话，使用如 *note Mapping: 3290. 的抽象容器类型是更好的选择。

     这个类型可以这样使用:

          def count_words(text: str) -> Dict[str, int]:
              ...

 -- 类: typing.DefaultDict (collections.defaultdict, MutableMapping[KT,
          VT])

     *note collections.defaultdict: b42. 的泛型版本。

     3.5.2 新版功能.

 -- 类: typing.OrderedDict (collections.OrderedDict, MutableMapping[KT,
          VT])

     *note collections.OrderedDict: 1ba. 的泛型版本。

     3.7.2 新版功能.

 -- 类: typing.Counter (collections.Counter, Dict[T, int])

     *note collections.Counter: 9e2. 的泛型版本。

     3.5.4 新版功能.

     3.6.1 新版功能.

 -- 类: typing.ChainMap (collections.ChainMap, MutableMapping[KT, VT])

     *note collections.ChainMap: 4b1. 的泛型版本。

     3.5.4 新版功能.

     3.6.1 新版功能.

 -- 类: typing.Generator (Iterator[T_co], Generic[T_co, T_contra, V_co])

     生成器可以由泛型类型 ‘Generator[YieldType, SendType, ReturnType]’ 注
     解。例如：

          def echo_round() -> Generator[int, float, str]:
              sent = yield 0
              while sent >= 0:
                  sent = yield round(sent)
              return 'Done'

     注意，与 typing 模块里的其他泛型不同， *note Generator: 329e. 的
     ‘‘SendType‘‘ 的操作是逆变的， 不是协变，也是不变。

     如果生成器只生成值，可将 ‘SendType’ 与 ‘ReturnType’ 设为 ‘None’：

          def infinite_stream(start: int) -> Generator[int, None, None]:
              while True:
                  yield start
                  start += 1

     另外，把生成器注解为返回类型

          def infinite_stream(start: int) -> Iterator[int]:
              while True:
                  yield start
                  start += 1

 -- 类: typing.AsyncGenerator (AsyncIterator[T_co], Generic[T_co,
          T_contra])

     异步生成器可由泛型类型 ‘AsyncGenerator[YieldType, SendType]’ 注解。
     例如：

          async def echo_round() -> AsyncGenerator[int, float]:
              sent = yield 0
              while sent >= 0.0:
                  rounded = await round(sent)
                  sent = yield rounded

     与常规生成器不同，异步生成器不能返回值，因此没有 ‘ReturnType’ 类型
     参数。 与 *note Generator: 329e. 类似，‘SendType’ 也属于逆变行为。

     如果生成器只产生值，可将 ‘SendType’ 设置为 ‘None’：

          async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
              while True:
                  yield start
                  start = await increment(start)

     此外，可用 ‘AsyncIterable[YieldType]’ 或 ‘AsyncIterator[YieldType]’
     注解生成器的类型：

          async def infinite_stream(start: int) -> AsyncIterator[int]:
              while True:
                  yield start
                  start = await increment(start)

     3.6.1 新版功能.

 -- 类: typing.Text

     ‘Text’ 是 ‘str’ 的别名。提供了对 Python 2 代码的向下兼容：Python 2
     中，‘Text’ 是‘‘unicode‘‘ 的别名。

     用

          def add_unicode_checkmark(text: Text) -> Text:
              return text + u' \u2713'

     3.5.2 新版功能.

 -- 类: typing.IO
 -- 类: typing.TextIO
 -- 类: typing.BinaryIO

     泛型类型 ‘IO[AnyStr]’ 及其子类 ‘TextIO(IO[str])’ 与
     ‘BinaryIO(IO[bytes])’ 表示 I/O 流的类型，例如 *note open(): 4f8. 所
     返回的对象。

 -- 类: typing.Pattern
 -- 类: typing.Match

     这些类型对应的是从 *note re.compile(): 452. 和 *note re.match():
     bbb. 返回的类型。 这些类型（及相应的函数）是 ‘AnyStr’ 中的泛型并可
     通过编写 ‘Pattern[str]’, ‘Pattern[bytes]’, ‘Match[str]’ 或
     ‘Match[bytes]’ 来具体指定。

 -- 类: typing.NamedTuple

     *note collections.namedtuple(): 1b7. 的类型版本。

     用法:

          class Employee(NamedTuple):
              name: str
              id: int

     这相当于:

          Employee = collections.namedtuple('Employee', ['name', 'id'])

     为字段提供默认值，要在类体内赋值：

          class Employee(NamedTuple):
              name: str
              id: int = 3

          employee = Employee('Guido')
          assert employee.id == 3

     带默认值的字段必须在不带默认值的字段后面。

     生成的类具有 ‘__annotations__’ 这个附加属性，提供了映射字段名与字段
     类型的字典。（字段名在 ）

     ‘NamedTuple’ 子类也支持文档字符串与方法：

          class Employee(NamedTuple):
              """Represents an employee."""
              name: str
              id: int = 3

              def __repr__(self) -> str:
                  return f'<Employee {self.name}, id={self.id}>'

     反向兼容用法：

          Employee = NamedTuple('Employee', [('name', str), ('id', int)])

     在 3.6 版更改: 添加了对 PEP 526(5) 中变量注解句法的支持。

     在 3.6.1 版更改: 添加了对默认值、方法、文档字符串的支持。

     Deprecated since version 3.8, will be removed in version 3.9:
     Deprecated the ‘_field_types’ attribute in favor of the more
     standard ‘__annotations__’ attribute which has the same
     information.

     在 3.8 版更改: ‘_field_types’ 和 ‘__annotations__’ 属性现已使用常规
     字典，不再使用 ‘OrderedDict’ 实例。

 -- 类: typing.TypedDict (dict)

     A simple typed namespace.  At runtime it is equivalent to a plain
     *note dict: 1b9.

     ‘TypedDict’ creates a dictionary type that expects all of its
     instances to have a certain set of keys, where each key is
     associated with a value of a consistent type.  This expectation is
     not checked at runtime but is only enforced by type checkers.
     Usage:

          class Point2D(TypedDict):
              x: int
              y: int
              label: str

          a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
          b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check

          assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')

     用于内省的类型信息可通过 ‘Point2D.__annotations__’ 和
     ‘Point2D.__total__’ 访问。为了让不支持 PEP 526(6) 的老版 Python 也
     能使用此功能，‘TypedDict’ 支持两个附加的等价句法形式：

          Point2D = TypedDict('Point2D', x=int, y=int, label=str)
          Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})

     默认情况下，所有键都必须列在 TypedDict 里。不过，也可以通过指定
     total 参数进行重写。用法如下：

          class point2D(TypedDict, total=False):
              x: int
              y: int

     这段代码的意思是，可以省略 point2D 这个 TypedDict 中的任意键。类型
     核查器只支持字面量 False 或 True 作为 total 参数的值。True 是默认值
     ，表明在类体中，必须定义所有项目。

     更多示例与 ‘TypedDict’ 的详细规则，请参阅 PEP 589(7)。

     3.8 新版功能.

 -- 类: typing.ForwardRef

     用于字符串前向引用的内部类型表示的类。 例如，‘List["SomeClass"]’ 会
     被隐式转换为 ‘List[ForwardRef("SomeClass")]’。 这个类不应由用户来实
     例化，但可以由内省工具使用。

     3.7.4 新版功能.

 -- 函数: typing.NewType (name, tp)

     用于为类型核查器标明不同类型的辅助函数，参阅 *note NewType: 3279.。
     在运行时，用于返回一个函数，该函数返回它的参数。用法如下：

          UserId = NewType('UserId', int)
          first_user = UserId(1)

     3.5.2 新版功能.

 -- 函数: typing.cast (typ, val)

     把值强制转换为类型。

     不变更返回值。对类型检查器来说，这代表了返回值具有指定的类型，但在
     运行时，故意不做任何检查（目的是让该检查速度尽量快）。

 -- 函数: typing.get_type_hints (obj[, globals[, locals]])

     返回一个字典，字典内含有函数、方法、模块或类对象的类型提示。

     一般情况下，与 ‘obj.__annotations__’ 相同。此外，可通过在 ‘globals’
     与 ‘locals’ 命名空间里进行评估，以此来处理编码为字符串字面量的前向
     引用。如有需要，在默认值设置为 ‘None``时，可为函数或方法注解添加
     ``Optional[t]’。对于类 ‘C’，则返回一个由所有 ‘__annotations__’ 与
     ‘C.__mro__’ 逆序合并而成的字典。

 -- 函数: typing.get_origin (tp)

 -- 函数: typing.get_args (tp)

     为泛型类型与特殊类型形式提供了基本内省功能。

     For a typing object of the form ‘X[Y, Z, ...]’ these functions
     return ‘X’ and ‘(Y, Z, ...)’.  If ‘X’ is a generic alias for a
     builtin or *note collections: 1e. class, it gets normalized to the
     original class.  For unsupported objects return ‘None’ and ‘()’
     correspondingly.  Examples:

          assert get_origin(Dict[str, int]) is dict
          assert get_args(Dict[int, str]) == (int, str)

          assert get_origin(Union[int, str]) is Union
          assert get_args(Union[int, str]) == (int, str)

     3.8 新版功能.

 -- 函数: @typing.overload

     ‘@overload’ 装饰器可以修饰支持多个不同参数类型组合的函数或方法。
     ‘@overload’ - 装饰定义的系列必须紧跟一个非 ‘@overload’-装饰定义（用
     于同一个函数/方法）。‘@overload’-装饰定义仅是为了协助类型检查器， 因
     为该装饰器会被非 ‘@overload’-装饰定义覆盖，后者用于运行时，而且会被
     类型检查器忽略。在运行时直接调用 ‘@overload’ 装饰的函数会触发 *note
     NotImplementedError: 617.。下面的重载示例给出了比联合类型或类型变量
     更精准的类型：

          @overload
          def process(response: None) -> None:
              ...
          @overload
          def process(response: int) -> Tuple[int, str]:
              ...
          @overload
          def process(response: bytes) -> str:
              ...
          def process(response):
              <actual implementation>

     详见 PEP 484(8)，与其他类型语义进行对比。

 -- 函数: @typing.final

     告知类型检查器被装饰的方法不能被覆盖，且被装饰的类不能作为子类，例
     如：

          class Base:
              @final
              def done(self) -> None:
                  ...
          class Sub(Base):
              def done(self) -> None:  # Error reported by type checker
                    ...

          @final
          class Leaf:
              ...
          class Other(Leaf):  # Error reported by type checker
              ...

     这些属性没有运行时检查。详情请参阅 PEP 591(9)。

     3.8 新版功能.

 -- 函数: @typing.no_type_check

     用于指明标注不是类型提示的装饰器。

     此 *note decorator: 284. 装饰器生效于类或函数上。如果作用于类上的话
     ，它会递归地作用于这个类的所定义的所有方法上（但是对于超类或子类所
     定义的方法不会生效）。

     此方法会就地地修改函数。

 -- 函数: @typing.no_type_check_decorator

     使其它装饰器起到 *note no_type_check(): 32b1. 效果的装饰器。

     本装饰器用 *note no_type_check(): 32b1. 里的装饰函数打包其他装饰器
     。

 -- 函数: @typing.type_check_only

     标记一个类或函数在运行时内不可用的装饰器。

     在运行时，该装饰器本身不可用。实现返回了私有类实例时，它主要是用于
     标记在类型存根文件中定义的类。

          @type_check_only
          class Response:  # private or not available at runtime
              code: int
              def get_header(self, name: str) -> str: ...

          def fetch_response() -> Response: ...

     注意，不建议返回私有类的实例，最好将这些类设为公共类。

 -- 函数: @typing.runtime_checkable

     把 Protocol 类 标记为运行时协议。

     该协议可以与 *note isinstance(): 457. 和 *note issubclass(): 458. 一
     起使用。应用于非协议的类时，会触发 *note TypeError: 193.。该指令支
     持简易结构核查，与 *note collections.abc: 1f. 的 *note Iterable:
     1962. 非常类似，只擅长做一件事。 例如：

          @runtime_checkable
          class Closable(Protocol):
              def close(self): ...

          assert isinstance(open('/some/file'), Closable)

     `警告:' 这将只检查所需方法是否存在，而不检查其类型签名！

     3.8 新版功能.

 -- 数据: typing.Any

     特殊类型，表明类型没有任何限制。

        * 每一个类型都对 *note Any: 65b. 兼容。

        * *note Any: 65b. 对每一个类型都兼容。

 -- 数据: typing.NoReturn

     标记一个函数没有返回值的特殊类型。比如说:

          from typing import NoReturn

          def stop() -> NoReturn:
              raise RuntimeError('no way')

     3.5.4 新版功能.

     3.6.2 新版功能.

 -- 数据: typing.Union

     联合类型； ‘Union[X, Y]’ 意味着：要不是 X，要不是 Y。

     使用形如 ‘Union[int, str]’ 的形式来定义一个联合类型。细节如下:

        * 参数必须是类型，而且必须至少有一个参数。

        * 联合类型的联合类型会被展开打平，比如:

               Union[Union[int, str], float] == Union[int, str, float]

        * 仅有一个参数的联合类型会坍缩成参数自身，比如:

               Union[int] == int  # The constructor actually returns int

        * 多余的参数会被跳过，比如:

               Union[int, str, int] == Union[int, str]

        * 在比较联合类型的时候，参数顺序会被忽略，比如:

               Union[int, str] == Union[str, int]

        * 你不能继承或者实例化一个联合类型。

        * 你不能写成 ‘Union[X][Y]’ 。

        * 你可以使用 ‘Optional[X]’ 作为 ‘Union[X, None]’ 的缩写。

     在 3.7 版更改: 不要在运行时内从联合类型中移除显式说明的子类。

 -- 数据: typing.Optional

     可选类型。

     ‘Optional[X]’ 等价于 ‘Union[X, None]’ 。

     请注意，这与可选参数并非相同的概念。可选参数是一个具有默认值的参数
     。可选参数的类型注解并不因为它是可选的就需要 ‘Optional’ 限定符。例
     如：

          def foo(arg: int = 0) -> None:
              ...

     另一方面，如果允许显式地传递值 ‘None’ ， 使用 ‘Optional’ 也是正当的
     ，无论该参数是否是可选的。例如：

          def foo(arg: Optional[int] = None) -> None:
              ...

 -- 数据: typing.Tuple

     元组类型； ‘Tuple[X, Y]’ 标注了一个二元组类型，其第一个元素的类型为
     X 且第二个元素的类型为 Y。空元组的类型可写作 ‘Tuple[()]’ 。

     举例： ‘Tuple[T1, T2]’ 是一个二元组，类型分别为 T1 和 T2。
     ‘Tuple[int, float, str]’ 是一个由整数、浮点数和字符串组成的三元组。

     为表达一个同类型元素的变长元组，使用省略号字面量，如 ‘Tuple[int,
     ...]’ 。单独的一个 *note Tuple: 3275. 等价于 ‘Tuple[Any, ...]’，进
     而等价于 *note tuple: 486. 。

 -- 数据: typing.Callable

     可调用类型； ‘Callable[[int], str]’ 是一个函数，接受一个 int 参数，
     返回一个 str 。

     下标值的语法必须恰为两个值：参数列表和返回类型。参数列表必须是一个
     类型和省略号组成的列表；返回值必须是单一一个类型。

     不存在语法来表示可选的或关键词参数，这类函数类型罕见用于回调函数。
     ‘Callable[..., ReturnType]’ （使用字面省略号）能被用于提示一个可调
     用对象，接受任意数量的参数并且返回 ‘ReturnType’。单独的 *note
     Callable: 3276. 等价于 ‘Callable[..., Any]’ ，并且进而等价于 *note
     collections.abc.Callable: 1965. 。

 -- 数据: typing.Literal

     该类型将指示类型检查器该变量或者函数参数的值等价于提供的字面量（或
     者提供的几个字面量的其中之一）。例如：

          def validate_simple(data: Any) -> Literal[True]:  # always returns True
              ...

          MODE = Literal['r', 'rb', 'w', 'wb']
          def open_helper(file: str, mode: MODE) -> str:
              ...

          open_helper('/some/path', 'r')  # Passes type check
          open_helper('/other/path', 'typo')  # Error in type checker

     ‘Literal[...]’ 不能创建子类。在运行时，任意值均可作为
     ‘Literal[...]’ 的类型参数，但类型检查器可以施加额外限制。关于字面量
     类型更多详情请见 PEP 586(10) 。

     3.8 新版功能.

 -- 数据: typing.ClassVar

     特殊的类型构造器，用以标记类变量。

     在 PEP 526(11) 中被引入，ClassVar 包裹起来的变量注解指示了给定属性
     预期用于类变量，并且不应在类的实例上被设置。用法：

          class Starship:
              stats: ClassVar[Dict[str, int]] = {} # class variable
              damage: int = 10                     # instance variable

     *note ClassVar: 5ac. 仅接受类型，并且不能被再次下标。

     *note ClassVar: 5ac. 本身并不是一个类，并且不应与 *note
     isinstance(): 457. or *note issubclass(): 458. 一起使用。 *note
     ClassVar: 5ac. 并不改变 Python 运行时行为，但它可以被用于第三方类型
     检查器。例如，某个类型检查器可能会标记以下代码为错误的：

          enterprise_d = Starship(3000)
          enterprise_d.stats = {} # Error, setting class variable on instance
          Starship.stats = {}     # This is OK

     3.5.3 新版功能.

 -- 数据: typing.Final

     一个特殊的类型构造来指示类型检查器该名称不能被再次赋值或者在子类中
     被重载。例如：

          MAX_SIZE: Final = 9000
          MAX_SIZE += 1  # Error reported by type checker

          class Connection:
              TIMEOUT: Final[int] = 10

          class FastConnector(Connection):
              TIMEOUT = 1  # Error reported by type checker

     这些属性没有运行时检查。详情请参阅 PEP 591(12)。

     3.8 新版功能.

 -- 数据: typing.AnyStr

     ‘AnyStr’ 类型变量的定义为 ‘AnyStr = TypeVar('AnyStr', str, bytes)’。

     这里指的是，它可以接受任意同类字符串，但不支持混用不同类别的字符串
     。例如：

          def concat(a: AnyStr, b: AnyStr) -> AnyStr:
              return a + b

          concat(u"foo", u"bar")  # Ok, output has type 'unicode'
          concat(b"foo", b"bar")  # Ok, output has type 'bytes'
          concat(u"foo", b"bar")  # Error, cannot mix unicode and bytes

 -- 数据: typing.TYPE_CHECKING

     被第三方静态类型检查器假定为 ‘True’ 的特殊常量。 在运行时为
     ‘False’。 用法如下:

          if TYPE_CHECKING:
              import expensive_mod

          def fun(arg: 'expensive_mod.SomeType') -> None:
              local_var: expensive_mod.AnotherType = other_fun()

     Note that the first type annotation must be enclosed in quotes,
     making it a "forward reference", to hide the ‘expensive_mod’
     reference from the interpreter runtime.  Type annotations for local
     variables are not evaluated, so the second annotation does not need
     to be enclosed in quotes.

     3.5.2 新版功能.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0484

   (3) https://www.python.org/dev/peps/pep-0544

   (4) https://www.python.org/dev/peps/pep-0484

   (5) https://www.python.org/dev/peps/pep-0526

   (6) https://www.python.org/dev/peps/pep-0526

   (7) https://www.python.org/dev/peps/pep-0589

   (8) https://www.python.org/dev/peps/pep-0484

   (9) https://www.python.org/dev/peps/pep-0591

   (10) https://www.python.org/dev/peps/pep-0586

   (11) https://www.python.org/dev/peps/pep-0526

   (12) https://www.python.org/dev/peps/pep-0591


File: python.info,  Node: pydoc --- 文档生成器和在线帮助系统,  Next: doctest --- 测试交互性的Python示例,  Prev: typing --- 类型标注支持,  Up: 开发工具

5.26.2 ‘pydoc’ — 文档生成器和在线帮助系统
-----------------------------------------

`源代码:' Lib/pydoc.py(1)

__________________________________________________________________

The *note pydoc: da. module automatically generates documentation from
Python modules.  The documentation can be presented as pages of text on
the console, served to a Web browser, or saved to HTML files.

对于模块、类、函数和方法，显示的文档内容取自文档字符串（即 ‘__doc__’ 属
性），并会递归地从其带文档的成员中获取。 如果没有文档字符串，*note
pydoc: da. 会尝试从类、函数或方法定义上方，或是模块顶部的注释行段落获取
(参见 *note inspect.getcomments(): 32b9.).

内置函数 *note help(): 57b. 会发起调用交互式解释器的在线帮助系统，该系统
使用 *note pydoc: da. 在终端上生成文本形式的文档内容。 同样的文本文档也
可以在 Python 解释器以外通过在操作系统的命令提示符下以脚本方式运行
‘pydoc’ 来查看。 例如，运行

     pydoc sys

在终端提示符下将通过 *note sys: fe. 模块显示文档内容，其样式类似于 Unix
‘man’ 命令所显示的指南页面。 ‘pydoc’ 的参数可以为函数、模块、包，或带点
号的对模块中的类、方法或函数以及包中的模块的引用。 如果传给 ‘pydoc’ 的参
数像是一个路径（即包含所在操作系统的路径分隔符，例如 Unix 的正斜杠），并
且其指向一个现有的 Python 源文件，则会为该文件生成文档内容。

     注解: 为了找到对象及其文档内容，*note pydoc: da. 会导入文档所在的模
     块。 因此，任何模块层级的代码都将被执行。 请使用 ‘if __name__ ==
     '__main__':’ 语句来确保一个文件的特定代码仅在作为脚本被发起调用时执
     行而不是在被导入时执行。

当打印输出到控制台时，‘pydoc’ 会尝试对输出进行分页以方便阅读。 如果设置
了 ‘PAGER’ 环境变量，‘pydoc’ 将使用该变量值作为分页程序。

在参数前指定 ‘-w’ 旗标将把 HTML 文档写入到当前目录下的一个文件中，而不是
在控制台中显示文本。

在参数前指定 ‘-k’ 旗标将在全部可用模块的提要行中搜索参数所给定的关键字，
具体方式同样类似于 Unix ‘man’ 命令。 模块的提要行就是其文档字符串的第一
行。

你还可以使用 ‘pydoc’ 在本机上启动一个 HTTP 服务，这将向来访的 Web 浏览器
提供文档服务。 ‘pydoc -p 1234’ 将在 1234 端口上启动 HTTP 服务，允许你在
你喜欢的 Web 服务器中通过 ‘http://localhost:1234/’ 浏览文档内容。 指定
‘0’ 作为端口号将会任意选择一个未使用的端口。

‘pydoc -n <hostname>’ 将启动在给定主机名上执行监听的服务。 默认主机名为
’localhost’ 但如果你希望能从其他机器搜索该服务器，你可能会想要改变服务器
所响应的主机名。 在开发阶段此特性会特别有用，因为这样你将能在一个容器中
运行 pydoc。

‘pydoc -b’ 将启动服务并额外打开一个 Web 浏览器访问模块索引页。 所发布的
每个页面顶端都带有导航栏，你可以点击 `Get' 获取特定条目的帮助，点击
`Search' 在所有模块的提要行中搜索特定关键词，或是点击 `Module index',
`Topics' 和 `Keywords' 前往相应的页面。

当 ‘pydoc’ 生成文档内容时，它会使用当前环境和路径来定位模块。 因此，发起
调用 ‘pydoc spam’ 得到的文档版本会与你启动 Python 解释器并输入 ‘import
spam’ 时得到的模块版本完全相同。

核心模块的模块文档位置对应于 ‘https://docs.python.org/X.Y/library/’ 其中
‘X’ 和 ‘Y’ 是 Python 解释器的主要版本号和小版本号。 这可通过设置
‘PYTHONDOCS’ 环境变量来重载为指向不同的 URL 或包含 Library Reference
Manual 页面的本地目录。

在 3.2 版更改: 添加 ‘-b’ 选项。

在 3.3 版更改: 命令行选项 ‘-g’ 已经移除。

在 3.4 版更改: *note pydoc: da. 现在会使用 *note inspect.signature():
564. 而非 *note inspect.getfullargspec(): 566. 来从可调用对象中提取签名
信息。

在 3.7 版更改: 添加 ‘-n’ 选项。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/pydoc.py


File: python.info,  Node: doctest --- 测试交互性的Python示例,  Next: unittest --- 单元测试框架,  Prev: pydoc --- 文档生成器和在线帮助系统,  Up: 开发工具

5.26.3 ‘doctest’ — 测试交互性的Python示例
-----------------------------------------

** 源代码 ** Lib/doctest.py(1)

__________________________________________________________________

*note doctest: 67. 模块寻找像Python交互式代码的文本，然后执行这些代码来
确保它们的确就像展示的那样正确运行，有许多方法来使用doctest：

   * 通过验证所有交互式示例仍然按照记录的方式工作，以此来检查模块的文档
     字符串是否是最新的。

   * 通过验证来自一个测试文件或一个测试对象的交互式示例按预期工作，来进
     行回归测试。

   * To write tutorial documentation for a package, liberally
     illustrated with input-output examples.  Depending on whether the
     examples or the expository text are emphasized, this has the flavor
     of "literate testing" or "executable documentation".

下面是一个小却完整的示例模块:

     """
     This is the "example" module.

     The example module supplies one function, factorial().  For example,

     >>> factorial(5)
     120
     """

     def factorial(n):
         """Return the factorial of n, an exact integer >= 0.

         >>> [factorial(n) for n in range(6)]
         [1, 1, 2, 6, 24, 120]
         >>> factorial(30)
         265252859812191058636308480000000
         >>> factorial(-1)
         Traceback (most recent call last):
             ...
         ValueError: n must be >= 0

         Factorials of floats are OK, but the float must be an exact integer:
         >>> factorial(30.1)
         Traceback (most recent call last):
             ...
         ValueError: n must be exact integer
         >>> factorial(30.0)
         265252859812191058636308480000000

         It must also not be ridiculously large:
         >>> factorial(1e100)
         Traceback (most recent call last):
             ...
         OverflowError: n too large
         """

         import math
         if not n >= 0:
             raise ValueError("n must be >= 0")
         if math.floor(n) != n:
             raise ValueError("n must be exact integer")
         if n+1 == n:  # catch a value like 1e300
             raise OverflowError("n too large")
         result = 1
         factor = 2
         while factor <= n:
             result *= factor
             factor += 1
         return result


     if __name__ == "__main__":
         import doctest
         doctest.testmod()

如果你直接在命令行里运行 ‘example.py’ ， *note doctest: 67. 将发挥它的作
用。

     $ python example.py
     $

There’s no output!  That’s normal, and it means all the examples worked.
Pass ‘-v’ to the script, and *note doctest: 67. prints a detailed log of
what it’s trying, and prints a summary at the end:

     $ python example.py -v
     Trying:
         factorial(5)
     Expecting:
         120
     ok
     Trying:
         [factorial(n) for n in range(6)]
     Expecting:
         [1, 1, 2, 6, 24, 120]
     ok

以此类推，最终以：

     Trying:
         factorial(1e100)
     Expecting:
         Traceback (most recent call last):
             ...
         OverflowError: n too large
     ok
     2 items passed all tests:
        1 tests in __main__
        8 tests in __main__.factorial
     9 tests in 2 items.
     9 passed and 0 failed.
     Test passed.
     $

That’s all you need to know to start making productive use of *note
doctest: 67.!  Jump in.  The following sections provide full details.
Note that there are many examples of doctests in the standard Python
test suite and libraries.  Especially useful examples can be found in
the standard test file ‘Lib/test/test_doctest.py’.

* Menu:

* 简单用法：检查Docstrings中的示例::
* Simple Usage; Checking Examples in a Text File: Simple Usage Checking Examples in a Text File.
* How It Works::
* Basic API::
* Unittest API::
* Advanced API::
* 调试::
* Soapbox::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/doctest.py


File: python.info,  Node: 简单用法：检查Docstrings中的示例,  Next: Simple Usage Checking Examples in a Text File,  Up: doctest --- 测试交互性的Python示例

5.26.3.1 简单用法：检查Docstrings中的示例
.........................................

开始使用doctest的最简单方法（但不一定是你将继续这样做的方式）是结束每个
模块 ‘M’ 使用:

     if __name__ == "__main__":
         import doctest
         doctest.testmod()

*note doctest: 67. then examines docstrings in module ‘M’.

Running the module as a script causes the examples in the docstrings to
get executed and verified:

     python M.py

This won’t display anything unless an example fails, in which case the
failing example(s) and the cause(s) of the failure(s) are printed to
stdout, and the final line of output is ‘***Test Failed*** N failures.’,
where `N' is the number of examples that failed.

Run it with the ‘-v’ switch instead:

     python M.py -v

and a detailed report of all examples tried is printed to standard
output, along with assorted summaries at the end.

You can force verbose mode by passing ‘verbose=True’ to *note testmod():
dd8, or prohibit it by passing ‘verbose=False’.  In either of those
cases, ‘sys.argv’ is not examined by *note testmod(): dd8. (so passing
‘-v’ or not has no effect).

There is also a command line shortcut for running *note testmod(): dd8.
You can instruct the Python interpreter to run the doctest module
directly from the standard library and pass the module name(s) on the
command line:

     python -m doctest -v example.py

This will import ‘example.py’ as a standalone module and run *note
testmod(): dd8. on it.  Note that this may not work correctly if the
file is part of a package and imports other submodules from that
package.

For more information on *note testmod(): dd8, see section *note Basic
API: 32be.


File: python.info,  Node: Simple Usage Checking Examples in a Text File,  Next: How It Works,  Prev: 简单用法：检查Docstrings中的示例,  Up: doctest --- 测试交互性的Python示例

5.26.3.2 Simple Usage: Checking Examples in a Text File
.......................................................

Another simple application of doctest is testing interactive examples in
a text file.  This can be done with the *note testfile(): 32c1.
function:

     import doctest
     doctest.testfile("example.txt")

That short script executes and verifies any interactive Python examples
contained in the file ‘example.txt’.  The file content is treated as if
it were a single giant docstring; the file doesn’t need to contain a
Python program!  For example, perhaps ‘example.txt’ contains this:

     The ``example`` module
     ======================

     Using ``factorial``
     -------------------

     This is an example text file in reStructuredText format.  First import
     ``factorial`` from the ``example`` module:

         >>> from example import factorial

     Now use it:

         >>> factorial(6)
         120

Running ‘doctest.testfile("example.txt")’ then finds the error in this
documentation:

     File "./example.txt", line 14, in example.txt
     Failed example:
         factorial(6)
     Expected:
         120
     Got:
         720

As with *note testmod(): dd8, *note testfile(): 32c1. won’t display
anything unless an example fails.  If an example does fail, then the
failing example(s) and the cause(s) of the failure(s) are printed to
stdout, using the same format as *note testmod(): dd8.

By default, *note testfile(): 32c1. looks for files in the calling
module’s directory.  See section *note Basic API: 32be. for a
description of the optional arguments that can be used to tell it to
look for files in other locations.

Like *note testmod(): dd8, *note testfile(): 32c1.’s verbosity can be
set with the ‘-v’ command-line switch or with the optional keyword
argument `verbose'.

There is also a command line shortcut for running *note testfile():
32c1.  You can instruct the Python interpreter to run the doctest module
directly from the standard library and pass the file name(s) on the
command line:

     python -m doctest -v example.txt

Because the file name does not end with ‘.py’, *note doctest: 67. infers
that it must be run with *note testfile(): 32c1, not *note testmod():
dd8.

For more information on *note testfile(): 32c1, see section *note Basic
API: 32be.


File: python.info,  Node: How It Works,  Next: Basic API,  Prev: Simple Usage Checking Examples in a Text File,  Up: doctest --- 测试交互性的Python示例

5.26.3.3 How It Works
.....................

This section examines in detail how doctest works: which docstrings it
looks at, how it finds interactive examples, what execution context it
uses, how it handles exceptions, and how option flags can be used to
control its behavior.  This is the information that you need to know to
write doctest examples; for information about actually running doctest
on these examples, see the following sections.

* Menu:

* Which Docstrings Are Examined?::
* How are Docstring Examples Recognized?::
* What's the Execution Context?::
* What About Exceptions?::
* Option Flags::
* Directives::
* 警告: 警告<2>.


File: python.info,  Node: Which Docstrings Are Examined?,  Next: How are Docstring Examples Recognized?,  Up: How It Works

5.26.3.4 Which Docstrings Are Examined?
.......................................

The module docstring, and all function, class and method docstrings are
searched.  Objects imported into the module are not searched.

In addition, if ‘M.__test__’ exists and "is true", it must be a dict,
and each entry maps a (string) name to a function object, class object,
or string.  Function and class object docstrings found from ‘M.__test__’
are searched, and strings are treated as if they were docstrings.  In
output, a key ‘K’ in ‘M.__test__’ appears with name

     <name of M>.__test__.K

Any classes found are recursively searched similarly, to test docstrings
in their contained methods and nested classes.

`CPython implementation detail:' Prior to version 3.4, extension modules
written in C were not fully searched by doctest.


File: python.info,  Node: How are Docstring Examples Recognized?,  Next: What's the Execution Context?,  Prev: Which Docstrings Are Examined?,  Up: How It Works

5.26.3.5 How are Docstring Examples Recognized?
...............................................

In most cases a copy-and-paste of an interactive console session works
fine, but doctest isn’t trying to do an exact emulation of any specific
Python shell.

     >>> # comments are ignored
     >>> x = 12
     >>> x
     12
     >>> if x == 13:
     ...     print("yes")
     ... else:
     ...     print("no")
     ...     print("NO")
     ...     print("NO!!!")
     ...
     no
     NO
     NO!!!
     >>>

Any expected output must immediately follow the final ‘'>>> '’ or ‘'...
'’ line containing the code, and the expected output (if any) extends to
the next ‘'>>> '’ or all-whitespace line.

The fine print:

   * Expected output cannot contain an all-whitespace line, since such a
     line is taken to signal the end of expected output.  If expected
     output does contain a blank line, put ‘<BLANKLINE>’ in your doctest
     example each place a blank line is expected.

   * All hard tab characters are expanded to spaces, using 8-column tab
     stops.  Tabs in output generated by the tested code are not
     modified.  Because any hard tabs in the sample output `are'
     expanded, this means that if the code output includes hard tabs,
     the only way the doctest can pass is if the *note
     NORMALIZE_WHITESPACE: 32c8. option or *note directive: 32c9. is in
     effect.  Alternatively, the test can be rewritten to capture the
     output and compare it to an expected value as part of the test.
     This handling of tabs in the source was arrived at through trial
     and error, and has proven to be the least error prone way of
     handling them.  It is possible to use a different algorithm for
     handling tabs by writing a custom *note DocTestParser: 32ca. class.

   * Output to stdout is captured, but not output to stderr (exception
     tracebacks are captured via a different means).

   * If you continue a line via backslashing in an interactive session,
     or for any other reason use a backslash, you should use a raw
     docstring, which will preserve your backslashes exactly as you type
     them:

          >>> def f(x):
          ...     r'''Backslashes in a raw docstring: m\n'''
          >>> print(f.__doc__)
          Backslashes in a raw docstring: m\n

     Otherwise, the backslash will be interpreted as part of the string.
     For example, the ‘\n’ above would be interpreted as a newline
     character.  Alternatively, you can double each backslash in the
     doctest version (and not use a raw string):

          >>> def f(x):
          ...     '''Backslashes in a raw docstring: m\\n'''
          >>> print(f.__doc__)
          Backslashes in a raw docstring: m\n

   * The starting column doesn’t matter:

          >>> assert "Easy!"
                >>> import math
                    >>> math.floor(1.9)
                    1

     and as many leading whitespace characters are stripped from the
     expected output as appeared in the initial ‘'>>> '’ line that
     started the example.


File: python.info,  Node: What's the Execution Context?,  Next: What About Exceptions?,  Prev: How are Docstring Examples Recognized?,  Up: How It Works

5.26.3.6 What’s the Execution Context?
......................................

By default, each time *note doctest: 67. finds a docstring to test, it
uses a `shallow copy' of ‘M’’s globals, so that running tests doesn’t
change the module’s real globals, and so that one test in ‘M’ can’t
leave behind crumbs that accidentally allow another test to work.  This
means examples can freely use any names defined at top-level in ‘M’, and
names defined earlier in the docstring being run.  Examples cannot see
names defined in other docstrings.

You can force use of your own dict as the execution context by passing
‘globs=your_dict’ to *note testmod(): dd8. or *note testfile(): 32c1.
instead.


File: python.info,  Node: What About Exceptions?,  Next: Option Flags,  Prev: What's the Execution Context?,  Up: How It Works

5.26.3.7 What About Exceptions?
...............................

No problem, provided that the traceback is the only output produced by
the example: just paste in the traceback.  (1) Since tracebacks contain
details that are likely to change rapidly (for example, exact file paths
and line numbers), this is one case where doctest works hard to be
flexible in what it accepts.

Simple example:

     >>> [1, 2, 3].remove(42)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     ValueError: list.remove(x): x not in list

That doctest succeeds if *note ValueError: 1fc. is raised, with the
‘list.remove(x): x not in list’ detail as shown.

The expected output for an exception must start with a traceback header,
which may be either of the following two lines, indented the same as the
first line of the example:

     Traceback (most recent call last):
     Traceback (innermost last):

The traceback header is followed by an optional traceback stack, whose
contents are ignored by doctest.  The traceback stack is typically
omitted, or copied verbatim from an interactive session.

The traceback stack is followed by the most interesting part: the
line(s) containing the exception type and detail.  This is usually the
last line of a traceback, but can extend across multiple lines if the
exception has a multi-line detail:

     >>> raise ValueError('multi\n    line\ndetail')
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     ValueError: multi
         line
     detail

The last three lines (starting with *note ValueError: 1fc.) are compared
against the exception’s type and detail, and the rest are ignored.

Best practice is to omit the traceback stack, unless it adds significant
documentation value to the example.  So the last example is probably
better as:

     >>> raise ValueError('multi\n    line\ndetail')
     Traceback (most recent call last):
         ...
     ValueError: multi
         line
     detail

Note that tracebacks are treated very specially.  In particular, in the
rewritten example, the use of ‘...’ is independent of doctest’s *note
ELLIPSIS: dd9. option.  The ellipsis in that example could be left out,
or could just as well be three (or three hundred) commas or digits, or
an indented transcript of a Monty Python skit.

Some details you should read once, but won’t need to remember:

   * Doctest can’t guess whether your expected output came from an
     exception traceback or from ordinary printing.  So, e.g., an
     example that expects ‘ValueError: 42 is prime’ will pass whether
     *note ValueError: 1fc. is actually raised or if the example merely
     prints that traceback text.  In practice, ordinary output rarely
     begins with a traceback header line, so this doesn’t create real
     problems.

   * Each line of the traceback stack (if present) must be indented
     further than the first line of the example, `or' start with a
     non-alphanumeric character.  The first line following the traceback
     header indented the same and starting with an alphanumeric is taken
     to be the start of the exception detail.  Of course this does the
     right thing for genuine tracebacks.

   * When the *note IGNORE_EXCEPTION_DETAIL: 32cf. doctest option is
     specified, everything following the leftmost colon and any module
     information in the exception name is ignored.

   * The interactive shell omits the traceback header line for some
     *note SyntaxError: 460.s.  But doctest uses the traceback header
     line to distinguish exceptions from non-exceptions.  So in the rare
     case where you need to test a *note SyntaxError: 460. that omits
     the traceback header, you will need to manually add the traceback
     header line to your test example.

   * For some *note SyntaxError: 460.s, Python displays the character
     position of the syntax error, using a ‘^’ marker:

          >>> 1 1
            File "<stdin>", line 1
              1 1
                ^
          SyntaxError: invalid syntax

     Since the lines showing the position of the error come before the
     exception type and detail, they are not checked by doctest.  For
     example, the following test would pass, even though it puts the ‘^’
     marker in the wrong location:

          >>> 1 1
          Traceback (most recent call last):
            File "<stdin>", line 1
              1 1
              ^
          SyntaxError: invalid syntax

   ---------- Footnotes ----------

   (1) (1) Examples containing both expected output and an exception are
not supported.  Trying to guess where one ends and the other begins is
too error-prone, and that also makes for a confusing test.


File: python.info,  Node: Option Flags,  Next: Directives,  Prev: What About Exceptions?,  Up: How It Works

5.26.3.8 Option Flags
.....................

A number of option flags control various aspects of doctest’s behavior.
Symbolic names for the flags are supplied as module constants, which can
be *note bitwise ORed: 154d. together and passed to various functions.
The names can also be used in *note doctest directives: 32c9, and may be
passed to the doctest command line interface via the ‘-o’ option.

3.4 新版功能: The ‘-o’ command line option.

The first group of options define test semantics, controlling aspects of
how doctest decides whether actual output matches an example’s expected
output:

 -- 数据: doctest.DONT_ACCEPT_TRUE_FOR_1

     By default, if an expected output block contains just ‘1’, an
     actual output block containing just ‘1’ or just ‘True’ is
     considered to be a match, and similarly for ‘0’ versus ‘False’.
     When *note DONT_ACCEPT_TRUE_FOR_1: 32d2. is specified, neither
     substitution is allowed.  The default behavior caters to that
     Python changed the return type of many functions from integer to
     boolean; doctests expecting "little integer" output still work in
     these cases.  This option will probably go away, but not for
     several years.

 -- 数据: doctest.DONT_ACCEPT_BLANKLINE

     By default, if an expected output block contains a line containing
     only the string ‘<BLANKLINE>’, then that line will match a blank
     line in the actual output.  Because a genuinely blank line delimits
     the expected output, this is the only way to communicate that a
     blank line is expected.  When *note DONT_ACCEPT_BLANKLINE: 32d3. is
     specified, this substitution is not allowed.

 -- 数据: doctest.NORMALIZE_WHITESPACE

     When specified, all sequences of whitespace (blanks and newlines)
     are treated as equal.  Any sequence of whitespace within the
     expected output will match any sequence of whitespace within the
     actual output.  By default, whitespace must match exactly.  *note
     NORMALIZE_WHITESPACE: 32c8. is especially useful when a line of
     expected output is very long, and you want to wrap it across
     multiple lines in your source.

 -- 数据: doctest.ELLIPSIS

     When specified, an ellipsis marker (‘...’) in the expected output
     can match any substring in the actual output.  This includes
     substrings that span line boundaries, and empty substrings, so it’s
     best to keep usage of this simple.  Complicated uses can lead to
     the same kinds of "oops, it matched too much!"  surprises that ‘.*’
     is prone to in regular expressions.

 -- 数据: doctest.IGNORE_EXCEPTION_DETAIL

     When specified, an example that expects an exception passes if an
     exception of the expected type is raised, even if the exception
     detail does not match.  For example, an example expecting
     ‘ValueError: 42’ will pass if the actual exception raised is
     ‘ValueError: 3*14’, but will fail, e.g., if *note TypeError: 193.
     is raised.

     It will also ignore the module name used in Python 3 doctest
     reports.  Hence both of these variations will work with the flag
     specified, regardless of whether the test is run under Python 2.7
     or Python 3.2 (or later versions):

          >>> raise CustomError('message')
          Traceback (most recent call last):
          CustomError: message

          >>> raise CustomError('message')
          Traceback (most recent call last):
          my_module.CustomError: message

     Note that *note ELLIPSIS: dd9. can also be used to ignore the
     details of the exception message, but such a test may still fail
     based on whether or not the module details are printed as part of
     the exception name.  Using *note IGNORE_EXCEPTION_DETAIL: 32cf. and
     the details from Python 2.3 is also the only clear way to write a
     doctest that doesn’t care about the exception detail yet continues
     to pass under Python 2.3 or earlier (those releases do not support
     *note doctest directives: 32c9. and ignore them as irrelevant
     comments).  For example:

          >>> (1, 2)[3] = 'moo'
          Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
          TypeError: object doesn't support item assignment

     passes under Python 2.3 and later Python versions with the flag
     specified, even though the detail changed in Python 2.4 to say
     "does not" instead of "doesn’t".

     在 3.2 版更改: *note IGNORE_EXCEPTION_DETAIL: 32cf. now also
     ignores any information relating to the module containing the
     exception under test.

 -- 数据: doctest.SKIP

     When specified, do not run the example at all.  This can be useful
     in contexts where doctest examples serve as both documentation and
     test cases, and an example should be included for documentation
     purposes, but should not be checked.  E.g., the example’s output
     might be random; or the example might depend on resources which
     would be unavailable to the test driver.

     The SKIP flag can also be used for temporarily "commenting out"
     examples.

 -- 数据: doctest.COMPARISON_FLAGS

     A bitmask or’ing together all the comparison flags above.

The second group of options controls how test failures are reported:

 -- 数据: doctest.REPORT_UDIFF

     When specified, failures that involve multi-line expected and
     actual outputs are displayed using a unified diff.

 -- 数据: doctest.REPORT_CDIFF

     When specified, failures that involve multi-line expected and
     actual outputs will be displayed using a context diff.

 -- 数据: doctest.REPORT_NDIFF

     When specified, differences are computed by ‘difflib.Differ’, using
     the same algorithm as the popular ‘ndiff.py’ utility.  This is the
     only method that marks differences within lines as well as across
     lines.  For example, if a line of expected output contains digit
     ‘1’ where actual output contains letter ‘l’, a line is inserted
     with a caret marking the mismatching column positions.

 -- 数据: doctest.REPORT_ONLY_FIRST_FAILURE

     When specified, display the first failing example in each doctest,
     but suppress output for all remaining examples.  This will prevent
     doctest from reporting correct examples that break because of
     earlier failures; but it might also hide incorrect examples that
     fail independently of the first failure.  When *note
     REPORT_ONLY_FIRST_FAILURE: 32d6. is specified, the remaining
     examples are still run, and still count towards the total number of
     failures reported; only the output is suppressed.

 -- 数据: doctest.FAIL_FAST

     When specified, exit after the first failing example and don’t
     attempt to run the remaining examples.  Thus, the number of
     failures reported will be at most 1.  This flag may be useful
     during debugging, since examples after the first failure won’t even
     produce debugging output.

     The doctest command line accepts the option ‘-f’ as a shorthand for
     ‘-o FAIL_FAST’.

     3.4 新版功能.

 -- 数据: doctest.REPORTING_FLAGS

     A bitmask or’ing together all the reporting flags above.

There is also a way to register new option flag names, though this isn’t
useful unless you intend to extend *note doctest: 67. internals via
subclassing:

 -- 函数: doctest.register_optionflag (name)

     Create a new option flag with a given name, and return the new
     flag’s integer value.  *note register_optionflag(): 32d8. can be
     used when subclassing *note OutputChecker: 32d9. or *note
     DocTestRunner: 32da. to create new options that are supported by
     your subclasses.  *note register_optionflag(): 32d8. should always
     be called using the following idiom:

          MY_FLAG = register_optionflag('MY_FLAG')


File: python.info,  Node: Directives,  Next: 警告<2>,  Prev: Option Flags,  Up: How It Works

5.26.3.9 Directives
...................

Doctest directives may be used to modify the *note option flags: 845.
for an individual example.  Doctest directives are special Python
comments following an example’s source code:

     directive             ::= "#" "doctest:" directive_options
     directive_options     ::= directive_option ("," directive_option)\*
     directive_option      ::= on_or_off directive_option_name
     on_or_off             ::= "+" \| "-"
     directive_option_name ::= "DONT_ACCEPT_BLANKLINE" \| "NORMALIZE_WHITESPACE" \| ...

Whitespace is not allowed between the ‘+’ or ‘-’ and the directive
option name.  The directive option name can be any of the option flag
names explained above.

An example’s doctest directives modify doctest’s behavior for that
single example.  Use ‘+’ to enable the named behavior, or ‘-’ to disable
it.

For example, this test passes:

     >>> print(list(range(20)))
     [0,   1,  2,  3,  4,  5,  6,  7,  8,  9,
     10,  11, 12, 13, 14, 15, 16, 17, 18, 19]

Without the directive it would fail, both because the actual output
doesn’t have two blanks before the single-digit list elements, and
because the actual output is on a single line.  This test also passes,
and also requires a directive to do so:

     >>> print(list(range(20)))
     [0, 1, ..., 18, 19]

Multiple directives can be used on a single physical line, separated by
commas:

     >>> print(list(range(20)))
     [0,    1, ...,   18,    19]

If multiple directive comments are used for a single example, then they
are combined:

     >>> print(list(range(20)))
     ...
     [0,    1, ...,   18,    19]

As the previous example shows, you can add ‘...’ lines to your example
containing only directives.  This can be useful when an example is too
long for a directive to comfortably fit on the same line:

     >>> print(list(range(5)) + list(range(10, 20)) + list(range(30, 40)))
     ...
     [0, ..., 4, 10, ..., 19, 30, ..., 39]

Note that since all options are disabled by default, and directives
apply only to the example they appear in, enabling options (via ‘+’ in a
directive) is usually the only meaningful choice.  However, option flags
can also be passed to functions that run doctests, establishing
different defaults.  In such cases, disabling an option via ‘-’ in a
directive can be useful.


File: python.info,  Node: 警告<2>,  Prev: Directives,  Up: How It Works

5.26.3.10 警告
..............

*note doctest: 67. is serious about requiring exact matches in expected
output.  If even a single character doesn’t match, the test fails.  This
will probably surprise you a few times, as you learn exactly what Python
does and doesn’t guarantee about output.  For example, when printing a
set, Python doesn’t guarantee that the element is printed in any
particular order, so a test like

     >>> foo()
     {"Hermione", "Harry"}

is vulnerable!  One workaround is to do

     >>> foo() == {"Hermione", "Harry"}
     True

instead.  Another is to do

     >>> d = sorted(foo())
     >>> d
     ['Harry', 'Hermione']

     注解: Before Python 3.6, when printing a dict, Python did not
     guarantee that the key-value pairs was printed in any particular
     order.

There are others, but you get the idea.

Another bad idea is to print things that embed an object address, like

     >>> id(1.0) # certain to fail some of the time
     7948648
     >>> class C: pass
     >>> C()   # the default repr() for instances embeds an address
     <__main__.C instance at 0x00AC18F0>

The *note ELLIPSIS: dd9. directive gives a nice approach for the last
example:

     >>> C()
     <__main__.C instance at 0x...>

Floating-point numbers are also subject to small output variations
across platforms, because Python defers to the platform C library for
float formatting, and C libraries vary widely in quality here.

     >>> 1./7  # risky
     0.14285714285714285
     >>> print(1./7) # safer
     0.142857142857
     >>> print(round(1./7, 6)) # much safer
     0.142857

Numbers of the form ‘I/2.**J’ are safe across all platforms, and I often
contrive doctest examples to produce numbers of that form:

     >>> 3./4  # utterly safe
     0.75

Simple fractions are also easier for people to understand, and that
makes for better documentation.


File: python.info,  Node: Basic API,  Next: Unittest API,  Prev: How It Works,  Up: doctest --- 测试交互性的Python示例

5.26.3.11 Basic API
...................

The functions *note testmod(): dd8. and *note testfile(): 32c1. provide
a simple interface to doctest that should be sufficient for most basic
uses.  For a less formal introduction to these two functions, see
sections *note 简单用法：检查Docstrings中的示例: 32bc. and *note Simple
Usage; Checking Examples in a Text File: 32bf.

 -- 函数: doctest.testfile (filename, module_relative=True, name=None,
          package=None, globs=None, verbose=None, report=True,
          optionflags=0, extraglobs=None, raise_on_error=False,
          parser=DocTestParser(), encoding=None)

     All arguments except `filename' are optional, and should be
     specified in keyword form.

     Test examples in the file named `filename'.  Return
     ‘(failure_count, test_count)’.

     Optional argument `module_relative' specifies how the filename
     should be interpreted:

        * If `module_relative' is ‘True’ (the default), then `filename'
          specifies an OS-independent module-relative path.  By default,
          this path is relative to the calling module’s directory; but
          if the `package' argument is specified, then it is relative to
          that package.  To ensure OS-independence, `filename' should
          use ‘/’ characters to separate path segments, and may not be
          an absolute path (i.e., it may not begin with ‘/’).

        * If `module_relative' is ‘False’, then `filename' specifies an
          OS-specific path.  The path may be absolute or relative;
          relative paths are resolved with respect to the current
          working directory.

     Optional argument `name' gives the name of the test; by default, or
     if ‘None’, ‘os.path.basename(filename)’ is used.

     Optional argument `package' is a Python package or the name of a
     Python package whose directory should be used as the base directory
     for a module-relative filename.  If no package is specified, then
     the calling module’s directory is used as the base directory for
     module-relative filenames.  It is an error to specify `package' if
     `module_relative' is ‘False’.

     Optional argument `globs' gives a dict to be used as the globals
     when executing examples.  A new shallow copy of this dict is
     created for the doctest, so its examples start with a clean slate.
     By default, or if ‘None’, a new empty dict is used.

     Optional argument `extraglobs' gives a dict merged into the globals
     used to execute examples.  This works like *note dict.update():
     dd1.: if `globs' and `extraglobs' have a common key, the associated
     value in `extraglobs' appears in the combined dict.  By default, or
     if ‘None’, no extra globals are used.  This is an advanced feature
     that allows parameterization of doctests.  For example, a doctest
     can be written for a base class, using a generic name for the
     class, then reused to test any number of subclasses by passing an
     `extraglobs' dict mapping the generic name to the subclass to be
     tested.

     Optional argument `verbose' prints lots of stuff if true, and
     prints only failures if false; by default, or if ‘None’, it’s true
     if and only if ‘'-v'’ is in ‘sys.argv’.

     Optional argument `report' prints a summary at the end when true,
     else prints nothing at the end.  In verbose mode, the summary is
     detailed, else the summary is very brief (in fact, empty if all
     tests passed).

     Optional argument `optionflags' (default value 0) takes the *note
     bitwise OR: 154d. of option flags.  See section *note Option Flags:
     845.

     Optional argument `raise_on_error' defaults to false.  If true, an
     exception is raised upon the first failure or unexpected exception
     in an example.  This allows failures to be post-mortem debugged.
     Default behavior is to continue running examples.

     Optional argument `parser' specifies a *note DocTestParser: 32ca.
     (or subclass) that should be used to extract tests from the files.
     It defaults to a normal parser (i.e., ‘DocTestParser()’).

     Optional argument `encoding' specifies an encoding that should be
     used to convert the file to unicode.

 -- 函数: doctest.testmod (m=None, name=None, globs=None, verbose=None,
          report=True, optionflags=0, extraglobs=None,
          raise_on_error=False, exclude_empty=False)

     All arguments are optional, and all except for `m' should be
     specified in keyword form.

     Test examples in docstrings in functions and classes reachable from
     module `m' (or module *note __main__: 1. if `m' is not supplied or
     is ‘None’), starting with ‘m.__doc__’.

     Also test examples reachable from dict ‘m.__test__’, if it exists
     and is not ‘None’.  ‘m.__test__’ maps names (strings) to functions,
     classes and strings; function and class docstrings are searched for
     examples; strings are searched directly, as if they were
     docstrings.

     Only docstrings attached to objects belonging to module `m' are
     searched.

     Return ‘(failure_count, test_count)’.

     Optional argument `name' gives the name of the module; by default,
     or if ‘None’, ‘m.__name__’ is used.

     Optional argument `exclude_empty' defaults to false.  If true,
     objects for which no doctests are found are excluded from
     consideration.  The default is a backward compatibility hack, so
     that code still using ‘doctest.master.summarize()’ in conjunction
     with *note testmod(): dd8. continues to get output for objects with
     no tests.  The `exclude_empty' argument to the newer *note
     DocTestFinder: 32e4. constructor defaults to true.

     Optional arguments `extraglobs', `verbose', `report',
     `optionflags', `raise_on_error', and `globs' are the same as for
     function *note testfile(): 32c1. above, except that `globs'
     defaults to ‘m.__dict__’.

 -- 函数: doctest.run_docstring_examples (f, globs, verbose=False,
          name="NoName", compileflags=None, optionflags=0)

     Test examples associated with object `f'; for example, `f' may be a
     string, a module, a function, or a class object.

     A shallow copy of dictionary argument `globs' is used for the
     execution context.

     Optional argument `name' is used in failure messages, and defaults
     to ‘"NoName"’.

     If optional argument `verbose' is true, output is generated even if
     there are no failures.  By default, output is generated only in
     case of an example failure.

     Optional argument `compileflags' gives the set of flags that should
     be used by the Python compiler when running the examples.  By
     default, or if ‘None’, flags are deduced corresponding to the set
     of future features found in `globs'.

     Optional argument `optionflags' works as for function *note
     testfile(): 32c1. above.


File: python.info,  Node: Unittest API,  Next: Advanced API,  Prev: Basic API,  Up: doctest --- 测试交互性的Python示例

5.26.3.12 Unittest API
......................

As your collection of doctest’ed modules grows, you’ll want a way to run
all their doctests systematically.  *note doctest: 67. provides two
functions that can be used to create *note unittest: 11c. test suites
from modules and text files containing doctests.  To integrate with
*note unittest: 11c. test discovery, include a ‘load_tests()’ function
in your test module:

     import unittest
     import doctest
     import my_module_with_doctests

     def load_tests(loader, tests, ignore):
         tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
         return tests

There are two main functions for creating *note unittest.TestSuite: 6d7.
instances from text files and modules with doctests:

 -- 函数: doctest.DocFileSuite (*paths, module_relative=True,
          package=None, setUp=None, tearDown=None, globs=None,
          optionflags=0, parser=DocTestParser(), encoding=None)

     Convert doctest tests from one or more text files to a *note
     unittest.TestSuite: 6d7.

     The returned *note unittest.TestSuite: 6d7. is to be run by the
     unittest framework and runs the interactive examples in each file.
     If an example in any file fails, then the synthesized unit test
     fails, and a ‘failureException’ exception is raised showing the
     name of the file containing the test and a (sometimes approximate)
     line number.

     Pass one or more paths (as strings) to text files to be examined.

     Options may be provided as keyword arguments:

     Optional argument `module_relative' specifies how the filenames in
     `paths' should be interpreted:

        * If `module_relative' is ‘True’ (the default), then each
          filename in `paths' specifies an OS-independent
          module-relative path.  By default, this path is relative to
          the calling module’s directory; but if the `package' argument
          is specified, then it is relative to that package.  To ensure
          OS-independence, each filename should use ‘/’ characters to
          separate path segments, and may not be an absolute path (i.e.,
          it may not begin with ‘/’).

        * If `module_relative' is ‘False’, then each filename in `paths'
          specifies an OS-specific path.  The path may be absolute or
          relative; relative paths are resolved with respect to the
          current working directory.

     Optional argument `package' is a Python package or the name of a
     Python package whose directory should be used as the base directory
     for module-relative filenames in `paths'.  If no package is
     specified, then the calling module’s directory is used as the base
     directory for module-relative filenames.  It is an error to specify
     `package' if `module_relative' is ‘False’.

     Optional argument `setUp' specifies a set-up function for the test
     suite.  This is called before running the tests in each file.  The
     `setUp' function will be passed a *note DocTest: 32e9. object.  The
     setUp function can access the test globals as the `globs' attribute
     of the test passed.

     Optional argument `tearDown' specifies a tear-down function for the
     test suite.  This is called after running the tests in each file.
     The `tearDown' function will be passed a *note DocTest: 32e9.
     object.  The setUp function can access the test globals as the
     `globs' attribute of the test passed.

     Optional argument `globs' is a dictionary containing the initial
     global variables for the tests.  A new copy of this dictionary is
     created for each test.  By default, `globs' is a new empty
     dictionary.

     Optional argument `optionflags' specifies the default doctest
     options for the tests, created by or-ing together individual option
     flags.  See section *note Option Flags: 845.  See function *note
     set_unittest_reportflags(): 32ea. below for a better way to set
     reporting options.

     Optional argument `parser' specifies a *note DocTestParser: 32ca.
     (or subclass) that should be used to extract tests from the files.
     It defaults to a normal parser (i.e., ‘DocTestParser()’).

     Optional argument `encoding' specifies an encoding that should be
     used to convert the file to unicode.

     The global ‘__file__’ is added to the globals provided to doctests
     loaded from a text file using *note DocFileSuite(): 32e8.

 -- 函数: doctest.DocTestSuite (module=None, globs=None,
          extraglobs=None, test_finder=None, setUp=None, tearDown=None,
          checker=None)

     Convert doctest tests for a module to a *note unittest.TestSuite:
     6d7.

     The returned *note unittest.TestSuite: 6d7. is to be run by the
     unittest framework and runs each doctest in the module.  If any of
     the doctests fail, then the synthesized unit test fails, and a
     ‘failureException’ exception is raised showing the name of the file
     containing the test and a (sometimes approximate) line number.

     Optional argument `module' provides the module to be tested.  It
     can be a module object or a (possibly dotted) module name.  If not
     specified, the module calling this function is used.

     Optional argument `globs' is a dictionary containing the initial
     global variables for the tests.  A new copy of this dictionary is
     created for each test.  By default, `globs' is a new empty
     dictionary.

     Optional argument `extraglobs' specifies an extra set of global
     variables, which is merged into `globs'.  By default, no extra
     globals are used.

     Optional argument `test_finder' is the *note DocTestFinder: 32e4.
     object (or a drop-in replacement) that is used to extract doctests
     from the module.

     Optional arguments `setUp', `tearDown', and `optionflags' are the
     same as for function *note DocFileSuite(): 32e8. above.

     This function uses the same search technique as *note testmod():
     dd8.

     在 3.5 版更改: *note DocTestSuite(): 6d6. returns an empty *note
     unittest.TestSuite: 6d7. if `module' contains no docstrings instead
     of raising *note ValueError: 1fc.

Under the covers, *note DocTestSuite(): 6d6. creates a *note
unittest.TestSuite: 6d7. out of ‘doctest.DocTestCase’ instances, and
‘DocTestCase’ is a subclass of *note unittest.TestCase: 907.
‘DocTestCase’ isn’t documented here (it’s an internal detail), but
studying its code can answer questions about the exact details of *note
unittest: 11c. integration.

Similarly, *note DocFileSuite(): 32e8. creates a *note
unittest.TestSuite: 6d7. out of ‘doctest.DocFileCase’ instances, and
‘DocFileCase’ is a subclass of ‘DocTestCase’.

So both ways of creating a *note unittest.TestSuite: 6d7. run instances
of ‘DocTestCase’.  This is important for a subtle reason: when you run
*note doctest: 67. functions yourself, you can control the *note
doctest: 67. options in use directly, by passing option flags to *note
doctest: 67. functions.  However, if you’re writing a *note unittest:
11c. framework, *note unittest: 11c. ultimately controls when and how
tests get run.  The framework author typically wants to control *note
doctest: 67. reporting options (perhaps, e.g., specified by command line
options), but there’s no way to pass options through *note unittest:
11c. to *note doctest: 67. test runners.

For this reason, *note doctest: 67. also supports a notion of *note
doctest: 67. reporting flags specific to *note unittest: 11c. support,
via this function:

 -- 函数: doctest.set_unittest_reportflags (flags)

     Set the *note doctest: 67. reporting flags to use.

     Argument `flags' takes the *note bitwise OR: 154d. of option flags.
     See section *note Option Flags: 845.  Only "reporting flags" can be
     used.

     This is a module-global setting, and affects all future doctests
     run by module *note unittest: 11c.: the ‘runTest()’ method of
     ‘DocTestCase’ looks at the option flags specified for the test case
     when the ‘DocTestCase’ instance was constructed.  If no reporting
     flags were specified (which is the typical and expected case),
     *note doctest: 67.’s *note unittest: 11c. reporting flags are *note
     bitwise ORed: 154d. into the option flags, and the option flags so
     augmented are passed to the *note DocTestRunner: 32da. instance
     created to run the doctest.  If any reporting flags were specified
     when the ‘DocTestCase’ instance was constructed, *note doctest:
     67.’s *note unittest: 11c. reporting flags are ignored.

     The value of the *note unittest: 11c. reporting flags in effect
     before the function was called is returned by the function.


File: python.info,  Node: Advanced API,  Next: 调试,  Prev: Unittest API,  Up: doctest --- 测试交互性的Python示例

5.26.3.13 Advanced API
......................

The basic API is a simple wrapper that’s intended to make doctest easy
to use.  It is fairly flexible, and should meet most users’ needs;
however, if you require more fine-grained control over testing, or wish
to extend doctest’s capabilities, then you should use the advanced API.

The advanced API revolves around two container classes, which are used
to store the interactive examples extracted from doctest cases:

   * *note Example: 32ed.: A single Python *note statement: 1ba2, paired
     with its expected output.

   * *note DocTest: 32e9.: A collection of *note Example: 32ed.s,
     typically extracted from a single docstring or text file.

Additional processing classes are defined to find, parse, and run, and
check doctest examples:

   * *note DocTestFinder: 32e4.: Finds all docstrings in a given module,
     and uses a *note DocTestParser: 32ca. to create a *note DocTest:
     32e9. from every docstring that contains interactive examples.

   * *note DocTestParser: 32ca.: Creates a *note DocTest: 32e9. object
     from a string (such as an object’s docstring).

   * *note DocTestRunner: 32da.: Executes the examples in a *note
     DocTest: 32e9, and uses an *note OutputChecker: 32d9. to verify
     their output.

   * *note OutputChecker: 32d9.: Compares the actual output from a
     doctest example with the expected output, and decides whether they
     match.

The relationships among these processing classes are summarized in the
following diagram:

                                 list of:
     +------+                   +---------+
     |module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
     +------+    |        ^     +---------+     |       ^    (printed)
                 |        |     | Example |     |       |
                 v        |     |   ...   |     v       |
                DocTestParser   | Example |   OutputChecker
                                +---------+

* Menu:

* DocTest 对象::
* Example Objects::
* DocTestFinder 对象::
* DocTestParser 对象::
* DocTestRunner 对象::
* OutputChecker 对象::


File: python.info,  Node: DocTest 对象,  Next: Example Objects,  Up: Advanced API

5.26.3.14 DocTest 对象
......................

 -- 类: doctest.DocTest (examples, globs, name, filename, lineno,
          docstring)

     A collection of doctest examples that should be run in a single
     namespace.  The constructor arguments are used to initialize the
     attributes of the same names.

     *note DocTest: 32e9. defines the following attributes.  They are
     initialized by the constructor, and should not be modified
     directly.

      -- 属性: examples

          A list of *note Example: 32ed. objects encoding the individual
          interactive Python examples that should be run by this test.

      -- 属性: globs

          The namespace (aka globals) that the examples should be run
          in.  This is a dictionary mapping names to values.  Any
          changes to the namespace made by the examples (such as binding
          new variables) will be reflected in *note globs: 32f1. after
          the test is run.

      -- 属性: name

          A string name identifying the *note DocTest: 32e9.  Typically,
          this is the name of the object or file that the test was
          extracted from.

      -- 属性: filename

          The name of the file that this *note DocTest: 32e9. was
          extracted from; or ‘None’ if the filename is unknown, or if
          the *note DocTest: 32e9. was not extracted from a file.

      -- 属性: lineno

          The line number within *note filename: 32f3. where this *note
          DocTest: 32e9. begins, or ‘None’ if the line number is
          unavailable.  This line number is zero-based with respect to
          the beginning of the file.

      -- 属性: docstring

          The string that the test was extracted from, or ‘None’ if the
          string is unavailable, or if the test was not extracted from a
          string.


File: python.info,  Node: Example Objects,  Next: DocTestFinder 对象,  Prev: DocTest 对象,  Up: Advanced API

5.26.3.15 Example Objects
.........................

 -- 类: doctest.Example (source, want, exc_msg=None, lineno=0, indent=0,
          options=None)

     A single interactive example, consisting of a Python statement and
     its expected output.  The constructor arguments are used to
     initialize the attributes of the same names.

     *note Example: 32ed. defines the following attributes.  They are
     initialized by the constructor, and should not be modified
     directly.

      -- 属性: source

          A string containing the example’s source code.  This source
          code consists of a single Python statement, and always ends
          with a newline; the constructor adds a newline when necessary.

      -- 属性: want

          The expected output from running the example’s source code
          (either from stdout, or a traceback in case of exception).
          *note want: 32f9. ends with a newline unless no output is
          expected, in which case it’s an empty string.  The constructor
          adds a newline when necessary.

      -- 属性: exc_msg

          The exception message generated by the example, if the example
          is expected to generate an exception; or ‘None’ if it is not
          expected to generate an exception.  This exception message is
          compared against the return value of *note
          traceback.format_exception_only(): 32fb.  *note exc_msg: 32fa.
          ends with a newline unless it’s ‘None’.  The constructor adds
          a newline if needed.

      -- 属性: lineno

          The line number within the string containing this example
          where the example begins.  This line number is zero-based with
          respect to the beginning of the containing string.

      -- 属性: indent

          The example’s indentation in the containing string, i.e., the
          number of space characters that precede the example’s first
          prompt.

      -- 属性: options

          A dictionary mapping from option flags to ‘True’ or ‘False’,
          which is used to override default options for this example.
          Any option flags not contained in this dictionary are left at
          their default value (as specified by the *note DocTestRunner:
          32da.’s ‘optionflags’).  By default, no options are set.


File: python.info,  Node: DocTestFinder 对象,  Next: DocTestParser 对象,  Prev: Example Objects,  Up: Advanced API

5.26.3.16 DocTestFinder 对象
............................

 -- 类: doctest.DocTestFinder (verbose=False, parser=DocTestParser(),
          recurse=True, exclude_empty=True)

     A processing class used to extract the *note DocTest: 32e9.s that
     are relevant to a given object, from its docstring and the
     docstrings of its contained objects.  *note DocTest: 32e9.s can be
     extracted from modules, classes, functions, methods, staticmethods,
     classmethods, and properties.

     The optional argument `verbose' can be used to display the objects
     searched by the finder.  It defaults to ‘False’ (no output).

     The optional argument `parser' specifies the *note DocTestParser:
     32ca. object (or a drop-in replacement) that is used to extract
     doctests from docstrings.

     If the optional argument `recurse' is false, then *note
     DocTestFinder.find(): 3301. will only examine the given object, and
     not any contained objects.

     If the optional argument `exclude_empty' is false, then *note
     DocTestFinder.find(): 3301. will include tests for objects with
     empty docstrings.

     *note DocTestFinder: 32e4. defines the following method:

      -- 方法: find (obj[, name][, module][, globs][, extraglobs])

          Return a list of the *note DocTest: 32e9.s that are defined by
          `obj'’s docstring, or by any of its contained objects’
          docstrings.

          The optional argument `name' specifies the object’s name; this
          name will be used to construct names for the returned *note
          DocTest: 32e9.s.  If `name' is not specified, then
          ‘obj.__name__’ is used.

          The optional parameter `module' is the module that contains
          the given object.  If the module is not specified or is
          ‘None’, then the test finder will attempt to automatically
          determine the correct module.  The object’s module is used:

             * As a default namespace, if `globs' is not specified.

             * To prevent the DocTestFinder from extracting DocTests
               from objects that are imported from other modules.
               (Contained objects with modules other than `module' are
               ignored.)

             * To find the name of the file containing the object.

             * To help find the line number of the object within its
               file.

          If `module' is ‘False’, no attempt to find the module will be
          made.  This is obscure, of use mostly in testing doctest
          itself: if `module' is ‘False’, or is ‘None’ but cannot be
          found automatically, then all objects are considered to belong
          to the (non-existent) module, so all contained objects will
          (recursively) be searched for doctests.

          The globals for each *note DocTest: 32e9. is formed by
          combining `globs' and `extraglobs' (bindings in `extraglobs'
          override bindings in `globs').  A new shallow copy of the
          globals dictionary is created for each *note DocTest: 32e9.
          If `globs' is not specified, then it defaults to the module’s
          `__dict__', if specified, or ‘{}’ otherwise.  If `extraglobs'
          is not specified, then it defaults to ‘{}’.


File: python.info,  Node: DocTestParser 对象,  Next: DocTestRunner 对象,  Prev: DocTestFinder 对象,  Up: Advanced API

5.26.3.17 DocTestParser 对象
............................

 -- 类: doctest.DocTestParser

     A processing class used to extract interactive examples from a
     string, and use them to create a *note DocTest: 32e9. object.

     *note DocTestParser: 32ca. defines the following methods:

      -- 方法: get_doctest (string, globs, name, filename, lineno)

          Extract all doctest examples from the given string, and
          collect them into a *note DocTest: 32e9. object.

          `globs', `name', `filename', and `lineno' are attributes for
          the new *note DocTest: 32e9. object.  See the documentation
          for *note DocTest: 32e9. for more information.

      -- 方法: get_examples (string, name='<string>')

          Extract all doctest examples from the given string, and return
          them as a list of *note Example: 32ed. objects.  Line numbers
          are 0-based.  The optional argument `name' is a name
          identifying this string, and is only used for error messages.

      -- 方法: parse (string, name='<string>')

          Divide the given string into examples and intervening text,
          and return them as a list of alternating *note Example: 32ed.s
          and strings.  Line numbers for the *note Example: 32ed.s are
          0-based.  The optional argument `name' is a name identifying
          this string, and is only used for error messages.


File: python.info,  Node: DocTestRunner 对象,  Next: OutputChecker 对象,  Prev: DocTestParser 对象,  Up: Advanced API

5.26.3.18 DocTestRunner 对象
............................

 -- 类: doctest.DocTestRunner (checker=None, verbose=None,
          optionflags=0)

     A processing class used to execute and verify the interactive
     examples in a *note DocTest: 32e9.

     The comparison between expected outputs and actual outputs is done
     by an *note OutputChecker: 32d9.  This comparison may be customized
     with a number of option flags; see section *note Option Flags: 845.
     for more information.  If the option flags are insufficient, then
     the comparison may also be customized by passing a subclass of
     *note OutputChecker: 32d9. to the constructor.

     The test runner’s display output can be controlled in two ways.
     First, an output function can be passed to ‘TestRunner.run()’; this
     function will be called with strings that should be displayed.  It
     defaults to ‘sys.stdout.write’.  If capturing the output is not
     sufficient, then the display output can be also customized by
     subclassing DocTestRunner, and overriding the methods *note
     report_start(): 3309, *note report_success(): 330a, *note
     report_unexpected_exception(): 330b, and *note report_failure():
     330c.

     The optional keyword argument `checker' specifies the *note
     OutputChecker: 32d9. object (or drop-in replacement) that should be
     used to compare the expected outputs to the actual outputs of
     doctest examples.

     The optional keyword argument `verbose' controls the *note
     DocTestRunner: 32da.’s verbosity.  If `verbose' is ‘True’, then
     information is printed about each example, as it is run.  If
     `verbose' is ‘False’, then only failures are printed.  If `verbose'
     is unspecified, or ‘None’, then verbose output is used iff the
     command-line switch ‘-v’ is used.

     The optional keyword argument `optionflags' can be used to control
     how the test runner compares expected output to actual output, and
     how it displays failures.  For more information, see section *note
     Option Flags: 845.

     *note DocTestParser: 32ca. defines the following methods:

      -- 方法: report_start (out, test, example)

          Report that the test runner is about to process the given
          example.  This method is provided to allow subclasses of *note
          DocTestRunner: 32da. to customize their output; it should not
          be called directly.

          `example' is the example about to be processed.  `test' is the
          test `containing example'.  `out' is the output function that
          was passed to *note DocTestRunner.run(): 330d.

      -- 方法: report_success (out, test, example, got)

          Report that the given example ran successfully.  This method
          is provided to allow subclasses of *note DocTestRunner: 32da.
          to customize their output; it should not be called directly.

          `example' is the example about to be processed.  `got' is the
          actual output from the example.  `test' is the test containing
          `example'.  `out' is the output function that was passed to
          *note DocTestRunner.run(): 330d.

      -- 方法: report_failure (out, test, example, got)

          Report that the given example failed.  This method is provided
          to allow subclasses of *note DocTestRunner: 32da. to customize
          their output; it should not be called directly.

          `example' is the example about to be processed.  `got' is the
          actual output from the example.  `test' is the test containing
          `example'.  `out' is the output function that was passed to
          *note DocTestRunner.run(): 330d.

      -- 方法: report_unexpected_exception (out, test, example,
               exc_info)

          Report that the given example raised an unexpected exception.
          This method is provided to allow subclasses of *note
          DocTestRunner: 32da. to customize their output; it should not
          be called directly.

          `example' is the example about to be processed.  `exc_info' is
          a tuple containing information about the unexpected exception
          (as returned by *note sys.exc_info(): c67.).  `test' is the
          test containing `example'.  `out' is the output function that
          was passed to *note DocTestRunner.run(): 330d.

      -- 方法: run (test, compileflags=None, out=None, clear_globs=True)

          Run the examples in `test' (a *note DocTest: 32e9. object),
          and display the results using the writer function `out'.

          The examples are run in the namespace ‘test.globs’.  If
          `clear_globs' is true (the default), then this namespace will
          be cleared after the test runs, to help with garbage
          collection.  If you would like to examine the namespace after
          the test completes, then use `clear_globs=False'.

          `compileflags' gives the set of flags that should be used by
          the Python compiler when running the examples.  If not
          specified, then it will default to the set of future-import
          flags that apply to `globs'.

          The output of each example is checked using the *note
          DocTestRunner: 32da.’s output checker, and the results are
          formatted by the ‘DocTestRunner.report_*()’ methods.

      -- 方法: summarize (verbose=None)

          Print a summary of all the test cases that have been run by
          this DocTestRunner, and return a *note named tuple: aab.
          ‘TestResults(failed, attempted)’.

          The optional `verbose' argument controls how detailed the
          summary is.  If the verbosity is not specified, then the *note
          DocTestRunner: 32da.’s verbosity is used.


File: python.info,  Node: OutputChecker 对象,  Prev: DocTestRunner 对象,  Up: Advanced API

5.26.3.19 OutputChecker 对象
............................

 -- 类: doctest.OutputChecker

     A class used to check the whether the actual output from a doctest
     example matches the expected output.  *note OutputChecker: 32d9.
     defines two methods: *note check_output(): 3311, which compares a
     given pair of outputs, and returns ‘True’ if they match; and *note
     output_difference(): 3312, which returns a string describing the
     differences between two outputs.

     *note OutputChecker: 32d9. defines the following methods:

      -- 方法: check_output (want, got, optionflags)

          Return ‘True’ iff the actual output from an example (`got')
          matches the expected output (`want').  These strings are
          always considered to match if they are identical; but
          depending on what option flags the test runner is using,
          several non-exact match types are also possible.  See section
          *note Option Flags: 845. for more information about option
          flags.

      -- 方法: output_difference (example, got, optionflags)

          Return a string describing the differences between the
          expected output for a given example (`example') and the actual
          output (`got').  `optionflags' is the set of option flags used
          to compare `want' and `got'.


File: python.info,  Node: 调试,  Next: Soapbox,  Prev: Advanced API,  Up: doctest --- 测试交互性的Python示例

5.26.3.20 调试
..............

Doctest provides several mechanisms for debugging doctest examples:

   * Several functions convert doctests to executable Python programs,
     which can be run under the Python debugger, *note pdb: ca.

   * The *note DebugRunner: 3315. class is a subclass of *note
     DocTestRunner: 32da. that raises an exception for the first failing
     example, containing information about that example.  This
     information can be used to perform post-mortem debugging on the
     example.

   * The *note unittest: 11c. cases generated by *note DocTestSuite():
     6d6. support the *note debug(): 3316. method defined by *note
     unittest.TestCase: 907.

   * You can add a call to *note pdb.set_trace(): 3ca. in a doctest
     example, and you’ll drop into the Python debugger when that line is
     executed.  Then you can inspect current values of variables, and so
     on.  For example, suppose ‘a.py’ contains just this module
     docstring:

          """
          >>> def f(x):
          ...     g(x*2)
          >>> def g(x):
          ...     print(x+3)
          ...     import pdb; pdb.set_trace()
          >>> f(3)
          9
          """

     Then an interactive Python session may look like this:

          >>> import a, doctest
          >>> doctest.testmod(a)
          --Return--
          > <doctest a[1]>(3)g()->None
          -> import pdb; pdb.set_trace()
          (Pdb) list
            1     def g(x):
            2         print(x+3)
            3  ->     import pdb; pdb.set_trace()
          [EOF]
          (Pdb) p x
          6
          (Pdb) step
          --Return--
          > <doctest a[0]>(2)f()->None
          -> g(x*2)
          (Pdb) list
            1     def f(x):
            2  ->     g(x*2)
          [EOF]
          (Pdb) p x
          3
          (Pdb) step
          --Return--
          > <doctest a[2]>(1)?()->None
          -> f(3)
          (Pdb) cont
          (0, 3)
          >>>

Functions that convert doctests to Python code, and possibly run the
synthesized code under the debugger:

 -- 函数: doctest.script_from_examples (s)

     Convert text with examples to a script.

     Argument `s' is a string containing doctest examples.  The string
     is converted to a Python script, where doctest examples in `s' are
     converted to regular code, and everything else is converted to
     Python comments.  The generated script is returned as a string.
     For example,

          import doctest
          print(doctest.script_from_examples(r"""
              Set x and y to 1 and 2.
              >>> x, y = 1, 2

              Print their sum:
              >>> print(x+y)
              3
          """))

     displays:

          # Set x and y to 1 and 2.
          x, y = 1, 2
          #
          # Print their sum:
          print(x+y)
          # Expected:
          ## 3

     This function is used internally by other functions (see below),
     but can also be useful when you want to transform an interactive
     Python session into a Python script.

 -- 函数: doctest.testsource (module, name)

     Convert the doctest for an object to a script.

     Argument `module' is a module object, or dotted name of a module,
     containing the object whose doctests are of interest.  Argument
     `name' is the name (within the module) of the object with the
     doctests of interest.  The result is a string, containing the
     object’s docstring converted to a Python script, as described for
     *note script_from_examples(): 3317. above.  For example, if module
     ‘a.py’ contains a top-level function ‘f()’, then

          import a, doctest
          print(doctest.testsource(a, "a.f"))

     prints a script version of function ‘f()’’s docstring, with
     doctests converted to code, and the rest placed in comments.

 -- 函数: doctest.debug (module, name, pm=False)

     Debug the doctests for an object.

     The `module' and `name' arguments are the same as for function
     *note testsource(): 3318. above.  The synthesized Python script for
     the named object’s docstring is written to a temporary file, and
     then that file is run under the control of the Python debugger,
     *note pdb: ca.

     A shallow copy of ‘module.__dict__’ is used for both local and
     global execution context.

     Optional argument `pm' controls whether post-mortem debugging is
     used.  If `pm' has a true value, the script file is run directly,
     and the debugger gets involved only if the script terminates via
     raising an unhandled exception.  If it does, then post-mortem
     debugging is invoked, via *note pdb.post_mortem(): d4d, passing the
     traceback object from the unhandled exception.  If `pm' is not
     specified, or is false, the script is run under the debugger from
     the start, via passing an appropriate *note exec(): c4c. call to
     *note pdb.run(): 3319.

 -- 函数: doctest.debug_src (src, pm=False, globs=None)

     Debug the doctests in a string.

     This is like function *note debug(): 3316. above, except that a
     string containing doctest examples is specified directly, via the
     `src' argument.

     Optional argument `pm' has the same meaning as in function *note
     debug(): 3316. above.

     Optional argument `globs' gives a dictionary to use as both local
     and global execution context.  If not specified, or ‘None’, an
     empty dictionary is used.  If specified, a shallow copy of the
     dictionary is used.

The *note DebugRunner: 3315. class, and the special exceptions it may
raise, are of most interest to testing framework authors, and will only
be sketched here.  See the source code, and especially *note
DebugRunner: 3315.’s docstring (which is a doctest!)  for more details:

 -- 类: doctest.DebugRunner (checker=None, verbose=None, optionflags=0)

     A subclass of *note DocTestRunner: 32da. that raises an exception
     as soon as a failure is encountered.  If an unexpected exception
     occurs, an *note UnexpectedException: 331b. exception is raised,
     containing the test, the example, and the original exception.  If
     the output doesn’t match, then a *note DocTestFailure: 331c.
     exception is raised, containing the test, the example, and the
     actual output.

     For information about the constructor parameters and methods, see
     the documentation for *note DocTestRunner: 32da. in section *note
     Advanced API: 32ec.

There are two exceptions that may be raised by *note DebugRunner: 3315.
instances:

 -- 例外: doctest.DocTestFailure (test, example, got)

     An exception raised by *note DocTestRunner: 32da. to signal that a
     doctest example’s actual output did not match its expected output.
     The constructor arguments are used to initialize the attributes of
     the same names.

*note DocTestFailure: 331c. defines the following attributes:

 -- 属性: DocTestFailure.test

     The *note DocTest: 32e9. object that was being run when the example
     failed.

 -- 属性: DocTestFailure.example

     The *note Example: 32ed. that failed.

 -- 属性: DocTestFailure.got

     The example’s actual output.

 -- 例外: doctest.UnexpectedException (test, example, exc_info)

     An exception raised by *note DocTestRunner: 32da. to signal that a
     doctest example raised an unexpected exception.  The constructor
     arguments are used to initialize the attributes of the same names.

*note UnexpectedException: 331b. defines the following attributes:

 -- 属性: UnexpectedException.test

     The *note DocTest: 32e9. object that was being run when the example
     failed.

 -- 属性: UnexpectedException.example

     The *note Example: 32ed. that failed.

 -- 属性: UnexpectedException.exc_info

     A tuple containing information about the unexpected exception, as
     returned by *note sys.exc_info(): c67.


File: python.info,  Node: Soapbox,  Prev: 调试,  Up: doctest --- 测试交互性的Python示例

5.26.3.21 Soapbox
.................

As mentioned in the introduction, *note doctest: 67. has grown to have
three primary uses:

  1. Checking examples in docstrings.

  2. Regression testing.

  3. Executable documentation / literate testing.

These uses have different requirements, and it is important to
distinguish them.  In particular, filling your docstrings with obscure
test cases makes for bad documentation.

When writing a docstring, choose docstring examples with care.  There’s
an art to this that needs to be learned—it may not be natural at first.
Examples should add genuine value to the documentation.  A good example
can often be worth many words.  If done with care, the examples will be
invaluable for your users, and will pay back the time it takes to
collect them many times over as the years go by and things change.  I’m
still amazed at how often one of my *note doctest: 67. examples stops
working after a "harmless" change.

Doctest also makes an excellent tool for regression testing, especially
if you don’t skimp on explanatory text.  By interleaving prose and
examples, it becomes much easier to keep track of what’s actually being
tested, and why.  When a test fails, good prose can make it much easier
to figure out what the problem is, and how it should be fixed.  It’s
true that you could write extensive comments in code-based testing, but
few programmers do.  Many have found that using doctest approaches
instead leads to much clearer tests.  Perhaps this is simply because
doctest makes writing prose a little easier than writing code, while
writing comments in code is a little harder.  I think it goes deeper
than just that: the natural attitude when writing a doctest-based test
is that you want to explain the fine points of your software, and
illustrate them with examples.  This in turn naturally leads to test
files that start with the simplest features, and logically progress to
complications and edge cases.  A coherent narrative is the result,
instead of a collection of isolated functions that test isolated bits of
functionality seemingly at random.  It’s a different attitude, and
produces different results, blurring the distinction between testing and
explaining.

Regression testing is best confined to dedicated objects or files.
There are several options for organizing tests:

   * Write text files containing test cases as interactive examples, and
     test the files using *note testfile(): 32c1. or *note
     DocFileSuite(): 32e8.  This is recommended, although is easiest to
     do for new projects, designed from the start to use doctest.

   * Define functions named ‘_regrtest_topic’ that consist of single
     docstrings, containing test cases for the named topics.  These
     functions can be included in the same file as the module, or
     separated out into a separate test file.

   * Define a ‘__test__’ dictionary mapping from regression test topics
     to docstrings containing test cases.

When you have placed your tests in a module, the module can itself be
the test runner.  When a test fails, you can arrange for your test
runner to re-run only the failing doctest while you debug the problem.
Here is a minimal example of such a test runner:

     if __name__ == '__main__':
         import doctest
         flags = doctest.REPORT_NDIFF|doctest.FAIL_FAST
         if len(sys.argv) > 1:
             name = sys.argv[1]
             if name in globals():
                 obj = globals()[name]
             else:
                 obj = __test__[name]
             doctest.run_docstring_examples(obj, globals(), name=name,
                                            optionflags=flags)
         else:
             fail, total = doctest.testmod(optionflags=flags)
             print("{} failures out of {} tests".format(fail, total))

备注
....


File: python.info,  Node: unittest --- 单元测试框架,  Next: unittest mock --- 模拟对象库,  Prev: doctest --- 测试交互性的Python示例,  Up: 开发工具

5.26.4 ‘unittest’ — 单元测试框架
--------------------------------

`源代码：' Lib/unittest/__init__.py(1)

__________________________________________________________________

（如果你已经对测试的概念比较熟悉了，你可能想直接跳转到这一部分 *note
断言方法: 3327.。）

*note unittest: 11c. 单元测试框架是受到 JUnit 的启发，与其他语言中的主流
单元测试框架有着相似的风格。其支持测试自动化，配置共享和关机代码测试。支
持将测试样例聚合到测试集中，并将测试与报告框架独立。

为了实现这些，*note unittest: 11c. 通过面向对象的方式支持了一些重要的概
念。

测试脚手架

     `test fixture' 表示为了开展一项或多项测试所需要进行的准备工作，以及
     所有相关的清理操作。举个例子，这可能包含创建临时或代理的数据库、目
     录，再或者启动一个服务器进程。

测试用例

     一个测试用例是一个独立的测试单元。它检查输入特定的数据时的响应。
     *note unittest: 11c. 提供一个基类： *note TestCase: 907. ，用于新建
     测试用例。

测试套件

     `test suite' 是一系列的测试用例，或测试套件，或两者皆有。它用于归档
     需要一起执行的测试。

测试运行器（test runner）

     `test runner' 是一个用于执行和输出测试结果的组件。这个运行器可能使
     用图形接口、文本接口，或返回一个特定的值表示运行测试的结果。

参见
....

*note doctest: 67. — 文档测试模块

     另一个风格完全不同的测试模块。

简单 Smalltalk 测试：便用模式(2)

     Kent Beck 有关使用 *note unittest: 11c. 所共享的模式的测试框架的原
     创论文。

pytest(3)

     第三方单元测试框架，提供轻量化的语法来编写测试，例如：‘assert
     func(10) == 42’。

Python 测试工具分类

     一个 Python 测试工具的详细列表，包含测试框架和模拟对象库。

Python 中的测试 邮件列表

     一个讨论 Python 中的测试和测试工具的特别兴趣小组。

随 Python 源代码分发的脚本 ‘Tools/unittestgui/unittestgui.py’ 是一个一个
用于发现和执行测试的用户图形界面工具。这为了极大地方便单元测试新手使用。
建议在生产环境中测试应由一个持续集成系统来启动，如 Buildbot(4),
Jenkins(5) 或者‘Travis-CI <‘https://travis-ci.com’>‘_, 或者 AppVeyor(6)。

* Menu:

* 基本实例::
* 命令行界面: 命令行界面<5>.
* 探索性测试::
* 组织你的测试代码::
* 复用已有的测试代码::
* 跳过测试与预计的失败::
* Distinguishing test iterations using subtests::
* 类与函数::
* Class and Module Fixtures::
* 信号处理::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/unittest/__init__.py

   (2) 
https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm

   (3) https://docs.pytest.org/

   (4) https://buildbot.net/

   (5) https://jenkins.io/

   (6) https://www.appveyor.com/


File: python.info,  Node: 基本实例,  Next: 命令行界面<5>,  Up: unittest --- 单元测试框架

5.26.4.1 基本实例
.................

*note unittest: 11c. 模块提供了一系列创建和运行测试的工具。这一段落演示
了这些工具的一小部分，但也足以满足大部分用户的需求。

这是一段简短的代码，来测试三种字符串方法:

     import unittest

     class TestStringMethods(unittest.TestCase):

         def test_upper(self):
             self.assertEqual('foo'.upper(), 'FOO')

         def test_isupper(self):
             self.assertTrue('FOO'.isupper())
             self.assertFalse('Foo'.isupper())

         def test_split(self):
             s = 'hello world'
             self.assertEqual(s.split(), ['hello', 'world'])
             # check that s.split fails when the separator is not a string
             with self.assertRaises(TypeError):
                 s.split(2)

     if __name__ == '__main__':
         unittest.main()

继承 *note unittest.TestCase: 907. 就创建了一个测试样例。上述三个独立的
测试是三个类的方法，这些方法的命名都以 ‘test’ 开头。 这个命名约定告诉测
试运行者类的哪些方法表示测试。

每个测试的关键是：调用 *note assertEqual(): bbd. 来检查预期的输出； 调用
*note assertTrue(): bbc. 或 *note assertFalse(): ccf. 来验证一个条件；调
用 *note assertRaises(): ac2. 来验证抛出了一个特定的异常。使用这些方法而
不是 *note assert: e0e. 语句是为了让测试运行者能聚合所有的测试结果并产生
结果报告。

通过 *note setUp(): cd3. 和 *note tearDown(): cd4. 方法，可以设置测试开
始前与完成后需要执行的指令。 在 *note 组织你的测试代码: 332a. 中，对此有
更为详细的描述。

最后的代码块中，演示了运行测试的一个简单的方法。 *note unittest.main():
90a. 提供了一个测试脚本的命令行接口。当在命令行运行该测试脚本，上文的脚
本生成如以下格式的输出:

     ...
     ----------------------------------------------------------------------
     Ran 3 tests in 0.000s

     OK

在调用测试脚本时添加 ‘-v’ 参数使 *note unittest.main(): 90a. 显示更为详
细的信息，生成如以下形式的输出:

     test_isupper (__main__.TestStringMethods) ... ok
     test_split (__main__.TestStringMethods) ... ok
     test_upper (__main__.TestStringMethods) ... ok

     ----------------------------------------------------------------------
     Ran 3 tests in 0.001s

     OK

以上例子演示了 *note unittest: 11c. 中最常用的、足够满足许多日常测试需求
的特性。文档的剩余部分详述该框架的完整特性。


File: python.info,  Node: 命令行界面<5>,  Next: 探索性测试,  Prev: 基本实例,  Up: unittest --- 单元测试框架

5.26.4.2 命令行界面
...................

unittest 模块可以通过命令行运行模块、类和独立测试方法的测试:

     python -m unittest test_module1 test_module2
     python -m unittest test_module.TestClass
     python -m unittest test_module.TestClass.test_method

你可以传入模块名、类或方法名或他们的任意组合。

同样的，测试模块可以通过文件路径指定:

     python -m unittest tests/test_something.py

这样就可以使用 shell 的文件名补全指定测试模块。所指定的文件仍需要可以被
作为模块导入。路径通过去除 ’.py’ 、把分隔符转换为 ’.’ 转换为模块名。若你
需要执行不能被作为模块导入的测试文件，你需要直接执行该测试文件。

在运行测试时，你可以通过添加 -v 参数获取更详细（更多的冗余）的信息。

     python -m unittest -v test_module

当运行时不包含参数，开始 *note 探索性测试: 332d.

     python -m unittest

用于获取命令行选项列表：

     python -m unittest -h

在 3.2 版更改: 在早期版本中，只支持运行独立的测试方法，而不支持模块和类
。

* Menu:

* 命令行选项: 命令行选项<5>.


File: python.info,  Node: 命令行选项<5>,  Up: 命令行界面<5>

5.26.4.3 命令行选项
...................

‘unittest’ supports these command-line options:

 -- 程序选项: -b, --buffer

     在测试运行时，标准输出流与标准错误流会被放入缓冲区。成功的测试的运
     行时输出会被丢弃；测试不通过时，测试运行中的输出会正常显示，错误会
     被加入到测试失败信息。

 -- 程序选项: -c, --catch

     当测试正在运行时， ‘Control-C’ 会等待当前测试完成，并在完成后报告已
     执行的测试的结果。当再次按下 ‘Control-C’ 时，引发平常的 *note
     KeyboardInterrupt: 198. 异常。

     See *note Signal Handling: 332f. for the functions that provide
     this functionality.

 -- 程序选项: -f, --failfast

     当出现第一个错误或者失败时，停止运行测试。

 -- 程序选项: -k

     只运行匹配模式或子串的测试方法和类。可以多次使用这个选项，以便包含
     匹配子串的所有测试用例。

     包含通配符（*）的模式使用 *note fnmatch.fnmatchcase(): 1c8c. 对测试
     名称进行匹配。另外，该匹配是大小写敏感的。

     模式对测试加载器导入的测试方法全名进行匹配。

     例如，‘-k foo’ 可以匹配到 ‘foo_tests.SomeTest.test_something’ 和
     ‘bar_tests.SomeTest.test_foo’ ，但是不能匹配到
     ‘bar_tests.FooTest.test_something’ 。

 -- 程序选项: --locals

     在回溯中显示局部变量。

3.2 新版功能: 添加命令行选项 ‘-b’, ‘-c’ 和 ‘-f’ 。

3.5 新版功能: 命令行选项 ‘--locals’ 。

3.7 新版功能: 命令行选项 ‘-k’ 。

命令行亦可用于探索性测试，以运行一个项目的所有测试或其子集。


File: python.info,  Node: 探索性测试,  Next: 组织你的测试代码,  Prev: 命令行界面<5>,  Up: unittest --- 单元测试框架

5.26.4.4 探索性测试
...................

3.2 新版功能.

Unittest支持简单的测试搜索。若需要使用探索性测试，所有的测试文件必须是
*note modules: 128d. 或 *note packages: 129a. （包括 *note namespace
packages: 14c3. )并可从项目根目录导入（即它们的文件名必须是有效的 *note
identifiers: 13e4. ）。

探索性测试在 *note TestLoader.discover(): 90c. 中实现，但也可以通过命令
行使用。它在命令行中的基本用法如下：

     cd project_directory
     python -m unittest discover

     注解: 方便起见， ‘python -m unittest’ 与 ‘python -m unittest
     discover’ 等价。如果你需要向探索性测试传入参数，必须显式地使用
     ‘discover’ 子命令。

‘discover’ 有以下选项：

 -- 程序选项: -v, --verbose

     更详细地输出结果。

 -- 程序选项: -s, --start-directory directory

     开始进行搜索的目录(默认值为当前目录 ‘.’ )。

 -- 程序选项: -p, --pattern pattern

     用于匹配测试文件的模式（默认为 ‘test*.py’ ）。

 -- 程序选项: -t, --top-level-directory directory

     指定项目的最上层目录（通常为开始时所在目录）。

*note -s: 3334. ，*note -p: 3335. 和 *note -t: 3336. 选项可以按顺序作为
位置参数传入。以下两条命令是等价的：

     python -m unittest discover -s project_directory -p "*_test.py"
     python -m unittest discover project_directory "*_test.py"

正如可以传入路径那样，传入一个包名作为起始目录也是可行的，如
‘myproject.subpackage.test’ 。你提供的包名会被导入，它在文件系统中的位置
会被作为起始目录。

     警告: 探索性测试通过导入测试对测试进行加载。在找到所有你指定的开始
     目录下的所有测试文件后，它把路径转换为包名并进行导入。如
     ‘foo/bar/baz.py’ 会被导入为 ‘foo.bar.baz’ 。

     如果你有一个全局安装的包，并尝试对这个包的副本进行探索性测试，可能
     会从错误的地方开始导入。如果出现这种情况，测试会输出警告并退出。

     如果你使用包名而不是路径作为开始目录，搜索时会假定它导入的是你想要
     的目录，所以你不会收到警告。

测试模块和包可以通过 *note load_tests protocol: 3337. 自定义测试的加载和
搜索。

在 3.4 版更改: Test discovery supports *note namespace packages: 14c3.
for start directory.  Note that you need to the top level directory too.
(e.g.  ‘python -m unittest discover -s root/namespace -t root’).


File: python.info,  Node: 组织你的测试代码,  Next: 复用已有的测试代码,  Prev: 探索性测试,  Up: unittest --- 单元测试框架

5.26.4.5 组织你的测试代码
.........................

单元测试的构建单位是 `test cases' ：独立的、包含执行条件与正确性检查的方
案。在 *note unittest: 11c. 中，测试用例表示为 *note unittest.TestCase:
907. 的实例。通过编写 *note TestCase: 907. 的子类或使用 *note
FunctionTestCase: 3339. 编写你自己的测试用例。

一个 *note TestCase: 907. 实例的测试代码必须是完全自含的，因此它可以独立
运行，或与其它任意组合任意数量的测试用例一起运行。

*note TestCase: 907. 的最简单的子类需要实现一个测试方法（例如一个命名以
‘test’ 开头的方法）以执行特定的测试代码：

     import unittest

     class DefaultWidgetSizeTestCase(unittest.TestCase):
         def test_default_widget_size(self):
             widget = Widget('The widget')
             self.assertEqual(widget.size(), (50, 50))

可以看到，为了进行测试，我们使用了基类 *note TestCase: 907. 提供的其中一
个 ‘assert*()’ 方法。若测试不通过，将会引发一个带有说明信息的异常，并且
*note unittest: 11c. 会将这个测试用例标记为测试不通过。任何其它类型的异
常将会被当做错误处理。

可能同时存在多个前置操作相同的测试，我们可以把测试的前置操作从测试代码中
拆解出来，并实现测试前置方法 *note setUp(): cd3. 。在运行测试时，测试框
架会自动地为每个单独测试调用前置方法。

     import unittest

     class WidgetTestCase(unittest.TestCase):
         def setUp(self):
             self.widget = Widget('The widget')

         def test_default_widget_size(self):
             self.assertEqual(self.widget.size(), (50,50),
                              'incorrect default size')

         def test_widget_resize(self):
             self.widget.resize(100,150)
             self.assertEqual(self.widget.size(), (100,150),
                              'wrong size after resize')

     注解: 多个测试运行的顺序由内置字符串排序方法对测试名进行排序的结果
     决定。

在测试运行时，若 *note setUp(): cd3. 方法引发异常，测试框架会认为测试发
生了错误，因此测试方法不会被运行。

相似的，我们提供了一个 *note tearDown(): cd4. 方法在测试方法运行后进行清
理工作。

     import unittest

     class WidgetTestCase(unittest.TestCase):
         def setUp(self):
             self.widget = Widget('The widget')

         def tearDown(self):
             self.widget.dispose()

若 *note setUp(): cd3. 成功运行，无论测试方法是否成功，都会运行 *note
tearDown(): cd4. 。

这样的一个测试代码运行的环境被称为 `test fixture' 。一个新的 TestCase 实
例作为一个测试脚手架，用于运行各个独立的测试方法。在运行每个测试时，
*note setUp(): cd3. 、*note tearDown(): cd4. 和 ‘__init__()’ 会被调用一
次。

建议你根据所测试的功能，将测试用 TestCase 实现集合起来。*note unittest:
11c. 为此提供了机制：`test suite'，以 *note unittest: 11c. 的类 *note
TestSuite: 6d7. 为代表。大部分情况下，调用 *note unittest.main(): 90a. 即
可，并且它会为你集合所有模块的测试用例并执行。

然而，如果你需要自定义你的测试套件的话，你可以参考以下方法组织你的测试：

     def suite():
         suite = unittest.TestSuite()
         suite.addTest(WidgetTestCase('test_default_widget_size'))
         suite.addTest(WidgetTestCase('test_widget_resize'))
         return suite

     if __name__ == '__main__':
         runner = unittest.TextTestRunner()
         runner.run(suite())

你可以把测试用例和测试套件放在与被测试代码相同的模块中（比如
‘widget.py’），但将测试代码放在单独的模块中（比如 ‘test_widget.py’）有几
个优势。

   * 测试模块可以从命令行被独立调用。

   * 更容易在分发的代码中剥离测试代码。

   * 降低没有好理由的情况下修改测试代码以通过测试的诱惑。

   * 测试代码应比被测试代码更少地被修改。

   * 被测试代码可以更容易地被重构。

   * 对用 C 语言写成的模块无论如何都得单独写成一个模块，为什么不保持一致
     呢？

   * 如果测试策略发生了改变，没有必要修改源代码。


File: python.info,  Node: 复用已有的测试代码,  Next: 跳过测试与预计的失败,  Prev: 组织你的测试代码,  Up: unittest --- 单元测试框架

5.26.4.6 复用已有的测试代码
...........................

一些用户希望直接使用 *note unittest: 11c. 运行已有的测试代码，而不需要把
已有的每个测试函数转化为一个 *note TestCase: 907. 的子类。

因此， *note unittest: 11c. 提供 *note FunctionTestCase: 3339. 类。这个
*note TestCase: 907. 的子类可用于打包已有的测试函数，并支持设置前置与后
置函数。

假定有一个测试函数：

     def testSomething():
         something = makeSomething()
         assert something.name is not None
         # ...

可以创建等价的测试用例如下，其中前置和后置方法是可选的。

     testcase = unittest.FunctionTestCase(testSomething,
                                          setUp=makeSomethingDB,
                                          tearDown=deleteSomethingDB)

     注解: 可以用 *note FunctionTestCase: 3339. 快速将现有的测试转换成基
     于 *note unittest: 11c. 的测试，但不推荐。花点时间继承 *note
     TestCase: 907. 会让以后重构测试无比轻松。

In some cases, the existing tests may have been written using the *note
doctest: 67. module.  If so, *note doctest: 67. provides a
‘DocTestSuite’ class that can automatically build *note
unittest.TestSuite: 6d7. instances from the existing *note doctest:
67.-based tests.


File: python.info,  Node: 跳过测试与预计的失败,  Next: Distinguishing test iterations using subtests,  Prev: 复用已有的测试代码,  Up: unittest --- 单元测试框架

5.26.4.7 跳过测试与预计的失败
.............................

3.1 新版功能.

Unittest 支持跳过单个或整组的测试用例。它还支持把测试标注成“预期失败”的
测试。这些坏测试会失败，但不会算进 *note TestResult: ac7. 的失败里。

Skipping a test is simply a matter of using the *note skip(): f90. *note
decorator: 284. or one of its conditional variants, calling *note
TestCase.skipTest(): 333e. within a *note setUp(): cd3. or test method,
or raising *note SkipTest: 90b. directly.

跳过测试的基本用法如下:

     class MyTestCase(unittest.TestCase):

         @unittest.skip("demonstrating skipping")
         def test_nothing(self):
             self.fail("shouldn't happen")

         @unittest.skipIf(mylib.__version__ < (1, 3),
                          "not supported in this library version")
         def test_format(self):
             # Tests that work for only a certain version of the library.
             pass

         @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
         def test_windows_support(self):
             # windows specific testing code
             pass

         def test_maybe_skipped(self):
             if not external_resource_available():
                 self.skipTest("external resource not available")
             # test code that depends on the external resource
             pass

在啰嗦模式下运行以上测试例子时，程序输出如下：

     test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
     test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
     test_maybe_skipped (__main__.MyTestCase) ... skipped 'external resource not available'
     test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'

     ----------------------------------------------------------------------
     Ran 4 tests in 0.005s

     OK (skipped=4)

跳过测试类的写法跟跳过测试方法的写法相似:

     @unittest.skip("showing class skipping")
     class MySkippedTestCase(unittest.TestCase):
         def test_not_run(self):
             pass

*note TestCase.setUp(): cd3. 也可以跳过测试。可以用于所需资源不可用的情
况下跳过接下来的测试。

使用 *note expectedFailure(): 333f. 装饰器表明这个测试预计失败。:

     class ExpectedFailureTestCase(unittest.TestCase):
         @unittest.expectedFailure
         def test_fail(self):
             self.assertEqual(1, 0, "broken")

It’s easy to roll your own skipping decorators by making a decorator
that calls *note skip(): f90. on the test when it wants it to be
skipped.  This decorator skips the test unless the passed object has a
certain attribute:

     def skipUnlessHasattr(obj, attr):
         if hasattr(obj, attr):
             return lambda func: func
         return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))

以下的装饰器和异常实现了跳过测试和预期失败两种功能：

 -- 函数: @unittest.skip (reason)

     跳过被此装饰器装饰的测试。 `reason' 为测试被跳过的原因。

 -- 函数: @unittest.skipIf (condition, reason)

     当 `condition' 为真时，跳过被装饰的测试。

 -- 函数: @unittest.skipUnless (condition, reason)

     跳过被装饰的测试，除非 `condition' 为真。

 -- 函数: @unittest.expectedFailure

     Mark the test as an expected failure or error.  If the test fails
     or errors it will be considered a success.  If the test passes, it
     will be considered a failure.

 -- 例外: unittest.SkipTest (reason)

     引发此异常以跳过一个测试。

     通常来说，你可以使用 *note TestCase.skipTest(): 333e. 或其中一个跳
     过测试的装饰器实现跳过测试的功能，而不是直接引发此异常。

被跳过的测试的 *note setUp(): cd3. 和 *note tearDown(): cd4. 不会被运行
。被跳过的类的 *note setUpClass(): 24d. 和 *note tearDownClass(): cd1. 不
会被运行。被跳过的模组的 ‘setUpModule()’ 和 ‘tearDownModule()’ 不会被运
行。


File: python.info,  Node: Distinguishing test iterations using subtests,  Next: 类与函数,  Prev: 跳过测试与预计的失败,  Up: unittest --- 单元测试框架

5.26.4.8 Distinguishing test iterations using subtests
......................................................

3.4 新版功能.

When there are very small differences among your tests, for instance
some parameters, unittest allows you to distinguish them inside the body
of a test method using the *note subTest(): 908. context manager.

例如，以下测试:

     class NumbersTest(unittest.TestCase):

         def test_even(self):
             """
             Test that numbers between 0 and 5 are all even.
             """
             for i in range(0, 6):
                 with self.subTest(i=i):
                     self.assertEqual(i % 2, 0)

可以得到以下输出:

     ======================================================================
     FAIL: test_even (__main__.NumbersTest) (i=1)
     ----------------------------------------------------------------------
     Traceback (most recent call last):
       File "subtests.py", line 32, in test_even
         self.assertEqual(i % 2, 0)
     AssertionError: 1 != 0

     ======================================================================
     FAIL: test_even (__main__.NumbersTest) (i=3)
     ----------------------------------------------------------------------
     Traceback (most recent call last):
       File "subtests.py", line 32, in test_even
         self.assertEqual(i % 2, 0)
     AssertionError: 1 != 0

     ======================================================================
     FAIL: test_even (__main__.NumbersTest) (i=5)
     ----------------------------------------------------------------------
     Traceback (most recent call last):
       File "subtests.py", line 32, in test_even
         self.assertEqual(i % 2, 0)
     AssertionError: 1 != 0

如果不使用子测试，程序遇到第一次错误之后就会停止。而且因为‘‘i‘‘的值不显
示，错误也更难找。

     ======================================================================
     FAIL: test_even (__main__.NumbersTest)
     ----------------------------------------------------------------------
     Traceback (most recent call last):
       File "subtests.py", line 32, in test_even
         self.assertEqual(i % 2, 0)
     AssertionError: 1 != 0


File: python.info,  Node: 类与函数,  Next: Class and Module Fixtures,  Prev: Distinguishing test iterations using subtests,  Up: unittest --- 单元测试框架

5.26.4.9 类与函数
.................

本节深入介绍了 *note unittest: 11c. 的 API。

* Menu:

* 测试用例::
* Grouping tests::
* Loading and running tests::


File: python.info,  Node: 测试用例,  Next: Grouping tests,  Up: 类与函数

5.26.4.10 测试用例
..................

 -- 类: unittest.TestCase (methodName='runTest')

     Instances of the *note TestCase: 907. class represent the logical
     test units in the *note unittest: 11c. universe.  This class is
     intended to be used as a base class, with specific tests being
     implemented by concrete subclasses.  This class implements the
     interface needed by the test runner to allow it to drive the tests,
     and methods that the test code can use to check for and report
     various kinds of failure.

     Each instance of *note TestCase: 907. will run a single base
     method: the method named `methodName'.  In most uses of *note
     TestCase: 907, you will neither change the `methodName' nor
     reimplement the default ‘runTest()’ method.

     在 3.2 版更改: *note TestCase: 907. can be instantiated
     successfully without providing a `methodName'.  This makes it
     easier to experiment with *note TestCase: 907. from the interactive
     interpreter.

     *note TestCase: 907. instances provide three groups of methods: one
     group used to run the test, another used by the test implementation
     to check conditions and report failures, and some inquiry methods
     allowing information about the test itself to be gathered.

     第一组（用于运行测试的）方法是：

      -- 方法: setUp ()

          Method called to prepare the test fixture.  This is called
          immediately before calling the test method; other than *note
          AssertionError: 103e. or *note SkipTest: 90b, any exception
          raised by this method will be considered an error rather than
          a test failure.  The default implementation does nothing.

      -- 方法: tearDown ()

          Method called immediately after the test method has been
          called and the result recorded.  This is called even if the
          test method raised an exception, so the implementation in
          subclasses may need to be particularly careful about checking
          internal state.  Any exception, other than *note
          AssertionError: 103e. or *note SkipTest: 90b, raised by this
          method will be considered an additional error rather than a
          test failure (thus increasing the total number of reported
          errors).  This method will only be called if the *note
          setUp(): cd3. succeeds, regardless of the outcome of the test
          method.  The default implementation does nothing.

      -- 方法: setUpClass ()

          A class method called before tests in an individual class are
          run.  ‘setUpClass’ is called with the class as the only
          argument and must be decorated as a *note classmethod(): 1d9.:

               @classmethod
               def setUpClass(cls):
                   ...

          查看 *note Class and Module Fixtures: 3347. 获取更详细的说明。

          3.2 新版功能.

      -- 方法: tearDownClass ()

          A class method called after tests in an individual class have
          run.  ‘tearDownClass’ is called with the class as the only
          argument and must be decorated as a *note classmethod(): 1d9.:

               @classmethod
               def tearDownClass(cls):
                   ...

          查看 *note Class and Module Fixtures: 3347. 获取更详细的说明。

          3.2 新版功能.

      -- 方法: run (result=None)

          Run the test, collecting the result into the *note TestResult:
          ac7. object passed as `result'.  If `result' is omitted or
          ‘None’, a temporary result object is created (by calling the
          *note defaultTestResult(): 3348. method) and used.  The result
          object is returned to *note run(): ac6.’s caller.

          The same effect may be had by simply calling the *note
          TestCase: 907. instance.

          在 3.3 版更改: Previous versions of ‘run’ did not return the
          result.  Neither did calling an instance.

      -- 方法: skipTest (reason)

          Calling this during a test method or *note setUp(): cd3. skips
          the current test.  See *note 跳过测试与预计的失败: 333d. for
          more information.

          3.1 新版功能.

      -- 方法: subTest (msg=None, **params)

          Return a context manager which executes the enclosed code
          block as a subtest.  `msg' and `params' are optional,
          arbitrary values which are displayed whenever a subtest fails,
          allowing you to identify them clearly.

          A test case can contain any number of subtest declarations,
          and they can be arbitrarily nested.

          查看 *note Distinguishing test iterations using subtests: 909.
          获取更详细的信息。

          3.4 新版功能.

      -- 方法: debug ()

          Run the test without collecting the result.  This allows
          exceptions raised by the test to be propagated to the caller,
          and can be used to support running tests under a debugger.
     The *note TestCase: 907. class provides several assert methods to
     check for and report failures.  The following table lists the most
     commonly used methods (see the tables below for more assert
     methods):

     Method                                        Checks that                       New in
                                                                                     
     ----------------------------------------------------------------------------------------------------
                                                                                     
     *note assertEqual(a, b): bbd.                 ‘a == b’
                                                   
                                                                                     
     *note assertNotEqual(a, b): bbe.              ‘a != b’
                                                   
                                                                                     
     *note assertTrue(x): bbc.                     ‘bool(x) is True’
                                                   
                                                                                     
     *note assertFalse(x): ccf.                    ‘bool(x) is False’
                                                   
                                                                                     
     *note assertIs(a, b): cd7.                    ‘a is b’                          3.1
                                                                                     
                                                                                     
     *note assertIsNot(a, b): cd8.                 ‘a is not b’                      3.1
                                                                                     
                                                                                     
     *note assertIsNone(x): cd5.                   ‘x is None’                       3.1
                                                                                     
                                                                                     
     *note assertIsNotNone(x): cd6.                ‘x is not None’                   3.1
                                                                                     
                                                                                     
     *note assertIn(a, b): ce0.                    ‘a in b’                          3.1
                                                                                     
                                                                                     
     *note assertNotIn(a, b): ce1.                 ‘a not in b’                      3.1
                                                                                     
                                                                                     
     *note assertIsInstance(a, b): cd9.            ‘isinstance(a, b)’                3.2
                                                                                     
                                                                                     
     *note assertNotIsInstance(a, b): cda.         ‘not isinstance(a, b)’            3.2
                                                                                     

     All the assert methods accept a `msg' argument that, if specified,
     is used as the error message on failure (see also *note
     longMessage: cd0.).  Note that the `msg' keyword argument can be
     passed to *note assertRaises(): ac2, *note assertRaisesRegex():
     ac3, *note assertWarns(): ac4, *note assertWarnsRegex(): ac5. only
     when they are used as a context manager.

      -- 方法: assertEqual (first, second, msg=None)

          Test that `first' and `second' are equal.  If the values do
          not compare equal, the test will fail.

          In addition, if `first' and `second' are the exact same type
          and one of list, tuple, dict, set, frozenset or str or any
          type that a subclass registers with *note
          addTypeEqualityFunc(): ce9. the type-specific equality
          function will be called in order to generate a more useful
          default error message (see also the *note list of
          type-specific methods: 3349.).

          在 3.1 版更改: Added the automatic calling of type-specific
          equality function.

          在 3.2 版更改: *note assertMultiLineEqual(): cdf. added as the
          default type equality function for comparing strings.

      -- 方法: assertNotEqual (first, second, msg=None)

          Test that `first' and `second' are not equal.  If the values
          do compare equal, the test will fail.

      -- 方法: assertTrue (expr, msg=None)
      -- 方法: assertFalse (expr, msg=None)

          Test that `expr' is true (or false).

          Note that this is equivalent to ‘bool(expr) is True’ and not
          to ‘expr is True’ (use ‘assertIs(expr, True)’ for the latter).
          This method should also be avoided when more specific methods
          are available (e.g.  ‘assertEqual(a, b)’ instead of
          ‘assertTrue(a == b)’), because they provide a better error
          message in case of failure.

      -- 方法: assertIs (first, second, msg=None)
      -- 方法: assertIsNot (first, second, msg=None)

          Test that `first' and `second' are (or are not) the same
          object.

          3.1 新版功能.

      -- 方法: assertIsNone (expr, msg=None)
      -- 方法: assertIsNotNone (expr, msg=None)

          Test that `expr' is (or is not) ‘None’.

          3.1 新版功能.

      -- 方法: assertIn (member, container, msg=None)
      -- 方法: assertNotIn (member, container, msg=None)

          Test that `member' is (or is not) in `container'.

          3.1 新版功能.

      -- 方法: assertIsInstance (obj, cls, msg=None)
      -- 方法: assertNotIsInstance (obj, cls, msg=None)

          Test that `obj' is (or is not) an instance of `cls' (which can
          be a class or a tuple of classes, as supported by *note
          isinstance(): 457.).  To check for the exact type, use *note
          assertIs(type(obj), cls): cd7.

          3.2 新版功能.

     It is also possible to check the production of exceptions,
     warnings, and log messages using the following methods:

     Method                                                        Checks that                                New in
                                                                                                              
     --------------------------------------------------------------------------------------------------------------------------
                                                                                                              
     *note assertRaises(exc, fun, *args, **kwds): ac2.             ‘fun(*args, **kwds)’ raises `exc'
                                                                   
                                                                                                              
     *note assertRaisesRegex(exc, r, fun, *args, **kwds): ac3.     ‘fun(*args, **kwds)’ raises `exc' and      3.1
                                                                   the message matches regex `r'              
                                                                   
                                                                                                              
     *note assertWarns(warn, fun, *args, **kwds): ac4.             ‘fun(*args, **kwds)’ raises `warn'         3.2
                                                                                                              
                                                                                                              
     *note assertWarnsRegex(warn, r, fun, *args, **kwds): ac5.     ‘fun(*args, **kwds)’ raises `warn' and     3.2
                                                                   the message matches regex `r'              
                                                                   
                                                                                                              
     *note assertLogs(logger, level): 90d.                         The ‘with’ block logs on `logger' with     3.4
                                                                   minimum `level'                            
                                                                   

      -- 方法: assertRaises (exception, callable, *args, **kwds)

      -- 方法: assertRaises (exception, *, msg=None)

          Test that an exception is raised when `callable' is called
          with any positional or keyword arguments that are also passed
          to *note assertRaises(): ac2.  The test passes if `exception'
          is raised, is an error if another exception is raised, or
          fails if no exception is raised.  To catch any of a group of
          exceptions, a tuple containing the exception classes may be
          passed as `exception'.

          If only the `exception' and possibly the `msg' arguments are
          given, return a context manager so that the code under test
          can be written inline rather than as a function:

               with self.assertRaises(SomeException):
                   do_something()

          When used as a context manager, *note assertRaises(): ac2.
          accepts the additional keyword argument `msg'.

          The context manager will store the caught exception object in
          its ‘exception’ attribute.  This can be useful if the
          intention is to perform additional checks on the exception
          raised:

               with self.assertRaises(SomeException) as cm:
                   do_something()

               the_exception = cm.exception
               self.assertEqual(the_exception.error_code, 3)

          在 3.1 版更改: Added the ability to use *note assertRaises():
          ac2. as a context manager.

          在 3.2 版更改: Added the ‘exception’ attribute.

          在 3.3 版更改: Added the `msg' keyword argument when used as a
          context manager.

      -- 方法: assertRaisesRegex (exception, regex, callable, *args,
               **kwds)

      -- 方法: assertRaisesRegex (exception, regex, *, msg=None)

          Like *note assertRaises(): ac2. but also tests that `regex'
          matches on the string representation of the raised exception.
          `regex' may be a regular expression object or a string
          containing a regular expression suitable for use by *note
          re.search(): bba.  Examples:

               self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
                                      int, 'XYZ')

          或者：

               with self.assertRaisesRegex(ValueError, 'literal'):
                  int('XYZ')

          3.1 新版功能: 以方法名‘‘assertRaisesRegexp‘‘添加。

          在 3.2 版更改: Renamed to *note assertRaisesRegex(): ac3.

          在 3.3 版更改: Added the `msg' keyword argument when used as a
          context manager.

      -- 方法: assertWarns (warning, callable, *args, **kwds)

      -- 方法: assertWarns (warning, *, msg=None)

          Test that a warning is triggered when `callable' is called
          with any positional or keyword arguments that are also passed
          to *note assertWarns(): ac4.  The test passes if `warning' is
          triggered and fails if it isn’t.  Any exception is an error.
          To catch any of a group of warnings, a tuple containing the
          warning classes may be passed as `warnings'.

          If only the `warning' and possibly the `msg' arguments are
          given, return a context manager so that the code under test
          can be written inline rather than as a function:

               with self.assertWarns(SomeWarning):
                   do_something()

          When used as a context manager, *note assertWarns(): ac4.
          accepts the additional keyword argument `msg'.

          The context manager will store the caught warning object in
          its ‘warning’ attribute, and the source line which triggered
          the warnings in the ‘filename’ and ‘lineno’ attributes.  This
          can be useful if the intention is to perform additional checks
          on the warning caught:

               with self.assertWarns(SomeWarning) as cm:
                   do_something()

               self.assertIn('myfile.py', cm.filename)
               self.assertEqual(320, cm.lineno)

          This method works regardless of the warning filters in place
          when it is called.

          3.2 新版功能.

          在 3.3 版更改: Added the `msg' keyword argument when used as a
          context manager.

      -- 方法: assertWarnsRegex (warning, regex, callable, *args,
               **kwds)

      -- 方法: assertWarnsRegex (warning, regex, *, msg=None)

          Like *note assertWarns(): ac4. but also tests that `regex'
          matches on the message of the triggered warning.  `regex' may
          be a regular expression object or a string containing a
          regular expression suitable for use by *note re.search(): bba.
          Example:

               self.assertWarnsRegex(DeprecationWarning,
                                     r'legacy_function\(\) is deprecated',
                                     legacy_function, 'XYZ')

          或者：

               with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
                   frobnicate('/etc/passwd')

          3.2 新版功能.

          在 3.3 版更改: Added the `msg' keyword argument when used as a
          context manager.

      -- 方法: assertLogs (logger=None, level=None)

          A context manager to test that at least one message is logged
          on the `logger' or one of its children, with at least the
          given `level'.

          If given, `logger' should be a *note logging.Logger: 3af.
          object or a *note str: 339. giving the name of a logger.  The
          default is the root logger, which will catch all messages that
          were not blocked by a non-propagating descendent logger.

          If given, `level' should be either a numeric logging level or
          its string equivalent (for example either ‘"ERROR"’ or
          ‘logging.ERROR’).  The default is ‘logging.INFO’.

          The test passes if at least one message emitted inside the
          ‘with’ block matches the `logger' and `level' conditions,
          otherwise it fails.

          The object returned by the context manager is a recording
          helper which keeps tracks of the matching log messages.  It
          has two attributes:

           -- 属性: records

               A list of *note logging.LogRecord: 90e. objects of the
               matching log messages.

           -- 属性: output

               A list of *note str: 339. objects with the formatted
               output of matching messages.

          示例:

               with self.assertLogs('foo', level='INFO') as cm:
                  logging.getLogger('foo').info('first message')
                  logging.getLogger('foo.bar').error('second message')
               self.assertEqual(cm.output, ['INFO:foo:first message',
                                            'ERROR:foo.bar:second message'])

          3.4 新版功能.

     There are also other methods used to perform more specific checks,
     such as:

     Method                                      Checks that                          New in
                                                                                      
     ----------------------------------------------------------------------------------------------------
                                                                                      
     *note assertAlmostEqual(a, b): bbf.         ‘round(a-b, 7) == 0’
                                                 
                                                                                      
     *note assertNotAlmostEqual(a, b): bc0.      ‘round(a-b, 7) != 0’
                                                 
                                                                                      
     *note assertGreater(a, b): cdb.             ‘a > b’                              3.1
                                                                                      
                                                                                      
     *note assertGreaterEqual(a, b): cdc.        ‘a >= b’                             3.1
                                                                                      
                                                                                      
     *note assertLess(a, b): cdd.                ‘a < b’                              3.1
                                                                                      
                                                                                      
     *note assertLessEqual(a, b): cde.           ‘a <= b’                             3.1
                                                                                      
                                                                                      
     *note assertRegex(s, r): bb9.               ‘r.search(s)’                        3.1
                                                                                      
                                                                                      
     *note assertNotRegex(s, r): 334c.           ‘not r.search(s)’                    3.2
                                                                                      
                                                                                      
     *note assertCountEqual(a, b): bb7.          `a' and `b' have the same elements   3.2
                                                 in the same number, regardless of    
                                                 their order.
                                                 

      -- 方法: assertAlmostEqual (first, second, places=7, msg=None,
               delta=None)
      -- 方法: assertNotAlmostEqual (first, second, places=7, msg=None,
               delta=None)

          Test that `first' and `second' are approximately (or not
          approximately) equal by computing the difference, rounding to
          the given number of decimal `places' (default 7), and
          comparing to zero.  Note that these methods round the values
          to the given number of `decimal places' (i.e.  like the *note
          round(): c75. function) and not `significant digits'.

          If `delta' is supplied instead of `places' then the difference
          between `first' and `second' must be less or equal to (or
          greater than) `delta'.

          Supplying both `delta' and `places' raises a *note TypeError:
          193.

          在 3.2 版更改: *note assertAlmostEqual(): bbf. automatically
          considers almost equal objects that compare equal.  *note
          assertNotAlmostEqual(): bc0. automatically fails if the
          objects compare equal.  Added the `delta' keyword argument.

      -- 方法: assertGreater (first, second, msg=None)
      -- 方法: assertGreaterEqual (first, second, msg=None)
      -- 方法: assertLess (first, second, msg=None)
      -- 方法: assertLessEqual (first, second, msg=None)

          Test that `first' is respectively >, >=, < or <= than `second'
          depending on the method name.  If not, the test will fail:

               >>> self.assertGreaterEqual(3, 4)
               AssertionError: "3" unexpectedly not greater than or equal to "4"

          3.1 新版功能.

      -- 方法: assertRegex (text, regex, msg=None)
      -- 方法: assertNotRegex (text, regex, msg=None)

          测试一个 `regex' 搜索匹配（或不匹配） `文本'。如果不匹配，错误
          信息中将包含匹配模式和 `文本*（或部分匹配失败的 *文本'）。
          `regex' 可以是正则表达式对象或能够用于 *note re.search(): bba.
          的包含正则表达式的字符串。

          3.1 新版功能: 以方法名‘‘assertRegexpMatches‘‘添加。

          在 3.2 版更改: 方法 ‘assertRegexpMatches()’ 已被改名为 *note
          assertRegex(): bb9.。

          3.2 新版功能: *note assertNotRegex(): 334c.

          3.5 新版功能: ‘assertNotRegexpMatches’ 这个名字是 *note
          assertNotRegex(): 334c. 的已被弃用的别名。

      -- 方法: assertCountEqual (first, second, msg=None)

          Test that sequence `first' contains the same elements as
          `second', regardless of their order.  When they don’t, an
          error message listing the differences between the sequences
          will be generated.

          Duplicate elements are `not' ignored when comparing `first'
          and `second'.  It verifies whether each element has the same
          count in both sequences.  Equivalent to:
          ‘assertEqual(Counter(list(first)), Counter(list(second)))’ but
          works with sequences of unhashable objects as well.

          3.2 新版功能.

     The *note assertEqual(): bbd. method dispatches the equality check
     for objects of the same type to different type-specific methods.
     These methods are already implemented for most of the built-in
     types, but it’s also possible to register new methods using *note
     addTypeEqualityFunc(): ce9.:

      -- 方法: addTypeEqualityFunc (typeobj, function)

          Registers a type-specific method called by *note
          assertEqual(): bbd. to check if two objects of exactly the
          same `typeobj' (not subclasses) compare equal.  `function'
          must take two positional arguments and a third msg=None
          keyword argument just as *note assertEqual(): bbd. does.  It
          must raise *note self.failureException(msg): 334d. when
          inequality between the first two parameters is detected –
          possibly providing useful information and explaining the
          inequalities in details in the error message.

          3.1 新版功能.

     以下是 *note assertEqual(): bbd. 自动选用的不同类型的比较方法。一般
     情况下不需要直接在测试中调用这些方法。

     Method                                        用作比较                          New in
                                                                                     
     ---------------------------------------------------------------------------------------------------
                                                                                     
     *note assertMultiLineEqual(a, b): cdf.        字符串                            3.1
                                                                                     
                                                                                     
     *note assertSequenceEqual(a, b): ce5.         序列                              3.1
                                                                                     
                                                                                     
     *note assertListEqual(a, b): ce3.             列表                              3.1
                                                                                     
                                                                                     
     *note assertTupleEqual(a, b): ce4.            元组                              3.1
                                                                                     
                                                                                     
     *note assertSetEqual(a, b): ce2.              集合                              3.1
                                                                                     
                                                                                     
     *note assertDictEqual(a, b): ce6.             字典                              3.1
                                                                                     

      -- 方法: assertMultiLineEqual (first, second, msg=None)

          Test that the multiline string `first' is equal to the string
          `second'.  When not equal a diff of the two strings
          highlighting the differences will be included in the error
          message.  This method is used by default when comparing
          strings with *note assertEqual(): bbd.

          3.1 新版功能.

      -- 方法: assertSequenceEqual (first, second, msg=None,
               seq_type=None)

          Tests that two sequences are equal.  If a `seq_type' is
          supplied, both `first' and `second' must be instances of
          `seq_type' or a failure will be raised.  If the sequences are
          different an error message is constructed that shows the
          difference between the two.

          This method is not called directly by *note assertEqual():
          bbd, but it’s used to implement *note assertListEqual(): ce3.
          and *note assertTupleEqual(): ce4.

          3.1 新版功能.

      -- 方法: assertListEqual (first, second, msg=None)
      -- 方法: assertTupleEqual (first, second, msg=None)

          Tests that two lists or tuples are equal.  If not, an error
          message is constructed that shows only the differences between
          the two.  An error is also raised if either of the parameters
          are of the wrong type.  These methods are used by default when
          comparing lists or tuples with *note assertEqual(): bbd.

          3.1 新版功能.

      -- 方法: assertSetEqual (first, second, msg=None)

          Tests that two sets are equal.  If not, an error message is
          constructed that lists the differences between the sets.  This
          method is used by default when comparing sets or frozensets
          with *note assertEqual(): bbd.

          Fails if either of `first' or `second' does not have a
          ‘set.difference()’ method.

          3.1 新版功能.

      -- 方法: assertDictEqual (first, second, msg=None)

          Test that two dictionaries are equal.  If not, an error
          message is constructed that shows the differences in the
          dictionaries.  This method will be used by default to compare
          dictionaries in calls to *note assertEqual(): bbd.

          3.1 新版功能.

     Finally the *note TestCase: 907. provides the following methods and
     attributes:

      -- 方法: fail (msg=None)

          Signals a test failure unconditionally, with `msg' or ‘None’
          for the error message.

      -- 属性: failureException

          This class attribute gives the exception raised by the test
          method.  If a test framework needs to use a specialized
          exception, possibly to carry additional information, it must
          subclass this exception in order to "play fair" with the
          framework.  The initial value of this attribute is *note
          AssertionError: 103e.

      -- 属性: longMessage

          This class attribute determines what happens when a custom
          failure message is passed as the msg argument to an assertXYY
          call that fails.  ‘True’ is the default value.  In this case,
          the custom message is appended to the end of the standard
          failure message.  When set to ‘False’, the custom message
          replaces the standard message.

          The class setting can be overridden in individual test methods
          by assigning an instance attribute, self.longMessage, to
          ‘True’ or ‘False’ before calling the assert methods.

          The class setting gets reset before each test call.

          3.1 新版功能.

      -- 属性: maxDiff

          This attribute controls the maximum length of diffs output by
          assert methods that report diffs on failure.  It defaults to
          80*8 characters.  Assert methods affected by this attribute
          are *note assertSequenceEqual(): ce5. (including all the
          sequence comparison methods that delegate to it), *note
          assertDictEqual(): ce6. and *note assertMultiLineEqual(): cdf.

          Setting ‘maxDiff’ to ‘None’ means that there is no maximum
          length of diffs.

          3.2 新版功能.

     Testing frameworks can use the following methods to collect
     information on the test:

      -- 方法: countTestCases ()

          Return the number of tests represented by this test object.
          For *note TestCase: 907. instances, this will always be ‘1’.

      -- 方法: defaultTestResult ()

          Return an instance of the test result class that should be
          used for this test case class (if no other result instance is
          provided to the *note run(): ac6. method).

          For *note TestCase: 907. instances, this will always be an
          instance of *note TestResult: ac7.; subclasses of *note
          TestCase: 907. should override this as necessary.

      -- 方法: id ()

          Return a string identifying the specific test case.  This is
          usually the full name of the test method, including the module
          and class name.

      -- 方法: shortDescription ()

          Returns a description of the test, or ‘None’ if no description
          has been provided.  The default implementation of this method
          returns the first line of the test method’s docstring, if
          available, or ‘None’.

          在 3.1 版更改: In 3.1 this was changed to add the test name to
          the short description even in the presence of a docstring.
          This caused compatibility issues with unittest extensions and
          adding the test name was moved to the *note TextTestResult:
          3353. in Python 3.2.

      -- 方法: addCleanup (function, *args, **kwargs)

          Add a function to be called after *note tearDown(): cd4. to
          cleanup resources used during the test.  Functions will be
          called in reverse order to the order they are added (LIFO).
          They are called with any arguments and keyword arguments
          passed into *note addCleanup(): 2a3. when they are added.

          If *note setUp(): cd3. fails, meaning that *note tearDown():
          cd4. is not called, then any cleanup functions added will
          still be called.

          3.1 新版功能.

      -- 方法: doCleanups ()

          This method is called unconditionally after *note tearDown():
          cd4, or after *note setUp(): cd3. if *note setUp(): cd3.
          raises an exception.

          It is responsible for calling all the cleanup functions added
          by *note addCleanup(): 2a3.  If you need cleanup functions to
          be called `prior' to *note tearDown(): cd4. then you can call
          *note doCleanups(): cd2. yourself.

          *note doCleanups(): cd2. pops methods off the stack of cleanup
          functions one at a time, so it can be called at any time.

          3.1 新版功能.

      -- 方法: classmethod addClassCleanup (function, /, *args,
               **kwargs)

          Add a function to be called after *note tearDownClass(): cd1.
          to cleanup resources used during the test class.  Functions
          will be called in reverse order to the order they are added
          (LIFO).  They are called with any arguments and keyword
          arguments passed into *note addClassCleanup(): 24c. when they
          are added.

          If *note setUpClass(): 24d. fails, meaning that *note
          tearDownClass(): cd1. is not called, then any cleanup
          functions added will still be called.

          3.8 新版功能.

      -- 方法: classmethod doClassCleanups ()

          This method is called unconditionally after *note
          tearDownClass(): cd1, or after *note setUpClass(): 24d. if
          *note setUpClass(): 24d. raises an exception.

          It is responsible for calling all the cleanup functions added
          by *note addClassCleanup(): 24c.  If you need cleanup
          functions to be called `prior' to *note tearDownClass(): cd1.
          then you can call *note doClassCleanups(): 3354. yourself.

          *note doClassCleanups(): 3354. pops methods off the stack of
          cleanup functions one at a time, so it can be called at any
          time.

          3.8 新版功能.

 -- 类: unittest.IsolatedAsyncioTestCase (methodName='runTest')

     This class provides an API similar to *note TestCase: 907. and also
     accepts coroutines as test functions.

     3.8 新版功能.

      -- 方法: coroutine asyncSetUp ()

          Method called to prepare the test fixture.  This is called
          after ‘setUp()’.  This is called immediately before calling
          the test method; other than *note AssertionError: 103e. or
          *note SkipTest: 90b, any exception raised by this method will
          be considered an error rather than a test failure.  The
          default implementation does nothing.

      -- 方法: coroutine asyncTearDown ()

          Method called immediately after the test method has been
          called and the result recorded.  This is called before
          ‘tearDown()’.  This is called even if the test method raised
          an exception, so the implementation in subclasses may need to
          be particularly careful about checking internal state.  Any
          exception, other than *note AssertionError: 103e. or *note
          SkipTest: 90b, raised by this method will be considered an
          additional error rather than a test failure (thus increasing
          the total number of reported errors).  This method will only
          be called if the *note asyncSetUp(): 3355. succeeds,
          regardless of the outcome of the test method.  The default
          implementation does nothing.

      -- 方法: addAsyncCleanup (function, /, *args, **kwargs)

          This method accepts a coroutine that can be used as a cleanup
          function.

      -- 方法: run (result=None)

          Sets up a new event loop to run the test, collecting the
          result into the *note TestResult: ac7. object passed as
          `result'.  If `result' is omitted or ‘None’, a temporary
          result object is created (by calling the ‘defaultTestResult()’
          method) and used.  The result object is returned to *note
          run(): 3358.’s caller.  At the end of the test all the tasks
          in the event loop are cancelled.

     An example illustrating the order:

          from unittest import IsolatedAsyncioTestCase

          events = []


          class Test(IsolatedAsyncioTestCase):


              def setUp(self):
                  events.append("setUp")

              async def asyncSetUp(self):
                  self._async_connection = await AsyncConnection()
                  events.append("asyncSetUp")

              async def test_response(self):
                  events.append("test_response")
                  response = await self._async_connection.get("https://example.com")
                  self.assertEqual(response.status_code, 200)
                  self.addAsyncCleanup(self.on_cleanup)

              def tearDown(self):
                  events.append("tearDown")

              async def asyncTearDown(self):
                  await self._async_connection.close()
                  events.append("asyncTearDown")

              async def on_cleanup(self):
                  events.append("cleanup")

          if __name__ == "__main__":
              unittest.main()

     After running the test, ‘events’ would contain ‘["setUp",
     "asyncSetUp", "test_response", "asyncTearDown", "tearDown",
     "cleanup"]’.

 -- 类: unittest.FunctionTestCase (testFunc, setUp=None, tearDown=None,
          description=None)

     This class implements the portion of the *note TestCase: 907.
     interface which allows the test runner to drive the test, but does
     not provide the methods which test code can use to check and report
     errors.  This is used to create test cases using legacy test code,
     allowing it to be integrated into a *note unittest: 11c.-based test
     framework.

* Menu:

* Deprecated aliases::


File: python.info,  Node: Deprecated aliases,  Up: 测试用例

5.26.4.11 Deprecated aliases
............................

For historical reasons, some of the *note TestCase: 907. methods had one
or more aliases that are now deprecated.  The following table lists the
correct names along with their deprecated aliases:

     方法名                             Deprecated alias           Deprecated alias
                                                                   
     ------------------------------------------------------------------------------------------
                                                                   
     *note assertEqual(): bbd.          failUnlessEqual            assertEquals
                                                                   
                                                                   
     *note assertNotEqual(): bbe.       failIfEqual                assertNotEquals
                                                                   
                                                                   
     *note assertTrue(): bbc.           failUnless                 assert_
                                                                   
                                                                   
     *note assertFalse(): ccf.          failIf
                                        
                                                                   
     *note assertRaises(): ac2.         failUnlessRaises
                                        
                                                                   
     *note assertAlmostEqual(): bbf.    failUnlessAlmostEqual      assertAlmostEquals
                                                                   
                                                                   
     *note assertNotAlmostEqual(): bc0. failIfAlmostEqual          assertNotAlmostEquals
                                                                   
                                                                   
     *note assertRegex(): bb9.                                     assertRegexpMatches
                                                                   
                                                                   
     *note assertNotRegex(): 334c.                                 assertNotRegexpMatches
                                                                   
                                                                   
     *note assertRaisesRegex(): ac3.                               assertRaisesRegexp
                                                                   

     3.1 版后已移除: The fail* aliases listed in the second column have
     been deprecated.

     3.2 版后已移除: The assert* aliases listed in the third column have
     been deprecated.

     3.2 版后已移除: ‘assertRegexpMatches’ and ‘assertRaisesRegexp’ have
     been renamed to *note assertRegex(): bb9. and *note
     assertRaisesRegex(): ac3.

     3.5 版后已移除: The ‘assertNotRegexpMatches’ name is deprecated in
     favor of *note assertNotRegex(): 334c.


File: python.info,  Node: Grouping tests,  Next: Loading and running tests,  Prev: 测试用例,  Up: 类与函数

5.26.4.12 Grouping tests
........................

 -- 类: unittest.TestSuite (tests=())

     This class represents an aggregation of individual test cases and
     test suites.  The class presents the interface needed by the test
     runner to allow it to be run as any other test case.  Running a
     *note TestSuite: 6d7. instance is the same as iterating over the
     suite, running each test individually.

     If `tests' is given, it must be an iterable of individual test
     cases or other test suites that will be used to build the suite
     initially.  Additional methods are provided to add test cases and
     suites to the collection later on.

     *note TestSuite: 6d7. objects behave much like *note TestCase: 907.
     objects, except they do not actually implement a test.  Instead,
     they are used to aggregate tests into groups of tests that should
     be run together.  Some additional methods are available to add
     tests to *note TestSuite: 6d7. instances:

      -- 方法: addTest (test)

          Add a *note TestCase: 907. or *note TestSuite: 6d7. to the
          suite.

      -- 方法: addTests (tests)

          Add all the tests from an iterable of *note TestCase: 907. and
          *note TestSuite: 6d7. instances to this test suite.

          This is equivalent to iterating over `tests', calling *note
          addTest(): 335c. for each element.

     *note TestSuite: 6d7. shares the following methods with *note
     TestCase: 907.:

      -- 方法: run (result)

          Run the tests associated with this suite, collecting the
          result into the test result object passed as `result'.  Note
          that unlike *note TestCase.run(): ac6, *note TestSuite.run():
          335e. requires the result object to be passed in.

      -- 方法: debug ()

          Run the tests associated with this suite without collecting
          the result.  This allows exceptions raised by the test to be
          propagated to the caller and can be used to support running
          tests under a debugger.

      -- 方法: countTestCases ()

          Return the number of tests represented by this test object,
          including all individual tests and sub-suites.

      -- 方法: __iter__ ()

          Tests grouped by a *note TestSuite: 6d7. are always accessed
          by iteration.  Subclasses can lazily provide tests by
          overriding *note __iter__(): 96a.  Note that this method may
          be called several times on a single suite (for example when
          counting tests or comparing for equality) so the tests
          returned by repeated iterations before *note TestSuite.run():
          335e. must be the same for each call iteration.  After *note
          TestSuite.run(): 335e, callers should not rely on the tests
          returned by this method unless the caller uses a subclass that
          overrides ‘TestSuite._removeTestAtIndex()’ to preserve test
          references.

          在 3.2 版更改: In earlier versions the *note TestSuite: 6d7.
          accessed tests directly rather than through iteration, so
          overriding *note __iter__(): 96a. wasn’t sufficient for
          providing tests.

          在 3.4 版更改: In earlier versions the *note TestSuite: 6d7.
          held references to each *note TestCase: 907. after *note
          TestSuite.run(): 335e.  Subclasses can restore that behavior
          by overriding ‘TestSuite._removeTestAtIndex()’.

     In the typical usage of a *note TestSuite: 6d7. object, the *note
     run(): 335e. method is invoked by a ‘TestRunner’ rather than by the
     end-user test harness.


File: python.info,  Node: Loading and running tests,  Prev: Grouping tests,  Up: 类与函数

5.26.4.13 Loading and running tests
...................................

 -- 类: unittest.TestLoader

     The *note TestLoader: 78b. class is used to create test suites from
     classes and modules.  Normally, there is no need to create an
     instance of this class; the *note unittest: 11c. module provides an
     instance that can be shared as *note unittest.defaultTestLoader:
     3362.  Using a subclass or instance, however, allows customization
     of some configurable properties.

     *note TestLoader: 78b. objects have the following attributes:

      -- 属性: errors

          A list of the non-fatal errors encountered while loading
          tests.  Not reset by the loader at any point.  Fatal errors
          are signalled by the relevant a method raising an exception to
          the caller.  Non-fatal errors are also indicated by a
          synthetic test that will raise the original error when run.

          3.5 新版功能.

     *note TestLoader: 78b. objects have the following methods:

      -- 方法: loadTestsFromTestCase (testCaseClass)

          Return a suite of all test cases contained in the *note
          TestCase: 907.-derived ‘testCaseClass’.

          A test case instance is created for each method named by *note
          getTestCaseNames(): 3364.  By default these are the method
          names beginning with ‘test’.  If *note getTestCaseNames():
          3364. returns no methods, but the ‘runTest()’ method is
          implemented, a single test case is created for that method
          instead.

      -- 方法: loadTestsFromModule (module, pattern=None)

          Return a suite of all test cases contained in the given
          module.  This method searches `module' for classes derived
          from *note TestCase: 907. and creates an instance of the class
          for each test method defined for the class.

               注解: While using a hierarchy of *note TestCase:
               907.-derived classes can be convenient in sharing
               fixtures and helper functions, defining test methods on
               base classes that are not intended to be instantiated
               directly does not play well with this method.  Doing so,
               however, can be useful when the fixtures are different
               and defined in subclasses.

          If a module provides a ‘load_tests’ function it will be called
          to load the tests.  This allows modules to customize test
          loading.  This is the *note load_tests protocol: 3337.  The
          `pattern' argument is passed as the third argument to
          ‘load_tests’.

          在 3.2 版更改: Support for ‘load_tests’ added.

          在 3.5 版更改: The undocumented and unofficial
          `use_load_tests' default argument is deprecated and ignored,
          although it is still accepted for backward compatibility.  The
          method also now accepts a keyword-only argument `pattern'
          which is passed to ‘load_tests’ as the third argument.

      -- 方法: loadTestsFromName (name, module=None)

          Return a suite of all test cases given a string specifier.

          The specifier `name' is a "dotted name" that may resolve
          either to a module, a test case class, a test method within a
          test case class, a *note TestSuite: 6d7. instance, or a
          callable object which returns a *note TestCase: 907. or *note
          TestSuite: 6d7. instance.  These checks are applied in the
          order listed here; that is, a method on a possible test case
          class will be picked up as "a test method within a test case
          class", rather than "a callable object".

          For example, if you have a module ‘SampleTests’ containing a
          *note TestCase: 907.-derived class ‘SampleTestCase’ with three
          test methods (‘test_one()’, ‘test_two()’, and ‘test_three()’),
          the specifier ‘'SampleTests.SampleTestCase'’ would cause this
          method to return a suite which will run all three test
          methods.  Using the specifier
          ‘'SampleTests.SampleTestCase.test_two'’ would cause it to
          return a test suite which will run only the ‘test_two()’ test
          method.  The specifier can refer to modules and packages which
          have not been imported; they will be imported as a
          side-effect.

          The method optionally resolves `name' relative to the given
          `module'.

          在 3.5 版更改: If an *note ImportError: 33d. or *note
          AttributeError: 3a3. occurs while traversing `name' then a
          synthetic test that raises that error when run will be
          returned.  These errors are included in the errors accumulated
          by self.errors.

      -- 方法: loadTestsFromNames (names, module=None)

          Similar to *note loadTestsFromName(): ce7, but takes a
          sequence of names rather than a single name.  The return value
          is a test suite which supports all the tests defined for each
          name.

      -- 方法: getTestCaseNames (testCaseClass)

          Return a sorted sequence of method names found within
          `testCaseClass'; this should be a subclass of *note TestCase:
          907.

      -- 方法: discover (start_dir, pattern='test*.py',
               top_level_dir=None)

          Find all the test modules by recursing into subdirectories
          from the specified start directory, and return a TestSuite
          object containing them.  Only test files that match `pattern'
          will be loaded.  (Using shell style pattern matching.)  Only
          module names that are importable (i.e.  are valid Python
          identifiers) will be loaded.

          All test modules must be importable from the top level of the
          project.  If the start directory is not the top level
          directory then the top level directory must be specified
          separately.

          If importing a module fails, for example due to a syntax
          error, then this will be recorded as a single error and
          discovery will continue.  If the import failure is due to
          *note SkipTest: 90b. being raised, it will be recorded as a
          skip instead of an error.

          If a package (a directory containing a file named
          ‘__init__.py’) is found, the package will be checked for a
          ‘load_tests’ function.  If this exists then it will be called
          ‘package.load_tests(loader, tests, pattern)’.  Test discovery
          takes care to ensure that a package is only checked for tests
          once during an invocation, even if the load_tests function
          itself calls ‘loader.discover’.

          If ‘load_tests’ exists then discovery does `not' recurse into
          the package, ‘load_tests’ is responsible for loading all tests
          in the package.

          The pattern is deliberately not stored as a loader attribute
          so that packages can continue discovery themselves.
          `top_level_dir' is stored so ‘load_tests’ does not need to
          pass this argument in to ‘loader.discover()’.

          `start_dir' can be a dotted module name as well as a
          directory.

          3.2 新版功能.

          在 3.4 版更改: Modules that raise *note SkipTest: 90b. on
          import are recorded as skips, not errors.

          在 3.4 版更改: `start_dir' can be a *note namespace packages:
          14c3.

          在 3.4 版更改: Paths are sorted before being imported so that
          execution order is the same even if the underlying file
          system’s ordering is not dependent on file name.

          在 3.5 版更改: Found packages are now checked for ‘load_tests’
          regardless of whether their path matches `pattern', because it
          is impossible for a package name to match the default pattern.

     The following attributes of a *note TestLoader: 78b. can be
     configured either by subclassing or assignment on an instance:

      -- 属性: testMethodPrefix

          String giving the prefix of method names which will be
          interpreted as test methods.  The default value is ‘'test'’.

          This affects *note getTestCaseNames(): 3364. and all the
          ‘loadTestsFrom*()’ methods.

      -- 属性: sortTestMethodsUsing

          Function to be used to compare method names when sorting them
          in *note getTestCaseNames(): 3364. and all the
          ‘loadTestsFrom*()’ methods.

      -- 属性: suiteClass

          Callable object that constructs a test suite from a list of
          tests.  No methods on the resulting object are needed.  The
          default value is the *note TestSuite: 6d7. class.

          This affects all the ‘loadTestsFrom*()’ methods.

      -- 属性: testNamePatterns

          List of Unix shell-style wildcard test name patterns that test
          methods have to match to be included in test suites (see ‘-v’
          option).

          If this attribute is not ‘None’ (the default), all test
          methods to be included in test suites must match one of the
          patterns in this list.  Note that matches are always performed
          using *note fnmatch.fnmatchcase(): 1c8c, so unlike patterns
          passed to the ‘-v’ option, simple substring patterns will have
          to be converted using ‘*’ wildcards.

          This affects all the ‘loadTestsFrom*()’ methods.

          3.7 新版功能.

 -- 类: unittest.TestResult

     This class is used to compile information about which tests have
     succeeded and which have failed.

     A *note TestResult: ac7. object stores the results of a set of
     tests.  The *note TestCase: 907. and *note TestSuite: 6d7. classes
     ensure that results are properly recorded; test authors do not need
     to worry about recording the outcome of tests.

     Testing frameworks built on top of *note unittest: 11c. may want
     access to the *note TestResult: ac7. object generated by running a
     set of tests for reporting purposes; a *note TestResult: ac7.
     instance is returned by the ‘TestRunner.run()’ method for this
     purpose.

     *note TestResult: ac7. instances have the following attributes that
     will be of interest when inspecting the results of running a set of
     tests:

      -- 属性: errors

          A list containing 2-tuples of *note TestCase: 907. instances
          and strings holding formatted tracebacks.  Each tuple
          represents a test which raised an unexpected exception.

      -- 属性: failures

          A list containing 2-tuples of *note TestCase: 907. instances
          and strings holding formatted tracebacks.  Each tuple
          represents a test where a failure was explicitly signalled
          using the ‘TestCase.assert*()’ methods.

      -- 属性: skipped

          A list containing 2-tuples of *note TestCase: 907. instances
          and strings holding the reason for skipping the test.

          3.1 新版功能.

      -- 属性: expectedFailures

          A list containing 2-tuples of *note TestCase: 907. instances
          and strings holding formatted tracebacks.  Each tuple
          represents an expected failure or error of the test case.

      -- 属性: unexpectedSuccesses

          A list containing *note TestCase: 907. instances that were
          marked as expected failures, but succeeded.

      -- 属性: shouldStop

          Set to ‘True’ when the execution of tests should stop by *note
          stop(): 336f.

      -- 属性: testsRun

          The total number of tests run so far.

      -- 属性: buffer

          If set to true, ‘sys.stdout’ and ‘sys.stderr’ will be buffered
          in between *note startTest(): 3372. and *note stopTest():
          3373. being called.  Collected output will only be echoed onto
          the real ‘sys.stdout’ and ‘sys.stderr’ if the test fails or
          errors.  Any output is also attached to the failure / error
          message.

          3.2 新版功能.

      -- 属性: failfast

          If set to true *note stop(): 336f. will be called on the first
          failure or error, halting the test run.

          3.2 新版功能.

      -- 属性: tb_locals

          If set to true then local variables will be shown in
          tracebacks.

          3.5 新版功能.

      -- 方法: wasSuccessful ()

          Return ‘True’ if all tests run so far have passed, otherwise
          returns ‘False’.

          在 3.4 版更改: Returns ‘False’ if there were any *note
          unexpectedSuccesses: 336d. from tests marked with the *note
          expectedFailure(): 333f. decorator.

      -- 方法: stop ()

          This method can be called to signal that the set of tests
          being run should be aborted by setting the *note shouldStop:
          336e. attribute to ‘True’.  ‘TestRunner’ objects should
          respect this flag and return without running any additional
          tests.

          For example, this feature is used by the *note TextTestRunner:
          3377. class to stop the test framework when the user signals
          an interrupt from the keyboard.  Interactive tools which
          provide ‘TestRunner’ implementations can use this in a similar
          manner.

     The following methods of the *note TestResult: ac7. class are used
     to maintain the internal data structures, and may be extended in
     subclasses to support additional reporting requirements.  This is
     particularly useful in building tools which support interactive
     reporting while tests are being run.

      -- 方法: startTest (test)

          Called when the test case `test' is about to be run.

      -- 方法: stopTest (test)

          Called after the test case `test' has been executed,
          regardless of the outcome.

      -- 方法: startTestRun ()

          Called once before any tests are executed.

          3.1 新版功能.

      -- 方法: stopTestRun ()

          Called once after all tests are executed.

          3.1 新版功能.

      -- 方法: addError (test, err)

          Called when the test case `test' raises an unexpected
          exception.  `err' is a tuple of the form returned by *note
          sys.exc_info(): c67.: ‘(type, value, traceback)’.

          The default implementation appends a tuple ‘(test,
          formatted_err)’ to the instance’s *note errors: 3369.
          attribute, where `formatted_err' is a formatted traceback
          derived from `err'.

      -- 方法: addFailure (test, err)

          Called when the test case `test' signals a failure.  `err' is
          a tuple of the form returned by *note sys.exc_info(): c67.:
          ‘(type, value, traceback)’.

          The default implementation appends a tuple ‘(test,
          formatted_err)’ to the instance’s *note failures: 336a.
          attribute, where `formatted_err' is a formatted traceback
          derived from `err'.

      -- 方法: addSuccess (test)

          Called when the test case `test' succeeds.

          The default implementation does nothing.

      -- 方法: addSkip (test, reason)

          Called when the test case `test' is skipped.  `reason' is the
          reason the test gave for skipping.

          The default implementation appends a tuple ‘(test, reason)’ to
          the instance’s *note skipped: 336b. attribute.

      -- 方法: addExpectedFailure (test, err)

          Called when the test case `test' fails or errors, but was
          marked with the *note expectedFailure(): 333f. decorator.

          The default implementation appends a tuple ‘(test,
          formatted_err)’ to the instance’s *note expectedFailures:
          336c. attribute, where `formatted_err' is a formatted
          traceback derived from `err'.

      -- 方法: addUnexpectedSuccess (test)

          Called when the test case `test' was marked with the *note
          expectedFailure(): 333f. decorator, but succeeded.

          The default implementation appends the test to the instance’s
          *note unexpectedSuccesses: 336d. attribute.

      -- 方法: addSubTest (test, subtest, outcome)

          Called when a subtest finishes.  `test' is the test case
          corresponding to the test method.  `subtest' is a custom *note
          TestCase: 907. instance describing the subtest.

          If `outcome' is *note None: 158, the subtest succeeded.
          Otherwise, it failed with an exception where `outcome' is a
          tuple of the form returned by *note sys.exc_info(): c67.:
          ‘(type, value, traceback)’.

          The default implementation does nothing when the outcome is a
          success, and records subtest failures as normal failures.

          3.4 新版功能.

 -- 类: unittest.TextTestResult (stream, descriptions, verbosity)

     A concrete implementation of *note TestResult: ac7. used by the
     *note TextTestRunner: 3377.

     3.2 新版功能: This class was previously named ‘_TextTestResult’.
     The old name still exists as an alias but is deprecated.

 -- 数据: unittest.defaultTestLoader

     Instance of the *note TestLoader: 78b. class intended to be shared.
     If no customization of the *note TestLoader: 78b. is needed, this
     instance can be used instead of repeatedly creating new instances.

 -- 类: unittest.TextTestRunner (stream=None, descriptions=True,
          verbosity=1, failfast=False, buffer=False, resultclass=None,
          warnings=None, *, tb_locals=False)

     A basic test runner implementation that outputs results to a
     stream.  If `stream' is ‘None’, the default, *note sys.stderr: 318.
     is used as the output stream.  This class has a few configurable
     parameters, but is essentially very simple.  Graphical applications
     which run test suites should provide alternate implementations.
     Such implementations should accept ‘**kwargs’ as the interface to
     construct runners changes when features are added to unittest.

     By default this runner shows *note DeprecationWarning: 279, *note
     PendingDeprecationWarning: 27a, *note ResourceWarning: 4d8. and
     *note ImportWarning: 5e1. even if they are *note ignored by
     default: 337f.  Deprecation warnings caused by *note deprecated
     unittest methods: bc1. are also special-cased and, when the warning
     filters are ‘'default'’ or ‘'always'’, they will appear only once
     per-module, in order to avoid too many warning messages.  This
     behavior can be overridden using Python’s ‘-Wd’ or ‘-Wa’ options
     (see *note Warning control: 135b.) and leaving `warnings' to
     ‘None’.

     在 3.2 版更改: Added the ‘warnings’ argument.

     在 3.2 版更改: The default stream is set to *note sys.stderr: 318.
     at instantiation time rather than import time.

     在 3.5 版更改: Added the tb_locals parameter.

      -- 方法: _makeResult ()

          This method returns the instance of ‘TestResult’ used by *note
          run(): 3381.  It is not intended to be called directly, but
          can be overridden in subclasses to provide a custom
          ‘TestResult’.

          ‘_makeResult()’ instantiates the class or callable passed in
          the ‘TextTestRunner’ constructor as the ‘resultclass’
          argument.  It defaults to *note TextTestResult: 3353. if no
          ‘resultclass’ is provided.  The result class is instantiated
          with the following arguments:

               stream, descriptions, verbosity

      -- 方法: run (test)

          This method is the main public interface to the
          ‘TextTestRunner’.  This method takes a *note TestSuite: 6d7.
          or *note TestCase: 907. instance.  A *note TestResult: ac7. is
          created by calling *note _makeResult(): 3380. and the test(s)
          are run and the results printed to stdout.

 -- 函数: unittest.main (module='__main__', defaultTest=None, argv=None,
          testRunner=None, testLoader=unittest.defaultTestLoader,
          exit=True, verbosity=1, failfast=None, catchbreak=None,
          buffer=None, warnings=None)

     A command-line program that loads a set of tests from `module' and
     runs them; this is primarily for making test modules conveniently
     executable.  The simplest use for this function is to include the
     following line at the end of a test script:

          if __name__ == '__main__':
              unittest.main()

     You can run tests with more detailed information by passing in the
     verbosity argument:

          if __name__ == '__main__':
              unittest.main(verbosity=2)

     The `defaultTest' argument is either the name of a single test or
     an iterable of test names to run if no test names are specified via
     `argv'.  If not specified or ‘None’ and no test names are provided
     via `argv', all tests found in `module' are run.

     The `argv' argument can be a list of options passed to the program,
     with the first element being the program name.  If not specified or
     ‘None’, the values of *note sys.argv: c03. are used.

     The `testRunner' argument can either be a test runner class or an
     already created instance of it.  By default ‘main’ calls *note
     sys.exit(): cea. with an exit code indicating success or failure of
     the tests run.

     The `testLoader' argument has to be a *note TestLoader: 78b.
     instance, and defaults to *note defaultTestLoader: 3362.

     ‘main’ supports being used from the interactive interpreter by
     passing in the argument ‘exit=False’.  This displays the result on
     standard output without calling *note sys.exit(): cea.:

          >>> from unittest import main
          >>> main(module='test_module', exit=False)

     The `failfast', `catchbreak' and `buffer' parameters have the same
     effect as the same-name *note command-line options: 332e.

     The `warnings' argument specifies the *note warning filter: 135c.
     that should be used while running the tests.  If it’s not
     specified, it will remain ‘None’ if a ‘-W’ option is passed to
     ‘python’ (see *note Warning control: 135b.), otherwise it will be
     set to ‘'default'’.

     Calling ‘main’ actually returns an instance of the ‘TestProgram’
     class.  This stores the result of the tests run as the ‘result’
     attribute.

     在 3.1 版更改: The `exit' parameter was added.

     在 3.2 版更改: The `verbosity', `failfast', `catchbreak', `buffer'
     and `warnings' parameters were added.

     在 3.4 版更改: The `defaultTest' parameter was changed to also
     accept an iterable of test names.

* Menu:

* load_tests Protocol::


File: python.info,  Node: load_tests Protocol,  Up: Loading and running tests

5.26.4.14 load_tests Protocol
.............................

3.2 新版功能.

Modules or packages can customize how tests are loaded from them during
normal test runs or test discovery by implementing a function called
‘load_tests’.

If a test module defines ‘load_tests’ it will be called by *note
TestLoader.loadTestsFromModule(): 789. with the following arguments:

     load_tests(loader, standard_tests, pattern)

where `pattern' is passed straight through from ‘loadTestsFromModule’.
It defaults to ‘None’.

It should return a *note TestSuite: 6d7.

`loader' is the instance of *note TestLoader: 78b. doing the loading.
`standard_tests' are the tests that would be loaded by default from the
module.  It is common for test modules to only want to add or remove
tests from the standard set of tests.  The third argument is used when
loading packages as part of test discovery.

A typical ‘load_tests’ function that loads tests from a specific set of
*note TestCase: 907. classes may look like:

     test_cases = (TestCase1, TestCase2, TestCase3)

     def load_tests(loader, tests, pattern):
         suite = TestSuite()
         for test_class in test_cases:
             tests = loader.loadTestsFromTestCase(test_class)
             suite.addTests(tests)
         return suite

If discovery is started in a directory containing a package, either from
the command line or by calling *note TestLoader.discover(): 90c, then
the package ‘__init__.py’ will be checked for ‘load_tests’.  If that
function does not exist, discovery will recurse into the package as
though it were just another directory.  Otherwise, discovery of the
package’s tests will be left up to ‘load_tests’ which is called with the
following arguments:

     load_tests(loader, standard_tests, pattern)

This should return a *note TestSuite: 6d7. representing all the tests
from the package.  (‘standard_tests’ will only contain tests collected
from ‘__init__.py’.)

Because the pattern is passed into ‘load_tests’ the package is free to
continue (and potentially modify) test discovery.  A ’do nothing’
‘load_tests’ function for a test package would look like:

     def load_tests(loader, standard_tests, pattern):
         # top level directory cached on loader instance
         this_dir = os.path.dirname(__file__)
         package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
         standard_tests.addTests(package_tests)
         return standard_tests

在 3.5 版更改: Discovery no longer checks package names for matching
`pattern' due to the impossibility of package names matching the default
pattern.


File: python.info,  Node: Class and Module Fixtures,  Next: 信号处理,  Prev: 类与函数,  Up: unittest --- 单元测试框架

5.26.4.15 Class and Module Fixtures
...................................

Class and module level fixtures are implemented in *note TestSuite: 6d7.
When the test suite encounters a test from a new class then
‘tearDownClass()’ from the previous class (if there is one) is called,
followed by ‘setUpClass()’ from the new class.

Similarly if a test is from a different module from the previous test
then ‘tearDownModule’ from the previous module is run, followed by
‘setUpModule’ from the new module.

After all the tests have run the final ‘tearDownClass’ and
‘tearDownModule’ are run.

Note that shared fixtures do not play well with [potential] features
like test parallelization and they break test isolation.  They should be
used with care.

The default ordering of tests created by the unittest test loaders is to
group all tests from the same modules and classes together.  This will
lead to ‘setUpClass’ / ‘setUpModule’ (etc) being called exactly once per
class and module.  If you randomize the order, so that tests from
different modules and classes are adjacent to each other, then these
shared fixture functions may be called multiple times in a single test
run.

Shared fixtures are not intended to work with suites with non-standard
ordering.  A ‘BaseTestSuite’ still exists for frameworks that don’t want
to support shared fixtures.

If there are any exceptions raised during one of the shared fixture
functions the test is reported as an error.  Because there is no
corresponding test instance an ‘_ErrorHolder’ object (that has the same
interface as a *note TestCase: 907.) is created to represent the error.
If you are just using the standard unittest test runner then this detail
doesn’t matter, but if you are a framework author it may be relevant.

* Menu:

* setUpClass and tearDownClass::
* setUpModule and tearDownModule::


File: python.info,  Node: setUpClass and tearDownClass,  Next: setUpModule and tearDownModule,  Up: Class and Module Fixtures

5.26.4.16 setUpClass and tearDownClass
......................................

These must be implemented as class methods:

     import unittest

     class Test(unittest.TestCase):
         @classmethod
         def setUpClass(cls):
             cls._connection = createExpensiveConnectionObject()

         @classmethod
         def tearDownClass(cls):
             cls._connection.destroy()

If you want the ‘setUpClass’ and ‘tearDownClass’ on base classes called
then you must call up to them yourself.  The implementations in *note
TestCase: 907. are empty.

If an exception is raised during a ‘setUpClass’ then the tests in the
class are not run and the ‘tearDownClass’ is not run.  Skipped classes
will not have ‘setUpClass’ or ‘tearDownClass’ run.  If the exception is
a *note SkipTest: 90b. exception then the class will be reported as
having been skipped instead of as an error.


File: python.info,  Node: setUpModule and tearDownModule,  Prev: setUpClass and tearDownClass,  Up: Class and Module Fixtures

5.26.4.17 setUpModule and tearDownModule
........................................

These should be implemented as functions:

     def setUpModule():
         createConnection()

     def tearDownModule():
         closeConnection()

If an exception is raised in a ‘setUpModule’ then none of the tests in
the module will be run and the ‘tearDownModule’ will not be run.  If the
exception is a *note SkipTest: 90b. exception then the module will be
reported as having been skipped instead of as an error.

To add cleanup code that must be run even in the case of an exception,
use ‘addModuleCleanup’:

 -- 函数: unittest.addModuleCleanup (function, /, *args, **kwargs)

     Add a function to be called after ‘tearDownModule()’ to cleanup
     resources used during the test class.  Functions will be called in
     reverse order to the order they are added (LIFO).  They are called
     with any arguments and keyword arguments passed into *note
     addModuleCleanup(): 24b. when they are added.

     If ‘setUpModule()’ fails, meaning that ‘tearDownModule()’ is not
     called, then any cleanup functions added will still be called.

     3.8 新版功能.

 -- 函数: unittest.doModuleCleanups ()

     This function is called unconditionally after ‘tearDownModule()’,
     or after ‘setUpModule()’ if ‘setUpModule()’ raises an exception.

     It is responsible for calling all the cleanup functions added by
     ‘addCleanupModule()’.  If you need cleanup functions to be called
     `prior' to ‘tearDownModule()’ then you can call *note
     doModuleCleanups(): 3384. yourself.

     *note doModuleCleanups(): 3384. pops methods off the stack of
     cleanup functions one at a time, so it can be called at any time.

     3.8 新版功能.


File: python.info,  Node: 信号处理,  Prev: Class and Module Fixtures,  Up: unittest --- 单元测试框架

5.26.4.18 信号处理
..................

3.2 新版功能.

The *note -c/–catch: ccc. command-line option to unittest, along with
the ‘catchbreak’ parameter to *note unittest.main(): 90a, provide more
friendly handling of control-C during a test run.  With catch break
behavior enabled control-C will allow the currently running test to
complete, and the test run will then end and report all the results so
far.  A second control-c will raise a *note KeyboardInterrupt: 198. in
the usual way.

The control-c handling signal handler attempts to remain compatible with
code or tests that install their own *note signal.SIGINT: 24e2. handler.
If the ‘unittest’ handler is called but `isn’t' the installed *note
signal.SIGINT: 24e2. handler, i.e.  it has been replaced by the system
under test and delegated to, then it calls the default handler.  This
will normally be the expected behavior by code that replaces an
installed handler and delegates to it.  For individual tests that need
‘unittest’ control-c handling disabled the *note removeHandler(): ccd.
decorator can be used.

There are a few utility functions for framework authors to enable
control-c handling functionality within test frameworks.

 -- 函数: unittest.installHandler ()

     Install the control-c handler.  When a *note signal.SIGINT: 24e2.
     is received (usually in response to the user pressing control-c)
     all registered results have *note stop(): 336f. called.

 -- 函数: unittest.registerResult (result)

     Register a *note TestResult: ac7. object for control-c handling.
     Registering a result stores a weak reference to it, so it doesn’t
     prevent the result from being garbage collected.

     Registering a *note TestResult: ac7. object has no side-effects if
     control-c handling is not enabled, so test frameworks can
     unconditionally register all results they create independently of
     whether or not handling is enabled.

 -- 函数: unittest.removeResult (result)

     Remove a registered result.  Once a result has been removed then
     *note stop(): 336f. will no longer be called on that result object
     in response to a control-c.

 -- 函数: unittest.removeHandler (function=None)

     When called without arguments this function removes the control-c
     handler if it has been installed.  This function can also be used
     as a test decorator to temporarily remove the handler while the
     test is being executed:

          @unittest.removeHandler
          def test_signal_handling(self):
              ...


File: python.info,  Node: unittest mock --- 模拟对象库,  Next: unittest mock 上手指南,  Prev: unittest --- 单元测试框架,  Up: 开发工具

5.26.5 ‘unittest.mock’ — 模拟对象库
-----------------------------------

3.3 新版功能.

`源代码：' Lib/unittest/mock.py(1)

__________________________________________________________________

*note unittest.mock: 11d. 是一个用于测试的Python库。它允许使用模拟对象来
替换受测系统的一些部分，并对这些部分如何被使用进行断言判断。

*note unittest.mock: 11d. 提供了一个核心类 *note Mock: 24a. 用于消除在整
个测试套件中创建大量存根(stub)的需求。在执行一个操作后，你就可以用断言去
判断：哪些方法/属性及其参数被调用到了。你还可以用常规的方式指定返回值并
设置所需的属性。

此外，mock 还提供了用于修补测试范围内模块和类级别属性的 *note patch():
791. 装饰器，和用于创建独特对象的 *note sentinel: 412. 。 阅读 *note
quick guide: 338a. 中的案例了解如何使用 *note Mock: 24a. ，*note
MagicMock: 78e. 和 *note patch(): 791. 。

Mock 是为 *note unittest: 11c. 而设计，且简单易用。模拟基于 ’action ->
assertion’ 模式，而不是许多模拟框架所使用的 ’record -> replay’模式。

在 Python 的早期版本要单独使用 *note unittest.mock: 11d. ，在 PyPI 获取
mock(2)

* Menu:

* 快速上手::
* Mock 类::
* The patchers::
* MagicMock and magic method support::
* Helpers::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/unittest/mock.py

   (2) https://pypi.org/project/mock


File: python.info,  Node: 快速上手,  Next: Mock 类,  Up: unittest mock --- 模拟对象库

5.26.5.1 快速上手
.................

当您访问对象时， *note Mock: 24a. 和 *note MagicMock: 78e. 将创建所有属
性和方法，并保存他们在使用时的细节。你可以通过配置，指定返回值或者限制可
访问属性，然后断言他们如何被调用。

     >>> from unittest.mock import MagicMock
     >>> thing = ProductionClass()
     >>> thing.method = MagicMock(return_value=3)
     >>> thing.method(3, 4, 5, key='value')
     3
     >>> thing.method.assert_called_with(3, 4, 5, key='value')

通过 ‘side_effect’ 设置副作用(side effects) ，可以是一个 mock 被调用是抛
出的异常

     >>> mock = Mock(side_effect=KeyError('foo'))
     >>> mock()
     Traceback (most recent call last):
      ...
     KeyError: 'foo'

     >>> values = {'a': 1, 'b': 2, 'c': 3}
     >>> def side_effect(arg):
     ...     return values[arg]
     ...
     >>> mock.side_effect = side_effect
     >>> mock('a'), mock('b'), mock('c')
     (1, 2, 3)
     >>> mock.side_effect = [5, 4, 3, 2, 1]
     >>> mock(), mock(), mock()
     (5, 4, 3)

Mock 还可以通过其他方法配置和控制其行为。例如 mock 可以通过设置 `spec' 参
数来从一个对象中获取其规格(specification)。如果访问 mock 的属性或方法不
在 spec 中，会报 *note AttributeError: 3a3. 错误。

使用 *note patch(): 791. 装饰去/上下文管理器，可以更方便地测试一个模块下
的类或对象。你指定的对象会在测试过程中替换成 mock （或者其他对象），测试
结束后恢复。

     >>> from unittest.mock import patch
     >>> @patch('module.ClassName2')
     ... @patch('module.ClassName1')
     ... def test(MockClass1, MockClass2):
     ...     module.ClassName1()
     ...     module.ClassName2()
     ...     assert MockClass1 is module.ClassName1
     ...     assert MockClass2 is module.ClassName2
     ...     assert MockClass1.called
     ...     assert MockClass2.called
     ...
     >>> test()

     注解: 当你嵌套 patch 装饰器时，mock 将以执行顺序传递给装饰器函数（
     `Python' 装饰器正常顺序）。由于从下至上，因此在上面的示例中，首先
     mock 传入的 ‘module.ClassName1’ 。

     在查找对象的名称空间中修补对象使用 *note patch(): 791. 。使用起来很
     简单，阅读 *note 在哪里打补丁: 338b. 来快速上手。

*note patch(): 791. 也可以 with 语句中使用上下文管理。

     >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
     ...     thing = ProductionClass()
     ...     thing.method(1, 2, 3)
     ...
     >>> mock_method.assert_called_once_with(1, 2, 3)

还有一个 *note patch.dict(): fdf. 用于在一定范围内设置字典中的值，并在测
试结束时将字典恢复为其原始状态：

     >>> foo = {'key': 'value'}
     >>> original = foo.copy()
     >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
     ...     assert foo == {'newkey': 'newvalue'}
     ...
     >>> assert foo == original

Mock支持 Python *note 魔术方法: 338c. 。使用模式方法最简单的方式是使用
*note MagicMock: 78e. class. 。它可以做如下事情：

     >>> mock = MagicMock()
     >>> mock.__str__.return_value = 'foobarbaz'
     >>> str(mock)
     'foobarbaz'
     >>> mock.__str__.assert_called_with()

Mock 能指定函数（或其他 Mock 实例）为魔术方法，它们将被适当地调用。
*note MagicMock: 78e. 是预先创建了所有魔术方法（所有有用的方法） 的 Mock
。

下面是一个使用了普通 Mock 类的魔术方法的例子

     >>> mock = Mock()
     >>> mock.__str__ = Mock(return_value='wheeeeee')
     >>> str(mock)
     'wheeeeee'

使用 *note auto-speccing: 338d. 可以保证测试中的模拟对象与要替换的对象具
有相同的api 。在 patch 中可以通过 `autospec' 参数实现自动推断，或者使用
*note create_autospec(): f59. 函数。自动推断会创建一个与要替换对象相同的
属相和方法的模拟对象，并且任何函数和方法（包括构造函数）都具有与真实对象
相同的调用签名。

这么做是为了因确保不当地使用 mock 导致与生产代码相同的失败：

     >>> from unittest.mock import create_autospec
     >>> def function(a, b, c):
     ...     pass
     ...
     >>> mock_function = create_autospec(function, return_value='fishy')
     >>> mock_function(1, 2, 3)
     'fishy'
     >>> mock_function.assert_called_once_with(1, 2, 3)
     >>> mock_function('wrong arguments')
     Traceback (most recent call last):
      ...
     TypeError: <lambda>() takes exactly 3 arguments (1 given)

在类中使用 *note create_autospec(): f59. 时，会复制 ‘__init__’ 的签名，
另外在可调用对象上使用时，会复制 ‘__call__’ 的签名。


File: python.info,  Node: Mock 类,  Next: The patchers,  Prev: 快速上手,  Up: unittest mock --- 模拟对象库

5.26.5.2 Mock 类
................

*note Mock: 24a. 是一个可以灵活的替换存根 (stubs) 的对象，可以测试所有代
码。 Mock 是可调用的，在访问其属性时创建一个新的 mock (1) 。访问相同的属
性只会返回相同的 mock 。 Mock 保存调用记录，可以通过断言获悉代码的调用。

*note MagicMock: 78e. 是 *note Mock: 24a. 的子类，它有所有预创建且可使用
的魔术方法。在需要模拟不可调用对象时，可以使用 *note NonCallableMock:
338f.  和 *note NonCallableMagicMock: 3390.

*note patch(): 791. 装饰器使得用 *note Mock: 24a. 对象临时替换特定模块中
的类非常方便。 默认情况下 *note patch(): 791. 将为你创建一个 *note
MagicMock: 78e.。 你可以使用 *note patch(): 791. 的 `new_callable' 参数
指定替代 *note Mock: 24a. 的类。

 -- 类: unittest.mock.Mock (spec=None, side_effect=None,
          return_value=DEFAULT, wraps=None, name=None, spec_set=None,
          unsafe=False, **kwargs)

     创建一个新的 *note Mock: 24a. 对象。通过可选参数指定 *note Mock:
     24a. 对象的行为：

        * `spec': 可以是要给字符串列表，也可以是充当模拟对象规范的现有对
          象（类或实例）。如果传入一个对象，则通过在该对象上调用 dir 来
          生成字符串列表（不支持的魔法属性和方法除外）。访问不在此列表中
          的任何属性都将引发 *note AttributeError: 3a3. 。

          如果 `spec' 是一个对象（而不是字符串列表），则 *note
          __class__: e12. 返回 `spec' 对象的类。 这允许模拟程序通过
          *note isinstance(): 457. 测试。

        * `spec_set' ：`spec' 的更严格的变体。如果使用了该属性，尝试模拟
          `set' 或 `get' 的属性不在 `spec_set' 所包含的对象中时，会抛出
          *note AttributeError: 3a3. 。

        * `side_effect' ：每当调用 Mock 时都会调用的函数。 参见 *note
          side_effect: 3391. 属性。 对于引发异常或动态更改返回值很有用。
          该函数使用与 mock 函数相同的参数调用，并且除非返回 *note
          DEFAULT: 3392. ，否则该函数的返回值将用作返回值。

          另外， `side_effect' 可以是异常类或实例。 此时，调用模拟程序时
          将引发异常。

          如果 `side_effect' 是可迭代对象，则每次调用 mock 都将返回可迭
          代对象的下一个值。

          设置 `side_effect' 为 ‘None’ 即可清空。

        * `return_value' ：调用 mock 的返回值。 默认情况下，是一个新的
          Mock（在首次访问时创建）。 参见 *note return_value: 3393. 属性
          。

        * `unsafe' ：默认情况下，如果任何以 `assert' 或 `assret' 开头的
          属性都将引发 *note AttributeError: 3a3. 。 当 ‘unsafe=True’ 时
          可以访问。

          3.5 新版功能.

        * `wraps' ：要包装的 mock 对象。 如果 `wraps' 不是 ‘None’ ，那么
          调用 Mock 会将调用传递给 `wraps' 的对象（返回实际结果）。 对模
          拟的属性访问将返回一个 Mock 对象，该对象包装了 `wraps' 对象的
          相应属性（因此，尝试访问不存在的属性将引发 *note
          AttributeError: 3a3. ）。

          如果该 mock 明确指定 `return_value' ，调用是，不会返回包装对象
          ，而是返回 `return_value' 。

        * `name' ：mock 的名称。 在调试时很有用。 名称会传递到子 mock 。

     还可以使用任意关键字参数来调用 mock 。 创建模拟后，将使用这些属性来
     设置 mock 的属性。 有关详细信息，请参见 *note configure_mock():
     3394. 方法。

      -- 方法: assert_called ()

          断言该 mock 至少被调用过一次。

               >>> mock = Mock()
               >>> mock.method()
               <Mock name='mock.method()' id='...'>
               >>> mock.method.assert_called()

          3.6 新版功能.

      -- 方法: assert_called_once ()

          断言仅被调用一次。

               >>> mock = Mock()
               >>> mock.method()
               <Mock name='mock.method()' id='...'>
               >>> mock.method.assert_called_once()
               >>> mock.method()
               <Mock name='mock.method()' id='...'>
               >>> mock.method.assert_called_once()
               Traceback (most recent call last):
               ...
               AssertionError: Expected 'method' to have been called once. Called 2 times.

          3.6 新版功能.

      -- 方法: assert_called_with (*args, **kwargs)

          此方法是断言上次调用已以特定方式进行的一种便捷方法：

               >>> mock = Mock()
               >>> mock.method(1, 2, 3, test='wow')
               <Mock name='mock.method()' id='...'>
               >>> mock.method.assert_called_with(1, 2, 3, test='wow')

      -- 方法: assert_called_once_with (*args, **kwargs)

          断言仅被调用一次，并且该调用是使用指定的参数进行的。

               >>> mock = Mock(return_value=None)
               >>> mock('foo', bar='baz')
               >>> mock.assert_called_once_with('foo', bar='baz')
               >>> mock('other', bar='values')
               >>> mock.assert_called_once_with('other', bar='values')
               Traceback (most recent call last):
                 ...
               AssertionError: Expected 'mock' to be called once. Called 2 times.

      -- 方法: assert_any_call (*args, **kwargs)

          断言使用指定的参数调用。

          The assert passes if the mock has `ever' been called, unlike
          *note assert_called_with(): 100f. and *note
          assert_called_once_with(): 3395. that only pass if the call is
          the most recent one, and in the case of *note
          assert_called_once_with(): 3395. it must also be the only
          call.

               >>> mock = Mock(return_value=None)
               >>> mock(1, 2, arg='thing')
               >>> mock('some', 'thing', 'else')
               >>> mock.assert_any_call(1, 2, arg='thing')

      -- 方法: assert_has_calls (calls, any_order=False)

          assert the mock has been called with the specified calls.  The
          *note mock_calls: 3398. list is checked for the calls.

          If `any_order' is false then the calls must be sequential.
          There can be extra calls before or after the specified calls.

          If `any_order' is true then the calls can be in any order, but
          they must all appear in *note mock_calls: 3398.

               >>> mock = Mock(return_value=None)
               >>> mock(1)
               >>> mock(2)
               >>> mock(3)
               >>> mock(4)
               >>> calls = [call(2), call(3)]
               >>> mock.assert_has_calls(calls)
               >>> calls = [call(4), call(2), call(3)]
               >>> mock.assert_has_calls(calls, any_order=True)

      -- 方法: assert_not_called ()

          Assert the mock was never called.

               >>> m = Mock()
               >>> m.hello.assert_not_called()
               >>> obj = m.hello()
               >>> m.hello.assert_not_called()
               Traceback (most recent call last):
                 ...
               AssertionError: Expected 'hello' to not have been called. Called 1 times.

          3.5 新版功能.

      -- 方法: reset_mock (*, return_value=False, side_effect=False)

          The reset_mock method resets all the call attributes on a mock
          object:

               >>> mock = Mock(return_value=None)
               >>> mock('hello')
               >>> mock.called
               True
               >>> mock.reset_mock()
               >>> mock.called
               False

          在 3.6 版更改: Added two keyword only argument to the
          reset_mock function.

          This can be useful where you want to make a series of
          assertions that reuse the same object.  Note that *note
          reset_mock(): 5b3. `doesn’t' clear the return value, *note
          side_effect: 3391. or any child attributes you have set using
          normal assignment by default.  In case you want to reset
          `return_value' or *note side_effect: 3391, then pass the
          corresponding parameter as ‘True’.  Child mocks and the return
          value mock (if any) are reset as well.

               注解: `return_value', and *note side_effect: 3391. are
               keyword only argument.

      -- 方法: mock_add_spec (spec, spec_set=False)

          Add a spec to a mock.  `spec' can either be an object or a
          list of strings.  Only attributes on the `spec' can be fetched
          as attributes from the mock.

          If `spec_set' is true then only attributes on the spec can be
          set.

      -- 方法: attach_mock (mock, attribute)

          Attach a mock as an attribute of this one, replacing its name
          and parent.  Calls to the attached mock will be recorded in
          the *note method_calls: 339b. and *note mock_calls: 3398.
          attributes of this one.

      -- 方法: configure_mock (**kwargs)

          Set attributes on the mock through keyword arguments.

          Attributes plus return values and side effects can be set on
          child mocks using standard dot notation and unpacking a
          dictionary in the method call:

               >>> mock = Mock()
               >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
               >>> mock.configure_mock(**attrs)
               >>> mock.method()
               3
               >>> mock.other()
               Traceback (most recent call last):
                 ...
               KeyError

          The same thing can be achieved in the constructor call to
          mocks:

               >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
               >>> mock = Mock(some_attribute='eggs', **attrs)
               >>> mock.some_attribute
               'eggs'
               >>> mock.method()
               3
               >>> mock.other()
               Traceback (most recent call last):
                 ...
               KeyError

          *note configure_mock(): 3394. exists to make it easier to do
          configuration after the mock has been created.

      -- 方法: __dir__ ()

          *note Mock: 24a. objects limit the results of ‘dir(some_mock)’
          to useful results.  For mocks with a `spec' this includes all
          the permitted attributes for the mock.

          See *note FILTER_DIR: 339d. for what this filtering does, and
          how to switch it off.

      -- 方法: _get_child_mock (**kw)

          Create the child mocks for attributes and return value.  By
          default child mocks will be the same type as the parent.
          Subclasses of Mock may want to override this to customize the
          way child mocks are made.

          For non-callable mocks the callable variant will be used
          (rather than any custom subclass).

      -- 属性: called

          A boolean representing whether or not the mock object has been
          called:

               >>> mock = Mock(return_value=None)
               >>> mock.called
               False
               >>> mock()
               >>> mock.called
               True

      -- 属性: call_count

          An integer telling you how many times the mock object has been
          called:

               >>> mock = Mock(return_value=None)
               >>> mock.call_count
               0
               >>> mock()
               >>> mock()
               >>> mock.call_count
               2

      -- 属性: return_value

          Set this to configure the value returned by calling the mock:

               >>> mock = Mock()
               >>> mock.return_value = 'fish'
               >>> mock()
               'fish'

          The default return value is a mock object and you can
          configure it in the normal way:

               >>> mock = Mock()
               >>> mock.return_value.attribute = sentinel.Attribute
               >>> mock.return_value()
               <Mock name='mock()()' id='...'>
               >>> mock.return_value.assert_called_with()

          *note return_value: 3393. can also be set in the constructor:

               >>> mock = Mock(return_value=3)
               >>> mock.return_value
               3
               >>> mock()
               3

      -- 属性: side_effect

          This can either be a function to be called when the mock is
          called, an iterable or an exception (class or instance) to be
          raised.

          If you pass in a function it will be called with same
          arguments as the mock and unless the function returns the
          *note DEFAULT: 3392. singleton the call to the mock will then
          return whatever the function returns.  If the function returns
          *note DEFAULT: 3392. then the mock will return its normal
          value (from the *note return_value: 3393.).

          If you pass in an iterable, it is used to retrieve an iterator
          which must yield a value on every call.  This value can either
          be an exception instance to be raised, or a value to be
          returned from the call to the mock (*note DEFAULT: 3392.
          handling is identical to the function case).

          An example of a mock that raises an exception (to test
          exception handling of an API):

               >>> mock = Mock()
               >>> mock.side_effect = Exception('Boom!')
               >>> mock()
               Traceback (most recent call last):
                 ...
               Exception: Boom!

          Using *note side_effect: 3391. to return a sequence of values:

               >>> mock = Mock()
               >>> mock.side_effect = [3, 2, 1]
               >>> mock(), mock(), mock()
               (3, 2, 1)

          Using a callable:

               >>> mock = Mock(return_value=3)
               >>> def side_effect(*args, **kwargs):
               ...     return DEFAULT
               ...
               >>> mock.side_effect = side_effect
               >>> mock()
               3

          *note side_effect: 3391. can be set in the constructor.
          Here’s an example that adds one to the value the mock is
          called with and returns it:

               >>> side_effect = lambda value: value + 1
               >>> mock = Mock(side_effect=side_effect)
               >>> mock(3)
               4
               >>> mock(-8)
               -7

          Setting *note side_effect: 3391. to ‘None’ clears it:

               >>> m = Mock(side_effect=KeyError, return_value=3)
               >>> m()
               Traceback (most recent call last):
                ...
               KeyError
               >>> m.side_effect = None
               >>> m()
               3

      -- 属性: call_args

          This is either ‘None’ (if the mock hasn’t been called), or the
          arguments that the mock was last called with.  This will be in
          the form of a tuple: the first member, which can also be
          accessed through the ‘args’ property, is any ordered arguments
          the mock was called with (or an empty tuple) and the second
          member, which can also be accessed through the ‘kwargs’
          property, is any keyword arguments (or an empty dictionary).

               >>> mock = Mock(return_value=None)
               >>> print(mock.call_args)
               None
               >>> mock()
               >>> mock.call_args
               call()
               >>> mock.call_args == ()
               True
               >>> mock(3, 4)
               >>> mock.call_args
               call(3, 4)
               >>> mock.call_args == ((3, 4),)
               True
               >>> mock.call_args.args
               (3, 4)
               >>> mock.call_args.kwargs
               {}
               >>> mock(3, 4, 5, key='fish', next='w00t!')
               >>> mock.call_args
               call(3, 4, 5, key='fish', next='w00t!')
               >>> mock.call_args.args
               (3, 4, 5)
               >>> mock.call_args.kwargs
               {'key': 'fish', 'next': 'w00t!'}

          *note call_args: f34, along with members of the lists *note
          call_args_list: 33a1, *note method_calls: 339b. and *note
          mock_calls: 3398. are *note call: f8a. objects.  These are
          tuples, so they can be unpacked to get at the individual
          arguments and make more complex assertions.  See *note calls
          as tuples: 33a2.

          在 3.8 版更改: Added ‘args’ and ‘kwargs’ properties.

      -- 属性: call_args_list

          This is a list of all the calls made to the mock object in
          sequence (so the length of the list is the number of times it
          has been called).  Before any calls have been made it is an
          empty list.  The *note call: f8a. object can be used for
          conveniently constructing lists of calls to compare with *note
          call_args_list: 33a1.

               >>> mock = Mock(return_value=None)
               >>> mock()
               >>> mock(3, 4)
               >>> mock(key='fish', next='w00t!')
               >>> mock.call_args_list
               [call(), call(3, 4), call(key='fish', next='w00t!')]
               >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
               >>> mock.call_args_list == expected
               True

          Members of *note call_args_list: 33a1. are *note call: f8a.
          objects.  These can be unpacked as tuples to get at the
          individual arguments.  See *note calls as tuples: 33a2.

      -- 属性: method_calls

          As well as tracking calls to themselves, mocks also track
          calls to methods and attributes, and `their' methods and
          attributes:

               >>> mock = Mock()
               >>> mock.method()
               <Mock name='mock.method()' id='...'>
               >>> mock.property.method.attribute()
               <Mock name='mock.property.method.attribute()' id='...'>
               >>> mock.method_calls
               [call.method(), call.property.method.attribute()]

          Members of *note method_calls: 339b. are *note call: f8a.
          objects.  These can be unpacked as tuples to get at the
          individual arguments.  See *note calls as tuples: 33a2.

      -- 属性: mock_calls

          *note mock_calls: 3398. records `all' calls to the mock
          object, its methods, magic methods `and' return value mocks.

               >>> mock = MagicMock()
               >>> result = mock(1, 2, 3)
               >>> mock.first(a=3)
               <MagicMock name='mock.first()' id='...'>
               >>> mock.second()
               <MagicMock name='mock.second()' id='...'>
               >>> int(mock)
               1
               >>> result(1)
               <MagicMock name='mock()()' id='...'>
               >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
               ... call.__int__(), call()(1)]
               >>> mock.mock_calls == expected
               True

          Members of *note mock_calls: 3398. are *note call: f8a.
          objects.  These can be unpacked as tuples to get at the
          individual arguments.  See *note calls as tuples: 33a2.

               注解: The way *note mock_calls: 3398. are recorded means
               that where nested calls are made, the parameters of
               ancestor calls are not recorded and so will always
               compare equal:

                    >>> mock = MagicMock()
                    >>> mock.top(a=3).bottom()
                    <MagicMock name='mock.top().bottom()' id='...'>
                    >>> mock.mock_calls
                    [call.top(a=3), call.top().bottom()]
                    >>> mock.mock_calls[-1] == call.top(a=-1).bottom()
                    True

      -- 属性: __class__

          Normally the *note __class__: 33a3. attribute of an object
          will return its type.  For a mock object with a ‘spec’,
          ‘__class__’ returns the spec class instead.  This allows mock
          objects to pass *note isinstance(): 457. tests for the object
          they are replacing / masquerading as:

               >>> mock = Mock(spec=3)
               >>> isinstance(mock, int)
               True

          *note __class__: 33a3. is assignable to, this allows a mock to
          pass an *note isinstance(): 457. check without forcing you to
          use a spec:

               >>> mock = Mock()
               >>> mock.__class__ = dict
               >>> isinstance(mock, dict)
               True

 -- 类: unittest.mock.NonCallableMock (spec=None, wraps=None, name=None,
          spec_set=None, **kwargs)

     A non-callable version of *note Mock: 24a.  The constructor
     parameters have the same meaning of *note Mock: 24a, with the
     exception of `return_value' and `side_effect' which have no meaning
     on a non-callable mock.

Mock objects that use a class or an instance as a ‘spec’ or ‘spec_set’
are able to pass *note isinstance(): 457. tests:

     >>> mock = Mock(spec=SomeClass)
     >>> isinstance(mock, SomeClass)
     True
     >>> mock = Mock(spec_set=SomeClass())
     >>> isinstance(mock, SomeClass)
     True

The *note Mock: 24a. classes have support for mocking magic methods.
See *note magic methods: 338c. for the full details.

The mock classes and the *note patch(): 791. decorators all take
arbitrary keyword arguments for configuration.  For the *note patch():
791. decorators the keywords are passed to the constructor of the mock
being created.  The keyword arguments are for configuring attributes of
the mock:

     >>> m = MagicMock(attribute=3, other='fish')
     >>> m.attribute
     3
     >>> m.other
     'fish'

The return value and side effect of child mocks can be set in the same
way, using dotted notation.  As you can’t use dotted names directly in a
call you have to create a dictionary and unpack it using ‘**’:

     >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
     >>> mock = Mock(some_attribute='eggs', **attrs)
     >>> mock.some_attribute
     'eggs'
     >>> mock.method()
     3
     >>> mock.other()
     Traceback (most recent call last):
       ...
     KeyError

A callable mock which was created with a `spec' (or a `spec_set') will
introspect the specification object’s signature when matching calls to
the mock.  Therefore, it can match the actual call’s arguments
regardless of whether they were passed positionally or by name:

     >>> def f(a, b, c): pass
     ...
     >>> mock = Mock(spec=f)
     >>> mock(1, 2, c=3)
     <Mock name='mock()' id='140161580456576'>
     >>> mock.assert_called_with(1, 2, 3)
     >>> mock.assert_called_with(a=1, b=2, c=3)

This applies to *note assert_called_with(): 100f, *note
assert_called_once_with(): 3395, *note assert_has_calls(): 3397. and
*note assert_any_call(): 3396.  When *note Autospeccing: 338d, it will
also apply to method calls on the mock object.

     在 3.4 版更改: Added signature introspection on specced and
     autospecced mock objects.

 -- 类: unittest.mock.PropertyMock (*args, **kwargs)

     A mock intended to be used as a property, or other descriptor, on a
     class.  *note PropertyMock: 33a4. provides *note __get__(): 144b.
     and *note __set__(): 144f. methods so you can specify a return
     value when it is fetched.

     Fetching a *note PropertyMock: 33a4. instance from an object calls
     the mock, with no args.  Setting it calls the mock with the value
     being set.

          >>> class Foo:
          ...     @property
          ...     def foo(self):
          ...         return 'something'
          ...     @foo.setter
          ...     def foo(self, value):
          ...         pass
          ...
          >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
          ...     mock_foo.return_value = 'mockity-mock'
          ...     this_foo = Foo()
          ...     print(this_foo.foo)
          ...     this_foo.foo = 6
          ...
          mockity-mock
          >>> mock_foo.mock_calls
          [call(), call(6)]

Because of the way mock attributes are stored you can’t directly attach
a *note PropertyMock: 33a4. to a mock object.  Instead you can attach it
to the mock type object:

     >>> m = MagicMock()
     >>> p = PropertyMock(return_value=3)
     >>> type(m).foo = p
     >>> m.foo
     3
     >>> p.assert_called_once_with()

 -- 类: unittest.mock.AsyncMock (spec=None, side_effect=None,
          return_value=DEFAULT, wraps=None, name=None, spec_set=None,
          unsafe=False, **kwargs)

     An asynchronous version of *note Mock: 24a.  The *note AsyncMock:
     249. object will behave so the object is recognized as an async
     function, and the result of a call is an awaitable.

          >>> mock = AsyncMock()
          >>> asyncio.iscoroutinefunction(mock)
          True
          >>> inspect.isawaitable(mock())
          True

     The result of ‘mock()’ is an async function which will have the
     outcome of ‘side_effect’ or ‘return_value’ after it has been
     awaited:

        - if ‘side_effect’ is a function, the async function will return
          the result of that function,

        - if ‘side_effect’ is an exception, the async function will
          raise the exception,

        - if ‘side_effect’ is an iterable, the async function will
          return the next value of the iterable, however, if the
          sequence of result is exhausted, ‘StopAsyncIteration’ is
          raised immediately,

        - if ‘side_effect’ is not defined, the async function will
          return the value defined by ‘return_value’, hence, by default,
          the async function returns a new *note AsyncMock: 249. object.

     Setting the `spec' of a *note Mock: 24a. or *note MagicMock: 78e.
     to an async function will result in a coroutine object being
     returned after calling.

          >>> async def async_func(): pass
          ...
          >>> mock = MagicMock(async_func)
          >>> mock
          <MagicMock spec='function' id='...'>
          >>> mock()
          <coroutine object AsyncMockMixin._mock_call at ...>

     Setting the `spec' of a *note Mock: 24a, *note MagicMock: 78e, or
     *note AsyncMock: 249. to a class with asynchronous and synchronous
     functions will automatically detect the synchronous functions and
     set them as *note MagicMock: 78e. (if the parent mock is *note
     AsyncMock: 249. or *note MagicMock: 78e.) or *note Mock: 24a. (if
     the parent mock is *note Mock: 24a.).  All asynchronous functions
     will be *note AsyncMock: 249.

          >>> class ExampleClass:
          ...     def sync_foo():
          ...         pass
          ...     async def async_foo():
          ...         pass
          ...
          >>> a_mock = AsyncMock(ExampleClass)
          >>> a_mock.sync_foo
          <MagicMock name='mock.sync_foo' id='...'>
          >>> a_mock.async_foo
          <AsyncMock name='mock.async_foo' id='...'>
          >>> mock = Mock(ExampleClass)
          >>> mock.sync_foo
          <Mock name='mock.sync_foo' id='...'>
          >>> mock.async_foo
          <AsyncMock name='mock.async_foo' id='...'>

     3.8 新版功能.

      -- 方法: assert_awaited ()

          Assert that the mock was awaited at least once.  Note that
          this is separate from the object having been called, the
          ‘await’ keyword must be used:

               >>> mock = AsyncMock()
               >>> async def main(coroutine_mock):
               ...     await coroutine_mock
               ...
               >>> coroutine_mock = mock()
               >>> mock.called
               True
               >>> mock.assert_awaited()
               Traceback (most recent call last):
               ...
               AssertionError: Expected mock to have been awaited.
               >>> asyncio.run(main(coroutine_mock))
               >>> mock.assert_awaited()

      -- 方法: assert_awaited_once ()

          Assert that the mock was awaited exactly once.

               >>> mock = AsyncMock()
               >>> async def main():
               ...     await mock()
               ...
               >>> asyncio.run(main())
               >>> mock.assert_awaited_once()
               >>> asyncio.run(main())
               >>> mock.method.assert_awaited_once()
               Traceback (most recent call last):
               ...
               AssertionError: Expected mock to have been awaited once. Awaited 2 times.

      -- 方法: assert_awaited_with (*args, **kwargs)

          Assert that the last await was with the specified arguments.

               >>> mock = AsyncMock()
               >>> async def main(*args, **kwargs):
               ...     await mock(*args, **kwargs)
               ...
               >>> asyncio.run(main('foo', bar='bar'))
               >>> mock.assert_awaited_with('foo', bar='bar')
               >>> mock.assert_awaited_with('other')
               Traceback (most recent call last):
               ...
               AssertionError: expected call not found.
               Expected: mock('other')
               Actual: mock('foo', bar='bar')

      -- 方法: assert_awaited_once_with (*args, **kwargs)

          Assert that the mock was awaited exactly once and with the
          specified arguments.

               >>> mock = AsyncMock()
               >>> async def main(*args, **kwargs):
               ...     await mock(*args, **kwargs)
               ...
               >>> asyncio.run(main('foo', bar='bar'))
               >>> mock.assert_awaited_once_with('foo', bar='bar')
               >>> asyncio.run(main('foo', bar='bar'))
               >>> mock.assert_awaited_once_with('foo', bar='bar')
               Traceback (most recent call last):
               ...
               AssertionError: Expected mock to have been awaited once. Awaited 2 times.

      -- 方法: assert_any_await (*args, **kwargs)

          Assert the mock has ever been awaited with the specified
          arguments.

               >>> mock = AsyncMock()
               >>> async def main(*args, **kwargs):
               ...     await mock(*args, **kwargs)
               ...
               >>> asyncio.run(main('foo', bar='bar'))
               >>> asyncio.run(main('hello'))
               >>> mock.assert_any_await('foo', bar='bar')
               >>> mock.assert_any_await('other')
               Traceback (most recent call last):
               ...
               AssertionError: mock('other') await not found

      -- 方法: assert_has_awaits (calls, any_order=False)

          Assert the mock has been awaited with the specified calls.
          The *note await_args_list: f33. list is checked for the
          awaits.

          If `any_order' is false then the awaits must be sequential.
          There can be extra calls before or after the specified awaits.

          If `any_order' is true then the awaits can be in any order,
          but they must all appear in *note await_args_list: f33.

               >>> mock = AsyncMock()
               >>> async def main(*args, **kwargs):
               ...     await mock(*args, **kwargs)
               ...
               >>> calls = [call("foo"), call("bar")]
               >>> mock.assert_has_awaits(calls)
               Traceback (most recent call last):
               ...
               AssertionError: Awaits not found.
               Expected: [call('foo'), call('bar')]
               Actual: []
               >>> asyncio.run(main('foo'))
               >>> asyncio.run(main('bar'))
               >>> mock.assert_has_awaits(calls)

      -- 方法: assert_not_awaited ()

          Assert that the mock was never awaited.

               >>> mock = AsyncMock()
               >>> mock.assert_not_awaited()

      -- 方法: reset_mock (*args, **kwargs)

          See *note Mock.reset_mock(): 5b3.  Also sets *note
          await_count: 33ad. to 0, *note await_args: 33ae. to None, and
          clears the *note await_args_list: f33.

      -- 属性: await_count

          An integer keeping track of how many times the mock object has
          been awaited.

               >>> mock = AsyncMock()
               >>> async def main():
               ...     await mock()
               ...
               >>> asyncio.run(main())
               >>> mock.await_count
               1
               >>> asyncio.run(main())
               >>> mock.await_count
               2

      -- 属性: await_args

          This is either ‘None’ (if the mock hasn’t been awaited), or
          the arguments that the mock was last awaited with.  Functions
          the same as *note Mock.call_args: f34.

               >>> mock = AsyncMock()
               >>> async def main(*args):
               ...     await mock(*args)
               ...
               >>> mock.await_args
               >>> asyncio.run(main('foo'))
               >>> mock.await_args
               call('foo')
               >>> asyncio.run(main('bar'))
               >>> mock.await_args
               call('bar')

      -- 属性: await_args_list

          This is a list of all the awaits made to the mock object in
          sequence (so the length of the list is the number of times it
          has been awaited).  Before any awaits have been made it is an
          empty list.

               >>> mock = AsyncMock()
               >>> async def main(*args):
               ...     await mock(*args)
               ...
               >>> mock.await_args_list
               []
               >>> asyncio.run(main('foo'))
               >>> mock.await_args_list
               [call('foo')]
               >>> asyncio.run(main('bar'))
               >>> mock.await_args_list
               [call('foo'), call('bar')]

* Menu:

* Calling::
* Deleting Attributes::
* Mock names and the name attribute::
* Attaching Mocks as Attributes::

   ---------- Footnotes ----------

   (1) (1) The only exceptions are magic methods and attributes (those
that have leading and trailing double underscores).  Mock doesn’t create
these but instead raises an *note AttributeError: 3a3.  This is because
the interpreter will often implicitly request these methods, and gets
`very' confused to get a new Mock object when it expects a magic method.
If you need magic method support see *note magic methods: 338c.


File: python.info,  Node: Calling,  Next: Deleting Attributes,  Up: Mock 类

5.26.5.3 Calling
................

Mock objects are callable.  The call will return the value set as the
*note return_value: 3393. attribute.  The default return value is a new
Mock object; it is created the first time the return value is accessed
(either explicitly or by calling the Mock) - but it is stored and the
same one returned each time.

Calls made to the object will be recorded in the attributes like *note
call_args: f34. and *note call_args_list: 33a1.

If *note side_effect: 3391. is set then it will be called after the call
has been recorded, so if ‘side_effect’ raises an exception the call is
still recorded.

The simplest way to make a mock raise an exception when called is to
make *note side_effect: 3391. an exception class or instance:

     >>> m = MagicMock(side_effect=IndexError)
     >>> m(1, 2, 3)
     Traceback (most recent call last):
       ...
     IndexError
     >>> m.mock_calls
     [call(1, 2, 3)]
     >>> m.side_effect = KeyError('Bang!')
     >>> m('two', 'three', 'four')
     Traceback (most recent call last):
       ...
     KeyError: 'Bang!'
     >>> m.mock_calls
     [call(1, 2, 3), call('two', 'three', 'four')]

If ‘side_effect’ is a function then whatever that function returns is
what calls to the mock return.  The ‘side_effect’ function is called
with the same arguments as the mock.  This allows you to vary the return
value of the call dynamically, based on the input:

     >>> def side_effect(value):
     ...     return value + 1
     ...
     >>> m = MagicMock(side_effect=side_effect)
     >>> m(1)
     2
     >>> m(2)
     3
     >>> m.mock_calls
     [call(1), call(2)]

If you want the mock to still return the default return value (a new
mock), or any set return value, then there are two ways of doing this.
Either return ‘mock.return_value’ from inside ‘side_effect’, or return
*note DEFAULT: 3392.:

     >>> m = MagicMock()
     >>> def side_effect(*args, **kwargs):
     ...     return m.return_value
     ...
     >>> m.side_effect = side_effect
     >>> m.return_value = 3
     >>> m()
     3
     >>> def side_effect(*args, **kwargs):
     ...     return DEFAULT
     ...
     >>> m.side_effect = side_effect
     >>> m()
     3

To remove a ‘side_effect’, and return to the default behaviour, set the
‘side_effect’ to ‘None’:

     >>> m = MagicMock(return_value=6)
     >>> def side_effect(*args, **kwargs):
     ...     return 3
     ...
     >>> m.side_effect = side_effect
     >>> m()
     3
     >>> m.side_effect = None
     >>> m()
     6

The ‘side_effect’ can also be any iterable object.  Repeated calls to
the mock will return values from the iterable (until the iterable is
exhausted and a *note StopIteration: 48e. is raised):

     >>> m = MagicMock(side_effect=[1, 2, 3])
     >>> m()
     1
     >>> m()
     2
     >>> m()
     3
     >>> m()
     Traceback (most recent call last):
       ...
     StopIteration

If any members of the iterable are exceptions they will be raised
instead of returned:

     >>> iterable = (33, ValueError, 66)
     >>> m = MagicMock(side_effect=iterable)
     >>> m()
     33
     >>> m()
     Traceback (most recent call last):
      ...
     ValueError
     >>> m()
     66


File: python.info,  Node: Deleting Attributes,  Next: Mock names and the name attribute,  Prev: Calling,  Up: Mock 类

5.26.5.4 Deleting Attributes
............................

Mock objects create attributes on demand.  This allows them to pretend
to be objects of any type.

You may want a mock object to return ‘False’ to a *note hasattr(): 450.
call, or raise an *note AttributeError: 3a3. when an attribute is
fetched.  You can do this by providing an object as a ‘spec’ for a mock,
but that isn’t always convenient.

You "block" attributes by deleting them.  Once deleted, accessing an
attribute will raise an *note AttributeError: 3a3.

     >>> mock = MagicMock()
     >>> hasattr(mock, 'm')
     True
     >>> del mock.m
     >>> hasattr(mock, 'm')
     False
     >>> del mock.f
     >>> mock.f
     Traceback (most recent call last):
         ...
     AttributeError: f


File: python.info,  Node: Mock names and the name attribute,  Next: Attaching Mocks as Attributes,  Prev: Deleting Attributes,  Up: Mock 类

5.26.5.5 Mock names and the name attribute
..........................................

Since "name" is an argument to the *note Mock: 24a. constructor, if you
want your mock object to have a "name" attribute you can’t just pass it
in at creation time.  There are two alternatives.  One option is to use
*note configure_mock(): 3394.:

     >>> mock = MagicMock()
     >>> mock.configure_mock(name='my_name')
     >>> mock.name
     'my_name'

A simpler option is to simply set the "name" attribute after mock
creation:

     >>> mock = MagicMock()
     >>> mock.name = "foo"


File: python.info,  Node: Attaching Mocks as Attributes,  Prev: Mock names and the name attribute,  Up: Mock 类

5.26.5.6 Attaching Mocks as Attributes
......................................

When you attach a mock as an attribute of another mock (or as the return
value) it becomes a "child" of that mock.  Calls to the child are
recorded in the *note method_calls: 339b. and *note mock_calls: 3398.
attributes of the parent.  This is useful for configuring child mocks
and then attaching them to the parent, or for attaching mocks to a
parent that records all calls to the children and allows you to make
assertions about the order of calls between mocks:

     >>> parent = MagicMock()
     >>> child1 = MagicMock(return_value=None)
     >>> child2 = MagicMock(return_value=None)
     >>> parent.child1 = child1
     >>> parent.child2 = child2
     >>> child1(1)
     >>> child2(2)
     >>> parent.mock_calls
     [call.child1(1), call.child2(2)]

The exception to this is if the mock has a name.  This allows you to
prevent the "parenting" if for some reason you don’t want it to happen.

     >>> mock = MagicMock()
     >>> not_a_child = MagicMock(name='not-a-child')
     >>> mock.attribute = not_a_child
     >>> mock.attribute()
     <MagicMock name='not-a-child()' id='...'>
     >>> mock.mock_calls
     []

Mocks created for you by *note patch(): 791. are automatically given
names.  To attach mocks that have names to a parent you use the *note
attach_mock(): 339a. method:

     >>> thing1 = object()
     >>> thing2 = object()
     >>> parent = MagicMock()
     >>> with patch('__main__.thing1', return_value=None) as child1:
     ...     with patch('__main__.thing2', return_value=None) as child2:
     ...         parent.attach_mock(child1, 'child1')
     ...         parent.attach_mock(child2, 'child2')
     ...         child1('one')
     ...         child2('two')
     ...
     >>> parent.mock_calls
     [call.child1('one'), call.child2('two')]


File: python.info,  Node: The patchers,  Next: MagicMock and magic method support,  Prev: Mock 类,  Up: unittest mock --- 模拟对象库

5.26.5.7 The patchers
.....................

The patch decorators are used for patching objects only within the scope
of the function they decorate.  They automatically handle the unpatching
for you, even if exceptions are raised.  All of these functions can also
be used in with statements or as class decorators.

* Menu:

* patch::
* patch.object: patch object.
* patch.dict: patch dict.
* patch.multiple: patch multiple.
* patch methods; start and stop: patch methods start and stop.
* patch builtins::
* TEST_PREFIX::
* Nesting Patch Decorators::
* Where to patch::
* Patching Descriptors and Proxy Objects::


File: python.info,  Node: patch,  Next: patch object,  Up: The patchers

5.26.5.8 patch
..............

     注解: *note patch(): 791. is straightforward to use.  The key is to
     do the patching in the right namespace.  See the section *note
     where to patch: 33b6.

 -- 函数: unittest.mock.patch (target, new=DEFAULT, spec=None,
          create=False, spec_set=None, autospec=None, new_callable=None,
          **kwargs)

     *note patch(): 791. acts as a function decorator, class decorator
     or a context manager.  Inside the body of the function or with
     statement, the `target' is patched with a `new' object.  When the
     function/with statement exits the patch is undone.

     If `new' is omitted, then the target is replaced with an *note
     AsyncMock: 249. if the patched object is an async function or a
     *note MagicMock: 78e. otherwise.  If *note patch(): 791. is used as
     a decorator and `new' is omitted, the created mock is passed in as
     an extra argument to the decorated function.  If *note patch():
     791. is used as a context manager the created mock is returned by
     the context manager.

     `target' should be a string in the form
     ‘'package.module.ClassName'’.  The `target' is imported and the
     specified object replaced with the `new' object, so the `target'
     must be importable from the environment you are calling *note
     patch(): 791. from.  The target is imported when the decorated
     function is executed, not at decoration time.

     The `spec' and `spec_set' keyword arguments are passed to the *note
     MagicMock: 78e. if patch is creating one for you.

     In addition you can pass ‘spec=True’ or ‘spec_set=True’, which
     causes patch to pass in the object being mocked as the
     spec/spec_set object.

     `new_callable' allows you to specify a different class, or callable
     object, that will be called to create the `new' object.  By default
     *note AsyncMock: 249. is used for async functions and *note
     MagicMock: 78e. for the rest.

     A more powerful form of `spec' is `autospec'.  If you set
     ‘autospec=True’ then the mock will be created with a spec from the
     object being replaced.  All attributes of the mock will also have
     the spec of the corresponding attribute of the object being
     replaced.  Methods and functions being mocked will have their
     arguments checked and will raise a *note TypeError: 193. if they
     are called with the wrong signature.  For mocks replacing a class,
     their return value (the ’instance’) will have the same spec as the
     class.  See the *note create_autospec(): f59. function and *note
     Autospeccing: 338d.

     Instead of ‘autospec=True’ you can pass ‘autospec=some_object’ to
     use an arbitrary object as the spec instead of the one being
     replaced.

     By default *note patch(): 791. will fail to replace attributes that
     don’t exist.  If you pass in ‘create=True’, and the attribute
     doesn’t exist, patch will create the attribute for you when the
     patched function is called, and delete it again after the patched
     function has exited.  This is useful for writing tests against
     attributes that your production code creates at runtime.  It is off
     by default because it can be dangerous.  With it switched on you
     can write passing tests against APIs that don’t actually exist!

          注解: 
          在 3.5 版更改: If you are patching builtins in a module then
          you don’t need to pass ‘create=True’, it will be added by
          default.

     Patch can be used as a ‘TestCase’ class decorator.  It works by
     decorating each test method in the class.  This reduces the
     boilerplate code when your test methods share a common patchings
     set.  *note patch(): 791. finds tests by looking for method names
     that start with ‘patch.TEST_PREFIX’.  By default this is ‘'test'’,
     which matches the way *note unittest: 11c. finds tests.  You can
     specify an alternative prefix by setting ‘patch.TEST_PREFIX’.

     Patch can be used as a context manager, with the with statement.
     Here the patching applies to the indented block after the with
     statement.  If you use "as" then the patched object will be bound
     to the name after the "as"; very useful if *note patch(): 791. is
     creating a mock object for you.

     *note patch(): 791. takes arbitrary keyword arguments.  These will
     be passed to the *note Mock: 24a. (or `new_callable') on
     construction.

     ‘patch.dict(...)’, ‘patch.multiple(...)’ and ‘patch.object(...)’
     are available for alternate use-cases.

*note patch(): 791. as function decorator, creating the mock for you and
passing it into the decorated function:

     >>> @patch('__main__.SomeClass')
     ... def function(normal_argument, mock_class):
     ...     print(mock_class is SomeClass)
     ...
     >>> function(None)
     True

Patching a class replaces the class with a *note MagicMock: 78e.
`instance'.  If the class is instantiated in the code under test then it
will be the *note return_value: 3393. of the mock that will be used.

If the class is instantiated multiple times you could use *note
side_effect: 3391. to return a new mock each time.  Alternatively you
can set the `return_value' to be anything you want.

To configure return values on methods of `instances' on the patched
class you must do this on the ‘return_value’.  For example:

     >>> class Class:
     ...     def method(self):
     ...         pass
     ...
     >>> with patch('__main__.Class') as MockClass:
     ...     instance = MockClass.return_value
     ...     instance.method.return_value = 'foo'
     ...     assert Class() is instance
     ...     assert Class().method() == 'foo'
     ...

If you use `spec' or `spec_set' and *note patch(): 791. is replacing a
`class', then the return value of the created mock will have the same
spec.

     >>> Original = Class
     >>> patcher = patch('__main__.Class', spec=True)
     >>> MockClass = patcher.start()
     >>> instance = MockClass()
     >>> assert isinstance(instance, Original)
     >>> patcher.stop()

The `new_callable' argument is useful where you want to use an
alternative class to the default *note MagicMock: 78e. for the created
mock.  For example, if you wanted a *note NonCallableMock: 338f. to be
used:

     >>> thing = object()
     >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
     ...     assert thing is mock_thing
     ...     thing()
     ...
     Traceback (most recent call last):
       ...
     TypeError: 'NonCallableMock' object is not callable

Another use case might be to replace an object with an *note
io.StringIO: 836. instance:

     >>> from io import StringIO
     >>> def foo():
     ...     print('Something')
     ...
     >>> @patch('sys.stdout', new_callable=StringIO)
     ... def test(mock_stdout):
     ...     foo()
     ...     assert mock_stdout.getvalue() == 'Something\n'
     ...
     >>> test()

When *note patch(): 791. is creating a mock for you, it is common that
the first thing you need to do is to configure the mock.  Some of that
configuration can be done in the call to patch.  Any arbitrary keywords
you pass into the call will be used to set attributes on the created
mock:

     >>> patcher = patch('__main__.thing', first='one', second='two')
     >>> mock_thing = patcher.start()
     >>> mock_thing.first
     'one'
     >>> mock_thing.second
     'two'

As well as attributes on the created mock attributes, like the *note
return_value: 3393. and *note side_effect: 3391, of child mocks can also
be configured.  These aren’t syntactically valid to pass in directly as
keyword arguments, but a dictionary with these as keys can still be
expanded into a *note patch(): 791. call using ‘**’:

     >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
     >>> patcher = patch('__main__.thing', **config)
     >>> mock_thing = patcher.start()
     >>> mock_thing.method()
     3
     >>> mock_thing.other()
     Traceback (most recent call last):
       ...
     KeyError

By default, attempting to patch a function in a module (or a method or
an attribute in a class) that does not exist will fail with *note
AttributeError: 3a3.:

     >>> @patch('sys.non_existing_attribute', 42)
     ... def test():
     ...     assert sys.non_existing_attribute == 42
     ...
     >>> test()
     Traceback (most recent call last):
       ...
     AttributeError: <module 'sys' (built-in)> does not have the attribute 'non_existing'

but adding ‘create=True’ in the call to *note patch(): 791. will make
the previous example work as expected:

     >>> @patch('sys.non_existing_attribute', 42, create=True)
     ... def test(mock_stdout):
     ...     assert sys.non_existing_attribute == 42
     ...
     >>> test()

在 3.8 版更改: *note patch(): 791. now returns an *note AsyncMock: 249.
if the target is an async function.


File: python.info,  Node: patch object,  Next: patch dict,  Prev: patch,  Up: The patchers

5.26.5.9 patch.object
.....................

 -- 函数: patch.object (target, attribute, new=DEFAULT, spec=None,
          create=False, spec_set=None, autospec=None, new_callable=None,
          **kwargs)

     patch the named member (`attribute') on an object (`target') with a
     mock object.

     *note patch.object(): f6f. can be used as a decorator, class
     decorator or a context manager.  Arguments `new', `spec', `create',
     `spec_set', `autospec' and `new_callable' have the same meaning as
     for *note patch(): 791.  Like *note patch(): 791, *note
     patch.object(): f6f. takes arbitrary keyword arguments for
     configuring the mock object it creates.

     When used as a class decorator *note patch.object(): f6f. honours
     ‘patch.TEST_PREFIX’ for choosing which methods to wrap.

You can either call *note patch.object(): f6f. with three arguments or
two arguments.  The three argument form takes the object to be patched,
the attribute name and the object to replace the attribute with.

When calling with the two argument form you omit the replacement object,
and a mock is created for you and passed in as an extra argument to the
decorated function:

     >>> @patch.object(SomeClass, 'class_method')
     ... def test(mock_method):
     ...     SomeClass.class_method(3)
     ...     mock_method.assert_called_with(3)
     ...
     >>> test()

`spec', `create' and the other arguments to *note patch.object(): f6f.
have the same meaning as they do for *note patch(): 791.


File: python.info,  Node: patch dict,  Next: patch multiple,  Prev: patch object,  Up: The patchers

5.26.5.10 patch.dict
....................

 -- 函数: patch.dict (in_dict, values=(), clear=False, **kwargs)

     Patch a dictionary, or dictionary like object, and restore the
     dictionary to its original state after the test.

     `in_dict' can be a dictionary or a mapping like container.  If it
     is a mapping then it must at least support getting, setting and
     deleting items plus iterating over keys.

     `in_dict' can also be a string specifying the name of the
     dictionary, which will then be fetched by importing it.

     `values' can be a dictionary of values to set in the dictionary.
     `values' can also be an iterable of ‘(key, value)’ pairs.

     If `clear' is true then the dictionary will be cleared before the
     new values are set.

     *note patch.dict(): fdf. can also be called with arbitrary keyword
     arguments to set values in the dictionary.

     在 3.8 版更改: *note patch.dict(): fdf. now returns the patched
     dictionary when used as a context manager.

*note patch.dict(): fdf. can be used as a context manager, decorator or
class decorator:

     >>> foo = {}
     >>> @patch.dict(foo, {'newkey': 'newvalue'})
     ... def test():
     ...     assert foo == {'newkey': 'newvalue'}
     >>> test()
     >>> assert foo == {}

When used as a class decorator *note patch.dict(): fdf. honours
‘patch.TEST_PREFIX’ (default to ‘'test'’) for choosing which methods to
wrap:

     >>> import os
     >>> import unittest
     >>> from unittest.mock import patch
     >>> @patch.dict('os.environ', {'newkey': 'newvalue'})
     ... class TestSample(unittest.TestCase):
     ...     def test_sample(self):
     ...         self.assertEqual(os.environ['newkey'], 'newvalue')

If you want to use a different prefix for your test, you can inform the
patchers of the different prefix by setting ‘patch.TEST_PREFIX’.  For
more details about how to change the value of see *note TEST_PREFIX:
33b9.

*note patch.dict(): fdf. can be used to add members to a dictionary, or
simply let a test change a dictionary, and ensure the dictionary is
restored when the test ends.

     >>> foo = {}
     >>> with patch.dict(foo, {'newkey': 'newvalue'}) as patched_foo:
     ...     assert foo == {'newkey': 'newvalue'}
     ...     assert patched_foo == {'newkey': 'newvalue'}
     ...     # You can add, update or delete keys of foo (or patched_foo, it's the same dict)
     ...     patched_foo['spam'] = 'eggs'
     ...
     >>> assert foo == {}
     >>> assert patched_foo == {}

     >>> import os
     >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
     ...     print(os.environ['newkey'])
     ...
     newvalue
     >>> assert 'newkey' not in os.environ

Keywords can be used in the *note patch.dict(): fdf. call to set values
in the dictionary:

     >>> mymodule = MagicMock()
     >>> mymodule.function.return_value = 'fish'
     >>> with patch.dict('sys.modules', mymodule=mymodule):
     ...     import mymodule
     ...     mymodule.function('some', 'args')
     ...
     'fish'

*note patch.dict(): fdf. can be used with dictionary like objects that
aren’t actually dictionaries.  At the very minimum they must support
item getting, setting, deleting and either iteration or membership test.
This corresponds to the magic methods *note __getitem__(): 280, *note
__setitem__(): c6a, *note __delitem__(): c6b. and either *note
__iter__(): 517. or *note __contains__(): d30.

     >>> class Container:
     ...     def __init__(self):
     ...         self.values = {}
     ...     def __getitem__(self, name):
     ...         return self.values[name]
     ...     def __setitem__(self, name, value):
     ...         self.values[name] = value
     ...     def __delitem__(self, name):
     ...         del self.values[name]
     ...     def __iter__(self):
     ...         return iter(self.values)
     ...
     >>> thing = Container()
     >>> thing['one'] = 1
     >>> with patch.dict(thing, one=2, two=3):
     ...     assert thing['one'] == 2
     ...     assert thing['two'] == 3
     ...
     >>> assert thing['one'] == 1
     >>> assert list(thing) == ['one']


File: python.info,  Node: patch multiple,  Next: patch methods start and stop,  Prev: patch dict,  Up: The patchers

5.26.5.11 patch.multiple
........................

 -- 函数: patch.multiple (target, spec=None, create=False,
          spec_set=None, autospec=None, new_callable=None, **kwargs)

     Perform multiple patches in a single call.  It takes the object to
     be patched (either as an object or a string to fetch the object by
     importing) and keyword arguments for the patches:

          with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
              ...

     Use *note DEFAULT: 3392. as the value if you want *note
     patch.multiple(): 33bb. to create mocks for you.  In this case the
     created mocks are passed into a decorated function by keyword, and
     a dictionary is returned when *note patch.multiple(): 33bb. is used
     as a context manager.

     *note patch.multiple(): 33bb. can be used as a decorator, class
     decorator or a context manager.  The arguments `spec', `spec_set',
     `create', `autospec' and `new_callable' have the same meaning as
     for *note patch(): 791.  These arguments will be applied to `all'
     patches done by *note patch.multiple(): 33bb.

     When used as a class decorator *note patch.multiple(): 33bb.
     honours ‘patch.TEST_PREFIX’ for choosing which methods to wrap.

If you want *note patch.multiple(): 33bb. to create mocks for you, then
you can use *note DEFAULT: 3392. as the value.  If you use *note
patch.multiple(): 33bb. as a decorator then the created mocks are passed
into the decorated function by keyword.

     >>> thing = object()
     >>> other = object()

     >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
     ... def test_function(thing, other):
     ...     assert isinstance(thing, MagicMock)
     ...     assert isinstance(other, MagicMock)
     ...
     >>> test_function()

*note patch.multiple(): 33bb. can be nested with other ‘patch’
decorators, but put arguments passed by keyword `after' any of the
standard arguments created by *note patch(): 791.:

     >>> @patch('sys.exit')
     ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
     ... def test_function(mock_exit, other, thing):
     ...     assert 'other' in repr(other)
     ...     assert 'thing' in repr(thing)
     ...     assert 'exit' in repr(mock_exit)
     ...
     >>> test_function()

If *note patch.multiple(): 33bb. is used as a context manager, the value
returned by the context manager is a dictionary where created mocks are
keyed by name:

     >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
     ...     assert 'other' in repr(values['other'])
     ...     assert 'thing' in repr(values['thing'])
     ...     assert values['thing'] is thing
     ...     assert values['other'] is other
     ...


File: python.info,  Node: patch methods start and stop,  Next: patch builtins,  Prev: patch multiple,  Up: The patchers

5.26.5.12 patch methods: start and stop
.......................................

All the patchers have ‘start()’ and ‘stop()’ methods.  These make it
simpler to do patching in ‘setUp’ methods or where you want to do
multiple patches without nesting decorators or with statements.

To use them call *note patch(): 791, *note patch.object(): f6f. or *note
patch.dict(): fdf. as normal and keep a reference to the returned
‘patcher’ object.  You can then call ‘start()’ to put the patch in place
and ‘stop()’ to undo it.

If you are using *note patch(): 791. to create a mock for you then it
will be returned by the call to ‘patcher.start’.

     >>> patcher = patch('package.module.ClassName')
     >>> from package import module
     >>> original = module.ClassName
     >>> new_mock = patcher.start()
     >>> assert module.ClassName is not original
     >>> assert module.ClassName is new_mock
     >>> patcher.stop()
     >>> assert module.ClassName is original
     >>> assert module.ClassName is not new_mock

A typical use case for this might be for doing multiple patches in the
‘setUp’ method of a ‘TestCase’:

     >>> class MyTest(unittest.TestCase):
     ...     def setUp(self):
     ...         self.patcher1 = patch('package.module.Class1')
     ...         self.patcher2 = patch('package.module.Class2')
     ...         self.MockClass1 = self.patcher1.start()
     ...         self.MockClass2 = self.patcher2.start()
     ...
     ...     def tearDown(self):
     ...         self.patcher1.stop()
     ...         self.patcher2.stop()
     ...
     ...     def test_something(self):
     ...         assert package.module.Class1 is self.MockClass1
     ...         assert package.module.Class2 is self.MockClass2
     ...
     >>> MyTest('test_something').run()

     警告: If you use this technique you must ensure that the patching
     is "undone" by calling ‘stop’.  This can be fiddlier than you might
     think, because if an exception is raised in the ‘setUp’ then
     ‘tearDown’ is not called.  *note unittest.TestCase.addCleanup():
     2a3. makes this easier:

          >>> class MyTest(unittest.TestCase):
          ...     def setUp(self):
          ...         patcher = patch('package.module.Class')
          ...         self.MockClass = patcher.start()
          ...         self.addCleanup(patcher.stop)
          ...
          ...     def test_something(self):
          ...         assert package.module.Class is self.MockClass
          ...

     As an added bonus you no longer need to keep a reference to the
     ‘patcher’ object.

It is also possible to stop all patches which have been started by using
*note patch.stopall(): 33be.

 -- 函数: patch.stopall ()

     Stop all active patches.  Only stops patches started with ‘start’.


File: python.info,  Node: patch builtins,  Next: TEST_PREFIX,  Prev: patch methods start and stop,  Up: The patchers

5.26.5.13 patch builtins
........................

You can patch any builtins within a module.  The following example
patches builtin *note ord(): 1437.:

     >>> @patch('__main__.ord')
     ... def test(mock_ord):
     ...     mock_ord.return_value = 101
     ...     print(ord('c'))
     ...
     >>> test()
     101


File: python.info,  Node: TEST_PREFIX,  Next: Nesting Patch Decorators,  Prev: patch builtins,  Up: The patchers

5.26.5.14 TEST_PREFIX
.....................

All of the patchers can be used as class decorators.  When used in this
way they wrap every test method on the class.  The patchers recognise
methods that start with ‘'test'’ as being test methods.  This is the
same way that the *note unittest.TestLoader: 78b. finds test methods by
default.

It is possible that you want to use a different prefix for your tests.
You can inform the patchers of the different prefix by setting
‘patch.TEST_PREFIX’:

     >>> patch.TEST_PREFIX = 'foo'
     >>> value = 3
     >>>
     >>> @patch('__main__.value', 'not three')
     ... class Thing:
     ...     def foo_one(self):
     ...         print(value)
     ...     def foo_two(self):
     ...         print(value)
     ...
     >>>
     >>> Thing().foo_one()
     not three
     >>> Thing().foo_two()
     not three
     >>> value
     3


File: python.info,  Node: Nesting Patch Decorators,  Next: Where to patch,  Prev: TEST_PREFIX,  Up: The patchers

5.26.5.15 Nesting Patch Decorators
..................................

If you want to perform multiple patches then you can simply stack up the
decorators.

You can stack up multiple patch decorators using this pattern:

     >>> @patch.object(SomeClass, 'class_method')
     ... @patch.object(SomeClass, 'static_method')
     ... def test(mock1, mock2):
     ...     assert SomeClass.static_method is mock1
     ...     assert SomeClass.class_method is mock2
     ...     SomeClass.static_method('foo')
     ...     SomeClass.class_method('bar')
     ...     return mock1, mock2
     ...
     >>> mock1, mock2 = test()
     >>> mock1.assert_called_once_with('foo')
     >>> mock2.assert_called_once_with('bar')

Note that the decorators are applied from the bottom upwards.  This is
the standard way that Python applies decorators.  The order of the
created mocks passed into your test function matches this order.


File: python.info,  Node: Where to patch,  Next: Patching Descriptors and Proxy Objects,  Prev: Nesting Patch Decorators,  Up: The patchers

5.26.5.16 Where to patch
........................

*note patch(): 791. works by (temporarily) changing the object that a
`name' points to with another one.  There can be many names pointing to
any individual object, so for patching to work you must ensure that you
patch the name used by the system under test.

The basic principle is that you patch where an object is `looked up',
which is not necessarily the same place as where it is defined.  A
couple of examples will help to clarify this.

Imagine we have a project that we want to test with the following
structure:

     a.py
         -> Defines SomeClass

     b.py
         -> from a import SomeClass
         -> some_function instantiates SomeClass

Now we want to test ‘some_function’ but we want to mock out ‘SomeClass’
using *note patch(): 791.  The problem is that when we import module b,
which we will have to do then it imports ‘SomeClass’ from module a.  If
we use *note patch(): 791. to mock out ‘a.SomeClass’ then it will have
no effect on our test; module b already has a reference to the `real'
‘SomeClass’ and it looks like our patching had no effect.

The key is to patch out ‘SomeClass’ where it is used (or where it is
looked up).  In this case ‘some_function’ will actually look up
‘SomeClass’ in module b, where we have imported it.  The patching should
look like:

     @patch('b.SomeClass')

However, consider the alternative scenario where instead of ‘from a
import SomeClass’ module b does ‘import a’ and ‘some_function’ uses
‘a.SomeClass’.  Both of these import forms are common.  In this case the
class we want to patch is being looked up in the module and so we have
to patch ‘a.SomeClass’ instead:

     @patch('a.SomeClass')


File: python.info,  Node: Patching Descriptors and Proxy Objects,  Prev: Where to patch,  Up: The patchers

5.26.5.17 Patching Descriptors and Proxy Objects
................................................

Both *note patch: 33b5. and *note patch.object: 33b7. correctly patch
and restore descriptors: class methods, static methods and properties.
You should patch these on the `class' rather than an instance.  They
also work with `some' objects that proxy attribute access, like the
django settings object(1).

   ---------- Footnotes ----------

   (1) 
http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198


File: python.info,  Node: MagicMock and magic method support,  Next: Helpers,  Prev: The patchers,  Up: unittest mock --- 模拟对象库

5.26.5.18 MagicMock and magic method support
............................................

* Menu:

* Mocking Magic Methods::
* Magic Mock::


File: python.info,  Node: Mocking Magic Methods,  Next: Magic Mock,  Up: MagicMock and magic method support

5.26.5.19 Mocking Magic Methods
...............................

*note Mock: 24a. supports mocking the Python protocol methods, also
known as "magic methods".  This allows mock objects to replace
containers or other objects that implement Python protocols.

Because magic methods are looked up differently from normal methods (1),
this support has been specially implemented.  This means that only
specific magic methods are supported.  The supported list includes
`almost' all of them.  If there are any missing that you need please let
us know.

You mock magic methods by setting the method you are interested in to a
function or a mock instance.  If you are using a function then it `must'
take ‘self’ as the first argument (2).

     >>> def __str__(self):
     ...     return 'fooble'
     ...
     >>> mock = Mock()
     >>> mock.__str__ = __str__
     >>> str(mock)
     'fooble'

     >>> mock = Mock()
     >>> mock.__str__ = Mock()
     >>> mock.__str__.return_value = 'fooble'
     >>> str(mock)
     'fooble'

     >>> mock = Mock()
     >>> mock.__iter__ = Mock(return_value=iter([]))
     >>> list(mock)
     []

One use case for this is for mocking objects used as context managers in
a *note with: 6f2. statement:

     >>> mock = Mock()
     >>> mock.__enter__ = Mock(return_value='foo')
     >>> mock.__exit__ = Mock(return_value=False)
     >>> with mock as m:
     ...     assert m == 'foo'
     ...
     >>> mock.__enter__.assert_called_with()
     >>> mock.__exit__.assert_called_with(None, None, None)

Calls to magic methods do not appear in *note method_calls: 339b, but
they are recorded in *note mock_calls: 3398.

     注解: If you use the `spec' keyword argument to create a mock then
     attempting to set a magic method that isn’t in the spec will raise
     an *note AttributeError: 3a3.

The full list of supported magic methods is:

   * ‘__hash__’, ‘__sizeof__’, ‘__repr__’ and ‘__str__’

   * ‘__dir__’, ‘__format__’ and ‘__subclasses__’

   * ‘__round__’, ‘__floor__’, ‘__trunc__’ and ‘__ceil__’

   * Comparisons: ‘__lt__’, ‘__gt__’, ‘__le__’, ‘__ge__’, ‘__eq__’ and
     ‘__ne__’

   * Container methods: ‘__getitem__’, ‘__setitem__’, ‘__delitem__’,
     ‘__contains__’, ‘__len__’, ‘__iter__’, ‘__reversed__’ and
     ‘__missing__’

   * Context manager: ‘__enter__’, ‘__exit__’, ‘__aenter__’ and
     ‘__aexit__’

   * Unary numeric methods: ‘__neg__’, ‘__pos__’ and ‘__invert__’

   * The numeric methods (including right hand and in-place variants):
     ‘__add__’, ‘__sub__’, ‘__mul__’, ‘__matmul__’, ‘__div__’,
     ‘__truediv__’, ‘__floordiv__’, ‘__mod__’, ‘__divmod__’,
     ‘__lshift__’, ‘__rshift__’, ‘__and__’, ‘__xor__’, ‘__or__’, and
     ‘__pow__’

   * Numeric conversion methods: ‘__complex__’, ‘__int__’, ‘__float__’
     and ‘__index__’

   * Descriptor methods: ‘__get__’, ‘__set__’ and ‘__delete__’

   * Pickling: ‘__reduce__’, ‘__reduce_ex__’, ‘__getinitargs__’,
     ‘__getnewargs__’, ‘__getstate__’ and ‘__setstate__’

   * File system path representation: ‘__fspath__’

   * Asynchronous iteration methods: ‘__aiter__’ and ‘__anext__’

在 3.8 版更改: Added support for *note os.PathLike.__fspath__(): 4f4.

在 3.8 版更改: Added support for ‘__aenter__’, ‘__aexit__’, ‘__aiter__’
and ‘__anext__’.

The following methods exist but are `not' supported as they are either
in use by mock, can’t be set dynamically, or can cause problems:

   * ‘__getattr__’, ‘__setattr__’, ‘__init__’ and ‘__new__’

   * ‘__prepare__’, ‘__instancecheck__’, ‘__subclasscheck__’, ‘__del__’

   ---------- Footnotes ----------

   (1) (2) Magic methods `should' be looked up on the class rather than
the instance.  Different versions of Python are inconsistent about
applying this rule.  The supported protocol methods should work with all
supported versions of Python.

   (2) (3) The function is basically hooked up to the class, but each
‘Mock’ instance is kept isolated from the others.


File: python.info,  Node: Magic Mock,  Prev: Mocking Magic Methods,  Up: MagicMock and magic method support

5.26.5.20 Magic Mock
....................

There are two ‘MagicMock’ variants: *note MagicMock: 78e. and *note
NonCallableMagicMock: 3390.

 -- 类: unittest.mock.MagicMock (*args, **kw)

     ‘MagicMock’ is a subclass of *note Mock: 24a. with default
     implementations of most of the magic methods.  You can use
     ‘MagicMock’ without having to configure the magic methods yourself.

     The constructor parameters have the same meaning as for *note Mock:
     24a.

     If you use the `spec' or `spec_set' arguments then `only' magic
     methods that exist in the spec will be created.

 -- 类: unittest.mock.NonCallableMagicMock (*args, **kw)

     A non-callable version of *note MagicMock: 78e.

     The constructor parameters have the same meaning as for *note
     MagicMock: 78e, with the exception of `return_value' and
     `side_effect' which have no meaning on a non-callable mock.

The magic methods are setup with *note MagicMock: 78e. objects, so you
can configure them and use them in the usual way:

     >>> mock = MagicMock()
     >>> mock[3] = 'fish'
     >>> mock.__setitem__.assert_called_with(3, 'fish')
     >>> mock.__getitem__.return_value = 'result'
     >>> mock[2]
     'result'

By default many of the protocol methods are required to return objects
of a specific type.  These methods are preconfigured with a default
return value, so that they can be used without you having to do anything
if you aren’t interested in the return value.  You can still `set' the
return value manually if you want to change the default.

Methods and their defaults:

   * ‘__lt__’: ‘NotImplemented’

   * ‘__gt__’: ‘NotImplemented’

   * ‘__le__’: ‘NotImplemented’

   * ‘__ge__’: ‘NotImplemented’

   * ‘__int__’: ‘1’

   * ‘__contains__’: ‘False’

   * ‘__len__’: ‘0’

   * ‘__iter__’: ‘iter([])’

   * ‘__exit__’: ‘False’

   * ‘__aexit__’: ‘False’

   * ‘__complex__’: ‘1j’

   * ‘__float__’: ‘1.0’

   * ‘__bool__’: ‘True’

   * ‘__index__’: ‘1’

   * ‘__hash__’: default hash for the mock

   * ‘__str__’: default str for the mock

   * ‘__sizeof__’: default sizeof for the mock

例如:

     >>> mock = MagicMock()
     >>> int(mock)
     1
     >>> len(mock)
     0
     >>> list(mock)
     []
     >>> object() in mock
     False

The two equality methods, *note __eq__(): 348. and *note __ne__(): e5e,
are special.  They do the default equality comparison on identity, using
the *note side_effect: 3391. attribute, unless you change their return
value to return something else:

     >>> MagicMock() == 3
     False
     >>> MagicMock() != 3
     True
     >>> mock = MagicMock()
     >>> mock.__eq__.return_value = True
     >>> mock == 3
     True

The return value of ‘MagicMock.__iter__()’ can be any iterable object
and isn’t required to be an iterator:

     >>> mock = MagicMock()
     >>> mock.__iter__.return_value = ['a', 'b', 'c']
     >>> list(mock)
     ['a', 'b', 'c']
     >>> list(mock)
     ['a', 'b', 'c']

If the return value `is' an iterator, then iterating over it once will
consume it and subsequent iterations will result in an empty list:

     >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
     >>> list(mock)
     ['a', 'b', 'c']
     >>> list(mock)
     []

‘MagicMock’ has all of the supported magic methods configured except for
some of the obscure and obsolete ones.  You can still set these up if
you want.

Magic methods that are supported but not setup by default in ‘MagicMock’
are:

   * ‘__subclasses__’

   * ‘__dir__’

   * ‘__format__’

   * ‘__get__’, ‘__set__’ and ‘__delete__’

   * ‘__reversed__’ and ‘__missing__’

   * ‘__reduce__’, ‘__reduce_ex__’, ‘__getinitargs__’, ‘__getnewargs__’,
     ‘__getstate__’ and ‘__setstate__’

   * ‘__getformat__’ and ‘__setformat__’


File: python.info,  Node: Helpers,  Prev: MagicMock and magic method support,  Up: unittest mock --- 模拟对象库

5.26.5.21 Helpers
.................

* Menu:

* sentinel::
* DEFAULT::
* call::
* create_autospec::
* ANY::
* FILTER_DIR::
* mock_open::
* Autospeccing::
* Sealing mocks::


File: python.info,  Node: sentinel,  Next: DEFAULT,  Up: Helpers

5.26.5.22 sentinel
..................

 -- 数据: unittest.mock.sentinel

     The ‘sentinel’ object provides a convenient way of providing unique
     objects for your tests.

     Attributes are created on demand when you access them by name.
     Accessing the same attribute will always return the same object.
     The objects returned have a sensible repr so that test failure
     messages are readable.

     在 3.7 版更改: The ‘sentinel’ attributes now preserve their
     identity when they are *note copied: 26. or *note pickled: cb.

Sometimes when testing you need to test that a specific object is passed
as an argument to another method, or returned.  It can be common to
create named sentinel objects to test this.  *note sentinel: 412.
provides a convenient way of creating and testing the identity of
objects like this.

In this example we monkey patch ‘method’ to return
‘sentinel.some_object’:

     >>> real = ProductionClass()
     >>> real.method = Mock(name="method")
     >>> real.method.return_value = sentinel.some_object
     >>> result = real.method()
     >>> assert result is sentinel.some_object
     >>> sentinel.some_object
     sentinel.some_object


File: python.info,  Node: DEFAULT,  Next: call,  Prev: sentinel,  Up: Helpers

5.26.5.23 DEFAULT
.................

 -- 数据: unittest.mock.DEFAULT

     The *note DEFAULT: 3392. object is a pre-created sentinel (actually
     ‘sentinel.DEFAULT’).  It can be used by *note side_effect: 3391.
     functions to indicate that the normal return value should be used.


File: python.info,  Node: call,  Next: create_autospec,  Prev: DEFAULT,  Up: Helpers

5.26.5.24 call
..............

 -- 函数: unittest.mock.call (*args, **kwargs)

     *note call(): f8a. is a helper object for making simpler
     assertions, for comparing with *note call_args: f34, *note
     call_args_list: 33a1, *note mock_calls: 3398. and *note
     method_calls: 339b.  *note call(): f8a. can also be used with *note
     assert_has_calls(): 3397.

          >>> m = MagicMock(return_value=None)
          >>> m(1, 2, a='foo', b='bar')
          >>> m()
          >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
          True

 -- 方法: call.call_list ()

     For a call object that represents multiple calls, *note
     call_list(): 33cb. returns a list of all the intermediate calls as
     well as the final call.

‘call_list’ is particularly useful for making assertions on "chained
calls".  A chained call is multiple calls on a single line of code.
This results in multiple entries in *note mock_calls: 3398. on a mock.
Manually constructing the sequence of calls can be tedious.

*note call_list(): 33cb. can construct the sequence of calls from the
same chained call:

     >>> m = MagicMock()
     >>> m(1).method(arg='foo').other('bar')(2.0)
     <MagicMock name='mock().method().other()()' id='...'>
     >>> kall = call(1).method(arg='foo').other('bar')(2.0)
     >>> kall.call_list()
     [call(1),
      call().method(arg='foo'),
      call().method().other('bar'),
      call().method().other()(2.0)]
     >>> m.mock_calls == kall.call_list()
     True
A ‘call’ object is either a tuple of (positional args, keyword args) or
(name, positional args, keyword args) depending on how it was
constructed.  When you construct them yourself this isn’t particularly
interesting, but the ‘call’ objects that are in the *note
Mock.call_args: f34, *note Mock.call_args_list: 33a1. and *note
Mock.mock_calls: 3398. attributes can be introspected to get at the
individual arguments they contain.

The ‘call’ objects in *note Mock.call_args: f34. and *note
Mock.call_args_list: 33a1. are two-tuples of (positional args, keyword
args) whereas the ‘call’ objects in *note Mock.mock_calls: 3398, along
with ones you construct yourself, are three-tuples of (name, positional
args, keyword args).

You can use their "tupleness" to pull out the individual arguments for
more complex introspection and assertions.  The positional arguments are
a tuple (an empty tuple if there are no positional arguments) and the
keyword arguments are a dictionary:

     >>> m = MagicMock(return_value=None)
     >>> m(1, 2, 3, arg='one', arg2='two')
     >>> kall = m.call_args
     >>> kall.args
     (1, 2, 3)
     >>> kall.kwargs
     {'arg': 'one', 'arg2': 'two'}
     >>> kall.args is kall[0]
     True
     >>> kall.kwargs is kall[1]
     True

     >>> m = MagicMock()
     >>> m.foo(4, 5, 6, arg='two', arg2='three')
     <MagicMock name='mock.foo()' id='...'>
     >>> kall = m.mock_calls[0]
     >>> name, args, kwargs = kall
     >>> name
     'foo'
     >>> args
     (4, 5, 6)
     >>> kwargs
     {'arg': 'two', 'arg2': 'three'}
     >>> name is m.mock_calls[0][0]
     True


File: python.info,  Node: create_autospec,  Next: ANY,  Prev: call,  Up: Helpers

5.26.5.25 create_autospec
.........................

 -- 函数: unittest.mock.create_autospec (spec, spec_set=False,
          instance=False, **kwargs)

     Create a mock object using another object as a spec.  Attributes on
     the mock will use the corresponding attribute on the `spec' object
     as their spec.

     Functions or methods being mocked will have their arguments checked
     to ensure that they are called with the correct signature.

     If `spec_set' is ‘True’ then attempting to set attributes that
     don’t exist on the spec object will raise an *note AttributeError:
     3a3.

     If a class is used as a spec then the return value of the mock (the
     instance of the class) will have the same spec.  You can use a
     class as the spec for an instance object by passing
     ‘instance=True’.  The returned mock will only be callable if
     instances of the mock are callable.

     *note create_autospec(): f59. also takes arbitrary keyword
     arguments that are passed to the constructor of the created mock.

See *note Autospeccing: 338d. for examples of how to use auto-speccing
with *note create_autospec(): f59. and the `autospec' argument to *note
patch(): 791.

在 3.8 版更改: *note create_autospec(): f59. now returns an *note
AsyncMock: 249. if the target is an async function.


File: python.info,  Node: ANY,  Next: FILTER_DIR,  Prev: create_autospec,  Up: Helpers

5.26.5.26 ANY
.............

 -- 数据: unittest.mock.ANY

Sometimes you may need to make assertions about `some' of the arguments
in a call to mock, but either not care about some of the arguments or
want to pull them individually out of *note call_args: f34. and make
more complex assertions on them.

To ignore certain arguments you can pass in objects that compare equal
to `everything'.  Calls to *note assert_called_with(): 100f. and *note
assert_called_once_with(): 3395. will then succeed no matter what was
passed in.

     >>> mock = Mock(return_value=None)
     >>> mock('foo', bar=object())
     >>> mock.assert_called_once_with('foo', bar=ANY)

*note ANY: 33ce. can also be used in comparisons with call lists like
*note mock_calls: 3398.:

     >>> m = MagicMock(return_value=None)
     >>> m(1)
     >>> m(1, 2)
     >>> m(object())
     >>> m.mock_calls == [call(1), call(1, 2), ANY]
     True


File: python.info,  Node: FILTER_DIR,  Next: mock_open,  Prev: ANY,  Up: Helpers

5.26.5.27 FILTER_DIR
....................

 -- 数据: unittest.mock.FILTER_DIR

*note FILTER_DIR: 339d. is a module level variable that controls the way
mock objects respond to *note dir(): d3b. (only for Python 2.6 or more
recent).  The default is ‘True’, which uses the filtering described
below, to only show useful members.  If you dislike this filtering, or
need to switch it off for diagnostic purposes, then set ‘mock.FILTER_DIR
= False’.

With filtering on, ‘dir(some_mock)’ shows only useful attributes and
will include any dynamically created attributes that wouldn’t normally
be shown.  If the mock was created with a `spec' (or `autospec' of
course) then all the attributes from the original are shown, even if
they haven’t been accessed yet:

     >>> dir(Mock())
     ['assert_any_call',
      'assert_called',
      'assert_called_once',
      'assert_called_once_with',
      'assert_called_with',
      'assert_has_calls',
      'assert_not_called',
      'attach_mock',
      ...
     >>> from urllib import request
     >>> dir(Mock(spec=request))
     ['AbstractBasicAuthHandler',
      'AbstractDigestAuthHandler',
      'AbstractHTTPHandler',
      'BaseHandler',
      ...

Many of the not-very-useful (private to *note Mock: 24a. rather than the
thing being mocked) underscore and double underscore prefixed attributes
have been filtered from the result of calling *note dir(): d3b. on a
*note Mock: 24a.  If you dislike this behaviour you can switch it off by
setting the module level switch *note FILTER_DIR: 339d.:

     >>> from unittest import mock
     >>> mock.FILTER_DIR = False
     >>> dir(mock.Mock())
     ['_NonCallableMock__get_return_value',
      '_NonCallableMock__get_side_effect',
      '_NonCallableMock__return_value_doc',
      '_NonCallableMock__set_return_value',
      '_NonCallableMock__set_side_effect',
      '__call__',
      '__class__',
      ...

Alternatively you can just use ‘vars(my_mock)’ (instance members) and
‘dir(type(my_mock))’ (type members) to bypass the filtering irrespective
of ‘mock.FILTER_DIR’.


File: python.info,  Node: mock_open,  Next: Autospeccing,  Prev: FILTER_DIR,  Up: Helpers

5.26.5.28 mock_open
...................

 -- 函数: unittest.mock.mock_open (mock=None, read_data=None)

     A helper function to create a mock to replace the use of *note
     open(): 4f8.  It works for *note open(): 4f8. called directly or
     used as a context manager.

     The `mock' argument is the mock object to configure.  If ‘None’
     (the default) then a *note MagicMock: 78e. will be created for you,
     with the API limited to methods or attributes available on standard
     file handles.

     `read_data' is a string for the ‘read()’, *note readline(): 1713,
     and *note readlines(): 17a0. methods of the file handle to return.
     Calls to those methods will take data from `read_data' until it is
     depleted.  The mock of these methods is pretty simplistic: every
     time the `mock' is called, the `read_data' is rewound to the start.
     If you need more control over the data that you are feeding to the
     tested code you will need to customize this mock for yourself.
     When that is insufficient, one of the in-memory filesystem packages
     on PyPI(1) can offer a realistic filesystem for testing.

     在 3.4 版更改: Added *note readline(): 1713. and *note readlines():
     17a0. support.  The mock of ‘read()’ changed to consume `read_data'
     rather than returning it on each call.

     在 3.5 版更改: `read_data' is now reset on each call to the `mock'.

     在 3.8 版更改: Added *note __iter__(): 517. to implementation so
     that iteration (such as in for loops) correctly consumes
     `read_data'.

Using *note open(): 4f8. as a context manager is a great way to ensure
your file handles are closed properly and is becoming common:

     with open('/some/path', 'w') as f:
         f.write('something')

The issue is that even if you mock out the call to *note open(): 4f8. it
is the `returned object' that is used as a context manager (and has
*note __enter__(): c9d. and *note __exit__(): c9e. called).

Mocking context managers with a *note MagicMock: 78e. is common enough
and fiddly enough that a helper function is useful.

     >>> m = mock_open()
     >>> with patch('__main__.open', m):
     ...     with open('foo', 'w') as h:
     ...         h.write('some stuff')
     ...
     >>> m.mock_calls
     [call('foo', 'w'),
      call().__enter__(),
      call().write('some stuff'),
      call().__exit__(None, None, None)]
     >>> m.assert_called_once_with('foo', 'w')
     >>> handle = m()
     >>> handle.write.assert_called_once_with('some stuff')

And for reading files:

     >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
     ...     with open('foo') as h:
     ...         result = h.read()
     ...
     >>> m.assert_called_once_with('foo')
     >>> assert result == 'bibble'

   ---------- Footnotes ----------

   (1) https://pypi.org


File: python.info,  Node: Autospeccing,  Next: Sealing mocks,  Prev: mock_open,  Up: Helpers

5.26.5.29 Autospeccing
......................

Autospeccing is based on the existing ‘spec’ feature of mock.  It limits
the api of mocks to the api of an original object (the spec), but it is
recursive (implemented lazily) so that attributes of mocks only have the
same api as the attributes of the spec.  In addition mocked functions /
methods have the same call signature as the original so they raise a
*note TypeError: 193. if they are called incorrectly.

Before I explain how auto-speccing works, here’s why it is needed.

*note Mock: 24a. is a very powerful and flexible object, but it suffers
from two flaws when used to mock out objects from a system under test.
One of these flaws is specific to the *note Mock: 24a. api and the other
is a more general problem with using mock objects.

First the problem specific to *note Mock: 24a.  *note Mock: 24a. has two
assert methods that are extremely handy: *note assert_called_with():
100f. and *note assert_called_once_with(): 3395.

     >>> mock = Mock(name='Thing', return_value=None)
     >>> mock(1, 2, 3)
     >>> mock.assert_called_once_with(1, 2, 3)
     >>> mock(1, 2, 3)
     >>> mock.assert_called_once_with(1, 2, 3)
     Traceback (most recent call last):
      ...
     AssertionError: Expected 'mock' to be called once. Called 2 times.

Because mocks auto-create attributes on demand, and allow you to call
them with arbitrary arguments, if you misspell one of these assert
methods then your assertion is gone:

     >>> mock = Mock(name='Thing', return_value=None)
     >>> mock(1, 2, 3)
     >>> mock.assret_called_once_with(4, 5, 6)

Your tests can pass silently and incorrectly because of the typo.

The second issue is more general to mocking.  If you refactor some of
your code, rename members and so on, any tests for code that is still
using the `old api' but uses mocks instead of the real objects will
still pass.  This means your tests can all pass even though your code is
broken.

Note that this is another reason why you need integration tests as well
as unit tests.  Testing everything in isolation is all fine and dandy,
but if you don’t test how your units are "wired together" there is still
lots of room for bugs that tests might have caught.

‘mock’ already provides a feature to help with this, called speccing.
If you use a class or instance as the ‘spec’ for a mock then you can
only access attributes on the mock that exist on the real class:

     >>> from urllib import request
     >>> mock = Mock(spec=request.Request)
     >>> mock.assret_called_with
     Traceback (most recent call last):
      ...
     AttributeError: Mock object has no attribute 'assret_called_with'

The spec only applies to the mock itself, so we still have the same
issue with any methods on the mock:

     >>> mock.has_data()
     <mock.Mock object at 0x...>
     >>> mock.has_data.assret_called_with()

Auto-speccing solves this problem.  You can either pass ‘autospec=True’
to *note patch(): 791. / *note patch.object(): f6f. or use the *note
create_autospec(): f59. function to create a mock with a spec.  If you
use the ‘autospec=True’ argument to *note patch(): 791. then the object
that is being replaced will be used as the spec object.  Because the
speccing is done "lazily" (the spec is created as attributes on the mock
are accessed) you can use it with very complex or deeply nested objects
(like modules that import modules that import modules) without a big
performance hit.

Here’s an example of it in use:

     >>> from urllib import request
     >>> patcher = patch('__main__.request', autospec=True)
     >>> mock_request = patcher.start()
     >>> request is mock_request
     True
     >>> mock_request.Request
     <MagicMock name='request.Request' spec='Request' id='...'>

You can see that ‘request.Request’ has a spec.  ‘request.Request’ takes
two arguments in the constructor (one of which is `self').  Here’s what
happens if we try to call it incorrectly:

     >>> req = request.Request()
     Traceback (most recent call last):
      ...
     TypeError: <lambda>() takes at least 2 arguments (1 given)

The spec also applies to instantiated classes (i.e.  the return value of
specced mocks):

     >>> req = request.Request('foo')
     >>> req
     <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>

‘Request’ objects are not callable, so the return value of instantiating
our mocked out ‘request.Request’ is a non-callable mock.  With the spec
in place any typos in our asserts will raise the correct error:

     >>> req.add_header('spam', 'eggs')
     <MagicMock name='request.Request().add_header()' id='...'>
     >>> req.add_header.assret_called_with
     Traceback (most recent call last):
      ...
     AttributeError: Mock object has no attribute 'assret_called_with'
     >>> req.add_header.assert_called_with('spam', 'eggs')

In many cases you will just be able to add ‘autospec=True’ to your
existing *note patch(): 791. calls and then be protected against bugs
due to typos and api changes.

As well as using `autospec' through *note patch(): 791. there is a *note
create_autospec(): f59. for creating autospecced mocks directly:

     >>> from urllib import request
     >>> mock_request = create_autospec(request)
     >>> mock_request.Request('foo', 'bar')
     <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>

This isn’t without caveats and limitations however, which is why it is
not the default behaviour.  In order to know what attributes are
available on the spec object, autospec has to introspect (access
attributes) the spec.  As you traverse attributes on the mock a
corresponding traversal of the original object is happening under the
hood.  If any of your specced objects have properties or descriptors
that can trigger code execution then you may not be able to use
autospec.  On the other hand it is much better to design your objects so
that introspection is safe (1).

A more serious problem is that it is common for instance attributes to
be created in the *note __init__(): d66. method and not to exist on the
class at all.  `autospec' can’t know about any dynamically created
attributes and restricts the api to visible attributes.

     >>> class Something:
     ...   def __init__(self):
     ...     self.a = 33
     ...
     >>> with patch('__main__.Something', autospec=True):
     ...   thing = Something()
     ...   thing.a
     ...
     Traceback (most recent call last):
       ...
     AttributeError: Mock object has no attribute 'a'

There are a few different ways of resolving this problem.  The easiest,
but not necessarily the least annoying, way is to simply set the
required attributes on the mock after creation.  Just because `autospec'
doesn’t allow you to fetch attributes that don’t exist on the spec it
doesn’t prevent you setting them:

     >>> with patch('__main__.Something', autospec=True):
     ...   thing = Something()
     ...   thing.a = 33
     ...

There is a more aggressive version of both `spec' and `autospec' that
`does' prevent you setting non-existent attributes.  This is useful if
you want to ensure your code only `sets' valid attributes too, but
obviously it prevents this particular scenario:

     >>> with patch('__main__.Something', autospec=True, spec_set=True):
     ...   thing = Something()
     ...   thing.a = 33
     ...
     Traceback (most recent call last):
      ...
     AttributeError: Mock object has no attribute 'a'

Probably the best way of solving the problem is to add class attributes
as default values for instance members initialised in *note __init__():
d66.  Note that if you are only setting default attributes in *note
__init__(): d66. then providing them via class attributes (shared
between instances of course) is faster too.  e.g.

     class Something:
         a = 33

This brings up another issue.  It is relatively common to provide a
default value of ‘None’ for members that will later be an object of a
different type.  ‘None’ would be useless as a spec because it wouldn’t
let you access `any' attributes or methods on it.  As ‘None’ is `never'
going to be useful as a spec, and probably indicates a member that will
normally of some other type, autospec doesn’t use a spec for members
that are set to ‘None’.  These will just be ordinary mocks (well -
MagicMocks):

     >>> class Something:
     ...     member = None
     ...
     >>> mock = create_autospec(Something)
     >>> mock.member.foo.bar.baz()
     <MagicMock name='mock.member.foo.bar.baz()' id='...'>

If modifying your production classes to add defaults isn’t to your
liking then there are more options.  One of these is simply to use an
instance as the spec rather than the class.  The other is to create a
subclass of the production class and add the defaults to the subclass
without affecting the production class.  Both of these require you to
use an alternative object as the spec.  Thankfully *note patch(): 791.
supports this - you can simply pass the alternative object as the
`autospec' argument:

     >>> class Something:
     ...   def __init__(self):
     ...     self.a = 33
     ...
     >>> class SomethingForTest(Something):
     ...   a = 33
     ...
     >>> p = patch('__main__.Something', autospec=SomethingForTest)
     >>> mock = p.start()
     >>> mock.a
     <NonCallableMagicMock name='Something.a' spec='int' id='...'>

   ---------- Footnotes ----------

   (1) (4) This only applies to classes or already instantiated objects.
Calling a mocked class to create a mock instance `does not' create a
real instance.  It is only attribute lookups - along with calls to *note
dir(): d3b. - that are done.


File: python.info,  Node: Sealing mocks,  Prev: Autospeccing,  Up: Helpers

5.26.5.30 Sealing mocks
.......................

 -- 函数: unittest.mock.seal (mock)

     Seal will disable the automatic creation of mocks when accessing an
     attribute of the mock being sealed or any of its attributes that
     are already mocks recursively.

     If a mock instance with a name or a spec is assigned to an
     attribute it won’t be considered in the sealing chain.  This allows
     one to prevent seal from fixing part of the mock object.

          >>> mock = Mock()
          >>> mock.submock.attribute1 = 2
          >>> mock.not_submock = mock.Mock(name="sample_name")
          >>> seal(mock)
          >>> mock.new_attribute  # This will raise AttributeError.
          >>> mock.submock.attribute2  # This will raise AttributeError.
          >>> mock.not_submock.attribute2  # This won't raise.

     3.7 新版功能.


File: python.info,  Node: unittest mock 上手指南,  Next: 2to3 - 自动将 Python 2 代码转为 Python 3 代码,  Prev: unittest mock --- 模拟对象库,  Up: 开发工具

5.26.6 ‘unittest.mock’ 上手指南
-------------------------------

3.3 新版功能.

* Menu:

* 使用 mock::
* Patch Decorators::
* Further Examples::


File: python.info,  Node: 使用 mock,  Next: Patch Decorators,  Up: unittest mock 上手指南

5.26.6.1 使用 mock
..................

* Menu:

* 模拟方法调用::
* 对象上的方法调用的 mock::
* Mocking Classes::
* Naming your mocks::
* Tracking all Calls::
* Setting Return Values and Attributes::
* Raising exceptions with mocks::
* Side effect functions and iterables::
* Mocking asynchronous iterators::
* Mocking asynchronous context manager::
* Creating a Mock from an Existing Object::


File: python.info,  Node: 模拟方法调用,  Next: 对象上的方法调用的 mock,  Up: 使用 mock

5.26.6.2 模拟方法调用
.....................

使用 *note Mock: 24a. 的常见场景：

   * 模拟函数调用

   * 记录“对象上的方法调用”

你可能需要替换一个对象上的方法，用于确认此方法被系统中的其他部分调用过，
并且调用时使用了正确的参数。

     >>> real = SomeClass()
     >>> real.method = MagicMock(name='method')
     >>> real.method(3, 4, 5, key='value')
     <MagicMock name='method()' id='...'>

使用了 mock（本例中的 ‘real.method’）之后，它有方法和属性可以让你针对它
是被如何使用的下断言。

     注解: 在多数示例中，*note Mock: 24a. 与 *note MagicMock: 78e. 两个
     类可以相互替换，而 ‘MagicMock’ 是一个更适用的类，通常情况下，使用它
     就可以了。

如果 mock 被调用，它的 *note called: 339f. 属性就会变成 ‘True’，更重要的
是，我们可以使用 *note assert_called_with(): 100f. 或者 *note
assert_called_once_with(): 3395. 方法来确认它在被调用时使用了正确的参数
。

在如下的测试示例中，验证对于 ‘ProductionClass().method’ 的调用会导致
‘something’ 的调用。

     >>> class ProductionClass:
     ...     def method(self):
     ...         self.something(1, 2, 3)
     ...     def something(self, a, b, c):
     ...         pass
     ...
     >>> real = ProductionClass()
     >>> real.something = MagicMock()
     >>> real.method()
     >>> real.something.assert_called_once_with(1, 2, 3)


File: python.info,  Node: 对象上的方法调用的 mock,  Next: Mocking Classes,  Prev: 模拟方法调用,  Up: 使用 mock

5.26.6.3 对象上的方法调用的 mock
................................

In the last example we patched a method directly on an object to check
that it was called correctly.  Another common use case is to pass an
object into a method (or some part of the system under test) and then
check that it is used in the correct way.

The simple ‘ProductionClass’ below has a ‘closer’ method.  If it is
called with an object then it calls ‘close’ on it.

     >>> class ProductionClass:
     ...     def closer(self, something):
     ...         something.close()
     ...

So to test it we need to pass in an object with a ‘close’ method and
check that it was called correctly.

     >>> real = ProductionClass()
     >>> mock = Mock()
     >>> real.closer(mock)
     >>> mock.close.assert_called_with()

We don’t have to do any work to provide the ’close’ method on our mock.
Accessing close creates it.  So, if ’close’ hasn’t already been called
then accessing it in the test will create it, but *note
assert_called_with(): 100f. will raise a failure exception.


File: python.info,  Node: Mocking Classes,  Next: Naming your mocks,  Prev: 对象上的方法调用的 mock,  Up: 使用 mock

5.26.6.4 Mocking Classes
........................

A common use case is to mock out classes instantiated by your code under
test.  When you patch a class, then that class is replaced with a mock.
Instances are created by `calling the class'.  This means you access the
"mock instance" by looking at the return value of the mocked class.

In the example below we have a function ‘some_function’ that
instantiates ‘Foo’ and calls a method on it.  The call to *note patch():
791. replaces the class ‘Foo’ with a mock.  The ‘Foo’ instance is the
result of calling the mock, so it is configured by modifying the mock
*note return_value: 3393.

     >>> def some_function():
     ...     instance = module.Foo()
     ...     return instance.method()
     ...
     >>> with patch('module.Foo') as mock:
     ...     instance = mock.return_value
     ...     instance.method.return_value = 'the result'
     ...     result = some_function()
     ...     assert result == 'the result'


File: python.info,  Node: Naming your mocks,  Next: Tracking all Calls,  Prev: Mocking Classes,  Up: 使用 mock

5.26.6.5 Naming your mocks
..........................

It can be useful to give your mocks a name.  The name is shown in the
repr of the mock and can be helpful when the mock appears in test
failure messages.  The name is also propagated to attributes or methods
of the mock:

     >>> mock = MagicMock(name='foo')
     >>> mock
     <MagicMock name='foo' id='...'>
     >>> mock.method
     <MagicMock name='foo.method' id='...'>


File: python.info,  Node: Tracking all Calls,  Next: Setting Return Values and Attributes,  Prev: Naming your mocks,  Up: 使用 mock

5.26.6.6 Tracking all Calls
...........................

Often you want to track more than a single call to a method.  The *note
mock_calls: 3398. attribute records all calls to child attributes of the
mock - and also to their children.

     >>> mock = MagicMock()
     >>> mock.method()
     <MagicMock name='mock.method()' id='...'>
     >>> mock.attribute.method(10, x=53)
     <MagicMock name='mock.attribute.method()' id='...'>
     >>> mock.mock_calls
     [call.method(), call.attribute.method(10, x=53)]

If you make an assertion about ‘mock_calls’ and any unexpected methods
have been called, then the assertion will fail.  This is useful because
as well as asserting that the calls you expected have been made, you are
also checking that they were made in the right order and with no
additional calls:

You use the *note call: f8a. object to construct lists for comparing
with ‘mock_calls’:

     >>> expected = [call.method(), call.attribute.method(10, x=53)]
     >>> mock.mock_calls == expected
     True

However, parameters to calls that return mocks are not recorded, which
means it is not possible to track nested calls where the parameters used
to create ancestors are important:

     >>> m = Mock()
     >>> m.factory(important=True).deliver()
     <Mock name='mock.factory().deliver()' id='...'>
     >>> m.mock_calls[-1] == call.factory(important=False).deliver()
     True


File: python.info,  Node: Setting Return Values and Attributes,  Next: Raising exceptions with mocks,  Prev: Tracking all Calls,  Up: 使用 mock

5.26.6.7 Setting Return Values and Attributes
.............................................

Setting the return values on a mock object is trivially easy:

     >>> mock = Mock()
     >>> mock.return_value = 3
     >>> mock()
     3

Of course you can do the same for methods on the mock:

     >>> mock = Mock()
     >>> mock.method.return_value = 3
     >>> mock.method()
     3

The return value can also be set in the constructor:

     >>> mock = Mock(return_value=3)
     >>> mock()
     3

If you need an attribute setting on your mock, just do it:

     >>> mock = Mock()
     >>> mock.x = 3
     >>> mock.x
     3

Sometimes you want to mock up a more complex situation, like for example
‘mock.connection.cursor().execute("SELECT 1")’.  If we wanted this call
to return a list, then we have to configure the result of the nested
call.

We can use *note call: f8a. to construct the set of calls in a "chained
call" like this for easy assertion afterwards:

     >>> mock = Mock()
     >>> cursor = mock.connection.cursor.return_value
     >>> cursor.execute.return_value = ['foo']
     >>> mock.connection.cursor().execute("SELECT 1")
     ['foo']
     >>> expected = call.connection.cursor().execute("SELECT 1").call_list()
     >>> mock.mock_calls
     [call.connection.cursor(), call.connection.cursor().execute('SELECT 1')]
     >>> mock.mock_calls == expected
     True

It is the call to ‘.call_list()’ that turns our call object into a list
of calls representing the chained calls.


File: python.info,  Node: Raising exceptions with mocks,  Next: Side effect functions and iterables,  Prev: Setting Return Values and Attributes,  Up: 使用 mock

5.26.6.8 Raising exceptions with mocks
......................................

A useful attribute is *note side_effect: 3391.  If you set this to an
exception class or instance then the exception will be raised when the
mock is called.

     >>> mock = Mock(side_effect=Exception('Boom!'))
     >>> mock()
     Traceback (most recent call last):
       ...
     Exception: Boom!


File: python.info,  Node: Side effect functions and iterables,  Next: Mocking asynchronous iterators,  Prev: Raising exceptions with mocks,  Up: 使用 mock

5.26.6.9 Side effect functions and iterables
............................................

‘side_effect’ can also be set to a function or an iterable.  The use
case for ‘side_effect’ as an iterable is where your mock is going to be
called several times, and you want each call to return a different
value.  When you set ‘side_effect’ to an iterable every call to the mock
returns the next value from the iterable:

     >>> mock = MagicMock(side_effect=[4, 5, 6])
     >>> mock()
     4
     >>> mock()
     5
     >>> mock()
     6

For more advanced use cases, like dynamically varying the return values
depending on what the mock is called with, ‘side_effect’ can be a
function.  The function will be called with the same arguments as the
mock.  Whatever the function returns is what the call returns:

     >>> vals = {(1, 2): 1, (2, 3): 2}
     >>> def side_effect(*args):
     ...     return vals[args]
     ...
     >>> mock = MagicMock(side_effect=side_effect)
     >>> mock(1, 2)
     1
     >>> mock(2, 3)
     2


File: python.info,  Node: Mocking asynchronous iterators,  Next: Mocking asynchronous context manager,  Prev: Side effect functions and iterables,  Up: 使用 mock

5.26.6.10 Mocking asynchronous iterators
........................................

Since Python 3.8, ‘AsyncMock’ and ‘MagicMock’ have support to mock *note
异步迭代器: 64f. through ‘__aiter__’.  The *note return_value: 3393.
attribute of ‘__aiter__’ can be used to set the return values to be used
for iteration.

     >>> mock = MagicMock()  # AsyncMock also works here
     >>> mock.__aiter__.return_value = [1, 2, 3]
     >>> async def main():
     ...     return [i async for i in mock]
     ...
     >>> asyncio.run(main())
     [1, 2, 3]


File: python.info,  Node: Mocking asynchronous context manager,  Next: Creating a Mock from an Existing Object,  Prev: Mocking asynchronous iterators,  Up: 使用 mock

5.26.6.11 Mocking asynchronous context manager
..............................................

Since Python 3.8, ‘AsyncMock’ and ‘MagicMock’ have support to mock *note
异步上下文管理器: 14a6. through ‘__aenter__’ and ‘__aexit__’.  By
default, ‘__aenter__’ and ‘__aexit__’ are ‘AsyncMock’ instances that
return an async function.

     >>> class AsyncContextManager:
     ...     async def __aenter__(self):
     ...         return self
     ...     async def __aexit__(self, exc_type, exc, tb):
     ...         pass
     ...
     >>> mock_instance = MagicMock(AsyncContextManager())  # AsyncMock also works here
     >>> async def main():
     ...     async with mock_instance as result:
     ...         pass
     ...
     >>> asyncio.run(main())
     >>> mock_instance.__aenter__.assert_awaited_once()
     >>> mock_instance.__aexit__.assert_awaited_once()


File: python.info,  Node: Creating a Mock from an Existing Object,  Prev: Mocking asynchronous context manager,  Up: 使用 mock

5.26.6.12 Creating a Mock from an Existing Object
.................................................

One problem with over use of mocking is that it couples your tests to
the implementation of your mocks rather than your real code.  Suppose
you have a class that implements ‘some_method’.  In a test for another
class, you provide a mock of this object that `also' provides
‘some_method’.  If later you refactor the first class, so that it no
longer has ‘some_method’ - then your tests will continue to pass even
though your code is now broken!

*note Mock: 24a. allows you to provide an object as a specification for
the mock, using the `spec' keyword argument.  Accessing methods /
attributes on the mock that don’t exist on your specification object
will immediately raise an attribute error.  If you change the
implementation of your specification, then tests that use that class
will start failing immediately without you having to instantiate the
class in those tests.

     >>> mock = Mock(spec=SomeClass)
     >>> mock.old_method()
     Traceback (most recent call last):
        ...
     AttributeError: object has no attribute 'old_method'

Using a specification also enables a smarter matching of calls made to
the mock, regardless of whether some parameters were passed as
positional or named arguments:

     >>> def f(a, b, c): pass
     ...
     >>> mock = Mock(spec=f)
     >>> mock(1, 2, 3)
     <Mock name='mock()' id='140161580456576'>
     >>> mock.assert_called_with(a=1, b=2, c=3)

If you want this smarter matching to also work with method calls on the
mock, you can use *note auto-speccing: 338d.

If you want a stronger form of specification that prevents the setting
of arbitrary attributes as well as the getting of them then you can use
`spec_set' instead of `spec'.


File: python.info,  Node: Patch Decorators,  Next: Further Examples,  Prev: 使用 mock,  Up: unittest mock 上手指南

5.26.6.13 Patch Decorators
..........................

     注解: 在查找对象的名称空间中修补对象使用 *note patch(): 791. 。使用
     起来很简单，阅读 *note 在哪里打补丁: 338b. 来快速上手。

A common need in tests is to patch a class attribute or a module
attribute, for example patching a builtin or patching a class in a
module to test that it is instantiated.  Modules and classes are
effectively global, so patching on them has to be undone after the test
or the patch will persist into other tests and cause hard to diagnose
problems.

mock provides three convenient decorators for this: *note patch(): 791,
*note patch.object(): f6f. and *note patch.dict(): fdf.  ‘patch’ takes a
single string, of the form ‘package.module.Class.attribute’ to specify
the attribute you are patching.  It also optionally takes a value that
you want the attribute (or class or whatever) to be replaced with.
’patch.object’ takes an object and the name of the attribute you would
like patched, plus optionally the value to patch it with.

‘patch.object’:

     >>> original = SomeClass.attribute
     >>> @patch.object(SomeClass, 'attribute', sentinel.attribute)
     ... def test():
     ...     assert SomeClass.attribute == sentinel.attribute
     ...
     >>> test()
     >>> assert SomeClass.attribute == original

     >>> @patch('package.module.attribute', sentinel.attribute)
     ... def test():
     ...     from package.module import attribute
     ...     assert attribute is sentinel.attribute
     ...
     >>> test()

If you are patching a module (including *note builtins: 13.) then use
*note patch(): 791. instead of *note patch.object(): f6f.:

     >>> mock = MagicMock(return_value=sentinel.file_handle)
     >>> with patch('builtins.open', mock):
     ...     handle = open('filename', 'r')
     ...
     >>> mock.assert_called_with('filename', 'r')
     >>> assert handle == sentinel.file_handle, "incorrect file handle returned"

The module name can be ’dotted’, in the form ‘package.module’ if needed:

     >>> @patch('package.module.ClassName.attribute', sentinel.attribute)
     ... def test():
     ...     from package.module import ClassName
     ...     assert ClassName.attribute == sentinel.attribute
     ...
     >>> test()

A nice pattern is to actually decorate test methods themselves:

     >>> class MyTest(unittest.TestCase):
     ...     @patch.object(SomeClass, 'attribute', sentinel.attribute)
     ...     def test_something(self):
     ...         self.assertEqual(SomeClass.attribute, sentinel.attribute)
     ...
     >>> original = SomeClass.attribute
     >>> MyTest('test_something').test_something()
     >>> assert SomeClass.attribute == original

If you want to patch with a Mock, you can use *note patch(): 791. with
only one argument (or *note patch.object(): f6f. with two arguments).
The mock will be created for you and passed into the test function /
method:

     >>> class MyTest(unittest.TestCase):
     ...     @patch.object(SomeClass, 'static_method')
     ...     def test_something(self, mock_method):
     ...         SomeClass.static_method()
     ...         mock_method.assert_called_with()
     ...
     >>> MyTest('test_something').test_something()

You can stack up multiple patch decorators using this pattern:

     >>> class MyTest(unittest.TestCase):
     ...     @patch('package.module.ClassName1')
     ...     @patch('package.module.ClassName2')
     ...     def test_something(self, MockClass2, MockClass1):
     ...         self.assertIs(package.module.ClassName1, MockClass1)
     ...         self.assertIs(package.module.ClassName2, MockClass2)
     ...
     >>> MyTest('test_something').test_something()

When you nest patch decorators the mocks are passed in to the decorated
function in the same order they applied (the normal `Python' order that
decorators are applied).  This means from the bottom up, so in the
example above the mock for ‘test_module.ClassName2’ is passed in first.

还有一个 *note patch.dict(): fdf. 用于在一定范围内设置字典中的值，并在测
试结束时将字典恢复为其原始状态：

     >>> foo = {'key': 'value'}
     >>> original = foo.copy()
     >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
     ...     assert foo == {'newkey': 'newvalue'}
     ...
     >>> assert foo == original

‘patch’, ‘patch.object’ and ‘patch.dict’ can all be used as context
managers.

Where you use *note patch(): 791. to create a mock for you, you can get
a reference to the mock using the "as" form of the with statement:

     >>> class ProductionClass:
     ...     def method(self):
     ...         pass
     ...
     >>> with patch.object(ProductionClass, 'method') as mock_method:
     ...     mock_method.return_value = None
     ...     real = ProductionClass()
     ...     real.method(1, 2, 3)
     ...
     >>> mock_method.assert_called_with(1, 2, 3)

As an alternative ‘patch’, ‘patch.object’ and ‘patch.dict’ can be used
as class decorators.  When used in this way it is the same as applying
the decorator individually to every method whose name starts with
"test".


File: python.info,  Node: Further Examples,  Prev: Patch Decorators,  Up: unittest mock 上手指南

5.26.6.14 Further Examples
..........................

Here are some more examples for some slightly more advanced scenarios.

* Menu:

* Mocking chained calls::
* Partial mocking::
* Mocking a Generator Method::
* Applying the same patch to every test method::
* Mocking Unbound Methods::
* Checking multiple calls with mock::
* Coping with mutable arguments::
* Nesting Patches::
* Mocking a dictionary with MagicMock::
* Mock subclasses and their attributes::
* Mocking imports with patch.dict: Mocking imports with patch dict.
* Tracking order of calls and less verbose call assertions::
* More complex argument matching::


File: python.info,  Node: Mocking chained calls,  Next: Partial mocking,  Up: Further Examples

5.26.6.15 Mocking chained calls
...............................

Mocking chained calls is actually straightforward with mock once you
understand the *note return_value: 3393. attribute.  When a mock is
called for the first time, or you fetch its ‘return_value’ before it has
been called, a new *note Mock: 24a. is created.

This means that you can see how the object returned from a call to a
mocked object has been used by interrogating the ‘return_value’ mock:

     >>> mock = Mock()
     >>> mock().foo(a=2, b=3)
     <Mock name='mock().foo()' id='...'>
     >>> mock.return_value.foo.assert_called_with(a=2, b=3)

From here it is a simple step to configure and then make assertions
about chained calls.  Of course another alternative is writing your code
in a more testable way in the first place...

So, suppose we have some code that looks a little bit like this:

     >>> class Something:
     ...     def __init__(self):
     ...         self.backend = BackendProvider()
     ...     def method(self):
     ...         response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
     ...         # more code

Assuming that ‘BackendProvider’ is already well tested, how do we test
‘method()’?  Specifically, we want to test that the code section ‘# more
code’ uses the response object in the correct way.

As this chain of calls is made from an instance attribute we can monkey
patch the ‘backend’ attribute on a ‘Something’ instance.  In this
particular case we are only interested in the return value from the
final call to ‘start_call’ so we don’t have much configuration to do.
Let’s assume the object it returns is ’file-like’, so we’ll ensure that
our response object uses the builtin *note open(): 4f8. as its ‘spec’.

To do this we create a mock instance as our mock backend and create a
mock response object for it.  To set the response as the return value
for that final ‘start_call’ we could do this:

     mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response

We can do that in a slightly nicer way using the *note configure_mock():
3394. method to directly set the return value for us:

     >>> something = Something()
     >>> mock_response = Mock(spec=open)
     >>> mock_backend = Mock()
     >>> config = {'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response}
     >>> mock_backend.configure_mock(**config)

With these we monkey patch the "mock backend" in place and can make the
real call:

     >>> something.backend = mock_backend
     >>> something.method()

Using *note mock_calls: 3398. we can check the chained call with a
single assert.  A chained call is several calls in one line of code, so
there will be several entries in ‘mock_calls’.  We can use *note
call.call_list(): 33cb. to create this list of calls for us:

     >>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
     >>> call_list = chained.call_list()
     >>> assert mock_backend.mock_calls == call_list


File: python.info,  Node: Partial mocking,  Next: Mocking a Generator Method,  Prev: Mocking chained calls,  Up: Further Examples

5.26.6.16 Partial mocking
.........................

In some tests I wanted to mock out a call to *note
datetime.date.today(): 18b8. to return a known date, but I didn’t want
to prevent the code under test from creating new date objects.
Unfortunately *note datetime.date: 194. is written in C, and so I
couldn’t just monkey-patch out the static ‘date.today()’ method.

I found a simple way of doing this that involved effectively wrapping
the date class with a mock, but passing through calls to the constructor
to the real class (and returning real instances).

The *note patch decorator: 791. is used here to mock out the ‘date’
class in the module under test.  The ‘side_effect’ attribute on the mock
date class is then set to a lambda function that returns a real date.
When the mock date class is called a real date will be constructed and
returned by ‘side_effect’.

     >>> from datetime import date
     >>> with patch('mymodule.date') as mock_date:
     ...     mock_date.today.return_value = date(2010, 10, 8)
     ...     mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
     ...
     ...     assert mymodule.date.today() == date(2010, 10, 8)
     ...     assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)

Note that we don’t patch *note datetime.date: 194. globally, we patch
‘date’ in the module that `uses' it.  See *note where to patch: 338b.

When ‘date.today()’ is called a known date is returned, but calls to the
‘date(...)’ constructor still return normal dates.  Without this you can
find yourself having to calculate an expected result using exactly the
same algorithm as the code under test, which is a classic testing
anti-pattern.

Calls to the date constructor are recorded in the ‘mock_date’ attributes
(‘call_count’ and friends) which may also be useful for your tests.

An alternative way of dealing with mocking dates, or other builtin
classes, is discussed in this blog entry(1).

   ---------- Footnotes ----------

   (1) 
https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/


File: python.info,  Node: Mocking a Generator Method,  Next: Applying the same patch to every test method,  Prev: Partial mocking,  Up: Further Examples

5.26.6.17 Mocking a Generator Method
....................................

A Python generator is a function or method that uses the *note yield:
190. statement to return a series of values when iterated over (1).

A generator method / function is called to return the generator object.
It is the generator object that is then iterated over.  The protocol
method for iteration is *note __iter__(): 1639, so we can mock this
using a *note MagicMock: 78e.

Here’s an example class with an "iter" method implemented as a
generator:

     >>> class Foo:
     ...     def iter(self):
     ...         for i in [1, 2, 3]:
     ...             yield i
     ...
     >>> foo = Foo()
     >>> list(foo.iter())
     [1, 2, 3]

How would we mock this class, and in particular its "iter" method?

To configure the values returned from the iteration (implicit in the
call to *note list: 263.), we need to configure the object returned by
the call to ‘foo.iter()’.

     >>> mock_foo = MagicMock()
     >>> mock_foo.iter.return_value = iter([1, 2, 3])
     >>> list(mock_foo.iter())
     [1, 2, 3]

   ---------- Footnotes ----------

   (1) (1) There are also generator expressions and more advanced uses
(http://www.dabeaz.com/coroutines/index.html) of generators, but we
aren’t concerned about them here.  A very good introduction to
generators and how powerful they are is: Generator Tricks for Systems
Programmers (http://www.dabeaz.com/generators/).


File: python.info,  Node: Applying the same patch to every test method,  Next: Mocking Unbound Methods,  Prev: Mocking a Generator Method,  Up: Further Examples

5.26.6.18 Applying the same patch to every test method
......................................................

If you want several patches in place for multiple test methods the
obvious way is to apply the patch decorators to every method.  This can
feel like unnecessary repetition.  For Python 2.6 or more recent you can
use *note patch(): 791. (in all its various forms) as a class decorator.
This applies the patches to all test methods on the class.  A test
method is identified by methods whose names start with ‘test’:

     >>> @patch('mymodule.SomeClass')
     ... class MyTest(unittest.TestCase):
     ...
     ...     def test_one(self, MockSomeClass):
     ...         self.assertIs(mymodule.SomeClass, MockSomeClass)
     ...
     ...     def test_two(self, MockSomeClass):
     ...         self.assertIs(mymodule.SomeClass, MockSomeClass)
     ...
     ...     def not_a_test(self):
     ...         return 'something'
     ...
     >>> MyTest('test_one').test_one()
     >>> MyTest('test_two').test_two()
     >>> MyTest('test_two').not_a_test()
     'something'

An alternative way of managing patches is to use the *note patch
methods; start and stop: 33bd.  These allow you to move the patching
into your ‘setUp’ and ‘tearDown’ methods.

     >>> class MyTest(unittest.TestCase):
     ...     def setUp(self):
     ...         self.patcher = patch('mymodule.foo')
     ...         self.mock_foo = self.patcher.start()
     ...
     ...     def test_foo(self):
     ...         self.assertIs(mymodule.foo, self.mock_foo)
     ...
     ...     def tearDown(self):
     ...         self.patcher.stop()
     ...
     >>> MyTest('test_foo').run()

If you use this technique you must ensure that the patching is "undone"
by calling ‘stop’.  This can be fiddlier than you might think, because
if an exception is raised in the setUp then tearDown is not called.
*note unittest.TestCase.addCleanup(): 2a3. makes this easier:

     >>> class MyTest(unittest.TestCase):
     ...     def setUp(self):
     ...         patcher = patch('mymodule.foo')
     ...         self.addCleanup(patcher.stop)
     ...         self.mock_foo = patcher.start()
     ...
     ...     def test_foo(self):
     ...         self.assertIs(mymodule.foo, self.mock_foo)
     ...
     >>> MyTest('test_foo').run()


File: python.info,  Node: Mocking Unbound Methods,  Next: Checking multiple calls with mock,  Prev: Applying the same patch to every test method,  Up: Further Examples

5.26.6.19 Mocking Unbound Methods
.................................

Whilst writing tests today I needed to patch an `unbound method'
(patching the method on the class rather than on the instance).  I
needed self to be passed in as the first argument because I want to make
asserts about which objects were calling this particular method.  The
issue is that you can’t patch with a mock for this, because if you
replace an unbound method with a mock it doesn’t become a bound method
when fetched from the instance, and so it doesn’t get self passed in.
The workaround is to patch the unbound method with a real function
instead.  The *note patch(): 791. decorator makes it so simple to patch
out methods with a mock that having to create a real function becomes a
nuisance.

If you pass ‘autospec=True’ to patch then it does the patching with a
`real' function object.  This function object has the same signature as
the one it is replacing, but delegates to a mock under the hood.  You
still get your mock auto-created in exactly the same way as before.
What it means though, is that if you use it to patch out an unbound
method on a class the mocked function will be turned into a bound method
if it is fetched from an instance.  It will have ‘self’ passed in as the
first argument, which is exactly what I wanted:

     >>> class Foo:
     ...   def foo(self):
     ...     pass
     ...
     >>> with patch.object(Foo, 'foo', autospec=True) as mock_foo:
     ...   mock_foo.return_value = 'foo'
     ...   foo = Foo()
     ...   foo.foo()
     ...
     'foo'
     >>> mock_foo.assert_called_once_with(foo)

If we don’t use ‘autospec=True’ then the unbound method is patched out
with a Mock instance instead, and isn’t called with ‘self’.


File: python.info,  Node: Checking multiple calls with mock,  Next: Coping with mutable arguments,  Prev: Mocking Unbound Methods,  Up: Further Examples

5.26.6.20 Checking multiple calls with mock
...........................................

mock has a nice API for making assertions about how your mock objects
are used.

     >>> mock = Mock()
     >>> mock.foo_bar.return_value = None
     >>> mock.foo_bar('baz', spam='eggs')
     >>> mock.foo_bar.assert_called_with('baz', spam='eggs')

If your mock is only being called once you can use the
‘assert_called_once_with()’ method that also asserts that the
‘call_count’ is one.

     >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
     >>> mock.foo_bar()
     >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
     Traceback (most recent call last):
         ...
     AssertionError: Expected to be called once. Called 2 times.

Both ‘assert_called_with’ and ‘assert_called_once_with’ make assertions
about the `most recent' call.  If your mock is going to be called
several times, and you want to make assertions about `all' those calls
you can use *note call_args_list: 33a1.:

     >>> mock = Mock(return_value=None)
     >>> mock(1, 2, 3)
     >>> mock(4, 5, 6)
     >>> mock()
     >>> mock.call_args_list
     [call(1, 2, 3), call(4, 5, 6), call()]

The *note call: f8a. helper makes it easy to make assertions about these
calls.  You can build up a list of expected calls and compare it to
‘call_args_list’.  This looks remarkably similar to the repr of the
‘call_args_list’:

     >>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
     >>> mock.call_args_list == expected
     True


File: python.info,  Node: Coping with mutable arguments,  Next: Nesting Patches,  Prev: Checking multiple calls with mock,  Up: Further Examples

5.26.6.21 Coping with mutable arguments
.......................................

Another situation is rare, but can bite you, is when your mock is called
with mutable arguments.  ‘call_args’ and ‘call_args_list’ store
`references' to the arguments.  If the arguments are mutated by the code
under test then you can no longer make assertions about what the values
were when the mock was called.

Here’s some example code that shows the problem.  Imagine the following
functions defined in ’mymodule’:

     def frob(val):
         pass

     def grob(val):
         "First frob and then clear val"
         frob(val)
         val.clear()

When we try to test that ‘grob’ calls ‘frob’ with the correct argument
look what happens:

     >>> with patch('mymodule.frob') as mock_frob:
     ...     val = {6}
     ...     mymodule.grob(val)
     ...
     >>> val
     set()
     >>> mock_frob.assert_called_with({6})
     Traceback (most recent call last):
         ...
     AssertionError: Expected: (({6},), {})
     Called with: ((set(),), {})

One possibility would be for mock to copy the arguments you pass in.
This could then cause problems if you do assertions that rely on object
identity for equality.

Here’s one solution that uses the ‘side_effect’ functionality.  If you
provide a ‘side_effect’ function for a mock then ‘side_effect’ will be
called with the same args as the mock.  This gives us an opportunity to
copy the arguments and store them for later assertions.  In this example
I’m using `another' mock to store the arguments so that I can use the
mock methods for doing the assertion.  Again a helper function sets this
up for me.

     >>> from copy import deepcopy
     >>> from unittest.mock import Mock, patch, DEFAULT
     >>> def copy_call_args(mock):
     ...     new_mock = Mock()
     ...     def side_effect(*args, **kwargs):
     ...         args = deepcopy(args)
     ...         kwargs = deepcopy(kwargs)
     ...         new_mock(*args, **kwargs)
     ...         return DEFAULT
     ...     mock.side_effect = side_effect
     ...     return new_mock
     ...
     >>> with patch('mymodule.frob') as mock_frob:
     ...     new_mock = copy_call_args(mock_frob)
     ...     val = {6}
     ...     mymodule.grob(val)
     ...
     >>> new_mock.assert_called_with({6})
     >>> new_mock.call_args
     call({6})

‘copy_call_args’ is called with the mock that will be called.  It
returns a new mock that we do the assertion on.  The ‘side_effect’
function makes a copy of the args and calls our ‘new_mock’ with the
copy.

     注解: If your mock is only going to be used once there is an easier
     way of checking arguments at the point they are called.  You can
     simply do the checking inside a ‘side_effect’ function.

          >>> def side_effect(arg):
          ...     assert arg == {6}
          ...
          >>> mock = Mock(side_effect=side_effect)
          >>> mock({6})
          >>> mock(set())
          Traceback (most recent call last):
              ...
          AssertionError

An alternative approach is to create a subclass of *note Mock: 24a. or
*note MagicMock: 78e. that copies (using *note copy.deepcopy(): 3d4.)
the arguments.  Here’s an example implementation:

     >>> from copy import deepcopy
     >>> class CopyingMock(MagicMock):
     ...     def __call__(self, /, *args, **kwargs):
     ...         args = deepcopy(args)
     ...         kwargs = deepcopy(kwargs)
     ...         return super().__call__(*args, **kwargs)
     ...
     >>> c = CopyingMock(return_value=None)
     >>> arg = set()
     >>> c(arg)
     >>> arg.add(1)
     >>> c.assert_called_with(set())
     >>> c.assert_called_with(arg)
     Traceback (most recent call last):
         ...
     AssertionError: Expected call: mock({1})
     Actual call: mock(set())
     >>> c.foo
     <CopyingMock name='mock.foo' id='...'>

When you subclass ‘Mock’ or ‘MagicMock’ all dynamically created
attributes, and the ‘return_value’ will use your subclass automatically.
That means all children of a ‘CopyingMock’ will also have the type
‘CopyingMock’.


File: python.info,  Node: Nesting Patches,  Next: Mocking a dictionary with MagicMock,  Prev: Coping with mutable arguments,  Up: Further Examples

5.26.6.22 Nesting Patches
.........................

Using patch as a context manager is nice, but if you do multiple patches
you can end up with nested with statements indenting further and further
to the right:

     >>> class MyTest(unittest.TestCase):
     ...
     ...     def test_foo(self):
     ...         with patch('mymodule.Foo') as mock_foo:
     ...             with patch('mymodule.Bar') as mock_bar:
     ...                 with patch('mymodule.Spam') as mock_spam:
     ...                     assert mymodule.Foo is mock_foo
     ...                     assert mymodule.Bar is mock_bar
     ...                     assert mymodule.Spam is mock_spam
     ...
     >>> original = mymodule.Foo
     >>> MyTest('test_foo').test_foo()
     >>> assert mymodule.Foo is original

With unittest ‘cleanup’ functions and the *note patch methods; start and
stop: 33bd. we can achieve the same effect without the nested
indentation.  A simple helper method, ‘create_patch’, puts the patch in
place and returns the created mock for us:

     >>> class MyTest(unittest.TestCase):
     ...
     ...     def create_patch(self, name):
     ...         patcher = patch(name)
     ...         thing = patcher.start()
     ...         self.addCleanup(patcher.stop)
     ...         return thing
     ...
     ...     def test_foo(self):
     ...         mock_foo = self.create_patch('mymodule.Foo')
     ...         mock_bar = self.create_patch('mymodule.Bar')
     ...         mock_spam = self.create_patch('mymodule.Spam')
     ...
     ...         assert mymodule.Foo is mock_foo
     ...         assert mymodule.Bar is mock_bar
     ...         assert mymodule.Spam is mock_spam
     ...
     >>> original = mymodule.Foo
     >>> MyTest('test_foo').run()
     >>> assert mymodule.Foo is original


File: python.info,  Node: Mocking a dictionary with MagicMock,  Next: Mock subclasses and their attributes,  Prev: Nesting Patches,  Up: Further Examples

5.26.6.23 Mocking a dictionary with MagicMock
.............................................

You may want to mock a dictionary, or other container object, recording
all access to it whilst having it still behave like a dictionary.

We can do this with *note MagicMock: 78e, which will behave like a
dictionary, and using *note side_effect: 3391. to delegate dictionary
access to a real underlying dictionary that is under our control.

When the *note __getitem__(): 280. and *note __setitem__(): c6a. methods
of our ‘MagicMock’ are called (normal dictionary access) then
‘side_effect’ is called with the key (and in the case of ‘__setitem__’
the value too).  We can also control what is returned.

After the ‘MagicMock’ has been used we can use attributes like *note
call_args_list: 33a1. to assert about how the dictionary was used:

     >>> my_dict = {'a': 1, 'b': 2, 'c': 3}
     >>> def getitem(name):
     ...      return my_dict[name]
     ...
     >>> def setitem(name, val):
     ...     my_dict[name] = val
     ...
     >>> mock = MagicMock()
     >>> mock.__getitem__.side_effect = getitem
     >>> mock.__setitem__.side_effect = setitem

     注解: An alternative to using ‘MagicMock’ is to use ‘Mock’ and
     `only' provide the magic methods you specifically want:

          >>> mock = Mock()
          >>> mock.__getitem__ = Mock(side_effect=getitem)
          >>> mock.__setitem__ = Mock(side_effect=setitem)

     A `third' option is to use ‘MagicMock’ but passing in ‘dict’ as the
     `spec' (or `spec_set') argument so that the ‘MagicMock’ created
     only has dictionary magic methods available:

          >>> mock = MagicMock(spec_set=dict)
          >>> mock.__getitem__.side_effect = getitem
          >>> mock.__setitem__.side_effect = setitem

With these side effect functions in place, the ‘mock’ will behave like a
normal dictionary but recording the access.  It even raises a *note
KeyError: 2c8. if you try to access a key that doesn’t exist.

     >>> mock['a']
     1
     >>> mock['c']
     3
     >>> mock['d']
     Traceback (most recent call last):
         ...
     KeyError: 'd'
     >>> mock['b'] = 'fish'
     >>> mock['d'] = 'eggs'
     >>> mock['b']
     'fish'
     >>> mock['d']
     'eggs'

After it has been used you can make assertions about the access using
the normal mock methods and attributes:

     >>> mock.__getitem__.call_args_list
     [call('a'), call('c'), call('d'), call('b'), call('d')]
     >>> mock.__setitem__.call_args_list
     [call('b', 'fish'), call('d', 'eggs')]
     >>> my_dict
     {'a': 1, 'b': 'fish', 'c': 3, 'd': 'eggs'}


File: python.info,  Node: Mock subclasses and their attributes,  Next: Mocking imports with patch dict,  Prev: Mocking a dictionary with MagicMock,  Up: Further Examples

5.26.6.24 Mock subclasses and their attributes
..............................................

There are various reasons why you might want to subclass *note Mock:
24a.  One reason might be to add helper methods.  Here’s a silly
example:

     >>> class MyMock(MagicMock):
     ...     def has_been_called(self):
     ...         return self.called
     ...
     >>> mymock = MyMock(return_value=None)
     >>> mymock
     <MyMock id='...'>
     >>> mymock.has_been_called()
     False
     >>> mymock()
     >>> mymock.has_been_called()
     True

The standard behaviour for ‘Mock’ instances is that attributes and the
return value mocks are of the same type as the mock they are accessed
on.  This ensures that ‘Mock’ attributes are ‘Mocks’ and ‘MagicMock’
attributes are ‘MagicMocks’ (1).  So if you’re subclassing to add helper
methods then they’ll also be available on the attributes and return
value mock of instances of your subclass.

     >>> mymock.foo
     <MyMock name='mock.foo' id='...'>
     >>> mymock.foo.has_been_called()
     False
     >>> mymock.foo()
     <MyMock name='mock.foo()' id='...'>
     >>> mymock.foo.has_been_called()
     True

Sometimes this is inconvenient.  For example, one user(2) is subclassing
mock to created a Twisted adaptor(3).  Having this applied to attributes
too actually causes errors.

‘Mock’ (in all its flavours) uses a method called ‘_get_child_mock’ to
create these "sub-mocks" for attributes and return values.  You can
prevent your subclass being used for attributes by overriding this
method.  The signature is that it takes arbitrary keyword arguments
(‘**kwargs’) which are then passed onto the mock constructor:

     >>> class Subclass(MagicMock):
     ...     def _get_child_mock(self, /, **kwargs):
     ...         return MagicMock(**kwargs)
     ...
     >>> mymock = Subclass()
     >>> mymock.foo
     <MagicMock name='mock.foo' id='...'>
     >>> assert isinstance(mymock, Subclass)
     >>> assert not isinstance(mymock.foo, Subclass)
     >>> assert not isinstance(mymock(), Subclass)

   ---------- Footnotes ----------

   (1) (2) An exception to this rule are the non-callable mocks.
Attributes use the callable variant because otherwise non-callable mocks
couldn’t have callable methods.

   (2) https://code.google.com/archive/p/mock/issues/105

   (3) 
https://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html


File: python.info,  Node: Mocking imports with patch dict,  Next: Tracking order of calls and less verbose call assertions,  Prev: Mock subclasses and their attributes,  Up: Further Examples

5.26.6.25 Mocking imports with patch.dict
.........................................

One situation where mocking can be hard is where you have a local import
inside a function.  These are harder to mock because they aren’t using
an object from the module namespace that we can patch out.

Generally local imports are to be avoided.  They are sometimes done to
prevent circular dependencies, for which there is `usually' a much
better way to solve the problem (refactor the code) or to prevent "up
front costs" by delaying the import.  This can also be solved in better
ways than an unconditional local import (store the module as a class or
module attribute and only do the import on first use).

That aside there is a way to use ‘mock’ to affect the results of an
import.  Importing fetches an `object' from the *note sys.modules: f36.
dictionary.  Note that it fetches an `object', which need not be a
module.  Importing a module for the first time results in a module
object being put in ‘sys.modules’, so usually when you import something
you get a module back.  This need not be the case however.

This means you can use *note patch.dict(): fdf. to `temporarily' put a
mock in place in *note sys.modules: f36.  Any imports whilst this patch
is active will fetch the mock.  When the patch is complete (the
decorated function exits, the with statement body is complete or
‘patcher.stop()’ is called) then whatever was there previously will be
restored safely.

Here’s an example that mocks out the ’fooble’ module.

     >>> import sys
     >>> mock = Mock()
     >>> with patch.dict('sys.modules', {'fooble': mock}):
     ...    import fooble
     ...    fooble.blob()
     ...
     <Mock name='mock.blob()' id='...'>
     >>> assert 'fooble' not in sys.modules
     >>> mock.blob.assert_called_once_with()

As you can see the ‘import fooble’ succeeds, but on exit there is no
’fooble’ left in *note sys.modules: f36.

This also works for the ‘from module import name’ form:

     >>> mock = Mock()
     >>> with patch.dict('sys.modules', {'fooble': mock}):
     ...    from fooble import blob
     ...    blob.blip()
     ...
     <Mock name='mock.blob.blip()' id='...'>
     >>> mock.blob.blip.assert_called_once_with()

With slightly more work you can also mock package imports:

     >>> mock = Mock()
     >>> modules = {'package': mock, 'package.module': mock.module}
     >>> with patch.dict('sys.modules', modules):
     ...    from package.module import fooble
     ...    fooble()
     ...
     <Mock name='mock.module.fooble()' id='...'>
     >>> mock.module.fooble.assert_called_once_with()


File: python.info,  Node: Tracking order of calls and less verbose call assertions,  Next: More complex argument matching,  Prev: Mocking imports with patch dict,  Up: Further Examples

5.26.6.26 Tracking order of calls and less verbose call assertions
..................................................................

The *note Mock: 24a. class allows you to track the `order' of method
calls on your mock objects through the *note method_calls: 339b.
attribute.  This doesn’t allow you to track the order of calls between
separate mock objects, however we can use *note mock_calls: 3398. to
achieve the same effect.

Because mocks track calls to child mocks in ‘mock_calls’, and accessing
an arbitrary attribute of a mock creates a child mock, we can create our
separate mocks from a parent one.  Calls to those child mock will then
all be recorded, in order, in the ‘mock_calls’ of the parent:

     >>> manager = Mock()
     >>> mock_foo = manager.foo
     >>> mock_bar = manager.bar

     >>> mock_foo.something()
     <Mock name='mock.foo.something()' id='...'>
     >>> mock_bar.other.thing()
     <Mock name='mock.bar.other.thing()' id='...'>

     >>> manager.mock_calls
     [call.foo.something(), call.bar.other.thing()]

We can then assert about the calls, including the order, by comparing
with the ‘mock_calls’ attribute on the manager mock:

     >>> expected_calls = [call.foo.something(), call.bar.other.thing()]
     >>> manager.mock_calls == expected_calls
     True

If ‘patch’ is creating, and putting in place, your mocks then you can
attach them to a manager mock using the *note attach_mock(): 339a.
method.  After attaching calls will be recorded in ‘mock_calls’ of the
manager.

     >>> manager = MagicMock()
     >>> with patch('mymodule.Class1') as MockClass1:
     ...     with patch('mymodule.Class2') as MockClass2:
     ...         manager.attach_mock(MockClass1, 'MockClass1')
     ...         manager.attach_mock(MockClass2, 'MockClass2')
     ...         MockClass1().foo()
     ...         MockClass2().bar()
     <MagicMock name='mock.MockClass1().foo()' id='...'>
     <MagicMock name='mock.MockClass2().bar()' id='...'>
     >>> manager.mock_calls
     [call.MockClass1(),
     call.MockClass1().foo(),
     call.MockClass2(),
     call.MockClass2().bar()]

If many calls have been made, but you’re only interested in a particular
sequence of them then an alternative is to use the *note
assert_has_calls(): 3397. method.  This takes a list of calls
(constructed with the *note call: f8a. object).  If that sequence of
calls are in *note mock_calls: 3398. then the assert succeeds.

     >>> m = MagicMock()
     >>> m().foo().bar().baz()
     <MagicMock name='mock().foo().bar().baz()' id='...'>
     >>> m.one().two().three()
     <MagicMock name='mock.one().two().three()' id='...'>
     >>> calls = call.one().two().three().call_list()
     >>> m.assert_has_calls(calls)

Even though the chained call ‘m.one().two().three()’ aren’t the only
calls that have been made to the mock, the assert still succeeds.

Sometimes a mock may have several calls made to it, and you are only
interested in asserting about `some' of those calls.  You may not even
care about the order.  In this case you can pass ‘any_order=True’ to
‘assert_has_calls’:

     >>> m = MagicMock()
     >>> m(1), m.two(2, 3), m.seven(7), m.fifty('50')
     (...)
     >>> calls = [call.fifty('50'), call(1), call.seven(7)]
     >>> m.assert_has_calls(calls, any_order=True)


File: python.info,  Node: More complex argument matching,  Prev: Tracking order of calls and less verbose call assertions,  Up: Further Examples

5.26.6.27 More complex argument matching
........................................

Using the same basic concept as *note ANY: 33ce. we can implement
matchers to do more complex assertions on objects used as arguments to
mocks.

Suppose we expect some object to be passed to a mock that by default
compares equal based on object identity (which is the Python default for
user defined classes).  To use *note assert_called_with(): 100f. we
would need to pass in the exact same object.  If we are only interested
in some of the attributes of this object then we can create a matcher
that will check these attributes for us.

You can see in this example how a ’standard’ call to
‘assert_called_with’ isn’t sufficient:

     >>> class Foo:
     ...     def __init__(self, a, b):
     ...         self.a, self.b = a, b
     ...
     >>> mock = Mock(return_value=None)
     >>> mock(Foo(1, 2))
     >>> mock.assert_called_with(Foo(1, 2))
     Traceback (most recent call last):
         ...
     AssertionError: Expected: call(<__main__.Foo object at 0x...>)
     Actual call: call(<__main__.Foo object at 0x...>)

A comparison function for our ‘Foo’ class might look something like
this:

     >>> def compare(self, other):
     ...     if not type(self) == type(other):
     ...         return False
     ...     if self.a != other.a:
     ...         return False
     ...     if self.b != other.b:
     ...         return False
     ...     return True
     ...

And a matcher object that can use comparison functions like this for its
equality operation would look something like this:

     >>> class Matcher:
     ...     def __init__(self, compare, some_obj):
     ...         self.compare = compare
     ...         self.some_obj = some_obj
     ...     def __eq__(self, other):
     ...         return self.compare(self.some_obj, other)
     ...

Putting all this together:

     >>> match_foo = Matcher(compare, Foo(1, 2))
     >>> mock.assert_called_with(match_foo)

The ‘Matcher’ is instantiated with our compare function and the ‘Foo’
object we want to compare against.  In ‘assert_called_with’ the
‘Matcher’ equality method will be called, which compares the object the
mock was called with against the one we created our matcher with.  If
they match then ‘assert_called_with’ passes, and if they don’t an *note
AssertionError: 103e. is raised:

     >>> match_wrong = Matcher(compare, Foo(3, 4))
     >>> mock.assert_called_with(match_wrong)
     Traceback (most recent call last):
         ...
     AssertionError: Expected: ((<Matcher object at 0x...>,), {})
     Called with: ((<Foo object at 0x...>,), {})

With a bit of tweaking you could have the comparison function raise the
*note AssertionError: 103e. directly and provide a more useful failure
message.

As of version 1.5, the Python testing library PyHamcrest(1) provides
similar functionality, that may be useful here, in the form of its
equality matcher (hamcrest.library.integration.match_equality(2)).

   ---------- Footnotes ----------

   (1) https://pyhamcrest.readthedocs.io/

   (2) 
https://pyhamcrest.readthedocs.io/en/release-1.8/integration/#module-hamcrest.library.integration.match_equality


File: python.info,  Node: 2to3 - 自动将 Python 2 代码转为 Python 3 代码,  Next: test --- Python回归测试包,  Prev: unittest mock 上手指南,  Up: 开发工具

5.26.7 2to3 - 自动将 Python 2 代码转为 Python 3 代码
----------------------------------------------------

2to3 是一个 Python 程序，它可以用来读取 Python 2.x 版本的代码，并使用一
系列的 `修复器' 来将其转换为合法的 Python 3.x 代码。标准库中已经包含了丰
富的修复器，这足以处理绝大多数代码。不过 2to3 的支持库 *note lib2to3:
a8. 是一个很灵活通用的库，所以你也可以为 2to3 编写你自己的修复器。*note
lib2to3: a8. 也可以用在那些需要自动处理 Python 代码的应用中。

* Menu:

* 使用 2to3::
* 修复器::
* lib2to3 —— 2to3 支持库::


File: python.info,  Node: 使用 2to3,  Next: 修复器,  Up: 2to3 - 自动将 Python 2 代码转为 Python 3 代码

5.26.7.1 使用 2to3
..................

2to3 通常会作为脚本和 Python 解释器一起安装，你可以在 Python 根目录的
‘Tools/scripts’ 文件夹下找到它。

2to3 的基本调用参数是一个需要转换的文件或目录列表。对于目录，会递归地寻
找其中的 Python 源码。

这里有一个 Python 2.x 的源码文件，‘example.py’：

     def greet(name):
         print "Hello, {0}!".format(name)
     print "What's your name?"
     name = raw_input()
     greet(name)

它可以在命令行中使用 2to3 转换成 Python 3.x 版本的代码：

     $ 2to3 example.py

这个命令会打印出和源文件的区别。通过传入 ‘-w’ 参数，2to3 也可以把需要的
修改写回到原文件中（除非传入了 ‘-n’ 参数，否则会为原始文件创建一个副本）
：

     $ 2to3 -w example.py

在转换完成后，‘example.py’ 看起来像是这样：

     def greet(name):
         print("Hello, {0}!".format(name))
     print("What's your name?")
     name = input()
     greet(name)

注释和缩进都会在转换过程中保持不变。

默认情况下，2to3 会执行 *note 预定义修复器: 33f6. 的集合。使用 ‘-l’ 参数
可以列出所有可用的修复器。使用 ‘-f’ 参数可以明确指定需要使用的修复器集合
。而使用 ‘-x’ 参数则可以明确指定不使用的修复器。下面的例子会只使用
‘imports’ 和 ‘has_key’ 修复器运行：

     $ 2to3 -f imports -f has_key example.py

这个命令会执行除了 ‘apply’ 之外的所有修复器：

     $ 2to3 -x apply example.py

有一些修复器是需要 `显式指定' 的，它们默认不会执行，必须在命令行中列出才
会执行。比如下面的例子，除了默认的修复器以外，还会执行 ‘idioms’ 修复器：

     $ 2to3 -f all -f idioms example.py

注意这里使用 ‘all’ 来启用所有默认的修复器。

有些情况下 2to3 会找到源码中有一些需要修改，但是无法自动处理的代码。在这
种情况下，2to3 会在差异处下面打印一个警告信息。你应该定位到相应的代码并
对其进行修改，以使其兼容 Python 3.x。

2to3 也可以重构 doctests。使用 ‘-d’ 开启这个模式。需要注意*只有*
doctests 会被重构。这种模式下不需要文件是合法的 Python 代码。举例来说，
reST 文档中类似 doctests 的示例也可以使用这个选项进行重构。

‘-v’ 选项可以输出更多转换程序的详细信息。

由于某些 print 语句可被解读为函数调用或是语句，2to3 并不是总能读取包含
print 函数的文件。当 2to3 检测到存在 ‘from __future__ import
print_function’ 编译器指令时，会修改其内部语法将 *note print(): 88f. 解
读为函数。这一变动也可以使用 ‘-p’ 选项手动开启。使用 ‘-p’ 来为已经转换过
print 语句的代码运行修复器。

‘-o’ 或 ‘--output-dir’ 选项可以指定将转换后的文件写入其他目录中。由于这
种情况下不会覆写原始文件，所以创建副本文件毫无意义，因此也需要使用 ‘-n’
选项来禁用创建副本。

3.2.3 新版功能: 增加了 ‘-o’ 选项。

‘-W’ 或 ‘--write-unchanged-files’ 选项用来告诉 2to3 始终需要输出文件，即
使没有任何改动。这在使用 ‘-o’ 参数时十分有用，这样就可以将整个 Python 源
码包完整地转换到另一个目录。这个选项隐含了 ‘-w’ 选项，否则等于没有作用。

3.2.3 新版功能: 增加了 ‘-W’ 选项。

‘--add-suffix’ 选项接受一个字符串，用来作为后缀附加在输出文件名后面的后
面。由于写入的文件名与原始文件不同，所以没有必要创建副本，因此 ‘-n’ 选项
也是必要的。举个例子：

     $ 2to3 -n -W --add-suffix=3 example.py

这样会把转换后的文件写入 ‘example.py3’ 文件。

3.2.3 新版功能: 增加了 ‘--add-suffix’ 选项。

将整个项目从一个目录转换到另一个目录可以用这样的命令：

     $ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode


File: python.info,  Node: 修复器,  Next: lib2to3 —— 2to3 支持库,  Prev: 使用 2to3,  Up: 2to3 - 自动将 Python 2 代码转为 Python 3 代码

5.26.7.2 修复器
...............

转换代码的每一个步骤都封装在修复器中。可以使用 ‘2to3 -l’ 来列出可用的修
复器。*note 之前已经提到: 33f4.，每个修复器都可以独立地打开或是关闭。下
面会对各个修复器做更详细的描述。

 -- 2to3fixer: apply

     移除对 ‘apply()’ 的使用，举例来说，‘apply(function, *args,
     **kwargs)’ 会被转换成 ‘function(*args, **kwargs)’。

 -- 2to3fixer: asserts

     将已弃用的 *note unittest: 11c. 方法替换为正确的。

     从                                   到
                                          
     ------------------------------------------------------------------------------------
                                          
     ‘failUnlessEqual(a, b)’              *note assertEqual(a, b): bbd.
                                          
                                          
     ‘assertEquals(a, b)’                 *note assertEqual(a, b): bbd.
                                          
                                          
     ‘failIfEqual(a, b)’                  *note assertNotEqual(a, b): bbe.
                                          
                                          
     ‘assertNotEquals(a, b)’              *note assertNotEqual(a, b): bbe.
                                          
                                          
     ‘failUnless(a)’                      *note assertTrue(a): bbc.
                                          
                                          
     ‘assert_(a)’                         *note assertTrue(a): bbc.
                                          
                                          
     ‘failIf(a)’                          *note assertFalse(a): ccf.
                                          
                                          
     ‘failUnlessRaises(exc, cal)’         *note assertRaises(exc, cal): ac2.
                                          
                                          
     ‘failUnlessAlmostEqual(a, b)’        *note assertAlmostEqual(a, b): bbf.
                                          
                                          
     ‘assertAlmostEquals(a, b)’           *note assertAlmostEqual(a, b): bbf.
                                          
                                          
     ‘failIfAlmostEqual(a, b)’            *note assertNotAlmostEqual(a, b): bc0.
                                          
                                          
     ‘assertNotAlmostEquals(a, b)’        *note assertNotAlmostEqual(a, b): bc0.
                                          

 -- 2to3fixer: basestring

     将 ‘basestring’ 转换为 *note str: 339.。

 -- 2to3fixer: buffer

     将 ‘buffer’ 转换为 *note memoryview: 25d.。这个修复器是可选的，因为
     *note memoryview: 25d. API 和 ‘buffer’ 很相似，但不完全一样。

 -- 2to3fixer: dict

     修复字典迭代方法。‘dict.iteritems()’ 会转换成 *note dict.items():
     c33.，‘dict.iterkeys()’ 会转换成 *note dict.keys(): c32.，
     ‘dict.itervalues()’ 会转换成 *note dict.values(): c34.。类似的，
     ‘dict.viewitems()’，‘dict.viewkeys()’ 和 ‘dict.viewvalues()’ 会分别
     转换成 *note dict.items(): c33.，*note dict.keys(): c32. 和 *note
     dict.values(): c34.。另外也会将原有的 *note dict.items(): c33.，
     *note dict.keys(): c32. 和 *note dict.values(): c34. 方法调用用
     *note list: 263. 包装一层。

 -- 2to3fixer: except

     将 ‘except X, T’ 转换为 ‘except X as T’。

 -- 2to3fixer: exec

     将 ‘exec’ 语句转换为 *note exec(): c4c. 函数调用。

 -- 2to3fixer: execfile

     移除 ‘execfile()’ 的使用。‘execfile()’ 的实参会使用 *note open():
     4f8.，*note compile(): 1b5. 和 *note exec(): c4c. 包装。

 -- 2to3fixer: exitfunc

     将对 ‘sys.exitfunc’ 的赋值改为使用 *note atexit: c. 模块代替。

 -- 2to3fixer: filter

     将 *note filter(): c36. 函数用 *note list: 263. 包装一层。

 -- 2to3fixer: funcattrs

     修复已经重命名的函数属性。比如 ‘my_function.func_closure’ 会被转换
     为 ‘my_function.__closure__’。

 -- 2to3fixer: future

     移除 ‘from __future__ import new_feature’ 语句。

 -- 2to3fixer: getcwdu

     将 ‘os.getcwdu()’ 重命名为 *note os.getcwd(): fee.。

 -- 2to3fixer: has_key

     将 ‘dict.has_key(key)’ 转换为 ‘key in dict’。

 -- 2to3fixer: idioms

     这是一个可选的修复器，会进行多种转换，将 Python 代码变成更加常见的
     写法。类似 ‘type(x) is SomeClass’ 和 ‘type(x) == SomeClass’ 的类型
     对比会被转换成 ‘isinstance(x, SomeClass)’。‘while 1’ 转换成 ‘while
     True’。这个修复器还会在合适的地方使用 *note sorted(): 44c. 函数。举
     个例子，这样的代码块：

          L = list(some_iterable)
          L.sort()

     会被转换为：

          L = sorted(some_iterable)

 -- 2to3fixer: import

     检测 sibling imports，并将其转换成相对 import。

 -- 2to3fixer: imports

     处理标准库模块的重命名。

 -- 2to3fixer: imports2

     处理标准库中其他模块的重命名。这个修复器由于一些技术上的限制，因此
     和 *note imports: 3407. 拆分开了。

 -- 2to3fixer: input

     将 ‘input(prompt)’ 转换为 ‘eval(input(prompt))’。

 -- 2to3fixer: intern

     将 ‘intern()’ 转换为 *note sys.intern(): c76.。

 -- 2to3fixer: isinstance

     修复 *note isinstance(): 457. 函数第二个实参中重复的类型。举例来说
     ，‘isinstance(x, (int, int))’ 会转换为 ‘isinstance(x, int)’,
     ‘isinstance(x, (int, float, int))’ 会转换为 ‘isinstance(x, (int,
     float))’。

 -- 2to3fixer: itertools_imports

     移除 ‘itertools.ifilter()’，‘itertools.izip()’ 以及
     ‘itertools.imap()’ 的 import。对 ‘itertools.ifilterfalse()’ 的
     import 也会替换成 *note itertools.filterfalse(): 15fc.。

 -- 2to3fixer: itertools

     修改 ‘itertools.ifilter()’，‘itertools.izip()’ 和
     ‘itertools.imap()’ 的调用为对应的内建实现。
     ‘itertools.ifilterfalse()’ 会替换成 *note itertools.filterfalse():
     15fc.。

 -- 2to3fixer: long

     将 ‘long’ 重命名为 *note int: 185.。

 -- 2to3fixer: map

     用 *note list: 263. 包装 *note map(): c35.。同时也会将 ‘map(None,
     x)’ 替换为 ‘list(x)’。使用 ‘from future_builtins import map’ 禁用这
     个修复器。

 -- 2to3fixer: metaclass

     将老的元类语法（类体中的 ‘__metaclass__ = Meta’）替换为新的（‘class
     X(metaclass=Meta)’）。

 -- 2to3fixer: methodattrs

     修复老的方法属性名。例如 ‘meth.im_func’ 会被转换为 ‘meth.__func__’。

 -- 2to3fixer: ne

     转换老的不等语法，将 ‘<>’ 转为 ‘!=’。

 -- 2to3fixer: next

     将迭代器的 ‘next()’ 方法调用转为 *note next(): 68b. 函数。也会将
     *note next(): 68b. 方法重命名为 *note __next__(): c6c.。

 -- 2to3fixer: nonzero

     将 ‘__nonzero__()’ 转换为 *note __bool__(): c70.。

 -- 2to3fixer: numliterals

     将八进制字面量转为新的语法。

 -- 2to3fixer: operator

     将 *note operator: c3. 模块中的许多方法调用转为其他的等效函数调用。
     如果有需要，会添加适当的 ‘import’ 语句，比如 ‘import
     collections.abc’。有以下转换映射：

     从                                     到
                                            
     -----------------------------------------------------------------------------------------
                                            
     ‘operator.isCallable(obj)’             ‘callable(obj)’
                                            
                                            
     ‘operator.sequenceIncludes(obj)’       ‘operator.contains(obj)’
                                            
                                            
     ‘operator.isSequenceType(obj)’         ‘isinstance(obj, collections.abc.Sequence)’
                                            
                                            
     ‘operator.isMappingType(obj)’          ‘isinstance(obj, collections.abc.Mapping)’
                                            
                                            
     ‘operator.isNumberType(obj)’           ‘isinstance(obj, numbers.Number)’
                                            
                                            
     ‘operator.repeat(obj, n)’              ‘operator.mul(obj, n)’
                                            
                                            
     ‘operator.irepeat(obj, n)’             ‘operator.imul(obj, n)’
                                            

 -- 2to3fixer: paren

     在列表生成式中增加必须的括号。例如将 ‘[x for x in 1, 2]’ 转换为 ‘[x
     for x in (1, 2)]’。

 -- 2to3fixer: print

     将 ‘print’ 语句转换为 *note print(): 88f. 函数。

 -- 2to3fixer: raise

     将 ‘raise E, V’ 转换为 ‘raise E(V)’，将 ‘raise E, V, T’ 转换为
     ‘raise E(V).with_traceback(T)’。如果 ‘E’ 是元组，这样的转换是不正确
     的，因为用元组代替异常的做法在 3.0 中已经移除了。

 -- 2to3fixer: raw_input

     将 ‘raw_input()’ 转换为 *note input(): c73.。

 -- 2to3fixer: reduce

     将 ‘reduce()’ 转换为 *note functools.reduce(): c77.。

 -- 2to3fixer: reload

     将 ‘reload()’ 转换为 *note importlib.reload(): 3a1.。

 -- 2to3fixer: renames

     将 ‘sys.maxint’ 转换为 *note sys.maxsize: b4b.。

 -- 2to3fixer: repr

     将反引号 repr 表达式替换为 *note repr(): 7d5. 函数。

 -- 2to3fixer: set_literal

     将 *note set: b77. 构造函数替换为 set literals 写法。这个修复器是可
     选的。

 -- 2to3fixer: standarderror

     将 ‘StandardError’ 重命名为 *note Exception: 1aa.。

 -- 2to3fixer: sys_exc

     将弃用的 ‘sys.exc_value’，‘sys.exc_type’，‘sys.exc_traceback’ 替换
     为 *note sys.exc_info(): c67. 的用法。

 -- 2to3fixer: throw

     修复生成器的 ‘throw()’ 方法的 API 变更。

 -- 2to3fixer: tuple_params

     移除隐式的元组参数解包。这个修复器会插入临时变量。

 -- 2to3fixer: types

     修复 *note type: 611. 模块中一些成员的移除引起的代码问题。

 -- 2to3fixer: unicode

     将 ‘unicode’ 重命名为 *note str: 339.。

 -- 2to3fixer: urllib

     将 *note urllib: 11e. 和 ‘urllib2’ 重命名为 *note urllib: 11e. 包。

 -- 2to3fixer: ws_comma

     移除逗号分隔的元素之间多余的空白。这个修复器是可选的。

 -- 2to3fixer: xrange

     将 ‘xrange()’ 重命名为 *note range(): 9c6.，并用 *note list: 263. 包
     装原有的 *note range(): 9c6.。

 -- 2to3fixer: xreadlines

     将 ‘for x in file.xreadlines()’ 转换为 ‘for x in file’。

 -- 2to3fixer: zip

     用 *note list: 263. 包装 *note zip(): c3a.。如果使用了 ‘from
     future_builtins import zip’ 的话会禁用。


File: python.info,  Node: lib2to3 —— 2to3 支持库,  Prev: 修复器,  Up: 2to3 - 自动将 Python 2 代码转为 Python 3 代码

5.26.7.3 ‘lib2to3’ —— 2to3 支持库
.................................

`源代码：' Lib/lib2to3/(1)

__________________________________________________________________

     注解: *note lib2to3: a8. API 并不稳定，并可能在未来大幅修改。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/lib2to3/


File: python.info,  Node: test --- Python回归测试包,  Next: test support --- Utilities for the Python test suite,  Prev: 2to3 - 自动将 Python 2 代码转为 Python 3 代码,  Up: 开发工具

5.26.8 ‘test’ — Python回归测试包
--------------------------------

     注解: The *note test: 106. package is meant for internal use by
     Python only.  It is documented for the benefit of the core
     developers of Python.  Any use of this package outside of Python’s
     standard library is discouraged as code mentioned here can change
     or be removed without notice between releases of Python.

__________________________________________________________________

The *note test: 106. package contains all regression tests for Python as
well as the modules *note test.support: 107. and ‘test.regrtest’.  *note
test.support: 107. is used to enhance your tests while ‘test.regrtest’
drives the testing suite.

Each module in the *note test: 106. package whose name starts with
‘test_’ is a testing suite for a specific module or feature.  All new
tests should be written using the *note unittest: 11c. or *note doctest:
67. module.  Some older tests are written using a "traditional" testing
style that compares output printed to ‘sys.stdout’; this style of test
is considered deprecated.

参见
....

模块 *note unittest: 11c.

     编写 PyUnit 回归测试.

*note doctest: 67. — 文档测试模块

     Tests embedded in documentation strings.

* Menu:

* Writing Unit Tests for the test package::
* Running tests using the command-line interface::


File: python.info,  Node: Writing Unit Tests for the test package,  Next: Running tests using the command-line interface,  Up: test --- Python回归测试包

5.26.8.1 Writing Unit Tests for the ‘test’ package
..................................................

It is preferred that tests that use the *note unittest: 11c. module
follow a few guidelines.  One is to name the test module by starting it
with ‘test_’ and end it with the name of the module being tested.  The
test methods in the test module should start with ‘test_’ and end with a
description of what the method is testing.  This is needed so that the
methods are recognized by the test driver as test methods.  Also, no
documentation string for the method should be included.  A comment (such
as ‘# Tests function returns only True or False’) should be used to
provide documentation for test methods.  This is done because
documentation strings get printed out if they exist and thus what test
is being run is not stated.

A basic boilerplate is often used:

     import unittest
     from test import support

     class MyTestCase1(unittest.TestCase):

         # Only use setUp() and tearDown() if necessary

         def setUp(self):
             ... code to execute in preparation for tests ...

         def tearDown(self):
             ... code to execute to clean up after tests ...

         def test_feature_one(self):
             # Test feature one.
             ... testing code ...

         def test_feature_two(self):
             # Test feature two.
             ... testing code ...

         ... more test methods ...

     class MyTestCase2(unittest.TestCase):
         ... same structure as MyTestCase1 ...

     ... more test classes ...

     if __name__ == '__main__':
         unittest.main()

This code pattern allows the testing suite to be run by ‘test.regrtest’,
on its own as a script that supports the *note unittest: 11c. CLI, or
via the ‘python -m unittest’ CLI.

The goal for regression testing is to try to break code.  This leads to
a few guidelines to be followed:

   * The testing suite should exercise all classes, functions, and
     constants.  This includes not just the external API that is to be
     presented to the outside world but also "private" code.

   * Whitebox testing (examining the code being tested when the tests
     are being written) is preferred.  Blackbox testing (testing only
     the published user interface) is not complete enough to make sure
     all boundary and edge cases are tested.

   * Make sure all possible values are tested including invalid ones.
     This makes sure that not only all valid values are acceptable but
     also that improper values are handled correctly.

   * Exhaust as many code paths as possible.  Test where branching
     occurs and thus tailor input to make sure as many different paths
     through the code are taken.

   * Add an explicit test for any bugs discovered for the tested code.
     This will make sure that the error does not crop up again if the
     code is changed in the future.

   * Make sure to clean up after your tests (such as close and remove
     all temporary files).

   * If a test is dependent on a specific condition of the operating
     system then verify the condition already exists before attempting
     the test.

   * Import as few modules as possible and do it as soon as possible.
     This minimizes external dependencies of tests and also minimizes
     possible anomalous behavior from side-effects of importing a
     module.

   * Try to maximize code reuse.  On occasion, tests will vary by
     something as small as what type of input is used.  Minimize code
     duplication by subclassing a basic test class with a class that
     specifies the input:

          class TestFuncAcceptsSequencesMixin:

              func = mySuperWhammyFunction

              def test_func(self):
                  self.func(self.arg)

          class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
              arg = [1, 2, 3]

          class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
              arg = 'abc'

          class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
              arg = (1, 2, 3)

     When using this pattern, remember that all classes that inherit
     from *note unittest.TestCase: 907. are run as tests.  The ‘Mixin’
     class in the example above does not have any data and so can’t be
     run by itself, thus it does not inherit from *note
     unittest.TestCase: 907.

参见
....

Test Driven Development

     A book by Kent Beck on writing tests before code.


File: python.info,  Node: Running tests using the command-line interface,  Prev: Writing Unit Tests for the test package,  Up: test --- Python回归测试包

5.26.8.2 Running tests using the command-line interface
.......................................................

The *note test: 106. package can be run as a script to drive Python’s
regression test suite, thanks to the *note -m: 340. option: ‘python -m
test’.  Under the hood, it uses ‘test.regrtest’; the call ‘python -m
test.regrtest’ used in previous Python versions still works.  Running
the script by itself automatically starts running all regression tests
in the *note test: 106. package.  It does this by finding all modules in
the package whose name starts with ‘test_’, importing them, and
executing the function ‘test_main()’ if present or loading the tests via
unittest.TestLoader.loadTestsFromModule if ‘test_main’ does not exist.
The names of tests to execute may also be passed to the script.
Specifying a single regression test (‘python -m test test_spam’) will
minimize output and only print whether the test passed or failed.

Running *note test: 106. directly allows what resources are available
for tests to use to be set.  You do this by using the ‘-u’ command-line
option.  Specifying ‘all’ as the value for the ‘-u’ option enables all
possible resources: ‘python -m test -uall’.  If all but one resource is
desired (a more common case), a comma-separated list of resources that
are not desired may be listed after ‘all’.  The command ‘python -m test
-uall,-audio,-largefile’ will run *note test: 106. with all resources
except the ‘audio’ and ‘largefile’ resources.  For a list of all
resources and more command-line options, run ‘python -m test -h’.

Some other ways to execute the regression tests depend on what platform
the tests are being executed on.  On Unix, you can run ‘make test’ at
the top-level directory where Python was built.  On Windows, executing
‘rt.bat’ from your ‘PCbuild’ directory will run all regression tests.


File: python.info,  Node: test support --- Utilities for the Python test suite,  Next: test support script_helper --- Utilities for the Python execution tests,  Prev: test --- Python回归测试包,  Up: 开发工具

5.26.9 ‘test.support’ — Utilities for the Python test suite
-----------------------------------------------------------

The *note test.support: 107. module provides support for Python’s
regression test suite.

     注解: *note test.support: 107. is not a public module.  It is
     documented here to help Python developers write tests.  The API of
     this module is subject to change without backwards compatibility
     concerns between releases.

This module defines the following exceptions:

 -- 例外: test.support.TestFailed

     Exception to be raised when a test fails.  This is deprecated in
     favor of *note unittest: 11c.-based tests and *note
     unittest.TestCase: 907.’s assertion methods.

 -- 例外: test.support.ResourceDenied

     Subclass of *note unittest.SkipTest: 90b.  Raised when a resource
     (such as a network connection) is not available.  Raised by the
     *note requires(): 3433. function.

The *note test.support: 107. module defines the following constants:

 -- 数据: test.support.verbose

     ‘True’ when verbose output is enabled.  Should be checked when more
     detailed information is desired about a running test.  `verbose' is
     set by ‘test.regrtest’.

 -- 数据: test.support.is_jython

     ‘True’ if the running interpreter is Jython.

 -- 数据: test.support.is_android

     ‘True’ if the system is Android.

 -- 数据: test.support.unix_shell

     Path for shell if not on Windows; otherwise ‘None’.

 -- 数据: test.support.FS_NONASCII

     A non-ASCII character encodable by *note os.fsencode(): 4f7.

 -- 数据: test.support.TESTFN

     Set to a name that is safe to use as the name of a temporary file.
     Any temporary file that is created should be closed and unlinked
     (removed).

 -- 数据: test.support.TESTFN_UNICODE

     Set to a non-ASCII name for a temporary file.

 -- 数据: test.support.TESTFN_ENCODING

     Set to *note sys.getfilesystemencoding(): 4fe.

 -- 数据: test.support.TESTFN_UNENCODABLE

     Set to a filename (str type) that should not be able to be encoded
     by file system encoding in strict mode.  It may be ‘None’ if it’s
     not possible to generate such a filename.

 -- 数据: test.support.TESTFN_UNDECODABLE

     Set to a filename (bytes type) that should not be able to be
     decoded by file system encoding in strict mode.  It may be ‘None’
     if it’s not possible to generate such a filename.

 -- 数据: test.support.TESTFN_NONASCII

     Set to a filename containing the *note FS_NONASCII: 3438.
     character.

 -- 数据: test.support.IPV6_ENABLED

     Set to ‘True’ if IPV6 is enabled on this host, ‘False’ otherwise.

 -- 数据: test.support.SAVEDCWD

     Set to *note os.getcwd(): fee.

 -- 数据: test.support.PGO

     Set when tests can be skipped when they are not useful for PGO.

 -- 数据: test.support.PIPE_MAX_SIZE

     A constant that is likely larger than the underlying OS pipe buffer
     size, to make writes blocking.

 -- 数据: test.support.SOCK_MAX_SIZE

     A constant that is likely larger than the underlying OS socket
     buffer size, to make writes blocking.

 -- 数据: test.support.TEST_SUPPORT_DIR

     Set to the top level directory that contains *note test.support:
     107.

 -- 数据: test.support.TEST_HOME_DIR

     Set to the top level directory for the test package.

 -- 数据: test.support.TEST_DATA_DIR

     Set to the ‘data’ directory within the test package.

 -- 数据: test.support.MAX_Py_ssize_t

     Set to *note sys.maxsize: b4b. for big memory tests.

 -- 数据: test.support.max_memuse

     Set by *note set_memlimit(): 3449. as the memory limit for big
     memory tests.  Limited by *note MAX_Py_ssize_t: 3447.

 -- 数据: test.support.real_max_memuse

     Set by *note set_memlimit(): 3449. as the memory limit for big
     memory tests.  Not limited by *note MAX_Py_ssize_t: 3447.

 -- 数据: test.support.MISSING_C_DOCSTRINGS

     Return ‘True’ if running on CPython, not on Windows, and
     configuration not set with ‘WITH_DOC_STRINGS’.

 -- 数据: test.support.HAVE_DOCSTRINGS

     Check for presence of docstrings.

 -- 数据: test.support.TEST_HTTP_URL

     Define the URL of a dedicated HTTP server for the network tests.

 -- 数据: test.support.ALWAYS_EQ

     Object that is equal to anything.  Used to test mixed type
     comparison.

 -- 数据: test.support.LARGEST

     Object that is greater than anything (except itself).  Used to test
     mixed type comparison.

 -- 数据: test.support.SMALLEST

     Object that is less than anything (except itself).  Used to test
     mixed type comparison.

The *note test.support: 107. module defines the following functions:

 -- 函数: test.support.forget (module_name)

     Remove the module named `module_name' from ‘sys.modules’ and delete
     any byte-compiled files of the module.

 -- 函数: test.support.unload (name)

     Delete `name' from ‘sys.modules’.

 -- 函数: test.support.unlink (filename)

     Call *note os.unlink(): a44. on `filename'.  On Windows platforms,
     this is wrapped with a wait loop that checks for the existence fo
     the file.

 -- 函数: test.support.rmdir (filename)

     Call *note os.rmdir(): a42. on `filename'.  On Windows platforms,
     this is wrapped with a wait loop that checks for the existence of
     the file.

 -- 函数: test.support.rmtree (path)

     Call *note shutil.rmtree(): 21d. on `path' or call *note
     os.lstat(): 1f3. and *note os.rmdir(): a42. to remove a path and
     its contents.  On Windows platforms, this is wrapped with a wait
     loop that checks for the existence of the files.

 -- 函数: test.support.make_legacy_pyc (source)

     Move a PEP 3147(1)/ PEP 488(2) pyc file to its legacy pyc location
     and return the file system path to the legacy pyc file.  The
     `source' value is the file system path to the source file.  It does
     not need to exist, however the PEP 3147/488 pyc file must exist.

 -- 函数: test.support.is_resource_enabled (resource)

     Return ‘True’ if `resource' is enabled and available.  The list of
     available resources is only set when ‘test.regrtest’ is executing
     the tests.

 -- 函数: test.support.python_is_optimized ()

     Return ‘True’ if Python was not built with ‘-O0’ or ‘-Og’.

 -- 函数: test.support.with_pymalloc ()

     Return ‘_testcapi.WITH_PYMALLOC’.

 -- 函数: test.support.requires (resource, msg=None)

     Raise *note ResourceDenied: 3432. if `resource' is not available.
     `msg' is the argument to *note ResourceDenied: 3432. if it is
     raised.  Always returns ‘True’ if called by a function whose
     ‘__name__’ is ‘'__main__'’.  Used when tests are executed by
     ‘test.regrtest’.

 -- 函数: test.support.system_must_validate_cert (f)

     Raise *note unittest.SkipTest: 90b. on TLS certification validation
     failures.

 -- 函数: test.support.sortdict (dict)

     Return a repr of `dict' with keys sorted.

 -- 函数: test.support.findfile (filename, subdir=None)

     Return the path to the file named `filename'.  If no match is found
     `filename' is returned.  This does not equal a failure since it
     could be the path to the file.

     Setting `subdir' indicates a relative path to use to find the file
     rather than looking directly in the path directories.

 -- 函数: test.support.create_empty_file (filename)

     Create an empty file with `filename'.  If it already exists,
     truncate it.

 -- 函数: test.support.fd_count ()

     Count the number of open file descriptors.

 -- 函数: test.support.match_test (test)

     Match `test' to patterns set in *note set_match_tests(): 3460.

 -- 函数: test.support.set_match_tests (patterns)

     Define match test with regular expression `patterns'.

 -- 函数: test.support.run_unittest (*classes)

     Execute *note unittest.TestCase: 907. subclasses passed to the
     function.  The function scans the classes for methods starting with
     the prefix ‘test_’ and executes the tests individually.

     It is also legal to pass strings as parameters; these should be
     keys in ‘sys.modules’.  Each associated module will be scanned by
     ‘unittest.TestLoader.loadTestsFromModule()’.  This is usually seen
     in the following ‘test_main()’ function:

          def test_main():
              support.run_unittest(__name__)

     This will run all tests defined in the named module.

 -- 函数: test.support.run_doctest (module, verbosity=None,
          optionflags=0)

     Run *note doctest.testmod(): dd8. on the given `module'.  Return
     ‘(failure_count, test_count)’.

     If `verbosity' is ‘None’, *note doctest.testmod(): dd8. is run with
     verbosity set to *note verbose: 3434.  Otherwise, it is run with
     verbosity set to ‘None’.  `optionflags' is passed as ‘optionflags’
     to *note doctest.testmod(): dd8.

 -- 函数: test.support.setswitchinterval (interval)

     Set the *note sys.setswitchinterval(): bf3. to the given
     `interval'.  Defines a minimum interval for Android systems to
     prevent the system from hanging.

 -- 函数: test.support.check_impl_detail (**guards)

     Use this check to guard CPython’s implementation-specific tests or
     to run them only on the implementations guarded by the arguments:

          check_impl_detail()               # Only on CPython (default).
          check_impl_detail(jython=True)    # Only on Jython.
          check_impl_detail(cpython=False)  # Everywhere except CPython.

 -- 函数: test.support.check_warnings (*filters, quiet=True)

     A convenience wrapper for *note warnings.catch_warnings(): 3465.
     that makes it easier to test that a warning was correctly raised.
     It is approximately equivalent to calling
     ‘warnings.catch_warnings(record=True)’ with *note
     warnings.simplefilter(): 3466. set to ‘always’ and with the option
     to automatically validate the results that are recorded.

     ‘check_warnings’ accepts 2-tuples of the form ‘("message regexp",
     WarningCategory)’ as positional arguments.  If one or more
     `filters' are provided, or if the optional keyword argument `quiet'
     is ‘False’, it checks to make sure the warnings are as expected:
     each specified filter must match at least one of the warnings
     raised by the enclosed code or the test fails, and if any warnings
     are raised that do not match any of the specified filters the test
     fails.  To disable the first of these checks, set `quiet' to
     ‘True’.

     If no arguments are specified, it defaults to:

          check_warnings(("", Warning), quiet=True)

     In this case all warnings are caught and no errors are raised.

     On entry to the context manager, a ‘WarningRecorder’ instance is
     returned.  The underlying warnings list from *note
     catch_warnings(): 3465. is available via the recorder object’s
     *note warnings: 127. attribute.  As a convenience, the attributes
     of the object representing the most recent warning can also be
     accessed directly through the recorder object (see example below).
     If no warning has been raised, then any of the attributes that
     would otherwise be expected on an object representing a warning
     will return ‘None’.

     The recorder object also has a ‘reset()’ method, which clears the
     warnings list.

     The context manager is designed to be used like this:

          with check_warnings(("assertion is always true", SyntaxWarning),
                              ("", UserWarning)):
              exec('assert(False, "Hey!")')
              warnings.warn(UserWarning("Hide me!"))

     In this case if either warning was not raised, or some other
     warning was raised, *note check_warnings(): 3464. would raise an
     error.

     When a test needs to look more deeply into the warnings, rather
     than just checking whether or not they occurred, code like this can
     be used:

          with check_warnings(quiet=True) as w:
              warnings.warn("foo")
              assert str(w.args[0]) == "foo"
              warnings.warn("bar")
              assert str(w.args[0]) == "bar"
              assert str(w.warnings[0].args[0]) == "foo"
              assert str(w.warnings[1].args[0]) == "bar"
              w.reset()
              assert len(w.warnings) == 0

     Here all warnings will be caught, and the test code tests the
     captured warnings directly.

     在 3.2 版更改: New optional arguments `filters' and `quiet'.

 -- 函数: test.support.check_no_resource_warning (testcase)

     Context manager to check that no *note ResourceWarning: 4d8. was
     raised.  You must remove the object which may emit *note
     ResourceWarning: 4d8. before the end of the context manager.

 -- 函数: test.support.set_memlimit (limit)

     Set the values for *note max_memuse: 3448. and *note
     real_max_memuse: 344a. for big memory tests.

 -- 函数: test.support.record_original_stdout (stdout)

     Store the value from `stdout'.  It is meant to hold the stdout at
     the time the regrtest began.

 -- 函数: test.support.get_original_stdout ()

     Return the original stdout set by *note record_original_stdout():
     3468. or ‘sys.stdout’ if it’s not set.

 -- 函数: test.support.strip_python_strerr (stderr)

     Strip the `stderr' of a Python process from potential debug output
     emitted by the interpreter.  This will typically be run on the
     result of *note subprocess.Popen.communicate(): 2462.

 -- 函数: test.support.args_from_interpreter_flags ()

     Return a list of command line arguments reproducing the current
     settings in ‘sys.flags’ and ‘sys.warnoptions’.

 -- 函数: test.support.optim_args_from_interpreter_flags ()

     Return a list of command line arguments reproducing the current
     optimization settings in ‘sys.flags’.

 -- 函数: test.support.captured_stdin ()
 -- 函数: test.support.captured_stdout ()
 -- 函数: test.support.captured_stderr ()

     A context managers that temporarily replaces the named stream with
     *note io.StringIO: 836. object.

     Example use with output streams:

          with captured_stdout() as stdout, captured_stderr() as stderr:
              print("hello")
              print("error", file=sys.stderr)
          assert stdout.getvalue() == "hello\n"
          assert stderr.getvalue() == "error\n"

     Example use with input stream:

          with captured_stdin() as stdin:
              stdin.write('hello\n')
              stdin.seek(0)
              # call test code that consumes from sys.stdin
              captured = input()
          self.assertEqual(captured, "hello")

 -- 函数: test.support.temp_dir (path=None, quiet=False)

     A context manager that creates a temporary directory at `path' and
     yields the directory.

     If `path' is ‘None’, the temporary directory is created using *note
     tempfile.mkdtemp(): 1c79.  If `quiet' is ‘False’, the context
     manager raises an exception on error.  Otherwise, if `path' is
     specified and cannot be created, only a warning is issued.

 -- 函数: test.support.change_cwd (path, quiet=False)

     A context manager that temporarily changes the current working
     directory to `path' and yields the directory.

     If `quiet' is ‘False’, the context manager raises an exception on
     error.  Otherwise, it issues only a warning and keeps the current
     working directory the same.

 -- 函数: test.support.temp_cwd (name='tempcwd', quiet=False)

     A context manager that temporarily creates a new directory and
     changes the current working directory (CWD).

     The context manager creates a temporary directory in the current
     directory with name `name' before temporarily changing the current
     working directory.  If `name' is ‘None’, the temporary directory is
     created using *note tempfile.mkdtemp(): 1c79.

     If `quiet' is ‘False’ and it is not possible to create or change
     the CWD, an error is raised.  Otherwise, only a warning is raised
     and the original CWD is used.

 -- 函数: test.support.temp_umask (umask)

     A context manager that temporarily sets the process umask.

 -- 函数: test.support.transient_internet (resource_name, *,
          timeout=30.0, errnos=())

     A context manager that raises *note ResourceDenied: 3432. when
     various issues with the internet connection manifest themselves as
     exceptions.

 -- 函数: test.support.disable_faulthandler ()

     A context manager that replaces ‘sys.stderr’ with ‘sys.__stderr__’.

 -- 函数: test.support.gc_collect ()

     Force as many objects as possible to be collected.  This is needed
     because timely deallocation is not guaranteed by the garbage
     collector.  This means that ‘__del__’ methods may be called later
     than expected and weakrefs may remain alive for longer than
     expected.

 -- 函数: test.support.disable_gc ()

     A context manager that disables the garbage collector upon entry
     and reenables it upon exit.

 -- 函数: test.support.swap_attr (obj, attr, new_val)

     Context manager to swap out an attribute with a new object.

     用法:

          with swap_attr(obj, "attr", 5):
              ...

     This will set ‘obj.attr’ to 5 for the duration of the ‘with’ block,
     restoring the old value at the end of the block.  If ‘attr’ doesn’t
     exist on ‘obj’, it will be created and then deleted at the end of
     the block.

     The old value (or ‘None’ if it doesn’t exist) will be assigned to
     the target of the "as" clause, if there is one.

 -- 函数: test.support.swap_item (obj, attr, new_val)

     Context manager to swap out an item with a new object.

     用法:

          with swap_item(obj, "item", 5):
              ...

     This will set ‘obj["item"]’ to 5 for the duration of the ‘with’
     block, restoring the old value at the end of the block.  If ‘item’
     doesn’t exist on ‘obj’, it will be created and then deleted at the
     end of the block.

     The old value (or ‘None’ if it doesn’t exist) will be assigned to
     the target of the "as" clause, if there is one.

 -- 函数: test.support.wait_threads_exit (timeout=60.0)

     Context manager to wait until all threads created in the ‘with’
     statement exit.

 -- 函数: test.support.start_threads (threads, unlock=None)

     Context manager to start `threads'.  It attempts to join the
     threads upon exit.

 -- 函数: test.support.calcobjsize (fmt)

     Return *note struct.calcsize(): 1820. for ‘nP{fmt}0n’ or, if
     ‘gettotalrefcount’ exists, ‘2PnP{fmt}0P’.

 -- 函数: test.support.calcvobjsize (fmt)

     Return *note struct.calcsize(): 1820. for ‘nPn{fmt}0n’ or, if
     ‘gettotalrefcount’ exists, ‘2PnPn{fmt}0P’.

 -- 函数: test.support.checksizeof (test, o, size)

     For testcase `test', assert that the ‘sys.getsizeof’ for `o' plus
     the GC header size equals `size'.

 -- 函数: test.support.can_symlink ()

     Return ‘True’ if the OS supports symbolic links, ‘False’ otherwise.

 -- 函数: test.support.can_xattr ()

     Return ‘True’ if the OS supports xattr, ‘False’ otherwise.

 -- 函数: @test.support.skip_unless_symlink

     A decorator for running tests that require support for symbolic
     links.

 -- 函数: @test.support.skip_unless_xattr

     A decorator for running tests that require support for xattr.

 -- 函数: @test.support.skip_unless_bind_unix_socket

     A decorator for running tests that require a functional bind() for
     Unix sockets.

 -- 函数: @test.support.anticipate_failure (condition)

     A decorator to conditionally mark tests with *note
     unittest.expectedFailure(): 333f.  Any use of this decorator should
     have an associated comment identifying the relevant tracker issue.

 -- 函数: @test.support.run_with_locale (catstr, *locales)

     A decorator for running a function in a different locale, correctly
     resetting it after it has finished.  `catstr' is the locale
     category as a string (for example ‘"LC_ALL"’).  The `locales'
     passed will be tried sequentially, and the first valid locale will
     be used.

 -- 函数: @test.support.run_with_tz (tz)

     A decorator for running a function in a specific timezone,
     correctly resetting it after it has finished.

 -- 函数: @test.support.requires_freebsd_version (*min_version)

     Decorator for the minimum version when running test on FreeBSD. If
     the FreeBSD version is less than the minimum, raise *note
     unittest.SkipTest: 90b.

 -- 函数: @test.support.requires_linux_version (*min_version)

     Decorator for the minimum version when running test on Linux.  If
     the Linux version is less than the minimum, raise *note
     unittest.SkipTest: 90b.

 -- 函数: @test.support.requires_mac_version (*min_version)

     Decorator for the minimum version when running test on Mac OS X. If
     the MAC OS X version is less than the minimum, raise *note
     unittest.SkipTest: 90b.

 -- 函数: @test.support.requires_IEEE_754

     Decorator for skipping tests on non-IEEE 754 platforms.

 -- 函数: @test.support.requires_zlib

     Decorator for skipping tests if *note zlib: 145. doesn’t exist.

 -- 函数: @test.support.requires_gzip

     Decorator for skipping tests if *note gzip: 8c. doesn’t exist.

 -- 函数: @test.support.requires_bz2

     Decorator for skipping tests if *note bz2: 14. doesn’t exist.

 -- 函数: @test.support.requires_lzma

     Decorator for skipping tests if *note lzma: ae. doesn’t exist.

 -- 函数: @test.support.requires_resource (resource)

     Decorator for skipping tests if `resource' is not available.

 -- 函数: @test.support.requires_docstrings

     Decorator for only running the test if *note HAVE_DOCSTRINGS: 344c.

 -- 函数: @test.support.cpython_only (test)

     Decorator for tests only applicable to CPython.

 -- 函数: @test.support.impl_detail (msg=None, **guards)

     Decorator for invoking *note check_impl_detail(): 3463. on
     `guards'.  If that returns ‘False’, then uses `msg' as the reason
     for skipping the test.

 -- 函数: @test.support.no_tracing (func)

     Decorator to temporarily turn off tracing for the duration of the
     test.

 -- 函数: @test.support.refcount_test (test)

     Decorator for tests which involve reference counting.  The
     decorator does not run the test if it is not run by CPython.  Any
     trace function is unset for the duration of the test to prevent
     unexpected refcounts caused by the trace function.

 -- 函数: @test.support.reap_threads (func)

     Decorator to ensure the threads are cleaned up even if the test
     fails.

 -- 函数: @test.support.bigmemtest (size, memuse, dry_run=True)

     Decorator for bigmem tests.

     `size' is a requested size for the test (in arbitrary,
     test-interpreted units.)  `memuse' is the number of bytes per unit
     for the test, or a good estimate of it.  For example, a test that
     needs two byte buffers, of 4 GiB each, could be decorated with
     ‘@bigmemtest(size=_4G, memuse=2)’.

     The `size' argument is normally passed to the decorated test method
     as an extra argument.  If `dry_run' is ‘True’, the value passed to
     the test method may be less than the requested value.  If `dry_run'
     is ‘False’, it means the test doesn’t support dummy runs when ‘-M’
     is not specified.

 -- 函数: @test.support.bigaddrspacetest (f)

     Decorator for tests that fill the address space.  `f' is the
     function to wrap.

 -- 函数: test.support.make_bad_fd ()

     Create an invalid file descriptor by opening and closing a
     temporary file, and returning its descriptor.

 -- 函数: test.support.check_syntax_error (testcase, statement,
          errtext='', *, lineno=None, offset=None)

     Test for syntax errors in `statement' by attempting to compile
     `statement'.  `testcase' is the *note unittest: 11c. instance for
     the test.  `errtext' is the regular expression which should match
     the string representation of the raised *note SyntaxError: 460.  If
     `lineno' is not ‘None’, compares to the line of the exception.  If
     `offset' is not ‘None’, compares to the offset of the exception.

 -- 函数: test.support.check_syntax_warning (testcase, statement,
          errtext='', *, lineno=1, offset=None)

     Test for syntax warning in `statement' by attempting to compile
     `statement'.  Test also that the *note SyntaxWarning: 192. is
     emitted only once, and that it will be converted to a *note
     SyntaxError: 460. when turned into error.  `testcase' is the *note
     unittest: 11c. instance for the test.  `errtext' is the regular
     expression which should match the string representation of the
     emitted *note SyntaxWarning: 192. and raised *note SyntaxError:
     460.  If `lineno' is not ‘None’, compares to the line of the
     warning and exception.  If `offset' is not ‘None’, compares to the
     offset of the exception.

     3.8 新版功能.

 -- 函数: test.support.open_urlresource (url, *args, **kw)

     Open `url'.  If open fails, raises *note TestFailed: 3431.

 -- 函数: test.support.import_module (name, deprecated=False, *,
          required_on())

     This function imports and returns the named module.  Unlike a
     normal import, this function raises *note unittest.SkipTest: 90b.
     if the module cannot be imported.

     Module and package deprecation messages are suppressed during this
     import if `deprecated' is ‘True’.  If a module is required on a
     platform but optional for others, set `required_on' to an iterable
     of platform prefixes which will be compared against *note
     sys.platform: 2b2.

     3.1 新版功能.

 -- 函数: test.support.import_fresh_module (name, fresh=(), blocked=(),
          deprecated=False)

     This function imports and returns a fresh copy of the named Python
     module by removing the named module from ‘sys.modules’ before doing
     the import.  Note that unlike ‘reload()’, the original module is
     not affected by this operation.

     `fresh' is an iterable of additional module names that are also
     removed from the ‘sys.modules’ cache before doing the import.

     `blocked' is an iterable of module names that are replaced with
     ‘None’ in the module cache during the import to ensure that
     attempts to import them raise *note ImportError: 33d.

     The named module and any modules named in the `fresh' and `blocked'
     parameters are saved before starting the import and then reinserted
     into ‘sys.modules’ when the fresh import is complete.

     Module and package deprecation messages are suppressed during this
     import if `deprecated' is ‘True’.

     This function will raise *note ImportError: 33d. if the named
     module cannot be imported.

     Example use:

          # Get copies of the warnings module for testing without affecting the
          # version being used by the rest of the test suite. One copy uses the
          # C implementation, the other is forced to use the pure Python fallback
          # implementation
          py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
          c_warnings = import_fresh_module('warnings', fresh=['_warnings'])

     3.1 新版功能.

 -- 函数: test.support.modules_setup ()

     Return a copy of *note sys.modules: f36.

 -- 函数: test.support.modules_cleanup (oldmodules)

     Remove modules except for `oldmodules' and ‘encodings’ in order to
     preserve internal cache.

 -- 函数: test.support.threading_setup ()

     Return current thread count and copy of dangling threads.

 -- 函数: test.support.threading_cleanup (*original_values)

     Cleanup up threads not specified in `original_values'.  Designed to
     emit a warning if a test leaves running threads in the background.

 -- 函数: test.support.join_thread (thread, timeout=30.0)

     Join a `thread' within `timeout'.  Raise an *note AssertionError:
     103e. if thread is still alive after `timeout' seconds.

 -- 函数: test.support.reap_children ()

     Use this at the end of ‘test_main’ whenever sub-processes are
     started.  This will help ensure that no extra children (zombies)
     stick around to hog resources and create problems when looking for
     refleaks.

 -- 函数: test.support.get_attribute (obj, name)

     Get an attribute, raising *note unittest.SkipTest: 90b. if *note
     AttributeError: 3a3. is raised.

 -- 函数: test.support.bind_port (sock, host=HOST)

     Bind the socket to a free port and return the port number.  Relies
     on ephemeral ports in order to ensure we are using an unbound port.
     This is important as many tests may be running simultaneously,
     especially in a buildbot environment.  This method raises an
     exception if the ‘sock.family’ is *note AF_INET: 25b8. and
     ‘sock.type’ is *note SOCK_STREAM: c92, and the socket has
     ‘SO_REUSEADDR’ or ‘SO_REUSEPORT’ set on it.  Tests should never set
     these socket options for TCP/IP sockets.  The only case for setting
     these options is testing multicasting via multiple UDP sockets.

     Additionally, if the ‘SO_EXCLUSIVEADDRUSE’ socket option is
     available (i.e.  on Windows), it will be set on the socket.  This
     will prevent anyone else from binding to our host/port for the
     duration of the test.

 -- 函数: test.support.bind_unix_socket (sock, addr)

     Bind a unix socket, raising *note unittest.SkipTest: 90b. if *note
     PermissionError: 608. is raised.

 -- 函数: test.support.catch_threading_exception ()

     Context manager catching *note threading.Thread: 235. exception
     using *note threading.excepthook(): 232.

     Attributes set when an exception is catched:

        * ‘exc_type’

        * ‘exc_value’

        * ‘exc_traceback’

        * ‘thread’

     See *note threading.excepthook(): 232. documentation.

     These attributes are deleted at the context manager exit.

     用法:

          with support.catch_threading_exception() as cm:
              # code spawning a thread which raises an exception
              ...

              # check the thread exception, use cm attributes:
              # exc_type, exc_value, exc_traceback, thread
              ...

          # exc_type, exc_value, exc_traceback, thread attributes of cm no longer
          # exists at this point
          # (to avoid reference cycles)

     3.8 新版功能.

 -- 函数: test.support.catch_unraisable_exception ()

     Context manager catching unraisable exception using *note
     sys.unraisablehook(): 22e.

     Storing the exception value (‘cm.unraisable.exc_value’) creates a
     reference cycle.  The reference cycle is broken explicitly when the
     context manager exits.

     Storing the object (‘cm.unraisable.object’) can resurrect it if it
     is set to an object which is being finalized.  Exiting the context
     manager clears the stored object.

     用法:

          with support.catch_unraisable_exception() as cm:
              # code creating an "unraisable exception"
              ...

              # check the unraisable exception: use cm.unraisable
              ...

          # cm.unraisable attribute no longer exists at this point
          # (to break a reference cycle)

     3.8 新版功能.

 -- 函数: test.support.find_unused_port (family=socket.AF_INET,
          socktype=socket.SOCK_STREAM)

     Returns an unused port that should be suitable for binding.  This
     is achieved by creating a temporary socket with the same family and
     type as the ‘sock’ parameter (default is *note AF_INET: 25b8, *note
     SOCK_STREAM: c92.), and binding it to the specified host address
     (defaults to ‘0.0.0.0’) with the port set to 0, eliciting an unused
     ephemeral port from the OS. The temporary socket is then closed and
     deleted, and the ephemeral port is returned.

     Either this method or *note bind_port(): 34a3. should be used for
     any tests where a server socket needs to be bound to a particular
     port for the duration of the test.  Which one to use depends on
     whether the calling code is creating a Python socket, or if an
     unused port needs to be provided in a constructor or passed to an
     external program (i.e.  the ‘-accept’ argument to openssl’s
     s_server mode).  Always prefer *note bind_port(): 34a3. over *note
     find_unused_port(): 34a5. where possible.  Using a hard coded port
     is discouraged since it can make multiple instances of the test
     impossible to run simultaneously, which is a problem for buildbots.

 -- 函数: test.support.load_package_tests (pkg_dir, loader,
          standard_tests, pattern)

     Generic implementation of the *note unittest: 11c. ‘load_tests’
     protocol for use in test packages.  `pkg_dir' is the root directory
     of the package; `loader', `standard_tests', and `pattern' are the
     arguments expected by ‘load_tests’.  In simple cases, the test
     package’s ‘__init__.py’ can be the following:

          import os
          from test.support import load_package_tests

          def load_tests(*args):
              return load_package_tests(os.path.dirname(__file__), *args)

 -- 函数: test.support.fs_is_case_insensitive (directory)

     Return ‘True’ if the file system for `directory' is
     case-insensitive.

 -- 函数: test.support.detect_api_mismatch (ref_api, other_api, *,
          ignore=())

     Returns the set of attributes, functions or methods of `ref_api'
     not found on `other_api', except for a defined list of items to be
     ignored in this check specified in `ignore'.

     By default this skips private attributes beginning with ’_’ but
     includes all magic methods, i.e.  those starting and ending in
     ’__’.

     3.5 新版功能.

 -- 函数: test.support.patch (test_instance, object_to_patch, attr_name,
          new_value)

     Override `object_to_patch.attr_name' with `new_value'.  Also add
     cleanup procedure to `test_instance' to restore `object_to_patch'
     for `attr_name'.  The `attr_name' should be a valid attribute for
     `object_to_patch'.

 -- 函数: test.support.run_in_subinterp (code)

     Run `code' in subinterpreter.  Raise *note unittest.SkipTest: 90b.
     if *note tracemalloc: 115. is enabled.

 -- 函数: test.support.check_free_after_iterating (test, iter, cls,
          args=())

     Assert that `iter' is deallocated after iterating.

 -- 函数: test.support.missing_compiler_executable (cmd_names=[])

     Check for the existence of the compiler executables whose names are
     listed in `cmd_names' or all the compiler executables when
     `cmd_names' is empty and return the first missing executable or
     ‘None’ when none is found missing.

 -- 函数: test.support.check__all__ (test_case, module,
          name_of_module=None, extra=(), blacklist=())

     Assert that the ‘__all__’ variable of `module' contains all public
     names.

     The module’s public names (its API) are detected automatically
     based on whether they match the public name convention and were
     defined in `module'.

     The `name_of_module' argument can specify (as a string or tuple
     thereof) what module(s) an API could be defined in order to be
     detected as a public API. One case for this is when `module'
     imports part of its public API from other modules, possibly a C
     backend (like ‘csv’ and its ‘_csv’).

     The `extra' argument can be a set of names that wouldn’t otherwise
     be automatically detected as "public", like objects without a
     proper ‘__module__’ attribute.  If provided, it will be added to
     the automatically detected ones.

     The `blacklist' argument can be a set of names that must not be
     treated as part of the public API even though their names indicate
     otherwise.

     Example use:

          import bar
          import foo
          import unittest
          from test import support

          class MiscTestCase(unittest.TestCase):
              def test__all__(self):
                  support.check__all__(self, foo)

          class OtherTestCase(unittest.TestCase):
              def test__all__(self):
                  extra = {'BAR_CONST', 'FOO_CONST'}
                  blacklist = {'baz'}  # Undocumented name.
                  # bar imports part of its API from _bar.
                  support.check__all__(self, bar, ('bar', '_bar'),
                                       extra=extra, blacklist=blacklist)

     3.6 新版功能.

The *note test.support: 107. module defines the following classes:

 -- 类: test.support.TransientResource (exc, **kwargs)

     Instances are a context manager that raises *note ResourceDenied:
     3432. if the specified exception type is raised.  Any keyword
     arguments are treated as attribute/value pairs to be compared
     against any exception raised within the *note with: 6f2. statement.
     Only if all pairs match properly against attributes on the
     exception is *note ResourceDenied: 3432. raised.

 -- 类: test.support.EnvironmentVarGuard

     Class used to temporarily set or unset environment variables.
     Instances can be used as a context manager and have a complete
     dictionary interface for querying/modifying the underlying
     ‘os.environ’.  After exit from the context manager all changes to
     environment variables done through this instance will be rolled
     back.

     在 3.1 版更改: Added dictionary interface.

 -- 方法: EnvironmentVarGuard.set (envvar, value)

     Temporarily set the environment variable ‘envvar’ to the value of
     ‘value’.

 -- 方法: EnvironmentVarGuard.unset (envvar)

     Temporarily unset the environment variable ‘envvar’.

 -- 类: test.support.SuppressCrashReport

     A context manager used to try to prevent crash dialog popups on
     tests that are expected to crash a subprocess.

     On Windows, it disables Windows Error Reporting dialogs using
     SetErrorMode(3).

     On UNIX, *note resource.setrlimit(): 34b3. is used to set *note
     resource.RLIMIT_CORE: 34b4.’s soft limit to 0 to prevent coredump
     file creation.

     On both platforms, the old value is restored by *note __exit__():
     c9e.

 -- 类: test.support.CleanImport (*module_names)

     A context manager to force import to return a new module reference.
     This is useful for testing module-level behaviors, such as the
     emission of a DeprecationWarning on import.  Example usage:

          with CleanImport('foo'):
              importlib.import_module('foo')  # New reference.

 -- 类: test.support.DirsOnSysPath (*paths)

     A context manager to temporarily add directories to sys.path.

     This makes a copy of *note sys.path: 490, appends any directories
     given as positional arguments, then reverts *note sys.path: 490. to
     the copied settings when the context ends.

     Note that `all' *note sys.path: 490. modifications in the body of
     the context manager, including replacement of the object, will be
     reverted at the end of the block.

 -- 类: test.support.SaveSignals

     Class to save and restore signal handlers registered by the Python
     signal handler.

 -- 类: test.support.Matcher

      -- 方法: matches (self, d, **kwargs)

          Try to match a single dict with the supplied arguments.

      -- 方法: match_value (self, k, dv, v)

          Try to match a single stored value (`dv') with a supplied
          value (`v').

 -- 类: test.support.WarningsRecorder

     Class used to record warnings for unit tests.  See documentation of
     *note check_warnings(): 3464. above for more details.

 -- 类: test.support.BasicTestRunner

      -- 方法: run (test)

          Run `test' and return the result.

 -- 类: test.support.TestHandler (logging.handlers.BufferingHandler)

     Class for logging support.

 -- 类: test.support.FakePath (path)

     Simple *note path-like object: 373.  It implements the
     ‘__fspath__()’ method which just returns the `path' argument.  If
     `path' is an exception, it will be raised in ‘__fspath__()’.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147

   (2) https://www.python.org/dev/peps/pep-0488

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx


File: python.info,  Node: test support script_helper --- Utilities for the Python execution tests,  Prev: test support --- Utilities for the Python test suite,  Up: 开发工具

5.26.10 ‘test.support.script_helper’ — Utilities for the Python execution tests
-------------------------------------------------------------------------------

The *note test.support.script_helper: 108. module provides support for
Python’s script execution tests.

 -- 函数: test.support.script_helper.interpreter_requires_environment ()

     Return ‘True’ if ‘sys.executable interpreter’ requires environment
     variables in order to be able to run at all.

     This is designed to be used with ‘@unittest.skipIf()’ to annotate
     tests that need to use an ‘assert_python*()’ function to launch an
     isolated mode (‘-I’) or no environment mode (‘-E’) sub-interpreter
     process.

     A normal build & test does not run into this situation but it can
     happen when trying to run the standard library test suite from an
     interpreter that doesn’t have an obvious home with Python’s current
     home finding logic.

     Setting *note PYTHONHOME: 4de. is one way to get most of the
     testsuite to run in that situation.  *note PYTHONPATH: 95b. or
     ‘PYTHONUSERSITE’ are other common environment variables that might
     impact whether or not the interpreter can start.

 -- 函数: test.support.script_helper.run_python_until_end (*args,
          **env_vars)

     Set up the environment based on `env_vars' for running the
     interpreter in a subprocess.  The values can include ‘__isolated’,
     ‘__cleanenv’, ‘__cwd’, and ‘TERM’.

 -- 函数: test.support.script_helper.assert_python_ok (*args,
          **env_vars)

     Assert that running the interpreter with `args' and optional
     environment variables `env_vars' succeeds (‘rc == 0’) and return a
     ‘(return code, stdout, stderr)’ tuple.

     If the ‘__cleanenv’ keyword is set, `env_vars' is used as a fresh
     environment.

     Python is started in isolated mode (command line option ‘-I’),
     except if the ‘__isolated’ keyword is set to ‘False’.

 -- 函数: test.support.script_helper.assert_python_failure (*args,
          **env_vars)

     Assert that running the interpreter with `args' and optional
     environment variables `env_vars' fails (‘rc != 0’) and return a
     ‘(return code, stdout, stderr)’ tuple.

     See *note assert_python_ok(): 34c3. for more options.

 -- 函数: test.support.script_helper.spawn_python (*args,
          stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw)

     Run a Python subprocess with the given arguments.

     `kw' is extra keyword args to pass to *note subprocess.Popen():
     2ba.  Returns a *note subprocess.Popen: 2ba. object.

 -- 函数: test.support.script_helper.kill_python (p)

     Run the given *note subprocess.Popen: 2ba. process until completion
     and return stdout.

 -- 函数: test.support.script_helper.make_script (script_dir,
          script_basename, source, omit_suffix=False)

     Create script containing `source' in path `script_dir' and
     `script_basename'.  If `omit_suffix' is ‘False’, append ‘.py’ to
     the name.  Return the full script path.

 -- 函数: test.support.script_helper.make_zip_script (zip_dir,
          zip_basename, script_name, name_in_zip=None)

     Create zip file at `zip_dir' and `zip_basename' with extension
     ‘zip’ which contains the files in `script_name'.  `name_in_zip' is
     the archive name.  Return a tuple containing ‘(full path, full path
     of archive name)’.

 -- 函数: test.support.script_helper.make_pkg (pkg_dir, init_source='')

     Create a directory named `pkg_dir' containing an ‘__init__’ file
     with `init_source' as its contents.

 -- 函数: test.support.script_helper.make_zip_pkg (zip_dir,
          zip_basename, pkg_name, script_basename, source, depth=1,
          compiled=False)

     Create a zip package directory with a path of `zip_dir' and
     `zip_basename' containing an empty ‘__init__’ file and a file
     `script_basename' containing the `source'.  If `compiled' is
     ‘True’, both source files will be compiled and added to the zip
     package.  Return a tuple of the full zip path and the archive name
     for the zip file.

另请参看 Python 开发模式: *note -X: 156. ‘dev’ 选项以及 *note
PYTHONDEVMODE: 335. 环境变量。


File: python.info,  Node: 调试和分析,  Next: 软件打包和分发,  Prev: 开发工具,  Up: Python 标准库

5.27 调试和分析
===============

这些库可以帮助你进行 Python 开发：调试器使你能够逐步执行代码，分析堆栈帧
并设置中断点等等，性能分析器可以运行代码并为你提供执行时间的详细数据，使
你能够找出你的程序中的瓶颈。 审计事件提供运行时行为的可见性，如果没有此
工具则需要进行侵入式调试或修补。

* Menu:

* 审计事件表::
* bdb: bdb --- Debugger framework. Debugger framework
* faulthandler: faulthandler --- Dump the Python traceback. Dump the Python traceback
* pdb: pdb --- Python的调试器. Python的调试器
* Python Profilers 分析器::
* timeit: timeit --- 测量小代码片段的执行时间. 测量小代码片段的执行时间
* trace: trace --- 跟踪Python语句的执行. 跟踪Python语句的执行
* tracemalloc: tracemalloc --- 跟踪内存分配. 跟踪内存分配


File: python.info,  Node: 审计事件表,  Next: bdb --- Debugger framework,  Up: 调试和分析

5.27.1 审计事件表
-----------------

下表包含了在整个 CPython 运行时和标准库中由 *note sys.audit(): f38. 或
*note PySys_Audit(): f46. 调用所引发的全部事件。 这些调用是在 3.8.0 或更
高版本中添加了 (参见 PEP 578(1))。

请参阅 *note sys.addaudithook(): 34d0. 和 *note PySys_AddAuditHook():
34d1. 了解有关处理这些事件的详细信息。

`CPython implementation detail:' 此表是根据 CPython 文档生成的，可能无法
表示其他实现所引发的事件。 请参阅你的运行时专属的文档了解实际引发的事件
。

Audit event                        Arguments                                                   References
                                                                                               
-------------------------------------------------------------------------------------------------------------------
                                                                                               
array.__new__                      ‘typecode’, ‘initializer’                                   *note [1]: 459.
                                                                                               
                                                                                               
builtins.breakpoint                ‘breakpointhook’                                            *note [1]: 302.
                                                                                               
                                                                                               
builtins.id                        ‘id’                                                        *note [1]: d8e.
                                                                                               
                                                                                               
builtins.input                     ‘prompt’                                                    *note [1]: c73.
                                                                                               
                                                                                               
builtins.input/result              ‘result’                                                    *note [1]: c73.
                                                                                               
                                                                                               
code.__new__                       ‘code’, ‘filename’, ‘name’, ‘argcount’,                     *note [1]: 199.
                                   ‘posonlyargcount’, ‘kwonlyargcount’, ‘nlocals’,             
                                   ‘stacksize’, ‘flags’
                                   
                                                                                               
compile                            ‘source’, ‘filename’                                        *note [1]: 1b5.
                                                                                               
                                                                                               
cpython.PyInterpreterState_Clear                                                               *note [1]: 34d2.
                                                                                               
                                                                                               
cpython.PyInterpreterState_New                                                                 *note [1]: 34d3.
                                                                                               
                                                                                               
cpython._PySys_ClearAuditHooks                                                                 *note [1]: 5d2.
                                                                                               
                                                                                               
cpython.run_command                ‘command’                                                   *note [1]: 121b.
                                                                                               
                                                                                               
cpython.run_file                   ‘filename’                                                  *note [1]: 34d4.
                                                                                               
                                                                                               
cpython.run_interactivehook        ‘hook’                                                      *note [1]: 8ec.
                                                                                               
                                                                                               
cpython.run_module                 ‘module-name’                                               *note [1]: 340.
                                                                                               
                                                                                               
cpython.run_startup                ‘filename’                                                  *note [1]: 8ed.
                                                                                               
                                                                                               
cpython.run_stdin                                                                              *note [1]: 34d5.
                                                                                               
                                                                                               
ctypes.addressof                   ‘obj’                                                       *note [1]: 232a.
                                                                                               
                                                                                               
ctypes.call_function               ‘func_pointer’, ‘arguments’                                 *note [1]: 231f.
                                                                                               
                                                                                               
ctypes.cdata                       ‘address’                                                   *note [1]: 233c.
                                                                                               
                                                                                               
ctypes.cdata/buffer                ‘pointer’, ‘size’, ‘offset’                                 *note [1]: 233a.*note [2]: 233b.
                                                                                               
                                                                                               
ctypes.create_string_buffer        ‘init’, ‘size’                                              *note [1]: 22dc.
                                                                                               
                                                                                               
ctypes.create_unicode_buffer       ‘init’, ‘size’                                              *note [1]: fbd.
                                                                                               
                                                                                               
ctypes.dlopen                      ‘name’                                                      *note [1]: 231c.
                                                                                               
                                                                                               
ctypes.dlsym                       ‘library’, ‘name’                                           *note [1]: 231c.
                                                                                               
                                                                                               
ctypes.dlsym/handle                ‘handle’, ‘name’                                            *note [1]: 231c.
                                                                                               
                                                                                               
ctypes.get_errno                                                                               *note [1]: 2316.
                                                                                               
                                                                                               
ctypes.get_last_error                                                                          *note [1]: 2318.
                                                                                               
                                                                                               
ctypes.seh_exception               ‘code’                                                      *note [1]: 231f.
                                                                                               
                                                                                               
ctypes.set_errno                   ‘errno’                                                     *note [1]: 2317.
                                                                                               
                                                                                               
ctypes.set_last_error              ‘error’                                                     *note [1]: 2319.
                                                                                               
                                                                                               
ctypes.string_at                   ‘address’, ‘size’                                           *note [1]: 2333.
                                                                                               
                                                                                               
ctypes.wstring_at                  ‘address’, ‘size’                                           *note [1]: 2335.
                                                                                               
                                                                                               
ensurepip.bootstrap                ‘root’                                                      *note [1]: 34d6.
                                                                                               
                                                                                               
exec                               ‘code_object’                                               *note [1]: b98.*note [2]: c4c.
                                                                                               
                                                                                               
fcntl.fcntl                        ‘fd’, ‘cmd’, ‘arg’                                          *note [1]: 26a9.
                                                                                               
                                                                                               
fcntl.flock                        ‘fd’, ‘operation’                                           *note [1]: 34d7.
                                                                                               
                                                                                               
fcntl.ioctl                        ‘fd’, ‘request’, ‘arg’                                      *note [1]: de6.
                                                                                               
                                                                                               
fcntl.lockf                        ‘fd’, ‘cmd’, ‘len’, ‘start’, ‘whence’                       *note [1]: d5a.
                                                                                               
                                                                                               
ftplib.connect                     ‘self’, ‘host’, ‘port’                                      *note [1]: 2d25.
                                                                                               
                                                                                               
ftplib.sendcmd                     ‘self’, ‘cmd’                                               *note [1]: 2d29.*note [2]: 2d2a.
                                                                                               
                                                                                               
function.__new__                   ‘code’                                                      *note [1]: 19b8.
                                                                                               
                                                                                               
gc.get_objects                     ‘generation’                                                *note [1]: 1ce.
                                                                                               
                                                                                               
gc.get_referents                   ‘objs’                                                      *note [1]: eb5.
                                                                                               
                                                                                               
gc.get_referrers                   ‘objs’                                                      *note [1]: eb4.
                                                                                               
                                                                                               
glob.glob                          ‘pathname’, ‘recursive’                                     *note [1]: 5cf.*note [2]: 5d0.
                                                                                               
                                                                                               
imaplib.open                       ‘self’, ‘host’, ‘port’                                      *note [1]: 2d75.
                                                                                               
                                                                                               
imaplib.send                       ‘self’, ‘data’                                              *note [1]: 2d78.
                                                                                               
                                                                                               
import                             ‘module’, ‘filename’, ‘sys.path’, ‘sys.meta_path’,          *note [1]: c25.
                                   ‘sys.path_hooks’                                            
                                   
                                                                                               
mmap.__new__                       ‘fileno’, ‘length’, ‘access’, ‘offset’                      *note [1]: 1ed.
                                                                                               
                                                                                               
msvcrt.get_osfhandle               ‘fd’                                                        *note [1]: 34d8.
                                                                                               
                                                                                               
msvcrt.locking                     ‘fd’, ‘mode’, ‘nbytes’                                      *note [1]: 34d9.
                                                                                               
                                                                                               
msvcrt.open_osfhandle              ‘handle’, ‘flags’                                           *note [1]: 34da.
                                                                                               
                                                                                               
nntplib.connect                    ‘self’, ‘host’, ‘port’                                      *note [1]: a34.*note [2]: bad.
                                                                                               
                                                                                               
nntplib.putline                    ‘self’, ‘line’                                              *note [1]: a34.*note [2]: bad.
                                                                                               
                                                                                               
object.__delattr__                 ‘obj’, ‘name’                                               *note [1]: 1440.
                                                                                               
                                                                                               
object.__getattr__                 ‘obj’, ‘name’                                               *note [1]: 44f.
                                                                                               
                                                                                               
object.__setattr__                 ‘obj’, ‘name’, ‘value’                                      *note [1]: e34.
                                                                                               
                                                                                               
open                               ‘file’, ‘mode’, ‘flags’                                     *note [1]: 4f8.*note [2]: 663.*note [3]: 66e.
                                                                                               
                                                                                               
os.add_dll_directory               ‘path’                                                      *note [1]: 1c3.
                                                                                               
                                                                                               
os.chdir                           ‘path’                                                      *note [1]: a47.*note [2]: 664.
                                                                                               
                                                                                               
os.chflags                         ‘path’, ‘flags’                                             *note [1]: a3a.*note [2]: 1f5c.
                                                                                               
                                                                                               
os.chmod                           ‘path’, ‘mode’, ‘dir_fd’                                    *note [1]: a3b.*note [2]: 665.*note [3]: 1039.
                                                                                               
                                                                                               
os.chown                           ‘path’, ‘uid’, ‘gid’, ‘dir_fd’                              *note [1]: a3c.*note [2]: 666.*note [3]: 1f5d.
                                                                                               
                                                                                               
os.exec                            ‘path’, ‘args’, ‘env’                                       *note [1]: 1f99.
                                                                                               
                                                                                               
os.fork                                                                                        *note [1]: 969.
                                                                                               
                                                                                               
os.forkpty                                                                                     *note [1]: 1fb1.
                                                                                               
                                                                                               
os.getxattr                        ‘path’, ‘attribute’                                         *note [1]: a53.
                                                                                               
                                                                                               
os.kill                            ‘pid’, ‘sig’                                                *note [1]: cfb.
                                                                                               
                                                                                               
os.killpg                          ‘pgid’, ‘sig’                                               *note [1]: f3f.
                                                                                               
                                                                                               
os.link                            ‘src’, ‘dst’, ‘src_dir_fd’, ‘dst_dir_fd’                    *note [1]: a3d.
                                                                                               
                                                                                               
os.listdir                         ‘path’                                                      *note [1]: a49.
                                                                                               
                                                                                               
os.listxattr                       ‘path’                                                      *note [1]: a54.
                                                                                               
                                                                                               
os.lockf                           ‘fd’, ‘cmd’, ‘len’                                          *note [1]: a62.
                                                                                               
                                                                                               
os.mkdir                           ‘path’, ‘mode’, ‘dir_fd’                                    *note [1]: 3c5.*note [2]: a3e.
                                                                                               
                                                                                               
os.posix_spawn                     ‘path’, ‘argv’, ‘env’                                       *note [1]: 258.*note [2]: 1025.
                                                                                               
                                                                                               
os.putenv                          ‘key’, ‘value’                                              *note [1]: 1ef5.
                                                                                               
                                                                                               
os.remove                          ‘path’, ‘dir_fd’                                            *note [1]: a3f.*note [2]: 1f64.*note [3]: a44.
                                                                                               
                                                                                               
os.removexattr                     ‘path’, ‘attribute’                                         *note [1]: a55.
                                                                                               
                                                                                               
os.rename                          ‘src’, ‘dst’, ‘src_dir_fd’, ‘dst_dir_fd’                    *note [1]: a40.*note [2]: 1f65.*note [3]: a41.
                                                                                               
                                                                                               
os.rmdir                           ‘path’, ‘dir_fd’                                            *note [1]: a42.
                                                                                               
                                                                                               
os.scandir                         ‘path’                                                      *note [1]: 260.
                                                                                               
                                                                                               
os.setxattr                        ‘path’, ‘attribute’, ‘value’, ‘flags’                       *note [1]: a56.
                                                                                               
                                                                                               
os.spawn                           ‘mode’, ‘path’, ‘args’, ‘env’                               *note [1]: 1f55.
                                                                                               
                                                                                               
os.startfile                       ‘path’, ‘operation’                                         *note [1]: 1fc5.
                                                                                               
                                                                                               
os.symlink                         ‘src’, ‘dst’, ‘dir_fd’                                      *note [1]: a43.
                                                                                               
                                                                                               
os.system                          ‘command’                                                   *note [1]: dc9.
                                                                                               
                                                                                               
os.truncate                        ‘fd’, ‘length’                                              *note [1]: 66b.*note [2]: 72d.
                                                                                               
                                                                                               
os.unsetenv                        ‘key’                                                       *note [1]: d4b.
                                                                                               
                                                                                               
os.utime                           ‘path’, ‘times’, ‘ns’, ‘dir_fd’                             *note [1]: a45.
                                                                                               
                                                                                               
pdb.Pdb                                                                                        *note [1]: 575.
                                                                                               
                                                                                               
pickle.find_class                  ‘module’, ‘name’                                            *note [1]: 1cd0.
                                                                                               
                                                                                               
poplib.connect                     ‘self’, ‘host’, ‘port’                                      *note [1]: 2d40.*note [2]: bc9.
                                                                                               
                                                                                               
poplib.putline                     ‘self’, ‘line’                                              *note [1]: 2d40.*note [2]: bc9.
                                                                                               
                                                                                               
pty.spawn                          ‘argv’                                                      *note [1]: 8a1.
                                                                                               
                                                                                               
resource.prlimit                   ‘pid’, ‘resource’, ‘limits’                                 *note [1]: 8a8.
                                                                                               
                                                                                               
resource.setrlimit                 ‘resource’, ‘limits’                                        *note [1]: 34b3.
                                                                                               
                                                                                               
setopencodehook                                                                                *note [1]: 1ff6.
                                                                                               
                                                                                               
shutil.chown                       ‘path’, ‘user’, ‘group’                                     *note [1]: a7e.
                                                                                               
                                                                                               
shutil.copyfile                    ‘src’, ‘dst’                                                *note [1]: 25a.*note [2]: 25b.*note [3]: 259.
                                                                                               
                                                                                               
shutil.copymode                    ‘src’, ‘dst’                                                *note [1]: 25a.*note [2]: 1c97.
                                                                                               
                                                                                               
shutil.copystat                    ‘src’, ‘dst’                                                *note [1]: 25b.*note [2]: a7f.
                                                                                               
                                                                                               
shutil.copytree                    ‘src’, ‘dst’                                                *note [1]: 21b.
                                                                                               
                                                                                               
shutil.make_archive                ‘base_name’, ‘format’, ‘root_dir’, ‘base_dir’               *note [1]: 21c.
                                                                                               
                                                                                               
shutil.move                        ‘src’, ‘dst’                                                *note [1]: 25c.
                                                                                               
                                                                                               
shutil.rmtree                      ‘path’                                                      *note [1]: 21d.
                                                                                               
                                                                                               
shutil.unpack_archive              ‘filename’, ‘extract_dir’, ‘format’                         *note [1]: b9f.
                                                                                               
                                                                                               
signal.pthread_kill                ‘thread_id’, ‘signalnum’                                    *note [1]: a82.
                                                                                               
                                                                                               
smtplib.connect                    ‘self’, ‘host’, ‘port’                                      *note [1]: eeb.
                                                                                               
                                                                                               
smtplib.send                       ‘self’, ‘data’                                              *note [1]: a89.
                                                                                               
                                                                                               
socket.__new__                     ‘self’, ‘family’, ‘type’, ‘protocol’                        *note [1]: 67d.
                                                                                               
                                                                                               
socket.bind                        ‘self’, ‘address’                                           *note [1]: 26a3.
                                                                                               
                                                                                               
socket.connect                     ‘self’, ‘address’                                           *note [1]: 67f.*note [2]: 26a5.
                                                                                               
                                                                                               
socket.getaddrinfo                 ‘host’, ‘port’, ‘family’, ‘type’, ‘protocol’                *note [1]: 25cc.
                                                                                               
                                                                                               
socket.gethostbyaddr               ‘ip_address’                                                *note [1]: ead.
                                                                                               
                                                                                               
socket.gethostbyname               ‘hostname’                                                  *note [1]: 269b.*note [2]: eae.
                                                                                               
                                                                                               
socket.gethostname                                                                             *note [1]: 1f14.
                                                                                               
                                                                                               
socket.getnameinfo                 ‘sockaddr’                                                  *note [1]: 25cd.
                                                                                               
                                                                                               
socket.getservbyname               ‘servicename’, ‘protocolname’                               *note [1]: 269d.
                                                                                               
                                                                                               
socket.getservbyport               ‘port’, ‘protocolname’                                      *note [1]: 269e.
                                                                                               
                                                                                               
socket.sendmsg                     ‘self’, ‘address’                                           *note [1]: 685.
                                                                                               
                                                                                               
socket.sendto                      ‘self’, ‘address’                                           *note [1]: 686.
                                                                                               
                                                                                               
socket.sethostname                 ‘name’                                                      *note [1]: a8f.
                                                                                               
                                                                                               
sqlite3.connect                    ‘database’                                                  *note [1]: 3e2.
                                                                                               
                                                                                               
subprocess.Popen                   ‘executable’, ‘args’, ‘cwd’, ‘env’                          *note [1]: 2ba.
                                                                                               
                                                                                               
sys._current_frames                                                                            *note [1]: da3.
                                                                                               
                                                                                               
sys._getframe                                                                                  *note [1]: e6c.
                                                                                               
                                                                                               
sys.addaudithook                                                                               *note [1]: 34d1.*note [2]: 34d0.
                                                                                               
                                                                                               
sys.excepthook                     ‘hook’, ‘type’, ‘value’, ‘traceback’                        *note [1]: e6b.
                                                                                               
                                                                                               
sys.set_asyncgen_hooks_finalizer                                                               *note [1]: f39.
                                                                                               
                                                                                               
sys.set_asyncgen_hooks_firstiter                                                               *note [1]: f39.
                                                                                               
                                                                                               
sys.setprofile                                                                                 *note [1]: e45.
                                                                                               
                                                                                               
sys.settrace                                                                                   *note [1]: e46.
                                                                                               
                                                                                               
sys.unraisablehook                 ‘hook’, ‘unraisable’                                        *note [1]: 22e.
                                                                                               
                                                                                               
syslog.closelog                                                                                *note [1]: 34db.
                                                                                               
                                                                                               
syslog.openlog                     ‘ident’, ‘logoption’, ‘facility’                            *note [1]: 34dc.
                                                                                               
                                                                                               
syslog.setlogmask                  ‘maskpri’                                                   *note [1]: 34dd.
                                                                                               
                                                                                               
syslog.syslog                      ‘priority’, ‘message’                                       *note [1]: 34de.
                                                                                               
                                                                                               
telnetlib.Telnet.open              ‘self’, ‘host’, ‘port’                                      *note [1]: 2dea.
                                                                                               
                                                                                               
telnetlib.Telnet.write             ‘self’, ‘buffer’                                            *note [1]: 2dfa.
                                                                                               
                                                                                               
tempfile.mkdtemp                   ‘fullpath’                                                  *note [1]: bd0.*note [2]: 1c79.
                                                                                               
                                                                                               
tempfile.mkstemp                   ‘fullpath’                                                  *note [1]: d51.*note [2]: 1c77.*note [3]: 1c78.
                                                                                               
                                                                                               
urllib.Request                     ‘fullurl’, ‘data’, ‘headers’, ‘method’                      *note [1]: 795.
                                                                                               
                                                                                               
webbrowser.open                    ‘url’                                                       *note [1]: 2bdd.
                                                                                               
                                                                                               
winreg.ConnectRegistry             ‘computer_name’, ‘key’                                      *note [1]: 34df.
                                                                                               
                                                                                               
winreg.CreateKey                   ‘key’, ‘sub_key’, ‘access’                                  *note [1]: 34e0.*note [2]: 34e1.
                                                                                               
                                                                                               
winreg.DeleteKey                   ‘key’, ‘sub_key’, ‘access’                                  *note [1]: 34e2.*note [2]: 34e3.
                                                                                               
                                                                                               
winreg.DeleteValue                 ‘key’, ‘value’                                              *note [1]: 34e4.
                                                                                               
                                                                                               
winreg.DisableReflectionKey        ‘key’                                                       *note [1]: 34e5.
                                                                                               
                                                                                               
winreg.EnableReflectionKey         ‘key’                                                       *note [1]: 34e6.
                                                                                               
                                                                                               
winreg.EnumKey                     ‘key’, ‘index’                                              *note [1]: 34e7.
                                                                                               
                                                                                               
winreg.EnumValue                   ‘key’, ‘index’                                              *note [1]: 34e8.
                                                                                               
                                                                                               
winreg.ExpandEnvironmentStrings    ‘str’                                                       *note [1]: 34e9.
                                                                                               
                                                                                               
winreg.LoadKey                     ‘key’, ‘sub_key’, ‘file_name’                               *note [1]: 34ea.
                                                                                               
                                                                                               
winreg.OpenKey                     ‘key’, ‘sub_key’, ‘access’                                  *note [1]: 34eb.
                                                                                               
                                                                                               
winreg.OpenKey/result              ‘key’                                                       *note [1]: 34e0.*note [2]: 34e1.*note [3]: 34eb.
                                                                                               
                                                                                               
winreg.PyHKEY.Detach               ‘key’                                                       *note [1]: 34ec.
                                                                                               
                                                                                               
winreg.QueryInfoKey                ‘key’                                                       *note [1]: 34ed.
                                                                                               
                                                                                               
winreg.QueryReflectionKey          ‘key’                                                       *note [1]: 34ee.
                                                                                               
                                                                                               
winreg.QueryValue                  ‘key’, ‘sub_key’, ‘value_name’                              *note [1]: 34ef.*note [2]: 34f0.
                                                                                               
                                                                                               
winreg.SaveKey                     ‘key’, ‘file_name’                                          *note [1]: 34f1.
                                                                                               
                                                                                               
winreg.SetValue                    ‘key’, ‘sub_key’, ‘type’, ‘value’                           *note [1]: 34f2.*note [2]: 34f3.
                                                                                               

下列事件只在内部被引发，而不会回应任何 CPython 公共 API:

审计事件                       实参
                               
-------------------------------------------------------------------------------
                               
_winapi.CreateFile             ‘file_name’, ‘desired_access’, ‘share_mode’,
                               ‘creation_disposition’,
                               ‘flags_and_attributes’
                               
                               
_winapi.CreateJunction         ‘src_path’, ‘dst_path’
                               
                               
_winapi.CreateNamedPipe        ‘name’, ‘open_mode’, ‘pipe_mode’
                               
                               
_winapi.CreatePipe

_winapi.CreateProcess          ‘application_name’, ‘command_line’,
                               ‘current_directory’
                               
                               
_winapi.OpenProcess            ‘process_id’, ‘desired_access’
                               
                               
_winapi.TerminateProcess       ‘handle’, ‘exit_code’
                               
                               
ctypes.PyObj_FromPtr           ‘obj’
                               

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0578


File: python.info,  Node: bdb --- Debugger framework,  Next: faulthandler --- Dump the Python traceback,  Prev: 审计事件表,  Up: 调试和分析

5.27.2 ‘bdb’ — Debugger framework
---------------------------------

`Source code:' Lib/bdb.py(1)

__________________________________________________________________

The *note bdb: f. module handles basic debugger functions, like setting
breakpoints or managing execution via the debugger.

定义了以下异常：

 -- 例外: bdb.BdbQuit

     Exception raised by the *note Bdb: ca0. class for quitting the
     debugger.

The *note bdb: f. module also defines two classes:

 -- 类: bdb.Breakpoint (self, file, line, temporary=0, cond=None,
          funcname=None)

     This class implements temporary breakpoints, ignore counts,
     disabling and (re-)enabling, and conditionals.

     Breakpoints are indexed by number through a list called
     ‘bpbynumber’ and by ‘(file, line)’ pairs through ‘bplist’.  The
     former points to a single instance of class *note Breakpoint: 34f7.
     The latter points to a list of such instances since there may be
     more than one breakpoint per line.

     When creating a breakpoint, its associated filename should be in
     canonical form.  If a `funcname' is defined, a breakpoint hit will
     be counted when the first line of that function is executed.  A
     conditional breakpoint always counts a hit.

     *note Breakpoint: 34f7. instances have the following methods:

      -- 方法: deleteMe ()

          Delete the breakpoint from the list associated to a file/line.
          If it is the last breakpoint in that position, it also deletes
          the entry for the file/line.

      -- 方法: enable ()

          Mark the breakpoint as enabled.

      -- 方法: disable ()

          Mark the breakpoint as disabled.

      -- 方法: bpformat ()

          Return a string with all the information about the breakpoint,
          nicely formatted:

             * The breakpoint number.

             * If it is temporary or not.

             * Its file,line position.

             * The condition that causes a break.

             * If it must be ignored the next N times.

             * The breakpoint hit count.

          3.2 新版功能.

      -- 方法: bpprint (out=None)

          Print the output of *note bpformat(): 34fb. to the file `out',
          or if it is ‘None’, to standard output.

 -- 类: bdb.Bdb (skip=None)

     The *note Bdb: ca0. class acts as a generic Python debugger base
     class.

     This class takes care of the details of the trace facility; a
     derived class should implement user interaction.  The standard
     debugger class (*note pdb.Pdb: 575.) is an example.

     The `skip' argument, if given, must be an iterable of glob-style
     module name patterns.  The debugger will not step into frames that
     originate in a module that matches one of these patterns.  Whether
     a frame is considered to originate in a certain module is
     determined by the ‘__name__’ in the frame globals.

     3.1 新版功能: `skip' 参数。

     The following methods of *note Bdb: ca0. normally don’t need to be
     overridden.

      -- 方法: canonic (filename)

          Auxiliary method for getting a filename in a canonical form,
          that is, as a case-normalized (on case-insensitive
          filesystems) absolute path, stripped of surrounding angle
          brackets.

      -- 方法: reset ()

          Set the ‘botframe’, ‘stopframe’, ‘returnframe’ and ‘quitting’
          attributes with values ready to start debugging.

      -- 方法: trace_dispatch (frame, event, arg)

          This function is installed as the trace function of debugged
          frames.  Its return value is the new trace function (in most
          cases, that is, itself).

          The default implementation decides how to dispatch a frame,
          depending on the type of event (passed as a string) that is
          about to be executed.  `event' can be one of the following:

             * ‘"line"’: A new line of code is going to be executed.

             * ‘"call"’: A function is about to be called, or another
               code block entered.

             * ‘"return"’: A function or other code block is about to
               return.

             * ‘"exception"’: An exception has occurred.

             * ‘"c_call"’: A C function is about to be called.

             * ‘"c_return"’: A C function has returned.

             * ‘"c_exception"’: A C function has raised an exception.

          For the Python events, specialized functions (see below) are
          called.  For the C events, no action is taken.

          The `arg' parameter depends on the previous event.

          See the documentation for *note sys.settrace(): e46. for more
          information on the trace function.  For more information on
          code and frame objects, refer to *note 标准类型层级结构: 1431.

      -- 方法: dispatch_line (frame)

          If the debugger should stop on the current line, invoke the
          *note user_line(): 3501. method (which should be overridden in
          subclasses).  Raise a *note BdbQuit: 34f6. exception if the
          ‘Bdb.quitting’ flag is set (which can be set from *note
          user_line(): 3501.).  Return a reference to the *note
          trace_dispatch(): 34ff. method for further tracing in that
          scope.

      -- 方法: dispatch_call (frame, arg)

          If the debugger should stop on this function call, invoke the
          *note user_call(): 3503. method (which should be overridden in
          subclasses).  Raise a *note BdbQuit: 34f6. exception if the
          ‘Bdb.quitting’ flag is set (which can be set from *note
          user_call(): 3503.).  Return a reference to the *note
          trace_dispatch(): 34ff. method for further tracing in that
          scope.

      -- 方法: dispatch_return (frame, arg)

          If the debugger should stop on this function return, invoke
          the *note user_return(): 3505. method (which should be
          overridden in subclasses).  Raise a *note BdbQuit: 34f6.
          exception if the ‘Bdb.quitting’ flag is set (which can be set
          from *note user_return(): 3505.).  Return a reference to the
          *note trace_dispatch(): 34ff. method for further tracing in
          that scope.

      -- 方法: dispatch_exception (frame, arg)

          If the debugger should stop at this exception, invokes the
          *note user_exception(): 3507. method (which should be
          overridden in subclasses).  Raise a *note BdbQuit: 34f6.
          exception if the ‘Bdb.quitting’ flag is set (which can be set
          from *note user_exception(): 3507.).  Return a reference to
          the *note trace_dispatch(): 34ff. method for further tracing
          in that scope.

     Normally derived classes don’t override the following methods, but
     they may if they want to redefine the definition of stopping and
     breakpoints.

      -- 方法: stop_here (frame)

          This method checks if the `frame' is somewhere below
          ‘botframe’ in the call stack.  ‘botframe’ is the frame in
          which debugging started.

      -- 方法: break_here (frame)

          This method checks if there is a breakpoint in the filename
          and line belonging to `frame' or, at least, in the current
          function.  If the breakpoint is a temporary one, this method
          deletes it.

      -- 方法: break_anywhere (frame)

          This method checks if there is a breakpoint in the filename of
          the current frame.

     Derived classes should override these methods to gain control over
     debugger operation.

      -- 方法: user_call (frame, argument_list)

          This method is called from *note dispatch_call(): 3502. when
          there is the possibility that a break might be necessary
          anywhere inside the called function.

      -- 方法: user_line (frame)

          This method is called from *note dispatch_line(): 3500. when
          either *note stop_here(): 3508. or *note break_here(): 3509.
          yields ‘True’.

      -- 方法: user_return (frame, return_value)

          This method is called from *note dispatch_return(): 3504. when
          *note stop_here(): 3508. yields ‘True’.

      -- 方法: user_exception (frame, exc_info)

          This method is called from *note dispatch_exception(): 3506.
          when *note stop_here(): 3508. yields ‘True’.

      -- 方法: do_clear (arg)

          Handle how a breakpoint must be removed when it is a temporary
          one.

          This method must be implemented by derived classes.

     Derived classes and clients can call the following methods to
     affect the stepping state.

      -- 方法: set_step ()

          Stop after one line of code.

      -- 方法: set_next (frame)

          Stop on the next line in or below the given frame.

      -- 方法: set_return (frame)

          Stop when returning from the given frame.

      -- 方法: set_until (frame)

          Stop when the line with the line no greater than the current
          one is reached or when returning from current frame.

      -- 方法: set_trace ([frame])

          Start debugging from `frame'.  If `frame' is not specified,
          debugging starts from caller’s frame.

      -- 方法: set_continue ()

          Stop only at breakpoints or when finished.  If there are no
          breakpoints, set the system trace function to ‘None’.

      -- 方法: set_quit ()

          Set the ‘quitting’ attribute to ‘True’.  This raises *note
          BdbQuit: 34f6. in the next call to one of the ‘dispatch_*()’
          methods.

     Derived classes and clients can call the following methods to
     manipulate breakpoints.  These methods return a string containing
     an error message if something went wrong, or ‘None’ if all is well.

      -- 方法: set_break (filename, lineno, temporary=0, cond, funcname)

          Set a new breakpoint.  If the `lineno' line doesn’t exist for
          the `filename' passed as argument, return an error message.
          The `filename' should be in canonical form, as described in
          the *note canonic(): 34fd. method.

      -- 方法: clear_break (filename, lineno)

          Delete the breakpoints in `filename' and `lineno'.  If none
          were set, an error message is returned.

      -- 方法: clear_bpbynumber (arg)

          Delete the breakpoint which has the index `arg' in the
          ‘Breakpoint.bpbynumber’.  If `arg' is not numeric or out of
          range, return an error message.

      -- 方法: clear_all_file_breaks (filename)

          Delete all breakpoints in `filename'.  If none were set, an
          error message is returned.

      -- 方法: clear_all_breaks ()

          Delete all existing breakpoints.

      -- 方法: get_bpbynumber (arg)

          Return a breakpoint specified by the given number.  If `arg'
          is a string, it will be converted to a number.  If `arg' is a
          non-numeric string, if the given breakpoint never existed or
          has been deleted, a *note ValueError: 1fc. is raised.

          3.2 新版功能.

      -- 方法: get_break (filename, lineno)

          Check if there is a breakpoint for `lineno' of `filename'.

      -- 方法: get_breaks (filename, lineno)

          Return all breakpoints for `lineno' in `filename', or an empty
          list if none are set.

      -- 方法: get_file_breaks (filename)

          Return all breakpoints in `filename', or an empty list if none
          are set.

      -- 方法: get_all_breaks ()

          Return all breakpoints that are set.

     Derived classes and clients can call the following methods to get a
     data structure representing a stack trace.

      -- 方法: get_stack (f, t)

          Get a list of records for a frame and all higher (calling) and
          lower frames, and the size of the higher part.

      -- 方法: format_stack_entry (frame_lineno, lprefix=': ')

          Return a string with information about a stack entry,
          identified by a ‘(frame, lineno)’ tuple:

             * The canonical form of the filename which contains the
               frame.

             * The function name, or ‘"<lambda>"’.

             * The input arguments.

             * The return value.

             * The line of code (if it exists).

     The following two methods can be called by clients to use a
     debugger to debug a *note statement: 1ba2, given as a string.

      -- 方法: run (cmd, globals=None, locals=None)

          Debug a statement executed via the *note exec(): c4c.
          function.  `globals' defaults to ‘__main__.__dict__’, `locals'
          defaults to `globals'.

      -- 方法: runeval (expr, globals=None, locals=None)

          Debug an expression executed via the *note eval(): b98.
          function.  `globals' and `locals' have the same meaning as in
          *note run(): 351f.

      -- 方法: runctx (cmd, globals, locals)

          For backwards compatibility.  Calls the *note run(): 351f.
          method.

      -- 方法: runcall (func, *args, **kwds)

          Debug a single function call, and return its result.

Finally, the module defines the following functions:

 -- 函数: bdb.checkfuncname (b, frame)

     Check whether we should break here, depending on the way the
     breakpoint `b' was set.

     If it was set via line number, it checks if ‘b.line’ is the same as
     the one in the frame also passed as argument.  If the breakpoint
     was set via function name, we have to check we are in the right
     frame (the right function) and if we are in its first executable
     line.

 -- 函数: bdb.effective (file, line, frame)

     Determine if there is an effective (active) breakpoint at this line
     of code.  Return a tuple of the breakpoint and a boolean that
     indicates if it is ok to delete a temporary breakpoint.  Return
     ‘(None, None)’ if there is no matching breakpoint.

 -- 函数: bdb.set_trace ()

     Start debugging with a *note Bdb: ca0. instance from caller’s
     frame.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/bdb.py


File: python.info,  Node: faulthandler --- Dump the Python traceback,  Next: pdb --- Python的调试器,  Prev: bdb --- Debugger framework,  Up: 调试和分析

5.27.3 ‘faulthandler’ — Dump the Python traceback
-------------------------------------------------

3.3 新版功能.

__________________________________________________________________

This module contains functions to dump Python tracebacks explicitly, on
a fault, after a timeout, or on a user signal.  Call *note
faulthandler.enable(): 551. to install fault handlers for the ‘SIGSEGV’,
‘SIGFPE’, ‘SIGABRT’, ‘SIGBUS’, and ‘SIGILL’ signals.  You can also
enable them at startup by setting the *note PYTHONFAULTHANDLER: 9d0.
environment variable or by using the *note -X: 156. ‘faulthandler’
command line option.

The fault handler is compatible with system fault handlers like Apport
or the Windows fault handler.  The module uses an alternative stack for
signal handlers if the ‘sigaltstack()’ function is available.  This
allows it to dump the traceback even on a stack overflow.

The fault handler is called on catastrophic cases and therefore can only
use signal-safe functions (e.g.  it cannot allocate memory on the heap).
Because of this limitation traceback dumping is minimal compared to
normal Python tracebacks:

   * Only ASCII is supported.  The ‘backslashreplace’ error handler is
     used on encoding.

   * Each string is limited to 500 characters.

   * Only the filename, the function name and the line number are
     displayed.  (no source code)

   * It is limited to 100 frames and 100 threads.

   * The order is reversed: the most recent call is shown first.

By default, the Python traceback is written to *note sys.stderr: 318.
To see tracebacks, applications must be run in the terminal.  A log file
can alternatively be passed to *note faulthandler.enable(): 551.

The module is implemented in C, so tracebacks can be dumped on a crash
or when Python is deadlocked.

* Menu:

* Dumping the traceback::
* Fault handler state::
* Dumping the tracebacks after a timeout::
* Dumping the traceback on a user signal::
* Issue with file descriptors::
* 示例: 示例<15>.


File: python.info,  Node: Dumping the traceback,  Next: Fault handler state,  Up: faulthandler --- Dump the Python traceback

5.27.3.1 Dumping the traceback
..............................

 -- 函数: faulthandler.dump_traceback (file=sys.stderr,
          all_threads=True)

     Dump the tracebacks of all threads into `file'.  If `all_threads'
     is ‘False’, dump only the current thread.

     在 3.5 版更改: Added support for passing file descriptor to this
     function.


File: python.info,  Node: Fault handler state,  Next: Dumping the tracebacks after a timeout,  Prev: Dumping the traceback,  Up: faulthandler --- Dump the Python traceback

5.27.3.2 Fault handler state
............................

 -- 函数: faulthandler.enable (file=sys.stderr, all_threads=True)

     Enable the fault handler: install handlers for the ‘SIGSEGV’,
     ‘SIGFPE’, ‘SIGABRT’, ‘SIGBUS’ and ‘SIGILL’ signals to dump the
     Python traceback.  If `all_threads' is ‘True’, produce tracebacks
     for every running thread.  Otherwise, dump only the current thread.

     The `file' must be kept open until the fault handler is disabled:
     see *note issue with file descriptors: 3529.

     在 3.5 版更改: Added support for passing file descriptor to this
     function.

     在 3.6 版更改: On Windows, a handler for Windows exception is also
     installed.

 -- 函数: faulthandler.disable ()

     Disable the fault handler: uninstall the signal handlers installed
     by *note enable(): 551.

 -- 函数: faulthandler.is_enabled ()

     Check if the fault handler is enabled.


File: python.info,  Node: Dumping the tracebacks after a timeout,  Next: Dumping the traceback on a user signal,  Prev: Fault handler state,  Up: faulthandler --- Dump the Python traceback

5.27.3.3 Dumping the tracebacks after a timeout
...............................................

 -- 函数: faulthandler.dump_traceback_later (timeout, repeat=False,
          file=sys.stderr, exit=False)

     Dump the tracebacks of all threads, after a timeout of `timeout'
     seconds, or every `timeout' seconds if `repeat' is ‘True’.  If
     `exit' is ‘True’, call ‘_exit()’ with status=1 after dumping the
     tracebacks.  (Note ‘_exit()’ exits the process immediately, which
     means it doesn’t do any cleanup like flushing file buffers.)  If
     the function is called twice, the new call replaces previous
     parameters and resets the timeout.  The timer has a sub-second
     resolution.

     The `file' must be kept open until the traceback is dumped or *note
     cancel_dump_traceback_later(): 352d. is called: see *note issue
     with file descriptors: 3529.

     This function is implemented using a watchdog thread.

     在 3.7 版更改: This function is now always available.

     在 3.5 版更改: Added support for passing file descriptor to this
     function.

 -- 函数: faulthandler.cancel_dump_traceback_later ()

     Cancel the last call to *note dump_traceback_later(): 6e2.


File: python.info,  Node: Dumping the traceback on a user signal,  Next: Issue with file descriptors,  Prev: Dumping the tracebacks after a timeout,  Up: faulthandler --- Dump the Python traceback

5.27.3.4 Dumping the traceback on a user signal
...............................................

 -- 函数: faulthandler.register (signum, file=sys.stderr,
          all_threads=True, chain=False)

     Register a user signal: install a handler for the `signum' signal
     to dump the traceback of all threads, or of the current thread if
     `all_threads' is ‘False’, into `file'.  Call the previous handler
     if chain is ‘True’.

     The `file' must be kept open until the signal is unregistered by
     *note unregister(): 352f.: see *note issue with file descriptors:
     3529.

     Not available on Windows.

     在 3.5 版更改: Added support for passing file descriptor to this
     function.

 -- 函数: faulthandler.unregister (signum)

     Unregister a user signal: uninstall the handler of the `signum'
     signal installed by *note register(): 6e0.  Return ‘True’ if the
     signal was registered, ‘False’ otherwise.

     Not available on Windows.


File: python.info,  Node: Issue with file descriptors,  Next: 示例<15>,  Prev: Dumping the traceback on a user signal,  Up: faulthandler --- Dump the Python traceback

5.27.3.5 Issue with file descriptors
....................................

*note enable(): 551, *note dump_traceback_later(): 6e2. and *note
register(): 6e0. keep the file descriptor of their `file' argument.  If
the file is closed and its file descriptor is reused by a new file, or
if *note os.dup2(): 3c6. is used to replace the file descriptor, the
traceback will be written into a different file.  Call these functions
again each time that the file is replaced.


File: python.info,  Node: 示例<15>,  Prev: Issue with file descriptors,  Up: faulthandler --- Dump the Python traceback

5.27.3.6 示例
.............

Example of a segmentation fault on Linux with and without enabling the
fault handler:

     $ python3 -c "import ctypes; ctypes.string_at(0)"
     Segmentation fault

     $ python3 -q -X faulthandler
     >>> import ctypes
     >>> ctypes.string_at(0)
     Fatal Python error: Segmentation fault

     Current thread 0x00007fb899f39700 (most recent call first):
       File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at
       File "<stdin>", line 1 in <module>
     Segmentation fault


File: python.info,  Node: pdb --- Python的调试器,  Next: Python Profilers 分析器,  Prev: faulthandler --- Dump the Python traceback,  Up: 调试和分析

5.27.4 ‘pdb’ — Python的调试器
-----------------------------

`源代码：' Lib/pdb.py(1)

__________________________________________________________________

*note pdb: ca. 模块定义了一个交互式源代码调试器，用于 Python 程序。它支
持在源码行间设置（有条件的）断点和单步执行，检视堆栈帧，列出源码列表，以
及在任何堆栈帧的上下文中运行任意 Python 代码。它还支持事后调试，可以在程
序控制下调用。

调试器是可扩展的——调试器实际被定义为 *note Pdb: 575. 类。该类目前没有文
档，但通过阅读源码很容易理解它。扩展接口使用了 *note bdb: f. 和 *note
cmd: 1a. 模块。

调试器的提示符是 ‘(Pdb)’。在调试器的控制下运行程序的典型用法是:

     >>> import pdb
     >>> import mymodule
     >>> pdb.run('mymodule.test()')
     > <string>(0)?()
     (Pdb) continue
     > <string>(1)?()
     (Pdb) continue
     NameError: 'spam'
     > <string>(1)?()
     (Pdb)

在 3.3 版更改: 由 *note readline: df. 模块实现的 Tab 补全可用于补全本模
块的命令和命令的参数，例如，‘p’ 命令的参数可补全为当前的全局变量和局部变
量。

也可以将 ‘pdb.py’ 作为脚本调用来调试其他脚本。例如:

     python3 -m pdb myscript.py

当作为脚本调用时，如果要调试的程序异常退出，pdb 调试将自动进入事后调试。
事后调试之后（或程序正常退出之后），pdb 将重新启动程序。自动重启会保留
pdb 的状态（如断点），在大多数情况下，这比在退出程序的同时退出调试器更加
实用。

3.2 新版功能: ‘pdb.py’ 现在接受 ‘-c’ 选项，可以执行命令，这与将该命令写
入 ‘.pdbrc’ 文件相同，请参阅 *note 调试器命令: 3535.。

3.7 新版功能: ‘pdb.py’ 现在接受 ‘-m’ 选项，该选项用于执行一个模块，类似
于 ‘python3 -m’。与脚本相同，调试器将暂停在待执行模块第一行前。

从正在运行的程序进入调试器的典型用法是插入

     import pdb; pdb.set_trace()

到你想进入调试器的位置。然后就可以单步执行上述语句之后的代码，要关闭调试
器继续运行，请使用 *note continue: 3536. 命令。

3.7 新版功能: 内置函数 *note breakpoint(): 302.，当以默认参数调用它时，
可以用来代替 ‘import pdb; pdb.set_trace()’。

检查已崩溃程序的典型用法是:

     >>> import pdb
     >>> import mymodule
     >>> mymodule.test()
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
       File "./mymodule.py", line 4, in test
         test2()
       File "./mymodule.py", line 3, in test2
         print(spam)
     NameError: spam
     >>> pdb.pm()
     > ./mymodule.py(3)test2()
     -> print(spam)
     (Pdb)

本模块定义了下列函数，每个函数进入调试器的方式略有不同：

 -- 函数: pdb.run (statement, globals=None, locals=None)

     在调试器控制范围内执行 `statement' （以字符串或代码对象的形式提供）
     。调试器提示符会在执行代码前出现，你可以设置断点并键入 *note
     continue: 3536.，也可以使用 *note step: 3537. 或 *note next: 3538.
     逐步执行语句（上述所有命令在后文有说明）。可选参数 `globals' 和
     `locals' 指定代码执行环境，默认时使用 *note __main__: 1. 模块的字典
     。（请参阅内置函数 *note exec(): c4c. 或 *note eval(): b98. 的说明
     。）

 -- 函数: pdb.runeval (expression, globals=None, locals=None)

     在调试器控制范围内执行 `expression' （以字符串或代码对象的形式提供
     ）。*note runeval(): 3539. 返回时将返回表达式的值。本函数在其他方面
     与 *note run(): 3319. 类似。

 -- 函数: pdb.runcall (function, *args, **kwds)

     使用给定的参数调用 `function' （以函数或方法对象的形式提供，不能是
     字符串）。*note runcall(): 353a. 返回的是所调用函数的返回值。调试器
     提示符将在进入函数后立即出现。

 -- 函数: pdb.set_trace (*, header=None)

     在调用本函数的堆栈帧处进入调试器。用于硬编码一个断点到程序中的固定
     点处，即使该代码不在调试状态（如断言失败时）。如果传入 `header'，它
     将在调试开始前被打印到控制台。

     在 3.7 版更改: 仅关键字参数 `header'。

 -- 函数: pdb.post_mortem (traceback=None)

     进入 `traceback' 对象的事后调试。如果没有给定 `traceback'，默认使用
     当前正在处理的异常之一（默认时，必须存在正在处理的异常）。

 -- 函数: pdb.pm ()

     在 *note sys.last_traceback: 353c. 中查找 traceback，并进入其事后调
     试。

‘run*’ 函数和 *note set_trace(): 3ca. 都是别名，用于实例化 *note Pdb:
575. 类和调用同名方法。如果要使用其他功能，则必须自己执行以下操作：

 -- 类: pdb.Pdb (completekey='tab', stdin=None, stdout=None, skip=None,
          nosigint=False, readrc=True)

     *note Pdb: 575. 是调试器类。

     `completekey'、`stdin' 和 `stdout' 参数都会传递给底层的 *note
     cmd.Cmd: 3144. 类，请参考相应的描述。

     如果给出 `skip' 参数，则它必须是一个迭代器，可以迭代出 glob-style 样
     式的模块名称。如果遇到匹配上述样式的模块，调试器将不会进入来自该模
     块的堆栈帧。 (2)

     默认情况下，当发出 ‘continue’ 命令时，Pdb 将为 SIGINT 信号设置一个
     处理程序（SIGINT 信号是用户在控制台按 ‘Ctrl-C’ 时发出的）。这使用户
     可以按 ‘Ctrl-C’ 再次进入调试器。如果希望 Pdb 不要修改 SIGINT 处理程
     序，请将 `nosigint' 设置为 true。

     `readrc' 参数默认为 true，它控制 Pdb 是否从文件系统加载 .pdbrc 文件
     。

     启用跟踪且带有 `skip' 参数的调用示范:

          import pdb; pdb.Pdb(skip=['django.*']).set_trace()

     引发一个 *note 审计事件: ea1. ‘pdb.Pdb’，没有附带参数。

     3.1 新版功能: `skip' 参数。

     3.2 新版功能: `nosigint' 参数。在这之前，Pdb 不为 SIGINT 设置处理程
     序。

     在 3.6 版更改: `readrc' 参数。

      -- 方法: run (statement, globals=None, locals=None)
      -- 方法: runeval (expression, globals=None, locals=None)
      -- 方法: runcall (function, *args, **kwds)
      -- 方法: set_trace ()

          请参阅上文解释同名函数的文档。

* Menu:

* 调试器命令::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/pdb.py

   (2) (1) 一个帧是否会被认为源自特定模块是由帧全局变量 ‘__name__’ 来决
定的。


File: python.info,  Node: 调试器命令,  Up: pdb --- Python的调试器

5.27.4.1 调试器命令
...................

下方列出的是调试器可接受的命令。如下所示，大多数命令可以缩写为一个或两个
字母。如 ‘h(elp)’ 表示可以输入 ‘h’ 或 ‘help’ 来输入帮助命令（但不能输入
‘he’ 或 ‘hel’，也不能是 ‘H’ 或 ‘Help’ 或 ‘HELP’）。命令的参数必须用空格
（空格符或制表符）分隔。在命令语法中，可选参数括在方括号 (‘[]’) 中，使用
时请勿输入方括号。命令语法中的选择项由竖线 (‘|’) 分隔。

输入一个空白行将重复最后输入的命令。例外：如果最后一个命令是 *note list:
3542. 命令，则会列出接下来的 11 行。

调试器无法识别的命令将被认为是 Python 语句，并在正在调试的程序的上下文中
执行。Python 语句也可以用感叹号 (‘!’) 作为前缀。这是检查正在调试的程序的
强大方法，甚至可以修改变量或调用函数。当此类语句发生异常，将打印异常名称
，但调试器的状态不会改变。

调试器支持 *note 别名: 3543.。别名可以有参数，使得调试器对被检查的上下文
有一定程度的适应性。

在一行中可以输入多个命令，以 ‘;;’ 分隔。（不能使用单个 ‘;’，因为它用于分
隔传递给 Python 解释器的一行中的多条语句。）切分命令很无脑，总是在第一个
‘;;’ 对处将输入切分开，即使它位于带引号的字符串之中。

如果文件 ‘.pdbrc’ 存在于用户主目录或当前目录中，则将其读入并执行，等同于
在调试器提示符下键入该文件。这对于别名很有用。若两个文件都存在则首先读取
主目录中的文件，且本地文件可以覆盖其中定义的别名。

在 3.2 版更改: ‘.pdbrc’ 现在可以包含继续调试的命令，如 *note continue:
3536. 或 *note next: 3538.。文件中的这些命令以前是无效的。

 -- Pdbcommand: h(elp) [command]

     不带参数时，显示可用的命令列表。参数为 `command' 时，打印有关该命令
     的帮助。‘help pdb’ 显示完整文档（即 *note pdb: ca. 模块的文档字符串
     ）。由于 `command' 参数必须是标识符，因此要获取 ‘!’ 的帮助必须输入
     ‘help exec’。

 -- Pdbcommand: w(here)

     打印堆栈回溯，最新一帧在底部。有一个箭头指向当前帧，该帧决定了大多
     数命令的上下文。

 -- Pdbcommand: d(own) [count]

     在堆栈回溯中，将当前帧向下移动 `count' 级（默认为 1 级，移向更新的
     帧）。

 -- Pdbcommand: u(p) [count]

     在堆栈回溯中，将当前帧向上移动 `count' 级（默认为 1 级，移向更老的
     帧）。

 -- Pdbcommand: b(reak) [([filename:]lineno | function) [, condition]]

     如果带有 `lineno' 参数，则在当前文件相应行处设置一个断点。如果带有
     `function' 参数，则在该函数的第一条可执行语句处设置一个断点。行号可
     以加上文件名和冒号作为前缀，以在另一个文件（可能是尚未加载的文件）
     中设置一个断点。另一个文件将在 *note sys.path: 490. 范围内搜索。请
     注意，每个断点都分配有一个编号，其他所有断点命令都引用该编号。

     如果第二个参数存在，它应该是一个表达式，且它的计算值为 true 时断点
     才起作用。

     如果不带参数执行，将列出所有中断，包括每个断点、命中该断点的次数、
     当前的忽略次数以及关联的条件（如果有）。

 -- Pdbcommand: tbreak [([filename:]lineno | function) [, condition]]

     临时断点，在第一次命中时会自动删除。它的参数与 *note break: 3548. 相
     同。

 -- Pdbcommand: cl(ear) [filename:lineno | bpnumber [bpnumber ...]]

     如果参数是 `filename:lineno'，则清除此行上的所有断点。如果参数是空
     格分隔的断点编号列表，则清除这些断点。如果不带参数，则清除所有断点
     （但会先提示确认）。

 -- Pdbcommand: disable [bpnumber [bpnumber ...]]

     禁用断点，断点以空格分隔的断点编号列表给出。禁用断点表示它不会导致
     程序停止执行，但是与清除断点不同，禁用的断点将保留在断点列表中并且
     可以（重新）启用。

 -- Pdbcommand: enable [bpnumber [bpnumber ...]]

     启用指定的断点。

 -- Pdbcommand: ignore bpnumber [count]

     为指定的断点编号设置忽略次数。如果省略 count，则忽略次数将设置为 0。
     忽略次数为 0 时断点将变为活动状态。如果为非零值，在每次达到断点，且
     断点未禁用，且关联条件计算值为 true 的情况下，该忽略次数会递减。

 -- Pdbcommand: condition bpnumber [condition]

     为断点设置一个新 `condition'，它是一个表达式，且它的计算值为 true 时
     断点才起作用。如果没有给出 `condition'，则删除现有条件，也就是将断
     点设为无条件。

 -- Pdbcommand: commands [bpnumber]

     为编号是 `bpnumber' 的断点指定一系列命令。命令内容将显示在后续的几
     行中。输入仅包含 ‘end’ 的行来结束命令列表。举个例子:

          (Pdb) commands 1
          (com) p some_variable
          (com) end
          (Pdb)

     要删除断点上的所有命令，请输入 ‘commands’ 并立即以 ‘end’ 结尾，也就
     是不指定任何命令。

     如果不带 `bpnumber' 参数，‘commands’ 作用于最后一个被设置的断点。

     可以使用断点命令来重新启动程序。只需使用 *note continue: 3536. 或
     *note step: 3537. 命令或其他可以恢复运行的命令。

     如果指定了某个继续运行程序的命令（目前包括 *note continue: 3536,
     *note step: 3537, *note next: 3538, *note return: 3550, *note jump:
     3551, *note quit: 3552. 及它们的缩写）将终止命令列表（就像该命令后
     紧跟着 end）。因为在任何时候继续运行下去（即使是简单的 next 或
     step），都可能会遇到另一个断点，该断点可能具有自己的命令列表，这导
     致要执行的列表含糊不清。

     如果在命令列表中加入 ’silent’ 命令，那么在该断点处停下时就不会打印
     常规信息。如果希望断点打印特定信息后继续运行，这可能是理想的。如果
     没有其他命令来打印一些信息，则看不到已达到断点的迹象。

 -- Pdbcommand: s(tep)

     执行当前行，在第一个可以停止的位置（在调用的函数中或在当前函数的下
     一行）停下。

 -- Pdbcommand: n(ext)

     继续运行，直到运行到当前函数的下一行，或当前函数返回为止。（ *note
     next: 3538. 和 *note step: 3537. 之间的区别在于，*note step: 3537.
     进入被调用函数内部并停止，而 *note next: 3538. （几乎）全速运行被调
     用函数，仅在当前函数的下一行停止。）

 -- Pdbcommand: unt(il) [lineno]

     如果不带参数，则继续运行，直到行号比当前行大时停止。

     如果带有行号，则继续运行，直到行号大于或等于该行号时停止。在这两种
     情况下，当前帧返回时也将停止。

     在 3.2 版更改: 允许明确给定行号。

 -- Pdbcommand: r(eturn)

     继续运行，直到当前函数返回。

 -- Pdbcommand: c(ont(inue))

     继续运行，仅在遇到断点时停止。

 -- Pdbcommand: j(ump) lineno

     设置即将运行的下一行。仅可用于堆栈最底部的帧。它可以往回跳来再次运
     行代码，也可以往前跳来跳过不想运行的代码。

     需要注意的是，不是所有的跳转都是允许的 – 例如，不能跳转到 *note
     for: c38. 循环的中间或跳出 *note finally: 183. 子句。

 -- Pdbcommand: l(ist) [first[, last]]

     列出当前文件的源代码。如果不带参数，则列出当前行周围的 11 行，或继
     续前一个列表。如果用 ‘.’ 作为参数，则列出当前行周围的 11 行。如果带
     有一个参数，则列出那一行周围的 11 行。如果带有两个参数，则列出所给
     的范围中的代码；如果第二个参数小于第一个参数，则将其解释为列出行数
     的计数。

     当前帧中的当前行用 ‘->’ 标记。如果正在调试异常，且最早抛出或传递该
     异常的行不是当前行，则那一行用 ‘>>’ 标记。

     3.2 新版功能: ‘>>’ 标记。

 -- Pdbcommand: ll | longlist

     列出当前函数或帧的所有源代码。相关行的标记与 *note list: 3542. 相同
     。

     3.2 新版功能.

 -- Pdbcommand: a(rgs)

     打印当前函数的参数列表。

 -- Pdbcommand: p expression

     在当前上下文中运行 `expression' 并打印它的值。

          注解: ‘print()’ 也可以使用，但它不是一个调试器命令 — 它执行
          Python *note print(): 88f. 函数。

 -- Pdbcommand: pp expression

     与 *note p: 890. 命令类似，但表达式的值使用 *note pprint: d3. 模块
     美观地打印。

 -- Pdbcommand: whatis expression

     打印 `expression' 的类型。

 -- Pdbcommand: source expression

     尝试获取给定对象的源代码并显示出来。

     3.2 新版功能.

 -- Pdbcommand: display [expression]

     如果表达式的值发生改变则显示它的值，每次将停止执行当前帧。

     不带表达式则列出当前帧的所有显示表达式。

     3.2 新版功能.

 -- Pdbcommand: undisplay [expression]

     不再显示当前帧中的表达式。 不带表达式则清除当前帧的所有显示表达式。

     3.2 新版功能.

 -- Pdbcommand: interact

     启动一个交互式解释器（使用 *note code: 1b. 模块），它的全局命名空间
     将包含当前作用域中的所有（全局和局部）名称。

     3.2 新版功能.

 -- Pdbcommand: alias [name [command]]

     创建一个标识为 `name' 的别名来执行 `command'。 执行的命令 `不可' 加
     上引号。 可替换形参可通过 ‘%1’, ‘%2’ 等来标示，而 ‘%*’ 会被所有形参
     所替换。 如果没有给出命令，则会显示 `name' 的当前别名。 如果没有给
     出参数，则会列出所有别名。

     别名允许嵌套并可包含能在 pdb 提示符下合法输入的任何内容。 请注意内
     部 pdb 命令 `可以' 被别名所覆盖。 这样的命令将被隐藏直到别名被移除
     。 别名会递归地应用到命令行的第一个单词；行内的其他单词不会受影响。

     作为示例，这里列出了两个有用的别名（特别适合放在 ‘.pdbrc’ 文件中）:

          # Print instance variables (usage "pi classInst")
          alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])
          # Print instance variables in self
          alias ps pi self

 -- Pdbcommand: unalias name

     删除指定的别名。

 -- Pdbcommand: ! statement

     在当前堆栈帧的上下文中执行 (单行) `statement'。 感叹号可以被省略，
     除非语句的第一个单词与调试器命令重名。 要设置全局变量，你可以在同一
     行上为赋值命令添加前缀的 *note global: 1254. 语句，例如:

          (Pdb) global list_options; list_options = ['-l']
          (Pdb)

 -- Pdbcommand: run [args ...]
 -- Pdbcommand: restart [args ...]

     重启被调试的 Python 程序。 如果提供了参数，它会用 *note shlex: e9.
     来拆分且拆分结果将被用作新的 *note sys.argv: c03.。 历史、中断点、
     动作和调试器选项将被保留。 *note restart: 3560. 是 *note run: 355f.
     的一个别名。

 -- Pdbcommand: q(uit)

     退出调试器。 被执行的程序将被中止。

 -- Pdbcommand: debug code

     进入一个对代码参数执行步进的递归调试器（该参数是在当前环境中执行的
     任意表达式或语句）。

 -- Pdbcommand: retval

     打印函数最后一次返回的返回值。

备注
....


File: python.info,  Node: Python Profilers 分析器,  Next: timeit --- 测量小代码片段的执行时间,  Prev: pdb --- Python的调试器,  Up: 调试和分析

5.27.5 Python Profilers 分析器
------------------------------

`源代码：' Lib/profile.py(1) 和 Lib/pstats.py(2)

__________________________________________________________________

* Menu:

* profile分析器简介::
* 实时用户手册::
* profile 和 cProfile 模块参考::
* Stats 类::
* 什么是确定性性能分析？::
* 局限性::
* 准确估量::
* 使用自定义计时器::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/profile.py

   (2) https://github.com/python/cpython/tree/3.8/Lib/pstats.py


File: python.info,  Node: profile分析器简介,  Next: 实时用户手册,  Up: Python Profilers 分析器

5.27.5.1 profile分析器简介
..........................

*note cProfile: 28. 和 *note profile: d4. 提供了 Python 程序的 `确定性性
能分析' 。 `profile' 是一组统计数据，描述程序的各个部分执行的频率和时间
。这些统计数据可以通过 *note pstats: d5. 模块格式化为报表。

Python 标准库提供了同一分析接口的两种不同实现：

  1. 对于大多数用户，建议使用 *note cProfile: 28. ；这是一个 C 扩展插件
     ，因为其合理的运行开销，所以适合于分析长时间运行的程序。该插件基于
     ‘lsprof’ ，由 Brett Rosen 和 Ted Chaotter 贡献。

  2. *note profile: d4. 是一个纯 Python 模块（*note cProfile: 28. 就是模
     拟其接口的 C 语言实现），但它会显著增加配置程序的开销。如果你正在尝
     试以某种方式扩展分析器，则使用此模块可能会更容易完成任务。该模块最
     初由 Jim Roskind 设计和编写。

     注解: profiler 分析器模块被设计为给指定的程序提供执行概要文件，而不
     是用于基准测试目的（ *note timeit: 10c. 才是用于此目标的，它能获得
     合理准确的结果）。这特别适用于将 Python 代码与 C 代码进行基准测试：
     分析器为Python 代码引入开销，但不会为 C级别的函数引入开销，因此 C 代
     码似乎比任何Python 代码都更快。


File: python.info,  Node: 实时用户手册,  Next: profile 和 cProfile 模块参考,  Prev: profile分析器简介,  Up: Python Profilers 分析器

5.27.5.2 实时用户手册
.....................

本节是为 “不想阅读手册” 的用户提供的。它提供了非常简短的概述，并允许用户
快速对现有应用程序执行评测。

要分析采用单个参数的函数，可以执行以下操作：

     import cProfile
     import re
     cProfile.run('re.compile("foo|bar")')

（如果 *note cProfile: 28. 在您的系统上不可用，请使用 *note profile: d4.
。）

上述操作将运行 *note re.compile(): 452. 并打印分析结果，如下所示：

           197 function calls (192 primitive calls) in 0.002 seconds

     Ordered by: standard name

     ncalls  tottime  percall  cumtime  percall filename:lineno(function)
          1    0.000    0.000    0.001    0.001 <string>:1(<module>)
          1    0.000    0.000    0.001    0.001 re.py:212(compile)
          1    0.000    0.000    0.001    0.001 re.py:268(_compile)
          1    0.000    0.000    0.000    0.000 sre_compile.py:172(_compile_charset)
          1    0.000    0.000    0.000    0.000 sre_compile.py:201(_optimize_charset)
          4    0.000    0.000    0.000    0.000 sre_compile.py:25(_identityfunction)
        3/1    0.000    0.000    0.000    0.000 sre_compile.py:33(_compile)

第一行显示监听了197个调用。在这些调用中，有192个是 `原始的' ，这意味着调
用不是通过递归引发的。下一行: ‘Ordered by: standard name’ ，表示最右边列
中的文本字符串用于对输出进行排序。列标题包括：

ncalls

     调用次数

tottime

     在指定函数中消耗的总时间（不包括调用子函数的时间）

percall

     是 ‘tottime’ 除以 ‘ncalls’ 的商

cumtime

     指定的函数及其所有子函数（从调用到退出）消耗的累积时间。这个数字对
     于递归函数来说是准确的。

percall

     是 ‘cumtime’ 除以原始调用（次数）的商（即：函数运行一次的平均时间）

filename:lineno(function)

     提供相应数据的每个函数

如果第一列中有两个数字（例如3/1），则表示函数递归。第二个值是原始调用次
数，第一个是调用的总次数。请注意，当函数不递归时，这两个值是相同的，并且
只打印单个数字。

profile 运行结束时，打印输出不是必须的。也可以通过为 ‘run()’ 函数指定文
件名，将结果保存到文件中：

     import cProfile
     import re
     cProfile.run('re.compile("foo|bar")', 'restats')

*note pstats.Stats: 356a. 类从文件中读取 profile 结果，并以各种方式对其
进行格式化。

*note cProfile: 28. 和 *note profile: d4. 文件也可以作为脚本调用，以分析
另一个脚本。例如：

     python -m cProfile [-o output_file] [-s sort_order] (-m module | myscript.py)

‘-o’ 将profile 结果写入文件而不是标准输出

‘-s’ 指定 *note sort_stats(): 356b. 排序值之一以对输出进行排序。这仅适用
于未提供 ‘-o’ 的情况

‘-m’ 指定要分析的是模块而不是脚本。

     3.7 新版功能: *note cProfile: 28. 添加 ‘-m’ 选项

     3.8 新版功能: *note profile: d4. 添加 ‘-m’ 选项

The *note pstats: d5. module’s *note Stats: 356a. class has a variety of
methods for manipulating and printing the data saved into a profile
results file:

     import pstats
     from pstats import SortKey
     p = pstats.Stats('restats')
     p.strip_dirs().sort_stats(-1).print_stats()

The *note strip_dirs(): 356c. method removed the extraneous path from
all the module names.  The *note sort_stats(): 356b. method sorted all
the entries according to the standard module/line/name string that is
printed.  The *note print_stats(): 356d. method printed out all the
statistics.  You might try the following sort calls:

     p.sort_stats(SortKey.NAME)
     p.print_stats()

The first call will actually sort the list by function name, and the
second call will print out the statistics.  The following are some
interesting calls to experiment with:

     p.sort_stats(SortKey.CUMULATIVE).print_stats(10)

This sorts the profile by cumulative time in a function, and then only
prints the ten most significant lines.  If you want to understand what
algorithms are taking time, the above line is what you would use.

If you were looking to see what functions were looping a lot, and taking
a lot of time, you would do:

     p.sort_stats(SortKey.TIME).print_stats(10)

to sort according to time spent within each function, and then print the
statistics for the top ten functions.

你也可以尝试：

     p.sort_stats(SortKey.FILENAME).print_stats('__init__')

This will sort all the statistics by file name, and then print out
statistics for only the class init methods (since they are spelled with
‘__init__’ in them).  As one final example, you could try:

     p.sort_stats(SortKey.TIME, SortKey.CUMULATIVE).print_stats(.5, 'init')

This line sorts statistics with a primary key of time, and a secondary
key of cumulative time, and then prints out some of the statistics.  To
be specific, the list is first culled down to 50% (re: ‘.5’) of its
original size, then only lines containing ‘init’ are maintained, and
that sub-sub-list is printed.

If you wondered what functions called the above functions, you could now
(‘p’ is still sorted according to the last criteria) do:

     p.print_callers(.5, 'init')

and you would get a list of callers for each of the listed functions.

If you want more functionality, you’re going to have to read the manual,
or guess what the following functions do:

     p.print_callees()
     p.add('restats')

Invoked as a script, the *note pstats: d5. module is a statistics
browser for reading and examining profile dumps.  It has a simple
line-oriented interface (implemented using *note cmd: 1a.) and
interactive help.


File: python.info,  Node: profile 和 cProfile 模块参考,  Next: Stats 类,  Prev: 实时用户手册,  Up: Python Profilers 分析器

5.27.5.3 ‘profile’ 和 ‘cProfile’ 模块参考
.........................................

*note profile: d4. 和 *note cProfile: 28. 模块都提供下列函数：

 -- 函数: profile.run (command, filename=None, sort=-1)

     This function takes a single argument that can be passed to the
     *note exec(): c4c. function, and an optional file name.  In all
     cases this routine executes:

          exec(command, __main__.__dict__, __main__.__dict__)

     and gathers profiling statistics from the execution.  If no file
     name is present, then this function automatically creates a *note
     Stats: 356a. instance and prints a simple profiling report.  If the
     sort value is specified, it is passed to this *note Stats: 356a.
     instance to control how the results are sorted.

 -- 函数: profile.runctx (command, globals, locals, filename=None,
          sort=-1)

     This function is similar to *note run(): 356f, with added arguments
     to supply the globals and locals dictionaries for the `command'
     string.  This routine executes:

          exec(command, globals, locals)

     and gathers profiling statistics as in the *note run(): 356f.
     function above.

 -- 类: profile.Profile (timer=None, timeunit=0.0, subcalls=True,
          builtins=True)

     This class is normally only used if more precise control over
     profiling is needed than what the ‘cProfile.run()’ function
     provides.

     A custom timer can be supplied for measuring how long code takes to
     run via the `timer' argument.  This must be a function that returns
     a single number representing the current time.  If the number is an
     integer, the `timeunit' specifies a multiplier that specifies the
     duration of each unit of time.  For example, if the timer returns
     times measured in thousands of seconds, the time unit would be
     ‘.001’.

     Directly using the *note Profile: 1bc. class allows formatting
     profile results without writing the profile data to a file:

          import cProfile, pstats, io
          from pstats import SortKey
          pr = cProfile.Profile()
          pr.enable()
          # ... do something ...
          pr.disable()
          s = io.StringIO()
          sortby = SortKey.CUMULATIVE
          ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
          ps.print_stats()
          print(s.getvalue())

     The *note Profile: 1bc. class can also be used as a context manager
     (supported only in *note cProfile: 28. module.  see *note
     上下文管理器类型: 1498.):

          import cProfile

          with cProfile.Profile() as pr:
              # ... do something ...

          pr.print_stats()

     在 3.8 版更改: 添加了上下文管理器支持。

      -- 方法: enable ()

          开始收集分析数据。仅在 *note cProfile: 28. 可用。

      -- 方法: disable ()

          停止收集分析数据。仅在 *note cProfile: 28. 可用。

      -- 方法: create_stats ()

          停止收集分析数据，并在内部将结果记录为当前 profile。

      -- 方法: print_stats (sort=-1)

          Create a *note Stats: 356a. object based on the current
          profile and print the results to stdout.

      -- 方法: dump_stats (filename)

          将当前profile 的结果写入 `filename' 。

      -- 方法: run (cmd)

          Profile the cmd via *note exec(): c4c.

      -- 方法: runctx (cmd, globals, locals)

          Profile the cmd via *note exec(): c4c. with the specified
          global and local environment.

      -- 方法: runcall (func, *args, **kwargs)

          Profile ‘func(*args, **kwargs)’

Note that profiling will only work if the called command/function
actually returns.  If the interpreter is terminated (e.g.  via a *note
sys.exit(): cea. call during the called command/function execution) no
profiling results will be printed.


File: python.info,  Node: Stats 类,  Next: 什么是确定性性能分析？,  Prev: profile 和 cProfile 模块参考,  Up: Python Profilers 分析器

5.27.5.4 ‘Stats’ 类
...................

Analysis of the profiler data is done using the *note Stats: 356a.
class.

 -- 类: pstats.Stats (*filenames or profile, stream=sys.stdout)

     This class constructor creates an instance of a "statistics object"
     from a `filename' (or list of filenames) or from a ‘Profile’
     instance.  Output will be printed to the stream specified by
     `stream'.

     The file selected by the above constructor must have been created
     by the corresponding version of *note profile: d4. or *note
     cProfile: 28.  To be specific, there is `no' file compatibility
     guaranteed with future versions of this profiler, and there is no
     compatibility with files produced by other profilers, or the same
     profiler run on a different operating system.  If several files are
     provided, all the statistics for identical functions will be
     coalesced, so that an overall view of several processes can be
     considered in a single report.  If additional files need to be
     combined with data in an existing *note Stats: 356a. object, the
     *note add(): 357a. method can be used.

     Instead of reading the profile data from a file, a
     ‘cProfile.Profile’ or *note profile.Profile: 1bc. object can be
     used as the profile data source.

     *note Stats: 356a. 对象有以下方法:

      -- 方法: strip_dirs ()

          This method for the *note Stats: 356a. class removes all
          leading path information from file names.  It is very useful
          in reducing the size of the printout to fit within (close to)
          80 columns.  This method modifies the object, and the stripped
          information is lost.  After performing a strip operation, the
          object is considered to have its entries in a "random" order,
          as it was just after object initialization and loading.  If
          *note strip_dirs(): 356c. causes two function names to be
          indistinguishable (they are on the same line of the same
          filename, and have the same function name), then the
          statistics for these two entries are accumulated into a single
          entry.

      -- 方法: add (*filenames)

          This method of the *note Stats: 356a. class accumulates
          additional profiling information into the current profiling
          object.  Its arguments should refer to filenames created by
          the corresponding version of *note profile.run(): 356f. or
          ‘cProfile.run()’.  Statistics for identically named (re: file,
          line, name) functions are automatically accumulated into
          single function statistics.

      -- 方法: dump_stats (filename)

          Save the data loaded into the *note Stats: 356a. object to a
          file named `filename'.  The file is created if it does not
          exist, and is overwritten if it already exists.  This is
          equivalent to the method of the same name on the *note
          profile.Profile: 1bc. and ‘cProfile.Profile’ classes.

      -- 方法: sort_stats (*keys)

          This method modifies the *note Stats: 356a. object by sorting
          it according to the supplied criteria.  The argument can be
          either a string or a SortKey enum identifying the basis of a
          sort (example: ‘'time'’, ‘'name'’, ‘SortKey.TIME’ or
          ‘SortKey.NAME’).  The SortKey enums argument have advantage
          over the string argument in that it is more robust and less
          error prone.

          When more than one key is provided, then additional keys are
          used as secondary criteria when there is equality in all keys
          selected before them.  For example, ‘sort_stats(SortKey.NAME,
          SortKey.FILE)’ will sort all the entries according to their
          function name, and resolve all ties (identical function names)
          by sorting by file name.

          For the string argument, abbreviations can be used for any key
          names, as long as the abbreviation is unambiguous.

          The following are the valid string and SortKey:

          有效字符串参数         有效枚举参数              含义
                                                           
          ----------------------------------------------------------------------------
                                                           
          ‘'calls'’              SortKey.CALLS             调用次数
                                                           
                                                           
          ‘'cumulative'’         SortKey.CUMULATIVE        累积时间
                                                           
                                                           
          ‘'cumtime'’            N/A                       累积时间
                                                           
                                                           
          ‘'file'’               N/A                       文件名
                                                           
                                                           
          ‘'filename'’           SortKey.FILENAME          文件名
                                                           
                                                           
          ‘'module'’             N/A                       文件名
                                                           
                                                           
          ‘'ncalls'’             N/A                       调用次数
                                                           
                                                           
          ‘'pcalls'’             SortKey.PCALLS            原始调用计数
                                                           
                                                           
          ‘'line'’               SortKey.LINE              行号
                                                           
                                                           
          ‘'name'’               SortKey.NAME              函数名称
                                                           
                                                           
          ‘'nfl'’                SortKey.NFL               名称/文件/行
                                                           
                                                           
          ‘'stdname'’            SortKey.STDNAME           标准名称
                                                           
                                                           
          ‘'time'’               SortKey.TIME              内部时间
                                                           
                                                           
          ‘'tottime'’            N/A                       内部时间
                                                           

          Note that all sorts on statistics are in descending order
          (placing most time consuming items first), where as name,
          file, and line number searches are in ascending order
          (alphabetical).  The subtle distinction between ‘SortKey.NFL’
          and ‘SortKey.STDNAME’ is that the standard name is a sort of
          the name as printed, which means that the embedded line
          numbers get compared in an odd way.  For example, lines 3, 20,
          and 40 would (if the file names were the same) appear in the
          string order 20, 3 and 40.  In contrast, ‘SortKey.NFL’ does a
          numeric compare of the line numbers.  In fact,
          ‘sort_stats(SortKey.NFL)’ is the same as
          ‘sort_stats(SortKey.NAME, SortKey.FILENAME, SortKey.LINE)’.

          For backward-compatibility reasons, the numeric arguments
          ‘-1’, ‘0’, ‘1’, and ‘2’ are permitted.  They are interpreted
          as ‘'stdname'’, ‘'calls'’, ‘'time'’, and ‘'cumulative'’
          respectively.  If this old style format (numeric) is used,
          only one sort key (the numeric key) will be used, and
          additional arguments will be silently ignored.

          3.7 新版功能: Added the SortKey enum.

      -- 方法: reverse_order ()

          This method for the *note Stats: 356a. class reverses the
          ordering of the basic list within the object.  Note that by
          default ascending vs descending order is properly selected
          based on the sort key of choice.

      -- 方法: print_stats (*restrictions)

          This method for the *note Stats: 356a. class prints out a
          report as described in the *note profile.run(): 356f.
          definition.

          The order of the printing is based on the last *note
          sort_stats(): 356b. operation done on the object (subject to
          caveats in *note add(): 357a. and *note strip_dirs(): 356c.).

          The arguments provided (if any) can be used to limit the list
          down to the significant entries.  Initially, the list is taken
          to be the complete set of profiled functions.  Each
          restriction is either an integer (to select a count of lines),
          or a decimal fraction between 0.0 and 1.0 inclusive (to select
          a percentage of lines), or a string that will interpreted as a
          regular expression (to pattern match the standard name that is
          printed).  If several restrictions are provided, then they are
          applied sequentially.  For example:

               print_stats(.1, 'foo:')

          would first limit the printing to first 10% of list, and then
          only print functions that were part of filename ‘.*foo:’.  In
          contrast, the command:

               print_stats('foo:', .1)

          would limit the list to all functions having file names
          ‘.*foo:’, and then proceed to only print the first 10% of
          them.

      -- 方法: print_callers (*restrictions)

          This method for the *note Stats: 356a. class prints a list of
          all functions that called each function in the profiled
          database.  The ordering is identical to that provided by *note
          print_stats(): 356d, and the definition of the restricting
          argument is also identical.  Each caller is reported on its
          own line.  The format differs slightly depending on the
          profiler that produced the stats:

             * With *note profile: d4, a number is shown in parentheses
               after each caller to show how many times this specific
               call was made.  For convenience, a second
               non-parenthesized number repeats the cumulative time
               spent in the function at the right.

             * With *note cProfile: 28, each caller is preceded by three
               numbers: the number of times this specific call was made,
               and the total and cumulative times spent in the current
               function while it was invoked by this specific caller.

      -- 方法: print_callees (*restrictions)

          This method for the *note Stats: 356a. class prints a list of
          all function that were called by the indicated function.
          Aside from this reversal of direction of calls (re: called vs
          was called by), the arguments and ordering are identical to
          the *note print_callers(): 357d. method.


File: python.info,  Node: 什么是确定性性能分析？,  Next: 局限性,  Prev: Stats 类,  Up: Python Profilers 分析器

5.27.5.5 什么是确定性性能分析？
...............................

`确定性性能分析' 旨在反映这样一个事实：即所有 `函数调用' 、 `函数返回' 和
`异常' 事件都被监控，并且对这些事件之间的间隔（在此期间用户的代码正在执
行）进行精确计时。相反，统计分析（不是由该模块完成）随机采样有效指令指针
，并推断时间花费在哪里。后一种技术传统上涉及较少的开销（因为代码不需要检
测），但只提供了时间花在哪里的相对指示。

在Python中，由于在执行过程中总有一个活动的解释器，因此执行确定性评测不需
要插入指令的代码。Python 自动为每个事件提供一个:dfn:‘钩子’ （可选回调）
。此外，Python 的解释特性往往会给执行增加太多开销，以至于在典型的应用程
序中，确定性分析往往只会增加很小的处理开销。结果是，确定性分析并没有那么
代价高昂，但是它提供了有关 Python 程序执行的大量运行时统计信息。

调用计数统计信息可用于识别代码中的错误（意外计数），并识别可能的内联扩展
点（高频调用）。内部时间统计可用于识别应仔细优化的 "热循环" 。累积时间统
计可用于识别算法选择上的高级别错误。请注意，该分析器中对累积时间的异常处
理，允许直接比较算法的递归实现与迭代实现的统计信息。


File: python.info,  Node: 局限性,  Next: 准确估量,  Prev: 什么是确定性性能分析？,  Up: Python Profilers 分析器

5.27.5.6 局限性
...............

一个限制是关于时间信息的准确性。确定性性能分析存在一个涉及精度的基本问题
。最明显的限制是，底层的 "时钟" 周期大约为0.001秒（通常）。因此，没有什
么测量会比底层时钟更精确。如果进行了足够的测量，那么 "误差" 将趋于平均。
不幸的是，删除第一个错误会导致第二个错误来源。

第二个问题是，从调度事件到分析器调用获取时间函数实际 `获取' 时钟状态，这
需要 "一段时间" 。类似地，从获取时钟值（然后保存）开始，直到再次执行用户
代码为止，退出分析器事件句柄时也存在一定的延迟。因此，多次调用单个函数或
调用多个函数通常会累积此错误。尽管这种方式的误差通常小于时钟的精度（小于
一个时钟周期），但它 `可以' 累积并变得非常可观。

与开销较低的 *note cProfile: 28. 相比， *note profile: d4. 的问题更为严
重。出于这个原因， *note profile: d4. 提供了一种针对指定平台的自我校准方
法，以便可以在很大程度上（平均地）消除此误差。 校准后，结果将更准确（在
最小二乘意义上），但它有时会产生负数（当调用计数异常低，且概率之神对您不
利时：-）。因此 `不要' 对产生的负数感到惊慌。它们应该只在你手工校准分析
器的情况下才会出现，实际上结果比没有校准的情况要好。


File: python.info,  Node: 准确估量,  Next: 使用自定义计时器,  Prev: 局限性,  Up: Python Profilers 分析器

5.27.5.7 准确估量
.................

*note profile: d4. 模块的 profiler 会从每个事件处理时间中减去一个常量，
以补偿调用 time 函数和存储结果的开销。默认情况下，常数为0。对于特定的平
台，可用以下程序获得更好修正常数（ *note 局限性: 3582. ）。

     import profile
     pr = profile.Profile()
     for i in range(5):
         print(pr.calibrate(10000))

The method executes the number of Python calls given by the argument,
directly and again under the profiler, measuring the time for both.  It
then computes the hidden overhead per profiler event, and returns that
as a float.  For example, on a 1.8Ghz Intel Core i5 running Mac OS X,
and using Python’s time.process_time() as the timer, the magical number
is about 4.04e-6.

The object of this exercise is to get a fairly consistent result.  If
your computer is `very' fast, or your timer function has poor
resolution, you might have to pass 100000, or even 1000000, to get
consistent results.

当你有一个一致的答案时，有三种方法可以使用：

     import profile

     # 1. Apply computed bias to all Profile instances created hereafter.
     profile.Profile.bias = your_computed_bias

     # 2. Apply computed bias to a specific Profile instance.
     pr = profile.Profile()
     pr.bias = your_computed_bias

     # 3. Specify computed bias in instance constructor.
     pr = profile.Profile(bias=your_computed_bias)

If you have a choice, you are better off choosing a smaller constant,
and then your results will "less often" show up as negative in profile
statistics.


File: python.info,  Node: 使用自定义计时器,  Prev: 准确估量,  Up: Python Profilers 分析器

5.27.5.8 使用自定义计时器
.........................

If you want to change how current time is determined (for example, to
force use of wall-clock time or elapsed process time), pass the timing
function you want to the ‘Profile’ class constructor:

     pr = profile.Profile(your_time_func)

The resulting profiler will then call ‘your_time_func’.  Depending on
whether you are using *note profile.Profile: 1bc. or ‘cProfile.Profile’,
‘your_time_func’’s return value will be interpreted differently:

*note profile.Profile: 1bc.

     ‘your_time_func’ should return a single number, or a list of
     numbers whose sum is the current time (like what *note os.times():
     a64. returns).  If the function returns a single time number, or
     the list of returned numbers has length 2, then you will get an
     especially fast version of the dispatch routine.

     Be warned that you should calibrate the profiler class for the
     timer function that you choose (see *note 准确估量: 3584.).  For
     most machines, a timer that returns a lone integer value will
     provide the best results in terms of low overhead during profiling.
     (*note os.times(): a64. is `pretty' bad, as it returns a tuple of
     floating point values).  If you want to substitute a better timer
     in the cleanest fashion, derive a class and hardwire a replacement
     dispatch method that best handles your timer call, along with the
     appropriate calibration constant.

‘cProfile.Profile’

     ‘your_time_func’ should return a single number.  If it returns
     integers, you can also invoke the class constructor with a second
     argument specifying the real duration of one unit of time.  For
     example, if ‘your_integer_time_func’ returns times measured in
     thousands of seconds, you would construct the ‘Profile’ instance as
     follows:

          pr = cProfile.Profile(your_integer_time_func, 0.001)

     As the ‘cProfile.Profile’ class cannot be calibrated, custom timer
     functions should be used with care and should be as fast as
     possible.  For the best results with a custom timer, it might be
     necessary to hard-code it in the C source of the internal ‘_lsprof’
     module.

Python 3.3 adds several new functions in *note time: 10b. that can be
used to make precise measurements of process or wall-clock time.  For
example, see *note time.perf_counter(): 2ab.


File: python.info,  Node: timeit --- 测量小代码片段的执行时间,  Next: trace --- 跟踪Python语句的执行,  Prev: Python Profilers 分析器,  Up: 调试和分析

5.27.6 ‘timeit’ — 测量小代码片段的执行时间
------------------------------------------

`源码：' Lib/timeit.py(1)

__________________________________________________________________

该模块提供了一种简单的方法来计算一小段 Python 代码的耗时。它有 *note
命令行界面: 3589. 以及一个 *note 可调用: 358a. 方法。它避免了许多用于测
量执行时间的常见陷阱。另见 Tim Peters 对 O’Reilly 出版的 `Python
Cookbook' 中“算法”章节的介绍。

* Menu:

* 基本示例: 基本示例<2>.
* Python 接口::
* 命令行界面: 命令行界面<6>.
* 例子: 例子<25>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/timeit.py


File: python.info,  Node: 基本示例<2>,  Next: Python 接口,  Up: timeit --- 测量小代码片段的执行时间

5.27.6.1 基本示例
.................

以下示例显示了如何使用 *note 命令行界面: 3589. 来比较三个不同的表达式：

     $ python3 -m timeit '"-".join(str(n) for n in range(100))'
     10000 loops, best of 5: 30.2 usec per loop
     $ python3 -m timeit '"-".join([str(n) for n in range(100)])'
     10000 loops, best of 5: 27.5 usec per loop
     $ python3 -m timeit '"-".join(map(str, range(100)))'
     10000 loops, best of 5: 23.2 usec per loop

这可以通过 *note Python 接口: 358a. 实现

     >>> import timeit
     >>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
     0.3018611848820001
     >>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
     0.2727368790656328
     >>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
     0.23702679807320237

从 *note Python 接口: 358a. 还可以传出一个可调用对象:

     >>> timeit.timeit(lambda: "-".join(map(str, range(100))), number=10000)
     0.19665591977536678

但请注意 *note timeit(): 77a. 仅在使用命令行界面时会自动确定重复次数。 在
*note 例子: 358c. 一节你可以找到更多的进阶示例。


File: python.info,  Node: Python 接口,  Next: 命令行界面<6>,  Prev: 基本示例<2>,  Up: timeit --- 测量小代码片段的执行时间

5.27.6.2 Python 接口
....................

该模块定义了三个便利函数和一个公共类：

 -- 函数: timeit.timeit (stmt='pass', setup='pass', timer=<default
          timer>, number=1000000, globals=None)

     使用给定语句、 `setup' 代码和 `timer' 函数创建一个 *note Timer:
     358e. 实例，并执行 `number' 次其 *note timeit(): 5a5. 方法。可选的
     `globals' 参数指定用于执行代码的命名空间。

     在 3.5 版更改: 添加可选参数 `globals' 。

 -- 函数: timeit.repeat (stmt='pass', setup='pass', timer=<default
          timer>, repeat=5, number=1000000, globals=None)

     使用给定语句、 `setup' 代码和 `timer' 函数创建一个 *note Timer:
     358e. 实例，并使用给定的 `repeat' 计数和 `number' 执行运行其 *note
     repeat(): 3590. 方法。可选的 `globals' 参数指定用于执行代码的命名空
     间。

     在 3.5 版更改: 添加可选参数 `globals' 。

     在 3.7 版更改: `repeat' 的默认值由 3 更改为 5 。

 -- 函数: timeit.default_timer ()

     默认的计时器，总是 *note time.perf_counter(): 2ab. 。

     在 3.3 版更改: *note time.perf_counter(): 2ab. 现在是默认计时器。

 -- 类: timeit.Timer (stmt='pass', setup='pass', timer=<timer function>,
          globals=None)

     用于小代码片段的计数执行速度的类。

     构造函数接受一个将计时的语句、一个用于设置的附加语句和一个定时器函
     数。两个语句都默认为 ‘'pass'’ ；计时器函数与平台有关（请参阅模块文
     档字符串）。 `stmt' 和 `setup' 也可能包含多个以 ‘;’ 或换行符分隔的
     语句，只要它们不包含多行字符串文字即可。该语句默认在 timeit 的命名
     空间内执行；可以通过将命名空间传递给 `globals' 来控制此行为。

     要测量第一个语句的执行时间，请使用 *note timeit(): 5a5. 方法。
     *note repeat(): 3590. 和 *note autorange(): 5a4. 方法是方便的方法来
     调用 *note timeit(): 5a5. 多次。

     `setup' 的执行时间从总体计时执行中排除。

     `stmt' 和 `setup' 参数也可以使用不带参数的可调用对象。这将在一个计
     时器函数中嵌入对它们的调用，然后由 *note timeit(): 5a5. 执行。请注
     意，由于额外的函数调用，在这种情况下，计时开销会略大一些。

     在 3.5 版更改: 添加可选参数 `globals' 。

      -- 方法: timeit (number=1000000)

          执行 `number' 次主要语句。这将执行一次 setup 语句，然后返回执
          行主语句多次所需的时间，以秒为单位测量为浮点数。参数是通过循环
          的次数，默认为一百万。要使用的主语句、 setup 语句和 timer 函数
          将传递给构造函数。

               注解: 默认情况下， *note timeit(): 5a5. 暂时关闭 *note
               garbage collection: ed8. 。这种方法的优点在于它使独立时序
               更具可比性。缺点是GC可能是所测量功能性能的重要组成部分。
               如果是这样，可以在 `setup' 字符串中的第一个语句重新启用
               GC。例如:

                    timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()

      -- 方法: autorange (callback=None)

          自动决定调用多少次 *note timeit(): 5a5. 。

          这是一个便利函数，它反复调用 *note timeit(): 5a5. ，以便总时间
          >= 0.2 秒，返回最终（循环次数，循环所用的时间）。它调用 *note
          timeit(): 5a5. 的次数以序列 1, 2, 5, 10, 20, 50, ... 递增，直
          到所用的时间至少为0.2秒。

          如果给出 `callback' 并且不是 ‘None’ ，则在每次试验后将使用两个
          参数调用它： ‘callback(number, time_taken)’ 。

          3.6 新版功能.

      -- 方法: repeat (repeat=5, number=1000000)

          调用 *note timeit(): 5a5. 几次。

          这是一个方便的函数，它反复调用 *note timeit(): 5a5. ，返回结果
          列表。第一个参数指定调用 *note timeit(): 5a5. 的次数。第二个参
          数指定 *note timeit(): 5a5. 的 `number' 参数。

               注解: 从结果向量计算并报告平均值和标准差这些是很诱人的。
               但是，这不是很有用。在典型情况下，最低值给出了机器运行给
               定代码段的速度的下限；结果向量中较高的值通常不是由
               Python的速度变化引起的，而是由于其他过程干扰你的计时准确
               性。所以结果的 *note min(): 812. 可能是你应该感兴趣的唯一
               数字。之后，你应该看看整个向量并应用常识而不是统计。

          在 3.7 版更改: `repeat' 的默认值由 3 更改为 5 。

      -- 方法: print_exc (file=None)

          帮助程序从计时代码中打印回溯。

          典型使用:

               t = Timer(...)       # outside the try/except
               try:
                   t.timeit(...)    # or t.repeat(...)
               except Exception:
                   t.print_exc()

          与标准回溯相比，优势在于将显示已编译模板中的源行。可选的
          `file' 参数指向发送回溯的位置；它默认为 *note sys.stderr: 318.
          。


File: python.info,  Node: 命令行界面<6>,  Next: 例子<25>,  Prev: Python 接口,  Up: timeit --- 测量小代码片段的执行时间

5.27.6.3 命令行界面
...................

从命令行调用程序时，使用以下表单:

     python -m timeit [-n N] [-r N] [-u U] [-s S] [-h] [statement ...]

如果了解以下选项：

 -- 程序选项: -n N, --number=N

     执行 ’语句’ 多少次

 -- 程序选项: -r N, --repeat=N

     重复计时器的次数（默认为5）

 -- 程序选项: -s S, --setup=S

     最初要执行一次的语句（默认为 ‘pass’ ）

 -- 程序选项: -p, --process

     测量进程时间，而不是 wallclock 时间，使用 *note
     time.process_time(): 2ac. 而不是 *note time.perf_counter(): 2ab. ，
     这是默认值

     3.3 新版功能.

 -- 程序选项: -u, --unit=U

     指定定时器输出的时间单位；可以选择 nsec，usec，msec或sec

     3.5 新版功能.

 -- 程序选项: -v, --verbose

     打印原始计时结果；重复更多位数精度

 -- 程序选项: -h, --help

     打印一条简短的使用信息并退出

可以通过将每一行指定为单独的语句参数来给出多行语句；通过在引号中包含参数
并使用前导空格可以缩进行。多个 *note -s: 3596. 选项的处理方式相似。

如果未给出 *note -n: 3594.，则会通过尝试按序列 1, 2, 5, 10, 20, 50, ...
递增的数值来计算合适的循环次数，直到总计时间至少为 0.2 秒。

*note default_timer(): 3591. 测量可能受到在同一台机器上运行的其他程序的
影响，因此在需要精确计时时最好的做法是重复几次计时并使用最佳时间。 *note
-r: 3595. 选项对此有利；在大多数情况下，默认的 5 次重复可能就足够了。 你
可以使用 *note time.process_time(): 2ac. 来测量CPU时间。

     注解: 执行 pass 语句会产生一定的基线开销。这里的代码不会试图隐藏它
     ，但你应该知道它。可以通过不带参数调用程序来测量基线开销，并且
     Python版本之间可能会有所不同。


File: python.info,  Node: 例子<25>,  Prev: 命令行界面<6>,  Up: timeit --- 测量小代码片段的执行时间

5.27.6.4 例子
.............

可以提供一个在开头只执行一次的 setup 语句：

     $ python -m timeit -s 'text = "sample string"; char = "g"'  'char in text'
     5000000 loops, best of 5: 0.0877 usec per loop
     $ python -m timeit -s 'text = "sample string"; char = "g"'  'text.find(char)'
     1000000 loops, best of 5: 0.342 usec per loop

     >>> import timeit
     >>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"')
     0.41440500499993504
     >>> timeit.timeit('text.find(char)', setup='text = "sample string"; char = "g"')
     1.7246671520006203

使用 *note Timer: 358e. 类及其方法可以完成同样的操作:

     >>> import timeit
     >>> t = timeit.Timer('char in text', setup='text = "sample string"; char = "g"')
     >>> t.timeit()
     0.3955516149999312
     >>> t.repeat()
     [0.40183617287970225, 0.37027556854118704, 0.38344867356679524, 0.3712595970846668, 0.37866875250654886]

以下示例显示如何计算包含多行的表达式。 在这里我们对比使用 *note
hasattr(): 450. 与 *note try: d7a./*note except: b46. 的开销来测试缺失与
提供对象属性:

     $ python -m timeit 'try:' '  str.__bool__' 'except AttributeError:' '  pass'
     20000 loops, best of 5: 15.7 usec per loop
     $ python -m timeit 'if hasattr(str, "__bool__"): pass'
     50000 loops, best of 5: 4.26 usec per loop

     $ python -m timeit 'try:' '  int.__bool__' 'except AttributeError:' '  pass'
     200000 loops, best of 5: 1.43 usec per loop
     $ python -m timeit 'if hasattr(int, "__bool__"): pass'
     100000 loops, best of 5: 2.23 usec per loop

     >>> import timeit
     >>> # attribute is missing
     >>> s = """\
     ... try:
     ...     str.__bool__
     ... except AttributeError:
     ...     pass
     ... """
     >>> timeit.timeit(stmt=s, number=100000)
     0.9138244460009446
     >>> s = "if hasattr(str, '__bool__'): pass"
     >>> timeit.timeit(stmt=s, number=100000)
     0.5829014980008651
     >>>
     >>> # attribute is present
     >>> s = """\
     ... try:
     ...     int.__bool__
     ... except AttributeError:
     ...     pass
     ... """
     >>> timeit.timeit(stmt=s, number=100000)
     0.04215312199994514
     >>> s = "if hasattr(int, '__bool__'): pass"
     >>> timeit.timeit(stmt=s, number=100000)
     0.08588060699912603

要让 *note timeit: 10c. 模块访问你定义的函数，你可以传递一个包含 import
语句的 `setup' 参数:

     def test():
         """Stupid test function"""
         L = [i for i in range(100)]

     if __name__ == '__main__':
         import timeit
         print(timeit.timeit("test()", setup="from __main__ import test"))

另一种选择是将 *note globals(): 15f2. 传递给 `globals' 参数，这将导致代
码在当前的全局命名空间中执行。这比单独指定 import 更方便

     def f(x):
         return x**2
     def g(x):
         return x**4
     def h(x):
         return x**8

     import timeit
     print(timeit.timeit('[func(42) for func in (f,g,h)]', globals=globals()))


File: python.info,  Node: trace --- 跟踪Python语句的执行,  Next: tracemalloc --- 跟踪内存分配,  Prev: timeit --- 测量小代码片段的执行时间,  Up: 调试和分析

5.27.7 ‘trace’ — 跟踪Python语句的执行
-------------------------------------

`源代码:' Lib/trace.py(1)

__________________________________________________________________

模块 *note trace: 113. module 允许你跟踪程序的执行过程，生成带注释的语句
覆盖率列表，打印调用/被调用关系以及列出在程序运行期间执行过的函数。可以
在其他程序或者命令行中使用它

参见
....

Coverage.py(2)

     A popular third-party coverage tool that provides HTML output along
     with advanced features such as branch coverage.

* Menu:

* Command-Line Usage::
* 编程接口::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/trace.py

   (2) https://coverage.readthedocs.io/


File: python.info,  Node: Command-Line Usage,  Next: 编程接口,  Up: trace --- 跟踪Python语句的执行

5.27.7.1 Command-Line Usage
...........................

The *note trace: 113. module can be invoked from the command line.  It
can be as simple as

     python -m trace --count -C . somefile.py ...

The above will execute ‘somefile.py’ and generate annotated listings of
all Python modules imported during the execution into the current
directory.

 -- 程序选项: --help

     Display usage and exit.

 -- 程序选项: --version

     Display the version of the module and exit.

3.8 新版功能: Added ‘--module’ option that allows to run an executable
module.

* Menu:

* Main options::
* Modifiers::
* Filters::


File: python.info,  Node: Main options,  Next: Modifiers,  Up: Command-Line Usage

5.27.7.2 Main options
.....................

At least one of the following options must be specified when invoking
*note trace: 113.  The *note –listfuncs: 35a3. option is mutually
exclusive with the *note –trace: 35a4. and *note –count: 35a5. options.
When *note –listfuncs: 35a3. is provided, neither *note –count: 35a5.
nor *note –trace: 35a4. are accepted, and vice versa.

 -- 程序选项: -c, --count

     Produce a set of annotated listing files upon program completion
     that shows how many times each statement was executed.  See also
     *note –coverdir: 35a6, *note –file: 35a7. and *note –no-report:
     35a8. below.

 -- 程序选项: -t, --trace

     Display lines as they are executed.

 -- 程序选项: -l, --listfuncs

     Display the functions executed by running the program.

 -- 程序选项: -r, --report

     Produce an annotated list from an earlier program run that used the
     *note –count: 35a5. and *note –file: 35a7. option.  This does not
     execute any code.

 -- 程序选项: -T, --trackcalls

     Display the calling relationships exposed by running the program.


File: python.info,  Node: Modifiers,  Next: Filters,  Prev: Main options,  Up: Command-Line Usage

5.27.7.3 Modifiers
..................

 -- 程序选项: -f, --file=<file>

     Name of a file to accumulate counts over several tracing runs.
     Should be used with the *note –count: 35a5. option.

 -- 程序选项: -C, --coverdir=<dir>

     Directory where the report files go.  The coverage report for
     ‘package.module’ is written to file
     ‘`dir'/`package'/`module'.cover’.

 -- 程序选项: -m, --missing

     When generating annotated listings, mark lines which were not
     executed with ‘>>>>>>’.

 -- 程序选项: -s, --summary

     When using *note –count: 35a5. or *note –report: 35a9, write a
     brief summary to stdout for each file processed.

 -- 程序选项: -R, --no-report

     Do not generate annotated listings.  This is useful if you intend
     to make several runs with *note –count: 35a5, and then produce a
     single set of annotated listings at the end.

 -- 程序选项: -g, --timing

     Prefix each line with the time since the program started.  Only
     used while tracing.


File: python.info,  Node: Filters,  Prev: Modifiers,  Up: Command-Line Usage

5.27.7.4 Filters
................

These options may be repeated multiple times.

 -- 程序选项: --ignore-module=<mod>

     Ignore each of the given module names and its submodules (if it is
     a package).  The argument can be a list of names separated by a
     comma.

 -- 程序选项: --ignore-dir=<dir>

     Ignore all modules and packages in the named directory and
     subdirectories.  The argument can be a list of directories
     separated by *note os.pathsep: 1365.


File: python.info,  Node: 编程接口,  Prev: Command-Line Usage,  Up: trace --- 跟踪Python语句的执行

5.27.7.5 编程接口
.................

 -- 类: trace.Trace (count=1, trace=1, countfuncs=0, countcallers=0,
          ignoremods=(), ignoredirs=(), infile=None, outfile=None,
          timing=False)

     Create an object to trace execution of a single statement or
     expression.  All parameters are optional.  `count' enables counting
     of line numbers.  `trace' enables line execution tracing.
     `countfuncs' enables listing of the functions called during the
     run.  `countcallers' enables call relationship tracking.
     `ignoremods' is a list of modules or packages to ignore.
     `ignoredirs' is a list of directories whose modules or packages
     should be ignored.  `infile' is the name of the file from which to
     read stored count information.  `outfile' is the name of the file
     in which to write updated count information.  `timing' enables a
     timestamp relative to when tracing was started to be displayed.

      -- 方法: run (cmd)

          Execute the command and gather statistics from the execution
          with the current tracing parameters.  `cmd' must be a string
          or code object, suitable for passing into *note exec(): c4c.

      -- 方法: runctx (cmd, globals=None, locals=None)

          Execute the command and gather statistics from the execution
          with the current tracing parameters, in the defined global and
          local environments.  If not defined, `globals' and `locals'
          default to empty dictionaries.

      -- 方法: runfunc (func, *args, **kwds)

          Call `func' with the given arguments under control of the
          *note Trace: 35b4. object with the current tracing parameters.

      -- 方法: results ()

          Return a *note CoverageResults: 35b8. object that contains the
          cumulative results of all previous calls to ‘run’, ‘runctx’
          and ‘runfunc’ for the given *note Trace: 35b4. instance.  Does
          not reset the accumulated trace results.

 -- 类: trace.CoverageResults

     A container for coverage results, created by *note Trace.results():
     35b7.  Should not be created directly by the user.

      -- 方法: update (other)

          Merge in data from another *note CoverageResults: 35b8.
          object.

      -- 方法: write_results (show_missing=True, summary=False,
               coverdir=None)

          Write coverage results.  Set `show_missing' to show lines that
          had no hits.  Set `summary' to include in the output the
          coverage summary per module.  `coverdir' specifies the
          directory into which the coverage result files will be output.
          If ‘None’, the results for each source file are placed in its
          directory.

A simple example demonstrating the use of the programmatic interface:

     import sys
     import trace

     # create a Trace object, telling it what to ignore, and whether to
     # do tracing or line-counting or both.
     tracer = trace.Trace(
         ignoredirs=[sys.prefix, sys.exec_prefix],
         trace=0,
         count=1)

     # run the new command using the given tracer
     tracer.run('main()')

     # make a report, placing output in the current directory
     r = tracer.results()
     r.write_results(show_missing=True, coverdir=".")


File: python.info,  Node: tracemalloc --- 跟踪内存分配,  Prev: trace --- 跟踪Python语句的执行,  Up: 调试和分析

5.27.8 ‘tracemalloc’ — 跟踪内存分配
-----------------------------------

3.4 新版功能.

`源代码：' Lib/tracemalloc.py(1)

__________________________________________________________________

The tracemalloc module is a debug tool to trace memory blocks allocated
by Python.  It provides the following information:

   * Traceback where an object was allocated

   * Statistics on allocated memory blocks per filename and per line
     number: total size, number and average size of allocated memory
     blocks

   * Compute the differences between two snapshots to detect memory
     leaks

To trace most memory blocks allocated by Python, the module should be
started as early as possible by setting the *note PYTHONTRACEMALLOC:
136b. environment variable to ‘1’, or by using *note -X: 156.
‘tracemalloc’ command line option.  The *note tracemalloc.start(): 135f.
function can be called at runtime to start tracing Python memory
allocations.

By default, a trace of an allocated memory block only stores the most
recent frame (1 frame).  To store 25 frames at startup: set the *note
PYTHONTRACEMALLOC: 136b. environment variable to ‘25’, or use the *note
-X: 156. ‘tracemalloc=25’ command line option.

* Menu:

* 例子: 例子<26>.
* API::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/tracemalloc.py


File: python.info,  Node: 例子<26>,  Next: API,  Up: tracemalloc --- 跟踪内存分配

5.27.8.1 例子
.............

* Menu:

* 显示前10项::
* 计算差异::
* Get the traceback of a memory block::
* Pretty top::


File: python.info,  Node: 显示前10项,  Next: 计算差异,  Up: 例子<26>

5.27.8.2 显示前10项
...................

显示内存分配最多的10个文件：

     import tracemalloc

     tracemalloc.start()

     # ... run your application ...

     snapshot = tracemalloc.take_snapshot()
     top_stats = snapshot.statistics('lineno')

     print("[ Top 10 ]")
     for stat in top_stats[:10]:
         print(stat)

Python测试套件的输出示例：

     [ Top 10 ]
     <frozen importlib._bootstrap>:716: size=4855 KiB, count=39328, average=126 B
     <frozen importlib._bootstrap>:284: size=521 KiB, count=3199, average=167 B
     /usr/lib/python3.4/collections/__init__.py:368: size=244 KiB, count=2315, average=108 B
     /usr/lib/python3.4/unittest/case.py:381: size=185 KiB, count=779, average=243 B
     /usr/lib/python3.4/unittest/case.py:402: size=154 KiB, count=378, average=416 B
     /usr/lib/python3.4/abc.py:133: size=88.7 KiB, count=347, average=262 B
     <frozen importlib._bootstrap>:1446: size=70.4 KiB, count=911, average=79 B
     <frozen importlib._bootstrap>:1454: size=52.0 KiB, count=25, average=2131 B
     <string>:5: size=49.7 KiB, count=148, average=344 B
     /usr/lib/python3.4/sysconfig.py:411: size=48.0 KiB, count=1, average=48.0 KiB

We can see that Python loaded ‘4855 KiB’ data (bytecode and constants)
from modules and that the *note collections: 1e. module allocated ‘244
KiB’ to build *note namedtuple: 1b7. types.

See *note Snapshot.statistics(): 35bf. for more options.


File: python.info,  Node: 计算差异,  Next: Get the traceback of a memory block,  Prev: 显示前10项,  Up: 例子<26>

5.27.8.3 计算差异
.................

获取两个快照并显示差异：

     import tracemalloc
     tracemalloc.start()
     # ... start your application ...

     snapshot1 = tracemalloc.take_snapshot()
     # ... call the function leaking memory ...
     snapshot2 = tracemalloc.take_snapshot()

     top_stats = snapshot2.compare_to(snapshot1, 'lineno')

     print("[ Top 10 differences ]")
     for stat in top_stats[:10]:
         print(stat)

Example of output before/after running some tests of the Python test
suite:

     [ Top 10 differences ]
     <frozen importlib._bootstrap>:716: size=8173 KiB (+4428 KiB), count=71332 (+39369), average=117 B
     /usr/lib/python3.4/linecache.py:127: size=940 KiB (+940 KiB), count=8106 (+8106), average=119 B
     /usr/lib/python3.4/unittest/case.py:571: size=298 KiB (+298 KiB), count=589 (+589), average=519 B
     <frozen importlib._bootstrap>:284: size=1005 KiB (+166 KiB), count=7423 (+1526), average=139 B
     /usr/lib/python3.4/mimetypes.py:217: size=112 KiB (+112 KiB), count=1334 (+1334), average=86 B
     /usr/lib/python3.4/http/server.py:848: size=96.0 KiB (+96.0 KiB), count=1 (+1), average=96.0 KiB
     /usr/lib/python3.4/inspect.py:1465: size=83.5 KiB (+83.5 KiB), count=109 (+109), average=784 B
     /usr/lib/python3.4/unittest/mock.py:491: size=77.7 KiB (+77.7 KiB), count=143 (+143), average=557 B
     /usr/lib/python3.4/urllib/parse.py:476: size=71.8 KiB (+71.8 KiB), count=969 (+969), average=76 B
     /usr/lib/python3.4/contextlib.py:38: size=67.2 KiB (+67.2 KiB), count=126 (+126), average=546 B

We can see that Python has loaded ‘8173 KiB’ of module data (bytecode
and constants), and that this is ‘4428 KiB’ more than had been loaded
before the tests, when the previous snapshot was taken.  Similarly, the
*note linecache: a9. module has cached ‘940 KiB’ of Python source code
to format tracebacks, all of it since the previous snapshot.

If the system has little free memory, snapshots can be written on disk
using the *note Snapshot.dump(): 35c1. method to analyze the snapshot
offline.  Then use the *note Snapshot.load(): 35c2. method reload the
snapshot.


File: python.info,  Node: Get the traceback of a memory block,  Next: Pretty top,  Prev: 计算差异,  Up: 例子<26>

5.27.8.4 Get the traceback of a memory block
............................................

Code to display the traceback of the biggest memory block:

     import tracemalloc

     # Store 25 frames
     tracemalloc.start(25)

     # ... run your application ...

     snapshot = tracemalloc.take_snapshot()
     top_stats = snapshot.statistics('traceback')

     # pick the biggest memory block
     stat = top_stats[0]
     print("%s memory blocks: %.1f KiB" % (stat.count, stat.size / 1024))
     for line in stat.traceback.format():
         print(line)

Example of output of the Python test suite (traceback limited to 25
frames):

     903 memory blocks: 870.1 KiB
       File "<frozen importlib._bootstrap>", line 716
       File "<frozen importlib._bootstrap>", line 1036
       File "<frozen importlib._bootstrap>", line 934
       File "<frozen importlib._bootstrap>", line 1068
       File "<frozen importlib._bootstrap>", line 619
       File "<frozen importlib._bootstrap>", line 1581
       File "<frozen importlib._bootstrap>", line 1614
       File "/usr/lib/python3.4/doctest.py", line 101
         import pdb
       File "<frozen importlib._bootstrap>", line 284
       File "<frozen importlib._bootstrap>", line 938
       File "<frozen importlib._bootstrap>", line 1068
       File "<frozen importlib._bootstrap>", line 619
       File "<frozen importlib._bootstrap>", line 1581
       File "<frozen importlib._bootstrap>", line 1614
       File "/usr/lib/python3.4/test/support/__init__.py", line 1728
         import doctest
       File "/usr/lib/python3.4/test/test_pickletools.py", line 21
         support.run_doctest(pickletools)
       File "/usr/lib/python3.4/test/regrtest.py", line 1276
         test_runner()
       File "/usr/lib/python3.4/test/regrtest.py", line 976
         display_failure=not verbose)
       File "/usr/lib/python3.4/test/regrtest.py", line 761
         match_tests=ns.match_tests)
       File "/usr/lib/python3.4/test/regrtest.py", line 1563
         main()
       File "/usr/lib/python3.4/test/__main__.py", line 3
         regrtest.main_in_temp_cwd()
       File "/usr/lib/python3.4/runpy.py", line 73
         exec(code, run_globals)
       File "/usr/lib/python3.4/runpy.py", line 160
         "__main__", fname, loader, pkg_name)

We can see that the most memory was allocated in the *note importlib:
9b. module to load data (bytecode and constants) from modules: ‘870.1
KiB’.  The traceback is where the *note importlib: 9b. loaded data most
recently: on the ‘import pdb’ line of the *note doctest: 67. module.
The traceback may change if a new module is loaded.


File: python.info,  Node: Pretty top,  Prev: Get the traceback of a memory block,  Up: 例子<26>

5.27.8.5 Pretty top
...................

Code to display the 10 lines allocating the most memory with a pretty
output, ignoring ‘<frozen importlib._bootstrap>’ and ‘<unknown>’ files:

     import linecache
     import os
     import tracemalloc

     def display_top(snapshot, key_type='lineno', limit=10):
         snapshot = snapshot.filter_traces((
             tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
             tracemalloc.Filter(False, "<unknown>"),
         ))
         top_stats = snapshot.statistics(key_type)

         print("Top %s lines" % limit)
         for index, stat in enumerate(top_stats[:limit], 1):
             frame = stat.traceback[0]
             print("#%s: %s:%s: %.1f KiB"
                   % (index, frame.filename, frame.lineno, stat.size / 1024))
             line = linecache.getline(frame.filename, frame.lineno).strip()
             if line:
                 print('    %s' % line)

         other = top_stats[limit:]
         if other:
             size = sum(stat.size for stat in other)
             print("%s other: %.1f KiB" % (len(other), size / 1024))
         total = sum(stat.size for stat in top_stats)
         print("Total allocated size: %.1f KiB" % (total / 1024))

     tracemalloc.start()

     # ... run your application ...

     snapshot = tracemalloc.take_snapshot()
     display_top(snapshot)

Python测试套件的输出示例：

     Top 10 lines
     #1: Lib/base64.py:414: 419.8 KiB
         _b85chars2 = [(a + b) for a in _b85chars for b in _b85chars]
     #2: Lib/base64.py:306: 419.8 KiB
         _a85chars2 = [(a + b) for a in _a85chars for b in _a85chars]
     #3: collections/__init__.py:368: 293.6 KiB
         exec(class_definition, namespace)
     #4: Lib/abc.py:133: 115.2 KiB
         cls = super().__new__(mcls, name, bases, namespace)
     #5: unittest/case.py:574: 103.1 KiB
         testMethod()
     #6: Lib/linecache.py:127: 95.4 KiB
         lines = fp.readlines()
     #7: urllib/parse.py:476: 71.8 KiB
         for a in _hexdig for b in _hexdig}
     #8: <string>:5: 62.0 KiB
     #9: Lib/_weakrefset.py:37: 60.0 KiB
         self.data = set()
     #10: Lib/base64.py:142: 59.8 KiB
         _b32tab2 = [a + b for a in _b32tab for b in _b32tab]
     6220 other: 3602.8 KiB
     Total allocated size: 5303.1 KiB

See *note Snapshot.statistics(): 35bf. for more options.


File: python.info,  Node: API,  Prev: 例子<26>,  Up: tracemalloc --- 跟踪内存分配

5.27.8.6 API
............

* Menu:

* 函数: 函数<9>.
* 域过滤器::
* 过滤器::
* Frame::
* 快照::
* 统计::
* StatisticDiff::
* 跟踪::
* 回溯: 回溯<4>.


File: python.info,  Node: 函数<9>,  Next: 域过滤器,  Up: API

5.27.8.7 函数
.............

 -- 函数: tracemalloc.clear_traces ()

     Clear traces of memory blocks allocated by Python.

     See also *note stop(): 35c8.

 -- 函数: tracemalloc.get_object_traceback (obj)

     Get the traceback where the Python object `obj' was allocated.
     Return a *note Traceback: 407. instance, or ‘None’ if the *note
     tracemalloc: 115. module is not tracing memory allocations or did
     not trace the allocation of the object.

     See also *note gc.get_referrers(): eb4. and *note sys.getsizeof():
     35c9. functions.

 -- 函数: tracemalloc.get_traceback_limit ()

     Get the maximum number of frames stored in the traceback of a
     trace.

     The *note tracemalloc: 115. module must be tracing memory
     allocations to get the limit, otherwise an exception is raised.

     The limit is set by the *note start(): 135f. function.

 -- 函数: tracemalloc.get_traced_memory ()

     Get the current size and peak size of memory blocks traced by the
     *note tracemalloc: 115. module as a tuple: ‘(current: int, peak:
     int)’.

 -- 函数: tracemalloc.get_tracemalloc_memory ()

     Get the memory usage in bytes of the *note tracemalloc: 115. module
     used to store traces of memory blocks.  Return an *note int: 185.

 -- 函数: tracemalloc.is_tracing ()

     ‘True’ if the *note tracemalloc: 115. module is tracing Python
     memory allocations, ‘False’ otherwise.

     See also *note start(): 135f. and *note stop(): 35c8. functions.

 -- 函数: tracemalloc.start (nframe: int=1)

     Start tracing Python memory allocations: install hooks on Python
     memory allocators.  Collected tracebacks of traces will be limited
     to `nframe' frames.  By default, a trace of a memory block only
     stores the most recent frame: the limit is ‘1’.  `nframe' must be
     greater or equal to ‘1’.

     Storing more than ‘1’ frame is only useful to compute statistics
     grouped by ‘'traceback'’ or to compute cumulative statistics: see
     the *note Snapshot.compare_to(): 35ce. and *note
     Snapshot.statistics(): 35bf. methods.

     Storing more frames increases the memory and CPU overhead of the
     *note tracemalloc: 115. module.  Use the *note
     get_tracemalloc_memory(): 35cc. function to measure how much memory
     is used by the *note tracemalloc: 115. module.

     The *note PYTHONTRACEMALLOC: 136b. environment variable
     (‘PYTHONTRACEMALLOC=NFRAME’) and the *note -X: 156.
     ‘tracemalloc=NFRAME’ command line option can be used to start
     tracing at startup.

     See also *note stop(): 35c8, *note is_tracing(): 35cd. and *note
     get_traceback_limit(): 35ca. functions.

 -- 函数: tracemalloc.stop ()

     Stop tracing Python memory allocations: uninstall hooks on Python
     memory allocators.  Also clears all previously collected traces of
     memory blocks allocated by Python.

     Call *note take_snapshot(): 35cf. function to take a snapshot of
     traces before clearing them.

     See also *note start(): 135f, *note is_tracing(): 35cd. and *note
     clear_traces(): 35c7. functions.

 -- 函数: tracemalloc.take_snapshot ()

     Take a snapshot of traces of memory blocks allocated by Python.
     Return a new *note Snapshot: 35d0. instance.

     The snapshot does not include memory blocks allocated before the
     *note tracemalloc: 115. module started to trace memory allocations.

     Tracebacks of traces are limited to *note get_traceback_limit():
     35ca. frames.  Use the `nframe' parameter of the *note start():
     135f. function to store more frames.

     The *note tracemalloc: 115. module must be tracing memory
     allocations to take a snapshot, see the *note start(): 135f.
     function.

     See also the *note get_object_traceback(): 1176. function.


File: python.info,  Node: 域过滤器,  Next: 过滤器,  Prev: 函数<9>,  Up: API

5.27.8.8 域过滤器
.................

 -- 类: tracemalloc.DomainFilter (inclusive: bool, domain: int)

     Filter traces of memory blocks by their address space (domain).

     3.6 新版功能.

      -- 属性: inclusive

          If `inclusive' is ‘True’ (include), match memory blocks
          allocated in the address space *note domain: 35d3.

          If `inclusive' is ‘False’ (exclude), match memory blocks not
          allocated in the address space *note domain: 35d3.

      -- 属性: domain

          Address space of a memory block (‘int’).  Read-only property.


File: python.info,  Node: 过滤器,  Next: Frame,  Prev: 域过滤器,  Up: API

5.27.8.9 过滤器
...............

 -- 类: tracemalloc.Filter (inclusive: bool, filename_pattern: str,
          lineno: int=None, all_frames: bool=False, domain: int=None)

     对内存块的跟踪进行筛选。

     See the *note fnmatch.fnmatch(): 1c86. function for the syntax of
     `filename_pattern'.  The ‘'.pyc'’ file extension is replaced with
     ‘'.py'’.

     示例：

        * ‘Filter(True, subprocess.__file__)’ only includes traces of
          the *note subprocess: fa. module

        * ‘Filter(False, tracemalloc.__file__)’ excludes traces of the
          *note tracemalloc: 115. module

        * ‘Filter(False, "<unknown>")’ excludes empty tracebacks

     在 3.5 版更改: The ‘'.pyo'’ file extension is no longer replaced
     with ‘'.py'’.

     在 3.6 版更改: Added the *note domain: 35d6. attribute.

      -- 属性: domain

          Address space of a memory block (‘int’ or ‘None’).

          tracemalloc uses the domain ‘0’ to trace memory allocations
          made by Python.  C extensions can use other domains to trace
          other resources.

      -- 属性: inclusive

          If `inclusive' is ‘True’ (include), only match memory blocks
          allocated in a file with a name matching *note
          filename_pattern: 35d8. at line number *note lineno: 35d9.

          If `inclusive' is ‘False’ (exclude), ignore memory blocks
          allocated in a file with a name matching *note
          filename_pattern: 35d8. at line number *note lineno: 35d9.

      -- 属性: lineno

          Line number (‘int’) of the filter.  If `lineno' is ‘None’, the
          filter matches any line number.

      -- 属性: filename_pattern

          Filename pattern of the filter (‘str’).  Read-only property.

      -- 属性: all_frames

          If `all_frames' is ‘True’, all frames of the traceback are
          checked.  If `all_frames' is ‘False’, only the most recent
          frame is checked.

          This attribute has no effect if the traceback limit is ‘1’.
          See the *note get_traceback_limit(): 35ca. function and *note
          Snapshot.traceback_limit: 35db. attribute.


File: python.info,  Node: Frame,  Next: 快照,  Prev: 过滤器,  Up: API

5.27.8.10 Frame
...............

 -- 类: tracemalloc.Frame

     Frame of a traceback.

     The *note Traceback: 407. class is a sequence of *note Frame: 35dd.
     instances.

      -- 属性: filename

          文件名（‘字符串’）

      -- 属性: lineno

          行号（‘整形’）


File: python.info,  Node: 快照,  Next: 统计,  Prev: Frame,  Up: API

5.27.8.11 快照
..............

 -- 类: tracemalloc.Snapshot

     Snapshot of traces of memory blocks allocated by Python.

     The *note take_snapshot(): 35cf. function creates a snapshot
     instance.

      -- 方法: compare_to (old_snapshot: Snapshot, key_type: str,
               cumulative: bool=False)

          Compute the differences with an old snapshot.  Get statistics
          as a sorted list of *note StatisticDiff: 35e1. instances
          grouped by `key_type'.

          See the *note Snapshot.statistics(): 35bf. method for
          `key_type' and `cumulative' parameters.

          The result is sorted from the biggest to the smallest by:
          absolute value of *note StatisticDiff.size_diff: 35e2, *note
          StatisticDiff.size: 35e3, absolute value of *note
          StatisticDiff.count_diff: 35e4, *note Statistic.count: 35e5.
          and then by *note StatisticDiff.traceback: 35e6.

      -- 方法: dump (filename)

          将快照写入文件

          使用 *note load(): 35c2. 重载快照。

      -- 方法: filter_traces (filters)

          Create a new *note Snapshot: 35d0. instance with a filtered
          *note traces: 35e8. sequence, `filters' is a list of *note
          DomainFilter: 5a9. and *note Filter: 35d5. instances.  If
          `filters' is an empty list, return a new *note Snapshot: 35d0.
          instance with a copy of the traces.

          All inclusive filters are applied at once, a trace is ignored
          if no inclusive filters match it.  A trace is ignored if at
          least one exclusive filter matches it.

          在 3.6 版更改: *note DomainFilter: 5a9. instances are now also
          accepted in `filters'.

      -- 方法: classmethod load (filename)

          从文件载入快照。

          另见 *note dump(): 35c1.

      -- 方法: statistics (key_type: str, cumulative: bool=False)

          获取 *note Statistic: 35e9. 信息列表，按 `key_type' 分组排序：

          key_type                  描述
                                    
          -------------------------------------------------------
                                    
          ‘'filename'’              文件名
                                    
                                    
          ‘'lineno'’                文件名和行号
                                    
                                    
          ‘'traceback'’             回溯
                                    

          If `cumulative' is ‘True’, cumulate size and count of memory
          blocks of all frames of the traceback of a trace, not only the
          most recent frame.  The cumulative mode can only be used with
          `key_type' equals to ‘'filename'’ and ‘'lineno'’.

          The result is sorted from the biggest to the smallest by:
          *note Statistic.size: 35ea, *note Statistic.count: 35e5. and
          then by *note Statistic.traceback: 35eb.

      -- 属性: traceback_limit

          Maximum number of frames stored in the traceback of *note
          traces: 35e8.: result of the *note get_traceback_limit():
          35ca. when the snapshot was taken.

      -- 属性: traces

          Traces of all memory blocks allocated by Python: sequence of
          *note Trace: 35ec. instances.

          The sequence has an undefined order.  Use the *note
          Snapshot.statistics(): 35bf. method to get a sorted list of
          statistics.


File: python.info,  Node: 统计,  Next: StatisticDiff,  Prev: 快照,  Up: API

5.27.8.12 统计
..............

 -- 类: tracemalloc.Statistic

     统计内存分配

     *note Snapshot.statistics(): 35bf. 返回 *note Statistic: 35e9. 实例
     的列表。.

     参见 *note StatisticDiff: 35e1. 类。

      -- 属性: count

          内存块数（‘整形’）。

      -- 属性: size

          Total size of memory blocks in bytes (‘int’).

      -- 属性: traceback

          Traceback where the memory block was allocated, *note
          Traceback: 407. instance.


File: python.info,  Node: StatisticDiff,  Next: 跟踪,  Prev: 统计,  Up: API

5.27.8.13 StatisticDiff
.......................

 -- 类: tracemalloc.StatisticDiff

     Statistic difference on memory allocations between an old and a new
     *note Snapshot: 35d0. instance.

     *note Snapshot.compare_to(): 35ce. returns a list of *note
     StatisticDiff: 35e1. instances.  See also the *note Statistic:
     35e9. class.

      -- 属性: count

          Number of memory blocks in the new snapshot (‘int’): ‘0’ if
          the memory blocks have been released in the new snapshot.

      -- 属性: count_diff

          Difference of number of memory blocks between the old and the
          new snapshots (‘int’): ‘0’ if the memory blocks have been
          allocated in the new snapshot.

      -- 属性: size

          Total size of memory blocks in bytes in the new snapshot
          (‘int’): ‘0’ if the memory blocks have been released in the
          new snapshot.

      -- 属性: size_diff

          Difference of total size of memory blocks in bytes between the
          old and the new snapshots (‘int’): ‘0’ if the memory blocks
          have been allocated in the new snapshot.

      -- 属性: traceback

          Traceback where the memory blocks were allocated, *note
          Traceback: 407. instance.


File: python.info,  Node: 跟踪,  Next: 回溯<4>,  Prev: StatisticDiff,  Up: API

5.27.8.14 跟踪
..............

 -- 类: tracemalloc.Trace

     Trace of a memory block.

     The *note Snapshot.traces: 35e8. attribute is a sequence of *note
     Trace: 35ec. instances.

     在 3.6 版更改: Added the *note domain: 35f1. attribute.

      -- 属性: domain

          Address space of a memory block (‘int’).  Read-only property.

          tracemalloc uses the domain ‘0’ to trace memory allocations
          made by Python.  C extensions can use other domains to trace
          other resources.

      -- 属性: size

          Size of the memory block in bytes (‘int’).

      -- 属性: traceback

          Traceback where the memory block was allocated, *note
          Traceback: 407. instance.


File: python.info,  Node: 回溯<4>,  Prev: 跟踪,  Up: API

5.27.8.15 回溯
..............

 -- 类: tracemalloc.Traceback

     Sequence of *note Frame: 35dd. instances sorted from the oldest
     frame to the most recent frame.

     A traceback contains at least ‘1’ frame.  If the ‘tracemalloc’
     module failed to get a frame, the filename ‘"<unknown>"’ at line
     number ‘0’ is used.

     When a snapshot is taken, tracebacks of traces are limited to *note
     get_traceback_limit(): 35ca. frames.  See the *note
     take_snapshot(): 35cf. function.

     The *note Trace.traceback: 35f3. attribute is an instance of *note
     Traceback: 407. instance.

     在 3.7 版更改: Frames are now sorted from the oldest to the most
     recent, instead of most recent to oldest.

      -- 方法: format (limit=None, most_recent_first=False)

          Format the traceback as a list of lines with newlines.  Use
          the *note linecache: a9. module to retrieve lines from the
          source code.  If `limit' is set, format the `limit' most
          recent frames if `limit' is positive.  Otherwise, format the
          ‘abs(limit)’ oldest frames.  If `most_recent_first' is ‘True’,
          the order of the formatted frames is reversed, returning the
          most recent frame first instead of last.

          Similar to the *note traceback.format_tb(): 35f5. function,
          except that *note format(): 408. does not include newlines.

          示例:

               print("Traceback (most recent call first):")
               for line in traceback:
                   print(line)

          输出:

               Traceback (most recent call first):
                 File "test.py", line 9
                   obj = Object()
                 File "test.py", line 12
                   tb = tracemalloc.get_object_traceback(f())


File: python.info,  Node: 软件打包和分发,  Next: Python运行时服务,  Prev: 调试和分析,  Up: Python 标准库

5.28 软件打包和分发
===================

这些库可帮助你发布和安装 Python 软件。 虽然这些模块设计为与‘Python 包索
引 <‘https://pypi.org’>‘__结合使用，但它们也可以与本地索引服务器一起使用
，或者根本不使用任何索引服务器。

* Menu:

* distutils: distutils --- 构建和安装 Python 模块. 构建和安装 Python 模块
* ensurepip: ensurepip --- Bootstrapping the pip installer. Bootstrapping the pip installer
* venv: venv --- 创建虚拟环境. 创建虚拟环境
* zipapp: zipapp --- Manage executable Python zip archives. Manage executable Python zip archives


File: python.info,  Node: distutils --- 构建和安装 Python 模块,  Next: ensurepip --- Bootstrapping the pip installer,  Up: 软件打包和分发

5.28.1 ‘distutils’ — 构建和安装 Python 模块
-------------------------------------------

__________________________________________________________________

*note distutils: 39. 包为将待构建和安装的额外的模块，打包成 Python 安装
包提供支持。新模块既可以是百分百的纯 Python，也可以是用 C 写的扩展模块，
或者可以是一组包含了同时用 Python 和 C 编码的 Python 包。

大多数 Python 用户 `不会' 想要直接使用这个包，而是使用 Python 包官方维护
的跨版本工具。特别地， setuptools(1) 是一个对于 *note distutils: 39. 的
增强选项，它能提供：

   * 对声明项目依赖的支持

   * 额外的用于配置哪些文件包含在源代码发布中的机制（包括与版本控制系统
     集成需要的插件）

   * 生成项目“进入点”的能力，进入点可用作应用插件系统的基础

   * 自动在安装时间生成 Windows 命令行可执行文件的能力，而不是需要预编译
     它们

   * 跨所有受支持的 Python 版本上的一致的表现

推荐的 pip(2) 安装器用 ‘setuptools’ 运行所有的 ‘setup.py’ 脚本，即使脚本
本身只引了 ‘distutils’ 包。参考 Python Packaging User Guide(3)  获得更多
信息。

为了打包工具的作者和用户能更好理解当前的打包和分发系统，遗留的基于 *note
distutils: 39. 的用户文档和 API 参考保持可用：

   * *note 安装Python模块（旧版）: 800.

   * *note 分发 Python 模块（遗留版本）: 801.

   ---------- Footnotes ----------

   (1) https://setuptools.readthedocs.io/en/latest/

   (2) https://pip.pypa.io/

   (3) https://packaging.python.org


File: python.info,  Node: ensurepip --- Bootstrapping the pip installer,  Next: venv --- 创建虚拟环境,  Prev: distutils --- 构建和安装 Python 模块,  Up: 软件打包和分发

5.28.2 ‘ensurepip’ — Bootstrapping the ‘pip’ installer
------------------------------------------------------

3.4 新版功能.

__________________________________________________________________

The *note ensurepip: 7a. package provides support for bootstrapping the
‘pip’ installer into an existing Python installation or virtual
environment.  This bootstrapping approach reflects the fact that ‘pip’
is an independent project with its own release cycle, and the latest
available stable version is bundled with maintenance and feature
releases of the CPython reference interpreter.

In most cases, end users of Python shouldn’t need to invoke this module
directly (as ‘pip’ should be bootstrapped by default), but it may be
needed if installing ‘pip’ was skipped when installing Python (or when
creating a virtual environment) or after explicitly uninstalling ‘pip’.

     注解: This module `does not' access the internet.  All of the
     components needed to bootstrap ‘pip’ are included as internal parts
     of the package.

参见
....

*note 安装 Python 模块: 7fe.

     The end user guide for installing Python packages

PEP 453(1): Explicit bootstrapping of pip in Python installations

     The original rationale and specification for this module.

* Menu:

* Command line interface::
* Module API::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0453


File: python.info,  Node: Command line interface,  Next: Module API,  Up: ensurepip --- Bootstrapping the pip installer

5.28.2.1 Command line interface
...............................

The command line interface is invoked using the interpreter’s ‘-m’
switch.

The simplest possible invocation is:

     python -m ensurepip

This invocation will install ‘pip’ if it is not already installed, but
otherwise does nothing.  To ensure the installed version of ‘pip’ is at
least as recent as the one bundled with ‘ensurepip’, pass the
‘--upgrade’ option:

     python -m ensurepip --upgrade

By default, ‘pip’ is installed into the current virtual environment (if
one is active) or into the system site packages (if there is no active
virtual environment).  The installation location can be controlled
through two additional command line options:

   * ‘--root <dir>’: Installs ‘pip’ relative to the given root directory
     rather than the root of the currently active virtual environment
     (if any) or the default root for the current Python installation.

   * ‘--user’: Installs ‘pip’ into the user site packages directory
     rather than globally for the current Python installation (this
     option is not permitted inside an active virtual environment).

By default, the scripts ‘pipX’ and ‘pipX.Y’ will be installed (where X.Y
stands for the version of Python used to invoke ‘ensurepip’).  The
scripts installed can be controlled through two additional command line
options:

   * ‘--altinstall’: if an alternate installation is requested, the
     ‘pipX’ script will `not' be installed.

   * ‘--default-pip’: if a "default pip" installation is requested, the
     ‘pip’ script will be installed in addition to the two regular
     scripts.

Providing both of the script selection options will trigger an
exception.


File: python.info,  Node: Module API,  Prev: Command line interface,  Up: ensurepip --- Bootstrapping the pip installer

5.28.2.2 Module API
...................

*note ensurepip: 7a. exposes two functions for programmatic use:

 -- 函数: ensurepip.version ()

     Returns a string specifying the bundled version of pip that will be
     installed when bootstrapping an environment.

 -- 函数: ensurepip.bootstrap (root=None, upgrade=False, user=False,
          altinstall=False, default_pip=False, verbosity=0)

     Bootstraps ‘pip’ into the current or designated environment.

     `root' specifies an alternative root directory to install relative
     to.  If `root' is ‘None’, then installation uses the default
     install location for the current environment.

     `upgrade' indicates whether or not to upgrade an existing
     installation of an earlier version of ‘pip’ to the bundled version.

     `user' indicates whether to use the user scheme rather than
     installing globally.

     By default, the scripts ‘pipX’ and ‘pipX.Y’ will be installed
     (where X.Y stands for the current version of Python).

     If `altinstall' is set, then ‘pipX’ will `not' be installed.

     If `default_pip' is set, then ‘pip’ will be installed in addition
     to the two regular scripts.

     Setting both `altinstall' and `default_pip' will trigger *note
     ValueError: 1fc.

     `verbosity' controls the level of output to *note sys.stdout: 317.
     from the bootstrapping operation.

     Raises an *note auditing event: ea1. ‘ensurepip.bootstrap’ with
     argument ‘root’.

          注解: The bootstrapping process has side effects on both
          ‘sys.path’ and ‘os.environ’.  Invoking the command line
          interface in a subprocess instead allows these side effects to
          be avoided.

          注解: The bootstrapping process may install additional modules
          required by ‘pip’, but other software should not assume those
          dependencies will always be present by default (as the
          dependencies may be removed in a future version of ‘pip’).


File: python.info,  Node: venv --- 创建虚拟环境,  Next: zipapp --- Manage executable Python zip archives,  Prev: ensurepip --- Bootstrapping the pip installer,  Up: 软件打包和分发

5.28.3 ‘venv’ — 创建虚拟环境
----------------------------

3.3 新版功能.

`源码：' Lib/venv/(1)

__________________________________________________________________

*note venv: 126. 模块支持使用自己的站点目录创建轻量级“虚拟环境”，可选择
与系统站点目录隔离。每个虚拟环境都有自己的 Python 二进制文件（与用于创建
此环境的二进制文件的版本相匹配），并且可以在其站点目录中拥有自己独立的已
安装 Python 软件包集。

有关 Python 虚拟环境的更多信息，请参阅 PEP 405(2) 。

参见
....

Python 打包用户指南：创建和使用虚拟环境(3)

* Menu:

* 创建虚拟环境: 创建虚拟环境<2>.
* API: API<2>.
* 一个扩展 EnvBuilder 的例子::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/venv/

   (2) https://www.python.org/dev/peps/pep-0405

   (3) 
https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#creating-a-virtual-environment


File: python.info,  Node: 创建虚拟环境<2>,  Next: API<2>,  Up: venv --- 创建虚拟环境

5.28.3.1 创建虚拟环境
.....................

通过执行 ‘venv’ 指令来创建一个 *note 虚拟环境: 3602.:

     python3 -m venv /path/to/new/virtual/environment

运行此命令将创建目标目录（父目录若不存在也将创建），并放置一个
‘pyvenv.cfg’ 文件在其中，文件中有一个 ‘home’ 键，它的值指向运行此命令的
Python 安装（目标目录的常用名称是 ‘.venv’）。它还会创建一个 ‘bin’ 子目录
（在 Windows 上是 ‘Scripts’），其中包含 Python 二进制文件的副本或符号链
接（视创建环境时使用的平台或参数而定）。它还会创建一个（初始为空的）
‘lib/pythonX.Y/site-packages’ 子目录（在 Windows 上是
‘Lib\site-packages’）。如果指定了一个现有的目录，这个目录就将被重新使用
。

3.6 版后已移除: ‘pyvenv’ 是 Python 3.3 和 3.4 中创建虚拟环境的推荐工具，
不过 在 Python 3.6 中已弃用(1)。

在 3.5 版更改: 现在推荐使用 ‘venv’ 来创建虚拟环境。

在 Windows 上，调用 ‘venv’ 命令如下:

     c:\>c:\Python35\python -m venv c:\path\to\myenv

或者，如果已经为 *note Python 安装: 2da. 配置好 ‘PATH’ 和 ‘PATHEXT’ 变量
:

     c:\>python -m venv c:\path\to\myenv

本命令如果以 ‘-h’ 参数运行，将显示可用的选项:

     usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
                 [--upgrade] [--without-pip] [--prompt PROMPT]
                 ENV_DIR [ENV_DIR ...]

     Creates virtual Python environments in one or more target directories.

     positional arguments:
       ENV_DIR               A directory to create the environment in.

     optional arguments:
       -h, --help            show this help message and exit
       --system-site-packages
                             Give the virtual environment access to the system
                             site-packages dir.
       --symlinks            Try to use symlinks rather than copies, when symlinks
                             are not the default for the platform.
       --copies              Try to use copies rather than symlinks, even when
                             symlinks are the default for the platform.
       --clear               Delete the contents of the environment directory if it
                             already exists, before environment creation.
       --upgrade             Upgrade the environment directory to use this version
                             of Python, assuming Python has been upgraded in-place.
       --without-pip         Skips installing or upgrading pip in the virtual
                             environment (pip is bootstrapped by default)
       --prompt PROMPT       Provides an alternative prompt prefix for this
                             environment.

     Once an environment has been created, you may wish to activate it, e.g. by
     sourcing an activate script in its bin directory.

在 3.4 版更改: 默认安装 pip，并添加 ‘--without-pip’ 和 ‘--copies’ 选项

在 3.4 版更改: 在早期版本中，如果目标目录已存在，将引发错误，除非使用了
‘--clear’ 或 ‘--upgrade’ 选项。

     注解: 虽然 Windows 支持符号链接，但不推荐使用它们。特别注意，在文件
     资源管理器中双击 ‘python.exe’ 将立即解析符号链接，并忽略虚拟环境。

     注解: 在 Microsoft Windows 上，为了启用 ‘Activate.ps1’ 脚本，可能需
     要修改用户的执行策略。可以运行以下 PowerShell 命令来执行此操作：

     PS C:> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope
     CurrentUser

     参阅 About Execution Policies(2) 以获取更多信息。

生成的 ‘pyvenv.cfg’ 文件还包括 ‘include-system-site-packages’ 键，如果运
行 ‘venv’ 带有 ‘--system-site-packages’ 选项，则键值为 ‘true’，否则为
‘false’。

除非采用 ‘--without-pip’ 选项，否则将会调用 *note ensurepip: 7a. 将
‘pip’ 引导到虚拟环境中。

可以向 ‘venv’ 传入多个路径，此时将根据给定的选项，在所给的每个路径上创建
相同的虚拟环境。

创建虚拟环境后，可以使用虚拟环境的二进制目录中的脚本来“激活”该环境。不同
平台调用的脚本是不同的（须将 ‘<venv>’ 替换为包含虚拟环境的目录路径）：

平台              Shell                 用于激活虚拟环境的命令
                                        
--------------------------------------------------------------------------------------
                                        
POSIX             bash/zsh              $ source <venv>/bin/activate
                                        
                                        
                  fish                  $ .  <venv>/bin/activate.fish
                                        
                                        
                  csh/tcsh              $ source <venv>/bin/activate.csh
                                        
                                        
                  PowerShell Core       $ <venv>/bin/Activate.ps1
                                        
                                        
Windows           cmd.exe               C:\> <venv>\Scripts\activate.bat
                                        
                                        
                  PowerShell            PS C:\> <venv>\Scripts\Activate.ps1
                                        

当一个虚拟环境被激活时， ‘VIRTUAL_ENV’ 环境变量会被设为该虚拟环境的路径
。 这可被用来检测程序是否运行在虚拟环境中。

激活环境不是 `必须' 的，激活只是将虚拟环境的二进制目录添加到搜索路径中，
这样 "python" 命令将调用虚拟环境的 Python 解释器，可以运行其中已安装的脚
本，而不必输入其完整路径。但是，安装在虚拟环境中的所有脚本都应在不激活的
情况下可运行，并自动与虚拟环境的 Python 一起运行。

在 shell 中输入 "deactivate" 可以退出虚拟环境。具体机制取决于不同平台，
并且是内部实现（通常使用脚本或 shell 函数）。

3.4 新版功能: ‘fish’ 和 ‘csh’ 激活脚本。

3.8 新版功能: 在 POSIX 上安装 PowerShell 激活脚本，以支持 PowerShell
Core。

     注解: 虚拟环境是一个 Python 环境，安装到其中的 Python 解释器、库和
     脚本与其他虚拟环境中的内容是隔离的，且（默认）与“系统级” Python（操
     作系统的一部分）中安装的库是隔离的。

     虚拟环境是一个目录树，其中包含 Python 可执行文件和其他文件，其他文
     件指示了这是一个是虚拟环境。

     常用安装工具如 setuptools(3) 和 pip(4) 可以在虚拟环境中按预期工作。
     换句话说，当虚拟环境被激活，它们就会将 Python 软件包安装到虚拟环境
     中，无需明确指示。

     当虚拟环境被激活（即虚拟环境的 Python 解释器正在运行），属性 *note
     sys.prefix: 3603. 和 *note sys.exec_prefix: 3604. 指向的是虚拟环境
     的基础目录，而 *note sys.base_prefix: 304e. 和 *note
     sys.base_exec_prefix: 3605. 指向非虚拟环境的 Python 安装，即曾用于
     创建虚拟环境的那个 Python 安装。如果虚拟环境没有被激活，则 *note
     sys.prefix: 3603. 与 *note sys.base_prefix: 304e. 相同，且 *note
     sys.exec_prefix: 3604. 与 *note sys.base_exec_prefix: 3605. 相同（
     它们均指向非虚拟环境的 Python 安装）。

     当虚拟环境被激活，所有 *note distutils: 39. 配置文件中更改安装路径
     的选项都会被忽略，以防止无意中将项目安装在虚拟环境之外。

     在命令行 shell 中工作时，用户可以运行虚拟环境可执行文件目录中的
     ‘activate’ 脚本来激活虚拟环境（调用该文件的确切文件名和命令取决于
     shell），这会将虚拟环境的可执行文件目录添加到当前 shell 的 ‘PATH’ 环
     境变量。在其他情况下，无需激活虚拟环境。安装到虚拟环境中的脚本有
     "shebang" 行，指向虚拟环境的 Python 解释器。这意味着无论 ‘PATH’ 的
     值如何，脚本都将与该解释器一起运行。在 Windows 上，如果已安装
     Python Launcher for Windows，则支持处理 "shebang" 行（此功能在
     Python 3.3 中添加，详情请参阅 PEP 397(5)）。这样，在 Windows 资源管
     理器中双击已安装的脚本，应该会使用正确的解释器运行该脚本，而在
     ‘PATH’ 中无需指向其虚拟环境。

   ---------- Footnotes ----------

   (1) https://docs.python.org/dev/whatsnew/3.6.html#deprecated-features

   (2) https://go.microsoft.com/fwlink/?LinkID=135170

   (3) https://pypi.org/project/setuptools/

   (4) https://pypi.org/project/pip/

   (5) https://www.python.org/dev/peps/pep-0397


File: python.info,  Node: API<2>,  Next: 一个扩展 EnvBuilder 的例子,  Prev: 创建虚拟环境<2>,  Up: venv --- 创建虚拟环境

5.28.3.2 API
............

上述的高级方法使用了一个简单的 API，该 API 提供了一种机制，第三方虚拟环
境创建者可以根据其需求自定义环境创建过程，该 API 为 *note EnvBuilder:
910. 类。

 -- 类: venv.EnvBuilder (system_site_packages=False, clear=False,
          symlinks=False, upgrade=False, with_pip=False, prompt=None)

     *note EnvBuilder: 910. 类在实例化时接受以下关键字参数：

        * ‘system_site_packages’ – 一个布尔值，要求系统 Python 的
          site-packages 对环境可用（默认为 ‘False’）。

        * ‘clear’ – 一个布尔值，如果为 true，则在创建环境前将删除目标目
          录的现有内容。

        * ‘symlinks’ – 一个布尔值，指示是否尝试符号链接 Python 二进制文
          件，而不是进行复制。

        * ‘upgrade’ – 一个布尔值，如果为 true，则将使用当前运行的 Python
          去升级一个现有的环境，这主要在原位置的 Python 更新后使用（默认
          为 ‘False’）。

        * ‘with_pip’ – 一个布尔值，如果为 true，则确保在虚拟环境中已安装
          pip。这使用的是带有 ‘--default-pip’ 选项的 *note ensurepip:
          7a.。

        * ‘prompt’ – a String to be used after virtual environment is
          activated (defaults to ‘None’ which means directory name of
          the environment would be used).

     在 3.4 版更改: 添加 ‘with_pip’ 参数

     3.6 新版功能: 添加 ‘prompt’ 参数

     第三方虚拟环境工具的创建者可以自由地将此处提供的 *note EnvBuilder:
     910. 类作为基类。

     返回的 env-builder 是一个对象，包含一个 ‘create’ 方法：

      -- 方法: create (env_dir)

          指定要建立虚拟环境的目标目录（绝对路径或相对于当前路径）来创建
          虚拟环境。‘create’ 方法将在指定目录中创建环境，或者引发对应的
          异常。

          *note EnvBuilder: 910. 类的 ‘create’ 方法说明了可用于定制子类
          的钩子:

               def create(self, env_dir):
                   """
                   Create a virtualized Python environment in a directory.
                   env_dir is the target directory to create an environment in.
                   """
                   env_dir = os.path.abspath(env_dir)
                   context = self.ensure_directories(env_dir)
                   self.create_configuration(context)
                   self.setup_python(context)
                   self.setup_scripts(context)
                   self.post_setup(context)

          每个方法 *note ensure_directories(): 3608, *note
          create_configuration(): 3609, *note setup_python(): 360a,
          *note setup_scripts(): 360b. 和 *note post_setup(): 360c. 都可
          以被重写。

      -- 方法: ensure_directories (env_dir)

          创建环境目录和所有必需的目录，并返回一个上下文对象。该对象只是
          一个容器，保存属性（如路径），供其他方法使用。允许目录已经存在
          ，如果指定了 ‘clear’ 或 ‘upgrade’ 就允许在现有环境目录上进行操
          作。

      -- 方法: create_configuration (context)

          在环境中创建 ‘pyvenv.cfg’ 配置文件。

      -- 方法: setup_python (context)

          在环境中创建 Python 可执行文件的拷贝或符号链接。在 POSIX 系统
          上，如果给定了可执行文件 ‘python3.x’，将创建指向该可执行文件的
          ‘python’ 和 ‘python3’ 符号链接，除非相同名称的文件已经存在。

      -- 方法: setup_scripts (context)

          将适用于平台的激活脚本安装到虚拟环境中。

      -- 方法: post_setup (context)

          占位方法，可以在第三方实现中重写，用于在虚拟环境中预安装软件包
          ，或是其他创建后要执行的步骤。

     在 3.7.2 版更改: Windows 现在为 ‘python[w].exe’ 使用重定向脚本，而
     不是复制实际的二进制文件。仅在 3.7.2 中，除非运行的是源码树中的构建
     ，否则 *note setup_python(): 360a. 不会执行任何操作。

     在 3.7.3 版更改: Windows 将重定向脚本复制为 *note setup_python():
     360a. 的一部分而非 *note setup_scripts(): 360b.。在 3.7.2 中不是这
     种情况。使用符号链接时，将链接至原始可执行文件。

     此外，*note EnvBuilder: 910. 提供了如下实用方法，可以从子类的 *note
     setup_scripts(): 360b. 或 *note post_setup(): 360c. 调用，用来将自
     定义脚本安装到虚拟环境中。

      -- 方法: install_scripts (context, path)

          `path' 是一个目录的路径，该目录应包含子目录 "common", "posix",
          "nt"，每个子目录存有发往对应环境中 bin 目录的脚本。在下列占位
          符替换完毕后，将复制 "common" 的内容和与 *note os.name: 1eef.
          对应的子目录：

             * ‘__VENV_DIR__’ 会被替换为环境目录的绝对路径。

             * ‘__VENV_NAME__’ 会被替换为环境名称（环境目录的最后一个字
               段）。

             * ‘__VENV_PROMPT__’ 会被替换为提示符（用括号括起来的环境名
               称紧跟着一个空格）。

             * ‘__VENV_BIN_NAME__’ 会被替换为 bin 目录的名称（ ‘bin’ 或
               ‘Scripts’ ）。

             * ‘__VENV_PYTHON__’ 会被替换为环境可执行文件的绝对路径。

          允许目录已存在（用于升级现有环境时）。

有一个方便实用的模块级别的函数:

 -- 函数: venv.create (env_dir, system_site_packages=False, clear=False,
          symlinks=False, with_pip=False, prompt=None)

     通过关键词参数来创建一个 *note EnvBuilder: 910.，并且使用 `env_dir'
     参数来调用它的 *note create(): 3607. 方法。

     3.3 新版功能.

     在 3.4 版更改: 添加 ‘with_pip’ 参数

     在 3.6 版更改: 添加 ‘prompt’ 参数


File: python.info,  Node: 一个扩展 EnvBuilder 的例子,  Prev: API<2>,  Up: venv --- 创建虚拟环境

5.28.3.3 一个扩展 ‘EnvBuilder’ 的例子
.....................................

下面的脚本展示了如何通过实现一个子类来扩展 *note EnvBuilder: 910.。这个
子类会安装 setuptotols 和 pip 的到被创建的虚拟环境中。

     import os
     import os.path
     from subprocess import Popen, PIPE
     import sys
     from threading import Thread
     from urllib.parse import urlparse
     from urllib.request import urlretrieve
     import venv

     class ExtendedEnvBuilder(venv.EnvBuilder):
         """
         This builder installs setuptools and pip so that you can pip or
         easy_install other packages into the created virtual environment.

         :param nodist: If true, setuptools and pip are not installed into the
                        created virtual environment.
         :param nopip: If true, pip is not installed into the created
                       virtual environment.
         :param progress: If setuptools or pip are installed, the progress of the
                          installation can be monitored by passing a progress
                          callable. If specified, it is called with two
                          arguments: a string indicating some progress, and a
                          context indicating where the string is coming from.
                          The context argument can have one of three values:
                          'main', indicating that it is called from virtualize()
                          itself, and 'stdout' and 'stderr', which are obtained
                          by reading lines from the output streams of a subprocess
                          which is used to install the app.

                          If a callable is not specified, default progress
                          information is output to sys.stderr.
         """

         def __init__(self, *args, **kwargs):
             self.nodist = kwargs.pop('nodist', False)
             self.nopip = kwargs.pop('nopip', False)
             self.progress = kwargs.pop('progress', None)
             self.verbose = kwargs.pop('verbose', False)
             super().__init__(*args, **kwargs)

         def post_setup(self, context):
             """
             Set up any packages which need to be pre-installed into the
             virtual environment being created.

             :param context: The information for the virtual environment
                             creation request being processed.
             """
             os.environ['VIRTUAL_ENV'] = context.env_dir
             if not self.nodist:
                 self.install_setuptools(context)
             # Can't install pip without setuptools
             if not self.nopip and not self.nodist:
                 self.install_pip(context)

         def reader(self, stream, context):
             """
             Read lines from a subprocess' output stream and either pass to a progress
             callable (if specified) or write progress information to sys.stderr.
             """
             progress = self.progress
             while True:
                 s = stream.readline()
                 if not s:
                     break
                 if progress is not None:
                     progress(s, context)
                 else:
                     if not self.verbose:
                         sys.stderr.write('.')
                     else:
                         sys.stderr.write(s.decode('utf-8'))
                     sys.stderr.flush()
             stream.close()

         def install_script(self, context, name, url):
             _, _, path, _, _, _ = urlparse(url)
             fn = os.path.split(path)[-1]
             binpath = context.bin_path
             distpath = os.path.join(binpath, fn)
             # Download script into the virtual environment's binaries folder
             urlretrieve(url, distpath)
             progress = self.progress
             if self.verbose:
                 term = '\n'
             else:
                 term = ''
             if progress is not None:
                 progress('Installing %s ...%s' % (name, term), 'main')
             else:
                 sys.stderr.write('Installing %s ...%s' % (name, term))
                 sys.stderr.flush()
             # Install in the virtual environment
             args = [context.env_exe, fn]
             p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath)
             t1 = Thread(target=self.reader, args=(p.stdout, 'stdout'))
             t1.start()
             t2 = Thread(target=self.reader, args=(p.stderr, 'stderr'))
             t2.start()
             p.wait()
             t1.join()
             t2.join()
             if progress is not None:
                 progress('done.', 'main')
             else:
                 sys.stderr.write('done.\n')
             # Clean up - no longer needed
             os.unlink(distpath)

         def install_setuptools(self, context):
             """
             Install setuptools in the virtual environment.

             :param context: The information for the virtual environment
                             creation request being processed.
             """
             url = 'https://bitbucket.org/pypa/setuptools/downloads/ez_setup.py'
             self.install_script(context, 'setuptools', url)
             # clear up the setuptools archive which gets downloaded
             pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz')
             files = filter(pred, os.listdir(context.bin_path))
             for f in files:
                 f = os.path.join(context.bin_path, f)
                 os.unlink(f)

         def install_pip(self, context):
             """
             Install pip in the virtual environment.

             :param context: The information for the virtual environment
                             creation request being processed.
             """
             url = 'https://bootstrap.pypa.io/get-pip.py'
             self.install_script(context, 'pip', url)

     def main(args=None):
         compatible = True
         if sys.version_info < (3, 3):
             compatible = False
         elif not hasattr(sys, 'base_prefix'):
             compatible = False
         if not compatible:
             raise ValueError('This script is only for use with '
                              'Python 3.3 or later')
         else:
             import argparse

             parser = argparse.ArgumentParser(prog=__name__,
                                              description='Creates virtual Python '
                                                          'environments in one or '
                                                          'more target '
                                                          'directories.')
             parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
                                 help='A directory in which to create the
                                      'virtual environment.')
             parser.add_argument('--no-setuptools', default=False,
                                 action='store_true', dest='nodist',
                                 help="Don't install setuptools or pip in the "
                                      "virtual environment.")
             parser.add_argument('--no-pip', default=False,
                                 action='store_true', dest='nopip',
                                 help="Don't install pip in the virtual "
                                      "environment.")
             parser.add_argument('--system-site-packages', default=False,
                                 action='store_true', dest='system_site',
                                 help='Give the virtual environment access to the '
                                      'system site-packages dir.')
             if os.name == 'nt':
                 use_symlinks = False
             else:
                 use_symlinks = True
             parser.add_argument('--symlinks', default=use_symlinks,
                                 action='store_true', dest='symlinks',
                                 help='Try to use symlinks rather than copies, '
                                      'when symlinks are not the default for '
                                      'the platform.')
             parser.add_argument('--clear', default=False, action='store_true',
                                 dest='clear', help='Delete the contents of the '
                                                    'virtual environment '
                                                    'directory if it already '
                                                    'exists, before virtual '
                                                    'environment creation.')
             parser.add_argument('--upgrade', default=False, action='store_true',
                                 dest='upgrade', help='Upgrade the virtual '
                                                      'environment directory to '
                                                      'use this version of '
                                                      'Python, assuming Python '
                                                      'has been upgraded '
                                                      'in-place.')
             parser.add_argument('--verbose', default=False, action='store_true',
                                 dest='verbose', help='Display the output '
                                                    'from the scripts which '
                                                    'install setuptools and pip.')
             options = parser.parse_args(args)
             if options.upgrade and options.clear:
                 raise ValueError('you cannot supply --upgrade and --clear together.')
             builder = ExtendedEnvBuilder(system_site_packages=options.system_site,
                                            clear=options.clear,
                                            symlinks=options.symlinks,
                                            upgrade=options.upgrade,
                                            nodist=options.nodist,
                                            nopip=options.nopip,
                                            verbose=options.verbose)
             for d in options.dirs:
                 builder.create(d)

     if __name__ == '__main__':
         rc = 1
         try:
             main()
             rc = 0
         except Exception as e:
             print('Error: %s' % e, file=sys.stderr)
         sys.exit(rc)

这个脚本同样可以 在线下载(1)。

   ---------- Footnotes ----------

   (1) https://gist.github.com/vsajip/4673395


File: python.info,  Node: zipapp --- Manage executable Python zip archives,  Prev: venv --- 创建虚拟环境,  Up: 软件打包和分发

5.28.4 ‘zipapp’ — Manage executable Python zip archives
-------------------------------------------------------

3.5 新版功能.

`Source code:' Lib/zipapp.py(1)

__________________________________________________________________

This module provides tools to manage the creation of zip files
containing Python code, which can be *note executed directly by the
Python interpreter: 134a.  The module provides both a *note 命令行界面:
3612. and a *note Python API: 3613.

* Menu:

* Basic Example::
* 命令行界面: 命令行界面<7>.
* Python API::
* 例子: 例子<27>.
* Specifying the Interpreter::
* Creating Standalone Applications with zipapp::
* The Python Zip Application Archive Format::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/zipapp.py


File: python.info,  Node: Basic Example,  Next: 命令行界面<7>,  Up: zipapp --- Manage executable Python zip archives

5.28.4.1 Basic Example
......................

The following example shows how the *note 命令行界面: 3612. can be used
to create an executable archive from a directory containing Python code.
When run, the archive will execute the ‘main’ function from the module
‘myapp’ in the archive.

     $ python -m zipapp myapp -m "myapp:main"
     $ python myapp.pyz
     <output from myapp>


File: python.info,  Node: 命令行界面<7>,  Next: Python API,  Prev: Basic Example,  Up: zipapp --- Manage executable Python zip archives

5.28.4.2 命令行界面
...................

When called as a program from the command line, the following form is
used:

     $ python -m zipapp source [options]

If `source' is a directory, this will create an archive from the
contents of `source'.  If `source' is a file, it should be an archive,
and it will be copied to the target archive (or the contents of its
shebang line will be displayed if the –info option is specified).

The following options are understood:

 -- 程序选项: -o <output>, --output=<output>

     Write the output to a file named `output'.  If this option is not
     specified, the output filename will be the same as the input
     `source', with the extension ‘.pyz’ added.  If an explicit filename
     is given, it is used as is (so a ‘.pyz’ extension should be
     included if required).

     An output filename must be specified if the `source' is an archive
     (and in that case, `output' must not be the same as `source').

 -- 程序选项: -p <interpreter>, --python=<interpreter>

     Add a ‘#!’ line to the archive specifying `interpreter' as the
     command to run.  Also, on POSIX, make the archive executable.  The
     default is to write no ‘#!’ line, and not make the file executable.

 -- 程序选项: -m <mainfn>, --main=<mainfn>

     Write a ‘__main__.py’ file to the archive that executes `mainfn'.
     The `mainfn' argument should have the form "pkg.mod:fn", where
     "pkg.mod" is a package/module in the archive, and "fn" is a
     callable in the given module.  The ‘__main__.py’ file will execute
     that callable.

     *note –main: 3618. cannot be specified when copying an archive.

 -- 程序选项: -c, --compress

     Compress files with the deflate method, reducing the size of the
     output file.  By default, files are stored uncompressed in the
     archive.

     *note –compress: 3619. has no effect when copying an archive.

     3.7 新版功能.

 -- 程序选项: --info

     Display the interpreter embedded in the archive, for diagnostic
     purposes.  In this case, any other options are ignored and SOURCE
     must be an archive, not a directory.

 -- 程序选项: -h, --help

     Print a short usage message and exit.


File: python.info,  Node: Python API,  Next: 例子<27>,  Prev: 命令行界面<7>,  Up: zipapp --- Manage executable Python zip archives

5.28.4.3 Python API
...................

The module defines two convenience functions:

 -- 函数: zipapp.create_archive (source, target=None, interpreter=None,
          main=None, filter=None, compressed=False)

     Create an application archive from `source'.  The source can be any
     of the following:

        * The name of a directory, or a *note path-like object: 373.
          referring to a directory, in which case a new application
          archive will be created from the content of that directory.

        * The name of an existing application archive file, or a *note
          path-like object: 373. referring to such a file, in which case
          the file is copied to the target (modifying it to reflect the
          value given for the `interpreter' argument).  The file name
          should include the ‘.pyz’ extension, if required.

        * A file object open for reading in bytes mode.  The content of
          the file should be an application archive, and the file object
          is assumed to be positioned at the start of the archive.

     The `target' argument determines where the resulting archive will
     be written:

        * If it is the name of a file, or a *note path-like object: 373,
          the archive will be written to that file.

        * If it is an open file object, the archive will be written to
          that file object, which must be open for writing in bytes
          mode.

        * If the target is omitted (or ‘None’), the source must be a
          directory and the target will be a file with the same name as
          the source, with a ‘.pyz’ extension added.

     The `interpreter' argument specifies the name of the Python
     interpreter with which the archive will be executed.  It is written
     as a "shebang" line at the start of the archive.  On POSIX, this
     will be interpreted by the OS, and on Windows it will be handled by
     the Python launcher.  Omitting the `interpreter' results in no
     shebang line being written.  If an interpreter is specified, and
     the target is a filename, the executable bit of the target file
     will be set.

     The `main' argument specifies the name of a callable which will be
     used as the main program for the archive.  It can only be specified
     if the source is a directory, and the source does not already
     contain a ‘__main__.py’ file.  The `main' argument should take the
     form "pkg.module:callable" and the archive will be run by importing
     "pkg.module" and executing the given callable with no arguments.
     It is an error to omit `main' if the source is a directory and does
     not contain a ‘__main__.py’ file, as otherwise the resulting
     archive would not be executable.

     The optional `filter' argument specifies a callback function that
     is passed a Path object representing the path to the file being
     added (relative to the source directory).  It should return ‘True’
     if the file is to be added.

     The optional `compressed' argument determines whether files are
     compressed.  If set to ‘True’, files in the archive are compressed
     with the deflate method; otherwise, files are stored uncompressed.
     This argument has no effect when copying an existing archive.

     If a file object is specified for `source' or `target', it is the
     caller’s responsibility to close it after calling create_archive.

     When copying an existing archive, file objects supplied only need
     ‘read’ and ‘readline’, or ‘write’ methods.  When creating an
     archive from a directory, if the target is a file object it will be
     passed to the ‘zipfile.ZipFile’ class, and must supply the methods
     needed by that class.

     3.7 新版功能: Added the `filter' and `compressed' arguments.

 -- 函数: zipapp.get_interpreter (archive)

     Return the interpreter specified in the ‘#!’ line at the start of
     the archive.  If there is no ‘#!’ line, return *note None: 158.
     The `archive' argument can be a filename or a file-like object open
     for reading in bytes mode.  It is assumed to be at the start of the
     archive.


File: python.info,  Node: 例子<27>,  Next: Specifying the Interpreter,  Prev: Python API,  Up: zipapp --- Manage executable Python zip archives

5.28.4.4 例子
.............

Pack up a directory into an archive, and run it.

     $ python -m zipapp myapp
     $ python myapp.pyz
     <output from myapp>

The same can be done using the *note create_archive(): 425. function:

     >>> import zipapp
     >>> zipapp.create_archive('myapp', 'myapp.pyz')

To make the application directly executable on POSIX, specify an
interpreter to use.

     $ python -m zipapp myapp -p "/usr/bin/env python"
     $ ./myapp.pyz
     <output from myapp>

To replace the shebang line on an existing archive, create a modified
archive using the *note create_archive(): 425. function:

     >>> import zipapp
     >>> zipapp.create_archive('old_archive.pyz', 'new_archive.pyz', '/usr/bin/python3')

To update the file in place, do the replacement in memory using a
‘BytesIO’ object, and then overwrite the source afterwards.  Note that
there is a risk when overwriting a file in place that an error will
result in the loss of the original file.  This code does not protect
against such errors, but production code should do so.  Also, this
method will only work if the archive fits in memory:

     >>> import zipapp
     >>> import io
     >>> temp = io.BytesIO()
     >>> zipapp.create_archive('myapp.pyz', temp, '/usr/bin/python2')
     >>> with open('myapp.pyz', 'wb') as f:
     >>>     f.write(temp.getvalue())


File: python.info,  Node: Specifying the Interpreter,  Next: Creating Standalone Applications with zipapp,  Prev: 例子<27>,  Up: zipapp --- Manage executable Python zip archives

5.28.4.5 Specifying the Interpreter
...................................

Note that if you specify an interpreter and then distribute your
application archive, you need to ensure that the interpreter used is
portable.  The Python launcher for Windows supports most common forms of
POSIX ‘#!’ line, but there are other issues to consider:

   * If you use "/usr/bin/env python" (or other forms of the "python"
     command, such as "/usr/bin/python"), you need to consider that your
     users may have either Python 2 or Python 3 as their default, and
     write your code to work under both versions.

   * If you use an explicit version, for example "/usr/bin/env python3"
     your application will not work for users who do not have that
     version.  (This may be what you want if you have not made your code
     Python 2 compatible).

   * There is no way to say "python X.Y or later", so be careful of
     using an exact version like "/usr/bin/env python3.4" as you will
     need to change your shebang line for users of Python 3.5, for
     example.

Typically, you should use an "/usr/bin/env python2" or "/usr/bin/env
python3", depending on whether your code is written for Python 2 or 3.


File: python.info,  Node: Creating Standalone Applications with zipapp,  Next: The Python Zip Application Archive Format,  Prev: Specifying the Interpreter,  Up: zipapp --- Manage executable Python zip archives

5.28.4.6 Creating Standalone Applications with zipapp
.....................................................

Using the *note zipapp: 142. module, it is possible to create
self-contained Python programs, which can be distributed to end users
who only need to have a suitable version of Python installed on their
system.  The key to doing this is to bundle all of the application’s
dependencies into the archive, along with the application code.

The steps to create a standalone archive are as follows:

  1. Create your application in a directory as normal, so you have a
     ‘myapp’ directory containing a ‘__main__.py’ file, and any
     supporting application code.

  2. Install all of your application’s dependencies into the ‘myapp’
     directory, using pip:

          $ python -m pip install -r requirements.txt --target myapp

     (this assumes you have your project requirements in a
     ‘requirements.txt’ file - if not, you can just list the
     dependencies manually on the pip command line).

  3. Optionally, delete the ‘.dist-info’ directories created by pip in
     the ‘myapp’ directory.  These hold metadata for pip to manage the
     packages, and as you won’t be making any further use of pip they
     aren’t required - although it won’t do any harm if you leave them.

  4. Package the application using:

          $ python -m zipapp -p "interpreter" myapp

This will produce a standalone executable, which can be run on any
machine with the appropriate interpreter available.  See *note
Specifying the Interpreter: 3621. for details.  It can be shipped to
users as a single file.

On Unix, the ‘myapp.pyz’ file is executable as it stands.  You can
rename the file to remove the ‘.pyz’ extension if you prefer a "plain"
command name.  On Windows, the ‘myapp.pyz[w]’ file is executable by
virtue of the fact that the Python interpreter registers the ‘.pyz’ and
‘.pyzw’ file extensions when installed.

* Menu:

* Making a Windows executable::
* Caveats::


File: python.info,  Node: Making a Windows executable,  Next: Caveats,  Up: Creating Standalone Applications with zipapp

5.28.4.7 Making a Windows executable
....................................

On Windows, registration of the ‘.pyz’ extension is optional, and
furthermore, there are certain places that don’t recognise registered
extensions "transparently" (the simplest example is that
‘subprocess.run(['myapp'])’ won’t find your application - you need to
explicitly specify the extension).

On Windows, therefore, it is often preferable to create an executable
from the zipapp.  This is relatively easy, although it does require a C
compiler.  The basic approach relies on the fact that zipfiles can have
arbitrary data prepended, and Windows exe files can have arbitrary data
appended.  So by creating a suitable launcher and tacking the ‘.pyz’
file onto the end of it, you end up with a single-file executable that
runs your application.

A suitable launcher can be as simple as the following:

     #define Py_LIMITED_API 1
     #include "Python.h"

     #define WIN32_LEAN_AND_MEAN
     #include <windows.h>

     #ifdef WINDOWS
     int WINAPI wWinMain(
         HINSTANCE hInstance,      /* handle to current instance */
         HINSTANCE hPrevInstance,  /* handle to previous instance */
         LPWSTR lpCmdLine,         /* pointer to command line */
         int nCmdShow              /* show state of window */
     )
     #else
     int wmain()
     #endif
     {
         wchar_t **myargv = _alloca((__argc + 1) * sizeof(wchar_t*));
         myargv[0] = __wargv[0];
         memcpy(myargv + 1, __wargv, __argc * sizeof(wchar_t *));
         return Py_Main(__argc+1, myargv);
     }

If you define the ‘WINDOWS’ preprocessor symbol, this will generate a
GUI executable, and without it, a console executable.

To compile the executable, you can either just use the standard MSVC
command line tools, or you can take advantage of the fact that distutils
knows how to compile Python source:

     >>> from distutils.ccompiler import new_compiler
     >>> import distutils.sysconfig
     >>> import sys
     >>> import os
     >>> from pathlib import Path

     >>> def compile(src):
     >>>     src = Path(src)
     >>>     cc = new_compiler()
     >>>     exe = src.stem
     >>>     cc.add_include_dir(distutils.sysconfig.get_python_inc())
     >>>     cc.add_library_dir(os.path.join(sys.base_exec_prefix, 'libs'))
     >>>     # First the CLI executable
     >>>     objs = cc.compile([str(src)])
     >>>     cc.link_executable(objs, exe)
     >>>     # Now the GUI executable
     >>>     cc.define_macro('WINDOWS')
     >>>     objs = cc.compile([str(src)])
     >>>     cc.link_executable(objs, exe + 'w')

     >>> if __name__ == "__main__":
     >>>     compile("zastub.c")

The resulting launcher uses the "Limited ABI", so it will run unchanged
with any version of Python 3.x.  All it needs is for Python
(‘python3.dll’) to be on the user’s ‘PATH’.

For a fully standalone distribution, you can distribute the launcher
with your application appended, bundled with the Python "embedded"
distribution.  This will run on any PC with the appropriate architecture
(32 bit or 64 bit).


File: python.info,  Node: Caveats,  Prev: Making a Windows executable,  Up: Creating Standalone Applications with zipapp

5.28.4.8 Caveats
................

There are some limitations to the process of bundling your application
into a single file.  In most, if not all, cases they can be addressed
without needing major changes to your application.

  1. If your application depends on a package that includes a C
     extension, that package cannot be run from a zip file (this is an
     OS limitation, as executable code must be present in the filesystem
     for the OS loader to load it).  In this case, you can exclude that
     dependency from the zipfile, and either require your users to have
     it installed, or ship it alongside your zipfile and add code to
     your ‘__main__.py’ to include the directory containing the unzipped
     module in ‘sys.path’.  In this case, you will need to make sure to
     ship appropriate binaries for your target architecture(s) (and
     potentially pick the correct version to add to ‘sys.path’ at
     runtime, based on the user’s machine).

  2. If you are shipping a Windows executable as described above, you
     either need to ensure that your users have ‘python3.dll’ on their
     PATH (which is not the default behaviour of the installer) or you
     should bundle your application with the embedded distribution.

  3. The suggested launcher above uses the Python embedding API. This
     means that in your application, ‘sys.executable’ will be your
     application, and `not' a conventional Python interpreter.  Your
     code and its dependencies need to be prepared for this possibility.
     For example, if your application uses the *note multiprocessing:
     b8. module, it will need to call *note
     multiprocessing.set_executable(): 23d8. to let the module know
     where to find the standard Python interpreter.


File: python.info,  Node: The Python Zip Application Archive Format,  Prev: Creating Standalone Applications with zipapp,  Up: zipapp --- Manage executable Python zip archives

5.28.4.9 The Python Zip Application Archive Format
..................................................

Python has been able to execute zip files which contain a ‘__main__.py’
file since version 2.6.  In order to be executed by Python, an
application archive simply has to be a standard zip file containing a
‘__main__.py’ file which will be run as the entry point for the
application.  As usual for any Python script, the parent of the script
(in this case the zip file) will be placed on *note sys.path: 490. and
thus further modules can be imported from the zip file.

The zip file format allows arbitrary data to be prepended to a zip file.
The zip application format uses this ability to prepend a standard POSIX
"shebang" line to the file (‘#!/path/to/interpreter’).

Formally, the Python zip application format is therefore:

  1. An optional shebang line, containing the characters ‘b'#!'’
     followed by an interpreter name, and then a newline (‘b'\n'’)
     character.  The interpreter name can be anything acceptable to the
     OS "shebang" processing, or the Python launcher on Windows.  The
     interpreter should be encoded in UTF-8 on Windows, and in *note
     sys.getfilesystemencoding(): 4fe. on POSIX.

  2. Standard zipfile data, as generated by the *note zipfile: 143.
     module.  The zipfile content `must' include a file called
     ‘__main__.py’ (which must be in the "root" of the zipfile - i.e.,
     it cannot be in a subdirectory).  The zipfile data can be
     compressed or uncompressed.

If an application archive has a shebang line, it may have the executable
bit set on POSIX systems, to allow it to be executed directly.

There is no requirement that the tools in this module are used to create
application archives - the module is a convenience, but archives in the
above format created by any means are acceptable to Python.


File: python.info,  Node: Python运行时服务,  Next: 自定义 Python 解释器,  Prev: 软件打包和分发,  Up: Python 标准库

5.29 Python运行时服务
=====================

本章里描述的模块提供了和Python解释器及其环境交互相关的广泛服务。以下是综
述：

* Menu:

* sys: sys --- 系统相关的参数和函数. 系统相关的参数和函数
* sysconfig: sysconfig --- Provide access to Python's configuration information. Provide access to Python’s configuration information
* builtins: builtins --- 内建对象. 内建对象
* __main__: __main__ --- 顶层脚本环境. 顶层脚本环境
* warnings: warnings --- Warning control. Warning control
* dataclasses: dataclasses --- 数据类. 数据类
* contextlib: contextlib --- 为 with语句上下文提供的工具. 为 with语句上下文提供的工具
* abc: abc --- 抽象基类. 抽象基类
* atexit: atexit --- 退出处理器. 退出处理器
* traceback: traceback --- 打印或检索堆栈回溯. 打印或检索堆栈回溯
* __future__: __future__ --- Future 语句定义. Future 语句定义
* gc: gc --- 垃圾回收器接口. 垃圾回收器接口
* inspect: inspect --- 检查对象. 检查对象
* site —— 站点专属的配置钩子::


File: python.info,  Node: sys --- 系统相关的参数和函数,  Next: sysconfig --- Provide access to Python's configuration information,  Up: Python运行时服务

5.29.1 ‘sys’ — 系统相关的参数和函数
-----------------------------------

__________________________________________________________________

该模块提供了一些变量和函数。这些变量可能被解释器使用，也可能由解释器提供
。这些函数会影响解释器。本模块总是可用的。

 -- 数据: sys.abiflags

     在POSIX系统上，以标准的 ‘configure’ 脚本构建的 Python 中，这个变量
     会包含 PEP 3149(1) 中定义的ABI标签。

     在 3.8 版更改: 默认的 flags 变为了空字符串（用于 pymalloc 的 ‘m’ 旗
     标已经移除）

     3.2 新版功能.

 -- 函数: sys.addaudithook (hook)

     将可调用对象 `hook' 附加到当前（子）解释器的活动的审计钩子列表中。

     当通过 *note sys.audit(): f38. 函数引发审计事件时，每个钩子将按照其
     被加入的先后顺序被调用，调用时会传入事件名称和参数元组。 由 *note
     PySys_AddAuditHook(): 34d1. 添加的原生钩子会先被调用，然后是当前（
     子）解释器中添加的钩子。 接下来这些钩子会记录事件，引发异常来中止操
     作，或是完全终止进程。

     调用 *note sys.addaudithook(): 34d0. 时它自身将引发一个名为
     ‘sys.addaudithook’ 的审计事件且不附带参数。 如果任何现有的钩子引发
     了派生自 *note RuntimeError: 2bb. 的异常，则新的钩子不会被添加并且
     该异常会被抑制。 其结果就是，调用者无法确保他们的钩子已经被添加，除
     非他们控制了全部现有的钩子。

     请参阅 *note 审计事件表: 34cd. 以获取由 CPython 引发的所有事件，并
     参阅 PEP 578(2) 了解最初的设计讨论。

     3.8 新版功能.

     在 3.8.1 版更改: 派生自 *note Exception: 1aa. （而非 *note
     RuntimeError: 2bb. ）的异常不会被抑制。

     `CPython implementation detail:' 启用跟踪时（参阅 *note settrace():
     e46. ），仅当可调用对象（钩子）的 ‘__cantrace__’ 成员设置为 true 时
     ，才会跟踪该钩子。否则，跟踪功能将跳过该钩子。

 -- 数据: sys.argv

     一个列表，其中包含了被传递给 Python 脚本的命令行参数。 ‘argv[0]’ 为
     脚本的名称（是否是完整的路径名取决于操作系统）。如果是通过 Python 解
     释器的命令行参数 *note -c: 121b. 来执行的， ‘argv[0]’ 会被设置成字
     符串 ‘'-c'’ 。如果没有脚本名被传递给 Python 解释器， ‘argv[0]’ 为空
     字符串。

     为了遍历标准输入，或者通过命令行传递的文件列表，参照 *note
     fileinput: 80. 模块

          注解: 在 Unix 上，系统传递的命令行参数是字节类型的。Python 使
          用文件系统编码和 "surrogateescape" 错误处理程序对它们进行解码
          。当需要原始字节时，可以通过 ‘[os.fsencode(arg) for arg in
          sys.argv]’ 来获取。
 -- 函数: sys.audit (event, *args)

     引发一个审计事件并触发任何激活的审计钩子。 `event' 是一个用于标识事
     件的字符串，`args' 会包含有关事件的更多信息的可选参数。 特定事件的
     参数的数量和类型会被视为是公有的稳定 API 且不应当在版本之间进行修改
     。

     例如，有一个审计事件的名称为 ‘os.chdir’。 此事件具有一个名为 `path'
     的参数，该参数将包含所请求的新工作目录。

     *note sys.audit(): f38. 将调用现有的审计钩子，传入事件名称和参数，
     并将重新引发来自任何钩子的第一个异常。 通常来说，如果有一个异常被引
     发，则它不应当被处理且其进程应当被尽可能快地终止。 这将允许钩子实现
     来决定对特定事件要如何反应：它们可以只是将事件写入日志或是通过引发
     异常来中止操作。

     钩子程序由 *note sys.addaudithook(): 34d0. 或 *note
     PySys_AddAuditHook(): 34d1. 函数添加。

     与本函数相等效的原生函数是 *note PySys_Audit(): f46.，应尽量使用原
     生函数。

     参阅 *note 审计事件表: 34cd. 以获取 CPython 定义的所有审计事件。

     3.8 新版功能.

 -- 数据: sys.base_exec_prefix

     在 ‘site.py’ 运行之前， Python 启动的时候被设置为跟 *note
     exec_prefix: 3604. 同样的值。如果不是运行在 *note 虚拟环境: 3602. 中
     ，两个值会保持相同；如果 ‘site.py’ 发现处于一个虚拟环境中， *note
     prefix: 3603. 和 *note exec_prefix: 3604. 将会指向虚拟环境。然而
     *note base_prefix: 304e. 和 *note base_exec_prefix: 3605. 将仍然会
     指向基础的 Python 环境（用来创建虚拟环境的 Python 环境）

     3.3 新版功能.

 -- 数据: sys.base_prefix

     在 ‘site.py’ 运行之前， Python 启动的时候被设置为跟 *note prefix:
     3603. 同样的值。如果不是运行在 *note 虚拟环境: 3602. 中, 两个值会保
     持相同；如果 ‘site.py’ 发现处于一个虚拟环境中， *note prefix: 3603.
     和 *note exec_prefix: 3604. 将会指向虚拟环境。然而 *note
     base_prefix: 304e. 和 *note base_exec_prefix: 3605. 将仍然会指向基
     础的 Python 环境（用来创建虚拟环境的 Python 环境）

     3.3 新版功能.

 -- 数据: sys.byteorder

     本地字节顺序的指示符。在大端序（最高有效位优先）操作系统上值为
     ‘'big'’ ，在小端序（最低有效位优先）操作系统上为 ‘'little'’ 。

 -- 数据: sys.builtin_module_names

     一个元素为字符串的元组。包含了所有的被编译进 Python 解释器的模块。
     （这个信息无法通过其他的办法获取， ‘modules.keys()’ 只包括被导入过
     的模块。）

 -- 函数: sys.call_tracing (func, args)

     在启用跟踪时调用 ‘func(*args)’ 来保存跟踪状态，然后恢复跟踪状态。这
     将从检查点的调试器调用，以便递归地调试其他的一些代码。

 -- 数据: sys.copyright

     一个字符串，包含了 Python 解释器有关的版权信息

 -- 函数: sys._clear_type_cache ()

     清除内部的类型缓存。类型缓存是为了加速查找方法和属性的。在调试引用
     泄漏的时候调用这个函数 `只会' 清除不必要的引用。

     这个函数应该只在内部为了一些特定的目的使用。

 -- 函数: sys._current_frames ()

     返回一个字典，存放着每个线程的标识符与（调用本函数时）该线程栈顶的
     帧（当前活动的帧）之间的映射。注意 *note traceback: 114. 模块中的函
     数可以在给定某一帧的情况下构建调用堆栈。

     这对于调试死锁最有用：本函数不需要死锁线程的配合，并且只要这些线程
     的调用栈保持死锁，它们就是冻结的。在调用本代码来检查栈顶的帧的那一
     刻，非死锁线程返回的帧可能与该线程当前活动的帧没有任何关系。

     这个函数应该只在内部为了一些特定的目的使用。

     引发一个 *note 审计事件: ea1. ‘sys._current_frames’，没有附带参数。

 -- 函数: sys.breakpointhook ()

     本钩子函数由内建函数 *note breakpoint(): 302. 调用。默认情况下，它
     将进入 *note pdb: ca. 调试器，但可以将其改为任何其他函数，以选择使
     用哪个调试器。

     该函数的特征取决于其调用的函数。例如，默认绑定（即
     ‘pdb.set_trace()’ ）不要求提供参数，但可以将绑定换成要求提供附加参
     数（位置参数/关键字参数）的函数。内建函数 ‘breakpoint()’ 直接将其
     ‘*args’ 和 ‘**kws’ 传入。‘breakpointhooks()’ 返回的所有内容都会从
     ‘breakpoint()’ 返回。

     默认的实现首先会查询环境变量 *note PYTHONBREAKPOINT: 31d.。如果将该
     变量设置为 ‘"0"’，则本函数立即返回，表示在断点处无操作。如果未设置
     该环境变量或将其设置为空字符串，则调用 ‘pdb.set_trace()’。否则，此
     变量应指定要运行的函数，指定函数时应使用 Python 的点导入命名法，如
     ‘package.subpackage.module.function’。这种情况下将导入
     ‘package.subpackage.module’，且导入的模块必须有一个名为
     ‘function()’ 的可调用对象。该可调用对象会运行，‘*args’ 和 ‘**kws’ 会
     传入，且无论 ‘function()’ 返回什么，‘sys.breakpointhook()’ 都将返回
     到內建函数 *note breakpoint(): 302.。

     注意，如果在导入 *note PYTHONBREAKPOINT: 31d. 指定的可调用对象时出
     错，则将报告一个 *note RuntimeWarning: 2c1. 并忽略断点。

     另请注意，如果以编程方式覆盖 ‘sys.breakpointhook()’，则 `不会' 查询
     *note PYTHONBREAKPOINT: 31d.。

     3.7 新版功能.

 -- 函数: sys._debugmallocstats ()

     将有关 CPython 内存分配器状态的底层的信息打印至 stderr。

     如果 Python 被配置为 –with-pydebug，本方法还将执行一些开销较大的内
     部一致性检查。

     3.3 新版功能.

     `CPython implementation detail:' 本函数仅限 CPython。此处没有定义确
     切的输出格式，且可能会更改。

 -- 数据: sys.dllhandle

     指向 Python DLL 句柄的整数。

     *note 可用性: 136f.: Windows。

 -- 函数: sys.displayhook (value)

     如果 `value' 不是 ‘None’，则本函数会将 ‘repr(value)’ 打印至
     ‘sys.stdout’，并将 `value' 保存在 ‘builtins._’ 中。如果
     ‘repr(value)’ 无法用 ‘sys.stdout.errors’ 错误回调方法（可能较为“严
     格”）编码为 ‘sys.stdout.encoding’，请用 ‘'backslashreplace'’ 错误回
     调方法将其编码为 ‘sys.stdout.encoding’。

     在交互式 Python 会话中运行 *note expression: 3631. 产生结果后，将在
     结果上调用 ‘sys.displayhook’。若要自定义这些 value 的显示，可以将
     ‘sys.displayhook’ 指定为另一个单参数函数。

     伪代码:

          def displayhook(value):
              if value is None:
                  return
              # Set '_' to None to avoid recursion
              builtins._ = None
              text = repr(value)
              try:
                  sys.stdout.write(text)
              except UnicodeEncodeError:
                  bytes = text.encode(sys.stdout.encoding, 'backslashreplace')
                  if hasattr(sys.stdout, 'buffer'):
                      sys.stdout.buffer.write(bytes)
                  else:
                      text = bytes.decode(sys.stdout.encoding, 'strict')
                      sys.stdout.write(text)
              sys.stdout.write("\n")
              builtins._ = value

     在 3.2 版更改: 在发生 *note UnicodeEncodeError: 1fd. 时使用
     ‘'backslashreplace'’ 错误回调方法。

 -- 数据: sys.dont_write_bytecode

     如果该值为 true，则 Python 在导入源码模块时将不会尝试写入 ‘.pyc’ 文
     件。该值会被初始化为 ‘True’ 或 ‘False’，依据是 *note -B: d40. 命令
     行选项和 *note PYTHONDONTWRITEBYTECODE: d41. 环境变量，可以自行设置
     该值，来控制是否生成字节码文件。

 -- 数据: sys.pycache_prefix

     如果将该选项设为某个目录（不是 ‘None’ ），Python 会将字节码缓存文件
     ‘.pyc’ 写入到以该目录为根的并行目录树中（并从中读取），而不是在源码
     树中的 ‘__pycache__’ 目录下读写。源码树中所有的 ‘__pycache__’ 目录
     都将被忽略，并将在 pycache prefix 内写入新的 ‘.pyc’ 文件。因此，如
     果使用 *note compileall: 21. 作为预构建步骤，则必须确保预构建时使用
     的 pycache prefix （如果有）与将来运行的时候相同。

     相对路径将解释为相对于当前工作目录。

     该值的初值设置，依据 *note -X: 156. ‘pycache_prefix=PATH’ 命令行选
     项或 *note PYTHONPYCACHEPREFIX: 155. 环境变量的值（命令行优先）。如
     果两者均未设置，则为 ‘None’。

     3.8 新版功能.

 -- 函数: sys.excepthook (type, value, traceback)

     本函数会将所给的回溯和异常输出到 ‘sys.stderr’ 中。

     当抛出一个异常，且未被捕获时，解释器将调用 ‘sys.excepthook’ 并带有
     三个参数：异常类、异常实例和一个回溯对象。在交互式会话中，这会在控
     制权返回到提示符之前发生。在 Python 程序中，这会在程序退出之前发生
     。如果要自定义此类顶级异常的处理过程，可以将另一个 3 个参数的函数赋
     给 ‘sys.excepthook’。

     引发一个 *note 审计事件: ea1. ‘sys.excepthook’，附带参数 ‘hook’,
     ‘type’, ‘value’, ‘traceback’。

     参见
     ....

     *note sys.unraisablehook(): 22e. 函数处理无法抛出的异常，*note
     threading.excepthook(): 232. 函数处理 *note threading.Thread.run():
     233. 抛出的异常。

 -- 数据: sys.__breakpointhook__
 -- 数据: sys.__displayhook__
 -- 数据: sys.__excepthook__
 -- 数据: sys.__unraisablehook__

     程序开始时，这些对象存有 ‘breakpointhook’、‘displayhook’、
     ‘excepthook’ 和 ‘unraisablehook’ 的初始值。保存它们是为了可以在
     ‘breakpointhook’、‘displayhook’ 和 ‘excepthook’、‘unraisablehook’ 被
     破坏或被替换时恢复它们。

     3.7 新版功能: __breakpointhook__

     3.8 新版功能: __unraisablehook__

 -- 函数: sys.exc_info ()

     本函数返回的元组包含三个值，它们给出当前正在处理的异常的信息。返回
     的信息仅限于当前线程和当前堆栈帧。如果当前堆栈帧没有正在处理的异常
     ，则信息将从调用的下级堆栈帧或上级调用者等位置获取，依此类推，直到
     找到正在处理异常的堆栈帧为止。此处的“处理异常”被定义为“执行 except
     子句”。任何堆栈帧都只能访问当前正在处理的异常的信息。

     如果整个堆栈都没有正在处理的异常，则返回包含三个 ‘None’ 值的元组。
     否则返回值为 ‘(type, value, traceback)’。它们的含义是：`type' 是正
     在处理的异常类型（它是 *note BaseException: 1a9. 的子类）；`value'
     是异常实例（异常类型的实例）；`traceback' 是一个 *note 回溯对象:
     33f.，该对象封装了最初发生异常时的调用堆栈。

 -- 数据: sys.exec_prefix

     一个字符串，给出特定域的目录前缀，该目录中安装了与平台相关的 Python
     文件，默认也是 ‘'/usr/local'’。该目录前缀可以在构建时使用
     ‘configure’ 脚本的 ‘--exec-prefix’ 参数进行设置。具体而言，所有配置
     文件（如 ‘pyconfig.h’ 头文件）都安装在目录
     ‘`exec_prefix'/lib/python`X.Y'/config’ 中，共享库模块安装在
     ‘`exec_prefix'/lib/python`X.Y'/lib-dynload’ 中，其中 `X.Y' 是
     Python 的版本号，如 ‘3.2’。

          注解: 如果在一个 *note 虚拟环境: 3602. 中，那么该值将在
          ‘site.py’ 中被修改，指向虚拟环境。Python 安装位置仍然可以用
          *note base_exec_prefix: 3605. 来获取。

 -- 数据: sys.executable

     一个字符串，提供 Python 解释器的可执行二进制文件的绝对路径，仅在部
     分系统中此值有意义。如果 Python 无法获取其可执行文件的真实路径，则
     *note sys.executable: 275. 将为空字符串或 ‘None’。

 -- 函数: sys.exit ([arg])

     从Python中退出。实现方式是抛出一个 *note SystemExit: 605. 异常。异
     常抛出后 *note try: d7a. 声明的 finally 分支语句的清除动作将被出发
     。此动作有可能打断更外层的退出尝试。

     可选参数 `arg' 可以是表示退出状态的整数（默认为 0），也可以是其他类
     型的对象。如果它是整数，则 shell 等将 0 视为“成功终止”，非零值视为
     “异常终止”。大多数系统要求该值的范围是 0–127，否则会产生不确定的结
     果。某些系统为退出代码约定了特定的含义，但通常尚不完善；Unix 程序通
     常用 2 表示命令行语法错误，用 1 表示所有其他类型的错误。传入其他类
     型的对象，如果传入 ‘None’ 等同于传入 0，如果传入其他对象则将其打印
     至 *note stderr: 318.，且退出代码为 1。特别地，‘sys.exit("some
     error message")’ 可以在发生错误时快速退出程序。

     由于 *note exit(): 161f. 最终“只是”抛出一个异常，因此当从主线程调用
     时，只会从进程退出；而异常不会因此被打断。

     在 3.6 版更改: 在 Python 解释器捕获 *note SystemExit: 605. 后，如果
     在清理中发生错误（如清除标准流中的缓冲数据时出错），则退出状态码将
     变为 120。

 -- 数据: sys.flags

     *note 具名元组: aab. `flags' 含有命令行标志的状态。这些属性是只读的
     。

     attribute – 属性                  标志
                                       
     --------------------------------------------------------------------
                                       
     ‘debug’                           *note -d: 1352.
                                       
                                       
     *note inspect: a1.                *note -i: e27.
                                       
                                       
     ‘interactive’                     *note -i: e27.
                                       
                                       
     ‘isolated’                        *note -I: 1018.
                                       
                                       
     ‘optimize’                        *note -O: 694. 或
                                       *note -OO: 695.
                                       
                                       
     *note dont_write_bytecode: 3632.  *note -B: d40.
                                       
                                       
     ‘no_user_site’                    *note -s: d1d.
                                       
                                       
     ‘no_site’                         *note -S: b2c.
                                       
                                       
     ‘ignore_environment’              *note -E: 1019.
                                       
                                       
     ‘verbose’                         *note -v: d90.
                                       
                                       
     ‘bytes_warning’                   *note -b: 41d.
                                       
                                       
     ‘quiet’                           *note -q: 1355.
                                       
                                       
     ‘hash_randomization’              *note -R: 10a4.
                                       
                                       
     ‘dev_mode’                        *note -X: 156. ‘dev’
                                       
                                       
     ‘utf8_mode’                       *note -X: 156. ‘utf8’
                                       

     在 3.2 版更改: 为新的 *note -q: 1355. 标志添加了 ‘quiet’ 属性

     3.2.3 新版功能: ‘hash_randomization’ 属性

     在 3.3 版更改: 删除了过时的 ‘division_warning’ 属性

     在 3.4 版更改: 为 *note -I: 1018. ‘isolated’ 标志添加了 ‘isolated’
     属性。

     在 3.7 版更改: Added ‘dev_mode’ attribute for the new *note -X:
     156. ‘dev’ flag and ‘utf8_mode’ attribute for the new *note -X:
     156. ‘utf8’ flag.

 -- 数据: sys.float_info

     一个 *note 具名元组: aab.，存有浮点型的相关信息。它包含的是关于精度
     和内部表示的底层信息。这些值与标准头文件 ‘float.h’ 中为 C 语言定义
     的各种浮点常量对应，详情请参阅 1999 ISO/IEC C 标准 *note [C99]:
     3637. 的 5.2.4.2.2 节，’Characteristics of floating types（浮点型的
     特性）’。

     attribute – 属性          float.h 宏           说明
                                                    
     ------------------------------------------------------------------------------------------------------
                                                    
     ‘epsilon’                 DBL_EPSILON          大于 1.0 的最小值和 1.0 之间的差，表示为浮点数
                                                    
                                                    
     ‘dig’                     DBL_DIG              浮点数可以真实表示的最大十进制数字；见下文
                                                    
                                                    
     ‘mant_dig’                DBL_MANT_DIG         浮点数精度：‘radix’ 基数下的浮点数有效位数
                                                    
                                                    
     *note max: 813.           DBL_MAX              最大可表示的正有限浮点数
                                                    
                                                    
     ‘max_exp’                 DBL_MAX_EXP          使得 ‘radix**(e-1)’ 是可表示的浮点数（非无穷）的最大
                                                    整数 `e'
                                                    
                                                    
     ‘max_10_exp’              DBL_MAX_10_EXP       使得 ‘10**e’ 在可表示的浮点数（非无穷）范围内的最大
                                                    整数 `e'
                                                    
                                                    
     *note min: 812.           DBL_MIN              可表示的最小正 `规格化' 浮点数
                                                    
                                                    
     ‘min_exp’                 DBL_MIN_EXP          使得 ‘radix**(e-1)’ 是规格化浮点数的最小整数 `e'
                                                    
                                                    
     ‘min_10_exp’              DBL_MIN_10_EXP       使得 ‘10**e’ 是规格化浮点数的最小整数 `e'
                                                    
                                                    
     ‘radix’                   FLT_RADIX            指数表示法中采用的基数
                                                    
                                                    
     ‘rounds’                  FLT_ROUNDS           整数常数，表示算术运算中的舍入方式。它反映了解释器启
                                                    动时系统的 FLT_ROUNDS 宏的值。关于可能的值及其含义的
                                                    说明，请参阅 C99 标准 5.2.4.2.2 节。
                                                    

     关于 ‘sys.float_info.dig’ 属性的进一步说明。如果 ‘s’ 是表示十进制数
     的字符串，而该数最多有 ‘sys.float_info.dig’ 位有效数字，则将 ‘s’ 转
     换为 float 再转回去将恢复原先相同十进制值的字符串:

          >>> import sys
          >>> sys.float_info.dig
          15
          >>> s = '3.14159265358979'    # decimal string with 15 significant digits
          >>> format(float(s), '.15g')  # convert to float and back -> same value
          '3.14159265358979'

     但是对于超过 ‘sys.float_info.dig’ 位有效数字的字符串，转换前后并非
     总是相同:

          >>> s = '9876543211234567'    # 16 significant digits is too many!
          >>> format(float(s), '.16g')  # conversion changes value
          '9876543211234568'

 -- 数据: sys.float_repr_style

     一个字符串，反映 *note repr(): 7d5. 函数在浮点数上的行为。如果该字
     符串是 ‘'short'’，那么对于（非无穷的）浮点数 ‘x’，‘repr(x)’ 将会生
     成一个短字符串，满足 ‘float(repr(x)) == x’ 的特性。这是 Python 3.1
     及更高版本中的常见行为。否则 ‘float_repr_style’ 的值将是
     ‘'legacy'’，此时 ‘repr(x)’ 的行为方式将与 Python 3.1 之前的版本相同
     。

     3.1 新版功能.

 -- 函数: sys.getallocatedblocks ()

     返回解释器当前已分配的内存块数，无论它们大小如何。本函数主要用于跟
     踪和调试内存泄漏。因为解释器有内部缓存，所以不同调用之间结果会变化
     。可能需要调用 *note _clear_type_cache(): 362e. 和 *note
     gc.collect(): 22f. 使结果更容易预测。

     如果当前 Python 构建或实现无法合理地计算此信息，允许 *note
     getallocatedblocks(): 8ea. 返回 0。

     3.4 新版功能.

 -- 函数: sys.getandroidapilevel ()

     返回一个整数，表示 Android 构建时 API 版本。

     *note 可用性: 136f.：Android。

     3.7 新版功能.

 -- 函数: sys.getcheckinterval ()

     Return the interpreter’s "check interval"; see *note
     setcheckinterval(): 3638.

     3.2 版后已移除: Use *note getswitchinterval(): 3639. instead.

 -- 函数: sys.getdefaultencoding ()

     返回当前 Unicode 实现所使用的默认字符串编码名称。

 -- 函数: sys.getdlopenflags ()

     返回当前 ‘dlopen()’ 调用所使用的标志位的值。标志值对应的符号名称可
     以在 *note os: c5. 模块中找到（形如 ‘RTLD_xxx’ 的常量，如 *note
     os.RTLD_LAZY: a67. ）。

     *note 可用性: 136f.: Unix。

 -- 函数: sys.getfilesystemencoding ()

     返回编码名称，该编码用于在 Unicode 文件名和 bytes 文件名之间转换。
     为获得最佳兼容性，任何时候都应使用 str 表示文件名，尽管用字节来表示
     文件名也是支持的。函数如果需要接受或返回文件名，它应支持 str 或
     bytes，并在内部将其转换为系统首选的表示形式。

     该编码始终是 ASCII 兼容的。

     应使用 *note os.fsencode(): 4f7. 和 *note os.fsdecode(): 4f6. 来保
     证所采用的编码和错误模式都是正确的。

        * 在UTF-8模式下，任何平台上的编码均为 ‘utf-8’ 。

        * 在macOS上，编码为 ‘'utf-8'’。

        * 在Unix上，编码是语言环境编码。

        * 在Windows上取决于用户配置，编码可能是 ‘'utf-8'’ 或 ‘'mbcs'’。

        * 在Android上，编码为 ‘'utf-8'’。

        * 在VxWorks上，编码为 ‘'utf-8'’。

     在 3.2 版更改: *note getfilesystemencoding(): 4fe. 的结果将不再有可
     能是 ‘None’。

     在 3.6 版更改: Windows 不再保证会返回 ‘'mbcs'’。详情请参阅 PEP
     529(3) 和 *note _enablelegacywindowsfsencoding(): 500.。

     在 3.7 版更改: 在UTF-8模式下返回 ’utf-8’ 。

 -- 函数: sys.getfilesystemencodeerrors ()

     返回错误回调函数的名称，该错误回调函数将在 Unicode 文件名和 bytes 文
     件名转换时生效。编码的名称是由 *note getfilesystemencoding(): 4fe.
     返回的。

     应使用 *note os.fsencode(): 4f7. 和 *note os.fsdecode(): 4f6. 来保
     证所采用的编码和错误模式都是正确的。

     3.6 新版功能.

 -- 函数: sys.getrefcount (object)

     返回 `object' 的引用计数。返回的计数通常比预期的多一，因为它包括了
     作为 *note getrefcount(): 363b. 参数的这一次（临时）引用。

 -- 函数: sys.getrecursionlimit ()

     返回当前的递归限制值，即 Python 解释器堆栈的最大深度。此限制可防止
     无限递归导致的 C 堆栈溢出和 Python 崩溃。该值可以通过 *note
     setrecursionlimit(): e83. 设置。

 -- 函数: sys.getsizeof (object[, default])

     返回对象的大小（以字节为单位）。该对象可以是任何类型。所有内建对象
     返回的结果都是正确的，但对于第三方扩展不一定正确，因为这与具体实现
     有关。

     只计算直接分配给对象的内存消耗，不计算它所引用的对象的内存消耗。

     对象不提供计算大小的方法时，如果有给出 `default' 则返回它，否则抛出
     *note TypeError: 193. 异常。

     如果对象由垃圾回收器管理，则 *note getsizeof(): 35c9. 将调用对象的
     ‘__sizeof__’ 方法，并在上层添加额外的垃圾回收器。

     可以参考 recursive sizeof recipe(4) 中的示例，关于递归调用 *note
     getsizeof(): 35c9. 来得到各个容器及其所有内容物的大小。

 -- 函数: sys.getswitchinterval ()

     返回解释器的“线程切换间隔时间”，请参阅 *note setswitchinterval():
     bf3.。

     3.2 新版功能.

 -- 函数: sys._getframe ([depth])

     返回来自调用栈的一个帧对象。如果传入可选整数 `depth'，则返回从栈顶
     往下相应调用层数的帧对象。如果该数比调用栈更深，则抛出 *note
     ValueError: 1fc.。`depth' 的默认值是 0，返回调用栈顶部的帧。

     引发一个 *note 审计事件: ea1. ‘sys._getframe’，没有附带参数。

     `CPython implementation detail:' 这个函数应该只在内部为了一些特定的
     目的使用。不保证它在所有 Python 实现中都存在。

 -- 函数: sys.getprofile ()

     返回由 *note setprofile(): e45. 设置的性能分析函数

 -- 函数: sys.gettrace ()

     返回由 *note settrace(): e46. 设置的跟踪函数。

     `CPython implementation detail:' *note gettrace(): d50. 函数仅用于
     实现调试器，性能分析器，打包工具等。它的行为是实现平台的一部分，而
     不是语言定义的一部分，因此并非在所有 Python 实现中都可用。

 -- 函数: sys.getwindowsversion ()

     返回一个具名元组，描述当前正在运行的 Windows 版本。元素名称包括
     `major', `minor', `build', `platform', `service_pack',
     `service_pack_minor', `service_pack_major', `suite_mask',
     `product_type' 和 `platform_version'。`service_pack' 包含一个字符串
     ，`platform_version' 包含一个三元组，其他所有值都是整数。元素也可以
     通过名称来访问，所以 ‘sys.getwindowsversion()[0]’ 与
     ‘sys.getwindowsversion().major’ 是等效的。为保持与旧版本的兼容性，
     只有前 5 个元素可以用索引检索。

     `platform' 将会是 ‘2 (VER_PLATFORM_WIN32_NT)’。

     `product_type' 可能是以下值之一：

     常数                                        含义
                                                 
     ----------------------------------------------------------------------------------
                                                 
     ‘1 (VER_NT_WORKSTATION)’                    系统是工作站。
                                                 
                                                 
     ‘2 (VER_NT_DOMAIN_CONTROLLER)’              系统是域控制器。
                                                 
                                                 
     ‘3 (VER_NT_SERVER)’                         系统是服务器，但不是域控制器。
                                                 

     本函数包装了 Win32 ‘GetVersionEx()’ 函数，参阅 Microsoft 文档有关
     ‘OSVERSIONINFOEX()’ 的内容可获取这些字段的更多信息。

     `platform_version' 返回当前操作系统的主要版本、次要版本和编译版本号
     ，而不是为该进程所模拟的版本。 它旨在用于日志记录而非特性检测。

          注解: `platform_version' 会从 kernel32.dll 获取版本号，这个版
          本可能与 OS 版本不同。 请使用 *note platform: cf. 模块来获取准
          确的 OS 版本号。

     *note 可用性: 136f.: Windows。

     在 3.2 版更改: 更改为具名元组，添加 `service_pack_minor',
     `service_pack_major', `suite_mask' 和 `product_type'。

     在 3.6 版更改: 添加了 `platform_version'

 -- 函数: sys.get_asyncgen_hooks ()

     返回一个 `asyncgen_hooks' 对象，该对象类似于 *note namedtuple:
     1b7.，形式为 ‘(firstiter, finalizer)’，其中 `firstiter' 和
     `finalizer' 为 ‘None’ 或函数，函数以 *note 异步生成器迭代器: 363d.
     作为参数，并用于在事件循环中干预异步生成器的终结。

     3.6 新版功能: 详情请参阅 PEP 525(5)。

          注解: 本函数已添加至暂定软件包（详情请参阅 PEP 411(6) ）。

 -- 函数: sys.get_coroutine_origin_tracking_depth ()

     获取由 *note set_coroutine_origin_tracking_depth(): 3fb. 设置的协程
     来源的追踪深度。

     3.7 新版功能.

          注解: 本函数已添加至暂定软件包（详情请参阅 PEP 411(7) ）。仅将
          其用于调试目的。

 -- 数据: sys.hash_info

     一个 *note 具名元组: aab.，给出数字类型的哈希的实现参数。关于数字类
     型的哈希的详情请参阅 *note 数字类型的哈希运算: 1637.。

     attribute – 属性          说明
                               
     ---------------------------------------------------------------------------------
                               
     ‘width’                   用于哈希值的位宽度
                               
                               
     ‘modulus’                 用于数字散列方案的素数模数P。
                               
                               
     ‘inf’                     为正无穷大返回的哈希值
                               
                               
     ‘nan’                     为nan返回的哈希值
                               
                               
     ‘imag’                    用于复数虚部的乘数
                               
                               
     ‘algorithm’               字符串、字节和内存视图的哈希算法的名称
                               
                               
     ‘hash_bits’               哈希算法的内部输出大小。
                               
                               
     ‘seed_bits’               散列算法的种子密钥的大小
                               

     3.2 新版功能.

     在 3.4 版更改: 添加了 `algorithm', `hash_bits' 和 `seed_bits'

 -- 数据: sys.hexversion

     编码为单个整数的版本号。该整数会确保每个版本都自增，其中适当包括了
     未发布版本。举例来说，要测试 Python 解释器的版本不低于 1.5.2，请使
     用:

          if sys.hexversion >= 0x010502F0:
              # use some advanced feature
              ...
          else:
              # use an alternative implementation or warn the user
              ...

     之所以称它为 ‘hexversion’，是因为只有将它传入内置函数 *note hex():
     c6e. 后，其结果才看起来有意义。也可以使用 *note 具名元组: aab.
     *note sys.version_info: b22.，它对相同信息有着更人性化的编码。

     关于 ‘hexversion’ 的更多信息可以在 *note API 和 ABI 版本管理: 363f.
     中找到。

 -- 数据: sys.implementation

     一个对象，该对象包含当前运行的 Python 解释器的实现信息。所有 Python
     实现中都必须存在下列属性。

     `name' 是当前实现的标识符，如 ‘'cpython'’。实际的字符串由 Python 实
     现定义，但保证是小写字母。

     `version' 是一个具名元组，格式与 *note sys.version_info: b22. 相同
     。它表示 Python `实现' 的版本。 另一个（由 ‘sys.version_info’ 表示
     ）是当前解释器遵循的相应 Python `语言' 的版本，两者具有不同的含义。
     例如，对于 PyPy 1.8，‘sys.implementation.version’ 可能是
     ‘sys.version_info(1, 8, 0, 'final', 0)’，而 ‘sys.version_info’ 则是
     ‘sys.version_info(2, 7, 2, 'final', 0)’。对于 CPython 而言两个值是
     相同的，因为它是参考实现。

     `hexversion' 是十六进制的实现版本，类似于 *note sys.hexversion:
     363e.。

     `cache_tag' 是导入机制使用的标记，用于已缓存模块的文件名。按照惯例
     ，它将由实现的名称和版本组成，如 ‘'cpython-33'’。但如果合适，Python
     实现可以使用其他值。如果 ‘cache_tag’ 被置为 ‘None’，表示模块缓存已
     禁用。

     *note sys.implementation: 9b2. 可能包含相应 Python 实现的其他属性。
     这些非标准属性必须以下划线开头，此处不详细阐述。无论其内容如何，
     *note sys.implementation: 9b2. 在解释器运行期间或不同实现版本之间都
     不会更改。（但是不同 Python 语言版本间可能会不同。）详情请参阅 PEP
     421(8)。

     3.3 新版功能.

          注解: 新的必要属性的添加必须经过常规的 PEP 过程。详情请参阅
          PEP 421(9)。

 -- 数据: sys.int_info

     一个 *note 具名元组: aab.，包含 Python 内部整数表示形式的信息。这些
     属性是只读的。

     属性                          说明
                                   
     ---------------------------------------------------------------------------------
                                   
     ‘bits_per_digit’              每个数字占有的位数。Python 内部将整数存储在基底
                                   ‘2**int_info.bits_per_digit’
                                   
                                   
     ‘sizeof_digit’                用于表示数字的C类型的字节大小
                                   

     3.1 新版功能.

 -- 数据: sys.__interactivehook__

     当本属性存在，则以 *note 交互模式: 8eb. 启动解释器时，将自动（不带
     参数地）调用本属性的值。该过程是在读取 *note PYTHONSTARTUP: 8ed. 文
     件之后完成的，所以可以在该文件中设置这一钩子。*note site: ec. 模块
     *note 设置了这一属性: 8ee.。

     引发一个 *note 审计事件: ea1. ‘cpython.run_interactivehook’，附带参
     数 ‘hook’。

     3.4 新版功能.

 -- 函数: sys.intern (string)

     将 `string' 插入 "interned" （驻留）字符串表，返回被插入的字符串 –
     它是 `string' 本身或副本。驻留字符串对提高字典查找的性能很有用 – 如
     果字典中的键已驻留，且所查找的键也已驻留，则键（取散列后）的比较可
     以用指针代替字符串来比较。通常，Python 程序使用到的名称会被自动驻留
     ，且用于保存模块、类或实例属性的字典的键也已驻留。

     驻留字符串不是永久存在的，对 *note intern(): c76. 返回值的引用必须
     保留下来，才能发挥驻留字符串的优势。

 -- 函数: sys.is_finalizing ()

     如果 Python 解释器 *note 正在关闭: 76c.，则返回 *note True: 4a1.，
     否则返回 *note False: 390.。

     3.5 新版功能.

 -- 数据: sys.last_type
 -- 数据: sys.last_value
 -- 数据: sys.last_traceback

     这三个变量并非总是有定义，仅当有异常未处理，且解释器打印了错误消息
     和堆栈回溯时，才会给它们赋值。它们的预期用途，是允许交互中的用户导
     入调试器模块，进行事后调试，而不必重新运行导致错误的命令。（通常使
     用 ‘import pdb; pdb.pm()’ 进入事后调试器，详情请参阅 *note pdb: ca.
     模块。）

     这些变量的含义与上述 *note exc_info(): c67. 返回值的含义相同。

 -- 数据: sys.maxsize

     一个整数，表示 ‘Py_ssize_t’ 类型的变量可以取到的最大值。在 32 位平
     台上通常为 ‘2**31 - 1’，在 64 位平台上通常为 ‘2**63 - 1’。

 -- 数据: sys.maxunicode

     一个整数，表示最大的 Unicode 码点值，如 ‘1114111’ （十六进制为
     ‘0x10FFFF’ ）。

     在 3.3 版更改: 在 PEP 393(10) 之前，‘sys.maxunicode’ 曾是 ‘0xFFFF’
     或 ‘0x10FFFF’，具体取决于配置选项，该选项指定将 Unicode 字符存储为
     UCS-2 还是 UCS-4。

 -- 数据: sys.meta_path

     一个由 *note 元路径查找器: 9b9. 对象组成的列表，当查找需要导入的模
     块时，会调用这些对象的 *note find_spec(): 46b. 方法，观察这些对象是
     否能找到所需模块。调用 *note find_spec(): 46b. 方法最少需要传入待导
     入模块的绝对名称。如果待导入模块包含在一个包中，则父包的 *note
     __path__: 129f. 属性将作为第二个参数被传入。该方法返回 *note
     模块规格: 3641.，找不到模块则返回 ‘None’。

     参见
     ....

     *note importlib.abc.MetaPathFinder: 9bb.

          抽象基类，定义了 *note meta_path: 5ef. 内的查找器对象的接口。

     *note importlib.machinery.ModuleSpec: 14d6.

          *note find_spec(): 46b. 返回的实例所对应的具体类。

     在 3.4 版更改: 在 Python 3.4 中通过 PEP 451(11) 引入了 *note
     模块规格: 3641.。早期版本的 Python 会寻找一个称为 *note
     find_module(): 46a. 的方法。如果某个 *note meta_path: 5ef. 条目没有
     *note find_spec(): 46b. 方法，就会回退去调用前一种方法。

 -- 数据: sys.modules

     一个字典，将模块名称映射到已加载的模块。可以操作该字典来强制重新加
     载模块，或是实现其他技巧。但是，替换的字典不一定会按预期工作，并且
     从字典中删除必要的项目可能会导致 Python 崩溃。

 -- 数据: sys.path

     一个由字符串组成的列表，用于指定模块的搜索路径。初始化自环境变量
     *note PYTHONPATH: 95b.，再加上一条与安装有关的默认路径。

     程序启动时将初始化该列表，列表的第一项 ‘path[0]’ 目录含有调用
     Python 解释器的脚本。如果脚本目录不可用（比如以交互方式调用了解释器
     ，或脚本是从标准输入中读取的），则 ‘path[0]’ 为空字符串，这将导致
     Python 优先搜索当前目录中的模块。注意，脚本目录将插入在 *note
     PYTHONPATH: 95b. 的条目*之前*。

     程序可以随意修改本列表用于自己的目的。只能向 *note sys.path: 490. 中
     添加 string 和 bytes 类型，其他数据类型将在导入期间被忽略。

     参见
     ....

     *note site: ec. 模块，该模块描述了如何使用 .pth 文件来扩展 *note
     sys.path: 490.。

 -- 数据: sys.path_hooks

     一个由可调用对象组成的列表，这些对象接受一个路径作为参数，并尝试为
     该路径创建一个 *note 查找器: 14ca.。如果成功创建查找器，则可调用对
     象将返回它，否则将引发 *note ImportError: 33d. 异常。

     本特性最早在 PEP 302(12) 中被提及。

 -- 数据: sys.path_importer_cache

     一个字典，作为 *note 查找器: 14ca. 对象的缓存。key 是传入 *note
     sys.path_hooks: 964. 的路径，value 是相应已找到的查找器。如果路径是
     有效的文件系统路径，但在 *note sys.path_hooks: 964. 中未找到查找器
     ，则存入 ‘None’。

     本特性最早在 PEP 302(13) 中被提及。

     在 3.3 版更改: 未找到查找器时，改为存储 ‘None’，而不是 *note
     imp.NullImporter: 9c3.。

 -- 数据: sys.platform

     本字符串是一个平台标识符，举例而言，该标识符可用于将特定平台的组件
     追加到 *note sys.path: 490. 中。

     对于 Unix 系统（除 Linux 和 AIX 外），该字符串是 `Python 构建时的'
     ‘uname -s’ 返回的小写操作系统名称，并附加了 ‘uname -r’ 返回的系统版
     本的第一部分，如 ‘'sunos5'’ 或 ‘'freebsd8'’。除非需要检测特定版本的
     系统，否则建议使用以下习惯用法:

          if sys.platform.startswith('freebsd'):
              # FreeBSD-specific code here...
          elif sys.platform.startswith('linux'):
              # Linux-specific code here...
          elif sys.platform.startswith('aix'):
              # AIX-specific code here...

     对于其他系统，值是：

     系统                 ‘平台’ 值
                          
     -----------------------------------------------------
                          
     AIX                  ‘'aix'’
                          
                          
     Linux                ‘'linux'’
                          
                          
     Windows              ‘'win32'’
                          
                          
     Windows/Cygwin       ‘'cygwin'’
                          
                          
     macOS                ‘'darwin'’
                          

     在 3.3 版更改: 在 Linux 上，*note sys.platform: 2b2. 将不再包含副版
     本号。它将总是 ‘'linux'’ 而不是 ‘'linux2'’ 或 ‘'linux3'’。由于旧版
     本的 Python 会包含该版本号，因此推荐总是使用上述 ‘startswith’ 习惯
     用法。

     在 3.8 版更改: 在 AIX 上，*note sys.platform: 2b2. 将不再包含副版本
     号。它将总是 ‘'aix'’ 而不是 ‘'aix5'’ 或 ‘'aix7'’。由于旧版本的
     Python 会包含该版本号，因此推荐总是使用上述 ‘startswith’ 习惯用法。

     参见
     ....

     *note os.name: 1eef. 更加简略。*note os.uname(): a65. 提供系统的版
     本信息。

     *note platform: cf. 模块对系统的标识有更详细的检查。

 -- 数据: sys.prefix

     一个字符串，给出特定域的目录前缀，该目录中安装了与平台不相关的
     Python 文件，默认为 ‘'/usr/local'’。该目录前缀可以在构建时使用
     ‘configure’ 脚本的 ‘--prefix’ 参数进行设置。Python 库模块的的主要集
     合安装在目录 ‘`prefix'/lib/python`X.Y'’ ，而与平台无关的头文件 (除
     了 ‘pyconfig.h’) 保存在 ‘`prefix'/include/python`X.Y'’, 其中 `X.Y'
     是 Python 的版本号, 例如 ‘3.2’.

          注解: 如果在一个 *note 虚拟环境: 3602. 中，那么该值将在
          ‘site.py’ 中被修改，指向虚拟环境。Python 安装位置仍然可以用
          *note base_prefix: 304e. 来获取。

 -- 数据: sys.ps1
 -- 数据: sys.ps2

     字符串，指定解释器的首要和次要提示符。仅当解释器处于交互模式时，它
     们才有定义。这种情况下，它们的初值为 ‘'>>> '’ 和 ‘'... '’。如果赋给
     其中某个变量的是非字符串对象，则每次解释器准备读取新的交互式命令时
     ，都会重新运行该对象的 *note str(): 339.，这可以用来实现动态的提示
     符。

 -- 函数: sys.setcheckinterval (interval)

     Set the interpreter’s "check interval".  This integer value
     determines how often the interpreter checks for periodic things
     such as thread switches and signal handlers.  The default is ‘100’,
     meaning the check is performed every 100 Python virtual
     instructions.  Setting it to a larger value may increase
     performance for programs using threads.  Setting it to a value ‘<=’
     0 checks every virtual instruction, maximizing responsiveness as
     well as overhead.

     3.2 版后已移除: This function doesn’t have an effect anymore, as
     the internal logic for thread switching and asynchronous tasks has
     been rewritten.  Use *note setswitchinterval(): bf3. instead.

 -- 函数: sys.setdlopenflags (n)

     设置解释器在调用 ‘dlopen()’ 时用到的标志，例如解释器在加载扩展模块
     时。首先，调用 ‘sys.setdlopenflags(0)’ 将在导入模块时对符号启用惰性
     解析。要在扩展模块之间共享符号，请调用
     ‘sys.setdlopenflags(os.RTLD_GLOBAL)’。标志值的符号名称可以在 *note
     os: c5. 模块中找到（即 ‘RTLD_xxx’ 常数，如 *note os.RTLD_LAZY: a67.
     ）。

     *note 可用性: 136f.: Unix。

 -- 函数: sys.setprofile (profilefunc)

     设置系统的性能分析函数，该函数使得在 Py​​thon 中能够实现一个 Python 源
     代码性能分析器。关于 Python Profiler 的更多信息请参阅 *note Python
     Profilers 分析器: 3564. 章节。性能分析函数的调用方式类似于系统的跟
     踪函数（参阅 *note settrace(): e46. ），但它是通过不同的事件调用的
     ，例如，不是每执行一行代码就调用它一次（仅在调用某函数和从某函数返
     回时才会调用性能分析函数，但即使某函数发生异常也会算作返回事件）。
     该函数是特定于线程的，但是性能分析器无法得知线程之间的上下文切换，
     因此在存在多个线程的情况下使用它是没有意义的。另外，因为它的返回值
     不会被用到，所以可以简单地返回 ‘None’。性能分析函数中的错误将导致其
     自身被解除设置。

     性能分析函数应接收三个参数：`frame'、`event' 和 `arg'。`frame' 是当
     前的堆栈帧。`event' 是一个字符串：‘'call'’、‘'return'’、
     ‘'c_call'’、‘'c_return'’ 或 ‘'c_exception'’。`arg' 取决于事件类型。

     引发一个 *note 审计事件: ea1. ‘sys.setprofile’，不附带任何参数。

     这些事件具有以下含义：

     ‘'call'’

          表示调用了某个函数（或进入了其他的代码块）。性能分析函数将被调
          用，`arg' 为 ‘None’。

     ‘'return'’

          表示某个函数（或别的代码块）即将返回。性能分析函数将被调用，
          `arg' 是即将返回的值，如果此次事件是由抛出的异常引起的，`arg'
          为 ‘None’。

     ‘'c_call'’

          表示即将调用某个 C 函数。它可能是扩展函数或是内建函数。`arg' 是
          C 函数对象。

     ‘'c_return'’

          表示返回了某个 C 函数。`arg' 是 C 函数对象。

     ‘'c_exception'’

          表示某个 C 函数抛出了异常。`arg' 是 C 函数对象。

 -- 函数: sys.setrecursionlimit (limit)

     将 Python 解释器堆栈的最大深度设置为 `limit'。此限制可防止无限递归
     导致的 C 堆栈溢出和 Python 崩溃。

     不同平台所允许的最高限值不同。当用户有需要深度递归的程序且平台支持
     更高的限值，可能就需要调高限值。进行该操作需要谨慎，因为过高的限值
     可能会导致崩溃。

     如果新的限值低于当前的递归深度，将抛出 *note RecursionError: 63d. 异
     常。

     在 3.5.1 版更改: 如果新的限值低于当前的递归深度，现在将抛出 *note
     RecursionError: 63d. 异常。

 -- 函数: sys.setswitchinterval (interval)

     设置解释器的线程切换间隔时间（单位为秒）。该浮点数决定了“时间片”的
     理想持续时间，时间片将分配给同时运行的 Python 线程。请注意，实际值
     可能更高，尤其是使用了运行时间长的内部函数或方法时。同时，在时间间
     隔末尾调度哪个线程是操作系统的决定。解释器没有自己的调度程序。

     3.2 新版功能.

 -- 函数: sys.settrace (tracefunc)

     设置系统的跟踪函数，使得用户在 Python 中就可以实现 Python 源代码调
     试器。该函数是特定于单个线程的，所以要让调试器支持多线程，必须为正
     在调试的每个线程都用 *note settrace(): e46. 注册一个跟踪函数，或使
     用 *note threading.settrace(): 2361.。

     跟踪函数应接收三个参数：`frame'、`event' 和 `arg'。`frame' 是当前的
     堆栈帧。`event' 是一个字符串：‘'call'’、‘'line'’、‘'return'’、
     ‘'exception'’ 或 ‘'opcode'’。`arg' 取决于事件类型。

     每次进入 trace 函数的新本地作用域，都会调用 trace 函数（ `event' 会
     被设置为 ‘'call'’ ），它应该返回一个引用，指向即将用在新作用域上的
     本地跟踪函数；如果不需要跟踪当前的作用域，则返回 ‘None’。

     本地跟踪函数应返回对自身的引用（或对另一个函数的引用，用来在其作用
     范围内进行进一步的跟踪），或者返回 ‘None’ 来停止跟踪其作用范围。

     如果跟踪函数出错，则该跟踪函数将被取消设置，类似于调用
     ‘settrace(None)’。

     这些事件具有以下含义：

     ‘'call'’

          表示调用了某个函数（或进入了其他的代码块）。全局跟踪函数将被调
          用，`arg' 为 ‘None’。返回值取决于本地跟踪函数。

     ‘'line'’

          表示解释器即将执行新一行代码或重新执行循环条件。局部跟踪函数将
          被调用，`arg' 为 ‘None’，其返回值将指定新的局部跟踪函数。关于
          其工作原理的详细说明，请参见 ‘Objects/lnotab_notes.txt’。要在
          该堆栈帧禁用每行触发事件，可以在堆栈帧上将 ‘f_trace_lines’ 设
          置为 *note False: 390.。

     ‘'return'’

          表示某个函数（或别的代码块）即将返回。局部跟踪函数将被调用，
          `arg' 是即将返回的值，如果此次返回事件是由于抛出异常，`arg' 为
          ‘None’。跟踪函数的返回值将被忽略。

     ‘'exception'’

          表示发生了某个异常。局部跟踪函数将被调用，`arg' 是一个
          ‘(exception, value, traceback)’ 元组，返回值将指定新的局部跟踪
          函数。

     ‘'opcode'’

          表示解释器即将执行一个新的操作码（操作码的详情请参阅 *note
          dis: 38. ）。局部跟踪函数将被调用，`arg' 为 ‘None’，其返回值将
          指定新的局部跟踪函数。每操作码触发事件默认情况下都不发出：必须
          在堆栈帧上将 ‘f_trace_opcodes’ 显式地设置为 *note True: 4a1. 来
          请求这些事件。

     注意，由于异常是在链式调用中传播的，所以每一级都会产生一个
     ‘'exception'’ 事件。

     更细微的用法是，可以显式地通过赋值 ‘frame.f_trace = tracefunc’ 来设
     置跟踪函数，而不是用现有跟踪函数的返回值去间接设置它。当前帧上的跟
     踪函数必须激活，而 *note settrace(): e46. 还没有做这件事。注意，为
     了使上述设置起效，必须使用 *note settrace(): e46. 来安装全局跟踪函
     数才能启用运行时跟踪机制，但是它不必与上述是同一个跟踪函数（它可以
     是一个开销很低的跟踪函数，只返回 ‘None’，即在各个帧上立即将其自身禁
     用）。

     关于代码对象和帧对象的更多信息请参考 *note 标准类型层级结构: 1431.。

     引发一个 *note 审计事件: ea1. ‘sys.settrace’，不附带任何参数。

     `CPython implementation detail:' *note settrace(): e46. 函数仅用于
     实现调试器，性能分析器，打包工具等。它的行为是实现平台的一部分，而
     不是语言定义的一部分，因此并非在所有 Python 实现中都可用。

     在 3.7 版更改: 添加了 ‘'opcode'’ 事件类型；为帧对象添加了
     ‘f_trace_lines’ 和 ‘f_trace_opcodes’ 属性。

 -- 函数: sys.set_asyncgen_hooks (firstiter, finalizer)

     接受两个可选的关键字参数，要求它们是可调用对象，且接受一个 *note
     异步生成器迭代器: 363d. 作为参数。`firstiter' 对象将在异步生成器第
     一次迭代时调用。`finalizer' 将在异步生成器即将被销毁时调用。

     引发一个 *note 审计事件: ea1. ‘sys.set_asyncgen_hooks_firstiter’，
     不附带任何参数。

     引发一个 *note 审计事件: ea1. ‘sys.set_asyncgen_hooks_finalizer’，
     不附带任何参数。

     之所以会引发两个审计事件，是因为底层的 API 由两个调用组成，每个调用
     都须要引发自己的事件。

     3.6 新版功能: 更多详情请参阅 PEP 525(14)，`finalizer' 方法的参考示
     例可参阅 Lib/asyncio/base_events.py(15) 中
     ‘asyncio.Loop.shutdown_asyncgens’ 的实现。

          注解: 本函数已添加至暂定软件包（详情请参阅 PEP 411(16) ）。

 -- 函数: sys.set_coroutine_origin_tracking_depth (depth)

     用于启用或禁用协程溯源。启用后，协程对象上的 ‘cr_origin’ 属性将包含
     一个元组，它由多个（文件名 filename，行号 line number，函数名
     function name）元组组成，整个元组描述出了协程对象创建过程的回溯，元
     组首端是最近一次的调用。禁用后，‘cr_origin’ 将为 None。

     要启用，请向 `depth' 传递一个大于零的值，它指定了有多少帧将被捕获信
     息。要禁用，请将 `depth' 置为零。

     该设置是特定于单个线程的。

     3.7 新版功能.

          注解: 本函数已添加至暂定软件包（详情请参阅 PEP 411(17) ）。仅
          将其用于调试目的。

 -- 函数: sys._enablelegacywindowsfsencoding ()

     将默认文件系统编码和错误处理方案分别更改为 ’mbcs’ 和 ’replace’，这
     是为了与 Python 3.6 前的版本保持一致。

     这等同于在启动 Python 前先定义好 *note
     PYTHONLEGACYWINDOWSFSENCODING: 4ff. 环境变量。

     *note 可用性: 136f.: Windows。

     3.6 新版功能: 有关更多详细信息，请参阅 PEP 529(18)。

 -- 数据: sys.stdin
 -- 数据: sys.stdout
 -- 数据: sys.stderr

     解释器用于标准输入、标准输出和标准错误的 *note 文件对象: b4a.：

        * ‘stdin’ 用于所有交互式输入（包括对 *note input(): c73. 的调用
          ）；

        * ‘stdout’ 用于 *note print(): 88f. 和 *note expression: 3631. 语
          句的输出，以及用于 *note input(): c73. 的提示符；

        * 解释器自身的提示符和它的错误消息都发往 ‘stderr’。

     这些流都是常规 *note 文本文件: 12b5.，与 *note open(): 4f8. 函数返
     回的对象一致。它们的参数选择如下：

        * 字符编码取决于各个平台。在非 Windows 平台上使用的是语言环境
          (locale) 编码（可参阅 *note locale.getpreferredencoding():
          3ad. ）。

          在 Windows 上，控制台设备使用 UTF-8 编码。非字符设备（如磁盘文
          件和管道）使用系统语言环境编码（即 ANSI 代码页）。非控制台字符
          设备（即 ‘isatty()’ 返回的是 ‘True’，如 NUL）在启动时，会把控
          制台输入代码页和输出代码页的值分别用于 stdin 和 stdout/stderr。
          如果进程原本没有附加到控制台，则默认为系统语言环境编码。

          要重写控制台的特殊行为，可以在启动 Python 前设置
          PYTHONLEGACYWINDOWSSTDIO 环境变量。此时，控制台代码页将用于其
          他字符设备。

          在所有平台上，都可以通过在 Python 启动前设置 *note
          PYTHONIOENCODING: 937. 环境变量来重写字符编码，或通过新的
          *note -X: 156. ‘utf8’ 命令行选项和 *note PYTHONUTF8: 31a. 环境
          变量来设置。但是，对 Windows 控制台来说，上述方法仅在设置了
          *note PYTHONLEGACYWINDOWSSTDIO: 502. 后才起效。

        * When interactive, ‘stdout’ and ‘stderr’ streams are
          line-buffered.  Otherwise, they are block-buffered like
          regular text files.  You can override this value with the
          *note -u: 1358. command-line option.

          注解: 要从标准流写入或读取二进制数据，请使用底层二进制 *note
          buffer: c42. 对象。例如，要将字节写入 *note stdout: 317.，请使
          用 ‘sys.stdout.buffer.write(b'abc')’。

          但是，如果你在写一个库（并且不限制执行库代码时的上下文），那么
          请注意，标准流可能会被替换为文件类对象，如 *note io.StringIO:
          836.，它们是不支持 ‘buffer’ 属性的。

 -- 数据: sys.__stdin__
 -- 数据: sys.__stdout__
 -- 数据: sys.__stderr__

     程序开始时，这些对象存有 ‘stdin’、‘stderr’ 和 ‘stdout’ 的初始值。它
     们在程序结束前都可以使用，且在需要向实际的标准流打印内容时很有用，
     无论 ‘sys.std*’ 对象是否已重定向。

     如果实际文件已经被覆盖成一个损坏的对象了，那它也可用于将实际文件还
     原成能正常工作的文件对象。但是，本过程的最佳方法应该是，在原来的流
     被替换之前就显式地保存它，并使用这一保存的对象来还原。

          注解: 某些情况下的 ‘stdin’、‘stdout’ 和 ‘stderr’ 以及初始值
          ‘__stdin__’、‘__stdout__’ 和 ‘__stderr__’ 可以是 ‘None’。通常
          发生在未连接到控制台的 Windows GUI app 中，以及在用 ‘pythonw’
          启动的 Python app 中。

 -- 数据: sys.thread_info

     一个 *note 具名元组: aab.，包含线程实现的信息。

     属性                   说明
                            
     -------------------------------------------------------------------------------------
                            
     ‘name’                 线程实现的名称：
                            
                                    * ‘'nt'’: Windows 线程
                            
                                    * ‘'pthread'’: POSIX 线程
                            
                                    * ‘'solaris'’: Solaris 线程
                            
                            
     ‘lock’                 锁实现的名称：
                            
                                    * ‘'semaphore'’: 锁使用信号量
                            
                                    * ‘'mutex+cond'’: 锁使用互斥和条件变量
                            
                                    * ‘None’ 如果此信息未知
                            
                            
     *note version: 5dc.    线程库的名称和版本。它是一个字符串，如果此信息未知，则为
                            ‘None’ 。
                            

     3.3 新版功能.

 -- 数据: sys.tracebacklimit

     当该变量值设置为整数，在发生未处理的异常时，它将决定打印的回溯信息
     的最大层级数。默认为 ‘1000’。当将其设置为 ‘0’ 或小于 0，将关闭所有
     回溯信息，并且只打印异常类型和异常值。

 -- 函数: sys.unraisablehook (unraisable, /)

     处理一个无法抛出的异常。

     它会在发生了一个异常但 Python 没有办法处理时被调用。例如，当一个析
     构器引发了异常，或在垃圾回收 (*note gc.collect(): 22f.) 期间引发了
     异常。

     `unraisable' 参数具有以下属性:

        * `exc_type': 异常类型

        * `exc_value': 异常值，可以是 ‘None’.

        * `exc_traceback': 异常回溯，可以是 ‘None’.

        * `err_msg': 错误信息，可以是 ‘None’.

        * `object': 导致异常的对象，可以为 ‘None’.

     默认的钩子程序会将 `err_msg' 和 `object' 格式化为： ‘f'{err_msg}:
     {object!r}'’；如果 `err_msg' 为 ‘None’ 则采用 "Exception ignored
     in" 错误信息。

     要改变无法抛出的异常的处理过程，可以重写 *note
     sys.unraisablehook(): 22e.。

     使用定制钩子存放 `exc_value' 可能会创建引用循环。 它应当在不再需要
     异常时被显式地清空以打破引用循环。

     如果一个 `object' 正在被销毁，那么使用自定义的钩子储存该对象可能会
     将其复活。请在自定义钩子生效后避免储存 `object'，以避免对象的复活。

     另请参阅 *note excepthook(): e6b.，它处理未捕获的异常。

     当发生无法处理的异常时，将引发一个审计事件 ‘sys.unraisablehook’，附
     带参数 ‘hook’、‘unraisable’。其中 ‘unraisable’ 对象与传递给钩子的对
     象相同。如果没有设置钩子，那么 ‘hook’ 可能是 ‘None’。

     3.8 新版功能.

 -- 数据: sys.version

     一个包含 Python 解释器版本号加编译版本号以及所用编译器等额外信息的
     字符串。 此字符串会在交互式解释器启动时显示。 请不要从中提取版本信
     息，而应当使用 *note version_info: b22. 以及 *note platform: cf. 模
     块所提供的函数。

 -- 数据: sys.api_version

     这个解释器的 C API 版本。当你在调试 Python及期扩展模板的版本冲突这
     个功能非常有用。

 -- 数据: sys.version_info

     一个包含版本号五部分的元组: `major', `minor', `micro',
     `releaselevel' 和 `serial'。 除 `releaselevel' 外的所有值均为整数；
     发布级别值则为 ‘'alpha'’, ‘'beta'’, ‘'candidate'’ 或 ‘'final'’。 对
     应于 Python 版本 2.0 的 ‘version_info’ 值为 ‘(2, 0, 0, 'final',
     0)’。 这些部分也可按名称访问，因此 ‘sys.version_info[0]’ 就等价于
     ‘sys.version_info.major’，依此类推。

     在 3.1 版更改: 增加了以名称表示的各部分属性。

 -- 数据: sys.warnoptions

     这是警告框架的一个实现细节；请不要修改此值。 有关警告框架的更多信息
     请参阅 *note warnings: 127. 模块。

 -- 数据: sys.winver

     用于在 Windows 平台上组成注册表键的版本号。 这在 Python DLL 中存储
     为 1000 号字符串资源。 其值通常是 *note version: 5dc. 的头三个字符
     。 它在 *note sys: fe. 模块中提供是为了信息展示目的；修改此值不会影
     响 Python 所使用的注册表键。

     *note 可用性: 136f.: Windows。

 -- 数据: sys._xoptions

     由多个具体实现专属的通过 *note -X: 156. 命令行选项传递的旗标构成的
     字典。 选项名称将会映射到显式指定的值或者 *note True: 4a1.。 例如:

          $ ./python -Xa=b -Xc
          Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50)
          [GCC 4.4.3] on linux2
          Type "help", "copyright", "credits" or "license" for more information.
          >>> import sys
          >>> sys._xoptions
          {'a': 'b', 'c': True}

     `CPython implementation detail:' 这是 CPython 专属的访问通过 *note
     -X: 156. 传递的选项的方式。 其他实现可能会通过其他方式导出它们，或
     者完全不导出。

     3.2 新版功能.

引用
....

(C99) ISO/IEC 9899:1999.  "Programming languages – C." 该标准的公开草案
可从 ‘http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf’获得。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3149

   (2) https://www.python.org/dev/peps/pep-0578

   (3) https://www.python.org/dev/peps/pep-0529

   (4) https://code.activestate.com/recipes/577504

   (5) https://www.python.org/dev/peps/pep-0525

   (6) https://www.python.org/dev/peps/pep-0411

   (7) https://www.python.org/dev/peps/pep-0411

   (8) https://www.python.org/dev/peps/pep-0421

   (9) https://www.python.org/dev/peps/pep-0421

   (10) https://www.python.org/dev/peps/pep-0393

   (11) https://www.python.org/dev/peps/pep-0451

   (12) https://www.python.org/dev/peps/pep-0302

   (13) https://www.python.org/dev/peps/pep-0302

   (14) https://www.python.org/dev/peps/pep-0525

   (15) 
https://github.com/python/cpython/tree/3.8/Lib/asyncio/base_events.py

   (16) https://www.python.org/dev/peps/pep-0411

   (17) https://www.python.org/dev/peps/pep-0411

   (18) https://www.python.org/dev/peps/pep-0529


File: python.info,  Node: sysconfig --- Provide access to Python's configuration information,  Next: builtins --- 内建对象,  Prev: sys --- 系统相关的参数和函数,  Up: Python运行时服务

5.29.2 ‘sysconfig’ — Provide access to Python’s configuration information
-------------------------------------------------------------------------

3.2 新版功能.

`源代码：' Lib/sysconfig.py(1)

__________________________________________________________________

The *note sysconfig: ff. module provides access to Python’s
configuration information like the list of installation paths and the
configuration variables relevant for the current platform.

* Menu:

* 配置变量::
* 安装路径::
* 其他功能: 其他功能<3>.
* Using sysconfig as a script::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/sysconfig.py


File: python.info,  Node: 配置变量,  Next: 安装路径,  Up: sysconfig --- Provide access to Python's configuration information

5.29.2.1 配置变量
.................

A Python distribution contains a ‘Makefile’ and a ‘pyconfig.h’ header
file that are necessary to build both the Python binary itself and
third-party C extensions compiled using *note distutils: 39.

*note sysconfig: ff. puts all variables found in these files in a
dictionary that can be accessed using *note get_config_vars(): 96d. or
*note get_config_var(): 96c.

Notice that on Windows, it’s a much smaller set.

 -- 函数: sysconfig.get_config_vars (*args)

     With no arguments, return a dictionary of all configuration
     variables relevant for the current platform.

     With arguments, return a list of values that result from looking up
     each argument in the configuration variable dictionary.

     For each argument, if the value is not found, return ‘None’.

 -- 函数: sysconfig.get_config_var (name)

     Return the value of a single variable `name'.  Equivalent to
     ‘get_config_vars().get(name)’.

     If `name' is not found, return ‘None’.

用法示例:

     >>> import sysconfig
     >>> sysconfig.get_config_var('Py_ENABLE_SHARED')
     0
     >>> sysconfig.get_config_var('LIBDIR')
     '/usr/local/lib'
     >>> sysconfig.get_config_vars('AR', 'CXX')
     ['ar', 'g++']


File: python.info,  Node: 安装路径,  Next: 其他功能<3>,  Prev: 配置变量,  Up: sysconfig --- Provide access to Python's configuration information

5.29.2.2 安装路径
.................

Python uses an installation scheme that differs depending on the
platform and on the installation options.  These schemes are stored in
*note sysconfig: ff. under unique identifiers based on the value
returned by *note os.name: 1eef.

Every new component that is installed using *note distutils: 39. or a
Distutils-based system will follow the same scheme to copy its file in
the right places.

Python currently supports seven schemes:

   - `posix_prefix': scheme for POSIX platforms like Linux or Mac OS X.
     This is the default scheme used when Python or a component is
     installed.

   - `posix_home': scheme for POSIX platforms used when a `home' option
     is used upon installation.  This scheme is used when a component is
     installed through Distutils with a specific home prefix.

   - `posix_user': scheme for POSIX platforms used when a component is
     installed through Distutils and the `user' option is used.  This
     scheme defines paths located under the user home directory.

   - `nt': scheme for NT platforms like Windows.

   - `nt_user': scheme for NT platforms, when the `user' option is used.

Each scheme is itself composed of a series of paths and each path has a
unique identifier.  Python currently uses eight paths:

   - `stdlib': directory containing the standard Python library files
     that are not platform-specific.

   - `platstdlib': directory containing the standard Python library
     files that are platform-specific.

   - `platlib': directory for site-specific, platform-specific files.

   - `purelib': directory for site-specific, non-platform-specific
     files.

   - `include': directory for non-platform-specific header files.

   - `platinclude': directory for platform-specific header files.

   - `scripts': directory for script files.

   - `data': directory for data files.

*note sysconfig: ff. provides some functions to determine these paths.

 -- 函数: sysconfig.get_scheme_names ()

     Return a tuple containing all schemes currently supported in *note
     sysconfig: ff.

 -- 函数: sysconfig.get_path_names ()

     Return a tuple containing all path names currently supported in
     *note sysconfig: ff.

 -- 函数: sysconfig.get_path (name[, scheme[, vars[, expand]]])

     Return an installation path corresponding to the path `name', from
     the install scheme named `scheme'.

     `name' has to be a value from the list returned by *note
     get_path_names(): 364c.

     *note sysconfig: ff. stores installation paths corresponding to
     each path name, for each platform, with variables to be expanded.
     For instance the `stdlib' path for the `nt' scheme is:
     ‘{base}/Lib’.

     *note get_path(): cc6. will use the variables returned by *note
     get_config_vars(): 96d. to expand the path.  All variables have
     default values for each platform so one may call this function and
     get the default value.

     If `scheme' is provided, it must be a value from the list returned
     by *note get_scheme_names(): 364b.  Otherwise, the default scheme
     for the current platform is used.

     If `vars' is provided, it must be a dictionary of variables that
     will update the dictionary return by *note get_config_vars(): 96d.

     If `expand' is set to ‘False’, the path will not be expanded using
     the variables.

     If `name' is not found, return ‘None’.

 -- 函数: sysconfig.get_paths ([scheme[, vars[, expand]]])

     Return a dictionary containing all installation paths corresponding
     to an installation scheme.  See *note get_path(): cc6. for more
     information.

     If `scheme' is not provided, will use the default scheme for the
     current platform.

     If `vars' is provided, it must be a dictionary of variables that
     will update the dictionary used to expand the paths.

     If `expand' is set to false, the paths will not be expanded.

     If `scheme' is not an existing scheme, *note get_paths(): be1. will
     raise a *note KeyError: 2c8.


File: python.info,  Node: 其他功能<3>,  Next: Using sysconfig as a script,  Prev: 安装路径,  Up: sysconfig --- Provide access to Python's configuration information

5.29.2.3 其他功能
.................

 -- 函数: sysconfig.get_python_version ()

     Return the ‘MAJOR.MINOR’ Python version number as a string.
     Similar to ‘'%d.%d' % sys.version_info[:2]’.

 -- 函数: sysconfig.get_platform ()

     Return a string that identifies the current platform.

     This is used mainly to distinguish platform-specific build
     directories and platform-specific built distributions.  Typically
     includes the OS name and version and the architecture (as supplied
     by ’os.uname()’), although the exact information included depends
     on the OS; e.g., on Linux, the kernel version isn’t particularly
     important.

     返回值的示例：

        - linux-i586

        - linux-alpha (?)

        - solaris-2.6-sun4u

     Windows将返回以下之一：

        - win-amd64 (在 AMD64, aka x86_64, Intel64, 和 EM64T上的64位
          Windows )

        - win32 (all others - specifically, sys.platform is returned)

     Mac OS X 返回：

        - macosx-10.6-ppc

        - macosx-10.4-ppc64

        - macosx-10.3-i386

        - macosx-10.4-fat

     对于其他非-POSIX 平台， 目前只是返回 *note sys.platform: 2b2. 。

 -- 函数: sysconfig.is_python_build ()

     Return ‘True’ if the running Python interpreter was built from
     source and is being run from its built location, and not from a
     location resulting from e.g.  running ‘make install’ or installing
     via a binary installer.

 -- 函数: sysconfig.parse_config_h (fp[, vars])

     Parse a ‘config.h’-style file.

     `fp' is a file-like object pointing to the ‘config.h’-like file.

     A dictionary containing name/value pairs is returned.  If an
     optional dictionary is passed in as the second argument, it is used
     instead of a new dictionary, and updated with the values read in
     the file.

 -- 函数: sysconfig.get_config_h_filename ()

     返回 ‘pyconfig.h’ 的目录

 -- 函数: sysconfig.get_makefile_filename ()

     返回 ‘Makefile’ 的目录


File: python.info,  Node: Using sysconfig as a script,  Prev: 其他功能<3>,  Up: sysconfig --- Provide access to Python's configuration information

5.29.2.4 Using ‘sysconfig’ as a script
......................................

You can use *note sysconfig: ff. as a script with Python’s `-m' option:

     $ python -m sysconfig
     Platform: "macosx-10.4-i386"
     Python version: "3.2"
     Current installation scheme: "posix_prefix"

     Paths:
             data = "/usr/local"
             include = "/Users/tarek/Dev/svn.python.org/py3k/Include"
             platinclude = "."
             platlib = "/usr/local/lib/python3.2/site-packages"
             platstdlib = "/usr/local/lib/python3.2"
             purelib = "/usr/local/lib/python3.2/site-packages"
             scripts = "/usr/local/bin"
             stdlib = "/usr/local/lib/python3.2"

     Variables:
             AC_APPLE_UNIVERSAL_BUILD = "0"
             AIX_GENUINE_CPLUSPLUS = "0"
             AR = "ar"
             ARFLAGS = "rc"
             ...

This call will print in the standard output the information returned by
*note get_platform(): bdf, *note get_python_version(): be0, *note
get_path(): cc6. and *note get_config_vars(): 96d.


File: python.info,  Node: builtins --- 内建对象,  Next: __main__ --- 顶层脚本环境,  Prev: sysconfig --- Provide access to Python's configuration information,  Up: Python运行时服务

5.29.3 ‘builtins’ — 内建对象
----------------------------

__________________________________________________________________

该模块提供对Python的所有“内置”标识符的直接访问；例如，‘builtins.open’ 是
内置函数的全名 *note open(): 4f8. 。请参阅 *note 内置函数: bfb. 和 *note
内置常量: 161b. 的文档。

大多数应用程序通常不会显式访问此模块，但在提供与内置值同名的对象的模块中
可能很有用，但其中还需要内置该名称。例如，在一个想要实现 *note open():
4f8. 函数的模块中，它包装了内置的 *note open(): 4f8. ，这个模块可以直接
使用:

     import builtins

     def open(path):
         f = builtins.open(path, 'r')
         return UpperCaser(f)

     class UpperCaser:
         '''Wrapper around a file that converts output to upper-case.'''

         def __init__(self, f):
             self._f = f

         def read(self, count=-1):
             return self._f.read(count).upper()

         # ...

作为一个实现细节，大多数模块都将名称 ‘__builtins__’ 作为其全局变量的一部
分提供。 ‘__builtins__’ 的值通常是这个模块或者这个模块的值 *note
__dict__: 504. 属性。由于这是一个实现细节，因此 Python 的替代实现可能不
会使用它。


File: python.info,  Node: __main__ --- 顶层脚本环境,  Next: warnings --- Warning control,  Prev: builtins --- 内建对象,  Up: Python运行时服务

5.29.4 ‘__main__’ — 顶层脚本环境
--------------------------------

__________________________________________________________________

‘'__main__'’ 是顶层代码执行的作用域的名称。模块的 __name__ 在通过标准输
入、脚本文件或是交互式命令读入的时候会等于 ‘'__main__'’。

模块可以通过检查自己的 ‘__name__’ 来得知是否运行在 main 作用域中，这使得
模块可以在作为脚本或是通过 ‘python -m’ 运行时条件性地执行一些代码，而在
被 import 时不会执行。

     if __name__ == "__main__":
         # execute only if run as a script
         main()

对软件包来说，通过加入 ‘__main__.py’ 模块可以达到同样的效果，当使用 ‘-m’
运行模块时，其中的代码会被执行。


File: python.info,  Node: warnings --- Warning control,  Next: dataclasses --- 数据类,  Prev: __main__ --- 顶层脚本环境,  Up: Python运行时服务

5.29.5 ‘warnings’ — Warning control
-----------------------------------

`源代码：' Lib/warnings.py(1)

__________________________________________________________________

Warning messages are typically issued in situations where it is useful
to alert the user of some condition in a program, where that condition
(normally) doesn’t warrant raising an exception and terminating the
program.  For example, one might want to issue a warning when a program
uses an obsolete module.

Python programmers issue warnings by calling the *note warn(): e60.
function defined in this module.  (C programmers use *note
PyErr_WarnEx(): db9.; see *note 异常处理: 3658. for details).

Warning messages are normally written to *note sys.stderr: 318, but
their disposition can be changed flexibly, from ignoring all warnings to
turning them into exceptions.  The disposition of warnings can vary
based on the *note warning category: 1729, the text of the warning
message, and the source location where it is issued.  Repetitions of a
particular warning for the same source location are typically
suppressed.

There are two stages in warning control: first, each time a warning is
issued, a determination is made whether a message should be issued or
not; next, if a message is to be issued, it is formatted and printed
using a user-settable hook.

The determination whether to issue a warning message is controlled by
the *note warning filter: 135c, which is a sequence of matching rules
and actions.  Rules can be added to the filter by calling *note
filterwarnings(): e0f. and reset to its default state by calling *note
resetwarnings(): 3659.

The printing of warning messages is done by calling *note showwarning():
365a, which may be overridden; the default implementation of this
function formats the message by calling *note formatwarning(): 1002,
which is also available for use by custom implementations.

参见
....

*note logging.captureWarnings(): 20df. allows you to handle all warnings
with the standard logging infrastructure.

* Menu:

* 警告类别::
* The Warnings Filter::
* 暂时禁止警告::
* 测试警告::
* Updating Code For New Versions of Dependencies::
* Available Functions::
* Available Context Managers::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/warnings.py


File: python.info,  Node: 警告类别,  Next: The Warnings Filter,  Up: warnings --- Warning control

5.29.5.1 警告类别
.................

There are a number of built-in exceptions that represent warning
categories.  This categorization is useful to be able to filter out
groups of warnings.

While these are technically *note built-in exceptions: 1727, they are
documented here, because conceptually they belong to the warnings
mechanism.

User code can define additional warning categories by subclassing one of
the standard warning categories.  A warning category must always be a
subclass of the *note Warning: 172a. class.

The following warnings category classes are currently defined:

Class                                  描述
                                       
-------------------------------------------------------------------------------------------
                                       
*note Warning: 172a.                   This is the base class of all warning category
                                       classes.  It is a subclass of
                                       *note Exception: 1aa.
                                       
                                       
*note UserWarning: 172b.               The default category for *note warn(): e60.
                                       
                                       
*note DeprecationWarning: 279.         Base category for warnings about deprecated
                                       features when those warnings are intended for
                                       other Python developers (ignored by default,
                                       unless triggered by code in ‘__main__’).
                                       
                                       
*note SyntaxWarning: 192.              Base category for warnings about dubious
                                       syntactic features.
                                       
                                       
*note RuntimeWarning: 2c1.             Base category for warnings about dubious runtime
                                       features.
                                       
                                       
*note FutureWarning: 32e.              Base category for warnings about deprecated
                                       features when those warnings are intended for end
                                       users of applications that are written in Python.
                                       
                                       
*note PendingDeprecationWarning: 27a.  Base category for warnings about features that
                                       will be deprecated in the future (ignored by
                                       default).
                                       
                                       
*note ImportWarning: 5e1.              Base category for warnings triggered during the
                                       process of importing a module (ignored by
                                       default).
                                       
                                       
*note UnicodeWarning: d8f.             Base category for warnings related to Unicode.
                                       
                                       
*note BytesWarning: 4bd.               Base category for warnings related to
                                       *note bytes: 33a. and *note bytearray: 33b.
                                       
                                       
*note ResourceWarning: 4d8.            Base category for warnings related to resource
                                       usage.
                                       

在 3.7 版更改: Previously *note DeprecationWarning: 279. and *note
FutureWarning: 32e. were distinguished based on whether a feature was
being removed entirely or changing its behaviour.  They are now
distinguished based on their intended audience and the way they’re
handled by the default warnings filters.


File: python.info,  Node: The Warnings Filter,  Next: 暂时禁止警告,  Prev: 警告类别,  Up: warnings --- Warning control

5.29.5.2 The Warnings Filter
............................

The warnings filter controls whether warnings are ignored, displayed, or
turned into errors (raising an exception).

Conceptually, the warnings filter maintains an ordered list of filter
specifications; any specific warning is matched against each filter
specification in the list in turn until a match is found; the filter
determines the disposition of the match.  Each entry is a tuple of the
form (`action', `message', `category', `module', `lineno'), where:

   * `action' is one of the following strings:

     值                  处置
                         
     -----------------------------------------------------------------------
                         
     ‘"default"’         为发出警告的每个位置（模块+行号）打印第一个匹配
                         警告
                         
                         
     ‘"error"’           将匹配警告转换为异常
                         
                         
     ‘"ignore"’          从不打印匹配的警告
                         
                         
     ‘"always"’          总是打印匹配的警告
                         
                         
     ‘"module"’          为发出警告的每个模块打印第一次匹配警告（无论行号
                         如何）
                         
                         
     ‘"once"’            无论位置如何，仅打印第一次出现的匹配警告
                         

   * `message' is a string containing a regular expression that the
     start of the warning message must match.  The expression is
     compiled to always be case-insensitive.

   * `category' is a class (a subclass of *note Warning: 172a.) of which
     the warning category must be a subclass in order to match.

   * `module' is a string containing a regular expression that the
     module name must match.  The expression is compiled to be
     case-sensitive.

   * `lineno' is an integer that the line number where the warning
     occurred must match, or ‘0’ to match all line numbers.

Since the *note Warning: 172a. class is derived from the built-in *note
Exception: 1aa. class, to turn a warning into an error we simply raise
‘category(message)’.

If a warning is reported and doesn’t match any registered filter then
the "default" action is applied (hence its name).

* Menu:

* Describing Warning Filters::
* 默认警告过滤器::
* Overriding the default filter::


File: python.info,  Node: Describing Warning Filters,  Next: 默认警告过滤器,  Up: The Warnings Filter

5.29.5.3 Describing Warning Filters
...................................

The warnings filter is initialized by *note -W: 41f. options passed to
the Python interpreter command line and the *note PYTHONWARNINGS: 420.
environment variable.  The interpreter saves the arguments for all
supplied entries without interpretation in *note sys.warnoptions: 41e.;
the *note warnings: 127. module parses these when it is first imported
(invalid options are ignored, after printing a message to *note
sys.stderr: 318.).

Individual warnings filters are specified as a sequence of fields
separated by colons:

     action:message:category:module:line

The meaning of each of these fields is as described in *note The
Warnings Filter: 135c.  When listing multiple filters on a single line
(as for *note PYTHONWARNINGS: 420.), the individual filters are
separated by commas and the filters listed later take precedence over
those listed before them (as they’re applied left-to-right, and the most
recently applied filters take precedence over earlier ones).

Commonly used warning filters apply to either all warnings, warnings in
a particular category, or warnings raised by particular modules or
packages.  Some examples:

     default                      # Show all warnings (even those ignored by default)
     ignore                       # Ignore all warnings
     error                        # Convert all warnings to errors
     error::ResourceWarning       # Treat ResourceWarning messages as errors
     default::DeprecationWarning  # Show DeprecationWarning messages
     ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
     error:::mymodule[.*]         # Convert warnings to errors in "mymodule"
                                  # and any subpackages of "mymodule"


File: python.info,  Node: 默认警告过滤器,  Next: Overriding the default filter,  Prev: Describing Warning Filters,  Up: The Warnings Filter

5.29.5.4 默认警告过滤器
.......................

By default, Python installs several warning filters, which can be
overridden by the *note -W: 41f. command-line option, the *note
PYTHONWARNINGS: 420. environment variable and calls to *note
filterwarnings(): e0f.

In regular release builds, the default warning filter has the following
entries (in order of precedence):

     default::DeprecationWarning:__main__
     ignore::DeprecationWarning
     ignore::PendingDeprecationWarning
     ignore::ImportWarning
     ignore::ResourceWarning

In debug builds, the list of default warning filters is empty.

在 3.2 版更改: *note DeprecationWarning: 279. is now ignored by default
in addition to *note PendingDeprecationWarning: 27a.

在 3.7 版更改: *note DeprecationWarning: 279. is once again shown by
default when triggered directly by code in ‘__main__’.

在 3.7 版更改: *note BytesWarning: 4bd. no longer appears in the default
filter list and is instead configured via *note sys.warnoptions: 41e.
when *note -b: 41d. is specified twice.


File: python.info,  Node: Overriding the default filter,  Prev: 默认警告过滤器,  Up: The Warnings Filter

5.29.5.5 Overriding the default filter
......................................

Developers of applications written in Python may wish to hide `all'
Python level warnings from their users by default, and only display them
when running tests or otherwise working on the application.  The *note
sys.warnoptions: 41e. attribute used to pass filter configurations to
the interpreter can be used as a marker to indicate whether or not
warnings should be disabled:

     import sys

     if not sys.warnoptions:
         import warnings
         warnings.simplefilter("ignore")

Developers of test runners for Python code are advised to instead ensure
that `all' warnings are displayed by default for the code under test,
using code like:

     import sys

     if not sys.warnoptions:
         import os, warnings
         warnings.simplefilter("default") # Change the filter in this process
         os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses

Finally, developers of interactive shells that run user code in a
namespace other than ‘__main__’ are advised to ensure that *note
DeprecationWarning: 279. messages are made visible by default, using
code like the following (where ‘user_ns’ is the module used to execute
code entered interactively):

     import warnings
     warnings.filterwarnings("default", category=DeprecationWarning,
                                        module=user_ns.get("__name__"))


File: python.info,  Node: 暂时禁止警告,  Next: 测试警告,  Prev: The Warnings Filter,  Up: warnings --- Warning control

5.29.5.6 暂时禁止警告
.....................

If you are using code that you know will raise a warning, such as a
deprecated function, but do not want to see the warning (even when
warnings have been explicitly configured via the command line), then it
is possible to suppress the warning using the *note catch_warnings:
3465. context manager:

     import warnings

     def fxn():
         warnings.warn("deprecated", DeprecationWarning)

     with warnings.catch_warnings():
         warnings.simplefilter("ignore")
         fxn()

While within the context manager all warnings will simply be ignored.
This allows you to use known-deprecated code without having to see the
warning while not suppressing the warning for other code that might not
be aware of its use of deprecated code.  Note: this can only be
guaranteed in a single-threaded application.  If two or more threads use
the *note catch_warnings: 3465. context manager at the same time, the
behavior is undefined.


File: python.info,  Node: 测试警告,  Next: Updating Code For New Versions of Dependencies,  Prev: 暂时禁止警告,  Up: warnings --- Warning control

5.29.5.7 测试警告
.................

To test warnings raised by code, use the *note catch_warnings: 3465.
context manager.  With it you can temporarily mutate the warnings filter
to facilitate your testing.  For instance, do the following to capture
all raised warnings to check:

     import warnings

     def fxn():
         warnings.warn("deprecated", DeprecationWarning)

     with warnings.catch_warnings(record=True) as w:
         # Cause all warnings to always be triggered.
         warnings.simplefilter("always")
         # Trigger a warning.
         fxn()
         # Verify some things
         assert len(w) == 1
         assert issubclass(w[-1].category, DeprecationWarning)
         assert "deprecated" in str(w[-1].message)

One can also cause all warnings to be exceptions by using ‘error’
instead of ‘always’.  One thing to be aware of is that if a warning has
already been raised because of a ‘once’/‘default’ rule, then no matter
what filters are set the warning will not be seen again unless the
warnings registry related to the warning has been cleared.

Once the context manager exits, the warnings filter is restored to its
state when the context was entered.  This prevents tests from changing
the warnings filter in unexpected ways between tests and leading to
indeterminate test results.  The *note showwarning(): 365a. function in
the module is also restored to its original value.  Note: this can only
be guaranteed in a single-threaded application.  If two or more threads
use the *note catch_warnings: 3465. context manager at the same time,
the behavior is undefined.

When testing multiple operations that raise the same kind of warning, it
is important to test them in a manner that confirms each operation is
raising a new warning (e.g.  set warnings to be raised as exceptions and
check the operations raise exceptions, check that the length of the
warning list continues to increase after each operation, or else delete
the previous entries from the warnings list before each new operation).


File: python.info,  Node: Updating Code For New Versions of Dependencies,  Next: Available Functions,  Prev: 测试警告,  Up: warnings --- Warning control

5.29.5.8 Updating Code For New Versions of Dependencies
.......................................................

Warning categories that are primarily of interest to Python developers
(rather than end users of applications written in Python) are ignored by
default.

Notably, this "ignored by default" list includes *note
DeprecationWarning: 279. (for every module except ‘__main__’), which
means developers should make sure to test their code with typically
ignored warnings made visible in order to receive timely notifications
of future breaking API changes (whether in the standard library or third
party packages).

In the ideal case, the code will have a suitable test suite, and the
test runner will take care of implicitly enabling all warnings when
running tests (the test runner provided by the *note unittest: 11c.
module does this).

In less ideal cases, applications can be checked for use of deprecated
interfaces by passing *note -Wd: 41f. to the Python interpreter (this is
shorthand for ‘-W default’) or setting ‘PYTHONWARNINGS=default’ in the
environment.  This enables default handling for all warnings, including
those that are ignored by default.  To change what action is taken for
encountered warnings you can change what argument is passed to *note -W:
41f. (e.g.  ‘-W error’).  See the *note -W: 41f. flag for more details
on what is possible.


File: python.info,  Node: Available Functions,  Next: Available Context Managers,  Prev: Updating Code For New Versions of Dependencies,  Up: warnings --- Warning control

5.29.5.9 Available Functions
............................

 -- 函数: warnings.warn (message, category=None, stacklevel=1,
          source=None)

     Issue a warning, or maybe ignore it or raise an exception.  The
     `category' argument, if given, must be a *note warning category
     class: 1729.; it defaults to *note UserWarning: 172b.
     Alternatively, `message' can be a *note Warning: 172a. instance, in
     which case `category' will be ignored and ‘message.__class__’ will
     be used.  In this case, the message text will be ‘str(message)’.
     This function raises an exception if the particular warning issued
     is changed into an error by the *note warnings filter: 135c.  The
     `stacklevel' argument can be used by wrapper functions written in
     Python, like this:

          def deprecation(message):
              warnings.warn(message, DeprecationWarning, stacklevel=2)

     This makes the warning refer to ‘deprecation()’’s caller, rather
     than to the source of ‘deprecation()’ itself (since the latter
     would defeat the purpose of the warning message).

     `source', if supplied, is the destroyed object which emitted a
     *note ResourceWarning: 4d8.

     在 3.6 版更改: Added `source' parameter.

 -- 函数: warnings.warn_explicit (message, category, filename, lineno,
          module=None, registry=None, module_globals=None, source=None)

     This is a low-level interface to the functionality of *note warn():
     e60, passing in explicitly the message, category, filename and line
     number, and optionally the module name and the registry (which
     should be the ‘__warningregistry__’ dictionary of the module).  The
     module name defaults to the filename with ‘.py’ stripped; if no
     registry is passed, the warning is never suppressed.  `message'
     must be a string and `category' a subclass of *note Warning: 172a.
     or `message' may be a *note Warning: 172a. instance, in which case
     `category' will be ignored.

     `module_globals', if supplied, should be the global namespace in
     use by the code for which the warning is issued.  (This argument is
     used to support displaying source for modules found in zipfiles or
     other non-filesystem import sources).

     `source', if supplied, is the destroyed object which emitted a
     *note ResourceWarning: 4d8.

     在 3.6 版更改: Add the `source' parameter.

 -- 函数: warnings.showwarning (message, category, filename, lineno,
          file=None, line=None)

     Write a warning to a file.  The default implementation calls
     ‘formatwarning(message, category, filename, lineno, line)’ and
     writes the resulting string to `file', which defaults to *note
     sys.stderr: 318.  You may replace this function with any callable
     by assigning to ‘warnings.showwarning’.  `line' is a line of source
     code to be included in the warning message; if `line' is not
     supplied, *note showwarning(): 365a. will try to read the line
     specified by `filename' and `lineno'.

 -- 函数: warnings.formatwarning (message, category, filename, lineno,
          line=None)

     Format a warning the standard way.  This returns a string which may
     contain embedded newlines and ends in a newline.  `line' is a line
     of source code to be included in the warning message; if `line' is
     not supplied, *note formatwarning(): 1002. will try to read the
     line specified by `filename' and `lineno'.

 -- 函数: warnings.filterwarnings (action, message='', category=Warning,
          module='', lineno=0, append=False)

     Insert an entry into the list of *note warnings filter
     specifications: 135c.  The entry is inserted at the front by
     default; if `append' is true, it is inserted at the end.  This
     checks the types of the arguments, compiles the `message' and
     `module' regular expressions, and inserts them as a tuple in the
     list of warnings filters.  Entries closer to the front of the list
     override entries later in the list, if both match a particular
     warning.  Omitted arguments default to a value that matches
     everything.

 -- 函数: warnings.simplefilter (action, category=Warning, lineno=0,
          append=False)

     Insert a simple entry into the list of *note warnings filter
     specifications: 135c.  The meaning of the function parameters is as
     for *note filterwarnings(): e0f, but regular expressions are not
     needed as the filter inserted always matches any message in any
     module as long as the category and line number match.

 -- 函数: warnings.resetwarnings ()

     Reset the warnings filter.  This discards the effect of all
     previous calls to *note filterwarnings(): e0f, including that of
     the *note -W: 41f. command line options and calls to *note
     simplefilter(): 3466.


File: python.info,  Node: Available Context Managers,  Prev: Available Functions,  Up: warnings --- Warning control

5.29.5.10 Available Context Managers
....................................

 -- 类: warnings.catch_warnings (*, record=False, module=None)

     A context manager that copies and, upon exit, restores the warnings
     filter and the *note showwarning(): 365a. function.  If the
     `record' argument is *note False: 390. (the default) the context
     manager returns *note None: 158. on entry.  If `record' is *note
     True: 4a1, a list is returned that is progressively populated with
     objects as seen by a custom *note showwarning(): 365a. function
     (which also suppresses output to ‘sys.stdout’).  Each object in the
     list has attributes with the same names as the arguments to *note
     showwarning(): 365a.

     The `module' argument takes a module that will be used instead of
     the module returned when you import *note warnings: 127. whose
     filter will be protected.  This argument exists primarily for
     testing the *note warnings: 127. module itself.

          注解: The *note catch_warnings: 3465. manager works by
          replacing and then later restoring the module’s *note
          showwarning(): 365a. function and internal list of filter
          specifications.  This means the context manager is modifying
          global state and therefore is not thread-safe.


File: python.info,  Node: dataclasses --- 数据类,  Next: contextlib --- 为 with语句上下文提供的工具,  Prev: warnings --- Warning control,  Up: Python运行时服务

5.29.6 ‘dataclasses’ — 数据类
-----------------------------

`源码：' Lib/dataclasses.py(1)

__________________________________________________________________

这个模块提供了一个装饰器和一些函数，用于自动添加生成的 *note special
method: 366c.，例如 *note __init__(): d66. 和 *note __repr__(): 347. 到
用户定义的类。 它最初描述于 PEP 557(2) 。

在这些生成的方法中使用的成员变量使用 PEP 526(3) 类型注释定义。例如这段代
码:

     from dataclasses import dataclass

     @dataclass
     class InventoryItem:
         """Class for keeping track of an item in inventory."""
         name: str
         unit_price: float
         quantity_on_hand: int = 0

         def total_cost(self) -> float:
             return self.unit_price * self.quantity_on_hand

除其他事情外，将添加 *note __init__(): d66. ，其看起来像:

     def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0):
         self.name = name
         self.unit_price = unit_price
         self.quantity_on_hand = quantity_on_hand

请注意，此方法会自动添加到类中：它不会在上面显示的 ‘InventoryItem’ 定义
中直接指定。

3.7 新版功能.

* Menu:

* 模块级装饰器、类和函数::
* 初始化后处理::
* 类变量::
* 仅初始化变量::
* 冻结的实例::
* 继承: 继承<2>.
* 默认工厂函数::
* 可变的默认值::
* 异常: 异常<17>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/dataclasses.py

   (2) https://www.python.org/dev/peps/pep-0557

   (3) https://www.python.org/dev/peps/pep-0526


File: python.info,  Node: 模块级装饰器、类和函数,  Next: 初始化后处理,  Up: dataclasses --- 数据类

5.29.6.1 模块级装饰器、类和函数
...............................

 -- 函数: @dataclasses.dataclass (*, init=True, repr=True, eq=True,
          order=False, unsafe_hash=False, frozen=False)

     这个函数是 *note decorator: 284. ，用于将生成的 *note special
     method: 366c. 添加到类中，如下所述。

     *note dataclass(): 346. 装饰器检查类以找到 ‘field’。 ‘field’ 被定义
     为具有 *note 类型标注: 628. 的类变量。除了下面描述的两个例外，在
     *note dataclass(): 346. 中没有任何内容检查变量标注中指定的类型。

     所有生成的方法中的字段顺序是它们在类定义中出现的顺序。

     *note dataclass(): 346. 装饰器将向类中添加各种“dunder”方法，如下所
     述。如果类中已存在任何添加的方法，则行为取决于参数，如下所述。装饰
     器返回被调用的同一个类；没有创建新类。

     如果 *note dataclass(): 346. 仅用作没有参数的简单装饰器，它就像它具
     有此签名中记录的默认值一样。也就是说，这三种 *note dataclass():
     346. 用法是等价的:

          @dataclass
          class C:
              ...

          @dataclass()
          class C:
              ...

          @dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
          class C:
             ...

     *note dataclass(): 346. 的参数有：

        - ‘init’: 如果为真值（默认），将生成一个 *note __init__(): d66.
          方法。

          如果类已定义 *note __init__(): d66. ，则忽略此参数。

        - ‘repr’ ：如果为真值（默认），将生成一个 *note __repr__(): 347.
          方法。 生成的 repr 字符串将具有类名以及每个字段的名称和 repr ，
          按照它们在类中定义的顺序。不包括标记为从 repr 中排除的字段。 例
          如：‘InventoryItem(name='widget', unit_price=3.0,
          quantity_on_hand=10)’。

          如果类已定义 *note __repr__(): 347. ，则忽略此参数。

        - ‘eq’ ：如果为true（默认值），将生成 *note __eq__(): 348. 方法
          。此方法将类作为其字段的元组按顺序比较。比较中的两个实例必须是
          相同的类型。

          如果类已定义 *note __eq__(): 348. ，则忽略此参数。

        - ‘order’ ：如果为真值（默认为 ‘False’ ），则 *note __lt__():
          c3c. 、 *note __le__(): ca8. 、 *note __gt__(): ca9. 和 *note
          __ge__(): caa. 方法将生成。 这将类作为其字段的元组按顺序比较。
          比较中的两个实例必须是相同的类型。如果 ‘order’ 为真值并且 ‘eq’
          为假值 ，则引发 *note ValueError: 1fc. 。

          如果类已经定义了 *note __lt__(): c3c. 、 *note __le__(): ca8.
          、 *note __gt__(): ca9. 或者 *note __ge__(): caa. 中的任意一个
          ，将引发 *note TypeError: 193. 。

        - ‘unsafe_hash’ ：如果为 ‘False’ （默认值），则根据 ‘eq’ 和
          ‘frozen’ 的设置方式生成 *note __hash__(): 349. 方法。

          *note __hash__(): 349. 由内置的 *note hash(): 9cc. 使用，当对
          象被添加到散列集合（如字典和集合）时。有一个 *note __hash__():
          349. 意味着类的实例是不可变的。可变性是一个复杂的属性，取决于
          程序员的意图， *note __eq__(): 348. 的存在性和行为，以及 *note
          dataclass(): 346. 装饰器中 ‘eq’ 和 ‘frozen’ 标志的值。

          默认情况下， *note dataclass(): 346. 不会隐式添加 *note
          __hash__(): 349. 方法，除非这样做是安全的。 它也不会添加或更改
          现有的明确定义的 *note __hash__(): 349. 方法。 设置类属性
          ‘__hash__ = None’ 对 Python 具有特定含义，如 *note __hash__():
          349. 文档中所述。

          如果 *note __hash__(): 349. 没有显式定义，或者它被设为 ‘None’，
          则 *note dataclass(): 346. `可能' 会添加一个隐式 *note
          __hash__(): 349. 方法。 虽然并不推荐，但你可以用
          ‘unsafe_hash=True’ 来强制 *note dataclass(): 346. 创建一个
          *note __hash__(): 349. 方法。 如果你的类在逻辑上不可变但却仍然
          可被修改那么可能就是这种情况。 这是一个特殊用例并且应当被仔细
          地考虑。

          以下是隐式创建 *note __hash__(): 349. 方法的规则。请注意，你不
          能在数据类中都使用显式的 *note __hash__(): 349. 方法并设置
          ‘unsafe_hash=True’ ；这将导致 *note TypeError: 193. 。

          如果 ‘eq’ 和 ‘frozen’ 都是 true，默认情况下 *note dataclass():
          346. 将为你生成一个 *note __hash__(): 349. 方法。如果 ‘eq’ 为
          true 且 ‘frozen’ 为 false ，则 *note __hash__(): 349. 将被设置
          为 ‘None’ ，标记它不可用（因为它是可变的）。如果 ‘eq’ 为 false
          ，则 *note __hash__(): 349. 将保持不变，这意味着将使用超类的
          *note __hash__(): 349. 方法（如果超类是 *note object: 2b1. ，
          这意味着它将回到基于id的hash）。

        - ‘frozen’: 如为真值 (默认值为 ‘False’)，则对字段赋值将会产生异
          常。 这模拟了只读的冻结实例。 如果在类中定义了 *note
          __setattr__(): e34. 或 *note __delattr__(): 1440. 则将会引发
          *note TypeError: 193.。 参见下文的讨论。

     ‘field’s 可以选择使用普通的 Python 语法指定默认值:

          @dataclass
          class C:
              a: int       # 'a' has no default value
              b: int = 0   # assign a default value for 'b'

     在这个例子中， ‘a’ 和 ‘b’ 都将包含在添加的 *note __init__(): d66. 方
     法中，它们将被定义为:

          def __init__(self, a: int, b: int = 0):

     如果没有默认值的字段跟在具有默认值的字段后，将引发 *note TypeError:
     193. 。当这发生在单个类中时，或者作为类继承的结果时，都是如此。

 -- 函数: dataclasses.field (*, default=MISSING,
          default_factory=MISSING, repr=True, hash=None, init=True,
          compare=True, metadata=None)

     对于常见和简单的用例，不需要其他功能。但是，有些数据类功能需要额外
     的每字段信息。为了满足这种对附加信息的需求，你可以通过调用提供的
     *note field(): 100e. 函数来替换默认字段值。例如:

          @dataclass
          class C:
              mylist: List[int] = field(default_factory=list)

          c = C()
          c.mylist += [1, 2, 3]

     如上所示， ‘MISSING’ 值是一个 sentinel 对象，用于检测是否提供了
     ‘default’ 和 ‘default_factory’ 参数。 使用此 sentinel 是因为 ‘None’
     是 ‘default’ 的有效值。没有代码应该直接使用 ‘MISSING’ 值。

     *note field(): 100e. 参数有：

        - ‘default’ ：如果提供，这将是该字段的默认值。这是必需的，因为
          *note field(): 100e. 调用本身会替换一般的默认值。

        - ‘default_factory’ ：如果提供，它必须是一个零参数可调用对象，当
          该字段需要一个默认值时，它将被调用。除了其他目的之外，这可以用
          于指定具有可变默认值的字段，如下所述。 同时指定 ‘default’ 和
          ‘default_factory’ 将产生错误。

        - ‘init’ ：如果为true（默认值），则该字段作为参数包含在生成的
          *note __init__(): d66. 方法中。

        - ‘repr’ ：如果为true（默认值），则该字段包含在生成的 *note
          __repr__(): 347. 方法返回的字符串中。

        - ‘compare’ ：如果为true（默认值），则该字段包含在生成的相等性和
          比较方法中（ *note __eq__(): 348. ， *note __gt__(): ca9. 等等
          ）。

        - ‘hash’ ：这可以是布尔值或 ‘None’ 。如果为true，则此字段包含在
          生成的 *note __hash__(): 349. 方法中。如果为 ‘None’ （默认值）
          ，请使用 ‘compare’ 的值，这通常是预期的行为。如果字段用于比较
          ，则应在 hash 中考虑该字段。不鼓励将此值设置为 ‘None’ 以外的任
          何值。

          设置 ‘hash=False’ 但 ‘compare=True’ 的一个可能原因是，如果一个
          计算 hash 的代价很高的字段是检验等价性需要的，但还有其他字段可
          以计算类型的 hash 。 即使从 hash 中排除某个字段，它仍将用于比
          较。

        - ‘metadata’ ：这可以是映射或 None 。 None 被视为一个空的字典。
          这个值包含在 ‘MappingProxyType()’ 中，使其成为只读，并暴露在
          *note Field: 366e. 对象上。数据类根本不使用它，它是作为第三方
          扩展机制提供的。多个第三方可以各自拥有自己的键值，以用作元数据
          中的命名空间。

     如果通过调用 *note field(): 100e. 指定字段的默认值，则该字段的类属
     性将替换为指定的 ‘default’ 值。如果没有提供 ‘default’ ，那么将删除
     类属性。目的是在 *note dataclass(): 346. 装饰器运行之后，类属性将包
     含字段的默认值，就像指定了默认值一样。例如，之后:

          @dataclass
          class C:
              x: int
              y: int = field(repr=False)
              z: int = field(repr=False, default=10)
              t: int = 20

     类属性 ‘C.z’ 将是 ‘10’ ，类属性 ‘C.t’ 将是 ‘20’，类属性 ‘C.x’ 和
     ‘C.y’ 将不设置。

 -- 类: dataclasses.Field

     *note Field: 366e. 对象描述每个定义的字段。这些对象在内部创建，并由
     *note fields(): 366f. 模块级方法返回（见下文）。用户永远不应该直接
     实例化 *note Field: 366e. 对象。 其有文档的属性是：

             - ‘name’ ：字段的名字。

             - ‘type’ ：字段的类型。

             - ‘default’ 、 ‘default_factory’ 、 ‘init’ 、 ‘repr’ 、
               ‘hash’ 、 ‘compare’ 以及 ‘metadata’ 与具有和 *note
               field(): 100e. 声明中相同的意义和值。

     可能存在其他属性，但它们是私有的，不能被审查或依赖。

 -- 函数: dataclasses.fields (class_or_instance)

     返回 *note Field: 366e. 对象的元组，用于定义此数据类的字段。 接受数
     据类或数据类的实例。如果没有传递一个数据类或实例将引发 *note
     TypeError: 193. 。 不返回 ‘ClassVar’ 或 ‘InitVar’ 的伪字段。

 -- 函数: dataclasses.asdict (instance, *, dict_factory=dict)

     将数据类 ‘instance’ 转换为字典（使用工厂函数 ‘dict_factory’ ）。每
     个数据类都转换为其字段的字典，如 ‘name: value’ 对。数据类、字典、列
     表和元组被递归。例如:

          @dataclass
          class Point:
               x: int
               y: int

          @dataclass
          class C:
               mylist: List[Point]

          p = Point(10, 20)
          assert asdict(p) == {'x': 10, 'y': 20}

          c = C([Point(0, 0), Point(10, 4)])
          assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}

     引发 *note TypeError: 193. 如果 ‘instance’ 不是数据类实例。

 -- 函数: dataclasses.astuple (instance, *, tuple_factory=tuple)

     将数据类 ‘instance’ 转换为元组（通过使用工厂函数 ‘tuple_factory’ ）
     。每个数据类都转换为其字段值的元组。数据类、字典、列表和元组被递归
     。

     继续前一个例子:

          assert astuple(p) == (10, 20)
          assert astuple(c) == ([(0, 0), (10, 4)],)

     引发 *note TypeError: 193. 如果 ‘instance’ 不是数据类实例。

 -- 函数: dataclasses.make_dataclass (cls_name, fields, *, bases=(),
          namespace=None, init=True, repr=True, eq=True, order=False,
          unsafe_hash=False, frozen=False)

     创建一个名为 ‘cls_name’ 的新数据类，字段为 ‘fields’ 中定义的字段，
     基类为 ‘bases’ 中给出的基类，并使用 ‘namespace’ 中给出的命名空间进
     行初始化。 ‘fields’ 是一个可迭代的元素，每个元素都是 ‘name’ 、
     ‘(name, type)’ 或 ‘(name, type, Field)’ 。 如果只提供‘‘name‘‘ ，
     ‘type’ 为 ‘typing.Any’ 。 ‘init’ 、 ‘repr’ 、 ‘eq’ 、 ‘order’ 、
     ‘unsafe_hash’ 和 ‘frozen’ 的值与它们在 *note dataclass(): 346. 中的
     含义相同。

     此函数不是严格要求的，因为用于任何创建带有 ‘__annotations__’ 的新类
     的 Python 机制都可以应用 *note dataclass(): 346. 函数将该类转换为数
     据类。提供此功能是为了方便。例如:

          C = make_dataclass('C',
                             [('x', int),
                               'y',
                              ('z', int, field(default=5))],
                             namespace={'add_one': lambda self: self.x + 1})

     等价于

          @dataclass
          class C:
              x: int
              y: 'typing.Any'
              z: int = 5

              def add_one(self):
                  return self.x + 1

 -- 函数: dataclasses.replace (instance, **changes)

     创建一个 ‘instance’ 相同类型的新对象，用 ‘changes’ 中的值替换字段。
     如果 ‘instance’ 不是数据类，则引发 *note TypeError: 193. 。如果
     ‘changes’ 中的值没有指定字段，则引发 *note TypeError: 193. 。

     新返回的对象通过调用数据类的 *note __init__(): d66. 方法创建。这确
     保了如果存在 ‘__post_init__()’ ，其也被调用。

     如果存在没有默认值的仅初始化变量，必须在调用 *note replace(): ea8.
     时指定，以便它们可以传递给 *note __init__(): d66. 和
     ‘__post_init__()’ 。

     ‘changes’ 包含任何定义为 ‘init=False’ 的字段是错误的。在这种情况下
     会引发 *note ValueError: 1fc. 。

     提前提醒 ‘init=False’ 字段在调用 *note replace(): ea8. 时的工作方式
     。如果它们完全被初始化的话，它们不是从源对象复制的，而是在
     ‘__post_init__()’ 中初始化。估计 ‘init=False’ 字段很少能被正确地使
     用。如果使用它们，那么使用备用类构造函数或者可能是处理实例复制的自
     定义 ‘replace()’ （或类似命名的）方法可能是明智的。

 -- 函数: dataclasses.is_dataclass (class_or_instance)

     如果其形参为 dataclass 或其实例则返回 ‘True’，否则返回 ‘False’。

     如果你需要知道一个类是否是一个数据类的实例（而不是一个数据类本身）
     ，那么再添加一个 ‘not isinstance(obj, type)’ 检查:

          def is_dataclass_instance(obj):
              return is_dataclass(obj) and not isinstance(obj, type)


File: python.info,  Node: 初始化后处理,  Next: 类变量,  Prev: 模块级装饰器、类和函数,  Up: dataclasses --- 数据类

5.29.6.2 初始化后处理
.....................

生成的 *note __init__(): d66. 代码将调用一个名为 ‘__post_init__()’ 的方
法，如果在类上已经定义了 ‘__post_init__()’ 。它通常被称为
‘self.__post_init__()’ 。但是，如果定义了任何 ‘InitVar’ 字段，它们也将按
照它们在类中定义的顺序传递给 ‘__post_init__()’ 。 如果没有 *note
__init__(): d66. 方法生成，那么 ‘__post_init__()’ 将不会被自动调用。

在其他用途中，这允许初始化依赖于一个或多个其他字段的字段值。例如:

     @dataclass
     class C:
         a: float
         b: float
         c: float = field(init=False)

         def __post_init__(self):
             self.c = self.a + self.b

有关将参数传递给 ‘__post_init__()’ 的方法，请参阅下面有关仅初始化变量的
段落。另请参阅关于 *note replace(): ea8. 处理 ‘init=False’ 字段的警告。


File: python.info,  Node: 类变量,  Next: 仅初始化变量,  Prev: 初始化后处理,  Up: dataclasses --- 数据类

5.29.6.3 类变量
...............

两个地方 *note dataclass(): 346. 实际检查字段类型的之一是确定字段是否是
如 PEP 526(1) 所定义的类变量。它通过检查字段的类型是否为
‘typing.ClassVar’ 来完成此操作。如果一个字段是一个 ‘ClassVar’ ，它将被排
除在考虑范围之外，并被数据类机制忽略。这样的 ‘ClassVar’ 伪字段不会由模块
级的 *note fields(): 366f. 函数返回。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0526


File: python.info,  Node: 仅初始化变量,  Next: 冻结的实例,  Prev: 类变量,  Up: dataclasses --- 数据类

5.29.6.4 仅初始化变量
.....................

另一个 *note dataclass(): 346. 检查类型注解地方是为了确定一个字段是否是
一个仅初始化变量。它通过查看字段的类型是否为 ‘dataclasses.InitVar’ 类型
来实现。如果一个字段是一个 ‘InitVar’ ，它被认为是一个称为仅初始化字段的
伪字段。因为它不是一个真正的字段，所以它不会被模块级的 *note fields():
366f. 函数返回。仅初始化字段作为参数添加到生成的 *note __init__(): d66.
方法中，并传递给可选的 ‘__post_init__()’ 方法。数据类不会使用它们。

例如，假设一个字段将从数据库初始化，如果在创建类时未提供其值:

     @dataclass
     class C:
         i: int
         j: int = None
         database: InitVar[DatabaseType] = None

         def __post_init__(self, database):
             if self.j is None and database is not None:
                 self.j = database.lookup('j')

     c = C(10, database=my_database)

在这种情况下， *note fields(): 366f. 将返回 ‘i’ 和 ‘j’ 的 *note Field:
366e. 对象，但不包括 ‘database’ 。


File: python.info,  Node: 冻结的实例,  Next: 继承<2>,  Prev: 仅初始化变量,  Up: dataclasses --- 数据类

5.29.6.5 冻结的实例
...................

无法创建真正不可变的 Python 对象。但是，通过将 ‘frozen=True’ 传递给
*note dataclass(): 346. 装饰器，你可以模拟不变性。在这种情况下，数据类将
向类添加 *note __setattr__(): e34. 和 *note __delattr__(): 1440. 方法。
些方法在调用时会引发 *note FrozenInstanceError: 3678. 。

使用 ‘frozen=True’ 时会有很小的性能损失： *note __init__(): d66. 不能使
用简单的赋值来初始化字段，并必须使用 *note object.__setattr__(): e34.。


File: python.info,  Node: 继承<2>,  Next: 默认工厂函数,  Prev: 冻结的实例,  Up: dataclasses --- 数据类

5.29.6.6 继承
.............

当数组由 *note dataclass(): 346. 装饰器创建时，它会查看反向 MRO 中的所有
类的基类（即从 *note object: 2b1. 开始 ），并且对于它找到的每个数据类，
将该基类中的字段添加到字段的有序映射中。添加完所有基类字段后，它会将自己
的字段添加到有序映射中。所有生成的方法都将使用这种组合的，计算的有序字段
映射。由于字段是按插入顺序排列的，因此派生类会重载基类。一个例子:

     @dataclass
     class Base:
         x: Any = 15.0
         y: int = 0

     @dataclass
     class C(Base):
         z: int = 10
         x: int = 15

最后的字段列表依次是 ‘x’ 、 ‘y’ 、 ‘z’ 。 ‘x’ 的最终类型是 ‘int’ ，如类
‘C’ 中所指定的那样。

为 ‘C’ 生成的 *note __init__(): d66. 方法看起来像:

     def __init__(self, x: int = 15, y: int = 0, z: int = 10):


File: python.info,  Node: 默认工厂函数,  Next: 可变的默认值,  Prev: 继承<2>,  Up: dataclasses --- 数据类

5.29.6.7 默认工厂函数
.....................

     如果一个 *note field(): 100e. 指定了一个 ‘default_factory’ ，当需要
     该字段的默认值时，将使用零参数调用它。例如，要创建列表的新实例，请
     使用:

          mylist: list = field(default_factory=list)

     如果一个字段被排除在 *note __init__(): d66. 之外（使用 ‘init=False’
     ）并且字段也指定 ‘default_factory’ ，则默认的工厂函数将始终从生成的
     *note __init__(): d66. 函数调用。发生这种情况是因为没有其他方法可以
     为字段提供初始值。


File: python.info,  Node: 可变的默认值,  Next: 异常<17>,  Prev: 默认工厂函数,  Up: dataclasses --- 数据类

5.29.6.8 可变的默认值
.....................

     Python 在类属性中存储默认成员变量值。思考这个例子，不使用数据类:

          class C:
              x = []
              def add(self, element):
                  self.x.append(element)

          o1 = C()
          o2 = C()
          o1.add(1)
          o2.add(2)
          assert o1.x == [1, 2]
          assert o1.x is o2.x

     请注意，类 ‘C’ 的两个实例共享相同的类变量 ‘x’ ，如预期的那样。

     使用数据类， `如果' 此代码有效:

          @dataclass
          class D:
              x: List = []
              def add(self, element):
                  self.x += element

     它生成的代码类似于:

          class D:
              x = []
              def __init__(self, x=x):
                  self.x = x
              def add(self, element):
                  self.x += element

          assert D().x is D().x

     这与使用类 ‘C’ 的原始示例具有相同的问题。也就是说，在创建类实例时没
     有为 ‘x’ 指定值的类 ‘D’ 的两个实例将共享相同的 ‘x’ 副本。由于数据类
     只使用普通的 Python 类创建，因此它们也会共享此行为。数据类没有通用
     的方法来检测这种情况。相反，如果数据类检测到类型为 ‘list’ 、 ‘dict’
     或 ‘set’ 的默认参数，则会引发 *note TypeError: 193. 。这是一个部分
     解决方案，但它可以防止许多常见错误。

     使用默认工厂函数是一种创建可变类型新实例的方法，并将其作为字段的默
     认值:

          @dataclass
          class D:
              x: list = field(default_factory=list)

          assert D().x is not D().x


File: python.info,  Node: 异常<17>,  Prev: 可变的默认值,  Up: dataclasses --- 数据类

5.29.6.9 异常
.............

 -- 例外: dataclasses.FrozenInstanceError

     在使用 ‘frozen=True’ 定义的数据类上调用隐式定义的 *note
     __setattr__(): e34. 或 *note __delattr__(): 1440. 时引发。 这是
     *note AttributeError: 3a3. 的一个子类。


File: python.info,  Node: contextlib --- 为 with语句上下文提供的工具,  Next: abc --- 抽象基类,  Prev: dataclasses --- 数据类,  Up: Python运行时服务

5.29.7 ‘contextlib’ — 为 ‘with’语句上下文提供的工具
---------------------------------------------------

`源代码' Lib/contextlib.py(1)

__________________________________________________________________

此模块为涉及 *note with: 6f2. 语句的常见任务提供了实用的程序。更多信息请
参见 *note 上下文管理器类型: 1498. 和 *note with 语句上下文管理器:
1496.。

* Menu:

* 工具::
* 例子和配方: 例子和配方<2>.
* Single use, reusable and reentrant context managers: Single use reusable and reentrant context managers.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/contextlib.py


File: python.info,  Node: 工具,  Next: 例子和配方<2>,  Up: contextlib --- 为 with语句上下文提供的工具

5.29.7.1 工具
.............

提供的函数和类：

 -- 类: contextlib.AbstractContextManager

     一个为实现了 *note object.__aenter__(): 14a8. 与 *note
     object.__aexit__(): 14a9. 的类提供的 *note abstract base class:
     b3b.。 为 *note object.__aenter__(): 14a8. 提供的一个默认实现是返回
     ‘self’ 而 *note object.__aexit__(): 14a9. 是一个默认返回 ‘None’ 的
     抽象方法。 参见 *note 异步上下文管理器: 14a6. 的定义。

     3.6 新版功能.

 -- 类: contextlib.AbstractAsyncContextManager

     一个为实现了 *note object.__aenter__(): 14a8. 与 *note
     object.__aexit__(): 14a9. 的类提供的 *note abstract base class:
     b3b.。 为 *note object.__aenter__(): 14a8. 提供的一个默认实现是返回
     ‘self’ 而 *note object.__aexit__(): 14a9. 是一个默认返回 ‘None’ 的
     抽象方法。 参见 *note 异步上下文管理器: 14a6. 的定义。

     3.7 新版功能.

 -- 函数: @contextlib.contextmanager

     这个函数是一个 *note decorator: 284. ，它可以定义一个支持 *note
     with: 6f2. 语句上下文的工厂函数， 而不需要创建一个类或区 *note
     __enter__(): c9d. 与 *note __exit__(): c9e. 方法。

     尽管许多对象原生支持使用 with 语句，但有些需要被管理的资源并不是上
     下文管理器，并且没有实现 ‘close()’ 方法而不能使用
     ‘contextlib.closing’ 。

     下面是一个抽象的示例，展示如何确保正确的资源管理：

          from contextlib import contextmanager

          @contextmanager
          def managed_resource(*args, **kwds):
              # Code to acquire resource, e.g.:
              resource = acquire_resource(*args, **kwds)
              try:
                  yield resource
              finally:
                  # Code to release resource, e.g.:
                  release_resource(resource)

          >>> with managed_resource(timeout=3600) as resource:
          ...     # Resource is released at the end of this block,
          ...     # even if code in the block raises an exception

     被装饰的函数在被调用时，必须返回一个 *note generator:
     9aa.-iterator。这个迭代器必须只 yield 一个值出来，这个值会被用在
     *note with: 6f2. 语句中，绑定到 ‘as’ 后面的变量，如果给定了的话。

     当生成器发生 yield 时，嵌套在 *note with: 6f2. 语句中的语句体会被执
     行。 语句体执行完毕离开之后，该生成器将被恢复执行。 如果在该语句体
     中发生了未处理的异常，则该异常会在生成器发生 yield 时重新被引发。 因
     此，你可以使用 *note try: d7a...*note except: b46...*note finally:
     183. 语句来捕获该异常（如果有的话），或确保进行了一些清理。 如果仅
     出于记录日志或执行某些操作（而非完全抑制异常）的目的捕获了异常，生
     成器必须重新引发该异常。 否则生成器的上下文管理器将向 ‘with’ 语句指
     示该异常已经被处理，程序将立即在 ‘with’ 语句之后恢复并继续执行。

     *note contextmanager(): b86. 使用 *note ContextDecorator: b85. 因此
     它创建的上下文管理器不仅可以用在 *note with: 6f2. 语句中，还可以用
     作一个装饰器。当它用作一个装饰器时，每一次函数调用时都会隐式创建一
     个新的生成器实例（这使得 *note contextmanager(): b86. 创建的上下文
     管理器满足了支持多次调用以用作装饰器的需求，而非“一次性”的上下文管
     理器）。

     在 3.2 版更改: *note ContextDecorator: b85. 的使用。

 -- 函数: @contextlib.asynccontextmanager

     与 *note contextmanager(): b86. 类似，但创建的是一个 *note
     异步上下文管理器: 14a6.。

     这个函数是一个 *note decorator: 284. ，它可以定义一个支持 *note
     async with: 64c. 语句的异步上下文管理器的工厂函数， 而不需要创建一
     个类或区分 *note __aenter__(): 14a8. 与 *note __aexit__(): 14a9. 方
     法。它必须被作用在一个 *note asynchronous generator: 1513. 函数上

     一个简单的示例：

          from contextlib import asynccontextmanager

          @asynccontextmanager
          async def get_connection():
              conn = await acquire_db_connection()
              try:
                  yield conn
              finally:
                  await release_db_connection(conn)

          async def get_all_users():
              async with get_connection() as conn:
                  return conn.query('SELECT ...')

     3.7 新版功能.

 -- 函数: contextlib.closing (thing)

     返回一个在语句块执行完成时关闭 `things' 的上下文管理器。这基本上等
     价于

          from contextlib import contextmanager

          @contextmanager
          def closing(thing):
              try:
                  yield thing
              finally:
                  thing.close()

     并允许你编写这样的代码

          from contextlib import closing
          from urllib.request import urlopen

          with closing(urlopen('http://www.python.org')) as page:
              for line in page:
                  print(line)

     而无需显式地关闭 ‘page’ 。 即使发生错误，在退出 *note with: 6f2. 语
     句块时， ‘page.close()’ 也同样会被调用。
 -- 函数: contextlib.nullcontext (enter_result=None)

     返回一个从 `__enter__' 返回 `enter_result' 的上下文管理器，除此之外
     不执行任何操作。它旨在用于可选上下文管理器的一种替代，例如：:

          def myfunction(arg, ignore_exceptions=False):
              if ignore_exceptions:
                  # Use suppress to ignore all exceptions.
                  cm = contextlib.suppress(Exception)
              else:
                  # Do not ignore any exceptions, cm has no effect.
                  cm = contextlib.nullcontext()
              with cm:
                  # Do something

     一个使用 `enter_result' 的例子：

          def process_file(file_or_path):
              if isinstance(file_or_path, str):
                  # If string, open file
                  cm = open(file_or_path)
              else:
                  # Caller is responsible for closing file
                  cm = nullcontext(file_or_path)

              with cm as file:
                  # Perform processing on the file

     3.7 新版功能.

 -- 函数: contextlib.suppress (*exceptions)

     返回一个上下文管理器，如果任何一个指定的异常发生在使用该上下文管理
     器的 with 语句中，该异常将被它抑制，然后程序将从 with 语句结束后的
     第一个语句开始恢复执行。

     与完全抑制异常的任何其他机制一样，该上下文管理器应当只用来抑制非常
     具体的错误，并确保该场景下静默地继续执行程序是通用的正确做法。

     例如

          from contextlib import suppress

          with suppress(FileNotFoundError):
              os.remove('somefile.tmp')

          with suppress(FileNotFoundError):
              os.remove('someotherfile.tmp')

     这段代码等价于：

          try:
              os.remove('somefile.tmp')
          except FileNotFoundError:
              pass

          try:
              os.remove('someotherfile.tmp')
          except FileNotFoundError:
              pass

     该上下文管理器是 *note reentrant: 3682. 。

     3.4 新版功能.

 -- 函数: contextlib.redirect_stdout (new_target)

     用于将 *note sys.stdout: 317. 临时重定向到一个文件或类文件对象的上
     下文管理器。

     该工具给已有的将输出硬编码写到 stdout 的函数或类提供了额外的灵活性
     。

     例如， *note help(): 57b. 通常把输出写到 `sys.stdout' 。你可以通过
     重定向到一个 *note io.StringIO: 836. 来捕获该输出到一个字符串中。

          f = io.StringIO()
          with redirect_stdout(f):
              help(pow)
          s = f.getvalue()

     如果要把 *note help(): 57b. 的输出写到磁盘上的一个文件，重定向该输
     出到一个常规文件：

          with open('help.txt', 'w') as f:
              with redirect_stdout(f):
                  help(pow)

     如果要把 *note help(): 57b. 的输出写到 `sys.stderr' ：

          with redirect_stdout(sys.stderr):
              help(pow)

     需要注意的点在于， *note sys.stdout: 317. 的全局副作用意味着此上下
     文管理器不适合在库代码和大多数多线程应用程序中使用。它对子进程的输
     出没有影响。不过对于许多工具脚本而言，它仍然是一个有用的方法。

     该上下文管理器是 *note reentrant: 3682. 。

     3.4 新版功能.

 -- 函数: contextlib.redirect_stderr (new_target)

     与 *note redirect_stdout(): 6cb. 类似，不过是将 *note sys.stderr:
     318. 重定向到一个文件或类文件对象。

     该上下文管理器是 *note reentrant: 3682. 。

     3.5 新版功能.

 -- 类: contextlib.ContextDecorator

     一个使上下文管理器能用作装饰器的基类。

     与往常一样，继承自 ‘ContextDecorator’  的上下文管理器必须实现
     ‘__enter__’ 与 ‘__exit__’ 。即使用作装饰器， ‘__exit__’ 依旧会保持
     可能的异常处理。

     ‘ContextDecorator’ 被用在 *note contextmanager(): b86. 中，因此你自
     然获得了这项功能。

     ‘ContextDecorator’ 的示例:

          from contextlib import ContextDecorator

          class mycontext(ContextDecorator):
              def __enter__(self):
                  print('Starting')
                  return self

              def __exit__(self, *exc):
                  print('Finishing')
                  return False

          >>> @mycontext()
          ... def function():
          ...     print('The bit in the middle')
          ...
          >>> function()
          Starting
          The bit in the middle
          Finishing

          >>> with mycontext():
          ...     print('The bit in the middle')
          ...
          Starting
          The bit in the middle
          Finishing

     这个改动只是针对如下形式的一个语法糖：

          def f():
              with cm():
                  # Do stuff

     ‘ContextDecorator’ 使得你可以这样改写：

          @cm()
          def f():
              # Do stuff

     这能清楚地表明， ‘cm’ 作用于整个函数，而不仅仅是函数的一部分（同时
     也能保持不错的缩进层级）。

     现有的上下文管理器即使已经有基类，也可以使用 ‘ContextDecorator’ 作
     为混合类进行扩展：

          from contextlib import ContextDecorator

          class mycontext(ContextBaseClass, ContextDecorator):
              def __enter__(self):
                  return self

              def __exit__(self, *exc):
                  return False

          注解: 由于被装饰的函数必须能够被多次调用，因此对应的上下文管理
          器必须支持在多个 *note with: 6f2. 语句中使用。如果不是这样，则
          应当使用原来的具有显式 ‘with’ 语句的形式使用该上下文管理器。

     3.2 新版功能.

 -- 类: contextlib.ExitStack

     该上下文管理器的设计目标是使得在编码中组合其他上下文管理器和清理函
     数更加容易，尤其是那些可选的或由输入数据驱动的上下文管理器。

     例如，通过一个如下的 with 语句可以很容易处理一组文件：

          with ExitStack() as stack:
              files = [stack.enter_context(open(fname)) for fname in filenames]
              # All opened files will automatically be closed at the end of
              # the with statement, even if attempts to open files later
              # in the list raise an exception

     每个实例维护一个注册了一组回调的栈，这些回调在实例关闭时以相反的顺
     序被调用（显式或隐式地在 *note with: 6f2. 语句的末尾）。请注意，当
     一个栈实例被垃圾回收时，这些回调将 `不会' 被隐式调用。

     通过使用这个基于栈的模型，那些通过 ‘__init__’ 方法获取资源的上下文
     管理器（如文件对象）能够被正确处理。

     由于注册的回调函数是按照与注册相反的顺序调用的，因此最终的行为就像
     多个嵌套的 *note with: 6f2. 语句用在这些注册的回调函数上。这个行为
     甚至扩展到了异常处理：如果内部的回调函数抑制或替换了异常，则外部回
     调收到的参数是基于该更新后的状态得到的。

     这是一个相对底层的 API，它负责正确处理栈里回调退出时依次展开的细节
     。它为相对高层的上下文管理器提供了一个合适的基础，使得它能根据应用
     程序的需求使用特定方式操作栈。

     3.3 新版功能.

      -- 方法: enter_context (cm)

          Enters a new context manager and adds its *note __exit__():
          c9e. method to the callback stack.  The return value is the
          result of the context manager’s own *note __enter__(): c9d.
          method.

          These context managers may suppress exceptions just as they
          normally would if used directly as part of a *note with: 6f2.
          statement.

      -- 方法: push (exit)

          Adds a context manager’s *note __exit__(): c9e. method to the
          callback stack.

          As ‘__enter__’ is `not' invoked, this method can be used to
          cover part of an *note __enter__(): c9d. implementation with a
          context manager’s own *note __exit__(): c9e. method.

          If passed an object that is not a context manager, this method
          assumes it is a callback with the same signature as a context
          manager’s *note __exit__(): c9e. method and adds it directly
          to the callback stack.

          By returning true values, these callbacks can suppress
          exceptions the same way context manager *note __exit__(): c9e.
          methods can.

          The passed in object is returned from the function, allowing
          this method to be used as a function decorator.

      -- 方法: callback (callback, *args, **kwds)

          Accepts an arbitrary callback function and arguments and adds
          it to the callback stack.

          Unlike the other methods, callbacks added this way cannot
          suppress exceptions (as they are never passed the exception
          details).

          The passed in callback is returned from the function, allowing
          this method to be used as a function decorator.

      -- 方法: pop_all ()

          Transfers the callback stack to a fresh *note ExitStack: 37f.
          instance and returns it.  No callbacks are invoked by this
          operation - instead, they will now be invoked when the new
          stack is closed (either explicitly or implicitly at the end of
          a *note with: 6f2. statement).

          For example, a group of files can be opened as an "all or
          nothing" operation as follows:

               with ExitStack() as stack:
                   files = [stack.enter_context(open(fname)) for fname in filenames]
                   # Hold onto the close method, but don't call it yet.
                   close_files = stack.pop_all().close
                   # If opening any file fails, all previously opened files will be
                   # closed automatically. If all files are opened successfully,
                   # they will remain open even after the with statement ends.
                   # close_files() can then be invoked explicitly to close them all.

      -- 方法: close ()

          Immediately unwinds the callback stack, invoking callbacks in
          the reverse order of registration.  For any context managers
          and exit callbacks registered, the arguments passed in will
          indicate that no exception occurred.

 -- 类: contextlib.AsyncExitStack

     An *note asynchronous context manager: 14a6, similar to *note
     ExitStack: 37f, that supports combining both synchronous and
     asynchronous context managers, as well as having coroutines for
     cleanup logic.

     The ‘close()’ method is not implemented, *note aclose(): 3687. must
     be used instead.

      -- 方法: enter_async_context (cm)

          Similar to ‘enter_context()’ but expects an asynchronous
          context manager.

      -- 方法: push_async_exit (exit)

          Similar to ‘push()’ but expects either an asynchronous context
          manager or a coroutine function.

      -- 方法: push_async_callback (callback, *args, **kwds)

          Similar to ‘callback()’ but expects a coroutine function.

      -- 方法: aclose ()

          Similar to ‘close()’ but properly handles awaitables.

     Continuing the example for *note asynccontextmanager(): 380.:

          async with AsyncExitStack() as stack:
              connections = [await stack.enter_async_context(get_connection())
                  for i in range(5)]
              # All opened connections will automatically be released at the end of
              # the async with statement, even if attempts to open a connection
              # later in the list raise an exception.

     3.7 新版功能.


File: python.info,  Node: 例子和配方<2>,  Next: Single use reusable and reentrant context managers,  Prev: 工具,  Up: contextlib --- 为 with语句上下文提供的工具

5.29.7.2 例子和配方
...................

This section describes some examples and recipes for making effective
use of the tools provided by *note contextlib: 24.

* Menu:

* Supporting a variable number of context managers::
* Catching exceptions from __enter__ methods::
* Cleaning up in an __enter__ implementation::
* Replacing any use of try-finally and flag variables::
* Using a context manager as a function decorator::


File: python.info,  Node: Supporting a variable number of context managers,  Next: Catching exceptions from __enter__ methods,  Up: 例子和配方<2>

5.29.7.3 Supporting a variable number of context managers
.........................................................

The primary use case for *note ExitStack: 37f. is the one given in the
class documentation: supporting a variable number of context managers
and other cleanup operations in a single *note with: 6f2. statement.
The variability may come from the number of context managers needed
being driven by user input (such as opening a user specified collection
of files), or from some of the context managers being optional:

     with ExitStack() as stack:
         for resource in resources:
             stack.enter_context(resource)
         if need_special_resource():
             special = acquire_special_resource()
             stack.callback(release_special_resource, special)
         # Perform operations that use the acquired resources

As shown, *note ExitStack: 37f. also makes it quite easy to use *note
with: 6f2. statements to manage arbitrary resources that don’t natively
support the context management protocol.


File: python.info,  Node: Catching exceptions from __enter__ methods,  Next: Cleaning up in an __enter__ implementation,  Prev: Supporting a variable number of context managers,  Up: 例子和配方<2>

5.29.7.4 Catching exceptions from ‘__enter__’ methods
.....................................................

It is occasionally desirable to catch exceptions from an ‘__enter__’
method implementation, `without' inadvertently catching exceptions from
the *note with: 6f2. statement body or the context manager’s ‘__exit__’
method.  By using *note ExitStack: 37f. the steps in the context
management protocol can be separated slightly in order to allow this:

     stack = ExitStack()
     try:
         x = stack.enter_context(cm)
     except Exception:
         # handle __enter__ exception
     else:
         with stack:
             # Handle normal case

Actually needing to do this is likely to indicate that the underlying
API should be providing a direct resource management interface for use
with *note try: d7a./*note except: b46./*note finally: 183. statements,
but not all APIs are well designed in that regard.  When a context
manager is the only resource management API provided, then *note
ExitStack: 37f. can make it easier to handle various situations that
can’t be handled directly in a *note with: 6f2. statement.


File: python.info,  Node: Cleaning up in an __enter__ implementation,  Next: Replacing any use of try-finally and flag variables,  Prev: Catching exceptions from __enter__ methods,  Up: 例子和配方<2>

5.29.7.5 Cleaning up in an ‘__enter__’ implementation
.....................................................

As noted in the documentation of *note ExitStack.push(): 3684, this
method can be useful in cleaning up an already allocated resource if
later steps in the *note __enter__(): c9d. implementation fail.

Here’s an example of doing this for a context manager that accepts
resource acquisition and release functions, along with an optional
validation function, and maps them to the context management protocol:

     from contextlib import contextmanager, AbstractContextManager, ExitStack

     class ResourceManager(AbstractContextManager):

         def __init__(self, acquire_resource, release_resource, check_resource_ok=None):
             self.acquire_resource = acquire_resource
             self.release_resource = release_resource
             if check_resource_ok is None:
                 def check_resource_ok(resource):
                     return True
             self.check_resource_ok = check_resource_ok

         @contextmanager
         def _cleanup_on_error(self):
             with ExitStack() as stack:
                 stack.push(self)
                 yield
                 # The validation check passed and didn't raise an exception
                 # Accordingly, we want to keep the resource, and pass it
                 # back to our caller
                 stack.pop_all()

         def __enter__(self):
             resource = self.acquire_resource()
             with self._cleanup_on_error():
                 if not self.check_resource_ok(resource):
                     msg = "Failed validation for {!r}"
                     raise RuntimeError(msg.format(resource))
             return resource

         def __exit__(self, *exc_details):
             # We don't need to duplicate any of our resource release logic
             self.release_resource()


File: python.info,  Node: Replacing any use of try-finally and flag variables,  Next: Using a context manager as a function decorator,  Prev: Cleaning up in an __enter__ implementation,  Up: 例子和配方<2>

5.29.7.6 Replacing any use of ‘try-finally’ and flag variables
..............................................................

A pattern you will sometimes see is a ‘try-finally’ statement with a
flag variable to indicate whether or not the body of the ‘finally’
clause should be executed.  In its simplest form (that can’t already be
handled just by using an ‘except’ clause instead), it looks something
like this:

     cleanup_needed = True
     try:
         result = perform_operation()
         if result:
             cleanup_needed = False
     finally:
         if cleanup_needed:
             cleanup_resources()

As with any ‘try’ statement based code, this can cause problems for
development and review, because the setup code and the cleanup code can
end up being separated by arbitrarily long sections of code.

*note ExitStack: 37f. makes it possible to instead register a callback
for execution at the end of a ‘with’ statement, and then later decide to
skip executing that callback:

     from contextlib import ExitStack

     with ExitStack() as stack:
         stack.callback(cleanup_resources)
         result = perform_operation()
         if result:
             stack.pop_all()

This allows the intended cleanup up behaviour to be made explicit up
front, rather than requiring a separate flag variable.

If a particular application uses this pattern a lot, it can be
simplified even further by means of a small helper class:

     from contextlib import ExitStack

     class Callback(ExitStack):
         def __init__(self, callback, /, *args, **kwds):
             super().__init__()
             self.callback(callback, *args, **kwds)

         def cancel(self):
             self.pop_all()

     with Callback(cleanup_resources) as cb:
         result = perform_operation()
         if result:
             cb.cancel()

If the resource cleanup isn’t already neatly bundled into a standalone
function, then it is still possible to use the decorator form of *note
ExitStack.callback(): 2a6. to declare the resource cleanup in advance:

     from contextlib import ExitStack

     with ExitStack() as stack:
         @stack.callback
         def cleanup_resources():
             ...
         result = perform_operation()
         if result:
             stack.pop_all()

Due to the way the decorator protocol works, a callback function
declared this way cannot take any parameters.  Instead, any resources to
be released must be accessed as closure variables.


File: python.info,  Node: Using a context manager as a function decorator,  Prev: Replacing any use of try-finally and flag variables,  Up: 例子和配方<2>

5.29.7.7 Using a context manager as a function decorator
........................................................

*note ContextDecorator: b85. makes it possible to use a context manager
in both an ordinary ‘with’ statement and also as a function decorator.

For example, it is sometimes useful to wrap functions or groups of
statements with a logger that can track the time of entry and time of
exit.  Rather than writing both a function decorator and a context
manager for the task, inheriting from *note ContextDecorator: b85.
provides both capabilities in a single definition:

     from contextlib import ContextDecorator
     import logging

     logging.basicConfig(level=logging.INFO)

     class track_entry_and_exit(ContextDecorator):
         def __init__(self, name):
             self.name = name

         def __enter__(self):
             logging.info('Entering: %s', self.name)

         def __exit__(self, exc_type, exc, exc_tb):
             logging.info('Exiting: %s', self.name)

Instances of this class can be used as both a context manager:

     with track_entry_and_exit('widget loader'):
         print('Some time consuming activity goes here')
         load_widget()

And also as a function decorator:

     @track_entry_and_exit('widget loader')
     def activity():
         print('Some time consuming activity goes here')
         load_widget()

Note that there is one additional limitation when using context managers
as function decorators: there’s no way to access the return value of
*note __enter__(): c9d.  If that value is needed, then it is still
necessary to use an explicit ‘with’ statement.

参见
....

PEP 343(1) - "with" 语句

     Python *note with: 6f2. 语句的规范描述、背景和示例。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0343


File: python.info,  Node: Single use reusable and reentrant context managers,  Prev: 例子和配方<2>,  Up: contextlib --- 为 with语句上下文提供的工具

5.29.7.8 Single use, reusable and reentrant context managers
............................................................

Most context managers are written in a way that means they can only be
used effectively in a *note with: 6f2. statement once.  These single use
context managers must be created afresh each time they’re used -
attempting to use them a second time will trigger an exception or
otherwise not work correctly.

This common limitation means that it is generally advisable to create
context managers directly in the header of the *note with: 6f2.
statement where they are used (as shown in all of the usage examples
above).

Files are an example of effectively single use context managers, since
the first *note with: 6f2. statement will close the file, preventing any
further IO operations using that file object.

Context managers created using *note contextmanager(): b86. are also
single use context managers, and will complain about the underlying
generator failing to yield if an attempt is made to use them a second
time:

     >>> from contextlib import contextmanager
     >>> @contextmanager
     ... def singleuse():
     ...     print("Before")
     ...     yield
     ...     print("After")
     ...
     >>> cm = singleuse()
     >>> with cm:
     ...     pass
     ...
     Before
     After
     >>> with cm:
     ...     pass
     ...
     Traceback (most recent call last):
         ...
     RuntimeError: generator didn't yield

* Menu:

* Reentrant context managers::
* Reusable context managers::


File: python.info,  Node: Reentrant context managers,  Next: Reusable context managers,  Up: Single use reusable and reentrant context managers

5.29.7.9 Reentrant context managers
...................................

More sophisticated context managers may be "reentrant".  These context
managers can not only be used in multiple *note with: 6f2. statements,
but may also be used `inside' a ‘with’ statement that is already using
the same context manager.

*note threading.RLock: bf7. is an example of a reentrant context
manager, as are *note suppress(): 835. and *note redirect_stdout(): 6cb.
Here’s a very simple example of reentrant use:

     >>> from contextlib import redirect_stdout
     >>> from io import StringIO
     >>> stream = StringIO()
     >>> write_to_stream = redirect_stdout(stream)
     >>> with write_to_stream:
     ...     print("This is written to the stream rather than stdout")
     ...     with write_to_stream:
     ...         print("This is also written to the stream")
     ...
     >>> print("This is written directly to stdout")
     This is written directly to stdout
     >>> print(stream.getvalue())
     This is written to the stream rather than stdout
     This is also written to the stream

Real world examples of reentrancy are more likely to involve multiple
functions calling each other and hence be far more complicated than this
example.

Note also that being reentrant is `not' the same thing as being thread
safe.  *note redirect_stdout(): 6cb, for example, is definitely not
thread safe, as it makes a global modification to the system state by
binding *note sys.stdout: 317. to a different stream.


File: python.info,  Node: Reusable context managers,  Prev: Reentrant context managers,  Up: Single use reusable and reentrant context managers

5.29.7.10 Reusable context managers
...................................

Distinct from both single use and reentrant context managers are
"reusable" context managers (or, to be completely explicit, "reusable,
but not reentrant" context managers, since reentrant context managers
are also reusable).  These context managers support being used multiple
times, but will fail (or otherwise not work correctly) if the specific
context manager instance has already been used in a containing with
statement.

*note threading.Lock: 2374. is an example of a reusable, but not
reentrant, context manager (for a reentrant lock, it is necessary to use
*note threading.RLock: bf7. instead).

Another example of a reusable, but not reentrant, context manager is
*note ExitStack: 37f, as it invokes `all' currently registered callbacks
when leaving any with statement, regardless of where those callbacks
were added:

     >>> from contextlib import ExitStack
     >>> stack = ExitStack()
     >>> with stack:
     ...     stack.callback(print, "Callback: from first context")
     ...     print("Leaving first context")
     ...
     Leaving first context
     Callback: from first context
     >>> with stack:
     ...     stack.callback(print, "Callback: from second context")
     ...     print("Leaving second context")
     ...
     Leaving second context
     Callback: from second context
     >>> with stack:
     ...     stack.callback(print, "Callback: from outer context")
     ...     with stack:
     ...         stack.callback(print, "Callback: from inner context")
     ...         print("Leaving inner context")
     ...     print("Leaving outer context")
     ...
     Leaving inner context
     Callback: from inner context
     Callback: from outer context
     Leaving outer context

As the output from the example shows, reusing a single stack object
across multiple with statements works correctly, but attempting to nest
them will cause the stack to be cleared at the end of the innermost with
statement, which is unlikely to be desirable behaviour.

Using separate *note ExitStack: 37f. instances instead of reusing a
single instance avoids that problem:

     >>> from contextlib import ExitStack
     >>> with ExitStack() as outer_stack:
     ...     outer_stack.callback(print, "Callback: from outer context")
     ...     with ExitStack() as inner_stack:
     ...         inner_stack.callback(print, "Callback: from inner context")
     ...         print("Leaving inner context")
     ...     print("Leaving outer context")
     ...
     Leaving inner context
     Callback: from inner context
     Leaving outer context
     Callback: from outer context


File: python.info,  Node: abc --- 抽象基类,  Next: atexit --- 退出处理器,  Prev: contextlib --- 为 with语句上下文提供的工具,  Up: Python运行时服务

5.29.8 ‘abc’ — 抽象基类
-----------------------

`源代码：' Lib/abc.py(1)

__________________________________________________________________

该模块提供了在 Python 中定义 *note 抽象基类: b3b. (ABC) 的组件，在 PEP
3119(2) 中已有概述。查看 PEP 文档了解为什么需要在 Python 中增加这个模块
。（也可查看 PEP 3141(3) 以及 *note numbers: c2. 模块了解基于 ABC 的数字
类型继承关系。）

*note collections: 1e. 模块中有一些派生自 ABC 的具体类；当然这些类还可以
进一步被派生。此外，*note collections.abc: 1f. 子模块中有一些 ABC 可被用
于测试一个类或实例是否提供特定的接口，例如它是否可哈希或它是否为映射等。

该模块提供了一个元类 *note ABCMeta: 822.，可以用来定义抽象类，另外还提供
一个工具类 *note ABC: 821.，可以用它以继承的方式定义抽象基类。

 -- 类: abc.ABC

     一个使用 *note ABCMeta: 822. 作为元类的工具类。抽象基类可以通过从
     *note ABC: 821. 派生来简单地创建，这就避免了在某些情况下会令人混淆
     的元类用法，例如：

          from abc import ABC

          class MyABC(ABC):
              pass

     注意 *note ABC: 821. 的类型仍然是 *note ABCMeta: 822.，因此继承
     *note ABC: 821. 仍然需要关注元类使用中的注意事项，比如可能会导致元
     类冲突的多重继承。当然你也可以直接使用 *note ABCMeta: 822. 作为元类
     来定义抽象基类，例如：

          from abc import ABCMeta

          class MyABC(metaclass=ABCMeta):
              pass

     3.4 新版功能.

 -- 类: abc.ABCMeta

     用于定义抽象基类（ABC）的元类。

     使用该元类以创建抽象基类。抽象基类可以像 mix-in 类一样直接被子类继
     承。你也可以将不相关的具体类（包括内建类）和抽象基类注册为“抽象子类
     ” —— 这些类以及它们的子类会被内建函数 *note issubclass(): 458. 识别
     为对应的抽象基类的子类，但是该抽象基类不会出现在其 MRO（Method
     Resolution Order，方法解析顺序）中，抽象基类中实现的方法也不可调用
     （即使通过 *note super(): 4eb. 调用也不行）。(4)

     使用 *note ABCMeta: 822. 作为元类创建的类含有如下方法：

      -- 方法: register (subclass)

          将“子类”注册为该抽象基类的“抽象子类”，例如：

               from abc import ABC

               class MyABC(ABC):
                   pass

               MyABC.register(tuple)

               assert issubclass(tuple, MyABC)
               assert isinstance((), MyABC)

          在 3.3 版更改: 返回注册的子类，使其能够作为类装饰器。

          在 3.4 版更改: 你可以使用 *note get_cache_token(): 820. 函数来
          检测对 *note register(): 9d9. 的调用。

     你也可以在虚基类中重载这个方法。

      -- 方法: __subclasshook__ (subclass)

          （必须定义为类方法。）

          检查 `subclass' 是否是该抽象基类的子类。也就是说对于那些你希望
          定义为该抽象基类的子类的类，你不用对每个类都调用 *note
          register(): 9d9. 方法了，而是可以直接自定义 ‘issubclass’ 的行
          为。（这个类方法是在抽象基类的 ‘__subclasscheck__()’ 方法中调
          用的。）

          该方法必须返回 ‘True’, ‘False’ 或是 ‘NotImplemented’。如果返回
          ‘True’，`subclass' 就会被认为是这个抽象基类的子类。如果返回
          ‘False’，无论正常情况是否应该认为是其子类，统一视为不是。如果
          返回 ‘NotImplemented’，子类检查会按照正常机制继续执行。

     为了对这些概念做一演示，请看以下定义 ABC 的示例：

          class Foo:
              def __getitem__(self, index):
                  ...
              def __len__(self):
                  ...
              def get_iterator(self):
                  return iter(self)

          class MyIterable(ABC):

              @abstractmethod
              def __iter__(self):
                  while False:
                      yield None

              def get_iterator(self):
                  return self.__iter__()

              @classmethod
              def __subclasshook__(cls, C):
                  if cls is MyIterable:
                      if any("__iter__" in B.__dict__ for B in C.__mro__):
                          return True
                  return NotImplemented

          MyIterable.register(Foo)

     ABC ‘MyIterable’ 定义了标准的迭代方法 *note __iter__(): 163a. 作为
     一个抽象方法。这里给出的实现仍可在子类中被调用。‘get_iterator()’ 方
     法也是 ‘MyIterable’ 抽象基类的一部分，但它并非必须被非抽象派生类所
     重载。

     这里定义的 *note __subclasshook__(): 3696. 类方法指明了任何在其
     *note __dict__: 504. (或在其通过 *note __mro__: 1615. 列表访问的基
     类) 中具有 *note __iter__(): 163a. 方法的类也都会被视为
     ‘MyIterable’。

     最后，末尾行使得 ‘Foo’ 成为 ‘MyIterable’ 的一个虚子类，即使它没有定
     义 *note __iter__(): 163a. 方法（它使用了以 *note __len__(): dd3. 和
     *note __getitem__(): 280. 术语定义的旧式可迭代对象协议）。 请注意这
     将不会使 ‘get_iterator’ 成为 ‘Foo’ 的一个可用方法，它是被另外提供的
     。

此外，*note abc: 4. 模块还提供了这些装饰器：

 -- 函数: @abc.abstractmethod

     用于声明抽象方法的装饰器。

     使用此装饰器要求类的元类是 *note ABCMeta: 822. 或是从该类派生。一个
     具有派生自 *note ABCMeta: 822. 的元类的类不可以被实例化，除非它全部
     的抽象方法和特征属性均已被重载。抽象方法可通过任何普通的“super”调用
     机制来调用。 *note abstractmethod(): 9d6. 可被用于声明特性属性和描
     述器的抽象方法。

     不支持动态添加抽象方法到一个类，或试图在方法或类被创建后修改其抽象
     状态等操作。 *note abstractmethod(): 9d6. 只会影响使用常规继承所派
     生的子类；通过 ABC 的 ‘register()’ 方法注册的“虚子类”不会受到影响。

     当 *note abstractmethod(): 9d6. 与其他方法描述符配合应用时，它应当
     被应用为最内层的装饰器，如以下用法示例所示:

          class C(ABC):
              @abstractmethod
              def my_abstract_method(self, ...):
                  ...
              @classmethod
              @abstractmethod
              def my_abstract_classmethod(cls, ...):
                  ...
              @staticmethod
              @abstractmethod
              def my_abstract_staticmethod(...):
                  ...

              @property
              @abstractmethod
              def my_abstract_property(self):
                  ...
              @my_abstract_property.setter
              @abstractmethod
              def my_abstract_property(self, val):
                  ...

              @abstractmethod
              def _get_x(self):
                  ...
              @abstractmethod
              def _set_x(self, val):
                  ...
              x = property(_get_x, _set_x)

     为了能正确地与抽象基类机制实现互操作，描述符必须使用
     ‘__isabstractmethod__’ 将自身标识为抽象的。 通常，如果被用于组成描
     述符的任何方法都是抽象的则此属性应当为 ‘True’。 例如，Python 的内置
     *note property: 1d8. 所做的就等价于:

          class Descriptor:
              ...
              @property
              def __isabstractmethod__(self):
                  return any(getattr(f, '__isabstractmethod__', False) for
                             f in (self._fget, self._fset, self._fdel))

          注解: 不同于 Java 抽象方法，这些抽象方法可能具有一个实现。 这
          个实现可在重载它的类上通过 *note super(): 4eb. 机制来调用。 这
          在使用协作多重继承的框架中可以被用作超调用的一个端点。

*note abc: 4. 模块还支持下列旧式装饰器:

 -- 函数: @abc.abstractclassmethod

     3.2 新版功能.

     3.3 版后已移除: 现在可以让 *note classmethod: 1d9. 配合 *note
     abstractmethod(): 9d6. 使用，使得此装饰器变得冗余。

     内置 *note classmethod(): 1d9. 的子类，指明一个抽象类方法。 在其他
     情况下它都类似于 *note abstractmethod(): 9d6.。

     这个特殊情况已被弃用，因为现在 *note classmethod(): 1d9. 当将装饰器
     应用于抽象方法时它会被正确地标识为抽象的:

          class C(ABC):
              @classmethod
              @abstractmethod
              def my_abstract_classmethod(cls, ...):
                  ...

 -- 函数: @abc.abstractstaticmethod

     3.2 新版功能.

     3.3 版后已移除: 现在可以让 *note staticmethod: 1da. 配合 *note
     abstractmethod(): 9d6. 使用，使得此装饰器变得冗余。

     内置 *note staticmethod(): 1da. 的子类，指明一个抽象静态方法。 在其
     他方面它都类似于 *note abstractmethod(): 9d6.。

     这个特殊情况已被弃用，因为现在当 *note staticmethod(): 1da. 装饰器
     应用于抽象方法时它会被正确地标识为抽象的:

          class C(ABC):
              @staticmethod
              @abstractmethod
              def my_abstract_staticmethod(...):
                  ...

 -- 函数: @abc.abstractproperty

     3.3 版后已移除: 现在可以让 *note property: 1d8,
     ‘property.getter()’, ‘property.setter()’ 和 ‘property.deleter()’ 配
     合 *note abstractmethod(): 9d6. 使用，使得此装饰器变得冗余。

     内置 *note property(): 1d8. 的子类，指明一个抽象特性属性。

     这个特例已被弃用，因为现在当 *note property(): 1d8. 装饰器应用于抽
     象方法时它会被正确地标识为抽象的:

          class C(ABC):
              @property
              @abstractmethod
              def my_abstract_property(self):
                  ...

     上面的例子定义了一个只读特征属性；你也可以通过适当地将一个或多个下
     层方法标记为抽象的来定义可读写的抽象特征属性:

          class C(ABC):
              @property
              def x(self):
                  ...

              @x.setter
              @abstractmethod
              def x(self, val):
                  ...

     如果只有某些组件是抽象的，则只需更新那些组件即可在子类中创建具体的
     特征属性:

          class D(C):
              @C.x.setter
              def x(self, val):
                  ...

*note abc: 4. 模块还提供了这些函数：

 -- 函数: abc.get_cache_token ()

     返回当前抽象基类的缓存令牌

     此令牌是一个不透明对象（支持相等性测试），用于为虚子类标识抽象基类
     缓存的当前版本。 此令牌会在任何 ABC 上每次调用 *note
     ABCMeta.register(): 9d9. 时发生更改。

     3.4 新版功能.

备注
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/abc.py

   (2) https://www.python.org/dev/peps/pep-3119

   (3) https://www.python.org/dev/peps/pep-3141

   (4) (1) C++ 程序员需要注意：Python 中虚基类的概念和 C++ 中的并不相同
。


File: python.info,  Node: atexit --- 退出处理器,  Next: traceback --- 打印或检索堆栈回溯,  Prev: abc --- 抽象基类,  Up: Python运行时服务

5.29.9 ‘atexit’ — 退出处理器
----------------------------

__________________________________________________________________

*note atexit: c. 模块定义了清理函数的注册和反注册函数. 被注册的函数会在
解释器正常终止时执行.  *note atexit: c. 会按照注册顺序的*逆序*执行; 如果
你注册了 ‘A’, ‘B’ 和 ‘C’, 那么在解释器终止时会依序执行 ‘C’, ‘B’, ‘A’.

`注意:' 通过该模块注册的函数, 在程序被未被 Python 捕获的信号杀死时并不会
执行, 在检测到 Python 内部致命错误以及调用了 *note os._exit(): 171e. 时
也不会执行.

在 3.7 版更改: 当配合 C-API 子解释器使用时，已注册函数是它们所注册解释器
中的局部对象。

 -- 函数: atexit.register (func, *args, **kwargs)

     将 `func' 注册为终止时执行的函数.  任何传给 `func' 的可选的参数都应
     当作为参数传给 *note register(): e8d.  可以多次注册同样的函数及参数
     .

     在正常的程序终止时 (举例来说, 当调用了 *note sys.exit(): cea. 或是
     主模块的执行完成时), 所有注册过的函数都会以后进先出的顺序执行. 这样
     做是假定更底层的模块通常会比高层模块更早引入, 因此需要更晚清理.

     如果在 exit 处理程序执行期间引发了异常，将会打印回溯信息 (除非引发
     的是 *note SystemExit: 605.) 并且异常信息会被保存。 在所有 exit 处
     理程序获得运行机会之后，所引发的最后一个异常会被重新引发。

     这个函数返回 `func' 对象，可以把它当作装饰器使用。

 -- 函数: atexit.unregister (func)

     从解释器关闭前要运行的函数列表中移除 `func'。 在调用 *note
     unregister(): 3699. 之后，当解释器关闭时会确保 `func' 不会被调用，
     即使它被多次注册。 如果 `func' 之前没有被注册，*note unregister():
     3699. 会静默地不做任何操作。

参见
....

模块 *note readline: df.

     使用 *note atexit: c. 读写 *note readline: df. 历史文件的有用的例子
     。

* Menu:

* atexit 示例::


File: python.info,  Node: atexit 示例,  Up: atexit --- 退出处理器

5.29.9.1 ‘atexit’ 示例
......................

以下简单例子演示了一个模块在被导入时如何从文件初始化一个计数器，并在程序
终结时自动保存计数器的更新值，此操作不依赖于应用在终结时对此模块进行显式
调用。:

     try:
         with open("counterfile") as infile:
             _count = int(infile.read())
     except FileNotFoundError:
         _count = 0

     def incrcounter(n):
         global _count
         _count = _count + n

     def savecounter():
         with open("counterfile", "w") as outfile:
             outfile.write("%d" % _count)

     import atexit
     atexit.register(savecounter)

位置和关键字参数也可传入 *note register(): e8d. 以便传递给被调用的已注册
函数:

     def goodbye(name, adjective):
         print('Goodbye, %s, it was %s to meet you.' % (name, adjective))

     import atexit
     atexit.register(goodbye, 'Donny', 'nice')

     # or:
     atexit.register(goodbye, adjective='nice', name='Donny')

作为 *note decorator: 284.: 使用:

     import atexit

     @atexit.register
     def goodbye():
         print("You are now leaving the Python sector.")

只有在函数不需要任何参数调用时才能工作.


File: python.info,  Node: traceback --- 打印或检索堆栈回溯,  Next: __future__ --- Future 语句定义,  Prev: atexit --- 退出处理器,  Up: Python运行时服务

5.29.10 ‘traceback’ — 打印或检索堆栈回溯
----------------------------------------

`源代码：' Lib/traceback.py(1)

__________________________________________________________________

该模块提供了一个标准接口来提取、格式化和打印 Python 程序的堆栈跟踪结果。
它完全模仿Python 解释器在打印堆栈跟踪结果时的行为。当您想要在程序控制下
打印堆栈跟踪结果时，例如在“封装”解释器时，这是非常有用的。

这个模块使用 traceback 对象 —— 这是存储在 *note sys.last_traceback:
353c. 中的对象类型变量，并作为 *note sys.exc_info(): c67. 的第三项被返回
。

这个模块定义了以下函数：

 -- 函数: traceback.print_tb (tb, limit=None, file=None)

     如果*limit*是正整数，那么从 traceback 对象 "tb" 输出最高 `limit' 个
     （从调用函数开始的）栈的堆栈回溯‎条目‎；如果 `limit' 是负数就输出
     ‘abs(limit)’ 个回溯条目；又如果 `limit' 被省略或者为 ‘None’，那么就
     会输出所有回溯条目。如果 `file' 被省略或为 ‘None’ 那么就会输出至标
     准输出‘‘sys.stderr‘‘否则它应该是一个打开的文件或者文件类对象来接收
     输出

     在 3.5 版更改: 添加了对负数值 `limit' 的支持

 -- 函数: traceback.print_exception (etype, value, tb, limit=None,
          file=None, chain=True)

     打印回溯对象 `tb' 到 `file' 的异常信息和整个堆栈回溯。这和 *note
     print_tb(): 782. 比有以下方面不同：

        * 如果 `tb' 不为 ‘None’，它将打印一个开始信息‘‘Traceback (most
          recent call last):‘‘

        * 它将在输出完堆栈回溯后，输出异常中的 `etype' 和 `value' 的信息

        * if `type(value)' is *note SyntaxError: 460. and `value' has
          the appropriate format, it prints the line where the syntax
          error occurred with a caret indicating the approximate
          position of the error.

     The optional `limit' argument has the same meaning as for *note
     print_tb(): 782.  If `chain' is true (the default), then chained
     exceptions (the ‘__cause__’ or ‘__context__’ attributes of the
     exception) will be printed as well, like the interpreter itself
     does when printing an unhandled exception.

     在 3.5 版更改: The `etype' argument is ignored and inferred from
     the type of `value'.

 -- 函数: traceback.print_exc (limit=None, file=None, chain=True)

     This is a shorthand for ‘print_exception(*sys.exc_info(), limit,
     file, chain)’.

 -- 函数: traceback.print_last (limit=None, file=None, chain=True)

     This is a shorthand for ‘print_exception(sys.last_type,
     sys.last_value, sys.last_traceback, limit, file, chain)’.  In
     general it will work only after an exception has reached an
     interactive prompt (see *note sys.last_type: c62.).

 -- 函数: traceback.print_stack (f=None, limit=None, file=None)

     Print up to `limit' stack trace entries (starting from the
     invocation point) if `limit' is positive.  Otherwise, print the
     last ‘abs(limit)’ entries.  If `limit' is omitted or ‘None’, all
     entries are printed.  The optional `f' argument can be used to
     specify an alternate stack frame to start.  The optional `file'
     argument has the same meaning as for *note print_tb(): 782.

     在 3.5 版更改: 添加了对负数值 `limit' 的支持

 -- 函数: traceback.extract_tb (tb, limit=None)

     Return a *note StackSummary: 780. object representing a list of
     "pre-processed" stack trace entries extracted from the traceback
     object `tb'.  It is useful for alternate formatting of stack
     traces.  The optional `limit' argument has the same meaning as for
     *note print_tb(): 782.  A "pre-processed" stack trace entry is a
     *note FrameSummary: 781. object containing attributes ‘filename’,
     ‘lineno’, ‘name’, and ‘line’ representing the information that is
     usually printed for a stack trace.  The ‘line’ is a string with
     leading and trailing whitespace stripped; if the source is not
     available it is ‘None’.

 -- 函数: traceback.extract_stack (f=None, limit=None)

     Extract the raw traceback from the current stack frame.  The return
     value has the same format as for *note extract_tb(): 36a0.  The
     optional `f' and `limit' arguments have the same meaning as for
     *note print_stack(): 783.

 -- 函数: traceback.format_list (extracted_list)

     Given a list of tuples or *note FrameSummary: 781. objects as
     returned by *note extract_tb(): 36a0. or *note extract_stack():
     36a1, return a list of strings ready for printing.  Each string in
     the resulting list corresponds to the item with the same index in
     the argument list.  Each string ends in a newline; the strings may
     contain internal newlines as well, for those items whose source
     text line is not ‘None’.

 -- 函数: traceback.format_exception_only (etype, value)

     Format the exception part of a traceback.  The arguments are the
     exception type and value such as given by ‘sys.last_type’ and
     ‘sys.last_value’.  The return value is a list of strings, each
     ending in a newline.  Normally, the list contains a single string;
     however, for *note SyntaxError: 460. exceptions, it contains
     several lines that (when printed) display detailed information
     about where the syntax error occurred.  The message indicating
     which exception occurred is the always last string in the list.

 -- 函数: traceback.format_exception (etype, value, tb, limit=None,
          chain=True)

     Format a stack trace and the exception information.  The arguments
     have the same meaning as the corresponding arguments to *note
     print_exception(): 20bf.  The return value is a list of strings,
     each ending in a newline and some containing internal newlines.
     When these lines are concatenated and printed, exactly the same
     text is printed as does *note print_exception(): 20bf.

     在 3.5 版更改: The `etype' argument is ignored and inferred from
     the type of `value'.

 -- 函数: traceback.format_exc (limit=None, chain=True)

     This is like ‘print_exc(limit)’ but returns a string instead of
     printing to a file.

 -- 函数: traceback.format_tb (tb, limit=None)

     A shorthand for ‘format_list(extract_tb(tb, limit))’.

 -- 函数: traceback.format_stack (f=None, limit=None)

     A shorthand for ‘format_list(extract_stack(f, limit))’.

 -- 函数: traceback.clear_frames (tb)

     Clears the local variables of all the stack frames in a traceback
     `tb' by calling the ‘clear()’ method of each frame object.

     3.4 新版功能.

 -- 函数: traceback.walk_stack (f)

     Walk a stack following ‘f.f_back’ from the given frame, yielding
     the frame and line number for each frame.  If `f' is ‘None’, the
     current stack is used.  This helper is used with *note
     StackSummary.extract(): 36a6.

     3.5 新版功能.

 -- 函数: traceback.walk_tb (tb)

     Walk a traceback following ‘tb_next’ yielding the frame and line
     number for each frame.  This helper is used with *note
     StackSummary.extract(): 36a6.

     3.5 新版功能.

The module also defines the following classes:

* Menu:

* TracebackException Objects::
* StackSummary Objects::
* FrameSummary Objects::
* Traceback Examples::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/traceback.py


File: python.info,  Node: TracebackException Objects,  Next: StackSummary Objects,  Up: traceback --- 打印或检索堆栈回溯

5.29.10.1 ‘TracebackException’ Objects
......................................

3.5 新版功能.

*note TracebackException: 77f. objects are created from actual
exceptions to capture data for later printing in a lightweight fashion.

 -- 类: traceback.TracebackException (exc_type, exc_value,
          exc_traceback, *, limit=None, lookup_lines=True,
          capture_locals=False)

     Capture an exception for later rendering.  `limit', `lookup_lines'
     and `capture_locals' are as for the *note StackSummary: 780. class.

     Note that when locals are captured, they are also shown in the
     traceback.

      -- 属性: __cause__

          A *note TracebackException: 77f. of the original ‘__cause__’.

      -- 属性: __context__

          A *note TracebackException: 77f. of the original
          ‘__context__’.

      -- 属性: __suppress_context__

          The ‘__suppress_context__’ value from the original exception.

      -- 属性: stack

          A *note StackSummary: 780. representing the traceback.

      -- 属性: exc_type

          The class of the original traceback.

      -- 属性: filename

          For syntax errors - the file name where the error occurred.

      -- 属性: lineno

          For syntax errors - the line number where the error occurred.

      -- 属性: text

          For syntax errors - the text where the error occurred.

      -- 属性: offset

          For syntax errors - the offset into the text where the error
          occurred.

      -- 属性: msg

          For syntax errors - the compiler error message.

      -- 方法: classmethod from_exception (exc, *, limit=None,
               lookup_lines=True, capture_locals=False)

          Capture an exception for later rendering.  `limit',
          `lookup_lines' and `capture_locals' are as for the *note
          StackSummary: 780. class.

          Note that when locals are captured, they are also shown in the
          traceback.

      -- 方法: format (*, chain=True)

          Format the exception.

          If `chain' is not ‘True’, ‘__cause__’ and ‘__context__’ will
          not be formatted.

          The return value is a generator of strings, each ending in a
          newline and some containing internal newlines.  *note
          print_exception(): 20bf. is a wrapper around this method which
          just prints the lines to a file.

          The message indicating which exception occurred is always the
          last string in the output.

      -- 方法: format_exception_only ()

          Format the exception part of the traceback.

          The return value is a generator of strings, each ending in a
          newline.

          Normally, the generator emits a single string; however, for
          *note SyntaxError: 460. exceptions, it emits several lines
          that (when printed) display detailed information about where
          the syntax error occurred.

          The message indicating which exception occurred is always the
          last string in the output.


File: python.info,  Node: StackSummary Objects,  Next: FrameSummary Objects,  Prev: TracebackException Objects,  Up: traceback --- 打印或检索堆栈回溯

5.29.10.2 ‘StackSummary’ Objects
................................

3.5 新版功能.

*note StackSummary: 780. objects represent a call stack ready for
formatting.

 -- 类: traceback.StackSummary

      -- 方法: classmethod extract (frame_gen, *, limit=None,
               lookup_lines=True, capture_locals=False)

          Construct a *note StackSummary: 780. object from a frame
          generator (such as is returned by *note walk_stack(): 77d. or
          *note walk_tb(): 77e.).

          If `limit' is supplied, only this many frames are taken from
          `frame_gen'.  If `lookup_lines' is ‘False’, the returned *note
          FrameSummary: 781. objects will not have read their lines in
          yet, making the cost of creating the *note StackSummary: 780.
          cheaper (which may be valuable if it may not actually get
          formatted).  If `capture_locals' is ‘True’ the local variables
          in each *note FrameSummary: 781. are captured as object
          representations.

      -- 方法: classmethod from_list (a_list)

          Construct a *note StackSummary: 780. object from a supplied
          list of *note FrameSummary: 781. objects or old-style list of
          tuples.  Each tuple should be a 4-tuple with filename, lineno,
          name, line as the elements.

      -- 方法: format ()

          Returns a list of strings ready for printing.  Each string in
          the resulting list corresponds to a single frame from the
          stack.  Each string ends in a newline; the strings may contain
          internal newlines as well, for those items with source text
          lines.

          For long sequences of the same frame and line, the first few
          repetitions are shown, followed by a summary line stating the
          exact number of further repetitions.

          在 3.6 版更改: Long sequences of repeated frames are now
          abbreviated.


File: python.info,  Node: FrameSummary Objects,  Next: Traceback Examples,  Prev: StackSummary Objects,  Up: traceback --- 打印或检索堆栈回溯

5.29.10.3 ‘FrameSummary’ Objects
................................

3.5 新版功能.

*note FrameSummary: 781. objects represent a single frame in a
traceback.

 -- 类: traceback.FrameSummary (filename, lineno, name,
          lookup_line=True, locals=None, line=None)

     Represent a single frame in the traceback or stack that is being
     formatted or printed.  It may optionally have a stringified version
     of the frames locals included in it.  If `lookup_line' is ‘False’,
     the source code is not looked up until the *note FrameSummary: 781.
     has the ‘line’ attribute accessed (which also happens when casting
     it to a tuple).  ‘line’ may be directly provided, and will prevent
     line lookups happening at all.  `locals' is an optional local
     variable dictionary, and if supplied the variable representations
     are stored in the summary for later display.


File: python.info,  Node: Traceback Examples,  Prev: FrameSummary Objects,  Up: traceback --- 打印或检索堆栈回溯

5.29.10.4 Traceback Examples
............................

This simple example implements a basic read-eval-print loop, similar to
(but less useful than) the standard Python interactive interpreter loop.
For a more complete implementation of the interpreter loop, refer to the
*note code: 1b. module.

     import sys, traceback

     def run_user_code(envdir):
         source = input(">>> ")
         try:
             exec(source, envdir)
         except Exception:
             print("Exception in user code:")
             print("-"*60)
             traceback.print_exc(file=sys.stdout)
             print("-"*60)

     envdir = {}
     while True:
         run_user_code(envdir)

The following example demonstrates the different ways to print and
format the exception and traceback:

     import sys, traceback

     def lumberjack():
         bright_side_of_death()

     def bright_side_of_death():
         return tuple()[0]

     try:
         lumberjack()
     except IndexError:
         exc_type, exc_value, exc_traceback = sys.exc_info()
         print("*** print_tb:")
         traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
         print("*** print_exception:")
         # exc_type below is ignored on 3.5 and later
         traceback.print_exception(exc_type, exc_value, exc_traceback,
                                   limit=2, file=sys.stdout)
         print("*** print_exc:")
         traceback.print_exc(limit=2, file=sys.stdout)
         print("*** format_exc, first and last line:")
         formatted_lines = traceback.format_exc().splitlines()
         print(formatted_lines[0])
         print(formatted_lines[-1])
         print("*** format_exception:")
         # exc_type below is ignored on 3.5 and later
         print(repr(traceback.format_exception(exc_type, exc_value,
                                               exc_traceback)))
         print("*** extract_tb:")
         print(repr(traceback.extract_tb(exc_traceback)))
         print("*** format_tb:")
         print(repr(traceback.format_tb(exc_traceback)))
         print("*** tb_lineno:", exc_traceback.tb_lineno)

The output for the example would look similar to this:

     *** print_tb:
       File "<doctest...>", line 10, in <module>
         lumberjack()
     *** print_exception:
     Traceback (most recent call last):
       File "<doctest...>", line 10, in <module>
         lumberjack()
       File "<doctest...>", line 4, in lumberjack
         bright_side_of_death()
     IndexError: tuple index out of range
     *** print_exc:
     Traceback (most recent call last):
       File "<doctest...>", line 10, in <module>
         lumberjack()
       File "<doctest...>", line 4, in lumberjack
         bright_side_of_death()
     IndexError: tuple index out of range
     *** format_exc, first and last line:
     Traceback (most recent call last):
     IndexError: tuple index out of range
     *** format_exception:
     ['Traceback (most recent call last):\n',
      '  File "<doctest...>", line 10, in <module>\n    lumberjack()\n',
      '  File "<doctest...>", line 4, in lumberjack\n    bright_side_of_death()\n',
      '  File "<doctest...>", line 7, in bright_side_of_death\n    return tuple()[0]\n',
      'IndexError: tuple index out of range\n']
     *** extract_tb:
     [<FrameSummary file <doctest...>, line 10 in <module>>,
      <FrameSummary file <doctest...>, line 4 in lumberjack>,
      <FrameSummary file <doctest...>, line 7 in bright_side_of_death>]
     *** format_tb:
     ['  File "<doctest...>", line 10, in <module>\n    lumberjack()\n',
      '  File "<doctest...>", line 4, in lumberjack\n    bright_side_of_death()\n',
      '  File "<doctest...>", line 7, in bright_side_of_death\n    return tuple()[0]\n']
     *** tb_lineno: 10

The following example shows the different ways to print and format the
stack:

     >>> import traceback
     >>> def another_function():
     ...     lumberstack()
     ...
     >>> def lumberstack():
     ...     traceback.print_stack()
     ...     print(repr(traceback.extract_stack()))
     ...     print(repr(traceback.format_stack()))
     ...
     >>> another_function()
       File "<doctest>", line 10, in <module>
         another_function()
       File "<doctest>", line 3, in another_function
         lumberstack()
       File "<doctest>", line 6, in lumberstack
         traceback.print_stack()
     [('<doctest>', 10, '<module>', 'another_function()'),
      ('<doctest>', 3, 'another_function', 'lumberstack()'),
      ('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
     ['  File "<doctest>", line 10, in <module>\n    another_function()\n',
      '  File "<doctest>", line 3, in another_function\n    lumberstack()\n',
      '  File "<doctest>", line 8, in lumberstack\n    print(repr(traceback.format_stack()))\n']

This last example demonstrates the final few formatting functions:

     >>> import traceback
     >>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
     ...                        ('eggs.py', 42, 'eggs', 'return "bacon"')])
     ['  File "spam.py", line 3, in <module>\n    spam.eggs()\n',
      '  File "eggs.py", line 42, in eggs\n    return "bacon"\n']
     >>> an_error = IndexError('tuple index out of range')
     >>> traceback.format_exception_only(type(an_error), an_error)
     ['IndexError: tuple index out of range\n']


File: python.info,  Node: __future__ --- Future 语句定义,  Next: gc --- 垃圾回收器接口,  Prev: traceback --- 打印或检索堆栈回溯,  Up: Python运行时服务

5.29.11 ‘__future__’ — Future 语句定义
--------------------------------------

`源代码：' Lib/__future__.py(1)

__________________________________________________________________

*note __future__: 0. 是一个真正的模块，这主要有 3 个原因：

   * 避免混淆已有的分析 import 语句并查找 import 的模块的工具。

   * 确保 *note future 语句: 159d. 在 2.1 之前的版本运行时至少能抛出
     runtime 异常（import *note __future__: 0. 会失败，因为 2.1 版本之前
     没有这个模块）。

   * 当引入不兼容的修改时，可以记录其引入的时间以及强制使用的时间。这是
     一种可执行的文档，并且可以通过 import *note __future__: 0. 来做程序
     性的检查。

‘__future__.py’ 中的每一条语句都是以下格式的：

     FeatureName = _Feature(OptionalRelease, MandatoryRelease,
                            CompilerFlag)

通常 `OptionalRelease' 要比 `MandatoryRelease' 小，并且都是和 *note
sys.version_info: b22. 格式一致的 5 元素元组。

     (PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int
      PY_MINOR_VERSION, # the 1; an int
      PY_MICRO_VERSION, # the 0; an int
      PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string
      PY_RELEASE_SERIAL # the 3; an int
     )

`OptionalRelease' 记录了一个特性首次发布时的 Python 版本。

在 `MandatoryRelases' 还没有发布时，`MandatoryRelease' 表示该特性会变成
语言的一部分的预测时间。

其他情况下，`MandatoryRelease' 用来记录这个特性是何时成为语言的一部分的
。从该版本往后，使用该特性将不需要 future 语句，不过很多人还是会加上对应
的 import。

`MandatoryRelease' 也可能是 ‘None’, 表示这个特性已经被撤销。

‘_Feature’ 类的实例有两个对应的方法，‘getOptionalRelease()’ 和
‘getMandatoryRelease()’。

`CompilerFlag' 是一个（位）标记，对于动态编译的代码，需要将这个标记作为
第四个参数传入内建函数 *note compile(): 1b5. 中以开启对应的特性。这个标
记存储在 ‘_Feature’ 类实例的 ‘compiler_flag’ 属性中。

*note __future__: 0. 中不会删除特性的描述。从 Python 2.1 中首次加入以来
，通过这种方式引入了以下特性：

特性                   可选版本          强制加入版本       效果
                                                            
--------------------------------------------------------------------------------------------------------------
                                                            
nested_scopes          2.1.0b1           2.2                PEP 227(2): `静态嵌套作用域'
                                                            
                                                            
generators             2.2.0a1           2.3                PEP 255(3): `简单生成器'
                                                            
                                                            
division               2.2.0a2           3.0                PEP 238(4): `修改除法运算符'
                                                            
                                                            
absolute_import        2.5.0a1           3.0                PEP 328(5): `导入：多行与绝对/相对'
                                                            
                                                            
with_statement         2.5.0a1           2.6                PEP 343(6): * "with" 语句*
                                                            
                                                            
print_function         2.6.0a2           3.0                PEP 3105(7): `print 改为函数'
                                                            
                                                            
unicode_literals       2.6.0a2           3.0                PEP 3112(8): `Python 3000 中的字节字面值'
                                                            
                                                            
generator_stop         3.5.0b1           3.7                PEP 479(9): `在生成器中处理 StopIteration'
                                                            
                                                            
annotations            3.7.0b1           3.10               PEP 563(10): `Postponed evaluation of
                                                            annotations'
                                                            

参见
....

*note future 语句: 159d.

     编译器怎样处理 future import。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/__future__.py

   (2) https://www.python.org/dev/peps/pep-0227

   (3) https://www.python.org/dev/peps/pep-0255

   (4) https://www.python.org/dev/peps/pep-0238

   (5) https://www.python.org/dev/peps/pep-0328

   (6) https://www.python.org/dev/peps/pep-0343

   (7) https://www.python.org/dev/peps/pep-3105

   (8) https://www.python.org/dev/peps/pep-3112

   (9) https://www.python.org/dev/peps/pep-0479

   (10) https://www.python.org/dev/peps/pep-0563


File: python.info,  Node: gc --- 垃圾回收器接口,  Next: inspect --- 检查对象,  Prev: __future__ --- Future 语句定义,  Up: Python运行时服务

5.29.12 ‘gc’ — 垃圾回收器接口
-----------------------------

__________________________________________________________________

此模块提供可选的垃圾回收器的接口，提供的功能包括：关闭收集器、调整收集频
率、设置调试选项。它同时提供对回收器找到但是无法释放的不可达对象的访问。
由于 Python 使用了带有引用计数的回收器，如果你确定你的程序不会产生循环引
用，你可以关闭回收器。可以通过调用 ‘gc.disable()’ 关闭自动垃圾回收。若要
调试一个存在内存泄漏的程序，调用 ‘gc.set_debug(gc.DEBUG_LEAK)’ ；需要注
意的是，它包含 ‘gc.DEBUG_SAVEALL’ ，使得被垃圾回收的对象会被存放在
gc.garbage 中以待检查。

*note gc: 86. 模块提供下列函数：

 -- 函数: gc.enable ()

     启用自动垃圾回收

 -- 函数: gc.disable ()

     停用自动垃圾回收

 -- 函数: gc.isenabled ()

     如果启用了自动回收则返回 ‘True’。

 -- 函数: gc.collect (generation=2)

     若被调用时不包含参数，则启动完全的垃圾回收。可选的参数 `generation'
     可以是一个整数，指明需要回收哪一代（从 0 到 2 ）的垃圾。当参数
     `generation' 无效时，会引发 *note ValueError: 1fc. 异常。返回发现的
     不可达对象的数目。

     每当运行完整收集或最高代 (2) 收集时，为多个内置类型所维护的空闲列表
     会被清空。 由于特定类型特别是 *note float: 188. 的实现，在某些空闲
     列表中并非所有项都会被释放。

 -- 函数: gc.set_debug (flags)

     设置垃圾回收器的调试标识位。调试信息会被写入 ‘sys.stderr’ 。此文档
     末尾列出了各个标志位及其含义；可以使用位操作对多个标志位进行设置以
     控制调试器。

 -- 函数: gc.get_debug ()

     返回当前调试标识位。

 -- 函数: gc.get_objects (generation=None)

     返回一个收集器所跟踪的所有对象的列表，所返回的列表除外。 如果
     `generation' 不为 None，则只返回收集器所跟踪的属于该生成的对象。

     在 3.8 版更改: 新的 `generation' 形参。

     引发一个 *note 审计事件: ea1. ‘gc.get_objects’，附带参数
     ‘generation’。

 -- 函数: gc.get_stats ()

     返回一个包含三个字典对象的列表，每个字典分别包含对应代的从解释器开
     始运行的垃圾回收统计数据。字典的键的数目在将来可能发生改变，目前每
     个字典包含以下内容：

        * ‘collections’ 是该代被回收的次数；

        * ‘collected’ 是该代中被回收的对象总数；

        * ‘uncollectable’ 是在这一代中被发现无法收集的对象总数 （因此被
          移动到 *note garbage: b48. 列表中）。

     3.4 新版功能.

 -- 函数: gc.set_threshold (threshold0[, threshold1[, threshold2]])

     设置垃圾回收阈值（收集频率）。 将 `threshold0' 设为零会禁用回收。

     垃圾回收器把所有对象分类为三代，其依据是对象在多少次垃圾回收后幸存
     。 新建对象会被放在最年轻代（第 ‘0’ 代）。 如果一个对象在一次垃圾回
     收后幸存，它会被移入下一个较老代。 由于第 ‘2’ 代是最老代，这一代的
     对象在一次垃圾回收后仍会保留原样。 为了确定何时要运行，垃圾回收器会
     跟踪自上一次回收后对象分配和释放的数量。 当分配数量减去释放数量的结
     果值大于 `threshold0' 时，垃圾回收就会开始。 初始时只有第 ‘0’ 代会
     被检查。 如果自第 ‘1’ 代被检查后第 ‘0’ 代已被检查超过 `threshold1'
     次，则第 ‘1’ 也会被检查。 对于第三代来说情况还会更复杂，请参阅
     Collecting the oldest generation(1) 来了解详情。

 -- 函数: gc.get_count ()

     将当前回收计数以形为 ‘(count0, count1, count2)’ 的元组返回。

 -- 函数: gc.get_threshold ()

     将当前回收阈值以形为 ‘(threshold0, threshold1, threshold2)’ 的元组
     返回。

 -- 函数: gc.get_referrers (*objs)

     返回直接引用任意一个 `ojbs' 的对象列表。这个函数只定位支持垃圾回收
     的容器；引用了其它对象但不支持垃圾回收的扩展类型不会被找到。

     需要注意的是，已经解除对 `objs' 引用的对象，但仍存在于循环引用中未
     被回收时，仍然会被作为引用者出现在返回的列表当中。若要获取当前正在
     引用 `objs' 的对象，需要调用 *note collect(): 22f. 然后再调用 *note
     get_referrers(): eb4. 。

          警告: 在使用 *note get_referrers(): eb4. 返回的对象时必须要小
          心，因为其中一些对象可能仍在构造中因此处于暂时的无效状态。不要
          把 *note get_referrers(): eb4. 用于调试以外的其它目的。

     引发一个 *note 审计事件: ea1. ‘gc.get_referrers’，附带参数 ‘objs’。

 -- 函数: gc.get_referents (*objs)

     返回被任意一个参数中的对象直接引用的对象的列表。返回的被引用对象是
     被参数中的对象的C语言级别方法（若存在） *note tp_traverse: 36c7. 访
     问到的对象，可能不是所有的实际直接可达对象。只有支持垃圾回收的对象
     支持 *note tp_traverse: 36c7.  方法，并且此方法只会在需要访问涉及循
     环引用的对象时使用。因此，可以有以下例子：一个整数对其中一个参数是
     直接可达的，这个整数有可能出现或不出现在返回的结果列表当中。

     引发一个 *note 审计事件: ea1. ‘gc.get_referents’，附带参数 ‘objs’。

 -- 函数: gc.is_tracked (obj)

     当对象正在被垃圾回收器监控时返回 ‘True’ ，否则返回 ‘False’ 。一般来
     说，原子类的实例不会被监控，而非原子类（如容器、用户自定义的对象）
     会被监控。然而，会有一些特定类型的优化以便减少垃圾回收器在简单实例
     （如只含有原子性的键和值的字典）上的消耗。

          >>> gc.is_tracked(0)
          False
          >>> gc.is_tracked("a")
          False
          >>> gc.is_tracked([])
          True
          >>> gc.is_tracked({})
          False
          >>> gc.is_tracked({"a": 1})
          False
          >>> gc.is_tracked({"a": []})
          True

     3.1 新版功能.

 -- 函数: gc.freeze ()

     冻结 gc 所跟踪的所有对象 —— 将它们移至永久代并忽略所有未来的集合。
     这可以在 POSIX fork() 调用之前使用以便令对写入复制保持友好或加速收
     集。 并且在 POSIX fork() 调用之前的收集也可以释放页面以供未来分配，
     这也可能导致写入时复制，因此建议在主进程中禁用 gc 并在 fork 之前冻
     结，而在子进程中启用 gc。

     3.7 新版功能.

 -- 函数: gc.unfreeze ()

     解冻永久代中的对象，并将它们放回到年老代中。

     3.7 新版功能.

 -- 函数: gc.get_freeze_count ()

     返回永久代中的对象数量。

     3.7 新版功能.

提供以下变量仅供只读访问（你可以修改但不应该重绑定它们）：

 -- 数据: gc.garbage

     一个回收器发现不可达而又无法被释放的对象（不可回收对象）列表。 从
     Python 3.4 开始，该列表在大多数时候都应该是空的，除非使用了含有非
     ‘NULL’ ‘tp_del’ 空位的 C 扩展类型的实例。

     如果设置了 *note DEBUG_SAVEALL: 36c8. ，则所有不可访问对象将被添加
     至该列表而不会被释放。

     在 3.2 版更改: 当 *note interpreter shutdown: 76c. 即解释器关闭时，
     若此列表非空，会产生 *note ResourceWarning: 4d8. ，即资源警告，在默
     认情况下此警告不会被提醒。如果设置了 *note DEBUG_UNCOLLECTABLE:
     b49. ，所有无法被回收的对象会被打印。

     在 3.4 版更改: 根据 PEP 442(2) ，带有 *note __del__(): 927. 方法的
     对象最终不再会进入 *note gc.garbage: b48. 。

 -- 数据: gc.callbacks

     在垃圾回收器开始前和完成后会被调用的一系列回调函数。这些回调函数在
     被调用时使用两个参数： `phase' 和 `info' 。

     `phase' 可为以下两值之一：

          "start": 垃圾回收即将开始。

          "stop": 垃圾回收已结束。

     `info' is a dict providing more information for the callback.  The
     following keys are currently defined:

          "generation"（代） ：正在被回收的最久远的一代。

          "collected"（已回收的 ）: 当*phase* 为 "stop" 时，被成功回收的
          对象的数目。

          "uncollectable"（不可回收的）: 当 `phase' 为 "stop" 时，不能被
          回收并被放入 *note garbage: b48. 的对象的数目。

     应用程序可以把他们自己的回调函数加入此列表。主要的使用场景有：

          统计垃圾回收的数据，如：不同代的回收频率、回收所花费的时间。

          使应用程序可以识别和清理他们自己的在 *note garbage: b48. 中的
          不可回收类型的对象。

     3.3 新版功能.

以下常量被用于 *note set_debug(): 36c2. ：

 -- 数据: gc.DEBUG_STATS

     在回收完成后打印统计信息。当回收频率设置较高时，这些信息会比较有用
     。

 -- 数据: gc.DEBUG_COLLECTABLE

     当发现可回收对象时打印信息。

 -- 数据: gc.DEBUG_UNCOLLECTABLE

     打印找到的不可回收对象的信息（指不能被回收器回收的不可达对象）。这
     些对象会被添加到 ‘garbage’ 列表中。

     在 3.2 版更改: 当 *note interpreter shutdown: 76c. 时，即解释器关闭
     时，若 *note garbage: b48. 列表中存在对象，这些对象也会被打印输出。

 -- 数据: gc.DEBUG_SAVEALL

     设置后，所有回收器找到的不可达对象会被添加进 `garbage' 而不是直接被
     释放。这在调试一个内存泄漏的程序时会很有用。

 -- 数据: gc.DEBUG_LEAK

     调试内存泄漏的程序时，使回收器打印信息的调试标识位。（等价于
     ‘DEBUG_COLLECTABLE | DEBUG_UNCOLLECTABLE | DEBUG_SAVEALL’ ）。

   ---------- Footnotes ----------

   (1) 
https://devguide.python.org/garbage_collector/#collecting-the-oldest-generation

   (2) https://www.python.org/dev/peps/pep-0442


File: python.info,  Node: inspect --- 检查对象,  Next: site —— 站点专属的配置钩子,  Prev: gc --- 垃圾回收器接口,  Up: Python运行时服务

5.29.13 ‘inspect’ — 检查对象
----------------------------

`源代码:' Lib/inspect.py(1)

__________________________________________________________________

*note inspect: a1. 模块提供了一些有用的函数帮助获取对象的信息，例如模块
、类、方法、函数、回溯、帧对象以及代码对象。例如它可以帮助你检查类的内容
，获取某个方法的源代码，取得并格式化某个函数的参数列表，或者获取你需要显
示的回溯的详细信息。

该模块提供了4种主要的功能：类型检查、获取源代码、检查类与函数、检查解释
器的调用堆栈。

* Menu:

* 类型和成员::
* Retrieving source code::
* Introspecting callables with the Signature object::
* 类与函数: 类与函数<2>.
* The interpreter stack::
* Fetching attributes statically::
* Current State of Generators and Coroutines::
* Code Objects Bit Flags::
* 命令行界面: 命令行界面<8>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/inspect.py


File: python.info,  Node: 类型和成员,  Next: Retrieving source code,  Up: inspect --- 检查对象

5.29.13.1 类型和成员
....................

*note getmembers(): 36d0. 函数获取对象的成员，例如类或模块。函数名以
"is"开始的函数主要作为 *note getmembers(): 36d0. 的第2个参数使用。它们也
可用于判定某对象是否有如下的特殊属性:

类型            属性                    描述
                                        
------------------------------------------------------------------------
                                        
module          __doc__                 文档字符串
                                        
                                        
                __file__                文件名(内置模块没有文件名)
                                        
                                        
class – 类      __doc__                 文档字符串
                                        
                                        
                __name__                类定义时所使用的名称
                                        
                                        
                __qualname__            qualified name – 限定名称
                                        
                                        
                __module__              该类型被定义时所在的模块的名
                                        称
                                        
                                        
method 方法     __doc__                 文档字符串
                                        
                                        
                __name__                该方法定义时所使用的名称
                                        
                                        
                __qualname__            qualified name – 限定名称
                                        
                                        
                __func__                实现该方法的函数对象
                                        
                                        
                __self__                该方法被绑定的实例，若没有绑
                                        定则为 ‘None’
                                        
                                        
                __module__              定义此方法的模块的名称
                                        
                                        
function – 函   __doc__                 文档字符串
数                                      

                __name__                用于定义此函数的名称
                                        
                                        
                __qualname__            qualified name – 限定名称
                                        
                                        
                __code__                包含已编译函数的代码对象
                                        *note bytecode: 61d.
                                        
                                        
                __defaults__            所有位置或关键字参数的默认值
                                        的元组
                                        
                                        
                __kwdefaults__          mapping of any default values
                                        for keyword-only parameters
                                        
                                        
                __globals__             global namespace in which
                                        this function was defined
                                        
                                        
                __annotations__         mapping of parameters names
                                        to annotations; ‘"return"’
                                        key is reserved for return
                                        annotations.
                                        
                                        
                __module__              name of module in which this
                                        function was defined
                                        
                                        
回溯            tb_frame                此级别的框架对象
                                        
                                        
                tb_lasti                index of last attempted
                                        instruction in bytecode
                                        
                                        
                tb_lineno               current line number in Python
                                        source code
                                        
                                        
                tb_next                 next inner traceback object
                                        (called by this level)
                                        
                                        
框架            f_back                  next outer frame object (this
                                        frame’s caller)
                                        
                                        
                f_builtins              builtins namespace seen by
                                        this frame
                                        
                                        
                f_code                  code object being executed in
                                        this frame
                                        
                                        
                f_globals               global namespace seen by this
                                        frame
                                        
                                        
                f_lasti                 index of last attempted
                                        instruction in bytecode
                                        
                                        
                f_lineno                current line number in Python
                                        source code
                                        
                                        
                f_locals                local namespace seen by this
                                        frame
                                        
                                        
                f_trace                 tracing function for this
                                        frame, or ‘None’
                                        
                                        
code            co_argcount             number of arguments (not
                                        including keyword only
                                        arguments, * or ** args)
                                        
                                        
                co_code                 原始编译字节码的字符串
                                        
                                        
                co_cellvars             单元变量名称的元组(通过包含作
                                        用域引用)
                                        
                                        
                co_consts               字节码中使用的常量元组
                                        
                                        
                co_filename             创建此代码对象的文件的名称
                                        
                                        
                co_firstlineno          number of first line in
                                        Python source code
                                        
                                        
                co_flags                bitmap of ‘CO_*’ flags, read
                                        more *note here: 36d1.
                                        
                                        
                co_lnotab               编码的行号到字节码索引的映射
                                        
                                        
                co_freevars             tuple of names of free
                                        variables (referenced via a
                                        function’s closure)
                                        
                                        
                co_posonlyargcount      number of positional only
                                        arguments
                                        
                                        
                co_kwonlyargcount       number of keyword only
                                        arguments (not including **
                                        arg)
                                        
                                        
                co_name                 定义此代码对象的名称
                                        
                                        
                co_names                局部变量名称的元组
                                        
                                        
                co_nlocals              局部变量的数量
                                        
                                        
                co_stacksize            需要虚拟机堆栈空间
                                        
                                        
                co_varnames             参数名和局部变量的元组
                                        
                                        
generator – 生  __name__                名称
成器                                    

                __qualname__            qualified name – 限定名称
                                        
                                        
                gi_frame                框架
                                        
                                        
                gi_running              生成器在运行吗？
                                        
                                        
                gi_code                 code
                                        
                                        
                gi_yieldfrom            object being iterated by
                                        ‘yield from’, or ‘None’
                                        
                                        
coroutine – 协  __name__                名称
程                                      

                __qualname__            qualified name – 限定名称
                                        
                                        
                cr_await                object being awaited on, or
                                        ‘None’
                                        
                                        
                cr_frame                框架
                                        
                                        
                cr_running              is the coroutine running?
                                        
                                        
                cr_code                 code
                                        
                                        
                cr_origin               where coroutine was created,
                                        or ‘None’.  See
                                        *note sys.set_coroutine_origin_tracking_depth(): 3fb.
                                        
                                        
builtin         __doc__                 文档字符串
                                        
                                        
                __name__                此函数或方法的原始名称
                                        
                                        
                __qualname__            qualified name – 限定名称
                                        
                                        
                __self__                instance to which a method is
                                        bound, or ‘None’
                                        

在 3.5 版更改: Add ‘__qualname__’ and ‘gi_yieldfrom’ attributes to
generators.

The ‘__name__’ attribute of generators is now set from the function
name, instead of the code name, and it can now be modified.

在 3.7 版更改: Add ‘cr_origin’ attribute to coroutines.

 -- 函数: inspect.getmembers (object[, predicate])

     Return all the members of an object in a list of ‘(name, value)’
     pairs sorted by name.  If the optional `predicate' argument—which
     will be called with the ‘value’ object of each member—is supplied,
     only members for which the predicate returns a true value are
     included.

          注解: *note getmembers(): 36d0. will only return class
          attributes defined in the metaclass when the argument is a
          class and those attributes have been listed in the metaclass’
          custom *note __dir__(): 324.

 -- 函数: inspect.getmodulename (path)

     Return the name of the module named by the file `path', without
     including the names of enclosing packages.  The file extension is
     checked against all of the entries in *note
     importlib.machinery.all_suffixes(): 36d2.  If it matches, the final
     path component is returned with the extension removed.  Otherwise,
     ‘None’ is returned.

     Note that this function `only' returns a meaningful name for actual
     Python modules - paths that potentially refer to Python packages
     will still return ‘None’.

     在 3.3 版更改: The function is based directly on *note importlib:
     9b.

 -- 函数: inspect.ismodule (object)

     Return ‘True’ if the object is a module.

 -- 函数: inspect.isclass (object)

     Return ‘True’ if the object is a class, whether built-in or created
     in Python code.

 -- 函数: inspect.ismethod (object)

     Return ‘True’ if the object is a bound method written in Python.

 -- 函数: inspect.isfunction (object)

     Return ‘True’ if the object is a Python function, which includes
     functions created by a *note lambda: 36d7. expression.

 -- 函数: inspect.isgeneratorfunction (object)

     Return ‘True’ if the object is a Python generator function.

     在 3.8 版更改: Functions wrapped in *note functools.partial(): 7d1.
     now return ‘True’ if the wrapped function is a Python generator
     function.

 -- 函数: inspect.isgenerator (object)

     Return ‘True’ if the object is a generator.

 -- 函数: inspect.iscoroutinefunction (object)

     Return ‘True’ if the object is a *note coroutine function: 648. (a
     function defined with an *note async def: 285. syntax).

     3.5 新版功能.

     在 3.8 版更改: Functions wrapped in *note functools.partial(): 7d1.
     now return ‘True’ if the wrapped function is a *note coroutine
     function: 648.

 -- 函数: inspect.iscoroutine (object)

     Return ‘True’ if the object is a *note coroutine: 1a7. created by
     an *note async def: 285. function.

     3.5 新版功能.

 -- 函数: inspect.isawaitable (object)

     Return ‘True’ if the object can be used in *note await: 1a4.
     expression.

     Can also be used to distinguish generator-based coroutines from
     regular generators:

          def gen():
              yield
          @types.coroutine
          def gen_coro():
              yield

          assert not isawaitable(gen())
          assert isawaitable(gen_coro())

     3.5 新版功能.

 -- 函数: inspect.isasyncgenfunction (object)

     Return ‘True’ if the object is an *note asynchronous generator:
     1513. function, for example:

          >>> async def agen():
          ...     yield 1
          ...
          >>> inspect.isasyncgenfunction(agen)
          True

     3.6 新版功能.

     在 3.8 版更改: Functions wrapped in *note functools.partial(): 7d1.
     now return ‘True’ if the wrapped function is a *note asynchronous
     generator: 1513. function.

 -- 函数: inspect.isasyncgen (object)

     Return ‘True’ if the object is an *note asynchronous generator
     iterator: 363d. created by an *note asynchronous generator: 1513.
     function.

     3.6 新版功能.

 -- 函数: inspect.istraceback (object)

     Return ‘True’ if the object is a traceback.

 -- 函数: inspect.isframe (object)

     Return ‘True’ if the object is a frame.

 -- 函数: inspect.iscode (object)

     Return ‘True’ if the object is a code.

 -- 函数: inspect.isbuiltin (object)

     Return ‘True’ if the object is a built-in function or a bound
     built-in method.

 -- 函数: inspect.isroutine (object)

     Return ‘True’ if the object is a user-defined or built-in function
     or method.

 -- 函数: inspect.isabstract (object)

     Return ‘True’ if the object is an abstract base class.

 -- 函数: inspect.ismethoddescriptor (object)

     Return ‘True’ if the object is a method descriptor, but not if
     *note ismethod(): 36d5, *note isclass(): 36d4, *note isfunction():
     36d6. or *note isbuiltin(): 36dd. are true.

     This, for example, is true of ‘int.__add__’.  An object passing
     this test has a *note __get__(): 144b. method but not a *note
     __set__(): 144f. method, but beyond that the set of attributes
     varies.  A *note __name__: c6f. attribute is usually sensible, and
     ‘__doc__’ often is.

     Methods implemented via descriptors that also pass one of the other
     tests return ‘False’ from the *note ismethoddescriptor(): 36e0.
     test, simply because the other tests promise more – you can, e.g.,
     count on having the ‘__func__’ attribute (etc) when an object
     passes *note ismethod(): 36d5.

 -- 函数: inspect.isdatadescriptor (object)

     Return ‘True’ if the object is a data descriptor.

     Data descriptors have a *note __set__: 144f. or a *note __delete__:
     1450. method.  Examples are properties (defined in Python),
     getsets, and members.  The latter two are defined in C and there
     are more specific tests available for those types, which is robust
     across Python implementations.  Typically, data descriptors will
     also have *note __name__: c6f. and ‘__doc__’ attributes
     (properties, getsets, and members have both of these attributes),
     but this is not guaranteed.

 -- 函数: inspect.isgetsetdescriptor (object)

     Return ‘True’ if the object is a getset descriptor.

     `CPython implementation detail:' getsets are attributes defined in
     extension modules via *note PyGetSetDef: 42f. structures.  For
     Python implementations without such types, this method will always
     return ‘False’.

 -- 函数: inspect.ismemberdescriptor (object)

     Return ‘True’ if the object is a member descriptor.

     `CPython implementation detail:' Member descriptors are attributes
     defined in extension modules via *note PyMemberDef: 42e.
     structures.  For Python implementations without such types, this
     method will always return ‘False’.


File: python.info,  Node: Retrieving source code,  Next: Introspecting callables with the Signature object,  Prev: 类型和成员,  Up: inspect --- 检查对象

5.29.13.2 Retrieving source code
................................

 -- 函数: inspect.getdoc (object)

     Get the documentation string for an object, cleaned up with *note
     cleandoc(): 36e6.  If the documentation string for an object is not
     provided and the object is a class, a method, a property or a
     descriptor, retrieve the documentation string from the inheritance
     hierarchy.

     在 3.5 版更改: Documentation strings are now inherited if not
     overridden.

 -- 函数: inspect.getcomments (object)

     Return in a single string any lines of comments immediately
     preceding the object’s source code (for a class, function, or
     method), or at the top of the Python source file (if the object is
     a module).  If the object’s source code is unavailable, return
     ‘None’.  This could happen if the object has been defined in C or
     the interactive shell.

 -- 函数: inspect.getfile (object)

     Return the name of the (text or binary) file in which an object was
     defined.  This will fail with a *note TypeError: 193. if the object
     is a built-in module, class, or function.

 -- 函数: inspect.getmodule (object)

     Try to guess which module an object was defined in.

 -- 函数: inspect.getsourcefile (object)

     Return the name of the Python source file in which an object was
     defined.  This will fail with a *note TypeError: 193. if the object
     is a built-in module, class, or function.

 -- 函数: inspect.getsourcelines (object)

     Return a list of source lines and starting line number for an
     object.  The argument may be a module, class, method, function,
     traceback, frame, or code object.  The source code is returned as a
     list of the lines corresponding to the object and the line number
     indicates where in the original source file the first line of code
     was found.  An *note OSError: 1d4. is raised if the source code
     cannot be retrieved.

     在 3.3 版更改: *note OSError: 1d4. is raised instead of *note
     IOError: 99a, now an alias of the former.

 -- 函数: inspect.getsource (object)

     Return the text of the source code for an object.  The argument may
     be a module, class, method, function, traceback, frame, or code
     object.  The source code is returned as a single string.  An *note
     OSError: 1d4. is raised if the source code cannot be retrieved.

     在 3.3 版更改: *note OSError: 1d4. is raised instead of *note
     IOError: 99a, now an alias of the former.

 -- 函数: inspect.cleandoc (doc)

     Clean up indentation from docstrings that are indented to line up
     with blocks of code.

     All leading whitespace is removed from the first line.  Any leading
     whitespace that can be uniformly removed from the second line
     onwards is removed.  Empty lines at the beginning and end are
     subsequently removed.  Also, all tabs are expanded to spaces.


File: python.info,  Node: Introspecting callables with the Signature object,  Next: 类与函数<2>,  Prev: Retrieving source code,  Up: inspect --- 检查对象

5.29.13.3 Introspecting callables with the Signature object
...........................................................

3.3 新版功能.

The Signature object represents the call signature of a callable object
and its return annotation.  To retrieve a Signature object, use the
*note signature(): 564. function.

 -- 函数: inspect.signature (callable, *, follow_wrapped=True)

     Return a *note Signature: 6fc. object for the given ‘callable’:

          >>> from inspect import signature
          >>> def foo(a, *, b:int, **kwargs):
          ...     pass

          >>> sig = signature(foo)

          >>> str(sig)
          '(a, *, b:int, **kwargs)'

          >>> str(sig.parameters['b'])
          'b:int'

          >>> sig.parameters['b'].annotation
          <class 'int'>

     Accepts a wide range of Python callables, from plain functions and
     classes to *note functools.partial(): 7d1. objects.

     Raises *note ValueError: 1fc. if no signature can be provided, and
     *note TypeError: 193. if that type of object is not supported.

     A slash(/) in the signature of a function denotes that the
     parameters prior to it are positional-only.  For more info, see
     *note the FAQ entry on positional-only parameters: 1603.

     3.5 新版功能: ‘follow_wrapped’ parameter.  Pass ‘False’ to get a
     signature of ‘callable’ specifically (‘callable.__wrapped__’ will
     not be used to unwrap decorated callables.)

          注解: Some callables may not be introspectable in certain
          implementations of Python.  For example, in CPython, some
          built-in functions defined in C provide no metadata about
          their arguments.

 -- 类: inspect.Signature (parameters=None, *,
          return_annotation=Signature.empty)

     A Signature object represents the call signature of a function and
     its return annotation.  For each parameter accepted by the function
     it stores a *note Parameter: 6fd. object in its *note parameters:
     36eb. collection.

     The optional `parameters' argument is a sequence of *note
     Parameter: 6fd. objects, which is validated to check that there are
     no parameters with duplicate names, and that the parameters are in
     the right order, i.e.  positional-only first, then
     positional-or-keyword, and that parameters with defaults follow
     parameters without defaults.

     The optional `return_annotation' argument, can be an arbitrary
     Python object, is the "return" annotation of the callable.

     Signature objects are `immutable'.  Use *note Signature.replace():
     36ec. to make a modified copy.

     在 3.5 版更改: Signature objects are picklable and hashable.

      -- 属性: empty

          A special class-level marker to specify absence of a return
          annotation.

      -- 属性: parameters

          An ordered mapping of parameters’ names to the corresponding
          *note Parameter: 6fd. objects.  Parameters appear in strict
          definition order, including keyword-only parameters.

          在 3.7 版更改: Python only explicitly guaranteed that it
          preserved the declaration order of keyword-only parameters as
          of version 3.7, although in practice this order had always
          been preserved in Python 3.

      -- 属性: return_annotation

          The "return" annotation for the callable.  If the callable has
          no "return" annotation, this attribute is set to *note
          Signature.empty: 36ed.

      -- 方法: bind (*args, **kwargs)

          Create a mapping from positional and keyword arguments to
          parameters.  Returns *note BoundArguments: 9b0. if ‘*args’ and
          ‘**kwargs’ match the signature, or raises a *note TypeError:
          193.

      -- 方法: bind_partial (*args, **kwargs)

          Works the same way as *note Signature.bind(): 36ef, but allows
          the omission of some required arguments (mimics *note
          functools.partial(): 7d1. behavior.)  Returns *note
          BoundArguments: 9b0, or raises a *note TypeError: 193. if the
          passed arguments do not match the signature.

      -- 方法: replace (*[, parameters][, return_annotation])

          Create a new Signature instance based on the instance replace
          was invoked on.  It is possible to pass different ‘parameters’
          and/or ‘return_annotation’ to override the corresponding
          properties of the base signature.  To remove return_annotation
          from the copied Signature, pass in *note Signature.empty:
          36ed.

               >>> def test(a, b):
               ...     pass
               >>> sig = signature(test)
               >>> new_sig = sig.replace(return_annotation="new return anno")
               >>> str(new_sig)
               "(a, b) -> 'new return anno'"

      -- 方法: classmethod from_callable (obj, *, follow_wrapped=True)

          Return a *note Signature: 6fc. (or its subclass) object for a
          given callable ‘obj’.  Pass ‘follow_wrapped=False’ to get a
          signature of ‘obj’ without unwrapping its ‘__wrapped__’ chain.

          This method simplifies subclassing of *note Signature: 6fc.:

               class MySignature(Signature):
                   pass
               sig = MySignature.from_callable(min)
               assert isinstance(sig, MySignature)

          3.5 新版功能.

 -- 类: inspect.Parameter (name, kind, *, default=Parameter.empty,
          annotation=Parameter.empty)

     Parameter objects are `immutable'.  Instead of modifying a
     Parameter object, you can use *note Parameter.replace(): 36f1. to
     create a modified copy.

     在 3.5 版更改: Parameter objects are picklable and hashable.

      -- 属性: empty

          A special class-level marker to specify absence of default
          values and annotations.

      -- 属性: name

          The name of the parameter as a string.  The name must be a
          valid Python identifier.

          `CPython implementation detail:' CPython generates implicit
          parameter names of the form ‘.0’ on the code objects used to
          implement comprehensions and generator expressions.

          在 3.6 版更改: These parameter names are exposed by this
          module as names like ‘implicit0’.

      -- 属性: default

          The default value for the parameter.  If the parameter has no
          default value, this attribute is set to *note Parameter.empty:
          36f2.

      -- 属性: annotation

          The annotation for the parameter.  If the parameter has no
          annotation, this attribute is set to *note Parameter.empty:
          36f2.

      -- 属性: kind

          Describes how argument values are bound to the parameter.
          Possible values (accessible via *note Parameter: 6fd, like
          ‘Parameter.KEYWORD_ONLY’):

          名称                         含义
                                       
          --------------------------------------------------------------------------------
                                       
          `POSITIONAL_ONLY'            Value must be supplied as a positional argument.
                                       Positional only parameters are those which
                                       appear before a ‘/’ entry (if present) in a
                                       Python function definition.
                                       
                                       
          `POSITIONAL_OR_KEYWORD'      Value may be supplied as either a keyword or
                                       positional argument (this is the standard
                                       binding behaviour for functions implemented in
                                       Python.)
                                       
                                       
          `VAR_POSITIONAL'             A tuple of positional arguments that aren’t
                                       bound to any other parameter.  This corresponds
                                       to a ‘*args’ parameter in a Python function
                                       definition.
                                       
                                       
          `KEYWORD_ONLY'               Value must be supplied as a keyword argument.
                                       Keyword only parameters are those which appear
                                       after a ‘*’ or ‘*args’ entry in a Python
                                       function definition.
                                       
                                       
          `VAR_KEYWORD'                A dict of keyword arguments that aren’t bound to
                                       any other parameter.  This corresponds to a
                                       ‘**kwargs’ parameter in a Python function
                                       definition.
                                       

          Example: print all keyword-only arguments without default
          values:

               >>> def foo(a, b, *, c, d=10):
               ...     pass

               >>> sig = signature(foo)
               >>> for param in sig.parameters.values():
               ...     if (param.kind == param.KEYWORD_ONLY and
               ...                        param.default is param.empty):
               ...         print('Parameter:', param)
               Parameter: c

      -- 属性: kind.description

          Describes a enum value of Parameter.kind.

          3.8 新版功能.

          Example: print all descriptions of arguments:

               >>> def foo(a, b, *, c, d=10):
               ...     pass

               >>> sig = signature(foo)
               >>> for param in sig.parameters.values():
               ...     print(param.kind.description)
               positional or keyword
               positional or keyword
               keyword-only
               keyword-only

      -- 方法: replace (*[, name][, kind][, default][, annotation])

               Create a new Parameter instance based on the instance
               replaced was invoked on.  To override a *note Parameter:
               6fd. attribute, pass the corresponding argument.  To
               remove a default value or/and an annotation from a
               Parameter, pass *note Parameter.empty: 36f2.

                    >>> from inspect import Parameter
                    >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
                    >>> str(param)
                    'foo=42'

                    >>> str(param.replace()) # Will create a shallow copy of 'param'
                    'foo=42'

                    >>> str(param.replace(default=Parameter.empty, annotation='spam'))
                    "foo:'spam'"

          在 3.4 版更改: In Python 3.3 Parameter objects were allowed to
          have ‘name’ set to ‘None’ if their ‘kind’ was set to
          ‘POSITIONAL_ONLY’.  This is no longer permitted.

 -- 类: inspect.BoundArguments

     Result of a *note Signature.bind(): 36ef. or *note
     Signature.bind_partial(): 36f0. call.  Holds the mapping of
     arguments to the function’s parameters.

      -- 属性: arguments

          An ordered, mutable mapping (*note collections.OrderedDict:
          1ba.) of parameters’ names to arguments’ values.  Contains
          only explicitly bound arguments.  Changes in *note arguments:
          36f8. will reflect in *note args: 36f9. and *note kwargs:
          36fa.

          Should be used in conjunction with *note Signature.parameters:
          36eb. for any argument processing purposes.

               注解: Arguments for which *note Signature.bind(): 36ef.
               or *note Signature.bind_partial(): 36f0. relied on a
               default value are skipped.  However, if needed, use *note
               BoundArguments.apply_defaults(): 6fe. to add them.

      -- 属性: args

          A tuple of positional arguments values.  Dynamically computed
          from the *note arguments: 36f8. attribute.

      -- 属性: kwargs

          A dict of keyword arguments values.  Dynamically computed from
          the *note arguments: 36f8. attribute.

      -- 属性: signature

          A reference to the parent *note Signature: 6fc. object.

      -- 方法: apply_defaults ()

          Set default values for missing arguments.

          For variable-positional arguments (‘*args’) the default is an
          empty tuple.

          For variable-keyword arguments (‘**kwargs’) the default is an
          empty dict.

               >>> def foo(a, b='ham', *args): pass
               >>> ba = inspect.signature(foo).bind('spam')
               >>> ba.apply_defaults()
               >>> ba.arguments
               OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])

          3.5 新版功能.

     The *note args: 36f9. and *note kwargs: 36fa. properties can be
     used to invoke functions:

          def test(a, *, b):
              ...

          sig = signature(test)
          ba = sig.bind(10, b=20)
          test(*ba.args, **ba.kwargs)

参见
....

PEP 362(1) - Function Signature Object.

     The detailed specification, implementation details and examples.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0362


File: python.info,  Node: 类与函数<2>,  Next: The interpreter stack,  Prev: Introspecting callables with the Signature object,  Up: inspect --- 检查对象

5.29.13.4 类与函数
..................

 -- 函数: inspect.getclasstree (classes, unique=False)

     Arrange the given list of classes into a hierarchy of nested lists.
     Where a nested list appears, it contains classes derived from the
     class whose entry immediately precedes the list.  Each entry is a
     2-tuple containing a class and a tuple of its base classes.  If the
     `unique' argument is true, exactly one entry appears in the
     returned structure for each class in the given list.  Otherwise,
     classes using multiple inheritance and their descendants will
     appear multiple times.

 -- 函数: inspect.getargspec (func)

     Get the names and default values of a Python function’s parameters.
     A *note named tuple: aab. ‘ArgSpec(args, varargs, keywords,
     defaults)’ is returned.  `args' is a list of the parameter names.
     `varargs' and `keywords' are the names of the ‘*’ and ‘**’
     parameters or ‘None’.  `defaults' is a tuple of default argument
     values or ‘None’ if there are no default arguments; if this tuple
     has `n' elements, they correspond to the last `n' elements listed
     in `args'.

     3.0 版后已移除: Use *note getfullargspec(): 566. for an updated API
     that is usually a drop-in replacement, but also correctly handles
     function annotations and keyword-only parameters.

     Alternatively, use *note signature(): 564. and *note Signature
     Object: 36e9, which provide a more structured introspection API for
     callables.

 -- 函数: inspect.getfullargspec (func)

     Get the names and default values of a Python function’s parameters.
     A *note named tuple: aab. is returned:

     ‘FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
     kwonlydefaults, annotations)’

     `args' is a list of the positional parameter names.  `varargs' is
     the name of the ‘*’ parameter or ‘None’ if arbitrary positional
     arguments are not accepted.  `varkw' is the name of the ‘**’
     parameter or ‘None’ if arbitrary keyword arguments are not
     accepted.  `defaults' is an `n'-tuple of default argument values
     corresponding to the last `n' positional parameters, or ‘None’ if
     there are no such defaults defined.  `kwonlyargs' is a list of
     keyword-only parameter names in declaration order.
     `kwonlydefaults' is a dictionary mapping parameter names from
     `kwonlyargs' to the default values used if no argument is supplied.
     `annotations' is a dictionary mapping parameter names to
     annotations.  The special key ‘"return"’ is used to report the
     function return value annotation (if any).

     Note that *note signature(): 564. and *note Signature Object: 36e9.
     provide the recommended API for callable introspection, and support
     additional behaviours (like positional-only arguments) that are
     sometimes encountered in extension module APIs.  This function is
     retained primarily for use in code that needs to maintain
     compatibility with the Python 2 ‘inspect’ module API.

     在 3.4 版更改: This function is now based on *note signature():
     564, but still ignores ‘__wrapped__’ attributes and includes the
     already bound first parameter in the signature output for bound
     methods.

     在 3.6 版更改: This method was previously documented as deprecated
     in favour of *note signature(): 564. in Python 3.5, but that
     decision has been reversed in order to restore a clearly supported
     standard interface for single-source Python 2/3 code migrating away
     from the legacy *note getargspec(): 565. API.

     在 3.7 版更改: Python only explicitly guaranteed that it preserved
     the declaration order of keyword-only parameters as of version 3.7,
     although in practice this order had always been preserved in Python
     3.

 -- 函数: inspect.getargvalues (frame)

     Get information about arguments passed into a particular frame.  A
     *note named tuple: aab. ‘ArgInfo(args, varargs, keywords, locals)’
     is returned.  `args' is a list of the argument names.  `varargs'
     and `keywords' are the names of the ‘*’ and ‘**’ arguments or
     ‘None’.  `locals' is the locals dictionary of the given frame.

          注解: This function was inadvertently marked as deprecated in
          Python 3.5.

 -- 函数: inspect.formatargspec (args[, varargs, varkw, defaults,
          kwonlyargs, kwonlydefaults, annotations[, formatarg,
          formatvarargs, formatvarkw, formatvalue, formatreturns,
          formatannotations]])

     Format a pretty argument spec from the values returned by *note
     getfullargspec(): 566.

     The first seven arguments are (‘args’, ‘varargs’, ‘varkw’,
     ‘defaults’, ‘kwonlyargs’, ‘kwonlydefaults’, ‘annotations’).

     The other six arguments are functions that are called to turn
     argument names, ‘*’ argument name, ‘**’ argument name, default
     values, return annotation and individual annotations into strings,
     respectively.

     例如:

          >>> from inspect import formatargspec, getfullargspec
          >>> def f(a: int, b: float):
          ...     pass
          ...
          >>> formatargspec(*getfullargspec(f))
          '(a: int, b: float)'

     3.5 版后已移除: Use *note signature(): 564. and *note Signature
     Object: 36e9, which provide a better introspecting API for
     callables.

 -- 函数: inspect.formatargvalues (args[, varargs, varkw, locals,
          formatarg, formatvarargs, formatvarkw, formatvalue])

     Format a pretty argument spec from the four values returned by
     *note getargvalues(): 7c1.  The format* arguments are the
     corresponding optional formatting functions that are called to turn
     names and values into strings.

          注解: This function was inadvertently marked as deprecated in
          Python 3.5.

 -- 函数: inspect.getmro (cls)

     Return a tuple of class cls’s base classes, including cls, in
     method resolution order.  No class appears more than once in this
     tuple.  Note that the method resolution order depends on cls’s
     type.  Unless a very peculiar user-defined metatype is in use, cls
     will be the first element of the tuple.

 -- 函数: inspect.getcallargs (func, /, *args, **kwds)

     Bind the `args' and `kwds' to the argument names of the Python
     function or method `func', as if it was called with them.  For
     bound methods, bind also the first argument (typically named
     ‘self’) to the associated instance.  A dict is returned, mapping
     the argument names (including the names of the ‘*’ and ‘**’
     arguments, if any) to their values from `args' and `kwds'.  In case
     of invoking `func' incorrectly, i.e.  whenever ‘func(*args,
     **kwds)’ would raise an exception because of incompatible
     signature, an exception of the same type and the same or similar
     message is raised.  For example:

          >>> from inspect import getcallargs
          >>> def f(a, b=1, *pos, **named):
          ...     pass
          >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
          True
          >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
          True
          >>> getcallargs(f)
          Traceback (most recent call last):
          ...
          TypeError: f() missing 1 required positional argument: 'a'

     3.2 新版功能.

     3.5 版后已移除: Use *note Signature.bind(): 36ef. and *note
     Signature.bind_partial(): 36f0. instead.

 -- 函数: inspect.getclosurevars (func)

     Get the mapping of external name references in a Python function or
     method `func' to their current values.  A *note named tuple: aab.
     ‘ClosureVars(nonlocals, globals, builtins, unbound)’ is returned.
     `nonlocals' maps referenced names to lexical closure variables,
     `globals' to the function’s module globals and `builtins' to the
     builtins visible from the function body.  `unbound' is the set of
     names referenced in the function that could not be resolved at all
     given the current module globals and builtins.

     *note TypeError: 193. is raised if `func' is not a Python function
     or method.

     3.3 新版功能.

 -- 函数: inspect.unwrap (func, *, stop=None)

     Get the object wrapped by `func'.  It follows the chain of
     ‘__wrapped__’ attributes returning the last object in the chain.

     `stop' is an optional callback accepting an object in the wrapper
     chain as its sole argument that allows the unwrapping to be
     terminated early if the callback returns a true value.  If the
     callback never returns a true value, the last object in the chain
     is returned as usual.  For example, *note signature(): 564. uses
     this to stop unwrapping if any object in the chain has a
     ‘__signature__’ attribute defined.

     *note ValueError: 1fc. is raised if a cycle is encountered.

     3.4 新版功能.


File: python.info,  Node: The interpreter stack,  Next: Fetching attributes statically,  Prev: 类与函数<2>,  Up: inspect --- 检查对象

5.29.13.5 The interpreter stack
...............................

When the following functions return "frame records," each record is a
*note named tuple: aab. ‘FrameInfo(frame, filename, lineno, function,
code_context, index)’.  The tuple contains the frame object, the
filename, the line number of the current line, the function name, a list
of lines of context from the source code, and the index of the current
line within that list.

在 3.5 版更改: Return a named tuple instead of a tuple.

     注解: Keeping references to frame objects, as found in the first
     element of the frame records these functions return, can cause your
     program to create reference cycles.  Once a reference cycle has
     been created, the lifespan of all objects which can be accessed
     from the objects which form the cycle can become much longer even
     if Python’s optional cycle detector is enabled.  If such cycles
     must be created, it is important to ensure they are explicitly
     broken to avoid the delayed destruction of objects and increased
     memory consumption which occurs.

     Though the cycle detector will catch these, destruction of the
     frames (and local variables) can be made deterministic by removing
     the cycle in a *note finally: 183. clause.  This is also important
     if the cycle detector was disabled when Python was compiled or
     using *note gc.disable(): 36c0.  For example:

          def handle_stackframe_without_leak():
              frame = inspect.currentframe()
              try:
                  # do something with the frame
              finally:
                  del frame

     If you want to keep the frame around (for example to print a
     traceback later), you can also break reference cycles by using the
     *note frame.clear(): 814. method.

The optional `context' argument supported by most of these functions
specifies the number of lines of context to return, which are centered
around the current line.

 -- 函数: inspect.getframeinfo (frame, context=1)

     Get information about a frame or traceback object.  A *note named
     tuple: aab. ‘Traceback(filename, lineno, function, code_context,
     index)’ is returned.

 -- 函数: inspect.getouterframes (frame, context=1)

     Get a list of frame records for a frame and all outer frames.
     These frames represent the calls that lead to the creation of
     `frame'.  The first entry in the returned list represents `frame';
     the last entry represents the outermost call on `frame'’s stack.

     在 3.5 版更改: A list of *note named tuples: aab. ‘FrameInfo(frame,
     filename, lineno, function, code_context, index)’ is returned.

 -- 函数: inspect.getinnerframes (traceback, context=1)

     Get a list of frame records for a traceback’s frame and all inner
     frames.  These frames represent calls made as a consequence of
     `frame'.  The first entry in the list represents `traceback'; the
     last entry represents where the exception was raised.

     在 3.5 版更改: A list of *note named tuples: aab. ‘FrameInfo(frame,
     filename, lineno, function, code_context, index)’ is returned.

 -- 函数: inspect.currentframe ()

     Return the frame object for the caller’s stack frame.

     `CPython implementation detail:' This function relies on Python
     stack frame support in the interpreter, which isn’t guaranteed to
     exist in all implementations of Python.  If running in an
     implementation without Python stack frame support this function
     returns ‘None’.

 -- 函数: inspect.stack (context=1)

     Return a list of frame records for the caller’s stack.  The first
     entry in the returned list represents the caller; the last entry
     represents the outermost call on the stack.

     在 3.5 版更改: A list of *note named tuples: aab. ‘FrameInfo(frame,
     filename, lineno, function, code_context, index)’ is returned.

 -- 函数: inspect.trace (context=1)

     Return a list of frame records for the stack between the current
     frame and the frame in which an exception currently being handled
     was raised in.  The first entry in the list represents the caller;
     the last entry represents where the exception was raised.

     在 3.5 版更改: A list of *note named tuples: aab. ‘FrameInfo(frame,
     filename, lineno, function, code_context, index)’ is returned.


File: python.info,  Node: Fetching attributes statically,  Next: Current State of Generators and Coroutines,  Prev: The interpreter stack,  Up: inspect --- 检查对象

5.29.13.6 Fetching attributes statically
........................................

Both *note getattr(): 451. and *note hasattr(): 450. can trigger code
execution when fetching or checking for the existence of attributes.
Descriptors, like properties, will be invoked and *note __getattr__():
323. and *note __getattribute__(): 44f. may be called.

For cases where you want passive introspection, like documentation
tools, this can be inconvenient.  *note getattr_static(): bd3. has the
same signature as *note getattr(): 451. but avoids executing code when
it fetches attributes.

 -- 函数: inspect.getattr_static (obj, attr, default=None)

     Retrieve attributes without triggering dynamic lookup via the
     descriptor protocol, *note __getattr__(): 323. or *note
     __getattribute__(): 44f.

     Note: this function may not be able to retrieve all attributes that
     getattr can fetch (like dynamically created attributes) and may
     find attributes that getattr can’t (like descriptors that raise
     AttributeError).  It can also return descriptors objects instead of
     instance members.

     If the instance *note __dict__: 504. is shadowed by another member
     (for example a property) then this function will be unable to find
     instance members.

     3.2 新版功能.

*note getattr_static(): bd3. does not resolve descriptors, for example
slot descriptors or getset descriptors on objects implemented in C. The
descriptor object is returned instead of the underlying attribute.

You can handle these with code like the following.  Note that for
arbitrary getset descriptors invoking these may trigger code execution:

     # example code for resolving the builtin descriptor types
     class _foo:
         __slots__ = ['foo']

     slot_descriptor = type(_foo.foo)
     getset_descriptor = type(type(open(__file__)).name)
     wrapper_descriptor = type(str.__dict__['__add__'])
     descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)

     result = getattr_static(some_object, 'foo')
     if type(result) in descriptor_types:
         try:
             result = result.__get__()
         except AttributeError:
             # descriptors can raise AttributeError to
             # indicate there is no underlying value
             # in which case the descriptor itself will
             # have to do
             pass


File: python.info,  Node: Current State of Generators and Coroutines,  Next: Code Objects Bit Flags,  Prev: Fetching attributes statically,  Up: inspect --- 检查对象

5.29.13.7 Current State of Generators and Coroutines
....................................................

When implementing coroutine schedulers and for other advanced uses of
generators, it is useful to determine whether a generator is currently
executing, is waiting to start or resume or execution, or has already
terminated.  *note getgeneratorstate(): bd2. allows the current state of
a generator to be determined easily.

 -- 函数: inspect.getgeneratorstate (generator)

     Get current state of a generator-iterator.

     Possible states are:

             * GEN_CREATED: Waiting to start execution.

             * GEN_RUNNING: Currently being executed by the interpreter.

             * GEN_SUSPENDED: Currently suspended at a yield expression.

             * GEN_CLOSED: Execution has completed.

     3.2 新版功能.

 -- 函数: inspect.getcoroutinestate (coroutine)

     Get current state of a coroutine object.  The function is intended
     to be used with coroutine objects created by *note async def: 285.
     functions, but will accept any coroutine-like object that has
     ‘cr_running’ and ‘cr_frame’ attributes.

     Possible states are:

             * CORO_CREATED: Waiting to start execution.

             * CORO_RUNNING: Currently being executed by the
               interpreter.

             * CORO_SUSPENDED: Currently suspended at an await
               expression.

             * CORO_CLOSED: Execution has completed.

     3.5 新版功能.

The current internal state of the generator can also be queried.  This
is mostly useful for testing purposes, to ensure that internal state is
being updated as expected:

 -- 函数: inspect.getgeneratorlocals (generator)

     Get the mapping of live local variables in `generator' to their
     current values.  A dictionary is returned that maps from variable
     names to values.  This is the equivalent of calling *note locals():
     45d. in the body of the generator, and all the same caveats apply.

     If `generator' is a *note generator: 9aa. with no currently
     associated frame, then an empty dictionary is returned.  *note
     TypeError: 193. is raised if `generator' is not a Python generator
     object.

     `CPython implementation detail:' This function relies on the
     generator exposing a Python stack frame for introspection, which
     isn’t guaranteed to be the case in all implementations of Python.
     In such cases, this function will always return an empty
     dictionary.

     3.3 新版功能.

 -- 函数: inspect.getcoroutinelocals (coroutine)

     This function is analogous to *note getgeneratorlocals(): a22, but
     works for coroutine objects created by *note async def: 285.
     functions.

     3.5 新版功能.


File: python.info,  Node: Code Objects Bit Flags,  Next: 命令行界面<8>,  Prev: Current State of Generators and Coroutines,  Up: inspect --- 检查对象

5.29.13.8 Code Objects Bit Flags
................................

Python code objects have a ‘co_flags’ attribute, which is a bitmap of
the following flags:

 -- 数据: inspect.CO_OPTIMIZED

     The code object is optimized, using fast locals.

 -- 数据: inspect.CO_NEWLOCALS

     If set, a new dict will be created for the frame’s ‘f_locals’ when
     the code object is executed.

 -- 数据: inspect.CO_VARARGS

     The code object has a variable positional parameter (‘*args’-like).

 -- 数据: inspect.CO_VARKEYWORDS

     The code object has a variable keyword parameter (‘**kwargs’-like).

 -- 数据: inspect.CO_NESTED

     The flag is set when the code object is a nested function.

 -- 数据: inspect.CO_GENERATOR

     The flag is set when the code object is a generator function, i.e.
     a generator object is returned when the code object is executed.

 -- 数据: inspect.CO_NOFREE

     The flag is set if there are no free or cell variables.

 -- 数据: inspect.CO_COROUTINE

     The flag is set when the code object is a coroutine function.  When
     the code object is executed it returns a coroutine object.  See PEP
     492(1) for more details.

     3.5 新版功能.

 -- 数据: inspect.CO_ITERABLE_COROUTINE

     The flag is used to transform generators into generator-based
     coroutines.  Generator objects with this flag can be used in
     ‘await’ expression, and can ‘yield from’ coroutine objects.  See
     PEP 492(2) for more details.

     3.5 新版功能.

 -- 数据: inspect.CO_ASYNC_GENERATOR

     The flag is set when the code object is an asynchronous generator
     function.  When the code object is executed it returns an
     asynchronous generator object.  See PEP 525(3) for more details.

     3.6 新版功能.

     注解: The flags are specific to CPython, and may not be defined in
     other Python implementations.  Furthermore, the flags are an
     implementation detail, and can be removed or deprecated in future
     Python releases.  It’s recommended to use public APIs from the
     *note inspect: a1. module for any introspection needs.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0492

   (2) https://www.python.org/dev/peps/pep-0492

   (3) https://www.python.org/dev/peps/pep-0525


File: python.info,  Node: 命令行界面<8>,  Prev: Code Objects Bit Flags,  Up: inspect --- 检查对象

5.29.13.9 命令行界面
....................

The *note inspect: a1. module also provides a basic introspection
capability from the command line.

By default, accepts the name of a module and prints the source of that
module.  A class or function within the module can be printed instead by
appended a colon and the qualified name of the target object.

 -- 程序选项: --details

     Print information about the specified object rather than the source
     code


File: python.info,  Node: site —— 站点专属的配置钩子,  Prev: inspect --- 检查对象,  Up: Python运行时服务

5.29.14 ‘site’ —— 站点专属的配置钩子
------------------------------------

`源代码:' Lib/site.py(1)

__________________________________________________________________

`这个模块将在初始化时被自动导入。' 此自动导入可以通过使用解释器的 *note
-S: b2c. 选项来屏蔽。

导入此模块将会附加域特定的路径到模块搜索路径并且添加一些内建对象，除非使
用了 *note -S: b2c. 选项。 那样的话，模块可以被安全地导入，而不会对模块
搜索路径和内建对象有自动的修改或添加。要明确地触发通常域特定的添加，调用
函数 *note site.main(): 1357.。

在 3.3 版更改: 在之前即便使用了 *note -S: b2c.，导入此模块仍然会触发路径
操纵。

它会从头部和尾部构建至多四个目录作为起点。 对于头部，它会使用
‘sys.prefix’ 和 ‘sys.exec_prefix’；空的头部会被跳过。 对于尾部，它会使用
空字符串然后是 ‘lib/site-packages’ (在 Windows 上) 或
‘lib/python`X.Y'/site-packages’ (在 Unix 和 Macintosh 上)。 对于每个不同
的头-尾组合，它会查看其是否指向现有的目录，如果是的话，则将其添加到
‘sys.path’ 并且检查新添加目录中的配置文件。

在 3.5 版更改: 对 "site-python" 目录的支持已被移除。

如果名为 "pyvenv.cfg" 的文件存在于 sys.executable 之上的一个目录中，则
sys.prefix 和 sys.exec_prefix 将被设置为该目录，并且还会检查
site-packages （ sys.base_prefix 和 sys.base_exec_prefix 始终是 Python 安
装的 "真实" 前缀）。 如果 "pyvenv.cfg" （引导程序配置文件）包含设置为非
"true"（不区分大小写）的 "include-system-site-packages" 键，则不会在系统
级前缀中搜索 site-packages；反之则会。

一个路径配置文件是具有 ‘`name'.pth’ 命名格式的文件，并且存在上面提到的四
个目录之一中；它的内容是要添加到 ‘sys.path’ 中的额外项目（每行一个）。不
存在的项目不会添加到 ‘sys.path’，并且不会检查项目指向的是目录还是文件。
项目不会被添加到 ‘sys.path’ 超过一次。空行和由 ‘#’ 起始的行会被跳过。以
‘import’ 开始的行（跟着空格或 TAB）会被执行。

     注解: 每次启动 Python，在 ‘.pth’ 文件中的可执行行都将会被运行，而不
     管特定的模块实际上是否需要被使用。 因此，其影响应降至最低。可执行行
     的主要预期目的是使相关模块可导入（加载第三方导入钩子，调整 ‘PATH’ 等
     ）。如果它发生了，任何其他的初始化都应当在模块实际导入之前完成。将
     代码块限制为一行是一种有意采取的措施，不鼓励在此处放置更复杂的内容
     。

例如，假设 ‘sys.prefix’ 和 ‘sys.exec_prefix’ 已经被设置为 ‘/usr/local’。
Python X.Y 的库之后被安装为 ‘/usr/local/lib/python`X.Y'’。假设有一个拥有
三个孙目录 ‘foo’, ‘bar’ 和 ‘spam’ 的子目录
‘/usr/local/lib/python`X.Y'/site-packages’，并且有两个路径配置文件
‘foot.pth’ 和 ‘bar.pth’。假定 ‘foo.pth’ 内容如下:

     # foo package configuration

     foo
     bar
     bletch

并且 ‘bar.pth’ 包含:

     # bar package configuration

     bar

则下面特定版目录将以如下顺序被添加到 ‘sys.path’。

     /usr/local/lib/pythonX.Y/site-packages/bar
     /usr/local/lib/pythonX.Y/site-packages/foo

请注意 ‘bletch’ 已被省略因为它并不存在；‘bar’ 目前在 ‘foo’ 目录之前因为
‘bar.pth’ 按字母顺序排在 ‘foo.pth’ 之前；而 ‘spam’ 已被省略因为它在两个
路径配置文件中都未被提及。

在这些路径操作之后，会尝试导入一个名为 ‘sitecustomize’ 的模块，它可以执
行任意站点专属的定制。 它通常是由系统管理员在 site-packages 目录下创建的
。 如此此导入失败并引发 *note ImportError: 33d. 或其子类异常，并且异常的
‘name’ 属性等于 ‘'sitecustomize'’，则它会被静默地忽略。 如果 Python 是在
没有可用输出流的情况下启动的，例如在 Windows 上使用 ‘pythonw.exe’ (它默
认被用于启动 start IDLE)，则来自 ‘sitecustomize’ 的输出尝试会被忽略。 任
何其他异常都会导致静默且可能令人迷惑不解的进程失败。

在此之后，会尝试导入一个名为 ‘usercustomize’ 的模块，它可以执行任意用户
专属的定制，如果 *note ENABLE_USER_SITE: 3715. 为真值的话。 这个文件应该
在用户的 site-packages 目录中创建（见下文），该目录是 ‘sys.path’ 的组成
部分，除非被 *note -s: d1d. 所禁用。 如果此导入失败并引发 *note
ImportError: 33d. 或者其子类异常，并且异常的 ‘name’ 属性等于
‘'usercustomize'’，它会被静默地忽略。

请注意对于某些非 Unix 系统来说，‘sys.prefix’ 和 ‘sys.exec_prefix’ 均为空
值，并且路径操作会被跳过；但是仍然会尝试导入 ‘sitecustomize’ 和
‘usercustomize’。

* Menu:

* Readline（类库） 配置::
* 模块内容: 模块内容<7>.
* 命令行界面: 命令行界面<9>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/site.py


File: python.info,  Node: Readline（类库） 配置,  Next: 模块内容<7>,  Up: site —— 站点专属的配置钩子

5.29.14.1 Readline（类库） 配置
...............................

在支持 *note readline: df. 的系统上，这个模块也将导入并配置 *note
rlcompleter: e2. 模块，如果 Python 是以 *note 交互模式: 8eb. 启动并且不
带 *note -S: b2c. 选项的话。 默认的行为是启用 tab 键补全并使用
‘~/.python_history’ 作为历史存档文件。 要禁用它，请删除（或重载）你的
‘sitecustomize’ 或 ‘usercustomize’ 模块或 *note PYTHONSTARTUP: 8ed. 文件
中的 *note sys.__interactivehook__: 8ec. 属性。

在 3.4 版更改: rlcompleter 和 history 会被自动激活。


File: python.info,  Node: 模块内容<7>,  Next: 命令行界面<9>,  Prev: Readline（类库） 配置,  Up: site —— 站点专属的配置钩子

5.29.14.2 模块内容
..................

 -- 数据: site.PREFIXES

     site-packages 目录的前缀列表。

 -- 数据: site.ENABLE_USER_SITE

     显示用户 site-packages 目录状态的旗标。 ‘True’ 意味着它被启用并被添
     加到 ‘sys.path’。 ‘False’ 意味着它按照用户请求被禁用 (通过 *note
     -s: d1d. 或 *note PYTHONNOUSERSITE: d1e.)。 ‘None’ 意味着它因安全理
     由（user 或 group id 和 effective id 之间不匹配）或是被管理员所禁用
     。

 -- 数据: site.USER_SITE

     正在运行的 Python 的用户级 site-packages 的路径。 它可以为 ‘None’，
     如果 *note getusersitepackages(): bdd. 尚未被调用的话。 默认值在
     UNIX 和非框架 Mac OS X 编译版上为
     ‘~/.local/lib/python`X.Y'/site-packages’，在 Mac 框架编译版上为
     ‘~/Library/Python/`X.Y'/lib/python/site-packages’，而在 Windows 上
     则为 ‘`%APPDATA%'\Python\Python`XY'\site-packages’。 此目录属于站点
     目录，这意味着其中的 ‘.pth’ 文件将会被处理。

 -- 数据: site.USER_BASE

     用户级 site-packages 的基准目录的路径。 它可以为 ‘None’，如果 *note
     getuserbase(): bdc. 尚未被调用的话。 默认值在 UNIX 和 Mac OS X 非框
     架编译版上为 ‘~/.local’，在 Mac 框架编译版上为
     ‘~/Library/Python/`X.Y'’，而在 Windows 上则为 ‘`%APPDATA%'\Python’。
     这个值会被 Distutils 用来计算脚本、数据文件和 Python 模块等的安装目
     录。 对于 *note 用户安装规范: 1369.。 另请参阅 *note
     PYTHONUSERBASE: d1c.。

 -- 函数: site.main ()

     将所有的标准站点专属目录添加到模块搜索路径。 这个函数会在导入此模块
     时被自动调用，除非 Python 解释器启动时附带了 *note -S: b2c. 旗标。

     在 3.3 版更改: 这个函数使用无条件调用。

 -- 函数: site.addsitedir (sitedir, known_paths=None)

     将一个目录添加到 sys.path 并处理其 ‘.pth’ 文件。 通常被用于
     ‘sitecustomize’ 或 ‘usercustomize’ (见下文)。

 -- 函数: site.getsitepackages ()

     返回包含所有全局 site-packages 目录的列表。

     3.2 新版功能.

 -- 函数: site.getuserbase ()

     返回用户基准目录的路径 *note USER_BASE: 1368.。 如果它尚未被初始化
     ，则此函数还将参照 *note PYTHONUSERBASE: d1c. 来设置它。

     3.2 新版功能.

 -- 函数: site.getusersitepackages ()

     返回用户专属 site-packages 目录的路径 *note USER_SITE: 1356.。 如果
     它尚未被初始化，则此函数还将参照 *note USER_BASE: 1368. 来设置它。
     要确定用户专属 site-packages 是否已被添加到 ‘sys.path’ 则应当使用
     *note ENABLE_USER_SITE: 3715.。

     3.2 新版功能.


File: python.info,  Node: 命令行界面<9>,  Prev: 模块内容<7>,  Up: site —— 站点专属的配置钩子

5.29.14.3 命令行界面
....................

*note site: ec. 模块还提供了一个从命令行获取用户目录的方式:

     $ python3 -m site --user-site
     /home/user/.local/lib/python3.3/site-packages

如果它被不带参数地调用，它将在标准输出打印 *note sys.path: 490. 的内容，
再打印 *note USER_BASE: 1368. 的值以及该目录是否存在，然后打印 *note
USER_SITE: 1356. 的相应信息，最后打印 *note ENABLE_USER_SITE: 3715. 的值
。

 -- 程序选项: --user-base

     输出用户基本的路径。

 -- 程序选项: --user-site

     将路径输出到用户site-packages目录。

如果同时给出了两个选项，则将打印用户基准目录和用户站点信息（总是按此顺序
），并以 *note os.pathsep: 1365. 分隔。

如果给出了其中一个选项，脚本将退出并返回以下值中的一个：如果用户级
site-packages 目录被启用则为 ‘0’，如果它被用户禁用则为 ‘1’，如果它因安全
理由或被管理员禁用则为 ‘2’，如果发生错误则为大于 2 的值。

参见
....

PEP 370(1) – 分用户的 site-packages 目录

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0370


File: python.info,  Node: 自定义 Python 解释器,  Next: 导入模块,  Prev: Python运行时服务,  Up: Python 标准库

5.30 自定义 Python 解释器
=========================

本章中描述的模块允许编写类似于 Python 的交互式解释器的接口。 如果你想要
一个支持附加一些特殊功能到 Python 语言的 Python 解释器，你应该看看 *note
code: 1b. 模块。 （ *note codeop: 1d. 模块是低层级的，用于支持编译可能不
完整的 Python 代码块。）

本章描述的完整模块列表如下：

* Menu:

* code: code --- 解释器基类. 解释器基类
* codeop: codeop --- 编译Python代码. 编译Python代码


File: python.info,  Node: code --- 解释器基类,  Next: codeop --- 编译Python代码,  Up: 自定义 Python 解释器

5.30.1 ‘code’ — 解释器基类
--------------------------

`源代码：' Lib/code.py(1)

__________________________________________________________________

‘code’ 模块提供了在 Python 中实现 read-eval-print 循环的功能。它包含两个
类和一些快捷功能，可用于构建提供交互式解释器的应用程序。

 -- 类: code.InteractiveInterpreter (locals=None)

     这个类处理解析器和解释器状态（用户命名空间的）；它不处理缓冲器、终
     端提示区或着输入文件名（文件名总是显示地传递）。可选的 `locals' 参
     数指定一个字典，字典里面包含将在此类执行的代码；它默认创建新的字典
     ，其键 ‘'__name__'’ 设置为 ‘'__console__'’ ，键 ‘'__doc__'’ 设置为
     ‘None’ 。

 -- 类: code.InteractiveConsole (locals=None, filename="<console>")

     尽可能模拟交互式 Python 解释器的行为。此类建立在 *note
     InteractiveInterpreter: 3723. 的基础上，使用熟悉的 ‘sys.ps1’ 和
     ‘sys.ps2’ 作为输入提示符，并有输入缓冲。

 -- 函数: code.interact (banner=None, readfunc=None, local=None,
          exitmsg=None)

     运行一个 read-eval-print 循环的便捷函数。这会创建一个新的 *note
     InteractiveConsole: 1811. 实例。如果提供了 `readfunc' ，会设置为
     *note InteractiveConsole.raw_input(): 3725. 方法。如果提供了
     `local' ，则将其传递给 *note InteractiveConsole: 1811. 的构造函数，
     以用作解释器循环的默认命名空间。然后，如果提供了 `banner' 和
     `exitmsg' ，实例的 *note interact(): 3724. 方法会以此为标题和退出消
     息。控制台对象在使用后将被丢弃。

     在 3.6 版更改: 加入 `exitmsg' 参数。

 -- 函数: code.compile_command (source, filename="<input>",
          symbol="single")

     这个函数主要用来模拟 Python 解释器的主循环（即 read-eval-print 循环
     ）。难点的部分是当用户输入不完整命令时，判断能否通过之后的输入来完
     成（要么成为完整的命令，要么语法错误）。该函数 `几乎' 和实际的解释
     器主循环的判断是相同的。

     `source' 是源字符串；`filename' 是可选的用作读取源的文件名，默认为
     ‘'<input>'’；`symbol' 是可选的语法开启符号，应为 ‘'single'’ (默认),
     ‘'eval'’ 或 ‘'exec'’。

     如果命令完整且有效则返回一个代码对象 (等价于 ‘compile(source,
     filename, symbol)’)；如果命令不完整则返回 ‘None’；如果命令完整但包
     含语法错误则会引发 *note SyntaxError: 460. 或 *note OverflowError:
     968. 而如果命令包含无效字面值则将引发 *note ValueError: 1fc.。

* Menu:

* 交互解释器对象::
* 交互式控制台对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/code.py


File: python.info,  Node: 交互解释器对象,  Next: 交互式控制台对象,  Up: code --- 解释器基类

5.30.1.1 交互解释器对象
.......................

 -- 方法: InteractiveInterpreter.runsource (source, filename="<input>",
          symbol="single")

     在解释器中编译并运行一段源码。 所用参数与 *note compile_command():
     3726. 一样；`filename' 的默认值为 ‘'<input>'’，`symbol' 则为
     ‘'single'’。 可能发生以下情况之一：

        * 输入不正确；*note compile_command(): 3726. 引发了一个异常
          (*note SyntaxError: 460. 或 *note OverflowError: 968.)。 将通
          过调用 *note showsyntaxerror(): 372a. 方法打印语法回溯信息。
          *note runsource(): 3729. 返回 ‘False’。

        * 输入不完整，需要更多输入；函数 *note compile_command(): 3726.
          返回 ‘None’ 。方法 *note runsource(): 3729. 返回 ‘True’ 。

        * 输入完整；*note compile_command(): 3726. 返回了一个代码对象。
          将通过调用 *note runcode(): 372b. 执行代码（该方法也会处理运行
          时异常，*note SystemExit: 605. 除外）。 *note runsource():
          3729. 返回 ‘False’。

     该返回值用于决定使用 ‘sys.ps1’ 还是 ‘sys.ps2’ 来作为下一行的输入提
     示符。

 -- 方法: InteractiveInterpreter.runcode (code)

     执行一个代码对象。当发生异常时，调用 *note showtraceback(): 6b0. 来
     显示回溯。除 *note SystemExit: 605. （允许传播）以外的所有异常都会
     被捕获。

     有关 *note KeyboardInterrupt: 198. 的说明，该异常可能发生于此代码的
     其他位置，并且并不总能被捕获。 调用者应当准备好处理它。

 -- 方法: InteractiveInterpreter.showsyntaxerror (filename=None)

     显示刚发生的语法错误。 这不会显示堆栈回溯因为语法错误并无此种信息。
     如果给出了 `filename'，它会被放入异常来替代 Python 解析器所提供的默
     认文件名，因为它在从一个字符串读取时总是会使用 ‘'<string>'’。 输出
     将由 *note write(): 372c. 方法来写入。

 -- 方法: InteractiveInterpreter.showtraceback ()

     显示刚发生的异常。 我们移除了第一个堆栈条目因为它从属于解释器对象的
     实现。 输出将由 *note write(): 372c. 方法来写入。

     在 3.5 版更改: 将显示完整的链式回溯，而不只是主回溯。

 -- 方法: InteractiveInterpreter.write (data)

     将一个字符串写入到标准错误流 (‘sys.stderr’)。 所有派生类都应重载此
     方法以提供必要的正确输出处理。


File: python.info,  Node: 交互式控制台对象,  Prev: 交互解释器对象,  Up: code --- 解释器基类

5.30.1.2 交互式控制台对象
.........................

*note InteractiveConsole: 1811. 类是 *note InteractiveInterpreter: 3723.
的子类，因此它提供了解释器对象的所有方法，还有以下的额外方法。

 -- 方法: InteractiveConsole.interact (banner=None, exitmsg=None)

     近似地模拟交互式 Python 终端。 可选的 `banner' 参数指定要在第一次交
     互前打印的条幅；默认情况下会类似于标准 Python 解释器所打印的内容，
     并附上外加圆括号的终端对象类名（这样就不会与真正的解释器混淆 —— 因
     为确实太像了！）

     可选的 `exitmsg' 参数指定要在退出时打印的退出消息。 传入空字符串可
     以屏蔽退出消息。 如果 `exitmsg' 未给出或为 ‘None’，则将打印默认消息
     。

     在 3.4 版更改: 要禁止打印任何条幅消息，请传递一个空字符串。

     在 3.6 版更改: 退出时打印退出消息。

 -- 方法: InteractiveConsole.push (line)

     将一行源文本推入解释器。 行内容不应带有末尾换行符；它可以有内部换行
     符。 行内容会被添加到一个缓冲区并且会调用解释器的 ‘runsource()’ 方
     法，附带缓冲区内容的拼接结果作为源文本。 如果显示命令已执行或不合法
     ，缓冲区将被重置；否则，则命令尚未结束，缓冲区将在添加行后保持原样
     。 如果要求更多输入则返回值为 ‘True’，如果行已按某种方式被处理则返
     回值为 ‘False’ (这与 ‘runsource()’ 相同)。

 -- 方法: InteractiveConsole.resetbuffer ()

     从输入缓冲区中删除所有未处理的内容。

 -- 方法: InteractiveConsole.raw_input (prompt="")

     输出提示并读取一行。返回的行不包含末尾的换行符。当用户输入 EOF 键序
     列时，会引发 *note EOFError: c74. 异常。默认实现是从 ‘sys.stdin’ 读
     取；子类可以用其他实现代替。


File: python.info,  Node: codeop --- 编译Python代码,  Prev: code --- 解释器基类,  Up: 自定义 Python 解释器

5.30.2 ‘codeop’ — 编译Python代码
--------------------------------

`源代码：' Lib/codeop.py(1)

__________________________________________________________________

*note codeop: 1d. 模块提供了可以模拟Python读取-执行-打印循环的实用程序，
就像在 *note code: 1b. 模块中一样。因此，您可能不希望直接使用该模块；如
果你想在程序中包含这样一个循环，你可能需要使用 *note code: 1b. 模块。

这个任务有两个部分:

  1. 能够判断一行输入是否完成了一个Python语句：简而言之，告诉我们是否要
     打印 ’‘>>>’’ 或 ’‘...’’。

  2. 记住用户已输入了哪些 future 语句，这样后续的输入可以在这些语句被启
     用的状态下被编译。

*note codeop: 1d. 模块提供了分别以及同时执行这两个部分的方式。

只执行前一部分：

 -- 函数: codeop.compile_command (source, filename="<input>",
          symbol="single")

     尝试编译 `source'，这应当是一个 Python 代码字符串，并且在 `source'
     是有效的 Python 代码时返回一个代码对象。 在此情况下，代码对象的
     filename 属性将为 `filename'，其默认值为 ‘'<input>'’。 如果
     `source' `不是' 有效的 Python 代码而是有效的 Python 代码的一个前缀
     时将返回 ‘None’。

     如果 `source' 存在问题，将引发异常。 如果存在无效的 Python 语法将引
     发 *note SyntaxError: 460.，而如果存在无效的字面值则将引发 *note
     OverflowError: 968. 或 *note ValueError: 1fc.。

     `symbol' 参数确定 `source' 是作为一条语句 (对应默认值 ‘'single'’)，
     作为一系列语句 (‘'exec'’) 还是作为一个 *note expression: 3631.
     (‘'eval'’) 进行编译。 任何其他值都将导致引发 *note ValueError:
     1fc.。

          注解: 解析器有可能（但很不常见）会在到达源码结尾之前停止解析并
          成功输出结果；在这种情况下，末尾的符号可能会被忽略而不是引发错
          误。 例如，一个反斜杠加两个换行符之后可以跟随任何无意义的符号
          。 一旦解析器 API 得到改进将修正这个问题。

 -- 类: codeop.Compile

     这个类的实例具有 *note __call__(): 143e. 方法，其签名与内置函数
     *note compile(): 1b5. 相似，区别在于如果该实例编译了包含 *note
     __future__: 0. 语句的程序文本，则实例会‘记住’并使用已生效的语句编译
     所有后续程序文本。

 -- 类: codeop.CommandCompiler

     这个类的实例具有 *note __call__(): 143e. 方法，其签名与 *note
     compile_command(): 3734. 相似；区别在于如果该实例编译了包含
     ‘__future__’ 语句的程序文本，则实例会‘记住’并使用已生效的语句编译编
     译所有后续程序文本。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/codeop.py


File: python.info,  Node: 导入模块,  Next: Python 语言服务,  Prev: 自定义 Python 解释器,  Up: Python 标准库

5.31 导入模块
=============

本章中介绍的模块提供了导入其他Python模块和挂钩以自定义导入过程的新方法。

本章描述的完整模块列表如下：

* Menu:

* zipimport: zipimport --- 从 Zip 存档中导入模块. 从 Zip 存档中导入模块
* pkgutil: pkgutil --- 包扩展工具. 包扩展工具
* modulefinder: modulefinder --- 查找脚本使用的模块. 查找脚本使用的模块
* runpy: runpy --- Locating and executing Python modules. Locating and executing Python modules
* importlib: importlib --- import 的实现. import 的实现
* Using importlib.metadata: Using importlib metadata.


File: python.info,  Node: zipimport --- 从 Zip 存档中导入模块,  Next: pkgutil --- 包扩展工具,  Up: 导入模块

5.31.1 ‘zipimport’ — 从 Zip 存档中导入模块
------------------------------------------

`源代码：' Lib/zipimport.py(1)

__________________________________________________________________

此模块添加了从 ZIP 格式档案中导入 Python 模块（ ‘*.py’ ， ‘*.pyc’ ）和包
的能力。通常不需要明确地使用 *note zipimport: 144. 模块，内置的 *note
import: c25. 机制会自动将此模块用于 ZIP 档案路径的 *note sys.path: 490.
项目上。

通常， *note sys.path: 490. 是字符串的目录名称列表。此模块同样允许 *note
sys.path: 490. 的一项成为命名 ZIP 文件档案的字符串。 ZIP 档案可以容纳子
目录结构去支持包的导入，并且可以将归档文件中的路径指定为仅从子目录导入。
比如说，路径 ‘example.zip/lib/’ 将只会从档案中的 ‘lib/’ 子目录导入。

任何文件都可以存在于 ZIP档案之中，但是只有 ‘.py’ 和 ‘.pyc’ 文件是能够导
入的。不允许导入 ZIP 中的动态模组（ ‘.pyd’ ， ‘.so’ ）。请注意，如果档案
中只包含 ‘.py’ 文件， Python不会尝试通过添加对应的 ‘.pyc’ 文件修改档案，
意思是如果 ZIP 档案不包含 ‘.pyc’ 文件，导入或许会变慢。

在 3.8 版更改: 以前，不支持带有档案注释的 ZIP 档案。

参见
....

PKZIP Application Note(2)

     Phil Katz 编写的 ZIP 文件格式文档，此格式和使用的算法的创建者。

PEP 273(3) -  从ZIP压缩包导入模块

     由 James C. Ahlstrom 编写，他也提供了实现。 Python 2.3 遵循 PEP
     273(4) 的规范，但是使用 Just van Rossum 编写的使用了 PEP 302(5) 中
     描述的导入钩的实现。

PEP 302(6) - 新导入钩

     PEP 添加导入钩来有助于模块运作。

此模块定义了一个异常：

 -- 例外: zipimport.ZipImportError

     异常由 zipimporter 对象引发。这是 *note ImportError: 33d. 的子类，
     因此，也可以捕获为 *note ImportError: 33d. 。

* Menu:

* zipimporter 对象::
* 例子: 例子<28>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/zipimport.py

   (2) https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT

   (3) https://www.python.org/dev/peps/pep-0273

   (4) https://www.python.org/dev/peps/pep-0273

   (5) https://www.python.org/dev/peps/pep-0302

   (6) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: zipimporter 对象,  Next: 例子<28>,  Up: zipimport --- 从 Zip 存档中导入模块

5.31.1.1 zipimporter 对象
.........................

*note zipimporter: 373f. 是用于导入 ZIP 文件的类。

 -- 类: zipimport.zipimporter (archivepath)

     创建新的 zipimporter 实例。 `archivepath' 必须是指向 ZIP 文件的路径
     ，或者 ZIP 文件中的特定路径。例如， ‘foo/bar.zip/lib’ 的
     `archivepath' 将在 ZIP 文件 ‘foo/bar.zip’ 中的 ‘lib’ 目录中查找模块
     （只要它存在）。

     如果 `archivepath' 没有指向一个有效的 ZIP 档案，引发 *note
     ZipImportError: 373c. 。

      -- 方法: find_module (fullname[, path])

          搜索由 `fullname' 指定的模块。 `fullname' 必须是完全合格的（点
          分的）模块名。它返回 zipimporter 实例本身如果模块被找到，或者
          返回 *note None: 158. 如果没找到指定模块。可选的 `path' 被忽略
          ，这是为了与导入器协议兼容。

      -- 方法: get_code (fullname)

          返回指定模块的代码对象。如果不能找到模块会引发 *note
          ZipImportError: 373c. 错误。

      -- 方法: get_data (pathname)

          返回与 `pathname' 相关联的数据。如果不能找到文件则引发 *note
          OSError: 1d4. 错误。

          在 3.3 版更改: 曾经是 *note IOError: 99a. 被引发而不是 *note
          OSError: 1d4. 。

      -- 方法: get_filename (fullname)

          如果导入了指定的模块 ‘__file__’ ，则返回为该模块设置的值。如果
          未找到模块则引发 *note ZipImportError: 373c. 错误。

          3.1 新版功能.

      -- 方法: get_source (fullname)

          返回指定模块的源代码。如果没有找到模块则引发 *note
          ZipImportError: 373c. ，如果档案包含模块但是没有源代码，返回
          *note None: 158. 。

      -- 方法: is_package (fullname)

          如果由 `fullname' 指定的模块是一个包则返回 ‘True’ 。如果不能找
          到模块则引发 *note ZipImportError: 373c. 错误。

      -- 方法: load_module (fullname)

          加载由 `fullname' 指定的模块。 `fullname' 必须是完全限定的（点
          分的）模块名。它返回已加载模块，或者当找不到模块时引发 *note
          ZipImportError: 373c. 错误。

      -- 属性: archive

          导入器关联的 ZIP 文件的文件名，没有可能的子路径。

      -- 属性: prefix

          ZIP 文件中搜索的模块的子路径。这是一个指向 ZIP 文件根目录的
          zipimporter 对象的空字符串。

     当与斜杠结合使用时， *note archive: 3746. 和 *note prefix: 3747. 属
     性等价于赋予 *note zipimporter: 373f. 构造器的原始 `archivepath' 参
     数。


File: python.info,  Node: 例子<28>,  Prev: zipimporter 对象,  Up: zipimport --- 从 Zip 存档中导入模块

5.31.1.2 例子
.............

这是一个从 ZIP 档案中导入模块的例子 - 请注意 *note zipimport: 144. 模块
不需要明确地使用。

     $ unzip -l example.zip
     Archive:  example.zip
       Length     Date   Time    Name
      --------    ----   ----    ----
          8467  11-26-02 22:30   jwzthreading.py
      --------                   -------
          8467                   1 file
     $ ./python
     Python 2.3 (#1, Aug 1 2003, 19:54:32)
     >>> import sys
     >>> sys.path.insert(0, 'example.zip')  # Add .zip file to front of path
     >>> import jwzthreading
     >>> jwzthreading.__file__
     'example.zip/jwzthreading.py'


File: python.info,  Node: pkgutil --- 包扩展工具,  Next: modulefinder --- 查找脚本使用的模块,  Prev: zipimport --- 从 Zip 存档中导入模块,  Up: 导入模块

5.31.2 ‘pkgutil’ — 包扩展工具
-----------------------------

`源代码:' Lib/pkgutil.py(1)

__________________________________________________________________

该模块为导入系统提供了工具，尤其是在包支持方面。

 -- 类: pkgutil.ModuleInfo (module_finder, name, ispkg)

     一个包含模块信息的简短摘要的命名元组。

     3.6 新版功能.

 -- 函数: pkgutil.extend_path (path, name)

     Extend the search path for the modules which comprise a package.
     Intended use is to place the following code in a package’s
     ‘__init__.py’:

          from pkgutil import extend_path
          __path__ = extend_path(__path__, __name__)

     This will add to the package’s ‘__path__’ all subdirectories of
     directories on ‘sys.path’ named after the package.  This is useful
     if one wants to distribute different parts of a single logical
     package as multiple directories.

     It also looks for ‘*.pkg’ files beginning where ‘*’ matches the
     `name' argument.  This feature is similar to ‘*.pth’ files (see the
     *note site: ec. module for more information), except that it
     doesn’t special-case lines starting with ‘import’.  A ‘*.pkg’ file
     is trusted at face value: apart from checking for duplicates, all
     entries found in a ‘*.pkg’ file are added to the path, regardless
     of whether they exist on the filesystem.  (This is a feature.)

     If the input path is not a list (as is the case for frozen
     packages) it is returned unchanged.  The input path is not
     modified; an extended copy is returned.  Items are only appended to
     the copy at the end.

     It is assumed that *note sys.path: 490. is a sequence.  Items of
     *note sys.path: 490. that are not strings referring to existing
     directories are ignored.  Unicode items on *note sys.path: 490.
     that cause errors when used as filenames may cause this function to
     raise an exception (in line with *note os.path.isdir(): 1f9.
     behavior).

 -- 类: pkgutil.ImpImporter (dirname=None)

     PEP 302(2) Finder that wraps Python’s "classic" import algorithm.

     If `dirname' is a string, a PEP 302(3) finder is created that
     searches that directory.  If `dirname' is ‘None’, a PEP 302(4)
     finder is created that searches the current *note sys.path: 490,
     plus any modules that are frozen or built-in.

     Note that *note ImpImporter: 374d. does not currently support being
     used by placement on *note sys.meta_path: 5ef.

     3.3 版后已移除: This emulation is no longer needed, as the standard
     import mechanism is now fully PEP 302(5) compliant and available in
     *note importlib: 9b.

 -- 类: pkgutil.ImpLoader (fullname, file, filename, etc)

     *note Loader: 14cb. that wraps Python’s "classic" import algorithm.

     3.3 版后已移除: This emulation is no longer needed, as the standard
     import mechanism is now fully PEP 302(6) compliant and available in
     *note importlib: 9b.

 -- 函数: pkgutil.find_loader (fullname)

     Retrieve a module *note loader: 14cb. for the given `fullname'.

     This is a backwards compatibility wrapper around *note
     importlib.util.find_spec(): 940. that converts most failures to
     *note ImportError: 33d. and only returns the loader rather than the
     full ‘ModuleSpec’.

     在 3.3 版更改: Updated to be based directly on *note importlib: 9b.
     rather than relying on the package internal PEP 302(7) import
     emulation.

     在 3.4 版更改: Updated to be based on PEP 451(8)

 -- 函数: pkgutil.get_importer (path_item)

     Retrieve a *note finder: 14ca. for the given `path_item'.

     The returned finder is cached in *note sys.path_importer_cache:
     4a5. if it was newly created by a path hook.

     The cache (or part of it) can be cleared manually if a rescan of
     *note sys.path_hooks: 964. is necessary.

     在 3.3 版更改: Updated to be based directly on *note importlib: 9b.
     rather than relying on the package internal PEP 302(9) import
     emulation.

 -- 函数: pkgutil.get_loader (module_or_name)

     Get a *note loader: 14cb. object for `module_or_name'.

     If the module or package is accessible via the normal import
     mechanism, a wrapper around the relevant part of that machinery is
     returned.  Returns ‘None’ if the module cannot be found or
     imported.  If the named module is not already imported, its
     containing package (if any) is imported, in order to establish the
     package ‘__path__’.

     在 3.3 版更改: Updated to be based directly on *note importlib: 9b.
     rather than relying on the package internal PEP 302(10) import
     emulation.

     在 3.4 版更改: Updated to be based on PEP 451(11)

 -- 函数: pkgutil.iter_importers (fullname='')

     Yield *note finder: 14ca. objects for the given module name.

     If fullname contains a ’.’, the finders will be for the package
     containing fullname, otherwise they will be all registered top
     level finders (i.e.  those on both sys.meta_path and
     sys.path_hooks).

     If the named module is in a package, that package is imported as a
     side effect of invoking this function.

     If no module name is specified, all top level finders are produced.

     在 3.3 版更改: Updated to be based directly on *note importlib: 9b.
     rather than relying on the package internal PEP 302(12) import
     emulation.

 -- 函数: pkgutil.iter_modules (path=None, prefix='')

     Yields *note ModuleInfo: 616. for all submodules on `path', or, if
     `path' is ‘None’, all top-level modules on ‘sys.path’.

     `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.

          注解: Only works for a *note finder: 14ca. which defines an
          ‘iter_modules()’ method.  This interface is non-standard, so
          the module also provides implementations for *note
          importlib.machinery.FileFinder: 9be. and *note
          zipimport.zipimporter: 373f.

     在 3.3 版更改: Updated to be based directly on *note importlib: 9b.
     rather than relying on the package internal PEP 302(13) import
     emulation.

 -- 函数: pkgutil.walk_packages (path=None, prefix='', onerror=None)

     Yields *note ModuleInfo: 616. 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, *note ImportError: 33d.s are caught and ignored, while
     all other exceptions are propagated, terminating the search.

     示例:

          # list all modules python can access
          walk_packages()

          # list all submodules of ctypes
          walk_packages(ctypes.__path__, ctypes.__name__ + '.')

          注解: Only works for a *note finder: 14ca. which defines an
          ‘iter_modules()’ method.  This interface is non-standard, so
          the module also provides implementations for *note
          importlib.machinery.FileFinder: 9be. and *note
          zipimport.zipimporter: 373f.

     在 3.3 版更改: Updated to be based directly on *note importlib: 9b.
     rather than relying on the package internal PEP 302(14) import
     emulation.

 -- 函数: pkgutil.get_data (package, resource)

     从包中获取一个资源。

     This is a wrapper for the *note loader: 14cb. *note get_data: 3753.
     API. The `package' argument should be the name of a package, in
     standard module format (‘foo.bar’).  The `resource' argument should
     be in the form of a relative filename, using ‘/’ as the path
     separator.  The parent directory name ‘..’ is not allowed, and nor
     is a rooted name (starting with a ‘/’).

     The function returns a binary string that is the contents of the
     specified resource.

     For packages located in the filesystem, which have already been
     imported, this is the rough equivalent of:

          d = os.path.dirname(sys.modules[package].__file__)
          data = open(os.path.join(d, resource), 'rb').read()

     If the package cannot be located or loaded, or it uses a *note
     loader: 14cb. which does not support *note get_data: 3753, then
     ‘None’ is returned.  In particular, the *note loader: 14cb. for
     *note namespace packages: 14c3. does not support *note get_data:
     3753.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/pkgutil.py

   (2) https://www.python.org/dev/peps/pep-0302

   (3) https://www.python.org/dev/peps/pep-0302

   (4) https://www.python.org/dev/peps/pep-0302

   (5) https://www.python.org/dev/peps/pep-0302

   (6) https://www.python.org/dev/peps/pep-0302

   (7) https://www.python.org/dev/peps/pep-0302

   (8) https://www.python.org/dev/peps/pep-0451

   (9) https://www.python.org/dev/peps/pep-0302

   (10) https://www.python.org/dev/peps/pep-0302

   (11) https://www.python.org/dev/peps/pep-0451

   (12) https://www.python.org/dev/peps/pep-0302

   (13) https://www.python.org/dev/peps/pep-0302

   (14) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: modulefinder --- 查找脚本使用的模块,  Next: runpy --- Locating and executing Python modules,  Prev: pkgutil --- 包扩展工具,  Up: 导入模块

5.31.3 ‘modulefinder’ — 查找脚本使用的模块
------------------------------------------

`源码：' Lib/modulefinder.py(1)

__________________________________________________________________

该模块提供了一个 *note ModuleFinder: ff0. 类，可用于确定脚本导入的模块集
。 ‘modulefinder.py’ 也可以作为脚本运行，给出 Python 脚本的文件名作为参
数，之后将打印导入模块的报告。

 -- 函数: modulefinder.AddPackagePath (pkg_name, path)

     记录名为 `pkg_name' 的包可以在指定的 `path' 中找到。

 -- 函数: modulefinder.ReplacePackage (oldname, newname)

     允许指定名为 `oldname' 的模块实际上是名为 `newname' 的包。

 -- 类: modulefinder.ModuleFinder (path=None, debug=0, excludes=[],
          replace_paths=[])

     该类提供 *note run_script(): 3758. 和 *note report(): 3759. 方法，
     用于确定脚本导入的模块集。 `path' 可以是搜索模块的目录列表；如果没
     有指定，则使用 ‘sys.path’ 。 `debug' 设置调试级别；更高的值使类打印
     调试消息，关于它正在做什么。 `excludes' 是要从分析中排除的模块名称
     列表。 `replace_paths' 是将在模块路径中替换的 ‘(oldpath, newpath)’
     元组的列表。

      -- 方法: report ()

          将报告打印到标准输出，列出脚本导入的模块及其路径，以及缺少或似
          乎缺失的模块。

      -- 方法: run_script (pathname)

          分析 `pathname' 文件的内容，该文件必须包含 Python 代码。

      -- 属性: modules

          一个将模块名称映射到模块的字典。 请参阅 *note ModuleFinder
          的示例用法: 375b.。

* Menu:

* ModuleFinder 的示例用法::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/modulefinder.py


File: python.info,  Node: ModuleFinder 的示例用法,  Up: modulefinder --- 查找脚本使用的模块

5.31.3.1 ‘ModuleFinder’ 的示例用法
..................................

稍后将分析的脚本（bacon.py）:

     import re, itertools

     try:
         import baconhameggs
     except ImportError:
         pass

     try:
         import guido.python.ham
     except ImportError:
         pass

将输出 bacon.py 报告的脚本:

     from modulefinder import ModuleFinder

     finder = ModuleFinder()
     finder.run_script('bacon.py')

     print('Loaded modules:')
     for name, mod in finder.modules.items():
         print('%s: ' % name, end='')
         print(','.join(list(mod.globalnames.keys())[:3]))

     print('-'*50)
     print('Modules not imported:')
     print('\n'.join(finder.badmodules.keys()))

输出样例（可能因架构而异）:

     Loaded modules:
     _types:
     copyreg:  _inverted_registry,_slotnames,__all__
     sre_compile:  isstring,_sre,_optimize_unicode
     _sre:
     sre_constants:  REPEAT_ONE,makedict,AT_END_LINE
     sys:
     re:  __module__,finditer,_expand
     itertools:
     __main__:  re,itertools,baconhameggs
     sre_parse:  _PATTERNENDERS,SRE_FLAG_UNICODE
     array:
     types:  __module__,IntType,TypeType
     ---------------------------------------------------
     Modules not imported:
     guido.python.ham
     baconhameggs


File: python.info,  Node: runpy --- Locating and executing Python modules,  Next: importlib --- import 的实现,  Prev: modulefinder --- 查找脚本使用的模块,  Up: 导入模块

5.31.4 ‘runpy’ — Locating and executing Python modules
------------------------------------------------------

`Source code:' Lib/runpy.py(1)

__________________________________________________________________

The *note runpy: e3. module is used to locate and run Python modules
without importing them first.  Its main use is to implement the *note
-m: 340. command line switch that allows scripts to be located using the
Python module namespace rather than the filesystem.

Note that this is `not' a sandbox module - all code is executed in the
current process, and any side effects (such as cached imports of other
modules) will remain in place after the functions have returned.

Furthermore, any functions and classes defined by the executed code are
not guaranteed to work correctly after a *note runpy: e3. function has
returned.  If that limitation is not acceptable for a given use case,
*note importlib: 9b. is likely to be a more suitable choice than this
module.

The *note runpy: e3. module provides two functions:

 -- 函数: runpy.run_module (mod_name, init_globals=None, run_name=None,
          alter_sys=False)

     Execute the code of the specified module and return the resulting
     module globals dictionary.  The module’s code is first located
     using the standard import mechanism (refer to PEP 302(2) for
     details) and then executed in a fresh module namespace.

     The `mod_name' argument should be an absolute module name.  If the
     module name refers to a package rather than a normal module, then
     that package is imported and the ‘__main__’ submodule within that
     package is then executed and the resulting module globals
     dictionary returned.

     The optional dictionary argument `init_globals' may be used to
     pre-populate the module’s globals dictionary before the code is
     executed.  The supplied dictionary will not be modified.  If any of
     the special global variables below are defined in the supplied
     dictionary, those definitions are overridden by *note run_module():
     134b.

     The special global variables ‘__name__’, ‘__spec__’, ‘__file__’,
     ‘__cached__’, ‘__loader__’ and ‘__package__’ are set in the globals
     dictionary before the module code is executed (Note that this is a
     minimal set of variables - other variables may be set implicitly as
     an interpreter implementation detail).

     ‘__name__’ is set to `run_name' if this optional argument is not
     *note None: 158, to ‘mod_name + '.__main__'’ if the named module is
     a package and to the `mod_name' argument otherwise.

     ‘__spec__’ will be set appropriately for the `actually' imported
     module (that is, ‘__spec__.name’ will always be `mod_name' or
     ‘mod_name + '.__main__’, never `run_name').

     ‘__file__’, ‘__cached__’, ‘__loader__’ and ‘__package__’ are *note
     set as normal: 14d2. based on the module spec.

     If the argument `alter_sys' is supplied and evaluates to *note
     True: 4a1, then ‘sys.argv[0]’ is updated with the value of
     ‘__file__’ and ‘sys.modules[__name__]’ is updated with a temporary
     module object for the module being executed.  Both ‘sys.argv[0]’
     and ‘sys.modules[__name__]’ are restored to their original values
     before the function returns.

     Note that this manipulation of *note sys: fe. is not thread-safe.
     Other threads may see the partially initialised module, as well as
     the altered list of arguments.  It is recommended that the *note
     sys: fe. module be left alone when invoking this function from
     threaded code.

     参见
     ....

     The *note -m: 340. option offering equivalent functionality from
     the command line.

     在 3.1 版更改: Added ability to execute packages by looking for a
     ‘__main__’ submodule.

     在 3.2 版更改: Added ‘__cached__’ global variable (see PEP
     3147(3)).

     在 3.4 版更改: Updated to take advantage of the module spec feature
     added by PEP 451(4).  This allows ‘__cached__’ to be set correctly
     for modules run this way, as well as ensuring the real module name
     is always accessible as ‘__spec__.name’.

 -- 函数: runpy.run_path (file_path, init_globals=None, run_name=None)

     Execute the code at the named filesystem location and return the
     resulting module globals dictionary.  As with a script name
     supplied to the CPython command line, the supplied path may refer
     to a Python source file, a compiled bytecode file or a valid
     sys.path entry containing a ‘__main__’ module (e.g.  a zipfile
     containing a top-level ‘__main__.py’ file).

     For a simple script, the specified code is simply executed in a
     fresh module namespace.  For a valid sys.path entry (typically a
     zipfile or directory), the entry is first added to the beginning of
     ‘sys.path’.  The function then looks for and executes a *note
     __main__: 1. module using the updated path.  Note that there is no
     special protection against invoking an existing *note __main__: 1.
     entry located elsewhere on ‘sys.path’ if there is no such module at
     the specified location.

     The optional dictionary argument `init_globals' may be used to
     pre-populate the module’s globals dictionary before the code is
     executed.  The supplied dictionary will not be modified.  If any of
     the special global variables below are defined in the supplied
     dictionary, those definitions are overridden by *note run_path():
     cb9.

     The special global variables ‘__name__’, ‘__spec__’, ‘__file__’,
     ‘__cached__’, ‘__loader__’ and ‘__package__’ are set in the globals
     dictionary before the module code is executed (Note that this is a
     minimal set of variables - other variables may be set implicitly as
     an interpreter implementation detail).

     ‘__name__’ is set to `run_name' if this optional argument is not
     *note None: 158. and to ‘'<run_path>'’ otherwise.

     If the supplied path directly references a script file (whether as
     source or as precompiled byte code), then ‘__file__’ will be set to
     the supplied path, and ‘__spec__’, ‘__cached__’, ‘__loader__’ and
     ‘__package__’ will all be set to *note None: 158.

     If the supplied path is a reference to a valid sys.path entry, then
     ‘__spec__’ will be set appropriately for the imported ‘__main__’
     module (that is, ‘__spec__.name’ will always be ‘__main__’).
     ‘__file__’, ‘__cached__’, ‘__loader__’ and ‘__package__’ will be
     *note set as normal: 14d2. based on the module spec.

     A number of alterations are also made to the *note sys: fe. module.
     Firstly, ‘sys.path’ may be altered as described above.
     ‘sys.argv[0]’ is updated with the value of ‘file_path’ and
     ‘sys.modules[__name__]’ is updated with a temporary module object
     for the module being executed.  All modifications to items in *note
     sys: fe. are reverted before the function returns.

     Note that, unlike *note run_module(): 134b, the alterations made to
     *note sys: fe. are not optional in this function as these
     adjustments are essential to allowing the execution of sys.path
     entries.  As the thread-safety limitations still apply, use of this
     function in threaded code should be either serialised with the
     import lock or delegated to a separate process.

     参见
     ....

     *note 接口选项: 134a. for equivalent functionality on the command
     line (‘python path/to/script’).

     3.2 新版功能.

     在 3.4 版更改: Updated to take advantage of the module spec feature
     added by PEP 451(5).  This allows ‘__cached__’ to be set correctly
     in the case where ‘__main__’ is imported from a valid sys.path
     entry rather than being executed directly.

参见
....

PEP 338(6) – 将模块作为脚本执行

     PEP 由 Nick Coghlan 撰写并实现。

PEP 366(7) – Main module explicit relative imports

     PEP 由 Nick Coghlan 撰写并实现。

PEP 451(8) – A ModuleSpec Type for the Import System

     PEP written and implemented by Eric Snow

*note 命令行与环境: fba. - CPython command line details

The *note importlib.import_module(): b1b. function

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/runpy.py

   (2) https://www.python.org/dev/peps/pep-0302

   (3) https://www.python.org/dev/peps/pep-3147

   (4) https://www.python.org/dev/peps/pep-0451

   (5) https://www.python.org/dev/peps/pep-0451

   (6) https://www.python.org/dev/peps/pep-0338

   (7) https://www.python.org/dev/peps/pep-0366

   (8) https://www.python.org/dev/peps/pep-0451


File: python.info,  Node: importlib --- import 的实现,  Next: Using importlib metadata,  Prev: runpy --- Locating and executing Python modules,  Up: 导入模块

5.31.5 ‘importlib’ — ‘import’ 的实现
------------------------------------

3.1 新版功能.

`源代码' Lib/importlib/__init__.py(1)

__________________________________________________________________

* Menu:

* 概述: 概述<13>.
* 函数: 函数<10>.
* importlib.abc —— 关于导入的抽象基类: importlib abc —— 关于导入的抽象基类.
* importlib.resources: importlib resources -- 资源. 资源
* importlib.machinery: importlib machinery -- Importers and path hooks. Importers and path hooks
* importlib.util: importlib util -- Utility code for importers. Utility code for importers
* 例子: 例子<29>.

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/importlib/__init__.py


File: python.info,  Node: 概述<13>,  Next: 函数<10>,  Up: importlib --- import 的实现

5.31.5.1 概述
.............

*note importlib: 9b. 包的目的有两个。 第一个目的是在 Python 源代码中提供
*note import: c25. 语句的实现（并且因此而扩展 *note __import__(): 619. 函
数）。 这提供了一个可移植到任何 Python 解释器的 ‘import’ 实现。 相比使用
Python 以外的编程语言实现方式，这一实现更加易于理解。

第二个目的是实现 *note import: c25. 的部分被公开在这个包中，使得用户更容
易创建他们自己的自定义对象 (通常被称为 *note importer: 14cc.) 来参与到导
入过程中。

参见
....

*note import 语句: c25.

     *note import: c25. 语句的语言参考

包规格说明(1)

     包的初始规范。自从编写这个文档开始，一些语义已经发生改变了（比如基
     于 *note sys.modules: f36. 中 ‘None’ 的重定向）。

*note __import__(): 9b6. 函数

     *note import: c25. 语句是这个函数的语法糖。

PEP 235(2)

     在忽略大小写的平台上进行导入

PEP 263(3)

     定义 Python 源代码编码

PEP 302(4)

     新导入钩子

PEP 328(5)

     导入：多行和绝对/相对

PEP 366(6)

     主模块显式相对导入

PEP 420(7)

     隐式命名空间包

PEP 451(8)

     导入系统的一个模块规范类型

PEP 488(9)

     消除PYO文件

PEP 489(10)

     多阶段扩展模块初始化

PEP 552(11)

     确定性的 pyc 文件

PEP 3120(12)

     使用 UTF-8 作为默认的源编码

PEP 3147(13)

     PYC 仓库目录

   ---------- Footnotes ----------

   (1) https://www.python.org/doc/essays/packages/

   (2) https://www.python.org/dev/peps/pep-0235

   (3) https://www.python.org/dev/peps/pep-0263

   (4) https://www.python.org/dev/peps/pep-0302

   (5) https://www.python.org/dev/peps/pep-0328

   (6) https://www.python.org/dev/peps/pep-0366

   (7) https://www.python.org/dev/peps/pep-0420

   (8) https://www.python.org/dev/peps/pep-0451

   (9) https://www.python.org/dev/peps/pep-0488

   (10) https://www.python.org/dev/peps/pep-0489

   (11) https://www.python.org/dev/peps/pep-0552

   (12) https://www.python.org/dev/peps/pep-3120

   (13) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: 函数<10>,  Next: importlib abc —— 关于导入的抽象基类,  Prev: 概述<13>,  Up: importlib --- import 的实现

5.31.5.2 函数
.............

 -- 函数: importlib.__import__ (name, globals=None, locals=None,
          fromlist=(), level=0)

     内置 *note __import__(): 619. 函数的实现。

          注解: 程序式地导入模块应该使用 *note import_module(): b1b. 而
          不是这个函数。

 -- 函数: importlib.import_module (name, package=None)

     导入一个模块。参数 `name' 指定了以绝对或相对导入方式导入什么模块 (比
     如要么像这样 ‘pkg.mod’ 或者这样 ‘..mod’)。如果参数 name 使用相对导
     入的方式来指定，那么那个参数 `packages' 必须设置为那个包名，这个包
     名作为解析这个包名的锚点 (比如 ‘import_module('..mod',
     'pkg.subpkg')’ 将会导入 ‘pkg.mod’)。

     *note import_module(): b1b. 函数是一个对 *note
     importlib.__import__(): 9b6. 进行简化的包装器。 这意味着该函数的所
     有主义都来自于 *note importlib.__import__(): 9b6.。 这两个函数之间
     最重要的不同点在于 *note import_module(): b1b. 返回指定的包或模块
     (例如 ‘pkg.mod’)，而 *note __import__(): 619. 返回最高层级的包或模
     块 (例如 ‘pkg’)。

     如果动态导入一个自从解释器开始执行以来被创建的模块（即创建了一个
     Python 源代码文件），为了让导入系统知道这个新模块，可能需要调用
     *note invalidate_caches(): 4a4.。

     在 3.3 版更改: 父包会被自动导入。

 -- 函数: importlib.find_loader (name, path=None)

     查找一个模块的加载器，可选择地在指定的 `path' 里面。如果这个模块是
     在 *note sys.modules: f36.，那么返回 ‘sys.modules[name].__loader__’
     (除非这个加载器是 ‘None’ 或者是没有被设置， 在这样的情况下，会引起
     *note ValueError: 1fc. 异常）。 否则使用 *note sys.meta_path: 5ef.
     的一次搜索就结束。如果未发现加载器，则返回 ‘None’。

     点状的名称没有使得它父包或模块隐式地导入，因为它需要加载它们并且可
     能不需要。为了适当地导入一个子模块，需要导入子模块的所有父包并且使
     用正确的参数提供给 `path'。

     3.3 新版功能.

     在 3.4 版更改: 如果没有设置 ‘__loader__’，会引起 *note ValueError:
     1fc. 异常，就像属性设置为 ‘None’ 的时候一样。

     3.4 版后已移除: 使用 *note importlib.util.find_spec(): 940. 来代替
     。

 -- 函数: importlib.invalidate_caches ()

     使查找器存储在 *note sys.meta_path: 5ef. 中的内部缓存无效。如果一个
     查找器实现了 ‘invalidate_caches()’，那么它会被调用来执行那个无效过
     程。 如果创建/安装任何模块，同时正在运行的程序是为了保证所有的查找
     器知道新模块的存在，那么应该调用这个函数。

     3.3 新版功能.

 -- 函数: importlib.reload (module)

     重新加载之前导入的 `module'。那个参数必须是一个模块对象，所以它之前
     必须已经成功导入了。这样做是有用的，如果使用外部编辑器编已经辑过了
     那个模块的源代码文件并且想在退出 Python 解释器之前试验这个新版本的
     模块。函数的返回值是那个模块对象（如果重新导入导致一个不同的对象放
     置在 *note sys.modules: f36. 中，那么那个模块对象是有可能会不同）。

     当执行 *note reload(): 3a1. 的时候：

        * Python 模块的代码会被重新编译并且那个模块级的代码被重新执行，
          通过重新使用一开始加载那个模块的 *note loader: 14cb.，定义一个
          新的绑定在那个模块字典中的名称的对象集合。扩展模块的‘‘init‘‘函
          数不会被调用第二次。

        * 与Python中的所有的其它对象一样，旧的对象只有在它们的引用计数为
          0之后才会被回收。

        * 模块命名空间中的名称重新指向任何新的或更改后的对象。

        * 其他旧对象的引用（例如那个模块的外部名称）不会被重新绑定到引用
          的新对象的，并且如果有需要，必须在出现的每个命名空间中进行更新
          。

     有一些其他注意事项：

     当一个模块被重新加载的时候，它的字典（包含了那个模块的全区变量）会
     被保留。名称的重新定义会覆盖旧的定义，所以通常来说这不是问题。如果
     一个新模块没有定义在旧版本模块中定义的名称，则将保留旧版本中的定义
     。这一特性可用于作为那个模块的优点，如果它维护一个全局表或者对象的
     缓存 —— 使用 *note try: d7a. 语句，就可以测试表的存在并且跳过它的初
     始化，如果有需要的话:

          try:
              cache
          except NameError:
              cache = {}

     重新加载内置的或者动态加载模块，通常来说不是很有用处。不推荐重新加
     载"*note sys: fe.，*note __main__: 1.，*note builtins: 13. 和其它关
     键模块。在很多例子中，扩展模块并不是设计为不止一次的初始化，并且当
     重新加载时，可能会以任意方式失败。

     如果一个模块使用 *note from: c4d. ...  *note import: c25. ... 导入
     的对象来自另外一个模块，给其它模块调用 *note reload(): 3a1. 不会重
     新定义来自这个模块的对象 —— 解决这个问题的一种方式是重新执行 ‘from’
     语句，另一种方式是使用 ‘import’ 和限定名称(`module.name')来代替。

     如果一个模块创建一个类的实例，重新加载定义那个类的模块不影响那些实
     例的方法定义———它们继续使用旧类中的定义。对于子类来说同样是正确的。

     3.4 新版功能.

     在 3.7 版更改: 当重新加载的那个模块缺少 ‘ModuleSpec’ 的时候，会引起
     *note ModuleNotFoundError: 3a2. 异常。


File: python.info,  Node: importlib abc —— 关于导入的抽象基类,  Next: importlib resources -- 资源,  Prev: 函数<10>,  Up: importlib --- import 的实现

5.31.5.3 ‘importlib.abc’ —— 关于导入的抽象基类
..............................................

`源代码：' Lib/importlib/abc.py(1)

__________________________________________________________________

The *note importlib.abc: 9c. module contains all of the core abstract
base classes used by *note import: c25.  Some subclasses of the core
abstract base classes are also provided to help in implementing the core
ABCs.

ABC 类的层次结构：

     object
      +-- Finder (deprecated)
      |    +-- MetaPathFinder
      |    +-- PathEntryFinder
      +-- Loader
           +-- ResourceLoader --------+
           +-- InspectLoader          |
                +-- ExecutionLoader --+
                                      +-- FileLoader
                                      +-- SourceLoader

 -- 类: importlib.abc.Finder

     代表 *note finder: 14ca. 的一个抽象基类

     3.3 版后已移除: 使用 *note MetaPathFinder: 9bb. 或 *note
     PathEntryFinder: 9bc. 来代替。

      -- 方法: abstractmethod find_module (fullname, path=None)

          为指定的模块查找 *note loader: 14cb. 定义的抽象方法。本来是在
          PEP 302(2) 指定的，这个方法是在 *note sys.meta_path: 5ef. 和基
          于路径的导入子系统中使用。

          在 3.4 版更改: 当被调用的时候，返回 ‘None’ 而不是引发 *note
          NotImplementedError: 617.。

 -- 类: importlib.abc.MetaPathFinder

     代表 *note meta path finder: 9b9. 的一个抽象基类。 为了保持兼容性，
     这是 *note Finder: 9bd. 的一个子类。

     3.3 新版功能.

      -- 方法: find_spec (fullname, path, target=None)

          An abstract method for finding a *note spec: 3641. for the
          specified module.  If this is a top-level import, `path' will
          be ‘None’.  Otherwise, this is a search for a subpackage or
          module and `path' will be the value of *note __path__: 129f.
          from the parent package.  If a spec cannot be found, ‘None’ is
          returned.  When passed in, ‘target’ is a module object that
          the finder may use to make a more educated guess about what
          spec to return.  *note importlib.util.spec_from_loader():
          3765. may be useful for implementing concrete
          ‘MetaPathFinders’.

          3.4 新版功能.

      -- 方法: find_module (fullname, path)

          一个用于查找指定的模块中 *note loader: 14cb. 的遗留方法。如果
          这是最高层级的导入，`path' 的值将会是 ‘None’。否则，这是一个查
          找子包或者模块的方法，并且 `path' 的值将会是来自父包的 *note
          __path__: 129f. 的值。如果未发现加载器，返回 ‘None’。

          如果定义了 *note find_spec(): 46b. 方法，则提供了向后兼容的功
          能。

          在 3.4 版更改: 当调用这个方法的时候返回 ‘None’ 而不是引发
          *note NotImplementedError: 617.。 可以使用 *note find_spec():
          46b. 来提供功能。

          3.4 版后已移除: 使用 *note find_spec(): 46b. 来代替。

      -- 方法: invalidate_caches ()

          当被调用的时候，一个可选的方法应该将查找器使用的任何内部缓存进
          行无效。将在 *note sys.meta_path: 5ef. 上的所有查找器的缓存进
          行无效的时候，这个函数被 *note importlib.invalidate_caches():
          4a4. 所使用。

          在 3.4 版更改: 当方法被调用的时候，方法返回是 ‘None’ 而不是
          ‘NotImplemented’ 。

 -- 类: importlib.abc.PathEntryFinder

     *note path entry finder: 9ba. 的一个抽象基类。 尽管这个基类和 *note
     MetaPathFinder: 9bb. 有一些相似之处，但是 ‘PathEntryFinder’ 只在由
     ‘PathFinder’ 提供的基于路径导入子系统中使用。 这个抽象基类是 *note
     Finder: 9bd. 的一个子类，仅仅是因为兼容性的原因。

     3.3 新版功能.

      -- 方法: find_spec (fullname, target=None)

          An abstract method for finding a *note spec: 3641. for the
          specified module.  The finder will search for the module only
          within the *note path entry: 14df. to which it is assigned.
          If a spec cannot be found, ‘None’ is returned.  When passed
          in, ‘target’ is a module object that the finder may use to
          make a more educated guess about what spec to return.  *note
          importlib.util.spec_from_loader(): 3765. may be useful for
          implementing concrete ‘PathEntryFinders’.

          3.4 新版功能.

      -- 方法: find_loader (fullname)

          一个用于在模块中查找一个 *note loader: 14cb. 的遗留方法。 返回
          一个 ‘(loader, portion)’ 的2元组，‘portion’ 是一个贡献给命名空
          间包部分的文件系统位置的序列。 加载器可能是 ‘None’，同时正在指
          定的 ‘portion’ 表示的是贡献给命名空间包的文件系统位置。
          ‘portion’ 可以使用一个空列表来表示加载器不是命名空间包的一部分
          。 如果 ‘loader’ 是 ‘None’ 并且 ‘portion’ 是一个空列表，那么命
          名空间包中无加载器或者文件系统位置可查找到（即在那个模块中未能
          找到任何东西）。

          如果定义了 *note find_spec(): 46d. ，则提供了向后兼容的功能。

          在 3.4 版更改: 返回 ‘(None, [])’ 而不是引发 *note
          NotImplementedError: 617.。 当可于提供相应的功能的时候，使用
          *note find_spec(): 46d.。

          3.4 版后已移除: 使用 *note find_spec(): 46d. 来代替。

      -- 方法: find_module (fullname)

          ‘Finder.find_module`的具体实现，该方法等价于
          ``self.find_loader(fullname)[0]`()’。

          3.4 版后已移除: 使用 *note find_spec(): 46d. 来代替。

      -- 方法: invalidate_caches ()

          当被调用的时候，一个可选的方法应该将查找器使用的任何内部缓存进
          行无效。当将所有缓存的查找器的缓存进行无效的时候，该函数被
          ‘PathFinder.invalidate_caches()’ 使用。

 -- 类: importlib.abc.Loader

     *note loader: 14cb. 的抽象基类。 关于一个加载器的实际定义请查看 PEP
     302(3)。

     加载器想要支持资源读取应该实现一个由 *note
     importlib.abc.ResourceReader: 34b. 指定的
     ‘‘get_resource_reader(fullname)‘‘ 方法。

     在 3.7 版更改: 引入了可选的 ‘get_resource_reader()’ 方法。

      -- 方法: create_module (spec)

          当导入一个模块的时候，一个返回将要使用的那个模块对象的方法。这
          个方法可能返回 ‘None’ ，这暗示着应该发生默认的模块创建语义。"

          3.4 新版功能.

          在 3.5 版更改: 从 Python 3.6 开始，当定义了 *note
          exec_module(): 5ed. 的时候，这个方法将不会是可选的。

      -- 方法: exec_module (module)

          当一个模块被导入或重新加载时，一个抽象方法在它自己的命名空间中
          执行那个模块。当调用 ‘exec_module()’ 的时候，那个模块应该已经
          被初始化 了。当这个方法存在时，必须定义 *note create_module():
          55d. 。

          3.4 新版功能.

          在 3.6 版更改: *note create_module(): 55d. 也必须被定义。

      -- 方法: load_module (fullname)

          用于加载一个模块的传统方法。如果这个模块不能被导入，将引起
          *note ImportError: 33d. 异常，否则返回那个被加载的模块。

          如果请求的模块已经存在 *note sys.modules: f36.，应该使用并且重
          新加载那个模块。 否则加载器应该是创建一个新的模块并且在任何家
          过程开始之前将这个新模块插入到 *note sys.modules: f36. 中，来
          阻止递归导入。 如果加载器插入了一个模块并且加载失败了，加载器
          必须从 *note sys.modules: f36. 中将这个模块移除。在加载器开始
          执行之前，已经在 *note sys.modules: f36. 中的模块应该被忽略 (查
          看 *note importlib.util.module_for_loader(): 94a.)。

          加载器应该在模块上面设置几个属性。（要知道当重新加载一个模块的
          时候，那些属性某部分可以改变）：

             - 
               *note __name__: d1a.

                    模块的名字

             - 
               *note __file__: ec7.

                    模块数据存储的路径(不是为了内置的模块而设置)

             - 
               *note __cached__: b3a.

                    被存储或应该被存储的模块的编译版本的路径（当这个属性
                    不恰当的时候不设置）。

             - 
               *note __path__: 129f.

                    指定在一个包中搜索路径的一个字符串列表。这个属性不在
                    模块上面进行设置。

             - 
               *note __package__: 95d.

                    The fully-qualified name of the package under which
                    the module was loaded as a submodule (or the empty
                    string for top-level modules).  For packages, it is
                    the same as *note __name__: d1a.  The *note
                    importlib.util.module_for_loader(): 94a. decorator
                    can handle the details for *note __package__: 95d.

             - 
               *note __loader__: 95e.

                    用来加载那个模块的加载器。 *note
                    importlib.util.module_for_loader(): 94a. 装饰器可以
                    处理 *note __package__: 95d. 的细节。

          当 *note exec_module(): 5ed. 可用的时候，那么则提供了向后兼容
          的功能。

          在 3.4 版更改: 当这个方法被调用的时候，触发 *note ImportError:
          33d. 异常而不是 *note NotImplementedError: 617.。当 *note
          exec_module(): 5ed. 可用的时候，使用它的功能。

          3.4 版后已移除: 加载模块推荐的使用的 API 是 *note
          exec_module(): 5ed. (和 *note create_module(): 55d.)。 加载器
          应该实现它而不是 load_module()。 当 exec_module() 被实现的时候
          ，导入机制关心的是 load_module() 所有其他的责任。

      -- 方法: module_repr (module)

          一个遗留方法，在实现时计算并返回给定模块的 repr，作为字符串。
          模块类型的默认 repr() 将根据需要使用此方法的结果。

          3.3 新版功能.

          在 3.4 版更改: 是可选的方法而不是一个抽象方法。

          3.4 版后已移除: 现在导入机制会自动地关注这个方法。

 -- 类: importlib.abc.ResourceReader

     提供读取 `resources' 能力的一个 *note abstract base class: b3b. 。

     从这个 ABC 的视角出发，`resource' 指一个包附带的二进制文件。常见的
     如在包的 ‘__init__.py’ 文件旁的数据文件。这个类存在的目的是为了将对
     数据文件的访问进行抽象，这样包就和其数据文件的存储方式无关了。不论
     这些文件是存放在一个 zip 文件里还是直接在文件系统内。

     对于该类中的任一方法，`resource' 参数的值都需要是一个在概念上表示文
     件名称的 *note path-like object: 373.。 这意味着任何子目录的路径都
     不该出现在 `resouce' 参数值内。 因为对于阅读器而言，包的位置就代表
     着「目录」。 因此目录和文件名就分别对应于包和资源。 这也是该类的实
     例都需要和一个包直接关联（而不是潜在指代很多包或者一整个模块）的原
     因。

     想支持资源读取的加载器需要提供一个返回实现了此 ABC 的接口的
     ‘get_resource_reader(fullname)’ 方法。如果通过全名指定的模块不是一
     个包，这个方法应该返回 *note None: 158.。 当指定的模块是一个包时，
     应该只返回一个与这个抽象类ABC兼容的对象。

     3.7 新版功能.

      -- 方法: abstractmethod open_resource (resource)

          返回一个打开的 *note file-like object: 1c7a. 用于 `resource' 的
          二进制读取。

          如果无法找到资源，将会引发 *note FileNotFoundError: 7c9.。

      -- 方法: abstractmethod resource_path (resource)

          返回 `resource' 的文件系统路径。

          如果资源并不实际存在于文件系统中，将会引发 *note
          FileNotFoundError: 7c9.。

      -- 方法: abstractmethod is_resource (name)

          如果*name* 被视作资源，则返回True。如果*name*不存在，则引发
          *note FileNotFoundError: 7c9. 异常。

      -- 方法: abstractmethod contents ()

          反回由字符串组成的 *note iterable: bb4.，表示这个包的所有内容
          。 请注意并不要求迭代器返回的所有名称都是实际的资源，例如返回
          *note is_resource(): 376a. 为假值的名称也是可接受的。

          允许非资源名字被返回是为了允许存储的一个包和它的资源的方式是已
          知先验的并且非资源名字会有用的情况。比如，允许返回子目录名字，
          目的是当得知包和资源存储在文件系统上面的时候，能够直接使用子目
          录的名字。

          这个抽象方法返回了一个不包含任何内容的可迭代对象。

 -- 类: importlib.abc.ResourceLoader

     一个 *note loader: 14cb. 的抽象基类，它实现了可选的 PEP 302(4) 协议
     用于从存储后端加载任意资源。

     3.7 版后已移除: 由于要支持使用 *note importlib.abc.ResourceReader:
     34b. 类来加载资源，这个 ABC 已经被弃用了。

      -- 方法: abstractmethod get_data (path)

          一个用于返回位于 `path' 的字节数据的抽象方法。有一个允许存储任
          意数据的类文件存储后端的加载器能够实现这个抽象方法来直接访问这
          些被存储的数据。如果不能够找到 `path'，则会引发 *note OSError:
          1d4. 异常。`path' 被希望使用一个模块的 ‘__file’ 属性或来自一个
          包的 *note __path__: 129f. 来构建。

          在 3.4 版更改: 引发 *note OSError: 1d4. 异常而不是 *note
          NotImplementedError: 617. 异常。

 -- 类: importlib.abc.InspectLoader

     一个实现加载器检查模块可选的 PEP 302(5) 协议的 *note loader: 14cb.
     的抽象基类。

      -- 方法: get_code (fullname)

          返回一个模块的代码对象，或如果模块没有一个代码对象（例如，对于
          内置的模块来说，这会是这种情况），则为 ‘None’。 如果加载器不能
          找到请求的模块，则引发 *note ImportError: 33d. 异常。

               注解: 当这个方法有一个默认的实现的时候，出于性能方面的考
               虑，如果有可能的话，建议覆盖它。

          在 3.4 版更改: 不再抽象并且提供一个具体的实现。

      -- 方法: abstractmethod get_source (fullname)

          一个返回模块源的抽象方法。使用 *note universal newlines: 5fd.
          作为文本字符串被返回，将所有可识别行分割符翻译成 ‘'\n'’ 字符。
          如果没有可用的源（例如，一个内置模块），则返回 ‘None’。 如果加
          载器不能找到指定的模块，则引发 *note ImportError: 33d. 异常。

          在 3.4 版更改: 引发 *note ImportError: 33d. 而不是 *note
          NotImplementedError: 617.。

      -- 方法: is_package (fullname)

          一个抽象方法，如果这个模块是一个包则返回真值，否则返回假值。 如
          果 *note loader: 14cb. 不能找到这个模块，则引发 *note
          ImportError: 33d.。

          在 3.4 版更改: 引发 *note ImportError: 33d. 而不是 *note
          NotImplementedError: 617.。

      -- 方法: static source_to_code (data, path='<string>')

          创建一个来自Python源码的代码对象。

          参数 `data' 可以是任意 *note compile(): 1b5. 函数支持的类型（
          例如字符串或字节串）。 参数 `path' 应该是源代码来源的路径，这
          可能是一个抽象概念（例如位于一个 zip 文件中）。

          在有后续代码对象的情况下，可以在一个模块中通过运行‘‘exec(code,
          module.__dict__)‘‘来执行它。

          3.4 新版功能.

          在 3.5 版更改: 使得这个方法变成静态的。

      -- 方法: exec_module (module)

          *note Loader.exec_module(): 5ed. 的实现。

          3.4 新版功能.

      -- 方法: load_module (fullname)

          *note Loader.load_module(): 5ec. 的实现。

          3.4 版后已移除: 使用 *note exec_module(): 947. 来代替。

 -- 类: importlib.abc.ExecutionLoader

     一个继承自 *note InspectLoader: 869. 的抽象基类，当被实现时，帮助一
     个模块作为脚本来执行。 这个抽象基类表示可选的 PEP 302(6) 协议。

      -- 方法: abstractmethod get_filename (fullname)

          一个用来为指定模块返回 *note __file__: ec7. 的值的抽象方法。如
          果无路径可用，则引发 *note ImportError: 33d.。

          如果源代码可用，那么这个方法返回源文件的路径，不管是否是用来加
          载模块的字节码。

          在 3.4 版更改: 引发 *note ImportError: 33d. 而不是 *note
          NotImplementedError: 617.。

 -- 类: importlib.abc.FileLoader (fullname, path)

     一个继承自 *note ResourceLoader: 46e. 和 *note ExecutionLoader:
     376c.，提供 *note ResourceLoader.get_data(): 3753. 和 *note
     ExecutionLoader.get_filename(): 376d. 具体实现的抽象基类。

     参数*fullname*是加载器要处理的模块的完全解析的名字。参数*path*是模
     块文件的路径。

     3.3 新版功能.

      -- 属性: name

          加载器可以处理的模块的名字。

      -- 属性: path

          模块的文件路径

      -- 方法: load_module (fullname)

          调用super的‘‘load_module()‘‘。

          3.4 版后已移除: 使用 *note Loader.exec_module(): 5ed. 来代替。

      -- 方法: abstractmethod get_filename (fullname)

          返回 *note path: 376f.。

      -- 方法: abstractmethod get_data (path)

          读取 `path' 作为二进制文件并且返回来自它的字节数据。

 -- 类: importlib.abc.SourceLoader

     一个用于实现源文件（和可选地字节码）加载的抽象基类。这个类继承自
     *note ResourceLoader: 46e. 和 *note ExecutionLoader: 376c.，需要实
     现：

        * *note ResourceLoader.get_data(): 3753.

        * 
          *note ExecutionLoader.get_filename(): 376d.

               应该是只返回源文件的路径；不支持无源加载。

     由这个类定义的抽象方法用来添加可选的字节码文件支持。不实现这些可选
     的方法（或导致它们引发 *note NotImplementedError: 617. 异常）导致这
     个加载器只能与源代码一起工作。 实现这些方法允许加载器能与源 `和' 字
     节码文件一起工作。不允许只提供字节码的 `无源式' 加载。字节码文件是
     通过移除 Python 编译器的解析步骤来加速加载的优化，并且因此没有开放
     出字节码专用的 API。

      -- 方法: path_stats (path)

          返回一个包含关于指定路径的元数据的 *note dict: 1b9. 的可选的抽
          象方法。 支持的字典键有：

             - ‘'mtime'’ (必选项): 一个表示源码修改时间的整数或浮点数；

             - ‘'size'’ (可选项)：源码的字节大小。

          字典中任何其他键会被忽略，以允许将来的扩展。 如果不能处理该路
          径，则会引发 *note OSError: 1d4.。

          3.3 新版功能.

          在 3.4 版更改: 引发 *note OSError: 1d4. 而不是 *note
          NotImplemented: 855.。

      -- 方法: path_mtime (path)

          返回指定文件路径修改时间的可选的抽象方法。

          3.3 版后已移除: 在有了 *note path_stats(): af4. 的情况下，这个
          方法被弃用了。 没必要去实现它了，但是为了兼容性，它依然处于可
          用状态。 如果文件路径不能被处理，则引发 *note OSError: 1d4. 异
          常。

          在 3.4 版更改: 引发 *note OSError: 1d4. 而不是 *note
          NotImplemented: 855.。

      -- 方法: set_data (path, data)

          往一个文件路径写入指定字节的的可选的抽象方法。任何中间不存在的
          目录不会被自动创建。

          由于路径是只读的，当写入的路径产生错误时（*note errno.EACCES:
          2254./*note PermissionError: 608.），不会传播异常。

          在 3.4 版更改: 当被调用时，不再引起 *note NotImplementedError:
          617. 异常。

      -- 方法: get_code (fullname)

          *note InspectLoader.get_code(): 86a. 的具体实现。

      -- 方法: exec_module (module)

          *note Loader.exec_module(): 5ed. 的具体实现。

          3.4 新版功能.

      -- 方法: load_module (fullname)

          Concrete implementation of *note Loader.load_module(): 5ec.

          3.4 版后已移除: 使用 *note exec_module(): 948. 来代替。

      -- 方法: get_source (fullname)

          *note InspectLoader.get_source(): 86e. 的具体实现。

      -- 方法: is_package (fullname)

          *note InspectLoader.is_package(): 376b. 的具体实现。一个模块被
          确定为一个包的条件是：它的文件路径（由 *note
          ExecutionLoader.get_filename(): 376d. 提供）当文件扩展名被移除
          时是一个命名为 ‘__init__’ 的文件，`并且' 这个模块名字本身不是
          以‘‘__init__‘‘结束。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/importlib/abc.py

   (2) https://www.python.org/dev/peps/pep-0302

   (3) https://www.python.org/dev/peps/pep-0302

   (4) https://www.python.org/dev/peps/pep-0302

   (5) https://www.python.org/dev/peps/pep-0302

   (6) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: importlib resources -- 资源,  Next: importlib machinery -- Importers and path hooks,  Prev: importlib abc —— 关于导入的抽象基类,  Up: importlib --- import 的实现

5.31.5.4 ‘importlib.resources’ – 资源
.....................................

`源码：' Lib/importlib/resources.py(1)

__________________________________________________________________

3.7 新版功能.

这个模块使得Python的导入系统提供了访问*包*内的*资源*的功能。如果能够导入
一个包，那么就能够访问那个包里面的资源。资源可以以二进制或文本模式方式被
打开或读取。

资源非常类似于目录内部的文件，要牢记的是这仅仅是一个比喻。资源和包不是与
文件系统上的物理文件和目录一样存在着。

     注解: This module provides functionality similar to
     pkg_resources(2) Basic Resource Access(3) without the performance
     overhead of that package.  This makes reading resources included in
     packages easier, with more stable and consistent semantics.

     The standalone backport of this module provides more information on
     using importlib.resources(4) and migrating from pkg_resources to
     importlib.resources(5).

加载器想要支持资源读取应该实现一个由 *note importlib.abc.ResourceReader:
34b. 指定的‘‘get_resource_reader(fullname)‘‘ 方法。

The following types are defined.

 -- 数据: importlib.resources.Package

     The ‘Package’ type is defined as ‘Union[str, ModuleType]’.  This
     means that where the function describes accepting a ‘Package’, you
     can pass in either a string or a module.  Module objects must have
     a resolvable ‘__spec__.submodule_search_locations’ that is not
     ‘None’.

 -- 数据: importlib.resources.Resource

     This type describes the resource names passed into the various
     functions in this package.  This is defined as ‘Union[str,
     os.PathLike]’.

The following functions are available.

 -- 函数: importlib.resources.open_binary (package, resource)

     Open for binary reading the `resource' within `package'.

     `package' is either a name or a module object which conforms to the
     ‘Package’ requirements.  `resource' is the name of the resource to
     open within `package'; it may not contain path separators and it
     may not have sub-resources (i.e.  it cannot be a directory).  This
     function returns a ‘typing.BinaryIO’ instance, a binary I/O stream
     open for reading.

 -- 函数: importlib.resources.open_text (package, resource,
          encoding='utf-8', errors='strict')

     Open for text reading the `resource' within `package'.  By default,
     the resource is opened for reading as UTF-8.

     `package' is either a name or a module object which conforms to the
     ‘Package’ requirements.  `resource' is the name of the resource to
     open within `package'; it may not contain path separators and it
     may not have sub-resources (i.e.  it cannot be a directory).
     `encoding' and `errors' have the same meaning as with built-in
     *note open(): 4f8.

     This function returns a ‘typing.TextIO’ instance, a text I/O stream
     open for reading.

 -- 函数: importlib.resources.read_binary (package, resource)

     Read and return the contents of the `resource' within `package' as
     ‘bytes’.

     `package' is either a name or a module object which conforms to the
     ‘Package’ requirements.  `resource' is the name of the resource to
     open within `package'; it may not contain path separators and it
     may not have sub-resources (i.e.  it cannot be a directory).  This
     function returns the contents of the resource as *note bytes: 33a.

 -- 函数: importlib.resources.read_text (package, resource,
          encoding='utf-8', errors='strict')

     Read and return the contents of `resource' within `package' as a
     ‘str’.  By default, the contents are read as strict UTF-8.

     `package' is either a name or a module object which conforms to the
     ‘Package’ requirements.  `resource' is the name of the resource to
     open within `package'; it may not contain path separators and it
     may not have sub-resources (i.e.  it cannot be a directory).
     `encoding' and `errors' have the same meaning as with built-in
     *note open(): 4f8.  This function returns the contents of the
     resource as *note str: 339.

 -- 函数: importlib.resources.path (package, resource)

     Return the path to the `resource' as an actual file system path.
     This function returns a context manager for use in a *note with:
     6f2. statement.  The context manager provides a *note pathlib.Path:
     202. object.

     Exiting the context manager cleans up any temporary file created
     when the resource needs to be extracted from e.g.  a zip file.

     `package' is either a name or a module object which conforms to the
     ‘Package’ requirements.  `resource' is the name of the resource to
     open within `package'; it may not contain path separators and it
     may not have sub-resources (i.e.  it cannot be a directory).

 -- 函数: importlib.resources.is_resource (package, name)

     Return ‘True’ if there is a resource named `name' in the package,
     otherwise ‘False’.  Remember that directories are `not' resources!
     `package' is either a name or a module object which conforms to the
     ‘Package’ requirements.

 -- 函数: importlib.resources.contents (package)

     Return an iterable over the named items within the package.  The
     iterable returns *note str: 339. resources (e.g.  files) and
     non-resources (e.g.  directories).  The iterable does not recurse
     into subdirectories.

     `package' is either a name or a module object which conforms to the
     ‘Package’ requirements.

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/importlib/resources.py

   (2) https://setuptools.readthedocs.io/en/latest/pkg_resources.html

   (3) 
http://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access

   (4) http://importlib-resources.readthedocs.io/en/latest/using.html

   (5) 
http://importlib-resources.readthedocs.io/en/latest/migration.html


File: python.info,  Node: importlib machinery -- Importers and path hooks,  Next: importlib util -- Utility code for importers,  Prev: importlib resources -- 资源,  Up: importlib --- import 的实现

5.31.5.5 ‘importlib.machinery’ – Importers and path hooks
.........................................................

`Source code:' Lib/importlib/machinery.py(1)

__________________________________________________________________

This module contains the various objects that help *note import: c25.
find and load modules.

 -- 属性: importlib.machinery.SOURCE_SUFFIXES

     A list of strings representing the recognized file suffixes for
     source modules.

     3.3 新版功能.

 -- 属性: importlib.machinery.DEBUG_BYTECODE_SUFFIXES

     A list of strings representing the file suffixes for non-optimized
     bytecode modules.

     3.3 新版功能.

     3.5 版后已移除: Use *note BYTECODE_SUFFIXES: 3781. instead.

 -- 属性: importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES

     A list of strings representing the file suffixes for optimized
     bytecode modules.

     3.3 新版功能.

     3.5 版后已移除: Use *note BYTECODE_SUFFIXES: 3781. instead.

 -- 属性: importlib.machinery.BYTECODE_SUFFIXES

     A list of strings representing the recognized file suffixes for
     bytecode modules (including the leading dot).

     3.3 新版功能.

     在 3.5 版更改: The value is no longer dependent on ‘__debug__’.

 -- 属性: importlib.machinery.EXTENSION_SUFFIXES

     A list of strings representing the recognized file suffixes for
     extension modules.

     3.3 新版功能.

 -- 函数: importlib.machinery.all_suffixes ()

     Returns a combined list of strings representing all file suffixes
     for modules recognized by the standard import machinery.  This is a
     helper for code which simply needs to know if a filesystem path
     potentially refers to a module without needing any details on the
     kind of module (for example, *note inspect.getmodulename(): 5fb.).

     3.3 新版功能.

 -- 类: importlib.machinery.BuiltinImporter

     An *note importer: 14cc. for built-in modules.  All known built-in
     modules are listed in *note sys.builtin_module_names: 362b.  This
     class implements the *note importlib.abc.MetaPathFinder: 9bb. and
     *note importlib.abc.InspectLoader: 869. ABCs.

     Only class methods are defined by this class to alleviate the need
     for instantiation.

     在 3.5 版更改: As part of PEP 489(2), the builtin importer now
     implements ‘Loader.create_module()’ and ‘Loader.exec_module()’

 -- 类: importlib.machinery.FrozenImporter

     An *note importer: 14cc. for frozen modules.  This class implements
     the *note importlib.abc.MetaPathFinder: 9bb. and *note
     importlib.abc.InspectLoader: 869. ABCs.

     Only class methods are defined by this class to alleviate the need
     for instantiation.

     在 3.4 版更改: Gained ‘create_module()’ and ‘exec_module()’
     methods.

 -- 类: importlib.machinery.WindowsRegistryFinder

     *note Finder: 14ca. for modules declared in the Windows registry.
     This class implements the *note importlib.abc.MetaPathFinder: 9bb.
     ABC.

     Only class methods are defined by this class to alleviate the need
     for instantiation.

     3.3 新版功能.

     3.6 版后已移除: Use *note site: ec. configuration instead.  Future
     versions of Python may not enable this finder by default.

 -- 类: importlib.machinery.PathFinder

     A *note Finder: 14ca. for *note sys.path: 490. and package
     ‘__path__’ attributes.  This class implements the *note
     importlib.abc.MetaPathFinder: 9bb. ABC.

     Only class methods are defined by this class to alleviate the need
     for instantiation.

      -- 方法: classmethod find_spec (fullname, path=None, target=None)

          Class method that attempts to find a *note spec: 3641. for the
          module specified by `fullname' on *note sys.path: 490. or, if
          defined, on `path'.  For each path entry that is searched,
          *note sys.path_importer_cache: 4a5. is checked.  If a
          non-false object is found then it is used as the *note path
          entry finder: 9ba. to look for the module being searched for.
          If no entry is found in *note sys.path_importer_cache: 4a5,
          then *note sys.path_hooks: 964. is searched for a finder for
          the path entry and, if found, is stored in *note
          sys.path_importer_cache: 4a5. along with being queried about
          the module.  If no finder is ever found then ‘None’ is both
          stored in the cache and returned.

          3.4 新版功能.

          在 3.5 版更改: If the current working directory – represented
          by an empty string – is no longer valid then ‘None’ is
          returned but no value is cached in *note
          sys.path_importer_cache: 4a5.

      -- 方法: classmethod find_module (fullname, path=None)

          A legacy wrapper around *note find_spec(): 942.

          3.4 版后已移除: 使用 *note find_spec(): 942. 来代替。

      -- 方法: classmethod invalidate_caches ()

          Calls *note importlib.abc.PathEntryFinder.invalidate_caches():
          3767. on all finders stored in *note sys.path_importer_cache:
          4a5. that define the method.  Otherwise entries in *note
          sys.path_importer_cache: 4a5. set to ‘None’ are deleted.

          在 3.7 版更改: Entries of ‘None’ in *note
          sys.path_importer_cache: 4a5. are deleted.

     在 3.4 版更改: Calls objects in *note sys.path_hooks: 964. with the
     current working directory for ‘''’ (i.e.  the empty string).

 -- 类: importlib.machinery.FileFinder (path, *loader_details)

     A concrete implementation of *note importlib.abc.PathEntryFinder:
     9bc. which caches results from the file system.

     The `path' argument is the directory for which the finder is in
     charge of searching.

     The `loader_details' argument is a variable number of 2-item tuples
     each containing a loader and a sequence of file suffixes the loader
     recognizes.  The loaders are expected to be callables which accept
     two arguments of the module’s name and the path to the file found.

     The finder will cache the directory contents as necessary, making
     stat calls for each module search to verify the cache is not
     outdated.  Because cache staleness relies upon the granularity of
     the operating system’s state information of the file system, there
     is a potential race condition of searching for a module, creating a
     new file, and then searching for the module the new file
     represents.  If the operations happen fast enough to fit within the
     granularity of stat calls, then the module search will fail.  To
     prevent this from happening, when you create a module dynamically,
     make sure to call *note importlib.invalidate_caches(): 4a4.

     3.3 新版功能.

      -- 属性: path

          The path the finder will search in.

      -- 方法: find_spec (fullname, target=None)

          Attempt to find the spec to handle `fullname' within *note
          path: 3784.

          3.4 新版功能.

      -- 方法: find_loader (fullname)

          Attempt to find the loader to handle `fullname' within *note
          path: 3784.

      -- 方法: invalidate_caches ()

          Clear out the internal cache.

      -- 方法: classmethod path_hook (*loader_details)

          A class method which returns a closure for use on *note
          sys.path_hooks: 964.  An instance of *note FileFinder: 9be. is
          returned by the closure using the path argument given to the
          closure directly and `loader_details' indirectly.

          If the argument to the closure is not an existing directory,
          *note ImportError: 33d. is raised.

 -- 类: importlib.machinery.SourceFileLoader (fullname, path)

     A concrete implementation of *note importlib.abc.SourceLoader:
     3772. by subclassing *note importlib.abc.FileLoader: 9bf. and
     providing some concrete implementations of other methods.

     3.3 新版功能.

      -- 属性: name

          The name of the module that this loader will handle.

      -- 属性: path

          The path to the source file.

      -- 方法: is_package (fullname)

          Return ‘True’ if *note path: 3789. appears to be for a
          package.

      -- 方法: path_stats (path)

          Concrete implementation of *note
          importlib.abc.SourceLoader.path_stats(): af4.

      -- 方法: set_data (path, data)

          Concrete implementation of *note
          importlib.abc.SourceLoader.set_data(): 3773.

      -- 方法: load_module (name=None)

          Concrete implementation of *note
          importlib.abc.Loader.load_module(): 5ec. where specifying the
          name of the module to load is optional.

          3.6 版后已移除: Use *note importlib.abc.Loader.exec_module():
          5ed. instead.

 -- 类: importlib.machinery.SourcelessFileLoader (fullname, path)

     A concrete implementation of *note importlib.abc.FileLoader: 9bf.
     which can import bytecode files (i.e.  no source code files exist).

     Please note that direct use of bytecode files (and thus not source
     code files) inhibits your modules from being usable by all Python
     implementations or new versions of Python which change the bytecode
     format.

     3.3 新版功能.

      -- 属性: name

          The name of the module the loader will handle.

      -- 属性: path

          The path to the bytecode file.

      -- 方法: is_package (fullname)

          Determines if the module is a package based on *note path:
          378e.

      -- 方法: get_code (fullname)

          Returns the code object for *note name: 378d. created from
          *note path: 378e.

      -- 方法: get_source (fullname)

          Returns ‘None’ as bytecode files have no source when this
          loader is used.

      -- 方法: load_module (name=None)

     Concrete implementation of *note
     importlib.abc.Loader.load_module(): 5ec. where specifying the name
     of the module to load is optional.

     3.6 版后已移除: Use *note importlib.abc.Loader.exec_module(): 5ed.
     instead.

 -- 类: importlib.machinery.ExtensionFileLoader (fullname, path)

     A concrete implementation of *note importlib.abc.ExecutionLoader:
     376c. for extension modules.

     The `fullname' argument specifies the name of the module the loader
     is to support.  The `path' argument is the path to the extension
     module’s file.

     3.3 新版功能.

      -- 属性: name

          Name of the module the loader supports.

      -- 属性: path

          Path to the extension module.

      -- 方法: create_module (spec)

          Creates the module object from the given specification in
          accordance with PEP 489(3).

          3.5 新版功能.

      -- 方法: exec_module (module)

          Initializes the given module object in accordance with PEP
          489(4).

          3.5 新版功能.

      -- 方法: is_package (fullname)

          Returns ‘True’ if the file path points to a package’s
          ‘__init__’ module based on *note EXTENSION_SUFFIXES: 3783.

      -- 方法: get_code (fullname)

          Returns ‘None’ as extension modules lack a code object.

      -- 方法: get_source (fullname)

          Returns ‘None’ as extension modules do not have source code.

      -- 方法: get_filename (fullname)

          返回 *note path: 3793.。

          3.4 新版功能.

 -- 类: importlib.machinery.ModuleSpec (name, loader, *, origin=None,
          loader_state=None, is_package=None)

     A specification for a module’s import-system-related state.  This
     is typically exposed as the module’s ‘__spec__’ attribute.  In the
     descriptions below, the names in parentheses give the corresponding
     attribute available directly on the module object.  E.g.
     ‘module.__spec__.origin == module.__file__’.  Note however that
     while the `values' are usually equivalent, they can differ since
     there is no synchronization between the two objects.  Thus it is
     possible to update the module’s ‘__path__’ at runtime, and this
     will not be automatically reflected in
     ‘__spec__.submodule_search_locations’.

     3.4 新版功能.

      -- 属性: name

     (‘__name__’)

     A string for the fully-qualified name of the module.

      -- 属性: loader

     (‘__loader__’)

     The *note Loader: 14cb. that should be used when loading the
     module.  *note Finders: 14ca. should always set this.

      -- 属性: origin

     (‘__file__’)

     Name of the place from which the module is loaded, e.g.  "builtin"
     for built-in modules and the filename for modules loaded from
     source.  Normally "origin" should be set, but it may be ‘None’ (the
     default) which indicates it is unspecified (e.g.  for namespace
     packages).

      -- 属性: submodule_search_locations

     (‘__path__’)

     List of strings for where to find submodules, if a package (‘None’
     otherwise).

      -- 属性: loader_state

     Container of extra module-specific data for use during loading (or
     ‘None’).

      -- 属性: cached

     (‘__cached__’)

     String for where the compiled module should be stored (or ‘None’).

      -- 属性: parent

     (‘__package__’)

     (Read-only) The fully-qualified name of the package under which the
     module should be loaded as a submodule (or the empty string for
     top-level modules).  For packages, it is the same as *note
     __name__: d1a.

      -- 属性: has_location

     Boolean indicating whether or not the module’s "origin" attribute
     refers to a loadable location.

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/importlib/machinery.py

   (2) https://www.python.org/dev/peps/pep-0489

   (3) https://www.python.org/dev/peps/pep-0489

   (4) https://www.python.org/dev/peps/pep-0489


File: python.info,  Node: importlib util -- Utility code for importers,  Next: 例子<29>,  Prev: importlib machinery -- Importers and path hooks,  Up: importlib --- import 的实现

5.31.5.6 ‘importlib.util’ – Utility code for importers
......................................................

`Source code:' Lib/importlib/util.py(1)

__________________________________________________________________

This module contains the various objects that help in the construction
of an *note importer: 14cc.

 -- 属性: importlib.util.MAGIC_NUMBER

     The bytes which represent the bytecode version number.  If you need
     help with loading/writing bytecode then consider *note
     importlib.abc.SourceLoader: 3772.

     3.4 新版功能.

 -- 函数: importlib.util.cache_from_source (path, debug_override=None,
          *, optimization=None)

     Return the PEP 3147(2)/ PEP 488(3) path to the byte-compiled file
     associated with the source `path'.  For example, if `path' is
     ‘/foo/bar/baz.py’ the return value would be
     ‘/foo/bar/__pycache__/baz.cpython-32.pyc’ for Python 3.2.  The
     ‘cpython-32’ string comes from the current magic tag (see
     ‘get_tag()’; if ‘sys.implementation.cache_tag’ is not defined then
     *note NotImplementedError: 617. will be raised).

     The `optimization' parameter is used to specify the optimization
     level of the bytecode file.  An empty string represents no
     optimization, so ‘/foo/bar/baz.py’ with an `optimization' of ‘''’
     will result in a bytecode path of
     ‘/foo/bar/__pycache__/baz.cpython-32.pyc’.  ‘None’ causes the
     interpreter’s optimization level to be used.  Any other value’s
     string representation is used, so ‘/foo/bar/baz.py’ with an
     `optimization' of ‘2’ will lead to the bytecode path of
     ‘/foo/bar/__pycache__/baz.cpython-32.opt-2.pyc’.  The string
     representation of `optimization' can only be alphanumeric, else
     *note ValueError: 1fc. is raised.

     The `debug_override' parameter is deprecated and can be used to
     override the system’s value for ‘__debug__’.  A ‘True’ value is the
     equivalent of setting `optimization' to the empty string.  A
     ‘False’ value is the same as setting `optimization' to ‘1’.  If
     both `debug_override' an `optimization' are not ‘None’ then *note
     TypeError: 193. is raised.

     3.4 新版功能.

     在 3.5 版更改: The `optimization' parameter was added and the
     `debug_override' parameter was deprecated.

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: importlib.util.source_from_cache (path)

     Given the `path' to a PEP 3147(4) file name, return the associated
     source code file path.  For example, if `path' is
     ‘/foo/bar/__pycache__/baz.cpython-32.pyc’ the returned path would
     be ‘/foo/bar/baz.py’.  `path' need not exist, however if it does
     not conform to PEP 3147(5) or PEP 488(6) format, a *note
     ValueError: 1fc. is raised.  If ‘sys.implementation.cache_tag’ is
     not defined, *note NotImplementedError: 617. is raised.

     3.4 新版功能.

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: importlib.util.decode_source (source_bytes)

     Decode the given bytes representing source code and return it as a
     string with universal newlines (as required by *note
     importlib.abc.InspectLoader.get_source(): 86e.).

     3.4 新版功能.

 -- 函数: importlib.util.resolve_name (name, package)

     Resolve a relative module name to an absolute one.

     If `name' has no leading dots, then `name' is simply returned.
     This allows for usage such as ‘importlib.util.resolve_name('sys',
     __spec__.parent)’ without doing a check to see if the `package'
     argument is needed.

     *note ValueError: 1fc. is raised if `name' is a relative module
     name but package is a false value (e.g.  ‘None’ or the empty
     string).  *note ValueError: 1fc. is also raised a relative name
     would escape its containing package (e.g.  requesting ‘..bacon’
     from within the ‘spam’ package).

     3.3 新版功能.

 -- 函数: importlib.util.find_spec (name, package=None)

     Find the *note spec: 3641. for a module, optionally relative to the
     specified `package' name.  If the module is in *note sys.modules:
     f36, then ‘sys.modules[name].__spec__’ is returned (unless the spec
     would be ‘None’ or is not set, in which case *note ValueError: 1fc.
     is raised).  Otherwise a search using *note sys.meta_path: 5ef. is
     done.  ‘None’ is returned if no spec is found.

     If `name' is for a submodule (contains a dot), the parent module is
     automatically imported.

     `name' and `package' work the same as for ‘import_module()’.

     3.4 新版功能.

     在 3.7 版更改: Raises *note ModuleNotFoundError: 3a2. instead of
     *note AttributeError: 3a3. if `package' is in fact not a package
     (i.e.  lacks a *note __path__: 129f. attribute).

 -- 函数: importlib.util.module_from_spec (spec)

     Create a new module based on `spec' and *note
     spec.loader.create_module: 55d.

     If *note spec.loader.create_module: 55d. does not return ‘None’,
     then any pre-existing attributes will not be reset.  Also, no *note
     AttributeError: 3a3. will be raised if triggered while accessing
     `spec' or setting an attribute on the module.

     This function is preferred over using *note types.ModuleType: 6fa.
     to create a new module as `spec' is used to set as many
     import-controlled attributes on the module as possible.

     3.5 新版功能.

 -- 函数: @importlib.util.module_for_loader

     A *note decorator: 284. for *note
     importlib.abc.Loader.load_module(): 5ec. to handle selecting the
     proper module object to load with.  The decorated method is
     expected to have a call signature taking two positional arguments
     (e.g.  ‘load_module(self, module)’) for which the second argument
     will be the module `object' to be used by the loader.  Note that
     the decorator will not work on static methods because of the
     assumption of two arguments.

     The decorated method will take in the `name' of the module to be
     loaded as expected for a *note loader: 14cb.  If the module is not
     found in *note sys.modules: f36. then a new one is constructed.
     Regardless of where the module came from, *note __loader__: 95e.
     set to `self' and *note __package__: 95d. is set based on what
     *note importlib.abc.InspectLoader.is_package(): 376b. returns (if
     available).  These attributes are set unconditionally to support
     reloading.

     If an exception is raised by the decorated method and a module was
     added to *note sys.modules: f36, then the module will be removed to
     prevent a partially initialized module from being in left in *note
     sys.modules: f36.  If the module was already in *note sys.modules:
     f36. then it is left alone.

     在 3.3 版更改: *note __loader__: 95e. and *note __package__: 95d.
     are automatically set (when possible).

     在 3.4 版更改: Set *note __name__: d1a, *note __loader__: 95e.
     *note __package__: 95d. unconditionally to support reloading.

     3.4 版后已移除: The import machinery now directly performs all the
     functionality provided by this function.

 -- 函数: @importlib.util.set_loader

     A *note decorator: 284. for *note
     importlib.abc.Loader.load_module(): 5ec. to set the *note
     __loader__: 95e. attribute on the returned module.  If the
     attribute is already set the decorator does nothing.  It is assumed
     that the first positional argument to the wrapped method (i.e.
     ‘self’) is what *note __loader__: 95e. should be set to.

     在 3.4 版更改: Set ‘__loader__’ if set to ‘None’, as if the
     attribute does not exist.

     3.4 版后已移除: The import machinery takes care of this
     automatically.

 -- 函数: @importlib.util.set_package

     A *note decorator: 284. for *note
     importlib.abc.Loader.load_module(): 5ec. to set the *note
     __package__: 95d. attribute on the returned module.  If *note
     __package__: 95d. is set and has a value other than ‘None’ it will
     not be changed.

     3.4 版后已移除: The import machinery takes care of this
     automatically.

 -- 函数: importlib.util.spec_from_loader (name, loader, *, origin=None,
          is_package=None)

     A factory function for creating a ‘ModuleSpec’ instance based on a
     loader.  The parameters have the same meaning as they do for
     ModuleSpec.  The function uses available *note loader: 14cb. APIs,
     such as ‘InspectLoader.is_package()’, to fill in any missing
     information on the spec.

     3.4 新版功能.

 -- 函数: importlib.util.spec_from_file_location (name, location, *,
          loader=None, submodule_search_locations=None)

     A factory function for creating a ‘ModuleSpec’ instance based on
     the path to a file.  Missing information will be filled in on the
     spec by making use of loader APIs and by the implication that the
     module will be file-based.

     3.4 新版功能.

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- 函数: importlib.util.source_hash (source_bytes)

     Return the hash of `source_bytes' as bytes.  A hash-based ‘.pyc’
     file embeds the *note source_hash(): 379f. of the corresponding
     source file’s contents in its header.

     3.7 新版功能.

 -- 类: importlib.util.LazyLoader (loader)

     A class which postpones the execution of the loader of a module
     until the module has an attribute accessed.

     This class `only' works with loaders that define *note
     exec_module(): 5ed. as control over what module type is used for
     the module is required.  For those same reasons, the loader’s *note
     create_module(): 55d. method must return ‘None’ or a type for which
     its ‘__class__’ attribute can be mutated along with not using *note
     slots: 37a0.  Finally, modules which substitute the object placed
     into *note sys.modules: f36. will not work as there is no way to
     properly replace the module references throughout the interpreter
     safely; *note ValueError: 1fc. is raised if such a substitution is
     detected.

          注解: For projects where startup time is critical, this class
          allows for potentially minimizing the cost of loading a module
          if it is never used.  For projects where startup time is not
          essential then use of this class is `heavily' discouraged due
          to error messages created during loading being postponed and
          thus occurring out of context.

     3.5 新版功能.

     在 3.6 版更改: Began calling *note create_module(): 55d, removing
     the compatibility warning for *note
     importlib.machinery.BuiltinImporter: 55e. and *note
     importlib.machinery.ExtensionFileLoader: 55f.

      -- 方法: classmethod factory (loader)

          A static method which returns a callable that creates a lazy
          loader.  This is meant to be used in situations where the
          loader is passed by class instead of by instance.

               suffixes = importlib.machinery.SOURCE_SUFFIXES
               loader = importlib.machinery.SourceFileLoader
               lazy_loader = importlib.util.LazyLoader.factory(loader)
               finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes))

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/importlib/util.py

   (2) https://www.python.org/dev/peps/pep-3147

   (3) https://www.python.org/dev/peps/pep-0488

   (4) https://www.python.org/dev/peps/pep-3147

   (5) https://www.python.org/dev/peps/pep-3147

   (6) https://www.python.org/dev/peps/pep-0488


File: python.info,  Node: 例子<29>,  Prev: importlib util -- Utility code for importers,  Up: importlib --- import 的实现

5.31.5.7 例子
.............

* Menu:

* Importing programmatically::
* Checking if a module can be imported::
* Importing a source file directly::
* Setting up an importer::
* Approximating importlib.import_module(): Approximating importlib import_module.


File: python.info,  Node: Importing programmatically,  Next: Checking if a module can be imported,  Up: 例子<29>

5.31.5.8 Importing programmatically
...................................

To programmatically import a module, use *note
importlib.import_module(): b1b.

     import importlib

     itertools = importlib.import_module('itertools')


File: python.info,  Node: Checking if a module can be imported,  Next: Importing a source file directly,  Prev: Importing programmatically,  Up: 例子<29>

5.31.5.9 Checking if a module can be imported
.............................................

If you need to find out if a module can be imported without actually
doing the import, then you should use *note importlib.util.find_spec():
940.

     import importlib.util
     import sys

     # For illustrative purposes.
     name = 'itertools'

     if name in sys.modules:
         print(f"{name!r} already in sys.modules")
     elif (spec := importlib.util.find_spec(name)) is not None:
         # If you chose to perform the actual import ...
         module = importlib.util.module_from_spec(spec)
         sys.modules[name] = module
         spec.loader.exec_module(module)
         print(f"{name!r} has been imported")
     else:
         print(f"can't find the {name!r} module")


File: python.info,  Node: Importing a source file directly,  Next: Setting up an importer,  Prev: Checking if a module can be imported,  Up: 例子<29>

5.31.5.10 Importing a source file directly
..........................................

To import a Python source file directly, use the following recipe
(Python 3.5 and newer only):

     import importlib.util
     import sys

     # For illustrative purposes.
     import tokenize
     file_path = tokenize.__file__
     module_name = tokenize.__name__

     spec = importlib.util.spec_from_file_location(module_name, file_path)
     module = importlib.util.module_from_spec(spec)
     sys.modules[module_name] = module
     spec.loader.exec_module(module)


File: python.info,  Node: Setting up an importer,  Next: Approximating importlib import_module,  Prev: Importing a source file directly,  Up: 例子<29>

5.31.5.11 Setting up an importer
................................

For deep customizations of import, you typically want to implement an
*note importer: 14cc.  This means managing both the *note finder: 14ca.
and *note loader: 14cb. side of things.  For finders there are two
flavours to choose from depending on your needs: a *note meta path
finder: 9b9. or a *note path entry finder: 9ba.  The former is what you
would put on *note sys.meta_path: 5ef. while the latter is what you
create using a *note path entry hook: 14e1. on *note sys.path_hooks:
964. which works with *note sys.path: 490. entries to potentially create
a finder.  This example will show you how to register your own importers
so that import will use them (for creating an importer for yourself,
read the documentation for the appropriate classes defined within this
package):

     import importlib.machinery
     import sys

     # For illustrative purposes only.
     SpamMetaPathFinder = importlib.machinery.PathFinder
     SpamPathEntryFinder = importlib.machinery.FileFinder
     loader_details = (importlib.machinery.SourceFileLoader,
                       importlib.machinery.SOURCE_SUFFIXES)

     # Setting up a meta path finder.
     # Make sure to put the finder in the proper location in the list in terms of
     # priority.
     sys.meta_path.append(SpamMetaPathFinder)

     # Setting up a path entry finder.
     # Make sure to put the path hook in the proper location in the list in terms
     # of priority.
     sys.path_hooks.append(SpamPathEntryFinder.path_hook(loader_details))


File: python.info,  Node: Approximating importlib import_module,  Prev: Setting up an importer,  Up: 例子<29>

5.31.5.12 Approximating ‘importlib.import_module()’
...................................................

Import itself is implemented in Python code, making it possible to
expose most of the import machinery through importlib.  The following
helps illustrate the various APIs that importlib exposes by providing an
approximate implementation of *note importlib.import_module(): b1b.
(Python 3.4 and newer for the importlib usage, Python 3.6 and newer for
other parts of the code).

     import importlib.util
     import sys

     def import_module(name, package=None):
         """An approximate implementation of import."""
         absolute_name = importlib.util.resolve_name(name, package)
         try:
             return sys.modules[absolute_name]
         except KeyError:
             pass

         path = None
         if '.' in absolute_name:
             parent_name, _, child_name = absolute_name.rpartition('.')
             parent_module = import_module(parent_name)
             path = parent_module.__spec__.submodule_search_locations
         for finder in sys.meta_path:
             spec = finder.find_spec(absolute_name, path)
             if spec is not None:
                 break
         else:
             msg = f'No module named {absolute_name!r}'
             raise ModuleNotFoundError(msg, name=absolute_name)
         module = importlib.util.module_from_spec(spec)
         sys.modules[absolute_name] = module
         spec.loader.exec_module(module)
         if path is not None:
             setattr(parent_module, child_name, module)
         return module


File: python.info,  Node: Using importlib metadata,  Prev: importlib --- import 的实现,  Up: 导入模块

5.31.6 Using ‘importlib.metadata’
---------------------------------

3.8 新版功能.

`Source code:' Lib/importlib/metadata.py(1)

     注解: This functionality is provisional and may deviate from the
     usual version semantics of the standard library.

‘importlib.metadata’ is a library that provides for access to installed
package metadata.  Built in part on Python’s import system, this library
intends to replace similar functionality in the entry point API(2) and
metadata API(3) of ‘pkg_resources’.  Along with *note
importlib.resources: 9f. in Python 3.7 and newer (backported as
importlib_resources(4) for older versions of Python), this can eliminate
the need to use the older and less efficient ‘pkg_resources’ package.

By "installed package" we generally mean a third-party package installed
into Python’s ‘site-packages’ directory via tools such as pip(5).
Specifically, it means a package with either a discoverable ‘dist-info’
or ‘egg-info’ directory, and metadata defined by PEP 566(6) or its older
specifications.  By default, package metadata can live on the file
system or in zip archives on *note sys.path: 490.  Through an extension
mechanism, the metadata can live almost anywhere.

* Menu:

* 概述: 概述<14>.
* 功能性 API: 功能性 API<2>.
* Distributions::
* Extending the search algorithm::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/importlib/metadata.py

   (2) 
https://setuptools.readthedocs.io/en/latest/pkg_resources.html#entry-points

   (3) 
https://setuptools.readthedocs.io/en/latest/pkg_resources.html#metadata-api

   (4) https://importlib-resources.readthedocs.io/en/latest/index.html

   (5) https://pypi.org/project/pip/

   (6) https://www.python.org/dev/peps/pep-0566


File: python.info,  Node: 概述<14>,  Next: 功能性 API<2>,  Up: Using importlib metadata

5.31.6.1 概述
.............

Let’s say you wanted to get the version string for a package you’ve
installed using ‘pip’.  We start by creating a virtual environment and
installing something into it:

     $ python3 -m venv example
     $ source example/bin/activate
     (example) $ pip install wheel

You can get the version string for ‘wheel’ by running the following:

     (example) $ python
     >>> from importlib.metadata import version
     >>> version('wheel')
     '0.32.3'

You can also get the set of entry points keyed by group, such as
‘console_scripts’, ‘distutils.commands’ and others.  Each group contains
a sequence of *note EntryPoint: 37ad. objects.

You can get the *note metadata for a distribution: 37ae.:

     >>> list(metadata('wheel'))
     ['Metadata-Version', 'Name', 'Version', 'Summary', 'Home-page', 'Author', 'Author-email', 'Maintainer', 'Maintainer-email', 'License', 'Project-URL', 'Project-URL', 'Project-URL', 'Keywords', 'Platform', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Requires-Python', 'Provides-Extra', 'Requires-Dist', 'Requires-Dist']

You can also get a *note distribution’s version number: 37af, list its
*note constituent files: 37b0, and get a list of the distribution’s
*note Distribution requirements: 37b1.


File: python.info,  Node: 功能性 API<2>,  Next: Distributions,  Prev: 概述<14>,  Up: Using importlib metadata

5.31.6.2 功能性 API
...................

This package provides the following functionality via its public API.

* Menu:

* Entry points::
* Distribution metadata::
* Distribution versions::
* Distribution files::
* Distribution requirements::


File: python.info,  Node: Entry points,  Next: Distribution metadata,  Up: 功能性 API<2>

5.31.6.3 Entry points
.....................

The ‘entry_points()’ function returns a dictionary of all entry points,
keyed by group.  Entry points are represented by ‘EntryPoint’ instances;
each ‘EntryPoint’ has a ‘.name’, ‘.group’, and ‘.value’ attributes and a
‘.load()’ method to resolve the value.

     >>> eps = entry_points()
     >>> list(eps)
     ['console_scripts', 'distutils.commands', 'distutils.setup_keywords', 'egg_info.writers', 'setuptools.installation']
     >>> scripts = eps['console_scripts']
     >>> wheel = [ep for ep in scripts if ep.name == 'wheel'][0]
     >>> wheel
     EntryPoint(name='wheel', value='wheel.cli:main', group='console_scripts')
     >>> main = wheel.load()
     >>> main
     <function main at 0x103528488>

The ‘group’ and ‘name’ are arbitrary values defined by the package
author and usually a client will wish to resolve all entry points for a
particular group.  Read the setuptools docs(1) for more information on
entrypoints, their definition, and usage.

   ---------- Footnotes ----------

   (1) 
https://setuptools.readthedocs.io/en/latest/setuptools.html#dynamic-discovery-of-services-and-plugins


File: python.info,  Node: Distribution metadata,  Next: Distribution versions,  Prev: Entry points,  Up: 功能性 API<2>

5.31.6.4 Distribution metadata
..............................

Every distribution includes some metadata, which you can extract using
the ‘metadata()’ function:

     >>> wheel_metadata = metadata('wheel')

The keys of the returned data structure (1) name the metadata keywords,
and their values are returned unparsed from the distribution metadata:

     >>> wheel_metadata['Requires-Python']
     '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'

   ---------- Footnotes ----------

   (1) (1) Technically, the returned distribution metadata object is an
*note email.message.EmailMessage: 54b. instance, but this is an
implementation detail, and not part of the stable API. You should only
use dictionary-like methods and syntax to access the metadata contents.


File: python.info,  Node: Distribution versions,  Next: Distribution files,  Prev: Distribution metadata,  Up: 功能性 API<2>

5.31.6.5 Distribution versions
..............................

The ‘version()’ function is the quickest way to get a distribution’s
version number, as a string:

     >>> version('wheel')
     '0.32.3'


File: python.info,  Node: Distribution files,  Next: Distribution requirements,  Prev: Distribution versions,  Up: 功能性 API<2>

5.31.6.6 Distribution files
...........................

You can also get the full set of files contained within a distribution.
The ‘files()’ function takes a distribution package name and returns all
of the files installed by this distribution.  Each file object returned
is a ‘PackagePath’, a *note pathlib.Path: 202. derived object with
additional ‘dist’, ‘size’, and ‘hash’ properties as indicated by the
metadata.  For example:

     >>> util = [p for p in files('wheel') if 'util.py' in str(p)][0]
     >>> util
     PackagePath('wheel/util.py')
     >>> util.size
     859
     >>> util.dist
     <importlib.metadata._hooks.PathDistribution object at 0x101e0cef0>
     >>> util.hash
     <FileHash mode: sha256 value: bYkw5oMccfazVCoYQwKkkemoVyMAFoR34mmKBx8R1NI>

Once you have the file, you can also read its contents:

     >>> print(util.read_text())
     import base64
     import sys
     ...
     def as_bytes(s):
         if isinstance(s, text_type):
             return s.encode('utf-8')
         return s

In the case where the metadata file listing files (RECORD or
SOURCES.txt) is missing, ‘files()’ will return ‘None’.  The caller may
wish to wrap calls to ‘files()’ in always_iterable(1) or otherwise guard
against this condition if the target distribution is not known to have
the metadata present.

   ---------- Footnotes ----------

   (1) 
https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_iterable


File: python.info,  Node: Distribution requirements,  Prev: Distribution files,  Up: 功能性 API<2>

5.31.6.7 Distribution requirements
..................................

To get the full set of requirements for a distribution, use the
‘requires()’ function:

     >>> requires('wheel')
     ["pytest (>=3.0.0) ; extra == 'test'", "pytest-cov ; extra == 'test'"]


File: python.info,  Node: Distributions,  Next: Extending the search algorithm,  Prev: 功能性 API<2>,  Up: Using importlib metadata

5.31.6.8 Distributions
......................

While the above API is the most common and convenient usage, you can get
all of that information from the ‘Distribution’ class.  A ‘Distribution’
is an abstract object that represents the metadata for a Python package.
You can get the ‘Distribution’ instance:

     >>> from importlib.metadata import distribution
     >>> dist = distribution('wheel')

Thus, an alternative way to get the version number is through the
‘Distribution’ instance:

     >>> dist.version
     '0.32.3'

There are all kinds of additional metadata available on the
‘Distribution’ instance:

     >>> dist.metadata['Requires-Python']
     '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
     >>> dist.metadata['License']
     'MIT'

The full set of available metadata is not described here.  See PEP
566(1) for additional details.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0566


File: python.info,  Node: Extending the search algorithm,  Prev: Distributions,  Up: Using importlib metadata

5.31.6.9 Extending the search algorithm
.......................................

Because package metadata is not available through *note sys.path: 490.
searches, or package loaders directly, the metadata for a package is
found through import system *note finders: 14c8.  To find a distribution
package’s metadata, ‘importlib.metadata’ queries the list of *note meta
path finders: 9b9. on *note sys.meta_path: 5ef.

The default ‘PathFinder’ for Python includes a hook that calls into
‘importlib.metadata.MetadataPathFinder’ for finding distributions loaded
from typical file-system-based paths.

The abstract class *note importlib.abc.MetaPathFinder: 9bb. defines the
interface expected of finders by Python’s import system.
‘importlib.metadata’ extends this protocol by looking for an optional
‘find_distributions’ callable on the finders from *note sys.meta_path:
5ef. and presents this extended interface as the ‘DistributionFinder’
abstract base class, which defines this abstract method:

     @abc.abstractmethod
     def find_distributions(context=DistributionFinder.Context()):
         """Return an iterable of all Distribution instances capable of
         loading the metadata for packages for the indicated ``context``.
         """

The ‘DistributionFinder.Context’ object provides ‘.path’ and ‘.name’
properties indicating the path to search and names to match and may
supply other relevant context.

What this means in practice is that to support finding distribution
package metadata in locations other than the file system, subclass
‘Distribution’ and implement the abstract methods.  Then from a custom
finder, return instances of this derived ‘Distribution’ in the
‘find_distributions()’ method.

备注
....


File: python.info,  Node: Python 语言服务,  Next: 杂项服务,  Prev: 导入模块,  Up: Python 标准库

5.32 Python 语言服务
====================

Python 提供了许多模块来帮助使用 Python 语言。 这些模块支持标记化、解析、
语法分析、字节码反汇编以及各种其他工具。

这些模块包括：

* Menu:

* parser: parser --- 访问 Python 解析树. 访问 Python 解析树
* ast: ast --- 抽象语法树. 抽象语法树
* symtable: symtable --- Access to the compiler's symbol tables. Access to the compiler’s symbol tables
* symbol: symbol --- 与 Python 解析树一起使用的常量. 与 Python 解析树一起使用的常量
* token: token --- 与Python解析树一起使用的常量. 与Python解析树一起使用的常量
* keyword: keyword --- 检验Python关键字. 检验Python关键字
* tokenize: tokenize --- 对 Python 代码使用的标记解析器. 对 Python 代码使用的标记解析器
* tabnanny: tabnanny --- 模糊缩进检测. 模糊缩进检测
* pyclbr: pyclbr --- Python 模块浏览器支持. Python 模块浏览器支持
* py_compile: py_compile --- 编译 Python 源文件. 编译 Python 源文件
* compileall: compileall --- Byte-compile Python libraries. Byte-compile Python libraries
* dis: dis --- Python 字节码反汇编器. Python 字节码反汇编器
* pickletools: pickletools --- pickle 开发者工具集. pickle 开发者工具集


File: python.info,  Node: parser --- 访问 Python 解析树,  Next: ast --- 抽象语法树,  Up: Python 语言服务

5.32.1 ‘parser’ — 访问 Python 解析树
------------------------------------

__________________________________________________________________

The *note parser: c8. module provides an interface to Python’s internal
parser and byte-code compiler.  The primary purpose for this interface
is to allow Python code to edit the parse tree of a Python expression
and create executable code from this.  This is better than trying to
parse and modify an arbitrary Python code fragment as a string because
parsing is performed in a manner identical to the code forming the
application.  It is also faster.

     注解: From Python 2.5 onward, it’s much more convenient to cut in
     at the Abstract Syntax Tree (AST) generation and compilation stage,
     using the *note ast: 8. module.

There are a few things to note about this module which are important to
making use of the data structures created.  This is not a tutorial on
editing the parse trees for Python code, but some examples of using the
*note parser: c8. module are presented.

Most importantly, a good understanding of the Python grammar processed
by the internal parser is required.  For full information on the
language syntax, refer to *note Python语言参考: 120c.  The parser itself
is created from a grammar specification defined in the file
‘Grammar/Grammar’ in the standard Python distribution.  The parse trees
stored in the ST objects created by this module are the actual output
from the internal parser when created by the *note expr(): 37bf. or
*note suite(): 37c0. functions, described below.  The ST objects created
by *note sequence2st(): 37c1. faithfully simulate those structures.  Be
aware that the values of the sequences which are considered "correct"
will vary from one version of Python to another as the formal grammar
for the language is revised.  However, transporting code from one Python
version to another as source text will always allow correct parse trees
to be created in the target version, with the only restriction being
that migrating to an older version of the interpreter will not support
more recent language constructs.  The parse trees are not typically
compatible from one version to another, though source code has usually
been forward-compatible within a major release series.

Each element of the sequences returned by *note st2list(): 37c2. or
*note st2tuple(): 37c3. has a simple form.  Sequences representing
non-terminal elements in the grammar always have a length greater than
one.  The first element is an integer which identifies a production in
the grammar.  These integers are given symbolic names in the C header
file ‘Include/graminit.h’ and the Python module *note symbol: fc.  Each
additional element of the sequence represents a component of the
production as recognized in the input string: these are always sequences
which have the same form as the parent.  An important aspect of this
structure which should be noted is that keywords used to identify the
parent node type, such as the keyword *note if: def. in an ‘if_stmt’,
are included in the node tree without any special treatment.  For
example, the ‘if’ keyword is represented by the tuple ‘(1, 'if')’, where
‘1’ is the numeric value associated with all ‘NAME’ tokens, including
variable and function names defined by the user.  In an alternate form
returned when line number information is requested, the same token might
be represented as ‘(1, 'if', 12)’, where the ‘12’ represents the line
number at which the terminal symbol was found.

Terminal elements are represented in much the same way, but without any
child elements and the addition of the source text which was identified.
The example of the *note if: def. keyword above is representative.  The
various types of terminal symbols are defined in the C header file
‘Include/token.h’ and the Python module *note token: 111.

The ST objects are not required to support the functionality of this
module, but are provided for three purposes: to allow an application to
amortize the cost of processing complex parse trees, to provide a parse
tree representation which conserves memory space when compared to the
Python list or tuple representation, and to ease the creation of
additional modules in C which manipulate parse trees.  A simple
"wrapper" class may be created in Python to hide the use of ST objects.

The *note parser: c8. module defines functions for a few distinct
purposes.  The most important purposes are to create ST objects and to
convert ST objects to other representations such as parse trees and
compiled code objects, but there are also functions which serve to query
the type of parse tree represented by an ST object.

参见
....

模块 *note symbol: fc.

     代表解析树内部节点的有用常量。

模块 *note token: 111.

     代表解析树叶子节点和测试节点值的函数的有用常量。

* Menu:

* 创建 ST 对象::
* 转换 ST 对象::
* Queries on ST Objects::
* 异常和错误处理::
* ST 对象::
* 示例; compile() 的模拟: 示例 compile 的模拟.


File: python.info,  Node: 创建 ST 对象,  Next: 转换 ST 对象,  Up: parser --- 访问 Python 解析树

5.32.1.1 创建 ST 对象
.....................

ST objects may be created from source code or from a parse tree.  When
creating an ST object from source, different functions are used to
create the ‘'eval'’ and ‘'exec'’ forms.

 -- 函数: parser.expr (source)

     The *note expr(): 37bf. function parses the parameter `source' as
     if it were an input to ‘compile(source, 'file.py', 'eval')’.  If
     the parse succeeds, an ST object is created to hold the internal
     parse tree representation, otherwise an appropriate exception is
     raised.

 -- 函数: parser.suite (source)

     The *note suite(): 37c0. function parses the parameter `source' as
     if it were an input to ‘compile(source, 'file.py', 'exec')’.  If
     the parse succeeds, an ST object is created to hold the internal
     parse tree representation, otherwise an appropriate exception is
     raised.

 -- 函数: parser.sequence2st (sequence)

     This function accepts a parse tree represented as a sequence and
     builds an internal representation if possible.  If it can validate
     that the tree conforms to the Python grammar and all nodes are
     valid node types in the host version of Python, an ST object is
     created from the internal representation and returned to the
     called.  If there is a problem creating the internal
     representation, or if the tree cannot be validated, a *note
     ParserError: 37c6. exception is raised.  An ST object created this
     way should not be assumed to compile correctly; normal exceptions
     raised by compilation may still be initiated when the ST object is
     passed to *note compilest(): 37c7.  This may indicate problems not
     related to syntax (such as a *note MemoryError: efc. exception),
     but may also be due to constructs such as the result of parsing
     ‘del f(0)’, which escapes the Python parser but is checked by the
     bytecode compiler.

     Sequences representing terminal tokens may be represented as either
     two-element lists of the form ‘(1, 'name')’ or as three-element
     lists of the form ‘(1, 'name', 56)’.  If the third element is
     present, it is assumed to be a valid line number.  The line number
     may be specified for any subset of the terminal symbols in the
     input tree.

 -- 函数: parser.tuple2st (sequence)

     This is the same function as *note sequence2st(): 37c1.  This entry
     point is maintained for backward compatibility.


File: python.info,  Node: 转换 ST 对象,  Next: Queries on ST Objects,  Prev: 创建 ST 对象,  Up: parser --- 访问 Python 解析树

5.32.1.2 转换 ST 对象
.....................

ST objects, regardless of the input used to create them, may be
converted to parse trees represented as list- or tuple- trees, or may be
compiled into executable code objects.  Parse trees may be extracted
with or without line numbering information.

 -- 函数: parser.st2list (st, line_info=False, col_info=False)

     This function accepts an ST object from the caller in `st' and
     returns a Python list representing the equivalent parse tree.  The
     resulting list representation can be used for inspection or the
     creation of a new parse tree in list form.  This function does not
     fail so long as memory is available to build the list
     representation.  If the parse tree will only be used for
     inspection, *note st2tuple(): 37c3. should be used instead to
     reduce memory consumption and fragmentation.  When the list
     representation is required, this function is significantly faster
     than retrieving a tuple representation and converting that to
     nested lists.

     If `line_info' is true, line number information will be included
     for all terminal tokens as a third element of the list representing
     the token.  Note that the line number provided specifies the line
     on which the token `ends'.  This information is omitted if the flag
     is false or omitted.

 -- 函数: parser.st2tuple (st, line_info=False, col_info=False)

     This function accepts an ST object from the caller in `st' and
     returns a Python tuple representing the equivalent parse tree.
     Other than returning a tuple instead of a list, this function is
     identical to *note st2list(): 37c2.

     If `line_info' is true, line number information will be included
     for all terminal tokens as a third element of the list representing
     the token.  This information is omitted if the flag is false or
     omitted.

 -- 函数: parser.compilest (st, filename='<syntax-tree>')

     The Python byte compiler can be invoked on an ST object to produce
     code objects which can be used as part of a call to the built-in
     *note exec(): c4c. or *note eval(): b98. functions.  This function
     provides the interface to the compiler, passing the internal parse
     tree from `st' to the parser, using the source file name specified
     by the `filename' parameter.  The default value supplied for
     `filename' indicates that the source was an ST object.

     Compiling an ST object may result in exceptions related to
     compilation; an example would be a *note SyntaxError: 460. caused
     by the parse tree for ‘del f(0)’: this statement is considered
     legal within the formal grammar for Python but is not a legal
     language construct.  The *note SyntaxError: 460. raised for this
     condition is actually generated by the Python byte-compiler
     normally, which is why it can be raised at this point by the *note
     parser: c8. module.  Most causes of compilation failure can be
     diagnosed programmatically by inspection of the parse tree.


File: python.info,  Node: Queries on ST Objects,  Next: 异常和错误处理,  Prev: 转换 ST 对象,  Up: parser --- 访问 Python 解析树

5.32.1.3 Queries on ST Objects
..............................

Two functions are provided which allow an application to determine if an
ST was created as an expression or a suite.  Neither of these functions
can be used to determine if an ST was created from source code via *note
expr(): 37bf. or *note suite(): 37c0. or from a parse tree via *note
sequence2st(): 37c1.

 -- 函数: parser.isexpr (st)

     When `st' represents an ‘'eval'’ form, this function returns
     ‘True’, otherwise it returns ‘False’.  This is useful, since code
     objects normally cannot be queried for this information using
     existing built-in functions.  Note that the code objects created by
     *note compilest(): 37c7. cannot be queried like this either, and
     are identical to those created by the built-in *note compile():
     1b5. function.

 -- 函数: parser.issuite (st)

     This function mirrors *note isexpr(): 37cd. in that it reports
     whether an ST object represents an ‘'exec'’ form, commonly known as
     a "suite."  It is not safe to assume that this function is
     equivalent to ‘not isexpr(st)’, as additional syntactic fragments
     may be supported in the future.


File: python.info,  Node: 异常和错误处理,  Next: ST 对象,  Prev: Queries on ST Objects,  Up: parser --- 访问 Python 解析树

5.32.1.4 异常和错误处理
.......................

The parser module defines a single exception, but may also pass other
built-in exceptions from other portions of the Python runtime
environment.  See each function for information about the exceptions it
can raise.

 -- 例外: parser.ParserError

     Exception raised when a failure occurs within the parser module.
     This is generally produced for validation failures rather than the
     built-in *note SyntaxError: 460. raised during normal parsing.  The
     exception argument is either a string describing the reason of the
     failure or a tuple containing a sequence causing the failure from a
     parse tree passed to *note sequence2st(): 37c1. and an explanatory
     string.  Calls to *note sequence2st(): 37c1. need to be able to
     handle either type of exception, while calls to other functions in
     the module will only need to be aware of the simple string values.

Note that the functions *note compilest(): 37c7, *note expr(): 37bf, and
*note suite(): 37c0. may raise exceptions which are normally raised by
the parsing and compilation process.  These include the built in
exceptions *note MemoryError: efc, *note OverflowError: 968, *note
SyntaxError: 460, and *note SystemError: 604.  In these cases, these
exceptions carry all the meaning normally associated with them.  Refer
to the descriptions of each function for detailed information.


File: python.info,  Node: ST 对象,  Next: 示例 compile 的模拟,  Prev: 异常和错误处理,  Up: parser --- 访问 Python 解析树

5.32.1.5 ST 对象
................

Ordered and equality comparisons are supported between ST objects.
Pickling of ST objects (using the *note pickle: cb. module) is also
supported.

 -- 数据: parser.STType

     The type of the objects returned by *note expr(): 37bf, *note
     suite(): 37c0. and *note sequence2st(): 37c1.

ST 对象具有以下方法:

 -- 方法: ST.compile (filename='<syntax-tree>')

     和 ‘compilest(st, filename)’ 相同.

 -- 方法: ST.isexpr ()

     和 ‘isexpr(st)’ 相同。

 -- 方法: ST.issuite ()

     和 ‘issuite(st)’ 相同。

 -- 方法: ST.tolist (line_info=False, col_info=False)

     和 ‘st2list(st, line_info, col_info)’ 相同。

 -- 方法: ST.totuple (line_info=False, col_info=False)

     和 ‘st2tuple(st, line_info, col_info)’ 相同。


File: python.info,  Node: 示例 compile 的模拟,  Prev: ST 对象,  Up: parser --- 访问 Python 解析树

5.32.1.6 示例: ‘compile()’ 的模拟
.................................

While many useful operations may take place between parsing and bytecode
generation, the simplest operation is to do nothing.  For this purpose,
using the *note parser: c8. module to produce an intermediate data
structure is equivalent to the code

     >>> code = compile('a + 5', 'file.py', 'eval')
     >>> a = 5
     >>> eval(code)
     10

The equivalent operation using the *note parser: c8. module is somewhat
longer, and allows the intermediate internal parse tree to be retained
as an ST object:

     >>> import parser
     >>> st = parser.expr('a + 5')
     >>> code = st.compile('file.py')
     >>> a = 5
     >>> eval(code)
     10

An application which needs both ST and code objects can package this
code into readily available functions:

     import parser

     def load_suite(source_string):
         st = parser.suite(source_string)
         return st, st.compile()

     def load_expression(source_string):
         st = parser.expr(source_string)
         return st, st.compile()


File: python.info,  Node: ast --- 抽象语法树,  Next: symtable --- Access to the compiler's symbol tables,  Prev: parser --- 访问 Python 解析树,  Up: Python 语言服务

5.32.2 ‘ast’ — 抽象语法树
-------------------------

`源代码：' Lib/ast.py(1)

__________________________________________________________________

*note ast: 8. 模块帮助 Python 程序处理 Python 语法的抽象语法树。抽象语法
或许会随着 Python 的更新发布而改变；该模块能够帮助理解当前语法在编程层面
的样貌。

抽象语法树可通过将 ‘ast.PyCF_ONLY_AST’ 作为旗标传递给 *note compile():
1b5. 内置函数来生成，或是使用此模块中提供的 *note parse(): 1a2. 辅助函数
。返回结果将是一个对象树，，其中的类都继承自 *note ast.AST: 37dc.。抽象
语法树可被内置的 *note compile(): 1b5. 函数编译为一个 Python 代码对象。

* Menu:

* 节点类::
* 抽象文法::
* ast 中的辅助函数::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/ast.py


File: python.info,  Node: 节点类,  Next: 抽象文法,  Up: ast --- 抽象语法树

5.32.2.1 节点类
...............

 -- 类: ast.AST

     这是所有 AST 节点类的基类。实际上，这些节点类派生自
     ‘Parser/Python.asdl’ 文件，其中定义的语法树示例 *note 如下: 37de.。
     它们在 C 语言模块 ‘_ast’ 中定义，并被导出至 *note ast: 8. 模块。

     抽象语法定义的每个左侧符号(比方说， ‘ast.stmt’ 或者 ‘ast.expr’)定义
     了一个类。另外，在抽象语法定义的右侧，对每一个构造器也定义了一个类
     ；这些类继承自树左侧的类。比如，‘ast.BinOp’ 继承自 ‘ast.expr’。对于
     多分支产生式(也就是"和规则")，树右侧的类是抽象的；只有特定构造器结
     点的实例能被构造。

      -- 属性: _fields

          每个具体类都有个属性 *note _fields: 37df, 用来给出所有子节点的
          名字。

          每个具体类的实例对它每个子节点都有一个属性，对应类型如文法中所
          定义。比如，‘ast.BinOp’ 的实例有个属性 ‘left’，类型是
          ‘ast.expr’.

          如果这些属性在文法中标记为可选（使用问号），对应值可能会是
          ‘None’。如果这些属性有零或多个（用星号标记），对应值会用
          Python的列表来表示。所有可能的属性必须在用 *note compile():
          1b5. 编译得到AST时给出，且是有效的值。

      -- 属性: lineno
      -- 属性: col_offset
      -- 属性: end_lineno
      -- 属性: end_col_offset

          Instances of ‘ast.expr’ and ‘ast.stmt’ subclasses have *note
          lineno: 37e0, *note col_offset: 37e1, *note lineno: 37e0, and
          *note col_offset: 37e1. attributes.  The *note lineno: 37e0.
          and *note end_lineno: 37e2. are the first and last line
          numbers of source text span (1-indexed so the first line is
          line 1) and the *note col_offset: 37e1. and *note
          end_col_offset: 37e3. are the corresponding UTF-8 byte offsets
          of the first and last tokens that generated the node.  The
          UTF-8 offset is recorded because the parser uses UTF-8
          internally.

          Note that the end positions are not required by the compiler
          and are therefore optional.  The end offset is `after' the
          last symbol, for example one can get the source segment of a
          one-line expression node using ‘source_line[node.col_offset :
          node.end_col_offset]’.

     一个类的构造器 ‘ast.T’ 像下面这样parse它的参数。

        * 如果有位置参数，它们必须和 ‘T._fields’ 中的元素一样多；他们会
          像这些名字的属性一样被赋值。

        * 如果有关键字参数，它们必须被设为和给定值同名的属性。

     比方说，要创建和填充节点 ‘ast.UnaryOp’，你得用

          node = ast.UnaryOp()
          node.op = ast.USub()
          node.operand = ast.Constant()
          node.operand.value = 5
          node.operand.lineno = 0
          node.operand.col_offset = 0
          node.lineno = 0
          node.col_offset = 0

     或者更紧凑点

          node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),
                             lineno=0, col_offset=0)

在 3.8 版更改: Class ‘ast.Constant’ is now used for all constants.

3.8 版后已移除: Old classes ‘ast.Num’, ‘ast.Str’, ‘ast.Bytes’,
‘ast.NameConstant’ and ‘ast.Ellipsis’ are still available, but they will
be removed in future Python releases.  In the meanwhile, instantiating
them will return an instance of a different class.


File: python.info,  Node: 抽象文法,  Next: ast 中的辅助函数,  Prev: 节点类,  Up: ast --- 抽象语法树

5.32.2.2 抽象文法
.................

抽象文法目前定义如下

     -- ASDL's 5 builtin types are:
     -- identifier, int, string, object, constant

     module Python
     {
         mod = Module(stmt* body, type_ignore *type_ignores)
             | Interactive(stmt* body)
             | Expression(expr body)
             | FunctionType(expr* argtypes, expr returns)

             -- not really an actual node but useful in Jython's typesystem.
             | Suite(stmt* body)

         stmt = FunctionDef(identifier name, arguments args,
                            stmt* body, expr* decorator_list, expr? returns,
                            string? type_comment)
               | AsyncFunctionDef(identifier name, arguments args,
                                  stmt* body, expr* decorator_list, expr? returns,
                                  string? type_comment)

               | ClassDef(identifier name,
                  expr* bases,
                  keyword* keywords,
                  stmt* body,
                  expr* decorator_list)
               | Return(expr? value)

               | Delete(expr* targets)
               | Assign(expr* targets, expr value, string? type_comment)
               | AugAssign(expr target, operator op, expr value)
               -- 'simple' indicates that we annotate simple name without parens
               | AnnAssign(expr target, expr annotation, expr? value, int simple)

               -- use 'orelse' because else is a keyword in target languages
               | For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
               | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
               | While(expr test, stmt* body, stmt* orelse)
               | If(expr test, stmt* body, stmt* orelse)
               | With(withitem* items, stmt* body, string? type_comment)
               | AsyncWith(withitem* items, stmt* body, string? type_comment)

               | Raise(expr? exc, expr? cause)
               | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
               | Assert(expr test, expr? msg)

               | Import(alias* names)
               | ImportFrom(identifier? module, alias* names, int? level)

               | Global(identifier* names)
               | Nonlocal(identifier* names)
               | Expr(expr value)
               | Pass | Break | Continue

               -- XXX Jython will be different
               -- col_offset is the byte offset in the utf8 string the parser uses
               attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

               -- BoolOp() can use left & right?
         expr = BoolOp(boolop op, expr* values)
              | NamedExpr(expr target, expr value)
              | BinOp(expr left, operator op, expr right)
              | UnaryOp(unaryop op, expr operand)
              | Lambda(arguments args, expr body)
              | IfExp(expr test, expr body, expr orelse)
              | Dict(expr* keys, expr* values)
              | Set(expr* elts)
              | ListComp(expr elt, comprehension* generators)
              | SetComp(expr elt, comprehension* generators)
              | DictComp(expr key, expr value, comprehension* generators)
              | GeneratorExp(expr elt, comprehension* generators)
              -- the grammar constrains where yield expressions can occur
              | Await(expr value)
              | Yield(expr? value)
              | YieldFrom(expr value)
              -- need sequences for compare to distinguish between
              -- x < 4 < 3 and (x < 4) < 3
              | Compare(expr left, cmpop* ops, expr* comparators)
              | Call(expr func, expr* args, keyword* keywords)
              | FormattedValue(expr value, int? conversion, expr? format_spec)
              | JoinedStr(expr* values)
              | Constant(constant value, string? kind)

              -- the following expression can appear in assignment context
              | Attribute(expr value, identifier attr, expr_context ctx)
              | Subscript(expr value, slice slice, expr_context ctx)
              | Starred(expr value, expr_context ctx)
              | Name(identifier id, expr_context ctx)
              | List(expr* elts, expr_context ctx)
              | Tuple(expr* elts, expr_context ctx)

               -- col_offset is the byte offset in the utf8 string the parser uses
               attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

         expr_context = Load | Store | Del | AugLoad | AugStore | Param

         slice = Slice(expr? lower, expr? upper, expr? step)
               | ExtSlice(slice* dims)
               | Index(expr value)

         boolop = And | Or

         operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift
                      | RShift | BitOr | BitXor | BitAnd | FloorDiv

         unaryop = Invert | Not | UAdd | USub

         cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn

         comprehension = (expr target, expr iter, expr* ifs, int is_async)

         excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)
                         attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

         arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs,
                      expr* kw_defaults, arg? kwarg, expr* defaults)

         arg = (identifier arg, expr? annotation, string? type_comment)
                attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

         -- keyword arguments supplied to call (NULL identifier for **kwargs)
         keyword = (identifier? arg, expr value)

         -- import name with optional 'as' alias.
         alias = (identifier name, identifier? asname)

         withitem = (expr context_expr, expr? optional_vars)

         type_ignore = TypeIgnore(int lineno, string tag)
     }


File: python.info,  Node: ast 中的辅助函数,  Prev: 抽象文法,  Up: ast --- 抽象语法树

5.32.2.3 ‘ast’ 中的辅助函数
...........................

除了节点类， *note ast: 8. 模块里为遍历抽象语法树定义了这些工具函数和类:

 -- 函数: ast.parse (source, filename='<unknown>', mode='exec', *,
          type_comments=False, feature_version=None)

     把源码解析为AST节点。和 ‘compile(source, filename,
     mode,ast.PyCF_ONLY_AST)’ 等价。

     If ‘type_comments=True’ is given, the parser is modified to check
     and return type comments as specified by PEP 484(1) and PEP 526(2).
     This is equivalent to adding ‘ast.PyCF_TYPE_COMMENTS’ to the flags
     passed to *note compile(): 1b5.  This will report syntax errors for
     misplaced type comments.  Without this flag, type comments will be
     ignored, and the ‘type_comment’ field on selected AST nodes will
     always be ‘None’.  In addition, the locations of ‘# type: ignore’
     comments will be returned as the ‘type_ignores’ attribute of
     ‘Module’ (otherwise it is always an empty list).

     In addition, if ‘mode’ is ‘'func_type'’, the input syntax is
     modified to correspond to PEP 484(3) "signature type comments",
     e.g.  ‘(str, int) -> List[str]’.

     Also, setting ‘feature_version’ to a tuple ‘(major, minor)’ will
     attempt to parse using that Python version’s grammar.  Currently
     ‘major’ must equal to ‘3’.  For example, setting
     ‘feature_version=(3, 4)’ will allow the use of ‘async’ and ‘await’
     as variable names.  The lowest supported version is ‘(3, 4)’; the
     highest is ‘sys.version_info[0:2]’.

          警告: 足够复杂或是巨大的字符串可能导致Python解释器的崩溃，因为
          Python的AST编译器是有栈深限制的。

     在 3.8 版更改: Added ‘type_comments’, ‘mode='func_type'’ and
     ‘feature_version’.

 -- 函数: ast.literal_eval (node_or_string)

     对表达式节点以及包含Python字面量或容器的字符串进行安全的求值。传入
     的字符串或者节点里可能只包含下列的Python字面量结构: 字符串，字节对
     象(bytes)，数值，元组，列表，字典，集合，布尔值和 ‘None’。

     This can be used for safely evaluating strings containing Python
     values from untrusted sources without the need to parse the values
     oneself.  It is not capable of evaluating arbitrarily complex
     expressions, for example involving operators or indexing.

          警告: 足够复杂或是巨大的字符串可能导致Python解释器的崩溃，因为
          Python的AST编译器是有栈深限制的。

     在 3.2 版更改: 目前支持字节和集合。

 -- 函数: ast.get_docstring (node, clean=True)

     Return the docstring of the given `node' (which must be a
     ‘FunctionDef’, ‘AsyncFunctionDef’, ‘ClassDef’, or ‘Module’ node),
     or ‘None’ if it has no docstring.  If `clean' is true, clean up the
     docstring’s indentation with *note inspect.cleandoc(): 36e6.

     在 3.5 版更改: 目前支持 ‘AsyncFunctionDef’

 -- 函数: ast.get_source_segment (source, node, *, padded=False)

     Get source code segment of the `source' that generated `node'.  If
     some location information (‘lineno’, ‘end_lineno’, ‘col_offset’, or
     ‘end_col_offset’) is missing, return ‘None’.

     If `padded' is ‘True’, the first line of a multi-line statement
     will be padded with spaces to match its original position.

     3.8 新版功能.

 -- 函数: ast.fix_missing_locations (node)

     When you compile a node tree with *note compile(): 1b5, the
     compiler expects ‘lineno’ and ‘col_offset’ attributes for every
     node that supports them.  This is rather tedious to fill in for
     generated nodes, so this helper adds these attributes recursively
     where not already set, by setting them to the values of the parent
     node.  It works recursively starting at `node'.

 -- 函数: ast.increment_lineno (node, n=1)

     Increment the line number and end line number of each node in the
     tree starting at `node' by `n'.  This is useful to "move code" to a
     different location in a file.

 -- 函数: ast.copy_location (new_node, old_node)

     Copy source location (‘lineno’, ‘col_offset’, ‘end_lineno’, and
     ‘end_col_offset’) from `old_node' to `new_node' if possible, and
     return `new_node'.

 -- 函数: ast.iter_fields (node)

     Yield a tuple of ‘(fieldname, value)’ for each field in
     ‘node._fields’ that is present on `node'.

 -- 函数: ast.iter_child_nodes (node)

     Yield all direct child nodes of `node', that is, all fields that
     are nodes and all items of fields that are lists of nodes.

 -- 函数: ast.walk (node)

     Recursively yield all descendant nodes in the tree starting at
     `node' (including `node' itself), in no specified order.  This is
     useful if you only want to modify nodes in place and don’t care
     about the context.

 -- 类: ast.NodeVisitor

     A node visitor base class that walks the abstract syntax tree and
     calls a visitor function for every node found.  This function may
     return a value which is forwarded by the *note visit(): 37eb.
     method.

     This class is meant to be subclassed, with the subclass adding
     visitor methods.

      -- 方法: visit (node)

          Visit a node.  The default implementation calls the method
          called ‘self.visit_`classname'’ where `classname' is the name
          of the node class, or *note generic_visit(): 37ec. if that
          method doesn’t exist.

      -- 方法: generic_visit (node)

          This visitor calls *note visit(): 37eb. on all children of the
          node.

          Note that child nodes of nodes that have a custom visitor
          method won’t be visited unless the visitor calls *note
          generic_visit(): 37ec. or visits them itself.

     Don’t use the *note NodeVisitor: 282. if you want to apply changes
     to nodes during traversal.  For this a special visitor exists
     (*note NodeTransformer: 37ed.) that allows modifications.

     3.8 版后已移除: Methods ‘visit_Num()’, ‘visit_Str()’,
     ‘visit_Bytes()’, ‘visit_NameConstant()’ and ‘visit_Ellipsis()’ are
     deprecated now and will not be called in future Python versions.
     Add the ‘visit_Constant()’ method to handle all constant nodes.

 -- 类: ast.NodeTransformer

     子类 *note NodeVisitor: 282. 用于遍历抽象语法树，并允许修改节点。

     *note NodeTransformer: 37ed. 将遍历抽象语法树并使用visitor方法的返
     回值去替换或移除旧节点。如果visitor方法的返回值为 ‘None’ , 则该节点
     将从其位置移除，否则将替换为返回值。当返回值是原始节点时，无需替换
     。

     如下是一个转换器示例，它将所有出现的名称 (‘foo’) 重写为
     ‘data['foo']’:

          class RewriteName(NodeTransformer):

              def visit_Name(self, node):
                  return Subscript(
                      value=Name(id='data', ctx=Load()),
                      slice=Index(value=Constant(value=node.id)),
                      ctx=node.ctx
                  )

     请记住，如果您正在操作的节点具有子节点，则必须先转换其子节点或为该
     节点调用 ‘generic_visit()’ 方法。

     对于属于语句集合（适用于所有语句节点）的节点，访问者还可以返回节点
     列表而不仅仅是单个节点。

     If *note NodeTransformer: 37ed. introduces new nodes (that weren’t
     part of original tree) without giving them location information
     (such as ‘lineno’), *note fix_missing_locations(): 37e6. should be
     called with the new sub-tree to recalculate the location
     information:

          tree = ast.parse('foo', mode='eval')
          new_tree = fix_missing_locations(RewriteName().visit(tree))

     通常你可以像这样使用转换器:

          node = YourTransformer().visit(node)

 -- 函数: ast.dump (node, annotate_fields=True,
          include_attributes=False)

     Return a formatted dump of the tree in `node'.  This is mainly
     useful for debugging purposes.  If `annotate_fields' is true (by
     default), the returned string will show the names and the values
     for fields.  If `annotate_fields' is false, the result string will
     be more compact by omitting unambiguous field names.  Attributes
     such as line numbers and column offsets are not dumped by default.
     If this is wanted, `include_attributes' can be set to true.

参见
....

Green Tree Snakes(4), an external documentation resource, has good
details on working with Python ASTs.

ASTTokens(5) annotates Python ASTs with the positions of tokens and text
in the source code that generated them.  This is helpful for tools that
make source code transformations.

leoAst.py(6) unifies the token-based and parse-tree-based views of
python programs by inserting two-way links between tokens and ast nodes.

LibCST(7) parses code as a Concrete Syntax Tree that looks like an ast
tree and keeps all formatting details.  It’s useful for building
automated refactoring (codemod) applications and linters.

Parso(8) is a Python parser that supports error recovery and round-trip
parsing for different Python versions (in multiple Python versions).
Parso is also able to list multiple syntax errors in your python file.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0526

   (3) https://www.python.org/dev/peps/pep-0484

   (4) https://greentreesnakes.readthedocs.io/

   (5) https://asttokens.readthedocs.io/en/latest/user-guide.html

   (6) http://leoeditor.com/appendices.html#leoast-py

   (7) https://libcst.readthedocs.io/

   (8) https://parso.readthedocs.io


File: python.info,  Node: symtable --- Access to the compiler's symbol tables,  Next: symbol --- 与 Python 解析树一起使用的常量,  Prev: ast --- 抽象语法树,  Up: Python 语言服务

5.32.3 ‘symtable’ — Access to the compiler’s symbol tables
----------------------------------------------------------

`Source code:' Lib/symtable.py(1)

__________________________________________________________________

Symbol tables are generated by the compiler from AST just before
bytecode is generated.  The symbol table is responsible for calculating
the scope of every identifier in the code.  *note symtable: fd. provides
an interface to examine these tables.

* Menu:

* Generating Symbol Tables::
* Examining Symbol Tables::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/symtable.py


File: python.info,  Node: Generating Symbol Tables,  Next: Examining Symbol Tables,  Up: symtable --- Access to the compiler's symbol tables

5.32.3.1 Generating Symbol Tables
.................................

 -- 函数: symtable.symtable (code, filename, compile_type)

     Return the toplevel *note SymbolTable: 37f1. for the Python source
     `code'.  `filename' is the name of the file containing the code.
     `compile_type' is like the `mode' argument to *note compile(): 1b5.


File: python.info,  Node: Examining Symbol Tables,  Prev: Generating Symbol Tables,  Up: symtable --- Access to the compiler's symbol tables

5.32.3.2 Examining Symbol Tables
................................

 -- 类: symtable.SymbolTable

     A namespace table for a block.  The constructor is not public.

      -- 方法: get_type ()

          Return the type of the symbol table.  Possible values are
          ‘'class'’, ‘'module'’, and ‘'function'’.

      -- 方法: get_id ()

          Return the table’s identifier.

      -- 方法: get_name ()

          Return the table’s name.  This is the name of the class if the
          table is for a class, the name of the function if the table is
          for a function, or ‘'top'’ if the table is global (*note
          get_type(): 37f3. returns ‘'module'’).

      -- 方法: get_lineno ()

          Return the number of the first line in the block this table
          represents.

      -- 方法: is_optimized ()

          Return ‘True’ if the locals in this table can be optimized.

      -- 方法: is_nested ()

          Return ‘True’ if the block is a nested class or function.

      -- 方法: has_children ()

          Return ‘True’ if the block has nested namespaces within it.
          These can be obtained with *note get_children(): 37fa.

      -- 方法: has_exec ()

          Return ‘True’ if the block uses ‘exec’.

      -- 方法: get_identifiers ()

          Return a list of names of symbols in this table.

      -- 方法: lookup (name)

          Lookup `name' in the table and return a *note Symbol: 37fe.
          instance.

      -- 方法: get_symbols ()

          Return a list of *note Symbol: 37fe. instances for names in
          the table.

      -- 方法: get_children ()

          Return a list of the nested symbol tables.

 -- 类: symtable.Function

     A namespace for a function or method.  This class inherits *note
     SymbolTable: 37f1.

      -- 方法: get_parameters ()

          Return a tuple containing names of parameters to this
          function.

      -- 方法: get_locals ()

          Return a tuple containing names of locals in this function.

      -- 方法: get_globals ()

          Return a tuple containing names of globals in this function.

      -- 方法: get_nonlocals ()

          Return a tuple containing names of nonlocals in this function.

      -- 方法: get_frees ()

          Return a tuple containing names of free variables in this
          function.

 -- 类: symtable.Class

     A namespace of a class.  This class inherits *note SymbolTable:
     37f1.

      -- 方法: get_methods ()

          Return a tuple containing the names of methods declared in the
          class.

 -- 类: symtable.Symbol

     An entry in a *note SymbolTable: 37f1. corresponding to an
     identifier in the source.  The constructor is not public.

      -- 方法: get_name ()

          Return the symbol’s name.

      -- 方法: is_referenced ()

          Return ‘True’ if the symbol is used in its block.

      -- 方法: is_imported ()

          Return ‘True’ if the symbol is created from an import
          statement.

      -- 方法: is_parameter ()

          Return ‘True’ if the symbol is a parameter.

      -- 方法: is_global ()

          Return ‘True’ if the symbol is global.

      -- 方法: is_nonlocal ()

          Return ‘True’ if the symbol is nonlocal.

      -- 方法: is_declared_global ()

          Return ‘True’ if the symbol is declared global with a global
          statement.

      -- 方法: is_local ()

          Return ‘True’ if the symbol is local to its block.

      -- 方法: is_annotated ()

          Return ‘True’ if the symbol is annotated.

          3.6 新版功能.

      -- 方法: is_free ()

          Return ‘True’ if the symbol is referenced in its block, but
          not assigned to.

      -- 方法: is_assigned ()

          Return ‘True’ if the symbol is assigned to in its block.

      -- 方法: is_namespace ()

          Return ‘True’ if name binding introduces new namespace.

          If the name is used as the target of a function or class
          statement, this will be true.

          例如

               >>> table = symtable.symtable("def some_func(): pass", "string", "exec")
               >>> table.lookup("some_func").is_namespace()
               True

          Note that a single name can be bound to multiple objects.  If
          the result is ‘True’, the name may also be bound to other
          objects, like an int or list, that does not introduce a new
          namespace.

      -- 方法: get_namespaces ()

          Return a list of namespaces bound to this name.

      -- 方法: get_namespace ()

          Return the namespace bound to this name.  If more than one
          namespace is bound, *note ValueError: 1fc. is raised.


File: python.info,  Node: symbol --- 与 Python 解析树一起使用的常量,  Next: token --- 与Python解析树一起使用的常量,  Prev: symtable --- Access to the compiler's symbol tables,  Up: Python 语言服务

5.32.4 ‘symbol’ — 与 Python 解析树一起使用的常量
------------------------------------------------

`源代码:' Lib/symbol.py(1)

__________________________________________________________________

此模块提供用于表示解析树内部节点数值的常量。 与大多数 Python 不同，这些
常量使用小写字符名称。 请参阅 Python 发行版中的 ‘Grammar/Grammar’ 文件来
获取该语言语法上下文中对这些名称的定义。 这些名称所映射的特定数字值可能
会在 Python 版本之间更改。

此模块还提供了一个额外的数据对象:

 -- 数据: symbol.sym_name

     将此模块中定义的常量的数值映射回名称字符串的字典，允许生成更加人类
     可读的解析树表示。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/symbol.py


File: python.info,  Node: token --- 与Python解析树一起使用的常量,  Next: keyword --- 检验Python关键字,  Prev: symbol --- 与 Python 解析树一起使用的常量,  Up: Python 语言服务

5.32.5 ‘token’ — 与Python解析树一起使用的常量
---------------------------------------------

`源码：' Lib/token.py(1)

__________________________________________________________________

此模块提供表示解析树（终端令牌）的叶节点的数值的常量。 请参阅 Python 发
行版中的文件 ‘Grammar/Grammar’ ，以获取语言语法上下文中名称的定义。 名称
映射到的特定数值可能会在 Python 版本之间更改。

该模块还提供从数字代码到名称和一些函数的映射。 这些函数镜像了 Python C 头
文件中的定义。

 -- 数据: token.tok_name

     将此模块中定义的常量的数值映射回名称字符串的字典，允许生成更加人类
     可读的解析树表示。

 -- 函数: token.ISTERMINAL (x)

     对终端标记值返回 ‘True’。

 -- 函数: token.ISNONTERMINAL (x)

     对非终端标记值返回 ‘True’。

 -- 函数: token.ISEOF (x)

     如果 `x' 是表示输入结束的标记则返回 ‘True’。

标记常量是：

 -- 数据: token.ENDMARKER

 -- 数据: token.NAME

 -- 数据: token.NUMBER

 -- 数据: token.STRING

 -- 数据: token.NEWLINE

 -- 数据: token.INDENT

 -- 数据: token.DEDENT

 -- 数据: token.LPAR

     ‘"("’ 的权标值。

 -- 数据: token.RPAR

     ‘")"’ 的权标值。

 -- 数据: token.LSQB

     ‘"["’ 的权标值。

 -- 数据: token.RSQB

     ‘"]"’ 的权标值。

 -- 数据: token.COLON

     ‘":"’ 的权标值。

 -- 数据: token.COMMA

     ‘","’ 的权标值。

 -- 数据: token.SEMI

     ‘";"’ 的权标值。

 -- 数据: token.PLUS

     ‘"+"’ 的权标值。

 -- 数据: token.MINUS

     ‘"-"’ 的权标值。

 -- 数据: token.STAR

     ‘"*"’ 的权标值。

 -- 数据: token.SLASH

     ‘"/"’ 的权标值。

 -- 数据: token.VBAR

     ‘"|"’ 的权标值。

 -- 数据: token.AMPER

     ‘"&"’ 的权标值。

 -- 数据: token.LESS

     ‘"<"’ 的权标值。

 -- 数据: token.GREATER

     ‘">"’ 的权标值。

 -- 数据: token.EQUAL

     Token value for ‘"="’.

 -- 数据: token.DOT

     Token value for ‘"."’.

 -- 数据: token.PERCENT

     Token value for ‘"%"’.

 -- 数据: token.LBRACE

     Token value for ‘"{"’.

 -- 数据: token.RBRACE

     Token value for ‘"}"’.

 -- 数据: token.EQEQUAL

     Token value for ‘"=="’.

 -- 数据: token.NOTEQUAL

     Token value for ‘"!="’.

 -- 数据: token.LESSEQUAL

     Token value for ‘"<="’.

 -- 数据: token.GREATEREQUAL

     Token value for ‘">="’.

 -- 数据: token.TILDE

     Token value for ‘"~"’.

 -- 数据: token.CIRCUMFLEX

     Token value for ‘"^"’.

 -- 数据: token.LEFTSHIFT

     Token value for ‘"<<"’.

 -- 数据: token.RIGHTSHIFT

     Token value for ‘">>"’.

 -- 数据: token.DOUBLESTAR

     Token value for ‘"**"’.

 -- 数据: token.PLUSEQUAL

     Token value for ‘"+="’.

 -- 数据: token.MINEQUAL

     Token value for ‘"-="’.

 -- 数据: token.STAREQUAL

     Token value for ‘"*="’.

 -- 数据: token.SLASHEQUAL

     Token value for ‘"/="’.

 -- 数据: token.PERCENTEQUAL

     Token value for ‘"%="’.

 -- 数据: token.AMPEREQUAL

     Token value for ‘"&="’.

 -- 数据: token.VBAREQUAL

     Token value for ‘"|="’.

 -- 数据: token.CIRCUMFLEXEQUAL

     Token value for ‘"^="’.

 -- 数据: token.LEFTSHIFTEQUAL

     Token value for ‘"<<="’.

 -- 数据: token.RIGHTSHIFTEQUAL

     Token value for ‘">>="’.

 -- 数据: token.DOUBLESTAREQUAL

     Token value for ‘"**="’.

 -- 数据: token.DOUBLESLASH

     Token value for ‘"//"’.

 -- 数据: token.DOUBLESLASHEQUAL

     Token value for ‘"//="’.

 -- 数据: token.AT

     Token value for ‘"@"’.

 -- 数据: token.ATEQUAL

     Token value for ‘"@="’.

 -- 数据: token.RARROW

     Token value for ‘"->"’.

 -- 数据: token.ELLIPSIS

     Token value for ‘"..."’.

 -- 数据: token.COLONEQUAL

     Token value for ‘":="’.

 -- 数据: token.OP

 -- 数据: token.AWAIT

 -- 数据: token.ASYNC

 -- 数据: token.TYPE_IGNORE

 -- 数据: token.TYPE_COMMENT

 -- 数据: token.ERRORTOKEN

 -- 数据: token.N_TOKENS

 -- 数据: token.NT_OFFSET

C 标记生成器不使用以下标记类型值，但 *note tokenize: 112. 模块需要这些标
记类型值。

 -- 数据: token.COMMENT

     标记值用于表示注释。

 -- 数据: token.NL

     标记值用于表示非终止换行符。 *note NEWLINE: 3821. 标记表示 Python 代
     码逻辑行的结束；当在多条物理线路上继续执行逻辑代码行时，会生成 ‘NL’
     标记。

 -- 数据: token.ENCODING

     指示用于将源字节解码为文本的编码的标记值。 *note
     tokenize.tokenize(): c63. 返回的第一个标记将始终是一个 ‘ENCODING’ 标
     记。

 -- 数据: token.TYPE_COMMENT

     Token value indicating that a type comment was recognized.  Such
     tokens are only produced when *note ast.parse(): 1a2. is invoked
     with ‘type_comments=True’.

在 3.5 版更改: 补充 *note AWAIT: 3854. 和 *note ASYNC: 3855. 标记。

在 3.7 版更改: 补充 *note COMMENT: 385b. 、 *note NL: 385c. 和 *note
ENCODING: 385d. 标记。

在 3.7 版更改: 移除 *note AWAIT: 3854. 和 *note ASYNC: 3855. 标记。
"async" 和 "await" 现在被标记为 *note NAME: 381e. 标记。

在 3.8 版更改: Added *note TYPE_COMMENT: 3857, *note TYPE_IGNORE: 3856,
*note COLONEQUAL: 3852.  Added *note AWAIT: 3854. and *note ASYNC: 3855.
tokens back (they’re needed to support parsing older Python versions for
*note ast.parse(): 1a2. with ‘feature_version’ set to 6 or lower).

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/token.py


File: python.info,  Node: keyword --- 检验Python关键字,  Next: tokenize --- 对 Python 代码使用的标记解析器,  Prev: token --- 与Python解析树一起使用的常量,  Up: Python 语言服务

5.32.6 ‘keyword’ — 检验Python关键字
-----------------------------------

`源码：' Lib/keyword.py(1)

__________________________________________________________________

此模块允许 Python 程序确定某个字符串是否为 *note 关键字: 13ec.。

 -- 函数: keyword.iskeyword (s)

     如果 `s' 是一个 Python *note 关键字: 13ec. 则返回 ‘True’。

 -- 数据: keyword.kwlist

     包含解释器定义的所有 *note 关键字: 13ec. 的序列。 如果所定义的任何
     关键字仅在特定 *note __future__: 0. 语句生效时被激活，它们也将被包
     含在内。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/keyword.py


File: python.info,  Node: tokenize --- 对 Python 代码使用的标记解析器,  Next: tabnanny --- 模糊缩进检测,  Prev: keyword --- 检验Python关键字,  Up: Python 语言服务

5.32.7 ‘tokenize’ — 对 Python 代码使用的标记解析器
--------------------------------------------------

`源码：' Lib/tokenize.py(1)

__________________________________________________________________

The *note tokenize: 112. module provides a lexical scanner for Python
source code, implemented in Python.  The scanner in this module returns
comments as tokens as well, making it useful for implementing
"pretty-printers", including colorizers for on-screen displays.

为了简化标记流的处理，所有的 *note 运算符: 1429. 和 *note 定界符: 142a.
以及 *note Ellipsis: 161c. 返回时都会打上通用的 *note OP: 3853. 标记。 可
以通过 *note tokenize.tokenize(): c63. 返回的 *note named tuple: aab. 对
象的 ‘exact_type’ 属性来获得确切的标记类型。

* Menu:

* 对输入进行解析标记::
* Command-Line Usage: Command-Line Usage<2>.
* 例子: 例子<30>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/tokenize.py


File: python.info,  Node: 对输入进行解析标记,  Next: Command-Line Usage<2>,  Up: tokenize --- 对 Python 代码使用的标记解析器

5.32.7.1 对输入进行解析标记
...........................

主要的入口是一个 *note generator: 9aa.:

 -- 函数: tokenize.tokenize (readline)

     生成器 *note tokenize(): c63. 需要一个 `readline' 参数，这个参数必
     须是一个可调用对象，且能提供与文件对象的 *note
     io.IOBase.readline(): 1713. 方法相同的接口。每次调用这个函数都要 返
     回字节类型输入的一行数据。

     The generator produces 5-tuples with these members: the token type;
     the token string; a 2-tuple ‘(srow, scol)’ of ints specifying the
     row and column where the token begins in the source; a 2-tuple
     ‘(erow, ecol)’ of ints specifying the row and column where the
     token ends in the source; and the line on which the token was
     found.  The line passed (the last tuple item) is the `physical'
     line.  The 5 tuple is returned as a *note named tuple: aab. with
     the field names: ‘type string start end line’.

     The returned *note named tuple: aab. has an additional property
     named ‘exact_type’ that contains the exact operator type for *note
     OP: 3853. tokens.  For all other token types ‘exact_type’ equals
     the named tuple ‘type’ field.

     在 3.1 版更改: Added support for named tuples.

     在 3.3 版更改: Added support for ‘exact_type’.

     *note tokenize(): c63. determines the source encoding of the file
     by looking for a UTF-8 BOM or encoding cookie, according to PEP
     263(1).

 -- 函数: tokenize.generate_tokens (readline)

     Tokenize a source reading unicode strings instead of bytes.

     Like *note tokenize(): c63, the `readline' argument is a callable
     returning a single line of input.  However, *note
     generate_tokens(): 1045. expects `readline' to return a str object
     rather than bytes.

     The result is an iterator yielding named tuples, exactly like *note
     tokenize(): c63.  It does not yield an *note ENCODING: 385d. token.

All constants from the *note token: 111. module are also exported from
*note tokenize: 112.

Another function is provided to reverse the tokenization process.  This
is useful for creating tools that tokenize a script, modify the token
stream, and write back the modified script.

 -- 函数: tokenize.untokenize (iterable)

     Converts tokens back into Python source code.  The `iterable' must
     return sequences with at least two elements, the token type and the
     token string.  Any additional sequence elements are ignored.

     The reconstructed script is returned as a single string.  The
     result is guaranteed to tokenize back to match the input so that
     the conversion is lossless and round-trips are assured.  The
     guarantee applies only to the token type and token string as the
     spacing between tokens (column positions) may change.

     It returns bytes, encoded using the *note ENCODING: 385d. token,
     which is the first token sequence output by *note tokenize(): c63.
     If there is no encoding token in the input, it returns a str
     instead.

*note tokenize(): c63. needs to detect the encoding of source files it
tokenizes.  The function it uses to do this is available:

 -- 函数: tokenize.detect_encoding (readline)

     The *note detect_encoding(): 1c90. function is used to detect the
     encoding that should be used to decode a Python source file.  It
     requires one argument, readline, in the same way as the *note
     tokenize(): c63. generator.

     It will call readline a maximum of twice, and return the encoding
     used (as a string) and a list of any lines (not decoded from bytes)
     it has read in.

     It detects the encoding from the presence of a UTF-8 BOM or an
     encoding cookie as specified in PEP 263(2).  If both a BOM and a
     cookie are present, but disagree, a *note SyntaxError: 460. will be
     raised.  Note that if the BOM is found, ‘'utf-8-sig'’ will be
     returned as an encoding.

     If no encoding is specified, then the default of ‘'utf-8'’ will be
     returned.

     Use *note open(): 1c8f. to open Python source files: it uses *note
     detect_encoding(): 1c90. to detect the file encoding.

 -- 函数: tokenize.open (filename)

     Open a file in read only mode using the encoding detected by *note
     detect_encoding(): 1c90.

     3.2 新版功能.

 -- 例外: tokenize.TokenError

     Raised when either a docstring or expression that may be split over
     several lines is not completed anywhere in the file, for example:

          """Beginning of
          docstring

     或者：

          [1,
           2,
           3

Note that unclosed single-quoted strings do not cause an error to be
raised.  They are tokenized as *note ERRORTOKEN: 3858, followed by the
tokenization of their contents.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0263

   (2) https://www.python.org/dev/peps/pep-0263


File: python.info,  Node: Command-Line Usage<2>,  Next: 例子<30>,  Prev: 对输入进行解析标记,  Up: tokenize --- 对 Python 代码使用的标记解析器

5.32.7.2 Command-Line Usage
...........................

3.3 新版功能.

The *note tokenize: 112. module can be executed as a script from the
command line.  It is as simple as:

     python -m tokenize [-e] [filename.py]

The following options are accepted:

 -- 程序选项: -h, --help

     show this help message and exit

 -- 程序选项: -e, --exact

     display token names using the exact type

If ‘filename.py’ is specified its contents are tokenized to stdout.
Otherwise, tokenization is performed on stdin.


File: python.info,  Node: 例子<30>,  Prev: Command-Line Usage<2>,  Up: tokenize --- 对 Python 代码使用的标记解析器

5.32.7.3 例子
.............

Example of a script rewriter that transforms float literals into Decimal
objects:

     from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP
     from io import BytesIO

     def decistmt(s):
         """Substitute Decimals for floats in a string of statements.

         >>> from decimal import Decimal
         >>> s = 'print(+21.3e-5*-.1234/81.7)'
         >>> decistmt(s)
         "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"

         The format of the exponent is inherited from the platform C library.
         Known cases are "e-007" (Windows) and "e-07" (not Windows).  Since
         we're only showing 12 digits, and the 13th isn't close to 5, the
         rest of the output should be platform-independent.

         >>> exec(s)  #doctest: +ELLIPSIS
         -3.21716034272e-0...7

         Output from calculations with Decimal should be identical across all
         platforms.

         >>> exec(decistmt(s))
         -3.217160342717258261933904529E-7
         """
         result = []
         g = tokenize(BytesIO(s.encode('utf-8')).readline)  # tokenize the string
         for toknum, tokval, _, _, _ in g:
             if toknum == NUMBER and '.' in tokval:  # replace NUMBER tokens
                 result.extend([
                     (NAME, 'Decimal'),
                     (OP, '('),
                     (STRING, repr(tokval)),
                     (OP, ')')
                 ])
             else:
                 result.append((toknum, tokval))
         return untokenize(result).decode('utf-8')

Example of tokenizing from the command line.  The script:

     def say_hello():
         print("Hello, World!")

     say_hello()

will be tokenized to the following output where the first column is the
range of the line/column coordinates where the token is found, the
second column is the name of the token, and the final column is the
value of the token (if any)

     $ python -m tokenize hello.py
     0,0-0,0:            ENCODING       'utf-8'
     1,0-1,3:            NAME           'def'
     1,4-1,13:           NAME           'say_hello'
     1,13-1,14:          OP             '('
     1,14-1,15:          OP             ')'
     1,15-1,16:          OP             ':'
     1,16-1,17:          NEWLINE        '\n'
     2,0-2,4:            INDENT         '    '
     2,4-2,9:            NAME           'print'
     2,9-2,10:           OP             '('
     2,10-2,25:          STRING         '"Hello, World!"'
     2,25-2,26:          OP             ')'
     2,26-2,27:          NEWLINE        '\n'
     3,0-3,1:            NL             '\n'
     4,0-4,0:            DEDENT         ''
     4,0-4,9:            NAME           'say_hello'
     4,9-4,10:           OP             '('
     4,10-4,11:          OP             ')'
     4,11-4,12:          NEWLINE        '\n'
     5,0-5,0:            ENDMARKER      ''

The exact token type names can be displayed using the *note -e: 3869.
option:

     $ python -m tokenize -e hello.py
     0,0-0,0:            ENCODING       'utf-8'
     1,0-1,3:            NAME           'def'
     1,4-1,13:           NAME           'say_hello'
     1,13-1,14:          LPAR           '('
     1,14-1,15:          RPAR           ')'
     1,15-1,16:          COLON          ':'
     1,16-1,17:          NEWLINE        '\n'
     2,0-2,4:            INDENT         '    '
     2,4-2,9:            NAME           'print'
     2,9-2,10:           LPAR           '('
     2,10-2,25:          STRING         '"Hello, World!"'
     2,25-2,26:          RPAR           ')'
     2,26-2,27:          NEWLINE        '\n'
     3,0-3,1:            NL             '\n'
     4,0-4,0:            DEDENT         ''
     4,0-4,9:            NAME           'say_hello'
     4,9-4,10:           LPAR           '('
     4,10-4,11:          RPAR           ')'
     4,11-4,12:          NEWLINE        '\n'
     5,0-5,0:            ENDMARKER      ''

Example of tokenizing a file programmatically, reading unicode strings
instead of bytes with *note generate_tokens(): 1045.:

     import tokenize

     with tokenize.open('hello.py') as f:
         tokens = tokenize.generate_tokens(f.readline)
         for token in tokens:
             print(token)

或者通过 *note tokenize(): c63. 直接读取字节数据:

     import tokenize

     with open('hello.py', 'rb') as f:
         tokens = tokenize.tokenize(f.readline)
         for token in tokens:
             print(token)


File: python.info,  Node: tabnanny --- 模糊缩进检测,  Next: pyclbr --- Python 模块浏览器支持,  Prev: tokenize --- 对 Python 代码使用的标记解析器,  Up: Python 语言服务

5.32.8 ‘tabnanny’ — 模糊缩进检测
--------------------------------

`源代码:' Lib/tabnanny.py(1)

__________________________________________________________________

目前，该模块旨在作为脚本调用。但是可以使用下面描述的 *note check():
386d. 函数将其导入IDE。

     注解: 此模块提供的API可能会在将来的版本中更改；此类更改可能无法向后
     兼容。

 -- 函数: tabnanny.check (file_or_dir)

     如果 `file_or_dir' 是目录而非符号链接，则递归地在名为 `file_or_dir'
     的目录树中下行，沿途检查所有 ‘.py’ 文件。 如果 `file_or_dir' 是一个
     普通 Python 源文件，将检查其中的空格相关问题。 诊断消息将使用 *note
     print(): 88f. 函数写入到标准输出。

 -- 数据: tabnanny.verbose

     此旗标指明是否打印详细消息。 如果作为脚本调用则是通过 ‘-v’ 选项来增
     加。

 -- 数据: tabnanny.filename_only

     此旗标指明是否只打印包含空格相关问题文件的文件名。 如果作为脚本调用
     则是通过 ‘-q’ 选项来设为真值。

 -- 例外: tabnanny.NannyNag

     如果检测到模糊缩进则由 *note process_tokens(): 3871. 引发。 在
     *note check(): 386d. 中捕获并处理。

 -- 函数: tabnanny.process_tokens (tokens)

     此函数由 *note check(): 386d. 用来处理由 *note tokenize: 112. 模块
     所生成的标记。

参见
....

模块 *note tokenize: 112.

     用于Python源代码的词法扫描程序。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/tabnanny.py


File: python.info,  Node: pyclbr --- Python 模块浏览器支持,  Next: py_compile --- 编译 Python 源文件,  Prev: tabnanny --- 模糊缩进检测,  Up: Python 语言服务

5.32.9 ‘pyclbr’ — Python 模块浏览器支持
---------------------------------------

`源代码:' Lib/pyclbr.py(1)

__________________________________________________________________

*note pyclbr: d9. 模块提供了对于以 Python 编写的模块中定义的函数、类和方
法的受限信息。 这种信息足够用来实现一个模块浏览器。 这种信息是从 Python
源代码中直接提取而非通过导入模块，因此该模块可以安全地用于不受信任的代码
。 此限制使得非 Python 实现的模块无法使用此模块，包括所有标准和可选的扩
展模块。

 -- 函数: pyclbr.readmodule (module, path=None)

     返回一个将模块层级的类名映射到类描述器的字典。 如果可能，将会包括已
     导入基类的描述器。 形参 `module' 为要读取模块名称的字符串；它可能是
     某个包内部的模块名称。 `path' 如果给出则为添加到 ‘sys.path’ 开头的
     目录路径序列，它会被用于定位模块的源代码。

     此函数为原始接口，仅保留用于向下兼容。 它会返回以下内容的过滤版本。

 -- 函数: pyclbr.readmodule_ex (module, path=None)

     返回一个基于字典的树，其中包含与模块中每个用 ‘def’ 或 ‘class’ 语句
     定义的函数和类相对应的函数和类描述器。 被返回的字典会将模块层级的函
     数和类名映射到它们的描述器。 嵌套的对象会被输入到它们的上级子目录中
     。 与 readmodule 一样，`module' 指明要读取的模块而 `path' 会被添加
     到 sys.path。 如果被读取的模块是一个包，则返回的字典将具有
     ‘'__path__'’ 键，其值是一个包含包搜索路径的列表。

3.7 新版功能: 嵌套定义的描述器。 它们通过新的子属性来访问。 每个定义都会
有一个新的上级属性。

这些函数所返回的描述器是 Function 和 Class 类的实例。 用户不应自行创建这
些类的实例。

* Menu:

* 函数对象::
* 类对象: 类对象<2>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/pyclbr.py


File: python.info,  Node: 函数对象,  Next: 类对象<2>,  Up: pyclbr --- Python 模块浏览器支持

5.32.9.1 函数对象
.................

‘Function’ 类的实例描述了由 def 语句所定义的函数。 它们具有下列属性:

 -- 属性: Function.file

     函数定义所在的文件名。

 -- 属性: Function.module

     定义了所描述函数的模块名。

 -- 属性: Function.name

     函数名称。

 -- 属性: Function.lineno

     定义在文件中起始位置的行号。

 -- 属性: Function.parent

     对于最高层级函数为 None。 对于嵌套函数则为上级函数。

     3.7 新版功能.

 -- 属性: Function.children

     将名称映射到嵌套函数和类描述器的字典。

     3.7 新版功能.


File: python.info,  Node: 类对象<2>,  Prev: 函数对象,  Up: pyclbr --- Python 模块浏览器支持

5.32.9.2 类对象
...............

‘Class’ 类的实例描述了由 class 语句所定义的类。 它们具有与 Function 对象
相同的属性以及两个额外属性。

 -- 属性: Class.file

     类定义所在的文件名称。

 -- 属性: Class.module

     定义了所描述类的模块名称。

 -- 属性: Class.name

     类名称。

 -- 属性: Class.lineno

     定义在文件中起始位置的行号。

 -- 属性: Class.parent

     对于最高层级类为 None。 对于嵌套类则为上级类。

     3.7 新版功能.

 -- 属性: Class.children

     将名称映射到嵌套函数和类描述器的字典。

     3.7 新版功能.

 -- 属性: Class.super

     一个 ‘Class’ 对象的列表，它们描述了所描述类的直接基类。 被命名为超
     类但无法被 *note readmodule_ex(): 117a. 发现的类会作为类名字符串而
     非 ‘Class’ 对象列出。

 -- 属性: Class.methods

     一个将方法名映射到行号的字典。 此属性可从更新的子目录中获取，仅保留
     用于向下兼容。


File: python.info,  Node: py_compile --- 编译 Python 源文件,  Next: compileall --- Byte-compile Python libraries,  Prev: pyclbr --- Python 模块浏览器支持,  Up: Python 语言服务

5.32.10 ‘py_compile’ — 编译 Python 源文件
-----------------------------------------

`源代码:' Lib/py_compile.py(1)

__________________________________________________________________

*note py_compile: d8. 模块提供了用来从源文件生成字节码的函数和另一个用于
当模块源文件作为脚本被调用时的函数。

虽然不太常用，但这个函数在安装共享模块时还是很有用的，特别是当一些用户可
能没有权限在包含源代码的目录中写字节码缓存文件时。

 -- 例外: py_compile.PyCompileError

     当编译文件过程中发生错误时，抛出的异常。

 -- 函数: py_compile.compile (file, cfile=None, dfile=None,
          doraise=False, optimize=-1,
          invalidation_mode=PycInvalidationMode.TIMESTAMP, quiet=0)

     将源文件编译成字节码并写出字节码缓存文件。 源代码从名为 `file' 的文
     件中加载。 字节码会写入到 `cfile'，默认为 PEP 3147(2)/ PEP 488(3) 路
     径，以 ‘.pyc’ 结尾。 举例来说，如果 `file' 是 ‘/foo/bar/baz.py’ 则
     对于 Python 3.2 `cfile' 将默认为
     ‘/foo/bar/__pycache__/baz.cpython-32.pyc’。 如果指定了 `dfile'，则
     在错误信息中它将代替 `file' 作为源文件的名称。 如果 `doraise' 为真
     值，则当编译 `file' 遇到错误时将会引发 *note PyCompileError: 3888.。
     如果 `doraise' 为假值（默认），则将写入错误信息到 ‘sys.stderr’，但
     不会引发异常。 此函数返回编译后字节码文件的路径，即 `cfile' 所使用
     的值。

     `doraise' 和 `quiet' 参数确定在编译文件时如何处理错误。 如果
     `quiet' 为 0 或 1，并且 `doraise' 为假值，则会启用默认行为：写入错
     误信息到 ‘sys.stderr’，并且函数将返回 ‘None’ 而非一个路径。 如果
     `doraise' 为真值，则将改为引发 *note PyCompileError: 3888.。 但是如
     果 `quiet' 为 2，则不会写入消息，并且 `doraise' 也不会有效果。

     如果 `cfile' 所表示（显式指定或计算得出）的路径为符号链接或非常规文
     件，则将引发 *note FileExistsError: 960.。 此行为是用来警告如果允许
     写入编译后字节码文件到这些路径则导入操作将会把它们转为常规文件。 这
     是使用文件重命名来将最终编译后字节码文件放置到位以防止并发文件写入
     问题的导入操作的附带效果。

     `optimize' 控制优化级别并会被传给内置的 *note compile(): 1b5. 函数
     。 默认值 ‘-1’ 表示选择当前解释器的优化级别。

     `invalidation_mode' 应当是 *note PycInvalidationMode: 3889. 枚举的
     成员，它控制在运行时如何让已生成的字节码缓存失效。 如果设置了
     ‘SOURCE_DATE_EPOCH’ 环境变量则默认值为 *note
     PycInvalidationMode.CHECKED_HASH: 388a.，否则默认值为 *note
     PycInvalidationMode.TIMESTAMP: 388b.。

     在 3.2 版更改: 将 `cfile' 的默认值改成与 PEP 3147(4) 兼容。 之前的
     默认值是 `file' + ‘'c'’ (如果启用优化则为 ‘'o'’)。 同时也添加了
     `optimize' 形参。

     在 3.4 版更改: 将代码更改为使用 *note importlib: 9b. 执行字节码缓存
     文件写入。 这意味着文件创建/写入的语义现在与 *note importlib: 9b. 所
     做的相匹配，例如权限、写入和移动语义等等。 同时也添加了当 `cfile' 为
     符号链接或非常规文件时引发 *note FileExistsError: 960. 的预警设置。

     在 3.7 版更改: `invalidation_mode' 形参是根据 PEP 552(5) 的描述添加
     的。 如果设置了 ‘SOURCE_DATE_EPOCH’ 环境变量，`invalidation_mode' 将
     被强制设为 *note PycInvalidationMode.CHECKED_HASH: 388a.。

     在 3.7.2 版更改: ‘SOURCE_DATE_EPOCH’ 环境变量不会再覆盖
     `invalidation_mode' 参数的值，而改为确定其默认值。

     在 3.8 版更改: 增加了 `quiet' 形参。

 -- 类: py_compile.PycInvalidationMode

     一个由可用方法组成的枚举，解释器可以用来确定字节码文件是否与源文件
     保持一致。 ‘.pyc’ 文件在其标头中指明了所需的失效模式。 请参阅 *note
     已缓存字节码的失效: 332. 了解有关 Python 在运行时如何让 ‘.pyc’ 文件
     失效的更多信息。

     3.7 新版功能.

      -- 属性: TIMESTAMP

          ‘.pyc’ 文件包括时间戳和源文件的大小，Python 将在运行时将其与源
          文件的元数据进行比较以确定 ‘.pyc’ 文件是否需要重新生成。

      -- 属性: CHECKED_HASH

          ‘.pyc’ 文件包括源文件内容的哈希值，Python 将在运行时将其与源文
          件内容进行比较以确定 ‘.pyc’ 文件是否需要重新生成。

      -- 属性: UNCHECKED_HASH

          类似于 *note CHECKED_HASH: 388a.，‘.pyc’ 文件包括源文件内容的
          哈希值。 但是，Python 将在运行时假定 ‘.pyc’ 文件是最新的而完全
          不会将 ‘.pyc’ 与源文件进行验证。

          此选项适用于 ‘.pycs’ 由 Python 以外的某个系统例如构建系统来确
          保最新的情况。

 -- 函数: py_compile.main (args=None)

     编译多个源文件。 在 `args' 中（或者当 `args' 为 ‘None’ 时则是在命令
     行中）指定的文件会被编译并将结果字节码以正常方式来缓存。 此函数不会
     搜索目录结构来定位源文件；它只编译显式指定的文件。 如果 ‘'-'’ 是
     args 中唯一的值，则会从标准输入获取文件列表。

     在 3.2 版更改: 添加了对 ‘'-'’ 的支持。

当此模块作为脚本运行时，会使用 *note main(): 388d. 来编译命令行中指定的
所有文件。 如果某个文件无法被编译则退出状态将为非零值。

参见
....

模块 *note compileall: 21.

     编译一个目录树中所有 Python 源文件的工具。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/py_compile.py

   (2) https://www.python.org/dev/peps/pep-3147

   (3) https://www.python.org/dev/peps/pep-0488

   (4) https://www.python.org/dev/peps/pep-3147

   (5) https://www.python.org/dev/peps/pep-0552


File: python.info,  Node: compileall --- Byte-compile Python libraries,  Next: dis --- Python 字节码反汇编器,  Prev: py_compile --- 编译 Python 源文件,  Up: Python 语言服务

5.32.11 ‘compileall’ — Byte-compile Python libraries
----------------------------------------------------

`Source code:' Lib/compileall.py(1)

__________________________________________________________________

This module provides some utility functions to support installing Python
libraries.  These functions compile Python source files in a directory
tree.  This module can be used to create the cached byte-code files at
library installation time, which makes them available for use even by
users who don’t have write permission to the library directories.

* Menu:

* Command-line use::
* Public functions::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/compileall.py


File: python.info,  Node: Command-line use,  Next: Public functions,  Up: compileall --- Byte-compile Python libraries

5.32.11.1 Command-line use
..........................

This module can work as a script (using ‘python -m compileall’) to
compile Python sources.

 -- 程序选项: directory ...
 -- 程序选项: file ...

     Positional arguments are files to compile or directories that
     contain source files, traversed recursively.  If no argument is
     given, behave as if the command line was ‘-l <directories from
     sys.path>’.

 -- 程序选项: -l

     Do not recurse into subdirectories, only compile source code files
     directly contained in the named or implied directories.

 -- 程序选项: -f

     Force rebuild even if timestamps are up-to-date.

 -- 程序选项: -q

     Do not print the list of files compiled.  If passed once, error
     messages will still be printed.  If passed twice (‘-qq’), all
     output is suppressed.

 -- 程序选项: -d destdir

     Directory prepended to the path to each file being compiled.  This
     will appear in compilation time tracebacks, and is also compiled in
     to the byte-code file, where it will be used in tracebacks and
     other messages in cases where the source file does not exist at the
     time the byte-code file is executed.

 -- 程序选项: -x regex

     regex is used to search the full path to each file considered for
     compilation, and if the regex produces a match, the file is
     skipped.

 -- 程序选项: -i list

     Read the file ‘list’ and add each line that it contains to the list
     of files and directories to compile.  If ‘list’ is ‘-’, read lines
     from ‘stdin’.

 -- 程序选项: -b

     Write the byte-code files to their legacy locations and names,
     which may overwrite byte-code files created by another version of
     Python.  The default is to write files to their PEP 3147(1)
     locations and names, which allows byte-code files from multiple
     versions of Python to coexist.

 -- 程序选项: -r

     Control the maximum recursion level for subdirectories.  If this is
     given, then ‘-l’ option will not be taken into account.  ‘python -m
     compileall <directory> -r 0’ is equivalent to ‘python -m compileall
     <directory> -l’.

 -- 程序选项: -j N

     Use `N' workers to compile the files within the given directory.
     If ‘0’ is used, then the result of *note os.cpu_count(): 888. will
     be used.

 -- 程序选项: --invalidation-mode
          [timestamp|checked-hash|unchecked-hash]

     Control how the generated byte-code files are invalidated at
     runtime.  The ‘timestamp’ value, means that ‘.pyc’ files with the
     source timestamp and size embedded will be generated.  The
     ‘checked-hash’ and ‘unchecked-hash’ values cause hash-based pycs to
     be generated.  Hash-based pycs embed a hash of the source file
     contents rather than a timestamp.  See *note 已缓存字节码的失效:
     332. for more information on how Python validates bytecode cache
     files at runtime.  The default is ‘timestamp’ if the
     ‘SOURCE_DATE_EPOCH’ environment variable is not set, and
     ‘checked-hash’ if the ‘SOURCE_DATE_EPOCH’ environment variable is
     set.

在 3.2 版更改: Added the ‘-i’, ‘-b’ and ‘-h’ options.

在 3.5 版更改: Added the ‘-j’, ‘-r’, and ‘-qq’ options.  ‘-q’ option was
changed to a multilevel value.  ‘-b’ will always produce a byte-code
file ending in ‘.pyc’, never ‘.pyo’.

在 3.7 版更改: Added the ‘--invalidation-mode’ option.

There is no command-line option to control the optimization level used
by the *note compile(): 1b5. function, because the Python interpreter
itself already provides the option: ‘python -O -m compileall’.

Similarly, the *note compile(): 1b5. function respects the *note
sys.pycache_prefix: 157. setting.  The generated bytecode cache will
only be useful if *note compile(): 1b5. is run with the same *note
sys.pycache_prefix: 157. (if any) that will be used at runtime.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: Public functions,  Prev: Command-line use,  Up: compileall --- Byte-compile Python libraries

5.32.11.2 Public functions
..........................

 -- 函数: compileall.compile_dir (dir, maxlevels=10, ddir=None,
          force=False, rx=None, quiet=0, legacy=False, optimize=-1,
          workers=1, invalidation_mode=None)

     Recursively descend the directory tree named by `dir', compiling
     all ‘.py’ files along the way.  Return a true value if all the
     files compiled successfully, and a false value otherwise.

     The `maxlevels' parameter is used to limit the depth of the
     recursion; it defaults to ‘10’.

     If `ddir' is given, it is prepended to the path to each file being
     compiled for use in compilation time tracebacks, and is also
     compiled in to the byte-code file, where it will be used in
     tracebacks and other messages in cases where the source file does
     not exist at the time the byte-code file is executed.

     If `force' is true, modules are re-compiled even if the timestamps
     are up to date.

     If `rx' is given, its search method is called on the complete path
     to each file considered for compilation, and if it returns a true
     value, the file is skipped.

     If `quiet' is ‘False’ or ‘0’ (the default), the filenames and other
     information are printed to standard out.  Set to ‘1’, only errors
     are printed.  Set to ‘2’, all output is suppressed.

     If `legacy' is true, byte-code files are written to their legacy
     locations and names, which may overwrite byte-code files created by
     another version of Python.  The default is to write files to their
     PEP 3147(1) locations and names, which allows byte-code files from
     multiple versions of Python to coexist.

     `optimize' specifies the optimization level for the compiler.  It
     is passed to the built-in *note compile(): 1b5. function.

     The argument `workers' specifies how many workers are used to
     compile files in parallel.  The default is to not use multiple
     workers.  If the platform can’t use multiple workers and `workers'
     argument is given, then sequential compilation will be used as a
     fallback.  If `workers' is 0, the number of cores in the system is
     used.  If `workers' is lower than ‘0’, a *note ValueError: 1fc.
     will be raised.

     `invalidation_mode' should be a member of the *note
     py_compile.PycInvalidationMode: 3889. enum and controls how the
     generated pycs are invalidated at runtime.

     在 3.2 版更改: Added the `legacy' and `optimize' parameter.

     在 3.5 版更改: Added the `workers' parameter.

     在 3.5 版更改: `quiet' parameter was changed to a multilevel value.

     在 3.5 版更改: The `legacy' parameter only writes out ‘.pyc’ files,
     not ‘.pyo’ files no matter what the value of `optimize' is.

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

     在 3.7 版更改: The `invalidation_mode' parameter was added.

     在 3.7.2 版更改: The `invalidation_mode' parameter’s default value
     is updated to None.

     在 3.8 版更改: Setting `workers' to 0 now chooses the optimal
     number of cores.

 -- 函数: compileall.compile_file (fullname, ddir=None, force=False,
          rx=None, quiet=0, legacy=False, optimize=-1,
          invalidation_mode=None)

     Compile the file with path `fullname'.  Return a true value if the
     file compiled successfully, and a false value otherwise.

     If `ddir' is given, it is prepended to the path to the file being
     compiled for use in compilation time tracebacks, and is also
     compiled in to the byte-code file, where it will be used in
     tracebacks and other messages in cases where the source file does
     not exist at the time the byte-code file is executed.

     If `rx' is given, its search method is passed the full path name to
     the file being compiled, and if it returns a true value, the file
     is not compiled and ‘True’ is returned.

     If `quiet' is ‘False’ or ‘0’ (the default), the filenames and other
     information are printed to standard out.  Set to ‘1’, only errors
     are printed.  Set to ‘2’, all output is suppressed.

     If `legacy' is true, byte-code files are written to their legacy
     locations and names, which may overwrite byte-code files created by
     another version of Python.  The default is to write files to their
     PEP 3147(2) locations and names, which allows byte-code files from
     multiple versions of Python to coexist.

     `optimize' specifies the optimization level for the compiler.  It
     is passed to the built-in *note compile(): 1b5. function.

     `invalidation_mode' should be a member of the *note
     py_compile.PycInvalidationMode: 3889. enum and controls how the
     generated pycs are invalidated at runtime.

     3.2 新版功能.

     在 3.5 版更改: `quiet' parameter was changed to a multilevel value.

     在 3.5 版更改: The `legacy' parameter only writes out ‘.pyc’ files,
     not ‘.pyo’ files no matter what the value of `optimize' is.

     在 3.7 版更改: The `invalidation_mode' parameter was added.

     在 3.7.2 版更改: The `invalidation_mode' parameter’s default value
     is updated to None.

 -- 函数: compileall.compile_path (skip_curdir=True, maxlevels=0,
          force=False, quiet=0, legacy=False, optimize=-1,
          invalidation_mode=None)

     Byte-compile all the ‘.py’ files found along ‘sys.path’.  Return a
     true value if all the files compiled successfully, and a false
     value otherwise.

     If `skip_curdir' is true (the default), the current directory is
     not included in the search.  All other parameters are passed to the
     *note compile_dir(): 37b. function.  Note that unlike the other
     compile functions, ‘maxlevels’ defaults to ‘0’.

     在 3.2 版更改: Added the `legacy' and `optimize' parameter.

     在 3.5 版更改: `quiet' parameter was changed to a multilevel value.

     在 3.5 版更改: The `legacy' parameter only writes out ‘.pyc’ files,
     not ‘.pyo’ files no matter what the value of `optimize' is.

     在 3.7 版更改: The `invalidation_mode' parameter was added.

     在 3.7.2 版更改: The `invalidation_mode' parameter’s default value
     is updated to None.

To force a recompile of all the ‘.py’ files in the ‘Lib/’ subdirectory
and all its subdirectories:

     import compileall

     compileall.compile_dir('Lib/', force=True)

     # Perform same compilation, excluding files in .svn directories.
     import re
     compileall.compile_dir('Lib/', rx=re.compile(r'[/\\][.]svn'), force=True)

     # pathlib.Path objects can also be used.
     import pathlib
     compileall.compile_dir(pathlib.Path('Lib/'), force=True)

参见
....

模块 *note py_compile: d8.

     Byte-compile a single source file.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147

   (2) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: dis --- Python 字节码反汇编器,  Next: pickletools --- pickle 开发者工具集,  Prev: compileall --- Byte-compile Python libraries,  Up: Python 语言服务

5.32.12 ‘dis’ — Python 字节码反汇编器
-------------------------------------

`Source code:' Lib/dis.py(1)

__________________________________________________________________

*note dis: 38. 模块通过反汇编支持CPython的 *note bytecode: 61d. 分析。该
模块作为输入的 CPython 字节码在文件 ‘Include/opcode.h’ 中定义，并由编译
器和解释器使用。

`CPython implementation detail:' 字节码是 CPython 解释器的实现细节。不保
证不会在Python版本之间添加、删除或更改字节码。不应考虑将此模块的跨
Python VM 或 Python 版本的使用。

在 3.6 版更改: 每条指令使用2个字节。以前字节数因指令而异。

示例：给出函数 ‘myfunc()’:

     def myfunc(alist):
         return len(alist)

可以使用以下命令显示 ‘myfunc()’ 的反汇编

     >>> dis.dis(myfunc)
       2           0 LOAD_GLOBAL              0 (len)
                   2 LOAD_FAST                0 (alist)
                   4 CALL_FUNCTION            1
                   6 RETURN_VALUE

("2" 是行号)。

* Menu:

* 字节码分析::
* 分析函数::
* Python字节码说明::
* 操作码集合::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/dis.py


File: python.info,  Node: 字节码分析,  Next: 分析函数,  Up: dis --- Python 字节码反汇编器

5.32.12.1 字节码分析
....................

3.4 新版功能.

字节码分析 API 允许将 Python 代码片段包装在 *note Bytecode: 840. 对象中
，以便轻松访问已编译代码的详细信息。

 -- 类: dis.Bytecode (x, *, first_line=None, current_offset=None)

     分析的字节码对应于函数、生成器、异步生成器、协程、方法、源代码字符
     串或代码对象（由 *note compile(): 1b5. 返回）。

     这是下面列出的许多函数的便利包装，最值得注意的是 *note
     get_instructions(): 83f. ，迭代于 *note Bytecode: 840. 的实例产生字
     节码操作 *note Instruction: 83e. 的实例。

     如果 `first_line' 不是 ‘None’ ，则表示应该为反汇编代码中的第一个源
     代码行报告的行号。否则，源行信息（如果有的话）直接来自反汇编的代码
     对象。

     如果 `current_offset' 不是 ‘None’ ，则它指的是反汇编代码中的指令偏
     移量。设置它意味着 *note dis(): 841. 将针对指定的操作码显示“当前指
     令”标记。

      -- 方法: classmethod from_traceback (tb)

          从给定回溯构造一个 *note Bytecode: 840. 实例，将设置
          `current_offset' 为异常负责的指令。

      -- 数据: codeobj

          已编译的代码对象。

      -- 数据: first_line

          代码对象的第一个源代码行（如果可用）

      -- 方法: dis ()

          返回字节码操作的格式化视图（与 *note dis.dis(): 38c. 打印相同
          ，但作为多行字符串返回）。

      -- 方法: info ()

          返回带有关于代码对象的详细信息的格式化多行字符串，如 *note
          code_info(): bd6. 。

     在 3.7 版更改: 现在可以处理协程和异步生成器对象。

示例:

     >>> bytecode = dis.Bytecode(myfunc)
     >>> for instr in bytecode:
     ...     print(instr.opname)
     ...
     LOAD_GLOBAL
     LOAD_FAST
     CALL_FUNCTION
     RETURN_VALUE


File: python.info,  Node: 分析函数,  Next: Python字节码说明,  Prev: 字节码分析,  Up: dis --- Python 字节码反汇编器

5.32.12.2 分析函数
..................

*note dis: 38. 模块还定义了以下分析函数，它们将输入直接转换为所需的输出
。如果只执行单个操作，它们可能很有用，因此中间分析对象没用：

 -- 函数: dis.code_info (x)

     返回格式化的多行字符串，其包含详细代码对象信息的用于被提供的函数、
     生成器、异步生成器、协程、方法、源代码字符串或代码对象。

     请注意，代码信息字符串的确切内容是高度依赖于实现的，它们可能会在
     Python VM或Python版本中任意更改。

     3.2 新版功能.

     在 3.7 版更改: 现在可以处理协程和异步生成器对象。

 -- 函数: dis.show_code (x, *, file=None)

     将提供的函数、方法。源代码字符串或代码对象的详细代码对象信息打印到
     `file' （如果未指定 `file' ，则为 ‘sys.stdout’ ）。

     这是 ‘print(code_info(x), file=file)’ 的便捷简写，用于在解释器提示
     符下进行交互式探索。

     3.2 新版功能.

     在 3.4 版更改: 添加 `file' 形参。

 -- 函数: dis.dis (x=None, *, file=None, depth=None)

     反汇编 `x' 对象。 `x' 可以表示模块、类、方法、函数、生成器、异步生
     成器、协程、代码对象、源代码字符串或原始字节码的字节序列。对于模块
     ，它会反汇编所有功能。对于一个类，它反汇编所有方法（包括类和静态方
     法）。对于代码对象或原始字节码序列，它每字节码指令打印一行。它还递
     归地反汇编嵌套代码对象（推导式代码，生成器表达式和嵌套函数，以及用
     于构建嵌套类的代码）。在被反汇编之前，首先使用 *note compile():
     1b5. 内置函数将字符串编译为代码对象。如果未提供任何对象，则此函数会
     反汇编最后一次回溯。

     如果提供的话，反汇编将作为文本写入提供的 `file' 参数，否则写入
     ‘sys.stdout’ 。

     递归的最大深度受 `depth' 限制，除非它是 ‘None’ 。 ‘depth=0’ 表示没
     有递归。

     在 3.4 版更改: 添加 `file' 形参。

     在 3.7 版更改: 实现了递归反汇编并添加了 `depth' 参数。

     在 3.7 版更改: 现在可以处理协程和异步生成器对象。

 -- 函数: dis.distb (tb=None, *, file=None)

     如果没有传递，则使用最后一个回溯来反汇编回溯的堆栈顶部函数。 指示了
     导致异常的指令。

     如果提供的话，反汇编将作为文本写入提供的 `file' 参数，否则写入
     ‘sys.stdout’ 。

     在 3.4 版更改: 添加 `file' 形参。

 -- 函数: dis.disassemble (code, lasti=-1, *, file=None)
 -- 函数: dis.disco (code, lasti=-1, *, file=None)

     反汇编代码对象，如果提供了 `lasti' ，则指示最后一条指令。输出分为以
     下几列：

       1. 行号，用于每行的第一条指令

       2. 当前指令，表示为 ‘-->’ ，

       3. 一个标记的指令，用 ‘>>’ 表示，

       4. 指令的地址，

       5. 操作码名称，

       6. 操作参数，和

       7. 括号中参数的解释。

     参数解释识别本地和全局变量名称、常量值、分支目标和比较运算符。

     如果提供的话，反汇编将作为文本写入提供的 `file' 参数，否则写入
     ‘sys.stdout’ 。

     在 3.4 版更改: 添加 `file' 形参。

 -- 函数: dis.get_instructions (x, *, first_line=None)

     在所提供的函数、方法、源代码字符串或代码对象中的指令上返回一个迭代
     器。

     迭代器生成一系列 *note Instruction: 83e. ，命名为元组，提供所提供代
     码中每个操作的详细信息。

     如果 `first_line' 不是 ‘None’ ，则表示应该为反汇编代码中的第一个源
     代码行报告的行号。否则，源行信息（如果有的话）直接来自反汇编的代码
     对象。

     3.4 新版功能.

 -- 函数: dis.findlinestarts (code)

     此生成器函数使用代码对象 `code' 的 ‘co_firstlineno’ 和 ‘co_lnotab’
     属性来查找源代码中行开头的偏移量。它们生成为 ‘(offset, lineno)’ 对
     。请参阅 objects/lnotab_notes.txt(1) ，了解 ‘co_lnotab’ 格式以及如
     何解码它。

     在 3.6 版更改: 行号可能会减少。 以前，他们总是在增加。

 -- 函数: dis.findlabels (code)

     检测作为跳转目标的原始编译后字节码字符串 `code' 中的所有偏移量，并
     返回这些偏移量的列表。

 -- 函数: dis.stack_effect (opcode, oparg=None, *, jump=None)

     使用参数 `oparg' 计算 `opcode' 的堆栈效果。

     如果代码有一个跳转目标并且 `jump' 是 ‘True’ ，则 ‘drag_effect()’ 将
     返回跳转的堆栈效果。如果 `jump' 是 ‘False’ ，它将返回不跳跃的堆栈效
     果。如果 `jump' 是 ‘None’ （默认值），它将返回两种情况的最大堆栈效
     果。

     3.4 新版功能.

     在 3.8 版更改: 添加 `jump' 参数。

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/objects/lnotab_notes.txt


File: python.info,  Node: Python字节码说明,  Next: 操作码集合,  Prev: 分析函数,  Up: dis --- Python 字节码反汇编器

5.32.12.3 Python字节码说明
..........................

*note get_instructions(): 83f. 函数和 *note Bytecode: 840. 类提供字节码
指令的详细信息的 *note Instruction: 83e. 实例：

 -- 类: dis.Instruction

     字节码操作的详细信息

      -- 数据: opcode

          操作的数字代码，对应于下面列出的操作码值和 *note 操作码集合:
          38ab. 中的字节码值。

      -- 数据: opname

          人类可读的操作名称

      -- 数据: arg

          操作的数字参数（如果有的话），否则为 ‘None’

      -- 数据: argval

          已解析的 arg 值（如果已知），否则与 arg 相同

      -- 数据: argrepr

          人类可读的操作参数描述

      -- 数据: offset

          在字节码序列中启动操作索引

      -- 数据: starts_line

          行由此操作码（如果有）启动，否则为 ‘None’

      -- 数据: is_jump_target

          如果其他代码跳到这里，则为 ‘True’ ，否则为 ‘False’

     3.4 新版功能.

Python编译器当前生成以下字节码指令。

`一般指令'

 -- Opcode: NOP

     什么都不做。 用作字节码优化器的占位符。

 -- Opcode: POP_TOP

     删除堆栈顶部（TOS）项。

 -- Opcode: ROT_TWO

     交换两个最顶层的堆栈项。

 -- Opcode: ROT_THREE

     将第二个和第三个堆栈项向上提升一个位置，顶项移动到位置三。

 -- Opcode: ROT_FOUR

     将第二个、第三个和第四个堆栈项向上提升一个位置，将顶项移动到第四个
     位置。

     3.8 新版功能.

 -- Opcode: DUP_TOP

     复制堆栈顶部的引用。

     3.2 新版功能.

 -- Opcode: DUP_TOP_TWO

     复制堆栈顶部的两个引用，使它们保持相同的顺序。

     3.2 新版功能.

`一元操作'

一元操作获取堆栈顶部元素，应用操作，并将结果推回堆栈。

 -- Opcode: UNARY_POSITIVE

     实现 ‘TOS = +TOS’ 。

 -- Opcode: UNARY_NEGATIVE

     实现 ‘TOS = -TOS’ 。

 -- Opcode: UNARY_NOT

     实现 ‘TOS = not TOS’ 。

 -- Opcode: UNARY_INVERT

     实现 ‘TOS = ~TOS’ 。

 -- Opcode: GET_ITER

     实现 ‘TOS = iter(TOS)’ 。

 -- Opcode: GET_YIELD_FROM_ITER

     如果 ‘TOS’ 是一个 *note generator iterator: 45f. 或 *note
     coroutine: 1a7. 对象则保持原样。否则实现 ‘TOS = iter(TOS)’ 。

     3.5 新版功能.

`二元操作'

二元操作从堆栈中删除堆栈顶部（TOS）和第二个最顶层堆栈项（TOS1）。 它们执
行操作，并将结果放回堆栈。

 -- Opcode: BINARY_POWER

     实现 ‘TOS = TOS1 ** TOS’ 。

 -- Opcode: BINARY_MULTIPLY

     实现 ‘TOS = TOS1 * TOS’ 。

 -- Opcode: BINARY_MATRIX_MULTIPLY

     实现 ‘TOS = TOS1 @ TOS’ 。

     3.5 新版功能.

 -- Opcode: BINARY_FLOOR_DIVIDE

     实现 ‘TOS = TOS1 // TOS’。

 -- Opcode: BINARY_TRUE_DIVIDE

     实现 ‘TOS = TOS1 / TOS’ 。

 -- Opcode: BINARY_MODULO

     实现 ‘TOS = TOS1 % TOS’ 。

 -- Opcode: BINARY_ADD

     实现 ‘TOS = TOS1 + TOS’ 。

 -- Opcode: BINARY_SUBTRACT

     实现 ‘TOS = TOS1 - TOS’ 。

 -- Opcode: BINARY_SUBSCR

     实现 ‘TOS = TOS1[TOS]’ 。

 -- Opcode: BINARY_LSHIFT

     实现 ‘TOS = TOS1 << TOS’ 。

 -- Opcode: BINARY_RSHIFT

     实现 ‘TOS = TOS1 >> TOS’ 。

 -- Opcode: BINARY_AND

     实现 ‘TOS = TOS1 & TOS’ 。

 -- Opcode: BINARY_XOR

     实现 ‘TOS = TOS1 ^ TOS’ 。

 -- Opcode: BINARY_OR

     实现 ‘TOS = TOS1 | TOS’ 。

`就地操作'

就地操作就像二元操作，因为它们删除了TOS和TOS1，并将结果推回到堆栈上，但
是当TOS1支持它时，操作就地完成，并且产生的TOS可能是（但不一定） 原来的
TOS1。

 -- Opcode: INPLACE_POWER

     就地实现 ‘TOS = TOS1 ** TOS’ 。

 -- Opcode: INPLACE_MULTIPLY

     就地实现 ‘TOS = TOS1 * TOS’ 。

 -- Opcode: INPLACE_MATRIX_MULTIPLY

     就地实现 ‘TOS = TOS1 @ TOS’ 。

     3.5 新版功能.

 -- Opcode: INPLACE_FLOOR_DIVIDE

     就地实现 ‘TOS = TOS1 // TOS’ 。

 -- Opcode: INPLACE_TRUE_DIVIDE

     就地实现 ‘TOS = TOS1 / TOS’ 。

 -- Opcode: INPLACE_MODULO

     就地实现 ‘TOS = TOS1 % TOS’ 。

 -- Opcode: INPLACE_ADD

     就地实现 ‘TOS = TOS1 + TOS’ 。

 -- Opcode: INPLACE_SUBTRACT

     就地实现 ‘TOS = TOS1 - TOS’ 。

 -- Opcode: INPLACE_LSHIFT

     就地实现 ‘TOS = TOS1 << TOS’ 。

 -- Opcode: INPLACE_RSHIFT

     就地实现 ‘TOS = TOS1 >> TOS’ 。

 -- Opcode: INPLACE_AND

     就地实现 ‘TOS = TOS1 & TOS’ 。

 -- Opcode: INPLACE_XOR

     就地实现 ‘TOS = TOS1 ^ TOS’ 。

 -- Opcode: INPLACE_OR

     就地实现 ‘TOS = TOS1 | TOS’ 。

 -- Opcode: STORE_SUBSCR

     实现 ‘TOS1[TOS] = TOS2’ 。

 -- Opcode: DELETE_SUBSCR

     实现 ‘del TOS1[TOS]’ 。

`协程操作码'

 -- Opcode: GET_AWAITABLE

     实现 ‘TOS = get_awaitable(TOS)’ ，其中 ‘get_awaitable(o)’ 返回 ‘o’
     如果 ‘o’ 是一个有 CO_ITERABLE_COROUTINE 标志的协程对象或生成器对象
     ，否则解析 ‘o.__await__’ 。

     3.5 新版功能.

 -- Opcode: GET_AITER

     实现 ‘TOS = TOS.__aiter__()’ 。

     3.5 新版功能.

     在 3.7 版更改: 已经不再支持从 ‘__aiter__’ 返回可等待对象。

 -- Opcode: GET_ANEXT

     实现 ‘PUSH(get_awaitable(TOS.__anext__()))’ 。参见 ‘GET_AWAITABLE’
     获取更多 ‘get_awaitable’ 的细节

     3.5 新版功能.

 -- Opcode: END_ASYNC_FOR

     终止一个 *note async for: 2e4. 循环。处理等待下一个项目时引发的异常
     。如果 TOS 是 *note StopAsyncIteration: 1022.， 从堆栈弹出7个值，并
     使用后三个恢复异常状态。否则，使用堆栈中的三个值重新引发异常。从块
     堆栈中删除异常处理程序块。

     3.8 新版功能.

 -- Opcode: BEFORE_ASYNC_WITH

     从栈顶对象解析 ‘__aenter__’ 和 ‘__aexit__’ 。将 ‘__aexit__’ 和
     ‘__aenter__()’ 的结果推入堆栈。

     3.5 新版功能.

 -- Opcode: SETUP_ASYNC_WITH

     创建一个新的帧对象。

     3.5 新版功能.

`其他操作码'

 -- Opcode: PRINT_EXPR

     实现交互模式的表达式语句。TOS从堆栈中被移除并打印。在非交互模式下，
     表达式语句以 *note POP_TOP: 38b4. 终止。

 -- Opcode: SET_ADD (i)

     调用 ‘set.add(TOS1[-i], TOS)’ 。 用于实现集合推导。

 -- Opcode: LIST_APPEND (i)

     调用 ‘list.append(TOS1[-i], TOS)’。 用于实现列表推导式。

 -- Opcode: MAP_ADD (i)

     调用 ‘dict.__setitem__(TOS1[-i], TOS1, TOS)’ 。 用于实现字典推导。

     3.1 新版功能.

     在 3.8 版更改: 映射值为 TOS ，映射键为 TOS1 。之前，它们被颠倒了。

对于所有 *note SET_ADD: 38e2. 、 *note LIST_APPEND: 38e3. 和 *note
MAP_ADD: 2e5. 指令，当弹出添加的值或键值对时，容器对象保留在堆栈上，以便
它可用于循环的进一步迭代。

 -- Opcode: RETURN_VALUE

     返回 TOS 到函数的调用者。

 -- Opcode: YIELD_VALUE

     弹出 TOS 并从一个 *note generator: 9aa. 生成它。

 -- Opcode: YIELD_FROM

     弹出 TOS 并将其委托给它作为 *note generator: 9aa. 的子迭代器。

     3.3 新版功能.

 -- Opcode: SETUP_ANNOTATIONS

     检查 ‘__annotations__’ 是否在 ‘locals()’ 中定义，如果没有，它被设置
     为空 ‘dict’ 。只有在类或模块体静态地包含 *note variable
     annotations: 628. 时才会发出此操作码。

     3.6 新版功能.

 -- Opcode: IMPORT_STAR

     将所有不以 ‘'_'’ 开头的符号直接从模块 TOS 加载到局部命名空间。加载
     所有名称后弹出该模块。这个操作码实现了 ‘from module import *’ 。

 -- Opcode: POP_BLOCK

     从块堆栈中删除一个块。有一块堆栈，每帧用于表示 *note try: d7a. 语句
     等。

 -- Opcode: POP_EXCEPT

     从块堆栈中删除一个块。 弹出的块必须是异常处理程序块，在进入 except
     处理程序时隐式创建。除了从帧堆栈弹出无关值之外，最后三个弹出值还用
     于恢复异常状态。

 -- Opcode: POP_FINALLY (preserve_tos)

     清除值堆栈和块堆栈。如果 `preserve_tos' 不是 ‘0’ ，则在执行其他堆栈
     操作后，首先从堆栈中弹出 TOS 并将其推入堆栈：

        * 如果TOS是 ‘NULL’ 或整数（由 *note BEGIN_FINALLY: 2de. 或 *note
          CALL_FINALLY: 2df. 推入），它将从堆栈中弹出。

        * 如果TOS是异常类型（在引发异常时被推入），则从堆栈中弹出6个值，
          最后三个弹出值用于恢复异常状态。从块堆栈中删除异常处理程序块。

     它类似于 *note END_FINALLY: 2e1. ，但不会更改字节码计数器也不会引发
     异常。用于在 *note finally: 183. 块中实现 *note break: 2dc. 、
     *note continue: 182. 和 *note return: 191. 。

     3.8 新版功能.

 -- Opcode: BEGIN_FINALLY

     将 ‘NULL’ 推入堆栈以便在以下操作中使用 *note END_FINALLY: 2e1. 、
     *note POP_FINALLY: 2e0. 、 *note WITH_CLEANUP_START: 2e2. 和 *note
     WITH_CLEANUP_FINISH: 38ea. 。开始 *note finally: 183. 块。

     3.8 新版功能.

 -- Opcode: END_FINALLY

     终止 *note finally: 183. 子句。解释器回溯是否有必须重新抛出异常的情
     况或根据 TOS 的值继续执行。

        * 如果 TOS 是 ‘NULL’ （由 *note BEGIN_FINALLY: 2de. 推入）继续下
          一条指令。 TOS 被弹出。

        * 如果 TO S是一个整数（由 *note CALL_FINALLY: 2df. 推入），则将
          字节码计数器设置为 TOS 。 TOS 被弹出。

        * 如果TOS是异常类型（在引发异常时被推送），则从堆栈中弹出 6 个值
          ，前三个弹出值用于重新引发异常，最后三个弹出值用于恢复异常状态
          。从块堆栈中删除异常处理程序块。

 -- Opcode: LOAD_BUILD_CLASS

     将 ‘builtins .__ build_class__()’ 推到堆栈上。它之后被 *note
     CALL_FUNCTION: 622. 调用来构造一个类。

 -- Opcode: SETUP_WITH (delta)

     此操作码在 with 块开始之前执行多个操作。首先，它从上下文管理器加载
     *note __exit__(): c9e. 并将其推入到堆栈以供以后被 *note
     WITH_CLEANUP_START: 2e2. 使用。然后，调用 ‘__enter__()’ ，并推入指
     向 `delta' 的 finally 块。最后，调用 ‘__enter__()’ 方法的结果被压入
     堆栈。一个操作码将忽略它（ *note POP_TOP: 38b4. ），或将其存储在一
     个或多个变量（ *note STORE_FAST: 38ed. 、 *note STORE_NAME: 38ee. 或
     *note UNPACK_SEQUENCE: 38ef. ）中。

     3.2 新版功能.

 -- Opcode: WITH_CLEANUP_START

     当 *note with: 6f2. 语句块退出时，开始清理堆栈。

     在堆栈的顶部是 ‘NULL’ （由 *note BEGIN_FINALLY: 2de. 推送）或者如果
     在 with 块中引发了异常，则推送 6 个值。下面是上下文管理器 *note
     __exit__(): c9e. 或 *note __aexit__(): 14a9. 绑定方法。

     如果TOS是 ‘NULL’ ，则调用 ‘SECOND(None, None, None)’ ，从堆栈中删除
     函数，离开 TOS ，并将 ‘None’ 推送到堆栈。 否则调用 ‘SEVENTH(TOP,
     SECOND, THIRD)’ ，将堆栈的底部3值向下移动，用 ‘NULL’ 替换空位并推入
     TOS 。最后拖入调用的结果。

 -- Opcode: WITH_CLEANUP_FINISH

     当 *note with: 6f2. 语句块退出时，完成清理堆栈。

     TOS 是 *note WITH_CLEANUP_START: 2e2. 推送的 ‘__exit__()’ 或
     ‘__aexit__()’ 函数的结果。 SECOND是 ‘None’ 或异常类型（引发异常时推
     入的）。

     从堆栈中弹出两个值。如果 SECOND 不为 None 并且 TOS 为 true ，则展开
     EXCEPT_HANDLER 块，该块是在捕获异常时创建的，并将 ‘NULL’ 推入堆栈。

以下所有操作码均使用其参数。

 -- Opcode: STORE_NAME (namei)

     实现 ‘name = TOS’。 `namei' 是 `name' 在代码对象的 ‘co_names’ 属性
     中的索引。 在可能的情况下，编译器会尝试使用 *note STORE_FAST: 38ed.
     或 *note STORE_GLOBAL: 38f0.。

 -- Opcode: DELETE_NAME (namei)

     实现 ‘del name’ ，其中 `namei' 是代码对象的 ‘co_names’ 属性的索引。

 -- Opcode: UNPACK_SEQUENCE (count)

     将 TOS 解包为 `count' 个单独的值，它们将按从右至左的顺序被放入堆栈
     。

 -- Opcode: UNPACK_EX (counts)

     实现使用带星号的目标进行赋值：将 TOS 中的可迭代对象解包为单独的值，
     其中值的总数可以小于可迭代对象中的项数：新值之一将是由所有剩余项构
     成的列表。

     `counts' 的低字节是列表值之前的值的数量，`counts' 中的高字节则是之
     后的值的数量。 结果值会按从右至左的顺序入栈。

 -- Opcode: STORE_ATTR (namei)

     实现 ‘TOS.name = TOS1’，其中 `namei' 是 name 在 ‘co_names’ 中的索引
     号。

 -- Opcode: DELETE_ATTR (namei)

     实现 ‘del TOS.name’，使用 `namei' 作为 ‘co_names’ 中的索引号。

 -- Opcode: STORE_GLOBAL (namei)

     类似于 *note STORE_NAME: 38ee. 但会将 name 存储为全局变量。

 -- Opcode: DELETE_GLOBAL (namei)

     类似于 *note DELETE_NAME: 38f1. 但会删除一个全局变量。

 -- Opcode: LOAD_CONST (consti)

     将 ‘co_consts[consti]’ 推入栈顶。

 -- Opcode: LOAD_NAME (namei)

     将与 ‘co_names[namei]’ 相关联的值推入栈顶。

 -- Opcode: BUILD_TUPLE (count)

     创建一个使用了来自栈的 `count' 个项的元组，并将结果元组推入栈顶。

 -- Opcode: BUILD_LIST (count)

     类似于 *note BUILD_TUPLE: 38f8. 但会创建一个列表。

 -- Opcode: BUILD_SET (count)

     类似于 *note BUILD_TUPLE: 38f8. 但会创建一个集合。

 -- Opcode: BUILD_MAP (count)

     将一个新字典对象推入栈顶。 弹出 ‘2 * count’ 项使得字典包含 `count'
     个条目: ‘{..., TOS3: TOS2, TOS1: TOS}’。

     在 3.5 版更改: 字典是根据栈中的项创建而不是创建一个预设大小包含
     `count' 项的空字典。

 -- Opcode: BUILD_CONST_KEY_MAP (count)

     *note BUILD_MAP: 38fb. 版本专用于常量键。 弹出的栈顶元素包含一个由
     键构成的元组，然后从 ‘TOS1’ 开始从构建字典的值中弹出 `count' 个值。

     3.6 新版功能.

 -- Opcode: BUILD_STRING (count)

     拼接 `count' 个来自栈的字符串并将结果字符串推入栈顶。

     3.6 新版功能.

 -- Opcode: BUILD_TUPLE_UNPACK (count)

     从栈中弹出 `count' 个可迭代对象，将它们合并为单个元组，并将结果推入
     栈顶。 实现可迭代对象解包为元组形式 ‘(*x, *y, *z)’。

     3.5 新版功能.

 -- Opcode: BUILD_TUPLE_UNPACK_WITH_CALL (count)

     这类似于 *note BUILD_TUPLE_UNPACK: 38fc. 但专用于 ‘f(*x, *y, *z)’ 调
     用语法。 栈中 ‘count + 1’ 位置上的项应当是相应的可调用对象 ‘f’。

     3.6 新版功能.

 -- Opcode: BUILD_LIST_UNPACK (count)

     这类似于 *note BUILD_TUPLE_UNPACK: 38fc. 但会将一个列表而非元组推入
     栈顶。 实现可迭代对象解包为列表形式 ‘[*x, *y, *z]’。

     3.5 新版功能.

 -- Opcode: BUILD_SET_UNPACK (count)

     这类似于 *note BUILD_TUPLE_UNPACK: 38fc. 但会将一个集合而非元组推入
     栈顶。 实现可迭代对象解包为集合形式 ‘{*x, *y, *z}’。

     3.5 新版功能.

 -- Opcode: BUILD_MAP_UNPACK (count)

     从栈中弹出 `count' 个映射对象，将它们合并为单个字典，并将结果推入栈
     顶。 实现字典解包为字典形式 ‘{**x, **y, **z}’。

     3.5 新版功能.

 -- Opcode: BUILD_MAP_UNPACK_WITH_CALL (count)

     这类似于 *note BUILD_MAP_UNPACK: 38ff. 但专用于 ‘f(**x, **y, **z)’
     调用语法。 栈中 ‘count + 2’ 位置上的项应当是相应的可调用对象 ‘f’。

     3.5 新版功能.

     在 3.6 版更改: 可迭代对象的位置的确定方式是将操作码参数加 2 而不是
     将其编码到参数的第二个字节。

 -- Opcode: LOAD_ATTR (namei)

     将 TOS 替换为 ‘getattr(TOS, co_names[namei])’。

 -- Opcode: COMPARE_OP (opname)

     执行布尔运算操作。 操作名称可在 ‘cmp_op[opname]’ 中找到。

 -- Opcode: IMPORT_NAME (namei)

     导入模块 ‘co_names[namei]’。 会弹出 TOS 和 TOS1 以提供 `fromlist' 和
     `level' 参数给 *note __import__(): 619.。 模块对象会被推入栈顶。 当
     前命名空间不受影响：对于一条标准 import 语句，会执行后续的 *note
     STORE_FAST: 38ed. 指令来修改命名空间。

 -- Opcode: IMPORT_FROM (namei)

     从在 TOS 内找到的模块中加载属性 ‘co_names[namei]’。 结果对象会被推
     入栈顶，以便由后续的 *note STORE_FAST: 38ed. 指令来保存。

 -- Opcode: JUMP_FORWARD (delta)

     将字节码计数器的值增加 `delta'。

 -- Opcode: POP_JUMP_IF_TRUE (target)

     如果 TOS 为真值，则将字节码计数器的值设为 `target'。 TOS 会被弹出。

     3.1 新版功能.

 -- Opcode: POP_JUMP_IF_FALSE (target)

     如果 TOS 为假值，则将字节码计数器的值设为 `target'。 TOS 会被弹出。

     3.1 新版功能.

 -- Opcode: JUMP_IF_TRUE_OR_POP (target)

     如果 TOS 为真值，则将字节码计数器的值设为 `target' 并将 TOS 留在栈
     顶。 否则（如 TOS 为假值），TOS 会被弹出。

     3.1 新版功能.

 -- Opcode: JUMP_IF_FALSE_OR_POP (target)

     如果 TOS 为假值，则将字节码计数器的值设为 `target' 并将 TOS 留在栈
     顶。 否则（如 TOS 为真值），TOS 会被弹出。

     3.1 新版功能.

 -- Opcode: JUMP_ABSOLUTE (target)

     将字节码计数器的值设为 `target'。

 -- Opcode: FOR_ITER (delta)

     TOS 是一个 *note iterator: 104b.。 可调用它的 *note __next__():
     c6c. 方法。 如果产生了一个新值，则将其推入栈顶（将迭代器留在其下方
     ）。 如果迭代器提示已耗尽则 TOS 会被弹出，并将字节码计数器的值增加
     `delta'。

 -- Opcode: LOAD_GLOBAL (namei)

     加载名称为 ‘co_names[namei]’ 的全局对象推入栈顶。

 -- Opcode: SETUP_FINALLY (delta)

     将一个来自 try-finally 或 try-except 子句的 try 代码块推入代码块栈
     顶。 相对 finally 代码块或第一个 except 代码块 `delta' 个点数。

 -- Opcode: CALL_FINALLY (delta)

     将下一条指令的地址推入栈顶并将字节码计数器的值增加 `delta'。 用于将
     finally 代码块作为一个“子例程”调用。

     3.8 新版功能.

 -- Opcode: LOAD_FAST (var_num)

     将指向局部对象 ‘co_varnames[var_num]’ 的引用推入栈顶。

 -- Opcode: STORE_FAST (var_num)

     将 TOS 存放到局部对象 ‘co_varnames[var_num]’。

 -- Opcode: DELETE_FAST (var_num)

     移除局部对象 ‘co_varnames[var_num]’。

 -- Opcode: LOAD_CLOSURE (i)

     将一个包含在单元的第 `i' 个空位中的对单元的引用推入栈顶并释放可用的
     存储空间。 如果 `i' 小于 `co_cellvars' 的长度则变量的名称为
     ‘co_cellvars[i]’。 否则为 ‘co_freevars[i - len(co_cellvars)]’。

 -- Opcode: LOAD_DEREF (i)

     加载包含在单元的第 `i' 个空位中的单元并释放可用的存储空间。 将一个
     对单元所包含对象的引用推入栈顶。

 -- Opcode: LOAD_CLASSDEREF (i)

     类似于 *note LOAD_DEREF: 3910. 但在查询单元之前会首先检查局部对象字
     典。 这被用于加载类语句体中的自由变量。

     3.4 新版功能.

 -- Opcode: STORE_DEREF (i)

     将 TOS 存放到包含在单元的第 `i' 个空位中的单元内并释放可用存储空间
     。

 -- Opcode: DELETE_DEREF (i)

     清空包含在单元的第 `i' 个空位中的单元并释放可用存储空间。 被用于
     *note del: 127e. 语句。

     3.2 新版功能.

 -- Opcode: RAISE_VARARGS (argc)

     使用 ‘raise’ 语句的 3 种形式之一引发异常，具体形式取决于 `argc' 的
     值：

        * 0: ‘raise’ (重新引发之前的异常)

        * 1: ‘raise TOS’ (在 ‘TOS’ 上引发异常实例或类型)

        * 2: ‘raise TOS1 from TOS’ (在 ‘TOS1’ 上引发异常实例或类型并将
          ‘__cause__’ 设为 ‘TOS’)

 -- Opcode: CALL_FUNCTION (argc)

     调用一个可调用对象并传入位置参数。 `argc' 指明位置参数的数量。 栈顶
     包含位置参数，其中最右边的参数在最顶端。 在参数之下是一个待调用的可
     调用对象。 ‘CALL_FUNCTION’ 会从栈中弹出所有参数以及可调用对象，附带
     这些参数调用该可调用对象，并将可调用对象所返回的返回值推入栈顶。

     在 3.6 版更改: 此操作码仅用于附带位置参数的调用。

 -- Opcode: CALL_FUNCTION_KW (argc)

     调用一个可调用对象并传入位置参数（如果有的话）和关键字参数。 `argc'
     指明位置参数和关键字参数的总数量。 栈顶元素包含一个关键字参数名称的
     元组。 在元组之下是根据元组排序的关键字参数。 在关键字参数之下是位
     置参数，其中最右边的参数在最顶端。 在参数之下是一个待调用的可调用对
     象。 ‘CALL_FUNCTION_KW’ 会从栈中弹出所有参数以及可调用对象，附带这
     些参数调用该可调用对象，并将可调用对象所返回的返回值推入栈顶。

     在 3.6 版更改: 关键字参数会被打包为一个元组而非字典，`argc' 指明参
     数的总数量。

 -- Opcode: CALL_FUNCTION_EX (flags)

     调用一个可调用对象并附带位置参数和关键字参数变量集合。 如果设置了
     `flags' 的最低位，则栈顶包含一个由额外关键字参数组成的映射对象。 在
     该对象之下是一个包含位置参数的可迭代对象和一个待调用的可调用对象。
     *note BUILD_MAP_UNPACK_WITH_CALL: 624. 和 *note
     BUILD_TUPLE_UNPACK_WITH_CALL: 626. 可用于合并多个映射对象和包含参数
     的可迭代对象。 在该可调用对象被调用之前，映射对象和可迭代对象会被分
     别“解包”并将它们的内容分别作为关键字参数和位置参数传入。
     ‘CALL_FUNCTION_EX’ 会从栈中弹出所有参数以及可调用对象，附带这些参数
     调用该可调用对象，并将可调用对象所返回的返回值推入栈顶。

     3.6 新版功能.

 -- Opcode: LOAD_METHOD (namei)

     从 TOS 对象加载一个名为 ‘co_names[namei]’ 的方法。 TOS 将被弹出。 此
     字节码可区分两种情况：如果 TOS 有一个名称正确的方法，字节码会将未绑
     定方法和 TOS 推入栈顶。 TOS 将在调用未绑定方法时被用作 *note
     CALL_METHOD: 4b6. 的第一个参数 (‘self’)。 否则会将 ‘NULL’ 和属性查
     找所返回的对象推入栈顶。

     3.7 新版功能.

 -- Opcode: CALL_METHOD (argc)

     调用一个方法。 `argc' 是位置参数的数量。 关键字参数不受支持。 此操
     作码被设计用于配合 *note LOAD_METHOD: 4b5. 使用。 位置参数放在栈顶
     。 在它们之下放在栈中的是由 *note LOAD_METHOD: 4b5. 所描述的两个条
     目（或者是 ‘self’ 和一个未绑定方法对象，或者是 ‘NULL’ 和一个任意可
     调用对象）。 它们会被全部弹出并将返回值推入栈顶。

     3.7 新版功能.

 -- Opcode: MAKE_FUNCTION (flags)

     将一个新函数对象推入栈顶。 从底端到顶端，如果参数带有指定的旗标值则
     所使用的栈必须由这些值组成。

        * ‘0x01’ 一个默认值的元组，用于按位置排序的仅限位置形参以及位置
          或关键字形参

        * ‘0x02’ 一个仅限关键字形参的默认值的字典

        * ‘0x04’ 是一个标注字典

        * ‘0x08’ 一个包含用于自由变量的单元的元组，生成一个闭包

        * 与函数相关联的代码 (在 TOS1)

        * 函数的 *note qualified name: 143b. (在 TOS)

 -- Opcode: BUILD_SLICE (argc)

     将一个切片对象推入栈顶。 `argc' 必须为 2 或 3。 如果为 2，则推入
     ‘slice(TOS1, TOS)’；如果为 3，则推入 ‘slice(TOS2, TOS1, TOS)’。 请
     参阅 *note slice(): e0c. 内置函数了解详细信息。

 -- Opcode: EXTENDED_ARG (ext)

     为任意带有大到无法放入默认的单字节的参数的操作码添加前缀。 `ext' 存
     放一个附加字节作为参数中的高比特位。 对于每个操作码，最多允许三个
     ‘EXTENDED_ARG’ 前缀，构成两字节到三字节的参数。

 -- Opcode: FORMAT_VALUE (flags)

     用于实现格式化字面值字符串（f-字符串）。 从栈中弹出一个可选的
     `fmt_spec'，然后是一个必须的 `value'。 `flags' 的解读方式如下：

        * ‘(flags & 0x03) == 0x00’: `value' 按原样格式化。

        * ‘(flags & 0x03) == 0x01’: 在格式化 `value' 之前调用其 *note
          str(): 339.。

        * ‘(flags & 0x03) == 0x02’: 在格式化 `value' 之前调用其 *note
          repr(): 7d5.。

        * ‘(flags & 0x03) == 0x03’: 在格式化 `value' 之前调用其 *note
          ascii(): d54.。

        * ‘(flags & 0x04) == 0x04’: 从栈中弹出 `fmt_spec' 并使用它，否则
          使用空的 `fmt_spec'。

     使用 ‘PyObject_Format()’ 执行格式化。 结果会被推入栈顶。

     3.6 新版功能.

 -- Opcode: HAVE_ARGUMENT

     这不是一个真正的操作码。 它用于标明使用参数和不使用参数的操作码 (分
     别为 ‘< HAVE_ARGUMENT’ 和 ‘>= HAVE_ARGUMENT’) 之间的分隔线。

     在 3.6 版更改: 现在每条指令都带有参数，但操作码 ‘< HAVE_ARGUMENT’ 会
     忽略它。 之前仅限操作码 ‘>= HAVE_ARGUMENT’ 带有参数。


File: python.info,  Node: 操作码集合,  Prev: Python字节码说明,  Up: dis --- Python 字节码反汇编器

5.32.12.4 操作码集合
....................

提供这些集合用于字节码指令的自动内省：

 -- 数据: dis.opname

     操作名称的序列，可使用字节码来索引。

 -- 数据: dis.opmap

     映射操作名称到字节码的字典

 -- 数据: dis.cmp_op

     所有比较操作名称的序列。

 -- 数据: dis.hasconst

     访问常量的字节码序列。

 -- 数据: dis.hasfree

     访问自由变量的字节码序列（请注意这里所说的‘自由’是指在当前作用域中
     被内部作用域所引用的名称，或在外部作用域中被此作用域所引用的名称。
     它 `并不' 包括对全局或内置作用域的引用）。

 -- 数据: dis.hasname

     按名称访问属性的字节码序列。

 -- 数据: dis.hasjrel

     具有相对跳转目标的字节码序列。

 -- 数据: dis.hasjabs

     具有绝对跳转目标的字节码序列。

 -- 数据: dis.haslocal

     访问局部变量的字节码序列。

 -- 数据: dis.hascompare

     布尔运算的字节码序列。


File: python.info,  Node: pickletools --- pickle 开发者工具集,  Prev: dis --- Python 字节码反汇编器,  Up: Python 语言服务

5.32.13 ‘pickletools’ — pickle 开发者工具集
-------------------------------------------

`源代码:' Lib/pickletools.py(1)

__________________________________________________________________

此模块包含与 *note pickle: cb. 模块内部细节有关的多个常量，一些关于具体
实现的详细注释，以及一些能够分析封存数据的有用函数。 此模块的内容对需要
操作 *note pickle: cb. 的 Python 核心开发者来说很有用处；*note pickle:
cb. 的一般用户则可能会感觉 *note pickletools: cc. 模块与他们无关。

* Menu:

* 命令行语法: 命令行语法<2>.
* 编程接口: 编程接口<2>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/pickletools.py


File: python.info,  Node: 命令行语法<2>,  Next: 编程接口<2>,  Up: pickletools --- pickle 开发者工具集

5.32.13.1 命令行语法
....................

3.2 新版功能.

当从命令行发起调用时，‘python -m pickletools’ 将对一个或更多 pickle 文件
的内容进行拆解。 请注意如果你查看 pickle 中保存的 Python 对象而非 pickle
格式的细节，你可能需要改用 ‘-m pickle’。 但是，当你想检查的 pickle 文件
来自某个不受信任的源时，‘-m pickletools’ 是更安全的选择，因为它不会执行
pickle 字节码。

例如，对于一个封存在文件 ‘x.pickle’ 中的元组 ‘(1, 2)’:

     $ python -m pickle x.pickle
     (1, 2)

     $ python -m pickletools x.pickle
         0: \x80 PROTO      3
         2: K    BININT1    1
         4: K    BININT1    2
         6: \x86 TUPLE2
         7: q    BINPUT     0
         9: .    STOP
     highest protocol among opcodes = 2

* Menu:

* 命令行选项: 命令行选项<6>.


File: python.info,  Node: 命令行选项<6>,  Up: 命令行语法<2>

5.32.13.2 命令行选项
....................

 -- 程序选项: -a, --annotate

     使用简短的操作码描述来标注每一行。

 -- 程序选项: -o, --output=<file>

     输出应当写入到的文件名称。

 -- 程序选项: -l, --indentlevel=<num>

     一个新的 MARK 层级所需缩进的空格数。

 -- 程序选项: -m, --memo

     当反汇编多个对象时，保留各个反汇编的备忘记录。

 -- 程序选项: -p, --preamble=<preamble>

     当指定一个以上的 pickle 文件时，在每次反汇编之前打印给定的前言。


File: python.info,  Node: 编程接口<2>,  Prev: 命令行语法<2>,  Up: pickletools --- pickle 开发者工具集

5.32.13.3 编程接口
..................

 -- 函数: pickletools.dis (pickle, out=None, memo=None, indentlevel=4,
          annotate=0)

     将 pickle 的符号化反汇编数据输出到文件类对象 `out'，默认为
     ‘sys.stdout’。 `pickle' 可以是一个字符串或一个文件类对象。 `memo' 可
     以是一个将被用作 pickle 的备忘记录的 Python 字典；它可被用来对由同
     一封存器创建的多个封存对象执行反汇编。 由 ‘MARK’ 操作码指明的每个连
     续级别将会缩进 `indentlevel' 个空格。 如果为 `annotate' 指定了一个
     非零值，则输出中的每个操作码将以一个简短描述来标注。 `annotate' 的
     值会被用作标注所应开始的列的提示。

     3.2 新版功能: `annotate' 参数。

 -- 函数: pickletools.genops (pickle)

     提供包含 pickle 中所有操作码的 *note iterator: 104b.，返回一个
     ‘(opcode, arg, pos)’ 三元组的序列。 `opcode' 是 ‘OpcodeInfo’ 类的一
     个实例；`arg' 是 Python 对象形式的 opcode 参数的已解码值；`pos' 是
     opcode 所在的位置。 `pickle' 可以是一个字符串或一个文件类对象。

 -- 函数: pickletools.optimize (picklestring)

     在消除未使用的 ‘PUT’ 操作码之后返回一个新的等效 pickle 字符串。 优
     化后的 pickle 将更为简短，耗费更为的传输时间，要求更少的存储空间并
     能更高效地解封。


File: python.info,  Node: 杂项服务,  Next: Windows系统相关模块,  Prev: Python 语言服务,  Up: Python 标准库

5.33 杂项服务
=============

本章中介绍的模块提供了所有 Python 版本中提供的各种杂项服务。 这是一个概
述：

* Menu:

* formatter: formatter --- 通用格式化输出. 通用格式化输出


File: python.info,  Node: formatter --- 通用格式化输出,  Up: 杂项服务

5.33.1 ‘formatter’ — 通用格式化输出
-----------------------------------

3.4 版后已移除: 因为被使用的次数很少，此格式化模块已经被弃用了。

__________________________________________________________________

This module supports two interface definitions, each with multiple
implementations: The `formatter' interface, and the `writer' interface
which is required by the formatter interface.

Formatter objects transform an abstract flow of formatting events into
specific output events on writer objects.  Formatters manage several
stack structures to allow various properties of a writer object to be
changed and restored; writers need not be able to handle relative
changes nor any sort of "change back" operation.  Specific writer
properties which may be controlled via formatter objects are horizontal
alignment, font, and left margin indentations.  A mechanism is provided
which supports providing arbitrary, non-exclusive style settings to a
writer as well.  Additional interfaces facilitate formatting events
which are not reversible, such as paragraph separation.

Writer objects encapsulate device interfaces.  Abstract devices, such as
file formats, are supported as well as physical devices.  The provided
implementations all work with abstract devices.  The interface makes
available mechanisms for setting the properties which formatter objects
manage and inserting data into the output.

* Menu:

* The Formatter Interface::
* Formatter Implementations::
* The Writer Interface::
* Writer Implementations::


File: python.info,  Node: The Formatter Interface,  Next: Formatter Implementations,  Up: formatter --- 通用格式化输出

5.33.1.1 The Formatter Interface
................................

Interfaces to create formatters are dependent on the specific formatter
class being instantiated.  The interfaces described below are the
required interfaces which all formatters must support once initialized.

One data element is defined at the module level:

 -- 数据: formatter.AS_IS

     Value which can be used in the font specification passed to the
     ‘push_font()’ method described below, or as the new value to any
     other ‘push_property()’ method.  Pushing the ‘AS_IS’ value allows
     the corresponding ‘pop_property()’ method to be called without
     having to track whether the property was changed.

The following attributes are defined for formatter instance objects:

 -- 属性: formatter.writer

     The writer instance with which the formatter interacts.

 -- 方法: formatter.end_paragraph (blanklines)

     Close any open paragraphs and insert at least `blanklines' before
     the next paragraph.

 -- 方法: formatter.add_line_break ()

     Add a hard line break if one does not already exist.  This does not
     break the logical paragraph.

 -- 方法: formatter.add_hor_rule (*args, **kw)

     Insert a horizontal rule in the output.  A hard break is inserted
     if there is data in the current paragraph, but the logical
     paragraph is not broken.  The arguments and keywords are passed on
     to the writer’s ‘send_line_break()’ method.

 -- 方法: formatter.add_flowing_data (data)

     Provide data which should be formatted with collapsed whitespace.
     Whitespace from preceding and successive calls to *note
     add_flowing_data(): 3939. is considered as well when the whitespace
     collapse is performed.  The data which is passed to this method is
     expected to be word-wrapped by the output device.  Note that any
     word-wrapping still must be performed by the writer object due to
     the need to rely on device and font information.

 -- 方法: formatter.add_literal_data (data)

     Provide data which should be passed to the writer unchanged.
     Whitespace, including newline and tab characters, are considered
     legal in the value of `data'.

 -- 方法: formatter.add_label_data (format, counter)

     Insert a label which should be placed to the left of the current
     left margin.  This should be used for constructing bulleted or
     numbered lists.  If the `format' value is a string, it is
     interpreted as a format specification for `counter', which should
     be an integer.  The result of this formatting becomes the value of
     the label; if `format' is not a string it is used as the label
     value directly.  The label value is passed as the only argument to
     the writer’s ‘send_label_data()’ method.  Interpretation of
     non-string label values is dependent on the associated writer.

     Format specifications are strings which, in combination with a
     counter value, are used to compute label values.  Each character in
     the format string is copied to the label value, with some
     characters recognized to indicate a transform on the counter value.
     Specifically, the character ‘'1'’ represents the counter value
     formatter as an Arabic number, the characters ‘'A'’ and ‘'a'’
     represent alphabetic representations of the counter value in upper
     and lower case, respectively, and ‘'I'’ and ‘'i'’ represent the
     counter value in Roman numerals, in upper and lower case.  Note
     that the alphabetic and roman transforms require that the counter
     value be greater than zero.

 -- 方法: formatter.flush_softspace ()

     Send any pending whitespace buffered from a previous call to *note
     add_flowing_data(): 3939. to the associated writer object.  This
     should be called before any direct manipulation of the writer
     object.

 -- 方法: formatter.push_alignment (align)

     Push a new alignment setting onto the alignment stack.  This may be
     *note AS_IS: 3934. if no change is desired.  If the alignment value
     is changed from the previous setting, the writer’s
     ‘new_alignment()’ method is called with the `align' value.

 -- 方法: formatter.pop_alignment ()

     Restore the previous alignment.

 -- 方法: formatter.push_font ((size, italic, bold, teletype))

     Change some or all font properties of the writer object.
     Properties which are not set to *note AS_IS: 3934. are set to the
     values passed in while others are maintained at their current
     settings.  The writer’s ‘new_font()’ method is called with the
     fully resolved font specification.

 -- 方法: formatter.pop_font ()

     Restore the previous font.

 -- 方法: formatter.push_margin (margin)

     Increase the number of left margin indentations by one, associating
     the logical tag `margin' with the new indentation.  The initial
     margin level is ‘0’.  Changed values of the logical tag must be
     true values; false values other than *note AS_IS: 3934. are not
     sufficient to change the margin.

 -- 方法: formatter.pop_margin ()

     Restore the previous margin.

 -- 方法: formatter.push_style (*styles)

     Push any number of arbitrary style specifications.  All styles are
     pushed onto the styles stack in order.  A tuple representing the
     entire stack, including *note AS_IS: 3934. values, is passed to the
     writer’s ‘new_styles()’ method.

 -- 方法: formatter.pop_style (n=1)

     Pop the last `n' style specifications passed to *note push_style():
     3943.  A tuple representing the revised stack, including *note
     AS_IS: 3934. values, is passed to the writer’s ‘new_styles()’
     method.

 -- 方法: formatter.set_spacing (spacing)

     Set the spacing style for the writer.

 -- 方法: formatter.assert_line_data (flag=1)

     Inform the formatter that data has been added to the current
     paragraph out-of-band.  This should be used when the writer has
     been manipulated directly.  The optional `flag' argument can be set
     to false if the writer manipulations produced a hard line break at
     the end of the output.


File: python.info,  Node: Formatter Implementations,  Next: The Writer Interface,  Prev: The Formatter Interface,  Up: formatter --- 通用格式化输出

5.33.1.2 Formatter Implementations
..................................

Two implementations of formatter objects are provided by this module.
Most applications may use one of these classes without modification or
subclassing.

 -- 类: formatter.NullFormatter (writer=None)

     A formatter which does nothing.  If `writer' is omitted, a *note
     NullWriter: 394a. instance is created.  No methods of the writer
     are called by *note NullFormatter: 3949. instances.
     Implementations should inherit from this class if implementing a
     writer interface but don’t need to inherit any implementation.

 -- 类: formatter.AbstractFormatter (writer)

     The standard formatter.  This implementation has demonstrated wide
     applicability to many writers, and may be used directly in most
     circumstances.  It has been used to implement a full-featured World
     Wide Web browser.


File: python.info,  Node: The Writer Interface,  Next: Writer Implementations,  Prev: Formatter Implementations,  Up: formatter --- 通用格式化输出

5.33.1.3 The Writer Interface
.............................

Interfaces to create writers are dependent on the specific writer class
being instantiated.  The interfaces described below are the required
interfaces which all writers must support once initialized.  Note that
while most applications can use the *note AbstractFormatter: 394b. class
as a formatter, the writer must typically be provided by the
application.

 -- 方法: writer.flush ()

     Flush any buffered output or device control events.

 -- 方法: writer.new_alignment (align)

     Set the alignment style.  The `align' value can be any object, but
     by convention is a string or ‘None’, where ‘None’ indicates that
     the writer’s "preferred" alignment should be used.  Conventional
     `align' values are ‘'left'’, ‘'center'’, ‘'right'’, and
     ‘'justify'’.

 -- 方法: writer.new_font (font)

     Set the font style.  The value of `font' will be ‘None’, indicating
     that the device’s default font should be used, or a tuple of the
     form ‘(size, italic, bold, teletype)’.  Size will be a string
     indicating the size of font that should be used; specific strings
     and their interpretation must be defined by the application.  The
     `italic', `bold', and `teletype' values are Boolean values
     specifying which of those font attributes should be used.

 -- 方法: writer.new_margin (margin, level)

     Set the margin level to the integer `level' and the logical tag to
     `margin'.  Interpretation of the logical tag is at the writer’s
     discretion; the only restriction on the value of the logical tag is
     that it not be a false value for non-zero values of `level'.

 -- 方法: writer.new_spacing (spacing)

     Set the spacing style to `spacing'.

 -- 方法: writer.new_styles (styles)

     Set additional styles.  The `styles' value is a tuple of arbitrary
     values; the value *note AS_IS: 3934. should be ignored.  The
     `styles' tuple may be interpreted either as a set or as a stack
     depending on the requirements of the application and writer
     implementation.

 -- 方法: writer.send_line_break ()

     Break the current line.

 -- 方法: writer.send_paragraph (blankline)

     Produce a paragraph separation of at least `blankline' blank lines,
     or the equivalent.  The `blankline' value will be an integer.  Note
     that the implementation will receive a call to *note
     send_line_break(): 3954. before this call if a line break is
     needed; this method should not include ending the last line of the
     paragraph.  It is only responsible for vertical spacing between
     paragraphs.

 -- 方法: writer.send_hor_rule (*args, **kw)

     Display a horizontal rule on the output device.  The arguments to
     this method are entirely application- and writer-specific, and
     should be interpreted with care.  The method implementation may
     assume that a line break has already been issued via *note
     send_line_break(): 3954.

 -- 方法: writer.send_flowing_data (data)

     Output character data which may be word-wrapped and re-flowed as
     needed.  Within any sequence of calls to this method, the writer
     may assume that spans of multiple whitespace characters have been
     collapsed to single space characters.

 -- 方法: writer.send_literal_data (data)

     Output character data which has already been formatted for display.
     Generally, this should be interpreted to mean that line breaks
     indicated by newline characters should be preserved and no new line
     breaks should be introduced.  The data may contain embedded newline
     and tab characters, unlike data provided to the
     ‘send_formatted_data()’ interface.

 -- 方法: writer.send_label_data (data)

     Set `data' to the left of the current left margin, if possible.
     The value of `data' is not restricted; treatment of non-string
     values is entirely application- and writer-dependent.  This method
     will only be called at the beginning of a line.


File: python.info,  Node: Writer Implementations,  Prev: The Writer Interface,  Up: formatter --- 通用格式化输出

5.33.1.4 Writer Implementations
...............................

Three implementations of the writer object interface are provided as
examples by this module.  Most applications will need to derive new
writer classes from the *note NullWriter: 394a. class.

 -- 类: formatter.NullWriter

     A writer which only provides the interface definition; no actions
     are taken on any methods.  This should be the base class for all
     writers which do not need to inherit any implementation methods.

 -- 类: formatter.AbstractWriter

     A writer which can be used in debugging formatters, but not much
     else.  Each method simply announces itself by printing its name and
     arguments on standard output.

 -- 类: formatter.DumbWriter (file=None, maxcol=72)

     Simple writer class which writes output on the *note file object:
     b4a. passed in as `file' or, if `file' is omitted, on standard
     output.  The output is simply word-wrapped to the number of columns
     specified by `maxcol'.  This class is suitable for reflowing a
     sequence of paragraphs.


File: python.info,  Node: Windows系统相关模块,  Next: Unix 专有服务,  Prev: 杂项服务,  Up: Python 标准库

5.34 Windows系统相关模块
========================

本章节叙述的模块只在 Windows 平台上可用。

* Menu:

* msilib: msilib --- Read and write Microsoft Installer files. Read and write Microsoft Installer files
* msvcrt: msvcrt --- 来自 MS VC++ 运行时的有用例程. 来自 MS VC++ 运行时的有用例程
* winreg: winreg --- Windows 注册表访问. Windows 注册表访问
* winsound: winsound --- Sound-playing interface for Windows. Sound-playing interface for Windows


File: python.info,  Node: msilib --- Read and write Microsoft Installer files,  Next: msvcrt --- 来自 MS VC++ 运行时的有用例程,  Up: Windows系统相关模块

5.34.1 ‘msilib’ — Read and write Microsoft Installer files
----------------------------------------------------------

`Source code:' Lib/msilib/__init__.py(1)

__________________________________________________________________

The *note msilib: b6. supports the creation of Microsoft Installer
(‘.msi’) files.  Because these files often contain an embedded "cabinet"
file (‘.cab’), it also exposes an API to create CAB files.  Support for
reading ‘.cab’ files is currently not implemented; read support for the
‘.msi’ database is possible.

This package aims to provide complete access to all tables in an ‘.msi’
file, therefore, it is a fairly low-level API. Two primary applications
of this package are the *note distutils: 39. command ‘bdist_msi’, and
the creation of Python installer package itself (although that currently
uses a different version of ‘msilib’).

The package contents can be roughly split into four parts: low-level CAB
routines, low-level MSI routines, higher-level MSI routines, and
standard table structures.

 -- 函数: msilib.FCICreate (cabname, files)

     Create a new CAB file named `cabname'.  `files' must be a list of
     tuples, each containing the name of the file on disk, and the name
     of the file inside the CAB file.

     The files are added to the CAB file in the order they appear in the
     list.  All files are added into a single CAB file, using the MSZIP
     compression algorithm.

     Callbacks to Python for the various steps of MSI creation are
     currently not exposed.

 -- 函数: msilib.UuidCreate ()

     Return the string representation of a new unique identifier.  This
     wraps the Windows API functions ‘UuidCreate()’ and
     ‘UuidToString()’.

 -- 函数: msilib.OpenDatabase (path, persist)

     Return a new database object by calling MsiOpenDatabase.  `path' is
     the file name of the MSI file; `persist' can be one of the
     constants ‘MSIDBOPEN_CREATEDIRECT’, ‘MSIDBOPEN_CREATE’,
     ‘MSIDBOPEN_DIRECT’, ‘MSIDBOPEN_READONLY’, or ‘MSIDBOPEN_TRANSACT’,
     and may include the flag ‘MSIDBOPEN_PATCHFILE’.  See the Microsoft
     documentation for the meaning of these flags; depending on the
     flags, an existing database is opened, or a new one created.

 -- 函数: msilib.CreateRecord (count)

     Return a new record object by calling ‘MSICreateRecord()’.  `count'
     is the number of fields of the record.

 -- 函数: msilib.init_database (name, schema, ProductName, ProductCode,
          ProductVersion, Manufacturer)

     Create and return a new database `name', initialize it with
     `schema', and set the properties `ProductName', `ProductCode',
     `ProductVersion', and `Manufacturer'.

     `schema' must be a module object containing ‘tables’ and
     ‘_Validation_records’ attributes; typically, *note msilib.schema:
     3965. should be used.

     The database will contain just the schema and the validation
     records when this function returns.

 -- 函数: msilib.add_data (database, table, records)

     Add all `records' to the table named `table' in `database'.

     The `table' argument must be one of the predefined tables in the
     MSI schema, e.g.  ‘'Feature'’, ‘'File'’, ‘'Component'’, ‘'Dialog'’,
     ‘'Control'’, etc.

     `records' should be a list of tuples, each one containing all
     fields of a record according to the schema of the table.  For
     optional fields, ‘None’ can be passed.

     Field values can be ints, strings, or instances of the Binary
     class.

 -- 类: msilib.Binary (filename)

     Represents entries in the Binary table; inserting such an object
     using *note add_data(): 3966. reads the file named `filename' into
     the table.

 -- 函数: msilib.add_tables (database, module)

     Add all table content from `module' to `database'.  `module' must
     contain an attribute `tables' listing all tables for which content
     should be added, and one attribute per table that has the actual
     content.

     This is typically used to install the sequence tables.

 -- 函数: msilib.add_stream (database, name, path)

     Add the file `path' into the ‘_Stream’ table of `database', with
     the stream name `name'.

 -- 函数: msilib.gen_uuid ()

     Return a new UUID, in the format that MSI typically requires (i.e.
     in curly braces, and with all hexdigits in upper-case).

参见
....

FCICreate(2) UuidCreate(3) UuidToString(4)

* Menu:

* Database Objects::
* View Objects::
* Summary Information Objects::
* Record Objects::
* Errors::
* CAB Objects::
* Directory Objects::
* 相关特性: 相关特性<3>.
* GUI classes::
* Precomputed tables::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/msilib/__init__.py

   (2) https://msdn.microsoft.com/en-us/library/bb432265.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa379205.aspx

   (4) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa379352.aspx


File: python.info,  Node: Database Objects,  Next: View Objects,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.1 Database Objects
.........................

 -- 方法: Database.OpenView (sql)

     Return a view object, by calling ‘MSIDatabaseOpenView()’.  `sql' is
     the SQL statement to execute.

 -- 方法: Database.Commit ()

     Commit the changes pending in the current transaction, by calling
     ‘MSIDatabaseCommit()’.

 -- 方法: Database.GetSummaryInformation (count)

     Return a new summary information object, by calling
     ‘MsiGetSummaryInformation()’.  `count' is the maximum number of
     updated values.

 -- 方法: Database.Close ()

     Close the database object, through ‘MsiCloseHandle()’.

     3.7 新版功能.

参见
....

MSIDatabaseOpenView(1) MSIDatabaseCommit(2) MSIGetSummaryInformation(3)
MsiCloseHandle(4)

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370082.aspx

   (2) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370075.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370301.aspx

   (4) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370067.aspx


File: python.info,  Node: View Objects,  Next: Summary Information Objects,  Prev: Database Objects,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.2 View Objects
.....................

 -- 方法: View.Execute (params)

     Execute the SQL query of the view, through ‘MSIViewExecute()’.  If
     `params' is not ‘None’, it is a record describing actual values of
     the parameter tokens in the query.

 -- 方法: View.GetColumnInfo (kind)

     Return a record describing the columns of the view, through calling
     ‘MsiViewGetColumnInfo()’.  `kind' can be either ‘MSICOLINFO_NAMES’
     or ‘MSICOLINFO_TYPES’.

 -- 方法: View.Fetch ()

     Return a result record of the query, through calling
     ‘MsiViewFetch()’.

 -- 方法: View.Modify (kind, data)

     Modify the view, by calling ‘MsiViewModify()’.  `kind' can be one
     of ‘MSIMODIFY_SEEK’, ‘MSIMODIFY_REFRESH’, ‘MSIMODIFY_INSERT’,
     ‘MSIMODIFY_UPDATE’, ‘MSIMODIFY_ASSIGN’, ‘MSIMODIFY_REPLACE’,
     ‘MSIMODIFY_MERGE’, ‘MSIMODIFY_DELETE’,
     ‘MSIMODIFY_INSERT_TEMPORARY’, ‘MSIMODIFY_VALIDATE’,
     ‘MSIMODIFY_VALIDATE_NEW’, ‘MSIMODIFY_VALIDATE_FIELD’, or
     ‘MSIMODIFY_VALIDATE_DELETE’.

     `data' must be a record describing the new data.

 -- 方法: View.Close ()

     Close the view, through ‘MsiViewClose()’.

参见
....

MsiViewExecute(1) MSIViewGetColumnInfo(2) MsiViewFetch(3)
MsiViewModify(4) MsiViewClose(5)

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370513.aspx

   (2) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370516.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370514.aspx

   (4) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370519.aspx

   (5) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370510.aspx


File: python.info,  Node: Summary Information Objects,  Next: Record Objects,  Prev: View Objects,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.3 Summary Information Objects
....................................

 -- 方法: SummaryInformation.GetProperty (field)

     Return a property of the summary, through
     ‘MsiSummaryInfoGetProperty()’.  `field' is the name of the
     property, and can be one of the constants ‘PID_CODEPAGE’,
     ‘PID_TITLE’, ‘PID_SUBJECT’, ‘PID_AUTHOR’, ‘PID_KEYWORDS’,
     ‘PID_COMMENTS’, ‘PID_TEMPLATE’, ‘PID_LASTAUTHOR’, ‘PID_REVNUMBER’,
     ‘PID_LASTPRINTED’, ‘PID_CREATE_DTM’, ‘PID_LASTSAVE_DTM’,
     ‘PID_PAGECOUNT’, ‘PID_WORDCOUNT’, ‘PID_CHARCOUNT’, ‘PID_APPNAME’,
     or ‘PID_SECURITY’.

 -- 方法: SummaryInformation.GetPropertyCount ()

     Return the number of summary properties, through
     ‘MsiSummaryInfoGetPropertyCount()’.

 -- 方法: SummaryInformation.SetProperty (field, value)

     Set a property through ‘MsiSummaryInfoSetProperty()’.  `field' can
     have the same values as in *note GetProperty(): fd3, `value' is the
     new value of the property.  Possible value types are integer and
     string.

 -- 方法: SummaryInformation.Persist ()

     Write the modified properties to the summary information stream,
     using ‘MsiSummaryInfoPersist()’.

参见
....

MsiSummaryInfoGetProperty(1) MsiSummaryInfoGetPropertyCount(2)
MsiSummaryInfoSetProperty(3) MsiSummaryInfoPersist(4)

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370409.aspx

   (2) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370488.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370491.aspx

   (4) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370490.aspx


File: python.info,  Node: Record Objects,  Next: Errors,  Prev: Summary Information Objects,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.4 Record Objects
.......................

 -- 方法: Record.GetFieldCount ()

     Return the number of fields of the record, through
     ‘MsiRecordGetFieldCount()’.

 -- 方法: Record.GetInteger (field)

     Return the value of `field' as an integer where possible.  `field'
     must be an integer.

 -- 方法: Record.GetString (field)

     Return the value of `field' as a string where possible.  `field'
     must be an integer.

 -- 方法: Record.SetString (field, value)

     Set `field' to `value' through ‘MsiRecordSetString()’.  `field'
     must be an integer; `value' a string.

 -- 方法: Record.SetStream (field, value)

     Set `field' to the contents of the file named `value', through
     ‘MsiRecordSetStream()’.  `field' must be an integer; `value' a
     string.

 -- 方法: Record.SetInteger (field, value)

     Set `field' to `value' through ‘MsiRecordSetInteger()’.  Both
     `field' and `value' must be an integer.

 -- 方法: Record.ClearData ()

     Set all fields of the record to 0, through ‘MsiRecordClearData()’.

参见
....

MsiRecordGetFieldCount(1) MsiRecordSetString(2) MsiRecordSetStream(3)
MsiRecordSetInteger(4) MsiRecordClearData(5)

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370366.aspx

   (2) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370373.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370372.aspx

   (4) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370371.aspx

   (5) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370364.aspx


File: python.info,  Node: Errors,  Next: CAB Objects,  Prev: Record Objects,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.5 Errors
...............

All wrappers around MSI functions raise ‘MSIError’; the string inside
the exception will contain more detail.


File: python.info,  Node: CAB Objects,  Next: Directory Objects,  Prev: Errors,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.6 CAB Objects
....................

 -- 类: msilib.CAB (name)

     The class *note CAB: 3988. represents a CAB file.  During MSI
     construction, files will be added simultaneously to the ‘Files’
     table, and to a CAB file.  Then, when all files have been added,
     the CAB file can be written, then added to the MSI file.

     `name' is the name of the CAB file in the MSI file.

      -- 方法: append (full, file, logical)

          Add the file with the pathname `full' to the CAB file, under
          the name `logical'.  If there is already a file named
          `logical', a new file name is created.

          Return the index of the file in the CAB file, and the new name
          of the file inside the CAB file.

      -- 方法: commit (database)

          Generate a CAB file, add it as a stream to the MSI file, put
          it into the ‘Media’ table, and remove the generated file from
          the disk.


File: python.info,  Node: Directory Objects,  Next: 相关特性<3>,  Prev: CAB Objects,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.7 Directory Objects
..........................

 -- 类: msilib.Directory (database, cab, basedir, physical, logical,
          default[, componentflags])

     Create a new directory in the Directory table.  There is a current
     component at each point in time for the directory, which is either
     explicitly created through *note start_component(): fd4, or
     implicitly when files are added for the first time.  Files are
     added into the current component, and into the cab file.  To create
     a directory, a base directory object needs to be specified (can be
     ‘None’), the path to the physical directory, and a logical
     directory name.  `default' specifies the DefaultDir slot in the
     directory table.  `componentflags' specifies the default flags that
     new components get.

      -- 方法: start_component (component=None, feature=None,
               flags=None, keyfile=None, uuid=None)

          Add an entry to the Component table, and make this component
          the current component for this directory.  If no component
          name is given, the directory name is used.  If no `feature' is
          given, the current feature is used.  If no `flags' are given,
          the directory’s default flags are used.  If no `keyfile' is
          given, the KeyPath is left null in the Component table.

      -- 方法: add_file (file, src=None, version=None, language=None)

          Add a file to the current component of the directory, starting
          a new one if there is no current component.  By default, the
          file name in the source and the file table will be identical.
          If the `src' file is specified, it is interpreted relative to
          the current directory.  Optionally, a `version' and a
          `language' can be specified for the entry in the File table.

      -- 方法: glob (pattern, exclude=None)

          Add a list of files to the current component as specified in
          the glob pattern.  Individual files can be excluded in the
          `exclude' list.

      -- 方法: remove_pyc ()

          Remove ‘.pyc’ files on uninstall.

参见
....

Directory Table(1) File Table(2) Component Table(3) FeatureComponents
Table(4)

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368295.aspx

   (2) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368596.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368007.aspx

   (4) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368579.aspx


File: python.info,  Node: 相关特性<3>,  Next: GUI classes,  Prev: Directory Objects,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.8 相关特性
.................

 -- 类: msilib.Feature (db, id, title, desc, display, level=1,
          parent=None, directory=None, attributes=0)

     Add a new record to the ‘Feature’ table, using the values `id',
     `parent.id', `title', `desc', `display', `level', `directory', and
     `attributes'.  The resulting feature object can be passed to the
     ‘start_component()’ method of *note Directory: 398d.

      -- 方法: set_current ()

          Make this feature the current feature of *note msilib: b6.
          New components are automatically added to the default feature,
          unless a feature is explicitly specified.

参见
....

Feature Table(1)

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368585.aspx


File: python.info,  Node: GUI classes,  Next: Precomputed tables,  Prev: 相关特性<3>,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.9 GUI classes
....................

*note msilib: b6. provides several classes that wrap the GUI tables in
an MSI database.  However, no standard user interface is provided; use
*note bdist_msi: 41. to create MSI files with a user-interface for
installing Python packages.

 -- 类: msilib.Control (dlg, name)

     Base class of the dialog controls.  `dlg' is the dialog object the
     control belongs to, and `name' is the control’s name.

      -- 方法: event (event, argument, condition=1, ordering=None)

          Make an entry into the ‘ControlEvent’ table for this control.

      -- 方法: mapping (event, attribute)

          Make an entry into the ‘EventMapping’ table for this control.

      -- 方法: condition (action, condition)

          Make an entry into the ‘ControlCondition’ table for this
          control.

 -- 类: msilib.RadioButtonGroup (dlg, name, property)

     Create a radio button control named `name'.  `property' is the
     installer property that gets set when a radio button is selected.

      -- 方法: add (name, x, y, width, height, text, value=None)

          Add a radio button named `name' to the group, at the
          coordinates `x', `y', `width', `height', and with the label
          `text'.  If `value' is ‘None’, it defaults to `name'.

 -- 类: msilib.Dialog (db, name, x, y, w, h, attr, title, first,
          default, cancel)

     Return a new *note Dialog: 399d. object.  An entry in the ‘Dialog’
     table is made, with the specified coordinates, dialog attributes,
     title, name of the first, default, and cancel controls.

      -- 方法: control (name, type, x, y, width, height, attributes,
               property, text, control_next, help)

          Return a new *note Control: 3997. object.  An entry in the
          ‘Control’ table is made with the specified parameters.

          This is a generic method; for specific types, specialized
          methods are provided.

      -- 方法: text (name, x, y, width, height, attributes, text)

          Add and return a ‘Text’ control.

      -- 方法: bitmap (name, x, y, width, height, text)

          Add and return a ‘Bitmap’ control.

      -- 方法: line (name, x, y, width, height)

          Add and return a ‘Line’ control.

      -- 方法: pushbutton (name, x, y, width, height, attributes, text,
               next_control)

          Add and return a ‘PushButton’ control.

      -- 方法: radiogroup (name, x, y, width, height, attributes,
               property, text, next_control)

          Add and return a ‘RadioButtonGroup’ control.

      -- 方法: checkbox (name, x, y, width, height, attributes,
               property, text, next_control)

          Add and return a ‘CheckBox’ control.

参见
....

Dialog Table(1) Control Table(2) Control Types(3) ControlCondition
Table(4) ControlEvent Table(5) EventMapping Table(6) RadioButton
Table(7)

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368286.aspx

   (2) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368044.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368039.aspx

   (4) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368035.aspx

   (5) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368037.aspx

   (6) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368559.aspx

   (7) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370962.aspx


File: python.info,  Node: Precomputed tables,  Prev: GUI classes,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.10 Precomputed tables
............................

*note msilib: b6. provides a few subpackages that contain only schema
and table definitions.  Currently, these definitions are based on MSI
version 2.0.

 -- 数据: msilib.schema

     This is the standard MSI schema for MSI 2.0, with the `tables'
     variable providing a list of table definitions, and
     `_Validation_records' providing the data for MSI validation.

 -- 数据: msilib.sequence

     This module contains table contents for the standard sequence
     tables: `AdminExecuteSequence', `AdminUISequence',
     `AdvtExecuteSequence', `InstallExecuteSequence', and
     `InstallUISequence'.

 -- 数据: msilib.text

     This module contains definitions for the UIText and ActionText
     tables, for the standard installer actions.


File: python.info,  Node: msvcrt --- 来自 MS VC++ 运行时的有用例程,  Next: winreg --- Windows 注册表访问,  Prev: msilib --- Read and write Microsoft Installer files,  Up: Windows系统相关模块

5.34.2 ‘msvcrt’ — 来自 MS VC++ 运行时的有用例程
-----------------------------------------------

__________________________________________________________________

这些函数提供了对 Windows 平台上一些有用功能的访问。一些更高级别的模块使
用这些函数来构建其服务的 Windows 实现。 例如， *note getpass: 88. 模块在
实现 *note getpass(): 88. 函数时使用了这些函数。

关于这些函数的更多信息可以在平台 API 文档中找到。

该模块实现了控制台 I/O API 的普通和宽字符变体。普通的 API 只处理ASCII字
符，国际化应用受限。应该尽可能地使用宽字符 API 。

在 3.3 版更改: 此模块中过去会引发 *note IOError: 99a. 的操作现在将引发
*note OSError: 1d4.。

* Menu:

* 文件操作::
* 控制台 I/O::
* 其他函数::


File: python.info,  Node: 文件操作,  Next: 控制台 I/O,  Up: msvcrt --- 来自 MS VC++ 运行时的有用例程

5.34.2.1 文件操作
.................

 -- 函数: msvcrt.locking (fd, mode, nbytes)

     基于文件描述符 `fd' 从 C 运行时锁定文件的某一部分。 失败时引发
     *note OSError: 1d4.。 锁定的文件区域从当前文件位置开始扩展 `nbytes'
     个字节，并可能持续到超出文件末尾。 `mode' 必须为下面列出的 ‘LK_*’ 之
     一。 一个文件中的多个区域可以被同时锁定，但是不能重叠。 相邻区域不
     会被合并；它们必须单独被解锁。

     引发一个 *note 审计事件: ea1. ‘msvcrt.locking’，附带参数 ‘fd’,
     ‘mode’, ‘nbytes’。

 -- 数据: msvcrt.LK_LOCK
 -- 数据: msvcrt.LK_RLCK

     锁定指定的字节数据。 如果字节数据无法被锁定，程序会在 1 秒之后立即
     重试。 如果在 10 次尝试后字节数据仍无法被锁定，则会引发 *note
     OSError: 1d4.。

 -- 数据: msvcrt.LK_NBLCK
 -- 数据: msvcrt.LK_NBRLCK

     锁定指定的字节数据。 如果字节数据无法被锁定，则会引发 *note
     OSError: 1d4.。

 -- 数据: msvcrt.LK_UNLCK

     解锁指定的字节数据，该对象必须在之前被锁定。

 -- 函数: msvcrt.setmode (fd, flags)

     设置文件描述符 `fd' 的行结束符转写模式。 要将其设为文本模式，则
     `flags' 应当为 *note os.O_TEXT: 1f37.；设为二进制模式，则应当为
     *note os.O_BINARY: 1f28.。

 -- 函数: msvcrt.open_osfhandle (handle, flags)

     基于文件句柄 `handle' 创建一个 C 运行时文件描述符。 `flags' 形参应
     当 *note os.O_APPEND: 1f2a, *note os.O_RDONLY: 1f26. 和 *note
     os.O_TEXT: 1f37. 按位 OR 的结果。 返回的文件描述符可以被用作 *note
     os.fdopen(): 1441. 的形参以创建一个文件对象。

     引发一个 *note 审计事件: ea1. ‘msvcrt.open_osfhandle’，附带参数
     ‘handle’, ‘flags’。

 -- 函数: msvcrt.get_osfhandle (fd)

     返回文件描述符 `fd' 的文件句柄。 如果 `fd' 不能被识别则会引发 *note
     OSError: 1d4.。

     引发一个 *note 审计事件: ea1. ‘msvcrt.get_osfhandle’，附带参数
     ‘fd’。


File: python.info,  Node: 控制台 I/O,  Next: 其他函数,  Prev: 文件操作,  Up: msvcrt --- 来自 MS VC++ 运行时的有用例程

5.34.2.2 控制台 I/O
...................

 -- 函数: msvcrt.kbhit ()

     如果有某个按键正在等待被读取则返回 ‘True’。

 -- 函数: msvcrt.getch ()

     读取一个按键并将结果字符返回为一个字节串。 不会有内容回显到缝制台。
     如果还没有任何键被按下此调用将会阻塞，但它将不会等待 ‘Enter’ 被按下
     。 如果按下的键是一个特殊功能键，此函数将返回 ‘'\000'’ 或 ‘'\xe0'’；
     下一次调用将返回键代码。 ‘Control-C’ 按钮无法使用此函数来读取。

 -- 函数: msvcrt.getwch ()

     *note getch(): 39b6. 的宽字符版本，返回一个 Unicode 值。

 -- 函数: msvcrt.getche ()

     类似于 *note getch(): 39b6.，但按键如果表示一个可打印字符则它将被回
     显。

 -- 函数: msvcrt.getwche ()

     *note getche(): 39b8. 的宽字符版本，返回一个 Unicode 值。

 -- 函数: msvcrt.putch (char)

     将字符串 `char' 打印到终端，不使用缓冲区。

 -- 函数: msvcrt.putwch (unicode_char)

     *note putch(): 39ba. 的宽字符版本，接受一个 Unicode 值。

 -- 函数: msvcrt.ungetch (char)

     使得字节串 `char' 被“推回”终端缓冲区；它将是被 *note getch(): 39b6.
     或 *note getche(): 39b8. 读取的下一个字符。

 -- 函数: msvcrt.ungetwch (unicode_char)

     *note ungetch(): 39bc. 的宽字符版本，接受一个 Unicode 值。


File: python.info,  Node: 其他函数,  Prev: 控制台 I/O,  Up: msvcrt --- 来自 MS VC++ 运行时的有用例程

5.34.2.3 其他函数
.................

 -- 函数: msvcrt.heapmin ()

     强制 ‘malloc()’ 堆清空自身并将未使用的块返回给操作系统。 失败时，这
     将引发 *note OSError: 1d4.。


File: python.info,  Node: winreg --- Windows 注册表访问,  Next: winsound --- Sound-playing interface for Windows,  Prev: msvcrt --- 来自 MS VC++ 运行时的有用例程,  Up: Windows系统相关模块

5.34.3 ‘winreg’ — Windows 注册表访问
------------------------------------

__________________________________________________________________

这些函数将 Windows 注册表 API 暴露给 Python。为了确保即便程序员忽略了显
式关闭句柄，该句柄依然能够正确关闭，它使用了一个 *note handle 对象:
39c3. 而不是整数来作为注册表句柄。

在 3.3 版更改: 该模块中的几个函数被用于引发 *note WindowsError: 99c.，该
异常现在是 *note OSError: 1d4. 的别名。

* Menu:

* 函数: 函数<11>.
* 常量: 常量<10>.
* Registry Handle Objects::


File: python.info,  Node: 函数<11>,  Next: 常量<10>,  Up: winreg --- Windows 注册表访问

5.34.3.1 函数
.............

该模块提供了下列函数：

 -- 函数: winreg.CloseKey (hkey)

     关闭之前打开的注册表键。参数 `hkey' 指之前打开的键。

          注解: 如果没有使用该方法关闭 `hkey' (或者通过 *note
          hkey.Close(): 39c8.)，在对象 `hkey' 被 Python 销毁时会将其关闭
          。

 -- 函数: winreg.ConnectRegistry (computer_name, key)

     建立到另一台计算上上的预定义注册表句柄的连接，并返回一个 *note
     handle 对象: 39c3.

     `computer_name' 是远程计算机的名称，以 ‘r"\\computername"’ 的形式。
     如果是 ‘None’ ，将会使用本地计算机。

     `key' 是所连接到的预定义句柄。

     返回值是所开打键的句柄。如果函数失败，则引发一个 *note OSError:
     1d4. 异常。

     引发一个 *note 审计事件: ea1. ‘winreg.ConnectRegistry’，附带参数
     ‘computer_name’, ‘key’。

     在 3.3 版更改: 参考 *note 上文: 39c4.。

 -- 函数: winreg.CreateKey (key, sub_key)

     创建或打开特定的键，返回一个 *note handle 对象: 39c3.。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     `sub_key' 是用于命名该方法所打开或创建的键的字符串。

     如果 `key' 是预定义键之一，`sub_key' 可能会是 ‘None’。该情况下，返
     回的句柄就是传入函数的句柄。

     如果键已经存在，则该函数打开已经存在的该键。

     返回值是所开打键的句柄。如果函数失败，则引发一个 *note OSError:
     1d4. 异常。

     引发一个 *note 审计事件: ea1. ‘winreg.CreateKey’，附带参数 ‘key’,
     ‘sub_key’, ‘access’。

     引发一个 *note 审计事件: ea1. ‘winreg.OpenKey/result’，附带参数
     ‘key’。

     在 3.3 版更改: 参考 *note 上文: 39c4.。

 -- 函数: winreg.CreateKeyEx (key, sub_key, reserved=0,
          access=KEY_WRITE)

     创建或打开特定的键，返回一个 *note handle 对象: 39c3.。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     `sub_key' 是用于命名该方法所打开或创建的键的字符串。

     `reserved' 是一个保留的证书，必须是零。默认值为零。

     `access' 为一个整数，用于给键的预期安全访问指定访问掩码。默认值为
     *note KEY_WRITE: 39ca.。 参阅 *note Access Rights: 39cb. 了解其它允
     许值。

     如果 `key' 是预定义键之一，`sub_key' 可能会是 ‘None’。该情况下，返
     回的句柄就是传入函数的句柄。

     如果键已经存在，则该函数打开已经存在的该键。

     返回值是所开打键的句柄。如果函数失败，则引发一个 *note OSError:
     1d4. 异常。

     引发一个 *note 审计事件: ea1. ‘winreg.CreateKey’，附带参数 ‘key’,
     ‘sub_key’, ‘access’。

     引发一个 *note 审计事件: ea1. ‘winreg.OpenKey/result’，附带参数
     ‘key’。

     3.2 新版功能.

     在 3.3 版更改: 参考 *note 上文: 39c4.。

 -- 函数: winreg.DeleteKey (key, sub_key)

     删除指定的键。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     `sub_key' 这个字符串必须是由 `key' 参数所指定键的一个子项。该值项不
     可以是 ‘None’，同时键也不可以有子项。

     `该方法不能删除带有子项的键。'

     如果方法成功，则整个键，包括其所有值项都会被移除。如果方法失败，则
     引发一个 *note OSError: 1d4. 异常。

     引发一个 *note 审计事件: ea1. ‘winreg.DeleteKey’，附带参数 ‘key’,
     ‘sub_key’, ‘access’。

     在 3.3 版更改: 参考 *note 上文: 39c4.。

 -- 函数: winreg.DeleteKeyEx (key, sub_key, access=KEY_WOW64_64KEY,
          reserved=0)

     删除指定的键。

          注解: 函数 *note DeleteKeyEx(): 34e3. 通过 RegDeleteKeyEx 这个
          Windows API 函数实现，该函数为 Windows 的64位版本专属。 参阅
          RegDeleteKeyEx 文档(1)。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     `sub_key' 这个字符串必须是由 `key' 参数所指定键的一个子项。该值项不
     可以是 ‘None’，同时键也不可以有子项。

     `reserved' 是一个保留的证书，必须是零。默认值为零。

     `access' 为一个整数，用于给键的预期安全访问指定访问掩码。默认值为常
     量 ‘_WOW64_64KEY’ 。参阅 *note Access Rights: 39cb. 了解其它允许值
     。

     `该方法不能删除带有子项的键。'

     如果方法成功，则整个键，包括其所有值项都会被移除。如果方法失败，则
     引发一个 *note OSError: 1d4. 异常。

     在不支持的 Windows 版本之上，将会引发 *note NotImplementedError:
     617. 异常。

     引发一个 *note 审计事件: ea1. ‘winreg.DeleteKey’，附带参数 ‘key’,
     ‘sub_key’, ‘access’。

     3.2 新版功能.

     在 3.3 版更改: 参考 *note 上文: 39c4.。

 -- 函数: winreg.DeleteValue (key, value)

     从某个注册键中删除一个命名值项。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     `value' 为标识所要删除值项的字符串。

     引发一个 *note 审计事件: ea1. ‘winreg.DeleteValue’，附带参数 ‘key’,
     ‘value’。

 -- 函数: winreg.EnumKey (key, index)

     列举某个已经打开注册表键的子项，并返回一个字符串。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     `index' 为一个整数，用于标识所获取键的索引。

     每次调用该函数都会获取一个子项的名字。通常它会被反复调用，直到引发
     *note OSError: 1d4. 异常，这说明已经没有更多的可用值了。

     引发一个 *note 审计事件: ea1. ‘winreg.EnumKey’，附带参数 ‘key’,
     ‘index’。

     在 3.3 版更改: 参考 *note 上文: 39c4.。

 -- 函数: winreg.EnumValue (key, index)

     列举某个已经打开注册表键的值项，并返回一个元组。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     `index' 为一个整数，用于标识要获取值项的索引。

     每次调用该函数都会获取一个子项的名字。通常它会被反复调用，直到引发
     *note OSError: 1d4. 异常，这说明已经没有更多的可用值了。

     结果为3元素的元组。

     索引        含义
                 
     -------------------------------------------------------------
                 
     ‘0’         用于标识值项名称的字符串。
                 
                 
     ‘1’         保存值项数据的对象，其类型取决于背后的注册表类
                 型。
                 
                 
     ‘2’         标识值项数据类型的整数。（请查阅
                 *note SetValueEx(): 34f3. 文档中的表格）
                 

     引发一个 *note 审计事件: ea1. ‘winreg.EnumValue’，附带参数 ‘key’,
     ‘index’。

     在 3.3 版更改: 参考 *note 上文: 39c4.。

 -- 函数: winreg.ExpandEnvironmentStrings (str)

     Expands environment variable placeholders ‘%NAME%’ in strings like
     *note REG_EXPAND_SZ: 39cc.:

          >>> ExpandEnvironmentStrings('%windir%')
          'C:\\Windows'

     引发一个 *note 审计事件: ea1. ‘winreg.ExpandEnvironmentStrings’，附
     带参数 ‘str’。

 -- 函数: winreg.FlushKey (key)

     将某个键的所有属性写入注册表。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     It is not necessary to call *note FlushKey(): 39cd. to change a
     key.  Registry changes are flushed to disk by the registry using
     its lazy flusher.  Registry changes are also flushed to disk at
     system shutdown.  Unlike *note CloseKey(): 39c7, the *note
     FlushKey(): 39cd. method returns only when all the data has been
     written to the registry.  An application should only call *note
     FlushKey(): 39cd. if it requires absolute certainty that registry
     changes are on disk.

          注解: If you don’t know whether a *note FlushKey(): 39cd. call
          is required, it probably isn’t.

 -- 函数: winreg.LoadKey (key, sub_key, file_name)

     Creates a subkey under the specified key and stores registration
     information from a specified file into that subkey.

     `key' is a handle returned by *note ConnectRegistry(): 34df. or one
     of the constants *note HKEY_USERS: 39ce. or *note
     HKEY_LOCAL_MACHINE: 39cf.

     `sub_key' is a string that identifies the subkey to load.

     `file_name' is the name of the file to load registry data from.
     This file must have been created with the *note SaveKey(): 34f1.
     function.  Under the file allocation table (FAT) file system, the
     filename may not have an extension.

     A call to *note LoadKey(): 34ea. fails if the calling process does
     not have the ‘SE_RESTORE_PRIVILEGE’ privilege.  Note that
     privileges are different from permissions – see the RegLoadKey
     documentation(2) for more details.

     If `key' is a handle returned by *note ConnectRegistry(): 34df,
     then the path specified in `file_name' is relative to the remote
     computer.

     引发一个 *note 审计事件: ea1. ‘winreg.LoadKey’，附带参数 ‘key’,
     ‘sub_key’, ‘file_name’。

 -- 函数: winreg.OpenKey (key, sub_key, reserved=0, access=KEY_READ)
 -- 函数: winreg.OpenKeyEx (key, sub_key, reserved=0, access=KEY_READ)

     Opens the specified key, returning a *note handle object: 39c3.

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     `sub_key' is a string that identifies the sub_key to open.

     `reserved' is a reserved integer, and must be zero.  The default is
     zero.

     `access' is an integer that specifies an access mask that describes
     the desired security access for the key.  Default is *note
     KEY_READ: 39d1.  See *note Access Rights: 39cb. for other allowed
     values.

     The result is a new handle to the specified key.

     If the function fails, *note OSError: 1d4. is raised.

     引发一个 *note 审计事件: ea1. ‘winreg.OpenKey’，附带参数 ‘key’,
     ‘sub_key’, ‘access’。

     引发一个 *note 审计事件: ea1. ‘winreg.OpenKey/result’，附带参数
     ‘key’。

     在 3.2 版更改: Allow the use of named arguments.

     在 3.3 版更改: 参考 *note 上文: 39c4.。

 -- 函数: winreg.QueryInfoKey (key)

     Returns information about a key, as a tuple.

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     结果为3元素的元组。

     索引        含义
                 
     --------------------------------------------------------------
                 
     ‘0’         An integer giving the number of sub keys this
                 key has.
                 
                 
     ‘1’         An integer giving the number of values this key
                 has.
                 
                 
     ‘2’         An integer giving when the key was last
                 modified (if available) as 100’s of nanoseconds
                 since Jan 1, 1601.
                 

     引发一个 *note 审计事件: ea1. ‘winreg.QueryInfoKey’，附带参数
     ‘key’。

 -- 函数: winreg.QueryValue (key, sub_key)

     Retrieves the unnamed value for a key, as a string.

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     `sub_key' is a string that holds the name of the subkey with which
     the value is associated.  If this parameter is ‘None’ or empty, the
     function retrieves the value set by the *note SetValue(): 34f2.
     method for the key identified by `key'.

     Values in the registry have name, type, and data components.  This
     method retrieves the data for a key’s first value that has a ‘NULL’
     name.  But the underlying API call doesn’t return the type, so
     always use *note QueryValueEx(): 34f0. if possible.

     引发一个 *note 审计事件: ea1. ‘winreg.QueryValue’，附带参数 ‘key’,
     ‘sub_key’, ‘value_name’。

 -- 函数: winreg.QueryValueEx (key, value_name)

     Retrieves the type and data for a specified value name associated
     with an open registry key.

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     `value_name' is a string indicating the value to query.

     The result is a tuple of 2 items:

     索引        含义
                 
     ----------------------------------------------------------
                 
     ‘0’         The value of the registry item.
                 
                 
     ‘1’         An integer giving the registry type for
                 this value (see table in docs for
                 *note SetValueEx(): 34f3.)
                 

     引发一个 *note 审计事件: ea1. ‘winreg.QueryValue’，附带参数 ‘key’,
     ‘sub_key’, ‘value_name’。

 -- 函数: winreg.SaveKey (key, file_name)

     Saves the specified key, and all its subkeys to the specified file.

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     `file_name' is the name of the file to save registry data to.  This
     file cannot already exist.  If this filename includes an extension,
     it cannot be used on file allocation table (FAT) file systems by
     the *note LoadKey(): 34ea. method.

     If `key' represents a key on a remote computer, the path described
     by `file_name' is relative to the remote computer.  The caller of
     this method must possess the ‘SeBackupPrivilege’ security
     privilege.  Note that privileges are different than permissions –
     see the Conflicts Between User Rights and Permissions
     documentation(3) for more details.

     This function passes ‘NULL’ for `security_attributes' to the API.

     引发一个 *note 审计事件: ea1. ‘winreg.SaveKey’，附带参数 ‘key’,
     ‘file_name’。

 -- 函数: winreg.SetValue (key, sub_key, type, value)

     Associates a value with a specified key.

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     `sub_key' is a string that names the subkey with which the value is
     associated.

     `type' is an integer that specifies the type of the data.
     Currently this must be *note REG_SZ: 39d2, meaning only strings are
     supported.  Use the *note SetValueEx(): 34f3. function for support
     for other data types.

     `value' is a string that specifies the new value.

     If the key specified by the `sub_key' parameter does not exist, the
     SetValue function creates it.

     Value lengths are limited by available memory.  Long values (more
     than 2048 bytes) should be stored as files with the filenames
     stored in the configuration registry.  This helps the registry
     perform efficiently.

     The key identified by the `key' parameter must have been opened
     with *note KEY_SET_VALUE: 39d3. access.

     引发一个 *note 审计事件: ea1. ‘winreg.SetValue’，附带参数 ‘key’,
     ‘sub_key’, ‘type’, ‘value’。

 -- 函数: winreg.SetValueEx (key, value_name, reserved, type, value)

     Stores data in the value field of an open registry key.

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     `value_name' is a string that names the subkey with which the value
     is associated.

     `reserved' can be anything – zero is always passed to the API.

     `type' is an integer that specifies the type of the data.  See
     *note Value Types: 39d4. for the available types.

     `value' is a string that specifies the new value.

     This method can also set additional value and type information for
     the specified key.  The key identified by the key parameter must
     have been opened with *note KEY_SET_VALUE: 39d3. access.

     To open the key, use the *note CreateKey(): 34e0. or *note
     OpenKey(): 34eb. methods.

     Value lengths are limited by available memory.  Long values (more
     than 2048 bytes) should be stored as files with the filenames
     stored in the configuration registry.  This helps the registry
     perform efficiently.

     引发一个 *note 审计事件: ea1. ‘winreg.SetValue’，附带参数 ‘key’,
     ‘sub_key’, ‘type’, ‘value’。

 -- 函数: winreg.DisableReflectionKey (key)

     Disables registry reflection for 32-bit processes running on a
     64-bit operating system.

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     Will generally raise *note NotImplementedError: 617. if executed on
     a 32-bit operating system.

     If the key is not on the reflection list, the function succeeds but
     has no effect.  Disabling reflection for a key does not affect
     reflection of any subkeys.

     引发一个 *note 审计事件: ea1. ‘winreg.DisableReflectionKey’，附带参
     数 ‘key’。

 -- 函数: winreg.EnableReflectionKey (key)

     Restores registry reflection for the specified disabled key.

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     Will generally raise *note NotImplementedError: 617. if executed on
     a 32-bit operating system.

     Restoring reflection for a key does not affect reflection of any
     subkeys.

     引发一个 *note 审计事件: ea1. ‘winreg.EnableReflectionKey’，附带参
     数 ‘key’。

 -- 函数: winreg.QueryReflectionKey (key)

     Determines the reflection state for the specified key.

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 39c9. 之
     一。

     Returns ‘True’ if reflection is disabled.

     Will generally raise *note NotImplementedError: 617. if executed on
     a 32-bit operating system.

     引发一个 *note 审计事件: ea1. ‘winreg.QueryReflectionKey’，附带参数
     ‘key’。

   ---------- Footnotes ----------

   (1) https://msdn.microsoft.com/en-us/library/ms724847%28VS.85%29.aspx

   (2) 
https://msdn.microsoft.com/en-us/library/ms724889%28v=VS.85%29.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx


File: python.info,  Node: 常量<10>,  Next: Registry Handle Objects,  Prev: 函数<11>,  Up: winreg --- Windows 注册表访问

5.34.3.2 常量
.............

The following constants are defined for use in many ‘_winreg’ functions.

* Menu:

* HKEY_* Constants::
* Access Rights::
* Value Types::


File: python.info,  Node: HKEY_* Constants,  Next: Access Rights,  Up: 常量<10>

5.34.3.3 HKEY_* Constants
.........................

 -- 数据: winreg.HKEY_CLASSES_ROOT

     Registry entries subordinate to this key define types (or classes)
     of documents and the properties associated with those types.  Shell
     and COM applications use the information stored under this key.

 -- 数据: winreg.HKEY_CURRENT_USER

     Registry entries subordinate to this key define the preferences of
     the current user.  These preferences include the settings of
     environment variables, data about program groups, colors, printers,
     network connections, and application preferences.

 -- 数据: winreg.HKEY_LOCAL_MACHINE

     Registry entries subordinate to this key define the physical state
     of the computer, including data about the bus type, system memory,
     and installed hardware and software.

 -- 数据: winreg.HKEY_USERS

     Registry entries subordinate to this key define the default user
     configuration for new users on the local computer and the user
     configuration for the current user.

 -- 数据: winreg.HKEY_PERFORMANCE_DATA

     Registry entries subordinate to this key allow you to access
     performance data.  The data is not actually stored in the registry;
     the registry functions cause the system to collect the data from
     its source.

 -- 数据: winreg.HKEY_CURRENT_CONFIG

     Contains information about the current hardware profile of the
     local computer system.

 -- 数据: winreg.HKEY_DYN_DATA

     This key is not used in versions of Windows after 98.


File: python.info,  Node: Access Rights,  Next: Value Types,  Prev: HKEY_* Constants,  Up: 常量<10>

5.34.3.4 Access Rights
......................

For more information, see Registry Key Security and Access(1).

 -- 数据: winreg.KEY_ALL_ACCESS

     Combines the STANDARD_RIGHTS_REQUIRED, *note KEY_QUERY_VALUE: 39df,
     *note KEY_SET_VALUE: 39d3, *note KEY_CREATE_SUB_KEY: 39e0, *note
     KEY_ENUMERATE_SUB_KEYS: 39e1, *note KEY_NOTIFY: 39e2, and *note
     KEY_CREATE_LINK: 39e3. access rights.

 -- 数据: winreg.KEY_WRITE

     Combines the STANDARD_RIGHTS_WRITE, *note KEY_SET_VALUE: 39d3, and
     *note KEY_CREATE_SUB_KEY: 39e0. access rights.

 -- 数据: winreg.KEY_READ

     Combines the STANDARD_RIGHTS_READ, *note KEY_QUERY_VALUE: 39df,
     *note KEY_ENUMERATE_SUB_KEYS: 39e1, and *note KEY_NOTIFY: 39e2.
     values.

 -- 数据: winreg.KEY_EXECUTE

     Equivalent to *note KEY_READ: 39d1.

 -- 数据: winreg.KEY_QUERY_VALUE

     Required to query the values of a registry key.

 -- 数据: winreg.KEY_SET_VALUE

     Required to create, delete, or set a registry value.

 -- 数据: winreg.KEY_CREATE_SUB_KEY

     Required to create a subkey of a registry key.

 -- 数据: winreg.KEY_ENUMERATE_SUB_KEYS

     Required to enumerate the subkeys of a registry key.

 -- 数据: winreg.KEY_NOTIFY

     Required to request change notifications for a registry key or for
     subkeys of a registry key.

 -- 数据: winreg.KEY_CREATE_LINK

     Reserved for system use.

* Menu:

* 64-bit Specific::

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx


File: python.info,  Node: 64-bit Specific,  Up: Access Rights

5.34.3.5 64-bit Specific
........................

For more information, see Accessing an Alternate Registry View(1).

 -- 数据: winreg.KEY_WOW64_64KEY

     Indicates that an application on 64-bit Windows should operate on
     the 64-bit registry view.

 -- 数据: winreg.KEY_WOW64_32KEY

     Indicates that an application on 64-bit Windows should operate on
     the 32-bit registry view.

   ---------- Footnotes ----------

   (1) https://msdn.microsoft.com/en-us/library/aa384129(v=VS.85).aspx


File: python.info,  Node: Value Types,  Prev: Access Rights,  Up: 常量<10>

5.34.3.6 Value Types
....................

For more information, see Registry Value Types(1).

 -- 数据: winreg.REG_BINARY

     Binary data in any form.

 -- 数据: winreg.REG_DWORD

     32-bit number.

 -- 数据: winreg.REG_DWORD_LITTLE_ENDIAN

     A 32-bit number in little-endian format.  Equivalent to *note
     REG_DWORD: 39eb.

 -- 数据: winreg.REG_DWORD_BIG_ENDIAN

     A 32-bit number in big-endian format.

 -- 数据: winreg.REG_EXPAND_SZ

     Null-terminated string containing references to environment
     variables (‘%PATH%’).

 -- 数据: winreg.REG_LINK

     A Unicode symbolic link.

 -- 数据: winreg.REG_MULTI_SZ

     A sequence of null-terminated strings, terminated by two null
     characters.  (Python handles this termination automatically.)

 -- 数据: winreg.REG_NONE

     No defined value type.

 -- 数据: winreg.REG_QWORD

     A 64-bit number.

     3.6 新版功能.

 -- 数据: winreg.REG_QWORD_LITTLE_ENDIAN

     A 64-bit number in little-endian format.  Equivalent to *note
     REG_QWORD: 5bb.

     3.6 新版功能.

 -- 数据: winreg.REG_RESOURCE_LIST

     A device-driver resource list.

 -- 数据: winreg.REG_FULL_RESOURCE_DESCRIPTOR

     A hardware setting.

 -- 数据: winreg.REG_RESOURCE_REQUIREMENTS_LIST

     A hardware resource list.

 -- 数据: winreg.REG_SZ

     A null-terminated string.

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/ms724884%28v=VS.85%29.aspx


File: python.info,  Node: Registry Handle Objects,  Prev: 常量<10>,  Up: winreg --- Windows 注册表访问

5.34.3.7 Registry Handle Objects
................................

This object wraps a Windows HKEY object, automatically closing it when
the object is destroyed.  To guarantee cleanup, you can call either the
*note Close(): 39c8. method on the object, or the *note CloseKey():
39c7. function.

All registry functions in this module return one of these objects.

All registry functions in this module which accept a handle object also
accept an integer, however, use of the handle object is encouraged.

Handle objects provide semantics for *note __bool__(): c70. – thus

     if handle:
         print("Yes")

will print ‘Yes’ if the handle is currently valid (has not been closed
or detached).

The object also support comparison semantics, so handle objects will
compare true if they both reference the same underlying Windows handle
value.

Handle objects can be converted to an integer (e.g., using the built-in
*note int(): 185. function), in which case the underlying Windows handle
value is returned.  You can also use the *note Detach(): 34ec. method to
return the integer handle, and also disconnect the Windows handle from
the handle object.

 -- 方法: PyHKEY.Close ()

     Closes the underlying Windows handle.

     If the handle is already closed, no error is raised.

 -- 方法: PyHKEY.Detach ()

     Detaches the Windows handle from the handle object.

     The result is an integer that holds the value of the handle before
     it is detached.  If the handle is already detached or closed, this
     will return zero.

     After calling this function, the handle is effectively invalidated,
     but the handle is not closed.  You would call this function when
     you need the underlying Win32 handle to exist beyond the lifetime
     of the handle object.

     引发一个 *note 审计事件: ea1. ‘winreg.PyHKEY.Detach’，附带参数
     ‘key’。

 -- 方法: PyHKEY.__enter__ ()
 -- 方法: PyHKEY.__exit__ (*exc_info)

     The HKEY object implements *note __enter__(): c9d. and *note
     __exit__(): c9e. and thus supports the context protocol for the
     *note with: 6f2. statement:

          with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key:
              ...  # work with key

     will automatically close `key' when control leaves the *note with:
     6f2. block.


File: python.info,  Node: winsound --- Sound-playing interface for Windows,  Prev: winreg --- Windows 注册表访问,  Up: Windows系统相关模块

5.34.4 ‘winsound’ — Sound-playing interface for Windows
-------------------------------------------------------

__________________________________________________________________

The *note winsound: 12c. module provides access to the basic
sound-playing machinery provided by Windows platforms.  It includes
functions and several constants.

 -- 函数: winsound.Beep (frequency, duration)

     Beep the PC’s speaker.  The `frequency' parameter specifies
     frequency, in hertz, of the sound, and must be in the range 37
     through 32,767.  The `duration' parameter specifies the number of
     milliseconds the sound should last.  If the system is not able to
     beep the speaker, *note RuntimeError: 2bb. is raised.

 -- 函数: winsound.PlaySound (sound, flags)

     Call the underlying ‘PlaySound()’ function from the Platform API.
     The `sound' parameter may be a filename, a system sound alias,
     audio data as a *note bytes-like object: 5f1, or ‘None’.  Its
     interpretation depends on the value of `flags', which can be a
     bitwise ORed combination of the constants described below.  If the
     `sound' parameter is ‘None’, any currently playing waveform sound
     is stopped.  If the system indicates an error, *note RuntimeError:
     2bb. is raised.

 -- 函数: winsound.MessageBeep (type=MB_OK)

     Call the underlying ‘MessageBeep()’ function from the Platform API.
     This plays a sound as specified in the registry.  The `type'
     argument specifies which sound to play; possible values are ‘-1’,
     ‘MB_ICONASTERISK’, ‘MB_ICONEXCLAMATION’, ‘MB_ICONHAND’,
     ‘MB_ICONQUESTION’, and ‘MB_OK’, all described below.  The value
     ‘-1’ produces a "simple beep"; this is the final fallback if a
     sound cannot be played otherwise.  If the system indicates an
     error, *note RuntimeError: 2bb. is raised.

 -- 数据: winsound.SND_FILENAME

     The `sound' parameter is the name of a WAV file.  Do not use with
     *note SND_ALIAS: 39fa.

 -- 数据: winsound.SND_ALIAS

     The `sound' parameter is a sound association name from the
     registry.  If the registry contains no such name, play the system
     default sound unless *note SND_NODEFAULT: 39fb. is also specified.
     If no default sound is registered, raise *note RuntimeError: 2bb.
     Do not use with *note SND_FILENAME: 39f9.

     All Win32 systems support at least the following; most systems
     support many more:

     *note PlaySound(): 5bf.        Corresponding Control Panel Sound name
     `name'                         

     ----------------------------------------------------------------------------
                                    
     ‘'SystemAsterisk'’             Asterisk
                                    
                                    
     ‘'SystemExclamation'’          Exclamation
                                    
                                    
     ‘'SystemExit'’                 Exit Windows
                                    
                                    
     ‘'SystemHand'’                 Critical Stop
                                    
                                    
     ‘'SystemQuestion'’             Question
                                    

     例如

          import winsound
          # Play Windows exit sound.
          winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

          # Probably play Windows default sound, if any is registered (because
          # "*" probably isn't the registered name of any sound).
          winsound.PlaySound("*", winsound.SND_ALIAS)

 -- 数据: winsound.SND_LOOP

     Play the sound repeatedly.  The *note SND_ASYNC: 39fd. flag must
     also be used to avoid blocking.  Cannot be used with *note
     SND_MEMORY: 39fe.

 -- 数据: winsound.SND_MEMORY

     The `sound' parameter to *note PlaySound(): 5bf. is a memory image
     of a WAV file, as a *note bytes-like object: 5f1.

          注解: This module does not support playing from a memory image
          asynchronously, so a combination of this flag and *note
          SND_ASYNC: 39fd. will raise *note RuntimeError: 2bb.

 -- 数据: winsound.SND_PURGE

     Stop playing all instances of the specified sound.

          注解: This flag is not supported on modern Windows platforms.

 -- 数据: winsound.SND_ASYNC

     Return immediately, allowing sounds to play asynchronously.

 -- 数据: winsound.SND_NODEFAULT

     If the specified sound cannot be found, do not play the system
     default sound.

 -- 数据: winsound.SND_NOSTOP

     Do not interrupt sounds currently playing.

 -- 数据: winsound.SND_NOWAIT

     Return immediately if the sound driver is busy.

          注解: This flag is not supported on modern Windows platforms.

 -- 数据: winsound.MB_ICONASTERISK

     Play the ‘SystemDefault’ sound.

 -- 数据: winsound.MB_ICONEXCLAMATION

     Play the ‘SystemExclamation’ sound.

 -- 数据: winsound.MB_ICONHAND

     Play the ‘SystemHand’ sound.

 -- 数据: winsound.MB_ICONQUESTION

     Play the ‘SystemQuestion’ sound.

 -- 数据: winsound.MB_OK

     Play the ‘SystemDefault’ sound.


File: python.info,  Node: Unix 专有服务,  Next: 被取代的模块,  Prev: Windows系统相关模块,  Up: Python 标准库

5.35 Unix 专有服务
==================

本章描述的模块提供了 Unix 操作系统独有特性的接口，在某些情况下也适用于它
的某些或许多衍生版。 以下为模块概览：

* Menu:

* posix: posix --- 最常见的 POSIX 系统调用. 最常见的 POSIX 系统调用
* pwd: pwd --- 用户密码数据库. 用户密码数据库
* spwd: spwd --- The shadow password database. The shadow password database
* grp: grp --- 组数据库. 组数据库
* crypt: crypt --- Function to check Unix passwords. Function to check Unix passwords
* termios: termios --- POSIX 风格的 tty 控制. POSIX 风格的 tty 控制
* tty: tty --- 终端控制功能. 终端控制功能
* pty: pty --- 伪终端工具. 伪终端工具
* fcntl: fcntl --- The fcntl and ioctl system calls. The fcntl and ioctl system calls
* pipes: pipes --- 终端管道接口. 终端管道接口
* resource: resource --- Resource usage information. Resource usage information
* nis: nis --- Sun 的 NIS 黄页 接口. Sun 的 NIS (黄页) 接口
* Unix syslog 库例程::


File: python.info,  Node: posix --- 最常见的 POSIX 系统调用,  Next: pwd --- 用户密码数据库,  Up: Unix 专有服务

5.35.1 ‘posix’ — 最常见的 POSIX 系统调用
----------------------------------------

__________________________________________________________________

此模块提供了对基于 C 标准和 POSIX 标准（一种稍加修改的 Unix 接口）进行标
准化的系统功能的访问。

`请勿直接导入此模块。' 而应导入 *note os: c5. 模块，它提供了此接口的 `可
移植' 版本。 在 Unix 上，*note os: c5. 模块提供了 *note posix: d2. 接口
的一个超集。 在非 Unix 操作系统上 *note posix: d2. 模块将不可用，但会通
过 *note os: c5. 接口提供它的一个可用子集。 一旦导入了 *note os: c5.，用
它替代 *note posix: d2. 时就 `没有' 性能惩罚。 此外，*note os: c5. 还提
供了一些附加功能，例如在 ‘os.environ’ 中的某个条目被修改时会自动调用
*note putenv(): 1ef5.。

错误将作为异常被报告；对于类型错误会给出普通异常，而系统调用所报告的异常
则会引发 *note OSError: 1d4.。

* Menu:

* 大文件支持::
* 重要的模块内容::


File: python.info,  Node: 大文件支持,  Next: 重要的模块内容,  Up: posix --- 最常见的 POSIX 系统调用

5.35.1.1 大文件支持
...................

某些操作系统（包括 AIX, HP-UX, Irix 和 Solaris）可对 ‘int’ 和 ‘long’ 为
32 位值的 C 编程模型提供大于 2 GiB 的文件的支持。 这在通常情况下是以将相
关数据长度和偏移类型定义为 64 位值的方式来实现的。 这样的文件有时被称为
`大文件'。

Python 中的大文件支持会在 ‘off_t’ 的大小超过 ‘long’ 且 ‘long long’ 至少
与 ‘off_t’ 一样大时被启用。 要启用此模式可能必须在启用特定编译旗标的情况
下执行 Python 配置和编译。 例如，在最近几个版本的 Irix 中默认启用了大文
件支持，但在 Solaris 2.6 和 2.7 中你还需要执行这样的操作:

     CFLAGS="`getconf LFS_CFLAGS`" OPT="-g -O2 $CFLAGS" \
             ./configure

在支持大文件的 Linux 系统中，可以这样做:

     CFLAGS='-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64' OPT="-g -O2 $CFLAGS" \
             ./configure


File: python.info,  Node: 重要的模块内容,  Prev: 大文件支持,  Up: posix --- 最常见的 POSIX 系统调用

5.35.1.2 重要的模块内容
.......................

除了 *note os: c5. 模块文档已说明的许多函数，*note posix: d2. 还定义了下
列数据项:

 -- 数据: posix.environ

     一个表示解释器启动时间点的字符串环境的字典。 键和值的类型在Unix 上
     为 bytes 而在 Windows 上为 str。 例如，‘environ[b'HOME']’ (Windows
     上的 ‘environ['HOME']’) 是你的家目录的路径名，等价于 C 中的
     ‘getenv("HOME")’。

     修改此字典不会影响由 *note execv(): 1f08, *note popen(): 2aa. 或
     *note system(): dc9. 所传入的字符串环境；如果你需要修改环境，请将
     ‘environ’ 传给 *note execve(): a48. 或者为 *note system(): dc9. 或
     *note popen(): 2aa. 的命令字符串添加变量赋值和 export 语句。

     在 3.2 版更改: 在 Unix 上，键和值为 bytes 类型。

          注解: *note os: c5. 模块提供了对 ‘environ’ 的替代实现，它会在
          被修改时更新环境。 还要注意更新 *note os.environ: b3f. 将导致
          此字典失效。 推荐使用这个 *note os: c5. 模块版本而不是直接访问
          *note posix: d2. 模块。


File: python.info,  Node: pwd --- 用户密码数据库,  Next: spwd --- The shadow password database,  Prev: posix --- 最常见的 POSIX 系统调用,  Up: Unix 专有服务

5.35.2 ‘pwd’ — 用户密码数据库
-----------------------------

__________________________________________________________________

此模块可以访问 Unix 用户账户名及密码数据库，在所有 Unix 版本上均可使用。

密码数据库中的条目以元组对象返回，属性对应 ‘passwd’ 中的结构（属性如下所
示，可参考 ‘<pwd.h>’）：

索引        属性                含义
                                
------------------------------------------------------------------
                                
0           ‘pw_name’           登录名
                                
                                
1           ‘pw_passwd’         密码，可能已经加密
                                
                                
2           ‘pw_uid’            用户 ID 数值
                                
                                
3           ‘pw_gid’            组 ID 数值
                                
                                
4           ‘pw_gecos’          用户名或备注
                                
                                
5           ‘pw_dir’            用户主目录
                                
                                
6           ‘pw_shell’          用户的命令解释器
                                

其中 uid 和 gid 是整数，其他是字符串，如果找不到对应的项目，抛出 *note
KeyError: 2c8. 异常。

     注解: 
     传统的 Unix 系统中，‘pw_passwd’ 的值通常使用 DES 导出的算法加密（参
     阅 *note crypt: 29. 模块）。不过现在的 unix 系统使用 `影子密码' 系
     统。在这些 unix 上，`pw_passwd' 只包含星号（‘'*'’）或字母（‘'x'’）
     ，而加密的密码存储在文件 ‘/etc/shadow’ 中，此文件不是全局可读的。在
     `pw_passwd' 中是否包含有用信息是系统相关的。如果可以访问到加密的密
     码，就需要使用 *note spwd: f2. 模块了。

本模块定义如下内容：

 -- 函数: pwd.getpwuid (uid)

     给定用户的数值 ID，返回密码数据库的对应项目。

 -- 函数: pwd.getpwnam (name)

     给定用户名，返回密码数据库的对应项目。

 -- 函数: pwd.getpwall ()

     返回密码数据库中所有项目的列表，顺序不是固定的。

参见
....

模块 *note grp: 8b.

     针对用户组数据库的接口，与本模块类似。

模块 *note spwd: f2.

     针对影子密码数据库的接口，与本模块类似。


File: python.info,  Node: spwd --- The shadow password database,  Next: grp --- 组数据库,  Prev: pwd --- 用户密码数据库,  Up: Unix 专有服务

5.35.3 ‘spwd’ — The shadow password database
--------------------------------------------

__________________________________________________________________

This module provides access to the Unix shadow password database.  It is
available on various Unix versions.

You must have enough privileges to access the shadow password database
(this usually means you have to be root).

Shadow password database entries are reported as a tuple-like object,
whose attributes correspond to the members of the ‘spwd’ structure
(Attribute field below, see ‘<shadow.h>’):

索引        属性                含义
                                
----------------------------------------------------------------------
                                
0           ‘sp_namp’           登录名
                                
                                
1           ‘sp_pwdp’           Encrypted password
                                
                                
2           ‘sp_lstchg’         Date of last change
                                
                                
3           ‘sp_min’            Minimal number of days between
                                changes
                                
                                
4           ‘sp_max’            Maximum number of days between
                                changes
                                
                                
5           ‘sp_warn’           Number of days before password
                                expires to warn user about it
                                
                                
6           ‘sp_inact’          Number of days after password
                                expires until account is disabled
                                
                                
7           ‘sp_expire’         Number of days since 1970-01-01
                                when account expires
                                
                                
8           ‘sp_flag’           Reserved
                                

The sp_namp and sp_pwdp items are strings, all others are integers.
*note KeyError: 2c8. is raised if the entry asked for cannot be found.

定义了以下函数：

 -- 函数: spwd.getspnam (name)

     Return the shadow password database entry for the given user name.

     在 3.6 版更改: Raises a *note PermissionError: 608. instead of
     *note KeyError: 2c8. if the user doesn’t have privileges.

 -- 函数: spwd.getspall ()

     Return a list of all available shadow password database entries, in
     arbitrary order.

参见
....

模块 *note grp: 8b.

     针对用户组数据库的接口，与本模块类似。

模块 *note pwd: d7.

     An interface to the normal password database, similar to this.


File: python.info,  Node: grp --- 组数据库,  Next: crypt --- Function to check Unix passwords,  Prev: spwd --- The shadow password database,  Up: Unix 专有服务

5.35.4 ‘grp’ — 组数据库
-----------------------

__________________________________________________________________

该模块提供对Unix组数据库的访问。 它在所有Unix版本上都可用。

组数据库条目被报告为类似元组的对象，其属性对应于 ‘group’ 结构的成员（下
面的属性字段，请参见 ‘<pwd.h>’ ）：

索引        属性            含义
                            
------------------------------------------------------------------
                            
0           gr_name         组名
                            
                            
1           gr_passwd       （加密的）组密码； 通常为空
                            
                            
2           gr_gid          数字组ID
                            
                            
3           gr_mem          组内所有成员的用户名
                            

gid 是整数，名称和密码是字符串，成员列表是字符串列表。 （注意，大多数用
户未根据密码数据库显式列为所属组的成员。请检查两个数据库以获取完整的成员
资格信息。还要注意，以 ‘+’ 或 ‘-’ 开头的 ‘gr_name’ 可能是 YP/NIS 引用，
可能无法通过 *note getgrnam(): 103b. 或 *note getgrgid(): 5e8. 访问。）

本模块定义如下内容：

 -- 函数: grp.getgrgid (gid)

     返回给定数字组 ID 的组数据库条目。 如果请求的条目无法找到则会引发
     *note KeyError: 2c8.。

     3.6 版后已移除: 从 Python 3.6 开始，弃用对 *note getgrgid(): 5e8. 中
     的 float 或 string 等非 integer 参数的支持。

 -- 函数: grp.getgrnam (name)

     返回给定组名的组数据库条目。 如果找不到要求的条目，则会引发 *note
     KeyError: 2c8. 错误。

 -- 函数: grp.getgrall ()

     以任意顺序返回所有可用组条目的列表。

参见
....

模块 *note pwd: d7.

     用户数据库的接口，与此类似。

模块 *note spwd: f2.

     针对影子密码数据库的接口，与本模块类似。


File: python.info,  Node: crypt --- Function to check Unix passwords,  Next: termios --- POSIX 风格的 tty 控制,  Prev: grp --- 组数据库,  Up: Unix 专有服务

5.35.5 ‘crypt’ — Function to check Unix passwords
-------------------------------------------------

`Source code:' Lib/crypt.py(1)

__________________________________________________________________

This module implements an interface to the ‘crypt(3)’ routine, which is
a one-way hash function based upon a modified DES algorithm; see the
Unix man page for further details.  Possible uses include storing hashed
passwords so you can check passwords without storing the actual
password, or attempting to crack Unix passwords with a dictionary.

Notice that the behavior of this module depends on the actual
implementation of the ‘crypt(3)’ routine in the running system.
Therefore, any extensions available on the current implementation will
also be available on this module.

*note 可用性: 136f.: Unix。 在 VxWorks 上不可用。

* Menu:

* Hashing Methods::
* Module Attributes::
* 模块函数: 模块函数<2>.
* 例子: 例子<31>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/crypt.py


File: python.info,  Node: Hashing Methods,  Next: Module Attributes,  Up: crypt --- Function to check Unix passwords

5.35.5.1 Hashing Methods
........................

3.3 新版功能.

The *note crypt: 29. module defines the list of hashing methods (not all
methods are available on all platforms):

 -- 数据: crypt.METHOD_SHA512

     A Modular Crypt Format method with 16 character salt and 86
     character hash based on the SHA-512 hash function.  This is the
     strongest method.

 -- 数据: crypt.METHOD_SHA256

     Another Modular Crypt Format method with 16 character salt and 43
     character hash based on the SHA-256 hash function.

 -- 数据: crypt.METHOD_BLOWFISH

     Another Modular Crypt Format method with 22 character salt and 31
     character hash based on the Blowfish cipher.

     3.7 新版功能.

 -- 数据: crypt.METHOD_MD5

     Another Modular Crypt Format method with 8 character salt and 22
     character hash based on the MD5 hash function.

 -- 数据: crypt.METHOD_CRYPT

     The traditional method with a 2 character salt and 13 characters of
     hash.  This is the weakest method.


File: python.info,  Node: Module Attributes,  Next: 模块函数<2>,  Prev: Hashing Methods,  Up: crypt --- Function to check Unix passwords

5.35.5.2 Module Attributes
..........................

3.3 新版功能.

 -- 属性: crypt.methods

     A list of available password hashing algorithms, as
     ‘crypt.METHOD_*’ objects.  This list is sorted from strongest to
     weakest.


File: python.info,  Node: 模块函数<2>,  Next: 例子<31>,  Prev: Module Attributes,  Up: crypt --- Function to check Unix passwords

5.35.5.3 模块函数
.................

The *note crypt: 29. module defines the following functions:

 -- 函数: crypt.crypt (word, salt=None)

     `word' will usually be a user’s password as typed at a prompt or in
     a graphical interface.  The optional `salt' is either a string as
     returned from *note mksalt(): 385, one of the ‘crypt.METHOD_*’
     values (though not all may be available on all platforms), or a
     full encrypted password including salt, as returned by this
     function.  If `salt' is not provided, the strongest method will be
     used (as returned by *note methods(): 3a22.).

     Checking a password is usually done by passing the plain-text
     password as `word' and the full results of a previous *note
     crypt(): 29. call, which should be the same as the results of this
     call.

     `salt' (either a random 2 or 16 character string, possibly prefixed
     with ‘$digit$’ to indicate the method) which will be used to
     perturb the encryption algorithm.  The characters in `salt' must be
     in the set ‘[./a-zA-Z0-9]’, with the exception of Modular Crypt
     Format which prefixes a ‘$digit$’.

     Returns the hashed password as a string, which will be composed of
     characters from the same alphabet as the salt.

     Since a few ‘crypt(3)’ extensions allow different values, with
     different sizes in the `salt', it is recommended to use the full
     crypted password as salt when checking for a password.

     在 3.3 版更改: Accept ‘crypt.METHOD_*’ values in addition to
     strings for `salt'.

 -- 函数: crypt.mksalt (method=None, *, rounds=None)

     Return a randomly generated salt of the specified method.  If no
     `method' is given, the strongest method available as returned by
     *note methods(): 3a22. is used.

     The return value is a string suitable for passing as the `salt'
     argument to *note crypt(): 29.

     `rounds' specifies the number of rounds for ‘METHOD_SHA256’,
     ‘METHOD_SHA512’ and ‘METHOD_BLOWFISH’.  For ‘METHOD_SHA256’ and
     ‘METHOD_SHA512’ it must be an integer between ‘1000’ and
     ‘999_999_999’, the default is ‘5000’.  For ‘METHOD_BLOWFISH’ it
     must be a power of two between ‘16’ (2^4) and ‘2_147_483_648’
     (2^31), the default is ‘4096’ (2^12).

     3.3 新版功能.

     在 3.7 版更改: Added the `rounds' parameter.


File: python.info,  Node: 例子<31>,  Prev: 模块函数<2>,  Up: crypt --- Function to check Unix passwords

5.35.5.4 例子
.............

A simple example illustrating typical use (a constant-time comparison
operation is needed to limit exposure to timing attacks.  *note
hmac.compare_digest(): a14. is suitable for this purpose):

     import pwd
     import crypt
     import getpass
     from hmac import compare_digest as compare_hash

     def login():
         username = input('Python login: ')
         cryptedpasswd = pwd.getpwnam(username)[1]
         if cryptedpasswd:
             if cryptedpasswd == 'x' or cryptedpasswd == '*':
                 raise ValueError('no support for shadow passwords')
             cleartext = getpass.getpass()
             return compare_hash(crypt.crypt(cleartext, cryptedpasswd), cryptedpasswd)
         else:
             return True

To generate a hash of a password using the strongest available method
and check it against the original:

     import crypt
     from hmac import compare_digest as compare_hash

     hashed = crypt.crypt(plaintext)
     if not compare_hash(hashed, crypt.crypt(plaintext, hashed)):
         raise ValueError("hashed version doesn't validate against original")


File: python.info,  Node: termios --- POSIX 风格的 tty 控制,  Next: tty --- 终端控制功能,  Prev: crypt --- Function to check Unix passwords,  Up: Unix 专有服务

5.35.6 ‘termios’ — POSIX 风格的 tty 控制
----------------------------------------

__________________________________________________________________

此模块提供了针对tty I/O 控制的 POSIX 调用的接口。 有关此类调用的完整描述
，请参阅 ‘termios(3)’ Unix 指南页。 它仅在当安装时配置了支持 POSIX
`termios' 风格的 tty I/O 控制的 Unix 版本上可用。

此模块中的所有函数均接受一个文件描述符 `fd' 作为第一个参数。 这可以是一
个整数形式的文件描述符，例如 ‘sys.stdin.fileno()’ 所返回的对象，或是一个
*note file object: b4a.，例如 ‘sys.stdin’ 本身。

这个模块还定义了与此处所提供的函数一起使用的所有必要的常量；这些常量与它
们在 C 中的对应常量同名。 请参考你的系统文档了解有关如何使用这些终端控制
接口的更多信息。

这个模块定义了以下函数：

 -- 函数: termios.tcgetattr (fd)

     对于文件描述符 `fd' 返回一个包含 tty 属性的列表，形式如下: ‘[iflag,
     oflag, cflag, lflag, ispeed, ospeed, cc]’，其中 `cc' 为一个包含 tty
     特殊字符的列表（每一项都是长度为 1 的字符串，索引号为 ‘VMIN’ 和
     ‘VTIME’ 的项除外，这些字段如有定义则应为整数）。 对旗标和速度以及
     `cc' 数组中索引的解读必须使用在 *note termios: 105. 模块中定义的符
     号常量来完成。

 -- 函数: termios.tcsetattr (fd, when, attributes)

     根据 `attributes' 列表设置文件描述符 `fd' 的 tty 属性，该列表即
     *note tcgetattr(): 3a28. 所返回的对象。 `when' 参数确定何时改变属性
     : ‘TCSANOW’ 表示立即改变，‘TCSADRAIN’ 表示在传输所有队列输出后再改
     变，或 ‘TCSAFLUSH’ 表示在传输所有队列输出并丢失所有队列输入后再改变
     。

 -- 函数: termios.tcsendbreak (fd, duration)

     在文件描述符 `fd' 上发送一个中断。 `duration' 为零表示发送时长为
     0.25–0.5 秒的中断；`duration' 非零值的含义取决于具体系统。

 -- 函数: termios.tcdrain (fd)

     进入等待状态直到写入文件描述符 `fd' 的所有输出都传送完毕。

 -- 函数: termios.tcflush (fd, queue)

     在文件描述符 `fd' 上丢弃队列数据。 `queue' 选择器指定哪个队列:
     ‘TCIFLUSH’ 表示输入队列，‘TCOFLUSH’ 表示输出队列，或 ‘TCIOFLUSH’ 表
     示两个队列同时。

 -- 函数: termios.tcflow (fd, action)

     在文件描述符 `fd' 上挂起一战恢复输入或输出。 `action' 参数可以为
     ‘TCOOFF’ 表示挂起输出，‘TCOON’ 表示重启输出，‘TCIOFF’ 表示挂起输入
     ，或 ‘TCION’ 表示重启输入。

参见
....

模块 *note tty: 116.

     针对常用终端控制操作的便捷函数。

* Menu:

* 示例: 示例<16>.


File: python.info,  Node: 示例<16>,  Up: termios --- POSIX 风格的 tty 控制

5.35.6.1 示例
.............

这个函数可提示输入密码并且关闭回显。 请注意其采取的技巧是使用一个单独的
*note tcgetattr(): 3a28. 调用和一个 *note try: d7a. ...  *note finally:
183. 语句来确保旧的 tty 属性无论在何种情况下都会被原样保存:

     def getpass(prompt="Password: "):
         import termios, sys
         fd = sys.stdin.fileno()
         old = termios.tcgetattr(fd)
         new = termios.tcgetattr(fd)
         new[3] = new[3] & ~termios.ECHO          # lflags
         try:
             termios.tcsetattr(fd, termios.TCSADRAIN, new)
             passwd = input(prompt)
         finally:
             termios.tcsetattr(fd, termios.TCSADRAIN, old)
         return passwd


File: python.info,  Node: tty --- 终端控制功能,  Next: pty --- 伪终端工具,  Prev: termios --- POSIX 风格的 tty 控制,  Up: Unix 专有服务

5.35.7 ‘tty’ — 终端控制功能
---------------------------

`Source code:' Lib/tty.py(1)

__________________________________________________________________

*note tty: 116. 模块定义了将 tty 放入 cbreak 和 raw 模式的函数。

因为它需要 *note termios: 105. 模块，所以只能在 Unix 上运行。

*note tty: 116. 模块定义了以下函数：

 -- 函数: tty.setraw (fd, when=termios.TCSAFLUSH)

     将文件描述符 `fd' 的模式更改为 raw 。如果 `when' 被省略，则默认为
     ‘termios.TCSAFLUSH’ ，并传递给 *note termios.tcsetattr(): 3a29. 。

 -- 函数: tty.setcbreak (fd, when=termios.TCSAFLUSH)

     将文件描述符 `fd' 的模式更改为 cbreak 。如果 `when' 被省略，则默认
     为 ‘termios.TCSAFLUSH’ ，并传递给 *note termios.tcsetattr(): 3a29.
     。

参见
....

模块 *note termios: 105.

     低级终端控制接口。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/tty.py


File: python.info,  Node: pty --- 伪终端工具,  Next: fcntl --- The fcntl and ioctl system calls,  Prev: tty --- 终端控制功能,  Up: Unix 专有服务

5.35.8 ‘pty’ — 伪终端工具
-------------------------

`源代码:' Lib/pty.py(1)

__________________________________________________________________

*note pty: d6. 模块定义了一些处理“伪终端”概念的操作：启动另一个进程并能
以程序方式在其控制终端中进行读写。

由于伪终端处理高度依赖于具体平台，因此此功能只有针对 Linux 的代码。 （
Linux 代码也可在其他平台上工作，但是未经测试。）

*note pty: d6. 模块定义了下列函数:

 -- 函数: pty.fork ()

     分叉。 将子进程的控制终端连接到一个伪终端。 返回值为 ‘(pid, fd)’。
     请注意子进程获得 `pid' 0 而 `fd' 为 `invalid'。 父进程返回值为子进
     程的 `pid' 而 `fd' 为一个连接到子进程的控制终端（并同时连接到子进程
     的标准输入和输出）的文件描述符。

 -- 函数: pty.openpty ()

     打开一个新的伪终端对，如果可能将使用 *note os.openpty(): 1f3d.，或
     是针对通用 Unix 系统的模拟代码。 返回一个文件描述符对 ‘(master,
     slave)’，分别表示主从两端。

 -- 函数: pty.spawn (argv[, master_read[, stdin_read]])

     生成一个进程，并将其控制终端连接到当前进程的标准 io。 这常被用来应
     对坚持要从控制终端读取数据的程序。 在 pty 背后生成的进程预期最后将
     被终止，而且当它被终止时 `spawn' 将会返回。

     会向 `master_read' 和 `stdin_read' 函数传入一个文件描述符供它们读取
     ，并且它们总是应当返回一个字节串。 为了强制 spawn 在子进程退出之前
     返回所以应当抛出 *note OSError: 1d4.。

     两个函数的默认实现在每次函数被调用时将读取并返回至多 1024 个字节。
     会向 `master_read' 回调传入伪终端的主文件描述符以从子进程读取输出，
     而向 `stdin_read' 传入文件描述符 0 以从父进程的标准输入读取数据。

     从两个回调返回空字节串会被解读为文件结束 (EOF) 条件，在此之后回调将
     不再被调用。 如果 `stdin_read' 发出 EOF 信号则控制终端就不能再与父
     进程或子进程进行通信。 除非子进程将不带任何输入就退出，否则随后
     `spawn' 将一直循环下去。 如果 `master_read' 发出 EOF 信号则会有相同
     的行为结果（至少是在 Linux 上）。

     如果两个回调都发出 EOF 信号则 `spawn' 可能将永不返回，除非在你的平
     台上当传入三个空列表时 `select' 会抛出一个错误。 这是一个程序缺陷，
     相关文档见 问题 26228(2)。

     引发一个 *note 审计事件: ea1. ‘pty.spawn’，附带参数 ‘argv’。

     在 3.4 版更改: *note spawn(): 8a1. 现在会从子进程的 *note
     os.waitpid(): 676. 返回状态值。

* Menu:

* 示例: 示例<17>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/pty.py

   (2) https://bugs.python.org/issue26228


File: python.info,  Node: 示例<17>,  Up: pty --- 伪终端工具

5.35.8.1 示例
.............

以下程序的作用类似于 Unix 命令 ‘script(1)’，它使用一个伪终端来记录一个
"typescript" 里终端进程的所有输入和输出:

     import argparse
     import os
     import pty
     import sys
     import time

     parser = argparse.ArgumentParser()
     parser.add_argument('-a', dest='append', action='store_true')
     parser.add_argument('-p', dest='use_python', action='store_true')
     parser.add_argument('filename', nargs='?', default='typescript')
     options = parser.parse_args()

     shell = sys.executable if options.use_python else os.environ.get('SHELL', 'sh')
     filename = options.filename
     mode = 'ab' if options.append else 'wb'

     with open(filename, mode) as script:
         def read(fd):
             data = os.read(fd, 1024)
             script.write(data)
             return data

         print('Script started, file is', filename)
         script.write(('Script started on %s\n' % time.asctime()).encode())

         pty.spawn(shell, read)

         script.write(('Script done on %s\n' % time.asctime()).encode())
         print('Script done, file is', filename)


File: python.info,  Node: fcntl --- The fcntl and ioctl system calls,  Next: pipes --- 终端管道接口,  Prev: pty --- 伪终端工具,  Up: Unix 专有服务

5.35.9 ‘fcntl’ — The ‘fcntl’ and ‘ioctl’ system calls
-----------------------------------------------------

__________________________________________________________________

This module performs file control and I/O control on file descriptors.
It is an interface to the ‘fcntl()’ and ‘ioctl()’ Unix routines.  For a
complete description of these calls, see ‘fcntl(2)’ and ‘ioctl(2)’ Unix
manual pages.

All functions in this module take a file descriptor `fd' as their first
argument.  This can be an integer file descriptor, such as returned by
‘sys.stdin.fileno()’, or an *note io.IOBase: 1dc. object, such as
‘sys.stdin’ itself, which provides a *note fileno(): 1f19. that returns
a genuine file descriptor.

在 3.3 版更改: Operations in this module used to raise an *note IOError:
99a. where they now raise an *note OSError: 1d4.

在 3.8 版更改: The fcntl module now contains ‘F_ADD_SEALS’,
‘F_GET_SEALS’, and ‘F_SEAL_*’ constants for sealing of *note
os.memfd_create(): 1f1. file descriptors.

这个模块定义了以下函数：

 -- 函数: fcntl.fcntl (fd, cmd, arg=0)

     Perform the operation `cmd' on file descriptor `fd' (file objects
     providing a *note fileno(): 1f19. method are accepted as well).
     The values used for `cmd' are operating system dependent, and are
     available as constants in the *note fcntl: 7e. module, using the
     same names as used in the relevant C header files.  The argument
     `arg' can either be an integer value, or a *note bytes: 33a.
     object.  With an integer value, the return value of this function
     is the integer return value of the C ‘fcntl()’ call.  When the
     argument is bytes it represents a binary structure, e.g.  created
     by *note struct.pack(): c13.  The binary data is copied to a buffer
     whose address is passed to the C ‘fcntl()’ call.  The return value
     after a successful call is the contents of the buffer, converted to
     a *note bytes: 33a. object.  The length of the returned object will
     be the same as the length of the `arg' argument.  This is limited
     to 1024 bytes.  If the information returned in the buffer by the
     operating system is larger than 1024 bytes, this is most likely to
     result in a segmentation violation or a more subtle data
     corruption.

     If the ‘fcntl()’ fails, an *note OSError: 1d4. is raised.

     Raises an *note auditing event: ea1. ‘fcntl.fcntl’ with arguments
     ‘fd’, ‘cmd’, ‘arg’.

 -- 函数: fcntl.ioctl (fd, request, arg=0, mutate_flag=True)

     This function is identical to the *note fcntl(): 26a9. function,
     except that the argument handling is even more complicated.

     The `request' parameter is limited to values that can fit in
     32-bits.  Additional constants of interest for use as the `request'
     argument can be found in the *note termios: 105. module, under the
     same names as used in the relevant C header files.

     The parameter `arg' can be one of an integer, an object supporting
     the read-only buffer interface (like *note bytes: 33a.) or an
     object supporting the read-write buffer interface (like *note
     bytearray: 33b.).

     In all but the last case, behaviour is as for the *note fcntl():
     26a9. function.

     If a mutable buffer is passed, then the behaviour is determined by
     the value of the `mutate_flag' parameter.

     If it is false, the buffer’s mutability is ignored and behaviour is
     as for a read-only buffer, except that the 1024 byte limit
     mentioned above is avoided – so long as the buffer you pass is at
     least as long as what the operating system wants to put there,
     things should work.

     If `mutate_flag' is true (the default), then the buffer is (in
     effect) passed to the underlying *note ioctl(): de6. system call,
     the latter’s return code is passed back to the calling Python, and
     the buffer’s new contents reflect the action of the *note ioctl():
     de6.  This is a slight simplification, because if the supplied
     buffer is less than 1024 bytes long it is first copied into a
     static buffer 1024 bytes long which is then passed to *note
     ioctl(): de6. and copied back into the supplied buffer.

     If the ‘ioctl()’ fails, an *note OSError: 1d4. exception is raised.

     举个例子：

          >>> import array, fcntl, struct, termios, os
          >>> os.getpgrp()
          13341
          >>> struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, "  "))[0]
          13341
          >>> buf = array.array('h', [0])
          >>> fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1)
          0
          >>> buf
          array('h', [13341])

     Raises an *note auditing event: ea1. ‘fcntl.ioctl’ with arguments
     ‘fd’, ‘request’, ‘arg’.

 -- 函数: fcntl.flock (fd, operation)

     Perform the lock operation `operation' on file descriptor `fd'
     (file objects providing a *note fileno(): 1f19. method are accepted
     as well).  See the Unix manual ‘flock(2)’ for details.  (On some
     systems, this function is emulated using ‘fcntl()’.)

     If the ‘flock()’ fails, an *note OSError: 1d4. exception is raised.

     Raises an *note auditing event: ea1. ‘fcntl.flock’ with arguments
     ‘fd’, ‘operation’.

 -- 函数: fcntl.lockf (fd, cmd, len=0, start=0, whence=0)

     This is essentially a wrapper around the *note fcntl(): 26a9.
     locking calls.  `fd' is the file descriptor (file objects providing
     a *note fileno(): 1f19. method are accepted as well) of the file to
     lock or unlock, and `cmd' is one of the following values:

        * ‘LOCK_UN’ – unlock

        * ‘LOCK_SH’ – acquire a shared lock

        * ‘LOCK_EX’ – acquire an exclusive lock

     When `cmd' is ‘LOCK_SH’ or ‘LOCK_EX’, it can also be bitwise ORed
     with ‘LOCK_NB’ to avoid blocking on lock acquisition.  If ‘LOCK_NB’
     is used and the lock cannot be acquired, an *note OSError: 1d4.
     will be raised and the exception will have an `errno' attribute set
     to ‘EACCES’ or ‘EAGAIN’ (depending on the operating system; for
     portability, check for both values).  On at least some systems,
     ‘LOCK_EX’ can only be used if the file descriptor refers to a file
     opened for writing.

     `len' is the number of bytes to lock, `start' is the byte offset at
     which the lock starts, relative to `whence', and `whence' is as
     with *note io.IOBase.seek(): 1da7, specifically:

        * ‘0’ – relative to the start of the file (*note os.SEEK_SET:
          d9c.)

        * ‘1’ – relative to the current buffer position (*note
          os.SEEK_CUR: d9d.)

        * ‘2’ – relative to the end of the file (*note os.SEEK_END:
          d9e.)

     The default for `start' is 0, which means to start at the beginning
     of the file.  The default for `len' is 0 which means to lock to the
     end of the file.  The default for `whence' is also 0.

     Raises an *note auditing event: ea1. ‘fcntl.lockf’ with arguments
     ‘fd’, ‘cmd’, ‘len’, ‘start’, ‘whence’.

Examples (all on a SVR4 compliant system):

     import struct, fcntl, os

     f = open(...)
     rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NDELAY)

     lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
     rv = fcntl.fcntl(f, fcntl.F_SETLKW, lockdata)

Note that in the first example the return value variable `rv' will hold
an integer value; in the second example it will hold a *note bytes: 33a.
object.  The structure lay-out for the `lockdata' variable is system
dependent — therefore using the *note flock(): 34d7. call may be better.

参见
....

模块 *note os: c5.

     If the locking flags *note O_SHLOCK: d9f. and *note O_EXLOCK: da0.
     are present in the *note os: c5. module (on BSD only), the *note
     os.open(): 66e. function provides an alternative to the *note
     lockf(): d5a. and *note flock(): 34d7. functions.


File: python.info,  Node: pipes --- 终端管道接口,  Next: resource --- Resource usage information,  Prev: fcntl --- The fcntl and ioctl system calls,  Up: Unix 专有服务

5.35.10 ‘pipes’ — 终端管道接口
------------------------------

`源代码：' Lib/pipes.py(1)

__________________________________________________________________

*note pipes: cd. 定义了一个类用来抽象 `pipeline' 的概念 — 将数据从一个文
件转到另一文件的转换器序列。

由于模块使用了 ‘/bin/sh’ 命令行，因此要求有 POSIX 或兼容 *note
os.system(): dc9. 和 *note os.popen(): 2aa. 的终端程序。

*note pipes: cd. 模块定义了以下的类:

 -- 类: pipes.Template

     对管道的抽象。

示例:

     >>> import pipes
     >>> t = pipes.Template()
     >>> t.append('tr a-z A-Z', '--')
     >>> f = t.open('pipefile', 'w')
     >>> f.write('hello world')
     >>> f.close()
     >>> open('pipefile').read()
     'HELLO WORLD'

* Menu:

* 模板对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/pipes.py


File: python.info,  Node: 模板对象,  Up: pipes --- 终端管道接口

5.35.10.1 模板对象
..................

模板对象有以下方法:

 -- 方法: Template.reset ()

     将一个管道模板恢复为初始状态。

 -- 方法: Template.clone ()

     返回一个新的等价的管道模板。

 -- 方法: Template.debug (flag)

     如果 `flag' 为真值，则启用调试。 否则禁用调试。 当启用调试时，要执
     行的命令会被打印出来，并且会给予终端 ‘set -x’ 命令以输出更详细的信
     息。

 -- 方法: Template.append (cmd, kind)

     在末尾添加一个新的动作。 `cmd' 变量必须为一个有效的 bourne 终端命令
     。 `kind' 变量由两个字母组成。

     第一个字母可以为 ‘'-'’ (这表示命令将读取其标准输入), ‘'f'’ (这表示
     命令将读取在命令行中给定的文件) 或 ‘'.'’ (这表示命令将不读取输入，
     因而必须放在前面。)

     类似地，第二个字母可以为 ‘'-'’ (这表示命令将写入到标准输出), ‘'f'’
     (这表示命令将写入在命令行中给定的文件) 或 ‘'.'’ (这表示命令将不执行
     写入，因而必须放在末尾。)

 -- 方法: Template.prepend (cmd, kind)

     在开头添加一个新的动作。 请参阅 *note append(): 3a43. 获取相应参数
     的说明。

 -- 方法: Template.open (file, mode)

     返回一个文件类对象，打开到 `file'，但是将从管道读取或写入。 请注意
     只能给出 ‘'r'’, ‘'w'’ 中的一个。

 -- 方法: Template.copy (infile, outfile)

     通过管道将 `infile' 拷贝到 `outfile'。


File: python.info,  Node: resource --- Resource usage information,  Next: nis --- Sun 的 NIS 黄页 接口,  Prev: pipes --- 终端管道接口,  Up: Unix 专有服务

5.35.11 ‘resource’ — Resource usage information
-----------------------------------------------

__________________________________________________________________

This module provides basic mechanisms for measuring and controlling
system resources utilized by a program.

Symbolic constants are used to specify particular system resources and
to request usage information about either the current process or its
children.

An *note OSError: 1d4. is raised on syscall failure.

 -- 例外: resource.error

     一个被弃用的 *note OSError: 1d4. 的别名。

     在 3.3 版更改: 根据 PEP 3151(1)，这个类是 *note OSError: 1d4. 的别
     名。

* Menu:

* Resource Limits::
* Resource Usage::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3151


File: python.info,  Node: Resource Limits,  Next: Resource Usage,  Up: resource --- Resource usage information

5.35.11.1 Resource Limits
.........................

Resources usage can be limited using the *note setrlimit(): 34b3.
function described below.  Each resource is controlled by a pair of
limits: a soft limit and a hard limit.  The soft limit is the current
limit, and may be lowered or raised by a process over time.  The soft
limit can never exceed the hard limit.  The hard limit can be lowered to
any value greater than the soft limit, but not raised.  (Only processes
with the effective UID of the super-user can raise a hard limit.)

The specific resources that can be limited are system dependent.  They
are described in the ‘getrlimit(2)’ man page.  The resources listed
below are supported when the underlying operating system supports them;
resources which cannot be checked or controlled by the operating system
are not defined in this module for those platforms.

 -- 数据: resource.RLIM_INFINITY

     Constant used to represent the limit for an unlimited resource.

 -- 函数: resource.getrlimit (resource)

     Returns a tuple ‘(soft, hard)’ with the current soft and hard
     limits of `resource'.  Raises *note ValueError: 1fc. if an invalid
     resource is specified, or *note error: 3a49. if the underlying
     system call fails unexpectedly.

 -- 函数: resource.setrlimit (resource, limits)

     Sets new limits of consumption of `resource'.  The `limits'
     argument must be a tuple ‘(soft, hard)’ of two integers describing
     the new limits.  A value of *note RLIM_INFINITY: 3a4b. can be used
     to request a limit that is unlimited.

     Raises *note ValueError: 1fc. if an invalid resource is specified,
     if the new soft limit exceeds the hard limit, or if a process tries
     to raise its hard limit.  Specifying a limit of *note
     RLIM_INFINITY: 3a4b. when the hard or system limit for that
     resource is not unlimited will result in a *note ValueError: 1fc.
     A process with the effective UID of super-user can request any
     valid limit value, including unlimited, but *note ValueError: 1fc.
     will still be raised if the requested limit exceeds the system
     imposed limit.

     ‘setrlimit’ may also raise *note error: 3a49. if the underlying
     system call fails.

     VxWorks only supports setting *note RLIMIT_NOFILE: 3a4d.

     Raises an *note auditing event: ea1. ‘resource.setrlimit’ with
     arguments ‘resource’, ‘limits’.

 -- 函数: resource.prlimit (pid, resource[, limits])

     Combines *note setrlimit(): 34b3. and *note getrlimit(): 3a4c. in
     one function and supports to get and set the resources limits of an
     arbitrary process.  If `pid' is 0, then the call applies to the
     current process.  `resource' and `limits' have the same meaning as
     in *note setrlimit(): 34b3, except that `limits' is optional.

     When `limits' is not given the function returns the `resource'
     limit of the process `pid'.  When `limits' is given the `resource'
     limit of the process is set and the former resource limit is
     returned.

     Raises *note ProcessLookupError: 9a3. when `pid' can’t be found and
     *note PermissionError: 608. when the user doesn’t have
     ‘CAP_SYS_RESOURCE’ for the process.

     Raises an *note auditing event: ea1. ‘resource.prlimit’ with
     arguments ‘pid’, ‘resource’, ‘limits’.

     *note Availability: 136f.: Linux 2.6.36 or later with glibc 2.13 or
     later.

     3.4 新版功能.

These symbols define resources whose consumption can be controlled using
the *note setrlimit(): 34b3. and *note getrlimit(): 3a4c. functions
described below.  The values of these symbols are exactly the constants
used by C programs.

The Unix man page for ‘getrlimit(2)’ lists the available resources.
Note that not all systems use the same symbol or same value to denote
the same resource.  This module does not attempt to mask platform
differences — symbols not defined for a platform will not be available
from this module on that platform.

 -- 数据: resource.RLIMIT_CORE

     The maximum size (in bytes) of a core file that the current process
     can create.  This may result in the creation of a partial core file
     if a larger core would be required to contain the entire process
     image.

 -- 数据: resource.RLIMIT_CPU

     The maximum amount of processor time (in seconds) that a process
     can use.  If this limit is exceeded, a ‘SIGXCPU’ signal is sent to
     the process.  (See the *note signal: eb. module documentation for
     information about how to catch this signal and do something useful,
     e.g.  flush open files to disk.)

 -- 数据: resource.RLIMIT_FSIZE

     The maximum size of a file which the process may create.

 -- 数据: resource.RLIMIT_DATA

     The maximum size (in bytes) of the process’s heap.

 -- 数据: resource.RLIMIT_STACK

     The maximum size (in bytes) of the call stack for the current
     process.  This only affects the stack of the main thread in a
     multi-threaded process.

 -- 数据: resource.RLIMIT_RSS

     The maximum resident set size that should be made available to the
     process.

 -- 数据: resource.RLIMIT_NPROC

     The maximum number of processes the current process may create.

 -- 数据: resource.RLIMIT_NOFILE

     The maximum number of open file descriptors for the current
     process.

 -- 数据: resource.RLIMIT_OFILE

     The BSD name for *note RLIMIT_NOFILE: 3a4d.

 -- 数据: resource.RLIMIT_MEMLOCK

     The maximum address space which may be locked in memory.

 -- 数据: resource.RLIMIT_VMEM

     The largest area of mapped memory which the process may occupy.

 -- 数据: resource.RLIMIT_AS

     The maximum area (in bytes) of address space which may be taken by
     the process.

 -- 数据: resource.RLIMIT_MSGQUEUE

     The number of bytes that can be allocated for POSIX message queues.

     *note Availability: 136f.: Linux 2.6.8 or later.

     3.4 新版功能.

 -- 数据: resource.RLIMIT_NICE

     The ceiling for the process’s nice level (calculated as 20 -
     rlim_cur).

     *note Availability: 136f.: Linux 2.6.12 or later.

     3.4 新版功能.

 -- 数据: resource.RLIMIT_RTPRIO

     The ceiling of the real-time priority.

     *note Availability: 136f.: Linux 2.6.12 or later.

     3.4 新版功能.

 -- 数据: resource.RLIMIT_RTTIME

     The time limit (in microseconds) on CPU time that a process can
     spend under real-time scheduling without making a blocking syscall.

     *note Availability: 136f.: Linux 2.6.25 or later.

     3.4 新版功能.

 -- 数据: resource.RLIMIT_SIGPENDING

     The number of signals which the process may queue.

     *note Availability: 136f.: Linux 2.6.8 or later.

     3.4 新版功能.

 -- 数据: resource.RLIMIT_SBSIZE

     The maximum size (in bytes) of socket buffer usage for this user.
     This limits the amount of network memory, and hence the amount of
     mbufs, that this user may hold at any time.

     *note Availability: 136f.: FreeBSD 9 or later.

     3.4 新版功能.

 -- 数据: resource.RLIMIT_SWAP

     The maximum size (in bytes) of the swap space that may be reserved
     or used by all of this user id’s processes.  This limit is enforced
     only if bit 1 of the vm.overcommit sysctl is set.  Please see
     tuning(7)(1) for a complete description of this sysctl.

     *note Availability: 136f.: FreeBSD 9 or later.

     3.4 新版功能.

 -- 数据: resource.RLIMIT_NPTS

     The maximum number of pseudo-terminals created by this user id.

     *note Availability: 136f.: FreeBSD 9 or later.

     3.4 新版功能.

   ---------- Footnotes ----------

   (1) https://www.freebsd.org/cgi/man.cgi?query=tuning&sektion=7


File: python.info,  Node: Resource Usage,  Prev: Resource Limits,  Up: resource --- Resource usage information

5.35.11.2 Resource Usage
........................

These functions are used to retrieve resource usage information:

 -- 函数: resource.getrusage (who)

     This function returns an object that describes the resources
     consumed by either the current process or its children, as
     specified by the `who' parameter.  The `who' parameter should be
     specified using one of the ‘RUSAGE_*’ constants described below.

     一个简单的示例：

          from resource import *
          import time

          # a non CPU-bound task
          time.sleep(3)
          print(getrusage(RUSAGE_SELF))

          # a CPU-bound task
          for i in range(10 ** 8):
             _ = 1 + 1
          print(getrusage(RUSAGE_SELF))

     The fields of the return value each describe how a particular
     system resource has been used, e.g.  amount of time spent running
     is user mode or number of times the process was swapped out of main
     memory.  Some values are dependent on the clock tick internal, e.g.
     the amount of memory the process is using.

     For backward compatibility, the return value is also accessible as
     a tuple of 16 elements.

     The fields ‘ru_utime’ and ‘ru_stime’ of the return value are
     floating point values representing the amount of time spent
     executing in user mode and the amount of time spent executing in
     system mode, respectively.  The remaining values are integers.
     Consult the ‘getrusage(2)’ man page for detailed information about
     these values.  A brief summary is presented here:

     索引         域                        Resource
                                            
     -----------------------------------------------------------------------------------
                                            
     ‘0’          ‘ru_utime’                time in user mode (float seconds)
                                            
                                            
     ‘1’          ‘ru_stime’                time in system mode (float seconds)
                                            
                                            
     ‘2’          ‘ru_maxrss’               maximum resident set size
                                            
                                            
     ‘3’          ‘ru_ixrss’                shared memory size
                                            
                                            
     ‘4’          ‘ru_idrss’                unshared memory size
                                            
                                            
     ‘5’          ‘ru_isrss’                unshared stack size
                                            
                                            
     ‘6’          ‘ru_minflt’               page faults not requiring I/O
                                            
                                            
     ‘7’          ‘ru_majflt’               page faults requiring I/O
                                            
                                            
     ‘8’          ‘ru_nswap’                number of swap outs
                                            
                                            
     ‘9’          ‘ru_inblock’              block input operations
                                            
                                            
     ‘10’         ‘ru_oublock’              block output operations
                                            
                                            
     ‘11’         ‘ru_msgsnd’               messages sent
                                            
                                            
     ‘12’         ‘ru_msgrcv’               messages received
                                            
                                            
     ‘13’         ‘ru_nsignals’             signals received
                                            
                                            
     ‘14’         ‘ru_nvcsw’                voluntary context switches
                                            
                                            
     ‘15’         ‘ru_nivcsw’               involuntary context switches
                                            

     This function will raise a *note ValueError: 1fc. if an invalid
     `who' parameter is specified.  It may also raise *note error: 3a49.
     exception in unusual circumstances.

 -- 函数: resource.getpagesize ()

     Returns the number of bytes in a system page.  (This need not be
     the same as the hardware page size.)

The following ‘RUSAGE_*’ symbols are passed to the *note getrusage():
da1. function to specify which processes information should be provided
for.

 -- 数据: resource.RUSAGE_SELF

     Pass to *note getrusage(): da1. to request resources consumed by
     the calling process, which is the sum of resources used by all
     threads in the process.

 -- 数据: resource.RUSAGE_CHILDREN

     Pass to *note getrusage(): da1. to request resources consumed by
     child processes of the calling process which have been terminated
     and waited for.

 -- 数据: resource.RUSAGE_BOTH

     Pass to *note getrusage(): da1. to request resources consumed by
     both the current process and child processes.  May not be available
     on all systems.

 -- 数据: resource.RUSAGE_THREAD

     Pass to *note getrusage(): da1. to request resources consumed by
     the current thread.  May not be available on all systems.

     3.2 新版功能.


File: python.info,  Node: nis --- Sun 的 NIS 黄页 接口,  Next: Unix syslog 库例程,  Prev: resource --- Resource usage information,  Up: Unix 专有服务

5.35.12 ‘nis’ — Sun 的 NIS (黄页) 接口
--------------------------------------

__________________________________________________________________

*note nis: c0. 模块提供了对 NIS 库的轻量级包装，适用于多个主机的集中管理
。

因为 NIS 仅存在于 Unix 系统，此模块仅在 Unix 上可用。

*note nis: c0. 模块定义了以下函数：

 -- 函数: nis.match (key, mapname, domain=default_domain)

     返回 `key' 在映射 `mapname' 中的匹配结果，如无结果则会引发错误
     (*note nis.error: 3a60.)。 两个参数都应为字符串，`key' 定长 8 个比
     特。 返回值为任意字节数组（可包含 ‘NULL’ 和其他特殊值）。

     请注意如果 `mapname' 是另一名称的别名则会先检查别名。

     `domain' 参数可允许重载用于查找的 NIS 域。 如果未指定，则会在默认
     NIS 域中查找。

 -- 函数: nis.cat (mapname, domain=default_domain)

     返回一个字典，其元素为 `key' 到 `value' 的映射使得 ‘match(key,
     mapname)==value’。 请注意字典的键和值均为任意字节数组。

     请注意如果 `mapname' 是另一名称的别名则会先检查别名。

     `domain' 参数可允许重载用于查找的 NIS 域。 如果未指定，则会在默认
     NIS 域中查找。

 -- 函数: nis.maps (domain=default_domain)

     返回全部可用映射的列表。

     `domain' 参数可允许重载用于查找的 NIS 域。 如果未指定，则会在默认
     NIS 域中查找。

 -- 函数: nis.get_default_domain ()

     返回系统默认的 NIS 域。

*note nis: c0. 模块定义了以下异常：

 -- 例外: nis.error

     当 NIS 函数返回一个错误码时引发的异常。


File: python.info,  Node: Unix syslog 库例程,  Prev: nis --- Sun 的 NIS 黄页 接口,  Up: Unix 专有服务

5.35.13 Unix syslog 库例程
--------------------------

__________________________________________________________________

此模块提供一个接口到Unix ‘syslog’ 日常库. 参考 Unix 手册页关于 ‘syslog’
设施的详细描述.

此模块包装了系统的 ‘syslog’ 例程族。 一个能与 syslog 服务器对话的纯
Python 库则以 *note logging.handlers: ad. 模块中 ‘SysLogHandler’ 类的形
式提供。

这个模块定义了以下函数：

 -- 函数: syslog.syslog (message)

 -- 函数: syslog.syslog (priority, message)

     将字符串 `message' 发送到系统日志记录器。 如有必要会添加末尾换行符
     。 每条消息都带有一个由 `facility' 和 `level' 组成的优先级标价签。
     可选的 `priority' 参数默认值为 ‘LOG_INFO’，它确定消息的优先级。 如
     果未在 `priority' 中使用逻辑或 (‘LOG_INFO | LOG_USER’) 对 facility
     进行编码，则会使用在 *note openlog(): 34dc. 调用中所给定的值。

     如果 *note openlog(): 34dc. 未在对 *note syslog(): 100. 的调用之前
     被调用，则将不带参数地调用 ‘openlog()’。

     引发 *note 审计事件: ea1. ‘syslog.syslog’ 使用参数 ‘priority’,
     ‘message’.

 -- 函数: syslog.openlog ([ident[, logoption[, facility]]])

     后续 *note syslog(): 100. 调用的日志选项可以通过调用 *note
     openlog(): 34dc. 来设置。 如果日志当前未打开则 *note syslog(): 100.
     将不带参数地调用 *note openlog(): 34dc.。

     可选的 `ident' 关键字参数是在每条消息前添加的字符串，默认为
     ‘sys.argv[0]’ 去除打头的路径部分。 可选的 `logoption' 关键字参数（
     默认为 0）是一个位字段 – 请参见下文了解可能的组合值。 可选的
     `facility' 关键字参数 (默认为 ‘LOG_USER’) 为没有显式编码 facility 的
     消息设置默认的 facility。

     引发 *note 审计事件: ea1. ‘syslog.openlog’ 使用参数 ‘ident’,
     ‘logoption’, ‘facility’.

     在 3.2 版更改: 在之前的版本中，不允许关键字参数，并且要求必须有
     `ident'。 `ident' 的默认值依赖于系统库，它往往为 ‘python’ 而不是
     Python 程序文件的实际名称。

 -- 函数: syslog.closelog ()

     重置日志模块值并且调用系统库 ‘closelog()’.

     这使得此模块在初始导入时行为固定。 例如，*note openlog(): 34dc. 将
     在首次调用 *note syslog(): 100. 时被调用（如果 *note openlog():
     34dc. 还未被调用过），并且 `ident' 和其他 *note openlog(): 34dc. 形
     参会被重置为默认值。

     引发一个 *note 审计事件: ea1. ‘syslog.closelog’ 不附带任何参数。

 -- 函数: syslog.setlogmask (maskpri)

     将优先级掩码设为 `maskpri' 并返回之前的掩码值。 调用 *note
     syslog(): 100. 并附带未在 `maskpri' 中设置的优先级将会被忽略。 默认
     设置为记录所有优先级。 函数 ‘LOG_MASK(pri)’ 可计算单个优先级 `pri'
     的掩码。 函数 ‘LOG_UPTO(pri)’ 可计算包括 `pri' 在内的所有优先级的掩
     码。

     引发一个 *note 审计事件: ea1. ‘syslog.setlogmask’ 附带参数
     ‘maskpri’。

此莫款定义了一下常量:

优先级级别 (高到低):

     ‘LOG_EMERG’, ‘LOG_ALERT’, ‘LOG_CRIT’, ‘LOG_ERR’, ‘LOG_WARNING’,
     ‘LOG_NOTICE’, ‘LOG_INFO’, ‘LOG_DEBUG’.

设施:

     ‘LOG_KERN’, ‘LOG_USER’, ‘LOG_MAIL’, ‘LOG_DAEMON’, ‘LOG_AUTH’,
     ‘LOG_LPR’, ‘LOG_NEWS’, ‘LOG_UUCP’, ‘LOG_CRON’, ‘LOG_SYSLOG’,
     ‘LOG_LOCAL0’ to ‘LOG_LOCAL7’，如果 ‘<syslog.h>’ 中有定义则还有
     ‘LOG_AUTHPRIV’。

日志选项:

     ‘LOG_PID’, ‘LOG_CONS’, ‘LOG_NDELAY’，如果 ‘<syslog.h>’ 中有定义则还
     有 ‘LOG_ODELAY’, ‘LOG_NOWAIT’ 以及 ‘LOG_PERROR’。

* Menu:

* 例子: 例子<32>.


File: python.info,  Node: 例子<32>,  Up: Unix syslog 库例程

5.35.13.1 例子
..............

* Menu:

* 简单示例::


File: python.info,  Node: 简单示例,  Up: 例子<32>

5.35.13.2 简单示例
..................

一个简单的示例集:

     import syslog

     syslog.syslog('Processing started')
     if error:
         syslog.syslog(syslog.LOG_ERR, 'Processing started')

一个设置多种日志选项的示例，其中有在日志消息中包含进程 ID，以及将消息写
入用于邮件日志记录的目标设施等:

     syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL)
     syslog.syslog('E-mail processing initiated...')


File: python.info,  Node: 被取代的模块,  Next: 未创建文档的模块,  Prev: Unix 专有服务,  Up: Python 标准库

5.36 被取代的模块
=================

本章中描述的模块均已弃用，仅保留用于向后兼容。 它们已经被其他模块所取代
。

* Menu:

* optparse: optparse --- 解析器的命令行选项. 解析器的命令行选项
* imp: imp --- Access the import internals. Access the import internals


File: python.info,  Node: optparse --- 解析器的命令行选项,  Next: imp --- Access the import internals,  Up: 被取代的模块

5.36.1 ‘optparse’ — 解析器的命令行选项
--------------------------------------

`源代码：' Lib/optparse.py(1)

3.2 版后已移除: *note optparse: c4. 模块已被弃用并且将不再继续开发；开发
将转至 *note argparse: 6. 模块进行。

__________________________________________________________________

*note optparse: c4. 是一个相比原有 *note getopt: 87. 模块更为方便、灵活
和强大的命令行选项解析库。 *note optparse: c4. 使用更为显明的命令行解析
风格：创建一个 *note OptionParser: 3a6c. 的实例，向其中填充选项，然后解
析命令行。 *note optparse: c4. 允许用户以传统的 GNU/POSIX 语法来指定选项
，并为你生成额外的用法和帮助消息。

下面是在一个简单脚本中使用 *note optparse: c4. 的示例:

     from optparse import OptionParser
     ...
     parser = OptionParser()
     parser.add_option("-f", "--file", dest="filename",
                       help="write report to FILE", metavar="FILE")
     parser.add_option("-q", "--quiet",
                       action="store_false", dest="verbose", default=True,
                       help="don't print status messages to stdout")

     (options, args) = parser.parse_args()

With these few lines of code, users of your script can now do the "usual
thing" on the command-line, for example:

     <yourscript> --file=outfile -q

As it parses the command line, *note optparse: c4. sets attributes of
the ‘options’ object returned by ‘parse_args()’ based on user-supplied
command-line values.  When ‘parse_args()’ returns from parsing this
command line, ‘options.filename’ will be ‘"outfile"’ and
‘options.verbose’ will be ‘False’.  *note optparse: c4. supports both
long and short options, allows short options to be merged together, and
allows options to be associated with their arguments in a variety of
ways.  Thus, the following command lines are all equivalent to the above
example:

     <yourscript> -f outfile --quiet
     <yourscript> --quiet --file outfile
     <yourscript> -q -foutfile
     <yourscript> -qfoutfile

Additionally, users can run one of the following

     <yourscript> -h
     <yourscript> --help

and *note optparse: c4. will print out a brief summary of your script’s
options:

     Usage: <yourscript> [options]

     Options:
       -h, --help            show this help message and exit
       -f FILE, --file=FILE  write report to FILE
       -q, --quiet           don't print status messages to stdout

where the value of `yourscript' is determined at runtime (normally from
‘sys.argv[0]’).

* Menu:

* 背景::
* 教程: 教程<2>.
* 参考指南::
* Option Callbacks::
* Extending optparse::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/optparse.py


File: python.info,  Node: 背景,  Next: 教程<2>,  Up: optparse --- 解析器的命令行选项

5.36.1.1 背景
.............

*note optparse: c4. was explicitly designed to encourage the creation of
programs with straightforward, conventional command-line interfaces.  To
that end, it supports only the most common command-line syntax and
semantics conventionally used under Unix.  If you are unfamiliar with
these conventions, read this section to acquaint yourself with them.

* Menu:

* 术语::
* What are options for?::
* 位置位置::


File: python.info,  Node: 术语,  Next: What are options for?,  Up: 背景

5.36.1.2 术语
.............

argument – 参数

     a string entered on the command-line, and passed by the shell to
     ‘execl()’ or ‘execv()’.  In Python, arguments are elements of
     ‘sys.argv[1:]’ (‘sys.argv[0]’ is the name of the program being
     executed).  Unix shells also use the term "word".

     It is occasionally desirable to substitute an argument list other
     than ‘sys.argv[1:]’, so you should read "argument" as "an element
     of ‘sys.argv[1:]’, or of some other list provided as a substitute
     for ‘sys.argv[1:]’".

选项

     an argument used to supply extra information to guide or customize
     the execution of a program.  There are many different syntaxes for
     options; the traditional Unix syntax is a hyphen ("-") followed by
     a single letter, e.g.  ‘-x’ or ‘-F’.  Also, traditional Unix syntax
     allows multiple options to be merged into a single argument, e.g.
     ‘-x -F’ is equivalent to ‘-xF’.  The GNU project introduced ‘--’
     followed by a series of hyphen-separated words, e.g.  ‘--file’ or
     ‘--dry-run’.  These are the only two option syntaxes provided by
     *note optparse: c4.

     Some other option syntaxes that the world has seen include:

        * a hyphen followed by a few letters, e.g.  ‘-pf’ (this is `not'
          the same as multiple options merged into a single argument)

        * a hyphen followed by a whole word, e.g.  ‘-file’ (this is
          technically equivalent to the previous syntax, but they aren’t
          usually seen in the same program)

        * a plus sign followed by a single letter, or a few letters, or
          a word, e.g.  ‘+f’, ‘+rgb’

        * a slash followed by a letter, or a few letters, or a word,
          e.g.  ‘/f’, ‘/file’

     These option syntaxes are not supported by *note optparse: c4, and
     they never will be.  This is deliberate: the first three are
     non-standard on any environment, and the last only makes sense if
     you’re exclusively targeting VMS, MS-DOS, and/or Windows.

可选参数:

     an argument that follows an option, is closely associated with that
     option, and is consumed from the argument list when that option is.
     With *note optparse: c4, option arguments may either be in a
     separate argument from their option:

          -f foo
          --file foo

     or included in the same argument:

          -ffoo
          --file=foo

     Typically, a given option either takes an argument or it doesn’t.
     Lots of people want an "optional option arguments" feature, meaning
     that some options will take an argument if they see it, and won’t
     if they don’t.  This is somewhat controversial, because it makes
     parsing ambiguous: if ‘-a’ takes an optional argument and ‘-b’ is
     another option entirely, how do we interpret ‘-ab’?  Because of
     this ambiguity, *note optparse: c4. does not support this feature.

positional argument – 位置参数

     something leftover in the argument list after options have been
     parsed, i.e.  after options and their arguments have been parsed
     and removed from the argument list.

必选选项

     an option that must be supplied on the command-line; note that the
     phrase "required option" is self-contradictory in English.  *note
     optparse: c4. doesn’t prevent you from implementing required
     options, but doesn’t give you much help at it either.

For example, consider this hypothetical command-line:

     prog -v --report report.txt foo bar

‘-v’ and ‘--report’ are both options.  Assuming that ‘--report’ takes
one argument, ‘report.txt’ is an option argument.  ‘foo’ and ‘bar’ are
positional arguments.


File: python.info,  Node: What are options for?,  Next: 位置位置,  Prev: 术语,  Up: 背景

5.36.1.3 What are options for?
..............................

Options are used to provide extra information to tune or customize the
execution of a program.  In case it wasn’t clear, options are usually
`optional'.  A program should be able to run just fine with no options
whatsoever.  (Pick a random program from the Unix or GNU toolsets.  Can
it run without any options at all and still make sense?  The main
exceptions are ‘find’, ‘tar’, and ‘dd’—all of which are mutant oddballs
that have been rightly criticized for their non-standard syntax and
confusing interfaces.)

Lots of people want their programs to have "required options".  Think
about it.  If it’s required, then it’s `not optional'!  If there is a
piece of information that your program absolutely requires in order to
run successfully, that’s what positional arguments are for.

As an example of good command-line interface design, consider the humble
‘cp’ utility, for copying files.  It doesn’t make much sense to try to
copy files without supplying a destination and at least one source.
Hence, ‘cp’ fails if you run it with no arguments.  However, it has a
flexible, useful syntax that does not require any options at all:

     cp SOURCE DEST
     cp SOURCE ... DEST-DIR

You can get pretty far with just that.  Most ‘cp’ implementations
provide a bunch of options to tweak exactly how the files are copied:
you can preserve mode and modification time, avoid following symlinks,
ask before clobbering existing files, etc.  But none of this distracts
from the core mission of ‘cp’, which is to copy either one file to
another, or several files to another directory.


File: python.info,  Node: 位置位置,  Prev: What are options for?,  Up: 背景

5.36.1.4 位置位置
.................

Positional arguments are for those pieces of information that your
program absolutely, positively requires to run.

A good user interface should have as few absolute requirements as
possible.  If your program requires 17 distinct pieces of information in
order to run successfully, it doesn’t much matter `how' you get that
information from the user—most people will give up and walk away before
they successfully run the program.  This applies whether the user
interface is a command-line, a configuration file, or a GUI: if you make
that many demands on your users, most of them will simply give up.

In short, try to minimize the amount of information that users are
absolutely required to supply—use sensible defaults whenever possible.
Of course, you also want to make your programs reasonably flexible.
That’s what options are for.  Again, it doesn’t matter if they are
entries in a config file, widgets in the "Preferences" dialog of a GUI,
or command-line options—the more options you implement, the more
flexible your program is, and the more complicated its implementation
becomes.  Too much flexibility has drawbacks as well, of course; too
many options can overwhelm users and make your code much harder to
maintain.


File: python.info,  Node: 教程<2>,  Next: 参考指南,  Prev: 背景,  Up: optparse --- 解析器的命令行选项

5.36.1.5 教程
.............

While *note optparse: c4. is quite flexible and powerful, it’s also
straightforward to use in most cases.  This section covers the code
patterns that are common to any *note optparse: c4.-based program.

First, you need to import the OptionParser class; then, early in the
main program, create an OptionParser instance:

     from optparse import OptionParser
     ...
     parser = OptionParser()

Then you can start defining options.  The basic syntax is:

     parser.add_option(opt_str, ...,
                       attr=value, ...)

Each option has one or more option strings, such as ‘-f’ or ‘--file’,
and several option attributes that tell *note optparse: c4. what to
expect and what to do when it encounters that option on the command
line.

Typically, each option will have one short option string and one long
option string, e.g.:

     parser.add_option("-f", "--file", ...)

You’re free to define as many short option strings and as many long
option strings as you like (including zero), as long as there is at
least one option string overall.

The option strings passed to *note OptionParser.add_option(): 2083. are
effectively labels for the option defined by that call.  For brevity, we
will frequently refer to `encountering an option' on the command line;
in reality, *note optparse: c4. encounters `option strings' and looks up
options from them.

Once all of your options are defined, instruct *note optparse: c4. to
parse your program’s command line:

     (options, args) = parser.parse_args()

(If you like, you can pass a custom argument list to ‘parse_args()’, but
that’s rarely necessary: by default it uses ‘sys.argv[1:]’.)

‘parse_args()’ 返回两个值：

   * ‘options’, an object containing values for all of your options—e.g.
     if ‘--file’ takes a single string argument, then ‘options.file’
     will be the filename supplied by the user, or ‘None’ if the user
     did not supply that option

   * ‘args’, the list of positional arguments leftover after parsing
     options

This tutorial section only covers the four most important option
attributes: *note action: 3a77, *note type: 3a78, *note dest: 3a79.
(destination), and *note help: 3a7a.  Of these, *note action: 3a77. is
the most fundamental.

* Menu:

* Understanding option actions::
* The store action::
* Handling boolean (flag) options: Handling boolean flag options.
* Other actions::
* 默认值: 默认值<2>.
* Generating help::
* Printing a version string::
* How optparse handles errors::
* Putting it all together::


File: python.info,  Node: Understanding option actions,  Next: The store action,  Up: 教程<2>

5.36.1.6 Understanding option actions
.....................................

Actions tell *note optparse: c4. what to do when it encounters an option
on the command line.  There is a fixed set of actions hard-coded into
*note optparse: c4.; adding new actions is an advanced topic covered in
section *note Extending optparse: 3a7d.  Most actions tell *note
optparse: c4. to store a value in some variable—for example, take a
string from the command line and store it in an attribute of ‘options’.

If you don’t specify an option action, *note optparse: c4. defaults to
‘store’.


File: python.info,  Node: The store action,  Next: Handling boolean flag options,  Prev: Understanding option actions,  Up: 教程<2>

5.36.1.7 The store action
.........................

The most common option action is ‘store’, which tells *note optparse:
c4. to take the next argument (or the remainder of the current
argument), ensure that it is of the correct type, and store it to your
chosen destination.

例如

     parser.add_option("-f", "--file",
                       action="store", type="string", dest="filename")

Now let’s make up a fake command line and ask *note optparse: c4. to
parse it:

     args = ["-f", "foo.txt"]
     (options, args) = parser.parse_args(args)

When *note optparse: c4. sees the option string ‘-f’, it consumes the
next argument, ‘foo.txt’, and stores it in ‘options.filename’.  So,
after this call to ‘parse_args()’, ‘options.filename’ is ‘"foo.txt"’.

Some other option types supported by *note optparse: c4. are ‘int’ and
‘float’.  Here’s an option that expects an integer argument:

     parser.add_option("-n", type="int", dest="num")

Note that this option has no long option string, which is perfectly
acceptable.  Also, there’s no explicit action, since the default is
‘store’.

Let’s parse another fake command-line.  This time, we’ll jam the option
argument right up against the option: since ‘-n42’ (one argument) is
equivalent to ‘-n 42’ (two arguments), the code

     (options, args) = parser.parse_args(["-n42"])
     print(options.num)

will print ‘42’.

If you don’t specify a type, *note optparse: c4. assumes ‘string’.
Combined with the fact that the default action is ‘store’, that means
our first example can be a lot shorter:

     parser.add_option("-f", "--file", dest="filename")

If you don’t supply a destination, *note optparse: c4. figures out a
sensible default from the option strings: if the first long option
string is ‘--foo-bar’, then the default destination is ‘foo_bar’.  If
there are no long option strings, *note optparse: c4. looks at the first
short option string: the default destination for ‘-f’ is ‘f’.

*note optparse: c4. also includes the built-in ‘complex’ type.  Adding
types is covered in section *note Extending optparse: 3a7d.


File: python.info,  Node: Handling boolean flag options,  Next: Other actions,  Prev: The store action,  Up: 教程<2>

5.36.1.8 Handling boolean (flag) options
........................................

Flag options—set a variable to true or false when a particular option is
seen—are quite common.  *note optparse: c4. supports them with two
separate actions, ‘store_true’ and ‘store_false’.  For example, you
might have a ‘verbose’ flag that is turned on with ‘-v’ and off with
‘-q’:

     parser.add_option("-v", action="store_true", dest="verbose")
     parser.add_option("-q", action="store_false", dest="verbose")

Here we have two different options with the same destination, which is
perfectly OK. (It just means you have to be a bit careful when setting
default values—see below.)

When *note optparse: c4. encounters ‘-v’ on the command line, it sets
‘options.verbose’ to ‘True’; when it encounters ‘-q’, ‘options.verbose’
is set to ‘False’.


File: python.info,  Node: Other actions,  Next: 默认值<2>,  Prev: Handling boolean flag options,  Up: 教程<2>

5.36.1.9 Other actions
......................

Some other actions supported by *note optparse: c4. are:

‘"store_const"’

     store a constant value

‘"append"’

     append this option’s argument to a list

‘"count"’

     increment a counter by one

‘"callback"’

     调用指定函数

These are covered in section *note 参考指南: 3a84, and section *note
Option Callbacks: 3a85.


File: python.info,  Node: 默认值<2>,  Next: Generating help,  Prev: Other actions,  Up: 教程<2>

5.36.1.10 默认值
................

All of the above examples involve setting some variable (the
"destination") when certain command-line options are seen.  What happens
if those options are never seen?  Since we didn’t supply any defaults,
they are all set to ‘None’.  This is usually fine, but sometimes you
want more control.  *note optparse: c4. lets you supply a default value
for each destination, which is assigned before the command line is
parsed.

First, consider the verbose/quiet example.  If we want *note optparse:
c4. to set ‘verbose’ to ‘True’ unless ‘-q’ is seen, then we can do this:

     parser.add_option("-v", action="store_true", dest="verbose", default=True)
     parser.add_option("-q", action="store_false", dest="verbose")

Since default values apply to the `destination' rather than to any
particular option, and these two options happen to have the same
destination, this is exactly equivalent:

     parser.add_option("-v", action="store_true", dest="verbose")
     parser.add_option("-q", action="store_false", dest="verbose", default=True)

考虑一下：

     parser.add_option("-v", action="store_true", dest="verbose", default=False)
     parser.add_option("-q", action="store_false", dest="verbose", default=True)

Again, the default value for ‘verbose’ will be ‘True’: the last default
value supplied for any particular destination is the one that counts.

A clearer way to specify default values is the ‘set_defaults()’ method
of OptionParser, which you can call at any time before calling
‘parse_args()’:

     parser.set_defaults(verbose=True)
     parser.add_option(...)
     (options, args) = parser.parse_args()

As before, the last value specified for a given option destination is
the one that counts.  For clarity, try to use one method or the other of
setting default values, not both.


File: python.info,  Node: Generating help,  Next: Printing a version string,  Prev: 默认值<2>,  Up: 教程<2>

5.36.1.11 Generating help
.........................

*note optparse: c4.’s ability to generate help and usage text
automatically is useful for creating user-friendly command-line
interfaces.  All you have to do is supply a *note help: 3a7a. value for
each option, and optionally a short usage message for your whole
program.  Here’s an OptionParser populated with user-friendly
(documented) options:

     usage = "usage: %prog [options] arg1 arg2"
     parser = OptionParser(usage=usage)
     parser.add_option("-v", "--verbose",
                       action="store_true", dest="verbose", default=True,
                       help="make lots of noise [default]")
     parser.add_option("-q", "--quiet",
                       action="store_false", dest="verbose",
                       help="be vewwy quiet (I'm hunting wabbits)")
     parser.add_option("-f", "--filename",
                       metavar="FILE", help="write output to FILE")
     parser.add_option("-m", "--mode",
                       default="intermediate",
                       help="interaction mode: novice, intermediate, "
                            "or expert [default: %default]")

If *note optparse: c4. encounters either ‘-h’ or ‘--help’ on the
command-line, or if you just call ‘parser.print_help()’, it prints the
following to standard output:

     Usage: <yourscript> [options] arg1 arg2

     Options:
       -h, --help            show this help message and exit
       -v, --verbose         make lots of noise [default]
       -q, --quiet           be vewwy quiet (I'm hunting wabbits)
       -f FILE, --filename=FILE
                             write output to FILE
       -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                             expert [default: intermediate]

(If the help output is triggered by a help option, *note optparse: c4.
exits after printing the help text.)

There’s a lot going on here to help *note optparse: c4. generate the
best possible help message:

   * the script defines its own usage message:

          usage = "usage: %prog [options] arg1 arg2"

     *note optparse: c4. expands ‘%prog’ in the usage string to the name
     of the current program, i.e.  ‘os.path.basename(sys.argv[0])’.  The
     expanded string is then printed before the detailed option help.

     If you don’t supply a usage string, *note optparse: c4. uses a
     bland but sensible default: ‘"Usage: %prog [options]"’, which is
     fine if your script doesn’t take any positional arguments.

   * every option defines a help string, and doesn’t worry about
     line-wrapping—*note optparse: c4. takes care of wrapping lines and
     making the help output look good.

   * options that take a value indicate this fact in their
     automatically-generated help message, e.g.  for the "mode" option:

          -m MODE, --mode=MODE

     Here, "MODE" is called the meta-variable: it stands for the
     argument that the user is expected to supply to ‘-m’/‘--mode’.  By
     default, *note optparse: c4. converts the destination variable name
     to uppercase and uses that for the meta-variable.  Sometimes,
     that’s not what you want—for example, the ‘--filename’ option
     explicitly sets ‘metavar="FILE"’, resulting in this
     automatically-generated option description:

          -f FILE, --filename=FILE

     This is important for more than just saving space, though: the
     manually written help text uses the meta-variable ‘FILE’ to clue
     the user in that there’s a connection between the semi-formal
     syntax ‘-f FILE’ and the informal semantic description "write
     output to FILE". This is a simple but effective way to make your
     help text a lot clearer and more useful for end users.

   * options that have a default value can include ‘%default’ in the
     help string—*note optparse: c4. will replace it with *note str():
     339. of the option’s default value.  If an option has no default
     value (or the default value is ‘None’), ‘%default’ expands to
     ‘none’.

* Menu:

* Grouping Options::


File: python.info,  Node: Grouping Options,  Up: Generating help

5.36.1.12 Grouping Options
..........................

When dealing with many options, it is convenient to group these options
for better help output.  An *note OptionParser: 3a6c. can contain
several option groups, each of which can contain several options.

An option group is obtained using the class *note OptionGroup: 3a8b.:

 -- 类: optparse.OptionGroup (parser, title, description=None)

     where

        * parser is the *note OptionParser: 3a6c. instance the group
          will be inserted in to

        * title is the group title

        * description, optional, is a long description of the group

*note OptionGroup: 3a8b. inherits from ‘OptionContainer’ (like *note
OptionParser: 3a6c.) and so the ‘add_option()’ method can be used to add
an option to the group.

Once all the options are declared, using the *note OptionParser: 3a6c.
method ‘add_option_group()’ the group is added to the previously defined
parser.

Continuing with the parser defined in the previous section, adding an
*note OptionGroup: 3a8b. to a parser is easy:

     group = OptionGroup(parser, "Dangerous Options",
                         "Caution: use these options at your own risk.  "
                         "It is believed that some of them bite.")
     group.add_option("-g", action="store_true", help="Group option.")
     parser.add_option_group(group)

This would result in the following help output:

     Usage: <yourscript> [options] arg1 arg2

     Options:
       -h, --help            show this help message and exit
       -v, --verbose         make lots of noise [default]
       -q, --quiet           be vewwy quiet (I'm hunting wabbits)
       -f FILE, --filename=FILE
                             write output to FILE
       -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                             expert [default: intermediate]

       Dangerous Options:
         Caution: use these options at your own risk.  It is believed that some
         of them bite.

         -g                  Group option.

A bit more complete example might involve using more than one group:
still extending the previous example:

     group = OptionGroup(parser, "Dangerous Options",
                         "Caution: use these options at your own risk.  "
                         "It is believed that some of them bite.")
     group.add_option("-g", action="store_true", help="Group option.")
     parser.add_option_group(group)

     group = OptionGroup(parser, "Debug Options")
     group.add_option("-d", "--debug", action="store_true",
                      help="Print debug information")
     group.add_option("-s", "--sql", action="store_true",
                      help="Print all SQL statements executed")
     group.add_option("-e", action="store_true", help="Print every action done")
     parser.add_option_group(group)

that results in the following output:

     Usage: <yourscript> [options] arg1 arg2

     Options:
       -h, --help            show this help message and exit
       -v, --verbose         make lots of noise [default]
       -q, --quiet           be vewwy quiet (I'm hunting wabbits)
       -f FILE, --filename=FILE
                             write output to FILE
       -m MODE, --mode=MODE  interaction mode: novice, intermediate, or expert
                             [default: intermediate]

       Dangerous Options:
         Caution: use these options at your own risk.  It is believed that some
         of them bite.

         -g                  Group option.

       Debug Options:
         -d, --debug         Print debug information
         -s, --sql           Print all SQL statements executed
         -e                  Print every action done

Another interesting method, in particular when working programmatically
with option groups is:

 -- 方法: OptionParser.get_option_group (opt_str)

     Return the *note OptionGroup: 3a8b. to which the short or long
     option string `opt_str' (e.g.  ‘'-o'’ or ‘'--option'’) belongs.  If
     there’s no such *note OptionGroup: 3a8b, return ‘None’.


File: python.info,  Node: Printing a version string,  Next: How optparse handles errors,  Prev: Generating help,  Up: 教程<2>

5.36.1.13 Printing a version string
...................................

Similar to the brief usage string, *note optparse: c4. can also print a
version string for your program.  You have to supply the string as the
‘version’ argument to OptionParser:

     parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")

‘%prog’ is expanded just like it is in ‘usage’.  Apart from that,
‘version’ can contain anything you like.  When you supply it, *note
optparse: c4. automatically adds a ‘--version’ option to your parser.
If it encounters this option on the command line, it expands your
‘version’ string (by replacing ‘%prog’), prints it to stdout, and exits.

For example, if your script is called ‘/usr/bin/foo’:

     $ /usr/bin/foo --version
     foo 1.0

The following two methods can be used to print and get the ‘version’
string:

 -- 方法: OptionParser.print_version (file=None)

     Print the version message for the current program (‘self.version’)
     to `file' (default stdout).  As with *note print_usage(): 3a90, any
     occurrence of ‘%prog’ in ‘self.version’ is replaced with the name
     of the current program.  Does nothing if ‘self.version’ is empty or
     undefined.

 -- 方法: OptionParser.get_version ()

     Same as *note print_version(): 3a8f. but returns the version string
     instead of printing it.


File: python.info,  Node: How optparse handles errors,  Next: Putting it all together,  Prev: Printing a version string,  Up: 教程<2>

5.36.1.14 How ‘optparse’ handles errors
.......................................

There are two broad classes of errors that *note optparse: c4. has to
worry about: programmer errors and user errors.  Programmer errors are
usually erroneous calls to *note OptionParser.add_option(): 2083, e.g.
invalid option strings, unknown option attributes, missing option
attributes, etc.  These are dealt with in the usual way: raise an
exception (either ‘optparse.OptionError’ or *note TypeError: 193.) and
let the program crash.

Handling user errors is much more important, since they are guaranteed
to happen no matter how stable your code is.  *note optparse: c4. can
automatically detect some user errors, such as bad option arguments
(passing ‘-n 4x’ where ‘-n’ takes an integer argument), missing
arguments (‘-n’ at the end of the command line, where ‘-n’ takes an
argument of any type).  Also, you can call ‘OptionParser.error()’ to
signal an application-defined error condition:

     (options, args) = parser.parse_args()
     ...
     if options.a and options.b:
         parser.error("options -a and -b are mutually exclusive")

In either case, *note optparse: c4. handles the error the same way: it
prints the program’s usage message and an error message to standard
error and exits with error status 2.

Consider the first example above, where the user passes ‘4x’ to an
option that takes an integer:

     $ /usr/bin/foo -n 4x
     Usage: foo [options]

     foo: error: option -n: invalid integer value: '4x'

Or, where the user fails to pass a value at all:

     $ /usr/bin/foo -n
     Usage: foo [options]

     foo: error: -n option requires an argument

*note optparse: c4.-generated error messages take care always to mention
the option involved in the error; be sure to do the same when calling
‘OptionParser.error()’ from your application code.

If *note optparse: c4.’s default error-handling behaviour does not suit
your needs, you’ll need to subclass OptionParser and override its
‘exit()’ and/or ‘error()’ methods.


File: python.info,  Node: Putting it all together,  Prev: How optparse handles errors,  Up: 教程<2>

5.36.1.15 Putting it all together
.................................

Here’s what *note optparse: c4.-based scripts usually look like:

     from optparse import OptionParser
     ...
     def main():
         usage = "usage: %prog [options] arg"
         parser = OptionParser(usage)
         parser.add_option("-f", "--file", dest="filename",
                           help="read data from FILENAME")
         parser.add_option("-v", "--verbose",
                           action="store_true", dest="verbose")
         parser.add_option("-q", "--quiet",
                           action="store_false", dest="verbose")
         ...
         (options, args) = parser.parse_args()
         if len(args) != 1:
             parser.error("incorrect number of arguments")
         if options.verbose:
             print("reading %s..." % options.filename)
         ...

     if __name__ == "__main__":
         main()


File: python.info,  Node: 参考指南,  Next: Option Callbacks,  Prev: 教程<2>,  Up: optparse --- 解析器的命令行选项

5.36.1.16 参考指南
..................

* Menu:

* 创建解析器::
* 填充解析器::
* 定义选项::
* Option attributes::
* Standard option actions::
* Standard option types::
* 解析参数: 解析参数<2>.
* Querying and manipulating your option parser::
* Conflicts between options::
* 清理: 清理<2>.
* Other methods::


File: python.info,  Node: 创建解析器,  Next: 填充解析器,  Up: 参考指南

5.36.1.17 创建解析器
....................

The first step in using *note optparse: c4. is to create an OptionParser
instance.

 -- 类: optparse.OptionParser (...)

     The OptionParser constructor has no required arguments, but a
     number of optional keyword arguments.  You should always pass them
     as keyword arguments, i.e.  do not rely on the order in which the
     arguments are declared.

     ‘usage’ (默认: ‘"%prog [options]"’)

          The usage summary to print when your program is run
          incorrectly or with a help option.  When *note optparse: c4.
          prints the usage string, it expands ‘%prog’ to
          ‘os.path.basename(sys.argv[0])’ (or to ‘prog’ if you passed
          that keyword argument).  To suppress a usage message, pass the
          special value ‘optparse.SUPPRESS_USAGE’.

     ‘option_list’ (默认: ‘[]’)

          A list of Option objects to populate the parser with.  The
          options in ‘option_list’ are added after any options in
          ‘standard_option_list’ (a class attribute that may be set by
          OptionParser subclasses), but before any version or help
          options.  Deprecated; use *note add_option(): 2083. after
          creating the parser instead.

     ‘option_class’ (默认: optparse.Option)

          Class to use when adding options to the parser in *note
          add_option(): 2083.

     ‘version’ (默认: ‘None’)

          A version string to print when the user supplies a version
          option.  If you supply a true value for ‘version’, *note
          optparse: c4. automatically adds a version option with the
          single option string ‘--version’.  The substring ‘%prog’ is
          expanded the same as for ‘usage’.

     ‘conflict_handler’ (默认: ‘"error"’)

          Specifies what to do when options with conflicting option
          strings are added to the parser; see section *note Conflicts
          between options: 3a99.

     ‘description’ (默认: ‘None’)

          A paragraph of text giving a brief overview of your program.
          *note optparse: c4. reformats this paragraph to fit the
          current terminal width and prints it when the user requests
          help (after ‘usage’, but before the list of options).

     ‘formatter’ (default: a new ‘IndentedHelpFormatter’)

          An instance of optparse.HelpFormatter that will be used for
          printing help text.  *note optparse: c4. provides two concrete
          classes for this purpose: IndentedHelpFormatter and
          TitledHelpFormatter.

     ‘add_help_option’ (默认: ‘True’)

          If true, *note optparse: c4. will add a help option (with
          option strings ‘-h’ and ‘--help’) to the parser.

     ‘prog’

          The string to use when expanding ‘%prog’ in ‘usage’ and
          ‘version’ instead of ‘os.path.basename(sys.argv[0])’.

     ‘epilog’ (默认: ‘None’)

          A paragraph of help text to print after the option help.


File: python.info,  Node: 填充解析器,  Next: 定义选项,  Prev: 创建解析器,  Up: 参考指南

5.36.1.18 填充解析器
....................

There are several ways to populate the parser with options.  The
preferred way is by using *note OptionParser.add_option(): 2083, as
shown in section *note 教程: 3a75.  ‘add_option()’ can be called in one
of two ways:

   * pass it an Option instance (as returned by ‘make_option()’)

   * pass it any combination of positional and keyword arguments that
     are acceptable to ‘make_option()’ (i.e., to the Option
     constructor), and it will create the Option instance for you

The other alternative is to pass a list of pre-constructed Option
instances to the OptionParser constructor, as in:

     option_list = [
         make_option("-f", "--filename",
                     action="store", type="string", dest="filename"),
         make_option("-q", "--quiet",
                     action="store_false", dest="verbose"),
         ]
     parser = OptionParser(option_list=option_list)

(‘make_option()’ is a factory function for creating Option instances;
currently it is an alias for the Option constructor.  A future version
of *note optparse: c4. may split Option into several classes, and
‘make_option()’ will pick the right class to instantiate.  Do not
instantiate Option directly.)


File: python.info,  Node: 定义选项,  Next: Option attributes,  Prev: 填充解析器,  Up: 参考指南

5.36.1.19 定义选项
..................

Each Option instance represents a set of synonymous command-line option
strings, e.g.  ‘-f’ and ‘--file’.  You can specify any number of short
or long option strings, but you must specify at least one overall option
string.

The canonical way to create an ‘Option’ instance is with the
‘add_option()’ method of *note OptionParser: 3a6c.

 -- 方法: OptionParser.add_option (option)

 -- 方法: OptionParser.add_option (*opt_str, attr=value, ...)

     To define an option with only a short option string:

          parser.add_option("-f", attr=value, ...)

     And to define an option with only a long option string:

          parser.add_option("--foo", attr=value, ...)

     The keyword arguments define attributes of the new Option object.
     The most important option attribute is *note action: 3a77, and it
     largely determines which other attributes are relevant or required.
     If you pass irrelevant option attributes, or fail to pass required
     ones, *note optparse: c4. raises an ‘OptionError’ exception
     explaining your mistake.

     An option’s `action' determines what *note optparse: c4. does when
     it encounters this option on the command-line.  The standard option
     actions hard-coded into *note optparse: c4. are:

     ‘"store"’

          存储此选项的参数（默认）

     ‘"store_const"’

          store a constant value

     ‘"store_true"’

          store ‘True’

     ‘"store_false"’

          store ‘False’

     ‘"append"’

          append this option’s argument to a list

     ‘"append_const"’

          将常量值附加到列表

     ‘"count"’

          increment a counter by one

     ‘"callback"’

          调用指定函数

     ‘"help"’

          打印用法消息，包括所有选项和文档

     (If you don’t supply an action, the default is ‘"store"’.  For this
     action, you may also supply *note type: 3a78. and *note dest: 3a79.
     option attributes; see *note Standard option actions: 3a9e.)

As you can see, most actions involve storing or updating a value
somewhere.  *note optparse: c4. always creates a special object for
this, conventionally called ‘options’ (it happens to be an instance of
‘optparse.Values’).  Option arguments (and various other values) are
stored as attributes of this object, according to the *note dest: 3a79.
(destination) option attribute.

For example, when you call

     parser.parse_args()

one of the first things *note optparse: c4. does is create the ‘options’
object:

     options = Values()

If one of the options in this parser is defined with

     parser.add_option("-f", "--file", action="store", type="string", dest="filename")

and the command-line being parsed includes any of the following:

     -ffoo
     -f foo
     --file=foo
     --file foo

then *note optparse: c4, on seeing this option, will do the equivalent
of

     options.filename = "foo"

The *note type: 3a78. and *note dest: 3a79. option attributes are almost
as important as *note action: 3a77, but *note action: 3a77. is the only
one that makes sense for `all' options.


File: python.info,  Node: Option attributes,  Next: Standard option actions,  Prev: 定义选项,  Up: 参考指南

5.36.1.20 Option attributes
...........................

The following option attributes may be passed as keyword arguments to
*note OptionParser.add_option(): 2083.  If you pass an option attribute
that is not relevant to a particular option, or fail to pass a required
option attribute, *note optparse: c4. raises ‘OptionError’.

 -- 属性: Option.action

     (默认: ‘"store"’)

     Determines *note optparse: c4.’s behaviour when this option is seen
     on the command line; the available options are documented *note
     here: 3a9e.

 -- 属性: Option.type

     (默认: ‘"string"’)

     The argument type expected by this option (e.g., ‘"string"’ or
     ‘"int"’); the available option types are documented *note here:
     3aa1.

 -- 属性: Option.dest

     (default: derived from option strings)

     If the option’s action implies writing or modifying a value
     somewhere, this tells *note optparse: c4. where to write it: *note
     dest: 3a79. names an attribute of the ‘options’ object that *note
     optparse: c4. builds as it parses the command line.

 -- 属性: Option.default

     The value to use for this option’s destination if the option is not
     seen on the command line.  See also *note
     OptionParser.set_defaults(): 3aa3.

 -- 属性: Option.nargs

     (默认: 1)

     How many arguments of type *note type: 3a78. should be consumed
     when this option is seen.  If > 1, *note optparse: c4. will store a
     tuple of values to *note dest: 3a79.

 -- 属性: Option.const

     For actions that store a constant value, the constant value to
     store.

 -- 属性: Option.choices

     For options of type ‘"choice"’, the list of strings the user may
     choose from.

 -- 属性: Option.callback

     For options with action ‘"callback"’, the callable to call when
     this option is seen.  See section *note Option Callbacks: 3a85. for
     detail on the arguments passed to the callable.

 -- 属性: Option.callback_args
 -- 属性: Option.callback_kwargs

     Additional positional and keyword arguments to pass to ‘callback’
     after the four standard callback arguments.

 -- 属性: Option.help

     Help text to print for this option when listing all available
     options after the user supplies a *note help: 3a7a. option (such as
     ‘--help’).  If no help text is supplied, the option will be listed
     without help text.  To hide this option, use the special value
     ‘optparse.SUPPRESS_HELP’.

 -- 属性: Option.metavar

     (default: derived from option strings)

     Stand-in for the option argument(s) to use when printing help text.
     See section *note 教程: 3a75. for an example.


File: python.info,  Node: Standard option actions,  Next: Standard option types,  Prev: Option attributes,  Up: 参考指南

5.36.1.21 Standard option actions
.................................

The various option actions all have slightly different requirements and
effects.  Most actions have several relevant option attributes which you
may specify to guide *note optparse: c4.’s behaviour; a few have
required attributes, which you must specify for any option using that
action.

   * ‘"store"’ [relevant: *note type: 3a78, *note dest: 3a79, *note
     nargs: 3aa4, *note choices: 3aa6.]

     The option must be followed by an argument, which is converted to a
     value according to *note type: 3a78. and stored in *note dest:
     3a79.  If *note nargs: 3aa4. > 1, multiple arguments will be
     consumed from the command line; all will be converted according to
     *note type: 3a78. and stored to *note dest: 3a79. as a tuple.  See
     the *note Standard option types: 3aa1. section.

     If *note choices: 3aa6. is supplied (a list or tuple of strings),
     the type defaults to ‘"choice"’.

     If *note type: 3a78. is not supplied, it defaults to ‘"string"’.

     If *note dest: 3a79. is not supplied, *note optparse: c4. derives a
     destination from the first long option string (e.g., ‘--foo-bar’
     implies ‘foo_bar’).  If there are no long option strings, *note
     optparse: c4. derives a destination from the first short option
     string (e.g., ‘-f’ implies ‘f’).

     示例:

          parser.add_option("-f")
          parser.add_option("-p", type="float", nargs=3, dest="point")

     As it parses the command line

          -f foo.txt -p 1 -3.5 4 -fbar.txt

     *note optparse: c4. will set

          options.f = "foo.txt"
          options.point = (1.0, -3.5, 4.0)
          options.f = "bar.txt"

   * ‘"store_const"’ [required: *note const: 3aa5.; relevant: *note
     dest: 3a79.]

     The value *note const: 3aa5. is stored in *note dest: 3a79.

     示例:

          parser.add_option("-q", "--quiet",
                            action="store_const", const=0, dest="verbose")
          parser.add_option("-v", "--verbose",
                            action="store_const", const=1, dest="verbose")
          parser.add_option("--noisy",
                            action="store_const", const=2, dest="verbose")

     If ‘--noisy’ is seen, *note optparse: c4. will set

          options.verbose = 2

   * ‘"store_true"’ [relevant: *note dest: 3a79.]

     A special case of ‘"store_const"’ that stores ‘True’ to *note dest:
     3a79.

   * ‘"store_false"’ [relevant: *note dest: 3a79.]

     Like ‘"store_true"’, but stores ‘False’.

     示例:

          parser.add_option("--clobber", action="store_true", dest="clobber")
          parser.add_option("--no-clobber", action="store_false", dest="clobber")

   * ‘"append"’ [relevant: *note type: 3a78, *note dest: 3a79, *note
     nargs: 3aa4, *note choices: 3aa6.]

     The option must be followed by an argument, which is appended to
     the list in *note dest: 3a79.  If no default value for *note dest:
     3a79. is supplied, an empty list is automatically created when
     *note optparse: c4. first encounters this option on the
     command-line.  If *note nargs: 3aa4. > 1, multiple arguments are
     consumed, and a tuple of length *note nargs: 3aa4. is appended to
     *note dest: 3a79.

     The defaults for *note type: 3a78. and *note dest: 3a79. are the
     same as for the ‘"store"’ action.

     示例:

          parser.add_option("-t", "--tracks", action="append", type="int")

     If ‘-t3’ is seen on the command-line, *note optparse: c4. does the
     equivalent of:

          options.tracks = []
          options.tracks.append(int("3"))

     If, a little later on, ‘--tracks=4’ is seen, it does:

          options.tracks.append(int("4"))

     The ‘append’ action calls the ‘append’ method on the current value
     of the option.  This means that any default value specified must
     have an ‘append’ method.  It also means that if the default value
     is non-empty, the default elements will be present in the parsed
     value for the option, with any values from the command line
     appended after those default values:

          >>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
          >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
          >>> opts.files
          ['~/.mypkg/defaults', 'overrides.mypkg']

   * ‘"append_const"’ [required: *note const: 3aa5.; relevant: *note
     dest: 3a79.]

     Like ‘"store_const"’, but the value *note const: 3aa5. is appended
     to *note dest: 3a79.; as with ‘"append"’, *note dest: 3a79.
     defaults to ‘None’, and an empty list is automatically created the
     first time the option is encountered.

   * ‘"count"’ [relevant: *note dest: 3a79.]

     Increment the integer stored at *note dest: 3a79.  If no default
     value is supplied, *note dest: 3a79. is set to zero before being
     incremented the first time.

     示例:

          parser.add_option("-v", action="count", dest="verbosity")

     The first time ‘-v’ is seen on the command line, *note optparse:
     c4. does the equivalent of:

          options.verbosity = 0
          options.verbosity += 1

     Every subsequent occurrence of ‘-v’ results in

          options.verbosity += 1

   * ‘"callback"’ [required: *note callback: 3aa7.; relevant: *note
     type: 3a78, *note nargs: 3aa4, *note callback_args: 3aa8, *note
     callback_kwargs: 3aa9.]

     Call the function specified by *note callback: 3aa7, which is
     called as

          func(option, opt_str, value, parser, *args, **kwargs)

     See section *note Option Callbacks: 3a85. for more detail.

   * ‘"help"’

     Prints a complete help message for all the options in the current
     option parser.  The help message is constructed from the ‘usage’
     string passed to OptionParser’s constructor and the *note help:
     3a7a. string passed to every option.

     If no *note help: 3a7a. string is supplied for an option, it will
     still be listed in the help message.  To omit an option entirely,
     use the special value ‘optparse.SUPPRESS_HELP’.

     *note optparse: c4. automatically adds a *note help: 3a7a. option
     to all OptionParsers, so you do not normally need to create one.

     示例:

          from optparse import OptionParser, SUPPRESS_HELP

          # usually, a help option is added automatically, but that can
          # be suppressed using the add_help_option argument
          parser = OptionParser(add_help_option=False)

          parser.add_option("-h", "--help", action="help")
          parser.add_option("-v", action="store_true", dest="verbose",
                            help="Be moderately verbose")
          parser.add_option("--file", dest="filename",
                            help="Input file to read data from")
          parser.add_option("--secret", help=SUPPRESS_HELP)

     If *note optparse: c4. sees either ‘-h’ or ‘--help’ on the command
     line, it will print something like the following help message to
     stdout (assuming ‘sys.argv[0]’ is ‘"foo.py"’):

          Usage: foo.py [options]

          Options:
            -h, --help        Show this help message and exit
            -v                Be moderately verbose
            --file=FILENAME   Input file to read data from

     After printing the help message, *note optparse: c4. terminates
     your process with ‘sys.exit(0)’.

   * ‘"version"’

     Prints the version number supplied to the OptionParser to stdout
     and exits.  The version number is actually formatted and printed by
     the ‘print_version()’ method of OptionParser.  Generally only
     relevant if the ‘version’ argument is supplied to the OptionParser
     constructor.  As with *note help: 3a7a. options, you will rarely
     create ‘version’ options, since *note optparse: c4. automatically
     adds them when needed.


File: python.info,  Node: Standard option types,  Next: 解析参数<2>,  Prev: Standard option actions,  Up: 参考指南

5.36.1.22 Standard option types
...............................

*note optparse: c4. has five built-in option types: ‘"string"’, ‘"int"’,
‘"choice"’, ‘"float"’ and ‘"complex"’.  If you need to add new option
types, see section *note Extending optparse: 3a7d.

Arguments to string options are not checked or converted in any way: the
text on the command line is stored in the destination (or passed to the
callback) as-is.

Integer arguments (type ‘"int"’) are parsed as follows:

   * if the number starts with ‘0x’, it is parsed as a hexadecimal
     number

   * if the number starts with ‘0’, it is parsed as an octal number

   * if the number starts with ‘0b’, it is parsed as a binary number

   * otherwise, the number is parsed as a decimal number

The conversion is done by calling *note int(): 185. with the appropriate
base (2, 8, 10, or 16).  If this fails, so will *note optparse: c4,
although with a more useful error message.

‘"float"’ and ‘"complex"’ option arguments are converted directly with
*note float(): 188. and *note complex(): 18a, with similar
error-handling.

‘"choice"’ options are a subtype of ‘"string"’ options.  The *note
choices: 3aa6. option attribute (a sequence of strings) defines the set
of allowed option arguments.  ‘optparse.check_choice()’ compares
user-supplied option arguments against this master list and raises
‘OptionValueError’ if an invalid string is given.


File: python.info,  Node: 解析参数<2>,  Next: Querying and manipulating your option parser,  Prev: Standard option types,  Up: 参考指南

5.36.1.23 解析参数
..................

The whole point of creating and populating an OptionParser is to call
its ‘parse_args()’ method:

     (options, args) = parser.parse_args(args=None, values=None)

输入参数的位置

‘args’

     the list of arguments to process (default: ‘sys.argv[1:]’)

‘values’

     an ‘optparse.Values’ object to store option arguments in (default:
     a new instance of ‘Values’) – if you give an existing object, the
     option defaults will not be initialized on it

and the return values are

‘options’

     the same object that was passed in as ‘values’, or the
     optparse.Values instance created by *note optparse: c4.

‘args’

     the leftover positional arguments after all options have been
     processed

The most common usage is to supply neither keyword argument.  If you
supply ‘values’, it will be modified with repeated *note setattr():
15ec. calls (roughly one for every option argument stored to an option
destination) and returned by ‘parse_args()’.

If ‘parse_args()’ encounters any errors in the argument list, it calls
the OptionParser’s ‘error()’ method with an appropriate end-user error
message.  This ultimately terminates your process with an exit status of
2 (the traditional Unix exit status for command-line errors).


File: python.info,  Node: Querying and manipulating your option parser,  Next: Conflicts between options,  Prev: 解析参数<2>,  Up: 参考指南

5.36.1.24 Querying and manipulating your option parser
......................................................

The default behavior of the option parser can be customized slightly,
and you can also poke around your option parser and see what’s there.
OptionParser provides several methods to help you out:

 -- 方法: OptionParser.disable_interspersed_args ()

     Set parsing to stop on the first non-option.  For example, if ‘-a’
     and ‘-b’ are both simple options that take no arguments, *note
     optparse: c4. normally accepts this syntax:

          prog -a arg1 -b arg2

     and treats it as equivalent to

          prog -a -b arg1 arg2

     To disable this feature, call *note disable_interspersed_args():
     2084.  This restores traditional Unix syntax, where option parsing
     stops with the first non-option argument.

     Use this if you have a command processor which runs another command
     which has options of its own and you want to make sure these
     options don’t get confused.  For example, each command might have a
     different set of options.

 -- 方法: OptionParser.enable_interspersed_args ()

     Set parsing to not stop on the first non-option, allowing
     interspersing switches with command arguments.  This is the default
     behavior.

 -- 方法: OptionParser.get_option (opt_str)

     Returns the Option instance with the option string `opt_str', or
     ‘None’ if no options have that option string.

 -- 方法: OptionParser.has_option (opt_str)

     Return ‘True’ if the OptionParser has an option with option string
     `opt_str' (e.g., ‘-q’ or ‘--verbose’).

 -- 方法: OptionParser.remove_option (opt_str)

     If the *note OptionParser: 3a6c. has an option corresponding to
     `opt_str', that option is removed.  If that option provided any
     other option strings, all of those option strings become invalid.
     If `opt_str' does not occur in any option belonging to this *note
     OptionParser: 3a6c, raises *note ValueError: 1fc.


File: python.info,  Node: Conflicts between options,  Next: 清理<2>,  Prev: Querying and manipulating your option parser,  Up: 参考指南

5.36.1.25 Conflicts between options
...................................

If you’re not careful, it’s easy to define options with conflicting
option strings:

     parser.add_option("-n", "--dry-run", ...)
     ...
     parser.add_option("-n", "--noisy", ...)

(This is particularly true if you’ve defined your own OptionParser
subclass with some standard options.)

Every time you add an option, *note optparse: c4. checks for conflicts
with existing options.  If it finds any, it invokes the current
conflict-handling mechanism.  You can set the conflict-handling
mechanism either in the constructor:

     parser = OptionParser(..., conflict_handler=handler)

or with a separate call:

     parser.set_conflict_handler(handler)

The available conflict handlers are:

     ‘"error"’ (默认)

          assume option conflicts are a programming error and raise
          ‘OptionConflictError’

     ‘"resolve"’

          resolve option conflicts intelligently (see below)

As an example, let’s define an *note OptionParser: 3a6c. that resolves
conflicts intelligently and add conflicting options to it:

     parser = OptionParser(conflict_handler="resolve")
     parser.add_option("-n", "--dry-run", ..., help="do no harm")
     parser.add_option("-n", "--noisy", ..., help="be noisy")

At this point, *note optparse: c4. detects that a previously-added
option is already using the ‘-n’ option string.  Since
‘conflict_handler’ is ‘"resolve"’, it resolves the situation by removing
‘-n’ from the earlier option’s list of option strings.  Now ‘--dry-run’
is the only way for the user to activate that option.  If the user asks
for help, the help message will reflect that:

     Options:
       --dry-run     do no harm
       ...
       -n, --noisy   be noisy

It’s possible to whittle away the option strings for a previously-added
option until there are none left, and the user has no way of invoking
that option from the command-line.  In that case, *note optparse: c4.
removes that option completely, so it doesn’t show up in help text or
anywhere else.  Carrying on with our existing OptionParser:

     parser.add_option("--dry-run", ..., help="new dry-run option")

At this point, the original ‘-n’/‘--dry-run’ option is no longer
accessible, so *note optparse: c4. removes it, leaving this help text:

     Options:
       ...
       -n, --noisy   be noisy
       --dry-run     new dry-run option


File: python.info,  Node: 清理<2>,  Next: Other methods,  Prev: Conflicts between options,  Up: 参考指南

5.36.1.26 清理
..............

OptionParser instances have several cyclic references.  This should not
be a problem for Python’s garbage collector, but you may wish to break
the cyclic references explicitly by calling ‘destroy()’ on your
OptionParser once you are done with it.  This is particularly useful in
long-running applications where large object graphs are reachable from
your OptionParser.


File: python.info,  Node: Other methods,  Prev: 清理<2>,  Up: 参考指南

5.36.1.27 Other methods
.......................

OptionParser supports several other public methods:

 -- 方法: OptionParser.set_usage (usage)

     Set the usage string according to the rules described above for the
     ‘usage’ constructor keyword argument.  Passing ‘None’ sets the
     default usage string; use ‘optparse.SUPPRESS_USAGE’ to suppress a
     usage message.

 -- 方法: OptionParser.print_usage (file=None)

     Print the usage message for the current program (‘self.usage’) to
     `file' (default stdout).  Any occurrence of the string ‘%prog’ in
     ‘self.usage’ is replaced with the name of the current program.
     Does nothing if ‘self.usage’ is empty or not defined.

 -- 方法: OptionParser.get_usage ()

     Same as *note print_usage(): 3a90. but returns the usage string
     instead of printing it.

 -- 方法: OptionParser.set_defaults (dest=value, ...)

     Set default values for several option destinations at once.  Using
     *note set_defaults(): 3aa3. is the preferred way to set default
     values for options, since multiple options can share the same
     destination.  For example, if several "mode" options all set the
     same destination, any one of them can set the default, and the last
     one wins:

          parser.add_option("--advanced", action="store_const",
                            dest="mode", const="advanced",
                            default="novice")    # overridden below
          parser.add_option("--novice", action="store_const",
                            dest="mode", const="novice",
                            default="advanced")  # overrides above setting

     To avoid this confusion, use *note set_defaults(): 3aa3.:

          parser.set_defaults(mode="advanced")
          parser.add_option("--advanced", action="store_const",
                            dest="mode", const="advanced")
          parser.add_option("--novice", action="store_const",
                            dest="mode", const="novice")


File: python.info,  Node: Option Callbacks,  Next: Extending optparse,  Prev: 参考指南,  Up: optparse --- 解析器的命令行选项

5.36.1.28 Option Callbacks
..........................

When *note optparse: c4.’s built-in actions and types aren’t quite
enough for your needs, you have two choices: extend *note optparse: c4.
or define a callback option.  Extending *note optparse: c4. is more
general, but overkill for a lot of simple cases.  Quite often a simple
callback is all you need.

There are two steps to defining a callback option:

   * define the option itself using the ‘"callback"’ action

   * write the callback; this is a function (or method) that takes at
     least four arguments, as described below

* Menu:

* Defining a callback option::
* How callbacks are called::
* Raising errors in a callback::
* Callback example 1; trivial callback: Callback example 1 trivial callback.
* Callback example 2; check option order: Callback example 2 check option order.
* Callback example 3; check option order (generalized): Callback example 3 check option order generalized.
* Callback example 4; check arbitrary condition: Callback example 4 check arbitrary condition.
* Callback example 5; fixed arguments: Callback example 5 fixed arguments.
* Callback example 6; variable arguments: Callback example 6 variable arguments.


File: python.info,  Node: Defining a callback option,  Next: How callbacks are called,  Up: Option Callbacks

5.36.1.29 Defining a callback option
....................................

As always, the easiest way to define a callback option is by using the
*note OptionParser.add_option(): 2083. method.  Apart from *note action:
3a77, the only option attribute you must specify is ‘callback’, the
function to call:

     parser.add_option("-c", action="callback", callback=my_callback)

‘callback’ is a function (or other callable object), so you must have
already defined ‘my_callback()’ when you create this callback option.
In this simple case, *note optparse: c4. doesn’t even know if ‘-c’ takes
any arguments, which usually means that the option takes no
arguments—the mere presence of ‘-c’ on the command-line is all it needs
to know.  In some circumstances, though, you might want your callback to
consume an arbitrary number of command-line arguments.  This is where
writing callbacks gets tricky; it’s covered later in this section.

*note optparse: c4. always passes four particular arguments to your
callback, and it will only pass additional arguments if you specify them
via *note callback_args: 3aa8. and *note callback_kwargs: 3aa9.  Thus,
the minimal callback function signature is:

     def my_callback(option, opt, value, parser):

The four arguments to a callback are described below.

There are several other option attributes that you can supply when you
define a callback option:

*note type: 3a78.

     has its usual meaning: as with the ‘"store"’ or ‘"append"’ actions,
     it instructs *note optparse: c4. to consume one argument and
     convert it to *note type: 3a78.  Rather than storing the converted
     value(s) anywhere, though, *note optparse: c4. passes it to your
     callback function.

*note nargs: 3aa4.

     also has its usual meaning: if it is supplied and > 1, *note
     optparse: c4. will consume *note nargs: 3aa4. arguments, each of
     which must be convertible to *note type: 3a78.  It then passes a
     tuple of converted values to your callback.

*note callback_args: 3aa8.

     a tuple of extra positional arguments to pass to the callback

*note callback_kwargs: 3aa9.

     a dictionary of extra keyword arguments to pass to the callback


File: python.info,  Node: How callbacks are called,  Next: Raising errors in a callback,  Prev: Defining a callback option,  Up: Option Callbacks

5.36.1.30 How callbacks are called
..................................

All callbacks are called as follows:

     func(option, opt_str, value, parser, *args, **kwargs)

where

‘option’

     is the Option instance that’s calling the callback

‘opt_str’

     is the option string seen on the command-line that’s triggering the
     callback.  (If an abbreviated long option was used, ‘opt_str’ will
     be the full, canonical option string—e.g.  if the user puts ‘--foo’
     on the command-line as an abbreviation for ‘--foobar’, then
     ‘opt_str’ will be ‘"--foobar"’.)

‘value’

     is the argument to this option seen on the command-line.  *note
     optparse: c4. will only expect an argument if *note type: 3a78. is
     set; the type of ‘value’ will be the type implied by the option’s
     type.  If *note type: 3a78. for this option is ‘None’ (no argument
     expected), then ‘value’ will be ‘None’.  If *note nargs: 3aa4. > 1,
     ‘value’ will be a tuple of values of the appropriate type.

‘parser’

     is the OptionParser instance driving the whole thing, mainly useful
     because you can access some other interesting data through its
     instance attributes:

     ‘parser.largs’

          the current list of leftover arguments, ie.  arguments that
          have been consumed but are neither options nor option
          arguments.  Feel free to modify ‘parser.largs’, e.g.  by
          adding more arguments to it.  (This list will become ‘args’,
          the second return value of ‘parse_args()’.)

     ‘parser.rargs’

          the current list of remaining arguments, ie.  with ‘opt_str’
          and ‘value’ (if applicable) removed, and only the arguments
          following them still there.  Feel free to modify
          ‘parser.rargs’, e.g.  by consuming more arguments.

     ‘parser.values’

          the object where option values are by default stored (an
          instance of optparse.OptionValues).  This lets callbacks use
          the same mechanism as the rest of *note optparse: c4. for
          storing option values; you don’t need to mess around with
          globals or closures.  You can also access or modify the
          value(s) of any options already encountered on the
          command-line.

‘args’

     is a tuple of arbitrary positional arguments supplied via the *note
     callback_args: 3aa8. option attribute.

‘kwargs’

     is a dictionary of arbitrary keyword arguments supplied via *note
     callback_kwargs: 3aa9.


File: python.info,  Node: Raising errors in a callback,  Next: Callback example 1 trivial callback,  Prev: How callbacks are called,  Up: Option Callbacks

5.36.1.31 Raising errors in a callback
......................................

The callback function should raise ‘OptionValueError’ if there are any
problems with the option or its argument(s).  *note optparse: c4.
catches this and terminates the program, printing the error message you
supply to stderr.  Your message should be clear, concise, accurate, and
mention the option at fault.  Otherwise, the user will have a hard time
figuring out what they did wrong.


File: python.info,  Node: Callback example 1 trivial callback,  Next: Callback example 2 check option order,  Prev: Raising errors in a callback,  Up: Option Callbacks

5.36.1.32 Callback example 1: trivial callback
..............................................

Here’s an example of a callback option that takes no arguments, and
simply records that the option was seen:

     def record_foo_seen(option, opt_str, value, parser):
         parser.values.saw_foo = True

     parser.add_option("--foo", action="callback", callback=record_foo_seen)

Of course, you could do that with the ‘"store_true"’ action.


File: python.info,  Node: Callback example 2 check option order,  Next: Callback example 3 check option order generalized,  Prev: Callback example 1 trivial callback,  Up: Option Callbacks

5.36.1.33 Callback example 2: check option order
................................................

Here’s a slightly more interesting example: record the fact that ‘-a’ is
seen, but blow up if it comes after ‘-b’ in the command-line.

     def check_order(option, opt_str, value, parser):
         if parser.values.b:
             raise OptionValueError("can't use -a after -b")
         parser.values.a = 1
     ...
     parser.add_option("-a", action="callback", callback=check_order)
     parser.add_option("-b", action="store_true", dest="b")


File: python.info,  Node: Callback example 3 check option order generalized,  Next: Callback example 4 check arbitrary condition,  Prev: Callback example 2 check option order,  Up: Option Callbacks

5.36.1.34 Callback example 3: check option order (generalized)
..............................................................

If you want to re-use this callback for several similar options (set a
flag, but blow up if ‘-b’ has already been seen), it needs a bit of
work: the error message and the flag that it sets must be generalized.

     def check_order(option, opt_str, value, parser):
         if parser.values.b:
             raise OptionValueError("can't use %s after -b" % opt_str)
         setattr(parser.values, option.dest, 1)
     ...
     parser.add_option("-a", action="callback", callback=check_order, dest='a')
     parser.add_option("-b", action="store_true", dest="b")
     parser.add_option("-c", action="callback", callback=check_order, dest='c')


File: python.info,  Node: Callback example 4 check arbitrary condition,  Next: Callback example 5 fixed arguments,  Prev: Callback example 3 check option order generalized,  Up: Option Callbacks

5.36.1.35 Callback example 4: check arbitrary condition
.......................................................

Of course, you could put any condition in there—you’re not limited to
checking the values of already-defined options.  For example, if you
have options that should not be called when the moon is full, all you
have to do is this:

     def check_moon(option, opt_str, value, parser):
         if is_moon_full():
             raise OptionValueError("%s option invalid when moon is full"
                                    % opt_str)
         setattr(parser.values, option.dest, 1)
     ...
     parser.add_option("--foo",
                       action="callback", callback=check_moon, dest="foo")

(The definition of ‘is_moon_full()’ is left as an exercise for the
reader.)


File: python.info,  Node: Callback example 5 fixed arguments,  Next: Callback example 6 variable arguments,  Prev: Callback example 4 check arbitrary condition,  Up: Option Callbacks

5.36.1.36 Callback example 5: fixed arguments
.............................................

Things get slightly more interesting when you define callback options
that take a fixed number of arguments.  Specifying that a callback
option takes arguments is similar to defining a ‘"store"’ or ‘"append"’
option: if you define *note type: 3a78, then the option takes one
argument that must be convertible to that type; if you further define
*note nargs: 3aa4, then the option takes *note nargs: 3aa4. arguments.

Here’s an example that just emulates the standard ‘"store"’ action:

     def store_value(option, opt_str, value, parser):
         setattr(parser.values, option.dest, value)
     ...
     parser.add_option("--foo",
                       action="callback", callback=store_value,
                       type="int", nargs=3, dest="foo")

Note that *note optparse: c4. takes care of consuming 3 arguments and
converting them to integers for you; all you have to do is store them.
(Or whatever; obviously you don’t need a callback for this example.)


File: python.info,  Node: Callback example 6 variable arguments,  Prev: Callback example 5 fixed arguments,  Up: Option Callbacks

5.36.1.37 Callback example 6: variable arguments
................................................

Things get hairy when you want an option to take a variable number of
arguments.  For this case, you must write a callback, as *note optparse:
c4. doesn’t provide any built-in capabilities for it.  And you have to
deal with certain intricacies of conventional Unix command-line parsing
that *note optparse: c4. normally handles for you.  In particular,
callbacks should implement the conventional rules for bare ‘--’ and ‘-’
arguments:

   * either ‘--’ or ‘-’ can be option arguments

   * bare ‘--’ (if not the argument to some option): halt command-line
     processing and discard the ‘--’

   * bare ‘-’ (if not the argument to some option): halt command-line
     processing but keep the ‘-’ (append it to ‘parser.largs’)

If you want an option that takes a variable number of arguments, there
are several subtle, tricky issues to worry about.  The exact
implementation you choose will be based on which trade-offs you’re
willing to make for your application (which is why *note optparse: c4.
doesn’t support this sort of thing directly).

Nevertheless, here’s a stab at a callback for an option with variable
arguments:

     def vararg_callback(option, opt_str, value, parser):
         assert value is None
         value = []

         def floatable(str):
             try:
                 float(str)
                 return True
             except ValueError:
                 return False

         for arg in parser.rargs:
             # stop on --foo like options
             if arg[:2] == "--" and len(arg) > 2:
                 break
             # stop on -a, but not on -3 or -3.0
             if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
                 break
             value.append(arg)

         del parser.rargs[:len(value)]
         setattr(parser.values, option.dest, value)

     ...
     parser.add_option("-c", "--callback", dest="vararg_attr",
                       action="callback", callback=vararg_callback)


File: python.info,  Node: Extending optparse,  Prev: Option Callbacks,  Up: optparse --- 解析器的命令行选项

5.36.1.38 Extending ‘optparse’
..............................

Since the two major controlling factors in how *note optparse: c4.
interprets command-line options are the action and type of each option,
the most likely direction of extension is to add new actions and new
types.

* Menu:

* Adding new types::
* Adding new actions::


File: python.info,  Node: Adding new types,  Next: Adding new actions,  Up: Extending optparse

5.36.1.39 Adding new types
..........................

To add new types, you need to define your own subclass of *note
optparse: c4.’s ‘Option’ class.  This class has a couple of attributes
that define *note optparse: c4.’s types: *note TYPES: 3ad2. and *note
TYPE_CHECKER: 3ad3.

 -- 属性: Option.TYPES

     A tuple of type names; in your subclass, simply define a new tuple
     *note TYPES: 3ad2. that builds on the standard one.

 -- 属性: Option.TYPE_CHECKER

     A dictionary mapping type names to type-checking functions.  A
     type-checking function has the following signature:

          def check_mytype(option, opt, value)

     where ‘option’ is an ‘Option’ instance, ‘opt’ is an option string
     (e.g., ‘-f’), and ‘value’ is the string from the command line that
     must be checked and converted to your desired type.
     ‘check_mytype()’ should return an object of the hypothetical type
     ‘mytype’.  The value returned by a type-checking function will wind
     up in the OptionValues instance returned by
     ‘OptionParser.parse_args()’, or be passed to a callback as the
     ‘value’ parameter.

     Your type-checking function should raise ‘OptionValueError’ if it
     encounters any problems.  ‘OptionValueError’ takes a single string
     argument, which is passed as-is to *note OptionParser: 3a6c.’s
     ‘error()’ method, which in turn prepends the program name and the
     string ‘"error:"’ and prints everything to stderr before
     terminating the process.

Here’s a silly example that demonstrates adding a ‘"complex"’ option
type to parse Python-style complex numbers on the command line.  (This
is even sillier than it used to be, because *note optparse: c4. 1.3
added built-in support for complex numbers, but never mind.)

First, the necessary imports:

     from copy import copy
     from optparse import Option, OptionValueError

You need to define your type-checker first, since it’s referred to later
(in the *note TYPE_CHECKER: 3ad3. class attribute of your Option
subclass):

     def check_complex(option, opt, value):
         try:
             return complex(value)
         except ValueError:
             raise OptionValueError(
                 "option %s: invalid complex value: %r" % (opt, value))

Finally, the Option subclass:

     class MyOption (Option):
         TYPES = Option.TYPES + ("complex",)
         TYPE_CHECKER = copy(Option.TYPE_CHECKER)
         TYPE_CHECKER["complex"] = check_complex

(If we didn’t make a *note copy(): 26. of *note Option.TYPE_CHECKER:
3ad3, we would end up modifying the *note TYPE_CHECKER: 3ad3. attribute
of *note optparse: c4.’s Option class.  This being Python, nothing stops
you from doing that except good manners and common sense.)

That’s it!  Now you can write a script that uses the new option type
just like any other *note optparse: c4.-based script, except you have to
instruct your OptionParser to use MyOption instead of Option:

     parser = OptionParser(option_class=MyOption)
     parser.add_option("-c", type="complex")

Alternately, you can build your own option list and pass it to
OptionParser; if you don’t use ‘add_option()’ in the above way, you
don’t need to tell OptionParser which option class to use:

     option_list = [MyOption("-c", action="store", type="complex", dest="c")]
     parser = OptionParser(option_list=option_list)


File: python.info,  Node: Adding new actions,  Prev: Adding new types,  Up: Extending optparse

5.36.1.40 Adding new actions
............................

Adding new actions is a bit trickier, because you have to understand
that *note optparse: c4. has a couple of classifications for actions:

"store" actions

     actions that result in *note optparse: c4. storing a value to an
     attribute of the current OptionValues instance; these options
     require a *note dest: 3a79. attribute to be supplied to the Option
     constructor.

"typed" actions

     actions that take a value from the command line and expect it to be
     of a certain type; or rather, a string that can be converted to a
     certain type.  These options require a *note type: 3a78. attribute
     to the Option constructor.

These are overlapping sets: some default "store" actions are ‘"store"’,
‘"store_const"’, ‘"append"’, and ‘"count"’, while the default "typed"
actions are ‘"store"’, ‘"append"’, and ‘"callback"’.

When you add an action, you need to categorize it by listing it in at
least one of the following class attributes of Option (all are lists of
strings):

 -- 属性: Option.ACTIONS

     All actions must be listed in ACTIONS.

 -- 属性: Option.STORE_ACTIONS

     "store" actions are additionally listed here.

 -- 属性: Option.TYPED_ACTIONS

     "typed" actions are additionally listed here.

 -- 属性: Option.ALWAYS_TYPED_ACTIONS

     Actions that always take a type (i.e.  whose options always take a
     value) are additionally listed here.  The only effect of this is
     that *note optparse: c4. assigns the default type, ‘"string"’, to
     options with no explicit type whose action is listed in *note
     ALWAYS_TYPED_ACTIONS: 3ad9.

In order to actually implement your new action, you must override
Option’s ‘take_action()’ method and add a case that recognizes your
action.

For example, let’s add an ‘"extend"’ action.  This is similar to the
standard ‘"append"’ action, but instead of taking a single value from
the command-line and appending it to an existing list, ‘"extend"’ will
take multiple values in a single comma-delimited string, and extend an
existing list with them.  That is, if ‘--names’ is an ‘"extend"’ option
of type ‘"string"’, the command line

     --names=foo,bar --names blah --names ding,dong

would result in a list

     ["foo", "bar", "blah", "ding", "dong"]

Again we define a subclass of Option:

     class MyOption(Option):

         ACTIONS = Option.ACTIONS + ("extend",)
         STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
         TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
         ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)

         def take_action(self, action, dest, opt, value, values, parser):
             if action == "extend":
                 lvalue = value.split(",")
                 values.ensure_value(dest, []).extend(lvalue)
             else:
                 Option.take_action(
                     self, action, dest, opt, value, values, parser)

Features of note:

   * ‘"extend"’ both expects a value on the command-line and stores that
     value somewhere, so it goes in both *note STORE_ACTIONS: 3ad7. and
     *note TYPED_ACTIONS: 3ad8.

   * to ensure that *note optparse: c4. assigns the default type of
     ‘"string"’ to ‘"extend"’ actions, we put the ‘"extend"’ action in
     *note ALWAYS_TYPED_ACTIONS: 3ad9. as well.

   * ‘MyOption.take_action()’ implements just this one new action, and
     passes control back to ‘Option.take_action()’ for the standard
     *note optparse: c4. actions.

   * ‘values’ is an instance of the optparse_parser.Values class, which
     provides the very useful ‘ensure_value()’ method.  ‘ensure_value()’
     is essentially *note getattr(): 451. with a safety valve; it is
     called as

          values.ensure_value(attr, value)

     If the ‘attr’ attribute of ‘values’ doesn’t exist or is ‘None’,
     then ensure_value() first sets it to ‘value’, and then returns
     ’value.  This is very handy for actions like ‘"extend"’,
     ‘"append"’, and ‘"count"’, all of which accumulate data in a
     variable and expect that variable to be of a certain type (a list
     for the first two, an integer for the latter).  Using
     ‘ensure_value()’ means that scripts using your action don’t have to
     worry about setting a default value for the option destinations in
     question; they can just leave the default as ‘None’ and
     ‘ensure_value()’ will take care of getting it right when it’s
     needed.


File: python.info,  Node: imp --- Access the import internals,  Prev: optparse --- 解析器的命令行选项,  Up: 被取代的模块

5.36.2 ‘imp’ — Access the import internals
------------------------------------------

`Source code:' Lib/imp.py(1)

3.4 版后已移除: The *note imp: 9a. module is deprecated in favor of
*note importlib: 9b.

__________________________________________________________________

This module provides an interface to the mechanisms used to implement
the *note import: c25. statement.  It defines the following constants
and functions:

 -- 函数: imp.get_magic ()

     Return the magic string value used to recognize byte-compiled code
     files (‘.pyc’ files).  (This value may be different for each Python
     version.)

     3.4 版后已移除: Use *note importlib.util.MAGIC_NUMBER: 86b.
     instead.

 -- 函数: imp.get_suffixes ()

     Return a list of 3-element tuples, each describing a particular
     type of module.  Each triple has the form ‘(suffix, mode, type)’,
     where `suffix' is a string to be appended to the module name to
     form the filename to search for, `mode' is the mode string to pass
     to the built-in *note open(): 4f8. function to open the file (this
     can be ‘'r'’ for text files or ‘'rb'’ for binary files), and `type'
     is the file type, which has one of the values *note PY_SOURCE:
     3add, *note PY_COMPILED: 3ade, or *note C_EXTENSION: 3adf,
     described below.

     3.3 版后已移除: Use the constants defined on *note
     importlib.machinery: 9d. instead.

 -- 函数: imp.find_module (name[, path])

     Try to find the module `name'.  If `path' is omitted or ‘None’, the
     list of directory names given by ‘sys.path’ is searched, but first
     a few special places are searched: the function tries to find a
     built-in module with the given name (*note C_BUILTIN: 3ae1.), then
     a frozen module (*note PY_FROZEN: 3ae2.), and on some systems some
     other places are looked in as well (on Windows, it looks in the
     registry which may point to a specific file).

     Otherwise, `path' must be a list of directory names; each directory
     is searched for files with any of the suffixes returned by *note
     get_suffixes(): 3adc. above.  Invalid names in the list are
     silently ignored (but all list items must be strings).

     If search is successful, the return value is a 3-element tuple
     ‘(file, pathname, description)’:

     `file' is an open *note file object: b4a. positioned at the
     beginning, `pathname' is the pathname of the file found, and
     `description' is a 3-element tuple as contained in the list
     returned by *note get_suffixes(): 3adc. describing the kind of
     module found.

     If the module is built-in or frozen then `file' and `pathname' are
     both ‘None’ and the `description' tuple contains empty strings for
     its suffix and mode; the module type is indicated as given in
     parentheses above.  If the search is unsuccessful, *note
     ImportError: 33d. is raised.  Other exceptions indicate problems
     with the arguments or environment.

     If the module is a package, `file' is ‘None’, `pathname' is the
     package path and the last item in the `description' tuple is *note
     PKG_DIRECTORY: 3ae3.

     This function does not handle hierarchical module names (names
     containing dots).  In order to find `P.M', that is, submodule `M'
     of package `P', use *note find_module(): 3ae0. and *note
     load_module(): 3ae4. to find and load package `P', and then use
     *note find_module(): 3ae0. with the `path' argument set to
     ‘P.__path__’.  When `P' itself has a dotted name, apply this recipe
     recursively.

     3.3 版后已移除: Use *note importlib.util.find_spec(): 940. instead
     unless Python 3.3 compatibility is required, in which case use
     *note importlib.find_loader(): 93f.  For example usage of the
     former case, see the *note 例子: 37a3. section of the *note
     importlib: 9b. documentation.

 -- 函数: imp.load_module (name, file, pathname, description)

     Load a module that was previously found by *note find_module():
     3ae0. (or by an otherwise conducted search yielding compatible
     results).  This function does more than importing the module: if
     the module was already imported, it will reload the module!  The
     `name' argument indicates the full module name (including the
     package name, if this is a submodule of a package).  The `file'
     argument is an open file, and `pathname' is the corresponding file
     name; these can be ‘None’ and ‘''’, respectively, when the module
     is a package or not being loaded from a file.  The `description'
     argument is a tuple, as would be returned by *note get_suffixes():
     3adc, describing what kind of module must be loaded.

     If the load is successful, the return value is the module object;
     otherwise, an exception (usually *note ImportError: 33d.) is
     raised.

     `Important:' the caller is responsible for closing the `file'
     argument, if it was not ‘None’, even when an exception is raised.
     This is best done using a *note try: d7a. ...  *note finally: 183.
     statement.

     3.3 版后已移除: If previously used in conjunction with *note
     imp.find_module(): 3ae0. then consider using *note
     importlib.import_module(): b1b, otherwise use the loader returned
     by the replacement you chose for *note imp.find_module(): 3ae0.  If
     you called *note imp.load_module(): 3ae4. and related functions
     directly with file path arguments then use a combination of *note
     importlib.util.spec_from_file_location(): 562. and *note
     importlib.util.module_from_spec(): 6f9.  See the *note 例子: 37a3.
     section of the *note importlib: 9b. documentation for details of
     the various approaches.

 -- 函数: imp.new_module (name)

     Return a new empty module object called `name'.  This object is
     `not' inserted in ‘sys.modules’.

     3.4 版后已移除: Use *note importlib.util.module_from_spec(): 6f9.
     instead.

 -- 函数: imp.reload (module)

     Reload a previously imported `module'.  The argument must be a
     module object, so it must have been successfully imported before.
     This is useful if you have edited the module source file using an
     external editor and want to try out the new version without leaving
     the Python interpreter.  The return value is the module object (the
     same as the `module' argument).

     When ‘reload(module)’ is executed:

        * Python modules’ code is recompiled and the module-level code
          reexecuted, defining a new set of objects which are bound to
          names in the module’s dictionary.  The ‘init’ function of
          extension modules is not called a second time.

        * 与Python中的所有的其它对象一样，旧的对象只有在它们的引用计数为
          0之后才会被回收。

        * 模块命名空间中的名称重新指向任何新的或更改后的对象。

        * 其他旧对象的引用（例如那个模块的外部名称）不会被重新绑定到引用
          的新对象的，并且如果有需要，必须在出现的每个命名空间中进行更新
          。

     有一些其他注意事项：

     当一个模块被重新加载的时候，它的字典（包含了那个模块的全区变量）会
     被保留。名称的重新定义会覆盖旧的定义，所以通常来说这不是问题。如果
     一个新模块没有定义在旧版本模块中定义的名称，则将保留旧版本中的定义
     。这一特性可用于作为那个模块的优点，如果它维护一个全局表或者对象的
     缓存 —— 使用 *note try: d7a. 语句，就可以测试表的存在并且跳过它的初
     始化，如果有需要的话:

          try:
              cache
          except NameError:
              cache = {}

     It is legal though generally not very useful to reload built-in or
     dynamically loaded modules, except for *note sys: fe, *note
     __main__: 1. and *note builtins: 13.  In many cases, however,
     extension modules are not designed to be initialized more than
     once, and may fail in arbitrary ways when reloaded.

     If a module imports objects from another module using *note from:
     c4d. ...  *note import: c25. ..., calling *note reload(): c78. for
     the other module does not redefine the objects imported from it —
     one way around this is to re-execute the ‘from’ statement, another
     is to use ‘import’ and qualified names (`module'.*name*) instead.

     如果一个模块创建一个类的实例，重新加载定义那个类的模块不影响那些实
     例的方法定义———它们继续使用旧类中的定义。对于子类来说同样是正确的。

     在 3.3 版更改: Relies on both ‘__name__’ and ‘__loader__’ being
     defined on the module being reloaded instead of just ‘__name__’.

     3.4 版后已移除: Use *note importlib.reload(): 3a1. instead.

The following functions are conveniences for handling PEP 3147(2)
byte-compiled file paths.

3.2 新版功能.

 -- 函数: imp.cache_from_source (path, debug_override=None)

     Return the PEP 3147(3) path to the byte-compiled file associated
     with the source `path'.  For example, if `path' is
     ‘/foo/bar/baz.py’ the return value would be
     ‘/foo/bar/__pycache__/baz.cpython-32.pyc’ for Python 3.2.  The
     ‘cpython-32’ string comes from the current magic tag (see *note
     get_tag(): 3ae7.; if ‘sys.implementation.cache_tag’ is not defined
     then *note NotImplementedError: 617. will be raised).  By passing
     in ‘True’ or ‘False’ for `debug_override' you can override the
     system’s value for ‘__debug__’, leading to optimized bytecode.

     `path' need not exist.

     在 3.3 版更改: If ‘sys.implementation.cache_tag’ is ‘None’, then
     *note NotImplementedError: 617. is raised.

     3.4 版后已移除: Use *note importlib.util.cache_from_source(): 560.
     instead.

     在 3.5 版更改: The `debug_override' parameter no longer creates a
     ‘.pyo’ file.

 -- 函数: imp.source_from_cache (path)

     Given the `path' to a PEP 3147(4) file name, return the associated
     source code file path.  For example, if `path' is
     ‘/foo/bar/__pycache__/baz.cpython-32.pyc’ the returned path would
     be ‘/foo/bar/baz.py’.  `path' need not exist, however if it does
     not conform to PEP 3147(5) format, a *note ValueError: 1fc. is
     raised.  If ‘sys.implementation.cache_tag’ is not defined, *note
     NotImplementedError: 617. is raised.

     在 3.3 版更改: Raise *note NotImplementedError: 617. when
     ‘sys.implementation.cache_tag’ is not defined.

     3.4 版后已移除: Use *note importlib.util.source_from_cache(): 561.
     instead.

 -- 函数: imp.get_tag ()

     Return the PEP 3147(6) magic tag string matching this version of
     Python’s magic number, as returned by *note get_magic(): 86c.

     3.4 版后已移除: Use ‘sys.implementation.cache_tag’ directly
     starting in Python 3.3.

The following functions help interact with the import system’s internal
locking mechanism.  Locking semantics of imports are an implementation
detail which may vary from release to release.  However, Python ensures
that circular imports work without any deadlocks.

 -- 函数: imp.lock_held ()

     Return ‘True’ if the global import lock is currently held, else
     ‘False’.  On platforms without threads, always return ‘False’.

     On platforms with threads, a thread executing an import first holds
     a global import lock, then sets up a per-module lock for the rest
     of the import.  This blocks other threads from importing the same
     module until the original import completes, preventing other
     threads from seeing incomplete module objects constructed by the
     original thread.  An exception is made for circular imports, which
     by construction have to expose an incomplete module object at some
     point.

     在 3.3 版更改: The locking scheme has changed to per-module locks
     for the most part.  A global import lock is kept for some critical
     tasks, such as initializing the per-module locks.

     3.4 版后已移除.

 -- 函数: imp.acquire_lock ()

     Acquire the interpreter’s global import lock for the current
     thread.  This lock should be used by import hooks to ensure
     thread-safety when importing modules.

     Once a thread has acquired the import lock, the same thread may
     acquire it again without blocking; the thread must release it once
     for each time it has acquired it.

     On platforms without threads, this function does nothing.

     在 3.3 版更改: The locking scheme has changed to per-module locks
     for the most part.  A global import lock is kept for some critical
     tasks, such as initializing the per-module locks.

     3.4 版后已移除.

 -- 函数: imp.release_lock ()

     Release the interpreter’s global import lock.  On platforms without
     threads, this function does nothing.

     在 3.3 版更改: The locking scheme has changed to per-module locks
     for the most part.  A global import lock is kept for some critical
     tasks, such as initializing the per-module locks.

     3.4 版后已移除.

The following constants with integer values, defined in this module, are
used to indicate the search result of *note find_module(): 3ae0.

 -- 数据: imp.PY_SOURCE

     The module was found as a source file.

     3.3 版后已移除.

 -- 数据: imp.PY_COMPILED

     The module was found as a compiled code object file.

     3.3 版后已移除.

 -- 数据: imp.C_EXTENSION

     The module was found as dynamically loadable shared library.

     3.3 版后已移除.

 -- 数据: imp.PKG_DIRECTORY

     The module was found as a package directory.

     3.3 版后已移除.

 -- 数据: imp.C_BUILTIN

     The module was found as a built-in module.

     3.3 版后已移除.

 -- 数据: imp.PY_FROZEN

     The module was found as a frozen module.

     3.3 版后已移除.

 -- 类: imp.NullImporter (path_string)

     The *note NullImporter: 9c3. type is a PEP 302(7) import hook that
     handles non-directory path strings by failing to find any modules.
     Calling this type with an existing directory or empty string raises
     *note ImportError: 33d.  Otherwise, a *note NullImporter: 9c3.
     instance is returned.

     Instances have only one method:

      -- 方法: find_module (fullname[, path])

          This method always returns ‘None’, indicating that the
          requested module could not be found.

     在 3.3 版更改: ‘None’ is inserted into ‘sys.path_importer_cache’
     instead of an instance of *note NullImporter: 9c3.

     3.4 版后已移除: Insert ‘None’ into ‘sys.path_importer_cache’
     instead.

* Menu:

* 例子: 例子<33>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Lib/imp.py

   (2) https://www.python.org/dev/peps/pep-3147

   (3) https://www.python.org/dev/peps/pep-3147

   (4) https://www.python.org/dev/peps/pep-3147

   (5) https://www.python.org/dev/peps/pep-3147

   (6) https://www.python.org/dev/peps/pep-3147

   (7) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: 例子<33>,  Up: imp --- Access the import internals

5.36.2.1 例子
.............

The following function emulates what was the standard import statement
up to Python 1.4 (no hierarchical module names).  (This `implementation'
wouldn’t work in that version, since *note find_module(): 3ae0. has been
extended and *note load_module(): 3ae4. has been added in 1.4.)

     import imp
     import sys

     def __import__(name, globals=None, locals=None, fromlist=None):
         # Fast path: see if the module has already been imported.
         try:
             return sys.modules[name]
         except KeyError:
             pass

         # If any of the following calls raises an exception,
         # there's a problem we can't handle -- let the caller handle it.

         fp, pathname, description = imp.find_module(name)

         try:
             return imp.load_module(name, fp, pathname, description)
         finally:
             # Since we may exit via an exception, close fp explicitly.
             if fp:
                 fp.close()


File: python.info,  Node: 未创建文档的模块,  Prev: 被取代的模块,  Up: Python 标准库

5.37 未创建文档的模块
=====================

以下是目前未创建文档模块的速览列表，但其它们应创建文档。 欢迎为他们提供
文档！ （通过电子邮件发送到 <docs@python.org> ）

本章的想法和原内容取自 Fredrik Lundh 的帖子；本章的具体内容已经大幅修改
。

* Menu:

* 平台特定模块::


File: python.info,  Node: 平台特定模块,  Up: 未创建文档的模块

5.37.1 平台特定模块
-------------------

这些模块用于实现 *note os.path: c6. 模块，除此之外没有文档。几乎没有必要
创建这些文档。

‘ntpath’

     — 在 Win32 和 Win64 平台上实现 *note os.path: c6. 。

‘posixpath’

     — 在 POSIX 上实现 *note os.path: c6. 。


File: python.info,  Node: 扩展和嵌入 Python 解释器,  Next: Python/C API 参考手册,  Prev: Python 标准库,  Up: Top

6 扩展和嵌入 Python 解释器
**************************

本文档描述了如何使用 C 或 C++ 编写模块以使用新模块来扩展 Python 解释器的
功能。 这些模块不仅可以定义新的函数，还可以定义新的对象类型及其方法。 该
文档还描述了如何将 Python 解释器嵌入到另一个应用程序中，以用作扩展语言。
最后，它展示了如何编译和链接扩展模块，以便它们可以动态地（在运行时）加载
到解释器中，如果底层操作系统支持此特性的话。

本文档假设你具备有关 Python 的基本知识。有关该语言的非正式介绍，请参阅
*note Python 教程: 120a. 。 *note Python语言参考: 120c. 给出了更正式的语
言定义。 *note Python 标准库: 120b. 包含现有的对象类型、函数和模块（内置
和用 Python 编写）的文档，使语言具有广泛的应用范围。

关于整个 Python/C API 的详细介绍，请参阅独立的 *note Python/C API
参考手册: 120e. 。

* Menu:

* 推荐的第三方工具::
* 不使用第三方工具创建扩展::
* 在更大的应用程序中嵌入 CPython 运行时::


File: python.info,  Node: 推荐的第三方工具,  Next: 不使用第三方工具创建扩展,  Up: 扩展和嵌入 Python 解释器

6.1 推荐的第三方工具
====================

本指南仅介绍了作为此 CPython 版本的一部分提供的创建扩展的基本工具。 第三
方工具，如 Cython(1) 、 cffi(2) 、 SWIG(3) 和 Numba(4) 提供了更简单和更
复杂的方法来为 Python 创建 C 和 C ++ 扩展。

参见
....

Python Packaging User Guide: Binary Extensions(5)

     “ Python Packaging User Guide ”不仅涵盖了几个简化二进制扩展创建的可
     用工具，还讨论了为什么首先创建扩展模块的各种原因。

   ---------- Footnotes ----------

   (1) http://cython.org/

   (2) https://cffi.readthedocs.io

   (3) http://www.swig.org

   (4) https://numba.pydata.org/

   (5) https://packaging.python.org/guides/packaging-binary-extensions/


File: python.info,  Node: 不使用第三方工具创建扩展,  Next: 在更大的应用程序中嵌入 CPython 运行时,  Prev: 推荐的第三方工具,  Up: 扩展和嵌入 Python 解释器

6.2 不使用第三方工具创建扩展
============================

本指南的这一部分包括在没有第三方工具帮助的情况下创建 C 和 C ++ 扩展。它
主要用于这些工具的创建者，而不是建议你创建自己的 C 扩展的方法。

* Menu:

* 使用 C 或 C++ 扩展 Python::
* 自定义扩展类型：教程::
* 定义扩展类型：已分类主题::
* 构建C/C++扩展::
* 在Windows平台编译C和C++扩展::


File: python.info,  Node: 使用 C 或 C++ 扩展 Python,  Next: 自定义扩展类型：教程,  Up: 不使用第三方工具创建扩展

6.2.1 使用 C 或 C++ 扩展 Python
-------------------------------

如果你会用 C，添加新的 Python 内置模块会很简单。以下两件不能用 Python 直
接做的事，可以通过 `extension modules' 来实现：实现新的内置对象类型；调
用 C 的库函数和系统调用。

为了支持扩展，Python API（应用程序编程接口）定义了一系列函数、宏和变量，
可以访问 Python 运行时系统的大部分内容。Python 的 API 可以通过在一个 C 源
文件中引用 ‘"Python.h"’ 头文件来使用。

扩展模块的编写方式取决与你的目的以及系统设置；下面章节会详细介绍。

     注解: C扩展接口特指CPython，扩展模块无法在其他Python实现上工作。在
     大多数情况下，应该避免写C扩展，来保持可移植性。举个例子，如果你的用
     例调用了C库或系统调用，你应该考虑使用 *note ctypes: 2b. 模块或
     cffi(1) 库，而不是自己写C代码。这些模块允许你写Python代码来接口C代
     码，而且可移植性更好。不知为何编译失败了。

* Menu:

* 一个简单的例子::
* 关于错误和异常::
* 回到例子::
* 模块方法表和初始化函数::
* 编译和链接::
* 在C中调用Python函数::
* 提取扩展函数的参数::
* 给扩展函数的关键字参数::
* 构造任意值::
* 引用计数::
* 在C++中编写扩展::
* 给扩展模块提供C API::

   ---------- Footnotes ----------

   (1) https://cffi.readthedocs.io/


File: python.info,  Node: 一个简单的例子,  Next: 关于错误和异常,  Up: 使用 C 或 C++ 扩展 Python

6.2.1.1 一个简单的例子
......................

让我们创建一个扩展模块 ‘spam’ (Monty Python 粉丝最喜欢的食物...) 并且想
要创建对应 C 库函数 ‘system()’ (1) 的 Python 接口。 这个函数接受一个以
null 结尾的字符串参数并返回一个整数。 我们希望可以在 Python 中以如下方式
调用此函数:

     >>> import spam
     >>> status = spam.system("ls -l")

首先创建一个 ‘spammodule.c’ 文件。（传统上，如果一个模块叫 ‘spam’，则对
应实现它的 C 文件叫 ‘spammodule.c’；如果这个模块名字非常长，比如
‘spammify’，则这个模块的文件可以直接叫 ‘spammify.c’。）

文件中开始的两行是：

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>

这会导入 Python API（如果你喜欢，你可以在这里添加描述模块目标和版权信息
的注释)。

     注解: 由于 Python 可能会定义一些能在某些系统上影响标准头文件的预处
     理器定义，因此在包含任何标准头文件之前，你 `必须' 先包含
     ‘Python.h’。

     推荐总是在 ‘Python.h’ 前定义 ‘PY_SSIZE_T_CLEAN’ 。查看 *note
     提取扩展函数的参数: 3afc. 来了解这个宏的更多内容。

所有在 ‘Python.h’ 中定义的用户可见的符号都具有 ‘Py’ 或 ‘PY’ 前缀，已在标
准头文件中定义的那些除外。 考虑到便利性，也由于其在 Python 解释器中被广
泛使用，‘"Python.h"’ 还包含了一些标准头文件: ‘<stdio.h>’，‘<string.h>’，
‘<errno.h>’ 和 ‘<stdlib.h>’。 如果后面的头文件在你的系统上不存在，它还会
直接声明函数 ‘malloc()’，‘free()’ 和 ‘realloc()’。

下面添加C函数到扩展模块，当调用 ‘spam.system(string)’ 时会做出响应，(我
们稍后会看到调用)：

     static PyObject *
     spam_system(PyObject *self, PyObject *args)
     {
         const char *command;
         int sts;

         if (!PyArg_ParseTuple(args, "s", &command))
             return NULL;
         sts = system(command);
         return PyLong_FromLong(sts);
     }

有个直接翻译参数列表的方法(举个例子，单独的 ‘"ls -l"’ )到要传递给C函数的
参数。C函数总是有两个参数，通常名字是 `self' 和 `args' 。

对模块级函数， `self' 参数指向模块对象；对于方法则指向对象实例。

`args' 参数是指向一个 Python 的 tuple 对象的指针，其中包含参数。 每个
tuple 项对应一个调用参数。 这些参数也全都是 Python 对象 — 要在我们的 C 函
数中使用它们就需要先将其转换为 C 值。 Python API 中的函数 *note
PyArg_ParseTuple(): 26b. 会检查参数类型并将其转换为 C 值。 它使用模板字
符串确定需要的参数类型以及存储被转换的值的 C 变量类型。 细节将稍后说明。

*note PyArg_ParseTuple(): 26b. 在所有参数都有正确类型且组成部分按顺序放
在传递进来的地址里时，返回真(非零)。其在传入无效参数时返回假(零)。在后续
例子里，还会抛出特定异常，使得调用的函数可以理解返回 ‘NULL’ (也就是例子
里所见)。

   ---------- Footnotes ----------

   (1) (1) 这个函数的接口已经在标准模块 *note os: c5. 里了，这里作为一个
简单而直接的例子。


File: python.info,  Node: 关于错误和异常,  Next: 回到例子,  Prev: 一个简单的例子,  Up: 使用 C 或 C++ 扩展 Python

6.2.1.2 关于错误和异常
......................

在 Python 解释器中有一个重要的惯例：当一个函数出错时，它应当设置异常条件
并返回错误值（通常为 ‘NULL’ 指针）。 异常存储于解释器内部的静态全局变量
中；如此变量为 ‘NULL’ 表示未发生异常。 还有第二个全局变量用于保存异常的
“关联值”（即 *note raise: c4a. 的第二个参数）。 第三个变量包含 Python 代
码产生错误情况下的栈回溯信息。 这三个变量是 Python 中 *note
sys.exc_info(): c67. 的结果在 C 中的对应物（请参阅 Python 库参考的 *note
sys: fe. 模块部分）。 了解它们对于理解错误的传递方式是非常重要的。

Python API中定义了一些函数来设置这些变量。

最常用的就是 *note PyErr_SetString(): 3aff.。 其参数是异常对象和 C 字符
串。 异常对象一般是像 ‘PyExc_ZeroDivisionError’ 这样的预定义对象。 C 字
符串指明异常原因，并被转换为一个 Python 字符串对象存储为异常的“关联值”。

另一个有用的函数是 *note PyErr_SetFromErrno(): 3b00. ，仅接受一个异常对
象，异常描述包含在全局变量 ‘errno’ 中。最通用的函数还是 *note
PyErr_SetObject(): 3b01. ，包含两个参数，分别为异常对象和异常描述。你不
需要使用 *note Py_INCREF(): 266. 来增加传递到其他函数的参数对象的引用计
数。

你可以通过 *note PyErr_Occurred(): 3b02. 在不造成破坏的情况下检测是否设
置了异常。 这将返回当前异常对象，或者如果未发生异常则返回 ‘NULL’。 你通
常不需要调用 *note PyErr_Occurred(): 3b02. 来查看函数调用中是否发生了错
误，因为你应该能从返回值中看出来。

当一个函数 `f' 调用另一个函数 `g' 时检测到后者出错了，`f' 应当自己返回一
个错误值 (通常为 ‘NULL’ 或 ‘-1’)。 它 `不应该' 调用某个 ‘PyErr_*()’ 函数
— 这类函数已经被 `g' 调用过了。 `f' 的调用者随后也应当返回一个错误来提示
`它的' 调用者，同样 `不应该' 调用 ‘PyErr_*()’，依此类推 — 错误的最详细原
因已经由首先检测到它的函数报告了。 一旦这个错误到达 Python 解释器的主循
环，它会中止当前执行的 Python 代码并尝试找出由 Python 程序员所指定的异常
处理程序。

（在某些情况下，当模块确实能够通过调用其它 ‘PyErr_*()’ 函数给出更加详细
的错误消息，并且在这些情况是可以这样做的。 但是按照一般规则，这是不必要
的，并可能导致有关错误原因的信息丢失：大多数操作会由于种种原因而失败。）

想要忽略由一个失败的函数调用所设置的异常，异常条件必须通过调用 *note
PyErr_Clear(): 973. 显式地被清除。 C 代码应当调用 *note PyErr_Clear():
973. 的唯一情况是如果它不想将错误传给解释器而是想完全由自己来处理它（可
能是尝试其他方法，或是假装没有出错）。

每次失败的 ‘malloc()’ 调用必须转换为一个异常。 ‘malloc()’ (或
‘realloc()’ )的直接调用者必须调用 *note PyErr_NoMemory(): 3b03. 来返回错
误来提示。所有对象创建函数(例如 *note PyLong_FromLong(): 3b04. )已经这么
做了，所以这个提示仅用于直接调用 ‘malloc()’ 的情况。

还要注意的是，除了 *note PyArg_ParseTuple(): 26b. 等重要的例外，返回整数
状态码的函数通常都是返回正值或零来表示成功，而以 ‘-1’ 表示失败，如同
Unix 系统调用一样。

最后，当你返回一个错误指示器时要注意清理垃圾（通过为你已经创建的对象执行
*note Py_XDECREF(): 269. 或 *note Py_DECREF(): 267. 调用）！

选择引发哪个异常完全取决于你的喜好。 所有内置的 Python 异常都有对应的预
声明 C 对象，例如 ‘PyExc_ZeroDivisionError’，你可以直接使用它们。 当然，
你应当明智地选择异常 — 不要使用 ‘PyExc_TypeError’ 来表示一个文件无法被打
开 (那大概应该用 ‘PyExc_IOError’)。 如果参数列表有问题，*note
PyArg_ParseTuple(): 26b. 函数通常会引发 ‘PyExc_TypeError’。 如果你想要一
个参数的值必须处于特定范围之内或必须满足其他条件，则适宜使用
‘PyExc_ValueError’。

你也可以为你的模块定义一个唯一的新异常。需要在文件前部声明一个静态对象变
量，如:

     static PyObject *SpamError;

并且在你的模块的初始化函数 (‘PyInit_spam()’) 中使用一个异常对象来初始化:

     PyMODINIT_FUNC
     PyInit_spam(void)
     {
         PyObject *m;

         m = PyModule_Create(&spammodule);
         if (m == NULL)
             return NULL;

         SpamError = PyErr_NewException("spam.error", NULL, NULL);
         Py_XINCREF(SpamError);
         if (PyModule_AddObject(m, "error", SpamError) < 0) {
             Py_XDECREF(SpamError);
             Py_CLEAR(SpamError);
             Py_DECREF(m);
             return NULL;
         }

         return m;
     }

注意异常对象的Python名字是 ‘spam.error’ 。而 *note PyErr_NewException():
c08. 函数可以创建一个类，其基类为 *note Exception: 1aa. (除非是另一个类
传入以替换 ‘NULL’ )， 细节参见 *note 内置异常: 12be. 。

同样注意的是创建类保存了 ‘SpamError’ 的一个引用，这是有意的。为了防止被
垃圾回收掉，否则 ‘SpamError’ 随时会成为野指针。

一会讨论 ‘PyMODINIT_FUNC’ 作为函数返回类型的用法。

‘spam.error’ 异常可以在扩展模块中抛出，通过 *note PyErr_SetString():
3aff. 函数调用，如下：

     static PyObject *
     spam_system(PyObject *self, PyObject *args)
     {
         const char *command;
         int sts;

         if (!PyArg_ParseTuple(args, "s", &command))
             return NULL;
         sts = system(command);
         if (sts < 0) {
             PyErr_SetString(SpamError, "System command failed");
             return NULL;
         }
         return PyLong_FromLong(sts);
     }


File: python.info,  Node: 回到例子,  Next: 模块方法表和初始化函数,  Prev: 关于错误和异常,  Up: 使用 C 或 C++ 扩展 Python

6.2.1.3 回到例子
................

回到前面的例子，你应该明白下面的代码:

     if (!PyArg_ParseTuple(args, "s", &command))
         return NULL;

如果在参数列表中检测到错误，它将返回 ‘NULL’ (该值是返回对象指针的函数所
使用的错误提示)，这取决于 *note PyArg_ParseTuple(): 26b. 设置的异常。 在
其他情况下参数的字符串值会被拷贝到局部变量 ‘command’。 这是一个指针赋值
并且你不应该修改它所指向的字符串 (因此在标准 C 中，变量 ‘command’ 应当被
正确地声明为 ‘const char *command’)。

下一个语句使用UNIX系统函数 ‘system()’ ，传递给他的参数是刚才从 *note
PyArg_ParseTuple(): 26b. 取出的:

     sts = system(command);

我们的 ‘spam.system()’ 函数必须返回 ‘sts’ 的值作为Python对象。这通过使用
函数 *note PyLong_FromLong(): 3b04. 来实现。

     return PyLong_FromLong(sts);

在这种情况下，会返回一个整数对象，(这个对象会在Python堆里面管理)。

如果你的 C 函数没有有用的返回值 (返回 ‘void’ 的函数)，则对应的 Python 函
数必须返回 ‘None’。 你必须使用这种写法（可以通过 *note Py_RETURN_NONE:
dde. 宏来实现）:

     Py_INCREF(Py_None);
     return Py_None;

*note Py_None: 3b07. 是特殊 Python 对象 ‘None’ 所对应的 C 名称。 它是一
个真正的 Python 对象而不是 ‘NULL’ 指针，如我们所见，后者在大多数上下文中
都意味着“错误”。


File: python.info,  Node: 模块方法表和初始化函数,  Next: 编译和链接,  Prev: 回到例子,  Up: 使用 C 或 C++ 扩展 Python

6.2.1.4 模块方法表和初始化函数
..............................

为了展示 ‘spam_system()’ 如何被Python程序调用。把函数声明为可以被
Python调用，需要先定义一个方法表 "method table" 。

     static PyMethodDef SpamMethods[] = {
         ...
         {"system",  spam_system, METH_VARARGS,
          "Execute a shell command."},
         ...
         {NULL, NULL, 0, NULL}        /* Sentinel */
     };

注意第三个参数 ( ‘METH_VARARGS’ ) ，这个标志指定会使用C的调用惯例。可选
值有 ‘METH_VARARGS’ 、 ‘METH_VARARGS | METH_KEYWORDS’ 。值 ‘0’ 代表使用
*note PyArg_ParseTuple(): 26b. 的陈旧变量。

如果单独使用 ‘METH_VARARGS’ ，函数会等待Python传来tuple格式的参数，并最
终使用 *note PyArg_ParseTuple(): 26b. 进行解析。

‘METH_KEYWORDS’ 值表示接受关键字参数。这种情况下C函数需要接受第三个
‘PyObject *’ 对象，表示字典参数，使用 *note
PyArg_ParseTupleAndKeywords(): 5d3. 来解析出参数。

这个方法表必须被模块定义结构所引用。

     static struct PyModuleDef spammodule = {
         PyModuleDef_HEAD_INIT,
         "spam",   /* name of module */
         spam_doc, /* module documentation, may be NULL */
         -1,       /* size of per-interpreter state of the module,
                      or -1 if the module keeps state in global variables. */
         SpamMethods
     };

这个结构体必须传递给解释器的模块初始化函数。初始化函数必须命名为
‘PyInit_name()’ ，其中 `name' 是模块的名字，并应该定义为非 ‘static’ ，且
在模块文件里：

     PyMODINIT_FUNC
     PyInit_spam(void)
     {
         return PyModule_Create(&spammodule);
     }

注意 PyMODINIT_FUNC 将函数声明为 ‘PyObject *’ 返回类型，声明了任何平台所
要求的特殊链接声明，并针对 C++ 将函数声明为 ‘extern "C"’。

当 Python 程序首次导入 ‘spam’ 模块时， ‘PyInit_spam()’ 会被调用。 （有关
嵌入 Python 的注释参见下文。） 它将调用 *note PyModule_Create(): 3b0a.，
该函数会返回一个模块对象，并基于在模块定义中找到的表将内置函数对象插入到
新创建的模块中（该表是一个 *note PyMethodDef: e23. 结构体的数组）。
*note PyModule_Create(): 3b0a. 返回一个指向它所创建的模块对象的指针。 它
可能会因程度严重的特定错误而中止，或者在模块无法成功初始化时返回 ‘NULL’。
初始化函数必须返回模块对象给其调用者，这样它就可以被插入到 ‘sys.modules’
中。

当嵌入Python时， ‘PyInit_spam()’ 函数不会被自动调用，除非放在
‘PyImport_Inittab’ 表里。要添加模块到初始化表，使用 *note
PyImport_AppendInittab(): 3b0b. ，可选的跟着一个模块的导入。

     int
     main(int argc, char *argv[])
     {
         wchar_t *program = Py_DecodeLocale(argv[0], NULL);
         if (program == NULL) {
             fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
             exit(1);
         }

         /* Add a built-in module, before Py_Initialize */
         if (PyImport_AppendInittab("spam", PyInit_spam) == -1) {
             fprintf(stderr, "Error: could not extend in-built modules table\n");
             exit(1);
         }

         /* Pass argv[0] to the Python interpreter */
         Py_SetProgramName(program);

         /* Initialize the Python interpreter.  Required.
            If this step fails, it will be a fatal error. */
         Py_Initialize();

         /* Optionally import the module; alternatively,
            import can be deferred until the embedded script
            imports it. */
         PyObject *pmodule = PyImport_ImportModule("spam");
         if (!pmodule) {
             PyErr_Print();
             fprintf(stderr, "Error: could not import module 'spam'\n");
         }

         ...

         PyMem_RawFree(program);
         return 0;
     }

     注解: 要从 ‘sys.modules’ 删除实体或导入已编译模块到一个进程里的多个
     解释器(或使用 ‘fork()’ 而没用 ‘exec()’ )会在一些扩展模块上产生错误
     。扩展模块作者可以在初始化内部数据结构时给出警告。

更多关于模块的现实的例子包含在Python源码包的 ‘Modules/xxmodule.c’ 中。这
些文件可以用作你的代码模板，或者学习。脚本 modulator.py 包含在源码发行版
或Windows安装中，提供了一个简单的GUI，用来声明需要实现的函数和对象，并且
可以生成供填入的模板。脚本在 Tools/modulator/ 目录。查看README以了解用法
。

     注解: 不像我们的 ‘spam’ 例子， ‘xxmodule’ 使用了 `多阶段初始化'
     (Python3.5开始引入)， ‘PyInit_spam’ 会返回一个 PyModuleDef 结构体，
     然后创建的模块放到导入机制。细节参考 PEP 489(1) 的多阶段初始化。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0489


File: python.info,  Node: 编译和链接,  Next: 在C中调用Python函数,  Prev: 模块方法表和初始化函数,  Up: 使用 C 或 C++ 扩展 Python

6.2.1.5 编译和链接
..................

在你能使用你的新写的扩展之前，你还需要做两件事情：使用 Python 系统来编译
和链接。如果你使用动态加载，这取决于你使用的操作系统的动态加载机制；更多
信息请参考编译扩展模块的章节（ *note 构建C/C++扩展: 3b0e. 章节），以及在
Windows 上编译需要的额外信息（ *note 在Windows平台编译C和C++扩展: 13ac.
章节）。

如果你不使用动态加载，或者想要让模块永久性的作为Python解释器的一部分，就
必须修改配置设置，并重新构建解释器。幸运的是在Unix上很简单，只需要把你的
文件 ( ‘spammodule.c’ 为例) 放在解压缩源码发行包的 ‘Modules/’ 目录下，添
加一行到 ‘Modules/Setup.local’ 来描述你的文件：

     spam spammodule.o

然后在顶层目录运行 ‘make’ 来重新构建解释器。你也可以在 ‘Modules/’ 子目录
使用 ‘make’，但是你必须先重建 ‘Makefile’ 文件，然后运行 ’‘make’
Makefile’ 命令。（你每次修改 ‘Setup’ 文件都需要这样操作。）

如果你的模块需要额外的链接，这些内容可以列出在配置文件里，举个实例：

     spam spammodule.o -lX11


File: python.info,  Node: 在C中调用Python函数,  Next: 提取扩展函数的参数,  Prev: 编译和链接,  Up: 使用 C 或 C++ 扩展 Python

6.2.1.6 在C中调用Python函数
...........................

迄今为止，我们一直把注意力集中于让Python调用C函数，其实反过来也很有用，
就是用C调用Python函数。这在回调函数中尤其有用。如果一个C接口使用回调，那
么就要实现这个回调机制。

幸运的是，Python解释器是比较方便回调的，并给标准Python函数提供了标准接口
。(这里就不再详述解析Python字符串作为输入的方式，如果有兴趣可以参考
‘Python/pythonmain.c’ 中的 *note -c: 121b. 命令行代码。)

调用Python函数很简单，首先Python程序要传递Python函数对象。应该提供个函数
(或其他接口)来实现。当调用这个函数时，用全局变量保存Python函数对象的指针
，还要调用 (*note Py_INCREF(): 266.) 来增加引用计数，当然不用全局变量也
没什么关系。举个例子，如下函数可能是模块定义的一部分：

     static PyObject *my_callback = NULL;

     static PyObject *
     my_set_callback(PyObject *dummy, PyObject *args)
     {
         PyObject *result = NULL;
         PyObject *temp;

         if (PyArg_ParseTuple(args, "O:set_callback", &temp)) {
             if (!PyCallable_Check(temp)) {
                 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
                 return NULL;
             }
             Py_XINCREF(temp);         /* Add a reference to new callback */
             Py_XDECREF(my_callback);  /* Dispose of previous callback */
             my_callback = temp;       /* Remember new callback */
             /* Boilerplate to return "None" */
             Py_INCREF(Py_None);
             result = Py_None;
         }
         return result;
     }

这个函数必须使用 *note METH_VARARGS: e50. 标志注册到解释器，这在 *note
模块方法表和初始化函数: 3b08. 章节会描述。 *note PyArg_ParseTuple():
26b. 函数及其参数的文档在 *note 提取扩展函数的参数: 3afc. 。

*note Py_XINCREF(): 268. 和 *note Py_XDECREF(): 269. 这两个宏可增加/减少
一个对象的引用计数，并且当存在 ‘NULL’ 指针时仍可保证安全 (但请注意在这个
上下文中 `temp' 将不为 ‘NULL’)。 更多相关信息请参考 *note 引用计数:
3b11. 章节。

随后，当要调用此函数时，你将调用 C 函数 *note PyObject_CallObject():
3b12.。 该函数有两个参数，它们都属于指针，指向任意 Python 对象：即
Python 函数，及其参数列表。 参数列表必须总是一个元组对象，其长度即参数的
个数量。 要不带参数地调用 Python 函数，则传入 ‘NULL’ 或一个空元组；要带
一个参数调用它，则传入一个单元组。 *note Py_BuildValue(): 2cf. 会在其格
式字符串包含一对圆括号内的零个或多个格式代码时返回一个元组。 例如:

     int arg;
     PyObject *arglist;
     PyObject *result;
     ...
     arg = 123;
     ...
     /* Time to call the callback */
     arglist = Py_BuildValue("(i)", arg);
     result = PyObject_CallObject(my_callback, arglist);
     Py_DECREF(arglist);

*note PyObject_CallObject(): 3b12. 返回Python对象指针，这也是Python函数
的返回值。 *note PyObject_CallObject(): 3b12. 是一个对其参数 "引用计数无
关" 的函数。例子中新的元组创建用于参数列表，并且在 *note
PyObject_CallObject(): 3b12. 之后立即使用了 *note Py_DECREF(): 267. 。

‘PyEval_CallObject()’ 的返回值总是“新”的：要么是一个新建的对象；要么是已
有对象，但增加了引用计数。所以除非你想把结果保存在全局变量中，你需要对这
个值使用 *note Py_DECREF(): 267.，即使你对里面的内容（特别！）不感兴趣。

但是在你这么做之前，很重要的一点是检查返回值不是 ‘NULL’。 如果是的话，
Python 函数会终止并引发异常。 如果调用 *note PyObject_CallObject():
3b12. 的 C 代码是在 Python 中发起调用的，它应当立即返回一个错误来告知其
Python 调用者，以便解释器能打印栈回溯信息，或者让调用方 Python 代码能处
理该异常。 如果这无法做到或不合本意，则应当通过调用 *note PyErr_Clear():
973. 来清除异常。 例如:

     if (result == NULL)
         return NULL; /* Pass error back */
     ...use result...
     Py_DECREF(result);

依赖于具体的回调函数，你还要提供一个参数列表到 ‘PyEval_CallObject()’ 。
在某些情况下参数列表是由Python程序提供的，通过接口再传到回调函数对象。这
样就可以不改变形式直接传递。另外一些时候你要构造一个新的元组来传递参数。
最简单的方法就是 *note Py_BuildValue(): 2cf. 函数构造tuple。举个例子，你
要传递一个事件代码时可以用如下代码:

     PyObject *arglist;
     ...
     arglist = Py_BuildValue("(l)", eventcode);
     result = PyObject_CallObject(my_callback, arglist);
     Py_DECREF(arglist);
     if (result == NULL)
         return NULL; /* Pass error back */
     /* Here maybe use the result */
     Py_DECREF(result);

注意 ‘Py_DECREF(arglist)’ 所在处会立即调用，在错误检查之前。当然还要注意
一些常规的错误，比如 *note Py_BuildValue(): 2cf. 可能会遭遇内存不足等等
。

当你调用函数时还需要注意，用关键字参数调用 *note PyObject_Call(): 3b13.
，需要支持普通参数和关键字参数。有如如上例子中，我们使用 *note
Py_BuildValue(): 2cf. 来构造字典。

     PyObject *dict;
     ...
     dict = Py_BuildValue("{s:i}", "name", val);
     result = PyObject_Call(my_callback, NULL, dict);
     Py_DECREF(dict);
     if (result == NULL)
         return NULL; /* Pass error back */
     /* Here maybe use the result */
     Py_DECREF(result);


File: python.info,  Node: 提取扩展函数的参数,  Next: 给扩展函数的关键字参数,  Prev: 在C中调用Python函数,  Up: 使用 C 或 C++ 扩展 Python

6.2.1.7 提取扩展函数的参数
..........................

函数 *note PyArg_ParseTuple(): 26b. 的声明如下：

     int PyArg_ParseTuple(PyObject *arg, const char *format, ...);

参数 `arg' 必须是一个元组对象，包含从 Python 传递给 C 函数的参数列表。
`format' 参数必须是一个格式字符串，语法请参考 Python C/API 手册中的
*note 解析参数并构建值变量: 2d1.。剩余参数是各个变量的地址，类型要与格式
字符串对应。

注意 *note PyArg_ParseTuple(): 26b. 会检测他需要的Python参数类型，却无法
检测传递给他的C变量地址，如果这里出错了，可能会在内存中随机写入东西，小
心。

注意任何由调用者提供的 Python 对象引用是 `借来的' 引用；不要递减它们的引
用计数！

一些调用的例子：

     #define PY_SSIZE_T_CLEAN  /* Make "s#" use Py_ssize_t rather than int. */
     #include <Python.h>

     int ok;
     int i, j;
     long k, l;
     const char *s;
     Py_ssize_t size;

     ok = PyArg_ParseTuple(args, ""); /* No arguments */
         /* Python call: f() */

     ok = PyArg_ParseTuple(args, "s", &s); /* A string */
         /* Possible Python call: f('whoops!') */

     ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
         /* Possible Python call: f(1, 2, 'three') */

     ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
         /* A pair of ints and a string, whose size is also returned */
         /* Possible Python call: f((1, 2), 'three') */

     {
         const char *file;
         const char *mode = "r";
         int bufsize = 0;
         ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
         /* A string, and optionally another string and an integer */
         /* Possible Python calls:
            f('spam')
            f('spam', 'w')
            f('spam', 'wb', 100000) */
     }

     {
         int left, top, right, bottom, h, v;
         ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
                  &left, &top, &right, &bottom, &h, &v);
         /* A rectangle and a point */
         /* Possible Python call:
            f(((0, 0), (400, 300)), (10, 10)) */
     }

     {
         Py_complex c;
         ok = PyArg_ParseTuple(args, "D:myfunction", &c);
         /* a complex, also providing a function name for errors */
         /* Possible Python call: myfunction(1+2j) */
     }


File: python.info,  Node: 给扩展函数的关键字参数,  Next: 构造任意值,  Prev: 提取扩展函数的参数,  Up: 使用 C 或 C++ 扩展 Python

6.2.1.8 给扩展函数的关键字参数
..............................

函数 *note PyArg_ParseTupleAndKeywords(): 5d3. 声明如下：

     int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
                                     const char *format, char *kwlist[], ...);

`arg' 与 `format' 形参与 *note PyArg_ParseTuple(): 26b. 函数所定义的一致
。 `kwdict' 形参是作为第三个参数从 Python 运行时接收的关键字字典。
`kwlist' 形参是以 ‘NULL’ 结尾的字符串列表，它被用来标识形参；名称从左至
右与来自 `format' 的类型信息相匹配。 如果执行成功，*note
PyArg_ParseTupleAndKeywords(): 5d3. 会返回真值，否则返回假值并引发一个适
当的异常。

     注解: 嵌套的元组在使用关键字参数时无法生效，不在 `kwlist' 中的关键
     字参数会导致 *note TypeError: 193. 异常。

如下例子是使用关键字参数的例子模块，作者是 Geoff Philbrick
(<philbrick@hks.com>):

     #define PY_SSIZE_T_CLEAN  /* Make "s#" use Py_ssize_t rather than int. */
     #include <Python.h>

     static PyObject *
     keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)
     {
         int voltage;
         const char *state = "a stiff";
         const char *action = "voom";
         const char *type = "Norwegian Blue";

         static char *kwlist[] = {"voltage", "state", "action", "type", NULL};

         if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
                                          &voltage, &state, &action, &type))
             return NULL;

         printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
                action, voltage);
         printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);

         Py_RETURN_NONE;
     }

     static PyMethodDef keywdarg_methods[] = {
         /* The cast of the function is necessary since PyCFunction values
          * only take two PyObject* parameters, and keywdarg_parrot() takes
          * three.
          */
         {"parrot", (PyCFunction)(void(*)(void))keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
          "Print a lovely skit to standard output."},
         {NULL, NULL, 0, NULL}   /* sentinel */
     };

     static struct PyModuleDef keywdargmodule = {
         PyModuleDef_HEAD_INIT,
         "keywdarg",
         NULL,
         -1,
         keywdarg_methods
     };

     PyMODINIT_FUNC
     PyInit_keywdarg(void)
     {
         return PyModule_Create(&keywdargmodule);
     }


File: python.info,  Node: 构造任意值,  Next: 引用计数,  Prev: 给扩展函数的关键字参数,  Up: 使用 C 或 C++ 扩展 Python

6.2.1.9 构造任意值
..................

这个函数与 *note PyArg_ParseTuple(): 26b. 很相似，声明如下：

     PyObject *Py_BuildValue(const char *format, ...);

接受一个格式字符串，与 *note PyArg_ParseTuple(): 26b. 相同，但是参数必须
是原变量的地址指针(输入给函数，而非输出)。最终返回一个Python对象适合于返
回C函数调用给Python代码。

一个与 *note PyArg_ParseTuple(): 26b. 的不同是，后面可能需要的要求返回一
个元组(Python参数里诶包总是在内部描述为元组)，比如用于传递给其他Python函
数以参数。 *note Py_BuildValue(): 2cf. 并不总是生成元组，在多于1个格式字
符串时会生成元组，而如果格式字符串为空则返回 ‘None’ ，一个参数则直接返回
该参数的对象。如果要求强制生成一个长度为0的元组，或包含一个元素的元组，
需要在格式字符串中加上括号。

例子(左侧是调用，右侧是Python值结果)：

     Py_BuildValue("")                        None
     Py_BuildValue("i", 123)                  123
     Py_BuildValue("iii", 123, 456, 789)      (123, 456, 789)
     Py_BuildValue("s", "hello")              'hello'
     Py_BuildValue("y", "hello")              b'hello'
     Py_BuildValue("ss", "hello", "world")    ('hello', 'world')
     Py_BuildValue("s#", "hello", 4)          'hell'
     Py_BuildValue("y#", "hello", 4)          b'hell'
     Py_BuildValue("()")                      ()
     Py_BuildValue("(i)", 123)                (123,)
     Py_BuildValue("(ii)", 123, 456)          (123, 456)
     Py_BuildValue("(i,i)", 123, 456)         (123, 456)
     Py_BuildValue("[i,i]", 123, 456)         [123, 456]
     Py_BuildValue("{s:i,s:i}",
                   "abc", 123, "def", 456)    {'abc': 123, 'def': 456}
     Py_BuildValue("((ii)(ii)) (ii)",
                   1, 2, 3, 4, 5, 6)          (((1, 2), (3, 4)), (5, 6))


File: python.info,  Node: 引用计数,  Next: 在C++中编写扩展,  Prev: 构造任意值,  Up: 使用 C 或 C++ 扩展 Python

6.2.1.10 引用计数
.................

在C/C++语言中，程序员负责动态分配和回收堆heap当中的内存。在C里，通过函数
‘malloc()’ 和 ‘free()’ 来完成。在C++里是操作 ‘new’ 和 ‘delete’ 来实现相
同的功能。

每个由 ‘malloc()’ 分配的内存块，最终都要由 ‘free()’ 退回到可用内存池里面
去。而调用 ‘free()’ 的时机非常重要，如果一个内存块忘了 ‘free()’ 则会导致
内存泄漏，这块内存在程序结束前将无法重新使用。这叫做 `内存泄漏' 。而如果
对同一内存块 ‘free()’ 了以后，另外一个指针再次访问，则再次使用
‘malloc()’ 复用这块内存会导致冲突。这叫做 `野指针' 。等同于使用未初始化
的数据，core dump，错误结果，神秘的崩溃等。

内存泄露往往发生在一些并不常见的代码流程上面。比如一个函数申请了内存以后
，做了些计算，然后释放内存块。现在一些对函数的修改可能增加对计算的测试并
检测错误条件，然后过早的从函数返回了。这很容易忘记在退出前释放内存，特别
是后期修改的代码。这种内存泄漏，一旦引入，通常很长时间都难以检测到，错误
退出被调用的频度较低，而现代电脑又有非常巨大的虚拟内存，所以泄漏仅在长期
运行或频繁调用泄漏函数时才会变得明显。因此，有必要避免内存泄漏，通过代码
规范会策略来最小化此类错误。

Python通过 ‘malloc()’ 和 ‘free()’ 包含大量的内存分配和释放，同样需要避免
内存泄漏和野指针。他选择的方法就是 `引用计数' 。其原理比较简单：每个对象
都包含一个计数器，计数器的增减与对象引用的增减直接相关，当引用计数为0时
，表示对象已经没有存在的意义了，对象就可以删除了。

另一个叫法是 `自动垃圾回收' 。(有时引用计数也被看作是垃圾回收策略，于是
这里的"自动"用以区分两者)。自动垃圾回收的优点是用户不需要明确的调用
‘free()’ 。(另一个优点是改善速度或内存使用，然而这并不难)。缺点是对C，没
有可移植的自动垃圾回收器，而引用计数则可以可移植的实现(只要 ‘malloc()’ 和
‘free()’ 函数是可用的，这也是C标准担保的)。也许以后有一天会出现可移植的
自动垃圾回收器，但在此前我们必须与引用计数一起工作。

Python使用传统的引用计数实现，也提供了循环监测器，用以检测引用循环。这使
得应用无需担心直接或间接的创建了循环引用，这是引用计数垃圾收集的一个弱点
。引用循环是对象(可能直接)的引用了本身，所以循环中的每个对象的引用计数都
不是0。典型的引用计数实现无法回收处于引用循环中的对象，或者被循环所引用
的对象，哪怕没有循环以外的引用了。

循环探测器可以检测垃圾循环并回收。 *note gc: 86. 模块提供了方法运行探测
器 ( *note collect(): 22f. 函数) ，而且可以在运行时配置禁用探测器。循环
探测器被当作可选组件，默认是包含的，也可以在构建时禁用，在Unix平台(包括
Mac OS X)使用 ‘--without-cycle-gc’ 选项到 ‘configure’ 脚本。如果循环探测
器被禁用， *note gc: 86. 模块就不可用了。

* Menu:

* Python中的引用计数::
* 拥有规则::
* 危险的薄冰::
* NULL指针::


File: python.info,  Node: Python中的引用计数,  Next: 拥有规则,  Up: 引用计数

6.2.1.11 Python中的引用计数
...........................

有两个宏 ‘Py_INCREF(x)’ 和 ‘Py_DECREF(x)’ ，会处理引用计数的增减。 *note
Py_DECREF(): 267. 也会在引用计数到达0时释放对象。为了灵活，并不会直接调
用 ‘free()’ ，而是通过对象的 `类型对象' 的函数指针来调用。为了这个目的
(或其他的)，每个对象同时包含一个指向自身类型对象的指针。

最大的问题依旧：何时使用 ‘Py_INCREF(x)’ 和 ‘Py_DECREF(x)’ ？我们首先引入
一些概念。没有人"拥有"一个对象，你可以 `拥有一个引用' 到一个对象。一个对
象的引用计数定义为拥有引用的数量。引用的拥有者有责任调用 *note
Py_DECREF(): 267. ，在引用不再需要时。引用的拥有关系可以被传递。有三种办
法来处置拥有的引用：传递、存储、调用 *note Py_DECREF(): 267. 。忘记处置
一个拥有的引用会导致内存泄漏。

还可以 `借用' (1) 一个对象的引用。借用的引用不应该调用 *note
Py_DECREF(): 267. 。借用者必须确保不能持有对象超过拥有者借出的时间。在拥
有者处置对象后使用借用的引用是有风险的，应该完全避免 (2) 。

借用相对于引用的优点是你无需担心整条路径上代码的引用，或者说，通过借用你
无需担心内存泄漏的风险。借用的缺点是一些看起来正确代码上的借用可能会在拥
有者处置后使用对象。

借用可以变为拥有引用，通过调用 *note Py_INCREF(): 266. 。这不会影响已经
借出的拥有者的状态。这回创建一个新的拥有引用，并给予完全的拥有者责任(新
的拥有者必须恰当的处置引用，就像之前的拥有者那样)。

   ---------- Footnotes ----------

   (1) (2) 术语"借用"一个引用是不完全正确的：拥有者仍然有引用的拷贝。

   (2) (3) 检查引用计数至少为1 `没有用' ，引用计数本身可以在已经释放的内
存里，并有可能被其他对象所用。


File: python.info,  Node: 拥有规则,  Next: 危险的薄冰,  Prev: Python中的引用计数,  Up: 引用计数

6.2.1.12 拥有规则
.................

当一个对象引用传递进出一个函数时，函数的接口应该指定拥有关系的传递是否包
含引用。

大多数函数返回一个对象的引用，并传递引用拥有关系。通常，所有创建对象的函
数，例如 *note PyLong_FromLong(): 3b04. 和 *note Py_BuildValue(): 2cf. ，
会传递拥有关系给接收者。即便是对象不是真正新的，你仍然可以获得对象的新引
用。一个实例是 *note PyLong_FromLong(): 3b04. 维护了一个流行值的缓存，并
可以返回已缓存项目的新引用。

很多另一个对象提取对象的函数，也会传递引用关系，例如 *note
PyObject_GetAttrString(): 3b1e. 。这里的情况不够清晰，一些不太常用的例程
是例外的 *note PyTuple_GetItem(): 3b1f. ， *note PyList_GetItem(): 3b20.
， *note PyDict_GetItem(): 3b21. ， *note PyDict_GetItemString(): 3b22.
都是返回从元组、列表、字典里借用的引用。

函数 *note PyImport_AddModule(): 3b23. 也会返回借用的引用，哪怕可能会返
回创建的对象：这个可能因为一个拥有的引用对象是存储在 ‘sys.modules’ 里。

当你传递一个对象引用到另一个函数时，通常函数是借用出去的。如果需要存储，
就使用 *note Py_INCREF(): 266. 来变成独立的拥有者。这个规则有两个重要的
例外： *note PyTuple_SetItem(): 3b24. 和 *note PyList_SetItem(): 3b25. 。
这些函数接受传递来的引用关系，哪怕会失败！(注意 *note PyDict_SetItem():
3b26. 及其同类不会接受引用关系，他们是"正常的")。

当一个C函数被Python调用时，会从调用方传来的参数借用引用。调用者拥有对象
的引用，所以借用的引用生命周期可以保证到函数返回。只要当借用的引用需要存
储或传递时，就必须转换为拥有的引用，通过调用 *note Py_INCREF(): 266. 。

Python调用从C函数返回的对象引用时必须是拥有的引用—拥有关系被从函数传递给
调用者。


File: python.info,  Node: 危险的薄冰,  Next: NULL指针,  Prev: 拥有规则,  Up: 引用计数

6.2.1.13 危险的薄冰
...................

有少数情况下，借用的引用看起来无害，但却可能导致问题。这通常是因为解释器
的隐式调用，并可能导致引用拥有者处置这个引用。

首先需要特别注意的情况是使用 *note Py_DECREF(): 267. 到一个无关对象，而
这个对象的引用是借用自一个列表的元素。举个实例：

     void
     bug(PyObject *list)
     {
         PyObject *item = PyList_GetItem(list, 0);

         PyList_SetItem(list, 1, PyLong_FromLong(0L));
         PyObject_Print(item, stdout, 0); /* BUG! */
     }

这个函数首先借用一个引用 ‘list[0]’ ，然后替换 ‘list[1]’ 为值 ‘0’ ，最后
打印借用的引用。看起来无害是吧，但却不是。

我们跟着控制流进入 *note PyList_SetItem(): 3b25. 。列表拥有者引用了其所
有成员，所以当成员1被替换时，就必须处置原来的成员1。现在假设原来的成员
1是用户定义类的实例，且假设这个类定义了 *note __del__(): 927. 方法。如果
这个类实例的引用计数是1，那么处置动作就会调用 *note __del__(): 927. 方法
。

既然是Python写的， *note __del__(): 927. 方法可以执行任意Python代码。是
否可能在 ‘bug()’ 的 ‘item’ 废止引用呢，是的。假设列表传递到 ‘bug()’ 会被
*note __del__(): 927. 方法所访问，就可以执行一个语句来实现 ‘del list[0]’
，然后假设这是最后一个对对象的引用，就需要释放内存，从而使得 ‘item’ 无效
化。

解决方法是，当你知道了问题的根源，就容易了：临时增加引用计数。正确版本的
函数代码如下：

     void
     no_bug(PyObject *list)
     {
         PyObject *item = PyList_GetItem(list, 0);

         Py_INCREF(item);
         PyList_SetItem(list, 1, PyLong_FromLong(0L));
         PyObject_Print(item, stdout, 0);
         Py_DECREF(item);
     }

这是个真实的故事。一个旧版本的Python包含了这个bug的变种，而一些人花费了
大量时间在C调试器上去寻找为什么 *note __del__(): 927. 方法会失败。

这个问题的第二种情况是借用的引用涉及线程的变种。通常，Python解释器里多个
线程无法进入对方的路径，因为有个全局锁保护着Python整个对象空间。但可以使
用宏 *note Py_BEGIN_ALLOW_THREADS: 3b29. 来临时释放这个锁，重新获取锁用
*note Py_END_ALLOW_THREADS: 2b6. 。这通常围绕在阻塞I/O调用外，使得其他线
程可以在等待I/O期间使用处理器。显然，如下函数会跟之前那个有一样的问题：

     void
     bug(PyObject *list)
     {
         PyObject *item = PyList_GetItem(list, 0);
         Py_BEGIN_ALLOW_THREADS
         ...some blocking I/O call...
         Py_END_ALLOW_THREADS
         PyObject_Print(item, stdout, 0); /* BUG! */
     }


File: python.info,  Node: NULL指针,  Prev: 危险的薄冰,  Up: 引用计数

6.2.1.14 NULL指针
.................

通常，接受对象引用作为参数的函数不希望你传给它们 ‘NULL’ 指针，并且当你这
样做时将会转储核心（或在以后导致核心转储）。 返回对象引用的函数通常只在
要指明发生了异常时才返回 ‘NULL’。 不检测 ‘NULL’ 参数的原因在于这些函数经
常要将它们所接收的对象传给其他函数 — 如果每个函数都检测 ‘NULL’，将会导致
大量的冗余检测而使代码运行得更缓慢。

更好的做法是仅在“源头”上检测 ‘NULL’，即在接收到一个可能为 ‘NULL’ 的指针
，例如来自 ‘malloc()’ 或是一个可能引发异常的函数的时候。

*note Py_INCREF(): 266. 和 *note Py_DECREF(): 267. 等宏不会检测 ‘NULL’ 指
针 — 但是，它们的变种 *note Py_XINCREF(): 268. 和 *note Py_XDECREF():
269. 则会检测。

用于检测特定对象类型的宏 (‘Pytype_Check()’) 不会检测 ‘NULL’ 指针 — 同样
地，有大量代码会连续调用这些宏来测试一个对象是否为几种不同预期类型之一，
这将会生成冗余的测试。 不存在带有 ‘NULL’ 检测的变体。

C 函数调用机制会保证传给 C 函数的参数 (本示例中为 ‘args’) 绝不会为
‘NULL’ — 实际上它会保证其总是为一个元组 (1)。

任何时候将 ‘NULL’ 指针“泄露”给 Python 用户都会是个严重的错误。

   ---------- Footnotes ----------

   (1) (4) 当你使用 "旧式" 风格调用约定时，这些保证不成立，尽管这依旧存
在于很多旧代码中。


File: python.info,  Node: 在C++中编写扩展,  Next: 给扩展模块提供C API,  Prev: 引用计数,  Up: 使用 C 或 C++ 扩展 Python

6.2.1.15 在C++中编写扩展
........................

还可以在C++中编写扩展模块，只是有些限制。如果主程序(Python解释器)是使用
C编译器来编译和链接的，全局或静态对象的构造器就不能使用。而如果是C++编译
器来链接的就没有这个问题。函数会被Python解释器调用(通常就是模块初始化函
数)必须声明为 ‘extern "C"’ 。而是否在 ‘extern "C" {...}’ 里包含Python头
文件则不是那么重要，因为如果定义了符号 ‘__cplusplus’ 则已经是这么声明的
了(所有现代C++编译器都会定义这个符号)。


File: python.info,  Node: 给扩展模块提供C API,  Prev: 在C++中编写扩展,  Up: 使用 C 或 C++ 扩展 Python

6.2.1.16 给扩展模块提供C API
............................

很多扩展模块提供了新的函数和类型供Python使用，但有时扩展模块里的代码也可
以被其他扩展模块使用。例如，一个扩展模块可以实现一个类型 "collection" 看
起来是没有顺序的。就像是Python列表类型，拥有C API允许扩展模块来创建和维
护列表，这个新的集合类型可以有一堆C函数用于给其他扩展模块直接使用。

开始看起来很简单：只需要编写函数(无需声明为 ‘static’ )，提供恰当的头文件
，以及C API的文档。实际上在所有扩展模块都是静态链接到Python解释器时也是
可以正常工作的。当模块以共享库链接时，一个模块中的符号定义对另一个模块不
可见。可见的细节依赖于操作系统，一些系统的Python解释器使用全局命名空间
(例如Windows)，有些则在链接时需要一个严格的已导入符号列表(一个例子是
AIX)，或者提供可选的不同策略(如Unix系列)。即便是符号是全局可见的，你要调
用的模块也可能尚未加载。

可移植性需要不能对符号可见性做任何假设。这意味着扩展模块里的所有符号都应
该声明为 ‘static’ ，除了模块的初始化函数，来避免与其他扩展模块的命名冲突
(在段落 *note 模块方法表和初始化函数: 3b08. 中讨论) 。这意味着符号应该
`必须' 通过其他导出方式来供其他扩展模块访问。

Python提供了一个特别的机制来传递C级别信息(指针)，从一个扩展模块到另一个
：Capsules。一个Capsule是一个Python数据类型，会保存指针( ‘void *’ )。
Capsule只能通过其C API来创建和访问，但可以像其他Python对象一样的传递。通
常，我们可以指定一个扩展模块命名空间的名字。其他扩展模块可以导入这个模块
，获取这个名字的值，然后从Capsule获取指针。

Capsule可以用多种方式导出C API给扩展模块。每个函数可以用自己的Capsule，
或者所有C API指针可以存储在一个数组里，数组地址再发布给Capsule。存储和获
取指针也可以用多种方式，供客户端模块使用。

无论你选择哪个方法，正确地为你的 Capsule 命名都很重要。 函数 *note
PyCapsule_New(): 3b2f. 接受一个名称形参 (‘const char *’)；允许你传入一个
‘NULL’ 作为名称，但我们强烈建议你指定一个名称。 正确地命名的 Capsule 提
供了一定程序的运行时类型安全；没有可行的方式能区分两个未命名的 Capsule。

通常来说，Capsule用于暴露C API，其名字应该遵循如下规范：

     modulename.attributename

便利函数 *note PyCapsule_Import(): 3b30. 可以方便的载入通过Capsule提供的
C API，仅在Capsule的名字匹配时。这个行为为C API用户提供了高度的确定性来
载入正确的C API。

如下例子展示了将大部分负担交由导出模块作者的方法，适用于常用的库模块。其
会存储所有C API指针(例子里只有一个)在 ‘void’ 指针的数组里，并使其值变为
Capsule。对应的模块头文件提供了宏来管理导入模块和获取C API指针；客户端模
块只需要在访问C API前调用这个宏即可。

导出的模块修改自 ‘spam’ 模块，来自 *note 一个简单的例子: 3afb. 段落。函
数 ‘spam.system()’ 不会直接调用C库函数 ‘system()’ ，但一个函数
‘PySpam_System()’ 会负责调用，当然现实中会更复杂些(例如添加 "spam" 到每
个命令)。函数 ‘PySpam_System()’ 也会导出给其他扩展模块。

函数 ‘PySpam_System()’ 是个纯C函数，声明 ‘static’ 就像其他地方那样:

     static int
     PySpam_System(const char *command)
     {
         return system(command);
     }

函数 ‘spam_system()’ 按照如下方式修改:

     static PyObject *
     spam_system(PyObject *self, PyObject *args)
     {
         const char *command;
         int sts;

         if (!PyArg_ParseTuple(args, "s", &command))
             return NULL;
         sts = PySpam_System(command);
         return PyLong_FromLong(sts);
     }

在模块开头，在此行后:

     #include <Python.h>

添加另外两行:

     #define SPAM_MODULE
     #include "spammodule.h"

‘#define’ 用于告知头文件需要包含给导出的模块，而不是客户端模块。最终，模
块的初始化函数必须负责初始化C API指针数组:

     PyMODINIT_FUNC
     PyInit_spam(void)
     {
         PyObject *m;
         static void *PySpam_API[PySpam_API_pointers];
         PyObject *c_api_object;

         m = PyModule_Create(&spammodule);
         if (m == NULL)
             return NULL;

         /* Initialize the C API pointer array */
         PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;

         /* Create a Capsule containing the API pointer array's address */
         c_api_object = PyCapsule_New((void *)PySpam_API, "spam._C_API", NULL);

         if (PyModule_AddObject(m, "_C_API", c_api_object) < 0) {
             Py_XDECREF(c_api_object);
             Py_DECREF(m);
             return NULL;
         }

         return m;
     }

注意 ‘PySpam_API’ 声明为 ‘static’ ；此外指针数组会在 ‘PyInit_spam()’ 结
束后消失!

头文件 ‘spammodule.h’ 里的一堆工作，看起来如下所示:

     #ifndef Py_SPAMMODULE_H
     #define Py_SPAMMODULE_H
     #ifdef __cplusplus
     extern "C" {
     #endif

     /* Header file for spammodule */

     /* C API functions */
     #define PySpam_System_NUM 0
     #define PySpam_System_RETURN int
     #define PySpam_System_PROTO (const char *command)

     /* Total number of C API pointers */
     #define PySpam_API_pointers 1


     #ifdef SPAM_MODULE
     /* This section is used when compiling spammodule.c */

     static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;

     #else
     /* This section is used in modules that use spammodule's API */

     static void **PySpam_API;

     #define PySpam_System \
      (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])

     /* Return -1 on error, 0 on success.
      * PyCapsule_Import will set an exception if there's an error.
      */
     static int
     import_spam(void)
     {
         PySpam_API = (void **)PyCapsule_Import("spam._C_API", 0);
         return (PySpam_API != NULL) ? 0 : -1;
     }

     #endif

     #ifdef __cplusplus
     }
     #endif

     #endif /* !defined(Py_SPAMMODULE_H) */

客户端模块必须在其初始化函数里按顺序调用函数 ‘import_spam()’ (或其他宏
)才能访问函数 ‘PySpam_System()’ 。

     PyMODINIT_FUNC
     PyInit_client(void)
     {
         PyObject *m;

         m = PyModule_Create(&clientmodule);
         if (m == NULL)
             return NULL;
         if (import_spam() < 0)
             return NULL;
         /* additional initialization can happen here */
         return m;
     }

这种方法的主要缺点是，文件 ‘spammodule.h’ 过于复杂。当然，对每个要导出的
函数，基本结构是相似的，所以只需要学习一次。

最后需要提醒的是Capsule提供了额外的功能，用于存储在Capsule里的指针的内存
分配和释放。细节参考 Python/C API参考手册的章节 *note 胶囊: 3b31. 和
Capsule的实现(在Python源码发行包的 ‘Include/pycapsule.h’ 和
‘Objects/pycapsule.c’ )。

备注
....


File: python.info,  Node: 自定义扩展类型：教程,  Next: 定义扩展类型：已分类主题,  Prev: 使用 C 或 C++ 扩展 Python,  Up: 不使用第三方工具创建扩展

6.2.2 自定义扩展类型：教程
--------------------------

Python 允许编写 C 扩展模块定义可以从 Python 代码中操纵的新类型，这很像内
置的 *note str: 339. 和 *note list: 263. 类型。所有扩展类型的代码都遵循
一个模式，但是在您开始之前，您需要了解一些细节。这份文件是对这个主题介绍
。

* Menu:

* 基础::
* Adding data and methods to the Basic example::
* Providing finer control over data attributes::
* Supporting cyclic garbage collection::
* Subclassing other types::


File: python.info,  Node: 基础,  Next: Adding data and methods to the Basic example,  Up: 自定义扩展类型：教程

6.2.2.1 基础
............

*note CPython: 1446. 运行时将所有 Python 对象都视为类型 *note PyObject*:
4c2. 的变量，即所有 Python 对象的"基础类型"。 *note PyObject: 4c2. 结构
体本身包含了对象的 *note reference count: 3b37. 和对象的"类型对象"。 类
型对象确定解释器需要调用哪些 (C) 函数，例如一个属性查询一个对象，一个方
法调用，或者与另一个对象相乘。 这些 C 函数被称为“类型方法”。

所以，如果你想要定义新的扩展类型，需要创建新的类型对象。

这类事情只能用例子解释，这里用一个最小化但完整的的模块，定义了新的类型叫
做 ‘Custom’ 在C扩展模块 ‘custom’ 里。

     注解: 这里展示的方法是定义 `static' 扩展类型的传统方法。可以适合大
     部分用途。C API也可以定义在堆上分配的扩展类型，使用 *note
     PyType_FromSpec(): 2d2. 函数，但不在本入门里讨论。

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>

     typedef struct {
         PyObject_HEAD
         /* Type-specific fields go here. */
     } CustomObject;

     static PyTypeObject CustomType = {
         PyVarObject_HEAD_INIT(NULL, 0)
         .tp_name = "custom.Custom",
         .tp_doc = "Custom objects",
         .tp_basicsize = sizeof(CustomObject),
         .tp_itemsize = 0,
         .tp_flags = Py_TPFLAGS_DEFAULT,
         .tp_new = PyType_GenericNew,
     };

     static PyModuleDef custommodule = {
         PyModuleDef_HEAD_INIT,
         .m_name = "custom",
         .m_doc = "Example module that creates an extension type.",
         .m_size = -1,
     };

     PyMODINIT_FUNC
     PyInit_custom(void)
     {
         PyObject *m;
         if (PyType_Ready(&CustomType) < 0)
             return NULL;

         m = PyModule_Create(&custommodule);
         if (m == NULL)
             return NULL;

         Py_INCREF(&CustomType);
         if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
             Py_DECREF(&CustomType);
             Py_DECREF(m);
             return NULL;
         }

         return m;
     }

这部分很容易理解，这是为了跟上一章能对接上。这个文件定义了三件事：

  1. ‘Custom’ 类的对象 `object' 包含了： ‘CustomObject’ 结构，这会为每个
     ‘Custom’ 实例分配一次。

  2. ‘Custom’ `type' 的行为：这是 ‘CustomType’ 结构体，其定义了一堆标识
     和函数指针，会指向解释器里请求的操作。

  3. 初始化 ‘custom’ 模块： ‘PyInit_custom’ 函数和对应的 ‘custommodule’
     结构体。

结构的第一块是

     typedef struct {
         PyObject_HEAD
     } CustomObject;

这就是一个自定义对象所包含的。 ‘PyObject_HEAD’ 是强制要求必须在每个对象
结构体之前，用以定义一个类型为 *note PyObject: 4c2. 的字段叫 ‘ob_base’ ，
包含了一个指针指向类型对象和一个引用计数(这可以用宏 *note Py_REFCNT:
3b38. 和 *note Py_TYPE: 3b39. 来区分)。用宏来抽象，使得附加字段可以用调
试构建。

     注解: 注意在宏 *note PyObject_HEAD: c7a. 后没有分号。意外添加分号会
     导致编译器提示出错。

当然，对象除了在 ‘PyObject_HEAD’ 存储数据外，还有额外数据；例如，如下定
义了标准的Python浮点数:

     typedef struct {
         PyObject_HEAD
         double ob_fval;
     } PyFloatObject;

第二个位是类型对象的定义:

     static PyTypeObject CustomType = {
         PyVarObject_HEAD_INIT(NULL, 0)
         .tp_name = "custom.Custom",
         .tp_doc = "Custom objects",
         .tp_basicsize = sizeof(CustomObject),
         .tp_itemsize = 0,
         .tp_flags = Py_TPFLAGS_DEFAULT,
         .tp_new = PyType_GenericNew,
     };

     注解: 推荐使用如上C99风格的初始化，以避免列出所有的 *note
     PyTypeObject: 2d7. 字段，其中很多是你不需要关心的，这样也可以避免关
     注字段的定义顺序。

在 ‘object.h’ 中实际定义的 *note PyTypeObject: 2d7. 具有比如上定义更多的
*note 字段: 3b3a.。 剩余的字段会由 C 编译器用零来填充，通常的做法是不显
式地指定它们，除非你确实需要它们。

我们先挑选一部分，每次一个字段:

     PyVarObject_HEAD_INIT(NULL, 0)

这一行是强制的样板，用以初始化如上提到的 ‘ob_base’ 字段:

     .tp_name = "custom.Custom",

我们的类型的名称。 这将出现在我们的对象的默认文本表示形式和某些错误消息
中，例如:

     >>> "" + custom.Custom()
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: can only concatenate str (not "custom.Custom") to str

Note that the name is a dotted name that includes both the module name
and the name of the type within the module.  The module in this case is
‘custom’ and the type is ‘Custom’, so we set the type name to
‘custom.Custom’.  Using the real dotted import path is important to make
your type compatible with the *note pydoc: da. and *note pickle: cb.
modules.

     .tp_basicsize = sizeof(CustomObject),
     .tp_itemsize = 0,

This is so that Python knows how much memory to allocate when creating
new ‘Custom’ instances.  *note tp_itemsize: 3b3b. is only used for
variable-sized objects and should otherwise be zero.

     注解: If you want your type to be subclassable from Python, and
     your type has the same *note tp_basicsize: 3b3c. as its base type,
     you may have problems with multiple inheritance.  A Python subclass
     of your type will have to list your type first in its *note
     __bases__: e11, or else it will not be able to call your type’s
     *note __new__(): 892. method without getting an error.  You can
     avoid this problem by ensuring that your type has a larger value
     for *note tp_basicsize: 3b3c. than its base type does.  Most of the
     time, this will be true anyway, because either your base type will
     be *note object: 2b1, or else you will be adding data members to
     your base type, and therefore increasing its size.

We set the class flags to *note Py_TPFLAGS_DEFAULT: 3b3d.

     .tp_flags = Py_TPFLAGS_DEFAULT,

All types should include this constant in their flags.  It enables all
of the members defined until at least Python 3.3.  If you need further
members, you will need to OR the corresponding flags.

We provide a doc string for the type in *note tp_doc: 3b3e.

     .tp_doc = "Custom objects",

To enable object creation, we have to provide a *note tp_new: 3b3f.
handler.  This is the equivalent of the Python method *note __new__():
892, but has to be specified explicitly.  In this case, we can just use
the default implementation provided by the API function *note
PyType_GenericNew(): 3b40.

     .tp_new = PyType_GenericNew,

Everything else in the file should be familiar, except for some code in
‘PyInit_custom()’:

     if (PyType_Ready(&CustomType) < 0)
         return;

This initializes the ‘Custom’ type, filling in a number of members to
the appropriate default values, including ‘ob_type’ that we initially
set to ‘NULL’.

     Py_INCREF(&CustomType);
     if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
         Py_DECREF(&CustomType);
         Py_DECREF(m);
         return NULL;
     }

This adds the type to the module dictionary.  This allows us to create
‘Custom’ instances by calling the ‘Custom’ class:

     >>> import custom
     >>> mycustom = custom.Custom()

That’s it!  All that remains is to build it; put the above code in a
file called ‘custom.c’ and:

     from distutils.core import setup, Extension
     setup(name="custom", version="1.0",
           ext_modules=[Extension("custom", ["custom.c"])])

in a file called ‘setup.py’; then typing

     $ python setup.py build

at a shell should produce a file ‘custom.so’ in a subdirectory; move to
that directory and fire up Python — you should be able to ‘import
custom’ and play around with Custom objects.

这并不难，对吗？

Of course, the current Custom type is pretty uninteresting.  It has no
data and doesn’t do anything.  It can’t even be subclassed.

     注解: While this documentation showcases the standard *note
     distutils: 39. module for building C extensions, it is recommended
     in real-world use cases to use the newer and better-maintained
     ‘setuptools’ library.  Documentation on how to do this is out of
     scope for this document and can be found in the Python Packaging
     User’s Guide(1).

   ---------- Footnotes ----------

   (1) https://packaging.python.org/tutorials/distributing-packages/


File: python.info,  Node: Adding data and methods to the Basic example,  Next: Providing finer control over data attributes,  Prev: 基础,  Up: 自定义扩展类型：教程

6.2.2.2 Adding data and methods to the Basic example
....................................................

Let’s extend the basic example to add some data and methods.  Let’s also
make the type usable as a base class.  We’ll create a new module,
‘custom2’ that adds these capabilities:

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>
     #include "structmember.h"

     typedef struct {
         PyObject_HEAD
         PyObject *first; /* first name */
         PyObject *last;  /* last name */
         int number;
     } CustomObject;

     static void
     Custom_dealloc(CustomObject *self)
     {
         Py_XDECREF(self->first);
         Py_XDECREF(self->last);
         Py_TYPE(self)->tp_free((PyObject *) self);
     }

     static PyObject *
     Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
     {
         CustomObject *self;
         self = (CustomObject *) type->tp_alloc(type, 0);
         if (self != NULL) {
             self->first = PyUnicode_FromString("");
             if (self->first == NULL) {
                 Py_DECREF(self);
                 return NULL;
             }
             self->last = PyUnicode_FromString("");
             if (self->last == NULL) {
                 Py_DECREF(self);
                 return NULL;
             }
             self->number = 0;
         }
         return (PyObject *) self;
     }

     static int
     Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
     {
         static char *kwlist[] = {"first", "last", "number", NULL};
         PyObject *first = NULL, *last = NULL, *tmp;

         if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
                                          &first, &last,
                                          &self->number))
             return -1;

         if (first) {
             tmp = self->first;
             Py_INCREF(first);
             self->first = first;
             Py_XDECREF(tmp);
         }
         if (last) {
             tmp = self->last;
             Py_INCREF(last);
             self->last = last;
             Py_XDECREF(tmp);
         }
         return 0;
     }

     static PyMemberDef Custom_members[] = {
         {"first", T_OBJECT_EX, offsetof(CustomObject, first), 0,
          "first name"},
         {"last", T_OBJECT_EX, offsetof(CustomObject, last), 0,
          "last name"},
         {"number", T_INT, offsetof(CustomObject, number), 0,
          "custom number"},
         {NULL}  /* Sentinel */
     };

     static PyObject *
     Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
     {
         if (self->first == NULL) {
             PyErr_SetString(PyExc_AttributeError, "first");
             return NULL;
         }
         if (self->last == NULL) {
             PyErr_SetString(PyExc_AttributeError, "last");
             return NULL;
         }
         return PyUnicode_FromFormat("%S %S", self->first, self->last);
     }

     static PyMethodDef Custom_methods[] = {
         {"name", (PyCFunction) Custom_name, METH_NOARGS,
          "Return the name, combining the first and last name"
         },
         {NULL}  /* Sentinel */
     };

     static PyTypeObject CustomType = {
         PyVarObject_HEAD_INIT(NULL, 0)
         .tp_name = "custom2.Custom",
         .tp_doc = "Custom objects",
         .tp_basicsize = sizeof(CustomObject),
         .tp_itemsize = 0,
         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
         .tp_new = Custom_new,
         .tp_init = (initproc) Custom_init,
         .tp_dealloc = (destructor) Custom_dealloc,
         .tp_members = Custom_members,
         .tp_methods = Custom_methods,
     };

     static PyModuleDef custommodule = {
         PyModuleDef_HEAD_INIT,
         .m_name = "custom2",
         .m_doc = "Example module that creates an extension type.",
         .m_size = -1,
     };

     PyMODINIT_FUNC
     PyInit_custom2(void)
     {
         PyObject *m;
         if (PyType_Ready(&CustomType) < 0)
             return NULL;

         m = PyModule_Create(&custommodule);
         if (m == NULL)
             return NULL;

         Py_INCREF(&CustomType);
         if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
             Py_DECREF(&CustomType);
             Py_DECREF(m);
             return NULL;
         }

         return m;
     }

This version of the module has a number of changes.

We’ve added an extra include:

     #include <structmember.h>

This include provides declarations that we use to handle attributes, as
described a bit later.

The ‘Custom’ type now has three data attributes in its C struct,
`first', `last', and `number'.  The `first' and `last' variables are
Python strings containing first and last names.  The `number' attribute
is a C integer.

The object structure is updated accordingly:

     typedef struct {
         PyObject_HEAD
         PyObject *first; /* first name */
         PyObject *last;  /* last name */
         int number;
     } CustomObject;

Because we now have data to manage, we have to be more careful about
object allocation and deallocation.  At a minimum, we need a
deallocation method:

     static void
     Custom_dealloc(CustomObject *self)
     {
         Py_XDECREF(self->first);
         Py_XDECREF(self->last);
         Py_TYPE(self)->tp_free((PyObject *) self);
     }

which is assigned to the *note tp_dealloc: 3b42. member:

     .tp_dealloc = (destructor) Custom_dealloc,

This method first clears the reference counts of the two Python
attributes.  *note Py_XDECREF(): 269. correctly handles the case where
its argument is ‘NULL’ (which might happen here if ‘tp_new’ failed
midway).  It then calls the *note tp_free: 3b43. member of the object’s
type (computed by ‘Py_TYPE(self)’) to free the object’s memory.  Note
that the object’s type might not be ‘CustomType’, because the object may
be an instance of a subclass.

     注解: The explicit cast to ‘destructor’ above is needed because we
     defined ‘Custom_dealloc’ to take a ‘CustomObject *’ argument, but
     the ‘tp_dealloc’ function pointer expects to receive a ‘PyObject *’
     argument.  Otherwise, the compiler will emit a warning.  This is
     object-oriented polymorphism, in C!

We want to make sure that the first and last names are initialized to
empty strings, so we provide a ‘tp_new’ implementation:

     static PyObject *
     Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
     {
         CustomObject *self;
         self = (CustomObject *) type->tp_alloc(type, 0);
         if (self != NULL) {
             self->first = PyUnicode_FromString("");
             if (self->first == NULL) {
                 Py_DECREF(self);
                 return NULL;
             }
             self->last = PyUnicode_FromString("");
             if (self->last == NULL) {
                 Py_DECREF(self);
                 return NULL;
             }
             self->number = 0;
         }
         return (PyObject *) self;
     }

and install it in the *note tp_new: 3b3f. member:

     .tp_new = Custom_new,

The ‘tp_new’ handler is responsible for creating (as opposed to
initializing) objects of the type.  It is exposed in Python as the *note
__new__(): 892. method.  It is not required to define a ‘tp_new’ member,
and indeed many extension types will simply reuse *note
PyType_GenericNew(): 3b40. as done in the first version of the ‘Custom’
type above.  In this case, we use the ‘tp_new’ handler to initialize the
‘first’ and ‘last’ attributes to non-‘NULL’ default values.

‘tp_new’ is passed the type being instantiated (not necessarily
‘CustomType’, if a subclass is instantiated) and any arguments passed
when the type was called, and is expected to return the instance
created.  ‘tp_new’ handlers always accept positional and keyword
arguments, but they often ignore the arguments, leaving the argument
handling to initializer (a.k.a.  ‘tp_init’ in C or ‘__init__’ in Python)
methods.

     注解: ‘tp_new’ shouldn’t call ‘tp_init’ explicitly, as the
     interpreter will do it itself.

The ‘tp_new’ implementation calls the *note tp_alloc: 3b44. slot to
allocate memory:

     self = (CustomObject *) type->tp_alloc(type, 0);

Since memory allocation may fail, we must check the *note tp_alloc:
3b44. result against ‘NULL’ before proceeding.

     注解: We didn’t fill the *note tp_alloc: 3b44. slot ourselves.
     Rather *note PyType_Ready(): 3b45. fills it for us by inheriting it
     from our base class, which is *note object: 2b1. by default.  Most
     types use the default allocation strategy.

     注解: If you are creating a co-operative *note tp_new: 3b3f. (one
     that calls a base type’s *note tp_new: 3b3f. or *note __new__():
     892.), you must `not' try to determine what method to call using
     method resolution order at runtime.  Always statically determine
     what type you are going to call, and call its *note tp_new: 3b3f.
     directly, or via ‘type->tp_base->tp_new’.  If you do not do this,
     Python subclasses of your type that also inherit from other
     Python-defined classes may not work correctly.  (Specifically, you
     may not be able to create instances of such subclasses without
     getting a *note TypeError: 193.)

We also define an initialization function which accepts arguments to
provide initial values for our instance:

     static int
     Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
     {
         static char *kwlist[] = {"first", "last", "number", NULL};
         PyObject *first = NULL, *last = NULL, *tmp;

         if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
                                          &first, &last,
                                          &self->number))
             return -1;

         if (first) {
             tmp = self->first;
             Py_INCREF(first);
             self->first = first;
             Py_XDECREF(tmp);
         }
         if (last) {
             tmp = self->last;
             Py_INCREF(last);
             self->last = last;
             Py_XDECREF(tmp);
         }
         return 0;
     }

by filling the *note tp_init: 3b46. slot.

     .tp_init = (initproc) Custom_init,

The *note tp_init: 3b46. slot is exposed in Python as the *note
__init__(): d66. method.  It is used to initialize an object after it’s
created.  Initializers always accept positional and keyword arguments,
and they should return either ‘0’ on success or ‘-1’ on error.

Unlike the ‘tp_new’ handler, there is no guarantee that ‘tp_init’ is
called at all (for example, the *note pickle: cb. module by default
doesn’t call *note __init__(): d66. on unpickled instances).  It can
also be called multiple times.  Anyone can call the *note __init__():
d66. method on our objects.  For this reason, we have to be extra
careful when assigning the new attribute values.  We might be tempted,
for example to assign the ‘first’ member like this:

     if (first) {
         Py_XDECREF(self->first);
         Py_INCREF(first);
         self->first = first;
     }

But this would be risky.  Our type doesn’t restrict the type of the
‘first’ member, so it could be any kind of object.  It could have a
destructor that causes code to be executed that tries to access the
‘first’ member; or that destructor could release the *note Global
interpreter Lock: bf2. and let arbitrary code run in other threads that
accesses and modifies our object.

To be paranoid and protect ourselves against this possibility, we almost
always reassign members before decrementing their reference counts.
When don’t we have to do this?

   * when we absolutely know that the reference count is greater than 1;

   * when we know that deallocation of the object (1) will neither
     release the *note GIL: bf2. nor cause any calls back into our
     type’s code;

   * when decrementing a reference count in a *note tp_dealloc: 3b42.
     handler on a type which doesn’t support cyclic garbage collection
     (2).

We want to expose our instance variables as attributes.  There are a
number of ways to do that.  The simplest way is to define member
definitions:

     static PyMemberDef Custom_members[] = {
         {"first", T_OBJECT_EX, offsetof(CustomObject, first), 0,
          "first name"},
         {"last", T_OBJECT_EX, offsetof(CustomObject, last), 0,
          "last name"},
         {"number", T_INT, offsetof(CustomObject, number), 0,
          "custom number"},
         {NULL}  /* Sentinel */
     };

and put the definitions in the *note tp_members: 3b47. slot:

     .tp_members = Custom_members,

Each member definition has a member name, type, offset, access flags and
documentation string.  See the *note 泛型属性管理: 3b48. section below
for details.

A disadvantage of this approach is that it doesn’t provide a way to
restrict the types of objects that can be assigned to the Python
attributes.  We expect the first and last names to be strings, but any
Python objects can be assigned.  Further, the attributes can be deleted,
setting the C pointers to ‘NULL’.  Even though we can make sure the
members are initialized to non-‘NULL’ values, the members can be set to
‘NULL’ if the attributes are deleted.

We define a single method, ‘Custom.name()’, that outputs the objects
name as the concatenation of the first and last names.

     static PyObject *
     Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
     {
         if (self->first == NULL) {
             PyErr_SetString(PyExc_AttributeError, "first");
             return NULL;
         }
         if (self->last == NULL) {
             PyErr_SetString(PyExc_AttributeError, "last");
             return NULL;
         }
         return PyUnicode_FromFormat("%S %S", self->first, self->last);
     }

The method is implemented as a C function that takes a ‘Custom’ (or
‘Custom’ subclass) instance as the first argument.  Methods always take
an instance as the first argument.  Methods often take positional and
keyword arguments as well, but in this case we don’t take any and don’t
need to accept a positional argument tuple or keyword argument
dictionary.  This method is equivalent to the Python method:

     def name(self):
         return "%s %s" % (self.first, self.last)

Note that we have to check for the possibility that our ‘first’ and
‘last’ members are ‘NULL’.  This is because they can be deleted, in
which case they are set to ‘NULL’.  It would be better to prevent
deletion of these attributes and to restrict the attribute values to be
strings.  We’ll see how to do that in the next section.

Now that we’ve defined the method, we need to create an array of method
definitions:

     static PyMethodDef Custom_methods[] = {
         {"name", (PyCFunction) Custom_name, METH_NOARGS,
          "Return the name, combining the first and last name"
         },
         {NULL}  /* Sentinel */
     };

(note that we used the *note METH_NOARGS: e20. flag to indicate that the
method is expecting no arguments other than `self')

and assign it to the *note tp_methods: 3b49. slot:

     .tp_methods = Custom_methods,

Finally, we’ll make our type usable as a base class for subclassing.
We’ve written our methods carefully so far so that they don’t make any
assumptions about the type of the object being created or used, so all
we need to do is to add the *note Py_TPFLAGS_BASETYPE: 3b4a. to our
class flag definition:

     .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,

We rename ‘PyInit_custom()’ to ‘PyInit_custom2()’, update the module
name in the *note PyModuleDef: 3b4b. struct, and update the full class
name in the *note PyTypeObject: 2d7. struct.

Finally, we update our ‘setup.py’ file to build the new module:

     from distutils.core import setup, Extension
     setup(name="custom", version="1.0",
           ext_modules=[
              Extension("custom", ["custom.c"]),
              Extension("custom2", ["custom2.c"]),
              ])

   ---------- Footnotes ----------

   (1) (1) This is true when we know that the object is a basic type,
like a string or a float.

   (2) (2) We relied on this in the *note tp_dealloc: 3b42. handler in
this example, because our type doesn’t support garbage collection.


File: python.info,  Node: Providing finer control over data attributes,  Next: Supporting cyclic garbage collection,  Prev: Adding data and methods to the Basic example,  Up: 自定义扩展类型：教程

6.2.2.3 Providing finer control over data attributes
....................................................

In this section, we’ll provide finer control over how the ‘first’ and
‘last’ attributes are set in the ‘Custom’ example.  In the previous
version of our module, the instance variables ‘first’ and ‘last’ could
be set to non-string values or even deleted.  We want to make sure that
these attributes always contain strings.

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>
     #include "structmember.h"

     typedef struct {
         PyObject_HEAD
         PyObject *first; /* first name */
         PyObject *last;  /* last name */
         int number;
     } CustomObject;

     static void
     Custom_dealloc(CustomObject *self)
     {
         Py_XDECREF(self->first);
         Py_XDECREF(self->last);
         Py_TYPE(self)->tp_free((PyObject *) self);
     }

     static PyObject *
     Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
     {
         CustomObject *self;
         self = (CustomObject *) type->tp_alloc(type, 0);
         if (self != NULL) {
             self->first = PyUnicode_FromString("");
             if (self->first == NULL) {
                 Py_DECREF(self);
                 return NULL;
             }
             self->last = PyUnicode_FromString("");
             if (self->last == NULL) {
                 Py_DECREF(self);
                 return NULL;
             }
             self->number = 0;
         }
         return (PyObject *) self;
     }

     static int
     Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
     {
         static char *kwlist[] = {"first", "last", "number", NULL};
         PyObject *first = NULL, *last = NULL, *tmp;

         if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
                                          &first, &last,
                                          &self->number))
             return -1;

         if (first) {
             tmp = self->first;
             Py_INCREF(first);
             self->first = first;
             Py_DECREF(tmp);
         }
         if (last) {
             tmp = self->last;
             Py_INCREF(last);
             self->last = last;
             Py_DECREF(tmp);
         }
         return 0;
     }

     static PyMemberDef Custom_members[] = {
         {"number", T_INT, offsetof(CustomObject, number), 0,
          "custom number"},
         {NULL}  /* Sentinel */
     };

     static PyObject *
     Custom_getfirst(CustomObject *self, void *closure)
     {
         Py_INCREF(self->first);
         return self->first;
     }

     static int
     Custom_setfirst(CustomObject *self, PyObject *value, void *closure)
     {
         PyObject *tmp;
         if (value == NULL) {
             PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
             return -1;
         }
         if (!PyUnicode_Check(value)) {
             PyErr_SetString(PyExc_TypeError,
                             "The first attribute value must be a string");
             return -1;
         }
         tmp = self->first;
         Py_INCREF(value);
         self->first = value;
         Py_DECREF(tmp);
         return 0;
     }

     static PyObject *
     Custom_getlast(CustomObject *self, void *closure)
     {
         Py_INCREF(self->last);
         return self->last;
     }

     static int
     Custom_setlast(CustomObject *self, PyObject *value, void *closure)
     {
         PyObject *tmp;
         if (value == NULL) {
             PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute");
             return -1;
         }
         if (!PyUnicode_Check(value)) {
             PyErr_SetString(PyExc_TypeError,
                             "The last attribute value must be a string");
             return -1;
         }
         tmp = self->last;
         Py_INCREF(value);
         self->last = value;
         Py_DECREF(tmp);
         return 0;
     }

     static PyGetSetDef Custom_getsetters[] = {
         {"first", (getter) Custom_getfirst, (setter) Custom_setfirst,
          "first name", NULL},
         {"last", (getter) Custom_getlast, (setter) Custom_setlast,
          "last name", NULL},
         {NULL}  /* Sentinel */
     };

     static PyObject *
     Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
     {
         return PyUnicode_FromFormat("%S %S", self->first, self->last);
     }

     static PyMethodDef Custom_methods[] = {
         {"name", (PyCFunction) Custom_name, METH_NOARGS,
          "Return the name, combining the first and last name"
         },
         {NULL}  /* Sentinel */
     };

     static PyTypeObject CustomType = {
         PyVarObject_HEAD_INIT(NULL, 0)
         .tp_name = "custom3.Custom",
         .tp_doc = "Custom objects",
         .tp_basicsize = sizeof(CustomObject),
         .tp_itemsize = 0,
         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
         .tp_new = Custom_new,
         .tp_init = (initproc) Custom_init,
         .tp_dealloc = (destructor) Custom_dealloc,
         .tp_members = Custom_members,
         .tp_methods = Custom_methods,
         .tp_getset = Custom_getsetters,
     };

     static PyModuleDef custommodule = {
         PyModuleDef_HEAD_INIT,
         .m_name = "custom3",
         .m_doc = "Example module that creates an extension type.",
         .m_size = -1,
     };

     PyMODINIT_FUNC
     PyInit_custom3(void)
     {
         PyObject *m;
         if (PyType_Ready(&CustomType) < 0)
             return NULL;

         m = PyModule_Create(&custommodule);
         if (m == NULL)
             return NULL;

         Py_INCREF(&CustomType);
         if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
             Py_DECREF(&CustomType);
             Py_DECREF(m);
             return NULL;
         }

         return m;
     }

To provide greater control, over the ‘first’ and ‘last’ attributes,
we’ll use custom getter and setter functions.  Here are the functions
for getting and setting the ‘first’ attribute:

     static PyObject *
     Custom_getfirst(CustomObject *self, void *closure)
     {
         Py_INCREF(self->first);
         return self->first;
     }

     static int
     Custom_setfirst(CustomObject *self, PyObject *value, void *closure)
     {
         PyObject *tmp;
         if (value == NULL) {
             PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
             return -1;
         }
         if (!PyUnicode_Check(value)) {
             PyErr_SetString(PyExc_TypeError,
                             "The first attribute value must be a string");
             return -1;
         }
         tmp = self->first;
         Py_INCREF(value);
         self->first = value;
         Py_DECREF(tmp);
         return 0;
     }

The getter function is passed a ‘Custom’ object and a "closure", which
is a void pointer.  In this case, the closure is ignored.  (The closure
supports an advanced usage in which definition data is passed to the
getter and setter.  This could, for example, be used to allow a single
set of getter and setter functions that decide the attribute to get or
set based on data in the closure.)

The setter function is passed the ‘Custom’ object, the new value, and
the closure.  The new value may be ‘NULL’, in which case the attribute
is being deleted.  In our setter, we raise an error if the attribute is
deleted or if its new value is not a string.

We create an array of *note PyGetSetDef: 42f. structures:

     static PyGetSetDef Custom_getsetters[] = {
         {"first", (getter) Custom_getfirst, (setter) Custom_setfirst,
          "first name", NULL},
         {"last", (getter) Custom_getlast, (setter) Custom_setlast,
          "last name", NULL},
         {NULL}  /* Sentinel */
     };

and register it in the *note tp_getset: 3b4d. slot:

     .tp_getset = Custom_getsetters,

The last item in a *note PyGetSetDef: 42f. structure is the "closure"
mentioned above.  In this case, we aren’t using a closure, so we just
pass ‘NULL’.

We also remove the member definitions for these attributes:

     static PyMemberDef Custom_members[] = {
         {"number", T_INT, offsetof(CustomObject, number), 0,
          "custom number"},
         {NULL}  /* Sentinel */
     };

We also need to update the *note tp_init: 3b46. handler to only allow
strings (1) to be passed:

     static int
     Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
     {
         static char *kwlist[] = {"first", "last", "number", NULL};
         PyObject *first = NULL, *last = NULL, *tmp;

         if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
                                          &first, &last,
                                          &self->number))
             return -1;

         if (first) {
             tmp = self->first;
             Py_INCREF(first);
             self->first = first;
             Py_DECREF(tmp);
         }
         if (last) {
             tmp = self->last;
             Py_INCREF(last);
             self->last = last;
             Py_DECREF(tmp);
         }
         return 0;
     }

With these changes, we can assure that the ‘first’ and ‘last’ members
are never ‘NULL’ so we can remove checks for ‘NULL’ values in almost all
cases.  This means that most of the *note Py_XDECREF(): 269. calls can
be converted to *note Py_DECREF(): 267. calls.  The only place we can’t
change these calls is in the ‘tp_dealloc’ implementation, where there is
the possibility that the initialization of these members failed in
‘tp_new’.

We also rename the module initialization function and module name in the
initialization function, as we did before, and we add an extra
definition to the ‘setup.py’ file.

   ---------- Footnotes ----------

   (1) (3) We now know that the first and last members are strings, so
perhaps we could be less careful about decrementing their reference
counts, however, we accept instances of string subclasses.  Even though
deallocating normal strings won’t call back into our objects, we can’t
guarantee that deallocating an instance of a string subclass won’t call
back into our objects.


File: python.info,  Node: Supporting cyclic garbage collection,  Next: Subclassing other types,  Prev: Providing finer control over data attributes,  Up: 自定义扩展类型：教程

6.2.2.4 Supporting cyclic garbage collection
............................................

Python has a *note cyclic garbage collector (GC): ed8. that can identify
unneeded objects even when their reference counts are not zero.  This
can happen when objects are involved in cycles.  For example, consider:

     >>> l = []
     >>> l.append(l)
     >>> del l

In this example, we create a list that contains itself.  When we delete
it, it still has a reference from itself.  Its reference count doesn’t
drop to zero.  Fortunately, Python’s cyclic garbage collector will
eventually figure out that the list is garbage and free it.

In the second version of the ‘Custom’ example, we allowed any kind of
object to be stored in the ‘first’ or ‘last’ attributes (1).  Besides,
in the second and third versions, we allowed subclassing ‘Custom’, and
subclasses may add arbitrary attributes.  For any of those two reasons,
‘Custom’ objects can participate in cycles:

     >>> import custom3
     >>> class Derived(custom3.Custom): pass
     ...
     >>> n = Derived()
     >>> n.some_attribute = n

To allow a ‘Custom’ instance participating in a reference cycle to be
properly detected and collected by the cyclic GC, our ‘Custom’ type
needs to fill two additional slots and to enable a flag that enables
these slots:

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>
     #include "structmember.h"

     typedef struct {
         PyObject_HEAD
         PyObject *first; /* first name */
         PyObject *last;  /* last name */
         int number;
     } CustomObject;

     static int
     Custom_traverse(CustomObject *self, visitproc visit, void *arg)
     {
         Py_VISIT(self->first);
         Py_VISIT(self->last);
         return 0;
     }

     static int
     Custom_clear(CustomObject *self)
     {
         Py_CLEAR(self->first);
         Py_CLEAR(self->last);
         return 0;
     }

     static void
     Custom_dealloc(CustomObject *self)
     {
         PyObject_GC_UnTrack(self);
         Custom_clear(self);
         Py_TYPE(self)->tp_free((PyObject *) self);
     }

     static PyObject *
     Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
     {
         CustomObject *self;
         self = (CustomObject *) type->tp_alloc(type, 0);
         if (self != NULL) {
             self->first = PyUnicode_FromString("");
             if (self->first == NULL) {
                 Py_DECREF(self);
                 return NULL;
             }
             self->last = PyUnicode_FromString("");
             if (self->last == NULL) {
                 Py_DECREF(self);
                 return NULL;
             }
             self->number = 0;
         }
         return (PyObject *) self;
     }

     static int
     Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
     {
         static char *kwlist[] = {"first", "last", "number", NULL};
         PyObject *first = NULL, *last = NULL, *tmp;

         if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
                                          &first, &last,
                                          &self->number))
             return -1;

         if (first) {
             tmp = self->first;
             Py_INCREF(first);
             self->first = first;
             Py_DECREF(tmp);
         }
         if (last) {
             tmp = self->last;
             Py_INCREF(last);
             self->last = last;
             Py_DECREF(tmp);
         }
         return 0;
     }

     static PyMemberDef Custom_members[] = {
         {"number", T_INT, offsetof(CustomObject, number), 0,
          "custom number"},
         {NULL}  /* Sentinel */
     };

     static PyObject *
     Custom_getfirst(CustomObject *self, void *closure)
     {
         Py_INCREF(self->first);
         return self->first;
     }

     static int
     Custom_setfirst(CustomObject *self, PyObject *value, void *closure)
     {
         if (value == NULL) {
             PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
             return -1;
         }
         if (!PyUnicode_Check(value)) {
             PyErr_SetString(PyExc_TypeError,
                             "The first attribute value must be a string");
             return -1;
         }
         Py_INCREF(value);
         Py_CLEAR(self->first);
         self->first = value;
         return 0;
     }

     static PyObject *
     Custom_getlast(CustomObject *self, void *closure)
     {
         Py_INCREF(self->last);
         return self->last;
     }

     static int
     Custom_setlast(CustomObject *self, PyObject *value, void *closure)
     {
         if (value == NULL) {
             PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute");
             return -1;
         }
         if (!PyUnicode_Check(value)) {
             PyErr_SetString(PyExc_TypeError,
                             "The last attribute value must be a string");
             return -1;
         }
         Py_INCREF(value);
         Py_CLEAR(self->last);
         self->last = value;
         return 0;
     }

     static PyGetSetDef Custom_getsetters[] = {
         {"first", (getter) Custom_getfirst, (setter) Custom_setfirst,
          "first name", NULL},
         {"last", (getter) Custom_getlast, (setter) Custom_setlast,
          "last name", NULL},
         {NULL}  /* Sentinel */
     };

     static PyObject *
     Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
     {
         return PyUnicode_FromFormat("%S %S", self->first, self->last);
     }

     static PyMethodDef Custom_methods[] = {
         {"name", (PyCFunction) Custom_name, METH_NOARGS,
          "Return the name, combining the first and last name"
         },
         {NULL}  /* Sentinel */
     };

     static PyTypeObject CustomType = {
         PyVarObject_HEAD_INIT(NULL, 0)
         .tp_name = "custom4.Custom",
         .tp_doc = "Custom objects",
         .tp_basicsize = sizeof(CustomObject),
         .tp_itemsize = 0,
         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
         .tp_new = Custom_new,
         .tp_init = (initproc) Custom_init,
         .tp_dealloc = (destructor) Custom_dealloc,
         .tp_traverse = (traverseproc) Custom_traverse,
         .tp_clear = (inquiry) Custom_clear,
         .tp_members = Custom_members,
         .tp_methods = Custom_methods,
         .tp_getset = Custom_getsetters,
     };

     static PyModuleDef custommodule = {
         PyModuleDef_HEAD_INIT,
         .m_name = "custom4",
         .m_doc = "Example module that creates an extension type.",
         .m_size = -1,
     };

     PyMODINIT_FUNC
     PyInit_custom4(void)
     {
         PyObject *m;
         if (PyType_Ready(&CustomType) < 0)
             return NULL;

         m = PyModule_Create(&custommodule);
         if (m == NULL)
             return NULL;

         Py_INCREF(&CustomType);
         if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
             Py_DECREF(&CustomType);
             Py_DECREF(m);
             return NULL;
         }

         return m;
     }

First, the traversal method lets the cyclic GC know about subobjects
that could participate in cycles:

     static int
     Custom_traverse(CustomObject *self, visitproc visit, void *arg)
     {
         int vret;
         if (self->first) {
             vret = visit(self->first, arg);
             if (vret != 0)
                 return vret;
         }
         if (self->last) {
             vret = visit(self->last, arg);
             if (vret != 0)
                 return vret;
         }
         return 0;
     }

For each subobject that can participate in cycles, we need to call the
‘visit()’ function, which is passed to the traversal method.  The
‘visit()’ function takes as arguments the subobject and the extra
argument `arg' passed to the traversal method.  It returns an integer
value that must be returned if it is non-zero.

Python provides a *note Py_VISIT(): 3b4f. macro that automates calling
visit functions.  With *note Py_VISIT(): 3b4f, we can minimize the
amount of boilerplate in ‘Custom_traverse’:

     static int
     Custom_traverse(CustomObject *self, visitproc visit, void *arg)
     {
         Py_VISIT(self->first);
         Py_VISIT(self->last);
         return 0;
     }

     注解: The *note tp_traverse: 36c7. implementation must name its
     arguments exactly `visit' and `arg' in order to use *note
     Py_VISIT(): 3b4f.

Second, we need to provide a method for clearing any subobjects that can
participate in cycles:

     static int
     Custom_clear(CustomObject *self)
     {
         Py_CLEAR(self->first);
         Py_CLEAR(self->last);
         return 0;
     }

Notice the use of the *note Py_CLEAR(): 3b50. macro.  It is the
recommended and safe way to clear data attributes of arbitrary types
while decrementing their reference counts.  If you were to call *note
Py_XDECREF(): 269. instead on the attribute before setting it to ‘NULL’,
there is a possibility that the attribute’s destructor would call back
into code that reads the attribute again (`especially' if there is a
reference cycle).

     注解: You could emulate *note Py_CLEAR(): 3b50. by writing:

          PyObject *tmp;
          tmp = self->first;
          self->first = NULL;
          Py_XDECREF(tmp);

     Nevertheless, it is much easier and less error-prone to always use
     *note Py_CLEAR(): 3b50. when deleting an attribute.  Don’t try to
     micro-optimize at the expense of robustness!

The deallocator ‘Custom_dealloc’ may call arbitrary code when clearing
attributes.  It means the circular GC can be triggered inside the
function.  Since the GC assumes reference count is not zero, we need to
untrack the object from the GC by calling *note PyObject_GC_UnTrack():
e4d. before clearing members.  Here is our reimplemented deallocator
using *note PyObject_GC_UnTrack(): e4d. and ‘Custom_clear’:

     static void
     Custom_dealloc(CustomObject *self)
     {
         PyObject_GC_UnTrack(self);
         Custom_clear(self);
         Py_TYPE(self)->tp_free((PyObject *) self);
     }

Finally, we add the *note Py_TPFLAGS_HAVE_GC: 3b51. flag to the class
flags:

     .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,

That’s pretty much it.  If we had written custom *note tp_alloc: 3b44.
or *note tp_free: 3b43. handlers, we’d need to modify them for cyclic
garbage collection.  Most extensions will use the versions automatically
provided.

   ---------- Footnotes ----------

   (1) (4) Also, even with our attributes restricted to strings
instances, the user could pass arbitrary *note str: 339. subclasses and
therefore still create reference cycles.


File: python.info,  Node: Subclassing other types,  Prev: Supporting cyclic garbage collection,  Up: 自定义扩展类型：教程

6.2.2.5 Subclassing other types
...............................

It is possible to create new extension types that are derived from
existing types.  It is easiest to inherit from the built in types, since
an extension can easily use the *note PyTypeObject: 2d7. it needs.  It
can be difficult to share these *note PyTypeObject: 2d7. structures
between extension modules.

In this example we will create a ‘SubList’ type that inherits from the
built-in *note list: 263. type.  The new type will be completely
compatible with regular lists, but will have an additional ‘increment()’
method that increases an internal counter:

     >>> import sublist
     >>> s = sublist.SubList(range(3))
     >>> s.extend(s)
     >>> print(len(s))
     6
     >>> print(s.increment())
     1
     >>> print(s.increment())
     2

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>

     typedef struct {
         PyListObject list;
         int state;
     } SubListObject;

     static PyObject *
     SubList_increment(SubListObject *self, PyObject *unused)
     {
         self->state++;
         return PyLong_FromLong(self->state);
     }

     static PyMethodDef SubList_methods[] = {
         {"increment", (PyCFunction) SubList_increment, METH_NOARGS,
          PyDoc_STR("increment state counter")},
         {NULL},
     };

     static int
     SubList_init(SubListObject *self, PyObject *args, PyObject *kwds)
     {
         if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0)
             return -1;
         self->state = 0;
         return 0;
     }

     static PyTypeObject SubListType = {
         PyVarObject_HEAD_INIT(NULL, 0)
         .tp_name = "sublist.SubList",
         .tp_doc = "SubList objects",
         .tp_basicsize = sizeof(SubListObject),
         .tp_itemsize = 0,
         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
         .tp_init = (initproc) SubList_init,
         .tp_methods = SubList_methods,
     };

     static PyModuleDef sublistmodule = {
         PyModuleDef_HEAD_INIT,
         .m_name = "sublist",
         .m_doc = "Example module that creates an extension type.",
         .m_size = -1,
     };

     PyMODINIT_FUNC
     PyInit_sublist(void)
     {
         PyObject *m;
         SubListType.tp_base = &PyList_Type;
         if (PyType_Ready(&SubListType) < 0)
             return NULL;

         m = PyModule_Create(&sublistmodule);
         if (m == NULL)
             return NULL;

         Py_INCREF(&SubListType);
         if (PyModule_AddObject(m, "SubList", (PyObject *) &SubListType) < 0) {
             Py_DECREF(&SubListType);
             Py_DECREF(m);
             return NULL;
         }

         return m;
     }

As you can see, the source code closely resembles the ‘Custom’ examples
in previous sections.  We will break down the main differences between
them.

     typedef struct {
         PyListObject list;
         int state;
     } SubListObject;

The primary difference for derived type objects is that the base type’s
object structure must be the first value.  The base type will already
include the *note PyObject_HEAD(): c7a. at the beginning of its
structure.

When a Python object is a ‘SubList’ instance, its ‘PyObject *’ pointer
can be safely cast to both ‘PyListObject *’ and ‘SubListObject *’:

     static int
     SubList_init(SubListObject *self, PyObject *args, PyObject *kwds)
     {
         if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0)
             return -1;
         self->state = 0;
         return 0;
     }

We see above how to call through to the *note __init__: d66. method of
the base type.

This pattern is important when writing a type with custom *note tp_new:
3b3f. and *note tp_dealloc: 3b42. members.  The *note tp_new: 3b3f.
handler should not actually create the memory for the object with its
*note tp_alloc: 3b44, but let the base class handle it by calling its
own *note tp_new: 3b3f.

The *note PyTypeObject: 2d7. struct supports a *note tp_base: 3b53.
specifying the type’s concrete base class.  Due to cross-platform
compiler issues, you can’t fill that field directly with a reference to
*note PyList_Type: 3b54.; it should be done later in the module
initialization function:

     PyMODINIT_FUNC
     PyInit_sublist(void)
     {
         PyObject* m;
         SubListType.tp_base = &PyList_Type;
         if (PyType_Ready(&SubListType) < 0)
             return NULL;

         m = PyModule_Create(&sublistmodule);
         if (m == NULL)
             return NULL;

         Py_INCREF(&SubListType);
         if (PyModule_AddObject(m, "SubList", (PyObject *) &SubListType) < 0) {
             Py_DECREF(&SubListType);
             Py_DECREF(m);
             return NULL;
         }

         return m;
     }

Before calling *note PyType_Ready(): 3b45, the type structure must have
the *note tp_base: 3b53. slot filled in.  When we are deriving an
existing type, it is not necessary to fill out the *note tp_alloc: 3b44.
slot with *note PyType_GenericNew(): 3b40. – the allocation function
from the base type will be inherited.

After that, calling *note PyType_Ready(): 3b45. and adding the type
object to the module is the same as with the basic ‘Custom’ examples.

备注
....


File: python.info,  Node: 定义扩展类型：已分类主题,  Next: 构建C/C++扩展,  Prev: 自定义扩展类型：教程,  Up: 不使用第三方工具创建扩展

6.2.3 定义扩展类型：已分类主题
------------------------------

本章节目标是提供一个各种你可以实现的类型方法及其功能的简短介绍。

这是C类型 *note PyTypeObject: 2d7. 的定义，省略了只用于调试构建的字段:

     typedef struct _typeobject {
         PyObject_VAR_HEAD
         const char *tp_name; /* For printing, in format "<module>.<name>" */
         Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

         /* Methods to implement standard operations */

         destructor tp_dealloc;
         Py_ssize_t tp_vectorcall_offset;
         getattrfunc tp_getattr;
         setattrfunc tp_setattr;
         PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
                                         or tp_reserved (Python 3) */
         reprfunc tp_repr;

         /* Method suites for standard classes */

         PyNumberMethods *tp_as_number;
         PySequenceMethods *tp_as_sequence;
         PyMappingMethods *tp_as_mapping;

         /* More standard operations (here for binary compatibility) */

         hashfunc tp_hash;
         ternaryfunc tp_call;
         reprfunc tp_str;
         getattrofunc tp_getattro;
         setattrofunc tp_setattro;

         /* Functions to access object as input/output buffer */
         PyBufferProcs *tp_as_buffer;

         /* Flags to define presence of optional/expanded features */
         unsigned long tp_flags;

         const char *tp_doc; /* Documentation string */

         /* call function for all accessible objects */
         traverseproc tp_traverse;

         /* delete references to contained objects */
         inquiry tp_clear;

         /* rich comparisons */
         richcmpfunc tp_richcompare;

         /* weak reference enabler */
         Py_ssize_t tp_weaklistoffset;

         /* Iterators */
         getiterfunc tp_iter;
         iternextfunc tp_iternext;

         /* Attribute descriptor and subclassing stuff */
         struct PyMethodDef *tp_methods;
         struct PyMemberDef *tp_members;
         struct PyGetSetDef *tp_getset;
         struct _typeobject *tp_base;
         PyObject *tp_dict;
         descrgetfunc tp_descr_get;
         descrsetfunc tp_descr_set;
         Py_ssize_t tp_dictoffset;
         initproc tp_init;
         allocfunc tp_alloc;
         newfunc tp_new;
         freefunc tp_free; /* Low-level free-memory routine */
         inquiry tp_is_gc; /* For PyObject_IS_GC */
         PyObject *tp_bases;
         PyObject *tp_mro; /* method resolution order */
         PyObject *tp_cache;
         PyObject *tp_subclasses;
         PyObject *tp_weaklist;
         destructor tp_del;

         /* Type attribute cache version tag. Added in version 2.6 */
         unsigned int tp_version_tag;

         destructor tp_finalize;

     } PyTypeObject;

这里有 `很多' 方法。但是不要太担心，如果你要定义一个类型，通常只需要实现
少量的方法。

正如你猜到的一样，我们正要一步一步详细介绍各种处理程序。因为有大量的历史
包袱影响字段的排序，所以我们不会根据它们在结构体里定义的顺序讲解。通常非
常容易找到一个包含你需要的字段的例子，然后改变值去适应你新的类型。

     const char *tp_name; /* For printing */

类型的名字 - 上一章提到过的，会出现在很多地方，几乎全部都是为了诊断目的
。尝试选择一个好名字，对于诊断很有帮助。

     Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

这些字段告诉运行时在创造这个类型的新对象时需要分配多少内存。Python为了可
变长度的结构（想下：字符串，元组）有些内置支持，这是 *note tp_itemsize:
3b3b. 字段存在的原由。这部分稍后解释。

     const char *tp_doc;

这里你可以放置一段字符串（或者它的地址），当你想在Python脚本引用
‘obj.__doc__’ 时返回这段文档字符串。

现在我们来看一下基本类型方法 - 大多数扩展类型将实现的方法。

* Menu:

* 终结和内存释放::
* 对象展示::
* 属性管理::
* Object Comparison::
* Abstract Protocol Support::
* Weak Reference Support::
* 更多建议::


File: python.info,  Node: 终结和内存释放,  Next: 对象展示,  Up: 定义扩展类型：已分类主题

6.2.3.1 终结和内存释放
......................

     destructor tp_dealloc;

当您的类型实例的引用计数减少为零并且Python解释器想要回收它时，将调用此函
数。如果你的类型有内存可供释放或执行其他清理，你可以把它放在这里。 对象
本身也需要在这里释放。 以下是此函数的示例：

     static void
     newdatatype_dealloc(newdatatypeobject *obj)
     {
         free(obj->obj_UnderlyingDatatypePtr);
         Py_TYPE(obj)->tp_free(obj);
     }

一个重要的释放器函数实现要求是把所有未决异常放着不动。这很重要是因为释放
器会被解释器频繁的调用，当栈异常退出时(而非正常返回)，不会有任何办法保护
释放器看到一个异常尚未被设置。此事释放器的任何行为都会导致额外增加的
Python代码来检查异常是否被设置。这可能导致解释器的误导性错误。正确的保护
方法是，在任何不安全的操作前，保存未决异常，然后在其完成后恢复。者可以通
过 *note PyErr_Fetch(): 972. 和 *note PyErr_Restore(): 3b5a. 函数来实现:

     static void
     my_dealloc(PyObject *obj)
     {
         MyObject *self = (MyObject *) obj;
         PyObject *cbresult;

         if (self->my_callback != NULL) {
             PyObject *err_type, *err_value, *err_traceback;

             /* This saves the current exception state */
             PyErr_Fetch(&err_type, &err_value, &err_traceback);

             cbresult = PyObject_CallObject(self->my_callback, NULL);
             if (cbresult == NULL)
                 PyErr_WriteUnraisable(self->my_callback);
             else
                 Py_DECREF(cbresult);

             /* This restores the saved exception state */
             PyErr_Restore(err_type, err_value, err_traceback);

             Py_DECREF(self->my_callback);
         }
         Py_TYPE(obj)->tp_free((PyObject*)self);
     }

     注解: There are limitations to what you can safely do in a
     deallocator function.  First, if your type supports garbage
     collection (using *note tp_traverse: 36c7. and/or *note tp_clear:
     3b5b.), some of the object’s members can have been cleared or
     finalized by the time *note tp_dealloc: 3b42. is called.  Second,
     in *note tp_dealloc: 3b42, your object is in an unstable state: its
     reference count is equal to zero.  Any call to a non-trivial object
     or API (as in the example above) might end up calling *note
     tp_dealloc: 3b42. again, causing a double free and a crash.

     从 Python 3.4 开始，推荐不要在 *note tp_dealloc: 3b42. 放复杂的终结
     代码，而是使用新的 *note tp_finalize: 2d8. 类型方法。

     参见
     ....

     PEP 442(1) 解释了新的终结方案。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0442


File: python.info,  Node: 对象展示,  Next: 属性管理,  Prev: 终结和内存释放,  Up: 定义扩展类型：已分类主题

6.2.3.2 对象展示
................

在 Python 中，有两种方式可以生成对象的文本表示: *note repr(): 7d5. 函数
和 *note str(): 339. 函数。 (*note print(): 88f. 函数会直接调用 *note
str(): 339.。) 这些处理程序都是可选的。

     reprfunc tp_repr;
     reprfunc tp_str;

*note tp_repr: 3b5d. 处理程序应该返回一个字符串对象，其中包含调用它的实
例的表示形式。 下面是一个简单的例子:

     static PyObject *
     newdatatype_repr(newdatatypeobject * obj)
     {
         return PyUnicode_FromFormat("Repr-ified_newdatatype{{size:%d}}",
                                     obj->obj_UnderlyingDatatypePtr->size);
     }

如果没有指定 *note tp_repr: 3b5d. 处理程序，解释器将提供一个使用 *note
tp_name: 3b5e. 的表示形式以及对象的惟一标识值。

The *note tp_str: 3b5f. handler is to *note str(): 339. what the *note
tp_repr: 3b5d. handler described above is to *note repr(): 7d5.; that
is, it is called when Python code calls *note str(): 339. on an instance
of your object.  Its implementation is very similar to the *note
tp_repr: 3b5d. function, but the resulting string is intended for human
consumption.  If *note tp_str: 3b5f. is not specified, the *note
tp_repr: 3b5d. handler is used instead.

下面是一个简单的例子:

     static PyObject *
     newdatatype_str(newdatatypeobject * obj)
     {
         return PyUnicode_FromFormat("Stringified_newdatatype{{size:%d}}",
                                     obj->obj_UnderlyingDatatypePtr->size);
     }


File: python.info,  Node: 属性管理,  Next: Object Comparison,  Prev: 对象展示,  Up: 定义扩展类型：已分类主题

6.2.3.3 属性管理
................

For every object which can support attributes, the corresponding type
must provide the functions that control how the attributes are resolved.
There needs to be a function which can retrieve attributes (if any are
defined), and another to set attributes (if setting attributes is
allowed).  Removing an attribute is a special case, for which the new
value passed to the handler is ‘NULL’.

Python supports two pairs of attribute handlers; a type that supports
attributes only needs to implement the functions for one pair.  The
difference is that one pair takes the name of the attribute as a
‘char*’, while the other accepts a *note PyObject*: 4c2.  Each type can
use whichever pair makes more sense for the implementation’s
convenience.

     getattrfunc  tp_getattr;        /* char * version */
     setattrfunc  tp_setattr;
     /* ... */
     getattrofunc tp_getattro;       /* PyObject * version */
     setattrofunc tp_setattro;

If accessing attributes of an object is always a simple operation (this
will be explained shortly), there are generic implementations which can
be used to provide the *note PyObject*: 4c2. version of the attribute
management functions.  The actual need for type-specific attribute
handlers almost completely disappeared starting with Python 2.2, though
there are many examples which have not been updated to use some of the
new generic mechanism that is available.

* Menu:

* 泛型属性管理::
* Type-specific Attribute Management::


File: python.info,  Node: 泛型属性管理,  Next: Type-specific Attribute Management,  Up: 属性管理

6.2.3.4 泛型属性管理
....................

大多数扩展类型只使用 `简单' 属性，那么，是什么让属性变得“简单”呢？只需要
满足下面几个条件：

  1. 当调用 *note PyType_Ready(): 3b45. 时，必须知道属性的名称。

  2. 不需要特殊的处理来记录属性是否被查找或设置，也不需要根据值采取操作
     。

请注意，此列表不对属性的值、值的计算时间或相关数据的存储方式施加任何限制
。

When *note PyType_Ready(): 3b45. is called, it uses three tables
referenced by the type object to create *note descriptor: 1616.s which
are placed in the dictionary of the type object.  Each descriptor
controls access to one attribute of the instance object.  Each of the
tables is optional; if all three are ‘NULL’, instances of the type will
only have attributes that are inherited from their base type, and should
leave the *note tp_getattro: 3b62. and *note tp_setattro: 3b63. fields
‘NULL’ as well, allowing the base type to handle attributes.

表被声明为object::类型的三个字段:

     struct PyMethodDef *tp_methods;
     struct PyMemberDef *tp_members;
     struct PyGetSetDef *tp_getset;

If *note tp_methods: 3b49. is not ‘NULL’, it must refer to an array of
*note PyMethodDef: e23. structures.  Each entry in the table is an
instance of this structure:

     typedef struct PyMethodDef {
         const char  *ml_name;       /* method name */
         PyCFunction  ml_meth;       /* implementation function */
         int          ml_flags;      /* flags */
         const char  *ml_doc;        /* docstring */
     } PyMethodDef;

One entry should be defined for each method provided by the type; no
entries are needed for methods inherited from a base type.  One
additional entry is needed at the end; it is a sentinel that marks the
end of the array.  The ‘ml_name’ field of the sentinel must be ‘NULL’.

The second table is used to define attributes which map directly to data
stored in the instance.  A variety of primitive C types are supported,
and access may be read-only or read-write.  The structures in the table
are defined as:

     typedef struct PyMemberDef {
         const char *name;
         int         type;
         int         offset;
         int         flags;
         const char *doc;
     } PyMemberDef;

For each entry in the table, a *note descriptor: 1616. will be
constructed and added to the type which will be able to extract a value
from the instance structure.  The *note type: 611. field should contain
one of the type codes defined in the ‘structmember.h’ header; the value
will be used to determine how to convert Python values to and from C
values.  The ‘flags’ field is used to store flags which control how the
attribute can be accessed.

以下标志常量定义在:file: ’ structmember.h ’;它们可以使用bitwise-OR组合。

常数                            含义
                                
-----------------------------------------------------------------------------------
                                
‘READONLY’                      没有可写的
                                
                                
‘READ_RESTRICTED’               Not readable in restricted mode.
                                
                                
‘WRITE_RESTRICTED’              Not writable in restricted mode.
                                
                                
‘RESTRICTED’                    在受限模式下不可读，也不可写。
                                

An interesting advantage of using the *note tp_members: 3b47. table to
build descriptors that are used at runtime is that any attribute defined
this way can have an associated doc string simply by providing the text
in the table.  An application can use the introspection API to retrieve
the descriptor from the class object, and get the doc string using its
‘__doc__’ attribute.

As with the *note tp_methods: 3b49. table, a sentinel entry with a
‘name’ value of ‘NULL’ is required.


File: python.info,  Node: Type-specific Attribute Management,  Prev: 泛型属性管理,  Up: 属性管理

6.2.3.5 Type-specific Attribute Management
..........................................

For simplicity, only the ‘char*’ version will be demonstrated here; the
type of the name parameter is the only difference between the ‘char*’
and *note PyObject*: 4c2. flavors of the interface.  This example
effectively does the same thing as the generic example above, but does
not use the generic support added in Python 2.2.  It explains how the
handler functions are called, so that if you do need to extend their
functionality, you’ll understand what needs to be done.

The *note tp_getattr: 3b65. handler is called when the object requires
an attribute look-up.  It is called in the same situations where the
*note __getattr__(): 323. method of a class would be called.

例如：

     static PyObject *
     newdatatype_getattr(newdatatypeobject *obj, char *name)
     {
         if (strcmp(name, "data") == 0)
         {
             return PyLong_FromLong(obj->data);
         }

         PyErr_Format(PyExc_AttributeError,
                      "'%.50s' object has no attribute '%.400s'",
                      tp->tp_name, name);
         return NULL;
     }

The *note tp_setattr: 3b66. handler is called when the *note
__setattr__(): e34. or *note __delattr__(): 1440. method of a class
instance would be called.  When an attribute should be deleted, the
third parameter will be ‘NULL’.  Here is an example that simply raises
an exception; if this were really all you wanted, the *note tp_setattr:
3b66. handler should be set to ‘NULL’.

     static int
     newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)
     {
         PyErr_Format(PyExc_RuntimeError, "Read-only attribute: %s", name);
         return -1;
     }


File: python.info,  Node: Object Comparison,  Next: Abstract Protocol Support,  Prev: 属性管理,  Up: 定义扩展类型：已分类主题

6.2.3.6 Object Comparison
.........................

     richcmpfunc tp_richcompare;

The *note tp_richcompare: 3b68. handler is called when comparisons are
needed.  It is analogous to the *note rich comparison methods: 1448,
like *note __lt__(): c3c, and also called by *note
PyObject_RichCompare(): 3b69. and *note PyObject_RichCompareBool(): f57.

This function is called with two Python objects and the operator as
arguments, where the operator is one of ‘Py_EQ’, ‘Py_NE’, ‘Py_LE’,
‘Py_GT’, ‘Py_LT’ or ‘Py_GT’.  It should compare the two objects with
respect to the specified operator and return ‘Py_True’ or ‘Py_False’ if
the comparison is successful, ‘Py_NotImplemented’ to indicate that
comparison is not implemented and the other object’s comparison method
should be tried, or ‘NULL’ if an exception was set.

Here is a sample implementation, for a datatype that is considered equal
if the size of an internal pointer is equal:

     static PyObject *
     newdatatype_richcmp(PyObject *obj1, PyObject *obj2, int op)
     {
         PyObject *result;
         int c, size1, size2;

         /* code to make sure that both arguments are of type
            newdatatype omitted */

         size1 = obj1->obj_UnderlyingDatatypePtr->size;
         size2 = obj2->obj_UnderlyingDatatypePtr->size;

         switch (op) {
         case Py_LT: c = size1 <  size2; break;
         case Py_LE: c = size1 <= size2; break;
         case Py_EQ: c = size1 == size2; break;
         case Py_NE: c = size1 != size2; break;
         case Py_GT: c = size1 >  size2; break;
         case Py_GE: c = size1 >= size2; break;
         }
         result = c ? Py_True : Py_False;
         Py_INCREF(result);
         return result;
      }


File: python.info,  Node: Abstract Protocol Support,  Next: Weak Reference Support,  Prev: Object Comparison,  Up: 定义扩展类型：已分类主题

6.2.3.7 Abstract Protocol Support
.................................

Python supports a variety of `abstract' ’protocols;’ the specific
interfaces provided to use these interfaces are documented in *note
抽象对象层: 3b6b.

A number of these abstract interfaces were defined early in the
development of the Python implementation.  In particular, the number,
mapping, and sequence protocols have been part of Python since the
beginning.  Other protocols have been added over time.  For protocols
which depend on several handler routines from the type implementation,
the older protocols have been defined as optional blocks of handlers
referenced by the type object.  For newer protocols there are additional
slots in the main type object, with a flag bit being set to indicate
that the slots are present and should be checked by the interpreter.
(The flag bit does not indicate that the slot values are non-‘NULL’.
The flag may be set to indicate the presence of a slot, but a slot may
still be unfilled.)

     PyNumberMethods   *tp_as_number;
     PySequenceMethods *tp_as_sequence;
     PyMappingMethods  *tp_as_mapping;

If you wish your object to be able to act like a number, a sequence, or
a mapping object, then you place the address of a structure that
implements the C type *note PyNumberMethods: d89, *note
PySequenceMethods: 3b6c, or *note PyMappingMethods: 3b6d, respectively.
It is up to you to fill in this structure with appropriate values.  You
can find examples of the use of each of these in the ‘Objects’ directory
of the Python source distribution.

     hashfunc tp_hash;

This function, if you choose to provide it, should return a hash number
for an instance of your data type.  Here is a simple example:

     static Py_hash_t
     newdatatype_hash(newdatatypeobject *obj)
     {
         Py_hash_t result;
         result = obj->some_size + 32767 * obj->some_number;
         if (result == -1)
            result = -2;
         return result;
     }

‘Py_hash_t’ is a signed integer type with a platform-varying width.
Returning ‘-1’ from *note tp_hash: 3b6e. indicates an error, which is
why you should be careful to avoid returning it when hash computation is
successful, as seen above.

     ternaryfunc tp_call;

This function is called when an instance of your data type is "called",
for example, if ‘obj1’ is an instance of your data type and the Python
script contains ‘obj1('hello')’, the *note tp_call: 3b6f. handler is
invoked.

This function takes three arguments:

  1. `self' is the instance of the data type which is the subject of the
     call.  If the call is ‘obj1('hello')’, then `self' is ‘obj1’.

  2. `args' is a tuple containing the arguments to the call.  You can
     use *note PyArg_ParseTuple(): 26b. to extract the arguments.

  3. `kwds' is a dictionary of keyword arguments that were passed.  If
     this is non-‘NULL’ and you support keyword arguments, use *note
     PyArg_ParseTupleAndKeywords(): 5d3. to extract the arguments.  If
     you do not want to support keyword arguments and this is
     non-‘NULL’, raise a *note TypeError: 193. with a message saying
     that keyword arguments are not supported.

Here is a toy ‘tp_call’ implementation:

     static PyObject *
     newdatatype_call(newdatatypeobject *self, PyObject *args, PyObject *kwds)
     {
         PyObject *result;
         const char *arg1;
         const char *arg2;
         const char *arg3;

         if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3)) {
             return NULL;
         }
         result = PyUnicode_FromFormat(
             "Returning -- value: [%d] arg1: [%s] arg2: [%s] arg3: [%s]\n",
             obj->obj_UnderlyingDatatypePtr->size,
             arg1, arg2, arg3);
         return result;
     }

     /* Iterators */
     getiterfunc tp_iter;
     iternextfunc tp_iternext;

These functions provide support for the iterator protocol.  Both
handlers take exactly one parameter, the instance for which they are
being called, and return a new reference.  In the case of an error, they
should set an exception and return ‘NULL’.  *note tp_iter: e38.
corresponds to the Python *note __iter__(): 517. method, while *note
tp_iternext: e39. corresponds to the Python *note __next__(): c6c.
method.

Any *note iterable: bb4. object must implement the *note tp_iter: e38.
handler, which must return an *note iterator: 104b. object.  Here the
same guidelines apply as for Python classes:

   * For collections (such as lists and tuples) which can support
     multiple independent iterators, a new iterator should be created
     and returned by each call to *note tp_iter: e38.

   * Objects which can only be iterated over once (usually due to side
     effects of iteration, such as file objects) can implement *note
     tp_iter: e38. by returning a new reference to themselves – and
     should also therefore implement the *note tp_iternext: e39.
     handler.

Any *note iterator: 104b. object should implement both *note tp_iter:
e38. and *note tp_iternext: e39.  An iterator’s *note tp_iter: e38.
handler should return a new reference to the iterator.  Its *note
tp_iternext: e39. handler should return a new reference to the next
object in the iteration, if there is one.  If the iteration has reached
the end, *note tp_iternext: e39. may return ‘NULL’ without setting an
exception, or it may set *note StopIteration: 48e. `in addition' to
returning ‘NULL’; avoiding the exception can yield slightly better
performance.  If an actual error occurs, *note tp_iternext: e39. should
always set an exception and return ‘NULL’.


File: python.info,  Node: Weak Reference Support,  Next: 更多建议,  Prev: Abstract Protocol Support,  Up: 定义扩展类型：已分类主题

6.2.3.8 Weak Reference Support
..............................

One of the goals of Python’s weak reference implementation is to allow
any type to participate in the weak reference mechanism without
incurring the overhead on performance-critical objects (such as
numbers).

参见
....

Documentation for the *note weakref: 129. module.

For an object to be weakly referencable, the extension type must do two
things:

  1. Include a *note PyObject*: 4c2. field in the C object structure
     dedicated to the weak reference mechanism.  The object’s
     constructor should leave it ‘NULL’ (which is automatic when using
     the default *note tp_alloc: 3b44.).

  2. Set the *note tp_weaklistoffset: 3b71. type member to the offset of
     the aforementioned field in the C object structure, so that the
     interpreter knows how to access and modify that field.

Concretely, here is how a trivial object structure would be augmented
with the required field:

     typedef struct {
         PyObject_HEAD
         PyObject *weakreflist;  /* List of weak references */
     } TrivialObject;

And the corresponding member in the statically-declared type object:

     static PyTypeObject TrivialType = {
         PyVarObject_HEAD_INIT(NULL, 0)
         /* ... other members omitted for brevity ... */
         .tp_weaklistoffset = offsetof(TrivialObject, weakreflist),
     };

The only further addition is that ‘tp_dealloc’ needs to clear any weak
references (by calling ‘PyObject_ClearWeakRefs()’) if the field is
non-‘NULL’:

     static void
     Trivial_dealloc(TrivialObject *self)
     {
         /* Clear weakrefs first before calling any destructors */
         if (self->weakreflist != NULL)
             PyObject_ClearWeakRefs((PyObject *) self);
         /* ... remainder of destruction code omitted for brevity ... */
         Py_TYPE(self)->tp_free((PyObject *) self);
     }


File: python.info,  Node: 更多建议,  Prev: Weak Reference Support,  Up: 定义扩展类型：已分类主题

6.2.3.9 更多建议
................

In order to learn how to implement any specific method for your new data
type, get the *note CPython: 1446. source code.  Go to the ‘Objects’
directory, then search the C source files for ‘tp_’ plus the function
you want (for example, ‘tp_richcompare’).  You will find examples of the
function you want to implement.

When you need to verify that an object is a concrete instance of the
type you are implementing, use the *note PyObject_TypeCheck(): 3b73.
function.  A sample of its use might be something like the following:

     if (!PyObject_TypeCheck(some_object, &MyType)) {
         PyErr_SetString(PyExc_TypeError, "arg #1 not a mything");
         return NULL;
     }

参见
....

下载CPython源代码版本。

     ‘https://www.python.org/downloads/source/’

GitHub上开发CPython源代码的CPython项目。

     ‘https://github.com/python/cpython’


File: python.info,  Node: 构建C/C++扩展,  Next: 在Windows平台编译C和C++扩展,  Prev: 定义扩展类型：已分类主题,  Up: 不使用第三方工具创建扩展

6.2.4 构建C/C++扩展
-------------------

一个CPython的C扩展是一个共享库(例如一个Linux上的 ‘.so’ ，或者Windows上的
‘.pyd’ )，其会导出一个 `初始化函数' 。

为了可导入，共享库必须在 *note PYTHONPATH: 95b. 中有效，且必须命名遵循模
块名字，通过适当的扩展。当使用distutils时，会自动生成正确的文件名。

初始化函数的声明如下：

 -- C 函数: PyObject* PyInit_modulename (void)

该函数返回完整初始化过的模块，或一个 *note PyModuleDef: 3b4b. 实例。查看
*note Initializing C modules: 3b77. 了解更多细节。

对于仅有ASCII编码的模块名，函数必须是 ‘PyInit_<modulename>’ ，将
‘<modulename>’ 替换为模块的名字。当使用 *note Multi-phase
initialization: 3b78. 时，允许使用非ASCII编码的模块名。此时初始化函数的
名字是 ‘PyInitU_<modulename>’ ，而 ‘<modulename>’ 需要用Python的
`punycode' 编码，连字号需替换为下划线。在Python里:

     def initfunc_name(name):
         try:
             suffix = b'_' + name.encode('ascii')
         except UnicodeEncodeError:
             suffix = b'U_' + name.encode('punycode').replace(b'-', b'_')
         return b'PyInit' + suffix

可以在一个动态库里导出多个模块，通过定义多个初始化函数。而导入他们需要符
号链接或自定义导入器，因为缺省时只有对应了文件名的函数才会被发现。查看
`"一个库里的多模块"' 章节，在 PEP 489(1) 了解更多细节。

* Menu:

* 使用distutils构建C和C++扩展::
* 发布你的扩展模块::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0489


File: python.info,  Node: 使用distutils构建C和C++扩展,  Next: 发布你的扩展模块,  Up: 构建C/C++扩展

6.2.4.1 使用distutils构建C和C++扩展
...................................

扩展模块可以用distutils来构建，这是Python自带的。distutils也支持创建二进
制包，用户无需编译器而distutils就能安装扩展。

一个distutils包包含了一个驱动脚本 ‘setup.py’ 。这是个纯Python文件，大多
数时候也很简单，看起来如下：

     from distutils.core import setup, Extension

     module1 = Extension('demo',
                         sources = ['demo.c'])

     setup (name = 'PackageName',
            version = '1.0',
            description = 'This is a demo package',
            ext_modules = [module1])

通过文件 ‘setup.py’ ，和文件 ‘demo.c’ ，运行如下

     python setup.py build

这会编译 ‘demo.c’ ，然后产生一个扩展模块叫做 ‘demo’ 在目录 ‘build’ 里。
依赖于系统，模块文件会放在某个子目录形如 ‘build/lib.system’ ，名字可能是
‘demo.so’ 或 ‘demo.pyd’ 。

在文件 ‘setup.py’ 里，所有动作的入口通过 ‘setup’ 函数。该函数可以接受可
变数量个关键字参数，上面的例子只使用了一个子集。特别需要注意的例子指定了
构建包的元信息，以及指定了包内容。通常一个包会包括多个模块，就像Python的
源码模块、文档、子包等。请参数distutils的文档，在 *note 分发 Python
模块（遗留版本）: 801. 来了解更多distutils的特性；本章节只解释构建扩展模
块的部分。

通常预计算参数给 ‘setup()’ ，想要更好的结构化驱动脚本。有如如上例子函数
*note setup(): 3b7a. 的 ‘ext_modules’ 参数是一列扩展模块，每个是一个
‘Extension’ 类的实例。例子中的实例定义了扩展命名为 ‘demo’ ，从单一源码文
件构建 ‘demo.c’ 。

更多时候，构建一个扩展会复杂的多，需要额外的预处理器定义和库。如下例子展
示了这些。

     from distutils.core import setup, Extension

     module1 = Extension('demo',
                         define_macros = [('MAJOR_VERSION', '1'),
                                          ('MINOR_VERSION', '0')],
                         include_dirs = ['/usr/local/include'],
                         libraries = ['tcl83'],
                         library_dirs = ['/usr/local/lib'],
                         sources = ['demo.c'])

     setup (name = 'PackageName',
            version = '1.0',
            description = 'This is a demo package',
            author = 'Martin v. Loewis',
            author_email = 'martin@v.loewis.de',
            url = 'https://docs.python.org/extending/building',
            long_description = '''
     This is really just a demo package.
     ''',
            ext_modules = [module1])

例子中函数 *note setup(): 3b7a. 在调用时额外传递了元信息，是推荐发布包构
建时的内容。对于这个扩展，其指定了预处理器定义，include目录，库目录，库
。依赖于编译器，distutils还会用其他方式传递信息给编译器。例如在Unix上，
结果是如下编译命令

     gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DMAJOR_VERSION=1 -DMINOR_VERSION=0 -I/usr/local/include -I/usr/local/include/python2.2 -c demo.c -o build/temp.linux-i686-2.2/demo.o

     gcc -shared build/temp.linux-i686-2.2/demo.o -L/usr/local/lib -ltcl83 -o build/lib.linux-i686-2.2/demo.so

这些行代码仅用于展示目的；distutils用户应该相信distutils能正确调用。


File: python.info,  Node: 发布你的扩展模块,  Prev: 使用distutils构建C和C++扩展,  Up: 构建C/C++扩展

6.2.4.2 发布你的扩展模块
........................

当一个扩展已经成功地被构建时，有三种方式来使用它。

最终用户通常想要安装模块，可以这么运行

     python setup.py install

模块维护者应该制作源码包；要实现可以运行

     python setup.py sdist

有些情况下，需要在源码发布包里包含额外的文件；这通过 ‘MANIFEST.in’ 文件
实现，查看 *note Specifying the files to distribute: 3b7d. 了解细节。

如果源码发行包被成功地构建，维护者还可以创建二进制发行包。 取决于具体平
台，以下命令中的一个可以用来完成此任务

     python setup.py bdist_wininst
     python setup.py bdist_rpm
     python setup.py bdist_dumb


File: python.info,  Node: 在Windows平台编译C和C++扩展,  Prev: 构建C/C++扩展,  Up: 不使用第三方工具创建扩展

6.2.5 在Windows平台编译C和C++扩展
---------------------------------

这一章简要介绍了如何使用 Microsoft Visual C++ 创建 Python 的 Windows 扩
展模块，然后再提供有关其工作机理的详细背景信息。 这些说明材料同时适用于
Windows 程序员学习构建 Python 扩展以及 Unix 程序员学习如何生成在 Unix 和
Windows 上均能成功构建的软件。

鼓励模块作者使用 distutils 方式来构建扩展模块，而不使用本节所描述的方式
。 你仍将需要使用 C 编译器来构建 Python；通常为 Microsoft Visual C++。

     注解: 这一章提及了多个包括已编码 Python 版本号的文件名。 这些文件名
     以显示为 ‘XY’ 的版本号来代表；在实践中，‘'X'’ 将为你所使用的 Python
     发布版的主版本号而 ‘'Y'’ 将为次版本号。 例如，如果你所使用的是
     Python 2.2.1，‘XY’ 将为 ‘22’。

* Menu:

* 菜谱式说明::
* Unix 和 Windows 之间的差异::
* DLL 的实际使用::


File: python.info,  Node: 菜谱式说明,  Next: Unix 和 Windows 之间的差异,  Up: 在Windows平台编译C和C++扩展

6.2.5.1 菜谱式说明
..................

在 Windows 和 Unix 上构建扩展模块都有两种方式：使用 *note distutils: 39.
包来控制构建过程，或者全手动操作。 distutils 方式适用于大多数扩展；使用
*note distutils: 39. 构建和打包扩展模块的文档见 *note 分发 Python
模块（遗留版本）: 801.。 如果你发现你确实需要手动操作，那么研究一下
winsound(1) 标准库模块的项目文件可能会很有帮助。

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/PCbuild/winsound.vcxproj


File: python.info,  Node: Unix 和 Windows 之间的差异,  Next: DLL 的实际使用,  Prev: 菜谱式说明,  Up: 在Windows平台编译C和C++扩展

6.2.5.2 Unix 和 Windows 之间的差异
..................................

Unix 和 Windows 对于代码的运行时加载使用了完全不同的范式。 在你尝试构建
可动态加载的模块之前，要先了解你所用系统是如何工作的。

在 Unix 中，一个共享对象 (‘.so’) 文件中包含将由程序来使用的代码，也包含
在程序中可被找到的函数名称和数据。 当文件被合并到程序中时，对在文件代码
中这些函数和数据的全部引用都会被改为指向程序中函数和数据在内存中所放置的
实际位置。 这基本上是一个链接操作。

在 Windows 中，一个动态链接库 (‘.dll’) 文件中没有悬挂的引用。 而是通过一
个查找表执行对函数或数据的访问。 因此在运行时 DLL 代码不必在运行时进行修
改；相反地，代码已经使用了 DLL 的查找表，并且在运行时查找表会被修改以指
向特定的函数和数据。

在 Unix 中，只存在一种库文件 (‘.a’)，它包含来自多个对象文件 (‘.o’) 的代
码。 在创建共享对象文件 (‘.so’) 的链接阶段，链接器可能会发现它不知道某个
标识符是在哪里定义的。 链接器将在各个库的对象文件中查找它；如果找到了它
，链接器将会包括来自该对象文件的所有代码。

在 Windows 中，存在两种库类型，静态库和导入库 (扩展名都是 ‘.lib’)。 静态
库类似于 Unix 的 ‘.a’ 文件；它包含在必要时可被包括的代码。 导入库基本上
仅用于让链接器能确保特定标识符是合法的，并且将在 DLL 被加载时出现于程序
中。 这样链接器可使用来自导入库的信息构建查找表以便使用未包括在 DLL 中的
标识符。 当一个应用程序或 DLL 被链接时，可能会生成一个导入库，它将需要被
用于应用程序或 DLL 中未来所有依赖于这些符号的 DLL。

假设你正在编译两个动态加载模块 B 和 C，它们应当共享另一个代码块 A。 在
Unix 上，你 `不应' 将 ‘A.a’ 传给链接器作为 ‘B.so’ 和 ‘C.so’；那会导致它
被包括两次，这样 B 和 C 将分别拥有它们自己的副本。 在 Windows 上，编译
‘A.dll’ 将同时编译 ‘A.lib’。 你 `应当' 将 ‘A.lib’ 传给链接器用于 B 和 C。
‘A.lib’ 并不包含代码；它只包含将在运行时被用于访问 A 的代码的信息。

在 Windows 上，使用导入库有点像是使用 ‘import spam’；它让你可以访问 spam
中的名称，但并不会创建一个单独副本。 在 Unix 上，链接到一个库更像是
‘from spam import *’；它会创建一个单独副本。


File: python.info,  Node: DLL 的实际使用,  Prev: Unix 和 Windows 之间的差异,  Up: 在Windows平台编译C和C++扩展

6.2.5.3 DLL 的实际使用
......................

Windows 版 Python 是用 Microsoft Visual C++ 编译的；使用其他编译器可能行
也可能不行（但 Borland 看来是可以的）。 这一节的剩余部分只适用于 MSVC++。

当在 Windows 中创建 DLL 时，你必须将 ‘pythonXY.lib’ 传给链接器。 要编译
两个 DLL，spam 和 ni (会使用 spam 中找到的 C 函数)，你应当使用以下命令:

     cl /LD /I/python/include spam.c ../libs/pythonXY.lib
     cl /LD /I/python/include ni.c spam.lib ../libs/pythonXY.lib

第一个命令创建了三个文件: ‘spam.obj’, ‘spam.dll’ 和 ‘spam.lib’。
‘Spam.dll’ 不包含任何 Python 函数 (例如 *note PyArg_ParseTuple(): 26b.)，
但它通过 ‘pythonXY.lib’ 可以知道如何找到所需的 Python 代码。

第二条命令创建了 ‘ni.dll’ (以及 ‘.obj’ 和 ‘.lib’)，它知道如何从 spam 以
及 Python 可执行文件中找到所需的函数。

不是每个标识符都会被导出到查找表。 如果你想要任何其他模块（包括 Python）
都能看到你的标识符，你必须写上 ‘_declspec(dllexport)’，就如在 ‘void
_declspec(dllexport) initspam(void)’ 或 ‘PyObject _declspec(dllexport)
*NiGetSpamData(void)’ 中一样。

Developer Studio 将加入大量你并不真正需要的导入库，使你的可执行文件大小
增加 100K。 要摆脱它们，请使用项目设置对话框的链接选项卡指定 `忽略默认库
'。 将正确的 ‘msvcrtxx.lib’ 添加到库列表中。


File: python.info,  Node: 在更大的应用程序中嵌入 CPython 运行时,  Prev: 不使用第三方工具创建扩展,  Up: 扩展和嵌入 Python 解释器

6.3 在更大的应用程序中嵌入 CPython 运行时
=========================================

有时，不是要创建在 Python 解释器中作为主应用程序运行的扩展，而是希望将
CPython 运行时嵌入到更大的应用程序中。 本节介绍了成功完成此操作所涉及的
一些细节。

* Menu:

* 在其它应用程序嵌入 Python::


File: python.info,  Node: 在其它应用程序嵌入 Python,  Up: 在更大的应用程序中嵌入 CPython 运行时

6.3.1 在其它应用程序嵌入 Python
-------------------------------

The previous chapters discussed how to extend Python, that is, how to
extend the functionality of Python by attaching a library of C functions
to it.  It is also possible to do it the other way around: enrich your
C/C++ application by embedding Python in it.  Embedding provides your
application with the ability to implement some of the functionality of
your application in Python rather than C or C++.  This can be used for
many purposes; one example would be to allow users to tailor the
application to their needs by writing some scripts in Python.  You can
also use it yourself if some of the functionality can be written in
Python more easily.

Embedding Python is similar to extending it, but not quite.  The
difference is that when you extend Python, the main program of the
application is still the Python interpreter, while if you embed Python,
the main program may have nothing to do with Python — instead, some
parts of the application occasionally call the Python interpreter to run
some Python code.

So if you are embedding Python, you are providing your own main program.
One of the things this main program has to do is initialize the Python
interpreter.  At the very least, you have to call the function *note
Py_Initialize(): 441.  There are optional calls to pass command line
arguments to Python.  Then later you can call the interpreter from any
part of the application.

There are several different ways to call the interpreter: you can pass a
string containing Python statements to *note PyRun_SimpleString(): 3b8a,
or you can pass a stdio file pointer and a file name (for identification
in error messages only) to *note PyRun_SimpleFile(): 3b8b.  You can also
call the lower-level operations described in the previous chapters to
construct and use Python objects.

参见
....

*note Python/C API 参考手册: 120e.

     The details of Python’s C interface are given in this manual.  A
     great deal of necessary information can be found here.

* Menu:

* Very High Level Embedding::
* Beyond Very High Level Embedding; An overview: Beyond Very High Level Embedding An overview.
* 纯嵌入::
* Extending Embedded Python::
* 在 C++ 中嵌入 Python::
* 在类 Unix 系统中编译和链接::


File: python.info,  Node: Very High Level Embedding,  Next: Beyond Very High Level Embedding An overview,  Up: 在其它应用程序嵌入 Python

6.3.1.1 Very High Level Embedding
.................................

The simplest form of embedding Python is the use of the very high level
interface.  This interface is intended to execute a Python script
without needing to interact with the application directly.  This can for
example be used to perform some operation on a file.

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>

     int
     main(int argc, char *argv[])
     {
         wchar_t *program = Py_DecodeLocale(argv[0], NULL);
         if (program == NULL) {
             fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
             exit(1);
         }
         Py_SetProgramName(program);  /* optional but recommended */
         Py_Initialize();
         PyRun_SimpleString("from time import time,ctime\n"
                            "print('Today is', ctime(time()))\n");
         if (Py_FinalizeEx() < 0) {
             exit(120);
         }
         PyMem_RawFree(program);
         return 0;
     }

The *note Py_SetProgramName(): f99. function should be called before
*note Py_Initialize(): 441. to inform the interpreter about paths to
Python run-time libraries.  Next, the Python interpreter is initialized
with *note Py_Initialize(): 441, followed by the execution of a
hard-coded Python script that prints the date and time.  Afterwards, the
*note Py_FinalizeEx(): 5d2. call shuts the interpreter down, followed by
the end of the program.  In a real program, you may want to get the
Python script from another source, perhaps a text-editor routine, a
file, or a database.  Getting the Python code from a file can better be
done by using the *note PyRun_SimpleFile(): 3b8b. function, which saves
you the trouble of allocating memory space and loading the file
contents.


File: python.info,  Node: Beyond Very High Level Embedding An overview,  Next: 纯嵌入,  Prev: Very High Level Embedding,  Up: 在其它应用程序嵌入 Python

6.3.1.2 Beyond Very High Level Embedding: An overview
.....................................................

The high level interface gives you the ability to execute arbitrary
pieces of Python code from your application, but exchanging data values
is quite cumbersome to say the least.  If you want that, you should use
lower level calls.  At the cost of having to write more C code, you can
achieve almost anything.

It should be noted that extending Python and embedding Python is quite
the same activity, despite the different intent.  Most topics discussed
in the previous chapters are still valid.  To show this, consider what
the extension code from Python to C really does:

  1. 转换 Python 的数据值到 C,

  2. Perform a function call to a C routine using the converted values,
     and

  3. Convert the data values from the call from C to Python.

When embedding Python, the interface code does:

  1. 转换 C 的数据值到 Python,

  2. Perform a function call to a Python interface routine using the
     converted values, and

  3. Convert the data values from the call from Python to C.

As you can see, the data conversion steps are simply swapped to
accommodate the different direction of the cross-language transfer.  The
only difference is the routine that you call between both data
conversions.  When extending, you call a C routine, when embedding, you
call a Python routine.

This chapter will not discuss how to convert data from Python to C and
vice versa.  Also, proper use of references and dealing with errors is
assumed to be understood.  Since these aspects do not differ from
extending the interpreter, you can refer to earlier chapters for the
required information.


File: python.info,  Node: 纯嵌入,  Next: Extending Embedded Python,  Prev: Beyond Very High Level Embedding An overview,  Up: 在其它应用程序嵌入 Python

6.3.1.3 纯嵌入
..............

The first program aims to execute a function in a Python script.  Like
in the section about the very high level interface, the Python
interpreter does not directly interact with the application (but that
will change in the next section).

The code to run a function defined in a Python script is:

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>

     int
     main(int argc, char *argv[])
     {
         PyObject *pName, *pModule, *pFunc;
         PyObject *pArgs, *pValue;
         int i;

         if (argc < 3) {
             fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
             return 1;
         }

         Py_Initialize();
         pName = PyUnicode_DecodeFSDefault(argv[1]);
         /* Error checking of pName left out */

         pModule = PyImport_Import(pName);
         Py_DECREF(pName);

         if (pModule != NULL) {
             pFunc = PyObject_GetAttrString(pModule, argv[2]);
             /* pFunc is a new reference */

             if (pFunc && PyCallable_Check(pFunc)) {
                 pArgs = PyTuple_New(argc - 3);
                 for (i = 0; i < argc - 3; ++i) {
                     pValue = PyLong_FromLong(atoi(argv[i + 3]));
                     if (!pValue) {
                         Py_DECREF(pArgs);
                         Py_DECREF(pModule);
                         fprintf(stderr, "Cannot convert argument\n");
                         return 1;
                     }
                     /* pValue reference stolen here: */
                     PyTuple_SetItem(pArgs, i, pValue);
                 }
                 pValue = PyObject_CallObject(pFunc, pArgs);
                 Py_DECREF(pArgs);
                 if (pValue != NULL) {
                     printf("Result of call: %ld\n", PyLong_AsLong(pValue));
                     Py_DECREF(pValue);
                 }
                 else {
                     Py_DECREF(pFunc);
                     Py_DECREF(pModule);
                     PyErr_Print();
                     fprintf(stderr,"Call failed\n");
                     return 1;
                 }
             }
             else {
                 if (PyErr_Occurred())
                     PyErr_Print();
                 fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
             }
             Py_XDECREF(pFunc);
             Py_DECREF(pModule);
         }
         else {
             PyErr_Print();
             fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
             return 1;
         }
         if (Py_FinalizeEx() < 0) {
             return 120;
         }
         return 0;
     }

This code loads a Python script using ‘argv[1]’, and calls the function
named in ‘argv[2]’.  Its integer arguments are the other values of the
‘argv’ array.  If you *note compile and link: 3b92. this program (let’s
call the finished executable ‘call’), and use it to execute a Python
script, such as:

     def multiply(a,b):
         print("Will compute", a, "times", b)
         c = 0
         for i in range(0, a):
             c = c + b
         return c

然后结果应该是:

     $ call multiply multiply 3 2
     Will compute 3 times 2
     Result of call: 6

Although the program is quite large for its functionality, most of the
code is for data conversion between Python and C, and for error
reporting.  The interesting part with respect to embedding Python starts
with

     Py_Initialize();
     pName = PyUnicode_DecodeFSDefault(argv[1]);
     /* Error checking of pName left out */
     pModule = PyImport_Import(pName);

After initializing the interpreter, the script is loaded using *note
PyImport_Import(): d67.  This routine needs a Python string as its
argument, which is constructed using the *note PyUnicode_FromString():
3b93. data conversion routine.

     pFunc = PyObject_GetAttrString(pModule, argv[2]);
     /* pFunc is a new reference */

     if (pFunc && PyCallable_Check(pFunc)) {
         ...
     }
     Py_XDECREF(pFunc);

Once the script is loaded, the name we’re looking for is retrieved using
*note PyObject_GetAttrString(): 3b1e.  If the name exists, and the
object returned is callable, you can safely assume that it is a
function.  The program then proceeds by constructing a tuple of
arguments as normal.  The call to the Python function is then made with:

     pValue = PyObject_CallObject(pFunc, pArgs);

Upon return of the function, ‘pValue’ is either ‘NULL’ or it contains a
reference to the return value of the function.  Be sure to release the
reference after examining the value.


File: python.info,  Node: Extending Embedded Python,  Next: 在 C++ 中嵌入 Python,  Prev: 纯嵌入,  Up: 在其它应用程序嵌入 Python

6.3.1.4 Extending Embedded Python
.................................

Until now, the embedded Python interpreter had no access to
functionality from the application itself.  The Python API allows this
by extending the embedded interpreter.  That is, the embedded
interpreter gets extended with routines provided by the application.
While it sounds complex, it is not so bad.  Simply forget for a while
that the application starts the Python interpreter.  Instead, consider
the application to be a set of subroutines, and write some glue code
that gives Python access to those routines, just like you would write a
normal Python extension.  For example:

     static int numargs=0;

     /* Return the number of arguments of the application command line */
     static PyObject*
     emb_numargs(PyObject *self, PyObject *args)
     {
         if(!PyArg_ParseTuple(args, ":numargs"))
             return NULL;
         return PyLong_FromLong(numargs);
     }

     static PyMethodDef EmbMethods[] = {
         {"numargs", emb_numargs, METH_VARARGS,
          "Return the number of arguments received by the process."},
         {NULL, NULL, 0, NULL}
     };

     static PyModuleDef EmbModule = {
         PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods,
         NULL, NULL, NULL, NULL
     };

     static PyObject*
     PyInit_emb(void)
     {
         return PyModule_Create(&EmbModule);
     }

Insert the above code just above the ‘main()’ function.  Also, insert
the following two statements before the call to *note Py_Initialize():
441.:

     numargs = argc;
     PyImport_AppendInittab("emb", &PyInit_emb);

These two lines initialize the ‘numargs’ variable, and make the
‘emb.numargs()’ function accessible to the embedded Python interpreter.
With these extensions, the Python script can do things like

     import emb
     print("Number of arguments", emb.numargs())

In a real application, the methods will expose an API of the application
to Python.


File: python.info,  Node: 在 C++ 中嵌入 Python,  Next: 在类 Unix 系统中编译和链接,  Prev: Extending Embedded Python,  Up: 在其它应用程序嵌入 Python

6.3.1.5 在 C++ 中嵌入 Python
............................

It is also possible to embed Python in a C++ program; precisely how this
is done will depend on the details of the C++ system used; in general
you will need to write the main program in C++, and use the C++ compiler
to compile and link your program.  There is no need to recompile Python
itself using C++.


File: python.info,  Node: 在类 Unix 系统中编译和链接,  Prev: 在 C++ 中嵌入 Python,  Up: 在其它应用程序嵌入 Python

6.3.1.6 在类 Unix 系统中编译和链接
..................................

It is not necessarily trivial to find the right flags to pass to your
compiler (and linker) in order to embed the Python interpreter into your
application, particularly because Python needs to load library modules
implemented as C dynamic extensions (‘.so’ files) linked against it.

To find out the required compiler and linker flags, you can execute the
‘python`X.Y'-config’ script which is generated as part of the
installation process (a ‘python3-config’ script may also be available).
This script has several options, of which the following will be directly
useful to you:

   * ‘pythonX.Y-config --cflags’ will give you the recommended flags
     when compiling:

          $ /opt/bin/python3.4-config --cflags
          -I/opt/include/python3.4m -I/opt/include/python3.4m -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes

   * ‘pythonX.Y-config --ldflags’ will give you the recommended flags
     when linking:

          $ /opt/bin/python3.4-config --ldflags
          -L/opt/lib/python3.4/config-3.4m -lpthread -ldl -lutil -lm -lpython3.4m -Xlinker -export-dynamic

     注解: To avoid confusion between several Python installations (and
     especially between the system Python and your own compiled Python),
     it is recommended that you use the absolute path to
     ‘python`X.Y'-config’, as in the above example.

If this procedure doesn’t work for you (it is not guaranteed to work for
all Unix-like platforms; however, we welcome *note bug reports: 3b99.)
you will have to read your system’s documentation about dynamic linking
and/or examine Python’s ‘Makefile’ (use *note
sysconfig.get_makefile_filename(): 3650. to find its location) and
compilation options.  In this case, the *note sysconfig: ff. module is a
useful tool to programmatically extract the configuration values that
you will want to combine together.  For example:

     >>> import sysconfig
     >>> sysconfig.get_config_var('LIBS')
     '-lpthread -ldl  -lutil'
     >>> sysconfig.get_config_var('LINKFORSHARED')
     '-Xlinker -export-dynamic'


File: python.info,  Node: Python/C API 参考手册,  Next: 分发 Python 模块,  Prev: 扩展和嵌入 Python 解释器,  Up: Top

7 Python/C API 参考手册
***********************

本手册描述了希望编写扩展模块并将 Python 解释器嵌入其应用程序中的 C 和
C++ 程序员可用的 API。同时可以参阅 *note 扩展和嵌入 Python 解释器: 120d.
，其中描述了扩展编写的一般原则，但没有详细描述 API 函数。

* Menu:

* 概述: 概述<15>.
* 稳定的应用程序二进制接口::
* The Very High Level Layer::
* 引用计数: 引用计数<3>.
* 异常处理::
* 工具: 工具<2>.
* 抽象对象层::
* 具体的对象层::
* 初始化，终结和线程::
* Python初始化配置::
* 内存管理::
* 对象实现支持::
* API 和 ABI 版本管理::


File: python.info,  Node: 概述<15>,  Next: 稳定的应用程序二进制接口,  Up: Python/C API 参考手册

7.1 概述
========

Python 的应用编程接口（API）使得 C 和 C++ 程序员可以在多个层级上访问
Python 解释器。该 API 在 C++ 中同样可用，但为简化描述，通常将其称为
Python/C API。使用 Python/C API 有两个基本的理由。第一个理由是为了特定目
的而编写 `扩展模块'；它们是扩展 Python 解释器功能的 C 模块。这可能是最常
见的使用场景。第二个理由是将 Python 用作更大规模应用的组件；这种技巧通常
被称为在一个应用中 `embedding' Python。

编写扩展模块的过程相对来说更易于理解，可以通过“菜谱”的形式分步骤介绍。使
用某些工具可在一定程度上自动化这一过程。虽然人们在其他应用中嵌入 Python
的做法早已有之，但嵌入 Python 的过程没有编写扩展模块那样方便直观。

许多 API 函数在你嵌入或是扩展 Python 这两种场景下都能发挥作用；此外，大
多数嵌入 Python 的应用程序也需要提供自定义扩展，因此在尝试在实际应用中嵌
入 Python 之前先熟悉编写扩展应该会是个好主意。

* Menu:

* 代码标准::
* 包含文件::
* 有用的宏::
* 对象、类型和引用计数::
* 异常: 异常<18>.
* 嵌入Python: 嵌入Python<2>.
* 调试构建::


File: python.info,  Node: 代码标准,  Next: 包含文件,  Up: 概述<15>

7.1.1 代码标准
--------------

如果你想要编写可包含于 CPython 的 C 代码，你 `必须' 遵循在 PEP 7(1) 中定
义的指导原则和标准。这些指导原则适用于任何你所要扩展的 Python 版本。在编
写你自己的第三方扩展模块时可以不必遵循这些规范，除非你准备在日后向
Python 贡献这些模块。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0007


File: python.info,  Node: 包含文件,  Next: 有用的宏,  Prev: 代码标准,  Up: 概述<15>

7.1.2 包含文件
--------------

使用 Python/C API 所需要的全部函数、类型和宏定义可通过下面这行语句包含到
你的代码之中：

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>

这意味着包含以下标准头文件：‘<stdio.h>’，‘<string.h>’，‘<errno.h>’，
‘<limits.h>’，‘<assert.h>’ 和 ‘<stdlib.h>’（如果可用）。

     注解: 由于 Python 可能会定义一些能在某些系统上影响标准头文件的预处
     理器定义，因此在包含任何标准头文件之前，你 `必须' 先包含
     ‘Python.h’。

     推荐总是在 ‘Python.h’ 前定义 ‘PY_SSIZE_T_CLEAN’ 。查看 *note
     解析参数并构建值变量: 2d1. 来了解这个宏的更多内容。

Python.h 所定义的全部用户可见名称（由包含的标准头文件所定义的除外）都带
有前缀 ‘Py’ 或者 ‘_Py’。以 ‘_Py’ 打头的名称是供 Python 实现内部使用的，
不应被扩展编写者使用。结构成员名称没有保留前缀。

     注解: 用户代码永远不应该定义以 ‘Py’ 或 ‘_Py’ 开头的名称。这会使读者
     感到困惑，并危及用户代码对未来Python版本的可移植性，这些版本可能会
     定义以这些前缀之一开头的其他名称。

头文件通常会与 Python 一起安装。在 Unix 上，它们位于以下目录：
‘`prefix'/include/pythonversion/’ 和
‘`exec_prefix'/include/pythonversion/’，其中 ‘prefix’ 和 ‘exec_prefix’ 是
由向 Python 的 ‘configure’ 脚本传入的对应形参所定义，而 `version' 则为
‘'%d.%d' % sys.version_info[:2]’。在 Windows 上，头文件安装于
‘`prefix'/include’，其中 ‘prefix’ 是向安装程序指定的安装目录。

要包含头文件，请将两个目录（如果不同）都放到你所用编译器的包含搜索路径中
。请 `不要' 将父目录放入搜索路径然后使用 ‘#include
<pythonX.Y/Python.h>’；这将使得多平台编译不可用，因为 ‘prefix’ 下平台无
关的头文件需要包含来自 ‘exec_prefix’ 下特定平台的头文件。

C++ 用户应该注意，尽管 API 是完全使用 C 来定义的，但头文件正确地将入口点
声明为 ‘extern "C"’，因此 API 在 C++ 中使用此 API 不必再做任何特殊处理。


File: python.info,  Node: 有用的宏,  Next: 对象、类型和引用计数,  Prev: 包含文件,  Up: 概述<15>

7.1.3 有用的宏
--------------

Python 头文件中定义了一些有用的宏。许多是在靠近它们被使用的地方定义的（
例如 *note Py_RETURN_NONE: dde.）。其他更为通用的则定义在这里。这里所显
示的并不是一个完整的列表。

 -- C 宏: Py_UNREACHABLE ()

     这个可以在你有一个不打算被触及的代码路径时使用。例如，当一个
     ‘switch’ 语句中所有可能的值都已被 ‘case’ 子句覆盖了，就可将其用在
     ‘default:’ 子句中。当你非常想在某个位置放一个 ‘assert(0)’ 或
     ‘abort()’ 调用时也可以用这个。

     3.7 新版功能.

 -- C 宏: Py_ABS (x)

     返回 ‘x’ 的绝对值。

     3.3 新版功能.

 -- C 宏: Py_MIN (x, y)

     返回 ‘x’ 和 ‘y’ 当中的最小值。

     3.3 新版功能.

 -- C 宏: Py_MAX (x, y)

     返回 ‘x’ 和 ‘y’ 当中的最大值。

     3.3 新版功能.

 -- C 宏: Py_STRINGIFY (x)

     将 ‘x’ 转换为 C 字符串。例如 ‘Py_STRINGIFY(123)’ 返回 ‘"123"’。

     3.4 新版功能.

 -- C 宏: Py_MEMBER_SIZE (type, member)

     返回结构 (‘type’) ‘member’ 的大小，以字节表示。

     3.6 新版功能.

 -- C 宏: Py_CHARMASK (c)

     参数必须为 [-128, 127] 或 [0, 255] 范围内的字符或整数类型。这个宏将
     ‘c’ 强制转换为 ‘unsigned char’ 返回。

 -- C 宏: Py_GETENV (s)

     与 ‘getenv(s)’ 类似，但是如果命令行上传递了 *note -E: 1019. ，则返
     回 ‘NULL’ （即如果设置了 ‘Py_IgnoreEnvironmentFlag’ ）。

 -- C 宏: Py_UNUSED (arg)

     用于函数定义中未使用的参数，从而消除编译器警告。例如： ‘int
     func(int a, int Py_UNUSED(b)) { return a; }’ 。

     3.4 新版功能.

 -- C 宏: Py_DEPRECATED (version)

     弃用声明。该宏必须放置在符号名称前。

     示例:

          Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);

     在 3.8 版更改: 添加了 MSVC 支持。

 -- C 宏: PyDoc_STRVAR (name, str)

     创建一个可以在文档字符串中使用的，名字为 ‘name’ 的变量。如果不和文
     档字符串一起构建 Python，该值将为空。

     如 PEP 7(1) 所述，使用 *note PyDoc_STRVAR: f3c. 作为文档字符串，以
     支持在没有文档字符串的情况下构建 Python。

     示例:

          PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");

          static PyMethodDef deque_methods[] = {
              // ...
              {"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},
              // ...
          }

 -- C 宏: PyDoc_STR (str)

     为给定的字符串输入创建一个文档字符串，或者当文档字符串被禁用时，创
     建一个空字符串。

     如 PEP 7(2) 所述，使用 *note PyDoc_STR: 3bac. 指定文档字符串，以支
     持不和文档字符串一起构建 Python 的情况。

     示例:

          static PyMethodDef pysqlite_row_methods[] = {
              {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
                  PyDoc_STR("Returns the keys of the row.")},
              {NULL, NULL}
          };

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0007

   (2) https://www.python.org/dev/peps/pep-0007


File: python.info,  Node: 对象、类型和引用计数,  Next: 异常<18>,  Prev: 有用的宏,  Up: 概述<15>

7.1.4 对象、类型和引用计数
--------------------------

多数 Python/C API 有一个或多个参数，以及一个 *note PyObject*: 4c2. 类型
的返回值。这种类型是指向任意 Python 对象的不透明数据类型的指针。所有
Python 对象类型在大多数情况下都被 Python 语言由相同的方式处理（例如，赋
值，作用域规则，和参数传递），因此将它们由单个 C 类型表示才合适。几乎所
有 Python 对象存放在堆中：你不能声明一个类型为 *note PyObject: 4c2. 的自
动或静态的变量，只能声明类型为 *note PyObject*: 4c2. 的指针。type 对象是
唯一的例外，因为它们永远不能被释放，所以它们通常是静态的 *note
PyTypeObject: 2d7. 对象。

所有 Python 对象（甚至 Python 整数）都有一个 `type' 和一个 `reference
count'。对象的类型确定它是什么类型的对象（例如整数、列表或用户定义函数；
还有更多，如 *note 标准类型层级结构: 1431. 中所述）。对于每个众所周知的
类型，都有一个宏来检查对象是否属于该类型；例如，当（且仅当） `a' 所指的
对象是 Python 列表时 ‘PyList_Check(a)’ 为真。

* Menu:

* 引用计数: 引用计数<2>.
* 类型::


File: python.info,  Node: 引用计数<2>,  Next: 类型,  Up: 对象、类型和引用计数

7.1.4.1 引用计数
................

引用计数非常重要，因为现代计算机内存（通常十分）有限；它计算有多少不同的
地方引用同一个对象。这样的地方可以是某个对象，或者是某个全局（或静态）C
变量，亦或是某个 C 函数的局部变量。当一个对象的引用计数变为 0，释放该对
象。如果这个已释放的对象包含其它对象的引用计数，则递减这些对象的引用计数
。如果这些对象的引用计数减少为零，则可以依次释放这些对象，依此类推。（这
里有一个很明显的问题——对象之间相互引用；目前，解决方案是“不要那样做”。）

总是显式操作引用计数。通常的方法是使用宏 *note Py_INCREF(): 266. 来增加
一个对象的引用计数，使用宏 *note Py_DECREF(): 267. 来减少一个对象的引用
计数。宏 *note Py_DECREF(): 267. 必须检查引用计数是否为零，然后调用对象
的释放器， 因此它比 incref 宏复杂得多。释放器是一个包含在对象类型结构中
的函数指针。如果对象是复合对象类型（例如列表），则类型特定的释放器负责递
减包含在对象中的其他对象的引用计数，并执行所需的终结。引用计数不会溢出，
至少用与虚拟内存中不同内存位置一样多的位用于保存引用计数（即
‘sizeof(Py_ssize_t) >= sizeof(void*)’ ）。因此，引用计数递增是一个简单的
操作。

没有必要为每个包含指向对象的指针的局部变量增加对象的引用计数。理论上，当
变量指向对象时，对象的引用计数增加 1 ，当变量超出范围时，对象的引用计数
减少 1 。但是，这两者相互抵消，所以最后引用计数没有改变。使用引用计数的
唯一真正原因是只要我们的变量指向它，就可以防止对象被释放。如果知道至少有
一个对该对象的其他引用存活时间至少和我们的变量一样长，则没必要临时增加引
用计数。一个典型的情形是，对象作为参数从 Python 中传递给被调用的扩展模块
中的 C 函数时，调用机制会保证在调用期间持有对所有参数的引用。

但是，有一个常见的陷阱是从列表中提取一个对象，并将其持有一段时间，而不增
加其引用计数。某些操作可能会从列表中删除某个对象，减少其引用计数，并有可
能重新分配这个对象。真正的危险是，这个看似无害的操作可能会调用任意
Python 代码——也许有一个代码路径允许控制流从 *note Py_DECREF(): 267. 回到
用户，因此在复合对象上的操作都存在潜在的风险。

一个安全的方式是始终使用泛型操作（名称以 ‘PyObject_’ ， ‘PyNumber_’ ，
‘PySequence_’ 或 ‘PyMapping_’ 开头的函数）。这些操作总是增加它们返回的对
象的引用计数。这让调用者有责任在获得结果后调用 *note Py_DECREF(): 267. 。
习惯这种方式很简单。

* Menu:

* 引用计数细节::


File: python.info,  Node: 引用计数细节,  Up: 引用计数<2>

7.1.4.2 引用计数细节
....................

The reference count behavior of functions in the Python/C API is best
explained in terms of `ownership of references'.  Ownership pertains to
references, never to objects (objects are not owned: they are always
shared).  "Owning a reference" means being responsible for calling
Py_DECREF on it when the reference is no longer needed.  Ownership can
also be transferred, meaning that the code that receives ownership of
the reference then becomes responsible for eventually decref’ing it by
calling *note Py_DECREF(): 267. or *note Py_XDECREF(): 269. when it’s no
longer needed—or passing on this responsibility (usually to its caller).
When a function passes ownership of a reference on to its caller, the
caller is said to receive a `new' reference.  When no ownership is
transferred, the caller is said to `borrow' the reference.  Nothing
needs to be done for a borrowed reference.

Conversely, when a calling function passes in a reference to an object,
there are two possibilities: the function `steals' a reference to the
object, or it does not.  `Stealing a reference' means that when you pass
a reference to a function, that function assumes that it now owns that
reference, and you are not responsible for it any longer.

Few functions steal references; the two notable exceptions are *note
PyList_SetItem(): 3b25. and *note PyTuple_SetItem(): 3b24, which steal a
reference to the item (but not to the tuple or list into which the item
is put!).  These functions were designed to steal a reference because of
a common idiom for populating a tuple or list with newly created
objects; for example, the code to create the tuple ‘(1, 2, "three")’
could look like this (forgetting about error handling for the moment; a
better way to code this is shown below):

     PyObject *t;

     t = PyTuple_New(3);
     PyTuple_SetItem(t, 0, PyLong_FromLong(1L));
     PyTuple_SetItem(t, 1, PyLong_FromLong(2L));
     PyTuple_SetItem(t, 2, PyUnicode_FromString("three"));

Here, *note PyLong_FromLong(): 3b04. returns a new reference which is
immediately stolen by *note PyTuple_SetItem(): 3b24.  When you want to
keep using an object although the reference to it will be stolen, use
*note Py_INCREF(): 266. to grab another reference before calling the
reference-stealing function.

Incidentally, *note PyTuple_SetItem(): 3b24. is the `only' way to set
tuple items; *note PySequence_SetItem(): 105f. and *note
PyObject_SetItem(): 3bb3. refuse to do this since tuples are an
immutable data type.  You should only use *note PyTuple_SetItem(): 3b24.
for tuples that you are creating yourself.

Equivalent code for populating a list can be written using *note
PyList_New(): 3bb4. and *note PyList_SetItem(): 3b25.

However, in practice, you will rarely use these ways of creating and
populating a tuple or list.  There’s a generic function, *note
Py_BuildValue(): 2cf, that can create most common objects from C values,
directed by a `format string'.  For example, the above two blocks of
code could be replaced by the following (which also takes care of the
error checking):

     PyObject *tuple, *list;

     tuple = Py_BuildValue("(iis)", 1, 2, "three");
     list = Py_BuildValue("[iis]", 1, 2, "three");

It is much more common to use *note PyObject_SetItem(): 3bb3. and
friends with items whose references you are only borrowing, like
arguments that were passed in to the function you are writing.  In that
case, their behaviour regarding reference counts is much saner, since
you don’t have to increment a reference count so you can give a
reference away ("have it be stolen").  For example, this function sets
all items of a list (actually, any mutable sequence) to a given item:

     int
     set_all(PyObject *target, PyObject *item)
     {
         Py_ssize_t i, n;

         n = PyObject_Length(target);
         if (n < 0)
             return -1;
         for (i = 0; i < n; i++) {
             PyObject *index = PyLong_FromSsize_t(i);
             if (!index)
                 return -1;
             if (PyObject_SetItem(target, index, item) < 0) {
                 Py_DECREF(index);
                 return -1;
             }
             Py_DECREF(index);
         }
         return 0;
     }

The situation is slightly different for function return values.  While
passing a reference to most functions does not change your ownership
responsibilities for that reference, many functions that return a
reference to an object give you ownership of the reference.  The reason
is simple: in many cases, the returned object is created on the fly, and
the reference you get is the only reference to the object.  Therefore,
the generic functions that return object references, like *note
PyObject_GetItem(): 3bb5. and *note PySequence_GetItem(): 105e, always
return a new reference (the caller becomes the owner of the reference).

It is important to realize that whether you own a reference returned by
a function depends on which function you call only — `the plumage' (the
type of the object passed as an argument to the function) `doesn’t enter
into it!'  Thus, if you extract an item from a list using *note
PyList_GetItem(): 3b20, you don’t own the reference — but if you obtain
the same item from the same list using *note PySequence_GetItem(): 105e.
(which happens to take exactly the same arguments), you do own a
reference to the returned object.

Here is an example of how you could write a function that computes the
sum of the items in a list of integers; once using *note
PyList_GetItem(): 3b20, and once using *note PySequence_GetItem(): 105e.

     long
     sum_list(PyObject *list)
     {
         Py_ssize_t i, n;
         long total = 0, value;
         PyObject *item;

         n = PyList_Size(list);
         if (n < 0)
             return -1; /* Not a list */
         for (i = 0; i < n; i++) {
             item = PyList_GetItem(list, i); /* Can't fail */
             if (!PyLong_Check(item)) continue; /* Skip non-integers */
             value = PyLong_AsLong(item);
             if (value == -1 && PyErr_Occurred())
                 /* Integer too big to fit in a C long, bail out */
                 return -1;
             total += value;
         }
         return total;
     }

     long
     sum_sequence(PyObject *sequence)
     {
         Py_ssize_t i, n;
         long total = 0, value;
         PyObject *item;
         n = PySequence_Length(sequence);
         if (n < 0)
             return -1; /* Has no length */
         for (i = 0; i < n; i++) {
             item = PySequence_GetItem(sequence, i);
             if (item == NULL)
                 return -1; /* Not a sequence, or other failure */
             if (PyLong_Check(item)) {
                 value = PyLong_AsLong(item);
                 Py_DECREF(item);
                 if (value == -1 && PyErr_Occurred())
                     /* Integer too big to fit in a C long, bail out */
                     return -1;
                 total += value;
             }
             else {
                 Py_DECREF(item); /* Discard reference ownership */
             }
         }
         return total;
     }


File: python.info,  Node: 类型,  Prev: 引用计数<2>,  Up: 对象、类型和引用计数

7.1.4.3 类型
............

There are few other data types that play a significant role in the
Python/C API; most are simple C types such as ‘int’, ‘long’, ‘double’
and ‘char*’.  A few structure types are used to describe static tables
used to list the functions exported by a module or the data attributes
of a new object type, and another is used to describe the value of a
complex number.  These will be discussed together with the functions
that use them.


File: python.info,  Node: 异常<18>,  Next: 嵌入Python<2>,  Prev: 对象、类型和引用计数,  Up: 概述<15>

7.1.5 异常
----------

Python程序员只需要处理特定需要处理的错误异常；未处理的异常会自动传递给调
用者，然后传递给调用者的调用者，依此类推，直到他们到达顶级解释器，在那里
将它们报告给用户并伴随堆栈回溯。

For C programmers, however, error checking always has to be explicit.
All functions in the Python/C API can raise exceptions, unless an
explicit claim is made otherwise in a function’s documentation.  In
general, when a function encounters an error, it sets an exception,
discards any object references that it owns, and returns an error
indicator.  If not documented otherwise, this indicator is either ‘NULL’
or ‘-1’, depending on the function’s return type.  A few functions
return a Boolean true/false result, with false indicating an error.
Very few functions return no explicit error indicator or have an
ambiguous return value, and require explicit testing for errors with
*note PyErr_Occurred(): 3b02.  These exceptions are always explicitly
documented.

Exception state is maintained in per-thread storage (this is equivalent
to using global storage in an unthreaded application).  A thread can be
in one of two states: an exception has occurred, or not.  The function
*note PyErr_Occurred(): 3b02. can be used to check for this: it returns
a borrowed reference to the exception type object when an exception has
occurred, and ‘NULL’ otherwise.  There are a number of functions to set
the exception state: *note PyErr_SetString(): 3aff. is the most common
(though not the most general) function to set the exception state, and
*note PyErr_Clear(): 973. clears the exception state.

The full exception state consists of three objects (all of which can be
‘NULL’): the exception type, the corresponding exception value, and the
traceback.  These have the same meanings as the Python result of
‘sys.exc_info()’; however, they are not the same: the Python objects
represent the last exception being handled by a Python *note try: d7a.
...  *note except: b46. statement, while the C level exception state
only exists while an exception is being passed on between C functions
until it reaches the Python bytecode interpreter’s main loop, which
takes care of transferring it to ‘sys.exc_info()’ and friends.

Note that starting with Python 1.5, the preferred, thread-safe way to
access the exception state from Python code is to call the function
*note sys.exc_info(): c67, which returns the per-thread exception state
for Python code.  Also, the semantics of both ways to access the
exception state have changed so that a function which catches an
exception will save and restore its thread’s exception state so as to
preserve the exception state of its caller.  This prevents common bugs
in exception handling code caused by an innocent-looking function
overwriting the exception being handled; it also reduces the often
unwanted lifetime extension for objects that are referenced by the stack
frames in the traceback.

As a general principle, a function that calls another function to
perform some task should check whether the called function raised an
exception, and if so, pass the exception state on to its caller.  It
should discard any object references that it owns, and return an error
indicator, but it should `not' set another exception — that would
overwrite the exception that was just raised, and lose important
information about the exact cause of the error.

A simple example of detecting exceptions and passing them on is shown in
the ‘sum_sequence()’ example above.  It so happens that this example
doesn’t need to clean up any owned references when it detects an error.
The following example function shows some error cleanup.  First, to
remind you why you like Python, we show the equivalent Python code:

     def incr_item(dict, key):
         try:
             item = dict[key]
         except KeyError:
             item = 0
         dict[key] = item + 1

下面是对应的闪耀荣光的 C 代码：

     int
     incr_item(PyObject *dict, PyObject *key)
     {
         /* Objects all initialized to NULL for Py_XDECREF */
         PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
         int rv = -1; /* Return value initialized to -1 (failure) */

         item = PyObject_GetItem(dict, key);
         if (item == NULL) {
             /* Handle KeyError only: */
             if (!PyErr_ExceptionMatches(PyExc_KeyError))
                 goto error;

             /* Clear the error and use zero: */
             PyErr_Clear();
             item = PyLong_FromLong(0L);
             if (item == NULL)
                 goto error;
         }
         const_one = PyLong_FromLong(1L);
         if (const_one == NULL)
             goto error;

         incremented_item = PyNumber_Add(item, const_one);
         if (incremented_item == NULL)
             goto error;

         if (PyObject_SetItem(dict, key, incremented_item) < 0)
             goto error;
         rv = 0; /* Success */
         /* Continue with cleanup code */

      error:
         /* Cleanup code, shared by success and failure path */

         /* Use Py_XDECREF() to ignore NULL references */
         Py_XDECREF(item);
         Py_XDECREF(const_one);
         Py_XDECREF(incremented_item);

         return rv; /* -1 for error, 0 for success */
     }

This example represents an endorsed use of the ‘goto’ statement in C! It
illustrates the use of *note PyErr_ExceptionMatches(): 3bba. and *note
PyErr_Clear(): 973. to handle specific exceptions, and the use of *note
Py_XDECREF(): 269. to dispose of owned references that may be ‘NULL’
(note the ‘'X'’ in the name; *note Py_DECREF(): 267. would crash when
confronted with a ‘NULL’ reference).  It is important that the variables
used to hold owned references are initialized to ‘NULL’ for this to
work; likewise, the proposed return value is initialized to ‘-1’
(failure) and only set to success after the final call made is
successful.


File: python.info,  Node: 嵌入Python<2>,  Next: 调试构建,  Prev: 异常<18>,  Up: 概述<15>

7.1.6 嵌入Python
----------------

The one important task that only embedders (as opposed to extension
writers) of the Python interpreter have to worry about is the
initialization, and possibly the finalization, of the Python
interpreter.  Most functionality of the interpreter can only be used
after the interpreter has been initialized.

The basic initialization function is *note Py_Initialize(): 441.  This
initializes the table of loaded modules, and creates the fundamental
modules *note builtins: 13, *note __main__: 1, and *note sys: fe.  It
also initializes the module search path (‘sys.path’).

*note Py_Initialize(): 441. does not set the "script argument list"
(‘sys.argv’).  If this variable is needed by Python code that will be
executed later, it must be set explicitly with a call to
‘PySys_SetArgvEx(argc, argv, updatepath)’ after the call to *note
Py_Initialize(): 441.

On most systems (in particular, on Unix and Windows, although the
details are slightly different), *note Py_Initialize(): 441. calculates
the module search path based upon its best guess for the location of the
standard Python interpreter executable, assuming that the Python library
is found in a fixed location relative to the Python interpreter
executable.  In particular, it looks for a directory named
‘lib/python`X.Y'’ relative to the parent directory where the executable
named ‘python’ is found on the shell command search path (the
environment variable ‘PATH’).

For instance, if the Python executable is found in
‘/usr/local/bin/python’, it will assume that the libraries are in
‘/usr/local/lib/python`X.Y'’.  (In fact, this particular path is also
the "fallback" location, used when no executable file named ‘python’ is
found along ‘PATH’.)  The user can override this behavior by setting the
environment variable *note PYTHONHOME: 4de, or insert additional
directories in front of the standard path by setting *note PYTHONPATH:
95b.

The embedding application can steer the search by calling
‘Py_SetProgramName(file)’ `before' calling *note Py_Initialize(): 441.
Note that *note PYTHONHOME: 4de. still overrides this and *note
PYTHONPATH: 95b. is still inserted in front of the standard path.  An
application that requires total control has to provide its own
implementation of *note Py_GetPath(): 3bbd, *note Py_GetPrefix(): 3bbe,
*note Py_GetExecPrefix(): 3bbf, and *note Py_GetProgramFullPath(): 276.
(all defined in ‘Modules/getpath.c’).

Sometimes, it is desirable to "uninitialize" Python.  For instance, the
application may want to start over (make another call to *note
Py_Initialize(): 441.) or the application is simply done with its use of
Python and wants to free memory allocated by Python.  This can be
accomplished by calling *note Py_FinalizeEx(): 5d2.  The function *note
Py_IsInitialized(): 3bc0. returns true if Python is currently in the
initialized state.  More information about these functions is given in a
later chapter.  Notice that *note Py_FinalizeEx(): 5d2. does `not' free
all memory allocated by the Python interpreter, e.g.  memory allocated
by extension modules currently cannot be released.


File: python.info,  Node: 调试构建,  Prev: 嵌入Python<2>,  Up: 概述<15>

7.1.7 调试构建
--------------

Python can be built with several macros to enable extra checks of the
interpreter and extension modules.  These checks tend to add a large
amount of overhead to the runtime so they are not enabled by default.

A full list of the various types of debugging builds is in the file
‘Misc/SpecialBuilds.txt’ in the Python source distribution.  Builds are
available that support tracing of reference counts, debugging the memory
allocator, or low-level profiling of the main interpreter loop.  Only
the most frequently-used builds will be described in the remainder of
this section.

Compiling the interpreter with the ‘Py_DEBUG’ macro defined produces
what is generally meant by "a debug build" of Python.  ‘Py_DEBUG’ is
enabled in the Unix build by adding ‘--with-pydebug’ to the
‘./configure’ command.  It is also implied by the presence of the
not-Python-specific ‘_DEBUG’ macro.  When ‘Py_DEBUG’ is enabled in the
Unix build, compiler optimization is disabled.

除了前面描述的引用计数调试之外，还执行以下额外检查：

   * 额外检查将添加到对象分配器。

   * 额外的检查将添加到解析器和编译器中。

   * 检查从宽类型向窄类型的向下强转是否损失了信息。

   * 许多断言被添加到字典和集合实现中。另外，集合对象包含 ‘test_c_api()’
     方法。

   * 添加输入参数的完整性检查到框架创建中。

   * 使用已知的无效模式初始化整型的存储，以捕获对未初始化数字的引用。

   * 添加底层跟踪和额外的异常检查到虚拟机的运行时中。

   * 添加额外的检查到 arena 内存实现。

   * 添加额外调试到线程模块。

这里可能没有提到的额外的检查。

Defining ‘Py_TRACE_REFS’ enables reference tracing.  When defined, a
circular doubly linked list of active objects is maintained by adding
two extra fields to every *note PyObject: 4c2.  Total allocations are
tracked as well.  Upon exit, all existing references are printed.  (In
interactive mode this happens after every statement run by the
interpreter.)  Implied by ‘Py_DEBUG’.

有关更多详细信息，请参阅Python源代码中的 ‘Misc/SpecialBuilds.txt’ 。


File: python.info,  Node: 稳定的应用程序二进制接口,  Next: The Very High Level Layer,  Prev: 概述<15>,  Up: Python/C API 参考手册

7.2 稳定的应用程序二进制接口
============================

传统上，Python的C API将随每个版本而变化。大多数更改都与源代码兼容，通常
只添加API，而不是更改现有API或删除API（尽管某些接口会首先弃用然后再删除
）。

不幸的是，API兼容性没有扩展到二进制兼容性（ABI）。原因主要是结构定义的演
变，在这里添加新字段或更改字段类型可能不会破坏API，但可能会破坏ABI。因此
，每个Python版本都需要重新编译扩展模块（即使在未使用任何受影响的接口的情
况下，Unix上也可能会出现异常）。此外，在Windows上，扩展模块与特定的
pythonXY.dll链接，需要重新编译才能与新的pythonXY.dll链接。

从Python3.2起，已经声明了一个API的子集，以确保稳定的ABI。如果使用此API（
也被称为“受限API”）的扩展模块需要定义‘‘Py_LIMITED_API‘‘。许多解释器细节
将从扩展模块中隐藏; 反过来，在任何3.x版本（x>=2）上构建的模块都不需要重
新编译

在某些情况下，需要添加新函数来扩展稳定版 ABI。希望使用这些新 API 的扩展
模块需要将 ‘Py_LIMITED_API’ 设置为他们想要支持的最低 Python 版本的
‘PY_VERSION_HEX’ 值（例如： Python 3.3 为 ‘0x03030000’）（参见 *note API
和 ABI 版本管理: 363f.）。此类模块将适用于所有后续 Python版本，但无法在
旧版本上加载（因为缺少符号）。

从Python 3.2开始，受限API可用的函数集记录在 PEP 384(1) 。在C API文档中，
不属于受限API的API元素标记为 “不属于受限API” 。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0384


File: python.info,  Node: The Very High Level Layer,  Next: 引用计数<3>,  Prev: 稳定的应用程序二进制接口,  Up: Python/C API 参考手册

7.3 The Very High Level Layer
=============================

The functions in this chapter will let you execute Python source code
given in a file or a buffer, but they will not let you interact in a
more detailed way with the interpreter.

Several of these functions accept a start symbol from the grammar as a
parameter.  The available start symbols are ‘Py_eval_input’,
‘Py_file_input’, and ‘Py_single_input’.  These are described following
the functions which accept them as parameters.

Note also that several of these functions take ‘FILE*’ parameters.  One
particular issue which needs to be handled carefully is that the ‘FILE’
structure for different C libraries can be different and incompatible.
Under Windows (at least), it is possible for dynamically linked
extensions to actually use different libraries, so care should be taken
that ‘FILE*’ parameters are only passed to these functions if it is
certain that they were created by the same library that the Python
runtime is using.

 -- C 函数: int Py_Main (int argc, wchar_t **argv)

     The main program for the standard interpreter.  This is made
     available for programs which embed Python.  The `argc' and `argv'
     parameters should be prepared exactly as those which are passed to
     a C program’s ‘main()’ function (converted to wchar_t according to
     the user’s locale).  It is important to note that the argument list
     may be modified (but the contents of the strings pointed to by the
     argument list are not).  The return value will be ‘0’ if the
     interpreter exits normally (i.e., without an exception), ‘1’ if the
     interpreter exits due to an exception, or ‘2’ if the parameter list
     does not represent a valid Python command line.

     Note that if an otherwise unhandled *note SystemExit: 605. is
     raised, this function will not return ‘1’, but exit the process, as
     long as ‘Py_InspectFlag’ is not set.

 -- C 函数: int Py_BytesMain (int argc, char **argv)

     Similar to *note Py_Main(): 4bf. but `argv' is an array of bytes
     strings.

     3.8 新版功能.

 -- C 函数: int PyRun_AnyFile (FILE *fp, const char *filename)

     This is a simplified interface to *note PyRun_AnyFileExFlags():
     3bca. below, leaving `closeit' set to ‘0’ and `flags' set to
     ‘NULL’.

 -- C 函数: int PyRun_AnyFileFlags (FILE *fp, const char *filename,
          PyCompilerFlags *flags)

     This is a simplified interface to *note PyRun_AnyFileExFlags():
     3bca. below, leaving the `closeit' argument set to ‘0’.

 -- C 函数: int PyRun_AnyFileEx (FILE *fp, const char *filename,
          int closeit)

     This is a simplified interface to *note PyRun_AnyFileExFlags():
     3bca. below, leaving the `flags' argument set to ‘NULL’.

 -- C 函数: int PyRun_AnyFileExFlags (FILE *fp, const char *filename,
          int closeit, PyCompilerFlags *flags)

     If `fp' refers to a file associated with an interactive device
     (console or terminal input or Unix pseudo-terminal), return the
     value of *note PyRun_InteractiveLoop(): 3bcd, otherwise return the
     result of *note PyRun_SimpleFile(): 3b8b.  `filename' is decoded
     from the filesystem encoding (*note sys.getfilesystemencoding():
     4fe.).  If `filename' is ‘NULL’, this function uses ‘"???"’ as the
     filename.

 -- C 函数: int PyRun_SimpleString (const char *command)

     This is a simplified interface to *note PyRun_SimpleStringFlags():
     3bce. below, leaving the *note PyCompilerFlags: 2cd.* argument set
     to ‘NULL’.

 -- C 函数: int PyRun_SimpleStringFlags (const char *command,
          PyCompilerFlags *flags)

     Executes the Python source code from `command' in the *note
     __main__: 1. module according to the `flags' argument.  If *note
     __main__: 1. does not already exist, it is created.  Returns ‘0’ on
     success or ‘-1’ if an exception was raised.  If there was an error,
     there is no way to get the exception information.  For the meaning
     of `flags', see below.

     Note that if an otherwise unhandled *note SystemExit: 605. is
     raised, this function will not return ‘-1’, but exit the process,
     as long as ‘Py_InspectFlag’ is not set.

 -- C 函数: int PyRun_SimpleFile (FILE *fp, const char *filename)

     This is a simplified interface to *note PyRun_SimpleFileExFlags():
     ed7. below, leaving `closeit' set to ‘0’ and `flags' set to ‘NULL’.

 -- C 函数: int PyRun_SimpleFileEx (FILE *fp, const char *filename,
          int closeit)

     This is a simplified interface to *note PyRun_SimpleFileExFlags():
     ed7. below, leaving `flags' set to ‘NULL’.

 -- C 函数: int PyRun_SimpleFileExFlags (FILE *fp, const char *filename,
          int closeit, PyCompilerFlags *flags)

     Similar to *note PyRun_SimpleStringFlags(): 3bce, but the Python
     source code is read from `fp' instead of an in-memory string.
     `filename' should be the name of the file, it is decoded from the
     filesystem encoding (*note sys.getfilesystemencoding(): 4fe.).  If
     `closeit' is true, the file is closed before
     PyRun_SimpleFileExFlags returns.

          注解: On Windows, `fp' should be opened as binary mode (e.g.
          ‘fopen(filename, "rb")’.  Otherwise, Python may not handle
          script file with LF line ending correctly.

 -- C 函数: int PyRun_InteractiveOne (FILE *fp, const char *filename)

     This is a simplified interface to *note
     PyRun_InteractiveOneFlags(): 3bd1. below, leaving `flags' set to
     ‘NULL’.

 -- C 函数: int PyRun_InteractiveOneFlags (FILE *fp, const
          char *filename, PyCompilerFlags *flags)

     Read and execute a single statement from a file associated with an
     interactive device according to the `flags' argument.  The user
     will be prompted using ‘sys.ps1’ and ‘sys.ps2’.  `filename' is
     decoded from the filesystem encoding (*note
     sys.getfilesystemencoding(): 4fe.).

     Returns ‘0’ when the input was executed successfully, ‘-1’ if there
     was an exception, or an error code from the ‘errcode.h’ include
     file distributed as part of Python if there was a parse error.
     (Note that ‘errcode.h’ is not included by ‘Python.h’, so must be
     included specifically if needed.)

 -- C 函数: int PyRun_InteractiveLoop (FILE *fp, const char *filename)

     This is a simplified interface to *note
     PyRun_InteractiveLoopFlags(): 3bd2. below, leaving `flags' set to
     ‘NULL’.

 -- C 函数: int PyRun_InteractiveLoopFlags (FILE *fp, const
          char *filename, PyCompilerFlags *flags)

     Read and execute statements from a file associated with an
     interactive device until EOF is reached.  The user will be prompted
     using ‘sys.ps1’ and ‘sys.ps2’.  `filename' is decoded from the
     filesystem encoding (*note sys.getfilesystemencoding(): 4fe.).
     Returns ‘0’ at EOF or a negative number upon failure.

 -- C 变量: int (*PyOS_InputHook) (void)

     Can be set to point to a function with the prototype ‘int
     func(void)’.  The function will be called when Python’s interpreter
     prompt is about to become idle and wait for user input from the
     terminal.  The return value is ignored.  Overriding this hook can
     be used to integrate the interpreter’s prompt with other event
     loops, as done in the ‘Modules/_tkinter.c’ in the Python source
     code.

 -- C 变量: char* (*PyOS_ReadlineFunctionPointer) (FILE *, FILE *, const
          char *)

     Can be set to point to a function with the prototype ‘char
     *func(FILE *stdin, FILE *stdout, char *prompt)’, overriding the
     default function used to read a single line of input at the
     interpreter’s prompt.  The function is expected to output the
     string `prompt' if it’s not ‘NULL’, and then read a line of input
     from the provided standard input file, returning the resulting
     string.  For example, The *note readline: df. module sets this hook
     to provide line-editing and tab-completion features.

     The result must be a string allocated by *note PyMem_RawMalloc():
     975. or *note PyMem_RawRealloc(): 976, or ‘NULL’ if an error
     occurred.

     在 3.4 版更改: The result must be allocated by *note
     PyMem_RawMalloc(): 975. or *note PyMem_RawRealloc(): 976, instead
     of being allocated by *note PyMem_Malloc(): 50d. or *note
     PyMem_Realloc(): 977.

 -- C 函数: struct _node* PyParser_SimpleParseString (const char *str,
          int start)

     This is a simplified interface to *note
     PyParser_SimpleParseStringFlagsFilename(): 3bd5. below, leaving
     `filename' set to ‘NULL’ and `flags' set to ‘0’.

 -- C 函数: struct _node* PyParser_SimpleParseStringFlags (const
          char *str, int start, int flags)

     This is a simplified interface to *note
     PyParser_SimpleParseStringFlagsFilename(): 3bd5. below, leaving
     `filename' set to ‘NULL’.

 -- C 函数: struct _node* PyParser_SimpleParseStringFlagsFilename (const
          char *str, const char *filename, int start, int flags)

     Parse Python source code from `str' using the start token `start'
     according to the `flags' argument.  The result can be used to
     create a code object which can be evaluated efficiently.  This is
     useful if a code fragment must be evaluated many times.  `filename'
     is decoded from the filesystem encoding (*note
     sys.getfilesystemencoding(): 4fe.).

 -- C 函数: struct _node* PyParser_SimpleParseFile (FILE *fp, const
          char *filename, int start)

     This is a simplified interface to *note
     PyParser_SimpleParseFileFlags(): 3bd8. below, leaving `flags' set
     to ‘0’.

 -- C 函数: struct _node* PyParser_SimpleParseFileFlags (FILE *fp, const
          char *filename, int start, int flags)

     Similar to *note PyParser_SimpleParseStringFlagsFilename(): 3bd5,
     but the Python source code is read from `fp' instead of an
     in-memory string.

 -- C 函数: PyObject* PyRun_String (const char *str, int start,
          PyObject *globals, PyObject *locals)
     `Return value: New reference.'  This is a simplified interface to
     *note PyRun_StringFlags(): 3bd9. below, leaving `flags' set to
     ‘NULL’.

 -- C 函数: PyObject* PyRun_StringFlags (const char *str, int start,
          PyObject *globals, PyObject *locals, PyCompilerFlags *flags)
     `Return value: New reference.'  Execute Python source code from
     `str' in the context specified by the objects `globals' and
     `locals' with the compiler flags specified by `flags'.  `globals'
     must be a dictionary; `locals' can be any object that implements
     the mapping protocol.  The parameter `start' specifies the start
     token that should be used to parse the source code.

     Returns the result of executing the code as a Python object, or
     ‘NULL’ if an exception was raised.

 -- C 函数: PyObject* PyRun_File (FILE *fp, const char *filename,
          int start, PyObject *globals, PyObject *locals)
     `Return value: New reference.'  This is a simplified interface to
     *note PyRun_FileExFlags(): 3bdb. below, leaving `closeit' set to
     ‘0’ and `flags' set to ‘NULL’.

 -- C 函数: PyObject* PyRun_FileEx (FILE *fp, const char *filename,
          int start, PyObject *globals, PyObject *locals, int closeit)
     `Return value: New reference.'  This is a simplified interface to
     *note PyRun_FileExFlags(): 3bdb. below, leaving `flags' set to
     ‘NULL’.

 -- C 函数: PyObject* PyRun_FileFlags (FILE *fp, const char *filename,
          int start, PyObject *globals, PyObject *locals,
          PyCompilerFlags *flags)
     `Return value: New reference.'  This is a simplified interface to
     *note PyRun_FileExFlags(): 3bdb. below, leaving `closeit' set to
     ‘0’.

 -- C 函数: PyObject* PyRun_FileExFlags (FILE *fp, const char *filename,
          int start, PyObject *globals, PyObject *locals, int closeit,
          PyCompilerFlags *flags)
     `Return value: New reference.'  Similar to *note
     PyRun_StringFlags(): 3bd9, but the Python source code is read from
     `fp' instead of an in-memory string.  `filename' should be the name
     of the file, it is decoded from the filesystem encoding (*note
     sys.getfilesystemencoding(): 4fe.).  If `closeit' is true, the file
     is closed before *note PyRun_FileExFlags(): 3bdb. returns.

 -- C 函数: PyObject* Py_CompileString (const char *str, const
          char *filename, int start)
     `Return value: New reference.'  This is a simplified interface to
     *note Py_CompileStringFlags(): 3bdf. below, leaving `flags' set to
     ‘NULL’.

 -- C 函数: PyObject* Py_CompileStringFlags (const char *str, const
          char *filename, int start, PyCompilerFlags *flags)
     `Return value: New reference.'  This is a simplified interface to
     *note Py_CompileStringExFlags(): 3be0. below, with `optimize' set
     to ‘-1’.

 -- C 函数: PyObject* Py_CompileStringObject (const char *str,
          PyObject *filename, int start, PyCompilerFlags *flags,
          int optimize)
     `Return value: New reference.'  Parse and compile the Python source
     code in `str', returning the resulting code object.  The start
     token is given by `start'; this can be used to constrain the code
     which can be compiled and should be ‘Py_eval_input’,
     ‘Py_file_input’, or ‘Py_single_input’.  The filename specified by
     `filename' is used to construct the code object and may appear in
     tracebacks or *note SyntaxError: 460. exception messages.  This
     returns ‘NULL’ if the code cannot be parsed or compiled.

     The integer `optimize' specifies the optimization level of the
     compiler; a value of ‘-1’ selects the optimization level of the
     interpreter as given by *note -O: 694. options.  Explicit levels
     are ‘0’ (no optimization; ‘__debug__’ is true), ‘1’ (asserts are
     removed, ‘__debug__’ is false) or ‘2’ (docstrings are removed too).

     3.4 新版功能.

 -- C 函数: PyObject* Py_CompileStringExFlags (const char *str, const
          char *filename, int start, PyCompilerFlags *flags,
          int optimize)
     `Return value: New reference.'  Like *note
     Py_CompileStringObject(): 3be1, but `filename' is a byte string
     decoded from the filesystem encoding (*note os.fsdecode(): 4f6.).

     3.2 新版功能.

 -- C 函数: PyObject* PyEval_EvalCode (PyObject *co, PyObject *globals,
          PyObject *locals)
     `Return value: New reference.'  This is a simplified interface to
     *note PyEval_EvalCodeEx(): 3be3, with just the code object, and
     global and local variables.  The other arguments are set to ‘NULL’.

 -- C 函数: PyObject* PyEval_EvalCodeEx (PyObject *co,
          PyObject *globals, PyObject *locals, PyObject *const *args,
          int argcount, PyObject *const *kws, int kwcount, PyObject
          *const *defs, int defcount, PyObject *kwdefs,
          PyObject *closure)
     `Return value: New reference.'  Evaluate a precompiled code object,
     given a particular environment for its evaluation.  This
     environment consists of a dictionary of global variables, a mapping
     object of local variables, arrays of arguments, keywords and
     defaults, a dictionary of default values for *note keyword-only:
     2ad. arguments and a closure tuple of cells.

 -- C 类型: PyFrameObject

     The C structure of the objects used to describe frame objects.  The
     fields of this type are subject to change at any time.

 -- C 函数: PyObject* PyEval_EvalFrame (PyFrameObject *f)
     `Return value: New reference.'  Evaluate an execution frame.  This
     is a simplified interface to *note PyEval_EvalFrameEx(): 96f, for
     backward compatibility.

 -- C 函数: PyObject* PyEval_EvalFrameEx (PyFrameObject *f,
          int throwflag)
     `Return value: New reference.'  This is the main, unvarnished
     function of Python interpretation.  The code object associated with
     the execution frame `f' is executed, interpreting bytecode and
     executing calls as needed.  The additional `throwflag' parameter
     can mostly be ignored - if true, then it causes an exception to
     immediately be thrown; this is used for the *note throw(): 14a1.
     methods of generator objects.

     在 3.4 版更改: 该函数现在包含一个调试断言，用以确保不会静默地丢弃活
     动的异常。

 -- C 函数: int PyEval_MergeCompilerFlags (PyCompilerFlags *cf)

     This function changes the flags of the current evaluation frame,
     and returns true on success, false on failure.

 -- C 变量: int Py_eval_input

     The start symbol from the Python grammar for isolated expressions;
     for use with *note Py_CompileString(): 3bde.

 -- C 变量: int Py_file_input

     The start symbol from the Python grammar for sequences of
     statements as read from a file or other source; for use with *note
     Py_CompileString(): 3bde.  This is the symbol to use when compiling
     arbitrarily long Python source code.

 -- C 变量: int Py_single_input

     The start symbol from the Python grammar for a single statement;
     for use with *note Py_CompileString(): 3bde.  This is the symbol
     used for the interactive interpreter loop.

 -- C 类型: struct PyCompilerFlags

     This is the structure used to hold compiler flags.  In cases where
     code is only being compiled, it is passed as ‘int flags’, and in
     cases where code is being executed, it is passed as
     ‘PyCompilerFlags *flags’.  In this case, ‘from __future__ import’
     can modify `flags'.

     Whenever ‘PyCompilerFlags *flags’ is ‘NULL’, ‘cf_flags’ is treated
     as equal to ‘0’, and any modification due to ‘from __future__
     import’ is discarded.

      -- C 成员: int cf_flags

          Compiler flags.

      -- C 成员: int cf_feature_version

          `cf_feature_version' is the minor Python version.  It should
          be initialized to ‘PY_MINOR_VERSION’.

          The field is ignored by default, it is used if and only if
          ‘PyCF_ONLY_AST’ flag is set in `cf_flags'.

     在 3.8 版更改: Added `cf_feature_version' field.

 -- C 变量: int CO_FUTURE_DIVISION

     This bit can be set in `flags' to cause division operator ‘/’ to be
     interpreted as "true division" according to PEP 238(1).

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0238


File: python.info,  Node: 引用计数<3>,  Next: 异常处理,  Prev: The Very High Level Layer,  Up: Python/C API 参考手册

7.4 引用计数
============

本节介绍的宏被用于管理 Python 对象的引用计数。

 -- C 函数: void Py_INCREF (PyObject *o)

     增加对象 `o' 的引用计数。 对象必须不为 ‘NULL’；如果你不确定它不为
     ‘NULL’，可使用 *note Py_XINCREF(): 268.。

 -- C 函数: void Py_XINCREF (PyObject *o)

     增加对象 `o' 的引用计数。 对象可以为 ‘NULL’，在此情况下该宏不产生任
     何效果。

 -- C 函数: void Py_DECREF (PyObject *o)

     减少对象 `o' 的引用计数。 对象必须不为 ‘NULL’；如果你不确定它不为
     ‘NULL’，可使用 *note Py_XDECREF(): 269.。 如果引用计数降为零，将发
     起调用对象所属类型的释放函数 (它必须不为 ‘NULL’)。

          警告: 释放函数可导致任意 Python 代码被发起调用（例如当一个带有
          *note __del__(): 927. 方法的类实例被释放时就是如此）。 虽然此
          类代码中的异常不会被传播，但被执行的代码能够自由访问所有
          Python 全局变量。 这意味着任何可通过全局变量获取的对象在 *note
          Py_DECREF(): 267. 被发起调用之前都应当处于完好状态。 例如，从
          一个列表中删除对象的代码应当将被删除对象的引用拷贝到一个临时变
          量中，更新列表数据结构，然后再为临时变量调用 *note
          Py_DECREF(): 267.。

 -- C 函数: void Py_XDECREF (PyObject *o)

     减少对象 `o' 的引用计数。 对象可以为 ‘NULL’，在此情况下该宏不产生任
     何效果；在其他情况下其效果与 *note Py_DECREF(): 267. 相同，并会应用
     同样的警告。

 -- C 函数: void Py_CLEAR (PyObject *o)

     减少对象 `o' 的引用计数。 对象可以为 ‘NULL’，在此情况下该宏不产生任
     何效果；在其他情况下其效果与 *note Py_DECREF(): 267. 相同，区别在于
     其参数也会被设为 ‘NULL’。 针对 *note Py_DECREF(): 267. 的警告不适用
     于所传递的对象，因为该宏会细心地使用一个临时变量并在减少其引用计数
     之前将参数设为 ‘NULL’。

     每当要减少在垃圾回收期间可能会被遍历的对象的引用计数时，使用该宏是
     一个好主意。

以下函数适用于 Python 的运行时动态嵌入: ‘Py_IncRef(PyObject *o)’,
‘Py_DecRef(PyObject *o)’。 它们分别只是 *note Py_XINCREF(): 268. 和
*note Py_XDECREF(): 269. 的简单导出函数版本。

以下函数或宏仅可在解释器核心内部使用: ‘_Py_Dealloc()’,
‘_Py_ForgetReference()’, ‘_Py_NewReference()’ 以及全局变量
‘_Py_RefTotal’。


File: python.info,  Node: 异常处理,  Next: 工具<2>,  Prev: 引用计数<3>,  Up: Python/C API 参考手册

7.5 异常处理
============

本章描述的函数将让你处理和触发 Python 异常。了解一些 Python 异常处理的基
本知识是很重要的。 它的工作原理有点像 POSIX 的 ‘errno’ 变量：（每个线程
）有一个全局指示器显示最近发生的错误。 大多数 C API 函数不会在成功时理会
它，但会在失败时设置它来指示错误的原因。 多数 C API 函数也返回一个错误指
示器，如果它们应该返回一个指针，通常返回 ‘NULL’，如果返回一个整数，则返
回 ‘-1’ (例外: ‘PyArg_*()’ 函数成功时返回 ‘1’ 而失败时返回 ‘0’)。

具体地说，错误指示器由三个对象指针组成：异常的类型，异常的值，和回溯对象
。如果没有错误被设置，这些指针都可以是 ‘NULL’ （尽管一些组合使禁止的，例
如，如果异常类型是 ‘NULL’，你不能有一个非 ‘NULL’ 的回溯）。

当一个函数由于它调用的某个函数失败而必须失败时，通常不会设置错误指示器；
它调用的那个函数已经设置了它。而它负责处理错误和清理异常，或在清除其拥有
的所有资源后返回（如对象应用或内存分配）。如果不准备处理异常，则*不*应该
正常地继续。如果是由于一个错误返回，那么一定要向调用者表明已经设置了错误
。如果错误没有得到处理或小心传播，对 Python/C API的其它调用可能不会有预
期的行为，并且可能会以某种神秘的方式失败。

     注解: 错误指示器 `不是' *note sys.exc_info(): c67. 的执行结果。前者
     对应尚未捕获的异常（异常还在传播），而后者在捕获异常后返回这个异常
     （异常已经停止传播）。

* Menu:

* 打印和清理::
* 抛出异常: 抛出异常<2>.
* 警告: 警告<3>.
* 查询错误指示器::
* 信号处理: 信号处理<2>.
* 异常类::
* 异常对象::
* Unicode 异常对象::
* 递归控制::
* 标准异常::
* 标准警告类别::


File: python.info,  Node: 打印和清理,  Next: 抛出异常<2>,  Up: 异常处理

7.5.1 打印和清理
----------------

 -- C 函数: void PyErr_Clear ()

     清楚错误指示器。如果没有设置错误指示器，则不会有作用。

 -- C 函数: void PyErr_PrintEx (int set_sys_last_vars)

     将标准回溯打印到 ‘sys.stderr’ 并清除错误指示器。`除非' 错误是
     ‘SystemExit’，这种情况下不会打印回溯进程，且会退出 Python 进程，并
     显示 ‘SystemExit’ 实例指定的错误代码。

     只有在错误指示器被设置时才需要调用这个函数，否则这会导致错误！

     如果 `set_sys_last_vars' 非零，则变量 *note sys.last_type: c62.，
     *note sys.last_value: 3640. 和 *note sys.last_traceback: 353c. 将分
     别设置为打印异常的类型，值和回溯。

 -- C 函数: void PyErr_Print ()

     ‘PyErr_PrintEx(1)’ 的别名。

 -- C 函数: void PyErr_WriteUnraisable (PyObject *obj)

     使用当前异常和 `obj' 参数调用 *note sys.unraisablehook(): 22e.。

     当设置了异常，但解释器不可能实际地触发异常时，这个实用函数向
     ‘sys.stderr’ 打印一个警告信息。例如，当 *note __del__(): 927. 方法
     中发生异常时使用这个函数。

     该函数使用单个参数 `obj' 进行调用，该参数标识发生不可触发异常的上下
     文。如果可能，`obj' 的报告将打印在警告消息中。

     调用此函数时必须设置一个异常。


File: python.info,  Node: 抛出异常<2>,  Next: 警告<3>,  Prev: 打印和清理,  Up: 异常处理

7.5.2 抛出异常
--------------

这些函数可帮助你设置当前线程的错误指示器。为了方便起见，一些函数将始终返
回 ‘NULL’ 指针，以便用于 ‘return’ 语句。

 -- C 函数: void PyErr_SetString (PyObject *type, const char *message)

     这是设置错误指示器最常用的方法。第一个参数指定异常类型；它通常是标
     准异常之一，e.g.  ‘PyExc_RuntimeError’。你不务要增加它的引用计数。
     第二个参数是错误信息，它解码自 ‘'utf-8'’。

 -- C 函数: void PyErr_SetObject (PyObject *type, PyObject *value)

     此函数类似于 *note PyErr_SetString(): 3aff.，但是允许你为异常的“值
     ”指定任意一个 Python 对象。

 -- C 函数: PyObject* PyErr_Format (PyObject *exception, const
          char *format, ...)
     `Return value: Always NULL.' 这个函数设置了一个错误的指针并且返回了
     "NULL".“exception”应当是一个python中的异常类。The "format" 和随后的
     参数帮助格式化这个错误的信息;他们与 *note PyUnicode_FromFormat():
     7d4. 有着相同的含义和值。"format"是一个ASCII编码的字符串

 -- C 函数: PyObject* PyErr_FormatV (PyObject *exception, const
          char *format, va_list vargs)
     `Return value: Always NULL.' 和 *note PyErr_Format(): 7b3. 相同，但
     它接受一个 ‘va_list’ 类型的参数而不是可变数量的参数集。

     3.5 新版功能.

 -- C 函数: void PyErr_SetNone (PyObject *type)

     这是 ‘PyErr_SetObject(type, Py_None)’ 的简写。

 -- C 函数: int PyErr_BadArgument ()

     这是 ‘PyErr_SetString(PyExc_TypeError, message)’ 的简写，其中
     `message' 指出使用了非法参数调用内置操作。它主要用于内部使用。

 -- C 函数: PyObject* PyErr_NoMemory ()
     `Return value: Always NULL.' 这是
     ‘PyErr_SetNone(PyExc_MemoryError)’ 的简写；它返回 ‘NULL’ ，以便当内
     存耗尽时，对象分配函数可以写 ‘return PyErr_NoMemory();’ 。

 -- C 函数: PyObject* PyErr_SetFromErrno (PyObject *type)
     `Return value: Always NULL.'

     这是个方便的函数，当 C 库函数返回错误并设置 ‘errno’ 时，这个函数会
     触发异常。它构造一个元组对象，其第一项是整数值 ‘errno’，第二项是相
     应的错误消息（从 ‘strerror()’ 获取），然后调用
     ‘PyErr_SetObject(type, object)’。在 Unix 上，当 ‘errno’ 值是
     ‘EINTR’ ，即中断的系统调用时，这个函数会调用 *note
     PyErr_CheckSignals(): 3bf6. ，如果设置了错误指示器，则将其设置为该
     值。该函数永远返回 ‘NULL’ ，因此当系统调用返回错误时，围绕系统调用
     的包装函数可以写成 ‘return PyErr_SetFromErrno(type);’。

 -- C 函数: PyObject* PyErr_SetFromErrnoWithFilenameObject
          (PyObject *type, PyObject *filenameObject)
     `Return value: Always NULL.' 类似于 *note PyErr_SetFromErrno():
     3b00. ，附加的行为是如果 `filenameObject' 不为 ‘NULL’ ，它将作为第
     三个参数传递给 `type' 的构造函数。举个例子，在 *note OSError: 1d4.
     异常中，`filenameObject' 将用来定义异常实例的 ‘filename’ 属性。

 -- C 函数: PyObject* PyErr_SetFromErrnoWithFilenameObjects
          (PyObject *type, PyObject *filenameObject,
          PyObject *filenameObject2)
     `Return value: Always NULL.' 类似于 *note
     PyErr_SetFromErrnoWithFilenameObject(): 3bf7. ，但接受第二个文件名
     对象，用于当一个接受两个文件名的函数失败时触发错误。

     3.4 新版功能.

 -- C 函数: PyObject* PyErr_SetFromErrnoWithFilename (PyObject *type,
          const char *filename)
     `Return value: Always NULL.' 类似于 *note
     PyErr_SetFromErrnoWithFilenameObject(): 3bf7. ，但 filename 以 C 字
     符串形式给出。 `filename' 是从文件系统编码（*note os.fsdecode():
     4f6.）解码出来的。

 -- C 函数: PyObject* PyErr_SetFromWindowsErr (int ierr)
     `Return value: Always NULL.' 这是触发 *note WindowsError: 99c. 的方
     便的函数。如果 `lerr' 为 ‘0’ ，则改用调用 ‘GetLastError()’ 返回的错
     误代码。它调用 Win32 函数 ‘FormatMessage()’ 来检索 `ierr' 或
     ‘GetLastError()’ 给定的错误代码的 Windows 描述，然后构造一个元组对
     象，其第一项是 `ierr' 值，第二项是相应的错误信息（从
     ‘FormatMessage()’ 获取），然后调用
     ‘PyErr_SetObject(PyExc_WindowsError, object)’ 。该函数永远返回
     ‘NULL’ 。

     *note 可用性: 136f.: Windows。

 -- C 函数: PyObject* PyErr_SetExcFromWindowsErr (PyObject *type,
          int ierr)
     `Return value: Always NULL.' 类似于 *note
     PyErr_SetFromWindowsErr(): 3bfa. ，额外的参数指定要触发的异常类型。

     *note 可用性: 136f.: Windows。

 -- C 函数: PyObject* PyErr_SetFromWindowsErrWithFilename (int ierr,
          const char *filename)
     `Return value: Always NULL.' 类似于
     ‘PyErr_SetFromWindowsErrWithFilenameObject()’ ，但是 filename 是以
     C 字符串形式给出的。 `filename' 是从文件系统编码（*note
     os.fsdecode(): 4f6.）解码出来的。

     *note 可用性: 136f.: Windows。

 -- C 函数: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObject
          (PyObject *type, int ierr, PyObject *filename)
     `Return value: Always NULL.' 类似于
     ‘PyErr_SetFromWindowsErrWithFilenameObject()’ ，额外参数指定要触发
     的异常类型。

     *note 可用性: 136f.: Windows。

 -- C 函数: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObjects
          (PyObject *type, int ierr, PyObject *filename,
          PyObject *filename2)
     `Return value: Always NULL.' 类似于 *note
     PyErr_SetExcFromWindowsErrWithFilenameObject(): 3bfd. ，但是接受第
     二个 filename 对象。

     *note 可用性: 136f.: Windows。

     3.4 新版功能.

 -- C 函数: PyObject* PyErr_SetExcFromWindowsErrWithFilename
          (PyObject *type, int ierr, const char *filename)
     `Return value: Always NULL.' 类似于 *note
     PyErr_SetFromWindowsErrWithFilename(): 3bfc. ，额外参数指定要触发的
     异常类型。

     *note 可用性: 136f.: Windows。

 -- C 函数: PyObject* PyErr_SetImportError (PyObject *msg,
          PyObject *name, PyObject *path)
     `Return value: Always NULL.' 这是触发 *note ImportError: 33d. 的便
     捷函数。 `msg' 将被设为异常的消息字符串。 `name' 和 `path' ，（都可
     以为 ‘NULL’ ），将用来被设置 *note ImportError: 33d. 对应的属性
     ‘name’ 和 ‘path’。

     3.3 新版功能.

 -- C 函数: void PyErr_SyntaxLocationObject (PyObject *filename,
          int lineno, int col_offset)

     设置当前异常的文件，行和偏移信息。如果当前异常不是 *note
     SyntaxError: 460. ，则它设置额外的属性，使异常打印子系统认为异常是
     *note SyntaxError: 460.。

     3.4 新版功能.

 -- C 函数: void PyErr_SyntaxLocationEx (const char *filename,
          int lineno, int col_offset)

     与 *note PyErr_SyntaxLocationObject(): 3c00. 类似，只是 `filename'
     是从文件系统编码（ *note os.fsdecode(): 4f6. ）解码出的一个字节字符
     串。

     3.2 新版功能.

 -- C 函数: void PyErr_SyntaxLocation (const char *filename, int lineno)

     与 *note PyErr_SyntaxLocationEx(): 3c01. 类似，但省略了参数
     col_offset。

 -- C 函数: void PyErr_BadInternalCall ()

     这是 ‘PyErr_SetString(PyExc_SystemError, message)’ 的缩写，其中
     `message' 表示使用了非法参数调用内部操作（例如，Python/C API 函数）
     。它主要用于内部使用。


File: python.info,  Node: 警告<3>,  Next: 查询错误指示器,  Prev: 抛出异常<2>,  Up: 异常处理

7.5.3 警告
----------

这些函数可以从 C 代码中发出警告。它们仿照了由 Python 模块 *note
warnings: 127. 导出的函数。它们通常向 `sys.stderr' 打印一条警告信息；当
然，用户也有可能已经指定将警告转换为错误，在这种情况下，它们将触发异常。
也有可能由于警告机制出现问题，使得函数触发异常。如果没有触发异常，返回值
为 ‘0’ ；如果触发异常，返回值为 ‘-1’。（无法确定是否实际打印了警告信息，
也无法确定异常触发的原因。这是故意为之）。如果触发了异常，调用者应该进行
正常的异常处理（例如，*note Py_DECREF(): 267. 持有引用并返回一个错误值）
。

 -- C 函数: int PyErr_WarnEx (PyObject *category, const char *message,
          Py_ssize_t stack_level)

     发出一个警告信息。参数 `category' 是一个警告类别（见下面）或 ‘NULL’
     ； `message' 是一个 UTF-8 编码的字符串。 `stack_level' 是一个给出栈
     帧数量的正数；警告将从该栈帧中当前正在执行的代码行发出。
     `stack_level' 为 1 的是调用 *note PyErr_WarnEx(): db9. 的函数，2 是
     在此之上的函数，以此类推。

     警告类别必须是 ‘PyExc_Warning’ 的子类， ‘PyExc_Warning’ 是
     ‘PyExc_Exception’ 的子类；默认警告类别是 ‘PyExc_RuntimeWarning’ 。
     标准 Python 警告类别作为全局变量可用，所有其名称见 *note
     标准警告类别: 3c05. 。

     有关警告控制的信息，参见模块文档 *note warnings: 127. 和命令行文档
     中的 *note -W: 41f. 选项。没有用于警告控制的 C API。

 -- C 函数: PyObject* PyErr_SetImportErrorSubclass (PyObject *exception,
          PyObject *msg, PyObject *name, PyObject *path)
     `Return value: Always NULL.' 和 *note PyErr_SetImportError(): 601.
     很类似，但这个函数允许指定一个 *note ImportError: 33d. 的子类来触发
     。

     3.6 新版功能.

 -- C 函数: int PyErr_WarnExplicitObject (PyObject *category,
          PyObject *message, PyObject *filename, int lineno,
          PyObject *module, PyObject *registry)

     Issue a warning message with explicit control over all warning
     attributes.  This is a straightforward wrapper around the Python
     function *note warnings.warn_explicit(): 5b9, see there for more
     information.  The `module' and `registry' arguments may be set to
     ‘NULL’ to get the default effect described there.

     3.4 新版功能.

 -- C 函数: int PyErr_WarnExplicit (PyObject *category, const
          char *message, const char *filename, int lineno, const
          char *module, PyObject *registry)

     Similar to *note PyErr_WarnExplicitObject(): 3c06. except that
     `message' and `module' are UTF-8 encoded strings, and `filename' is
     decoded from the filesystem encoding (*note os.fsdecode(): 4f6.).

 -- C 函数: int PyErr_WarnFormat (PyObject *category,
          Py_ssize_t stack_level, const char *format, ...)

     Function similar to *note PyErr_WarnEx(): db9, but use *note
     PyUnicode_FromFormat(): 7d4. to format the warning message.
     `format' is an ASCII-encoded string.

     3.2 新版功能.

 -- C 函数: int PyErr_ResourceWarning (PyObject *source,
          Py_ssize_t stack_level, const char *format, ...)

     Function similar to *note PyErr_WarnFormat(): 3c08, but `category'
     is *note ResourceWarning: 4d8. and it passes `source' to
     ‘warnings.WarningMessage()’.

     3.6 新版功能.


File: python.info,  Node: 查询错误指示器,  Next: 信号处理<2>,  Prev: 警告<3>,  Up: 异常处理

7.5.4 查询错误指示器
--------------------

 -- C 函数: PyObject* PyErr_Occurred ()
     `Return value: Borrowed reference.'  Test whether the error
     indicator is set.  If set, return the exception `type' (the first
     argument to the last call to one of the ‘PyErr_Set*()’ functions or
     to *note PyErr_Restore(): 3b5a.).  If not set, return ‘NULL’.  You
     do not own a reference to the return value, so you do not need to
     *note Py_DECREF(): 267. it.

          注解: Do not compare the return value to a specific exception;
          use *note PyErr_ExceptionMatches(): 3bba. instead, shown
          below.  (The comparison could easily fail since the exception
          may be an instance instead of a class, in the case of a class
          exception, or it may be a subclass of the expected exception.)

 -- C 函数: int PyErr_ExceptionMatches (PyObject *exc)

     Equivalent to ‘PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)’.
     This should only be called when an exception is actually set; a
     memory access violation will occur if no exception has been raised.

 -- C 函数: int PyErr_GivenExceptionMatches (PyObject *given,
          PyObject *exc)

     Return true if the `given' exception matches the exception type in
     `exc'.  If `exc' is a class object, this also returns true when
     `given' is an instance of a subclass.  If `exc' is a tuple, all
     exception types in the tuple (and recursively in subtuples) are
     searched for a match.

 -- C 函数: void PyErr_Fetch (PyObject **ptype, PyObject **pvalue,
          PyObject **ptraceback)

     Retrieve the error indicator into three variables whose addresses
     are passed.  If the error indicator is not set, set all three
     variables to ‘NULL’.  If it is set, it will be cleared and you own
     a reference to each object retrieved.  The value and traceback
     object may be ‘NULL’ even when the type object is not.

          注解: This function is normally only used by code that needs
          to catch exceptions or by code that needs to save and restore
          the error indicator temporarily, e.g.:

               {
                  PyObject *type, *value, *traceback;
                  PyErr_Fetch(&type, &value, &traceback);

                  /* ... code that might produce other errors ... */

                  PyErr_Restore(type, value, traceback);
               }

 -- C 函数: void PyErr_Restore (PyObject *type, PyObject *value,
          PyObject *traceback)

     Set the error indicator from the three objects.  If the error
     indicator is already set, it is cleared first.  If the objects are
     ‘NULL’, the error indicator is cleared.  Do not pass a ‘NULL’ type
     and non-‘NULL’ value or traceback.  The exception type should be a
     class.  Do not pass an invalid exception type or value.  (Violating
     these rules will cause subtle problems later.)  This call takes
     away a reference to each object: you must own a reference to each
     object before the call and after the call you no longer own these
     references.  (If you don’t understand this, don’t use this
     function.  I warned you.)

          注解: This function is normally only used by code that needs
          to save and restore the error indicator temporarily.  Use
          *note PyErr_Fetch(): 972. to save the current error indicator.

 -- C 函数: void PyErr_NormalizeException (PyObject**exc, PyObject**val,
          PyObject**tb)

     Under certain circumstances, the values returned by *note
     PyErr_Fetch(): 972. below can be "unnormalized", meaning that
     ‘*exc’ is a class object but ‘*val’ is not an instance of the same
     class.  This function can be used to instantiate the class in that
     case.  If the values are already normalized, nothing happens.  The
     delayed normalization is implemented to improve performance.

          注解: This function `does not' implicitly set the
          ‘__traceback__’ attribute on the exception value.  If setting
          the traceback appropriately is desired, the following
          additional snippet is needed:

               if (tb != NULL) {
                 PyException_SetTraceback(val, tb);
               }

 -- C 函数: void PyErr_GetExcInfo (PyObject **ptype, PyObject **pvalue,
          PyObject **ptraceback)

     Retrieve the exception info, as known from ‘sys.exc_info()’.  This
     refers to an exception that was `already caught', not to an
     exception that was freshly raised.  Returns new references for the
     three objects, any of which may be ‘NULL’.  Does not modify the
     exception info state.

          注解: This function is not normally used by code that wants to
          handle exceptions.  Rather, it can be used when code needs to
          save and restore the exception state temporarily.  Use *note
          PyErr_SetExcInfo(): 3c0c. to restore or clear the exception
          state.

     3.3 新版功能.

 -- C 函数: void PyErr_SetExcInfo (PyObject *type, PyObject *value,
          PyObject *traceback)

     Set the exception info, as known from ‘sys.exc_info()’.  This
     refers to an exception that was `already caught', not to an
     exception that was freshly raised.  This function steals the
     references of the arguments.  To clear the exception state, pass
     ‘NULL’ for all three arguments.  For general rules about the three
     arguments, see *note PyErr_Restore(): 3b5a.

          注解: This function is not normally used by code that wants to
          handle exceptions.  Rather, it can be used when code needs to
          save and restore the exception state temporarily.  Use *note
          PyErr_GetExcInfo(): 3c0b. to read the exception state.

     3.3 新版功能.


File: python.info,  Node: 信号处理<2>,  Next: 异常类,  Prev: 查询错误指示器,  Up: 异常处理

7.5.5 信号处理
--------------

 -- C 函数: int PyErr_CheckSignals ()

     This function interacts with Python’s signal handling.  It checks
     whether a signal has been sent to the processes and if so, invokes
     the corresponding signal handler.  If the *note signal: eb. module
     is supported, this can invoke a signal handler written in Python.
     In all cases, the default effect for ‘SIGINT’ is to raise the *note
     KeyboardInterrupt: 198. exception.  If an exception is raised the
     error indicator is set and the function returns ‘-1’; otherwise the
     function returns ‘0’.  The error indicator may or may not be
     cleared if it was previously set.

 -- C 函数: void PyErr_SetInterrupt ()

     Simulate the effect of a ‘SIGINT’ signal arriving.  The next time
     *note PyErr_CheckSignals(): 3bf6. is called, the Python signal
     handler for ‘SIGINT’ will be called.

     如果 Python 没有处理 *note signal.SIGINT: 24e2. (将它设为 *note
     signal.SIG_DFL: 24e3. 或 *note signal.SIG_IGN: 24e4.)，此函数将不做
     任何事。

 -- C 函数: int PySignal_SetWakeupFd (int fd)

     This utility function specifies a file descriptor to which the
     signal number is written as a single byte whenever a signal is
     received.  `fd' must be non-blocking.  It returns the previous such
     file descriptor.

     The value ‘-1’ disables the feature; this is the initial state.
     This is equivalent to *note signal.set_wakeup_fd(): 3d6. in Python,
     but without any error checking.  `fd' should be a valid file
     descriptor.  The function should only be called from the main
     thread.

     在 3.5 版更改: 在 Windows 上，此函数现在也支持套接字处理。


File: python.info,  Node: 异常类,  Next: 异常对象,  Prev: 信号处理<2>,  Up: 异常处理

7.5.6 异常类
------------

 -- C 函数: PyObject* PyErr_NewException (const char *name,
          PyObject *base, PyObject *dict)
     `Return value: New reference.'  This utility function creates and
     returns a new exception class.  The `name' argument must be the
     name of the new exception, a C string of the form
     ‘module.classname’.  The `base' and `dict' arguments are normally
     ‘NULL’.  This creates a class object derived from *note Exception:
     1aa. (accessible in C as ‘PyExc_Exception’).

     The ‘__module__’ attribute of the new class is set to the first
     part (up to the last dot) of the `name' argument, and the class
     name is set to the last part (after the last dot).  The `base'
     argument can be used to specify alternate base classes; it can
     either be only one class or a tuple of classes.  The `dict'
     argument can be used to specify a dictionary of class variables and
     methods.

 -- C 函数: PyObject* PyErr_NewExceptionWithDoc (const char *name, const
          char *doc, PyObject *base, PyObject *dict)
     `Return value: New reference.' 和 *note PyErr_NewException(): c08.
     一样，除了可以轻松地给新的异常类一个文档字符串：如果 `doc' 属性非空
     ，它将用作异常类的文档字符串。

     3.2 新版功能.


File: python.info,  Node: 异常对象,  Next: Unicode 异常对象,  Prev: 异常类,  Up: 异常处理

7.5.7 异常对象
--------------

 -- C 函数: PyObject* PyException_GetTraceback (PyObject *ex)
     `Return value: New reference.'  Return the traceback associated
     with the exception as a new reference, as accessible from Python
     through ‘__traceback__’.  If there is no traceback associated, this
     returns ‘NULL’.

 -- C 函数: int PyException_SetTraceback (PyObject *ex, PyObject *tb)

     将异常关联的回溯设置为 `tb' 。使用‘‘Py_None‘‘清除它。

 -- C 函数: PyObject* PyException_GetContext (PyObject *ex)
     `Return value: New reference.'  Return the context (another
     exception instance during whose handling `ex' was raised)
     associated with the exception as a new reference, as accessible
     from Python through ‘__context__’.  If there is no context
     associated, this returns ‘NULL’.

 -- C 函数: void PyException_SetContext (PyObject *ex, PyObject *ctx)

     Set the context associated with the exception to `ctx'.  Use ‘NULL’
     to clear it.  There is no type check to make sure that `ctx' is an
     exception instance.  This steals a reference to `ctx'.

 -- C 函数: PyObject* PyException_GetCause (PyObject *ex)
     `Return value: New reference.'  Return the cause (either an
     exception instance, or *note None: 158, set by ‘raise ... from
     ...’) associated with the exception as a new reference, as
     accessible from Python through ‘__cause__’.

 -- C 函数: void PyException_SetCause (PyObject *ex, PyObject *cause)

     Set the cause associated with the exception to `cause'.  Use ‘NULL’
     to clear it.  There is no type check to make sure that `cause' is
     either an exception instance or *note None: 158.  This steals a
     reference to `cause'.

     ‘__suppress_context__’ is implicitly set to ‘True’ by this
     function.


File: python.info,  Node: Unicode 异常对象,  Next: 递归控制,  Prev: 异常对象,  Up: 异常处理

7.5.8 Unicode 异常对象
----------------------

The following functions are used to create and modify Unicode exceptions
from C.

 -- C 函数: PyObject* PyUnicodeDecodeError_Create (const char *encoding,
          const char *object, Py_ssize_t length, Py_ssize_t start,
          Py_ssize_t end, const char *reason)
     `Return value: New reference.'  Create a *note UnicodeDecodeError:
     1fe. object with the attributes `encoding', `object', `length',
     `start', `end' and `reason'.  `encoding' and `reason' are UTF-8
     encoded strings.

 -- C 函数: PyObject* PyUnicodeEncodeError_Create (const char *encoding,
          const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start,
          Py_ssize_t end, const char *reason)
     `Return value: New reference.'  Create a *note UnicodeEncodeError:
     1fd. object with the attributes `encoding', `object', `length',
     `start', `end' and `reason'.  `encoding' and `reason' are UTF-8
     encoded strings.

     3.3 版后已移除: 3.11

     ‘Py_UNICODE’ is deprecated since Python 3.3.  Please migrate to
     ‘PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns", ...)’.

 -- C 函数: PyObject* PyUnicodeTranslateError_Create (const
          Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start,
          Py_ssize_t end, const char *reason)
     `Return value: New reference.'  Create a *note
     UnicodeTranslateError: 1725. object with the attributes `object',
     `length', `start', `end' and `reason'.  `reason' is a UTF-8 encoded
     string.

     3.3 版后已移除: 3.11

     ‘Py_UNICODE’ is deprecated since Python 3.3.  Please migrate to
     ‘PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns", ...)’.

 -- C 函数: PyObject* PyUnicodeDecodeError_GetEncoding (PyObject *exc)
 -- C 函数: PyObject* PyUnicodeEncodeError_GetEncoding (PyObject *exc)
     `Return value: New reference.' 返回给定异常对象的 `encoding' 属性

 -- C 函数: PyObject* PyUnicodeDecodeError_GetObject (PyObject *exc)
 -- C 函数: PyObject* PyUnicodeEncodeError_GetObject (PyObject *exc)
 -- C 函数: PyObject* PyUnicodeTranslateError_GetObject (PyObject *exc)
     `Return value: New reference.' 返回给定异常对象的 `object' 属性

 -- C 函数: int PyUnicodeDecodeError_GetStart (PyObject *exc,
          Py_ssize_t *start)
 -- C 函数: int PyUnicodeEncodeError_GetStart (PyObject *exc,
          Py_ssize_t *start)
 -- C 函数: int PyUnicodeTranslateError_GetStart (PyObject *exc,
          Py_ssize_t *start)

     Get the `start' attribute of the given exception object and place
     it into `*start'.  `start' must not be ‘NULL’.  Return ‘0’ on
     success, ‘-1’ on failure.

 -- C 函数: int PyUnicodeDecodeError_SetStart (PyObject *exc,
          Py_ssize_t start)
 -- C 函数: int PyUnicodeEncodeError_SetStart (PyObject *exc,
          Py_ssize_t start)
 -- C 函数: int PyUnicodeTranslateError_SetStart (PyObject *exc,
          Py_ssize_t start)

     Set the `start' attribute of the given exception object to `start'.
     Return ‘0’ on success, ‘-1’ on failure.

 -- C 函数: int PyUnicodeDecodeError_GetEnd (PyObject *exc,
          Py_ssize_t *end)
 -- C 函数: int PyUnicodeEncodeError_GetEnd (PyObject *exc,
          Py_ssize_t *end)
 -- C 函数: int PyUnicodeTranslateError_GetEnd (PyObject *exc,
          Py_ssize_t *end)

     Get the `end' attribute of the given exception object and place it
     into `*end'.  `end' must not be ‘NULL’.  Return ‘0’ on success,
     ‘-1’ on failure.

 -- C 函数: int PyUnicodeDecodeError_SetEnd (PyObject *exc,
          Py_ssize_t end)
 -- C 函数: int PyUnicodeEncodeError_SetEnd (PyObject *exc,
          Py_ssize_t end)
 -- C 函数: int PyUnicodeTranslateError_SetEnd (PyObject *exc,
          Py_ssize_t end)

     Set the `end' attribute of the given exception object to `end'.
     Return ‘0’ on success, ‘-1’ on failure.

 -- C 函数: PyObject* PyUnicodeDecodeError_GetReason (PyObject *exc)
 -- C 函数: PyObject* PyUnicodeEncodeError_GetReason (PyObject *exc)
 -- C 函数: PyObject* PyUnicodeTranslateError_GetReason (PyObject *exc)
     `Return value: New reference.' 返回给定异常对象的 `reason' 属性

 -- C 函数: int PyUnicodeDecodeError_SetReason (PyObject *exc, const
          char *reason)
 -- C 函数: int PyUnicodeEncodeError_SetReason (PyObject *exc, const
          char *reason)
 -- C 函数: int PyUnicodeTranslateError_SetReason (PyObject *exc, const
          char *reason)

     Set the `reason' attribute of the given exception object to
     `reason'.  Return ‘0’ on success, ‘-1’ on failure.


File: python.info,  Node: 递归控制,  Next: 标准异常,  Prev: Unicode 异常对象,  Up: 异常处理

7.5.9 递归控制
--------------

These two functions provide a way to perform safe recursive calls at the
C level, both in the core and in extension modules.  They are needed if
the recursive code does not necessarily invoke Python code (which tracks
its recursion depth automatically).

 -- C 函数: int Py_EnterRecursiveCall (const char *where)

     Marks a point where a recursive C-level call is about to be
     performed.

     If ‘USE_STACKCHECK’ is defined, this function checks if the OS
     stack overflowed using *note PyOS_CheckStack(): 3c34.  In this is
     the case, it sets a *note MemoryError: efc. and returns a nonzero
     value.

     The function then checks if the recursion limit is reached.  If
     this is the case, a *note RecursionError: 63d. is set and a nonzero
     value is returned.  Otherwise, zero is returned.

     `where' should be a string such as ‘" in instance check"’ to be
     concatenated to the *note RecursionError: 63d. message caused by
     the recursion depth limit.

 -- C 函数: void Py_LeaveRecursiveCall ()

     Ends a *note Py_EnterRecursiveCall(): 3c33.  Must be called once
     for each `successful' invocation of *note Py_EnterRecursiveCall():
     3c33.

Properly implementing *note tp_repr: 3b5d. for container types requires
special recursion handling.  In addition to protecting the stack, *note
tp_repr: 3b5d. also needs to track objects to prevent cycles.  The
following two functions facilitate this functionality.  Effectively,
these are the C equivalent to *note reprlib.recursive_repr(): b78.

 -- C 函数: int Py_ReprEnter (PyObject *object)

     Called at the beginning of the *note tp_repr: 3b5d. implementation
     to detect cycles.

     If the object has already been processed, the function returns a
     positive integer.  In that case the *note tp_repr: 3b5d.
     implementation should return a string object indicating a cycle.
     As examples, *note dict: 1b9. objects return ‘{...}’ and *note
     list: 263. objects return ‘[...]’.

     The function will return a negative integer if the recursion limit
     is reached.  In that case the *note tp_repr: 3b5d. implementation
     should typically return ‘NULL’.

     Otherwise, the function returns zero and the *note tp_repr: 3b5d.
     implementation can continue normally.

 -- C 函数: void Py_ReprLeave (PyObject *object)

     Ends a *note Py_ReprEnter(): 3c36.  Must be called once for each
     invocation of *note Py_ReprEnter(): 3c36. that returns zero.


File: python.info,  Node: 标准异常,  Next: 标准警告类别,  Prev: 递归控制,  Up: 异常处理

7.5.10 标准异常
---------------

All standard Python exceptions are available as global variables whose
names are ‘PyExc_’ followed by the Python exception name.  These have
the type *note PyObject*: 4c2.; they are all class objects.  For
completeness, here are all the variables:

C 名称                                        Python 名称                           注释
                                                                                    
---------------------------------------------------------------------------------------------------
                                                                                    
‘PyExc_BaseException’                         *note BaseException: 1a9.             (1)
                                                                                    
                                                                                    
‘PyExc_Exception’                             *note Exception: 1aa.                 (1)
                                                                                    
                                                                                    
‘PyExc_ArithmeticError’                       *note ArithmeticError: 170e.          (1)
                                                                                    
                                                                                    
‘PyExc_AssertionError’                        *note AssertionError: 103e.
                                              
                                                                                    
‘PyExc_AttributeError’                        *note AttributeError: 3a3.
                                              
                                                                                    
‘PyExc_BlockingIOError’                       *note BlockingIOError: 99f.
                                              
                                                                                    
‘PyExc_BrokenPipeError’                       *note BrokenPipeError: 9a5.
                                              
                                                                                    
‘PyExc_BufferError’                           *note BufferError: 1710.
                                              
                                                                                    
‘PyExc_ChildProcessError’                     *note ChildProcessError: 9a0.
                                              
                                                                                    
‘PyExc_ConnectionAbortedError’                *note ConnectionAbortedError: 9a6.
                                              
                                                                                    
‘PyExc_ConnectionError’                       *note ConnectionError: 6ef.
                                              
                                                                                    
‘PyExc_ConnectionRefusedError’                *note ConnectionRefusedError: 9a7.
                                              
                                                                                    
‘PyExc_ConnectionResetError’                  *note ConnectionResetError: 9a8.
                                              
                                                                                    
‘PyExc_EOFError’                              *note EOFError: c74.
                                              
                                                                                    
‘PyExc_FileExistsError’                       *note FileExistsError: 960.
                                              
                                                                                    
‘PyExc_FileNotFoundError’                     *note FileNotFoundError: 7c9.
                                              
                                                                                    
‘PyExc_FloatingPointError’                    *note FloatingPointError: 170f.
                                              
                                                                                    
‘PyExc_GeneratorExit’                         *note GeneratorExit: d3a.
                                              
                                                                                    
‘PyExc_ImportError’                           *note ImportError: 33d.
                                              
                                                                                    
‘PyExc_IndentationError’                      *note IndentationError: e80.
                                              
                                                                                    
‘PyExc_IndexError’                            *note IndexError: e7d.
                                              
                                                                                    
‘PyExc_InterruptedError’                      *note InterruptedError: 662.
                                              
                                                                                    
‘PyExc_IsADirectoryError’                     *note IsADirectoryError: 9a1.
                                              
                                                                                    
‘PyExc_KeyError’                              *note KeyError: 2c8.
                                              
                                                                                    
‘PyExc_KeyboardInterrupt’                     *note KeyboardInterrupt: 198.
                                              
                                                                                    
‘PyExc_LookupError’                           *note LookupError: 166d.              (1)
                                                                                    
                                                                                    
‘PyExc_MemoryError’                           *note MemoryError: efc.
                                              
                                                                                    
‘PyExc_ModuleNotFoundError’                   *note ModuleNotFoundError: 3a2.
                                              
                                                                                    
‘PyExc_NameError’                             *note NameError: d83.
                                              
                                                                                    
‘PyExc_NotADirectoryError’                    *note NotADirectoryError: 9a2.
                                              
                                                                                    
‘PyExc_NotImplementedError’                   *note NotImplementedError: 617.
                                              
                                                                                    
‘PyExc_OSError’                               *note OSError: 1d4.                   (1)
                                                                                    
                                                                                    
‘PyExc_OverflowError’                         *note OverflowError: 968.
                                              
                                                                                    
‘PyExc_PermissionError’                       *note PermissionError: 608.
                                              
                                                                                    
‘PyExc_ProcessLookupError’                    *note ProcessLookupError: 9a3.
                                              
                                                                                    
‘PyExc_RecursionError’                        *note RecursionError: 63d.
                                              
                                                                                    
‘PyExc_ReferenceError’                        *note ReferenceError: e55.            (2)
                                                                                    
                                                                                    
‘PyExc_RuntimeError’                          *note RuntimeError: 2bb.
                                              
                                                                                    
‘PyExc_StopAsyncIteration’                    *note StopAsyncIteration: 1022.
                                              
                                                                                    
‘PyExc_StopIteration’                         *note StopIteration: 48e.
                                              
                                                                                    
‘PyExc_SyntaxError’                           *note SyntaxError: 460.
                                              
                                                                                    
‘PyExc_SystemError’                           *note SystemError: 604.
                                              
                                                                                    
‘PyExc_SystemExit’                            *note SystemExit: 605.
                                              
                                                                                    
‘PyExc_TabError’                              *note TabError: e7f.
                                              
                                                                                    
‘PyExc_TimeoutError’                          *note TimeoutError: 9a4.
                                              
                                                                                    
‘PyExc_TypeError’                             *note TypeError: 193.
                                              
                                                                                    
‘PyExc_UnboundLocalError’                     *note UnboundLocalError: e7e.
                                              
                                                                                    
‘PyExc_UnicodeDecodeError’                    *note UnicodeDecodeError: 1fe.
                                              
                                                                                    
‘PyExc_UnicodeEncodeError’                    *note UnicodeEncodeError: 1fd.
                                              
                                                                                    
‘PyExc_UnicodeError’                          *note UnicodeError: c43.
                                              
                                                                                    
‘PyExc_UnicodeTranslateError’                 *note UnicodeTranslateError: 1725.
                                              
                                                                                    
‘PyExc_ValueError’                            *note ValueError: 1fc.
                                              
                                                                                    
‘PyExc_ZeroDivisionError’                     *note ZeroDivisionError: 12bd.
                                              

3.3 新版功能: ‘PyExc_BlockingIOError’, ‘PyExc_BrokenPipeError’,
‘PyExc_ChildProcessError’, ‘PyExc_ConnectionError’,
‘PyExc_ConnectionAbortedError’, ‘PyExc_ConnectionRefusedError’,
‘PyExc_ConnectionResetError’, ‘PyExc_FileExistsError’,
‘PyExc_FileNotFoundError’, ‘PyExc_InterruptedError’,
‘PyExc_IsADirectoryError’, ‘PyExc_NotADirectoryError’,
‘PyExc_PermissionError’, ‘PyExc_ProcessLookupError’ and
‘PyExc_TimeoutError’ 介绍如下 PEP 3151(1).

3.5 新版功能: ‘PyExc_StopAsyncIteration’ 和 ‘PyExc_RecursionError’.

3.6 新版功能: ‘PyExc_ModuleNotFoundError’.

这些是兼容性别名 ‘PyExc_OSError’:

C 名称                                    注释
                                          
---------------------------------------------------------
                                          
‘PyExc_EnvironmentError’

‘PyExc_IOError’

‘PyExc_WindowsError’                      (3)
                                          

在 3.3 版更改: 这些别名曾经是单独的异常类型。

注释:

  1. 这是其他标准异常的基类。

  2. Only defined on Windows; protect code that uses this by testing
     that the preprocessor macro ‘MS_WINDOWS’ is defined.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3151


File: python.info,  Node: 标准警告类别,  Prev: 标准异常,  Up: 异常处理

7.5.11 标准警告类别
-------------------

All standard Python warning categories are available as global variables
whose names are ‘PyExc_’ followed by the Python exception name.  These
have the type *note PyObject*: 4c2.; they are all class objects.  For
completeness, here are all the variables:

C 名称                                         Python 名称                           注释
                                                                                     
----------------------------------------------------------------------------------------------------
                                                                                     
‘PyExc_Warning’                                *note Warning: 172a.                  (1)
                                                                                     
                                                                                     
‘PyExc_BytesWarning’                           *note BytesWarning: 4bd.
                                               
                                                                                     
‘PyExc_DeprecationWarning’                     *note DeprecationWarning: 279.
                                               
                                                                                     
‘PyExc_FutureWarning’                          *note FutureWarning: 32e.
                                               
                                                                                     
‘PyExc_ImportWarning’                          *note ImportWarning: 5e1.
                                               
                                                                                     
‘PyExc_PendingDeprecationWarning’              *note PendingDeprecationWarning: 27a.
                                               
                                                                                     
‘PyExc_ResourceWarning’                        *note ResourceWarning: 4d8.
                                               
                                                                                     
‘PyExc_RuntimeWarning’                         *note RuntimeWarning: 2c1.
                                               
                                                                                     
‘PyExc_SyntaxWarning’                          *note SyntaxWarning: 192.
                                               
                                                                                     
‘PyExc_UnicodeWarning’                         *note UnicodeWarning: d8f.
                                               
                                                                                     
‘PyExc_UserWarning’                            *note UserWarning: 172b.
                                               

3.2 新版功能: ‘PyExc_ResourceWarning’.

注释:

  1. 这是其他标准警告类别的基类。


File: python.info,  Node: 工具<2>,  Next: 抽象对象层,  Prev: 异常处理,  Up: Python/C API 参考手册

7.6 工具
========

本章中的函数执行各种实用工具任务，包括帮助 C 代码提升跨平台可移植性，在
C 中使用 Python 模块，以及解析函数参数并根据 C 中的值构建 Python 中的值
等等。

* Menu:

* 操作系统实用程序::
* 系统功能::
* 过程控制::
* 导入模块: 导入模块<2>.
* 数据 marshal 操作支持::
* 解析参数并构建值变量::
* 字符串转换与格式化::
* 反射::
* 编解码器注册与支持功能::


File: python.info,  Node: 操作系统实用程序,  Next: 系统功能,  Up: 工具<2>

7.6.1 操作系统实用程序
----------------------

 -- C 函数: PyObject* PyOS_FSPath (PyObject *path)
     `Return value: New reference.'  Return the file system
     representation for `path'.  If the object is a *note str: 339. or
     *note bytes: 33a. object, then its reference count is incremented.
     If the object implements the *note os.PathLike: 4f3. interface,
     then *note __fspath__(): 4f4. is returned as long as it is a *note
     str: 339. or *note bytes: 33a. object.  Otherwise *note TypeError:
     193. is raised and ‘NULL’ is returned.

     3.6 新版功能.

 -- C 函数: int Py_FdIsInteractive (FILE *fp, const char *filename)

     Return true (nonzero) if the standard I/O file `fp' with name
     `filename' is deemed interactive.  This is the case for files for
     which ‘isatty(fileno(fp))’ is true.  If the global flag *note
     Py_InteractiveFlag: 3c42. is true, this function also returns true
     if the `filename' pointer is ‘NULL’ or if the name is equal to one
     of the strings ‘'<stdin>'’ or ‘'???'’.

 -- C 函数: void PyOS_BeforeFork ()

     Function to prepare some internal state before a process fork.
     This should be called before calling ‘fork()’ or any similar
     function that clones the current process.  Only available on
     systems where ‘fork()’ is defined.

          警告: The C ‘fork()’ call should only be made from the *note
          "main" thread: 3c43. (of the *note "main" interpreter: 3c44.).
          The same is true for ‘PyOS_BeforeFork()’.

     3.7 新版功能.

 -- C 函数: void PyOS_AfterFork_Parent ()

     Function to update some internal state after a process fork.  This
     should be called from the parent process after calling ‘fork()’ or
     any similar function that clones the current process, regardless of
     whether process cloning was successful.  Only available on systems
     where ‘fork()’ is defined.

          警告: The C ‘fork()’ call should only be made from the *note
          "main" thread: 3c43. (of the *note "main" interpreter: 3c44.).
          The same is true for ‘PyOS_AfterFork_Parent()’.

     3.7 新版功能.

 -- C 函数: void PyOS_AfterFork_Child ()

     Function to update internal interpreter state after a process fork.
     This must be called from the child process after calling ‘fork()’,
     or any similar function that clones the current process, if there
     is any chance the process will call back into the Python
     interpreter.  Only available on systems where ‘fork()’ is defined.

          警告: The C ‘fork()’ call should only be made from the *note
          "main" thread: 3c43. (of the *note "main" interpreter: 3c44.).
          The same is true for ‘PyOS_AfterFork_Child()’.

     3.7 新版功能.

     参见
     ....

     *note os.register_at_fork(): 3be. allows registering custom Python
     functions to be called by *note PyOS_BeforeFork(): 43a, *note
     PyOS_AfterFork_Parent(): 43b. and *note PyOS_AfterFork_Child():
     2ce.

 -- C 函数: void PyOS_AfterFork ()

     Function to update some internal state after a process fork; this
     should be called in the new process if the Python interpreter will
     continue to be used.  If a new executable is loaded into the new
     process, this function does not need to be called.

     3.7 版后已移除: This function is superseded by *note
     PyOS_AfterFork_Child(): 2ce.

 -- C 函数: int PyOS_CheckStack ()

     Return true when the interpreter runs out of stack space.  This is
     a reliable check, but is only available when ‘USE_STACKCHECK’ is
     defined (currently on Windows using the Microsoft Visual C++
     compiler).  ‘USE_STACKCHECK’ will be defined automatically; you
     should never change the definition in your own code.

 -- C 函数: PyOS_sighandler_t PyOS_getsig (int i)

     Return the current signal handler for signal `i'.  This is a thin
     wrapper around either ‘sigaction()’ or ‘signal()’.  Do not call
     those functions directly!  ‘PyOS_sighandler_t’ is a typedef alias
     for ‘void (*)(int)’.

 -- C 函数: PyOS_sighandler_t PyOS_setsig (int i, PyOS_sighandler_t h)

     Set the signal handler for signal `i' to be `h'; return the old
     signal handler.  This is a thin wrapper around either ‘sigaction()’
     or ‘signal()’.  Do not call those functions directly!
     ‘PyOS_sighandler_t’ is a typedef alias for ‘void (*)(int)’.

 -- C 函数: wchar_t* Py_DecodeLocale (const char* arg, size_t *size)

     Decode a byte string from the locale encoding with the *note
     surrogateescape error handler: 1858.: undecodable bytes are decoded
     as characters in range U+DC80..U+DCFF. If a byte sequence can be
     decoded as a surrogate character, escape the bytes using the
     surrogateescape error handler instead of decoding them.

     Encoding, highest priority to lowest priority:

        * ‘UTF-8’ on macOS, Android, and VxWorks;

        * ‘UTF-8’ on Windows if *note Py_LegacyWindowsFSEncodingFlag:
          3c47. is zero;

        * ‘UTF-8’ if the Python UTF-8 mode is enabled;

        * ‘ASCII’ if the ‘LC_CTYPE’ locale is ‘"C"’,
          ‘nl_langinfo(CODESET)’ returns the ‘ASCII’ encoding (or an
          alias), and ‘mbstowcs()’ and ‘wcstombs()’ functions uses the
          ‘ISO-8859-1’ encoding.

        * the current locale encoding.

     Return a pointer to a newly allocated wide character string, use
     *note PyMem_RawFree(): 3c48. to free the memory.  If size is not
     ‘NULL’, write the number of wide characters excluding the null
     character into ‘*size’

     Return ‘NULL’ on decoding error or memory allocation error.  If
     `size' is not ‘NULL’, ‘*size’ is set to ‘(size_t)-1’ on memory
     error or set to ‘(size_t)-2’ on decoding error.

     Decoding errors should never happen, unless there is a bug in the C
     library.

     Use the *note Py_EncodeLocale(): 445. function to encode the
     character string back to a byte string.

     参见
     ....

     The *note PyUnicode_DecodeFSDefaultAndSize(): 3c49. and *note
     PyUnicode_DecodeLocaleAndSize(): 446. functions.

     3.5 新版功能.

     在 3.7 版更改: The function now uses the UTF-8 encoding in the
     UTF-8 mode.

     在 3.8 版更改: The function now uses the UTF-8 encoding on Windows
     if *note Py_LegacyWindowsFSEncodingFlag: 3c47. is zero;

 -- C 函数: char* Py_EncodeLocale (const wchar_t *text,
          size_t *error_pos)

     Encode a wide character string to the locale encoding with the
     *note surrogateescape error handler: 1858.: surrogate characters in
     the range U+DC80..U+DCFF are converted to bytes 0x80..0xFF.

     Encoding, highest priority to lowest priority:

        * ‘UTF-8’ on macOS, Android, and VxWorks;

        * ‘UTF-8’ on Windows if *note Py_LegacyWindowsFSEncodingFlag:
          3c47. is zero;

        * ‘UTF-8’ if the Python UTF-8 mode is enabled;

        * ‘ASCII’ if the ‘LC_CTYPE’ locale is ‘"C"’,
          ‘nl_langinfo(CODESET)’ returns the ‘ASCII’ encoding (or an
          alias), and ‘mbstowcs()’ and ‘wcstombs()’ functions uses the
          ‘ISO-8859-1’ encoding.

        * the current locale encoding.

     The function uses the UTF-8 encoding in the Python UTF-8 mode.

     Return a pointer to a newly allocated byte string, use *note
     PyMem_Free(): db1. to free the memory.  Return ‘NULL’ on encoding
     error or memory allocation error

     If error_pos is not ‘NULL’, ‘*error_pos’ is set to ‘(size_t)-1’ on
     success, or set to the index of the invalid character on encoding
     error.

     Use the *note Py_DecodeLocale(): 444. function to decode the bytes
     string back to a wide character string.

     参见
     ....

     The *note PyUnicode_EncodeFSDefault(): 105b. and *note
     PyUnicode_EncodeLocale(): 447. functions.

     3.5 新版功能.

     在 3.7 版更改: The function now uses the UTF-8 encoding in the
     UTF-8 mode.

     在 3.8 版更改: The function now uses the UTF-8 encoding on Windows
     if *note Py_LegacyWindowsFSEncodingFlag: 3c47. is zero;


File: python.info,  Node: 系统功能,  Next: 过程控制,  Prev: 操作系统实用程序,  Up: 工具<2>

7.6.2 系统功能
--------------

These are utility functions that make functionality from the *note sys:
fe. module accessible to C code.  They all work with the current
interpreter thread’s *note sys: fe. module’s dict, which is contained in
the internal thread state structure.

 -- C 函数: PyObject *PySys_GetObject (const char *name)
     `Return value: Borrowed reference.'  Return the object `name' from
     the *note sys: fe. module or ‘NULL’ if it does not exist, without
     setting an exception.

 -- C 函数: int PySys_SetObject (const char *name, PyObject *v)

     Set `name' in the *note sys: fe. module to `v' unless `v' is
     ‘NULL’, in which case `name' is deleted from the sys module.
     Returns ‘0’ on success, ‘-1’ on error.

 -- C 函数: void PySys_ResetWarnOptions ()

     Reset *note sys.warnoptions: 41e. to an empty list.  This function
     may be called prior to *note Py_Initialize(): 441.

 -- C 函数: void PySys_AddWarnOption (const wchar_t *s)

     Append `s' to *note sys.warnoptions: 41e.  This function must be
     called prior to *note Py_Initialize(): 441. in order to affect the
     warnings filter list.

 -- C 函数: void PySys_AddWarnOptionUnicode (PyObject *unicode)

     Append `unicode' to *note sys.warnoptions: 41e.

     Note: this function is not currently usable from outside the
     CPython implementation, as it must be called prior to the implicit
     import of *note warnings: 127. in *note Py_Initialize(): 441. to be
     effective, but can’t be called until enough of the runtime has been
     initialized to permit the creation of Unicode objects.

 -- C 函数: void PySys_SetPath (const wchar_t *path)

     Set *note sys.path: 490. to a list object of paths found in `path'
     which should be a list of paths separated with the platform’s
     search path delimiter (‘:’ on Unix, ‘;’ on Windows).

 -- C 函数: void PySys_WriteStdout (const char *format, ...)

     Write the output string described by `format' to *note sys.stdout:
     317.  No exceptions are raised, even if truncation occurs (see
     below).

     `format' should limit the total size of the formatted output string
     to 1000 bytes or less – after 1000 bytes, the output string is
     truncated.  In particular, this means that no unrestricted "%s"
     formats should occur; these should be limited using "%.<N>s" where
     <N> is a decimal number calculated so that <N> plus the maximum
     size of other formatted text does not exceed 1000 bytes.  Also
     watch out for "%f", which can print hundreds of digits for very
     large numbers.

     If a problem occurs, or *note sys.stdout: 317. is unset, the
     formatted message is written to the real (C level) `stdout'.

 -- C 函数: void PySys_WriteStderr (const char *format, ...)

     As *note PySys_WriteStdout(): 3c50, but write to *note sys.stderr:
     318. or `stderr' instead.

 -- C 函数: void PySys_FormatStdout (const char *format, ...)

     Function similar to PySys_WriteStdout() but format the message
     using *note PyUnicode_FromFormatV(): 3c53. and don’t truncate the
     message to an arbitrary length.

     3.2 新版功能.

 -- C 函数: void PySys_FormatStderr (const char *format, ...)

     As *note PySys_FormatStdout(): 3c52, but write to *note sys.stderr:
     318. or `stderr' instead.

     3.2 新版功能.

 -- C 函数: void PySys_AddXOption (const wchar_t *s)

     Parse `s' as a set of *note -X: 156. options and add them to the
     current options mapping as returned by *note PySys_GetXOptions():
     3c56.  This function may be called prior to *note Py_Initialize():
     441.

     3.2 新版功能.

 -- C 函数: PyObject *PySys_GetXOptions ()
     `Return value: Borrowed reference.'  Return the current dictionary
     of *note -X: 156. options, similarly to *note sys._xoptions: 1361.
     On error, ‘NULL’ is returned and an exception is set.

     3.2 新版功能.

 -- C 函数: int PySys_Audit (const char *event, const char *format, ...)

     Raise an auditing event with any active hooks.  Return zero for
     success and non-zero with an exception set on failure.

     If any hooks have been added, `format' and other arguments will be
     used to construct a tuple to pass.  Apart from ‘N’, the same format
     characters as used in *note Py_BuildValue(): 2cf. are available.
     If the built value is not a tuple, it will be added into a
     single-element tuple.  (The ‘N’ format option consumes a reference,
     but since there is no way to know whether arguments to this
     function will be consumed, using it may cause reference leaks.)

     Note that ‘#’ format characters should always be treated as
     ‘Py_ssize_t’, regardless of whether ‘PY_SSIZE_T_CLEAN’ was defined.

     *note sys.audit(): f38. performs the same function from Python
     code.

     3.8 新版功能.

     在 3.8.2 版更改: Require ‘Py_ssize_t’ for ‘#’ format characters.
     Previously, an unavoidable deprecation warning was raised.

 -- C 函数: int PySys_AddAuditHook (Py_AuditHookFunction hook,
          void *userData)

     Append the callable `hook' to the list of active auditing hooks.
     Return zero for success and non-zero on failure.  If the runtime
     has been initialized, also set an error on failure.  Hooks added
     through this API are called for all interpreters created by the
     runtime.

     `userData' 指针会被传入钩子函数。 因于钩子函数可能由不同的运行时调
     用，该指针不应直接指向 Python 状态。

     This function is safe to call before *note Py_Initialize(): 441.
     When called after runtime initialization, existing audit hooks are
     notified and may silently abort the operation by raising an error
     subclassed from *note Exception: 1aa. (other errors will not be
     silenced).

     The hook function is of type ‘int (*)(const char *event, PyObject
     *args, void *userData)’, where `args' is guaranteed to be a *note
     PyTupleObject: 3c57.  The hook function is always called with the
     GIL held by the Python interpreter that raised the event.

     See PEP 578(1) for a detailed description of auditing.  Functions
     in the runtime and standard library that raise events are listed in
     the *note audit events table: 34cd.  Details are in each function’s
     documentation.

     引发一个 *note 审计事件: ea1. ‘sys.addaudithook’，没有附带参数。

     3.8 新版功能.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0578


File: python.info,  Node: 过程控制,  Next: 导入模块<2>,  Prev: 系统功能,  Up: 工具<2>

7.6.3 过程控制
--------------

 -- C 函数: void Py_FatalError (const char *message)

     Print a fatal error message and kill the process.  No cleanup is
     performed.  This function should only be invoked when a condition
     is detected that would make it dangerous to continue using the
     Python interpreter; e.g., when the object administration appears to
     be corrupted.  On Unix, the standard C library function ‘abort()’
     is called which will attempt to produce a ‘core’ file.

 -- C 函数: void Py_Exit (int status)

     Exit the current process.  This calls *note Py_FinalizeEx(): 5d2.
     and then calls the standard C library function ‘exit(status)’.  If
     *note Py_FinalizeEx(): 5d2. indicates an error, the exit status is
     set to 120.

     在 3.6 版更改: Errors from finalization no longer ignored.

 -- C 函数: int Py_AtExit (void (*func)())

     Register a cleanup function to be called by *note Py_FinalizeEx():
     5d2.  The cleanup function will be called with no arguments and
     should return no value.  At most 32 cleanup functions can be
     registered.  When the registration is successful, *note
     Py_AtExit(): 3c5a. returns ‘0’; on failure, it returns ‘-1’.  The
     cleanup function registered last is called first.  Each cleanup
     function will be called at most once.  Since Python’s internal
     finalization will have completed before the cleanup function, no
     Python APIs should be called by `func'.


File: python.info,  Node: 导入模块<2>,  Next: 数据 marshal 操作支持,  Prev: 过程控制,  Up: 工具<2>

7.6.4 导入模块
--------------

 -- C 函数: PyObject* PyImport_ImportModule (const char *name)
     `Return value: New reference.'

     This is a simplified interface to *note PyImport_ImportModuleEx():
     b29. below, leaving the `globals' and `locals' arguments set to
     ‘NULL’ and `level' set to 0.  When the `name' argument contains a
     dot (when it specifies a submodule of a package), the `fromlist'
     argument is set to the list ‘['*']’ so that the return value is the
     named module rather than the top-level package containing it as
     would otherwise be the case.  (Unfortunately, this has an
     additional side effect when `name' in fact specifies a subpackage
     instead of a submodule: the submodules specified in the package’s
     ‘__all__’ variable are loaded.)  Return a new reference to the
     imported module, or ‘NULL’ with an exception set on failure.  A
     failing import of a module doesn’t leave the module in *note
     sys.modules: f36.

     该函数总是使用绝对路径导入。

 -- C 函数: PyObject* PyImport_ImportModuleNoBlock (const char *name)
     `Return value: New reference.' 该函数是 *note
     PyImport_ImportModule(): c7b. 的一个被遗弃的别名。

     在 3.3 版更改: This function used to fail immediately when the
     import lock was held by another thread.  In Python 3.3 though, the
     locking scheme switched to per-module locks for most purposes, so
     this function’s special behaviour isn’t needed anymore.

 -- C 函数: PyObject* PyImport_ImportModuleEx (const char *name,
          PyObject *globals, PyObject *locals, PyObject *fromlist)
     `Return value: New reference.'

     Import a module.  This is best described by referring to the
     built-in Python function *note __import__(): 619.

     The return value is a new reference to the imported module or
     top-level package, or ‘NULL’ with an exception set on failure.
     Like for *note __import__(): 619, the return value when a submodule
     of a package was requested is normally the top-level package,
     unless a non-empty `fromlist' was given.

     Failing imports remove incomplete module objects, like with *note
     PyImport_ImportModule(): c7b.

 -- C 函数: PyObject* PyImport_ImportModuleLevelObject (PyObject *name,
          PyObject *globals, PyObject *locals, PyObject *fromlist,
          int level)
     `Return value: New reference.'  Import a module.  This is best
     described by referring to the built-in Python function *note
     __import__(): 619, as the standard *note __import__(): 619.
     function calls this function directly.

     The return value is a new reference to the imported module or
     top-level package, or ‘NULL’ with an exception set on failure.
     Like for *note __import__(): 619, the return value when a submodule
     of a package was requested is normally the top-level package,
     unless a non-empty `fromlist' was given.

     3.3 新版功能.

 -- C 函数: PyObject* PyImport_ImportModuleLevel (const char *name,
          PyObject *globals, PyObject *locals, PyObject *fromlist,
          int level)
     `Return value: New reference.'  Similar to *note
     PyImport_ImportModuleLevelObject(): 3c5e, but the name is a UTF-8
     encoded string instead of a Unicode object.

     在 3.3 版更改: Negative values for `level' are no longer accepted.

 -- C 函数: PyObject* PyImport_Import (PyObject *name)
     `Return value: New reference.'  This is a higher-level interface
     that calls the current "import hook function" (with an explicit
     `level' of 0, meaning absolute import).  It invokes the *note
     __import__(): 619. function from the ‘__builtins__’ of the current
     globals.  This means that the import is done using whatever import
     hooks are installed in the current environment.

     该函数总是使用绝对路径导入。

 -- C 函数: PyObject* PyImport_ReloadModule (PyObject *m)
     `Return value: New reference.'  Reload a module.  Return a new
     reference to the reloaded module, or ‘NULL’ with an exception set
     on failure (the module still exists in this case).

 -- C 函数: PyObject* PyImport_AddModuleObject (PyObject *name)
     `Return value: Borrowed reference.'  Return the module object
     corresponding to a module name.  The `name' argument may be of the
     form ‘package.module’.  First check the modules dictionary if
     there’s one there, and if not, create a new one and insert it in
     the modules dictionary.  Return ‘NULL’ with an exception set on
     failure.

          注解: This function does not load or import the module; if the
          module wasn’t already loaded, you will get an empty module
          object.  Use *note PyImport_ImportModule(): c7b. or one of its
          variants to import a module.  Package structures implied by a
          dotted name for `name' are not created if not already present.

     3.3 新版功能.

 -- C 函数: PyObject* PyImport_AddModule (const char *name)
     `Return value: Borrowed reference.'  Similar to *note
     PyImport_AddModuleObject(): 3c60, but the name is a UTF-8 encoded
     string instead of a Unicode object.

 -- C 函数: PyObject* PyImport_ExecCodeModule (const char *name,
          PyObject *co)
     `Return value: New reference.'

     Given a module name (possibly of the form ‘package.module’) and a
     code object read from a Python bytecode file or obtained from the
     built-in function *note compile(): 1b5, load the module.  Return a
     new reference to the module object, or ‘NULL’ with an exception set
     if an error occurred.  `name' is removed from *note sys.modules:
     f36. in error cases, even if `name' was already in *note
     sys.modules: f36. on entry to *note PyImport_ExecCodeModule():
     3c61.  Leaving incompletely initialized modules in *note
     sys.modules: f36. is dangerous, as imports of such modules have no
     way to know that the module object is an unknown (and probably
     damaged with respect to the module author’s intents) state.

     The module’s *note __spec__: ec8. and *note __loader__: 95e. will
     be set, if not set already, with the appropriate values.  The
     spec’s loader will be set to the module’s ‘__loader__’ (if set) and
     to an instance of ‘SourceFileLoader’ otherwise.

     The module’s *note __file__: ec7. attribute will be set to the code
     object’s ‘co_filename’.  If applicable, *note __cached__: b3a. will
     also be set.

     This function will reload the module if it was already imported.
     See *note PyImport_ReloadModule(): 3c5f. for the intended way to
     reload a module.

     If `name' points to a dotted name of the form ‘package.module’, any
     package structures not already created will still not be created.

     See also *note PyImport_ExecCodeModuleEx(): 3c62. and *note
     PyImport_ExecCodeModuleWithPathnames(): 3c63.

 -- C 函数: PyObject* PyImport_ExecCodeModuleEx (const char *name,
          PyObject *co, const char *pathname)
     `Return value: New reference.'  Like *note
     PyImport_ExecCodeModule(): 3c61, but the *note __file__: ec7.
     attribute of the module object is set to `pathname' if it is
     non-‘NULL’.

     参见 *note PyImport_ExecCodeModuleWithPathnames(): 3c63.。

 -- C 函数: PyObject* PyImport_ExecCodeModuleObject (PyObject *name,
          PyObject *co, PyObject *pathname, PyObject *cpathname)
     `Return value: New reference.'  Like *note
     PyImport_ExecCodeModuleEx(): 3c62, but the *note __cached__: b3a.
     attribute of the module object is set to `cpathname' if it is
     non-‘NULL’.  Of the three functions, this is the preferred one to
     use.

     3.3 新版功能.

 -- C 函数: PyObject* PyImport_ExecCodeModuleWithPathnames (const
          char *name, PyObject *co, const char *pathname, const
          char *cpathname)
     `Return value: New reference.'  Like *note
     PyImport_ExecCodeModuleObject(): 3c64, but `name', `pathname' and
     `cpathname' are UTF-8 encoded strings.  Attempts are also made to
     figure out what the value for `pathname' should be from `cpathname'
     if the former is set to ‘NULL’.

     3.2 新版功能.

     在 3.3 版更改: Uses *note imp.source_from_cache(): 3ae8. in
     calculating the source path if only the bytecode path is provided.

 -- C 函数: long PyImport_GetMagicNumber ()

     Return the magic number for Python bytecode files (a.k.a.  ‘.pyc’
     file).  The magic number should be present in the first four bytes
     of the bytecode file, in little-endian byte order.  Returns ‘-1’ on
     error.

     在 3.3 版更改: 失败时返回值 ‘-1’。

 -- C 函数: const char * PyImport_GetMagicTag ()

     Return the magic tag string for PEP 3147(1) format Python bytecode
     file names.  Keep in mind that the value at
     ‘sys.implementation.cache_tag’ is authoritative and should be used
     instead of this function.

     3.2 新版功能.

 -- C 函数: PyObject* PyImport_GetModuleDict ()
     `Return value: Borrowed reference.'  Return the dictionary used for
     the module administration (a.k.a.  ‘sys.modules’).  Note that this
     is a per-interpreter variable.

 -- C 函数: PyObject* PyImport_GetModule (PyObject *name)
     `Return value: New reference.'  Return the already imported module
     with the given name.  If the module has not been imported yet then
     returns ‘NULL’ but does not set an error.  Returns ‘NULL’ and sets
     an error if the lookup failed.

     3.7 新版功能.

 -- C 函数: PyObject* PyImport_GetImporter (PyObject *path)
     `Return value: New reference.'  Return a finder object for a *note
     sys.path: 490./‘pkg.__path__’ item `path', possibly by fetching it
     from the *note sys.path_importer_cache: 4a5. dict.  If it wasn’t
     yet cached, traverse *note sys.path_hooks: 964. until a hook is
     found that can handle the path item.  Return ‘None’ if no hook
     could; this tells our caller that the *note path based finder:
     14d0. could not find a finder for this path item.  Cache the result
     in *note sys.path_importer_cache: 4a5.  Return a new reference to
     the finder object.

 -- C 函数: void _PyImport_Init ()

     Initialize the import mechanism.  For internal use only.

 -- C 函数: void PyImport_Cleanup ()

     Empty the module table.  For internal use only.

 -- C 函数: void _PyImport_Fini ()

     Finalize the import mechanism.  For internal use only.

 -- C 函数: int PyImport_ImportFrozenModuleObject (PyObject *name)
     `Return value: New reference.'  Load a frozen module named `name'.
     Return ‘1’ for success, ‘0’ if the module is not found, and ‘-1’
     with an exception set if the initialization failed.  To access the
     imported module on a successful load, use *note
     PyImport_ImportModule(): c7b.  (Note the misnomer — this function
     would reload the module if it was already imported.)

     3.3 新版功能.

     在 3.4 版更改: The ‘__file__’ attribute is no longer set on the
     module.

 -- C 函数: int PyImport_ImportFrozenModule (const char *name)

     Similar to *note PyImport_ImportFrozenModuleObject(): 3c6b, but the
     name is a UTF-8 encoded string instead of a Unicode object.

 -- C 类型: struct _frozen

     This is the structure type definition for frozen module
     descriptors, as generated by the ‘freeze’ utility (see
     ‘Tools/freeze/’ in the Python source distribution).  Its
     definition, found in ‘Include/import.h’, is:

          struct _frozen {
              const char *name;
              const unsigned char *code;
              int size;
          };

 -- C 变量: const struct _frozen* PyImport_FrozenModules

     该指针被初始化为指向 ‘struct _frozen’ 数组，以 ‘NULL’ 或者 0 作为结
     束标记。当一个冻结模块被导入，首先要在这个表中搜索。第三方库可以以
     此来提供动态创建的冻结模块集合。

 -- C 函数: int PyImport_AppendInittab (const char *name, PyObject*
          (*initfunc)(void))

     Add a single module to the existing table of built-in modules.
     This is a convenience wrapper around *note
     PyImport_ExtendInittab(): 3c6e, returning ‘-1’ if the table could
     not be extended.  The new module can be imported by the name
     `name', and uses the function `initfunc' as the initialization
     function called on the first attempted import.  This should be
     called before *note Py_Initialize(): 441.

 -- C 类型: struct _inittab

     Structure describing a single entry in the list of built-in
     modules.  Each of these structures gives the name and
     initialization function for a module built into the interpreter.
     The name is an ASCII encoded string.  Programs which embed Python
     may use an array of these structures in conjunction with *note
     PyImport_ExtendInittab(): 3c6e. to provide additional built-in
     modules.  The structure is defined in ‘Include/import.h’ as:

          struct _inittab {
              const char *name;           /* ASCII encoded string */
              PyObject* (*initfunc)(void);
          };

 -- C 函数: int PyImport_ExtendInittab (struct _inittab *newtab)

     Add a collection of modules to the table of built-in modules.  The
     `newtab' array must end with a sentinel entry which contains ‘NULL’
     for the ‘name’ field; failure to provide the sentinel value can
     result in a memory fault.  Returns ‘0’ on success or ‘-1’ if
     insufficient memory could be allocated to extend the internal
     table.  In the event of failure, no modules are added to the
     internal table.  This should be called before *note
     Py_Initialize(): 441.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: 数据 marshal 操作支持,  Next: 解析参数并构建值变量,  Prev: 导入模块<2>,  Up: 工具<2>

7.6.5 数据 marshal 操作支持
---------------------------

这些例程允许 C 代码处理与 *note marshal: b1. 模块所用相同数据格式的序列
化对象。 其中有些函数可用来将数据写入这种序列化格式，另一些函数则可用来
读取并恢复数据。 用于存储 marshal 数据的文件必须以二进制模式打开。

数字值在存储时会将最低位字节放在开头。

此模块支持两种数据格式版本：第 0 版为历史版本，第 1 版本会在文件和
marshal 反序列化中共享固化的字符串。 第 2 版本会对浮点数使用二进制格式。
‘Py_MARSHAL_VERSION’ 指明了当前文件的格式（当前取值为 2）。

 -- C 函数: void PyMarshal_WriteLongToFile (long value, FILE *file,
          int version)

     将一个 ‘long’ 整数 `value' 以 marshal 格式写入 `file'。 这将只写入
     `value' 最低的 32 位；无论本机 ‘long’ 类型的长度如何。 `version' 指
     明文件格式的版本。

 -- C 函数: void PyMarshal_WriteObjectToFile (PyObject *value,
          FILE *file, int version)

     将一个 Python 对象 `value' 以 marshal 格式写入 `file'。 `version' 指
     明文件格式的版本。

 -- C 函数: PyObject* PyMarshal_WriteObjectToString (PyObject *value,
          int version)
     `Return value: New reference.' 返回一个包含 `value' 的 marshal 表示
     形式的字节串对象。 `version' 指明文件格式的版本。

以下函数允许读取并恢复存储为 marshal 格式的值。

 -- C 函数: long PyMarshal_ReadLongFromFile (FILE *file)

     从打开用于读取的 ‘FILE*’ 的对应数据流返回一个 C ‘long’。 使用只函数
     只能读取 32 位的值，无论本机 ‘long’ 类型的长度为何。

     发生错误时，将设置适当的异常 (*note EOFError: c74.) 并返回 ‘-1’。

 -- C 函数: int PyMarshal_ReadShortFromFile (FILE *file)

     从打开用于读取的 ‘FILE*’ 的对应数据流返回一个 C ‘short’。 使用此函
     数只能读取 16 位的值，无论本机 ‘short’ 类型的长度为何。

     发生错误时，将设置适当的异常 (*note EOFError: c74.) 并返回 ‘-1’。

 -- C 函数: PyObject* PyMarshal_ReadObjectFromFile (FILE *file)
     `Return value: New reference.' 从打开用于读取的 ‘FILE*’ 的对应数据
     流返回一个 Python 对象。

     发生错误时，将设置适当的异常 (*note EOFError: c74, *note
     ValueError: 1fc. 或 *note TypeError: 193.) 并返回 ‘NULL’。

 -- C 函数: PyObject* PyMarshal_ReadLastObjectFromFile (FILE *file)
     `Return value: New reference.' 从打开用于读取的 ‘FILE*’ 的对应数据
     流返回一个 Python 对象。 不同于 *note
     PyMarshal_ReadObjectFromFile(): 3c78.，此函数假定将不再从该文件读取
     更多的对象，允许其将文件数据积极地载入内存，以便反序列化过程可以在
     内存中的数据上操作而不是每次从文件读取一个字节。 只有当你确定不会再
     从文件读取任何内容时方可使用此形式。

     发生错误时，将设置适当的异常 (*note EOFError: c74, *note
     ValueError: 1fc. 或 *note TypeError: 193.) 并返回 ‘NULL’。

 -- C 函数: PyObject* PyMarshal_ReadObjectFromString (const char *data,
          Py_ssize_t len)
     `Return value: New reference.' 从包含指向 `data' 的 `len' 个字节的
     字节缓冲区对应的数据流返回一个 Python 对象。

     发生错误时，将设置适当的异常 (*note EOFError: c74, *note
     ValueError: 1fc. 或 *note TypeError: 193.) 并返回 ‘NULL’。


File: python.info,  Node: 解析参数并构建值变量,  Next: 字符串转换与格式化,  Prev: 数据 marshal 操作支持,  Up: 工具<2>

7.6.6 解析参数并构建值变量
--------------------------

在创建你自己的扩展函数和方法时，这些函数是有用的。其它的信息和样例见
*note 扩展和嵌入 Python 解释器: 120d. 。

这些函数描述的前三个，*note PyArg_ParseTuple(): 26b.，*note
PyArg_ParseTupleAndKeywords(): 5d3.，以及 *note PyArg_Parse(): f75.，它
们都使用 `格式化字符串' 来将函数期待的参数告知函数。这些函数都使用相同语
法规则的格式化字符串。

* Menu:

* 解析参数: 解析参数<3>.
* 创建变量::


File: python.info,  Node: 解析参数<3>,  Next: 创建变量,  Up: 解析参数并构建值变量

7.6.6.1 解析参数
................

一个格式化字符串包含 0 或者更多的格式单元。一个格式单元用来描述一个
Python 对象；它通常是一个字符或者由括号括起来的格式单元序列。除了少数例
外，一个非括号序列的格式单元通常对应这些函数的具有单一地址的参数。在接下
来的描述中，双引号内的表达式是格式单元；圆括号 () 内的是对应这个格式单元
的 Python 对象类型；方括号 [] 内的是传递的 C 变量(变量集)类型。

* Menu:

* 字符串和缓存区::
* 数字: 数字<2>.
* 其他对象::
* API 函数::


File: python.info,  Node: 字符串和缓存区,  Next: 数字<2>,  Up: 解析参数<3>

7.6.6.2 字符串和缓存区
......................

这些格式允许将对象按照连续的内存块形式进行访问。你没必要提供返回的
unicode 字符或者字节区的原始数据存储。

一般的，当一个表达式设置一个指针指向一个缓冲区，这个缓冲区可以被相应的
Python 对象管理，并且这个缓冲区共享这个对象的生存周期。你不需要人为的释
放任何内存空间。除了这些 ‘es’, ‘es#’, ‘et’ and ‘et#’.

然而，当一个 *note Py_buffer: b23. 结构被赋值，其包含的缓冲区被锁住，所
以调用者在随后使用这个缓冲区，即使在 *note Py_BEGIN_ALLOW_THREADS: 3b29.
块中，可以避免可变数据因为调整大小或者被销毁所带来的风险。因此，`你不得
不调用' *note PyBuffer_Release(): d5c. 在你结束数据的处理时(或者在之前任
何中断事件中)

除非另有说明，缓冲区是不会以空终止的。

某些格式需要只读的 *note bytes-like object: 5f1.，并设置指针而不是缓冲区
结构。 他们通过检查对象的 *note PyBufferProcs.bf_releasebuffer: 3c7f. 字
段是否为 ‘NULL’ 来发挥作用，该字段不允许为 *note bytearray: 33b. 这样的
可变对象。

     注解: 所有 ‘#’ 表达式的变式(‘s#’，‘y#’，等等)，长度参数的类型(整型
     或者 ‘Py_ssize_t’)在包含 ‘Python.h’ 头文件之前由 ‘PY_SSIZE_T_CLEAN’
     宏的定义控制。如果这个宏被定义，长度是一个 ‘Py_ssize_t’ Python 元大
     小类型而不是一个 ‘int’ 整型。在未来的 Python 版本中将会改变，只支持
     ‘Py_ssize_t’ 而放弃支持 ‘int’ 整型。最好一直定义 ‘PY_SSIZE_T_CLEAN’
     这个宏。

‘s’ (*note str: 339.) [const char *]

     将一个 Unicode 对象转换成一个指向字符串的 C 指针。一个指针指向一个
     已经存在的字符串，这个字符串存储的是传如的字符指针变量。C 字符串是
     已空结束的。Python 字符串不能包含嵌入的无效的代码点；如果由，一个
     *note ValueError: 1fc. 异常会被引发。Unicode 对象被转化成 ‘'utf-8'’
     编码的 C 字符串。如果转换失败，一个 *note UnicodeError: c43. 异常被
     引发。

          注解: 这个表达式不接受 *note bytes-like objects: 5f1.。如果你
          想接受文件系统路径并将它们转化成 C 字符串，建议使用 ‘O&’ 表达
          式配合 *note PyUnicode_FSConverter(): 5d7. 作为 `转化函数'。

     在 3.5 版更改: 以前，当 Python 字符串中遇到了嵌入的 null 代码点会引
     发 *note TypeError: 193. 。

‘s*’ (*note str: 339. or *note bytes-like object: 5f1.) [Py_buffer]

     这个表达式既接受 Unicode 对象也接受类字节类型对象。它为由调用者提供
     的 *note Py_buffer: b23. 结构赋值。这里结果的 C 字符串可能包含嵌入
     的 NUL 字节。Unicode 对象通过 ‘'utf-8'’ 编码转化成 C 字符串。

‘s#’ (*note str: 339, 只读 *note bytes-like object: 5f1.) [const char *, int or ‘Py_ssize_t’]

     像 ‘s*’，除了它不接受易变的对象。结果存储在两个 C 变量中，第一个是
     指向 C 字符串的指针，第二个是它的长度。字符串可能包含嵌入的 null 字
     节。Unicode 对象都被通过 ‘'utf-8'’ 编码转化成 C 字符串。

‘z’ (*note str: 339. or ‘None’) [const char *]

     与 ‘s’ 类似，但 Python 对象也可能为 ‘None’，在这种情况下，C 指针设
     置为 ‘NULL’。

‘z*’ (*note str: 339, *note bytes-like object: 5f1. or ‘None’) [Py_buffer]

     与 ‘s*’ 类似，但 Python 对象也可能为 ‘None’，在这种情况下，*note
     Py_buffer: b23. 结构的 ‘buf’ 成员设置为 ‘NULL’。

‘z#’ (*note str: 339, 只读 *note bytes-like object: 5f1. 或 ‘None’) [const char *, int 或 ‘Py_ssize_t’]

     与 ‘s#’ 类似，但 Python 对象也可能为 ‘None’，在这种情况下，C 指针设
     置为 ‘NULL’。

‘y’ (read-only *note bytes-like object: 5f1.) [const char *]

     这个表达式将一个类字节类型对象转化成一个指向字符串的 C 指针；它不接
     受 Unicode 对象。字节缓存区必须不包含嵌入的 null 字节；如果包含了
     null 字节，会引发一个 *note ValueError: 1fc. 异常。

     在 3.5 版更改: 以前，当字节缓冲区中遇到了嵌入的 null 字节会引发
     *note TypeError: 193. 。

‘y*’ (*note bytes-like object: 5f1.) [Py_buffer]

     ‘s*’ 的变式，不接受 Unicode 对象，只接受类字节类型变量。`这是接受二
     进制数据的推荐方法。'

‘y#’ (只读 *note bytes-like object: 5f1.) [const char *, int 或 ‘Py_ssize_t’]

     ‘s#’ 的变式，不接受 Unicode 对象，只接受类字节类型变量。

‘S’ (*note bytes: 33a.) [PyBytesObject *]

     要求 Python 对象为 *note bytes: 33a. 对象，不尝试进行任何转换。 如
     果该对象不为 bytes 对象则会引发 *note TypeError: 193.。 C 变量也可
     被声明为 *note PyObject*: 4c2. 类型。

‘Y’ (*note bytearray: 33b.) [PyByteArrayObject *]

     要求 Python 对象为 *note bytearray: 33b. 对象，不尝试进行任何转换。
     如果该对象不为 *note bytearray: 33b. 对象则会引发 *note TypeError:
     193.。 C 变量也可被声明为 *note PyObject*: 4c2. 类型。

‘u’ (*note str: 339.) [const Py_UNICODE *]

     将一个 Python Unicode 对象转化成指向一个以空终止的 Unicode 字符缓冲
     区的指针。你必须传入一个 *note Py_UNICODE: af6. 指针变量的地址，存
     储了一个指向已经存在的 Unicode 缓冲区的指针。请注意一个 *note
     Py_UNICODE: af6. 类型的字符宽度取决于编译选项(16 位或者 32 位)。
     Python 字符串必须不能包含嵌入的 null 代码点；如果有，引发一个 *note
     ValueError: 1fc. 异常。

     在 3.5 版更改: 以前，当 Python 字符串中遇到了嵌入的 null 代码点会引
     发 *note TypeError: 193. 。

     Deprecated since version 3.3, will be removed in version 3.12: 这是
     旧版样式 *note Py_UNICODE: af6. API; 请迁移至 *note
     PyUnicode_AsWideCharString(): 440.

‘u#’ (*note str: 339.) [const Py_UNICODE *, int 或 ‘Py_ssize_t’]

     ‘u’ 的变式，存储两个 C 变量，第一个指针指向一个 Unicode 数据缓存区
     ，第二个是它的长度。它允许 null 代码点。

     Deprecated since version 3.3, will be removed in version 3.12: 这是
     旧版样式 *note Py_UNICODE: af6. API; 请迁移至 *note
     PyUnicode_AsWideCharString(): 440.

‘Z’ (*note str: 339. 或 ‘None’) [const Py_UNICODE *]

     与 ‘u’ 类似，但 Python 对象也可能为 ‘None’，在这种情况下 *note
     Py_UNICODE: af6. 指针设置为 ‘NULL’。

     Deprecated since version 3.3, will be removed in version 3.12: 这是
     旧版样式 *note Py_UNICODE: af6. API; 请迁移至 *note
     PyUnicode_AsWideCharString(): 440.

‘Z#’ (*note str: 339. 或 ‘None’) [const Py_UNICODE *, int 或 ‘Py_ssize_t’]

     与 ‘u#’ 类似，但 Python 对象也可能为 ‘None’，在这种情况下 *note
     Py_UNICODE: af6. 指针设置为 ‘NULL’。

     Deprecated since version 3.3, will be removed in version 3.12: 这是
     旧版样式 *note Py_UNICODE: af6. API; 请迁移至 *note
     PyUnicode_AsWideCharString(): 440.

‘U’ (*note str: 339.) [PyObject *]

     要求 Python 对象为 Unicode 对象，不尝试进行任何转换。 如果该对象不
     为 Unicode 对象则会引发 *note TypeError: 193.。 C 变量也可被声明为
     *note PyObject*: 4c2.。

‘w*’ (可读写 *note bytes-like object: 5f1.) [Py_buffer]

     这个表达式接受任何实现可读写缓存区接口的对象。它为调用者提供的
     *note Py_buffer: b23. 结构赋值。缓冲区可能存在嵌入的 null 字节。当
     缓冲区使用完后调用者需要调用 *note PyBuffer_Release(): d5c.。

‘es’ (*note str: 339.) [const char *encoding, char **buffer]

     ‘s’ 的变式，它将编码后的 Unicode 字符存入字符缓冲区。它只处理没有嵌
     NUL 字节的已编码数据。

     此格式需要两个参数。 第一个仅用作输入，并且必须为 ‘const char*’，它
     指向一个以 NUL 结束的字符串表示的编码格式名称，或者为 ‘NULL’，这表
     示使用 ‘'utf-8'’ 编码格式。 如果为 Python 无法识别的编码格式名称则
     会引发异常。 第二个参数必须为 ‘char**’；它所引用的指针值将被设为带
     有参数文本内容的缓冲区。 文本将以第一个参数所指定的编码格式进行编码
     。

     *note PyArg_ParseTuple(): 26b. 会分配一个足够大小的缓冲区，将编码后
     的数据拷贝进这个缓冲区并且设置 `*buffer' 引用这个新分配的内存空间。
     调用者有责任在使用后调用 *note PyMem_Free(): db1. 去释放已经分配的
     缓冲区。

‘et’ (*note str: 339, *note bytes: 33a. or *note bytearray: 33b.) [const char *encoding, char **buffer]

     和 ‘es’ 相同，除了不用重编码传入的字符串对象。相反，它假设传入的参
     数是编码后的字符串类型。

‘es#’ (*note str: 339.) [const char *encoding, char **buffer, int 或 ‘Py_ssize_t’ *buffer_length]

     ‘s#’ 的变式，它将已编码的 Unicode 字符存入字符缓冲区。不像 ‘es’ 表
     达式，它允许传入的数据包含 NUL 字符。

     它需要三个参数。 第一个仅用作输入，并且必须为 ‘const char*’，它指向
     一个编码格式名称，形式为以 NUL 结束的字符串或 ‘NULL’，在后一种情况
     下将使用 ‘'utf-8'’ 编码格式。 如果编码格式名称无法被 Python 识别则
     会引发异常。 第二个参数必须为 ‘char**’；它所引用的指针值将被设为带
     有参数文本内容的缓冲区。 文本将以第一个参数所指定的编码格式进行编码
     。 第三个参数必须为指向一个整数的指针；被引用的整数将被设为输出缓冲
     区中的字节数。

     有两种操作方式：

     如果 `*buffer' 指向 ‘NULL’ 指针，则函数将分配所需大小的缓冲区，将编
     码的数据复制到此缓冲区，并设置 `*buffer' 以引用新分配的存储。 呼叫
     者负责调用 *note PyMem_Free(): db1. 以在使用后释放分配的缓冲区。

     如果 `*buffer' 指向非 ‘NULL’ 指针（已分配的缓冲区），则 *note
     PyArg_ParseTuple(): 26b. 将使用此位置作为缓冲区，并将
     `*buffer_length' 的初始值解释为缓冲区大小。 然后，它将将编码的数据
     复制到缓冲区，并终止它。 如果缓冲区不够大，将设置一个 *note
     ValueError: 1fc.。

     在这两个例子中，`*buffer_length' 被设置为编码后结尾不为 NUL 的数据
     的长度。

‘et#’ (*note str: 339, *note bytes: 33a. 或 *note bytearray: 33b.) [const char *encoding, char **buffer, int 或 ‘Py_ssize_t’ *buffer_length]

     和 ‘es#’ 相同，除了不用重编码传入的字符串对象。相反，它假设传入的参
     数是编码后的字符串类型。


File: python.info,  Node: 数字<2>,  Next: 其他对象,  Prev: 字符串和缓存区,  Up: 解析参数<3>

7.6.6.3 数字
............

‘b’ (*note int: 185.) [unsigned char]

     将一个非负的 Python 整型转化成一个无符号的微整型，存储在一个 C
     ‘unsigned char’ 类型中。

‘B’ (*note int: 185.) [unsigned char]

     将一个 Python 整型转化成一个微整型并不检查溢出问题，存储在一个 C
     ‘unsigned char’ 类型中。

‘h’ (*note int: 185.) [short int]

     将一个 Python 整型转化成一个 C ‘short int’ 短整型。

‘H’ (*note int: 185.) [unsigned short int]

     将一个 Python 整型转化成一个 C ‘unsigned short int’ 无符号短整型，
     并不检查溢出问题。

‘i’ (*note int: 185.) [int]

     将一个 Python 整型转化成一个 C ‘int’ 整型。

‘I’ (*note int: 185.) [unsigned int]

     将一个 Python 整型转化成一个 C ‘unsigned int’ 无符号整型，并不检查
     溢出问题。

‘l’ (*note int: 185.) [long int]

     将一个 Python 整型转化成一个 C ‘long int’ 长整型。

‘k’ (*note int: 185.) [unsigned long]

     将一个Python整型转化成一个C ‘unsigned long int’ 无符号长整型，并不
     检查溢出问题。

‘L’ (*note int: 185.) [long long]

     将一个 Python 整型转化成一个 C ‘long long’ 长长整型。

‘K’ (*note int: 185.) [unsigned long long]

     将一个 Python 整型转化成一个 C ‘unsigned long long’ 无符号长长整型
     ，并不检查溢出问题。

‘n’ (*note int: 185.) [Py_ssize_t]

     将一个 Python 整型转化成一个 C ‘Py_ssize_t’ Python 元大小类型。

‘c’ (*note bytes: 33a. 或者 *note bytearray: 33b. 长度为 1) [char]

     将一个 Python 字节类型，如一个长度为 1 的 *note bytes: 33a. 或者
     *note bytearray: 33b. 对象，转化成一个 C ‘char’ 字符类型。

     在 3.3 版更改: 允许 *note bytearray: 33b. 类型的对象。

‘C’ (*note str: 339. 长度为 1) [int]

     将一个 Python 字符，如一个长度为 1 的 *note str: 339. 字符串对象，
     转化成一个 C ‘int’ 整型类型。

‘f’ (*note float: 188.) [float]

     将一个 Python 浮点数转化成一个 C ‘float’ 浮点数。

‘d’ (*note float: 188.) [double]

     将一个Python浮点数转化成一个C ‘double’ 双精度浮点数。

‘D’ (*note complex: 18a.) [Py_complex]

     将一个 Python 复数类型转化成一个 C *note Py_complex: 3c81. Python 复
     数类型。


File: python.info,  Node: 其他对象,  Next: API 函数,  Prev: 数字<2>,  Up: 解析参数<3>

7.6.6.4 其他对象
................

‘O’ (object) [PyObject *]

     将 Python 对象（不进行任何转换）存储在 C 对象指针中。 因此，C 程序
     接收已传递的实际对象。 对象的引用计数不会增加。 存储的指针不是
     ‘NULL’。

‘O!’ (object) [`typeobject', PyObject *]

     将一个 Python 对象存入一个 C 对象指针。 这类似于 ‘O’，但是接受两个
     C 参数：第一个是 Python 类型对象的地址，第二个是存储对象指针的 C 变
     量 (类型为 *note PyObject*: 4c2.) 的地址。 如果 Python 对象不具有所
     要求的类型，则会引发 *note TypeError: 193.

‘O&’ (object) [`converter', `anything']

     通过一个 `converter' 函数将一个 Python 对象转换为一个 C 变量。 此函
     数接受两个参数：第一个是函数，第二个是 C 变量 (类型任意) 的地址，转
     换为 ‘void *’ 类型。 `converter' 函数将以如下方式被调用:

          status = converter(object, address);

     其中 `object' 是待转换的 Python 对象而 `address' 为传给 *note
     PyArg_Parse*(): f75. 函数的 ‘void*’ 参数。 返回的 `status' 应当以
     ‘1’ 代表转换成功而以 ‘0’ 代表转换失败。 当转换失败时，`converter' 函
     数应当引发异常并且会让 `address' 的内容保持未修改状态。

     如果 `converter' 返回 ‘Py_CLEANUP_SUPPORTED’，则如果参数解析最终失
     败，它可能会再次调用该函数，从而使转换器有机会释放已分配的任何内存
     。在第二个调用中，`object' 参数将为 ‘NULL’;因此，该参数将为
     ‘NULL’;因此，该参数将为 ‘NULL’，因此，该参数将为 ‘NULL``（如果值）
     为 ``NULL’ `address' 的值与原始呼叫中的值相同。

     在 3.1 版更改: ‘Py_CLEANUP_SUPPORTED’ 被添加。

‘p’ (*note bool: 184.) [int]

     测试传入的值是否为真(一个布尔判断)并且将结果转化为相对应的 C
     true/false 整型值。如果表达式为真置 ‘1’，假则置 ‘0’。它接受任何合法
     的 Python 值。参见 *note 逻辑值检测: 15f3. 获取更多关于 Python 如何
     测试值为真的信息。

     3.3 新版功能.

‘(items)’ (*note tuple: 486.) [`matching-items']

     对象必须是 Python 序列，它的长度是 `items' 中格式单元的数量。C 参数
     必须对应 `items' 中每一个独立的格式单元。序列中的格式单元可能有嵌套
     。

传递 "long" 整型(整型的值超过了平台的 ‘LONG_MAX’ 限制)是可能的，然而没有
进行适当的范围检测——当接收字段太小而接收不到值时，最重要的位被静默地截断
(实际上，C 语言会在语义继承的基础上强制类型转换——期望的值可能会发生变化
)。

格式化字符串中还有一些其他的字符具有特殊的涵义。这些可能并不嵌套在圆括号
中。它们是：

‘|’

     表明在 Python 参数列表中剩下的参数都是可选的。C 变量对应的可选参数
     需要初始化为默认值——当一个可选参数没有指定时， *note
     PyArg_ParseTuple(): 26b. 不能访问相应的 C 变量(变量集)的内容。

‘$’

     *note PyArg_ParseTupleAndKeywords(): 5d3. only：表明在 Python 参数
     列表中剩下的参数都是强制关键字参数。当前，所有强制关键字参数都必须
     也是可选参数，所以格式化字符串中 ‘|’ 必须一直在 ‘$’ 前面。

     3.3 新版功能.

‘:’

     格式单元的列表结束标志；冒号后的字符串被用来作为错误消息中的函数名
     (*note PyArg_ParseTuple(): 26b. 函数引发的“关联值”异常)。

‘;’

     格式单元的列表结束标志；分号后的字符串被用来作为错误消息取代默认的
     错误消息。 ‘:’ 和 ‘;’ 相互排斥。

注意任何由调用者提供的 Python 对象引用是 `借来的' 引用；不要递减它们的引
用计数！

传递给这些函数的附加参数必须是由格式化字符串确定的变量的地址；这些都是用
来存储输入元组的值。有一些情况，如上面的格式单元列表中所描述的，这些参数
作为输入值使用；在这种情况下，它们应该匹配指定的相应的格式单元。

为了转换成功，`arg' 对象必须匹配格式并且格式必须用尽。成功的话，*note
PyArg_Parse*(): f75. 函数返回 true，反之它们返回 false 并且引发一个合适
的异常。当 *note PyArg_Parse*(): f75. 函数因为某一个格式单元转化失败而失
败时，对应的以及后续的格式单元地址内的变量都不会被使用。


File: python.info,  Node: API 函数,  Prev: 其他对象,  Up: 解析参数<3>

7.6.6.5 API 函数
................

 -- C 函数: int PyArg_ParseTuple (PyObject *args, const char *format,
          ...)

     解析一个函数的参数，表达式中的参数按参数位置顺序存入局部变量中。成
     功返回 true；失败返回 false 并且引发相应的异常。

 -- C 函数: int PyArg_VaParse (PyObject *args, const char *format,
          va_list vargs)

     和 *note PyArg_ParseTuple(): 26b. 相同，然而它接受一个 va_list 类型
     的参数而不是可变数量的参数集。

 -- C 函数: int PyArg_ParseTupleAndKeywords (PyObject *args,
          PyObject *kw, const char *format, char *keywords[], ...)

     分析将位置参数和关键字参数同时转换为局部变量的函数的参数。
     `keywords' 参数是关键字参数名称的 ‘NULL’ 终止数组。 空名称表示
     *note positional-only parameters: 2a8.。成功时返回 true;发生故障时
     ，它将返回 false 并引发相应的异常。

     在 3.6 版更改: 添加了 *note positional-only parameters: 2a8. 的支持
     。

 -- C 函数: int PyArg_VaParseTupleAndKeywords (PyObject *args,
          PyObject *kw, const char *format, char *keywords[],
          va_list vargs)

     和 *note PyArg_ParseTupleAndKeywords(): 5d3. 相同，然而它接受一个
     va_list类型的参数而不是可变数量的参数集。

 -- C 函数: int PyArg_ValidateKeywordArguments (PyObject *)

     确保字典中的关键字参数都是字符串。这个函数只被使用于 *note
     PyArg_ParseTupleAndKeywords(): 5d3. 不被使用的情况下，后者已经不再
     做这样的检查。

     3.2 新版功能.

 -- C 函数: int PyArg_Parse (PyObject *args, const char *format, ...)

     函数被用来析构“旧类型”函数的参数列表——这些函数使用的 ‘METH_OLDARGS’
     参数解析方法已从 Python 3 中移除。这不被推荐用于新代码的参数解析，
     并且在标准解释器中的大多数代码已被修改，已不再用于该目的。它仍然方
     便于分解其他元组，然而可能因为这个目的被继续使用。

 -- C 函数: int PyArg_UnpackTuple (PyObject *args, const char *name,
          Py_ssize_t min, Py_ssize_t max, ...)

     一个更简单的参数提取方式，它不使用格式字符串来指定参数类型。 使用这
     种方法来提取参数的函数应当在函数或方法表中被声明为 *note
     METH_VARARGS: e50.。 包含实际参数的元组应当作为 `args' 传入；它必须
     确实是一个元组。 元组的长度必须至少为 `min' 并且不超过 `max'；`min'
     和 `max' 可能相等。 额外的参数必须被传入函数，每个参数必须是一个指
     向 *note PyObject*: 4c2. 变量的指针；它们将以来自 `args' 的值填充；
     它们将包含暂借的引用。 对应于可选参数的变量不会由 `args' 给出的值填
     充；它们将由调用者来初始化。 此函数执行成功时返回真值，如果 `args'
     不是元组或者包含错误数量的元素则返回假值；如果执行失败则将设置一个
     异常。

     这是一个使用此函数的示例，取自 ‘_weakref’ 帮助模块用来弱化引用的源
     代码：

          static PyObject *
          weakref_ref(PyObject *self, PyObject *args)
          {
              PyObject *object;
              PyObject *callback = NULL;
              PyObject *result = NULL;

              if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {
                  result = PyWeakref_NewRef(object, callback);
              }
              return result;
          }

     这个例子中调用 *note PyArg_UnpackTuple(): e4e. 完全等价于调用 *note
     PyArg_ParseTuple(): 26b.:

          PyArg_ParseTuple(args, "O|O:ref", &object, &callback)


File: python.info,  Node: 创建变量,  Prev: 解析参数<3>,  Up: 解析参数并构建值变量

7.6.6.6 创建变量
................

 -- C 函数: PyObject* Py_BuildValue (const char *format, ...)
     `Return value: New reference.' 基于类似于 *note PyArg_Parse*():
     f75. 函数系列和一系列值的格式字符串创建新值。 在出现错误时返回值或
     ‘NULL’;如果返回 ‘NULL’，将引发异常。

     *note Py_BuildValue(): 2cf. 并不一直创建一个元组。只有当它的格式化
     字符串包含两个或更多的格式单元才会创建一个元组。如果格式化字符串是
     空，它返回 ‘None’；如果它包含一个格式单元，它返回由格式单元描述的的
     任一对象。用圆括号包裹格式化字符串可以强制它返回一个大小为 0 或者 1
     的元组。

     当内存缓存区的数据以参数形式传递用来构建对象时，如 ‘s’ 和 ‘s#’ 格式
     单元，会拷贝需要的数据。调用者提供的缓冲区从来都不会被由 *note
     Py_BuildValue(): 2cf. 创建的对象来引用。换句话说，如果你的代码调用
     ‘malloc()’ 并且将分配的内存空间传递给 *note Py_BuildValue(): 2cf.，
     你的代码就有责任在 *note Py_BuildValue(): 2cf. 返回时调用 ‘free()’
     。

     在下面的描述中，双引号的表达式使格式单元；圆括号 () 内的是格式单元
     将要返回的 Python 对象类型；方括号 [] 内的是传递的 C 变量(变量集)的
     类型。

     字符例如空格，制表符，冒号和逗号在格式化字符串中会被忽略(但是不包括
     格式单元，如 ‘s#’)。这可以使很长的格式化字符串具有更好的可读性。

     ‘s’ (*note str: 339. 或 ‘None’) [const char *]

          使用 ‘'utf-8'’ 编码将空终止的 C 字符串转换为 Python *note str:
          339. 对象。如果 C 字符串指针为 ‘NULL’，则使用 ‘None’。

     ‘s#’ (*note str: 339. 或 ‘None’) [const char *, int 或 ‘Py_ssize_t’]

          使用 ‘'utf-8'’ 编码将 C 字符串及其长度转换为 Python *note str:
          339. 对象。如果 C 字符串指针为 ‘NULL’，则长度将被忽略，并返回
          ‘None’。

     ‘y’ (*note bytes: 33a.) [const char *]

          这将 C 字符串转换为 Python *note bytes: 33a. 对象。 如果 C 字
          符串指针为 ‘NULL’，则返回 ‘None’。

     ‘y#’ (*note bytes: 33a.) [const char *, int 或 ‘Py_ssize_t’]

          这会将 C 字符串及其长度转换为一个 Python 对象。 如果该 C 字符
          串指针为 ‘NULL’，则返回 ‘None’。

     ‘z’ (*note str: 339. or ‘None’) [const char *]

          和 ‘s’ 一样。

     ‘z#’ (*note str: 339. 或 ‘None’) [const char *, int 或 ‘Py_ssize_t’]

          和 ‘s#’ 一样。

     ‘u’ (*note str: 339.) [const wchar_t *]

          将空终止的 ‘wchar_t’ 的 Unicode （UTF-16 或 UCS-4） 数据缓冲区
          转换为 Python Unicode 对象。 如果 Unicode 缓冲区指针为 ‘NULL’，
          则返回 ‘None’。

     ‘u#’ (*note str: 339.) [const wchar_t *, int 或 ‘Py_ssize_t’]

          将 Unicode （UTF-16 或 UCS-4） 数据缓冲区及其长度转换为 Python
          Unicode 对象。 如果 Unicode 缓冲区指针为 ‘NULL’，则长度将被忽
          略，并返回 ‘None’。

     ‘U’ (*note str: 339. 或 ‘None’) [const char *]

          和 ‘s’ 一样。

     ‘U#’ (*note str: 339. 或 ‘None’) [const char *, int 或 ‘Py_ssize_t’]

          和 ‘s#’ 一样。

     ‘i’ (*note int: 185.) [int]

          将一个 C ‘int’ 整型转化成 Python 整型对象。

     ‘b’ (*note int: 185.) [char]

          将一个 C ‘char’ 字符型转化成 Python 整型对象。

     ‘h’ (*note int: 185.) [short int]

          将一个 C ‘short int’ 短整型转化成 Python 整型对象。

     ‘l’ (*note int: 185.) [long int]

          将一个 C ‘long int’ 长整型转化成 Python 整型对象。

     ‘B’ (*note int: 185.) [unsigned char]

          将一个 C ‘unsigned char’ 无符号字符型转化成 Python 整型对象。

     ‘H’ (*note int: 185.) [unsigned short int]

          将一个 C ‘unsigned long’ 无符号短整型转化成 Python 整型对象。

     ‘I’ (*note int: 185.) [unsigned int]

          将一个 C ‘unsigned long’ 无符号整型转化成 Python 整型对象。

     ‘k’ (*note int: 185.) [unsigned long]

          将一个 C ‘unsigned long’ 无符号长整型转化成 Python 整型对象。

     ‘L’ (*note int: 185.) [long long]

          将一个 C ‘long long’ 长长整形转化成 Python 整形对象。

     ‘K’ (*note int: 185.) [unsigned long long]

          将一个 C ‘unsigned long long’ 无符号长长整型转化成 Python 整型
          对象。

     ‘n’ (*note int: 185.) [Py_ssize_t]

          将一个 C ‘Py_ssize_t’ 类型转化为 Python 整型。

     ‘c’ (*note bytes: 33a. 长度为1 ) [char]

          将一个 C ‘int’ 整型代表的字符转化为 Python *note bytes: 33a. 长
          度为 1 的字节对象。

     ‘C’ (*note str: 339. 长度为 1) [int]

          将一个 C ‘int’ 整型代表的字符转化为 Python *note str: 339. 长
          度为 1 的字符串对象。

     ‘d’ (*note float: 188.) [double]

          将一个 C ‘double’ 双精度浮点数转化为 Python 浮点数类型数字。

     ‘f’ (*note float: 188.) [float]

          将一个 C ‘float’ 单精度浮点数转化为 Python 浮点数类型数字。

     ‘D’ (*note complex: 18a.) [Py_complex *]

          将一个 C *note Py_complex: 3c81. 类型的结构转化为 Python 复数
          类型。

     ‘O’ (object) [PyObject *]

          将 Python 对象传递不变（其引用计数除外，该计数由 1 递增）。 如
          果传入的对象是 ‘NULL’ 指针，则假定这是由于生成参数的调用发现错
          误并设置异常而引起的。因此，*note Py_BuildValue(): 2cf. 将返回
          ‘NULL’，但不会引发异常。 如果尚未引发异常，则设置 *note
          SystemError: 604.。

     ‘S’ (object) [PyObject *]

          和 ‘O’ 相同。

     ‘N’ (object) [PyObject *]

          和 ‘O’ 相同，然而它并不增加对象的引用计数。当通过调用参数列表
          中的对象构造器创建对象时很实用。

     ‘O&’ (object) [`converter', `anything']

          通过 `converter' 函数将 `anything' 转换为 Python 对象。 该函数
          调用时会传入 `anything' (应与 ‘void*’ 兼容) 作为参数并且应当返
          回一个“新的”Python 对象，或者当发生错误时返回 ‘NULL’。

     ‘(items)’ (*note tuple: 486.) [`matching-items']

          将一个 C 变量序列转换成 Python 元组并保持相同的元素数量。

     ‘[items]’ (*note list: 263.) [`相关的元素']

          将一个 C 变量序列转换成 Python 列表并保持相同的元素数量。

     ‘{items}’ (*note dict: 1b9.) [`相关的元素']

          将一个C变量序列转换成 Python 字典。每一对连续的 C 变量对作为一
          个元素插入字典中，分别作为关键字和值。

     如果格式字符串中出现错误，则设置 *note SystemError: 604. 异常并返回
     ‘NULL’。

 -- C 函数: PyObject* Py_VaBuildValue (const char *format,
          va_list vargs)
     `Return value: New reference.' 和 *note Py_BuildValue(): 2cf. 相同
     ，然而它接受一个 va_list 类型的参数而不是可变数量的参数集。


File: python.info,  Node: 字符串转换与格式化,  Next: 反射,  Prev: 解析参数并构建值变量,  Up: 工具<2>

7.6.7 字符串转换与格式化
------------------------

用于数字转换和格式化字符串输出的函数

 -- C 函数: int PyOS_snprintf (char *str, size_t size, const
          char *format, ...)

     根据格式字符串 `format' 和额外参数，输出不超过 `size' 个字节到
     `str'。 参见 Unix 手册页面 ‘snprintf(3)’。

 -- C 函数: int PyOS_vsnprintf (char *str, size_t size, const
          char *format, va_list va)

     根据格式字符串 `format' 和变量参数列表 `va'，输出不超过 `size' 个字
     节到 `str'。 参见 Unix 手册页面 ‘vsnprintf(3)’。

*note PyOS_snprintf(): e51. 和 *note PyOS_vsnprintf(): e52. 包装 C 标准
库函数 ‘snprintf()’ 和 ‘vsnprintf()’ 。它们的目的是保证在极端情况下的一
致行为，而标准 C 的函数则不然。

包装器会确保 ‘str[size-1]’ 在返回时始终为 ‘'\0'’。 它们从不写入超过
`size' 个字节 (包括末尾的 ‘'\0'’) 到字符串。 两个函数都要求 ‘str !=
NULL’, ‘size > 0’ 和 ‘format != NULL’。

如果平台没有 ‘vsnprintf()’ 而且缓冲区大小需要避免截断超出 `size' 512 字
节以上，Python 会以一个 *note Py_FatalError(): f9a. 来中止。

这些函数的返回值（ `rv' ）应按照以下规则被解释：

   * 当 ‘0 <= rv < size’ 时，输出转换即成功并将 `rv' 个字符写入到 `str'
     (不包括末尾 ‘str[rv]’ 位置的 ‘'\0'’ 字节)。

   * 当 ‘rv >= size’ 时，输出转换会被截断并且需要一个具有 ‘rv + 1’ 字节
     的缓冲区才能成功执行。 在此情况下 ‘str[size-1]’ 为 ‘'\0'’。

   * 当 ‘rv < 0’ 时，"会发生不好的事情。" 在此情况下 ‘str[size-1]’ 也为
     ‘'\0'’，但 `str' 的其余部分是未定义的。 错误的确切原因取决于底层平
     台。

以下函数提供与语言环境无关的字符串到数字转换。

 -- C 函数: double PyOS_string_to_double (const char *s, char **endptr,
          PyObject *overflow_exception)

     将字符串 ‘s’ 转换为 ‘double’ 类型，失败时引发Python异常。接受的字符
     串的集合对应于被 Python 的 *note float(): 188. 构造函数接受的字符串
     的集合，除了 ‘s’ 必须没有前导或尾随空格。转换必须独立于当前的区域。

     如果 ‘endptr’ 是 ‘NULL’ ，转换整个字符串。引发 *note ValueError:
     1fc. 并且 返回 ‘-1.0’ 如果字符串不是浮点数的有效的表达方式。

     如果 ‘endptr’ 不是 ‘NULL’ ，尽可能多的转换字符串并将 ‘*endptr’ 设置
     为指向第一个未转换的字符。如果字符串的初始段不是浮点数的有效的表达
     方式，将 ‘*endptr’ 设置为指向字符串的开头，引发 ValueError 异常，并
     且返回 ‘-1.0’ 。

     如果 ‘s’ 表示一个太大而不能存储在一个浮点数中的值（比方说，
     ‘"1e500"’ 在许多平台上是一个字符串）然后如果 ‘overflow_exception’ 是
     ‘NULL’ 返回 ‘Py_HUGE_VAL’ （用适当的符号）并且不设置任何异常。 在其
     他方面， ‘overflow_exception’ 必须指向一个 Python 异常对象；引发异
     常并返回 ‘-1.0’ 。在这两种情况下，设置 ‘*endptr’ 指向转换值之后的第
     一个字符。

     如果在转换期间发生任何其他错误（比如一个内存不足的错误），设置适当
     的 Python 异常并且返回 ‘-1.0’ 。

     3.1 新版功能.

 -- C 函数: char* PyOS_double_to_string (double val, char format_code,
          int precision, int flags, int *ptype)

     转换 ‘double’ `val' 为一个使用 `format_code'， `precision' 和
     `flags' 的字符串

     `格式码' 必须是以下其中之一, ‘'e'’, ‘'E'’, ‘'f'’, ‘'F'’, ‘'g'’,
     ‘'G'’ 或者 ‘'r'’。对于 ‘'r'’ , 提供的 `精度' 必须是0。‘'r'’ 格式码
     指定了标准函数 *note repr(): 7d5. 格式。

     `flags' 可以为零或者其他值 ‘Py_DTSF_SIGN’, ‘Py_DTSF_ADD_DOT_0’ 或
     ‘Py_DTSF_ALT’ 或其组合：

        * ‘Py_DTSF_SIGN’ 表示总是在返回的字符串前附加一个符号字符，即使
          `val' 为非负数。

        * ‘Py_DTSF_ADD_DOT_0’ 表示确保返回的字符串看起来不像是一个整数。

        * ‘Py_DTSF_ALT’ 表示应用 "替代的" 格式化规则。 相关细节请参阅
          *note PyOS_snprintf(): e51. ‘'#'’ 定义文档。

     如果 `ptype' 不为 ‘NULL’，则它指向的值将被设为 ‘Py_DTST_FINITE’,
     ‘Py_DTST_INFINITE’ 或 ‘Py_DTST_NAN’ 中的一个，分别表示 `val' 是一个
     有限数字、无限数字或非数字。

     返回值是一个指向包含转换后字符串的 `buffer' 的指针，如果转换失败则
     为 ‘NULL’。 调用方要负责调用 *note PyMem_Free(): db1. 来释放返回的
     字符串。

     3.1 新版功能.

 -- C 函数: int PyOS_stricmp (const char *s1, const char *s2)

     字符串不区分大小写。该函数几乎与 ‘strcmp()’ 的工作方式相同，只是它
     忽略了大小写。

 -- C 函数: int PyOS_strnicmp (const char *s1, const char *s2,
          Py_ssize_t  size)

     字符串不区分大小写。该函数几乎与 ‘strncmp()’ 的工作方式相同，只是它
     忽略了大小写。


File: python.info,  Node: 反射,  Next: 编解码器注册与支持功能,  Prev: 字符串转换与格式化,  Up: 工具<2>

7.6.8 反射
----------

 -- C 函数: PyObject* PyEval_GetBuiltins ()
     `Return value: Borrowed reference.' 返回当前执行帧中内置函数的字典
     ，如果当前没有帧正在执行，则返回线程状态的解释器。

 -- C 函数: PyObject* PyEval_GetLocals ()
     `Return value: Borrowed reference.' 返回当前执行帧中局部变量的字典
     ，如果没有当前执行的帧则返回 ‘NULL’。

 -- C 函数: PyObject* PyEval_GetGlobals ()
     `Return value: Borrowed reference.' 返回当前执行帧中全局变量的字典
     ，如果没有当前执行的帧则返回 ‘NULL’。

 -- C 函数: PyFrameObject* PyEval_GetFrame ()
     `Return value: Borrowed reference.' 返回当前线程状态的帧，如果没有
     当前执行的帧则返回 ‘NULL’。

 -- C 函数: int PyFrame_GetLineNumber (PyFrameObject *frame)

     返回 `frame' 当前正在执行的行号。

 -- C 函数: const char* PyEval_GetFuncName (PyObject *func)

     如果 `func' 是函数、类或实例对象，则返回它的名称，否则返回 `func' 的
     类型的名称。

 -- C 函数: const char* PyEval_GetFuncDesc (PyObject *func)

     根据 `func' 的类型返回描述字符串。 返回值包括函数和方法的 "()", "
     constructor", " instance" 和 " object"。 与 *note
     PyEval_GetFuncName(): 3c96. 的结果连接，结果将是 `func' 的描述。


File: python.info,  Node: 编解码器注册与支持功能,  Prev: 反射,  Up: 工具<2>

7.6.9 编解码器注册与支持功能
----------------------------

 -- C 函数: int PyCodec_Register (PyObject *search_function)

     注册一个新的编解码器搜索函数。

     作为副作用，其尝试加载 ‘encodings’ 包，如果尚未完成，请确保它始终位
     于搜索函数列表的第一位。

 -- C 函数: int PyCodec_KnownEncoding (const char *encoding)

     根据注册的给定 `encoding' 的编解码器是否已存在而返回 ‘1’ 或 ‘0’。此
     函数总能成功。

 -- C 函数: PyObject* PyCodec_Encode (PyObject *object, const
          char *encoding, const char *errors)
     `Return value: New reference.' 泛型编解码器基本编码 API。

     `object' 使用由 `errors' 所定义的错误处理方法传递给定 `encoding' 的
     编码器函数。 `errors' 可以为 ‘NULL’ 表示使用为编码器所定义的默认方
     法。 如果找不到编码器则会引发 *note LookupError: 166d.。

 -- C 函数: PyObject* PyCodec_Decode (PyObject *object, const
          char *encoding, const char *errors)
     `Return value: New reference.' 泛型编解码器基本解码 API。

     `object' 使用由 `errors' 所定义的错误处理方法传递给定 `encoding' 的
     解码器函数。 `errors' 可以为 ‘NULL’ 表示使用为编解码器所定义的默认
     方法。 如果找不到编解码器则会引发 *note LookupError: 166d.。

* Menu:

* Codec 查找API::
* 用于Unicode编码错误处理程序的注册表API::


File: python.info,  Node: Codec 查找API,  Next: 用于Unicode编码错误处理程序的注册表API,  Up: 编解码器注册与支持功能

7.6.9.1 Codec 查找API
.....................

在下列函数中，`encoding' 字符串会被查找并转换为小写字母形式，这使得通过
此机制查找编码格式实际上对大小写不敏感。 如果未找到任何编解码器，则将设
置 *note KeyError: 2c8. 并返回 ‘NULL’。

 -- C 函数: PyObject* PyCodec_Encoder (const char *encoding)
     `Return value: New reference.' 为给定的 `encoding' 获取一个编码器函
     数。

 -- C 函数: PyObject* PyCodec_Decoder (const char *encoding)
     `Return value: New reference.' 为给定的 `encoding' 获取一个解码器函
     数。

 -- C 函数: PyObject* PyCodec_IncrementalEncoder (const char *encoding,
          const char *errors)
     `Return value: New reference.' 为给定的 `encoding' 获取一个 *note
     IncrementalEncoder: 183c. 对象。

 -- C 函数: PyObject* PyCodec_IncrementalDecoder (const char *encoding,
          const char *errors)
     `Return value: New reference.' 为给定的 `encoding' 获取一个 *note
     IncrementalDecoder: 183d. 对象。

 -- C 函数: PyObject* PyCodec_StreamReader (const char *encoding,
          PyObject *stream, const char *errors)
     `Return value: New reference.' 为给定的 `encoding' 获取一个 *note
     StreamReader: 1841. 工厂函数。

 -- C 函数: PyObject* PyCodec_StreamWriter (const char *encoding,
          PyObject *stream, const char *errors)
     `Return value: New reference.' 为给定的 `encoding' 获取一个 *note
     StreamWriter: 1840. 工厂函数。


File: python.info,  Node: 用于Unicode编码错误处理程序的注册表API,  Prev: Codec 查找API,  Up: 编解码器注册与支持功能

7.6.9.2 用于Unicode编码错误处理程序的注册表API
..............................................

 -- C 函数: int PyCodec_RegisterError (const char *name,
          PyObject *error)

     在给定的 `name' 之下注册错误处理回调函数 `error'。 该回调函数将在一
     个编解码器遇到无法编码的字符/无法解码的字节数据并且 `name' 被指定为
     encode/decode 函数调用的 error 形参时由该编解码器来调用。

     该回调函数会接受一个 *note UnicodeEncodeError: 1fd, *note
     UnicodeDecodeError: 1fe. 或 *note UnicodeTranslateError: 1725. 的实
     例作为单独参数，其中包含关于有问题字符或字节序列及其在原始序列的偏
     移量信息（请参阅 *note Unicode 异常对象: 3c17. 了解提取此信息的函数
     详情）。 该回调函数必须引发给定的异常，或者返回一个包含有问题序列及
     相应替换序列的二元组，以及一个表示偏移量的整数，该整数指明应在什么
     位置上恢复编码/解码操作。

     成功则返回‘‘0‘‘ ，失败则返回‘‘-1‘‘

 -- C 函数: PyObject* PyCodec_LookupError (const char *name)
     `Return value: New reference.' 查找在 `name' 之下注册的错误处理回调
     函数。 作为特例还可以传入 ‘NULL’，在此情况下将返回针对 "strict" 的
     错误处理回调函数。

 -- C 函数: PyObject* PyCodec_StrictErrors (PyObject *exc)
     `Return value: Always NULL.' 引发 `exc' 作为异常。

 -- C 函数: PyObject* PyCodec_IgnoreErrors (PyObject *exc)
     `Return value: New reference.' 忽略 unicode 错误，跳过错误的输入。

 -- C 函数: PyObject* PyCodec_ReplaceErrors (PyObject *exc)
     `Return value: New reference.' 使用 ‘?’ 或 ‘U+FFFD’ 替换 unicode 编
     码错误。

 -- C 函数: PyObject* PyCodec_XMLCharRefReplaceErrors (PyObject *exc)
     `Return value: New reference.' 使用 XML 字符引用替换 unicode 编码错
     误。

 -- C 函数: PyObject* PyCodec_BackslashReplaceErrors (PyObject *exc)
     `Return value: New reference.' 使用反斜杠转义符 (‘\x’, ‘\u’ 和
     ‘\U’) 替换 unicode 编码错误。

 -- C 函数: PyObject* PyCodec_NameReplaceErrors (PyObject *exc)
     `Return value: New reference.' 使用 ‘\N{...}’ 转义符替换 unicode 编
     码错误。

     3.5 新版功能.


File: python.info,  Node: 抽象对象层,  Next: 具体的对象层,  Prev: 工具<2>,  Up: Python/C API 参考手册

7.7 抽象对象层
==============

本章中的函数与 Python对象交互，无论其类型，或具有广泛类的对象类型（例如
，所有数值类型，或所有序列类型）。当使用对象类型并不适用时，他们会产生一
个 Python 异常。

这些函数是不可能用于未正确初始化的对象的，如一个列表对象被 *note
PyList_New(): 3bb4. 创建，但其中的项目没有被设置为一些非‘‘NULL‘‘的值。

* Menu:

* 对象协议::
* 数字协议::
* 序列协议::
* 映射协议::
* 迭代器协议::
* 缓冲协议::
* 旧缓冲协议::


File: python.info,  Node: 对象协议,  Next: 数字协议,  Up: 抽象对象层

7.7.1 对象协议
--------------

 -- C 变量: PyObject* Py_NotImplemented

     ‘NotImplemented’ 单例，用于标记某个操作没有针对给定类型组合的实现。

 -- C 宏: Py_RETURN_NOTIMPLEMENTED

     C 函数内部应正确处理 *note Py_NotImplemented: 3cb2. 的返回过程（即
     增加 NotImplemented 的引用计数并返回之）。

 -- C 函数: int PyObject_Print (PyObject *o, FILE *fp, int flags)

     向文件 `fp' 输出对象 `o'。出错时返回 ‘-1’。参数 flags 用于开启某些
     输出选项。目前唯一支持的选项是 ‘Py_PRINT_RAW’ ；如果给出该选项，则
     对象的 *note str(): 339. 将被写入，而不是 *note repr(): 7d5. 。

 -- C 函数: int PyObject_HasAttr (PyObject *o, PyObject *attr_name)

     如果 `o' 带有属性 `attr_name'，则返回 ‘1’，否则返回 ‘0’。这相当于
     Python 表达式 ‘hasattr(o, attr_name)’。 此函数总是成功。

     注意，在调用 *note __getattr__(): 323. 和 *note __getattribute__():
     44f. 方法时发生的异常将被抑制。若要获得错误报告，请换用 *note
     PyObject_GetAttr(): 3cb5. 。

 -- C 函数: int PyObject_HasAttrString (PyObject *o, const
          char *attr_name)

     如果 `o' 带有属性 `attr_name'，则返回 ‘1’，否则返回 ‘0’。这相当于
     Python 表达式 ‘hasattr(o, attr_name)’。 此函数总是成功。

     注意，在调用 *note __getattr__(): 323. 和 *note __getattribute__():
     44f. 方法并创建一个临时字符串对象时，异常将被抑制。若要获得错误报告
     ，请换用 *note PyObject_GetAttrString(): 3b1e. 。

 -- C 函数: PyObject* PyObject_GetAttr (PyObject *o,
          PyObject *attr_name)
     `Return value: New reference.' 从对象 `o' 中读取名为 `attr_name' 的
     属性。成功返回属性值，失败则返回 ‘NULL’。 这相当于 Python 表达式
     ‘o.attr_name’。

 -- C 函数: PyObject* PyObject_GetAttrString (PyObject *o, const
          char *attr_name)
     `Return value: New reference.' 从对象 `o' 中读取一个名为
     `attr_name' 的属性。成功时返回属性值，失败则返回 ‘NULL’。这相当于
     Python 表达式 ‘o.attr_name’。

 -- C 函数: PyObject* PyObject_GenericGetAttr (PyObject *o,
          PyObject *name)
     `Return value: New reference.' 通用的属性获取函数，用于放入类型对象
     的 ‘tp_getattro’ 槽中。它在类的字典中（位于对象的 MRO 中）查找某个
     描述符，并在对象的 *note __dict__: 504. 中查找某个属性。正如 *note
     实现描述器: 4f1. 所述，数据描述符优先于实例属性，而非数据描述符则不
     优先。失败则会触发 *note AttributeError: 3a3. 。

 -- C 函数: int PyObject_SetAttr (PyObject *o, PyObject *attr_name,
          PyObject *v)

     将对象 `o' 中名为 `attr_name' 的属性值设为 `v' 。失败时引发异常并返
     回 ‘-1’；成功时返 回‘‘0‘‘ 。这相当于 Python 语句 ‘o.attr_name = v’。

     如果 `v' 为 ‘NULL’，属性将被删除，但是此功能已被弃用，应改用 *note
     PySequence_DelItem(): 1060. 。

 -- C 函数: int PyObject_SetAttrString (PyObject *o, const
          char *attr_name, PyObject *v)

     将对象 `o' 中名为 `attr_name' 的属性值设为 `v' 。失败时引发异常并返
     回 ‘-1’；成功时返 回‘‘0‘‘ 。这相当于 Python 语句 ‘o.attr_name = v’。

     如果 `v' 为 ‘NULL’，该属性将被删除，但是此功能已被弃用，应改用
     *note PySequence_DelItem(): 1060. 。

 -- C 函数: int PyObject_GenericSetAttr (PyObject *o, PyObject *name,
          PyObject *value)

     通用的属性设置和删除函数，用于放入类型对象的 *note tp_setattro:
     3b63. 槽。它在类的字典中（位于对象的MRO中）查找数据描述器，如果找到
     ，则将比在实例字典中设置或删除属性优先执行。否则，该属性将在对象的
     *note __dict__: 504. 中设置或删除。如果成功将返回 ‘0’，否则将引发
     *note AttributeError: 3a3. 并返回 ‘-1’。

 -- C 函数: int PyObject_DelAttr (PyObject *o, PyObject *attr_name)

     删除对象 `o' 中名为 `attr_name' 的属性。失败时返回 ‘-1’。这相当于
     Python 语句 ‘del o.attr_name’。

 -- C 函数: int PyObject_DelAttrString (PyObject *o, const
          char *attr_name)

     删除对象 `o' 中名为 `attr_name' 的属性。失败时返回 ‘-1’。这相当于
     Python 语句 ‘del o.attr_name’。

 -- C 函数: PyObject* PyObject_GenericGetDict (PyObject *o,
          void *context)
     `Return value: New reference.'  ‘__dict__’ 描述符的获取函数的一种通
     用实现。必要时会创建字典。

     3.3 新版功能.

 -- C 函数: int PyObject_GenericSetDict (PyObject *o, PyObject *value,
          void *context)

     ‘__dict__’ 描述符设置函数的一种通用实现。这里不允许删除字典。

     3.3 新版功能.

 -- C 函数: PyObject* PyObject_RichCompare (PyObject *o1, PyObject *o2,
          int opid)
     `Return value: New reference.' 用 `opid' 指定的操作比较 `o1' 和
     `o2' 的值，必须是 ‘Py_LT’ 、 ‘Py_LE’ 、 ‘Py_EQ’ 、 ‘Py_NE’ 、
     ‘Py_GT’ 或 ‘Py_GE’ 之一，分别对应于‘‘<=‘‘ 、‘==’ 、 ‘!=’ 、‘>’ 或
     ‘>=’。这相当于 Python 表达式 ‘o1 op o2’，其中 ‘op’ 是对应于 `opid'
     的操作符。成功时返回比较值，失败时返回 ‘NULL’。

 -- C 函数: int PyObject_RichCompareBool (PyObject *o1, PyObject *o2,
          int opid)

     用 `opid' 指定的操作比较 `o1' 和 `o2' 的值，必须是 ‘Py_LT’ 、
     ‘Py_LE’ 、 ‘Py_EQ’ 、 ‘Py_NE’ 、 ‘Py_GT’ 或 ‘Py_GE’ 之一，分别对应
     于 ‘<’ 、‘<=’、 ‘==’ 、‘!=’ 、‘>’ 或 ‘>=’。错误时返回 ‘-1’，若结果
     为 false 则返回 ‘0’，否则返回 ‘1’。这相当于 Python 表达式 ‘o1 op
     o2’，其中 ‘op’ 是对应于 `opid' 的操作符。

     注解: 如果 `o1' 和 `o2' 是同一个对象，*note
     PyObject_RichCompareBool(): f57. 为 ‘Py_EQ’ 则返回 ‘1’ ，为 ‘Py_NE’
     则返回 ‘0’。

 -- C 函数: PyObject* PyObject_Repr (PyObject *o)
     `Return value: New reference.'

     计算对象 `o' 的字符串形式。 成功时返回字符串，失败时返回 ‘NULL’。 这
     相当于 Python 表达式 ‘repr(o)’。 由内置函数 *note repr(): 7d5. 调用
     。

     在 3.4 版更改: 该函数现在包含一个调试断言，用以确保不会静默地丢弃活
     动的异常。

 -- C 函数: PyObject* PyObject_ASCII (PyObject *o)
     `Return value: New reference.'

     与 *note PyObject_Repr(): 970. 一样，计算对象 `o' 的字符串形式，但
     在 *note PyObject_Repr(): 970. 返回的字符串中用 ‘\x’、‘\u’ 或 ‘\U’
     转义非 ASCII 字符。这将生成一个类似于 Python 2 中由 *note
     PyObject_Repr(): 970. 返回的字符串。由内置函数 *note ascii(): d54.
     调用。

 -- C 函数: PyObject* PyObject_Str (PyObject *o)
     `Return value: New reference.' 计算对象 `o' 的字符串形式。 成功时返
     回字符串，失败时返回 ‘NULL’。 这相当于 Python 表达式 ‘str(o)’。由内
     置函数 *note str(): 339. 调用，因此也由 *note print(): 88f. 函数调
     用。

     在 3.4 版更改: 该函数现在包含一个调试断言，用以确保不会静默地丢弃活
     动的异常。

 -- C 函数: PyObject* PyObject_Bytes (PyObject *o)
     `Return value: New reference.'

     计算对象 `o' 的字节形式。失败时返回 ‘NULL’，成功时返回一个字节串对
     象。这相当于 `o' 不是整数时的 Python 表达式 ‘bytes(o)’ 。与
     ‘bytes(o)’ 不同的是，当 `o' 是整数而不是初始为 0 的字节串对象时，会
     触发 TypeError。

 -- C 函数: int PyObject_IsSubclass (PyObject *derived, PyObject *cls)

     如果 `derived' 类与 `cls' 类相同或为其派生类，则返回 ‘1’，否则返回
     ‘0’。 如果出错则返回 ‘-1’。

     如果 `cls' 是元组，则会对 `cls' 进行逐项检测。如果至少有一次检测返
     回 ‘1’，结果将为 ‘1’，否则将是 ‘0’。

     正如 PEP 3119(1) 所述，如果 `cls' 带有 *note __subclasscheck__():
     1461. 方法，将会被调用以确定子类的状态。 否则，如果 `derived' 是个
     直接或间接子类，即包含在 ‘cls.__mro__’ 中，那么它就是 `cls' 的一个
     子类。

     通常只有类对象才会被视为类，即 *note type: 611. 或派生类的实例。然
     而，对象可以通过拥有 ‘__bases__’ 属性（必须是基类的元组）来覆盖这一
     点。

 -- C 函数: int PyObject_IsInstance (PyObject *inst, PyObject *cls)

     如果 `inst' 是 `cls' 类或其子类的实例，则返回 ‘1’，如果不是则返回
     ‘‘0‘‘。 如果出错则返回 ‘-1’ 并设置一个异常。

     如果 `cls' 是元组，则会对 `cls' 进行逐项检测。如果至少有一次检测返
     回 ‘1’，结果将为 ‘1’，否则将是 ‘0’。

     正如 PEP 3119(2) 所述，如果 `cls' 带有 *note __subclasscheck__():
     1461. 方法，将会被调用以确定子类的状态。 否则，如果 `derived' 是
     `cls' 的子类，那么它就是 `cls' 的一个实例。

     实例 `inst' 可以通过 ‘__class__’ 属性来覆盖其所属类。

     对象 `cls' 可以通过 ‘__bases__’ 属性（必须是基类的元组）来覆盖它是
     否被认作类的状态，及其基类。

 -- C 函数: int PyCallable_Check (PyObject *o)

     确定对象 `o' 是可调对象。如果对象是可调对象则返回 ‘1’ ，其他情况返
     回 ‘0’ 。这个函数不会调用失败。

 -- C 函数: PyObject* PyObject_Call (PyObject *callable, PyObject *args,
          PyObject *kwargs)
     `Return value: New reference.' 调用一个可调用的 Python 对象
     `callable'，附带由元组 `args' 所给出的参数，以及由字典 `kwargs' 所
     给出的关键字参数。

     `args' must not be ‘NULL’, use an empty tuple if no arguments are
     needed.  If no named arguments are needed, `kwargs' can be ‘NULL’.

     Return the result of the call on success, or raise an exception and
     return ‘NULL’ on failure.

     这等价于 Python 表达式 ‘callable(*args, **kwargs)’。

 -- C 函数: PyObject* PyObject_CallObject (PyObject *callable,
          PyObject *args)
     `Return value: New reference.'  Call a callable Python object
     `callable', with arguments given by the tuple `args'.  If no
     arguments are needed, then `args' can be ‘NULL’.

     Return the result of the call on success, or raise an exception and
     return ‘NULL’ on failure.

     这等价于 Python 表达式 ‘callable(*args)’。

 -- C 函数: PyObject* PyObject_CallFunction (PyObject *callable, const
          char *format, ...)
     `Return value: New reference.'  Call a callable Python object
     `callable', with a variable number of C arguments.  The C arguments
     are described using a *note Py_BuildValue(): 2cf. style format
     string.  The format can be ‘NULL’, indicating that no arguments are
     provided.

     Return the result of the call on success, or raise an exception and
     return ‘NULL’ on failure.

     这等价于 Python 表达式 ‘callable(*args)’。

     请注意如果你只传入 *note PyObject *: 4c2. 参数，则 *note
     PyObject_CallFunctionObjArgs(): 3cc2. 是更快速的选择。

     在 3.4 版更改: 这个 `format' 类型已从 ‘char *’ 更改。

 -- C 函数: PyObject* PyObject_CallMethod (PyObject *obj, const
          char *name, const char *format, ...)
     `Return value: New reference.'  Call the method named `name' of
     object `obj' with a variable number of C arguments.  The C
     arguments are described by a *note Py_BuildValue(): 2cf. format
     string that should produce a tuple.

     The format can be ‘NULL’, indicating that no arguments are
     provided.

     Return the result of the call on success, or raise an exception and
     return ‘NULL’ on failure.

     这和Python表达式‘‘obj.name(arg1, arg2, ...)‘‘是一样的。

     请注意如果你只传入 *note PyObject *: 4c2. 参数，则 *note
     PyObject_CallMethodObjArgs(): fe9. 是更快速的选择。

     在 3.4 版更改: The types of `name' and `format' were changed from
     ‘char *’.

 -- C 函数: PyObject* PyObject_CallFunctionObjArgs (PyObject *callable,
          ...)
     `Return value: New reference.'  Call a callable Python object
     `callable', with a variable number of *note PyObject*: 4c2.
     arguments.  The arguments are provided as a variable number of
     parameters followed by ‘NULL’.

     Return the result of the call on success, or raise an exception and
     return ‘NULL’ on failure.

     这和Python表达式‘‘callable(arg1, arg2, ...)‘‘是一样的。

 -- C 函数: PyObject* PyObject_CallMethodObjArgs (PyObject *obj,
          PyObject *name, ...)
     `Return value: New reference.'  Calls a method of the Python object
     `obj', where the name of the method is given as a Python string
     object in `name'.  It is called with a variable number of *note
     PyObject*: 4c2. arguments.  The arguments are provided as a
     variable number of parameters followed by ‘NULL’.

     Return the result of the call on success, or raise an exception and
     return ‘NULL’ on failure.

 -- C 函数: PyObject* _PyObject_Vectorcall (PyObject *callable, PyObject
          *const *args, size_t nargsf, PyObject *kwnames)

     Call a callable Python object `callable', using *note vectorcall:
     3cc5. if possible.

     `args' is a C array with the positional arguments.

     `nargsf' is the number of positional arguments plus optionally the
     flag ‘PY_VECTORCALL_ARGUMENTS_OFFSET’ (see below).  To get actual
     number of arguments, use *note PyVectorcall_NARGS(nargsf): 3cc6.

     `kwnames' can be either ‘NULL’ (no keyword arguments) or a tuple of
     keyword names.  In the latter case, the values of the keyword
     arguments are stored in `args' after the positional arguments.  The
     number of keyword arguments does not influence `nargsf'.

     `kwnames' must contain only objects of type ‘str’ (not a subclass),
     and all keys must be unique.

     Return the result of the call on success, or raise an exception and
     return ‘NULL’ on failure.

     This uses the vectorcall protocol if the callable supports it;
     otherwise, the arguments are converted to use *note tp_call: 3b6f.

          注解: This function is provisional and expected to become
          public in Python 3.9, with a different name and, possibly,
          changed semantics.  If you use the function, plan for updating
          your code for Python 3.9.

     3.8 新版功能.

 -- C 宏: PY_VECTORCALL_ARGUMENTS_OFFSET

     If set in a vectorcall `nargsf' argument, the callee is allowed to
     temporarily change ‘args[-1]’.  In other words, `args' points to
     argument 1 (not 0) in the allocated vector.  The callee must
     restore the value of ‘args[-1]’ before returning.

     Whenever they can do so cheaply (without additional allocation),
     callers are encouraged to use ‘PY_VECTORCALL_ARGUMENTS_OFFSET’.
     Doing so will allow callables such as bound methods to make their
     onward calls (which include a prepended `self' argument) cheaply.

     3.8 新版功能.

 -- C 函数: Py_ssize_t PyVectorcall_NARGS (size_t nargsf)

     Given a vectorcall `nargsf' argument, return the actual number of
     arguments.  Currently equivalent to ‘nargsf &
     ~PY_VECTORCALL_ARGUMENTS_OFFSET’.

     3.8 新版功能.

 -- C 函数: PyObject* _PyObject_FastCallDict (PyObject *callable,
          PyObject *const *args, size_t nargsf, PyObject *kwdict)

     Same as *note _PyObject_Vectorcall(): 3cc4. except that the keyword
     arguments are passed as a dictionary in `kwdict'.  This may be
     ‘NULL’ if there are no keyword arguments.

     For callables supporting *note vectorcall: 3cc5, the arguments are
     internally converted to the vectorcall convention.  Therefore, this
     function adds some overhead compared to *note
     _PyObject_Vectorcall(): 3cc4.  It should only be used if the caller
     already has a dictionary ready to use.

          注解: This function is provisional and expected to become
          public in Python 3.9, with a different name and, possibly,
          changed semantics.  If you use the function, plan for updating
          your code for Python 3.9.

     3.8 新版功能.

 -- C 函数: Py_hash_t PyObject_Hash (PyObject *o)

     计算并返回对象的哈希值 `o'。 失败时返回 ‘-1’。这相当于 Python 表达
     式 ‘hash(o)’。

     在 3.2 版更改: 现在的返回类型是 Py_hash_t。 这是一个带符号整数，与
     Py_ssize_t 大小相同。

 -- C 函数: Py_hash_t PyObject_HashNotImplemented (PyObject *o)

     设置一个 *note TypeError: 193. 表示 ‘type(o)’ 是不可哈希的，并返回
     ‘-1’ 。该函数保存在 ‘tp_hash’ 槽中时会受到特别对待，允许某个类型向
     解释器显式表明它不可散列。

 -- C 函数: int PyObject_IsTrue (PyObject *o)

     如果对象 `o' 被认为是 true，则返回 ‘1’，否则返回 ‘0’。这相当于
     Python 表达式 ‘not not o’。 失败则返回 ‘-1’。

 -- C 函数: int PyObject_Not (PyObject *o)

     如果对象 `o' 被认为是 true，则返回 ‘1’，否则返回 ‘0’。这相当于
     Python 表达式 ‘not not o’。 失败则返回 ‘-1’。

 -- C 函数: PyObject* PyObject_Type (PyObject *o)
     `Return value: New reference.'

     当 `o' 非 ‘NULL’ 时，返回一个与对象 `o' 的类型相对应的类型对象。失
     败时，引发 *note SystemError: 604. 并返回 ‘NULL’。这等同于 Python 表
     达式 ‘type(o)’。该函数会增加返回值的引用计数。实际上没有理由不去用
     普通的表达式 ‘o->ob_type’ 而使用该函数，表达式会返回一个类型指针
     *note PyTypeObject*: 2d7. ，除非需要增加引用计数。

 -- C 函数: int PyObject_TypeCheck (PyObject *o, PyTypeObject *type)

     Return true if the object `o' is of type `type' or a subtype of
     `type'.  Both parameters must be non-‘NULL’.

 -- C 函数: Py_ssize_t PyObject_Size (PyObject *o)
 -- C 函数: Py_ssize_t PyObject_Length (PyObject *o)

     返回对象 `o' 的长度。 如果对象 `o' 支持序列和映射协议，则返回序列长
     度。 出错时返回 ‘-1’。这等同于 Python 表达式 ‘len(o)’。

 -- C 函数: Py_ssize_t PyObject_LengthHint (PyObject *o,
          Py_ssize_t default)

     Return an estimated length for the object `o'.  First try to return
     its actual length, then an estimate using *note __length_hint__():
     815, and finally return the default value.  On error return ‘-1’.
     This is the equivalent to the Python expression
     ‘operator.length_hint(o, default)’.

     3.4 新版功能.

 -- C 函数: PyObject* PyObject_GetItem (PyObject *o, PyObject *key)
     `Return value: New reference.' 返回对象 `key' 对应的 `o' 元素，或在
     失败时返回 ‘NULL’。这等同于 Python 表达式 ‘o[key]’。

 -- C 函数: int PyObject_SetItem (PyObject *o, PyObject *key,
          PyObject *v)

     将对象 `key' 映射到值 `v'。 失败时引发异常并返回 ‘-1’；成功时返回
     ‘0’。 这相当于 Python 语句 ‘o[key] = v’。该函数 `不会' 偷取 `v' 的
     引用。

 -- C 函数: int PyObject_DelItem (PyObject *o, PyObject *key)

     从对象 `o' 中移除对象 `key' 的映射。失败时返回 ‘-1’。 这相当于
     Python 语句 ‘del o[key]’。

 -- C 函数: PyObject* PyObject_Dir (PyObject *o)
     `Return value: New reference.' 相当于 Python 表达式 ‘dir(o)’，返回
     一个（可能为空）适合对象参数的字符串列表，如果出错则返回 ‘NULL’。 如
     果参数为 ‘NULL’，类似 Python 的 ‘dir()’，则返回当前 locals 的名字；
     这时如果没有活动的执行框架，则返回 ‘NULL’，但 *note
     PyErr_Occurred(): 3b02. 将返回 false。

 -- C 函数: PyObject* PyObject_GetIter (PyObject *o)
     `Return value: New reference.' 等同于 Python 表达式 ‘iter(o)’。为对
     象参数返回一个新的迭代器，如果该对象已经是一个迭代器，则返回对象本
     身。如果对象不能被迭代，会引发 *note TypeError: 193. ，并返回
     ‘NULL’。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3119

   (2) https://www.python.org/dev/peps/pep-3119


File: python.info,  Node: 数字协议,  Next: 序列协议,  Prev: 对象协议,  Up: 抽象对象层

7.7.2 数字协议
--------------

 -- C 函数: int PyNumber_Check (PyObject *o)

     如果对象 `o' 提供数字的协议，返回真 ‘1’，否则返回假。这个函数不会调
     用失败。

     在 3.8 版更改: 如果 `o' 是一个索引整数则返回 ‘1’。

 -- C 函数: PyObject* PyNumber_Add (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 、`o2' 相加的结果，如果失
     败，返回 `NULL' 。等价于 Python 中的表达式 ‘o1 + o2’ 。

 -- C 函数: PyObject* PyNumber_Subtract (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 减去 `o2' 的结果，如果失败
     ，返回 ‘NULL’ 。等价于Python中的表达式 ‘o1 - o2’ 。

 -- C 函数: PyObject* PyNumber_Multiply (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 、 `o2' 相乘的结果，如果失
     败，返回 ‘NULL’。等价于Python中的表达式 ‘o1 * o2’。

 -- C 函数: PyObject* PyNumber_MatrixMultiply (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 、`o2' 做矩阵乘法的结果，
     如果失败，返回 ‘NULL’。等价于Python中的表达式 ‘o1 @ o2’。

     3.5 新版功能.

 -- C 函数: PyObject* PyNumber_FloorDivide (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 除以 `o2' 的向下取整后的结
     果，如果失败，返回 ‘NULL’。等价于“传统”的整数除法。

 -- C 函数: PyObject* PyNumber_TrueDivide (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 除以 `o2' 的一个合理的近似
     值，如果失败，返回 ‘NULL’。这个值是近似的，因为二进制浮点数是一个近
     似值，它不可能表示出以2为基数的所有实数。这个函数返回两个整数相除得
     到的浮点数。

 -- C 函数: PyObject* PyNumber_Remainder (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 除以 `o2' 得到的余数，如果
     失败，返回 ‘NULL’。等价于Python中的表达式 ‘o1 % o2’。

 -- C 函数: PyObject* PyNumber_Divmod (PyObject *o1, PyObject *o2)
     `Return value: New reference.'

     参考内置函数 *note divmod(): 153.。如果失败，返回 ‘NULL’。等价于
     Python表达式 ‘divmod(o1, o2)’。

 -- C 函数: PyObject* PyNumber_Power (PyObject *o1, PyObject *o2,
          PyObject *o3)
     `Return value: New reference.'

     请参阅内置函数 *note pow(): 19b.。 如果失败，返回 ‘NULL’。 等价于
     Python 中的表达式 ‘pow(o1, o2, o3)’，其中 `o3' 是可选的。如果要忽略
     `o3'，则需传入 *note Py_None: 3b07. 作为代替（如果传入 ‘NULL’ 会导
     致非法内存访问）。

 -- C 函数: PyObject* PyNumber_Negative (PyObject *o)
     `Return value: New reference.' 返回 `o' 的负值，如果失败，返回
     ‘NULL’ 。等价于 Python 表达式 ‘-o’。

 -- C 函数: PyObject* PyNumber_Positive (PyObject *o)
     `Return value: New reference.' 返回 `o'，如果失败，返回 ‘NULL’ 。等
     价于 Python 表达式 ‘+o’。

 -- C 函数: PyObject* PyNumber_Absolute (PyObject *o)
     `Return value: New reference.'

     返回 `o' 的绝对值，如果失败，返回 ‘NULL’。等价于 Python 表达式
     ‘abs(o)’。

 -- C 函数: PyObject* PyNumber_Invert (PyObject *o)
     `Return value: New reference.' 返回 `o' 的按位取反后的结果，如果失
     败，返回 ‘NULL’。等价于 Python 表达式 ‘~o’。

 -- C 函数: PyObject* PyNumber_Lshift (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 左移 `o2' 个比特后的结果，
     如果失败，返回 ‘NULL’。等价于 Python 表达式 ‘o1 << o2’。

 -- C 函数: PyObject* PyNumber_Rshift (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 右移 `o2' 个比特后的结果，
     如果失败，返回 ‘NULL’ 。等价于 Python 表达式 ‘o1 >> o2’。

 -- C 函数: PyObject* PyNumber_And (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 和 `o2' “按位与”的结果，如
     果失败，返回 ‘NULL’ 。等价于 Python 表达式 ‘o1 & o2’。

 -- C 函数: PyObject* PyNumber_Xor (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 和 `o2' “按位异或”的结果，
     如果失败，返回 ‘NULL’ 。等价于Python中的表达式 ‘o1 ^o2’。

 -- C 函数: PyObject* PyNumber_Or (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 和 `o2' “按位或”的结果，如
     果失败，返回 ‘NULL’ 。等价于 Python 表达式 ‘o1 | o2’。

 -- C 函数: PyObject* PyNumber_InPlaceAdd (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 、`o2' 相加的结果，如果失
     败，返回 `NULL' 。当 `o1' 支持时，这个操作直接将值赋给 `o1'。 等价
     于 Python 语句 ‘o1 + o2’。

 -- C 函数: PyObject* PyNumber_InPlaceSubtract (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 、`o2' 相减的结果，如果失
     败，返回 ‘NULL’ 。当 `o1' 支持时，这个运算完成后将值赋给 `o1' 。 等
     价于 Python语句 ‘o1 -= o2’。

 -- C 函数: PyObject* PyNumber_InPlaceMultiply (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 、`o2*相乘的结果，如果失败
     ，返回 ‘‘NULL‘‘ 。当 *o1' 支持时，这个运算完成后将值赋给 `o1'。 等
     价于 Python 语句 ‘o1 += o2’。

 -- C 函数: PyObject* PyNumber_InPlaceMatrixMultiply (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 、`o2' 做矩阵乘法后的结果
     ，如果失败，返回 ‘NULL’ 。当 `o1' 支持时，这个运算完成后将值赋给
     `o1'。 等价于 Python 语句 ‘o1 @= o2’。

     3.5 新版功能.

 -- C 函数: PyObject* PyNumber_InPlaceFloorDivide (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 除以 `o2' 后向下取整的结果
     ，如果失败，返回 ‘NULL’。当 `o1' 支持时，这个运算完成后将值赋给
     `o1'。 等价于 Python 语句 ‘o1 //= o2’。

 -- C 函数: PyObject* PyNumber_InPlaceTrueDivide (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 除以 `o2' 的一个合理的近似
     值，如果失败，返回 ‘NULL’。这个值是近似的，因为二进制浮点数是一个近
     似值，不可能以2为基数来表示出所有实数。这个函数返回两个整数相除得到
     的浮点数。当 `o1' 支持时，这个运算完成后将值赋给 `o1'。

 -- C 函数: PyObject* PyNumber_InPlaceRemainder (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 除以 `o2' 得到的余数，如果
     失败，返回 ‘NULL’。当 `o1' 支持时，这个运算直接使用它储存结果。 等
     价于 Python 语句 ‘o1 %= o2’。

 -- C 函数: PyObject* PyNumber_InPlacePower (PyObject *o1, PyObject *o2,
          PyObject *o3)
     `Return value: New reference.'

     请参阅内置函数 *note pow(): 19b.。 如果失败，返回 ‘NULL’。当 `o1' 支
     持时，这个运算直接使用它储存结果。当 `o3' 是 *note Py_None: 3b07. 时
     ，等价于 Python 语句 ‘o1 **= o2’；否则等价于在原来位置储存结果的
     ‘pow(o1, o2, o3)’ 。如果要忽略 `o3'，则需传入 *note Py_None: 3b07.
     （传入 ‘NULL’ 会导致非法内存访问）。

 -- C 函数: PyObject* PyNumber_InPlaceLshift (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 左移 `o2' 个比特后的结果，
     如果失败，返回 ‘NULL’。当 `o1' 支持时，这个运算直接使用它储存结果。
     等价于 Python 语句 ‘o1 <<= o2’。

 -- C 函数: PyObject* PyNumber_InPlaceRshift (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 右移 `o2' 个比特后的结果，
     如果失败，返回 ‘NULL’。当 `o1' 支持时，这个运算直接使用它储存结果。
     等价于 Python 语句 ‘o1 >>= o2’。

 -- C 函数: PyObject* PyNumber_InPlaceAnd (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 成功时返回 `o1' 和 `o2' "按位与" 的
     结果，失败时返回 ‘NULL’。 在 `o1' 支持的前提下该操作将 `原地' 执行
     。 等价与 Python 语句 ‘o1 &= o2’。

 -- C 函数: PyObject* PyNumber_InPlaceXor (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 成功时返回 `o1' 和 `o2' "按位异或的
     结果，失败时返回 ‘NULL’。 在 `o1' 支持的前提下该操作将 `原地' 执行
     。 等价与 Python 语句 ‘o1 ^= o2’。

 -- C 函数: PyObject* PyNumber_InPlaceOr (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 成功时返回 `o1' 和 `o2' "按位或" 的
     结果，失败时返回 ‘NULL’。 在 `o1' 支持的前提下该操作将 `原地' 执行
     。 等价于 Python 语句 ‘o1 |= o2’。

 -- C 函数: PyObject* PyNumber_Long (PyObject *o)
     `Return value: New reference.'

     成功时返回 `o' 换为整数对象或的结果，失败时返回 ‘NULL’。 等价于
     Python 表达式 ‘int(o)’。

 -- C 函数: PyObject* PyNumber_Float (PyObject *o)
     `Return value: New reference.'

     成功时返回 `o' 转换为浮点对象后的结果，失败时返回 ‘NULL’。 等价于
     Python 表达式 ‘float(o)’。

 -- C 函数: PyObject* PyNumber_Index (PyObject *o)
     `Return value: New reference.' 成功时返回 `o' 转换为 Python int 类
     型后的结果，失败时返回 ‘NULL’ 并引发 *note TypeError: 193. 异常。

 -- C 函数: PyObject* PyNumber_ToBase (PyObject *n, int base)
     `Return value: New reference.' 返回整数 `n' 转换成以 `base' 为基数
     的字符串后的结果。这个 `base' 参数必须是 2，8，10 或者 16 。对于基
     数 2，8，或 16 ，返回的字符串将分别加上基数标识 ‘'0b'’, ‘'0o'’, or
     ‘'0x'’。如果 `n' 不是 Python 中的整数 `int' 类型，就先通过 *note
     PyNumber_Index(): 3cf2. 将它转换成整数类型。

 -- C 函数: Py_ssize_t PyNumber_AsSsize_t (PyObject *o, PyObject *exc)

     如果 `o' 是一个整数类型的解释型，返回 `o' 转换成一个 Py_ssize_t 值
     项后的结果。如果调用失败，返回 ‘-1’ 并引发异常。

     如果 `o' 可以被转换为 Python int 类型但尝试转换为 Py_ssize_t 值则会
     引发 *note OverflowError: 968.，这时 `exc' 参数为将被引发的异常类型
     (通常是 *note IndexError: e7d. 或 *note OverflowError: 968.)。 如果
     `exc' 为 ‘NULL’，则异常会被清除并且值会被剪切到负整数
     ‘PY_SSIZE_T_MIN’ 或正整数 ‘PY_SSIZE_T_MAX’。

 -- C 函数: int PyIndex_Check (PyObject *o)

     如果 `o' 是一个索引整数（存有 nb_index 位置并有 tp_as_number 填入其
     中）则返回 ‘1’，否则返回 ‘0’ 。这个函数不会调用失败。


File: python.info,  Node: 序列协议,  Next: 映射协议,  Prev: 数字协议,  Up: 抽象对象层

7.7.3 序列协议
--------------

 -- C 函数: int PySequence_Check (PyObject *o)

     如果对象提供序列协议，函数返回 ‘1’，否则返回 ‘0’。 请注意它将为具有
     *note __getitem__(): 280. 方法的 Python 类返回 ‘1’，除非它们是
     *note dict: 1b9. 的子类，因为在一般情况下无法确定它所支持键类型。 此
     函数总是会成功执行。

 -- C 函数: Py_ssize_t PySequence_Size (PyObject *o)
 -- C 函数: Py_ssize_t PySequence_Length (PyObject *o)

     成功时返回序列中*o*的对象数,失败时返回‘‘-1‘‘. 相当于Python的
     ‘‘len(o)‘‘表达式.

 -- C 函数: PyObject* PySequence_Concat (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 成功时返回 `o1' 和 `o2' 的拼接，失败
     时返回 ‘NULL’。 这等价于 Python 表达式 ‘o1 + o2’。

 -- C 函数: PyObject* PySequence_Repeat (PyObject *o, Py_ssize_t count)
     `Return value: New reference.' 返回序列对象 `o' 重复 `count' 次的结
     果，失败时返回 ‘NULL’。 这等价于 Python 表达式 ‘o * count’。

 -- C 函数: PyObject* PySequence_InPlaceConcat (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 成功时返回 `o1' 和 `o2' 的拼接，失败
     时返回 ‘NULL’。 在 `o1' 支持的情况下操作将 `原地' 完成。 这等价于
     Python 表达式 ‘o1 += o2’。

 -- C 函数: PyObject* PySequence_InPlaceRepeat (PyObject *o,
          Py_ssize_t count)
     `Return value: New reference.'  Return the result of repeating
     sequence object返回序列对象 `o' 重复 `count' 次的结果，失败时返回
     ‘NULL’。 在 `o' 支持的情况下该操作会 `原地' 完成。 这等价于 Python
     表达式 ‘o *= count’。

 -- C 函数: PyObject* PySequence_GetItem (PyObject *o, Py_ssize_t i)
     `Return value: New reference.' 返回 `o' 中的第 `i' 号元素，失败时返
     回 ‘NULL’。 这等价于 Python 表达式 ‘o[i]’。

 -- C 函数: PyObject* PySequence_GetSlice (PyObject *o, Py_ssize_t i1,
          Py_ssize_t i2)
     `Return value: New reference.' 返回序列对象 `o' 的 `i1' 到 `i2' 的
     切片，失败时返回 ‘NULL’。 这等价于 Python 表达式 ‘o[i1:i2]’。

 -- C 函数: int PySequence_SetItem (PyObject *o, Py_ssize_t i,
          PyObject *v)

     将对象 `v' 赋值给 `o' 的第 `i' 号元素。 失败时会引发异常并返回
     ‘-1’；成功时返回 ‘0’。 这相当于 Python 语句 ‘o[i] = v’。 此函数 `不
     会' 改变对 `v' 的引用。

     如果 `v' 为 ‘NULL’，元素将被删除，但是此特性已被弃用，应当改用
     *note PySequence_DelItem(): 1060.。

 -- C 函数: int PySequence_DelItem (PyObject *o, Py_ssize_t i)

     删除对象 `o' 的第 `i' 号元素。 失败时返回 ‘-1’。 这相当于 Python 语
     句 ‘del o[i]’。

 -- C 函数: int PySequence_SetSlice (PyObject *o, Py_ssize_t i1,
          Py_ssize_t i2, PyObject *v)

     将序列对象 `v' 赋值给序列对象 `o' 的从 `i1' 到 `i2' 切片。 这相当于
     Python 语句 ‘o[i1:i2] = v’。

 -- C 函数: int PySequence_DelSlice (PyObject *o, Py_ssize_t i1,
          Py_ssize_t i2)

     删除序列对象 `o' 的从 `i1' 到 `i2' 的切片。 失败时返回 ‘-1’。 这相
     当于 Python 语句 ‘del o[i1:i2]’。

 -- C 函数: Py_ssize_t PySequence_Count (PyObject *o, PyObject *value)

     返回 `value' 在 `o' 中出现的次数，即返回使得 ‘o[key] == value’ 的键
     的数量。 失败时返回 ‘-1’。 这相当于 Python 表达式 ‘o.count(value)’。

 -- C 函数: int PySequence_Contains (PyObject *o, PyObject *value)

     确定 `o' 是否包含 `value'。 如果 `o' 中的某一项等于 `value'，则返回
     ‘1’，否则返回 ‘0’。 出错时，返回 ‘-1’。 这相当于 Python 表达式
     ‘value in o’。

 -- C 函数: Py_ssize_t PySequence_Index (PyObject *o, PyObject *value)

     返回第一个索引*i*,其中 ‘o[i] == value’.出错时,返回 ‘-1’.相当于
     Python的‘‘o.index(value)‘‘表达式.

 -- C 函数: PyObject* PySequence_List (PyObject *o)
     `Return value: New reference.' 返回一个列表对象，其内容与序列或可迭
     代对象 `o' 相同，失败时返回 ‘NULL’。 返回的列表保证是一个新对象。 这
     等价于 Python 表达式 ‘list(o)’。

 -- C 函数: PyObject* PySequence_Tuple (PyObject *o)
     `Return value: New reference.'

     返回一个元组对象，其内容与序列或可迭代对象 `o' 相同，失败时返回
     ‘NULL’。 如果 `o' 为元组，则将返回一个新的引用，在其他情况下将使用
     适当的内容构造一个元组。 这等价于 Python 表达式 ‘tuple(o)’。

 -- C 函数: PyObject* PySequence_Fast (PyObject *o, const char *m)
     `Return value: New reference.' 将序列或可迭代对象 `o' 作为其他
     ‘PySequence_Fast*’ 函数族可用的对象返回。 如果该对象不是序列或可迭
     代对象，则会引发 *note TypeError: 193. 并将 `m' 作为消息文本。 失败
     时返回 ‘NULL’。

     ‘PySequence_Fast*’ 函数之所以这样命名，是因为它们会假定 `o' 是一个
     *note PyTupleObject: 3c57. 或 *note PyListObject: 3d06. 并直接访问
     `o' 的数据字段。

     作为 CPython 的实现细节，如果 `o' 已经是一个序列或列表，它将被直接
     返回。

 -- C 函数: Py_ssize_t PySequence_Fast_GET_SIZE (PyObject *o)

     在 `o' 由 *note PySequence_Fast(): 3d05. 返回且 `o' 不为 ‘NULL’ 的
     情况下返回 `o' 的长度。 也可以通过在 `o' 上调用 *note
     PySequence_Size(): 105d. 来获取大小，但是 *note
     PySequence_Fast_GET_SIZE(): 3d07. 速度更快，因为它可以假定 `o' 为列
     表或元组。

 -- C 函数: PyObject* PySequence_Fast_GET_ITEM (PyObject *o,
          Py_ssize_t i)
     `Return value: Borrowed reference.' 在 `o' 由 *note
     PySequence_Fast(): 3d05. 返回且 `o' 不 ‘NULL’，并且 `i' d在索引范围
     内的情况下返回 `o' 的第 `i' 号元素。

 -- C 函数: PyObject** PySequence_Fast_ITEMS (PyObject *o)

     返回 PyObject 指针的底层数组。 假设 `o' 由 *note PySequence_Fast():
     3d05. 返回且 `o' 不为 ‘NULL’。

     请注意,如果列表调整大小,重新分配可能会重新定位items数组.因此,仅在序
     列无法更改的上下文中使用基础数组指针.

 -- C 函数: PyObject* PySequence_ITEM (PyObject *o, Py_ssize_t i)
     `Return value: New reference.' 返回 `o' 的第 `i' 个元素或在失败时返
     回 ‘NULL’。 此形式比 *note PySequence_GetItem(): 105e. 理馔，但不会
     检查 `o' 上的 *note PySequence_Check(): 3cf7. 是否为真值，也不会对
     负序号进行调整。


File: python.info,  Node: 映射协议,  Next: 迭代器协议,  Prev: 序列协议,  Up: 抽象对象层

7.7.4 映射协议
--------------

参见 *note PyObject_GetItem(): 3bb5.、*note PyObject_SetItem(): 3bb3. 与
*note PyObject_DelItem(): 3ccf.。

 -- C 函数: int PyMapping_Check (PyObject *o)

     如果对象提供映射协议或支持切片则返回 ‘1’，否则返回 ‘0’。 请注意它将
     为具有 *note __getitem__(): 280. 方法的 Python 类返回 ‘1’，因为在一
     般情况下无法确定它所支持的键类型。 此函数总是会成功执行。

 -- C 函数: Py_ssize_t PyMapping_Size (PyObject *o)
 -- C 函数: Py_ssize_t PyMapping_Length (PyObject *o)

     成功时返回对象 `o' 中键的数量，失败时返回 ‘-1’。 这相当于 Python 表
     达式 ‘len(o)’。

 -- C 函数: PyObject* PyMapping_GetItemString (PyObject *o, const
          char *key)
     `Return value: New reference.' 返回 `o' 中对应于字符串 `key' 的元素
     ，或者失败时返回 ‘NULL’。 这相当于 Python 表达式 ‘o[key]’。 另请参
     见 also *note PyObject_GetItem(): 3bb5.。

 -- C 函数: int PyMapping_SetItemString (PyObject *o, const char *key,
          PyObject *v)

     在对象 `o' 中将字符串 `key' 映射到值 `v'。 失败时返回 ‘-1’。 这相当
     于 Python 语句 ‘o[key] = v’。 另请参见 *note PyObject_SetItem():
     3bb3.。 此函数 `不会' 增加对 `v' 的引用。

 -- C 函数: int PyMapping_DelItem (PyObject *o, PyObject *key)

     从对象 `o' 中移除对象 `key' 的映射。 失败时返回 ‘-1’。 这相当于
     Python 语句 ‘del o[key]’。 这是 *note PyObject_DelItem(): 3ccf. 的
     一个别名。

 -- C 函数: int PyMapping_DelItemString (PyObject *o, const char *key)

     从对象 `o' 中移除字符串 `key' 的映射。 失败时返回 ‘-1’。 这相当于
     Python 语句 ‘del o[key]’。

 -- C 函数: int PyMapping_HasKey (PyObject *o, PyObject *key)

     如果映射对象具有键 `key' 则返回 ‘1’，否则返回 ‘0’。 这相当于 Python
     表达式 ‘key in o’。 此函数总是会成功执行。

     请注意在调用 *note __getitem__(): 280. 方法期间发生的异常将会被屏蔽
     。 要获取错误报告请改用 *note PyObject_GetItem(): 3bb5.。

 -- C 函数: int PyMapping_HasKeyString (PyObject *o, const char *key)

     如果映射对象具有键 `key' 则返回 ‘1’，否则返回 ‘0’。 这相当于 Python
     表达式 ‘key in o’。 此函数总是会成功执行。

     请注意在调用 *note __getitem__(): 280. 方法期间发生的异常将会被屏蔽
     。 要获取错误报告请改用 *note PyMapping_GetItemString(): 3d10.。

 -- C 函数: PyObject* PyMapping_Keys (PyObject *o)
     `Return value: New reference.' 成功时，返回对象 `o' 中的键的列表。
     失败时，返回 ‘NULL’。

     在 3.7 版更改: 在之前版本中，此函数返回一个列表或元组。

 -- C 函数: PyObject* PyMapping_Values (PyObject *o)
     `Return value: New reference.' 成功时，返回对象 `o' 中的值的列表。
     失败时，返回 ‘NULL’。

     在 3.7 版更改: 在之前版本中，此函数返回一个列表或元组。

 -- C 函数: PyObject* PyMapping_Items (PyObject *o)
     `Return value: New reference.' 成功时，返回对象 `o' 中条目的列表，
     其中每个条目是一个包含键值对的元组。 失败时，返回 ‘NULL’。

     在 3.7 版更改: 在之前版本中，此函数返回一个列表或元组。


File: python.info,  Node: 迭代器协议,  Next: 缓冲协议,  Prev: 映射协议,  Up: 抽象对象层

7.7.5 迭代器协议
----------------

迭代器有两个函数。

 -- C 函数: int PyIter_Check (PyObject *o)

     返回 true ， 如果对象 `o' 支持迭代器协议的话。

 -- C 函数: PyObject* PyIter_Next (PyObject *o)
     `Return value: New reference.' 返回迭代 `o' 的下一个值。 对象必须是
     一个迭代器（这应由调用者来判断）。 如果没有余下的值，则返回 ‘NULL’
     并且不设置异常。 如果在获取条目时发生了错误，则返回 ‘NULL’ 并且传递
     异常。

要为迭代器编写一个一个循环，C代码应该看起来像这样

     PyObject *iterator = PyObject_GetIter(obj);
     PyObject *item;

     if (iterator == NULL) {
         /* propagate error */
     }

     while ((item = PyIter_Next(iterator))) {
         /* do something with item */
         ...
         /* release reference when done */
         Py_DECREF(item);
     }

     Py_DECREF(iterator);

     if (PyErr_Occurred()) {
         /* propagate error */
     }
     else {
         /* continue doing useful work */
     }


File: python.info,  Node: 缓冲协议,  Next: 旧缓冲协议,  Prev: 迭代器协议,  Up: 抽象对象层

7.7.6 缓冲协议
--------------

在 Python 中可使用一些对象来包装对底层内存数组或称 `缓冲' 的访问。此类对
象包括内置的 *note bytes: 33a. 和 *note bytearray: 33b. 以及一些如 *note
array.array: 459. 这样的扩展类型。第三方库也可能会为了特殊的目的而定义它
们自己的类型，例如用于图像处理和数值分析等。

虽然这些类型中的每一种都有自己的语义，但它们具有由可能较大的内存缓冲区支
持的共同特征。 在某些情况下，希望直接访问该缓冲区而无需中间复制。

Python 以 *note 缓冲协议: 15f7. 的形式在 C 层级上提供这样的功能。 此协议
包括两个方面:

   - 在生产者这一方面，该类型的协议可以导出一个“缓冲区接口”，允许公开它
     的底层缓冲区信息。该接口的描述信息在 *note Buffer Object
     Structures: 3d1c. 一节中；

   - 在消费者一侧，有几种方法可用于获得指向对象的原始底层数据的指针（例
     如一个方法的形参）。

一些简单的对象例如 *note bytes: 33a. 和 *note bytearray: 33b. 会以面向字
节的形式公开它们的底层缓冲区。 也可能会用其他形式；例如 *note
array.array: 459. 所公开的元素可以是多字节值。

缓冲区接口的消费者的一个例子是文件对象的 *note write(): 592. 方法：任何
可以输出为一系列字节流的对象可以被写入文件。然而 ‘write()’ 方法只需要对
于传入对象的只读权限，其他的方法，如 *note readinto(): 2003. 需要参数内
容的写入权限。缓冲区接口使得对象可以选择性地允许或拒绝读写或只读缓冲区的
导出。

对于缓冲区接口的使用者而言，有两种方式来获取一个目的对象的缓冲：

   * 使用正确的参数来调用 *note PyObject_GetBuffer(): d2d. 函数；

   * 调用 *note PyArg_ParseTuple(): 26b. (或其同级对象之一) 并传入 ‘y*’,
     ‘w*’ or ‘s*’ *note 格式代码: 2d1. 中的一个。

在这两种情况下，当不再需要缓冲区时必须调用 *note PyBuffer_Release():
d5c. 。如果此操作失败，可能会导致各种问题，例如资源泄漏。

* Menu:

* 缓冲区结构::
* 缓冲区请求的类型::
* 复杂数组::
* 缓冲区相关函数::


File: python.info,  Node: 缓冲区结构,  Next: 缓冲区请求的类型,  Up: 缓冲协议

7.7.6.1 缓冲区结构
..................

缓冲区结构(或者简单地称为“buffers”)对于将二进制数据从另一个对象公开给
Python 程序员非常有用。它们还可以用作零拷贝切片机制。使用它们引用内存块
的能力，可以很容易地将任何数据公开给 Python 程序员。内存可以是 C 扩展中
的一个大的常量数组，也可以是在传递到操作系统库之前用于操作的原始内存块，
或者可以用来传递本机内存格式的结构化数据。

与 Python 解释器公开的大多部数据类型不同，缓冲区不是 *note PyObject:
4c2. 指针而是简单的 C 结构。 这使得它们可以非常简单地创建和复制。 当需要
为缓冲区加上泛型包装器时，可以创建一个 *note 内存视图: 3d1f. 对象。

有关如何编写并导出对象的简短说明，请参阅 *note 缓冲区对象结构: 3d1c.。 要
获取缓冲区对象，请参阅 *note PyObject_GetBuffer(): d2d.。

 -- C 类型: Py_buffer

      -- C 成员: void *buf

          指向由缓冲区字段描述的逻辑结构开始的指针。 这可以是导出程序底
          层物理内存块中的任何位置。 例如，使用负的 *note strides: 3d21.
          值可能指向内存块的末尾。

          对于 *note contiguous: 16c5. ，‘邻接’数组，值指向内存块的开头
          。

      -- C 成员: void *obj

          对导出对象的新引用。 该引用归使用者所有，并由 *note
          PyBuffer_Release(): d5c. 自动递减并设置为 ‘NULL’。 该字段等于
          任何标准 C-API 函数的返回值。

          作为一种特殊情况，对于由 *note PyMemoryView_FromBuffer():
          3d23. 或 *note PyBuffer_FillInfo(): 3d24. 包装的 `temporary' 缓
          冲区，此字段为 ‘NULL’。 通常，导出对象不得使用此方案。

      -- C 成员: Py_ssize_t len

          ‘product(shape) * itemsize’。对于连续数组，这是基础内存块的长
          度。对于非连续数组，如果逻辑结构复制到连续表示形式，则该长度将
          具有该长度。

          仅当缓冲区是通过保证连续性的请求获取时，才访问 ‘((char
          *)buf)[0] up to ((char *)buf)[len-1]’ 时才有效。在大多数情况下
          ，此类请求将为 *note PyBUF_SIMPLE: 3d26. 或 *note
          PyBUF_WRITABLE: 3d27.。

      -- C 成员: int readonly

          缓冲区是否为只读的指示器。此字段由 *note PyBUF_WRITABLE: 3d27.
          标志控制。

      -- C 成员: Py_ssize_t itemsize

          单个元素的项大小（以字节为单位）。与 *note struct.calcsize():
          1820. 调用非 ‘NULL’ *note format: 3d2a. 的值相同。

          重要例外：如果使用者请求的缓冲区没有 *note PyBUF_FORMAT: 3d2b.
          标志，*note format: 3d2a. 将设置为 ‘NULL’，但 *note itemsize:
          3d29. 仍具有原始格式的值。

          如果 *note shape: 3d2c. 存在，则相等的 ‘product(shape) *
          itemsize == len’ 仍然存在，使用者可以使用 *note itemsize:
          3d29. 来导航缓冲区。

          如果 *note shape: 3d2c. 是 ‘NULL’，因为结果为 *note
          PyBUF_SIMPLE: 3d26. 或 *note PyBUF_WRITABLE: 3d27. 请求，则使
          用者必须忽略 *note itemsize: 3d29.，并假设 ‘itemsize == 1’。

      -- C 成员: const char *format

          在 *note struct: f9. 模块样式语法中 `NUL' 字符串，描述单个项的
          内容。如果这是 ‘NULL’，则假定为‘‘"B"‘‘ (无符号字节) 。

          此字段由 *note PyBUF_FORMAT: 3d2b. 标志控制。

      -- C 成员: int ndim

          内存表示为 n 维数组的维数。 如果是‘‘0‘‘， *note buf: 3d20. 指
          向表示标量的单个项目。 在这种情况下，*note shape: 3d2c.、*note
          strides: 3d21. 和 *note suboffsets: 3d2e. 必须是‘‘NULL‘‘ 。

          宏 ‘PyBUF_MAX_NDIM’ 将最大维度数限制为 64。 导出程序必须遵守这
          个限制，多维缓冲区的使用者应该能够处理最多 ‘PyBUF_MAX_NDIM’ 维
          度。

      -- C 成员: Py_ssize_t *shape

          一个长度为 ‘Py_ssize_t’ 的数组 *note ndim: 3d2d. 表示作为 n 维
          数组的内存形状。 请注意，‘shape[0] * ... * shape[ndim-1] *
          itemsize’ 必须等于 *note len: 3d25.。

          Shape值被限定在 ‘shape[n] >= 0’ 。 ‘shape[n] == 0’ 这一情形需
          要特别注意。查看 *note complex arrays: 3d2f. 来获得更多的信息
          。

          shape数组对于使用者来说是只读的。

      -- C 成员: Py_ssize_t *strides

          一个长度为 ‘Py_ssize_t’ 的数组 *note ndim: 3d2d. 给出要跳过的
          字节数以获取每个尺寸中的新元素。

          Stride 步幅数组中的值可以为任何整数。对于常规数组，步幅通常为
          正数，但是使用者必须能够处理 ‘strides[n] <= 0’ 的情况。更多信
          息请参阅 *note complex arrays: 3d2f. 。

          strides数组对用户来说是只读的。

      -- C 成员: Py_ssize_t *suboffsets

          An array of ‘Py_ssize_t’ of length *note ndim: 3d2d.  If
          ‘suboffsets[n] >= 0’, the values stored along the nth
          dimension are pointers and the suboffset value dictates how
          many bytes to add to each pointer after de-referencing.  A
          suboffset value that is negative indicates that no
          de-referencing should occur (striding in a contiguous memory
          block).

          如果所有子偏移均为负（即无需取消引用），则此字段必须为 ‘NULL’
          （默认值）。

          Python Imaging Library (PIL) 中使用了这种数组的表达方式。请参
          阅 *note complex arrays: 3d2f. 来了解如何从这样一个数组中访问
          元素。

          suboffsets 数组对于使用者来说是只读的。

      -- C 成员: void *internal

          This is for use internally by the exporting object.  For
          example, this might be re-cast as an integer by the exporter
          and used to store flags about whether or not the shape,
          strides, and suboffsets arrays must be freed when the buffer
          is released.  The consumer MUST NOT alter this value.


File: python.info,  Node: 缓冲区请求的类型,  Next: 复杂数组,  Prev: 缓冲区结构,  Up: 缓冲协议

7.7.6.2 缓冲区请求的类型
........................

Buffers are usually obtained by sending a buffer request to an exporting
object via *note PyObject_GetBuffer(): d2d.  Since the complexity of the
logical structure of the memory can vary drastically, the consumer uses
the `flags' argument to specify the exact buffer type it can handle.

所有 *note Py_buffer: b23. 字段均由请求类型明确定义。

* Menu:

* 与请求无关的字段::
* 只读，格式::
* 形状，步幅，子偏移量::
* 连续性的请求::
* 复合请求::


File: python.info,  Node: 与请求无关的字段,  Next: 只读，格式,  Up: 缓冲区请求的类型

7.7.6.3 与请求无关的字段
........................

以下字段不会被 `flags' 影响，并且必须总是用正确的值填充：*note obj:
3d22, *note buf: 3d20.，*note len: 3d25.，*note itemsize: 3d29.，*note
ndim: 3d2d.。


File: python.info,  Node: 只读，格式,  Next: 形状，步幅，子偏移量,  Prev: 与请求无关的字段,  Up: 缓冲区请求的类型

7.7.6.4 只读，格式
..................

      -- C 宏: PyBUF_WRITABLE

          Controls the *note readonly: 3d28. field.  If set, the
          exporter MUST provide a writable buffer or else report
          failure.  Otherwise, the exporter MAY provide either a
          read-only or writable buffer, but the choice MUST be
          consistent for all consumers.

      -- C 宏: PyBUF_FORMAT

          控制 *note format: 3d2a. 字段。 如果设置，则必须正确填写此字段
          。其他情况下，此字段必须为‘‘NULL‘‘。

*note PyBUF_WRITABLE: 3d27. can be |’d to any of the flags in the next
section.  Since *note PyBUF_SIMPLE: 3d26. is defined as 0, *note
PyBUF_WRITABLE: 3d27. can be used as a stand-alone flag to request a
simple writable buffer.

*note PyBUF_FORMAT: 3d2b. 可以被设为除了 *note PyBUF_SIMPLE: 3d26. 之外
的任何标志。 后者已经按暗示了‘‘B‘‘(无符号字节串)格式。


File: python.info,  Node: 形状，步幅，子偏移量,  Next: 连续性的请求,  Prev: 只读，格式,  Up: 缓冲区请求的类型

7.7.6.5 形状，步幅，子偏移量
............................

控制内存逻辑结构的标志按照复杂度的递减顺序列出。注意，每个标志包含它下面
的所有标志。

请求                              形状        步幅          子偏移量
                                                            
-----------------------------------------------------------------------------
                                                            
 -- C 宏: PyBUF_INDIRECT          是          是            如果需要的话
                                                            
                                                            
 -- C 宏: PyBUF_STRIDES           是          是            NULL
                                                            
                                                            
 -- C 宏: PyBUF_ND                是          NULL          NULL
                                                            
                                                            
 -- C 宏: PyBUF_SIMPLE            NULL        NULL          NULL
                                                            


File: python.info,  Node: 连续性的请求,  Next: 复合请求,  Prev: 形状，步幅，子偏移量,  Up: 缓冲区请求的类型

7.7.6.6 连续性的请求
....................

可以显式地请求C 或 Fortran *note 连续: 16c5. ，不管有没有步幅信息。若没
有步幅信息，则缓冲区必须是 C-连续的。

请求                                    形状        步幅          子偏移量         邻接
                                                                                   
------------------------------------------------------------------------------------------------
                                                                                   
 -- C 宏: PyBUF_C_CONTIGUOUS            是          是            NULL             C
                                                                                   
                                                                                   
 -- C 宏: PyBUF_F_CONTIGUOUS            是          是            NULL             F
                                                                                   
                                                                                   
 -- C 宏: PyBUF_ANY_CONTIGUOUS          是          是            NULL             C 或 F
                                                                                   
                                                                                   
*note PyBUF_ND: 3d38.                   是          NULL          NULL             C
                                                                                   


File: python.info,  Node: 复合请求,  Prev: 连续性的请求,  Up: 缓冲区请求的类型

7.7.6.7 复合请求
................

所有可能的请求都由上一节中某些标志的组合完全定义。为方便起见，缓冲区协议
提供常用的组合作为单个标志。

In the following table `U' stands for undefined contiguity.  The
consumer would have to call *note PyBuffer_IsContiguous(): 3d3e. to
determine contiguity.

请求                                形状        步幅          子偏移量         邻接         只读           format
                                                                                                           
------------------------------------------------------------------------------------------------------------------------
                                                                                                           
 -- C 宏: PyBUF_FULL                是          是            如果需要的话     U            0              是
                                                                                                           
                                                                                                           
 -- C 宏: PyBUF_FULL_RO             是          是            如果需要的话     U            1 或 0         是
                                                                                                           
                                                                                                           
 -- C 宏: PyBUF_RECORDS             是          是            NULL             U            0              是
                                                                                                           
                                                                                                           
 -- C 宏: PyBUF_RECORDS_RO          是          是            NULL             U            1 或 0         是
                                                                                                           
                                                                                                           
 -- C 宏: PyBUF_STRIDED             是          是            NULL             U            0              NULL
                                                                                                           
                                                                                                           
 -- C 宏: PyBUF_STRIDED_RO          是          是            NULL             U            1 或 0         NULL
                                                                                                           
                                                                                                           
 -- C 宏: PyBUF_CONTIG              是          NULL          NULL             C            0              NULL
                                                                                                           
                                                                                                           
 -- C 宏: PyBUF_CONTIG_RO           是          NULL          NULL             C            1 或 0         NULL
                                                                                                           


File: python.info,  Node: 复杂数组,  Next: 缓冲区相关函数,  Prev: 缓冲区请求的类型,  Up: 缓冲协议

7.7.6.8 复杂数组
................

* Menu:

* NumPy-风格：形状和步幅::
* PIL-风格：形状，步幅和子偏移量::


File: python.info,  Node: NumPy-风格：形状和步幅,  Next: PIL-风格：形状，步幅和子偏移量,  Up: 复杂数组

7.7.6.9 NumPy-风格：形状和步幅
..............................

The logical structure of NumPy-style arrays is defined by *note
itemsize: 3d29, *note ndim: 3d2d, *note shape: 3d2c. and *note strides:
3d21.

If ‘ndim == 0’, the memory location pointed to by *note buf: 3d20. is
interpreted as a scalar of size *note itemsize: 3d29.  In that case,
both *note shape: 3d2c. and *note strides: 3d21. are ‘NULL’.

If *note strides: 3d21. is ‘NULL’, the array is interpreted as a
standard n-dimensional C-array.  Otherwise, the consumer must access an
n-dimensional array as follows:

     ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * strides[n-1];
     item = *((typeof(item) *)ptr);

As noted above, *note buf: 3d20. can point to any location within the
actual memory block.  An exporter can check the validity of a buffer
with this function:

     def verify_structure(memlen, itemsize, ndim, shape, strides, offset):
         """Verify that the parameters represent a valid array within
            the bounds of the allocated memory:
                char *mem: start of the physical memory block
                memlen: length of the physical memory block
                offset: (char *)buf - mem
         """
         if offset % itemsize:
             return False
         if offset < 0 or offset+itemsize > memlen:
             return False
         if any(v % itemsize for v in strides):
             return False

         if ndim <= 0:
             return ndim == 0 and not shape and not strides
         if 0 in shape:
             return True

         imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)
                    if strides[j] <= 0)
         imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)
                    if strides[j] > 0)

         return 0 <= offset+imin and offset+imax+itemsize <= memlen


File: python.info,  Node: PIL-风格：形状，步幅和子偏移量,  Prev: NumPy-风格：形状和步幅,  Up: 复杂数组

7.7.6.10 PIL-风格：形状，步幅和子偏移量
.......................................

除了常规项之外， PIL 风格的数组还可以包含指针，必须跟随这些指针才能到达
维度的下一个元素。例如，常规的三维 C 语言数组 ‘char v[2][2][3]’ 可以看作
是一个指向 2 个二维数组的 2 个指针：‘char (*v[2])[2][3]’。在子偏移表示中
，这两个指针可以嵌入在 *note buf: 3d20. 的开头，指向两个可以位于内存任何
位置的 ‘char x[2][3]’ 数组。

Here is a function that returns a pointer to the element in an N-D array
pointed to by an N-dimensional index when there are both non-‘NULL’
strides and suboffsets:

     void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
                            Py_ssize_t *suboffsets, Py_ssize_t *indices) {
         char *pointer = (char*)buf;
         int i;
         for (i = 0; i < ndim; i++) {
             pointer += strides[i] * indices[i];
             if (suboffsets[i] >=0 ) {
                 pointer = *((char**)pointer) + suboffsets[i];
             }
         }
         return (void*)pointer;
     }


File: python.info,  Node: 缓冲区相关函数,  Prev: 复杂数组,  Up: 缓冲协议

7.7.6.11 缓冲区相关函数
.......................

 -- C 函数: int PyObject_CheckBuffer (PyObject *obj)

     Return ‘1’ if `obj' supports the buffer interface otherwise ‘0’.
     When ‘1’ is returned, it doesn’t guarantee that *note
     PyObject_GetBuffer(): d2d. will succeed.  This function always
     succeeds.

 -- C 函数: int PyObject_GetBuffer (PyObject *exporter, Py_buffer *view,
          int flags)

     Send a request to `exporter' to fill in `view' as specified by
     `flags'.  If the exporter cannot provide a buffer of the exact
     type, it MUST raise ‘PyExc_BufferError’, set ‘view->obj’ to ‘NULL’
     and return ‘-1’.

     On success, fill in `view', set ‘view->obj’ to a new reference to
     `exporter' and return 0.  In the case of chained buffer providers
     that redirect requests to a single object, ‘view->obj’ MAY refer to
     this object instead of `exporter' (See *note Buffer Object
     Structures: 3d1c.).

     Successful calls to *note PyObject_GetBuffer(): d2d. must be paired
     with calls to *note PyBuffer_Release(): d5c, similar to ‘malloc()’
     and ‘free()’.  Thus, after the consumer is done with the buffer,
     *note PyBuffer_Release(): d5c. must be called exactly once.

 -- C 函数: void PyBuffer_Release (Py_buffer *view)

     Release the buffer `view' and decrement the reference count for
     ‘view->obj’.  This function MUST be called when the buffer is no
     longer being used, otherwise reference leaks may occur.

     It is an error to call this function on a buffer that was not
     obtained via *note PyObject_GetBuffer(): d2d.

 -- C 函数: Py_ssize_t PyBuffer_SizeFromFormat (const char *)

     Return the implied *note itemsize: 3d29. from *note format: 3d2a.
     This function is not yet implemented.

 -- C 函数: int PyBuffer_IsContiguous (Py_buffer *view, char order)

     Return ‘1’ if the memory defined by the `view' is C-style (`order'
     is ‘'C'’) or Fortran-style (`order' is ‘'F'’) *note contiguous:
     16c5. or either one (`order' is ‘'A'’).  Return ‘0’ otherwise.
     This function always succeeds.

 -- C 函数: void* PyBuffer_GetPointer (Py_buffer *view,
          Py_ssize_t *indices)

     Get the memory area pointed to by the `indices' inside the given
     `view'.  `indices' must point to an array of ‘view->ndim’ indices.

 -- C 函数: int PyBuffer_FromContiguous (Py_buffer *view, void *buf,
          Py_ssize_t len, char fort)

     Copy contiguous `len' bytes from `buf' to `view'.  `fort' can be
     ‘'C'’ or ‘'F'’ (for C-style or Fortran-style ordering).  ‘0’ is
     returned on success, ‘-1’ on error.

 -- C 函数: int PyBuffer_ToContiguous (void *buf, Py_buffer *src,
          Py_ssize_t len, char order)

     Copy `len' bytes from `src' to its contiguous representation in
     `buf'.  `order' can be ‘'C'’ or ‘'F'’ or ‘'A'’ (for C-style or
     Fortran-style ordering or either one).  ‘0’ is returned on success,
     ‘-1’ on error.

     如果 `len' != `src->len' 则此函数将报错。

 -- C 函数: void PyBuffer_FillContiguousStrides (int ndims,
          Py_ssize_t *shape, Py_ssize_t *strides, int itemsize,
          char order)

     Fill the `strides' array with byte-strides of a *note contiguous:
     16c5. (C-style if `order' is ‘'C'’ or Fortran-style if `order' is
     ‘'F'’) array of the given shape with the given number of bytes per
     element.

 -- C 函数: int PyBuffer_FillInfo (Py_buffer *view, PyObject *exporter,
          void *buf, Py_ssize_t len, int readonly, int flags)

     处理导出程序的缓冲区请求，该导出程序要暴露大小为 `len' 的 `buf' ，
     并根据 `readonly' 设置可写性。`bug' 被解释为一个无符号字节序列。

     The `flags' argument indicates the request type.  This function
     always fills in `view' as specified by flags, unless `buf' has been
     designated as read-only and *note PyBUF_WRITABLE: 3d27. is set in
     `flags'.

     On success, set ‘view->obj’ to a new reference to `exporter' and
     return 0.  Otherwise, raise ‘PyExc_BufferError’, set ‘view->obj’ to
     ‘NULL’ and return ‘-1’;

     如果此函数用作 *note getbufferproc: 3d1c. 的一部分，则 `exporter' 必
     须设置为导出对象，并且必须在未修改的情况下传递 `flags'。否则，
     `exporter' 必须是 ‘NULL’。


File: python.info,  Node: 旧缓冲协议,  Prev: 缓冲协议,  Up: 抽象对象层

7.7.7 旧缓冲协议
----------------

3.0 版后已移除.

这些函数是 Python 2 中“旧缓冲协议”API 的组成部分。 在 Python 3 中，此协
议已不复存在，但这些函数仍然被公开以便移植 2.x 的代码。 它们被用作 *note
新缓冲协议: 15f7. 的兼容性包装器，但它们并不会在缓冲被导出时向你提供对所
获资源的生命周期控制。

因此，推荐你调用 *note PyObject_GetBuffer(): d2d. (或者配合 *note
PyArg_ParseTuple(): 26b. 函数族使用 ‘y*’ 或 ‘w*’ *note 格式码: 2d1.) 来
获取一个对象的缓冲视图，并在缓冲视图可被释放时调用 *note
PyBuffer_Release(): d5c.。

 -- C 函数: int PyObject_AsCharBuffer (PyObject *obj, const
          char **buffer, Py_ssize_t *buffer_len)

     返回一个指向可用作基于字符的输入的只读内存地址的指针。 `obj' 参数必
     须支持单段字符缓冲接口。 成功时返回 ‘0’，将 `buffer' 设为内存地址并
     将 `buffer_len' 设为缓冲区长度。 出错时返回 ‘-1’ 并设置一个 *note
     TypeError: 193.。

 -- C 函数: int PyObject_AsReadBuffer (PyObject *obj, const
          void **buffer, Py_ssize_t *buffer_len)

     返回一个指向包含任意数据的只读内存地址的指针。 `obj' 参数必须支持单
     段可读缓冲接口。 成功时返回 ‘0’，将 `buffer' 设为内存地址并将
     `buffer_len' 设为缓冲区长度。 出错时返回 ‘-1’ 并设置一个 *note
     TypeError: 193.。

 -- C 函数: int PyObject_CheckReadBuffer (PyObject *o)

     如果 `o' 支持单段可读缓冲接口则返回 ‘1’。 否则返回 ‘0’。 此函数总是
     会成功执行。

     请注意此函数会尝试获取并释放一个缓冲区，并且在调用对应函数期间发生
     的异常会被屏蔽。 要获取错误报告则应改用 *note PyObject_GetBuffer():
     d2d.。

 -- C 函数: int PyObject_AsWriteBuffer (PyObject *obj, void **buffer,
          Py_ssize_t *buffer_len)

     返回一个指向可写内存地址的指针。 `obj' 必须支持单段字符缓冲接口。 成
     功时返回 ‘0’，将 `buffer' 设为内存地址并将 `buffer_len' 设为缓冲区
     长度。 出错时返回 ‘-1’ 并设置一个 *note TypeError: 193.。


File: python.info,  Node: 具体的对象层,  Next: 初始化，终结和线程,  Prev: 抽象对象层,  Up: Python/C API 参考手册

7.8 具体的对象层
================

本章中的函数特定于某些 Python 对象类型。 将错误类型的对象传递给它们并不
是一个好主意；如果您从 Python 程序接收到一个对象，但不确定它是否具有正确
的类型，则必须首先执行类型检查；例如，要检查对象是否为字典，请使用 *note
PyDict_Check(): 3d59.。 本章的结构类似于 Python 对象类型的“家族树”。

     警告: 虽然本章所描述的函数会仔细检查传入对象的类型，但是其中许多函
     数不会检查传入的对象是否为 ‘NULL’。 允许传入 ‘NULL’ 可能导致内存访
     问冲突和解释器的立即终止。

* Menu:

* 基本对象::
* 数值对象::
* 序列对象::
* 容器对象::
* 函数对象: 函数对象<2>.
* 其他对象: 其他对象<2>.


File: python.info,  Node: 基本对象,  Next: 数值对象,  Up: 具体的对象层

7.8.1 基本对象
--------------

本节描述Python类型对象和单一实例对象 象None。

* Menu:

* 类型对象: 类型对象<2>.
* None 对象::


File: python.info,  Node: 类型对象<2>,  Next: None 对象,  Up: 基本对象

7.8.1.1 类型对象
................

 -- C 类型: PyTypeObject

     对象的 C 结构用于描述 built-in 类型。

 -- C 变量: PyObject* PyType_Type

     这是属于 type 对象的 type object，它在 Python 层面和 *note type:
     611. 是相同的对象。

 -- C 函数: int PyType_Check (PyObject *o)

     如果对象 `o' 是一个类型对象，包括继承于标准类型对象的类型实例，返回
     真。在其它所有情况下返回假。

 -- C 函数: int PyType_CheckExact (PyObject *o)

     如果对象 `o' 是一个类型对象，但不是标准类型对象的子类型时，返回真。
     在其它所有情况下返回假。

 -- C 函数: unsigned int PyType_ClearCache ()

     Clear the internal lookup cache.  Return the current version tag.

 -- C 函数: unsigned long PyType_GetFlags (PyTypeObject* type)

     Return the *note tp_flags: 3d64. member of `type'.  This function
     is primarily meant for use with ‘Py_LIMITED_API’; the individual
     flag bits are guaranteed to be stable across Python releases, but
     access to *note tp_flags: 3d64. itself is not part of the limited
     API.

     3.2 新版功能.

     在 3.4 版更改: The return type is now ‘unsigned long’ rather than
     ‘long’.

 -- C 函数: void PyType_Modified (PyTypeObject *type)

     Invalidate the internal lookup cache for the type and all of its
     subtypes.  This function must be called after any manual
     modification of the attributes or base classes of the type.

 -- C 函数: int PyType_HasFeature (PyTypeObject *o, int feature)

     Return true if the type object `o' sets the feature `feature'.
     Type features are denoted by single bit flags.

 -- C 函数: int PyType_IS_GC (PyTypeObject *o)

     Return true if the type object includes support for the cycle
     detector; this tests the type flag *note Py_TPFLAGS_HAVE_GC: 3b51.

 -- C 函数: int PyType_IsSubtype (PyTypeObject *a, PyTypeObject *b)

     Return true if `a' is a subtype of `b'.

     This function only checks for actual subtypes, which means that
     *note __subclasscheck__(): 1461. is not called on `b'.  Call *note
     PyObject_IsSubclass(): 7a7. to do the same check that *note
     issubclass(): 458. would do.

 -- C 函数: PyObject* PyType_GenericAlloc (PyTypeObject *type,
          Py_ssize_t nitems)
     `Return value: New reference.'  Generic handler for the *note
     tp_alloc: 3b44. slot of a type object.  Use Python’s default memory
     allocation mechanism to allocate a new instance and initialize all
     its contents to ‘NULL’.

 -- C 函数: PyObject* PyType_GenericNew (PyTypeObject *type,
          PyObject *args, PyObject *kwds)
     `Return value: New reference.'  Generic handler for the *note
     tp_new: 3b3f. slot of a type object.  Create a new instance using
     the type’s *note tp_alloc: 3b44. slot.

 -- C 函数: int PyType_Ready (PyTypeObject *type)

     Finalize a type object.  This should be called on all type objects
     to finish their initialization.  This function is responsible for
     adding inherited slots from a type’s base class.  Return ‘0’ on
     success, or return ‘-1’ and sets an exception on error.

 -- C 函数: void* PyType_GetSlot (PyTypeObject *type, int slot)

     Return the function pointer stored in the given slot.  If the
     result is ‘NULL’, this indicates that either the slot is ‘NULL’, or
     that the function was called with invalid parameters.  Callers will
     typically cast the result pointer into the appropriate function
     type.

     See ‘PyType_Slot.slot’ for possible values of the `slot' argument.

     An exception is raised if `type' is not a heap type.

     3.4 新版功能.

* Menu:

* Creating Heap-Allocated Types::


File: python.info,  Node: Creating Heap-Allocated Types,  Up: 类型对象<2>

7.8.1.2 Creating Heap-Allocated Types
.....................................

The following functions and structs are used to create *note heap types:
3d6a.

 -- C 函数: PyObject* PyType_FromSpecWithBases (PyType_Spec *spec,
          PyObject *bases)
     `Return value: New reference.'  Creates and returns a heap type
     object from the `spec' (*note Py_TPFLAGS_HEAPTYPE: 3d6c.).

     If `bases' is a tuple, the created heap type contains all types
     contained in it as base types.

     If `bases' is ‘NULL’, the `Py_tp_bases' slot is used instead.  If
     that also is ‘NULL’, the `Py_tp_base' slot is used instead.  If
     that also is ‘NULL’, the new type derives from *note object: 2b1.

     This function calls *note PyType_Ready(): 3b45. on the new type.

     3.3 新版功能.

 -- C 函数: PyObject* PyType_FromSpec (PyType_Spec *spec)
     `Return value: New reference.'  Equivalent to
     ‘PyType_FromSpecWithBases(spec, NULL)’.

 -- C 类型: PyType_Spec

     Structure defining a type’s behavior.

      -- C 成员: const char* PyType_Spec.name

          Name of the type, used to set *note PyTypeObject.tp_name:
          3b5e.

      -- C 成员: int PyType_Spec.basicsize

      -- C 成员: int PyType_Spec.itemsize

          Size of the instance in bytes, used to set *note
          PyTypeObject.tp_basicsize: 3b3c. and *note
          PyTypeObject.tp_itemsize: 3b3b.

      -- C 成员: int PyType_Spec.flags

          Type flags, used to set *note PyTypeObject.tp_flags: 3d64.

          If the ‘Py_TPFLAGS_HEAPTYPE’ flag is not set, *note
          PyType_FromSpecWithBases(): 3d6b. sets it automatically.

      -- C 成员: PyType_Slot *PyType_Spec.slots

          Array of *note PyType_Slot: 3d73. structures.  Terminated by
          the special slot value ‘{0, NULL}’.

 -- C 类型: PyType_Slot

     Structure defining optional functionality of a type, containing a
     slot ID and a value pointer.

      -- C 成员: int PyType_Slot.slot

          A slot ID.

          Slot IDs are named like the field names of the structures
          *note PyTypeObject: 2d7, *note PyNumberMethods: d89, *note
          PySequenceMethods: 3b6c, *note PyMappingMethods: 3b6d. and
          *note PyAsyncMethods: 3d75. with an added ‘Py_’ prefix.  For
          example, use:

             * ‘Py_tp_dealloc’ to set *note PyTypeObject.tp_dealloc:
               3b42.

             * ‘Py_nb_add’ to set *note PyNumberMethods.nb_add: 3d76.

             * ‘Py_sq_length’ to set *note PySequenceMethods.sq_length:
               3d77.

          The following fields cannot be set using *note PyType_Spec:
          3d6d. and *note PyType_Slot: 3d73.:

             * *note tp_dict: 3d78.

             * *note tp_mro: 3d79.

             * *note tp_cache: 3d7a.

             * *note tp_subclasses: 3d7b.

             * *note tp_weaklist: 3d7c.

             * ‘tp_print’

             * *note tp_weaklistoffset: 3b71.

             * *note tp_dictoffset: 3d7d.

             * *note bf_getbuffer: 3d7e.

             * *note bf_releasebuffer: 3c7f.

          Setting ‘Py_tp_bases’ or ‘Py_tp_base’ may be problematic on
          some platforms.  To avoid issues, use the `bases' argument of
          ‘PyType_FromSpecWithBases()’ instead.

      -- C 成员: void *PyType_Slot.pfunc

          The desired value of the slot.  In most cases, this is a
          pointer to a function.

          May not be ‘NULL’.


File: python.info,  Node: None 对象,  Prev: 类型对象<2>,  Up: 基本对象

7.8.1.3 ‘None’ 对象
...................

请注意， ‘None’ 的 *note PyTypeObject: 2d7. 不会直接在 Python / C API 中
公开。 由于 ‘None’ 是单例，测试对象标识（在C中使用 ‘==’ ）就足够了。 由
于同样的原因，没有 ‘PyNone_Check()’ 函数。

 -- C 变量: PyObject* Py_None

     Python ‘None’ 对象，表示缺乏值。 这个对象没有方法。 它需要像引用计
     数一样处理任何其他对象。

 -- C 宏: Py_RETURN_NONE

     正确处理来自C函数内的 *note Py_None: 3b07. 返回（也就是说，增加
     ‘None’ 的引用计数并返回它。）


File: python.info,  Node: 数值对象,  Next: 序列对象,  Prev: 基本对象,  Up: 具体的对象层

7.8.2 数值对象
--------------

* Menu:

* 整数型对象::
* 布尔对象::
* 浮点数对象::
* 复数对象::


File: python.info,  Node: 整数型对象,  Next: 布尔对象,  Up: 数值对象

7.8.2.1 整数型对象
..................

所有整数都使用以任意大小的长整数对象表示。

在出错时，大多数 ‘PyLong_As*’ API返回 ‘(返回值类型)-1’ ，无法与一般的数
字区分开来。请使用 *note PyErr_Occurred(): 3b02. 来区分。

 -- C 类型: PyLongObject

     表示 Python 整数对象的 *note PyObject: 4c2. 子类型。

 -- C 变量: PyTypeObject PyLong_Type

     这个 *note PyTypeObject: 2d7. 的实例表示 Python 的整数类型。与
     Python层中的 *note int: 185. 相同。

 -- C 函数: int PyLong_Check (PyObject *p)

     如果参数是 *note PyLongObject: 3d88. 或 *note PyLongObject: 3d88. 的
     子类型，返回 true 。

 -- C 函数: int PyLong_CheckExact (PyObject *p)

     如果参数是 *note PyLongObject: 3d88. 但不是 *note PyLongObject:
     3d88. 的子类型，返回 true。

 -- C 函数: PyObject* PyLong_FromLong (long v)
     `Return value: New reference.' 由 `v' 返回一个新的 *note
     PyLongObject: 3d88. 对象，失败时返回 ‘NULL’ 。

     The current implementation keeps an array of integer objects for
     all integers between ‘-5’ and ‘256’, when you create an int in that
     range you actually just get back a reference to the existing
     object.  So it should be possible to change the value of ‘1’.  I
     suspect the behaviour of Python in this case is undefined.  :-)

 -- C 函数: PyObject* PyLong_FromUnsignedLong (unsigned long v)
     `Return value: New reference.' 由 C ‘unsigned long’ 类型返回一个新
     的 *note PyLongObject: 3d88. 对象，失败时返回 ‘NULL’ 。

 -- C 函数: PyObject* PyLong_FromSsize_t (Py_ssize_t v)
     `Return value: New reference.' 从 C ‘Py_ssize_t’ 类型返回一个新的
     *note PyLongObject: 3d88. 对象，如果失败则返回‘‘NULL‘‘。

 -- C 函数: PyObject* PyLong_FromSize_t (size_t v)
     `Return value: New reference.' 从 C ‘size_t’ 返回一个新的 *note
     PyLongObject: 3d88. 对象，如果失败则返回‘‘NULL‘‘。

 -- C 函数: PyObject* PyLong_FromLongLong (long long v)
     `Return value: New reference.' 从 C ‘long long’ 返回一个新的 *note
     PyLongObject: 3d88. 对象，失败时返回‘‘NULL‘‘。

 -- C 函数: PyObject* PyLong_FromUnsignedLongLong (unsigned long long v)
     `Return value: New reference.' 从 C ‘unsigned long long’ 返回一个新
     的 *note PyLongObject: 3d88. 对象，失败时返回‘‘NULL‘‘。

 -- C 函数: PyObject* PyLong_FromDouble (double v)
     `Return value: New reference.' 从 `v' 的整数部分返回一个新的 *note
     PyLongObject: 3d88. 对象，如果失败则返回‘‘NULL‘‘。

 -- C 函数: PyObject* PyLong_FromString (const char *str, char **pend,
          int base)
     `Return value: New reference.' 根据 `str' 字符串值返回一个新的
     *note PyLongObject: 3d88. ，`base' 指定基数。如果 `pend' 不是
     ‘NULL’ ， `/*pend' 将指向 `str' 中表示这个数字部分的后面的第一个字
     符。如果 `base' 是 ‘0’ ， `str' 将使用 *note 整型数字面值: 1412. 定
     义来解释；在这种情况下，一个非零的十进制数中的前导零会引发一个
     *note ValueError: 1fc. 。如果 `base' 不是 ‘0’ ，它必须在 ‘2’ 和‘
     ‘36‘’ 之间，包括2和36。基数说明符后以及数字之间的前导空格、单下划线
     将被忽略。如果没有数字，将引发 *note ValueError: 1fc.。

 -- C 函数: PyObject* PyLong_FromUnicode (Py_UNICODE *u,
          Py_ssize_t length, int base)
     `Return value: New reference.' 将 Unicode 数字序列转换为 Python 整
     数值。

     Deprecated since version 3.3, will be removed in version 3.10: 旧的
     *note Py_UNICODE: af6. API的一部分;请迁移到使用 *note
     PyLong_FromUnicodeObject(): 3d94. 。

 -- C 函数: PyObject* PyLong_FromUnicodeObject (PyObject *u, int base)
     `Return value: New reference.' 将字符串 `u' 中的 Unicode 数字序列转
     换为 Python 整数值。

     3.3 新版功能.

 -- C 函数: PyObject* PyLong_FromVoidPtr (void *p)
     `Return value: New reference.' 从指针 `p' 创建一个 Python 整数。可
     以使用 *note PyLong_AsVoidPtr(): 3d96. 返回的指针值。

 -- C 函数: long PyLong_AsLong (PyObject *obj)

     返回 `obj' 的 C ‘long’ 表达方式。 如果 `obj' 不是 *note
     PyLongObject: 3d88. 的实例，先调用它的 *note __index__(): 18b. 或
     *note __int__(): 18c. 方法(如果有)将其转换为 *note PyLongObject:
     3d88. 。

     如果 `obj' 的值溢出了 ‘long’ 的范围，会抛出 *note OverflowError:
     968.。

     发生错误时返回 ‘-1’ 。使用 *note PyErr_Occurred(): 3b02. 来消歧义。

     在 3.8 版更改: 如果可用将使用 *note __index__(): 18b.。

     3.8 版后已移除: *note __int__(): 18c. 已被弃用。

 -- C 函数: long PyLong_AsLongAndOverflow (PyObject *obj, int *overflow)

     返回 `obj' 的 C ‘long’ 表达方式。 如果 `obj' 不是 *note
     PyLongObject: 3d88. 的实例，先调用它的 *note __index__(): 18b. 或
     *note __int__(): 18c. 方法(如果有)将其转换为 *note PyLongObject:
     3d88. 。

     If the value of `obj' is greater than ‘LONG_MAX’ or less than
     ‘LONG_MIN’, set `*overflow' to ‘1’ or ‘-1’, respectively, and
     return ‘-1’; otherwise, set `*overflow' to ‘0’.  If any other
     exception occurs set `*overflow' to ‘0’ and return ‘-1’ as usual.

     发生错误时返回 ‘-1’ 。使用 *note PyErr_Occurred(): 3b02. 来消歧义。

     在 3.8 版更改: 如果可用将使用 *note __index__(): 18b.。

     3.8 版后已移除: *note __int__(): 18c. 已被弃用。

 -- C 函数: long long PyLong_AsLongLong (PyObject *obj)

     Return a C ‘long long’ representation of `obj'.  If `obj' is not an
     instance of *note PyLongObject: 3d88, first call its *note
     __index__(): 18b. or *note __int__(): 18c. method (if present) to
     convert it to a *note PyLongObject: 3d88.

     如果 `obj' 值超出 ‘long long’ ，触发 *note OverflowError: 968.

     发生错误时返回 ‘-1’ 。使用 *note PyErr_Occurred(): 3b02. 来消歧义。

     在 3.8 版更改: 如果可用将使用 *note __index__(): 18b.。

     3.8 版后已移除: *note __int__(): 18c. 已被弃用。

 -- C 函数: long long PyLong_AsLongLongAndOverflow (PyObject *obj,
          int *overflow)

     Return a C ‘long long’ representation of `obj'.  If `obj' is not an
     instance of *note PyLongObject: 3d88, first call its *note
     __index__(): 18b. or *note __int__(): 18c. method (if present) to
     convert it to a *note PyLongObject: 3d88.

     If the value of `obj' is greater than ‘PY_LLONG_MAX’ or less than
     ‘PY_LLONG_MIN’, set `*overflow' to ‘1’ or ‘-1’, respectively, and
     return ‘-1’; otherwise, set `*overflow' to ‘0’.  If any other
     exception occurs set `*overflow' to ‘0’ and return ‘-1’ as usual.

     发生错误时返回 ‘-1’ 。使用 *note PyErr_Occurred(): 3b02. 来消歧义。

     3.2 新版功能.

     在 3.8 版更改: 如果可用将使用 *note __index__(): 18b.。

     3.8 版后已移除: *note __int__(): 18c. 已被弃用。

 -- C 函数: Py_ssize_t PyLong_AsSsize_t (PyObject *pylong)

     Return a C ‘Py_ssize_t’ representation of `pylong'.  `pylong' must
     be an instance of *note PyLongObject: 3d88.

     Raise *note OverflowError: 968. if the value of `pylong' is out of
     range for a ‘Py_ssize_t’.

     发生错误时返回 ‘-1’ 。使用 *note PyErr_Occurred(): 3b02. 来消歧义。

 -- C 函数: unsigned long PyLong_AsUnsignedLong (PyObject *pylong)

     Return a C ‘unsigned long’ representation of `pylong'.  `pylong'
     must be an instance of *note PyLongObject: 3d88.

     Raise *note OverflowError: 968. if the value of `pylong' is out of
     range for a ‘unsigned long’.

     Returns ‘(unsigned long)-1’ on error.  Use *note PyErr_Occurred():
     3b02. to disambiguate.

 -- C 函数: size_t PyLong_AsSize_t (PyObject *pylong)

     Return a C ‘size_t’ representation of `pylong'.  `pylong' must be
     an instance of *note PyLongObject: 3d88.

     Raise *note OverflowError: 968. if the value of `pylong' is out of
     range for a ‘size_t’.

     Returns ‘(size_t)-1’ on error.  Use *note PyErr_Occurred(): 3b02.
     to disambiguate.

 -- C 函数: unsigned long long PyLong_AsUnsignedLongLong
          (PyObject *pylong)

     Return a C ‘unsigned long long’ representation of `pylong'.
     `pylong' must be an instance of *note PyLongObject: 3d88.

     Raise *note OverflowError: 968. if the value of `pylong' is out of
     range for an ‘unsigned long long’.

     Returns ‘(unsigned long long)-1’ on error.  Use *note
     PyErr_Occurred(): 3b02. to disambiguate.

     在 3.1 版更改: A negative `pylong' now raises *note OverflowError:
     968, not *note TypeError: 193.

 -- C 函数: unsigned long PyLong_AsUnsignedLongMask (PyObject *obj)

     Return a C ‘unsigned long’ representation of `obj'.  If `obj' is
     not an instance of *note PyLongObject: 3d88, first call its *note
     __index__(): 18b. or *note __int__(): 18c. method (if present) to
     convert it to a *note PyLongObject: 3d88.

     If the value of `obj' is out of range for an ‘unsigned long’,
     return the reduction of that value modulo ‘ULONG_MAX + 1’.

     Returns ‘(unsigned long)-1’ on error.  Use *note PyErr_Occurred():
     3b02. to disambiguate.

     在 3.8 版更改: 如果可用将使用 *note __index__(): 18b.。

     3.8 版后已移除: *note __int__(): 18c. 已被弃用。

 -- C 函数: unsigned long long PyLong_AsUnsignedLongLongMask
          (PyObject *obj)

     Return a C ‘unsigned long long’ representation of `obj'.  If `obj'
     is not an instance of *note PyLongObject: 3d88, first call its
     *note __index__(): 18b. or *note __int__(): 18c. method (if
     present) to convert it to a *note PyLongObject: 3d88.

     If the value of `obj' is out of range for an ‘unsigned long long’,
     return the reduction of that value modulo ‘PY_ULLONG_MAX + 1’.

     Returns ‘(unsigned long long)-1’ on error.  Use *note
     PyErr_Occurred(): 3b02. to disambiguate.

     在 3.8 版更改: 如果可用将使用 *note __index__(): 18b.。

     3.8 版后已移除: *note __int__(): 18c. 已被弃用。

 -- C 函数: double PyLong_AsDouble (PyObject *pylong)

     Return a C ‘double’ representation of `pylong'.  `pylong' must be
     an instance of *note PyLongObject: 3d88.

     Raise *note OverflowError: 968. if the value of `pylong' is out of
     range for a ‘double’.

     Returns ‘-1.0’ on error.  Use *note PyErr_Occurred(): 3b02. to
     disambiguate.

 -- C 函数: void* PyLong_AsVoidPtr (PyObject *pylong)

     Convert a Python integer `pylong' to a C ‘void’ pointer.  If
     `pylong' cannot be converted, an *note OverflowError: 968. will be
     raised.  This is only assured to produce a usable ‘void’ pointer
     for values created with *note PyLong_FromVoidPtr(): 3d95.

     Returns ‘NULL’ on error.  Use *note PyErr_Occurred(): 3b02. to
     disambiguate.


File: python.info,  Node: 布尔对象,  Next: 浮点数对象,  Prev: 整数型对象,  Up: 数值对象

7.8.2.2 布尔对象
................

Python 中的布尔值是作为整数的子类实现的。只有 ‘Py_False’ 和 ‘Py_True’ 两
个布尔值。因此，正常的创建和删除功能不适用于布尔值。但是，下列宏可用。

 -- C 函数: int PyBool_Check (PyObject *o)

     如果 `o' 是 ‘PyBool_Type’ 类型，则返回true。

 -- C 变量: PyObject* Py_False

     Python的‘‘False‘‘对象。该对象没有任何方法。它应该象其它使用引用计数
     管理的对象一样使用。

 -- C 变量: PyObject* Py_True

     Python的‘‘True‘‘对象。该对象没有任何方法。它应该象其它使用引用计数
     管理的对象一样使用。

 -- C 宏: Py_RETURN_FALSE

     从函数返回 ‘Py_False’ 时，需要增加它的引用计数。

 -- C 宏: Py_RETURN_TRUE

     从函数返回 ‘Py_True’ 时，需要增加它的引用计数。

 -- C 函数: PyObject* PyBool_FromLong (long v)
     `Return value: New reference.' 根据 `v' 的实际值，返回一个
     ‘Py_True’ 或者 ‘Py_False’ 的新引用。


File: python.info,  Node: 浮点数对象,  Next: 复数对象,  Prev: 布尔对象,  Up: 数值对象

7.8.2.3 浮点数对象
..................

 -- C 类型: PyFloatObject

     这个C类型 *note PyObject: 4c2. 的子类型代表一个Python浮点数对象。

 -- C 变量: PyTypeObject PyFloat_Type

     这是个属于C类型 *note PyTypeObject: 2d7. 的代表Python浮点类型的实例
     。在Python层面的类型 *note float: 188. 是同一个对象。

 -- C 函数: int PyFloat_Check (PyObject *p)

     当他的参数是一个C类型 *note PyFloatObject: 3da7. 或者是C类型 *note
     PyFloatObject: 3da7. 的子类型时，返回真。

 -- C 函数: int PyFloat_CheckExact (PyObject *p)

     当他的参数是一个C类型 *note PyFloatObject: 3da7. 但不是C类型 *note
     PyFloatObject: 3da7. 的子类型时，返回真。

 -- C 函数: PyObject* PyFloat_FromString (PyObject *str)
     `Return value: New reference.' 根据字符串 `str' 的值创建一个 *note
     PyFloatObject: 3da7.，失败时返回 ‘NULL’。

 -- C 函数: PyObject* PyFloat_FromDouble (double v)
     `Return value: New reference.' 根据 `v' 创建一个 *note
     PyFloatObject: 3da7. 对象，失败时返回 ‘NULL’。

 -- C 函数: double PyFloat_AsDouble (PyObject *pyfloat)

     返回一个 C ‘double’ 代表 `pyfloat' 的内容。 如果 `pyfloat' 不是一个
     Python 浮点数对象但是具有 *note __float__(): 18d. 方法，此方法将首
     先被调用，将 `pyfloat' 转换成一个数点数。 如果 ‘__float__()’ 未定义
     则将回退至 *note __index__(): 18b.。 如果失败，此方法将返回 ‘-1.0’，
     因此开发者应当调用 *note PyErr_Occurred(): 3b02. 来检查错误。

     在 3.8 版更改: 如果可用将使用 *note __index__(): 18b.。

 -- C 函数: double PyFloat_AS_DOUBLE (PyObject *pyfloat)

     返回一个 `pyfloat' 内容的 C ‘double’ 表示，但没有错误检查。

 -- C 函数: PyObject* PyFloat_GetInfo (void)
     `Return value: New reference.' 返回一个 structseq 实例，其中包含有
     关 float 的精度、最小值和最大值的信息。 它是头文件 ‘float.h’ 的一个
     简单包装。

 -- C 函数: double PyFloat_GetMax ()

     返回最大可表示的有限浮点数 `DBL_MAX' 为 C ‘double’ 。

 -- C 函数: double PyFloat_GetMin ()

     返回最小可表示归一化正浮点数 `DBL_MIN' 为 C ‘double’ 。

 -- C 函数: int PyFloat_ClearFreeList ()

     清空浮点数释放列表。 返回无法释放的项目数。


File: python.info,  Node: 复数对象,  Prev: 浮点数对象,  Up: 数值对象

7.8.2.4 复数对象
................

从C API看，Python的复数对象由两个不同的部分实现：一个是在Python程序使用
的Python对象，另外的是一个代表真正复数值的C结构体。API提供了函数共同操作
两者。

* Menu:

* 表示复数的C结构体::
* 表示复数的Python对象::


File: python.info,  Node: 表示复数的C结构体,  Next: 表示复数的Python对象,  Up: 复数对象

7.8.2.5 表示复数的C结构体
.........................

需要注意的是接受这些结构体的作为参数并当做结果返回的函数，都是传递“值”而
不是引用指针。此规则适用于整个API。

 -- C 类型: Py_complex

     这是一个对应Python复数对象的值部分的C结构体。绝大部分处理复数对象的
     函数都用这类型的结构体作为输入或者输出值，它可近似地定义为：

          typedef struct {
             double real;
             double imag;
          } Py_complex;

 -- C 函数: Py_complex _Py_c_sum (Py_complex left, Py_complex right)

     返回两个复数的和，用 C 类型 *note Py_complex: 3c81. 表示。

 -- C 函数: Py_complex _Py_c_diff (Py_complex left, Py_complex right)

     返回两个复数的差，用 C 类型 *note Py_complex: 3c81. 表示。

 -- C 函数: Py_complex _Py_c_neg (Py_complex complex)

     返回复数 `complex' 的负值，用 C 类型 *note Py_complex: 3c81. 表示。

 -- C 函数: Py_complex _Py_c_prod (Py_complex left, Py_complex right)

     返回两个复数的乘积，用 C 类型 *note Py_complex: 3c81. 表示。

 -- C 函数: Py_complex _Py_c_quot (Py_complex dividend,
          Py_complex divisor)

     返回两个复数的商，用 C 类型 *note Py_complex: 3c81. 表示。

     如果 `divisor' 为空，这个方法返回零并设置 ‘errno’ 为 ‘EDOM’。

 -- C 函数: Py_complex _Py_c_pow (Py_complex num, Py_complex exp)

     返回 `num' 的 `exp' 次幂，用 C 类型 *note Py_complex: 3c81. 表示。

     如果 `num' 为空且 `exp' 不是正实数，这个方法返回零并设置 ‘errno’ 为
     ‘EDOM’。


File: python.info,  Node: 表示复数的Python对象,  Prev: 表示复数的C结构体,  Up: 复数对象

7.8.2.6 表示复数的Python对象
............................

 -- C 类型: PyComplexObject

     这个C类型 *note PyObject: 4c2. 的子类型代表一个 Python 复数对象。

 -- C 变量: PyTypeObject PyComplex_Type

     这是个属于 *note PyTypeObject: 2d7. 的代表Python复数类型的实例。在
     Python层面的类型 *note complex: 18a. 是同一个对象。

 -- C 函数: int PyComplex_Check (PyObject *p)

     如果它的变量是一个C类型 *note PyComplexObject: 3dba. 或者是C类型
     *note PyComplexObject: 3dba. 的子类型，返回真。

 -- C 函数: int PyComplex_CheckExact (PyObject *p)

     如果它的参数是一个C类型 *note PyComplexObject: 3dba. 但不是C类型
     *note PyComplexObject: 3dba. 的子类型，返回真。

 -- C 函数: PyObject* PyComplex_FromCComplex (Py_complex v)
     `Return value: New reference.' 根据C类型 *note Py_complex: 3c81. 的
     值生成一个新的Python复数对象。

 -- C 函数: PyObject* PyComplex_FromDoubles (double real, double imag)
     `Return value: New reference.' 根据 `real' 和 `imag' 返回一个新的
     C类型 *note PyComplexObject: 3dba. 对象。

 -- C 函数: double PyComplex_RealAsDouble (PyObject *op)

     以C类型 ‘double’ 返回 `op' 的实部。

 -- C 函数: double PyComplex_ImagAsDouble (PyObject *op)

     以C类型 ‘double’ 返回 `op' 的虚部。

 -- C 函数: Py_complex PyComplex_AsCComplex (PyObject *op)

     返回复数 `op' 的C类型 *note Py_complex: 3c81. 值。

     如果 `op' 不是一个 Python 复数对象，但是具有 *note __complex__():
     18e. 方法，此方法将首先被调用，将 `op' 转换为一个 Python 复数对象。
     如果 ‘__complex__()’ 未定义则将回退至 *note __float__(): 18d.，如果
     ‘__float__()’ 未定义则将回退至 *note __index__(): 18b.。 如果失败，
     此方法将返回 ‘-1.0’ 作为实数值。

     在 3.8 版更改: 如果可用将使用 *note __index__(): 18b.。


File: python.info,  Node: 序列对象,  Next: 容器对象,  Prev: 数值对象,  Up: 具体的对象层

7.8.3 序列对象
--------------

序列对象的一般操作在前一章中讨论过;本节介绍Python语言固有的特定类型的序
列对象。

* Menu:

* bytes 对象: bytes 对象<2>.
* 字节数组对象::
* Unicode对象和编码解码器::
* 元组对象::
* 结构序列对象::
* 列表对象::


File: python.info,  Node: bytes 对象<2>,  Next: 字节数组对象,  Up: 序列对象

7.8.3.1 bytes 对象
..................

当期望带一个字节串形参但却带一个非字节串形参被调用时，这些函数会引发
*note TypeError: 193.。

 -- C 类型: PyBytesObject

     这种 *note PyObject: 4c2. 的子类型表示一个 Python 字节对象。

 -- C 变量: PyTypeObject PyBytes_Type

     *note PyTypeObject: 2d7. 的实例代表一个 Python 字节类型，在 Python
     层面它与 *note bytes: 33a. 是相同的对象。

 -- C 函数: int PyBytes_Check (PyObject *o)

     如果对象 `o' 是字节对象或字节类型的子类型的实例，则返回 true。

 -- C 函数: int PyBytes_CheckExact (PyObject *o)

     如果对象 `o' 是字节对象，但不是字节类型子类型的实例，则返回 true。

 -- C 函数: PyObject* PyBytes_FromString (const char *v)
     `Return value: New reference.' 成功时返回一个以字符串 `v' 的副本为
     值的新字节串对象，失败时返回 ‘NULL’。 形参 `v' 不可为 ‘NULL’；它不
     会被检查。

 -- C 函数: PyObject* PyBytes_FromStringAndSize (const char *v,
          Py_ssize_t len)
     `Return value: New reference.' 成功时返回一个以字符串 `v' 的副本为
     值且长度为 `len' 的新字节串对象，失败时返回 ‘NULL’。 如果 `v' 为
     ‘NULL’，则不初始化字节串对象的内容。

 -- C 函数: PyObject* PyBytes_FromFormat (const char *format, ...)
     `Return value: New reference.' 接受一个 C ‘printf()’ 风格的
     `format' 字符串和可变数量的参数，计算结果 Python 字节串对象的大小并
     返回参数值经格式化后的字节串对象。 可变数量的参数必须均为 C 类型并
     且必须恰好与 `format' 字符串中的格式字符相对应。 允许使用下列格式字
     符串:

     格式字符                类型                注释
                                                 
     ---------------------------------------------------------------------------------
                                                 
     ‘%%’                    `不适用'            文字%字符。
                                                 
                                                 
     ‘%c’                    int                 一个字节，被表示为一个 C 语言的整
                                                 型
                                                 
                                                 
     ‘%d’                    int                 相当于 ‘printf("%d")’.  (1)
                                                 
                                                 
     ‘%u’                    unsigned int        相当于 ‘printf("%u")’.  (2)
                                                 
                                                 
     ‘%ld’                   长整型              相当于 ‘printf("%ld")’.  (3)
                                                 
                                                 
     ‘%lu’                   unsigned long       相当于 ‘printf("%lu")’.  (4)
                                                 
                                                 
     ‘%zd’                   Py_ssize_t          相当于 ‘printf("%zd")’.  (5)
                                                 
                                                 
     ‘%zu’                   size_t              相当于 ‘printf("%zu")’.  (6)
                                                 
                                                 
     ‘%i’                    int                 相当于 ‘printf("%i")’.  (7)
                                                 
                                                 
     ‘%x’                    int                 相当于 ‘printf("%x")’.  (8)
                                                 
                                                 
     ‘%s’                    const char*         以 null 为终止符的 C 字符数组。
                                                 
                                                 
     ‘%p’                    const void*         一个 C 指针的十六进制表示形式。 基
                                                 本等价于 ‘printf("%p")’ 但它会确保
                                                 以字面值 ‘0x’ 开头，不论系统平台上
                                                 ‘printf’ 的输出是什么。
                                                 

     无法识别的格式字符会导致将格式字符串的其余所有内容原样复制到结果对
     象，并丢弃所有多余的参数。

 -- C 函数: PyObject* PyBytes_FromFormatV (const char *format,
          va_list vargs)
     `Return value: New reference.' 与 *note PyBytes_FromFormat(): 101b.
     完全相同，除了它需要两个参数。

 -- C 函数: PyObject* PyBytes_FromObject (PyObject *o)
     `Return value: New reference.' 返回字节表示实现缓冲区协议的对象
     *o*。

 -- C 函数: Py_ssize_t PyBytes_Size (PyObject *o)

     返回字节对象*o*中字节的长度。

 -- C 函数: Py_ssize_t PyBytes_GET_SIZE (PyObject *o)

     宏版本的 *note PyBytes_Size(): 3dcc. 但是不带错误检测。

 -- C 函数: char* PyBytes_AsString (PyObject *o)

     返回对应 `o' 的内容的指针。 该指针指向 `o' 的内部缓冲区，其中包含
     ‘len(o) + 1’ 个字节。 缓冲区的最后一个字节总是为空，不论是否存在其
     他空字节。 该数据不可通过任何形式来修改，除非是刚使用
     ‘PyBytes_FromStringAndSize(NULL, size)’ 创建该对象。 它不可被撤销分
     配。 如果 `o' 根本不是一个字节串对象，则 *note PyBytes_AsString():
     3dce. 将返回 ‘NULL’ 并引发 *note TypeError: 193.。

 -- C 函数: char* PyBytes_AS_STRING (PyObject *string)

     宏版本的 *note PyBytes_AsString(): 3dce. 但是不带错误检测。

 -- C 函数: int PyBytes_AsStringAndSize (PyObject *obj, char **buffer,
          Py_ssize_t *length)

     通过输出变量 `buffer' 和 `length' 返回以 null 为终止符的对象 `obj'
     的内容。

     如果 `length' 为 ‘NULL’，字节串对象就不包含嵌入的空字节；如果包含，
     则该函数将返回 ‘-1’ 并引发 *note ValueError: 1fc.。

     该缓冲区指向 `obj' 的内部缓冲，它的末尾包含一个额外的空字节（不算在
     `length' 当中）。 该数据不可通过任何方式来修改，除非是刚使用
     ‘PyBytes_FromStringAndSize(NULL, size)’ 创建该对象。 它不可被撤销分
     配。 如果 `obj' 根本不是一个字节串对象，则 *note
     PyBytes_AsStringAndSize(): 3dd0. 将返回 ‘-1’ 并引发 *note
     TypeError: 193.。

     在 3.5 版更改: 以前，当字节串对象中出现嵌入的空字节时将引发 *note
     TypeError: 193.。

 -- C 函数: void PyBytes_Concat (PyObject **bytes, PyObject *newpart)

     在 `*bytes' 中创建新的字节串对象，其中包含添加到 `bytes' 的
     `newpart' 的内容；调用者将获得新的引用。 对 `bytes' 原值的引用将被
     收回。 如果无法创建新对象，对 `bytes' 的旧引用仍将被丢弃且 `*bytes'
     的值将被设为 ‘NULL’；并将设置适当的异常。

 -- C 函数: void PyBytes_ConcatAndDel (PyObject **bytes,
          PyObject *newpart)

     在 `*bytes' 中创建新的字节串对象，其中包含添加到 `bytes' 的
     `newpart' 的内容。 此版本会减少 `newpart' 的引用计数。

 -- C 函数: int _PyBytes_Resize (PyObject **bytes, Py_ssize_t newsize)

     改变字节串大小的一种方式，即使其为“不可变对象”。 此方式仅用于创建全
     新的字节串对象；如果字节串在代码的其他部分已知则不可使用此方式。 如
     果输入字节串对象的引用计数不为一则调用此函数将报错。 传入一个现有字
     节串对象的地址作为 lvalue（它可能会被写入），并传入希望的新大小。 当
     成功时，`*bytes' 将存放改变大小后的字节串对象并返回 ‘0’；`*bytes' 中
     的地址可能与其输入值不同。 如果重新分配失败，则 `*bytes' 上的原字节
     串对象将被撤销分配，`*bytes' 会被设为 ‘NULL’，同时设置 *note
     MemoryError: efc. 并返回 ‘-1’。

   ---------- Footnotes ----------

   (1) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。

   (2) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。

   (3) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。

   (4) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。

   (5) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。

   (6) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。

   (7) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。

   (8) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。


File: python.info,  Node: 字节数组对象,  Next: Unicode对象和编码解码器,  Prev: bytes 对象<2>,  Up: 序列对象

7.8.3.2 字节数组对象
....................

 -- C 类型: PyByteArrayObject

     这个 *note PyObject: 4c2. 的子类型表示一个 Python 字节数组对象。

 -- C 变量: PyTypeObject PyByteArray_Type

     Python bytearray 类型表示为 *note PyTypeObject: 2d7. 的实例；这与
     Python层面的 *note bytearray: 33b. 是相同的对象。

* Menu:

* 类型检查宏::
* 直接 API 函数::
* 宏::


File: python.info,  Node: 类型检查宏,  Next: 直接 API 函数,  Up: 字节数组对象

7.8.3.3 类型检查宏
..................

 -- C 函数: int PyByteArray_Check (PyObject *o)

     当对象 `o' 是一个字节数组对象而且是一个字节数组类型的子类型实例时，
     返回真。

 -- C 函数: int PyByteArray_CheckExact (PyObject *o)

     当对象 `o' 是一个字节数组对象，但不是一个字节数组类型的子类型实例时
     ，返回真。


File: python.info,  Node: 直接 API 函数,  Next: 宏,  Prev: 类型检查宏,  Up: 字节数组对象

7.8.3.4 直接 API 函数
.....................

 -- C 函数: PyObject* PyByteArray_FromObject (PyObject *o)
     `Return value: New reference.' 根据任何实现了 *note 缓冲区协议:
     15f7. 的对象 `o'，返回一个新的字节数组对象。

 -- C 函数: PyObject* PyByteArray_FromStringAndSize (const char *string,
          Py_ssize_t len)
     `Return value: New reference.' 根据 `string' 及其长度 `len' 创建一
     个新的 bytearray 对象。 当失败时返回 ‘NULL’。

 -- C 函数: PyObject* PyByteArray_Concat (PyObject *a, PyObject *b)
     `Return value: New reference.' 连接字节数组 `a' 和 `b' 并返回一个带
     有结果的新的字节数组。

 -- C 函数: Py_ssize_t PyByteArray_Size (PyObject *bytearray)

     在检查 ‘NULL’ 指针后返回 `bytearray' 的大小。

 -- C 函数: char* PyByteArray_AsString (PyObject *bytearray)

     在检查 ‘NULL’ 指针后返回将 `bytearray' 返回为一个字符数组。 返回的
     数组总是会附加一个额外的空字节。

 -- C 函数: int PyByteArray_Resize (PyObject *bytearray, Py_ssize_t len)

     将 `bytearray' 的内部缓冲区的大小调整为 `len'。


File: python.info,  Node: 宏,  Prev: 直接 API 函数,  Up: 字节数组对象

7.8.3.5 宏
..........

这些宏减低安全性以换取性能，它们不检查指针。

 -- C 函数: char* PyByteArray_AS_STRING (PyObject *bytearray)

     C函数 *note PyByteArray_AsString(): 3dde. 的宏版本。

 -- C 函数: Py_ssize_t PyByteArray_GET_SIZE (PyObject *bytearray)

     C函数 *note PyByteArray_Size(): 3ddd. 的宏版本。


File: python.info,  Node: Unicode对象和编码解码器,  Next: 元组对象,  Prev: 字节数组对象,  Up: 序列对象

7.8.3.6 Unicode对象和编码解码器
...............................

* Menu:

* Unicode对象::
* Built-in Codecs::
* Methods and Slot Functions::


File: python.info,  Node: Unicode对象,  Next: Built-in Codecs,  Up: Unicode对象和编码解码器

7.8.3.7 Unicode对象
...................

自从python3.3中实现了:pep:‘393’ 以来，Unicode对象在内部使用各种表示形式
，以便在保持内存效率的同时处理完整范围的Unicode字符。对于所有代码点都低
于128、256或65536的字符串，有一些特殊情况；否则，代码点必须低于1114112（
这是完整的Unicode范围）。

*note Py_UNICODE*: af6. and UTF-8 representations are created on demand
and cached in the Unicode object.  The *note Py_UNICODE*: af6.
representation is deprecated and inefficient.

Due to the transition between the old APIs and the new APIs, Unicode
objects can internally be in two states depending on how they were
created:

   * "canonical" Unicode objects are all objects created by a
     non-deprecated Unicode API. They use the most efficient
     representation allowed by the implementation.

   * "legacy" Unicode objects have been created through one of the
     deprecated APIs (typically *note PyUnicode_FromUnicode(): af7.) and
     only bear the *note Py_UNICODE*: af6. representation; you will have
     to call *note PyUnicode_READY(): ade. on them before calling any
     other API.

     注解: The "legacy" Unicode object will be removed in Python 3.12
     with deprecated APIs.  All Unicode objects will be "canonical"
     since then.  See PEP 623(1) for more information.

* Menu:

* Unicode类型::
* Unicode字符属性::
* Creating and accessing Unicode strings::
* Deprecated Py_UNICODE APIs::
* Locale Encoding::
* File System Encoding::
* wchar_t Support::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0623


File: python.info,  Node: Unicode类型,  Next: Unicode字符属性,  Up: Unicode对象

7.8.3.8 Unicode类型
...................

These are the basic Unicode object types used for the Unicode
implementation in Python:

 -- C 类型: Py_UCS4
 -- C 类型: Py_UCS2
 -- C 类型: Py_UCS1

     These types are typedefs for unsigned integer types wide enough to
     contain characters of 32 bits, 16 bits and 8 bits, respectively.
     When dealing with single Unicode characters, use *note Py_UCS4:
     adb.

     3.3 新版功能.

 -- C 类型: Py_UNICODE

     This is a typedef of ‘wchar_t’, which is a 16-bit type or 32-bit
     type depending on the platform.

     在 3.3 版更改: In previous versions, this was a 16-bit type or a
     32-bit type depending on whether you selected a "narrow" or "wide"
     Unicode version of Python at build time.

 -- C 类型: PyASCIIObject
 -- C 类型: PyCompactUnicodeObject
 -- C 类型: PyUnicodeObject

     These subtypes of *note PyObject: 4c2. represent a Python Unicode
     object.  In almost all cases, they shouldn’t be used directly,
     since all API functions that deal with Unicode objects take and
     return *note PyObject: 4c2. pointers.

     3.3 新版功能.

 -- C 变量: PyTypeObject PyUnicode_Type

     This instance of *note PyTypeObject: 2d7. represents the Python
     Unicode type.  It is exposed to Python code as ‘str’.

The following APIs are really C macros and can be used to do fast checks
and to access internal read-only data of Unicode objects:

 -- C 函数: int PyUnicode_Check (PyObject *o)

     Return true if the object `o' is a Unicode object or an instance of
     a Unicode subtype.

 -- C 函数: int PyUnicode_CheckExact (PyObject *o)

     Return true if the object `o' is a Unicode object, but not an
     instance of a subtype.

 -- C 函数: int PyUnicode_READY (PyObject *o)

     Ensure the string object `o' is in the "canonical" representation.
     This is required before using any of the access macros described
     below.

     Returns ‘0’ on success and ‘-1’ with an exception set on failure,
     which in particular happens if memory allocation fails.

     3.3 新版功能.

     Deprecated since version 3.10, will be removed in version 3.12:
     This API will be removed with *note PyUnicode_FromUnicode(): af7.

 -- C 函数: Py_ssize_t PyUnicode_GET_LENGTH (PyObject *o)

     Return the length of the Unicode string, in code points.  `o' has
     to be a Unicode object in the "canonical" representation (not
     checked).

     3.3 新版功能.

 -- C 函数: Py_UCS1* PyUnicode_1BYTE_DATA (PyObject *o)
 -- C 函数: Py_UCS2* PyUnicode_2BYTE_DATA (PyObject *o)
 -- C 函数: Py_UCS4* PyUnicode_4BYTE_DATA (PyObject *o)

     Return a pointer to the canonical representation cast to UCS1, UCS2
     or UCS4 integer types for direct character access.  No checks are
     performed if the canonical representation has the correct character
     size; use *note PyUnicode_KIND(): ae6. to select the right macro.
     Make sure *note PyUnicode_READY(): ade. has been called before
     accessing this.

     3.3 新版功能.

 -- C 宏: PyUnicode_WCHAR_KIND
 -- C 宏: PyUnicode_1BYTE_KIND
 -- C 宏: PyUnicode_2BYTE_KIND
 -- C 宏: PyUnicode_4BYTE_KIND

     Return values of the *note PyUnicode_KIND(): ae6. macro.

     3.3 新版功能.

     Deprecated since version 3.10, will be removed in version 3.12:
     ‘PyUnicode_WCHAR_KIND’ is deprecated.

 -- C 函数: int PyUnicode_KIND (PyObject *o)

     Return one of the PyUnicode kind constants (see above) that
     indicate how many bytes per character this Unicode object uses to
     store its data.  `o' has to be a Unicode object in the "canonical"
     representation (not checked).

     3.3 新版功能.

 -- C 函数: void* PyUnicode_DATA (PyObject *o)

     Return a void pointer to the raw Unicode buffer.  `o' has to be a
     Unicode object in the "canonical" representation (not checked).

     3.3 新版功能.

 -- C 函数: void PyUnicode_WRITE (int kind, void *data,
          Py_ssize_t index, Py_UCS4 value)

     Write into a canonical representation `data' (as obtained with
     *note PyUnicode_DATA(): ae2.).  This macro does not do any sanity
     checks and is intended for usage in loops.  The caller should cache
     the `kind' value and `data' pointer as obtained from other macro
     calls.  `index' is the index in the string (starts at 0) and
     `value' is the new code point value which should be written to that
     location.

     3.3 新版功能.

 -- C 函数: Py_UCS4 PyUnicode_READ (int kind, void *data,
          Py_ssize_t index)

     Read a code point from a canonical representation `data' (as
     obtained with *note PyUnicode_DATA(): ae2.).  No checks or ready
     calls are performed.

     3.3 新版功能.

 -- C 函数: Py_UCS4 PyUnicode_READ_CHAR (PyObject *o, Py_ssize_t index)

     Read a character from a Unicode object `o', which must be in the
     "canonical" representation.  This is less efficient than *note
     PyUnicode_READ(): aeb. if you do multiple consecutive reads.

     3.3 新版功能.

 -- C 宏: PyUnicode_MAX_CHAR_VALUE (o)

     Return the maximum code point that is suitable for creating another
     string based on `o', which must be in the "canonical"
     representation.  This is always an approximation but more efficient
     than iterating over the string.

     3.3 新版功能.

 -- C 函数: int PyUnicode_ClearFreeList ()

     清空释放列表。 返回所释放的条目数。

 -- C 函数: Py_ssize_t PyUnicode_GET_SIZE (PyObject *o)

     Return the size of the deprecated *note Py_UNICODE: af6.
     representation, in code units (this includes surrogate pairs as 2
     units).  `o' has to be a Unicode object (not checked).

     Deprecated since version 3.3, will be removed in version 3.12: Part
     of the old-style Unicode API, please migrate to using *note
     PyUnicode_GET_LENGTH(): ad4.

 -- C 函数: Py_ssize_t PyUnicode_GET_DATA_SIZE (PyObject *o)

     Return the size of the deprecated *note Py_UNICODE: af6.
     representation in bytes.  `o' has to be a Unicode object (not
     checked).

     Deprecated since version 3.3, will be removed in version 3.12: Part
     of the old-style Unicode API, please migrate to using *note
     PyUnicode_GET_LENGTH(): ad4.

 -- C 函数: Py_UNICODE* PyUnicode_AS_UNICODE (PyObject *o)
 -- C 函数: const char* PyUnicode_AS_DATA (PyObject *o)

     Return a pointer to a *note Py_UNICODE: af6. representation of the
     object.  The returned buffer is always terminated with an extra
     null code point.  It may also contain embedded null code points,
     which would cause the string to be truncated when used in most C
     functions.  The ‘AS_DATA’ form casts the pointer to ‘const char *’.
     The `o' argument has to be a Unicode object (not checked).

     在 3.3 版更改: This macro is now inefficient – because in many
     cases the *note Py_UNICODE: af6. representation does not exist and
     needs to be created – and can fail (return ‘NULL’ with an exception
     set).  Try to port the code to use the new ‘PyUnicode_nBYTE_DATA()’
     macros or use *note PyUnicode_WRITE(): aed. or *note
     PyUnicode_READ(): aeb.

     Deprecated since version 3.3, will be removed in version 3.12: Part
     of the old-style Unicode API, please migrate to using the
     ‘PyUnicode_nBYTE_DATA()’ family of macros.


File: python.info,  Node: Unicode字符属性,  Next: Creating and accessing Unicode strings,  Prev: Unicode类型,  Up: Unicode对象

7.8.3.9 Unicode字符属性
.......................

Unicode provides many different character properties.  The most often
needed ones are available through these macros which are mapped to C
functions depending on the Python configuration.

 -- C 函数: int Py_UNICODE_ISSPACE (Py_UNICODE ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a whitespace
     character.

 -- C 函数: int Py_UNICODE_ISLOWER (Py_UNICODE ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a lowercase
     character.

 -- C 函数: int Py_UNICODE_ISUPPER (Py_UNICODE ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is an uppercase
     character.

 -- C 函数: int Py_UNICODE_ISTITLE (Py_UNICODE ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a titlecase
     character.

 -- C 函数: int Py_UNICODE_ISLINEBREAK (Py_UNICODE ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a linebreak
     character.

 -- C 函数: int Py_UNICODE_ISDECIMAL (Py_UNICODE ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a decimal character.

 -- C 函数: int Py_UNICODE_ISDIGIT (Py_UNICODE ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a digit character.

 -- C 函数: int Py_UNICODE_ISNUMERIC (Py_UNICODE ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a numeric character.

 -- C 函数: int Py_UNICODE_ISALPHA (Py_UNICODE ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is an alphabetic
     character.

 -- C 函数: int Py_UNICODE_ISALNUM (Py_UNICODE ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is an alphanumeric
     character.

 -- C 函数: int Py_UNICODE_ISPRINTABLE (Py_UNICODE ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a printable
     character.  Nonprintable characters are those characters defined in
     the Unicode character database as "Other" or "Separator", excepting
     the ASCII space (0x20) which is considered printable.  (Note that
     printable characters in this context are those which should not be
     escaped when *note repr(): 7d5. is invoked on a string.  It has no
     bearing on the handling of strings written to *note sys.stdout:
     317. or *note sys.stderr: 318.)

These APIs can be used for fast direct character conversions:

 -- C 函数: Py_UNICODE Py_UNICODE_TOLOWER (Py_UNICODE ch)

     Return the character `ch' converted to lower case.

     3.3 版后已移除: This function uses simple case mappings.

 -- C 函数: Py_UNICODE Py_UNICODE_TOUPPER (Py_UNICODE ch)

     Return the character `ch' converted to upper case.

     3.3 版后已移除: This function uses simple case mappings.

 -- C 函数: Py_UNICODE Py_UNICODE_TOTITLE (Py_UNICODE ch)

     Return the character `ch' converted to title case.

     3.3 版后已移除: This function uses simple case mappings.

 -- C 函数: int Py_UNICODE_TODECIMAL (Py_UNICODE ch)

     Return the character `ch' converted to a decimal positive integer.
     Return ‘-1’ if this is not possible.  This macro does not raise
     exceptions.

 -- C 函数: int Py_UNICODE_TODIGIT (Py_UNICODE ch)

     Return the character `ch' converted to a single digit integer.
     Return ‘-1’ if this is not possible.  This macro does not raise
     exceptions.

 -- C 函数: double Py_UNICODE_TONUMERIC (Py_UNICODE ch)

     Return the character `ch' converted to a double.  Return ‘-1.0’ if
     this is not possible.  This macro does not raise exceptions.

These APIs can be used to work with surrogates:

 -- C 宏: Py_UNICODE_IS_SURROGATE (ch)

     Check if `ch' is a surrogate (‘0xD800 <= ch <= 0xDFFF’).

 -- C 宏: Py_UNICODE_IS_HIGH_SURROGATE (ch)

     Check if `ch' is a high surrogate (‘0xD800 <= ch <= 0xDBFF’).

 -- C 宏: Py_UNICODE_IS_LOW_SURROGATE (ch)

     Check if `ch' is a low surrogate (‘0xDC00 <= ch <= 0xDFFF’).

 -- C 宏: Py_UNICODE_JOIN_SURROGATES (high, low)

     Join two surrogate characters and return a single Py_UCS4 value.
     `high' and `low' are respectively the leading and trailing
     surrogates in a surrogate pair.


File: python.info,  Node: Creating and accessing Unicode strings,  Next: Deprecated Py_UNICODE APIs,  Prev: Unicode字符属性,  Up: Unicode对象

7.8.3.10 Creating and accessing Unicode strings
...............................................

To create Unicode objects and access their basic sequence properties,
use these APIs:

 -- C 函数: PyObject* PyUnicode_New (Py_ssize_t size, Py_UCS4 maxchar)
     `Return value: New reference.'  Create a new Unicode object.
     `maxchar' should be the true maximum code point to be placed in the
     string.  As an approximation, it can be rounded up to the nearest
     value in the sequence 127, 255, 65535, 1114111.

     This is the recommended way to allocate a new Unicode object.
     Objects created using this function are not resizable.

     3.3 新版功能.

 -- C 函数: PyObject* PyUnicode_FromKindAndData (int kind, const
          void *buffer, Py_ssize_t size)
     `Return value: New reference.'  Create a new Unicode object with
     the given `kind' (possible values are *note PyUnicode_1BYTE_KIND:
     ae8. etc., as returned by *note PyUnicode_KIND(): ae6.).  The
     `buffer' must point to an array of `size' units of 1, 2 or 4 bytes
     per character, as given by the kind.

     3.3 新版功能.

 -- C 函数: PyObject* PyUnicode_FromStringAndSize (const char *u,
          Py_ssize_t size)
     `Return value: New reference.'  Create a Unicode object from the
     char buffer `u'.  The bytes will be interpreted as being UTF-8
     encoded.  The buffer is copied into the new object.  If the buffer
     is not ‘NULL’, the return value might be a shared object, i.e.
     modification of the data is not allowed.

     If `u' is ‘NULL’, this function behaves like *note
     PyUnicode_FromUnicode(): af7. with the buffer set to ‘NULL’.  This
     usage is deprecated in favor of *note PyUnicode_New(): ad5, and
     will be removed in Python 3.12.

 -- C 函数: PyObject *PyUnicode_FromString (const char *u)
     `Return value: New reference.'  Create a Unicode object from a
     UTF-8 encoded null-terminated char buffer `u'.

 -- C 函数: PyObject* PyUnicode_FromFormat (const char *format, ...)
     `Return value: New reference.'  Take a C ‘printf()’-style `format'
     string and a variable number of arguments, calculate the size of
     the resulting Python Unicode string and return a string with the
     values formatted into it.  The variable arguments must be C types
     and must correspond exactly to the format characters in the
     `format' ASCII-encoded string.  The following format characters are
     allowed:

     格式字符                类型                      注释
                                                       
     -----------------------------------------------------------------------------------------
                                                       
     ‘%%’                    `不适用'                  文字%字符。
                                                       
                                                       
     ‘%c’                    int                       单个字符，表示为C 语言的整型。
                                                       
                                                       
     ‘%d’                    int                       相当于 ‘printf("%d")’.  (1)
                                                       
                                                       
     ‘%u’                    unsigned int              相当于 ‘printf("%u")’.  (2)
                                                       
                                                       
     ‘%ld’                   长整型                    相当于 ‘printf("%ld")’.  (3)
                                                       
                                                       
     ‘%li’                   长整型                    相当于 ‘printf("%li")’.  (4)
                                                       
                                                       
     ‘%lu’                   unsigned long             相当于 ‘printf("%lu")’.  (5)
                                                       
                                                       
     ‘%lld’                  long long                 相当于 ‘printf("%lld")’.  (6)
                                                       
                                                       
     ‘%lli’                  long long                 相当于 ‘printf("%lli")’.  (7)
                                                       
                                                       
     ‘%llu’                  unsigned long long        相当于 ‘printf("%llu")’.  (8)
                                                       
                                                       
     ‘%zd’                   Py_ssize_t                相当于 ‘printf("%zd")’.  (9)
                                                       
                                                       
     ‘%zi’                   Py_ssize_t                相当于 ‘printf("%zi")’.  (10)
                                                       
                                                       
     ‘%zu’                   size_t                    相当于 ‘printf("%zu")’.  (11)
                                                       
                                                       
     ‘%i’                    int                       相当于 ‘printf("%i")’.  (12)
                                                       
                                                       
     ‘%x’                    int                       相当于 ‘printf("%x")’.  (13)
                                                       
                                                       
     ‘%s’                    const char*               以 null 为终止符的 C 字符数组。
                                                       
                                                       
     ‘%p’                    const void*               一个 C 指针的十六进制表示形式。 基本
                                                       等价于 ‘printf("%p")’ 但它会确保以字
                                                       面值 ‘0x’ 开头，不论系统平台上
                                                       ‘printf’ 的输出是什么。
                                                       
                                                       
     ‘%A’                    PyObject*                 *note ascii(): d54. 调用的结果。
                                                       
                                                       
     ‘%U’                    PyObject*                 A Unicode object.
                                                       
                                                       
     ‘%V’                    PyObject*, const char*    A Unicode object (which may be
                                                       ‘NULL’) and a null-terminated C
                                                       character array as a second
                                                       parameter (which will be used, if
                                                       the first parameter is ‘NULL’).
                                                       
                                                       
     ‘%S’                    PyObject*                 The result of calling
                                                       *note PyObject_Str(): 971.
                                                       
                                                       
     ‘%R’                    PyObject*                 The result of calling
                                                       *note PyObject_Repr(): 970.
                                                       

     An unrecognized format character causes all the rest of the format
     string to be copied as-is to the result string, and any extra
     arguments discarded.

          注解: The width formatter unit is number of characters rather
          than bytes.  The precision formatter unit is number of bytes
          for ‘"%s"’ and ‘"%V"’ (if the ‘PyObject*’ argument is ‘NULL’),
          and a number of characters for ‘"%A"’, ‘"%U"’, ‘"%S"’, ‘"%R"’
          and ‘"%V"’ (if the ‘PyObject*’ argument is not ‘NULL’).

     在 3.2 版更改: Support for ‘"%lld"’ and ‘"%llu"’ added.

     在 3.3 版更改: Support for ‘"%li"’, ‘"%lli"’ and ‘"%zi"’ added.

     在 3.4 版更改: Support width and precision formatter for ‘"%s"’,
     ‘"%A"’, ‘"%U"’, ‘"%V"’, ‘"%S"’, ‘"%R"’ added.

 -- C 函数: PyObject* PyUnicode_FromFormatV (const char *format,
          va_list vargs)
     `Return value: New reference.'  Identical to *note
     PyUnicode_FromFormat(): 7d4. except that it takes exactly two
     arguments.

 -- C 函数: PyObject* PyUnicode_FromEncodedObject (PyObject *obj, const
          char *encoding, const char *errors)
     `Return value: New reference.'  Decode an encoded object `obj' to a
     Unicode object.

     *note bytes: 33a, *note bytearray: 33b. and other *note bytes-like
     objects: 5f1. are decoded according to the given `encoding' and
     using the error handling defined by `errors'.  Both can be ‘NULL’
     to have the interface use the default values (see *note Built-in
     Codecs: 3e04. for details).

     All other objects, including Unicode objects, cause a *note
     TypeError: 193. to be set.

     The API returns ‘NULL’ if there was an error.  The caller is
     responsible for decref’ing the returned objects.

 -- C 函数: Py_ssize_t PyUnicode_GetLength (PyObject *unicode)

     Return the length of the Unicode object, in code points.

     3.3 新版功能.

 -- C 函数: Py_ssize_t PyUnicode_CopyCharacters (PyObject *to,
          Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start,
          Py_ssize_t how_many)

     Copy characters from one Unicode object into another.  This
     function performs character conversion when necessary and falls
     back to ‘memcpy()’ if possible.  Returns ‘-1’ and sets an exception
     on error, otherwise returns the number of copied characters.

     3.3 新版功能.

 -- C 函数: Py_ssize_t PyUnicode_Fill (PyObject *unicode,
          Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char)

     Fill a string with a character: write `fill_char' into
     ‘unicode[start:start+length]’.

     Fail if `fill_char' is bigger than the string maximum character, or
     if the string has more than 1 reference.

     Return the number of written character, or return ‘-1’ and raise an
     exception on error.

     3.3 新版功能.

 -- C 函数: int PyUnicode_WriteChar (PyObject *unicode,
          Py_ssize_t index, Py_UCS4 character)

     Write a character to a string.  The string must have been created
     through *note PyUnicode_New(): ad5.  Since Unicode strings are
     supposed to be immutable, the string must not be shared, or have
     been hashed yet.

     This function checks that `unicode' is a Unicode object, that the
     index is not out of bounds, and that the object can be modified
     safely (i.e.  that it its reference count is one).

     3.3 新版功能.

 -- C 函数: Py_UCS4 PyUnicode_ReadChar (PyObject *unicode,
          Py_ssize_t index)

     Read a character from a string.  This function checks that
     `unicode' is a Unicode object and the index is not out of bounds,
     in contrast to the macro version *note PyUnicode_READ_CHAR(): aec.

     3.3 新版功能.

 -- C 函数: PyObject* PyUnicode_Substring (PyObject *str,
          Py_ssize_t start, Py_ssize_t end)
     `Return value: New reference.'  Return a substring of `str', from
     character index `start' (included) to character index `end'
     (excluded).  Negative indices are not supported.

     3.3 新版功能.

 -- C 函数: Py_UCS4* PyUnicode_AsUCS4 (PyObject *u, Py_UCS4 *buffer,
          Py_ssize_t buflen, int copy_null)

     Copy the string `u' into a UCS4 buffer, including a null character,
     if `copy_null' is set.  Returns ‘NULL’ and sets an exception on
     error (in particular, a *note SystemError: 604. if `buflen' is
     smaller than the length of `u').  `buffer' is returned on success.

     3.3 新版功能.

 -- C 函数: Py_UCS4* PyUnicode_AsUCS4Copy (PyObject *u)

     Copy the string `u' into a new UCS4 buffer that is allocated using
     *note PyMem_Malloc(): 50d.  If this fails, ‘NULL’ is returned with
     a *note MemoryError: efc. set.  The returned buffer always has an
     extra null code point appended.

     3.3 新版功能.

   ---------- Footnotes ----------

   (1) (1) For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd,
zi, zu, i, x): the 0-conversion flag has effect even when a precision is
given.

   (2) (1) For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd,
zi, zu, i, x): the 0-conversion flag has effect even when a precision is
given.

   (3) (1) For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd,
zi, zu, i, x): the 0-conversion flag has effect even when a precision is
given.

   (4) (1) For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd,
zi, zu, i, x): the 0-conversion flag has effect even when a precision is
given.

   (5) (1) For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd,
zi, zu, i, x): the 0-conversion flag has effect even when a precision is
given.

   (6) (1) For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd,
zi, zu, i, x): the 0-conversion flag has effect even when a precision is
given.

   (7) (1) For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd,
zi, zu, i, x): the 0-conversion flag has effect even when a precision is
given.

   (8) (1) For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd,
zi, zu, i, x): the 0-conversion flag has effect even when a precision is
given.

   (9) (1) For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd,
zi, zu, i, x): the 0-conversion flag has effect even when a precision is
given.

   (10) (1) For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd,
zi, zu, i, x): the 0-conversion flag has effect even when a precision is
given.

   (11) (1) For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd,
zi, zu, i, x): the 0-conversion flag has effect even when a precision is
given.

   (12) (1) For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd,
zi, zu, i, x): the 0-conversion flag has effect even when a precision is
given.

   (13) (1) For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd,
zi, zu, i, x): the 0-conversion flag has effect even when a precision is
given.


File: python.info,  Node: Deprecated Py_UNICODE APIs,  Next: Locale Encoding,  Prev: Creating and accessing Unicode strings,  Up: Unicode对象

7.8.3.11 Deprecated Py_UNICODE APIs
...................................

Deprecated since version 3.3, will be removed in version 3.12.

These API functions are deprecated with the implementation of PEP
393(1).  Extension modules can continue using them, as they will not be
removed in Python 3.x, but need to be aware that their use can now cause
performance and memory hits.

 -- C 函数: PyObject* PyUnicode_FromUnicode (const Py_UNICODE *u,
          Py_ssize_t size)
     `Return value: New reference.'  Create a Unicode object from the
     Py_UNICODE buffer `u' of the given size.  `u' may be ‘NULL’ which
     causes the contents to be undefined.  It is the user’s
     responsibility to fill in the needed data.  The buffer is copied
     into the new object.

     If the buffer is not ‘NULL’, the return value might be a shared
     object.  Therefore, modification of the resulting Unicode object is
     only allowed when `u' is ‘NULL’.

     If the buffer is ‘NULL’, *note PyUnicode_READY(): ade. must be
     called once the string content has been filled before using any of
     the access macros such as *note PyUnicode_KIND(): ae6.

     Deprecated since version 3.3, will be removed in version 3.12: Part
     of the old-style Unicode API, please migrate to using *note
     PyUnicode_FromKindAndData(): adf, *note PyUnicode_FromWideChar():
     af8, or *note PyUnicode_New(): ad5.

 -- C 函数: Py_UNICODE* PyUnicode_AsUnicode (PyObject *unicode)

     Return a read-only pointer to the Unicode object’s internal *note
     Py_UNICODE: af6. buffer, or ‘NULL’ on error.  This will create the
     *note Py_UNICODE*: af6. representation of the object if it is not
     yet available.  The buffer is always terminated with an extra null
     code point.  Note that the resulting *note Py_UNICODE: af6. string
     may also contain embedded null code points, which would cause the
     string to be truncated when used in most C functions.

     Deprecated since version 3.3, will be removed in version 3.12: Part
     of the old-style Unicode API, please migrate to using *note
     PyUnicode_AsUCS4(): ae0, *note PyUnicode_AsWideChar(): 1062, *note
     PyUnicode_ReadChar(): ad7. or similar new APIs.

     Deprecated since version 3.3, will be removed in version 3.10.

 -- C 函数: PyObject* PyUnicode_TransformDecimalToASCII (Py_UNICODE *s,
          Py_ssize_t size)
     `Return value: New reference.'  Create a Unicode object by
     replacing all decimal digits in *note Py_UNICODE: af6. buffer of
     the given `size' by ASCII digits 0–9 according to their decimal
     value.  Return ‘NULL’ if an exception occurs.

     Deprecated since version 3.3, will be removed in version 3.11: Part
     of the old-style *note Py_UNICODE: af6. API; please migrate to
     using *note Py_UNICODE_TODECIMAL(): 3dfa.

 -- C 函数: Py_UNICODE* PyUnicode_AsUnicodeAndSize (PyObject *unicode,
          Py_ssize_t *size)

     Like *note PyUnicode_AsUnicode(): afa, but also saves the *note
     Py_UNICODE(): af6. array length (excluding the extra null
     terminator) in `size'.  Note that the resulting *note Py_UNICODE*:
     af6. string may contain embedded null code points, which would
     cause the string to be truncated when used in most C functions.

     3.3 新版功能.

     Deprecated since version 3.3, will be removed in version 3.12: Part
     of the old-style Unicode API, please migrate to using *note
     PyUnicode_AsUCS4(): ae0, *note PyUnicode_AsWideChar(): 1062, *note
     PyUnicode_ReadChar(): ad7. or similar new APIs.

 -- C 函数: Py_UNICODE* PyUnicode_AsUnicodeCopy (PyObject *unicode)

     Create a copy of a Unicode string ending with a null code point.
     Return ‘NULL’ and raise a *note MemoryError: efc. exception on
     memory allocation failure, otherwise return a new allocated buffer
     (use *note PyMem_Free(): db1. to free the buffer).  Note that the
     resulting *note Py_UNICODE*: af6. string may contain embedded null
     code points, which would cause the string to be truncated when used
     in most C functions.

     3.2 新版功能.

     Please migrate to using *note PyUnicode_AsUCS4Copy(): ae1. or
     similar new APIs.

 -- C 函数: Py_ssize_t PyUnicode_GetSize (PyObject *unicode)

     Return the size of the deprecated *note Py_UNICODE: af6.
     representation, in code units (this includes surrogate pairs as 2
     units).

     Deprecated since version 3.3, will be removed in version 3.12: Part
     of the old-style Unicode API, please migrate to using *note
     PyUnicode_GET_LENGTH(): ad4.

 -- C 函数: PyObject* PyUnicode_FromObject (PyObject *obj)
     `Return value: New reference.'  Copy an instance of a Unicode
     subtype to a new true Unicode object if necessary.  If `obj' is
     already a true Unicode object (not a subtype), return the reference
     with incremented refcount.

     Objects other than Unicode or its subtypes will cause a *note
     TypeError: 193.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393


File: python.info,  Node: Locale Encoding,  Next: File System Encoding,  Prev: Deprecated Py_UNICODE APIs,  Up: Unicode对象

7.8.3.12 Locale Encoding
........................

The current locale encoding can be used to decode text from the
operating system.

 -- C 函数: PyObject* PyUnicode_DecodeLocaleAndSize (const char *str,
          Py_ssize_t len, const char *errors)
     `Return value: New reference.'  Decode a string from UTF-8 on
     Android and VxWorks, or from the current locale encoding on other
     platforms.  The supported error handlers are ‘"strict"’ and
     ‘"surrogateescape"’ ( PEP 383(1)).  The decoder uses ‘"strict"’
     error handler if `errors' is ‘NULL’.  `str' must end with a null
     character but cannot contain embedded null characters.

     Use *note PyUnicode_DecodeFSDefaultAndSize(): 3c49. to decode a
     string from ‘Py_FileSystemDefaultEncoding’ (the locale encoding
     read at Python startup).

     This function ignores the Python UTF-8 mode.

     参见
     ....

     The *note Py_DecodeLocale(): 444. function.

     3.3 新版功能.

     在 3.7 版更改: The function now also uses the current locale
     encoding for the ‘surrogateescape’ error handler, except on
     Android.  Previously, *note Py_DecodeLocale(): 444. was used for
     the ‘surrogateescape’, and the current locale encoding was used for
     ‘strict’.

 -- C 函数: PyObject* PyUnicode_DecodeLocale (const char *str, const
          char *errors)
     `Return value: New reference.'  Similar to *note
     PyUnicode_DecodeLocaleAndSize(): 446, but compute the string length
     using ‘strlen()’.

     3.3 新版功能.

 -- C 函数: PyObject* PyUnicode_EncodeLocale (PyObject *unicode, const
          char *errors)
     `Return value: New reference.'  Encode a Unicode object to UTF-8 on
     Android and VxWorks, or to the current locale encoding on other
     platforms.  The supported error handlers are ‘"strict"’ and
     ‘"surrogateescape"’ ( PEP 383(2)).  The encoder uses ‘"strict"’
     error handler if `errors' is ‘NULL’.  Return a *note bytes: 33a.
     object.  `unicode' cannot contain embedded null characters.

     Use *note PyUnicode_EncodeFSDefault(): 105b. to encode a string to
     ‘Py_FileSystemDefaultEncoding’ (the locale encoding read at Python
     startup).

     This function ignores the Python UTF-8 mode.

     参见
     ....

     The *note Py_EncodeLocale(): 445. function.

     3.3 新版功能.

     在 3.7 版更改: The function now also uses the current locale
     encoding for the ‘surrogateescape’ error handler, except on
     Android.  Previously, *note Py_EncodeLocale(): 445. was used for
     the ‘surrogateescape’, and the current locale encoding was used for
     ‘strict’.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0383

   (2) https://www.python.org/dev/peps/pep-0383


File: python.info,  Node: File System Encoding,  Next: wchar_t Support,  Prev: Locale Encoding,  Up: Unicode对象

7.8.3.13 File System Encoding
.............................

To encode and decode file names and other environment strings,
‘Py_FileSystemDefaultEncoding’ should be used as the encoding, and
‘Py_FileSystemDefaultEncodeErrors’ should be used as the error handler (
PEP 383(1) and PEP 529(2)).  To encode file names to *note bytes: 33a.
during argument parsing, the ‘"O&"’ converter should be used, passing
*note PyUnicode_FSConverter(): 5d7. as the conversion function:

 -- C 函数: int PyUnicode_FSConverter (PyObject* obj, void* result)

     ParseTuple converter: encode *note str: 339. objects – obtained
     directly or through the *note os.PathLike: 4f3. interface – to
     *note bytes: 33a. using *note PyUnicode_EncodeFSDefault(): 105b.;
     *note bytes: 33a. objects are output as-is.  `result' must be a
     *note PyBytesObject*: d26. which must be released when it is no
     longer used.

     3.1 新版功能.

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

To decode file names to *note str: 339. during argument parsing, the
‘"O&"’ converter should be used, passing *note PyUnicode_FSDecoder():
5d8. as the conversion function:

 -- C 函数: int PyUnicode_FSDecoder (PyObject* obj, void* result)

     ParseTuple converter: decode *note bytes: 33a. objects – obtained
     either directly or indirectly through the *note os.PathLike: 4f3.
     interface – to *note str: 339. using *note
     PyUnicode_DecodeFSDefaultAndSize(): 3c49.; *note str: 339. objects
     are output as-is.  `result' must be a *note PyUnicodeObject*: 3de7.
     which must be released when it is no longer used.

     3.2 新版功能.

     在 3.6 版更改: 接受一个 *note path-like object: 373.。

 -- C 函数: PyObject* PyUnicode_DecodeFSDefaultAndSize (const char *s,
          Py_ssize_t size)
     `Return value: New reference.'  Decode a string using
     ‘Py_FileSystemDefaultEncoding’ and the
     ‘Py_FileSystemDefaultEncodeErrors’ error handler.

     If ‘Py_FileSystemDefaultEncoding’ is not set, fall back to the
     locale encoding.

     ‘Py_FileSystemDefaultEncoding’ is initialized at startup from the
     locale encoding and cannot be modified later.  If you need to
     decode a string from the current locale encoding, use *note
     PyUnicode_DecodeLocaleAndSize(): 446.

     参见
     ....

     The *note Py_DecodeLocale(): 444. function.

     在 3.6 版更改: Use ‘Py_FileSystemDefaultEncodeErrors’ error
     handler.

 -- C 函数: PyObject* PyUnicode_DecodeFSDefault (const char *s)
     `Return value: New reference.'  Decode a null-terminated string
     using ‘Py_FileSystemDefaultEncoding’ and the
     ‘Py_FileSystemDefaultEncodeErrors’ error handler.

     If ‘Py_FileSystemDefaultEncoding’ is not set, fall back to the
     locale encoding.

     Use *note PyUnicode_DecodeFSDefaultAndSize(): 3c49. if you know the
     string length.

     在 3.6 版更改: Use ‘Py_FileSystemDefaultEncodeErrors’ error
     handler.

 -- C 函数: PyObject* PyUnicode_EncodeFSDefault (PyObject *unicode)
     `Return value: New reference.'  Encode a Unicode object to
     ‘Py_FileSystemDefaultEncoding’ with the
     ‘Py_FileSystemDefaultEncodeErrors’ error handler, and return *note
     bytes: 33a.  Note that the resulting *note bytes: 33a. object may
     contain null bytes.

     If ‘Py_FileSystemDefaultEncoding’ is not set, fall back to the
     locale encoding.

     ‘Py_FileSystemDefaultEncoding’ is initialized at startup from the
     locale encoding and cannot be modified later.  If you need to
     encode a string to the current locale encoding, use *note
     PyUnicode_EncodeLocale(): 447.

     参见
     ....

     The *note Py_EncodeLocale(): 445. function.

     3.2 新版功能.

     在 3.6 版更改: Use ‘Py_FileSystemDefaultEncodeErrors’ error
     handler.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0383

   (2) https://www.python.org/dev/peps/pep-0529


File: python.info,  Node: wchar_t Support,  Prev: File System Encoding,  Up: Unicode对象

7.8.3.14 wchar_t Support
........................

‘wchar_t’ support for platforms which support it:

 -- C 函数: PyObject* PyUnicode_FromWideChar (const wchar_t *w,
          Py_ssize_t size)
     `Return value: New reference.'  Create a Unicode object from the
     ‘wchar_t’ buffer `w' of the given `size'.  Passing ‘-1’ as the
     `size' indicates that the function must itself compute the length,
     using wcslen.  Return ‘NULL’ on failure.

 -- C 函数: Py_ssize_t PyUnicode_AsWideChar (PyObject *unicode,
          wchar_t *w, Py_ssize_t size)

     Copy the Unicode object contents into the ‘wchar_t’ buffer `w'.  At
     most `size' ‘wchar_t’ characters are copied (excluding a possibly
     trailing null termination character).  Return the number of
     ‘wchar_t’ characters copied or ‘-1’ in case of an error.  Note that
     the resulting ‘wchar_t*’ string may or may not be null-terminated.
     It is the responsibility of the caller to make sure that the
     ‘wchar_t*’ string is null-terminated in case this is required by
     the application.  Also, note that the ‘wchar_t*’ string might
     contain null characters, which would cause the string to be
     truncated when used with most C functions.

 -- C 函数: wchar_t* PyUnicode_AsWideCharString (PyObject *unicode,
          Py_ssize_t *size)

     Convert the Unicode object to a wide character string.  The output
     string always ends with a null character.  If `size' is not ‘NULL’,
     write the number of wide characters (excluding the trailing null
     termination character) into `*size'.  Note that the resulting
     ‘wchar_t’ string might contain null characters, which would cause
     the string to be truncated when used with most C functions.  If
     `size' is ‘NULL’ and the ‘wchar_t*’ string contains null characters
     a *note ValueError: 1fc. is raised.

     Returns a buffer allocated by ‘PyMem_Alloc()’ (use *note
     PyMem_Free(): db1. to free it) on success.  On error, returns
     ‘NULL’ and `*size' is undefined.  Raises a *note MemoryError: efc.
     if memory allocation is failed.

     3.2 新版功能.

     在 3.7 版更改: Raises a *note ValueError: 1fc. if `size' is ‘NULL’
     and the ‘wchar_t*’ string contains null characters.


File: python.info,  Node: Built-in Codecs,  Next: Methods and Slot Functions,  Prev: Unicode对象,  Up: Unicode对象和编码解码器

7.8.3.15 Built-in Codecs
........................

Python provides a set of built-in codecs which are written in C for
speed.  All of these codecs are directly usable via the following
functions.

Many of the following APIs take two arguments encoding and errors, and
they have the same semantics as the ones of the built-in *note str():
339. string object constructor.

Setting encoding to ‘NULL’ causes the default encoding to be used which
is ASCII. The file system calls should use *note
PyUnicode_FSConverter(): 5d7. for encoding file names.  This uses the
variable ‘Py_FileSystemDefaultEncoding’ internally.  This variable
should be treated as read-only: on some systems, it will be a pointer to
a static string, on others, it will change at run-time (such as when the
application invokes setlocale).

Error handling is set by errors which may also be set to ‘NULL’ meaning
to use the default handling defined for the codec.  Default error
handling for all built-in codecs is "strict" (*note ValueError: 1fc. is
raised).

The codecs all use a similar interface.  Only deviation from the
following generic ones are documented for simplicity.

* Menu:

* Generic Codecs::
* UTF-8 Codecs::
* UTF-32 Codecs::
* UTF-16 Codecs::
* UTF-7 Codecs::
* Unicode-Escape Codecs::
* Raw-Unicode-Escape Codecs::
* Latin-1 Codecs::
* ASCII Codecs::
* Character Map Codecs::
* MBCS codecs for Windows::
* Methods & Slots::


File: python.info,  Node: Generic Codecs,  Next: UTF-8 Codecs,  Up: Built-in Codecs

7.8.3.16 Generic Codecs
.......................

These are the generic codec APIs:

 -- C 函数: PyObject* PyUnicode_Decode (const char *s, Py_ssize_t size,
          const char *encoding, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the encoded string `s'.  `encoding' and `errors'
     have the same meaning as the parameters of the same name in the
     *note str(): 339. built-in function.  The codec to be used is
     looked up using the Python codec registry.  Return ‘NULL’ if an
     exception was raised by the codec.

 -- C 函数: PyObject* PyUnicode_AsEncodedString (PyObject *unicode,
          const char *encoding, const char *errors)
     `Return value: New reference.'  Encode a Unicode object and return
     the result as Python bytes object.  `encoding' and `errors' have
     the same meaning as the parameters of the same name in the Unicode
     *note encode(): c3f. method.  The codec to be used is looked up
     using the Python codec registry.  Return ‘NULL’ if an exception was
     raised by the codec.

 -- C 函数: PyObject* PyUnicode_Encode (const Py_UNICODE *s,
          Py_ssize_t size, const char *encoding, const char *errors)
     `Return value: New reference.'  Encode the *note Py_UNICODE: af6.
     buffer `s' of the given `size' and return a Python bytes object.
     `encoding' and `errors' have the same meaning as the parameters of
     the same name in the Unicode *note encode(): c3f. method.  The
     codec to be used is looked up using the Python codec registry.
     Return ‘NULL’ if an exception was raised by the codec.

     Deprecated since version 3.3, will be removed in version 3.11: Part
     of the old-style *note Py_UNICODE: af6. API; please migrate to
     using *note PyUnicode_AsEncodedString(): 3e0e.


File: python.info,  Node: UTF-8 Codecs,  Next: UTF-32 Codecs,  Prev: Generic Codecs,  Up: Built-in Codecs

7.8.3.17 UTF-8 Codecs
.....................

These are the UTF-8 codec APIs:

 -- C 函数: PyObject* PyUnicode_DecodeUTF8 (const char *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the UTF-8 encoded string `s'.  Return ‘NULL’ if an
     exception was raised by the codec.

 -- C 函数: PyObject* PyUnicode_DecodeUTF8Stateful (const char *s,
          Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
     `Return value: New reference.'  If `consumed' is ‘NULL’, behave
     like *note PyUnicode_DecodeUTF8(): 3e10.  If `consumed' is not
     ‘NULL’, trailing incomplete UTF-8 byte sequences will not be
     treated as an error.  Those bytes will not be decoded and the
     number of bytes that have been decoded will be stored in
     `consumed'.

 -- C 函数: PyObject* PyUnicode_AsUTF8String (PyObject *unicode)
     `Return value: New reference.'  Encode a Unicode object using UTF-8
     and return the result as Python bytes object.  Error handling is
     "strict".  Return ‘NULL’ if an exception was raised by the codec.

 -- C 函数: const char* PyUnicode_AsUTF8AndSize (PyObject *unicode,
          Py_ssize_t *size)

     Return a pointer to the UTF-8 encoding of the Unicode object, and
     store the size of the encoded representation (in bytes) in `size'.
     The `size' argument can be ‘NULL’; in this case no size will be
     stored.  The returned buffer always has an extra null byte appended
     (not included in `size'), regardless of whether there are any other
     null code points.

     In the case of an error, ‘NULL’ is returned with an exception set
     and no `size' is stored.

     This caches the UTF-8 representation of the string in the Unicode
     object, and subsequent calls will return a pointer to the same
     buffer.  The caller is not responsible for deallocating the buffer.

     3.3 新版功能.

     在 3.7 版更改: The return type is now ‘const char *’ rather of
     ‘char *’.

 -- C 函数: const char* PyUnicode_AsUTF8 (PyObject *unicode)

     As *note PyUnicode_AsUTF8AndSize(): 432, but does not store the
     size.

     3.3 新版功能.

     在 3.7 版更改: The return type is now ‘const char *’ rather of
     ‘char *’.

 -- C 函数: PyObject* PyUnicode_EncodeUTF8 (const Py_UNICODE *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Encode the *note Py_UNICODE: af6.
     buffer `s' of the given `size' using UTF-8 and return a Python
     bytes object.  Return ‘NULL’ if an exception was raised by the
     codec.

     Deprecated since version 3.3, will be removed in version 3.11: Part
     of the old-style *note Py_UNICODE: af6. API; please migrate to
     using *note PyUnicode_AsUTF8String(): b07, *note
     PyUnicode_AsUTF8AndSize(): 432. or *note
     PyUnicode_AsEncodedString(): 3e0e.


File: python.info,  Node: UTF-32 Codecs,  Next: UTF-16 Codecs,  Prev: UTF-8 Codecs,  Up: Built-in Codecs

7.8.3.18 UTF-32 Codecs
......................

These are the UTF-32 codec APIs:

 -- C 函数: PyObject* PyUnicode_DecodeUTF32 (const char *s,
          Py_ssize_t size, const char *errors, int *byteorder)
     `Return value: New reference.'  Decode `size' bytes from a UTF-32
     encoded buffer string and return the corresponding Unicode object.
     `errors' (if non-‘NULL’) defines the error handling.  It defaults
     to "strict".

     If `byteorder' is non-‘NULL’, the decoder starts decoding using the
     given byte order:

          *byteorder == -1: little endian
          *byteorder == 0:  native order
          *byteorder == 1:  big endian

     If ‘*byteorder’ is zero, and the first four bytes of the input data
     are a byte order mark (BOM), the decoder switches to this byte
     order and the BOM is not copied into the resulting Unicode string.
     If ‘*byteorder’ is ‘-1’ or ‘1’, any byte order mark is copied to
     the output.

     After completion, `*byteorder' is set to the current byte order at
     the end of input data.

     If `byteorder' is ‘NULL’, the codec starts in native order mode.

     Return ‘NULL’ if an exception was raised by the codec.

 -- C 函数: PyObject* PyUnicode_DecodeUTF32Stateful (const char *s,
          Py_ssize_t size, const char *errors, int *byteorder,
          Py_ssize_t *consumed)
     `Return value: New reference.'  If `consumed' is ‘NULL’, behave
     like *note PyUnicode_DecodeUTF32(): 3e13.  If `consumed' is not
     ‘NULL’, *note PyUnicode_DecodeUTF32Stateful(): 3e14. will not treat
     trailing incomplete UTF-32 byte sequences (such as a number of
     bytes not divisible by four) as an error.  Those bytes will not be
     decoded and the number of bytes that have been decoded will be
     stored in `consumed'.

 -- C 函数: PyObject* PyUnicode_AsUTF32String (PyObject *unicode)
     `Return value: New reference.'  Return a Python byte string using
     the UTF-32 encoding in native byte order.  The string always starts
     with a BOM mark.  Error handling is "strict".  Return ‘NULL’ if an
     exception was raised by the codec.

 -- C 函数: PyObject* PyUnicode_EncodeUTF32 (const Py_UNICODE *s,
          Py_ssize_t size, const char *errors, int byteorder)
     `Return value: New reference.'  Return a Python bytes object
     holding the UTF-32 encoded value of the Unicode data in `s'.
     Output is written according to the following byte order:

          byteorder == -1: little endian
          byteorder == 0:  native byte order (writes a BOM mark)
          byteorder == 1:  big endian

     If byteorder is ‘0’, the output string will always start with the
     Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
     prepended.

     If ‘Py_UNICODE_WIDE’ is not defined, surrogate pairs will be output
     as a single code point.

     Return ‘NULL’ if an exception was raised by the codec.

     Deprecated since version 3.3, will be removed in version 3.11: Part
     of the old-style *note Py_UNICODE: af6. API; please migrate to
     using *note PyUnicode_AsUTF32String(): 3e15. or *note
     PyUnicode_AsEncodedString(): 3e0e.


File: python.info,  Node: UTF-16 Codecs,  Next: UTF-7 Codecs,  Prev: UTF-32 Codecs,  Up: Built-in Codecs

7.8.3.19 UTF-16 Codecs
......................

These are the UTF-16 codec APIs:

 -- C 函数: PyObject* PyUnicode_DecodeUTF16 (const char *s,
          Py_ssize_t size, const char *errors, int *byteorder)
     `Return value: New reference.'  Decode `size' bytes from a UTF-16
     encoded buffer string and return the corresponding Unicode object.
     `errors' (if non-‘NULL’) defines the error handling.  It defaults
     to "strict".

     If `byteorder' is non-‘NULL’, the decoder starts decoding using the
     given byte order:

          *byteorder == -1: little endian
          *byteorder == 0:  native order
          *byteorder == 1:  big endian

     If ‘*byteorder’ is zero, and the first two bytes of the input data
     are a byte order mark (BOM), the decoder switches to this byte
     order and the BOM is not copied into the resulting Unicode string.
     If ‘*byteorder’ is ‘-1’ or ‘1’, any byte order mark is copied to
     the output (where it will result in either a ‘\ufeff’ or a ‘\ufffe’
     character).

     After completion, `*byteorder' is set to the current byte order at
     the end of input data.

     If `byteorder' is ‘NULL’, the codec starts in native order mode.

     Return ‘NULL’ if an exception was raised by the codec.

 -- C 函数: PyObject* PyUnicode_DecodeUTF16Stateful (const char *s,
          Py_ssize_t size, const char *errors, int *byteorder,
          Py_ssize_t *consumed)
     `Return value: New reference.'  If `consumed' is ‘NULL’, behave
     like *note PyUnicode_DecodeUTF16(): 3e17.  If `consumed' is not
     ‘NULL’, *note PyUnicode_DecodeUTF16Stateful(): 3e18. will not treat
     trailing incomplete UTF-16 byte sequences (such as an odd number of
     bytes or a split surrogate pair) as an error.  Those bytes will not
     be decoded and the number of bytes that have been decoded will be
     stored in `consumed'.

 -- C 函数: PyObject* PyUnicode_AsUTF16String (PyObject *unicode)
     `Return value: New reference.'  Return a Python byte string using
     the UTF-16 encoding in native byte order.  The string always starts
     with a BOM mark.  Error handling is "strict".  Return ‘NULL’ if an
     exception was raised by the codec.

 -- C 函数: PyObject* PyUnicode_EncodeUTF16 (const Py_UNICODE *s,
          Py_ssize_t size, const char *errors, int byteorder)
     `Return value: New reference.'  Return a Python bytes object
     holding the UTF-16 encoded value of the Unicode data in `s'.
     Output is written according to the following byte order:

          byteorder == -1: little endian
          byteorder == 0:  native byte order (writes a BOM mark)
          byteorder == 1:  big endian

     If byteorder is ‘0’, the output string will always start with the
     Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
     prepended.

     If ‘Py_UNICODE_WIDE’ is defined, a single *note Py_UNICODE: af6.
     value may get represented as a surrogate pair.  If it is not
     defined, each *note Py_UNICODE: af6. values is interpreted as a
     UCS-2 character.

     Return ‘NULL’ if an exception was raised by the codec.

     Deprecated since version 3.3, will be removed in version 3.11: Part
     of the old-style *note Py_UNICODE: af6. API; please migrate to
     using *note PyUnicode_AsUTF16String(): 3e19. or *note
     PyUnicode_AsEncodedString(): 3e0e.


File: python.info,  Node: UTF-7 Codecs,  Next: Unicode-Escape Codecs,  Prev: UTF-16 Codecs,  Up: Built-in Codecs

7.8.3.20 UTF-7 Codecs
.....................

These are the UTF-7 codec APIs:

 -- C 函数: PyObject* PyUnicode_DecodeUTF7 (const char *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the UTF-7 encoded string `s'.  Return ‘NULL’ if an
     exception was raised by the codec.

 -- C 函数: PyObject* PyUnicode_DecodeUTF7Stateful (const char *s,
          Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
     `Return value: New reference.'  If `consumed' is ‘NULL’, behave
     like *note PyUnicode_DecodeUTF7(): 3e1b.  If `consumed' is not
     ‘NULL’, trailing incomplete UTF-7 base-64 sections will not be
     treated as an error.  Those bytes will not be decoded and the
     number of bytes that have been decoded will be stored in
     `consumed'.

 -- C 函数: PyObject* PyUnicode_EncodeUTF7 (const Py_UNICODE *s,
          Py_ssize_t size, int base64SetO, int base64WhiteSpace, const
          char *errors)
     `Return value: New reference.'  Encode the *note Py_UNICODE: af6.
     buffer of the given size using UTF-7 and return a Python bytes
     object.  Return ‘NULL’ if an exception was raised by the codec.

     If `base64SetO' is nonzero, "Set O" (punctuation that has no
     otherwise special meaning) will be encoded in base-64.  If
     `base64WhiteSpace' is nonzero, whitespace will be encoded in
     base-64.  Both are set to zero for the Python "utf-7" codec.

     Deprecated since version 3.3, will be removed in version 3.11: Part
     of the old-style *note Py_UNICODE: af6. API; please migrate to
     using *note PyUnicode_AsEncodedString(): 3e0e.


File: python.info,  Node: Unicode-Escape Codecs,  Next: Raw-Unicode-Escape Codecs,  Prev: UTF-7 Codecs,  Up: Built-in Codecs

7.8.3.21 Unicode-Escape Codecs
..............................

These are the "Unicode Escape" codec APIs:

 -- C 函数: PyObject* PyUnicode_DecodeUnicodeEscape (const char *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the Unicode-Escape encoded string `s'.  Return
     ‘NULL’ if an exception was raised by the codec.

 -- C 函数: PyObject* PyUnicode_AsUnicodeEscapeString
          (PyObject *unicode)
     `Return value: New reference.'  Encode a Unicode object using
     Unicode-Escape and return the result as a bytes object.  Error
     handling is "strict".  Return ‘NULL’ if an exception was raised by
     the codec.

 -- C 函数: PyObject* PyUnicode_EncodeUnicodeEscape (const
          Py_UNICODE *s, Py_ssize_t size)
     `Return value: New reference.'  Encode the *note Py_UNICODE: af6.
     buffer of the given `size' using Unicode-Escape and return a bytes
     object.  Return ‘NULL’ if an exception was raised by the codec.

     Deprecated since version 3.3, will be removed in version 3.11: Part
     of the old-style *note Py_UNICODE: af6. API; please migrate to
     using *note PyUnicode_AsUnicodeEscapeString(): b0b.


File: python.info,  Node: Raw-Unicode-Escape Codecs,  Next: Latin-1 Codecs,  Prev: Unicode-Escape Codecs,  Up: Built-in Codecs

7.8.3.22 Raw-Unicode-Escape Codecs
..................................

These are the "Raw Unicode Escape" codec APIs:

 -- C 函数: PyObject* PyUnicode_DecodeRawUnicodeEscape (const char *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the Raw-Unicode-Escape encoded string `s'.  Return
     ‘NULL’ if an exception was raised by the codec.

 -- C 函数: PyObject* PyUnicode_AsRawUnicodeEscapeString
          (PyObject *unicode)
     `Return value: New reference.'  Encode a Unicode object using
     Raw-Unicode-Escape and return the result as a bytes object.  Error
     handling is "strict".  Return ‘NULL’ if an exception was raised by
     the codec.

 -- C 函数: PyObject* PyUnicode_EncodeRawUnicodeEscape (const
          Py_UNICODE *s, Py_ssize_t size)
     `Return value: New reference.'  Encode the *note Py_UNICODE: af6.
     buffer of the given `size' using Raw-Unicode-Escape and return a
     bytes object.  Return ‘NULL’ if an exception was raised by the
     codec.

     Deprecated since version 3.3, will be removed in version 3.11: Part
     of the old-style *note Py_UNICODE: af6. API; please migrate to
     using *note PyUnicode_AsRawUnicodeEscapeString(): b0d. or *note
     PyUnicode_AsEncodedString(): 3e0e.


File: python.info,  Node: Latin-1 Codecs,  Next: ASCII Codecs,  Prev: Raw-Unicode-Escape Codecs,  Up: Built-in Codecs

7.8.3.23 Latin-1 Codecs
.......................

These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256
Unicode ordinals and only these are accepted by the codecs during
encoding.

 -- C 函数: PyObject* PyUnicode_DecodeLatin1 (const char *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the Latin-1 encoded string `s'.  Return ‘NULL’ if
     an exception was raised by the codec.

 -- C 函数: PyObject* PyUnicode_AsLatin1String (PyObject *unicode)
     `Return value: New reference.'  Encode a Unicode object using
     Latin-1 and return the result as Python bytes object.  Error
     handling is "strict".  Return ‘NULL’ if an exception was raised by
     the codec.

 -- C 函数: PyObject* PyUnicode_EncodeLatin1 (const Py_UNICODE *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Encode the *note Py_UNICODE: af6.
     buffer of the given `size' using Latin-1 and return a Python bytes
     object.  Return ‘NULL’ if an exception was raised by the codec.

     Deprecated since version 3.3, will be removed in version 3.11: Part
     of the old-style *note Py_UNICODE: af6. API; please migrate to
     using *note PyUnicode_AsLatin1String(): b0f. or *note
     PyUnicode_AsEncodedString(): 3e0e.


File: python.info,  Node: ASCII Codecs,  Next: Character Map Codecs,  Prev: Latin-1 Codecs,  Up: Built-in Codecs

7.8.3.24 ASCII Codecs
.....................

These are the ASCII codec APIs.  Only 7-bit ASCII data is accepted.  All
other codes generate errors.

 -- C 函数: PyObject* PyUnicode_DecodeASCII (const char *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the ASCII encoded string `s'.  Return ‘NULL’ if an
     exception was raised by the codec.

 -- C 函数: PyObject* PyUnicode_AsASCIIString (PyObject *unicode)
     `Return value: New reference.'  Encode a Unicode object using ASCII
     and return the result as Python bytes object.  Error handling is
     "strict".  Return ‘NULL’ if an exception was raised by the codec.

 -- C 函数: PyObject* PyUnicode_EncodeASCII (const Py_UNICODE *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Encode the *note Py_UNICODE: af6.
     buffer of the given `size' using ASCII and return a Python bytes
     object.  Return ‘NULL’ if an exception was raised by the codec.

     Deprecated since version 3.3, will be removed in version 3.11: Part
     of the old-style *note Py_UNICODE: af6. API; please migrate to
     using *note PyUnicode_AsASCIIString(): b11. or *note
     PyUnicode_AsEncodedString(): 3e0e.


File: python.info,  Node: Character Map Codecs,  Next: MBCS codecs for Windows,  Prev: ASCII Codecs,  Up: Built-in Codecs

7.8.3.25 Character Map Codecs
.............................

This codec is special in that it can be used to implement many different
codecs (and this is in fact what was done to obtain most of the standard
codecs included in the ‘encodings’ package).  The codec uses mapping to
encode and decode characters.  The mapping objects provided must support
the *note __getitem__(): 280. mapping interface; dictionaries and
sequences work well.

These are the mapping codec APIs:

 -- C 函数: PyObject* PyUnicode_DecodeCharmap (const char *data,
          Py_ssize_t size, PyObject *mapping, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the encoded string `s' using the given `mapping'
     object.  Return ‘NULL’ if an exception was raised by the codec.

     If `mapping' is ‘NULL’, Latin-1 decoding will be applied.  Else
     `mapping' must map bytes ordinals (integers in the range from 0 to
     255) to Unicode strings, integers (which are then interpreted as
     Unicode ordinals) or ‘None’.  Unmapped data bytes – ones which
     cause a *note LookupError: 166d, as well as ones which get mapped
     to ‘None’, ‘0xFFFE’ or ‘'\ufffe'’, are treated as undefined
     mappings and cause an error.

 -- C 函数: PyObject* PyUnicode_AsCharmapString (PyObject *unicode,
          PyObject *mapping)
     `Return value: New reference.'  Encode a Unicode object using the
     given `mapping' object and return the result as a bytes object.
     Error handling is "strict".  Return ‘NULL’ if an exception was
     raised by the codec.

     The `mapping' object must map Unicode ordinal integers to bytes
     objects, integers in the range from 0 to 255 or ‘None’.  Unmapped
     character ordinals (ones which cause a *note LookupError: 166d.) as
     well as mapped to ‘None’ are treated as "undefined mapping" and
     cause an error.

 -- C 函数: PyObject* PyUnicode_EncodeCharmap (const Py_UNICODE *s,
          Py_ssize_t size, PyObject *mapping, const char *errors)
     `Return value: New reference.'  Encode the *note Py_UNICODE: af6.
     buffer of the given `size' using the given `mapping' object and
     return the result as a bytes object.  Return ‘NULL’ if an exception
     was raised by the codec.

     Deprecated since version 3.3, will be removed in version 3.11: Part
     of the old-style *note Py_UNICODE: af6. API; please migrate to
     using *note PyUnicode_AsCharmapString(): 3e27. or *note
     PyUnicode_AsEncodedString(): 3e0e.

The following codec API is special in that maps Unicode to Unicode.

 -- C 函数: PyObject* PyUnicode_Translate (PyObject *str,
          PyObject *table, const char *errors)
     `Return value: New reference.'  Translate a string by applying a
     character mapping table to it and return the resulting Unicode
     object.  Return ‘NULL’ if an exception was raised by the codec.

     The mapping table must map Unicode ordinal integers to Unicode
     ordinal integers or ‘None’ (causing deletion of the character).

     Mapping tables need only provide the *note __getitem__(): 280.
     interface; dictionaries and sequences work well.  Unmapped
     character ordinals (ones which cause a *note LookupError: 166d.)
     are left untouched and are copied as-is.

     `errors' has the usual meaning for codecs.  It may be ‘NULL’ which
     indicates to use the default error handling.

 -- C 函数: PyObject* PyUnicode_TranslateCharmap (const Py_UNICODE *s,
          Py_ssize_t size, PyObject *mapping, const char *errors)
     `Return value: New reference.'  Translate a *note Py_UNICODE: af6.
     buffer of the given `size' by applying a character `mapping' table
     to it and return the resulting Unicode object.  Return ‘NULL’ when
     an exception was raised by the codec.

     Deprecated since version 3.3, will be removed in version 3.11: Part
     of the old-style *note Py_UNICODE: af6. API; please migrate to
     using *note PyUnicode_Translate(): 3e28.  or *note generic codec
     based API: 5f7.


File: python.info,  Node: MBCS codecs for Windows,  Next: Methods & Slots,  Prev: Character Map Codecs,  Up: Built-in Codecs

7.8.3.26 MBCS codecs for Windows
................................

These are the MBCS codec APIs.  They are currently only available on
Windows and use the Win32 MBCS converters to implement the conversions.
Note that MBCS (or DBCS) is a class of encodings, not just one.  The
target encoding is defined by the user settings on the machine running
the codec.

 -- C 函数: PyObject* PyUnicode_DecodeMBCS (const char *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the MBCS encoded string `s'.  Return ‘NULL’ if an
     exception was raised by the codec.

 -- C 函数: PyObject* PyUnicode_DecodeMBCSStateful (const char *s,
          Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
     `Return value: New reference.'  If `consumed' is ‘NULL’, behave
     like *note PyUnicode_DecodeMBCS(): 3e2a.  If `consumed' is not
     ‘NULL’, *note PyUnicode_DecodeMBCSStateful(): 3e2b. will not decode
     trailing lead byte and the number of bytes that have been decoded
     will be stored in `consumed'.

 -- C 函数: PyObject* PyUnicode_AsMBCSString (PyObject *unicode)
     `Return value: New reference.'  Encode a Unicode object using MBCS
     and return the result as Python bytes object.  Error handling is
     "strict".  Return ‘NULL’ if an exception was raised by the codec.

 -- C 函数: PyObject* PyUnicode_EncodeCodePage (int code_page,
          PyObject *unicode, const char *errors)
     `Return value: New reference.'  Encode the Unicode object using the
     specified code page and return a Python bytes object.  Return
     ‘NULL’ if an exception was raised by the codec.  Use ‘CP_ACP’ code
     page to get the MBCS encoder.

     3.3 新版功能.

 -- C 函数: PyObject* PyUnicode_EncodeMBCS (const Py_UNICODE *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Encode the *note Py_UNICODE: af6.
     buffer of the given `size' using MBCS and return a Python bytes
     object.  Return ‘NULL’ if an exception was raised by the codec.

     Deprecated since version 3.3, will be removed in version 4.0: Part
     of the old-style *note Py_UNICODE: af6. API; please migrate to
     using *note PyUnicode_AsMBCSString(): b15, *note
     PyUnicode_EncodeCodePage(): b16. or *note
     PyUnicode_AsEncodedString(): 3e0e.


File: python.info,  Node: Methods & Slots,  Prev: MBCS codecs for Windows,  Up: Built-in Codecs

7.8.3.27 Methods & Slots
........................


File: python.info,  Node: Methods and Slot Functions,  Prev: Built-in Codecs,  Up: Unicode对象和编码解码器

7.8.3.28 Methods and Slot Functions
...................................

The following APIs are capable of handling Unicode objects and strings
on input (we refer to them as strings in the descriptions) and return
Unicode objects or integers as appropriate.

They all return ‘NULL’ or ‘-1’ if an exception occurs.

 -- C 函数: PyObject* PyUnicode_Concat (PyObject *left, PyObject *right)
     `Return value: New reference.'  Concat two strings giving a new
     Unicode string.

 -- C 函数: PyObject* PyUnicode_Split (PyObject *s, PyObject *sep,
          Py_ssize_t maxsplit)
     `Return value: New reference.'  Split a string giving a list of
     Unicode strings.  If `sep' is ‘NULL’, splitting will be done at all
     whitespace substrings.  Otherwise, splits occur at the given
     separator.  At most `maxsplit' splits will be done.  If negative,
     no limit is set.  Separators are not included in the resulting
     list.

 -- C 函数: PyObject* PyUnicode_Splitlines (PyObject *s, int keepend)
     `Return value: New reference.'  Split a Unicode string at line
     breaks, returning a list of Unicode strings.  CRLF is considered to
     be one line break.  If `keepend' is ‘0’, the Line break characters
     are not included in the resulting strings.

 -- C 函数: PyObject* PyUnicode_Join (PyObject *separator,
          PyObject *seq)
     `Return value: New reference.'  Join a sequence of strings using
     the given `separator' and return the resulting Unicode string.

 -- C 函数: Py_ssize_t PyUnicode_Tailmatch (PyObject *str,
          PyObject *substr, Py_ssize_t start, Py_ssize_t end,
          int direction)

     Return ‘1’ if `substr' matches ‘str[start:end]’ at the given tail
     end (`direction' == ‘-1’ means to do a prefix match, `direction' ==
     ‘1’ a suffix match), ‘0’ otherwise.  Return ‘-1’ if an error
     occurred.

 -- C 函数: Py_ssize_t PyUnicode_Find (PyObject *str, PyObject *substr,
          Py_ssize_t start, Py_ssize_t end, int direction)

     Return the first position of `substr' in ‘str[start:end]’ using the
     given `direction' (`direction' == ‘1’ means to do a forward search,
     `direction' == ‘-1’ a backward search).  The return value is the
     index of the first match; a value of ‘-1’ indicates that no match
     was found, and ‘-2’ indicates that an error occurred and an
     exception has been set.

 -- C 函数: Py_ssize_t PyUnicode_FindChar (PyObject *str, Py_UCS4 ch,
          Py_ssize_t start, Py_ssize_t end, int direction)

     Return the first position of the character `ch' in ‘str[start:end]’
     using the given `direction' (`direction' == ‘1’ means to do a
     forward search, `direction' == ‘-1’ a backward search).  The return
     value is the index of the first match; a value of ‘-1’ indicates
     that no match was found, and ‘-2’ indicates that an error occurred
     and an exception has been set.

     3.3 新版功能.

     在 3.7 版更改: `start' and `end' are now adjusted to behave like
     ‘str[start:end]’.

 -- C 函数: Py_ssize_t PyUnicode_Count (PyObject *str, PyObject *substr,
          Py_ssize_t start, Py_ssize_t end)

     Return the number of non-overlapping occurrences of `substr' in
     ‘str[start:end]’.  Return ‘-1’ if an error occurred.

 -- C 函数: PyObject* PyUnicode_Replace (PyObject *str,
          PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)
     `Return value: New reference.'  Replace at most `maxcount'
     occurrences of `substr' in `str' with `replstr' and return the
     resulting Unicode object.  `maxcount' == ‘-1’ means replace all
     occurrences.

 -- C 函数: int PyUnicode_Compare (PyObject *left, PyObject *right)

     Compare two strings and return ‘-1’, ‘0’, ‘1’ for less than, equal,
     and greater than, respectively.

     This function returns ‘-1’ upon failure, so one should call *note
     PyErr_Occurred(): 3b02. to check for errors.

 -- C 函数: int PyUnicode_CompareWithASCIIString (PyObject *uni, const
          char *string)

     Compare a Unicode object, `uni', with `string' and return ‘-1’,
     ‘0’, ‘1’ for less than, equal, and greater than, respectively.  It
     is best to pass only ASCII-encoded strings, but the function
     interprets the input string as ISO-8859-1 if it contains non-ASCII
     characters.

     This function does not raise exceptions.

 -- C 函数: PyObject* PyUnicode_RichCompare (PyObject *left,
          PyObject *right, int op)
     `Return value: New reference.'  Rich compare two Unicode strings
     and return one of the following:

        * ‘NULL’ in case an exception was raised

        * ‘Py_True’ or ‘Py_False’ for successful comparisons

        * ‘Py_NotImplemented’ in case the type combination is unknown

     Possible values for `op' are ‘Py_GT’, ‘Py_GE’, ‘Py_EQ’, ‘Py_NE’,
     ‘Py_LT’, and ‘Py_LE’.

 -- C 函数: PyObject* PyUnicode_Format (PyObject *format,
          PyObject *args)
     `Return value: New reference.'  Return a new string object from
     `format' and `args'; this is analogous to ‘format % args’.

 -- C 函数: int PyUnicode_Contains (PyObject *container,
          PyObject *element)

     Check whether `element' is contained in `container' and return true
     or false accordingly.

     `element' has to coerce to a one element Unicode string.  ‘-1’ is
     returned if there was an error.

 -- C 函数: void PyUnicode_InternInPlace (PyObject **string)

     Intern the argument `*string' in place.  The argument must be the
     address of a pointer variable pointing to a Python Unicode string
     object.  If there is an existing interned string that is the same
     as `*string', it sets `*string' to it (decrementing the reference
     count of the old string object and incrementing the reference count
     of the interned string object), otherwise it leaves `*string' alone
     and interns it (incrementing its reference count).  (Clarification:
     even though there is a lot of talk about reference counts, think of
     this function as reference-count-neutral; you own the object after
     the call if and only if you owned it before the call.)

 -- C 函数: PyObject* PyUnicode_InternFromString (const char *v)
     `Return value: New reference.'  A combination of *note
     PyUnicode_FromString(): 3b93. and *note PyUnicode_InternInPlace():
     3e37, returning either a new Unicode string object that has been
     interned, or a new ("owned") reference to an earlier interned
     string object with the same value.


File: python.info,  Node: 元组对象,  Next: 结构序列对象,  Prev: Unicode对象和编码解码器,  Up: 序列对象

7.8.3.29 元组对象
.................

 -- C 类型: PyTupleObject

     这个 *note PyObject: 4c2. 的子类型代表一个 Python 的元组对象。

 -- C 变量: PyTypeObject PyTuple_Type

     *note PyTypeObject: 2d7. 的实例代表一个 Python 元组类型，这与
     Python 层面的 *note tuple: 486. 是相同的对象。

 -- C 函数: int PyTuple_Check (PyObject *p)

     如果 `p' 是一个元组对象或者元组类型的子类型的实例，则返回真值。

 -- C 函数: int PyTuple_CheckExact (PyObject *p)

     如果 `p' 是一个元组对象，而不是一个元组子类型的实例，则返回真值。

 -- C 函数: PyObject* PyTuple_New (Py_ssize_t len)
     `Return value: New reference.' 成功时返回一个新的元组对象，长度为
     `len'，失败时返回“NULL”。

 -- C 函数: PyObject* PyTuple_Pack (Py_ssize_t n, ...)
     `Return value: New reference.' 成功时返回一个新的元组对象，大小为
     `n' ，失败时返回 ‘NULL’。 元组值初始化为指向 Python 对象的后续 `n'
     C 参数。 ‘PyTuple_Pack(2, a, b)’ 和 ‘Py_BuildValue("(OO)", a, b)’ 相
     等。

 -- C 函数: Py_ssize_t PyTuple_Size (PyObject *p)

     获取指向元组对象的指针，并返回该元组的大小。

 -- C 函数: Py_ssize_t PyTuple_GET_SIZE (PyObject *p)

     返回元组*p*的大小，它必须是非‘‘NULL‘‘并且指向一个元组；不执行错误检
     查

 -- C 函数: PyObject* PyTuple_GetItem (PyObject *p, Py_ssize_t pos)
     `Return value: Borrowed reference.' 返回 `p' 所指向的元组中，位于
     `pos' 处的对象。 如果 `pos' 超出界限，返回 ‘NULL’ ，并抛出一个
     *note IndexError: e7d. 异常。

 -- C 函数: PyObject* PyTuple_GET_ITEM (PyObject *p, Py_ssize_t pos)
     `Return value: Borrowed reference.' 类似于 *note PyTuple_GetItem():
     3b1f.，但不检查其参数。

 -- C 函数: PyObject* PyTuple_GetSlice (PyObject *p, Py_ssize_t low,
          Py_ssize_t high)
     `Return value: New reference.' 返回*p*所指向的元组的切片，在*low*和
     *high*之间，或者在失败时返回‘‘NULL‘‘。这等同于Python表达式：
     ‘p[low:high]’ 。不支持从列表末尾索引。

 -- C 函数: int PyTuple_SetItem (PyObject *p, Py_ssize_t pos,
          PyObject *o)

     在 `p' 指向的元组的 `pos' 位置插入对对象 `o' 的引用。 成功时返回
     ‘0’；如果 `pos' 越界，则返回 ‘-1’，并抛出一个 *note IndexError:
     e7d. 异常。

          注解: 此函数会“窃取”对*o*的引用，并丢弃对元组中已在受影响位置
          的条目的引用。

 -- C 函数: void PyTuple_SET_ITEM (PyObject *p, Py_ssize_t pos,
          PyObject *o)

     类似于 *note PyTuple_SetItem(): 3b24.，但不进行错误检查，并且应该
     `只是' 被用来填充全新的元组。

          注解: 这个宏会“偷走”一个对 `o' 的引用，但与 *note
          PyTuple_SetItem(): 3b24. 不同，它 `不会' 丢弃对任何被替换项的
          引用；元组中位于 `pos' 位置的任何引用都将被泄漏。

 -- C 函数: int _PyTuple_Resize (PyObject **p, Py_ssize_t newsize)

     可以用于调整元组的大小。 `newsize' 将是元组的新长度。 因为元组 `被
     认为' 是不可变的，所以只有在对象仅有一个引用时，才应该使用它。 如果
     元组已经被代码的其他部分所引用，请不要使用此项。 元组在最后总是会增
     长或缩小。 把它看作是销毁旧元组并创建一个新元组，只会更有效。 成功
     时返回 ‘0’ 。 客户端代码不应假定 ‘*p’ 的结果值将与调用此函数之前的
     值相同。 如果替换了 ‘*p’ 引用的对象，则原始的 ‘*p’ 将被销毁。 失败
     时，返回‘‘-1‘‘，将 ‘*p’ 设置为 ‘NULL’，并引发 *note MemoryError:
     efc. 或者 *note SystemError: 604.。

 -- C 函数: int PyTuple_ClearFreeList ()

     清空释放列表。 返回所释放的条目数。


File: python.info,  Node: 结构序列对象,  Next: 列表对象,  Prev: 元组对象,  Up: 序列对象

7.8.3.30 结构序列对象
.....................

结构序列对象是等价于 *note namedtuple(): 1b7. 的 C 对象，即一个序列，其
中的条目也可以通过属性访问。 要创建结构序列，你首先必须创建特定的结构序
列类型。

 -- C 函数: PyTypeObject* PyStructSequence_NewType
          (PyStructSequence_Desc *desc)
     `Return value: New reference.' 根据 `desc' 中的数据创建一个新的结构
     序列类型，如下所述。 可以使用 *note PyStructSequence_New(): 3e49. 创
     建结果类型的实例。

 -- C 函数: void PyStructSequence_InitType (PyTypeObject *type,
          PyStructSequence_Desc *desc)

     从*desc*就地初始化结构序列类型*type*。

 -- C 函数: int PyStructSequence_InitType2 (PyTypeObject *type,
          PyStructSequence_Desc *desc)

     与 ‘PyStructSequence_InitType’ 相同，但成功时返回 ‘0’ ，失败时返回
     ‘-1’ 。

     3.4 新版功能.

 -- C 类型: PyStructSequence_Desc

     包含要创建的结构序列类型的元信息。

     域                      C 类型                             含义
                                                                
     ------------------------------------------------------------------------------------------------------
                                                                
     ‘name’                  ‘const char *’                     结构序列类型的名称
                                                                
                                                                
     ‘doc’                   ‘const char *’                     指向要忽略类型的文档字符串或 ‘NULL’ 的指
                                                                针
                                                                
                                                                
     ‘fields’                ‘PyStructSequence_Field *’         指向以 ‘NULL’ 结尾的数组的指针，其字段名
                                                                称为新类型
                                                                
                                                                
     ‘n_in_sequence’         ‘int’                              Python侧可见的字段数（如果用作元组）
                                                                

 -- C 类型: PyStructSequence_Field

     描述结构序列的一个字段。 当结构序列被建模为元组时，所有字段的类型都
     是 *note PyObject*: 4c2.。 在 *note PyStructSequence_Desc: 431. 的
     ‘fields’ 数组中的索引确定了结构序列描述的是哪个字段。

     域              C 类型                 含义
                                            
     -------------------------------------------------------------------------------------
                                            
     ‘name’          ‘const char *’         字段的名称或‘‘NULL‘‘ ，若要结束命名字段的列
                                            表，请设置为：
                                            *note PyStructSequence_UnnamedField: 3e4a.
                                            以保留未命名字段
                                            
                                            
     ‘doc’           ‘const char *’         要忽略的字段docstring或‘‘NULL‘‘
                                            

 -- C 变量: char* PyStructSequence_UnnamedField

     字段名的特殊值将保持未命名状态。

 -- C 函数: PyObject* PyStructSequence_New (PyTypeObject *type)
     `Return value: New reference.' 创建 `type' 的实例，该实例必须使用
     *note PyStructSequence_NewType(): 3e48. 创建。

 -- C 函数: PyObject* PyStructSequence_GetItem (PyObject *p,
          Py_ssize_t pos)
     `Return value: Borrowed reference.' 返回*p*所指向的结构序列中，位于
     *pos*处的对象。不需要进行边界检查。

 -- C 函数: PyObject* PyStructSequence_GET_ITEM (PyObject *p,
          Py_ssize_t pos)
     `Return value: Borrowed reference.'  *note
     PyStructSequence_GetItem(): 3e4b. 的宏版本。

 -- C 函数: void PyStructSequence_SetItem (PyObject *p, Py_ssize_t pos,
          PyObject *o)

     将结构序列 `p' 的索引 `pos' 处的字段设置为值 `o'。 与 *note
     PyTuple_SET_ITEM(): 3e45. 一样，它应该只用于填充全新的实例。

          注解: 这个函数“窃取”了指向*o*的一个引用。

 -- C 函数: void PyStructSequence_SET_ITEM (PyObject *p,
          Py_ssize_t *pos, PyObject *o)

     *note PyStructSequence_SetItem(): 3e4d. 的宏版本。

          注解: 这个函数“窃取”了指向*o*的一个引用。


File: python.info,  Node: 列表对象,  Prev: 结构序列对象,  Up: 序列对象

7.8.3.31 列表对象
.................

 -- C 类型: PyListObject

     这个C类型 *note PyObject: 4c2. 的子类型代表一个Python列表对象。

 -- C 变量: PyTypeObject PyList_Type

     这是个属于 *note PyTypeObject: 2d7. 的代表Python列表类型的实例。在
     Python层面和类型 *note list: 263. 是同一个对象。

 -- C 函数: int PyList_Check (PyObject *p)

     如果 `p' 是一个列表对象或者是一个列表类型的子类型实例时，返回真。

 -- C 函数: int PyList_CheckExact (PyObject *p)

     当 `p' 是一个列表对象，但是不是列表类型的子类型实例时，返回真。

 -- C 函数: PyObject* PyList_New (Py_ssize_t len)
     `Return value: New reference.' 成功时返回一个长度为 `len' 的新列表
     ，失败时返回 ‘NULL’。

          注解: 当 `len' 大于零时，被返回的列表对象项目被设成 ‘NULL’。因
          此你不能用类似C函数 *note PySequence_SetItem(): 105f. 的抽象
          API或者用C函数 *note PyList_SetItem(): 3b25. 将所有项目设置成
          真实对象前对Python代码公开这个对象。

 -- C 函数: Py_ssize_t PyList_Size (PyObject *list)

     返回 `list' 中列表对象的长度；这等于在列表对象调用 ‘len(list)’ 。

 -- C 函数: Py_ssize_t PyList_GET_SIZE (PyObject *list)

     宏版本的C函数 *note PyList_Size(): d86. ，没有错误检测。

 -- C 函数: PyObject* PyList_GetItem (PyObject *list, Py_ssize_t index)
     `Return value: Borrowed reference.' 返回 `list' 所指向列表中
     `index' 位置上的对象。 位置值必须为非负数；不支持从列表末尾进行索引
     。 如果 `index' 超出边界 (<0 or >=len(list))，则返回 ‘NULL’ 并设置
     *note IndexError: e7d. 异常。

 -- C 函数: PyObject* PyList_GET_ITEM (PyObject *list, Py_ssize_t i)
     `Return value: Borrowed reference.' 宏版本的C函数 *note
     PyList_GetItem(): 3b20. ，没有错误检测。

 -- C 函数: int PyList_SetItem (PyObject *list, Py_ssize_t index,
          PyObject *item)

     将列表中索引为 `index' 的项设为 `item'。 成功时返回 ‘0’。 如果
     `index' 超出范围则返回 ‘-1’ 并设定 *note IndexError: e7d. 异常。

          注解: 此函数会“偷走”一个对 `item' 的引用并丢弃一个对列表中受影
          响位置上的已有条目的引用。

 -- C 函数: void PyList_SET_ITEM (PyObject *list, Py_ssize_t i,
          PyObject *o)

     不带错误检测的宏版本 *note PyList_SetItem(): 3b25.。 这通常只被用于
     新列表中之前没有内容的位置进行填充。

          注解: 该宏会“偷走”一个对 `item' 的引用，但与 *note
          PyList_SetItem(): 3b25. 不同的是它 `不会' 丢弃对任何被替换条目
          的引用；在 `list' 的 `i' 位置上的任何引用都将被泄露。

 -- C 函数: int PyList_Insert (PyObject *list, Py_ssize_t index,
          PyObject *item)

     将条目 `item' 插入到列表 `list' 索引号 `index' 之前的位置。 如果成
     功将返回 ‘0’；如果不成功则返回 ‘-1’ 并设置一个异常。 相当于
     ‘list.insert(index, item)’。

 -- C 函数: int PyList_Append (PyObject *list, PyObject *item)

     将对象 `item' 添加到列表 `list' 的末尾。 如果成功将返回 ‘0’；如果不
     成功则返回 ‘-1’ 并设置一个异常。 相当于 ‘list.append(item)’。

 -- C 函数: PyObject* PyList_GetSlice (PyObject *list, Py_ssize_t low,
          Py_ssize_t high)
     `Return value: New reference.' 返回一个对象列表，包含 `list' 当中位
     于 `low' 和 `high' `之间' 的对象。 如果不成功则返回 ‘NULL’ 并设置异
     常。 相当于 ‘list[low:high]’。 不支持从列表末尾进行索引。

 -- C 函数: int PyList_SetSlice (PyObject *list, Py_ssize_t low,
          Py_ssize_t high, PyObject *itemlist)

     将 `list' 当中 `low' 与 `high' 之间的切片设为 `itemlist' 的内容。 相
     当于 ‘list[low:high] = itemlist’。 `itemlist' 可以为 ‘NULL’，表示赋
     值为一个空列表（删除切片）。 成功时返回 ‘0’，失败时返回 ‘-1’。 这里
     不支持从列表末尾进行索引。

 -- C 函数: int PyList_Sort (PyObject *list)

     对 `list' 中的条目进行原地排序。 成功时返回 ‘0’，失败时返回 ‘-1’。
     这等价于 ‘list.sort()’。

 -- C 函数: int PyList_Reverse (PyObject *list)

     对 `list' 中的条目进行原地反转。 成功时返回 ‘0’，失败时返回 ‘-1’。
     这等价于 ‘list.reverse()’。

 -- C 函数: PyObject* PyList_AsTuple (PyObject *list)
     `Return value: New reference.'

     返回一个新的元组对象，其中包含 `list' 的内容；等价于 ‘tuple(list)’。

 -- C 函数: int PyList_ClearFreeList ()

     清空释放列表。 返回所释放的条目数。

     3.3 新版功能.


File: python.info,  Node: 容器对象,  Next: 函数对象<2>,  Prev: 序列对象,  Up: 具体的对象层

7.8.4 容器对象
--------------

* Menu:

* 字典对象::
* 集合对象::


File: python.info,  Node: 字典对象,  Next: 集合对象,  Up: 容器对象

7.8.4.1 字典对象
................

 -- C 类型: PyDictObject

     这个 *note PyObject: 4c2. 的子类型代表一个Python字典对象。

 -- C 变量: PyTypeObject PyDict_Type

     Python字典类型表示为 *note PyTypeObject: 2d7. 的实例。这与Python层
     面的 *note dict: 1b9. 是相同的对象。

 -- C 函数: int PyDict_Check (PyObject *p)

     如果 `p' 是字典对象或者字典类型的子类型的实例，则返回真。

 -- C 函数: int PyDict_CheckExact (PyObject *p)

     如果 `p' 是字典对象但不是字典类型的子类型的实例，则返回真。

 -- C 函数: PyObject* PyDict_New ()
     `Return value: New reference.' 返回一个新的空字典，失败时返回
     ‘NULL’。

 -- C 函数: PyObject* PyDictProxy_New (PyObject *mapping)
     `Return value: New reference.' 返回 *note types.MappingProxyType:
     abe. 对象，用于强制执行只读行为的映射。这通常用于创建视图以防止修改
     非动态类类型的字典。

 -- C 函数: void PyDict_Clear (PyObject *p)

     清空现有字典的所有键值对。

 -- C 函数: int PyDict_Contains (PyObject *p, PyObject *key)

     确定 `key' 是否包含在字典 `p' 中。如果 `key' 匹配上 `p' 的某一项，
     则返回 ‘1’ ，否则返回 ‘0’ 。返回 ‘-1’ 表示出错。这等同于Python表达
     式 ‘key in p’ 。

 -- C 函数: PyObject* PyDict_Copy (PyObject *p)
     `Return value: New reference.' 返回与 `p' 包含相同键值对的新字典。

 -- C 函数: int PyDict_SetItem (PyObject *p, PyObject *key,
          PyObject *val)

     使用 `key' 作为键将 `val' 插入字典 `p'。 `key' 必须为 *note
     hashable: 1439.；如果不是，则将引发 *note TypeError: 193.。 成功时
     返回 ‘0’，失败时返回 ‘-1’。 此函数 `不会' 附带对 `val' 的引用。

 -- C 函数: int PyDict_SetItemString (PyObject *p, const char *key,
          PyObject *val)

     使用 `key' 作为键将 `val' 插入到字典 `p'。 `key' 应当为 ‘const
     char*’。 键对象是使用 ‘PyUnicode_FromString(key)’ 创建的。 成功时返
     回 ‘0’，失败时返回 ‘-1’。 此函数 `不会' 附带对 `val' 的引用。

 -- C 函数: int PyDict_DelItem (PyObject *p, PyObject *key)

     移除字典 `p' 中键为 `key' 的条目。 `key' 必须是可哈希的；如果不是，
     则会引发 *note TypeError: 193.。 如果字典中没有 `key'，则会引发
     *note KeyError: 2c8.。 成功时返回 ‘0’，失败时返回 ‘-1’。

 -- C 函数: int PyDict_DelItemString (PyObject *p, const char *key)

     移除字典 `p' 中由字符串 `key' 指定的键的条目。 如果字典中没有
     `key'，则会引发 *note KeyError: 2c8.。 成功时返回 ‘0’，失败时返回
     ‘-1’。

 -- C 函数: PyObject* PyDict_GetItem (PyObject *p, PyObject *key)
     `Return value: Borrowed reference.' 从字典 `p' 中返回以 `key' 为键
     的对象。 如果键名 `key' 不存在但 `没有' 设置一个异常则返回 ‘NULL’。

     需要注意的是，调用 *note __hash__(): 349. 和 *note __eq__(): 348. 方
     法产生的异常不会被抛出。改用 *note PyDict_GetItemWithError(): 3e6f.
     获得错误报告。

 -- C 函数: PyObject* PyDict_GetItemWithError (PyObject *p,
          PyObject *key)
     `Return value: Borrowed reference.'  *note PyDict_GetItem(): 3b21.
     的变种，它不会屏蔽异常。 当异常发生时将返回 ‘NULL’ `并且' 设置一个
     异常。 如果键不存在则返回 ‘NULL’ `并且不会' 设置一个异常。

 -- C 函数: PyObject* PyDict_GetItemString (PyObject *p, const
          char *key)
     `Return value: Borrowed reference.' 这与 *note PyDict_GetItem():
     3b21. 一样，但是 `key' 被指定为 ‘const char*’，而不是 *note
     PyObject*: 4c2.。

     需要注意的是，调用 *note __hash__(): 349. 、 *note __eq__(): 348. 方
     法和创建一个临时的字符串对象时产生的异常不会被抛出。改用 *note
     PyDict_GetItemWithError(): 3e6f. 获得错误报告。

 -- C 函数: PyObject* PyDict_SetDefault (PyObject *p, PyObject *key,
          PyObject *defaultobj)
     `Return value: Borrowed reference.' 这跟Python层面的 *note
     dict.setdefault(): 9c7. 一样。如果键 `key' 存在，它返回在字典 `p' 里
     面对应的值。如果键不存在，它会和值 `defaultobj' 一起插入并返回
     `defaultobj' 。这个函数只计算 `key' 的哈希函数一次，而不是在查找和
     插入时分别计算它。

     3.4 新版功能.

 -- C 函数: PyObject* PyDict_Items (PyObject *p)
     `Return value: New reference.' 返回一个包含字典中所有键值项的 *note
     PyListObject: 3d06.。

 -- C 函数: PyObject* PyDict_Keys (PyObject *p)
     `Return value: New reference.' 返回一个包含字典中所有键(keys)的
     *note PyListObject: 3d06.。

 -- C 函数: PyObject* PyDict_Values (PyObject *p)
     `Return value: New reference.' 返回一个包含字典中所有值(values)的
     *note PyListObject: 3d06.。

 -- C 函数: Py_ssize_t PyDict_Size (PyObject *p)

     返回字典中项目数，等价于对字典 `p' 使用 ‘len(p)’。

 -- C 函数: int PyDict_Next (PyObject *p, Py_ssize_t *ppos,
          PyObject **pkey, PyObject **pvalue)

     迭代字典 `p' 中的所有键值对。 在第一次调用此函数开始迭代之前，由
     `ppos' 所引用的 ‘Py_ssize_t’ 必须被初始化为 ‘0’；该函数将为字典中的
     每个键值对返回真值，一旦所有键值对都报告完毕则返回假值。 形参
     `pkey' 和 `pvalue' 应当指向 *note PyObject*: 4c2. 变量，它们将分别
     使用每个键和值来填充，或者也可以为 ‘NULL’。 通过它们返回的任何引用
     都是暂借的。 `ppos' 在迭代期间不应被更改。 它的值表示内部字典结构中
     的偏移量，并且由于结构是稀疏的，因此偏移量并不连续。

     例如

          PyObject *key, *value;
          Py_ssize_t pos = 0;

          while (PyDict_Next(self->dict, &pos, &key, &value)) {
              /* do something interesting with the values... */
              ...
          }

     字典 `p' 不应该在遍历期间发生改变。在遍历字典时，改变键中的值是安全
     的，但仅限于键的集合不发生改变。例如:

          PyObject *key, *value;
          Py_ssize_t pos = 0;

          while (PyDict_Next(self->dict, &pos, &key, &value)) {
              long i = PyLong_AsLong(value);
              if (i == -1 && PyErr_Occurred()) {
                  return -1;
              }
              PyObject *o = PyLong_FromLong(i + 1);
              if (o == NULL)
                  return -1;
              if (PyDict_SetItem(self->dict, key, o) < 0) {
                  Py_DECREF(o);
                  return -1;
              }
              Py_DECREF(o);
          }

 -- C 函数: int PyDict_Merge (PyObject *a, PyObject *b, int override)

     对映射对象 `b' 进行迭代，将键值对添加到字典 `a'。 `b' 可以是一个字
     典，或任何支持 *note PyMapping_Keys(): 434. 和 *note
     PyObject_GetItem(): 3bb5. 的对象。 如果 `override' 为真值，则如果在
     `b' 中找到相同的键则 `a' 中已存在的相应键值对将被替换，否则如果在
     `a' 中没有相同的键则只是添加键值对。 当成功时返回 ‘0’ 或者当引发异
     常时返回 ‘-1’。

 -- C 函数: int PyDict_Update (PyObject *a, PyObject *b)

     这与 C 中的 ‘PyDict_Merge(a, b, 1)’ 一样，也类似于 Python 中的
     ‘a.update(b)’，差别在于 *note PyDict_Update(): 3e77. 在第二个参数没
     有 "keys" 属性时不会回退到迭代键值对的序列。 当成功时返回 ‘0’ 或者
     当引发异常时返回 ‘-1’。

 -- C 函数: int PyDict_MergeFromSeq2 (PyObject *a, PyObject *seq2,
          int override)

     将 `seq2' 中的键值对更新或合并到字典 `a'。 `seq2' 必须为产生长度为
     2 的用作键值对的元素的可迭代对象。 当存在重复的键时，如果
     `override' 真值则最后出现的键胜出。 当成功时返回 ‘0’ 或者当引发异常
     时返回 ‘-1’。 等价的 Python 代码（返回值除外）:

          def PyDict_MergeFromSeq2(a, seq2, override):
              for key, value in seq2:
                  if override or key not in a:
                      a[key] = value

 -- C 函数: int PyDict_ClearFreeList ()

     清空释放列表。 返回所释放的条目数。

     3.3 新版功能.


File: python.info,  Node: 集合对象,  Prev: 字典对象,  Up: 容器对象

7.8.4.2 集合对象
................

这一章节详细介绍了 *note set: b77. 和 *note frozenset: bf6. 对象的公共
API。 任何未在下面列出的功能最好是使用抽象对象协议 (包括 *note
PyObject_CallMethod(): 3cc3, *note PyObject_RichCompareBool(): f57,
*note PyObject_Hash(): 3cc9, *note PyObject_Repr(): 970, *note
PyObject_IsTrue(): 3cca, *note PyObject_Print(): 105c. 以及 *note
PyObject_GetIter(): 3cd1.) 或者抽象数字协议 (包括 *note PyNumber_And():
3ce3, *note PyNumber_Subtract(): 3cd6, *note PyNumber_Or(): 3ce5, *note
PyNumber_Xor(): 3ce4, *note PyNumber_InPlaceAnd(): 3cef, *note
PyNumber_InPlaceSubtract(): 3ce7, *note PyNumber_InPlaceOr(): 3cf1. 以及
*note PyNumber_InPlaceXor(): 3cf0.) 来访问。

 -- C 类型: PySetObject

     这个 *note PyObject: 4c2. 的子类型被用来保存 *note set: b77. 和
     *note frozenset: bf6. 对象的内部数据。 它类似于 *note PyDictObject:
     3e64.，因为对于小尺寸集合来说它是固定大小的（很像元组的存储方式），
     并且对于中等和大尺寸集合来说它将指向单独的可变大小的内存块（很像列
     表的存储方式）。 此结构体的字段不应被视为公有并且可能发生改变。 所
     有访问应当通过已写入文档的 API 来进行，而不可通过操纵结构体中的值。

 -- C 变量: PyTypeObject PySet_Type

     这是一个 *note PyTypeObject: 2d7. 实例，表示 Python *note set: b77.
     类型。

 -- C 变量: PyTypeObject PyFrozenSet_Type

     这是一个 *note PyTypeObject: 2d7. 实例，表示 Python *note
     frozenset: bf6. 类型。

下列类型检查宏适用于指向任意 Python 对象的指针。 类似地，这些构造函数也
适用于任意可迭代的 Python 对象。

 -- C 函数: int PySet_Check (PyObject *p)

     如果 `p' 是一个 *note set: b77. 对象或者是其子类型的实例则返回真值
     。

 -- C 函数: int PyFrozenSet_Check (PyObject *p)

     如果 `p' 是一个 *note frozenset: bf6. 对象或者是其子类型的实例则返
     回真值。

 -- C 函数: int PyAnySet_Check (PyObject *p)

     如果 `p' 是一个 *note set: b77. 对象、*note frozenset: bf6. 对象或
     者是其子类型的实例则返回真值。

 -- C 函数: int PyAnySet_CheckExact (PyObject *p)

     如果 `p' 是一个 *note set: b77. 对象或 *note frozenset: bf6. 对象但
     不是其子类型的实例则返回真值。

 -- C 函数: int PyFrozenSet_CheckExact (PyObject *p)

     如果 `p' 是一个 *note frozenset: bf6. 对象但不是其子类型的实例则返
     回真值。

 -- C 函数: PyObject* PySet_New (PyObject *iterable)
     `Return value: New reference.' 返回一个新的 *note set: b77.，其中包
     含 `iterable' 所返回的对象。 `iterable' 可以为 ‘NULL’ 表示创建一个
     新的空集合。 成功时返回新的集合，失败时返回 ‘NULL’。 如果
     `iterable' 实际上不是可迭代对象则引发 *note TypeError: 193.。 该构
     造器也适用于拷贝集合 (‘c=set(s)’)。

 -- C 函数: PyObject* PyFrozenSet_New (PyObject *iterable)
     `Return value: New reference.' 返回一个新的 *note frozenset: bf6.，
     其中包含 `iterable' 所返回的对象。 `iterable' 可以为 ‘NULL’ 表示创
     建一个新的空冻结集合。 成功时返回新的冻结集合，失败时返回 ‘NULL’。
     如果 `iterable' 实际上不是可迭代对象则引发 *note TypeError: 193.。

下列函数和宏适用于 *note set: b77. 或 *note frozenset: bf6. 的实例或是其
子类型的实例。

 -- C 函数: Py_ssize_t PySet_Size (PyObject *anyset)

     返回 *note set: b77. 或 *note frozenset: bf6. 对象的长度。 等价于
     ‘len(anyset)’。 如果 `anyset' 不是 *note set: b77, *note frozenset:
     bf6. 或其子类型的实例则会引发 ‘PyExc_SystemError’。

 -- C 函数: Py_ssize_t PySet_GET_SIZE (PyObject *anyset)

     宏版本的 *note PySet_Size(): db8.，不带错误检测。

 -- C 函数: int PySet_Contains (PyObject *anyset, PyObject *key)

     如果找到返回 ‘1’，如果未找到返回 ‘0’，如果遇到错误则返回 ‘-1’。 不
     同于 Python *note __contains__(): d30. 方法，此函数不会自动将不可哈
     希的集合转换为临时的冻结集合。 如果 `key' 为不可哈希对象则会引发
     *note TypeError: 193.。 如果 `anyset' 不是 *note set: b77, *note
     frozenset: bf6. 或其子类型的实例则会引发 ‘PyExc_SystemError’。

 -- C 函数: int PySet_Add (PyObject *set, PyObject *key)

     添加 `key' 到一个 *note set: b77. 实例。 也可用于 *note frozenset:
     bf6. 实例（类似于 *note PyTuple_SetItem(): 3b24.，它可被用来为全新
     冻结集合在公开给其他代码之前填充全新的值）。 成功时返回 ‘0’，失败时
     返回 ‘-1’。 如果 `key' 为不可哈希对象则会引发 *note TypeError:
     193.。 如果没有增长空间则会引发 *note MemoryError: efc.。 如果
     `set' 不是 *note set: b77. 或其子类型的实例则会引发 *note
     SystemError: 604.。

下列函数适用于 *note set: b77. 或其子类型的实例，但不可用于 *note
frozenset: bf6. 或其子类型的实例。

 -- C 函数: int PySet_Discard (PyObject *set, PyObject *key)

     如果找到并移除返回 ‘1’，如果未找到（无操作）返回 ‘0’，如果遇到错误
     则返回 ‘-1’。 对于不存在的键不会引发 *note KeyError: 2c8.。 如果
     `key' 为不可哈希对象则会引发 *note TypeError: 193.。 不同于 Python
     ‘discard()’ 方法，此函数不会自动将不可哈希的集合转换为临时的冻结集
     合。 如果 `set' 不是 *note set: b77. 或其子类型的实例则会引发
     ‘PyExc_SystemError’。

 -- C 函数: PyObject* PySet_Pop (PyObject *set)
     `Return value: New reference.' 返回 `set' 中任意对象的新引用，并从
     `set' 中移除该对象。 失败时返回 ‘NULL’。 如果集合为空则会引发 *note
     KeyError: 2c8.。 如果 `set' 不是 *note set: b77. 或其子类型的实例则
     会引发 *note SystemError: 604.。

 -- C 函数: int PySet_Clear (PyObject *set)

     清空现有字典的所有键值对。

 -- C 函数: int PySet_ClearFreeList ()

     清空释放列表。 返回所释放的条目数。

     3.3 新版功能.


File: python.info,  Node: 函数对象<2>,  Next: 其他对象<2>,  Prev: 容器对象,  Up: 具体的对象层

7.8.5 函数对象
--------------

* Menu:

* 函数对象: 函数对象<3>.
* 实例方法对象::
* 方法对象: 方法对象<2>.
* Cell 对象::
* 代码对象: 代码对象<2>.


File: python.info,  Node: 函数对象<3>,  Next: 实例方法对象,  Up: 函数对象<2>

7.8.5.1 函数对象
................

有一些特定于 Python 函数的函数。

 -- C 类型: PyFunctionObject

     用于函数的 C 结构体。

 -- C 变量: PyTypeObject PyFunction_Type

     这是一个 *note PyTypeObject: 2d7. 实例并表示 Python 函数类型。 它作
     为 ‘types.FunctionType’ 向 Python 程序员公开。

 -- C 函数: int PyFunction_Check (PyObject *o)

     如果 `o' 是函数对象 (类型为 *note PyFunction_Type: 3e8f.) 则返回真
     值。 形参必须不为 ‘NULL’。

 -- C 函数: PyObject* PyFunction_New (PyObject *code, PyObject *globals)
     `Return value: New reference.' 返回与代码对象 `code' 关联的新函数对
     象。 `globals' 必须是一个字典，该函数可以访问全局变量。

     从代码对象中提取函数的文档字符串和名称。 `__module__' 会从
     `globals' 中提取。 参数 defaults, annotations 和 closure 设为
     ‘NULL’。 `__qualname__' 设为与函数名称相同的值。

 -- C 函数: PyObject* PyFunction_NewWithQualName (PyObject *code,
          PyObject *globals, PyObject *qualname)
     `Return value: New reference.' 类似 *note PyFunction_New(): 3e91.，
     但还允许设置函数对象的 ‘__qualname__’ 属性。 `qualname' 应当是
     unicode 对象或 ‘NULL’；如果是 ‘NULL’ 则 ‘__qualname__’ 属性设为与其
     ‘__name__’ 属性相同的值。

     3.3 新版功能.

 -- C 函数: PyObject* PyFunction_GetCode (PyObject *op)
     `Return value: Borrowed reference.' 返回与函数对象 `op' 关联的代码
     对象。

 -- C 函数: PyObject* PyFunction_GetGlobals (PyObject *op)
     `Return value: Borrowed reference.' 返回与函数对象*op*相关联的全局
     字典。

 -- C 函数: PyObject* PyFunction_GetModule (PyObject *op)
     `Return value: Borrowed reference.' 返回函数对象 `op' 的
     `__module__' 属性，通常为一个包含了模块名称的字符串，但可以通过
     Python 代码设为返回其他任意对象。

 -- C 函数: PyObject* PyFunction_GetDefaults (PyObject *op)
     `Return value: Borrowed reference.' 返回函数对象 `op' 的参数默认值
     。 这可以是一个参数元组或 ‘NULL’。

 -- C 函数: int PyFunction_SetDefaults (PyObject *op,
          PyObject *defaults)

     为函数对象 `op' 设置参数默认值。 `defaults' 必须为 ‘Py_None’ 或一个
     元组。

     失败时引发 *note SystemError: 604. 异常并返回 ‘-1’ 。

 -- C 函数: PyObject* PyFunction_GetClosure (PyObject *op)
     `Return value: Borrowed reference.' 返回关联到函数对象 `op' 的闭包
     。 这可以是 ‘NULL’ 或 cell 对象的元组。

 -- C 函数: int PyFunction_SetClosure (PyObject *op, PyObject *closure)

     设置关联到函数对象 `op' 的闭包。 `closure' 必须为 ‘Py_None’ 或 cell
     对象的元组。

     失败时引发 *note SystemError: 604. 异常并返回 ‘-1’ 。

 -- C 函数: PyObject *PyFunction_GetAnnotations (PyObject *op)
     `Return value: Borrowed reference.' 返回函数对象 `op' 的标注。 这可
     以是一个可变字典或 ‘NULL’。

 -- C 函数: int PyFunction_SetAnnotations (PyObject *op,
          PyObject *annotations)

     设置函数对象 `op' 的标注。 `annotations' 必须为一个字典或
     ‘Py_None’。

     失败时引发 *note SystemError: 604. 异常并返回 ‘-1’ 。


File: python.info,  Node: 实例方法对象,  Next: 方法对象<2>,  Prev: 函数对象<3>,  Up: 函数对象<2>

7.8.5.2 实例方法对象
....................

实例方法是 *note PyCFunction: de3. 的包装器，也是将 *note PyCFunction:
de3. 绑定到类对象的一种新方式。 它替代了原先的调用 ‘PyMethod_New(func,
NULL, class)’。

 -- C 变量: PyTypeObject PyInstanceMethod_Type

     这个 *note PyTypeObject: 2d7. 实例代表 Python 实例方法类型。 它并不
     对 Python 程序公开。

 -- C 函数: int PyInstanceMethod_Check (PyObject *o)

     如果 `o' 是实例方法对象 (类型为 *note PyInstanceMethod_Type: 3e9f.)
     则返回真值。 形参必须不为 ‘NULL’。

 -- C 函数: PyObject* PyInstanceMethod_New (PyObject *func)
     `Return value: New reference.' 返回一个新的实例方法对象，`func' 应
     为任意可调用对象，`func' 将在实例方法被调用时作为函数被调用。

 -- C 函数: PyObject* PyInstanceMethod_Function (PyObject *im)
     `Return value: Borrowed reference.' 返回关联到实例方法 `im' 的函数
     对象。

 -- C 函数: PyObject* PyInstanceMethod_GET_FUNCTION (PyObject *im)
     `Return value: Borrowed reference.' 宏版本的 *note
     PyInstanceMethod_Function(): 3ea2.，略去了错误检测。


File: python.info,  Node: 方法对象<2>,  Next: Cell 对象,  Prev: 实例方法对象,  Up: 函数对象<2>

7.8.5.3 方法对象
................

方法是绑定的函数对象。 方法总是会被绑定到一个用户自定义类的实例。 未绑定
方法（绑定到一个类的方法）已不再可用。

 -- C 变量: PyTypeObject PyMethod_Type

     这个 *note PyTypeObject: 2d7. 实例代表 Python 方法类型。 它作为
     ‘types.MethodType’ 向 Python 程序公开。

 -- C 函数: int PyMethod_Check (PyObject *o)

     如果 `o' 是方法对象 (类型为 *note PyMethod_Type: 3ea6.) 则返回真值
     。 形参必须不为 ‘NULL’。

 -- C 函数: PyObject* PyMethod_New (PyObject *func, PyObject *self)
     `Return value: New reference.' 返回一个新的方法对象，`func' 应为任
     意可调用对象，`self' 为该方法应绑定的实例。 在方法被调用时 `func' 将
     作为函数被调用。 `self' 必须不为 ‘NULL’。

 -- C 函数: PyObject* PyMethod_Function (PyObject *meth)
     `Return value: Borrowed reference.' 返回关联到方法 `meth' 的函数对
     象。

 -- C 函数: PyObject* PyMethod_GET_FUNCTION (PyObject *meth)
     `Return value: Borrowed reference.' 宏版本的 *note
     PyMethod_Function(): 3ea9.，略去了错误检测。

 -- C 函数: PyObject* PyMethod_Self (PyObject *meth)
     `Return value: Borrowed reference.' 返回关联到方法 `meth' 的实例。

 -- C 函数: PyObject* PyMethod_GET_SELF (PyObject *meth)
     `Return value: Borrowed reference.' 宏版本的 *note PyMethod_Self():
     3eab.，略去了错误检测。

 -- C 函数: int PyMethod_ClearFreeList ()

     清空释放列表。 返回所释放的条目数。


File: python.info,  Node: Cell 对象,  Next: 代码对象<2>,  Prev: 方法对象<2>,  Up: 函数对象<2>

7.8.5.4 Cell 对象
.................

“Cell”对象用于实现由多个作用域引用的变量。 对于每个这样的变量，一个
“Cell”对象为了存储该值而被创建；引用该值的每个堆栈框架的局部变量包含同样
使用该变量的对外部作用域的“Cell”引用。 访问该值时，将使用“Cell”中包含的
值而不是单元格对象本身。 这种对“Cell”对象的非关联化的引用需要支持生成的
字节码；访问时不会自动非关联化这些内容。 “Cell”对象在其他地方可能不太有
用。

 -- C 类型: PyCellObject

     用于Cell对象的C结构体。

 -- C 变量: PyTypeObject PyCell_Type

     与 Cell 对象对应的类型对​​象。

 -- C 函数: int PyCell_Check (ob)

     如果 `ob' 是一个 cell 对象则返回真值；`ob' 必须不为 ‘NULL’。

 -- C 函数: PyObject* PyCell_New (PyObject *ob)
     `Return value: New reference.' 创建并返回一个包含值 `ob' 的新 cell
     对象。形参可以为 ‘NULL’。

 -- C 函数: PyObject* PyCell_Get (PyObject *cell)
     `Return value: New reference.' 返回 cell 对象 `cell' 的内容。

 -- C 函数: PyObject* PyCell_GET (PyObject *cell)
     `Return value: Borrowed reference.' 返回 cell 对象 `cell' 的内容，
     但是不检测 `cell' 是否非 ‘NULL’ 并且为一个 cell 对象。

 -- C 函数: int PyCell_Set (PyObject *cell, PyObject *value)

     将 cell 对象 `cell' 的内容设为 `value'。 这将释放任何对 cell 对象当
     前内容的引用。 `value' 可以为 ‘NULL’。 `cell' 必须为非 ‘NULL’；如果
     它不是一个 cell 对象则将返回 ‘-1’。 如果设置成功则将返回 ‘0’。

 -- C 函数: void PyCell_SET (PyObject *cell, PyObject *value)

     将 cell 对象 `cell' 的值设为 `value'。 不会调整引用计数，并且不会进
     行检测以保证安全；`cell' 必须为非 ‘NULL’ 并且为一个 cell 对象。


File: python.info,  Node: 代码对象<2>,  Prev: Cell 对象,  Up: 函数对象<2>

7.8.5.5 代码对象
................

代码对象是 CPython 实现的低级细节。 每个代表一块尚未绑定到函数中的可执行
代码。

 -- C 类型: PyCodeObject

     用于描述代码对象的对象的 C 结构。 此类型字段可随时更改。

 -- C 变量: PyTypeObject PyCode_Type

     这是一个 *note PyTypeObject: 2d7. 实例，其表示Python的 *note code:
     1b. 类型。

 -- C 函数: int PyCode_Check (PyObject *co)

     如果 `co' 是一个 *note code: 1b. 对象则返回 true。

 -- C 函数: int PyCode_GetNumFree (PyCodeObject *co)

     返回 `co' 中的自由变量数。

 -- C 函数: PyCodeObject* PyCode_New (int argcount, int kwonlyargcount,
          int nlocals, int stacksize, int flags, PyObject *code,
          PyObject *consts, PyObject *names, PyObject *varnames,
          PyObject *freevars, PyObject *cellvars, PyObject *filename,
          PyObject *name, int firstlineno, PyObject *lnotab)
     `Return value: New reference.' 返回一个新的代码对象。 如果你需要一
     个虚拟代码对象来创建一个代码帧，请使用 *note PyCode_NewEmpty():
     cf2.。 调用 *note PyCode_New(): 273. 直接可以绑定到准确的 Python 版
     本，因为字节码的定义经常变化。

 -- C 函数: PyCodeObject* PyCode_NewWithPosOnlyArgs (int argcount,
          int posonlyargcount, int kwonlyargcount, int nlocals,
          int stacksize, int flags, PyObject *code, PyObject *consts,
          PyObject *names, PyObject *varnames, PyObject *freevars,
          PyObject *cellvars, PyObject *filename, PyObject *name,
          int firstlineno, PyObject *lnotab)
     `Return value: New reference.' 类似于 *note PyCode_New(): 273.，但
     带有一个额外的 "posonlyargcount" 用于仅限位置参数。

     3.8 新版功能.

 -- C 函数: PyCodeObject* PyCode_NewEmpty (const char *filename, const
          char *funcname, int firstlineno)
     `Return value: New reference.' 返回具有指定文件名、函数名和第一行号
     的新空代码对象。 对于 *note exec(): c4c. 或 *note eval(): b98. 生成
     的代码对象是非法的。


File: python.info,  Node: 其他对象<2>,  Prev: 函数对象<2>,  Up: 具体的对象层

7.8.6 其他对象
--------------

* Menu:

* 文件对象::
* 模块对象::
* 迭代器对象::
* 描述符对象::
* 切片对象::
* Ellipsis 对象::
* MemoryView 对象::
* 弱引用对象: 弱引用对象<2>.
* 胶囊: 胶囊<2>.
* 生成器对象::
* 协程对象: 协程对象<2>.
* 上下文变量对象::
* DateTime 对象: DateTime 对象<2>.


File: python.info,  Node: 文件对象,  Next: 模块对象,  Up: 其他对象<2>

7.8.6.1 文件对象
................

这此 API 是对内置文件对象的 Python 2 C API 的最小仿真，它过去依赖于 C 标
准库的缓冲 I/O (‘FILE*’) 支持。 在 Python 3 中，文件和流使用新的 *note
io: a2. 模块，该模块在操作系统的低层级无缓冲 I/O 之上定义了几个层。 下面
所描述的函数是针对这些新 API 的便捷 C 包装器，主要用于解释器的内部错误报
告；建议第三方代码改为访问 *note io: a2. API。

 -- C 函数: PyObject* PyFile_FromFd (int fd, const char *name, const
          char *mode, int buffering, const char *encoding, const
          char *errors, const char *newline, int closefd)
     `Return value: New reference.' 根据已打开文件 `fd' 的文件描述符创建
     一个 Python 文件对象。 参数 `name', `encoding', `errors' 和
     `newline' 可以为 ‘NULL’ 表示使用默认值；`buffering' 可以为 `-1' 表
     示使用默认值。 `name' 会被忽略仅保留用于向下兼容。 失败时返回
     ‘NULL’。 有关参数的更全面描述，请参阅 *note io.open(): 663. 函数的
     文档。

          警告: 由于Python流具有自己的缓冲层，因此将它们与 OS 级文件描述
          符混合会产生各种问题（例如数据的意外排序）。

     在 3.2 版更改: 忽略 `name' 属性。

 -- C 函数: int PyObject_AsFileDescriptor (PyObject *p)

     将与 `p' 关联的文件描述器返回为 ‘int’ 。 如果对象是整数，则返回其值
     。 如果没有，则调用对象的 *note fileno(): 1f19. 方法（如果存在）; 该
     方法必须返回一个整数，该整数作为文件描述器值返回。 设置异常并在失败
     时返回 ‘-1’。

 -- C 函数: PyObject* PyFile_GetLine (PyObject *p, int n)
     `Return value: New reference.'

     等价于 ‘p.readline([n])’ ，这个函数从对象 `p' 中读取一行。 `p' 可以
     是文件对象或具有 *note readline(): 1713. 方法的任何对象。 如果 `n'
     是 ‘0’ ，则无论该行的长度如何，都会读取一行。 如果 `n' 大于‘‘0‘‘，
     则从文件中读取不超过 `n' 个字节；可以返回行的一部分。 在这两种情况
     下，如果立即到达文件末尾，则返回空字符串。 但是，如果 `n' 小于 ‘0’
     ，则无论长度如何都会读取一行，但是如果立即到达文件末尾，则引发
     *note EOFError: c74.。

 -- C 函数: int PyFile_SetOpenCodeHook (Py_OpenCodeHookFunction handler)

     重载 *note io.open_code(): f32. 的正常行为，将其形参通过所提供的处
     理程序来传递。

     处理程序是一个类型为 ‘PyObject *(*)(PyObject *path, void
     *userData)’ 的函数，其中 `path' 确保为 *note PyUnicodeObject:
     3de7.。

     `userData' 指针会被传入钩子函数。 因于钩子函数可能由不同的运行时调
     用，该指针不应直接指向 Python 状态。

     鉴于这个钩子专门在导入期间使用的，请避免在新模块执行期间进行导入操
     作，除非已知它们为冻结状态或者是在 ‘sys.modules’ 中可用。

     一旦钩子被设定，它就不能被移除或替换，之后对 *note
     PyFile_SetOpenCodeHook(): 1ff6. 的调用也将失败，如果解释器已经被初
     始化，函数将返回 -1 并设置一个异常。

     此函数可以安全地在 *note Py_Initialize(): 441. 之前调用。

     引发一个 *note 审计事件: ea1. ‘setopencodehook’，不附带任何参数。

     3.8 新版功能.

 -- C 函数: int PyFile_WriteObject (PyObject *obj, PyObject *p,
          int flags)

     将对象 `obj' 写入文件对象 `p' 。 `flags' 唯一支持的标志是
     ‘Py_PRINT_RAW’；如果给定，则写入对象的 *note str(): 339. 而不是
     *note repr(): 7d5.。成功时返回 ‘0’，失败时返回 ‘-1’。 将设置适当的
     例外。

 -- C 函数: int PyFile_WriteString (const char *s, PyObject *p)

     将字符串 `s' 写入文件对象 `p'。 成功返回 ‘0’ 失败返回 ‘-1’；将设定
     相应的异常。


File: python.info,  Node: 模块对象,  Next: 迭代器对象,  Prev: 文件对象,  Up: 其他对象<2>

7.8.6.2 模块对象
................

 -- C 变量: PyTypeObject PyModule_Type

     This instance of *note PyTypeObject: 2d7. represents the Python
     module type.  This is exposed to Python programs as
     ‘types.ModuleType’.

 -- C 函数: int PyModule_Check (PyObject *p)

     Return true if `p' is a module object, or a subtype of a module
     object.

 -- C 函数: int PyModule_CheckExact (PyObject *p)

     Return true if `p' is a module object, but not a subtype of *note
     PyModule_Type: 3ecc.

 -- C 函数: PyObject* PyModule_NewObject (PyObject *name)
     `Return value: New reference.'

     Return a new module object with the *note __name__: d1a. attribute
     set to `name'.  The module’s *note __name__: d1a, ‘__doc__’, *note
     __package__: 95d, and *note __loader__: 95e. attributes are filled
     in (all but *note __name__: d1a. are set to ‘None’); the caller is
     responsible for providing a *note __file__: ec7. attribute.

     3.3 新版功能.

     在 3.4 版更改: *note __package__: 95d. and *note __loader__: 95e.
     are set to ‘None’.

 -- C 函数: PyObject* PyModule_New (const char *name)
     `Return value: New reference.'  Similar to *note
     PyModule_NewObject(): 3ecf, but the name is a UTF-8 encoded string
     instead of a Unicode object.

 -- C 函数: PyObject* PyModule_GetDict (PyObject *module)
     `Return value: Borrowed reference.'

     Return the dictionary object that implements `module'’s namespace;
     this object is the same as the *note __dict__: 504. attribute of
     the module object.  If `module' is not a module object (or a
     subtype of a module object), *note SystemError: 604. is raised and
     ‘NULL’ is returned.

     It is recommended extensions use other ‘PyModule_*()’ and
     ‘PyObject_*()’ functions rather than directly manipulate a module’s
     *note __dict__: 504.

 -- C 函数: PyObject* PyModule_GetNameObject (PyObject *module)
     `Return value: New reference.'

     Return `module'’s *note __name__: d1a. value.  If the module does
     not provide one, or if it is not a string, *note SystemError: 604.
     is raised and ‘NULL’ is returned.

     3.3 新版功能.

 -- C 函数: const char* PyModule_GetName (PyObject *module)

     Similar to *note PyModule_GetNameObject(): 3ed2. but return the
     name encoded to ‘'utf-8'’.

 -- C 函数: void* PyModule_GetState (PyObject *module)

     Return the "state" of the module, that is, a pointer to the block
     of memory allocated at module creation time, or ‘NULL’.  See *note
     PyModuleDef.m_size: 3ed5.

 -- C 函数: PyModuleDef* PyModule_GetDef (PyObject *module)

     Return a pointer to the *note PyModuleDef: 3b4b. struct from which
     the module was created, or ‘NULL’ if the module wasn’t created from
     a definition.

 -- C 函数: PyObject* PyModule_GetFilenameObject (PyObject *module)
     `Return value: New reference.'

     Return the name of the file from which `module' was loaded using
     `module'’s *note __file__: ec7. attribute.  If this is not defined,
     or if it is not a unicode string, raise *note SystemError: 604. and
     return ‘NULL’; otherwise return a reference to a Unicode object.

     3.2 新版功能.

 -- C 函数: const char* PyModule_GetFilename (PyObject *module)

     Similar to *note PyModule_GetFilenameObject(): 3ed7. but return the
     filename encoded to ’utf-8’.

     3.2 版后已移除: *note PyModule_GetFilename(): 3ed8. raises
     ‘UnicodeEncodeError’ on unencodable filenames, use *note
     PyModule_GetFilenameObject(): 3ed7. instead.

* Menu:

* Initializing C modules::
* Module lookup::


File: python.info,  Node: Initializing C modules,  Next: Module lookup,  Up: 模块对象

7.8.6.3 Initializing C modules
..............................

Modules objects are usually created from extension modules (shared
libraries which export an initialization function), or compiled-in
modules (where the initialization function is added using *note
PyImport_AppendInittab(): 3b0b.).  See *note 构建C/C++扩展: 3b0e. or
*note Extending Embedded Python: 3b95. for details.

The initialization function can either pass a module definition instance
to *note PyModule_Create(): 3b0a, and return the resulting module
object, or request "multi-phase initialization" by returning the
definition struct itself.

 -- C 类型: PyModuleDef

     The module definition struct, which holds all information needed to
     create a module object.  There is usually only one statically
     initialized variable of this type for each module.

      -- C 成员: PyModuleDef_Base m_base

          Always initialize this member to ‘PyModuleDef_HEAD_INIT’.

      -- C 成员: const char *m_name

          Name for the new module.

      -- C 成员: const char *m_doc

          Docstring for the module; usually a docstring variable created
          with *note PyDoc_STRVAR: f3c. is used.

      -- C 成员: Py_ssize_t m_size

          Module state may be kept in a per-module memory area that can
          be retrieved with *note PyModule_GetState(): 3ed4, rather than
          in static globals.  This makes modules safe for use in
          multiple sub-interpreters.

          This memory area is allocated based on `m_size' on module
          creation, and freed when the module object is deallocated,
          after the ‘m_free’ function has been called, if present.

          Setting ‘m_size’ to ‘-1’ means that the module does not
          support sub-interpreters, because it has global state.

          Setting it to a non-negative value means that the module can
          be re-initialized and specifies the additional amount of
          memory it requires for its state.  Non-negative ‘m_size’ is
          required for multi-phase initialization.

          See PEP 3121(1) for more details.

      -- C 成员: PyMethodDef* m_methods

          A pointer to a table of module-level functions, described by
          *note PyMethodDef: e23. values.  Can be ‘NULL’ if no functions
          are present.

      -- C 成员: PyModuleDef_Slot* m_slots

          An array of slot definitions for multi-phase initialization,
          terminated by a ‘{0, NULL}’ entry.  When using single-phase
          initialization, `m_slots' must be ‘NULL’.

          在 3.5 版更改: Prior to version 3.5, this member was always
          set to ‘NULL’, and was defined as:

                -- C 成员: inquiry m_reload

      -- C 成员: traverseproc m_traverse

          A traversal function to call during GC traversal of the module
          object, or ‘NULL’ if not needed.  This function may be called
          before module state is allocated (*note PyModule_GetState():
          3ed4. may return ‘NULL’), and before the *note Py_mod_exec:
          3ee1. function is executed.

      -- C 成员: inquiry m_clear

          A clear function to call during GC clearing of the module
          object, or ‘NULL’ if not needed.  This function may be called
          before module state is allocated (*note PyModule_GetState():
          3ed4. may return ‘NULL’), and before the *note Py_mod_exec:
          3ee1. function is executed.

      -- C 成员: freefunc m_free

          A function to call during deallocation of the module object,
          or ‘NULL’ if not needed.  This function may be called before
          module state is allocated (*note PyModule_GetState(): 3ed4.
          may return ‘NULL’), and before the *note Py_mod_exec: 3ee1.
          function is executed.

* Menu:

* Single-phase initialization::
* Multi-phase initialization::
* Low-level module creation functions::
* Support functions::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3121


File: python.info,  Node: Single-phase initialization,  Next: Multi-phase initialization,  Up: Initializing C modules

7.8.6.4 Single-phase initialization
...................................

The module initialization function may create and return the module
object directly.  This is referred to as "single-phase initialization",
and uses one of the following two module creation functions:

 -- C 函数: PyObject* PyModule_Create (PyModuleDef *def)
     `Return value: New reference.'  Create a new module object, given
     the definition in `def'.  This behaves like *note
     PyModule_Create2(): 3ee5. with `module_api_version' set to
     ‘PYTHON_API_VERSION’.

 -- C 函数: PyObject* PyModule_Create2 (PyModuleDef *def,
          int module_api_version)
     `Return value: New reference.'  Create a new module object, given
     the definition in `def', assuming the API version
     `module_api_version'.  If that version does not match the version
     of the running interpreter, a *note RuntimeWarning: 2c1. is
     emitted.

          注解: Most uses of this function should be using *note
          PyModule_Create(): 3b0a. instead; only use this if you are
          sure you need it.

Before it is returned from in the initialization function, the resulting
module object is typically populated using functions like *note
PyModule_AddObject(): f8e.


File: python.info,  Node: Multi-phase initialization,  Next: Low-level module creation functions,  Prev: Single-phase initialization,  Up: Initializing C modules

7.8.6.5 Multi-phase initialization
..................................

An alternate way to specify extensions is to request "multi-phase
initialization".  Extension modules created this way behave more like
Python modules: the initialization is split between the `creation
phase', when the module object is created, and the `execution phase',
when it is populated.  The distinction is similar to the *note
__new__(): 892. and *note __init__(): d66. methods of classes.

Unlike modules created using single-phase initialization, these modules
are not singletons: if the `sys.modules' entry is removed and the module
is re-imported, a new module object is created, and the old module is
subject to normal garbage collection – as with Python modules.  By
default, multiple modules created from the same definition should be
independent: changes to one should not affect the others.  This means
that all state should be specific to the module object (using e.g.
using *note PyModule_GetState(): 3ed4.), or its contents (such as the
module’s *note __dict__: 504. or individual classes created with *note
PyType_FromSpec(): 2d2.).

All modules created using multi-phase initialization are expected to
support *note sub-interpreters: 3c44.  Making sure multiple modules are
independent is typically enough to achieve this.

To request multi-phase initialization, the initialization function
(PyInit_modulename) returns a *note PyModuleDef: 3b4b. instance with
non-empty *note m_slots: 3ede.  Before it is returned, the ‘PyModuleDef’
instance must be initialized with the following function:

 -- C 函数: PyObject* PyModuleDef_Init (PyModuleDef *def)
     `Return value: Borrowed reference.'  Ensures a module definition is
     a properly initialized Python object that correctly reports its
     type and reference count.

     Returns `def' cast to ‘PyObject*’, or ‘NULL’ if an error occurred.

     3.5 新版功能.

The `m_slots' member of the module definition must point to an array of
‘PyModuleDef_Slot’ structures:

 -- C 类型: PyModuleDef_Slot

      -- C 成员: int slot

          A slot ID, chosen from the available values explained below.

      -- C 成员: void* value

          Value of the slot, whose meaning depends on the slot ID.

     3.5 新版功能.

The `m_slots' array must be terminated by a slot with id 0.

The available slot types are:

 -- C 宏: Py_mod_create

     Specifies a function that is called to create the module object
     itself.  The `value' pointer of this slot must point to a function
     of the signature:

      -- C 函数: PyObject* create_module (PyObject *spec,
               PyModuleDef *def)

     The function receives a *note ModuleSpec: 14d6. instance, as
     defined in PEP 451(1), and the module definition.  It should return
     a new module object, or set an error and return ‘NULL’.

     This function should be kept minimal.  In particular, it should not
     call arbitrary Python code, as trying to import the same module
     again may result in an infinite loop.

     Multiple ‘Py_mod_create’ slots may not be specified in one module
     definition.

     If ‘Py_mod_create’ is not specified, the import machinery will
     create a normal module object using *note PyModule_New(): 3ed0.
     The name is taken from `spec', not the definition, to allow
     extension modules to dynamically adjust to their place in the
     module hierarchy and be imported under different names through
     symlinks, all while sharing a single module definition.

     There is no requirement for the returned object to be an instance
     of *note PyModule_Type: 3ecc.  Any type can be used, as long as it
     supports setting and getting import-related attributes.  However,
     only ‘PyModule_Type’ instances may be returned if the ‘PyModuleDef’
     has non-‘NULL’ ‘m_traverse’, ‘m_clear’, ‘m_free’; non-zero
     ‘m_size’; or slots other than ‘Py_mod_create’.

 -- C 宏: Py_mod_exec

     Specifies a function that is called to `execute' the module.  This
     is equivalent to executing the code of a Python module: typically,
     this function adds classes and constants to the module.  The
     signature of the function is:

      -- C 函数: int exec_module (PyObject* module)

     If multiple ‘Py_mod_exec’ slots are specified, they are processed
     in the order they appear in the `m_slots' array.

See PEP 489(2) for more details on multi-phase initialization.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0451

   (2) https://www.python.org/dev/peps/pep-0489


File: python.info,  Node: Low-level module creation functions,  Next: Support functions,  Prev: Multi-phase initialization,  Up: Initializing C modules

7.8.6.6 Low-level module creation functions
...........................................

The following functions are called under the hood when using multi-phase
initialization.  They can be used directly, for example when creating
module objects dynamically.  Note that both ‘PyModule_FromDefAndSpec’
and ‘PyModule_ExecDef’ must be called to fully initialize a module.

 -- C 函数: PyObject * PyModule_FromDefAndSpec (PyModuleDef *def,
          PyObject *spec)
     `Return value: New reference.'  Create a new module object, given
     the definition in `module' and the ModuleSpec `spec'.  This behaves
     like *note PyModule_FromDefAndSpec2(): 7b5. with
     `module_api_version' set to ‘PYTHON_API_VERSION’.

     3.5 新版功能.

 -- C 函数: PyObject * PyModule_FromDefAndSpec2 (PyModuleDef *def,
          PyObject *spec, int module_api_version)
     `Return value: New reference.'  Create a new module object, given
     the definition in `module' and the ModuleSpec `spec', assuming the
     API version `module_api_version'.  If that version does not match
     the version of the running interpreter, a *note RuntimeWarning:
     2c1. is emitted.

          注解: Most uses of this function should be using *note
          PyModule_FromDefAndSpec(): 7b4. instead; only use this if you
          are sure you need it.

     3.5 新版功能.

 -- C 函数: int PyModule_ExecDef (PyObject *module, PyModuleDef *def)

     Process any execution slots (*note Py_mod_exec: 3ee1.) given in
     `def'.

     3.5 新版功能.

 -- C 函数: int PyModule_SetDocString (PyObject *module, const
          char *docstring)

     Set the docstring for `module' to `docstring'.  This function is
     called automatically when creating a module from ‘PyModuleDef’,
     using either ‘PyModule_Create’ or ‘PyModule_FromDefAndSpec’.

     3.5 新版功能.

 -- C 函数: int PyModule_AddFunctions (PyObject *module,
          PyMethodDef *functions)

     Add the functions from the ‘NULL’ terminated `functions' array to
     `module'.  Refer to the *note PyMethodDef: e23. documentation for
     details on individual entries (due to the lack of a shared module
     namespace, module level "functions" implemented in C typically
     receive the module as their first parameter, making them similar to
     instance methods on Python classes).  This function is called
     automatically when creating a module from ‘PyModuleDef’, using
     either ‘PyModule_Create’ or ‘PyModule_FromDefAndSpec’.

     3.5 新版功能.


File: python.info,  Node: Support functions,  Prev: Low-level module creation functions,  Up: Initializing C modules

7.8.6.7 Support functions
.........................

The module initialization function (if using single phase
initialization) or a function called from a module execution slot (if
using multi-phase initialization), can use the following functions to
help initialize the module state:

 -- C 函数: int PyModule_AddObject (PyObject *module, const char *name,
          PyObject *value)

     Add an object to `module' as `name'.  This is a convenience
     function which can be used from the module’s initialization
     function.  This steals a reference to `value' on success.  Return
     ‘-1’ on error, ‘0’ on success.

          注解: Unlike other functions that steal references,
          ‘PyModule_AddObject()’ only decrements the reference count of
          `value' `on success'.

          This means that its return value must be checked, and calling
          code must *note Py_DECREF(): 267. `value' manually on error.
          Example usage:

               Py_INCREF(spam);
               if (PyModule_AddObject(module, "spam", spam) < 0) {
                   Py_DECREF(module);
                   Py_DECREF(spam);
                   return NULL;
               }

 -- C 函数: int PyModule_AddIntConstant (PyObject *module, const
          char *name, long value)

     Add an integer constant to `module' as `name'.  This convenience
     function can be used from the module’s initialization function.
     Return ‘-1’ on error, ‘0’ on success.

 -- C 函数: int PyModule_AddStringConstant (PyObject *module, const
          char *name, const char *value)

     Add a string constant to `module' as `name'.  This convenience
     function can be used from the module’s initialization function.
     The string `value' must be ‘NULL’-terminated.  Return ‘-1’ on
     error, ‘0’ on success.

 -- C 函数: int PyModule_AddIntMacro (PyObject *module, macro)

     Add an int constant to `module'.  The name and the value are taken
     from `macro'.  For example ‘PyModule_AddIntMacro(module, AF_INET)’
     adds the int constant `AF_INET' with the value of `AF_INET' to
     `module'.  Return ‘-1’ on error, ‘0’ on success.

 -- C 函数: int PyModule_AddStringMacro (PyObject *module, macro)

     Add a string constant to `module'.


File: python.info,  Node: Module lookup,  Prev: Initializing C modules,  Up: 模块对象

7.8.6.8 Module lookup
.....................

Single-phase initialization creates singleton modules that can be looked
up in the context of the current interpreter.  This allows the module
object to be retrieved later with only a reference to the module
definition.

These functions will not work on modules created using multi-phase
initialization, since multiple such modules can be created from a single
definition.

 -- C 函数: PyObject* PyState_FindModule (PyModuleDef *def)
     `Return value: Borrowed reference.'  Returns the module object that
     was created from `def' for the current interpreter.  This method
     requires that the module object has been attached to the
     interpreter state with *note PyState_AddModule(): 3ef7. beforehand.
     In case the corresponding module object is not found or has not
     been attached to the interpreter state yet, it returns ‘NULL’.

 -- C 函数: int PyState_AddModule (PyObject *module, PyModuleDef *def)

     Attaches the module object passed to the function to the
     interpreter state.  This allows the module object to be accessible
     via *note PyState_FindModule(): 3ef6.

     Only effective on modules created using single-phase
     initialization.

     Python calls ‘PyState_AddModule’ automatically after importing a
     module, so it is unnecessary (but harmless) to call it from module
     initialization code.  An explicit call is needed only if the
     module’s own init code subsequently calls ‘PyState_FindModule’.
     The function is mainly intended for implementing alternative import
     mechanisms (either by calling it directly, or by referring to its
     implementation for details of the required state updates).

     Return 0 on success or -1 on failure.

     3.3 新版功能.

 -- C 函数: int PyState_RemoveModule (PyModuleDef *def)

     Removes the module object created from `def' from the interpreter
     state.  Return 0 on success or -1 on failure.

     3.3 新版功能.


File: python.info,  Node: 迭代器对象,  Next: 描述符对象,  Prev: 模块对象,  Up: 其他对象<2>

7.8.6.9 迭代器对象
..................

Python 提供了两个通用迭代器对象。 第一个是序列迭代器，它使用支持 *note
__getitem__(): 280. 方法的任意序列。 第二个使用可调用对象和一个 sentinel
值，为序列中的每个项调用可调用对象，并在返回 sentinel 值时结束迭代。

 -- C 变量: PyTypeObject PySeqIter_Type

     *note PySeqIter_New(): 3efd. 返回迭代器对象的类型对象和内置序列类型
     内置函数 *note iter(): d2f. 的单参数形式。

 -- C 函数: int PySeqIter_Check (op)

     如果 `op' 的类型为 *note PySeqIter_Type: 3efc. 则返回 true。

 -- C 函数: PyObject* PySeqIter_New (PyObject *seq)
     `Return value: New reference.' 返回一个与常规序列对象一起使用的迭代
     器 `seq'。 当序列订阅操作引发 *note IndexError: e7d. 时，迭代结束。

 -- C 变量: PyTypeObject PyCallIter_Type

     由函数 *note PyCallIter_New(): 3f00. 和 *note iter(): d2f. 内置函数
     的双参数形式返回的迭代器对象类型对象。

 -- C 函数: int PyCallIter_Check (op)

     如果 `op' 的类型为 *note PyCallIter_Type: 3eff. 则返回 true。

 -- C 函数: PyObject* PyCallIter_New (PyObject *callable,
          PyObject *sentinel)
     `Return value: New reference.' 返回一个新的迭代器。 第一个参数
     `callable' 可以是任何可以在没有参数的情况下调用的 Python 可调用对象
     ；每次调用都应该返回迭代中的下一个项目。 当 `callable' 返回等于
     `sentinel' 的值时，迭代将终止。


File: python.info,  Node: 描述符对象,  Next: 切片对象,  Prev: 迭代器对象,  Up: 其他对象<2>

7.8.6.10 描述符对象
...................

“描述符”是描述对象的某些属性的对象。它们存在于类型对象的字典中。

 -- C 变量: PyTypeObject PyProperty_Type

     内建描述符类型的类型对象。

 -- C 函数: PyObject* PyDescr_NewGetSet (PyTypeObject *type, struct
          PyGetSetDef *getset)
     `Return value: New reference.'

 -- C 函数: PyObject* PyDescr_NewMember (PyTypeObject *type, struct
          PyMemberDef *meth)
     `Return value: New reference.'

 -- C 函数: PyObject* PyDescr_NewMethod (PyTypeObject *type, struct
          PyMethodDef *meth)
     `Return value: New reference.'

 -- C 函数: PyObject* PyDescr_NewWrapper (PyTypeObject *type, struct
          wrapperbase *wrapper, void *wrapped)
     `Return value: New reference.'

 -- C 函数: PyObject* PyDescr_NewClassMethod (PyTypeObject *type,
          PyMethodDef *method)
     `Return value: New reference.'

 -- C 函数: int PyDescr_IsData (PyObject *descr)

     如果描述符对象 `descr' 描述数据属性，则返回true；如果描述方法，则返
     回false。 `descr' 必须是描述符对象；没有错误检查。

 -- C 函数: PyObject* PyWrapper_New (PyObject *, PyObject *)
     `Return value: New reference.'


File: python.info,  Node: 切片对象,  Next: Ellipsis 对象,  Prev: 描述符对象,  Up: 其他对象<2>

7.8.6.11 切片对象
.................

 -- C 变量: PyTypeObject PySlice_Type

     切片对象的类型对象。 它与 Python 层面的 *note slice: e0c. 是相同的
     对象。

 -- C 函数: int PySlice_Check (PyObject *ob)

     如果 `ob' 是一个 slice 对象则返回真值；`ob' 必须不为 ‘NULL’。

 -- C 函数: PyObject* PySlice_New (PyObject *start, PyObject *stop,
          PyObject *step)
     `Return value: New reference.' 返回一个具有给定值的新 slice 对象。
     `start', `stop' 和 `step' 形参会被用作 slice 对象相应名称的属性的值
     。 这些值中的任何一个都可以为 ‘NULL’，在这种情况下将使用 ‘None’ 作
     为对应属性的值。 如果新对象无法被分配则返回 ‘NULL’。

 -- C 函数: int PySlice_GetIndices (PyObject *slice, Py_ssize_t length,
          Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)

     从 slice 对象 `slice' 提取 start, stop 和 step 索引号，将序列长度视
     为 `length'。 大于 `length' 的序列号将被当作错误。

     成功时返回 ‘0’，出错时返回 ‘-1’ 并且不设置异常（除非某个序列号不为
     *note None: 158. 且无法被转换为整数，在这种情况下会返回 ‘-1’ 并且设
     置一个异常）。

     你可能不会打算使用此函数。

     在 3.2 版更改: 之前 `slice' 形参的形参类型是 ‘PySliceObject*’。

 -- C 函数: int PySlice_GetIndicesEx (PyObject *slice,
          Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop,
          Py_ssize_t *step, Py_ssize_t *slicelength)

     *note PySlice_GetIndices(): 3f12. 的可用替代。 从 slice 对象
     `slice' 提取 start, stop 和 step 索引号，将序列长度视为 `length'，
     并将切片的长度保存在 `slicelength' 中，超出范围的索引号会以与普通切
     片一致的方式进行剪切。

     成功时返回 ‘0’，出错时返回 ‘-1’ 并且不设置异常。

          注解: 此函数对于可变大小序列来说是不安全的。 对它的调用应被替
          换为 *note PySlice_Unpack(): 437. 和 *note
          PySlice_AdjustIndices(): 438. 的组合，其中

               if (PySlice_GetIndicesEx(slice, length, &start, &stop, &step, &slicelength) < 0) {
                   // return error
               }

          会被替换为

               if (PySlice_Unpack(slice, &start, &stop, &step) < 0) {
                   // return error
               }
               slicelength = PySlice_AdjustIndices(length, &start, &stop, step);

     在 3.2 版更改: 之前 `slice' 形参的形参类型是 ‘PySliceObject*’。

     在 3.6.1 版更改: 如果 ‘Py_LIMITED_API’ 未设置或设置为 ‘0x03050400’
     与 ‘0x03060000’ 之前的值（不包含边界）或 ‘0x03060100’ 或更大则
     ‘PySlice_GetIndicesEx()’ 会被实现为一个使用 ‘PySlice_Unpack()’ 和
     ‘PySlice_AdjustIndices()’ 的宏。 参数 `start', `stop' 和 `step' 会
     被多被求值。

     3.6.1 版后已移除: 如果 ‘Py_LIMITED_API’ 设置为小于 ‘0x03050400’ 或
     ‘0x03060000’ 与 ‘0x03060100’ 之间的值（不包括边界）则
     ‘PySlice_GetIndicesEx()’ 为已弃用的函数。

 -- C 函数: int PySlice_Unpack (PyObject *slice, Py_ssize_t *start,
          Py_ssize_t *stop, Py_ssize_t *step)

     从切片对象中将 start, stop 和 step 数据成员提取为 C 整数。 会静默地
     将大于 ‘PY_SSIZE_T_MAX’ 的值减小为 ‘PY_SSIZE_T_MAX’，静默地将小于
     ‘PY_SSIZE_T_MIN’ 的 start 和 stop 值增大为 ‘PY_SSIZE_T_MIN’，并静默
     地将小于 ‘-PY_SSIZE_T_MAX’ 的 step 值增大为 ‘-PY_SSIZE_T_MAX’。

     出错时返回 ‘-1’，成功时返回 ‘0’。

     3.6.1 新版功能.

 -- C 函数: Py_ssize_t PySlice_AdjustIndices (Py_ssize_t length,
          Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step)

     将 start/end 切片索引号根据指定的序列长度进行调整。 超出范围的索引
     号会以与普通切片一致的方式进行剪切。

     返回切片的长度。 此操作总是会成功。 不会调用 Python 代码。

     3.6.1 新版功能.


File: python.info,  Node: Ellipsis 对象,  Next: MemoryView 对象,  Prev: 切片对象,  Up: 其他对象<2>

7.8.6.12 Ellipsis 对象
......................

 -- C 变量: PyObject *Py_Ellipsis

     Python 的 ‘Ellipsis’ 对象。 该对象没有任何方法。 它必须以与任何其他
     对象一样的方式遵循引用计数。 它与 *note Py_None: 3b07. 一样是单例对
     象。


File: python.info,  Node: MemoryView 对象,  Next: 弱引用对象<2>,  Prev: Ellipsis 对象,  Up: 其他对象<2>

7.8.6.13 MemoryView 对象
........................

一个 *note memoryview: 25d. 对象C级别的 *note 缓冲区接口: 15f7. 暴露为一
个可以像任何其他对象一样传递的 Python 对象。

 -- C 函数: PyObject *PyMemoryView_FromObject (PyObject *obj)
     `Return value: New reference.' 从提供缓冲区接口的对象创建
     memoryview 对象。 如果 `obj' 支持可写缓冲区导出，则 memoryview 对象
     将可以被读/写，否则它可能是只读的，也可以是导出器自行决定的读/写。

 -- C 函数: PyObject *PyMemoryView_FromMemory (char *mem,
          Py_ssize_t size, int flags)
     `Return value: New reference.' 使用 `mem' 作为底层缓冲区创建一个
     memoryview 对象。 `flags' 可以是 ‘PyBUF_READ’ 或者 ‘PyBUF_WRITE’ 之
     一.

     3.3 新版功能.

 -- C 函数: PyObject *PyMemoryView_FromBuffer (Py_buffer *view)
     `Return value: New reference.' 创建一个包含给定缓冲区结构 `view' 的
     memoryview 对象。 对于简单的字节缓冲区，*note
     PyMemoryView_FromMemory(): ad1. 是首选函数。

 -- C 函数: PyObject *PyMemoryView_GetContiguous (PyObject *obj,
          int buffertype, char order)
     `Return value: New reference.' 从定义缓冲区接口的对象创建一个
     memoryview 对象 *note contiguous: 16c5. 内存块（在 ’C’ 或 ’F’ortran
     `order' 中）。 如果内存是连续的，则 memoryview 对象指向原始内存。 否
     则，复制并且 memoryview 指向新的 bytes 对象。

 -- C 函数: int PyMemoryView_Check (PyObject *obj)

     如果对象 `obj' 是 memoryview 对象，则返回 true 。 目前不允许创建
     *note memoryview: 25d. 的子类。

 -- C 函数: Py_buffer *PyMemoryView_GET_BUFFER (PyObject *mview)

     返回指向 memoryview 的导出缓冲区私有副本的指针。 `mview' `必须' 是
     一个 memoryview 实例；这个宏不检查它的类型，你必须自己检查，否则你
     将面临崩溃风险。

 -- C 函数: Py_buffer *PyMemoryView_GET_BASE (PyObject *mview)

     返回 memoryview 所基于的导出对象的指针，或者如果 memoryview 已由函
     数 *note PyMemoryView_FromMemory(): ad1. 或 *note
     PyMemoryView_FromBuffer(): 3d23. 创建则返回 ‘NULL’。 `mview' `必须'
     是一个 memoryview 实例。


File: python.info,  Node: 弱引用对象<2>,  Next: 胶囊<2>,  Prev: MemoryView 对象,  Up: 其他对象<2>

7.8.6.14 弱引用对象
...................

Python 支持 “弱引用” 作为一类对象。具体来说，有两种直接实现弱引用的对象
。第一种就是简单的引用对象，第二种尽可能地作用为一个原对象的代理。

 -- C 函数: int PyWeakref_Check (ob)

     如果 “ob” 是一个引用或者一个代理对象，则返回 true。

 -- C 函数: int PyWeakref_CheckRef (ob)

     如果 “ob” 是一个引用，则返回 true。

 -- C 函数: int PyWeakref_CheckProxy (ob)

     如果 “ob” 是一个代理对象，则返回 true。

 -- C 函数: PyObject* PyWeakref_NewRef (PyObject *ob,
          PyObject *callback)
     `Return value: New reference.' 返回对象 `ob' 的一个弱引用对象。 该
     函数总是会返回一个新的引用，但不保证创建一个新的对象；它有可能返回
     一个现有的引用对象。 第二个形参 `callback' 为一个可调用对象，它会在
     `ob' 被作为垃圾回收时接收通知；它应该接受一个单独形参，即弱引用对象
     本身。 `callback' 也可以为 ‘None’ 或 ‘NULL’。 如果 `ob' 不是一个弱
     引用对象，或者如果 `callback' 不是可调用对象，‘None’ 或 ‘NULL’，该
     函数将返回 ‘NULL’ 并且引发 *note TypeError: 193.。

 -- C 函数: PyObject* PyWeakref_NewProxy (PyObject *ob,
          PyObject *callback)
     `Return value: New reference.' 返回对象 `ob' 的一个弱引用代理对象。
     该函数将总是返回一个新的引用，但不保证创建一个新的对象；它有可能返
     回一个现有的代理对象。 第二个形参 `callback' 为一个可调用对象，它会
     在 `ob' 被作为垃圾回收时接收通知；它应该接受一个单独形参，即弱引用
     对象本身。 `callback' 也可以为 ‘None’ 或 ‘NULL’。 如果 `ob' 不是一
     个弱引用对象，或者如果 `callback' 不是可调用对象，‘None’ 或 ‘NULL’，
     该函数将返回 ‘NULL’ 并且引发 *note TypeError: 193.。

 -- C 函数: PyObject* PyWeakref_GetObject (PyObject *ref)
     `Return value: Borrowed reference.' 返回弱引用对象 ref 的被引用对象
     。如果被引用对象不再存在，则返回 ‘Py_None’。

          注解: 该函数返回被引用对象的一个**借来的引用**。这意味着除非你
          很清楚在你使用期间这个对象不可能被销毁，否则你应该始终对该对象
          调用 *note Py_INCREF(): 266.。

 -- C 函数: PyObject* PyWeakref_GET_OBJECT (PyObject *ref)
     `Return value: Borrowed reference.' 类似 *note
     PyWeakref_GetObject(): 3f24.，但实现为一个不做类型检查的宏。


File: python.info,  Node: 胶囊<2>,  Next: 生成器对象,  Prev: 弱引用对象<2>,  Up: 其他对象<2>

7.8.6.15 胶囊
.............

有关使用这些对象的更多信息请参阅 *note 给扩展模块提供C API: cf9.。

3.1 新版功能.

 -- C 类型: PyCapsule

     这个 *note PyObject: 4c2. 的子类型代表一个隐藏的值，适用于需要将隐
     藏值（作为 ‘void*’ 指针）通过 Python 代码传递到其他 C 代码的 C 扩展
     模块。 它常常被用来让在一个模块中定义的 C 函数指针在其他模块中可用
     ，这样就可以使用常规导入机制来访问在动态加载的模块中定义的 C API。

 -- C 类型: PyCapsule_Destructor

     这种类型的一个析构器返回一个胶囊，定义如下：

          typedef void (*PyCapsule_Destructor)(PyObject *);

     参阅 *note PyCapsule_New(): 3b2f. 来获取 PyCapsule_Destructor 返回
     值的语义。

 -- C 函数: int PyCapsule_CheckExact (PyObject *p)

     如果参数是一个 *note PyCapsule: c0f. 则返回 True

 -- C 函数: PyObject* PyCapsule_New (void *pointer, const char *name,
          PyCapsule_Destructor destructor)
     `Return value: New reference.' 创建一个封装了 `pointer' 的 *note
     PyCapsule: c0f.。 `pointer' 参考可以不为 ‘NULL’。

     在失败时设置一个异常并返回 ‘NULL’。

     字符串 `name' 可以是 ‘NULL’ 或是一个指向有效的 C 字符串的指针。 如
     果不为 ‘NULL’，则此字符串必须比 capsule 长（虽然也允许在
     `destructor' 中释放它。）

     如果 `destructor' 参数不为 ‘NULL’，则当它被销毁时将附带 capsule 作
     为参数来调用。

     如果此 capsule 将被保存为一个模块的属性，则 `name' 应当被指定为
     ‘modulename.attributename’。 这将允许其他模块使用 *note
     PyCapsule_Import(): 3b30. 来导入此 capsule。

 -- C 函数: void* PyCapsule_GetPointer (PyObject *capsule, const
          char *name)

     提取保存在 capsule 中的 `pointer'。 在失败时设置一个异常并返回
     ‘NULL’。

     `name' 形参必须与保存在 capsule 中的名称进行精确比较。 如果保存在
     capsule 中的名称为 ‘NULL’，则传入的 `name' 也必须为 ‘NULL’。 Python
     会使用 C 函数 ‘strcmp()’ 来比较 capsule 名称。

 -- C 函数: PyCapsule_Destructor PyCapsule_GetDestructor
          (PyObject *capsule)

     返回保存为 capsule 中的当前析构器。 在失败时设置一个异常并返回
     ‘NULL’。

     具有 ‘NULL’ 析构器是合法的。 这会使得 ‘NULL’ 返回值有些歧义；请使用
     *note PyCapsule_IsValid(): cf8. 或 *note PyErr_Occurred(): 3b02. 来
     消除歧义。

 -- C 函数: void* PyCapsule_GetContext (PyObject *capsule)

     返回保存在 capsule 中的当前上下文。 在失败时设置一个异常并返回
     ‘NULL’。

     capsule 具有 ‘NULL’ 上下文是全法的。 这会使得 ‘NULL’ 返回码有些歧义
     ；请使用 *note PyCapsule_IsValid(): cf8. 或 *note PyErr_Occurred():
     3b02. 来消除歧义。

 -- C 函数: const char* PyCapsule_GetName (PyObject *capsule)

     返回保存在 capsule 中的当前名称。 在失败时设置一个异常并返回
     ‘NULL’。

     capsule 具有 ‘NULL’ 名称是合法的。 这会使得 ‘NULL’ 返回码有些歧义；
     请使用 *note PyCapsule_IsValid(): cf8. 或 *note PyErr_Occurred():
     3b02. 来消除歧义。

 -- C 函数: void* PyCapsule_Import (const char *name, int no_block)

     从一个模块的 capsule 属性导入指向 C 对象的指针。 `name' 形参应当指
     定属性的完整名称，与 ‘module.attribute’ 中的一致。 保存在 capsule 中
     的 `name' 必须完全匹配此字符串。 如果 `no_block' 为真值，则以无阻塞
     模式导入模块 (使用 *note PyImport_ImportModuleNoBlock(): 9c9.)。 如
     果 `no_block' 为假值，则以传统模式导入模块 (使用 *note
     PyImport_ImportModule(): c7b.)。

     成功时返回 capsule 的内部 `指针'。 在失败时设置一个异常并返回
     ‘NULL’。

 -- C 函数: int PyCapsule_IsValid (PyObject *capsule, const char *name)

     确定 `capsule' 是否是一个有效的。 有效的 capsule 必须不为 ‘NULL’，
     传递 *note PyCapsule_CheckExact(): 3f29.，在其中存储一个不为 ‘NULL’
     的指针，并且其内部名称与 `name' 形参相匹配。 （请参阅 *note
     PyCapsule_GetPointer(): 3f2a. 了解如何对 capsule 名称进行比较的有关
     信息。）

     换句话说，如果 *note PyCapsule_IsValid(): cf8. 返回真值，则任何对访
     问器（以 ‘PyCapsule_Get()’ 开头的任何函数）的调用都保证会成功。

     如果对象有效并且匹配传入的名称则返回非零值。 否则返回 ‘0’。 此函数
     一定不会失败。

 -- C 函数: int PyCapsule_SetContext (PyObject *capsule, void *context)

     将 `capsule' 内部的上下文指针设为 `context'。

     成功时返回 ‘0’。 失败时返回非零值并设置一个异常。

 -- C 函数: int PyCapsule_SetDestructor (PyObject *capsule,
          PyCapsule_Destructor destructor)

     将 `capsule' 内部的析构器设为 `destructor'。

     成功时返回 ‘0’。 失败时返回非零值并设置一个异常。

 -- C 函数: int PyCapsule_SetName (PyObject *capsule, const char *name)

     将 `capsule' 内部的名称设为 `name'。 如果不为 ‘NULL’，则名称的存在
     期必须比 capsule 更长。 如果之前保存在 capsule 中的 `name' 不为
     ‘NULL’，则不会尝试释放它。

     成功时返回 ‘0’。 失败时返回非零值并设置一个异常。

 -- C 函数: int PyCapsule_SetPointer (PyObject *capsule, void *pointer)

     将 `capsule' 内部的空指针设为 `pointer'。 指针不可为 ‘NULL’。

     成功时返回 ‘0’。 失败时返回非零值并设置一个异常。


File: python.info,  Node: 生成器对象,  Next: 协程对象<2>,  Prev: 胶囊<2>,  Up: 其他对象<2>

7.8.6.16 生成器对象
...................

生成器对象是Python用来实现生成器迭代器的对象。它们通常通过迭代产生值的函
数来创建，而不是显式调用 *note PyGen_New(): 3f35. 或 *note
PyGen_NewWithQualName(): 3f36.。

 -- C 类型: PyGenObject

     用于生成器对象的C结构体。

 -- C 变量: PyTypeObject PyGen_Type

     与生成器对象对应的类型对​​象。

 -- C 函数: int PyGen_Check (PyObject *ob)

     如果 `ob' 是一个生成器对象则返回真值；`ob' 必须不为 ‘NULL’。

 -- C 函数: int PyGen_CheckExact (PyObject *ob)

     如果 `ob' 的类型为 *note PyGen_Type: 3f38. 则返回真值；`ob' 必须不
     为 ‘NULL’。

 -- C 函数: PyObject* PyGen_New (PyFrameObject *frame)
     `Return value: New reference.' 基于 `frame' 对象创建并返回一个新的
     生成器对象。 此函数会取走一个对 `frame' 的引用。 参数必须不为
     ‘NULL’。

 -- C 函数: PyObject* PyGen_NewWithQualName (PyFrameObject *frame,
          PyObject *name, PyObject *qualname)
     `Return value: New reference.' 基于 `frame' 对象创建并返回一个新的
     生成器对象，其中 ‘__name__’ 和 ‘__qualname__’ 设为 `name' 和
     `qualname'。 此函数会取走一个对 `frame' 的引用。 `frame' 参数必须不
     为 ‘NULL’。


File: python.info,  Node: 协程对象<2>,  Next: 上下文变量对象,  Prev: 生成器对象,  Up: 其他对象<2>

7.8.6.17 协程对象
.................

3.5 新版功能.

协程对象是使用 ‘async’ 关键字声明的函数返回的。

 -- C 类型: PyCoroObject

     用于协程对象的C结构体。

 -- C 变量: PyTypeObject PyCoro_Type

     与协程对象对应的类型对​​象。

 -- C 函数: int PyCoro_CheckExact (PyObject *ob)

     如果 `ob' 的类型是 *note PyCoro_Type: 3f3e. 则返回真值；`ob' 必须不
     为 ‘NULL’。

 -- C 函数: PyObject* PyCoro_New (PyFrameObject *frame, PyObject *name,
          PyObject *qualname)
     `Return value: New reference.' 基于 `frame' 对象创建并返回一个新的
     协程对象，其中 ‘__name__’ 和 ‘__qualname__’ 设为 `name' 和
     `qualname'。 此函数会取得一个对 `frame' 的引用。 `frame' 参数必须不
     为 ‘NULL’。


File: python.info,  Node: 上下文变量对象,  Next: DateTime 对象<2>,  Prev: 协程对象<2>,  Up: 其他对象<2>

7.8.6.18 上下文变量对象
.......................

     注解 在 3.7.1 版更改:: 在 Python 3.7.1 中，所有上下文变量 C API 的
     签名被 `更改' 为使用 *note PyObject: 4c2. 指针而不是 *note
     PyContext: 3f43, *note PyContextVar: 3f44. 以及 *note
     PyContextToken: 3f45.，例如:

          // in 3.7.0:
          PyContext *PyContext_New(void);

          // in 3.7.1+:
          PyObject *PyContext_New(void);

     详情请参阅:issue: ’ 34762 ’。

3.7 新版功能.

本节深入介绍了 *note contextvars: 25. 模块的公用 C API。

 -- C 类型: PyContext

     用于表示 *note contextvars.Context: 24cb. 对象的 C 结构体。

 -- C 类型: PyContextVar

     用于表示 *note contextvars.ContextVar: 24c9. 对象的 C 结构体。

 -- C 类型: PyContextToken

     用于表示 ‘contextvars.Token’ 对象的 C 结构体。

 -- C 变量: PyTypeObject PyContext_Type

     表示 `context' 类型的类型对象。

 -- C 变量: PyTypeObject PyContextVar_Type

     表示 `context variable' 类型的类型对象。

 -- C 变量: PyTypeObject PyContextToken_Type

     表示 `context variable token' 类型的类型对象。

类型检查宏：

 -- C 函数: int PyContext_CheckExact (PyObject *o)

     如果 `o' 的类型为 *note PyContext_Type: 3f46. 则返回真值。 `o' 必须
     不为 ‘NULL’。 此函数总是会成功执行。

 -- C 函数: int PyContextVar_CheckExact (PyObject *o)

     如果 `o' 的类型为 *note PyContextVar_Type: 3f47. 则返回真值。 `o' 必
     须不为 ‘NULL’。 此函数总是会成功执行。

 -- C 函数: int PyContextToken_CheckExact (PyObject *o)

     如果 `o' 的类型为 *note PyContextToken_Type: 3f48. 则返回真值。 `o'
     必须不为 ‘NULL’。 此函数总是会成功执行。

上下文对象管理函数:

 -- C 函数: PyObject *PyContext_New (void)
     `Return value: New reference.' 创建一个新的空上下文对象。 如果发生
     错误则返回 ‘NULL’。

 -- C 函数: PyObject *PyContext_Copy (PyObject *ctx)
     `Return value: New reference.' 创建所传入的 `ctx' 上下文对象的浅拷
     贝。 如果发生错误则返回 ‘NULL’。

 -- C 函数: PyObject *PyContext_CopyCurrent (void)
     `Return value: New reference.' 创建当前线程上下文的浅拷贝。 如果发
     生错误则返回 ‘NULL’。

 -- C 函数: int PyContext_Enter (PyObject *ctx)

     将 `ctx' 设为当前线程的当前上下文。 成功时返回 ‘0’，出错时返回
     ‘-1’。

 -- C 函数: int PyContext_Exit (PyObject *ctx)

     取消激活 `ctx' 上下文并将之前的上下文恢复为当前线程的当前上下文。 成
     功时返回 ‘0’，出错时返回 ‘-1’。

 -- C 函数: int PyContext_ClearFreeList ()

     清空上下文变量释放列表。 返回所释放的条目总数。 此函数总是会成功执
     行。

上下文变量函数:

 -- C 函数: PyObject *PyContextVar_New (const char *name, PyObject *def)
     `Return value: New reference.' 创建一个新的 ‘ContextVar’ 对象。 形
     参 `name' 用于自我检查和调试目的。 形参 `def' 为上下文变量指定默认
     值，或为 ‘NULL’ 表示无默认值。 如果发生错误，这个函数会返回 ‘NULL’。

 -- C 函数: int PyContextVar_Get (PyObject *var,
          PyObject *default_value, PyObject **value)

     获取上下文变量的值。如果在查找过程中发生错误，返回’ ’ -1 ’ ’，如果
     没有发生错误，无论是否找到值，都返回’ ’ 0 ’ ’，

     如果找到上下文变量，`value' 将是指向它的指针。 如果上下文变量 `没有
     ' 找到，`value' 将指向：

        - `default_value'，如果非‘‘NULL‘‘;

        - `var' 的默认值，如果不是 ‘NULL’；

        - ‘NULL’

     除了返回 ‘NULL’，这个函数会返回一个新的引用。

 -- C 函数: PyObject *PyContextVar_Set (PyObject *var, PyObject *value)
     `Return value: New reference.' 在当前上下文中将 `var' 设为 `value'。
     返回针对此修改的新凭据对象，或者如果发生错误则返回 ‘NULL’。

 -- C 函数: int PyContextVar_Reset (PyObject *var, PyObject *token)

     将上下文变量 `var' 的状态重置为它在返回 `token' 的 *note
     PyContextVar_Set(): 3f54. 被调用之前的状态。 此函数成功时返回 ‘0’，
     出错时返回 ‘-1’。


File: python.info,  Node: DateTime 对象<2>,  Prev: 上下文变量对象,  Up: 其他对象<2>

7.8.6.19 DateTime 对象
......................

*note datetime: 31. 模块提供了各种日期和时间对象。 在使用任何这些函数之
前，必须在你的源码中包含头文件 ‘datetime.h’ (请注意此文件并未包含在
‘Python.h’ 中)，并且宏 ‘PyDateTime_IMPORT’ 必须被发起调用，通常是作为模
块初始化函数的一部分。 这个宏会将指向特定 C 结构的指针放入一个静态变量
‘PyDateTimeAPI’ 中，它会由下面的宏来使用。

宏访问UTC单例:

 -- C 变量: PyObject* PyDateTime_TimeZone_UTC

     返回表示 UTC 的时区单例，与 *note datetime.timezone.utc: 18fa. 为同
     一对象。

     3.7 新版功能.

类型检查宏：

 -- C 函数: int PyDate_Check (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_DateType’ 类型或 ‘PyDateTime_DateType’ 的
     某个子类型则返回真值。 `ob' 不能为 ‘NULL’。

 -- C 函数: int PyDate_CheckExact (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_DateType’ 类型则返回真值。 `ob' 不能为
     ‘NULL’。

 -- C 函数: int PyDateTime_Check (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_DateTimeType’ 类型或
     ‘PyDateTime_DateTimeType’ 的某个子类型则返回真值。 `ob' 不能为
     ‘NULL’。

 -- C 函数: int PyDateTime_CheckExact (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_DateTimeType’ 类型则返回真值。 `ob' 不能为
     ‘NULL’。

 -- C 函数: int PyTime_Check (PyObject *ob)

     如果 `ob' 的类型是 ‘PyDateTime_TimeType’ 或是 ‘PyDateTime_TimeType’
     的子类型则返回真值。 `ob' 必须不为 ‘NULL’。

 -- C 函数: int PyTime_CheckExact (PyObject *ob)

     如果 `ob' 的类型是 ‘PyDateTime_TimeType’ 则返回真值。 `ob' 必须不为
     ‘NULL’。

 -- C 函数: int PyDelta_Check (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_DeltaType’ 类型或 ‘PyDateTime_DeltaType’ 的
     某个子类型则返回真值。 `ob' 不能为 ‘NULL’。

 -- C 函数: int PyDelta_CheckExact (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_DeltaType’ 类型则返回真值。 `ob' 不能为
     ‘NULL’。

 -- C 函数: int PyTZInfo_Check (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_TZInfoType’ 类型或 ‘PyDateTime_TZInfoType’
     的某个子类型则返回真值。 `ob' 必须不为 ‘NULL’。

 -- C 函数: int PyTZInfo_CheckExact (PyObject *ob)

     如果 `ob' 的类型是 ‘PyDateTime_TZInfoType’ 则返回真值。 `ob' 不能为
     ‘NULL’。

用于创建对象的宏：

 -- C 函数: PyObject* PyDate_FromDate (int year, int month, int day)
     `Return value: New reference.' 返回指定年、月、日的 *note
     datetime.date: 194. 对象。

 -- C 函数: PyObject* PyDateTime_FromDateAndTime (int year, int month,
          int day, int hour, int minute, int second, int usecond)
     `Return value: New reference.' 返回具有指定 year, month, day, hour,
     minute, second 和 microsecond 属性的 *note datetime.datetime: 195.
     对象。

 -- C 函数: PyObject* PyDateTime_FromDateAndTimeAndFold (int year,
          int month, int day, int hour, int minute, int second,
          int usecond, int fold)
     `Return value: New reference.' 返回具有指定 year, month, day, hour,
     minute, second, microsecond 和 fold 属性的 *note datetime.datetime:
     195. 对象。

     3.6 新版功能.

 -- C 函数: PyObject* PyTime_FromTime (int hour, int minute, int second,
          int usecond)
     `Return value: New reference.' 返回具有指定 hour, minute, second
     and microsecond 属性的 *note datetime.time: 4fb. 对象。

 -- C 函数: PyObject* PyTime_FromTimeAndFold (int hour, int minute,
          int second, int usecond, int fold)
     `Return value: New reference.' 返回具有指定 hour, minute, second,
     microsecond 和 fold 属性的 *note datetime.time: 4fb. 对象。

     3.6 新版功能.

 -- C 函数: PyObject* PyDelta_FromDSU (int days, int seconds,
          int useconds)
     `Return value: New reference.' 返回代表给定天、秒和微秒数的 *note
     datetime.timedelta: 196. 对象。 将执行正规化操作以使最终的微秒和秒
     数处在 *note datetime.timedelta: 196. 对象的文档指明的区间之内。

 -- C 函数: PyObject* PyTimeZone_FromOffset
          (PyDateTime_DeltaType* offset)
     `Return value: New reference.' 返回一个 *note datetime.timezone:
     a09. 对象，该对象具有以 `offset' 参数表示 的未命名固定时差。

     3.7 新版功能.

 -- C 函数: PyObject* PyTimeZone_FromOffsetAndName
          (PyDateTime_DeltaType* offset, PyUnicode* name)
     `Return value: New reference.' 返回一个 *note datetime.timezone:
     a09. 对象，该对象具有以 `offset' 参数表示的固定时差和时区名称
     `name'。

     3.7 新版功能.

一些用来从 date 对象中提取字段的宏。 参数必须是 ‘PyDateTime_Date’ 包括其
子类 (例如 ‘PyDateTime_DateTime’) 的实例。 参数必须不为 ‘NULL’，并且类型
不被会检查:

 -- C 函数: int PyDateTime_GET_YEAR (PyDateTime_Date *o)

     以正整数的形式返回年份值。

 -- C 函数: int PyDateTime_GET_MONTH (PyDateTime_Date *o)

     返回月，从0到12的整数。

 -- C 函数: int PyDateTime_GET_DAY (PyDateTime_Date *o)

     返回日期，从0到31的整数。

一些用来从 datetime 对象中提取字段的宏。 参数必须是
‘PyDateTime_DateTime’ 包括其子类的实例。 参数必须不为 ‘NULL’，并且类型不
会被检查:

 -- C 函数: int PyDateTime_DATE_GET_HOUR (PyDateTime_DateTime *o)

     返回小时，从0到23的整数。

 -- C 函数: int PyDateTime_DATE_GET_MINUTE (PyDateTime_DateTime *o)

     返回分钟，从0到59的整数。

 -- C 函数: int PyDateTime_DATE_GET_SECOND (PyDateTime_DateTime *o)

     返回秒，从0到59的整数。

 -- C 函数: int PyDateTime_DATE_GET_MICROSECOND (PyDateTime_DateTime *o)

     返回微秒，从0到999999的整数。

一些用来从 time 对象中提取字段的宏。 参数必须是 ‘PyDateTime_Time’ 包括其
子类的实例。 参数必须不为 ‘NULL’，并且类型不会被检查:

 -- C 函数: int PyDateTime_TIME_GET_HOUR (PyDateTime_Time *o)

     返回小时，从0到23的整数。

 -- C 函数: int PyDateTime_TIME_GET_MINUTE (PyDateTime_Time *o)

     返回分钟，从0到59的整数。

 -- C 函数: int PyDateTime_TIME_GET_SECOND (PyDateTime_Time *o)

     返回秒，从0到59的整数。

 -- C 函数: int PyDateTime_TIME_GET_MICROSECOND (PyDateTime_Time *o)

     返回微秒，从0到999999的整数。

一些用来从 timedelta 对象中提取字段的宏。 参数必须是 ‘PyDateTime_Delta’
包括其子类的实例。 参数必须不为 ‘NULL’，并且类型不会被检查:

 -- C 函数: int PyDateTime_DELTA_GET_DAYS (PyDateTime_Delta *o)

     返回天数，从-999999999到999999999的整数。

     3.3 新版功能.

 -- C 函数: int PyDateTime_DELTA_GET_SECONDS (PyDateTime_Delta *o)

     返回秒数，从0到86399的整数。

     3.3 新版功能.

 -- C 函数: int PyDateTime_DELTA_GET_MICROSECONDS (PyDateTime_Delta *o)

     返回微秒数，从0到999999的整数。

     3.3 新版功能.

一些便于模块实现 DB API 的宏:

 -- C 函数: PyObject* PyDateTime_FromTimestamp (PyObject *args)
     `Return value: New reference.' 创建并返回一个给定元组参数的新 *note
     datetime.datetime: 195. 对象，适合传给 *note
     datetime.datetime.fromtimestamp(): 109b.。

 -- C 函数: PyObject* PyDate_FromTimestamp (PyObject *args)
     `Return value: New reference.' 创建并返回一个给定元组参数的新 *note
     datetime.date: 194. 对象，适合传给 *note
     datetime.date.fromtimestamp(): 18b9.。


File: python.info,  Node: 初始化，终结和线程,  Next: Python初始化配置,  Prev: 具体的对象层,  Up: Python/C API 参考手册

7.9 初始化，终结和线程
======================

请参阅 *note Python 初始化配置: 17e. 。

* Menu:

* 在Python初始化之前::
* 全局配置变量::
* Initializing and finalizing the interpreter::
* Process-wide parameters::
* Thread State and the Global Interpreter Lock::
* Sub-interpreter support::
* 异步通知::
* 分析和跟踪::
* 高级调试器支持::
* Thread Local Storage Support::


File: python.info,  Node: 在Python初始化之前,  Next: 全局配置变量,  Up: 初始化，终结和线程

7.9.1 在Python初始化之前
------------------------

在一个植入了 Python 的应用程序中，*note Py_Initialize(): 441. 函数必须在
任何其他 Python/C API 函数之前被调用；例外的只有个别函数和 *note
全局配置变量: 3f7c.。

在初始化Python之前，可以安全地调用以下函数：

   * 配置函数：

        * *note PyImport_AppendInittab(): 3b0b.

        * *note PyImport_ExtendInittab(): 3c6e.

        * ‘PyInitFrozenExtensions()’

        * *note PyMem_SetAllocator(): 3f7d.

        * *note PyMem_SetupDebugHooks(): 512.

        * *note PyObject_SetArenaAllocator(): 3f7e.

        * *note Py_SetPath(): 274.

        * *note Py_SetProgramName(): f99.

        * *note Py_SetPythonHome(): f98.

        * *note Py_SetStandardStreamEncoding(): 92d.

        * *note PySys_AddWarnOption(): 4bb.

        * *note PySys_AddXOption(): 3c55.

        * *note PySys_ResetWarnOptions(): 3c4e.

   * 信息函数：

        * *note Py_IsInitialized(): 3bc0.

        * *note PyMem_GetAllocator(): 3f7f.

        * *note PyObject_GetArenaAllocator(): 3f80.

        * *note Py_GetBuildInfo(): da2.

        * *note Py_GetCompiler(): 3f81.

        * *note Py_GetCopyright(): 3f82.

        * *note Py_GetPlatform(): 3f83.

        * *note Py_GetVersion(): 3f84.

   * 工具

        * *note Py_DecodeLocale(): 444.

   * 内存分配器：

        * *note PyMem_RawMalloc(): 975.

        * *note PyMem_RawRealloc(): 976.

        * *note PyMem_RawCalloc(): 7ae.

        * *note PyMem_RawFree(): 3c48.

     注解: 以下函数 `不应该' 在 *note Py_Initialize(): 441.: *note
     Py_EncodeLocale(): 445, *note Py_GetPath(): 3bbd, *note
     Py_GetPrefix(): 3bbe, *note Py_GetExecPrefix(): 3bbf, *note
     Py_GetProgramFullPath(): 276, *note Py_GetPythonHome(): 3f85, *note
     Py_GetProgramName(): 277. 和 *note PyEval_InitThreads(): c1a. 前调
     用。


File: python.info,  Node: 全局配置变量,  Next: Initializing and finalizing the interpreter,  Prev: 在Python初始化之前,  Up: 初始化，终结和线程

7.9.2 全局配置变量
------------------

Python 有负责控制全局配置中不同特性和选项的变量。这些标志默认被 *note
命令行选项: 134a.。

当一个选项设置一个旗标时，该旗标的值将是设置选项的次数。 例如，‘-b’ 会将
*note Py_BytesWarningFlag: 4bc. 设为 1 而 ‘-bb’ 会将 *note
Py_BytesWarningFlag: 4bc. 设为 2.

 -- C 变量: int Py_BytesWarningFlag

     Issue a warning when comparing *note bytes: 33a. or *note
     bytearray: 33b. with *note str: 339. or *note bytes: 33a. with
     *note int: 185.  Issue an error if greater or equal to ‘2’.

     由 *note -b: 41d. 选项设置。

 -- C 变量: int Py_DebugFlag

     Turn on parser debugging output (for expert only, depending on
     compilation options).

     Set by the *note -d: 1352. option and the *note PYTHONDEBUG: 1353.
     environment variable.

 -- C 变量: int Py_DontWriteBytecodeFlag

     If set to non-zero, Python won’t try to write ‘.pyc’ files on the
     import of source modules.

     Set by the *note -B: d40. option and the *note
     PYTHONDONTWRITEBYTECODE: d41. environment variable.

 -- C 变量: int Py_FrozenFlag

     Suppress error messages when calculating the module search path in
     *note Py_GetPath(): 3bbd.

     Private flag used by ‘_freeze_importlib’ and ‘frozenmain’ programs.

 -- C 变量: int Py_HashRandomizationFlag

     Set to ‘1’ if the *note PYTHONHASHSEED: 9cd. environment variable
     is set to a non-empty string.

     If the flag is non-zero, read the *note PYTHONHASHSEED: 9cd.
     environment variable to initialize the secret hash seed.

 -- C 变量: int Py_IgnoreEnvironmentFlag

     忽略所有 ‘PYTHON*’ 环境变量，例如可能已设置的 *note PYTHONPATH:
     95b. 和 *note PYTHONHOME: 4de.。

     由 *note -E: 1019. 和 *note -I: 1018. 选项设置。

 -- C 变量: int Py_InspectFlag

     When a script is passed as first argument or the *note -c: 121b.
     option is used, enter interactive mode after executing the script
     or the command, even when *note sys.stdin: 316. does not appear to
     be a terminal.

     Set by the *note -i: e27. option and the *note PYTHONINSPECT: e26.
     environment variable.

 -- C 变量: int Py_InteractiveFlag

     由 *note -i: e27. 选项设置。

 -- C 变量: int Py_IsolatedFlag

     Run Python in isolated mode.  In isolated mode *note sys.path: 490.
     contains neither the script’s directory nor the user’s
     site-packages directory.

     由 *note -I: 1018. 选项设置。

     3.4 新版功能.

 -- C 变量: int Py_LegacyWindowsFSEncodingFlag

     If the flag is non-zero, use the ‘mbcs’ encoding instead of the
     UTF-8 encoding for the filesystem encoding.

     Set to ‘1’ if the *note PYTHONLEGACYWINDOWSFSENCODING: 4ff.
     environment variable is set to a non-empty string.

     有关更多详细信息，请参阅 PEP 529(1)。

     *note 可用性: 136f.: Windows。

 -- C 变量: int Py_LegacyWindowsStdioFlag

     If the flag is non-zero, use *note io.FileIO: cac. instead of
     ‘WindowsConsoleIO’ for *note sys: fe. standard streams.

     Set to ‘1’ if the *note PYTHONLEGACYWINDOWSSTDIO: 502. environment
     variable is set to a non-empty string.

     有关更多详细信息，请参阅 PEP 528(2)。

     *note 可用性: 136f.: Windows。

 -- C 变量: int Py_NoSiteFlag

     禁用 *note site: ec. 的导入及其所附带的基于站点对 *note sys.path:
     490. 的操作。 如果 *note site: ec. 会在稍后被显式地导入也会禁用这些
     操作 (如果你希望触发它们则应调用 *note site.main(): 1357.)。

     由 *note -S: b2c. 选项设置。

 -- C 变量: int Py_NoUserSiteDirectory

     不要将 *note 用户 site-packages 目录: 1356. 添加到 *note sys.path:
     490.。

     Set by the *note -s: d1d. and *note -I: 1018. options, and the
     *note PYTHONNOUSERSITE: d1e. environment variable.

 -- C 变量: int Py_OptimizeFlag

     Set by the *note -O: 694. option and the *note PYTHONOPTIMIZE:
     1354. environment variable.

 -- C 变量: int Py_QuietFlag

     即使在交互模式下也不显示版权和版本信息。

     由 *note -q: 1355. 选项设置。

     3.2 新版功能.

 -- C 变量: int Py_UnbufferedStdioFlag

     Force the stdout and stderr streams to be unbuffered.

     Set by the *note -u: 1358. option and the *note PYTHONUNBUFFERED:
     1359. environment variable.

 -- C 变量: int Py_VerboseFlag

     Print a message each time a module is initialized, showing the
     place (filename or built-in module) from which it is loaded.  If
     greater or equal to ‘2’, print a message for each file that is
     checked for when searching for a module.  Also provides information
     on module cleanup at exit.

     Set by the *note -v: d90. option and the *note PYTHONVERBOSE: 135a.
     environment variable.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0529

   (2) https://www.python.org/dev/peps/pep-0528


File: python.info,  Node: Initializing and finalizing the interpreter,  Next: Process-wide parameters,  Prev: 全局配置变量,  Up: 初始化，终结和线程

7.9.3 Initializing and finalizing the interpreter
-------------------------------------------------

 -- C 函数: void Py_Initialize ()

     Initialize the Python interpreter.  In an application embedding
     Python, this should be called before using any other Python/C API
     functions; see *note Before Python Initialization: 442. for the few
     exceptions.

     This initializes the table of loaded modules (‘sys.modules’), and
     creates the fundamental modules *note builtins: 13, *note __main__:
     1. and *note sys: fe.  It also initializes the module search path
     (‘sys.path’).  It does not set ‘sys.argv’; use *note
     PySys_SetArgvEx(): c02. for that.  This is a no-op when called for
     a second time (without calling *note Py_FinalizeEx(): 5d2. first).
     There is no return value; it is a fatal error if the initialization
     fails.

          注解: On Windows, changes the console mode from ‘O_TEXT’ to
          ‘O_BINARY’, which will also affect non-Python uses of the
          console using the C Runtime.

 -- C 函数: void Py_InitializeEx (int initsigs)

     This function works like *note Py_Initialize(): 441. if `initsigs'
     is ‘1’.  If `initsigs' is ‘0’, it skips initialization registration
     of signal handlers, which might be useful when Python is embedded.

 -- C 函数: int Py_IsInitialized ()

     Return true (nonzero) when the Python interpreter has been
     initialized, false (zero) if not.  After *note Py_FinalizeEx():
     5d2. is called, this returns false until *note Py_Initialize():
     441. is called again.

 -- C 函数: int Py_FinalizeEx ()

     Undo all initializations made by *note Py_Initialize(): 441. and
     subsequent use of Python/C API functions, and destroy all
     sub-interpreters (see *note Py_NewInterpreter(): 3f95. below) that
     were created and not yet destroyed since the last call to *note
     Py_Initialize(): 441.  Ideally, this frees all memory allocated by
     the Python interpreter.  This is a no-op when called for a second
     time (without calling *note Py_Initialize(): 441. again first).
     Normally the return value is ‘0’.  If there were errors during
     finalization (flushing buffered data), ‘-1’ is returned.

     This function is provided for a number of reasons.  An embedding
     application might want to restart Python without having to restart
     the application itself.  An application that has loaded the Python
     interpreter from a dynamically loadable library (or DLL) might want
     to free all memory allocated by Python before unloading the DLL.
     During a hunt for memory leaks in an application a developer might
     want to free all memory allocated by Python before exiting from the
     application.

     `Bugs and caveats:' The destruction of modules and objects in
     modules is done in random order; this may cause destructors (*note
     __del__(): 927. methods) to fail when they depend on other objects
     (even functions) or modules.  Dynamically loaded extension modules
     loaded by Python are not unloaded.  Small amounts of memory
     allocated by the Python interpreter may not be freed (if you find a
     leak, please report it).  Memory tied up in circular references
     between objects is not freed.  Some memory allocated by extension
     modules may not be freed.  Some extensions may not work properly if
     their initialization routine is called more than once; this can
     happen if an application calls *note Py_Initialize(): 441. and
     *note Py_FinalizeEx(): 5d2. more than once.

     Raises an *note auditing event: ea1.
     ‘cpython._PySys_ClearAuditHooks’ with no arguments.

     3.6 新版功能.

 -- C 函数: void Py_Finalize ()

     This is a backwards-compatible version of *note Py_FinalizeEx():
     5d2. that disregards the return value.


File: python.info,  Node: Process-wide parameters,  Next: Thread State and the Global Interpreter Lock,  Prev: Initializing and finalizing the interpreter,  Up: 初始化，终结和线程

7.9.4 Process-wide parameters
-----------------------------

 -- C 函数: int Py_SetStandardStreamEncoding (const char *encoding,
          const char *errors)

     This function should be called before *note Py_Initialize(): 441,
     if it is called at all.  It specifies which encoding and error
     handling to use with standard IO, with the same meanings as in
     *note str.encode(): c3f.

     It overrides *note PYTHONIOENCODING: 937. values, and allows
     embedding code to control IO encoding when the environment variable
     does not work.

     `encoding' and/or `errors' may be ‘NULL’ to use *note
     PYTHONIOENCODING: 937. and/or default values (depending on other
     settings).

     Note that *note sys.stderr: 318. always uses the "backslashreplace"
     error handler, regardless of this (or any other) setting.

     If *note Py_FinalizeEx(): 5d2. is called, this function will need
     to be called again in order to affect subsequent calls to *note
     Py_Initialize(): 441.

     Returns ‘0’ if successful, a nonzero value on error (e.g.  calling
     after the interpreter has already been initialized).

     3.4 新版功能.

 -- C 函数: void Py_SetProgramName (const wchar_t *name)

     This function should be called before *note Py_Initialize(): 441.
     is called for the first time, if it is called at all.  It tells the
     interpreter the value of the ‘argv[0]’ argument to the ‘main()’
     function of the program (converted to wide characters).  This is
     used by *note Py_GetPath(): 3bbd. and some other functions below to
     find the Python run-time libraries relative to the interpreter
     executable.  The default value is ‘'python'’.  The argument should
     point to a zero-terminated wide character string in static storage
     whose contents will not change for the duration of the program’s
     execution.  No code in the Python interpreter will change the
     contents of this storage.

     Use *note Py_DecodeLocale(): 444. to decode a bytes string to get a
     ‘wchar_*’ string.

 -- C 函数: wchar* Py_GetProgramName ()

     Return the program name set with *note Py_SetProgramName(): f99, or
     the default.  The returned string points into static storage; the
     caller should not modify its value.

 -- C 函数: wchar_t* Py_GetPrefix ()

     Return the `prefix' for installed platform-independent files.  This
     is derived through a number of complicated rules from the program
     name set with *note Py_SetProgramName(): f99. and some environment
     variables; for example, if the program name is
     ‘'/usr/local/bin/python'’, the prefix is ‘'/usr/local'’.  The
     returned string points into static storage; the caller should not
     modify its value.  This corresponds to the ‘prefix’ variable in the
     top-level ‘Makefile’ and the ‘--prefix’ argument to the ‘configure’
     script at build time.  The value is available to Python code as
     ‘sys.prefix’.  It is only useful on Unix.  See also the next
     function.

 -- C 函数: wchar_t* Py_GetExecPrefix ()

     Return the `exec-prefix' for installed platform-`dependent' files.
     This is derived through a number of complicated rules from the
     program name set with *note Py_SetProgramName(): f99. and some
     environment variables; for example, if the program name is
     ‘'/usr/local/bin/python'’, the exec-prefix is ‘'/usr/local'’.  The
     returned string points into static storage; the caller should not
     modify its value.  This corresponds to the ‘exec_prefix’ variable
     in the top-level ‘Makefile’ and the ‘--exec-prefix’ argument to the
     ‘configure’ script at build time.  The value is available to Python
     code as ‘sys.exec_prefix’.  It is only useful on Unix.

     Background: The exec-prefix differs from the prefix when platform
     dependent files (such as executables and shared libraries) are
     installed in a different directory tree.  In a typical
     installation, platform dependent files may be installed in the
     ‘/usr/local/plat’ subtree while platform independent may be
     installed in ‘/usr/local’.

     Generally speaking, a platform is a combination of hardware and
     software families, e.g.  Sparc machines running the Solaris 2.x
     operating system are considered the same platform, but Intel
     machines running Solaris 2.x are another platform, and Intel
     machines running Linux are yet another platform.  Different major
     revisions of the same operating system generally also form
     different platforms.  Non-Unix operating systems are a different
     story; the installation strategies on those systems are so
     different that the prefix and exec-prefix are meaningless, and set
     to the empty string.  Note that compiled Python bytecode files are
     platform independent (but not independent from the Python version
     by which they were compiled!).

     System administrators will know how to configure the ‘mount’ or
     ‘automount’ programs to share ‘/usr/local’ between platforms while
     having ‘/usr/local/plat’ be a different filesystem for each
     platform.

 -- C 函数: wchar_t* Py_GetProgramFullPath ()

     Return the full program name of the Python executable; this is
     computed as a side-effect of deriving the default module search
     path from the program name (set by *note Py_SetProgramName(): f99.
     above).  The returned string points into static storage; the caller
     should not modify its value.  The value is available to Python code
     as ‘sys.executable’.

 -- C 函数: wchar_t* Py_GetPath ()

     Return the default module search path; this is computed from the
     program name (set by *note Py_SetProgramName(): f99. above) and
     some environment variables.  The returned string consists of a
     series of directory names separated by a platform dependent
     delimiter character.  The delimiter character is ‘':'’ on Unix and
     Mac OS X, ‘';'’ on Windows.  The returned string points into static
     storage; the caller should not modify its value.  The list *note
     sys.path: 490. is initialized with this value on interpreter
     startup; it can be (and usually is) modified later to change the
     search path for loading modules.

 -- C 函数: void Py_SetPath (const wchar_t *)

     Set the default module search path.  If this function is called
     before *note Py_Initialize(): 441, then *note Py_GetPath(): 3bbd.
     won’t attempt to compute a default search path but uses the one
     provided instead.  This is useful if Python is embedded by an
     application that has full knowledge of the location of all modules.
     The path components should be separated by the platform dependent
     delimiter character, which is ‘':'’ on Unix and Mac OS X, ‘';'’ on
     Windows.

     This also causes *note sys.executable: 275. to be set to the
     program full path (see *note Py_GetProgramFullPath(): 276.) and for
     *note sys.prefix: 3603. and *note sys.exec_prefix: 3604. to be
     empty.  It is up to the caller to modify these if required after
     calling *note Py_Initialize(): 441.

     Use *note Py_DecodeLocale(): 444. to decode a bytes string to get a
     ‘wchar_*’ string.

     The path argument is copied internally, so the caller may free it
     after the call completes.

     在 3.8 版更改: The program full path is now used for *note
     sys.executable: 275, instead of the program name.

 -- C 函数: const char* Py_GetVersion ()

     Return the version of this Python interpreter.  This is a string
     that looks something like

          "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"

     The first word (up to the first space character) is the current
     Python version; the first three characters are the major and minor
     version separated by a period.  The returned string points into
     static storage; the caller should not modify its value.  The value
     is available to Python code as *note sys.version: 5dc.

 -- C 函数: const char* Py_GetPlatform ()

     Return the platform identifier for the current platform.  On Unix,
     this is formed from the "official" name of the operating system,
     converted to lower case, followed by the major revision number;
     e.g., for Solaris 2.x, which is also known as SunOS 5.x, the value
     is ‘'sunos5'’.  On Mac OS X, it is ‘'darwin'’.  On Windows, it is
     ‘'win'’.  The returned string points into static storage; the
     caller should not modify its value.  The value is available to
     Python code as ‘sys.platform’.

 -- C 函数: const char* Py_GetCopyright ()

     Return the official copyright string for the current Python
     version, for example

     ‘'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'’

     The returned string points into static storage; the caller should
     not modify its value.  The value is available to Python code as
     ‘sys.copyright’.

 -- C 函数: const char* Py_GetCompiler ()

     Return an indication of the compiler used to build the current
     Python version, in square brackets, for example:

          "[GCC 2.7.2.2]"

     The returned string points into static storage; the caller should
     not modify its value.  The value is available to Python code as
     part of the variable ‘sys.version’.

 -- C 函数: const char* Py_GetBuildInfo ()

     Return information about the sequence number and build date and
     time of the current Python interpreter instance, for example

          "#67, Aug  1 1997, 22:34:28"

     The returned string points into static storage; the caller should
     not modify its value.  The value is available to Python code as
     part of the variable ‘sys.version’.

 -- C 函数: void PySys_SetArgvEx (int argc, wchar_t **argv,
          int updatepath)

     Set *note sys.argv: c03. based on `argc' and `argv'.  These
     parameters are similar to those passed to the program’s ‘main()’
     function with the difference that the first entry should refer to
     the script file to be executed rather than the executable hosting
     the Python interpreter.  If there isn’t a script that will be run,
     the first entry in `argv' can be an empty string.  If this function
     fails to initialize *note sys.argv: c03, a fatal condition is
     signalled using *note Py_FatalError(): f9a.

     If `updatepath' is zero, this is all the function does.  If
     `updatepath' is non-zero, the function also modifies *note
     sys.path: 490. according to the following algorithm:

        - If the name of an existing script is passed in ‘argv[0]’, the
          absolute path of the directory where the script is located is
          prepended to *note sys.path: 490.

        - Otherwise (that is, if `argc' is ‘0’ or ‘argv[0]’ doesn’t
          point to an existing file name), an empty string is prepended
          to *note sys.path: 490, which is the same as prepending the
          current working directory (‘"."’).

     Use *note Py_DecodeLocale(): 444. to decode a bytes string to get a
     ‘wchar_*’ string.

          注解: It is recommended that applications embedding the Python
          interpreter for purposes other than executing a single script
          pass ‘0’ as `updatepath', and update *note sys.path: 490.
          themselves if desired.  See CVE-2008-5983(1).

          On versions before 3.1.3, you can achieve the same effect by
          manually popping the first *note sys.path: 490. element after
          having called *note PySys_SetArgv(): cf4, for example using:

               PyRun_SimpleString("import sys; sys.path.pop(0)\n");

     3.1.3 新版功能.

 -- C 函数: void PySys_SetArgv (int argc, wchar_t **argv)

     This function works like *note PySys_SetArgvEx(): c02. with
     `updatepath' set to ‘1’ unless the ‘python’ interpreter was started
     with the *note -I: 1018.

     Use *note Py_DecodeLocale(): 444. to decode a bytes string to get a
     ‘wchar_*’ string.

     在 3.4 版更改: The `updatepath' value depends on *note -I: 1018.

 -- C 函数: void Py_SetPythonHome (const wchar_t *home)

     Set the default "home" directory, that is, the location of the
     standard Python libraries.  See *note PYTHONHOME: 4de. for the
     meaning of the argument string.

     The argument should point to a zero-terminated character string in
     static storage whose contents will not change for the duration of
     the program’s execution.  No code in the Python interpreter will
     change the contents of this storage.

     Use *note Py_DecodeLocale(): 444. to decode a bytes string to get a
     ‘wchar_*’ string.

 -- C 函数: w_char* Py_GetPythonHome ()

     Return the default "home", that is, the value set by a previous
     call to *note Py_SetPythonHome(): f98, or the value of the *note
     PYTHONHOME: 4de. environment variable if it is set.

   ---------- Footnotes ----------

   (1) https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983


File: python.info,  Node: Thread State and the Global Interpreter Lock,  Next: Sub-interpreter support,  Prev: Process-wide parameters,  Up: 初始化，终结和线程

7.9.5 Thread State and the Global Interpreter Lock
--------------------------------------------------

The Python interpreter is not fully thread-safe.  In order to support
multi-threaded Python programs, there’s a global lock, called the *note
global interpreter lock: 50e. or *note GIL: bf2, that must be held by
the current thread before it can safely access Python objects.  Without
the lock, even the simplest operations could cause problems in a
multi-threaded program: for example, when two threads simultaneously
increment the reference count of the same object, the reference count
could end up being incremented only once instead of twice.

Therefore, the rule exists that only the thread that has acquired the
*note GIL: bf2. may operate on Python objects or call Python/C API
functions.  In order to emulate concurrency of execution, the
interpreter regularly tries to switch threads (see *note
sys.setswitchinterval(): bf3.).  The lock is also released around
potentially blocking I/O operations like reading or writing a file, so
that other Python threads can run in the meantime.

The Python interpreter keeps some thread-specific bookkeeping
information inside a data structure called *note PyThreadState: 3f99.
There’s also one global variable pointing to the current *note
PyThreadState: 3f99.: it can be retrieved using *note
PyThreadState_Get(): 3f9a.

* Menu:

* Releasing the GIL from extension code::
* 非Python创建的线程::
* Cautions about fork(): Cautions about fork.
* 高阶 API::
* Low-level API::


File: python.info,  Node: Releasing the GIL from extension code,  Next: 非Python创建的线程,  Up: Thread State and the Global Interpreter Lock

7.9.5.1 Releasing the GIL from extension code
.............................................

Most extension code manipulating the *note GIL: bf2. has the following
simple structure:

     Save the thread state in a local variable.
     Release the global interpreter lock.
     ... Do some blocking I/O operation ...
     Reacquire the global interpreter lock.
     Restore the thread state from the local variable.

This is so common that a pair of macros exists to simplify it:

     Py_BEGIN_ALLOW_THREADS
     ... Do some blocking I/O operation ...
     Py_END_ALLOW_THREADS

The *note Py_BEGIN_ALLOW_THREADS: 3b29. macro opens a new block and
declares a hidden local variable; the *note Py_END_ALLOW_THREADS: 2b6.
macro closes the block.

The block above expands to the following code:

     PyThreadState *_save;

     _save = PyEval_SaveThread();
     ... Do some blocking I/O operation ...
     PyEval_RestoreThread(_save);

Here is how these functions work: the global interpreter lock is used to
protect the pointer to the current thread state.  When releasing the
lock and saving the thread state, the current thread state pointer must
be retrieved before the lock is released (since another thread could
immediately acquire the lock and store its own thread state in the
global variable).  Conversely, when acquiring the lock and restoring the
thread state, the lock must be acquired before storing the thread state
pointer.

     注解: Calling system I/O functions is the most common use case for
     releasing the GIL, but it can also be useful before calling
     long-running computations which don’t need access to Python
     objects, such as compression or cryptographic functions operating
     over memory buffers.  For example, the standard *note zlib: 145.
     and *note hashlib: 8d. modules release the GIL when compressing or
     hashing data.


File: python.info,  Node: 非Python创建的线程,  Next: Cautions about fork,  Prev: Releasing the GIL from extension code,  Up: Thread State and the Global Interpreter Lock

7.9.5.2 非Python创建的线程
..........................

When threads are created using the dedicated Python APIs (such as the
*note threading: 10a. module), a thread state is automatically
associated to them and the code showed above is therefore correct.
However, when threads are created from C (for example by a third-party
library with its own thread management), they don’t hold the GIL, nor is
there a thread state structure for them.

If you need to call Python code from these threads (often this will be
part of a callback API provided by the aforementioned third-party
library), you must first register these threads with the interpreter by
creating a thread state data structure, then acquiring the GIL, and
finally storing their thread state pointer, before you can start using
the Python/C API. When you are done, you should reset the thread state
pointer, release the GIL, and finally free the thread state data
structure.

The *note PyGILState_Ensure(): 2b7. and *note PyGILState_Release():
3f9e. functions do all of the above automatically.  The typical idiom
for calling into Python from a C thread is:

     PyGILState_STATE gstate;
     gstate = PyGILState_Ensure();

     /* Perform Python actions here. */
     result = CallSomeFunction();
     /* evaluate result or handle exception */

     /* Release the thread. No Python API allowed beyond this point. */
     PyGILState_Release(gstate);

Note that the ‘PyGILState_*()’ functions assume there is only one global
interpreter (created automatically by *note Py_Initialize(): 441.).
Python supports the creation of additional interpreters (using *note
Py_NewInterpreter(): 3f95.), but mixing multiple interpreters and the
‘PyGILState_*()’ API is unsupported.


File: python.info,  Node: Cautions about fork,  Next: 高阶 API,  Prev: 非Python创建的线程,  Up: Thread State and the Global Interpreter Lock

7.9.5.3 Cautions about fork()
.............................

Another important thing to note about threads is their behaviour in the
face of the C ‘fork()’ call.  On most systems with ‘fork()’, after a
process forks only the thread that issued the fork will exist.  This has
a concrete impact both on how locks must be handled and on all stored
state in CPython’s runtime.

The fact that only the "current" thread remains means any locks held by
other threads will never be released.  Python solves this for *note
os.fork(): 969. by acquiring the locks it uses internally before the
fork, and releasing them afterwards.  In addition, it resets any *note
锁对象: 2371. in the child.  When extending or embedding Python, there
is no way to inform Python of additional (non-Python) locks that need to
be acquired before or reset after a fork.  OS facilities such as
‘pthread_atfork()’ would need to be used to accomplish the same thing.
Additionally, when extending or embedding Python, calling ‘fork()’
directly rather than through *note os.fork(): 969. (and returning to or
calling into Python) may result in a deadlock by one of Python’s
internal locks being held by a thread that is defunct after the fork.
*note PyOS_AfterFork_Child(): 2ce. tries to reset the necessary locks,
but is not always able to.

The fact that all other threads go away also means that CPython’s
runtime state there must be cleaned up properly, which *note os.fork():
969. does.  This means finalizing all other *note PyThreadState: 3f99.
objects belonging to the current interpreter and all other *note
PyInterpreterState: 2c3. objects.  Due to this and the special nature of
the *note "main" interpreter: 3c44, ‘fork()’ should only be called in
that interpreter’s "main" thread, where the CPython global runtime was
originally initialized.  The only exception is if ‘exec()’ will be
called immediately after.


File: python.info,  Node: 高阶 API,  Next: Low-level API,  Prev: Cautions about fork,  Up: Thread State and the Global Interpreter Lock

7.9.5.4 高阶 API
................

These are the most commonly used types and functions when writing C
extension code, or when embedding the Python interpreter:

 -- C 类型: PyInterpreterState

     This data structure represents the state shared by a number of
     cooperating threads.  Threads belonging to the same interpreter
     share their module administration and a few other internal items.
     There are no public members in this structure.

     Threads belonging to different interpreters initially share
     nothing, except process state like available memory, open file
     descriptors and such.  The global interpreter lock is also shared
     by all threads, regardless of to which interpreter they belong.

 -- C 类型: PyThreadState

     This data structure represents the state of a single thread.  The
     only public data member is ‘interp’ (*note PyInterpreterState *:
     2c3.), which points to this thread’s interpreter state.

 -- C 函数: void PyEval_InitThreads ()

     Initialize and acquire the global interpreter lock.  It should be
     called in the main thread before creating a second thread or
     engaging in any other thread operations such as
     ‘PyEval_ReleaseThread(tstate)’.  It is not needed before calling
     *note PyEval_SaveThread(): c19. or *note PyEval_RestoreThread():
     2b5.

     This is a no-op when called for a second time.

     在 3.7 版更改: This function is now called by *note
     Py_Initialize(): 441, so you don’t have to call it yourself
     anymore.

     在 3.2 版更改: This function cannot be called before *note
     Py_Initialize(): 441. anymore.

 -- C 函数: int PyEval_ThreadsInitialized ()

     Returns a non-zero value if *note PyEval_InitThreads(): c1a. has
     been called.  This function can be called without holding the GIL,
     and therefore can be used to avoid calls to the locking API when
     running single-threaded.

     在 3.7 版更改: The *note GIL: bf2. is now initialized by *note
     Py_Initialize(): 441.

 -- C 函数: PyThreadState* PyEval_SaveThread ()

     Release the global interpreter lock (if it has been created) and
     reset the thread state to ‘NULL’, returning the previous thread
     state (which is not ‘NULL’).  If the lock has been created, the
     current thread must have acquired it.

 -- C 函数: void PyEval_RestoreThread (PyThreadState *tstate)

     Acquire the global interpreter lock (if it has been created) and
     set the thread state to `tstate', which must not be ‘NULL’.  If the
     lock has been created, the current thread must not have acquired
     it, otherwise deadlock ensues.

          注解: Calling this function from a thread when the runtime is
          finalizing will terminate the thread, even if the thread was
          not created by Python.  You can use ‘_Py_IsFinalizing()’ or
          *note sys.is_finalizing(): 76b. to check if the interpreter is
          in process of being finalized before calling this function to
          avoid unwanted termination.

 -- C 函数: PyThreadState* PyThreadState_Get ()

     Return the current thread state.  The global interpreter lock must
     be held.  When the current thread state is ‘NULL’, this issues a
     fatal error (so that the caller needn’t check for ‘NULL’).

 -- C 函数: PyThreadState* PyThreadState_Swap (PyThreadState *tstate)

     Swap the current thread state with the thread state given by the
     argument `tstate', which may be ‘NULL’.  The global interpreter
     lock must be held and is not released.

The following functions use thread-local storage, and are not compatible
with sub-interpreters:

 -- C 函数: PyGILState_STATE PyGILState_Ensure ()

     Ensure that the current thread is ready to call the Python C API
     regardless of the current state of Python, or of the global
     interpreter lock.  This may be called as many times as desired by a
     thread as long as each call is matched with a call to *note
     PyGILState_Release(): 3f9e.  In general, other thread-related APIs
     may be used between *note PyGILState_Ensure(): 2b7. and *note
     PyGILState_Release(): 3f9e. calls as long as the thread state is
     restored to its previous state before the Release().  For example,
     normal usage of the *note Py_BEGIN_ALLOW_THREADS: 3b29. and *note
     Py_END_ALLOW_THREADS: 2b6. macros is acceptable.

     The return value is an opaque "handle" to the thread state when
     *note PyGILState_Ensure(): 2b7. was called, and must be passed to
     *note PyGILState_Release(): 3f9e. to ensure Python is left in the
     same state.  Even though recursive calls are allowed, these handles
     `cannot' be shared - each unique call to *note PyGILState_Ensure():
     2b7. must save the handle for its call to *note
     PyGILState_Release(): 3f9e.

     When the function returns, the current thread will hold the GIL and
     be able to call arbitrary Python code.  Failure is a fatal error.

          注解: Calling this function from a thread when the runtime is
          finalizing will terminate the thread, even if the thread was
          not created by Python.  You can use ‘_Py_IsFinalizing()’ or
          *note sys.is_finalizing(): 76b. to check if the interpreter is
          in process of being finalized before calling this function to
          avoid unwanted termination.

 -- C 函数: void PyGILState_Release (PyGILState_STATE)

     Release any resources previously acquired.  After this call,
     Python’s state will be the same as it was prior to the
     corresponding *note PyGILState_Ensure(): 2b7. call (but generally
     this state will be unknown to the caller, hence the use of the
     GILState API).

     Every call to *note PyGILState_Ensure(): 2b7. must be matched by a
     call to *note PyGILState_Release(): 3f9e. on the same thread.

 -- C 函数: PyThreadState* PyGILState_GetThisThreadState ()

     Get the current thread state for this thread.  May return ‘NULL’ if
     no GILState API has been used on the current thread.  Note that the
     main thread always has such a thread-state, even if no
     auto-thread-state call has been made on the main thread.  This is
     mainly a helper/diagnostic function.

 -- C 函数: int PyGILState_Check ()

     Return ‘1’ if the current thread is holding the GIL and ‘0’
     otherwise.  This function can be called from any thread at any
     time.  Only if it has had its Python thread state initialized and
     currently is holding the GIL will it return ‘1’.  This is mainly a
     helper/diagnostic function.  It can be useful for example in
     callback contexts or memory allocation functions when knowing that
     the GIL is locked can allow the caller to perform sensitive actions
     or otherwise behave differently.

     3.4 新版功能.

The following macros are normally used without a trailing semicolon;
look for example usage in the Python source distribution.

 -- C 宏: Py_BEGIN_ALLOW_THREADS

     This macro expands to ‘{ PyThreadState *_save; _save =
     PyEval_SaveThread();’.  Note that it contains an opening brace; it
     must be matched with a following *note Py_END_ALLOW_THREADS: 2b6.
     macro.  See above for further discussion of this macro.

 -- C 宏: Py_END_ALLOW_THREADS

     This macro expands to ‘PyEval_RestoreThread(_save); }’.  Note that
     it contains a closing brace; it must be matched with an earlier
     *note Py_BEGIN_ALLOW_THREADS: 3b29. macro.  See above for further
     discussion of this macro.

 -- C 宏: Py_BLOCK_THREADS

     This macro expands to ‘PyEval_RestoreThread(_save);’: it is
     equivalent to *note Py_END_ALLOW_THREADS: 2b6. without the closing
     brace.

 -- C 宏: Py_UNBLOCK_THREADS

     This macro expands to ‘_save = PyEval_SaveThread();’: it is
     equivalent to *note Py_BEGIN_ALLOW_THREADS: 3b29. without the
     opening brace and variable declaration.


File: python.info,  Node: Low-level API,  Prev: 高阶 API,  Up: Thread State and the Global Interpreter Lock

7.9.5.5 Low-level API
.....................

All of the following functions must be called after *note
Py_Initialize(): 441.

在 3.7 版更改: *note Py_Initialize(): 441. now initializes the *note
GIL: bf2.

 -- C 函数: PyInterpreterState* PyInterpreterState_New ()

     Create a new interpreter state object.  The global interpreter lock
     need not be held, but may be held if it is necessary to serialize
     calls to this function.

     Raises an *note auditing event: ea1.
     ‘cpython.PyInterpreterState_New’ with no arguments.

 -- C 函数: void PyInterpreterState_Clear (PyInterpreterState *interp)

     Reset all information in an interpreter state object.  The global
     interpreter lock must be held.

     Raises an *note auditing event: ea1.
     ‘cpython.PyInterpreterState_Clear’ with no arguments.

 -- C 函数: void PyInterpreterState_Delete (PyInterpreterState *interp)

     Destroy an interpreter state object.  The global interpreter lock
     need not be held.  The interpreter state must have been reset with
     a previous call to *note PyInterpreterState_Clear(): 34d2.

 -- C 函数: PyThreadState* PyThreadState_New
          (PyInterpreterState *interp)

     Create a new thread state object belonging to the given interpreter
     object.  The global interpreter lock need not be held, but may be
     held if it is necessary to serialize calls to this function.

 -- C 函数: void PyThreadState_Clear (PyThreadState *tstate)

     Reset all information in a thread state object.  The global
     interpreter lock must be held.

 -- C 函数: void PyThreadState_Delete (PyThreadState *tstate)

     Destroy a thread state object.  The global interpreter lock need
     not be held.  The thread state must have been reset with a previous
     call to *note PyThreadState_Clear(): f2f.

 -- C 函数: PY_INT64_T PyInterpreterState_GetID
          (PyInterpreterState *interp)

     Return the interpreter’s unique ID. If there was any error in doing
     so then ‘-1’ is returned and an error is set.

     3.7 新版功能.

 -- C 函数: PyObject* PyInterpreterState_GetDict
          (PyInterpreterState *interp)

     Return a dictionary in which interpreter-specific data may be
     stored.  If this function returns ‘NULL’ then no exception has been
     raised and the caller should assume no interpreter-specific dict is
     available.

     This is not a replacement for *note PyModule_GetState(): 3ed4,
     which extensions should use to store interpreter-specific state
     information.

     3.8 新版功能.

 -- C 函数: PyObject* PyThreadState_GetDict ()
     `Return value: Borrowed reference.'  Return a dictionary in which
     extensions can store thread-specific state information.  Each
     extension should use a unique key to use to store state in the
     dictionary.  It is okay to call this function when no current
     thread state is available.  If this function returns ‘NULL’, no
     exception has been raised and the caller should assume no current
     thread state is available.

 -- C 函数: int PyThreadState_SetAsyncExc (unsigned long id,
          PyObject *exc)

     Asynchronously raise an exception in a thread.  The `id' argument
     is the thread id of the target thread; `exc' is the exception
     object to be raised.  This function does not steal any references
     to `exc'.  To prevent naive misuse, you must write your own C
     extension to call this.  Must be called with the GIL held.  Returns
     the number of thread states modified; this is normally one, but
     will be zero if the thread id isn’t found.  If `exc' is ‘NULL’, the
     pending exception (if any) for the thread is cleared.  This raises
     no exceptions.

     在 3.7 版更改: The type of the `id' parameter changed from ‘long’
     to ‘unsigned long’.

 -- C 函数: void PyEval_AcquireThread (PyThreadState *tstate)

     Acquire the global interpreter lock and set the current thread
     state to `tstate', which should not be ‘NULL’.  The lock must have
     been created earlier.  If this thread already has the lock,
     deadlock ensues.

          注解: Calling this function from a thread when the runtime is
          finalizing will terminate the thread, even if the thread was
          not created by Python.  You can use ‘_Py_IsFinalizing()’ or
          *note sys.is_finalizing(): 76b. to check if the interpreter is
          in process of being finalized before calling this function to
          avoid unwanted termination.

     在 3.8 版更改: Updated to be consistent with *note
     PyEval_RestoreThread(): 2b5, *note Py_END_ALLOW_THREADS(): 2b6, and
     *note PyGILState_Ensure(): 2b7, and terminate the current thread if
     called while the interpreter is finalizing.

     *note PyEval_RestoreThread(): 2b5. is a higher-level function which
     is always available (even when threads have not been initialized).

 -- C 函数: void PyEval_ReleaseThread (PyThreadState *tstate)

     Reset the current thread state to ‘NULL’ and release the global
     interpreter lock.  The lock must have been created earlier and must
     be held by the current thread.  The `tstate' argument, which must
     not be ‘NULL’, is only used to check that it represents the current
     thread state — if it isn’t, a fatal error is reported.

     *note PyEval_SaveThread(): c19. is a higher-level function which is
     always available (even when threads have not been initialized).

 -- C 函数: void PyEval_AcquireLock ()

     Acquire the global interpreter lock.  The lock must have been
     created earlier.  If this thread already has the lock, a deadlock
     ensues.

     3.2 版后已移除: This function does not update the current thread
     state.  Please use *note PyEval_RestoreThread(): 2b5. or *note
     PyEval_AcquireThread(): 2b4. instead.

          注解: Calling this function from a thread when the runtime is
          finalizing will terminate the thread, even if the thread was
          not created by Python.  You can use ‘_Py_IsFinalizing()’ or
          *note sys.is_finalizing(): 76b. to check if the interpreter is
          in process of being finalized before calling this function to
          avoid unwanted termination.

     在 3.8 版更改: Updated to be consistent with *note
     PyEval_RestoreThread(): 2b5, *note Py_END_ALLOW_THREADS(): 2b6, and
     *note PyGILState_Ensure(): 2b7, and terminate the current thread if
     called while the interpreter is finalizing.

 -- C 函数: void PyEval_ReleaseLock ()

     Release the global interpreter lock.  The lock must have been
     created earlier.

     3.2 版后已移除: This function does not update the current thread
     state.  Please use *note PyEval_SaveThread(): c19. or *note
     PyEval_ReleaseThread(): 3fac. instead.


File: python.info,  Node: Sub-interpreter support,  Next: 异步通知,  Prev: Thread State and the Global Interpreter Lock,  Up: 初始化，终结和线程

7.9.6 Sub-interpreter support
-----------------------------

While in most uses, you will only embed a single Python interpreter,
there are cases where you need to create several independent
interpreters in the same process and perhaps even in the same thread.
Sub-interpreters allow you to do that.

The "main" interpreter is the first one created when the runtime
initializes.  It is usually the only Python interpreter in a process.
Unlike sub-interpreters, the main interpreter has unique process-global
responsibilities like signal handling.  It is also responsible for
execution during runtime initialization and is usually the active
interpreter during runtime finalization.  The *note
PyInterpreterState_Main(): 3fae. function returns a pointer to its
state.

You can switch between sub-interpreters using the *note
PyThreadState_Swap(): 3fa1. function.  You can create and destroy them
using the following functions:

 -- C 函数: PyThreadState* Py_NewInterpreter ()

     Create a new sub-interpreter.  This is an (almost) totally separate
     environment for the execution of Python code.  In particular, the
     new interpreter has separate, independent versions of all imported
     modules, including the fundamental modules *note builtins: 13,
     *note __main__: 1. and *note sys: fe.  The table of loaded modules
     (‘sys.modules’) and the module search path (‘sys.path’) are also
     separate.  The new environment has no ‘sys.argv’ variable.  It has
     new standard I/O stream file objects ‘sys.stdin’, ‘sys.stdout’ and
     ‘sys.stderr’ (however these refer to the same underlying file
     descriptors).

     The return value points to the first thread state created in the
     new sub-interpreter.  This thread state is made in the current
     thread state.  Note that no actual thread is created; see the
     discussion of thread states below.  If creation of the new
     interpreter is unsuccessful, ‘NULL’ is returned; no exception is
     set since the exception state is stored in the current thread state
     and there may not be a current thread state.  (Like all other
     Python/C API functions, the global interpreter lock must be held
     before calling this function and is still held when it returns;
     however, unlike most other Python/C API functions, there needn’t be
     a current thread state on entry.)

     Extension modules are shared between (sub-)interpreters as follows:

        * For modules using multi-phase initialization, e.g.  *note
          PyModule_FromDefAndSpec(): 7b4, a separate module object is
          created and initialized for each interpreter.  Only C-level
          static and global variables are shared between these module
          objects.

        * For modules using single-phase initialization, e.g.  *note
          PyModule_Create(): 3b0a, the first time a particular extension
          is imported, it is initialized normally, and a (shallow) copy
          of its module’s dictionary is squirreled away.  When the same
          extension is imported by another (sub-)interpreter, a new
          module is initialized and filled with the contents of this
          copy; the extension’s ‘init’ function is not called.  Objects
          in the module’s dictionary thus end up shared across
          (sub-)interpreters, which might cause unwanted behavior (see
          *note Bugs and caveats: 3faf. below).

          Note that this is different from what happens when an
          extension is imported after the interpreter has been
          completely re-initialized by calling *note Py_FinalizeEx():
          5d2. and *note Py_Initialize(): 441.; in that case, the
          extension’s ‘initmodule’ function `is' called again.  As with
          multi-phase initialization, this means that only C-level
          static and global variables are shared between these modules.

 -- C 函数: void Py_EndInterpreter (PyThreadState *tstate)

     Destroy the (sub-)interpreter represented by the given thread
     state.  The given thread state must be the current thread state.
     See the discussion of thread states below.  When the call returns,
     the current thread state is ‘NULL’.  All thread states associated
     with this interpreter are destroyed.  (The global interpreter lock
     must be held before calling this function and is still held when it
     returns.)  *note Py_FinalizeEx(): 5d2. will destroy all
     sub-interpreters that haven’t been explicitly destroyed at that
     point.

* Menu:

* 错误和警告::


File: python.info,  Node: 错误和警告,  Up: Sub-interpreter support

7.9.6.1 错误和警告
..................

Because sub-interpreters (and the main interpreter) are part of the same
process, the insulation between them isn’t perfect — for example, using
low-level file operations like *note os.close(): 3da. they can
(accidentally or maliciously) affect each other’s open files.  Because
of the way extensions are shared between (sub-)interpreters, some
extensions may not work properly; this is especially likely when using
single-phase initialization or (static) global variables.  It is
possible to insert objects created in one sub-interpreter into a
namespace of another (sub-)interpreter; this should be avoided if
possible.

Special care should be taken to avoid sharing user-defined functions,
methods, instances or classes between sub-interpreters, since import
operations executed by such objects may affect the wrong
(sub-)interpreter’s dictionary of loaded modules.  It is equally
important to avoid sharing objects from which the above are reachable.

Also note that combining this functionality with ‘PyGILState_*()’ APIs
is delicate, because these APIs assume a bijection between Python thread
states and OS-level threads, an assumption broken by the presence of
sub-interpreters.  It is highly recommended that you don’t switch
sub-interpreters between a pair of matching *note PyGILState_Ensure():
2b7. and *note PyGILState_Release(): 3f9e. calls.  Furthermore,
extensions (such as *note ctypes: 2b.) using these APIs to allow calling
of Python code from non-Python created threads will probably be broken
when using sub-interpreters.


File: python.info,  Node: 异步通知,  Next: 分析和跟踪,  Prev: Sub-interpreter support,  Up: 初始化，终结和线程

7.9.7 异步通知
--------------

A mechanism is provided to make asynchronous notifications to the main
interpreter thread.  These notifications take the form of a function
pointer and a void pointer argument.

 -- C 函数: int Py_AddPendingCall (int (*func)(void *), void *arg)

     Schedule a function to be called from the main interpreter thread.
     On success, ‘0’ is returned and `func' is queued for being called
     in the main thread.  On failure, ‘-1’ is returned without setting
     any exception.

     When successfully queued, `func' will be `eventually' called from
     the main interpreter thread with the argument `arg'.  It will be
     called asynchronously with respect to normally running Python code,
     but with both these conditions met:

        * on a *note bytecode: 61d. boundary;

        * with the main thread holding the *note global interpreter
          lock: 50e. (`func' can therefore use the full C API).

     `func' must return ‘0’ on success, or ‘-1’ on failure with an
     exception set.  `func' won’t be interrupted to perform another
     asynchronous notification recursively, but it can still be
     interrupted to switch threads if the global interpreter lock is
     released.

     This function doesn’t need a current thread state to run, and it
     doesn’t need the global interpreter lock.

          警告: This is a low-level function, only useful for very
          special cases.  There is no guarantee that `func' will be
          called as quick as possible.  If the main thread is busy
          executing a system call, `func' won’t be called before the
          system call returns.  This function is generally `not'
          suitable for calling Python code from arbitrary C threads.
          Instead, use the *note PyGILState API: 3f9c.

     3.1 新版功能.


File: python.info,  Node: 分析和跟踪,  Next: 高级调试器支持,  Prev: 异步通知,  Up: 初始化，终结和线程

7.9.8 分析和跟踪
----------------

The Python interpreter provides some low-level support for attaching
profiling and execution tracing facilities.  These are used for
profiling, debugging, and coverage analysis tools.

This C interface allows the profiling or tracing code to avoid the
overhead of calling through Python-level callable objects, making a
direct C function call instead.  The essential attributes of the
facility have not changed; the interface allows trace functions to be
installed per-thread, and the basic events reported to the trace
function are the same as had been reported to the Python-level trace
functions in previous versions.

 -- C 类型: int (*Py_tracefunc) (PyObject *obj, PyFrameObject *frame,
          int what, PyObject *arg)

     The type of the trace function registered using *note
     PyEval_SetProfile(): e43. and *note PyEval_SetTrace(): e44.  The
     first parameter is the object passed to the registration function
     as `obj', `frame' is the frame object to which the event pertains,
     `what' is one of the constants ‘PyTrace_CALL’, ‘PyTrace_EXCEPTION’,
     ‘PyTrace_LINE’, ‘PyTrace_RETURN’, ‘PyTrace_C_CALL’,
     ‘PyTrace_C_EXCEPTION’, ‘PyTrace_C_RETURN’, or ‘PyTrace_OPCODE’, and
     `arg' depends on the value of `what':

     `what' 的值                        `arg' 的含义
                                        
     --------------------------------------------------------------------------------
                                        
     ‘PyTrace_CALL’                     总是 *note Py_None: 3b07.
                                        
                                        
     ‘PyTrace_EXCEPTION’                *note sys.exc_info(): c67. 返回的异常信息
                                        。
                                        
                                        
     ‘PyTrace_LINE’                     总是 *note Py_None: 3b07.
                                        
                                        
     ‘PyTrace_RETURN’                   Value being returned to the caller, or
                                        ‘NULL’ if caused by an exception.
                                        
                                        
     ‘PyTrace_C_CALL’                   正在调用函数对象。
                                        
                                        
     ‘PyTrace_C_EXCEPTION’              正在调用函数对象。
                                        
                                        
     ‘PyTrace_C_RETURN’                 正在调用函数对象。
                                        
                                        
     ‘PyTrace_OPCODE’                   总是 *note Py_None: 3b07.
                                        

 -- C 变量: int PyTrace_CALL

     The value of the `what' parameter to a *note Py_tracefunc: 3fb4.
     function when a new call to a function or method is being reported,
     or a new entry into a generator.  Note that the creation of the
     iterator for a generator function is not reported as there is no
     control transfer to the Python bytecode in the corresponding frame.

 -- C 变量: int PyTrace_EXCEPTION

     The value of the `what' parameter to a *note Py_tracefunc: 3fb4.
     function when an exception has been raised.  The callback function
     is called with this value for `what' when after any bytecode is
     processed after which the exception becomes set within the frame
     being executed.  The effect of this is that as exception
     propagation causes the Python stack to unwind, the callback is
     called upon return to each frame as the exception propagates.  Only
     trace functions receives these events; they are not needed by the
     profiler.

 -- C 变量: int PyTrace_LINE

     The value passed as the `what' parameter to a *note Py_tracefunc:
     3fb4. function (but not a profiling function) when a line-number
     event is being reported.  It may be disabled for a frame by setting
     ‘f_trace_lines’ to `0' on that frame.

 -- C 变量: int PyTrace_RETURN

     The value for the `what' parameter to *note Py_tracefunc: 3fb4.
     functions when a call is about to return.

 -- C 变量: int PyTrace_C_CALL

     The value for the `what' parameter to *note Py_tracefunc: 3fb4.
     functions when a C function is about to be called.

 -- C 变量: int PyTrace_C_EXCEPTION

     The value for the `what' parameter to *note Py_tracefunc: 3fb4.
     functions when a C function has raised an exception.

 -- C 变量: int PyTrace_C_RETURN

     The value for the `what' parameter to *note Py_tracefunc: 3fb4.
     functions when a C function has returned.

 -- C 变量: int PyTrace_OPCODE

     The value for the `what' parameter to *note Py_tracefunc: 3fb4.
     functions (but not profiling functions) when a new opcode is about
     to be executed.  This event is not emitted by default: it must be
     explicitly requested by setting ‘f_trace_opcodes’ to `1' on the
     frame.

 -- C 函数: void PyEval_SetProfile (Py_tracefunc func, PyObject *obj)

     Set the profiler function to `func'.  The `obj' parameter is passed
     to the function as its first parameter, and may be any Python
     object, or ‘NULL’.  If the profile function needs to maintain
     state, using a different value for `obj' for each thread provides a
     convenient and thread-safe place to store it.  The profile function
     is called for all monitored events except ‘PyTrace_LINE’
     ‘PyTrace_OPCODE’ and ‘PyTrace_EXCEPTION’.

 -- C 函数: void PyEval_SetTrace (Py_tracefunc func, PyObject *obj)

     Set the tracing function to `func'.  This is similar to *note
     PyEval_SetProfile(): e43, except the tracing function does receive
     line-number events and per-opcode events, but does not receive any
     event related to C function objects being called.  Any trace
     function registered using *note PyEval_SetTrace(): e44. will not
     receive ‘PyTrace_C_CALL’, ‘PyTrace_C_EXCEPTION’ or
     ‘PyTrace_C_RETURN’ as a value for the `what' parameter.


File: python.info,  Node: 高级调试器支持,  Next: Thread Local Storage Support,  Prev: 分析和跟踪,  Up: 初始化，终结和线程

7.9.9 高级调试器支持
--------------------

These functions are only intended to be used by advanced debugging
tools.

 -- C 函数: PyInterpreterState* PyInterpreterState_Head ()

     Return the interpreter state object at the head of the list of all
     such objects.

 -- C 函数: PyInterpreterState* PyInterpreterState_Main ()

     Return the main interpreter state object.

 -- C 函数: PyInterpreterState* PyInterpreterState_Next
          (PyInterpreterState *interp)

     Return the next interpreter state object after `interp' from the
     list of all such objects.

 -- C 函数: PyThreadState * PyInterpreterState_ThreadHead
          (PyInterpreterState *interp)

     Return the pointer to the first *note PyThreadState: 3f99. object
     in the list of threads associated with the interpreter `interp'.

 -- C 函数: PyThreadState* PyThreadState_Next (PyThreadState *tstate)

     Return the next thread state object after `tstate' from the list of
     all such objects belonging to the same *note PyInterpreterState:
     2c3. object.


File: python.info,  Node: Thread Local Storage Support,  Prev: 高级调试器支持,  Up: 初始化，终结和线程

7.9.10 Thread Local Storage Support
-----------------------------------

The Python interpreter provides low-level support for thread-local
storage (TLS) which wraps the underlying native TLS implementation to
support the Python-level thread local storage API (*note
threading.local: 2302.).  The CPython C level APIs are similar to those
offered by pthreads and Windows: use a thread key and functions to
associate a ‘void*’ value per thread.

The GIL does `not' need to be held when calling these functions; they
supply their own locking.

Note that ‘Python.h’ does not include the declaration of the TLS APIs,
you need to include ‘pythread.h’ to use thread-local storage.

     注解: None of these API functions handle memory management on
     behalf of the ‘void*’ values.  You need to allocate and deallocate
     them yourself.  If the ‘void*’ values happen to be *note PyObject*:
     4c2, these functions don’t do refcount operations on them either.

* Menu:

* Thread Specific Storage (TSS) API: Thread Specific Storage TSS API.
* Thread Local Storage (TLS) API: Thread Local Storage TLS API.


File: python.info,  Node: Thread Specific Storage TSS API,  Next: Thread Local Storage TLS API,  Up: Thread Local Storage Support

7.9.10.1 Thread Specific Storage (TSS) API
..........................................

TSS API is introduced to supersede the use of the existing TLS API
within the CPython interpreter.  This API uses a new type *note
Py_tss_t: 321. instead of ‘int’ to represent thread keys.

3.7 新版功能.

参见
....

"A New C-API for Thread-Local Storage in CPython" ( PEP 539(1))

 -- C 类型: Py_tss_t

     This data structure represents the state of a thread key, the
     definition of which may depend on the underlying TLS
     implementation, and it has an internal field representing the key’s
     initialization state.  There are no public members in this
     structure.

     When *note Py_LIMITED_API: 3bc4. is not defined, static allocation
     of this type by *note Py_tss_NEEDS_INIT: 3fc2. is allowed.

 -- C 宏: Py_tss_NEEDS_INIT

     This macro expands to the initializer for *note Py_tss_t: 321.
     variables.  Note that this macro won’t be defined with *note
     Py_LIMITED_API: 3bc4.

* Menu:

* Dynamic Allocation::
* 方法: 方法<4>.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0539


File: python.info,  Node: Dynamic Allocation,  Next: 方法<4>,  Up: Thread Specific Storage TSS API

7.9.10.2 Dynamic Allocation
...........................

Dynamic allocation of the *note Py_tss_t: 321, required in extension
modules built with *note Py_LIMITED_API: 3bc4, where static allocation
of this type is not possible due to its implementation being opaque at
build time.

 -- C 函数: Py_tss_t* PyThread_tss_alloc ()

     Return a value which is the same state as a value initialized with
     *note Py_tss_NEEDS_INIT: 3fc2, or ‘NULL’ in the case of dynamic
     allocation failure.

 -- C 函数: void PyThread_tss_free (Py_tss_t *key)

     Free the given `key' allocated by *note PyThread_tss_alloc(): 3fc4,
     after first calling *note PyThread_tss_delete(): 3fc6. to ensure
     any associated thread locals have been unassigned.  This is a no-op
     if the `key' argument is ‘NULL’.

          注解: A freed key becomes a dangling pointer, you should reset
          the key to ‘NULL’.


File: python.info,  Node: 方法<4>,  Prev: Dynamic Allocation,  Up: Thread Specific Storage TSS API

7.9.10.3 方法
.............

The parameter `key' of these functions must not be ‘NULL’.  Moreover,
the behaviors of *note PyThread_tss_set(): 3fc8. and *note
PyThread_tss_get(): 3fc9. are undefined if the given *note Py_tss_t:
321. has not been initialized by *note PyThread_tss_create(): 3fca.

 -- C 函数: int PyThread_tss_is_created (Py_tss_t *key)

     Return a non-zero value if the given *note Py_tss_t: 321. has been
     initialized by *note PyThread_tss_create(): 3fca.

 -- C 函数: int PyThread_tss_create (Py_tss_t *key)

     Return a zero value on successful initialization of a TSS key.  The
     behavior is undefined if the value pointed to by the `key' argument
     is not initialized by *note Py_tss_NEEDS_INIT: 3fc2.  This function
     can be called repeatedly on the same key – calling it on an already
     initialized key is a no-op and immediately returns success.

 -- C 函数: void PyThread_tss_delete (Py_tss_t *key)

     Destroy a TSS key to forget the values associated with the key
     across all threads, and change the key’s initialization state to
     uninitialized.  A destroyed key is able to be initialized again by
     *note PyThread_tss_create(): 3fca.  This function can be called
     repeatedly on the same key – calling it on an already destroyed key
     is a no-op.

 -- C 函数: int PyThread_tss_set (Py_tss_t *key, void *value)

     Return a zero value to indicate successfully associating a ‘void*’
     value with a TSS key in the current thread.  Each thread has a
     distinct mapping of the key to a ‘void*’ value.

 -- C 函数: void* PyThread_tss_get (Py_tss_t *key)

     Return the ‘void*’ value associated with a TSS key in the current
     thread.  This returns ‘NULL’ if no value is associated with the key
     in the current thread.


File: python.info,  Node: Thread Local Storage TLS API,  Prev: Thread Specific Storage TSS API,  Up: Thread Local Storage Support

7.9.10.4 Thread Local Storage (TLS) API
.......................................

3.7 版后已移除: This API is superseded by *note Thread Specific Storage
(TSS) API: 320.

     注解: This version of the API does not support platforms where the
     native TLS key is defined in a way that cannot be safely cast to
     ‘int’.  On such platforms, *note PyThread_create_key(): 3fcd. will
     return immediately with a failure status, and the other TLS
     functions will all be no-ops on such platforms.

由于上面提到的兼容性问题，不应在新代码中使用此版本的API。

 -- C 函数: int PyThread_create_key ()

 -- C 函数: void PyThread_delete_key (int key)

 -- C 函数: int PyThread_set_key_value (int key, void *value)

 -- C 函数: void* PyThread_get_key_value (int key)

 -- C 函数: void PyThread_delete_key_value (int key)

 -- C 函数: void PyThread_ReInitTLS ()


File: python.info,  Node: Python初始化配置,  Next: 内存管理,  Prev: 初始化，终结和线程,  Up: Python/C API 参考手册

7.10 Python初始化配置
=====================

3.8 新版功能.

结构

   * *note PyConfig: 160.

   * *note PyPreConfig: 161.

   * *note PyStatus: 162.

   * *note PyWideStringList: 163.

函数

   * *note PyConfig_Clear(): 164.

   * *note PyConfig_InitIsolatedConfig(): 165.

   * *note PyConfig_InitPythonConfig(): 166.

   * *note PyConfig_Read(): 167.

   * *note PyConfig_SetArgv(): 168.

   * *note PyConfig_SetBytesArgv(): 169.

   * *note PyConfig_SetBytesString(): 16a.

   * *note PyConfig_SetString(): 16b.

   * *note PyConfig_SetWideStringList(): 3fd4.

   * *note PyPreConfig_InitIsolatedConfig(): 16c.

   * *note PyPreConfig_InitPythonConfig(): 16d.

   * *note PyStatus_Error(): 16e.

   * *note PyStatus_Exception(): 16f.

   * *note PyStatus_Exit(): 170.

   * *note PyStatus_IsError(): 171.

   * *note PyStatus_IsExit(): 172.

   * *note PyStatus_NoMemory(): 173.

   * *note PyStatus_Ok(): 174.

   * *note PyWideStringList_Append(): 175.

   * *note PyWideStringList_Insert(): 176.

   * *note Py_ExitStatusException(): 178.

   * *note Py_InitializeFromConfig(): 179.

   * *note Py_PreInitialize(): 17a.

   * *note Py_PreInitializeFromArgs(): 17b.

   * *note Py_PreInitializeFromBytesArgs(): 17c.

   * *note Py_RunMain(): 17d.

The preconfiguration (‘PyPreConfig’ type) is stored in
‘_PyRuntime.preconfig’ and the configuration (‘PyConfig’ type) is stored
in ‘PyInterpreterState.config’.

See also *note Initialization, Finalization, and Threads: 3f79.

参见
....

PEP 587(1) "Python 初始化配置".

* Menu:

* PyWideStringList::
* PyStatus::
* PyPreConfig::
* Preinitialization with PyPreConfig::
* PyConfig::
* Initialization with PyConfig::
* Isolated Configuration::
* Python Configuration::
* 路径配置::
* Py_RunMain(): Py_RunMain.
* Multi-Phase Initialization Private Provisional API::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0587


File: python.info,  Node: PyWideStringList,  Next: PyStatus,  Up: Python初始化配置

7.10.1 PyWideStringList
-----------------------

 -- C 类型: PyWideStringList

     List of ‘wchar_t*’ strings.

     If `length' is non-zero, `items' must be non-‘NULL’ and all strings
     must be non-‘NULL’.

     方法

      -- C 函数: PyStatus PyWideStringList_Append
               (PyWideStringList *list, const wchar_t *item)

          Append `item' to `list'.

          Python must be preinitialized to call this function.

      -- C 函数: PyStatus PyWideStringList_Insert
               (PyWideStringList *list, Py_ssize_t index, const
               wchar_t *item)

          Insert `item' into `list' at `index'.

          If `index' is greater than or equal to `list' length, append
          `item' to `list'.

          `index' must be greater than or equal to 0.

          Python must be preinitialized to call this function.

     Structure fields:

      -- C 成员: Py_ssize_t length

          List 长度。

      -- C 成员: wchar_t** items

          列表项目。


File: python.info,  Node: PyStatus,  Next: PyPreConfig,  Prev: PyWideStringList,  Up: Python初始化配置

7.10.2 PyStatus
---------------

 -- C 类型: PyStatus

     Structure to store an initialization function status: success,
     error or exit.

     For an error, it can store the C function name which created the
     error.

     Structure fields:

      -- C 成员: int exitcode

          Exit code.  Argument passed to ‘exit()’.

      -- C 成员: const char *err_msg

          错误信息

      -- C 成员: const char *func

          Name of the function which created an error, can be ‘NULL’.

     Functions to create a status:

      -- C 函数: PyStatus PyStatus_Ok (void)

          完成。

      -- C 函数: PyStatus PyStatus_Error (const char *err_msg)

          Initialization error with a message.

      -- C 函数: PyStatus PyStatus_NoMemory (void)

          Memory allocation failure (out of memory).

      -- C 函数: PyStatus PyStatus_Exit (int exitcode)

          以指定的退出代码退出 Python。

     Functions to handle a status:

      -- C 函数: int PyStatus_Exception (PyStatus status)

          Is the status an error or an exit?  If true, the exception
          must be handled; by calling *note Py_ExitStatusException():
          178. for example.

      -- C 函数: int PyStatus_IsError (PyStatus status)

          结果错误吗？

      -- C 函数: int PyStatus_IsExit (PyStatus status)

          结果是否退出？

      -- C 函数: void Py_ExitStatusException (PyStatus status)

          Call ‘exit(exitcode)’ if `status' is an exit.  Print the error
          message and exit with a non-zero exit code if `status' is an
          error.  Must only be called if ‘PyStatus_Exception(status)’ is
          non-zero.

     注解: Internally, Python uses macros which set ‘PyStatus.func’,
     whereas functions to create a status set ‘func’ to ‘NULL’.

示例:

     PyStatus alloc(void **ptr, size_t size)
     {
         *ptr = PyMem_RawMalloc(size);
         if (*ptr == NULL) {
             return PyStatus_NoMemory();
         }
         return PyStatus_Ok();
     }

     int main(int argc, char **argv)
     {
         void *ptr;
         PyStatus status = alloc(&ptr, 16);
         if (PyStatus_Exception(status)) {
             Py_ExitStatusException(status);
         }
         PyMem_Free(ptr);
         return 0;
     }


File: python.info,  Node: PyPreConfig,  Next: Preinitialization with PyPreConfig,  Prev: PyStatus,  Up: Python初始化配置

7.10.3 PyPreConfig
------------------

 -- C 类型: PyPreConfig

     Structure used to preinitialize Python:

        * Set the Python memory allocator

        * Configure the LC_CTYPE locale

        * 设置为 UTF-8 模式

     Function to initialize a preconfiguration:

      -- C 函数: void PyPreConfig_InitPythonConfig
               (PyPreConfig *preconfig)

          Initialize the preconfiguration with *note Python
          Configuration: 3fdd.

      -- C 函数: void PyPreConfig_InitIsolatedConfig
               (PyPreConfig *preconfig)

          Initialize the preconfiguration with *note Isolated
          Configuration: 3fde.

     Structure fields:

      -- C 成员: int allocator

          Name of the memory allocator:

             * ‘PYMEM_ALLOCATOR_NOT_SET’ (‘0’): don’t change memory
               allocators (use defaults)

             * ‘PYMEM_ALLOCATOR_DEFAULT’ (‘1’): default memory
               allocators

             * ‘PYMEM_ALLOCATOR_DEBUG’ (‘2’): default memory allocators
               with debug hooks

             * ‘PYMEM_ALLOCATOR_MALLOC’ (‘3’): force usage of ‘malloc()’

             * ‘PYMEM_ALLOCATOR_MALLOC_DEBUG’ (‘4’): force usage of
               ‘malloc()’ with debug hooks

             * ‘PYMEM_ALLOCATOR_PYMALLOC’ (‘5’): *note Python pymalloc
               memory allocator: 5ca.

             * ‘PYMEM_ALLOCATOR_PYMALLOC_DEBUG’ (‘6’): *note Python
               pymalloc memory allocator: 5ca. with debug hooks

          ‘PYMEM_ALLOCATOR_PYMALLOC’ and
          ‘PYMEM_ALLOCATOR_PYMALLOC_DEBUG’ are not supported if Python
          is configured using ‘--without-pymalloc’

          See *note Memory Management: 3fe0.

      -- C 成员: int configure_locale

          Set the LC_CTYPE locale to the user preferred locale?  If
          equals to 0, set ‘coerce_c_locale’ and ‘coerce_c_locale_warn’
          to 0.

      -- C 成员: int coerce_c_locale

          If equals to 2, coerce the C locale; if equals to 1, read the
          LC_CTYPE locale to decide if it should be coerced.

      -- C 成员: int coerce_c_locale_warn

          If non-zero, emit a warning if the C locale is coerced.

      -- C 成员: int dev_mode

          参见 *note PyConfig.dev_mode: 3fe5.

      -- C 成员: int isolated

          参见 *note PyConfig.isolated: 3fe7.

      -- C 成员: int legacy_windows_fs_encoding (Windows only)

          If non-zero, disable UTF-8 Mode, set the Python filesystem
          encoding to ‘mbcs’, set the filesystem error handler to
          ‘replace’.

          Only available on Windows.  ‘#ifdef MS_WINDOWS’ macro can be
          used for Windows specific code.

      -- C 成员: int parse_argv

          If non-zero, *note Py_PreInitializeFromArgs(): 17b. and *note
          Py_PreInitializeFromBytesArgs(): 17c. parse their ‘argv’
          argument the same way the regular Python parses command line
          arguments: see *note Command Line Arguments: 933.

      -- C 成员: int use_environment

          参见 *note PyConfig.use_environment: 3feb.

      -- C 成员: int utf8_mode

          If non-zero, enable the UTF-8 mode.


File: python.info,  Node: Preinitialization with PyPreConfig,  Next: PyConfig,  Prev: PyPreConfig,  Up: Python初始化配置

7.10.4 Preinitialization with PyPreConfig
-----------------------------------------

Functions to preinitialize Python:

 -- C 函数: PyStatus Py_PreInitialize (const PyPreConfig *preconfig)

     Preinitialize Python from `preconfig' preconfiguration.

 -- C 函数: PyStatus Py_PreInitializeFromBytesArgs (const
          PyPreConfig *preconfig, int argc, char * const *argv)

     Preinitialize Python from `preconfig' preconfiguration and command
     line arguments (bytes strings).

 -- C 函数: PyStatus Py_PreInitializeFromArgs (const
          PyPreConfig *preconfig, int argc, wchar_t * const * argv)

     Preinitialize Python from `preconfig' preconfiguration and command
     line arguments (wide strings).

The caller is responsible to handle exceptions (error or exit) using
*note PyStatus_Exception(): 16f. and *note Py_ExitStatusException():
178.

For *note Python Configuration: 3fdd. (*note
PyPreConfig_InitPythonConfig(): 16d.), if Python is initialized with
command line arguments, the command line arguments must also be passed
to preinitialize Python, since they have an effect on the
pre-configuration like encodings.  For example, the *note -X utf8: 156.
command line option enables the UTF-8 Mode.

‘PyMem_SetAllocator()’ can be called after *note Py_PreInitialize():
17a. and before *note Py_InitializeFromConfig(): 179. to install a
custom memory allocator.  It can be called before *note
Py_PreInitialize(): 17a. if *note PyPreConfig.allocator: 3fdf. is set to
‘PYMEM_ALLOCATOR_NOT_SET’.

Python memory allocation functions like *note PyMem_RawMalloc(): 975.
must not be used before Python preinitialization, whereas calling
directly ‘malloc()’ and ‘free()’ is always safe.  *note
Py_DecodeLocale(): 444. must not be called before the preinitialization.

Example using the preinitialization to enable the UTF-8 Mode:

     PyStatus status;
     PyPreConfig preconfig;
     PyPreConfig_InitPythonConfig(&preconfig);

     preconfig.utf8_mode = 1;

     status = Py_PreInitialize(&preconfig);
     if (PyStatus_Exception(status)) {
         Py_ExitStatusException(status);
     }

     /* at this point, Python will speak UTF-8 */

     Py_Initialize();
     /* ... use Python API here ... */
     Py_Finalize();


File: python.info,  Node: PyConfig,  Next: Initialization with PyConfig,  Prev: Preinitialization with PyPreConfig,  Up: Python初始化配置

7.10.5 PyConfig
---------------

 -- C 类型: PyConfig

     Structure containing most parameters to configure Python.

     Structure methods:

      -- C 函数: void PyConfig_InitPythonConfig (PyConfig *config)

          Initialize configuration with *note Python Configuration:
          3fdd.

      -- C 函数: void PyConfig_InitIsolatedConfig (PyConfig *config)

          Initialize configuration with *note Isolated Configuration:
          3fde.

      -- C 函数: PyStatus PyConfig_SetString (PyConfig *config, wchar_t
               * const *config_str, const wchar_t *str)

          Copy the wide character string `str' into ‘*config_str’.

          Preinitialize Python if needed.

      -- C 函数: PyStatus PyConfig_SetBytesString (PyConfig *config,
               wchar_t * const *config_str, const char *str)

          Decode `str' using ‘Py_DecodeLocale()’ and set the result into
          ‘*config_str’.

          Preinitialize Python if needed.

      -- C 函数: PyStatus PyConfig_SetArgv (PyConfig *config, int argc,
               wchar_t * const *argv)

          Set command line arguments from wide character strings.

          Preinitialize Python if needed.

      -- C 函数: PyStatus PyConfig_SetBytesArgv (PyConfig *config,
               int argc, char * const *argv)

          Set command line arguments: decode bytes using *note
          Py_DecodeLocale(): 444.

          Preinitialize Python if needed.

      -- C 函数: PyStatus PyConfig_SetWideStringList (PyConfig *config,
               PyWideStringList *list, Py_ssize_t length,
               wchar_t **items)

          Set the list of wide strings `list' to `length' and `items'.

          Preinitialize Python if needed.

      -- C 函数: PyStatus PyConfig_Read (PyConfig *config)

          Read all Python configuration.

          Fields which are already initialized are left unchanged.

          Preinitialize Python if needed.

      -- C 函数: void PyConfig_Clear (PyConfig *config)

          Release configuration memory.

     Most ‘PyConfig’ methods preinitialize Python if needed.  In that
     case, the Python preinitialization configuration in based on the
     *note PyConfig: 160.  If configuration fields which are in common
     with *note PyPreConfig: 161. are tuned, they must be set before
     calling a *note PyConfig: 160. method:

        * *note dev_mode: 3fe5.

        * *note isolated: 3fe7.

        * *note parse_argv: 3fef.

        * *note use_environment: 3feb.

     Moreover, if *note PyConfig_SetArgv(): 168. or *note
     PyConfig_SetBytesArgv(): 169. is used, this method must be called
     first, before other methods, since the preinitialization
     configuration depends on command line arguments (if ‘parse_argv’ is
     non-zero).

     The caller of these methods is responsible to handle exceptions
     (error or exit) using ‘PyStatus_Exception()’ and
     ‘Py_ExitStatusException()’.

     Structure fields:

      -- C 成员: PyWideStringList argv

          Command line arguments, *note sys.argv: c03.  See *note
          parse_argv: 3fef. to parse *note argv: 3ff0. the same way the
          regular Python parses Python command line arguments.  If *note
          argv: 3ff0. is empty, an empty string is added to ensure that
          *note sys.argv: c03. always exists and is never empty.

      -- C 成员: wchar_t* base_exec_prefix

          *note sys.base_exec_prefix: 3605.

      -- C 成员: wchar_t* base_executable

          ‘sys._base_executable’: ‘__PYVENV_LAUNCHER__’ environment
          variable value, or copy of *note PyConfig.executable: 3ff3.

      -- C 成员: wchar_t* base_prefix

          *note sys.base_prefix: 304e.

      -- C 成员: int buffered_stdio

          If equals to 0, enable unbuffered mode, making the stdout and
          stderr streams unbuffered.

          stdin is always opened in buffered mode.

      -- C 成员: int bytes_warning

          If equals to 1, issue a warning when comparing *note bytes:
          33a. or *note bytearray: 33b. with *note str: 339, or
          comparing *note bytes: 33a. with *note int: 185.  If equal or
          greater to 2, raise a *note BytesWarning: 4bd. exception.

      -- C 成员: wchar_t* check_hash_pycs_mode

          Control the validation behavior of hash-based ‘.pyc’ files
          (see PEP 552(1)): *note –check-hash-based-pycs: 1351. command
          line option value.

          Valid values: ‘always’, ‘never’ and ‘default’.

          默认值为: ‘default’.

      -- C 成员: int configure_c_stdio

          If non-zero, configure C standard streams (‘stdio’, ‘stdout’,
          ‘stdout’).  For example, set their mode to ‘O_BINARY’ on
          Windows.

      -- C 成员: int dev_mode

          Development mode: see *note -X dev: 156.

      -- C 成员: int dump_refs

          If non-zero, dump all objects which are still alive at exit.

          Require a debug build of Python (‘Py_REF_DEBUG’ macro must be
          defined).

      -- C 成员: wchar_t* exec_prefix

          *note sys.exec_prefix: 3604.

      -- C 成员: wchar_t* executable

          *note sys.executable: 275.

      -- C 成员: int faulthandler

          If non-zero, call *note faulthandler.enable(): 551. at
          startup.

      -- C 成员: wchar_t* filesystem_encoding

          Filesystem encoding, *note sys.getfilesystemencoding(): 4fe.

      -- C 成员: wchar_t* filesystem_errors

          Filesystem encoding errors, *note
          sys.getfilesystemencodeerrors(): 59d.

      -- C 成员: unsigned long hash_seed

      -- C 成员: int use_hash_seed

          Randomized hash function seed.

          If *note use_hash_seed: 3fff. is zero, a seed is chosen
          randomly at Pythonstartup, and *note hash_seed: 3ffe. is
          ignored.

      -- C 成员: wchar_t* home

          Python home directory.

          Initialized from *note PYTHONHOME: 4de. environment variable
          value by default.

      -- C 成员: int import_time

          If non-zero, profile import time.

      -- C 成员: int inspect

          Enter interactive mode after executing a script or a command.

      -- C 成员: int install_signal_handlers

          Install signal handlers?

      -- C 成员: int interactive

          交互模式

      -- C 成员: int isolated

          If greater than 0, enable isolated mode:

             * *note sys.path: 490. contains neither the script’s
               directory (computed from ‘argv[0]’ or the current
               directory) nor the user’s site-packages directory.

             * Python REPL doesn’t import *note readline: df. nor enable
               default readline configuration on interactive prompts.

             * Set *note use_environment: 3feb. and *note
               user_site_directory: 4004. to 0.

      -- C 成员: int legacy_windows_stdio

          If non-zero, use *note io.FileIO: cac. instead of
          ‘io.WindowsConsoleIO’ for *note sys.stdin: 316, *note
          sys.stdout: 317. and *note sys.stderr: 318.

          Only available on Windows.  ‘#ifdef MS_WINDOWS’ macro can be
          used for Windows specific code.

      -- C 成员: int malloc_stats

          If non-zero, dump statistics on *note Python pymalloc memory
          allocator: 5ca. at exit.

          The option is ignored if Python is built using
          ‘--without-pymalloc’.

      -- C 成员: wchar_t* pythonpath_env

          Module search paths as a string separated by ‘DELIM’
          (‘os.path.pathsep’).

          Initialized from *note PYTHONPATH: 95b. environment variable
          value by default.

      -- C 成员: PyWideStringList module_search_paths

      -- C 成员: int module_search_paths_set

          *note sys.path: 490.  If *note module_search_paths_set: 4009.
          is equal to 0, the *note module_search_paths: 4008. is
          overridden by the function calculating the *note Path
          Configuration: 400a.

      -- C 成员: int optimization_level

          Compilation optimization level:

             * 0: Peephole optimizer (and ‘__debug__’ is set to ‘True’)

             * 1: Remove assertions, set ‘__debug__’ to ‘False’

             * 2: Strip docstrings

      -- C 成员: int parse_argv

          If non-zero, parse *note argv: 3ff0. the same way the regular
          Python command line arguments, and strip Python arguments from
          *note argv: 3ff0.: see *note Command Line Arguments: 933.

      -- C 成员: int parser_debug

          If non-zero, turn on parser debugging output (for expert only,
          depending on compilation options).

      -- C 成员: int pathconfig_warnings

          If equal to 0, suppress warnings when calculating the *note
          Path Configuration: 400a. (Unix only, Windows does not log any
          warning).  Otherwise, warnings are written into ‘stderr’.

      -- C 成员: wchar_t* prefix

          *note sys.prefix: 3603.

      -- C 成员: wchar_t* program_name

          Program name.  Used to initialize *note executable: 3ff3, and
          in early error messages.

      -- C 成员: wchar_t* pycache_prefix

          *note sys.pycache_prefix: 157.: ‘.pyc’ cache prefix.

          If ‘NULL’, *note sys.pycache_prefix: 157. is set to ‘None’.

      -- C 成员: int quiet

          Quiet mode.  For example, don’t display the copyright and
          version messages in interactive mode.

      -- C 成员: wchar_t* run_command

          ‘python3 -c COMMAND’ argument.  Used by *note Py_RunMain():
          17d.

      -- C 成员: wchar_t* run_filename

          ‘python3 FILENAME’ argument.  Used by *note Py_RunMain(): 17d.

      -- C 成员: wchar_t* run_module

          ‘python3 -m MODULE’ argument.  Used by *note Py_RunMain():
          17d.

      -- C 成员: int show_alloc_count

          Show allocation counts at exit?

          Set to 1 by *note -X showalloccount: 156. command line option.

          Need a special Python build with ‘COUNT_ALLOCS’ macro defined.

      -- C 成员: int show_ref_count

          Show total reference count at exit?

          Set to 1 by *note -X showrefcount: 156. command line option.

          Need a debug build of Python (‘Py_REF_DEBUG’ macro must be
          defined).

      -- C 成员: int site_import

          Import the *note site: ec. module at startup?

      -- C 成员: int skip_source_first_line

          Skip the first line of the source?

      -- C 成员: wchar_t* stdio_encoding

      -- C 成员: wchar_t* stdio_errors

          Encoding and encoding errors of *note sys.stdin: 316, *note
          sys.stdout: 317. and *note sys.stderr: 318.

      -- C 成员: int tracemalloc

          If non-zero, call *note tracemalloc.start(): 135f. at startup.

      -- C 成员: int use_environment

          If greater than 0, use *note environment variables: 1364.

      -- C 成员: int user_site_directory

          If non-zero, add user site directory to *note sys.path: 490.

      -- C 成员: int verbose

          If non-zero, enable verbose mode.

      -- C 成员: PyWideStringList warnoptions

          *note sys.warnoptions: 41e.: options of the *note warnings:
          127. module to build warnings filters: lowest to highest
          priority.

          The *note warnings: 127. module adds *note sys.warnoptions:
          41e. in the reverse order: the last *note
          PyConfig.warnoptions: 401d. item becomes the first item of
          ‘warnings.filters’ which is checked first (highest priority).

      -- C 成员: int write_bytecode

          If non-zero, write ‘.pyc’ files.

          *note sys.dont_write_bytecode: 3632. is initialized to the
          inverted value of *note write_bytecode: 401e.

      -- C 成员: PyWideStringList xoptions

          *note sys._xoptions: 1361.

If ‘parse_argv’ is non-zero, ‘argv’ arguments are parsed the same way
the regular Python parses command line arguments, and Python arguments
are stripped from ‘argv’: see *note Command Line Arguments: 933.

The ‘xoptions’ options are parsed to set other options: see *note -X:
156. option.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0552


File: python.info,  Node: Initialization with PyConfig,  Next: Isolated Configuration,  Prev: PyConfig,  Up: Python初始化配置

7.10.6 Initialization with PyConfig
-----------------------------------

Function to initialize Python:

 -- C 函数: PyStatus Py_InitializeFromConfig (const PyConfig *config)

     Initialize Python from `config' configuration.

The caller is responsible to handle exceptions (error or exit) using
*note PyStatus_Exception(): 16f. and *note Py_ExitStatusException():
178.

If ‘PyImport_FrozenModules’, ‘PyImport_AppendInittab()’ or
‘PyImport_ExtendInittab()’ are used, they must be set or called after
Python preinitialization and before the Python initialization.

Example setting the program name:

     void init_python(void)
     {
         PyStatus status;

         PyConfig config;
         PyConfig_InitPythonConfig(&config);

         /* Set the program name. Implicitly preinitialize Python. */
         status = PyConfig_SetString(&config, &config.program_name,
                                     L"/path/to/my_program");
         if (PyStatus_Exception(status)) {
             goto fail;
         }

         status = Py_InitializeFromConfig(&config);
         if (PyStatus_Exception(status)) {
             goto fail;
         }
         PyConfig_Clear(&config);
         return;

     fail:
         PyConfig_Clear(&config);
         Py_ExitStatusException(status);
     }

More complete example modifying the default configuration, read the
configuration, and then override some parameters:

     PyStatus init_python(const char *program_name)
     {
         PyStatus status;

         PyConfig config;
         PyConfig_InitPythonConfig(&config);

         /* Set the program name before reading the configuration
            (decode byte string from the locale encoding).

            Implicitly preinitialize Python. */
         status = PyConfig_SetBytesString(&config, &config.program_name,
                                       program_name);
         if (PyStatus_Exception(status)) {
             goto done;
         }

         /* Read all configuration at once */
         status = PyConfig_Read(&config);
         if (PyStatus_Exception(status)) {
             goto done;
         }

         /* Append our custom search path to sys.path */
         status = PyWideStringList_Append(&config.module_search_paths,
                                          L"/path/to/more/modules");
         if (PyStatus_Exception(status)) {
             goto done;
         }

         /* Override executable computed by PyConfig_Read() */
         status = PyConfig_SetString(&config, &config.executable,
                                     L"/path/to/my_executable");
         if (PyStatus_Exception(status)) {
             goto done;
         }

         status = Py_InitializeFromConfig(&config);

     done:
         PyConfig_Clear(&config);
         return status;
     }


File: python.info,  Node: Isolated Configuration,  Next: Python Configuration,  Prev: Initialization with PyConfig,  Up: Python初始化配置

7.10.7 Isolated Configuration
-----------------------------

*note PyPreConfig_InitIsolatedConfig(): 16c. and *note
PyConfig_InitIsolatedConfig(): 165. functions create a configuration to
isolate Python from the system.  For example, to embed Python into an
application.

This configuration ignores global configuration variables, environments
variables, command line arguments (*note PyConfig.argv: 3ff0. is not
parsed) and user site directory.  The C standard streams (ex: ‘stdout’)
and the LC_CTYPE locale are left unchanged.  Signal handlers are not
installed.

Configuration files are still used with this configuration.  Set the
*note Path Configuration: 400a. ("output fields") to ignore these
configuration files and avoid the function computing the default path
configuration.


File: python.info,  Node: Python Configuration,  Next: 路径配置,  Prev: Isolated Configuration,  Up: Python初始化配置

7.10.8 Python Configuration
---------------------------

*note PyPreConfig_InitPythonConfig(): 16d. and *note
PyConfig_InitPythonConfig(): 166. functions create a configuration to
build a customized Python which behaves as the regular Python.

Environments variables and command line arguments are used to configure
Python, whereas global configuration variables are ignored.

This function enables C locale coercion ( PEP 538(1)) and UTF-8 Mode (
PEP 540(2)) depending on the LC_CTYPE locale, *note PYTHONUTF8: 31a. and
*note PYTHONCOERCECLOCALE: 315. environment variables.

Example of customized Python always running in isolated mode:

     int main(int argc, char **argv)
     {
         PyStatus status;

         PyConfig config;
         PyConfig_InitPythonConfig(&config);
         config.isolated = 1;

         /* Decode command line arguments.
            Implicitly preinitialize Python (in isolated mode). */
         status = PyConfig_SetBytesArgv(&config, argc, argv);
         if (PyStatus_Exception(status)) {
             goto fail;
         }

         status = Py_InitializeFromConfig(&config);
         if (PyStatus_Exception(status)) {
             goto fail;
         }
         PyConfig_Clear(&config);

         return Py_RunMain();

     fail:
         PyConfig_Clear(&config);
         if (PyStatus_IsExit(status)) {
             return status.exitcode;
         }
         /* Display the error message and exit the process with
            non-zero exit code */
         Py_ExitStatusException(status);
     }

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0538

   (2) https://www.python.org/dev/peps/pep-0540


File: python.info,  Node: 路径配置,  Next: Py_RunMain,  Prev: Python Configuration,  Up: Python初始化配置

7.10.9 路径配置
---------------

*note PyConfig: 160. contains multiple fields for the path
configuration:

   * 路径配置输入：

        * *note PyConfig.home: 4000.

        * *note PyConfig.pathconfig_warnings: 400d.

        * *note PyConfig.program_name: 400f.

        * *note PyConfig.pythonpath_env: 4007.

        * current working directory: to get absolute paths

        * ‘PATH’ environment variable to get the program full path (from
          *note PyConfig.program_name: 400f.)

        * ‘__PYVENV_LAUNCHER__’ environment variable

        * (Windows only) Application paths in the registry under
          "SoftwarePythonPythonCoreX.YPythonPath" of HKEY_CURRENT_USER
          and HKEY_LOCAL_MACHINE (where X.Y is the Python version).

   * Path configuration output fields:

        * *note PyConfig.base_exec_prefix: 3ff1.

        * *note PyConfig.base_executable: 3ff2.

        * *note PyConfig.base_prefix: 3ff4.

        * *note PyConfig.exec_prefix: 3ffa.

        * *note PyConfig.executable: 3ff3.

        * *note PyConfig.module_search_paths_set: 4009, *note
          PyConfig.module_search_paths: 4008.

        * *note PyConfig.prefix: 400e.

If at least one "output field" is not set, Python calculates the path
configuration to fill unset fields.  If *note module_search_paths_set:
4009. is equal to 0, *note module_search_paths: 4008. is overridden and
*note module_search_paths_set: 4009. is set to 1.

It is possible to completely ignore the function calculating the default
path configuration by setting explicitly all path configuration output
fields listed above.  A string is considered as set even if it is
non-empty.  ‘module_search_paths’ is considered as set if
‘module_search_paths_set’ is set to 1.  In this case, path configuration
input fields are ignored as well.

Set *note pathconfig_warnings: 400d. to 0 to suppress warnings when
calculating the path configuration (Unix only, Windows does not log any
warning).

If *note base_prefix: 3ff4. or *note base_exec_prefix: 3ff1. fields are
not set, they inherit their value from *note prefix: 400e. and *note
exec_prefix: 3ffa. respectively.

*note Py_RunMain(): 17d. and *note Py_Main(): 4bf. modify *note
sys.path: 490.:

   * If *note run_filename: 4013. is set and is a directory which
     contains a ‘__main__.py’ script, prepend *note run_filename: 4013.
     to *note sys.path: 490.

   * If *note isolated: 3fe7. is zero:

        * If *note run_module: 4014. is set, prepend the current
          directory to *note sys.path: 490.  Do nothing if the current
          directory cannot be read.

        * If *note run_filename: 4013. is set, prepend the directory of
          the filename to *note sys.path: 490.

        * Otherwise, prepend an empty string to *note sys.path: 490.

If *note site_import: 4017. is non-zero, *note sys.path: 490. can be
modified by the *note site: ec. module.  If *note user_site_directory:
4004. is non-zero and the user’s site-package directory exists, the
*note site: ec. module appends the user’s site-package directory to
*note sys.path: 490.

The following configuration files are used by the path configuration:

   * ‘pyvenv.cfg’

   * ‘python._pth’ (仅Windows)

   * ‘pybuilddir.txt’ (仅Unix)

The ‘__PYVENV_LAUNCHER__’ environment variable is used to set *note
PyConfig.base_executable: 3ff2.


File: python.info,  Node: Py_RunMain,  Next: Multi-Phase Initialization Private Provisional API,  Prev: 路径配置,  Up: Python初始化配置

7.10.10 Py_RunMain()
--------------------

 -- C 函数: int Py_RunMain (void)

     Execute the command (*note PyConfig.run_command: 4012.), the script
     (*note PyConfig.run_filename: 4013.) or the module (*note
     PyConfig.run_module: 4014.) specified on the command line or in the
     configuration.

     By default and when if *note -i: e27. option is used, run the REPL.

     Finally, finalizes Python and returns an exit status that can be
     passed to the ‘exit()’ function.

See *note Python Configuration: 3fdd. for an example of customized
Python always running in isolated mode using *note Py_RunMain(): 17d.


File: python.info,  Node: Multi-Phase Initialization Private Provisional API,  Prev: Py_RunMain,  Up: Python初始化配置

7.10.11 Multi-Phase Initialization Private Provisional API
----------------------------------------------------------

This section is a private provisional API introducing multi-phase
initialization, the core feature of the PEP 432(1):

   * "Core" initialization phase, "bare minimum Python":

        * Builtin types;

        * Builtin exceptions;

        * Builtin and frozen modules;

        * The *note sys: fe. module is only partially initialized (ex:
          *note sys.path: 490. doesn’t exist yet).

   * "Main" initialization phase, Python is fully initialized:

        * Install and configure *note importlib: 9b.;

        * Apply the *note Path Configuration: 400a.;

        * Install signal handlers;

        * Finish *note sys: fe. module initialization (ex: create *note
          sys.stdout: 317. and *note sys.path: 490.);

        * Enable optional features like *note faulthandler: 7d. and
          *note tracemalloc: 115.;

        * Import the *note site: ec. module;

        * 等等.

私有临时API：

   * ‘PyConfig._init_main’: if set to 0, *note
     Py_InitializeFromConfig(): 179. stops at the "Core" initialization
     phase.

 -- C 函数: PyStatus _Py_InitializeMain (void)

     Move to the "Main" initialization phase, finish the Python
     initialization.

No module is imported during the "Core" phase and the ‘importlib’ module
is not configured: the *note Path Configuration: 400a. is only applied
during the "Main" phase.  It may allow to customize Python in Python to
override or tune the *note Path Configuration: 400a, maybe install a
custom *note sys.meta_path: 5ef. importer or an import hook, etc.

It may become possible to calculatin the *note Path Configuration: 400a.
in Python, after the Core phase and before the Main phase, which is one
of the PEP 432(2) motivation.

The "Core" phase is not properly defined: what should be and what should
not be available at this phase is not specified yet.  The API is marked
as private and provisional: the API can be modified or even be removed
anytime until a proper public API is designed.

Example running Python code between "Core" and "Main" initialization
phases:

     void init_python(void)
     {
         PyStatus status;

         PyConfig config;
         PyConfig_InitPythonConfig(&config);
         config._init_main = 0;

         /* ... customize 'config' configuration ... */

         status = Py_InitializeFromConfig(&config);
         PyConfig_Clear(&config);
         if (PyStatus_Exception(status)) {
             Py_ExitStatusException(status);
         }

         /* Use sys.stderr because sys.stdout is only created
            by _Py_InitializeMain() */
         int res = PyRun_SimpleString(
             "import sys; "
             "print('Run Python code before _Py_InitializeMain', "
                    "file=sys.stderr)");
         if (res < 0) {
             exit(1);
         }

         /* ... put more configuration code here ... */

         status = _Py_InitializeMain();
         if (PyStatus_Exception(status)) {
             Py_ExitStatusException(status);
         }
     }

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0432

   (2) https://www.python.org/dev/peps/pep-0432


File: python.info,  Node: 内存管理,  Next: 对象实现支持,  Prev: Python初始化配置,  Up: Python/C API 参考手册

7.11 内存管理
=============

* Menu:

* 概述: 概述<16>.
* 原始内存接口::
* 内存接口::
* 对象分配器::
* 默认内存分配器::
* 自定义内存分配器::
* pymalloc 分配器::
* tracemalloc C API::
* 例子: 例子<34>.


File: python.info,  Node: 概述<16>,  Next: 原始内存接口,  Up: 内存管理

7.11.1 概述
-----------

在 Python 中，内存管理涉及到一个包含所有 Python 对象和数据结构的私有堆（
heap）。这个私有堆的管理由内部的 `Python 内存管理器（Python memory
manager）' 保证。Python 内存管理器有不同的组件来处理各种动态存储管理方面
的问题，如共享、分割、预分配或缓存。

在最底层，一个原始内存分配器通过与操作系统的内存管理器交互，确保私有堆中
有足够的空间来存储所有与 Python 相关的数据。在原始内存分配器的基础上，几
个对象特定的分配器在同一堆上运行，并根据每种对象类型的特点实现不同的内存
管理策略。例如，整数对象在堆内的管理方式不同于字符串、元组或字典，因为整
数需要不同的存储需求和速度与空间的权衡。因此，Python 内存管理器将一些工
作分配给对象特定分配器，但确保后者在私有堆的范围内运行。

Python 堆内存的管理是由解释器来执行，用户对它没有控制权，即使他们经常操
作指向堆内内存块的对象指针，理解这一点十分重要。Python 对象和其他内部缓
冲区的堆空间分配是由 Python 内存管理器按需通过本文档中列出的 Python/C
API 函数进行的。

为了避免内存破坏，扩展的作者永远不应该试图用 C 库函数导出的函数来对
Python 对象进行操作，这些函数包括： ‘malloc()’, ‘calloc()’, ‘realloc()’
和 ‘free()’。这将导致 C 分配器和 Python 内存管理器之间的混用，引发严重后
果，这是由于它们实现了不同的算法，并在不同的堆上操作。但是，我们可以安全
地使用 C 库分配器为单独的目的分配和释放内存块，如下例所示：

     PyObject *res;
     char *buf = (char *) malloc(BUFSIZ); /* for I/O */

     if (buf == NULL)
         return PyErr_NoMemory();
     ...Do some I/O operation involving buf...
     res = PyBytes_FromString(buf);
     free(buf); /* malloc'ed */
     return res;

在这个例子中，I/O 缓冲区的内存请求是由 C 库分配器处理的。Python 内存管理
器只参与了分配作为结果返回的字节对象。

然而，在大多数情况下，建议专门从 Python 堆中分配内存，因为后者由 Python
内存管理器控制。例如，当解释器扩展了用 C 写的新对象类型时，就必须这样做
。使用 Python 堆的另一个原因是希望*通知* Python 内存管理器关于扩展模块的
内存需求。即使所请求的内存全部只用于内部的、高度特定的目的，将所有的内存
请求交给 Python 内存管理器能让解释器对其内存占用的整体情况有更准确的了解
。因此，在某些情况下，Python 内存管理器可能会触发或不触发适当的操作，如
垃圾回收、内存压缩或其他预防性操作。请注意，通过使用前面例子中所示的 C 库
分配器，为 I/O 缓冲区分配的内存会完全不受 Python 内存管理器管理。

参见
....

环境变量 *note PYTHONMALLOC: 50b. 可被用来配置 Python 所使用的内存分配器
。

环境变量 *note PYTHONMALLOCSTATS: 1172. 可以用来在每次创建和关闭新的
pymalloc 对象区域时打印 *note pymalloc 内存分配器: 5ca. 的统计数据。


File: python.info,  Node: 原始内存接口,  Next: 内存接口,  Prev: 概述<16>,  Up: 内存管理

7.11.2 原始内存接口
-------------------

以下函数集封装了系统分配器。这些函数是线程安全的，不需要持有 *note GIL:
50e.。

*note default raw memory allocator: 136d. 使用这些函数：‘malloc()’、
‘calloc()’、 ‘realloc()’ 和 ‘free()’；申请零字节时则调用 ‘malloc(1)``（
或 ``calloc(1, 1)’）

3.4 新版功能.

 -- C 函数: void* PyMem_RawMalloc (size_t n)

     分配 `n' 个字节并返回一个指向分配的内存的 ‘void*’ 类型指针，如果请
     求失败则返回 ‘NULL’。

     请求零字节可能返回一个独特的非 ‘NULL’ 指针，就像调用了
     ‘‘PyMem_RawMalloc(1)‘‘ 一样。但是内存不会以任何方式被初始化。

 -- C 函数: void* PyMem_RawCalloc (size_t nelem, size_t elsize)

     分配 `nelem' 个元素，每个元素的大小为 `elsize' 字节，并返回指向分配
     的内存的 ‘void*’ 类型指针，如果请求失败则返回 ‘NULL’。 内存会被初始
     化为零。

     请求零字节可能返回一个独特的非 ‘NULL’ 指针，就像调用了
     ‘‘PyMem_RawCalloc(1, 1)‘‘ 一样。

     3.5 新版功能.

 -- C 函数: void* PyMem_RawRealloc (void *p, size_t n)

     将 `p' 指向的内存块大小调整为 `n' 字节。以新旧内存块大小中的最小值
     为准，其中内容保持不变，

     如果*p*是‘‘NULL‘‘，则相当于调用 ‘PyMem_RawMalloc(n)’ ；如果 `n' 等
     于 0，则内存块大小会被调整，但不会被释放，返回非 ‘NULL’ 指针。

     除非 `p' 是 ‘NULL’ ，否则它必须是之前调用 *note PyMem_RawMalloc():
     975. 、 *note PyMem_RawRealloc(): 976. 或 *note PyMem_RawCalloc():
     7ae. 所返回的。

     如果请求失败，*note PyMem_RawRealloc(): 976. 返回 ‘NULL’ ， `p' 仍
     然是指向先前内存区域的有效指针。

 -- C 函数: void PyMem_RawFree (void *p)

     释放 `p' 指向的内存块。除非 `p' 是 ‘NULL’ ，否则它必须是之前调用
     *note PyMem_RawMalloc(): 975. 、 *note PyMem_RawRealloc(): 976. 或
     *note PyMem_RawCalloc(): 7ae. 所返回的指针。否则，或在
     ‘PyMem_RawFree(p)’ 之前已经调用过的情况下，未定义的行为会发生。

     如果 `p' 是 ‘NULL’, 那么什么操作也不会进行。


File: python.info,  Node: 内存接口,  Next: 对象分配器,  Prev: 原始内存接口,  Up: 内存管理

7.11.3 内存接口
---------------

以下函数集，仿照 ANSI C 标准，并指定了请求零字节时的行为，可用于从
Python堆分配和释放内存。

*note 默认内存分配器: 136d. 使用了 *note pymalloc 内存分配器: 5ca.

     警告: 在使用这些函数时，必须持有 *note 全局解释器锁（GIL）: 50e. 。

在 3.6 版更改: 现在默认的分配器是 pymalloc 而非系统的 ‘malloc()’ 。

 -- C 函数: void* PyMem_Malloc (size_t n)

     分配 `n' 个字节并返回一个指向分配的内存的 ‘void*’ 类型指针，如果请
     求失败则返回 ‘NULL’。

     请求零字节可能返回一个独特的非 ‘NULL’ 指针，就像调用了
     ‘‘PyMem_Malloc(1)‘‘ 一样。但是内存不会以任何方式被初始化。

 -- C 函数: void* PyMem_Calloc (size_t nelem, size_t elsize)

     分配 `nelem' 个元素，每个元素的大小为 `elsize' 字节，并返回指向分配
     的内存的 ‘void*’ 类型指针，如果请求失败则返回 ‘NULL’。 内存会被初始
     化为零。

     请求零字节可能返回一个独特的非 ‘NULL’ 指针，就像调用了
     ‘‘PyMem_Calloc(1, 1)‘‘ 一样。

     3.5 新版功能.

 -- C 函数: void* PyMem_Realloc (void *p, size_t n)

     将 `p' 指向的内存块大小调整为 `n' 字节。以新旧内存块大小中的最小值
     为准，其中内容保持不变，

     如果*p*是‘‘NULL‘‘，则相当于调用 ‘PyMem_Malloc(n)’ ；如果 `n' 等于
     0，则内存块大小会被调整，但不会被释放，返回非 ‘NULL’ 指针。

     除非 `p' 是 ‘NULL’ ，否则它必须是之前调用 *note PyMem_Malloc():
     50d. 、 *note PyMem_Realloc(): 977. 或 *note PyMem_Calloc(): 7af. 所
     返回的。

     如果请求失败，*note PyMem_Realloc(): 977. 返回 ‘NULL’ ， `p' 仍然是
     指向先前内存区域的有效指针。

 -- C 函数: void PyMem_Free (void *p)

     释放 `p' 指向的内存块。除非 `p' 是 ‘NULL’ ，否则它必须是之前调用
     *note PyMem_Malloc(): 50d. 、 *note PyMem_Realloc(): 977. 或 *note
     PyMem_Calloc(): 7af. 所返回的指针。否则，或在 ‘PyMem_Free(p)’ 之前
     已经调用过的情况下，未定义的行为会发生。

     如果 `p' 是 ‘NULL’, 那么什么操作也不会进行。

以下面向类型的宏为方便而提供。 注意 `TYPE' 可以指任何 C 类型。

 -- C 函数: TYPE* PyMem_New (TYPE, size_t n)

     与 *note PyMem_Malloc(): 50d. 相同，但会分配 ‘(n * sizeof(TYPE))’ 字
     节的内存。 返回一个转换为 ‘TYPE*’ 的指针。 内存将不会以任何方式被初
     始化。

 -- C 函数: TYPE* PyMem_Resize (void *p, TYPE, size_t n)

     与 *note PyMem_Realloc(): 977. 相同，但内存块的大小被调整为 ‘(n *
     sizeof(TYPE))’ 字节。 返回一个转换为 ‘TYPE*’ 类型的指针。 返回时，
     `p' 将为指向新内存区域的指针，如果失败则返回 ‘NULL’。

     这是一个 C 预处理宏， `p' 总是被重新赋值。请保存 `p' 的原始值，以避
     免在处理错误时丢失内存。

 -- C 函数: void PyMem_Del (void *p)

     与 *note PyMem_Free(): db1. 相同

此外，我们还提供了以下宏集用于直接调用 Python 内存分配器，而不涉及上面列
出的 C API 函数。但是请注意，使用它们并不能保证跨 Python 版本的二进制兼
容性，因此在扩展模块被弃用。

   * ‘PyMem_MALLOC(size)’

   * ‘PyMem_NEW(type, size)’

   * ‘PyMem_REALLOC(ptr, size)’

   * ‘PyMem_RESIZE(ptr, type, size)’

   * ‘PyMem_FREE(ptr)’

   * ‘PyMem_DEL(ptr)’


File: python.info,  Node: 对象分配器,  Next: 默认内存分配器,  Prev: 内存接口,  Up: 内存管理

7.11.4 对象分配器
-----------------

以下函数集，仿照 ANSI C 标准，并指定了请求零字节时的行为，可用于从
Python堆分配和释放内存。

*note 默认对象分配器: 136d. 使用 *note pymalloc 内存分配器: 5ca.

     警告: 在使用这些函数时，必须持有 *note 全局解释器锁（GIL）: 50e. 。

 -- C 函数: void* PyObject_Malloc (size_t n)

     分配 `n' 个字节并返回一个指向分配的内存的 ‘void*’ 类型指针，如果请
     求失败则返回 ‘NULL’。

     请求零字节可能返回一个独特的非 ‘NULL’ 指针，就像调用了
     ‘‘PyObject_Malloc(1)‘‘ 一样。但是内存不会以任何方式被初始化。

 -- C 函数: void* PyObject_Calloc (size_t nelem, size_t elsize)

     分配 `nelem' 个元素，每个元素的大小为 `elsize' 字节，并返回指向分配
     的内存的 ‘void*’ 类型指针，如果请求失败则返回 ‘NULL’。 内存会被初始
     化为零。

     请求零字节可能返回一个独特的非 ‘NULL’ 指针，就像调用了
     ‘‘PyObject_Calloc(1, 1)‘‘ 一样。

     3.5 新版功能.

 -- C 函数: void* PyObject_Realloc (void *p, size_t n)

     将 `p' 指向的内存块大小调整为 `n' 字节。以新旧内存块大小中的最小值
     为准，其中内容保持不变，

     如果*p*是‘‘NULL‘‘，则相当于调用 ‘PyObject_Malloc(n)’ ；如果 `n' 等
     于 0，则内存块大小会被调整，但不会被释放，返回非 ‘NULL’ 指针。

     除非 `p' 是 ‘NULL’ ，否则它必须是之前调用 *note PyObject_Malloc():
     510. 、 *note PyObject_Realloc(): db2. 或 *note PyObject_Calloc():
     7b0. 所返回的。

     如果请求失败，*note PyObject_Realloc(): db2. 返回 ‘NULL’ ， `p' 仍
     然是指向先前内存区域的有效指针。

 -- C 函数: void PyObject_Free (void *p)

     释放 `p' 指向的内存块。除非 `p' 是 ‘NULL’ ，否则它必须是之前调用
     *note PyObject_Malloc(): 510. 、 *note PyObject_Realloc(): db2. 或
     *note PyObject_Calloc(): 7b0. 所返回的指针。否则，或在
     ‘PyObject_Free(p)’ 之前已经调用过的情况下，未定义的行为会发生。

     如果 `p' 是 ‘NULL’, 那么什么操作也不会进行。


File: python.info,  Node: 默认内存分配器,  Next: 自定义内存分配器,  Prev: 对象分配器,  Up: 内存管理

7.11.5 默认内存分配器
---------------------

默认内存分配器：

配置                                名称                     PyMem_RawMalloc        PyMem_Malloc              PyObject_Malloc
                                                                                                              
---------------------------------------------------------------------------------------------------------------------------------------
                                                                                                              
发布版本                            ‘"pymalloc"’             ‘malloc’               ‘pymalloc’                ‘pymalloc’
                                                                                                              
                                                                                                              
调试构建                            ‘"pymalloc_debug"’       ‘malloc’ + debug       ‘pymalloc’ + debug        ‘pymalloc’ + debug
                                                                                                              
                                                                                                              
没有 pymalloc 的发布版本            ‘"malloc"’               ‘malloc’               ‘malloc’                  ‘malloc’
                                                                                                              
                                                                                                              
没有 pymalloc 的调试构建            ‘"malloc_debug"’         ‘malloc’ + debug       ‘malloc’ + debug          ‘malloc’ + debug
                                                                                                              

说明：

   * 名称: 环境变量 *note PYTHONMALLOC: 50b. 的值

   * ‘malloc’: 来自 C 标准库的系统分配, C 函数 ‘malloc()’, ‘calloc()’,
     ‘realloc()’ and ‘free()’

   * ‘pymalloc’: *note pymalloc 内存分配器: 5ca.

   * "+ debug": 带有 *note PyMem_SetupDebugHooks(): 512. 安装的调试钩子


File: python.info,  Node: 自定义内存分配器,  Next: pymalloc 分配器,  Prev: 默认内存分配器,  Up: 内存管理

7.11.6 自定义内存分配器
-----------------------

3.4 新版功能.

 -- C 类型: PyMemAllocatorEx

     用于描述内存块分配器的结构体。包含四个字段：

     域                                                             含义
                                                                    
     -----------------------------------------------------------------------------------------------------------
                                                                    
     ‘void *ctx’                                                    作为第一个参数传入的用户上下文
                                                                    
                                                                    
     ‘void* malloc(void *ctx, size_t size)’                         分配一个内存块
                                                                    
                                                                    
     ‘void* calloc(void *ctx, size_t nelem, size_t elsize)’         分配一个初始化为 0 的内存块
                                                                    
                                                                    
     ‘void* realloc(void *ctx, void *ptr, size_t new_size)’         分配一个内存块或调整其大小
                                                                    
                                                                    
     ‘void free(void *ctx, void *ptr)’                              释放一个内存块
                                                                    

     在 3.5 版更改: The ‘PyMemAllocator’ structure was renamed to *note
     PyMemAllocatorEx: 7d3. and a new ‘calloc’ field was added.

 -- C 类型: PyMemAllocatorDomain

     用来识别分配器域的枚举类。域有：

      -- C 宏: PYMEM_DOMAIN_RAW

          函数

             * *note PyMem_RawMalloc(): 975.

             * *note PyMem_RawRealloc(): 976.

             * *note PyMem_RawCalloc(): 7ae.

             * *note PyMem_RawFree(): 3c48.

      -- C 宏: PYMEM_DOMAIN_MEM

          函数

             * *note PyMem_Malloc(): 50d,

             * *note PyMem_Realloc(): 977.

             * *note PyMem_Calloc(): 7af.

             * *note PyMem_Free(): db1.

      -- C 宏: PYMEM_DOMAIN_OBJ

          函数

             * *note PyObject_Malloc(): 510.

             * *note PyObject_Realloc(): db2.

             * *note PyObject_Calloc(): 7b0.

             * *note PyObject_Free(): 50c.

 -- C 函数: void PyMem_GetAllocator (PyMemAllocatorDomain domain,
          PyMemAllocatorEx *allocator)

     获取指定域的内存块分配器。

 -- C 函数: void PyMem_SetAllocator (PyMemAllocatorDomain domain,
          PyMemAllocatorEx *allocator)

     设置指定域的内存块分配器。

     当请求零字节时，新的分配器必须返回一个独特的非 ‘NULL’ 指针。

     对于 *note PYMEM_DOMAIN_RAW: 136e. 域，分配器必须是线程安全的：当分
     配器被调用时，不持有 *note 全局解释器锁: 50e. 。

     如果新的分配器不是钩子（不调用之前的分配器），必须调用 *note
     PyMem_SetupDebugHooks(): 512. 函数在新分配器上重新安装调试钩子。

 -- C 函数: void PyMem_SetupDebugHooks (void)

     设置检测 Python 内存分配器函数中错误的钩子。

     新分配的内存由字节 ‘0xCD’ ( ‘CLEANBYTE’ ) 填充，释放的内存由字节
     ‘0xDD’ ( ‘DEADBYTE’ )填充。内存块被 "禁止字节" 包围（
     ‘FORBIDDENBYTE’ ：字节 ‘0xFD’ ）。

     运行时检查：

        - 检测对 API 的违反，例如：对用 *note PyMem_Malloc(): 50d. 分配
          的缓冲区调用 *note PyObject_Free(): 50c. 。

        - 检测缓冲区起始位置前的写入（缓冲区下溢）。

        - 检测缓冲区终止位置后的写入（缓冲区溢出）。

        - 检测当调用 *note PYMEM_DOMAIN_OBJ: 50f. (如: *note
          PyObject_Malloc(): 510.) 和 *note PYMEM_DOMAIN_MEM: 511. (如:
          *note PyMem_Malloc(): 50d.) 域的分配器函数时 *note GIL: 50e. 已
          被保持。

     在出错时，调试钩子使用 *note tracemalloc: 115. 模块来回溯内存块被分
     配的位置。只有当 *note tracemalloc: 115. 正在追踪 Python 内存分配，
     并且内存块被追踪时，才会显示回溯。

     如果 Python 是在调试模式下编译的，这些钩子是 *note installed by
     default: 136d. 。环境变量 *note PYTHONMALLOC: 50b. 可以用来在发布模
     式编译的 Python 上安装调试钩子。

     在 3.6 版更改: 这个函数现在也适用于以 发布模式编译的 Python。在出错
     时，调试钩子现在使用 *note tracemalloc: 115. 来回溯内存块被分配的位
     置。调试钩子现在也检查当 *note PYMEM_DOMAIN_OBJ: 50f. 和 *note
     PYMEM_DOMAIN_MEM: 511. 域的函数被调用时，全局解释器锁是否被持有。

     在 3.8 版更改: 字节模式 ‘0xCB’ (‘CLEANBYTE’)、 ‘0xDB’ (‘DEADBYTE’)
     和 ‘0xFB’ (‘FORBIDDENBYTE’) 已被 ‘0xCD’ 、 ‘0xDD’ 和 ‘0xFD’ 替代以
     使用与 Windows CRT 调试 ‘malloc()’ 和 ‘free()’ 相同的值。


File: python.info,  Node: pymalloc 分配器,  Next: tracemalloc C API,  Prev: 自定义内存分配器,  Up: 内存管理

7.11.7 pymalloc 分配器
----------------------

Python 有为具有短生命周期的小对象（小于或等于 512 字节）优化的
`pymalloc' 分配器。它使用固定大小为 256 KiB 的称为 "arenas" 的内存映射。
对于大于512字节的分配，它回到使用 *note PyMem_RawMalloc(): 975. 和 *note
PyMem_RawRealloc(): 976. 。

`pymalloc' 是 *note PYMEM_DOMAIN_MEM: 511. (例如: *note PyMem_Malloc():
50d.) 和 *note PYMEM_DOMAIN_OBJ: 50f. (例如: *note PyObject_Malloc():
510.) 域的 *note 默认分配器: 136d. 。

arena 分配器使用以下函数：

   * Windows 上的 ‘VirtualAlloc()’ and ‘VirtualFree()’ ,

   * ‘mmap()’ 和 ‘munmap()’ ，如果可用，

   * 否则， ‘malloc()’ 和 ‘free()’ 。

* Menu:

* 自定义 pymalloc Arena 分配器::


File: python.info,  Node: 自定义 pymalloc Arena 分配器,  Up: pymalloc 分配器

7.11.7.1 自定义 pymalloc Arena 分配器
.....................................

3.4 新版功能.

 -- C 类型: PyObjectArenaAllocator

     用来描述一个 arena 分配器的结构体。这个结构体有三个字段：

     域                                                     含义
                                                            
     ---------------------------------------------------------------------------------------------------
                                                            
     ‘void *ctx’                                            作为第一个参数传入的用户上下文
                                                            
                                                            
     ‘void* alloc(void *ctx, size_t size)’                  分配一块 size 字节的区域
                                                            
                                                            
     ‘void free(void *ctx, void *ptr, size_t size)’         释放一块区域
                                                            

 -- C 函数: void PyObject_GetArenaAllocator
          (PyObjectArenaAllocator *allocator)

     获取 arena 分配器

 -- C 函数: void PyObject_SetArenaAllocator
          (PyObjectArenaAllocator *allocator)

     设置 arena 分配器


File: python.info,  Node: tracemalloc C API,  Next: 例子<34>,  Prev: pymalloc 分配器,  Up: 内存管理

7.11.8 tracemalloc C API
------------------------

3.7 新版功能.

 -- C 函数: int PyTraceMalloc_Track (unsigned int domain, uintptr_t ptr,
          size_t size)

     在 *note tracemalloc: 115. 模块中跟踪一个已分配的内存块。

     成功时返回 ‘0’，出错时返回 ‘-1’ (无法分配内存来保存跟踪信息)。 如果
     禁用了 tracemalloc 则返回 ‘-2’。

     如果内存块已被跟踪，则更新现有跟踪信息。

 -- C 函数: int PyTraceMalloc_Untrack (unsigned int domain,
          uintptr_t ptr)

     在 *note tracemalloc: 115. 模块中取消跟踪一个已分配的内存块。 如果
     内存块未被跟踪则不执行任何操作。

     如果 tracemalloc 被禁用则返回 ‘-2’，否则返回 ‘0’。


File: python.info,  Node: 例子<34>,  Prev: tracemalloc C API,  Up: 内存管理

7.11.9 例子
-----------

以下是来自 *note 概述: 4029. 小节的示例，经过重写以使 I/O 缓冲区是通过使
用第一个函数集从 Python 堆中分配的:

     PyObject *res;
     char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */

     if (buf == NULL)
         return PyErr_NoMemory();
     /* ...Do some I/O operation involving buf... */
     res = PyBytes_FromString(buf);
     PyMem_Free(buf); /* allocated with PyMem_Malloc */
     return res;

使用面向类型函数集的相同代码:

     PyObject *res;
     char *buf = PyMem_New(char, BUFSIZ); /* for I/O */

     if (buf == NULL)
         return PyErr_NoMemory();
     /* ...Do some I/O operation involving buf... */
     res = PyBytes_FromString(buf);
     PyMem_Del(buf); /* allocated with PyMem_New */
     return res;

请注意在以上两个示例中，缓冲区总是通过归属于相同集的函数来操纵的。 事实
上，对于一个给定的内存块必须使用相同的内存 API 族，以便使得混合不同分配
器的风险减至最低。 以下代码序列包含两处错误，其中一个被标记为 `fatal' 因
为它混合了两种在不同堆上操作的不同分配器。

     char *buf1 = PyMem_New(char, BUFSIZ);
     char *buf2 = (char *) malloc(BUFSIZ);
     char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
     ...
     PyMem_Del(buf3);  /* Wrong -- should be PyMem_Free() */
     free(buf2);       /* Right -- allocated via malloc() */
     free(buf1);       /* Fatal -- should be PyMem_Del()  */

除了旨在处理来自 Python 堆的原始内存块的函数之外， Python 中的对象是通过
*note PyObject_New(): 2d3, *note PyObject_NewVar(): 2d4. 和 *note
PyObject_Del(): e1e. 来分配和释放的。

这些将在有关如何在 C 中定义和实现新对象类型的下一章中讲解。


File: python.info,  Node: 对象实现支持,  Next: API 和 ABI 版本管理,  Prev: 内存管理,  Up: Python/C API 参考手册

7.12 对象实现支持
=================

本章描述了定义新对象类型时所使用的函数、类型和宏。

* Menu:

* 在堆上分配对象::
* 公用对象的结构::
* 类型对象: 类型对象<3>.
* Number Object Structures::
* Mapping Object Structures::
* Sequence Object Structures::
* Buffer Object Structures::
* Async Object Structures::
* Slot Type typedefs::
* 例子: 例子<35>.
* 使对象类型支持循环垃圾回收::


File: python.info,  Node: 在堆上分配对象,  Next: 公用对象的结构,  Up: 对象实现支持

7.12.1 在堆上分配对象
---------------------

 -- C 函数: PyObject* _PyObject_New (PyTypeObject *type)
     `Return value: New reference.'

 -- C 函数: PyVarObject* _PyObject_NewVar (PyTypeObject *type,
          Py_ssize_t size)
     `Return value: New reference.'

 -- C 函数: PyObject* PyObject_Init (PyObject *op, PyTypeObject *type)
     `Return value: Borrowed reference.' 用它的类型和初始引用来初始化新
     分配对象 `op'。返回已初始化对象。如果 `type' 表明该对象参与循环垃圾
     检测器，则将其添加到检测器的观察对象集中。 对象的其他字段不受影响。

 -- C 函数: PyVarObject* PyObject_InitVar (PyVarObject *op,
          PyTypeObject *type, Py_ssize_t size)
     `Return value: Borrowed reference.' 它的功能和 *note
     PyObject_Init(): 270. 一样，并且会初始化变量大小对象的长度信息。

 -- C 函数: TYPE* PyObject_New (TYPE, PyTypeObject *type)
     `Return value: New reference.' 使用 C 结构类型 `TYPE' 和 Python 类
     型对象 `type' 分配一个新的 Python 对象。 未在该 Python 对象标头中定
     义的字段不会被初始化；对象的引用计数将为一。 内存分配大小由 type 对
     象的 *note tp_basicsize: 3b3c. 字段来确定。

 -- C 函数: TYPE* PyObject_NewVar (TYPE, PyTypeObject *type,
          Py_ssize_t size)
     `Return value: New reference.' 使用C的数据结构类型 `TYPE' 和
     Python的类型对象 `type' 分配一个新的Python对象。Python对象头文件中
     没有定义的字段不会被初始化。被分配的内存空间预留了 `TYPE' 结构加
     `type' 对象中 *note tp_itemsize: 3b3b. 字段提供的 `size' 字段的值。
     这对于实现类似元组这种能够在构造期决定自己大小的对象是很实用的。将
     字段的数组嵌入到相同的内存分配中可以减少内存分配的次数，这提高了内
     存分配的效率。

 -- C 函数: void PyObject_Del (void *op)

     释放由 *note PyObject_New(): 2d3. 或者 *note PyObject_NewVar():
     2d4. 分配内存的对象。这通常由对象的type字段定义的 *note tp_dealloc:
     3b42. 处理函数来调用。调用这个函数以后op对象中的字段都不可以被访问
     ，因为原分配的内存空间已不再是一个有效的Python对象。

 -- C 变量: PyObject _Py_NoneStruct

     这个对象是像 ‘None’ 一样的 Python 对象。它可以使用 *note Py_None:
     3b07. 宏访问，该宏的拿到指向该对象的指针。

参见
....

*note PyModule_Create(): 3b0a.

     分配内存和创建扩展模块


File: python.info,  Node: 公用对象的结构,  Next: 类型对象<3>,  Prev: 在堆上分配对象,  Up: 对象实现支持

7.12.2 公用对象的结构
---------------------

大量的结构体被用于定义Python的对象类型。这一节描述了这些的结构体和它们的
使用方法。

所有的 Python 对象都在对象的内存表示的开始部分共享少量的字段。 这些字段
用 *note PyObject: 4c2. 或 *note PyVarObject: 4048. 类型来表示，这些类型
又由一些宏定义，这些宏也直接或间接地用于所有其他 Python 对象的定义。

 -- C 类型: PyObject

     All object types are extensions of this type.  This is a type which
     contains the information Python needs to treat a pointer to an
     object as an object.  In a normal "release" build, it contains only
     the object’s reference count and a pointer to the corresponding
     type object.  Nothing is actually declared to be a *note PyObject:
     4c2, but every pointer to a Python object can be cast to a *note
     PyObject*: 4c2.  Access to the members must be done by using the
     macros *note Py_REFCNT: 3b38. and *note Py_TYPE: 3b39.

 -- C 类型: PyVarObject

     This is an extension of *note PyObject: 4c2. that adds the
     ‘ob_size’ field.  This is only used for objects that have some
     notion of `length'.  This type does not often appear in the
     Python/C API. Access to the members must be done by using the
     macros *note Py_REFCNT: 3b38, *note Py_TYPE: 3b39, and *note
     Py_SIZE: 4049.

 -- C 宏: PyObject_HEAD

     This is a macro used when declaring new types which represent
     objects without a varying length.  The PyObject_HEAD macro expands
     to:

          PyObject ob_base;

     See documentation of *note PyObject: 4c2. above.

 -- C 宏: PyObject_VAR_HEAD

     This is a macro used when declaring new types which represent
     objects with a length that varies from instance to instance.  The
     PyObject_VAR_HEAD macro expands to:

          PyVarObject ob_base;

     See documentation of *note PyVarObject: 4048. above.

 -- C 宏: Py_TYPE (o)

     This macro is used to access the ‘ob_type’ member of a Python
     object.  It expands to:

          (((PyObject*)(o))->ob_type)

 -- C 宏: Py_REFCNT (o)

     This macro is used to access the ‘ob_refcnt’ member of a Python
     object.  It expands to:

          (((PyObject*)(o))->ob_refcnt)

 -- C 宏: Py_SIZE (o)

     This macro is used to access the ‘ob_size’ member of a Python
     object.  It expands to:

          (((PyVarObject*)(o))->ob_size)

 -- C 宏: PyObject_HEAD_INIT (type)

     This is a macro which expands to initialization values for a new
     *note PyObject: 4c2. type.  This macro expands to:

          _PyObject_EXTRA_INIT
          1, type,

 -- C 宏: PyVarObject_HEAD_INIT (type, size)

     This is a macro which expands to initialization values for a new
     *note PyVarObject: 4048. type, including the ‘ob_size’ field.  This
     macro expands to:

          _PyObject_EXTRA_INIT
          1, type, size,

 -- C 类型: PyCFunction

     Type of the functions used to implement most Python callables in C.
     Functions of this type take two *note PyObject*: 4c2. parameters
     and return one such value.  If the return value is ‘NULL’, an
     exception shall have been set.  If not ‘NULL’, the return value is
     interpreted as the return value of the function as exposed in
     Python.  The function must return a new reference.

 -- C 类型: PyCFunctionWithKeywords

     Type of the functions used to implement Python callables in C with
     signature ‘METH_VARARGS | METH_KEYWORDS’.

 -- C 类型: _PyCFunctionFast

     Type of the functions used to implement Python callables in C with
     signature *note METH_FASTCALL: fc8.

 -- C 类型: _PyCFunctionFastWithKeywords

     Type of the functions used to implement Python callables in C with
     signature ‘METH_FASTCALL | METH_KEYWORDS’.

 -- C 类型: PyMethodDef

     Structure used to describe a method of an extension type.  This
     structure has four fields:

     域                     C 类型              含义
                                                
     -------------------------------------------------------------------------------
                                                
     ‘ml_name’              const char *        name of the method
                                                
                                                
     ‘ml_meth’              PyCFunction         pointer to the C implementation
                                                
                                                
     ‘ml_flags’             int                 flag bits indicating how the call
                                                should be constructed
                                                
                                                
     ‘ml_doc’               const char *        points to the contents of the
                                                docstring
                                                

The ‘ml_meth’ is a C function pointer.  The functions may be of
different types, but they always return *note PyObject*: 4c2.  If the
function is not of the *note PyCFunction: de3, the compiler will require
a cast in the method table.  Even though *note PyCFunction: de3. defines
the first parameter as *note PyObject*: 4c2, it is common that the
method implementation uses the specific C type of the `self' object.

The ‘ml_flags’ field is a bitfield which can include the following
flags.  The individual flags indicate either a calling convention or a
binding convention.

There are four basic calling conventions for positional arguments and
two of them can be combined with ‘METH_KEYWORDS’ to support also keyword
arguments.  So there are a total of 6 calling conventions:

 -- 数据: METH_VARARGS

     This is the typical calling convention, where the methods have the
     type *note PyCFunction: de3.  The function expects two *note
     PyObject*: 4c2. values.  The first one is the `self' object for
     methods; for module functions, it is the module object.  The second
     parameter (often called `args') is a tuple object representing all
     arguments.  This parameter is typically processed using *note
     PyArg_ParseTuple(): 26b. or *note PyArg_UnpackTuple(): e4e.

 -- 数据: METH_VARARGS | METH_KEYWORDS

     Methods with these flags must be of type *note
     PyCFunctionWithKeywords: 404d.  The function expects three
     parameters: `self', `args', `kwargs' where `kwargs' is a dictionary
     of all the keyword arguments or possibly ‘NULL’ if there are no
     keyword arguments.  The parameters are typically processed using
     *note PyArg_ParseTupleAndKeywords(): 5d3.

 -- 数据: METH_FASTCALL

     Fast calling convention supporting only positional arguments.  The
     methods have the type *note _PyCFunctionFast: 404e.  The first
     parameter is `self', the second parameter is a C array of *note
     PyObject*: 4c2. values indicating the arguments and the third
     parameter is the number of arguments (the length of the array).

     This is not part of the *note limited API: 3bc4.

     3.7 新版功能.

 -- 数据: METH_FASTCALL | METH_KEYWORDS

     Extension of *note METH_FASTCALL: fc8. supporting also keyword
     arguments, with methods of type *note _PyCFunctionFastWithKeywords:
     404f.  Keyword arguments are passed the same way as in the
     vectorcall protocol: there is an additional fourth *note PyObject*:
     4c2. parameter which is a tuple representing the names of the
     keyword arguments or possibly ‘NULL’ if there are no keywords.  The
     values of the keyword arguments are stored in the `args' array,
     after the positional arguments.

     This is not part of the *note limited API: 3bc4.

     3.7 新版功能.

 -- 数据: METH_NOARGS

     Methods without parameters don’t need to check whether arguments
     are given if they are listed with the *note METH_NOARGS: e20. flag.
     They need to be of type *note PyCFunction: de3.  The first
     parameter is typically named `self' and will hold a reference to
     the module or object instance.  In all cases the second parameter
     will be ‘NULL’.

 -- 数据: METH_O

     Methods with a single object argument can be listed with the *note
     METH_O: e4f. flag, instead of invoking *note PyArg_ParseTuple():
     26b. with a ‘"O"’ argument.  They have the type *note PyCFunction:
     de3, with the `self' parameter, and a *note PyObject*: 4c2.
     parameter representing the single argument.

These two constants are not used to indicate the calling convention but
the binding when use with methods of classes.  These may not be used for
functions defined for modules.  At most one of these flags may be set
for any given method.

 -- 数据: METH_CLASS

     The method will be passed the type object as the first parameter
     rather than an instance of the type.  This is used to create `class
     methods', similar to what is created when using the *note
     classmethod(): 1d9. built-in function.

 -- 数据: METH_STATIC

     The method will be passed ‘NULL’ as the first parameter rather than
     an instance of the type.  This is used to create `static methods',
     similar to what is created when using the *note staticmethod():
     1da. built-in function.

One other constant controls whether a method is loaded in place of
another definition with the same method name.

 -- 数据: METH_COEXIST

     The method will be loaded in place of existing definitions.
     Without `METH_COEXIST', the default is to skip repeated
     definitions.  Since slot wrappers are loaded before the method
     table, the existence of a `sq_contains' slot, for example, would
     generate a wrapped method named *note __contains__(): d30. and
     preclude the loading of a corresponding PyCFunction with the same
     name.  With the flag defined, the PyCFunction will be loaded in
     place of the wrapper object and will co-exist with the slot.  This
     is helpful because calls to PyCFunctions are optimized more than
     wrapper object calls.

 -- C 类型: PyMemberDef

     Structure which describes an attribute of a type which corresponds
     to a C struct member.  Its fields are:

     域                     C 类型              含义
                                                
     -------------------------------------------------------------------------------
                                                
     ‘name’                 const char *        name of the member
                                                
                                                
     ‘type’                 int                 the type of the member in the C
                                                struct
                                                
                                                
     ‘offset’               Py_ssize_t          the offset in bytes that the
                                                member is located on the type’s
                                                object struct
                                                
                                                
     ‘flags’                int                 flag bits indicating if the field
                                                should be read-only or writable
                                                
                                                
     ‘doc’                  const char *        points to the contents of the
                                                docstring
                                                

     ‘type’ can be one of many ‘T_’ macros corresponding to various C
     types.  When the member is accessed in Python, it will be converted
     to the equivalent Python type.

     Macro name          C 类型
                         
     -------------------------------------------
                         
     T_SHORT             short
                         
                         
     T_INT               int
                         
                         
     T_LONG              长整型
                         
                         
     T_FLOAT             float
                         
                         
     T_DOUBLE            double
                         
                         
     T_STRING            const char *
                         
                         
     T_OBJECT            PyObject *
                         
                         
     T_OBJECT_EX         PyObject *
                         
                         
     T_CHAR              char
                         
                         
     T_BYTE              char
                         
                         
     T_UBYTE             unsigned char
                         
                         
     T_UINT              unsigned int
                         
                         
     T_USHORT            unsigned short
                         
                         
     T_ULONG             unsigned long
                         
                         
     T_BOOL              char
                         
                         
     T_LONGLONG          long long
                         
                         
     T_ULONGLONG         unsigned long long
                         
                         
     T_PYSSIZET          Py_ssize_t
                         

     ‘T_OBJECT’ and ‘T_OBJECT_EX’ differ in that ‘T_OBJECT’ returns
     ‘None’ if the member is ‘NULL’ and ‘T_OBJECT_EX’ raises an *note
     AttributeError: 3a3.  Try to use ‘T_OBJECT_EX’ over ‘T_OBJECT’
     because ‘T_OBJECT_EX’ handles use of the *note del: 127e. statement
     on that attribute more correctly than ‘T_OBJECT’.

     ‘flags’ can be ‘0’ for write and read access or ‘READONLY’ for
     read-only access.  Using ‘T_STRING’ for *note type: 611. implies
     ‘READONLY’.  ‘T_STRING’ data is interpreted as UTF-8.  Only
     ‘T_OBJECT’ and ‘T_OBJECT_EX’ members can be deleted.  (They are set
     to ‘NULL’).

 -- C 类型: PyGetSetDef

     Structure to define property-like access for a type.  See also
     description of the *note PyTypeObject.tp_getset: 3b4d. slot.

     域                C 类型                 含义
                                              
     ---------------------------------------------------------------------------------
                                              
     名称              const char *           attribute name
                                              
                                              
     get               getter                 C Function to get the attribute
                                              
                                              
     set               setter                 optional C function to set or delete
                                              the attribute, if omitted the
                                              attribute is readonly
                                              
                                              
     doc               const char *           optional docstring
                                              
                                              
     closure           void *                 optional function pointer, providing
                                              additional data for getter and setter
                                              

     The ‘get’ function takes one *note PyObject*: 4c2. parameter (the
     instance) and a function pointer (the associated ‘closure’):

          typedef PyObject *(*getter)(PyObject *, void *);

     It should return a new reference on success or ‘NULL’ with a set
     exception on failure.

     ‘set’ functions take two *note PyObject*: 4c2. parameters (the
     instance and the value to be set) and a function pointer (the
     associated ‘closure’):

          typedef int (*setter)(PyObject *, PyObject *, void *);

     In case the attribute should be deleted the second parameter is
     ‘NULL’.  Should return ‘0’ on success or ‘-1’ with a set exception
     on failure.


File: python.info,  Node: 类型对象<3>,  Next: Number Object Structures,  Prev: 公用对象的结构,  Up: 对象实现支持

7.12.3 类型对象
---------------

Perhaps one of the most important structures of the Python object system
is the structure that defines a new type: the *note PyTypeObject: 2d7.
structure.  Type objects can be handled using any of the ‘PyObject_*()’
or ‘PyType_*()’ functions, but do not offer much that’s interesting to
most Python applications.  These objects are fundamental to how objects
behave, so they are very important to the interpreter itself and to any
extension module that implements new types.

Type objects are fairly large compared to most of the standard types.
The reason for the size is that each type object stores a large number
of values, mostly C function pointers, each of which implements a small
part of the type’s functionality.  The fields of the type object are
examined in detail in this section.  The fields will be described in the
order in which they occur in the structure.

In addition to the following quick reference, the *note 例子: 4053.
section provides at-a-glance insight into the meaning and use of *note
PyTypeObject: 2d7.

* Menu:

* 快速参考::
* PyTypeObject Definition::
* PyObject Slots::
* PyVarObject Slots::
* PyTypeObject Slots::
* Heap Types::


File: python.info,  Node: 快速参考,  Next: PyTypeObject Definition,  Up: 类型对象<3>

7.12.3.1 快速参考
.................

* Menu:

* "tp 槽"::
* sub-slots::
* slot typedefs::


File: python.info,  Node: "tp 槽",  Next: sub-slots,  Up: 快速参考

7.12.3.2 "tp 槽"
................

PyTypeObject 槽 (1)    *note Type: 4057.      特殊方法/属性          信
                                                                     息
                                                                     (2)
                                                                     
---------------------------------------------------------------------------------------------
                                                                     
O                      T                      D                      I
                                                                     
                                                                                       
<R>                    const char *           __name__               X     X
*note tp_name: 3b5e.                                                       

*note tp_basicsize: 3b3c.Py_ssize_t                                  X     X           X
                                                                                       
                                                                                       
*note tp_itemsize: 3b3b.Py_ssize_t                                         X           X
                                                                                       
                                                                                       
*note tp_dealloc: 3b42.*note destructor: 4058.                       X     X           X
                                                                                       
                                                                                       
*note tp_vectorcall_offset: 3cc5.Py_ssize_t                                            ?
                                                                                       
                                                                                       
(*note tp_getattr: 3b65.)*note getattrfunc: 4059.__getattribute__,                     G
                                              __getattr__                              
                                              
                                                                                       
(*note tp_setattr: 3b66.)*note setattrfunc: 405a.__setattr__,                          G
                                              __delattr__                              
                                              
                                                                                       
*note tp_as_async: 405b.*note PyAsyncMethods: 3d75.*note sub-slots: 405c.              %
                       *                                                               
                       
                                                                                       
*note tp_repr: 3b5d.   *note reprfunc: 405d.  __repr__               X     X           X
                                                                                       
                                                                                       
*note tp_as_number: 405e.*note PyNumberMethods: d89.*note sub-slots: 405c.             %
                       *                                                               
                       
                                                                                       
*note tp_as_sequence: 405f.*note PySequenceMethods: 3b6c.*note sub-slots: 405c.        %
                       *                                                               
                       
                                                                                       
*note tp_as_mapping: 4060.*note PyMappingMethods: 3b6d.*note sub-slots: 405c.          %
                       *                                                               
                       
                                                                                       
*note tp_hash: 3b6e.   *note hashfunc: 4061.  __hash__               X                 G
                                                                                       
                                                                                       
*note tp_call: 3b6f.   *note ternaryfunc: 4062.__call__                    X           X
                                                                                       
                                                                                       
*note tp_str: 3b5f.    *note reprfunc: 405d.  __str__                X                 X
                                                                                       
                                                                                       
*note tp_getattro: 3b62.*note getattrofunc: 4063.__getattribute__,   X     X           G
                                              __getattr__                              
                                              
                                                                                       
*note tp_setattro: 3b63.*note setattrofunc: 4064.__setattr__,        X     X           G
                                              __delattr__                              
                                              
                                                                                       
*note tp_as_buffer: 4065.*note PyBufferProcs: 4066.                                    %
                       *                                                               
                       
                                                                                       
*note tp_flags: 3d64.  unsigned long                                 X     X           ?
                                                                                       
                                                                                       
*note tp_doc: 3b3e.    const char *           __doc__                X     X
                                                                           
                                                                                       
*note tp_traverse: 36c7.*note traverseproc: 4067.                          X           G
                                                                                       
                                                                                       
*note tp_clear: 3b5b.  *note inquiry: 4068.                                X           G
                                                                                       
                                                                                       
*note tp_richcompare: 3b68.*note richcmpfunc: 4069.__lt__, __le__,   X                 G
                                              __eq__, __ne__,                          
                                              __gt__, __ge__
                                              
                                                                                       
*note tp_weaklistoffset: 3b71.Py_ssize_t                                   X           ?
                                                                                       
                                                                                       
*note tp_iter: e38.    *note getiterfunc: 406a.__iter__                                X
                                                                                       
                                                                                       
*note tp_iternext: e39.*note iternextfunc: 406b.__next__                               X
                                                                                       
                                                                                       
*note tp_methods: 3b49.*note PyMethodDef: e23.                       X     X
                       []                                                  
                       
                                                                                       
*note tp_members: 3b47.*note PyMemberDef: 42e.                             X
                       []                                                  
                       
                                                                                       
*note tp_getset: 3b4d. *note PyGetSetDef: 42f.                       X     X
                       []                                                  
                       
                                                                                       
*note tp_base: 3b53.   *note PyTypeObject: 2d7.__base__                          X
                       *                                                         
                       
                                                                                       
*note tp_dict: 3d78.   *note PyObject: 4c2.   __dict__                           ?
                       *                                                         
                       
                                                                                       
*note tp_descr_get: 406c.*note descrgetfunc: 406d.__get__                              X
                                                                                       
                                                                                       
*note tp_descr_set: 406e.*note descrsetfunc: 406f.__set__, __delete__                  X
                                                                                       
                                                                                       
*note tp_dictoffset: 3d7d.Py_ssize_t                                       X           ?
                                                                                       
                                                                                       
*note tp_init: 3b46.   *note initproc: 4070.  __init__               X     X           X
                                                                                       
                                                                                       
*note tp_alloc: 3b44.  *note allocfunc: 4071.                        X           ?     ?
                                                                                       
                                                                                       
*note tp_new: 3b3f.    *note newfunc: 4072.   __new__                X     X     ?     ?
                                                                                       
                                                                                       
*note tp_free: 3b43.   *note freefunc: 4073.                         X     X     ?     ?
                                                                                       
                                                                                       
*note tp_is_gc: 4074.  *note inquiry: 4068.                                X           X
                                                                                       
                                                                                       
<*note tp_bases: 4075.>*note PyObject: 4c2.   __bases__                          ~
                       *                                                         
                       
                                                                                       
<*note tp_mro: 3d79.>  *note PyObject: 4c2.   __mro__                            ~
                       *                                                         
                       
                                                                                       
[*note tp_cache: 3d7a.]*note PyObject: 4c2.
                       *
                       
                                                                                       
[*note tp_subclasses: 3d7b.]*note PyObject: 4c2.__subclasses__
                       *                      
                       
                                                                                       
[*note tp_weaklist: 3d7c.]*note PyObject: 4c2.
                       *
                       
                                                                                       
(*note tp_del: 4076.)  *note destructor: 4058.
                       
                                                                                       
[*note tp_version_tag: 4077.]unsigned int
                       
                                                                                       
*note tp_finalize: 2d8.*note destructor: 4058.__del__                                  X
                                                                                       

如果定义了 ‘COUNT_ALLOCS’ ，则还存在以下（仅内部）字段：

   * *note tp_allocs: 4078.

   * *note tp_frees: 4079.

   * *note tp_maxalloc: 407a.

   * *note tp_prev: 407b.

   * *note tp_next: 407c.

   ---------- Footnotes ----------

   (1) (1) A slot name in parentheses indicates it is (effectively)
deprecated.  Names in angle brackets should be treated as read-only.
Names in square brackets are for internal use only.  "<R>" (as a prefix)
means the field is required (must be non-‘NULL’).

   (2) (2) 列：

`"O"': set on ‘PyBaseObject_Type’

`"T"': set on *note PyType_Type: 3d5f.

`"D"': default (if slot is set to ‘NULL’)

     X - PyType_Ready sets this value if it is NULL
     ~ - PyType_Ready always sets this value (it should be NULL)
     ? - PyType_Ready may set this value depending on other slots

     Also see the inheritance column ("I").

`"I"': inheritance

     X - type slot is inherited via PyType_Ready if defined with a NULL value
     % - the slots of the sub-struct are inherited individually
     G - inherited, but only in combination with other slots; see the slot's description
     ? - it's complicated; see the slot's description

Note that some slots are effectively inherited through the normal
attribute lookup chain.


File: python.info,  Node: sub-slots,  Next: slot typedefs,  Prev: "tp 槽",  Up: 快速参考

7.12.3.3 sub-slots
..................

槽                             *note Type: 4057.     特殊方法
                                                     
----------------------------------------------------------------------
                                                     
*note am_await: 407e.          *note unaryfunc: 407f.__await__
                                                     
                                                     
*note am_aiter: 4080.          *note unaryfunc: 407f.__aiter__
                                                     
                                                     
*note am_anext: 4081.          *note unaryfunc: 407f.__anext__
                                                     
                                                     
                                                     
*note nb_add: 3d76.            *note binaryfunc: 4082.__add__
                                                     __radd__
                                                     
                                                     
*note nb_inplace_add: 4083.    *note binaryfunc: 4082.__iadd__
                                                     
                                                     
*note nb_subtract: 4084.       *note binaryfunc: 4082.__sub__
                                                     __rsub__
                                                     
                                                     
*note nb_inplace_subtract: 4085.*note binaryfunc: 4082.__sub__
                                                     
                                                     
*note nb_multiply: 4086.       *note binaryfunc: 4082.__mul__
                                                     __rmul__
                                                     
                                                     
*note nb_inplace_multiply: 4087.*note binaryfunc: 4082.__mul__
                                                     
                                                     
*note nb_remainder: 4088.      *note binaryfunc: 4082.__mod__
                                                     __rmod__
                                                     
                                                     
*note nb_inplace_remainder: 4089.*note binaryfunc: 4082.__mod__
                                                     
                                                     
*note nb_divmod: 408a.         *note binaryfunc: 4082.__divmod__
                                                     __rdivmod__
                                                     
                                                     
*note nb_power: 408b.          *note ternaryfunc: 4062.__pow__
                                                     __rpow__
                                                     
                                                     
*note nb_inplace_power: 408c.  *note ternaryfunc: 4062.__pow__
                                                     
                                                     
*note nb_negative: 408d.       *note unaryfunc: 407f.__neg__
                                                     
                                                     
*note nb_positive: 408e.       *note unaryfunc: 407f.__pos__
                                                     
                                                     
*note nb_absolute: 408f.       *note unaryfunc: 407f.__abs__
                                                     
                                                     
*note nb_bool: 4090.           *note inquiry: 4068.  __bool__
                                                     
                                                     
*note nb_invert: 4091.         *note unaryfunc: 407f.__invert__
                                                     
                                                     
*note nb_lshift: 4092.         *note binaryfunc: 4082.__lshift__
                                                     __rlshift__
                                                     
                                                     
*note nb_inplace_lshift: 4093. *note binaryfunc: 4082.__lshift__
                                                     
                                                     
*note nb_rshift: 4094.         *note binaryfunc: 4082.__rshift__
                                                     __rrshift__
                                                     
                                                     
*note nb_inplace_rshift: 4095. *note binaryfunc: 4082.__rshift__
                                                     
                                                     
*note nb_and: 4096.            *note binaryfunc: 4082.__and__
                                                     __rand__
                                                     
                                                     
*note nb_inplace_and: 4097.    *note binaryfunc: 4082.__and__
                                                     
                                                     
*note nb_xor: 4098.            *note binaryfunc: 4082.__xor__
                                                     __rxor__
                                                     
                                                     
*note nb_inplace_xor: 4099.    *note binaryfunc: 4082.__xor__
                                                     
                                                     
*note nb_or: 409a.             *note binaryfunc: 4082.__or__ __ror__
                                                     
                                                     
*note nb_inplace_or: 409b.     *note binaryfunc: 4082.__or__
                                                     
                                                     
*note nb_int: 409c.            *note unaryfunc: 407f.__int__
                                                     
                                                     
*note nb_reserved: 409d.       void *
                               
                                                     
*note nb_float: 409e.          *note unaryfunc: 407f.__float__
                                                     
                                                     
*note nb_floor_divide: 409f.   *note binaryfunc: 4082.__floordiv__
                                                     
                                                     
*note nb_inplace_floor_divide: 40a0.*note binaryfunc: 4082.__floordiv__
                                                     
                                                     
*note nb_true_divide: 40a1.    *note binaryfunc: 4082.__truediv__
                                                     
                                                     
*note nb_inplace_true_divide: 40a2.*note binaryfunc: 4082.__truediv__
                                                     
                                                     
*note nb_index: 40a3.          *note unaryfunc: 407f.__index__
                                                     
                                                     
*note nb_matrix_multiply: 40a4.*note binaryfunc: 4082.__matmul__
                                                     __rmatmul__
                                                     
                                                     
*note nb_inplace_matrix_multiply: 40a5.*note binaryfunc: 4082.__matmul__
                                                     
                                                     
                                                     
*note mp_length: 40a6.         *note lenfunc: 40a7.  __len__
                                                     
                                                     
*note mp_subscript: 40a8.      *note binaryfunc: 4082.__getitem__
                                                     
                                                     
*note mp_ass_subscript: 40a9.  *note objobjargproc: 40aa.__setitem__,
                                                     __delitem__
                                                     
                                                     
                                                     
*note sq_length: 3d77.         *note lenfunc: 40a7.  __len__
                                                     
                                                     
*note sq_concat: 40ab.         *note binaryfunc: 4082.__add__
                                                     
                                                     
*note sq_repeat: 40ac.         *note ssizeargfunc: 40ad.__mul__
                                                     
                                                     
*note sq_item: 40ae.           *note ssizeargfunc: 40ad.__getitem__
                                                     
                                                     
*note sq_ass_item: 40af.       *note ssizeobjargproc: 40b0.__setitem__
                                                     __delitem__
                                                     
                                                     
*note sq_contains: 40b1.       *note objobjproc: 40b2.__contains__
                                                     
                                                     
*note sq_inplace_concat: 40b3. *note binaryfunc: 4082.__iadd__
                                                     
                                                     
*note sq_inplace_repeat: 40b4. *note ssizeargfunc: 40ad.__imul__
                                                     
                                                     
                                                     
*note bf_getbuffer: 3d7e.      *note getbufferproc(): 40b5.
                               
                                                     
*note bf_releasebuffer: 3c7f.  *note releasebufferproc(): 40b6.
                               


File: python.info,  Node: slot typedefs,  Prev: sub-slots,  Up: 快速参考

7.12.3.4 slot typedefs
......................

typedef                           参数类型                          返回类型
                                                                    
-----------------------------------------------------------------------------------------------
                                                                    
*note allocfunc: 4071.                 *note PyTypeObject: 2d7. *   *note PyObject: 4c2. *
                                       Py_ssize_t                   
                                  
                                                                    
*note destructor: 4058.           void *                            void
                                                                    
                                                                    
*note freefunc: 4073.             void *                            void
                                                                    
                                                                    
*note traverseproc: 4067.              void *                       int
                                       *note visitproc: 40b8.       
                                       void * 
                                  
                                                                    
*note newfunc: 4072.                   *note PyObject: 4c2. *       *note PyObject: 4c2. *
                                       *note PyObject: 4c2. *       
                                       *note PyObject: 4c2. * 
                                  
                                                                    
*note initproc: 4070.                  *note PyObject: 4c2. *       int
                                       *note PyObject: 4c2. *       
                                       *note PyObject: 4c2. * 
                                  
                                                                    
*note reprfunc: 405d.             *note PyObject: 4c2. *            *note PyObject: 4c2. *
                                                                    
                                                                    
*note getattrfunc: 4059.               *note PyObject: 4c2. *       *note PyObject: 4c2. *
                                       const char *                 
                                  
                                                                    
*note setattrfunc: 405a.               *note PyObject: 4c2. *       int
                                       const char *                 
                                       *note PyObject: 4c2. * 
                                  
                                                                    
*note getattrofunc: 4063.              *note PyObject: 4c2. *       *note PyObject: 4c2. *
                                       *note PyObject: 4c2. *       
                                  
                                                                    
*note setattrofunc: 4064.              *note PyObject: 4c2. *       int
                                       *note PyObject: 4c2. *       
                                       *note PyObject: 4c2. * 
                                  
                                                                    
*note descrgetfunc: 406d.              *note PyObject: 4c2. *       *note PyObject: 4c2. *
                                       *note PyObject: 4c2. *       
                                       *note PyObject: 4c2. * 
                                  
                                                                    
*note descrsetfunc: 406f.              *note PyObject: 4c2. *       int
                                       *note PyObject: 4c2. *       
                                       *note PyObject: 4c2. * 
                                  
                                                                    
*note hashfunc: 4061.             *note PyObject: 4c2. *            Py_hash_t
                                                                    
                                                                    
*note richcmpfunc: 4069.               *note PyObject: 4c2. *       *note PyObject: 4c2. *
                                       *note PyObject: 4c2. *       
                                       int 
                                  
                                                                    
*note getiterfunc: 406a.          *note PyObject: 4c2. *            *note PyObject: 4c2. *
                                                                    
                                                                    
*note iternextfunc: 406b.         *note PyObject: 4c2. *            *note PyObject: 4c2. *
                                                                    
                                                                    
*note lenfunc: 40a7.              *note PyObject: 4c2. *            Py_ssize_t
                                                                    
                                                                    
*note getbufferproc: 40b5.             *note PyObject: 4c2. *       int
                                       *note Py_buffer: b23. *      
                                       int 
                                  
                                                                    
*note releasebufferproc: 40b6.         *note PyObject: 4c2. *       void
                                       *note Py_buffer: b23. *      
                                  
                                                                    
*note inquiry: 4068.              void *                            int
                                                                    
                                                                    
*note unaryfunc: 407f.                 *note PyObject: 4c2. *       *note PyObject: 4c2. *
                                                                    
                                                                    
*note binaryfunc: 4082.                *note PyObject: 4c2. *       *note PyObject: 4c2. *
                                       *note PyObject: 4c2. *       
                                  
                                                                    
*note ternaryfunc: 4062.               *note PyObject: 4c2. *       *note PyObject: 4c2. *
                                       *note PyObject: 4c2. *       
                                       *note PyObject: 4c2. * 
                                  
                                                                    
*note ssizeargfunc: 40ad.              *note PyObject: 4c2. *       *note PyObject: 4c2. *
                                       Py_ssize_t                   
                                  
                                                                    
*note ssizeobjargproc: 40b0.           *note PyObject: 4c2. *       int
                                       Py_ssize_t                   
                                  
                                                                    
*note objobjproc: 40b2.                *note PyObject: 4c2. *       int
                                       *note PyObject: 4c2. *       
                                  
                                                                    
*note objobjargproc: 40aa.             *note PyObject: 4c2. *       int
                                       *note PyObject: 4c2. *       
                                       *note PyObject: 4c2. * 
                                  

请参阅 *note Slot Type typedefs: 40b9. 里有更多详细信息。


File: python.info,  Node: PyTypeObject Definition,  Next: PyObject Slots,  Prev: 快速参考,  Up: 类型对象<3>

7.12.3.5 PyTypeObject Definition
................................

The structure definition for *note PyTypeObject: 2d7. can be found in
‘Include/object.h’.  For convenience of reference, this repeats the
definition found there:

     typedef struct _typeobject {
         PyObject_VAR_HEAD
         const char *tp_name; /* For printing, in format "<module>.<name>" */
         Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

         /* Methods to implement standard operations */

         destructor tp_dealloc;
         Py_ssize_t tp_vectorcall_offset;
         getattrfunc tp_getattr;
         setattrfunc tp_setattr;
         PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
                                         or tp_reserved (Python 3) */
         reprfunc tp_repr;

         /* Method suites for standard classes */

         PyNumberMethods *tp_as_number;
         PySequenceMethods *tp_as_sequence;
         PyMappingMethods *tp_as_mapping;

         /* More standard operations (here for binary compatibility) */

         hashfunc tp_hash;
         ternaryfunc tp_call;
         reprfunc tp_str;
         getattrofunc tp_getattro;
         setattrofunc tp_setattro;

         /* Functions to access object as input/output buffer */
         PyBufferProcs *tp_as_buffer;

         /* Flags to define presence of optional/expanded features */
         unsigned long tp_flags;

         const char *tp_doc; /* Documentation string */

         /* call function for all accessible objects */
         traverseproc tp_traverse;

         /* delete references to contained objects */
         inquiry tp_clear;

         /* rich comparisons */
         richcmpfunc tp_richcompare;

         /* weak reference enabler */
         Py_ssize_t tp_weaklistoffset;

         /* Iterators */
         getiterfunc tp_iter;
         iternextfunc tp_iternext;

         /* Attribute descriptor and subclassing stuff */
         struct PyMethodDef *tp_methods;
         struct PyMemberDef *tp_members;
         struct PyGetSetDef *tp_getset;
         struct _typeobject *tp_base;
         PyObject *tp_dict;
         descrgetfunc tp_descr_get;
         descrsetfunc tp_descr_set;
         Py_ssize_t tp_dictoffset;
         initproc tp_init;
         allocfunc tp_alloc;
         newfunc tp_new;
         freefunc tp_free; /* Low-level free-memory routine */
         inquiry tp_is_gc; /* For PyObject_IS_GC */
         PyObject *tp_bases;
         PyObject *tp_mro; /* method resolution order */
         PyObject *tp_cache;
         PyObject *tp_subclasses;
         PyObject *tp_weaklist;
         destructor tp_del;

         /* Type attribute cache version tag. Added in version 2.6 */
         unsigned int tp_version_tag;

         destructor tp_finalize;

     } PyTypeObject;


File: python.info,  Node: PyObject Slots,  Next: PyVarObject Slots,  Prev: PyTypeObject Definition,  Up: 类型对象<3>

7.12.3.6 PyObject Slots
.......................

The type object structure extends the *note PyVarObject: 4048.
structure.  The ‘ob_size’ field is used for dynamic types (created by
‘type_new()’, usually called from a class statement).  Note that *note
PyType_Type: 3d5f. (the metatype) initializes *note tp_itemsize: 3b3b,
which means that its instances (i.e.  type objects) `must' have the
‘ob_size’ field.

 -- C 成员: PyObject* PyObject._ob_next
 -- C 成员: PyObject* PyObject._ob_prev

     These fields are only present when the macro ‘Py_TRACE_REFS’ is
     defined.  Their initialization to ‘NULL’ is taken care of by the
     ‘PyObject_HEAD_INIT’ macro.  For statically allocated objects,
     these fields always remain ‘NULL’.  For dynamically allocated
     objects, these two fields are used to link the object into a
     doubly-linked list of `all' live objects on the heap.  This could
     be used for various debugging purposes; currently the only use is
     to print the objects that are still alive at the end of a run when
     the environment variable *note PYTHONDUMPREFS: 15a. is set.

     `Inheritance:'

     These fields are not inherited by subtypes.

 -- C 成员: Py_ssize_t PyObject.ob_refcnt

     This is the type object’s reference count, initialized to ‘1’ by
     the ‘PyObject_HEAD_INIT’ macro.  Note that for statically allocated
     type objects, the type’s instances (objects whose ‘ob_type’ points
     back to the type) do `not' count as references.  But for
     dynamically allocated type objects, the instances `do' count as
     references.

     `Inheritance:'

     This field is not inherited by subtypes.

 -- C 成员: PyTypeObject* PyObject.ob_type

     This is the type’s type, in other words its metatype.  It is
     initialized by the argument to the ‘PyObject_HEAD_INIT’ macro, and
     its value should normally be ‘&PyType_Type’.  However, for
     dynamically loadable extension modules that must be usable on
     Windows (at least), the compiler complains that this is not a valid
     initializer.  Therefore, the convention is to pass ‘NULL’ to the
     ‘PyObject_HEAD_INIT’ macro and to initialize this field explicitly
     at the start of the module’s initialization function, before doing
     anything else.  This is typically done like this:

          Foo_Type.ob_type = &PyType_Type;

     This should be done before any instances of the type are created.
     *note PyType_Ready(): 3b45. checks if ‘ob_type’ is ‘NULL’, and if
     so, initializes it to the ‘ob_type’ field of the base class.  *note
     PyType_Ready(): 3b45. will not change this field if it is non-zero.

     `Inheritance:'

     This field is inherited by subtypes.


File: python.info,  Node: PyVarObject Slots,  Next: PyTypeObject Slots,  Prev: PyObject Slots,  Up: 类型对象<3>

7.12.3.7 PyVarObject Slots
..........................

 -- C 成员: Py_ssize_t PyVarObject.ob_size

     For statically allocated type objects, this should be initialized
     to zero.  For dynamically allocated type objects, this field has a
     special internal meaning.

     `Inheritance:'

     This field is not inherited by subtypes.


File: python.info,  Node: PyTypeObject Slots,  Next: Heap Types,  Prev: PyVarObject Slots,  Up: 类型对象<3>

7.12.3.8 PyTypeObject Slots
...........................

Each slot has a section describing inheritance.  If *note
PyType_Ready(): 3b45. may set a value when the field is set to ‘NULL’
then there will also be a "Default" section.  (Note that many fields set
on ‘PyBaseObject_Type’ and *note PyType_Type: 3d5f. effectively act as
defaults.)

 -- C 成员: const char* PyTypeObject.tp_name

     Pointer to a NUL-terminated string containing the name of the type.
     For types that are accessible as module globals, the string should
     be the full module name, followed by a dot, followed by the type
     name; for built-in types, it should be just the type name.  If the
     module is a submodule of a package, the full package name is part
     of the full module name.  For example, a type named ‘T’ defined in
     module ‘M’ in subpackage ‘Q’ in package ‘P’ should have the *note
     tp_name: 3b5e. initializer ‘"P.Q.M.T"’.

     For dynamically allocated type objects, this should just be the
     type name, and the module name explicitly stored in the type dict
     as the value for key ‘'__module__'’.

     For statically allocated type objects, the tp_name field should
     contain a dot.  Everything before the last dot is made accessible
     as the ‘__module__’ attribute, and everything after the last dot is
     made accessible as the *note __name__: c6f. attribute.

     If no dot is present, the entire *note tp_name: 3b5e. field is made
     accessible as the *note __name__: c6f. attribute, and the
     ‘__module__’ attribute is undefined (unless explicitly set in the
     dictionary, as explained above).  This means your type will be
     impossible to pickle.  Additionally, it will not be listed in
     module documentations created with pydoc.

     This field must not be ‘NULL’.  It is the only required field in
     *note PyTypeObject(): 2d7. (other than potentially *note
     tp_itemsize: 3b3b.).

     `Inheritance:'

     This field is not inherited by subtypes.

 -- C 成员: Py_ssize_t PyTypeObject.tp_basicsize
 -- C 成员: Py_ssize_t PyTypeObject.tp_itemsize

     These fields allow calculating the size in bytes of instances of
     the type.

     There are two kinds of types: types with fixed-length instances
     have a zero *note tp_itemsize: 3b3b. field, types with
     variable-length instances have a non-zero *note tp_itemsize: 3b3b.
     field.  For a type with fixed-length instances, all instances have
     the same size, given in *note tp_basicsize: 3b3c.

     For a type with variable-length instances, the instances must have
     an ‘ob_size’ field, and the instance size is *note tp_basicsize:
     3b3c. plus N times *note tp_itemsize: 3b3b, where N is the "length"
     of the object.  The value of N is typically stored in the
     instance’s ‘ob_size’ field.  There are exceptions: for example,
     ints use a negative ‘ob_size’ to indicate a negative number, and N
     is ‘abs(ob_size)’ there.  Also, the presence of an ‘ob_size’ field
     in the instance layout doesn’t mean that the instance structure is
     variable-length (for example, the structure for the list type has
     fixed-length instances, yet those instances have a meaningful
     ‘ob_size’ field).

     The basic size includes the fields in the instance declared by the
     macro *note PyObject_HEAD: c7a. or *note PyObject_VAR_HEAD: 404a.
     (whichever is used to declare the instance struct) and this in turn
     includes the ‘_ob_prev’ and ‘_ob_next’ fields if they are present.
     This means that the only correct way to get an initializer for the
     *note tp_basicsize: 3b3c. is to use the ‘sizeof’ operator on the
     struct used to declare the instance layout.  The basic size does
     not include the GC header size.

     A note about alignment: if the variable items require a particular
     alignment, this should be taken care of by the value of *note
     tp_basicsize: 3b3c.  Example: suppose a type implements an array of
     ‘double’.  *note tp_itemsize: 3b3b. is ‘sizeof(double)’.  It is the
     programmer’s responsibility that *note tp_basicsize: 3b3c. is a
     multiple of ‘sizeof(double)’ (assuming this is the alignment
     requirement for ‘double’).

     For any type with variable-length instances, this field must not be
     ‘NULL’.

     `Inheritance:'

     These fields are inherited separately by subtypes.  If the base
     type has a non-zero *note tp_itemsize: 3b3b, it is generally not
     safe to set *note tp_itemsize: 3b3b. to a different non-zero value
     in a subtype (though this depends on the implementation of the base
     type).

 -- C 成员: destructor PyTypeObject.tp_dealloc

     A pointer to the instance destructor function.  This function must
     be defined unless the type guarantees that its instances will never
     be deallocated (as is the case for the singletons ‘None’ and
     ‘Ellipsis’).  The function signature is:

          void tp_dealloc(PyObject *self);

     The destructor function is called by the *note Py_DECREF(): 267.
     and *note Py_XDECREF(): 269. macros when the new reference count is
     zero.  At this point, the instance is still in existence, but there
     are no references to it.  The destructor function should free all
     references which the instance owns, free all memory buffers owned
     by the instance (using the freeing function corresponding to the
     allocation function used to allocate the buffer), and call the
     type’s *note tp_free: 3b43. function.  If the type is not
     subtypable (doesn’t have the *note Py_TPFLAGS_BASETYPE: 3b4a. flag
     bit set), it is permissible to call the object deallocator directly
     instead of via *note tp_free: 3b43.  The object deallocator should
     be the one used to allocate the instance; this is normally *note
     PyObject_Del(): e1e. if the instance was allocated using *note
     PyObject_New(): 2d3. or ‘PyObject_VarNew()’, or *note
     PyObject_GC_Del(): e4b. if the instance was allocated using *note
     PyObject_GC_New(): 2d5. or *note PyObject_GC_NewVar(): 2d6.

     Finally, if the type is heap allocated (*note Py_TPFLAGS_HEAPTYPE:
     3d6c.), the deallocator should decrement the reference count for
     its type object after calling the type deallocator.  In order to
     avoid dangling pointers, the recommended way to achieve this is:

          static void foo_dealloc(foo_object *self) {
              PyTypeObject *tp = Py_TYPE(self);
              // free references and buffers here
              tp->tp_free(self);
              Py_DECREF(tp);
          }

     `Inheritance:'

     This field is inherited by subtypes.

 -- C 成员: Py_ssize_t PyTypeObject.tp_vectorcall_offset

     An optional offset to a per-instance function that implements
     calling the object using the `vectorcall' protocol, a more
     efficient alternative of the simpler *note tp_call: 3b6f.

     This field is only used if the flag *note
     _Py_TPFLAGS_HAVE_VECTORCALL: 40c3. is set.  If so, this must be a
     positive integer containing the offset in the instance of a *note
     vectorcallfunc: 40c4. pointer.  The signature is the same as for
     *note _PyObject_Vectorcall(): 3cc4.:

          PyObject *vectorcallfunc(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwnames)

     The `vectorcallfunc' pointer may be zero, in which case the
     instance behaves as if *note _Py_TPFLAGS_HAVE_VECTORCALL: 40c3. was
     not set: calling the instance falls back to *note tp_call: 3b6f.

     Any class that sets ‘_Py_TPFLAGS_HAVE_VECTORCALL’ must also set
     *note tp_call: 3b6f. and make sure its behaviour is consistent with
     the `vectorcallfunc' function.  This can be done by setting
     `tp_call' to ‘PyVectorcall_Call’:

      -- C 函数: PyObject *PyVectorcall_Call (PyObject *callable,
               PyObject *tuple, PyObject *dict)

          Call `callable'’s `vectorcallfunc' with positional and keyword
          arguments given in a tuple and dict, respectively.

          This function is intended to be used in the ‘tp_call’ slot.
          It does not fall back to ‘tp_call’ and it currently does not
          check the ‘_Py_TPFLAGS_HAVE_VECTORCALL’ flag.  To call an
          object, use one of the *note PyObject_Call: 3b13. functions
          instead.

          注解: It is not recommended for *note heap types: 3d6a. to
          implement the vectorcall protocol.  When a user sets
          ‘__call__’ in Python code, only ‘tp_call’ is updated, possibly
          making it inconsistent with the vectorcall function.

          注解: The semantics of the ‘tp_vectorcall_offset’ slot are
          provisional and expected to be finalized in Python 3.9.  If
          you use vectorcall, plan for updating your code for Python
          3.9.

     在 3.8 版更改: This slot was used for print formatting in Python
     2.x.  In Python 3.0 to 3.7, it was reserved and named ‘tp_print’.

     `Inheritance:'

     This field is inherited by subtypes together with *note tp_call:
     3b6f.: a subtype inherits *note tp_vectorcall_offset: 3cc5. from
     its base type when the subtype’s *note tp_call: 3b6f. is ‘NULL’.

     Note that *note heap types: 40c6. (including subclasses defined in
     Python) do not inherit the *note _Py_TPFLAGS_HAVE_VECTORCALL: 40c3.
     flag.

 -- C 成员: getattrfunc PyTypeObject.tp_getattr

     An optional pointer to the get-attribute-string function.

     This field is deprecated.  When it is defined, it should point to a
     function that acts the same as the *note tp_getattro: 3b62.
     function, but taking a C string instead of a Python string object
     to give the attribute name.

     `Inheritance:'

     Group: ‘tp_getattr’, ‘tp_getattro’

     This field is inherited by subtypes together with *note
     tp_getattro: 3b62.: a subtype inherits both *note tp_getattr: 3b65.
     and *note tp_getattro: 3b62. from its base type when the subtype’s
     *note tp_getattr: 3b65. and *note tp_getattro: 3b62. are both
     ‘NULL’.

 -- C 成员: setattrfunc PyTypeObject.tp_setattr

     An optional pointer to the function for setting and deleting
     attributes.

     This field is deprecated.  When it is defined, it should point to a
     function that acts the same as the *note tp_setattro: 3b63.
     function, but taking a C string instead of a Python string object
     to give the attribute name.

     `Inheritance:'

     Group: ‘tp_setattr’, ‘tp_setattro’

     This field is inherited by subtypes together with *note
     tp_setattro: 3b63.: a subtype inherits both *note tp_setattr: 3b66.
     and *note tp_setattro: 3b63. from its base type when the subtype’s
     *note tp_setattr: 3b66. and *note tp_setattro: 3b63. are both
     ‘NULL’.

 -- C 成员: PyAsyncMethods* PyTypeObject.tp_as_async

     Pointer to an additional structure that contains fields relevant
     only to objects which implement *note awaitable: 521. and *note
     asynchronous iterator: 64e. protocols at the C-level.  See *note
     Async Object Structures: 40c7. for details.

     3.5 新版功能: Formerly known as ‘tp_compare’ and ‘tp_reserved’.

     `Inheritance:'

     The *note tp_as_async: 405b. field is not inherited, but the
     contained fields are inherited individually.

 -- C 成员: reprfunc PyTypeObject.tp_repr

     An optional pointer to a function that implements the built-in
     function *note repr(): 7d5.

     The signature is the same as for *note PyObject_Repr(): 970.:

          PyObject *tp_repr(PyObject *self);

     The function must return a string or a Unicode object.  Ideally,
     this function should return a string that, when passed to *note
     eval(): b98, given a suitable environment, returns an object with
     the same value.  If this is not feasible, it should return a string
     starting with ‘'<'’ and ending with ‘'>'’ from which both the type
     and the value of the object can be deduced.

     `Inheritance:'

     This field is inherited by subtypes.

     `Default:'

     When this field is not set, a string of the form ‘<%s object at
     %p>’ is returned, where ‘%s’ is replaced by the type name, and ‘%p’
     by the object’s memory address.

 -- C 成员: PyNumberMethods* PyTypeObject.tp_as_number

     Pointer to an additional structure that contains fields relevant
     only to objects which implement the number protocol.  These fields
     are documented in *note Number Object Structures: 40c8.

     `Inheritance:'

     The *note tp_as_number: 405e. field is not inherited, but the
     contained fields are inherited individually.

 -- C 成员: PySequenceMethods* PyTypeObject.tp_as_sequence

     Pointer to an additional structure that contains fields relevant
     only to objects which implement the sequence protocol.  These
     fields are documented in *note Sequence Object Structures: 40c9.

     `Inheritance:'

     The *note tp_as_sequence: 405f. field is not inherited, but the
     contained fields are inherited individually.

 -- C 成员: PyMappingMethods* PyTypeObject.tp_as_mapping

     Pointer to an additional structure that contains fields relevant
     only to objects which implement the mapping protocol.  These fields
     are documented in *note Mapping Object Structures: 40ca.

     `Inheritance:'

     The *note tp_as_mapping: 4060. field is not inherited, but the
     contained fields are inherited individually.

 -- C 成员: hashfunc PyTypeObject.tp_hash

     An optional pointer to a function that implements the built-in
     function *note hash(): 9cc.

     The signature is the same as for *note PyObject_Hash(): 3cc9.:

          Py_hash_t tp_hash(PyObject *);

     The value ‘-1’ should not be returned as a normal return value;
     when an error occurs during the computation of the hash value, the
     function should set an exception and return ‘-1’.

     When this field is not set (`and' ‘tp_richcompare’ is not set), an
     attempt to take the hash of the object raises *note TypeError: 193.
     This is the same as setting it to *note
     PyObject_HashNotImplemented(): d39.

     This field can be set explicitly to *note
     PyObject_HashNotImplemented(): d39. to block inheritance of the
     hash method from a parent type.  This is interpreted as the
     equivalent of ‘__hash__ = None’ at the Python level, causing
     ‘isinstance(o, collections.Hashable)’ to correctly return ‘False’.
     Note that the converse is also true - setting ‘__hash__ = None’ on
     a class at the Python level will result in the ‘tp_hash’ slot being
     set to *note PyObject_HashNotImplemented(): d39.

     `Inheritance:'

     Group: ‘tp_hash’, ‘tp_richcompare’

     This field is inherited by subtypes together with *note
     tp_richcompare: 3b68.: a subtype inherits both of *note
     tp_richcompare: 3b68. and *note tp_hash: 3b6e, when the subtype’s
     *note tp_richcompare: 3b68. and *note tp_hash: 3b6e. are both
     ‘NULL’.

 -- C 成员: ternaryfunc PyTypeObject.tp_call

     An optional pointer to a function that implements calling the
     object.  This should be ‘NULL’ if the object is not callable.  The
     signature is the same as for *note PyObject_Call(): 3b13.:

          PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);

     `Inheritance:'

     This field is inherited by subtypes.

 -- C 成员: reprfunc PyTypeObject.tp_str

     An optional pointer to a function that implements the built-in
     operation *note str(): 339.  (Note that *note str: 339. is a type
     now, and *note str(): 339. calls the constructor for that type.
     This constructor calls *note PyObject_Str(): 971. to do the actual
     work, and *note PyObject_Str(): 971. will call this handler.)

     The signature is the same as for *note PyObject_Str(): 971.:

          PyObject *tp_str(PyObject *self);

     The function must return a string or a Unicode object.  It should
     be a "friendly" string representation of the object, as this is the
     representation that will be used, among other things, by the *note
     print(): 88f. function.

     `Inheritance:'

     This field is inherited by subtypes.

     `Default:'

     When this field is not set, *note PyObject_Repr(): 970. is called
     to return a string representation.

 -- C 成员: getattrofunc PyTypeObject.tp_getattro

     An optional pointer to the get-attribute function.

     The signature is the same as for *note PyObject_GetAttr(): 3cb5.:

          PyObject *tp_getattro(PyObject *self, PyObject *attr);

     It is usually convenient to set this field to *note
     PyObject_GenericGetAttr(): 3cb7, which implements the normal way of
     looking for object attributes.

     `Inheritance:'

     Group: ‘tp_getattr’, ‘tp_getattro’

     This field is inherited by subtypes together with *note tp_getattr:
     3b65.: a subtype inherits both *note tp_getattr: 3b65. and *note
     tp_getattro: 3b62. from its base type when the subtype’s *note
     tp_getattr: 3b65. and *note tp_getattro: 3b62. are both ‘NULL’.

     `Default:'

     ‘PyBaseObject_Type’ uses *note PyObject_GenericGetAttr(): 3cb7.

 -- C 成员: setattrofunc PyTypeObject.tp_setattro

     An optional pointer to the function for setting and deleting
     attributes.

     The signature is the same as for *note PyObject_SetAttr(): 3cb8.:

          PyObject *tp_setattro(PyObject *self, PyObject *attr, PyObject *value);

     In addition, setting `value' to ‘NULL’ to delete an attribute must
     be supported.  It is usually convenient to set this field to *note
     PyObject_GenericSetAttr(): 3cba, which implements the normal way of
     setting object attributes.

     `Inheritance:'

     Group: ‘tp_setattr’, ‘tp_setattro’

     This field is inherited by subtypes together with *note tp_setattr:
     3b66.: a subtype inherits both *note tp_setattr: 3b66. and *note
     tp_setattro: 3b63. from its base type when the subtype’s *note
     tp_setattr: 3b66. and *note tp_setattro: 3b63. are both ‘NULL’.

     `Default:'

     ‘PyBaseObject_Type’ uses *note PyObject_GenericSetAttr(): 3cba.

 -- C 成员: PyBufferProcs* PyTypeObject.tp_as_buffer

     Pointer to an additional structure that contains fields relevant
     only to objects which implement the buffer interface.  These fields
     are documented in *note Buffer Object Structures: 3d1c.

     `Inheritance:'

     The *note tp_as_buffer: 4065. field is not inherited, but the
     contained fields are inherited individually.

 -- C 成员: unsigned long PyTypeObject.tp_flags

     This field is a bit mask of various flags.  Some flags indicate
     variant semantics for certain situations; others are used to
     indicate that certain fields in the type object (or in the
     extension structures referenced via *note tp_as_number: 405e, *note
     tp_as_sequence: 405f, *note tp_as_mapping: 4060, and *note
     tp_as_buffer: 4065.) that were historically not always present are
     valid; if such a flag bit is clear, the type fields it guards must
     not be accessed and must be considered to have a zero or ‘NULL’
     value instead.

     `Inheritance:'

     Inheritance of this field is complicated.  Most flag bits are
     inherited individually, i.e.  if the base type has a flag bit set,
     the subtype inherits this flag bit.  The flag bits that pertain to
     extension structures are strictly inherited if the extension
     structure is inherited, i.e.  the base type’s value of the flag bit
     is copied into the subtype together with a pointer to the extension
     structure.  The *note Py_TPFLAGS_HAVE_GC: 3b51. flag bit is
     inherited together with the *note tp_traverse: 36c7. and *note
     tp_clear: 3b5b. fields, i.e.  if the *note Py_TPFLAGS_HAVE_GC:
     3b51. flag bit is clear in the subtype and the *note tp_traverse:
     36c7. and *note tp_clear: 3b5b. fields in the subtype exist and
     have ‘NULL’ values.

     `Default:'

     ‘PyBaseObject_Type’ uses ‘Py_TPFLAGS_DEFAULT |
     Py_TPFLAGS_BASETYPE’.

     `Bit Masks:'

     The following bit masks are currently defined; these can be ORed
     together using the ‘|’ operator to form the value of the *note
     tp_flags: 3d64. field.  The macro *note PyType_HasFeature(): 3d66.
     takes a type and a flags value, `tp' and `f', and checks whether
     ‘tp->tp_flags & f’ is non-zero.

      -- 数据: Py_TPFLAGS_HEAPTYPE

          This bit is set when the type object itself is allocated on
          the heap, for example, types created dynamically using *note
          PyType_FromSpec(): 2d2.  In this case, the ‘ob_type’ field of
          its instances is considered a reference to the type, and the
          type object is INCREF’ed when a new instance is created, and
          DECREF’ed when an instance is destroyed (this does not apply
          to instances of subtypes; only the type referenced by the
          instance’s ob_type gets INCREF’ed or DECREF’ed).

          `Inheritance:'

          ???

      -- 数据: Py_TPFLAGS_BASETYPE

          This bit is set when the type can be used as the base type of
          another type.  If this bit is clear, the type cannot be
          subtyped (similar to a "final" class in Java).

          `Inheritance:'

          ???

      -- 数据: Py_TPFLAGS_READY

          This bit is set when the type object has been fully
          initialized by *note PyType_Ready(): 3b45.

          `Inheritance:'

          ???

      -- 数据: Py_TPFLAGS_READYING

          This bit is set while *note PyType_Ready(): 3b45. is in the
          process of initializing the type object.

          `Inheritance:'

          ???

      -- 数据: Py_TPFLAGS_HAVE_GC

          This bit is set when the object supports garbage collection.
          If this bit is set, instances must be created using *note
          PyObject_GC_New(): 2d5. and destroyed using *note
          PyObject_GC_Del(): e4b.  More information in section *note
          使对象类型支持循环垃圾回收: 40cd.  This bit also implies that
          the GC-related fields *note tp_traverse: 36c7. and *note
          tp_clear: 3b5b. are present in the type object.

          `Inheritance:'

          Group: *note Py_TPFLAGS_HAVE_GC: 3b51, ‘tp_traverse’,
          ‘tp_clear’

          The *note Py_TPFLAGS_HAVE_GC: 3b51. flag bit is inherited
          together with the ‘tp_traverse’ and ‘tp_clear’ fields, i.e.
          if the *note Py_TPFLAGS_HAVE_GC: 3b51. flag bit is clear in
          the subtype and the ‘tp_traverse’ and ‘tp_clear’ fields in the
          subtype exist and have ‘NULL’ values.

      -- 数据: Py_TPFLAGS_DEFAULT

          This is a bitmask of all the bits that pertain to the
          existence of certain fields in the type object and its
          extension structures.  Currently, it includes the following
          bits: ‘Py_TPFLAGS_HAVE_STACKLESS_EXTENSION’,
          ‘Py_TPFLAGS_HAVE_VERSION_TAG’.

          `Inheritance:'

          ???

      -- 数据: Py_TPFLAGS_METHOD_DESCRIPTOR

          This bit indicates that objects behave like unbound methods.

          If this flag is set for ‘type(meth)’, then:

             - ‘meth.__get__(obj, cls)(*args, **kwds)’ (with ‘obj’ not
               None) must be equivalent to ‘meth(obj, *args, **kwds)’.

             - ‘meth.__get__(None, cls)(*args, **kwds)’ must be
               equivalent to ‘meth(*args, **kwds)’.

          This flag enables an optimization for typical method calls
          like ‘obj.meth()’: it avoids creating a temporary "bound
          method" object for ‘obj.meth’.

          3.8 新版功能.

          `Inheritance:'

          This flag is never inherited by heap types.  For extension
          types, it is inherited whenever *note tp_descr_get: 406c. is
          inherited.

      -- 数据: Py_TPFLAGS_LONG_SUBCLASS

      -- 数据: Py_TPFLAGS_LIST_SUBCLASS

      -- 数据: Py_TPFLAGS_TUPLE_SUBCLASS

      -- 数据: Py_TPFLAGS_BYTES_SUBCLASS

      -- 数据: Py_TPFLAGS_UNICODE_SUBCLASS

      -- 数据: Py_TPFLAGS_DICT_SUBCLASS

      -- 数据: Py_TPFLAGS_BASE_EXC_SUBCLASS

      -- 数据: Py_TPFLAGS_TYPE_SUBCLASS

          These flags are used by functions such as *note
          PyLong_Check(): 3d8a. to quickly determine if a type is a
          subclass of a built-in type; such specific checks are faster
          than a generic check, like *note PyObject_IsInstance(): 7a6.
          Custom types that inherit from built-ins should have their
          *note tp_flags: 3d64. set appropriately, or the code that
          interacts with such types will behave differently depending on
          what kind of check is used.

      -- 数据: Py_TPFLAGS_HAVE_FINALIZE

          This bit is set when the *note tp_finalize: 2d8. slot is
          present in the type structure.

          3.4 新版功能.

          3.8 版后已移除: This flag isn’t necessary anymore, as the
          interpreter assumes the *note tp_finalize: 2d8. slot is always
          present in the type structure.

      -- 数据: _Py_TPFLAGS_HAVE_VECTORCALL

          This bit is set when the class implements the vectorcall
          protocol.  See *note tp_vectorcall_offset: 3cc5. for details.

          `Inheritance:'

          This bit is set on `static' subtypes if ‘tp_flags’ is not
          overridden: a subtype inherits ‘_Py_TPFLAGS_HAVE_VECTORCALL’
          from its base type when the subtype’s *note tp_call: 3b6f. is
          ‘NULL’ and the subtype’s ‘Py_TPFLAGS_HEAPTYPE’ is not set.

          *note Heap types: 40c6. do not inherit
          ‘_Py_TPFLAGS_HAVE_VECTORCALL’.

               注解: This flag is provisional and expected to become
               public in Python 3.9, with a different name and,
               possibly, changed semantics.  If you use vectorcall, plan
               for updating your code for Python 3.9.

          3.8 新版功能.

 -- C 成员: const char* PyTypeObject.tp_doc

     An optional pointer to a NUL-terminated C string giving the
     docstring for this type object.  This is exposed as the ‘__doc__’
     attribute on the type and instances of the type.

     `Inheritance:'

     This field is `not' inherited by subtypes.

 -- C 成员: traverseproc PyTypeObject.tp_traverse

     An optional pointer to a traversal function for the garbage
     collector.  This is only used if the *note Py_TPFLAGS_HAVE_GC:
     3b51. flag bit is set.  The signature is:

          int tp_traverse(PyObject *self, visitproc visit, void *arg);

     More information about Python’s garbage collection scheme can be
     found in section *note 使对象类型支持循环垃圾回收: 40cd.

     The *note tp_traverse: 36c7. pointer is used by the garbage
     collector to detect reference cycles.  A typical implementation of
     a *note tp_traverse: 36c7. function simply calls *note Py_VISIT():
     3b4f. on each of the instance’s members that are Python objects
     that the instance owns.  For example, this is function
     ‘local_traverse()’ from the *note _thread: 3. extension module:

          static int
          local_traverse(localobject *self, visitproc visit, void *arg)
          {
              Py_VISIT(self->args);
              Py_VISIT(self->kw);
              Py_VISIT(self->dict);
              return 0;
          }

     Note that *note Py_VISIT(): 3b4f. is called only on those members
     that can participate in reference cycles.  Although there is also a
     ‘self->key’ member, it can only be ‘NULL’ or a Python string and
     therefore cannot be part of a reference cycle.

     On the other hand, even if you know a member can never be part of a
     cycle, as a debugging aid you may want to visit it anyway just so
     the *note gc: 86. module’s *note get_referents(): eb5. function
     will include it.

          警告: When implementing *note tp_traverse: 36c7, only the
          members that the instance `owns' (by having strong references
          to them) must be visited.  For instance, if an object supports
          weak references via the *note tp_weaklist: 3d7c. slot, the
          pointer supporting the linked list (what `tp_weaklist' points
          to) must `not' be visited as the instance does not directly
          own the weak references to itself (the weakreference list is
          there to support the weak reference machinery, but the
          instance has no strong reference to the elements inside it, as
          they are allowed to be removed even if the instance is still
          alive).

     Note that *note Py_VISIT(): 3b4f. requires the `visit' and `arg'
     parameters to ‘local_traverse()’ to have these specific names;
     don’t name them just anything.

     `Inheritance:'

     Group: *note Py_TPFLAGS_HAVE_GC: 3b51, ‘tp_traverse’, ‘tp_clear’

     This field is inherited by subtypes together with *note tp_clear:
     3b5b. and the *note Py_TPFLAGS_HAVE_GC: 3b51. flag bit: the flag
     bit, *note tp_traverse: 36c7, and *note tp_clear: 3b5b. are all
     inherited from the base type if they are all zero in the subtype.

 -- C 成员: inquiry PyTypeObject.tp_clear

     An optional pointer to a clear function for the garbage collector.
     This is only used if the *note Py_TPFLAGS_HAVE_GC: 3b51. flag bit
     is set.  The signature is:

          int tp_clear(PyObject *);

     The *note tp_clear: 3b5b. member function is used to break
     reference cycles in cyclic garbage detected by the garbage
     collector.  Taken together, all *note tp_clear: 3b5b. functions in
     the system must combine to break all reference cycles.  This is
     subtle, and if in any doubt supply a *note tp_clear: 3b5b.
     function.  For example, the tuple type does not implement a *note
     tp_clear: 3b5b. function, because it’s possible to prove that no
     reference cycle can be composed entirely of tuples.  Therefore the
     *note tp_clear: 3b5b. functions of other types must be sufficient
     to break any cycle containing a tuple.  This isn’t immediately
     obvious, and there’s rarely a good reason to avoid implementing
     *note tp_clear: 3b5b.

     Implementations of *note tp_clear: 3b5b. should drop the instance’s
     references to those of its members that may be Python objects, and
     set its pointers to those members to ‘NULL’, as in the following
     example:

          static int
          local_clear(localobject *self)
          {
              Py_CLEAR(self->key);
              Py_CLEAR(self->args);
              Py_CLEAR(self->kw);
              Py_CLEAR(self->dict);
              return 0;
          }

     The *note Py_CLEAR(): 3b50. macro should be used, because clearing
     references is delicate: the reference to the contained object must
     not be decremented until after the pointer to the contained object
     is set to ‘NULL’.  This is because decrementing the reference count
     may cause the contained object to become trash, triggering a chain
     of reclamation activity that may include invoking arbitrary Python
     code (due to finalizers, or weakref callbacks, associated with the
     contained object).  If it’s possible for such code to reference
     `self' again, it’s important that the pointer to the contained
     object be ‘NULL’ at that time, so that `self' knows the contained
     object can no longer be used.  The *note Py_CLEAR(): 3b50. macro
     performs the operations in a safe order.

     Because the goal of *note tp_clear: 3b5b. functions is to break
     reference cycles, it’s not necessary to clear contained objects
     like Python strings or Python integers, which can’t participate in
     reference cycles.  On the other hand, it may be convenient to clear
     all contained Python objects, and write the type’s *note
     tp_dealloc: 3b42. function to invoke *note tp_clear: 3b5b.

     More information about Python’s garbage collection scheme can be
     found in section *note 使对象类型支持循环垃圾回收: 40cd.

     `Inheritance:'

     Group: *note Py_TPFLAGS_HAVE_GC: 3b51, ‘tp_traverse’, ‘tp_clear’

     This field is inherited by subtypes together with *note
     tp_traverse: 36c7. and the *note Py_TPFLAGS_HAVE_GC: 3b51. flag
     bit: the flag bit, *note tp_traverse: 36c7, and *note tp_clear:
     3b5b. are all inherited from the base type if they are all zero in
     the subtype.

 -- C 成员: richcmpfunc PyTypeObject.tp_richcompare

     An optional pointer to the rich comparison function, whose
     signature is:

          PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);

     The first parameter is guaranteed to be an instance of the type
     that is defined by *note PyTypeObject: 2d7.

     The function should return the result of the comparison (usually
     ‘Py_True’ or ‘Py_False’).  If the comparison is undefined, it must
     return ‘Py_NotImplemented’, if another error occurred it must
     return ‘NULL’ and set an exception condition.

     The following constants are defined to be used as the third
     argument for *note tp_richcompare: 3b68. and for *note
     PyObject_RichCompare(): 3b69.:

     常数                 对照
                          
     --------------------------------------
                          
     ‘Py_LT’              ‘<’
                          
                          
     ‘Py_LE’              ‘<=’
                          
                          
     ‘Py_EQ’              ‘==’
                          
                          
     ‘Py_NE’              ‘!=’
                          
                          
     ‘Py_GT’              ‘>’
                          
                          
     ‘Py_GE’              ‘>=’
                          

     定义以下宏是为了简化编写丰富的比较函数：

      -- C 宏: Py_RETURN_RICHCOMPARE (VAL_A, VAL_B, op)

          Return ‘Py_True’ or ‘Py_False’ from the function, depending on
          the result of a comparison.  VAL_A and VAL_B must be orderable
          by C comparison operators (for example, they may be C ints or
          floats).  The third argument specifies the requested
          operation, as for *note PyObject_RichCompare(): 3b69.

          The return value’s reference count is properly incremented.

          On error, sets an exception and returns ‘NULL’ from the
          function.

          3.7 新版功能.

     `Inheritance:'

     Group: ‘tp_hash’, ‘tp_richcompare’

     This field is inherited by subtypes together with *note tp_hash:
     3b6e.: a subtype inherits *note tp_richcompare: 3b68. and *note
     tp_hash: 3b6e. when the subtype’s *note tp_richcompare: 3b68. and
     *note tp_hash: 3b6e. are both ‘NULL’.

     `Default:'

     ‘PyBaseObject_Type’ provides a ‘tp_richcompare’ implementation,
     which may be inherited.  However, if only ‘tp_hash’ is defined, not
     even the inherited function is used and instances of the type will
     not be able to participate in any comparisons.

 -- C 成员: Py_ssize_t PyTypeObject.tp_weaklistoffset

     If the instances of this type are weakly referenceable, this field
     is greater than zero and contains the offset in the instance
     structure of the weak reference list head (ignoring the GC header,
     if present); this offset is used by ‘PyObject_ClearWeakRefs()’ and
     the ‘PyWeakref_*()’ functions.  The instance structure needs to
     include a field of type *note PyObject*: 4c2. which is initialized
     to ‘NULL’.

     Do not confuse this field with *note tp_weaklist: 3d7c.; that is
     the list head for weak references to the type object itself.

     `Inheritance:'

     This field is inherited by subtypes, but see the rules listed
     below.  A subtype may override this offset; this means that the
     subtype uses a different weak reference list head than the base
     type.  Since the list head is always found via *note
     tp_weaklistoffset: 3b71, this should not be a problem.

     When a type defined by a class statement has no *note __slots__:
     e35. declaration, and none of its base types are weakly
     referenceable, the type is made weakly referenceable by adding a
     weak reference list head slot to the instance layout and setting
     the *note tp_weaklistoffset: 3b71. of that slot’s offset.

     When a type’s *note __slots__: e35. declaration contains a slot
     named ‘__weakref__’, that slot becomes the weak reference list head
     for instances of the type, and the slot’s offset is stored in the
     type’s *note tp_weaklistoffset: 3b71.

     When a type’s *note __slots__: e35. declaration does not contain a
     slot named ‘__weakref__’, the type inherits its *note
     tp_weaklistoffset: 3b71. from its base type.

 -- C 成员: getiterfunc PyTypeObject.tp_iter

     An optional pointer to a function that returns an iterator for the
     object.  Its presence normally signals that the instances of this
     type are iterable (although sequences may be iterable without this
     function).

     This function has the same signature as *note PyObject_GetIter():
     3cd1.:

          PyObject *tp_iter(PyObject *self);

     `Inheritance:'

     This field is inherited by subtypes.

 -- C 成员: iternextfunc PyTypeObject.tp_iternext

     An optional pointer to a function that returns the next item in an
     iterator.  The signature is:

          PyObject *tp_iternext(PyObject *self);

     When the iterator is exhausted, it must return ‘NULL’; a *note
     StopIteration: 48e. exception may or may not be set.  When another
     error occurs, it must return ‘NULL’ too.  Its presence signals that
     the instances of this type are iterators.

     Iterator types should also define the *note tp_iter: e38. function,
     and that function should return the iterator instance itself (not a
     new iterator instance).

     This function has the same signature as *note PyIter_Next(): 3d19.

     `Inheritance:'

     This field is inherited by subtypes.

 -- C 成员: struct PyMethodDef* PyTypeObject.tp_methods

     An optional pointer to a static ‘NULL’-terminated array of *note
     PyMethodDef: e23. structures, declaring regular methods of this
     type.

     For each entry in the array, an entry is added to the type’s
     dictionary (see *note tp_dict: 3d78. below) containing a method
     descriptor.

     `Inheritance:'

     This field is not inherited by subtypes (methods are inherited
     through a different mechanism).

 -- C 成员: struct PyMemberDef* PyTypeObject.tp_members

     An optional pointer to a static ‘NULL’-terminated array of *note
     PyMemberDef: 42e. structures, declaring regular data members
     (fields or slots) of instances of this type.

     For each entry in the array, an entry is added to the type’s
     dictionary (see *note tp_dict: 3d78. below) containing a member
     descriptor.

     `Inheritance:'

     This field is not inherited by subtypes (members are inherited
     through a different mechanism).

 -- C 成员: struct PyGetSetDef* PyTypeObject.tp_getset

     An optional pointer to a static ‘NULL’-terminated array of *note
     PyGetSetDef: 42f. structures, declaring computed attributes of
     instances of this type.

     For each entry in the array, an entry is added to the type’s
     dictionary (see *note tp_dict: 3d78. below) containing a getset
     descriptor.

     `Inheritance:'

     This field is not inherited by subtypes (computed attributes are
     inherited through a different mechanism).

 -- C 成员: PyTypeObject* PyTypeObject.tp_base

     An optional pointer to a base type from which type properties are
     inherited.  At this level, only single inheritance is supported;
     multiple inheritance require dynamically creating a type object by
     calling the metatype.

          注解: 
          Slot initialization is subject to the rules of initializing
          globals.  C99 requires the initializers to be "address
          constants".  Function designators like *note
          PyType_GenericNew(): 3b40, with implicit conversion to a
          pointer, are valid C99 address constants.

          However, the unary ’&’ operator applied to a non-static
          variable like ‘PyBaseObject_Type()’ is not required to produce
          an address constant.  Compilers may support this (gcc does),
          MSVC does not.  Both compilers are strictly standard
          conforming in this particular behavior.

          Consequently, *note tp_base: 3b53. should be set in the
          extension module’s init function.

     `Inheritance:'

     This field is not inherited by subtypes (obviously).

     `Default:'

     This field defaults to ‘&PyBaseObject_Type’ (which to Python
     programmers is known as the type *note object: 2b1.).

 -- C 成员: PyObject* PyTypeObject.tp_dict

     The type’s dictionary is stored here by *note PyType_Ready(): 3b45.

     This field should normally be initialized to ‘NULL’ before
     PyType_Ready is called; it may also be initialized to a dictionary
     containing initial attributes for the type.  Once *note
     PyType_Ready(): 3b45. has initialized the type, extra attributes
     for the type may be added to this dictionary only if they don’t
     correspond to overloaded operations (like *note __add__(): 1467.).

     `Inheritance:'

     This field is not inherited by subtypes (though the attributes
     defined in here are inherited through a different mechanism).

     `Default:'

     If this field is ‘NULL’, *note PyType_Ready(): 3b45. will assign a
     new dictionary to it.

          警告: It is not safe to use *note PyDict_SetItem(): 3b26. on
          or otherwise modify *note tp_dict: 3d78. with the dictionary
          C-API.

 -- C 成员: descrgetfunc PyTypeObject.tp_descr_get

     An optional pointer to a "descriptor get" function.

     The function signature is:

          PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);

     `Inheritance:'

     This field is inherited by subtypes.

 -- C 成员: descrsetfunc PyTypeObject.tp_descr_set

     An optional pointer to a function for setting and deleting a
     descriptor’s value.

     The function signature is:

          int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);

     The `value' argument is set to ‘NULL’ to delete the value.

     `Inheritance:'

     This field is inherited by subtypes.

 -- C 成员: Py_ssize_t PyTypeObject.tp_dictoffset

     If the instances of this type have a dictionary containing instance
     variables, this field is non-zero and contains the offset in the
     instances of the type of the instance variable dictionary; this
     offset is used by *note PyObject_GenericGetAttr(): 3cb7.

     Do not confuse this field with *note tp_dict: 3d78.; that is the
     dictionary for attributes of the type object itself.

     If the value of this field is greater than zero, it specifies the
     offset from the start of the instance structure.  If the value is
     less than zero, it specifies the offset from the `end' of the
     instance structure.  A negative offset is more expensive to use,
     and should only be used when the instance structure contains a
     variable-length part.  This is used for example to add an instance
     variable dictionary to subtypes of *note str: 339. or *note tuple:
     486.  Note that the *note tp_basicsize: 3b3c. field should account
     for the dictionary added to the end in that case, even though the
     dictionary is not included in the basic object layout.  On a system
     with a pointer size of 4 bytes, *note tp_dictoffset: 3d7d. should
     be set to ‘-4’ to indicate that the dictionary is at the very end
     of the structure.

     The real dictionary offset in an instance can be computed from a
     negative *note tp_dictoffset: 3d7d. as follows:

          dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset
          if dictoffset is not aligned on sizeof(void*):
              round up to sizeof(void*)

     where *note tp_basicsize: 3b3c, *note tp_itemsize: 3b3b. and *note
     tp_dictoffset: 3d7d. are taken from the type object, and ‘ob_size’
     is taken from the instance.  The absolute value is taken because
     ints use the sign of ‘ob_size’ to store the sign of the number.
     (There’s never a need to do this calculation yourself; it is done
     for you by ‘_PyObject_GetDictPtr()’.)

     `Inheritance:'

     This field is inherited by subtypes, but see the rules listed
     below.  A subtype may override this offset; this means that the
     subtype instances store the dictionary at a difference offset than
     the base type.  Since the dictionary is always found via *note
     tp_dictoffset: 3d7d, this should not be a problem.

     When a type defined by a class statement has no *note __slots__:
     e35. declaration, and none of its base types has an instance
     variable dictionary, a dictionary slot is added to the instance
     layout and the *note tp_dictoffset: 3d7d. is set to that slot’s
     offset.

     When a type defined by a class statement has a *note __slots__:
     e35. declaration, the type inherits its *note tp_dictoffset: 3d7d.
     from its base type.

     (Adding a slot named *note __dict__: 504. to the *note __slots__:
     e35. declaration does not have the expected effect, it just causes
     confusion.  Maybe this should be added as a feature just like
     ‘__weakref__’ though.)

     `Default:'

     This slot has no default.  For static types, if the field is ‘NULL’
     then no *note __dict__: 504. gets created for instances.

 -- C 成员: initproc PyTypeObject.tp_init

     An optional pointer to an instance initialization function.

     This function corresponds to the *note __init__(): d66. method of
     classes.  Like *note __init__(): d66, it is possible to create an
     instance without calling *note __init__(): d66, and it is possible
     to reinitialize an instance by calling its *note __init__(): d66.
     method again.

     The function signature is:

          int tp_init(PyObject *self, PyObject *args, PyObject *kwds);

     The self argument is the instance to be initialized; the `args' and
     `kwds' arguments represent positional and keyword arguments of the
     call to *note __init__(): d66.

     The *note tp_init: 3b46. function, if not ‘NULL’, is called when an
     instance is created normally by calling its type, after the type’s
     *note tp_new: 3b3f. function has returned an instance of the type.
     If the *note tp_new: 3b3f. function returns an instance of some
     other type that is not a subtype of the original type, no *note
     tp_init: 3b46. function is called; if *note tp_new: 3b3f. returns
     an instance of a subtype of the original type, the subtype’s *note
     tp_init: 3b46. is called.

     Returns ‘0’ on success, ‘-1’ and sets an exception on error.

     `Inheritance:'

     This field is inherited by subtypes.

     `Default:'

     For static types this field does not have a default.

 -- C 成员: allocfunc PyTypeObject.tp_alloc

     An optional pointer to an instance allocation function.

     The function signature is:

          PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);

     `Inheritance:'

     This field is inherited by static subtypes, but not by dynamic
     subtypes (subtypes created by a class statement).

     `Default:'

     For dynamic subtypes, this field is always set to *note
     PyType_GenericAlloc(): 271, to force a standard heap allocation
     strategy.

     For static subtypes, ‘PyBaseObject_Type’ uses *note
     PyType_GenericAlloc(): 271.  That is the recommended value for all
     statically defined types.

 -- C 成员: newfunc PyTypeObject.tp_new

     An optional pointer to an instance creation function.

     The function signature is:

          PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);

     The subtype argument is the type of the object being created; the
     `args' and `kwds' arguments represent positional and keyword
     arguments of the call to the type.  Note that subtype doesn’t have
     to equal the type whose *note tp_new: 3b3f. function is called; it
     may be a subtype of that type (but not an unrelated type).

     The *note tp_new: 3b3f. function should call
     ‘subtype->tp_alloc(subtype, nitems)’ to allocate space for the
     object, and then do only as much further initialization as is
     absolutely necessary.  Initialization that can safely be ignored or
     repeated should be placed in the *note tp_init: 3b46. handler.  A
     good rule of thumb is that for immutable types, all initialization
     should take place in *note tp_new: 3b3f, while for mutable types,
     most initialization should be deferred to *note tp_init: 3b46.

     `Inheritance:'

     This field is inherited by subtypes, except it is not inherited by
     static types whose *note tp_base: 3b53. is ‘NULL’ or
     ‘&PyBaseObject_Type’.

     `Default:'

     For static types this field has no default.  This means if the slot
     is defined as ‘NULL’, the type cannot be called to create new
     instances; presumably there is some other way to create instances,
     like a factory function.

 -- C 成员: freefunc PyTypeObject.tp_free

     An optional pointer to an instance deallocation function.  Its
     signature is:

          void tp_free(void *self);

     An initializer that is compatible with this signature is *note
     PyObject_Free(): 50c.

     `Inheritance:'

     This field is inherited by static subtypes, but not by dynamic
     subtypes (subtypes created by a class statement)

     `Default:'

     In dynamic subtypes, this field is set to a deallocator suitable to
     match *note PyType_GenericAlloc(): 271. and the value of the *note
     Py_TPFLAGS_HAVE_GC: 3b51. flag bit.

     For static subtypes, ‘PyBaseObject_Type’ uses PyObject_Del.

 -- C 成员: inquiry PyTypeObject.tp_is_gc

     An optional pointer to a function called by the garbage collector.

     The garbage collector needs to know whether a particular object is
     collectible or not.  Normally, it is sufficient to look at the
     object’s type’s *note tp_flags: 3d64. field, and check the *note
     Py_TPFLAGS_HAVE_GC: 3b51. flag bit.  But some types have a mixture
     of statically and dynamically allocated instances, and the
     statically allocated instances are not collectible.  Such types
     should define this function; it should return ‘1’ for a collectible
     instance, and ‘0’ for a non-collectible instance.  The signature
     is:

          int tp_is_gc(PyObject *self);

     (The only example of this are types themselves.  The metatype,
     *note PyType_Type: 3d5f, defines this function to distinguish
     between statically and dynamically allocated types.)

     `Inheritance:'

     This field is inherited by subtypes.

     `Default:'

     This slot has no default.  If this field is ‘NULL’, *note
     Py_TPFLAGS_HAVE_GC: 3b51. is used as the functional equivalent.

 -- C 成员: PyObject* PyTypeObject.tp_bases

     Tuple of base types.

     This is set for types created by a class statement.  It should be
     ‘NULL’ for statically defined types.

     `Inheritance:'

     This field is not inherited.

 -- C 成员: PyObject* PyTypeObject.tp_mro

     Tuple containing the expanded set of base types, starting with the
     type itself and ending with *note object: 2b1, in Method Resolution
     Order.

     `Inheritance:'

     This field is not inherited; it is calculated fresh by *note
     PyType_Ready(): 3b45.

 -- C 成员: PyObject* PyTypeObject.tp_cache

     Unused.  Internal use only.

     `Inheritance:'

     This field is not inherited.

 -- C 成员: PyObject* PyTypeObject.tp_subclasses

     List of weak references to subclasses.  Internal use only.

     `Inheritance:'

     This field is not inherited.

 -- C 成员: PyObject* PyTypeObject.tp_weaklist

     Weak reference list head, for weak references to this type object.
     Not inherited.  Internal use only.

     `Inheritance:'

     This field is not inherited.

 -- C 成员: destructor PyTypeObject.tp_del

     This field is deprecated.  Use *note tp_finalize: 2d8. instead.

 -- C 成员: unsigned int PyTypeObject.tp_version_tag

     Used to index into the method cache.  Internal use only.

     `Inheritance:'

     This field is not inherited.

 -- C 成员: destructor PyTypeObject.tp_finalize

     An optional pointer to an instance finalization function.  Its
     signature is:

          void tp_finalize(PyObject *self);

     If *note tp_finalize: 2d8. is set, the interpreter calls it once
     when finalizing an instance.  It is called either from the garbage
     collector (if the instance is part of an isolated reference cycle)
     or just before the object is deallocated.  Either way, it is
     guaranteed to be called before attempting to break reference
     cycles, ensuring that it finds the object in a sane state.

     *note tp_finalize: 2d8. should not mutate the current exception
     status; therefore, a recommended way to write a non-trivial
     finalizer is:

          static void
          local_finalize(PyObject *self)
          {
              PyObject *error_type, *error_value, *error_traceback;

              /* Save the current exception, if any. */
              PyErr_Fetch(&error_type, &error_value, &error_traceback);

              /* ... */

              /* Restore the saved exception. */
              PyErr_Restore(error_type, error_value, error_traceback);
          }

     For this field to be taken into account (even through inheritance),
     you must also set the *note Py_TPFLAGS_HAVE_FINALIZE: 2d9. flags
     bit.

     `Inheritance:'

     This field is inherited by subtypes.

     3.4 新版功能.

     参见
     ....

     "Safe object finalization" ( PEP 442(1))

The remaining fields are only defined if the feature test macro
‘COUNT_ALLOCS’ is defined, and are for internal use only.  They are
documented here for completeness.  None of these fields are inherited by
subtypes.

 -- C 成员: Py_ssize_t PyTypeObject.tp_allocs

     Number of allocations.

 -- C 成员: Py_ssize_t PyTypeObject.tp_frees

     Number of frees.

 -- C 成员: Py_ssize_t PyTypeObject.tp_maxalloc

     Maximum simultaneously allocated objects.

 -- C 成员: PyTypeObject* PyTypeObject.tp_prev

     Pointer to the previous type object with a non-zero *note
     tp_allocs: 4078. field.

 -- C 成员: PyTypeObject* PyTypeObject.tp_next

     Pointer to the next type object with a non-zero *note tp_allocs:
     4078. field.

Also, note that, in a garbage collected Python, *note tp_dealloc: 3b42.
may be called from any Python thread, not just the thread which created
the object (if the object becomes part of a refcount cycle, that cycle
might be collected by a garbage collection on any thread).  This is not
a problem for Python API calls, since the thread on which tp_dealloc is
called will own the Global Interpreter Lock (GIL). However, if the
object being destroyed in turn destroys objects from some other C or C++
library, care should be taken to ensure that destroying those objects on
the thread which called tp_dealloc will not violate any assumptions of
the library.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0442


File: python.info,  Node: Heap Types,  Prev: PyTypeObject Slots,  Up: 类型对象<3>

7.12.3.9 Heap Types
...................

Traditionally, types defined in C code are `static', that is, a static
*note PyTypeObject: 2d7. structure is defined directly in code and
initialized using *note PyType_Ready(): 3b45.

This results in types that are limited relative to types defined in
Python:

   * Static types are limited to one base, i.e.  they cannot use
     multiple inheritance.

   * Static type objects (but not necessarily their instances) are
     immutable.  It is not possible to add or modify the type object’s
     attributes from Python.

   * Static type objects are shared across *note sub-interpreters: 3c44,
     so they should not include any subinterpreter-specific state.

Also, since *note PyTypeObject: 2d7. is not part of the *note stable
ABI: 3bc4, any extension modules using static types must be compiled for
a specific Python minor version.

An alternative to static types is `heap-allocated types', or `heap
types' for short, which correspond closely to classes created by
Python’s ‘class’ statement.

This is done by filling a *note PyType_Spec: 3d6d. structure and calling
*note PyType_FromSpecWithBases(): 3d6b.


File: python.info,  Node: Number Object Structures,  Next: Mapping Object Structures,  Prev: 类型对象<3>,  Up: 对象实现支持

7.12.4 Number Object Structures
-------------------------------

 -- C 类型: PyNumberMethods

     This structure holds pointers to the functions which an object uses
     to implement the number protocol.  Each function is used by the
     function of similar name documented in the *note 数字协议: 3cd3.
     section.

     Here is the structure definition:

          typedef struct {
               binaryfunc nb_add;
               binaryfunc nb_subtract;
               binaryfunc nb_multiply;
               binaryfunc nb_remainder;
               binaryfunc nb_divmod;
               ternaryfunc nb_power;
               unaryfunc nb_negative;
               unaryfunc nb_positive;
               unaryfunc nb_absolute;
               inquiry nb_bool;
               unaryfunc nb_invert;
               binaryfunc nb_lshift;
               binaryfunc nb_rshift;
               binaryfunc nb_and;
               binaryfunc nb_xor;
               binaryfunc nb_or;
               unaryfunc nb_int;
               void *nb_reserved;
               unaryfunc nb_float;

               binaryfunc nb_inplace_add;
               binaryfunc nb_inplace_subtract;
               binaryfunc nb_inplace_multiply;
               binaryfunc nb_inplace_remainder;
               ternaryfunc nb_inplace_power;
               binaryfunc nb_inplace_lshift;
               binaryfunc nb_inplace_rshift;
               binaryfunc nb_inplace_and;
               binaryfunc nb_inplace_xor;
               binaryfunc nb_inplace_or;

               binaryfunc nb_floor_divide;
               binaryfunc nb_true_divide;
               binaryfunc nb_inplace_floor_divide;
               binaryfunc nb_inplace_true_divide;

               unaryfunc nb_index;

               binaryfunc nb_matrix_multiply;
               binaryfunc nb_inplace_matrix_multiply;
          } PyNumberMethods;

          注解: Binary and ternary functions must check the type of all
          their operands, and implement the necessary conversions (at
          least one of the operands is an instance of the defined type).
          If the operation is not defined for the given operands, binary
          and ternary functions must return ‘Py_NotImplemented’, if
          another error occurred they must return ‘NULL’ and set an
          exception.

          注解: The ‘nb_reserved’ field should always be ‘NULL’.  It was
          previously called ‘nb_long’, and was renamed in Python 3.0.1.

 -- C 成员: binaryfunc PyNumberMethods.nb_add

 -- C 成员: binaryfunc PyNumberMethods.nb_subtract

 -- C 成员: binaryfunc PyNumberMethods.nb_multiply

 -- C 成员: binaryfunc PyNumberMethods.nb_remainder

 -- C 成员: binaryfunc PyNumberMethods.nb_divmod

 -- C 成员: ternaryfunc PyNumberMethods.nb_power

 -- C 成员: unaryfunc PyNumberMethods.nb_negative

 -- C 成员: unaryfunc PyNumberMethods.nb_positive

 -- C 成员: unaryfunc PyNumberMethods.nb_absolute

 -- C 成员: inquiry PyNumberMethods.nb_bool

 -- C 成员: unaryfunc PyNumberMethods.nb_invert

 -- C 成员: binaryfunc PyNumberMethods.nb_lshift

 -- C 成员: binaryfunc PyNumberMethods.nb_rshift

 -- C 成员: binaryfunc PyNumberMethods.nb_and

 -- C 成员: binaryfunc PyNumberMethods.nb_xor

 -- C 成员: binaryfunc PyNumberMethods.nb_or

 -- C 成员: unaryfunc PyNumberMethods.nb_int

 -- C 成员: void *PyNumberMethods.nb_reserved

 -- C 成员: unaryfunc PyNumberMethods.nb_float

 -- C 成员: binaryfunc PyNumberMethods.nb_inplace_add

 -- C 成员: binaryfunc PyNumberMethods.nb_inplace_subtract

 -- C 成员: binaryfunc PyNumberMethods.nb_inplace_multiply

 -- C 成员: binaryfunc PyNumberMethods.nb_inplace_remainder

 -- C 成员: ternaryfunc PyNumberMethods.nb_inplace_power

 -- C 成员: binaryfunc PyNumberMethods.nb_inplace_lshift

 -- C 成员: binaryfunc PyNumberMethods.nb_inplace_rshift

 -- C 成员: binaryfunc PyNumberMethods.nb_inplace_and

 -- C 成员: binaryfunc PyNumberMethods.nb_inplace_xor

 -- C 成员: binaryfunc PyNumberMethods.nb_inplace_or

 -- C 成员: binaryfunc PyNumberMethods.nb_floor_divide

 -- C 成员: binaryfunc PyNumberMethods.nb_true_divide

 -- C 成员: binaryfunc PyNumberMethods.nb_inplace_floor_divide

 -- C 成员: binaryfunc PyNumberMethods.nb_inplace_true_divide

 -- C 成员: unaryfunc PyNumberMethods.nb_index

 -- C 成员: binaryfunc PyNumberMethods.nb_matrix_multiply

 -- C 成员: binaryfunc PyNumberMethods.nb_inplace_matrix_multiply


File: python.info,  Node: Mapping Object Structures,  Next: Sequence Object Structures,  Prev: Number Object Structures,  Up: 对象实现支持

7.12.5 Mapping Object Structures
--------------------------------

 -- C 类型: PyMappingMethods

     This structure holds pointers to the functions which an object uses
     to implement the mapping protocol.  It has three members:

 -- C 成员: lenfunc PyMappingMethods.mp_length

     This function is used by *note PyMapping_Size(): 1061. and *note
     PyObject_Size(): 3ccd, and has the same signature.  This slot may
     be set to ‘NULL’ if the object has no defined length.

 -- C 成员: binaryfunc PyMappingMethods.mp_subscript

     This function is used by *note PyObject_GetItem(): 3bb5. and *note
     PySequence_GetSlice(): 3cfd, and has the same signature as
     ‘PyObject_GetItem()’.  This slot must be filled for the *note
     PyMapping_Check(): 3d0e. function to return ‘1’, it can be ‘NULL’
     otherwise.

 -- C 成员: objobjargproc PyMappingMethods.mp_ass_subscript

     This function is used by *note PyObject_SetItem(): 3bb3, *note
     PyObject_DelItem(): 3ccf, ‘PyObject_SetSlice()’ and
     ‘PyObject_DelSlice()’.  It has the same signature as
     ‘PyObject_SetItem()’, but `v' can also be set to ‘NULL’ to delete
     an item.  If this slot is ‘NULL’, the object does not support item
     assignment and deletion.


File: python.info,  Node: Sequence Object Structures,  Next: Buffer Object Structures,  Prev: Mapping Object Structures,  Up: 对象实现支持

7.12.6 Sequence Object Structures
---------------------------------

 -- C 类型: PySequenceMethods

     This structure holds pointers to the functions which an object uses
     to implement the sequence protocol.

 -- C 成员: lenfunc PySequenceMethods.sq_length

     This function is used by *note PySequence_Size(): 105d. and *note
     PyObject_Size(): 3ccd, and has the same signature.  It is also used
     for handling negative indices via the *note sq_item: 40ae. and the
     *note sq_ass_item: 40af. slots.

 -- C 成员: binaryfunc PySequenceMethods.sq_concat

     This function is used by *note PySequence_Concat(): 3cf9. and has
     the same signature.  It is also used by the ‘+’ operator, after
     trying the numeric addition via the *note nb_add: 3d76. slot.

 -- C 成员: ssizeargfunc PySequenceMethods.sq_repeat

     This function is used by *note PySequence_Repeat(): 3cfa. and has
     the same signature.  It is also used by the ‘*’ operator, after
     trying numeric multiplication via the *note nb_multiply: 4086.
     slot.

 -- C 成员: ssizeargfunc PySequenceMethods.sq_item

     This function is used by *note PySequence_GetItem(): 105e. and has
     the same signature.  It is also used by *note PyObject_GetItem():
     3bb5, after trying the subscription via the *note mp_subscript:
     40a8. slot.  This slot must be filled for the *note
     PySequence_Check(): 3cf7. function to return ‘1’, it can be ‘NULL’
     otherwise.

     Negative indexes are handled as follows: if the ‘sq_length’ slot is
     filled, it is called and the sequence length is used to compute a
     positive index which is passed to ‘sq_item’.  If ‘sq_length’ is
     ‘NULL’, the index is passed as is to the function.

 -- C 成员: ssizeobjargproc PySequenceMethods.sq_ass_item

     This function is used by *note PySequence_SetItem(): 105f. and has
     the same signature.  It is also used by *note PyObject_SetItem():
     3bb3. and *note PyObject_DelItem(): 3ccf, after trying the item
     assignment and deletion via the *note mp_ass_subscript: 40a9. slot.
     This slot may be left to ‘NULL’ if the object does not support item
     assignment and deletion.

 -- C 成员: objobjproc PySequenceMethods.sq_contains

     This function may be used by *note PySequence_Contains(): 3d01. and
     has the same signature.  This slot may be left to ‘NULL’, in this
     case ‘PySequence_Contains()’ simply traverses the sequence until it
     finds a match.

 -- C 成员: binaryfunc PySequenceMethods.sq_inplace_concat

     This function is used by *note PySequence_InPlaceConcat(): 3cfb.
     and has the same signature.  It should modify its first operand,
     and return it.  This slot may be left to ‘NULL’, in this case
     ‘PySequence_InPlaceConcat()’ will fall back to *note
     PySequence_Concat(): 3cf9.  It is also used by the augmented
     assignment ‘+=’, after trying numeric in-place addition via the
     *note nb_inplace_add: 4083. slot.

 -- C 成员: ssizeargfunc PySequenceMethods.sq_inplace_repeat

     This function is used by *note PySequence_InPlaceRepeat(): 3cfc.
     and has the same signature.  It should modify its first operand,
     and return it.  This slot may be left to ‘NULL’, in this case
     ‘PySequence_InPlaceRepeat()’ will fall back to *note
     PySequence_Repeat(): 3cfa.  It is also used by the augmented
     assignment ‘*=’, after trying numeric in-place multiplication via
     the *note nb_inplace_multiply: 4087. slot.


File: python.info,  Node: Buffer Object Structures,  Next: Async Object Structures,  Prev: Sequence Object Structures,  Up: 对象实现支持

7.12.7 Buffer Object Structures
-------------------------------

 -- C 类型: PyBufferProcs

     This structure holds pointers to the functions required by the
     *note Buffer protocol: 15f7.  The protocol defines how an exporter
     object can expose its internal data to consumer objects.

 -- C 成员: getbufferproc PyBufferProcs.bf_getbuffer

     The signature of this function is:

          int (PyObject *exporter, Py_buffer *view, int flags);

     Handle a request to `exporter' to fill in `view' as specified by
     `flags'.  Except for point (3), an implementation of this function
     MUST take these steps:

       1. Check if the request can be met.  If not, raise
          ‘PyExc_BufferError’, set ‘view->obj’ to ‘NULL’ and return
          ‘-1’.

       2. Fill in the requested fields.

       3. Increment an internal counter for the number of exports.

       4. Set ‘view->obj’ to `exporter' and increment ‘view->obj’.

       5. Return ‘0’.

     If `exporter' is part of a chain or tree of buffer providers, two
     main schemes can be used:

        * Re-export: Each member of the tree acts as the exporting
          object and sets ‘view->obj’ to a new reference to itself.

        * Redirect: The buffer request is redirected to the root object
          of the tree.  Here, ‘view->obj’ will be a new reference to the
          root object.

     The individual fields of `view' are described in section *note
     Buffer structure: 3d1d, the rules how an exporter must react to
     specific requests are in section *note Buffer request types: 3d31.

     All memory pointed to in the *note Py_buffer: b23. structure
     belongs to the exporter and must remain valid until there are no
     consumers left.  *note format: 3d2a, *note shape: 3d2c, *note
     strides: 3d21, *note suboffsets: 3d2e. and *note internal: 3d30.
     are read-only for the consumer.

     *note PyBuffer_FillInfo(): 3d24. provides an easy way of exposing a
     simple bytes buffer while dealing correctly with all request types.

     *note PyObject_GetBuffer(): d2d. is the interface for the consumer
     that wraps this function.

 -- C 成员: releasebufferproc PyBufferProcs.bf_releasebuffer

     The signature of this function is:

          void (PyObject *exporter, Py_buffer *view);

     Handle a request to release the resources of the buffer.  If no
     resources need to be released, *note
     PyBufferProcs.bf_releasebuffer: 3c7f. may be ‘NULL’.  Otherwise, a
     standard implementation of this function will take these optional
     steps:

       1. Decrement an internal counter for the number of exports.

       2. If the counter is ‘0’, free all memory associated with `view'.

     The exporter MUST use the *note internal: 3d30. field to keep track
     of buffer-specific resources.  This field is guaranteed to remain
     constant, while a consumer MAY pass a copy of the original buffer
     as the `view' argument.

     This function MUST NOT decrement ‘view->obj’, since that is done
     automatically in *note PyBuffer_Release(): d5c. (this scheme is
     useful for breaking reference cycles).

     *note PyBuffer_Release(): d5c. is the interface for the consumer
     that wraps this function.


File: python.info,  Node: Async Object Structures,  Next: Slot Type typedefs,  Prev: Buffer Object Structures,  Up: 对象实现支持

7.12.8 Async Object Structures
------------------------------

3.5 新版功能.

 -- C 类型: PyAsyncMethods

     This structure holds pointers to the functions required to
     implement *note awaitable: 521. and *note asynchronous iterator:
     64e. objects.

     Here is the structure definition:

          typedef struct {
              unaryfunc am_await;
              unaryfunc am_aiter;
              unaryfunc am_anext;
          } PyAsyncMethods;

 -- C 成员: unaryfunc PyAsyncMethods.am_await

     The signature of this function is:

          PyObject *am_await(PyObject *self);

     The returned object must be an iterator, i.e.  *note
     PyIter_Check(): 1020. must return ‘1’ for it.

     This slot may be set to ‘NULL’ if an object is not an *note
     awaitable: 521.

 -- C 成员: unaryfunc PyAsyncMethods.am_aiter

     The signature of this function is:

          PyObject *am_aiter(PyObject *self);

     Must return an *note awaitable: 521. object.  See *note
     __anext__(): 14a5. for details.

     This slot may be set to ‘NULL’ if an object does not implement
     asynchronous iteration protocol.

 -- C 成员: unaryfunc PyAsyncMethods.am_anext

     The signature of this function is:

          PyObject *am_anext(PyObject *self);

     Must return an *note awaitable: 521. object.  See *note
     __anext__(): 14a5. for details.  This slot may be set to ‘NULL’.


File: python.info,  Node: Slot Type typedefs,  Next: 例子<35>,  Prev: Async Object Structures,  Up: 对象实现支持

7.12.9 Slot Type typedefs
-------------------------

 -- C 类型: PyObject *(*allocfunc) (PyTypeObject *cls,
          Py_ssize_t nitems)

     The purpose of this function is to separate memory allocation from
     memory initialization.  It should return a pointer to a block of
     memory of adequate length for the instance, suitably aligned, and
     initialized to zeros, but with ‘ob_refcnt’ set to ‘1’ and ‘ob_type’
     set to the type argument.  If the type’s *note tp_itemsize: 3b3b.
     is non-zero, the object’s ‘ob_size’ field should be initialized to
     `nitems' and the length of the allocated memory block should be
     ‘tp_basicsize + nitems*tp_itemsize’, rounded up to a multiple of
     ‘sizeof(void*)’; otherwise, `nitems' is not used and the length of
     the block should be *note tp_basicsize: 3b3c.

     This function should not do any other instance initialization, not
     even to allocate additional memory; that should be done by *note
     tp_new: 3b3f.

 -- C 类型: void (*destructor) (PyObject *)

 -- C 类型: PyObject *(*vectorcallfunc) (PyObject *callable, PyObject
          *const *args, size_t nargsf, PyObject *kwnames)

     See *note tp_vectorcall_offset: 3cc5.

     Arguments to ‘vectorcallfunc’ are the same as for *note
     _PyObject_Vectorcall(): 3cc4.

     3.8 新版功能.

 -- C 类型: void (*freefunc) (void *)

     See *note tp_free: 3b43.

 -- C 类型: PyObject *(*newfunc) (PyObject *, PyObject *, PyObject *)

     See *note tp_new: 3b3f.

 -- C 类型: int (*initproc) (PyObject *, PyObject *, PyObject *)

     See *note tp_init: 3b46.

 -- C 类型: PyObject *(*reprfunc) (PyObject *)

     See *note tp_repr: 3b5d.

 -- C 类型: PyObject *(*getattrfunc) (PyObject *self, char *attr)

     Return the value of the named attribute for the object.

 -- C 类型: int (*setattrfunc) (PyObject *self, char *attr,
          PyObject *value)

     Set the value of the named attribute for the object.  The value
     argument is set to ‘NULL’ to delete the attribute.

 -- C 类型: PyObject *(*getattrofunc) (PyObject *self, PyObject *attr)

     Return the value of the named attribute for the object.

     See *note tp_getattro: 3b62.

 -- C 类型: int (*setattrofunc) (PyObject *self, PyObject *attr,
          PyObject *value)

     Set the value of the named attribute for the object.  The value
     argument is set to ‘NULL’ to delete the attribute.

     See *note tp_setattro: 3b63.

 -- C 类型: PyObject *(*descrgetfunc) (PyObject *, PyObject *,
          PyObject *)

     See ‘tp_descrget’.

 -- C 类型: int (*descrsetfunc) (PyObject *, PyObject *, PyObject *)

     See ‘tp_descrset’.

 -- C 类型: Py_hash_t (*hashfunc) (PyObject *)

     See *note tp_hash: 3b6e.

 -- C 类型: PyObject *(*richcmpfunc) (PyObject *, PyObject *, int)

     See *note tp_richcompare: 3b68.

 -- C 类型: PyObject *(*getiterfunc) (PyObject *)

     See *note tp_iter: e38.

 -- C 类型: PyObject *(*iternextfunc) (PyObject *)

     See *note tp_iternext: e39.

 -- C 类型: Py_ssize_t (*lenfunc) (PyObject *)

 -- C 类型: int (*getbufferproc) (PyObject *, Py_buffer *, int)

 -- C 类型: void (*releasebufferproc) (PyObject *, Py_buffer *)

 -- C 类型: PyObject *(*unaryfunc) (PyObject *)

 -- C 类型: PyObject *(*binaryfunc) (PyObject *, PyObject *)

 -- C 类型: PyObject *(*ternaryfunc) (PyObject *, PyObject *,
          PyObject *)

 -- C 类型: PyObject *(*ssizeargfunc) (PyObject *, Py_ssize_t)

 -- C 类型: int (*ssizeobjargproc) (PyObject *, Py_ssize_t)

 -- C 类型: int (*objobjproc) (PyObject *, PyObject *)

 -- C 类型: int (*objobjargproc) (PyObject *, PyObject *, PyObject *)


File: python.info,  Node: 例子<35>,  Next: 使对象类型支持循环垃圾回收,  Prev: Slot Type typedefs,  Up: 对象实现支持

7.12.10 例子
------------

The following are simple examples of Python type definitions.  They
include common usage you may encounter.  Some demonstrate tricky corner
cases.  For more examples, practical info, and a tutorial, see *note
自定义扩展类型：教程: 3b34. and *note 定义扩展类型：已分类主题: 3b57.

A basic static type:

     typedef struct {
         PyObject_HEAD
         const char *data;
     } MyObject;

     static PyTypeObject MyObject_Type = {
         PyVarObject_HEAD_INIT(NULL, 0)
         .tp_name = "mymod.MyObject",
         .tp_basicsize = sizeof(MyObject),
         .tp_doc = "My objects",
         .tp_new = myobj_new,
         .tp_dealloc = (destructor)myobj_dealloc,
         .tp_repr = (reprfunc)myobj_repr,
     };

You may also find older code (especially in the CPython code base) with
a more verbose initializer:

     static PyTypeObject MyObject_Type = {
         PyVarObject_HEAD_INIT(NULL, 0)
         "mymod.MyObject",               /* tp_name */
         sizeof(MyObject),               /* tp_basicsize */
         0,                              /* tp_itemsize */
         (destructor)myobj_dealloc,      /* tp_dealloc */
         0,                              /* tp_vectorcall_offset */
         0,                              /* tp_getattr */
         0,                              /* tp_setattr */
         0,                              /* tp_as_async */
         (reprfunc)myobj_repr,           /* tp_repr */
         0,                              /* tp_as_number */
         0,                              /* tp_as_sequence */
         0,                              /* tp_as_mapping */
         0,                              /* tp_hash */
         0,                              /* tp_call */
         0,                              /* tp_str */
         0,                              /* tp_getattro */
         0,                              /* tp_setattro */
         0,                              /* tp_as_buffer */
         0,                              /* tp_flags */
         "My objects",                   /* tp_doc */
         0,                              /* tp_traverse */
         0,                              /* tp_clear */
         0,                              /* tp_richcompare */
         0,                              /* tp_weaklistoffset */
         0,                              /* tp_iter */
         0,                              /* tp_iternext */
         0,                              /* tp_methods */
         0,                              /* tp_members */
         0,                              /* tp_getset */
         0,                              /* tp_base */
         0,                              /* tp_dict */
         0,                              /* tp_descr_get */
         0,                              /* tp_descr_set */
         0,                              /* tp_dictoffset */
         0,                              /* tp_init */
         0,                              /* tp_alloc */
         myobj_new,                      /* tp_new */
     };

A type that supports weakrefs, instance dicts, and hashing:

     typedef struct {
         PyObject_HEAD
         const char *data;
         PyObject *inst_dict;
         PyObject *weakreflist;
     } MyObject;

     static PyTypeObject MyObject_Type = {
         PyVarObject_HEAD_INIT(NULL, 0)
         .tp_name = "mymod.MyObject",
         .tp_basicsize = sizeof(MyObject),
         .tp_doc = "My objects",
         .tp_weaklistoffset = offsetof(MyObject, weakreflist),
         .tp_dictoffset = offsetof(MyObject, inst_dict),
         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
         .tp_new = myobj_new,
         .tp_traverse = (traverseproc)myobj_traverse,
         .tp_clear = (inquiry)myobj_clear,
         .tp_alloc = PyType_GenericNew,
         .tp_dealloc = (destructor)myobj_dealloc,
         .tp_repr = (reprfunc)myobj_repr,
         .tp_hash = (hashfunc)myobj_hash,
         .tp_richcompare = PyBaseObject_Type.tp_richcompare,
     };

A str subclass that cannot be subclassed and cannot be called to create
instances (e.g.  uses a separate factory func):

     typedef struct {
         PyUnicodeObject raw;
         char *extra;
     } MyStr;

     static PyTypeObject MyStr_Type = {
         PyVarObject_HEAD_INIT(NULL, 0)
         .tp_name = "mymod.MyStr",
         .tp_basicsize = sizeof(MyStr),
         .tp_base = NULL,  // set to &PyUnicode_Type in module init
         .tp_doc = "my custom str",
         .tp_flags = Py_TPFLAGS_DEFAULT,
         .tp_new = NULL,
         .tp_repr = (reprfunc)myobj_repr,
     };

The simplest static type (with fixed-length instances):

     typedef struct {
         PyObject_HEAD
     } MyObject;

     static PyTypeObject MyObject_Type = {
         PyVarObject_HEAD_INIT(NULL, 0)
         .tp_name = "mymod.MyObject",
     };

The simplest static type (with variable-length instances):

     typedef struct {
         PyObject_VAR_HEAD
         const char *data[1];
     } MyObject;

     static PyTypeObject MyObject_Type = {
         PyVarObject_HEAD_INIT(NULL, 0)
         .tp_name = "mymod.MyObject",
         .tp_basicsize = sizeof(MyObject) - sizeof(char *),
         .tp_itemsize = sizeof(char *),
     };


File: python.info,  Node: 使对象类型支持循环垃圾回收,  Prev: 例子<35>,  Up: 对象实现支持

7.12.11 使对象类型支持循环垃圾回收
----------------------------------

Python 对循环引用的垃圾检测与回收需要“容器”对象类型的支持，此类型的容器
对象中可能包含其它容器对象。不保存其它对象的引用的类型，或者只保存原子类
型（如数字或字符串）的引用的类型，不需要显式提供垃圾回收的支持。

若要创建一个容器类，类型对象的 *note tp_flags: 3d64. 字段必须包含 *note
Py_TPFLAGS_HAVE_GC: 3b51. 并提供一个 *note tp_traverse: 36c7. 处理的实现
。如果该类型的实例是可变的，还需要实现 *note tp_clear: 3b5b. 。

 -- 数据: Py_TPFLAGS_HAVE_GC

     设置了此标志位的类型的对象必须符合此处记录的规则。为方便起见，下文
     把这些对象称为容器对象。

容器类型的构造函数必须符合两个规则：

  1. 必须使用 *note PyObject_GC_New(): 2d5. 或 *note
     PyObject_GC_NewVar(): 2d6. 为这些对象分配内存。

  2. 初始化了所有可能包含其他容器的引用的字段后，它必须调用 *note
     PyObject_GC_Track(): e4c. 。

 -- C 函数: TYPE* PyObject_GC_New (TYPE, PyTypeObject *type)

     类似于 *note PyObject_New(): 2d3. ，适用于设置了 *note
     Py_TPFLAGS_HAVE_GC: 3b51. 标签的容器对象。

 -- C 函数: TYPE* PyObject_GC_NewVar (TYPE, PyTypeObject *type,
          Py_ssize_t size)

     类似于 *note PyObject_NewVar(): 2d4. ，适用于设置了 *note
     Py_TPFLAGS_HAVE_GC: 3b51. 标签的容器对象。

 -- C 函数: TYPE* PyObject_GC_Resize (TYPE, PyVarObject *op,
          Py_ssize_t newsize)

     为 *note PyObject_NewVar(): 2d4. 所分配对象重新调整大小。 返回调整
     大小后的对象或在失败时返回 ‘NULL’。 `op' 必须尚未被垃圾回收器追踪。

 -- C 函数: void PyObject_GC_Track (PyObject *op)

     把对象 `op' 加入到垃圾回收器跟踪的容器对象中。对象在被回收器跟踪时
     必须保持有效的，因为回收器可能在任何时候开始运行。在 *note
     tp_traverse: 36c7. 处理前的所有字段变为有效后，必须调用此函数，通常
     在靠近构造函数末尾的位置。

同样的，对象的释放器必须符合两个类似的规则：

  1. 在引用其它容器的字段失效前，必须调用 *note PyObject_GC_UnTrack():
     e4d. 。

  2. 必须使用 *note PyObject_GC_Del(): e4b. 释放对象的内存。

 -- C 函数: void PyObject_GC_Del (void *op)

     释放对象的内存，该对象初始化时由 *note PyObject_GC_New(): 2d5. 或
     *note PyObject_GC_NewVar(): 2d6. 分配内存。

 -- C 函数: void PyObject_GC_UnTrack (void *op)

     从回收器跟踪的容器对象集合中移除 `op' 对象。 请注意可以在此对象上再
     次调用 *note PyObject_GC_Track(): e4c. 以将其加回到被跟踪对象集合。
     释放器 (*note tp_dealloc: 3b42. 句柄) 应当在 *note tp_traverse:
     36c7. 句柄所使用的任何字段失效之前为对象调用此函数。

在 3.8 版更改: ‘_PyObject_GC_TRACK()’ 和 ‘_PyObject_GC_UNTRACK()’ 宏已从
公有 C API 中移除。

*note tp_traverse: 36c7. 处理接收以下类型的函数形参。

 -- C 类型: int (*visitproc) (PyObject *object, void *arg)

     传给 *note tp_traverse: 36c7. 处理的访问函数的类型。`object' 是容器
     中需要被遍历的一个对象，第三个形参对应于 *note tp_traverse: 36c7. 处
     理的 `arg' 。Python核心使用多个访问者函数实现循环引用的垃圾检测，不
     需要用户自行实现访问者函数。

*note tp_traverse: 36c7. 处理必须是以下类型：

 -- C 类型: int (*traverseproc) (PyObject *self, visitproc visit,
          void *arg)

     用于容器对象的遍历函数。 它的实现必须对 `self' 所直接包含的每个对象
     调用 `visit' 函数，`visit' 的形参为所包含对象和传给处理程序的 `arg'
     值。 `visit' 函数调用不可附带 ‘NULL’ 对象作为参数。 如果 `visit' 返
     回非零值，则该值应当被立即返回。

为了简化 *note tp_traverse: 36c7. 处理的实现，Python提供了一个 *note
Py_VISIT(): 3b4f. 宏。若要使用这个宏，必须把 *note tp_traverse: 36c7. 的
参数命名为 `visit' 和 `arg' 。

 -- C 函数: void Py_VISIT (PyObject *o)

     如果 `o' 不为 ‘NULL’，则调用 `visit' 回调函数，附带参数 `o' 和
     `arg'。 如果 `visit' 返回一个非零值，则返回该值。 使用此宏之后，
     *note tp_traverse: 36c7. 处理程序的形式如下:

          static int
          my_traverse(Noddy *self, visitproc visit, void *arg)
          {
              Py_VISIT(self->foo);
              Py_VISIT(self->bar);
              return 0;
          }

*note tp_clear: 3b5b. 处理程序必须为 *note inquiry: 4068. 类型，如果对象
不可变则为 ‘NULL’。

 -- C 类型: int (*inquiry) (PyObject *self)

     丢弃产生循环引用的引用。不可变对象不需要声明此方法，因为他们不可能
     直接产生循环引用。需要注意的是，对象在调用此方法后必须仍是有效的（
     不能对引用只调用 *note Py_DECREF(): 267. 方法）。当垃圾回收器检测到
     该对象在循环引用中时，此方法会被调用。


File: python.info,  Node: API 和 ABI 版本管理,  Prev: 对象实现支持,  Up: Python/C API 参考手册

7.13 API 和 ABI 版本管理
========================

‘PY_VERSION_HEX’ 是Python的版本号的单一整数形式。

例如, 如果 "PY _ VERSION _ HEX" 设置为 "0x0304012", 则可以通过按以下方式
将其视为32位数字来查找基础版本信息:

     字节串      位数（大端字节序）            含义
                                               
     -----------------------------------------------------------------------------------------------
                                               
     ‘1’         ‘1-8’                         ‘PY_MAJOR_VERSION’ （‘3.4.1a2’ 中的 ‘3’ ）
                                               
                                               
     ‘2’         ‘9-16’                        ‘PY_MINOR_VERSION’ （‘3.4.1a2’ 中的 ‘4’ ）
                                               
                                               
     ‘3’         ‘17-24’                       ‘PY_MICRO_VERSION’ （‘3.4.1a2’ 中的 ‘1’ ）
                                               
                                               
     ‘4’         ‘25-28’                       ‘PY_RELEASE_LEVEL’ (‘0xA’ 是 alpha版本, ‘0xB’ 是
                                               beta版本, ‘0xC’ 发布的候选版本并且 ‘0xF’ 是最终版
                                               本)，在这个例子中这个版本是alpha版本。
                                               
                                               
                 ‘29-32’                       ‘PY_RELEASE_SERIAL’ （ ‘3.4.1a2’ 中的 ‘2’ ，最终版
                                               本用0)
                                               

因此 ‘3.4.1a2’ 的16进制版本号是 ‘0x030401a2’ 。

所有提到的宏都定义在 Include/patchlevel.h(1)。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Include/patchlevel.h


File: python.info,  Node: 分发 Python 模块,  Next: 安装 Python 模块,  Prev: Python/C API 参考手册,  Up: Top

8 分发 Python 模块
******************


电子邮箱: <distutils-sig@python.org>

作为一个流行的开源开发项目，Python拥有一个活跃的贡献者和用户支持社区，这
些社区也可以让他们的软件可供其他Python开发人员在开源许可条款下使用。

这允许Python用户有效地共享和协作，从其他人已经创建的解决方案中受益于常见
（有时甚至是罕见的）问题，以及可以提供他们自己的解决方案。

本指南涵盖了分发部分的流程。有关安装其他Python项目的指南，请参阅 *note
安装指南: 7fe.。

     注解: 对于企业和其他机构用户，请注意许多组织都有自己的政策来使用和
     贡献开源软件。在使用Python提供的分发和安装工具时，请考虑这些政策。

* Menu:

* 关键术语::
* 开源许可与协作::
* 安装相关工具::
* 阅读 Python 打包用户指南::
* 我该如何...？: 我该如何 ？.


File: python.info,  Node: 关键术语,  Next: 开源许可与协作,  Up: 分发 Python 模块

8.1 关键术语
============

   * Python Packaging Index(1) 是一个开源许可的软件包公共存储库，可供所
     有 Python 用户使用。

   * Python Packaging Authority(2) 是负责标准打包工具以及相关元数据和文
     件格式标准维护与改进的开发人员和文档作者团队。 他们基于 GitHub(3) 和
     Bitbucket(4) 这两个平台维护着各种工具、文档和问题追踪系统。

   * *note distutils: 39. 是 1998 年首次添加到 Python 标准库的原始构建和
     分发系统。 虽然直接使用 *note distutils: 39. 正在逐步淘汰，但它仍然
     为当前的打包和分发基础架构奠定了基础它不仅仍然是标准库的一部分，而
     且它的名称还以其他方式存在（例如用于协调 Python 打包标准开发的邮件
     列表的名称）。

   * setuptools(5) （在很大程度上）是作为 *note distutils: 39. 的取代者
     ，于 2004 年首次发布。 它对未经修改的 *note distutils: 39. 工具最重
     要的补充是能够声明对其他包的依赖。 目前它被推荐用来替代 *note
     distutils: 39.，其更新更为频繁，在更为多样的 Python 版本之上为最新
     的打包标准提供持续支持。

   * wheel(6) （在此上下文中）是一个将 ‘bdist_wheel’ 命令添加到 *note
     distutils: 39./setuptools(7) 的项目。这产生了一个跨平台的二进制打包
     格式（称为“轮子”或“轮子文件”，并在 PEP 427(8) 中定义），它允许在系
     统上安装Python库，甚至包括二进制扩展的库，而不需在本地进行构建。

   ---------- Footnotes ----------

   (1) https://pypi.org

   (2) https://www.pypa.io/

   (3) https://github.com/pypa

   (4) https://bitbucket.org/pypa/

   (5) https://setuptools.readthedocs.io/en/latest/

   (6) https://wheel.readthedocs.io/

   (7) https://setuptools.readthedocs.io/en/latest/

   (8) https://www.python.org/dev/peps/pep-0427


File: python.info,  Node: 开源许可与协作,  Next: 安装相关工具,  Prev: 关键术语,  Up: 分发 Python 模块

8.2 开源许可与协作
==================

在世界上大多数地方，软件自动受版权保护。这意味着其他开发人员需要明确的权
限来复制，使用，修改和重新分发软件。

开源许可是一种以相对一致的方式明确授予此类权限的方式，允许开发人员通过为
各种问题免费提供通用解决方案来有效地共享和协作。这使得许多开发人员可以将
更多时间用于关注他们特定情况相对独特的问题。

Python提供的分发工具旨在使开发人员选择开源时，可以合理地直接将其自己的贡
献回馈到该公共软件池。

无论该软件是否作为开源软件发布，相同的分发工具也可用于在组织内分发软件。


File: python.info,  Node: 安装相关工具,  Next: 阅读 Python 打包用户指南,  Prev: 开源许可与协作,  Up: 分发 Python 模块

8.3 安装相关工具
================

标准库不包括支持现代Python打包标准的构建工具，因为核心开发团队已经发现，
即使在旧版本的Python上，使用一致工作的标准工具也很重要。

可以通过在命令行调用 ‘pip’ 模块来安装当前推荐的构建和分发工具:

     python -m pip install setuptools wheel twine

     注解: 对于POSIX用户（包括Mac OS X和Linux用户），这些说明假定使用
     *note virtual environment: 1322. 。

     对于Windows用户，这些说明假定在安装Python时选择了调整系统PATH环境变
     量的选项。

Python 打包用户指南包含有关 当前推荐工具的(1) 的更多详细信息。

   ---------- Footnotes ----------

   (1) 
https://packaging.python.org/guides/tool-recommendations/#packaging-tool-recommendations


File: python.info,  Node: 阅读 Python 打包用户指南,  Next: 我该如何 ？,  Prev: 安装相关工具,  Up: 分发 Python 模块

8.4 阅读 Python 打包用户指南
============================

“Python 打包用户指南”介绍了创建和发布项目所涉及的各个关键步骤和元素：

   * 项目的结构(1)

   * 项目的构建与打包(2)

   * 上传项目到 Python Packaging Index(3)

   * The .pypirc file(4)

   ---------- Footnotes ----------

   (1) https://packaging.python.org/tutorials/distributing-packages/

   (2) 
https://packaging.python.org/tutorials/distributing-packages/#packaging-your-project

   (3) 
https://packaging.python.org/tutorials/distributing-packages/#uploading-your-project-to-pypi

   (4) https://packaging.python.org/specifications/pypirc/


File: python.info,  Node: 我该如何 ？,  Prev: 阅读 Python 打包用户指南,  Up: 分发 Python 模块

8.5 我该如何...？
=================

这是一些常见任务的快速解答或相关链接。

* Menu:

* ...为我的项目选择一个名字？: 为我的项目选择一个名字？.
* ...创建和分发二进制扩展？: 创建和分发二进制扩展？.


File: python.info,  Node: 为我的项目选择一个名字？,  Next: 创建和分发二进制扩展？,  Up: 我该如何 ？

8.5.1 ...为我的项目选择一个名字？
---------------------------------

这不是一个简单的主题，但这里有一些提示：

   * 检查Python Packaging Index以查看该名称是否已被使用

   * 检查流行的托管网站如 GitHub，Bitbucket 等等，看是否已有一个该名称的
     项目

   * 检查您正在考虑的名称在网络搜索中出现的内容

   * 避免使用特别常见的单词，尤其是具有多重含义的单词，因为它们会使用户
     在搜索时难以找到您的软件


File: python.info,  Node: 创建和分发二进制扩展？,  Prev: 为我的项目选择一个名字？,  Up: 我该如何 ？

8.5.2 ...创建和分发二进制扩展？
-------------------------------

这实际上是一个非常复杂的主题，根据您的目标，可以提供各种替代方案。 有关
更多信息和建议，请参阅 Python 打包用户指南。

参见
....

Python 打包用户指南：二进制扩展(1)

   ---------- Footnotes ----------

   (1) https://packaging.python.org/guides/packaging-binary-extensions/


File: python.info,  Node: 安装 Python 模块,  Next: Python 常用指引,  Prev: 分发 Python 模块,  Up: Top

9 安装 Python 模块
******************


电子邮箱: <distutils-sig@python.org>

作为一个流行的开源开发项目，Python拥有一个活跃的贡献者和用户支持社区，这
些社区也可以让他们的软件可供其他Python开发人员在开源许可条款下使用。

这允许Python用户有效地共享和协作，从其他人已经创建的解决方案中受益于常见
（有时甚至是罕见的）问题，以及可以提供他们自己的解决方案。

本指南涵盖了分发部分的流程。有关安装其他Python项目的指南，请参阅 *note
安装指南: 7ff.。

     注解: 对于企业和其他机构用户，请注意许多组织都有自己的政策来使用和
     贡献开源软件。在使用Python提供的分发和安装工具时，请考虑这些政策。

* Menu:

* 关键术语: 关键术语<2>.
* 基本使用: 基本使用<2>.
* 我应如何 ...？: 我应如何 ？.
* 常见的安装问题::


File: python.info,  Node: 关键术语<2>,  Next: 基本使用<2>,  Up: 安装 Python 模块

9.1 关键术语
============

   * ‘pip’ 是首选的安装程序。从Python 3.4开始，它默认包含在Python二进制
     安装程序中。

   * `virtual environment' 是一种半隔离的 Python 环境，允许为特定的应用
     安装各自的包，而不是安装到整个系统。

   * ‘venv’ 是创建虚拟环境的标准工具，从 Python 3.3 开始成为 Python 的组
     成部分。 从 Python 3.4 开始，它会默认安装 ‘pip’ 到所创建的全部虚拟
     环境。

   * ‘virtualenv’ 是 ‘venv’ 的第三方替代（及其前身）。 它允许在 Python
     3.4 之前的版本中使用虚拟环境，那些版本或是完全不提供 ‘venv’，或是不
     会自动安装 ‘pip’ 到所创建的虚拟环境。

   * Python Packaging Index(1) 是一个由 Python 用户向其他用户发布开源许
     可软件包的公共仓库。

   * Python Packaging Authority(2) 是负责标准打包工具以及相关元数据和文
     件格式标准维护与改进的开发人员和文档作者团队。 他们基于 GitHub(3) 和
     Bitbucket(4) 这两个平台维护着各种工具、文档和问题追踪系统。

   * ‘distutils’ 是最初的构建和分发系统，于 1998 年首次加入 Python 标准
     库。 虽然直接使用 ‘distutils’ 的方式已被淘汰，它仍然是当前打包和分
     发架构的基础，而且它不仅仍然是标准库的一部分，这个名称还以其他方式
     存在（例如用于协调 Python 打包标准开发流程的邮件列表就以此命名）。

在 3.5 版更改: 现在推荐使用 ‘venv’ 来创建虚拟环境。

参见
....

Python 软件包用户指南：创建和使用虚拟环境(5)

   ---------- Footnotes ----------

   (1) https://pypi.org

   (2) https://www.pypa.io/

   (3) https://github.com/pypa

   (4) https://bitbucket.org/pypa/

   (5) 
https://packaging.python.org/installing/#creating-virtual-environments


File: python.info,  Node: 基本使用<2>,  Next: 我应如何 ？,  Prev: 关键术语<2>,  Up: 安装 Python 模块

9.2 基本使用
============

标准打包工具完全是针对命令行使用方式来设计的。

以下命令将从 Python Packaging Index 安装一个模块的最新版本及其依赖项:

     python -m pip install SomePackage

     注解: 对于 POSIX 用户（包括 Mac OS X 和 Linux 用户）本指南中的示例
     假定使用了 *note virtual environment: 1322.。

     对于 Windows 用户，本指南中的示例假定在安装 Python 时选择了修改系统
     PATH 环境变量。

在命令行中指定一个准确或最小版本也是可以的。 当使用比较运算符例如 ‘>’,
‘<’ 或其他某些可以被终端所解析的特殊字符时，包名称与版本号应当用双引号括
起来:

     python -m pip install SomePackage==1.0.4    # specific version
     python -m pip install "SomePackage>=1.0.4"  # minimum version

通常，如果一个匹配的模块已安装，尝试再次安装将不会有任何效果。 要升级现
有模块必须显式地发出请求:

     python -m pip install --upgrade SomePackage

更多有关 ‘pip’ 及其功能的信息和资源可以在 Python 软件包用户指南(1) 中找
到。

虚拟环境的创建可使用 *note venv: 126. 模块来完成。 向已激活虚拟环境安装
软件包可使用上文所介绍的命令。

参见
....

Python 软件包用户指南：安装 Python 分发包(2)

   ---------- Footnotes ----------

   (1) https://packaging.python.org

   (2) https://packaging.python.org/installing/


File: python.info,  Node: 我应如何 ？,  Next: 常见的安装问题,  Prev: 基本使用<2>,  Up: 安装 Python 模块

9.3 我应如何 ...？
==================

这是一些常见任务的快速解答或相关链接。

* Menu:

* ... 在 Python 3.4 之前的 Python 版本中安装 pip ？: 在 Python 3 4 之前的 Python 版本中安装 pip ？.
* ... 只为当前用户安装软件包？: 只为当前用户安装软件包？.
* ... 安装科学计算类 Python 软件包？: 安装科学计算类 Python 软件包？.
* ... 使用并行安装的多个 Python 版本？: 使用并行安装的多个 Python 版本？.


File: python.info,  Node: 在 Python 3 4 之前的 Python 版本中安装 pip ？,  Next: 只为当前用户安装软件包？,  Up: 我应如何 ？

9.3.1 ... 在 Python 3.4 之前的 Python 版本中安装 ‘pip’ ？
---------------------------------------------------------

Python 捆绑 ‘pip’ 是从 Python 3.4 才开始的。 对于更早的版本，‘pip’ 需要
“引导安装”，具体说明参见 Python 软件包用户指南。

参见
....

Python 软件包用户指南：安装软件包的前提要求(1)

   ---------- Footnotes ----------

   (1) 
https://packaging.python.org/installing/#requirements-for-installing-packages


File: python.info,  Node: 只为当前用户安装软件包？,  Next: 安装科学计算类 Python 软件包？,  Prev: 在 Python 3 4 之前的 Python 版本中安装 pip ？,  Up: 我应如何 ？

9.3.2 ... 只为当前用户安装软件包？
----------------------------------

将 ‘--user’ 选项传入 ‘python -m pip install’ 将只为当前用户而非为系统中
的所有用户安装软件包。


File: python.info,  Node: 安装科学计算类 Python 软件包？,  Next: 使用并行安装的多个 Python 版本？,  Prev: 只为当前用户安装软件包？,  Up: 我应如何 ？

9.3.3 ... 安装科学计算类 Python 软件包？
----------------------------------------

许多科学计算类 Python 软件包都有复杂的二进制编译文件依赖，直接使用 ‘pip’
安装目前并不太容易。 在当前情况下，通过 其他方式(1) 而非尝试用 ‘pip’ 安
装这些软件包对用户来说通常会更容易。

参见
....

Python 软件包用户指南：安装科学计算类软件包(2)

   ---------- Footnotes ----------

   (1) https://packaging.python.org/science/

   (2) https://packaging.python.org/science/


File: python.info,  Node: 使用并行安装的多个 Python 版本？,  Prev: 安装科学计算类 Python 软件包？,  Up: 我应如何 ？

9.3.4 ... 使用并行安装的多个 Python 版本？
------------------------------------------

在 Linux, Mac OS X 以及其他 POSIX 系统中，使用带版本号的 Python 命令配合
‘-m’ 开关选项来运行特定版本的 ‘pip’:

     python2   -m pip install SomePackage  # default Python 2
     python2.7 -m pip install SomePackage  # specifically Python 2.7
     python3   -m pip install SomePackage  # default Python 3
     python3.4 -m pip install SomePackage  # specifically Python 3.4

也可以使用带特定版本号的 ‘pip’ 命令。

在 Windows 中，使用 ‘py’ Python 启动器命令配合 ‘-m’ 开关选项:

     py -2   -m pip install SomePackage  # default Python 2
     py -2.7 -m pip install SomePackage  # specifically Python 2.7
     py -3   -m pip install SomePackage  # default Python 3
     py -3.4 -m pip install SomePackage  # specifically Python 3.4


File: python.info,  Node: 常见的安装问题,  Prev: 我应如何 ？,  Up: 安装 Python 模块

9.4 常见的安装问题
==================

* Menu:

* 在 Linux 的系统 Python 版本上安装::
* 未安装 pip::
* 安装二进制编译扩展::


File: python.info,  Node: 在 Linux 的系统 Python 版本上安装,  Next: 未安装 pip,  Up: 常见的安装问题

9.4.1 在 Linux 的系统 Python 版本上安装
---------------------------------------

Linux 系统通常会将某个 Python 版本作为发行版的一部分包含在内。 将软件包
安装到这个 Python 版本上需要系统 root 权限，并可能会干扰到系统包管理器和
其他系统组件的运作，如果这些组件在使用 ‘pip’ 时被意外升级的话。

在这样的系统上，通过 ‘pip’ 安装软件包通常最好是使用虚拟环境或分用户安装
。


File: python.info,  Node: 未安装 pip,  Next: 安装二进制编译扩展,  Prev: 在 Linux 的系统 Python 版本上安装,  Up: 常见的安装问题

9.4.2 未安装 pip
----------------

默认情况下可能未安装 ‘pip’，一种可选解决方案是:

     python -m ensurepip --default-pip

还有其他资源可用来 安装 pip(1)

   ---------- Footnotes ----------

   (1) 
https://packaging.python.org/tutorials/installing-packages/#install-pip-setuptools-and-wheel


File: python.info,  Node: 安装二进制编译扩展,  Prev: 未安装 pip,  Up: 常见的安装问题

9.4.3 安装二进制编译扩展
------------------------

Python 通常非常依赖基于源代码的发布方式，也就是期望最终用户在安装过程中
使用源码来编译生成扩展模块。

随着对二进制码 ‘wheel’ 格式支持的引入，以及通过 Python Packaging Index 至
少发布 Windows 和 Mac OS X 版的 wheel 文件，预计此问题将逐步得到解决，因
为用户将能够更频繁地安装预编译扩展，而不再需要自己编译它们。

某些用来安装 科学计算类软件包(1) 的解决方案对于尚未提供预编译 ‘wheel’ 文
件的那些扩展模块来说，也有助于用户在无需进行本机编译的情况下获取二进制码
扩展模块。

参见
....

Python 软件包用户指南：二进制码扩展(2)

   ---------- Footnotes ----------

   (1) https://packaging.python.org/science/

   (2) https://packaging.python.org/extensions/


File: python.info,  Node: Python 常用指引,  Next: Python 常见问题,  Prev: 安装 Python 模块,  Up: Top

10 Python 常用指引
******************

Python常用指引的形式来源于Linux文档项目的常用指引章节，是一系列独立、指
定主题并尝试完全覆盖该主题的文章集合。致力于提供比Python库参考帮助更详尽
的文档。

目前，提供了如下指引：

* Menu:

* 将 Python 2 代码迁移到 Python 3::
* 将扩展模块移植到 Python 3::
* 用 Python 进行 Curses 编程::
* 描述器使用指南::
* 函数式编程指引::
* 日志常用指引::
* 日志操作手册::
* 正则表达式HOWTO::
* 套接字编程指南::
* 排序指南::
* Unicode 指南::
* HOWTO 使用 urllib 包获取网络资源::
* Argparse 教程::
* ipaddress模块介绍::
* Argument Clinic How-To::
* 使用 DTrace 和 SystemTap 检测CPython::


File: python.info,  Node: 将 Python 2 代码迁移到 Python 3,  Next: 将扩展模块移植到 Python 3,  Up: Python 常用指引

10.1 将 Python 2 代码迁移到 Python 3
====================================


作者: Brett Cannon

摘要
....

Python 3 是 Python 的未来，但 Python 2 仍处于活跃使用阶段，最好让您的项
目在两个主要版本的Python 上都可用。本指南旨在帮助您了解如何最好地同时支
持 Python 2 和 3。

如果您希望迁移扩展模块而不是纯 Python 代码，请参阅 *note 将扩展模块移植到
Python 3: c7f.。

如果你想了解核心 Python 开发者对于 Python 3 的出现有何看法，你可以阅读
Nick Coghlan 的 Python 3 Q & A(1) 或 Brett Cannon 的 为什么要有 Python
3(2).

有关迁移的帮助，您可以通过电子邮件向 python-porting(3) 邮件列表发送问题
。

* Menu:

* 简要说明::
* 详情::

   ---------- Footnotes ----------

   (1) 
https://ncoghlan-devs-python-notes.readthedocs.io/en/latest/python3/questions_and_answers.html

   (2) https://snarky.ca/why-python-3-exists

   (3) https://mail.python.org/mailman/listinfo/python-porting


File: python.info,  Node: 简要说明,  Next: 详情,  Up: 将 Python 2 代码迁移到 Python 3

10.1.1 简要说明
---------------

To make your project be single-source Python 2/3 compatible, the basic
steps are:

  1. Only worry about supporting Python 2.7

  2. 确保有良好的测试覆盖率（可以用 coverage.py(1) 来完成此任务；用 ‘pip
     install coverage’ 安装）

  3. 了解Python 2 和 3之间的区别

  4. 使用 Futurize(2) (或 Modernize(3)) 升级你的代码 (例如.  ‘pip
     install future’)

  5. Use Pylint(4) to help make sure you don’t regress on your Python 3
     support (‘pip install pylint’)

  6. Use caniusepython3(5) to find out which of your dependencies are
     blocking your use of Python 3 (‘pip install caniusepython3’)

  7. Once your dependencies are no longer blocking you, use continuous
     integration to make sure you stay compatible with Python 2 & 3
     (tox(6) can help test against multiple versions of Python; ‘pip
     install tox’)

  8. Consider using optional static type checking to make sure your type
     usage works in both Python 2 & 3 (e.g.  use mypy(7) to check your
     typing under both Python 2 & Python 3).

   ---------- Footnotes ----------

   (1) https://pypi.org/project/coverage

   (2) http://python-future.org/automatic_conversion.html

   (3) https://python-modernize.readthedocs.io/

   (4) https://pypi.org/project/pylint

   (5) https://pypi.org/project/caniusepython3

   (6) https://pypi.org/project/tox

   (7) http://mypy-lang.org/


File: python.info,  Node: 详情,  Prev: 简要说明,  Up: 将 Python 2 代码迁移到 Python 3

10.1.2 详情
-----------

A key point about supporting Python 2 & 3 simultaneously is that you can
start `today'!  Even if your dependencies are not supporting Python 3
yet that does not mean you can’t modernize your code `now' to support
Python 3.  Most changes required to support Python 3 lead to cleaner
code using newer practices even in Python 2 code.

Another key point is that modernizing your Python 2 code to also support
Python 3 is largely automated for you.  While you might have to make
some API decisions thanks to Python 3 clarifying text data versus binary
data, the lower-level work is now mostly done for you and thus can at
least benefit from the automated changes immediately.

Keep those key points in mind while you read on about the details of
porting your code to support Python 2 & 3 simultaneously.

* Menu:

* 删除对Python 2.6及更早版本的支持: 删除对Python 2 6及更早版本的支持.
* Make sure you specify the proper version support in your setup.py file: Make sure you specify the proper version support in your setup py file.
* 良好的测试覆盖率::
* 了解Python 2 和 3之间的区别::
* 更新代码::
* Prevent compatibility regressions::
* Check which dependencies block your transition::
* Update your setup.py file to denote Python 3 compatibility: Update your setup py file to denote Python 3 compatibility.
* Use continuous integration to stay compatible::
* 考虑使用可选的静态类型检查::


File: python.info,  Node: 删除对Python 2 6及更早版本的支持,  Next: Make sure you specify the proper version support in your setup py file,  Up: 详情

10.1.2.1 删除对Python 2.6及更早版本的支持
.........................................

While you can make Python 2.5 work with Python 3, it is `much' easier if
you only have to work with Python 2.7.  If dropping Python 2.5 is not an
option then the six(1) project can help you support Python 2.5 & 3
simultaneously (‘pip install six’).  Do realize, though, that nearly all
the projects listed in this HOWTO will not be available to you.

If you are able to skip Python 2.5 and older, then the required changes
to your code should continue to look and feel like idiomatic Python
code.  At worst you will have to use a function instead of a method in
some instances or have to import a function instead of using a built-in
one, but otherwise the overall transformation should not feel foreign to
you.

But you should aim for only supporting Python 2.7.  Python 2.6 is no
longer freely supported and thus is not receiving bugfixes.  This means
`you' will have to work around any issues you come across with Python
2.6.  There are also some tools mentioned in this HOWTO which do not
support Python 2.6 (e.g., Pylint(2)), and this will become more
commonplace as time goes on.  It will simply be easier for you if you
only support the versions of Python that you have to support.

   ---------- Footnotes ----------

   (1) https://pypi.org/project/six

   (2) https://pypi.org/project/pylint


File: python.info,  Node: Make sure you specify the proper version support in your setup py file,  Next: 良好的测试覆盖率,  Prev: 删除对Python 2 6及更早版本的支持,  Up: 详情

10.1.2.2 Make sure you specify the proper version support in your ‘setup.py’ file
.................................................................................

In your ‘setup.py’ file you should have the proper trove classifier(1)
specifying what versions of Python you support.  As your project does
not support Python 3 yet you should at least have ‘Programming Language
:: Python :: 2 :: Only’ specified.  Ideally you should also specify each
major/minor version of Python that you do support, e.g.  ‘Programming
Language :: Python :: 2.7’.

   ---------- Footnotes ----------

   (1) https://pypi.org/classifiers


File: python.info,  Node: 良好的测试覆盖率,  Next: 了解Python 2 和 3之间的区别,  Prev: Make sure you specify the proper version support in your setup py file,  Up: 详情

10.1.2.3 良好的测试覆盖率
.........................

Once you have your code supporting the oldest version of Python 2 you
want it to, you will want to make sure your test suite has good
coverage.  A good rule of thumb is that if you want to be confident
enough in your test suite that any failures that appear after having
tools rewrite your code are actual bugs in the tools and not in your
code.  If you want a number to aim for, try to get over 80% coverage
(and don’t feel bad if you find it hard to get better than 90%
coverage).  If you don’t already have a tool to measure test coverage
then coverage.py(1) is recommended.

   ---------- Footnotes ----------

   (1) https://pypi.org/project/coverage


File: python.info,  Node: 了解Python 2 和 3之间的区别,  Next: 更新代码,  Prev: 良好的测试覆盖率,  Up: 详情

10.1.2.4 了解Python 2 和 3之间的区别
....................................

Once you have your code well-tested you are ready to begin porting your
code to Python 3!  But to fully understand how your code is going to
change and what you want to look out for while you code, you will want
to learn what changes Python 3 makes in terms of Python 2.  Typically
the two best ways of doing that is reading the *note "What’s New": 14a.
doc for each release of Python 3 and the Porting to Python 3(1) book
(which is free online).  There is also a handy cheat sheet(2) from the
Python-Future project.

   ---------- Footnotes ----------

   (1) http://python3porting.com/

   (2) http://python-future.org/compatible_idioms.html


File: python.info,  Node: 更新代码,  Next: Prevent compatibility regressions,  Prev: 了解Python 2 和 3之间的区别,  Up: 详情

10.1.2.5 更新代码
.................

Once you feel like you know what is different in Python 3 compared to
Python 2, it’s time to update your code!  You have a choice between two
tools in porting your code automatically: Futurize(1) and Modernize(2).
Which tool you choose will depend on how much like Python 3 you want
your code to be.  Futurize(3) does its best to make Python 3 idioms and
practices exist in Python 2, e.g.  backporting the ‘bytes’ type from
Python 3 so that you have semantic parity between the major versions of
Python.  Modernize(4), on the other hand, is more conservative and
targets a Python 2/3 subset of Python, directly relying on six(5) to
help provide compatibility.  As Python 3 is the future, it might be best
to consider Futurize to begin adjusting to any new practices that Python
3 introduces which you are not accustomed to yet.

Regardless of which tool you choose, they will update your code to run
under Python 3 while staying compatible with the version of Python 2 you
started with.  Depending on how conservative you want to be, you may
want to run the tool over your test suite first and visually inspect the
diff to make sure the transformation is accurate.  After you have
transformed your test suite and verified that all the tests still pass
as expected, then you can transform your application code knowing that
any tests which fail is a translation failure.

Unfortunately the tools can’t automate everything to make your code work
under Python 3 and so there are a handful of things you will need to
update manually to get full Python 3 support (which of these steps are
necessary vary between the tools).  Read the documentation for the tool
you choose to use to see what it fixes by default and what it can do
optionally to know what will (not) be fixed for you and what you may
have to fix on your own (e.g.  using ‘io.open()’ over the built-in
‘open()’ function is off by default in Modernize).  Luckily, though,
there are only a couple of things to watch out for which can be
considered large issues that may be hard to debug if not watched for.

* Menu:

* 除法::
* 文本与二进制数据::
* Use feature detection instead of version detection::

   ---------- Footnotes ----------

   (1) http://python-future.org/automatic_conversion.html

   (2) https://python-modernize.readthedocs.io/

   (3) http://python-future.org/automatic_conversion.html

   (4) https://python-modernize.readthedocs.io/

   (5) https://pypi.org/project/six


File: python.info,  Node: 除法,  Next: 文本与二进制数据,  Up: 更新代码

10.1.2.6 除法
.............

In Python 3, ‘5 / 2 == 2.5’ and not ‘2’; all division between ‘int’
values result in a ‘float’.  This change has actually been planned since
Python 2.2 which was released in 2002.  Since then users have been
encouraged to add ‘from __future__ import division’ to any and all files
which use the ‘/’ and ‘//’ operators or to be running the interpreter
with the ‘-Q’ flag.  If you have not been doing this then you will need
to go through your code and do two things:

  1. Add ‘from __future__ import division’ to your files

  2. Update any division operator as necessary to either use ‘//’ to use
     floor division or continue using ‘/’ and expect a float

The reason that ‘/’ isn’t simply translated to ‘//’ automatically is
that if an object defines a ‘__truediv__’ method but not ‘__floordiv__’
then your code would begin to fail (e.g.  a user-defined class that uses
‘/’ to signify some operation but not ‘//’ for the same thing or at
all).


File: python.info,  Node: 文本与二进制数据,  Next: Use feature detection instead of version detection,  Prev: 除法,  Up: 更新代码

10.1.2.7 文本与二进制数据
.........................

In Python 2 you could use the ‘str’ type for both text and binary data.
Unfortunately this confluence of two different concepts could lead to
brittle code which sometimes worked for either kind of data, sometimes
not.  It also could lead to confusing APIs if people didn’t explicitly
state that something that accepted ‘str’ accepted either text or binary
data instead of one specific type.  This complicated the situation
especially for anyone supporting multiple languages as APIs wouldn’t
bother explicitly supporting ‘unicode’ when they claimed text data
support.

To make the distinction between text and binary data clearer and more
pronounced, Python 3 did what most languages created in the age of the
internet have done and made text and binary data distinct types that
cannot blindly be mixed together (Python predates widespread access to
the internet).  For any code that deals only with text or only binary
data, this separation doesn’t pose an issue.  But for code that has to
deal with both, it does mean you might have to now care about when you
are using text compared to binary data, which is why this cannot be
entirely automated.

To start, you will need to decide which APIs take text and which take
binary (it is `highly' recommended you don’t design APIs that can take
both due to the difficulty of keeping the code working; as stated
earlier it is difficult to do well).  In Python 2 this means making sure
the APIs that take text can work with ‘unicode’ and those that work with
binary data work with the ‘bytes’ type from Python 3 (which is a subset
of ‘str’ in Python 2 and acts as an alias for ‘bytes’ type in Python 2).
Usually the biggest issue is realizing which methods exist on which
types in Python 2 & 3 simultaneously (for text that’s ‘unicode’ in
Python 2 and ‘str’ in Python 3, for binary that’s ‘str’/‘bytes’ in
Python 2 and ‘bytes’ in Python 3).  The following table lists the
`unique' methods of each data type across Python 2 & 3 (e.g., the
‘decode()’ method is usable on the equivalent binary data type in either
Python 2 or 3, but it can’t be used by the textual data type
consistently between Python 2 and 3 because ‘str’ in Python 3 doesn’t
have the method).  Do note that as of Python 3.5 the ‘__mod__’ method
was added to the bytes type.

`文本数据'                   `二进制数据'
                             
                             
                             decode
                             
                             
encode

format

isdecimal

isnumeric

Making the distinction easier to handle can be accomplished by encoding
and decoding between binary data and text at the edge of your code.
This means that when you receive text in binary data, you should
immediately decode it.  And if your code needs to send text as binary
data then encode it as late as possible.  This allows your code to work
with only text internally and thus eliminates having to keep track of
what type of data you are working with.

The next issue is making sure you know whether the string literals in
your code represent text or binary data.  You should add a ‘b’ prefix to
any literal that presents binary data.  For text you should add a ‘u’
prefix to the text literal.  (there is a *note __future__: 0. import to
force all unspecified literals to be Unicode, but usage has shown it
isn’t as effective as adding a ‘b’ or ‘u’ prefix to all literals
explicitly)

As part of this dichotomy you also need to be careful about opening
files.  Unless you have been working on Windows, there is a chance you
have not always bothered to add the ‘b’ mode when opening a binary file
(e.g., ‘rb’ for binary reading).  Under Python 3, binary files and text
files are clearly distinct and mutually incompatible; see the *note io:
a2. module for details.  Therefore, you `must' make a decision of
whether a file will be used for binary access (allowing binary data to
be read and/or written) or textual access (allowing text data to be read
and/or written).  You should also use *note io.open(): 663. for opening
files instead of the built-in *note open(): 4f8. function as the *note
io: a2. module is consistent from Python 2 to 3 while the built-in *note
open(): 4f8. function is not (in Python 3 it’s actually *note io.open():
663.).  Do not bother with the outdated practice of using *note
codecs.open(): 1372. as that’s only necessary for keeping compatibility
with Python 2.5.

The constructors of both ‘str’ and ‘bytes’ have different semantics for
the same arguments between Python 2 & 3.  Passing an integer to ‘bytes’
in Python 2 will give you the string representation of the integer:
‘bytes(3) == '3'’.  But in Python 3, an integer argument to ‘bytes’ will
give you a bytes object as long as the integer specified, filled with
null bytes: ‘bytes(3) == b'\x00\x00\x00'’.  A similar worry is necessary
when passing a bytes object to ‘str’.  In Python 2 you just get the
bytes object back: ‘str(b'3') == b'3'’.  But in Python 3 you get the
string representation of the bytes object: ‘str(b'3') == "b'3'"’.

Finally, the indexing of binary data requires careful handling (slicing
does `not' require any special handling).  In Python 2, ‘b'123'[1] ==
b'2'’ while in Python 3 ‘b'123'[1] == 50’.  Because binary data is
simply a collection of binary numbers, Python 3 returns the integer
value for the byte you index on.  But in Python 2 because ‘bytes ==
str’, indexing returns a one-item slice of bytes.  The six(1) project
has a function named ‘six.indexbytes()’ which will return an integer
like in Python 3: ‘six.indexbytes(b'123', 1)’.

To summarize:

  1. Decide which of your APIs take text and which take binary data

  2. Make sure that your code that works with text also works with
     ‘unicode’ and code for binary data works with ‘bytes’ in Python 2
     (see the table above for what methods you cannot use for each type)

  3. Mark all binary literals with a ‘b’ prefix, textual literals with a
     ‘u’ prefix

  4. Decode binary data to text as soon as possible, encode text as
     binary data as late as possible

  5. Open files using *note io.open(): 663. and make sure to specify the
     ‘b’ mode when appropriate

  6. Be careful when indexing into binary data

   ---------- Footnotes ----------

   (1) https://pypi.org/project/six


File: python.info,  Node: Use feature detection instead of version detection,  Prev: 文本与二进制数据,  Up: 更新代码

10.1.2.8 Use feature detection instead of version detection
...........................................................

Inevitably you will have code that has to choose what to do based on
what version of Python is running.  The best way to do this is with
feature detection of whether the version of Python you’re running under
supports what you need.  If for some reason that doesn’t work then you
should make the version check be against Python 2 and not Python 3.  To
help explain this, let’s look at an example.

Let’s pretend that you need access to a feature of *note importlib: 9b.
that is available in Python’s standard library since Python 3.3 and
available for Python 2 through importlib2(1) on PyPI. You might be
tempted to write code to access e.g.  the *note importlib.abc: 9c.
module by doing the following:

     import sys

     if sys.version_info[0] == 3:
         from importlib import abc
     else:
         from importlib2 import abc

The problem with this code is what happens when Python 4 comes out?  It
would be better to treat Python 2 as the exceptional case instead of
Python 3 and assume that future Python versions will be more compatible
with Python 3 than Python 2:

     import sys

     if sys.version_info[0] > 2:
         from importlib import abc
     else:
         from importlib2 import abc

The best solution, though, is to do no version detection at all and
instead rely on feature detection.  That avoids any potential issues of
getting the version detection wrong and helps keep you
future-compatible:

     try:
         from importlib import abc
     except ImportError:
         from importlib2 import abc

   ---------- Footnotes ----------

   (1) https://pypi.org/project/importlib2


File: python.info,  Node: Prevent compatibility regressions,  Next: Check which dependencies block your transition,  Prev: 更新代码,  Up: 详情

10.1.2.9 Prevent compatibility regressions
..........................................

Once you have fully translated your code to be compatible with Python 3,
you will want to make sure your code doesn’t regress and stop working
under Python 3.  This is especially true if you have a dependency which
is blocking you from actually running under Python 3 at the moment.

To help with staying compatible, any new modules you create should have
at least the following block of code at the top of it:

     from __future__ import absolute_import
     from __future__ import division
     from __future__ import print_function

You can also run Python 2 with the ‘-3’ flag to be warned about various
compatibility issues your code triggers during execution.  If you turn
warnings into errors with ‘-Werror’ then you can make sure that you
don’t accidentally miss a warning.

You can also use the Pylint(1) project and its ‘--py3k’ flag to lint
your code to receive warnings when your code begins to deviate from
Python 3 compatibility.  This also prevents you from having to run
Modernize(2) or Futurize(3) over your code regularly to catch
compatibility regressions.  This does require you only support Python
2.7 and Python 3.4 or newer as that is Pylint’s minimum Python version
support.

   ---------- Footnotes ----------

   (1) https://pypi.org/project/pylint

   (2) https://python-modernize.readthedocs.io/

   (3) http://python-future.org/automatic_conversion.html


File: python.info,  Node: Check which dependencies block your transition,  Next: Update your setup py file to denote Python 3 compatibility,  Prev: Prevent compatibility regressions,  Up: 详情

10.1.2.10 Check which dependencies block your transition
........................................................

`After' you have made your code compatible with Python 3 you should
begin to care about whether your dependencies have also been ported.
The caniusepython3(1) project was created to help you determine which
projects – directly or indirectly – are blocking you from supporting
Python 3.  There is both a command-line tool as well as a web interface
at ‘https://caniusepython3.com’.

The project also provides code which you can integrate into your test
suite so that you will have a failing test when you no longer have
dependencies blocking you from using Python 3.  This allows you to avoid
having to manually check your dependencies and to be notified quickly
when you can start running on Python 3.

   ---------- Footnotes ----------

   (1) https://pypi.org/project/caniusepython3


File: python.info,  Node: Update your setup py file to denote Python 3 compatibility,  Next: Use continuous integration to stay compatible,  Prev: Check which dependencies block your transition,  Up: 详情

10.1.2.11 Update your ‘setup.py’ file to denote Python 3 compatibility
......................................................................

Once your code works under Python 3, you should update the classifiers
in your ‘setup.py’ to contain ‘Programming Language :: Python :: 3’ and
to not specify sole Python 2 support.  This will tell anyone using your
code that you support Python 2 `and' 3.  Ideally you will also want to
add classifiers for each major/minor version of Python you now support.


File: python.info,  Node: Use continuous integration to stay compatible,  Next: 考虑使用可选的静态类型检查,  Prev: Update your setup py file to denote Python 3 compatibility,  Up: 详情

10.1.2.12 Use continuous integration to stay compatible
.......................................................

Once you are able to fully run under Python 3 you will want to make sure
your code always works under both Python 2 & 3.  Probably the best tool
for running your tests under multiple Python interpreters is tox(1).
You can then integrate tox with your continuous integration system so
that you never accidentally break Python 2 or 3 support.

You may also want to use the ‘-bb’ flag with the Python 3 interpreter to
trigger an exception when you are comparing bytes to strings or bytes to
an int (the latter is available starting in Python 3.5).  By default
type-differing comparisons simply return ‘False’, but if you made a
mistake in your separation of text/binary data handling or indexing on
bytes you wouldn’t easily find the mistake.  This flag will raise an
exception when these kinds of comparisons occur, making the mistake much
easier to track down.

And that’s mostly it!  At this point your code base is compatible with
both Python 2 and 3 simultaneously.  Your testing will also be set up so
that you don’t accidentally break Python 2 or 3 compatibility regardless
of which version you typically run your tests under while developing.

   ---------- Footnotes ----------

   (1) https://pypi.org/project/tox


File: python.info,  Node: 考虑使用可选的静态类型检查,  Prev: Use continuous integration to stay compatible,  Up: 详情

10.1.2.13 考虑使用可选的静态类型检查
....................................

Another way to help port your code is to use a static type checker like
mypy(1) or pytype(2) on your code.  These tools can be used to analyze
your code as if it’s being run under Python 2, then you can run the tool
a second time as if your code is running under Python 3.  By running a
static type checker twice like this you can discover if you’re e.g.
misusing binary data type in one version of Python compared to another.
If you add optional type hints to your code you can also explicitly
state whether your APIs use textual or binary data, helping to make sure
everything functions as expected in both versions of Python.

   ---------- Footnotes ----------

   (1) http://mypy-lang.org/

   (2) https://github.com/google/pytype


File: python.info,  Node: 将扩展模块移植到 Python 3,  Next: 用 Python 进行 Curses 编程,  Prev: 将 Python 2 代码迁移到 Python 3,  Up: Python 常用指引

10.2 将扩展模块移植到 Python 3
==============================

对于将扩展模块移植到 Python 3，我们推荐下列资源：

   * `Supporting Python 3: An in-depth guide' 中的 Migrating C
     extensions(1) 这一章，这本书介绍了如何从 Python 2 迁移到 Python 3，
     包括指导读者如何移植扩展模块。

   * `py3c' 项目中的 Porting guide(2) 提供了有关支持代码的指导性建议。

   * Cython(3) 和 CFFI(4) 库提供了对于 Python 的 C API 的抽象。 扩展大都
     需要进行重写以使用两者中的一个，然后就可以通过库来处理各种 Python 版
     本和实现之间的差异。

   ---------- Footnotes ----------

   (1) http://python3porting.com/cextensions.html

   (2) https://py3c.readthedocs.io/en/latest/guide.html

   (3) http://cython.org/

   (4) https://cffi.readthedocs.io/en/latest/


File: python.info,  Node: 用 Python 进行 Curses 编程,  Next: 描述器使用指南,  Prev: 将扩展模块移植到 Python 3,  Up: Python 常用指引

10.3 用 Python 进行 Curses 编程
===============================


作者: A.M. Kuchling, Eric S. Raymond


发布版本: 2.04

摘要
....

本文档介绍了如何使用 *note curses: 2c. 扩展模块控制文本模式的显示。

* Menu:

* curses 是什么？::
* 开始和结束curses应用程序::
* 窗口和面板::
* 显示文字::
* 用户输入::
* 更多的信息::


File: python.info,  Node: curses 是什么？,  Next: 开始和结束curses应用程序,  Up: 用 Python 进行 Curses 编程

10.3.1 curses 是什么？
----------------------

curses 库为基于文本的终端提供了独立于终端的屏幕绘制和键盘处理功能；这些
终端包括 VT100，Linux 控制台以及各种程序提供的模拟终端。显示终端支持各种
控制代码以执行常见的操作，例如移动光标，滚动屏幕和擦除区域。不同的终端使
用相差很大的代码，并且往往有自己的小怪癖。

在普遍使用图形显示的世界中，人们可能会问“为什么自找要麻烦”？毕竟字符单元
显示终端确实是一种过时的技术，但是在某些领域中，能够用它们做花哨的事情仍
然很有价值。一个小众市场是在不运行 X server 的小型或嵌入式 Unix 上。另一
个是在提供图形支持之前，可能需要运行的工具，例如操作系统安装程序和内核配
置程序。

curses 库提供了相当基础的功能，为程序员提供了包含多个非重叠文本窗口的显
示的抽象。窗口的内容可以通过多种方式更改—添加文本，擦除文本，更改其外观
—以及curses库将确定需要向终端发送哪些控制代码以产生正确的输出。 curses并
没有提供诸多用户界面概念，例如按钮，复选框或对话框。如果需要这些功能，请
考虑用户界面库，例如 Urwid(1) 。

curses 库最初是为BSD Unix 编写的。 后来 AT&T 的Unix System V 版本加入了
许多增强功能和新功能。如今BSD curses已不再维护，被ncurses取代，ncurses是
AT&T 接口的开源实现。如果使用的是 Linux 或 FreeBSD 等开源Unix系统，则几
乎肯定会使用ncurses。由于大多数当前的商业Unix版本都基于System V代码，因
此这里描述的所有功能可能都可用。但是，某些专有Unix所带来的较早版本的
curses可能无法支持所有功能。

Windows 版本的 Python 不包含 *note curses: 2c. 模块。提供了一个名为
UniCurses(2) 的移植版本。也可以尝试使用 Fredrik Lundh 编写 the Console
module(3)，它使用了与curses不相同的API，但提供了可光标定位的文本输出，完
全支持鼠标和键盘输入。

* Menu:

* Python 的 curses 模块::

   ---------- Footnotes ----------

   (1) https://pypi.org/project/urwid/

   (2) https://pypi.org/project/UniCurses

   (3) http://effbot.org/zone/console-index.htm


File: python.info,  Node: Python 的 curses 模块,  Up: curses 是什么？

10.3.1.1 Python 的 curses 模块
..............................

此 Python 模块相当简单地封装了 curses 提供的 C 函数；如果你已经熟悉在 C
语言中使用 curses 编程，把这些知识转移的 Python 是非常容易的。最大的差异
在于 Python 中的接口通过把不同的 C 函数合并来让事情变得更简单，比如
‘addstr()’、‘mvaddstr()’ 和 ‘mvwaddstr()’ 三个 C 函数被并入 *note
addstr(): 2173. 这一个方法。下文中会描述更多的细节。

本 HOWTO 是关于使用 curses 和 Python 编写文本模式程序的概述。它并不被设
计为一个 curses API 的完整指南；如需完整指南，请参见 ncurses 的 Python 库
指南章节和 ncurses 的 C 手册页。相对地，本 HOWTO 将会给你一些基本思路。


File: python.info,  Node: 开始和结束curses应用程序,  Next: 窗口和面板,  Prev: curses 是什么？,  Up: 用 Python 进行 Curses 编程

10.3.2 开始和结束curses应用程序
-------------------------------

在做任何事情之前，curses 必须先被初始化。可以通过调用函数 *note
initscr(): 217a. 来实现，它将查明终端的类型，向终端发送任何必须的设置代
码，并创建多种内部数据结构。如果此操作成功，‘initscr()’ 将会返回一个代表
整个屏幕的窗口对象；它通常会遵循对应的 C 变量名被称作 ‘stdscr’：

     import curses
     stdscr = curses.initscr()

使用 curses 的应用程序通常会关闭按键自动上屏，目的是读取按键并只在特定情
况下展示它们。这需要调用函数 *note noecho(): 2199.：

     curses.noecho()

应用程序也会广泛地需要立即响应按键，而不需要按下回车键；这被称为
“cbreak” 模式，与通常的缓冲输入模式相对：

     curses.cbreak()

终端通常会以多字节转义序列的形式返回特殊按键，比如光标键和导航键比如
Page Up 键和 Home 键。尽管你可以编写你的程序来应对这些序列，curses 能够
代替你做到这件事，返回一个特殊值比如 ‘curses.KEY_LEFT’。为了让 curses 做
这项工作，你需要启用 keypad 模式：

     stdscr.keypad(True)

终止一个 curses 应用程序比建立一个容易得多，你只需要调用：

     curses.nocbreak()
     stdscr.keypad(False)
     curses.echo()

来还原对终端作出的 curses 友好设置。然后，调用函数 *note endwin(): 2177.
来将终端还原到它的原始操作模式：

     curses.endwin()

调试一个 curses 应用程序时常会发生，一个应用程序还未能还原终端到原本的状
态就意外退出了，这会搅乱你的终端。在 Python 中这常常会发生在你的代码中有
bug 并引发了一个未捕获的异常。当你尝试输入时按键不会上屏，这使得使用终端
变得困难。

在 Python 中你可以避免这些复杂问题并让调试变得更简单，只需要导入 *note
curses.wrapper(): 2a2. 函数并像这样使用它：

     from curses import wrapper

     def main(stdscr):
         # Clear screen
         stdscr.clear()

         # This raises ZeroDivisionError when i == 10.
         for i in range(0, 11):
             v = i-10
             stdscr.addstr(i, 0, '10 divided by {} is {}'.format(v, 10/v))

         stdscr.refresh()
         stdscr.getkey()

     wrapper(main)

函数 *note wrapper(): 2a2. 接受一个可调用对象并首先进行上述初始化过程，
在终端支持着色时还会初始化颜色。接着 ‘wrapper()’ 运行你提供的可调用对象
。当该可调用对象返回时，‘wrapper()’ 会还原终端到初始状态。该可调用对象会
在 *note try: d7a...*note except: b46. 这样的结构内被调用，当它捕获到异
常时，会先还原终端再重新引发这个异常。所以你的终端不会因为异常而被留在一
个搞笑的状态，你也可以正常阅读异常消息和回溯信息。


File: python.info,  Node: 窗口和面板,  Next: 显示文字,  Prev: 开始和结束curses应用程序,  Up: 用 Python 进行 Curses 编程

10.3.3 窗口和面板
-----------------

窗口是 curses 中的基本抽象。一个窗口对象表示了屏幕上的一个矩形区域，并且
提供方法来显示文本、擦除文本、允许用户输入字符串等等。

函数 *note initscr(): 217a. 返回的 ‘stdscr’ 对象覆盖整个屏幕。许多程序可
能只需要这一个窗口，但你可能希望把屏幕分割为多个更小的窗口，来分别重绘或
者清除它们。函数 *note newwin(): 2197. 根据给定的尺寸创建一个新窗口，并
返回这个新的窗口对象：

     begin_x = 20; begin_y = 7
     height = 5; width = 40
     win = curses.newwin(height, width, begin_y, begin_x)

注意 curses 使用的坐标系统与寻常的不同。坐标始终是以 `y,x' 的顺序传递，
并且左上角是坐标 (0,0)。这打破了正常的坐标处理约定，即 `x' 坐标在前。这
是一个与其他计算机应用程序糟糕的差异，但这从 curses 最初被编写出来就已是
它的一部分，现在想要修改它已为时已晚。

你的应用程序能够查明屏幕的尺寸，‘curses.LINES’ 和 ‘curses.COLS’ 分别代表
了 `y' 和 `x' 方向上的尺寸。合理的坐标应位于 ‘(0,0)’ 到 ‘(curses.LINES -
1, curses.COLS - 1)’ 范围内。

当你调用一个方法来显示或擦除文本时，效果并不会立即显示。相反，你必须调用
窗口对象的 *note refresh(): 2175. 方法来更新屏幕。

这是因为 curses 最初是为 300 波特的龟速终端连接编写的；在这些终端上，压
制重绘屏幕的时间就非常重要。相对地，当你调用 ‘refresh()’ 时，curses 会累
积屏幕的修改并以效率最高的方式显示它们。打个比方，如果你的程序在一个窗口
内显示一些文本然后清楚了这个窗口，那么这些原始文本不需要被发送，因为它们
甚至不曾能被看见。

在实践中，显式地告诉 curses 来重绘一个窗口并不会太复杂化 curses 编程。大
部分程序会显示一堆内容然后等待按键或者其他某些用户侧动作。你要做的事情就
是，保证屏幕在暂停并等待用户输入前被重绘，只需要先调用
‘stdscr.refresh()’ 或者其他相关窗口的 ‘refresh()’ 方法。

一个面板是一种特殊的窗口，它可以比实际的显示屏幕更大，并且能只显示它的一
部分。创建面板需要指定面板的高度和宽度，但刷新一个面板需要给出屏幕坐标和
面板的需要显示的局部。

     pad = curses.newpad(100, 100)
     # These loops fill the pad with letters; addch() is
     # explained in the next section
     for y in range(0, 99):
         for x in range(0, 99):
             pad.addch(y,x, ord('a') + (x*x+y*y) % 26)

     # Displays a section of the pad in the middle of the screen.
     # (0,0) : coordinate of upper-left corner of pad area to display.
     # (5,5) : coordinate of upper-left corner of window area to be filled
     #         with pad content.
     # (20, 75) : coordinate of lower-right corner of window area to be
     #          : filled with pad content.
     pad.refresh( 0,0, 5,5, 20,75)

此 ‘refresh()’ 调用会在屏幕坐标 (5,5) 到坐标 (20,75) 的矩形范围内显示面
板的一个部分，被显示的部分在面板上的坐标是 (0,0)。除了上述差异，面板与常
规的窗口相同，也支持相同的方法。

如果你在屏幕上有多个窗口和面板，有一个更有效率的方法来更新窗口，避免每个
部分单独更新时烦人的屏幕闪烁。‘refresh()’ 实际上做了两件事：

  1. 调用每个窗口的 *note noutrefresh(): 2174. 方法来更新一个表达屏幕期
     望状态的底层的数据结构。

  2. 调用函数 *note doupdate(): 2172. 来改变物理屏幕来符合这个数据结构中
     记录的期望状态。

你可以改为调用在多个窗口上 ‘noutrefresh()’ 方法来更新该数据结构，然后调
用函数 ‘doupdate()’ 来更新屏幕。


File: python.info,  Node: 显示文字,  Next: 用户输入,  Prev: 窗口和面板,  Up: 用 Python 进行 Curses 编程

10.3.4 显示文字
---------------

从一名 C 语言程序员的视角来看，curses 有时看起来就像是一堆略有差异的函数
组成的扭曲迷宫。举个例子，‘addstr()’ 在 ‘stdscr’ 窗口的当前光标位置显示
一个字符串，而 ‘mvaddstr()’ 则是先移动到一个给定的 y,x 坐标再显示字符串
。‘waddstr()’ 与 ‘addstr()’ 类似，但允许指定一个窗口而非默认的 ‘stdscr’。
‘mvwaddstr()’ 允许同时指定一个窗口和一个坐标。

幸运的是，Python 接口隐藏了所有这些细节。‘stdscr’ 和其他任何窗口一样是一
个窗口对象，并且诸如 *note addstr(): 2173. 之类的方法接受多种参数形式。
通常有四种形式。

形式                                  描述
                                      
------------------------------------------------------------------------------------------
                                      
`str' 或 `ch'                         在当前位置显示字符串 `str' 或字符 `ch'
                                      
                                      
`str' 或 `ch', `attr'                 在当前位置使用 `attr' 属性显示字符串 `str' 或字符
                                      `ch'
                                      
                                      
`y', `x', `str' 或 `ch'               移动到窗口内的 `y,x' 位置，并显示 `str' 或 `ch'
                                      
                                      
`y', `x', `str' 或 `ch', `attr'       移至窗口内的 `y,x' 位置，并使用 `attr' 属性显示
                                      `str' 或 `ch'
                                      

属性允许以突出显示形态显示文本，比如加粗、下划线、反相或添加颜色。这些属
性将来下一小节细说。

方法 *note addstr(): 2173. 接受一个 Python 字符串或字节串作为用于显示的
值。字节串的内容会被原样发送到终端。字符串会使用窗口的 ‘encoding’ 属性值
编码为字节，它默认为 *note locale.getpreferredencoding(): 3ad. 返回的系
统默认编码。

方法 *note addch(): 21b2. 接受一个字符，可以是长度为 1 的字符串，长度为
1 的字节串或者一个整数。

对于特殊扩展字符有一些常量，这些常量是大于 255 的整数。比如，
‘ACS_PLMINUS’ 是一个 “加减” 符号，‘ACS_ULCORNER’ 是一个框的左上角（方便
绘制边界）。你也可以使用正确的 Unicode 字符。

窗口会记住上次操作之后光标所在位置，所以如果你忽略 `y,x' 坐标，字符串和
字符会出现在上次操作结束的位置。你也可以通过 ‘move(y,x)’ 的方法来移动光
标。因为一些终端始终会显示一个闪烁的光标，你可能会想要保证光标处于一些不
会让人感到分心的位置。在看似随机的位置出现一个闪烁的光标会令人非常迷惑。

如果你的应用程序完全不需要一个闪烁的光标，你可以调用 ‘curs_set(False)’ 来
使它隐形。为与旧版本 curses 的兼容性的关系，有函数 ‘leaveok(bool)’ 作为
*note curs_set(): 216c. 的等价替换。如果 `bool' 是真值，curses 库会尝试
移除闪烁光标，并且你也不必担心它会留在一些奇怪的位置。

* Menu:

* 属性和颜色::


File: python.info,  Node: 属性和颜色,  Up: 显示文字

10.3.4.1 属性和颜色
...................

字符可以以不同的方式显示。基于文本的应用程序常常以反相显示状态行，一个文
本查看器可能需要突出显示某些单词。为了支持这种用法，curses 允许你为屏幕
上的每个单元指定一个属性值。

属性值是一个整数，它的每一个二进制位代表一个不同的属性。你可以尝试以多种
不属性位组合来显示文本，但 curses 不保证所有的组合都是有效的，或者看上去
有明显不同。这一点取决于用户终端的能力，所以最稳妥的方式是只采用最常见的
有效属性，见下表。

属性                       描述
                           
----------------------------------------------------------------------
                           
‘A_BLINK’                  闪烁文字
                           
                           
‘A_BOLD’                   超亮或粗体文字
                           
                           
‘A_DIM’                    半明亮的文字
                           
                           
‘A_REVERSE’                反相显示文本
                           
                           
‘A_STANDOUT’               可用的最佳突出显示模式
                           
                           
‘A_UNDERLINE’              带下划线的文字
                           

所以，为了在屏幕顶部显示一个反相的状态行，你可以这么编写：

     stdscr.addstr(0, 0, "Current mode: Typing mode",
                   curses.A_REVERSE)
     stdscr.refresh()

curses 库还支持在提供了颜色功能的终端上显示颜色的功能。最常见的提供颜色
的终端很可能是 Linux 控制台，采用了 xterms 配色方案。

为了使用颜色，你必须在调用完函数 *note initscr(): 217a. 后尽快调用函数
*note start_color(): 21a5.，来初始化默认颜色集 (*note curses.wrapper():
2a2. 函数自动完成了这一点)。 当它完成后，如果使用中的终端支持显示颜色，
*note has_colors(): 2182. 会返回真值。 （注意：curses 使用美式拼写
“color”，而不是英式／加拿大拼写 “colour”。如果你习惯了英式拼写，你需要避
免自己在这些函数上拼写错误。）

curses 库维护一个有限数量的颜色对，包括一个前景（文本）色和一个背景色。
你可以使用函数 *note color_pair(): 216a. 获得一个颜色对对应的属性值。它
可以通过按位或运算与其他属性，比如 ‘A_REVERSE’ 组合。但再说明一遍，这种
组合并不保证在所有终端上都有效。

一个样例，用 1 号颜色对显示一行文本：

     stdscr.addstr("Pretty text", curses.color_pair(1))
     stdscr.refresh()

如前所述， 颜色对由前景色和背景色组成。 ‘init_pair(n, f, b)’ 函数改变颜
色对*n*的定义， 为前景色f和背景色b。 颜色对0硬连接到黑色上的白色，不能改
变。

颜色已经被编号，并且当其激活 color 模式时 ‘start_color()’ 会初始化 8 种
基本颜色。 它们是: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta,
6:cyan 和 7:white。 *note curses: 2c. 模块为这些颜色定义了相应的名称常量
: ‘curses.COLOR_BLACK’, ‘curses.COLOR_RED’ 等等。

让我们来做个综合练习。 要将颜色 1 改为红色文本白色背景，你应当调用:

     curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)

当你改变一个颜色对时，任何已经使用该颜色对来显示的文本将会更改为新的颜色
。 你还可以这样来显示新颜色的文本:

     stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1))

某些非常花哨的终端可以将实际颜色定义修改为给定的 RGB 值。 这允许你将通常
为红色的 1 号颜色改成紫色或蓝色或者任何你喜欢的颜色。 不幸的是，Linux 控
制台不支持此特性，所以我无法尝试它，也无法提供任何示例。 想要检查你的终
端是否能做到你可以调用 *note can_change_color(): 2166.，如果有此功能则它
将返回 ‘True’。 如果你幸运地拥有一个如此优秀的终端，请查询你的系统的帮助
页面来了解详情。


File: python.info,  Node: 用户输入,  Next: 更多的信息,  Prev: 显示文字,  Up: 用 Python 进行 Curses 编程

10.3.5 用户输入
---------------

C curses 库提供了非常简单的输入机制。 Python 的 *note curses: 2c. 模块添
加了一个基本的文本输入控件。 （其他的库例如 Urwid(1) 拥有更丰富的控件集
。）

有两个方法可以从窗口获取输入:

   * *note getch(): 217e. 会刷新屏幕然后等待用户按键，如果之前调用过
     *note echo(): 2176. 还会显示所按的键。 你还可以选择指定一个坐标以便
     在暂停之前让光标移动到那里。

   * *note getkey(): 21cb. 将做同样的事但是会把整数转换为字符串。 每个字
     符将返回为长度为 1 个字符的字符串，特殊键例如函数键将返回包含键名的
     较长字符串例如 ‘KEY_UP’ 或 ‘^G’。

使用 *note nodelay(): 21e1. 窗口方法可以做到不等待用户。 在
‘nodelay(True)’ 之后，窗口的 ‘getch()’ 和 ‘getkey()’ 将成为非阻塞的。 为
表明输入未就绪，‘getch()’ 会返回 ‘curses.ERR’ (值为 -1) 而 ‘getkey()’ 会
引发异常。 此外还有 *note halfdelay(): 2186. 函数，它可被用来（实际地）
在每个 ‘getch()’ 上设置一个计时器；如果在指定的延迟内没有输入可用（以十
分之一秒为单位），curses 将引发异常。

‘getch()’ 方法返回一个整数；如果数值在 0 到 255 之间，它代表所按下键的
ASCII 码。 大于 255 的值为特殊键例如 Page Up, Home 或方向键等。 你可以将
返回的值与 ‘curses.KEY_PPAGE’, ‘curses.KEY_HOME’ 或 ‘curses.KEY_LEFT’ 等
常量做比较。 你的程序主循环看起来可能是这样:

     while True:
         c = stdscr.getch()
         if c == ord('p'):
             PrintDocument()
         elif c == ord('q'):
             break  # Exit the while loop
         elif c == curses.KEY_HOME:
             x = y = 0

*note curses.ascii: 2d. 模块提供了一些 ASCII 类成员函数，它们接受整数或
长度为 1 个字符的字符串参数；这些函数在为这样的循环编写更具可读性的测试
时可能会很有用。 它还提供了一些转换函数，它们接受整数或长度为 1 个字符的
字符串参数并返回同样的类型。 例如，*note curses.ascii.ctrl(): 2215. 返回
与其参数相对应的控制字符。

还有一个可以提取整个字符串的方法 *note getstr(): 21ce.。 它并不经常被使
用，因为它的功能相当受限；可用的编辑键只有 Backspace 和 Enter 键，它们会
结束字符串。 也可以选择限制为固定数量的字符。

     curses.echo()            # Enable echoing of characters

     # Get a 15-character string, with the cursor on the top line
     s = stdscr.getstr(0,0, 15)

*note curses.textpad: 2f. 模块提供了一个文本框，它支持类似 Emacs 的键绑
定集。 *note Textbox: 21fb. 类的各种方法支持带输入验证的编辑及包含或不包
含末尾空格地收集编辑结果。 下面是一个例子:

     import curses
     from curses.textpad import Textbox, rectangle

     def main(stdscr):
         stdscr.addstr(0, 0, "Enter IM message: (hit Ctrl-G to send)")

         editwin = curses.newwin(5,30, 2,1)
         rectangle(stdscr, 1,0, 1+5+1, 1+30+1)
         stdscr.refresh()

         box = Textbox(editwin)

         # Let the user edit until Ctrl-G is struck.
         box.edit()

         # Get resulting contents
         message = box.gather()

请查看 *note curses.textpad: 2f. 的库文档了解更多细节。

   ---------- Footnotes ----------

   (1) https://pypi.org/project/urwid/


File: python.info,  Node: 更多的信息,  Prev: 用户输入,  Up: 用 Python 进行 Curses 编程

10.3.6 更多的信息
-----------------

本 HOWTO 没有涵盖一些进阶主题，例如读取屏幕的内容或从 xterm 实例捕获鼠标
事件等，但是 *note curses: 2c. 模块的 Python 库文档页面现在已相当完善。
接下来你应当去浏览一下其中的内容。

如果你对 curses 函数的细节行为有疑问，请查看你的 curses 实现版本的说明页
面，不论它是 ncurses 还是特定 Unix 厂商的版本。 说明页面将记录任何具体问
题，并提供所有函数、属性以及可用 ‘ACS_*’ 字符的完整列表。

由于 curses API 是如此的庞大，某些函数并不被 Python 接口所支持。 这往往
不是因为它们难以实现，而是因为还没有人需要它们。 此外，Python 尚不支持与
ncurses 相关联的菜单库。 欢迎提供添加这些功能的补丁；请参阅 Python 开发
者指南(1) 了解有关为 Python 提交补丁的详情。

   * 使用 NCURSES 编写程序(2): 一篇面向 C 程序员的详细教程。

   * ncurses 手册主页 <‘https://linux.die.net/man/3/ncurses’>‘_

   * ncurses 常见问题
     <‘http://invisible-island.net/ncurses/ncurses.faq.html’>‘_

   * "使用 curses... 请勿爆粗"(3): 一场有关使用 curses 或 Urwid 来控制终
     端的 PyCon 2013 演讲的视频。

   * "使用 Urwid 的控制台应用程序"(4): 一场演示使用 Urwid 编写应用程序的
     PyCon CA 2012 演讲的视频。

   ---------- Footnotes ----------

   (1) https://devguide.python.org/

   (2) http://invisible-island.net/ncurses/ncurses-intro.html

   (3) https://www.youtube.com/watch?v=eN1eZtjLEnU

   (4) http://www.pyvideo.org/video/1568/console-applications-with-urwid


File: python.info,  Node: 描述器使用指南,  Next: 函数式编程指引,  Prev: 用 Python 进行 Curses 编程,  Up: Python 常用指引

10.4 描述器使用指南
===================


作者: Raymond Hettinger


联系方式: <python at rcn dot com>

* Menu:

* 摘要::
* 定义和简介::
* 描述器协议::
* 调用描述器: 调用描述器<2>.
* 描述器示例::
* 属性::
* 函数和方法::
* 静态方法和类方法::


File: python.info,  Node: 摘要,  Next: 定义和简介,  Up: 描述器使用指南

10.4.1 摘要
-----------

定义描述器，总结描述器协议，展示描述器被如何使用。测试一个自定义的描述器
和若干 Python 内置的描述器，包括函数、属性、静态方法和类方法。通过给出一
个纯 Python 的等价实现和例程，展示每个描述器如何工作。

学习描述器不仅能提供接触到更多工具集的途径，还能更深地理解 Python 工作的
原理并更加体会到其设计的优雅性。


File: python.info,  Node: 定义和简介,  Next: 描述器协议,  Prev: 摘要,  Up: 描述器使用指南

10.4.2 定义和简介
-----------------

一般地，一个描述器是一个包含 “绑定行为” 的对象，对其属性的访问被描述器协
议中定义的方法覆盖。这些方法有：*note __get__(): 144b.，*note __set__():
144f. 和 *note __delete__(): 1450.。如果某个对象中定义了这些方法中的任意
一个，那么这个对象就可以被称为一个描述器。

属性访问的默认行为是从一个对象的字典中获取、设置或删除属性。例如，‘a.x’
的查找顺序会从 ‘a.__dict__['x']’ 开始，然后是 ‘type(a).__dict__['x']’，
接下来依次查找 ‘type(a)’ 的基类，不包括元类。 如果找到的值是定义了某个描
述器方法的对象，则 Python 可能会重载默认行为并转而发起调用描述器方法。这
具体发生在优先级链的哪个环节则要根据所定义的描述器方法及其被调用的方式来
决定。

描述器是一个强大而通用的协议。 它们是特征属性、方法静态方法、类方法和
*note super(): 4eb. 背后的实现机制。 它们在 Python 内部被广泛使用来实现
自 2.2 版中引入的新式类。 描述器简化了底层的 C 代码并为 Python 的日常程
序提供了一组灵活的新工具。


File: python.info,  Node: 描述器协议,  Next: 调用描述器<2>,  Prev: 定义和简介,  Up: 描述器使用指南

10.4.3 描述器协议
-----------------

‘descr.__get__(self, obj, type=None) -> value’

‘descr.__set__(self, obj, value) -> None’

‘descr.__delete__(self, obj) -> None’

以上就是全部。定义这些方法中的任何一个的对象被视为描述器，并在被作为属性
时覆盖其默认行为。

如果一个对象定义了 *note __set__(): 144f. 或 *note __delete__(): 1450.，
则它会被视为数据描述器。 仅定义了 *note __get__(): 144b. 的描述器称为非
数据描述器（它们通常被用于方法，但也可以有其他用途）。

数据和非数据描述器的不同之处在于，如何计算实例字典中条目的替代值。如果实
例的字典具有与数据描述器同名的条目，则数据描述器优先。如果实例的字典具有
与非数据描述器同名的条目，则该字典条目优先。

为了使数据描述器成为只读的，应该同时定义 *note __get__(): 144b. 和 *note
__set__(): 144f. ，并在 *note __set__(): 144f. 中引发 *note
AttributeError: 3a3. 。用引发异常的占位符定义 *note __set__(): 144f. 方
法使其成为数据描述器。


File: python.info,  Node: 调用描述器<2>,  Next: 描述器示例,  Prev: 描述器协议,  Up: 描述器使用指南

10.4.4 调用描述器
-----------------

描述器可以通过其方法名称直接调用。例如， ‘d.__get__(obj)’ 。

或者，更常见的是在属性访问时自动调用描述器。例如，在中 ‘obj.d’ 会在 ‘d’
的字典中查找 ‘obj’ 。如果 ‘d’ 定义了方法 *note __get__(): 144b. ，则
‘d.__get__(obj)’ 根据下面列出的优先级规则进行调用。

调用的细节取决于 ‘obj’ 是对象还是类。

对于对象来说，机制是 *note object.__getattribute__(): 44f. 中将 ‘b.x’ 转
换为 ‘type(b).__dict__['x'].__get__(b, type(b))’ 。这个实现通过一个优先
级链完成，该优先级链赋予数据描述器优先于实例变量的优先级，实例变量优先于
非数据描述器的优先级，并如果 *note __getattr__(): 323. 方法存在，为其分
配最低的优先级。 完整的C实现可在 Objects/object.c(1) 中的 *note
PyObject_GenericGetAttr(): 3cb7. 找到。

对于类来说，机制是 ‘type.__getattribute__()’ 中将 ‘B.x’ 转换为
‘B.__dict__['x'].__get__(None, B)’ 。在纯 Python中 ，它是这样的:

     def __getattribute__(self, key):
         "Emulate type_getattro() in Objects/typeobject.c"
         v = object.__getattribute__(self, key)
         if hasattr(v, '__get__'):
             return v.__get__(None, self)
         return v

要记住的重要点是：

   * 描述器由 *note __getattribute__(): 44f. 方法调用

   * 重写 *note __getattribute__(): 44f. 会阻止描述器的自动调用

   * *note object.__getattribute__(): 44f. 和 ‘type.__getattribute__()’
     会用不同的方式调用 *note __get__(): 144b.

   * 数据描述器始终会覆盖实例字典。

   * 非数据描述器会被实例字典覆盖。

The object returned by ‘super()’ also has a custom *note
__getattribute__(): 44f. method for invoking descriptors.  The attribute
lookup ‘super(B, obj).m’ searches ‘obj.__class__.__mro__’ for the base
class ‘A’ immediately following ‘B’ and then returns
‘A.__dict__['m'].__get__(obj, B)’.  If not a descriptor, ‘m’ is returned
unchanged.  If not in the dictionary, ‘m’ reverts to a search using
*note object.__getattribute__(): 44f.

这个实现的具体细节在 Objects/typeobject.c(2). 的 ‘super_getattro()’ 中，
并且你还可以在 Guido’s Tutorial(3) 中找到等价的纯 Python 实现。

以上展示的关于描述器机制的细节嵌入在 *note object: 2b1. ， *note type:
611. ， 和 *note super(): 4eb. 中的 *note __getattribute__(): 44f. 。当
类派生自类 *note object: 2b1. 或有提供类似功能的元类时，它们将继承此机制
。同样，类可以通过重写 *note __getattribute__(): 44f. 阻止描述器调用。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Objects/object.c

   (2) https://github.com/python/cpython/tree/3.8/Objects/typeobject.c

   (3) 
https://www.python.org/download/releases/2.2.3/descrintro/#cooperation


File: python.info,  Node: 描述器示例,  Next: 属性,  Prev: 调用描述器<2>,  Up: 描述器使用指南

10.4.5 描述器示例
-----------------

以下代码创建一个类，其对象是数据描述器，该描述器为每个 get 或 set 打印一
条消息。 覆盖 *note __getattribute__(): 44f. 是可以对每个属性执行此操作
的替代方法。但是，此描述器对于跟踪少数几个选定的属性很有用:

     class RevealAccess(object):
         """A data descriptor that sets and returns values
            normally and prints a message logging their access.
         """

         def __init__(self, initval=None, name='var'):
             self.val = initval
             self.name = name

         def __get__(self, obj, objtype):
             print('Retrieving', self.name)
             return self.val

         def __set__(self, obj, val):
             print('Updating', self.name)
             self.val = val

     >>> class MyClass(object):
     ...     x = RevealAccess(10, 'var "x"')
     ...     y = 5
     ...
     >>> m = MyClass()
     >>> m.x
     Retrieving var "x"
     10
     >>> m.x = 20
     Updating var "x"
     >>> m.x
     Retrieving var "x"
     20
     >>> m.y
     5

这个协议很简单，并提供了令人兴奋的可能性。有几种用例非常普遍，以至于它们
被打包到单独的函数调用中。属性、绑定方法、静态方法和类方法均基于描述器协
议。


File: python.info,  Node: 属性,  Next: 函数和方法,  Prev: 描述器示例,  Up: 描述器使用指南

10.4.6 属性
-----------

调用 *note property(): 1d8. 是构建数据描述器的简洁方式，该数据描述器在访
问属性时触发函数调用。它的签名是:

     property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

该文档显示了定义托管属性 ‘x’ 的典型用法:

     class C(object):
         def getx(self): return self.__x
         def setx(self, value): self.__x = value
         def delx(self): del self.__x
         x = property(getx, setx, delx, "I'm the 'x' property.")

要了解 *note property(): 1d8. 如何根据描述器协议实现，这里是一个纯
Python 的等价实现如下:

     class Property(object):
         "Emulate PyProperty_Type() in Objects/descrobject.c"

         def __init__(self, fget=None, fset=None, fdel=None, doc=None):
             self.fget = fget
             self.fset = fset
             self.fdel = fdel
             if doc is None and fget is not None:
                 doc = fget.__doc__
             self.__doc__ = doc

         def __get__(self, obj, objtype=None):
             if obj is None:
                 return self
             if self.fget is None:
                 raise AttributeError("unreadable attribute")
             return self.fget(obj)

         def __set__(self, obj, value):
             if self.fset is None:
                 raise AttributeError("can't set attribute")
             self.fset(obj, value)

         def __delete__(self, obj):
             if self.fdel is None:
                 raise AttributeError("can't delete attribute")
             self.fdel(obj)

         def getter(self, fget):
             return type(self)(fget, self.fset, self.fdel, self.__doc__)

         def setter(self, fset):
             return type(self)(self.fget, fset, self.fdel, self.__doc__)

         def deleter(self, fdel):
             return type(self)(self.fget, self.fset, fdel, self.__doc__)

这个内置的 *note property(): 1d8. 每当用户访问属性时生效，随后的变化需要
一个方法的参与。

例如，一个电子表格类可以通过 ‘Cell('b10').value’ 授予对单元格值的访问权
限。对程序的后续改进要求每次访问都要重新计算单元格；但是，程序员不希望影
响直接访问该属性的现有客户端代码。解决方案是将对 value 属性的访问包装在
属性数据描述器中:

     class Cell(object):
         . . .
         def getvalue(self):
             "Recalculate the cell before returning value"
             self.recalc()
             return self._value
         value = property(getvalue)


File: python.info,  Node: 函数和方法,  Next: 静态方法和类方法,  Prev: 属性,  Up: 描述器使用指南

10.4.7 函数和方法
-----------------

Python 的面向对象功能是在基于函数的环境构建的。通过使用非数据描述器，这
两方面完成了无缝融合。

类字典将方法存储为函数。在类定义中，方法是用 *note def: dc6. 或 *note
lambda: c37. 这两个创建函数的常用工具编写的。方法与常规函数的不同之处仅
在于第一个参数是为对象实例保留的。按照 Python 约定，实例引用称为 `self'
，但也可以称为 `this' 或任何其他变量名称。

为了支持方法调用，函数包含 *note __get__(): 144b. 方法用于在访问属性时将
其绑定成方法。这意味着所有函数都是非数据描述器，当从对象调用它们时，它们
返回绑定方法。在纯 Python 中，它的工作方式如下:

     class Function(object):
         . . .
         def __get__(self, obj, objtype=None):
             "Simulate func_descr_get() in Objects/funcobject.c"
             if obj is None:
                 return self
             return types.MethodType(self, obj)

运行解释器显示了函数描述器在实践中的工作方式：

     >>> class D(object):
     ...     def f(self, x):
     ...         return x
     ...
     >>> d = D()

     # Access through the class dictionary does not invoke __get__.
     # It just returns the underlying function object.
     >>> D.__dict__['f']
     <function D.f at 0x00C45070>

     # Dotted access from a class calls __get__() which just returns
     # the underlying function unchanged.
     >>> D.f
     <function D.f at 0x00C45070>

     # The function has a __qualname__ attribute to support introspection
     >>> D.f.__qualname__
     'D.f'

     # Dotted access from an instance calls __get__() which returns the
     # function wrapped in a bound method object
     >>> d.f
     <bound method D.f of <__main__.D object at 0x00B18C90>>

     # Internally, the bound method stores the underlying function and
     # the bound instance.
     >>> d.f.__func__
     <function D.f at 0x1012e5ae8>
     >>> d.f.__self__
     <__main__.D object at 0x1012e1f98>


File: python.info,  Node: 静态方法和类方法,  Prev: 函数和方法,  Up: 描述器使用指南

10.4.8 静态方法和类方法
-----------------------

非数据描述器为把函数绑定为方法的通常模式提供了一种简单的机制。

概括地说，函数具有 *note __get__(): 144b. 方法，以便在作为属性访问时可以
将其转换为方法。非数据描述符将 ‘obj.f(*args)’ 的调用转换为 ‘f(obj,
*args)’ 。调用 ‘klass.f(*args)‘’ 因而变成 ‘f(*args)’ 。

下表总结了绑定及其两个最有用的变体：

     转换形式              通过对象调用               通过类调用
                                                      
     ------------------------------------------------------------------------
                                                      
     function – 函数       f(obj, *args)              f(*args)
                                                      
                                                      
     静态方法              f(*args)                   f(*args)
                                                      
                                                      
     类方法                f(type(obj), *args)        f(klass, *args)
                                                      

静态方法返回底层函数，不做任何更改。调用 ‘c.f’ 或 ‘C.f’ 等效于通过
‘object.__getattribute__(c, "f")’ 或 ‘object.__getattribute__(C, "f")’ 查
找。这样该函数就可以从对象或类中进行相同的访问。

适合于作为静态方法的是那些不引用 ‘self’ 变量的方法。

例如，一个统计用的包可能包含一个实验数据的容器类。该容器类提供了用于计算
数据的平均值，均值，中位数和其他描述性统计信息的常规方法。但是，可能有在
概念上相关但不依赖于数据的函数。例如， ‘erf(x)’ 是在统计中的便捷转换，但
并不直接依赖于特定的数据集。可以从对象或类中调用它： ‘s.erf(1.5) -->
.9332’ 或 ‘Sample.erf(1.5) --> .9332’。

由于静态方法直接返回了底层的函数，因此示例调用是相同的：

     >>> class E(object):
     ...     def f(x):
     ...         print(x)
     ...     f = staticmethod(f)
     ...
     >>> E.f(3)
     3
     >>> E().f(3)
     3

使用非数据描述器，纯 Python 版本的 *note staticmethod(): 1da. 如下所示：

     class StaticMethod(object):
         "Emulate PyStaticMethod_Type() in Objects/funcobject.c"

         def __init__(self, f):
             self.f = f

         def __get__(self, obj, objtype=None):
             return self.f

与静态方法不同，类方法在调用函数之前将类引用放在参数列表的最前。无论调用
方是对象还是类，此格式相同：

     >>> class E(object):
     ...     def f(klass, x):
     ...         return klass.__name__, x
     ...     f = classmethod(f)
     ...
     >>> print(E.f(3))
     ('E', 3)
     >>> print(E().f(3))
     ('E', 3)

此行为适用于当函数仅需要使用类引用并且不关心任何底层数据时的情况。 类方
法的一种用途是创建替代的类构造器。 在 Python 2.3 中，类方法 *note
dict.fromkeys(): 16e4. 会从键列表中创建一个新的字典。 纯 Python 的等价形
式是:

     class Dict(object):
         . . .
         def fromkeys(klass, iterable, value=None):
             "Emulate dict_fromkeys() in Objects/dictobject.c"
             d = klass()
             for key in iterable:
                 d[key] = value
             return d
         fromkeys = classmethod(fromkeys)

现在可以这样构造一个新的唯一键字典：

     >>> Dict.fromkeys('abracadabra')
     {'a': None, 'r': None, 'b': None, 'c': None, 'd': None}

使用非数据描述符协议，纯 Python 版本的 *note classmethod(): 1d9. 如下：

     class ClassMethod(object):
         "Emulate PyClassMethod_Type() in Objects/funcobject.c"

         def __init__(self, f):
             self.f = f

         def __get__(self, obj, klass=None):
             if klass is None:
                 klass = type(obj)
             def newfunc(*args):
                 return self.f(klass, *args)
             return newfunc


File: python.info,  Node: 函数式编程指引,  Next: 日志常用指引,  Prev: 描述器使用指南,  Up: Python 常用指引

10.5 函数式编程指引
===================


作者: A. M. Kuchling


发布版本: 0.32

本文档提供恰当的 Python 函数式编程范例，在函数式编程简单的介绍之后，将简
单介绍Python中关于函数式编程的特性如 *note iterator: 104b. 和 *note
generator: 9aa. 以及相关库模块如 *note itertools: a4. 和 *note
functools: 85. 等。

* Menu:

* 概述: 概述<17>.
* 迭代器: 迭代器<2>.
* 生成器表达式和列表推导式::
* 生成器: 生成器<2>.
* 内置函数: 内置函数<2>.
* itertools 模块::
* functools 模块::
* 小函数和 lambda 表达式::
* 修订记录和致谢::
* 参考文献: 参考文献<2>.


File: python.info,  Node: 概述<17>,  Next: 迭代器<2>,  Up: 函数式编程指引

10.5.1 概述
-----------

本章介绍函数式编程的基本概念。如您仅想学习 Python 语言的特性，可跳过本章
直接查看 *note 迭代器: 412a.

编程语言支持通过以下几种方式来解构具体问题：

   * 大多数的编程语言都是 `过程式' 的，所谓程序就是一连串告诉计算机怎样
     处理程序输入的指令。C、Pascal 甚至 Unix shells 都是过程式语言。

   * 在 `声明式' 语言中，你编写一个用来描述待解决问题的说明，并且这个语
     言的具体实现会指明怎样高效的进行计算。 SQL 可能是你最熟悉的声明式语
     言了。 一个 SQL 查询语句描述了你想要检索的数据集，并且 SQL 引擎会决
     定是扫描整张表还是使用索引，应该先执行哪些子句等等。

   * `面向对象' 程序会操作一组对象。 对象拥有内部状态，并能够以某种方式
     支持请求和修改这个内部状态的方法。Smalltalk 和 Java 都是面向对象的
     语言。 C++ 和 Python 支持面向对象编程，但并不强制使用面向对象特性。

   * `函数式' 编程则将一个问题分解成一系列函数。 理想情况下，函数只接受
     输入并输出结果，对一个给定的输入也不会有影响输出的内部状态。 著名的
     函数式语言有 ML 家族（Standard ML，Ocaml 以及其他变种）和 Haskell。

一些语言的设计者选择强调一种特定的编程方式。 这通常会让以不同的方式来编
写程序变得困难。其他多范式语言则支持几种不同的编程方式。Lisp，C++ 和
Python 都是多范式语言；使用这些语言，你可以编写主要为过程式，面向对象或
者函数式的程序和函数库。在大型程序中，不同的部分可能会采用不同的方式编写
；比如 GUI 可能是面向对象的而处理逻辑则是过程式或者函数式。

在函数式程序里，输入会流经一系列函数。每个函数接受输入并输出结果。函数式
风格反对使用带有副作用的函数，这些副作用会修改内部状态，或者引起一些无法
体现在函数的返回值中的变化。完全不产生副作用的函数被称作“纯函数”。消除副
作用意味着不能使用随程序运行而更新的数据结构；每个函数的输出必须只依赖于
输入。

一些语言对纯洁性要求非常严格，以至于没有像 ‘a=3’ 或 ‘c = a + b’ 这样的赋
值表达式，但是完全消除副作用非常困难。 比如，显示在屏幕上或者写到磁盘文
件中都是副作用。举个例子，在 Python 里，调用函数 *note print(): 88f. 或
者 *note time.sleep(): 689. 并不会返回有用的结果；它们的用途只在于副作用
，向屏幕发送一段文字或暂停一秒钟。

函数式风格的 Python 程序并不会极端到消除所有 I/O 或者赋值的程度；相反，
他们会提供像函数式一样的接口，但会在内部使用非函数式的特性。比如，函数的
实现仍然会使用局部变量，但不会修改全局变量或者有其他副作用。

函数式编程可以被认为是面向对象编程的对立面。对象就像是颗小胶囊，包裹着内
部状态和随之而来的能让你修改这个内部状态的一组调用方法，以及由正确的状态
变化所构成的程序。函数式编程希望尽可能地消除状态变化，只和流经函数的数据
打交道。在 Python 里你可以把两种编程方式结合起来，在你的应用（电子邮件信
息，事务处理）中编写接受和返回对象实例的函数。

函数式设计在工作中看起来是个奇怪的约束。为什么你要消除对象和副作用呢？不
过函数式风格有其理论和实践上的优点：

   * 形式证明。

   * 模块化。

   * 组合性。

   * 易于调试和测试。

* Menu:

* 形式证明::
* 模块化::
* 易于调试和测试::
* 组合性::


File: python.info,  Node: 形式证明,  Next: 模块化,  Up: 概述<17>

10.5.1.1 形式证明
.................

一个理论上的优点是，构造数学证明来说明函数式程序是正确的相对更容易些。

很长时间，研究者们对寻找证明程序正确的数学方法都很感兴趣。这和通过大量输
入来测试，并得出程序的输出基本正确，或者阅读一个程序的源代码然后得出代码
看起来没问题不同；相反，这里的目标是一个严格的证明，证明程序对所有可能的
输入都能给出正确的结果。

证明程序正确性所用到的技术是写出 `不变量'，也就是对于输入数据和程序中的
变量永远为真的特性。然后对每行代码，你说明这行代码执行前的不变量 X 和 Y
以及执行后稍有不同的不变量 X’ 和 Y’ 为真。如此一直到程序结束，这时候在程
序的输出上，不变量应该会与期望的状态一致。

函数式编程之所以要消除赋值，是因为赋值在这个技术中难以处理；赋值可能会破
坏赋值前为真的不变量，却并不产生任何可以传递下去的新的不变量。

不幸的是，证明程序的正确性很大程度上是经验性质的，而且和 Python 软件无关
。即使是微不足道的程序都需要几页长的证明；一个中等复杂的程序的正确性证明
会非常庞大，而且，极少甚至没有你日常所使用的程序（Python 解释器，XML 解
析器，浏览器）的正确性能够被证明。即使你写出或者生成一个证明，验证证明也
会是一个问题；里面可能出了差错，而你错误地相信你证明了程序的正确性。


File: python.info,  Node: 模块化,  Next: 易于调试和测试,  Prev: 形式证明,  Up: 概述<17>

10.5.1.2 模块化
...............

函数式编程的一个更实用的优点是，它强制你把问题分解成小的方面。因此程序会
更加模块化。相对于一个进行了复杂变换的大型函数，一个小的函数更明确，更易
于编写, 也更易于阅读和检查错误。


File: python.info,  Node: 易于调试和测试,  Next: 组合性,  Prev: 模块化,  Up: 概述<17>

10.5.1.3 易于调试和测试
.......................

测试和调试函数式程序相对来说更容易。

调试很简单是因为函数通常都很小而且清晰明确。当程序无法工作的时候，每个函
数都是一个可以检查数据是否正确的接入点。你可以通过查看中间输入和输出迅速
找到出错的函数。

测试更容易是因为每个函数都是单元测试的潜在目标。在执行测试前，函数并不依
赖于需要重现的系统状态；相反，你只需要给出正确的输入，然后检查输出是否和
期望的结果一致。


File: python.info,  Node: 组合性,  Prev: 易于调试和测试,  Up: 概述<17>

10.5.1.4 组合性
...............

当你编写函数式风格的程序时，你会写出很多带有不同输入和输出的函数。其中一
些不可避免地会局限于特定的应用，但其他的却可以广泛的用在程序中。举例来说
，一个接受文件夹目录返回所有文件夹中的 XML 文件的函数； 或是一个接受文件
名，然后返回文件内容的函数，都可以应用在很多不同的场合。

久而久之你会形成一个个人工具库。通常你可以重新组织已有的函数来组成新的程
序，然后为当前的工作写一些特殊的函数。


File: python.info,  Node: 迭代器<2>,  Next: 生成器表达式和列表推导式,  Prev: 概述<17>,  Up: 函数式编程指引

10.5.2 迭代器
-------------

我会从 Python 的一个语言特性， 编写函数式风格程序的重要基石开始说起：迭
代器。

迭代器是一个表示数据流的对象；这个对象每次只返回一个元素。Python 迭代器
必须支持 *note __next__(): c6c. 方法；这个方法不接受参数，并总是返回数据
流中的下一个元素。如果数据流中没有元素，*note __next__(): c6c. 会抛出
*note StopIteration: 48e. 异常。迭代器未必是有限的；完全有理由构造一个输
出无限数据流的迭代器。

内置的 *note iter(): d2f. 函数接受任意对象并试图返回一个迭代器来输出对象
的内容或元素，并会在对象不支持迭代的时候抛出 *note TypeError: 193. 异常
。Python 有几种内置数据类型支持迭代，最常见的就是列表和字典。如果一个对
象能生成迭代器，那么它就会被称作 *note iterable: bb4.。

你可以手动试验迭代器的接口。

     >>> L = [1, 2, 3]
     >>> it = iter(L)
     >>> it
     <...iterator object at ...>
     >>> it.__next__()  # same as next(it)
     1
     >>> next(it)
     2
     >>> next(it)
     3
     >>> next(it)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     StopIteration
     >>>

Python 有不少要求使用可迭代的对象的地方，其中最重要的就是 *note for:
c38. 表达式。在表达式 ‘for X in Y’，Y 要么自身是一个迭代器，要么能够由
*note iter(): d2f. 创建一个迭代器。以下两种表达是等价的:

     for i in iter(obj):
         print(i)

     for i in obj:
         print(i)

可以用 *note list(): 263. 或 *note tuple(): 486. 这样的构造函数把迭代器
具体化成列表或元组:

     >>> L = [1, 2, 3]
     >>> iterator = iter(L)
     >>> t = tuple(iterator)
     >>> t
     (1, 2, 3)

序列的解压操作也支持迭代器：如果你知道一个迭代器能够返回 N 个元素，你可
以把他们解压到有 N 个元素的元组:

     >>> L = [1, 2, 3]
     >>> iterator = iter(L)
     >>> a, b, c = iterator
     >>> a, b, c
     (1, 2, 3)

像 *note max(): 813. 和 *note min(): 812. 这样的内置函数可以接受单个迭代
器参数，然后返回其中最大或者最小的元素。‘"in"’ 和 ‘"not in"’ 操作也支持
迭代器：如果能够在迭代器 iterator 返回的数据流中找到 X 的话，则‘‘X in
iterator‘‘ 为真。很显然，如果迭代器是无限的，这么做你就会遇到问题；*note
max(): 813. 和 *note min(): 812. 永远也不会返回；如果元素 X 也不出现在数
据流中，‘"in"’ 和 ‘"not in"’ 操作同样也永远不会返回。

注意你只能在迭代器中顺序前进；没有获取前一个元素的方法，除非重置迭代器，
或者重新复制一份。迭代器对象可以提供这些额外的功能，但迭代器协议只明确了
*note __next__(): c6c. 方法。函数可能因此而耗尽迭代器的输出，如果你要对
同样的数据流做不同的操作，你必须重新创建一个迭代器。

* Menu:

* 支持迭代器的数据类型::


File: python.info,  Node: 支持迭代器的数据类型,  Up: 迭代器<2>

10.5.2.1 支持迭代器的数据类型
.............................

我们已经知道列表和元组支持迭代器。实际上，Python 中的任何序列类型，比如
字符串，都自动支持创建迭代器。

对字典调用 *note iter(): d2f. 会返回一个遍历字典的键的迭代器:

     >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
     ...      'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
     >>> for key in m:
     ...     print(key, m[key])
     Jan 1
     Feb 2
     Mar 3
     Apr 4
     May 5
     Jun 6
     Jul 7
     Aug 8
     Sep 9
     Oct 10
     Nov 11
     Dec 12

注意从 Python 3.7 开始，字典的遍历顺序一定和输入顺序一样。先前的版本并没
有明确这一点，所以不同的实现可能不一致。

对字典使用 *note iter(): d2f. 总是会遍历键，但字典也有返回其他迭代器的方
法。如果你只遍历值或者键/值对，你可以明确地调用 *note values(): c34. 或
*note items(): c33. 方法得到合适的迭代器。

*note dict(): 1b9. 构造函数可以接受一个迭代器，然后返回一个有限的 ‘(key,
value)’ 元组的数据流:

     >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
     >>> dict(iter(L))
     {'Italy': 'Rome', 'France': 'Paris', 'US': 'Washington DC'}

文件也可以通过调用 *note readline(): 1c0e. 来遍历，直到穷尽文件中所有的
行。这意味着你可以像这样读取文件中的每一行:

     for line in file:
         # do something for each line
         ...

集合可以从可遍历的对象获取内容，也可以让你遍历集合的元素:

     S = {2, 3, 5, 7, 11, 13}
     for i in S:
         print(i)


File: python.info,  Node: 生成器表达式和列表推导式,  Next: 生成器<2>,  Prev: 迭代器<2>,  Up: 函数式编程指引

10.5.3 生成器表达式和列表推导式
-------------------------------

迭代器的输出有两个很常见的使用方式，1) 对每一个元素执行操作，2) 选择一个
符合条件的元素子集。比如，给定一个字符串列表，你可能想去掉每个字符串尾部
的空白字符，或是选出所有包含给定子串的字符串。

列表推导式和生成器表达时（简写："listcomps" 和 "genexps"）让这些操作更加
简明，这个形式借鉴自函数式程序语言 Haskell（‘https://www.haskell.org/’）
。你可以用以下代码去掉一个字符串流中的所有空白字符:

     line_list = ['  line 1\n', 'line 2  \n', ...]

     # Generator expression -- returns iterator
     stripped_iter = (line.strip() for line in line_list)

     # List comprehension -- returns list
     stripped_list = [line.strip() for line in line_list]

你可以加上条件语句 ‘"if"’ 来选取特定的元素:

     stripped_list = [line.strip() for line in line_list
                      if line != ""]

通过列表推导式，你会获得一个 Python 列表；‘stripped_list’ 就是一个包含所
有结果行的列表，并不是迭代器。 生成器表达式会返回一个迭代器，它在必要的
时候计算结果，避免一次性生成所有的值。 这意味着，如果迭代器返回一个无限
数据流或者大量的数据，列表推导式就不太好用了。 这种情况下生成器表达式会
更受青睐。

生成器表达式两边使用圆括号 ("()") ，而列表推导式则使用方括号 ("[]")。生
成器表达式的形式为:

     ( expression for expr in sequence1
                  if condition1
                  for expr2 in sequence2
                  if condition2
                  for expr3 in sequence3 ...
                  if condition3
                  for exprN in sequenceN
                  if conditionN )

再次说明，列表推导式只有两边的括号不一样（方括号而不是圆括号）。

这些生成用于输出的元素会成为 ‘expression’ 的后继值。其中 ‘if’ 语句是可选
的；如果给定的话 ‘expression’ 只会在符合条件时计算并加入到结果中。

生成器表达式总是写在圆括号里面，不过也可以算上调用函数时用的括号。如果你
想即时创建一个传递给函数的迭代器，可以这么写:

     obj_total = sum(obj.count for obj in list_all_objects())

其中 ‘for...in’ 语句包含了将要遍历的序列。这些序列并不必须同样长，因为它
们会从左往右开始遍历，而 `不是' 同时执行。对每个 ‘sequence1’ 中的元素，
‘sequence2’ 会从头开始遍历。‘sequence3’ 会对每个 ‘sequence1’ 和
‘sequence2’ 的元素对开始遍历。

换句话说，列表推导式器是和下面的 Python 代码等价:

     for expr1 in sequence1:
         if not (condition1):
             continue   # Skip this element
         for expr2 in sequence2:
             if not (condition2):
                 continue   # Skip this element
             ...
             for exprN in sequenceN:
                 if not (conditionN):
                     continue   # Skip this element

                 # Output the value of
                 # the expression.

这说明，如果有多个 ‘for...in’ 语句而没有 ‘if’ 语句，输出结果的长度就是所
有序列长度的乘积。如果你的两个列表长度为3，那么输出的列表长度就是9:

     >>> seq1 = 'abc'
     >>> seq2 = (1, 2, 3)
     >>> [(x, y) for x in seq1 for y in seq2]
     [('a', 1), ('a', 2), ('a', 3),
      ('b', 1), ('b', 2), ('b', 3),
      ('c', 1), ('c', 2), ('c', 3)]

为了不让 Python 语法变得含糊，如果 ‘expression’ 会生成元组，那这个元组必
须要用括号括起来。下面第一个列表推导式语法错误，第二个则是正确的:

     # Syntax error
     [x, y for x in seq1 for y in seq2]
     # Correct
     [(x, y) for x in seq1 for y in seq2]


File: python.info,  Node: 生成器<2>,  Next: 内置函数<2>,  Prev: 生成器表达式和列表推导式,  Up: 函数式编程指引

10.5.4 生成器
-------------

生成器是一类用来简化编写迭代器工作的特殊函数。普通的函数计算并返回一个值
，而生成器返回一个能返回数据流的迭代器。

毫无疑问，你已经对如何在 Python 和 C 中调用普通函数很熟悉了，这时候函数
会获得一个创建局部变量的私有命名空间。当函数到达 ‘return’ 表达式时，局部
变量会被销毁然后把返回给调用者。之后调用同样的函数时会创建一个新的私有命
名空间和一组全新的局部变量。但是，如果在退出一个函数时不扔掉局部变量会如
何呢？如果稍后你能够从退出函数的地方重新恢复又如何呢？这就是生成器所提供
的；他们可以被看成可恢复的函数。

这里有简单的生成器函数示例:

     >>> def generate_ints(N):
     ...    for i in range(N):
     ...        yield i

任何包含了 *note yield: 190. 关键字的函数都是生成器函数；Python 的 *note
bytecode: 61d. 编译器会在编译的时候检测到并因此而特殊处理。

当你调用一个生成器函数，它并不会返回单独的值，而是返回一个支持生成器协议
的生成器对象。当执行 ‘yield’ 表达式时，生成器会输出 ‘i’ 的值，就像
‘return’ 表达式一样。‘yield’ 和 ‘return’ 最大的区别在于，到达 ‘yield’ 的
时候生成器的执行状态会挂起并保留局部变量。在下一次调用生成器 *note
__next__(): 12ea. 方法的时候，函数会恢复执行。

这里有一个 ‘generate_ints()’ 生成器的示例:

     >>> gen = generate_ints(3)
     >>> gen
     <generator object generate_ints at ...>
     >>> next(gen)
     0
     >>> next(gen)
     1
     >>> next(gen)
     2
     >>> next(gen)
     Traceback (most recent call last):
       File "stdin", line 1, in <module>
       File "stdin", line 2, in generate_ints
     StopIteration

同样，你可以写出 ‘for i in generate_ints(5)’，或者 ‘a, b, c =
generate_ints(3)’。

在生成器函数里面，‘return value’ 会触发从 *note __next__(): 12ea. 方法抛
出 ‘StopIteration(value)’ 异常。一旦抛出这个异常，或者函数结束，处理数据
的过程就会停止，生成器也不会再生成新的值。

你可以手动编写自己的类来达到生成器的效果，把生成器的所有局部变量作为实例
的成员变量存储起来。比如，可以这么返回一个整数列表：把 ‘self.count’ 设为
0，然后通过 ‘count`()’。然而，对于一个中等复杂程度的生成器，写出一个相应
的类可能会相当繁杂。

包含在 Python 库中的测试套件 Lib/test/test_generators.py(1) 里有很多非常
有趣的例子。这里是一个用生成器实现树的递归中序遍历示例。:

     # A recursive generator that generates Tree leaves in in-order.
     def inorder(t):
         if t:
             for x in inorder(t.left):
                 yield x

             yield t.label

             for x in inorder(t.right):
                 yield x

另外两个 ‘test_generators.py’ 中的例子给出了 N 皇后问题（在 NxN 的棋盘上
放置 N 个皇后，任何一个都不能吃掉另一个），以及马的遍历路线（在NxN 的棋
盘上给马找出一条不重复的走过所有格子的路线）的解。

* Menu:

* 向生成器传递值::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.8/Lib/test/test_generators.py


File: python.info,  Node: 向生成器传递值,  Up: 生成器<2>

10.5.4.1 向生成器传递值
.......................

在 Python 2.4 及之前的版本中，生成器只产生输出。一旦调用生成器的代码创建
一个迭代器，就没有办法在函数恢复执行的时候向它传递新的信息。你可以设法实
现这个功能，让生成器引用一个全局变量或者一个调用者可以修改的可变对象，但
是这些方法都很繁杂。

在 Python 2.5 里有一个简单的将值传递给生成器的方法。*note yield: 190. 变
成了一个表达式，返回一个可以赋给变量或执行操作的值:

     val = (yield i)

我建议你在处理 ‘yield’ 表达式返回值的时候， `总是' 两边写上括号，就像上
面的例子一样。括号并不总是必须的，但是比起记住什么时候需要括号，写出来会
更容易一点。

（ PEP 342(1) 解释了具体的规则，也就是 ‘yield’ 表达式必须括起来，除非是
出现在最顶级的赋值表达式的右边。这意味着你可以写 ‘val = yield i’，但是必
须在操作的时候加上括号，就像‘‘val = (yield i) + 12‘‘）

可以调用 ‘send(value)()’ <generator.send> 方法向生成器发送值。这个方法会
恢复执行生成器的代码，然后 ‘yield’ 表达式返回特定的值。如果调用普通的
‘__next__`方法，``yield`()’ 会返回 ‘None’.

这里有一个简单的每次加1的计数器，并允许改变内部计数器的值。

     def counter(maximum):
         i = 0
         while i < maximum:
             val = (yield i)
             # If value provided, change counter
             if val is not None:
                 i = val
             else:
                 i += 1

这是改变计数器的一个示例

     >>> it = counter(10)
     >>> next(it)
     0
     >>> next(it)
     1
     >>> it.send(8)
     8
     >>> next(it)
     9
     >>> next(it)
     Traceback (most recent call last):
       File "t.py", line 15, in <module>
         it.next()
     StopIteration

因为 ‘yield’ 很多时候会返回 ‘None’，所以你应该总是检查这个情况。不要在表
达式中使用 ‘yield’ 的值，除非你确定 *note send(): 149f. 是唯一的用来恢复
你的生成器函数的方法。

除了 *note send(): 149f. 之外，生成器还有两个其他的方法:

   * *note throw(type, value=None, traceback=None): 14a1. 用于在生成器内
     部抛出异常；这个异常会在生成器暂停执行的时候由 ‘yield’ 表达式抛出。

   * *note generator.close(): 14a3. 会在生成器内部抛出 *note
     GeneratorExit: d3a. 异常来结束迭代。当接收到这个异常时，生成器的代
     码会抛出 *note GeneratorExit: d3a. 或者 *note StopIteration: 48e.；
     捕捉这个异常作其他处理是非法的，并会出发 *note RuntimeError: 2bb.。
     *note close(): 14a3. 也会在 Python 垃圾回收器回收生成器的时候调用。

     如果你要在 *note GeneratorExit: d3a. 发生的时候清理代码，我建议使用
     ‘try: ... finally:’ 组合来代替 *note GeneratorExit: d3a.。

这些改变的累积效应是，让生成器从单向的信息生产者变成了既是生产者，又是消
费者。

生成器也可以成为 `协程' ，一种更广义的子过程形式。子过程可以从一个地方进
入，然后从另一个地方退出（从函数的顶端进入，从 ‘return’ 语句退出），而协
程可以进入，退出，然后在很多不同的地方恢复（‘yield’ 语句）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0342


File: python.info,  Node: 内置函数<2>,  Next: itertools 模块,  Prev: 生成器<2>,  Up: 函数式编程指引

10.5.5 内置函数
---------------

我们可以看看迭代器常常用到的函数的更多细节。

Python 内置的两个函数 *note map(): c35. 和 *note filter(): c36. 复制了生
成器表达式的两个特性:

*note map(f, iterA, iterB, ...): c35. 返回一个遍历序列的迭代器

     ‘f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2],
     iterB[2]), ...’.

          >>> def upper(s):
          ...     return s.upper()

          >>> list(map(upper, ['sentence', 'fragment']))
          ['SENTENCE', 'FRAGMENT']
          >>> [upper(s) for s in ['sentence', 'fragment']]
          ['SENTENCE', 'FRAGMENT']

你当然也可以用列表推导式达到同样的效果。

*note filter(predicate, iter): c36. 返回一个遍历序列中满足指定条件的元素
的迭代器，和列表推导式的功能相似。 `predicate' （谓词）是一个在特定条件
下返回真值的函数；要使用函数 *note filter(): c36.，谓词函数必须只能接受
一个参数。

     >>> def is_even(x):
     ...     return (x % 2) == 0

     >>> list(filter(is_even, range(10)))
     [0, 2, 4, 6, 8]

这也可以写成列表推导式:

     >>> list(x for x in range(10) if is_even(x))
     [0, 2, 4, 6, 8]

*note enumerate(iter, start=0): deb. 计数可迭代对象中的元素，然后返回包
含每个计数（从 `start' 开始）和元素两个值的元组。:

     >>> for item in enumerate(['subject', 'verb', 'object']):
     ...     print(item)
     (0, 'subject')
     (1, 'verb')
     (2, 'object')

*note enumerate(): deb. 常常用于遍历列表并记录达到特定条件时的下标:

     f = open('data.txt', 'r')
     for i, line in enumerate(f):
         if line.strip() == '':
             print('Blank line at line #%i' % i)

*note sorted(iterable, key=None, reverse=False): 44c. 会将 iterable 中的
元素收集到一个列表中，然后排序并返回结果。其中 `key' 和 `reverse' 参数会
传递给所创建列表的 *note sort(): 44d. 方法。:

     >>> import random
     >>> # Generate 8 random numbers between [0, 10000)
     >>> rand_list = random.sample(range(10000), 8)
     >>> rand_list
     [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
     >>> sorted(rand_list)
     [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
     >>> sorted(rand_list, reverse=True)
     [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]

（对排序更详细的讨论可参见 *note 排序指南: 1611.。）

内置函数 *note any(iter): d8c. 和 *note all(iter): d8d. 会查看一个可迭代
对象内容的逻辑值。*note any(): d8c. 在可迭代对象中任意一个元素为真时返回
‘True’，而 *note all(): d8d. 在所有元素为真时返回 ‘True’:

     >>> any([0, 1, 0])
     True
     >>> any([0, 0, 0])
     False
     >>> any([1, 1, 1])
     True
     >>> all([0, 1, 0])
     False
     >>> all([0, 0, 0])
     False
     >>> all([1, 1, 1])
     True

*note zip(iterA, iterB, ...): c3a. 从每个可迭代对象中选取单个元素组成列
表并返回:

     zip(['a', 'b', 'c'], (1, 2, 3)) =>
       ('a', 1), ('b', 2), ('c', 3)

它并不会在内存创建一个列表并因此在返回前而耗尽输入的迭代器；相反，只有在
被请求的时候元组才会创建并返回。（这种行为的技术术语叫惰性计算，参见
lazy evaluation(1).）

这个迭代器设计用于长度相同的可迭代对象。如果可迭代对象的长度不一致，返回
的数据流的长度会和最短的可迭代对象相同

     zip(['a', 'b'], (1, 2, 3)) =>
       ('a', 1), ('b', 2)

然而，你应该避免这种情况，因为所有从更长的迭代器中取出的元素都会被丢弃。
这意味着之后你也无法冒着跳过被丢弃元素的风险来继续使用这个迭代器。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Lazy_evaluation


File: python.info,  Node: itertools 模块,  Next: functools 模块,  Prev: 内置函数<2>,  Up: 函数式编程指引

10.5.6 itertools 模块
---------------------

*note itertools: a4. 模块包含很多常用的迭代器以及用来组合迭代器的函数。
本节会用些小的例子来介绍这个模块的内容。

这个模块里的函数大致可以分为几类：

   * 从已有的迭代器创建新的迭代器的函数。

   * 接受迭代器元素作为参数的函数。

   * 选取部分迭代器输出的函数。

   * 给迭代器输出分组的函数。

* Menu:

* 创建新的迭代器::
* 对元素使用函数::
* 选择元素::
* 组合函数::
* 为元素分组::


File: python.info,  Node: 创建新的迭代器,  Next: 对元素使用函数,  Up: itertools 模块

10.5.6.1 创建新的迭代器
.......................

*note itertools.count(start, step): c23. 返回一个等分的无限数据流。初始
值默认为0，间隔默认为1，你也选择可以指定初始值和间隔:

     itertools.count() =>
       0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
     itertools.count(10) =>
       10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
     itertools.count(10, 5) =>
       10, 15, 20, 25, 30, 35, 40, 45, 50, 55, ...

*note itertools.cycle(iter): 1b4f. 保存一份所提供的可迭代对象的副本，并
返回一个能产生整个可迭代对象序列的新迭代器。新迭代器会无限重复这些元素。
:

     itertools.cycle([1, 2, 3, 4, 5]) =>
       1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...

*note itertools.repeat(elem, [n]): 10c2. 返回 `n' 次所提供的元素，当 `n'
不存在时，返回无数次所提供的元素。

     itertools.repeat('abc') =>
       abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
     itertools.repeat('abc', 5) =>
       abc, abc, abc, abc, abc

*note itertools.chain(iterA, iterB, ...): 1613. 接受任意数量的可迭代对象
作为输入，首先返回第一个迭代器的所有元素，然后是第二个的所有元素，如此一
直进行下去，直到消耗掉所有输入的可迭代对象。

     itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
       a, b, c, 1, 2, 3

*note itertools.islice(iter, [start], stop, [step]): 3aa. 返回一个所输入
的迭代器切片的数据流。如果只单独给定 `stop' 参数的话，它会返回从起始算起
`stop' 个数量的元素。如果你提供了起始下标 `start'，你会得到 `stop-start'
个元素；如果你给定了 `step' 参数，数据流会跳过相应的元素。和 Python 里的
字符串和列表切片不同，你不能在 `start', `stop' 或者 `step' 这些参数中使
用负数。:

     itertools.islice(range(10), 8) =>
       0, 1, 2, 3, 4, 5, 6, 7
     itertools.islice(range(10), 2, 8) =>
       2, 3, 4, 5, 6, 7
     itertools.islice(range(10), 2, 8, 2) =>
       2, 4, 6

*note itertools.tee(iter, [n]): 1b54. 可以复制一个迭代器；它返回 `n' 个
能够返回源迭代器内容的独立迭代器。如果你不提供参数 `n'，默认值为 2。复制
迭代器需要保存源迭代器的一部分内容，因此在源迭代器比较大的时候会显著地占
用内存；同时，在所有新迭代器中，有一个迭代器会比其他迭代器占用更多的内存
。

     itertools.tee( itertools.count() ) =>
        iterA, iterB

     where iterA ->
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...

     and   iterB ->
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...


File: python.info,  Node: 对元素使用函数,  Next: 选择元素,  Prev: 创建新的迭代器,  Up: itertools 模块

10.5.6.2 对元素使用函数
.......................

*note operator: c3. 模块包含一组对应于 Python 操作符的函数。比如 *note
operator.add(a, b): 1b75. （把两个数加起来），*note operator.ne(a, b):
1b65. （和 ‘a != b’ 相同），以及 *note operator.attrgetter(’id’): 724. （
返回获取 ‘.id’ 属性的可调用对象）。

*note itertools.starmap(func, iter): a30. 假定可迭代对象能够返回一个元组
的流，并且利用这些元组作为参数来调用 `func':

     itertools.starmap(os.path.join,
                       [('/bin', 'python'), ('/usr', 'bin', 'java'),
                        ('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')])
     =>
       /bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby


File: python.info,  Node: 选择元素,  Next: 组合函数,  Prev: 对元素使用函数,  Up: itertools 模块

10.5.6.3 选择元素
.................

另外一系列函数根据谓词选取一个迭代器中元素的子集。

*note itertools.filterfalse(predicate, iter): 15fc. 和 *note filter():
c36. 相反，返回所有让 predicate 返回 false 的元素:

     itertools.filterfalse(is_even, itertools.count()) =>
       1, 3, 5, 7, 9, 11, 13, 15, ...

*note itertools.takewhile(predicate, iter): 1b53. 返回一直让 predicate 返
回 true 的元素。一旦 predicate 返回 false，迭代器就会发出终止结果的信号
。:

     def less_than_10(x):
         return x < 10

     itertools.takewhile(less_than_10, itertools.count()) =>
       0, 1, 2, 3, 4, 5, 6, 7, 8, 9

     itertools.takewhile(is_even, itertools.count()) =>
       0

*note itertools.dropwhile(predicate, iter): 1b51. 在 predicate 返回 true
的时候丢弃元素，并且返回可迭代对象的剩余结果。:

     itertools.dropwhile(less_than_10, itertools.count()) =>
       10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...

     itertools.dropwhile(is_even, itertools.count()) =>
       1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...

*note itertools.compress(data, selectors): c22. 接受两个迭代器，然后返回
`data' 中使相应地 `selector' 中的元素为真的元素；它会在任一个迭代器耗尽
的时候停止:

     itertools.compress([1, 2, 3, 4, 5], [True, True, False, False, True]) =>
        1, 2, 5


File: python.info,  Node: 组合函数,  Next: 为元素分组,  Prev: 选择元素,  Up: itertools 模块

10.5.6.4 组合函数
.................

*note itertools.combinations(iterable, r): cae. 返回一个迭代器，它能给出
输入迭代器中所包含的元素的所有可能的 `r' 元元组的组合。:

     itertools.combinations([1, 2, 3, 4, 5], 2) =>
       (1, 2), (1, 3), (1, 4), (1, 5),
       (2, 3), (2, 4), (2, 5),
       (3, 4), (3, 5),
       (4, 5)

     itertools.combinations([1, 2, 3, 4, 5], 3) =>
       (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5),
       (2, 3, 4), (2, 3, 5), (2, 4, 5),
       (3, 4, 5)

每个元组中的元素保持着 `可迭代对象' 返回他们的顺序。例如，在上面的例子中
数字 1 总是会在 2, 3, 4 或 5 前面。一个类似的函数，*note
itertools.permutations(iterable, r=None): ed9.，取消了保持顺序的限制，返
回所有可能的长度为 `r' 的排列:

     itertools.permutations([1, 2, 3, 4, 5], 2) =>
       (1, 2), (1, 3), (1, 4), (1, 5),
       (2, 1), (2, 3), (2, 4), (2, 5),
       (3, 1), (3, 2), (3, 4), (3, 5),
       (4, 1), (4, 2), (4, 3), (4, 5),
       (5, 1), (5, 2), (5, 3), (5, 4)

     itertools.permutations([1, 2, 3, 4, 5]) =>
       (1, 2, 3, 4, 5), (1, 2, 3, 5, 4), (1, 2, 4, 3, 5),
       ...
       (5, 4, 3, 2, 1)

如果你不提供 `r' 参数的值，它会使用可迭代对象的长度，也就是说会排列所有
的元素。

注意这些函数会输出所有可能的位置组合，并不要求 `可迭代对象' 的内容不重复
:

     itertools.permutations('aba', 3) =>
       ('a', 'b', 'a'), ('a', 'a', 'b'), ('b', 'a', 'a'),
       ('b', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a')

同一个元组 ‘('a', 'a', 'b')’ 出现了两次，但是两个 ’a’ 字符来自不同的位置
。

*note itertools.combinations_with_replacement(iterable, r): c21. 函数放
松了一个不同的限制：元组中的元素可以重复。从概念讲，为每个元组第一个位置
选取一个元素，然后在选择第二个元素前替换掉它。:

     itertools.combinations_with_replacement([1, 2, 3, 4, 5], 2) =>
       (1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
       (2, 2), (2, 3), (2, 4), (2, 5),
       (3, 3), (3, 4), (3, 5),
       (4, 4), (4, 5),
       (5, 5)


File: python.info,  Node: 为元素分组,  Prev: 组合函数,  Up: itertools 模块

10.5.6.5 为元素分组
...................

我要讨论的最后一个函数，*note itertools.groupby(iter,key_func=None):
1b52.，是最复杂的函数。 ‘key_func(elem)’ 是一个可以对迭代器返回的每个元
素计算键值的函数。 如果你不提供这个键值函数，它就会简化成每个元素自身。

*note groupby(): 1b52. 从所依据的可迭代对象中连续地收集具有相同值的元素
，然后返回一个长度为2的元组的数据流, 每个元组包含键值以及对应这个键值的
元素所组成的迭代器。

     city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
                  ('Anchorage', 'AK'), ('Nome', 'AK'),
                  ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
                  ...
                 ]

     def get_state(city_state):
         return city_state[1]

     itertools.groupby(city_list, get_state) =>
       ('AL', iterator-1),
       ('AK', iterator-2),
       ('AZ', iterator-3), ...

     where
     iterator-1 =>
       ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
     iterator-2 =>
       ('Anchorage', 'AK'), ('Nome', 'AK')
     iterator-3 =>
       ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')

*note groupby(): 1b52. 假定了所依据的可迭代对象的内容已经根据键值排序。
注意，返回的迭代器也会使用所依据的可迭代对象，所以在请求迭代器 2和相应的
键之前你必须先消耗迭代器 1 的结果。


File: python.info,  Node: functools 模块,  Next: 小函数和 lambda 表达式,  Prev: itertools 模块,  Up: 函数式编程指引

10.5.7 functools 模块
---------------------

Python 2.5 中的 *note functools: 85. 模块包含了一些高阶函数。 `高阶函数'
接受一个或多个函数作为输入，返回新的函数。 这个模块中最有用的工具是
*note functools.partial(): 7d1. 函数。

对于用函数式风格编写的程序，有时你会希望通过给定部分参数，将已有的函数构
变形称新的函数。考虑一个 Python 函数 ‘f(a, b, c)’；你希望创建一个和
‘f(1, b, c)’ 等价的新函数 ‘g(b, c)’；也就是说你给定了 ‘f()’ 的一个参数的
值。这就是所谓的“部分函数应用”。

*note partial(): 7d1. 接受参数 ‘(function, arg1, arg2, ...,
kwarg1=value1, kwarg2=value2)’。它会返回一个可调用的对象，所以你能够直接
调用这个结果以使用给定参数的 ‘function’。

这里有一个很小但很现实的例子:

     import functools

     def log(message, subsystem):
         """Write the contents of 'message' to the specified subsystem."""
         print('%s: %s' % (subsystem, message))
         ...

     server_log = functools.partial(log, subsystem='server')
     server_log('Unable to open socket')

*note functools.reduce(func, iter, [initial_value]): c77. 持续地在可迭代
对象的所有元素上执行操作，因此它不能够用在无限的可迭代对象上。`func' 必
须是一个接受两个元素并返回一个值的函数。*note functools.reduce(): c77. 接
受迭代器返回的前两个元素 A 和 B 并计算 ‘func(A, B)’ 。然后它会请求第三个
元素，C，计算 ‘func(func(A, B), C)’，然后把这个结果再和第四个元素组合并
返回，如此继续下去直到消耗整个可迭代对象。如果输入的可迭代对象完全不返回
任何值，*note TypeError: 193. 异常就会抛出。如果提供了初值(initial
value)，它会被用作起始值，也就是先计算 ‘func(initial_value, A)’ 。:

     >>> import operator, functools
     >>> functools.reduce(operator.concat, ['A', 'BB', 'C'])
     'ABBC'
     >>> functools.reduce(operator.concat, [])
     Traceback (most recent call last):
       ...
     TypeError: reduce() of empty sequence with no initial value
     >>> functools.reduce(operator.mul, [1, 2, 3], 1)
     6
     >>> functools.reduce(operator.mul, [], 1)
     1

如果你在 *note functools.reduce(): c77. 中使用 *note operator.add():
1b75.，你就会把可迭代对象中的所有元素加起来.这种情况非常常见, 所以
Python 有一个特殊的内置函数 *note sum(): 1e6.:

     >>> import functools, operator
     >>> functools.reduce(operator.add, [1, 2, 3, 4], 0)
     10
     >>> sum([1, 2, 3, 4])
     10
     >>> sum([])
     0

不过, 对于很多使用 *note functools.reduce(): c77. 的情形, 使用明显的
*note for: c38. 循环会更清晰:

     import functools
     # Instead of:
     product = functools.reduce(operator.mul, [1, 2, 3], 1)

     # You can write:
     product = 1
     for i in [1, 2, 3]:
         product *= i

一个相关的函数是 *note itertools.accumulate(iterable,
func=operator.add): 1de. 。它执行同样的计算, 不过相对于只返回最终结果，
‘accumulate()’ 会返回一个迭代器来输出所有中间结果:

     itertools.accumulate([1, 2, 3, 4, 5]) =>
       1, 3, 6, 10, 15

     itertools.accumulate([1, 2, 3, 4, 5], operator.mul) =>
       1, 2, 6, 24, 120

* Menu:

* operator 模块::


File: python.info,  Node: operator 模块,  Up: functools 模块

10.5.7.1 operator 模块
......................

前面已经提到了 *note operator: c3. 模块。它包含一系列对应于 Python 操作
符的函数。在函数式风格的代码中，这些函数通常很有用，可以帮你省下不少时间
，避免写一些琐碎的仅仅执行一个简单操作的函数。

这个模块里的一些函数：

   * 数学运算： ‘add()’，‘sub()’，‘mul()’，‘floordiv()’，‘abs()’， ...

   * 逻辑运算： ‘not_()’，‘truth()’。

   * 位运算： ‘and_()’，‘or_()’，‘invert()’。

   * 比较： ‘eq()’，‘ne()’，‘lt()’，‘le()’，‘gt()’，和 ‘ge()’。

   * 确认对象： ‘is_()’，‘is_not()’。

全部函数列表可以参考 operator 模块的文档。


File: python.info,  Node: 小函数和 lambda 表达式,  Next: 修订记录和致谢,  Prev: functools 模块,  Up: 函数式编程指引

10.5.8 小函数和 lambda 表达式
-----------------------------

编写函数式风格程序时，你会经常需要很小的函数，作为谓词函数或者以某种方式
来组合元素。

如果合适的 Python 内置的或者其他模块中的函数，你就一点也不需要定义新的函
数:

     stripped_lines = [line.strip() for line in lines]
     existing_files = filter(os.path.exists, file_list)

如果不存在你需要的函数，你就必须自己编写。一个编写小函数的方式是使用
*note lambda: c37. 表达式。‘lambda’ 接受一组参数以及组合这些参数的表达式
，它会创建一个返回表达式值的匿名函数:

     adder = lambda x, y: x+y

     print_assign = lambda name, value: name + '=' + str(value)

另一种替代方案就是通常的使用 ‘def’ 语句来定义函数:

     def adder(x, y):
         return x + y

     def print_assign(name, value):
         return name + '=' + str(value)

哪一种更受青睐呢？这是一个风格问题；我通常的做法是避免使用 ‘lambda’。

我这么偏好的一个原因是，‘lambda’ 能够定义的函数非常受限。函数的结果必须
能够作为单独的表达式来计算，这意味着你不能使用多路 ‘if... elif... else’
比较，或者 ‘try... except’ 语句。如果你尝试在 ‘lambda’ 语句中做太多事情
，你最终会把表达式过于复杂以至于难以阅读。你能快速的说出下面的代码做了什
么事情吗？:

     import functools
     total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]

你可以弄明白，不过要花上时间来理清表达式来搞清楚发生了什么。使用一个简短
的嵌套的 ‘def’ 语句可以让情况变得更好:

     import functools
     def combine(a, b):
         return 0, a[1] + b[1]

     total = functools.reduce(combine, items)[1]

如果我仅仅使用一个 ‘for’ 循环会更好:

     total = 0
     for a, b in items:
         total += b

或者使用内置的 *note sum(): 1e6. 和一个生成器表达式:

     total = sum(b for a, b in items)

许多使用 *note functools.reduce(): c77. 的情形可以更清晰地写成 ‘for’ 循
环的形式。

Fredrik Lundh 曾经建议以下一组规则来重构 ‘lambda’ 的使用:

  1. 写一个 lambda 函数。

  2. 写一句注释来说明这个 lambda 究竟干了什么。

  3. 研究一会这个注释，然后想出一个抓住注释本质的名字。

  4. 用这个名字，把这个 lambda 改写成 def 语句。

  5. 把注释去掉。

我非常喜欢这些规则，不过你完全有权利争辩这种消除 lambda 的风格是不是更好
。


File: python.info,  Node: 修订记录和致谢,  Next: 参考文献<2>,  Prev: 小函数和 lambda 表达式,  Up: 函数式编程指引

10.5.9 修订记录和致谢
---------------------

作者要感谢以下人员对本文各种草稿给予的建议，更正和协助：Ian Bicking,Nick
Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell,Leandro
Lameiro, Jussi Salmela, Collin Winter, Blake Winton。

0.1 版: 2006 年 6 月 30 日发布。

0.11 版: 2006 年 7 月 1 日发布。 修正拼写错误。

0.2 版: 2006 年 7 月 10 日发布。 将 genexp 与 listcomp 两节合二为一。 修
正拼写错误。

0.21 版: 加入了 tutor 邮件列表中建议的更多参考文件。

0.30 版: 添加了有关 ‘functional’ 模块的小节，由 Collin Winter 撰写；添加
了有关 operator 模块的简短小节；其他少量修改。


File: python.info,  Node: 参考文献<2>,  Prev: 修订记录和致谢,  Up: 函数式编程指引

10.5.10 参考文献
----------------

* Menu:

* 通用文献::
* Python 相关::
* Python 文档::


File: python.info,  Node: 通用文献,  Next: Python 相关,  Up: 参考文献<2>

10.5.10.1 通用文献
..................

`Structure and Interpretation of Computer Programs', Harold Abelson,
Gerald Jay Sussman 和 Julie Sussman 著。全文可见
‘https://mitpress.mit.edu/sicp/’ 。在这部计算机科学的经典教科书中，第二
和第三章讨论了使用序列和流来组织程序内部的数据传递。书中的示例采用
Scheme 语言，但其中这些章节中描述的很多设计方法同样适用于函数式风格的
Python 代码。

‘http://www.defmacro.org/ramblings/fp.html’: 一个使用 Java 示例的函数式
编程的总体介绍，有很长的历史说明。

‘https://en.wikipedia.org/wiki/Functional_programming’: 一般性的函数式编
程的 Wikipedia 条目。

‘https://en.wikipedia.org/wiki/Coroutine’: 协程条目。

‘https://en.wikipedia.org/wiki/Currying’: 函数柯里化条目。


File: python.info,  Node: Python 相关,  Next: Python 文档,  Prev: 通用文献,  Up: 参考文献<2>

10.5.10.2 Python 相关
.....................

‘http://gnosis.cx/TPiP/’：David Mertz 书中的第一章 ‘Text Processing in
Python’，"Utilizing Higher-Order Functions in Text Processing" 标题部分
讨论了文本处理的函数式编程。

Mertz 还在 IBM 的 DeveloperWorks 站点上针对函数式编程撰写了一系列共 3 篇
文章；参见 part 1(1), part 2(2) 和 part 3(3),

   ---------- Footnotes ----------

   (1) https://developer.ibm.com/articles/l-prog/

   (2) https://developer.ibm.com/tutorials/l-prog2/

   (3) https://developer.ibm.com/tutorials/l-prog3/


File: python.info,  Node: Python 文档,  Prev: Python 相关,  Up: 参考文献<2>

10.5.10.3 Python 文档
.....................

*note itertools: a4. 模块文档。

*note functools: 85. 模块文档。

*note operator: c3. 模块文档。

PEP 289(1): "Generator Expressions"

PEP 342(2): "Coroutines via Enhanced Generators" 描述了 Python 2.5 中新
的生成器特性。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0289

   (2) https://www.python.org/dev/peps/pep-0342


File: python.info,  Node: 日志常用指引,  Next: 日志操作手册,  Prev: 函数式编程指引,  Up: Python 常用指引

10.6 日志常用指引
=================


作者: Vinay Sajip <vinay_sajip at red-dove dot com>

* Menu:

* 日志基础教程::
* 进阶日志教程::
* 日志级别: 日志级别<2>.
* 有用的处理程序::
* 记录日志中引发的异常::
* 使用任意对象作为消息::
* 优化::


File: python.info,  Node: 日志基础教程,  Next: 进阶日志教程,  Up: 日志常用指引

10.6.1 日志基础教程
-------------------

日志是对软件执行时所发生事件的一种追踪方式。软件开发人员对他们的代码添加
日志调用，借此来指示某事件的发生。一个事件通过一些包含变量数据的描述信息
来描述（比如：每个事件发生时的数据都是不同的）。开发者还会区分事件的重要
性，重要性也被称为 `等级' 或 `严重性'

* Menu:

* 什么时候使用日志::
* 一个简单的例子: 一个简单的例子<2>.
* 记录日志到文件::
* 从多个模块记录日志::
* 记录变量数据::
* 更改显示消息的格式::
* 在消息中显示日期/时间::
* 后续步骤::


File: python.info,  Node: 什么时候使用日志,  Next: 一个简单的例子<2>,  Up: 日志基础教程

10.6.1.1 什么时候使用日志
.........................

对于简单的日志使用来说日志功能提供了一系列便利的函数。它们是 *note
debug(): 2098.，*note info(): 20c3.，*note warning(): 20d5.，*note
error(): 20d6. 和 *note critical(): 20d7.。想要决定何时使用日志，请看下
表，其中显示了对于每个通用任务集合来说最好的工具。

你想要执行的任务                          此任务最好的工具
                                          
-------------------------------------------------------------------------------------
                                          
对于命令行或程序的应用，结果显示在控制    *note print(): 88f.
台。                                      

在对程序的普通操作发生时提交事件报告(比   *note logging.info(): 20c3. 函数(当有诊
如：状态监控和错误调查)                   断目的需要详细输出信息时使用
                                          *note logging.debug(): 2098. 函数)
                                          
                                          
提出一个警告信息基于一个特殊的运行时事    *note warnings.warn(): e60. 位于代码库中
件                                        ，该事件是可以避免的，需要修改客户端应用
                                          以消除告警
                                          
                                          *note logging.warning(): 20d5. 不需要修
                                          改客户端应用，但是该事件还是需要引起关注
                                          
                                          
对一个特殊的运行时事件报告错误            引发异常
                                          
                                          
报告错误而不引发异常(如在长时间运行中的   *note logging.error(): 20d6,
服务端进程的错误处理)                     *note logging.exception(): 20d8. 或
                                          *note logging.critical(): 20d7. 分别适用
                                          于特定的错误及应用领域
                                          

日志功能应以所追踪事件级别或严重性而定。各级别适用性如下（以严重性递增）
：

级别               何时使用
                   
---------------------------------------------------------------------
                   
‘DEBUG’            细节信息，仅当诊断问题时适用。
                   
                   
‘INFO’             确认程序按预期运行
                   
                   
‘WARNING’          表明有已经或即将发生的意外（例如：磁盘空间不足
                   ）。程序仍按预期进行
                   
                   
‘ERROR’            由于严重的问题，程序的某些功能已经不能正常执行
                   
                   
‘CRITICAL’         严重的错误，表明程序已不能继续执行
                   

默认的级别是‘‘WARNING‘‘，意味着只会追踪该级别及以上的事件，除非更改日志
配置。

所追踪事件可以以不同形式处理。最简单的方式是输出到控制台。另一种常用的方
式是写入磁盘文件。


File: python.info,  Node: 一个简单的例子<2>,  Next: 记录日志到文件,  Prev: 什么时候使用日志,  Up: 日志基础教程

10.6.1.2 一个简单的例子
.......................

一个非常简单的例子：

     import logging
     logging.warning('Watch out!')  # will print a message to the console
     logging.info('I told you so')  # will not print anything

如果你在命令行中输入这些代码并运行，你将会看到：

     WARNING:root:Watch out!

输出到命令行。‘INFO’ 消息并没有出现，因为默认级别是 ‘WARNING’ 。打印的信
息包含事件的级别以及在日志调用中的对于事件的描述，例如“Watch out!”。暂时
不用担心“root”部分：之后会作出解释。输出格式可按需要进行调整，格式化选项
同样会在之后作出解释。


File: python.info,  Node: 记录日志到文件,  Next: 从多个模块记录日志,  Prev: 一个简单的例子<2>,  Up: 日志基础教程

10.6.1.3 记录日志到文件
.......................

一种非常常见的情况是将日志事件记录到文件，让我们继续往下看。请确认启动新
的Python 解释器，不要在上一个环境中继续操作:

     import logging
     logging.basicConfig(filename='example.log',level=logging.DEBUG)
     logging.debug('This message should go to the log file')
     logging.info('So should this')
     logging.warning('And this, too')

现在，如果我们打开日志文件，我们应当能看到日志信息：

     DEBUG:root:This message should go to the log file
     INFO:root:So should this
     WARNING:root:And this, too

该示例同样展示了如何设置日志追踪级别的阈值。该示例中，由于我们设置的阈值
是 ‘DEBUG’，所有信息全部打印

如果你想从命令行设置日志级别，例如：

     --log=INFO

并且在一些 `loglevel' 变量中你可以获得 ‘--log’ 命令的参数，你可以使用：

     getattr(logging, loglevel.upper())

通过 `level' 参数获得你将传递给 *note basicConfig(): 1e1. 的值。你需要对
用户输入数据进行错误排查，可如下例：

     # assuming loglevel is bound to the string value obtained from the
     # command line argument. Convert to upper case to allow the user to
     # specify --log=DEBUG or --log=debug
     numeric_level = getattr(logging, loglevel.upper(), None)
     if not isinstance(numeric_level, int):
         raise ValueError('Invalid log level: %s' % loglevel)
     logging.basicConfig(level=numeric_level, ...)

对 *note basicConfig(): 1e1. 的调用应该在 *note debug(): 2098. ， *note
info(): 20c3. 等的前面。因为它被设计为一次性的配置，只有第一次调用会进行
操作，随后的调用不会产生有效操作。

如果多次运行上述脚本，则连续运行的消息将追加到文件 `example.log' 。 如果
你希望每次运行重新开始，而不是记住先前运行的消息，则可以通过将上例中的调
用更改为来指定 `filemode' 参数:

     logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)

输出将与之前相同，但不再追加进日志文件，因此早期运行的消息将丢失。


File: python.info,  Node: 从多个模块记录日志,  Next: 记录变量数据,  Prev: 记录日志到文件,  Up: 日志基础教程

10.6.1.4 从多个模块记录日志
...........................

如果你的程序包含多个模块，这里有一个如何组织日志记录的示例:

     # myapp.py
     import logging
     import mylib

     def main():
         logging.basicConfig(filename='myapp.log', level=logging.INFO)
         logging.info('Started')
         mylib.do_something()
         logging.info('Finished')

     if __name__ == '__main__':
         main()

     # mylib.py
     import logging

     def do_something():
         logging.info('Doing something')

如果你运行 `myapp.py' ，你应该在 `myapp.log' 中看到：

     INFO:root:Started
     INFO:root:Doing something
     INFO:root:Finished

这是你期待看到的。 你可以使用 `mylib.py' 中的模式将此概括为多个模块。 请
注意，对于这种简单的使用模式，除了查看事件描述之外，你不能通过查看日志文
件来了解应用程序中消息的 `来源' 。 如果要跟踪消息的位置，则需要参考教程
级别以外的文档 - 请参阅 *note 进阶日志教程: b7b. 。


File: python.info,  Node: 记录变量数据,  Next: 更改显示消息的格式,  Prev: 从多个模块记录日志,  Up: 日志基础教程

10.6.1.5 记录变量数据
.....................

要记录变量数据，请使用格式字符串作为事件描述消息，并将变量数据作为参数附
加。 例如:

     import logging
     logging.warning('%s before you %s', 'Look', 'leap!')

将显示：

     WARNING:root:Look before you leap!

如你所见，将可变数据合并到事件描述消息中使用旧的 %-s形式的字符串格式化。
这是为了向后兼容：logging 包的出现时间早于较新的格式化选项例如 *note
str.format(): 4e2. 和 *note string.Template: 3f3.。 这些较新格式化选项
`是' 受支持的，但探索它们超出了本教程的范围：有关详细信息，请参阅 *note
生效于整个应用程序的格式化样式: 20bb.。


File: python.info,  Node: 更改显示消息的格式,  Next: 在消息中显示日期/时间,  Prev: 记录变量数据,  Up: 日志基础教程

10.6.1.6 更改显示消息的格式
...........................

要更改用于显示消息的格式，你需要指定要使用的格式:

     import logging
     logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
     logging.debug('This message should appear on the console')
     logging.info('So should this')
     logging.warning('And this, too')

这将输出：

     DEBUG:This message should appear on the console
     INFO:So should this
     WARNING:And this, too

请注意，前面示例中出现的“root”已消失。 对于可以出现在格式字符串中的全部
内容，你可以参考以下文档 *note LogRecord 属性: 20b9. ，但为了简单使用，
你只需要 `levelname' （严重性）， `message' （事件描述，包括可变数据），
也许在事件发生时显示。 这将在下一节中介绍。


File: python.info,  Node: 在消息中显示日期/时间,  Next: 后续步骤,  Prev: 更改显示消息的格式,  Up: 日志基础教程

10.6.1.7 在消息中显示日期/时间
..............................

要显示事件的日期和时间，你可以在格式字符串中放置 ’%(asctime)s’

     import logging
     logging.basicConfig(format='%(asctime)s %(message)s')
     logging.warning('is when this event was logged.')

应该打印这样的东西：

     2010-12-12 11:41:42,612 is when this event was logged.

日期/时间显示的默认格式（如上所示）类似于 ISO8601 或 RFC 3339(1) 。 如果
你需要更多地控制日期/时间的格式，请为 ‘basicConfig’ 提供 `datefmt' 参数
，如下例所示:

     import logging
     logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
     logging.warning('is when this event was logged.')

这会显示如下内容：

     12/12/2010 11:46:36 AM is when this event was logged.

`datefmt' 参数的格式与 *note time.strftime(): b6d. 支持的格式相同。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3339.html


File: python.info,  Node: 后续步骤,  Prev: 在消息中显示日期/时间,  Up: 日志基础教程

10.6.1.8 后续步骤
.................

基本教程到此结束。 它应该足以让你启动并运行日志记录。 日志包提供了更多功
能，但为了充分利用它，你需要花更多的时间来阅读以下部分。 如果你准备好了
，可以拿一些你最喜欢的饮料然后继续。

如果你的日志记录需求很简单，那么使用上面的示例将日志记录合并到你自己的脚
本中，如果你遇到问题或者不理解某些内容，请在 comp.lang.python Usenet 组
上发布一个问题（在
‘https://groups.google.com/forum/#!forum/comp.lang.python’ ） ，你应该在
短时间内得到帮助。

还不够？ 你可以继续阅读接下来的几个部分，这些部分提供了比上面基本部分更
高级或深入的教程。 之后，你可以看一下 *note 日志操作手册: b7c. 。


File: python.info,  Node: 进阶日志教程,  Next: 日志级别<2>,  Prev: 日志基础教程,  Up: 日志常用指引

10.6.2 进阶日志教程
-------------------

日志库采用模块化方法，并提供几类组件：记录器、处理程序、过滤器和格式化程
序。

   * 记录器暴露了应用程序代码直接使用的接口。

   * 处理器将日志记录（由记录器创建）发送到适当的目标。

   * 过滤器提供了更精细的附加功能，用于确定要输出的日志记录。

   * 格式器指定最终输出中日志记录的样式。

日志事件信息在 *note LogRecord: 90e. 实例中的记录器、处理程序、过滤器和
格式化程序之间传递。

通过调用 *note Logger: 3af. 类（以下称为 `loggers' ， 记录器）的实例来执
行日志记录。 每个实例都有一个名称，它们在概念上以点（句点）作为分隔符排
列在命名空间的层次结构中。 例如，名为 ’scan’ 的记录器是记录器
’scan.text’ ，’scan.html’ 和 ’scan.pdf’ 的父级。 记录器名称可以是你想要
的任何名称，并指示记录消息源自的应用程序区域。

在命名记录器时使用的一个好习惯是在每个使用日志记录的模块中使用模块级记录
器，命名如下:

     logger = logging.getLogger(__name__)

这意味着记录器名称跟踪包或模块的层次结构，并且直观地从记录器名称显示记录
事件的位置。

记录器层次结构的根称为根记录器。 这是函数 *note debug(): 2098. 、 *note
info(): 20c3. 、 *note warning(): 20d5. 、 *note error(): 20d6. 和 *note
critical(): 20d7. 使用的记录器，它们只调用根记录器的同名方法。 功能和方
法具有相同的签名。 根记录器的名称在记录的输出中打印为 ’root’ 。

当然，可以将消息记录到不同的地方。 软件包中的支持包含，用于将日志消息写
入文件、 HTTP GET/POST 位置、通过 SMTP 发送电子邮件、通用套接字、队列或
特定于操作系统的日志记录机制（如 syslog 或 Windows NT 事件日志）。 目标
由 `handler' 类提供。 如果你有任何内置处理程序类未满足的特殊要求，则可以
创建自己的日志目标类。

默认情况下，没有为任何日志记录消息设置目标。 你可以使用 *note
basicConfig(): 1e1. 指定目标（例如控制台或文件），如教程示例中所示。 如
果你调用函数 *note debug(): 2098. 、 *note info(): 20c3. 、 *note
warning(): 20d5. 、 *note error(): 20d6. 和 *note critical(): 20d7. ，他
们将检查是否有设置目的地；如果没有设置，它们将在委托给根记录器进行实际的
消息输出之前设置目标为控制台（ ‘sys.stderr’ ）和默认格式的显示消息。

由 *note basicConfig(): 1e1. 设置的消息默认格式为：

     severity:logger name:message

你可以通过使用 `format' 参数将格式字符串传递给 *note basicConfig(): 1e1.
来更改此设置。有关如何构造格式字符串的所有选项，请参阅 *note 格式器对象:
20b7. 。

* Menu:

* 记录流程::
* 记录器::
* 处理程序::
* 格式化程序::
* 配置日志记录::
* 如果没有提供配置会发生什么::
* 配置库的日志记录::


File: python.info,  Node: 记录流程,  Next: 记录器,  Up: 进阶日志教程

10.6.2.1 记录流程
.................

记录器和处理程序中的日志事件信息流程如下图所示。

[python-figures/logging_flow]

File: python.info,  Node: 记录器,  Next: 处理程序,  Prev: 记录流程,  Up: 进阶日志教程

10.6.2.2 记录器
...............

*note Logger: 3af. 对象有三重任务。首先，它们向应用程序代码公开了几种方
法，以便应用程序可以在运行时记录消息。其次，记录器对象根据严重性（默认过
滤工具）或过滤器对象确定要处理的日志消息。第三，记录器对象将相关的日志消
息传递给所有感兴趣的日志处理程序。

记录器对象上使用最广泛的方法分为两类：配置和消息发送。

这些是最常见的配置方法：

   * *note Logger.setLevel(): 2091. 指定记录器将处理的最低严重性日志消息
     ，其中 debug 是最低内置严重性级别， critical 是最高内置严重性级别。
     例如，如果严重性级别为 INFO ，则记录器将仅处理 INFO 、 WARNING 、
     ERROR 和 CRITICAL 消息，并将忽略 DEBUG 消息。

   * *note Logger.addHandler(): 209e. 和 *note Logger.removeHandler():
     209f. 从记录器对象中添加和删除处理程序对象。处理程序在以下内容中有
     更详细的介绍 *note 处理程序: 4152. 。

   * *note Logger.addFilter(): 209b. 和 *note Logger.removeFilter():
     209c. 可以添加或移除记录器对象中的过滤器。 *note Filter 对象: 20c0.
     包含更多的过滤器细节。

你不需要始终在你创建的每个记录器上调用这些方法。 请参阅本节的最后两段。

配置记录器对象后，以下方法将创建日志消息：

   * *note Logger.debug(): 719. 、 *note Logger.info(): 2097. 、 *note
     Logger.warning(): 2099. 、 *note Logger.error(): 209a. 和 *note
     Logger.critical(): 718. 都创建日志记录，包含消息和与其各自方法名称
     对应的级别。该消息实际上是一个格式化字符串，它可能包含标题字符串替
     换语法 ‘%s’ 、 ‘%d’ 、 ‘%f’ 等等。其余参数是与消息中的替换字段对应
     的对象列表。关于 ‘**kwargs’ ，日志记录方法只关注 ‘exc_info’ 的关键
     字，并用它来确定是否记录异常信息。

   * *note Logger.exception(): 717. 创建与 *note Logger.error(): 209a. 相
     似的日志信息。 不同之处是， *note Logger.exception(): 717. 同时还记
     录当前的堆栈追踪。仅从异常处理程序调用此方法。

   * *note Logger.log(): 716. 将日志级别作为显式参数。对于记录消息而言，
     这比使用上面列出的日志级别方便方法更加冗长，但这是自定义日志级别的
     方法。

*note getLogger(): 208f. 返回对具有指定名称的记录器实例的引用（如果已提
供），或者如果没有则返回 ‘root’ 。名称是以句点分隔的层次结构。多次调用
*note getLogger(): 208f. 具有相同的名称将返回对同一记录器对象的引用。在
分层列表中较低的记录器是列表中较高的记录器的子项。例如，给定一个名为
‘foo’ 的记录器，名称为 ‘foo.bar’ 、 ‘foo.bar.baz’ 和 ‘foo.bam’ 的记录器
都是 ‘foo’ 子项。

记录器具有 `有效等级' 的概念。如果未在记录器上显式设置级别，则使用其父级
别作为其有效级别。如果父级没有明确的级别设置，则检查 `其' 父级。依此类推
，搜索所有上级元素，直到找到明确设置的级别。根记录器始终具有显式级别集（
默认情况下为 ‘WARNING’ ）。在决定是否处理事件时，记录器的有效级别用于确
定事件是否传递给记录器的处理程序。

子记录器将消息传播到与其上级记录器关联的处理程序。因此，不必为应用程序使
用的所有记录器定义和配置处理程序。为顶级记录器配置处理程序并根据需要创建
子记录器就足够了。（但是，你可以通过将记录器的 `propagate' 属性设置
‘False’ 来关闭传播。）


File: python.info,  Node: 处理程序,  Next: 格式化程序,  Prev: 记录器,  Up: 进阶日志教程

10.6.2.3 处理程序
.................

*note Handler: 2096. 对象负责将适当的日志消息（基于日志消息的严重性）分
派给处理程序的指定目标。 *note Logger: 3af. 对象可以使用 *note
addHandler(): 209e. 方法向自己添加零个或多个处理程序对象。作为示例场景，
应用程序可能希望将所有日志消息发送到日志文件，将错误或更高的所有日志消息
发送到标准输出，以及将所有关键消息发送至一个邮件地址。 此方案需要三个单
独的处理程序，其中每个处理程序负责将特定严重性的消息发送到特定位置。

标准库包含很多处理程序类型（参见 *note 有用的处理程序: 4154. ）；教程主
要使用 *note StreamHandler: b7d. 和 *note FileHandler: 20fa. 。

处理程序中很少有方法可供应用程序开发人员使用。与使用内置处理程序对象（即
不创建自定义处理程序）的应用程序开发人员相关的唯一处理程序方法是以下配置
方法：

   * ‘setLevel()’ 方法，就像在记录器对象中一样，指定将被分派到适当目标的
     最低严重性。为什么有两个 ‘setLevel()’ 方法？记录器中设置的级别确定
     将传递给其处理程序的消息的严重性。每个处理程序中设置的级别确定处理
     程序将发送哪些消息。

   * *note setFormatter(): 20ac. 选择一个该处理程序使用的 Formatter 对象
     。

   * *note addFilter(): 20ad. 和 *note removeFilter(): 20ae. 分别在处理
     程序上配置和取消配置过滤器对象。

应用程序代码不应直接实例化并使用 *note Handler: 2096. 的实例。 相反，
*note Handler: 2096. 类是一个基类，它定义了所有处理程序应该具有的接口，
并建立了子类可以使用（或覆盖）的一些默认行为。


File: python.info,  Node: 格式化程序,  Next: 配置日志记录,  Prev: 处理程序,  Up: 进阶日志教程

10.6.2.4 格式化程序
...................

格式化程序对象配置日志消息的最终顺序、结构和内容。 与 *note
logging.Handler: 2096. 类不同，应用程序代码可以实例化格式化程序类，但如
果应用程序需要特殊行为，则可能会对格式化程序进行子类化。构造函数有三个可
选参数 —— 消息格式字符串、日期格式字符串和样式指示符。

 -- 方法: logging.Formatter.__init__ (fmt=None, datefmt=None, style='%')

如果没有消息格式字符串，则默认使用原始消息。如果没有日期格式字符串，则默
认日期格式为：

     %Y-%m-%d %H:%M:%S

最后加上毫秒数。 ‘style’ 是 ‘％’，’{ ’ 或 ’$’ 之一。 如果未指定其中一个
，则将使用 ’％’。

如果 ‘style’ 是 ’％’，则消息格式字符串使用 ‘%(<dictionary key>)s’ 样式字
符串替换；可能的键值在 *note LogRecord 属性: 20b9. 中。 如果样式为 ’{’，
则假定消息格式字符串与 *note str.format(): 4e2. （使用关键字参数）兼容，
而如果样式为 ’$’ ，则消息格式字符串应符合 *note
string.Template.substitute(): 130f. 。

在 3.2 版更改: 添加 ‘style’ 形参。

以下消息格式字符串将以人类可读的格式记录时间、消息的严重性以及消息的内容
，按此顺序:

     '%(asctime)s - %(levelname)s - %(message)s'

格式化程序使用用户可配置的函数将记录的创建时间转换为元组。 默认情况下，
使用 *note time.localtime(): f5d. ；要为特定格式化程序实例更改此项，请将
实例的 ‘converter’ 属性设置为具有相同签名的函数 *note time.localtime():
f5d. 或 *note time.gmtime(): b47. 。 要为所有格式化程序更改它，例如，如
果你希望所有记录时间都以 GMT 显示，请在格式化程序类中设置 ‘converter’ 属
性（对于 GMT 显示，设置为 ‘time.gmtime’ ）。


File: python.info,  Node: 配置日志记录,  Next: 如果没有提供配置会发生什么,  Prev: 格式化程序,  Up: 进阶日志教程

10.6.2.5 配置日志记录
.....................

开发者可以通过三种方式配置日志记录：

  1. 使用调用上面列出的配置方法的 Python 代码显式创建记录器、处理程序和
     格式化程序。

  2. 创建日志配置文件并使用 *note fileConfig(): 3b1. 函数读取它。

  3. 创建配置信息字典并将其传递给 *note dictConfig(): b33. 函数。

有关最后两个选项的参考文档，请参阅 *note 配置函数: c90. 。 以下示例使用
Python 代码配置一个非常简单的记录器/一个控制台处理程序和一个简单的格式化
程序:

     import logging

     # create logger
     logger = logging.getLogger('simple_example')
     logger.setLevel(logging.DEBUG)

     # create console handler and set level to debug
     ch = logging.StreamHandler()
     ch.setLevel(logging.DEBUG)

     # create formatter
     formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

     # add formatter to ch
     ch.setFormatter(formatter)

     # add ch to logger
     logger.addHandler(ch)

     # 'application' code
     logger.debug('debug message')
     logger.info('info message')
     logger.warning('warn message')
     logger.error('error message')
     logger.critical('critical message')

从命令行运行此模块将生成以下输出：

     $ python simple_logging_module.py
     2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
     2005-03-19 15:10:26,620 - simple_example - INFO - info message
     2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
     2005-03-19 15:10:26,697 - simple_example - ERROR - error message
     2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message

以下 Python 模块创建的记录器、处理程序和格式化程序几乎与上面列出的示例中
的相同，唯一的区别是对象的名称:

     import logging
     import logging.config

     logging.config.fileConfig('logging.conf')

     # create logger
     logger = logging.getLogger('simpleExample')

     # 'application' code
     logger.debug('debug message')
     logger.info('info message')
     logger.warning('warn message')
     logger.error('error message')
     logger.critical('critical message')

这是 logging.conf 文件：

     [loggers]
     keys=root,simpleExample

     [handlers]
     keys=consoleHandler

     [formatters]
     keys=simpleFormatter

     [logger_root]
     level=DEBUG
     handlers=consoleHandler

     [logger_simpleExample]
     level=DEBUG
     handlers=consoleHandler
     qualname=simpleExample
     propagate=0

     [handler_consoleHandler]
     class=StreamHandler
     level=DEBUG
     formatter=simpleFormatter
     args=(sys.stdout,)

     [formatter_simpleFormatter]
     format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
     datefmt=

输出几乎与不基于配置文件的示例相同：

     $ python simple_logging_config.py
     2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
     2005-03-19 15:38:55,979 - simpleExample - INFO - info message
     2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
     2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
     2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message

你可以看到配置文件方法比 Python 代码方法有一些优势，主要是配置和代码的分
离以及非开发者轻松修改日志记录属性的能力。

     警告: *note fileConfig(): 3b1. 函数接受一个默认参数
     ‘disable_existing_loggers’ ，出于向后兼容的原因，默认为 ‘True’ 。这
     可能是你想要的，也可能不是你想要的，因为除非在配置中明确命名它们（
     或一个上级节点中），否则它将导致在 *note fileConfig(): 3b1. 调用之
     前存在的任何非 root 记录器被禁用。有关更多信息，请参阅参考文档，如
     果需要，请为此参数指定 ‘False’ 。

     传递给 *note dictConfig(): b33. 的字典也可以用键
     ‘disable_existing_loggers’ 指定一个布尔值，如果没有在字典中明确指定
     ，也默认被解释为 ‘True’ 。这会导致上面描述的记录器禁用行为，这可能
     不是你想要的——在这种情况下，明确地为键提供 ‘False’ 值。

请注意，配置文件中引用的类名称需要相对于日志记录模块，或者可以使用常规导
入机制解析的绝对值。因此，你可以使用 *note WatchedFileHandler: 210b. （
相对于日志记录模块）或 ‘mypackage.mymodule.MyHandler’ （对于在
‘mypackage’ 包中定义的类和模块 ‘mymodule’ ，其中 ‘mypackage’ 在Python导
入路径上可用）。

在 Python 3.2 中，引入了一种新的配置日志记录的方法，使用字典来保存配置信
息。 这提供了上述基于配置文件方法的功能的超集，并且是新应用程序和部署的
推荐配置方法。 因为 Python 字典用于保存配置信息，并且由于你可以使用不同
的方式填充该字典，因此你有更多的配置选项。 例如，你可以使用 JSON 格式的
配置文件，或者如果你有权访问 YAML 处理功能，则可以使用 YAML 格式的文件来
填充配置字典。当然，你可以在 Python 代码中构造字典，通过套接字以 pickle
形式接收它，或者使用对你的应用程序合理的任何方法。

以下是与上述相同配置的示例，采用 YAML 格式，用于新的基于字典的方法：

     version: 1
     formatters:
       simple:
         format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
     handlers:
       console:
         class: logging.StreamHandler
         level: DEBUG
         formatter: simple
         stream: ext://sys.stdout
     loggers:
       simpleExample:
         level: DEBUG
         handlers: [console]
         propagate: no
     root:
       level: DEBUG
       handlers: [console]

有关使用字典进行日志记录的更多信息，请参阅 *note 配置函数: c90. 。


File: python.info,  Node: 如果没有提供配置会发生什么,  Next: 配置库的日志记录,  Prev: 配置日志记录,  Up: 进阶日志教程

10.6.2.6 如果没有提供配置会发生什么
...................................

如果未提供日志记录配置，则可能出现需要输出日志记录事件但无法找到输出事件
的处理程序的情况。 在这些情况下，日志包的行为取决于 Python 版本。

对于3.2之前的Python版本，行为如下：

   * 如果 `logging.raiseExceptions' 为 ‘False’ （生产模式），则会以静默
     方式丢弃该事件。

   * 如果 `logging.raiseExceptions' 为 ‘True’ （开发模式），则会打印一条
     消息“无法找到记录器 X.Y.Z 的处理程序”。

在 Python 3.2 及更高版本中，行为如下：

   * 事件使用“最后的处理程序”输出，存储在 ‘logging.lastResort’ 中。 这个
     内部处理程序与任何记录器都没有关联，它的作用类似于 *note
     StreamHandler: b7d. ，它将事件描述消息写入 ‘sys.stderr’ 的当前值（
     因此服从任何可能的重定向影响）。 没有对消息进行格式化——只打印裸事件
     描述消息。处理程序的级别设置为“警告”，因此将输出此级别和更高级别的
     所有事件。

要获得 3.2 之前的行为， ‘logging.lastResort’ 可以设置为 ‘None’ 。


File: python.info,  Node: 配置库的日志记录,  Prev: 如果没有提供配置会发生什么,  Up: 进阶日志教程

10.6.2.7 配置库的日志记录
.........................

在开发使用日志记录的库时，你应该注意记录库如何使用日志记录——例如，使用的
记录器的名称。还需要考虑其日志记录配置。如果应用程序不使用日志记录，并且
库代码进行日志记录调用，那么（如上一节所述）严重性为“WARNING”及更高级别
的事件将打印到 ‘sys.stderr’ 。这被认为是最好的默认行为。

如果由于某种原因，你 `不' 希望在没有任何日志记录配置的情况下打印这些消息
，则可以将无操作处理程序附加到库的顶级记录器。这样可以避免打印消息，因为
将始终为库的事件找到处理程序：它不会产生任何输出。如果库用户配置应用程序
使用的日志记录，可能是配置将添加一些处理程序，如果级别已适当配置，则在库
代码中进行的日志记录调用将正常地将输出发送给这些处理程序。

日志包中包含一个不做任何事情的处理程序： *note NullHandler: c24. （自
Python 3.1 起）。可以将此处理程序的实例添加到库使用的日志记录命名空间的
顶级记录器中（ `如果' 你希望在没有日志记录配置的情况下阻止库的记录事件输
出到 ‘sys.stderr’ ）。如果库 `foo' 的所有日志记录都是使用名称匹配
’foo.x’ ， ’foo.x.y’ 等的记录器完成的，那么代码:

     import logging
     logging.getLogger('foo').addHandler(logging.NullHandler())

应该有预计的效果。如果一个组织生成了许多库，则指定的记录器名称可以是
“orgname.foo” 而不仅仅是 “foo” 。

     注解: 强烈建议你 `不要将' *note NullHandler: c24. `以外的任何处理程
     序添加到库的记录器中' 。这是因为处理程序的配置是使用你的库的应用程
     序开发人员的权利。应用程序开发人员了解他们的目标受众以及哪些处理程
     序最适合他们的应用程序：如果你在“底层”添加处理程序，则可能会干扰他
     们执行单元测试和提供符合其要求的日志的能力。


File: python.info,  Node: 日志级别<2>,  Next: 有用的处理程序,  Prev: 进阶日志教程,  Up: 日志常用指引

10.6.3 日志级别
---------------

日志记录级别的数值在下表中给出。如果你想要定义自己的级别，并且需要它们具
有相对于预定义级别的特定值，那么这些内容可能是你感兴趣的。如果你定义具有
相同数值的级别，它将覆盖预定义的值; 预定义的名称丢失。

级别               数值
                   
---------------------------------------
                   
‘CRITICAL’         50
                   
                   
‘ERROR’            40
                   
                   
‘WARNING’          30
                   
                   
‘INFO’             20
                   
                   
‘DEBUG’            10
                   
                   
‘NOTSET’           0
                   

级别也可以与记录器相关联，由开发人员设置或通过加载已保存的日志记录配置。
在记录器上调用日志记录方法时，记录器会将其自己的级别与与方法调用关联的级
别进行比较。如果记录器的级别高于方法调用的级别，则实际上不会生成任何记录
消息。这是控制日志记录输出详细程度的基本机制。

记录消息被编码为 *note LogRecord: 90e. 类的实例。当记录器决定实际记录事
件时，从记录消息创建 *note LogRecord: 90e. 实例。

记录消息通过使用 `handlers' 进行调度机制，它们是 *note Handler: 2096. 类
的子类的实例。处理程序负责确保记录的消息（以 *note LogRecord: 90e. 的形
式）最终位于特定位置（或一组位置），这对该消息的目标受众（例如最终用户、
支持服务台员工、系统管理员、开发人员）。传递处理程序用于特定目标的 *note
LogRecord: 90e. 实例。 每个记录器可以有零个、一个或多个与之关联的处理程
序（通过 *note Logger: 3af. 的 *note addHandler(): 209e. 方法）。除了与
记录器直接关联的任何处理程序之外，还调用与记录器的 `所有祖先相关联的所有
处理程序来分派消息（除非记录器的 *propagate' 标志设置为false值，这将停止
传递到上级处理程序）。

就像记录器一样，处理程序可以具有与它们相关联的级别。处理程序的级别作为过
滤器，其方式与记录器级别相同。如果处理程序决定调度一个事件，则使用
‘emit()’ 方法将消息发送到其目标。大多数用户定义的 *note Handler: 2096. 子
类都需要重载 ‘emit()’ 。

* Menu:

* 自定义级别::


File: python.info,  Node: 自定义级别,  Up: 日志级别<2>

10.6.3.1 自定义级别
...................

定义你自己的级别是可能的，但不一定是必要的，因为现有级别是根据实践经验选
择的。但是，如果你确信需要自定义级别，那么在执行此操作时应特别小心，如果
你正在开发库，则 `定义自定义级别可能是一个非常糟糕的主意' 。 这是因为如
果多个库作者都定义了他们自己的自定义级别，那么使用开发人员很难控制和解释
这些多个库的日志记录输出，因为给定的数值可能意味着不同的东西 对于不同的
库。


File: python.info,  Node: 有用的处理程序,  Next: 记录日志中引发的异常,  Prev: 日志级别<2>,  Up: 日志常用指引

10.6.4 有用的处理程序
---------------------

作为 *note Handler: 2096. 基类的补充，提供了很多有用的子类：

  1. *note StreamHandler: b7d. 实例发送消息到流（类似文件对象）。

  2. *note FileHandler: 20fa. 实例将消息发送到硬盘文件。

  3. *note BaseRotatingHandler: 210f. 是轮换日志文件的处理程序的基类。它
     并不应该直接实例化。而应该使用 *note RotatingFileHandler: 20eb. 或
     *note TimedRotatingFileHandler: 877. 代替它。

  4. *note RotatingFileHandler: 20eb. 实例将消息发送到硬盘文件，支持最大
     日志文件大小和日志文件轮换。

  5. *note TimedRotatingFileHandler: 877. 实例将消息发送到硬盘文件，以特
     定的时间间隔轮换日志文件。

  6. *note SocketHandler: 878. 实例将消息发送到 TCP/IP 套接字。从 3.4 开
     始，也支持 Unix 域套接字。

  7. *note DatagramHandler: 879. 实例将消息发送到 UDP 套接字。从 3.4 开
     始，也支持 Unix 域套接字。

  8. *note SMTPHandler: 213b. 实例将消息发送到指定的电子邮件地址。

  9. *note SysLogHandler: a26. 实例将消息发送到 Unix syslog 守护程序，可
     能在远程计算机上。

  10. *note NTEventLogHandler: 2133. 实例将消息发送到 Windows NT/2000/XP
     事件日志。

  11. *note MemoryHandler: 20f4. 实例将消息发送到内存中的缓冲区，只要满
     足特定条件，缓冲区就会刷新。

  12. *note HTTPHandler: 71a. 实例使用 ‘GET’ 或 ‘POST’ 方法将消息发送到
     HTTP 服务器。

  13. *note WatchedFileHandler: 210b. 实例会监视他们要写入日志的文件。如
     果文件发生更改，则会关闭该文件并使用文件名重新打开。此处理程序仅在
     类 Unix 系统上有用； Windows 不支持依赖的基础机制。

  14. *note QueueHandler: 214e. 实例将消息发送到队列，例如在 *note
     queue: db. 或 *note multiprocessing: b8. 模块中实现的队列。

  15. *note NullHandler: c24. 实例对错误消息不执行任何操作。它们由想要使
     用日志记录的库开发人员使用，但是想要避免如果库用户没有配置日志记录
     ，则显示 "无法找到记录器XXX的消息处理器" 消息的情况。有关更多信息，
     请参阅 *note 配置库的日志记录: 2108. 。

3.1 新版功能: *note NullHandler: c24. 类。

3.2 新版功能: *note QueueHandler: 214e. 类。

The *note NullHandler: c24. 、 *note StreamHandler: b7d. 和 *note
FileHandler: 20fa. 类在核心日志包中定义。其他处理程序定义在 *note
logging.handlers: ad. 中。（还有另一个子模块 *note logging.config: ac. ，
用于配置功能）

记录的消息被格式化为通过 *note Formatter: 2095. 类的实例进行呈现。 它们
使用适合与 ％ 运算符一起使用的格式字符串和字典进行初始化。

对于批量格式化多个消息，可以使用 ‘BufferingFormatter’ 的实例。除了格式字
符串（应用于批处理中的每个消息）之外，还提供了标题和尾部格式字符串。

当基于记录器级别和处理程序级别的过滤不够时，可以将 *note Filter: b7f. 的
实例添加到 *note Logger: 3af. 和 *note Handler: 2096. 实例（通过它们的
*note addFilter(): 20ad. 方法）。在决定进一步处理消息之前，记录器和处理
程序都会查询其所有过滤器以获得许可。如果任何过滤器返回 false 值，则不会
进一步处理该消息。

基本 *note Filter: b7f. 的功能允许按特定的记录器名称进行过滤。如果使用此
功能，则允许通过过滤器发送到指定记录器及其子项的消息，并丢弃所有消息。


File: python.info,  Node: 记录日志中引发的异常,  Next: 使用任意对象作为消息,  Prev: 有用的处理程序,  Up: 日志常用指引

10.6.5 记录日志中引发的异常
---------------------------

日志包设计为忽略记录日志生产时发生的异常。这样，处理日志记录事件时发生的
错误（例如日志记录错误配置、网络或其他类似错误）不会导致使用日志记录的应
用程序过早终止。

*note SystemExit: 605. 和 *note KeyboardInterrupt: 198. 异常永远不会被忽
略。 在 *note Handler: 2096. 子类的 ‘emit()’ 方法中发生的其他异常被传递
给它的 ‘handleError()’ 方法。

*note Handler: 2096. 中默认实现的 ‘handleError()’ 检查是否设置了模块级变
量 ‘raiseExceptions’ 。如果有设置，则会将跟踪打印到 *note sys.stderr:
318. 。如果未设置，则忽略异常。

     注解: ‘raiseExceptions’ 默认值是 ‘True’。 这是因为在开发期间，你通
     常希望收到任何发生异常的通知。建议你将 ‘raiseExceptions’ 设置为
     ‘False’ 以供生产环境使用。


File: python.info,  Node: 使用任意对象作为消息,  Next: 优化,  Prev: 记录日志中引发的异常,  Up: 日志常用指引

10.6.6 使用任意对象作为消息
---------------------------

在前面的部分和示例中，都假设记录事件时传递的消息是字符串。 但是，这不是
唯一的可能性。你可以将任意对象作为消息传递，并且当日志记录系统需要将其转
换为字符串表示时，将调用其 ‘__ str__()’ 方法。实际上，如果你愿意，你可以
完全避免计算字符串表示。例如， *note SocketHandler: 878. 通过 pickle 并
网络发送来发出事件。


File: python.info,  Node: 优化,  Prev: 使用任意对象作为消息,  Up: 日志常用指引

10.6.7 优化
-----------

消息参数的格式化将被推迟，直到无法避免。但是，计算传递给日志记录方法的参
数也可能很消耗资源，如果记录器只是丢弃你的事件，你可能希望避免这样做。要
决定做什么，可以调用 *note isEnabledFor(): 2094. 方法，该方法接受一个
level 参数，如果记录器为该级别的调用创建了该事件，则返回 true 。 你可以
写这样的代码:

     if logger.isEnabledFor(logging.DEBUG):
         logger.debug('Message with %s, %s', expensive_func1(),
                                             expensive_func2())

因此，如果记录器的阈值设置在“DEBUG”以上，则永远不会调用
‘expensive_func1()’ 和 ‘expensive_func2()’ 。

     注解: 在某些情况下， *note isEnabledFor(): 2094. 本身可能比你想要的
     更消耗资源（例如，对于深度嵌套的记录器，其中显式级别仅在记录器层次
     结构中设置为高）。在这种情况下（或者如果你想避免在紧密循环中调用方
     法），你可以在本地或实例变量中将调用的结果缓存到 *note
     isEnabledFor(): 2094. ，并使用它而不是调用每次方法。只在日志记录配
     置在应用程序运行时动态更改（这不常见）时需重新计算这样的缓存值。

对于需要对收集的日志信息进行更精确控制的特定应用程序，还可以进行其他优化
。 以下是你可以执行的操作列表，以避免在你不需要的日志记录期间进行处理：

你不想收集的内容                                    如何避免收集它
                                                    
-------------------------------------------------------------------------------------------------
                                                    
有关调用来源的信息                                  将 ‘logging._srcfile’ 设置为 ‘None’ 。这避
                                                    免了调用 *note sys._getframe(): e6c. ，如
                                                    果 PyPy 支持 Python 3.x ,这可能有助于加速
                                                    PyPy （无法加速使用
                                                    *note sys._getframe(): e6c. 的代码）等环境
                                                    中的代码.
                                                    
                                                    
线程信息                                            将 ‘logging.logThreads’ 置为 ‘0’ 。
                                                    
                                                    
进程信息                                            将 ‘logging.logProcesses’ 置为 ‘0’ 。
                                                    

另请注意，核心日志记录模块仅包含基本处理程序。如果你不导入 *note
logging.handlers: ad. 和 *note logging.config: ac. ，它们将不会占用任何
内存。

参见
....

模块 *note logging: ab.

     日志记录模块的 API 参考。

*note logging.config: ac. 模块

     日志记录模块的配置 API 。

*note logging.handlers: ad. 模块

     日志记录模块附带的有用处理器。

*note 日志操作手册: b7c.


File: python.info,  Node: 日志操作手册,  Next: 正则表达式HOWTO,  Prev: 日志常用指引,  Up: Python 常用指引

10.7 日志操作手册
=================


作者: Vinay Sajip <vinay_sajip at red-dove dot com>

本页包含了许多日志记录相关的概念，这些概念在过去一直被认为很有用。

* Menu:

* 在多个模块中记录日志::
* 在多个线程中记录日志::
* 多个日志处理器以及多种格式化器::
* 在多个地方记录日志::
* 日志服务器配置示例::
* 处理日志处理器的阻塞::
* 通过网络发送和接收日志::
* 在日志记录中添加上下文信息::
* 从多个进程记录至单个文件::
* 轮换日志文件::
* 使用其他日志格式化方式::
* 自定义 LogRecord::
* 子类化 QueueHandler - ZeroMQ 示例::
* 子类化 QueueListener —— ZeroMQ 示例::
* 基于字典进行日志配置的示例::
* 利用 rotator 和 namer 自定义日志轮换操作::
* 更加详细的多道处理示例::
* 在发送给 SysLogHandler 的信息中插入一个 BOM。::
* 结构化日志的实现代码::
* 利用 dictConfig() 自定义 handler: 利用 dictConfig 自定义 handler.
* 生效于整个应用程序的格式化样式::
* 利用 dictConfig() 定义过滤器: 利用 dictConfig 定义过滤器.
* 异常信息的自定义格式化::
* 语音播报日志信息::
* 缓冲日志消息并有条件地输出它们::
* 通过配置使用UTC (GMT) 格式化时间: 通过配置使用UTC GMT 格式化时间.
* 使用上下文管理器的可选的日志记录::
* 命令行日志应用起步::
* Qt GUI 日志示例::


File: python.info,  Node: 在多个模块中记录日志,  Next: 在多个线程中记录日志,  Up: 日志操作手册

10.7.1 在多个模块中记录日志
---------------------------

多次调用 ‘logging.getLogger('someLogger')’ 时会返回对同一个 logger 对象
的引用。 这不仅是在同一个模块中，在其他模块调用也是如此，只要是在同一个
Python 解释器进程中。 是应该引用同一个对象，此外，应用程序也可以在一个模
块中定义和配置父 logger，而在单独的模块中创建（但不配置）子 logger，对子
logger 的所有调用都将传给父 logger。 这里是主模块:

     import logging
     import auxiliary_module

     # create logger with 'spam_application'
     logger = logging.getLogger('spam_application')
     logger.setLevel(logging.DEBUG)
     # create file handler which logs even debug messages
     fh = logging.FileHandler('spam.log')
     fh.setLevel(logging.DEBUG)
     # create console handler with a higher log level
     ch = logging.StreamHandler()
     ch.setLevel(logging.ERROR)
     # create formatter and add it to the handlers
     formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
     fh.setFormatter(formatter)
     ch.setFormatter(formatter)
     # add the handlers to the logger
     logger.addHandler(fh)
     logger.addHandler(ch)

     logger.info('creating an instance of auxiliary_module.Auxiliary')
     a = auxiliary_module.Auxiliary()
     logger.info('created an instance of auxiliary_module.Auxiliary')
     logger.info('calling auxiliary_module.Auxiliary.do_something')
     a.do_something()
     logger.info('finished auxiliary_module.Auxiliary.do_something')
     logger.info('calling auxiliary_module.some_function()')
     auxiliary_module.some_function()
     logger.info('done with auxiliary_module.some_function()')

这里是辅助模块:

     import logging

     # create logger
     module_logger = logging.getLogger('spam_application.auxiliary')

     class Auxiliary:
         def __init__(self):
             self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary')
             self.logger.info('creating an instance of Auxiliary')

         def do_something(self):
             self.logger.info('doing something')
             a = 1 + 1
             self.logger.info('done doing something')

     def some_function():
         module_logger.info('received a call to "some_function"')

输出结果会像这样:

     2005-03-23 23:47:11,663 - spam_application - INFO -
        creating an instance of auxiliary_module.Auxiliary
     2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
        creating an instance of Auxiliary
     2005-03-23 23:47:11,665 - spam_application - INFO -
        created an instance of auxiliary_module.Auxiliary
     2005-03-23 23:47:11,668 - spam_application - INFO -
        calling auxiliary_module.Auxiliary.do_something
     2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
        doing something
     2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
        done doing something
     2005-03-23 23:47:11,670 - spam_application - INFO -
        finished auxiliary_module.Auxiliary.do_something
     2005-03-23 23:47:11,671 - spam_application - INFO -
        calling auxiliary_module.some_function()
     2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
        received a call to 'some_function'
     2005-03-23 23:47:11,673 - spam_application - INFO -
        done with auxiliary_module.some_function()


File: python.info,  Node: 在多个线程中记录日志,  Next: 多个日志处理器以及多种格式化器,  Prev: 在多个模块中记录日志,  Up: 日志操作手册

10.7.2 在多个线程中记录日志
---------------------------

在多个线程中记录日志并不需要特殊的处理，以下示例展示了如何在主（初始）线
程和另一个线程中记录日志:

     import logging
     import threading
     import time

     def worker(arg):
         while not arg['stop']:
             logging.debug('Hi from myfunc')
             time.sleep(0.5)

     def main():
         logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
         info = {'stop': False}
         thread = threading.Thread(target=worker, args=(info,))
         thread.start()
         while True:
             try:
                 logging.debug('Hello from main')
                 time.sleep(0.75)
             except KeyboardInterrupt:
                 info['stop'] = True
                 break
         thread.join()

     if __name__ == '__main__':
         main()

脚本会运行输出类似下面的内容:

        0 Thread-1 Hi from myfunc
        3 MainThread Hello from main
      505 Thread-1 Hi from myfunc
      755 MainThread Hello from main
     1007 Thread-1 Hi from myfunc
     1507 MainThread Hello from main
     1508 Thread-1 Hi from myfunc
     2010 Thread-1 Hi from myfunc
     2258 MainThread Hello from main
     2512 Thread-1 Hi from myfunc
     3009 MainThread Hello from main
     3013 Thread-1 Hi from myfunc
     3515 Thread-1 Hi from myfunc
     3761 MainThread Hello from main
     4017 Thread-1 Hi from myfunc
     4513 MainThread Hello from main
     4518 Thread-1 Hi from myfunc

这表明不同线程的日志像期望的那样穿插输出，当然更多的线程也会像这样输出。


File: python.info,  Node: 多个日志处理器以及多种格式化器,  Next: 在多个地方记录日志,  Prev: 在多个线程中记录日志,  Up: 日志操作手册

10.7.3 多个日志处理器以及多种格式化器
-------------------------------------

日志记录器是普通的Python对象。*note addHandler(): 209e. 方法对可以添加的
日志处理器的数量没有限制。有时候，应用程序需要将所有严重性的所有消息记录
到一个文本文件，而将错误或更高等级的消息输出到控制台。要进行这样的设定，
只需配置适当的日志处理器即可。在应用程序代码中，记录日志的调用将保持不变
。以下是对之前基于模块的简单配置示例的略微修改:

     import logging

     logger = logging.getLogger('simple_example')
     logger.setLevel(logging.DEBUG)
     # create file handler which logs even debug messages
     fh = logging.FileHandler('spam.log')
     fh.setLevel(logging.DEBUG)
     # create console handler with a higher log level
     ch = logging.StreamHandler()
     ch.setLevel(logging.ERROR)
     # create formatter and add it to the handlers
     formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
     ch.setFormatter(formatter)
     fh.setFormatter(formatter)
     # add the handlers to logger
     logger.addHandler(ch)
     logger.addHandler(fh)

     # 'application' code
     logger.debug('debug message')
     logger.info('info message')
     logger.warning('warn message')
     logger.error('error message')
     logger.critical('critical message')

需要注意的是，’应用程序’ 代码并不关心是否有多个日志处理器。示例中所做的
改变只是添加和配置了一个新的名为 `fh' 的日志处理器。

在编写和测试应用程序时，能够创建带有更高或更低消息等级的过滤器的日志处理
器是非常有用的。为了避免过多地使用 ‘print’ 语句去调试，请使用
‘logger.debug’ ：它不像 ‘print’ 语句需要你不得不在调试结束后注释或删除掉
，logger.debug 语句可以在源代码中保持不变，在你再一次需要它之前保持无效
。那时，唯一需要改变的是修改日志记录器和/或日志处理器的消息等级，以进行
调试。


File: python.info,  Node: 在多个地方记录日志,  Next: 日志服务器配置示例,  Prev: 多个日志处理器以及多种格式化器,  Up: 日志操作手册

10.7.4 在多个地方记录日志
-------------------------

假设有这样一种情况，你需要将日志按不同的格式和不同的情况存储在控制台和文
件中。比如说想把日志等级为DEBUG或更高的消息记录于文件中，而把那些等级为
INFO或更高的消息输出在控制台。而且记录在文件中的消息格式需要包含时间戳，
打印在控制台的不需要。以下示例展示了如何做到:

     import logging

     # set up logging to file - see previous section for more details
     logging.basicConfig(level=logging.DEBUG,
                         format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                         datefmt='%m-%d %H:%M',
                         filename='/temp/myapp.log',
                         filemode='w')
     # define a Handler which writes INFO messages or higher to the sys.stderr
     console = logging.StreamHandler()
     console.setLevel(logging.INFO)
     # set a format which is simpler for console use
     formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
     # tell the handler to use this format
     console.setFormatter(formatter)
     # add the handler to the root logger
     logging.getLogger('').addHandler(console)

     # Now, we can log to the root logger, or any other logger. First the root...
     logging.info('Jackdaws love my big sphinx of quartz.')

     # Now, define a couple of other loggers which might represent areas in your
     # application:

     logger1 = logging.getLogger('myapp.area1')
     logger2 = logging.getLogger('myapp.area2')

     logger1.debug('Quick zephyrs blow, vexing daft Jim.')
     logger1.info('How quickly daft jumping zebras vex.')
     logger2.warning('Jail zesty vixen who grabbed pay from quack.')
     logger2.error('The five boxing wizards jump quickly.')

当运行后，你会看到控制台如下所示

     root        : INFO     Jackdaws love my big sphinx of quartz.
     myapp.area1 : INFO     How quickly daft jumping zebras vex.
     myapp.area2 : WARNING  Jail zesty vixen who grabbed pay from quack.
     myapp.area2 : ERROR    The five boxing wizards jump quickly.

而在文件中会看到像这样

     10-22 22:19 root         INFO     Jackdaws love my big sphinx of quartz.
     10-22 22:19 myapp.area1  DEBUG    Quick zephyrs blow, vexing daft Jim.
     10-22 22:19 myapp.area1  INFO     How quickly daft jumping zebras vex.
     10-22 22:19 myapp.area2  WARNING  Jail zesty vixen who grabbed pay from quack.
     10-22 22:19 myapp.area2  ERROR    The five boxing wizards jump quickly.

正如你所看到的，DEBUG级别的消息只展示在文件中，而其他消息两个地方都会输
出。

这个示例只演示了在控制台和文件中去记录日志，但你也可以自由组合任意数量的
日志处理器。


File: python.info,  Node: 日志服务器配置示例,  Next: 处理日志处理器的阻塞,  Prev: 在多个地方记录日志,  Up: 日志操作手册

10.7.5 日志服务器配置示例
-------------------------

以下是在一个模块中使用日志服务器配置的示例:

     import logging
     import logging.config
     import time
     import os

     # read initial config file
     logging.config.fileConfig('logging.conf')

     # create and start listener on port 9999
     t = logging.config.listen(9999)
     t.start()

     logger = logging.getLogger('simpleExample')

     try:
         # loop through logging calls to see the difference
         # new configurations make, until Ctrl+C is pressed
         while True:
             logger.debug('debug message')
             logger.info('info message')
             logger.warning('warn message')
             logger.error('error message')
             logger.critical('critical message')
             time.sleep(5)
     except KeyboardInterrupt:
         # cleanup
         logging.config.stopListening()
         t.join()

然后如下的脚本，它接收文件名做为命令行参数，并将该文件以二进制编码的方式
传给服务器，做为新的日志服务器配置:

     #!/usr/bin/env python
     import socket, sys, struct

     with open(sys.argv[1], 'rb') as f:
         data_to_send = f.read()

     HOST = 'localhost'
     PORT = 9999
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     print('connecting...')
     s.connect((HOST, PORT))
     print('sending config...')
     s.send(struct.pack('>L', len(data_to_send)))
     s.send(data_to_send)
     s.close()
     print('complete')


File: python.info,  Node: 处理日志处理器的阻塞,  Next: 通过网络发送和接收日志,  Prev: 日志服务器配置示例,  Up: 日志操作手册

10.7.6 处理日志处理器的阻塞
---------------------------

有时候需要让日志处理程序在不阻塞当前正在记录线程的情况下完成工作。 这在
Web应用程序中很常见，当然也会在其他场景中出现。

一个常见的缓慢行为是 *note SMTPHandler: 213b.: 由于开发者无法控制的多种
原因（例如，性能不佳的邮件或网络基础架构），发送电子邮件可能需要很长时间
。 其实几乎所有基于网络的处理程序都可能造成阻塞：即便是 *note
SocketHandler: 878. 也可能在底层进行 DNS 查询，这太慢了（这个查询会深入
至套接字代码，位于 Python 层之下，这是不受开发者控制的）。

一种解决方案是分成两部分去处理。第一部分，针对那些对性能有要求的关键线程
的日志记录附加一个 *note QueueHandler: 214e.。 日志记录器只需简单写入队
列，该队列可以设置一个足够大的容量甚至不设置容量上限。通常写入队列是一个
快速的操作，即使可能需要在代码中去捕获例如 *note queue.Full: 23c5. 等异
常。 如果你是一名处理关键线程的开发者，请务必记录这些信息 (包括建议只为
日志处理器附加 ‘QueueHandlers’) 以便于其他开发者使用你的代码。

解决方案的另一部分是 *note QueueListener: 71b.，它被设计用来作为 *note
QueueHandler: 214e. 的对应。 *note QueueListener: 71b. 非常简单：向其传
入一个队列和一些处理句柄，它会启动一个内部线程来监听从 ‘QueueHandlers’
(或任何其他可用的 ‘LogRecords’ 源) 发送过来的 LogRecords 队列。
‘LogRecords’ 会从队列中被移除，并被传递给句柄进行处理。

使用一个单独的类 *note QueueListener: 71b. 优点是可以使用同一个实例去服
务于多个‘‘QueueHandlers‘‘。这样会更节省资源，否则每个处理程序都占用一个
线程没有任何益处。

以下是使用了这样两个类的示例(省略了导入语句):

     que = queue.Queue(-1)  # no limit on size
     queue_handler = QueueHandler(que)
     handler = logging.StreamHandler()
     listener = QueueListener(que, handler)
     root = logging.getLogger()
     root.addHandler(queue_handler)
     formatter = logging.Formatter('%(threadName)s: %(message)s')
     handler.setFormatter(formatter)
     listener.start()
     # The log output will display the thread which generated
     # the event (the main thread) rather than the internal
     # thread which monitors the internal queue. This is what
     # you want to happen.
     root.warning('Look out!')
     listener.stop()

在运行后会产生:

     MainThread: Look out!

在 3.5 版更改: 在 Python 3.5 之前，*note QueueListener: 71b. 总是把从队
列中接收的每个消息都传给它初始化的日志处理程序。(这是因为它会假设过滤级
别总是在队列的另一侧去设置的。) 从 Python 3.5 开始，可以通过在监听器构造
函数中添加一个参数 ‘respect_handler_level=True’ 改变这种情况。当这样设置
时，监听器会比较每条消息的等级和日志处理器中设置的等级，只把需要传递的消
息传给对应的日志处理器。


File: python.info,  Node: 通过网络发送和接收日志,  Next: 在日志记录中添加上下文信息,  Prev: 处理日志处理器的阻塞,  Up: 日志操作手册

10.7.7 通过网络发送和接收日志
-----------------------------

如果你想在网络上发送日志，并在接收端处理它们。一个简单的方式是通过附加一
个 *note SocketHandler: 878. 的实例在发送端的根日志处理器中:

     import logging, logging.handlers

     rootLogger = logging.getLogger('')
     rootLogger.setLevel(logging.DEBUG)
     socketHandler = logging.handlers.SocketHandler('localhost',
                         logging.handlers.DEFAULT_TCP_LOGGING_PORT)
     # don't bother with a formatter, since a socket handler sends the event as
     # an unformatted pickle
     rootLogger.addHandler(socketHandler)

     # Now, we can log to the root logger, or any other logger. First the root...
     logging.info('Jackdaws love my big sphinx of quartz.')

     # Now, define a couple of other loggers which might represent areas in your
     # application:

     logger1 = logging.getLogger('myapp.area1')
     logger2 = logging.getLogger('myapp.area2')

     logger1.debug('Quick zephyrs blow, vexing daft Jim.')
     logger1.info('How quickly daft jumping zebras vex.')
     logger2.warning('Jail zesty vixen who grabbed pay from quack.')
     logger2.error('The five boxing wizards jump quickly.')

在接收端，你可以使用 *note socketserver: f1. 模块设置一个接收器。这里是
一个基础示例:

     import pickle
     import logging
     import logging.handlers
     import socketserver
     import struct


     class LogRecordStreamHandler(socketserver.StreamRequestHandler):
         """Handler for a streaming logging request.

         This basically logs the record using whatever logging policy is
         configured locally.
         """

         def handle(self):
             """
             Handle multiple requests - each expected to be a 4-byte length,
             followed by the LogRecord in pickle format. Logs the record
             according to whatever policy is configured locally.
             """
             while True:
                 chunk = self.connection.recv(4)
                 if len(chunk) < 4:
                     break
                 slen = struct.unpack('>L', chunk)[0]
                 chunk = self.connection.recv(slen)
                 while len(chunk) < slen:
                     chunk = chunk + self.connection.recv(slen - len(chunk))
                 obj = self.unPickle(chunk)
                 record = logging.makeLogRecord(obj)
                 self.handleLogRecord(record)

         def unPickle(self, data):
             return pickle.loads(data)

         def handleLogRecord(self, record):
             # if a name is specified, we use the named logger rather than the one
             # implied by the record.
             if self.server.logname is not None:
                 name = self.server.logname
             else:
                 name = record.name
             logger = logging.getLogger(name)
             # N.B. EVERY record gets logged. This is because Logger.handle
             # is normally called AFTER logger-level filtering. If you want
             # to do filtering, do it at the client end to save wasting
             # cycles and network bandwidth!
             logger.handle(record)

     class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
         """
         Simple TCP socket-based logging receiver suitable for testing.
         """

         allow_reuse_address = True

         def __init__(self, host='localhost',
                      port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
                      handler=LogRecordStreamHandler):
             socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
             self.abort = 0
             self.timeout = 1
             self.logname = None

         def serve_until_stopped(self):
             import select
             abort = 0
             while not abort:
                 rd, wr, ex = select.select([self.socket.fileno()],
                                            [], [],
                                            self.timeout)
                 if rd:
                     self.handle_request()
                 abort = self.abort

     def main():
         logging.basicConfig(
             format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s')
         tcpserver = LogRecordSocketReceiver()
         print('About to start TCP server...')
         tcpserver.serve_until_stopped()

     if __name__ == '__main__':
         main()

首先运行服务端，然后是客户端。在客户端，没有什么内容会打印在控制台中；在
服务端，你应该会看到如下内容：

     About to start TCP server...
        59 root            INFO     Jackdaws love my big sphinx of quartz.
        59 myapp.area1     DEBUG    Quick zephyrs blow, vexing daft Jim.
        69 myapp.area1     INFO     How quickly daft jumping zebras vex.
        69 myapp.area2     WARNING  Jail zesty vixen who grabbed pay from quack.
        69 myapp.area2     ERROR    The five boxing wizards jump quickly.

请注意，在某些情况下序列化会存在一些安全。如果这影响到你，那么你可以通过
覆盖 ‘makePickle()’ 方法，使用自己的实现来解决，并调整上述脚本也使用覆盖
后的序列化方法。


File: python.info,  Node: 在日志记录中添加上下文信息,  Next: 从多个进程记录至单个文件,  Prev: 通过网络发送和接收日志,  Up: 日志操作手册

10.7.8 在日志记录中添加上下文信息
---------------------------------

有时，除了传递给日志记录器调用的参数外，我们还希望日志记录中包含上下文信
息。例如，有一个网络应用，可能需要记录一些特殊的客户端信息在日志中（比如
客户端的用户名、IP地址等）。虽然你可以通过设置额外的参数去达到这个目的，
但这种方式不一定方便。或者你可能想到在每个连接的基础上创建一个 ‘Logger’
的实例，但这些实例是不会被垃圾回收的，这在练习中也许不是问题，但当
‘Logger’ 的实例数量取决于你应用程序中想记录的细致程度时，如果 ‘Logger’ 的
实例数量不受限制的话，将会变得难以管理。

* Menu:

* 使用日志适配器传递上下文信息::
* 使用过滤器传递上下文信息::


File: python.info,  Node: 使用日志适配器传递上下文信息,  Next: 使用过滤器传递上下文信息,  Up: 在日志记录中添加上下文信息

10.7.8.1 使用日志适配器传递上下文信息
.....................................

一个传递上下文信息和日志事件信息的简单办法是使用类 ‘LoggerAdapter’。 这
个类设计的像 ‘Logger’，所以可以直接调用 ‘debug()’、‘info()’、
‘warning()’、 ‘error()’、‘exception()’、 ‘critical()’ 和 ‘log()’。 这些
方法在对应的 ‘Logger’ 中使用相同的签名，所以可以交替使用两种类型的实例。

当你创建一个 ‘LoggerAdapter’ 的实例时，你会传入一个 ‘Logger’ 的实例和一
个包含了上下文信息的字典对象。当你调用一个 ‘LoggerAdapter’ 实例的方法时
，它会把调用委托给内部的 ‘Logger’ 的实例，并为其整理相关的上下文信息。这
是 ‘LoggerAdapter’ 的一个代码片段:

     def debug(self, msg, /, *args, **kwargs):
         """
         Delegate a debug call to the underlying logger, after adding
         contextual information from this adapter instance.
         """
         msg, kwargs = self.process(msg, kwargs)
         self.logger.debug(msg, *args, **kwargs)

‘LoggerAdapter’ 的 ‘process()’ 方法是将上下文信息添加到日志的输出中。 它
传入日志消息和日志调用的关键字参数，并传回（隐式的）这些修改后的内容去调
用底层的日志记录器。此方法的默认参数只是一个消息字段，但留有一个 ’extra’
的字段作为关键字参数传给构造器。当然，如果你在调用适配器时传入了一个
’extra’ 字段的参数，它会被静默覆盖。

使用 ’extra’ 的优点是这些键值对会被传入 ‘LogRecord’ 实例的 __dict__ 中，
让你通过 ‘Formatter’ 的实例直接使用定制的字符串，实例能找到这个字典类对
象的键。 如果你需要一个其他的方法，比如说，想要在消息字符串前后增加上下
文信息，你只需要创建一个 ‘LoggerAdapter’ 的子类，并覆盖它的 ‘process()’
方法来做你想做的事情，以下是一个简单的示例:

     class CustomAdapter(logging.LoggerAdapter):
         """
         This example adapter expects the passed in dict-like object to have a
         'connid' key, whose value in brackets is prepended to the log message.
         """
         def process(self, msg, kwargs):
             return '[%s] %s' % (self.extra['connid'], msg), kwargs

你可以这样使用:

     logger = logging.getLogger(__name__)
     adapter = CustomAdapter(logger, {'connid': some_conn_id})

然后，你记录在适配器中的任何事件消息前将添加‘‘some_conn_id‘‘的值。

* Menu:

* 使用除字典之外的其它对象传递上下文信息::


File: python.info,  Node: 使用除字典之外的其它对象传递上下文信息,  Up: 使用日志适配器传递上下文信息

10.7.8.2 使用除字典之外的其它对象传递上下文信息
...............................................

你不需要将一个实际的字典传递给 ‘LoggerAdapter’-你可以传入一个实现了
‘‘__getitem__‘‘ 和‘‘__iter__‘‘的类的实例，这样它就像是一个字典。这对于你
想动态生成值（而字典中的值往往是常量）将很有帮助。


File: python.info,  Node: 使用过滤器传递上下文信息,  Prev: 使用日志适配器传递上下文信息,  Up: 在日志记录中添加上下文信息

10.7.8.3 使用过滤器传递上下文信息
.................................

你也可以使用一个用户定义的类 ‘Filter’ 在日志输出中添加上下文信息。
‘Filter’ 的实例是被允许修改传入的 ‘LogRecords’，包括添加其他的属性，然后
可以使用合适的格式化字符串输出，或者可以使用一个自定义的类 ‘Formatter’。

例如，在一个web应用程序中，正在处理的请求（或者至少是请求的一部分），可
以存储在一个线程本地 (*note threading.local: 2302.) 变量中，然后从
‘‘Filter‘‘ 中去访问。请求中的信息，如IP地址和用户名将被存储在
‘‘LogRecord‘‘中，使用上例 ‘LoggerAdapter’ 中的 ’ip’ 和 ’user’ 属性名。在
这种情况下，可以使用相同的格式化字符串来得到上例中类似的输出结果。这是一
段示例代码:

     import logging
     from random import choice

     class ContextFilter(logging.Filter):
         """
         This is a filter which injects contextual information into the log.

         Rather than use actual contextual information, we just use random
         data in this demo.
         """

         USERS = ['jim', 'fred', 'sheila']
         IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']

         def filter(self, record):

             record.ip = choice(ContextFilter.IPS)
             record.user = choice(ContextFilter.USERS)
             return True

     if __name__ == '__main__':
         levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
         logging.basicConfig(level=logging.DEBUG,
                             format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
         a1 = logging.getLogger('a.b.c')
         a2 = logging.getLogger('d.e.f')

         f = ContextFilter()
         a1.addFilter(f)
         a2.addFilter(f)
         a1.debug('A debug message')
         a1.info('An info message with %s', 'some parameters')
         for x in range(10):
             lvl = choice(levels)
             lvlname = logging.getLevelName(lvl)
             a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')

在运行时，产生如下内容:

     2010-09-06 22:38:15,292 a.b.c DEBUG    IP: 123.231.231.123 User: fred     A debug message
     2010-09-06 22:38:15,300 a.b.c INFO     IP: 192.168.0.1     User: sheila   An info message with some parameters
     2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
     2010-09-06 22:38:15,300 d.e.f ERROR    IP: 127.0.0.1       User: jim      A message at ERROR level with 2 parameters
     2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 127.0.0.1       User: sheila   A message at DEBUG level with 2 parameters
     2010-09-06 22:38:15,300 d.e.f ERROR    IP: 123.231.231.123 User: fred     A message at ERROR level with 2 parameters
     2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1     User: jim      A message at CRITICAL level with 2 parameters
     2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
     2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 192.168.0.1     User: jim      A message at DEBUG level with 2 parameters
     2010-09-06 22:38:15,301 d.e.f ERROR    IP: 127.0.0.1       User: sheila   A message at ERROR level with 2 parameters
     2010-09-06 22:38:15,301 d.e.f DEBUG    IP: 123.231.231.123 User: fred     A message at DEBUG level with 2 parameters
     2010-09-06 22:38:15,301 d.e.f INFO     IP: 123.231.231.123 User: fred     A message at INFO level with 2 parameters


File: python.info,  Node: 从多个进程记录至单个文件,  Next: 轮换日志文件,  Prev: 在日志记录中添加上下文信息,  Up: 日志操作手册

10.7.9 从多个进程记录至单个文件
-------------------------------

尽管 logging 是线程安全的，将单个进程中的多个线程日志记录至单个文件也 `是
' 受支持的，但将 `多个进程' 中的日志记录至单个文件则 `不是' 受支持的，因
为在 Python 中并没有在多个进程中实现对单个文件访问的序列化的标准方案。 如
果你需要将多个进程中的日志记录至单个文件，有一个方案是让所有进程都将日志
记录至一个 ‘SocketHandler’，然后用一个实现了套接字服务器的单独进程一边从
套接字中读取一边将日志记录至文件。 （如果愿意的话，你可以在一个现有进程
中专门开一个线程来执行此项功能。） *note 这一部分: 416a. 文档对此方式有
更详细的介绍，并包含一个可用的套接字接收器，你自己的应用可以在此基础上进
行适配。

你也可以编写你自己的处理程序，让其使用 *note multiprocessing: b8. 模块中
的 *note Lock: 23a5. 类来顺序访问你的多个进程中的文件。 现有的
‘FileHandler’ 及其子类目前并不使用 *note multiprocessing: b8.，尽管它们
将来可能会这样做。 请注意在目前，*note multiprocessing: b8. 模块并未在所
有平台上都提供可用的锁功能 (参见 ‘https://bugs.python.org/issue3770’)。

或者，你也可以使用 ‘Queue’ 和 *note QueueHandler: 214e. 将所有的日志事件
发送至你的多进程应用的一个进程中。 以下示例脚本演示了如何执行此操作。 在
示例中，一个单独的监听进程负责监听其他进程的日志事件，并根据自己的配置记
录。 尽管示例只演示了这种方法（例如你可能希望使用单独的监听线程而非监听
进程 —— 它们的实现是类似的），但你也可以在应用程序的监听进程和其他进程使
用不同的配置，它可以作为满足你特定需求的一个基础:

     # You'll need these imports in your own code
     import logging
     import logging.handlers
     import multiprocessing

     # Next two import lines for this demo only
     from random import choice, random
     import time

     #
     # Because you'll want to define the logging configurations for listener and workers, the
     # listener and worker process functions take a configurer parameter which is a callable
     # for configuring logging for that process. These functions are also passed the queue,
     # which they use for communication.
     #
     # In practice, you can configure the listener however you want, but note that in this
     # simple example, the listener does not apply level or filter logic to received records.
     # In practice, you would probably want to do this logic in the worker processes, to avoid
     # sending events which would be filtered out between processes.
     #
     # The size of the rotated files is made small so you can see the results easily.
     def listener_configurer():
         root = logging.getLogger()
         h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10)
         f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
         h.setFormatter(f)
         root.addHandler(h)

     # This is the listener process top-level loop: wait for logging events
     # (LogRecords)on the queue and handle them, quit when you get a None for a
     # LogRecord.
     def listener_process(queue, configurer):
         configurer()
         while True:
             try:
                 record = queue.get()
                 if record is None:  # We send this as a sentinel to tell the listener to quit.
                     break
                 logger = logging.getLogger(record.name)
                 logger.handle(record)  # No level or filter logic applied - just do it!
             except Exception:
                 import sys, traceback
                 print('Whoops! Problem:', file=sys.stderr)
                 traceback.print_exc(file=sys.stderr)

     # Arrays used for random selections in this demo

     LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
               logging.ERROR, logging.CRITICAL]

     LOGGERS = ['a.b.c', 'd.e.f']

     MESSAGES = [
         'Random message #1',
         'Random message #2',
         'Random message #3',
     ]

     # The worker configuration is done at the start of the worker process run.
     # Note that on Windows you can't rely on fork semantics, so each process
     # will run the logging configuration code when it starts.
     def worker_configurer(queue):
         h = logging.handlers.QueueHandler(queue)  # Just the one handler needed
         root = logging.getLogger()
         root.addHandler(h)
         # send all messages, for demo; no other level or filter logic applied.
         root.setLevel(logging.DEBUG)

     # This is the worker process top-level loop, which just logs ten events with
     # random intervening delays before terminating.
     # The print messages are just so you know it's doing something!
     def worker_process(queue, configurer):
         configurer(queue)
         name = multiprocessing.current_process().name
         print('Worker started: %s' % name)
         for i in range(10):
             time.sleep(random())
             logger = logging.getLogger(choice(LOGGERS))
             level = choice(LEVELS)
             message = choice(MESSAGES)
             logger.log(level, message)
         print('Worker finished: %s' % name)

     # Here's where the demo gets orchestrated. Create the queue, create and start
     # the listener, create ten workers and start them, wait for them to finish,
     # then send a None to the queue to tell the listener to finish.
     def main():
         queue = multiprocessing.Queue(-1)
         listener = multiprocessing.Process(target=listener_process,
                                            args=(queue, listener_configurer))
         listener.start()
         workers = []
         for i in range(10):
             worker = multiprocessing.Process(target=worker_process,
                                              args=(queue, worker_configurer))
             workers.append(worker)
             worker.start()
         for w in workers:
             w.join()
         queue.put_nowait(None)
         listener.join()

     if __name__ == '__main__':
         main()

上面脚本的一个变种，仍然在主进程中记录日志，但使用一个单独的线程:

     import logging
     import logging.config
     import logging.handlers
     from multiprocessing import Process, Queue
     import random
     import threading
     import time

     def logger_thread(q):
         while True:
             record = q.get()
             if record is None:
                 break
             logger = logging.getLogger(record.name)
             logger.handle(record)


     def worker_process(q):
         qh = logging.handlers.QueueHandler(q)
         root = logging.getLogger()
         root.setLevel(logging.DEBUG)
         root.addHandler(qh)
         levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
                   logging.CRITICAL]
         loggers = ['foo', 'foo.bar', 'foo.bar.baz',
                    'spam', 'spam.ham', 'spam.ham.eggs']
         for i in range(100):
             lvl = random.choice(levels)
             logger = logging.getLogger(random.choice(loggers))
             logger.log(lvl, 'Message no. %d', i)

     if __name__ == '__main__':
         q = Queue()
         d = {
             'version': 1,
             'formatters': {
                 'detailed': {
                     'class': 'logging.Formatter',
                     'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
                 }
             },
             'handlers': {
                 'console': {
                     'class': 'logging.StreamHandler',
                     'level': 'INFO',
                 },
                 'file': {
                     'class': 'logging.FileHandler',
                     'filename': 'mplog.log',
                     'mode': 'w',
                     'formatter': 'detailed',
                 },
                 'foofile': {
                     'class': 'logging.FileHandler',
                     'filename': 'mplog-foo.log',
                     'mode': 'w',
                     'formatter': 'detailed',
                 },
                 'errors': {
                     'class': 'logging.FileHandler',
                     'filename': 'mplog-errors.log',
                     'mode': 'w',
                     'level': 'ERROR',
                     'formatter': 'detailed',
                 },
             },
             'loggers': {
                 'foo': {
                     'handlers': ['foofile']
                 }
             },
             'root': {
                 'level': 'DEBUG',
                 'handlers': ['console', 'file', 'errors']
             },
         }
         workers = []
         for i in range(5):
             wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,))
             workers.append(wp)
             wp.start()
         logging.config.dictConfig(d)
         lp = threading.Thread(target=logger_thread, args=(q,))
         lp.start()
         # At this point, the main process could do some useful work of its own
         # Once it's done that, it can wait for the workers to terminate...
         for wp in workers:
             wp.join()
         # And now tell the logging thread to finish up, too
         q.put(None)
         lp.join()

这段变种的代码展示了如何使用特定的日志记录配置 - 例如‘‘foo‘‘记录器使用了
特殊的处理程序，将 ‘foo’ 子系统中所有的事件记录至一个文件
‘mplog-foo.log’。在主进程（即使是在工作进程中产生的日志事件）的日志记录
机制中将直接使用恰当的配置。

* Menu:

* concurrent.futures.ProcessPoolExecutor 的用法: concurrent futures ProcessPoolExecutor 的用法.


File: python.info,  Node: concurrent futures ProcessPoolExecutor 的用法,  Up: 从多个进程记录至单个文件

10.7.9.1 concurrent.futures.ProcessPoolExecutor 的用法
......................................................

若要利用 *note concurrent.futures.ProcessPoolExecutor: 2a4. 启动工作进程
，创建队列的方式应稍有不同。不能是：

     queue = multiprocessing.Queue(-1)

而应是：

     queue = multiprocessing.Manager().Queue(-1)  # also works with the examples above

然后就可以将以下工作进程的创建过程：

     workers = []
     for i in range(10):
         worker = multiprocessing.Process(target=worker_process,
                                          args=(queue, worker_configurer))
         workers.append(worker)
         worker.start()
     for w in workers:
         w.join()

改为 (记得要先导入 *note concurrent.futures: 22.):

     with concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor:
         for i in range(10):
             executor.submit(worker_process, queue, worker_configurer)


File: python.info,  Node: 轮换日志文件,  Next: 使用其他日志格式化方式,  Prev: 从多个进程记录至单个文件,  Up: 日志操作手册

10.7.10 轮换日志文件
--------------------

有时，你希望当日志文件不断记录增长至一定大小时，打开一个新的文件接着记录
。 你可能希望只保留一定数量的日志文件，当不断的创建文件到达该数量时，又
覆盖掉最开始的文件形成循环。 对于这种使用场景，日志包提供了
‘RotatingFileHandler’:

     import glob
     import logging
     import logging.handlers

     LOG_FILENAME = 'logging_rotatingfile_example.out'

     # Set up a specific logger with our desired output level
     my_logger = logging.getLogger('MyLogger')
     my_logger.setLevel(logging.DEBUG)

     # Add the log message handler to the logger
     handler = logging.handlers.RotatingFileHandler(
                   LOG_FILENAME, maxBytes=20, backupCount=5)

     my_logger.addHandler(handler)

     # Log some messages
     for i in range(20):
         my_logger.debug('i = %d' % i)

     # See what files are created
     logfiles = glob.glob('%s*' % LOG_FILENAME)

     for filename in logfiles:
         print(filename)

结果应该是6个单独的文件，每个文件都包含了应用程序的部分历史日志:

     logging_rotatingfile_example.out
     logging_rotatingfile_example.out.1
     logging_rotatingfile_example.out.2
     logging_rotatingfile_example.out.3
     logging_rotatingfile_example.out.4
     logging_rotatingfile_example.out.5

最新的文件始终是:file:‘logging_rotatingfile_example.out’，每次到达大小限
制时，都会使用后缀‘‘.1‘‘重命名。每个现有的备份文件都会被重命名并增加其后
缀（例如‘‘.1‘‘ 变为‘‘.2‘‘），而‘‘.6‘‘文件会被删除掉。

显然，这个例子将日志长度设置得太小，这是一个极端的例子。 你可能希望将
`maxBytes' 设置为一个合适的值。


File: python.info,  Node: 使用其他日志格式化方式,  Next: 自定义 LogRecord,  Prev: 轮换日志文件,  Up: 日志操作手册

10.7.11 使用其他日志格式化方式
------------------------------

当日志模块被添加至 Python 标准库时，只有一种格式化消息内容的方法即
%-formatting。 在那之后，Python 又增加了两种格式化方法: *note
string.Template: 3f3. (在 Python 2.4 中新增) 和 *note str.format(): 4e2.
(在 Python 2.6 中新增)。

日志（从 3.2 开始）为这两种格式化方式提供了更多支持。‘Formatter’ 类可以
添加一个额外的可选关键字参数 ‘style’。它的默认值是 ‘'%'’，其他的值 ‘'{'’
和 ‘'$'’ 也支持，对应了其他两种格式化样式。其保持了向后兼容（如您所愿）
，但通过显示指定样式参数，你可以指定格式化字符串的方式是使用 *note
str.format(): 4e2. 或 *note string.Template: 3f3.。 这里是一个控制台会话
的示例，展示了这些方式：

     >>> import logging
     >>> root = logging.getLogger()
     >>> root.setLevel(logging.DEBUG)
     >>> handler = logging.StreamHandler()
     >>> bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}',
     ...                        style='{')
     >>> handler.setFormatter(bf)
     >>> root.addHandler(handler)
     >>> logger = logging.getLogger('foo.bar')
     >>> logger.debug('This is a DEBUG message')
     2010-10-28 15:11:55,341 foo.bar DEBUG    This is a DEBUG message
     >>> logger.critical('This is a CRITICAL message')
     2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message
     >>> df = logging.Formatter('$asctime $name ${levelname} $message',
     ...                        style='$')
     >>> handler.setFormatter(df)
     >>> logger.debug('This is a DEBUG message')
     2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message
     >>> logger.critical('This is a CRITICAL message')
     2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message
     >>>

请注意最终输出到日志的消息格式完全独立于单条日志消息的构造方式。 它仍然
可以使用 %-formatting，如下所示:

     >>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message')
     2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message
     >>>

日志调用（‘logger.debug()’ 、‘logger.info()’ 等）接受的位置参数只会用于
日志信息本身，而关键字参数仅用于日志调用的可选处理参数（如关键字参数
‘exc_info’ 表示应记录跟踪信息， ‘extra’ 则标识了需要加入日志的额外上下文
信息）。所以不能直接用 *note str.format(): 4e2. 或 *note
string.Template: 3f3. 语法进行日志调用，因为日志包在内部使用 %-f 格式来
合并格式串和参数变量。在保持向下兼容性时，这一点不会改变，因为已有代码中
的所有日志调用都会使用%-f 格式串。

还有一种方法可以构建自己的日志信息，就是利用 {}- 和 $- 格式。回想一下，
任意对象都可用为日志信息的格式串，日志包将会调用该对象的 ‘str()’ 方法，
以获取最终的格式串。不妨看下一下两个类：

     class BraceMessage:
         def __init__(self, fmt, /, *args, **kwargs):
             self.fmt = fmt
             self.args = args
             self.kwargs = kwargs

         def __str__(self):
             return self.fmt.format(*self.args, **self.kwargs)

     class DollarMessage:
         def __init__(self, fmt, /, **kwargs):
             self.fmt = fmt
             self.kwargs = kwargs

         def __str__(self):
             from string import Template
             return Template(self.fmt).substitute(**self.kwargs)

上述两个类均可代替格式串，使得能用 {}- 或 $-formatting 构建最终的“日志信
息”部分，这些信息将出现在格式化后的日志输出中，替换 %(message)s 或
“{message}”或“$message”。每次写入日志时都要使用类名，有点不大实用，但如
果用上 __ 之类的别名就相当合适了（双下划线 — 不要与 _ 混淆，单下划线用作
*note gettext.gettext(): dd5. 或相关函数的同义词/别名 ）。

Python 并没有上述两个类，当然复制粘贴到自己的代码中也很容易。用法可如下
所示（假定在名为 ‘wherever’ 的模块中声明）：

     >>> from wherever import BraceMessage as __
     >>> print(__('Message with {0} {name}', 2, name='placeholders'))
     Message with 2 placeholders
     >>> class Point: pass
     ...
     >>> p = Point()
     >>> p.x = 0.5
     >>> p.y = 0.5
     >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})',
     ...       point=p))
     Message with coordinates: (0.50, 0.50)
     >>> from wherever import DollarMessage as __
     >>> print(__('Message with $num $what', num=2, what='placeholders'))
     Message with 2 placeholders
     >>>

上述示例用了 ‘print()’ 演示格式化输出的过程，实际记录日志时当然会用类似
‘logger.debug()’ 的方法来应用。

值得注意的是，上述做法对性能并没什么影响：格式化过程其实不是在日志记录调
用时发生的，而是在日志信息即将由 handler 输出到日志时发生。因此，唯一可
能让人困惑的稍不寻常的地方，就是包裹在格式串和参数外面的括号，而不是格式
串。因为 __ 符号只是对 XXXMessage 类的构造函数调用的语法糖。

只要愿意，上述类似的效果即可用 ‘LoggerAdapter’ 实现，如下例所示：

     import logging

     class Message:
         def __init__(self, fmt, args):
             self.fmt = fmt
             self.args = args

         def __str__(self):
             return self.fmt.format(*self.args)

     class StyleAdapter(logging.LoggerAdapter):
         def __init__(self, logger, extra=None):
             super().__init__(logger, extra or {})

         def log(self, level, msg, /, *args, **kwargs):
             if self.isEnabledFor(level):
                 msg, kwargs = self.process(msg, kwargs)
                 self.logger._log(level, Message(msg, args), (), **kwargs)

     logger = StyleAdapter(logging.getLogger(__name__))

     def main():
         logger.debug('Hello, {}', 'world!')

     if __name__ == '__main__':
         logging.basicConfig(level=logging.DEBUG)
         main()

在用 Python 3.2 以上版本运行时，上述代码应该会把 ‘Hello, world!’ 写入日
志。


File: python.info,  Node: 自定义 LogRecord,  Next: 子类化 QueueHandler - ZeroMQ 示例,  Prev: 使用其他日志格式化方式,  Up: 日志操作手册

10.7.12 自定义 ‘LogRecord’
--------------------------

每条日志事件都由一个 *note LogRecord: 90e. 实例表示。当某事件要记入日志
并且没有被某级别过滤掉时，就会创建一个 *note LogRecord: 90e. 对象，并将
有关事件的信息填入，传给该日志对象的 handler（及其祖先，直至对象禁止向上
传播为止）。在 Python 3.2 之前，只有两个地方会进行事件的创建：

   * *note Logger.makeRecord(): 20a2.，在事件正常记入日志的过程中调用。
     这会直接调用 *note LogRecord: 90e. 来创建一个实例。

   * *note makeLogRecord(): 20c7.，调用时会带上一个字典参数，其中存放着
     要加入 LogRecord 的属性。这通常在通过网络接收到合适的字典时调用（如
     通过 *note SocketHandler: 878. 以 pickle 形式，或通过 *note
     HTTPHandler: 71a. 以 JSON 形式）。

于是这意味着若要对 *note LogRecord: 90e. 进行定制，必须进行下述某种操作
。

   * 创建 *note Logger: 3af.  自定义子类，重写 *note
     Logger.makeRecord(): 20a2.，并在实例化所需日志对象之前用 *note
     setLoggerClass(): 20d4. 进行设置。

   * 为日志对象添加 *note Filter: b7f. 或 handler，当其 *note filter():
     20c2. 方法被调用时，会执行必要的定制操作。

比如说在有多个不同库要完成不同操作的场景下，第一种方式会有点笨拙。 每次
都要尝试设置自己的 *note Logger: 3af. 子类，而起作用的是最后一次尝试。

第二种方式在多数情况下效果都比较良好，但不允许你使用特殊化的 *note
LogRecord: 90e. 子类。 库开发者可以为他们的日志记录器设置合适的过滤器，
但他们应当要记得每次引入新的日志记录器时都需如此（他们只需通过添加新的包
或模块并执行以下操作即可）:

     logger = logging.getLogger(__name__)

或许这样要顾及太多事情。开发人员还可以将过滤器附加到其顶级日志对象的
*note NullHandler: c24. 中，但如果应用程序开发人员将 handler 附加到较底
层库的日志对象，则不会调用该过滤器 — 所以 handler 输出的内容不会符合库开
发人员的预期。

在 Python 3.2 以上版本中，*note LogRecord: 90e. 的创建是通过工厂对象完成
的，工厂对象可以指定。工厂对象只是一个可调用对象，可以用 *note
setLogRecordFactory(): 20ca. 进行设置，并用 *note getLogRecordFactory():
20c9. 进行查询。工厂对象的调用参数与 *note LogRecord: 90e. 的构造函数相
同，因为 *note LogRecord: 90e. 是工厂对象的默认设置。

这种方式可以让自定义工厂对象完全控制 LogRecord 的创建过程。比如可以返回
一个子类，或者在创建的日志对象中加入一些额外的属性，使用方式如下所示：

     old_factory = logging.getLogRecordFactory()

     def record_factory(*args, **kwargs):
         record = old_factory(*args, **kwargs)
         record.custom_attribute = 0xdecafbad
         return record

     logging.setLogRecordFactory(record_factory)

这种模式允许不同的库将多个工厂对象链在一起，只要不会覆盖彼此的属性或标准
属性，就不会出现意外。但应记住，工厂链中的每个节点都会增加日志操作的运行
开销，本技术仅在采用 *note Filter: b7f. 无法达到目标时才应使用。


File: python.info,  Node: 子类化 QueueHandler - ZeroMQ 示例,  Next: 子类化 QueueListener —— ZeroMQ 示例,  Prev: 自定义 LogRecord,  Up: 日志操作手册

10.7.13 子类化 QueueHandler - ZeroMQ 示例
-----------------------------------------

你可以使用 ‘QueueHandler’ 子类将消息发送给其他类型的队列 ，比如 ZeroMQ
’publish’ 套接字。 在以下示例中，套接字将单独创建并传给处理句柄 (作为它
的 ’queue’):

     import zmq   # using pyzmq, the Python binding for ZeroMQ
     import json  # for serializing records portably

     ctx = zmq.Context()
     sock = zmq.Socket(ctx, zmq.PUB)  # or zmq.PUSH, or other suitable value
     sock.bind('tcp://*:5556')        # or wherever

     class ZeroMQSocketHandler(QueueHandler):
         def enqueue(self, record):
             self.queue.send_json(record.__dict__)


     handler = ZeroMQSocketHandler(sock)

当然还有其他方案，比如通过 hander 传入所需数据，以创建 socket：

     class ZeroMQSocketHandler(QueueHandler):
         def __init__(self, uri, socktype=zmq.PUB, ctx=None):
             self.ctx = ctx or zmq.Context()
             socket = zmq.Socket(self.ctx, socktype)
             socket.bind(uri)
             super().__init__(socket)

         def enqueue(self, record):
             self.queue.send_json(record.__dict__)

         def close(self):
             self.queue.close()


File: python.info,  Node: 子类化 QueueListener —— ZeroMQ 示例,  Next: 基于字典进行日志配置的示例,  Prev: 子类化 QueueHandler - ZeroMQ 示例,  Up: 日志操作手册

10.7.14 子类化 QueueListener —— ZeroMQ 示例
-------------------------------------------

你还可以子类化 ‘QueueListener’ 来从其他类型的队列中获取消息，比如从
ZeroMQ ’subscribe’ 套接字。 下面是一个例子:

     class ZeroMQSocketListener(QueueListener):
         def __init__(self, uri, /, *handlers, **kwargs):
             self.ctx = kwargs.get('ctx') or zmq.Context()
             socket = zmq.Socket(self.ctx, zmq.SUB)
             socket.setsockopt_string(zmq.SUBSCRIBE, '')  # subscribe to everything
             socket.connect(uri)
             super().__init__(socket, *handlers, **kwargs)

         def dequeue(self):
             msg = self.queue.recv_json()
             return logging.makeLogRecord(msg)

参见
....

模块 *note logging: ab.

     日志记录模块的 API 参考。

*note logging.config: ac. 模块

     日志记录模块的配置 API 。

*note logging.handlers: ad. 模块

     日志记录模块附带的有用处理器。

*note 日志操作基础教程: b7a.

*note 日志操作的高级教程: b7b.


File: python.info,  Node: 基于字典进行日志配置的示例,  Next: 利用 rotator 和 namer 自定义日志轮换操作,  Prev: 子类化 QueueListener —— ZeroMQ 示例,  Up: 日志操作手册

10.7.15 基于字典进行日志配置的示例
----------------------------------

以下是日志配置字典的一个示例——它取自 Django 项目的‘文档
<‘https://docs.djangoproject.com/en/stable/topics/logging/#configuring-logging’>‘_。
此字典将被传给 *note dictConfig(): b33. 以使配置生效:

     LOGGING = {
         'version': 1,
         'disable_existing_loggers': True,
         'formatters': {
             'verbose': {
                 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
             },
             'simple': {
                 'format': '%(levelname)s %(message)s'
             },
         },
         'filters': {
             'special': {
                 '()': 'project.logging.SpecialFilter',
                 'foo': 'bar',
             }
         },
         'handlers': {
             'null': {
                 'level':'DEBUG',
                 'class':'django.utils.log.NullHandler',
             },
             'console':{
                 'level':'DEBUG',
                 'class':'logging.StreamHandler',
                 'formatter': 'simple'
             },
             'mail_admins': {
                 'level': 'ERROR',
                 'class': 'django.utils.log.AdminEmailHandler',
                 'filters': ['special']
             }
         },
         'loggers': {
             'django': {
                 'handlers':['null'],
                 'propagate': True,
                 'level':'INFO',
             },
             'django.request': {
                 'handlers': ['mail_admins'],
                 'level': 'ERROR',
                 'propagate': False,
             },
             'myproject.custom': {
                 'handlers': ['console', 'mail_admins'],
                 'level': 'INFO',
                 'filters': ['special']
             }
         }
     }

有关本配置的更多信息，请参阅 Django 文档的 有关章节(1) 。

   ---------- Footnotes ----------

   (1) 
https://docs.djangoproject.com/en/stable/topics/logging/#configuring-logging


File: python.info,  Node: 利用 rotator 和 namer 自定义日志轮换操作,  Next: 更加详细的多道处理示例,  Prev: 基于字典进行日志配置的示例,  Up: 日志操作手册

10.7.16 利用 rotator 和 namer 自定义日志轮换操作
------------------------------------------------

以下代码给出了定义 namer 和 rotator 的示例，其中演示了基于 zlib 的日志文
件压缩过程：

     def namer(name):
         return name + ".gz"

     def rotator(source, dest):
         with open(source, "rb") as sf:
             data = sf.read()
             compressed = zlib.compress(data, 9)
             with open(dest, "wb") as df:
                 df.write(compressed)
         os.remove(source)

     rh = logging.handlers.RotatingFileHandler(...)
     rh.rotator = rotator
     rh.namer = namer

这些不是“真正的” .gz 文件，因为他们只是纯压缩数据，缺少真正 gzip 文件中
的“容器”。此段代码只是用于演示。


File: python.info,  Node: 更加详细的多道处理示例,  Next: 在发送给 SysLogHandler 的信息中插入一个 BOM。,  Prev: 利用 rotator 和 namer 自定义日志轮换操作,  Up: 日志操作手册

10.7.17 更加详细的多道处理示例
------------------------------

以下可运行的示例显示了如何利用配置文件在多进程中应用日志。这些配置相当简
单，但足以说明如何在真实的多进程场景中实现较为复杂的配置。

上述示例中，主进程产生一个侦听器进程和一些工作进程。每个主进程、侦听器进
程和工作进程都有三种独立的日志配置（工作进程共享同一套配置）。大家可以看
到主进程的日志记录过程、工作线程向 QueueHandler 写入日志的过程，以及侦听
器实现 QueueListener 和较为复杂的日志配置，如何将由队列接收到的事件分发
给配置指定的 handler。请注意，这些配置纯粹用于演示，但应该能调整代码以适
用于自己的场景。

以下是代码——但愿文档字符串和注释能有助于理解其工作原理：

     import logging
     import logging.config
     import logging.handlers
     from multiprocessing import Process, Queue, Event, current_process
     import os
     import random
     import time

     class MyHandler:
         """
         A simple handler for logging events. It runs in the listener process and
         dispatches events to loggers based on the name in the received record,
         which then get dispatched, by the logging system, to the handlers
         configured for those loggers.
         """

         def handle(self, record):
             if record.name == "root":
                 logger = logging.getLogger()
             else:
                 logger = logging.getLogger(record.name)

             if logger.isEnabledFor(record.levelno):
                 # The process name is transformed just to show that it's the listener
                 # doing the logging to files and console
                 record.processName = '%s (for %s)' % (current_process().name, record.processName)
                 logger.handle(record)

     def listener_process(q, stop_event, config):
         """
         This could be done in the main process, but is just done in a separate
         process for illustrative purposes.

         This initialises logging according to the specified configuration,
         starts the listener and waits for the main process to signal completion
         via the event. The listener is then stopped, and the process exits.
         """
         logging.config.dictConfig(config)
         listener = logging.handlers.QueueListener(q, MyHandler())
         listener.start()
         if os.name == 'posix':
             # On POSIX, the setup logger will have been configured in the
             # parent process, but should have been disabled following the
             # dictConfig call.
             # On Windows, since fork isn't used, the setup logger won't
             # exist in the child, so it would be created and the message
             # would appear - hence the "if posix" clause.
             logger = logging.getLogger('setup')
             logger.critical('Should not appear, because of disabled logger ...')
         stop_event.wait()
         listener.stop()

     def worker_process(config):
         """
         A number of these are spawned for the purpose of illustration. In
         practice, they could be a heterogeneous bunch of processes rather than
         ones which are identical to each other.

         This initialises logging according to the specified configuration,
         and logs a hundred messages with random levels to randomly selected
         loggers.

         A small sleep is added to allow other processes a chance to run. This
         is not strictly needed, but it mixes the output from the different
         processes a bit more than if it's left out.
         """
         logging.config.dictConfig(config)
         levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
                   logging.CRITICAL]
         loggers = ['foo', 'foo.bar', 'foo.bar.baz',
                    'spam', 'spam.ham', 'spam.ham.eggs']
         if os.name == 'posix':
             # On POSIX, the setup logger will have been configured in the
             # parent process, but should have been disabled following the
             # dictConfig call.
             # On Windows, since fork isn't used, the setup logger won't
             # exist in the child, so it would be created and the message
             # would appear - hence the "if posix" clause.
             logger = logging.getLogger('setup')
             logger.critical('Should not appear, because of disabled logger ...')
         for i in range(100):
             lvl = random.choice(levels)
             logger = logging.getLogger(random.choice(loggers))
             logger.log(lvl, 'Message no. %d', i)
             time.sleep(0.01)

     def main():
         q = Queue()
         # The main process gets a simple configuration which prints to the console.
         config_initial = {
             'version': 1,
             'handlers': {
                 'console': {
                     'class': 'logging.StreamHandler',
                     'level': 'INFO'
                 }
             },
             'root': {
                 'handlers': ['console'],
                 'level': 'DEBUG'
             }
         }
         # The worker process configuration is just a QueueHandler attached to the
         # root logger, which allows all messages to be sent to the queue.
         # We disable existing loggers to disable the "setup" logger used in the
         # parent process. This is needed on POSIX because the logger will
         # be there in the child following a fork().
         config_worker = {
             'version': 1,
             'disable_existing_loggers': True,
             'handlers': {
                 'queue': {
                     'class': 'logging.handlers.QueueHandler',
                     'queue': q
                 }
             },
             'root': {
                 'handlers': ['queue'],
                 'level': 'DEBUG'
             }
         }
         # The listener process configuration shows that the full flexibility of
         # logging configuration is available to dispatch events to handlers however
         # you want.
         # We disable existing loggers to disable the "setup" logger used in the
         # parent process. This is needed on POSIX because the logger will
         # be there in the child following a fork().
         config_listener = {
             'version': 1,
             'disable_existing_loggers': True,
             'formatters': {
                 'detailed': {
                     'class': 'logging.Formatter',
                     'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
                 },
                 'simple': {
                     'class': 'logging.Formatter',
                     'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
                 }
             },
             'handlers': {
                 'console': {
                     'class': 'logging.StreamHandler',
                     'formatter': 'simple',
                     'level': 'INFO'
                 },
                 'file': {
                     'class': 'logging.FileHandler',
                     'filename': 'mplog.log',
                     'mode': 'w',
                     'formatter': 'detailed'
                 },
                 'foofile': {
                     'class': 'logging.FileHandler',
                     'filename': 'mplog-foo.log',
                     'mode': 'w',
                     'formatter': 'detailed'
                 },
                 'errors': {
                     'class': 'logging.FileHandler',
                     'filename': 'mplog-errors.log',
                     'mode': 'w',
                     'formatter': 'detailed',
                     'level': 'ERROR'
                 }
             },
             'loggers': {
                 'foo': {
                     'handlers': ['foofile']
                 }
             },
             'root': {
                 'handlers': ['console', 'file', 'errors'],
                 'level': 'DEBUG'
             }
         }
         # Log some initial events, just to show that logging in the parent works
         # normally.
         logging.config.dictConfig(config_initial)
         logger = logging.getLogger('setup')
         logger.info('About to create workers ...')
         workers = []
         for i in range(5):
             wp = Process(target=worker_process, name='worker %d' % (i + 1),
                          args=(config_worker,))
             workers.append(wp)
             wp.start()
             logger.info('Started worker: %s', wp.name)
         logger.info('About to create listener ...')
         stop_event = Event()
         lp = Process(target=listener_process, name='listener',
                      args=(q, stop_event, config_listener))
         lp.start()
         logger.info('Started listener')
         # We now hang around for the workers to finish their work.
         for wp in workers:
             wp.join()
         # Workers all done, listening can now stop.
         # Logging in the parent still works normally.
         logger.info('Telling listener to stop ...')
         stop_event.set()
         lp.join()
         logger.info('All done.')

     if __name__ == '__main__':
         main()


File: python.info,  Node: 在发送给 SysLogHandler 的信息中插入一个 BOM。,  Next: 结构化日志的实现代码,  Prev: 更加详细的多道处理示例,  Up: 日志操作手册

10.7.18 在发送给 SysLogHandler 的信息中插入一个 BOM。
-----------------------------------------------------

RFC 5424(1) 要求，Unicode 信息应采用字节流形式发送到系统 syslog 守护程序
，字节流结构如下所示：可选的纯 ASCII部分，后跟 UTF-8 字节序标记（BOM），
然后是采用 UTF-8 编码的 Unicode。（参见 相关规范(2) 。）

在 Python 3.1 的 *note SysLogHandler: a26. 中，已加入了在日志信息中插入
BOM 的代码，但不幸的是，代码并不正确，BOM 出现在了日志信息的开头，因此在
它之前就不允许出现纯 ASCII 内容了。

由于无法正常工作， Python 3.2.4 以上版本已删除了出错的插入 BOM 代码。但
已有版本的代码不会被替换，若要生成与 RFC 5424(3) 兼容的日志信息，包括一
个 BOM 符，前面有可选的纯 ASCII 字节流，后面为 UTF-8 编码的任意 Unicode，
那么 需要执行以下操作：

  1. 为 *note SysLogHandler: a26. 实例串上一个 *note Formatter: 2095. 实
     例，格式串可如下：

          'ASCII section\ufeffUnicode section'

     用 UTF-8 编码时，Unicode 码位 U+FEFF 将会编码为 UTF-8 BOM——字节串
     ‘b'\xef\xbb\xbf'’ 。

  2. 用任意占位符替换 ASCII 部分，但要保证替换之后的数据一定是 ASCII 码
     （这样在 UTF-8 编码后就会维持不变）。

  3. 用任意占位符替换 Unicode 部分；如果替换后的数据包含超出 ASCII 范围
     的字符，没问题——他们将用 UTF-8 进行编码。

‘SysLogHandler’ `将' 对格式化后的日志信息进行 UTF-8 编码。如果遵循上述规
则，应能生成符合 RFC 5424(4) 的日志信息。否则，日志记录过程可能不会有什
么反馈，但日志信息将不与 RFC 5424 兼容，syslog 守护程序可能会有出错反应
。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc5424.html

   (2) https://tools.ietf.org/html/rfc5424.html#section-6

   (3) https://tools.ietf.org/html/rfc5424.html

   (4) https://tools.ietf.org/html/rfc5424.html


File: python.info,  Node: 结构化日志的实现代码,  Next: 利用 dictConfig 自定义 handler,  Prev: 在发送给 SysLogHandler 的信息中插入一个 BOM。,  Up: 日志操作手册

10.7.19 结构化日志的实现代码
----------------------------

大多数日志信息是供人阅读的，所以机器解析起来并不容易，但某些时候可能希望
以结构化的格式输出，以 `能够' 被程序解析（无需用到复杂的正则表达式）。这
可以直接用 logging 包实现。实现方式有很多，以下是一种比较简单的方案，利
用 JSON 以机器可解析的方式对事件信息进行序列化：

     import json
     import logging

     class StructuredMessage:
         def __init__(self, message, /, **kwargs):
             self.message = message
             self.kwargs = kwargs

         def __str__(self):
             return '%s >>> %s' % (self.message, json.dumps(self.kwargs))

     _ = StructuredMessage   # optional, to improve readability

     logging.basicConfig(level=logging.INFO, format='%(message)s')
     logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))

上述代码运行后的结果是：

     message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"}

请注意，根据 Python 版本的不同，各项数据的输出顺序可能会不一样。

若需进行更为定制化的处理，可以使用自定义 JSON 编码对象，下面给出完整示例
：

     from __future__ import unicode_literals

     import json
     import logging

     # This next bit is to ensure the script runs unchanged on 2.x and 3.x
     try:
         unicode
     except NameError:
         unicode = str

     class Encoder(json.JSONEncoder):
         def default(self, o):
             if isinstance(o, set):
                 return tuple(o)
             elif isinstance(o, unicode):
                 return o.encode('unicode_escape').decode('ascii')
             return super().default(o)

     class StructuredMessage:
         def __init__(self, message, /, **kwargs):
             self.message = message
             self.kwargs = kwargs

         def __str__(self):
             s = Encoder().encode(self.kwargs)
             return '%s >>> %s' % (self.message, s)

     _ = StructuredMessage   # optional, to improve readability

     def main():
         logging.basicConfig(level=logging.INFO, format='%(message)s')
         logging.info(_('message 1', set_value={1, 2, 3}, snowman='\u2603'))

     if __name__ == '__main__':
         main()

上述代码运行后的结果是：

     message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]}

请注意，根据 Python 版本的不同，各项数据的输出顺序可能会不一样。


File: python.info,  Node: 利用 dictConfig 自定义 handler,  Next: 生效于整个应用程序的格式化样式,  Prev: 结构化日志的实现代码,  Up: 日志操作手册

10.7.20 利用 ‘dictConfig()’ 自定义 handler
------------------------------------------

有时需要以特定方式自定义日志 handler，如果采用 *note dictConfig(): b33.，
可能无需生成子类就可以做到。比如要设置日志文件的所有权。在 POSIX 上，可
以利用 *note shutil.chown(): a7e. 轻松完成，但 stdlib 中的文件 handler 并
不提供内置支持。于是可以用普通函数自定义 handler 的创建，例如：

     def owned_file_handler(filename, mode='a', encoding=None, owner=None):
         if owner:
             if not os.path.exists(filename):
                 open(filename, 'a').close()
             shutil.chown(filename, *owner)
         return logging.FileHandler(filename, mode, encoding)

然后，你可以在传给 *note dictConfig(): b33. 的日志配置中指定通过调用此函
数来创建日志处理程序:

     LOGGING = {
         'version': 1,
         'disable_existing_loggers': False,
         'formatters': {
             'default': {
                 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
             },
         },
         'handlers': {
             'file':{
                 # The values below are popped from this dictionary and
                 # used to create the handler, set the handler's level and
                 # its formatter.
                 '()': owned_file_handler,
                 'level':'DEBUG',
                 'formatter': 'default',
                 # The values below are passed to the handler creator callable
                 # as keyword arguments.
                 'owner': ['pulse', 'pulse'],
                 'filename': 'chowntest.log',
                 'mode': 'w',
                 'encoding': 'utf-8',
             },
         },
         'root': {
             'handlers': ['file'],
             'level': 'DEBUG',
         },
     }

出于演示目的，以下示例设置用户和用户组为 ‘pulse’。代码置于一个可运行的脚
本文件 ‘chowntest.py’ 中：

     import logging, logging.config, os, shutil

     def owned_file_handler(filename, mode='a', encoding=None, owner=None):
         if owner:
             if not os.path.exists(filename):
                 open(filename, 'a').close()
             shutil.chown(filename, *owner)
         return logging.FileHandler(filename, mode, encoding)

     LOGGING = {
         'version': 1,
         'disable_existing_loggers': False,
         'formatters': {
             'default': {
                 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
             },
         },
         'handlers': {
             'file':{
                 # The values below are popped from this dictionary and
                 # used to create the handler, set the handler's level and
                 # its formatter.
                 '()': owned_file_handler,
                 'level':'DEBUG',
                 'formatter': 'default',
                 # The values below are passed to the handler creator callable
                 # as keyword arguments.
                 'owner': ['pulse', 'pulse'],
                 'filename': 'chowntest.log',
                 'mode': 'w',
                 'encoding': 'utf-8',
             },
         },
         'root': {
             'handlers': ['file'],
             'level': 'DEBUG',
         },
     }

     logging.config.dictConfig(LOGGING)
     logger = logging.getLogger('mylogger')
     logger.debug('A debug message')

可能需要 ‘root’ 权限才能运行：

     $ sudo python3.3 chowntest.py
     $ cat chowntest.log
     2013-11-05 09:34:51,128 DEBUG mylogger A debug message
     $ ls -l chowntest.log
     -rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log

请注意此示例用的是 Python 3.3，因为 *note shutil.chown(): a7e. 是从此版
本开始出现的。 此方式应当适用于任何支持 *note dictConfig(): b33. 的
Python 版本 —— 例如 Python 2.7, 3.2 或更新的版本。 对于 3.3 之前的版本，
你应当使用 *note os.chown(): a3c. 之类的函数来实现实际的所有权修改。

实际应用中，handler 的创建函数可能位于项目的工具模块中。以下配置：

     '()': owned_file_handler,

应使用：

     '()': 'ext://project.util.owned_file_handler',

这里的 ‘project.util’ 可以换成函数所在包的实际名称。 在上述的可用脚本中
，应该可以使用 ‘'ext://__main__.owned_file_handler'’。 在这里，实际的可
调用对象是由 *note dictConfig(): b33. 从 ‘ext://’ 说明中解析出来的。

上述示例还指明了其他的文件修改类型的实现方案 —— 比如同样利用 *note
os.chmod(): a3b. 设置 POSIX 访问权限位。

当然，以上做法也可以扩展到 *note FileHandler: 20fa. 之外的其他类型的
handler ——比如某个轮换文件 handler，或类型完全不同的其他 handler。


File: python.info,  Node: 生效于整个应用程序的格式化样式,  Next: 利用 dictConfig 定义过滤器,  Prev: 利用 dictConfig 自定义 handler,  Up: 日志操作手册

10.7.21 生效于整个应用程序的格式化样式
--------------------------------------

在 Python 3.2 中，*note Formatter: 2095. 增加了一个 ‘style’ 关键字形参，
它默认为 ‘%’ 以便向下兼容，但是允许采用 ‘{’ 或 ‘{TX-PL-LABEL}#x60;’ 来支
持 *note str.format(): 4e2. 和 *note string.Template: 3f3. 所支持的格式
化方式。 请注意此形参控制着用用于最终输出到日志的日志消息格式，并且与单
独日志消息的构造方式完全无关。

日志函数（*note debug(): 719, *note info(): 2097. 等）只会读取位置参数获
取日志信息本身，而关键字参数仅用于确定日志函数的工作选项（比如关键字参数
‘exc_info’ 表示应将跟踪信息记入日志，关键字参数 ‘extra’ 则给出了需加入日
志的额外上下文信息）。所以不能直接使用 *note str.format(): 4e2. 或 *note
string.Template: 3f3. 这种语法进行日志调用，因为日志包在内部使用 %-f 格
式来合并格式串和可变参数。因为尚需保持向下兼容，这一点不会改变，已有代码
中的所有日志调用都将采用 %-f 格式串。

有人建议将格式化样式与特定的日志对象进行关联，但其实也会遇到向下兼容的问
题，因为已有代码可能用到了某日志对象并采用了 %-f 格式串。

为了让第三方库和自编代码都能够交互使用日志功能，需要决定在单次日志记录调
用级别采用什么格式。于是就出现了其他几种格式化样式方案。

* Menu:

* LogRecord 工厂的用法::
* 自定义信息对象的使用::


File: python.info,  Node: LogRecord 工厂的用法,  Next: 自定义信息对象的使用,  Up: 生效于整个应用程序的格式化样式

10.7.21.1 LogRecord 工厂的用法
..............................

在 Python 3.2 中，伴随着 *note Formatter: 2095. 的上述变化，logging 包增
加了允许用户使用 *note setLogRecordFactory(): 20ca. 函数来。设置自己的
*note LogRecord: 90e. 子类的功能。 你可以使用此功能来设置自己的 *note
LogRecord: 90e. 子类，它会通过重载 *note getMessage(): 20c8. 方法来完成
适当的操作。 ‘msg % args’ 格式化是在此方法的基类实现中进行的，你可以在那
里用你自己的格式化操作来替换；但是，你应当注意要支持全部的格式化样式并允
许将 %-formatting 作为默认样式，以确保与其他代码进行配合。 还应当注意调
用 ‘str(self.msg)’，正如基类实现所做的一样。

更多信息请参阅 *note setLogRecordFactory(): 20ca. 和 *note LogRecord:
90e. 的参考文档。


File: python.info,  Node: 自定义信息对象的使用,  Prev: LogRecord 工厂的用法,  Up: 生效于整个应用程序的格式化样式

10.7.21.2 自定义信息对象的使用
..............................

另一种方案可能更为简单，可以利用 {}- 和 $- 格式构建自己的日志消息。大家
或许还记得（来自 *note 使用任意对象作为消息: 20cc.），可以用任意对象作为
日志信息的格式串，日志包将调用该对象上 *note str(): 339. 获取实际的格式
串。看下以下两个类：

     class BraceMessage:
         def __init__(self, fmt, /, *args, **kwargs):
             self.fmt = fmt
             self.args = args
             self.kwargs = kwargs

         def __str__(self):
             return self.fmt.format(*self.args, **self.kwargs)

     class DollarMessage:
         def __init__(self, fmt, /, **kwargs):
             self.fmt = fmt
             self.kwargs = kwargs

         def __str__(self):
             from string import Template
             return Template(self.fmt).substitute(**self.kwargs)

以上两个类均都可用于替代格式串，以便用 {}- 或 $-formatting 构建实际的“日
志信息”部分，此部分将出现在格式化后的日志输出中，替换 %(message)s 、
“{message}”或“$message”。每次要写入日志时都使用类名，如果觉得使用不便，
可以采用 ‘M’ 或 ‘_’ 之类的别名（如果将 ‘_’ 用于本地化操作，则可用 ‘__’）
。

下面给出示例。 首先用 *note str.format(): 4e2. 进行格式化：

     >>> __ = BraceMessage
     >>> print(__('Message with {0} {1}', 2, 'placeholders'))
     Message with 2 placeholders
     >>> class Point: pass
     ...
     >>> p = Point()
     >>> p.x = 0.5
     >>> p.y = 0.5
     >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', point=p))
     Message with coordinates: (0.50, 0.50)

然后，用 *note string.Template: 3f3. 格式化：

     >>> __ = DollarMessage
     >>> print(__('Message with $num $what', num=2, what='placeholders'))
     Message with 2 placeholders
     >>>

值得注意的是，上述做法对性能并没什么影响：格式化过程其实不是在日志调用时
发生的，而是在日志信息即将由 handler 输出到日志时发生。因此，唯一可能让
人困惑的稍不寻常的地方，就是包裹在格式串和参数外面的括号，而不是格式串。
因为 __ 符号只是对 ‘XXXMessage’ 类的构造函数调用的语法糖。


File: python.info,  Node: 利用 dictConfig 定义过滤器,  Next: 异常信息的自定义格式化,  Prev: 生效于整个应用程序的格式化样式,  Up: 日志操作手册

10.7.22 利用 ‘dictConfig()’ 定义过滤器
--------------------------------------

用 *note dictConfig(): b33. `可以' 对日志过滤器进行设置，尽管乍一看做法
并不明显（所以才需要本秘籍）。 由于 *note Filter: b7f. 是标准库中唯一的
日志过滤器类，不太可能满足众多的要求（它只是作为基类存在），通常需要定义
自己的 *note Filter: b7f. 子类，并重写 *note filter(): 20c2. 方法。为此
，请在过滤器的配置字典中设置 ‘()’ 键，指定要用于创建过滤器的可调用对象（
最明显可用的就是给出一个类，但也可以提供任何一个可调用对象，只要能返回
*note Filter: b7f. 实例即可）。下面是一个完整的例子：

     import logging
     import logging.config
     import sys

     class MyFilter(logging.Filter):
         def __init__(self, param=None):
             self.param = param

         def filter(self, record):
             if self.param is None:
                 allow = True
             else:
                 allow = self.param not in record.msg
             if allow:
                 record.msg = 'changed: ' + record.msg
             return allow

     LOGGING = {
         'version': 1,
         'filters': {
             'myfilter': {
                 '()': MyFilter,
                 'param': 'noshow',
             }
         },
         'handlers': {
             'console': {
                 'class': 'logging.StreamHandler',
                 'filters': ['myfilter']
             }
         },
         'root': {
             'level': 'DEBUG',
             'handlers': ['console']
         },
     }

     if __name__ == '__main__':
         logging.config.dictConfig(LOGGING)
         logging.debug('hello')
         logging.debug('hello - noshow')

以上示例展示了将配置数据传给构造实例的可调用对象，形式是关键字参数。运行
后将会输出：

     changed: hello

这说明过滤器按照配置的参数生效了。

需要额外注意的地方：

   * 如果在配置中无法直接引用可调用对象（比如位于不同的模块中，并且不能
     在配置字典所在的位置直接导入），则可以采用 ‘ext://...’ 的形式，正如
     *note 访问外部对象: 20f1. 所述。例如，在上述示例中可以使用文本
     ‘'ext://__main__.MyFilter'’ 而不是 ‘MyFilter’ 对象。

   * 与过滤器一样，上述技术还可用于配置自定义 handler 和格式化对象。有关
     如何在日志配置中使用用户自定义对象的更多信息，请参阅 *note
     用户定义对象: 20ea.，以及上述 *note 利用 dictConfig() 自定义
     handler: 4180. 的其他指南。


File: python.info,  Node: 异常信息的自定义格式化,  Next: 语音播报日志信息,  Prev: 利用 dictConfig 定义过滤器,  Up: 日志操作手册

10.7.23 异常信息的自定义格式化
------------------------------

有时可能需要设置自定义的异常信息格式——考虑到会用到参数，假定要让每条日志
事件只占一行，即便存在异常信息也一样。这可以用自定义格式化类来实现，如下
所示：

     import logging

     class OneLineExceptionFormatter(logging.Formatter):
         def formatException(self, exc_info):
             """
             Format an exception so that it prints on a single line.
             """
             result = super().formatException(exc_info)
             return repr(result)  # or format into one line however you want to

         def format(self, record):
             s = super().format(record)
             if record.exc_text:
                 s = s.replace('\n', '') + '|'
             return s

     def configure_logging():
         fh = logging.FileHandler('output.txt', 'w')
         f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',
                                       '%d/%m/%Y %H:%M:%S')
         fh.setFormatter(f)
         root = logging.getLogger()
         root.setLevel(logging.DEBUG)
         root.addHandler(fh)

     def main():
         configure_logging()
         logging.info('Sample message')
         try:
             x = 1 / 0
         except ZeroDivisionError as e:
             logging.exception('ZeroDivisionError: %s', e)

     if __name__ == '__main__':
         main()

运行后将会生成只有两行信息的文件：

     28/01/2015 07:21:23|INFO|Sample message|
     28/01/2015 07:21:23|ERROR|ZeroDivisionError: integer division or modulo by zero|'Traceback (most recent call last):\n  File "logtest7.py", line 30, in main\n    x = 1 / 0\nZeroDivisionError: integer division or modulo by zero'|

虽然上述处理方式很简单，但也给出了根据喜好对异常信息进行格式化输出的方案
。或许 *note traceback: 114. 模块能满足更专门的需求。


File: python.info,  Node: 语音播报日志信息,  Next: 缓冲日志消息并有条件地输出它们,  Prev: 异常信息的自定义格式化,  Up: 日志操作手册

10.7.24 语音播报日志信息
------------------------

有时可能需要以声音的形式呈现日志消息。如果系统自带了文本转语音 （TTS）功
能，即便没与 Python 关联也很容易做到。大多数 TTS 系统都有一个可运行的命
令行程序，在 handler 中可以用 *note subprocess: fa. 进行调用。这里假定
TTS 命令行程序不会与用户交互，或需要很长时间才会执行完毕，写入日志的信息
也不会多到影响用户查看，并且可以接受每次播报一条信息，以下示例实现了等一
条信息播完再处理下一条，可能会导致其他 handler 的等待。这个简短示例仅供
演示，假定 ‘espeak’ TTS 包已就绪：

     import logging
     import subprocess
     import sys

     class TTSHandler(logging.Handler):
         def emit(self, record):
             msg = self.format(record)
             # Speak slowly in a female English voice
             cmd = ['espeak', '-s150', '-ven+f3', msg]
             p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                  stderr=subprocess.STDOUT)
             # wait for the program to finish
             p.communicate()

     def configure_logging():
         h = TTSHandler()
         root = logging.getLogger()
         root.addHandler(h)
         # the default formatter just returns the message
         root.setLevel(logging.DEBUG)

     def main():
         logging.info('Hello')
         logging.debug('Goodbye')

     if __name__ == '__main__':
         configure_logging()
         sys.exit(main())

运行后将会以女声播报“Hello”和“Goodbye”。

当然，上述方案也适用于其他 TTS 系统，甚至可以通过利用命令行运行的外部程
序来处理消息。


File: python.info,  Node: 缓冲日志消息并有条件地输出它们,  Next: 通过配置使用UTC GMT 格式化时间,  Prev: 语音播报日志信息,  Up: 日志操作手册

10.7.25 缓冲日志消息并有条件地输出它们
--------------------------------------

在某些情况下，你可能希望在临时区域中记录日志消息，并且只在发生某种特定的
情况下才输出它们。 例如，你可能希望起始在函数中记录调试事件，如果函数执
行完成且没有错误，你不希望输出收集的调试信息以避免造成日志混乱，但如果出
现错误，那么你希望所有调试以及错误消息被输出。

下面是一个示例，展示如何在你的日志记录函数上使用装饰器以实现这一功能。该
示例使用 *note logging.handlers.MemoryHandler: 20f4. ，它允许缓冲已记录
的事件直到某些条件发生，缓冲的事件才会被刷新（‘flushed’） - 传递给另一个
处理程序（ ‘target’ handler）进行处理。 默认情况下， ‘MemoryHandler’ 在
其缓冲区被填满时被刷新，或者看到一个级别大于或等于指定阈值的事件。 如果
想要自定义刷新行为，你可以通过更专业的 ‘MemoryHandler’ 子类来使用这个秘
诀。

这个示例脚本有一个简单的函数 ‘foo’ ，它只是在所有的日志级别中循环运行，
写到 ‘sys.stderr’ ，说明它要记录在哪个级别上，然后在这个级别上实际记录一
个消息。你可以给 ‘foo’ 传递一个参数，如果为 true ，它将在ERROR和
CRITICAL级别记录，否则，它只在DEBUG、INFO和WARNING级别记录。

脚本只是使用了一个装饰器来装饰 ‘foo’，这个装饰器将记录执行所需的条件。装
饰器使用一个记录器作为参数，并在调用被装饰的函数期间附加一个内存处理程序
。装饰器可以使用目标处理程序、记录级别和缓冲区的容量（缓冲记录的数量）来
附加参数。这些参数分别默认为写入‘‘sys.stderr‘‘ 的 *note StreamHandler:
b7d. ， ‘logging.ERROR’ 和 ‘100’。

以下是脚本：

     import logging
     from logging.handlers import MemoryHandler
     import sys

     logger = logging.getLogger(__name__)
     logger.addHandler(logging.NullHandler())

     def log_if_errors(logger, target_handler=None, flush_level=None, capacity=None):
         if target_handler is None:
             target_handler = logging.StreamHandler()
         if flush_level is None:
             flush_level = logging.ERROR
         if capacity is None:
             capacity = 100
         handler = MemoryHandler(capacity, flushLevel=flush_level, target=target_handler)

         def decorator(fn):
             def wrapper(*args, **kwargs):
                 logger.addHandler(handler)
                 try:
                     return fn(*args, **kwargs)
                 except Exception:
                     logger.exception('call failed')
                     raise
                 finally:
                     super(MemoryHandler, handler).flush()
                     logger.removeHandler(handler)
             return wrapper

         return decorator

     def write_line(s):
         sys.stderr.write('%s\n' % s)

     def foo(fail=False):
         write_line('about to log at DEBUG ...')
         logger.debug('Actually logged at DEBUG')
         write_line('about to log at INFO ...')
         logger.info('Actually logged at INFO')
         write_line('about to log at WARNING ...')
         logger.warning('Actually logged at WARNING')
         if fail:
             write_line('about to log at ERROR ...')
             logger.error('Actually logged at ERROR')
             write_line('about to log at CRITICAL ...')
             logger.critical('Actually logged at CRITICAL')
         return fail

     decorated_foo = log_if_errors(logger)(foo)

     if __name__ == '__main__':
         logger.setLevel(logging.DEBUG)
         write_line('Calling undecorated foo with False')
         assert not foo(False)
         write_line('Calling undecorated foo with True')
         assert foo(True)
         write_line('Calling decorated foo with False')
         assert not decorated_foo(False)
         write_line('Calling decorated foo with True')
         assert decorated_foo(True)

运行此脚本时，应看到以下输出：

     Calling undecorated foo with False
     about to log at DEBUG ...
     about to log at INFO ...
     about to log at WARNING ...
     Calling undecorated foo with True
     about to log at DEBUG ...
     about to log at INFO ...
     about to log at WARNING ...
     about to log at ERROR ...
     about to log at CRITICAL ...
     Calling decorated foo with False
     about to log at DEBUG ...
     about to log at INFO ...
     about to log at WARNING ...
     Calling decorated foo with True
     about to log at DEBUG ...
     about to log at INFO ...
     about to log at WARNING ...
     about to log at ERROR ...
     Actually logged at DEBUG
     Actually logged at INFO
     Actually logged at WARNING
     Actually logged at ERROR
     about to log at CRITICAL ...
     Actually logged at CRITICAL

如你所见，实际日志记录输出仅在消息等级为ERROR或更高的事件时发生，但在这
种情况下，任何之前较低消息等级的事件还会被记录。

你当然可以使用传统的装饰方法:

     @log_if_errors(logger)
     def foo(fail=False):
         ...


File: python.info,  Node: 通过配置使用UTC GMT 格式化时间,  Next: 使用上下文管理器的可选的日志记录,  Prev: 缓冲日志消息并有条件地输出它们,  Up: 日志操作手册

10.7.26 通过配置使用UTC (GMT) 格式化时间
----------------------------------------

有时候，你希望使用UTC来格式化时间，这可以通过使用一个类来实现，例如
‘UTCFormatter‘，如下所示：

     import logging
     import time

     class UTCFormatter(logging.Formatter):
         converter = time.gmtime

然后你可以在你的代码中使用 ‘UTCFormatter’，而不是 *note Formatter:
2095.。 如果你想通过配置来实现这一功能，你可以使用 *note dictConfig():
b33. API 来完成，该方法在以下完整示例中展示:

     import logging
     import logging.config
     import time

     class UTCFormatter(logging.Formatter):
         converter = time.gmtime

     LOGGING = {
         'version': 1,
         'disable_existing_loggers': False,
         'formatters': {
             'utc': {
                 '()': UTCFormatter,
                 'format': '%(asctime)s %(message)s',
             },
             'local': {
                 'format': '%(asctime)s %(message)s',
             }
         },
         'handlers': {
             'console1': {
                 'class': 'logging.StreamHandler',
                 'formatter': 'utc',
             },
             'console2': {
                 'class': 'logging.StreamHandler',
                 'formatter': 'local',
             },
         },
         'root': {
             'handlers': ['console1', 'console2'],
        }
     }

     if __name__ == '__main__':
         logging.config.dictConfig(LOGGING)
         logging.warning('The local time is %s', time.asctime())

脚本会运行输出类似下面的内容:

     2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015
     2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015

展示了如何将时间格式化为本地时间和UTC两种形式，其中每种形式对应一个日志
处理器 。


File: python.info,  Node: 使用上下文管理器的可选的日志记录,  Next: 命令行日志应用起步,  Prev: 通过配置使用UTC GMT 格式化时间,  Up: 日志操作手册

10.7.27 使用上下文管理器的可选的日志记录
----------------------------------------

有时候，我们需要暂时更改日志配置，并在执行某些操作后将其还原。为此，上下
文管理器是实现保存和恢复日志上下文的最明显的方式。这是一个关于上下文管理
器的简单例子，它允许你在上下文管理器的作用域内更改日志记录等级以及增加日
志处理器：

     import logging
     import sys

     class LoggingContext:
         def __init__(self, logger, level=None, handler=None, close=True):
             self.logger = logger
             self.level = level
             self.handler = handler
             self.close = close

         def __enter__(self):
             if self.level is not None:
                 self.old_level = self.logger.level
                 self.logger.setLevel(self.level)
             if self.handler:
                 self.logger.addHandler(self.handler)

         def __exit__(self, et, ev, tb):
             if self.level is not None:
                 self.logger.setLevel(self.old_level)
             if self.handler:
                 self.logger.removeHandler(self.handler)
             if self.handler and self.close:
                 self.handler.close()
             # implicit return of None => don't swallow exceptions

如果指定上下文管理器的日志记录等级属性，则在上下文管理器的with语句所涵盖
的代码中，日志记录器的记录等级将临时设置为上下文管理器所配置的日志记录等
级。 如果指定上下文管理的日志处理器属性，则该句柄在进入上下文管理器的上
下文时添加到记录器中，并在退出时被删除。 如果你再也不需要该日志处理器时
，你可以让上下文管理器在退出上下文管理器的上下文时关闭它。

为了说明它是如何工作的，我们可以在上面添加以下代码块:

     if __name__ == '__main__':
         logger = logging.getLogger('foo')
         logger.addHandler(logging.StreamHandler())
         logger.setLevel(logging.INFO)
         logger.info('1. This should appear just once on stderr.')
         logger.debug('2. This should not appear.')
         with LoggingContext(logger, level=logging.DEBUG):
             logger.debug('3. This should appear once on stderr.')
         logger.debug('4. This should not appear.')
         h = logging.StreamHandler(sys.stdout)
         with LoggingContext(logger, level=logging.DEBUG, handler=h, close=True):
             logger.debug('5. This should appear twice - once on stderr and once on stdout.')
         logger.info('6. This should appear just once on stderr.')
         logger.debug('7. This should not appear.')

我们最初设置日志记录器的消息等级为 ‘INFO’，因此消息#1出现，消息#2没有出
现。在接下来的 ‘with``代码块中我们暂时将消息等级变更为 ``DEBUG’，从而消
息 #3 出现。在这一代码块退出后，日志记录器的消息等级恢复为 ‘INFO’，从而
消息 #4 没有出现。在下一个 ‘with’ 代码块中，我们再一次将设置消息等级设置
为 ‘DEBUG’，同时添加一个将消息写入 ‘sys.stdout’ 的日志处理器。因此，消息
#5在控制台出现两次 (分别通过 ‘stderr’ 和 ‘stdout’)。在 ‘with’ 语句完成后
，状态与之前一样，因此消息 #6 出现（类似消息 #1），而消息 #7 没有出现（
类似消息 #2）。

如果我们运行生成的脚本，结果如下：

     $ python logctx.py
     1. This should appear just once on stderr.
     3. This should appear once on stderr.
     5. This should appear twice - once on stderr and once on stdout.
     5. This should appear twice - once on stderr and once on stdout.
     6. This should appear just once on stderr.

我们将‘‘stderr‘‘标准错误重定向到‘‘/dev/null‘‘，我再次运行生成的脚步，唯
一被写入‘‘stdout‘‘标准输出的消息，即我们所能看见的消息，如下：

     $ python logctx.py 2>/dev/null
     5. This should appear twice - once on stderr and once on stdout.

再一次，将 ‘stdout’ 标准输出重定向到 ‘/dev/null’，我获得如下结果：

     $ python logctx.py >/dev/null
     1. This should appear just once on stderr.
     3. This should appear once on stderr.
     5. This should appear twice - once on stderr and once on stdout.
     6. This should appear just once on stderr.

在这种情况下，与预期一致，打印到 ‘stdout’ 标准输出的消息＃5不会出现。

当然，这里描述的方法可以被推广，例如临时附加日志记录过滤器。 请注意，上
面的代码适用于Python 2以及Python 3。


File: python.info,  Node: 命令行日志应用起步,  Next: Qt GUI 日志示例,  Prev: 使用上下文管理器的可选的日志记录,  Up: 日志操作手册

10.7.28 命令行日志应用起步
--------------------------

下面的示例提供了如下功能：

   * 根据命令行参数确定日志级别

   * 在单独的文件中分发多条子命令，同一级别的子命令均以一致的方式记录。

   * 最简单的配置用法

假定有一个命令行应用程序，用于停止、启动或重新启动某些服务。为了便于演示
，不妨将 ‘app.py’ 作为应用程序的主代码文件，并在 ‘start.py’、
‘stop.py``和 ``restart.py’ 中实现单独的命令。再假定要通过命令行参数控制
应用程序的日志粒度，默认为 ‘logging.INFO’ 。以下是 ‘app.py’ 的一个示例：

     import argparse
     import importlib
     import logging
     import os
     import sys

     def main(args=None):
         scriptname = os.path.basename(__file__)
         parser = argparse.ArgumentParser(scriptname)
         levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
         parser.add_argument('--log-level', default='INFO', choices=levels)
         subparsers = parser.add_subparsers(dest='command',
                                            help='Available commands:')
         start_cmd = subparsers.add_parser('start', help='Start a service')
         start_cmd.add_argument('name', metavar='NAME',
                                help='Name of service to start')
         stop_cmd = subparsers.add_parser('stop',
                                          help='Stop one or more services')
         stop_cmd.add_argument('names', metavar='NAME', nargs='+',
                               help='Name of service to stop')
         restart_cmd = subparsers.add_parser('restart',
                                             help='Restart one or more services')
         restart_cmd.add_argument('names', metavar='NAME', nargs='+',
                                  help='Name of service to restart')
         options = parser.parse_args()
         # the code to dispatch commands could all be in this file. For the purposes
         # of illustration only, we implement each command in a separate module.
         try:
             mod = importlib.import_module(options.command)
             cmd = getattr(mod, 'command')
         except (ImportError, AttributeError):
             print('Unable to find the code for command \'%s\'' % options.command)
             return 1
         # Could get fancy here and load configuration from file or dictionary
         logging.basicConfig(level=options.log_level,
                             format='%(levelname)s %(name)s %(message)s')
         cmd(options)

     if __name__ == '__main__':
         sys.exit(main())

‘start’、‘stop’ 和 ‘restart’ 命令可以在单独的模块中实现，启动命令的代码
可如下：

     # start.py
     import logging

     logger = logging.getLogger(__name__)

     def command(options):
         logger.debug('About to start %s', options.name)
         # actually do the command processing here ...
         logger.info('Started the \'%s\' service.', options.name)

然后是停止命令的代码：

     # stop.py
     import logging

     logger = logging.getLogger(__name__)

     def command(options):
         n = len(options.names)
         if n == 1:
             plural = ''
             services = '\'%s\'' % options.names[0]
         else:
             plural = 's'
             services = ', '.join('\'%s\'' % name for name in options.names)
             i = services.rfind(', ')
             services = services[:i] + ' and ' + services[i + 2:]
         logger.debug('About to stop %s', services)
         # actually do the command processing here ...
         logger.info('Stopped the %s service%s.', services, plural)

重启命令类似：

     # restart.py
     import logging

     logger = logging.getLogger(__name__)

     def command(options):
         n = len(options.names)
         if n == 1:
             plural = ''
             services = '\'%s\'' % options.names[0]
         else:
             plural = 's'
             services = ', '.join('\'%s\'' % name for name in options.names)
             i = services.rfind(', ')
             services = services[:i] + ' and ' + services[i + 2:]
         logger.debug('About to restart %s', services)
         # actually do the command processing here ...
         logger.info('Restarted the %s service%s.', services, plural)

如果以默认日志级别运行该程序，会得到以下结果：

     $ python app.py start foo
     INFO start Started the 'foo' service.

     $ python app.py stop foo bar
     INFO stop Stopped the 'foo' and 'bar' services.

     $ python app.py restart foo bar baz
     INFO restart Restarted the 'foo', 'bar' and 'baz' services.

第一个单词是日志级别，第二个单词是日志事件所在的模块或包的名称。

如果修改了日志级别，发送给日志的信息就能得以改变。如要显示更多信息，则可
：

     $ python app.py --log-level DEBUG start foo
     DEBUG start About to start foo
     INFO start Started the 'foo' service.

     $ python app.py --log-level DEBUG stop foo bar
     DEBUG stop About to stop 'foo' and 'bar'
     INFO stop Stopped the 'foo' and 'bar' services.

     $ python app.py --log-level DEBUG restart foo bar baz
     DEBUG restart About to restart 'foo', 'bar' and 'baz'
     INFO restart Restarted the 'foo', 'bar' and 'baz' services.

若要显示的信息少一些，则：

     $ python app.py --log-level WARNING start foo
     $ python app.py --log-level WARNING stop foo bar
     $ python app.py --log-level WARNING restart foo bar baz

这里的命令不会向控制台输出任何信息，因为没有记录 ‘WARNING’ 以上级别的日
志。


File: python.info,  Node: Qt GUI 日志示例,  Prev: 命令行日志应用起步,  Up: 日志操作手册

10.7.29 Qt GUI 日志示例
-----------------------

GUI 应用程序如何记录日志，这是个常见的问题。 Qt(1) 框架是一个流行的跨平
台 UI 框架，采用的是 PySide2(2) 或 PyQt5(3) 库。

下面的例子演示了将日志写入 Qt GUI 程序的过程。这里引入了一个简单的
‘QtHandler’ 类，参数是一个可调用对象，其应为嵌入主线程某个“槽位”中运行的
，因为GUI 的更新由主线程完成。这里还创建了一个工作线程，以便演示由 UI（
通过人工点击日志按钮）和后台工作线程（此处只是记录级别和时间间隔均随机生
成的日志信息）将日志写入 GUI 的过程。

该工作线程是用 Qt 的 ‘QThread’ 类实现的，而不是 *note threading: 10a. 模
块，因为某些情况下只能采用 ‘`QThread’，它与其他 ‘Qt’ 组件的集成性更好一
些。

以下代码应能适用于最新版的 ‘PySide2’ 或 ‘PyQt5’。对于低版本的 Qt 应该也
能适用。更多详情，请参阅代码注释。

     import datetime
     import logging
     import random
     import sys
     import time

     # Deal with minor differences between PySide2 and PyQt5
     try:
         from PySide2 import QtCore, QtGui, QtWidgets
         Signal = QtCore.Signal
         Slot = QtCore.Slot
     except ImportError:
         from PyQt5 import QtCore, QtGui, QtWidgets
         Signal = QtCore.pyqtSignal
         Slot = QtCore.pyqtSlot


     logger = logging.getLogger(__name__)


     #
     # Signals need to be contained in a QObject or subclass in order to be correctly
     # initialized.
     #
     class Signaller(QtCore.QObject):
         signal = Signal(str, logging.LogRecord)

     #
     # Output to a Qt GUI is only supposed to happen on the main thread. So, this
     # handler is designed to take a slot function which is set up to run in the main
     # thread. In this example, the function takes a string argument which is a
     # formatted log message, and the log record which generated it. The formatted
     # string is just a convenience - you could format a string for output any way
     # you like in the slot function itself.
     #
     # You specify the slot function to do whatever GUI updates you want. The handler
     # doesn't know or care about specific UI elements.
     #
     class QtHandler(logging.Handler):
         def __init__(self, slotfunc, *args, **kwargs):
             super().__init__(*args, **kwargs)
             self.signaller = Signaller()
             self.signaller.signal.connect(slotfunc)

         def emit(self, record):
             s = self.format(record)
             self.signaller.signal.emit(s, record)

     #
     # This example uses QThreads, which means that the threads at the Python level
     # are named something like "Dummy-1". The function below gets the Qt name of the
     # current thread.
     #
     def ctname():
         return QtCore.QThread.currentThread().objectName()


     #
     # Used to generate random levels for logging.
     #
     LEVELS = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
               logging.CRITICAL)

     #
     # This worker class represents work that is done in a thread separate to the
     # main thread. The way the thread is kicked off to do work is via a button press
     # that connects to a slot in the worker.
     #
     # Because the default threadName value in the LogRecord isn't much use, we add
     # a qThreadName which contains the QThread name as computed above, and pass that
     # value in an "extra" dictionary which is used to update the LogRecord with the
     # QThread name.
     #
     # This example worker just outputs messages sequentially, interspersed with
     # random delays of the order of a few seconds.
     #
     class Worker(QtCore.QObject):
         @Slot()
         def start(self):
             extra = {'qThreadName': ctname() }
             logger.debug('Started work', extra=extra)
             i = 1
             # Let the thread run until interrupted. This allows reasonably clean
             # thread termination.
             while not QtCore.QThread.currentThread().isInterruptionRequested():
                 delay = 0.5 + random.random() * 2
                 time.sleep(delay)
                 level = random.choice(LEVELS)
                 logger.log(level, 'Message after delay of %3.1f: %d', delay, i, extra=extra)
                 i += 1

     #
     # Implement a simple UI for this cookbook example. This contains:
     #
     # * A read-only text edit window which holds formatted log messages
     # * A button to start work and log stuff in a separate thread
     # * A button to log something from the main thread
     # * A button to clear the log window
     #
     class Window(QtWidgets.QWidget):

         COLORS = {
             logging.DEBUG: 'black',
             logging.INFO: 'blue',
             logging.WARNING: 'orange',
             logging.ERROR: 'red',
             logging.CRITICAL: 'purple',
         }

         def __init__(self, app):
             super().__init__()
             self.app = app
             self.textedit = te = QtWidgets.QPlainTextEdit(self)
             # Set whatever the default monospace font is for the platform
             f = QtGui.QFont('nosuchfont')
             f.setStyleHint(f.Monospace)
             te.setFont(f)
             te.setReadOnly(True)
             PB = QtWidgets.QPushButton
             self.work_button = PB('Start background work', self)
             self.log_button = PB('Log a message at a random level', self)
             self.clear_button = PB('Clear log window', self)
             self.handler = h = QtHandler(self.update_status)
             # Remember to use qThreadName rather than threadName in the format string.
             fs = '%(asctime)s %(qThreadName)-12s %(levelname)-8s %(message)s'
             formatter = logging.Formatter(fs)
             h.setFormatter(formatter)
             logger.addHandler(h)
             # Set up to terminate the QThread when we exit
             app.aboutToQuit.connect(self.force_quit)

             # Lay out all the widgets
             layout = QtWidgets.QVBoxLayout(self)
             layout.addWidget(te)
             layout.addWidget(self.work_button)
             layout.addWidget(self.log_button)
             layout.addWidget(self.clear_button)
             self.setFixedSize(900, 400)

             # Connect the non-worker slots and signals
             self.log_button.clicked.connect(self.manual_update)
             self.clear_button.clicked.connect(self.clear_display)

             # Start a new worker thread and connect the slots for the worker
             self.start_thread()
             self.work_button.clicked.connect(self.worker.start)
             # Once started, the button should be disabled
             self.work_button.clicked.connect(lambda : self.work_button.setEnabled(False))

         def start_thread(self):
             self.worker = Worker()
             self.worker_thread = QtCore.QThread()
             self.worker.setObjectName('Worker')
             self.worker_thread.setObjectName('WorkerThread')  # for qThreadName
             self.worker.moveToThread(self.worker_thread)
             # This will start an event loop in the worker thread
             self.worker_thread.start()

         def kill_thread(self):
             # Just tell the worker to stop, then tell it to quit and wait for that
             # to happen
             self.worker_thread.requestInterruption()
             if self.worker_thread.isRunning():
                 self.worker_thread.quit()
                 self.worker_thread.wait()
             else:
                 print('worker has already exited.')

         def force_quit(self):
             # For use when the window is closed
             if self.worker_thread.isRunning():
                 self.kill_thread()

         # The functions below update the UI and run in the main thread because
         # that's where the slots are set up

         @Slot(str, logging.LogRecord)
         def update_status(self, status, record):
             color = self.COLORS.get(record.levelno, 'black')
             s = '<pre><font color="%s">%s</font></pre>' % (color, status)
             self.textedit.appendHtml(s)

         @Slot()
         def manual_update(self):
             # This function uses the formatted message passed in, but also uses
             # information from the record to format the message in an appropriate
             # color according to its severity (level).
             level = random.choice(LEVELS)
             extra = {'qThreadName': ctname() }
             logger.log(level, 'Manually logged!', extra=extra)

         @Slot()
         def clear_display(self):
             self.textedit.clear()


     def main():
         QtCore.QThread.currentThread().setObjectName('MainThread')
         logging.getLogger().setLevel(logging.DEBUG)
         app = QtWidgets.QApplication(sys.argv)
         example = Window(app)
         example.show()
         sys.exit(app.exec_())

     if __name__=='__main__':
         main()

   ---------- Footnotes ----------

   (1) https://www.qt.io/

   (2) https://pypi.org/project/PySide2/

   (3) https://pypi.org/project/PyQt5/


File: python.info,  Node: 正则表达式HOWTO,  Next: 套接字编程指南,  Prev: 日志操作手册,  Up: Python 常用指引

10.8 正则表达式HOWTO
====================


作者: A.M. Kuchling <<amk@amk.ca>>

摘要
....

本文档是在Python中使用 *note re: de. 模块使用正则表达式的入门教程。 它提
供了比“标准库参考”中相应部分更平和的介绍。

* Menu:

* 概述: 概述<18>.
* 简单模式::
* 使用正则表达式::
* 更多模式能力::
* 修改字符串::
* 常见问题::
* 反馈::


File: python.info,  Node: 概述<18>,  Next: 简单模式,  Up: 正则表达式HOWTO

10.8.1 概述
-----------

正则表达式（称为RE，或正则，或正则表达式模式）本质上是嵌入在Python中的一
种微小的、高度专业化的编程语言，可通过 *note re: de. 模块获得。 使用这种
小语言，你可以为要匹配的可能字符串集指定规则；此集可能包含英语句子，电子
邮件地址，TeX命令或你喜欢的任何内容。 然后，您可以询问诸如“此字符串是否
与模式匹配？”或“此字符串中的模式是否匹配？”等问题。 你还可以使用正则修改
字符串或以各种方式将其拆分。

正则表达式模式被编译成一系列字节码，然后由用 C 编写的匹配引擎执行。对于
高级用途，可能需要特别注意引擎如何执行给定的正则，并将正则写入以某种方式
生成运行速度更快的字节码。 本文档未涉及优化，因为它要求你充分了解匹配引
擎的内部结构。

正则表达式语言相对较小且受限制，因此并非所有可能的字符串处理任务都可以使
用正则表达式完成。 还有一些任务 `可以' 用正则表达式完成，但表达式变得非
常复杂。 在这些情况下，你最好编写 Python 代码来进行处理；虽然 Python 代
码比精心设计的正则表达式慢，但它也可能更容易理解。


File: python.info,  Node: 简单模式,  Next: 使用正则表达式,  Prev: 概述<18>,  Up: 正则表达式HOWTO

10.8.2 简单模式
---------------

我们首先要了解最简单的正则表达式。 由于正则表达式用于对字符串进行操作，
因此我们将从最常见的任务开始：匹配字符。

有关正则表达式（确定性和非确定性有限自动机）的计算机科学的详细解释，你可
以参考几乎所有有关编写编译器的教科书。

* Menu:

* 匹配字符::
* 重复::


File: python.info,  Node: 匹配字符,  Next: 重复,  Up: 简单模式

10.8.2.1 匹配字符
.................

大多数字母和字符只会匹配自己。 例如，正则表达式 ‘test’ 将完全匹配字符串
‘test’ 。 （你可以启用一个不区分大小写的模式，让这个正则匹配 ‘Test’ 或
‘TEST’，稍后会详细介绍。）

这条规则有例外；一些字符是特殊的 `metacharacters' ，并且不匹配自己。 相
反，它们表示应该匹配一些与众不同的东西，或者通过重复它们或改变它们的含义
来影响正则的其他部分。 本文档的大部分内容都致力于讨论各种元字符及其功能
。

这是元字符的完整列表；它们的意思将在本HOWTO的其余部分讨论。

     . ^ $ * + ? { } [ ] \ | ( )

我们将看到的第一个元字符是 ‘[’ 和 ‘]’ 。 它们用于指定字符类，它是你希望
匹配的一组字符。 可以单独列出字符，也可以通过给出两个字符并用 ‘'-'’ 标记
将它们分开来表示一系列字符。 例如， ‘[abc]’ 将匹配任何字符 ‘a’、 ‘b’ 或
‘c’ ；这与 ‘[a-c]’ 相同，它使用一个范围来表示同一组字符。 如果你只想匹配
小写字母，你的正则是 ‘[a-z]’ 。

字符类中的元字符不生效。 例如，‘[akm$]’ 将匹配 ‘'a'’ ， ‘'k'’ 、 ‘'m'’ 或
‘'$'’ 中的任意字符； ‘'$'’ 通常是一个元字符，但在一个字符类中它被剥夺了
特殊性。

你可以通过以下方式匹配 `complementing' 设置的字符类中未列出的字符。这通
过包含一个 ‘'^'’ 作为该类的第一个字符来表示。 例如，‘[^5]’ 将匹配除
‘'5'’ 之外的任何字符。 如果插入符出现在字符类的其他位置，则它没有特殊含
义。 例如：‘[5^]’ 将匹配 ‘'5'’ 或 ‘'^'’。

也许最重要的元字符是反斜杠，‘\’。 与 Python 字符串文字一样，反斜杠后面可
以跟各种字符，以指示各种特殊序列。它也用于转义所有元字符，因此您仍然可以
在模式中匹配它们；例如，如果你需要匹配 ‘[’ 或 ‘\’，你可以在它们前面加一
个反斜杠来移除它们的特殊含义：‘\[’ 或 ‘\\’。

一些以 ‘'\'’ 开头的特殊序列表示通常有用的预定义字符集，例如数字集、字母
集或任何非空格的集合。

让我们举一个例子：‘\w’ 匹配任何字母数字字符。 如果正则表达式模式以字节类
表示，这相当于类 ‘[a-zA-Z0-9_]’。如果正则表达式是一个字符串，‘\w’ 将匹配
由 *note unicodedata: 11b. 模块提供的 Unicode 数据库中标记为字母的所有字
符。 通过在编译正则表达式时提供 *note re.ASCII: 3d0. 标志，可以在字符串
模式中使用更为受限制的 ‘\w’ 定义。

以下特殊序列列表不完整。 有关 Unicode 字符串模式的序列和扩展类定义的完整
列表，请参阅标准库参考中的最后一部分 *note 正则表达式语法: 175d. 。通常
，Unicode 版本匹配 Unicode 数据库中相应类别中的任何字符。

‘\d’

     匹配任何十进制数字；这等价于类 ‘[0-9]’。

‘\D’

     匹配任何非数字字符；这等价于类 ‘[^0-9]’。

‘\s’

     匹配任何空白字符；这等价于类 ‘[ \t\n\r\f\v]’。

‘\S’

     匹配任何非空白字符；这相当于类 ‘[^ \t\n\r\f\v]’。

‘\w’

     匹配任何字母与数字字符；这相当于类 ‘[a-zA-Z0-9_]’。

‘\W’

     匹配任何非字母与数字字符；这相当于类 ‘[^a-zA-Z0-9_]’。

这些序列可以包含在字符类中。 例如，‘[\s,.]’ 是一个匹配任何空格字符的字符
类或者 ‘','’ ，或 ‘'.'’。

本节的最后一个元字符是 ‘.’ 。 它匹配除换行符之外的任何内容，并且有一个可
选模式（ *note re.DOTALL: 1761. ）甚至可以匹配换行符。 ‘.’ 常用于你想匹
配“任何字符”的地方。


File: python.info,  Node: 重复,  Prev: 匹配字符,  Up: 简单模式

10.8.2.2 重复
.............

能够匹配不同的字符集合是正则表达式可以做的第一件事，这对于字符串可用方法
来说是不可能的。 但是，如果这是正则表达式的唯一额外功能，那么它们就不会
有太大的优势。 另一个功能是你可以指定正则的某些部分必须重复一定次数。

重复中我们要了解的第一个元字符是 ‘*’。 ‘*’ 与字面字符 ‘'*'’ 不匹配；相反
，它指定前一个字符可以匹配零次或多次，而不是恰好一次。

例如，‘ca*t’ 将匹配 ‘'ct'’ (0个 ‘'a'’ 字符)，‘'cat'’ (1个 ‘'a'’ )，
‘'caaat'’ (3个 ‘'a'’ 字符)，等等。

类似 ‘*’ 这样的重复是 `贪婪的'；当重复正则时，匹配引擎将尝试尽可能多地重
复它。 如果模式的后续部分不匹配，则匹配引擎将回退并以较少的重复次数再次
尝试。

一个逐步的例子将使这更加明显。 让我们考虑表达式 ‘a[bcd]*b’。 这个正则匹
配字母 ‘'a'’，类 ‘[bcd]’ 中的零或多个字母，最后以 ‘'b'’ 结尾。 现在想象
一下这个正则与字符串 ‘'abcbd'’ 匹配。

步骤       匹配            说明
                           
-----------------------------------------------------------------
                           
1          ‘a’             正则中的 ‘a’ 匹配。
                           
                           
2          ‘abcbd’         引擎尽可能多地匹配 ‘[bcd]*’ ，直到
                           字符串结束。
                           
                           
3          `失败'          引擎尝试匹配 ‘b’ ，但是当前位置位于
                           字符串结束，所以匹配失败。
                           
                           
4          ‘abcb’          回退一次，‘[bcd]*’ 少匹配一个字符。
                           
                           
5          `失败'          再次尝试匹配 ‘b’ ， 但是当前位置是
                           最后一个字符 ‘'d'’ 。
                           
                           
6          ‘abc’           再次回退，所以 ‘[bcd]*’ 只匹配 ‘bc’
                           。
                           
                           
6          ‘abcb’          再试一次 ‘b’ 。 这次当前位置的字符
                           是 ‘'b'’ ，所以它成功了。
                           

正则现在已经结束了，它已经匹配了 ‘'abcb'’。 这演示了匹配引擎最初如何进行
，如果没有找到匹配，它将逐步回退并一次又一次地重试正则的其余部分。 它将
回退，直到它为 ‘[bcd]*’ 尝试零匹配，如果随后失败，引擎将断定该字符串与正
则完全不匹配。

另一个重复的元字符是 ‘+’，它匹配一次或多次。 要特别注意 ‘*’ 和 ‘+’ 之间
的区别；‘*’ 匹配 `零次' 或更多次，因此重复的任何东西都可能根本不存在，而
‘+’ 至少需要 `一次'。 使用类似的例子，‘ca+t’ 将匹配 ‘'cat'’ (1 个
‘'a'’)，‘'caaat'’ (3 个 ‘'a'’)，但不会匹配 ‘'ct'’。

还有两个重复限定符。 问号字符 ‘?’ 匹配一次或零次；你可以把它想象成是可选
的。 例如，‘home-?brew’ 匹配 ‘'homebrew'’ 或 ‘'home-brew'’。

最复杂的重复限定符是 ‘{m,n}’，其中 `m' 和 `n' 是十进制整数。 这个限定符
意味着必须至少重复 `m' 次，最多重复 `n' 次。 例如，‘a/{1,3}b’ 将匹配
‘'a/b'’ ，‘'a//b'’ 和 ‘'a///b'’ 。 它不匹配没有斜线的 ‘'ab'’，或者有四个
的 ‘'a////b'’。

你可以省略 `m' 或 `n'; 在这种情况下，将假定缺失值的合理值。 省略 `m' 被
解释为 0 下限，而省略 `n' 则为无穷大的上限。

还原论者的读者可能会注意到其他三个限定符都可以用这种表示法表达。 ‘{0,}’
与 ‘*’ 相同， ‘{1,}’ 相当于 ‘+’ ， ‘{0,1}’ 和 ‘?’ 相同。 最好使用 ‘*’ ，
‘+’ 或 ‘?’ ，只要因为它们更短更容易阅读。


File: python.info,  Node: 使用正则表达式,  Next: 更多模式能力,  Prev: 简单模式,  Up: 正则表达式HOWTO

10.8.3 使用正则表达式
---------------------

现在我们已经看了一些简单的正则表达式，我们如何在 Python 中实际使用它们？
*note re: de. 模块提供了正则表达式引擎的接口，允许你将正则编译为对象，然
后用它们进行匹配。

* Menu:

* 编译正则表达式::
* 反斜杠灾难::
* 应用匹配::
* 模块级别函数: 模块级别函数<2>.
* 编译标志::


File: python.info,  Node: 编译正则表达式,  Next: 反斜杠灾难,  Up: 使用正则表达式

10.8.3.1 编译正则表达式
.......................

正则表达式被编译成模式对象，模式对象具有各种操作的方法，例如搜索模式匹配
或执行字符串替换。:

     >>> import re
     >>> p = re.compile('ab*')
     >>> p
     re.compile('ab*')

*note re.compile(): 452. 也接受一个可选的 `flags' 参数，用于启用各种特殊
功能和语法变体。 我们稍后将介绍可用的设置，但现在只需一个例子

     >>> p = re.compile('ab*', re.IGNORECASE)

正则作为字符串传递给 *note re.compile(): 452. 。 正则被处理为字符串，因
为正则表达式不是核心Python语言的一部分，并且没有创建用于表达它们的特殊语
法。 （有些应用程序根本不需要正则，因此不需要通过包含它们来扩展语言规范
。）相反，*note re: de. 模块只是Python附带的C扩展模块，就类似于 *note
socket: f0. 或 *note zlib: 145. 模块。

将正则放在字符串中可以使 Python 语言更简单，但有一个缺点是下一节的主题。


File: python.info,  Node: 反斜杠灾难,  Next: 应用匹配,  Prev: 编译正则表达式,  Up: 使用正则表达式

10.8.3.2 反斜杠灾难
...................

如前所述，正则表达式使用反斜杠字符 (‘'\'’) 来表示特殊形式或允许使用特殊
字符而不调用它们的特殊含义。 这与 Python 在字符串文字中用于相同目的的相
同字符的使用相冲突。

假设你想要编写一个与字符串 ‘\section’ 相匹配的正则，它可以在 LaTeX 文件
中找到。 要找出在程序代码中写入的内容，请从要匹配的字符串开始。 接下来，
您必须通过在反斜杠前面添加反斜杠和其他元字符，从而产生字符串
‘\\section’。 必须传递给 *note re.compile(): 452. 的结果字符串必须是
‘\\section’。 但是，要将其表示为 Python 字符串文字，必须 `再次' 转义两个
反斜杠。

字符                    阶段
                        
-----------------------------------------------------------------------
                        
‘\section’              被匹配的字符串
                        
                        
‘\\section’             为 *note re.compile(): 452. 转义的反斜杠
                        
                        
‘"\\\\section"’         为字符串字面转义的反斜杠
                        

简而言之，要匹配文字反斜杠，必须将 ‘'\\\\'’ 写为正则字符串，因为正则表达
式必须是 ‘\\’，并且每个反斜杠必须表示为 ‘\\’ 在常规Python字符串字面中。
在反复使用反斜杠的正则中，这会导致大量重复的反斜杠，并使得生成的字符串难
以理解。

解决方案是使用 Python 的原始字符串表示法来表示正则表达式；反斜杠不以任何
特殊的方式处理前缀为 ‘'r'’ 的字符串字面，因此 ‘r"\n"’ 是一个包含 ‘'\'’ 和
‘'n'’ 的双字符字符串，而 ‘"\n"’ 是一个包含换行符的单字符字符串。 正则表
达式通常使用这种原始字符串表示法用 Python 代码编写。

此外，在正则表达式中有效但在 Python 字符串文字中无效的特殊转义序列现在导
致 *note DeprecationWarning: 279. 并最终变为 *note SyntaxError: 460.。 这
意味着如果未使用原始字符串表示法或转义反斜杠，序列将无效。

常规字符串              原始字符串
                        
-----------------------------------------------
                        
‘"ab*"’                 ‘r"ab*"’
                        
                        
‘"\\\\section"’         ‘r"\\section"’
                        
                        
‘"\\w+\\s+\\1"’         ‘r"\w+\s+\1"’
                        


File: python.info,  Node: 应用匹配,  Next: 模块级别函数<2>,  Prev: 反斜杠灾难,  Up: 使用正则表达式

10.8.3.3 应用匹配
.................

一旦你有一个表示编译正则表达式的对象，你用它做什么？ 模式对象有几种方法
和属性。 这里只介绍最重要的内容；请参阅 *note re: de. 文档获取完整列表。

方法 / 属性            目的
                       
---------------------------------------------------------------------------
                       
‘match()’              确定正则是否从字符串的开头匹配。
                       
                       
‘search()’             扫描字符串，查找此正则匹配的任何位置。
                       
                       
‘findall()’            找到正则匹配的所有子字符串，并将它们作为列表返回
                       。
                       
                       
‘finditer()’           找到正则匹配的所有子字符串，并将它们返回为一个
                       *note iterator: 104b.。
                       

如果没有找到匹配， *note match(): 176c. 和 *note search(): 176d. 返回
‘None’ 。如果它们成功， 一个 *note 匹配对象: 8a6. 实例将被返回，包含匹配
相关的信息：起始和终结位置、匹配的子串以及其它。

你可以通过交互式实验 *note re: de. 模块来了解这一点。 如果你有 *note
tkinter: 10d.，你可能还想查看 Tools/demo/redemo.py(1)，这是 Python 发行
附带的演示程序。 它允许你输入正则和字符串，并显示RE是匹配还是失败。
‘redemo.py’ 在尝试调试复杂的正则时非常有用。

本 HOWTO 使用标准 Python 解释器作为示例。 首先，运行 Python 解释器，导入
*note re: de. 模块，然后编译一个正则

     >>> import re
     >>> p = re.compile('[a-z]+')
     >>> p
     re.compile('[a-z]+')

现在，你可以尝试匹配正则 ‘[a-z]+’ 的各种字符串。 空字符串根本不匹配，因
为 ‘+’ 表示“一次或多次重复”。 *note match(): 176c. 在这种情况下应返回
‘None’，这将导致解释器不打印输出。 你可以显式打印 ‘match()’ 的结果，使其
清晰。:

     >>> p.match("")
     >>> print(p.match(""))
     None

现在，让我们尝试一下它应该匹配的字符串，例如 ‘tempo’。在这个例子中 *note
match(): 176c. 将返回一个 *note 匹配对象: 8a6.，因此你应该将结果储存到一
个变量中以供稍后使用。

     >>> m = p.match('tempo')
     >>> m
     <re.Match object; span=(0, 5), match='tempo'>

现在你可以检查 *note 匹配对象: 8a6. 以获取有关匹配字符串的信息。 匹配对
象实例也有几个方法和属性；最重要的是：

方法 / 属性            目的
                       
------------------------------------------------------------------------
                       
‘group()’              返回正则匹配的字符串
                       
                       
‘start()’              返回匹配的开始位置
                       
                       
‘end()’                返回匹配的结束位置
                       
                       
‘span()’               返回包含匹配 (start, end) 位置的元组
                       

尝试这些方法很快就会清楚它们的含义:

     >>> m.group()
     'tempo'
     >>> m.start(), m.end()
     (0, 5)
     >>> m.span()
     (0, 5)

*note group(): 1781. 返回正则匹配的子字符串。 *note start(): 1785. 和
*note end(): 1786. 返回匹配的起始和结束索引。 *note span(): 1787. 在单个
元组中返回开始和结束索引。 由于 *note match(): 176c. 方法只检查正则是否
在字符串的开头匹配，所以 ‘start()’ 将始终为零。 但是，模式的 *note
search(): 176d. 方法会扫描字符串，因此在这种情况下匹配可能不会从零开始。
:

     >>> print(p.match('::: message'))
     None
     >>> m = p.search('::: message'); print(m)
     <re.Match object; span=(4, 11), match='message'>
     >>> m.group()
     'message'
     >>> m.span()
     (4, 11)

在实际程序中，最常见的样式是在变量中存储 *note 匹配对象: 8a6.，然后检查
它是否为 ‘None’。 这通常看起来像:

     p = re.compile( ... )
     m = p.match( 'string goes here' )
     if m:
         print('Match found: ', m.group())
     else:
         print('No match')

两种模式方法返回模式的所有匹配项。 *note findall(): 1777. 返回匹配字符串
的列表:

     >>> p = re.compile(r'\d+')
     >>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
     ['12', '11', '10']

在这个例子中需要 ‘r’ 前缀，使字面为原始字符串字面，因为普通的“加工”字符
串字面中的转义序列不能被 Python 识别为正则表达式，导致 *note
DeprecationWarning: 279. 并最终产生 *note SyntaxError: 460.。 请参阅
*note 反斜杠灾难: 419e.。

*note findall(): 1777. 必须先创建整个列表才能返回结果。 *note
finditer(): 1778. 方法将一个 *note 匹配对象: 8a6. 的序列返回为一个 *note
iterator: 104b.

     >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
     >>> iterator
     <callable_iterator object at 0x...>
     >>> for match in iterator:
     ...     print(match.span())
     ...
     (0, 2)
     (22, 24)
     (29, 31)

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Tools/demo/redemo.py


File: python.info,  Node: 模块级别函数<2>,  Next: 编译标志,  Prev: 应用匹配,  Up: 使用正则表达式

10.8.3.4 模块级别函数
.....................

你不必创建模式对象并调用其方法；*note re: de. 模块还提供了顶级函数 *note
match(): bbb.，*note search(): bba.，*note findall(): 96b.，*note sub():
483. 等等。 这些函数采用与相应模式方法相同的参数，并将正则字符串作为第一
个参数添加，并仍然返回 ‘None’ 或 *note 匹配对象: 8a6. 实例。:

     >>> print(re.match(r'From\s+', 'Fromage amk'))
     None
     >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')
     <re.Match object; span=(0, 5), match='From '>

本质上，这些函数只是为你创建一个模式对象，并在其上调用适当的方法。 它们
还将编译对象存储在缓存中，因此使用相同的未来调用将不需要一次又一次地解析
该模式。

你是否应该使用这些模块级函数，还是应该自己获取模式并调用其方法？ 如果你
正在循环中访问正则表达式，预编译它将节省一些函数调用。 在循环之外，由于
有内部缓存，没有太大区别。


File: python.info,  Node: 编译标志,  Prev: 模块级别函数<2>,  Up: 使用正则表达式

10.8.3.5 编译标志
.................

编译标志允许你修改正则表达式的工作方式。 标志在 *note re: de. 模块中有两
个名称，长名称如 ‘IGNORECASE’ 和一个简短的单字母形式，例如 ‘I’。 （如果
你熟悉 Perl 的模式修饰符，则单字母形式使用和其相同的字母；例如， *note
re.VERBOSE: 1770. 的缩写形式为 *note re.X: 1768.。）多个标志可以 通过按
位或运算来指定它们；例如，‘re.I | re.M’ 设置 ‘I’ 和 ‘M’ 标志。

这是一个可用标志表，以及每个标志的更详细说明。

Flag                                  含义
                                      
---------------------------------------------------------------------------------------
                                      
‘ASCII’, ‘A’                          使几个转义如 ‘\w’、‘\b’、‘\s’ 和 ‘\d’ 匹配仅与
                                      具有相应特征属性的 ASCII 字符匹配。
                                      
                                      
‘DOTALL’, ‘S’                         使 ‘.’ 匹配任何字符，包括换行符。
                                      
                                      
‘IGNORECASE’, ‘I’                     进行大小写不敏感匹配。
                                      
                                      
‘LOCALE’, ‘L’                         进行区域设置感知匹配。
                                      
                                      
‘MULTILINE’, ‘M’                      多行匹配，影响 ‘^’ 和 ‘$’。
                                      
                                      
‘VERBOSE’, ‘X’ （为 ’扩展’）          启用详细的正则，可以更清晰，更容易理解。
                                      

 -- 数据: I

 -- 数据: IGNORECASE

     执行不区分大小写的匹配；字符类和字面字符串将通过忽略大小写来匹配字
     母。 例如，‘[A-Z]’ 也匹配小写字母。 除非使用 ‘ASCII’ 标志来禁用非
     ASCII匹配，否则完全 Unicode 匹配也有效。 当 Unicode 模式 ‘[a-z]’ 或
     ‘[A-Z]’ 与 ‘IGNORECASE’ 标志结合使用时，它们将匹配 52 个 ASCII 字母
     和 4 个额外的非 ASCII 字母：’İ’ (U+0130，拉丁大写字母 I，带上面的点
     )，’ı’ (U+0131，拉丁文小写字母无点 i)，’s’ (U+017F，拉丁文小写字母
     长 s) 和’K’ (U+212A，开尔文符号)。 ‘Spam’ 将匹配 ‘'Spam'’，
     ‘'spam'’，‘'spAM'’ 或 ‘'ſpam'’ (后者仅在 Unicode 模式下匹配)。 此小
     写不考虑当前区域设置；如果你还设置了 ‘LOCALE’ 标志，则将考虑。

 -- 数据: L

 -- 数据: LOCALE

     使 ‘\w’、‘\W’、‘\b’、‘\B’ 和大小写敏感匹配依赖于当前区域而不是
     Unicode 数据库。

     区域设置是 C 库的一个功能，旨在帮助编写考虑到语言差异的程序。例如，
     如果你正在处理编码的法语文本，那么你希望能够编写 ‘\w+’ 来匹配单词，
     但 ‘\w’ 只匹配字符类 ‘[A-Za-z]’ 字节模式；它不会匹配对应于 ‘é’ 或
     ‘ç’ 的字节。如果你的系统配置正确并且选择了法语区域设置，某些C函数将
     告诉程序对应于 ‘é’ 的字节也应该被视为字母。在编译正则表达式时设置
     ‘LOCALE’ 标志将导致生成的编译对象将这些C函数用于 ‘\w’；这比较慢，但
     也可以使 ‘\w+’ 匹配你所期望的法语单词。在 Python 3 中不鼓励使用此标
     志，因为语言环境机制非常不可靠，它一次只处理一个“文化”，它只适用于
     8 位语言环境。默认情况下，Python 3 中已经为 Unicode（str）模式启用
     了 Unicode 匹配，并且它能够处理不同的区域/语言。

 -- 数据: M

 -- 数据: MULTILINE

     (‘^’ 和 ‘$’ 还没有解释；它们将在以下部分介绍 *note 更多元字符:
     41a2.。)

     通常 ‘^’ 只匹配字符串的开头，而 ‘$’ 只匹配字符串的结尾，紧接在字符
     串末尾的换行符（如果有的话）之前。 当指定了这个标志时，‘^’ 匹配字符
     串的开头和字符串中每一行的开头，紧跟在每个换行符之后。 类似地，‘$’
     元字符匹配字符串的结尾和每行的结尾（紧接在每个换行符之前）。

 -- 数据: S

 -- 数据: DOTALL

     使 ‘'.'’ 特殊字符匹配任何字符，包括换行符；没有这个标志，‘'.'’ 将匹
     配任何字符 `除了' 换行符。

 -- 数据: A

 -- 数据: ASCII

     使 ‘\w’、‘\W’、‘\b’、‘\B’、‘\s’ 和 ‘\S’ 执行仅 ASCII 匹配而不是完整
     匹配 Unicode 匹配。 这仅对 Unicode 模式有意义，并且对于字节模式将被
     忽略。

 -- 数据: X

 -- 数据: VERBOSE

     此标志允许你编写更易读的正则表达式，方法是为您提供更灵活的格式化方
     式。 指定此标志后，将忽略正则字符串中的空格，除非空格位于字符类中或
     前面带有未转义的反斜杠；这使你可以更清楚地组织和缩进正则。 此标志还
     允许你将注释放在正则中，引擎将忽略该注释；注释标记为 ‘'#'’ 既不是在
     字符类中，也不是在未转义的反斜杠之前。

     例如，这里的正则使用 *note re.VERBOSE: 1770.；看看阅读有多容易？:

          charref = re.compile(r"""
           &[#]                # Start of a numeric entity reference
           (
               0[0-7]+         # Octal form
             | [0-9]+          # Decimal form
             | x[0-9a-fA-F]+   # Hexadecimal form
           )
           ;                   # Trailing semicolon
          """, re.VERBOSE)

     如果没有详细设置，正则将如下所示:

          charref = re.compile("&#(0[0-7]+"
                               "|[0-9]+"
                               "|x[0-9a-fA-F]+);")

     在上面的例子中，Python的字符串文字的自动连接已被用于将正则分解为更
     小的部分，但它仍然比以下使用 *note re.VERBOSE: 1770. 版本更难理解。


File: python.info,  Node: 更多模式能力,  Next: 修改字符串,  Prev: 使用正则表达式,  Up: 正则表达式HOWTO

10.8.4 更多模式能力
-------------------

到目前为止，我们只介绍了正则表达式的一部分功能。 在本节中，我们将介绍一
些新的元字符，以及如何使用组来检索匹配的文本部分。

* Menu:

* 更多元字符::
* 分组::
* 非捕获和命名组::
* 前向断言::


File: python.info,  Node: 更多元字符,  Next: 分组,  Up: 更多模式能力

10.8.4.1 更多元字符
...................

我们还没有涉及到一些元字符。 其中大部分内容将在本节中介绍。

要讨论的其余一些元字符是 `零宽度断言' 。 它们不会使解析引擎在字符串中前
进一个字符；相反，它们根本不占用任何字符，只是成功或失败。例如，‘\b’ 是
一个断言，指明当前位置位于字边界；这个位置根本不会被 ‘\b’ 改变。这意味着
永远不应重复零宽度断言，因为如果它们在给定位置匹配一次，它们显然可以无限
次匹配。

‘|’

     或者“or”运算符。 如果 `A' 和 `B' 是正则表达式，‘A|B’ 将匹配任何与
     `A' 或 `B' 匹配的字符串。 ‘|’ 具有非常低的优先级，以便在交替使用多
     字符字符串时使其合理地工作。 ‘Crow|Servo’ 将匹配 ‘'Crow'’ 或
     ‘'Servo'’，而不是 ‘'Cro'’、‘'w'’ 或 ‘'S'’ 和 ‘'ervo'’。

     要匹配字面 ‘'|'’，请使用 ‘\|’，或将其括在字符类中，如 ‘[|]’。

‘^’

     在行的开头匹配。 除非设置了 ‘MULTILINE’ 标志，否则只会在字符串的开
     头匹配。 在 ‘MULTILINE’ 模式下，这也在字符串中的每个换行符后立即匹
     配。

     例如，如果你希望仅在行的开头匹配单词 ‘From’，则要使用的正则
     ‘^From’。:

          >>> print(re.search('^From', 'From Here to Eternity'))
          <re.Match object; span=(0, 4), match='From'>
          >>> print(re.search('^From', 'Reciting From Memory'))
          None

     要匹配字面 ‘'^'’，使用 ‘\^’。

‘$’

     匹配行的末尾，定义为字符串的结尾，或者后跟换行符的任何位置。:

          >>> print(re.search('}$', '{block}'))
          <re.Match object; span=(6, 7), match='}'>
          >>> print(re.search('}$', '{block} '))
          None
          >>> print(re.search('}$', '{block}\n'))
          <re.Match object; span=(6, 7), match='}'>

     以匹配字面 ‘'$'’，使用 ‘\$’ 或者将其包裹在一个字符类中，例如 ‘[$]’。

‘\A’

     仅匹配字符串的开头。 当不在 ‘MULTILINE’ 模式时，‘\A’ 和 ‘^’ 实际上
     是相同的。 在 ‘MULTILINE’ 模式中，它们是不同的: ‘\A’ 仍然只在字符串
     的开头匹配，但 ‘^’ 可以匹配在换行符之后的字符串内的任何位置。

‘\Z’

     只匹配字符串尾。

‘\b’

     字边界。 这是一个零宽度断言，仅在单词的开头或结尾处匹配。 单词被定
     义为一个字母数字字符序列，因此单词的结尾由空格或非字母数字字符表示
     。

     以下示例仅当它是一个完整的单词时匹配 ‘class’；当它包含在另一个单词
     中时将不会匹配。

          >>> p = re.compile(r'\bclass\b')
          >>> print(p.search('no class at all'))
          <re.Match object; span=(3, 8), match='class'>
          >>> print(p.search('the declassified algorithm'))
          None
          >>> print(p.search('one subclass is'))
          None

     使用这个特殊序列时，你应该记住两个细微之处。 首先，这是 Python 的字
     符串文字和正则表达式序列之间最严重的冲突。 在 Python 的字符串文字中
     ，‘\b’ 是退格字符，ASCII 值为8。 如果你没有使用原始字符串，那么
     Python 会将 ‘\b’ 转换为退格，你的正则不会按照你的预期匹配。 以下示
     例与我们之前的正则看起来相同，但省略了正则字符串前面的 ‘'r'’。:

          >>> p = re.compile('\bclass\b')
          >>> print(p.search('no class at all'))
          None
          >>> print(p.search('\b' + 'class' + '\b'))
          <re.Match object; span=(0, 7), match='\x08class\x08'>

     其次，在一个字符类中，这个断言没有用处，‘\b’ 表示退格字符，以便与
     Python 的字符串文字兼容。

‘\B’

     另一个零宽度断言，这与 ‘\b’ 相反，仅在当前位置不在字边界时才匹配。


File: python.info,  Node: 分组,  Next: 非捕获和命名组,  Prev: 更多元字符,  Up: 更多模式能力

10.8.4.2 分组
.............

通常，你需要获取更多信息，而不仅仅是正则是否匹配。 正则表达式通常用于通
过将正则分成几个子组来解析字符串，这些子组匹配不同的感兴趣组件。 例如，
RFC-822 标题行分为标题名称和值，用 ‘':'’ 分隔，如下所示：

     From: author@example.com
     User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
     MIME-Version: 1.0
     To: editor@example.com

这可以通过编写与整个标题行匹配的正则表达式来处理，并且具有与标题名称匹配
的一个组，以及与标题的值匹配的另一个组。

组由 ‘'('’，‘')'’ 元字符标记。 ‘'('’ 和 ‘')'’ 与数学表达式的含义大致相同
；它们将包含在其中的表达式组合在一起，你可以使用重复限定符重复组的内容，
例如 ‘*’，‘+’，‘?’ 或 ‘{m,n}’。 例如，‘(ab)*’ 将匹配 ‘ab’ 的零次或多次重
复。:

     >>> p = re.compile('(ab)*')
     >>> print(p.match('ababababab').span())
     (0, 10)

用 ‘'('’，‘')'’ 表示的组也捕获它们匹配的文本的起始和结束索引；这可以通过
将参数传递给 *note group(): 1781.、*note start(): 1785.、*note end():
1786. 以及 *note span(): 1787.。 组从 0 开始编号。组 0 始终存在；它表示
整个正则，所以 *note 匹配对象: 8a6. 方法都将组 0 作为默认参数。 稍后我们
将看到如何表达不捕获它们匹配的文本范围的组。:

     >>> p = re.compile('(a)b')
     >>> m = p.match('ab')
     >>> m.group()
     'ab'
     >>> m.group(0)
     'ab'

子组从左到右编号，从 1 向上编号。 组可以嵌套；要确定编号，只需计算从左到
右的左括号字符。:

     >>> p = re.compile('(a(b)c)d')
     >>> m = p.match('abcd')
     >>> m.group(0)
     'abcd'
     >>> m.group(1)
     'abc'
     >>> m.group(2)
     'b'

*note group(): 1781. 可以一次传递多个组号，在这种情况下，它将返回一个包
含这些组的相应值的元组。:

     >>> m.group(2,1,2)
     ('b', 'abc', 'b')

*note groups(): 1783. 方法返回一个元组，其中包含所有子组的字符串，从1到
最后一个子组。:

     >>> m.groups()
     ('abc', 'b')

模式中的后向引用允许你指定还必须在字符串中的当前位置找到先前捕获组的内容
。 例如，如果可以在当前位置找到组 1 的确切内容，则 ‘\1’ 将成功，否则将失
败。 请记住，Python 的字符串文字也使用反斜杠后跟数字以允许在字符串中包含
任意字符，因此正则中引入反向引用时务必使用原始字符串。

例如，以下正则检测字符串中的双字。:

     >>> p = re.compile(r'\b(\w+)\s+\1\b')
     >>> p.search('Paris in the the spring').group()
     'the the'

像这样的后向引用通常不仅仅用于搜索字符串 —— 很少有文本格式以这种方式重复
数据 —— 但是你很快就会发现它们在执行字符串替换时 `非常' 有用。


File: python.info,  Node: 非捕获和命名组,  Next: 前向断言,  Prev: 分组,  Up: 更多模式能力

10.8.4.3 非捕获和命名组
.......................

精心设计的正则可以使用许多组，既可以捕获感兴趣的子串，也可以对正则本身进
行分组和构建。 在复杂的正则中，很难跟踪组号。 有两个功能可以帮助解决这个
问题。 它们都使用常用语法进行正则表达式扩展，因此我们首先看一下。

Perl 5 以其对标准正则表达式的强大补充而闻名。 对于这些新功能，Perl 开发
人员无法选择新的单键击元字符或以 ‘\’ 开头的新特殊序列，否则 Perl 的正则
表达式与标准正则容易混淆。 例如，如果他们选择 ‘&’ 作为一个新的元字符，旧
的表达式将假设 ‘&’ 是一个普通字符，并且不会编写 ‘\&’ 或 ‘[&]’。

Perl 开发人员选择的解决方案是使用 ‘(?...)’ 作为扩展语法。 括号后面的 ‘?’
是一个语法错误，因为 ‘?’ 没有什么可重复的，所以这并没有引入任何兼容性问
题。 紧跟在 ‘?’ 之后的字符表示正在使用什么扩展名，所以 ‘(?=foo)’ 是一个
东西（一个正向的先行断言）和 ‘(?:foo)’ 是其它东西（ 包含子表达式 ‘foo’ 的
非捕获组）。

Python 支持一些 Perl 的扩展，并增加了新的扩展语法用于 Perl 的扩展语法。
如果在问号之后的第一个字符为 ‘P’，即表明其为 Python 专属的扩展。

现在我们已经了解了一般的扩展语法，我们可以回到简化复杂正则中组处理的功能
。

有时你会想要使用组来表示正则表达式的一部分，但是对检索组的内容不感兴趣。
你可以通过使用非捕获组来显式表达这个事实: ‘(?:...)’，你可以用任何其他正
则表达式替换 ‘...’。:

     >>> m = re.match("([abc])+", "abc")
     >>> m.groups()
     ('c',)
     >>> m = re.match("(?:[abc])+", "abc")
     >>> m.groups()
     ()

除了你无法检索组匹配内容的事实外，非捕获组的行为与捕获组完全相同；你可以
在里面放任何东西，用重复元字符重复它，比如 ‘*’，然后把它嵌入其他组（捕获
或不捕获）。 ‘(?:...)’ 在修改现有模式时特别有用，因为你可以添加新组而不
更改所有其他组的编号方式。 值得一提的是，捕获和非捕获组之间的搜索没有性
能差异；两种形式没有一种更快。

更重要的功能是命名组：不是通过数字引用它们，而是可以通过名称引用组。

命名组的语法是Python特定的扩展之一: ‘(?P<name>...)’。 `name' 显然是该组
的名称。 命名组的行为与捕获组完全相同，并且还将名称与组关联。 处理捕获组
的 *note 匹配对象: 8a6. 方法都接受按编号引用组的整数或包含所需组名的字符
串。 命名组仍然是给定的数字，因此你可以通过两种方式检索有关组的信息:

     >>> p = re.compile(r'(?P<word>\b\w+\b)')
     >>> m = p.search( '(((( Lots of punctuation )))' )
     >>> m.group('word')
     'Lots'
     >>> m.group(1)
     'Lots'

此外，你可以通过 *note groupdict(): 1784. 将命名分组提取为一个字典:

     >>> m = re.match(r'(?P<first>\w+) (?P<last>\w+)', 'Jane Doe')
     >>> m.groupdict()
     {'first': 'Jane', 'last': 'Doe'}

命名组很有用，因为它们允许你使用容易记住的名称，而不必记住数字。 这是来
自 *note imaplib: 98. 模块的示例正则

     InternalDate = re.compile(r'INTERNALDATE "'
             r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
             r'(?P<year>[0-9][0-9][0-9][0-9])'
             r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
             r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
             r'"')

检索 ‘m.group('zonem')’ 显然要容易得多，而不必记住检索第 9 组。

表达式中的后向引用语法，例如 ‘(...)\1’，指的是组的编号。 当然有一种变体
使用组名而不是数字。 这是另一个 Python 扩展: ‘(?P=name)’ 表示在当前点再
次匹配名为 `name' 的组的内容。 用于查找双字的正则表达式，
‘\b(\w+)\s+\1\b’ 也可以写为 ‘\b(?P<word>\w+)\s+(?P=word)\b’:

     >>> p = re.compile(r'\b(?P<word>\w+)\s+(?P=word)\b')
     >>> p.search('Paris in the the spring').group()
     'the the'


File: python.info,  Node: 前向断言,  Prev: 非捕获和命名组,  Up: 更多模式能力

10.8.4.4 前向断言
.................

另一个零宽度断言是前向断言。 前向断言以正面和负面形式提供，如下所示：

‘(?=…)’

     正向前向断言。 如果包含的正则表达式，由 ‘...’ 表示，在当前位置成功
     匹配，则成功，否则失败。 但是，一旦尝试了包含的表达式，匹配的引擎就
     不会前进；模式其余的部分会在在断言开始的地方尝试。

‘(?!…)’

     负向前向断言。 这与积正向断言相反；如果包含的表达式在字符串中的当前
     位置 `不' 匹配，则成功。

更具体一些，让我们看看前向是有用的情况。 考虑一个简单的模式来匹配文件名
并将其拆分为基本名称和扩展名，用 ‘.’ 分隔。 例如，在 ‘news.rc’ 中，
‘news’ 是基本名称，‘rc’ 是文件名的扩展名。

与此匹配的模式非常简单：

‘.*[.].*$’

请注意，‘.’ 需要特别处理，因为它是元字符，所以它在字符类中只能匹配特定字
符。 还要注意尾随的 ‘$’；添加此项以确保扩展名中的所有其余字符串都必须包
含在扩展名中。 这个正则表达式匹配 ‘foo.bar’、‘autoexec.bat’、
‘sendmail.cf’ 和 ‘printers.conf’。

现在，考虑使更复杂一点的问题；如果你想匹配扩展名不是 ‘bat’ 的文件名怎么
办？ 一些错误的尝试：

‘.*[.][^b].*$’ 上面的第一次尝试试图通过要求扩展名的第一个字符不是 ‘b’ 来
排除 ‘bat’。 这是错误的，因为模式也与 ‘foo.bar’ 不匹配。

‘.*[.]([^b]..|.[^a].|..[^t])$’

当你尝试通过要求以下一种情况匹配来修补第一个解决方案时，表达式变得更加混
乱：扩展的第一个字符不是 ‘b’。 第二个字符不 ‘a’；或者第三个字符不是 ‘t’。
这接受 ‘foo.bar’ 并拒绝 ‘autoexec.bat’，但它需要三个字母的扩展名，并且不
接受带有两个字母扩展名的文件名，例如 ‘sendmail.cf’。 为了解决这个问题，
我们会再次使模式复杂化。

‘.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$’

在第三次尝试中，第二个和第三个字母都是可选的，以便允许匹配的扩展名短于三
个字符，例如 ‘sendmail.cf’。

模式现在变得非常复杂，这使得它难以阅读和理解。 更糟糕的是，如果问题发生
变化并且你想要将 ‘bat’ 和 ‘exe’ 排除为扩展，那么该模式将变得更加复杂和混
乱。

负面前向消除了所有这些困扰：

‘.*[.](?!bat$)[^.]*$’ 负向前向意味着：如果表达式 ‘bat’ 此时不匹配，请尝
试其余的模式；如果 ‘bat$’ 匹配，整个模式将失败。 尾随的 ‘$’ 是必需的，以
确保允许像 ‘sample.batch’ 这样的扩展只以 ‘bat’ 开头的文件能通过。
‘[^.]*’ 确保当文件名中有多个点时，模式有效。

现在很容易排除另一个文件扩展名；只需在断言中添加它作为替代。 以下模块排
除以 ‘bat’ 或 ‘exe’:

‘.*[.](?!bat$|exe$)[^.]*$’


File: python.info,  Node: 修改字符串,  Next: 常见问题,  Prev: 更多模式能力,  Up: 正则表达式HOWTO

10.8.5 修改字符串
-----------------

到目前为止，我们只是针对静态字符串执行搜索。 正则表达式通常也用于以各种
方式修改字符串，使用以下模式方法：

方法 / 属性            目的
                       
---------------------------------------------------------------------------
                       
‘split()’              将字符串拆分为一个列表，在正则匹配的任何地方将其
                       拆分
                       
                       
‘sub()’                找到正则匹配的所有子字符串，并用不同的字符串替换
                       它们
                       
                       
‘subn()’               与 ‘sub()’ 相同，但返回新字符串和替换次数
                       

* Menu:

* 分割字符串::
* 搜索和替换::


File: python.info,  Node: 分割字符串,  Next: 搜索和替换,  Up: 修改字符串

10.8.5.1 分割字符串
...................

模式的 *note split(): 1776. 方法在正则匹配的任何地方拆分字符串，返回一个
片段列表。 它类似于 *note split(): 7aa. 字符串方法，但在分隔符的分隔符中
提供了更多的通用性；字符串的 ‘split()’ 仅支持按空格或固定字符串进行拆分
。 正如你所期望的那样，还有一个模块级 *note re.split(): 3d2. 函数。

 -- 方法: .split (string[, maxsplit=0])

     通过正则表达式的匹配拆分 `字符串'。 如果在正则中使用捕获括号，则它
     们的内容也将作为结果列表的一部分返回。 如果 `maxsplit' 非零，则最多
     执行 `maxsplit' 次拆分。

你可以通过传递 `maxsplit' 的值来限制分割的数量。 当 `maxsplit' 非零时，
将最多进行 `maxsplit' 次拆分，并且字符串的其余部分将作为列表的最后一个元
素返回。 在以下示例中，分隔符是任何非字母数字字符序列。:

     >>> p = re.compile(r'\W+')
     >>> p.split('This is a test, short and sweet, of split().')
     ['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']
     >>> p.split('This is a test, short and sweet, of split().', 3)
     ['This', 'is', 'a', 'test, short and sweet, of split().']

有时你不仅对分隔符之间的文本感兴趣，而且还需要知道分隔符是什么。 如果在
正则中使用捕获括号，则它们的值也将作为列表的一部分返回。 比较以下调用:

     >>> p = re.compile(r'\W+')
     >>> p2 = re.compile(r'(\W+)')
     >>> p.split('This... is a test.')
     ['This', 'is', 'a', 'test', '']
     >>> p2.split('This... is a test.')
     ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']

模块级函数 *note re.split(): 3d2. 添加要正则作为第一个参数，但在其他方面
是相同的。:

     >>> re.split(r'[\W]+', 'Words, words, words.')
     ['Words', 'words', 'words', '']
     >>> re.split(r'([\W]+)', 'Words, words, words.')
     ['Words', ', ', 'words', ', ', 'words', '.', '']
     >>> re.split(r'[\W]+', 'Words, words, words.', 1)
     ['Words', 'words, words.']


File: python.info,  Node: 搜索和替换,  Prev: 分割字符串,  Up: 修改字符串

10.8.5.2 搜索和替换
...................

另一个常见任务是找到模式的所有匹配项，并用不同的字符串替换它们。 *note
sub(): 1779. 方法接受一个替换值，可以是字符串或函数，也可以是要处理的字
符串。

 -- 方法: .sub (replacement, string[, count=0])

     返回通过替换 `replacement' 替换 `string' 中正则的最左边非重叠出现而
     获得的字符串。 如果未找到模式，则 `string' 将保持不变。

     可选参数 `count' 是要替换的模式最大的出现次数；`count' 必须是非负整
     数。 默认值 0 表示替换所有。

这是一个使用 *note sub(): 1779. 方法的简单示例。 它用 ‘colour’ 这个词取
代颜色名称:

     >>> p = re.compile('(blue|white|red)')
     >>> p.sub('colour', 'blue socks and red shoes')
     'colour socks and colour shoes'
     >>> p.sub('colour', 'blue socks and red shoes', count=1)
     'colour socks and red shoes'

*note subn(): 177a. 方法完成相同的工作，但返回一个包含新字符串值和已执行
的替换次数的 2 元组:

     >>> p = re.compile('(blue|white|red)')
     >>> p.subn('colour', 'blue socks and red shoes')
     ('colour socks and colour shoes', 2)
     >>> p.subn('colour', 'no colours at all')
     ('no colours at all', 0)

仅当空匹配与前一个空匹配不相邻时，才会替换空匹配。:

     >>> p = re.compile('x*')
     >>> p.sub('-', 'abxd')
     '-a-b--d-'

如果 `replacement' 是一个字符串，则处理其中的任何反斜杠转义。 也就是说，
‘\n’ 被转换为单个换行符，‘\r’ 被转换为回车符，依此类推。 诸如 ‘\&’ 之类
的未知转义是孤立的。 后向引用，例如 ‘\6’，被替换为正则中相应组匹配的子字
符串。 这使你可以在生成的替换字符串中合并原始文本的部分内容。

这个例子匹配单词 ‘section’ 后跟一个用 ‘{’，‘}’ 括起来的字符串，并将
‘section’ 改为 ‘subsection’

     >>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)
     >>> p.sub(r'subsection{\1}','section{First} section{second}')
     'subsection{First} subsection{second}'

还有一种语法用于引用由 ‘(?P<name>...)’ 语法定义的命名组。 ‘\g<name>’ 将
使用名为 ‘name’ 的组匹配的子字符串，‘\g<number>’ 使用相应的组号。 因此
‘\g<2>’ 等同于 ‘\2’，但在诸如 ‘\g<2>0’ 之类的替换字符串中并不模糊。
(‘\20’ 将被解释为对组 20 的引用，而不是对组 2 的引用，后跟字面字符
‘'0'’。) 以下替换都是等效的，但使用所有三种变体替换字符串。:

     >>> p = re.compile('section{ (?P<name> [^}]* ) }', re.VERBOSE)
     >>> p.sub(r'subsection{\1}','section{First}')
     'subsection{First}'
     >>> p.sub(r'subsection{\g<1>}','section{First}')
     'subsection{First}'
     >>> p.sub(r'subsection{\g<name>}','section{First}')
     'subsection{First}'

`replacement' 也可以是一个函数，它可以为你提供更多控制。 如果
`replacement' 是一个函数，则为 `pattern' 的每次非重叠出现将调用该函数。
在每次调用时，函数都会传递一个匹配的 *note 匹配对象: 8a6. 参数，并可以使
用此信息计算所需的替换字符串并将其返回。

在以下示例中，替换函数将小数转换为十六进制:

     >>> def hexrepl(match):
     ...     "Return the hex string for a decimal number"
     ...     value = int(match.group())
     ...     return hex(value)
     ...
     >>> p = re.compile(r'\d+')
     >>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
     'Call 0xffd2 for printing, 0xc000 for user code.'

使用模块级别 *note re.sub(): 483. 函数时，模式作为第一个参数传递。 图案
可以作为对象或字符串提供；如果需要指定正则表达式标志，则必须使用模式对象
作为第一个参数，或者在模式字符串中使用嵌入式修饰符，例如: ‘sub("(?i)b+",
"x", "bbbb BBBB")’ 返回 ‘'x x'’。


File: python.info,  Node: 常见问题,  Next: 反馈,  Prev: 修改字符串,  Up: 正则表达式HOWTO

10.8.6 常见问题
---------------

正则表达式对于某些应用程序来说是一个强大的工具，但在某些方面，它们的行为
并不直观，有时它们的行为方式与你的预期不同。 本节将指出一些最常见的陷阱
。

* Menu:

* 使用字符串方法::
* match() 和 search(): match 和 search.
* 贪婪与非贪婪::
* 使用 re.VERBOSE: 使用 re VERBOSE.


File: python.info,  Node: 使用字符串方法,  Next: match 和 search,  Up: 常见问题

10.8.6.1 使用字符串方法
.......................

有时使用 *note re: de. 模块是一个错误。 如果你匹配固定字符串或单个字符类
，并且你没有使用任何 *note re: de. 功能，例如 *note IGNORECASE: 176f. 标
志，那么正则表达式的全部功能可能不是必需的。 字符串有几种方法可以使用固
定字符串执行操作，它们通常要快得多，因为实现是一个针对此目的而优化的单个
小 C 循环，而不是大型、更通用的正则表达式引擎。

一个例子可能是用另一个固定字符串替换一个固定字符串；例如，你可以用
‘deed’ 替换 ‘word’ 。 *note re.sub(): 483. 看起来像是用于此的函数，但请
考虑 *note replace(): 1664. 方法。 注意 ‘replace()’ 也会替换单词里面的
‘word’ ，把 ‘swordfish’ 变成 ‘sdeedfish’ ，但简单的正则 ‘word’ 也会这样
做。 （为了避免对单词的部分进行替换，模式必须是 ‘\bword\b’，以便要求
‘word’ 在任何一方都有一个单词边界。这使得工作超出了 ‘replace()’ 的能力。
）

另一个常见任务是从字符串中删除单个字符的每个匹配项或将其替换为另一个字符
。 你可以用 ‘re.sub('\n', ' ', S)’ 之类的东西来做这件事，但是 *note
translate(): 1663. 能够完成这两项任务，并且比任何正则表达式都快。

简而言之，在转向 *note re: de. 模块之前，请考虑是否可以使用更快更简单的
字符串方法解决问题。


File: python.info,  Node: match 和 search,  Next: 贪婪与非贪婪,  Prev: 使用字符串方法,  Up: 常见问题

10.8.6.2 match() 和 search()
............................

The *note match(): bbb. function only checks if the RE matches at the
beginning of the string while *note search(): bba. will scan forward
through the string for a match.  It’s important to keep this distinction
in mind.  Remember, ‘match()’ will only report a successful match which
will start at 0; if the match wouldn’t start at zero, ‘match()’ will
`not' report it.

     >>> print(re.match('super', 'superstition').span())
     (0, 5)
     >>> print(re.match('super', 'insuperable'))
     None

另一方面， *note search(): bba. 将向前扫描字符串，报告它找到的第一个匹配
项。:

     >>> print(re.search('super', 'superstition').span())
     (0, 5)
     >>> print(re.search('super', 'insuperable').span())
     (2, 7)

有时你会被诱惑继续使用 *note re.match(): bbb. ，只需在你的正则前面添加
‘.*’ 。抵制这种诱惑并使用 *note re.search(): bba. 代替。 正则表达式编译
器对正则进行一些分析，以加快寻找匹配的过程。 其中一个分析可以确定匹配的
第一个特征必须是什么；例如，以 ‘Crow’ 开头的模式必须与 ‘'C'’ 匹配。 分析
让引擎快速扫描字符串，寻找起始字符，只在找到 ‘'C'’ 时尝试完全匹配。

添加 ‘.*’ 会使这个优化失效，需要扫描到字符串的末尾，然后回溯以找到正则的
其余部分的匹配。 使用 *note re.search(): bba. 代替。


File: python.info,  Node: 贪婪与非贪婪,  Next: 使用 re VERBOSE,  Prev: match 和 search,  Up: 常见问题

10.8.6.3 贪婪与非贪婪
.....................

当重复一个正则表达式时，就像在 ‘a*’ 中一样，最终的动作就是消耗尽可能多的
模式。 当你尝试匹配一对对称分隔符，例如 HTML 标记周围的尖括号时，这个事
实经常会让你感到困惑。因为 ‘.*’ 的贪婪性质， 用于匹配单个 HTML 标记的简
单模式不起作用。

     >>> s = '<html><head><title>Title</title>'
     >>> len(s)
     32
     >>> print(re.match('<.*>', s).span())
     (0, 32)
     >>> print(re.match('<.*>', s).group())
     <html><head><title>Title</title>

正则匹配 ‘'<'’ 中的 ‘'<html>'’ 和 ‘.*’ 消耗字符串的其余部分。 正则中还有
更多的剩余东西，并且 ‘>’ 在字符串的末尾不能匹配，所以正则表达式引擎必须
逐个字符地回溯，直到它找到匹配 ‘>’ 。最终匹配从 ‘'<html>'’ 中的 ‘'<'’ 扩
展到 ‘'</title>'’ 中的 ‘'>'’ ，而这并不是你想要的结果。

在这种情况下，解决方案是使用非贪婪的限定符 ‘*?’ 、 ‘+?’ 、 ‘??’ 或
‘{m,n}?’ ，匹配为尽可能 `少' 的文字。 在上面的例子中，在第一次 ‘'<'’ 匹
配后立即尝试 ‘'>'’ ，当它失败时，引擎一次前进一个字符，每一步都重试
‘'>'’ 。 这产生了正确的结果:

     >>> print(re.match('<.*?>', s).group())
     <html>

（请注意，使用正则表达式解析 HTML 或 XML 很痛苦。快而脏的模式将处理常见
情况，但 HTML 和 XML 有特殊情况会破坏明显的正则表达式；当你编写正则表达
式处理所有可能的情况时，模式将非常复杂。使用 HTML 或 XML 解析器模块来执
行此类任务。）


File: python.info,  Node: 使用 re VERBOSE,  Prev: 贪婪与非贪婪,  Up: 常见问题

10.8.6.4 使用 re.VERBOSE
........................

到目前为止，你可能已经注意到正则表达式是一种非常紧凑的表示法，但它们并不
是非常易读。 具有中等复杂度的正则可能会成为反斜杠、括号和元字符的冗长集
合，使其难以阅读和理解。

对于这样的正则，在编译正则表达式时指定 *note re.VERBOSE: 1770. 标志可能
会有所帮助，因为它允许你更清楚地格式化正则表达式。

‘re.VERBOSE’ 标志有几种效果。 正则表达式中的 `不是' 在字符类中的空格将被
忽略。 这意味着表达式如 ‘dog | cat’ 等同于不太可读的 ‘dog|cat’ ，但 ‘[a
b]’ 仍将匹配字符 ‘'a'’ 、 ‘'b'’ 或空格。 此外，你还可以在正则中放置注释
；注释从 ‘#’ 字符扩展到下一个换行符。 当与三引号字符串一起使用时，这使正
则的格式更加整齐:

     pat = re.compile(r"""
      \s*                 # Skip leading whitespace
      (?P<header>[^:]+)   # Header name
      \s* :               # Whitespace, and a colon
      (?P<value>.*?)      # The header's value -- *? used to
                          # lose the following trailing whitespace
      \s*$                # Trailing whitespace to end-of-line
     """, re.VERBOSE)

这更具有可读性:

     pat = re.compile(r"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$")


File: python.info,  Node: 反馈,  Prev: 常见问题,  Up: 正则表达式HOWTO

10.8.7 反馈
-----------

正则表达式是一个复杂的主题。 这份文档是否有助于你理解它们？ 是否存在不清
楚的部分，或者你遇到的问题未在此处涉及？ 如果是，请向作者发送改进建议。

关于正则表达式的最完整的书几乎肯定是由 O’Reilly 出版的 Jeffrey Friedl 的
Mastering Regular Expressions 。 不幸的是，它专注于 Perl 和 Java 的正则
表达式，并且根本不包含任何 Python 材料，因此它不能用作 Python 编程的参考
。 （第一版涵盖了 Python 现在删除的 ‘regex’ 模块，这对你没有多大帮助。）
考虑从你的图书馆中查找它。


File: python.info,  Node: 套接字编程指南,  Next: 排序指南,  Prev: 正则表达式HOWTO,  Up: Python 常用指引

10.9 套接字编程指南
===================


作者: Gordon McMillan

摘要
....

套接字几乎无处不在，但是它却是被误解最严重的技术之一。这是一篇简单的套接
字概述。并不是一篇真正的教程 —— 你需要做更多的事情才能让它工作起来。其中
也并没有涵盖细节（细节会有很多），但是我希望它能提供足够的背景知识，让你
像模像样的开始使用套接字

* Menu:

* 套接字::
* 创建套接字: 创建套接字<2>.
* 使用一个套接字::
* 断开连接::
* 非阻塞的套接字::


File: python.info,  Node: 套接字,  Next: 创建套接字<2>,  Up: 套接字编程指南

10.9.1 套接字
-------------

我将只讨论关于 INET（比如：IPv4 地址族）的套接字，但是它将覆盖几乎 99% 的
套接字使用场景。并且我将仅讨论 STREAM（比如：TCP）类型的套接字 - 除非你
真的知道你在做什么（那么这篇 HOWTO 可能并不适合你），使用 STREAM 类型的
套接字将会得到比其它类型更好的表现与性能。我将尝试揭开套接字的神秘面纱，
也会讲到一些阻塞与非阻塞套接字的使用。但是我将以阻塞套接字为起点开始讨论
。只有你了解它是如何工作的以后才能处理非阻塞套接字。

理解这些东西的难点之一在于「套接字」可以表示很多微妙差异的东西，这取决于
上下文。所以首先，让我们先分清楚「客户端」套接字和「服务端」套接字之间的
不同，客户端套接字表示对话的一端，服务端套接字更像是总机接线员。客户端程
序只能（比如：你的浏览器）使用「客户端」套接字；网络服务器则可以使用「服
务端」套接字和「客户端」套接字来会话

* Menu:

* 历史::


File: python.info,  Node: 历史,  Up: 套接字

10.9.1.1 历史
.............

目前为止，在各种形式的 IPC (进程间通信) 中，套接字是最流行的。在任何指定
的平台上，可能会有其它更快的 IPC 形式，但是就跨平台通信来说，套接字大概
是唯一的玩法

套接字做为 BSD Unix 操作系统的一部分在伯克利诞生，像野火一样在因特网传播
。有一个很好的原因 —— 套接字与 INET 的结合使得与世界各地的任意机器间通信
变得令人难以置信的简单（至少对比与其他方案来说）


File: python.info,  Node: 创建套接字<2>,  Next: 使用一个套接字,  Prev: 套接字,  Up: 套接字编程指南

10.9.2 创建套接字
-----------------

简略地说，当你点击带你来到这个页面的链接时，你的浏览器就已经做了下面这几
件事情:

     # create an INET, STREAMing socket
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     # now connect to the web server on port 80 - the normal http port
     s.connect(("www.python.org", 80))

当连接完成，套接字可以用来发送请求来接收页面上显示的文字。同样是这个套接
字也会用来读取响应，最后再被销毁。是的，被销毁了。客户端套接字通常用来做
一次交换（或者说一小组序列的交换）。

网络服务器发生了什么这个问题就有点复杂了。首页，服务器创建一个「服务端套
接字」:

     # create an INET, STREAMing socket
     serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     # bind the socket to a public host, and a well-known port
     serversocket.bind((socket.gethostname(), 80))
     # become a server socket
     serversocket.listen(5)

有几件事需要注意：我们使用了 ‘socket.gethostname()’，所以套接字将外网可
见。如果我们使用的是 ‘s.bind(('localhost', 80))’ 或者
‘s.bind(('127.0.0.1', 80))’，也会得到一个「服务端」套接字，但是后者只在
同一机器上可见。‘s.bind(('', 80))’ 则指定套接字可以被机器上的任何地址碰
巧连接

第二个需要注点是：低端口号通常被一些「常用的」服务（HTTP, SNMP 等）所保
留。如果你想把程序跑起来，最好使用一个高位端口号（通常是4位的数字）。

最后，‘listen’ 方法的参数会告诉套接字库，我们希望在队列中累积多达 5 个（
通常的最大值）连接请求后再拒绝外部连接。 如果所有其他代码都准确无误，这
个队列长度应该是足够的。

现在我们已经有一个「服务端」套接字，监听了 80 端口，我们可以进入网络服务
器的主循环了:

     while True:
         # accept connections from outside
         (clientsocket, address) = serversocket.accept()
         # now do something with the clientsocket
         # in this case, we'll pretend this is a threaded server
         ct = client_thread(clientsocket)
         ct.run()

事际上，通常有 3 种方法可以让这个循环工作起来 - 调度一个线程来处理 ‘客户
端套接字’，或者把这个应用改成使用非阻塞模式套接字，亦或是使用 ‘select’ 库
来实现「服务端」套接字与任意活动 ‘客户端套接字’ 之间的多路复用。稍后会详
细介绍。现在最重要的是理解：这就是一个 `服务端' 套接字做的 `所有' 事情。
它并没有发送任何数据。也没有接收任何数据。它只创建「客户端」套接字。每个
‘客户端套接字’ 都是为了响应某些其它客户端套接字 ‘connect()’ 到我们绑定的
主机。一旦创建 ‘客户端套接字’ 完成，就会返回并监听更多的连接请求。现个客
户端可以随意通信 - 它们使用了一些动态分配的端口，会话结束时端口才会被回
收

* Menu:

* 进程间通信::


File: python.info,  Node: 进程间通信,  Up: 创建套接字<2>

10.9.2.1 进程间通信
...................

如果你需要在同一台机器上进行两个进程间的快速 IPC 通信，你应该了解管道或
者共享内存。如果你决定使用 AF_INET 类型的套接字，绑定「服务端」套接字到
‘'localhost'’ 。在大多数平台，这将会使用一个许多网络层间的通用快捷方式（
本地回环地址）并且速度会快很多

参见
....

*note multiprocessing: b8. 模块使跨平台 IPC 通信成为一个高层的 API


File: python.info,  Node: 使用一个套接字,  Next: 断开连接,  Prev: 创建套接字<2>,  Up: 套接字编程指南

10.9.3 使用一个套接字
---------------------

首先需要注意，浏览器的「客户端」套接字和网络服务器的「客户端」套接字是极
为相似的。即这种会话是「点对点」的。或者也可以说 `你作为设计师需要自行决
定会话的规则和礼节' 。通常情况下，‘连接’ 套接字通过发送一个请求或者信号
来开始一次会话。但这属于设计决定，并不是套接字规则。

现在有两组用于通信的动词。你可以使用 ‘send’ 和 ‘recv’ ，或者你可以把客户
端套接字改成文件类型的形式来使用 ‘read’ 和 ‘write’ 方法。后者是 Java 语
言中表示套接字的方法，我将不会在这儿讨论这个，但是要提醒你需要调用套接字
的 ‘flush’ 方法。这些是“缓冲”的文件，一个经常出现的错误是 ‘write’ 一些东
西，然后就直接开始 ‘read’ 一个响应。如果不调用 ‘flush’ ，你可能会一直等
待这个响应，因为请求可能还在你的输出缓冲中。

现在我来到了套接字的两个主要的绊脚石 - ‘send’ 和 ‘recv’ 操作网络缓冲区。
它们并不一定可以处理所有你想要（期望）的字节，因为它们主要关注点是处理网
络缓冲。通常，它们在关联的网络缓冲区 ‘send’ 或者清空 ‘recv’ 时返回。然后
告诉你处理了多少个字节。`你' 的责任是一直调用它们直到你所有的消息处理完
成。

当 ‘recv’ 方法返回 0 字节时，就表示另一端已经关闭（或者它所在的进程关闭
）了连接。你再也不能从这个连接上获取到任何数据了。你可以成功的发送数据；
我将在后面讨论这一点。

像 HTTP 这样的协议只使用一个套接字进行一次传输。客户端发送一个请求，然后
读取响应。就这么简单。套接字会被销毁。 表示客户端可以通过接收 0 字节序列
表示检测到响应的结束。

但是如果你打算在随后来的传输中复用套接字的话，你需要明白 `套接字里面是不
存在 :abbr:‘EOT (传输结束)‘' 的。重复一下：套接字 ‘send’ 或者 ‘recv’ 完
0 字节后返回，连接会中断。如果连接没有被断开，你可能会永远处于等待
‘recv’ 的状态，因为（就目前来说）套接字 `不会' 告诉你不用再读取了。现在
如果你细心一点，你可能会意识到套接字基本事实：`消息必须要么具有固定长度
，要么可以界定，要么指定了长度（比较好的做法），要么以关闭连接为结束'。
选择完全由你而定（这比让别人定更合理）。

假定你不希望结束连接，那么最简单的解决方案就是使用定长消息:

     class MySocket:
         """demonstration class only
           - coded for clarity, not efficiency
         """

         def __init__(self, sock=None):
             if sock is None:
                 self.sock = socket.socket(
                                 socket.AF_INET, socket.SOCK_STREAM)
             else:
                 self.sock = sock

         def connect(self, host, port):
             self.sock.connect((host, port))

         def mysend(self, msg):
             totalsent = 0
             while totalsent < MSGLEN:
                 sent = self.sock.send(msg[totalsent:])
                 if sent == 0:
                     raise RuntimeError("socket connection broken")
                 totalsent = totalsent + sent

         def myreceive(self):
             chunks = []
             bytes_recd = 0
             while bytes_recd < MSGLEN:
                 chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048))
                 if chunk == b'':
                     raise RuntimeError("socket connection broken")
                 chunks.append(chunk)
                 bytes_recd = bytes_recd + len(chunk)
             return b''.join(chunks)

发送分部代码几乎可用于任何消息传递方案 —— 在 Python 中你发送字符串，可以
使用 ‘len()’ 方法来确定它的长度（即使它嵌入了 ‘\0’ 字符），主要是接收代
码变得更复杂。（在 C 语言中，并没有更糟糕，除非消息嵌入了 ‘\0’ 字符而且
你又无法使用 ‘strlen’ ）

最简单的改进是让消息的第一个字符表示消息类型，由类型决定长度。现在你需要
两次 ‘recv’- 第一次取（至少）第一个字符来知晓长度，第二次在循环中获取剩
余所有的消息。如果你决定到分界线，你将收到一些任意大小的块，（4096 或者
8192 通常是比较合适的网络缓冲区大小），扫描你接收到的分界符

一个需要意识到的复杂情况是：如果你的会话协议允许多个消息被发送回来（没有
响应），调用 ‘recv’ 传入任意大小的块，你可能会因为读到后续接收的消息而停
止读取。你需要将它放在一边并保存，直到它需要为止。

以其长度（例如，作为5个数字字符）作为消息前缀时会变得更复杂，因为（信不
信由你）你可能无法在一个 ‘recv’ 中获得所有5个字符。在一般使用时，你会侥
幸避免该状况；但是在高网络负载中，除非你使用两个 ‘recv’ 循环，否则你的代
码将很快中断 —— 第一个用于确定长度，第二个用于获取消息的数据部分。这很讨
厌。当你发现 ‘send’ 并不总是设法在支持搞定一切时，你也会有这种感觉。 尽
管已经阅读过这篇文章，但最终还是会有所了解！

限于篇幅，建立你的角色，（保持与我的竞争位置），这些改进将留给读者做为练
习。现在让我们继续。

* Menu:

* 二进制数据::


File: python.info,  Node: 二进制数据,  Up: 使用一个套接字

10.9.3.1 二进制数据
...................

通过套接字传送二进制数据是可行的。主要问题在于并非所有机器都用同样的二进
制数据格式。比如 Motorola 芯片用两个十六进制字节 00 01 来表示一个 16 位
整数值 1。而 Intel 和 DEC 则会做字节反转 —— 即用 01 00 来表示 1。套接字
库要求转换 16 位和 32 位整数 —— ‘ntohl, htonl, ntohs, htons’ 其中的「n」
表示 `network'，「h」表示 `host'，「s」表示 `short'，「l」表示 `long'。
在网络序列就是主机序列时它们什么都不做，但是如果机器是字节反转的则会适当
地交换字节序。

在现今的 32 位机器中，二进制数据的 ascii 表示往往比二进制表示要小。这是
因为在非常多的时候所有 long 的值均为 0 或者 1。字符串形式的 "0" 为两个字
节，而二进制形式则为四个。当然这不适用于固定长度的信息。自行决定，请自行
决定。


File: python.info,  Node: 断开连接,  Next: 非阻塞的套接字,  Prev: 使用一个套接字,  Up: 套接字编程指南

10.9.4 断开连接
---------------

严格地讲，你应该在 ‘close’ 它之前将套接字 ‘shutdown’ 。 ‘shutdown’ 是发
送给套接字另一端的一种建议。调用时参数不同意义也不一样，它可能意味着「我
不会再发送了，但我仍然会监听」，或者「我没有监听了，真棒！」。然而，大多
数套接字库或者程序员都习惯了忽略使用这种礼节，因为通常情况下 ‘close’ 与
‘shutdown(); close()’ 是一样的。所以在大多数情况下，不需要显式的
‘shutdown’ 。

高效使用 ‘shutdown’ 的一种方法是在类似 HTTP 的交换中。客户端发送请求，然
后执行 ‘shutdown(1)’ 。 这告诉服务器“此客户端已完成发送，但仍可以接收”。
服务器可以通过接收 0 字节来检测 “EOF” 。它可以假设它有完整的请求。服务器
发送回复。如果 ‘send’ 成功完成，那么客户端仍在接收。

Python 进一步自动关闭，并说当一个套接字被垃圾收集时，如果需要它会自动执
行 ‘close’ 。但依靠这个机制是一个非常坏的习惯。如果你的套接字在没有
‘close’ 的情况下就消失了，那么另一端的套接字可能会无限期地挂起，以为你只
是慢了一步。完成后 `请' ‘close’ 你的套接字。

* Menu:

* 套接字何时销毁::


File: python.info,  Node: 套接字何时销毁,  Up: 断开连接

10.9.4.1 套接字何时销毁
.......................

使用阻塞套接字最糟糕的事情可能就是当另一边下线时（没有 ‘close’ ）会发生
什么。你的套接字可能会挂起。 TCP 是一种可靠的协议，它会在放弃连接之前等
待很长时间。如果你正在使用线程，那么整个线程基本上已经死了。你无能为力。
只要你没有做一些愚蠢的事情，比如在进行阻塞读取时持有一个锁，那么线程并没
有真正消耗掉资源。 `不要' 尝试杀死线程 —— 线程比进程更有效的部分原因是它
们避免了与自动回收资源相关的开销。换句话说，如果你设法杀死线程，你的整个
进程很可能被搞坏。


File: python.info,  Node: 非阻塞的套接字,  Prev: 断开连接,  Up: 套接字编程指南

10.9.5 非阻塞的套接字
---------------------

如果你已理解上述内容，那么你已经了解了使用套接字的机制所需了解的大部分内
容。你仍将以相同的方式使用相同的函数调用。 只是，如果你做得对，你的应用
程序几乎是由内到外的。

在 Python 中是使用 ‘socket.setblocking(0)’ 来使其为非阻塞。 在 C 中做法
更为复杂（例如，你需要在 BSD 风格的 ‘O_NONBLOCK’ 和几乎无区别的 POSIX 风
格的 ‘O_NDELAY’ 之间作出选择，这与 ‘TCP_NODELAY’ 完全不一样。）。 但其思
路是完全相同的。 你要在创建套拼字之后但在使用它之前执行此操作。 （实际上
，除非你是疯子才会反复切换。）

主要的机制差异是 ‘send’ 、 ‘recv’ 、 ‘connect’ 和 ‘accept’ 可以在没有做
任何事情的情况下返回。 你（当然）有很多选择。你可以检查返回代码和错误代
码，通常会让自己发疯。如果你不相信我，请尝试一下。你的应用程序将变得越来
越大、越来越 Bug 、吸干 CPU。因此，让我们跳过脑死亡的解决方案并做正确的
事。

使用 ‘select’ 库

在 C 中，编码 ‘select’ 相当复杂。 在 Python 中，它是很简单，但它与 C 版
本足够接近，如果你在 Python 中理解 ‘select’ ，那么在 C 中你会几乎不会遇
到麻烦:

     ready_to_read, ready_to_write, in_error = \
                    select.select(
                       potential_readers,
                       potential_writers,
                       potential_errs,
                       timeout)

你传递给 ‘select’ 三个列表：第一个包含你可能想要尝试读取的所有套接字；第
二个是你可能想要尝试写入的所有套接字，以及要检查错误的最后一个（通常为空
）。你应该注意，套接字可以进入多个列表。 ‘select’ 调用是阻塞的，但你可以
给它一个超时。这通常是一件明智的事情 —— 给它一个很长的超时（比如一分钟）
，除非你有充分的理由不这样做。

作为返回，你将获得三个列表。它们包含实际可读、可写和有错误的套接字。 这
些列表中的每一个都是你传入的相应列表的子集（可能为空）。

如果一个套接字在输出可读列表中，那么你可以像我们一样接近这个业务，那个套
接字上的 ‘recv’ 将返回 `一些内容' 。可写列表的也相同，你将能够发送 `一些
内容' 。 也许不是你想要的全部，但 `有些东西' 比没有东西更好。 （实际上，
任何合理健康的套接字都将以可写方式返回 —— 它只是意味着出站网络缓冲区空间
可用。）

如果你有一个“服务器”套接字，请将其放在 potential_readers 列表中。如果它
出现在可读列表中，那么你的 ‘accept’ （几乎肯定）会起作用。如果你已经创建
了一个新的套接字 ‘connect’ 其他人，请将它放在 potential_writers 列表中。
如果它出现在可写列表中，那么它有可能已连接。

实际上，即使使用阻塞套接字， ‘select’ 也很方便。这是确定是否阻塞的一种方
法 —— 当缓冲区中存在某些内容时，套接字返回为可读。然而，这仍然无助于确定
另一端是否完成或者只是忙于其他事情的问题。

`可移植性警告' ：在 Unix 上， ‘select’ 适用于套接字和文件。 不要在
Windows 上尝试。在 Windows 上， ‘select’ 仅适用于套接字。另请注意，在 C
中，许多更高级的套接字选项在 Windows 上的执行方式不同。事实上，在
Windows 上我通常在使用我的套接字使用线程（非常非常好）。


File: python.info,  Node: 排序指南,  Next: Unicode 指南,  Prev: 套接字编程指南,  Up: Python 常用指引

10.10 排序指南
==============


作者: Andrew Dalke 和 Raymond Hettinger


发布版本: 0.1

Python 列表有一个内置的 *note list.sort(): 44d. 方法可以直接修改列表。还
有一个 *note sorted(): 44c. 内置函数，它会从一个可迭代对象构建一个新的排
序列表。

在本文档中，我们将探索使用Python对数据进行排序的各种技术。

* Menu:

* 基本排序::
* 关键函数::
* Operator 模块函数::
* 升序和降序::
* 排序稳定性和排序复杂度::
* 使用装饰-排序-去装饰的旧方法::
* 使用 cmp 参数的旧方法::
* 其它::


File: python.info,  Node: 基本排序,  Next: 关键函数,  Up: 排序指南

10.10.1 基本排序
----------------

简单的升序排序非常简单：只需调用 *note sorted(): 44c. 函数即可。它会返回
一个新的已排序列表。

     >>> sorted([5, 2, 3, 1, 4])
     [1, 2, 3, 4, 5]

你也可以使用 *note list.sort(): 44d. 方法，它会直接修改原列表（并返回
‘None’ 以避免混淆），通常来说它不如 *note sorted(): 44c. 方便 ——— 但如果
你不需要原列表，它会更有效率。

     >>> a = [5, 2, 3, 1, 4]
     >>> a.sort()
     >>> a
     [1, 2, 3, 4, 5]

另外一个区别是， *note list.sort(): 44d. 方法只是为列表定义的，而 *note
sorted(): 44c. 函数可以接受任何可迭代对象。

     >>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
     [1, 2, 3, 4, 5]


File: python.info,  Node: 关键函数,  Next: Operator 模块函数,  Prev: 基本排序,  Up: 排序指南

10.10.2 关键函数
----------------

*note list.sort(): 44d. 和 *note sorted(): 44c. 都有一个 `key' 形参来指
定在进行比较之前要在每个列表元素上进行调用的函数。

例如，下面是一个不区分大小写的字符串比较：

     >>> sorted("This is a test string from Andrew".split(), key=str.lower)
     ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

`key' 形参的值应该是一个函数，它接受一个参数并并返回一个用于排序的键。这
种技巧速度很快，因为对于每个输入记录只会调用一次 key 函数。

一种常见的模式是使用对象的一些索引作为键对复杂对象进行排序。例如：

     >>> student_tuples = [
     ...     ('john', 'A', 15),
     ...     ('jane', 'B', 12),
     ...     ('dave', 'B', 10),
     ... ]
     >>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
     [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

同样的技术也适用于具有命名属性的对象。例如：

     >>> class Student:
     ...     def __init__(self, name, grade, age):
     ...         self.name = name
     ...         self.grade = grade
     ...         self.age = age
     ...     def __repr__(self):
     ...         return repr((self.name, self.grade, self.age))

     >>> student_objects = [
     ...     Student('john', 'A', 15),
     ...     Student('jane', 'B', 12),
     ...     Student('dave', 'B', 10),
     ... ]
     >>> sorted(student_objects, key=lambda student: student.age)   # sort by age
     [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]


File: python.info,  Node: Operator 模块函数,  Next: 升序和降序,  Prev: 关键函数,  Up: 排序指南

10.10.3 Operator 模块函数
-------------------------

上面显示的键函数模式非常常见，因此 Python 提供了便利功能，使访问器功能更
容易，更快捷。 *note operator: c3. 模块有 *note itemgetter(): 262. 、
*note attrgetter(): 724. 和 *note methodcaller(): 725. 函数。

使用这些函数，上述示例变得更简单，更快捷：

     >>> from operator import itemgetter, attrgetter

     >>> sorted(student_tuples, key=itemgetter(2))
     [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

     >>> sorted(student_objects, key=attrgetter('age'))
     [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Operator 模块功能允许多级排序。 例如，按 `grade' 排序，然后按 `age' 排序
：

     >>> sorted(student_tuples, key=itemgetter(1,2))
     [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

     >>> sorted(student_objects, key=attrgetter('grade', 'age'))
     [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]


File: python.info,  Node: 升序和降序,  Next: 排序稳定性和排序复杂度,  Prev: Operator 模块函数,  Up: 排序指南

10.10.4 升序和降序
------------------

*note list.sort(): 44d. 和 *note sorted(): 44c. 接受布尔值的 `reverse' 参
数。这用于标记降序排序。 例如，要以反向 `age' 顺序获取学生数据：

     >>> sorted(student_tuples, key=itemgetter(2), reverse=True)
     [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

     >>> sorted(student_objects, key=attrgetter('age'), reverse=True)
     [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]


File: python.info,  Node: 排序稳定性和排序复杂度,  Next: 使用装饰-排序-去装饰的旧方法,  Prev: 升序和降序,  Up: 排序指南

10.10.5 排序稳定性和排序复杂度
------------------------------

排序保证是 稳定(1) 的。 这意味着当多个记录具有相同的键值时，将保留其原始
顺序。

     >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
     >>> sorted(data, key=itemgetter(0))
     [('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]

注意 `blue' 的两个记录如何保留它们的原始顺序，以便 ‘('blue', 1)’ 保证在
‘('blue', 2)’ 之前。

这个美妙的属性允许你在一系列排序步骤中构建复杂的排序。例如，要按 `grade'
降序然后 `age' 升序对学生数据进行排序，请先 `age' 排序，然后再使用
`grade' 排序：

     >>> s = sorted(student_objects, key=attrgetter('age'))     # sort on secondary key
     >>> sorted(s, key=attrgetter('grade'), reverse=True)       # now sort on primary key, descending
     [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

这可以被抽象为一个包装函数，该函数能接受一个列表以及字段和顺序的元组，以
对它们进行多重排序。

     >>> def multisort(xs, specs):
     ...     for key, reverse in reversed(specs):
     ...         xs.sort(key=attrgetter(key), reverse=reverse)
     ...     return xs

     >>> multisort(list(student_objects), (('grade', True), ('age', False)))
     [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Python 中使用的 Timsort(2) 算法可以有效地进行多种排序，因为它可以利用数
据集中已存在的任何排序。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Sorting_algorithm#Stability

   (2) https://en.wikipedia.org/wiki/Timsort


File: python.info,  Node: 使用装饰-排序-去装饰的旧方法,  Next: 使用 cmp 参数的旧方法,  Prev: 排序稳定性和排序复杂度,  Up: 排序指南

10.10.6 使用装饰-排序-去装饰的旧方法
------------------------------------

这个三个步骤被称为 Decorate-Sort-Undecorate ：

   * 首先，初始列表使用控制排序顺序的新值进行修饰。

   * 然后，装饰列表已排序。

   * 最后，删除装饰，创建一个仅包含新排序中初始值的列表。

例如，要使用DSU方法按 `grade' 对学生数据进行排序：

     >>> decorated = [(student.grade, i, student) for i, student in enumerate(student_objects)]
     >>> decorated.sort()
     >>> [student for grade, i, student in decorated]               # undecorate
     [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

这方法语有效是因为元组按字典顺序进行比较，先比较第一项；如果它们相同则比
较第二个项目，依此类推。

不一定在所有情况下都要在装饰列表中包含索引 `i' ，但包含它有两个好处：

   * 排序是稳定的——如果两个项具有相同的键，它们的顺序将保留在排序列表中
     。

   * 原始项目不必具有可比性，因为装饰元组的排序最多由前两项决定。 因此，
     例如原始列表可能包含无法直接排序的复数。

这个方法的另一个名字是 Randal L. Schwartz 在 Perl 程序员中推广的
Schwartzian transform(1)。

既然 Python 排序提供了键函数，那么通常不需要这种技术。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Schwartzian_transform


File: python.info,  Node: 使用 cmp 参数的旧方法,  Next: 其它,  Prev: 使用装饰-排序-去装饰的旧方法,  Up: 排序指南

10.10.7 使用 `cmp' 参数的旧方法
-------------------------------

本 HOWTO 中给出的许多结构都假定为 Python 2.4 或更高版本。在此之前，没有
内置 *note sorted(): 44c. ， *note list.sort(): 44d. 也没有关键字参数。
相反，所有 Py2.x 版本都支持 `cmp' 参数来处理用户指定的比较函数。

在 Py3.0 中， `cmp' 参数被完全删除（作为简化和统一语言努力的一部分，消除
了丰富的比较与 ‘__cmp__()’ 魔术方法之间的冲突）。

在 Py2.x 中， sort 允许一个可选函数，可以调用它来进行比较。该函数应该采
用两个参数进行比较，然后返回负值为小于，如果它们相等则返回零，或者返回大
于大于的正值。例如，我们可以这样做：

     >>> def numeric_compare(x, y):
     ...     return x - y
     >>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare)
     [1, 2, 3, 4, 5]

或者你可反转比较的顺序：

     >>> def reverse_numeric(x, y):
     ...     return y - x
     >>> sorted([5, 2, 4, 1, 3], cmp=reverse_numeric)
     [5, 4, 3, 2, 1]

将代码从 Python 2.x 移植到 3.x 时，如果用户提供比较功能并且需要将其转换
为键函数，则会出现这种情况。 以下包装器使这很容易：

     def cmp_to_key(mycmp):
         'Convert a cmp= function into a key= function'
         class K:
             def __init__(self, obj, *args):
                 self.obj = obj
             def __lt__(self, other):
                 return mycmp(self.obj, other.obj) < 0
             def __gt__(self, other):
                 return mycmp(self.obj, other.obj) > 0
             def __eq__(self, other):
                 return mycmp(self.obj, other.obj) == 0
             def __le__(self, other):
                 return mycmp(self.obj, other.obj) <= 0
             def __ge__(self, other):
                 return mycmp(self.obj, other.obj) >= 0
             def __ne__(self, other):
                 return mycmp(self.obj, other.obj) != 0
         return K

要转换为键函数，只需包装旧的比较函数：

     >>> sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric))
     [5, 4, 3, 2, 1]

在 Python 3.2 中， *note functools.cmp_to_key(): b5e. 函数被添加到标准库
中的 *note functools: 85. 模块中。


File: python.info,  Node: 其它,  Prev: 使用 cmp 参数的旧方法,  Up: 排序指南

10.10.8 其它
------------

   * 对于区域相关的排序，请使用 *note locale.strxfrm(): 3091. 作为键函数
     ，或者 *note locale.strcoll(): 308f. 作为比较函数。

   * `reverse' 参数仍然保持排序稳定性（因此具有相等键的记录保留原始顺序
     ）。 有趣的是，通过使用内置的 *note reversed(): 18f. 函数两次，可以
     在没有参数的情况下模拟该效果：

          >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
          >>> standard_way = sorted(data, key=itemgetter(0), reverse=True)
          >>> double_reversed = list(reversed(sorted(reversed(data), key=itemgetter(0))))
          >>> assert standard_way == double_reversed
          >>> standard_way
          [('red', 1), ('red', 2), ('blue', 1), ('blue', 2)]

   * 在两个对象之间进行比较时，保证排序例程使用 *note __lt__(): c3c. 。
     因此，通过定义 *note __lt__(): c3c. 方法，可以很容易地为类添加标准
     排序顺序:

          >>> Student.__lt__ = lambda self, other: self.age < other.age
          >>> sorted(student_objects)
          [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

   * 键函数不需要直接依赖于被排序的对象。键函数还可以访问外部资源。例如
     ，如果学生成绩存储在字典中，则可以使用它们对单独的学生姓名列表进行
     排序：

          >>> students = ['dave', 'john', 'jane']
          >>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'}
          >>> sorted(students, key=newgrades.__getitem__)
          ['jane', 'dave', 'john']


File: python.info,  Node: Unicode 指南,  Next: HOWTO 使用 urllib 包获取网络资源,  Prev: 排序指南,  Up: Python 常用指引

10.11 Unicode 指南
==================


发布版本: 1.12

本指南讨论了 Python 对于表达文本数据的 Unicode 规范的支持，并且解释了人
们试图使用 Unicode 时经常遇到的问题。

* Menu:

* Unicode 概述::
* Python对Unicode的支持::
* Unicode 数据的读写::
* 致谢: 致谢<10>.


File: python.info,  Node: Unicode 概述,  Next: Python对Unicode的支持,  Up: Unicode 指南

10.11.1 Unicode 概述
--------------------

* Menu:

* 定义::
* 编码::
* 参考文献: 参考文献<3>.


File: python.info,  Node: 定义,  Next: 编码,  Up: Unicode 概述

10.11.1.1 定义
..............

如今的程序需要具有处理许多不同类型字符的能力。应用程序常常需要国际化以便
以用户可选择的不同语言显示信息和输出。同一个程序可能需要以英语、法语、日
语、希伯来语或俄语输出错误信息。网页内容可能由任何语言写成，并且可能包含
不同的表情符号。Python 的字符串类型使用 Unicode 标准来表示字符，这使
Python 程序能够正常处理所有这些可能的字符。

Unicode 规范 (‘https://www.unicode.org/’) 旨在列出人类语言中用到的每个字
符，并赋予每个字符唯一的编码。该规范持续进行修订和更新以添加新的语言和符
号。

一个**字符**是文本的最小可能部件。‘A’、‘B’、‘C’ 等都是不同的字符。‘È’ 和
‘Í’ 也一样。字符会随着语言或者上下文的变化而变化。比如，‘Ⅰ’ 是一个表示
“罗马数字 1” 的字符，它与大写字母 ‘I’ 不同。它们常常看起来相同，但这是两
个有着不同含义的不同字符。

Unicode 标准描述了**码位**如何表示字符。一个码位的值是在 0 到 0x10FFFF （
大约 110 万个值，目前有其中 11 万个被指派）。在这一标准中并且在这一文档
中，一个码位写作 ‘U+265E’ 来表示拥有值 ‘0x265e’ 的字符（十进制下为
9,822）。

Unicode 标准包含了许多表格来列出字符和对应的码位。

     0061    'a'; LATIN SMALL LETTER A
     0062    'b'; LATIN SMALL LETTER B
     0063    'c'; LATIN SMALL LETTER C
     ...
     007B    '{'; LEFT CURLY BRACKET
     ...
     2167    'Ⅷ'; ROMAN NUMERAL EIGHT
     2168    'Ⅸ'; ROMAN NUMERAL NINE
     ...
     265E    '♞'; BLACK CHESS KNIGHT
     265F    '♟'; BLACK CHESS PAWN
     ...
     1F600   '😀'; GRINNING FACE
     1F609   '😉'; WINKING FACE
     ...

严格地说，这些定义暗示了这样的说法是没有意义的：“这是字符 ‘U+265E’”。
‘U+265E’ 是一个码位，其代表了某特定的字符 —— 在这一情形下，它代表了字符
“国际象棋黑方骑士（黑马）” ‘♞’。在非正式上下文中，码位和字符的差异有时会
被忽略。

一个字符在屏幕上或在纸上被表示为一组图形元素，被称为**字形**。比如，大写
字母 A 的字形，是斜向的两笔和水平的一笔，而具体的细节取决于所使用的字体
。大部分 Python 代码不必担心字形，找到应被显示的正确字形一般来说是用户图
形界面工具箱或者终端的字体渲染器的工作。


File: python.info,  Node: 编码,  Next: 参考文献<3>,  Prev: 定义,  Up: Unicode 概述

10.11.1.2 编码
..............

上一段可以归结为：一个 Unicode 字符串是一系列码位（从 0 到 ‘0x10FFFF’ 或
者说十进制的 1,114,111 的数字）组成的序列。这一序列在内存中需要被表示为
一组**码元**，然后**码元** 会对应到包含八个二进制位的字节。将 Unicode 字
符串翻译成字节序列的规则被称为**字符编码**，或者**编码**。

你可能会想到的第一种编码是使用一个 32 位的整数来代表一个代码位，然后使用
CPU 对 32 位整数的表达方式。在这一表达方式中，字符串 “Python” 可能看起来
像是这样：

        P           y           t           h           o           n
     0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00
        0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

这个表达方式非常直接，但同时也存在 一些问题。

  1. 不够方便；不同的处理器对字节的排序不同。

  2. 非常浪费空间。多数编码都小于127，或者255，所以很多空间都是 ‘0x00’。
     上面的字符串takes 24 bytes compared to the 6 bytes needed for an
     ASCII representation.  Increased RAM usage doesn’t matter too much
     (desktop computers have gigabytes of RAM, and strings aren’t
     usually that large), but expanding our usage of disk and network
     bandwidth by a factor of 4 is intolerable.

  3. 与现有的 C 函数（如 ‘strlen()’ ）不兼容，因此需要采用一套新的宽字符
     串函数。

因此这种编码用得不多，人们转而选择其他更高效、更方便的编码，比如 UTF-8。

UTF-8 是最常用的编码之一，Python 往往默认会采用它。UTF 代表“Unicode
Transformation Format”，’8’ 表示编码采用 8 位数。（UTF-16 和 UTF-32 编码
也是存在的，但其使用频率不如 UTF-8。）UTF-8 的规则如下：

  1. 如果码位 < 128，则直接用对应的字节值表示。

  2. 如果码位 >= 128，则转换为 2、3、4 个字节的序列，每个字节值都位于
     128 和 255 之间。

UTF-8 有几个很方便的特性：

  1. 可以处理任何 Unicode 码位。

  2. Unicode 字符串被转换为一个字节序列，仅在表示空（null ）字符（
     U+0000）时才会包含零值的字节。这意味着 ‘strcpy()’ 之类的C 函数可以
     处理 UTF-8 字符串，而且用那些不能处理字符串结束符之外的零值字节的协
     议也能发送。

  3. ASCII 字符串也是也是也是合法的 UTF-8 文本。

  4. UTF-8 相当紧凑；大多数常用字符均可用一两个字节表示。

  5. 如果字节数据被损坏或丢失，则可以找出下一个 UTF-8 码点的开始位置并重
     新开始同步。随机的 8 位数据也不太可能像是有效的 UTF-8 编码。

  6. UTF-8 是一种面向字节的编码。编码规定了每个字符由一个或多个字节的序
     列表示。这避免了整数和双字节编码（如 UTF-16 和 UTF-32）可能出现的字
     节顺序问题，那时的字节序列会因执行编码的硬件而异。


File: python.info,  Node: 参考文献<3>,  Prev: 编码,  Up: Unicode 概述

10.11.1.3 参考文献
..................

Unicode Consortium 站点(1) 有 Unicode 规范的字符图表、词汇表和 PDF 版本
。 为一些困难的阅读做好准备。 Unicode 起源和发展的年表(2) 也可在该站点上
找到。

在 Computerphile 的 Youtube 频道上，Tom Scott 简要地‘讨论了 Unicode 和
UTF-8 <‘https://www.youtube.com/watch?v=MijmeoH9LT4’>‘_（9 分 36 秒）的
历史。

为了帮助理解该标准，Jukka Korpela 编写了阅读 Unicode 字符表的‘介绍性指南
<‘http://jkorpela.fi/unicode/guide.html’>‘_ 。

Joel Spolsky 撰写了另一篇不错的介绍性文章
<‘https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character’-
set-no-excuses/>‘_ 。如果本文没让您弄清楚，那应在继续之前先试着读读这篇
文章。

Wikipedia 条目通常也有帮助；请参阅“字符编码(3)”和 UTF-8(4) 的条目，例如
：

   ---------- Footnotes ----------

   (1) http://www.unicode.org

   (2) http://www.unicode.org/history/

   (3) https://en.wikipedia.org/wiki/Character_encoding

   (4) https://en.wikipedia.org/wiki/UTF-8


File: python.info,  Node: Python对Unicode的支持,  Next: Unicode 数据的读写,  Prev: Unicode 概述,  Up: Unicode 指南

10.11.2 Python对Unicode的支持
-----------------------------

现在您已经了解了 Unicode 的基础知识，可以看下 Python 的 Unicode 特性。

* Menu:

* 字符串类型::
* 转换为字节::
* Python 源代码中的 Unicode 文字::
* Unicode属性::
* 字符串比较::
* Unicode 正则表达式::
* 参考文献: 参考文献<4>.


File: python.info,  Node: 字符串类型,  Next: 转换为字节,  Up: Python对Unicode的支持

10.11.2.1 字符串类型
....................

从 Python 3.0 开始， *note str: 339. 类型包含了 Unicode 字符，这意味着用
‘‘"unicode rocks!"‘、’’unicode rocks!’‘‘ 或三重引号字符串语法创建的任何
字符串都会存储为 Unicode。

Python 源代码的默认编码是 UTF-8，因此可以直接在字符串中包含 Unicode 字符
：

     try:
         with open('/tmp/input.txt', 'r') as f:
             ...
     except OSError:
         # 'File not found' error message.
         print("Fichier non trouvé")

旁注：Python 3 还支持在标识符中使用 Unicode 字符：

     répertoire = "/tmp/records.log"
     with open(répertoire, "w") as f:
         f.write("test\n")

如果无法在编辑器中输入某个字符，或出于某种原因想只保留 ASCII 编码的源代
码，则还可以在字符串中使用转义序列。（根据系统的不同，可能会看到真的大写
Delta 字体而不是 u 转义符。）：

     >>> "\N{GREEK CAPITAL LETTER DELTA}"  # Using the character name
     '\u0394'
     >>> "\u0394"                          # Using a 16-bit hex value
     '\u0394'
     >>> "\U00000394"                      # Using a 32-bit hex value
     '\u0394'

此外，可以用 *note bytes: 33a. 的 *note decode(): c40. 方法创建一个字符
串。 该方法可以接受 `encoding' 参数，比如可以为 ‘UTF-8’ ，以及可选的
`errors' 参数。

若无法根据编码规则对输入字符串进行编码，`errors' 参数指定了响应策略。 该
参数的合法值可以是 ‘'strict'’ (触发 *note UnicodeDecodeError: 1fe. 异常
)、‘'replace'’ (用 ‘U+FFFD’、‘REPLACEMENT CHARACTER’)、‘'ignore'’ (只是
将字符从 Unicode 结果中去掉)，或 ‘'backslashreplace'’ (插入一个 ‘\xNN’ 转
义序列)。 以下示例演示了这些不同的参数:

     >>> b'\x80abc'.decode("utf-8", "strict")
     Traceback (most recent call last):
         ...
     UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0:
       invalid start byte
     >>> b'\x80abc'.decode("utf-8", "replace")
     '\ufffdabc'
     >>> b'\x80abc'.decode("utf-8", "backslashreplace")
     '\\x80abc'
     >>> b'\x80abc'.decode("utf-8", "ignore")
     'abc'

编码格式以包含编码格式名称的字符串来指明。 Python 有大约 100 种不同的编
码格式；清单详见 Python 库参考文档 *note 标准编码: 698.。 一些编码格式有
多个名称，比如 ‘'latin-1'’、‘'iso_8859_1'’ 和 ‘'8859’ 都是指同一种编码。

利用内置函数 *note chr(): 1438. 还可以创建单字符的 Unicode 字符串，该函
数可接受整数参数，并返回包含对应码位的长度为 1 的 Unicode 字符串。内置函
数 *note ord(): 1437. 是其逆操作，参数为单个字符的 Unicode 字符串，并返
回码位值：

     >>> chr(57344)
     '\ue000'
     >>> ord('\ue000')
     57344


File: python.info,  Node: 转换为字节,  Next: Python 源代码中的 Unicode 文字,  Prev: 字符串类型,  Up: Python对Unicode的支持

10.11.2.2 转换为字节
....................

*note bytes.decode(): c40. 的逆方法是 *note str.encode(): c3f. ，它会返
回 Unicode 字符串的 *note bytes: 33a. 形式，已按要求的 `encoding' 进行了
编码。

参数 `errors' 的意义与 *note decode(): c40. 方法相同，但支持更多可能的
handler。除了 ‘'strict'’ 、 ‘'ignore'’ 和 ‘'replace'’ （这时会插入问号替
换掉无法编码的字符），还有 ‘'xmlcharrefreplace'’ （插入一个 XML 字符引用
）、 ‘backslashreplace’ （插入一个 ‘\uNNNN’ 转义序列）和 ‘namereplace’ （
插入一个 ‘\N{...}’ 转义序列 ）。

以下例子演示了各种不同的结果：

     >>> u = chr(40960) + 'abcd' + chr(1972)
     >>> u.encode('utf-8')
     b'\xea\x80\x80abcd\xde\xb4'
     >>> u.encode('ascii')
     Traceback (most recent call last):
         ...
     UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in
       position 0: ordinal not in range(128)
     >>> u.encode('ascii', 'ignore')
     b'abcd'
     >>> u.encode('ascii', 'replace')
     b'?abcd?'
     >>> u.encode('ascii', 'xmlcharrefreplace')
     b'&#40960;abcd&#1972;'
     >>> u.encode('ascii', 'backslashreplace')
     b'\\ua000abcd\\u07b4'
     >>> u.encode('ascii', 'namereplace')
     b'\\N{YI SYLLABLE IT}abcd\\u07b4'

用于注册和访问可用编码格式的底层函数，位于 *note codecs: 1c. 模块中。 若
要实现新的编码格式，则还需要了解 *note codecs: 1c. 模块。 不过该模块返回
的编码和解码函数通常更为底层一些，不大好用，编写新的编码格式是一项专业的
任务，因此本文不会涉及该模块。


File: python.info,  Node: Python 源代码中的 Unicode 文字,  Next: Unicode属性,  Prev: 转换为字节,  Up: Python对Unicode的支持

10.11.2.3 Python 源代码中的 Unicode 文字
........................................

在 Python 源代码中，可以用 ‘\u’ 转义序列书写特定的 Unicode 码位，该序列
后跟 4 个代表码位的十六进制数字。‘\U’ 转义序列用法类似，但要用8 个十六进
制数字，而不是 4 个：

     >>> s = "a\xac\u1234\u20ac\U00008000"
     ... #     ^^^^ two-digit hex escape
     ... #         ^^^^^^ four-digit Unicode escape
     ... #                     ^^^^^^^^^^ eight-digit Unicode escape
     >>> [ord(c) for c in s]
     [97, 172, 4660, 8364, 32768]

对大于 127 的码位使用转义序列，数量不多时没什么问题，但如果要用到很多重
音字符，这会变得很烦人，类似于程序中的信息是用法语或其他使用重音的语言写
的。也可以用内置函数 *note chr(): 1438. 拼装字符串，但会更加乏味。

理想情况下，都希望能用母语的编码书写文本。还能用喜好的编辑器编辑 Python
源代码，编辑器要能自然地显示重音符，并在运行时使用正确的字符。

默认情况下，Python 支持以 UTF-8 格式编写源代码，但如果声明要用的编码，则
几乎可以使用任何编码。只要在源文件的第一行或第二行包含一个特殊注释即可：

     #!/usr/bin/env python
     # -*- coding: latin-1 -*-

     u = 'abcdé'
     print(ord(u[-1]))

上述语法的灵感来自于 Emacs 用于指定文件局部变量的符号。Emacs 支持许多不
同的变量，但 Python 仅支持“编码”。 ‘-*-’ 符号向 Emacs 标明该注释是特殊的
；这对 Python 没有什么意义，只是一种约定。Python 在注释中查找 ‘coding:
name’ 或 ‘coding=name’ 。

如果没有这种注释，则默认编码将会是前面提到的 UTF-8。更多信息请参阅 PEP
263(1) 。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0263


File: python.info,  Node: Unicode属性,  Next: 字符串比较,  Prev: Python 源代码中的 Unicode 文字,  Up: Python对Unicode的支持

10.11.2.4 Unicode属性
.....................

Unicode 规范包含了一个码位信息数据库。对于定义的每一个码位，都包含了字符
的名称、类别、数值（对于表示数字概念的字符，如罗马数字、分数如三分之一和
五分之四等）。还有有关显示的属性，比如如何在双向文本中使用码位。

以下程序显示了几个字符的信息，并打印一个字符的数值：

     import unicodedata

     u = chr(233) + chr(0x0bf2) + chr(3972) + chr(6000) + chr(13231)

     for i, c in enumerate(u):
         print(i, '%04x' % ord(c), unicodedata.category(c), end=" ")
         print(unicodedata.name(c))

     # Get numeric value of second character
     print(unicodedata.numeric(u[1]))

当运行时，这将打印出：

     0 00e9 Ll LATIN SMALL LETTER E WITH ACUTE
     1 0bf2 No TAMIL NUMBER ONE THOUSAND
     2 0f84 Mn TIBETAN MARK HALANTA
     3 1770 Lo TAGBANWA LETTER SA
     4 33af So SQUARE RAD OVER S SQUARED
     1000.0

类别代码是描述字符性质的缩写。 这些被分组为“字母”、“数字”、“标点符号”或
“符号”等类别，而这些类别又分为子类别。 从上面的输出中获取代码，‘'Ll'’ 表
示“字母，小写”，‘'No'’ 表示“数字，其他”，‘'Mn'’ 是“标记，非间距”，‘'So'’
是“符号，其他”。 有关类别代码列表，请参阅 Unicode 字符数据库文档
<‘http://www.unicode.org/reports/tr44/#General_Category_Values’>‘_ 的“通
用类别值”部分。


File: python.info,  Node: 字符串比较,  Next: Unicode 正则表达式,  Prev: Unicode属性,  Up: Python对Unicode的支持

10.11.2.5 字符串比较
....................

Unicode 让字符串的比较变得复杂了一些，因为同一组字符可能由不同的码位序列
组成。例如，像“ê”这样的字母可以表示为单码位 U+00EA，或是 U+0065 U+0302，
即“e”的码位后跟“COMBINING CIRCUMFLEX ACCENT”的码位。虽然在打印时会产生同
样的输出，但一个是长度为 1 的字符串，另一个是长度为 2 的字符串。

一种不区分大小写比较的工具是字符串方法 *note casefold(): 6b9. ，将按照
Unicode 标准描述的算法将字符串转换为不区分大小写的形式。该算法对诸如德语
字母“ß”（代码点 U+00DF）之类的字符进行了特殊处理，变为一对小写字母“ss”。

     >>> street = 'Gürzenichstraße'
     >>> street.casefold()
     'gürzenichstrasse'

第二个工具是 *note unicodedata: 11b. 模块的 *note normalize(): 10bf. 函
数，将字符串转换为几种常规形式之一，其中后跟组合字符的字母将被替换为单个
字符。 ‘normalize()’ 可用于执行字符串比较，即便两个字符串采用不同的字符
组合，也不会错误地报告两者不相等：

     import unicodedata

     def compare_strs(s1, s2):
         def NFD(s):
             return unicodedata.normalize('NFD', s)

         return NFD(s1) == NFD(s2)

     single_char = 'ê'
     multiple_chars = '\N{LATIN SMALL LETTER E}\N{COMBINING CIRCUMFLEX ACCENT}'
     print('length of first string=', len(single_char))
     print('length of second string=', len(multiple_chars))
     print(compare_strs(single_char, multiple_chars))

当运行时，这将输出：

     $ python3 compare-strs.py
     length of first string= 1
     length of second string= 2
     True

*note normalize(): 10bf. 函数的第一个参数是个字符串，给出所需的规范化形
式，可以是“NFC”、“NFKC”、“NFD”和“NFKD”之一。

Unicode 标准还设定了如何进行不区分大小写的比较：

     import unicodedata

     def compare_caseless(s1, s2):
         def NFD(s):
             return unicodedata.normalize('NFD', s)

         return NFD(NFD(s1).casefold()) == NFD(NFD(s2).casefold())

     # Example usage
     single_char = 'ê'
     multiple_chars = '\N{LATIN CAPITAL LETTER E}\N{COMBINING CIRCUMFLEX ACCENT}'

     print(compare_caseless(single_char, multiple_chars))

这将打印 ‘True’ 。（为什么 ‘NFD()’ 会被调用两次？因为有几个字符让
‘casefold()’ 返回非规范化的字符串，所以结果需要再次进行规范化。参见
Unicode 标准的 3.13 节 的一个讨论和示例。）


File: python.info,  Node: Unicode 正则表达式,  Next: 参考文献<4>,  Prev: 字符串比较,  Up: Python对Unicode的支持

10.11.2.6 Unicode 正则表达式
............................

*note re: de. 模块支持的正则表达式可以用字节串或字符串的形式提供。有一些
特殊字符序列，比如 ‘\d’ 和 ‘\w’ 具有不同的含义，具体取决于匹配模式是以字
节串还是字符串形式提供的。例如，‘\d’ 将匹配字节串中的字符 ‘[0-9]’ ，但对
于字符串将会匹配 ‘'Nd'’ 类别中的任何字符。

上述示例中的字符串包含了泰语和阿拉伯数字书写的数字 57：

     import re
     p = re.compile(r'\d+')

     s = "Over \u0e55\u0e57 57 flavours"
     m = p.search(s)
     print(repr(m.group()))

执行时，‘\d+’ 将匹配上泰语数字并打印出来。如果向 *note compile(): 452. 提
供的是 *note re.ASCII: 3d0. 标志，‘\d+’ 则会匹配子串 "57"。

类似地，‘\w’ 将匹配多种 Unicode 字符，但对于字节串则只会匹配
‘[a-zA-Z0-9_]’ ，如果指定 *note re.ASCII: 3d0.， ‘\s `` 将匹配 Unicode 空
白符或 ``[ \t\n\r\f\v]’。


File: python.info,  Node: 参考文献<4>,  Prev: Unicode 正则表达式,  Up: Python对Unicode的支持

10.11.2.7 参考文献
..................

关于 Python 的 Unicode 支持，其他还有一些很好的讨论：

   * 用 Python 3 处理文本文件(1) ，作者 Nick Coghlan。

   * 实用的 Unicode(2)，Ned Batchelder 在 PyCon 2012 上的演示。

*note str: 339. 类型在 Python 库参考文档 *note 文本序列类型 — str: 1233.
中有介绍。

*note unicodedata: 11b. 模块的文档

*note codecs: 1c. 模块的文档

Marc-André Lemburg 在 EuroPython 2002 上做了一个题为“Python 和 Unicode”（
PDF 幻灯片）
<‘https://downloads.egenix.com/python/Unicode-EPC2002-Talk.pdf’>‘_ 的演
示文稿。该幻灯片很好地概括了 Python 2 的 Unicode 功能设计（其中 Unicode
字符串类型称为 ‘unicode’，文字以 ‘u’ 开头）。

   ---------- Footnotes ----------

   (1) 
http://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html

   (2) https://nedbatchelder.com/text/unipain.html


File: python.info,  Node: Unicode 数据的读写,  Next: 致谢<10>,  Prev: Python对Unicode的支持,  Up: Unicode 指南

10.11.3 Unicode 数据的读写
--------------------------

既然处理 Unicode 数据的代码写好了，下一个问题就是输入/输出了。如何将
Unicode 字符串读入程序，如何将 Unicode 转换为适于存储或传输的形式呢？

根据输入源和输出目标的不同，或许什么都不用干；请检查一下应用程序用到的库
是否原生支持 Unicode。例如，XML 解析器往往会返回 Unicode 数据。许多关系
数据库的字段也支持 Unicode 值，并且 SQL 查询也能返回 Unicode 值。

在写入磁盘或通过套接字发送之前，Unicode 数据通常要转换为特定的编码。可以
自己完成所有工作：打开一个文件，从中读取一个 8 位字节对象，然后用
‘bytes.decode(encoding)’ 对字节串进行转换。但是，不推荐采用这种全人工的
方案。

编码的多字节特性就是一个难题； 一个 Unicode 字符可以用几个字节表示。 如
果要以任意大小的块（例如 1024 或 4096 字节）读取文件，那么在块的末尾可能
只读到某个 Unicode 字符的部分字节，这就需要编写错误处理代码。 有一种解决
方案是将整个文件读入内存，然后进行解码，但这样就没法处理很大的文件了；若
要读取 2 GB 的文件，就需要 2 GB 的 RAM。（其实需要的内存会更多些，因为至
少有一段时间需要在内存中同时存放已编码字符串及其 Unicode 版本。）

解决方案是利用底层解码接口去捕获编码序列不完整的情况。这部分代码已经是现
成的：内置函数 *note open(): 4f8. 可以返回一个文件类的对象，该对象认为文
件的内容采用指定的编码，*note read(): 2015. 和 *note write(): 2018. 等方
法接受 Unicode 参数。只要用 *note open(): 4f8. 的 `encoding' 和 `errors'
参数即可，参数释义同 *note str.encode(): c3f. 和 *note bytes.decode():
c40. 。

因此从文件读取 Unicode 就比较简单了：

     with open('unicode.txt', encoding='utf-8') as f:
         for line in f:
             print(repr(line))

也可以在更新模式下打开文件，以便同时读取和写入：

     with open('test', encoding='utf-8', mode='w+') as f:
         f.write('\u4500 blah blah blah\n')
         f.seek(0)
         print(repr(f.readline()[:1]))

Unicode 字符 ‘U+FEFF’ 用作字节顺序标记（BOM），通常作为文件的第一个字符
写入，以帮助自动检测文件的字节顺序。某些编码（例如 UTF-16）期望在文件开
头出现 BOM；当采用这种编码时，BOM 将自动作为第一个字符写入，并在读取文件
时会静默删除。这些编码有多种变体，例如用于 little-endian 和 big-endian 编
码的 “utf-16-le” 和 “utf-16-be”，会指定一种特定的字节顺序并且不会忽略
BOM。

在某些地区，习惯在 UTF-8 编码文件的开头用上“BOM”；此名称具有误导性，因为
UTF-8 与字节顺序无关。此标记只是声明该文件以 UTF-8 编码。要读取此类文件
，请使用“utf-8-sig”编码器自动忽略此标记。

* Menu:

* Unicode 文件名::
* 识别 Unicode 的编程技巧::
* 参考文献: 参考文献<5>.


File: python.info,  Node: Unicode 文件名,  Next: 识别 Unicode 的编程技巧,  Up: Unicode 数据的读写

10.11.3.1 Unicode 文件名
........................

当今大多数操作系统的文件名都支持包含任意 Unicode 字符。通常这是通过将
Unicode 字符串转换为某系统的编码来实现的。如今的 Python 趋向于采用 UTF-8
编码：MacOS 上的 Python 已经在多个版本中采用了 UTF-8，而 Python 3.6 在
Windows 上也改用了 UTF-8。在 Unix 系统中，只有设置了 ‘LANG’ 或
‘LC_CTYPE’ 环境变量，才会采用文件系统编码；否则默认编码还是 UTF-8。

*note sys.getfilesystemencoding(): 4fe. 函数将返回要在当前系统采用的编码
，若想手动进行编码时即可用到，但无需多虑。在打开文件进行读写时，通常只需
提供 Unicode 字符串作为文件名，会自动转换为合适的编码格式：

     filename = 'filename\u4500abc'
     with open(filename, 'w') as f:
         f.write('blah\n')

*note os: c5. 模块中的函数也能接受 Unicode 文件名，如 *note os.stat():
1f2. 。

*note os.listdir(): a49. 函数将返回文件名，这会引发一个难题：到底应返回
文件名的 Unicode 版本，还是应返回已编码的字节串呢？这两种操作 *note
os.listdir(): a49. 均可执行，具体取决于给出的目录路径是字节串形式还是
Unicode 字符串。若传入一个 Unicode 字符串作为路径，文件名将采用文件系统
的编码进行解码并返回一个 Unicode 字符串列表，而若传入一个字节串路径则会
返回字节串格式的文件名。以下假定默认文件系统编码为 UTF-8，运行以下程序：

     fn = 'filename\u4500abc'
     f = open(fn, 'w')
     f.close()

     import os
     print(os.listdir(b'.'))
     print(os.listdir('.'))

将产生以下输出：

     $ python listdir-test.py
     [b'filename\xe4\x94\x80abc', ...]
     ['filename\u4500abc', ...]

第一个列表包含 UTF-8 编码的文件名，第二个列表则包含 Unicode 版本的。

请注意，大多时候应该坚持用这些 API 处理 Unicode。字节串 API 应该仅用于可
能存在不可解码文件名的系统；现在几乎仅剩 Unix 系统了。


File: python.info,  Node: 识别 Unicode 的编程技巧,  Next: 参考文献<5>,  Prev: Unicode 文件名,  Up: Unicode 数据的读写

10.11.3.2 识别 Unicode 的编程技巧
.................................

本节提供了一些关于编写 Unicode 处理软件的建议。

最重要的技巧如下：

     程序应只在内部处理 Unicode 字符串，尽快对输入数据进行解码，并只在最
     后对输出进行编码。

如果尝试编写的处理函数对 Unicode 和字节串形式的字符串都能接受，就会发现
组合使用两种不同类型的字符串时，容易产生差错。没办法做到自动编码或解码：
如果执行 ‘str + bytes’，则会触发 *note TypeError: 193.。

当要使用的数据来自 Web 浏览器或其他不受信来源时，常用技术是在用该字符串
生成命令行之前，或要存入数据库之前，先检查字符串中是否包含非法字符。请仔
细检查解码后的字符串，而不是编码格式的字节串数据；有些编码可能具备一些有
趣的特性，例如与 ASCII 不是一一对应或不完全兼容。如果输入数据还指定了编
码格式，则尤其如此，因为攻击者可以选择一种巧妙的方式将恶意文本隐藏在经过
编码的字节流中。

* Menu:

* 在文件编码格式之间进行转换::
* 编码格式未知的文件::


File: python.info,  Node: 在文件编码格式之间进行转换,  Next: 编码格式未知的文件,  Up: 识别 Unicode 的编程技巧

10.11.3.3 在文件编码格式之间进行转换
....................................

*note StreamRecoder: fdd. 类可以在两种编码之间透明地进行转换，参数为编码
格式为 #1 的数据流，表现行为则是编码格式为 #2 的数据流。

假设输入文件 `f' 采用 Latin-1 编码格式，即可用 *note StreamRecoder: fdd.
包装后返回 UTF-8 编码的字节串：

     new_f = codecs.StreamRecoder(f,
         # en/decoder: used by read() to encode its results and
         # by write() to decode its input.
         codecs.getencoder('utf-8'), codecs.getdecoder('utf-8'),

         # reader/writer: used to read and write to the stream.
         codecs.getreader('latin-1'), codecs.getwriter('latin-1') )


File: python.info,  Node: 编码格式未知的文件,  Prev: 在文件编码格式之间进行转换,  Up: 识别 Unicode 的编程技巧

10.11.3.4 编码格式未知的文件
............................

若需对文件进行修改，但不知道文件的编码，那该怎么办呢？如果已知编码格式与
ASCII 兼容，并且只想查看或修改 ASCII 部分，则可利用 ‘surrogateescape’ 错
误处理程序打开文件：

     with open(fname, 'r', encoding="ascii", errors="surrogateescape") as f:
         data = f.read()

     # make changes to the string 'data'

     with open(fname + '.new', 'w',
               encoding="ascii", errors="surrogateescape") as f:
         f.write(data)

‘surrogateescape’ 错误处理 handler 会把所有非 ASCII 字节解码为 U+DC80 至
U+DCFF 这一特殊范围的码位。当 ‘surrogateescape’ 错误处理 handler用于数据
编码并回写时，这些码位将转换回去。


File: python.info,  Node: 参考文献<5>,  Prev: 识别 Unicode 的编程技巧,  Up: Unicode 数据的读写

10.11.3.5 参考文献
..................

David Beazley 在 PyCon 2010 上的演讲 掌握 Python 3 输入/输出(1) 中，有一
节讨论了文本和二进制数据的处理。

Marc-André Lemburg 演示的PDF 幻灯片“在 Python 中编写支持 Unicode 的应用
程序”(2) ，讨论了字符编码问题以及如何国际化和本地化应用程序。这些幻灯片
仅涵盖 Python 2.x。

Python Unicode 实质(3) 是 Benjamin Peterson 在 PyCon 2013 上的演讲，讨论
了 Unicode 在 Python 3.3 中的内部表示。

   ---------- Footnotes ----------

   (1) http://pyvideo.org/video/289/pycon-2010–mastering-python-3-io

   (2) 
https://downloads.egenix.com/python/LSM2005-Developing-Unicode-aware-applications-in-Python.pdf

   (3) http://pyvideo.org/video/1768/the-guts-of-unicode-in-python


File: python.info,  Node: 致谢<10>,  Prev: Unicode 数据的读写,  Up: Unicode 指南

10.11.4 致谢
------------

本文初稿由 Andrew Kuchling 撰写。此后，Alexander Belopolsky、Georg
Brandl、Andrew Kuchling 和 Ezio Melotti 作了进一步修订。

感谢以下各位指出本文错误或提出建议：Éric Araujo、Nicholas Bastin、Nick
Coghlan、Marius Gedminas、Kent Johnson、Ken Krugler、Marc-André Lemburg、
Martin von Löwis、Terry J. Reedy、Serhiy Storchaka , Eryk Sun, Chad
Whitacre, Graham Wideman。


File: python.info,  Node: HOWTO 使用 urllib 包获取网络资源,  Next: Argparse 教程,  Prev: Unicode 指南,  Up: Python 常用指引

10.12 HOWTO 使用 urllib 包获取网络资源
======================================


作者: Michael Foord(1)

     注解: 这份 HOWTO 文档的早期版本有一份法语的译文，可在 urllib2 - Le
     Manuel manquant(2) 处查阅。

* Menu:

* 概述: 概述<19>.
* 提取URL::
* 处理异常: 处理异常<2>.
* info and geturl::
* Opener 和 Handler::
* 基本认证::
* 代理::
* 套接字与分层::
* 备注::

   ---------- Footnotes ----------

   (1) http://www.voidspace.org.uk/python/index.shtml

   (2) 
http://www.voidspace.org.uk/python/articles/urllib2_francais.shtml


File: python.info,  Node: 概述<19>,  Next: 提取URL,  Up: HOWTO 使用 urllib 包获取网络资源

10.12.1 概述
------------

Related Articles
................

关于使用 Python 获取网页资源，你或许还可以找到下列有用的文章：

   * 基本的验证(1)

          关于 `基本的验证' 的入门指南，带有一些 Python 的示例。

`urllib.request' 是一个用于获取 URL （统一资源定位地址）的 Python 模块。
它以 `urlopen' 函数的形式提供了一个非常简单的接口。该接口能够使用不同的
协议获取 URL。同时它也提供了一个略微复杂的接口来处理常见情形——如：基本验
证、cookies、代理等等。这些功能是通过叫做 handlers 和 opener 的对象来提
供的。

urllib.request 支持多种 "URL 网址方案" （通过 URL中 ‘":"’ 之前的字符串加
以区分——如 URL 地址 ‘"ftp://python.org/"` 中的 ``"ftp"`’） ，使用与之相
关的网络协议（如：FTP、 HTTP）来获取 URL 资源。本指南重点关注最常用的情
形—— HTTP。

对于简单场景而言， `urlopen' 用起来十分容易。但只要在打开 HTTP URL 时遇
到错误或非常情况，就需要对超文本传输协议有所了解才行。最全面、最权威的
HTTP 参考是 RFC 2616(2) 。那是一份技术文档，并没有追求可读性。本 文旨在
说明 `urllib' 的用法，为了便于阅读也附带了足够详细的 HTTP 信息。本文并不
是为了替代 *note urllib.request: 121. 文档，只是其补充说明而已。

   ---------- Footnotes ----------

   (1) http://www.voidspace.org.uk/python/articles/authentication.shtml

   (2) https://tools.ietf.org/html/rfc2616.html


File: python.info,  Node: 提取URL,  Next: 处理异常<2>,  Prev: 概述<19>,  Up: HOWTO 使用 urllib 包获取网络资源

10.12.2 提取URL
---------------

下面是使用 urllib.request 最简单的方式：

     import urllib.request
     with urllib.request.urlopen('http://python.org/') as response:
        html = response.read()

如果你想通过 URL 获取资源并保存某个临时的地方，你可以通过 *note
shutil.copyfileobj(): 25e. 和 *note tempfile.NamedTemporaryFile(): d51.
函数:

     import shutil
     import tempfile
     import urllib.request

     with urllib.request.urlopen('http://python.org/') as response:
         with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
             shutil.copyfileobj(response, tmp_file)

     with open(tmp_file.name) as html:
         pass

urllib很易于使用（注意 URL 不仅仅可以以’http:’开头，也可以是’ftp:’，
’file:’等）。但是，这篇教程的目的是介绍更加复杂的用法，大多数以HTTP举例
。

HTTP基于请求和回应——客户端像服务器请求，服务器回应。urllib.request将你的
HTTP请求保存为一个‘‘Request‘‘对象。在最简单的情况下，一个Request对象里包
含你所请求的特定URL。以当前的Request对象作为参数调用‘‘urlopen‘‘返回服务
器对你正在请求的URL的回应。回应是个文件类对象，所以你可以调用如
‘‘.read()‘‘等命令。

     import urllib.request

     req = urllib.request.Request('http://www.voidspace.org.uk')
     with urllib.request.urlopen(req) as response:
        the_page = response.read()

注意urllib.request中的Request接口也支持处理所有的互联网协议。比如，你可
以像这样做一个 FTP 请求：

     req = urllib.request.Request('ftp://example.com/')

就 HTTP 而言，Request 对象能够做两件额外的事情：首先可以把数据传给服务器
。其次，可以将 `有关' 数据或请求本身的额外信息（metadata）传给服务器——这
些信息将会作为 HTTP “头部”数据发送。下面依次看下。

* Menu:

* 数据::
* HTTP 头部信息::


File: python.info,  Node: 数据,  Next: HTTP 头部信息,  Up: 提取URL

10.12.2.1 数据
..............

有时候你想要给一个 URL 发送数据（通常这个URL指向一个CGI（通用网关接口）
脚本或者其他 web 应用）。 对于 HTTP，这通常使用一个 `POST' 请求来完成。
比如在浏览器上提交一个 HTML 表单。 但并不是所有的 POST 都来自表单：你能
使用一个 POST 来传输任何数据到你自己的应用上。 在使用常见的 HTML 表单的
情况下，数据需要以标准的方式编码，然后再作为 ‘data’ 参数传给 Request 对
象。 编码需要使用一个来自 *note urllib.parse: 120. 库的函数。

     import urllib.parse
     import urllib.request

     url = 'http://www.someserver.com/cgi-bin/register.cgi'
     values = {'name' : 'Michael Foord',
               'location' : 'Northampton',
               'language' : 'Python' }

     data = urllib.parse.urlencode(values)
     data = data.encode('ascii') # data should be bytes
     req = urllib.request.Request(url, data)
     with urllib.request.urlopen(req) as response:
        the_page = response.read()

请注意，有时还需要采用其他编码，比如由 HTML 表单上传文件——更多细节请参见
HTML 规范，提交表单(1) 。

如果不传递 ‘data’ 参数，urllib 将采用 `GET' 请求。GET 和 POST 请求有一点
不同，POST 请求往往具有“副作用”，他们会以某种方式改变系统的状态。例如，
从网站下一个订单，购买一大堆罐装垃圾并运送到家。 尽管 HTTP 标准明确指出
POST `总是' 要导致副作用，而 GET 请求 `从来不会' 导致副作用。但没有什么
办法能阻止 GET 和 POST 请求的副作用。数据也可以在 HTTP GET 请求中传递，
只要把数据编码到 URL 中即可。

具体操作如下:

     >>> import urllib.request
     >>> import urllib.parse
     >>> data = {}
     >>> data['name'] = 'Somebody Here'
     >>> data['location'] = 'Northampton'
     >>> data['language'] = 'Python'
     >>> url_values = urllib.parse.urlencode(data)
     >>> print(url_values)  # The order may differ from below.
     name=Somebody+Here&language=Python&location=Northampton
     >>> url = 'http://www.example.com/example.cgi'
     >>> full_url = url + '?' + url_values
     >>> data = urllib.request.urlopen(full_url)

请注意，完整的 URL 是通过在其中添加 ‘?’ 创建的，后面跟着经过编码的数据。

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13


File: python.info,  Node: HTTP 头部信息,  Prev: 数据,  Up: 提取URL

10.12.2.2 HTTP 头部信息
.......................

下面介绍一个具体的 HTTP 头部信息，以此说明如何在 HTTP 请求加入头部信息。

有些网站 (1) 不愿被程序浏览到，或者要向不同的浏览器发送不同版本 (2) 的网
页。默认情况下，urllib 将自身标识为“Python-urllib/xy”（其中 ‘x’ 、 ‘y’ 是
Python 版本的主、次版本号，例如 ‘Python-urllib/2.5’），这可能会让网站不
知所措，或者干脆就使其无法正常工作。浏览器是通过头部信息 ‘User-Agent’
(3) 来标识自己的。在创建 Request 对象时，可以传入字典形式的头部信息。以
下示例将生成与之前相同的请求，只是将自身标识为某个版本的 Internet
Explorer (4) ：

     import urllib.parse
     import urllib.request

     url = 'http://www.someserver.com/cgi-bin/register.cgi'
     user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
     values = {'name': 'Michael Foord',
               'location': 'Northampton',
               'language': 'Python' }
     headers = {'User-Agent': user_agent}

     data = urllib.parse.urlencode(values)
     data = data.encode('ascii')
     req = urllib.request.Request(url, data, headers)
     with urllib.request.urlopen(req) as response:
        the_page = response.read()

响应对象也有两个很有用的方法。请参阅有关 *note info 和 geturl: 41e2. 部
分，了解出现问题时会发生什么。

   ---------- Footnotes ----------

   (1) (1) 例如 Google。

   (2) (2) 对于网站设计而言，探测不同的浏览器是非常糟糕的做法——更为明智
的做法是采用 web 标准构建网站。不幸的是，很多网站依然向不同的浏览器发送
不同版本的网页。

   (3) (3) MSIE 6 的 user-agent 信息是 `“Mozilla/4.0 (compatible; MSIE
6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)”'

   (4) (4) 有关 HTTP 请求的头部信息，详情请参阅 *note Quick Reference to
HTTP Headers: 41e1.。


File: python.info,  Node: 处理异常<2>,  Next: info and geturl,  Prev: 提取URL,  Up: HOWTO 使用 urllib 包获取网络资源

10.12.3 处理异常
----------------

如果 `urlopen' 无法处理响应信息，就会触发 ‘URLError’ 。尽管与通常的
Python API 一样，也可能触发 *note ValueError: 1fc. 、 *note TypeError:
193. 等内置异常。

‘HTTPError’ 是 ‘URLError’ 的子类，当 URL 是 HTTP 的情况时将会触发。

异常类从 *note urllib.error: 11f. 模块中导出。

* Menu:

* URLError::
* HTTPError::
* 包装起来::


File: python.info,  Node: URLError,  Next: HTTPError,  Up: 处理异常<2>

10.12.3.1 URLError
..................

通常，引发 URLError 的原因是没有网络连接（或者没有到指定服务器的路由），
或者指定的服务器不存在。该情况下，将会引发该异常，并带有一个 ’reason’ 属
性，该属性是一个包含错误代码和文本错误信息的元组。

例如

     >>> req = urllib.request.Request('http://www.pretend_server.org')
     >>> try: urllib.request.urlopen(req)
     ... except urllib.error.URLError as e:
     ...     print(e.reason)
     ...
     (4, 'getaddrinfo failed')


File: python.info,  Node: HTTPError,  Next: 包装起来,  Prev: URLError,  Up: 处理异常<2>

10.12.3.2 HTTPError
...................

从服务器返回的每个 HTTP 响应都包含一个数字的 “状态码”。有时该状态码表明
服务器无法完成该请求。默认的处理器（函数？）将会为你处理这其中的一些响应
。（例如，如果响应包含了 "redirection"，将会要求客户端去向另外的 URL 获
取文档，urllib 将会为你处理该情形）。对于那些它无法处理的（状态代码），
urlopen 将会引发一个 ‘HTTPError’ 。典型的错误包括：‘404’（页面无法找到）
、‘403’（请求遭拒绝）和 ’401‘ （需要身份验证）。

全部的 HTTP 错误码请参阅 RFC 2616(1) 。

‘HTTPError’ 实例将包含一个整数型的“code”属性，对应于服务器发来的错误。

* Menu:

* 错误代码::

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2616.html


File: python.info,  Node: 错误代码,  Up: HTTPError

10.12.3.3 错误代码
..................

由于默认处理函数会自行处理重定向（300 以内的错误码），而且 100–299 的状
态码表示成功，因此通常只会出现 400–599 的错误码。

*note http.server.BaseHTTPRequestHandler.responses: 2ce0. 是很有用的响应
码字典，其中给出了 RFC 2616(1) 用到的所有响应代码。为方便起见，下面将此
字典转载如下：

     # Table mapping response codes to messages; entries have the
     # form {code: (shortmessage, longmessage)}.
     responses = {
         100: ('Continue', 'Request received, please continue'),
         101: ('Switching Protocols',
               'Switching to new protocol; obey Upgrade header'),

         200: ('OK', 'Request fulfilled, document follows'),
         201: ('Created', 'Document created, URL follows'),
         202: ('Accepted',
               'Request accepted, processing continues off-line'),
         203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
         204: ('No Content', 'Request fulfilled, nothing follows'),
         205: ('Reset Content', 'Clear input form for further input.'),
         206: ('Partial Content', 'Partial content follows.'),

         300: ('Multiple Choices',
               'Object has several resources -- see URI list'),
         301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
         302: ('Found', 'Object moved temporarily -- see URI list'),
         303: ('See Other', 'Object moved -- see Method and URL list'),
         304: ('Not Modified',
               'Document has not changed since given time'),
         305: ('Use Proxy',
               'You must use proxy specified in Location to access this '
               'resource.'),
         307: ('Temporary Redirect',
               'Object moved temporarily -- see URI list'),

         400: ('Bad Request',
               'Bad request syntax or unsupported method'),
         401: ('Unauthorized',
               'No permission -- see authorization schemes'),
         402: ('Payment Required',
               'No payment -- see charging schemes'),
         403: ('Forbidden',
               'Request forbidden -- authorization will not help'),
         404: ('Not Found', 'Nothing matches the given URI'),
         405: ('Method Not Allowed',
               'Specified method is invalid for this server.'),
         406: ('Not Acceptable', 'URI not available in preferred format.'),
         407: ('Proxy Authentication Required', 'You must authenticate with '
               'this proxy before proceeding.'),
         408: ('Request Timeout', 'Request timed out; try again later.'),
         409: ('Conflict', 'Request conflict.'),
         410: ('Gone',
               'URI no longer exists and has been permanently removed.'),
         411: ('Length Required', 'Client must specify Content-Length.'),
         412: ('Precondition Failed', 'Precondition in headers is false.'),
         413: ('Request Entity Too Large', 'Entity is too large.'),
         414: ('Request-URI Too Long', 'URI is too long.'),
         415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
         416: ('Requested Range Not Satisfiable',
               'Cannot satisfy request range.'),
         417: ('Expectation Failed',
               'Expect condition could not be satisfied.'),

         500: ('Internal Server Error', 'Server got itself in trouble'),
         501: ('Not Implemented',
               'Server does not support this operation'),
         502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
         503: ('Service Unavailable',
               'The server cannot process the request due to a high load'),
         504: ('Gateway Timeout',
               'The gateway server did not receive a timely response'),
         505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
         }

当触发错误时，服务器通过返回 HTTP 错误码 `和' 错误页面进行响应。可以将
‘HTTPError’ 实例用作返回页面的响应。这意味着除了 code 属性之外，错误对象
还像 ‘urllib.response’ 模块返回的那样具有 read、geturl 和 info 方法：

     >>> req = urllib.request.Request('http://www.python.org/fish.html')
     >>> try:
     ...     urllib.request.urlopen(req)
     ... except urllib.error.HTTPError as e:
     ...     print(e.code)
     ...     print(e.read())
     ...
     404
     b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
       ...
       <title>Page Not Found</title>\n
       ...

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2616.html


File: python.info,  Node: 包装起来,  Prev: HTTPError,  Up: 处理异常<2>

10.12.3.4 包装起来
..................

若要准备处理 ‘HTTPError’  `或' ‘URLError’ ，有两种简单的方案。推荐使用第
二种方案。

* Menu:

* 数字1::
* 第二种方案::


File: python.info,  Node: 数字1,  Next: 第二种方案,  Up: 包装起来

10.12.3.5 数字1
...............

     from urllib.request import Request, urlopen
     from urllib.error import URLError, HTTPError
     req = Request(someurl)
     try:
         response = urlopen(req)
     except HTTPError as e:
         print('The server couldn\'t fulfill the request.')
         print('Error code: ', e.code)
     except URLError as e:
         print('We failed to reach a server.')
         print('Reason: ', e.reason)
     else:
         # everything is fine

     注解: ‘except HTTPError’ `必须' 首先处理，否则 ‘except URLError’ 将
     会 `同时' 捕获 ‘HTTPError’ 。


File: python.info,  Node: 第二种方案,  Prev: 数字1,  Up: 包装起来

10.12.3.6 第二种方案
....................

     from urllib.request import Request, urlopen
     from urllib.error import URLError
     req = Request(someurl)
     try:
         response = urlopen(req)
     except URLError as e:
         if hasattr(e, 'reason'):
             print('We failed to reach a server.')
             print('Reason: ', e.reason)
         elif hasattr(e, 'code'):
             print('The server couldn\'t fulfill the request.')
             print('Error code: ', e.code)
     else:
         # everything is fine


File: python.info,  Node: info and geturl,  Next: Opener 和 Handler,  Prev: 处理异常<2>,  Up: HOWTO 使用 urllib 包获取网络资源

10.12.4 info and geturl
-----------------------

由 urlopen （或者 ‘HTTPError’ 实例）所返回的响应包含两个有用的方法：
‘info()’ 和 ‘geturl()’，该响应由模块 *note urllib.response: 122. 定义。

`geturl' - 返回所获取页面的真实 URL。该方法很有用，因为 ‘urlopen’ （或者
所使用的 opener 对象）可能回包括一次重定向。所获取页面的 URL 未必就是所
请求的 URL 。

`info' - 该方法返回一个类似字典的对象，描述了所获取的页面，特别是由服务
器送出的头部信息（headers） 。目前它是一个 ‘http.client.HTTPMessage’ 实
例。

典型的 HTTP 头部信息包括“Content-length”、“Content-type”等。有关 HTTP 头
部信息的清单，包括含义和用途的简要说明，请参阅 HTTP Header 快速参考(1) 。

   ---------- Footnotes ----------

   (1) http://jkorpela.fi/http.html


File: python.info,  Node: Opener 和 Handler,  Next: 基本认证,  Prev: info and geturl,  Up: HOWTO 使用 urllib 包获取网络资源

10.12.5 Opener 和 Handler
-------------------------

当获取 URL 时，会用到了一个 opener（一个类名可能经过混淆的 *note
urllib.request.OpenerDirector: 2c43. 的实例）。通常一直会用默认的 opener
——通过 ‘urlopen’ ——但也可以创建自定义的 opener 。opener 会用到 handler。
所有的“繁重工作”都由 handler 完成。每种 handler 知道某种 URL 方案（
http、ftp 等）的 URL 的打开方式，或是某方面 URL 的打开方式，例如 HTTP 重
定向或 HTTP cookie。

若要用已安装的某个 handler 获取 URL，需要创建一个 opener 对象，例如处理
cookie 的 handler，或对重定向不做处理的 handler。

若要创建 opener，请实例化一个 ‘OpenerDirector’ ，然后重复调用
‘.add_handler(some_handler_instance)’ 。

或者也可以用 ‘build_opener’ ，这是个用单次调用创建 opener 对象的便捷函数
。‘build_opener’ 默认会添加几个 handler，不过还提供了一种快速添加和/或覆
盖默认 handler 的方法。

可能还需要其他类型的 handler，以便处理代理、身份认证和其他常见但稍微特殊
的情况。

‘install_opener’ 可用于让 ‘opener’ 对象成为（全局）默认 opener。这意味着
调用 ‘urlopen’ 时会采用已安装的 opener。

opener 对象带有一个 ‘`open’ 方法，可供直接调用以获取 url，方式与
‘urlopen’ 函数相同。除非是为了调用方便，否则没必要去调用
‘install_opener’ 。


File: python.info,  Node: 基本认证,  Next: 代理,  Prev: Opener 和 Handler,  Up: HOWTO 使用 urllib 包获取网络资源

10.12.6 基本认证
----------------

To illustrate creating and installing a handler we will use the
‘HTTPBasicAuthHandler’.  For a more detailed discussion of this subject
– including an explanation of how Basic Authentication works - see the
Basic Authentication Tutorial(1).

如果需要身份认证，服务器会发送一条请求身份认证的头部信息（以及 401 错误
代码）。这条信息中指明了身份认证方式和“安全区域（realm）”。格式如下所示
：‘WWW-Authenticate: SCHEME realm="REALM"’ 。

例如

     WWW-Authenticate: Basic realm="cPanel Users"

然后，客户端应重试发起请求，请求数据中的头部信息应包含安全区域对应的用户
名和密码。这就是“基本身份认证”。为了简化此过程，可以创建
‘HTTPBasicAuthHandler’ 的一个实例及使用它的 opener。

‘HTTPBasicAuthHandler’ 用一个名为密码管理器的对象来管理 URL、安全区域与
密码、用户名之间的映射关系。如果知道确切的安全区域（来自服务器发送的身份
认证头部信息），那就可以用到 ‘HTTPPasswordMgr’ 。通常人们并不关心安全区
域是什么，这时用‘‘HTTPPasswordMgrWithDefaultRealm‘‘ 就很方便，允许为 URL
指定默认的用户名和密码。当没有为某个安全区域提供用户名和密码时，就会用到
默认值。下面用 ‘None’ 作为 ‘add_password’ 方法的安全区域参数，表明采用默
认用户名和密码。

首先需要身份认证的是顶级 URL。比传给 .add_password() 的 URL 级别“更深”的
URL 也会得以匹配：

     # create a password manager
     password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()

     # Add the username and password.
     # If we knew the realm, we could use it instead of None.
     top_level_url = "http://example.com/foo/"
     password_mgr.add_password(None, top_level_url, username, password)

     handler = urllib.request.HTTPBasicAuthHandler(password_mgr)

     # create "opener" (OpenerDirector instance)
     opener = urllib.request.build_opener(handler)

     # use the opener to fetch a URL
     opener.open(a_url)

     # Install the opener.
     # Now all calls to urllib.request.urlopen use our opener.
     urllib.request.install_opener(opener)

     注解: 在以上例子中，只向 ‘build_opener’ 给出了
     ‘HTTPBasicAuthHandler’ 。默认情况下，opener 会有用于处理常见状况的
     handler ——‘ProxyHandler’ （如果设置代理的话，比如设置了环境变量
     ‘http_proxy’ ），‘UnknownHandler’ 、‘HTTPHandler’ 、
     ‘HTTPDefaultErrorHandler’ 、 ‘HTTPRedirectHandler’ 、 ‘FTPHandler’
     、 ‘FileHandler’ 、 ‘DataHandler’ 、 ‘HTTPErrorProcessor’ 。

‘top_level_url’ 其实 `要么' 是一条完整的 URL（包括 “http:” 部分和主机名
及可选的端口号），比如 ‘"http://example.com/"’ ， `要么' 是一条“访问权限
”（即主机名，及可选的端口号），比如 ‘"example.com"’ 或
‘"example.com:8080"’ （后一个示例包含了端口号）。访问权限 `不得' 包含“用
户信息”部分——比如 ‘"joe:password@example.com"’ 就不正确。

   ---------- Footnotes ----------

   (1) http://www.voidspace.org.uk/python/articles/authentication.shtml


File: python.info,  Node: 代理,  Next: 套接字与分层,  Prev: 基本认证,  Up: HOWTO 使用 urllib 包获取网络资源

10.12.7 代理
------------

`urllib' 将自动检测并使用代理设置。 这是通过 ‘ProxyHandler’ 实现的，当检
测到代理设置时，是正常 handler 链中的一部分。通常这是一件好事，但有时也
可能会无效 (1)。 一种方案是配置自己的 ‘ProxyHandler’ ，不要定义代理。 设
置的步骤与 *note Basic Authentication: 41ed. handler 类似:

     >>> proxy_support = urllib.request.ProxyHandler({})
     >>> opener = urllib.request.build_opener(proxy_support)
     >>> urllib.request.install_opener(opener)

     注解: 目前 ‘urllib.request’ `尚不' 支持通过代理抓取 ‘https’ 链接地
     址。 但此功能可以通过扩展 urllib.request 来启用，如以下例程所示
     (2)。

     注解: 如果设置了 ‘REQUEST_METHOD’ 变量，则会忽略 ‘HTTP_PROXY’ ；参
     阅 *note getproxies(): 2c50. 文档。

   ---------- Footnotes ----------

   (1) (5) 本人必须使用代理才能在工作中访问互联网。如果尝试通过代理获取
`localhost' URL，将会遭到阻止。IE 设置为代理模式，urllib 就会获取到配置
信息。为了用 localhost 服务器测试脚本，我必须阻止 urllib 使用代理。

   (2) (6) urllib 的 SSL 代理 opener（CONNECT  方法）： ASPN Cookbook
Recipe (https://code.activestate.com/recipes/456195/) 。


File: python.info,  Node: 套接字与分层,  Next: 备注,  Prev: 代理,  Up: HOWTO 使用 urllib 包获取网络资源

10.12.8 套接字与分层
--------------------

Python 获取 Web 资源的能力是分层的。urllib 用到的是 *note http.client:
94. 库，而后者又用到了套接字库。

从 Python 2.3 开始，可以指定套接字等待响应的超时时间。这对必须要读到网页
数据的应用程序会很有用。默认情况下，套接字模块 `不会超时' 并且可以挂起。
目前，套接字超时机制未暴露给 http.client 或 urllib.request 层使用。不过
可以为所有用到的套接字设置默认的全局超时。

     import socket
     import urllib.request

     # timeout in seconds
     timeout = 10
     socket.setdefaulttimeout(timeout)

     # this call to urllib.request.urlopen now uses the default timeout
     # we have set in the socket module
     req = urllib.request.Request('http://www.voidspace.org.uk')
     response = urllib.request.urlopen(req)

__________________________________________________________________


File: python.info,  Node: 备注,  Prev: 套接字与分层,  Up: HOWTO 使用 urllib 包获取网络资源

10.12.9 备注
------------

这篇文档由 John Lee 审订。


File: python.info,  Node: Argparse 教程,  Next: ipaddress模块介绍,  Prev: HOWTO 使用 urllib 包获取网络资源,  Up: Python 常用指引

10.13 Argparse 教程
===================


作者: Tshepang Lekhonkhobe

这篇教程旨在作为 *note argparse: 6. 的入门介绍，此模块是 Python 标准库中
推荐的命令行解析模块。

     注解: 还有另外两个模块可以完成同样的任务，称为 *note getopt: 87. (对
     应于 C 语言中的 ‘getopt()’ 函数) 和被弃用的 *note optparse: c4.。还
     要注意 *note argparse: 6. 是基于 *note optparse: c4. 的，因此用法与
     其非常相似。

* Menu:

* 概念::
* 基础: 基础<2>.
* 位置参数介绍::
* 可选参数介绍::
* 结合位置参数和可选参数::
* 进行一些小小的改进::
* 后记::


File: python.info,  Node: 概念,  Next: 基础<2>,  Up: Argparse 教程

10.13.1 概念
------------

让我们利用 ‘ls’ 命令来展示我们将要在这篇入门教程中探索的功能：

     $ ls
     cpython  devguide  prog.py  pypy  rm-unused-function.patch
     $ ls pypy
     ctypes_configure  demo  dotviewer  include  lib_pypy  lib-python ...
     $ ls -l
     total 20
     drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython
     drwxr-xr-x  4 wena wena 4096 Feb  8 12:04 devguide
     -rwxr-xr-x  1 wena wena  535 Feb 19 00:05 prog.py
     drwxr-xr-x 14 wena wena 4096 Feb  7 00:59 pypy
     -rw-r--r--  1 wena wena  741 Feb 18 01:01 rm-unused-function.patch
     $ ls --help
     Usage: ls [OPTION]... [FILE]...
     List information about the FILEs (the current directory by default).
     Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.
     ...

我们可以从这四个命令中学到几个概念：

   * ‘ls’ 是一个即使在运行的时候没有提供任何选项，也非常有用的命令。在默
     认情况下他会输出当前文件夹包含的文件和文件夹。

   * 如果我们想要使用比它默认提供的更多功能，我们需要告诉该命令更多信息
     。在这个例子里，我们想要查看一个不同的目录，‘pypy’。我们所做的是指
     定所谓的位置参数。之所以这样命名，是因为程序应该如何处理该参数值，
     完全取决于它在命令行出现的位置。更能体现这个概念的命令如 ‘cp’，它最
     基本的用法是 ‘cp SRC DEST’。第一个位置参数指的是*你想要复制的*，第
     二个位置参数指的是*你想要复制到的位置*。

   * 现在假设我们想要改变这个程序的行为。在我们的例子中，我们不仅仅只是
     输出每个文件的文件名，还输出了更多信息。在这个例子中，‘-l’ 被称为可
     选参数。

   * 这是一段帮助文档的文字。它是非常有用的，因为当你遇到一个你从未使用
     过的程序时，你可以通过阅读它的帮助文档来弄清楚它是如何运行的。


File: python.info,  Node: 基础<2>,  Next: 位置参数介绍,  Prev: 概念,  Up: Argparse 教程

10.13.2 基础
------------

让我们从一个简单到（几乎）什么也做不了的例子开始：

     import argparse
     parser = argparse.ArgumentParser()
     parser.parse_args()

以下是该代码的运行结果：

     $ python3 prog.py
     $ python3 prog.py --help
     usage: prog.py [-h]

     optional arguments:
       -h, --help  show this help message and exit
     $ python3 prog.py --verbose
     usage: prog.py [-h]
     prog.py: error: unrecognized arguments: --verbose
     $ python3 prog.py foo
     usage: prog.py [-h]
     prog.py: error: unrecognized arguments: foo

程序运行情况如下：

   * 在没有任何选项的情况下运行脚本不会在标准输出显示任何内容。这没有什
     么用处。

   * 第二行代码开始展现出 *note argparse: 6. 模块的作用。我们几乎什么也
     没有做，但已经得到一条很好的帮助信息。

   * ‘--help’ 选项，也可缩写为 ‘-h’，是唯一一个可以直接使用的选项（即不
     需要指定该选项的内容）。指定任何内容都会导致错误。即便如此，我们也
     能直接得到一条有用的用法信息。


File: python.info,  Node: 位置参数介绍,  Next: 可选参数介绍,  Prev: 基础<2>,  Up: Argparse 教程

10.13.3 位置参数介绍
--------------------

举个例子：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("echo")
     args = parser.parse_args()
     print(args.echo)

运行此程序：

     $ python3 prog.py
     usage: prog.py [-h] echo
     prog.py: error: the following arguments are required: echo
     $ python3 prog.py --help
     usage: prog.py [-h] echo

     positional arguments:
       echo

     optional arguments:
       -h, --help  show this help message and exit
     $ python3 prog.py foo
     foo

程序运行情况如下：

   * 我们增加了 ‘add_argument()’ 方法，该方法用于指定程序能够接受哪些命
     令行选项。在这个例子中，我将选项命名为 ‘echo’，与其功能一致。

   * 现在调用我们的程序必须要指定一个选项。

   * The ‘parse_args()’ method actually returns some data from the
     options specified, in this case, ‘echo’.

   * 这一变量是 *note argparse: 6. 免费施放的某种 “魔法”（即是说，不需要
     指定哪个变量是存储哪个值的）。你也可以注意到，这一名称与传递给方法
     的字符串参数一致，都是 ‘echo’。

然而请注意，尽管显示的帮助看起来清楚完整，但它可以比现在更有帮助。比如我
们可以知道 ‘echo’ 是一个位置参数，但我们除了靠猜或者看源代码，没法知道它
是用来干什么的。所以，我们可以把它改造得更有用：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("echo", help="echo the string you use here")
     args = parser.parse_args()
     print(args.echo)

然后我们得到：

     $ python3 prog.py -h
     usage: prog.py [-h] echo

     positional arguments:
       echo        echo the string you use here

     optional arguments:
       -h, --help  show this help message and exit

现在，来做一些更有用的事情：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("square", help="display a square of a given number")
     args = parser.parse_args()
     print(args.square**2)

以下是该代码的运行结果：

     $ python3 prog.py 4
     Traceback (most recent call last):
       File "prog.py", line 5, in <module>
         print(args.square**2)
     TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

进展不太顺利。那是因为 *note argparse: 6. 会把我们传递给它的选项视作为字
符串，除非我们告诉它别这样。所以，让我们来告诉 *note argparse: 6. 来把这
一输入视为整数：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("square", help="display a square of a given number",
                         type=int)
     args = parser.parse_args()
     print(args.square**2)

以下是该代码的运行结果：

     $ python3 prog.py 4
     16
     $ python3 prog.py four
     usage: prog.py [-h] square
     prog.py: error: argument square: invalid int value: 'four'

做得不错。当这个程序在收到错误的无效的输入时，它甚至能在执行计算之前先退
出，还能显示很有帮助的错误信息。


File: python.info,  Node: 可选参数介绍,  Next: 结合位置参数和可选参数,  Prev: 位置参数介绍,  Up: Argparse 教程

10.13.4 可选参数介绍
--------------------

到目前为止，我们一直在研究位置参数。让我们看看如何添加可选的：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("--verbosity", help="increase output verbosity")
     args = parser.parse_args()
     if args.verbosity:
         print("verbosity turned on")

和输出：

     $ python3 prog.py --verbosity 1
     verbosity turned on
     $ python3 prog.py
     $ python3 prog.py --help
     usage: prog.py [-h] [--verbosity VERBOSITY]

     optional arguments:
       -h, --help            show this help message and exit
       --verbosity VERBOSITY
                             increase output verbosity
     $ python3 prog.py --verbosity
     usage: prog.py [-h] [--verbosity VERBOSITY]
     prog.py: error: argument --verbosity: expected one argument

程序运行情况如下：

   * 这一程序被设计为当指定 ‘--verbosity’ 选项时显示某些东西，否则不显示
     。

   * 不添加这一选项时程序没有提示任何错误而退出，表明这一选项确实是可选
     的。注意，如果一个可选参数没有被使用时，相关变量被赋值为 ‘None’，在
     此例中是 ‘args.verbosity’，这也就是为什么它在 *note if: def. 语句中
     被当作逻辑假。

   * 帮助信息有点不同。

   * 使用 ‘--verbosity’ 选项时，必须指定一个值，但可以是任何值。

上述例子接受任何整数值作为 ‘--verbosity’ 的参数，但对于我们的简单程序而
言，只有两个值有实际意义：‘True’ 或者 ‘False’。让我们据此修改代码：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("--verbose", help="increase output verbosity",
                         action="store_true")
     args = parser.parse_args()
     if args.verbose:
         print("verbosity turned on")

和输出：

     $ python3 prog.py --verbose
     verbosity turned on
     $ python3 prog.py --verbose 1
     usage: prog.py [-h] [--verbose]
     prog.py: error: unrecognized arguments: 1
     $ python3 prog.py --help
     usage: prog.py [-h] [--verbose]

     optional arguments:
       -h, --help  show this help message and exit
       --verbose   increase output verbosity

程序运行情况如下：

   * 现在，这一选项更多地是一个标志，而非需要接受一个值的什么东西。我们
     甚至改变了选项的名字来符合这一思路。注意我们现在指定了一个新的关键
     词 ‘action’，并赋值为 ‘"store_true"’。这意味着，当这一选项存在时，
     为 ‘args.verbose’ 赋值为 ‘True’。没有指定时则隐含地赋值为 ‘False’。

   * 当你为其指定一个值时，它会报错，符合作为标志的真正的精神。

   * 留意不同的帮助文字。

* Menu:

* 短选项::


File: python.info,  Node: 短选项,  Up: 可选参数介绍

10.13.4.1 短选项
................

如果你熟悉命令行的用法，你会发现我还没讲到这一选项的短版本。这也很简单：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("-v", "--verbose", help="increase output verbosity",
                         action="store_true")
     args = parser.parse_args()
     if args.verbose:
         print("verbosity turned on")

效果就像这样：

     $ python3 prog.py -v
     verbosity turned on
     $ python3 prog.py --help
     usage: prog.py [-h] [-v]

     optional arguments:
       -h, --help     show this help message and exit
       -v, --verbose  increase output verbosity

可以注意到，这一新的能力也反映在帮助文本里。


File: python.info,  Node: 结合位置参数和可选参数,  Next: 进行一些小小的改进,  Prev: 可选参数介绍,  Up: Argparse 教程

10.13.5 结合位置参数和可选参数
------------------------------

我们的程序变得越来越复杂了：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("square", type=int,
                         help="display a square of a given number")
     parser.add_argument("-v", "--verbose", action="store_true",
                         help="increase output verbosity")
     args = parser.parse_args()
     answer = args.square**2
     if args.verbose:
         print("the square of {} equals {}".format(args.square, answer))
     else:
         print(answer)

接着是输出：

     $ python3 prog.py
     usage: prog.py [-h] [-v] square
     prog.py: error: the following arguments are required: square
     $ python3 prog.py 4
     16
     $ python3 prog.py 4 --verbose
     the square of 4 equals 16
     $ python3 prog.py --verbose 4
     the square of 4 equals 16

   * 我们带回了一个位置参数，结果发生了报错。

   * 注意顺序无关紧要。

给我们的程序加上接受多个冗长度的值，然后实际来用用：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("square", type=int,
                         help="display a square of a given number")
     parser.add_argument("-v", "--verbosity", type=int,
                         help="increase output verbosity")
     args = parser.parse_args()
     answer = args.square**2
     if args.verbosity == 2:
         print("the square of {} equals {}".format(args.square, answer))
     elif args.verbosity == 1:
         print("{}^2 == {}".format(args.square, answer))
     else:
         print(answer)

和输出：

     $ python3 prog.py 4
     16
     $ python3 prog.py 4 -v
     usage: prog.py [-h] [-v VERBOSITY] square
     prog.py: error: argument -v/--verbosity: expected one argument
     $ python3 prog.py 4 -v 1
     4^2 == 16
     $ python3 prog.py 4 -v 2
     the square of 4 equals 16
     $ python3 prog.py 4 -v 3
     16

除了最后一个，看上去都不错。最后一个暴露了我们的程序中有一个 bug。我们可
以通过限制 ‘--verbosity’ 选项可以接受的值来修复它：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("square", type=int,
                         help="display a square of a given number")
     parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
                         help="increase output verbosity")
     args = parser.parse_args()
     answer = args.square**2
     if args.verbosity == 2:
         print("the square of {} equals {}".format(args.square, answer))
     elif args.verbosity == 1:
         print("{}^2 == {}".format(args.square, answer))
     else:
         print(answer)

和输出：

     $ python3 prog.py 4 -v 3
     usage: prog.py [-h] [-v {0,1,2}] square
     prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
     $ python3 prog.py 4 -h
     usage: prog.py [-h] [-v {0,1,2}] square

     positional arguments:
       square                display a square of a given number

     optional arguments:
       -h, --help            show this help message and exit
       -v {0,1,2}, --verbosity {0,1,2}
                             increase output verbosity

注意这一改变同时反应在错误信息和帮助信息里。

现在，让我们使用另一种的方式来改变冗长度。这种方式更常见，也和 CPython 的
可执行文件处理它自己的冗长度参数的方式一致（参考 ‘python --help’ 的输出
）：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("square", type=int,
                         help="display the square of a given number")
     parser.add_argument("-v", "--verbosity", action="count",
                         help="increase output verbosity")
     args = parser.parse_args()
     answer = args.square**2
     if args.verbosity == 2:
         print("the square of {} equals {}".format(args.square, answer))
     elif args.verbosity == 1:
         print("{}^2 == {}".format(args.square, answer))
     else:
         print(answer)

我们引入了另一种动作 ‘count’，来数某一个可选参数出现了几次：

     $ python3 prog.py 4
     16
     $ python3 prog.py 4 -v
     4^2 == 16
     $ python3 prog.py 4 -vv
     the square of 4 equals 16
     $ python3 prog.py 4 --verbosity --verbosity
     the square of 4 equals 16
     $ python3 prog.py 4 -v 1
     usage: prog.py [-h] [-v] square
     prog.py: error: unrecognized arguments: 1
     $ python3 prog.py 4 -h
     usage: prog.py [-h] [-v] square

     positional arguments:
       square           display a square of a given number

     optional arguments:
       -h, --help       show this help message and exit
       -v, --verbosity  increase output verbosity
     $ python3 prog.py 4 -vvv
     16

   * 是的，它现在比前一版本更像是一个标志（和 ‘action="store_true"’ 相似
     ）。这能解释它为什么报错。

   * 它也表现得与 “store_true” 的行为相似。

   * 这给出了一个关于 ‘count’ 动作的效果的演示。你之前很可能应该已经看过
     这种用法。

   * 如果你不添加 ‘-v’ 标志，这一标志的值会是 ‘None’。

   * 如期望的那样，添加该标志的长形态能够获得相同的输出。

   * 可惜的是，对于我们的脚本获得的新能力，我们的帮助输出并没有提供很多
     信息，但我们总是可以通过改善文档来修复这一问题（比如通过 ‘help’ 关
     键字参数）。

   * 最后一个输出暴露了我们程序中的一个 bug。

让我们修复一下：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("square", type=int,
                         help="display a square of a given number")
     parser.add_argument("-v", "--verbosity", action="count",
                         help="increase output verbosity")
     args = parser.parse_args()
     answer = args.square**2

     # bugfix: replace == with >=
     if args.verbosity >= 2:
         print("the square of {} equals {}".format(args.square, answer))
     elif args.verbosity >= 1:
         print("{}^2 == {}".format(args.square, answer))
     else:
         print(answer)

这是它给我们的输出：

     $ python3 prog.py 4 -vvv
     the square of 4 equals 16
     $ python3 prog.py 4 -vvvv
     the square of 4 equals 16
     $ python3 prog.py 4
     Traceback (most recent call last):
       File "prog.py", line 11, in <module>
         if args.verbosity >= 2:
     TypeError: '>=' not supported between instances of 'NoneType' and 'int'

   * 第一组输出很好，修复了之前的 bug。也就是说，我们希望任何 >= 2 的值
     尽可能详尽。

   * 第三组输出并不理想。

让我们修复那个 bug：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("square", type=int,
                         help="display a square of a given number")
     parser.add_argument("-v", "--verbosity", action="count", default=0,
                         help="increase output verbosity")
     args = parser.parse_args()
     answer = args.square**2
     if args.verbosity >= 2:
         print("the square of {} equals {}".format(args.square, answer))
     elif args.verbosity >= 1:
         print("{}^2 == {}".format(args.square, answer))
     else:
         print(answer)

我们刚刚引入了又一个新的关键字 ‘default’。我们把它设置为 ‘0’ 来让它可以
与其他整数值相互比较。记住，默认情况下如果一个可选参数没有被指定，它的值
会是 ‘None’，并且它不能和整数值相比较（所以产生了 *note TypeError: 193.
异常）。

然后：

     $ python3 prog.py 4
     16

凭借我们目前已学的东西你就可以做到许多事情，而我们还仅仅学了一些皮毛而已
。 *note argparse: 6. 模块是非常强大的，在结束篇教程之前我们将再探索更多
一些内容。


File: python.info,  Node: 进行一些小小的改进,  Next: 后记,  Prev: 结合位置参数和可选参数,  Up: Argparse 教程

10.13.6 进行一些小小的改进
--------------------------

如果我们想扩展我们的简短程序来执行其他幂次的运算，而不仅是乘方:

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("x", type=int, help="the base")
     parser.add_argument("y", type=int, help="the exponent")
     parser.add_argument("-v", "--verbosity", action="count", default=0)
     args = parser.parse_args()
     answer = args.x**args.y
     if args.verbosity >= 2:
         print("{} to the power {} equals {}".format(args.x, args.y, answer))
     elif args.verbosity >= 1:
         print("{}^{} == {}".format(args.x, args.y, answer))
     else:
         print(answer)

输出：

     $ python3 prog.py
     usage: prog.py [-h] [-v] x y
     prog.py: error: the following arguments are required: x, y
     $ python3 prog.py -h
     usage: prog.py [-h] [-v] x y

     positional arguments:
       x                the base
       y                the exponent

     optional arguments:
       -h, --help       show this help message and exit
       -v, --verbosity
     $ python3 prog.py 4 2 -v
     4^2 == 16

请注意到目前为止我们一直在使用详细级别来 `更改' 所显示的文本。 以下示例
则使用详细级别来显示 `更多的' 文本:

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("x", type=int, help="the base")
     parser.add_argument("y", type=int, help="the exponent")
     parser.add_argument("-v", "--verbosity", action="count", default=0)
     args = parser.parse_args()
     answer = args.x**args.y
     if args.verbosity >= 2:
         print("Running '{}'".format(__file__))
     if args.verbosity >= 1:
         print("{}^{} == ".format(args.x, args.y), end="")
     print(answer)

输出：

     $ python3 prog.py 4 2
     16
     $ python3 prog.py 4 2 -v
     4^2 == 16
     $ python3 prog.py 4 2 -vv
     Running 'prog.py'
     4^2 == 16

* Menu:

* 矛盾的选项::


File: python.info,  Node: 矛盾的选项,  Up: 进行一些小小的改进

10.13.6.1 矛盾的选项
....................

到目前为止，我们一直在使用 *note argparse.ArgumentParser: 69e. 实例的两
个方法。 让我们再介绍第三个方法 ‘add_mutually_exclusive_group()’。 它允
许我们指定彼此相互冲突的选项。 让我们再更改程序的其余部分以便使用新功能
更有意义：我们将引入 ‘--quiet’ 选项，它将与 ‘--verbose’ 正好相反:

     import argparse

     parser = argparse.ArgumentParser()
     group = parser.add_mutually_exclusive_group()
     group.add_argument("-v", "--verbose", action="store_true")
     group.add_argument("-q", "--quiet", action="store_true")
     parser.add_argument("x", type=int, help="the base")
     parser.add_argument("y", type=int, help="the exponent")
     args = parser.parse_args()
     answer = args.x**args.y

     if args.quiet:
         print(answer)
     elif args.verbose:
         print("{} to the power {} equals {}".format(args.x, args.y, answer))
     else:
         print("{}^{} == {}".format(args.x, args.y, answer))

我们的程序现在变得更简洁了，我们出于演示需要略去了一些功能。 无论如何，
输出是这样的:

     $ python3 prog.py 4 2
     4^2 == 16
     $ python3 prog.py 4 2 -q
     16
     $ python3 prog.py 4 2 -v
     4 to the power 2 equals 16
     $ python3 prog.py 4 2 -vq
     usage: prog.py [-h] [-v | -q] x y
     prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
     $ python3 prog.py 4 2 -v --quiet
     usage: prog.py [-h] [-v | -q] x y
     prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose

这应该很容易理解。 我添加了末尾的输出这样你就可以看到其所达到的灵活性，
即混合使用长和短两种形式的选项。

在我们收尾之前，你也许希望告诉你的用户这个程序的主要目标，以免他们还不清
楚:

     import argparse

     parser = argparse.ArgumentParser(description="calculate X to the power of Y")
     group = parser.add_mutually_exclusive_group()
     group.add_argument("-v", "--verbose", action="store_true")
     group.add_argument("-q", "--quiet", action="store_true")
     parser.add_argument("x", type=int, help="the base")
     parser.add_argument("y", type=int, help="the exponent")
     args = parser.parse_args()
     answer = args.x**args.y

     if args.quiet:
         print(answer)
     elif args.verbose:
         print("{} to the power {} equals {}".format(args.x, args.y, answer))
     else:
         print("{}^{} == {}".format(args.x, args.y, answer))

请注意用法文本中有细微的差异。 注意 ‘[-v | -q]’，它的意思是说我们可以使
用 ‘-v’ 或 ‘-q’，但不能同时使用两者：

     $ python3 prog.py --help
     usage: prog.py [-h] [-v | -q] x y

     calculate X to the power of Y

     positional arguments:
       x              the base
       y              the exponent

     optional arguments:
       -h, --help     show this help message and exit
       -v, --verbose
       -q, --quiet


File: python.info,  Node: 后记,  Prev: 进行一些小小的改进,  Up: Argparse 教程

10.13.7 后记
------------

除了这里显示的内容，*note argparse: 6. 模块还提供了更多功能。 它的文档相
当详细和完整，包含大量示例。 完成这个教程之后，你应该能毫不困难地阅读该
文档。


File: python.info,  Node: ipaddress模块介绍,  Next: Argument Clinic How-To,  Prev: Argparse 教程,  Up: Python 常用指引

10.14 ipaddress模块介绍
=======================


作者: Peter Moody


作者: Nick Coghlan

概述
....

本文档旨在简要介绍 *note ipaddress: a3. 模块。 它主要针对那些不熟悉 IP 网
络术语的用户，但也可能对想要速览 *note ipaddress: a3. 如何代表IP网络寻址
概念的网络工程师有用。

* Menu:

* 创建 Address/Network/Interface 对象::
* 审查 Address/Network/Interface 对象::
* Network 作为 Address 列表::
* 比较运算: 比较运算<4>.
* 将IP地址与其他模块一起使用::
* 实例创建失败时获取更多详细信息::


File: python.info,  Node: 创建 Address/Network/Interface 对象,  Next: 审查 Address/Network/Interface 对象,  Up: ipaddress模块介绍

10.14.1 创建 Address/Network/Interface 对象
-------------------------------------------

因为 *note ipaddress: a3. 是一个用于检查和操作 IP 地址的模块，你要做的第
一件事就是创建一些对象。 您可以使用 *note ipaddress: a3. 从字符串和整数
创建对象。

* Menu:

* 关于IP版本的说明::
* IP主机地址::
* 定义网络::
* 主机接口::


File: python.info,  Node: 关于IP版本的说明,  Next: IP主机地址,  Up: 创建 Address/Network/Interface 对象

10.14.1.1 关于IP版本的说明
..........................

对于不太熟悉 IP 寻址的读者，重要的是要知道 Internet 协议当前正在从协议的
版本4转移到版本6。转换很大程度上是因为协议的版本4没有提供足够的地址来满
足整个世界的需求，特别是考虑到越来越多的设备直接连接到互联网。

解释协议的两个版本之间的差异的细节超出了本介绍的范围，但读者需要至少知道
存在这两个版本，并且有时需要强制使用一个版本或其他版本。


File: python.info,  Node: IP主机地址,  Next: 定义网络,  Prev: 关于IP版本的说明,  Up: 创建 Address/Network/Interface 对象

10.14.1.2 IP主机地址
....................

通常称为“主机地址”的地址是使用IP寻址时最基本的单元。 创建地址的最简单方
法是使用 *note ipaddress.ip_address(): 2f14. 工厂函数，该函数根据传入的
值自动确定是创建 IPv4 还是 IPv6 地址：

     >>> ipaddress.ip_address('192.0.2.1')
     IPv4Address('192.0.2.1')
     >>> ipaddress.ip_address('2001:DB8::1')
     IPv6Address('2001:db8::1')

地址也可以直接从整数创建，适配32位的值并假定为IPv4地址:

     >>> ipaddress.ip_address(3221225985)
     IPv4Address('192.0.2.1')
     >>> ipaddress.ip_address(42540766411282592856903984951653826561)
     IPv6Address('2001:db8::1')

要强制使用IPv4或IPv6地址，可以直接调用相关的类。 这对于强制为小整数创建
IPv6地址特别有用:

     >>> ipaddress.ip_address(1)
     IPv4Address('0.0.0.1')
     >>> ipaddress.IPv4Address(1)
     IPv4Address('0.0.0.1')
     >>> ipaddress.IPv6Address(1)
     IPv6Address('::1')


File: python.info,  Node: 定义网络,  Next: 主机接口,  Prev: IP主机地址,  Up: 创建 Address/Network/Interface 对象

10.14.1.3 定义网络
..................

主机地址通常组合在一起形成IP网络，因此 *note ipaddress: a3. 提供了一种创
建、检查和操作网络定义的方法。 IP网络对象由字符串构成，这些字符串定义作
为该网络一部分的主机地址范围。 该信息的最简单形式是“网络地址/网络前缀”对
，其中前缀定义了比较的前导比特数，以确定地址是否是网络的一部分，并且网络
地址定义了那些位的预期值。

对于地址，提供了一个自动确定正确IP版本的工厂函数:

     >>> ipaddress.ip_network('192.0.2.0/24')
     IPv4Network('192.0.2.0/24')
     >>> ipaddress.ip_network('2001:db8::0/96')
     IPv6Network('2001:db8::/96')

网络对象不能设置任何主机位。 这样做的实际效果是‘‘192.0.2.1/24‘‘没有描述
网络。 这种定义被称为接口对象，因为网络上IP表示法通常用于描述给定网络上
的计算机的网络接口，并在下一节中进一步描述。

默认情况下，尝试创建一个设置了主机位的网络对象将导致 *note ValueError:
1fc. 被引发。 要请求将附加位强制为零，可以将标志‘‘strict=False‘‘ 传递给
构造函数:

     >>> ipaddress.ip_network('192.0.2.1/24')
     Traceback (most recent call last):
        ...
     ValueError: 192.0.2.1/24 has host bits set
     >>> ipaddress.ip_network('192.0.2.1/24', strict=False)
     IPv4Network('192.0.2.0/24')

虽然字符串形式提供了更大的灵活性，但网络也可以用整数定义，就像主机地址一
样。 在这种情况下，网络被认为只包含由整数标识的单个地址，因此网络前缀包
括整个网络地址:

     >>> ipaddress.ip_network(3221225984)
     IPv4Network('192.0.2.0/32')
     >>> ipaddress.ip_network(42540766411282592856903984951653826560)
     IPv6Network('2001:db8::/128')

与地址一样，可以通过直接调用类构造函数而不是使用工厂函数来强制创建特定类
型的网络。


File: python.info,  Node: 主机接口,  Prev: 定义网络,  Up: 创建 Address/Network/Interface 对象

10.14.1.4 主机接口
..................

如上所述，如果您需要描述特定网络上的地址，则地址和网络类都不够。 像
‘192.0.2.1/24’ 这样的表示法通常被网络工程师和为防火墙和路由器编写工具的
人用作“ ‘192.0.2.0/24’ 网络上的主机 ‘192.0.2.1’ ”的简写。因此，*note
ipaddress: a3. 提供了一组将地址与特定网络相关联的混合类。用于创建的接口
与用于定义网络对象的接口相同，除了地址部分不限于是网络地址。

     >>> ipaddress.ip_interface('192.0.2.1/24')
     IPv4Interface('192.0.2.1/24')
     >>> ipaddress.ip_interface('2001:db8::1/96')
     IPv6Interface('2001:db8::1/96')

接受整数输入（与网络一样），并且可以通过直接调用相关构造函数来强制使用特
定IP版本。


File: python.info,  Node: 审查 Address/Network/Interface 对象,  Next: Network 作为 Address 列表,  Prev: 创建 Address/Network/Interface 对象,  Up: ipaddress模块介绍

10.14.2 审查 Address/Network/Interface 对象
-------------------------------------------

你已经遇到了创建IPv(4|6)(Address|Network|Interface) 对象的麻烦，因此你可
能希望获得有关它的信息。 *note ipaddress: a3. 试图让这个过程变得简单直观
。

提取 IP 版本:

     >>> addr4 = ipaddress.ip_address('192.0.2.1')
     >>> addr6 = ipaddress.ip_address('2001:db8::1')
     >>> addr6.version
     6
     >>> addr4.version
     4

从接口获取网络:

     >>> host4 = ipaddress.ip_interface('192.0.2.1/24')
     >>> host4.network
     IPv4Network('192.0.2.0/24')
     >>> host6 = ipaddress.ip_interface('2001:db8::1/96')
     >>> host6.network
     IPv6Network('2001:db8::/96')

找出网络中有多少独立地址:

     >>> net4 = ipaddress.ip_network('192.0.2.0/24')
     >>> net4.num_addresses
     256
     >>> net6 = ipaddress.ip_network('2001:db8::0/96')
     >>> net6.num_addresses
     4294967296

迭代网络上的“可用”地址:

     >>> net4 = ipaddress.ip_network('192.0.2.0/24')
     >>> for x in net4.hosts():
     ...     print(x)
     192.0.2.1
     192.0.2.2
     192.0.2.3
     192.0.2.4
     ...
     192.0.2.252
     192.0.2.253
     192.0.2.254

获取网络掩码（即对应于网络前缀的设置位）或主机掩码（不属于网络掩码的任何
位）：

     >>> net4 = ipaddress.ip_network('192.0.2.0/24')
     >>> net4.netmask
     IPv4Address('255.255.255.0')
     >>> net4.hostmask
     IPv4Address('0.0.0.255')
     >>> net6 = ipaddress.ip_network('2001:db8::0/96')
     >>> net6.netmask
     IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff::')
     >>> net6.hostmask
     IPv6Address('::ffff:ffff')

展开或压缩地址:

     >>> addr6.exploded
     '2001:0db8:0000:0000:0000:0000:0000:0001'
     >>> addr6.compressed
     '2001:db8::1'
     >>> net6.exploded
     '2001:0db8:0000:0000:0000:0000:0000:0000/96'
     >>> net6.compressed
     '2001:db8::/96'

虽然IPv4不支持展开或压缩，但关联对象仍提供相关属性，因此版本中性代码可以
轻松确保最简洁或最详细的形式用于IPv6地址，同时仍能正确处理IPv4地址。


File: python.info,  Node: Network 作为 Address 列表,  Next: 比较运算<4>,  Prev: 审查 Address/Network/Interface 对象,  Up: ipaddress模块介绍

10.14.3 Network 作为 Address 列表
---------------------------------

将网络视为列表有时很有用。 这意味着它可以像这样索引它们:

     >>> net4[1]
     IPv4Address('192.0.2.1')
     >>> net4[-1]
     IPv4Address('192.0.2.255')
     >>> net6[1]
     IPv6Address('2001:db8::1')
     >>> net6[-1]
     IPv6Address('2001:db8::ffff:ffff')

它还意味着网络对象可以使用像这样的列表成员测试语法:

     if address in network:
         # do something

根据网络前缀有效地完成包含性测试:

     >>> addr4 = ipaddress.ip_address('192.0.2.1')
     >>> addr4 in ipaddress.ip_network('192.0.2.0/24')
     True
     >>> addr4 in ipaddress.ip_network('192.0.3.0/24')
     False


File: python.info,  Node: 比较运算<4>,  Next: 将IP地址与其他模块一起使用,  Prev: Network 作为 Address 列表,  Up: ipaddress模块介绍

10.14.4 比较运算
----------------

*note ipaddress: a3. 有意义地提供了一些简单、希望直观的比较对象的方法:

     >>> ipaddress.ip_address('192.0.2.1') < ipaddress.ip_address('192.0.2.2')
     True

如果你尝试比较不同版本或不同类型的对象，则会引发 *note TypeError: 193. 异
常。


File: python.info,  Node: 将IP地址与其他模块一起使用,  Next: 实例创建失败时获取更多详细信息,  Prev: 比较运算<4>,  Up: ipaddress模块介绍

10.14.5 将IP地址与其他模块一起使用
----------------------------------

其他使用IP地址的模块（例如 *note socket: f0. ）通常不会直接接受来自该模
块的对象。 相反，它们必须被强制转换为另一个模块可接受的整数或字符串:

     >>> addr4 = ipaddress.ip_address('192.0.2.1')
     >>> str(addr4)
     '192.0.2.1'
     >>> int(addr4)
     3221225985


File: python.info,  Node: 实例创建失败时获取更多详细信息,  Prev: 将IP地址与其他模块一起使用,  Up: ipaddress模块介绍

10.14.6 实例创建失败时获取更多详细信息
--------------------------------------

使用与版本无关的工厂函数创建 address/network/interface 对象时，任何错误
都将报告为 *note ValueError: 1fc. ，带有一般错误消息，只是说传入的值未被
识别为该类型的对象。 缺少特定错误是因为有必要知道该值是*假设*是IPv4还是
IPv6，以便提供有关其被拒绝原因的更多详细信息。

为了支持访问这些额外细节的用例，各个类构造函数实际上引发了 *note
ValueError: 1fc. 子类 *note ipaddress.AddressValueError: 2f1d. 和 *note
ipaddress.NetmaskValueError: 2f42. 以准确指示定义的哪一部分无法正确解析
。

直接使用类构造函数时，错误消息更加详细。 例如:

     >>> ipaddress.ip_address("192.168.0.256")
     Traceback (most recent call last):
       ...
     ValueError: '192.168.0.256' does not appear to be an IPv4 or IPv6 address
     >>> ipaddress.IPv4Address("192.168.0.256")
     Traceback (most recent call last):
       ...
     ipaddress.AddressValueError: Octet 256 (> 255) not permitted in '192.168.0.256'

     >>> ipaddress.ip_network("192.168.0.1/64")
     Traceback (most recent call last):
       ...
     ValueError: '192.168.0.1/64' does not appear to be an IPv4 or IPv6 network
     >>> ipaddress.IPv4Network("192.168.0.1/64")
     Traceback (most recent call last):
       ...
     ipaddress.NetmaskValueError: '64' is not a valid netmask

但是，两个模块特定的异常都有 *note ValueError: 1fc. 作为它们的父类，所以
如果你不关心特定类型的错误，你仍然可以编写如下代码:

     try:
         network = ipaddress.IPv4Network(address)
     except ValueError:
         print('address/netmask is invalid for IPv4:', address)


File: python.info,  Node: Argument Clinic How-To,  Next: 使用 DTrace 和 SystemTap 检测CPython,  Prev: ipaddress模块介绍,  Up: Python 常用指引

10.15 Argument Clinic How-To
============================


作者: Larry Hastings

摘要
....

Argument Clinic is a preprocessor for CPython C files.  Its purpose is
to automate all the boilerplate involved with writing argument parsing
code for "builtins".  This document shows you how to convert your first
C function to work with Argument Clinic, and then introduces some
advanced topics on Argument Clinic usage.

Currently Argument Clinic is considered internal-only for CPython.  Its
use is not supported for files outside CPython, and no guarantees are
made regarding backwards compatibility for future versions.  In other
words: if you maintain an external C extension for CPython, you’re
welcome to experiment with Argument Clinic in your own code.  But the
version of Argument Clinic that ships with the next version of CPython
`could' be totally incompatible and break all your code.

* Menu:

* The Goals Of Argument Clinic::
* Basic Concepts And Usage::
* Converting Your First Function::
* Advanced Topics::


File: python.info,  Node: The Goals Of Argument Clinic,  Next: Basic Concepts And Usage,  Up: Argument Clinic How-To

10.15.1 The Goals Of Argument Clinic
------------------------------------

Argument Clinic’s primary goal is to take over responsibility for all
argument parsing code inside CPython.  This means that, when you convert
a function to work with Argument Clinic, that function should no longer
do any of its own argument parsing—the code generated by Argument Clinic
should be a "black box" to you, where CPython calls in at the top, and
your code gets called at the bottom, with ‘PyObject *args’ (and maybe
‘PyObject *kwargs’) magically converted into the C variables and types
you need.

In order for Argument Clinic to accomplish its primary goal, it must be
easy to use.  Currently, working with CPython’s argument parsing library
is a chore, requiring maintaining redundant information in a surprising
number of places.  When you use Argument Clinic, you don’t have to
repeat yourself.

Obviously, no one would want to use Argument Clinic unless it’s solving
their problem—and without creating new problems of its own.  So it’s
paramount that Argument Clinic generate correct code.  It’d be nice if
the code was faster, too, but at the very least it should not introduce
a major speed regression.  (Eventually Argument Clinic `should' make a
major speedup possible—we could rewrite its code generator to produce
tailor-made argument parsing code, rather than calling the
general-purpose CPython argument parsing library.  That would make for
the fastest argument parsing possible!)

Additionally, Argument Clinic must be flexible enough to work with any
approach to argument parsing.  Python has some functions with some very
strange parsing behaviors; Argument Clinic’s goal is to support all of
them.

Finally, the original motivation for Argument Clinic was to provide
introspection "signatures" for CPython builtins.  It used to be, the
introspection query functions would throw an exception if you passed in
a builtin.  With Argument Clinic, that’s a thing of the past!

One idea you should keep in mind, as you work with Argument Clinic: the
more information you give it, the better job it’ll be able to do.
Argument Clinic is admittedly relatively simple right now.  But as it
evolves it will get more sophisticated, and it should be able to do many
interesting and smart things with all the information you give it.


File: python.info,  Node: Basic Concepts And Usage,  Next: Converting Your First Function,  Prev: The Goals Of Argument Clinic,  Up: Argument Clinic How-To

10.15.2 Basic Concepts And Usage
--------------------------------

Argument Clinic ships with CPython; you’ll find it in
‘Tools/clinic/clinic.py’.  If you run that script, specifying a C file
as an argument:

     $ python3 Tools/clinic/clinic.py foo.c

Argument Clinic will scan over the file looking for lines that look
exactly like this:

     /*[clinic input]

When it finds one, it reads everything up to a line that looks exactly
like this:

     [clinic start generated code]*/

Everything in between these two lines is input for Argument Clinic.  All
of these lines, including the beginning and ending comment lines, are
collectively called an Argument Clinic "block".

When Argument Clinic parses one of these blocks, it generates output.
This output is rewritten into the C file immediately after the block,
followed by a comment containing a checksum.  The Argument Clinic block
now looks like this:

     /*[clinic input]
     ... clinic input goes here ...
     [clinic start generated code]*/
     ... clinic output goes here ...
     /*[clinic end generated code: checksum=...]*/

If you run Argument Clinic on the same file a second time, Argument
Clinic will discard the old output and write out the new output with a
fresh checksum line.  However, if the input hasn’t changed, the output
won’t change either.

You should never modify the output portion of an Argument Clinic block.
Instead, change the input until it produces the output you want.
(That’s the purpose of the checksum—to detect if someone changed the
output, as these edits would be lost the next time Argument Clinic
writes out fresh output.)

For the sake of clarity, here’s the terminology we’ll use with Argument
Clinic:

   * The first line of the comment (‘/*[clinic input]’) is the `start
     line'.

   * The last line of the initial comment (‘[clinic start generated
     code]*/’) is the `end line'.

   * The last line (‘/*[clinic end generated code: checksum=...]*/’) is
     the `checksum line'.

   * In between the start line and the end line is the `input'.

   * In between the end line and the checksum line is the `output'.

   * All the text collectively, from the start line to the checksum line
     inclusively, is the `block'.  (A block that hasn’t been
     successfully processed by Argument Clinic yet doesn’t have output
     or a checksum line, but it’s still considered a block.)


File: python.info,  Node: Converting Your First Function,  Next: Advanced Topics,  Prev: Basic Concepts And Usage,  Up: Argument Clinic How-To

10.15.3 Converting Your First Function
--------------------------------------

The best way to get a sense of how Argument Clinic works is to convert a
function to work with it.  Here, then, are the bare minimum steps you’d
need to follow to convert a function to work with Argument Clinic.  Note
that for code you plan to check in to CPython, you really should take
the conversion farther, using some of the advanced concepts you’ll see
later on in the document (like "return converters" and "self
converters").  But we’ll keep it simple for this walkthrough so you can
learn.

Let’s dive in!

  0. Make sure you’re working with a freshly updated checkout of the
     CPython trunk.

  1. Find a Python builtin that calls either *note PyArg_ParseTuple():
     26b. or *note PyArg_ParseTupleAndKeywords(): 5d3, and hasn’t been
     converted to work with Argument Clinic yet.  For my example I’m
     using ‘_pickle.Pickler.dump()’.

  2. If the call to the ‘PyArg_Parse’ function uses any of the following
     format units:

          O&
          O!
          es
          es#
          et
          et#

     or if it has multiple calls to *note PyArg_ParseTuple(): 26b, you
     should choose a different function.  Argument Clinic `does' support
     all of these scenarios.  But these are advanced topics—let’s do
     something simpler for your first function.

     Also, if the function has multiple calls to *note
     PyArg_ParseTuple(): 26b. or *note PyArg_ParseTupleAndKeywords():
     5d3. where it supports different types for the same argument, or if
     the function uses something besides PyArg_Parse functions to parse
     its arguments, it probably isn’t suitable for conversion to
     Argument Clinic.  Argument Clinic doesn’t support generic functions
     or polymorphic parameters.

  3. Add the following boilerplate above the function, creating our
     block:

          /*[clinic input]
          [clinic start generated code]*/

  4. Cut the docstring and paste it in between the ‘[clinic]’ lines,
     removing all the junk that makes it a properly quoted C string.
     When you’re done you should have just the text, based at the left
     margin, with no line wider than 80 characters.  (Argument Clinic
     will preserve indents inside the docstring.)

     If the old docstring had a first line that looked like a function
     signature, throw that line away.  (The docstring doesn’t need it
     anymore—when you use ‘help()’ on your builtin in the future, the
     first line will be built automatically based on the function’s
     signature.)

     Sample:

          /*[clinic input]
          Write a pickled representation of obj to the open file.
          [clinic start generated code]*/

  5. If your docstring doesn’t have a "summary" line, Argument Clinic
     will complain.  So let’s make sure it has one.  The "summary" line
     should be a paragraph consisting of a single 80-column line at the
     beginning of the docstring.

     (Our example docstring consists solely of a summary line, so the
     sample code doesn’t have to change for this step.)

  6. Above the docstring, enter the name of the function, followed by a
     blank line.  This should be the Python name of the function, and
     should be the full dotted path to the function—it should start with
     the name of the module, include any sub-modules, and if the
     function is a method on a class it should include the class name
     too.

     Sample:

          /*[clinic input]
          _pickle.Pickler.dump

          Write a pickled representation of obj to the open file.
          [clinic start generated code]*/

  7. If this is the first time that module or class has been used with
     Argument Clinic in this C file, you must declare the module and/or
     class.  Proper Argument Clinic hygiene prefers declaring these in a
     separate block somewhere near the top of the C file, in the same
     way that include files and statics go at the top.  (In our sample
     code we’ll just show the two blocks next to each other.)

     The name of the class and module should be the same as the one seen
     by Python.  Check the name defined in the *note PyModuleDef: 3b4b.
     or *note PyTypeObject: 2d7. as appropriate.

     When you declare a class, you must also specify two aspects of its
     type in C: the type declaration you’d use for a pointer to an
     instance of this class, and a pointer to the *note PyTypeObject:
     2d7. for this class.

     Sample:

          /*[clinic input]
          module _pickle
          class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
          [clinic start generated code]*/

          /*[clinic input]
          _pickle.Pickler.dump

          Write a pickled representation of obj to the open file.
          [clinic start generated code]*/

  8. Declare each of the parameters to the function.  Each parameter
     should get its own line.  All the parameter lines should be
     indented from the function name and the docstring.

     The general form of these parameter lines is as follows:

          name_of_parameter: converter

     If the parameter has a default value, add that after the converter:

          name_of_parameter: converter = default_value

     Argument Clinic’s support for "default values" is quite
     sophisticated; please see *note the section below on default
     values: 420c. for more information.

     Add a blank line below the parameters.

     What’s a "converter"?  It establishes both the type of the variable
     used in C, and the method to convert the Python value into a C
     value at runtime.  For now you’re going to use what’s called a
     "legacy converter"—a convenience syntax intended to make porting
     old code into Argument Clinic easier.

     For each parameter, copy the "format unit" for that parameter from
     the ‘PyArg_Parse()’ format argument and specify `that' as its
     converter, as a quoted string.  ("format unit" is the formal name
     for the one-to-three character substring of the ‘format’ parameter
     that tells the argument parsing function what the type of the
     variable is and how to convert it.  For more on format units please
     see *note 解析参数并构建值变量: 2d1.)

     For multicharacter format units like ‘z#’, use the entire
     two-or-three character string.

     Sample:

           /*[clinic input]
           module _pickle
           class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
           [clinic start generated code]*/

           /*[clinic input]
           _pickle.Pickler.dump

              obj: 'O'

          Write a pickled representation of obj to the open file.
          [clinic start generated code]*/

  9. If your function has ‘|’ in the format string, meaning some
     parameters have default values, you can ignore it.  Argument Clinic
     infers which parameters are optional based on whether or not they
     have default values.

     If your function has ‘$’ in the format string, meaning it takes
     keyword-only arguments, specify ‘*’ on a line by itself before the
     first keyword-only argument, indented the same as the parameter
     lines.

     (‘_pickle.Pickler.dump’ has neither, so our sample is unchanged.)

  10. If the existing C function calls *note PyArg_ParseTuple(): 26b.
     (as opposed to *note PyArg_ParseTupleAndKeywords(): 5d3.), then all
     its arguments are positional-only.

     To mark all parameters as positional-only in Argument Clinic, add a
     ‘/’ on a line by itself after the last parameter, indented the same
     as the parameter lines.

     Currently this is all-or-nothing; either all parameters are
     positional-only, or none of them are.  (In the future Argument
     Clinic may relax this restriction.)

     Sample:

          /*[clinic input]
          module _pickle
          class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
          [clinic start generated code]*/

          /*[clinic input]
          _pickle.Pickler.dump

              obj: 'O'
              /

          Write a pickled representation of obj to the open file.
          [clinic start generated code]*/

  11. It’s helpful to write a per-parameter docstring for each
     parameter.  But per-parameter docstrings are optional; you can skip
     this step if you prefer.

     Here’s how to add a per-parameter docstring.  The first line of the
     per-parameter docstring must be indented further than the parameter
     definition.  The left margin of this first line establishes the
     left margin for the whole per-parameter docstring; all the text you
     write will be outdented by this amount.  You can write as much text
     as you like, across multiple lines if you wish.

     Sample:

          /*[clinic input]
          module _pickle
          class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
          [clinic start generated code]*/

          /*[clinic input]
          _pickle.Pickler.dump

              obj: 'O'
                  The object to be pickled.
              /

          Write a pickled representation of obj to the open file.
          [clinic start generated code]*/

  12. Save and close the file, then run ‘Tools/clinic/clinic.py’ on it.
     With luck everything worked—your block now has output, and a ‘.c.h’
     file has been generated!  Reopen the file in your text editor to
     see:

          /*[clinic input]
          _pickle.Pickler.dump

              obj: 'O'
                  The object to be pickled.
              /

          Write a pickled representation of obj to the open file.
          [clinic start generated code]*/

          static PyObject *
          _pickle_Pickler_dump(PicklerObject *self, PyObject *obj)
          /*[clinic end generated code: output=87ecad1261e02ac7 input=552eb1c0f52260d9]*/

     Obviously, if Argument Clinic didn’t produce any output, it’s
     because it found an error in your input.  Keep fixing your errors
     and retrying until Argument Clinic processes your file without
     complaint.

     For readability, most of the glue code has been generated to a
     ‘.c.h’ file.  You’ll need to include that in your original ‘.c’
     file, typically right after the clinic module block:

          #include "clinic/_pickle.c.h"

  13. Double-check that the argument-parsing code Argument Clinic
     generated looks basically the same as the existing code.

     First, ensure both places use the same argument-parsing function.
     The existing code must call either *note PyArg_ParseTuple(): 26b.
     or *note PyArg_ParseTupleAndKeywords(): 5d3.; ensure that the code
     generated by Argument Clinic calls the `exact' same function.

     Second, the format string passed in to *note PyArg_ParseTuple():
     26b. or *note PyArg_ParseTupleAndKeywords(): 5d3. should be
     `exactly' the same as the hand-written one in the existing
     function, up to the colon or semi-colon.

     (Argument Clinic always generates its format strings with a ‘:’
     followed by the name of the function.  If the existing code’s
     format string ends with ‘;’, to provide usage help, this change is
     harmless—don’t worry about it.)

     Third, for parameters whose format units require two arguments
     (like a length variable, or an encoding string, or a pointer to a
     conversion function), ensure that the second argument is `exactly'
     the same between the two invocations.

     Fourth, inside the output portion of the block you’ll find a
     preprocessor macro defining the appropriate static *note
     PyMethodDef: e23. structure for this builtin:

          #define __PICKLE_PICKLER_DUMP_METHODDEF    \
          {"dump", (PyCFunction)__pickle_Pickler_dump, METH_O, __pickle_Pickler_dump__doc__},

     This static structure should be `exactly' the same as the existing
     static *note PyMethodDef: e23. structure for this builtin.

     If any of these items differ in `any way', adjust your Argument
     Clinic function specification and rerun ‘Tools/clinic/clinic.py’
     until they `are' the same.

  14. Notice that the last line of its output is the declaration of your
     "impl" function.  This is where the builtin’s implementation goes.
     Delete the existing prototype of the function you’re modifying, but
     leave the opening curly brace.  Now delete its argument parsing
     code and the declarations of all the variables it dumps the
     arguments into.  Notice how the Python arguments are now arguments
     to this impl function; if the implementation used different names
     for these variables, fix it.

     Let’s reiterate, just because it’s kind of weird.  Your code should
     now look like this:

          static return_type
          your_function_impl(...)
          /*[clinic end generated code: checksum=...]*/
          {
          ...

     Argument Clinic generated the checksum line and the function
     prototype just above it.  You should write the opening (and
     closing) curly braces for the function, and the implementation
     inside.

     Sample:

          /*[clinic input]
          module _pickle
          class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
          [clinic start generated code]*/
          /*[clinic end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/

          /*[clinic input]
          _pickle.Pickler.dump

              obj: 'O'
                  The object to be pickled.
              /

          Write a pickled representation of obj to the open file.
          [clinic start generated code]*/

          PyDoc_STRVAR(__pickle_Pickler_dump__doc__,
          "Write a pickled representation of obj to the open file.\n"
          "\n"
          ...
          static PyObject *
          _pickle_Pickler_dump_impl(PicklerObject *self, PyObject *obj)
          /*[clinic end generated code: checksum=3bd30745bf206a48f8b576a1da3d90f55a0a4187]*/
          {
              /* Check whether the Pickler was initialized correctly (issue3664).
                 Developers often forget to call __init__() in their subclasses, which
                 would trigger a segfault without this check. */
              if (self->write == NULL) {
                  PyErr_Format(PicklingError,
                               "Pickler.__init__() was not called by %s.__init__()",
                               Py_TYPE(self)->tp_name);
                  return NULL;
              }

              if (_Pickler_ClearBuffer(self) < 0)
                  return NULL;

              ...

  15. Remember the macro with the *note PyMethodDef: e23. structure for
     this function?  Find the existing *note PyMethodDef: e23. structure
     for this function and replace it with a reference to the macro.
     (If the builtin is at module scope, this will probably be very near
     the end of the file; if the builtin is a class method, this will
     probably be below but relatively near to the implementation.)

     Note that the body of the macro contains a trailing comma.  So when
     you replace the existing static *note PyMethodDef: e23. structure
     with the macro, `don’t' add a comma to the end.

     Sample:

          static struct PyMethodDef Pickler_methods[] = {
              __PICKLE_PICKLER_DUMP_METHODDEF
              __PICKLE_PICKLER_CLEAR_MEMO_METHODDEF
              {NULL, NULL}                /* sentinel */
          };

  16. Compile, then run the relevant portions of the regression-test
     suite.  This change should not introduce any new compile-time
     warnings or errors, and there should be no externally-visible
     change to Python’s behavior.

     Well, except for one difference: ‘inspect.signature()’ run on your
     function should now provide a valid signature!

     Congratulations, you’ve ported your first function to work with
     Argument Clinic!


File: python.info,  Node: Advanced Topics,  Prev: Converting Your First Function,  Up: Argument Clinic How-To

10.15.4 Advanced Topics
-----------------------

Now that you’ve had some experience working with Argument Clinic, it’s
time for some advanced topics.

* Menu:

* Symbolic default values::
* Renaming the C functions and variables generated by Argument Clinic::
* Converting functions using PyArg_UnpackTuple::
* Optional Groups::
* Using real Argument Clinic converters, instead of "legacy converters": Using real Argument Clinic converters instead of "legacy converters".
* Py_buffer::
* Advanced converters::
* Parameter default values::
* The NULL default value::
* Expressions specified as default values::
* Using a return converter::
* Cloning existing functions::
* Calling Python code::
* Using a "self converter"::
* Writing a custom converter::
* Writing a custom return converter::
* METH_O and METH_NOARGS::
* tp_new and tp_init functions::
* Changing and redirecting Clinic's output::
* The #ifdef trick::
* Using Argument Clinic in Python files::


File: python.info,  Node: Symbolic default values,  Next: Renaming the C functions and variables generated by Argument Clinic,  Up: Advanced Topics

10.15.4.1 Symbolic default values
.................................

The default value you provide for a parameter can’t be any arbitrary
expression.  Currently the following are explicitly supported:

   * Numeric constants (integer and float)

   * 字符串常量

   * ‘True’, ‘False’, and ‘None’

   * Simple symbolic constants like ‘sys.maxsize’, which must start with
     the name of the module

In case you’re curious, this is implemented in ‘from_builtin()’ in
‘Lib/inspect.py’.

(In the future, this may need to get even more elaborate, to allow full
expressions like ‘CONSTANT - 1’.)


File: python.info,  Node: Renaming the C functions and variables generated by Argument Clinic,  Next: Converting functions using PyArg_UnpackTuple,  Prev: Symbolic default values,  Up: Advanced Topics

10.15.4.2 Renaming the C functions and variables generated by Argument Clinic
.............................................................................

Argument Clinic automatically names the functions it generates for you.
Occasionally this may cause a problem, if the generated name collides
with the name of an existing C function.  There’s an easy solution:
override the names used for the C functions.  Just add the keyword
‘"as"’ to your function declaration line, followed by the function name
you wish to use.  Argument Clinic will use that function name for the
base (generated) function, then add ‘"_impl"’ to the end and use that
for the name of the impl function.

For example, if we wanted to rename the C function names generated for
‘pickle.Pickler.dump’, it’d look like this:

     /*[clinic input]
     pickle.Pickler.dump as pickler_dumper

     ...

The base function would now be named ‘pickler_dumper()’, and the impl
function would now be named ‘pickler_dumper_impl()’.

Similarly, you may have a problem where you want to give a parameter a
specific Python name, but that name may be inconvenient in C. Argument
Clinic allows you to give a parameter different names in Python and in
C, using the same ‘"as"’ syntax:

     /*[clinic input]
     pickle.Pickler.dump

         obj: object
         file as file_obj: object
         protocol: object = NULL
         *
         fix_imports: bool = True

Here, the name used in Python (in the signature and the ‘keywords’
array) would be ‘file’, but the C variable would be named ‘file_obj’.

You can use this to rename the ‘self’ parameter too!


File: python.info,  Node: Converting functions using PyArg_UnpackTuple,  Next: Optional Groups,  Prev: Renaming the C functions and variables generated by Argument Clinic,  Up: Advanced Topics

10.15.4.3 Converting functions using PyArg_UnpackTuple
......................................................

To convert a function parsing its arguments with *note
PyArg_UnpackTuple(): e4e, simply write out all the arguments, specifying
each as an ‘object’.  You may specify the ‘type’ argument to cast the
type as appropriate.  All arguments should be marked positional-only
(add a ‘/’ on a line by itself after the last argument).

Currently the generated code will use *note PyArg_ParseTuple(): 26b, but
this will change soon.


File: python.info,  Node: Optional Groups,  Next: Using real Argument Clinic converters instead of "legacy converters",  Prev: Converting functions using PyArg_UnpackTuple,  Up: Advanced Topics

10.15.4.4 Optional Groups
.........................

Some legacy functions have a tricky approach to parsing their arguments:
they count the number of positional arguments, then use a ‘switch’
statement to call one of several different *note PyArg_ParseTuple():
26b. calls depending on how many positional arguments there are.  (These
functions cannot accept keyword-only arguments.)  This approach was used
to simulate optional arguments back before *note
PyArg_ParseTupleAndKeywords(): 5d3. was created.

While functions using this approach can often be converted to use *note
PyArg_ParseTupleAndKeywords(): 5d3, optional arguments, and default
values, it’s not always possible.  Some of these legacy functions have
behaviors *note PyArg_ParseTupleAndKeywords(): 5d3. doesn’t directly
support.  The most obvious example is the builtin function ‘range()’,
which has an optional argument on the `left' side of its required
argument!  Another example is ‘curses.window.addch()’, which has a group
of two arguments that must always be specified together.  (The arguments
are called ‘x’ and ‘y’; if you call the function passing in ‘x’, you
must also pass in ‘y’—and if you don’t pass in ‘x’ you may not pass in
‘y’ either.)

In any case, the goal of Argument Clinic is to support argument parsing
for all existing CPython builtins without changing their semantics.
Therefore Argument Clinic supports this alternate approach to parsing,
using what are called `optional groups'.  Optional groups are groups of
arguments that must all be passed in together.  They can be to the left
or the right of the required arguments.  They can `only' be used with
positional-only parameters.

     注解: Optional groups are `only' intended for use when converting
     functions that make multiple calls to *note PyArg_ParseTuple():
     26b.!  Functions that use `any' other approach for parsing
     arguments should `almost never' be converted to Argument Clinic
     using optional groups.  Functions using optional groups currently
     cannot have accurate signatures in Python, because Python just
     doesn’t understand the concept.  Please avoid using optional groups
     wherever possible.

To specify an optional group, add a ‘[’ on a line by itself before the
parameters you wish to group together, and a ‘]’ on a line by itself
after these parameters.  As an example, here’s how ‘curses.window.addch’
uses optional groups to make the first two parameters and the last
parameter optional:

     /*[clinic input]

     curses.window.addch

         [
         x: int
           X-coordinate.
         y: int
           Y-coordinate.
         ]

         ch: object
           Character to add.

         [
         attr: long
           Attributes for the character.
         ]
         /

     ...

注释:

   * For every optional group, one additional parameter will be passed
     into the impl function representing the group.  The parameter will
     be an int named ‘group_{direction}_{number}’, where ‘{direction}’
     is either ‘right’ or ‘left’ depending on whether the group is
     before or after the required parameters, and ‘{number}’ is a
     monotonically increasing number (starting at 1) indicating how far
     away the group is from the required parameters.  When the impl is
     called, this parameter will be set to zero if this group was
     unused, and set to non-zero if this group was used.  (By used or
     unused, I mean whether or not the parameters received arguments in
     this invocation.)

   * If there are no required arguments, the optional groups will behave
     as if they’re to the right of the required arguments.

   * In the case of ambiguity, the argument parsing code favors
     parameters on the left (before the required parameters).

   * Optional groups can only contain positional-only parameters.

   * Optional groups are `only' intended for legacy code.  Please do not
     use optional groups for new code.


File: python.info,  Node: Using real Argument Clinic converters instead of "legacy converters",  Next: Py_buffer,  Prev: Optional Groups,  Up: Advanced Topics

10.15.4.5 Using real Argument Clinic converters, instead of "legacy converters"
...............................................................................

To save time, and to minimize how much you need to learn to achieve your
first port to Argument Clinic, the walkthrough above tells you to use
"legacy converters".  "Legacy converters" are a convenience, designed
explicitly to make porting existing code to Argument Clinic easier.  And
to be clear, their use is acceptable when porting code for Python 3.4.

However, in the long term we probably want all our blocks to use
Argument Clinic’s real syntax for converters.  Why?  A couple reasons:

   * The proper converters are far easier to read and clearer in their
     intent.

   * There are some format units that are unsupported as "legacy
     converters", because they require arguments, and the legacy
     converter syntax doesn’t support specifying arguments.

   * In the future we may have a new argument parsing library that isn’t
     restricted to what *note PyArg_ParseTuple(): 26b. supports; this
     flexibility won’t be available to parameters using legacy
     converters.

Therefore, if you don’t mind a little extra effort, please use the
normal converters instead of legacy converters.

In a nutshell, the syntax for Argument Clinic (non-legacy) converters
looks like a Python function call.  However, if there are no explicit
arguments to the function (all functions take their default values), you
may omit the parentheses.  Thus ‘bool’ and ‘bool()’ are exactly the same
converters.

All arguments to Argument Clinic converters are keyword-only.  All
Argument Clinic converters accept the following arguments:

     ‘c_default’

          The default value for this parameter when defined in C.
          Specifically, this will be the initializer for the variable
          declared in the "parse function".  See *note the section on
          default values: 420c. for how to use this.  Specified as a
          string.

     ‘annotation’

          The annotation value for this parameter.  Not currently
          supported, because PEP 8(1) mandates that the Python library
          may not use annotations.

In addition, some converters accept additional arguments.  Here is a
list of these arguments, along with their meanings:

     ‘accept’

          A set of Python types (and possibly pseudo-types); this
          restricts the allowable Python argument to values of these
          types.  (This is not a general-purpose facility; as a rule it
          only supports specific lists of types as shown in the legacy
          converter table.)

          To accept ‘None’, add ‘NoneType’ to this set.

     ‘bitwise’

          Only supported for unsigned integers.  The native integer
          value of this Python argument will be written to the parameter
          without any range checking, even for negative values.

     ‘converter’

          Only supported by the ‘object’ converter.  Specifies the name
          of a *note C "converter function": 3c83. to use to convert
          this object to a native type.

     ‘encoding’

          Only supported for strings.  Specifies the encoding to use
          when converting this string from a Python str (Unicode) value
          into a C ‘char *’ value.

     ‘subclass_of’

          Only supported for the ‘object’ converter.  Requires that the
          Python value be a subclass of a Python type, as expressed in
          C.

     ‘type’

          Only supported for the ‘object’ and ‘self’ converters.
          Specifies the C type that will be used to declare the
          variable.  Default value is ‘"PyObject *"’.

     ‘zeroes’

          Only supported for strings.  If true, embedded NUL bytes
          (‘'\\0'’) are permitted inside the value.  The length of the
          string will be passed in to the impl function, just after the
          string parameter, as a parameter named
          ‘<parameter_name>_length’.

Please note, not every possible combination of arguments will work.
Usually these arguments are implemented by specific ‘PyArg_ParseTuple’
`format units', with specific behavior.  For example, currently you
cannot call ‘unsigned_short’ without also specifying ‘bitwise=True’.
Although it’s perfectly reasonable to think this would work, these
semantics don’t map to any existing format unit.  So Argument Clinic
doesn’t support it.  (Or, at least, not yet.)

下表显示了传统转换器映射到实参转换器的情况。左边是传统转换器，右边是要替
换它的文本。

‘'B'’         ‘unsigned_char(bitwise=True)’
              
              
‘'b'’         ‘unsigned_char’
              
              
‘'c'’         ‘char’
              
              
‘'C'’         ‘int(accept={str})’
              
              
‘'d'’         ‘double’
              
              
‘'D'’         ‘Py_complex’
              
              
‘'es'’        ‘str(encoding='name_of_encoding')’
              
              
‘'es#'’       ‘str(encoding='name_of_encoding', zeroes=True)’
              
              
‘'et'’        ‘str(encoding='name_of_encoding', accept={bytes, bytearray, str})’
              
              
‘'et#'’       ‘str(encoding='name_of_encoding', accept={bytes, bytearray, str}, zeroes=True)’
              
              
‘'f'’         ‘float’
              
              
‘'h'’         ‘short’
              
              
‘'H'’         ‘unsigned_short(bitwise=True)’
              
              
‘'i'’         ‘int’
              
              
‘'I'’         ‘unsigned_int(bitwise=True)’
              
              
‘'k'’         ‘unsigned_long(bitwise=True)’
              
              
‘'K'’         ‘unsigned_long_long(bitwise=True)’
              
              
‘'l'’         ‘long’
              
              
‘'L'’         ‘long long’
              
              
‘'n'’         ‘Py_ssize_t’
              
              
‘'O'’         ‘object’
              
              
‘'O!'’        ‘object(subclass_of='&PySomething_Type')’
              
              
‘'O&'’        ‘object(converter='name_of_c_function')’
              
              
‘'p'’         ‘bool’
              
              
‘'S'’         ‘PyBytesObject’
              
              
‘'s'’         ‘str’
              
              
‘'s#'’        ‘str(zeroes=True)’
              
              
‘'s*'’        ‘Py_buffer(accept={buffer, str})’
              
              
‘'U'’         ‘unicode’
              
              
‘'u'’         ‘Py_UNICODE’
              
              
‘'u#'’        ‘Py_UNICODE(zeroes=True)’
              
              
‘'w*'’        ‘Py_buffer(accept={rwbuffer})’
              
              
‘'Y'’         ‘PyByteArrayObject’
              
              
‘'y'’         ‘str(accept={bytes})’
              
              
‘'y#'’        ‘str(accept={robuffer}, zeroes=True)’
              
              
‘'y*'’        ‘Py_buffer’
              
              
‘'Z'’         ‘Py_UNICODE(accept={str, NoneType})’
              
              
‘'Z#'’        ‘Py_UNICODE(accept={str, NoneType}, zeroes=True)’
              
              
‘'z'’         ‘str(accept={str, NoneType})’
              
              
‘'z#'’        ‘str(accept={str, NoneType}, zeroes=True)’
              
              
‘'z*'’        ‘Py_buffer(accept={buffer, str, NoneType})’
              

As an example, here’s our sample ‘pickle.Pickler.dump’ using the proper
converter:

     /*[clinic input]
     pickle.Pickler.dump

         obj: object
             The object to be pickled.
         /

     Write a pickled representation of obj to the open file.
     [clinic start generated code]*/

One advantage of real converters is that they’re more flexible than
legacy converters.  For example, the ‘unsigned_int’ converter (and all
the ‘unsigned_’ converters) can be specified without ‘bitwise=True’.
Their default behavior performs range checking on the value, and they
won’t accept negative numbers.  You just can’t do that with a legacy
converter!

Argument Clinic will show you all the converters it has available.  For
each converter it’ll show you all the parameters it accepts, along with
the default value for each parameter.  Just run ‘Tools/clinic/clinic.py
--converters’ to see the full list.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0008


File: python.info,  Node: Py_buffer,  Next: Advanced converters,  Prev: Using real Argument Clinic converters instead of "legacy converters",  Up: Advanced Topics

10.15.4.6 Py_buffer
...................

When using the ‘Py_buffer’ converter (or the ‘'s*'’, ‘'w*'’, ‘'*y'’, or
‘'z*'’ legacy converters), you `must' not call *note PyBuffer_Release():
d5c. on the provided buffer.  Argument Clinic generates code that does
it for you (in the parsing function).


File: python.info,  Node: Advanced converters,  Next: Parameter default values,  Prev: Py_buffer,  Up: Advanced Topics

10.15.4.7 Advanced converters
.............................

Remember those format units you skipped for your first time because they
were advanced?  Here’s how to handle those too.

The trick is, all those format units take arguments—either conversion
functions, or types, or strings specifying an encoding.  (But "legacy
converters" don’t support arguments.  That’s why we skipped them for
your first function.)  The argument you specified to the format unit is
now an argument to the converter; this argument is either ‘converter’
(for ‘O&’), ‘subclass_of’ (for ‘O!’), or ‘encoding’ (for all the format
units that start with ‘e’).

When using ‘subclass_of’, you may also want to use the other custom
argument for ‘object()’: ‘type’, which lets you set the type actually
used for the parameter.  For example, if you want to ensure that the
object is a subclass of ‘PyUnicode_Type’, you probably want to use the
converter ‘object(type='PyUnicodeObject *',
subclass_of='&PyUnicode_Type')’.

One possible problem with using Argument Clinic: it takes away some
possible flexibility for the format units starting with ‘e’.  When
writing a ‘PyArg_Parse’ call by hand, you could theoretically decide at
runtime what encoding string to pass in to *note PyArg_ParseTuple():
26b.  But now this string must be hard-coded at
Argument-Clinic-preprocessing-time.  This limitation is deliberate; it
made supporting this format unit much easier, and may allow for future
optimizations.  This restriction doesn’t seem unreasonable; CPython
itself always passes in static hard-coded encoding strings for
parameters whose format units start with ‘e’.


File: python.info,  Node: Parameter default values,  Next: The NULL default value,  Prev: Advanced converters,  Up: Advanced Topics

10.15.4.8 Parameter default values
..................................

Default values for parameters can be any of a number of values.  At
their simplest, they can be string, int, or float literals:

     foo: str = "abc"
     bar: int = 123
     bat: float = 45.6

They can also use any of Python’s built-in constants:

     yep:  bool = True
     nope: bool = False
     nada: object = None

There’s also special support for a default value of ‘NULL’, and for
simple expressions, documented in the following sections.


File: python.info,  Node: The NULL default value,  Next: Expressions specified as default values,  Prev: Parameter default values,  Up: Advanced Topics

10.15.4.9 The ‘NULL’ default value
..................................

For string and object parameters, you can set them to ‘None’ to indicate
that there’s no default.  However, that means the C variable will be
initialized to ‘Py_None’.  For convenience’s sakes, there’s a special
value called ‘NULL’ for just this reason: from Python’s perspective it
behaves like a default value of ‘None’, but the C variable is
initialized with ‘NULL’.


File: python.info,  Node: Expressions specified as default values,  Next: Using a return converter,  Prev: The NULL default value,  Up: Advanced Topics

10.15.4.10 Expressions specified as default values
..................................................

The default value for a parameter can be more than just a literal value.
It can be an entire expression, using math operators and looking up
attributes on objects.  However, this support isn’t exactly simple,
because of some non-obvious semantics.

Consider the following example:

     foo: Py_ssize_t = sys.maxsize - 1

‘sys.maxsize’ can have different values on different platforms.
Therefore Argument Clinic can’t simply evaluate that expression locally
and hard-code it in C. So it stores the default in such a way that it
will get evaluated at runtime, when the user asks for the function’s
signature.

What namespace is available when the expression is evaluated?  It’s
evaluated in the context of the module the builtin came from.  So, if
your module has an attribute called "‘max_widgets’", you may simply use
it:

     foo: Py_ssize_t = max_widgets

If the symbol isn’t found in the current module, it fails over to
looking in ‘sys.modules’.  That’s how it can find ‘sys.maxsize’ for
example.  (Since you don’t know in advance what modules the user will
load into their interpreter, it’s best to restrict yourself to modules
that are preloaded by Python itself.)

Evaluating default values only at runtime means Argument Clinic can’t
compute the correct equivalent C default value.  So you need to tell it
explicitly.  When you use an expression, you must also specify the
equivalent expression in C, using the ‘c_default’ parameter to the
converter:

     foo: Py_ssize_t(c_default="PY_SSIZE_T_MAX - 1") = sys.maxsize - 1

Another complication: Argument Clinic can’t know in advance whether or
not the expression you supply is valid.  It parses it to make sure it
looks legal, but it can’t `actually' know.  You must be very careful
when using expressions to specify values that are guaranteed to be valid
at runtime!

Finally, because expressions must be representable as static C values,
there are many restrictions on legal expressions.  Here’s a list of
Python features you’re not permitted to use:

   * Function calls.

   * Inline if statements (‘3 if foo else 5’).

   * Automatic sequence unpacking (‘*[1, 2, 3]’).

   * List/set/dict comprehensions and generator expressions.

   * Tuple/list/set/dict literals.


File: python.info,  Node: Using a return converter,  Next: Cloning existing functions,  Prev: Expressions specified as default values,  Up: Advanced Topics

10.15.4.11 Using a return converter
...................................

By default the impl function Argument Clinic generates for you returns
‘PyObject *’.  But your C function often computes some C type, then
converts it into the ‘PyObject *’ at the last moment.  Argument Clinic
handles converting your inputs from Python types into native C types—why
not have it convert your return value from a native C type into a Python
type too?

That’s what a "return converter" does.  It changes your impl function to
return some C type, then adds code to the generated (non-impl) function
to handle converting that value into the appropriate ‘PyObject *’.

The syntax for return converters is similar to that of parameter
converters.  You specify the return converter like it was a return
annotation on the function itself.  Return converters behave much the
same as parameter converters; they take arguments, the arguments are all
keyword-only, and if you’re not changing any of the default arguments
you can omit the parentheses.

(If you use both ‘"as"’ `and' a return converter for your function, the
‘"as"’ should come before the return converter.)

There’s one additional complication when using return converters: how do
you indicate an error has occurred?  Normally, a function returns a
valid (non-‘NULL’) pointer for success, and ‘NULL’ for failure.  But if
you use an integer return converter, all integers are valid.  How can
Argument Clinic detect an error?  Its solution: each return converter
implicitly looks for a special value that indicates an error.  If you
return that value, and an error has been set (‘PyErr_Occurred()’ returns
a true value), then the generated code will propagate the error.
Otherwise it will encode the value you return like normal.

Currently Argument Clinic supports only a few return converters:

     bool
     int
     unsigned int
     long
     unsigned int
     size_t
     Py_ssize_t
     float
     double
     DecodeFSDefault

None of these take parameters.  For the first three, return -1 to
indicate error.  For ‘DecodeFSDefault’, the return type is ‘const char
*’; return a ‘NULL’ pointer to indicate an error.

(There’s also an experimental ‘NoneType’ converter, which lets you
return ‘Py_None’ on success or ‘NULL’ on failure, without having to
increment the reference count on ‘Py_None’.  I’m not sure it adds enough
clarity to be worth using.)

To see all the return converters Argument Clinic supports, along with
their parameters (if any), just run ‘Tools/clinic/clinic.py
--converters’ for the full list.


File: python.info,  Node: Cloning existing functions,  Next: Calling Python code,  Prev: Using a return converter,  Up: Advanced Topics

10.15.4.12 Cloning existing functions
.....................................

If you have a number of functions that look similar, you may be able to
use Clinic’s "clone" feature.  When you clone an existing function, you
reuse:

   * its parameters, including

        * their names,

        * their converters, with all parameters,

        * their default values,

        * their per-parameter docstrings,

        * their `kind' (whether they’re positional only, positional or
          keyword, or keyword only), and

   * its return converter.

The only thing not copied from the original function is its docstring;
the syntax allows you to specify a new docstring.

Here’s the syntax for cloning a function:

     /*[clinic input]
     module.class.new_function [as c_basename] = module.class.existing_function

     Docstring for new_function goes here.
     [clinic start generated code]*/

(The functions can be in different modules or classes.  I wrote
‘module.class’ in the sample just to illustrate that you must use the
full path to `both' functions.)

Sorry, there’s no syntax for partially-cloning a function, or cloning a
function then modifying it.  Cloning is an all-or nothing proposition.

Also, the function you are cloning from must have been previously
defined in the current file.


File: python.info,  Node: Calling Python code,  Next: Using a "self converter",  Prev: Cloning existing functions,  Up: Advanced Topics

10.15.4.13 Calling Python code
..............................

The rest of the advanced topics require you to write Python code which
lives inside your C file and modifies Argument Clinic’s runtime state.
This is simple: you simply define a Python block.

A Python block uses different delimiter lines than an Argument Clinic
function block.  It looks like this:

     /*[python input]
     # python code goes here
     [python start generated code]*/

All the code inside the Python block is executed at the time it’s
parsed.  All text written to stdout inside the block is redirected into
the "output" after the block.

As an example, here’s a Python block that adds a static integer variable
to the C code:

     /*[python input]
     print('static int __ignored_unused_variable__ = 0;')
     [python start generated code]*/
     static int __ignored_unused_variable__ = 0;
     /*[python checksum:...]*/


File: python.info,  Node: Using a "self converter",  Next: Writing a custom converter,  Prev: Calling Python code,  Up: Advanced Topics

10.15.4.14 Using a "self converter"
...................................

Argument Clinic automatically adds a "self" parameter for you using a
default converter.  It automatically sets the ‘type’ of this parameter
to the "pointer to an instance" you specified when you declared the
type.  However, you can override Argument Clinic’s converter and specify
one yourself.  Just add your own ‘self’ parameter as the first parameter
in a block, and ensure that its converter is an instance of
‘self_converter’ or a subclass thereof.

What’s the point?  This lets you override the type of ‘self’, or give it
a different default name.

How do you specify the custom type you want to cast ‘self’ to?  If you
only have one or two functions with the same type for ‘self’, you can
directly use Argument Clinic’s existing ‘self’ converter, passing in the
type you want to use as the ‘type’ parameter:

     /*[clinic input]

     _pickle.Pickler.dump

       self: self(type="PicklerObject *")
       obj: object
       /

     Write a pickled representation of the given object to the open file.
     [clinic start generated code]*/

On the other hand, if you have a lot of functions that will use the same
type for ‘self’, it’s best to create your own converter, subclassing
‘self_converter’ but overwriting the ‘type’ member:

     /*[python input]
     class PicklerObject_converter(self_converter):
         type = "PicklerObject *"
     [python start generated code]*/

     /*[clinic input]

     _pickle.Pickler.dump

       self: PicklerObject
       obj: object
       /

     Write a pickled representation of the given object to the open file.
     [clinic start generated code]*/


File: python.info,  Node: Writing a custom converter,  Next: Writing a custom return converter,  Prev: Using a "self converter",  Up: Advanced Topics

10.15.4.15 Writing a custom converter
.....................................

As we hinted at in the previous section...  you can write your own
converters!  A converter is simply a Python class that inherits from
‘CConverter’.  The main purpose of a custom converter is if you have a
parameter using the ‘O&’ format unit—parsing this parameter means
calling a *note PyArg_ParseTuple(): 26b. "converter function".

Your converter class should be named ‘*something*_converter’.  If the
name follows this convention, then your converter class will be
automatically registered with Argument Clinic; its name will be the name
of your class with the ‘_converter’ suffix stripped off.  (This is
accomplished with a metaclass.)

You shouldn’t subclass ‘CConverter.__init__’.  Instead, you should write
a ‘converter_init()’ function.  ‘converter_init()’ always accepts a
‘self’ parameter; after that, all additional parameters `must' be
keyword-only.  Any arguments passed in to the converter in Argument
Clinic will be passed along to your ‘converter_init()’.

There are some additional members of ‘CConverter’ you may wish to
specify in your subclass.  Here’s the current list:

‘type’

     The C type to use for this variable.  ‘type’ should be a Python
     string specifying the type, e.g.  ‘int’.  If this is a pointer
     type, the type string should end with ‘' *'’.

‘default’

     The Python default value for this parameter, as a Python value.  Or
     the magic value ‘unspecified’ if there is no default.

‘py_default’

     ‘default’ as it should appear in Python code, as a string.  Or
     ‘None’ if there is no default.

‘c_default’

     ‘default’ as it should appear in C code, as a string.  Or ‘None’ if
     there is no default.

‘c_ignored_default’

     The default value used to initialize the C variable when there is
     no default, but not specifying a default may result in an
     "uninitialized variable" warning.  This can easily happen when
     using option groups—although properly-written code will never
     actually use this value, the variable does get passed in to the
     impl, and the C compiler will complain about the "use" of the
     uninitialized value.  This value should always be a non-empty
     string.

‘converter’

     The name of the C converter function, as a string.

‘impl_by_reference’

     A boolean value.  If true, Argument Clinic will add a ‘&’ in front
     of the name of the variable when passing it into the impl function.

‘parse_by_reference’

     A boolean value.  If true, Argument Clinic will add a ‘&’ in front
     of the name of the variable when passing it into *note
     PyArg_ParseTuple(): 26b.

Here’s the simplest example of a custom converter, from
‘Modules/zlibmodule.c’:

     /*[python input]

     class ssize_t_converter(CConverter):
         type = 'Py_ssize_t'
         converter = 'ssize_t_converter'

     [python start generated code]*/
     /*[python end generated code: output=da39a3ee5e6b4b0d input=35521e4e733823c7]*/

This block adds a converter to Argument Clinic named ‘ssize_t’.
Parameters declared as ‘ssize_t’ will be declared as type ‘Py_ssize_t’,
and will be parsed by the ‘'O&'’ format unit, which will call the
‘ssize_t_converter’ converter function.  ‘ssize_t’ variables
automatically support default values.

More sophisticated custom converters can insert custom C code to handle
initialization and cleanup.  You can see more examples of custom
converters in the CPython source tree; grep the C files for the string
‘CConverter’.


File: python.info,  Node: Writing a custom return converter,  Next: METH_O and METH_NOARGS,  Prev: Writing a custom converter,  Up: Advanced Topics

10.15.4.16 Writing a custom return converter
............................................

Writing a custom return converter is much like writing a custom
converter.  Except it’s somewhat simpler, because return converters are
themselves much simpler.

Return converters must subclass ‘CReturnConverter’.  There are no
examples yet of custom return converters, because they are not widely
used yet.  If you wish to write your own return converter, please read
‘Tools/clinic/clinic.py’, specifically the implementation of
‘CReturnConverter’ and all its subclasses.


File: python.info,  Node: METH_O and METH_NOARGS,  Next: tp_new and tp_init functions,  Prev: Writing a custom return converter,  Up: Advanced Topics

10.15.4.17 METH_O and METH_NOARGS
.................................

To convert a function using ‘METH_O’, make sure the function’s single
argument is using the ‘object’ converter, and mark the arguments as
positional-only:

     /*[clinic input]
     meth_o_sample

          argument: object
          /
     [clinic start generated code]*/

To convert a function using ‘METH_NOARGS’, just don’t specify any
arguments.

You can still use a self converter, a return converter, and specify a
‘type’ argument to the object converter for ‘METH_O’.


File: python.info,  Node: tp_new and tp_init functions,  Next: Changing and redirecting Clinic's output,  Prev: METH_O and METH_NOARGS,  Up: Advanced Topics

10.15.4.18 tp_new and tp_init functions
.......................................

You can convert ‘tp_new’ and ‘tp_init’ functions.  Just name them
‘__new__’ or ‘__init__’ as appropriate.  Notes:

   * The function name generated for ‘__new__’ doesn’t end in ‘__new__’
     like it would by default.  It’s just the name of the class,
     converted into a valid C identifier.

   * No ‘PyMethodDef’ ‘#define’ is generated for these functions.

   * ‘__init__’ functions return ‘int’, not ‘PyObject *’.

   * Use the docstring as the class docstring.

   * Although ‘__new__’ and ‘__init__’ functions must always accept both
     the ‘args’ and ‘kwargs’ objects, when converting you may specify
     any signature for these functions that you like.  (If your function
     doesn’t support keywords, the parsing function generated will throw
     an exception if it receives any.)


File: python.info,  Node: Changing and redirecting Clinic's output,  Next: The #ifdef trick,  Prev: tp_new and tp_init functions,  Up: Advanced Topics

10.15.4.19 Changing and redirecting Clinic’s output
...................................................

It can be inconvenient to have Clinic’s output interspersed with your
conventional hand-edited C code.  Luckily, Clinic is configurable: you
can buffer up its output for printing later (or earlier!), or write its
output to a separate file.  You can also add a prefix or suffix to every
line of Clinic’s generated output.

While changing Clinic’s output in this manner can be a boon to
readability, it may result in Clinic code using types before they are
defined, or your code attempting to use Clinic-generated code before it
is defined.  These problems can be easily solved by rearranging the
declarations in your file, or moving where Clinic’s generated code goes.
(This is why the default behavior of Clinic is to output everything into
the current block; while many people consider this hampers readability,
it will never require rearranging your code to fix definition-before-use
problems.)

Let’s start with defining some terminology:

`field'

     A field, in this context, is a subsection of Clinic’s output.  For
     example, the ‘#define’ for the ‘PyMethodDef’ structure is a field,
     called ‘methoddef_define’.  Clinic has seven different fields it
     can output per function definition:

          docstring_prototype
          docstring_definition
          methoddef_define
          impl_prototype
          parser_prototype
          parser_definition
          impl_definition

     All the names are of the form ‘"<a>_<b>"’, where ‘"<a>"’ is the
     semantic object represented (the parsing function, the impl
     function, the docstring, or the methoddef structure) and ‘"<b>"’
     represents what kind of statement the field is.  Field names that
     end in ‘"_prototype"’ represent forward declarations of that thing,
     without the actual body/data of the thing; field names that end in
     ‘"_definition"’ represent the actual definition of the thing, with
     the body/data of the thing.  (‘"methoddef"’ is special, it’s the
     only one that ends with ‘"_define"’, representing that it’s a
     preprocessor #define.)

`destination'

     A destination is a place Clinic can write output to.  There are
     five built-in destinations:

     ‘block’

          The default destination: printed in the output section of the
          current Clinic block.

     ‘buffer’

          A text buffer where you can save text for later.  Text sent
          here is appended to the end of any existing text.  It’s an
          error to have any text left in the buffer when Clinic finishes
          processing a file.

     ‘file’

          A separate "clinic file" that will be created automatically by
          Clinic.  The filename chosen for the file is
          ‘{basename}.clinic{extension}’, where ‘basename’ and
          ‘extension’ were assigned the output from ‘os.path.splitext()’
          run on the current file.  (Example: the ‘file’ destination for
          ‘_pickle.c’ would be written to ‘_pickle.clinic.c’.)

          `Important: When using a' ‘file’ `destination, you' `must
          check in' `the generated file!'

     ‘two-pass’

          A buffer like ‘buffer’.  However, a two-pass buffer can only
          be dumped once, and it prints out all text sent to it during
          all processing, even from Clinic blocks `after' the dumping
          point.

     ‘suppress’

          The text is suppressed—thrown away.

Clinic defines five new directives that let you reconfigure its output.

The first new directive is ‘dump’:

     dump <destination>

This dumps the current contents of the named destination into the output
of the current block, and empties it.  This only works with ‘buffer’ and
‘two-pass’ destinations.

The second new directive is ‘output’.  The most basic form of ‘output’
is like this:

     output <field> <destination>

This tells Clinic to output `field' to `destination'.  ‘output’ also
supports a special meta-destination, called ‘everything’, which tells
Clinic to output `all' fields to that `destination'.

‘output’ has a number of other functions:

     output push
     output pop
     output preset <preset>

‘output push’ and ‘output pop’ allow you to push and pop configurations
on an internal configuration stack, so that you can temporarily modify
the output configuration, then easily restore the previous
configuration.  Simply push before your change to save the current
configuration, then pop when you wish to restore the previous
configuration.

‘output preset’ sets Clinic’s output to one of several built-in preset
configurations, as follows:

     ‘block’

          Clinic’s original starting configuration.  Writes everything
          immediately after the input block.

          Suppress the ‘parser_prototype’ and ‘docstring_prototype’,
          write everything else to ‘block’.

     ‘file’

          Designed to write everything to the "clinic file" that it can.
          You then ‘#include’ this file near the top of your file.  You
          may need to rearrange your file to make this work, though
          usually this just means creating forward declarations for
          various ‘typedef’ and ‘PyTypeObject’ definitions.

          Suppress the ‘parser_prototype’ and ‘docstring_prototype’,
          write the ‘impl_definition’ to ‘block’, and write everything
          else to ‘file’.

          The default filename is ‘"{dirname}/clinic/{basename}.h"’.

     ‘buffer’

          Save up most of the output from Clinic, to be written into
          your file near the end.  For Python files implementing modules
          or builtin types, it’s recommended that you dump the buffer
          just above the static structures for your module or builtin
          type; these are normally very near the end.  Using ‘buffer’
          may require even more editing than ‘file’, if your file has
          static ‘PyMethodDef’ arrays defined in the middle of the file.

          Suppress the ‘parser_prototype’, ‘impl_prototype’, and
          ‘docstring_prototype’, write the ‘impl_definition’ to ‘block’,
          and write everything else to ‘file’.

     ‘two-pass’

          Similar to the ‘buffer’ preset, but writes forward
          declarations to the ‘two-pass’ buffer, and definitions to the
          ‘buffer’.  This is similar to the ‘buffer’ preset, but may
          require less editing than ‘buffer’.  Dump the ‘two-pass’
          buffer near the top of your file, and dump the ‘buffer’ near
          the end just like you would when using the ‘buffer’ preset.

          Suppresses the ‘impl_prototype’, write the ‘impl_definition’
          to ‘block’, write ‘docstring_prototype’, ‘methoddef_define’,
          and ‘parser_prototype’ to ‘two-pass’, write everything else to
          ‘buffer’.

     ‘partial-buffer’

          Similar to the ‘buffer’ preset, but writes more things to
          ‘block’, only writing the really big chunks of generated code
          to ‘buffer’.  This avoids the definition-before-use problem of
          ‘buffer’ completely, at the small cost of having slightly more
          stuff in the block’s output.  Dump the ‘buffer’ near the end,
          just like you would when using the ‘buffer’ preset.

          Suppresses the ‘impl_prototype’, write the
          ‘docstring_definition’ and ‘parser_definition’ to ‘buffer’,
          write everything else to ‘block’.

The third new directive is ‘destination’:

     destination <name> <command> [...]

This performs an operation on the destination named ‘name’.

There are two defined subcommands: ‘new’ and ‘clear’.

The ‘new’ subcommand works like this:

     destination <name> new <type>

This creates a new destination with name ‘<name>’ and type ‘<type>’.

There are five destination types:

     ‘suppress’

          Throws the text away.

     ‘block’

          Writes the text to the current block.  This is what Clinic
          originally did.

     ‘buffer’

          A simple text buffer, like the "buffer" builtin destination
          above.

     ‘file’

          A text file.  The file destination takes an extra argument, a
          template to use for building the filename, like so:

               destination <name> new <type> <file_template>

          The template can use three strings internally that will be
          replaced by bits of the filename:

               {path}

                    The full path to the file, including directory and
                    full filename.

               {dirname}

                    The name of the directory the file is in.

               {basename}

                    Just the name of the file, not including the
                    directory.

               {basename_root}

                    Basename with the extension clipped off (everything
                    up to but not including the last ’.’).

               {basename_extension}

                    The last ’.’ and everything after it.  If the
                    basename does not contain a period, this will be the
                    empty string.

          If there are no periods in the filename, {basename} and
          {filename} are the same, and {extension} is empty.
          "{basename}{extension}" is always exactly the same as
          "{filename}"."

     ‘two-pass’

          A two-pass buffer, like the "two-pass" builtin destination
          above.

The ‘clear’ subcommand works like this:

     destination <name> clear

It removes all the accumulated text up to this point in the destination.
(I don’t know what you’d need this for, but I thought maybe it’d be
useful while someone’s experimenting.)

The fourth new directive is ‘set’:

     set line_prefix "string"
     set line_suffix "string"

‘set’ lets you set two internal variables in Clinic.  ‘line_prefix’ is a
string that will be prepended to every line of Clinic’s output;
‘line_suffix’ is a string that will be appended to every line of
Clinic’s output.

Both of these support two format strings:

     ‘{block comment start}’

          Turns into the string ‘/*’, the start-comment text sequence
          for C files.

     ‘{block comment end}’

          Turns into the string ‘*/’, the end-comment text sequence for
          C files.

The final new directive is one you shouldn’t need to use directly,
called ‘preserve’:

     preserve

This tells Clinic that the current contents of the output should be
kept, unmodified.  This is used internally by Clinic when dumping output
into ‘file’ files; wrapping it in a Clinic block lets Clinic use its
existing checksum functionality to ensure the file was not modified by
hand before it gets overwritten.


File: python.info,  Node: The #ifdef trick,  Next: Using Argument Clinic in Python files,  Prev: Changing and redirecting Clinic's output,  Up: Advanced Topics

10.15.4.20 The #ifdef trick
...........................

If you’re converting a function that isn’t available on all platforms,
there’s a trick you can use to make life a little easier.  The existing
code probably looks like this:

     #ifdef HAVE_FUNCTIONNAME
     static module_functionname(...)
     {
     ...
     }
     #endif /* HAVE_FUNCTIONNAME */

And then in the ‘PyMethodDef’ structure at the bottom the existing code
will have:

     #ifdef HAVE_FUNCTIONNAME
     {'functionname', ... },
     #endif /* HAVE_FUNCTIONNAME */

In this scenario, you should enclose the body of your impl function
inside the ‘#ifdef’, like so:

     #ifdef HAVE_FUNCTIONNAME
     /*[clinic input]
     module.functionname
     ...
     [clinic start generated code]*/
     static module_functionname(...)
     {
     ...
     }
     #endif /* HAVE_FUNCTIONNAME */

Then, remove those three lines from the ‘PyMethodDef’ structure,
replacing them with the macro Argument Clinic generated:

     MODULE_FUNCTIONNAME_METHODDEF

(You can find the real name for this macro inside the generated code.
Or you can calculate it yourself: it’s the name of your function as
defined on the first line of your block, but with periods changed to
underscores, uppercased, and ‘"_METHODDEF"’ added to the end.)

Perhaps you’re wondering: what if ‘HAVE_FUNCTIONNAME’ isn’t defined?
The ‘MODULE_FUNCTIONNAME_METHODDEF’ macro won’t be defined either!

Here’s where Argument Clinic gets very clever.  It actually detects that
the Argument Clinic block might be deactivated by the ‘#ifdef’.  When
that happens, it generates a little extra code that looks like this:

     #ifndef MODULE_FUNCTIONNAME_METHODDEF
         #define MODULE_FUNCTIONNAME_METHODDEF
     #endif /* !defined(MODULE_FUNCTIONNAME_METHODDEF) */

That means the macro always works.  If the function is defined, this
turns into the correct structure, including the trailing comma.  If the
function is undefined, this turns into nothing.

However, this causes one ticklish problem: where should Argument Clinic
put this extra code when using the "block" output preset?  It can’t go
in the output block, because that could be deactivated by the ‘#ifdef’.
(That’s the whole point!)

In this situation, Argument Clinic writes the extra code to the "buffer"
destination.  This may mean that you get a complaint from Argument
Clinic:

     Warning in file "Modules/posixmodule.c" on line 12357:
     Destination buffer 'buffer' not empty at end of file, emptying.

When this happens, just open your file, find the ‘dump buffer’ block
that Argument Clinic added to your file (it’ll be at the very bottom),
then move it above the ‘PyMethodDef’ structure where that macro is used.


File: python.info,  Node: Using Argument Clinic in Python files,  Prev: The #ifdef trick,  Up: Advanced Topics

10.15.4.21 Using Argument Clinic in Python files
................................................

It’s actually possible to use Argument Clinic to preprocess Python
files.  There’s no point to using Argument Clinic blocks, of course, as
the output wouldn’t make any sense to the Python interpreter.  But using
Argument Clinic to run Python blocks lets you use Python as a Python
preprocessor!

Since Python comments are different from C comments, Argument Clinic
blocks embedded in Python files look slightly different.  They look like
this:

     #/*[python input]
     #print("def foo(): pass")
     #[python start generated code]*/
     def foo(): pass
     #/*[python checksum:...]*/


File: python.info,  Node: 使用 DTrace 和 SystemTap 检测CPython,  Prev: Argument Clinic How-To,  Up: Python 常用指引

10.16 使用 DTrace 和 SystemTap 检测CPython
==========================================


作者: David Malcolm


作者: Łukasz Langa

DTrace和SystemTap是监控工具，它们都提供了一种检查计算机系统上的进程的方
法。 它们都使用特定领域的语言，允许用户编写脚本，其中：

        - 进程监视的过滤器

        - 从感兴趣的进程中收集数据

        - 生成有关数据的报告

从Python 3.6开始，CPython可以使用嵌入式“标记”构建，也称为“探测器”，可以
通过DTrace或SystemTap脚本观察，从而更容易监视系统上的CPython进程正在做什
么。

`CPython implementation detail:' DTrace标记是CPython解释器的实现细节。 不
保证CPython版本之间的探针兼容性。 更改CPython版本时，DTrace脚本可能会停
止工作或无法正常工作而不会发出警告。

* Menu:

* 启用静态标记::
* 静态DTrace探针::
* 静态SystemTap标记::
* 可用的静态标记::
* SystemTap Tapsets::
* 例子: 例子<36>.


File: python.info,  Node: 启用静态标记,  Next: 静态DTrace探针,  Up: 使用 DTrace 和 SystemTap 检测CPython

10.16.1 启用静态标记
--------------------

macOS内置了对DTrace的支持。 在Linux上，为了使用SystemTap的嵌入式标记构建
CPython，必须安装SystemTap开发工具。

在Linux机器上，这可以通过：

     $ yum install systemtap-sdt-devel

或者：

     $ sudo apt-get install systemtap-sdt-dev

然后必须将CPython配置为‘‘–with-dtrace‘‘：

     checking for --with-dtrace... yes

在macOS上，您可以通过在后台运行Python进程列出可用的DTrace探测器，并列出
Python程序提供的所有探测器：

     $ python3.6 -q &
     $ sudo dtrace -l -P python$!  # or: dtrace -l -m python3.6

        ID   PROVIDER            MODULE                          FUNCTION NAME
     29564 python18035        python3.6          _PyEval_EvalFrameDefault function-entry
     29565 python18035        python3.6             dtrace_function_entry function-entry
     29566 python18035        python3.6          _PyEval_EvalFrameDefault function-return
     29567 python18035        python3.6            dtrace_function_return function-return
     29568 python18035        python3.6                           collect gc-done
     29569 python18035        python3.6                           collect gc-start
     29570 python18035        python3.6          _PyEval_EvalFrameDefault line
     29571 python18035        python3.6                 maybe_dtrace_line line

在Linux上，您可以通过查看是否包含“.note.stapsdt”部分来验证构建的二进制文
件中是否存在SystemTap静态标记。

     $ readelf -S ./python | grep .note.stapsdt
     [30] .note.stapsdt        NOTE         0000000000000000 00308d78

如果您已将Python构建为共享库（使用–enable-shared），则需要在共享库中查找
。 例如：

     $ readelf -S libpython3.3dm.so.1.0 | grep .note.stapsdt
     [29] .note.stapsdt        NOTE         0000000000000000 00365b68

足够现代的readelf命令可以打印元数据：

     $ readelf -n ./python

     Displaying notes found at file offset 0x00000254 with length 0x00000020:
         Owner                 Data size          Description
         GNU                  0x00000010          NT_GNU_ABI_TAG (ABI version tag)
             OS: Linux, ABI: 2.6.32

     Displaying notes found at file offset 0x00000274 with length 0x00000024:
         Owner                 Data size          Description
         GNU                  0x00000014          NT_GNU_BUILD_ID (unique build ID bitstring)
             Build ID: df924a2b08a7e89f6e11251d4602022977af2670

     Displaying notes found at file offset 0x002d6c30 with length 0x00000144:
         Owner                 Data size          Description
         stapsdt              0x00000031          NT_STAPSDT (SystemTap probe descriptors)
             Provider: python
             Name: gc__start
             Location: 0x00000000004371c3, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf6
             Arguments: -4@%ebx
         stapsdt              0x00000030          NT_STAPSDT (SystemTap probe descriptors)
             Provider: python
             Name: gc__done
             Location: 0x00000000004374e1, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf8
             Arguments: -8@%rax
         stapsdt              0x00000045          NT_STAPSDT (SystemTap probe descriptors)
             Provider: python
             Name: function__entry
             Location: 0x000000000053db6c, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6be8
             Arguments: 8@%rbp 8@%r12 -4@%eax
         stapsdt              0x00000046          NT_STAPSDT (SystemTap probe descriptors)
             Provider: python
             Name: function__return
             Location: 0x000000000053dba8, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bea
             Arguments: 8@%rbp 8@%r12 -4@%eax

上述元数据包含SystemTap的信息，描述如何修补策略性放置的机器代码指令以启
用SystemTap脚本使用的跟踪钩子。


File: python.info,  Node: 静态DTrace探针,  Next: 静态SystemTap标记,  Prev: 启用静态标记,  Up: 使用 DTrace 和 SystemTap 检测CPython

10.16.2 静态DTrace探针
----------------------

下面的 DTrace 脚本示例可以用来显示一个 Python 脚本的调用/返回层次结构，
只在调用名为 "start" 的函数内进行跟踪。换句话说，导入时的函数调用不会被
列出。

     self int indent;

     python$target:::function-entry
     /copyinstr(arg1) == "start"/
     {
             self->trace = 1;
     }

     python$target:::function-entry
     /self->trace/
     {
             printf("%d\t%*s:", timestamp, 15, probename);
             printf("%*s", self->indent, "");
             printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2);
             self->indent++;
     }

     python$target:::function-return
     /self->trace/
     {
             self->indent--;
             printf("%d\t%*s:", timestamp, 15, probename);
             printf("%*s", self->indent, "");
             printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2);
     }

     python$target:::function-return
     /copyinstr(arg1) == "start"/
     {
             self->trace = 0;
     }

它可以这样调用:

     $ sudo dtrace -q -s call_stack.d -c "python3.6 script.py"

输出结果会像这样:

     156641360502280  function-entry:call_stack.py:start:23
     156641360518804  function-entry: call_stack.py:function_1:1
     156641360532797  function-entry:  call_stack.py:function_3:9
     156641360546807 function-return:  call_stack.py:function_3:10
     156641360563367 function-return: call_stack.py:function_1:2
     156641360578365  function-entry: call_stack.py:function_2:5
     156641360591757  function-entry:  call_stack.py:function_1:1
     156641360605556  function-entry:   call_stack.py:function_3:9
     156641360617482 function-return:   call_stack.py:function_3:10
     156641360629814 function-return:  call_stack.py:function_1:2
     156641360642285 function-return: call_stack.py:function_2:6
     156641360656770  function-entry: call_stack.py:function_3:9
     156641360669707 function-return: call_stack.py:function_3:10
     156641360687853  function-entry: call_stack.py:function_4:13
     156641360700719 function-return: call_stack.py:function_4:14
     156641360719640  function-entry: call_stack.py:function_5:18
     156641360732567 function-return: call_stack.py:function_5:21
     156641360747370 function-return:call_stack.py:start:28


File: python.info,  Node: 静态SystemTap标记,  Next: 可用的静态标记,  Prev: 静态DTrace探针,  Up: 使用 DTrace 和 SystemTap 检测CPython

10.16.3 静态SystemTap标记
-------------------------

使用 SystemTap 集成的底层方法是直接使用静态标记。 这需要你显式地说明包含
它们的二进制文件。

例如，这个SystemTap脚本可以用来显示Python脚本的调用/返回层次结构：

     probe process("python").mark("function__entry") {
          filename = user_string($arg1);
          funcname = user_string($arg2);
          lineno = $arg3;

          printf("%s => %s in %s:%d\\n",
                 thread_indent(1), funcname, filename, lineno);
     }

     probe process("python").mark("function__return") {
         filename = user_string($arg1);
         funcname = user_string($arg2);
         lineno = $arg3;

         printf("%s <= %s in %s:%d\\n",
                thread_indent(-1), funcname, filename, lineno);
     }

它可以这样调用:

     $ stap \
       show-call-hierarchy.stp \
       -c "./python test.py"

输出结果会像这样:

     11408 python(8274):        => __contains__ in Lib/_abcoll.py:362
     11414 python(8274):         => __getitem__ in Lib/os.py:425
     11418 python(8274):          => encode in Lib/os.py:490
     11424 python(8274):          <= encode in Lib/os.py:493
     11428 python(8274):         <= __getitem__ in Lib/os.py:426
     11433 python(8274):        <= __contains__ in Lib/_abcoll.py:366

其中的列是：

        - 脚本开始后经过的微秒数

        - 可执行文件的名字

        - 进程的PID

其余部分则表示脚本执行时的调用/返回层次结构。

对于 ‘–enable-shared’ 构建的CPython来说，这些标记是包含在libpython共享库
中的，探针的点状路径需要反映这一点。比如上面例子中的这一行：

     probe process("python").mark("function__entry") {

应改为：

     probe process("python").library("libpython3.6dm.so.1.0").mark("function__entry") {

（假设是 CPython 3.6 的调试构建）


File: python.info,  Node: 可用的静态标记,  Next: SystemTap Tapsets,  Prev: 静态SystemTap标记,  Up: 使用 DTrace 和 SystemTap 检测CPython

10.16.4 可用的静态标记
----------------------

 -- Object: function__entry(str filename, str funcname, int lineno)

     这个标记表示一个Python函数的执行已经开始。它只对纯 Python （字节码
     ）函数触发。

     文件名、函数名和行号作为位置参数提供给跟踪脚本，必须使用 ‘$arg1’,
     ‘$arg2’, ‘$arg3’ 访问：

             * ‘$arg1’ : ‘(const char *)’ 文件名，使用
               ‘user_string($arg1)’ 访问

             * ‘$arg2’ : ‘(const char *)’ 函数名，使用
               ‘user_string($arg2)’ 访问

             * ‘$arg3’ : ‘int’ 行号

 -- Object: function__return(str filename, str funcname, int lineno)

     这个标记与 ‘function__entry()’ 相反，表示Python函数的执行已经结束
     (通过 ‘return’ 或者异常)。 它只对纯Python (字节码) 函数触发。

     参数和 ‘function__entry()’ 相同

 -- Object: line(str filename, str funcname, int lineno)

     这个标记表示一个 Python 行即将被执行。它相当于用 Python 分析器逐行
     追踪。它不会在C函数中触发。

     参数和 ‘function__entry()’ 相同

 -- Object: gc__start(int generation)

     当Python解释器启动一个垃圾回收循环时被触发。 ‘arg0’ 是要扫描的生成
     器，如 *note gc.collect(): 22f.。

 -- Object: gc__done(long collected)

     当Python解释器完成一个垃圾回收循环时被触发。‘arg0’ 是收集到的对象的
     数量。

 -- Object: import__find__load__start(str modulename)

     在 *note importlib: 9b. 试图查找并加载模块之前被触发。‘arg0’ 是模块
     名称。

     3.7 新版功能.

 -- Object: import__find__load__done(str modulename, int found)

     在 *note importlib: 9b. 的 find_and_load 函数被调用后被触发 。
     ‘arg0’ 是模块名称， ‘arg1’ 表示模块是否成功加载。

     3.7 新版功能.

 -- Object: audit(str event, void *tuple)

     当 *note sys.audit(): f38. 或 *note PySys_Audit(): f46. 被调用时启
     动。 ‘arg0’ 是事件名称的 C 字符串，‘arg1’ 是一个指向元组对象的
     *note PyObject: 4c2. 指针。

     3.8 新版功能.


File: python.info,  Node: SystemTap Tapsets,  Next: 例子<36>,  Prev: 可用的静态标记,  Up: 使用 DTrace 和 SystemTap 检测CPython

10.16.5 SystemTap Tapsets
-------------------------

使用SystemTap集成的更高层次的方法是使用 "tapset" 。SystemTap 的等效库，
它隐藏了静态标记的一些底层细节。

这里是一个基于 CPython 的非共享构建的 tapset 文件。

     /*
        Provide a higher-level wrapping around the function__entry and
        function__return markers:
      \*/
     probe python.function.entry = process("python").mark("function__entry")
     {
         filename = user_string($arg1);
         funcname = user_string($arg2);
         lineno = $arg3;
         frameptr = $arg4
     }
     probe python.function.return = process("python").mark("function__return")
     {
         filename = user_string($arg1);
         funcname = user_string($arg2);
         lineno = $arg3;
         frameptr = $arg4
     }

如果这个文件安装在 SystemTap 的 tapset 目录下（例如
‘‘/usr/share/systemtap/tapset‘‘ ），那么这些额外的探测点就会变得可用。

 -- Object: python.function.entry(str filename, str funcname, int
          lineno, frameptr)

     这个探针点表示一个Python函数的执行已经开始。它只对纯Python （字节码
     ）函数触发。

 -- Object: python.function.return(str filename, str funcname, int
          lineno, frameptr)

     这个探针点是 ‘python.function.return’ 的反义操作，表示一个 Python 函
     数的执行已经结束（或是通过 ‘return’，或是通过异常）。 它只会针对纯
     Python（字节码）函数触发。


File: python.info,  Node: 例子<36>,  Prev: SystemTap Tapsets,  Up: 使用 DTrace 和 SystemTap 检测CPython

10.16.6 例子
------------

这个SystemTap脚本使用上面的tapset来更清晰地实现上面给出的跟踪Python函数
调用层次结构的例子，而不需要直接命名静态标记。

     probe python.function.entry
     {
       printf("%s => %s in %s:%d\n",
              thread_indent(1), funcname, filename, lineno);
     }

     probe python.function.return
     {
       printf("%s <= %s in %s:%d\n",
              thread_indent(-1), funcname, filename, lineno);
     }

下面的脚本使用上面的tapset提供了所有运行中的CPython代码的顶部视图，显示
了整个系统中每一秒钟最频繁输入的前20个字节码帧。

     global fn_calls;

     probe python.function.entry
     {
         fn_calls[pid(), filename, funcname, lineno] += 1;
     }

     probe timer.ms(1000) {
         printf("\033[2J\033[1;1H") /* clear screen \*/
         printf("%6s %80s %6s %30s %6s\n",
                "PID", "FILENAME", "LINE", "FUNCTION", "CALLS")
         foreach ([pid, filename, funcname, lineno] in fn_calls- limit 20) {
             printf("%6d %80s %6d %30s %6d\n",
                 pid, filename, lineno, funcname,
                 fn_calls[pid, filename, funcname, lineno]);
         }
         delete fn_calls;
     }


File: python.info,  Node: Python 常见问题,  Next: 术语对照表,  Prev: Python 常用指引,  Up: Top

11 Python 常见问题
******************

* Menu:

* Python常见问题::
* 编程常见问题::
* 设计和历史常见问题::
* 代码库和插件 FAQ::
* 扩展/嵌入常见问题::
* Python在Windows上的常见问题::
* 图形用户界面（GUI）常见问题::
* “为什么我的电脑上安装了 Python ？”::


File: python.info,  Node: Python常见问题,  Next: 编程常见问题,  Up: Python 常见问题

11.1 Python常见问题
===================

* Menu:

* 一般信息::
* 现实世界中的 Python::


File: python.info,  Node: 一般信息,  Next: 现实世界中的 Python,  Up: Python常见问题

11.1.1 一般信息
---------------

* Menu:

* 什么是 Python？::
* 什么是 Python 软件基金会？::
* 使用 Python 是否存在版权限制？::
* 创造 Python 的最初理由是什么？::
* Python 适合做什么？::
* Python 版本的编号形式是怎样的？::
* 我应如何获取一份 Python 源代码的副本？::
* 我应如何获取 Python 的文档？::
* 我之前从未接触过编程。 哪里有 Python 的教程？::
* 是否有专门针对 Python 的新闻组或邮件列表？::
* 我应如何获取 Python 的公开测试版本？::
* 我应如何为 Python 提交错误报告和补丁？::
* 是否有任何公开发表的 Python 相关文章可以供我参考引用？::
* 是否有任何 Python 相关的书籍？::
* www.python.org 具体位于世界上的哪个地点？: www python org 具体位于世界上的哪个地点？.
* 为何命名为 Python？::
* 我必须喜欢 "Monty Python 的飞行马戏团" 吗？::


File: python.info,  Node: 什么是 Python？,  Next: 什么是 Python 软件基金会？,  Up: 一般信息

11.1.1.1 什么是 Python？
........................

Python 是一种解释型、交互式、面向对象的编程语言。 它包含了模块、异常、动
态类型、高层级动态数据类型以及类等特性。 在面向对象编程以外它还支持多种
编程范式，例如过程式和函数式编程等。 Python 结合了超强的功能和极清晰的语
法。 它带有许多系统调用和库以及多种窗口系统的接口，并且能用 C 或 C++ 来
进行扩展。 它还可用作需要可编程接口的应用程序的扩展语言。 最后，Python 非
常易于移植：它可以在包括 Linux 和 macOS 在内的许多 Unix 变种以及 Windows
上运行。

要了解更多详情，请先查看 *note Python 教程: 120a.。 Python 新手指南(1) 提
供了学习 Python 的其他入门教程及资源的链接。

   ---------- Footnotes ----------

   (1) https://wiki.python.org/moin/BeginnersGuide


File: python.info,  Node: 什么是 Python 软件基金会？,  Next: 使用 Python 是否存在版权限制？,  Prev: 什么是 Python？,  Up: 一般信息

11.1.1.2 什么是 Python 软件基金会？
...................................

Python 软件基金会（Python Software Foundation，简称 PSF）是一个独立的非
盈利组织，它拥有 Python 2.1 及以上各版本的版权。 PSF 的使命是推进与
Python 编程语言相关的开源技术，并推广 Python 的使用。 PSF 的主页是
‘https://www.python.org/psf/’。

向 PSF 提供捐助在美国是免税的。 如果你在使用 Python 并且感觉它对你很有帮
助，可以通过 PSF 捐助页(1) 进行捐助。

   ---------- Footnotes ----------

   (1) https://www.python.org/psf/donations/


File: python.info,  Node: 使用 Python 是否存在版权限制？,  Next: 创造 Python 的最初理由是什么？,  Prev: 什么是 Python 软件基金会？,  Up: 一般信息

11.1.1.3 使用 Python 是否存在版权限制？
.......................................

你可以任意使用源码，只要你保留版权信息并在你基于 Python 的产品文档中显示
该版权信息。 如果你遵守此版权规则，就可以将 Python 用于商业领域，以源码
或二进制码的形式（不论是否经过修改）销售 Python 的副本，或是以某种形式包
含了 Python 的产品。 当然，我们仍然希望获知所有对 Python 的商业使用。

请参阅 PSF 许可页(1) 以查看进一步的说明以及许可的完整文本内容的链接。

Python 的徽标是注册商标，在某些情况下需要获得允许方可使用。 请参阅 商标
使用政策(2) 了解详情。

   ---------- Footnotes ----------

   (1) https://www.python.org/psf/license/

   (2) https://www.python.org/psf/trademarks/


File: python.info,  Node: 创造 Python 的最初理由是什么？,  Next: Python 适合做什么？,  Prev: 使用 Python 是否存在版权限制？,  Up: 一般信息

11.1.1.4 创造 Python 的最初理由是什么？
.......................................

以下是有关最初缘起的一份 `非常' 简短的摘要，由 Guido van Rossum 本人撰写
:

     我在 CWI 的 ABC 部门时在实现解释型语言方面积累了丰富经验，通过与这
     个部门成员的协同工作，我学到了大量有关语言设计的知识。 这是许多
     Python 特性的最初来源，包括使用缩进来组织语句以及包含非常高层级的数
     据结构（虽然在 Python 中具体的实现细节完全不同）。

     我对 ABC 语言有过许多抱怨，但同时也很喜欢它的许多特性。 没有可能通
     过扩展 ABC 语言（或它的实现）来弥补我的不满 —— 实际上缺乏可扩展性就
     是它最大的问题之一。 我也有一些使用 Modula-2+ 的经验，并曾与
     Modula-3 的设计者进行交流，还阅读了 Modula-3 的报告。 Modula-3 是
     Python 中异常机制所用语法和语义，以及其他一些语言特性的最初来源。

     我还曾在 CWI 的 Amoeba 分布式操作系统部门工作。 当时我们需要有一种
     比编写 C 程序或 Bash 脚本更好的方式来进行系统管理，因为 Amoeba 有它
     自己的系统调用接口，并且无法方便地通过 Bash 来访问。 我在 Amoeba 中
     处理错误的经验令我深刻地意识到异常处理在编程语言特性当中的重要地位
     。

     我发现，某种具有 ABC 式的语法而又能访问 Amoeba 系统调用的脚本语言将
     可满足需求。 我意识到编写一种 Amoeba 专属的语言是愚蠢的，所以我决定
     编写一种具有全面可扩展性的语言。

     在 1989 年的圣诞假期中，我手头的时间非常充裕，因此我决定开始尝试一
     下。 在接下来的一年里，虽然我仍然主要用我的业余时间来做这件事，但
     Python 在 Amoeba 项目中的使用获得了很大的成功，来自同事的反馈让我得
     以增加了许多早期的改进。

     到 1991 年 2 月，经过一年多的开发，我决定将其发布到 USENET。 之后的
     事情就都可以在 ‘Misc/HISTORY’ 文件里面看了。


File: python.info,  Node: Python 适合做什么？,  Next: Python 版本的编号形式是怎样的？,  Prev: 创造 Python 的最初理由是什么？,  Up: 一般信息

11.1.1.5 Python 适合做什么？
............................

Python 是一种高层级的多用途编程语言，可用于解决许多不同门类的问题。

该语言附带一个庞大的标准库，涵盖了字符串处理（正则表达式，Unicode，比较
文件间的差异等），因特网协议（HTTP，FTP，SMTP，XML-RPC，POP，IMAP，CGI 编
程等），软件工程（单元测试，日志记录，性能分析，Python 代码解析等），以
及操作系统接口（系统调用，文件系统，TCP/IP 套接字等）。 请查看 *note
Python 标准库: 120b. 的目录以了解所有可用的内容。 此外还可以获取到各种各
样的第三方扩展。 请访问 Python 包索引(1) 来查找你感兴趣的软件包。

   ---------- Footnotes ----------

   (1) https://pypi.org


File: python.info,  Node: Python 版本的编号形式是怎样的？,  Next: 我应如何获取一份 Python 源代码的副本？,  Prev: Python 适合做什么？,  Up: 一般信息

11.1.1.6 Python 版本的编号形式是怎样的？
........................................

Python 版本的编号形式是 A.B.C 或 A.B。 A 称为大版本号 —— 它仅在对语言特
性进行非常重大改变时才会递增。 B 称为小版本号，它会在语言特性发生较小改
变时递增。 C 称为微版本号 —— 它会在每次发布问题修正时递增。 请参阅 PEP
6(1) 了解有关问题修正发布版的详情。

发布版本并非都是问题修正版本。 在新的主要发布版本开发过程中，还会发布一
系列的开发版，它们以 alpha (a), beta (b) 或 release candidate (rc) 来标
示。 其中 alpha 版是早期发布的测试版，它的接口并未最终确定；在两个 alpha
发布版本间出现接口的改变并不意外。 而 beta 版更为稳定，它会保留现有的接
口，但也可能增加新的模块，release candidate 版则会保持冻结状态不会再进行
改变，除非有重大问题需要修正。

以上 alpha, beta 和 release candidate 版本会附加一个后缀。 用于 alpha 版
本的后缀是带有一个小数字 N 的 “aN”，beta 版本的后缀是带有一个小数字 N 的
“bN”，release candidate 版本的后缀是带有一个小数字 N 的“cN”。 换句话说，
所有标记为 2.0aN 的版本都早于标记为 2.0bN 的版本，后者又都早于标记为
2.0cN 的版本，而 `这些版本' 全都早于 2.0。

你还可能看到带有“+”后缀的版本号，例如“2.2+”。 这表示未发布版本，直接基于
CPython 开发代码仓库构建。 在实际操作中，当一个小版本最终发布后，未发布
版本号会递增到下一个小版本号，成为“a0”版本，例如“2.4a0”。

另请参阅 *note sys.version: 5dc, *note sys.hexversion: 363e. 以及 *note
sys.version_info: b22. 的文档。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0006


File: python.info,  Node: 我应如何获取一份 Python 源代码的副本？,  Next: 我应如何获取 Python 的文档？,  Prev: Python 版本的编号形式是怎样的？,  Up: 一般信息

11.1.1.7 我应如何获取一份 Python 源代码的副本？
...............................................

最新的 Python 发布版源代码总能从 python.org 获取，下载页链接为
‘https://www.python.org/downloads/’。 最新的开发版源代码可以在
‘https://github.com/python/cpython/’ 获取。

发布版源代码是一个以 gzip 压缩的 tar 文件，其中包含完整的 C 源代码、
Sphinx 格式的文档、Python 库模块、示例程序以及一些有用的自由分发软件。 该
源代码将可在大多数 UNIX 类平台上直接编译并运行。

请参阅 Python 开发者指南的初步上手部分(1) 了解有关获取源代码并进行编译的
更多信息。

   ---------- Footnotes ----------

   (1) https://devguide.python.org/setup/


File: python.info,  Node: 我应如何获取 Python 的文档？,  Next: 我之前从未接触过编程。 哪里有 Python 的教程？,  Prev: 我应如何获取一份 Python 源代码的副本？,  Up: 一般信息

11.1.1.8 我应如何获取 Python 的文档？
.....................................

当前的 Python 稳定版本的标准文档可在 ‘https://docs.python.org/3/’ 查看。
也可在 ‘https://docs.python.org/3/download.html’ 获取PDF、纯文本以及可下
载的 HTML 版本。

文档以 reStructuredText 格式撰写，并使用 Sphinx 文档工具(1) 生成。 文档
的 reStructuredText 源文件是 Python 源代码发布版的一部分。

   ---------- Footnotes ----------

   (1) http://sphinx-doc.org/


File: python.info,  Node: 我之前从未接触过编程。 哪里有 Python 的教程？,  Next: 是否有专门针对 Python 的新闻组或邮件列表？,  Prev: 我应如何获取 Python 的文档？,  Up: 一般信息

11.1.1.9 我之前从未接触过编程。 哪里有 Python 的教程？
......................................................

有许多可选择的教程和书籍。 标准文档中也包含有 *note Python 教程: 120a.。

请参阅 新手指南(1) 以获取针对 Python 编程初学者的信息，包括教程的清单。

   ---------- Footnotes ----------

   (1) https://wiki.python.org/moin/BeginnersGuide


File: python.info,  Node: 是否有专门针对 Python 的新闻组或邮件列表？,  Next: 我应如何获取 Python 的公开测试版本？,  Prev: 我之前从未接触过编程。 哪里有 Python 的教程？,  Up: 一般信息

11.1.1.10 是否有专门针对 Python 的新闻组或邮件列表？
....................................................

有一个新闻组 ‘comp.lang.python’ 和一个邮件列表 python-list(1)。 新闻组和
邮件列表是彼此互通的 —— 如果你可以阅读新闻就不必再订阅邮件列表。
‘comp.lang.python’ 的流量很大，每天会收到数以百计的发帖，Usenet 使用者通
常更擅长处理这样大的流量。

有关新软件发布和活动的公告可以在 comp.lang.python.announce 中找到，这是
个严格管理的低流量列表，每天会收到五个左右的发帖。 可以在 Python 公告邮
件列表(2) 页面进行订阅。

有关其他邮件列表和新闻组的更多信息可以在
‘https://www.python.org/community/lists/’ 找到。

   ---------- Footnotes ----------

   (1) https://mail.python.org/mailman/listinfo/python-list

   (2) https://mail.python.org/mailman/listinfo/python-announce-list


File: python.info,  Node: 我应如何获取 Python 的公开测试版本？,  Next: 我应如何为 Python 提交错误报告和补丁？,  Prev: 是否有专门针对 Python 的新闻组或邮件列表？,  Up: 一般信息

11.1.1.11 我应如何获取 Python 的公开测试版本？
..............................................

可以从 ‘https://www.python.org/downloads/’ 下载 alpha 和 beta 发布版。 所
有发布版都会在 comp.lang.python 和 comp.lang.python.announce 新闻组以及
Python 主页 ‘https://www.python.org/’ 上进行公告；并会推送到 RSS 新闻源
。

你还可以通过 Git 访问 Python 的开发版。 请参阅 Python 开发者指南(1) 了解
详情。

   ---------- Footnotes ----------

   (1) https://devguide.python.org/


File: python.info,  Node: 我应如何为 Python 提交错误报告和补丁？,  Next: 是否有任何公开发表的 Python 相关文章可以供我参考引用？,  Prev: 我应如何获取 Python 的公开测试版本？,  Up: 一般信息

11.1.1.12 我应如何为 Python 提交错误报告和补丁？
................................................

要报告错误或提交补丁，请使用安装于 ‘https://bugs.python.org/’ 上的
Roundup。

你必须拥有一个 Roundup 账号才能报告错误；这样我们就可以在有后续问题时与
你联系。 这也使得 Roundup 能在我们处理所报告的错误时向你发送更新消息。 如
果你之前使用过 SourceForge 向 Python 报告错误，你可以通过 Roundup 的 密
码重置操作(1) 来获取你的 Roundup 密码。

有关 Python 开发流程的更多信息，请参阅 Python 开发者指南(2)。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/user?@template=forgotten

   (2) https://devguide.python.org/


File: python.info,  Node: 是否有任何公开发表的 Python 相关文章可以供我参考引用？,  Next: 是否有任何 Python 相关的书籍？,  Prev: 我应如何为 Python 提交错误报告和补丁？,  Up: 一般信息

11.1.1.13 是否有任何公开发表的 Python 相关文章可以供我参考引用？
................................................................

可能作为参考文献的最好方式还是引用你喜欢的 Python 相关书籍。

第一篇有关 Python 的文章写于 1991 年，现在其内容已经相当过时了。

     Guido van Rossum 与 Jelke de Boer, "使用 Python 编程语言交互式地测
     试远程服务器", CWI 季刊, 第 4 卷, 第 4 期 (1991 年 12 月), 阿姆斯特
     丹, 第 283–303 页。


File: python.info,  Node: 是否有任何 Python 相关的书籍？,  Next: www python org 具体位于世界上的哪个地点？,  Prev: 是否有任何公开发表的 Python 相关文章可以供我参考引用？,  Up: 一般信息

11.1.1.14 是否有任何 Python 相关的书籍？
........................................

是的，相关的书籍很多，还有更多即将发行。 请访问 python.org 的 wiki 页面
‘https://wiki.python.org/moin/PythonBooks’ 获取一份清单。

你也可以到各大在线书店搜索 "Python" 并过滤掉对 Monty Python 的引用；或者
也可以搜索 "Python" 加 "language"。


File: python.info,  Node: www python org 具体位于世界上的哪个地点？,  Next: 为何命名为 Python？,  Prev: 是否有任何 Python 相关的书籍？,  Up: 一般信息

11.1.1.15 www.python.org 具体位于世界上的哪个地点？
...................................................

Python 项目的基础架构分布于世界各地并由 Python 基础架构团队负责管理。 详
情请访问 这里(1)。

   ---------- Footnotes ----------

   (1) http://infra.psf.io


File: python.info,  Node: 为何命名为 Python？,  Next: 我必须喜欢 "Monty Python 的飞行马戏团" 吗？,  Prev: www python org 具体位于世界上的哪个地点？,  Up: 一般信息

11.1.1.16 为何命名为 Python？
.............................

在着手编写 Python 实现的时候，Guido van Rossum 同时还阅读了刚出版的
"Monty Python 的飞行马戏团"(1) 剧本，这是一部自 1970 年代开始播出的 BBC
系列喜剧。 Van Rossum 觉得他需要选择一个简短、独特而又略显神秘的名字，于
是他决定将这个新语言命名为 Python。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Monty_Python


File: python.info,  Node: 我必须喜欢 "Monty Python 的飞行马戏团" 吗？,  Prev: 为何命名为 Python？,  Up: 一般信息

11.1.1.17 我必须喜欢 "Monty Python 的飞行马戏团" 吗？
.....................................................

不必，但这对学习会有帮助。 :)


File: python.info,  Node: 现实世界中的 Python,  Prev: 一般信息,  Up: Python常见问题

11.1.2 现实世界中的 Python
--------------------------

* Menu:

* Python 有多稳定？::
* 有多少人在使用 Python？::
* 有哪些重要的项目是用 Python 开发的？::
* 在未来可以期待 Python 将有什么新进展？::
* 提议对 Python 加入不兼容的更改是否合理？::
* Python 是一种对编程初学者友好的语言吗？::


File: python.info,  Node: Python 有多稳定？,  Next: 有多少人在使用 Python？,  Up: 现实世界中的 Python

11.1.2.1 Python 有多稳定？
..........................

非常稳定。 自 1991 年起大约每隔 6 到 18 个月就会推出新的稳定发布版，这种
状态看来还还持续。 从 3.9 版开始，Python 将会每隔 12 个月推出一个新的主
要发布版 ( PEP 602(1))。

开发者也会推出旧版本的“问题修正”发布版，因此现有发布版的稳定性还会逐步提
升。 问题修正发布版会以版本号第三部分的数字来标示（例如 3.5.3, 3.6.2），
用于稳定性的管理；只有对已知问题的修正会包含在问题修正发布版中，同一系列
的问题修正发布版中的接口确定将会始终保持一致。

最新的稳定版本总是可以在 Python 下载页面(2) 上找到。有两个生产环境可用的
Python 版本： 2.x 和 3.x。 推荐的版本是 3.x，大多数广泛使用的库都支持它
。 虽然 2.x 仍然被广泛使用，但它 在 2020 年 1 月 1 日之后将不再维护(3)。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0602

   (2) https://www.python.org/downloads/

   (3) https://www.python.org/dev/peps/pep-0373/


File: python.info,  Node: 有多少人在使用 Python？,  Next: 有哪些重要的项目是用 Python 开发的？,  Prev: Python 有多稳定？,  Up: 现实世界中的 Python

11.1.2.2 有多少人在使用 Python？
................................

使用者应该数以百万计，但很难获得一个精确的数字。

Python 可以免费下载，因此并不存在销量数据，此外它也可以从许多不同网站获
取，并且包含于许多 Linux 发行版之中，因此下载量统计同样无法完全说明问题
。

comp.lang.python 新闻组非常活跃，但不是所有 Python 用户都会在新闻组发帖
，许多人甚至不会阅读新闻组。


File: python.info,  Node: 有哪些重要的项目是用 Python 开发的？,  Next: 在未来可以期待 Python 将有什么新进展？,  Prev: 有多少人在使用 Python？,  Up: 现实世界中的 Python

11.1.2.3 有哪些重要的项目是用 Python 开发的？
.............................................

请访问 ‘https://www.python.org/about/success’ 查看使用了 Python 的项目列
表。 阅览 历次 Python 会议(1) 的日程纪要可以看到许多不同公司和组织所做的
贡献。

高水准的 Python 项目包括 Mailman 邮件列表管理器(2) 和 Zope 应用服务器
(3)。 多个 Linux 发行版，其中最著名的有 Red Hat(4) 均已使用 Python 来编
写部分或全部的安装程序和系统管理软件。 在内部使用 Python 的大公司包括了
Google, Yahoo 以及 Lucasfilm 等。

   ---------- Footnotes ----------

   (1) https://www.python.org/community/workshops/

   (2) http://www.list.org

   (3) http://www.zope.org

   (4) https://www.redhat.com


File: python.info,  Node: 在未来可以期待 Python 将有什么新进展？,  Next: 提议对 Python 加入不兼容的更改是否合理？,  Prev: 有哪些重要的项目是用 Python 开发的？,  Up: 现实世界中的 Python

11.1.2.4 在未来可以期待 Python 将有什么新进展？
...............................................

请访问 ‘https://www.python.org/dev/peps/’ 查看 Python 增强提议（PEP）。
PEP 是为 Python 加入某种新特性的提议进行描述的设计文档，其中会提供简明的
技术规格说明与基本原理。 可以查找标题为“Python X.Y Release Schedule”的
PEP，其中 X.Y 是某个尚未公开发布的版本。

新版本的开发会在 python-dev 邮件列表(1) 中进行讨论。

   ---------- Footnotes ----------

   (1) https://mail.python.org/mailman/listinfo/python-dev/


File: python.info,  Node: 提议对 Python 加入不兼容的更改是否合理？,  Next: Python 是一种对编程初学者友好的语言吗？,  Prev: 在未来可以期待 Python 将有什么新进展？,  Up: 现实世界中的 Python

11.1.2.5 提议对 Python 加入不兼容的更改是否合理？
.................................................

通常来说是不合理的。 世界上已存在的 Python 代码数以亿计，因此，任何对该
语言的更改即便仅会使得现有程序中极少的一部分失效也是难以令人接受的。 就
算你可以提供一个转换程序，也仍然存在需要更新全部文档的问题；另外还有大量
已出版的 Python 书籍，我们不希望让它们在一瞬间全部变成废纸。

如果必须更改某个特性，则应该提供渐进式的升级路径。 PEP 5(1) 描述了引入向
后不兼容的更改所需遵循的流程，以尽可能减少对用户的干扰。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0005


File: python.info,  Node: Python 是一种对编程初学者友好的语言吗？,  Prev: 提议对 Python 加入不兼容的更改是否合理？,  Up: 现实世界中的 Python

11.1.2.6 Python 是一种对编程初学者友好的语言吗？
................................................

有的。

从过程式、静态类型的编程语言例如 Pascal, C 或者 C++ 以及 Java 的某一子集
开始引导学生入门仍然是常见的做法。 但以 Python 作为第一种编程语言进行学
习对学生可能更有利。Python 具有非常简单和一致的语法和庞大的标准库，而且
最重要的是，在编程入门教学中使用 Python 可以让学生专注于更重要的编程技能
，例如问题分解与数据类型设计。 使用 Python，可以快速向学生介绍基本概念例
如循环与过程等。 他们甚至有可能在第一次课里就开始接触用户自定义对象。

对于之前从未接触过编程的学生来说，使用静态类型语言会感觉不够自然。 这会
给学生带来必须掌握的额外复杂性，并减慢教学的进度。 学生需要尝试像计算机
一样思考，分解问题，设计一致的接口并封装数据。 虽然从长远来看，学习和使
用一种静态类型语言是很重要的，但这并不是最适宜在学生的第一次编程课上就进
行探讨的主题。

还有许多其他方面的特点使得 Python 成为很好的入门语言。 像 Java 一样，
Python 拥有一个庞大的标准库，因此可以在课程非常早期的阶段就给学生布置一
些 `实用' 的编程项目。 编程作业不必仅限于标准四则运算和账目检查程序。 通
过使用标准库，学生可以在学习编程基础知识的同时开发真正的应用，从而获得更
大的满足感。 使用标准库还能使学生了解代码重用的概念。 而像 PyGame 这样的
第三方模块同样有助于扩大学生的接触领域。

Python 的解释器使学生能够在编程时测试语言特性。 他们可以在一个窗口中输入
程序源代码的同时开启一个解释器运行窗口。 如果他们不记得列表有哪些方法，
他们这以这样做:

     >>> L = []
     >>> dir(L)
     ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
     '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
     '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__',
     '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__',
     '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
     '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
     '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear',
     'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
     'reverse', 'sort']
     >>> [d for d in dir(L) if '__' not in d]
     ['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

     >>> help(L.append)
     Help on built-in function append:

     append(...)
         L.append(object) -> None -- append object to end

     >>> L.append(1)
     >>> L
     [1]

通过使用解释器，学生编写程序时参考文档总是能伴随在他们身边。

Python 还拥有很好的 IDE。 IDLE 是一个跨平台的 Python IDE，它基于 Tkinter
库，使用 Python 语言编写。 PythonWin 是一个 Windows 专属的 IDE。 Emacs 用
户将高兴地了解到 Emacs 具有非常好的 Python 模式。 所有这些编程环境都提供
语法高亮，自动缩进以及在编写代码时使用交互式解释器等功能。 请访问 Python
wiki(1) 查看 Python 编程环境的完整列表。

如果你想要讨论 Python 在教育中的使用，你可能会有兴趣加入 edu-sig 邮件列
表(2)。

   ---------- Footnotes ----------

   (1) https://wiki.python.org/moin/PythonEditors

   (2) https://www.python.org/community/sigs/current/edu-sig


File: python.info,  Node: 编程常见问题,  Next: 设计和历史常见问题,  Prev: Python常见问题,  Up: Python 常见问题

11.2 编程常见问题
=================

* Menu:

* 一般问题::
* 核心语言::
* 数字和字符串::
* 性能: 性能<4>.
* 序列（元组/列表）::
* 对象::
* 模块: 模块<3>.


File: python.info,  Node: 一般问题,  Next: 核心语言,  Up: 编程常见问题

11.2.1 一般问题
---------------

* Menu:

* Python 有没有提供断点与单步调试等功能的，源码层次的调试器？::
* 是否有能帮助寻找漏洞或执行静态分析的工具？::
* 我如何能够通过一个 Python 脚本创建一个独立运行的二进制文件？::
* 是否有 Python 程序规范代码标准或风格指南？::


File: python.info,  Node: Python 有没有提供断点与单步调试等功能的，源码层次的调试器？,  Next: 是否有能帮助寻找漏洞或执行静态分析的工具？,  Up: 一般问题

11.2.1.1 Python 有没有提供断点与单步调试等功能的，源码层次的调试器？
....................................................................

有的。

以下介绍了一些 Python 的调试器，内置函数 *note breakpoint(): 302. 允许你
使用其中的任何一种。

pdb 模块是一个简单但是够用的控制台模式 Python 调试器。 它是标准 Python 库
的一部分，并且 *note 已收录于库参考手册: ca.。 你也可以通过使用 pdb 代码
作为样例来编写你自己的调试器。

作为标准 Python 发行版附带组件的 IDLE 交互式环境（通常位于
Tools/scripts/idle）中包含一个图形化的调试器。

PythonWin 是一个包括基于 pdb 的 GUI 调试器的 Python IDE。 PythonWin 的调
试器会为断点加上颜色，并具有许多很棒的特性，例如调试非 PythonWin 程序等
。 PythonWin 是 pywin32(1) 项目的组成部分，也是 ActivePython(2) 发行版的
组成部分。

Eric(3) 是一个基于PyQt和Scintilla编辑组件构建的IDE。

trepan3k(4) 是一个类似 gdb 的调试器。

Visual Studio Code(5) 是一个带有集成了版本控制软件的调试工具的 IDE。

有许多商业Python IDE包括图形调试器。他们包括：

   * Wing IDE(6)

   * Komodo IDE(7)

   * PyCharm(8)

   ---------- Footnotes ----------

   (1) https://github.com/mhammond/pywin32

   (2) https://www.activestate.com/products/python/

   (3) http://eric-ide.python-projects.org/

   (4) https://github.com/rocky/python3-trepan/

   (5) https://code.visualstudio.com/

   (6) https://wingware.com/

   (7) https://www.activestate.com/products/komodo-ide/

   (8) https://www.jetbrains.com/pycharm/


File: python.info,  Node: 是否有能帮助寻找漏洞或执行静态分析的工具？,  Next: 我如何能够通过一个 Python 脚本创建一个独立运行的二进制文件？,  Prev: Python 有没有提供断点与单步调试等功能的，源码层次的调试器？,  Up: 一般问题

11.2.1.2 是否有能帮助寻找漏洞或执行静态分析的工具？
...................................................

有的。

Pylint(1) 和 Pyflakes(2) 可进行基本检查来帮助你尽早捕捉漏洞。

静态类型检查器，例如 Mypy(3) 、 Pyre(4) 和 Pytype(5) 可以检查Python源代
码中的类型提示。

   ---------- Footnotes ----------

   (1) https://www.pylint.org/

   (2) https://github.com/PyCQA/pyflakes

   (3) http://mypy-lang.org/

   (4) https://pyre-check.org/

   (5) https://github.com/google/pytype


File: python.info,  Node: 我如何能够通过一个 Python 脚本创建一个独立运行的二进制文件？,  Next: 是否有 Python 程序规范代码标准或风格指南？,  Prev: 是否有能帮助寻找漏洞或执行静态分析的工具？,  Up: 一般问题

11.2.1.3 我如何能够通过一个 Python 脚本创建一个独立运行的二进制文件？
.....................................................................

如果你想要的只是一个独立的程序，用户可以下载和运行而不必先安装Python发行
版，你就不需要将Python编译成C代码。有许多工具可以确定程序所需的模块集，
并将这些模块与Python二进制文件绑定在一起以生成单个可执行文件。

一种是使用冻结工具，它包含在Python源代码树 ‘Tools/freeze’ 中。它将
Python字节代码转换为C数组；一个C编译器，你可以将所有模块嵌入到一个新程序
中，然后将其与标准Python模块链接。

它的工作原理是递归扫描源代码以获取import语句（两种形式），并在标准
Python路径和源目录（用于内置模块）中查找模块。 然后，它将用Python编写的
模块的字节码转换为C代码（可以使用编组模块转换为代码对象的数组初始化器）
，并创建一个定制的配置文件，该文件仅包含程序中实际使用的内置模块。 然后
，它编译生成的C代码并将其与Python解释器的其余部分链接，以形成一个独立的
二进制文件，其行为与你的脚本完全相同。

显然，freeze 需要一个 C 编译器。 还有一些其他实用工具则不需要:

   * py2exe(1) 用于生成 Windows 版二进制可执行文件

   * py2app(2) 用于生成 Mac OS X 版二进制可执行文件

   * cx_Freeze(3) 用于生成跨平台的二进制可执行文件

   ---------- Footnotes ----------

   (1) http://www.py2exe.org/

   (2) https://github.com/ronaldoussoren/py2app

   (3) https://cx-freeze.readthedocs.io/en/latest/


File: python.info,  Node: 是否有 Python 程序规范代码标准或风格指南？,  Prev: 我如何能够通过一个 Python 脚本创建一个独立运行的二进制文件？,  Up: 一般问题

11.2.1.4 是否有 Python 程序规范代码标准或风格指南？
...................................................

有的。 请参阅标准库模块所要求的代码风格描述文档 PEP 8(1) 。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0008


File: python.info,  Node: 核心语言,  Next: 数字和字符串,  Prev: 一般问题,  Up: 编程常见问题

11.2.2 核心语言
---------------

* Menu:

* 当变量有值时，为什么会出现UnboundLocalError？::
* Python中的局部变量和全局变量有哪些规则？::
* 为什么在具有不同值的循环中定义的lambdas都返回相同的结果？::
* 如何跨模块共享全局变量？::
* 导入模块的“最佳实践”是什么？::
* 为什么对象之间会共享默认值？::
* 如何将可选参数或关键字参数从一个函数传递到另一个函数？::
* 形参和实参之间有什么区别？::
* 为什么更改列表 'y' 也会更改列表 'x'？::
* 如何编写带输出参数的函数（通过引用调用）？::
* 如何在Python中创建高阶函数？::
* 如何在Python中复制对象？::
* 如何找到对象的方法或属性？::
* 我的代码如何才能发现对象的名称？::
* 逗号运算符的优先级是什么？::
* 是否有与 C 的 "?;" 三目运算符等价的东西？: 是否有与 C 的 "? " 三目运算符等价的东西？.
* 是否可以用Python编写混淆的单行程序?::
* 函数参数列表中的斜杠（/）是什么意思？::


File: python.info,  Node: 当变量有值时，为什么会出现UnboundLocalError？,  Next: Python中的局部变量和全局变量有哪些规则？,  Up: 核心语言

11.2.2.1 当变量有值时，为什么会出现UnboundLocalError？
......................................................

通过在函数体中的某处添加赋值语句，导致以前正常工作的代码被修改而得到
UnboundLocalError 会令人感到意外。

以下代码：

     >>> x = 10
     >>> def bar():
     ...     print(x)
     >>> bar()
     10

正常工作，但是以下代码

     >>> x = 10
     >>> def foo():
     ...     print(x)
     ...     x += 1

会得到一个 UnboundLocalError ：

     >>> foo()
     Traceback (most recent call last):
       ...
     UnboundLocalError: local variable 'x' referenced before assignment

这是因为当你对作用域中的变量进行赋值时，该变量将成为该作用域的局部变量，
并在外部作用域中隐藏任何类似命名的变量。由于foo中的最后一个语句为 ‘x’ 分
配了一个新值，编译器会将其识别为局部变量。因此，当先前的 ‘print(x)’ 尝试
打印未初始化的局部变量时会导致错误。

在上面的示例中，你可以通过将其声明为全局来访问外部作用域变量：

     >>> x = 10
     >>> def foobar():
     ...     global x
     ...     print(x)
     ...     x += 1
     >>> foobar()
     10

这个显式声明是必需的，以便提醒你（与类和实例变量的表面类似情况不同），你
实际上是在外部作用域中修改变量的值

     >>> print(x)
     11

你可以使用 *note nonlocal: c47. 关键字在嵌套作用域中执行类似的操作：

     >>> def foo():
     ...    x = 10
     ...    def bar():
     ...        nonlocal x
     ...        print(x)
     ...        x += 1
     ...    bar()
     ...    print(x)
     >>> foo()
     10
     11


File: python.info,  Node: Python中的局部变量和全局变量有哪些规则？,  Next: 为什么在具有不同值的循环中定义的lambdas都返回相同的结果？,  Prev: 当变量有值时，为什么会出现UnboundLocalError？,  Up: 核心语言

11.2.2.2 Python中的局部变量和全局变量有哪些规则？
.................................................

在Python中，仅在函数内引用的变量是隐式全局变量。如果在函数体内的任何位置
为变量赋值，则除非明确声明为全局，否则将其视为局部值。

虽然起初有点令人惊讶，但片刻考虑就可以解释。一方面，要求 *note global:
1254. 表示已分配的变量可以防止意外的副作用。另一方面，如果所有全局引用都
需要 ‘global’ ，那么你一直都在使用 ‘global’ 。你必须将对内置函数或导入模
块的组件的每个引用声明为全局。这种杂乱会破坏 ‘global’ 声明用于识别副作用
的有用性。


File: python.info,  Node: 为什么在具有不同值的循环中定义的lambdas都返回相同的结果？,  Next: 如何跨模块共享全局变量？,  Prev: Python中的局部变量和全局变量有哪些规则？,  Up: 核心语言

11.2.2.3 为什么在具有不同值的循环中定义的lambdas都返回相同的结果？
..................................................................

假设你使用for循环来定义几个不同的 lambda （甚至是普通函数），例如：:

     >>> squares = []
     >>> for x in range(5):
     ...     squares.append(lambda: x**2)

这给你一个包含5个lambdas的列表，它们计算 ‘x**2’ 。你可能会期望，当它们被
调用时，它们将分别返回 ‘0’ 、 ‘1’ 、 ‘4’ 、 ‘9’ 和 ‘16’ 。但是，当你真正
尝试时，你会看到它们都返回 ‘16’ 。:

     >>> squares[2]()
     16
     >>> squares[4]()
     16

发生这种情况是因为 ‘x’ 不是lambdas的内部变量，而是在外部作用域中定义，并
且在调用lambda时访问它 - 而不是在定义它时。 在循环结束时， ‘x’ 的值是
‘4’ ，所以所有的函数现在返回 ‘4**2’ ，即 ‘16’ 。你还可以通过更改 ‘x’ 的
值来验证这一点，并查看lambdas的结果如何变化:

     >>> x = 8
     >>> squares[2]()
     64

为了避免这种情况，你需要将值保存在lambdas的局部变量中，这样它们就不依赖
于全局‘‘x‘‘ 的值

     >>> squares = []
     >>> for x in range(5):
     ...     squares.append(lambda n=x: n**2)

这里， ‘n=x’ 在lambda本地创建一个新的变量 ‘n’ ，并在定义lambda时计算，使
它具有与 ‘x’ 在循环中该点相同的值。这意味着 ‘n’ 的值在第一个lambda中为
‘0’ ，在第二个lambda中为 ‘1’ ，在第三个中为 ‘2’ ，依此类推。因此每个
lambda现在将返回正确的结果:

     >>> squares[2]()
     4
     >>> squares[4]()
     16

请注意，这种行为并不是lambda所特有的，但也适用于常规函数。


File: python.info,  Node: 如何跨模块共享全局变量？,  Next: 导入模块的“最佳实践”是什么？,  Prev: 为什么在具有不同值的循环中定义的lambdas都返回相同的结果？,  Up: 核心语言

11.2.2.4 如何跨模块共享全局变量？
.................................

在单个程序中跨模块共享信息的规范方法是创建一个特殊模块（通常称为config或
cfg）。只需在应用程序的所有模块中导入配置模块；然后该模块可用作全局名称
。因为每个模块只有一个实例，所以对模块对象所做的任何更改都会在任何地方反
映出来。 例如：

config.py:

     x = 0   # Default value of the 'x' configuration setting

mod.py:

     import config
     config.x = 1

main.py:

     import config
     import mod
     print(config.x)

请注意，出于同样的原因，使用模块也是实现Singleton设计模式的基础。


File: python.info,  Node: 导入模块的“最佳实践”是什么？,  Next: 为什么对象之间会共享默认值？,  Prev: 如何跨模块共享全局变量？,  Up: 核心语言

11.2.2.5 导入模块的“最佳实践”是什么？
.....................................

通常，不要使用 ‘from modulename import *’ 。这样做会使导入器的命名空间变
得混乱，并且使得连接器更难以检测未定义的名称。

在文件的顶部导入模块。这样做可以清楚地了解代码所需的其他模块，并避免了模
块名称是否在范围内的问题。每行导入一个模块可以轻松添加和删除导入的模块，
但每行导入多个模块会占用更少的屏幕空间。

如果按以下顺序导入模块，这是一种很好的做法：

  1. 标准库模块 – 例如： ‘sys’, ‘os’, ‘getopt’, ‘re’

  2. 第三方库模块（安装在Python的site-packages目录中的任何内容） – 例如
     mx.DateTime，ZODB，PIL.Image等

  3. 本地开发的模块

有时需要将模块导入语句移动到函数或类里面，以避免循环导入问题。Gordon
McMillan 说：

     当两个模块都使用 "import <module>" 的导入形式时，循环导入就可以了。
     但是当第 2 个模块想从第 1 个模块中获取一个名称 ("from module import
     name") 并且导入位于顶层时，就会出错。 这是因为第 1 个模块中的名称还
     不可用，因为第 1 个模块正在忙着导入第 2 个模块。

在这种情况下，如果第二个模块仅用于一个函数，则可以轻松地将模块导入语句移
动到该函数中。调用导入时，第一个模块将完成初始化，第二个模块可以进行导入
。

如果某些模块是特定于平台的，则可能还需要将模块导入语句移出顶级代码。在这
种情况下，甚至可能无法导入文件顶部的所有模块。在这种情况下，在相应的特定
于平台的代码中导入正确的模块是一个很好的选择。

只有当需要解决诸如避免循环导入或试图减少模块初始化时间的问题时，才可以将
导入移动到本地范围，例如在函数定义中。如果根据程序的执行方式，许多导入是
不必要的，这种技术尤其有用。如果仅在某个函数中使用模块，您还可能希望将导
入移到该函数中。请注意，第一次加载模块可能会因为模块的一次初始化而代价高
昂，但多次加载模块实际上是免费的，只需进行几次字典查找。即使模块名称超出
了作用域，模块也可能在 *note sys.modules: f36. 中可用。


File: python.info,  Node: 为什么对象之间会共享默认值？,  Next: 如何将可选参数或关键字参数从一个函数传递到另一个函数？,  Prev: 导入模块的“最佳实践”是什么？,  Up: 核心语言

11.2.2.6 为什么对象之间会共享默认值？
.....................................

这种类型的缺陷通常会惹恼新手程序员。考虑这个函数

     def foo(mydict={}):  # Danger: shared reference to one dict for all calls
         ... compute something ...
         mydict[key] = value
         return mydict

第一次调用此函数时，‘mydict’ 包含一项。第二次，‘mydict’ 包含两项，因为当
‘foo()’ 开始执行时， ‘mydict’ 中已经有一项了。

函数调用经常被期望为默认值创建新的对象。 但实际情况并非如此。 默认值会在
函数定义时一次性地创建。 如果对象发生改变，就如本示例中的字典那样，则对
函数的后续调用将会引用这个被改变的对象。

按照定义，不可变对象例如数字、字符串、元组和 ‘None’ 因为不可变所以是安全
的。 对可变对象例如字典、列表和类实例的改变则可能造成迷惑。

由于这一特性，在编程中应遵循的一项好习惯是不使用可变对象作为默认值。 而
应使用 ‘None’ 作为默认值和函数中的值，检查值为 ‘None’ 的形参并创建相应的
列表、字典或其他可变对象。 例如，不要这样写:

     def foo(mydict={}):
         ...

而要这样写:

     def foo(mydict=None):
         if mydict is None:
             mydict = {}  # create a new dict for local namespace

这一特性有时会很有用处。 当你有一个需要进行大量耗时计算的函数时，一个常
见技巧是将每次调用函数的参数和结果值缓存起来，并在同样的值被再次请求时返
回缓存的值。 这称为“记忆”，具体实现方式可以是这样的:

     # Callers can only provide two parameters and optionally pass _cache by keyword
     def expensive(arg1, arg2, *, _cache={}):
         if (arg1, arg2) in _cache:
             return _cache[(arg1, arg2)]

         # Calculate the value
         result = ... expensive computation ...
         _cache[(arg1, arg2)] = result           # Store result in the cache
         return result

你也可以使用包含一个字典的全局变量而不使用参数默认值；这完全取决于个人偏
好。


File: python.info,  Node: 如何将可选参数或关键字参数从一个函数传递到另一个函数？,  Next: 形参和实参之间有什么区别？,  Prev: 为什么对象之间会共享默认值？,  Up: 核心语言

11.2.2.7 如何将可选参数或关键字参数从一个函数传递到另一个函数？
...............................................................

使用函数参数列表中的 ‘*’ 和 ‘**’ 说明符收集参数;这会将位置参数作为元组，
将关键字参数作为字典。然后，您可以使用 ‘*’ 和 ‘**’ 调用另一个函数时传递
这些参数：

     def f(x, *args, **kwargs):
         ...
         kwargs['width'] = '14.3c'
         ...
         g(x, *args, **kwargs)


File: python.info,  Node: 形参和实参之间有什么区别？,  Next: 为什么更改列表 'y' 也会更改列表 'x'？,  Prev: 如何将可选参数或关键字参数从一个函数传递到另一个函数？,  Up: 核心语言

11.2.2.8 形参和实参之间有什么区别？
...................................

*note 形参: 153b. 是指出现在函数定义中的名称，而 *note 实参: 1532. 则是
在调用函数时实际传入的值。 形参定义了一个函数能接受何种类型的实参。 例如
，对于以下函数定义:

     def func(foo, bar=None, **kwargs):
         pass

`foo', `bar' 和 `kwargs' 是 ‘func’ 的形参。 但是，在调用 ‘func’ 时，例如
：

     func(42, bar=314, extra=somevar)

实际的值 ‘42’, ‘314’ 和 ‘somevar’ 则是实参。


File: python.info,  Node: 为什么更改列表 'y' 也会更改列表 'x'？,  Next: 如何编写带输出参数的函数（通过引用调用）？,  Prev: 形参和实参之间有什么区别？,  Up: 核心语言

11.2.2.9 为什么更改列表 ’y’ 也会更改列表 ’x’？
..............................................

如果你编写的代码就像下面一样：

     >>> x = []
     >>> y = x
     >>> y.append(10)
     >>> y
     [10]
     >>> x
     [10]

你可能想知道为什么追加一个元素也改变了x。

产生这种结果有两个因素：

  1. 变量只是指向具体对象的名称。 执行 ‘y = x’ 并不会为列表创建一个副本
     —— 它只是创建了一个新变量 ‘y’ 指向 ‘x’ 所指向的同一对象。 这意味着
     只存在一个对象（列表），‘x’ 和 ‘y’ 都是对它的引用。

  2. 列表属于 *note mutable: 123a. 对象，这意味着你可以改变它的内容。

在调用 ‘append()’ 之后，这个可变对象的内容由 ‘[]’ 变为 ‘[10]’。 由于两个
变量都指向同一对象，因此使用任何一个名称所访问到的都是修改后的值 ‘[10]’。

如果我们改为将不可变对象赋值给 ‘x’:

     >>> x = 5  # ints are immutable
     >>> y = x
     >>> x = x + 1  # 5 can't be mutated, we are creating a new object here
     >>> x
     6
     >>> y
     5

我们可以看到在此情况下 ‘x’ 和 ‘y’ 就不再相等了。 这是因为整数是 *note
immutable: 1232. 对象，当我们执行 ‘x = x + 1’ 时我们并不是改变了 ‘5’ 这
个对象的值；而是创建了一个新的对象 (整数 ‘6’) 并将其赋值给 ‘x’ (也就是改
变了 ‘x’ 所指向的对象)。 在赋值之后我们就有了两个对象 (整数 ‘6’ 和 ‘5’)
以及分别指向它们的两个变量 (‘x’ 现在指向 ‘6’ 而 ‘y’ 仍然指向 ‘5’)。

某些操作 (例如 ‘y.append(10)’ 和 ‘y.sort()’) 是改变原对象，而看上去相似
的另一些操作 (例如 ‘y = y + [10]’ 和 ‘sorted(y)’) 则是创建新对象。 通常
在 Python 中 (以及在标准库的所有代码中) 会改变原对象的方法将返回 ‘None’
以帮助避免混淆这两种不同类型的操作。 因此如果你错误地使用了 ‘y.sort()’ 并
期望它将返回一个经过排序的 ‘y’ 的副本，你得到的结果将会是 ‘None’，这将导
致你的程序产生一个容易诊断的错误。

但是，还存在一类操作，不同的类型执行相同的操作会有不同的行为：那就是增强
赋值运算符。 例如，‘+=’ 会原地改变列表，但不会改变元组或整数 (‘a_list +=
[1, 2, 3]’ 与 ‘a_list.extend([1, 2, 3])’ 一样都会改变 ‘a_list’，而
‘some_tuple += (1, 2, 3)’ 和 ‘some_int += 1’ 则会创建新的对象)。

换而言之：

   * 如果我们有一个可变对象 (*note list: 263, *note dict: 1b9, *note
     set: b77. 等等)，我们可以使用某些特定的操作来改变它，所有指向它的变
     量都会显示它的改变。

   * 如果我们有一个不可变对象 (*note str: 339, *note int: 185, *note
     tuple: 486. 等等)，所有指向它的变量都将显示相同样的值，但凡是会改变
     这个值的操作将总是返回一个新对象。

如果你想知道两个变量是否指向相同的对象，你可以使用 *note is: eca. 运算符
，或内置函数 *note id(): d8e.。


File: python.info,  Node: 如何编写带输出参数的函数（通过引用调用）？,  Next: 如何在Python中创建高阶函数？,  Prev: 为什么更改列表 'y' 也会更改列表 'x'？,  Up: 核心语言

11.2.2.10 如何编写带输出参数的函数（通过引用调用）？
....................................................

请记住在 Python 中参数是通过赋值来传递的。 由于赋值只是创建了对象的引用
，因此在调用者和被调用者的参数名称之间没有别名，所以本身是没有按引用调用
的。 你可以通过多种方式实现所需的效果。

  1. 通过返回一个结果元组:

          >>> def func1(a, b):
          ...     a = 'new-value'        # a and b are local names
          ...     b = b + 1              # assigned to new objects
          ...     return a, b            # return new values
          ...
          >>> x, y = 'old-value', 99
          >>> func1(x, y)
          ('new-value', 100)

     这几乎总是最清晰明了的解决方案。

  2. 通过使用全局变量。 这种方式不是线程安全的，而且也不受推荐。

  3. 通过传递一个可变 (即可原地修改的) 对象:

          >>> def func2(a):
          ...     a[0] = 'new-value'     # 'a' references a mutable list
          ...     a[1] = a[1] + 1        # changes a shared object
          ...
          >>> args = ['old-value', 99]
          >>> func2(args)
          >>> args
          ['new-value', 100]

  4. 通过传递一个会被改变的字典:

          >>> def func3(args):
          ...     args['a'] = 'new-value'     # args is a mutable dictionary
          ...     args['b'] = args['b'] + 1   # change it in-place
          ...
          >>> args = {'a': 'old-value', 'b': 99}
          >>> func3(args)
          >>> args
          {'a': 'new-value', 'b': 100}

  5. 或者在一个类实例中捆绑值:

          >>> class Namespace:
          ...     def __init__(self, /, **args):
          ...         for key, value in args.items():
          ...             setattr(self, key, value)
          ...
          >>> def func4(args):
          ...     args.a = 'new-value'        # args is a mutable Namespace
          ...     args.b = args.b + 1         # change object in-place
          ...
          >>> args = Namespace(a='old-value', b=99)
          >>> func4(args)
          >>> vars(args)
          {'a': 'new-value', 'b': 100}

     几乎没有任何适当理由将问题如此复杂化。

你的最佳选择是返回一个包含多个结果的元组。


File: python.info,  Node: 如何在Python中创建高阶函数？,  Next: 如何在Python中复制对象？,  Prev: 如何编写带输出参数的函数（通过引用调用）？,  Up: 核心语言

11.2.2.11 如何在Python中创建高阶函数？
......................................

你有两种选择：使用嵌套作用域，或者使用可调用对象。 例如，假设你想要定义
‘linear(a,b)’ 使其返回一个函数 ‘f(x)’ 来设计 ‘a*x+b’ 的值。 可以使用以下
嵌套作用域:

     def linear(a, b):
         def result(x):
             return a * x + b
         return result

或使用一个可调用对象:

     class linear:

         def __init__(self, a, b):
             self.a, self.b = a, b

         def __call__(self, x):
             return self.a * x + self.b

在两种情况下，:

     taxes = linear(0.3, 2)

都会给出一个可调用对象，使得 ‘taxes(10e6) == 0.3 * 10e6 + 2’.

可调用对象方式的缺点是速度略慢且生成的代码略长。 但是，请注意一组可调用
对象能够通过继承来共享签名:

     class exponential(linear):
         # __init__ inherited
         def __call__(self, x):
             return self.a * (x ** self.b)

对象可以封装多个方法的状态:

     class counter:

         value = 0

         def set(self, x):
             self.value = x

         def up(self):
             self.value = self.value + 1

         def down(self):
             self.value = self.value - 1

     count = counter()
     inc, dec, reset = count.up, count.down, count.set

这里 ‘inc()’, ‘dec()’ 和 ‘reset()’ 将表现为共享同一计数变量的多个函数。


File: python.info,  Node: 如何在Python中复制对象？,  Next: 如何找到对象的方法或属性？,  Prev: 如何在Python中创建高阶函数？,  Up: 核心语言

11.2.2.12 如何在Python中复制对象？
..................................

一般来说，通常情况下请尝试 *note copy.copy(): 3d3. 或 *note
copy.deepcopy(): 3d4.。 不是所有对象都可以复制，但多数都是可以的。

某些对象可以方便地复制。 例如字典具有 *note copy(): 44e. 方法:

     newdict = olddict.copy()

序列可以通过切片来复制:

     new_l = l[:]


File: python.info,  Node: 如何找到对象的方法或属性？,  Next: 我的代码如何才能发现对象的名称？,  Prev: 如何在Python中复制对象？,  Up: 核心语言

11.2.2.13 如何找到对象的方法或属性？
....................................

对于一个用户自定义类的实例 x，‘dir(x)’ 将返回一个按字母顺序排序的包含实
例属性和方法及其类所定义的属性名称的列表。


File: python.info,  Node: 我的代码如何才能发现对象的名称？,  Next: 逗号运算符的优先级是什么？,  Prev: 如何找到对象的方法或属性？,  Up: 核心语言

11.2.2.14 我的代码如何才能发现对象的名称？
..........................................

通常来说是做不到的，因为对象并不真正具有名称。 在本质上，赋值总是会将一
个名称绑定到某个值；‘def’ 和 ‘class’ 语句也是如此，但在这种情况下该值是
一个可调用对象。 考虑以下代码:

     >>> class A:
     ...     pass
     ...
     >>> B = A
     >>> a = B()
     >>> b = a
     >>> print(b)
     <__main__.A object at 0x16D07CC>
     >>> print(a)
     <__main__.A object at 0x16D07CC>

不严谨地讲，该类有一个名称：虽然它是绑定了两个名称并通过名称 B 发起调用
，所创建的实例仍然被视为类 A 的一个实例。 但是实例的名称则无法确定地说是
a 或是 b，因为有两个名称被绑定到了同一个值。

一般来说你的代码应该没有必要“知道”特定值的名称。 除非你是在编写特殊的内
省程序，出现这样的问题通常表明如果改变方式可能会更有利。

在 comp.lang.python 中，Fredrik Lundh 在回答这样的问题时曾经给出过一个绝
佳的类比：

     跟你找出在你家门廊见到的某只猫的名字所用的办法一样：猫（对象）自己
     无法告诉你它的名字，它根本就不在乎 —— 所以找出它叫什么名字的唯一办
     法是问你的所有邻居（命名空间）那是不是他们的猫（对象）……

     ……并且如果你发现它有很多名字或根本没有名字也不必觉得惊讶！


File: python.info,  Node: 逗号运算符的优先级是什么？,  Next: 是否有与 C 的 "? " 三目运算符等价的东西？,  Prev: 我的代码如何才能发现对象的名称？,  Up: 核心语言

11.2.2.15 逗号运算符的优先级是什么？
....................................

逗号在 Python 中不是运算符。 考虑这个例子:

     >>> "a" in "b", "a"
     (False, 'a')

由于逗号不是运算符而是表达式之间的分隔符，以上代码的含义就相当于:

     ("a" in "b"), "a"

而不是:

     "a" in ("b", "a")

对于各种赋值运算符 (‘=’, ‘+=’ 等) 来说同样如此。 它们并不是真正的运算符
而是赋值语句中的语法分隔符。


File: python.info,  Node: 是否有与 C 的 "? " 三目运算符等价的东西？,  Next: 是否可以用Python编写混淆的单行程序?,  Prev: 逗号运算符的优先级是什么？,  Up: 核心语言

11.2.2.16 是否有与 C 的 "?:" 三目运算符等价的东西？
...................................................

有的。 相应语法如下:

     [on_true] if [expression] else [on_false]

     x, y = 50, 25
     small = x if x < y else y

在 Python 2.5 引入此语法之前，常见的做法是使用逻辑运算符:

     [expression] and [on_true] or [on_false]

然而这种做法并不保险，因为当 `on_true' 具有布尔假值时将会给出错误的结果
。 所以，使用 ‘... if ... else ...’ 形式总是会更好。


File: python.info,  Node: 是否可以用Python编写混淆的单行程序?,  Next: 函数参数列表中的斜杠（/）是什么意思？,  Prev: 是否有与 C 的 "? " 三目运算符等价的东西？,  Up: 核心语言

11.2.2.17 是否可以用Python编写混淆的单行程序?
.............................................

可以。通常是在 *note lambda: c37. 中嵌套 ‘lambda’ 来实现的。请参阅以下三
个来自 Ulf Bartelt 的示例代码：

     from functools import reduce

     # Primes < 1000
     print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
     map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))

     # First 10 Fibonacci numbers
     print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
     f(x,f), range(10))))

     # Mandelbrot set
     print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
     Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
     Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
     i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
     >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
     64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
     ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
     #    \___ ___/  \___ ___/  |   |   |__ lines on screen
     #        V          V      |   |______ columns on screen
     #        |          |      |__________ maximum of "iterations"
     #        |          |_________________ range on y axis
     #        |____________________________ range on x axis

请不要在家里尝试，骚年！


File: python.info,  Node: 函数参数列表中的斜杠（/）是什么意思？,  Prev: 是否可以用Python编写混淆的单行程序?,  Up: 核心语言

11.2.2.18 函数参数列表中的斜杠（/）是什么意思？
...............................................

函数参数列表中的斜杠表示在它之前的形参是仅限位置形参。 仅限位置形参没有
外部可用的名称。 在调用接受仅限位置形参的函数时，参数只会基于它们的位置
被映射到形参。 例如，*note divmod(): 153. 是一个接受仅限位置形参的函数。
它的文档是这样的:

     >>> help(divmod)
     Help on built-in function divmod in module builtins:

     divmod(x, y, /)
         Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.

在形参列表末尾的斜杠意味着两个形参都是仅限位置形参。 因此，附带关键字参
数调用 *note divmod(): 153. 将会导致报错:

     >>> divmod(x=3, y=4)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: divmod() takes no keyword arguments


File: python.info,  Node: 数字和字符串,  Next: 性能<4>,  Prev: 核心语言,  Up: 编程常见问题

11.2.3 数字和字符串
-------------------

* Menu:

* 如何指定十六进制和八进制整数？::
* 为什么-22 // 10返回-3？::
* 如何将字符串转换为数字？::
* 如何将数字转换为字符串？::
* 如何修改字符串？::
* 如何使用字符串调用函数/方法？::
* 是否有与Perl 的chomp() 等效的方法，用于从字符串中删除尾随换行符？: 是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？.
* 是否有 scanf() 或 sscanf() 的对应物？: 是否有 scanf 或 sscanf 的对应物？.
* 'UnicodeDecodeError' 或 'UnicodeEncodeError' 错误是什么意思？::


File: python.info,  Node: 如何指定十六进制和八进制整数？,  Next: 为什么-22 // 10返回-3？,  Up: 数字和字符串

11.2.3.1 如何指定十六进制和八进制整数？
.......................................

要指定一个八进制数码，则在八进制值之前加一个零和一个小写或大写字母 "o" 作
为前缀。 例如，要将变量 "a" 设为八进制的 "10" (十进制的 8)，就输入:

     >>> a = 0o10
     >>> a
     8

十六进制数也同样简单。 只要在十六进制数之前加一个零和一个小写或大写字母
"x"。 十六进制数码中的字母可以为大写或小写。 例如在 Python 解释器中输入:

     >>> a = 0xa5
     >>> a
     165
     >>> b = 0XB2
     >>> b
     178


File: python.info,  Node: 为什么-22 // 10返回-3？,  Next: 如何将字符串转换为数字？,  Prev: 如何指定十六进制和八进制整数？,  Up: 数字和字符串

11.2.3.2 为什么-22 // 10返回-3？
................................

这主要是为了让 ‘i % j’ 的正负与 ‘j’ 一致，如果你想要这样的结果，并且又想
要:

     i == (i // j) * j + (i % j)

那么整除就必须向下取整。 C 同样要求保持一致，并且编译器在截短 ‘i // j’ 的
结果值时需要使 ‘i % j’ 的正负与 ‘i’ 一致。

对于 ‘i % j’ 来说 ‘j’ 为负值的应用场景实际上是非常少的。 而 ‘j’ 为正值的
情况则非常多，并且实际上在所有情况下让 ‘i % j’ 的结果为 ‘>= 0’ 会更有用
处。 如果现在时间为 10 时，那么 200 小时前应是几时？ ‘-190 % 12 == 2’ 是
有用处的；‘-190 % 12 == -10’ 则是会导致意外的漏洞。


File: python.info,  Node: 如何将字符串转换为数字？,  Next: 如何将数字转换为字符串？,  Prev: 为什么-22 // 10返回-3？,  Up: 数字和字符串

11.2.3.3 如何将字符串转换为数字？
.................................

对于整数，可使用内置的 *note int(): 185. 类型构造器，例如 ‘int('144') ==
144’。 类似地，可使用 *note float(): 188. 转换为浮点数，例如
‘float('144') == 144.0’。

默认情况下，这些操作会将数字按十进制来解读，因此 ‘int('0144') == 144’ 而
‘int('0x144')’ 会引发 *note ValueError: 1fc.。 ‘int(string, base)’ 接受
第二个可选参数指定转换的基数，例如 ‘int('0x144', 16) == 324’。 如果指定
基数为 0，则按 Python 规则解读数字：前缀 ’0o’ 表示八进制，而 ’0x’ 表示十
六进制。

如果你只是想将字符串转为数字，请不要使用内置函数 *note eval(): b98.。
*note eval(): b98. 的速度会慢很多并且有安全风险：别人可能会传入具有你不
想要的附带效果的 Python 表达式。 例如，别人可以传入
‘__import__('os').system("rm -rf $HOME")’ 这将删除你的家目录。

*note eval(): b98. 还具有将数字解读为 Python 表达式的效果，这样
‘eval('09')’ 将会导致语法错误，因为 Python 不允许十进制数的首位是 ’0’
(’0’ 除外)。


File: python.info,  Node: 如何将数字转换为字符串？,  Next: 如何修改字符串？,  Prev: 如何将字符串转换为数字？,  Up: 数字和字符串

11.2.3.4 如何将数字转换为字符串？
.................................

例如要将数字 144 转换为字符串 ’144’，可使用内置类型构造器 *note str():
339.。 如果想要表示为十六进制或八进制数，可使用内置函数 *note hex():
c6e. 或 *note oct(): c6d.。 想要更好地格式化，请参阅 *note
格式化字符串字面值: 15d. 和 *note 格式字符串语法: d22. 等小节，例如
‘"{:04d}".format(144)’ 生成 ‘'0144'’ 而 ‘"{:.3f}".format(1.0/3.0)’ 生成
‘'0.333'’。


File: python.info,  Node: 如何修改字符串？,  Next: 如何使用字符串调用函数/方法？,  Prev: 如何将数字转换为字符串？,  Up: 数字和字符串

11.2.3.5 如何修改字符串？
.........................

无法修改，因为字符串是不可变对象。 在大多数情况下，你应该使用你想要的各
种部分来构造一个新字符串。 但是，如果你想要一个可以原地修改 Unicode 数据
的对象，可尝试使用 *note io.StringIO: 836. 对象或 *note array: 7. 模块:

     >>> import io
     >>> s = "Hello, world"
     >>> sio = io.StringIO(s)
     >>> sio.getvalue()
     'Hello, world'
     >>> sio.seek(7)
     7
     >>> sio.write("there!")
     6
     >>> sio.getvalue()
     'Hello, there!'

     >>> import array
     >>> a = array.array('u', s)
     >>> print(a)
     array('u', 'Hello, world')
     >>> a[0] = 'y'
     >>> print(a)
     array('u', 'yello, world')
     >>> a.tounicode()
     'yello, world'


File: python.info,  Node: 如何使用字符串调用函数/方法？,  Next: 是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？,  Prev: 如何修改字符串？,  Up: 数字和字符串

11.2.3.6 如何使用字符串调用函数/方法？
......................................

有多种技巧可供选择。

   * 最好的做法是使用一个将字符串映射到函数的字典。 这一技巧的主要优势在
     于字符串不必与函数名称一致。 这也是用于模拟其他语言中 case 结构的主
     要技巧:

          def a():
              pass

          def b():
              pass

          dispatch = {'go': a, 'stop': b}  # Note lack of parens for funcs

          dispatch[get_input()]()  # Note trailing parens to call function

   * 使用内置函数 *note getattr(): 451.

          import foo
          getattr(foo, 'bar')()

     请注意 *note getattr(): 451. 可用于任何对象，包括类、类实例、模块等
     等。

     在标准库中多次使用了这个技巧，例如:

          class Foo:
              def do_foo(self):
                  ...

              def do_bar(self):
                  ...

          f = getattr(foo_instance, 'do_' + opname)
          f()

   * 使用 *note locals(): 45d. 或 *note eval(): b98. 来解析出函数名:

          def myFunc():
              print("hello")

          fname = "myFunc"

          f = locals()[fname]
          f()

          f = eval(fname)
          f()

     注意：使用 *note eval(): b98. 速度慢而且危险。 如果你不能绝对掌控字
     符串的内容，别人将能传入可被解析为任意函数直接执行的字符串。


File: python.info,  Node: 是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？,  Next: 是否有 scanf 或 sscanf 的对应物？,  Prev: 如何使用字符串调用函数/方法？,  Up: 数字和字符串

11.2.3.7 是否有与Perl 的chomp() 等效的方法，用于从字符串中删除尾随换行符？
..........................................................................

可以使用 ‘S.rstrip("\r\n")’ 从字符串 ‘S’ 的末尾删除所有的换行符，而不删
除其他尾随空格。如果字符串 ‘S’ 表示多行，且末尾有几个空行，则将删除所有
空行的换行符：

     >>> lines = ("line 1 \r\n"
     ...          "\r\n"
     ...          "\r\n")
     >>> lines.rstrip("\n\r")
     'line 1 '

由于通常只在一次读取一行文本时才需要这样做，所以使用 ‘S.rstrip()’ 这种方
式工作得很好。


File: python.info,  Node: 是否有 scanf 或 sscanf 的对应物？,  Next: 'UnicodeDecodeError' 或 'UnicodeEncodeError' 错误是什么意思？,  Prev: 是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？,  Up: 数字和字符串

11.2.3.8 是否有 scanf() 或 sscanf() 的对应物？
..............................................

没有这样的对应物。

对于简单的输入解析，最方便的做法通常是使用字符串对象的 *note split():
7aa. 方法将一行内容拆解为以空格分隔的单词，然后使用 *note int(): 185. 或
*note float(): 188. 将表示十进制数的字符串转换为数值。 ‘split()’ 支持可
选的 "sep" 形参，适用于内容行使用空格符以外的分隔符的情况。

以于更复杂的输入解析，正则表达式会比 C 的 ‘sscanf()’ 更强大，也更适合此
类任务。


File: python.info,  Node: 'UnicodeDecodeError' 或 'UnicodeEncodeError' 错误是什么意思？,  Prev: 是否有 scanf 或 sscanf 的对应物？,  Up: 数字和字符串

11.2.3.9 ’UnicodeDecodeError’ 或 ’UnicodeEncodeError’ 错误是什么意思？
......................................................................

见 *note Unicode 指南: c44.


File: python.info,  Node: 性能<4>,  Next: 序列（元组/列表）,  Prev: 数字和字符串,  Up: 编程常见问题

11.2.4 性能
-----------

* Menu:

* 我的程序太慢了。该如何加快速度？::
* 将多个字符串连接在一起的最有效方法是什么？::


File: python.info,  Node: 我的程序太慢了。该如何加快速度？,  Next: 将多个字符串连接在一起的最有效方法是什么？,  Up: 性能<4>

11.2.4.1 我的程序太慢了。该如何加快速度？
.........................................

总的来说，这是个棘手的问题。首先，下面列出了深入了解前需要记住的事情：

   * 不同的 Python 实现具有不同的性能特点。 本 FAQ 着重解答的是 *note
     CPython: 1446.。

   * 行为可能因操作系统而异，尤其是在谈论 I / O 或多线程时。

   * 在尝试优化任何代码 `前' ，应始终找到程序中的热点（请参阅 *note
     profile: d4. 模块）。

   * 编写基准脚本将允许您在搜索改进时快速迭代（请参阅 *note timeit: 10c.
     模块）。

   * 强烈建议在可能引入隐藏在复杂优化中的回归之前，要有良好的代码覆盖率
     （通过单元测试或任何其他技术）。

话虽如此，加速Python代码有很多技巧。以下是一些可以达到可接受的性能水平的
一般原则：

   * 使您的算法更快（或更改为更快的算法）可以产生比尝试在代码中使用微优
     化技巧更大的好处。

   * 使用正确的数据结构。参考文档 *note 内置类型: 1624. 和 *note
     collections: 1e. 模块。

   * 当标准库提供用于执行某些操作的原语时，可能（尽管不能保证）比您可能
     提出的任何替代方案更快。对于用C编写的原语，例如内置函数和一些扩展类
     型，这是真的。例如，请确保使用 *note list.sort(): 44d. 内置方法或相
     关的 *note sorted(): 44c. 函数进行排序（有关适度高级用法的示例，请
     参阅 *note 排序指南: 1611. ）。

   * 抽象倾向于创造间接性并迫使翻译更多地工作。如果间接级别超过完成的有
     用工作量，则程序将变慢。你应该避免过度抽象，特别是在微小的功能或方
     法的形式下（这通常也会对可读性产生不利影响）。

如果你已经达到纯 Python 允许的限制，那么有一些工具可以让你走得更远。 例
如， Cython(1) 可以将稍微修改的 Python 代码版本编译为 C 扩展，并且可以在
许多不同的平台上使用。 Cython 可以利用编译（和可选的类型注释）来使代码明
显快于解释运行时的速度。 如果您对 C 编程技能有信心，也可以自己 *note 编写
C 扩展模块: 120d. 。

参见
....

专门介绍 性能提示(2) 的wiki页面。

   ---------- Footnotes ----------

   (1) http://cython.org

   (2) https://wiki.python.org/moin/PythonSpeed/PerformanceTips


File: python.info,  Node: 将多个字符串连接在一起的最有效方法是什么？,  Prev: 我的程序太慢了。该如何加快速度？,  Up: 性能<4>

11.2.4.2 将多个字符串连接在一起的最有效方法是什么？
...................................................

*note str: 339. 和 *note bytes: 33a. 对象是不可变的，因此将多个字符串连
接在一起效率很低，因为每个连接都会创建一个新对象。在一般情况下，总运行时
间是总字符串长度的二次方。

要连接多个 *note str: 339. 对象，通常推荐的用法是将它们放入一个列表中并
在结尾处调用 *note str.join(): 1642. ：

     chunks = []
     for s in my_strings:
         chunks.append(s)
     result = ''.join(chunks)

（另一个合理有效的惯用方法是 *note io.StringIO: 836. ）

要连接多个 *note str: 339. 对象，建议使用本地连接（ ‘+=’ 运算符）扩展
*note bytearray: 33b. 对象：

     result = bytearray()
     for b in my_bytes_objects:
         result += b


File: python.info,  Node: 序列（元组/列表）,  Next: 对象,  Prev: 性能<4>,  Up: 编程常见问题

11.2.5 序列（元组/列表）
------------------------

* Menu:

* 如何在元组和列表之间进行转换？::
* 什么是负数序号？::
* 如何以相反的顺序迭代序列？::
* 如何从列表中删除重复项？::
* 如何从列表中删除多个项？::
* 如何在Python中创建数组？::
* 如何创建多维列表？::
* 如何将方法应用于一系列对象？::
* 为什么 a_tuple[i] += ['item'] 会在执行加法时引发异常？::
* 我想做一个复杂的排序：你能用Python做一个Schwartzian变换吗？::
* 如何按其他列表中的值对一个列表进行排序？::


File: python.info,  Node: 如何在元组和列表之间进行转换？,  Next: 什么是负数序号？,  Up: 序列（元组/列表）

11.2.5.1 如何在元组和列表之间进行转换？
.......................................

类型构造器 ‘tuple(seq)’ 可将任意序列（实际上是任意可迭代对象）转换为具有
相同排列顺序的相同条目的元组。

例如，‘tuple([1, 2, 3])’ 产生 ‘(1, 2, 3)’ 而 ‘tuple('abc')’ 产生 ‘('a',
'b', 'c')’。 如果参数为一个元组，它不会创建副本而是返回同一对象，因此如
果你不确定某个对象是否为元组时也可简单地调用 *note tuple(): 486.。

类型构造器 ‘list(seq)’ 可将任意序列或可迭代对象转换为具有相同排列顺序的
相同条目的列表。 例如，‘list((1, 2, 3))’ 产生 ‘[1, 2, 3]’ 而
‘list('abc')’ 产生 ‘['a', 'b', 'c']’。 如果参数为一个列表，它会像
‘seq[:]’ 那样创建一个副本。


File: python.info,  Node: 什么是负数序号？,  Next: 如何以相反的顺序迭代序列？,  Prev: 如何在元组和列表之间进行转换？,  Up: 序列（元组/列表）

11.2.5.2 什么是负数序号？
.........................

Python 序列使用正数或负数作为序号或称索引号。 对于正数序号，第一个序号为
0 而 1 为第二个序号，依此类推。 对于负数序号，倒数第一个序号为 -1 而倒数
第二个序号为 -2，依此类推。 可以认为 ‘seq[-n]’ 就相当于
‘seq[len(seq)-n]’。

使用负数序号有时会很方便。 例如 ‘S[:-1]’ 就是原字符串去掉最后一个字符，
这可以用来移除某个字符串末尾的换行符。


File: python.info,  Node: 如何以相反的顺序迭代序列？,  Next: 如何从列表中删除重复项？,  Prev: 什么是负数序号？,  Up: 序列（元组/列表）

11.2.5.3 如何以相反的顺序迭代序列？
...................................

使用 *note reversed(): 18f. 内置函数:

     for x in reversed(sequence):
         ...  # do something with x ...

这不会修改您的原始序列，而是构建一个反向顺序的新副本以进行迭代。


File: python.info,  Node: 如何从列表中删除重复项？,  Next: 如何从列表中删除多个项？,  Prev: 如何以相反的顺序迭代序列？,  Up: 序列（元组/列表）

11.2.5.4 如何从列表中删除重复项？
.................................

有关执行此操作的许多方法的详细讨论，请参阅 Python Cookbook:

     ‘https://code.activestate.com/recipes/52560/’

如果您不介意重新排序列表，请对其进行排序，然后从列表末尾进行扫描，删除重
复项：

     if mylist:
         mylist.sort()
         last = mylist[-1]
         for i in range(len(mylist)-2, -1, -1):
             if last == mylist[i]:
                 del mylist[i]
             else:
                 last = mylist[i]

如果列表的所有元素都可以用作设置键（即：它们都是 *note hashable: 1439. ）
，这通常会更快:

     mylist = list(set(mylist))

这会将列表转换为集合，从而删除重复项，然后返回到列表中。


File: python.info,  Node: 如何从列表中删除多个项？,  Next: 如何在Python中创建数组？,  Prev: 如何从列表中删除重复项？,  Up: 序列（元组/列表）

11.2.5.5 如何从列表中删除多个项？
.................................

对于删除重复项，一种可能的做法是设置删除条件显式地进行反向迭代。但是更容
易也更快速的做法是进行隐式或显式的正向迭代并使用切片替代。 以下列出了三
种方式。:

     mylist[:] = filter(keep_function, mylist)
     mylist[:] = (x for x in mylist if keep_condition)
     mylist[:] = [x for x in mylist if keep_condition]

列表推导式可能是最快的。


File: python.info,  Node: 如何在Python中创建数组？,  Next: 如何创建多维列表？,  Prev: 如何从列表中删除多个项？,  Up: 序列（元组/列表）

11.2.5.6 如何在Python中创建数组？
.................................

使用列表:

     ["this", 1, "is", "an", "array"]

列表在时间复杂度方面相当于C或Pascal数组；主要区别在于，python列表可以包
含许多不同类型的对象。

‘array’ 模块还提供了创建具有紧凑表示的固定类型的数组的方法，但它的索引速
度比列表慢。还要注意，数字扩展和其他扩展还定义了具有各种特性的类似数组的
结构。

要获取Lisp样式的列表，可以使用元组模拟cons单元：

     lisp_list = ("like",  ("this",  ("example", None) ) )

如果需要可变性，可以使用列表而不是元组。这里模拟lisp car的是
‘lisp_list[0]’ ，模拟cdr的是 ‘lisp_list[1]’ 。只有在你确定真的需要的时候
才这样做，因为它通常比使用Python列表慢得多。


File: python.info,  Node: 如何创建多维列表？,  Next: 如何将方法应用于一系列对象？,  Prev: 如何在Python中创建数组？,  Up: 序列（元组/列表）

11.2.5.7 如何创建多维列表？
...........................

你可能试图制作一个像这样的多维数组:

     >>> A = [[None] * 2] * 3

如果你打印它，看起来是正确的：

     >>> A
     [[None, None], [None, None], [None, None]]

但是，当你给某一项赋值时，会同时在多个位置显示变化：

     >>> A[0][0] = 5
     >>> A
     [[5, None], [5, None], [5, None]]

其中的原因在于使用 ‘*’ 对列表执行重复操作并不是创建副本，它只是创建现有
对象的引用。 ‘*3’ 创建了对长度为二的同一列表的 3 个引用。 对某一行的改变
会作用于所有行，通常这一定不是你所希望的。

建议的做法是先创建一个所需长度的列表，然后其中的元素再以一个新创建的列表
来填充:

     A = [None] * 3
     for i in range(3):
         A[i] = [None] * 2

这样就生成了一个包含 3 个长度为二的不同列表的列表。 你也可以使用列表推导
式:

     w, h = 2, 3
     A = [[None] * w for i in range(h)]

或者你还可以使用提供矩阵类型的扩展包；其中最著名的是 NumPy(1)。

   ---------- Footnotes ----------

   (1) http://www.numpy.org/


File: python.info,  Node: 如何将方法应用于一系列对象？,  Next: 为什么 a_tuple[i] += ['item'] 会在执行加法时引发异常？,  Prev: 如何创建多维列表？,  Up: 序列（元组/列表）

11.2.5.8 如何将方法应用于一系列对象？
.....................................

可以使用列表推导式：

     result = [obj.method() for obj in mylist]


File: python.info,  Node: 为什么 a_tuple[i] += ['item'] 会在执行加法时引发异常？,  Next: 我想做一个复杂的排序：你能用Python做一个Schwartzian变换吗？,  Prev: 如何将方法应用于一系列对象？,  Up: 序列（元组/列表）

11.2.5.9 为什么 a_tuple[i] += [’item’] 会在执行加法时引发异常？
...............................................................

这是由两个事实共同导致的结果，一是增强赋值运算符属于 `赋值' 运算符，二是
在 Python 中存在可变和不可变两种不同的对象。

此处的讨论在任何对元组中指向可变对象的元素使用增强赋值运算符的情况都是普
遍成立的，但在此我们只以 ‘list’ 和 ‘+=’ 来举例。

如果你写成这样:

     >>> a_tuple = (1, 2)
     >>> a_tuple[0] += 1
     Traceback (most recent call last):
        ...
     TypeError: 'tuple' object does not support item assignment

发生异常的原因是显而易见的: ‘1’ 会与对象 ‘a_tuple[0]’ 相加，而该对象为
(‘1’)，得到结果对象 ‘2’，但当我们试图将运算结果 ‘2’ 赋值给元组的 ‘0’ 号
元素时就将报错，因为我们不能改变元组的元素所指向的对象。

在表层之处，以上增强赋值语句所做的大致是这样:

     >>> result = a_tuple[0] + 1
     >>> a_tuple[0] = result
     Traceback (most recent call last):
       ...
     TypeError: 'tuple' object does not support item assignment

由于元组是不可变的，因此操作的赋值部分会引发错误。

当你这样写的时候:

     >>> a_tuple = (['foo'], 'bar')
     >>> a_tuple[0] += ['item']
     Traceback (most recent call last):
       ...
     TypeError: 'tuple' object does not support item assignment

发生异常会令人略感吃惊，还有一个更为令人吃惊的事实：虽然有报错，但是添加
操作却生效了:

     >>> a_tuple[0]
     ['foo', 'item']

要明白为何会这样，你需要知道 (a) 如果一个对象实现了 ‘__iadd__’ 魔术方法
，它会在执行 ‘+=’ 增强赋值时被调用，并且其返回值将用于该赋值语句； (b) 对
于列表来说，‘__iadd__’ 等价于在列表上调用 ‘extend’ 并返回该列表。 因此对
于列表我们可以说 ‘+=’ 就是 ‘list.extend’ 的“快捷方式”:

     >>> a_list = []
     >>> a_list += [1]
     >>> a_list
     [1]

这相当于:

     >>> result = a_list.__iadd__([1])
     >>> a_list = result

a_list 所引用的对象已被修改，而引用被修改对象的指针又重新被赋值给
‘a_list’。 赋值的最终结果没有变化，因为它是引用 ‘a_list’ 之前所引用的同
一对象的指针，但仍然发生了赋值操作。

因此，在我们的元组示例中，发生的事情等同于：

     >>> result = a_tuple[0].__iadd__(['item'])
     >>> a_tuple[0] = result
     Traceback (most recent call last):
       ...
     TypeError: 'tuple' object does not support item assignment

‘__iadd__’ 成功执行，因此列表得到了扩充，但是虽然 ‘result’ 指向了
‘a_tuple[0]’ 已经指向的同一对象，最后的赋值仍然导致了报错，因为元组是不
可变的。


File: python.info,  Node: 我想做一个复杂的排序：你能用Python做一个Schwartzian变换吗？,  Next: 如何按其他列表中的值对一个列表进行排序？,  Prev: 为什么 a_tuple[i] += ['item'] 会在执行加法时引发异常？,  Up: 序列（元组/列表）

11.2.5.10 我想做一个复杂的排序：你能用Python做一个Schwartzian变换吗？
.....................................................................

该技术归功于Perl社区的 Randal Schwartz，它通过将每个元素映射到其 "排序值
（sort value）" 的度量对列表中的元素进行排序。在Python中，使用 *note
list.sort(): 44d. 方法的 ‘key’ 参数：

     Isorted = L[:]
     Isorted.sort(key=lambda s: int(s[10:15]))


File: python.info,  Node: 如何按其他列表中的值对一个列表进行排序？,  Prev: 我想做一个复杂的排序：你能用Python做一个Schwartzian变换吗？,  Up: 序列（元组/列表）

11.2.5.11 如何按其他列表中的值对一个列表进行排序？
..................................................

将它们合并到元组的迭代器中，对结果列表进行排序，然后选择所需的元素。

     >>> list1 = ["what", "I'm", "sorting", "by"]
     >>> list2 = ["something", "else", "to", "sort"]
     >>> pairs = zip(list1, list2)
     >>> pairs = sorted(pairs)
     >>> pairs
     [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
     >>> result = [x[1] for x in pairs]
     >>> result
     ['else', 'sort', 'to', 'something']

最后一步的替代方案是:

     >>> result = []
     >>> for p in pairs: result.append(p[1])

如果你觉得这个更容易读懂，那么你可能更喜欢使用这个而不是前面的列表推导。
然而，对于长列表来说，它的速度几乎是原来的两倍。为什么？首先，
‘append()’ 操作必须重新分配内存，虽然它使用了一些技巧来避免每次都这样做
，但它仍然偶尔需要这样做，而且代价相当高。第二，表达式 "result.append" 需
要额外的属性查找。第三，必须执行所有这些函数调用会降低速度。


File: python.info,  Node: 对象,  Next: 模块<3>,  Prev: 序列（元组/列表）,  Up: 编程常见问题

11.2.6 对象
-----------

* Menu:

* 什么是类？::
* 什么是方法？::
* 什么是 self ？::
* 如何检查对象是否为给定类或其子类的一个实例？::
* 什么是委托？::
* 如何从覆盖基类的派生类调用基类中定义的方法?::
* 如何组织代码以便更改基类？::
* 如何创建静态类数据和静态类方法？::
* 如何在Python中重载构造函数（或方法）？::
* 我尝试使用 __spam ，但是得到一个关于 _SomeClassName__spam 的错误信息。::
* 类定义了 __del__ 方法，但是删除对象时没有调用它。::
* 如何获取给定类的所有实例的列表？::
* 为什么 id() 的结果看起来不是唯一的？: 为什么 id 的结果看起来不是唯一的？.


File: python.info,  Node: 什么是类？,  Next: 什么是方法？,  Up: 对象

11.2.6.1 什么是类？
...................

‘类’ 是通过执行类语句创建的特定对象类型。‘类对象’ 被当作模板来创建实例对
象，实例对象包含了特定于数据类型的数据（属性）和代码（方法）。

类可以基于一个或多个的其他类，称之为基类（ES），它继承基类的属性和方法，
这样就可以通过继承来连续地细化对象模型。例如：您可能有一个 ‘Mailbox’ 类
提供邮箱的基本访问方法.，它的子类 ‘MboxMailbox’, ‘MaildirMailbox’,
‘OutlookMailbox’ 用于处理各种特定邮箱格式。


File: python.info,  Node: 什么是方法？,  Next: 什么是 self ？,  Prev: 什么是类？,  Up: 对象

11.2.6.2 什么是方法？
.....................

‘方法’ 实际上就是类定义中的函数。对于某个对象 ‘x’ 上的方法，通常称为
‘x.name(arguments...)’ 。

     class C:
         def meth(self, arg):
             return arg * 2 + self.attribute


File: python.info,  Node: 什么是 self ？,  Next: 如何检查对象是否为给定类或其子类的一个实例？,  Prev: 什么是方法？,  Up: 对象

11.2.6.3 什么是 self ？
.......................

Self 只是 ‘方法’ 的第一个参数的常规名称。例如：对于某个类的某个实例 ‘x’
，其方法 ‘meth(self, a, b, c)’ 实际上应该被称为 ‘x.meth(a, b, c)’ ；对于
被调用的方法会被称为 ‘meth(x, a, b, c)’ 。

另请参阅 *note 为什么必须在方法定义和调用中显式使用“self”？: 4281. 。


File: python.info,  Node: 如何检查对象是否为给定类或其子类的一个实例？,  Next: 什么是委托？,  Prev: 什么是 self ？,  Up: 对象

11.2.6.4 如何检查对象是否为给定类或其子类的一个实例？
.....................................................

可使用内置函数 ‘isinstance(obj, cls)’。 你可以提供一个元组而不是单个类来
检查某个对象是否为任意多个类当中某一个类的实例，例如 ‘isinstance(obj,
(class1, class2, ...))’，也可以检查某个对象是否为 Python 内置类型当中某
一个类型的对象，例如 ‘isinstance(obj, str)’ 或 ‘isinstance(obj, (int,
float, complex))’。

请注意大多数程序不会经常对用户自定义类使用 *note isinstance(): 457.。 如
果是你自已开发的类，更正确的面向对象风格是在类中定义方法来封装特定的行为
，而不是检查对象的类并根据它属于什么类来做不同的事。 例如，如果你有一个
执行某些操作的函数:

     def search(obj):
         if isinstance(obj, Mailbox):
             ...  # code to search a mailbox
         elif isinstance(obj, Document):
             ...  # code to search a document
         elif ...

更好的方法是在所有类上定义一个 ‘search()’ 方法，然后调用它：

     class Mailbox:
         def search(self):
             ...  # code to search a mailbox

     class Document:
         def search(self):
             ...  # code to search a document

     obj.search()


File: python.info,  Node: 什么是委托？,  Next: 如何从覆盖基类的派生类调用基类中定义的方法?,  Prev: 如何检查对象是否为给定类或其子类的一个实例？,  Up: 对象

11.2.6.5 什么是委托？
.....................

委托是一种面向对象的技巧（也称为设计模式）。 假设您有一个对象 ‘x’ 并且想
要改变其中一个方法的行为。 您可以创建一个新类，它提供您感兴趣的方法的新
实现，并将所有其他方法委托给 ‘x’ 的相应方法。

Python程序员可以轻松实现委托。 例如，以下类实现了一个类，该类的行为类似
于文件，但将所有写入的数据转换为大写：

     class UpperOut:

         def __init__(self, outfile):
             self._outfile = outfile

         def write(self, s):
             self._outfile.write(s.upper())

         def __getattr__(self, name):
             return getattr(self._outfile, name)

在这里 ‘UpperOut’ 类重新定义了 ‘write()’ 方法在调用下层的
‘self._outfile.write()’ 方法之前将参数字符串转换为大写形式。 所有其他方
法都被委托给下层的 ‘self._outfile’ 对象。 委托是通过 ‘__getattr__’ 方法
来完成的；请参阅 *note 语言参考: 1449. 了解有关控制属性访问的更多信息。

请注意对于更一般的情况来说，委托可能包含更多细节问题。 当某些属性既需要
读取又需要设置时，类还必须定义 *note __setattr__(): e34. 方法，并且这样
做必须小心谨慎。 *note __setattr__(): e34. 的基本实现大致相当于以下代码:

     class X:
         ...
         def __setattr__(self, name, value):
             self.__dict__[name] = value
         ...

大多数 *note __setattr__(): e34. 实现必须修改 ‘self.__dict__’ 来为自身保
存局部状态而又不至于造成无限递归。


File: python.info,  Node: 如何从覆盖基类的派生类调用基类中定义的方法?,  Next: 如何组织代码以便更改基类？,  Prev: 什么是委托？,  Up: 对象

11.2.6.6 如何从覆盖基类的派生类调用基类中定义的方法?
....................................................

使用内置的 *note super(): 4eb. 函数：

     class Derived(Base):
         def meth(self):
             super(Derived, self).meth()

对于 Python 3.0之前的版本，您可能正在使用经典类：对于诸如 ‘class
Derived(Base): ...’ 之类的类定义，可以将在 ‘Base’ (或 ‘Base’ 中的一个的
基类）中定义的方法 ‘meth()’ 调用为 ‘Base.meth(self, arguments...)’ 。这
里， ‘Base.meth’ 是一个未绑定的方法，因此您需要提供 ‘self’ 参数。


File: python.info,  Node: 如何组织代码以便更改基类？,  Next: 如何创建静态类数据和静态类方法？,  Prev: 如何从覆盖基类的派生类调用基类中定义的方法?,  Up: 对象

11.2.6.7 如何组织代码以便更改基类？
...................................

可以为基类定义别名，在类定义之前为其分配实际基类，并在整个类中使用别名。
然后更改分配给别名的值，就能实现上述要求。顺便提一下，如果你想动态决定（
例如，取决于资源的可用性）要使用哪个基类，这个技巧也很方便。例如：

     BaseAlias = <real base class>

     class Derived(BaseAlias):
         def meth(self):
             BaseAlias.meth(self)
             ...


File: python.info,  Node: 如何创建静态类数据和静态类方法？,  Next: 如何在Python中重载构造函数（或方法）？,  Prev: 如何组织代码以便更改基类？,  Up: 对象

11.2.6.8 如何创建静态类数据和静态类方法？
.........................................

Python支持静态数据和静态方法（在C ++或Java的意义上）。

对于静态数据，只需定义一个类属性。要为属性分配新值，就必须在赋值中显式使
用类名：

     class C:
         count = 0   # number of times C.__init__ called

         def __init__(self):
             C.count = C.count + 1

         def getcount(self):
             return C.count  # or return self.count

对于任意 ‘c’ 来说只要 ‘isinstance(c, C)’ 为真，则 ‘c.count’ 同样也指向
‘C.count’，除非被 ‘c’ 自身，或者从 ‘c.__class__’ 回到 ‘C’ 的基类搜索路径
上的某个类所重载。

注意：在 C 的某个方法内部，像 ‘self.count = 42’ 这样的赋值将在 ‘self’ 自
身的字典中新建一个名为 "count" 的不相关实例。 想要重新绑定类静态数据名称
就必须总是指明类名，无论是在方法内部还是外部:

     C.count = 314

静态方法是可行的：

     class C:
         @staticmethod
         def static(arg1, arg2, arg3):
             # No 'self' parameter!
             ...

然而，获得静态方法效果的更直接的方法是通过一个简单的模块级函数：

     def getcount():
         return C.count

如果您的代码是结构化的，以便为每个模块定义一个类（或紧密相关的类层次结构
），那么这就提供了所需的封装。


File: python.info,  Node: 如何在Python中重载构造函数（或方法）？,  Next: 我尝试使用 __spam ，但是得到一个关于 _SomeClassName__spam 的错误信息。,  Prev: 如何创建静态类数据和静态类方法？,  Up: 对象

11.2.6.9 如何在Python中重载构造函数（或方法）？
...............................................

这个答案实际上适用于所有方法，但问题通常首先出现在构造函数的上下文中。

在C ++中，你会这样写

     class C {
         C() { cout << "No arguments\n"; }
         C(int i) { cout << "Argument is " << i << "\n"; }
     }

在Python中，您必须编写一个构造函数，使用默认参数捕获所有情况。例如：

     class C:
         def __init__(self, i=None):
             if i is None:
                 print("No arguments")
             else:
                 print("Argument is", i)

这不完全等同，但在实践中足够接近。

你也可以尝试一个可变长度的参数列表，例如:

     def __init__(self, *args):
         ...

相同的方法适用于所有方法定义。


File: python.info,  Node: 我尝试使用 __spam ，但是得到一个关于 _SomeClassName__spam 的错误信息。,  Next: 类定义了 __del__ 方法，但是删除对象时没有调用它。,  Prev: 如何在Python中重载构造函数（或方法）？,  Up: 对象

11.2.6.10 我尝试使用 __spam ，但是得到一个关于 _SomeClassName__spam 的错误信息。
................................................................................

以双下划线打头的变量会被“更名”以提供一种定义类私有变量的简单而有效的方式
。 任何形式为 ‘__spam’ 的标识符（至少前缀两个下划线，至多后缀一个下划线
）文本会被替换为 ‘_classname__spam’，其中 ‘classname’ 为去除了全部前缀下
划线的当前类名称。

这并不能保证私密性：外部用户仍然可以访问 "_classname__spam" 属性，私有变
量值也在对象的 ‘__dict__’ 中可见。 许多 Python 程序员从来都不使用这种私
有变量名称。


File: python.info,  Node: 类定义了 __del__ 方法，但是删除对象时没有调用它。,  Next: 如何获取给定类的所有实例的列表？,  Prev: 我尝试使用 __spam ，但是得到一个关于 _SomeClassName__spam 的错误信息。,  Up: 对象

11.2.6.11 类定义了 __del__ 方法，但是删除对象时没有调用它。
...........................................................

这有几个可能的原因。

del 语句不一定调用 *note __del__(): 927. —— 它只是减少对象的引用计数，如
果（引用计数）达到零，才会调用 *note __del__(): 927.。

如果数据结构包含循环链接（例如，每个子级都有一个父级引用，每个父级都有一
个子级列表的树），则引用计数将永远不会返回零。尽管Python 偶尔会运行一个
算法来检测这样的循环，但在数据结构的引用计数清零后，垃圾收集器可能需要一
段时间来运行，因此 *note __del__(): 927. 方法可能会在不方便和随机的时间
被调用。这对于重现一个问题，是非常不方便的。更糟糕的是，对象 *note
__del__(): 927. 的方法执行顺序是任意的。虽然可以运行 *note gc.collect():
22f. 来强制回收，但在一些病态的情况下，对象永远不会被回收。

尽管有循环收集器，但在对象上定义一个显式的 ‘close()’ 方法以便在用完之后
调用它仍然是一个好主意。 这样 ‘close()’ 方法可以随即删除引用子对象的属性
。 不要直接调用 *note __del__(): 927. —— 应该由 *note __del__(): 927. 调
用 ‘close()’，并且 ‘close()’ 能确保可以被同一对象多次地调用。

另一种避免循环引用的方法是使用 *note weakref: 129. 模块，该模块允许您指
向对象而不增加其引用计数。例如，树状数据结构应该对其父级和同级引用使用弱
引用（如果需要的话！）

最后，如果 *note __del__(): 927. 方法引发异常，会将警告消息打印到 *note
sys.stderr: 318. 。


File: python.info,  Node: 如何获取给定类的所有实例的列表？,  Next: 为什么 id 的结果看起来不是唯一的？,  Prev: 类定义了 __del__ 方法，但是删除对象时没有调用它。,  Up: 对象

11.2.6.12 如何获取给定类的所有实例的列表？
..........................................

Python不跟踪类（或内置类型）的所有实例。您可以对类的构造函数进行编程，以
通过保留每个实例的弱引用列表来跟踪所有实例。


File: python.info,  Node: 为什么 id 的结果看起来不是唯一的？,  Prev: 如何获取给定类的所有实例的列表？,  Up: 对象

11.2.6.13 为什么 ‘id()’ 的结果看起来不是唯一的？
................................................

*note id(): d8e. 返回一个整数，该整数在对象的生命周期内保证是唯一的。因
为在CPython中，这是对象的内存地址，所以经常发生在从内存中删除对象之后，
下一个新创建的对象被分配在内存中的相同位置。这个例子说明了这一点：

     >>> id(1000)
     13901272
     >>> id(2000)
     13901272

这两个id属于之前创建的不同整数对象，并在执行 ‘id()’ 调用后立即删除。要确
保要检查其id的对象仍处于活动状态，请创建对该对象的另一个引用：

     >>> a = 1000; b = 2000
     >>> id(a)
     13901272
     >>> id(b)
     13891296


File: python.info,  Node: 模块<3>,  Prev: 对象,  Up: 编程常见问题

11.2.7 模块
-----------

* Menu:

* 如何创建 .pyc 文件？: 如何创建 pyc 文件？.
* 如何找到当前模块名称？::
* 如何让模块相互导入？::
* __import__(’x.y.z’) 返回 <module ’x’>; 如何获取z?: __import__ 'x y z' 返回 <module 'x'>; 如何获取z?.
* 当我编辑了导入过的模块并重新导入它时，这些变化没有显示出来。为什么会这样？::


File: python.info,  Node: 如何创建 pyc 文件？,  Next: 如何找到当前模块名称？,  Up: 模块<3>

11.2.7.1 如何创建 .pyc 文件？
.............................

当一个模块首次被导入时（或自当前已编译文件创建后源文件被修改时），将会在
对应 ‘.py’ 文件所在目录的 ‘__pycache__’ 子目录下创建一个包含已编译代码的
‘.pyc’ 文件。 该 ‘.pyc’ 文件的文件名的开头部分将与对应 ‘.py’ 文件名相同
，并以 ‘.pyc’ 为后缀，中间部门则是基于创建它的特定 ‘python’ 二进制代码版
本。 （详情参见 PEP 3147(1)。）

无法创建 ‘.pyc’ 文件的可能原因是包含源文件的目录存在权限问题，这意味着
‘__pycache__’ 子目录无法被创建。 举例来说，如果你以某一用户来开发程序但
以另一用户身份来运行程序时就可能发生问题，测试 Web 服务器就属于这种情况
。

除非设置了 *note PYTHONDONTWRITEBYTECODE: d41. 环境变量，否则当你导入模
块并且 Python 具有创建 ‘__pycache__’ 子目录并将已编译模块写入该子目录的
能力（权限、存储空间等等）时就会自动创建 .pyc 文件。

在最高层级运行的 Python 脚本不被视为导入，因此不会创建 ‘.pyc’ 文件。 例
如，如果你有一个最高层级模块文件 ‘foo.py’，它又导入了另一个模块
‘xyz.py’，当你运行 ‘foo’ 模块 (通过输入终端命令 ‘python foo.py’)，则将为
‘xyz’ 创建一个 ‘.pyc’，因为 ‘xyz’ 是被导入的，但不会为 ‘foo’ 创建 ‘.pyc’
文件，因为 ‘foo.py’ 不是被导入的。

如果你需要为 ‘foo’ 创建 ‘.pyc’ 文件 —— 即为不是被导入的模块创建 ‘.pyc’ 文
件 —— 你可以使用 *note py_compile: d8. 和 *note compileall: 21. 模块。

*note py_compile: d8. 模块能够手动编译任意模块。 一种做法是交互式地使用
该模块中的 ‘compile()’ 函数:

     >>> import py_compile
     >>> py_compile.compile('foo.py')

这将会将 ‘.pyc’ 文件写入与 ‘foo.py’ 相同位置下的 ‘__pycache__’ 子目录（
或者你也可以通过可选参数 ‘cfile’ 来重载该行为）。

你还可以使用 *note compileall: 21. 模块自动编译一个目录或多个目录下的所
有文件。 具体做法可以是在命令行提示符中运行 ‘compileall.py’ 并提供包含要
编译 Python 文件的目录路径:

     python -m compileall .

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: 如何找到当前模块名称？,  Next: 如何让模块相互导入？,  Prev: 如何创建 pyc 文件？,  Up: 模块<3>

11.2.7.2 如何找到当前模块名称？
...............................

模块可以通过查看预定义的全局变量 ‘__name__’ 找到自己的模块名称。如果它的
值为 ‘'__main__'’ ，程序将作为脚本运行。通常，通过导入使用的许多模块也提
供命令行界面或自检，并且只在检查 ‘__name__’ 之后，才执行之后的代码:

     def main():
         print('Running test...')
         ...

     if __name__ == '__main__':
         main()


File: python.info,  Node: 如何让模块相互导入？,  Next: __import__ 'x y z' 返回 <module 'x'>; 如何获取z?,  Prev: 如何找到当前模块名称？,  Up: 模块<3>

11.2.7.3 如何让模块相互导入？
.............................

假设您有以下模块：

foo.py:

     from bar import bar_var
     foo_var = 1

bar.py:

     from foo import foo_var
     bar_var = 2

问题是解释器将执行以下步骤：

   * 首先导入foo

   * 创建用于foo的空全局变量

   * foo被编译并开始执行

   * foo 导入 bar

   * 创建了用于bar 的空全局变量

   * bar被编译并开始执行

   * bar导入foo（这是一个空操作（no-op ），因为已经有一个名为foo的模块）

   * bar.foo_var = foo.foo_var

最后一步失败了，因为Python还没有解释foo，而foo的全局符号字典仍然是空的。

当你使用 ‘import foo’ ，然后尝试在全局代码中访问 ‘foo.foo_var’ 时，会发
生同样的事情。

这个问题有（至少）三种可能的解决方法。

Guido van Rossum 建议避免使用 ‘from <module> import ...’ ，并将所有代码
放在函数中。全局变量和类变量的初始化只能使用常量或内置函数。这意味着导入
模块中的所有内容都被引用为 ‘<module>.<name>’ 。

Jim Roskind建议在每个模块中按以下顺序执行步骤：

   * 导出（全局变量，函数和不需要导入基类的类）

   * ‘导入’ 声明

   * 活动代码（包括从导入值初始化的全局变量）。

van Rossum不喜欢这种方法，因为导入出现在一个陌生的地方，但这种方法确实有
效。

Matthias Urlichs建议重构代码，以便首先不需要递归导入。

这些解决方案并不相互排斥。


File: python.info,  Node: __import__ 'x y z' 返回 <module 'x'>; 如何获取z?,  Next: 当我编辑了导入过的模块并重新导入它时，这些变化没有显示出来。为什么会这样？,  Prev: 如何让模块相互导入？,  Up: 模块<3>

11.2.7.4 __import__(’x.y.z’) 返回 <module ’x’>; 如何获取z?
..........................................................

考虑使用 *note importlib: 9b. 中的函数 *note import_module(): b1b. ：

     z = importlib.import_module('x.y.z')


File: python.info,  Node: 当我编辑了导入过的模块并重新导入它时，这些变化没有显示出来。为什么会这样？,  Prev: __import__ 'x y z' 返回 <module 'x'>; 如何获取z?,  Up: 模块<3>

11.2.7.5 当我编辑了导入过的模块并重新导入它时，这些变化没有显示出来。为什么会这样？
...................................................................................

出于效率和一致性的原因，Python仅在第一次导入模块时读取模块文件。如果不这
么做，在一个由许多模块组成的程序中，每个模块都会导入相同的基本模块，那么
基本模块将被解析和重新解析多次。要强制重新读取已更改的模块，请执行以下操
作:

     import importlib
     import modname
     importlib.reload(modname)

警告：这种技术不是100％万无一失。特别是包含如下语句的模块

     from modname import some_objects

将继续使用旧版本的导入对象。如果模块包含类定义，则不会更新现有的类实例以
使用新的类定义。这可能导致以下矛盾行为:

     >>> import importlib
     >>> import cls
     >>> c = cls.C()                # Create an instance of C
     >>> importlib.reload(cls)
     <module 'cls' from 'cls.py'>
     >>> isinstance(c, cls.C)       # isinstance is false?!?
     False

如果打印出类对象的“标识”，问题的本质就会明确：

     >>> hex(id(c.__class__))
     '0x7352a0'
     >>> hex(id(cls.C))
     '0x4198d0'


File: python.info,  Node: 设计和历史常见问题,  Next: 代码库和插件 FAQ,  Prev: 编程常见问题,  Up: Python 常见问题

11.3 设计和历史常见问题
=======================

* Menu:

* 为什么Python使用缩进来分组语句？::
* 为什么简单的算术运算得到奇怪的结果？::
* 为什么浮点计算不准确？::
* 为什么Python字符串是不可变的？::
* 为什么必须在方法定义和调用中显式使用“self”？::
* 为什么不能在表达式中赋值？::
* 为什么Python对某些功能（例如list.index()）使用方法来实现，而其他功能（例如len(List)）使用函数实现？: 为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？.
* 为什么 join()是一个字符串方法而不是列表或元组方法？: 为什么 join 是一个字符串方法而不是列表或元组方法？.
* 异常有多快？::
* 为什么Python中没有switch或case语句？::
* 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？::
* 为什么lambda表达式不能包含语句？::
* 可以将Python编译为机器代码，C或其他语言吗？::
* Python如何管理内存？::
* 为什么CPython不使用更传统的垃圾回收方案？::
* CPython退出时为什么不释放所有内存？::
* 为什么有单独的元组和列表数据类型？::
* 列表是如何在CPython中实现的？::
* 字典是如何在CPython中实现的？::
* 为什么字典key必须是不可变的？::
* 为什么 list.sort() 没有返回排序列表？: 为什么 list sort 没有返回排序列表？.
* 如何在Python中指定和实施接口规范？::
* 为什么没有goto？::
* 为什么原始字符串（r-strings）不能以反斜杠结尾？::
* 为什么Python没有属性赋值的“with”语句？::
* 为什么 if/while/def/class语句需要冒号？::
* 为什么Python在列表和元组的末尾允许使用逗号？::


File: python.info,  Node: 为什么Python使用缩进来分组语句？,  Next: 为什么简单的算术运算得到奇怪的结果？,  Up: 设计和历史常见问题

11.3.1 为什么Python使用缩进来分组语句？
---------------------------------------

Guido van Rossum 认为使用缩进进行分组非常优雅，并且大大提高了普通
Python程序的清晰度。大多数人在一段时间后就学会并喜欢上这个功能。

由于没有开始/结束括号，因此解析器感知的分组与人类读者之间不会存在分歧。
偶尔C程序员会遇到像这样的代码片段:

     if (x <= y)
             x++;
             y--;
     z++;

如果条件为真，则只执行 ‘x++’ 语句，但缩进会使你认为情况并非如此。即使是
经验丰富的C程序员有时会长时间盯着它，想知道为什么即使 ‘x > y’ ， ‘y’ 也
在减少。

因为没有开始/结束括号，所以Python不太容易发生编码式冲突。在C中，括号可以
放到许多不同的位置。如果您习惯于阅读和编写使用一种风格的代码，那么在阅读
（或被要求编写）另一种风格时，您至少会感到有些不安。

许多编码风格将开始/结束括号单独放在一行上。这使得程序相当长，浪费了宝贵
的屏幕空间，使得更难以对程序进行全面的了解。理想情况下，函数应该适合一个
屏幕（例如，20–30行）。 20行Python可以完成比20行C更多的工作。这不仅仅是
由于缺少开始/结束括号 – 缺少声明和高级数据类型也是其中的原因 – 但缩进基
于语法肯定有帮助。


File: python.info,  Node: 为什么简单的算术运算得到奇怪的结果？,  Next: 为什么浮点计算不准确？,  Prev: 为什么Python使用缩进来分组语句？,  Up: 设计和历史常见问题

11.3.2 为什么简单的算术运算得到奇怪的结果？
-------------------------------------------

请看下一个问题。


File: python.info,  Node: 为什么浮点计算不准确？,  Next: 为什么Python字符串是不可变的？,  Prev: 为什么简单的算术运算得到奇怪的结果？,  Up: 设计和历史常见问题

11.3.3 为什么浮点计算不准确？
-----------------------------

用户经常对这样的结果感到惊讶:

     >>> 1.2 - 1.0
     0.19999999999999996

并且认为这是 Python中的一个 bug。其实不是这样。这与 Python 关系不大，而
与底层平台如何处理浮点数字关系更大。

CPython 中的 *note float: 188. 类型使用C语言的 ‘double’ 类型进行存储。
*note float: 188. 对象的值是以固定的精度（通常为 53 位）存储的二进制浮点
数，由于 Python 使用 C 操作，而后者依赖于处理器中的硬件实现来执行浮点运
算。 这意味着就浮点运算而言，Python 的行为类似于许多流行的语言，包括 C 和
Java。

许多可以轻松地用十进制表示的数字不能用二进制浮点表示。例如，在输入以下语
句后:

     >>> x = 1.2

为 ‘x’ 存储的值是与十进制的值 ‘1.2’ (非常接近) 的近似值，但不完全等于它
。 在典型的机器上，实际存储的值是：

     1.0011001100110011001100110011001100110011001100110011 (binary)

它对应于十进制数值:

     1.1999999999999999555910790149937383830547332763671875 (decimal)

典型的 53 位精度为 Python 浮点数提供了 15-16 位小数的精度。

要获得更完整的解释，请参阅 Python 教程中的 *note 浮点算术: 1332. 一章。


File: python.info,  Node: 为什么Python字符串是不可变的？,  Next: 为什么必须在方法定义和调用中显式使用“self”？,  Prev: 为什么浮点计算不准确？,  Up: 设计和历史常见问题

11.3.4 为什么Python字符串是不可变的？
-------------------------------------

有几个优点。

一个是性能：知道字符串是不可变的，意味着我们可以在创建时为它分配空间，并
且存储需求是固定不变的。这也是元组和列表之间区别的原因之一。

另一个优点是，Python 中的字符串被视为与数字一样“基本”。 任何动作都不会将
值 8 更改为其他值，在 Python 中，任何动作都不会将字符串 "8" 更改为其他值
。


File: python.info,  Node: 为什么必须在方法定义和调用中显式使用“self”？,  Next: 为什么不能在表达式中赋值？,  Prev: 为什么Python字符串是不可变的？,  Up: 设计和历史常见问题

11.3.5 为什么必须在方法定义和调用中显式使用“self”？
---------------------------------------------------

这个想法借鉴了 Modula-3 语言。 出于多种原因它被证明是非常有用的。

首先，更明显的显示出，使用的是方法或实例属性而不是局部变量。 阅读
‘self.x’ 或 ‘self.meth()’ 可以清楚地表明，即使您不知道类的定义，也会使用
实例变量或方法。在 C++ 中，可以通过缺少局部变量声明来判断（假设全局变量
很少见或容易识别） —— 但是在 Python 中没有局部变量声明，所以必须查找类定
义才能确定。 一些 C++ 和 Java 编码标准要求实例属性具有 ‘m_’ 前缀，因此这
种显式性在这些语言中仍然有用。

其次，这意味着如果要显式引用或从特定类调用该方法，不需要特殊语法。 在
C++ 中，如果你想使用在派生类中重写基类中的方法，你必须使用 ‘::’ 运算符 –
在 Python 中你可以编写 ‘baseclass.methodname(self, <argument list>)’。 这
对于 *note __init__(): d66. 方法非常有用，特别是在派生类方法想要扩展同名
的基类方法，而必须以某种方式调用基类方法时。

最后，它解决了变量赋值的语法问题：为了 Python 中的局部变量（根据定义！）
在函数体中赋值的那些变量（并且没有明确声明为全局）赋值，就必须以某种方式
告诉解释器一个赋值是为了分配一个实例变量而不是一个局部变量，它最好是通过
语法实现的（出于效率原因）。 C++ 通过声明来做到这一点，但是 Python 没有
声明，仅仅为了这个目的而引入它们会很可惜。 使用显式的 ‘self.var’ 很好地
解决了这个问题。 类似地，对于使用实例变量，必须编写 ‘self.var’ 意味着对
方法内部的非限定名称的引用不必搜索实例的目录。 换句话说，局部变量和实例
变量存在于两个不同的命名空间中，您需要告诉 Python 使用哪个命名空间。


File: python.info,  Node: 为什么不能在表达式中赋值？,  Next: 为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？,  Prev: 为什么必须在方法定义和调用中显式使用“self”？,  Up: 设计和历史常见问题

11.3.6 为什么不能在表达式中赋值？
---------------------------------

自 Python 3.8 开始，你能做到的！

赋值表达式使用海象运算符 ‘:=’ 在表达式中为变量赋值:

     while chunk := fp.read(200):
        print(chunk)

请参阅 PEP 572(1) 了解详情。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0572


File: python.info,  Node: 为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？,  Next: 为什么 join 是一个字符串方法而不是列表或元组方法？,  Prev: 为什么不能在表达式中赋值？,  Up: 设计和历史常见问题

11.3.7 为什么Python对某些功能（例如list.index()）使用方法来实现，而其他功能（例如len(List)）使用函数实现？
----------------------------------------------------------------------------------------------------------

正如Guido所说：

     (a) 对于某些操作，前缀表示法比后缀更容易阅读 – 前缀（和中缀！）运算
     在数学中有着悠久的传统，就像在视觉上帮助数学家思考问题的记法。比较
     一下我们将 x*(a+b) 这样的公式改写为 x*a+x*b 的容易程度，以及使用原
     始OO符号做相同事情的笨拙程度。

     (b) 当读到写有len(X)的代码时，就知道它要求的是某件东西的长度。这告
     诉我们两件事：结果是一个整数，参数是某种容器。相反，当阅读x.len()时
     ，必须已经知道x是某种实现接口的容器，或者是从具有标准len()的类继承
     的容器。当没有实现映射的类有get()或key()方法，或者不是文件的类有
     write()方法时，我们偶尔会感到困惑。

— ‘https://mail.python.org/pipermail/python-3000/2006-November/004643.html’


File: python.info,  Node: 为什么 join 是一个字符串方法而不是列表或元组方法？,  Next: 异常有多快？,  Prev: 为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？,  Up: 设计和历史常见问题

11.3.8 为什么 join()是一个字符串方法而不是列表或元组方法？
----------------------------------------------------------

从Python 1.6开始，字符串变得更像其他标准类型，当添加方法时，这些方法提供
的功能与始终使用String模块的函数时提供的功能相同。这些新方法中的大多数已
被广泛接受，但似乎让一些程序员感到不舒服的一种方法是：

     ", ".join(['1', '2', '4', '8', '16'])

结果如下:

     "1, 2, 4, 8, 16"

反对这种用法有两个常见的论点。

第一条是这样的：“使用字符串文本(String Constant)的方法看起来真的很难看
”，答案是也许吧，但是字符串文本只是一个固定值。如果在绑定到字符串的名称
上允许使用这些方法，则没有逻辑上的理由使其在文字上不可用。

第二个异议通常是这样的：“我实际上是在告诉序列使用字符串常量将其成员连接
在一起”。遗憾的是并非如此。出于某种原因，把 *note split(): 7aa. 作为一个
字符串方法似乎要容易得多，因为在这种情况下，很容易看到:

     "1, 2, 4, 8, 16".split(", ")

是对字符串文本的指令，用于返回由给定分隔符分隔的子字符串（或在默认情况下
，返回任意空格）。

*note join(): 1642. 是字符串方法，因为在使用该方法时，您告诉分隔符字符串
去迭代一个字符串序列，并在相邻元素之间插入自身。此方法的参数可以是任何遵
循序列规则的对象，包括您自己定义的任何新的类。对于字节和字节数组对象也有
类似的方法。


File: python.info,  Node: 异常有多快？,  Next: 为什么Python中没有switch或case语句？,  Prev: 为什么 join 是一个字符串方法而不是列表或元组方法？,  Up: 设计和历史常见问题

11.3.9 异常有多快？
-------------------

如果没有引发异常，则try/except块的效率极高。实际上捕获异常是昂贵的。在
2.0之前的Python版本中，通常使用这个习惯用法:

     try:
         value = mydict[key]
     except KeyError:
         mydict[key] = getvalue(key)
         value = mydict[key]

只有当你期望dict在任何时候都有key时，这才有意义。如果不是这样的话，你就
是应该这样编码：

     if key in mydict:
         value = mydict[key]
     else:
         value = mydict[key] = getvalue(key)

对于这种特定的情况，您还可以使用 ‘value = dict.setdefault(key,
getvalue(key))’，但前提是调用 ‘getvalue()’ 足够便宜，因为在所有情况下都
会对其进行评估。


File: python.info,  Node: 为什么Python中没有switch或case语句？,  Next: 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？,  Prev: 异常有多快？,  Up: 设计和历史常见问题

11.3.10 为什么Python中没有switch或case语句？
--------------------------------------------

你可以通过一系列 ‘if... elif... elif... else’.轻松完成这项工作。对于
switch语句语法已经有了一些建议，但尚未就是否以及如何进行范围测试达成共识
。有关完整的详细信息和当前状态，请参阅 PEP 275(1) 。

对于需要从大量可能性中进行选择的情况，可以创建一个字典，将case 值映射到
要调用的函数。例如：

     def function_1(...):
         ...

     functions = {'a': function_1,
                  'b': function_2,
                  'c': self.method_1, ...}

     func = functions[value]
     func()

对于对象调用方法，可以通过使用 *note getattr(): 451. 内置检索具有特定名
称的方法来进一步简化：

     def visit_a(self, ...):
         ...
     ...

     def dispatch(self, value):
         method_name = 'visit_' + str(value)
         method = getattr(self, method_name)
         method()

建议对方法名使用前缀，例如本例中的 ‘visit_’ 。如果没有这样的前缀，如果值
来自不受信任的源，攻击者将能够调用对象上的任何方法。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0275


File: python.info,  Node: 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？,  Next: 为什么lambda表达式不能包含语句？,  Prev: 为什么Python中没有switch或case语句？,  Up: 设计和历史常见问题

11.3.11 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？
--------------------------------------------------------------------------

答案1： 不幸的是，解释器为每个Python堆栈帧推送至少一个C堆栈帧。此外，扩
展可以随时回调Python。因此，一个完整的线程实现需要对C的线程支持。

答案2： 幸运的是， Stackless Python(1) 有一个完全重新设计的解释器循环，
可以避免C堆栈。

   ---------- Footnotes ----------

   (1) https://github.com/stackless-dev/stackless/wiki


File: python.info,  Node: 为什么lambda表达式不能包含语句？,  Next: 可以将Python编译为机器代码，C或其他语言吗？,  Prev: 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？,  Up: 设计和历史常见问题

11.3.12 为什么lambda表达式不能包含语句？
----------------------------------------

Python的 lambda表达式不能包含语句，因为Python的语法框架不能处理嵌套在表
达式内部的语句。然而，在Python中，这并不是一个严重的问题。与其他语言中添
加功能的lambda表单不同，Python的 lambdas只是一种速记符号，如果您懒得定义
函数的话。

函数已经是Python中的第一类对象，可以在本地范围内声明。 因此，使用
lambda而不是本地定义的函数的唯一优点是你不需要为函数创建一个名称 – 这只
是一个分配了函数对象(与lambda表达式生成的对象类型完全相同)的局部变量！


File: python.info,  Node: 可以将Python编译为机器代码，C或其他语言吗？,  Next: Python如何管理内存？,  Prev: 为什么lambda表达式不能包含语句？,  Up: 设计和历史常见问题

11.3.13 可以将Python编译为机器代码，C或其他语言吗？
---------------------------------------------------

Cython(1) 将带有可选注释的Python修改版本编译到C扩展中。 Nuitka(2) 是一个
将Python编译成 C++ 代码的新兴编译器，旨在支持完整的Python语言。要编译成
Java，可以考虑 VOC(3) 。

   ---------- Footnotes ----------

   (1) http://cython.org/

   (2) http://www.nuitka.net/

   (3) https://voc.readthedocs.io


File: python.info,  Node: Python如何管理内存？,  Next: 为什么CPython不使用更传统的垃圾回收方案？,  Prev: 可以将Python编译为机器代码，C或其他语言吗？,  Up: 设计和历史常见问题

11.3.14 Python如何管理内存？
----------------------------

Python 内存管理的细节取决于实现。 Python 的标准实现 *note CPython: 1446.
使用引用计数来检测不可访问的对象，并使用另一种机制来收集引用循环，定期执
行循环检测算法来查找不可访问的循环并删除所涉及的对象。 *note gc: 86. 模
块提供了执行垃圾回收、获取调试统计信息和优化收集器参数的函数。

但是，其他实现(如 Jython(1) 或 PyPy(2) )，)可以依赖不同的机制，如完全的
垃圾回收器 。如果你的Python代码依赖于引用计数实现的行为，则这种差异可能
会导致一些微妙的移植问题。

在一些Python实现中，以下代码（在CPython中工作的很好）可能会耗尽文件描述
符:

     for file in very_long_list_of_files:
         f = open(file)
         c = f.read(1)

实际上，使用CPython的引用计数和析构函数方案， 每个新赋值的 `f' 都会关闭
前一个文件。然而，对于传统的GC，这些文件对象只能以不同的时间间隔（可能很
长的时间间隔）被收集（和关闭）。

如果要编写可用于任何python实现的代码，则应显式关闭该文件或使用 *note
with: 6f2. 语句；无论内存管理方案如何，这都有效：

     for file in very_long_list_of_files:
         with open(file) as f:
             c = f.read(1)

   ---------- Footnotes ----------

   (1) http://www.jython.org

   (2) http://www.pypy.org


File: python.info,  Node: 为什么CPython不使用更传统的垃圾回收方案？,  Next: CPython退出时为什么不释放所有内存？,  Prev: Python如何管理内存？,  Up: 设计和历史常见问题

11.3.15 为什么CPython不使用更传统的垃圾回收方案？
-------------------------------------------------

首先，这不是C标准特性，因此不能移植。(是的，我们知道Boehm GC库。它包含了
`大多数' 常见平台（但不是所有平台）的汇编代码，尽管它基本上是透明的，但
也不是完全透明的; 要让Python使用它，需要使用补丁。)

当Python嵌入到其他应用程序中时，传统的GC也成为一个问题。在独立的Python中
，可以用GC库提供的版本替换标准的malloc()和free()，嵌入Python的应用程序可
能希望用 `它自己' 替代malloc()和free()，而可能不需要Python的。现在，
CPython可以正确地实现malloc()和free()。


File: python.info,  Node: CPython退出时为什么不释放所有内存？,  Next: 为什么有单独的元组和列表数据类型？,  Prev: 为什么CPython不使用更传统的垃圾回收方案？,  Up: 设计和历史常见问题

11.3.16 CPython退出时为什么不释放所有内存？
-------------------------------------------

当Python退出时，从全局命名空间或Python模块引用的对象并不总是被释放。 如
果存在循环引用，则可能发生这种情况 C库分配的某些内存也是不可能释放的（例
如像Purify这样的工具会抱怨这些内容）。 但是，Python在退出时清理内存并尝
试销毁每个对象。

如果要强制 Python 在释放时删除某些内容，请使用 *note atexit: c. 模块运行
一个函数，强制删除这些内容。


File: python.info,  Node: 为什么有单独的元组和列表数据类型？,  Next: 列表是如何在CPython中实现的？,  Prev: CPython退出时为什么不释放所有内存？,  Up: 设计和历史常见问题

11.3.17 为什么有单独的元组和列表数据类型？
------------------------------------------

虽然列表和元组在许多方面是相似的，但它们的使用方式通常是完全不同的。可以
认为元组类似于Pascal记录或C结构；它们是相关数据的小集合，可以是不同类型
的数据，可以作为一个组进行操作。例如，笛卡尔坐标适当地表示为两个或三个数
字的元组。

另一方面，列表更像其他语言中的数组。它们倾向于持有不同数量的对象，所有对
象都具有相同的类型，并且逐个操作。例如， ‘os.listdir('.')’ 返回表示当前
目录中的文件的字符串列表。如果向目录中添加了一两个文件，对此输出进行操作
的函数通常不会中断。

元组是不可变的，这意味着一旦创建了元组，就不能用新值替换它的任何元素。列
表是可变的，这意味着您始终可以更改列表的元素。只有不变元素可以用作字典的
key，因此只能将元组和非列表用作key。


File: python.info,  Node: 列表是如何在CPython中实现的？,  Next: 字典是如何在CPython中实现的？,  Prev: 为什么有单独的元组和列表数据类型？,  Up: 设计和历史常见问题

11.3.18 列表是如何在CPython中实现的？
-------------------------------------

CPython的列表实际上是可变长度的数组，而不是lisp风格的链表。该实现使用对
其他对象的引用的连续数组，并在列表头结构中保留指向该数组和数组长度的指针
。

这使得索引列表 ‘a[i]’ 的操作成本与列表的大小或索引的值无关。

当添加或插入项时，将调整引用数组的大小。并采用了一些巧妙的方法来提高重复
添加项的性能; 当数组必须增长时，会分配一些额外的空间，以便在接下来的几次
中不需要实际调整大小。


File: python.info,  Node: 字典是如何在CPython中实现的？,  Next: 为什么字典key必须是不可变的？,  Prev: 列表是如何在CPython中实现的？,  Up: 设计和历史常见问题

11.3.19 字典是如何在CPython中实现的？
-------------------------------------

CPython的字典实现为可调整大小的哈希表。与B-树相比，这在大多数情况下为查
找（目前最常见的操作）提供了更好的性能，并且实现更简单。

字典的工作方式是使用 *note hash(): 9cc. 内置函数计算字典中存储的每个键的
hash代码。hash代码根据键和每个进程的种子而变化很大；例如，"Python" 的
hash值为-539294296，而"python"(一个按位不同的字符串)的hash值为
1142331976。然后，hash代码用于计算内部数组中将存储该值的位置。假设您存储
的键都具有不同的hash值，这意味着字典需要恒定的时间 – O(1)，用Big-O表示法
– 来检索一个键。


File: python.info,  Node: 为什么字典key必须是不可变的？,  Next: 为什么 list sort 没有返回排序列表？,  Prev: 字典是如何在CPython中实现的？,  Up: 设计和历史常见问题

11.3.20 为什么字典key必须是不可变的？
-------------------------------------

字典的哈希表实现使用从键值计算的哈希值来查找键。如果键是可变对象，则其值
可能会发生变化，因此其哈希值也会发生变化。但是，由于无论谁更改键对象都无
法判断它是否被用作字典键值，因此无法在字典中修改条目。然后，当你尝试在字
典中查找相同的对象时，将无法找到它，因为其哈希值不同。如果你尝试查找旧值
，也不会找到它，因为在该哈希表中找到的对象的值会有所不同。

如果你想要一个用列表索引的字典，只需先将列表转换为元组；用函数
‘tuple(L)’ 创建一个元组，其条目与列表 ‘L’ 相同。 元组是不可变的，因此可
以用作字典键。

已经提出的一些不可接受的解决方案：

   - 哈希按其地址（对象ID）列出。这不起作用，因为如果你构造一个具有相同
     值的新列表，它将无法找到；例如:

          mydict = {[1, 2]: '12'}
          print(mydict[[1, 2]])

     会引发一个 *note KeyError: 2c8. 异常，因为第二行中使用的 ‘[1, 2]’ 的
     id 与第一行中的 id 不同。换句话说，应该使用 ‘==’ 来比较字典键，而不
     是使用 *note is: eca. 。

   - 使用列表作为键时进行复制。这没有用的，因为作为可变对象的列表可以包
     含对自身的引用，然后复制代码将进入无限循环。

   - 允许列表作为键，但告诉用户不要修改它们。当你意外忘记或修改列表时，
     这将产生程序中的一类难以跟踪的错误。它还使一个重要的字典不变量无效
     ： ‘d.keys()’ 中的每个值都可用作字典的键。

   - 将列表用作字典键后，应标记为其只读。问题是，它不仅仅是可以改变其值
     的顶级对象；你可以使用包含列表作为键的元组。将任何内容作为键关联到
     字典中都需要将从那里可到达的所有对象标记为只读 —— 并且自引用对象可
     能会导致无限循环。

如果需要，可以使用以下方法来解决这个问题，但使用它需要你自担风险：你可以
将一个可变结构包装在一个类实例中，该实例同时具有 *note __eq__(): 348. 和
*note __hash__(): 349. 方法。然后，你必须确保驻留在字典（或其他基于 hash
的结构）中的所有此类包装器对象的哈希值在对象位于字典（或其他结构）中时保
持固定。:

     class ListWrapper:
         def __init__(self, the_list):
             self.the_list = the_list

         def __eq__(self, other):
             return self.the_list == other.the_list

         def __hash__(self):
             l = self.the_list
             result = 98767 - len(l)*555
             for i, el in enumerate(l):
                 try:
                     result = result + (hash(el) % 9999999) * 1001 + i
                 except Exception:
                     result = (result % 7777777) + i * 333
             return result

注意，哈希计算由于列表的某些成员可能不可用以及算术溢出的可能性而变得复杂
。

此外，必须始终如此，如果 ‘o1 == o2’ （即 ‘o1.__eq__(o2) is True’ ）则
‘hash(o1) == hash(o2)``（即 ``o1.__hash__() == o2.__hash__()’ ），无论对
象是否在字典中。 如果你不能满足这些限制，字典和其他基于 hash 的结构将会
出错。

对于 ListWrapper ，只要包装器对象在字典中，包装列表就不能更改以避免异常
。除非你准备好认真考虑需求以及不正确地满足这些需求的后果，否则不要这样做
。请留意。


File: python.info,  Node: 为什么 list sort 没有返回排序列表？,  Next: 如何在Python中指定和实施接口规范？,  Prev: 为什么字典key必须是不可变的？,  Up: 设计和历史常见问题

11.3.21 为什么 list.sort() 没有返回排序列表？
---------------------------------------------

在性能很重要的情况下，仅仅为了排序而复制一份列表将是一种浪费。因此，
*note list.sort(): 44d. 对列表进行了适当的排序。为了提醒您这一事实，它不
会返回已排序的列表。这样，当您需要排序的副本，但也需要保留未排序的版本时
，就不会意外地覆盖列表。

如果要返回新列表，请使用内置 *note sorted(): 44c. 函数。此函数从提供的可
迭代列表中创建新列表，对其进行排序并返回。例如，下面是如何迭代遍历字典并
按keys排序:

     for key in sorted(mydict):
         ...  # do whatever with mydict[key]...


File: python.info,  Node: 如何在Python中指定和实施接口规范？,  Next: 为什么没有goto？,  Prev: 为什么 list sort 没有返回排序列表？,  Up: 设计和历史常见问题

11.3.22 如何在Python中指定和实施接口规范？
------------------------------------------

由C++和Java等语言提供的模块接口规范描述了模块的方法和函数的原型。许多人
认为接口规范的编译时强制执行有助于构建大型程序。

Python 2.6添加了一个 *note abc: 4. 模块，允许定义抽象基类 (ABCs)。然后可
以使用 *note isinstance(): 457. 和 *note issubclass(): 458. 来检查实例或
类是否实现了特定的ABC。 *note collections.abc: 1f. 模块定义了一组有用的
ABCs 例如 *note Iterable: 1962. ， *note Container: 1960. , 和 *note
MutableMapping: 9f7.

对于 Python，接口规范的许多好处可以通过组件的适当测试规程来获得。

一个好的模块测试套件既可以提供回归测试，也可以作为模块接口规范和一组示例
。许多Python模块可以作为脚本运行，以提供简单的“自我测试”。即使是使用复杂
外部接口的模块，也常常可以使用外部接口的简单“桩代码（stub）”模拟进行隔离
测试。可以使用 *note doctest: 67. 和 *note unittest: 11c. 模块或第三方测
试框架来构造详尽的测试套件，以运行模块中的每一行代码。

适当的测试规程可以帮助在Python中构建大型的、复杂的应用程序以及接口规范。
事实上，它可能会更好，因为接口规范不能测试程序的某些属性。例如，
‘append()’ 方法将向一些内部列表的末尾添加新元素；接口规范不能测试您的
‘append()’ 实现是否能够正确执行此操作，但是在测试套件中检查这个属性是很
简单的。

编写测试套件非常有用，您可能希望设计代码时着眼于使其易于测试。一种日益流
行的技术是面向测试的开发，它要求在编写任何实际代码之前，首先编写测试套件
的各个部分。当然，Python允许您草率行事，根本不编写测试用例。


File: python.info,  Node: 为什么没有goto？,  Next: 为什么原始字符串（r-strings）不能以反斜杠结尾？,  Prev: 如何在Python中指定和实施接口规范？,  Up: 设计和历史常见问题

11.3.23 为什么没有goto？
------------------------

在 1970 年代人们了解到不受限制的 goto 可能导致混乱得像“意大利面”那样难以
理解和修改的代码。 在高级语言中，它也是不必要的，只需有实现分支 (在
Python 中是使用 ‘if’ 语句以及 ‘or’, ‘and’ 和 ‘if-else’ 表达式) 和循环 (使
用 ‘while’ 和 ‘for’ 语句，并可能包含 ‘continue’ 和 ‘break’) 的手段就足够
了。

人们还可以使用异常捕获来提供甚至能跨函数调用的“结构化 goto”。 许多人认为
异常可以方便地模拟 C, Fortran 和其他语言中所有合理使用的“go”或“goto”构造
。 例如:

     class label(Exception): pass  # declare a label

     try:
         ...
         if condition: raise label()  # goto label
         ...
     except label:  # where to goto
         pass
     ...

但是不允许你跳到循环的中间，这通常被认为是滥用goto。谨慎使用。


File: python.info,  Node: 为什么原始字符串（r-strings）不能以反斜杠结尾？,  Next: 为什么Python没有属性赋值的“with”语句？,  Prev: 为什么没有goto？,  Up: 设计和历史常见问题

11.3.24 为什么原始字符串（r-strings）不能以反斜杠结尾？
-------------------------------------------------------

更准确地说，它们不能以奇数个反斜杠结束：结尾处的不成对反斜杠会转义结束引
号字符，留下未结束的字符串。

原始字符串的设计是为了方便想要执行自己的反斜杠转义处理的处理器(主要是正
则表达式引擎)创建输入。此类处理器将不匹配的尾随反斜杠视为错误，因此原始
字符串不允许这样做。反过来，允许通过使用引号字符转义反斜杠转义字符串。当
r-string用于它们的预期目的时，这些规则工作的很好。

如果您正在尝试构建Windows路径名，请注意所有Windows系统调用都使用正斜杠:

     f = open("/mydir/file.txt")  # works fine!

如果您正在尝试为DOS命令构建路径名，请尝试以下示例

     dir = r"\this\is\my\dos\dir" "\\"
     dir = r"\this\is\my\dos\dir\ "[:-1]
     dir = "\\this\\is\\my\\dos\\dir\\"


File: python.info,  Node: 为什么Python没有属性赋值的“with”语句？,  Next: 为什么 if/while/def/class语句需要冒号？,  Prev: 为什么原始字符串（r-strings）不能以反斜杠结尾？,  Up: 设计和历史常见问题

11.3.25 为什么Python没有属性赋值的“with”语句？
----------------------------------------------

Python有一个 ’with’ 语句，它封装了块的执行，在块的入口和出口调用代码。有
些语言的结构是这样的:

     with obj:
         a = 1               # equivalent to obj.a = 1
         total = total + 1   # obj.total = obj.total + 1

在Python中，这样的结构是不明确的。

其他语言，如ObjectPascal、Delphi和C++ 使用静态类型，因此可以毫不含糊地知
道分配给什么成员。这是静态类型的要点 – 编译器 `总是' 在编译时知道每个变
量的作用域。

Python使用动态类型。事先不可能知道在运行时引用哪个属性。可以动态地在对象
中添加或删除成员属性。这使得无法通过简单的阅读就知道引用的是什么属性：局
部属性、全局属性还是成员属性？

例如，采用以下不完整的代码段:

     def foo(a):
         with a:
             print(x)

该代码段假设 "a" 必须有一个名为 "x" 的成员属性。然而，Python中并没有告诉
解释器这一点。假设 "a" 是整数，会发生什么？如果有一个名为 "x" 的全局变量
，它是否会在with块中使用？如您所见，Python的动态特性使得这样的选择更加困
难。

然而，Python 可以通过赋值轻松实现 "with" 和类似语言特性（减少代码量）的
主要好处。代替:

     function(args).mydict[index][index].a = 21
     function(args).mydict[index][index].b = 42
     function(args).mydict[index][index].c = 63

写成这样:

     ref = function(args).mydict[index][index]
     ref.a = 21
     ref.b = 42
     ref.c = 63

这也具有提高执行速度的副作用，因为Python在运行时解析名称绑定，而第二个版
本只需要执行一次解析。


File: python.info,  Node: 为什么 if/while/def/class语句需要冒号？,  Next: 为什么Python在列表和元组的末尾允许使用逗号？,  Prev: 为什么Python没有属性赋值的“with”语句？,  Up: 设计和历史常见问题

11.3.26 为什么 if/while/def/class语句需要冒号？
-----------------------------------------------

冒号主要用于增强可读性(ABC语言实验的结果之一)。考虑一下这个:

     if a == b
         print(a)

与

     if a == b:
         print(a)

注意第二种方法稍微容易一些。请进一步注意，在这个FAQ解答的示例中，冒号是
如何设置的；这是英语中的标准用法。

另一个次要原因是冒号使带有语法突出显示的编辑器更容易工作；他们可以寻找冒
号来决定何时需要增加缩进，而不必对程序文本进行更精细的解析。


File: python.info,  Node: 为什么Python在列表和元组的末尾允许使用逗号？,  Prev: 为什么 if/while/def/class语句需要冒号？,  Up: 设计和历史常见问题

11.3.27 为什么Python在列表和元组的末尾允许使用逗号？
----------------------------------------------------

Python 允许您在列表，元组和字典的末尾添加一个尾随逗号:

     [1, 2, 3,]
     ('a', 'b', 'c',)
     d = {
         "A": [1, 5],
         "B": [6, 7],  # last trailing comma is optional but good style
     }

有几个理由允许这样做。

如果列表，元组或字典的字面值分布在多行中，则更容易添加更多元素，因为不必
记住在上一行中添加逗号。这些行也可以重新排序，而不会产生语法错误。

不小心省略逗号会导致难以诊断的错误。例如:

     x = [
       "fee",
       "fie"
       "foo",
       "fum"
     ]

这个列表看起来有四个元素，但实际上包含三个 : "fee", "fiefoo" 和 "fum" 。
总是加上逗号可以避免这个错误的来源。

允许尾随逗号也可以使编程代码更容易生成。


File: python.info,  Node: 代码库和插件 FAQ,  Next: 扩展/嵌入常见问题,  Prev: 设计和历史常见问题,  Up: Python 常见问题

11.4 代码库和插件 FAQ
=====================

* Menu:

* 通用的代码库问题::
* 通用任务::
* 线程相关::
* 输入输出: 输入输出<2>.
* 网络 / Internet 编程::
* 数据库::
* 数学和数字::


File: python.info,  Node: 通用的代码库问题,  Next: 通用任务,  Up: 代码库和插件 FAQ

11.4.1 通用的代码库问题
-----------------------

* Menu:

* 如何找到可以用来做 XXX 的模块或应用？::
* math.py（socket.py，regex.py 等）的源文件在哪？: math py（socket py，regex py 等）的源文件在哪？.
* 在 Unix 中怎样让 Python 脚本可执行？::
* Python 中有 curses/termcap 包吗？::
* Python 中存在类似 C 的 onexit() 函数的东西吗？: Python 中存在类似 C 的 onexit 函数的东西吗？.
* 为什么我的信号处理函数不能工作？::


File: python.info,  Node: 如何找到可以用来做 XXX 的模块或应用？,  Next: math py（socket py，regex py 等）的源文件在哪？,  Up: 通用的代码库问题

11.4.1.1 如何找到可以用来做 XXX 的模块或应用？
..............................................

在 *note 代码库参考: 120b. 中查找是否有适合的标准库模块。（如果你已经了
解标准库的内容，可以跳过这一步）

对于第三方软件包，请搜索 Python Package Index(1) 或是 Google(2) 等其他搜
索引擎。用“Python”加上一两个你需要的关键字通常会找到有用的东西。

   ---------- Footnotes ----------

   (1) https://pypi.org

   (2) https://www.google.com


File: python.info,  Node: math py（socket py，regex py 等）的源文件在哪？,  Next: 在 Unix 中怎样让 Python 脚本可执行？,  Prev: 如何找到可以用来做 XXX 的模块或应用？,  Up: 通用的代码库问题

11.4.1.2 math.py（socket.py，regex.py 等）的源文件在哪？
........................................................

如果找不到模块的源文件，可能它是一个内建的模块，或是使用 C，C++ 或其他编
译型语言实现的动态加载模块。这种情况下可能是没有源码文件的，类似
‘mathmodule.c’ 这样的文件会存放在 C 代码目录中（但不在 Python 目录中）。

Python 中（至少）有三类模块：

  1. 使用 Python 编写的模块（.py)；

  2. 使用 C 编写的动态加载模块（.dll，.pyd，.so，.sl 等）；

  3. 使用 C 编写并链接到解释器的模块，要获取此列表，输入：

          import sys
          print(sys.builtin_module_names)


File: python.info,  Node: 在 Unix 中怎样让 Python 脚本可执行？,  Next: Python 中有 curses/termcap 包吗？,  Prev: math py（socket py，regex py 等）的源文件在哪？,  Up: 通用的代码库问题

11.4.1.3 在 Unix 中怎样让 Python 脚本可执行？
.............................................

你需要做两件事：文件必须是可执行的，并且第一行需要以 ‘#!’ 开头，后面跟上
Python 解释器的路径。

第一点可以用执行 ‘chmod +x scriptfile’ 或是 ‘chmod 755 scriptfile’ 做到
。

第二点有很多种做法，最直接的方式是：

     #!/usr/local/bin/python

在文件第一行，使用你所在平台上的 Python 解释器的路径。

如果你希望脚本不依赖 Python 解释器的具体路径，你也可以使用 ‘env’ 程序。
假设你的 Python 解释器所在目录已经添加到了 ‘PATH’ 环境变量中，几乎所有的
类 Unix 系统都支持下面的写法：

     #!/usr/bin/env python

`不要' 在 CGI 脚本中这样做。CGI 脚本的 ‘PATH’ 环境变量通常会非常精简，所
以你必须使用解释器的完整绝对路径。

有时候，用户的环境变量如果太长，可能会导致 ‘/usr/bin/env’ 执行失败；又或
者甚至根本就不存在 env 程序。在这种情况下，你可以尝试使用下面的 hack 方
法（来自 Alex Rezinsky）：

     #! /bin/sh
     """:"
     exec python $0 ${1+"$@"}
     """

这样做有一个小小的缺点，它会定义脚本的 __doc__ 字符串。不过可以这样修复
：

     __doc__ = """...Whatever..."""


File: python.info,  Node: Python 中有 curses/termcap 包吗？,  Next: Python 中存在类似 C 的 onexit 函数的东西吗？,  Prev: 在 Unix 中怎样让 Python 脚本可执行？,  Up: 通用的代码库问题

11.4.1.4 Python 中有 curses/termcap 包吗？
..........................................

对于类 Unix 系统：标准 Python 源码发行版会在 Modules(1) 子目录中附带
curses 模块，但默认并不会编译。（注意：在 Windows 平台下不可用 ——
Windows 中没有 curses 模块。）

*note curses: 2c. 模块支持基本的 curses 特性，同时也支持 ncurses 和 SYSV
curses 中的很多额外功能，比如颜色、不同的字符集支持、填充和鼠标支持。这
意味着这个模块不兼容只有 BSD curses 模块的操作系统，但是目前仍在维护的系
统应该都不会存在这种情况。

对于 Windows 平台：使用 consolelib 模块(2).

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Modules

   (2) http://effbot.org/zone/console-index.htm


File: python.info,  Node: Python 中存在类似 C 的 onexit 函数的东西吗？,  Next: 为什么我的信号处理函数不能工作？,  Prev: Python 中有 curses/termcap 包吗？,  Up: 通用的代码库问题

11.4.1.5 Python 中存在类似 C 的 onexit() 函数的东西吗？
.......................................................

*note atexit: c. 模块提供了一个与 C 的 ‘onexit()’ 函数类似的注册函数。


File: python.info,  Node: 为什么我的信号处理函数不能工作？,  Prev: Python 中存在类似 C 的 onexit 函数的东西吗？,  Up: 通用的代码库问题

11.4.1.6 为什么我的信号处理函数不能工作？
.........................................

最常见的问题是信号处理函数没有正确定义参数列表。它会被这样调用：

     handler(signum, frame)

因此函数应该定义两个参数：

     def handler(signum, frame):
         ...


File: python.info,  Node: 通用任务,  Next: 线程相关,  Prev: 通用的代码库问题,  Up: 代码库和插件 FAQ

11.4.2 通用任务
---------------

* Menu:

* 怎样测试 Python 程序或组件？::
* 怎样用 docstring 创建文档？::
* 怎样一次只获取一个按键？::


File: python.info,  Node: 怎样测试 Python 程序或组件？,  Next: 怎样用 docstring 创建文档？,  Up: 通用任务

11.4.2.1 怎样测试 Python 程序或组件？
.....................................

Python 带有两个测试框架。*note doctest: 67. 模块从模块的 docstring 中寻
找示例并执行，对比输出是否与 docstring 中给出的是否一致。

*note unittest: 11c. 模块是一个模仿 Java 和 Smalltalk 测试框架的更棒的测
试框架。

为了使测试更容易，你应该在程序中使用良好的模块化设计。程序中的绝大多数功
能都应该用函数或类方法封装 —— 有时这样做会有额外惊喜，程序会运行得更快（
因为局部变量比全局变量访问要快）。除此之外，程序应该避免依赖可变的局部变
量，这会使得测试困难许多。

程序的“全局主逻辑”应该尽量简单：

     if __name__ == "__main__":
         main_logic()

并放置在程序主模块的最后面。

一旦你的程序已经用函数和类完善地组织起来，你就应该编写测试函数来测试其行
为。可以使用自动执行一系列测试函数的测试集与每个模块进行关联。听起来似乎
需要大量的工作，但是因为 Python 非常简洁和灵活，所以实际上会相当简单。在
编写“生产代码”的同时别忘了也要编写测试函数，你会发现编程会变得更愉快、更
有趣，因为这样会使得发现 bug 和设计缺陷更加容易。

程序主模块之外的其他“辅助模块”中可以增加自测试的入口。

     if __name__ == "__main__":
         self_test()

通过使用 Python 实现的“假”接口，即使是需要与复杂的外部接口交互的程序也可
以在外部接口不可用时进行测试。


File: python.info,  Node: 怎样用 docstring 创建文档？,  Next: 怎样一次只获取一个按键？,  Prev: 怎样测试 Python 程序或组件？,  Up: 通用任务

11.4.2.2 怎样用 docstring 创建文档？
....................................

*note pydoc: da. 模块可以用 Python 源码中的 docstring 创建 HTML 文件。也
可以使用 epydoc(1) 来只通过 docstring 创建 API 文档。Sphinx(2) 也可以引
入 docstring 的内容。

   ---------- Footnotes ----------

   (1) http://epydoc.sourceforge.net/

   (2) http://sphinx-doc.org


File: python.info,  Node: 怎样一次只获取一个按键？,  Prev: 怎样用 docstring 创建文档？,  Up: 通用任务

11.4.2.3 怎样一次只获取一个按键？
.................................

在类 Unix 系统中有多种方案。最直接的方法是使用 curses，但是 curses 模块
太大了，难以学习。


File: python.info,  Node: 线程相关,  Next: 输入输出<2>,  Prev: 通用任务,  Up: 代码库和插件 FAQ

11.4.3 线程相关
---------------

* Menu:

* 程序中怎样使用线程？::
* 我的线程都没有运行，为什么？::
* 如何将任务分配给多个工作线程？::
* 怎样修改全局变量是线程安全的？::
* 不能删除全局解释器锁吗？::


File: python.info,  Node: 程序中怎样使用线程？,  Next: 我的线程都没有运行，为什么？,  Up: 线程相关

11.4.3.1 程序中怎样使用线程？
.............................

一定要使用 *note threading: 10a. 模块，不要使用 *note _thread: 3. 模块。
*note threading: 10a. 模块对 *note _thread: 3. 模块提供的底层线程原语做
了更易用的抽象。

Aahz 的非常实用的 threading 教程中有一些幻灯片；可以参阅
‘http://www.pythoncraft.com/OSCON2001/’ 。


File: python.info,  Node: 我的线程都没有运行，为什么？,  Next: 如何将任务分配给多个工作线程？,  Prev: 程序中怎样使用线程？,  Up: 线程相关

11.4.3.2 我的线程都没有运行，为什么？
.....................................

一旦主线程退出，所有的子线程都会被杀掉。你的主线程运行得太快了，子线程还
没来得及工作。

简单的解决方法是在程序中加一个时间足够长的 sleep，让子线程能够完成运行。

     import threading, time

     def thread_task(name, n):
         for i in range(n):
             print(name, i)

     for i in range(10):
         T = threading.Thread(target=thread_task, args=(str(i), i))
         T.start()

     time.sleep(10)  # <---------------------------!

但目前（在许多平台上）线程不是并行运行的，而是按顺序依次执行！原因是系统
线程调度器在前一个线程阻塞之前不会启动新线程。

简单的解决方法是在运行函数的开始处加一个时间很短的 sleep。

     def thread_task(name, n):
         time.sleep(0.001)  # <--------------------!
         for i in range(n):
             print(name, i)

     for i in range(10):
         T = threading.Thread(target=thread_task, args=(str(i), i))
         T.start()

     time.sleep(10)

比起用 *note time.sleep(): 689. 猜一个合适的等待时间，使用信号量机制会更
好些。有一个办法是使用 *note queue: db. 模块创建一个 queue 对象，让每一
个线程在运行结束时 append 一个令牌到 queue 对象中，主线程中从 queue 对象
中读取与线程数量一致的令牌数量即可。


File: python.info,  Node: 如何将任务分配给多个工作线程？,  Next: 怎样修改全局变量是线程安全的？,  Prev: 我的线程都没有运行，为什么？,  Up: 线程相关

11.4.3.3 如何将任务分配给多个工作线程？
.......................................

最简单的方法是使用新的 *note concurrent.futures: 22. 模块，尤其是其中的
*note ThreadPoolExecutor: 27b. 类。

或者，如果你想更好地控制分发算法，你也可以自己写逻辑实现。使用 *note
queue: db. 模块来创建任务列表队列。*note Queue: d20. 类维护一个了一个存
有对象的列表，提供了 ‘.put(obj)’ 方法添加元素，并且可以用 ‘.get()’ 方法
获取元素。这个类会使用必要的加锁操作，以此确保每个任务只会执行一次。

这是一个简单的例子：

     import threading, queue, time

     # The worker thread gets jobs off the queue.  When the queue is empty, it
     # assumes there will be no more work and exits.
     # (Realistically workers will run until terminated.)
     def worker():
         print('Running worker')
         time.sleep(0.1)
         while True:
             try:
                 arg = q.get(block=False)
             except queue.Empty:
                 print('Worker', threading.currentThread(), end=' ')
                 print('queue empty')
                 break
             else:
                 print('Worker', threading.currentThread(), end=' ')
                 print('running with argument', arg)
                 time.sleep(0.5)

     # Create queue
     q = queue.Queue()

     # Start a pool of 5 workers
     for i in range(5):
         t = threading.Thread(target=worker, name='worker %i' % (i+1))
         t.start()

     # Begin adding work to the queue
     for i in range(50):
         q.put(i)

     # Give threads time to run
     print('Main thread sleeping')
     time.sleep(5)

运行时会产生如下输出：

     Running worker
     Running worker
     Running worker
     Running worker
     Running worker
     Main thread sleeping
     Worker <Thread(worker 1, started 130283832797456)> running with argument 0
     Worker <Thread(worker 2, started 130283824404752)> running with argument 1
     Worker <Thread(worker 3, started 130283816012048)> running with argument 2
     Worker <Thread(worker 4, started 130283807619344)> running with argument 3
     Worker <Thread(worker 5, started 130283799226640)> running with argument 4
     Worker <Thread(worker 1, started 130283832797456)> running with argument 5
     ...

查看模块的文档以获取更多信息；*note Queue: d20. 类提供了多种接口。


File: python.info,  Node: 怎样修改全局变量是线程安全的？,  Next: 不能删除全局解释器锁吗？,  Prev: 如何将任务分配给多个工作线程？,  Up: 线程相关

11.4.3.4 怎样修改全局变量是线程安全的？
.......................................

Python VM 内部会使用 *note global interpreter lock: 50e. （GIL）来确保同
一时间只有一个线程运行。通常 Python 只会在字节码指令之间切换线程；切换的
频率可以通过设置 *note sys.setswitchinterval(): bf3. 指定。从 Python 程
序的角度来看，每一条字节码指令以及每一条指令对应的 C 代码实现都是原子的
。

理论上说，具体的结果要看具体的 PVM 字节码实现对指令的解释。而实际上，对
内建类型（int，list，dict 等）的共享变量的“类原子”操作都是原子的。

举例来说，下面的操作是原子的（L、L1、L2 是列表，D、D1、D2 是字典，x、y 是
对象，i，j 是 int 变量）：

     L.append(x)
     L1.extend(L2)
     x = L[i]
     x = L.pop()
     L1[i:j] = L2
     L.sort()
     x = y
     x.field = y
     D[x] = y
     D1.update(D2)
     D.keys()

这些不是原子的：

     i = i+1
     L.append(L[-1])
     L[i] = L[j]
     D[x] = D[x] + 1

覆盖其他对象的操作会在其他对象的引用计数变成 0 时触发其 *note __del__():
927. 方法，这可能会产生一些影响。对字典和列表进行大量操作时尤其如此。如
果有疑问的话，使用互斥锁！


File: python.info,  Node: 不能删除全局解释器锁吗？,  Prev: 怎样修改全局变量是线程安全的？,  Up: 线程相关

11.4.3.5 不能删除全局解释器锁吗？
.................................

*note global interpreter lock: 50e. （GIL）通常被视为 Python 在高端多核
服务器上开发时的阻力，因为（几乎）所有 Python 代码只有在获取到 GIL 时才
能运行，所以多线程的 Python 程序只能有效地使用一个 CPU。

在 Python 1.5 时代，Greg Stein 开发了一个完整的补丁包（“free threadings”
补丁），移除了 GIL，并用粒度更合适的锁来代替。Adam Olsen 最近也在他的
python-safethread(1) 项目里做了类似的实验。不幸的是，由于为了移除 GIL 而
使用了大量细粒度的锁，这两个实验在单线程测试中的性能都有明显的下降（至少
慢 30%）。

但这并意味着你不能在多核机器上很好地使用 Python！你只需将任务划分为多*进
程*，而不是多*线程*。新的 *note concurrent.futures: 22. 模块中的 *note
ProcessPoolExecutor: 2a4. 类提供了一个简单的方法；如果你想对任务分发做更
多控制，可以使用 *note multiprocessing: b8. 模块提供的底层 API。

恰当地使用 C 拓展也很有用；使用 C 拓展处理耗时较久的任务时，拓展可以在线
程执行 C 代码时释放 GIL，让其他线程执行。*note zlib: 145. 和 *note
hashlib: 8d. 等标准库模块已经这样做了。

也有建议说 GIL 应该是解释器状态锁，而不是完全的全局锁；解释器不应该共享
对象。不幸的是，这也不可能发生。由于目前许多对象的实现都有全局的状态，因
此这是一个艰巨的工作。举例来说，小整型数和短字符串会缓存起来，这些缓存将
不得不移动到解释器状态中。其他对象类型都有自己的自由变量列表，这些自由变
量列表也必须移动到解释器状态中。等等。

我甚至怀疑这些工作是否可能在有限的时间内完成，因为同样的问题在第三方拓展
中也会存在。第三方拓展编写的速度可比你将它们转换为把全局状态存入解释器状
态中的速度快得多。

最后，假设多个解释器不共享任何状态，那么这样做比每个进程一个解释器好在哪
里呢？

   ---------- Footnotes ----------

   (1) https://code.google.com/archive/p/python-safethread


File: python.info,  Node: 输入输出<2>,  Next: 网络 / Internet 编程,  Prev: 线程相关,  Up: 代码库和插件 FAQ

11.4.4 输入输出
---------------

* Menu:

* 怎样删除文件？（以及其他文件相关的问题……）::
* 怎样复制文件？::
* 怎样读取（或写入）二进制数据？::
* 似乎 os.popen() 创建的管道不能使用 os.read()，这是为什么？: 似乎 os popen 创建的管道不能使用 os read ，这是为什么？.
* 怎样访问（RS232）串口？::
* 为什么关闭 sys.stdout（stdin，stderr）并不会真正关掉它？: 为什么关闭 sys stdout（stdin，stderr）并不会真正关掉它？.


File: python.info,  Node: 怎样删除文件？（以及其他文件相关的问题……）,  Next: 怎样复制文件？,  Up: 输入输出<2>

11.4.4.1 怎样删除文件？（以及其他文件相关的问题……）
...................................................

使用 ‘os.remove(filename)’ 或 ‘os.unlink(filename)’。查看 *note os: c5.
模块以获取更多文档。这两个函数是一样的，*note unlink(): a44. 是这个函数
在 Unix 系统调用中的名字。

如果要删除目录，应该使用 *note os.rmdir(): a42.；使用 *note os.mkdir():
a3e. 创建目录。‘os.makedirs(path)’ 会创建 ‘path’ 中任何不存在的目录。
‘os.removedirs(path)’ 则会删除其中的目录，只要它们都是空的；如果你想删除
整个目录以及其中的内容，可以使用 *note shutil.rmtree(): 21d.。

重命名文件可以使用 ‘os.rename(old_path, new_path)’。

如果需要截断文件，使用 ‘f = open(filename, "rb+")’ 打开文件，然后使用
‘f.truncate(offset)’；offset 默认是当前的搜索位置。也可以对使用 *note
os.open(): 66e. 打开的文件使用 ‘os.ftruncate(fd, offset)’，其中 `fd' 是
文件描述符（一个小的整型数）。

*note shutil: ea. 模块也包含了一些处理文件的函数，包括 *note copyfile():
259.，*note copytree(): 21b. 和 *note rmtree(): 21d.。


File: python.info,  Node: 怎样复制文件？,  Next: 怎样读取（或写入）二进制数据？,  Prev: 怎样删除文件？（以及其他文件相关的问题……）,  Up: 输入输出<2>

11.4.4.2 怎样复制文件？
.......................

*note shutil: ea. 模块有一个 *note copyfile(): 259. 函数。注意在 MacOS 9
中不会复制 resource fork 和 Finder info。


File: python.info,  Node: 怎样读取（或写入）二进制数据？,  Next: 似乎 os popen 创建的管道不能使用 os read ，这是为什么？,  Prev: 怎样复制文件？,  Up: 输入输出<2>

11.4.4.3 怎样读取（或写入）二进制数据？
.......................................

要读写复杂的二进制数据格式，最好使用 *note struct: f9. 模块。该模块可以
读取包含二进制数据（通常是数字）的字符串并转换为 Python 对象，反之亦然。

举例来说，下面的代码会从文件中以大端序格式读取一个 2 字节的整型和一个 4
字节的整型：

     import struct

     with open(filename, "rb") as f:
         s = f.read(8)
         x, y, z = struct.unpack(">hhl", s)

格式字符串中的 ‘>’ 强制以大端序读取数据；字母 ‘h’ 从字符串中读取一个“短
整型”（2 字节），字母 ‘l’ 读取一个“长整型”（4 字节）。

对于更常规的数据（例如整型或浮点类型的列表），你也可以使用 *note array:
7. 模块。

     注解: 要读写二进制数据的话，需要强制以二进制模式打开文件（这里为
     *note open(): 4f8. 函数传入 ‘"rb"’）。如果（默认）传入 ‘"r"’ 的话，
     文件会以文本模式打开，‘f.read()’ 会返回 *note str: 339. 对象，而不
     是 *note bytes: 33a. 对象。


File: python.info,  Node: 似乎 os popen 创建的管道不能使用 os read ，这是为什么？,  Next: 怎样访问（RS232）串口？,  Prev: 怎样读取（或写入）二进制数据？,  Up: 输入输出<2>

11.4.4.4 似乎 os.popen() 创建的管道不能使用 os.read()，这是为什么？
...................................................................

*note os.read(): 671. 是一个底层函数，它接收的是文件描述符 —— 用小整型数
表示的打开的文件。*note os.popen(): 2aa. 创建的是一个高级文件对象，和内
建的 *note open(): 4f8. 方法返回的类型一样。因此，如果要从 *note
os.popen(): 2aa. 创建的管道 `p' 中读取 `n' 个字节的话，你应该使用
‘p.read(n)’。


File: python.info,  Node: 怎样访问（RS232）串口？,  Next: 为什么关闭 sys stdout（stdin，stderr）并不会真正关掉它？,  Prev: 似乎 os popen 创建的管道不能使用 os read ，这是为什么？,  Up: 输入输出<2>

11.4.4.5 怎样访问（RS232）串口？
................................

对于 Win32，POSIX（Linux，BSD 等），Jython：

     ‘http://pyserial.sourceforge.net’

对于 Unix，查看 Mitch Chapman 发布的帖子：

     ‘https://groups.google.com/groups?selm=34A04430.CF9@ohioee.com’


File: python.info,  Node: 为什么关闭 sys stdout（stdin，stderr）并不会真正关掉它？,  Prev: 怎样访问（RS232）串口？,  Up: 输入输出<2>

11.4.4.6 为什么关闭 sys.stdout（stdin，stderr）并不会真正关掉它？
.................................................................

Python *note 文件对象: b4a. 是一个对底层 C 文件描述符的高层抽象。

对于在 Python 中通过内建的 *note open(): 4f8. 函数创建的多数文件对象来说
，‘f.close()’ 从 Python 的角度将其标记为已关闭，并且会关闭底层的 C 文件
描述符。在 ‘f’ 被垃圾回收的时候，析构函数中也会自动处理。

但由于 stdin，stdout 和 stderr 在 C 中的特殊地位，在 Python 中也会对它们
做特殊处理。运行 ‘sys.stdout.close()’ 会将 Python 的文件对象标记为已关闭
，但是*不会*关闭与之关联的文件描述符。

要关闭这三者的 C 文件描述符的话，首先你应该确认确实需要关闭它（比如，这
可能会影响到处理 I/O 的拓展）。如果确实需要这么做的话，使用 *note
os.close(): 3da.：

     os.close(stdin.fileno())
     os.close(stdout.fileno())
     os.close(stderr.fileno())

或者也可以使用常量 0，1，2 代替。


File: python.info,  Node: 网络 / Internet 编程,  Next: 数据库,  Prev: 输入输出<2>,  Up: 代码库和插件 FAQ

11.4.5 网络 / Internet 编程
---------------------------

* Menu:

* Python 中的 WWW 工具是什么？::
* 怎样模拟发送 CGI 表单（METHOD=POST）？::
* 生成 HTML 需要使用什么模块？::
* 怎样使用 Python 脚本发送邮件？::
* socket 的 connect() 方法怎样避免阻塞？: socket 的 connect 方法怎样避免阻塞？.


File: python.info,  Node: Python 中的 WWW 工具是什么？,  Next: 怎样模拟发送 CGI 表单（METHOD=POST）？,  Up: 网络 / Internet 编程

11.4.5.1 Python 中的 WWW 工具是什么？
.....................................

参阅代码库参考手册中 *note 互联网协议和支持: 2bd9. 和 *note
互联网数据处理: 27de. 这两章的内容。Python 有大量模块来帮助你构建服务端
和客户端 web 系统。

Paul Boddie 维护了一份可用框架的概览，见
‘https://wiki.python.org/moin/WebProgramming’ 。

Cameron Laird 维护了一份关于 Python web 技术的实用网页的集合，见
‘http://phaseit.net/claird/comp.lang.python/web_python’ 。


File: python.info,  Node: 怎样模拟发送 CGI 表单（METHOD=POST）？,  Next: 生成 HTML 需要使用什么模块？,  Prev: Python 中的 WWW 工具是什么？,  Up: 网络 / Internet 编程

11.4.5.2 怎样模拟发送 CGI 表单（METHOD=POST）？
...............................................

我需要通过 POST 表单获取网页，有什么代码能简单做到吗？

是的，这里有一个使用 urllib.request 的简单例子：

     #!/usr/local/bin/python

     import urllib.request

     # build the query string
     qs = "First=Josephine&MI=Q&Last=Public"

     # connect and send the server a path
     req = urllib.request.urlopen('http://www.some-server.out-there'
                                  '/cgi-bin/some-cgi-script', data=qs)
     with req:
         msg, hdrs = req.read(), req.info()

注意，通常在百分号编码的 POST 操作中，查询字符串必须使用 *note
urllib.parse.urlencode(): 794. 处理一下。举个例子，如果要发送 ‘name=Guy
Steele, Jr.’ 的话：

     >>> import urllib.parse
     >>> urllib.parse.urlencode({'name': 'Guy Steele, Jr.'})
     'name=Guy+Steele%2C+Jr.'

参见
....

查看 *note HOWTO 使用 urllib 包获取网络资源: 2cbc. 获取更多示例。


File: python.info,  Node: 生成 HTML 需要使用什么模块？,  Next: 怎样使用 Python 脚本发送邮件？,  Prev: 怎样模拟发送 CGI 表单（METHOD=POST）？,  Up: 网络 / Internet 编程

11.4.5.3 生成 HTML 需要使用什么模块？
.....................................

你可以在 Web 编程 wiki 页面(1) 找到许多有用的链接。

   ---------- Footnotes ----------

   (1) https://wiki.python.org/moin/WebProgramming


File: python.info,  Node: 怎样使用 Python 脚本发送邮件？,  Next: socket 的 connect 方法怎样避免阻塞？,  Prev: 生成 HTML 需要使用什么模块？,  Up: 网络 / Internet 编程

11.4.5.4 怎样使用 Python 脚本发送邮件？
.......................................

使用 *note smtplib: ee. 标准库模块。

下面是一个很简单的交互式发送邮件的代码。这个方法适用于任何支持 SMTP 协议
的主机。

     import sys, smtplib

     fromaddr = input("From: ")
     toaddrs  = input("To: ").split(',')
     print("Enter message, end with ^D:")
     msg = ''
     while True:
         line = sys.stdin.readline()
         if not line:
             break
         msg += line

     # The actual mail send
     server = smtplib.SMTP('localhost')
     server.sendmail(fromaddr, toaddrs, msg)
     server.quit()

在 Unix 系统中还可以使用 sendmail。sendmail 程序的位置在不同系统中不一样
，有时是在 ‘/usr/lib/sendmail’，有时是在 ‘/usr/sbin/sendmail’。sendmail
手册页面会对你有所帮助。以下是示例代码：

     import os

     SENDMAIL = "/usr/sbin/sendmail"  # sendmail location
     p = os.popen("%s -t -i" % SENDMAIL, "w")
     p.write("To: receiver@example.com\n")
     p.write("Subject: test\n")
     p.write("\n")  # blank line separating headers from body
     p.write("Some text\n")
     p.write("some more text\n")
     sts = p.close()
     if sts != 0:
         print("Sendmail exit status", sts)


File: python.info,  Node: socket 的 connect 方法怎样避免阻塞？,  Prev: 怎样使用 Python 脚本发送邮件？,  Up: 网络 / Internet 编程

11.4.5.5 socket 的 connect() 方法怎样避免阻塞？
...............................................

通常会用 *note select: e6. 模块处理 socket 异步 I/O。

要避免 TCP 连接阻塞，你可以设置将 socket 设置为非阻塞模式。此时当调用
‘connect()’ 时，要么连接会立刻建立好（几乎不可能），要么会收到一个包含了
错误码 ‘.error’ 的异常。‘errno.EINPROGRESS’ 表示连接正在进行，但还没有完
成。不同的系统会返回不同的值，所以你需要确认你使用的系统会返回什么。

你可以使用 ‘connect_ex()’ 方法来避免产生异常。这个方法只会返回错误码。如
果需要轮询的话，你可以再次调用 ‘connect_ex()’ —— ‘0’ 或 ‘errno.EISCONN’
表示连接已建立，或者你也可以用 select 检查这个 socket 是否可写。

     注解: *note asyncore: b. 模块提供了编写非阻塞网络代码框架性的方法。
     第三方的 Twisted(1) 库也很常用且功能强大。

   ---------- Footnotes ----------

   (1) https://twistedmatrix.com/trac/


File: python.info,  Node: 数据库,  Next: 数学和数字,  Prev: 网络 / Internet 编程,  Up: 代码库和插件 FAQ

11.4.6 数据库
-------------

* Menu:

* Python 中有数据库包的接口吗？::
* 在 Python 中如何实现持久化对象？::


File: python.info,  Node: Python 中有数据库包的接口吗？,  Next: 在 Python 中如何实现持久化对象？,  Up: 数据库

11.4.6.1 Python 中有数据库包的接口吗？
......................................

有的。

标准 Python 还包含了基于磁盘的哈希接口例如 *note DBM: 35. 和 *note GDBM:
34. 。除此之外还有 *note sqlite3: f3. 模块，该模块提供了一个轻量级的基于
磁盘的关系型数据库。

大多数关系型数据库都已经支持。查看 数据库编程 wiki 页面(1) 获取更多信息
。

   ---------- Footnotes ----------

   (1) https://wiki.python.org/moin/DatabaseProgramming


File: python.info,  Node: 在 Python 中如何实现持久化对象？,  Prev: Python 中有数据库包的接口吗？,  Up: 数据库

11.4.6.2 在 Python 中如何实现持久化对象？
.........................................

*note pickle: cb. 库模块以一种非常通用的方式解决了这个问题（虽然你依然不
能用它保存打开的文件、套接字或窗口之类的东西），此外 *note shelve: e8. 库
模块可使用 pickle 和 (g)dbm 来创建包含任意 Python 对象的持久化映射。


File: python.info,  Node: 数学和数字,  Prev: 数据库,  Up: 代码库和插件 FAQ

11.4.7 数学和数字
-----------------

* Menu:

* Python 中怎样生成随机数？::


File: python.info,  Node: Python 中怎样生成随机数？,  Up: 数学和数字

11.4.7.1 Python 中怎样生成随机数？
..................................

*note random: dd. 标准库模块实现了随机数生成器，使用起来非常简单：

     import random
     random.random()

这个函数会返回 [0, 1) 之间的随机浮点数。

该模块中还有许多其他的专门的生成器，例如：

   * ‘randrange(a, b)’ 返回 [a, b) 区间内的一个整型数。

   * ‘uniform(a, b)’ 返回 [a, b) 区间之间的浮点数。

   * ‘normalvariate(mean, sdev)’ 使用正态（高斯）分布采样。

还有一些高级函数直接对序列进行操作，例如：

   * ‘choice(S)’ 从给定的序列中随机选择一个元素。

   * ‘shuffle(L)’ 对列表进行原地重排，也就是说随机打乱。

还有 ‘Random’ 类，你可以将其实例化，用来创建多个独立的随机数生成器。


File: python.info,  Node: 扩展/嵌入常见问题,  Next: Python在Windows上的常见问题,  Prev: 代码库和插件 FAQ,  Up: Python 常见问题

11.5 扩展/嵌入常见问题
======================

* Menu:

* 可以使用 C 语言创建自己的函数吗？::
* 可以使用 C++ 语言创建自己的函数吗？::
* C很难写，有没有其他选择？::
* 如何在 C 中执行任意 Python 语句？::
* 如何在 C 中对任意 Python 表达式求值？::
* 如何从Python对象中提取C的值？::
* 如何使用Py_BuildValue()创建任意长度的元组？: 如何使用Py_BuildValue 创建任意长度的元组？.
* 如何从C调用对象的方法？::
* 如何捕获PyErr_Print()（或打印到stdout / stderr的任何内容）的输出？: 如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？.
* 如何从C访问用Python编写的模块？::
* 如何在 Python 中对接 C ++ 对象？::
* 我使用Setup文件添加了一个模块，为什么make失败了？::
* 如何调试扩展？::
* 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?::
* 如何区分“输入不完整”和“输入无效”？::
* 如何找到未定义的g++符号__builtin_new或__pure_virtual？::
* 能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？::


File: python.info,  Node: 可以使用 C 语言创建自己的函数吗？,  Next: 可以使用 C++ 语言创建自己的函数吗？,  Up: 扩展/嵌入常见问题

11.5.1 可以使用 C 语言创建自己的函数吗？
----------------------------------------

是的，您可以在C中创建包含函数、变量、异常甚至新类型的内置模块。在文档
*note 扩展和嵌入 Python 解释器: 120d. 中有说明。

大多数中级或高级的Python书籍也涵盖这个主题。


File: python.info,  Node: 可以使用 C++ 语言创建自己的函数吗？,  Next: C很难写，有没有其他选择？,  Prev: 可以使用 C 语言创建自己的函数吗？,  Up: 扩展/嵌入常见问题

11.5.2 可以使用 C++ 语言创建自己的函数吗？
------------------------------------------

是的，可以使用C ++中兼容C的功能。 在Python include文件周围放置‘
‘extern“C”{...}‘’ ，并在Python解释器调用的每个函数之前放置 ‘extern“C”’ 。
具有构造函数的全局或静态C ++对象可能不是一个好主意。


File: python.info,  Node: C很难写，有没有其他选择？,  Next: 如何在 C 中执行任意 Python 语句？,  Prev: 可以使用 C++ 语言创建自己的函数吗？,  Up: 扩展/嵌入常见问题

11.5.3 C很难写，有没有其他选择？
--------------------------------

编写自己的C扩展有很多选择，具体取决于您要做的事情。

Cython(1) 及其相关的 Pyrex(2) 是接受稍微修改过的Python形式并生成相应C代
码的编译器。 Cython和Pyrex可以编写扩展而无需学习Python的C API。

如果需要连接到某些当前不存在Python扩展的C或C ++库，可以尝试使用 SWIG(3)
等工具包装库的数据类型和函数。 SIP(4) ， CXX(5) Boost(6) , 或 Weave(7) 也
是包装C ++库的替代方案。

   ---------- Footnotes ----------

   (1) http://cython.org

   (2) https://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/

   (3) http://www.swig.org

   (4) https://riverbankcomputing.com/software/sip/intro

   (5) http://cxx.sourceforge.net/

   (6) http://www.boost.org/libs/python/doc/index.html

   (7) https://github.com/scipy/weave


File: python.info,  Node: 如何在 C 中执行任意 Python 语句？,  Next: 如何在 C 中对任意 Python 表达式求值？,  Prev: C很难写，有没有其他选择？,  Up: 扩展/嵌入常见问题

11.5.4 如何在 C 中执行任意 Python 语句？
----------------------------------------

执行此操作的最高层级函数为 *note PyRun_SimpleString(): 3b8a.，它接受单个
字符串参数用于在模块 ‘__main__’ 的上下文中执行并在成功时返回 ‘0’ 而在发
生异常 (包括 *note SyntaxError: 460.) 时返回 ‘-1’。 如果你想要更多可控性
，可以使用 *note PyRun_String(): fc3.；请在 ‘Python/pythonrun.c’ 中查看
*note PyRun_SimpleString(): 3b8a. 的源码。


File: python.info,  Node: 如何在 C 中对任意 Python 表达式求值？,  Next: 如何从Python对象中提取C的值？,  Prev: 如何在 C 中执行任意 Python 语句？,  Up: 扩展/嵌入常见问题

11.5.5 如何在 C 中对任意 Python 表达式求值？
--------------------------------------------

可以调用前一问题中介绍的函数 *note PyRun_String(): fc3. 并附带起始标记符
*note Py_eval_input: 3be6.；它会解析表达式，对其求值并返回结果值。


File: python.info,  Node: 如何从Python对象中提取C的值？,  Next: 如何使用Py_BuildValue 创建任意长度的元组？,  Prev: 如何在 C 中对任意 Python 表达式求值？,  Up: 扩展/嵌入常见问题

11.5.6 如何从Python对象中提取C的值？
------------------------------------

这取决于对象的类型。 如果是元组，*note PyTuple_Size(): 3e41. 可返回其长
度而 *note PyTuple_GetItem(): 3b1f. 可返回指定序号上的项。 对于列表也有
类似的函数 ‘PyListSize()’ 和 *note PyList_GetItem(): 3b20.。

对于字节串，*note PyBytes_Size(): 3dcc. 可返回其长度而 *note
PyBytes_AsStringAndSize(): 3dd0. 提供一个指向其值和长度的指针。 请注意
Python 字节串可能为空，因此 C 的 ‘strlen()’ 不应被使用。

要检测一个对象的类型，首先要确保它不为 ‘NULL’，然后使用 *note
PyBytes_Check(): d27, *note PyTuple_Check(): 3e3d, *note PyList_Check():
3e52. 等等。

还有一个针对 Python 对象的高层级 API，通过所谓的‘抽象’接口提供 —— 请参阅
‘Include/abstract.h’ 了解详情。 它允许使用 *note PySequence_Length():
3cf8, *note PySequence_GetItem(): 105e. 这样的调用来与任意种类的 Python
序列进行对接，此外还可使用许多其他有用的协议例如数字 (*note
PyNumber_Index(): 3cf2. 等) 以及 PyMapping API 中的各种映射等等。


File: python.info,  Node: 如何使用Py_BuildValue 创建任意长度的元组？,  Next: 如何从C调用对象的方法？,  Prev: 如何从Python对象中提取C的值？,  Up: 扩展/嵌入常见问题

11.5.7 如何使用Py_BuildValue()创建任意长度的元组？
--------------------------------------------------

不可以。应该使用 *note PyTuple_Pack(): 3e40. 。


File: python.info,  Node: 如何从C调用对象的方法？,  Next: 如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？,  Prev: 如何使用Py_BuildValue 创建任意长度的元组？,  Up: 扩展/嵌入常见问题

11.5.8 如何从C调用对象的方法？
------------------------------

可以使用 *note PyObject_CallMethod(): 3cc3. 函数来调用某个对象的任意方法
。 形参为该对象、要调用的方法名、类似 *note Py_BuildValue(): 2cf. 所用的
格式字符串以及要传给方法的参数值:

     PyObject *
     PyObject_CallMethod(PyObject *object, const char *method_name,
                         const char *arg_format, ...);

这适用于任何具有方法的对象 —— 不论是内置方法还是用户自定义方法。 你需要
负责对返回值进行最终的 *note Py_DECREF(): 267. 处理。

例如调用某个文件对象的 "seek" 方法并传入参数 10, 0 (假定文件对象的指针为
"f"):

     res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);
     if (res == NULL) {
             ... an exception occurred ...
     }
     else {
             Py_DECREF(res);
     }

请注意由于 *note PyObject_CallObject(): 3b12. `总是' 接受一个元组作为参
数列表，要调用不带参数的函数，则传入格式为 "()"，要调用只带一个参数的函
数，则应将参数包含于圆括号中，例如 "(i)"。


File: python.info,  Node: 如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？,  Next: 如何从C访问用Python编写的模块？,  Prev: 如何从C调用对象的方法？,  Up: 扩展/嵌入常见问题

11.5.9 如何捕获PyErr_Print()（或打印到stdout / stderr的任何内容）的输出？
-------------------------------------------------------------------------

在 Python 代码中，定义一个支持 ‘write()’ 方法的对象。 将此对象赋值给
*note sys.stdout: 317. 和 *note sys.stderr: 318.。 调用 print_error 或者
只是允许标准回溯机制生效。 在此之后，输出将转往你的 ‘write()’ 方法所指向
的任何地方。

做到这一点的最简单方式是使用 *note io.StringIO: 836. 类：

     >>> import io, sys
     >>> sys.stdout = io.StringIO()
     >>> print('foo')
     >>> print('hello world!')
     >>> sys.stderr.write(sys.stdout.getvalue())
     foo
     hello world!

实现同样效果的自定义对象看起来是这样的：

     >>> import io, sys
     >>> class StdoutCatcher(io.TextIOBase):
     ...     def __init__(self):
     ...         self.data = []
     ...     def write(self, stuff):
     ...         self.data.append(stuff)
     ...
     >>> import sys
     >>> sys.stdout = StdoutCatcher()
     >>> print('foo')
     >>> print('hello world!')
     >>> sys.stderr.write(''.join(sys.stdout.data))
     foo
     hello world!


File: python.info,  Node: 如何从C访问用Python编写的模块？,  Next: 如何在 Python 中对接 C ++ 对象？,  Prev: 如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？,  Up: 扩展/嵌入常见问题

11.5.10 如何从C访问用Python编写的模块？
---------------------------------------

你可以通过如下方式获得一个指向模块对象的指针:

     module = PyImport_ImportModule("<modulename>");

如果模块尚未被导入（即它还不存在于 *note sys.modules: f36. 中），这会初
始化该模块；否则它只是简单地返回 ‘sys.modules["<modulename>"]’ 的值。 请
注意它并不会将模块加入任何命名空间 —— 它只是确保模块被初始化并存在于
*note sys.modules: f36. 中。

之后你就可以通过如下方式来访问模块的属性（即模块中定义的任何名称）:

     attr = PyObject_GetAttrString(module, "<attrname>");

调用 *note PyObject_SetAttrString(): 3cb9. 为模块中的变量赋值也是可以的
。


File: python.info,  Node: 如何在 Python 中对接 C ++ 对象？,  Next: 我使用Setup文件添加了一个模块，为什么make失败了？,  Prev: 如何从C访问用Python编写的模块？,  Up: 扩展/嵌入常见问题

11.5.11 如何在 Python 中对接 C ++ 对象？
----------------------------------------

根据你的需求，可以选择许多方式。 手动的实现方式请查阅 *note "扩展与嵌入"
文档: 120d. 来入门。 需要知道的是对于 Python 运行时系统来说，C 和 C++ 并
不没有太大的区别 —— 因此围绕一个 C 结构（指针）类型构建新 Python 对象的
策略同样适用于 C++ 对象。

有关C ++库，请参阅 *note C很难写，有没有其他选择？: 42d8.


File: python.info,  Node: 我使用Setup文件添加了一个模块，为什么make失败了？,  Next: 如何调试扩展？,  Prev: 如何在 Python 中对接 C ++ 对象？,  Up: 扩展/嵌入常见问题

11.5.12 我使用Setup文件添加了一个模块，为什么make失败了？
---------------------------------------------------------

安装程序必须以换行符结束，如果没有换行符，则构建过程将失败。 （修复这个
需要一些丑陋的shell脚本编程，而且这个bug很小，看起来不值得花这么大力气。
)


File: python.info,  Node: 如何调试扩展？,  Next: 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?,  Prev: 我使用Setup文件添加了一个模块，为什么make失败了？,  Up: 扩展/嵌入常见问题

11.5.13 如何调试扩展？
----------------------

将GDB与动态加载的扩展名一起使用时，在加载扩展名之前，不能在扩展名中设置
断点。

在您的 ‘.gdbinit’ 文件中（或交互式）添加命令：

     br _PyImport_LoadDynamicModule

然后运行GDB：

     $ gdb /local/bin/python
     gdb) run myscript.py
     gdb) continue # repeat until your extension is loaded
     gdb) finish   # so that your extension is loaded
     gdb) br myfunction.c:50
     gdb) continue


File: python.info,  Node: 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?,  Next: 如何区分“输入不完整”和“输入无效”？,  Prev: 如何调试扩展？,  Up: 扩展/嵌入常见问题

11.5.14 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?
----------------------------------------------------------------------

大多数打包的Python版本不包含 ‘/usr/lib/python2.`x'/config/’ 目录，该目录
中包含编译Python扩展所需的各种文件。

对于Red Hat，安装python-devel RPM以获取必要的文件。

对于Debian，运行 ‘apt-get install python-dev’ 。


File: python.info,  Node: 如何区分“输入不完整”和“输入无效”？,  Next: 如何找到未定义的g++符号__builtin_new或__pure_virtual？,  Prev: 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?,  Up: 扩展/嵌入常见问题

11.5.15 如何区分“输入不完整”和“输入无效”？
------------------------------------------

有时，希望模仿Python交互式解释器的行为，在输入不完整时(例如，您键入了
“if”语句的开头，或者没有关闭括号或三个字符串引号)，给出一个延续提示，但
当输入无效时，立即给出一条语法错误消息。

在Python中，您可以使用 *note codeop: 1d. 模块，该模块非常接近解析器的行
为。例如，IDLE就使用了这个。

在C中执行此操作的最简单方法是调用 *note PyRun_InteractiveLoop(): 3bcd. （
可能在单独的线程中）并让Python解释器为您处理输入。您还可以设置 *note
PyOS_ReadlineFunctionPointer(): 974. 指向您的自定义输入函数。有关更多提
示，请参阅 ‘Modules/readline.c’ 和 ‘Parser/myreadline.c’ 。

但是，有时必须在与其他应用程序相同的线程中运行嵌入式Python解释器，并且不
能允许 *note PyRun_InteractiveLoop(): 3bcd. 在等待用户输入时停止。那么另
一个解决方案是调用 ‘PyParser_ParseString()’ 并测试 ‘e.error’ 等于
‘E_EOF’ ，如果等于，就意味着输入不完整。这是一个示例代码片段，未经测试，
灵感来自Alex Farber的代码:

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>
     #include <node.h>
     #include <errcode.h>
     #include <grammar.h>
     #include <parsetok.h>
     #include <compile.h>

     int testcomplete(char *code)
       /* code should end in \n */
       /* return -1 for error, 0 for incomplete, 1 for complete */
     {
       node *n;
       perrdetail e;

       n = PyParser_ParseString(code, &_PyParser_Grammar,
                                Py_file_input, &e);
       if (n == NULL) {
         if (e.error == E_EOF)
           return 0;
         return -1;
       }

       PyNode_Free(n);
       return 1;
     }

另一个解决方案是尝试使用 *note Py_CompileString(): 3bde. 编译接收到的字
符串。如果编译时没有出现错误，请尝试通过调用 *note PyEval_EvalCode():
3be2. 来执行返回的代码对象。否则，请将输入保存到以后。如果编译失败，找出
是错误还是只需要更多的输入-从异常元组中提取消息字符串，并将其与字符串 “分
析时意外的EOF” 进行比较。下面是使用GNUreadline库的完整示例(您可能希望在
调用readline()时忽略 `SIGINT' )：

     #include <stdio.h>
     #include <readline.h>

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>
     #include <object.h>
     #include <compile.h>
     #include <eval.h>

     int main (int argc, char* argv[])
     {
       int i, j, done = 0;                          /* lengths of line, code */
       char ps1[] = ">>> ";
       char ps2[] = "... ";
       char *prompt = ps1;
       char *msg, *line, *code = NULL;
       PyObject *src, *glb, *loc;
       PyObject *exc, *val, *trb, *obj, *dum;

       Py_Initialize ();
       loc = PyDict_New ();
       glb = PyDict_New ();
       PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ());

       while (!done)
       {
         line = readline (prompt);

         if (NULL == line)                          /* Ctrl-D pressed */
         {
           done = 1;
         }
         else
         {
           i = strlen (line);

           if (i > 0)
             add_history (line);                    /* save non-empty lines */

           if (NULL == code)                        /* nothing in code yet */
             j = 0;
           else
             j = strlen (code);

           code = realloc (code, i + j + 2);
           if (NULL == code)                        /* out of memory */
             exit (1);

           if (0 == j)                              /* code was empty, so */
             code[0] = '\0';                        /* keep strncat happy */

           strncat (code, line, i);                 /* append line to code */
           code[i + j] = '\n';                      /* append '\n' to code */
           code[i + j + 1] = '\0';

           src = Py_CompileString (code, "<stdin>", Py_single_input);

           if (NULL != src)                         /* compiled just fine - */
           {
             if (ps1  == prompt ||                  /* ">>> " or */
                 '\n' == code[i + j - 1])           /* "... " and double '\n' */
             {                                               /* so execute it */
               dum = PyEval_EvalCode (src, glb, loc);
               Py_XDECREF (dum);
               Py_XDECREF (src);
               free (code);
               code = NULL;
               if (PyErr_Occurred ())
                 PyErr_Print ();
               prompt = ps1;
             }
           }                                        /* syntax error or E_EOF? */
           else if (PyErr_ExceptionMatches (PyExc_SyntaxError))
           {
             PyErr_Fetch (&exc, &val, &trb);        /* clears exception! */

             if (PyArg_ParseTuple (val, "sO", &msg, &obj) &&
                 !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */
             {
               Py_XDECREF (exc);
               Py_XDECREF (val);
               Py_XDECREF (trb);
               prompt = ps2;
             }
             else                                   /* some other syntax error */
             {
               PyErr_Restore (exc, val, trb);
               PyErr_Print ();
               free (code);
               code = NULL;
               prompt = ps1;
             }
           }
           else                                     /* some non-syntax error */
           {
             PyErr_Print ();
             free (code);
             code = NULL;
             prompt = ps1;
           }

           free (line);
         }
       }

       Py_XDECREF(glb);
       Py_XDECREF(loc);
       Py_Finalize();
       exit(0);
     }


File: python.info,  Node: 如何找到未定义的g++符号__builtin_new或__pure_virtual？,  Next: 能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？,  Prev: 如何区分“输入不完整”和“输入无效”？,  Up: 扩展/嵌入常见问题

11.5.16 如何找到未定义的g++符号__builtin_new或__pure_virtual？
--------------------------------------------------------------

要动态加载g ++扩展模块，必须重新编译Python，要使用g ++重新链接（在Python
Modules Makefile中更改LINKCC），及链接扩展模块（例如： ‘g++ -shared -o
mymodule.so mymodule.o’ ）。


File: python.info,  Node: 能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？,  Prev: 如何找到未定义的g++符号__builtin_new或__pure_virtual？,  Up: 扩展/嵌入常见问题

11.5.17 能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？
---------------------------------------------------------------------------------------------

是的，您可以继承内置类，例如 *note int: 185. ， *note list: 263. ，
*note dict: 1b9. 等。

Boost Python库（BPL，http：//www.boost.org/libs/python/doc/index.html）
提供了一种从C ++执行此操作的方法（即，您可以使用BPL继承自C ++编写的扩展
类 ）。


File: python.info,  Node: Python在Windows上的常见问题,  Next: 图形用户界面（GUI）常见问题,  Prev: 扩展/嵌入常见问题,  Up: Python 常见问题

11.6 Python在Windows上的常见问题
================================

* Menu:

* 我怎样在Windows下运行一个Python程序？::
* 我怎么让 Python 脚本可执行？::
* 为什么有时候 Python 程序会启动缓慢？::
* 我怎样使用 Python 脚本制作可执行文件？::
* *.pyd 文件和 DLL 文件相同吗？: * pyd 文件和 DLL 文件相同吗？.
* 我怎样将 Python 嵌入一个 Windows 程序？::
* 如何让编辑器不要在我的 Python 源代码中插入 tab ？::
* 如何在不阻塞的情况下检查按键？::


File: python.info,  Node: 我怎样在Windows下运行一个Python程序？,  Next: 我怎么让 Python 脚本可执行？,  Up: Python在Windows上的常见问题

11.6.1 我怎样在Windows下运行一个Python程序？
--------------------------------------------

这不一定是一个简单的问题。如果你已经熟悉在Windows的命令行中运行程序的方
法，一切都显而易见；不然的话，你也许需要额外获得些许指导。

除非你在使用某种集成开发环境，否则你将会在被称为“DOS 窗口”或“命令提示符
窗口”的地方 `输入' Windows 命令。 通常你可以在搜索栏搜索 ‘cmd’ 来创建这
种窗口。 你应该能够识别你何时打开了这样的窗口，因为你将看到一个
Windows“命令提示符”，通常看起来是这样：

     C:\>

前面的字母可能会不同，而且后面有可能会有其他东西，所以你也许会看到类似这
样的东西：

     D:\YourName\Projects\Python>

出现的内容具体取决与你的电脑如何设置和最近用它做的事。 当你启动了这样一
个窗口后，就可以开始运行Python程序了。

Python 脚本需要被另外一个叫做 Python `解释器' 的程序来处理。 解释器读取
脚本，把它编译成字节码，然后执行字节码来运行你的程序。 所以怎样安排解释
器来处理你的 Python 脚本呢？

首先，确保命令窗口能够将“py”识别为指令来开启解释器。 如果你打开过一个命
令窗口， 尝试输入命令 ‘py’ 然后按回车：

     C:\Users\YourName> py

然后你应当看见类似类似这样的东西：

     Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
     Type "help", "copyright", "credits" or "license" for more information.
     >>>

解释器已经以“交互模式”打开。这意味着你可以交互输入Python语句或表达式，并
在等待时执行或评估它们。这是Python最强大的功能之一。输入几个表达式并看看
结果：

     >>> print("Hello")
     Hello
     >>> "Hello" * 3
     'HelloHelloHello'

许多人把交互模式当作方便和高度可编程的计算器。 想结束交互式Python会话时
，调用 *note exit(): 161f. 函数，或者按住 ‘Ctrl’ 键时输入 ‘Z’ ，之后按
‘Enter’ 键返回Windows命令提示符。

你可能发现在开始菜单有这样一个条目 开始 ‣ 所有程序 ‣ Python 3.x ‣ Python
(命令行)， 运行它后会出现一个有着 ‘>>>’ 提示的新窗口。 在此之后，如果调
用 *note exit(): 161f. 函数或按 ‘Ctrl-Z’ 组合键后窗口将会消失。 Windows
会在这个窗口中运行一个“python”命令，并且在你终止解释器的时候关闭它。

现在我们知道 ‘py’ 命令已经被识别，可以输入 Python 脚本了。 你需要提供
Python 脚本的绝对路径或相对路径。 假设 Python 脚本位于桌面上并命名为
‘hello.py’，并且命令提示符在用户主目录打开，那么可以看到类似于这样的东西
:

     C:\Users\YourName>

那么现在可以让 ‘py’ 命令执行你的脚本，只需要输入 ‘py’ 和脚本路径:

     C:\Users\YourName> py Desktop\hello.py
     hello


File: python.info,  Node: 我怎么让 Python 脚本可执行？,  Next: 为什么有时候 Python 程序会启动缓慢？,  Prev: 我怎样在Windows下运行一个Python程序？,  Up: Python在Windows上的常见问题

11.6.2 我怎么让 Python 脚本可执行？
-----------------------------------

在 Windows 上，标准 Python 安装程序已将 .py 扩展名与文件类型
(Python.File) 相关联，并为该文件类型提供运行解释器的打开命令
(‘D:\Program Files\Python\python.exe "%1" %*’) 。 这足以使脚本在命令提示
符下作为“foo.py”命令被执行。 如果希望通过简单地键入“foo”而无需输入文件扩
展名来执行脚本，则需要将 .py 添加到 PATHEXT 环境变量中。


File: python.info,  Node: 为什么有时候 Python 程序会启动缓慢？,  Next: 我怎样使用 Python 脚本制作可执行文件？,  Prev: 我怎么让 Python 脚本可执行？,  Up: Python在Windows上的常见问题

11.6.3 为什么有时候 Python 程序会启动缓慢？
-------------------------------------------

通常，Python 在 Windows 上启动得很快，但偶尔会有错误报告说 Python 突然需
要很长时间才能启动。更令人费解的是，在其他配置相同的 Windows 系统上，
Python 却可以工作得很好。

该问题可能是由于计算机上的杀毒软件配置错误造成的。当将病毒扫描配置为监视
文件系统中所有读取行为时，一些杀毒扫描程序会导致两个数量级的启动开销。请
检查你系统安装的杀毒扫描程序的配置，确保两台机它们是同样的配置。已知的，
McAfee 杀毒软件在将它设置为扫描所有文件系统访问时，会产生这个问题。


File: python.info,  Node: 我怎样使用 Python 脚本制作可执行文件？,  Next: * pyd 文件和 DLL 文件相同吗？,  Prev: 为什么有时候 Python 程序会启动缓慢？,  Up: Python在Windows上的常见问题

11.6.4 我怎样使用 Python 脚本制作可执行文件？
---------------------------------------------

请参看 cx_Freeze(1) 和 py2exe(2)，两者都是允许你基于 Python 代码创建控制
台和 GUI 可执行程序的 distutils 扩展。

   ---------- Footnotes ----------

   (1) https://cx-freeze.readthedocs.io/en/latest/

   (2) http://www.py2exe.org/


File: python.info,  Node: * pyd 文件和 DLL 文件相同吗？,  Next: 我怎样将 Python 嵌入一个 Windows 程序？,  Prev: 我怎样使用 Python 脚本制作可执行文件？,  Up: Python在Windows上的常见问题

11.6.5 ‘*.pyd’ 文件和 DLL 文件相同吗？
--------------------------------------

是的， .pyd 文件也是 dll ，但有一些差异。如果你有一个名为 ‘foo.pyd’ 的
DLL，那么它必须有一个函数 ‘PyInit_foo()’ 。 然后你可以编写 Python 代码
“import foo” ，Python 将搜索 foo.pyd （以及 foo.py 、 foo.pyc ）。如果找
到它，将尝试调用 ‘PyInit_foo()’ 来初始化它。你不应将 .exe 与 foo.lib 链
接，因为这会导致 Windows 要求存在 DLL 。

请注意， foo.pyd 的搜索路径是 PYTHONPATH ，与 Windows 用于搜索 foo.dll 的
路径不同。此外， foo.pyd 不需要存在来运行你的程序，而如果你将程序与 dll
链接，则需要 dll 。 当然，如果你想 ‘import foo’ ，则需要 foo.pyd 。在
DLL 中，链接在源代码中用 ‘__declspec(dllexport)’ 声明。 在 .pyd 中，链接
在可用函数列表中定义。


File: python.info,  Node: 我怎样将 Python 嵌入一个 Windows 程序？,  Next: 如何让编辑器不要在我的 Python 源代码中插入 tab ？,  Prev: * pyd 文件和 DLL 文件相同吗？,  Up: Python在Windows上的常见问题

11.6.6 我怎样将 Python 嵌入一个 Windows 程序？
----------------------------------------------

在 Windows 应用程序中嵌入 Python 解释器可以总结如下：

  1. 请 _不要_ 直接在你的 .exe 文件中内置 Python 。在 Windows 上，
     Python 必须是一个 DLL ，这样才可以处理导入的本身就是 DLL 的模块。（
     这是第一个未记录的关键事实。）相反，链接到 ‘python`NN'.dll’ ；它通
     常安装在 ‘C:\Windows\System’ 中。 `NN' 是 Python 版本，如数字“33”代
     表 Python 3.3 。

     你可以通过两种不同的方式链接到 Python 。加载时链接意味着链接到
     ‘python`NN'.lib’ ，而运行时链接意味着链接 ‘python`NN'.dll’ 。（一般
     说明： ‘python `NN'.lib’ 是所谓的“import lib”，对应于
     ‘python`NN'.dll’ 。它只定义了链接器的符号。）

     运行时链接极大地简化了链接选项，一切都在运行时发生。你的代码必须使
     用 Windows 的 ‘LoadLibraryEx()’ 程序加载 ‘python`NN'.dll’ 。代码还
     必须使用使用 Windows 的 ‘GetProcAddress()’ 例程获得的指针访问
     ‘python`NN'.dll’ 中程序和数据（即 Python 的 C API ）。宏可以使这些
     指针对任何调用 Python C API 中的例程的 C 代码都是透明的。

     Borland 提示：首先使用 Coff2Omf.exe 将 ‘python`NN'.lib’ 转换为 OMF
     格式。

  2. 如果你使用 SWIG ，很容易创建一个 Python “扩展模块”，它将使应用程序
     的数据和方法可供 Python 使用。SWIG将为你处理所有蹩脚的细节。结果是
     你将链接到 .exe 文件 `中' 的C代码 (!) 你不必创建 DLL 文件，这也简化
     了链接。

  3. SWIG 将创建一个 init 函数（一个 C 函数），其名称取决于扩展模块的名
     称。例如，如果模块的名称是 leo ，则 init 函数将被称为 initleo() 。
     如果您使用 SWIG 阴影类，则 init 函数将被称为 initleoc() 。这初始化
     了一个由阴影类使用的隐藏辅助类。

     你可以将步骤 2 中的 C 代码链接到 .exe 文件的原因是调用初始化函数等
     同于将模块导入 Python ！ （这是第二个关键的未记载事实。）

  4. 简而言之，你可以用以下代码使用扩展模块初始化 Python 解释器。

          #include "python.h"
          ...
          Py_Initialize();  // Initialize Python.
          initmyAppc();  // Initialize (import) the helper class.
          PyRun_SimpleString("import myApp");  // Import the shadow class.

  5. Python C API 存在两个问题，如果你使用除 MSVC 之外的编译器用于构建
     python.dll ，这将会变得明显。

     问题1：采用 FILE* 参数的所谓“极高级”函数在多编译器环境中不起作用，
     因为每个编译器的FILE结构体概念都不同。从实现的角度来看，这些是非常
     _低_ 级的功能。

     问题2：在为 void 函数生成包装器时，SWIG 会生成以下代码：

          Py_INCREF(Py_None);
          _resultobj = Py_None;
          return _resultobj;

     Py_None 是一个宏，它扩展为对 pythonNN.dll 中名为 _Py_NoneStruct 的
     复杂数据结构的引用。同样，此代码将在多编译器环境中失败。将此类代码
     替换为：

          return Py_BuildValue("");

     有可能使用 SWIG 的 ‘%typemap’ 命令自动进行更改，但我无法使其工作（
     我是一个完全的SWIG新手）。

  6. 使用 Python shell 脚本从 Windows 应用程序内部建立 Python 解释器窗口
     并不是一个好主意；生成的窗口将独立于应用程序的窗口系统。相反，你（
     或 wxPythonWindow 类）应该创建一个“本机”解释器窗口。将该窗口连接到
     Python解释器很容易。你可以将 Python的 i/o 重定向到支持读写的 _任意_
     对象，因此你只需要一个包含 read() 和 write() 方法的 Python 对象（在
     扩展模块中定义）。


File: python.info,  Node: 如何让编辑器不要在我的 Python 源代码中插入 tab ？,  Next: 如何在不阻塞的情况下检查按键？,  Prev: 我怎样将 Python 嵌入一个 Windows 程序？,  Up: Python在Windows上的常见问题

11.6.7 如何让编辑器不要在我的 Python 源代码中插入 tab ？
--------------------------------------------------------

本 FAQ 不建议使用制表符， Python 样式指南 PEP 8(1) ，为发行的 Python 代
码推荐 4 个空格；这也是 Emacs python-mode 默认值。

在任何编辑器下，混合制表符和空格都是一个坏主意。 MSVC 在这方面没有什么不
同，并且很容易配置为使用空格： 点击 Tools ‣ Options ‣ Tabs，对于文件类型
“Default”，设置“Tab size”和“Indent size”为 4 ，并选择“插入空格”单选按钮
。

如果混合制表符和空格导致前导空格出现问题， Python 会引发 *note
IndentationError: e80. 或 *note TabError: e7f. 。你还可以运行 *note
tabnanny: 101. 模块以批处理模式检查目录树。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0008


File: python.info,  Node: 如何在不阻塞的情况下检查按键？,  Prev: 如何让编辑器不要在我的 Python 源代码中插入 tab ？,  Up: Python在Windows上的常见问题

11.6.8 如何在不阻塞的情况下检查按键？
-------------------------------------

使用 *note msvcrt: b7. 模块。 这是一个标准的 Windows 专属扩展模块。 它定
义了一个函数 ‘kbhit()’ 用于检查是否有键盘中的某个键被按下，以及
‘getch()’ 用于获取一个字符而不将其回显。


File: python.info,  Node: 图形用户界面（GUI）常见问题,  Next: “为什么我的电脑上安装了 Python ？”,  Prev: Python在Windows上的常见问题,  Up: Python 常见问题

11.7 图形用户界面（GUI）常见问题
================================

* Menu:

* 图形界面常见问题::
* Python 是否有平台无关的图形界面工具包？::
* 有哪些Python的GUI工具是某个平台专用的？::
* 有关Tkinter的问题::


File: python.info,  Node: 图形界面常见问题,  Next: Python 是否有平台无关的图形界面工具包？,  Up: 图形用户界面（GUI）常见问题

11.7.1 图形界面常见问题
-----------------------


File: python.info,  Node: Python 是否有平台无关的图形界面工具包？,  Next: 有哪些Python的GUI工具是某个平台专用的？,  Prev: 图形界面常见问题,  Up: 图形用户界面（GUI）常见问题

11.7.2 Python 是否有平台无关的图形界面工具包？
----------------------------------------------

针对不同的（操作系统或）平台，有多种工具包可供选择。虽然有些工具包还没有
移植到 Python 3 上，但至少目前 *note Tkinter: 42f8. 以及 *note Qt: 42f9.
是兼容 Python 3 的。

* Menu:

* Tkinter::
* wxWidgets::
* Qt::
* Gtk+::
* Kivy::
* FLTK::
* OpenGL::


File: python.info,  Node: Tkinter,  Next: wxWidgets,  Up: Python 是否有平台无关的图形界面工具包？

11.7.2.1 Tkinter
................

Python 的标准编译包含了 *note tkinter: 317a.。这是一个面向对象的接口，指
向 Tcl/Tk 微件包。 该接口大概是最容易安装（因为该接口包含在 Python 的大
部分 二进制发行版(1) 中）和使用的工具包。要了解 Tk 的详情，比如源代码等
，可访问 Tcl/Tk 项目主页(2)。 Tcl/Tk 可完整移植至 Mac OS X，Windows 和
Unix 操作系统上。

   ---------- Footnotes ----------

   (1) https://www.python.org/downloads/

   (2) https://www.tcl.tk


File: python.info,  Node: wxWidgets,  Next: Qt,  Prev: Tkinter,  Up: Python 是否有平台无关的图形界面工具包？

11.7.2.2 wxWidgets
..................

wxWidgets (‘https://www.wxwidgets.org’) 是一个自由、可移植的 GUI 图形用
户界面类库，使用 C++ 编写。它可以在多个操作系统平台上提供原生自然的界面
观感。包括Windows、Mac OS X、 GTK 和 X11 平台在内，都是wxWidgets 当前稳
定支持的平台。在语言绑定适配方面，wxWidgets 类库可用于较多语言，包括
Python，Perl，Ruby等。

wxPython(1) 是 wxWidgets 的 Python 适配。虽然该绑定在更新进度上经常会稍
稍落后于 wxWidgets，但它利用纯 Python 扩展，提供了许多其他语言绑定没有实
现的特性。wxPython 有一个活跃的用户和开发者社区。

wxWidgets 和 wxPython 都是自由开源库。宽松的许可证允许人们在商业软件、自
由软件和共享软件中使用它们。

   ---------- Footnotes ----------

   (1) https://www.wxpython.org


File: python.info,  Node: Qt,  Next: Gtk+,  Prev: wxWidgets,  Up: Python 是否有平台无关的图形界面工具包？

11.7.2.3 Qt
...........

Qt 工具包 (可使用 PyQt(1) 或 PySide(2)) 及 KDE (PyKDE4(3)) 有多个绑定适
配可供选择。 PyQt 当前相较 PySide 更成熟，但如果你想编写专有软件，就必须
要从 Riverbank Computing(4) 购买 PyQt 许可证。 PySide 则可以自由使用于各
类软件。

Qt 4.5 以上版本使用 LGPL 进行许可；此外，商业许可证可从 Qt 公司(5) 那里
获得。

   ---------- Footnotes ----------

   (1) https://riverbankcomputing.com/software/pyqt/intro

   (2) https://wiki.qt.io/PySide

   (3) https://techbase.kde.org/Languages/Python/Using_PyKDE_4

   (4) https://www.riverbankcomputing.com/commercial/license-faq

   (5) https://www.qt.io/licensing/


File: python.info,  Node: Gtk+,  Next: Kivy,  Prev: Qt,  Up: Python 是否有平台无关的图形界面工具包？

11.7.2.4 Gtk+
.............

针对 Python 的 GObject 内省绑定(1) 可以用于编写 GTK+ 3 应用。 另请参阅
Python GTK+ 3 教程(2)。

更早的、针对 Gtk+ 2 工具包(3) 的 PyGtk 绑定，是由 James Henstridge 实现
的。具体请参考 <‘http://www.pygtk.org’>。

   ---------- Footnotes ----------

   (1) https://wiki.gnome.org/Projects/PyGObject

   (2) https://python-gtk-3-tutorial.readthedocs.io

   (3) https://www.gtk.org


File: python.info,  Node: Kivy,  Next: FLTK,  Prev: Gtk+,  Up: Python 是否有平台无关的图形界面工具包？

11.7.2.5 Kivy
.............

Kivy(1) 是一种跨平台图形用户界面库，同时支持桌面操作系统（Windows，macOS
和 Linux）以及移动设备（Android，iOS）。该库使用 Python 和 Cython 编写，
可以使用一系列窗口后端。

Kivy 是自由的开源软件，使用 MIT 许可证分发。

   ---------- Footnotes ----------

   (1) https://kivy.org/


File: python.info,  Node: FLTK,  Next: OpenGL,  Prev: Kivy,  Up: Python 是否有平台无关的图形界面工具包？

11.7.2.6 FLTK
.............

the FLTK toolkit(1) 的Python绑定是简单却功能强大且成熟的跨平台窗口系统，
可以在 the PyFLTK project(2) 里获得相关信息。

   ---------- Footnotes ----------

   (1) http://www.fltk.org

   (2) http://pyfltk.sourceforge.net


File: python.info,  Node: OpenGL,  Prev: FLTK,  Up: Python 是否有平台无关的图形界面工具包？

11.7.2.7 OpenGL
...............

对于OpenGL绑定，请参阅 PyOpenGL(1)。

   ---------- Footnotes ----------

   (1) http://pyopengl.sourceforge.net


File: python.info,  Node: 有哪些Python的GUI工具是某个平台专用的？,  Next: 有关Tkinter的问题,  Prev: Python 是否有平台无关的图形界面工具包？,  Up: 图形用户界面（GUI）常见问题

11.7.3 有哪些Python的GUI工具是某个平台专用的？
----------------------------------------------

通过安装 PyObjc Objective-C bridge(1)，Python程序可以使用Mac OS X的
Cocoa库。

Mark Hammond的 *note Pythonwin: 42ea. 包括一个微软基础类(MFC)的接口和一
个绝大多数由使用MFC类的Python写成的Python编程环境。

   ---------- Footnotes ----------

   (1) https://pypi.org/project/pyobjc/


File: python.info,  Node: 有关Tkinter的问题,  Prev: 有哪些Python的GUI工具是某个平台专用的？,  Up: 图形用户界面（GUI）常见问题

11.7.4 有关Tkinter的问题
------------------------

* Menu:

* 我怎样“冻结”Tkinter程序？::
* 在等待 I/O 操作时能够处理 Tk 事件吗？::
* 在Tkinter中键绑定不工作：为什么？::


File: python.info,  Node: 我怎样“冻结”Tkinter程序？,  Next: 在等待 I/O 操作时能够处理 Tk 事件吗？,  Up: 有关Tkinter的问题

11.7.4.1 我怎样“冻结”Tkinter程序？
..................................

Freeze （意为 “冻结”）是一个用来创建独立应用程序的工具。 当 “冻结”
Tkinter 程序时，程序并不是真的能够独立运行，因为程序仍然需要 Tcl 和 Tk 库
。

一种解决方法是将程序与 Tcl 和 Tk 库一同发布，并且在运行时使用环境变量
‘TCL_LIBRARY’ 和 ‘TK_LIBRARY’ 指向他们的位置。

为了获得真正能独立运行的应用程序，来自库里的 Tcl 脚本也需要被整合进应用
程序。 一个做这种事情的工具叫 SAM (stand-alone modules，独立模块) ，它是
Tix distribution (‘http://tix.sourceforge.net/’) 的一部分。

在启用 SAM 时编译 Tix ，在 Python 文件 ‘Modules/tkappinit.c’ 中执行对
‘Tclsam_init()’ 等的适当调用，并且将程序与 libtclsam 和 libtksam 相链接
（可能也要包括 Tix 的库）。


File: python.info,  Node: 在等待 I/O 操作时能够处理 Tk 事件吗？,  Next: 在Tkinter中键绑定不工作：为什么？,  Prev: 我怎样“冻结”Tkinter程序？,  Up: 有关Tkinter的问题

11.7.4.2 在等待 I/O 操作时能够处理 Tk 事件吗？
..............................................

在 Windows 以外的其他平台上可以，你甚至不需要使用线程！ 但是你必须稍微修
改一下你的 I/O 代码。 Tk 有与 Xt 的 ‘XtAddInput()’ 对应的调用，它允许你
注册一个回调函数，当一个文件描述符可以进行 I/O 操作的时候，Tk 主循环将会
调用这个回调函数。 参见 *note File Handlers: 3194.。


File: python.info,  Node: 在Tkinter中键绑定不工作：为什么？,  Prev: 在等待 I/O 操作时能够处理 Tk 事件吗？,  Up: 有关Tkinter的问题

11.7.4.3 在Tkinter中键绑定不工作：为什么？
..........................................

经常听到的抱怨是：已经通过 ‘bind()’ 方法绑定了事件的处理程序，但是，当按
下相关的按键后，这个处理程序却没有执行。

最常见的原因是，那个绑定的控件没有“键盘焦点”。请在 Tk 文档中查找 focus 指
令。通常一个控件要获得“键盘焦点”，需要点击那个控件（而不是标签；请查看
takefocus 选项）。


File: python.info,  Node: “为什么我的电脑上安装了 Python ？”,  Prev: 图形用户界面（GUI）常见问题,  Up: Python 常见问题

11.8 “为什么我的电脑上安装了 Python ？”
=======================================

* Menu:

* 什么是 Python？: 什么是 Python？<2>.
* 为什么我的电脑上安装了 Python ？::
* 我能删除 Python 吗？::


File: python.info,  Node: 什么是 Python？<2>,  Next: 为什么我的电脑上安装了 Python ？,  Up: “为什么我的电脑上安装了 Python ？”

11.8.1 什么是 Python？
----------------------

Python 是一种程序语言，被许多应用程序使用。它不仅因易学而在许多高校用于
编程入门，还被工作于 Google、NASA 和卢卡斯影业等公司的软件开发人员使用。

如果你想学习更多 Python，看看 Beginner’s Guide to Python(1).

   ---------- Footnotes ----------

   (1) https://wiki.python.org/moin/BeginnersGuide


File: python.info,  Node: 为什么我的电脑上安装了 Python ？,  Next: 我能删除 Python 吗？,  Prev: 什么是 Python？<2>,  Up: “为什么我的电脑上安装了 Python ？”

11.8.2 为什么我的电脑上安装了 Python ？
---------------------------------------

如果你不记得你曾主动安装过 Python，但它却出现在了你的电脑上，这里有一些
可能的原因。

   * 可能是这台电脑的其他用户因想学习编程而安装了它，你得琢磨一下谁用过
     这台电脑并安装了 Python。

   * 电脑上安装的第三方应用程序可能由 Python 写成并附带了一份 Python。这
     样的应用程序有很多，例如GUI程序、网络服务器、管理脚本等。

   * 一些 Windows 可能预装了 Python。在撰写本文时，我们了解到
     Hewlett-Packard 和 Compaq 的计算机包含Python。显然，HP/Compaq 的一
     些管理工具是用 Python 编写的。

   * 许多 Unix 兼容的操作系统，例如 Mac OS X 和一些 Linux 发行版，默认安
     装了Python；它被包含在基本安装套件中。


File: python.info,  Node: 我能删除 Python 吗？,  Prev: 为什么我的电脑上安装了 Python ？,  Up: “为什么我的电脑上安装了 Python ？”

11.8.3 我能删除 Python 吗？
---------------------------

这取决于所安装 Python 的来源

如果有人主动安装了 Python，你可以在不影响其它程序的情况下安全移除它。在
Windows 中，可使用“控制面板”中的“添加/删除程序”卸载。

如果 Python 来源于第三方应用程序，你也能删除它，但那些程序将不能正常工作
。你应该使用那些应用程序的卸载器而不是直接删除 Python。

如果 Python 来自于你的操作系统，不推荐删除！如果删除了它，任何用 Python
写成的工具将无法工作，其中某些工具对于你来说可能十分重要。你甚至可能需要
重装整个系统来修复因删除 Python 留下的烂摊子。


File: python.info,  Node: 术语对照表,  Next: 文档说明,  Prev: Python 常见问题,  Up: Top

12 术语对照表
*************

‘>>>’

     交互式终端中默认的 Python 提示符。往往会显示于能以交互方式在解释器
     里执行的样例代码之前。

‘...’

     可以是指：

        * 交互式终端中输入特殊代码行时默认的 Python 提示符，包括：缩进的
          代码块，成对的分隔符之内（圆括号、方括号、花括号或三重引号），
          或是指定一个装饰器之后。

        * *note Ellipsis: 161c. 内置常量。

2to3

     一个将 Python 2.x 代码转换为 Python 3.x 代码的工具，能够处理大部分
     通过解析源码并遍历解析树可检测到的不兼容问题。

     2to3 包含在标准库中，模块名为 *note lib2to3: a8.；并提供一个独立入
     口点 ‘Tools/scripts/2to3’。参见 *note 2to3 - 自动将 Python 2
     代码转为 Python 3 代码: c7e.。

abstract base class – 抽象基类

     抽象基类简称 ABC，是对 *note duck-typing: 430b. 的补充，它提供了一
     种定义接口的新方式，相比之下其他技巧例如 *note hasattr(): 450. 显得
     过于笨拙或有微妙错误（例如使用 *note 魔术方法: 144c.）。ABC 引入了
     虚拟子类，这种类并非继承自其他类，但却仍能被 *note isinstance():
     457. 和 *note issubclass(): 458. 所认可；详见 *note abc: 4. 模块文
     档。Python 自带许多内置的 ABC 用于实现数据结构（在 *note
     collections.abc: 1f. 模块中）、数字（在 *note numbers: c2. 模块中）
     、流（在 *note io: a2. 模块中）、导入查找器和加载器（在 *note
     importlib.abc: 9c. 模块中）。你可以使用 *note abc: 4. 模块来创建自
     己的 ABC。

annotation – 标注

     关联到某个变量、类属性、函数形参或返回值的标签，被约定作为 *note
     type hint: 430d. 来使用。

     局部变量的标注在运行时不可访问，但全局变量、类属性和函数的标注会分
     别存放模块、类和函数的 ‘__annotations__’ 特殊属性中。

     参见 *note variable annotation: 628.、*note function annotation:
     126d.、 PEP 484(1) 和 PEP 526(2)，对此功能均有介绍。

argument – 参数

     在调用函数时传给 *note function: 1533. （或 *note method: 430e. ）
     的值。参数分为两种：

        * `关键字参数': 在函数调用中前面带有标识符（例如 ‘name=’）或者作
          为包含在前面带有 ‘**’ 的字典里的值传入。举例来说，‘3’ 和 ‘5’ 在
          以下对 *note complex(): 18a. 的调用中均属于关键字参数:

               complex(real=3, imag=5)
               complex(**{'real': 3, 'imag': 5})

        * `位置参数': 不属于关键字参数的参数。位置参数可出现于参数列表的
          开头以及/或者作为前面带有 ‘*’ 的 *note iterable: bb4. 里的元素
          被传入。举例来说，‘3’ 和 ‘5’ 在以下调用中均属于位置参数:

               complex(3, 5)
               complex(*(3, 5))

     参数会被赋值给函数体中对应的局部变量。有关赋值规则参见 *note 调用:
     655. 一节。根据语法，任何表达式都可用来表示一个参数；最终算出的值会
     被赋给对应的局部变量。

     另参见 *note parameter: 153b. 术语表条目，常见问题中 *note
     参数与形参的区别: 4257. 以及 PEP 362(3)。

asynchronous context manager – 异步上下文管理器

     此种对象通过定义 *note __aenter__(): 14a8. 和 *note __aexit__():
     14a9. 方法来对 *note async with: 64c. 语句中的环境进行控制。由 PEP
     492(4) 引入。

asynchronous generator – 异步生成器

     返回值为 *note asynchronous generator iterator: 363d. 的函数。它与
     使用 *note async def: 285. 定义的协程函数很相似，不同之处在于它包含
     *note yield: 190. 表达式以产生一系列可在 *note async for: 2e4. 循环
     中使用的值。

     此术语通常是指异步生成器函数，但在某些情况下则可能是指 `异步生成器
     迭代器'。如果需要清楚表达具体含义，请使用全称以避免歧义。

     一个异步生成器函数可能包含 *note await: 1a4. 表达式或者 *note async
     for: 2e4. 以及 *note async with: 64c. 语句。

asynchronous generator iterator – 异步生成器迭代器

     *note asynchronous generator: 1513. 函数所创建的对象。

     此对象属于 *note asynchronous iterator: 64e.，当使用 *note
     __anext__(): 14a5. 方法调用时会返回一个可等待对象来执行异步生成器函
     数的代码直到下一个 *note yield: 190. 表达式。

     每个 *note yield: 190. 会临时暂停处理，记住当前位置执行状态 (包括局
     部变量和挂起的 try 语句)。当该 `异步生成器迭代器' 与其他 *note
     __anext__(): 14a5. 返回的可等待对象有效恢复时，它会从离开位置继续执
     行。参见 PEP 492(5) 和 PEP 525(6)。

asynchronous iterable – 异步可迭代对象

     可在 *note async for: 2e4. 语句中被使用的对象。必须通过它的 *note
     __aiter__(): 48f. 方法返回一个 *note asynchronous iterator: 64e.。
     由 PEP 492(7) 引入。

asynchronous iterator – 异步迭代器

     实现了 *note __aiter__(): 48f. 和 *note __anext__(): 14a5. 方法的对
     象。‘__anext__’ 必须返回一个 *note awaitable: 521. 对象。*note
     async for: 2e4. 会处理异步迭代器的 *note __anext__(): 14a5. 方法所
     返回的可等待对象，直到其引发一个 *note StopAsyncIteration: 1022. 异
     常。由 PEP 492(8) 引入。

attribute – 属性

     关联到一个对象的值，可以使用点号表达式通过其名称来引用。例如，如果
     一个对象 `o' 具有一个属性 `a'，就可以用 `o.a' 来引用它。

awaitable – 可等待对象

     能在 *note await: 1a4. 表达式中使用的对象。可以是 *note coroutine:
     1a7. 或是具有 *note __await__(): 64b. 方法的对象。参见 PEP 492(9)。

BDFL

     “终身仁慈独裁者”的英文缩写，即 Guido van Rossum(10)，Python 的创造
     者。

binary file – 二进制文件

     *note file object: b4a. 能够读写 *note 字节类对象: 5f1.。二进制文件
     的例子包括以二进制模式（‘'rb'’, ‘'wb'’ or ‘'rb+'’）打开的文件、
     ‘sys.stdin.buffer’、‘sys.stdout.buffer’ 以及 *note io.BytesIO: 7a4.
     和 *note gzip.GzipFile: 6e6. 的实例。

     另请参见 *note text file: 12b5. 了解能够读写 *note str: 339. 对象的
     文件对象。

bytes-like object – 字节类对象

     支持 *note 缓冲协议: 15f7. 并且能导出 C-*note contiguous: 16c5. 缓
     冲的对象。这包括所有 *note bytes: 33a.、*note bytearray: 33b. 和
     *note array.array: 459. 对象，以及许多普通 *note memoryview: 25d. 对
     象。字节类对象可在多种二进制数据操作中使用；这些操作包括压缩、保存
     为二进制文件以及通过套接字发送等。

     某些操作需要可变的二进制数据。这种对象在文档中常被称为“可读写字节类
     对象”。可变缓冲对象的例子包括 *note bytearray: 33b. 以及 *note
     bytearray: 33b. 的 *note memoryview: 25d.。其他操作要求二进制数据存
     放于不可变对象 ("只读字节类对象")；这种对象的例子包括 *note bytes:
     33a. 以及 *note bytes: 33a. 对象的 *note memoryview: 25d.。

bytecode – 字节码

     Python 源代码会被编译为字节码，即 CPython 解释器中表示 Python 程序
     的内部代码。字节码还会缓存在 ‘.pyc’ 文件中，这样第二次执行同一文件
     时速度更快（可以免去将源码重新编译为字节码）。这种 "中间语言" 运行
     在根据字节码执行相应机器码的 *note virtual machine: 2792. 之上。请
     注意不同 Python 虚拟机上的字节码不一定通用，也不一定能在不同 Python
     版本上兼容。

     字节码指令列表可以在 *note dis 模块: 38a8. 的文档中查看。

callback – 回调

     一个作为参数被传入以用以在未来的某个时刻被调用的子例程函数。

class – 类

     用来创建用户定义对象的模板。类定义通常包含对该类的实例进行操作的方
     法定义。

class variable – 类变量

     在类中定义的变量，并且仅限在类的层级上修改 (而不是在类的实例中修改
     )。

coercion – 强制类型转换

     在包含两个相同类型参数的操作中，一种类型的实例隐式地转换为另一种类
     型。例如，‘int(3.15)’ 是将原浮点数转换为整型数 ‘3’，但在 ‘3+4.5’ 中
     ，参数的类型不一致（一个是 int, 一个是 float），两者必须转换为相同
     类型才能相加，否则将引发 *note TypeError: 193.。如果没有强制类型转
     换机制，程序员必须将所有可兼容参数归一化为相同类型，例如要写成
     ‘float(3)+4.5’ 而不是 ‘3+4.5’。

complex number – 复数

     对普通实数系统的扩展，其中所有数字都被表示为一个实部和一个虚部的和
     。虚数是虚数单位（‘-1’ 的平方根）的实倍数，通常在数学中写为 ‘i’，在
     工程学中写为 ‘j’。Python 内置了对复数的支持，采用工程学标记方式；虚
     部带有一个 ‘j’ 后缀，例如 ‘3+1j’。如果需要 *note math: b2. 模块内对
     象的对应复数版本，请使用 *note cmath: 19.，复数的使用是一个比较高级
     的数学特性。如果你感觉没有必要，忽略它们也几乎不会有任何问题。

context manager – 上下文管理器

     在 *note with: 6f2. 语句中使用，通过定义 *note __enter__(): c9d. 和
     *note __exit__(): c9e. 方法来控制环境状态的对象。参见 PEP 343(11)。

context variable – 上下文变量

     一种根据其所属的上下文可以具有不同的值的变量。 这类似于在线程局部存
     储中每个执行线程可以具有不同的变量值。 不过，对于上下文变量来说，一
     个执行线程中可能会有多个上下文，而上下文变量的主要用途是对并发异步
     任务中变量进行追踪。 参见 *note contextvars: 25.。

contiguous – 连续

     一个缓冲如果是 `C 连续' 或 `Fortran 连续' 就会被认为是连续的。零维
     缓冲是 C 和 Fortran 连续的。在一维数组中，所有条目必须在内存中彼此
     相邻地排列，采用从零开始的递增索引顺序。在多维 C-连续数组中，当按内
     存地址排列时用最后一个索引访问条目时速度最快。但是在 Fortran 连续数
     组中则是用第一个索引最快。

coroutine – 协程

     协程是子例程的更一般形式。 子例程可以在某一点进入并在另一点退出。 协
     程则可以在许多不同的点上进入、退出和恢复。 它们可通过 *note async
     def: 285. 语句来实现。 参见 PEP 492(12)。

coroutine function – 协程函数

     返回一个 *note coroutine: 1a7. 对象的函数。协程函数可通过 *note
     async def: 285. 语句来定义，并可能包含 *note await: 1a4.、*note
     async for: 2e4. 和 *note async with: 64c. 关键字。这些特性是由 PEP
     492(13) 引入的。

CPython

     Python 编程语言的规范实现，在 python.org(14) 上发布。"CPython" 一词
     用于在必要时将此实现与其他实现例如 Jython 或 IronPython 相区别。

decorator – 装饰器

     返回值为另一个函数的函数，通常使用 ‘@wrapper’ 语法形式来进行函数变
     换。 装饰器的常见例子包括 *note classmethod(): 1d9. 和 *note
     staticmethod(): 1da.。

     装饰器语法只是一种语法糖，以下两个函数定义在语义上完全等价:

          def f(...):
              ...
          f = staticmethod(f)

          @staticmethod
          def f(...):
              ...

     同的样概念也适用于类，但通常较少这样使用。有关装饰器的详情可参见
     *note 函数定义: 126c. 和 *note 类定义: c72. 的文档。

descriptor – 描述器

     任何定义了 *note __get__(): 144b, *note __set__(): 144f. 或 *note
     __delete__(): 1450. 方法的对象。当一个类属性为描述器时，它的特殊绑
     定行为就会在属性查找时被触发。通常情况下，使用 `a.b' 来获取、设置或
     删除一个属性时会在 `a' 的类字典中查找名称为 `b' 的对象，但如果 `b'
     是一个描述器，则会调用对应的描述器方法。理解描述器的概念是更深层次
     理解 Python 的关键，因为这是许多重要特性的基础，包括函数、方法、属
     性、类方法、静态方法以及对超类的引用等等。

     有关描述符的方法的详情可参看 *note 实现描述器: 4f1.。

dictionary – 字典

     一个关联数组，其中的任意键都映射到相应的值。键可以是任何具有 *note
     __hash__(): 349. 和 *note __eq__(): 348. 方法的对象。在 Perl 语言中
     称为 hash。

dictionary comprehension – 字典推导式

     处理一个可迭代对象中的所有或部分元素并返回结果字典的一种紧凑写法。
     ‘results = {n: n ** 2 for n in range(10)}’ 将生成一个由键 ‘n’ 到值
     ‘n ** 2’ 的映射构成的字典。 参见 *note 列表、集合与字典的显示:
     14fb.。

dictionary view – 字典视图

     从 *note dict.keys(): c32, *note dict.values(): c34. 和 *note
     dict.items(): c33. 返回的对象被称为字典视图。它们提供了字典条目的一
     个动态视图，这意味着当字典改变时，视图也会相应改变。要将字典视图强
     制转换为真正的列表，可使用 ‘list(dictview)’。参见 *note
     字典视图对象: 16e6.。

docstring – 文档字符串

     作为类、函数或模块之内的第一个表达式出现的字符串字面值。它在代码执
     行时会被忽略，但会被解释器识别并放入所在类、函数或模块的 ‘__doc__’
     属性中。由于它可用于代码内省，因此是对象存放文档的规范位置。

duck-typing – 鸭子类型

     指一种编程风格，它并不依靠查找对象类型来确定其是否具有正确的接口，
     而是直接调用或使用其方法或属性（“看起来像鸭子，叫起来也像鸭子，那么
     肯定就是鸭子。”）由于强调接口而非特定类型，设计良好的代码可通过允许
     多态替代来提升灵活性。鸭子类型避免使用 *note type(): 611. 或 *note
     isinstance(): 457. 检测。(但要注意鸭子类型可以使用 *note 抽象基类:
     b3b. 作为补充。) 而往往会采用 *note hasattr(): 450. 检测或是 *note
     EAFP: 1f5b. 编程。

EAFP

     “求原谅比求许可更容易”的英文缩写。这种 Python 常用代码编写风格会假
     定所需的键或属性存在，并在假定错误时捕获异常。这种简洁快速风格的特
     点就是大量运用 *note try: d7a. 和 *note except: b46. 语句。于其相对
     的则是所谓 *note LBYL: 4317. 风格，常见于 C 等许多其他语言。

expression – 表达式

     可以求出某个值的语法单元。 换句话说，一个表达式就是表达元素例如字面
     值、名称、属性访问、运算符或函数调用的汇总，它们最终都会返回一个值
     。 与许多其他语言不同，并非所有语言构件都是表达式。 还存在不能被用
     作表达式的 *note statement: 1ba2.，例如 *note while: 123d.。 赋值也
     是属于语句而非表达式。

extension module – 扩展模块

     以 C 或 C++ 编写的模块，使用 Python 的 C API 来与语言核心以及用户代
     码进行交互。

f-string – f-字符串

     带有 ‘'f'’ 或 ‘'F'’ 前缀的字符串字面值通常被称为“f-字符串”即 *note
     格式化字符串字面值: 15d. 的简写。参见 PEP 498(15)。

file object – 文件对象

     对外提供面向文件 API 以使用下层资源的对象（带有 ‘read()’ 或
     ‘write()’ 这样的方法）。根据其创建方式的不同，文件对象可以处理对真
     实磁盘文件，对其他类型存储，或是对通讯设备的访问（例如标准输入/输出
     、内存缓冲区、套接字、管道等等）。文件对象也被称为 `文件类对象' 或
     `流'。

     实际上共有三种类别的文件对象: 原始 *note 二进制文件: 1cb4, 缓冲
     *note 二进制文件: 1cb4. 以及 *note 文本文件: 12b5.。它们的接口定义
     均在 *note io: a2. 模块中。创建文件对象的规范方式是使用 *note
     open(): 4f8. 函数。

file-like object – 文件类对象

     *note file object: b4a. 的同义词。

finder – 查找器

     一种会尝试查找被导入模块的 *note loader: 14cb. 的对象。

     从 Python 3.3 起存在两种类型的查找器: *note 元路径查找器: 9b9. 配合
     *note sys.meta_path: 5ef. 使用，以及 *note path entry finders: 9ba.
     配合 *note sys.path_hooks: 964. 使用。

     更多详情可参见 PEP 302(16), PEP 420(17) 和 PEP 451(18)。

floor division – 向下取整除法

     向下舍入到最接近的整数的数学除法。向下取整除法的运算符是 ‘//’ 。例
     如，表达式 ‘11 // 4’ 的计算结果是 ‘2’ ，而与之相反的是浮点数的真正
     除法返回 ‘2.75’ 。注意 ‘(-11) // 4’ 会返回 ‘-3’ 因为这是 ‘-2.75’ `向
     下' 舍入得到的结果。见 PEP 238(19) 。

function – 函数

     可以向调用者返回某个值的一组语句。还可以向其传入零个或多个 *note
     参数: 1532. 并在函数体执行中被使用。另见 *note parameter: 153b,
     *note method: 430e. 和 *note 函数定义: 126c. 等节。

function annotation – 函数标注

     即针对函数形参或返回值的 *note annotation: 430c. 。

     函数标注通常用于 *note 类型提示: 430d.：例如以下函数预期接受两个
     *note int: 185. 参数并预期返回一个 *note int: 185. 值:

          def sum_two_numbers(a: int, b: int) -> int:
             return a + b

     函数标注语法的详解见 *note 函数定义: 126c. 一节。

     请参看 *note variable annotation: 628. 和 PEP 484(20) 对此功能的描
     述。

__future__

     一种伪模块，可被程序员用来启用与当前解释器不兼容的新语言特性。

     通过导入 *note __future__: 0. 模块并对其中的变量求值，你可以查看新
     特性何时首次加入语言以及何时成为默认:

          >>> import __future__
          >>> __future__.division
          _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)

garbage collection – 垃圾回收

     释放不再被使用的内存空间的过程。Python 是通过引用计数和一个能够检测
     和打破循环引用的循环垃圾回收器来执行垃圾回收的。可以使用 *note gc:
     86. 模块来控制垃圾回收器。

generator – 生成器

     返回一个 *note generator iterator: 45f. 的函数。它看起来很像普通函
     数，不同点在于其包含 *note yield: 190. 表达式以便产生一系列值供给
     for-循环使用或是通过 *note next(): 68b. 函数逐一获取。

     通常是指生成器函数，但在某些情况下也可能是指 `生成器迭代器'。如果需
     要清楚表达具体含义，请使用全称以避免歧义。

generator iterator – 生成器迭代器

     *note generator: 9aa. 函数所创建的对象。

     每个 *note yield: 190. 会临时暂停处理，记住当前位置执行状态（包括局
     部变量和挂起的 try 语句）。当该 `生成器迭代器' 恢复时，它会从离开位
     置继续执行（这与每次调用都从新开始的普通函数差别很大）。

generator expression – 生成器表达式

     返回一个迭代器的表达式。 它看起来很像普通表达式后面带有定义了一个循
     环变量、范围的 ‘for’ 子句，以及一个可选的 ‘if’ 子句。 以下复合表达
     式会为外层函数生成一系列值:

          >>> sum(i*i for i in range(10))         # sum of squares 0, 1, 4, ... 81
          285

generic function – 泛型函数

     为不同的类型实现相同操作的多个函数所组成的函数。在调用时会由调度算
     法来确定应该使用哪个实现。

     另请参见 *note single dispatch: 1cb. 术语表条目、*note
     functools.singledispatch(): 392. 装饰器以及 PEP 443(21)。

GIL

     参见 *note global interpreter lock: 50e.。

global interpreter lock – 全局解释器锁

     *note CPython: 1446. 解释器所采用的一种机制，它确保同一时刻只有一个
     线程在执行 Python *note bytecode: 61d.。此机制通过设置对象模型（包
     括 *note dict: 1b9. 等重要内置类型）针对并发访问的隐式安全简化了
     CPython 实现。给整个解释器加锁使得解释器多线程运行更方便，其代价则
     是牺牲了在多处理器上的并行性。

     不过，某些标准库或第三方库的扩展模块被设计为在执行计算密集型任务如
     压缩或哈希时释放 GIL。此外，在执行 I/O 操作时也总是会释放 GIL。

     创建一个（以更精细粒度来锁定共享数据的）“自由线程”解释器的努力从未
     获得成功，因为这会牺牲在普通单处理器情况下的性能。据信克服这种性能
     问题的措施将导致实现变得更复杂，从而更难以维护。

hash-based pyc – 基于哈希的 pyc

     使用对应源文件的哈希值而非最后修改时间来确定其有效性的字节码缓存文
     件。 参见 *note 已缓存字节码的失效: 332.。

hashable – 可哈希

     一个对象的哈希值如果在其生命周期内绝不改变，就被称为 `可哈希' （它
     需要具有 *note __hash__(): 349. 方法），并可以同其他对象进行比较（
     它需要具有 *note __eq__(): 348. 方法）。可哈希对象必须具有相同的哈
     希值比较结果才会相同。

     可哈希性使得对象能够作为字典键或集合成员使用，因为这些数据结构要在
     内部使用哈希值。

     大多数 Python 中的不可变内置对象都是可哈希的；可变容器（例如列表或
     字典）都不可哈希；不可变容器（例如元组和 frozenset）仅当它们的元素
     均为可哈希时才是可哈希的。 用户定义类的实例对象默认是可哈希的。 它
     们在比较时一定不相同（除非是与自己比较），它们的哈希值的生成是基于
     它们的 *note id(): d8e.。

IDLE

     Python 的 IDE，“集成开发与学习环境”的英文缩写。是 Python 标准发行版
     附带的基本编辑器和解释器环境。

immutable – 不可变

     具有固定值的对象。不可变对象包括数字、字符串和元组。这样的对象不能
     被改变。如果必须存储一个不同的值，则必须创建新的对象。它们在需要常
     量哈希值的地方起着重要作用，例如作为字典中的键。

import path – 导入路径

     由多个位置（或 *note 路径条目: 14df.）组成的列表，会被模块的 *note
     path based finder: 14d0. 用来查找导入目标。在导入时，此位置列表通常
     来自 *note sys.path: 490.，但对次级包来说也可能来自上级包的
     ‘__path__’ 属性。

importing – 导入

     令一个模块中的 Python 代码能为另一个模块中的 Python 代码所使用的过
     程。

importer – 导入器

     查找并加载模块的对象；此对象既属于 *note finder: 14ca. 又属于 *note
     loader: 14cb.。

interactive – 交互

     Python 带有一个交互式解释器，即你可以在解释器提示符后输入语句和表达
     式，立即执行并查看其结果。只需不带参数地启动 ‘python’ 命令（也可以
     在你的计算机开始菜单中选择相应菜单项）。在测试新想法或检验模块和包
     的时候用这种方式会非常方便（请记得使用 ‘help(x)’）。

interpreted – 解释型

     Python 一是种解释型语言，与之相对的是编译型语言，虽然两者的区别由于
     字节码编译器的存在而会有所模糊。这意味着源文件可以直接运行而不必显
     式地创建可执行文件再运行。解释型语言通常具有比编译型语言更短的开发
     /调试周期，但是其程序往往运行得更慢。参见 *note interactive: 431c.。

interpreter shutdown – 解释器关闭

     当被要求关闭时，Python 解释器将进入一个特殊运行阶段并逐步释放所有已
     分配资源，例如模块和各种关键内部结构等。它还会多次调用 *note
     垃圾回收器: ed8.。这会触发用户定义析构器或弱引用回调中的代码执行。
     在关闭阶段执行的代码可能会遇到各种异常，因为其所依赖的资源已不再有
     效（常见的例子有库模块或警告机制等）。

     解释器需要关闭的主要原因有 ‘__main__’ 模块或所运行的脚本已完成执行
     。

iterable – 可迭代对象

     能够逐一返回其成员项的对象。 可迭代对象的例子包括所有序列类型 (例如
     *note list: 263, *note str: 339. 和 *note tuple: 486.) 以及某些非序
     列类型例如 *note dict: 1b9, *note 文件对象: b4a. 以及定义了 *note
     __iter__(): 517. 方法或是实现了 *note 序列: 1238. 语义的 *note
     __getitem__(): 280. 方法的任意自定义类对象。

     可迭代对象被可用于 *note for: c38. 循环以及许多其他需要一个序列的地
     方（*note zip(): c3a.、*note map(): c35. ...）。当一个可迭代对象作
     为参数传给内置函数 *note iter(): d2f. 时，它会返回该对象的迭代器。
     这种迭代器适用于对值集合的一次性遍历。在使用可迭代对象时，你通常不
     需要调用 *note iter(): d2f. 或者自己处理迭代器对象。‘for’ 语句会为
     你自动处理那些操作，创建一个临时的未命名变量用来在循环期间保存迭代
     器。参见 *note iterator: 104b.、*note sequence: 1238. 以及 *note
     generator: 9aa.。

iterator – 迭代器

     用来表示一连串数据流的对象。重复调用迭代器的 *note __next__(): c6c.
     方法（或将其传给内置函数 *note next(): 68b.）将逐个返回流中的项。当
     没有数据可用时则将引发 *note StopIteration: 48e. 异常。到这时迭代器
     对象中的数据项已耗尽，继续调用其 ‘__next__()’ 方法只会再次引发
     *note StopIteration: 48e. 异常。迭代器必须具有 *note __iter__():
     517. 方法用来返回该迭代器对象自身，因此迭代器必定也是可迭代对象，可
     被用于其他可迭代对象适用的大部分场合。一个显著的例外是那些会多次重
     复访问迭代项的代码。容器对象（例如 *note list: 263.）在你每次向其传
     入 *note iter(): d2f. 函数或是在 *note for: c38. 循环中使用它时都会
     产生一个新的迭代器。如果在此情况下你尝试用迭代器则会返回在之前迭代
     过程中被耗尽的同一迭代器对象，使其看起来就像是一个空容器。

     更多信息可查看 *note 迭代器类型: 146c.。

key function – 键函数

     键函数或称整理函数，是能够返回用于排序或排位的值的可调用对象。例如
     ，*note locale.strxfrm(): 3091. 可用于生成一个符合特定区域排序约定
     的排序键。

     Python 中有许多工具都允许用键函数来控制元素的排位或分组方式。其中包
     括 *note min(): 812, *note max(): 813, *note sorted(): 44c, *note
     list.sort(): 44d, *note heapq.merge(): 6e8, *note
     heapq.nsmallest(): 1974, *note heapq.nlargest(): 1973. 以及 *note
     itertools.groupby(): 1b52.。

     要创建一个键函数有多种方式。例如，*note str.lower(): 1653. 方法可以
     用作忽略大小写排序的键函数。另外，键函数也可通过 *note lambda: c37.
     表达式来创建，例如 ‘lambda r: (r[0], r[2])’。还有 *note operator:
     c3. 模块提供了三个键函数构造器：*note attrgetter(): 724.、*note
     itemgetter(): 262. 和 *note methodcaller(): 725.。请查看 *note
     如何排序: 1611. 一节以获取创建和使用键函数的示例。

keyword argument – 关键字参数

     参见 *note argument: 1532.。

lambda

     由一个单独 *note expression: 3631. 构成的匿名内联函数，表达式会在调
     用时被求值。创建 lambda 函数的句法为 ‘lambda [parameters]:
     expression’

LBYL

     “先查看后跳跃”的英文缩写。这种代码编写风格会在进行调用或查找之前显
     式地检查前提条件。此风格与 *note EAFP: 1f5b. 方式恰成对比，其特点是
     大量使用 *note if: def. 语句。

     在多线程环境中，LBYL 方式会导致“查看”和“跳跃”之间发生条件竞争风险。
     例如，以下代码 ‘if key in mapping: return mapping[key]’ 可能由于在
     检查操作之后其他线程从 `mapping' 中移除了 `key' 而出错。这种问题可
     通过加锁或使用 EAFP 方式来解决。

list – 列表

     Python 内置的一种 *note sequence: 1238.。虽然名为列表，但更类似于其
     他语言中的数组而非链接列表，因为访问元素的时间复杂度为 O(1)。

list comprehension – 列表推导式

     处理一个序列中的所有或部分元素并返回结果列表的一种紧凑写法。‘result
     = ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0]’ 将生成一
     个 0 到 255 范围内的十六进制偶数对应字符串（0x..）的列表。其中
     *note if: def. 子句是可选的，如果省略则 ‘range(256)’ 中的所有元素都
     会被处理。

loader – 加载器

     负责加载模块的对象。它必须定义名为 ‘load_module()’ 的方法。加载器通
     常由一个 *note finder: 14ca. 返回。详情参见 PEP 302(22)，对于 *note
     abstract base class: b3b. 可参见 *note importlib.abc.Loader: 7cb.。

magic method – 魔术方法

     *note special method: 366c. 的非正式同义词 。

mapping – 映射

     一种支持任意键查找并实现了 *note Mapping: 1954. 或 *note
     MutableMapping: 9f7. *note 抽象基类: 1937. 中所规定方法的容器对象。
     此类对象的例子包括 *note dict: 1b9, *note collections.defaultdict:
     b42, *note collections.OrderedDict: 1ba. 以及 *note
     collections.Counter: 9e2.。

meta path finder – 元路径查找器

     *note sys.meta_path: 5ef. 的搜索所返回的 *note finder: 14ca.。元路
     径查找器与 *note path entry finders: 9ba. 存在关联但并不相同。

     请查看 *note importlib.abc.MetaPathFinder: 9bb. 了解元路径查找器所
     实现的方法。

metaclass – 元类

     一种用于创建类的类。类定义包含类名、类字典和基类列表。元类负责接受
     上述三个参数并创建相应的类。大部分面向对象的编程语言都会提供一个默
     认实现。Python 的特别之处在于可以创建自定义元类。大部分用户永远不需
     要这个工具，但当需要出现时，元类可提供强大而优雅的解决方案。它们已
     被用于记录属性访问日志、添加线程安全性、跟踪对象创建、实现单例，以
     及其他许多任务。

     更多详情参见 *note 元类: 1458.。

method – 方法

     在类内部定义的函数。如果作为该类的实例的一个属性来调用，方法将会获
     取实例对象作为其第一个 *note argument: 1532. (通常命名为 ‘self’)。
     参见 *note function: 1533. 和 *note nested scope: 15fb.。

method resolution order – 方法解析顺序

     方法解析顺序就是在查找成员时搜索全部基类所用的先后顺序。请查看
     Python 2.3 方法解析顺序(23) 了解自 2.3 版起 Python 解析器所用相关算
     法的详情。

module – 模块

     此对象是 Python 代码的一种组织单位。各模块具有独立的命名空间，可包
     含任意 Python 对象。模块可通过 *note importing: 14be. 操作被加载到
     Python 中。

     另见 *note package: ec6.。

module spec – 模块规格

     一个命名空间，其中包含用于加载模块的相关导入信息。是 *note
     importlib.machinery.ModuleSpec: 14d6. 的实例。

MRO

     参见 *note method resolution order: 1614.。

mutable – 可变

     可变对象可以在其 *note id(): d8e. 保持固定的情况下改变其取值。另请
     参见 *note immutable: 1232.。

named tuple – 具名元组

     术语“具名元组”可用于任何继承自元组，并且其中的可索引元素还能使用名
     称属性来访问的类型或类。 这样的类型或类还可能拥有其他特性。

     有些内置类型属于具名元组，包括 *note time.localtime(): f5d. 和
     *note os.stat(): 1f2. 的返回值。 另一个例子是 *note sys.float_info:
     fd1.:

          >>> sys.float_info[1]                   # indexed access
          1024
          >>> sys.float_info.max_exp              # named field access
          1024
          >>> isinstance(sys.float_info, tuple)   # kind of tuple
          True

     有些具名元组是内置类型（例如上面的例子）。 此外，具名元组还可通过常
     规类定义从 *note tuple: 486. 继承并定义名称字段的方式来创建。 这样
     的类可以手工编写，或者使用工厂函数 *note collections.namedtuple():
     1b7. 创建。 后一种方式还会添加一些手工编写或内置具名元组所没有的额
     外方法。

namespace – 命名空间

     命名空间是存放变量的场所。命名空间有局部、全局和内置的，还有对象中
     的嵌套命名空间（在方法之内）。命名空间通过防止命名冲突来支持模块化
     。例如，函数 *note builtins.open: 4f8. 与 *note os.open(): 66e. 可
     通过各自的命名空间来区分。命名空间还通过明确哪个模块实现那个函数来
     帮助提高可读性和可维护性。例如，*note random.seed(): c10. 或 *note
     itertools.islice(): 3aa. 这种写法明确了这些函数是由 *note random:
     dd. 与 *note itertools: a4. 模块分别实现的。

namespace package – 命名空间包

     PEP 420(24) 所引入的一种仅被用作子包的容器的 *note package: ec6.，
     命名空间包可以没有实体表示物，其描述方式与 *note regular package:
     14c2. 不同，因为它们没有 ‘__init__.py’ 文件。

     另可参见 *note module: 14bd.。

nested scope – 嵌套作用域

     在一个定义范围内引用变量的能力。例如，在另一函数之内定义的函数可以
     引用前者的变量。请注意嵌套作用域默认只对引用有效而对赋值无效。局部
     变量的读写都受限于最内层作用域。类似的，全局变量的读写则作用于全局
     命名空间。通过 *note nonlocal: c47. 关键字可允许写入外层作用域。

new-style class – 新式类

     对于目前已被应于所有类对象的类形式的旧称谓。在早先的 Python 版本中
     ，只有新式类能够使用 Python 新增的更灵活特性，例如 *note __slots__:
     e35.、描述符、特征属性、*note __getattribute__(): 44f.、类方法和静
     态方法等。

object – 对象

     任何具有状态（属性或值）以及预定义行为（方法）的数据。object 也是任
     何 *note new-style class: 1cbc. 的最顶层基类名。

package – 包

     一种可包含子模块或递归地包含子包的 Python *note module: 14bd.。从技
     术上说，包是带有 ‘__path__’ 属性的 Python 模块。

     另参见 *note regular package: 14c2. 和 *note namespace package:
     14c3.。

parameter – 形参

     *note function: 1533. （或方法）定义中的命名实体，它指定函数可以接
     受的一个 *note argument: 1532. （或在某些情况下，多个实参）。有五种
     形参：

        * `positional-or-keyword'：位置或关键字，指定一个可以作为 *note
          位置参数: 1532. 传入也可以作为 *note 关键字参数: 1532. 传入的
          实参。这是默认的形参类型，例如下面的 `foo' 和 `bar':

               def func(foo, bar=None): ...

        * `positional-only'：仅限位置，指定一个只能通过位置传入的参数。
          仅限位置形参可通过在函数定义的形参列表中它们之后包含一个 ‘/’ 字
          符来定义，例如下面的 `posonly1' 和 `posonly2':

               def func(posonly1, posonly2, /, positional_or_keyword): ...

        * `keyword-only'：仅限关键字，指定一个只能通过关键字传入的参数。
          仅限关键字形参可通过在函数定义的形参列表中包含单个可变位置形参
          或者在多个可变位置形参之前放一个 ‘*’ 来定义，例如下面的
          `kw_only1' 和 `kw_only2':

               def func(arg, *, kw_only1, kw_only2): ...

        * `var-positional'：可变位置，指定可以提供由一个任意数量的位置参
          数构成的序列（附加在其他形参已接受的位置参数之后）。这种形参可
          通过在形参名称前加缀 ‘*’ 来定义，例如下面的 `args':

               def func(*args, **kwargs): ...

        * `var-keyword'：可变关键字，指定可以提供任意数量的关键字参数（
          附加在其他形参已接受的关键字参数之后）。这种形参可通过在形参名
          称前加缀 ‘**’ 来定义，例如上面的 `kwargs'。

     形参可以同时指定可选和必选参数，也可以为某些可选参数指定默认值。

     另参见 *note argument: 1532. 术语表条目、*note 参数与形参的区别:
     4257. 中的常见问题、*note inspect.Parameter: 6fd. 类、*note
     函数定义: 126c. 一节以及 PEP 362(25)。

path entry – 路径入口

     *note import path: 14cd. 中的一个单独位置，会被 *note path based
     finder: 14d0. 用来查找要导入的模块。

path entry finder – 路径入口查找器

     任一可调用对象使用 *note sys.path_hooks: 964. (即 *note path entry
     hook: 14e1.) 返回的 *note finder: 14ca.，此种对象能通过 *note path
     entry: 14df. 来定位模块。

     请参看 *note importlib.abc.PathEntryFinder: 9bc. 以了解路径入口查找
     器所实现的各个方法。

path entry hook – 路径入口钩子

     一种可调用对象，在知道如何查找特定 *note path entry: 14df. 中的模块
     的情况下能够使用 ‘sys.path_hook’ 列表返回一个 *note path entry
     finder: 9ba.。

path based finder – 基于路径的查找器

     默认的一种 *note 元路径查找器: 9b9.，可在一个 *note import path:
     14cd. 中查找模块。

path-like object – 路径类对象

     代表一个文件系统路径的对象。类路径对象可以是一个表示路径的 *note
     str: 339. 或者 *note bytes: 33a. 对象，还可以是一个实现了 *note
     os.PathLike: 4f3. 协议的对象。一个支持 *note os.PathLike: 4f3. 协议
     的对象可通过调用 *note os.fspath(): 4f5. 函数转换为 *note str: 339.
     或者 *note bytes: 33a. 类型的文件系统路径；*note os.fsdecode():
     4f6. 和 *note os.fsencode(): 4f7. 可被分别用来确保获得 *note str:
     339. 或 *note bytes: 33a. 类型的结果。此对象是由 PEP 519(26) 引入的
     。

PEP

     “Python 增强提议”的英文缩写。一个 PEP 就是一份设计文档，用来向
     Python 社区提供信息，或描述一个 Python 的新增特性及其进度或环境。
     PEP 应当提供精确的技术规格和所提议特性的原理说明。

     PEP 应被作为提出主要新特性建议、收集社区对特定问题反馈以及为必须加
     入 Python 的设计决策编写文档的首选机制。PEP 的作者有责任在社区内部
     建立共识，并应将不同意见也记入文档。

     参见 PEP 1(27)。

portion – 部分

     构成一个命名空间包的单个目录内文件集合（也可能存放于一个 zip 文件内
     ），具体定义见 PEP 420(28)。

positional argument – 位置参数

     参见 *note argument: 1532.。

provisional API – 暂定 API

     暂定 API 是指被有意排除在标准库的向后兼容性保证之外的应用编程接口。
     虽然此类接口通常不会再有重大改变，但只要其被标记为暂定，就可能在核
     心开发者确定有必要的情况下进行向后不兼容的更改（甚至包括移除该接口
     ）。此种更改并不会随意进行 – 仅在 API 被加入之前未考虑到的严重基础
     性缺陷被发现时才可能会这样做。

     即便是对暂定 API 来说，向后不兼容的更改也会被视为“最后的解决方案”
     —— 任何问题被确认时都会尽可能先尝试找到一种向后兼容的解决方案。

     这种处理过程允许标准库持续不断地演进，不至于被有问题的长期性设计缺
     陷所困。详情见 PEP 411(29)。

provisional package – 暂定包

     参见 *note provisional API: 351.。

Python 3000

     Python 3.x 发布路线的昵称（这个名字在版本 3 的发布还遥遥无期的时候
     就已出现了）。有时也被缩写为“Py3k”。

Pythonic

     指一个思路或一段代码紧密遵循了 Python 语言最常用的风格和理念，而不
     是使用其他语言中通用的概念来实现代码。例如，Python 的常用风格是使用
     *note for: c38. 语句循环来遍历一个可迭代对象中的所有元素。许多其他
     语言没有这样的结构，因此不熟悉 Python 的人有时会选择使用一个数字计
     数器:

          for i in range(len(food)):
              print(food[i])

     而相应的更简洁更 Pythonic 的方法是这样的:

          for piece in food:
              print(piece)

qualified name – 限定名称

     一个以点号分隔的名称，显示从模块的全局作用域到该模块中定义的某个类
     、函数或方法的“路径”，相关定义见 PEP 3155(30)。对于最高层级的函数和
     类，限定名称与对象名称一致:

          >>> class C:
          ...     class D:
          ...         def meth(self):
          ...             pass
          ...
          >>> C.__qualname__
          'C'
          >>> C.D.__qualname__
          'C.D'
          >>> C.D.meth.__qualname__
          'C.D.meth'

     当被用于引用模块时，`完整限定名称' 意为标示该模块的以点号分隔的整个
     路径，其中包含其所有的父包，例如 ‘email.mime.text’:

          >>> import email.mime.text
          >>> email.mime.text.__name__
          'email.mime.text'

reference count – 引用计数

     对特定对象的引用的数量。当一个对象的引用计数降为零时，所分配资源将
     被释放。引用计数对 Python 代码来说通常是不可见的，但它是 *note
     CPython: 1446. 实现的一个关键元素。*note sys: fe. 模块定义了一个
     *note getrefcount(): 363b. 函数，程序员可调用它来返回特定对象的引用
     计数。

regular package – 常规包

     传统型的 *note package: ec6.，例如包含有一个 ‘__init__.py’ 文件的目
     录。

     另参见 *note namespace package: 14c3.。

__slots__

     一种写在类内部的声明，通过预先声明实例属性等对象并移除实例字典来节
     省内存。虽然这种技巧很流行，但想要用好却并不容易，最好是只保留在少
     数情况下采用，例如极耗内存的应用程序，并且其中包含大量实例。

sequence – 序列

     一种 *note iterable: bb4.，它支持通过 *note __getitem__(): 280. 特
     殊方法来使用整数索引进行高效的元素访问，并定义了一个返回序列长度的
     *note __len__(): dd3. 方法。内置的序列类型有 *note list: 263.、
     *note str: 339.、*note tuple: 486. 和 *note bytes: 33a.。注意虽然
     *note dict: 1b9. 也支持 *note __getitem__(): 280. 和 *note
     __len__(): dd3.，但它被认为属于映射而非序列，因为它查找时使用任意的
     *note immutable: 1232. 键而非整数。

     *note collections.abc.Sequence: 1640. 抽象基类定义了一个更丰富的接
     口，它在 *note __getitem__(): 280. 和 *note __len__(): dd3. 之外又
     添加了 ‘count()’, ‘index()’, *note __contains__(): d30. 和 *note
     __reversed__(): 537.。 实现此扩展接口的类型可以使用 *note
     register(): 9d9. 来显式地注册。

set comprehension – 集合推导式

     处理一个可迭代对象中的所有或部分元素并返回结果集合的一种紧凑写法。
     ‘results = {c for c in 'abracadabra' if c not in 'abc'}’ 将生成字符
     串集合 ‘{'r', 'd'}’。 参见 *note 列表、集合与字典的显示: 14fb.。

single dispatch – 单分派

     一种 *note generic function: 1cc. 分派形式，其实现是基于单个参数的
     类型来选择的。

slice – 切片

     通常只包含了特定 *note sequence: 1238. 的一部分的对象。切片是通过使
     用下标标记来创建的，在 ‘[]’ 中给出几个以冒号分隔的数字，例如
     ‘variable_name[1:3:5]’。方括号（下标）标记在内部使用 *note slice:
     e0c. 对象。

special method – 特殊方法

     一种由 Python 隐式调用的方法，用来对某个类型执行特定操作例如相加等
     等。这种方法的名称的首尾都为双下划线。特殊方法的文档参见 *note
     特殊方法名称: 516.。

statement – 语句

     语句是程序段（一个代码“块”）的组成单位。一条语句可以是一个 *note
     expression: 3631. 或某个带有关键字的结构，例如 *note if: def.、
     *note while: 123d. 或 *note for: c38.。

text encoding – 文本编码

     用于将Unicode字符串编码为字节串的编码器。

text file – 文本文件

     一种能够读写 *note str: 339. 对象的 *note file object: b4a.。通常一
     个文本文件实际是访问一个面向字节的数据流并自动处理 *note text
     encoding: 160b.。文本文件的例子包括以文本模式（‘'r'’ 或 ‘'w'’）打开
     的文件、*note sys.stdin: 316.、*note sys.stdout: 317. 以及 *note
     io.StringIO: 836. 的实例。

     另请参看 *note binary file: 1cb4. 了解能够读写 *note 字节类对象:
     5f1. 的文件对象。

triple-quoted string – 三引号字符串

     首尾各带三个连续双引号（"）或者单引号（’）的字符串。它们在功能上与
     首尾各用一个引号标注的字符串没有什么不同，但是有多种用处。它们允许
     你在字符串内包含未经转义的单引号和双引号，并且可以跨越多行而无需使
     用连接符，在编写文档字符串时特别好用。

type – 类型

     类型决定一个 Python 对象属于什么种类；每个对象都具有一种类型。要知
     道对象的类型，可以访问它的 *note __class__: e12. 属性，或是通过
     ‘type(obj)’ 来获取。

type alias – 类型别名

     一个类型的同义词，创建方式是把类型赋值给特定的标识符。

     类型别名的作用是简化 *note 类型提示: 430d.。例如:

          from typing import List, Tuple

          def remove_gray_shades(
                  colors: List[Tuple[int, int, int]]) -> List[Tuple[int, int, int]]:
              pass

     可以这样提高可读性:

          from typing import List, Tuple

          Color = Tuple[int, int, int]

          def remove_gray_shades(colors: List[Color]) -> List[Color]:
              pass

     参见 *note typing: 11a. 和 PEP 484(31)，其中有对此功能的详细描述。

type hint – 类型提示

     *note annotation: 430c. 为变量、类属性、函数的形参或返回值指定预期
     的类型。

     类型提示属于可选项，Python 不要求提供，但其可对静态类型分析工具起作
     用，并可协助 IDE 实现代码补全与重构。

     全局变量、类属性和函数的类型提示可以使用 *note
     typing.get_type_hints(): 313. 来访问，但局部变量则不可以。

     参见 *note typing: 11a. 和 PEP 484(32)，其中有对此功能的详细描述。

universal newlines – 通用换行

     一种解读文本流的方式，将以下所有符号都识别为行结束标志：Unix 的行结
     束约定 ‘'\n'’、Windows 的约定 ‘'\r\n'’ 以及旧版 Macintosh 的约定
     ‘'\r'’。参见 PEP 278(33) 和 PEP 3116(34) 和 *note
     bytes.splitlines(): 16b3. 了解更多用法说明。

variable annotation – 变量标注

     对变量或类属性的 *note annotation: 430c.。

     在标注变量或类属性时，还可选择为其赋值:

          class C:
              field: 'annotation'

     变量标注通常被用作 *note 类型提示: 430d.：例如以下变量预期接受
     *note int: 185. 类型的值:

          count: int = 0

     变量标注语法的详细解释见 *note 带标注的赋值语句: 1586. 一节。

     请参看 *note function annotation: 126d.、 PEP 484(35) 和 PEP
     526(36)，其中对此功能有详细描述。

virtual environment – 虚拟环境

     一种采用协作式隔离的运行时环境，允许 Python 用户和应用程序在安装和
     升级 Python 分发包时不会干扰到同一系统上运行的其他 Python 应用程序
     的行为。

     另参见 *note venv: 126.。

virtual machine – 虚拟机

     一台完全通过软件定义的计算机。Python 虚拟机可执行字节码编译器所生成
     的 *note bytecode: 61d.。

Zen of Python – Python 之禅

     列出 Python 设计的原则与哲学，有助于理解与使用这种语言。查看其具体
     内容可在交互模式提示符中输入 "‘import this’"。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0526

   (3) https://www.python.org/dev/peps/pep-0362

   (4) https://www.python.org/dev/peps/pep-0492

   (5) https://www.python.org/dev/peps/pep-0492

   (6) https://www.python.org/dev/peps/pep-0525

   (7) https://www.python.org/dev/peps/pep-0492

   (8) https://www.python.org/dev/peps/pep-0492

   (9) https://www.python.org/dev/peps/pep-0492

   (10) https://gvanrossum.github.io/

   (11) https://www.python.org/dev/peps/pep-0343

   (12) https://www.python.org/dev/peps/pep-0492

   (13) https://www.python.org/dev/peps/pep-0492

   (14) https://www.python.org

   (15) https://www.python.org/dev/peps/pep-0498

   (16) https://www.python.org/dev/peps/pep-0302

   (17) https://www.python.org/dev/peps/pep-0420

   (18) https://www.python.org/dev/peps/pep-0451

   (19) https://www.python.org/dev/peps/pep-0238

   (20) https://www.python.org/dev/peps/pep-0484

   (21) https://www.python.org/dev/peps/pep-0443

   (22) https://www.python.org/dev/peps/pep-0302

   (23) https://www.python.org/download/releases/2.3/mro/

   (24) https://www.python.org/dev/peps/pep-0420

   (25) https://www.python.org/dev/peps/pep-0362

   (26) https://www.python.org/dev/peps/pep-0519

   (27) https://www.python.org/dev/peps/pep-0001

   (28) https://www.python.org/dev/peps/pep-0420

   (29) https://www.python.org/dev/peps/pep-0411

   (30) https://www.python.org/dev/peps/pep-3155

   (31) https://www.python.org/dev/peps/pep-0484

   (32) https://www.python.org/dev/peps/pep-0484

   (33) https://www.python.org/dev/peps/pep-0278

   (34) https://www.python.org/dev/peps/pep-3116

   (35) https://www.python.org/dev/peps/pep-0484

   (36) https://www.python.org/dev/peps/pep-0526


File: python.info,  Node: 文档说明,  Next: 处理错误,  Prev: 术语对照表,  Up: Top

13 文档说明
***********

这些文档是用 Sphinx(1) 从 reStructuredText(2) 源生成的，‘Sphinx’ 是一个
专为处理 Python 文档而编写的文档生成器。

本文档及其工具链之开发，皆在于志愿者之努力，亦恰如 Python 本身。如果您想
为此作出贡献，请阅读 *note 处理错误: 3b99. 了解如何参与。我们随时欢迎新
的志愿者！

特别鸣谢：

   * Fred L. Drake, Jr.，原始 Python 文档工具集之创造者，众多文档之作者
     ；

   * Docutils(3) 项目，该项目孕育了 reStructuredText 及 Docutils 套件；

   * Fredrik Lundh 的项目 Alternative Python Reference(4)，Sphinx 从中得
     到了很多不错的点子

* Menu:

* Python 文档的贡献者::

   ---------- Footnotes ----------

   (1) http://sphinx-doc.org/

   (2) http://docutils.sourceforge.net/rst.html

   (3) http://docutils.sourceforge.net/

   (4) http://effbot.org/zone/pyref.htm


File: python.info,  Node: Python 文档的贡献者,  Up: 文档说明

13.1 Python 文档的贡献者
========================

有很多对 Python 语言，Python 标准库和 Python 文档有贡献的人，随 Python 源
代码发布的 Misc/ACKS(1) 文件列出了部分贡献者。

仅通过 Python 社区的输入和贡献，Python 就拥有了如此出色的文档——谢谢你们
！

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.8/Misc/ACKS


File: python.info,  Node: 处理错误,  Next: 版权所有,  Prev: 文档说明,  Up: Top

14 处理错误
***********

Python 是一门成熟的编程语言，以稳定著称。为维持其美誉，开发者希望获悉所
有您在 Python 中发现的缺陷。

有时候自己修复漏洞并将补丁提交给 Python 能更快地解决问题，因为它简化了流
程并且减少了参与的人力。 请参阅如何 *note 提交补丁: 4330.。

* Menu:

* 文档 Bug::
* 使用 Python 的问题追踪系统::
* 开始为 Python 贡献您的知识::


File: python.info,  Node: 文档 Bug,  Next: 使用 Python 的问题追踪系统,  Up: 处理错误

14.1 文档 Bug
=============

如果您在本文档中发现了错误并打算帮助我们改进，请将错误提交到 *note
追踪系统: 4332.。 如果您有相应的修正建议，请一并提交。 （译者注：如果是
中文文档翻译相关的错误，请务必提交到
‘https://github.com/python/python-docs-zh-cn/issues’。如果将翻译问题反馈
到了其他地方，可能会因为语言不通而不能及时处理。）

如果您时间有限，还可以通过电子邮件将文档的错误报告发送至
<docs@python>.org（代码运行错误请发送至 <python-list@python.org>）。
“docs@”是一个由志愿者运作的邮件列表；您的请求会得到关注，但可能需要一些
时间才会被处理。

参见
....

Documentation bugs(1)

     已提交给 Python 问题追踪系统的文档错误列表。

问题跟踪(2)

     在追踪系统上参与问题改进的过程概述。

改进文档(3)

     给有兴趣为 Python 文档做出贡献的人。

   ---------- Footnotes ----------

   (1) 
https://bugs.python.org/issue?@filter=status&@filter=components&components=4&status=1&@columns=id,activity,title,status&@sort=-activity

   (2) https://devguide.python.org/tracker/

   (3) 
https://devguide.python.org/docquality/#helping-with-documentation


File: python.info,  Node: 使用 Python 的问题追踪系统,  Next: 开始为 Python 贡献您的知识,  Prev: 文档 Bug,  Up: 处理错误

14.2 使用 Python 的问题追踪系统
===============================

对于 Python 本身的错误报告应当通过 Python 错误追踪系统（
‘https://bugs.python.org/’）进行提交。该错误追踪系统提供了一个可以输入并
提交相关信息给开发者的网页表单。

第一步是确认是否有重复的报告。这样做除了可以节省开发者的时间，也能让您从
中了解到我们做出了怎样的努力；我们有可能已经在下个版本中修复了这个问题，
也有可能需要更详细的信息（在这种情况下，非常欢迎您提供！）。要查找重复的
报告，请使用顶部的搜索栏进行搜索。

如果您没有搜索到您想报告的问题，请返回并登录 Python 错误追踪系统。如果您
没有账号，请点击“注册（Register）”链接，或者在侧边栏中选择任何一个
OpenID 登录方式。您不能匿名提交一份错误报告。

如果已经登录， 那您就可以提交错误报告了。请点击侧边栏中的“新建（Create
New）”链接，打开报告表单。

表单中有几个空栏（译者注：请用英语填写）。请在 “标题（Title）”栏填入对问
题 `非常' 简短的描述；一个好的描述应当少于十个单词。在 “类型（Type）”栏
，选择您的问题的类型；同样地，选择 bug 相对应的“组件（Component）”和“版
本（Versions）”。

在“说明（Comment）”栏，请详细描述问题，包括您预期的情况和实际的情况。请
确保包含任何涉及的拓展模块，以及您当时所使用的硬件和软件平台（如果可能，
请附上版本信息）。

每一份错误报告将被分派给一名开发者，并由这名开发者决定如何修正这个问题。
每当有相关的进展时，您都会收到通知。

参见
....

如何有效地报告错误(1)

     该文章详细介绍了如何创建一份有用的错误报告。它描述了什么样的信息是
     有用的，以及为什么是有用的。

错误报告编写指南(2)

     关于写一份好的错误报告。部分仅针对 Mozilla 项目，不过其描述了通用的
     恰当做法。

   ---------- Footnotes ----------

   (1) https://www.chiark.greenend.org.uk/~sgtatham/bugs.html

   (2) 
https://developer.mozilla.org/en-US/docs/Mozilla/QA/Bug_writing_guidelines


File: python.info,  Node: 开始为 Python 贡献您的知识,  Prev: 使用 Python 的问题追踪系统,  Up: 处理错误

14.3 开始为 Python 贡献您的知识
===============================

除了仅仅报告您所发现的错误之外，同样欢迎您提交修复它们的补丁。您可以在
Python 开发者指引(1) 中找到更多为 Python 打补丁的信息。如果您有任何问题
，核心导师邮件列表(2) 是一个友好的去处，在那里， 你可以寻求修复 Python 相
关问题的答案。

   ---------- Footnotes ----------

   (1) https://devguide.python.org/

   (2) 
https://mail.python.org/mailman3/lists/core-mentorship.python.org/


File: python.info,  Node: 版权所有,  Next: 历史和许可证,  Prev: 处理错误,  Up: Top

15 版权所有
***********

Python 与这份文档：

版权所有 © 2001-2021 Python 软件基金会。 保留所有权利。

版权所有 © 2000 BeOpen.com。保留所有权利。

版权所有 © 1995-2000 Corporation for National Research Initiatives。保留
所有权利。

版权所有 © 1991-1995 Stichting Mathematisch Centrum。保留所有权利。

__________________________________________________________________

有关完整的许可证和许可信息，参见 *note 历史和许可证: 4338.。


File: python.info,  Node: 历史和许可证,  Next: 分发 Python 模块（遗留版本）,  Prev: 版权所有,  Up: Top

16 历史和许可证
***************

* Menu:

* 该软件的历史::
* 获取或以其他方式使用 Python 的条款和条件::
* 收录软件的许可与鸣谢::


File: python.info,  Node: 该软件的历史,  Next: 获取或以其他方式使用 Python 的条款和条件,  Up: 历史和许可证

16.1 该软件的历史
=================

Python 由荷兰数学和计算机科学研究学会（CWI，见 ‘https://www.cwi.nl/’ ）
的 Guido van Rossum 于 1990 年代初设计，作为一门叫做 ABC 的语言的替代品
。尽管 Python 包含了许多来自其他人的贡献，Guido 仍是其主要作者。

1995 年，Guido 在弗吉尼亚州的国家创新研究公司（CNRI，见
‘https://www.cnri.reston.va.us/’ ）继续他在 Python 上的工作，并在那里发
布了该软件的多个版本。

2000 年五月，Guido 和 Python 核心开发团队转到 BeOpen.com 并组建了 BeOpen
PythonLabs 团队。 同年十月，PythonLabs 团队转到 Digital Creations (现为
Zope Corporation；见 ‘https://www.zope.org/’)。 2001 年，Python 软件基金
会 (PSF，见 ‘https://www.python.org/psf/’) 成立，这是一个专为拥有 Python
相关知识产权而创建的非营利组织。 Zope Corporation 现在是 PSF 的赞助成员
。

所有的 Python 版本都是开源的（有关开源的定义参阅
‘https://opensource.org/’ ）。历史上，绝大多数 Python 版本是 GPL 兼容的
；下表总结了各个版本情况。

发布版本             源自               年份             所有者           GPL 兼容？
                                                                          
------------------------------------------------------------------------------------------------
                                                                          
0.9.0 至 1.2         n/a                1991-1995        CWI              是
                                                                          
                                                                          
1.3 至 1.5.2         1.2                1995-1999        CNRI             是
                                                                          
                                                                          
1.6                  1.5.2              2000             CNRI             否
                                                                          
                                                                          
2.0                  1.6                2000             BeOpen.com       否
                                                                          
                                                                          
1.6.1                1.6                2001             CNRI             否
                                                                          
                                                                          
2.1                  2.0+1.6.1          2001             PSF              否
                                                                          
                                                                          
2.0.1                2.0+1.6.1          2001             PSF              是
                                                                          
                                                                          
2.1.1                2.1+2.0.1          2001             PSF              是
                                                                          
                                                                          
2.1.2                2.1.1              2002             PSF              是
                                                                          
                                                                          
2.1.3                2.1.2              2002             PSF              是
                                                                          
                                                                          
2.2 及更高           2.1.1              2001 至今        PSF              是
                                                                          

     注解: GPL 兼容并不意味着 Python 在 GPL 下发布。与 GPL 不同，所有
     Python 许可证都允许您分发修改后的版本，而无需开源所做的更改。GPL 兼
     容的许可证使得 Python 可以与其它在 GPL 下发布的软件结合使用；但其它
     的许可证则不行。

感谢众多在 Guido 指导下工作的外部志愿者，使得这些发布成为可能。


File: python.info,  Node: 获取或以其他方式使用 Python 的条款和条件,  Next: 收录软件的许可与鸣谢,  Prev: 该软件的历史,  Up: 历史和许可证

16.2 获取或以其他方式使用 Python 的条款和条件
=============================================

Python 软件和文档的使用许可是依据 *note PSF 许可证协议: 433d.。

从 Python 3.8.6 开始，文档中的示例、操作指导和其他代码采用的是 PSF 许可
协议和 *note 零条款 BSD 许可: 433e. 的双重使用许可。

某些包含在 Python 中的软件是基于不同的许可。 这些许可会与相应许可之下的
代码一同列出。 有关这些许可的不完整列表请参阅 *note
收录软件的许可与鸣谢: 433f.。

* Menu:

* 用于 PYTHON 3.8.12 的 PSF 许可协议: 用于 PYTHON 3 8 12 的 PSF 许可协议.
* 用于 PYTHON 2.0 的 BEOPEN.COM 许可协议: 用于 PYTHON 2 0 的 BEOPEN COM 许可协议.
* 用于 PYTHON 1.6.1 的 CNRI 许可协议: 用于 PYTHON 1 6 1 的 CNRI 许可协议.
* 用于 PYTHON 0.9.0 至 1.2 的 CWI 许可协议: 用于 PYTHON 0 9 0 至 1 2 的 CWI 许可协议.
* ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3.8.12 DOCUMENTATION: ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3 8 12 DOCUMENTATION.


File: python.info,  Node: 用于 PYTHON 3 8 12 的 PSF 许可协议,  Next: 用于 PYTHON 2 0 的 BEOPEN COM 许可协议,  Up: 获取或以其他方式使用 Python 的条款和条件

16.2.1 用于 PYTHON 3.8.12 的 PSF 许可协议
-----------------------------------------

     1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
        the Individual or Organization ("Licensee") accessing and otherwise using Python
        3.8.12 software in source or binary form and its associated documentation.

     2. Subject to the terms and conditions of this License Agreement, PSF hereby
        grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
        analyze, test, perform and/or display publicly, prepare derivative works,
        distribute, and otherwise use Python 3.8.12 alone or in any derivative
        version, provided, however, that PSF's License Agreement and PSF's notice of
        copyright, i.e., "Copyright © 2001-2021 Python Software Foundation; All Rights
        Reserved" are retained in Python 3.8.12 alone or in any derivative version
        prepared by Licensee.

     3. In the event Licensee prepares a derivative work that is based on or
        incorporates Python 3.8.12 or any part thereof, and wants to make the
        derivative work available to others as provided herein, then Licensee hereby
        agrees to include in any such work a brief summary of the changes made to Python
        3.8.12.

     4. PSF is making Python 3.8.12 available to Licensee on an "AS IS" basis.
        PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
        EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
        WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
        USE OF PYTHON 3.8.12 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

     5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.8.12
        FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
        MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.8.12, OR ANY DERIVATIVE
        THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

     6. This License Agreement will automatically terminate upon a material breach of
        its terms and conditions.

     7. Nothing in this License Agreement shall be deemed to create any relationship
        of agency, partnership, or joint venture between PSF and Licensee.  This License
        Agreement does not grant permission to use PSF trademarks or trade name in a
        trademark sense to endorse or promote products or services of Licensee, or any
        third party.

     8. By copying, installing or otherwise using Python 3.8.12, Licensee agrees
        to be bound by the terms and conditions of this License Agreement.


File: python.info,  Node: 用于 PYTHON 2 0 的 BEOPEN COM 许可协议,  Next: 用于 PYTHON 1 6 1 的 CNRI 许可协议,  Prev: 用于 PYTHON 3 8 12 的 PSF 许可协议,  Up: 获取或以其他方式使用 Python 的条款和条件

16.2.2 用于 PYTHON 2.0 的 BEOPEN.COM 许可协议
---------------------------------------------

BEOPEN PYTHON 开源许可协议第 1 版

     1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at
        160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization
        ("Licensee") accessing and otherwise using this software in source or binary
        form and its associated documentation ("the Software").

     2. Subject to the terms and conditions of this BeOpen Python License Agreement,
        BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license
        to reproduce, analyze, test, perform and/or display publicly, prepare derivative
        works, distribute, and otherwise use the Software alone or in any derivative
        version, provided, however, that the BeOpen Python License is retained in the
        Software, alone or in any derivative version prepared by Licensee.

     3. BeOpen is making the Software available to Licensee on an "AS IS" basis.
        BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
        EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
        WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
        USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

     4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
        ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
        MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF
        ADVISED OF THE POSSIBILITY THEREOF.

     5. This License Agreement will automatically terminate upon a material breach of
        its terms and conditions.

     6. This License Agreement shall be governed by and interpreted in all respects
        by the law of the State of California, excluding conflict of law provisions.
        Nothing in this License Agreement shall be deemed to create any relationship of
        agency, partnership, or joint venture between BeOpen and Licensee.  This License
        Agreement does not grant permission to use BeOpen trademarks or trade names in a
        trademark sense to endorse or promote products or services of Licensee, or any
        third party.  As an exception, the "BeOpen Python" logos available at
        ‘http://www.pythonlabs.com/logos.html’ may be used according to the permissions
        granted on that web page.

     7. By copying, installing or otherwise using the software, Licensee agrees to be
        bound by the terms and conditions of this License Agreement.


File: python.info,  Node: 用于 PYTHON 1 6 1 的 CNRI 许可协议,  Next: 用于 PYTHON 0 9 0 至 1 2 的 CWI 许可协议,  Prev: 用于 PYTHON 2 0 的 BEOPEN COM 许可协议,  Up: 获取或以其他方式使用 Python 的条款和条件

16.2.3 用于 PYTHON 1.6.1 的 CNRI 许可协议
-----------------------------------------

     1. This LICENSE AGREEMENT is between the Corporation for National Research
        Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191
        ("CNRI"), and the Individual or Organization ("Licensee") accessing and
        otherwise using Python 1.6.1 software in source or binary form and its
        associated documentation.

     2. Subject to the terms and conditions of this License Agreement, CNRI hereby
        grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
        analyze, test, perform and/or display publicly, prepare derivative works,
        distribute, and otherwise use Python 1.6.1 alone or in any derivative version,
        provided, however, that CNRI's License Agreement and CNRI's notice of copyright,
        i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All
        Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version
        prepared by Licensee.  Alternately, in lieu of CNRI's License Agreement,
        Licensee may substitute the following text (omitting the quotes): "Python 1.6.1
        is made available subject to the terms and conditions in CNRI's License
        Agreement.  This Agreement together with Python 1.6.1 may be located on the
        Internet using the following unique, persistent identifier (known as a handle):
        1895.22/1013.  This Agreement may also be obtained from a proxy server on the
        Internet using the following URL: ‘http://hdl.handle.net/1895.22/1013’."

     3. In the event Licensee prepares a derivative work that is based on or
        incorporates Python 1.6.1 or any part thereof, and wants to make the derivative
        work available to others as provided herein, then Licensee hereby agrees to
        include in any such work a brief summary of the changes made to Python 1.6.1.

     4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis.  CNRI
        MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF EXAMPLE,
        BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
        OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
        PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

     5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR
        ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
        MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE
        THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

     6. This License Agreement will automatically terminate upon a material breach of
        its terms and conditions.

     7. This License Agreement shall be governed by the federal intellectual property
        law of the United States, including without limitation the federal copyright
        law, and, to the extent such U.S. federal law does not apply, by the law of the
        Commonwealth of Virginia, excluding Virginia's conflict of law provisions.
        Notwithstanding the foregoing, with regard to derivative works based on Python
        1.6.1 that incorporate non-separable material that was previously distributed
        under the GNU General Public License (GPL), the law of the Commonwealth of
        Virginia shall govern this License Agreement only as to issues arising under or
        with respect to Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in
        this License Agreement shall be deemed to create any relationship of agency,
        partnership, or joint venture between CNRI and Licensee.  This License Agreement
        does not grant permission to use CNRI trademarks or trade name in a trademark
        sense to endorse or promote products or services of Licensee, or any third
        party.

     8. By clicking on the "ACCEPT" button where indicated, or by copying, installing
        or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and
        conditions of this License Agreement.


File: python.info,  Node: 用于 PYTHON 0 9 0 至 1 2 的 CWI 许可协议,  Next: ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3 8 12 DOCUMENTATION,  Prev: 用于 PYTHON 1 6 1 的 CNRI 许可协议,  Up: 获取或以其他方式使用 Python 的条款和条件

16.2.4 用于 PYTHON 0.9.0 至 1.2 的 CWI 许可协议
-----------------------------------------------

     Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The
     Netherlands.  All rights reserved.

     Permission to use, copy, modify, and distribute this software and its
     documentation for any purpose and without fee is hereby granted, provided that
     the above copyright notice appear in all copies and that both that copyright
     notice and this permission notice appear in supporting documentation, and that
     the name of Stichting Mathematisch Centrum or CWI not be used in advertising or
     publicity pertaining to distribution of the software without specific, written
     prior permission.

     STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
     SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
     EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT
     OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
     DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
     ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
     SOFTWARE.


File: python.info,  Node: ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3 8 12 DOCUMENTATION,  Prev: 用于 PYTHON 0 9 0 至 1 2 的 CWI 许可协议,  Up: 获取或以其他方式使用 Python 的条款和条件

16.2.5 ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3.8.12 DOCUMENTATION
--------------------------------------------------------------------------

     Permission to use, copy, modify, and/or distribute this software for any
     purpose with or without fee is hereby granted.

     THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
     REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
     AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
     INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
     LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
     OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
     PERFORMANCE OF THIS SOFTWARE.


File: python.info,  Node: 收录软件的许可与鸣谢,  Prev: 获取或以其他方式使用 Python 的条款和条件,  Up: 历史和许可证

16.3 收录软件的许可与鸣谢
=========================

本节是Python发行版中收录的第三方软件的许可和致谢清单，该清单是不完整且不
断增长的。

* Menu:

* Mersenne Twister::
* 套接字: 套接字<2>.
* 异步套接字服务::
* Cookie 管理::
* 执行追踪::
* UUencode 与 UUdecode 函数::
* XML 远程过程调用::
* test_epoll::
* Select kqueue::
* SipHash24::
* strtod 和 dtoa::
* OpenSSL::
* expat::
* libffi::
* zlib: zlib<3>.
* cfuhash::
* libmpdec::
* W3C C14N 测试套件::


File: python.info,  Node: Mersenne Twister,  Next: 套接字<2>,  Up: 收录软件的许可与鸣谢

16.3.1 Mersenne Twister
-----------------------

‘_random’ 模块包含基于
‘http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html’
下载的代码。以下是原始代码的完整注释（声明）：

     A C-program for MT19937, with initialization improved 2002/1/26.
     Coded by Takuji Nishimura and Makoto Matsumoto.

     Before using, initialize the state by using init_genrand(seed)
     or init_by_array(init_key, key_length).

     Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
     All rights reserved.

     Redistribution and use in source and binary forms, with or without
     modification, are permitted provided that the following conditions
     are met:

      1. Redistributions of source code must retain the above copyright
         notice, this list of conditions and the following disclaimer.

      2. Redistributions in binary form must reproduce the above copyright
         notice, this list of conditions and the following disclaimer in the
         documentation and/or other materials provided with the distribution.

      3. The names of its contributors may not be used to endorse or promote
         products derived from this software without specific prior written
         permission.

     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
     LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
     NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
     SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


     Any feedback is very welcome.
     http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
     email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)


File: python.info,  Node: 套接字<2>,  Next: 异步套接字服务,  Prev: Mersenne Twister,  Up: 收录软件的许可与鸣谢

16.3.2 套接字
-------------

*note socket: f0. 模块使用 ‘getaddrinfo()’ 和 ‘getnameinfo()’ 函数，这些
函数源代码在WIDE项目（‘http://www.wide.ad.jp/’）的单独源文件中。

     Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
     All rights reserved.

     Redistribution and use in source and binary forms, with or without
     modification, are permitted provided that the following conditions
     are met:
     1. Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
     2. Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
     3. Neither the name of the project nor the names of its contributors
        may be used to endorse or promote products derived from this software
        without specific prior written permission.

     THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     SUCH DAMAGE.


File: python.info,  Node: 异步套接字服务,  Next: Cookie 管理,  Prev: 套接字<2>,  Up: 收录软件的许可与鸣谢

16.3.3 异步套接字服务
---------------------

*note asynchat: 9. 和 *note asyncore: b. 模块包含以下声明:

     Copyright 1996 by Sam Rushing

                             All Rights Reserved

     Permission to use, copy, modify, and distribute this software and
     its documentation for any purpose and without fee is hereby
     granted, provided that the above copyright notice appear in all
     copies and that both that copyright notice and this permission
     notice appear in supporting documentation, and that the name of Sam
     Rushing not be used in advertising or publicity pertaining to
     distribution of the software without specific, written prior
     permission.

     SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
     INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
     NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
     CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
     OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
     NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
     CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


File: python.info,  Node: Cookie 管理,  Next: 执行追踪,  Prev: 异步套接字服务,  Up: 收录软件的许可与鸣谢

16.3.4 Cookie 管理
------------------

*note http.cookies: 96. 模块包含以下声明:

     Copyright 2000 by Timothy O'Malley <timo@alum.mit.edu>

                    All Rights Reserved

     Permission to use, copy, modify, and distribute this software
     and its documentation for any purpose and without fee is hereby
     granted, provided that the above copyright notice appear in all
     copies and that both that copyright notice and this permission
     notice appear in supporting documentation, and that the name of
     Timothy O'Malley  not be used in advertising or publicity
     pertaining to distribution of the software without specific, written
     prior permission.

     Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
     SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
     AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR
     ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
     WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
     ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
     PERFORMANCE OF THIS SOFTWARE.


File: python.info,  Node: 执行追踪,  Next: UUencode 与 UUdecode 函数,  Prev: Cookie 管理,  Up: 收录软件的许可与鸣谢

16.3.5 执行追踪
---------------

*note trace: 113. 模块包含以下声明:

     portions copyright 2001, Autonomous Zones Industries, Inc., all rights...
     err...  reserved and offered to the public under the terms of the
     Python 2.2 license.
     Author: Zooko O'Whielacronx
     http://zooko.com/
     mailto:zooko@zooko.com

     Copyright 2000, Mojam Media, Inc., all rights reserved.
     Author: Skip Montanaro

     Copyright 1999, Bioreason, Inc., all rights reserved.
     Author: Andrew Dalke

     Copyright 1995-1997, Automatrix, Inc., all rights reserved.
     Author: Skip Montanaro

     Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.


     Permission to use, copy, modify, and distribute this Python software and
     its associated documentation for any purpose without fee is hereby
     granted, provided that the above copyright notice appears in all copies,
     and that both that copyright notice and this permission notice appear in
     supporting documentation, and that the name of neither Automatrix,
     Bioreason or Mojam Media be used in advertising or publicity pertaining to
     distribution of the software without specific, written prior permission.


File: python.info,  Node: UUencode 与 UUdecode 函数,  Next: XML 远程过程调用,  Prev: 执行追踪,  Up: 收录软件的许可与鸣谢

16.3.6 UUencode 与 UUdecode 函数
--------------------------------

*note uu: 124. 模块包含以下声明:

     Copyright 1994 by Lance Ellinghouse
     Cathedral City, California Republic, United States of America.
                            All Rights Reserved
     Permission to use, copy, modify, and distribute this software and its
     documentation for any purpose and without fee is hereby granted,
     provided that the above copyright notice appear in all copies and that
     both that copyright notice and this permission notice appear in
     supporting documentation, and that the name of Lance Ellinghouse
     not be used in advertising or publicity pertaining to distribution
     of the software without specific, written prior permission.
     LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
     THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
     FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE
     FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
     OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

     Modified by Jack Jansen, CWI, July 1995:
     - Use binascii module to do the actual line-by-line conversion
       between ascii and binary. This results in a 1000-fold speedup. The C
       version is still 5 times faster, though.
     - Arguments more compliant with Python standard


File: python.info,  Node: XML 远程过程调用,  Next: test_epoll,  Prev: UUencode 与 UUdecode 函数,  Up: 收录软件的许可与鸣谢

16.3.7 XML 远程过程调用
-----------------------

*note xmlrpc.client: 140. 模块包含以下声明:

         The XML-RPC client interface is

     Copyright (c) 1999-2002 by Secret Labs AB
     Copyright (c) 1999-2002 by Fredrik Lundh

     By obtaining, using, and/or copying this software and/or its
     associated documentation, you agree that you have read, understood,
     and will comply with the following terms and conditions:

     Permission to use, copy, modify, and distribute this software and
     its associated documentation for any purpose and without fee is
     hereby granted, provided that the above copyright notice appears in
     all copies, and that both that copyright notice and this permission
     notice appear in supporting documentation, and that the name of
     Secret Labs AB or the author not be used in advertising or publicity
     pertaining to distribution of the software without specific, written
     prior permission.

     SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
     TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
     ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
     BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
     DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
     WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
     ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
     OF THIS SOFTWARE.


File: python.info,  Node: test_epoll,  Next: Select kqueue,  Prev: XML 远程过程调用,  Up: 收录软件的许可与鸣谢

16.3.8 test_epoll
-----------------

‘test_epoll’ 模块包含以下声明:

     Copyright (c) 2001-2006 Twisted Matrix Laboratories.

     Permission is hereby granted, free of charge, to any person obtaining
     a copy of this software and associated documentation files (the
     "Software"), to deal in the Software without restriction, including
     without limitation the rights to use, copy, modify, merge, publish,
     distribute, sublicense, and/or sell copies of the Software, and to
     permit persons to whom the Software is furnished to do so, subject to
     the following conditions:

     The above copyright notice and this permission notice shall be
     included in all copies or substantial portions of the Software.

     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
     EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
     MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
     NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
     LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
     OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
     WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


File: python.info,  Node: Select kqueue,  Next: SipHash24,  Prev: test_epoll,  Up: 收录软件的许可与鸣谢

16.3.9 Select kqueue
--------------------

*note select: e6. 模块关于 kqueue 的接口包含以下声明:

     Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
     All rights reserved.

     Redistribution and use in source and binary forms, with or without
     modification, are permitted provided that the following conditions
     are met:
     1. Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
     2. Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.

     THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     SUCH DAMAGE.


File: python.info,  Node: SipHash24,  Next: strtod 和 dtoa,  Prev: Select kqueue,  Up: 收录软件的许可与鸣谢

16.3.10 SipHash24
-----------------

‘Python/pyhash.c’ 文件包含 Marek Majkowski’ 对 Dan Bernstein 的SipHash24
算法的实现。它包含以下声明:

     <MIT License>
     Copyright (c) 2013  Marek Majkowski <marek@popcount.org>

     Permission is hereby granted, free of charge, to any person obtaining a copy
     of this software and associated documentation files (the "Software"), to deal
     in the Software without restriction, including without limitation the rights
     to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     copies of the Software, and to permit persons to whom the Software is
     furnished to do so, subject to the following conditions:

     The above copyright notice and this permission notice shall be included in
     all copies or substantial portions of the Software.
     </MIT License>

     Original location:
        https://github.com/majek/csiphash/

     Solution inspired by code from:
        Samuel Neves (supercop/crypto_auth/siphash24/little)
        djb (supercop/crypto_auth/siphash24/little2)
        Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c)


File: python.info,  Node: strtod 和 dtoa,  Next: OpenSSL,  Prev: SipHash24,  Up: 收录软件的许可与鸣谢

16.3.11 strtod 和 dtoa
----------------------

‘Python/dtoa.c’ 文件提供了C语言的 dtoa 和 strtod 函数，用于将C语言的 双
精度型和字符串进行转换，由David M. Gay的同名文件派生而来，该文件当前可从
http://www.netlib.org/fp/ 下载。2009年3月16日检索到的原始文件包含以下版
权和许可声明:

     /****************************************************************
      *
      * The author of this software is David M. Gay.
      *
      * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
      *
      * Permission to use, copy, modify, and distribute this software for any
      * purpose without fee is hereby granted, provided that this entire notice
      * is included in all copies of any software which is or includes a copy
      * or modification of this software and in all copies of the supporting
      * documentation for such software.
      *
      * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
      * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
      * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
      * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
      *
      ***************************************************************/


File: python.info,  Node: OpenSSL,  Next: expat,  Prev: strtod 和 dtoa,  Up: 收录软件的许可与鸣谢

16.3.12 OpenSSL
---------------

如果操作系统可用，则 *note hashlib: 8d, *note posix: d2, *note ssl: f4,
*note crypt: 29. 模块使用OpenSSL库来提高性能。此外，适用于Python的
Windows和Mac OS X安装程序可能包括OpenSSL库的拷贝，所以在此处也列出了
OpenSSL许可证的拷贝:

      LICENSE ISSUES
      ==============

      The OpenSSL toolkit stays under a dual license, i.e. both the conditions of
      the OpenSSL License and the original SSLeay license apply to the toolkit.
      See below for the actual license texts. Actually both licenses are BSD-style
      Open Source licenses. In case of any license issues related to OpenSSL
      please contact openssl-core@openssl.org.

      OpenSSL License
      ---------------

        /* ====================================================================
         * Copyright (c) 1998-2008 The OpenSSL Project.  All rights reserved.
         *
         * Redistribution and use in source and binary forms, with or without
         * modification, are permitted provided that the following conditions
         * are met:
         *
         * 1. Redistributions of source code must retain the above copyright
         *    notice, this list of conditions and the following disclaimer.
         *
         * 2. Redistributions in binary form must reproduce the above copyright
         *    notice, this list of conditions and the following disclaimer in
         *    the documentation and/or other materials provided with the
         *    distribution.
         *
         * 3. All advertising materials mentioning features or use of this
         *    software must display the following acknowledgment:
         *    "This product includes software developed by the OpenSSL Project
         *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
         *
         * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
         *    endorse or promote products derived from this software without
         *    prior written permission. For written permission, please contact
         *    openssl-core@openssl.org.
         *
         * 5. Products derived from this software may not be called "OpenSSL"
         *    nor may "OpenSSL" appear in their names without prior written
         *    permission of the OpenSSL Project.
         *
         * 6. Redistributions of any form whatsoever must retain the following
         *    acknowledgment:
         *    "This product includes software developed by the OpenSSL Project
         *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
         *
         * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
         * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
         * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
         * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
         * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
         * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
         * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
         * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
         * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
         * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
         * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
         * OF THE POSSIBILITY OF SUCH DAMAGE.
         * ====================================================================
         *
         * This product includes cryptographic software written by Eric Young
         * (eay@cryptsoft.com).  This product includes software written by Tim
         * Hudson (tjh@cryptsoft.com).
         *
         */

     Original SSLeay License
     -----------------------

        /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
         * All rights reserved.
         *
         * This package is an SSL implementation written
         * by Eric Young (eay@cryptsoft.com).
         * The implementation was written so as to conform with Netscapes SSL.
         *
         * This library is free for commercial and non-commercial use as long as
         * the following conditions are aheared to.  The following conditions
         * apply to all code found in this distribution, be it the RC4, RSA,
         * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
         * included with this distribution is covered by the same copyright terms
         * except that the holder is Tim Hudson (tjh@cryptsoft.com).
         *
         * Copyright remains Eric Young's, and as such any Copyright notices in
         * the code are not to be removed.
         * If this package is used in a product, Eric Young should be given attribution
         * as the author of the parts of the library used.
         * This can be in the form of a textual message at program startup or
         * in documentation (online or textual) provided with the package.
         *
         * Redistribution and use in source and binary forms, with or without
         * modification, are permitted provided that the following conditions
         * are met:
         * 1. Redistributions of source code must retain the copyright
         *    notice, this list of conditions and the following disclaimer.
         * 2. Redistributions in binary form must reproduce the above copyright
         *    notice, this list of conditions and the following disclaimer in the
         *    documentation and/or other materials provided with the distribution.
         * 3. All advertising materials mentioning features or use of this software
         *    must display the following acknowledgement:
         *    "This product includes cryptographic software written by
         *     Eric Young (eay@cryptsoft.com)"
         *    The word 'cryptographic' can be left out if the rouines from the library
         *    being used are not cryptographic related :-).
         * 4. If you include any Windows specific code (or a derivative thereof) from
         *    the apps directory (application code) you must include an acknowledgement:
         *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
         *
         * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
         * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
         * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
         * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
         * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
         * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
         * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
         * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
         * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
         * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
         * SUCH DAMAGE.
         *
         * The licence and distribution terms for any publically available version or
         * derivative of this code cannot be changed.  i.e. this code cannot simply be
         * copied and put under another distribution licence
         * [including the GNU Public Licence.]
         */


File: python.info,  Node: expat,  Next: libffi,  Prev: OpenSSL,  Up: 收录软件的许可与鸣谢

16.3.13 expat
-------------

除非使用 ‘--with-system-expat’ 配置了构建，否则 ‘pyexpat’ 扩展都是用包含
expat源的拷贝构建的:

     Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
                                    and Clark Cooper

     Permission is hereby granted, free of charge, to any person obtaining
     a copy of this software and associated documentation files (the
     "Software"), to deal in the Software without restriction, including
     without limitation the rights to use, copy, modify, merge, publish,
     distribute, sublicense, and/or sell copies of the Software, and to
     permit persons to whom the Software is furnished to do so, subject to
     the following conditions:

     The above copyright notice and this permission notice shall be included
     in all copies or substantial portions of the Software.

     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
     EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
     MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
     IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
     CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
     TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
     SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


File: python.info,  Node: libffi,  Next: zlib<3>,  Prev: expat,  Up: 收录软件的许可与鸣谢

16.3.14 libffi
--------------

除非使用 ‘--with-system-libffi’ 配置了构建，否则 ‘_ctypes’ 扩展都是包含
libffi源的拷贝构建的:

     Copyright (c) 1996-2008  Red Hat, Inc and others.

     Permission is hereby granted, free of charge, to any person obtaining
     a copy of this software and associated documentation files (the
     ``Software''), to deal in the Software without restriction, including
     without limitation the rights to use, copy, modify, merge, publish,
     distribute, sublicense, and/or sell copies of the Software, and to
     permit persons to whom the Software is furnished to do so, subject to
     the following conditions:

     The above copyright notice and this permission notice shall be included
     in all copies or substantial portions of the Software.

     THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
     EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
     MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
     NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
     HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
     WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
     DEALINGS IN THE SOFTWARE.


File: python.info,  Node: zlib<3>,  Next: cfuhash,  Prev: libffi,  Up: 收录软件的许可与鸣谢

16.3.15 zlib
------------

如果系统上找到的zlib版本太旧而无法用于构建，则使用包含 zlib源代码的拷贝
来构建 *note zlib: 145. 扩展:

     Copyright (C) 1995-2011 Jean-loup Gailly and Mark Adler

     This software is provided 'as-is', without any express or implied
     warranty.  In no event will the authors be held liable for any damages
     arising from the use of this software.

     Permission is granted to anyone to use this software for any purpose,
     including commercial applications, and to alter it and redistribute it
     freely, subject to the following restrictions:

     1. The origin of this software must not be misrepresented; you must not
        claim that you wrote the original software. If you use this software
        in a product, an acknowledgment in the product documentation would be
        appreciated but is not required.

     2. Altered source versions must be plainly marked as such, and must not be
        misrepresented as being the original software.

     3. This notice may not be removed or altered from any source distribution.

     Jean-loup Gailly        Mark Adler
     jloup@gzip.org          madler@alumni.caltech.edu


File: python.info,  Node: cfuhash,  Next: libmpdec,  Prev: zlib<3>,  Up: 收录软件的许可与鸣谢

16.3.16 cfuhash
---------------

*note tracemalloc: 115. 使用的哈希表的实现基于 cfuhash项目:

     Copyright (c) 2005 Don Owens
     All rights reserved.

     This code is released under the BSD license:

     Redistribution and use in source and binary forms, with or without
     modification, are permitted provided that the following conditions
     are met:

       * Redistributions of source code must retain the above copyright
         notice, this list of conditions and the following disclaimer.

       * Redistributions in binary form must reproduce the above
         copyright notice, this list of conditions and the following
         disclaimer in the documentation and/or other materials provided
         with the distribution.

       * Neither the name of the author nor the names of its
         contributors may be used to endorse or promote products derived
         from this software without specific prior written permission.

     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
     FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
     COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
     (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
     SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
     STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
     OF THE POSSIBILITY OF SUCH DAMAGE.


File: python.info,  Node: libmpdec,  Next: W3C C14N 测试套件,  Prev: cfuhash,  Up: 收录软件的许可与鸣谢

16.3.17 libmpdec
----------------

除非使用 ‘--with-system-libmpdec’ 配置了构建，否则 ‘_decimal’ 模块都是用
包含 libmpdec 库的拷贝构建的。

     Copyright (c) 2008-2016 Stefan Krah. All rights reserved.

     Redistribution and use in source and binary forms, with or without
     modification, are permitted provided that the following conditions
     are met:

     1. Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.

     2. Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.

     THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
     ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     SUCH DAMAGE.


File: python.info,  Node: W3C C14N 测试套件,  Prev: libmpdec,  Up: 收录软件的许可与鸣谢

16.3.18 W3C C14N 测试套件
-------------------------

*note test: 106. 包（lib/test/xmltestdata/c14n-20/）中的 C14N2.0测试套件
来源于W3C网站 ‘https://www.w3.org/TR/xml-c14n2-testcases/’ ，并根据 BSD许
可证（三条款版）发行：

     Copyright (c) 2013 W3C(R) (MIT, ERCIM, Keio, Beihang), All Rights
     Reserved.

     Redistribution and use in source and binary forms, with or without
     modification, are permitted provided that the following conditions
     are met:

        * Redistributions of works must retain the original copyright
          notice, this list of conditions and the following disclaimer.

        * Redistributions in binary form must reproduce the original
          copyright notice, this list of conditions and the following
          disclaimer in the documentation and/or other materials
          provided with the distribution.

        * Neither the name of the W3C nor the names of its contributors
          may be used to endorse or promote products derived from this
          work without specific prior written permission.

     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
     FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
     COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
     (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
     SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
     STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
     OF THE POSSIBILITY OF SUCH DAMAGE.


File: python.info,  Node: 分发 Python 模块（遗留版本）,  Next: 安装Python模块（旧版）,  Prev: 历史和许可证,  Up: Top

17 分发 Python 模块（遗留版本）
*******************************


作者: Greg Ward ， Anthony Baxter


电子邮箱: <distutils-sig@python.org>

参见
....

*note 分发 Python 模块: 7ff.

     最新的模块分发文档

     注解: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

     注解: 本指南仅介绍构建和分发扩展的基本工具，这些扩展是作为此
     Python版本的一部分提供的。 第三方工具提供更易于使用和更安全的替代方
     案。有关详细信息，请参阅 Python 打包用户指南中的 快速推荐部分(1) 。

本文档从模块开发人员的角度描述了 Python Distribution Utilities
("Distutils")。 描述了 ‘setuptools’ 构建所依赖的下层功能，以允许 Python
开发者方便地为更广泛的受众编写 Python 模块和扩展。

* Menu:

* Distutils 模块介绍::
* 编写安装脚本::
* 编写设置脚本的配置文件::
* Creating a Source Distribution::
* 创建构建分布::
* Distutils 示例::
* 扩展 Distutils::
* 命令参考::
* API参考引用::

   ---------- Footnotes ----------

   (1) https://packaging.python.org/guides/tool-recommendations/


File: python.info,  Node: Distutils 模块介绍,  Next: 编写安装脚本,  Up: 分发 Python 模块（遗留版本）

17.1 Distutils 模块介绍
=======================

     注解: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

本文档介绍了使用 Distutils 模块分发你的 Python 模块，主要是针对开发者/分
发者的使用的——如果你想了解如何安装 Python 模块，你应该参考这个章节：
*note 安装Python模块（旧版）: 800.。

* Menu:

* 概念和术语::
* 一个简单的例子: 一个简单的例子<3>.
* 通用的 Python 术语::
* Distutils 特定的术语::


File: python.info,  Node: 概念和术语,  Next: 一个简单的例子<3>,  Up: Distutils 模块介绍

17.1.1 概念和术语
-----------------

Using the Distutils is quite simple, both for module developers and for
users/administrators installing third-party modules.  As a developer,
your responsibilities (apart from writing solid, well-documented and
well-tested code, of course!)  are:

   * 编写一个设置脚本 (‘setup.py’ by convention)

   * (可选)编写设置脚本的配置文件

   * 创建源码的发行版

   * （可选）创建一个或多个编译好（二进制）的发行版

每个这些任务均已在此文档覆盖.

Not all module developers have access to a multitude of platforms, so
it’s not always feasible to expect them to create a multitude of built
distributions.  It is hoped that a class of intermediaries, called
`packagers', will arise to address this need.  Packagers will take
source distributions released by module developers, build them on one or
more platforms, and release the resulting built distributions.  Thus,
users on the most popular platforms will be able to install most popular
Python module distributions in the most natural way for their platform,
without having to run a single setup script or compile a line of code.


File: python.info,  Node: 一个简单的例子<3>,  Next: 通用的 Python 术语,  Prev: 概念和术语,  Up: Distutils 模块介绍

17.1.2 一个简单的例子
---------------------

The setup script is usually quite simple, although since it’s written in
Python, there are no arbitrary limits to what you can do with it, though
you should be careful about putting arbitrarily expensive operations in
your setup script.  Unlike, say, Autoconf-style configure scripts, the
setup script may be run multiple times in the course of building and
installing your module distribution.

If all you want to do is distribute a module called ‘foo’, contained in
a file ‘foo.py’, then your setup script can be as simple as this:

     from distutils.core import setup
     setup(name='foo',
           version='1.0',
           py_modules=['foo'],
           )

一些观察:

   * most information that you supply to the Distutils is supplied as
     keyword arguments to the ‘setup()’ function

   * those keyword arguments fall into two categories: package metadata
     (name, version number) and information about what’s in the package
     (a list of pure Python modules, in this case)

   * modules are specified by module name, not filename (the same will
     hold true for packages and extensions)

   * it’s recommended that you supply a little more metadata, in
     particular your name, email address and a URL for the project (see
     section *note 编写安装脚本: 4361. for an example)

To create a source distribution for this module, you would create a
setup script, ‘setup.py’, containing the above code, and run this
command from a terminal:

     python setup.py sdist

Windows用户, 打开命令行窗口 (Start ‣ Accessories) 并且更改命令为:

     setup.py sdist

‘sdist’ 将创建一个归档文件（例如在 Unix 中为 tarball，在 Windows 中为
ZIP 文件），其中包含你的配置脚本 ‘setup.py’ 以及你的模块 ‘foo.py’。 此归
档文件将被命名为 ‘foo-1.0.tar.gz’ (或 ‘.zip’)，并将解包到目录 ‘foo-1.0’
当中。

If an end-user wishes to install your ‘foo’ module, all they have to do
is download ‘foo-1.0.tar.gz’ (or ‘.zip’), unpack it, and—from the
‘foo-1.0’ directory—run

     python setup.py install

which will ultimately copy ‘foo.py’ to the appropriate directory for
third-party modules in their Python installation.

This simple example demonstrates some fundamental concepts of the
Distutils.  First, both developers and installers have the same basic
user interface, i.e.  the setup script.  The difference is which
Distutils `commands' they use: the ‘sdist’ command is almost exclusively
for module developers, while ‘install’ is more often for installers
(although most developers will want to install their own code
occasionally).

If you want to make things really easy for your users, you can create
one or more built distributions for them.  For instance, if you are
running on a Windows machine, and want to make things easy for other
Windows users, you can create an executable installer (the most
appropriate type of built distribution for this platform) with the
‘bdist_wininst’ command.  For example:

     python setup.py bdist_wininst

will create an executable installer, ‘foo-1.0.win32.exe’, in the current
directory.

Other useful built distribution formats are RPM, implemented by the
‘bdist_rpm’ command, Solaris ‘pkgtool’ (‘bdist_pkgtool’), and HP-UX
‘swinstall’ (‘bdist_sdux’).  For example, the following command will
create an RPM file called ‘foo-1.0.noarch.rpm’:

     python setup.py bdist_rpm

(The ‘bdist_rpm’ command uses the ‘rpm’ executable, therefore this has
to be run on an RPM-based system such as Red Hat Linux, SuSE Linux, or
Mandrake Linux.)

You can find out what distribution formats are available at any time by
running

     python setup.py bdist --help-formats


File: python.info,  Node: 通用的 Python 术语,  Next: Distutils 特定的术语,  Prev: 一个简单的例子<3>,  Up: Distutils 模块介绍

17.1.3 通用的 Python 术语
-------------------------

If you’re reading this document, you probably have a good idea of what
modules, extensions, and so forth are.  Nevertheless, just to be sure
that everyone is operating from a common starting point, we offer the
following glossary of common Python terms:

module

     the basic unit of code reusability in Python: a block of code
     imported by some other code.  Three types of modules concern us
     here: pure Python modules, extension modules, and packages.

纯 Python 模块

     a module written in Python and contained in a single ‘.py’ file
     (and possibly associated ‘.pyc’ files).  Sometimes referred to as a
     "pure module."

extension module – 扩展模块

     a module written in the low-level language of the Python
     implementation: C/C++ for Python, Java for Jython.  Typically
     contained in a single dynamically loadable pre-compiled file, e.g.
     a shared object (‘.so’) file for Python extensions on Unix, a DLL
     (given the ‘.pyd’ extension) for Python extensions on Windows, or a
     Java class file for Jython extensions.  (Note that currently, the
     Distutils only handles C/C++ extensions for Python.)

package – 包

     a module that contains other modules; typically contained in a
     directory in the filesystem and distinguished from other
     directories by the presence of a file ‘__init__.py’.

root package

     the root of the hierarchy of packages.  (This isn’t really a
     package, since it doesn’t have an ‘__init__.py’ file.  But we have
     to call it something.)  The vast majority of the standard library
     is in the root package, as are many small, standalone third-party
     modules that don’t belong to a larger module collection.  Unlike
     regular packages, modules in the root package can be found in many
     directories: in fact, every directory listed in ‘sys.path’
     contributes modules to the root package.


File: python.info,  Node: Distutils 特定的术语,  Prev: 通用的 Python 术语,  Up: Distutils 模块介绍

17.1.4 Distutils 特定的术语
---------------------------

The following terms apply more specifically to the domain of
distributing Python modules using the Distutils:

module distribution

     a collection of Python modules distributed together as a single
     downloadable resource and meant to be installed `en masse'.
     Examples of some well-known module distributions are NumPy, SciPy,
     Pillow, or mxBase.  (This would be called a `package', except that
     term is already taken in the Python context: a single module
     distribution may contain zero, one, or many Python packages.)

pure module distribution

     a module distribution that contains only pure Python modules and
     packages.  Sometimes referred to as a "pure distribution."

non-pure module distribution

     a module distribution that contains at least one extension module.
     Sometimes referred to as a "non-pure distribution."

distribution root

     the top-level directory of your source tree (or source
     distribution); the directory where ‘setup.py’ exists.  Generally
     ‘setup.py’ will be run from this directory.


File: python.info,  Node: 编写安装脚本,  Next: 编写设置脚本的配置文件,  Prev: Distutils 模块介绍,  Up: 分发 Python 模块（遗留版本）

17.2 编写安装脚本
=================

     注解: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

The setup script is the centre of all activity in building,
distributing, and installing modules using the Distutils.  The main
purpose of the setup script is to describe your module distribution to
the Distutils, so that the various commands that operate on your modules
do the right thing.  As we saw in section *note 一个简单的例子: 4360.
above, the setup script consists mainly of a call to ‘setup()’, and most
information supplied to the Distutils by the module developer is
supplied as keyword arguments to ‘setup()’.

Here’s a slightly more involved example, which we’ll follow for the next
couple of sections: the Distutils’ own setup script.  (Keep in mind that
although the Distutils are included with Python 1.6 and later, they also
have an independent existence so that Python 1.5.2 users can use them to
install other module distributions.  The Distutils’ own setup script,
shown here, is used to install the package into Python 1.5.2.)

     #!/usr/bin/env python

     from distutils.core import setup

     setup(name='Distutils',
           version='1.0',
           description='Python Distribution Utilities',
           author='Greg Ward',
           author_email='gward@python.net',
           url='https://www.python.org/sigs/distutils-sig/',
           packages=['distutils', 'distutils.command'],
          )

There are only two differences between this and the trivial one-file
distribution presented in section *note 一个简单的例子: 4360.: more
metadata, and the specification of pure Python modules by package,
rather than by module.  This is important since the Distutils consist of
a couple of dozen modules split into (so far) two packages; an explicit
list of every module would be tedious to generate and difficult to
maintain.  For more information on the additional meta-data, see section
*note Additional meta-data: 4368.

Note that any pathnames (files or directories) supplied in the setup
script should be written using the Unix convention, i.e.
slash-separated.  The Distutils will take care of converting this
platform-neutral representation into whatever is appropriate on your
current platform before actually using the pathname.  This makes your
setup script portable across operating systems, which of course is one
of the major goals of the Distutils.  In this spirit, all pathnames in
this document are slash-separated.

This, of course, only applies to pathnames given to Distutils functions.
If you, for example, use standard Python functions such as *note
glob.glob(): 5cf. or *note os.listdir(): a49. to specify files, you
should be careful to write portable code instead of hardcoding path
separators:

     glob.glob(os.path.join('mydir', 'subdir', '*.html'))
     os.listdir(os.path.join('mydir', 'subdir'))

* Menu:

* Listing whole packages::
* Listing individual modules::
* Describing extension modules::
* Relationships between Distributions and Packages::
* Installing Scripts::
* Installing Package Data::
* Installing Additional Files::
* Additional meta-data::
* Debugging the setup script::


File: python.info,  Node: Listing whole packages,  Next: Listing individual modules,  Up: 编写安装脚本

17.2.1 Listing whole packages
-----------------------------

The ‘packages’ option tells the Distutils to process (build, distribute,
install, etc.)  all pure Python modules found in each package mentioned
in the ‘packages’ list.  In order to do this, of course, there has to be
a correspondence between package names and directories in the
filesystem.  The default correspondence is the most obvious one, i.e.
package *note distutils: 39. is found in the directory ‘distutils’
relative to the distribution root.  Thus, when you say ‘packages =
['foo']’ in your setup script, you are promising that the Distutils will
find a file ‘foo/__init__.py’ (which might be spelled differently on
your system, but you get the idea) relative to the directory where your
setup script lives.  If you break this promise, the Distutils will issue
a warning but still process the broken package anyway.

If you use a different convention to lay out your source directory,
that’s no problem: you just have to supply the ‘package_dir’ option to
tell the Distutils about your convention.  For example, say you keep all
Python source under ‘lib’, so that modules in the "root package" (i.e.,
not in any package at all) are in ‘lib’, modules in the ‘foo’ package
are in ‘lib/foo’, and so forth.  Then you would put

     package_dir = {'': 'lib'}

in your setup script.  The keys to this dictionary are package names,
and an empty package name stands for the root package.  The values are
directory names relative to your distribution root.  In this case, when
you say ‘packages = ['foo']’, you are promising that the file
‘lib/foo/__init__.py’ exists.

Another possible convention is to put the ‘foo’ package right in ‘lib’,
the ‘foo.bar’ package in ‘lib/bar’, etc.  This would be written in the
setup script as

     package_dir = {'foo': 'lib'}

A ‘package: dir’ entry in the ‘package_dir’ dictionary implicitly
applies to all packages below `package', so the ‘foo.bar’ case is
automatically handled here.  In this example, having ‘packages = ['foo',
'foo.bar']’ tells the Distutils to look for ‘lib/__init__.py’ and
‘lib/bar/__init__.py’.  (Keep in mind that although ‘package_dir’
applies recursively, you must explicitly list all packages in
‘packages’: the Distutils will `not' recursively scan your source tree
looking for any directory with an ‘__init__.py’ file.)


File: python.info,  Node: Listing individual modules,  Next: Describing extension modules,  Prev: Listing whole packages,  Up: 编写安装脚本

17.2.2 Listing individual modules
---------------------------------

For a small module distribution, you might prefer to list all modules
rather than listing packages—especially the case of a single module that
goes in the "root package" (i.e., no package at all).  This simplest
case was shown in section *note 一个简单的例子: 4360.; here is a
slightly more involved example:

     py_modules = ['mod1', 'pkg.mod2']

This describes two modules, one of them in the "root" package, the other
in the ‘pkg’ package.  Again, the default package/directory layout
implies that these two modules can be found in ‘mod1.py’ and
‘pkg/mod2.py’, and that ‘pkg/__init__.py’ exists as well.  And again,
you can override the package/directory correspondence using the
‘package_dir’ option.


File: python.info,  Node: Describing extension modules,  Next: Relationships between Distributions and Packages,  Prev: Listing individual modules,  Up: 编写安装脚本

17.2.3 Describing extension modules
-----------------------------------

Just as writing Python extension modules is a bit more complicated than
writing pure Python modules, describing them to the Distutils is a bit
more complicated.  Unlike pure modules, it’s not enough just to list
modules or packages and expect the Distutils to go out and find the
right files; you have to specify the extension name, source file(s), and
any compile/link requirements (include directories, libraries to link
with, etc.).

All of this is done through another keyword argument to ‘setup()’, the
‘ext_modules’ option.  ‘ext_modules’ is just a list of *note Extension:
436f. instances, each of which describes a single extension module.
Suppose your distribution includes a single extension, called ‘foo’ and
implemented by ‘foo.c’.  If no additional instructions to the
compiler/linker are needed, describing this extension is quite simple:

     Extension('foo', ['foo.c'])

The ‘Extension’ class can be imported from *note distutils.core: 54.
along with ‘setup()’.  Thus, the setup script for a module distribution
that contains only this one extension and nothing else might be:

     from distutils.core import setup, Extension
     setup(name='foo',
           version='1.0',
           ext_modules=[Extension('foo', ['foo.c'])],
           )

The ‘Extension’ class (actually, the underlying extension-building
machinery implemented by the ‘build_ext’ command) supports a great deal
of flexibility in describing Python extensions, which is explained in
the following sections.

* Menu:

* 扩展名和软件包::
* Extension source files::
* Preprocessor options::
* Library options::
* 其他选项: 其他选项<2>.


File: python.info,  Node: 扩展名和软件包,  Next: Extension source files,  Up: Describing extension modules

17.2.3.1 扩展名和软件包
.......................

The first argument to the *note Extension: 436f. constructor is always
the name of the extension, including any package names.  For example,

     Extension('foo', ['src/foo1.c', 'src/foo2.c'])

describes an extension that lives in the root package, while

     Extension('pkg.foo', ['src/foo1.c', 'src/foo2.c'])

describes the same extension in the ‘pkg’ package.  The source files and
resulting object code are identical in both cases; the only difference
is where in the filesystem (and therefore where in Python’s namespace
hierarchy) the resulting extension lives.

If you have a number of extensions all in the same package (or all under
the same base package), use the ‘ext_package’ keyword argument to
‘setup()’.  For example,

     setup(...,
           ext_package='pkg',
           ext_modules=[Extension('foo', ['foo.c']),
                        Extension('subpkg.bar', ['bar.c'])],
          )

will compile ‘foo.c’ to the extension ‘pkg.foo’, and ‘bar.c’ to
‘pkg.subpkg.bar’.


File: python.info,  Node: Extension source files,  Next: Preprocessor options,  Prev: 扩展名和软件包,  Up: Describing extension modules

17.2.3.2 Extension source files
...............................

The second argument to the *note Extension: 436f. constructor is a list
of source files.  Since the Distutils currently only support C, C++, and
Objective-C extensions, these are normally C/C++/Objective-C source
files.  (Be sure to use appropriate extensions to distinguish C++ source
files: ‘.cc’ and ‘.cpp’ seem to be recognized by both Unix and Windows
compilers.)

However, you can also include SWIG interface (‘.i’) files in the list;
the ‘build_ext’ command knows how to deal with SWIG extensions: it will
run SWIG on the interface file and compile the resulting C/C++ file into
your extension.

This warning notwithstanding, options to SWIG can be currently passed
like this:

     setup(...,
           ext_modules=[Extension('_foo', ['foo.i'],
                                  swig_opts=['-modern', '-I../include'])],
           py_modules=['foo'],
          )

Or on the commandline like this:

     > python setup.py build_ext --swig-opts="-modern -I../include"

On some platforms, you can include non-source files that are processed
by the compiler and included in your extension.  Currently, this just
means Windows message text (‘.mc’) files and resource definition (‘.rc’)
files for Visual C++.  These will be compiled to binary resource
(‘.res’) files and linked into the executable.


File: python.info,  Node: Preprocessor options,  Next: Library options,  Prev: Extension source files,  Up: Describing extension modules

17.2.3.3 Preprocessor options
.............................

Three optional arguments to *note Extension: 436f. will help if you need
to specify include directories to search or preprocessor macros to
define/undefine: ‘include_dirs’, ‘define_macros’, and ‘undef_macros’.

For example, if your extension requires header files in the ‘include’
directory under your distribution root, use the ‘include_dirs’ option:

     Extension('foo', ['foo.c'], include_dirs=['include'])

You can specify absolute directories there; if you know that your
extension will only be built on Unix systems with X11R6 installed to
‘/usr’, you can get away with

     Extension('foo', ['foo.c'], include_dirs=['/usr/include/X11'])

You should avoid this sort of non-portable usage if you plan to
distribute your code: it’s probably better to write C code like

     #include <X11/Xlib.h>

If you need to include header files from some other Python extension,
you can take advantage of the fact that header files are installed in a
consistent way by the Distutils ‘install_headers’ command.  For example,
the Numerical Python header files are installed (on a standard Unix
installation) to ‘/usr/local/include/python1.5/Numerical’.  (The exact
location will differ according to your platform and Python
installation.)  Since the Python include
directory—‘/usr/local/include/python1.5’ in this case—is always included
in the search path when building Python extensions, the best approach is
to write C code like

     #include <Numerical/arrayobject.h>

If you must put the ‘Numerical’ include directory right into your header
search path, though, you can find that directory using the Distutils
*note distutils.sysconfig: 62. module:

     from distutils.sysconfig import get_python_inc
     incdir = os.path.join(get_python_inc(plat_specific=1), 'Numerical')
     setup(...,
           Extension(..., include_dirs=[incdir]),
           )

Even though this is quite portable—it will work on any Python
installation, regardless of platform—it’s probably easier to just write
your C code in the sensible way.

You can define and undefine pre-processor macros with the
‘define_macros’ and ‘undef_macros’ options.  ‘define_macros’ takes a
list of ‘(name, value)’ tuples, where ‘name’ is the name of the macro to
define (a string) and ‘value’ is its value: either a string or ‘None’.
(Defining a macro ‘FOO’ to ‘None’ is the equivalent of a bare ‘#define
FOO’ in your C source: with most compilers, this sets ‘FOO’ to the
string ‘1’.)  ‘undef_macros’ is just a list of macros to undefine.

例如

     Extension(...,
               define_macros=[('NDEBUG', '1'),
                              ('HAVE_STRFTIME', None)],
               undef_macros=['HAVE_FOO', 'HAVE_BAR'])

is the equivalent of having this at the top of every C source file:

     #define NDEBUG 1
     #define HAVE_STRFTIME
     #undef HAVE_FOO
     #undef HAVE_BAR


File: python.info,  Node: Library options,  Next: 其他选项<2>,  Prev: Preprocessor options,  Up: Describing extension modules

17.2.3.4 Library options
........................

You can also specify the libraries to link against when building your
extension, and the directories to search for those libraries.  The
‘libraries’ option is a list of libraries to link against,
‘library_dirs’ is a list of directories to search for libraries at
link-time, and ‘runtime_library_dirs’ is a list of directories to search
for shared (dynamically loaded) libraries at run-time.

For example, if you need to link against libraries known to be in the
standard library search path on target systems

     Extension(...,
               libraries=['gdbm', 'readline'])

If you need to link with libraries in a non-standard location, you’ll
have to include the location in ‘library_dirs’:

     Extension(...,
               library_dirs=['/usr/X11R6/lib'],
               libraries=['X11', 'Xt'])

(Again, this sort of non-portable construct should be avoided if you
intend to distribute your code.)


File: python.info,  Node: 其他选项<2>,  Prev: Library options,  Up: Describing extension modules

17.2.3.5 其他选项
.................

There are still some other options which can be used to handle special
cases.

The ‘optional’ option is a boolean; if it is true, a build failure in
the extension will not abort the build process, but instead simply not
install the failing extension.

The ‘extra_objects’ option is a list of object files to be passed to the
linker.  These files must not have extensions, as the default extension
for the compiler is used.

‘extra_compile_args’ and ‘extra_link_args’ can be used to specify
additional command line options for the respective compiler and linker
command lines.

‘export_symbols’ is only useful on Windows.  It can contain a list of
symbols (functions or variables) to be exported.  This option is not
needed when building compiled extensions: Distutils will automatically
add ‘initmodule’ to the list of exported symbols.

The ‘depends’ option is a list of files that the extension depends on
(for example header files).  The build command will call the compiler on
the sources to rebuild extension if any on this files has been modified
since the previous build.


File: python.info,  Node: Relationships between Distributions and Packages,  Next: Installing Scripts,  Prev: Describing extension modules,  Up: 编写安装脚本

17.2.4 Relationships between Distributions and Packages
-------------------------------------------------------

A distribution may relate to packages in three specific ways:

  1. It can require packages or modules.

  2. It can provide packages or modules.

  3. It can obsolete packages or modules.

These relationships can be specified using keyword arguments to the
*note distutils.core.setup(): 3b7a. function.

Dependencies on other Python modules and packages can be specified by
supplying the `requires' keyword argument to ‘setup()’.  The value must
be a list of strings.  Each string specifies a package that is required,
and optionally what versions are sufficient.

To specify that any version of a module or package is required, the
string should consist entirely of the module or package name.  Examples
include ‘'mymodule'’ and ‘'xml.parsers.expat'’.

If specific versions are required, a sequence of qualifiers can be
supplied in parentheses.  Each qualifier may consist of a comparison
operator and a version number.  The accepted comparison operators are:

     <    >    ==
     <=   >=   !=

These can be combined by using multiple qualifiers separated by commas
(and optional whitespace).  In this case, all of the qualifiers must be
matched; a logical AND is used to combine the evaluations.

Let’s look at a bunch of examples:

Requires Expression           说明
                              
---------------------------------------------------------------------------------
                              
‘==1.0’                       Only version ‘1.0’ is compatible
                              
                              
‘>1.0, !=1.5.1, <2.0’         Any version after ‘1.0’ and before ‘2.0’ is
                              compatible, except ‘1.5.1’
                              

Now that we can specify dependencies, we also need to be able to specify
what we provide that other distributions can require.  This is done
using the `provides' keyword argument to ‘setup()’.  The value for this
keyword is a list of strings, each of which names a Python module or
package, and optionally identifies the version.  If the version is not
specified, it is assumed to match that of the distribution.

Some examples:

Provides Expression       说明
                          
-----------------------------------------------------------------------------
                          
‘mypkg’                   Provide ‘mypkg’, using the distribution version
                          
                          
‘mypkg (1.1)’             Provide ‘mypkg’ version 1.1, regardless of the
                          distribution version
                          

A package can declare that it obsoletes other packages using the
`obsoletes' keyword argument.  The value for this is similar to that of
the `requires' keyword: a list of strings giving module or package
specifiers.  Each specifier consists of a module or package name
optionally followed by one or more version qualifiers.  Version
qualifiers are given in parentheses after the module or package name.

The versions identified by the qualifiers are those that are obsoleted
by the distribution being described.  If no qualifiers are given, all
versions of the named module or package are understood to be obsoleted.


File: python.info,  Node: Installing Scripts,  Next: Installing Package Data,  Prev: Relationships between Distributions and Packages,  Up: 编写安装脚本

17.2.5 Installing Scripts
-------------------------

So far we have been dealing with pure and non-pure Python modules, which
are usually not run by themselves but imported by scripts.

Scripts are files containing Python source code, intended to be started
from the command line.  Scripts don’t require Distutils to do anything
very complicated.  The only clever feature is that if the first line of
the script starts with ‘#!’ and contains the word "python", the
Distutils will adjust the first line to refer to the current interpreter
location.  By default, it is replaced with the current interpreter
location.  The ‘--executable’ (or ‘-e’) option will allow the
interpreter path to be explicitly overridden.

The ‘scripts’ option simply is a list of files to be handled in this
way.  From the PyXML setup script:

     setup(...,
           scripts=['scripts/xmlproc_parse', 'scripts/xmlproc_val']
           )

在 3.1 版更改: All the scripts will also be added to the ‘MANIFEST’ file
if no template is provided.  See *note Specifying the files to
distribute: 3b7d.


File: python.info,  Node: Installing Package Data,  Next: Installing Additional Files,  Prev: Installing Scripts,  Up: 编写安装脚本

17.2.6 Installing Package Data
------------------------------

Often, additional files need to be installed into a package.  These
files are often data that’s closely related to the package’s
implementation, or text files containing documentation that might be of
interest to programmers using the package.  These files are called
`package data'.

Package data can be added to packages using the ‘package_data’ keyword
argument to the ‘setup()’ function.  The value must be a mapping from
package name to a list of relative path names that should be copied into
the package.  The paths are interpreted as relative to the directory
containing the package (information from the ‘package_dir’ mapping is
used if appropriate); that is, the files are expected to be part of the
package in the source directories.  They may contain glob patterns as
well.

The path names may contain directory portions; any necessary directories
will be created in the installation.

For example, if a package should contain a subdirectory with several
data files, the files can be arranged like this in the source tree:

     setup.py
     src/
         mypkg/
             __init__.py
             module.py
             data/
                 tables.dat
                 spoons.dat
                 forks.dat

The corresponding call to ‘setup()’ might be:

     setup(...,
           packages=['mypkg'],
           package_dir={'mypkg': 'src/mypkg'},
           package_data={'mypkg': ['data/*.dat']},
           )

在 3.1 版更改: All the files that match ‘package_data’ will be added to
the ‘MANIFEST’ file if no template is provided.  See *note Specifying
the files to distribute: 3b7d.


File: python.info,  Node: Installing Additional Files,  Next: Additional meta-data,  Prev: Installing Package Data,  Up: 编写安装脚本

17.2.7 Installing Additional Files
----------------------------------

The ‘data_files’ option can be used to specify additional files needed
by the module distribution: configuration files, message catalogs, data
files, anything which doesn’t fit in the previous categories.

‘data_files’ specifies a sequence of (`directory', `files') pairs in the
following way:

     setup(...,
           data_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']),
                       ('config', ['cfg/data.cfg'])],
          )

Each (`directory', `files') pair in the sequence specifies the
installation directory and the files to install there.

Each file name in `files' is interpreted relative to the ‘setup.py’
script at the top of the package source distribution.  Note that you can
specify the directory where the data files will be installed, but you
cannot rename the data files themselves.

The `directory' should be a relative path.  It is interpreted relative
to the installation prefix (Python’s ‘sys.prefix’ for system
installations; ‘site.USER_BASE’ for user installations).  Distutils
allows `directory' to be an absolute installation path, but this is
discouraged since it is incompatible with the wheel packaging format.
No directory information from `files' is used to determine the final
location of the installed file; only the name of the file is used.

You can specify the ‘data_files’ options as a simple sequence of files
without specifying a target directory, but this is not recommended, and
the ‘install’ command will print a warning in this case.  To install
data files directly in the target directory, an empty string should be
given as the directory.

在 3.1 版更改: All the files that match ‘data_files’ will be added to
the ‘MANIFEST’ file if no template is provided.  See *note Specifying
the files to distribute: 3b7d.


File: python.info,  Node: Additional meta-data,  Next: Debugging the setup script,  Prev: Installing Additional Files,  Up: 编写安装脚本

17.2.8 Additional meta-data
---------------------------

The setup script may include additional meta-data beyond the name and
version.  This information includes:

元数据                     描述                            值                    注释
                                                                                 
----------------------------------------------------------------------------------------------
                                                                                 
‘name’                     包名称                          短字符串              (1)
                                                                                 
                                                                                 
‘version’                  此发布的版本                    短字符串              (1)(2)
                                                                                 
                                                                                 
‘author’                   软件包作者的姓名                短字符串              (3)
                                                                                 
                                                                                 
‘author_email’             软件包的作者的电子邮件地址      电子邮件地址          (3)
                                                                                 
                                                                                 
‘maintainer’               软件包维护者的名字              短字符串              (3)
                                                                                 
                                                                                 
‘maintainer_email’         软件包维护者的电子邮件地址      电子邮件地址          (3)
                                                                                 
                                                                                 
‘url’                      软件包的网址                    网址                  (1)
                                                                                 
                                                                                 
‘description’              软件包的简短摘要说明            短字符串
                                                           
                                                                                 
‘long_description’         软件包的详细说明                长字符串              (4)
                                                                                 
                                                                                 
‘download_url’             可以下载软件包的网址            网址
                                                           
                                                                                 
‘classifiers’              分类列表                        字符串列表            (6)(7)
                                                                                 
                                                                                 
‘platforms’                平台清单                        字符串列表            (6)(8)
                                                                                 
                                                                                 
‘keywords’                 关键字列表                      字符串列表            (6)(8)
                                                                                 
                                                                                 
‘license’                  软件包许可证                    短字符串              (5)
                                                                                 

注释:

  1. These fields are required.

  2. It is recommended that versions take the form
     `major.minor[.patch[.sub]]'.

  3. Either the author or the maintainer must be identified.  If
     maintainer is provided, distutils lists it as the author in
     ‘PKG-INFO’.

  4. The ‘long_description’ field is used by PyPI when you publish a
     package, to build its project page.

  5. The ‘license’ field is a text indicating the license covering the
     package where the license is not a selection from the "License"
     Trove classifiers.  See the ‘Classifier’ field.  Notice that
     there’s a ‘licence’ distribution option which is deprecated but
     still acts as an alias for ‘license’.

  6. This field must be a list.

  7. The valid classifiers are listed on PyPI(1).

  8. To preserve backward compatibility, this field also accepts a
     string.  If you pass a comma-separated string ‘'foo, bar'’, it will
     be converted to ‘['foo', 'bar']’, Otherwise, it will be converted
     to a list of one string.

’short string’

     A single line of text, not more than 200 characters.

’long string’

     Multiple lines of plain text in reStructuredText format (see
     ‘http://docutils.sourceforge.net/’).

’list of strings’

     See below.

Encoding the version information is an art in itself.  Python packages
generally adhere to the version format `major.minor[.patch][sub]'.  The
major number is 0 for initial, experimental releases of software.  It is
incremented for releases that represent major milestones in a package.
The minor number is incremented when important new features are added to
the package.  The patch number increments when bug-fix releases are
made.  Additional trailing version information is sometimes used to
indicate sub-releases.  These are "a1,a2,...,aN" (for alpha releases,
where functionality and API may change), "b1,b2,...,bN" (for beta
releases, which only fix bugs) and "pr1,pr2,...,prN" (for final
pre-release release testing).  Some examples:

0.1.0

     the first, experimental release of a package

1.0.1a2

     the second alpha release of the first patch version of 1.0

‘classifiers’ must be specified in a list:

     setup(...,
           classifiers=[
               'Development Status :: 4 - Beta',
               'Environment :: Console',
               'Environment :: Web Environment',
               'Intended Audience :: End Users/Desktop',
               'Intended Audience :: Developers',
               'Intended Audience :: System Administrators',
               'License :: OSI Approved :: Python Software Foundation License',
               'Operating System :: MacOS :: MacOS X',
               'Operating System :: Microsoft :: Windows',
               'Operating System :: POSIX',
               'Programming Language :: Python',
               'Topic :: Communications :: Email',
               'Topic :: Office/Business',
               'Topic :: Software Development :: Bug Tracking',
               ],
           )

在 3.7 版更改: *note setup: 3b7a. now warns when ‘classifiers’,
‘keywords’ or ‘platforms’ fields are not specified as a list or a
string.

   ---------- Footnotes ----------

   (1) https://pypi.org/classifiers


File: python.info,  Node: Debugging the setup script,  Prev: Additional meta-data,  Up: 编写安装脚本

17.2.9 Debugging the setup script
---------------------------------

Sometimes things go wrong, and the setup script doesn’t do what the
developer wants.

Distutils catches any exceptions when running the setup script, and
print a simple error message before the script is terminated.  The
motivation for this behaviour is to not confuse administrators who don’t
know much about Python and are trying to install a package.  If they get
a big long traceback from deep inside the guts of Distutils, they may
think the package or the Python installation is broken because they
don’t read all the way down to the bottom and see that it’s a permission
problem.

On the other hand, this doesn’t help the developer to find the cause of
the failure.  For this purpose, the ‘DISTUTILS_DEBUG’ environment
variable can be set to anything except an empty string, and distutils
will now print detailed information about what it is doing, dump the
full traceback when an exception occurs, and print the whole command
line when an external program (like a C compiler) fails.


File: python.info,  Node: 编写设置脚本的配置文件,  Next: Creating a Source Distribution,  Prev: 编写安装脚本,  Up: 分发 Python 模块（遗留版本）

17.3 编写设置脚本的配置文件
===========================

     注解: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

通常，在 `事前' 就写出构建发布包所需的一切是不可能的：你可能需要从用户或
者用户的系统获取一些信息，才能继续下去。 只要这些信息相当简单 —— 例如一
个用于搜索 C 头文件或库的目录列表 —— 那么提供配置文件 ‘setup.cfg’ 供用户
配置就是一个低成本且方便的解决方式。 配置文件还允许你为任何命令选项提供
默认值，而安装器可以通过命令行或编辑配置文件来覆盖这些默认值。

安装配置文件是在安装脚本和安装脚本命令行之间一个适当的折衷方式 — 安装脚
本在理想情况下应当不受安装者的控制 (1) — 而安装脚本命令行则在你的控制范
围之外且完全取决于安装者的选择。 实际上，‘setup.cfg’ (以及目标系统上的其
他任何 Distutils 配置文件) 是在配置脚本之后、命令行之前被处理。 这导致了
几个有用的后果:

   * 安装者可以通过编辑 ‘setup.cfg’ 来覆盖你放在 ‘setup.py’ 中的配置

   * 你可以为无法在 ‘setup.py’ 中方便设置的选项提供非标准的默认值

   * 安装者可以使用 ‘setup.py’ 的命令行选项来覆盖 ‘setup.cfg’ 中的一切

配置文件的基本语法很简单:

     [command]
     option=value
     ...

其中 `command' 是一个 Distutils 命令 (例如 ‘build_py’, ‘install’)，而
`option' 是该命令所支持的某个选项。 可以为每个命令提供任意数量的选项，并
且可以在文件中包括任意数量的命令组。 空白行会被忽略，以一个 ‘'#'’ 开始的
注释行也是如此。 长选项值可以简单地通过缩进后续行的方式被拆分为多行。

你可以用通用的 ‘--help’ 选项找出特定命令所支持的选项列表，例如

     $ python setup.py --help build_ext
     [...]
     Options for 'build_ext' command:
       --build-lib (-b)     directory for compiled extension modules
       --build-temp (-t)    directory for temporary files (build by-products)
       --inplace (-i)       ignore build-lib and put compiled extensions into the
                            source directory alongside your pure Python modules
       --include-dirs (-I)  list of directories to search for header files
       --define (-D)        C preprocessor macros to define
       --undef (-U)         C preprocessor macros to undefine
       --swig-opts          list of SWIG command line options
     [...]

请注意在命令行中拼写为 ‘--foo-bar’ 的选项在配置文件中会拼写为 ‘foo_bar’。
例如，假设你希望你的扩展在“原地”构建 — 就是说你有一个扩展 ‘pkg.ext’，你
希望编译出的扩展文件 (例如在 Unix 上为 ‘ext.so’) 放在与你的纯 Python 模
块 ‘pkg.mod1’ 和 ‘pkg.mod2’ 相同的源目录中。 你总是可以在命令行中使用
‘--inplace’ 选项来确保这一点:

     python setup.py build_ext --inplace

但是这要求你总是显式地指定 ‘build_ext’ 命令，并且记得提供 ‘--inplace’。
一个更容易的方式是通过将其编码在此发布包的配置文件 ‘setup.cfg’ 中，“设置
并忘记”该选项。

     [build_ext]
     inplace=1

这将影响此模块发布包的所有构建，不论你是否显式指定 ‘build_ext’。 如果你
在你的源发布包中包括了 ‘setup.cfg’，它还将影响最终用户的构建 — 对此选项
来说这可能不是个好主意，因为总是原地构建扩展会破坏模块发布包的安装。 不
过在某些特殊情况下，模块是在其安装目录中被构建的，因此这可能会是个有用的
功能。 （但是，发布预期在其安装目录中被构建的扩展几乎总是一个坏主意。）

另一个例子：特定的命令会接受许多在多次运行中都不发生变化的选项；例如，
‘bdist_rpm’ 需要知道为创建 RPM 发布包生成 "spec" 文件所要求的所有信息。
这些信息有的来自安装脚本，有的由 Distutils 自动生成（例如已安装文件列表
）。 但有的则必须作为 ‘bdist_rpm’ 的选项提供，每次运行时都在命令行中完成
将会非常繁琐。 因此，这里提供 Distutils 本身的 ‘setup.cfg’ 中的一段代码:

     [bdist_rpm]
     release = 1
     packager = Greg Ward <gward@python.net>
     doc_files = CHANGES.txt
                 README.txt
                 USAGE.txt
                 doc/
                 examples/

请注意 ‘doc_files’ 选项只是一个空格分隔以提高可读性的多行字符串。

参见
....

"安装 Python 模块" 中的 *note Syntax of config files: 4383.

     有关配置文件的更多信息可在系统管理员手册中查看。

备注
....

   ---------- Footnotes ----------

   (1) (1) 在 Distutils 完全支持自动配置之前，这一理想可能是无法实现的。


File: python.info,  Node: Creating a Source Distribution,  Next: 创建构建分布,  Prev: 编写设置脚本的配置文件,  Up: 分发 Python 模块（遗留版本）

17.4 Creating a Source Distribution
===================================

     注解: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

As shown in section *note 一个简单的例子: 4360, you use the ‘sdist’
command to create a source distribution.  In the simplest case,

     python setup.py sdist

(assuming you haven’t specified any ‘sdist’ options in the setup script
or config file), ‘sdist’ creates the archive of the default format for
the current platform.  The default format is a gzip’ed tar file
(‘.tar.gz’) on Unix, and ZIP file on Windows.

You can specify as many formats as you like using the ‘--formats’
option, for example:

     python setup.py sdist --formats=gztar,zip

to create a gzipped tarball and a zip file.  The available formats are:

格式            描述                          注释
                                              
------------------------------------------------------------
                                              
‘zip’           zip 文件 (‘.zip’)             (1),(3)
                                              
                                              
‘gztar’         gzip’ed tar 文件              (2)
                (‘.tar.gz’)                   
                
                                              
‘bztar’         bzip2’ed tar 文件
                (‘.tar.bz2’)
                
                                              
‘xztar’         xz’ed tar 文件 (‘.tar.xz’)
                
                                              
‘ztar’          压缩 tar 文件 (‘.tar.Z’)      (4)
                                              
                                              
‘tar’           tar 文件 (‘.tar’)
                

在 3.5 版更改: 添加了对 ‘xztar’ 格式的支持

注释:

  1. 默认Windows

  2. 默认 Unix

  3. requires either external ‘zip’ utility or *note zipfile: 143.
     module (part of the standard Python library since Python 1.6)

  4. requires the ‘compress’ program.  Notice that this format is now
     pending for deprecation and will be removed in the future versions
     of Python.

When using any ‘tar’ format (‘gztar’, ‘bztar’, ‘xztar’, ‘ztar’ or
‘tar’), under Unix you can specify the ‘owner’ and ‘group’ names that
will be set for each member of the archive.

For example, if you want all files of the archive to be owned by root:

     python setup.py sdist --owner=root --group=root

* Menu:

* Specifying the files to distribute::
* Manifest-related options::


File: python.info,  Node: Specifying the files to distribute,  Next: Manifest-related options,  Up: Creating a Source Distribution

17.4.1 Specifying the files to distribute
-----------------------------------------

If you don’t supply an explicit list of files (or instructions on how to
generate one), the ‘sdist’ command puts a minimal default set into the
source distribution:

   * all Python source files implied by the ‘py_modules’ and ‘packages’
     options

   * all C source files mentioned in the ‘ext_modules’ or ‘libraries’
     options

   * scripts identified by the ‘scripts’ option See *note Installing
     Scripts: 4376.

   * anything that looks like a test script: ‘test/test*.py’ (currently,
     the Distutils don’t do anything with test scripts except include
     them in source distributions, but in the future there will be a
     standard for testing Python module distributions)

   * Any of the standard README files (‘README’, ‘README.txt’, or
     ‘README.rst’), ‘setup.py’ (or whatever you called your setup
     script), and ‘setup.cfg’.

   * all files that matches the ‘package_data’ metadata.  See *note
     Installing Package Data: 4378.

   * all files that matches the ‘data_files’ metadata.  See *note
     Installing Additional Files: 437a.

Sometimes this is enough, but usually you will want to specify
additional files to distribute.  The typical way to do this is to write
a `manifest template', called ‘MANIFEST.in’ by default.  The manifest
template is just a list of instructions for how to generate your
manifest file, ‘MANIFEST’, which is the exact list of files to include
in your source distribution.  The ‘sdist’ command processes this
template and generates a manifest based on its instructions and what it
finds in the filesystem.

If you prefer to roll your own manifest file, the format is simple: one
filename per line, regular files (or symlinks to them) only.  If you do
supply your own ‘MANIFEST’, you must specify everything: the default set
of files described above does not apply in this case.

在 3.1 版更改: An existing generated ‘MANIFEST’ will be regenerated
without ‘sdist’ comparing its modification time to the one of
‘MANIFEST.in’ or ‘setup.py’.

在 3.1.3 版更改: ‘MANIFEST’ files start with a comment indicating they
are generated.  Files without this comment are not overwritten or
removed.

在 3.2.2 版更改: ‘sdist’ will read a ‘MANIFEST’ file if no ‘MANIFEST.in’
exists, like it used to do.

在 3.7 版更改: ‘README.rst’ is now included in the list of distutils
standard READMEs.

The manifest template has one command per line, where each command
specifies a set of files to include or exclude from the source
distribution.  For an example, again we turn to the Distutils’ own
manifest template:

     include *.txt
     recursive-include examples *.txt *.py
     prune examples/sample?/build

The meanings should be fairly clear: include all files in the
distribution root matching ‘*.txt’, all files anywhere under the
‘examples’ directory matching ‘*.txt’ or ‘*.py’, and exclude all
directories matching ‘examples/sample?/build’.  All of this is done
`after' the standard include set, so you can exclude files from the
standard set with explicit instructions in the manifest template.  (Or,
you can use the ‘--no-defaults’ option to disable the standard set
entirely.)  There are several other commands available in the manifest
template mini-language; see section *note 创建源码发行包; sdist 命令:
4388.

The order of commands in the manifest template matters: initially, we
have the list of default files as described above, and each command in
the template adds to or removes from that list of files.  Once we have
fully processed the manifest template, we remove files that should not
be included in the source distribution:

   * all files in the Distutils "build" tree (default ‘build/’)

   * all files in directories named ‘RCS’, ‘CVS’, ‘.svn’, ‘.hg’, ‘.git’,
     ‘.bzr’ or ‘_darcs’

Now we have our complete list of files, which is written to the manifest
for future reference, and then used to build the source distribution
archive(s).

You can disable the default set of included files with the
‘--no-defaults’ option, and you can disable the standard exclude set
with ‘--no-prune’.

Following the Distutils’ own manifest template, let’s trace how the
‘sdist’ command builds the list of files to include in the Distutils
source distribution:

  1. include all Python source files in the ‘distutils’ and
     ‘distutils/command’ subdirectories (because packages corresponding
     to those two directories were mentioned in the ‘packages’ option in
     the setup script—see section *note 编写安装脚本: 4361.)

  2. include ‘README.txt’, ‘setup.py’, and ‘setup.cfg’ (standard files)

  3. include ‘test/test*.py’ (standard files)

  4. include ‘*.txt’ in the distribution root (this will find
     ‘README.txt’ a second time, but such redundancies are weeded out
     later)

  5. include anything matching ‘*.txt’ or ‘*.py’ in the sub-tree under
     ‘examples’,

  6. exclude all files in the sub-trees starting at directories matching
     ‘examples/sample?/build’—this may exclude files included by the
     previous two steps, so it’s important that the ‘prune’ command in
     the manifest template comes after the ‘recursive-include’ command

  7. exclude the entire ‘build’ tree, and any ‘RCS’, ‘CVS’, ‘.svn’,
     ‘.hg’, ‘.git’, ‘.bzr’ and ‘_darcs’ directories

Just like in the setup script, file and directory names in the manifest
template should always be slash-separated; the Distutils will take care
of converting them to the standard representation on your platform.
That way, the manifest template is portable across operating systems.


File: python.info,  Node: Manifest-related options,  Prev: Specifying the files to distribute,  Up: Creating a Source Distribution

17.4.2 Manifest-related options
-------------------------------

The normal course of operations for the ‘sdist’ command is as follows:

   * if the manifest file (‘MANIFEST’ by default) exists and the first
     line does not have a comment indicating it is generated from
     ‘MANIFEST.in’, then it is used as is, unaltered

   * if the manifest file doesn’t exist or has been previously
     automatically generated, read ‘MANIFEST.in’ and create the manifest

   * if neither ‘MANIFEST’ nor ‘MANIFEST.in’ exist, create a manifest
     with just the default file set

   * use the list of files now in ‘MANIFEST’ (either just generated or
     read in) to create the source distribution archive(s)

There are a couple of options that modify this behaviour.  First, use
the ‘--no-defaults’ and ‘--no-prune’ to disable the standard "include"
and "exclude" sets.

Second, you might just want to (re)generate the manifest, but not create
a source distribution:

     python setup.py sdist --manifest-only

‘-o’ is a shortcut for ‘--manifest-only’.


File: python.info,  Node: 创建构建分布,  Next: Distutils 示例,  Prev: Creating a Source Distribution,  Up: 分发 Python 模块（遗留版本）

17.5 创建构建分布
=================

     注解: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

A "built distribution" is what you’re probably used to thinking of
either as a "binary package" or an "installer" (depending on your
background).  It’s not necessarily binary, though, because it might
contain only Python source code and/or byte-code; and we don’t call it a
package, because that word is already spoken for in Python.  (And
"installer" is a term specific to the world of mainstream desktop
systems.)

A built distribution is how you make life as easy as possible for
installers of your module distribution: for users of RPM-based Linux
systems, it’s a binary RPM; for Windows users, it’s an executable
installer; for Debian-based Linux users, it’s a Debian package; and so
forth.  Obviously, no one person will be able to create built
distributions for every platform under the sun, so the Distutils are
designed to enable module developers to concentrate on their
specialty—writing code and creating source distributions—while an
intermediary species called `packagers' springs up to turn source
distributions into built distributions for as many platforms as there
are packagers.

Of course, the module developer could be their own packager; or the
packager could be a volunteer "out there" somewhere who has access to a
platform which the original developer does not; or it could be software
periodically grabbing new source distributions and turning them into
built distributions for as many platforms as the software has access to.
Regardless of who they are, a packager uses the setup script and the
‘bdist’ command family to generate built distributions.

As a simple example, if I run the following command in the Distutils
source tree:

     python setup.py bdist

then the Distutils builds my module distribution (the Distutils itself
in this case), does a "fake" installation (also in the ‘build’
directory), and creates the default type of built distribution for my
platform.  The default format for built distributions is a "dumb" tar
file on Unix, and a simple executable installer on Windows.  (That tar
file is considered "dumb" because it has to be unpacked in a specific
location to work.)

Thus, the above command on a Unix system creates
‘Distutils-1.0.`plat'.tar.gz’; unpacking this tarball from the right
place installs the Distutils just as though you had downloaded the
source distribution and run ‘python setup.py install’.  (The "right
place" is either the root of the filesystem or Python’s ‘`prefix'’
directory, depending on the options given to the ‘bdist_dumb’ command;
the default is to make dumb distributions relative to ‘`prefix'’.)

Obviously, for pure Python distributions, this isn’t any simpler than
just running ‘python setup.py install’—but for non-pure distributions,
which include extensions that would need to be compiled, it can mean the
difference between someone being able to use your extensions or not.
And creating "smart" built distributions, such as an RPM package or an
executable installer for Windows, is far more convenient for users even
if your distribution doesn’t include any extensions.

The ‘bdist’ command has a ‘--formats’ option, similar to the ‘sdist’
command, which you can use to select the types of built distribution to
generate: for example,

     python setup.py bdist --format=zip

would, when run on a Unix system, create
‘Distutils-1.0.`plat'.zip’—again, this archive would be unpacked from
the root directory to install the Distutils.

The available formats for built distributions are:

格式              描述                               注释
                                                     
-------------------------------------------------------------------
                                                     
‘gztar’           gzipped tar 文件 (‘.tar.gz’)       (1)
                                                     
                                                     
‘bztar’           bzipped tar 文件 (‘.tar.bz2’)
                  
                                                     
‘xztar’           xzipped tar 文件 (‘.tar.xz’)
                  
                                                     
‘ztar’            压缩 tar 文件 (‘.tar.Z’)           (3)
                                                     
                                                     
‘tar’             tar 文件 (‘.tar’)
                  
                                                     
‘zip’             zip 文件 (‘.zip’)                  (2),(4)
                                                     
                                                     
‘rpm’             RPM                                (5)
                                                     
                                                     
‘pkgtool’         Solaris ‘pkgtool’
                  
                                                     
‘sdux’            HP-UX ‘swinstall’
                  
                                                     
‘wininst’         Windows的自解压ZIP文件             (4)
                                                     
                                                     
‘msi’             Microsoft安装程序。
                  

在 3.5 版更改: 添加了对 ‘xztar’ 格式的支持

注释:

  1. 默认 Unix

  2. 默认Windows

  3. requires external ‘compress’ utility.

  4. requires either external ‘zip’ utility or *note zipfile: 143.
     module (part of the standard Python library since Python 1.6)

  5. requires external ‘rpm’ utility, version 3.0.4 or better (use ‘rpm
     --version’ to find out which version you have)

You don’t have to use the ‘bdist’ command with the ‘--formats’ option;
you can also use the command that directly implements the format you’re
interested in.  Some of these ‘bdist’ "sub-commands" actually generate
several similar formats; for instance, the ‘bdist_dumb’ command
generates all the "dumb" archive formats (‘tar’, ‘gztar’, ‘bztar’,
‘xztar’, ‘ztar’, and ‘zip’), and ‘bdist_rpm’ generates both binary and
source RPMs.  The ‘bdist’ sub-commands, and the formats generated by
each, are:

命令                           格式
                               
-------------------------------------------------------------------------
                               
‘bdist_dumb’                   tar, gztar, bztar, xztar, ztar, zip
                               
                               
‘bdist_rpm’                    rpm, srpm
                               
                               
‘bdist_wininst’                wininst
                               
                               
‘bdist_msi’                    msi
                               

     注解: 从Python 3.8开始不推荐使用 bdist_wininst

The following sections give details on the individual ‘bdist_*’
commands.

* Menu:

* 创建RPM软件包::
* Creating Windows Installers::
* Cross-compiling on Windows::
* Vista User Access Control (UAC): Vista User Access Control UAC.


File: python.info,  Node: 创建RPM软件包,  Next: Creating Windows Installers,  Up: 创建构建分布

17.5.1 创建RPM软件包
--------------------

The RPM format is used by many popular Linux distributions, including
Red Hat, SuSE, and Mandrake.  If one of these (or any of the other
RPM-based Linux distributions) is your usual environment, creating RPM
packages for other users of that same distribution is trivial.
Depending on the complexity of your module distribution and differences
between Linux distributions, you may also be able to create RPMs that
work on different RPM-based distributions.

The usual way to create an RPM of your module distribution is to run the
‘bdist_rpm’ command:

     python setup.py bdist_rpm

or the ‘bdist’ command with the ‘--format’ option:

     python setup.py bdist --formats=rpm

The former allows you to specify RPM-specific options; the latter allows
you to easily specify multiple formats in one run.  If you need to do
both, you can explicitly specify multiple ‘bdist_*’ commands and their
options:

     python setup.py bdist_rpm --packager="John Doe <jdoe@example.org>" \
                     bdist_wininst --target-version="2.0"

Creating RPM packages is driven by a ‘.spec’ file, much as using the
Distutils is driven by the setup script.  To make your life easier, the
‘bdist_rpm’ command normally creates a ‘.spec’ file based on the
information you supply in the setup script, on the command line, and in
any Distutils configuration files.  Various options and sections in the
‘.spec’ file are derived from options in the setup script as follows:

RPM ‘.spec’ 文件配置或选项                     Distutils安装脚本选项
                                               
--------------------------------------------------------------------------------------------------
                                               
名称                                           ‘name’
                                               
                                               
摘要（在序言中）                               ‘description’
                                               
                                               
版本                                           ‘version’
                                               
                                               
供应商                                         ‘author’ 和 ‘author_email’, 或 — & ‘maintainer’
                                               和 ‘maintainer_email’
                                               
                                               
版权所有                                       ‘license’
                                               
                                               
Url                                            ‘url’
                                               
                                               
%d描述（部分）                                 ‘long_description’
                                               

Additionally, there are many options in ‘.spec’ files that don’t have
corresponding options in the setup script.  Most of these are handled
through options to the ‘bdist_rpm’ command as follows:

RPM ‘.spec’ 文件配置或选项          ‘bdist_rpm’ 选项                  默认值
                                                                      
----------------------------------------------------------------------------------------------------
                                                                      
发布版本                            ‘release’                         "1"
                                                                      
                                                                      
组织                                ‘group’                           "Development/Libraries"
                                                                      
                                                                      
供应商                              ‘vendor’                          （同上）
                                                                      
                                                                      
打包                                ‘packager’                        (none)
                                                                      
                                                                      
提供                                ‘provides’                        (none)
                                                                      
                                                                      
需求                                ‘requires’                        (none)
                                                                      
                                                                      
冲突                                ‘conflicts’                       (none)
                                                                      
                                                                      
淘汰                                ‘obsoletes’                       (none)
                                                                      
                                                                      
Distribution                        ‘distribution_name’               (none)
                                                                      
                                                                      
构建要求                            ‘build_requires’                  (none)
                                                                      
                                                                      
Icon                                ‘icon’                            (none)
                                                                      

Obviously, supplying even a few of these options on the command-line
would be tedious and error-prone, so it’s usually best to put them in
the setup configuration file, ‘setup.cfg’—see section *note
编写设置脚本的配置文件: 4380.  If you distribute or package many Python
module distributions, you might want to put options that apply to all of
them in your personal Distutils configuration file
(‘~/.pydistutils.cfg’).  If you want to temporarily disable this file,
you can pass the ‘--no-user-cfg’ option to ‘setup.py’.

There are three steps to building a binary RPM package, all of which are
handled automatically by the Distutils:

  1. create a ‘.spec’ file, which describes the package (analogous to
     the Distutils setup script; in fact, much of the information in the
     setup script winds up in the ‘.spec’ file)

  2. create the source RPM

  3. create the "binary" RPM (which may or may not contain binary code,
     depending on whether your module distribution contains Python
     extensions)

Normally, RPM bundles the last two steps together; when you use the
Distutils, all three steps are typically bundled together.

If you wish, you can separate these three steps.  You can use the
‘--spec-only’ option to make ‘bdist_rpm’ just create the ‘.spec’ file
and exit; in this case, the ‘.spec’ file will be written to the
"distribution directory"—normally ‘dist/’, but customizable with the
‘--dist-dir’ option.  (Normally, the ‘.spec’ file winds up deep in the
"build tree," in a temporary directory created by ‘bdist_rpm’.)


File: python.info,  Node: Creating Windows Installers,  Next: Cross-compiling on Windows,  Prev: 创建RPM软件包,  Up: 创建构建分布

17.5.2 Creating Windows Installers
----------------------------------

     警告: 从Python 3.8开始不推荐使用 bdist_wininst

Executable installers are the natural format for binary distributions on
Windows.  They display a nice graphical user interface, display some
information about the module distribution to be installed taken from the
metadata in the setup script, let the user select a few options, and
start or cancel the installation.

Since the metadata is taken from the setup script, creating Windows
installers is usually as easy as running:

     python setup.py bdist_wininst

or the ‘bdist’ command with the ‘--formats’ option:

     python setup.py bdist --formats=wininst

If you have a pure module distribution (only containing pure Python
modules and packages), the resulting installer will be version
independent and have a name like ‘foo-1.0.win32.exe’.  Note that
creating ‘wininst’ binary distributions in only supported on Windows
systems.

If you have a non-pure distribution, the extensions can only be created
on a Windows platform, and will be Python version dependent.  The
installer filename will reflect this and now has the form
‘foo-1.0.win32-py2.0.exe’.  You have to create a separate installer for
every Python version you want to support.

The installer will try to compile pure modules into *note bytecode: 61d.
after installation on the target system in normal and optimizing mode.
If you don’t want this to happen for some reason, you can run the
‘bdist_wininst’ command with the ‘--no-target-compile’ and/or the
‘--no-target-optimize’ option.

By default the installer will display the cool "Python Powered" logo
when it is run, but you can also supply your own 152x261 bitmap which
must be a Windows ‘.bmp’ file with the ‘--bitmap’ option.

The installer will also display a large title on the desktop background
window when it is run, which is constructed from the name of your
distribution and the version number.  This can be changed to another
text by using the ‘--title’ option.

The installer file will be written to the "distribution directory" —
normally ‘dist/’, but customizable with the ‘--dist-dir’ option.


File: python.info,  Node: Cross-compiling on Windows,  Next: Vista User Access Control UAC,  Prev: Creating Windows Installers,  Up: 创建构建分布

17.5.3 Cross-compiling on Windows
---------------------------------

Starting with Python 2.6, distutils is capable of cross-compiling
between Windows platforms.  In practice, this means that with the
correct tools installed, you can use a 32bit version of Windows to
create 64bit extensions and vice-versa.

To build for an alternate platform, specify the ‘--plat-name’ option to
the build command.  Valid values are currently ’win32’, and ’win-amd64’.
For example, on a 32bit version of Windows, you could execute:

     python setup.py build --plat-name=win-amd64

to build a 64bit version of your extension.  The Windows Installers also
support this option, so the command:

     python setup.py build --plat-name=win-amd64 bdist_wininst

would create a 64bit installation executable on your 32bit version of
Windows.

To cross-compile, you must download the Python source code and
cross-compile Python itself for the platform you are targeting - it is
not possible from a binary installation of Python (as the .lib etc file
for other platforms are not included.)  In practice, this means the user
of a 32 bit operating system will need to use Visual Studio 2008 to open
the ‘PCbuild/PCbuild.sln’ solution in the Python source tree and build
the "x64" configuration of the ’pythoncore’ project before
cross-compiling extensions is possible.

Note that by default, Visual Studio 2008 does not install 64bit
compilers or tools.  You may need to reexecute the Visual Studio setup
process and select these tools (using Control Panel->[Add/Remove]
Programs is a convenient way to check or modify your existing install.)

* Menu:

* The Postinstallation script::


File: python.info,  Node: The Postinstallation script,  Up: Cross-compiling on Windows

17.5.3.1 The Postinstallation script
....................................

Starting with Python 2.3, a postinstallation script can be specified
with the ‘--install-script’ option.  The basename of the script must be
specified, and the script filename must also be listed in the scripts
argument to the setup function.

This script will be run at installation time on the target system after
all the files have been copied, with ‘argv[1]’ set to ‘-install’, and
again at uninstallation time before the files are removed with ‘argv[1]’
set to ‘-remove’.

The installation script runs embedded in the windows installer, every
output (‘sys.stdout’, ‘sys.stderr’) is redirected into a buffer and will
be displayed in the GUI after the script has finished.

Some functions especially useful in this context are available as
additional built-in functions in the installation script.

 -- 函数: directory_created (path)
 -- 函数: file_created (path)

     These functions should be called when a directory or file is
     created by the postinstall script at installation time.  It will
     register `path' with the uninstaller, so that it will be removed
     when the distribution is uninstalled.  To be safe, directories are
     only removed if they are empty.

 -- 函数: get_special_folder_path (csidl_string)

     This function can be used to retrieve special folder locations on
     Windows like the Start Menu or the Desktop.  It returns the full
     path to the folder.  `csidl_string' must be one of the following
     strings:

          "CSIDL_APPDATA"

          "CSIDL_COMMON_STARTMENU"
          "CSIDL_STARTMENU"

          "CSIDL_COMMON_DESKTOPDIRECTORY"
          "CSIDL_DESKTOPDIRECTORY"

          "CSIDL_COMMON_STARTUP"
          "CSIDL_STARTUP"

          "CSIDL_COMMON_PROGRAMS"
          "CSIDL_PROGRAMS"

          "CSIDL_FONTS"

     如果文件夹不能被检索到，会触发 *note OSError: 1d4. 。

     Which folders are available depends on the exact Windows version,
     and probably also the configuration.  For details refer to
     Microsoft’s documentation of the ‘SHGetSpecialFolderPath()’
     function.

 -- 函数: create_shortcut (target, description, filename[, arguments[,
          workdir[, iconpath[, iconindex]]]])

     This function creates a shortcut.  `target' is the path to the
     program to be started by the shortcut.  `description' is the
     description of the shortcut.  `filename' is the title of the
     shortcut that the user will see.  `arguments' specifies the command
     line arguments, if any.  `workdir' is the working directory for the
     program.  `iconpath' is the file containing the icon for the
     shortcut, and `iconindex' is the index of the icon in the file
     `iconpath'.  Again, for details consult the Microsoft documentation
     for the ‘IShellLink’ interface.


File: python.info,  Node: Vista User Access Control UAC,  Prev: Cross-compiling on Windows,  Up: 创建构建分布

17.5.4 Vista User Access Control (UAC)
--------------------------------------

Starting with Python 2.6, bdist_wininst supports a
‘--user-access-control’ option.  The default is ’none’ (meaning no UAC
handling is done), and other valid values are ’auto’ (meaning prompt for
UAC elevation if Python was installed for all users) and ’force’
(meaning always prompt for elevation).

     注解: 从Python 3.8开始不推荐使用 bdist_wininst


File: python.info,  Node: Distutils 示例,  Next: 扩展 Distutils,  Prev: 创建构建分布,  Up: 分发 Python 模块（遗留版本）

17.6 Distutils 示例
===================

     注解: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

本章节提供几个基础示例，来帮助用户入门 distutils。关于使用 distutils 的
额外信息可以参考 Distutils Cookbook。

参见
....

Distutils Cookbook(1)

     一套展示如何更好地控制和使用 distutils 的方法。

* Menu:

* 纯 Python 分发（通过 module）::
* 纯 Python 分发（通过 包）::
* 单个扩展模块::
* 检查一个包::
* 读取元数据::

   ---------- Footnotes ----------

   (1) https://wiki.python.org/moin/Distutils/Cookbook


File: python.info,  Node: 纯 Python 分发（通过 module）,  Next: 纯 Python 分发（通过 包）,  Up: Distutils 示例

17.6.1 纯 Python 分发（通过 module）
------------------------------------

如果你要分发一组模块，特别是它们不在特定的包中，你可以在配置脚本中使用
‘py_modules’ 选项单独指定它们。

最简单的情况下，你只用关心两个文件：一个配置脚本，和单个你要分发的模块，
这个示例中的 ‘foo.py’: ：

     <root>/
             setup.py
             foo.py

（在本章节的所有图中，`<root>' 表示分发根目录。）这种情况下的一个最小配
置脚本是：

     from distutils.core import setup
     setup(name='foo',
           version='1.0',
           py_modules=['foo'],
           )

注意分发的包名用 ‘name’ 选项单独指定，没有规定它必须和包中单独的模块同名
（虽然这也是个可以遵循的好习惯）。然而，分发名用来生成文件名，所以你应该
坚持用字母、数字、下划线和连词号。

因为 ‘py_modules’ 是个列表，你当然可以指定多个模块，比如，如果你要分发模
块 ‘foo’ 和 ‘bar’，你的配置可能是这样：

     <root>/
             setup.py
             foo.py
             bar.py

并且配置脚本是：

     from distutils.core import setup
     setup(name='foobar',
           version='1.0',
           py_modules=['foo', 'bar'],
           )

你可以把模块源文件放进另一个目录，但是如果你有足够的模块，也许用包指定模
块更简单，而不是单独列出它们。


File: python.info,  Node: 纯 Python 分发（通过 包）,  Next: 单个扩展模块,  Prev: 纯 Python 分发（通过 module）,  Up: Distutils 示例

17.6.2 纯 Python 分发（通过 包）
--------------------------------

如果你有超过一组模块要分发，特别是它们在不同的包中，也许指定整个包更简单
，而不是指定单独的模块。这样即使你的模块不在一个包中也有效；你可以直接令
Distutils 来从根包来处理模块，并且这样对任何其他包也有效（除非你不需要
‘__init__.py’ 文件）。

上一个示例的配置脚本也可以写成：

     from distutils.core import setup
     setup(name='foobar',
           version='1.0',
           packages=[''],
           )

（空字符串表示根包。）

如果两个文件移动到子目录，但是依然在根包中，如：

     <root>/
             setup.py
             src/      foo.py
                       bar.py

那么你依然需要指定根包，但是你还需要告诉 Distutils 根包中的源文件在哪：

     from distutils.core import setup
     setup(name='foobar',
           version='1.0',
           package_dir={'': 'src'},
           packages=[''],
           )

更一般地，你要分发多个在同一个包（或者子包）中的模块。举个例子，假设
‘foo’ 和 ‘bar’ 模块属于 ‘foobar’ 包，排布源文件树的一种方式是：

     <root>/
             setup.py
             foobar/
                      __init__.py
                      foo.py
                      bar.py

这其实是 Distutils 默认的排布，也是你的配置脚本中需要的工作量最小的。

     from distutils.core import setup
     setup(name='foobar',
           version='1.0',
           packages=['foobar'],
           )

如果你要把模块放到没有按照它们的包名命名的目录里，那你需要再次使用
‘package_dir’ 选项。比如，如果 ‘src’ 目录包含包 ‘foobar’ 中的模块：

     <root>/
             setup.py
             src/
                      __init__.py
                      foo.py
                      bar.py

一个合适的配置脚本可以是：

     from distutils.core import setup
     setup(name='foobar',
           version='1.0',
           package_dir={'foobar': 'src'},
           packages=['foobar'],
           )

或者，你可以把主包中的模块直接放到分发根目录：

     <root>/
             setup.py
             __init__.py
             foo.py
             bar.py

这样你的配置文件是：

     from distutils.core import setup
     setup(name='foobar',
           version='1.0',
           package_dir={'foobar': ''},
           packages=['foobar'],
           )

（空字符串同样表示当前目录。）

如果你有子包，则它们必须显式列在 ‘packages’ 中，但是 ‘package_dir’ 中的
任何条目会自动扩展到子包。（也就是说，Distutils `不会' 扫描你的源码树，
而是尝试通过查找 ‘__init__.py’ 文件，来弄清哪些目录与 Python 包关联。）
这样，如果默认排布产生一个子包：

     <root>/
             setup.py
             foobar/
                      __init__.py
                      foo.py
                      bar.py
                      subfoo/
                                __init__.py
                                blah.py

则相应的配置脚本是：

     from distutils.core import setup
     setup(name='foobar',
           version='1.0',
           packages=['foobar', 'foobar.subfoo'],
           )


File: python.info,  Node: 单个扩展模块,  Next: 检查一个包,  Prev: 纯 Python 分发（通过 包）,  Up: Distutils 示例

17.6.3 单个扩展模块
-------------------

扩展模块用 ‘ext_modules’ 选项指定。‘package_dir’ 对在哪寻找扩展源文件无
效；它只对纯 Python 模块的源文件有效。最简单的，一个用单个C源文件写的单
扩展模块是：

     <root>/
             setup.py
             foo.c

如果 ‘foo’ 扩展属于根包，则配置脚本可以是：

     from distutils.core import setup
     from distutils.extension import Extension
     setup(name='foobar',
           version='1.0',
           ext_modules=[Extension('foo', ['foo.c'])],
           )

如果扩展在包中，比如 ‘foopkg’，那么

使用完全相同的源文件树排布，通过改变扩展的名字，这个扩展很容易放入
‘foopkg’ 包中：

     from distutils.core import setup
     from distutils.extension import Extension
     setup(name='foobar',
           version='1.0',
           ext_modules=[Extension('foopkg.foo', ['foo.c'])],
           )


File: python.info,  Node: 检查一个包,  Next: 读取元数据,  Prev: 单个扩展模块,  Up: Distutils 示例

17.6.4 检查一个包
-----------------

‘check’ 命令允许你校验你的包的元数据是否满足生成分发的最低要求。

直接使用你的 ‘setup.py’ 脚本来运行它。如果缺了一些东西，‘check’ 会显示警
告。

我们来用单个脚本举例：

     from distutils.core import setup

     setup(name='foobar')

运行 ‘check’ 命令会显示一些警告：

     $ python setup.py check
     running check
     warning: check: missing required meta-data: version, url
     warning: check: missing meta-data: either (author and author_email) or
              (maintainer and maintainer_email) must be supplied

如果你在 ‘long_description’ 域中使用 reStructuredText 语法，并且安装了
docutils(1) ，你可以用 ‘check’ 命令，和 ‘restructuredtext’ 选项检查语法
是否正确。

比如，如果 ‘setup.py’ 脚本改成：

     from distutils.core import setup

     desc = """\
     My description
     ==============

     This is the description of the ``foobar`` package.
     """

     setup(name='foobar', version='1', author='tarek',
         author_email='tarek@ziade.org',
         url='http://example.com', long_description=desc)

长描述中有问题的地方，通过使用 ‘docutils’ 解析器，‘check’ 能进行删除：

     $ python setup.py check --restructuredtext
     running check
     warning: check: Title underline too short. (line 2)
     warning: check: Could not finish the parsing.

   ---------- Footnotes ----------

   (1) http://docutils.sourceforge.net


File: python.info,  Node: 读取元数据,  Prev: 检查一个包,  Up: Distutils 示例

17.6.5 读取元数据
-----------------

*note distutils.core.setup(): 3b7a. 函数提供一个通过项目的 ‘setup.py’ 脚
本，来查询项目的元数据的域的命令行接口：

     $ python setup.py --name
     distribute

这个调用通过运行 *note distutils.core.setup(): 3b7a. 函数读取 ‘name’ 元
数据。然而，当源文件或者二进制分发用 Distutils 创建时，元数据域写入一个
名为 ‘PKG-INFO’ 的静态文件。当一个基于Distutils的项目安装在 Python 中时
，‘PKG-INFO’ 文件随着分发的模块和包一起复制到
‘NAME-VERSION-pyX.X.egg-info’ 中，其中 ‘NAME’ 是项目的名字，‘VERSION’ 是
元数据中定义的版本， ‘pyX.X’ 则是 Python 的大版本和小版本，如 ‘2.7’ 或者
‘3.2’。

你可以读回静态文件，使用 ‘distutils.dist.DistributionMetadata’ 类和它的
‘read_pkg_file()’ 方法：

     >>> from distutils.dist import DistributionMetadata
     >>> metadata = DistributionMetadata()
     >>> metadata.read_pkg_file(open('distribute-0.6.8-py2.7.egg-info'))
     >>> metadata.name
     'distribute'
     >>> metadata.version
     '0.6.8'
     >>> metadata.description
     'Easily download, build, install, upgrade, and uninstall Python packages'

注意类也可以用元数据文件载入值来实例化：

     >>> pkg_info_path = 'distribute-0.6.8-py2.7.egg-info'
     >>> DistributionMetadata(pkg_info_path).name
     'distribute'


File: python.info,  Node: 扩展 Distutils,  Next: 命令参考,  Prev: Distutils 示例,  Up: 分发 Python 模块（遗留版本）

17.7 扩展 Distutils
===================

     注解: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

Distutils 可以通过各种方式扩展。 大多数扩展都采用新命令或现有命令的替换
形式。 例如，可以编写新命令以支持新的特定于平台的包格式，但是可以修改现
有命令的替换，以修改命令在包上的操作细节。

distutils 的大多数扩展都在想要修改现有命令的 ‘setup.py’ 脚本中编写；其中
许多只是简单地在 ‘.py’ 文件以外添加了一些应当被拷贝到包中的文件后缀以便
使用。

大多部 distutils 命令的实现都是 *note distutils.cmd.Command: 43a9. 类的
子类。 新增命令可直接继承自 ‘Command’，而替换命令往往间接派生自
‘Command’， 直接子类化它们所替换的命令。 所有命令都要求自 ‘Command’ 派生
。

* Menu:

* 集成新的命令::
* 添加新的发布类型::


File: python.info,  Node: 集成新的命令,  Next: 添加新的发布类型,  Up: 扩展 Distutils

17.7.1 集成新的命令
-------------------

有多种方法可将新的命令实现集成到 distutils 中。 最困难的一种是鼓动在
distutils 自身内部包含新特性，并等待（以及要求）某个 Python 版本提供该支
持。 出于多种原因，这确实是相当难的。

对于大多数需求来说最为常见并且可能最为合理的一种则是通过你自己的
‘setup.py’ 脚本来包含新的实现，然后让 *note distutils.core.setup():
3b7a. 函数使用它们:

     from distutils.command.build_py import build_py as _build_py
     from distutils.core import setup

     class build_py(_build_py):
         """Specialized Python source builder."""

         # implement whatever needs to be different...

     setup(cmdclass={'build_py': build_py},
           ...)

如果新的实现必须通过特定的包来使用则此方式最为适宜，因为每个对这个包感兴
趣的人都将会需要有新的命令实现。

从 Python 2.4 开始，还有第三个选项可用，其目标是允许添加支持现有
‘setup.py’ 脚本的新命令，而不需要修改 Python 安装包。 这预计可允许第三方
扩展提供对附加打包系统的支持，而相应命令又可用于任何 distutils 命令可被
使用的地方。 新的配置选项 ‘command_packages’ (命令行选项为
‘--command-packages’) 可用来指定附加包，以在其中查找实现新增命令的模块。
像所有 distutils 选项一样，这可以通过命令行或配置文件来指定。 此选项只能
在配置文件的 ‘[global]’ 小节之中或在命令行的任何命令之前设置。 如果是设
置在配置文件中，则它可被命令行设置重载；如果在命令行中将其设为空字符串则
将会使用默认值。 此选项绝不应当在随特定包提供的配置文件中设置。

这个新选项可被用来添加任意数量的包到查找命令实现的包列表；多个包名应当以
逗号分隔。 当未指明时，查找将只在 *note distutils.command: 3e. 包中进行
。 但是当 ‘setup.py’ 附带 ‘--command-packages distcmds,buildcmds’ 选项运
行时，*note distutils.command: 3e, ‘distcmds’ 和 ‘buildcmds’ 包将按此顺
序被查找。 新的命令应当在与命名同名的模块中由同名的类来实现。 给定上述示
例命令行选项，则命令 ‘bdist_openpkg’ 可由类
‘distcmds.bdist_openpkg.bdist_openpkg’ 或
‘buildcmds.bdist_openpkg.bdist_openpkg’ 来实现。


File: python.info,  Node: 添加新的发布类型,  Prev: 集成新的命令,  Up: 扩展 Distutils

17.7.2 添加新的发布类型
-----------------------

创建发布（在 ‘dist/’ 目录中的文件）的命令需要将 ‘(command, filename)’ 二
元组添加到 ‘self.distribution.dist_files’ 以便 ‘upload’ 可以将其上传到
PyPI。 二元组中的 `filename' 不包含路径信息而只有文件名本身。 在 dry-run
模式下，二元组仍然应当被添加以表示必须创建的内容。


File: python.info,  Node: 命令参考,  Next: API参考引用,  Prev: 扩展 Distutils,  Up: 分发 Python 模块（遗留版本）

17.8 命令参考
=============

     注解: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

* Menu:

* 安装模块; install 命令族: 安装模块 install 命令族.
* 创建源码发行包; sdist 命令: 创建源码发行包 sdist 命令.


File: python.info,  Node: 安装模块 install 命令族,  Next: 创建源码发行包 sdist 命令,  Up: 命令参考

17.8.1 安装模块: ‘install’ 命令族
---------------------------------

install 命令会确保 build 命令已经运行，然后运行子命令 ‘install_lib’,
‘install_data’ 和 ‘install_scripts’。

* Menu:

* install_data::
* install_scripts::


File: python.info,  Node: install_data,  Next: install_scripts,  Up: 安装模块 install 命令族

17.8.1.1 ‘install_data’
.......................

此命令会安装随发行包一同提供的所有数据文件。


File: python.info,  Node: install_scripts,  Prev: install_data,  Up: 安装模块 install 命令族

17.8.1.2 ‘install_scripts’
..........................

此命令会安装发行包中的所有（Python）脚本。


File: python.info,  Node: 创建源码发行包 sdist 命令,  Prev: 安装模块 install 命令族,  Up: 命令参考

17.8.2 创建源码发行包: ‘sdist’ 命令
-----------------------------------

列出的模板命令有:

命令                                            描述
                                                
----------------------------------------------------------------------------------------------------
                                                
‘include pat1 pat2 ...’                         包括与列出的模式匹配的所有文件
                                                
                                                
‘exclude pat1 pat2 ...’                         排除与列出的模式匹配的所有文件
                                                
                                                
‘recursive-include dir pat1 pat2 ...’           包括 `dir' 下与列出的模式匹配的所有文件
                                                
                                                
‘recursive-exclude dir pat1 pat2 ...’           排除 `dir' 下与列出的模式匹配的所有文件
                                                
                                                
‘global-include pat1 pat2 ...’                  包括与源树匹配的所有文件—和任何列出的模式
                                                
                                                
‘global-exclude pat1 pat2 ...’                  排除与源树匹配的所有文件—和任何列出的模式
                                                
                                                
‘prune dir’                                     排除 `dir' 下的所有文件
                                                
                                                
‘graft dir’                                     包括 `dir' 下的所有文件
                                                

此处的模式是 Unix 风格的 "glob" 模式: ‘*’ 匹配任意的常规文件名字符序列，
‘?’ 匹配任意单个常规文件名字符，而 ‘[range]’ 匹配 `range' 范围内的任意字
符 (例如 ‘a-z’, ‘a-zA-Z’, ‘a-f0-9_.’)。 “常规文件名字符”的定义取决于具体
平台：在 Unix 上是指正斜杠以外的任何字符；在 Windows 则是指反斜杠或冒号
以外的任何字符。


File: python.info,  Node: API参考引用,  Prev: 命令参考,  Up: 分发 Python 模块（遗留版本）

17.9 API参考引用
================

参见
....

New and changed setup.py arguments in setuptools(1)

     The ‘setuptools’ project adds new capabilities to the ‘setup’
     function and other APIs, makes the API consistent across different
     Python versions, and is hence recommended over using ‘distutils’
     directly.

     注解: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

* Menu:

* distutils.core: distutils core --- 分发包功能的核心. 分发包功能的核心
* distutils.ccompiler: distutils ccompiler --- CCompiler基类. CCompiler基类
* distutils.unixccompiler: distutils unixccompiler --- Unix C Compiler. Unix C Compiler
* distutils.msvccompiler: distutils msvccompiler --- Microsoft Compiler. Microsoft Compiler
* distutils.bcppcompiler: distutils bcppcompiler --- Borland Compiler. Borland Compiler
* distutils.cygwincompiler: distutils cygwincompiler --- Cygwin Compiler. Cygwin Compiler
* distutils.archive_util: distutils archive_util --- Archiving utilities. Archiving utilities
* distutils.dep_util: distutils dep_util --- Dependency checking. Dependency checking
* distutils.dir_util: distutils dir_util --- Directory tree operations. Directory tree operations
* distutils.file_util: distutils file_util --- Single file operations. Single file operations
* distutils.util: distutils util --- Miscellaneous other utility functions. Miscellaneous other utility functions
* distutils.dist: distutils dist --- The Distribution class. The Distribution class
* distutils.extension: distutils extension --- The Extension class. The Extension class
* distutils.debug: distutils debug --- Distutils debug mode. Distutils debug mode
* distutils.errors: distutils errors --- Distutils exceptions. Distutils exceptions
* distutils.fancy_getopt: distutils fancy_getopt --- Wrapper around the standard getopt module. Wrapper around the standard getopt module
* distutils.filelist: distutils filelist --- The FileList class. The FileList class
* distutils.log: distutils log --- Simple PEP 282-style logging. Simple PEP 282-style logging
* distutils.spawn: distutils spawn --- Spawn a sub-process. Spawn a sub-process
* distutils.sysconfig: distutils sysconfig --- System configuration information. System configuration information
* distutils.text_file: distutils text_file --- The TextFile class. The TextFile class
* distutils.version: distutils version --- Version number classes. Version number classes
* distutils.cmd: distutils cmd --- Abstract base class for Distutils commands. Abstract base class for Distutils commands
* Creating a new Distutils command::
* distutils.command: distutils command --- Individual Distutils commands. Individual Distutils commands
* distutils.command.bdist: distutils command bdist --- Build a binary installer. Build a binary installer
* distutils.command.bdist_packager: distutils command bdist_packager --- Abstract base class for packagers. Abstract base class for packagers
* distutils.command.bdist_dumb: distutils command bdist_dumb --- Build a "dumb" installer. Build a "dumb" installer
* distutils.command.bdist_msi: distutils command bdist_msi --- Build a Microsoft Installer binary package. Build a Microsoft Installer binary package
* distutils.command.bdist_rpm: distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM. Build a binary distribution as a Redhat RPM and
                               SRPM
* distutils.command.bdist_wininst: distutils command bdist_wininst --- Build a Windows installer. Build a Windows installer
* distutils.command.sdist: distutils command sdist --- Build a source distribution. Build a source distribution
* distutils.command.build: distutils command build --- Build all files of a package. Build all files of a package
* distutils.command.build_clib: distutils command build_clib --- Build any C libraries in a package. Build any C libraries in a package
* distutils.command.build_ext: distutils command build_ext --- Build any extensions in a package. Build any extensions in a package
* distutils.command.build_py: distutils command build_py --- Build the py/ pyc files of a package. Build the .py/.pyc files of a package
* distutils.command.build_scripts: distutils command build_scripts --- Build the scripts of a package. Build the scripts of a package
* distutils.command.clean: distutils command clean --- Clean a package build area. Clean a package build area
* distutils.command.config: distutils command config --- Perform package configuration. Perform package configuration
* distutils.command.install: distutils command install --- Install a package. Install a package
* distutils.command.install_data: distutils command install_data --- Install data files from a package. Install data files from a package
* distutils.command.install_headers: distutils command install_headers --- Install C/C++ header files from a package. Install C/C++ header files from a package
* distutils.command.install_lib: distutils command install_lib --- Install library files from a package. Install library files from a package
* distutils.command.install_scripts: distutils command install_scripts --- Install script files from a package. Install script files from a package
* distutils.command.register: distutils command register --- Register a module with the Python Package Index. Register a module with the Python Package Index
* distutils.command.check: distutils command check --- Check the meta-data of a package. Check the meta-data of a package

   ---------- Footnotes ----------

   (1) 
https://setuptools.readthedocs.io/en/latest/setuptools.html#new-and-changed-setup-keywords


File: python.info,  Node: distutils core --- 分发包功能的核心,  Next: distutils ccompiler --- CCompiler基类,  Up: API参考引用

17.9.1 ‘distutils.core’ — 分发包功能的核心
------------------------------------------

The *note distutils.core: 54. 是为了使用 Distutils 工具唯一要安装的模块
。它提供函数 *note setup(): 3b7a. （该函数被 setup 脚本调用）。间接提供
了类 ‘distutils.dist.Distribution’ 和 *note distutils.cmd.Command: 43a9.

 -- 函数: distutils.core.setup (arguments)

     The basic do-everything function that does most everything you
     could ever ask for from a Distutils method.

     The setup function takes a large number of arguments.  These are
     laid out in the following table.

     参数名称                 值                                   type
                                                                   
     --------------------------------------------------------------------------------------------------------------------------------
                                                                   
     `name'                   包的名字                             字符串
                                                                   
                                                                   
     `version'                包的版本号；参见                     字符串
                              *note distutils.version: 66.         
                              
                                                                   
     `description'            单行的包的描述                       字符串
                                                                   
                                                                   
     `long_description'       更长的包描述                         字符串
                                                                   
                                                                   
     `author'                 包的作者                             字符串
                                                                   
                                                                   
     `author_email'           包的作者的电子邮件                   字符串
                                                                   
                                                                   
     `maintainer'             The name of the current              字符串
                              maintainer, if different from the    
                              author.  Note that if the
                              maintainer is provided, distutils
                              will use it as the author in
                              ‘PKG-INFO’
                              
                                                                   
     `maintainer_email'       当前维护者的电子邮件地址，如果不同   字符串
                              与作者                               
                              
                                                                   
     `url'                    包的URL（主页）                      字符串
                                                                   
                                                                   
     `download_url'           包的下载地址                         字符串
                                                                   
                                                                   
     `packages'               A list of Python packages that       字符串列表
                              distutils will manipulate            
                              
                                                                   
     `py_modules'             distutils 会操作的 Python 模块列表   字符串列表
                                                                   
                                                                   
     `scripts'                要构建和安装的独立脚本文件的列表     字符串列表
                                                                   
                                                                   
     `ext_modules'            要构建的 Python 扩展的列表           类 *note distutils.core.Extension: 436f. 的实例的列表
                                                                   
                                                                   
     `classifiers'            包的类别列表                         a list of strings; valid classifiers are listed on PyPI(1).
                                                                   
                                                                   
     `distclass'              要使用的类                           *note distutils.core.Distribution: 43ba. 的子类
                              *note Distribution: 43ba. 类         
                              
                                                                   
     `script_name'            setup.py 脚本名称 —— 默认为          字符串
                              ‘sys.argv[0]’                        
                              
                                                                   
     `script_args'            提供给安装脚本的参数                 字符串列表
                                                                   
                                                                   
     `options'                安装脚本的默认选项                   字典
                                                                   
                                                                   
     `license'                包的许可证                           字符串
                                                                   
                                                                   
     `keywords'               Descriptive meta-data, see PEP       字符串列表或逗号分隔的字符串
                              314(2)                               
                              
                                                                   
     `platforms'                                                   字符串列表或逗号分隔的字符串
                                                                   
                                                                   
     `cmdclass'               A mapping of command names to        字典
                              *note Command: 43bb. subclasses      
                              
                                                                   
     `data_files'             要安装的数据文件列表                 列表
                                                                   
                                                                   
     `package_dir'            A mapping of package to directory    字典
                              names                                
                              

 -- 函数: distutils.core.run_setup (script_name[, script_args=None,
          stop_after='run'])

     Run a setup script in a somewhat controlled environment, and return
     the ‘distutils.dist.Distribution’ instance that drives things.
     This is useful if you need to find out the distribution meta-data
     (passed as keyword args from `script' to *note setup(): 3b7a.), or
     the contents of the config files or command-line.

     `script_name' is a file that will be read and run with *note
     exec(): c4c.  ‘sys.argv[0]’ will be replaced with `script' for the
     duration of the call.  `script_args' is a list of strings; if
     supplied, ‘sys.argv[1:]’ will be replaced by `script_args' for the
     duration of the call.

     `stop_after' tells *note setup(): 3b7a. when to stop processing;
     possible values:

     值                  描述
                         
     ----------------------------------------------------------------------
                         
     `init'              Stop after the *note Distribution: 43ba.
                         instance has been created and populated with
                         the keyword arguments to *note setup(): 3b7a.
                         
                         
     `config'            Stop after config files have been parsed (and
                         their data stored in the
                         *note Distribution: 43ba. instance)
                         
                         
     `commandline'       Stop after the command-line (‘sys.argv[1:]’ or
                         `script_args') have been parsed (and the data
                         stored in the *note Distribution: 43ba.
                         instance.)
                         
                         
     `run'               Stop after all commands have been run (the same
                         as if *note setup(): 3b7a. had been called in
                         the usual way).  This is the default value.
                         

In addition, the *note distutils.core: 54. module exposed a number of
classes that live elsewhere.

   * ‘Extension’ from *note distutils.extension: 5b.

   * *note Command: 43a9. from *note distutils.cmd: 3d.

   * ‘Distribution’ from *note distutils.dist: 59.

A short description of each of these follows, but see the relevant
module for the full reference.

 -- 类: distutils.core.Extension

     The Extension class describes a single C or C++ extension module in
     a setup script.  It accepts the following keyword arguments in its
     constructor:

     参数名称                     值                                   type
                                                                       
     --------------------------------------------------------------------------------------------------
                                                                       
     `name'                       the full name of the extension,      字符串
                                  including any packages — ie.         
                                  `not' a filename or pathname, but
                                  Python dotted name
                                  
                                                                       
     `sources'                    list of source filenames, relative   字符串列表
                                  to the distribution root (where      
                                  the setup script lives), in Unix
                                  form (slash-separated) for
                                  portability.  Source files may be
                                  C, C++, SWIG (.i),
                                  platform-specific resource files,
                                  or whatever else is recognized by
                                  the ‘build_ext’ command as source
                                  for a Python extension.
                                  
                                                                       
     `include_dirs'               list of directories to search for    字符串列表
                                  C/C++ header files (in Unix form     
                                  for portability)
                                  
                                                                       
     `define_macros'              list of macros to define; each       元组列表
                                  macro is defined using a 2-tuple     
                                  ‘(name, value)’, where `value' is
                                  either the string to define it to
                                  or ‘None’ to define it without a
                                  particular value (equivalent of
                                  ‘#define FOO’ in source or ‘-DFOO’
                                  on Unix C compiler command line)
                                  
                                                                       
     `undef_macros'               要明确取消定义的宏列表               字符串列表
                                                                       
                                                                       
     `library_dirs'               list of directories to search for    字符串列表
                                  C/C++ libraries at link time         
                                  
                                                                       
     `libraries'                  要链接的库名列表（不是文件名或路径   字符串列表
                                  ）                                   
                                  
                                                                       
     `runtime_library_dirs'       list of directories to search for    字符串列表
                                  C/C++ libraries at run time (for     
                                  shared extensions, this is when
                                  the extension is loaded)
                                  
                                                                       
     `extra_objects'              list of extra files to link with     字符串列表
                                  (eg.  object files not implied by    
                                  ’sources’, static library that
                                  must be explicitly specified,
                                  binary resource files, etc.)
                                  
                                                                       
     `extra_compile_args'         any extra platform- and              字符串列表
                                  compiler-specific information to     
                                  use when compiling the source
                                  files in ’sources’.  For platforms
                                  and compilers where a command line
                                  makes sense, this is typically a
                                  list of command-line arguments,
                                  but for other platforms it could
                                  be anything.
                                  
                                                                       
     `extra_link_args'            any extra platform- and              字符串列表
                                  compiler-specific information to     
                                  use when linking object files
                                  together to create the extension
                                  (or to create a new static Python
                                  interpreter).  Similar
                                  interpretation as for
                                  ’extra_compile_args’.
                                  
                                                                       
     `export_symbols'             list of symbols to be exported       字符串列表
                                  from a shared extension.  Not used   
                                  on all platforms, and not
                                  generally necessary for Python
                                  extensions, which typically export
                                  exactly one symbol: ‘init’ +
                                  extension_name.
                                  
                                                                       
     `depends'                    扩展名依赖的文件列表                 字符串列表
                                                                       
                                                                       
     `language'                   extension language (i.e.  ‘'c'’,     字符串
                                  ‘'c++'’, ‘'objc'’).  Will be         
                                  detected from the source
                                  extensions if not provided.
                                  
                                                                       
     `optional'                   指定扩展中的构建失败不应中止构建过   布尔
                                  程，而只是跳过扩展。                 
                                  

     在 3.8 版更改: On Unix, C extensions are no longer linked to
     libpython except on Android and Cygwin.

 -- 类: distutils.core.Distribution

     A *note Distribution: 43ba. describes how to build, install and
     package up a Python software package.

     See the *note setup(): 3b7a. function for a list of keyword
     arguments accepted by the Distribution constructor.  *note setup():
     3b7a. creates a Distribution instance.

     在 3.7 版更改: *note Distribution: 43ba. now warns if
     ‘classifiers’, ‘keywords’ and ‘platforms’ fields are not specified
     as a list or a string.

 -- 类: distutils.core.Command

     A *note Command: 43bb. class (or rather, an instance of one of its
     subclasses) implement a single distutils command.

   ---------- Footnotes ----------

   (1) https://pypi.org/classifiers

   (2) https://www.python.org/dev/peps/pep-0314


File: python.info,  Node: distutils ccompiler --- CCompiler基类,  Next: distutils unixccompiler --- Unix C Compiler,  Prev: distutils core --- 分发包功能的核心,  Up: API参考引用

17.9.2 ‘distutils.ccompiler’ — CCompiler基类
--------------------------------------------

This module provides the abstract base class for the *note CCompiler:
43be. classes.  A *note CCompiler: 43be. instance can be used for all
the compile and link steps needed to build a single project.  Methods
are provided to set options for the compiler — macro definitions,
include directories, link path, libraries and the like.

This module provides the following functions.

 -- 函数: distutils.ccompiler.gen_lib_options (compiler, library_dirs,
          runtime_library_dirs, libraries)

     Generate linker options for searching library directories and
     linking with specific libraries.  `libraries' and `library_dirs'
     are, respectively, lists of library names (not filenames!)  and
     search directories.  Returns a list of command-line options
     suitable for use with some compiler (depending on the two format
     strings passed in).

 -- 函数: distutils.ccompiler.gen_preprocess_options (macros,
          include_dirs)

     Generate C pre-processor options (‘-D’, ‘-U’, ‘-I’) as used by at
     least two types of compilers: the typical Unix compiler and Visual
     C++.  `macros' is the usual thing, a list of 1- or 2-tuples, where
     ‘(name,)’ means undefine (‘-U’) macro `name', and ‘(name, value)’
     means define (‘-D’) macro `name' to `value'.  `include_dirs' is
     just a list of directory names to be added to the header file
     search path (‘-I’).  Returns a list of command-line options
     suitable for either Unix compilers or Visual C++.

 -- 函数: distutils.ccompiler.get_default_compiler (osname, platform)

     Determine the default compiler to use for the given platform.

     `osname' should be one of the standard Python OS names (i.e.  the
     ones returned by ‘os.name’) and `platform' the common value
     returned by ‘sys.platform’ for the platform in question.

     The default values are ‘os.name’ and ‘sys.platform’ in case the
     parameters are not given.

 -- 函数: distutils.ccompiler.new_compiler (plat=None, compiler=None,
          verbose=0, dry_run=0, force=0)

     Factory function to generate an instance of some CCompiler subclass
     for the supplied platform/compiler combination.  `plat' defaults to
     ‘os.name’ (eg.  ‘'posix'’, ‘'nt'’), and `compiler' defaults to the
     default compiler for that platform.  Currently only ‘'posix'’ and
     ‘'nt'’ are supported, and the default compilers are "traditional
     Unix interface" (‘UnixCCompiler’ class) and Visual C++
     (‘MSVCCompiler’ class).  Note that it’s perfectly possible to ask
     for a Unix compiler object under Windows, and a Microsoft compiler
     object under Unix—if you supply a value for `compiler', `plat' is
     ignored.

 -- 函数: distutils.ccompiler.show_compilers ()

     Print list of available compilers (used by the ‘--help-compiler’
     options to ‘build’, ‘build_ext’, ‘build_clib’).

 -- 类: distutils.ccompiler.CCompiler ([verbose=0, dry_run=0, force=0])

     The abstract base class *note CCompiler: 43be. defines the
     interface that must be implemented by real compiler classes.  The
     class also has some utility methods used by several compiler
     classes.

     The basic idea behind a compiler abstraction class is that each
     instance can be used for all the compile/link steps in building a
     single project.  Thus, attributes common to all of those compile
     and link steps — include directories, macros to define, libraries
     to link against, etc.  — are attributes of the compiler instance.
     To allow for variability in how individual files are treated, most
     of those attributes may be varied on a per-compilation or per-link
     basis.

     The constructor for each subclass creates an instance of the
     Compiler object.  Flags are `verbose' (show verbose output),
     `dry_run' (don’t actually execute the steps) and `force' (rebuild
     everything, regardless of dependencies).  All of these flags
     default to ‘0’ (off).  Note that you probably don’t want to
     instantiate *note CCompiler: 43be. or one of its subclasses
     directly - use the ‘distutils.CCompiler.new_compiler()’ factory
     function instead.

     The following methods allow you to manually alter compiler options
     for the instance of the Compiler class.

      -- 方法: add_include_dir (dir)

          Add `dir' to the list of directories that will be searched for
          header files.  The compiler is instructed to search
          directories in the order in which they are supplied by
          successive calls to *note add_include_dir(): 43c4.

      -- 方法: set_include_dirs (dirs)

          Set the list of directories that will be searched to `dirs' (a
          list of strings).  Overrides any preceding calls to *note
          add_include_dir(): 43c4.; subsequent calls to *note
          add_include_dir(): 43c4. add to the list passed to *note
          set_include_dirs(): 43c5.  This does not affect any list of
          standard include directories that the compiler may search by
          default.

      -- 方法: add_library (libname)

          Add `libname' to the list of libraries that will be included
          in all links driven by this compiler object.  Note that
          `libname' should *not* be the name of a file containing a
          library, but the name of the library itself: the actual
          filename will be inferred by the linker, the compiler, or the
          compiler class (depending on the platform).

          The linker will be instructed to link against libraries in the
          order they were supplied to *note add_library(): 43c6. and/or
          *note set_libraries(): 43c7.  It is perfectly valid to
          duplicate library names; the linker will be instructed to link
          against libraries as many times as they are mentioned.

      -- 方法: set_libraries (libnames)

          Set the list of libraries to be included in all links driven
          by this compiler object to `libnames' (a list of strings).
          This does not affect any standard system libraries that the
          linker may include by default.

      -- 方法: add_library_dir (dir)

          Add `dir' to the list of directories that will be searched for
          libraries specified to *note add_library(): 43c6. and *note
          set_libraries(): 43c7.  The linker will be instructed to
          search for libraries in the order they are supplied to *note
          add_library_dir(): 43c8. and/or *note set_library_dirs():
          43c9.

      -- 方法: set_library_dirs (dirs)

          Set the list of library search directories to `dirs' (a list
          of strings).  This does not affect any standard library search
          path that the linker may search by default.

      -- 方法: add_runtime_library_dir (dir)

          Add `dir' to the list of directories that will be searched for
          shared libraries at runtime.

      -- 方法: set_runtime_library_dirs (dirs)

          Set the list of directories to search for shared libraries at
          runtime to `dirs' (a list of strings).  This does not affect
          any standard search path that the runtime linker may search by
          default.

      -- 方法: define_macro (name[, value=None])

          Define a preprocessor macro for all compilations driven by
          this compiler object.  The optional parameter `value' should
          be a string; if it is not supplied, then the macro will be
          defined without an explicit value and the exact outcome
          depends on the compiler used.

      -- 方法: undefine_macro (name)

          Undefine a preprocessor macro for all compilations driven by
          this compiler object.  If the same macro is defined by *note
          define_macro(): 43cc. and undefined by *note undefine_macro():
          43cd. the last call takes precedence (including multiple
          redefinitions or undefinitions).  If the macro is
          redefined/undefined on a per-compilation basis (ie.  in the
          call to *note compile(): 1b5.), then that takes precedence.

      -- 方法: add_link_object (object)

          Add `object' to the list of object files (or analogues, such
          as explicitly named library files or the output of "resource
          compilers") to be included in every link driven by this
          compiler object.

      -- 方法: set_link_objects (objects)

          Set the list of object files (or analogues) to be included in
          every link to `objects'.  This does not affect any standard
          object files that the linker may include by default (such as
          system libraries).

     The following methods implement methods for autodetection of
     compiler options, providing some functionality similar to GNU
     ‘autoconf’.

      -- 方法: detect_language (sources)

          Detect the language of a given file, or list of files.  Uses
          the instance attributes ‘language_map’ (a dictionary), and
          ‘language_order’ (a list) to do the job.

      -- 方法: find_library_file (dirs, lib[, debug=0])

          Search the specified list of directories for a static or
          shared library file `lib' and return the full path to that
          file.  If `debug' is true, look for a debugging version (if
          that makes sense on the current platform).  Return ‘None’ if
          `lib' wasn’t found in any of the specified directories.

      -- 方法: has_function (funcname[, includes=None,
               include_dirs=None, libraries=None, library_dirs=None])

          Return a boolean indicating whether `funcname' is supported on
          the current platform.  The optional arguments can be used to
          augment the compilation environment by providing additional
          include files and paths and libraries and paths.

      -- 方法: library_dir_option (dir)

          Return the compiler option to add `dir' to the list of
          directories searched for libraries.

      -- 方法: library_option (lib)

          Return the compiler option to add `lib' to the list of
          libraries linked into the shared library or executable.

      -- 方法: runtime_library_dir_option (dir)

          Return the compiler option to add `dir' to the list of
          directories searched for runtime libraries.

      -- 方法: set_executables (**args)

          Define the executables (and options for them) that will be run
          to perform the various stages of compilation.  The exact set
          of executables that may be specified here depends on the
          compiler class (via the ’executables’ class attribute), but
          most will have:

          attribute – 属性   描述
                             
          ------------------------------------------------------------------
                             
          `compiler'         C/C++ 编译器
                             
                             
          `linker_so'        用于创建共享对象和库的链接器
                             
                             
          `linker_exe'       用于创建二进制可执行文件的链接器
                             
                             
          `archiver'         静态库创建者
                             

          On platforms with a command-line (Unix, DOS/Windows), each of
          these is a string that will be split into executable name and
          (optional) list of arguments.  (Splitting the string is done
          similarly to how Unix shells operate: words are delimited by
          spaces, but quotes and backslashes can override this.  See
          *note distutils.util.split_quoted(): 43d7.)

     The following methods invoke stages in the build process.

      -- 方法: compile (sources[, output_dir=None, macros=None,
               include_dirs=None, debug=0, extra_preargs=None,
               extra_postargs=None, depends=None])

          Compile one or more source files.  Generates object files
          (e.g.  transforms a ‘.c’ file to a ‘.o’ file.)

          `sources' must be a list of filenames, most likely C/C++
          files, but in reality anything that can be handled by a
          particular compiler and compiler class (eg.  ‘MSVCCompiler’
          can handle resource files in `sources').  Return a list of
          object filenames, one per source filename in `sources'.
          Depending on the implementation, not all source files will
          necessarily be compiled, but all corresponding object
          filenames will be returned.

          If `output_dir' is given, object files will be put under it,
          while retaining their original path component.  That is,
          ‘foo/bar.c’ normally compiles to ‘foo/bar.o’ (for a Unix
          implementation); if `output_dir' is `build', then it would
          compile to ‘build/foo/bar.o’.

          `macros', if given, must be a list of macro definitions.  A
          macro definition is either a ‘(name, value)’ 2-tuple or a
          ‘(name,)’ 1-tuple.  The former defines a macro; if the value
          is ‘None’, the macro is defined without an explicit value.
          The 1-tuple case undefines a macro.  Later
          definitions/redefinitions/undefinitions take precedence.

          `include_dirs', if given, must be a list of strings, the
          directories to add to the default include file search path for
          this compilation only.

          `debug' is a boolean; if true, the compiler will be instructed
          to output debug symbols in (or alongside) the object file(s).

          `extra_preargs' and `extra_postargs' are
          implementation-dependent.  On platforms that have the notion
          of a command-line (e.g.  Unix, DOS/Windows), they are most
          likely lists of strings: extra command-line arguments to
          prepend/append to the compiler command line.  On other
          platforms, consult the implementation class documentation.  In
          any event, they are intended as an escape hatch for those
          occasions when the abstract compiler framework doesn’t cut the
          mustard.

          `depends', if given, is a list of filenames that all targets
          depend on.  If a source file is older than any file in
          depends, then the source file will be recompiled.  This
          supports dependency tracking, but only at a coarse
          granularity.

          Raises ‘CompileError’ on failure.

      -- 方法: create_static_lib (objects, output_libname[,
               output_dir=None, debug=0, target_lang=None])

          Link a bunch of stuff together to create a static library
          file.  The "bunch of stuff" consists of the list of object
          files supplied as `objects', the extra object files supplied
          to *note add_link_object(): 43ce. and/or *note
          set_link_objects(): 43cf, the libraries supplied to *note
          add_library(): 43c6. and/or *note set_libraries(): 43c7, and
          the libraries supplied as `libraries' (if any).

          `output_libname' should be a library name, not a filename; the
          filename will be inferred from the library name.  `output_dir'
          is the directory where the library file will be put.

          `debug' is a boolean; if true, debugging information will be
          included in the library (note that on most platforms, it is
          the compile step where this matters: the `debug' flag is
          included here just for consistency).

          `target_lang' is the target language for which the given
          objects are being compiled.  This allows specific linkage time
          treatment of certain languages.

          Raises ‘LibError’ on failure.

      -- 方法: link (target_desc, objects, output_filename[,
               output_dir=None, libraries=None, library_dirs=None,
               runtime_library_dirs=None, export_symbols=None, debug=0,
               extra_preargs=None, extra_postargs=None, build_temp=None,
               target_lang=None])

          Link a bunch of stuff together to create an executable or
          shared library file.

          The "bunch of stuff" consists of the list of object files
          supplied as `objects'.  `output_filename' should be a
          filename.  If `output_dir' is supplied, `output_filename' is
          relative to it (i.e.  `output_filename' can provide directory
          components if needed).

          `libraries' is a list of libraries to link against.  These are
          library names, not filenames, since they’re translated into
          filenames in a platform-specific way (eg.  `foo' becomes
          ‘libfoo.a’ on Unix and ‘foo.lib’ on DOS/Windows).  However,
          they can include a directory component, which means the linker
          will look in that specific directory rather than searching all
          the normal locations.

          `library_dirs', if supplied, should be a list of directories
          to search for libraries that were specified as bare library
          names (ie.  no directory component).  These are on top of the
          system default and those supplied to *note add_library_dir():
          43c8. and/or *note set_library_dirs(): 43c9.
          `runtime_library_dirs' is a list of directories that will be
          embedded into the shared library and used to search for other
          shared libraries that *it* depends on at run-time.  (This may
          only be relevant on Unix.)

          `export_symbols' is a list of symbols that the shared library
          will export.  (This appears to be relevant only on Windows.)

          `debug' is as for *note compile(): 1b5. and *note
          create_static_lib(): 43d9, with the slight distinction that it
          actually matters on most platforms (as opposed to *note
          create_static_lib(): 43d9, which includes a `debug' flag
          mostly for form’s sake).

          `extra_preargs' and `extra_postargs' are as for *note
          compile(): 1b5. (except of course that they supply
          command-line arguments for the particular linker being used).

          `target_lang' is the target language for which the given
          objects are being compiled.  This allows specific linkage time
          treatment of certain languages.

          Raises ‘LinkError’ on failure.

      -- 方法: link_executable (objects, output_progname[,
               output_dir=None, libraries=None, library_dirs=None,
               runtime_library_dirs=None, debug=0, extra_preargs=None,
               extra_postargs=None, target_lang=None])

          Link an executable.  `output_progname' is the name of the file
          executable, while `objects' are a list of object filenames to
          link in.  Other arguments are as for the *note link(): 43da.
          method.

      -- 方法: link_shared_lib (objects, output_libname[,
               output_dir=None, libraries=None, library_dirs=None,
               runtime_library_dirs=None, export_symbols=None, debug=0,
               extra_preargs=None, extra_postargs=None, build_temp=None,
               target_lang=None])

          Link a shared library.  `output_libname' is the name of the
          output library, while `objects' is a list of object filenames
          to link in.  Other arguments are as for the *note link():
          43da. method.

      -- 方法: link_shared_object (objects, output_filename[,
               output_dir=None, libraries=None, library_dirs=None,
               runtime_library_dirs=None, export_symbols=None, debug=0,
               extra_preargs=None, extra_postargs=None, build_temp=None,
               target_lang=None])

          Link a shared object.  `output_filename' is the name of the
          shared object that will be created, while `objects' is a list
          of object filenames to link in.  Other arguments are as for
          the *note link(): 43da. method.

      -- 方法: preprocess (source[, output_file=None, macros=None,
               include_dirs=None, extra_preargs=None,
               extra_postargs=None])

          Preprocess a single C/C++ source file, named in `source'.
          Output will be written to file named `output_file', or
          `stdout' if `output_file' not supplied.  `macros' is a list of
          macro definitions as for *note compile(): 1b5, which will
          augment the macros set with *note define_macro(): 43cc. and
          *note undefine_macro(): 43cd.  `include_dirs' is a list of
          directory names that will be added to the default list, in the
          same way as *note add_include_dir(): 43c4.

          Raises ‘PreprocessError’ on failure.

     The following utility methods are defined by the *note CCompiler:
     43be. class, for use by the various concrete subclasses.

      -- 方法: executable_filename (basename[, strip_dir=0,
               output_dir=''])

          Returns the filename of the executable for the given
          `basename'.  Typically for non-Windows platforms this is the
          same as the basename, while Windows will get a ‘.exe’ added.

      -- 方法: library_filename (libname[, lib_type='static',
               strip_dir=0, output_dir=''])

          Returns the filename for the given library name on the current
          platform.  On Unix a library with `lib_type' of ‘'static'’
          will typically be of the form ‘liblibname.a’, while a
          `lib_type' of ‘'dynamic'’ will be of the form ‘liblibname.so’.

      -- 方法: object_filenames (source_filenames[, strip_dir=0,
               output_dir=''])

          Returns the name of the object files for the given source
          files.  `source_filenames' should be a list of filenames.

      -- 方法: shared_object_filename (basename[, strip_dir=0,
               output_dir=''])

          Returns the name of a shared object file for the given file
          name `basename'.

      -- 方法: execute (func, args[, msg=None, level=1])

          Invokes *note distutils.util.execute(): 43e4.  This method
          invokes a Python function `func' with the given arguments
          `args', after logging and taking into account the `dry_run'
          flag.

      -- 方法: spawn (cmd)

          Invokes ‘distutils.util.spawn()’.  This invokes an external
          process to run the given command.

      -- 方法: mkpath (name[, mode=511])

          Invokes *note distutils.dir_util.mkpath(): 43e7.  This creates
          a directory and any missing ancestor directories.

      -- 方法: move_file (src, dst)

          Invokes *note distutils.file_util.move_file(): 43e9.  Renames
          `src' to `dst'.

      -- 方法: announce (msg[, level=1])

          Write a message using ‘distutils.log.debug()’.

      -- 方法: warn (msg)

          Write a warning message `msg' to standard error.

      -- 方法: debug_print (msg)

          If the `debug' flag is set on this *note CCompiler: 43be.
          instance, print `msg' to standard output, otherwise do
          nothing.


File: python.info,  Node: distutils unixccompiler --- Unix C Compiler,  Next: distutils msvccompiler --- Microsoft Compiler,  Prev: distutils ccompiler --- CCompiler基类,  Up: API参考引用

17.9.3 ‘distutils.unixccompiler’ — Unix C Compiler
--------------------------------------------------

This module provides the ‘UnixCCompiler’ class, a subclass of
‘CCompiler’ that handles the typical Unix-style command-line C compiler:

   * macros defined with ‘-Dname[=value]’

   * macros undefined with ‘-Uname’

   * include search directories specified with ‘-Idir’

   * libraries specified with ‘-llib’

   * library search directories specified with ‘-Ldir’

   * compile handled by ‘cc’ (or similar) executable with ‘-c’ option:
     compiles ‘.c’ to ‘.o’

   * link static library handled by ‘ar’ command (possibly with
     ‘ranlib’)

   * link shared library handled by ‘cc’ ‘-shared’


File: python.info,  Node: distutils msvccompiler --- Microsoft Compiler,  Next: distutils bcppcompiler --- Borland Compiler,  Prev: distutils unixccompiler --- Unix C Compiler,  Up: API参考引用

17.9.4 ‘distutils.msvccompiler’ — Microsoft Compiler
----------------------------------------------------

This module provides ‘MSVCCompiler’, an implementation of the abstract
‘CCompiler’ class for Microsoft Visual Studio.  Typically, extension
modules need to be compiled with the same compiler that was used to
compile Python.  For Python 2.3 and earlier, the compiler was Visual
Studio 6.  For Python 2.4 and 2.5, the compiler is Visual Studio .NET
2003.

‘MSVCCompiler’ will normally choose the right compiler, linker etc.  on
its own.  To override this choice, the environment variables
`DISTUTILS_USE_SDK' and `MSSdk' must be both set.  `MSSdk' indicates
that the current environment has been setup by the SDK’s ‘SetEnv.Cmd’
script, or that the environment variables had been registered when the
SDK was installed; `DISTUTILS_USE_SDK' indicates that the distutils user
has made an explicit choice to override the compiler selection by
‘MSVCCompiler’.


File: python.info,  Node: distutils bcppcompiler --- Borland Compiler,  Next: distutils cygwincompiler --- Cygwin Compiler,  Prev: distutils msvccompiler --- Microsoft Compiler,  Up: API参考引用

17.9.5 ‘distutils.bcppcompiler’ — Borland Compiler
--------------------------------------------------

This module provides ‘BorlandCCompiler’, a subclass of the abstract
‘CCompiler’ class for the Borland C++ compiler.


File: python.info,  Node: distutils cygwincompiler --- Cygwin Compiler,  Next: distutils archive_util --- Archiving utilities,  Prev: distutils bcppcompiler --- Borland Compiler,  Up: API参考引用

17.9.6 ‘distutils.cygwincompiler’ — Cygwin Compiler
---------------------------------------------------

This module provides the ‘CygwinCCompiler’ class, a subclass of
‘UnixCCompiler’ that handles the Cygwin port of the GNU C compiler to
Windows.  It also contains the Mingw32CCompiler class which handles the
mingw32 port of GCC (same as cygwin in no-cygwin mode).


File: python.info,  Node: distutils archive_util --- Archiving utilities,  Next: distutils dep_util --- Dependency checking,  Prev: distutils cygwincompiler --- Cygwin Compiler,  Up: API参考引用

17.9.7 ‘distutils.archive_util’ — Archiving utilities
-----------------------------------------------------

This module provides a few functions for creating archive files, such as
tarballs or zipfiles.

 -- 函数: distutils.archive_util.make_archive (base_name, format[,
          root_dir=None, base_dir=None, verbose=0, dry_run=0])

     Create an archive file (eg.  ‘zip’ or ‘tar’).  `base_name' is the
     name of the file to create, minus any format-specific extension;
     `format' is the archive format: one of ‘zip’, ‘tar’, ‘gztar’,
     ‘bztar’, ‘xztar’, or ‘ztar’.  `root_dir' is a directory that will
     be the root directory of the archive; ie.  we typically ‘chdir’
     into `root_dir' before creating the archive.  `base_dir' is the
     directory where we start archiving from; ie.  `base_dir' will be
     the common prefix of all files and directories in the archive.
     `root_dir' and `base_dir' both default to the current directory.
     Returns the name of the archive file.

     在 3.5 版更改: 添加了对 ‘xztar’ 格式的支持

 -- 函数: distutils.archive_util.make_tarball (base_name, base_dir[,
          compress='gzip', verbose=0, dry_run=0])

     ’Create an (optional compressed) archive as a tar file from all
     files in and under `base_dir'.  `compress' must be ‘'gzip'’ (the
     default), ‘'bzip2'’, ‘'xz'’, ‘'compress'’, or ‘None’.  For the
     ‘'compress'’ method the compression utility named by ‘compress’
     must be on the default program search path, so this is probably
     Unix-specific.  The output tar file will be named ‘base_dir.tar’,
     possibly plus the appropriate compression extension (‘.gz’, ‘.bz2’,
     ‘.xz’ or ‘.Z’).  Return the output filename.

     在 3.5 版更改: Added support for the ‘xz’ compression.

 -- 函数: distutils.archive_util.make_zipfile (base_name, base_dir[,
          verbose=0, dry_run=0])

     Create a zip file from all files in and under `base_dir'.  The
     output zip file will be named `base_name' + ‘.zip’.  Uses either
     the *note zipfile: 143. Python module (if available) or the InfoZIP
     ‘zip’ utility (if installed and found on the default search path).
     If neither tool is available, raises ‘DistutilsExecError’.  Returns
     the name of the output zip file.


File: python.info,  Node: distutils dep_util --- Dependency checking,  Next: distutils dir_util --- Directory tree operations,  Prev: distutils archive_util --- Archiving utilities,  Up: API参考引用

17.9.8 ‘distutils.dep_util’ — Dependency checking
-------------------------------------------------

This module provides functions for performing simple, timestamp-based
dependency of files and groups of files; also, functions based entirely
on such timestamp dependency analysis.

 -- 函数: distutils.dep_util.newer (source, target)

     Return true if `source' exists and is more recently modified than
     `target', or if `source' exists and `target' doesn’t.  Return false
     if both exist and `target' is the same age or newer than `source'.
     Raise ‘DistutilsFileError’ if `source' does not exist.

 -- 函数: distutils.dep_util.newer_pairwise (sources, targets)

     Walk two filename lists in parallel, testing if each source is
     newer than its corresponding target.  Return a pair of lists
     (`sources', `targets') where source is newer than target, according
     to the semantics of *note newer(): 43f6.

 -- 函数: distutils.dep_util.newer_group (sources, target[,
          missing='error'])

     Return true if `target' is out-of-date with respect to any file
     listed in `sources'.  In other words, if `target' exists and is
     newer than every file in `sources', return false; otherwise return
     true.  `missing' controls what we do when a source file is missing;
     the default (‘'error'’) is to blow up with an *note OSError: 1d4.
     from inside *note os.stat(): 1f2.; if it is ‘'ignore'’, we silently
     drop any missing source files; if it is ‘'newer'’, any missing
     source files make us assume that `target' is out-of-date (this is
     handy in "dry-run" mode: it’ll make you pretend to carry out
     commands that wouldn’t work because inputs are missing, but that
     doesn’t matter because you’re not actually going to run the
     commands).


File: python.info,  Node: distutils dir_util --- Directory tree operations,  Next: distutils file_util --- Single file operations,  Prev: distutils dep_util --- Dependency checking,  Up: API参考引用

17.9.9 ‘distutils.dir_util’ — Directory tree operations
-------------------------------------------------------

This module provides functions for operating on directories and trees of
directories.

 -- 函数: distutils.dir_util.mkpath (name[, mode=0o777, verbose=0,
          dry_run=0])

     Create a directory and any missing ancestor directories.  If the
     directory already exists (or if `name' is the empty string, which
     means the current directory, which of course exists), then do
     nothing.  Raise ‘DistutilsFileError’ if unable to create some
     directory along the way (eg.  some sub-path exists, but is a file
     rather than a directory).  If `verbose' is true, print a one-line
     summary of each mkdir to stdout.  Return the list of directories
     actually created.

 -- 函数: distutils.dir_util.create_tree (base_dir, files[, mode=0o777,
          verbose=0, dry_run=0])

     Create all the empty directories under `base_dir' needed to put
     `files' there.  `base_dir' is just the name of a directory which
     doesn’t necessarily exist yet; `files' is a list of filenames to be
     interpreted relative to `base_dir'.  `base_dir' + the directory
     portion of every file in `files' will be created if it doesn’t
     already exist.  `mode', `verbose' and `dry_run' flags are as for
     *note mkpath(): 43e7.

 -- 函数: distutils.dir_util.copy_tree (src, dst[, preserve_mode=1,
          preserve_times=1, preserve_symlinks=0, update=0, verbose=0,
          dry_run=0])

     Copy an entire directory tree `src' to a new location `dst'.  Both
     `src' and `dst' must be directory names.  If `src' is not a
     directory, raise ‘DistutilsFileError’.  If `dst' does not exist, it
     is created with *note mkpath(): 43e7.  The end result of the copy
     is that every file in `src' is copied to `dst', and directories
     under `src' are recursively copied to `dst'.  Return the list of
     files that were copied or might have been copied, using their
     output name.  The return value is unaffected by `update' or
     `dry_run': it is simply the list of all files under `src', with the
     names changed to be under `dst'.

     `preserve_mode' and `preserve_times' are the same as for *note
     distutils.file_util.copy_file(): 43fc.; note that they only apply
     to regular files, not to directories.  If `preserve_symlinks' is
     true, symlinks will be copied as symlinks (on platforms that
     support them!); otherwise (the default), the destination of the
     symlink will be copied.  `update' and `verbose' are the same as for
     ‘copy_file()’.

     Files in `src' that begin with ‘.nfs’ are skipped (more information
     on these files is available in answer D2 of the NFS FAQ page(1)).

     在 3.3.1 版更改: NFS files are ignored.

 -- 函数: distutils.dir_util.remove_tree (directory[, verbose=0,
          dry_run=0])

     Recursively remove `directory' and all files and directories
     underneath it.  Any errors are ignored (apart from being reported
     to ‘sys.stdout’ if `verbose' is true).

   ---------- Footnotes ----------

   (1) http://nfs.sourceforge.net/#section_d


File: python.info,  Node: distutils file_util --- Single file operations,  Next: distutils util --- Miscellaneous other utility functions,  Prev: distutils dir_util --- Directory tree operations,  Up: API参考引用

17.9.10 ‘distutils.file_util’ — Single file operations
------------------------------------------------------

This module contains some utility functions for operating on individual
files.

 -- 函数: distutils.file_util.copy_file (src, dst[, preserve_mode=1,
          preserve_times=1, update=0, link=None, verbose=0, dry_run=0])

     Copy file `src' to `dst'.  If `dst' is a directory, then `src' is
     copied there with the same name; otherwise, it must be a filename.
     (If the file exists, it will be ruthlessly clobbered.)  If
     `preserve_mode' is true (the default), the file’s mode (type and
     permission bits, or whatever is analogous on the current platform)
     is copied.  If `preserve_times' is true (the default), the
     last-modified and last-access times are copied as well.  If
     `update' is true, `src' will only be copied if `dst' does not
     exist, or if `dst' does exist but is older than `src'.

     `link' allows you to make hard links (using *note os.link(): a3d.)
     or symbolic links (using *note os.symlink(): a43.) instead of
     copying: set it to ‘'hard'’ or ‘'sym'’; if it is ‘None’ (the
     default), files are copied.  Don’t set `link' on systems that don’t
     support it: *note copy_file(): 43fc. doesn’t check if hard or
     symbolic linking is available.  It uses ‘_copy_file_contents()’ to
     copy file contents.

     Return a tuple ‘(dest_name, copied)’: `dest_name' is the actual
     name of the output file, and `copied' is true if the file was
     copied (or would have been copied, if `dry_run' true).

 -- 函数: distutils.file_util.move_file (src, dst[, verbose, dry_run])

     Move file `src' to `dst'.  If `dst' is a directory, the file will
     be moved into it with the same name; otherwise, `src' is just
     renamed to `dst'.  Returns the new full name of the file.

          警告: Handles cross-device moves on Unix using *note
          copy_file(): 43fc.  What about other systems?

 -- 函数: distutils.file_util.write_file (filename, contents)

     Create a file called `filename' and write `contents' (a sequence of
     strings without line terminators) to it.


File: python.info,  Node: distutils util --- Miscellaneous other utility functions,  Next: distutils dist --- The Distribution class,  Prev: distutils file_util --- Single file operations,  Up: API参考引用

17.9.11 ‘distutils.util’ — Miscellaneous other utility functions
----------------------------------------------------------------

This module contains other assorted bits and pieces that don’t fit into
any other utility module.

 -- 函数: distutils.util.get_platform ()

     Return a string that identifies the current platform.  This is used
     mainly to distinguish platform-specific build directories and
     platform-specific built distributions.  Typically includes the OS
     name and version and the architecture (as supplied by
     ’os.uname()’), although the exact information included depends on
     the OS; e.g., on Linux, the kernel version isn’t particularly
     important.

     返回值的示例：

        * ‘linux-i586’

        * ‘linux-alpha’

        * ‘solaris-2.6-sun4u’

     For non-POSIX platforms, currently just returns ‘sys.platform’.

     For Mac OS X systems the OS version reflects the minimal version on
     which binaries will run (that is, the value of
     ‘MACOSX_DEPLOYMENT_TARGET’ during the build of Python), not the OS
     version of the current system.

     For universal binary builds on Mac OS X the architecture value
     reflects the universal binary status instead of the architecture of
     the current processor.  For 32-bit universal binaries the
     architecture is ‘fat’, for 64-bit universal binaries the
     architecture is ‘fat64’, and for 4-way universal binaries the
     architecture is ‘universal’.  Starting from Python 2.7 and Python
     3.2 the architecture ‘fat3’ is used for a 3-way universal build
     (ppc, i386, x86_64) and ‘intel’ is used for a universal build with
     the i386 and x86_64 architectures

     Examples of returned values on Mac OS X:

        * ‘macosx-10.3-ppc’

        * ‘macosx-10.3-fat’

        * ‘macosx-10.5-universal’

        * ‘macosx-10.6-intel’

 -- 函数: distutils.util.convert_path (pathname)

     Return ’pathname’ as a name that will work on the native
     filesystem, i.e.  split it on ’/’ and put it back together again
     using the current directory separator.  Needed because filenames in
     the setup script are always supplied in Unix style, and have to be
     converted to the local convention before we can actually use them
     in the filesystem.  Raises *note ValueError: 1fc. on non-Unix-ish
     systems if `pathname' either starts or ends with a slash.

 -- 函数: distutils.util.change_root (new_root, pathname)

     Return `pathname' with `new_root' prepended.  If `pathname' is
     relative, this is equivalent to ‘os.path.join(new_root,pathname)’
     Otherwise, it requires making `pathname' relative and then joining
     the two, which is tricky on DOS/Windows.

 -- 函数: distutils.util.check_environ ()

     Ensure that ’os.environ’ has all the environment variables we
     guarantee that users can use in config files, command-line options,
     etc.  Currently this includes:

        * ‘HOME’ - user’s home directory (Unix only)

        * ‘PLAT’ - description of the current platform, including
          hardware and OS (see *note get_platform(): 4401.)

 -- 函数: distutils.util.subst_vars (s, local_vars)

     Perform shell/Perl-style variable substitution on `s'.  Every
     occurrence of ‘$’ followed by a name is considered a variable, and
     variable is substituted by the value found in the `local_vars'
     dictionary, or in ‘os.environ’ if it’s not in `local_vars'.
     `os.environ' is first checked/augmented to guarantee that it
     contains certain values: see *note check_environ(): 4404.  Raise
     *note ValueError: 1fc. for any variables not found in either
     `local_vars' or ‘os.environ’.

     Note that this is not a fully-fledged string interpolation
     function.  A valid ‘$variable’ can consist only of upper and lower
     case letters, numbers and an underscore.  No { } or ( ) style
     quoting is available.

 -- 函数: distutils.util.split_quoted (s)

     Split a string up according to Unix shell-like rules for quotes and
     backslashes.  In short: words are delimited by spaces, as long as
     those spaces are not escaped by a backslash, or inside a quoted
     string.  Single and double quotes are equivalent, and the quote
     characters can be backslash-escaped.  The backslash is stripped
     from any two-character escape sequence, leaving only the escaped
     character.  The quote characters are stripped from any quoted
     string.  Returns a list of words.

 -- 函数: distutils.util.execute (func, args[, msg=None, verbose=0,
          dry_run=0])

     Perform some action that affects the outside world (for instance,
     writing to the filesystem).  Such actions are special because they
     are disabled by the `dry_run' flag.  This method takes care of all
     that bureaucracy for you; all you have to do is supply the function
     to call and an argument tuple for it (to embody the "external
     action" being performed), and an optional message to print.

 -- 函数: distutils.util.strtobool (val)

     Convert a string representation of truth to true (1) or false (0).

     True values are ‘y’, ‘yes’, ‘t’, ‘true’, ‘on’ and ‘1’; false values
     are ‘n’, ‘no’, ‘f’, ‘false’, ‘off’ and ‘0’.  Raises *note
     ValueError: 1fc. if `val' is anything else.

 -- 函数: distutils.util.byte_compile (py_files[, optimize=0, force=0,
          prefix=None, base_dir=None, verbose=1, dry_run=0,
          direct=None])

     Byte-compile a collection of Python source files to ‘.pyc’ files in
     a ‘__pycache__’ subdirectory (see PEP 3147(1) and PEP 488(2)).
     `py_files' is a list of files to compile; any files that don’t end
     in ‘.py’ are silently skipped.  `optimize' must be one of the
     following:

        * ‘0’ - don’t optimize

        * ‘1’ - normal optimization (like ‘python -O’)

        * ‘2’ - extra optimization (like ‘python -OO’)

     If `force' is true, all files are recompiled regardless of
     timestamps.

     The source filename encoded in each *note bytecode: 61d. file
     defaults to the filenames listed in `py_files'; you can modify
     these with `prefix' and `basedir'.  `prefix' is a string that will
     be stripped off of each source filename, and `base_dir' is a
     directory name that will be prepended (after `prefix' is stripped).
     You can supply either or both (or neither) of `prefix' and
     `base_dir', as you wish.

     If `dry_run' is true, doesn’t actually do anything that would
     affect the filesystem.

     Byte-compilation is either done directly in this interpreter
     process with the standard *note py_compile: d8. module, or
     indirectly by writing a temporary script and executing it.
     Normally, you should let *note byte_compile(): 4407. figure out to
     use direct compilation or not (see the source for details).  The
     `direct' flag is used by the script generated in indirect mode;
     unless you know what you’re doing, leave it set to ‘None’.

     在 3.2.3 版更改: Create ‘.pyc’ files with an *note import magic
     tag: 3ae7. in their name, in a ‘__pycache__’ subdirectory instead
     of files without tag in the current directory.

     在 3.5 版更改: Create ‘.pyc’ files according to PEP 488(3).

 -- 函数: distutils.util.rfc822_escape (header)

     Return a version of `header' escaped for inclusion in an RFC 822(4)
     header, by ensuring there are 8 spaces space after each newline.
     Note that it does no other modification of the string.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147

   (2) https://www.python.org/dev/peps/pep-0488

   (3) https://www.python.org/dev/peps/pep-0488

   (4) https://tools.ietf.org/html/rfc822.html


File: python.info,  Node: distutils dist --- The Distribution class,  Next: distutils extension --- The Extension class,  Prev: distutils util --- Miscellaneous other utility functions,  Up: API参考引用

17.9.12 ‘distutils.dist’ — The Distribution class
-------------------------------------------------

This module provides the *note Distribution: 43ba. class, which
represents the module distribution being built/installed/distributed.


File: python.info,  Node: distutils extension --- The Extension class,  Next: distutils debug --- Distutils debug mode,  Prev: distutils dist --- The Distribution class,  Up: API参考引用

17.9.13 ‘distutils.extension’ — The Extension class
---------------------------------------------------

This module provides the ‘Extension’ class, used to describe C/C++
extension modules in setup scripts.


File: python.info,  Node: distutils debug --- Distutils debug mode,  Next: distutils errors --- Distutils exceptions,  Prev: distutils extension --- The Extension class,  Up: API参考引用

17.9.14 ‘distutils.debug’ — Distutils debug mode
------------------------------------------------

本模块提供DEBUG标识。


File: python.info,  Node: distutils errors --- Distutils exceptions,  Next: distutils fancy_getopt --- Wrapper around the standard getopt module,  Prev: distutils debug --- Distutils debug mode,  Up: API参考引用

17.9.15 ‘distutils.errors’ — Distutils exceptions
-------------------------------------------------

Provides exceptions used by the Distutils modules.  Note that Distutils
modules may raise standard exceptions; in particular, SystemExit is
usually raised for errors that are obviously the end-user’s fault (eg.
bad command-line arguments).

This module is safe to use in ‘from ... import *’ mode; it only exports
symbols whose names start with ‘Distutils’ and end with ‘Error’.


File: python.info,  Node: distutils fancy_getopt --- Wrapper around the standard getopt module,  Next: distutils filelist --- The FileList class,  Prev: distutils errors --- Distutils exceptions,  Up: API参考引用

17.9.16 ‘distutils.fancy_getopt’ — Wrapper around the standard getopt module
----------------------------------------------------------------------------

This module provides a wrapper around the standard *note getopt: 87.
module that provides the following additional features:

   * short and long options are tied together

   * options have help strings, so *note fancy_getopt(): 440e. could
     potentially create a complete usage summary

   * options set attributes of a passed-in object

   * boolean options can have "negative aliases" — eg.  if ‘--quiet’ is
     the "negative alias" of ‘--verbose’, then ‘--quiet’ on the command
     line sets `verbose' to false.

 -- 函数: distutils.fancy_getopt.fancy_getopt (options, negative_opt,
          object, args)

     Wrapper function.  `options' is a list of ‘(long_option,
     short_option, help_string)’ 3-tuples as described in the
     constructor for *note FancyGetopt: 440f.  `negative_opt' should be
     a dictionary mapping option names to option names, both the key and
     value should be in the `options' list.  `object' is an object which
     will be used to store values (see the *note getopt(): 87. method of
     the *note FancyGetopt: 440f. class).  `args' is the argument list.
     Will use ‘sys.argv[1:]’ if you pass ‘None’ as `args'.

 -- 函数: distutils.fancy_getopt.wrap_text (text, width)

     Wraps `text' to less than `width' wide.

 -- 类: distutils.fancy_getopt.FancyGetopt ([option_table=None])

     The option_table is a list of 3-tuples: ‘(long_option,
     short_option, help_string)’

     If an option takes an argument, its `long_option' should have ‘'='’
     appended; `short_option' should just be a single character, no
     ‘':'’ in any case.  `short_option' should be ‘None’ if a
     `long_option' doesn’t have a corresponding `short_option'.  All
     option tuples must have long options.

The *note FancyGetopt: 440f. class provides the following methods:

 -- 方法: FancyGetopt.getopt ([args=None, object=None])

     Parse command-line options in args.  Store as attributes on
     `object'.

     If `args' is ‘None’ or not supplied, uses ‘sys.argv[1:]’.  If
     `object' is ‘None’ or not supplied, creates a new ‘OptionDummy’
     instance, stores option values there, and returns a tuple ‘(args,
     object)’.  If `object' is supplied, it is modified in place and
     *note getopt(): 87. just returns `args'; in both cases, the
     returned `args' is a modified copy of the passed-in `args' list,
     which is left untouched.

 -- 方法: FancyGetopt.get_option_order ()

     Returns the list of ‘(option, value)’ tuples processed by the
     previous run of *note getopt(): 87. Raises *note RuntimeError: 2bb.
     if *note getopt(): 87. hasn’t been called yet.

 -- 方法: FancyGetopt.generate_help ([header=None])

     Generate help text (a list of strings, one per suggested line of
     output) from the option table for this *note FancyGetopt: 440f.
     object.

     If supplied, prints the supplied `header' at the top of the help.


File: python.info,  Node: distutils filelist --- The FileList class,  Next: distutils log --- Simple PEP 282-style logging,  Prev: distutils fancy_getopt --- Wrapper around the standard getopt module,  Up: API参考引用

17.9.17 ‘distutils.filelist’ — The FileList class
-------------------------------------------------

This module provides the ‘FileList’ class, used for poking about the
filesystem and building lists of files.


File: python.info,  Node: distutils log --- Simple PEP 282-style logging,  Next: distutils spawn --- Spawn a sub-process,  Prev: distutils filelist --- The FileList class,  Up: API参考引用

17.9.18 ‘distutils.log’ — Simple `PEP 282'-style logging
--------------------------------------------------------


File: python.info,  Node: distutils spawn --- Spawn a sub-process,  Next: distutils sysconfig --- System configuration information,  Prev: distutils log --- Simple PEP 282-style logging,  Up: API参考引用

17.9.19 ‘distutils.spawn’ — Spawn a sub-process
-----------------------------------------------

This module provides the ‘spawn()’ function, a front-end to various
platform-specific functions for launching another program in a
sub-process.  Also provides ‘find_executable()’ to search the path for a
given executable name.


File: python.info,  Node: distutils sysconfig --- System configuration information,  Next: distutils text_file --- The TextFile class,  Prev: distutils spawn --- Spawn a sub-process,  Up: API参考引用

17.9.20 ‘distutils.sysconfig’ — System configuration information
----------------------------------------------------------------

The *note distutils.sysconfig: 62. module provides access to Python’s
low-level configuration information.  The specific configuration
variables available depend heavily on the platform and configuration.
The specific variables depend on the build process for the specific
version of Python being run; the variables are those found in the
‘Makefile’ and configuration header that are installed with Python on
Unix systems.  The configuration header is called ‘pyconfig.h’ for
Python versions starting with 2.2, and ‘config.h’ for earlier versions
of Python.

Some additional functions are provided which perform some useful
manipulations for other parts of the *note distutils: 39. package.

 -- 数据: distutils.sysconfig.PREFIX

     The result of ‘os.path.normpath(sys.prefix)’.

 -- 数据: distutils.sysconfig.EXEC_PREFIX

     The result of ‘os.path.normpath(sys.exec_prefix)’.

 -- 函数: distutils.sysconfig.get_config_var (name)

     Return the value of a single variable.  This is equivalent to
     ‘get_config_vars().get(name)’.

 -- 函数: distutils.sysconfig.get_config_vars (...)

     Return a set of variable definitions.  If there are no arguments,
     this returns a dictionary mapping names of configuration variables
     to values.  If arguments are provided, they should be strings, and
     the return value will be a sequence giving the associated values.
     If a given name does not have a corresponding value, ‘None’ will be
     included for that variable.

 -- 函数: distutils.sysconfig.get_config_h_filename ()

     Return the full path name of the configuration header.  For Unix,
     this will be the header generated by the ‘configure’ script; for
     other platforms the header will have been supplied directly by the
     Python source distribution.  The file is a platform-specific text
     file.

 -- 函数: distutils.sysconfig.get_makefile_filename ()

     Return the full path name of the ‘Makefile’ used to build Python.
     For Unix, this will be a file generated by the ‘configure’ script;
     the meaning for other platforms will vary.  The file is a
     platform-specific text file, if it exists.  This function is only
     useful on POSIX platforms.

 -- 函数: distutils.sysconfig.get_python_inc ([plat_specific[, prefix]])

     Return the directory for either the general or platform-dependent C
     include files.  If `plat_specific' is true, the platform-dependent
     include directory is returned; if false or omitted, the
     platform-independent directory is returned.  If `prefix' is given,
     it is used as either the prefix instead of *note PREFIX: 4418, or
     as the exec-prefix instead of *note EXEC_PREFIX: 4419. if
     `plat_specific' is true.

 -- 函数: distutils.sysconfig.get_python_lib ([plat_specific[,
          standard_lib[, prefix]]])

     Return the directory for either the general or platform-dependent
     library installation.  If `plat_specific' is true, the
     platform-dependent include directory is returned; if false or
     omitted, the platform-independent directory is returned.  If
     `prefix' is given, it is used as either the prefix instead of *note
     PREFIX: 4418, or as the exec-prefix instead of *note EXEC_PREFIX:
     4419. if `plat_specific' is true.  If `standard_lib' is true, the
     directory for the standard library is returned rather than the
     directory for the installation of third-party extensions.

The following function is only intended for use within the *note
distutils: 39. package.

 -- 函数: distutils.sysconfig.customize_compiler (compiler)

     Do any platform-specific customization of a *note
     distutils.ccompiler.CCompiler: 43be. instance.

     This function is only needed on Unix at this time, but should be
     called consistently to support forward-compatibility.  It inserts
     the information that varies across Unix flavors and is stored in
     Python’s ‘Makefile’.  This information includes the selected
     compiler, compiler and linker options, and the extension used by
     the linker for shared objects.

This function is even more special-purpose, and should only be used from
Python’s own build procedures.

 -- 函数: distutils.sysconfig.set_python_build ()

     Inform the *note distutils.sysconfig: 62. module that it is being
     used as part of the build process for Python.  This changes a lot
     of relative locations for files, allowing them to be located in the
     build area rather than in an installed Python.


File: python.info,  Node: distutils text_file --- The TextFile class,  Next: distutils version --- Version number classes,  Prev: distutils sysconfig --- System configuration information,  Up: API参考引用

17.9.21 ‘distutils.text_file’ — The TextFile class
--------------------------------------------------

This module provides the *note TextFile: 4423. class, which gives an
interface to text files that (optionally) takes care of stripping
comments, ignoring blank lines, and joining lines with backslashes.

 -- 类: distutils.text_file.TextFile ([filename=None, file=None,
          **options])

     This class provides a file-like object that takes care of all the
     things you commonly want to do when processing a text file that has
     some line-by-line syntax: strip comments (as long as ‘#’ is your
     comment character), skip blank lines, join adjacent lines by
     escaping the newline (ie.  backslash at end of line), strip leading
     and/or trailing whitespace.  All of these are optional and
     independently controllable.

     The class provides a *note warn(): 4424. method so you can generate
     warning messages that report physical line number, even if the
     logical line in question spans multiple physical lines.  Also
     provides *note unreadline(): 4425. for implementing line-at-a-time
     lookahead.

     *note TextFile: 4423. instances are create with either `filename',
     `file', or both.  *note RuntimeError: 2bb. is raised if both are
     ‘None’.  `filename' should be a string, and `file' a file object
     (or something that provides *note readline(): df. and *note
     close(): 4426. methods).  It is recommended that you supply at
     least `filename', so that *note TextFile: 4423. can include it in
     warning messages.  If `file' is not supplied, *note TextFile: 4423.
     creates its own using the *note open(): 4f8. built-in function.

     The options are all boolean, and affect the values returned by
     *note readline(): df.

     选项名称               描述                                 默认值
                                                                 
     --------------------------------------------------------------------------
                                                                 
     `strip_comments'       strip from ‘'#'’ to end-of-line,     true
                            as well as any whitespace leading    
                            up to the ‘'#'’—unless it is
                            escaped by a backslash
                            
                                                                 
     `lstrip_ws'            strip leading whitespace from each   false
                            line before returning it             
                            
                                                                 
     `rstrip_ws'            strip trailing whitespace            true
                            (including line terminator!)  from   
                            each line before returning it.
                            
                                                                 
     `skip_blanks'          skip lines that are empty *after*    true
                            stripping comments and whitespace.   
                            (If both lstrip_ws and rstrip_ws
                            are false, then some lines may
                            consist of solely whitespace:
                            these will *not* be skipped, even
                            if `skip_blanks' is true.)
                            
                                                                 
     `join_lines'           if a backslash is the last           false
                            non-newline character on a line      
                            after stripping comments and
                            whitespace, join the following
                            line to it to form one logical
                            line; if N consecutive lines end
                            with a backslash, then N+1
                            physical lines will be joined to
                            form one logical line.
                            
                                                                 
     `collapse_join'        strip leading whitespace from        false
                            lines that are joined to their       
                            predecessor; only matters if
                            ‘(join_lines and not lstrip_ws)’
                            

     Note that since `rstrip_ws' can strip the trailing newline, the
     semantics of *note readline(): df. must differ from those of the
     built-in file object’s *note readline(): df. method!  In
     particular, *note readline(): df. returns ‘None’ for end-of-file:
     an empty string might just be a blank line (or an all-whitespace
     line), if `rstrip_ws' is true but `skip_blanks' is not.

      -- 方法: open (filename)

          Open a new file `filename'.  This overrides any `file' or
          `filename' constructor arguments.

      -- 方法: close ()

          Close the current file and forget everything we know about it
          (including the filename and the current line number).

      -- 方法: warn (msg[, line=None])

          Print (to stderr) a warning message tied to the current
          logical line in the current file.  If the current logical line
          in the file spans multiple physical lines, the warning refers
          to the whole range, such as ‘"lines 3-5"’.  If `line' is
          supplied, it overrides the current line number; it may be a
          list or tuple to indicate a range of physical lines, or an
          integer for a single physical line.

      -- 方法: readline ()

          Read and return a single logical line from the current file
          (or from an internal buffer if lines have previously been
          "unread" with *note unreadline(): 4425.).  If the `join_lines'
          option is true, this may involve reading multiple physical
          lines concatenated into a single string.  Updates the current
          line number, so calling *note warn(): 4424. after *note
          readline(): df. emits a warning about the physical line(s)
          just read.  Returns ‘None’ on end-of-file, since the empty
          string can occur if `rstrip_ws' is true but `strip_blanks' is
          not.

      -- 方法: readlines ()

          Read and return the list of all logical lines remaining in the
          current file.  This updates the current line number to the
          last line of the file.

      -- 方法: unreadline (line)

          Push `line' (a string) onto an internal buffer that will be
          checked by future *note readline(): df. calls.  Handy for
          implementing a parser with line-at-a-time lookahead.  Note
          that lines that are "unread" with *note unreadline(): 4425.
          are not subsequently re-cleansed (whitespace stripped, or
          whatever) when read with *note readline(): df.  If multiple
          calls are made to *note unreadline(): 4425. before a call to
          *note readline(): df, the lines will be returned most in most
          recent first order.


File: python.info,  Node: distutils version --- Version number classes,  Next: distutils cmd --- Abstract base class for Distutils commands,  Prev: distutils text_file --- The TextFile class,  Up: API参考引用

17.9.22 ‘distutils.version’ — Version number classes
----------------------------------------------------


File: python.info,  Node: distutils cmd --- Abstract base class for Distutils commands,  Next: Creating a new Distutils command,  Prev: distutils version --- Version number classes,  Up: API参考引用

17.9.23 ‘distutils.cmd’ — Abstract base class for Distutils commands
--------------------------------------------------------------------

This module supplies the abstract base class *note Command: 43a9.

 -- 类: distutils.cmd.Command (dist)

     Abstract base class for defining command classes, the "worker bees"
     of the Distutils.  A useful analogy for command classes is to think
     of them as subroutines with local variables called `options'.  The
     options are declared in *note initialize_options(): 442c. and
     defined (given their final values) in *note finalize_options():
     442d, both of which must be defined by every command class.  The
     distinction between the two is necessary because option values
     might come from the outside world (command line, config file, ...),
     and any options dependent on other options must be computed after
     these outside influences have been processed — hence *note
     finalize_options(): 442d.  The body of the subroutine, where it
     does all its work based on the values of its options, is the *note
     run(): 442e. method, which must also be implemented by every
     command class.

     The class constructor takes a single argument `dist', a *note
     Distribution: 43ba. instance.


File: python.info,  Node: Creating a new Distutils command,  Next: distutils command --- Individual Distutils commands,  Prev: distutils cmd --- Abstract base class for Distutils commands,  Up: API参考引用

17.9.24 Creating a new Distutils command
----------------------------------------

This section outlines the steps to create a new Distutils command.

A new command lives in a module in the *note distutils.command: 3e.
package.  There is a sample template in that directory called
‘command_template’.  Copy this file to a new module with the same name
as the new command you’re implementing.  This module should implement a
class with the same name as the module (and the command).  So, for
instance, to create the command ‘peel_banana’ (so that users can run
‘setup.py peel_banana’), you’d copy ‘command_template’ to
‘distutils/command/peel_banana.py’, then edit it so that it’s
implementing the class ‘peel_banana’, a subclass of *note
distutils.cmd.Command: 43a9.

Subclasses of *note Command: 43a9. must define the following methods.

 -- 方法: Command.initialize_options ()

     Set default values for all the options that this command supports.
     Note that these defaults may be overridden by other commands, by
     the setup script, by config files, or by the command-line.  Thus,
     this is not the place to code dependencies between options;
     generally, *note initialize_options(): 442c. implementations are
     just a bunch of ‘self.foo = None’ assignments.

 -- 方法: Command.finalize_options ()

     Set final values for all the options that this command supports.
     This is always called as late as possible, ie.  after any option
     assignments from the command-line or from other commands have been
     done.  Thus, this is the place to code option dependencies: if
     `foo' depends on `bar', then it is safe to set `foo' from `bar' as
     long as `foo' still has the same value it was assigned in *note
     initialize_options(): 442c.

 -- 方法: Command.run ()

     A command’s raison d’etre: carry out the action it exists to
     perform, controlled by the options initialized in *note
     initialize_options(): 442c, customized by other commands, the setup
     script, the command-line, and config files, and finalized in *note
     finalize_options(): 442d.  All terminal output and filesystem
     interaction should be done by *note run(): 442e.

 -- 属性: Command.sub_commands

     `sub_commands' formalizes the notion of a "family" of commands,
     e.g.  ‘install’ as the parent with sub-commands ‘install_lib’,
     ‘install_headers’, etc.  The parent of a family of commands defines
     `sub_commands' as a class attribute; it’s a list of 2-tuples
     ‘(command_name, predicate)’, with `command_name' a string and
     `predicate' a function, a string or ‘None’.  `predicate' is a
     method of the parent command that determines whether the
     corresponding command is applicable in the current situation.
     (E.g.  ‘install_headers’ is only applicable if we have any C header
     files to install.)  If `predicate' is ‘None’, that command is
     always applicable.

     `sub_commands' is usually defined at the `end' of a class, because
     predicates can be methods of the class, so they must already have
     been defined.  The canonical example is the ‘install’ command.


File: python.info,  Node: distutils command --- Individual Distutils commands,  Next: distutils command bdist --- Build a binary installer,  Prev: Creating a new Distutils command,  Up: API参考引用

17.9.25 ‘distutils.command’ — Individual Distutils commands
-----------------------------------------------------------


File: python.info,  Node: distutils command bdist --- Build a binary installer,  Next: distutils command bdist_packager --- Abstract base class for packagers,  Prev: distutils command --- Individual Distutils commands,  Up: API参考引用

17.9.26 ‘distutils.command.bdist’ — Build a binary installer
------------------------------------------------------------


File: python.info,  Node: distutils command bdist_packager --- Abstract base class for packagers,  Next: distutils command bdist_dumb --- Build a "dumb" installer,  Prev: distutils command bdist --- Build a binary installer,  Up: API参考引用

17.9.27 ‘distutils.command.bdist_packager’ — Abstract base class for packagers
------------------------------------------------------------------------------


File: python.info,  Node: distutils command bdist_dumb --- Build a "dumb" installer,  Next: distutils command bdist_msi --- Build a Microsoft Installer binary package,  Prev: distutils command bdist_packager --- Abstract base class for packagers,  Up: API参考引用

17.9.28 ‘distutils.command.bdist_dumb’ — Build a "dumb" installer
-----------------------------------------------------------------


File: python.info,  Node: distutils command bdist_msi --- Build a Microsoft Installer binary package,  Next: distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM,  Prev: distutils command bdist_dumb --- Build a "dumb" installer,  Up: API参考引用

17.9.29 ‘distutils.command.bdist_msi’ — Build a Microsoft Installer binary package
----------------------------------------------------------------------------------

 -- 类: distutils.command.bdist_msi.bdist_msi

     Builds a Windows Installer(1) (.msi) binary package.

     In most cases, the ‘bdist_msi’ installer is a better choice than
     the ‘bdist_wininst’ installer, because it provides better support
     for Win64 platforms, allows administrators to perform
     non-interactive installations, and allows installation through
     group policies.

   ---------- Footnotes ----------

   (1) https://msdn.microsoft.com/en-us/library/cc185688(VS.85).aspx


File: python.info,  Node: distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM,  Next: distutils command bdist_wininst --- Build a Windows installer,  Prev: distutils command bdist_msi --- Build a Microsoft Installer binary package,  Up: API参考引用

17.9.30 ‘distutils.command.bdist_rpm’ — Build a binary distribution as a Redhat RPM and SRPM
--------------------------------------------------------------------------------------------


File: python.info,  Node: distutils command bdist_wininst --- Build a Windows installer,  Next: distutils command sdist --- Build a source distribution,  Prev: distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM,  Up: API参考引用

17.9.31 ‘distutils.command.bdist_wininst’ — Build a Windows installer
---------------------------------------------------------------------

3.8 版后已移除: Use bdist_wheel (wheel packages) instead.


File: python.info,  Node: distutils command sdist --- Build a source distribution,  Next: distutils command build --- Build all files of a package,  Prev: distutils command bdist_wininst --- Build a Windows installer,  Up: API参考引用

17.9.32 ‘distutils.command.sdist’ — Build a source distribution
---------------------------------------------------------------


File: python.info,  Node: distutils command build --- Build all files of a package,  Next: distutils command build_clib --- Build any C libraries in a package,  Prev: distutils command sdist --- Build a source distribution,  Up: API参考引用

17.9.33 ‘distutils.command.build’ — Build all files of a package
----------------------------------------------------------------


File: python.info,  Node: distutils command build_clib --- Build any C libraries in a package,  Next: distutils command build_ext --- Build any extensions in a package,  Prev: distutils command build --- Build all files of a package,  Up: API参考引用

17.9.34 ‘distutils.command.build_clib’ — Build any C libraries in a package
---------------------------------------------------------------------------


File: python.info,  Node: distutils command build_ext --- Build any extensions in a package,  Next: distutils command build_py --- Build the py/ pyc files of a package,  Prev: distutils command build_clib --- Build any C libraries in a package,  Up: API参考引用

17.9.35 ‘distutils.command.build_ext’ — Build any extensions in a package
-------------------------------------------------------------------------


File: python.info,  Node: distutils command build_py --- Build the py/ pyc files of a package,  Next: distutils command build_scripts --- Build the scripts of a package,  Prev: distutils command build_ext --- Build any extensions in a package,  Up: API参考引用

17.9.36 ‘distutils.command.build_py’ — Build the .py/.pyc files of a package
----------------------------------------------------------------------------

 -- 类: distutils.command.build_py.build_py

 -- 类: distutils.command.build_py.build_py_2to3

     Alternative implementation of build_py which also runs the 2to3
     conversion library on each .py file that is going to be installed.
     To use this in a setup.py file for a distribution that is designed
     to run with both Python 2.x and 3.x, add:

          try:
              from distutils.command.build_py import build_py_2to3 as build_py
          except ImportError:
              from distutils.command.build_py import build_py

     to your setup.py, and later:

          cmdclass = {'build_py': build_py}

     to the invocation of setup().


File: python.info,  Node: distutils command build_scripts --- Build the scripts of a package,  Next: distutils command clean --- Clean a package build area,  Prev: distutils command build_py --- Build the py/ pyc files of a package,  Up: API参考引用

17.9.37 ‘distutils.command.build_scripts’ — Build the scripts of a package
--------------------------------------------------------------------------


File: python.info,  Node: distutils command clean --- Clean a package build area,  Next: distutils command config --- Perform package configuration,  Prev: distutils command build_scripts --- Build the scripts of a package,  Up: API参考引用

17.9.38 ‘distutils.command.clean’ — Clean a package build area
--------------------------------------------------------------

This command removes the temporary files created by ‘build’ and its
subcommands, like intermediary compiled object files.  With the ‘--all’
option, the complete build directory will be removed.

Extension modules built *note in place: 4382. will not be cleaned, as
they are not in the build directory.


File: python.info,  Node: distutils command config --- Perform package configuration,  Next: distutils command install --- Install a package,  Prev: distutils command clean --- Clean a package build area,  Up: API参考引用

17.9.39 ‘distutils.command.config’ — Perform package configuration
------------------------------------------------------------------


File: python.info,  Node: distutils command install --- Install a package,  Next: distutils command install_data --- Install data files from a package,  Prev: distutils command config --- Perform package configuration,  Up: API参考引用

17.9.40 ‘distutils.command.install’ — Install a package
-------------------------------------------------------


File: python.info,  Node: distutils command install_data --- Install data files from a package,  Next: distutils command install_headers --- Install C/C++ header files from a package,  Prev: distutils command install --- Install a package,  Up: API参考引用

17.9.41 ‘distutils.command.install_data’ — Install data files from a package
----------------------------------------------------------------------------


File: python.info,  Node: distutils command install_headers --- Install C/C++ header files from a package,  Next: distutils command install_lib --- Install library files from a package,  Prev: distutils command install_data --- Install data files from a package,  Up: API参考引用

17.9.42 ‘distutils.command.install_headers’ — Install C/C++ header files from a package
---------------------------------------------------------------------------------------


File: python.info,  Node: distutils command install_lib --- Install library files from a package,  Next: distutils command install_scripts --- Install script files from a package,  Prev: distutils command install_headers --- Install C/C++ header files from a package,  Up: API参考引用

17.9.43 ‘distutils.command.install_lib’ — Install library files from a package
------------------------------------------------------------------------------


File: python.info,  Node: distutils command install_scripts --- Install script files from a package,  Next: distutils command register --- Register a module with the Python Package Index,  Prev: distutils command install_lib --- Install library files from a package,  Up: API参考引用

17.9.44 ‘distutils.command.install_scripts’ — Install script files from a package
---------------------------------------------------------------------------------


File: python.info,  Node: distutils command register --- Register a module with the Python Package Index,  Next: distutils command check --- Check the meta-data of a package,  Prev: distutils command install_scripts --- Install script files from a package,  Up: API参考引用

17.9.45 ‘distutils.command.register’ — Register a module with the Python Package Index
--------------------------------------------------------------------------------------

The ‘register’ command registers the package with the Python Package
Index.  This is described in more detail in PEP 301(1).

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0301


File: python.info,  Node: distutils command check --- Check the meta-data of a package,  Prev: distutils command register --- Register a module with the Python Package Index,  Up: API参考引用

17.9.46 ‘distutils.command.check’ — Check the meta-data of a package
--------------------------------------------------------------------

The ‘check’ command performs some tests on the meta-data of a package.
For example, it verifies that all required meta-data are provided as the
arguments passed to the ‘setup()’ function.


File: python.info,  Node: 安装Python模块（旧版）,  Next: Python 模块索引,  Prev: 分发 Python 模块（遗留版本）,  Up: Top

18 安装Python模块（旧版）
*************************


作者: Greg Ward

参见
....

*note 安装 Python 模块: 7fe.

     最新的模块安装文档。对于常规Python使用，你几乎肯定像使用该文档而非
     这个。

     注解: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

     注解: 本指南仅介绍构建和分发扩展的基本工具，这些扩展是作为此
     Python版本的一部分提供的。 第三方工具提供更易于使用和更安全的替代方
     案。有关详细信息，请参阅 Python 打包用户指南中的 快速推荐部分(1) 。

* Menu:

* 概述: 概述<20>.
* Standard Build and Install::
* Alternate Installation::
* 自定义安装::
* Distutils Configuration Files::
* Building Extensions; Tips and Tricks: Building Extensions Tips and Tricks.

   ---------- Footnotes ----------

   (1) https://packaging.python.org/guides/tool-recommendations/


File: python.info,  Node: 概述<20>,  Next: Standard Build and Install,  Up: 安装Python模块（旧版）

18.1 概述
=========

在Python 2.0中，‘distutils’ API 首次被添加到标准库中。这向Linux发行版维
护者提供了一个将Python项目转换为发行版软件包的标准方法，以及向系统管理员
们提供了直接将这些软件包安装到目标系统的标准方法。

自从很多年前 Python 2.0 发布，将构建系统和包安装器与语言运行时的释放循环
紧密连接在一起产生了很多问题。现在推荐做法是在项目中使用 ‘pip’ 包安装器
和 ‘setuptools’ 构建系统，而不是直接使用 ‘distutils’。

请参阅 *note The Warnings Filter: 135c. 和 *note Describing Warning
Filters: 135d. 了解更多细节。

这个旧文档将被保留，至到我们相信 ‘setuptools’ 覆盖了所有内容。

* Menu:

* 基于分布式系统的源代码分发::


File: python.info,  Node: 基于分布式系统的源代码分发,  Up: 概述<20>

18.1.1 基于分布式系统的源代码分发
---------------------------------

If you download a module source distribution, you can tell pretty
quickly if it was packaged and distributed in the standard way, i.e.
using the Distutils.  First, the distribution’s name and version number
will be featured prominently in the name of the downloaded archive, e.g.
‘foo-1.0.tar.gz’ or ‘widget-0.9.7.zip’.  Next, the archive will unpack
into a similarly-named directory: ‘foo-1.0’ or ‘widget-0.9.7’.
Additionally, the distribution will contain a setup script ‘setup.py’,
and a file named ‘README.txt’ or possibly just ‘README’, which should
explain that building and installing the module distribution is a simple
matter of running one command from a terminal:

     python setup.py install

Windows 用户应该使用命令提示符来运行命令(Start ‣ Accessories):

     setup.py install

If all these things are true, then you already know how to build and
install the modules you’ve just downloaded: Run the command above.
Unless you need to install things in a non-standard way or customize the
build process, you don’t really need this manual.  Or rather, the above
command is everything you need to get out of this manual.


File: python.info,  Node: Standard Build and Install,  Next: Alternate Installation,  Prev: 概述<20>,  Up: 安装Python模块（旧版）

18.2 Standard Build and Install
===============================

As described in section *note 基于分布式系统的源代码分发: 444f, building
and installing a module distribution using the Distutils is usually one
simple command to run from a terminal:

     python setup.py install

* Menu:

* Platform variations::
* Splitting the job up::
* How building works::
* How installation works::


File: python.info,  Node: Platform variations,  Next: Splitting the job up,  Up: Standard Build and Install

18.2.1 Platform variations
--------------------------

You should always run the setup command from the distribution root
directory, i.e.  the top-level subdirectory that the module source
distribution unpacks into.  For example, if you’ve just downloaded a
module source distribution ‘foo-1.0.tar.gz’ onto a Unix system, the
normal thing to do is:

     gunzip -c foo-1.0.tar.gz | tar xf -    # unpacks into directory foo-1.0
     cd foo-1.0
     python setup.py install

On Windows, you’d probably download ‘foo-1.0.zip’.  If you downloaded
the archive file to ‘C:\Temp’, then it would unpack into
‘C:\Temp\foo-1.0’; you can use either an archive manipulator with a
graphical user interface (such as WinZip) or a command-line tool (such
as ‘unzip’ or ‘pkunzip’) to unpack the archive.  Then, open a command
prompt window and run:

     cd c:\Temp\foo-1.0
     python setup.py install


File: python.info,  Node: Splitting the job up,  Next: How building works,  Prev: Platform variations,  Up: Standard Build and Install

18.2.2 Splitting the job up
---------------------------

Running ‘setup.py install’ builds and installs all modules in one run.
If you prefer to work incrementally—especially useful if you want to
customize the build process, or if things are going wrong—you can use
the setup script to do one thing at a time.  This is particularly
helpful when the build and install will be done by different users—for
example, you might want to build a module distribution and hand it off
to a system administrator for installation (or do it yourself, with
super-user privileges).

For example, you can build everything in one step, and then install
everything in a second step, by invoking the setup script twice:

     python setup.py build
     python setup.py install

If you do this, you will notice that running the ‘install’ command first
runs the ‘build’ command, which—in this case—quickly notices that it has
nothing to do, since everything in the ‘build’ directory is up-to-date.

You may not need this ability to break things down often if all you do
is install modules downloaded off the ’net, but it’s very handy for more
advanced tasks.  If you get into distributing your own Python modules
and extensions, you’ll run lots of individual Distutils commands on
their own.


File: python.info,  Node: How building works,  Next: How installation works,  Prev: Splitting the job up,  Up: Standard Build and Install

18.2.3 How building works
-------------------------

As implied above, the ‘build’ command is responsible for putting the
files to install into a `build directory'.  By default, this is ‘build’
under the distribution root; if you’re excessively concerned with speed,
or want to keep the source tree pristine, you can change the build
directory with the ‘--build-base’ option.  For example:

     python setup.py build --build-base=/path/to/pybuild/foo-1.0

(Or you could do this permanently with a directive in your system or
personal Distutils configuration file; see section *note Distutils
Configuration Files: 4458.)  Normally, this isn’t necessary.

The default layout for the build tree is as follows:

     --- build/ --- lib/
     or
     --- build/ --- lib.<plat>/
                    temp.<plat>/

where ‘<plat>’ expands to a brief description of the current OS/hardware
platform and Python version.  The first form, with just a ‘lib’
directory, is used for "pure module distributions"—that is, module
distributions that include only pure Python modules.  If a module
distribution contains any extensions (modules written in C/C++), then
the second form, with two ‘<plat>’ directories, is used.  In that case,
the ‘temp.`plat'’ directory holds temporary files generated by the
compile/link process that don’t actually get installed.  In either case,
the ‘lib’ (or ‘lib.`plat'’) directory contains all Python modules (pure
Python and extensions) that will be installed.

In the future, more directories will be added to handle Python scripts,
documentation, binary executables, and whatever else is needed to handle
the job of installing Python modules and applications.


File: python.info,  Node: How installation works,  Prev: How building works,  Up: Standard Build and Install

18.2.4 How installation works
-----------------------------

After the ‘build’ command runs (whether you run it explicitly, or the
‘install’ command does it for you), the work of the ‘install’ command is
relatively simple: all it has to do is copy everything under ‘build/lib’
(or ‘build/lib.`plat'’) to your chosen installation directory.

If you don’t choose an installation directory—i.e., if you just run
‘setup.py install’—then the ‘install’ command installs to the standard
location for third-party Python modules.  This location varies by
platform and by how you built/installed Python itself.  On Unix (and Mac
OS X, which is also Unix-based), it also depends on whether the module
distribution being installed is pure Python or contains extensions
("non-pure"):

平台                  标准安装位置                                              默认值                                                 注释
                                                                                                                                       
---------------------------------------------------------------------------------------------------------------------------------------------------
                                                                                                                                       
（单一）Unix          ‘`prefix'/lib/python`X.Y'/site-packages’                  ‘/usr/local/lib/python`X.Y'/site-packages’             (1)
                                                                                                                                       
                                                                                                                                       
（类）Unix            ‘`exec-prefix'/lib/python`X.Y'/site-packages’             ‘/usr/local/lib/python`X.Y'/site-packages’             (1)
                                                                                                                                       
                                                                                                                                       
Windows               ‘`prefix'\Lib\site-packages’                              ‘C:\Python`XY'\Lib\site-packages’                      (2)
                                                                                                                                       

注释:

  1. Most Linux distributions include Python as a standard part of the
     system, so ‘`prefix'’ and ‘`exec-prefix'’ are usually both ‘/usr’
     on Linux.  If you build Python yourself on Linux (or any Unix-like
     system), the default ‘`prefix'’ and ‘`exec-prefix'’ are
     ‘/usr/local’.

  2. The default installation directory on Windows was ‘C:\Program
     Files\Python’ under Python 1.6a1, 1.5.2, and earlier.

‘`prefix'’ and ‘`exec-prefix'’ stand for the directories that Python is
installed to, and where it finds its libraries at run-time.  They are
always the same under Windows, and very often the same under Unix and
Mac OS X. You can find out what your Python installation uses for
‘`prefix'’ and ‘`exec-prefix'’ by running Python in interactive mode and
typing a few simple commands.  Under Unix, just type ‘python’ at the
shell prompt.  Under Windows, choose Start ‣ Programs ‣ Python X.Y ‣
Python (command line).  Once the interpreter is started, you type Python
code at the prompt.  For example, on my Linux system, I type the three
Python statements shown below, and get the output as shown, to find out
my ‘`prefix'’ and ‘`exec-prefix'’:

     Python 2.4 (#26, Aug  7 2004, 17:19:02)
     Type "help", "copyright", "credits" or "license" for more information.
     >>> import sys
     >>> sys.prefix
     '/usr'
     >>> sys.exec_prefix
     '/usr'

A few other placeholders are used in this document: ‘`X.Y'’ stands for
the version of Python, for example ‘3.2’; ‘`abiflags'’ will be replaced
by the value of *note sys.abiflags: 265. or the empty string for
platforms which don’t define ABI flags; ‘`distname'’ will be replaced by
the name of the module distribution being installed.  Dots and
capitalization are important in the paths; for example, a value that
uses ‘python3.2’ on UNIX will typically use ‘Python32’ on Windows.

If you don’t want to install modules to the standard location, or if you
don’t have permission to write there, then you need to read about
alternate installations in section *note Alternate Installation: 445b.
If you want to customize your installation directories more heavily, see
section *note 自定义安装: 445c. on custom installations.


File: python.info,  Node: Alternate Installation,  Next: 自定义安装,  Prev: Standard Build and Install,  Up: 安装Python模块（旧版）

18.3 Alternate Installation
===========================

Often, it is necessary or desirable to install modules to a location
other than the standard location for third-party Python modules.  For
example, on a Unix system you might not have permission to write to the
standard third-party module directory.  Or you might wish to try out a
module before making it a standard part of your local Python
installation.  This is especially true when upgrading a distribution
already present: you want to make sure your existing base of scripts
still works with the new version before actually upgrading.

The Distutils ‘install’ command is designed to make installing module
distributions to an alternate location simple and painless.  The basic
idea is that you supply a base directory for the installation, and the
‘install’ command picks a set of directories (called an `installation
scheme') under this base directory in which to install files.  The
details differ across platforms, so read whichever of the following
sections applies to you.

Note that the various alternate installation schemes are mutually
exclusive: you can pass ‘--user’, or ‘--home’, or ‘--prefix’ and
‘--exec-prefix’, or ‘--install-base’ and ‘--install-platbase’, but you
can’t mix from these groups.

* Menu:

* Alternate installation; the user scheme: Alternate installation the user scheme.
* Alternate installation; the home scheme: Alternate installation the home scheme.
* Alternate installation; Unix (the prefix scheme): Alternate installation Unix the prefix scheme.
* Alternate installation; Windows (the prefix scheme): Alternate installation Windows the prefix scheme.


File: python.info,  Node: Alternate installation the user scheme,  Next: Alternate installation the home scheme,  Up: Alternate Installation

18.3.1 Alternate installation: the user scheme
----------------------------------------------

This scheme is designed to be the most convenient solution for users
that don’t have write permission to the global site-packages directory
or don’t want to install into it.  It is enabled with a simple option:

     python setup.py install --user

Files will be installed into subdirectories of *note site.USER_BASE:
1368. (written as ‘`userbase'’ hereafter).  This scheme installs pure
Python modules and extension modules in the same location (also known as
*note site.USER_SITE: 1356.).  Here are the values for UNIX, including
Mac OS X:

文件类型            安装目录
                    
------------------------------------------------------------------------------------
                    
模块                ‘`userbase'/lib/python`X.Y'/site-packages’
                    
                    
脚本                ‘`userbase'/bin’
                    
                    
数据                ‘`userbase'’
                    
                    
C 头文件            ‘`userbase'/include/python`X.Y'`abiflags'/`distname'’
                    

以下是Windows上使用的值：

文件类型            安装目录
                    
------------------------------------------------------------------------------------
                    
模块                ‘`userbase'\Python`XY'\site-packages’
                    
                    
脚本                ‘`userbase'\Python`XY'\Scripts’
                    
                    
数据                ‘`userbase'’
                    
                    
C 头文件            ‘`userbase'\Python`XY'\Include{distname}’
                    

The advantage of using this scheme compared to the other ones described
below is that the user site-packages directory is under normal
conditions always included in *note sys.path: 490. (see *note site: ec.
for more information), which means that there is no additional step to
perform after running the ‘setup.py’ script to finalize the
installation.

The ‘build_ext’ command also has a ‘--user’ option to add
‘`userbase'/include’ to the compiler search path for header files and
‘`userbase'/lib’ to the compiler search path for libraries as well as to
the runtime search path for shared C libraries (rpath).


File: python.info,  Node: Alternate installation the home scheme,  Next: Alternate installation Unix the prefix scheme,  Prev: Alternate installation the user scheme,  Up: Alternate Installation

18.3.2 Alternate installation: the home scheme
----------------------------------------------

The idea behind the "home scheme" is that you build and maintain a
personal stash of Python modules.  This scheme’s name is derived from
the idea of a "home" directory on Unix, since it’s not unusual for a
Unix user to make their home directory have a layout similar to ‘/usr/’
or ‘/usr/local/’.  This scheme can be used by anyone, regardless of the
operating system they are installing for.

Installing a new module distribution is as simple as

     python setup.py install --home=<dir>

where you can supply any directory you like for the ‘--home’ option.  On
Unix, lazy typists can just type a tilde (‘~’); the ‘install’ command
will expand this to your home directory:

     python setup.py install --home=~

To make Python find the distributions installed with this scheme, you
may have to *note modify Python’s search path: 4461. or edit
‘sitecustomize’ (see *note site: ec.) to call *note site.addsitedir():
3719. or edit *note sys.path: 490.

The ‘--home’ option defines the installation base directory.  Files are
installed to the following directories under the installation base as
follows:

文件类型            安装目录
                    
------------------------------------------------------------------------------------
                    
模块                ‘`home'/lib/python’
                    
                    
脚本                ‘`home'/bin’
                    
                    
数据                ‘`home'’
                    
                    
C 头文件            ‘`home'/include/python/`distname'’
                    

(Mentally replace slashes with backslashes if you’re on Windows.)


File: python.info,  Node: Alternate installation Unix the prefix scheme,  Next: Alternate installation Windows the prefix scheme,  Prev: Alternate installation the home scheme,  Up: Alternate Installation

18.3.3 Alternate installation: Unix (the prefix scheme)
-------------------------------------------------------

The "prefix scheme" is useful when you wish to use one Python
installation to perform the build/install (i.e., to run the setup
script), but install modules into the third-party module directory of a
different Python installation (or something that looks like a different
Python installation).  If this sounds a trifle unusual, it is—that’s why
the user and home schemes come before.  However, there are at least two
known cases where the prefix scheme will be useful.

First, consider that many Linux distributions put Python in ‘/usr’,
rather than the more traditional ‘/usr/local’.  This is entirely
appropriate, since in those cases Python is part of "the system" rather
than a local add-on.  However, if you are installing Python modules from
source, you probably want them to go in ‘/usr/local/lib/python2.`X'’
rather than ‘/usr/lib/python2.`X'’.  This can be done with

     /usr/bin/python setup.py install --prefix=/usr/local

Another possibility is a network filesystem where the name used to write
to a remote directory is different from the name used to read it: for
example, the Python interpreter accessed as ‘/usr/local/bin/python’
might search for modules in ‘/usr/local/lib/python2.`X'’, but those
modules would have to be installed to, say,
‘/mnt/`@server'/export/lib/python2.`X'’.  This could be done with

     /usr/local/bin/python setup.py install --prefix=/mnt/@server/export

In either case, the ‘--prefix’ option defines the installation base, and
the ‘--exec-prefix’ option defines the platform-specific installation
base, which is used for platform-specific files.  (Currently, this just
means non-pure module distributions, but could be expanded to C
libraries, binary executables, etc.)  If ‘--exec-prefix’ is not
supplied, it defaults to ‘--prefix’.  Files are installed as follows:

文件类型              安装目录
                      
-------------------------------------------------------------------------------------
                      
Python 模块           ‘`prefix'/lib/python`X.Y'/site-packages’
                      
                      
扩展模块              ‘`exec-prefix'/lib/python`X.Y'/site-packages’
                      
                      
脚本                  ‘`prefix'/bin’
                      
                      
数据                  ‘`prefix'’
                      
                      
C 头文件              ‘`prefix'/include/python`X.Y'`abiflags'/`distname'’
                      

There is no requirement that ‘--prefix’ or ‘--exec-prefix’ actually
point to an alternate Python installation; if the directories listed
above do not already exist, they are created at installation time.

Incidentally, the real reason the prefix scheme is important is simply
that a standard Unix installation uses the prefix scheme, but with
‘--prefix’ and ‘--exec-prefix’ supplied by Python itself as ‘sys.prefix’
and ‘sys.exec_prefix’.  Thus, you might think you’ll never use the
prefix scheme, but every time you run ‘python setup.py install’ without
any other options, you’re using it.

Note that installing extensions to an alternate Python installation has
no effect on how those extensions are built: in particular, the Python
header files (‘Python.h’ and friends) installed with the Python
interpreter used to run the setup script will be used in compiling
extensions.  It is your responsibility to ensure that the interpreter
used to run extensions installed in this way is compatible with the
interpreter used to build them.  The best way to do this is to ensure
that the two interpreters are the same version of Python (possibly
different builds, or possibly copies of the same build).  (Of course, if
your ‘--prefix’ and ‘--exec-prefix’ don’t even point to an alternate
Python installation, this is immaterial.)


File: python.info,  Node: Alternate installation Windows the prefix scheme,  Prev: Alternate installation Unix the prefix scheme,  Up: Alternate Installation

18.3.4 Alternate installation: Windows (the prefix scheme)
----------------------------------------------------------

Windows has no concept of a user’s home directory, and since the
standard Python installation under Windows is simpler than under Unix,
the ‘--prefix’ option has traditionally been used to install additional
packages in separate locations on Windows.

     python setup.py install --prefix="\Temp\Python"

to install modules to the ‘\Temp\Python’ directory on the current drive.

The installation base is defined by the ‘--prefix’ option; the
‘--exec-prefix’ option is not supported under Windows, which means that
pure Python modules and extension modules are installed into the same
location.  Files are installed as follows:

文件类型            安装目录
                    
-----------------------------------------------------------------------------------
                    
模块                ‘`prefix'\Lib\site-packages’
                    
                    
脚本                ‘`prefix'\Scripts’
                    
                    
数据                ‘`prefix'’
                    
                    
C 头文件            ‘`prefix'\Include{distname}’
                    


File: python.info,  Node: 自定义安装,  Next: Distutils Configuration Files,  Prev: Alternate Installation,  Up: 安装Python模块（旧版）

18.4 自定义安装
===============

Sometimes, the alternate installation schemes described in section *note
Alternate Installation: 445b. just don’t do what you want.  You might
want to tweak just one or two directories while keeping everything under
the same base directory, or you might want to completely redefine the
installation scheme.  In either case, you’re creating a `custom
installation scheme'.

To create a custom installation scheme, you start with one of the
alternate schemes and override some of the installation directories used
for the various types of files, using these options:

文件类型                   覆盖选项
                           
-------------------------------------------------------
                           
Python 模块                ‘--install-purelib’
                           
                           
扩展模块                   ‘--install-platlib’
                           
                           
所有模块                   ‘--install-lib’
                           
                           
脚本                       ‘--install-scripts’
                           
                           
数据                       ‘--install-data’
                           
                           
C 头文件                   ‘--install-headers’
                           

These override options can be relative, absolute, or explicitly defined
in terms of one of the installation base directories.  (There are two
installation base directories, and they are normally the same—they only
differ when you use the Unix "prefix scheme" and supply different
‘--prefix’ and ‘--exec-prefix’ options; using ‘--install-lib’ will
override values computed or given for ‘--install-purelib’ and
‘--install-platlib’, and is recommended for schemes that don’t make a
difference between Python and extension modules.)

For example, say you’re installing a module distribution to your home
directory under Unix—but you want scripts to go in ‘~/scripts’ rather
than ‘~/bin’.  As you might expect, you can override this directory with
the ‘--install-scripts’ option; in this case, it makes most sense to
supply a relative path, which will be interpreted relative to the
installation base directory (your home directory, in this case):

     python setup.py install --home=~ --install-scripts=scripts

Another Unix example: suppose your Python installation was built and
installed with a prefix of ‘/usr/local/python’, so under a standard
installation scripts will wind up in ‘/usr/local/python/bin’.  If you
want them in ‘/usr/local/bin’ instead, you would supply this absolute
directory for the ‘--install-scripts’ option:

     python setup.py install --install-scripts=/usr/local/bin

(This performs an installation using the "prefix scheme", where the
prefix is whatever your Python interpreter was installed with—
‘/usr/local/python’ in this case.)

If you maintain Python on Windows, you might want third-party modules to
live in a subdirectory of ‘`prefix'’, rather than right in ‘`prefix'’
itself.  This is almost as easy as customizing the script installation
directory—you just have to remember that there are two types of modules
to worry about, Python and extension modules, which can conveniently be
both controlled by one option:

     python setup.py install --install-lib=Site

The specified installation directory is relative to ‘`prefix'’.  Of
course, you also have to ensure that this directory is in Python’s
module search path, such as by putting a ‘.pth’ file in a site directory
(see *note site: ec.).  See section *note Modifying Python’s Search
Path: 4461. to find out how to modify Python’s search path.

If you want to define an entire installation scheme, you just have to
supply all of the installation directory options.  The recommended way
to do this is to supply relative paths; for example, if you want to
maintain all Python module-related files under ‘python’ in your home
directory, and you want a separate directory for each platform that you
use your home directory from, you might define the following
installation scheme:

     python setup.py install --home=~ \
                             --install-purelib=python/lib \
                             --install-platlib=python/lib.$PLAT \
                             --install-scripts=python/scripts
                             --install-data=python/data

或者，等价于

     python setup.py install --home=~/python \
                             --install-purelib=lib \
                             --install-platlib='lib.$PLAT' \
                             --install-scripts=scripts
                             --install-data=data

‘$PLAT’ is not (necessarily) an environment variable—it will be expanded
by the Distutils as it parses your command line options, just as it does
when parsing your configuration file(s).

Obviously, specifying the entire installation scheme every time you
install a new module distribution would be very tedious.  Thus, you can
put these options into your Distutils config file (see section *note
Distutils Configuration Files: 4458.):

     [install]
     install-base=$HOME
     install-purelib=python/lib
     install-platlib=python/lib.$PLAT
     install-scripts=python/scripts
     install-data=python/data

或者，等价于，

     [install]
     install-base=$HOME/python
     install-purelib=lib
     install-platlib=lib.$PLAT
     install-scripts=scripts
     install-data=data

Note that these two are `not' equivalent if you supply a different
installation base directory when you run the setup script.  For example,

     python setup.py install --install-base=/tmp

would install pure modules to ‘/tmp/python/lib’ in the first case, and
to ‘/tmp/lib’ in the second case.  (For the second case, you probably
want to supply an installation base of ‘/tmp/python’.)

You probably noticed the use of ‘$HOME’ and ‘$PLAT’ in the sample
configuration file input.  These are Distutils configuration variables,
which bear a strong resemblance to environment variables.  In fact, you
can use environment variables in config files on platforms that have
such a notion but the Distutils additionally define a few extra
variables that may not be in your environment, such as ‘$PLAT’.  (And of
course, on systems that don’t have environment variables, such as Mac OS
9, the configuration variables supplied by the Distutils are the only
ones you can use.)  See section *note Distutils Configuration Files:
4458. for details.

     注解: When a *note virtual environment: 3602. is activated, any
     options that change the installation path will be ignored from all
     distutils configuration files to prevent inadvertently installing
     projects outside of the virtual environment.

* Menu:

* Modifying Python's Search Path::


File: python.info,  Node: Modifying Python's Search Path,  Up: 自定义安装

18.4.1 Modifying Python’s Search Path
-------------------------------------

When the Python interpreter executes an *note import: c25. statement, it
searches for both Python code and extension modules along a search path.
A default value for the path is configured into the Python binary when
the interpreter is built.  You can determine the path by importing the
*note sys: fe. module and printing the value of ‘sys.path’.

     $ python
     Python 2.2 (#11, Oct  3 2002, 13:31:27)
     [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2
     Type "help", "copyright", "credits" or "license" for more information.
     >>> import sys
     >>> sys.path
     ['', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2',
      '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload',
      '/usr/local/lib/python2.3/site-packages']
     >>>

The null string in ‘sys.path’ represents the current working directory.

The expected convention for locally installed packages is to put them in
the ‘`...'/site-packages/’ directory, but you may want to install Python
modules into some arbitrary directory.  For example, your site may have
a convention of keeping all software related to the web server under
‘/www’.  Add-on Python modules might then belong in ‘/www/python’, and
in order to import them, this directory must be added to ‘sys.path’.
There are several different ways to add the directory.

The most convenient way is to add a path configuration file to a
directory that’s already on Python’s path, usually to the
‘.../site-packages/’ directory.  Path configuration files have an
extension of ‘.pth’, and each line must contain a single path that will
be appended to ‘sys.path’.  (Because the new paths are appended to
‘sys.path’, modules in the added directories will not override standard
modules.  This means you can’t use this mechanism for installing fixed
versions of standard modules.)

Paths can be absolute or relative, in which case they’re relative to the
directory containing the ‘.pth’ file.  See the documentation of the
*note site: ec. module for more information.

A slightly less convenient way is to edit the ‘site.py’ file in Python’s
standard library, and modify ‘sys.path’.  ‘site.py’ is automatically
imported when the Python interpreter is executed, unless the *note -S:
b2c. switch is supplied to suppress this behaviour.  So you could simply
edit ‘site.py’ and add two lines to it:

     import sys
     sys.path.append('/www/python/')

However, if you reinstall the same major version of Python (perhaps when
upgrading from 2.2 to 2.2.2, for example) ‘site.py’ will be overwritten
by the stock version.  You’d have to remember that it was modified and
save a copy before doing the installation.

There are two environment variables that can modify ‘sys.path’.  *note
PYTHONHOME: 4de. sets an alternate value for the prefix of the Python
installation.  For example, if *note PYTHONHOME: 4de. is set to
‘/www/python’, the search path will be set to ‘['',
'/www/python/lib/pythonX.Y/', '/www/python/lib/pythonX.Y/plat-linux2',
...]’.

The *note PYTHONPATH: 95b. variable can be set to a list of paths that
will be added to the beginning of ‘sys.path’.  For example, if *note
PYTHONPATH: 95b. is set to ‘/www/python:/opt/py’, the search path will
begin with ‘['/www/python', '/opt/py']’.  (Note that directories must
exist in order to be added to ‘sys.path’; the *note site: ec. module
removes paths that don’t exist.)

Finally, ‘sys.path’ is just a regular Python list, so any Python
application can modify it by adding or removing entries.


File: python.info,  Node: Distutils Configuration Files,  Next: Building Extensions Tips and Tricks,  Prev: 自定义安装,  Up: 安装Python模块（旧版）

18.5 Distutils Configuration Files
==================================

As mentioned above, you can use Distutils configuration files to record
personal or site preferences for any Distutils options.  That is, any
option to any command can be stored in one of two or three (depending on
your platform) configuration files, which will be consulted before the
command-line is parsed.  This means that configuration files will
override default values, and the command-line will in turn override
configuration files.  Furthermore, if multiple configuration files
apply, values from "earlier" files are overridden by "later" files.

* Menu:

* Location and names of config files::
* Syntax of config files::


File: python.info,  Node: Location and names of config files,  Next: Syntax of config files,  Up: Distutils Configuration Files

18.5.1 Location and names of config files
-----------------------------------------

The names and locations of the configuration files vary slightly across
platforms.  On Unix and Mac OS X, the three configuration files (in the
order they are processed) are:

文件类型           位置和文件名                                                   注释
                                                                                  
----------------------------------------------------------------------------------------------
                                                                                  
system             ‘`prefix'/lib/python`ver'/distutils/distutils.cfg’             (1)
                                                                                  
                                                                                  
personal           ‘$HOME/.pydistutils.cfg’                                       (2)
                                                                                  
                                                                                  
local              ‘setup.cfg’                                                    (3)
                                                                                  

And on Windows, the configuration files are:

文件类型           位置和文件名                                          注释
                                                                         
-------------------------------------------------------------------------------------
                                                                         
system             ‘`prefix'\Lib\distutils\distutils.cfg’                (4)
                                                                         
                                                                         
personal           ‘%HOME%\pydistutils.cfg’                              (5)
                                                                         
                                                                         
local              ‘setup.cfg’                                           (3)
                                                                         

On all platforms, the "personal" file can be temporarily disabled by
passing the ‘–no-user-cfg’ option.

注释:

  1. Strictly speaking, the system-wide configuration file lives in the
     directory where the Distutils are installed; under Python 1.6 and
     later on Unix, this is as shown.  For Python 1.5.2, the Distutils
     will normally be installed to
     ‘`prefix'/lib/python1.5/site-packages/distutils’, so the system
     configuration file should be put there under Python 1.5.2.

  2. On Unix, if the ‘HOME’ environment variable is not defined, the
     user’s home directory will be determined with the ‘getpwuid()’
     function from the standard *note pwd: d7. module.  This is done by
     the *note os.path.expanduser(): 1ff. function used by Distutils.

  3. I.e., in the current directory (usually the location of the setup
     script).

  4. (See also note (1).)  Under Python 1.6 and later, Python’s default
     "installation prefix" is ‘C:\Python’, so the system configuration
     file is normally ‘C:\Python\Lib\distutils\distutils.cfg’.  Under
     Python 1.5.2, the default prefix was ‘C:\Program Files\Python’, and
     the Distutils were not part of the standard library—so the system
     configuration file would be ‘C:\Program
     Files\Python\distutils\distutils.cfg’ in a standard Python 1.5.2
     installation under Windows.

  5. On Windows, if the ‘HOME’ environment variable is not defined,
     ‘USERPROFILE’ then ‘HOMEDRIVE’ and ‘HOMEPATH’ will be tried.  This
     is done by the *note os.path.expanduser(): 1ff. function used by
     Distutils.


File: python.info,  Node: Syntax of config files,  Prev: Location and names of config files,  Up: Distutils Configuration Files

18.5.2 Syntax of config files
-----------------------------

The Distutils configuration files all have the same syntax.  The config
files are grouped into sections.  There is one section for each
Distutils command, plus a ‘global’ section for global options that
affect every command.  Each section consists of one option per line,
specified as ‘option=value’.

For example, the following is a complete config file that just forces
all commands to run quietly by default:

     [global]
     verbose=0

If this is installed as the system config file, it will affect all
processing of any Python module distribution by any user on the current
system.  If it is installed as your personal config file (on systems
that support them), it will affect only module distributions processed
by you.  And if it is used as the ‘setup.cfg’ for a particular module
distribution, it affects only that distribution.

You could override the default "build base" directory and make the
‘build*’ commands always forcibly rebuild all files with the following:

     [build]
     build-base=blib
     force=1

which corresponds to the command-line arguments

     python setup.py build --build-base=blib --force

except that including the ‘build’ command on the command-line means that
command will be run.  Including a particular command in config files has
no such implication; it only means that if the command is run, the
options in the config file will apply.  (Or if other commands that
derive values from it are run, they will use the values in the config
file.)

You can find out the complete list of options for any command using the
‘--help’ option, e.g.:

     python setup.py build --help

and you can find out the complete list of global options by using
‘--help’ without a command:

     python setup.py --help

See also the "Reference" section of the "Distributing Python Modules"
manual.


File: python.info,  Node: Building Extensions Tips and Tricks,  Prev: Distutils Configuration Files,  Up: 安装Python模块（旧版）

18.6 Building Extensions: Tips and Tricks
=========================================

Whenever possible, the Distutils try to use the configuration
information made available by the Python interpreter used to run the
‘setup.py’ script.  For example, the same compiler and linker flags used
to compile Python will also be used for compiling extensions.  Usually
this will work well, but in complicated situations this might be
inappropriate.  This section discusses how to override the usual
Distutils behaviour.

* Menu:

* Tweaking compiler/linker flags::
* Using non-Microsoft compilers on Windows::


File: python.info,  Node: Tweaking compiler/linker flags,  Next: Using non-Microsoft compilers on Windows,  Up: Building Extensions Tips and Tricks

18.6.1 Tweaking compiler/linker flags
-------------------------------------

Compiling a Python extension written in C or C++ will sometimes require
specifying custom flags for the compiler and linker in order to use a
particular library or produce a special kind of object code.  This is
especially true if the extension hasn’t been tested on your platform, or
if you’re trying to cross-compile Python.

In the most general case, the extension author might have foreseen that
compiling the extensions would be complicated, and provided a ‘Setup’
file for you to edit.  This will likely only be done if the module
distribution contains many separate extension modules, or if they often
require elaborate sets of compiler flags in order to work.

A ‘Setup’ file, if present, is parsed in order to get a list of
extensions to build.  Each line in a ‘Setup’ describes a single module.
Lines have the following structure:

     module ... [sourcefile ...] [cpparg ...] [library ...]

Let’s examine each of the fields in turn.

   * `module' is the name of the extension module to be built, and
     should be a valid Python identifier.  You can’t just change this in
     order to rename a module (edits to the source code would also be
     needed), so this should be left alone.

   * `sourcefile' is anything that’s likely to be a source code file, at
     least judging by the filename.  Filenames ending in ‘.c’ are
     assumed to be written in C, filenames ending in ‘.C’, ‘.cc’, and
     ‘.c++’ are assumed to be C++, and filenames ending in ‘.m’ or ‘.mm’
     are assumed to be in Objective C.

   * `cpparg' is an argument for the C preprocessor, and is anything
     starting with ‘-I’, ‘-D’, ‘-U’ or ‘-C’.

   * `library' is anything ending in ‘.a’ or beginning with ‘-l’ or
     ‘-L’.

If a particular platform requires a special library on your platform,
you can add it by editing the ‘Setup’ file and running ‘python setup.py
build’.  For example, if the module defined by the line

     foo foomodule.c

must be linked with the math library ‘libm.a’ on your platform, simply
add ‘-lm’ to the line:

     foo foomodule.c -lm

Arbitrary switches intended for the compiler or the linker can be
supplied with the ‘-Xcompiler’ `arg' and ‘-Xlinker’ `arg' options:

     foo foomodule.c -Xcompiler -o32 -Xlinker -shared -lm

The next option after ‘-Xcompiler’ and ‘-Xlinker’ will be appended to
the proper command line, so in the above example the compiler will be
passed the ‘-o32’ option, and the linker will be passed ‘-shared’.  If a
compiler option requires an argument, you’ll have to supply multiple
‘-Xcompiler’ options; for example, to pass ‘-x c++’ the ‘Setup’ file
would have to contain ‘-Xcompiler -x -Xcompiler c++’.

Compiler flags can also be supplied through setting the ‘CFLAGS’
environment variable.  If set, the contents of ‘CFLAGS’ will be added to
the compiler flags specified in the ‘Setup’ file.


File: python.info,  Node: Using non-Microsoft compilers on Windows,  Prev: Tweaking compiler/linker flags,  Up: Building Extensions Tips and Tricks

18.6.2 Using non-Microsoft compilers on Windows
-----------------------------------------------

* Menu:

* Borland/CodeGear C++::
* GNU C / Cygwin / MinGW::


File: python.info,  Node: Borland/CodeGear C++,  Next: GNU C / Cygwin / MinGW,  Up: Using non-Microsoft compilers on Windows

18.6.2.1 Borland/CodeGear C++
.............................

This subsection describes the necessary steps to use Distutils with the
Borland C++ compiler version 5.5.  First you have to know that Borland’s
object file format (OMF) is different from the format used by the Python
version you can download from the Python or ActiveState Web site.
(Python is built with Microsoft Visual C++, which uses COFF as the
object file format.)  For this reason you have to convert Python’s
library ‘python25.lib’ into the Borland format.  You can do this as
follows:

     coff2omf python25.lib python25_bcpp.lib

The ‘coff2omf’ program comes with the Borland compiler.  The file
‘python25.lib’ is in the ‘Libs’ directory of your Python installation.
If your extension uses other libraries (zlib, ...)  you have to convert
them too.

The converted files have to reside in the same directories as the normal
libraries.

How does Distutils manage to use these libraries with their changed
names?  If the extension needs a library (eg.  ‘foo’) Distutils checks
first if it finds a library with suffix ‘_bcpp’ (eg.  ‘foo_bcpp.lib’)
and then uses this library.  In the case it doesn’t find such a special
library it uses the default name (‘foo.lib’.)  (1)

To let Distutils compile your extension with Borland C++ you now have to
type:

     python setup.py build --compiler=bcpp

If you want to use the Borland C++ compiler as the default, you could
specify this in your personal or system-wide configuration file for
Distutils (see section *note Distutils Configuration Files: 4458.)

参见
....

C++Builder Compiler(2)

     Information about the free C++ compiler from Borland, including
     links to the download pages.

Creating Python Extensions Using Borland’s Free Compiler(3)

     Document describing how to use Borland’s free command-line C++
     compiler to build Python.

   ---------- Footnotes ----------

   (1) (1) This also means you could replace all existing COFF-libraries
with OMF-libraries of the same name.

   (2) https://www.embarcadero.com/products

   (3) http://www.cyberus.ca/~g_will/pyExtenDL.shtml


File: python.info,  Node: GNU C / Cygwin / MinGW,  Prev: Borland/CodeGear C++,  Up: Using non-Microsoft compilers on Windows

18.6.2.2 GNU C / Cygwin / MinGW
...............................

This section describes the necessary steps to use Distutils with the GNU
C/C++ compilers in their Cygwin and MinGW distributions.  (1) For a
Python interpreter that was built with Cygwin, everything should work
without any of these following steps.

Not all extensions can be built with MinGW or Cygwin, but many can.
Extensions most likely to not work are those that use C++ or depend on
Microsoft Visual C extensions.

To let Distutils compile your extension with Cygwin you have to type:

     python setup.py build --compiler=cygwin

and for Cygwin in no-cygwin mode (2) or for MinGW type:

     python setup.py build --compiler=mingw32

If you want to use any of these options/compilers as default, you should
consider writing it in your personal or system-wide configuration file
for Distutils (see section *note Distutils Configuration Files: 4458.)

* Menu:

* Older Versions of Python and MinGW::

   ---------- Footnotes ----------

   (1) (2) Check ‘https://www.sourceware.org/cygwin/’ for more
information

   (2) (3) Then you have no POSIX emulation available, but you also
don’t need ‘cygwin1.dll’.


File: python.info,  Node: Older Versions of Python and MinGW,  Up: GNU C / Cygwin / MinGW

18.6.2.3 Older Versions of Python and MinGW
...........................................

The following instructions only apply if you’re using a version of
Python inferior to 2.4.1 with a MinGW inferior to 3.0.0 (with
binutils-2.13.90-20030111-1).

These compilers require some special libraries.  This task is more
complex than for Borland’s C++, because there is no program to convert
the library.  First you have to create a list of symbols which the
Python DLL exports.  (You can find a good program for this task at
‘https://sourceforge.net/projects/mingw/files/MinGW/Extension/pexports/’).

     pexports python25.dll >python25.def

The location of an installed ‘python25.dll’ will depend on the
installation options and the version and language of Windows.  In a
"just for me" installation, it will appear in the root of the
installation directory.  In a shared installation, it will be located in
the system directory.

Then you can create from these information an import library for gcc.

     /cygwin/bin/dlltool --dllname python25.dll --def python25.def --output-lib libpython25.a

The resulting library has to be placed in the same directory as
‘python25.lib’.  (Should be the ‘libs’ directory under your Python
installation directory.)

If your extension uses other libraries (zlib,...)  you might have to
convert them too.  The converted files have to reside in the same
directories as the normal libraries do.

参见
....

Building Python modules on MS Windows platform with MinGW(1)

     Information about building the required libraries for the MinGW
     environment.

备注
....

   ---------- Footnotes ----------

   (1) http://old.zope.org/Members/als/tips/win32_mingw_modules


File: python.info,  Node: Python 模块索引,  Next: 索引,  Prev: 安装Python模块（旧版）,  Up: Top

Python 模块索引
***************

* Menu:

* __future__: 0. Future statement definitions
* __main__: 1. The environment where the top-level script is run.
* _dummy_thread: 2. Drop-in replacement for the _thread module.
* _thread: 3. Low-level threading API.
* abc: 4. Abstract base classes according to :pep:‘3119‘.
* aifc: 5. Read and write audio files in AIFF or AIFC format.
* argparse: 6. Command-line option and argument parsing library.
* array: 7. Space efficient arrays of uniformly typed numeric
                        values.
* ast: 8. Abstract Syntax Tree classes and manipulation.
* asynchat: 9. Support for asynchronous command/response protocols.
* asyncio: a. Asynchronous I/O.
* asyncore: b. A base class for developing asynchronous socket
                        handling services.
* atexit: c. Register and execute cleanup functions.
* audioop: d. Manipulate raw audio data.
* base64: e. RFC 3548: Base16, Base32, Base64 Data
                        Encodings; Base85 and Ascii85
* bdb: f. Debugger framework.
* binascii: 10. Tools for converting between binary and various ASCII-
                        encoded binary representations.
* binhex: 11. Encode and decode files in binhex4 format.
* bisect: 12. Array bisection algorithms for binary searching.
* builtins: 13. The module that provides the built-in namespace.
* bz2: 14. Interfaces for bzip2 compression and decompression.
* calendar: 15. Functions for working with calendars, including
                        some emulation of the Unix cal program.
* cgi: 16. Helpers for running Python scripts via the Common
                        Gateway Interface.
* cgitb: 17. Configurable traceback handler for CGI scripts.
* chunk: 18. Module to read IFF chunks.
* cmath: 19. Mathematical functions for complex numbers.
* cmd: 1a. Build line-oriented command interpreters.
* code: 1b. Facilities to implement read-eval-print loops.
* codecs: 1c. Encode and decode data and streams.
* codeop: 1d. Compile (possibly incomplete) Python code.
* collections: 1e. Container datatypes
* collections.abc: 1f. Abstract base classes for containers
* colorsys: 20. Conversion functions between RGB and other color
                        systems.
* compileall: 21. Tools for byte-compiling all Python source files in a
                        directory tree.
* concurrent.futures: 22. Execute computations concurrently using threads or
                        processes.
* configparser: 23. Configuration file parser.
* contextlib: 24. Utilities for with-statement contexts.
* contextvars: 25. Context Variables
* copy: 26. Shallow and deep copy operations.
* copyreg: 27. Register pickle support functions.
* cProfile: 28.
* crypt: 29. The crypt() function used to check Unix passwords.
* csv: 2a. Write and read tabular data to and from delimited
                        files.
* ctypes: 2b. A foreign function library for Python.
* curses: 2c. An interface to the curses library, providing
                        portable terminal handling.
* curses.ascii: 2d. Constants and set-membership functions for ASCII
                        characters.
* curses.panel: 2e. A panel stack extension that adds depth to curses
                        windows.
* curses.textpad: 2f. Emacs-like input editing in a curses window.
* dataclasses: 30. Generate special methods on user-defined classes.
* datetime: 31. Basic date and time types.
* dbm: 32. Interfaces to various Unix "database" formats.
* dbm.dumb: 33. Portable implementation of the simple DBM interface.
* dbm.gnu: 34. GNU’s reinterpretation of dbm.
* dbm.ndbm: 35. The standard "database" interface, based on
                        ndbm.
* decimal: 36. Implementation of the General Decimal Arithmetic
                        Specification.
* difflib: 37. Helpers for computing differences between objects.
* dis: 38. Disassembler for Python bytecode.
* distutils: 39. Support for building and installing Python modules
                        into an existing Python installation.
* distutils.archive_util: 3a. Utility functions for creating archive files
                          (tarballs, zip files, ...)
* distutils.bcppcompiler: 3b.
* distutils.ccompiler: 3c. Abstract CCompiler class
* distutils.cmd: 3d. Provides the abstract base class
                        :class:‘~distutils.cmd.Command‘. This class is
                        subclassed by the modules in the distutils.command
                        subpackage.
* distutils.command: 3e. Contains one module for each standard Distutils
                        command.
* distutils.command.bdist: 3f. Build a binary installer for a package
* distutils.command.bdist_dumb: 40. Build a "dumb" installer - a simple archive of
                                files
* distutils.command.bdist_msi: 41. Build a binary distribution as a Windows MSI
                               file
* distutils.command.bdist_packager: 42. Abstract base class for packagers
* distutils.command.bdist_rpm: 43. Build a binary distribution as a Redhat RPM and
                               SRPM
* distutils.command.bdist_wininst: 44. Build a Windows installer
* distutils.command.build: 45. Build all files of a package
* distutils.command.build_clib: 46. Build any C libraries in a package
* distutils.command.build_ext: 47. Build any extensions in a package
* distutils.command.build_py: 48. Build the .py/.pyc files of a package
* distutils.command.build_scripts: 49. Build the scripts of a package
* distutils.command.check: 4a. Check the meta-data of a package
* distutils.command.clean: 4b. Clean a package build area
* distutils.command.config: 4c. Perform package configuration
* distutils.command.install: 4d. Install a package
* distutils.command.install_data: 4e. Install data files from a package
* distutils.command.install_headers: 4f. Install C/C++ header files from a package
* distutils.command.install_lib: 50. Install library files from a package
* distutils.command.install_scripts: 51. Install script files from a package
* distutils.command.register: 52. Register a module with the Python Package Index
* distutils.command.sdist: 53. Build a source distribution
* distutils.core: 54. The core Distutils functionality
* distutils.cygwinccompiler: 55.
* distutils.debug: 56. Provides the debug flag for distutils
* distutils.dep_util: 57. Utility functions for simple dependency checking
* distutils.dir_util: 58. Utility functions for operating on directories and
                        directory trees
* distutils.dist: 59. Provides the Distribution class, which
                        represents the module distribution being
                        built/installed/distributed
* distutils.errors: 5a. Provides standard distutils exceptions
* distutils.extension: 5b. Provides the Extension class, used to describe
                        C/C++ extension modules in setup scripts
* distutils.fancy_getopt: 5c. Additional getopt functionality
* distutils.file_util: 5d. Utility functions for operating on single files
* distutils.filelist: 5e. The FileList class, used for poking about the
                        file system and building lists of files.
* distutils.log: 5f. A simple logging mechanism, :pep:‘282‘-style
* distutils.msvccompiler: 60. Microsoft Compiler
* distutils.spawn: 61. Provides the spawn() function
* distutils.sysconfig: 62. Low-level access to configuration information of the
                        Python interpreter.
* distutils.text_file: 63. Provides the TextFile class, a simple interface
                        to text files
* distutils.unixccompiler: 64. UNIX C Compiler
* distutils.util: 65. Miscellaneous other utility functions
* distutils.version: 66. Implements classes that represent module version
                        numbers.
* doctest: 67. Test pieces of code within docstrings.
* dummy_threading: 68. Drop-in replacement for the threading module.
* email: 69. Package supporting the parsing,
                        manipulating, and generating email messages.
* email.charset: 6a. Character Sets
* email.contentmanager: 6b. Storing and Retrieving Content from MIME Parts
* email.encoders: 6c. Encoders for email message payloads.
* email.errors: 6d. The exception classes used by the email package.
* email.generator: 6e. Generate flat text email messages from a message
                        structure.
* email.header: 6f. Representing non-ASCII headers
* email.headerregistry: 70. Automatic Parsing of headers based on the field name
* email.iterators: 71. Iterate over a message object tree.
* email.message: 72. The base class representing email messages.
* email.mime: 73. Build MIME messages.
* email.parser: 74. Parse flat text email messages to produce a message
                        object structure.
* email.policy: 75. Controlling the parsing and generating of messages
* email.utils: 76. Miscellaneous email package utilities.
* encodings.idna: 77. Internationalized Domain Names implementation
* encodings.mbcs: 78. Windows ANSI codepage
* encodings.utf_8_sig: 79. UTF-8 codec with BOM signature
* ensurepip: 7a. Bootstrapping the "pip" installer into an existing
                        Python installation or virtual environment.
* enum: 7b. Implementation of an enumeration class.
* errno: 7c. Standard errno system symbols.
* faulthandler: 7d. Dump the Python traceback.
* fcntl: 7e. The fcntl() and ioctl() system calls.
* filecmp: 7f. Compare files efficiently.
* fileinput: 80. Loop over standard input or a list of files.
* fnmatch: 81. Unix shell style filename pattern matching.
* formatter: 82. Generic output formatter and device interface.
* fractions: 83. Rational numbers.
* ftplib: 84. FTP protocol client (requires sockets).
* functools: 85. Higher-order functions and operations on callable
                        objects.
* gc: 86. Interface to the cycle-detecting garbage collector.
* getopt: 87. Portable parser for command line options; support both
                        short and long option names.
* getpass: 88. Portable reading of passwords and retrieval of the
                        userid.
* gettext: 89. Multilingual internationalization services.
* glob: 8a. Unix shell style pathname pattern expansion.
* grp: 8b. The group database (getgrnam() and friends).
* gzip: 8c. Interfaces for gzip compression and decompression
                        using file objects.
* hashlib: 8d. Secure hash and message digest algorithms.
* heapq: 8e. Heap queue algorithm (a.k.a. priority queue).
* hmac: 8f. Keyed-Hashing for Message Authentication (HMAC)
                        implementation
* html: 90. Helpers for manipulating HTML.
* html.entities: 91. Definitions of HTML general entities.
* html.parser: 92. A simple parser that can handle HTML and XHTML.
* http: 93. HTTP status codes and messages
* http.client: 94. HTTP and HTTPS protocol client (requires sockets).
* http.cookiejar: 95. Classes for automatic handling of HTTP cookies.
* http.cookies: 96. Support for HTTP state management (cookies).
* http.server: 97. HTTP server and request handlers.
* imaplib: 98. IMAP4 protocol client (requires sockets).
* imghdr: 99. Determine the type of image contained in a file or
                        byte stream.
* imp: 9a. Access the implementation of the import statement.
* importlib: 9b. The implementation of the import machinery.
* importlib.abc: 9c. Abstract base classes related to import
* importlib.machinery: 9d. Importers and path hooks
* importlib.metadata: 9e. The implementation of the importlib metadata.
* importlib.resources: 9f. Package resource reading, opening, and
                        access
* importlib.util: a0. Utility code for importers
* inspect: a1. Extract information and source code from live objects.
* io: a2. Core tools for working with streams.
* ipaddress: a3. IPv4/IPv6 manipulation library.
* itertools: a4. Functions creating iterators for efficient looping.
* json: a5. Encode and decode the JSON format.
* json.tool: a6. A command line to validate and pretty-print JSON.
* keyword: a7. Test whether a string is a keyword in Python.
* lib2to3: a8. The 2to3 library
* linecache: a9. Provides random access to individual lines from text
                        files.
* locale: aa. Internationalization services.
* logging: ab. Flexible event logging system for applications.
* logging.config: ac. Configuration of the logging module.
* logging.handlers: ad. Handlers for the logging module.
* lzma: ae. A Python wrapper for the liblzma compression library.
* mailbox: af. Manipulate mailboxes in various formats
* mailcap: b0. Mailcap file handling.
* marshal: b1. Convert Python objects to streams of bytes and back
                        (with different constraints).
* math: b2. Mathematical functions (sin() etc.).
* mimetypes: b3. Mapping of filename extensions to MIME types.
* mmap: b4. Interface to memory-mapped files for Unix and Windows.
* modulefinder: b5. Find modules used by a script.
* msilib: b6. Creation of Microsoft Installer files, and CAB
                        files.
* msvcrt: b7. Miscellaneous useful routines from the MS VC++
                        runtime.
* multiprocessing: b8. Process-based parallelism.
* multiprocessing.connection: b9. API for dealing with sockets.
* multiprocessing.dummy: ba. Dumb wrapper around threading.
* multiprocessing.managers: bb. Share data between process with shared objects.
* multiprocessing.pool: bc. Create pools of processes.
* multiprocessing.shared_memory: bd. Provides shared memory for direct access
                                 across processes.
* multiprocessing.sharedctypes: be. Allocate ctypes objects from shared memory.
* netrc: bf. Loading of .netrc files.
* nis: c0. Interface to Sun’s NIS (Yellow Pages) library.
* nntplib: c1. NNTP protocol client (requires sockets).
* numbers: c2. Numeric abstract base classes (Complex,
                        Real, Integral, etc.).
* operator: c3. Functions corresponding to the standard operators.
* optparse: c4. Command-line option parsing library.
* os: c5. Miscellaneous operating system interfaces.
* os.path: c6. Operations on pathnames.
* ossaudiodev: c7. Access to OSS-compatible audio devices.
* parser: c8. Access parse trees for Python source code.
* pathlib: c9. Object-oriented filesystem paths
* pdb: ca. The Python debugger for interactive interpreters.
* pickle: cb. Convert Python objects to streams of bytes and back.
* pickletools: cc. Contains extensive comments about the pickle protocols
                        and pickle-machine opcodes, as well as some
                        useful functions.
* pipes: cd. A Python interface to Unix shell pipelines.
* pkgutil: ce. Utilities for the import system.
* platform: cf. Retrieves as much platform identifying data as
                        possible.
* plistlib: d0. Generate and parse Mac OS X plist files.
* poplib: d1. POP3 protocol client (requires sockets).
* posix: d2. The most common POSIX system calls (normally used via
                        module os).
* pprint: d3. Data pretty printer.
* profile: d4. Python source profiler.
* pstats: d5. Statistics object for use with the profiler.
* pty: d6. Pseudo-Terminal Handling for Linux.
* pwd: d7. The password database (getpwnam() and friends).
* py_compile: d8. Generate byte-code files from Python source files.
* pyclbr: d9. Supports information extraction for a Python module
                        browser.
* pydoc: da. Documentation generator and online help system.
* queue: db. A synchronized queue class.
* quopri: dc. Encode and decode files using the MIME quoted-
                        printable encoding.
* random: dd. Generate pseudo-random numbers with various common
                        distributions.
* re: de. Regular expression operations.
* readline: df. GNU readline support for Python.
* reprlib: e0. Alternate repr() implementation with size limits.
* resource: e1. An interface to provide resource usage information on
                        the current process.
* rlcompleter: e2. Python identifier completion, suitable for the
                        GNU readline library.
* runpy: e3. Locate and run Python modules without importing them
                        first.
* sched: e4. General purpose event scheduler.
* secrets: e5. Generate secure random numbers for managing secrets.
* select: e6. Wait for I/O completion on multiple streams.
* selectors: e7. High-level I/O multiplexing.
* shelve: e8. Python object persistence.
* shlex: e9. Simple lexical analysis for Unix shell-like languages.
* shutil: ea. High-level file operations, including copying.
* signal: eb. Set handlers for asynchronous events.
* site: ec. Module responsible for site-specific configuration.
* smtpd: ed. A SMTP server implementation in Python.
* smtplib: ee. SMTP protocol client (requires sockets).
* sndhdr: ef. Determine type of a sound file.
* socket: f0. Low-level networking interface.
* socketserver: f1. A framework for network servers.
* spwd: f2. The shadow password database (getspnam() and friends).
* sqlite3: f3. A DB-API 2.0 implementation using SQLite 3.x.
* ssl: f4. TLS/SSL wrapper for socket objects
* stat: f5. Utilities for interpreting the results of
                        os.stat(), os.lstat() and os.fstat().
* statistics: f6. Mathematical statistics functions
* string: f7. Common string operations.
* stringprep: f8. String preparation, as per RFC 3453
* struct: f9. Interpret bytes as packed binary data.
* subprocess: fa. Subprocess management.
* sunau: fb. Provide an interface to the Sun AU sound format.
* symbol: fc. Constants representing internal nodes of the parse
                        tree.
* symtable: fd. Interface to the compiler’s internal symbol tables.
* sys: fe. Access system-specific parameters and functions.
* sysconfig: ff. Python’s configuration information
* syslog: 100. An interface to the Unix syslog library routines.
* tabnanny: 101. Tool for detecting white space related problems in
                        Python source files in a directory tree.
* tarfile: 102. Read and write tar-format archive files.
* telnetlib: 103. Telnet client class.
* tempfile: 104. Generate temporary files and directories.
* termios: 105. POSIX style tty control.
* test: 106. Regression tests package containing the testing suite
                        for Python.
* test.support: 107. Support for Python’s regression test suite.
* test.support.script_helper: 108. Support for Python’s script execution tests.
* textwrap: 109. Text wrapping and filling
* threading: 10a. Thread-based parallelism.
* time: 10b. Time access and conversions.
* timeit: 10c. Measure the execution time of small code snippets.
* tkinter: 10d. Interface to Tcl/Tk for graphical user interfaces
* tkinter.scrolledtext: 10e. Text widget with a vertical scroll bar.
* tkinter.tix: 10f. Tk Extension Widgets for Tkinter
* tkinter.ttk: 110. Tk themed widget set
* token: 111. Constants representing terminal nodes of the parse
                        tree.
* tokenize: 112. Lexical scanner for Python source code.
* trace: 113. Trace or track Python statement execution.
* traceback: 114. Print or retrieve a stack traceback.
* tracemalloc: 115. Trace memory allocations.
* tty: 116. Utility functions that perform common terminal control
                        operations.
* turtle: 117. An educational framework for simple graphics
                        applications
* turtledemo: 118. A viewer for example turtle scripts
* types: 119. Names for built-in types.
* typing: 11a. Support for type hints (see :pep:‘484‘).
* unicodedata: 11b. Access the Unicode Database.
* unittest: 11c. Unit testing framework for Python.
* unittest.mock: 11d. Mock object library.
* urllib: 11e.
* urllib.error: 11f. Exception classes raised by urllib.request.
* urllib.parse: 120. Parse URLs into or assemble them from components.
* urllib.request: 121. Extensible library for opening URLs.
* urllib.response: 122. Response classes used by urllib.
* urllib.robotparser: 123. Load a robots.txt file and answer questions about
                        fetchability of other URLs.
* uu: 124. Encode and decode files in uuencode format.
* uuid: 125. UUID objects (universally unique identifiers)
                        according to RFC 4122
* venv: 126. Creation of virtual environments.
* warnings: 127. Issue warning messages and control their disposition.
* wave: 128. Provide an interface to the WAV sound format.
* weakref: 129. Support for weak references and weak dictionaries.
* webbrowser: 12a. Easy-to-use controller for Web browsers.
* winreg: 12b. Routines and objects for manipulating the Windows
                        registry.
* winsound: 12c. Access to the sound-playing machinery for Windows.
* wsgiref: 12d. WSGI Utilities and Reference Implementation.
* wsgiref.handlers: 12e. WSGI server/gateway base classes.
* wsgiref.headers: 12f. WSGI response header tools.
* wsgiref.simple_server: 130. A simple WSGI HTTP server.
* wsgiref.util: 131. WSGI environment utilities.
* wsgiref.validate: 132. WSGI conformance checker.
* xdrlib: 133. Encoders and decoders for the External Data
                        Representation (XDR).
* xml: 134. Package containing XML processing modules
* xml.dom: 135. Document Object Model API for Python.
* xml.dom.minidom: 136. Minimal Document Object Model (DOM) implementation.
* xml.dom.pulldom: 137. Support for building partial DOM trees from SAX
                        events.
* xml.etree.ElementTree: 138. Implementation of the ElementTree API.
* xml.parsers.expat: 139. An interface to the Expat non-validating XML parser.
* xml.parsers.expat.errors: 13a.
* xml.parsers.expat.model: 13b.
* xml.sax: 13c. Package containing SAX2 base classes and convenience
                        functions.
* xml.sax.handler: 13d. Base classes for SAX event handlers.
* xml.sax.saxutils: 13e. Convenience functions and classes for use with SAX.
* xml.sax.xmlreader: 13f. Interface which SAX-compliant XML parsers must
                        implement.
* xmlrpc.client: 140. XML-RPC client access.
* xmlrpc.server: 141. Basic XML-RPC server implementations.
* zipapp: 142. Manage executable Python zip archives
* zipfile: 143. Read and write ZIP-format archive files.
* zipimport: 144. Support for importing Python modules from ZIP
                        archives.
* zlib: 145. Low-level interface to compression and decompression
                        routines compatible with gzip.


File: python.info,  Node: 索引,  Prev: Python 模块索引,  Up: Top

索引
****

[index]
* Menu:

* ! (exclamation); in a command interpreter: Cmd 对象.       (line   23)
* ! (exclamation); in curses module:     curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  213)
* ! (exclamation); in formatted string literal: 字符串字面值拼接.
                                                             (line   20)
* ! (exclamation); in glob-style wildcards: glob --- Unix 风格路径名模式扩展.
                                                             (line   10)
* ! (exclamation); in glob-style wildcards <1>: fnmatch --- Unix 文件名模式匹配.
                                                             (line   14)
* ! (exclamation); in string formatting: 格式字符串语法.     (line   11)
* ! (exclamation); in struct format strings: 字节顺序，大小和对齐方式.
                                                             (line    9)
* ! (pdb command):                       调试器命令.         (line  258)
* " (double quote); string literal:      字面值.             (line    8)
* """; string literal:                   字符串和字节串字面值.
                                                             (line   34)
* # (hash); comment:                     Python 的非正式介绍.
                                                             (line   12)
* # (hash); comment <1>:                 注释.               (line    6)
* # (hash); comment <2>:                 site —— 站点专属的配置钩子.
                                                             (line   37)
* # (hash); in doctests:                 Option Flags.       (line  183)
* # (hash); in printf-style formatting:  printf 风格的字符串格式化.
                                                             (line   53)
* # (hash); in printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line   52)
* # (hash); in regular expressions:      模块内容.           (line   98)
* # (hash); in string formatting:        格式规格迷你语言.   (line   72)
* # (hash); source encoding declaration: 编码声明.           (line    6)
* $ (dollar); environment variables expansion: os path --- 常用路径操作.
                                                             (line  138)
* $ (dollar); in regular expressions:    正则表达式语法.     (line   46)
* $ (dollar); in template strings:       模板字符串.         (line   11)
* $ (dollar); interpolation in configuration files: 值的插值.
                                                             (line   35)
* % (percent); datetime format:          timezone 对象.      (line   60)
* % (percent); datetime format <1>:      函数<2>.            (line  196)
* % (percent); datetime format <2>:      函数<2>.            (line  313)
* % (percent); environment variables expansion (Windows): os path --- 常用路径操作.
                                                             (line  138)
* % (percent); environment variables expansion (Windows) <1>: 函数<11>.
                                                             (line  212)
* % (percent); interpolation in configuration files: 值的插值.
                                                             (line    9)
* % (percent); printf-style formatting:  printf 风格的字符串格式化.
                                                             (line    6)
* % (percent); printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line    6)
* %=; augmented assignment:              增强赋值语句.       (line    6)
* &=; augmented assignment:              增强赋值语句.       (line    6)
* ’ (single quote); string literal:      字面值.             (line    8)
* ’’’; string literal:                   字符串和字节串字面值.
                                                             (line   34)
* () (parentheses); call:                切片.               (line   30)
* () (parentheses); class definition:    类定义.             (line    6)
* () (parentheses); function definition: 函数定义.           (line    6)
* () (parentheses); generator expression: 生成器表达式<2>.   (line    6)
* () (parentheses); in assignment target list: 赋值语句.     (line   30)
* () (parentheses); in printf-style formatting: printf 风格的字符串格式化.
                                                             (line   21)
* () (parentheses); in printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line   20)
* () (parentheses); in regular expressions: 正则表达式语法.  (line  156)
* () (parentheses); tuple display:       带圆括号的形式.     (line    6)
* (?!; in regular expressions:           正则表达式语法.     (line  254)
* (?#; in regular expressions:           正则表达式语法.     (line  244)
* (?; in regular expressions:            正则表达式语法.     (line  163)
* (?;; in regular expressions:           正则表达式语法.     (line  181)
* (?<!; in regular expressions:          正则表达式语法.     (line  284)
* (?<=; in regular expressions:          正则表达式语法.     (line  260)
* (?=; in regular expressions:           正则表达式语法.     (line  248)
* (?P<; in regular expressions:          正则表达式语法.     (line  207)
* (?P=; in regular expressions:          正则表达式语法.     (line  239)
* * (asterisk); function definition:     函数定义.           (line   65)
* * (asterisk); import statement:        import 语句.        (line   68)
* * (asterisk); in argparse module:      nargs.              (line   48)
* * (asterisk); in assignment target list: 赋值语句.         (line   30)
* * (asterisk); in AST grammar:          节点类.             (line   18)
* * (asterisk); in expression lists:     表达式列表.         (line   14)
* * (asterisk); in function calls:       任意的参数列表.     (line    6)
* * (asterisk); in function calls <1>:   调用.               (line   55)
* * (asterisk); in glob-style wildcards: glob --- Unix 风格路径名模式扩展.
                                                             (line   10)
* * (asterisk); in glob-style wildcards <1>: fnmatch --- Unix 文件名模式匹配.
                                                             (line   14)
* * (asterisk); in printf-style formatting: printf 风格的字符串格式化.
                                                             (line   21)
* * (asterisk); in printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line   20)
* * (asterisk); in regular expressions:  正则表达式语法.     (line   55)
* **; function definition:               函数定义.           (line   65)
* **; in dictionary displays:            字典显示.           (line   19)
* **; in function calls:                 解包参数列表.       (line   17)
* **; in function calls <1>:             调用.               (line   80)
* **; in glob-style wildcards:           glob --- Unix 风格路径名模式扩展.
                                                             (line   37)
* **=; augmented assignment:             增强赋值语句.       (line    6)
* *=; augmented assignment:              增强赋值语句.       (line    6)
* *?; in regular expressions:            正则表达式语法.     (line   69)
* + (plus); binary operator:             二元算术运算符.     (line   47)
* + (plus); binary operator <1>:         数字类型 --- int float complex.
                                                             (line   20)
* + (plus); in argparse module:          nargs.              (line   58)
* + (plus); in doctests:                 Option Flags.       (line  183)
* + (plus); in printf-style formatting:  printf 风格的字符串格式化.
                                                             (line   53)
* + (plus); in printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line   52)
* + (plus); in regular expressions:      正则表达式语法.     (line   60)
* + (plus); in string formatting:        格式规格迷你语言.   (line   59)
* + (plus); unary operator:              一元算术和位运算.   (line   12)
* + (plus); unary operator <1>:          数字类型 --- int float complex.
                                                             (line   20)
* +=; augmented assignment:              增强赋值语句.       (line    6)
* +?; in regular expressions:            正则表达式语法.     (line   69)
* , (comma):                             带圆括号的形式.     (line   18)
* , (comma); argument list:              切片.               (line   30)
* , (comma); expression list:            列表显示.           (line    6)
* , (comma); expression list <1>:        集合显示.           (line    6)
* , (comma); expression list <2>:        表达式列表.         (line    6)
* , (comma); expression list <3>:        assert 语句.        (line    6)
* , (comma); expression list <4>:        类定义.             (line    6)
* , (comma); identifier list:            global 语句.        (line    6)
* , (comma); identifier list <1>:        nonlocal 语句.      (line    6)
* , (comma); import statement:           import 语句.        (line    6)
* , (comma); in dictionary displays:     字典显示.           (line    6)
* , (comma); in string formatting:       格式规格迷你语言.   (line   80)
* , (comma); in target list:             赋值语句.           (line   30)
* , (comma); parameter list:             函数定义.           (line    6)
* , (comma); slicing:                    切片.               (line    6)
* , (comma); with statement:             with 语句.          (line    6)
* - (minus); binary operator:            二元算术运算符.     (line   51)
* - (minus); binary operator <1>:        数字类型 --- int float complex.
                                                             (line   20)
* - (minus); in doctests:                Option Flags.       (line  182)
* - (minus); in glob-style wildcards:    glob --- Unix 风格路径名模式扩展.
                                                             (line   10)
* - (minus); in glob-style wildcards <1>: fnmatch --- Unix 文件名模式匹配.
                                                             (line   14)
* - (minus); in printf-style formatting: printf 风格的字符串格式化.
                                                             (line   53)
* - (minus); in printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line   52)
* - (minus); in regular expressions:     正则表达式语法.     (line  114)
* - (minus); in string formatting:       格式规格迷你语言.   (line   59)
* - (minus); unary operator:             一元算术和位运算.   (line   10)
* - (minus); unary operator <1>:         数字类型 --- int float complex.
                                                             (line   20)
* -=; augmented assignment:              增强赋值语句.       (line    6)
* ->; function annotations:              函数标注.           (line    6)
* ->; function annotations <1>:          函数定义.           (line   77)
* . (dot); attribute reference:          属性引用.           (line    6)
* . (dot); in glob-style wildcards:      glob --- Unix 风格路径名模式扩展.
                                                             (line   10)
* . (dot); in numeric literal:           整型数字面值.       (line   35)
* . (dot); in pathnames:                 其他系统信息.       (line   67)
* . (dot); in pathnames <1>:             其他系统信息.       (line   90)
* . (dot); in printf-style formatting:   printf 风格的字符串格式化.
                                                             (line   21)
* . (dot); in printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line   20)
* . (dot); in regular expressions:       正则表达式语法.     (line   36)
* . (dot); in string formatting:         格式字符串语法.     (line   11)
* . (dot); in Tkinter:                   A Very Quick Look at Tcl/Tk.
                                                             (line   44)
* ...:                                   术语对照表.         (line    9)
* ...; ellipsis literal:                 标准类型层级结构.   (line   30)
* ...; ellipsis literal <1>:             内置常量.           (line   47)
* ...; ellipsis literal <2>:             空对象.             (line   10)
* ...; in doctests:                      Option Flags.       (line   49)
* ...; interpreter prompt:               How are Docstring Examples Recognized?.
                                                             (line   26)
* ...; interpreter prompt <1>:           sys --- 系统相关的参数和函数.
                                                             (line 1010)
* ...; placeholder:                      textwrap --- 文本自动换行与填充.
                                                             (line  232)
* ...; placeholder <1>:                  pprint --- 数据美化输出.
                                                             (line   23)
* ...; placeholder <2>:                  reprlib --- 另一种 repr 实现.
                                                             (line   34)
* ..; in pathnames:                      其他系统信息.       (line   72)
* .ini; file:                            configparser --- 配置文件解析器.
                                                             (line    8)
* .pdbrc; file:                          调试器命令.         (line   27)
* / (slash); function definition:        函数定义.           (line   65)
* / (slash); in pathnames:               其他系统信息.       (line   77)
* / (slash); in pathnames <1>:           其他系统信息.       (line   84)
* //=; augmented assignment:             增强赋值语句.       (line    6)
* /=; augmented assignment:              增强赋值语句.       (line    6)
* 0b; integer literal:                   数字字面值.         (line   12)
* 0o; integer literal:                   数字字面值.         (line   12)
* 0x; integer literal:                   数字字面值.         (line   12)
* 2-digit years:                         time --- 时间的访问和转换.
                                                             (line   28)
* 2to3:                                  术语对照表.         (line   20)
* ; (colon); annotated variable:         带标注的赋值语句.   (line    6)
* ; (colon); compound statement:         if 语句<2>.         (line    6)
* ; (colon); compound statement <1>:     while 语句.         (line    6)
* ; (colon); compound statement <2>:     for 语句<2>.        (line    6)
* ; (colon); compound statement <3>:     try 语句.           (line    6)
* ; (colon); compound statement <4>:     with 语句.          (line    6)
* ; (colon); compound statement <5>:     函数定义.           (line    6)
* ; (colon); compound statement <6>:     类定义.             (line    6)
* ; (colon); function annotations:       函数标注.           (line    6)
* ; (colon); function annotations <1>:   函数定义.           (line   77)
* ; (colon); in dictionary expressions:  字典显示.           (line    6)
* ; (colon); in formatted string literal: 字符串字面值拼接.  (line   20)
* ; (colon); in SQL statements:          Cursor 对象.        (line   10)
* ; (colon); in string formatting:       格式字符串语法.     (line   11)
* ; (colon); lambda expression:          lambda 表达式.      (line    6)
* ; (colon); path separator (POSIX):     其他系统信息.       (line   95)
* ; (colon); slicing:                    切片.               (line    6)
* ; (semicolon):                         复合语句.           (line   15)
* ; (semicolon) <1>:                     其他系统信息.       (line   95)
* < (less); in string formatting:        格式规格迷你语言.   (line   36)
* < (less); in struct format strings:    字节顺序，大小和对齐方式.
                                                             (line    9)
* <<=; augmented assignment:             增强赋值语句.       (line    6)
* <BLANKLINE>:                           Option Flags.       (line   30)
* = (equals); assignment statement:      赋值语句.           (line    6)
* = (equals); class definition:          元类.               (line    6)
* = (equals); for help in debugging using string literals: 字符串字面值拼接.
                                                             (line   19)
* = (equals); function definition:       函数定义.           (line   46)
* = (equals); in function calls:         切片.               (line   29)
* = (equals); in string formatting:      格式规格迷你语言.   (line   36)
* = (equals); in struct format strings:  字节顺序，大小和对齐方式.
                                                             (line    9)
* > (greater); in string formatting:     格式规格迷你语言.   (line   36)
* > (greater); in struct format strings: 字节顺序，大小和对齐方式.
                                                             (line    9)
* >>=; augmented assignment:             增强赋值语句.       (line    6)
* >>>:                                   术语对照表.         (line    6)
* >>>; interpreter prompt:               How are Docstring Examples Recognized?.
                                                             (line   26)
* >>>; interpreter prompt <1>:           sys --- 系统相关的参数和函数.
                                                             (line 1010)
* ? (question mark); in a command interpreter: Cmd 对象.     (line   23)
* ? (question mark); in argparse module: nargs.              (line   19)
* ? (question mark); in AST grammar:     节点类.             (line   18)
* ? (question mark); in glob-style wildcards: glob --- Unix 风格路径名模式扩展.
                                                             (line   10)
* ? (question mark); in glob-style wildcards <1>: fnmatch --- Unix 文件名模式匹配.
                                                             (line   14)
* ? (question mark); in regular expressions: 正则表达式语法. (line   65)
* ? (question mark); in SQL statements:  Cursor 对象.        (line   10)
* ? (question mark); in struct format strings: 格式字符.     (line   84)
* ? (question mark); in struct format strings <1>: 格式字符. (line  141)
* ? (question mark); replacement character: 错误处理方案.    (line   25)
* ??; in regular expressions:            正则表达式语法.     (line   69)
* @ (at); class definition:              类定义.             (line   35)
* @ (at); function definition:           函数定义.           (line   30)
* @ (at); in struct format strings:      字节顺序，大小和对齐方式.
                                                             (line    9)
* [] (square brackets); in assignment target list: 赋值语句. (line   30)
* [] (square brackets); in glob-style wildcards: glob --- Unix 风格路径名模式扩展.
                                                             (line   10)
* [] (square brackets); in glob-style wildcards <1>: fnmatch --- Unix 文件名模式匹配.
                                                             (line   14)
* [] (square brackets); in regular expressions: 正则表达式语法.
                                                             (line  107)
* [] (square brackets); in string formatting: 格式字符串语法.
                                                             (line   11)
* [] (square brackets); list expression: 列表显示.           (line    6)
* [] (square brackets); subscription:    抽取.               (line    6)
* \ (backslash); escape sequence:        字符串和字节串字面值.
                                                             (line   62)
* \ (backslash); escape sequence <1>:    错误处理方案.       (line   25)
* \ (backslash); in pathnames (Windows): 其他系统信息.       (line   77)
* \ (backslash); in regular expressions: 正则表达式语法.     (line   96)
* \ (backslash); in regular expressions <1>: 正则表达式语法. (line  123)
* \ (backslash); in regular expressions <2>: 正则表达式语法. (line  302)
* \a; escape sequence:                   字符串和字节串字面值.
                                                             (line   62)
* \A; in regular expressions:            正则表达式语法.     (line  311)
* \a; in regular expressions:            正则表达式语法.     (line  394)
* \b; escape sequence:                   字符串和字节串字面值.
                                                             (line   62)
* \b; in regular expressions:            正则表达式语法.     (line  315)
* \B; in regular expressions:            正则表达式语法.     (line  328)
* \b; in regular expressions <1>:        正则表达式语法.     (line  394)
* \d; in regular expressions:            正则表达式语法.     (line  336)
* \D; in regular expressions:            正则表达式语法.     (line  348)
* \f; escape sequence:                   字符串和字节串字面值.
                                                             (line   62)
* \f; in regular expressions:            正则表达式语法.     (line  394)
* \g; in regular expressions:            模块内容.           (line  225)
* \n; escape sequence:                   字符串和字节串字面值.
                                                             (line   62)
* \N; escape sequence:                   字符串和字节串字面值.
                                                             (line   62)
* \N; escape sequence <1>:               错误处理方案.       (line   25)
* \n; in regular expressions:            正则表达式语法.     (line  394)
* \N; in regular expressions:            正则表达式语法.     (line  394)
* \r; escape sequence:                   字符串和字节串字面值.
                                                             (line   62)
* \r; in regular expressions:            正则表达式语法.     (line  394)
* \s; in regular expressions:            正则表达式语法.     (line  353)
* \S; in regular expressions:            正则表达式语法.     (line  365)
* \t; escape sequence:                   字符串和字节串字面值.
                                                             (line   62)
* \t; in regular expressions:            正则表达式语法.     (line  394)
* \u; escape sequence:                   字符串和字节串字面值.
                                                             (line   62)
* \U; escape sequence:                   字符串和字节串字面值.
                                                             (line   62)
* \u; escape sequence <1>:               错误处理方案.       (line   25)
* \U; escape sequence <1>:               错误处理方案.       (line   25)
* \u; in regular expressions:            正则表达式语法.     (line  394)
* \U; in regular expressions:            正则表达式语法.     (line  394)
* \v; escape sequence:                   字符串和字节串字面值.
                                                             (line   62)
* \v; in regular expressions:            正则表达式语法.     (line  394)
* \w; in regular expressions:            正则表达式语法.     (line  370)
* \W; in regular expressions:            正则表达式语法.     (line  384)
* \x; escape sequence:                   字符串和字节串字面值.
                                                             (line   62)
* \x; escape sequence <1>:               错误处理方案.       (line   25)
* \x; in regular expressions:            正则表达式语法.     (line  394)
* \Z; in regular expressions:            正则表达式语法.     (line  390)
* \\; escape sequence:                   字符串和字节串字面值.
                                                             (line   62)
* \\; in regular expressions:            正则表达式语法.     (line  394)
* ^ (caret); in curses module:           curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  213)
* ^ (caret); in regular expressions:     正则表达式语法.     (line   41)
* ^ (caret); in regular expressions <1>: 正则表达式语法.     (line  127)
* ^ (caret); in string formatting:       格式规格迷你语言.   (line   36)
* ^ (caret); marker:                     What About Exceptions?.
                                                             (line   93)
* ^ (caret); marker <1>:                 traceback --- 打印或检索堆栈回溯.
                                                             (line   44)
* ^=; augmented assignment:              增强赋值语句.       (line    6)
* _ (underscore); gettext:               GNU gettext API.    (line   37)
* _ (underscore); in numeric literal:    数字字面值.         (line   11)
* _ (underscore); in numeric literal <1>: 整型数字面值.      (line   34)
* _ (underscore); in string formatting:  格式规格迷你语言.   (line   85)
* _, identifiers:                        关键字.             (line   17)
* _anonymous_ (ctypes.Structure 属性):   结构化数据类型.     (line   65)
* _asdict() (collections.somenamedtuple 方法): namedtuple 命名元组的工厂函数.
                                                             (line   90)
* _b_base_ (ctypes._CData 属性):         数据类型<2>.        (line   62)
* _b_needsfree_ (ctypes._CData 属性):    数据类型<2>.        (line   68)
* _callmethod() (multiprocessing.managers.BaseProxy 方法): 代理对象.
                                                             (line   86)
* _CData (ctypes 中的类):                数据类型<2>.        (line    6)
* _clear_type_cache() (在 sys 模块中):   sys --- 系统相关的参数和函数.
                                                             (line  132)
* _current_frames() (在 sys 模块中):     sys --- 系统相关的参数和函数.
                                                             (line  139)
* _debugmallocstats() (在 sys 模块中):   sys --- 系统相关的参数和函数.
                                                             (line  183)
* _dummy_thread (模块):                  _dummy_thread --- _thread 的替代模块.
                                                             (line    6)
* _enablelegacywindowsfsencoding() (在 sys 模块中): sys --- 系统相关的参数和函数.
                                                             (line 1227)
* _exit() (在 os 模块中):                进程管理.           (line   97)
* _fields (ast.AST 属性):                节点类.             (line   18)
* _fields (collections.somenamedtuple 属性): namedtuple 命名元组的工厂函数.
                                                             (line  117)
* _fields_ (ctypes.Structure 属性):      结构化数据类型.     (line   30)
* _field_defaults (collections.somenamedtuple 属性): namedtuple 命名元组的工厂函数.
                                                             (line  130)
* _flush() (wsgiref.handlers.BaseHandler 方法): wsgiref handlers -- server/gateway base classes.
                                                             (line  116)
* _frozen (C 类型):                      导入模块<2>.        (line  257)
* _FuncPtr (ctypes 中的类):              外部函数.           (line   10)
* _getframe() (在 sys 模块中):           sys --- 系统相关的参数和函数.
                                                             (line  613)
* _getvalue() (multiprocessing.managers.BaseProxy 方法): 代理对象.
                                                             (line  123)
* _get_child_mock() (unittest.mock.Mock 方法): Mock 类.      (line  266)
* _handle (ctypes.PyDLL 属性):           加载动态链接库.     (line  118)
* _inittab (C 类型):                     导入模块<2>.        (line  287)
* _length_ (ctypes.Array 属性):          数组与指针.         (line   16)
* _make() (collections.somenamedtuple 类方法): namedtuple 命名元组的工厂函数.
                                                             (line   82)
* _makeResult() (unittest.TextTestRunner 方法): Loading and running tests.
                                                             (line  465)
* _name (ctypes.PyDLL 属性):             加载动态链接库.     (line  122)
* _objects (ctypes._CData 属性):         数据类型<2>.        (line   73)
* _pack_ (ctypes.Structure 属性):        结构化数据类型.     (line   59)
* _parse() (gettext.NullTranslations 方法): NullTranslations 类.
                                                             (line   18)
* _Pointer (ctypes 中的类):              数组与指针.         (line   27)
* _PyBytes_Resize (C 函数):              bytes 对象<2>.      (line  155)
* _PyCFunctionFast (C 类型):             公用对象的结构.     (line  105)
* _PyCFunctionFastWithKeywords (C 类型): 公用对象的结构.     (line  110)
* _PyImport_Fini (C 函数):               导入模块<2>.        (line  235)
* _PyImport_Init (C 函数):               导入模块<2>.        (line  227)
* _PyObject_FastCallDict (C 函数):       对象协议.           (line  358)
* _PyObject_New (C 函数):                在堆上分配对象.     (line    6)
* _PyObject_NewVar (C 函数):             在堆上分配对象.     (line    9)
* _PyObject_Vectorcall (C 函数):         对象协议.           (line  303)
* _PyTuple_Resize (C 函数):              元组对象.           (line   80)
* _Py_c_diff (C 函数):                   表示复数的C结构体.  (line   23)
* _Py_c_neg (C 函数):                    表示复数的C结构体.  (line   27)
* _Py_c_pow (C 函数):                    表示复数的C结构体.  (line   42)
* _Py_c_prod (C 函数):                   表示复数的C结构体.  (line   31)
* _Py_c_quot (C 函数):                   表示复数的C结构体.  (line   35)
* _Py_c_sum (C 函数):                    表示复数的C结构体.  (line   19)
* _Py_InitializeMain (C 函数):           Multi-Phase Initialization Private Provisional API.
                                                             (line   44)
* _Py_NoneStruct (C 变量):               在堆上分配对象.     (line   48)
* _Py_TPFLAGS_HAVE_VECTORCALL (內置变量): PyTypeObject Slots.
                                                             (line  626)
* _replace() (collections.somenamedtuple 方法): namedtuple 命名元组的工厂函数.
                                                             (line  106)
* _setroot() (xml.etree.ElementTree.ElementTree 方法): ElementTree 对象.
                                                             (line   14)
* _SimpleCData (ctypes 中的类):          基础数据类型<2>.    (line    6)
* _structure() (在 email.iterators 模块中): email iterators 迭代器.
                                                             (line   37)
* _thread (模块):                        _thread --- 底层多线程 API.
                                                             (line    6)
* _type_ (ctypes.Array 属性):            数组与指针.         (line   21)
* _type_ (ctypes._Pointer 属性):         数组与指针.         (line   39)
* _write() (wsgiref.handlers.BaseHandler 方法): wsgiref handlers -- server/gateway base classes.
                                                             (line  108)
* _xoptions() (在 sys 模块中):           sys --- 系统相关的参数和函数.
                                                             (line 1422)
* __, identifiers:                       关键字.             (line   16)
* __abs__() (object 方法):               模拟数字类型.       (line   96)
* __abs__() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line   62)
* __add__() (object 方法):               模拟数字类型.       (line    9)
* __add__() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line   67)
* __aenter__() (object 方法):            异步上下文管理器.   (line   11)
* __aexit__() (object 方法):             异步上下文管理器.   (line   16)
* __aiter__() (object 方法):             异步迭代器.         (line   10)
* __all__:                               从包中导入 *.       (line    6)
* __all__ (optional module attribute):   import 语句.        (line   71)
* __all__ (package variable):            导入模块<2>.        (line    7)
* __and__() (object 方法):               模拟数字类型.       (line    9)
* __and__() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line   72)
* __anext__() (agen 方法):               异步生成器-迭代器方法.
                                                             (line    9)
* __anext__() (object 方法):             异步迭代器.         (line   14)
* __annotations__ (class attribute):     标准类型层级结构.   (line  445)
* __annotations__ (function attribute):  标准类型层级结构.   (line  234)
* __annotations__ (module attribute):    标准类型层级结构.   (line  409)
* __await__() (object 方法):             可等待对象.         (line   14)
* __bases__ (class attribute):           标准类型层级结构.   (line  445)
* __bases__ (class 属性):                特殊属性.           (line   17)
* __bool__() (object method):            模拟容器类型.       (line   29)
* __bool__() (object 方法):              基本定制.           (line  242)
* __breakpointhook__() (在 sys 模块中):  sys --- 系统相关的参数和函数.
                                                             (line  280)
* __bytes__() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  100)
* __bytes__() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  112)
* __bytes__() (object 方法):             基本定制.           (line  118)
* __cached__:                            导入相关的模块属性. (line   60)
* __callback__ (weakref.ref 属性):       weakref --- 弱引用. (line   91)
* __call__() (email.headerregistry.HeaderRegistry 方法): email headerregistry 自定义标头对象.
                                                             (line  333)
* __call__() (object method):            调用.               (line  119)
* __call__() (object 方法):              模拟可调用对象.     (line    6)
* __call__() (weakref.finalize 方法):    weakref --- 弱引用. (line  197)
* __cause__ (exception attribute):       raise 语句.         (line   25)
* __cause__ (traceback.TracebackException 属性): TracebackException Objects.
                                                             (line   21)
* __ceil__() (fractions.Fraction 方法):  fractions --- 分数. (line  140)
* __ceil__() (object 方法):              模拟数字类型.       (line  122)
* __classcell__ (class namespace entry): 创建类对象.         (line    6)
* __class_getitem__() (object 类方法):   模拟泛型类型.       (line    9)
* __class__ (instance attribute):        标准类型层级结构.   (line  471)
* __class__ (instance 属性):             特殊属性.           (line   13)
* __class__ (method cell):               创建类对象.         (line    6)
* __class__ (module attribute):          自定义模块属性访问. (line    6)
* __class__ (unittest.mock.Mock 属性):   Mock 类.            (line  517)
* __closure__ (function attribute):      标准类型层级结构.   (line  234)
* __code__ (function attribute):         标准类型层级结构.   (line  234)
* __code__ (function object attribute):  代码对象.           (line    6)
* __complex__() (object 方法):           模拟数字类型.       (line  103)
* __concat__() (在 operator 模块中):     operator --- 标准运算符替代函数.
                                                             (line  158)
* __contains__() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  143)
* __contains__() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  246)
* __contains__() (mailbox.Mailbox 方法): Mailbox 对象.       (line  158)
* __contains__() (object 方法):          模拟容器类型.       (line  117)
* __contains__() (在 operator 模块中):   operator --- 标准运算符替代函数.
                                                             (line  163)
* __context__ (exception attribute):     raise 语句.         (line   25)
* __context__ (traceback.TracebackException 属性): TracebackException Objects.
                                                             (line   25)
* __copy__() (copy protocol):            copy --- 浅层 shallow 和深层 deep 复制操作.
                                                             (line   63)
* __debug__:                             assert 语句.        (line   20)
* __debug__ (內置变量):                  内置常量.           (line   52)
* __deepcopy__() (copy protocol):        copy --- 浅层 shallow 和深层 deep 复制操作.
                                                             (line   63)
* __defaults__ (function attribute):     标准类型层级结构.   (line  234)
* __delattr__() (object 方法):           自定义属性访问.     (line   55)
* __delete__() (object 方法):            实现描述器.         (line   33)
* __delitem__() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  183)
* __delitem__() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  277)
* __delitem__() (mailbox.Mailbox 方法):  Mailbox 对象.       (line   58)
* __delitem__() (mailbox.MH 方法):       MH.                 (line   68)
* __delitem__() (object 方法):           模拟容器类型.       (line   80)
* __delitem__() (在 operator 模块中):    operator --- 标准运算符替代函数.
                                                             (line  172)
* __del__() (io.IOBase 方法):            I/O 基类.           (line  137)
* __del__() (object 方法):               基本定制.           (line   44)
* __dict__ (class attribute):            标准类型层级结构.   (line  445)
* __dict__ (function attribute):         标准类型层级结构.   (line  234)
* __dict__ (instance attribute):         标准类型层级结构.   (line  471)
* __dict__ (module attribute):           标准类型层级结构.   (line  417)
* __dict__ (module attribute) <1>:       模块对象.           (line   42)
* __dict__ (object 属性):                特殊属性.           (line    9)
* __dir__ (module attribute):            自定义模块属性访问. (line    6)
* __dir__() (object 方法):               自定义属性访问.     (line   63)
* __dir__() (unittest.mock.Mock 方法):   Mock 类.            (line  257)
* __displayhook__() (在 sys 模块中):     sys --- 系统相关的参数和函数.
                                                             (line  280)
* __divmod__() (object 方法):            模拟数字类型.       (line    9)
* __doc__ (class attribute):             标准类型层级结构.   (line  445)
* __doc__ (function attribute):          标准类型层级结构.   (line  234)
* __doc__ (method attribute):            标准类型层级结构.   (line  301)
* __doc__ (module attribute):            标准类型层级结构.   (line  409)
* __doc__ (module attribute) <1>:        模块对象.           (line   23)
* __doc__ (types.ModuleType 属性):       标准解释器类型.     (line  112)
* __enter__() (contextmanager 方法):     上下文管理器类型.   (line   10)
* __enter__() (object 方法):             with 语句上下文管理器.
                                                             (line   16)
* __enter__() (winreg.PyHKEY 方法):      Registry Handle Objects.
                                                             (line   56)
* __eq__() (email.charset.Charset 方法): email charset 表示字符集.
                                                             (line  134)
* __eq__() (email.header.Header 方法):   email header 国际化标头.
                                                             (line  134)
* __eq__() (instance method):            比较运算<2>.        (line   46)
* __eq__() (memoryview 方法):            内存视图.           (line   98)
* __eq__() (object 方法):                基本定制.           (line  142)
* __eq__() (在 operator 模块中):         operator --- 标准运算符替代函数.
                                                             (line   19)
* __excepthook__() (在 sys 模块中):      sys --- 系统相关的参数和函数.
                                                             (line  280)
* __exit__() (contextmanager 方法):      上下文管理器类型.   (line   26)
* __exit__() (object 方法):              with 语句上下文管理器.
                                                             (line   21)
* __exit__() (winreg.PyHKEY 方法):       Registry Handle Objects.
                                                             (line   56)
* __file__:                              导入相关的模块属性. (line   58)
* __file__ (module attribute):           标准类型层级结构.   (line  409)
* __file__ (module attribute) <1>:       模块对象.           (line   23)
* __file__ (module attribute) <2>:       模块对象.           (line   81)
* __float__() (object 方法):             模拟数字类型.       (line  103)
* __floordiv__() (object 方法):          模拟数字类型.       (line    9)
* __floordiv__() (在 operator 模块中):   operator --- 标准运算符替代函数.
                                                             (line   77)
* __floor__() (fractions.Fraction 方法): fractions --- 分数. (line  131)
* __floor__() (object 方法):             模拟数字类型.       (line  122)
* __format__:                            内置函数.           (line  538)
* __format__() (datetime.date 方法):     date 对象.          (line  252)
* __format__() (datetime.datetime 方法): datetime 对象.      (line  637)
* __format__() (datetime.time 方法):     time 对象.          (line  194)
* __format__() (object 方法):            基本定制.           (line  123)
* __fspath__() (os.PathLike 方法):       进程参数.           (line  110)
* __func__ (method attribute):           标准类型层级结构.   (line  301)
* __future__:                            术语对照表.         (line  392)
* __future__ (模块):                     __future__ --- Future 语句定义.
                                                             (line    6)
* __future__; future statement:          future 语句.        (line    6)
* __getattribute__() (object 方法):      自定义属性访问.     (line   27)
* __getattr__ (module attribute):        自定义模块属性访问. (line    6)
* __getattr__() (object 方法):           自定义属性访问.     (line    9)
* __getitem__() (email.headerregistry.HeaderRegistry 方法): email headerregistry 自定义标头对象.
                                                             (line  329)
* __getitem__() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  152)
* __getitem__() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  255)
* __getitem__() (mailbox.Mailbox 方法):  Mailbox 对象.       (line  114)
* __getitem__() (mapping object method): 特殊方法名称.       (line    6)
* __getitem__() (object 方法):           模拟容器类型.       (line   60)
* __getitem__() (re.Match 方法):         匹配对象.           (line   69)
* __getitem__() (在 operator 模块中):    operator --- 标准运算符替代函数.
                                                             (line  177)
* __getnewargs_ex__() (object 方法):     封存类实例.         (line   24)
* __getnewargs__() (object 方法):        封存类实例.         (line   39)
* __getstate__() (copy protocol):        处理有状态的对象.   (line    6)
* __getstate__() (object 方法):          封存类实例.         (line   52)
* __get__() (object 方法):               实现描述器.         (line   11)
* __ge__() (instance method):            比较运算<2>.        (line   46)
* __ge__() (object 方法):                基本定制.           (line  142)
* __ge__() (在 operator 模块中):         operator --- 标准运算符替代函数.
                                                             (line   19)
* __globals__ (function attribute):      标准类型层级结构.   (line  234)
* __gt__() (instance method):            比较运算<2>.        (line   46)
* __gt__() (object 方法):                基本定制.           (line  142)
* __gt__() (在 operator 模块中):         operator --- 标准运算符替代函数.
                                                             (line   19)
* __hash__() (object 方法):              基本定制.           (line  179)
* __iadd__() (object 方法):              模拟数字类型.       (line   66)
* __iadd__() (在 operator 模块中):       原地运算符.         (line   33)
* __iand__() (object 方法):              模拟数字类型.       (line   66)
* __iand__() (在 operator 模块中):       原地运算符.         (line   38)
* __iconcat__() (在 operator 模块中):    原地运算符.         (line   43)
* __ifloordiv__() (object 方法):         模拟数字类型.       (line   66)
* __ifloordiv__() (在 operator 模块中):  原地运算符.         (line   48)
* __ilshift__() (object 方法):           模拟数字类型.       (line   66)
* __ilshift__() (在 operator 模块中):    原地运算符.         (line   53)
* __imatmul__() (object 方法):           模拟数字类型.       (line   66)
* __imatmul__() (在 operator 模块中):    原地运算符.         (line   68)
* __imod__() (object 方法):              模拟数字类型.       (line   66)
* __imod__() (在 operator 模块中):       原地运算符.         (line   58)
* __import__() (內置函数):               内置函数.           (line 1494)
* __import__() (在 importlib 模块中):    函数<10>.           (line    6)
* __imul__() (object 方法):              模拟数字类型.       (line   66)
* __imul__() (在 operator 模块中):       原地运算符.         (line   63)
* __index__() (object 方法):             模拟数字类型.       (line  110)
* __index__() (在 operator 模块中):      operator --- 标准运算符替代函数.
                                                             (line   82)
* __init_subclass__() (object 类方法):   自定义类创建.       (line   11)
* __init__() (difflib.HtmlDiff 方法):    difflib --- 计算差异的辅助工具.
                                                             (line   74)
* __init__() (logging.Handler 方法):     处理器对象.         (line   12)
* __init__() (logging.logging.Formatter 方法): 格式化程序.   (line   11)
* __init__() (object 方法):              基本定制.           (line   31)
* __instancecheck__() (class 方法):      自定义实例及子类检查.
                                                             (line   13)
* __interactivehook__() (在 sys 模块中): sys --- 系统相关的参数和函数.
                                                             (line  812)
* __int__() (object 方法):               模拟数字类型.       (line  103)
* __invert__() (object 方法):            模拟数字类型.       (line   96)
* __invert__() (在 operator 模块中):     operator --- 标准运算符替代函数.
                                                             (line   87)
* __inv__() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line   87)
* __ior__() (object 方法):               模拟数字类型.       (line   66)
* __ior__() (在 operator 模块中):        原地运算符.         (line   75)
* __ipow__() (object 方法):              模拟数字类型.       (line   66)
* __ipow__() (在 operator 模块中):       原地运算符.         (line   80)
* __irshift__() (object 方法):           模拟数字类型.       (line   66)
* __irshift__() (在 operator 模块中):    原地运算符.         (line   85)
* __isub__() (object 方法):              模拟数字类型.       (line   66)
* __isub__() (在 operator 模块中):       原地运算符.         (line   90)
* __iter__() (container 方法):           迭代器类型.         (line   12)
* __iter__() (iterator 方法):            迭代器类型.         (line   22)
* __iter__() (mailbox.Mailbox 方法):     Mailbox 对象.       (line   89)
* __iter__() (object 方法):              模拟容器类型.       (line   92)
* __iter__() (unittest.TestSuite 方法):  Grouping tests.     (line   60)
* __itruediv__() (object 方法):          模拟数字类型.       (line   66)
* __itruediv__() (在 operator 模块中):   原地运算符.         (line   95)
* __ixor__() (object 方法):              模拟数字类型.       (line   66)
* __ixor__() (在 operator 模块中):       原地运算符.         (line  100)
* __kwdefaults__ (function attribute):   标准类型层级结构.   (line  234)
* __length_hint__() (object 方法):       模拟容器类型.       (line   40)
* __len__() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  139)
* __len__() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  242)
* __len__() (mailbox.Mailbox 方法):      Mailbox 对象.       (line  162)
* __len__() (mapping object method):     基本定制.           (line  244)
* __len__() (object 方法):               模拟容器类型.       (line   27)
* __le__() (instance method):            比较运算<2>.        (line   46)
* __le__() (object 方法):                基本定制.           (line  142)
* __le__() (在 operator 模块中):         operator --- 标准运算符替代函数.
                                                             (line   19)
* __loader__:                            导入相关的模块属性. (line   14)
* __loader__ (module attribute):         模块对象.           (line   23)
* __loader__ (types.ModuleType 属性):    标准解释器类型.     (line  116)
* __lshift__() (object 方法):            模拟数字类型.       (line    9)
* __lshift__() (在 operator 模块中):     operator --- 标准运算符替代函数.
                                                             (line   94)
* __lt__() (instance method):            比较运算<2>.        (line   46)
* __lt__() (object 方法):                基本定制.           (line  142)
* __lt__() (在 operator 模块中):         operator --- 标准运算符替代函数.
                                                             (line   19)
* __main__ (模块):                       __main__ --- 顶层脚本环境.
                                                             (line    6)
* __matmul__() (object 方法):            模拟数字类型.       (line    9)
* __matmul__() (在 operator 模块中):     operator --- 标准运算符替代函数.
                                                             (line  109)
* __missing__():                         映射类型 --- dict.  (line   80)
* __missing__() (collections.defaultdict 方法): defaultdict 对象.
                                                             (line   19)
* __missing__() (object 方法):           模拟容器类型.       (line   87)
* __module__ (class attribute):          标准类型层级结构.   (line  445)
* __module__ (function attribute):       标准类型层级结构.   (line  234)
* __module__ (method attribute):         标准类型层级结构.   (line  301)
* __mod__() (object 方法):               模拟数字类型.       (line    9)
* __mod__() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line   99)
* __mro__ (class 属性):                  特殊属性.           (line   31)
* __mul__() (object 方法):               模拟数字类型.       (line    9)
* __mul__() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line  104)
* __name__:                              导入相关的模块属性. (line    9)
* __name__ (class attribute):            标准类型层级结构.   (line  445)
* __name__ (definition 属性):            特殊属性.           (line   21)
* __name__ (function attribute):         标准类型层级结构.   (line  234)
* __name__ (method attribute):           标准类型层级结构.   (line  301)
* __name__ (module attribute):           标准类型层级结构.   (line  409)
* __name__ (module attribute) <1>:       模块对象.           (line   23)
* __name__ (module attribute) <2>:       模块对象.           (line   55)
* __name__ (types.ModuleType 属性):      标准解释器类型.     (line  130)
* __neg__() (object 方法):               模拟数字类型.       (line   96)
* __neg__() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line  116)
* __new__() (object 方法):               基本定制.           (line    6)
* __next__() (csv.csvreader 方法):       Reader 对象.        (line    9)
* __next__() (generator 方法):           生成器-迭代器的方法.
                                                             (line   11)
* __next__() (iterator 方法):            迭代器类型.         (line   28)
* __ne__() (email.charset.Charset 方法): email charset 表示字符集.
                                                             (line  138)
* __ne__() (email.header.Header 方法):   email header 国际化标头.
                                                             (line  138)
* __ne__() (instance method):            比较运算<2>.        (line   46)
* __ne__() (object 方法):                基本定制.           (line  142)
* __ne__() (在 operator 模块中):         operator --- 标准运算符替代函数.
                                                             (line   19)
* __not__() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line   40)
* __or__() (object 方法):                模拟数字类型.       (line    9)
* __or__() (在 operator 模块中):         operator --- 标准运算符替代函数.
                                                             (line  121)
* __package__:                           导入相关的模块属性. (line   20)
* __package__ (module attribute):        模块对象.           (line   23)
* __package__ (types.ModuleType 属性):   标准解释器类型.     (line  135)
* __path__:                              导入相关的模块属性. (line   48)
* __pos__() (object 方法):               模拟数字类型.       (line   96)
* __pos__() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line  126)
* __pow__() (object 方法):               模拟数字类型.       (line    9)
* __pow__() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line  131)
* __prepare__ (metaclass method):        准备类命名空间.     (line    6)
* __qualname__ (definition 属性):        特殊属性.           (line   25)
* __radd__() (object 方法):              模拟数字类型.       (line   36)
* __rand__() (object 方法):              模拟数字类型.       (line   36)
* __rdivmod__() (object 方法):           模拟数字类型.       (line   36)
* __reduce_ex__() (object 方法):         封存类实例.         (line  130)
* __reduce__() (object 方法):            封存类实例.         (line   88)
* __repr__() (multiprocessing.managers.BaseProxy 方法): 代理对象.
                                                             (line  129)
* __repr__() (netrc.netrc 方法):         netrc 对象.         (line   15)
* __repr__() (object 方法):              基本定制.           (line   92)
* __reversed__() (object 方法):          模拟容器类型.       (line  101)
* __rfloordiv__() (object 方法):         模拟数字类型.       (line   36)
* __rlshift__() (object 方法):           模拟数字类型.       (line   36)
* __rmatmul__() (object 方法):           模拟数字类型.       (line   36)
* __rmod__() (object 方法):              模拟数字类型.       (line   36)
* __rmul__() (object 方法):              模拟数字类型.       (line   36)
* __ror__() (object 方法):               模拟数字类型.       (line   36)
* __round__() (fractions.Fraction 方法): fractions --- 分数. (line  145)
* __round__() (object 方法):             模拟数字类型.       (line  122)
* __rpow__() (object 方法):              模拟数字类型.       (line   36)
* __rrshift__() (object 方法):           模拟数字类型.       (line   36)
* __rshift__() (object 方法):            模拟数字类型.       (line    9)
* __rshift__() (在 operator 模块中):     operator --- 标准运算符替代函数.
                                                             (line  136)
* __rsub__() (object 方法):              模拟数字类型.       (line   36)
* __rtruediv__() (object 方法):          模拟数字类型.       (line   36)
* __rxor__() (object 方法):              模拟数字类型.       (line   36)
* __self__ (method attribute):           标准类型层级结构.   (line  301)
* __setattr__() (object 方法):           自定义属性访问.     (line   44)
* __setitem__() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  164)
* __setitem__() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  265)
* __setitem__() (mailbox.Mailbox 方法):  Mailbox 对象.       (line   70)
* __setitem__() (mailbox.Maildir 方法):  Maildir.            (line   77)
* __setitem__() (object 方法):           模拟容器类型.       (line   73)
* __setitem__() (在 operator 模块中):    operator --- 标准运算符替代函数.
                                                             (line  186)
* __setstate__() (copy protocol):        处理有状态的对象.   (line    6)
* __setstate__() (object 方法):          封存类实例.         (line   59)
* __set_name__() (object 方法):          实现描述器.         (line   37)
* __set__() (object 方法):               实现描述器.         (line   25)
* __slots__:                             术语对照表.         (line  937)
* __spec__:                              导入相关的模块属性. (line   34)
* __spec__ (types.ModuleType 属性):      标准解释器类型.     (line  152)
* __stderr__() (在 sys 模块中):          sys --- 系统相关的参数和函数.
                                                             (line 1289)
* __stdin__() (在 sys 模块中):           sys --- 系统相关的参数和函数.
                                                             (line 1289)
* __stdout__() (在 sys 模块中):          sys --- 系统相关的参数和函数.
                                                             (line 1289)
* __str__() (datetime.date 方法):        date 对象.          (line  227)
* __str__() (datetime.datetime 方法):    datetime 对象.      (line  609)
* __str__() (datetime.time 方法):        time 对象.          (line  185)
* __str__() (email.charset.Charset 方法): email charset 表示字符集.
                                                             (line  129)
* __str__() (email.header.Header 方法):  email header 国际化标头.
                                                             (line  125)
* __str__() (email.headerregistry.Address 方法): email headerregistry 自定义标头对象.
                                                             (line  381)
* __str__() (email.headerregistry.Group 方法): email headerregistry 自定义标头对象.
                                                             (line  410)
* __str__() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line   74)
* __str__() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line   80)
* __str__() (multiprocessing.managers.BaseProxy 方法): 代理对象.
                                                             (line  133)
* __str__() (object 方法):               基本定制.           (line  105)
* __subclasscheck__() (class 方法):      自定义实例及子类检查.
                                                             (line   18)
* __subclasses__() (class 方法):         特殊属性.           (line   40)
* __subclasshook__() (abc.ABCMeta 方法): abc --- 抽象基类.   (line   79)
* __sub__() (object 方法):               模拟数字类型.       (line    9)
* __sub__() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line  141)
* __suppress_context__ (traceback.TracebackException 属性): TracebackException Objects.
                                                             (line   30)
* __traceback__ (exception attribute):   raise 语句.         (line    6)
* __truediv__() (object 方法):           模拟数字类型.       (line    9)
* __truediv__() (在 operator 模块中):    operator --- 标准运算符替代函数.
                                                             (line  146)
* __trunc__() (object 方法):             模拟数字类型.       (line  122)
* __unraisablehook__() (在 sys 模块中):  sys --- 系统相关的参数和函数.
                                                             (line  280)
* __xor__() (object 方法):               模拟数字类型.       (line    9)
* __xor__() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line  151)
* {} (curly brackets); dictionary expression: 字典显示.      (line    6)
* {} (curly brackets); in formatted string literal: 字符串字面值拼接.
                                                             (line   20)
* {} (curly brackets); in regular expressions: 正则表达式语法.
                                                             (line   77)
* {} (curly brackets); in string formatting: 格式字符串语法. (line   11)
* {} (curly brackets); set expression:   集合显示.           (line    6)
* | (vertical bar); in regular expressions: 正则表达式语法.  (line  146)
* |=; augmented assignment:              增强赋值语句.       (line    6)
* ~ (tilde); home directory expansion:   os path --- 常用路径操作.
                                                             (line  119)
* A() (在 re 模块中):                    模块内容.           (line   37)
* a-LAW:                                 audioop --- 处理原始音频数据.
                                                             (line   15)
* A-LAW:                                 aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  140)
* A-LAW <1>:                             sndhdr --- 推测声音文件的类型.
                                                             (line    8)
* a2b_base64() (在 binascii 模块中):     binascii --- 二进制和 ASCII 码互转.
                                                             (line   36)
* a2b_hex() (在 binascii 模块中):        binascii --- 二进制和 ASCII 码互转.
                                                             (line  137)
* a2b_hqx() (在 binascii 模块中):        binascii --- 二进制和 ASCII 码互转.
                                                             (line   66)
* a2b_qp() (在 binascii 模块中):         binascii --- 二进制和 ASCII 码互转.
                                                             (line   49)
* a2b_uu() (在 binascii 模块中):         binascii --- 二进制和 ASCII 码互转.
                                                             (line   23)
* a85decode() (在 base64 模块中):        base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  143)
* a85encode() (在 base64 模块中):        base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  122)
* ABC (abc 中的类):                      abc --- 抽象基类.   (line   22)
* abc (模块):                            abc --- 抽象基类.   (line    6)
* ABCMeta (abc 中的类):                  abc --- 抽象基类.   (line   45)
* abiflags() (在 sys 模块中):            sys --- 系统相关的参数和函数.
                                                             (line   11)
* abort():                               过程控制.           (line    8)
* abort() (asyncio.DatagramTransport 方法): 数据报传输.      (line   14)
* abort() (asyncio.WriteTransport 方法): 只写传输.           (line    6)
* abort() (ftplib.FTP 方法):             FTP 对象.           (line   49)
* abort() (threading.Barrier 方法):      栅栏对象.           (line   70)
* abort() (在 os 模块中):                进程管理.           (line   14)
* above() (curses.panel.Panel 方法):     Panel 对象.         (line   12)
* ABOVE_NORMAL_PRIORITY_CLASS() (在 subprocess 模块中): Windows 常数.
                                                             (line   45)
* abs() (decimal.Context 方法):          上下文对象.         (line  196)
* abs() (內置函数):                      内置函数.           (line   55)
* abs() (在 operator 模块中):            operator --- 标准运算符替代函数.
                                                             (line   62)
* abspath() (在 os.path 模块中):         os path --- 常用路径操作.
                                                             (line   46)
* abstract base class – 抽象基类:        术语对照表.         (line   28)
* AbstractAsyncContextManager (contextlib 中的类): 工具.     (line   18)
* AbstractBasicAuthHandler (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  276)
* AbstractChildWatcher (asyncio 中的类): 进程监视器.         (line   33)
* abstractclassmethod() (在 abc 模块中): abc --- 抽象基类.   (line  206)
* AbstractContextManager (contextlib 中的类): 工具.          (line    8)
* AbstractDigestAuthHandler (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  306)
* AbstractEventLoop (asyncio 中的类):    事件循环实现.       (line   39)
* AbstractEventLoopPolicy (asyncio 中的类): 策略对象.        (line    8)
* AbstractFormatter (formatter 中的类):  Formatter Implementations.
                                                             (line   18)
* abstractmethod() (在 abc 模块中):      abc --- 抽象基类.   (line  141)
* abstractproperty() (在 abc 模块中):    abc --- 抽象基类.   (line  244)
* AbstractSet (typing 中的类):           类 函数和修饰器.    (line  195)
* abstractstaticmethod() (在 abc 模块中): abc --- 抽象基类.  (line  225)
* AbstractWriter (formatter 中的类):     Writer Implementations.
                                                             (line   16)
* accept() (asyncore.dispatcher 方法):   asyncore --- 异步socket处理器.
                                                             (line  187)
* accept() (multiprocessing.connection.Listener 方法): 监听器及客户端.
                                                             (line   74)
* accept() (socket.socket 方法):         套接字对象.         (line   12)
* access() (在 os 模块中):               文件和目录.         (line   40)
* accumulate() (在 itertools 模块中):    Itertool函数.       (line    9)
* aclose() (agen 方法):                  异步生成器-迭代器方法.
                                                             (line   42)
* aclose() (contextlib.AsyncExitStack 方法): 工具.           (line  440)
* acos() (在 cmath 模块中):              三角函数<2>.        (line    6)
* acos() (在 math 模块中):               三角函数.           (line    6)
* acosh() (在 cmath 模块中):             双曲函数<2>.        (line    6)
* acosh() (在 math 模块中):              双曲函数.           (line    8)
* acquire() (asyncio.Condition 方法):    Condition.          (line   42)
* acquire() (asyncio.Lock 方法):         Lock.               (line   34)
* acquire() (asyncio.Semaphore 方法):    Semaphore.          (line   40)
* acquire() (logging.Handler 方法):      处理器对象.         (line   23)
* acquire() (multiprocessing.Lock 方法): 同步原语.           (line   54)
* acquire() (multiprocessing.RLock 方法): 同步原语.          (line   97)
* acquire() (threading.Condition 方法):  条件对象.           (line   71)
* acquire() (threading.Lock 方法):       锁对象.             (line   34)
* acquire() (threading.RLock 方法):      递归锁对象.         (line   27)
* acquire() (threading.Semaphore 方法):  信号量对象.         (line   30)
* acquire() (_thread.lock 方法):         _thread --- 底层多线程 API.
                                                             (line  103)
* acquire_lock() (在 imp 模块中):        imp --- Access the import internals.
                                                             (line  268)
* Action (argparse 中的类):              Action 类.          (line   10)
* action (optparse.Option 属性):         Option attributes.  (line   11)
* ACTIONS (optparse.Option 属性):        Adding new actions. (line   31)
* active_children() (在 multiprocessing 模块中): 杂项<3>.    (line    6)
* active_count() (在 threading 模块中):  threading --- 基于线程的并行.
                                                             (line   27)
* add() (decimal.Context 方法):          上下文对象.         (line  200)
* add() (frozenset 方法):                集合类型 --- set frozenset.
                                                             (line  175)
* add() (mailbox.Mailbox 方法):          Mailbox 对象.       (line   44)
* add() (mailbox.Maildir 方法):          Maildir.            (line   77)
* add() (msilib.RadioButtonGroup 方法):  GUI classes.        (line   34)
* add() (pstats.Stats 方法):             Stats 类.           (line   49)
* add() (tarfile.TarFile 方法):          TarFile 对象.       (line  173)
* add() (tkinter.ttk.Notebook 方法):     ttk Notebook.       (line    8)
* add() (在 audioop 模块中):             audioop --- 处理原始音频数据.
                                                             (line   26)
* add() (在 operator 模块中):            operator --- 标准运算符替代函数.
                                                             (line   67)
* addAsyncCleanup() (unittest.IsolatedAsyncioTestCase 方法): 测试用例.
                                                             (line  833)
* addaudithook() (在 sys 模块中):        sys --- 系统相关的参数和函数.
                                                             (line   21)
* addch() (curses.window 方法):          Window 对象.        (line    9)
* addClassCleanup() (unittest.TestCase 类方法): 测试用例.    (line  769)
* addCleanup() (unittest.TestCase 方法): 测试用例.           (line  739)
* addcomponent() (turtle.Shape 方法):    公共类.             (line   62)
* addError() (unittest.TestResult 方法): Loading and running tests.
                                                             (line  351)
* addExpectedFailure() (unittest.TestResult 方法): Loading and running tests.
                                                             (line  387)
* addFailure() (unittest.TestResult 方法): Loading and running tests.
                                                             (line  362)
* addfile() (tarfile.TarFile 方法):      TarFile 对象.       (line  189)
* addFilter() (logging.Handler 方法):    处理器对象.         (line   46)
* addFilter() (logging.Logger 方法):     记录器对象.         (line  200)
* addHandler() (logging.Logger 方法):    记录器对象.         (line  215)
* addition:                              二元算术运算符.     (line   47)
* addLevelName() (在 logging 模块中):    模块级别函数.       (line  157)
* addModuleCleanup() (在 unittest 模块中): setUpModule and tearDownModule.
                                                             (line   22)
* addnstr() (curses.window 方法):        Window 对象.        (line   20)
* AddPackagePath() (在 modulefinder 模块中): modulefinder --- 查找脚本使用的模块.
                                                             (line   14)
* addr (smtpd.SMTPChannel 属性):         SMTPChannel 对象.   (line   51)
* Address (email.headerregistry 中的类): email headerregistry 自定义标头对象.
                                                             (line  343)
* address (email.headerregistry.SingleAddressHeader 属性): email headerregistry 自定义标头对象.
                                                             (line  180)
* address (multiprocessing.connection.Listener 属性): 监听器及客户端.
                                                             (line   87)
* address (multiprocessing.managers.BaseManager 属性): 管理器.
                                                             (line  101)
* addresses (email.headerregistry.AddressHeader 属性): email headerregistry 自定义标头对象.
                                                             (line  159)
* addresses (email.headerregistry.Group 属性): email headerregistry 自定义标头对象.
                                                             (line  405)
* AddressHeader (email.headerregistry 中的类): email headerregistry 自定义标头对象.
                                                             (line  146)
* addressof() (在 ctypes 模块中):        工具函数.           (line    6)
* AddressValueError:                     Custom Exceptions.  (line    9)
* address_exclude() (ipaddress.IPv4Network 方法): Network objects.
                                                             (line  160)
* address_exclude() (ipaddress.IPv6Network 方法): Network objects.
                                                             (line  342)
* address_family (socketserver.BaseServer 属性): Server 对象<2>.
                                                             (line   65)
* address_string() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  311)
* addr_spec (email.headerregistry.Address 属性): email headerregistry 自定义标头对象.
                                                             (line  376)
* addshape() (在 turtle 模块中):         设置与特殊方法.     (line   68)
* addsitedir() (在 site 模块中):         模块内容<7>.        (line   45)
* addSkip() (unittest.TestResult 方法):  Loading and running tests.
                                                             (line  379)
* addstr() (curses.window 方法):         Window 对象.        (line   27)
* addSubTest() (unittest.TestResult 方法): Loading and running tests.
                                                             (line  405)
* addSuccess() (unittest.TestResult 方法): Loading and running tests.
                                                             (line  373)
* addTest() (unittest.TestSuite 方法):   Grouping tests.     (line   25)
* addTests() (unittest.TestSuite 方法):  Grouping tests.     (line   30)
* addTypeEqualityFunc() (unittest.TestCase 方法): 测试用例.  (line  558)
* addUnexpectedSuccess() (unittest.TestResult 方法): Loading and running tests.
                                                             (line  397)
* add_alias() (在 email.charset 模块中): email charset 表示字符集.
                                                             (line  169)
* add_alternative() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  539)
* add_argument() (argparse.ArgumentParser 方法): add_argument 方法.
                                                             (line    6)
* add_argument_group() (argparse.ArgumentParser 方法): 参数组.
                                                             (line    6)
* add_attachment() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  549)
* add_cgi_vars() (wsgiref.handlers.BaseHandler 方法): wsgiref handlers -- server/gateway base classes.
                                                             (line  132)
* add_charset() (在 email.charset 模块中): email charset 表示字符集.
                                                             (line  145)
* add_child_handler() (asyncio.AbstractChildWatcher 方法): 进程监视器.
                                                             (line   35)
* add_codec() (在 email.charset 模块中): email charset 表示字符集.
                                                             (line  176)
* add_cookie_header() (http.cookiejar.CookieJar 方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   11)
* add_data() (在 msilib 模块中):         msilib --- Read and write Microsoft Installer files.
                                                             (line   74)
* add_dll_directory() (在 os 模块中):    进程管理.           (line   21)
* add_done_callback() (asyncio.Future 方法): Future 对象<2>. (line   69)
* add_done_callback() (asyncio.Task 方法): Task 对象.        (line  134)
* add_done_callback() (concurrent.futures.Future 方法): Future 对象.
                                                             (line   58)
* add_fallback() (gettext.NullTranslations 方法): NullTranslations 类.
                                                             (line   24)
* add_file() (msilib.Directory 方法):    Directory Objects.  (line   30)
* add_flag() (mailbox.MaildirMessage 方法): MaildirMessage.  (line   70)
* add_flag() (mailbox.mboxMessage 方法): mboxMessage.        (line   68)
* add_flag() (mailbox.MMDFMessage 方法): MMDFMessage.        (line   67)
* add_flowing_data() (formatter.formatter 方法): The Formatter Interface.
                                                             (line   43)
* add_folder() (mailbox.Maildir 方法):   Maildir.            (line   59)
* add_folder() (mailbox.MH 方法):        MH.                 (line   37)
* add_get_handler() (email.contentmanager.ContentManager 方法): email contentmanager 管理 MIME 内容.
                                                             (line   64)
* add_handler() (urllib.request.OpenerDirector 方法): OpenerDirector 对象.
                                                             (line    8)
* add_header() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  213)
* add_header() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  307)
* add_header() (urllib.request.Request 方法): Request 对象.  (line   69)
* add_header() (wsgiref.headers.Headers 方法): wsgiref headers -- WSGI response header tools.
                                                             (line   61)
* add_history() (在 readline 模块中):    历史列表.           (line   33)
* add_hor_rule() (formatter.formatter 方法): The Formatter Interface.
                                                             (line   36)
* add_include_dir() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line   94)
* add_label() (mailbox.BabylMessage 方法): BabylMessage.     (line   52)
* add_label_data() (formatter.formatter 方法): The Formatter Interface.
                                                             (line   59)
* add_library() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  111)
* add_library_dir() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  133)
* add_line_break() (formatter.formatter 方法): The Formatter Interface.
                                                             (line   31)
* add_link_object() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  178)
* add_literal_data() (formatter.formatter 方法): The Formatter Interface.
                                                             (line   53)
* add_mutually_exclusive_group() (argparse.ArgumentParser 方法): 互斥.
                                                             (line    6)
* add_option() (optparse.OptionParser 方法): 定义选项.       (line   14)
* add_parent() (urllib.request.BaseHandler 方法): BaseHandler 对象.
                                                             (line    9)
* add_password() (urllib.request.HTTPPasswordMgr 方法): HTTPPasswordMgr 对象.
                                                             (line    9)
* add_password() (urllib.request.HTTPPasswordMgrWithPriorAuth 方法): HTTPPasswordMgrWithPriorAuth 对象.
                                                             (line    9)
* add_reader() (asyncio.loop 方法):      监控文件描述符.     (line    6)
* add_related() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  528)
* add_runtime_library_dir() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  148)
* add_section() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line   73)
* add_section() (configparser.RawConfigParser 方法): RawConfigParser 对象.
                                                             (line   23)
* add_sequence() (mailbox.MHMessage 方法): MHMessage.        (line   38)
* add_set_handler() (email.contentmanager.ContentManager 方法): email contentmanager 管理 MIME 内容.
                                                             (line   69)
* add_signal_handler() (asyncio.loop 方法): Unix 信号.       (line    6)
* add_stream() (在 msilib 模块中):       msilib --- Read and write Microsoft Installer files.
                                                             (line  104)
* add_subparsers() (argparse.ArgumentParser 方法): 子命令.   (line    6)
* add_tables() (在 msilib 模块中):       msilib --- Read and write Microsoft Installer files.
                                                             (line   95)
* add_type() (在 mimetypes 模块中):      mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line   89)
* add_unredirected_header() (urllib.request.Request 方法): Request 对象.
                                                             (line   77)
* add_writer() (asyncio.loop 方法):      监控文件描述符.     (line   15)
* adjusted() (decimal.Decimal 方法):     Decimal 对象.       (line   94)
* adler32() (在 zlib 模块中):            zlib --- 与 gzip 兼容的压缩.
                                                             (line   24)
* ADPCM, Intel/DVI:                      audioop --- 处理原始音频数据.
                                                             (line   15)
* adpcm2lin() (在 audioop 模块中):       audioop --- 处理原始音频数据.
                                                             (line   32)
* AF_ALG() (在 socket 模块中):           常量<8>.            (line  176)
* AF_CAN() (在 socket 模块中):           常量<8>.            (line   88)
* AF_INET() (在 socket 模块中):          常量<8>.            (line   11)
* AF_INET6() (在 socket 模块中):         常量<8>.            (line   11)
* AF_LINK() (在 socket 模块中):          常量<8>.            (line  200)
* AF_PACKET() (在 socket 模块中):        常量<8>.            (line  137)
* AF_QIPCRTR() (在 socket 模块中):       常量<8>.            (line  225)
* AF_RDS() (在 socket 模块中):           常量<8>.            (line  147)
* AF_UNIX() (在 socket 模块中):          常量<8>.            (line   11)
* AF_VSOCK() (在 socket 模块中):         常量<8>.            (line  187)
* aifc (模块):                           aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line    6)
* aifc() (aifc.aifc 方法):               aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  116)
* AIFF:                                  aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line    8)
* AIFF <1>:                              chunk --- 读取 IFF 分块数据.
                                                             (line    8)
* aiff() (aifc.aifc 方法):               aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  111)
* AIFF-C:                                aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line    8)
* AIFF-C <1>:                            chunk --- 读取 IFF 分块数据.
                                                             (line    8)
* alarm() (在 signal 模块中):            模块内容<5>.        (line  211)
* alaw2lin() (在 audioop 模块中):        audioop --- 处理原始音频数据.
                                                             (line   38)
* AlertDescription (ssl 中的类):         常量<9>.            (line  441)
* ALERT_DESCRIPTION_HANDSHAKE_FAILURE() (在 ssl 模块中): 常量<9>.
                                                             (line  428)
* ALERT_DESCRIPTION_INTERNAL_ERROR() (在 ssl 模块中): 常量<9>.
                                                             (line  428)
* algorithms_available() (在 hashlib 模块中): 哈希算法.      (line   74)
* algorithms_guaranteed() (在 hashlib 模块中): 哈希算法.     (line   66)
* alias (pdb command):                   调试器命令.         (line  236)
* alignment() (在 ctypes 模块中):        工具函数.           (line   12)
* alive (weakref.finalize 属性):         weakref --- 弱引用. (line  214)
* all() (內置函数):                      内置函数.           (line   61)
* allocate_lock() (在 _thread 模块中):   _thread --- 底层多线程 API.
                                                             (line   57)
* allocfunc (C 类型):                    Slot Type typedefs. (line    6)
* allowed_domains() (http.cookiejar.DefaultCookiePolicy 方法): DefaultCookiePolicy 对象.
                                                             (line   65)
* allow_reuse_address (socketserver.BaseServer 属性): Server 对象<2>.
                                                             (line   92)
* all_errors() (在 ftplib 模块中):       ftplib --- FTP 协议客户端.
                                                             (line  122)
* all_features() (在 xml.sax.handler 模块中): xml sax handler --- SAX 处理程序的基类.
                                                             (line   81)
* all_frames (tracemalloc.Filter 属性):  过滤器.             (line   57)
* all_properties() (在 xml.sax.handler 模块中): xml sax handler --- SAX 处理程序的基类.
                                                             (line  113)
* all_suffixes() (在 importlib.machinery 模块中): importlib machinery -- Importers and path hooks.
                                                             (line   54)
* all_tasks() (asyncio.Task 类方法):     Task 对象.          (line  206)
* all_tasks() (在 asyncio 模块中):       内省.               (line   16)
* alt() (在 curses.ascii 模块中):        curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  206)
* altsep() (在 os 模块中):               其他系统信息.       (line   84)
* altzone() (在 time 模块中):            时区常量.           (line    6)
* ALT_DIGITS() (在 locale 模块中):       locale --- 国际化服务.
                                                             (line  278)
* ALWAYS_EQ() (在 test.support 模块中):  test support --- Utilities for the Python test suite.
                                                             (line  145)
* ALWAYS_TYPED_ACTIONS (optparse.Option 属性): Adding new actions.
                                                             (line   43)
* AMPER() (在 token 模块中):             token --- 与Python解析树一起使用的常量.
                                                             (line   98)
* AMPEREQUAL() (在 token 模块中):        token --- 与Python解析树一起使用的常量.
                                                             (line  186)
* and_() (在 operator 模块中):           operator --- 标准运算符替代函数.
                                                             (line   72)
* annotated; assignment:                 带标注的赋值语句.   (line    6)
* annotation (inspect.Parameter 属性):   Introspecting callables with the Signature object.
                                                             (line  173)
* annotation – 标注:                     术语对照表.         (line   41)
* announce() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  500)
* anonymous; function:                   lambda 表达式.      (line    6)
* answer_challenge() (在 multiprocessing.connection 模块中): 监听器及客户端.
                                                             (line   23)
* anticipate_failure() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  567)
* any() (內置函数):                      内置函数.           (line   72)
* Any() (在 typing 模块中):              类 函数和修饰器.    (line  709)
* ANY() (在 unittest.mock 模块中):       ANY.                (line    6)
* AnyStr() (在 typing 模块中):           类 函数和修饰器.    (line  870)
* api_version() (在 sys 模块中):         sys --- 系统相关的参数和函数.
                                                             (line 1392)
* apop() (poplib.POP3 方法):             POP3 对象.          (line   38)
* APPDATA:                               PEP 370 分用户的 site-packages 目录.
                                                             (line   26)
* append() (array.array 方法):           array --- 高效的数值数组.
                                                             (line  104)
* append() (collections.deque 方法):     deque 对象.         (line   27)
* append() (email.header.Header 方法):   email header 国际化标头.
                                                             (line   77)
* append() (imaplib.IMAP4 方法):         IMAP4 Objects.      (line   33)
* append() (msilib.CAB 方法):            CAB Objects.        (line   15)
* append() (pipes.Template 方法):        模板对象.           (line   22)
* append() (sequence method):            可变序列类型.       (line   14)
* append() (xml.etree.ElementTree.Element 方法): 元素对象.   (line   74)
* appendChild() (xml.dom.Node 方法):     节点对象.           (line   99)
* appendleft() (collections.deque 方法): deque 对象.         (line   31)
* append_history_file() (在 readline 模块中): 历史文件.      (line   18)
* application_uri() (在 wsgiref.util 模块中): wsgiref util -- WSGI environment utilities.
                                                             (line   32)
* apply (2to3 fixer):                    修复器.             (line   10)
* apply() (multiprocessing.pool.Pool 方法): 进程池.          (line   49)
* apply_async() (multiprocessing.pool.Pool 方法): 进程池.    (line   55)
* apply_defaults() (inspect.BoundArguments 方法): Introspecting callables with the Signature object.
                                                             (line  310)
* architecture() (在 platform 模块中):   跨平台.             (line    6)
* archive (zipimport.zipimporter 属性):  zipimporter 对象.   (line   62)
* aRepr() (在 reprlib 模块中):           reprlib --- 另一种 repr 实现.
                                                             (line   20)
* argparse (模块):                       argparse --- 命令行选项、参数和子命令解析器.
                                                             (line    6)
* args (BaseException 属性):             基类.               (line   14)
* args (functools.partial 属性):         partial 对象.       (line   14)
* args (inspect.BoundArguments 属性):    Introspecting callables with the Signature object.
                                                             (line  296)
* args (pdb command):                    调试器命令.         (line  189)
* args (subprocess.CompletedProcess 属性): 使用 subprocess 模块.
                                                             (line   81)
* args (subprocess.Popen 属性):          Popen 对象.         (line   85)
* args_from_interpreter_flags() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  391)
* argtypes (ctypes._FuncPtr 属性):       外部函数.           (line   29)
* argument – 参数:                       术语对照表.         (line   52)
* argument; call semantics:              切片.               (line   30)
* argument; difference from parameter:   如何将可选参数或关键字参数从一个函数传递到另一个函数？.
                                                             (line   16)
* argument; function definition:         函数定义.           (line   46)
* ArgumentDefaultsHelpFormatter (argparse 中的类): formatter_class.
                                                             (line    9)
* ArgumentError:                         外部函数.           (line   64)
* ArgumentParser (argparse 中的类):      ArgumentParser 对象.
                                                             (line    6)
* arguments (inspect.BoundArguments 属性): Introspecting callables with the Signature object.
                                                             (line  280)
* argv (in module sys):                  Process-wide parameters.
                                                             (line  217)
* argv() (在 sys 模块中):                sys --- 系统相关的参数和函数.
                                                             (line   49)
* arithmetic:                            数字类型 --- int float complex.
                                                             (line   20)
* arithmetic; conversion:                算术转换.           (line    6)
* ArithmeticError:                       基类.               (line   36)
* array (array 中的类):                  array --- 高效的数值数组.
                                                             (line   71)
* Array (ctypes 中的类):                 数组与指针.         (line    6)
* array (模块):                          array --- 高效的数值数组.
                                                             (line    6)
* Array() (multiprocessing.managers.SyncManager 方法): 管理器.
                                                             (line  171)
* Array() (在 multiprocessing 模块中):   共享 ctypes 对象.   (line   38)
* Array() (在 multiprocessing.sharedctypes 模块中): multiprocessing sharedctypes 模块.
                                                             (line   43)
* arrays:                                array --- 高效的数值数组.
                                                             (line    6)
* arraysize (sqlite3.Cursor 属性):       Cursor 对象.        (line  193)
* article() (nntplib.NNTP 方法):         方法<3>.            (line  240)
* as; except clause:                     try 语句.           (line   31)
* as; import statement:                  import 语句.        (line   33)
* as; with statement:                    with 语句.          (line    6)
* ASCII:                                 标注.               (line   23)
* ASCII <1>:                             字面值.             (line    8)
* ascii() (內置函数):                    内置函数.           (line   83)
* ascii() (在 curses.ascii 模块中):      curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  197)
* ASCII() (在 re 模块中):                模块内容.           (line   37)
* ascii_letters() (在 string 模块中):    字符串常量.         (line    8)
* ascii_lowercase() (在 string 模块中):  字符串常量.         (line   13)
* ascii_uppercase() (在 string 模块中):  字符串常量.         (line   18)
* asctime() (在 time 模块中):            函数<2>.            (line    6)
* asdict() (在 dataclasses 模块中):      模块级装饰器、类和函数.
                                                             (line  217)
* asend() (agen 方法):                   异步生成器-迭代器方法.
                                                             (line   22)
* asin() (在 cmath 模块中):              三角函数<2>.        (line   12)
* asin() (在 math 模块中):               三角函数.           (line   10)
* asinh() (在 cmath 模块中):             双曲函数<2>.        (line   11)
* asinh() (在 math 模块中):              双曲函数.           (line   12)
* assertAlmostEqual() (unittest.TestCase 方法): 测试用例.    (line  482)
* assertCountEqual() (unittest.TestCase 方法): 测试用例.     (line  537)
* assertDictEqual() (unittest.TestCase 方法): 测试用例.      (line  645)
* assertEqual() (unittest.TestCase 方法): 测试用例.          (line  177)
* assertFalse() (unittest.TestCase 方法): 测试用例.          (line  201)
* assertGreater() (unittest.TestCase 方法): 测试用例.        (line  506)
* assertGreaterEqual() (unittest.TestCase 方法): 测试用例.   (line  506)
* assertIn() (unittest.TestCase 方法):   测试用例.           (line  228)
* AssertionError:                        具体异常.           (line    8)
* assertIs() (unittest.TestCase 方法):   测试用例.           (line  213)
* assertIsInstance() (unittest.TestCase 方法): 测试用例.     (line  235)
* assertIsNone() (unittest.TestCase 方法): 测试用例.         (line  221)
* assertIsNot() (unittest.TestCase 方法): 测试用例.          (line  213)
* assertIsNotNone() (unittest.TestCase 方法): 测试用例.      (line  221)
* assertLess() (unittest.TestCase 方法): 测试用例.           (line  506)
* assertLessEqual() (unittest.TestCase 方法): 测试用例.      (line  506)
* assertListEqual() (unittest.TestCase 方法): 测试用例.      (line  622)
* assertLogs() (unittest.TestCase 方法): 测试用例.           (line  403)
* assertMultiLineEqual() (unittest.TestCase 方法): 测试用例. (line  597)
* assertNotAlmostEqual() (unittest.TestCase 方法): 测试用例. (line  482)
* assertNotEqual() (unittest.TestCase 方法): 测试用例.       (line  196)
* assertNotIn() (unittest.TestCase 方法): 测试用例.          (line  228)
* assertNotIsInstance() (unittest.TestCase 方法): 测试用例.  (line  235)
* assertNotRegex() (unittest.TestCase 方法): 测试用例.       (line  519)
* assertRaises() (unittest.TestCase 方法): 测试用例.         (line  270)
* assertRaisesRegex() (unittest.TestCase 方法): 测试用例.    (line  311)
* assertRegex() (unittest.TestCase 方法): 测试用例.          (line  519)
* asserts (2to3 fixer):                  修复器.             (line   15)
* assertSequenceEqual() (unittest.TestCase 方法): 测试用例.  (line  607)
* assertSetEqual() (unittest.TestCase 方法): 测试用例.       (line  633)
* assertTrue() (unittest.TestCase 方法): 测试用例.           (line  201)
* assertTupleEqual() (unittest.TestCase 方法): 测试用例.     (line  622)
* assertWarns() (unittest.TestCase 方法): 测试用例.          (line  337)
* assertWarnsRegex() (unittest.TestCase 方法): 测试用例.     (line  378)
* assert_any_await() (unittest.mock.AsyncMock 方法): Mock 类.
                                                             (line  789)
* assert_any_call() (unittest.mock.Mock 方法): Mock 类.      (line  127)
* assert_awaited() (unittest.mock.AsyncMock 方法): Mock 类.  (line  719)
* assert_awaited_once() (unittest.mock.AsyncMock 方法): Mock 类.
                                                             (line  739)
* assert_awaited_once_with() (unittest.mock.AsyncMock 方法): Mock 类.
                                                             (line  772)
* assert_awaited_with() (unittest.mock.AsyncMock 方法): Mock 类.
                                                             (line  755)
* assert_called() (unittest.mock.Mock 方法): Mock 类.        (line   77)
* assert_called_once() (unittest.mock.Mock 方法): Mock 类.   (line   88)
* assert_called_once_with() (unittest.mock.Mock 方法): Mock 类.
                                                             (line  114)
* assert_called_with() (unittest.mock.Mock 方法): Mock 类.   (line  105)
* assert_has_awaits() (unittest.mock.AsyncMock 方法): Mock 类.
                                                             (line  806)
* assert_has_calls() (unittest.mock.Mock 方法): Mock 类.     (line  143)
* assert_line_data() (formatter.formatter 方法): The Formatter Interface.
                                                             (line  143)
* assert_not_awaited() (unittest.mock.AsyncMock 方法): Mock 类.
                                                             (line  833)
* assert_not_called() (unittest.mock.Mock 方法): Mock 类.    (line  164)
* assert_python_failure() (在 test.support.script_helper 模块中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   49)
* assert_python_ok() (在 test.support.script_helper 模块中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   36)
* assignment; statement:                 标准类型层级结构.   (line  146)
* assignment; statement <1>:             赋值语句.           (line    6)
* AST (ast 中的类):                      节点类.             (line    6)
* ast (模块):                            ast --- 抽象语法树. (line    6)
* astimezone() (datetime.datetime 方法): datetime 对象.      (line  386)
* astuple() (在 dataclasses 模块中):     模块级装饰器、类和函数.
                                                             (line  240)
* async for; in comprehensions:          列表、集合与字典的显示.
                                                             (line   13)
* ASYNC() (在 token 模块中):             token --- 与Python解析树一起使用的常量.
                                                             (line  242)
* AsyncContextManager (typing 中的类):   类 函数和修饰器.    (line  321)
* asynccontextmanager() (在 contextlib 模块中): 工具.        (line   78)
* AsyncExitStack (contextlib 中的类):    工具.               (line  416)
* AsyncGenerator (collections.abc 中的类): 容器抽象基类.     (line  235)
* AsyncGenerator (typing 中的类):        类 函数和修饰器.    (line  398)
* AsyncGeneratorType() (在 types 模块中): 标准解释器类型.    (line   37)
* asynchat (模块):                       asynchat --- 异步 socket 指令/响应 处理器.
                                                             (line    6)
* asynchronous context manager – 异步上下文管理器: 术语对照表.
                                                             (line   78)
* asynchronous generator – 异步生成器:   术语对照表.         (line   84)
* asynchronous generator iterator – 异步生成器迭代器: 术语对照表.
                                                             (line   97)
* asynchronous generator; asynchronous iterator: 标准类型层级结构.
                                                             (line  355)
* asynchronous generator; function:      标准类型层级结构.   (line  355)
* asynchronous iterable – 异步可迭代对象: 术语对照表.        (line  110)
* asynchronous iterator – 异步迭代器:    术语对照表.         (line  116)
* asyncio (模块):                        asyncio --- 异步 I/O.
                                                             (line    6)
* asyncio.subprocess.DEVNULL() (在 asyncio 模块中): 常量<7>. (line   22)
* asyncio.subprocess.PIPE() (在 asyncio 模块中): 常量<7>.    (line    6)
* asyncio.subprocess.Process (asyncio 中的类): 与子进程交互. (line   10)
* asyncio.subprocess.STDOUT() (在 asyncio 模块中): 常量<7>.  (line   17)
* AsyncIterable (collections.abc 中的类): 容器抽象基类.      (line  221)
* AsyncIterable (typing 中的类):         类 函数和修饰器.    (line  301)
* AsyncIterator (collections.abc 中的类): 容器抽象基类.      (line  228)
* AsyncIterator (typing 中的类):         类 函数和修饰器.    (line  307)
* AsyncMock (unittest.mock 中的类):      Mock 类.            (line  647)
* asyncore (模块):                       asyncore --- 异步socket处理器.
                                                             (line    6)
* AsyncResult (multiprocessing.pool 中的类): 进程池.         (line  157)
* asyncSetUp() (unittest.IsolatedAsyncioTestCase 方法): 测试用例.
                                                             (line  809)
* asyncTearDown() (unittest.IsolatedAsyncioTestCase 方法): 测试用例.
                                                             (line  818)
* async_chat (asynchat 中的类):          asynchat --- 异步 socket 指令/响应 处理器.
                                                             (line   24)
* async_chat.ac_in_buffer_size() (在 asynchat 模块中): asynchat --- 异步 socket 指令/响应 处理器.
                                                             (line   39)
* async_chat.ac_out_buffer_size() (在 asynchat 模块中): asynchat --- 异步 socket 指令/响应 处理器.
                                                             (line   43)
* as_bytes() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line   83)
* as_bytes() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line   85)
* as_completed() (在 asyncio 模块中):    简单等待.           (line   77)
* as_completed() (在 concurrent.futures 模块中): 模块函数.   (line   35)
* as_integer_ratio() (decimal.Decimal 方法): Decimal 对象.   (line  100)
* as_integer_ratio() (float 方法):       浮点类型的附加方法. (line    9)
* as_integer_ratio() (fractions.Fraction 方法): fractions --- 分数.
                                                             (line   87)
* as_integer_ratio() (int 方法):         整数类型的附加方法. (line   88)
* AS_IS() (在 formatter 模块中):         The Formatter Interface.
                                                             (line   12)
* as_posix() (pathlib.PurePath 方法):    方法和特征属性.     (line  139)
* as_string() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line   48)
* as_string() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line   47)
* as_tuple() (decimal.Decimal 方法):     Decimal 对象.       (line  113)
* as_uri() (pathlib.PurePath 方法):      方法和特征属性.     (line  149)
* AT() (在 token 模块中):                token --- 与Python解析树一起使用的常量.
                                                             (line  218)
* atan() (在 cmath 模块中):              三角函数<2>.        (line   16)
* atan() (在 math 模块中):               三角函数.           (line   14)
* atan2() (在 math 模块中):              三角函数.           (line   18)
* atanh() (在 cmath 模块中):             双曲函数<2>.        (line   16)
* atanh() (在 math 模块中):              双曲函数.           (line   16)
* ATEQUAL() (在 token 模块中):           token --- 与Python解析树一起使用的常量.
                                                             (line  222)
* atexit (weakref.finalize 属性):        weakref --- 弱引用. (line  218)
* atexit (模块):                         atexit --- 退出处理器.
                                                             (line    6)
* athrow() (agen 方法):                  异步生成器-迭代器方法.
                                                             (line   33)
* atof() (在 locale 模块中):             locale --- 国际化服务.
                                                             (line  428)
* atoi() (在 locale 模块中):             locale --- 国际化服务.
                                                             (line  433)
* atom:                                  原子.               (line    6)
* attach() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  137)
* attach_loop() (asyncio.AbstractChildWatcher 方法): 进程监视器.
                                                             (line   50)
* attach_mock() (unittest.mock.Mock 方法): Mock 类.          (line  215)
* AttlistDeclHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  173)
* attrgetter() (在 operator 模块中):     operator --- 标准运算符替代函数.
                                                             (line  203)
* attrib (xml.etree.ElementTree.Element 属性): 元素对象.     (line   39)
* attribute:                             标准类型层级结构.   (line   10)
* attribute – 属性:                      术语对照表.         (line  124)
* attribute; assignment:                 赋值语句.           (line    6)
* attribute; assignment <1>:             赋值语句.           (line   63)
* attribute; deletion:                   del 语句<2>.        (line   17)
* attribute; reference:                  属性引用.           (line    6)
* AttributeError:                        具体异常.           (line   12)
* attributes (xml.dom.Node 属性):        节点对象.           (line   23)
* AttributesImpl (xml.sax.xmlreader 中的类): xml sax xmlreader --- 用于 XML 解析器的接口.
                                                             (line   56)
* AttributesNSImpl (xml.sax.xmlreader 中的类): xml sax xmlreader --- 用于 XML 解析器的接口.
                                                             (line   64)
* attroff() (curses.window 方法):        Window 对象.        (line   45)
* attron() (curses.window 方法):         Window 对象.        (line   49)
* attrset() (curses.window 方法):        Window 对象.        (line   53)
* at_eof() (asyncio.StreamReader 方法):  StreamReader.       (line   56)
* Audio Interchange File Format:         aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line    8)
* Audio Interchange File Format <1>:     chunk --- 读取 IFF 分块数据.
                                                             (line    8)
* AUDIODEV:                              ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line   51)
* audioop (模块):                        audioop --- 处理原始音频数据.
                                                             (line    6)
* AUDIO_FILE_ENCODING_ADPCM_G721() (在 sunau 模块中): sunau --- 读写 Sun AU 文件.
                                                             (line   94)
* AUDIO_FILE_ENCODING_ADPCM_G722() (在 sunau 模块中): sunau --- 读写 Sun AU 文件.
                                                             (line   94)
* AUDIO_FILE_ENCODING_ADPCM_G723_3() (在 sunau 模块中): sunau --- 读写 Sun AU 文件.
                                                             (line   94)
* AUDIO_FILE_ENCODING_ADPCM_G723_5() (在 sunau 模块中): sunau --- 读写 Sun AU 文件.
                                                             (line   94)
* AUDIO_FILE_ENCODING_ALAW_8() (在 sunau 模块中): sunau --- 读写 Sun AU 文件.
                                                             (line   84)
* AUDIO_FILE_ENCODING_DOUBLE() (在 sunau 模块中): sunau --- 读写 Sun AU 文件.
                                                             (line   94)
* AUDIO_FILE_ENCODING_FLOAT() (在 sunau 模块中): sunau --- 读写 Sun AU 文件.
                                                             (line   94)
* AUDIO_FILE_ENCODING_LINEAR_16() (在 sunau 模块中): sunau --- 读写 Sun AU 文件.
                                                             (line   84)
* AUDIO_FILE_ENCODING_LINEAR_24() (在 sunau 模块中): sunau --- 读写 Sun AU 文件.
                                                             (line   84)
* AUDIO_FILE_ENCODING_LINEAR_32() (在 sunau 模块中): sunau --- 读写 Sun AU 文件.
                                                             (line   84)
* AUDIO_FILE_ENCODING_LINEAR_8() (在 sunau 模块中): sunau --- 读写 Sun AU 文件.
                                                             (line   84)
* AUDIO_FILE_ENCODING_MULAW_8() (在 sunau 模块中): sunau --- 读写 Sun AU 文件.
                                                             (line   84)
* AUDIO_FILE_MAGIC() (在 sunau 模块中):  sunau --- 读写 Sun AU 文件.
                                                             (line   78)
* audit events:                          调试和分析.         (line    9)
* audit() (在 sys 模块中):               sys --- 系统相关的参数和函数.
                                                             (line   64)
* auditing:                              sys --- 系统相关的参数和函数.
                                                             (line   66)
* augmented; assignment:                 增强赋值语句.       (line    6)
* auth() (ftplib.FTP_TLS 方法):          FTP_TLS 对象.       (line   12)
* auth() (smtplib.SMTP 方法):            SMTP Objects.       (line  134)
* authenticate() (imaplib.IMAP4 方法):   IMAP4 Objects.      (line   37)
* AuthenticationError:                   Process 和异常.     (line  187)
* authenticators() (netrc.netrc 方法):   netrc 对象.         (line    8)
* authkey (multiprocessing.Process 属性): Process 和异常.    (line   99)
* auto (enum 中的类):                    模块内容<2>.        (line   35)
* autorange() (timeit.Timer 方法):       Python 接口.        (line   73)
* avg() (在 audioop 模块中):             audioop --- 处理原始音频数据.
                                                             (line   43)
* avgpp() (在 audioop 模块中):           audioop --- 处理原始音频数据.
                                                             (line   47)
* avoids_symlink_attacks (shutil.rmtree 属性): 目录和文件操作.
                                                             (line  244)
* AWAIT() (在 token 模块中):             token --- 与Python解析树一起使用的常量.
                                                             (line  240)
* await; in comprehensions:              列表、集合与字典的显示.
                                                             (line   37)
* Awaitable (collections.abc 中的类):    容器抽象基类.       (line  187)
* Awaitable (typing 中的类):             类 函数和修饰器.    (line  280)
* awaitable – 可等待对象:                术语对照表.         (line  129)
* await_args (unittest.mock.AsyncMock 属性): Mock 类.        (line  862)
* await_args_list (unittest.mock.AsyncMock 属性): Mock 类.   (line  880)
* await_count (unittest.mock.AsyncMock 属性): Mock 类.       (line  846)
* b"; bytes literal:                     字符串和字节串字面值.
                                                             (line   39)
* b’; bytes literal:                     字符串和字节串字面值.
                                                             (line   39)
* b16decode() (在 base64 模块中):        base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  111)
* b16encode() (在 base64 模块中):        base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  106)
* b2a_base64() (在 binascii 模块中):     binascii --- 二进制和 ASCII 码互转.
                                                             (line   41)
* b2a_hex() (在 binascii 模块中):        binascii --- 二进制和 ASCII 码互转.
                                                             (line  111)
* b2a_hqx() (在 binascii 模块中):        binascii --- 二进制和 ASCII 码互转.
                                                             (line   85)
* b2a_qp() (在 binascii 模块中):         binascii --- 二进制和 ASCII 码互转.
                                                             (line   55)
* b2a_uu() (在 binascii 模块中):         binascii --- 二进制和 ASCII 码互转.
                                                             (line   28)
* b32decode() (在 base64 模块中):        base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line   89)
* b32encode() (在 base64 模块中):        base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line   84)
* b64decode() (在 base64 模块中):        base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line   46)
* b64encode() (在 base64 模块中):        base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line   36)
* b85decode() (在 base64 模块中):        base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  170)
* b85encode() (在 base64 模块中):        base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  160)
* Babyl (mailbox 中的类):                Babyl.              (line    6)
* BabylMessage (mailbox 中的类):         BabylMessage.       (line    6)
* back() (在 turtle 模块中):             海龟动作.           (line   23)
* backslash character:                   显式的行拼接.       (line    6)
* backslashreplace_errors() (在 codecs 模块中): 错误处理方案.
                                                             (line  126)
* backup() (sqlite3.Connection 方法):    连接对象（Connection）.
                                                             (line  365)
* backward() (在 turtle 模块中):         海龟动作.           (line   23)
* BadGzipFile:                           gzip --- 对 gzip 格式的支持.
                                                             (line   56)
* BadStatusLine:                         http client --- HTTP 协议客户端.
                                                             (line  159)
* BadZipFile:                            zipfile --- 使用ZIP存档.
                                                             (line   20)
* BadZipfile:                            zipfile --- 使用ZIP存档.
                                                             (line   26)
* Balloon (tkinter.tix 中的类):          Basic Widgets.      (line    6)
* Barrier (multiprocessing 中的类):      同步原语.           (line   11)
* Barrier (threading 中的类):            栅栏对象.           (line   31)
* Barrier() (multiprocessing.managers.SyncManager 方法): 管理器.
                                                             (line  121)
* base64 (模块):                         base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line    6)
* base64; encoding:                      base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line    8)
* BaseCGIHandler (wsgiref.handlers 中的类): wsgiref handlers -- server/gateway base classes.
                                                             (line   53)
* BaseCookie (http.cookies 中的类):      http cookies --- HTTP状态管理.
                                                             (line   38)
* BaseException:                         基类.               (line    8)
* BaseHandler (urllib.request 中的类):   urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  225)
* BaseHandler (wsgiref.handlers 中的类): wsgiref handlers -- server/gateway base classes.
                                                             (line   88)
* BaseHeader (email.headerregistry 中的类): email headerregistry 自定义标头对象.
                                                             (line   29)
* BaseHTTPRequestHandler (http.server 中的类): http server --- HTTP 服务器.
                                                             (line   42)
* BaseManager (multiprocessing.managers 中的类): 管理器.     (line   19)
* basename() (在 os.path 模块中):        os path --- 常用路径操作.
                                                             (line   54)
* BaseProtocol (asyncio 中的类):         基础协议.           (line    6)
* BaseProxy (multiprocessing.managers 中的类): 代理对象.     (line   82)
* BaseRequestHandler (socketserver 中的类): Request Handler Objects.
                                                             (line    6)
* BaseRotatingHandler (logging.handlers 中的类): BaseRotatingHandler.
                                                             (line   11)
* BaseSelector (selectors 中的类):       类<3>.              (line   51)
* BaseServer (socketserver 中的类):      Server 对象<2>.     (line    6)
* basestring (2to3 fixer):               修复器.             (line   59)
* BaseTransport (asyncio 中的类):        传输层级.           (line    6)
* base_exec_prefix() (在 sys 模块中):    sys --- 系统相关的参数和函数.
                                                             (line   90)
* base_prefix() (在 sys 模块中):         sys --- 系统相关的参数和函数.
                                                             (line  101)
* basicConfig() (在 logging 模块中):     模块级别函数.       (line  199)
* BasicContext (decimal 中的类):         上下文对象.         (line   42)
* BasicInterpolation (configparser 中的类): 值的插值.        (line    9)
* BasicTestRunner (test.support 中的类): test support --- Utilities for the Python test suite.
                                                             (line 1101)
* baudrate() (在 curses 模块中):         函数<3>.            (line   17)
* bbox() (tkinter.ttk.Treeview 方法):    ttk Treeview.       (line    8)
* BDADDR_ANY() (在 socket 模块中):       常量<8>.            (line  210)
* BDADDR_LOCAL() (在 socket 模块中):     常量<8>.            (line  210)
* Bdb (bdb 中的类):                      bdb --- Debugger framework.
                                                             (line   79)
* bdb (模块):                            bdb --- Debugger framework.
                                                             (line    6)
* BdbQuit:                               bdb --- Debugger framework.
                                                             (line   15)
* BDFL:                                  术语对照表.         (line  135)
* bdist_msi (distutils.command.bdist_msi 中的类): distutils command bdist_msi --- Build a Microsoft Installer binary package.
                                                             (line    6)
* beep() (在 curses 模块中):             函数<3>.            (line   23)
* Beep() (在 winsound 模块中):           winsound --- Sound-playing interface for Windows.
                                                             (line   12)
* BEFORE_ASYNC_WITH (opcode):            Python字节码说明.   (line  283)
* begin_fill() (在 turtle 模块中):       填充.               (line   16)
* BEGIN_FINALLY (opcode):                Python字节码说明.   (line  378)
* begin_poly() (在 turtle 模块中):       特殊海龟方法.       (line    6)
* below() (curses.panel.Panel 方法):     Panel 对象.         (line   16)
* BELOW_NORMAL_PRIORITY_CLASS() (在 subprocess 模块中): Windows 常数.
                                                             (line   52)
* benchmarking:                          函数<2>.            (line  159)
* benchmarking <1>:                      函数<2>.            (line  174)
* benchmarking <2>:                      函数<2>.            (line  414)
* Benchmarking:                          timeit --- 测量小代码片段的执行时间.
                                                             (line    8)
* betavariate() (在 random 模块中):      实值分布.           (line   27)
* bgcolor() (在 turtle 模块中):          窗口控制.           (line    6)
* bgpic() (在 turtle 模块中):            窗口控制.           (line   21)
* bias() (在 audioop 模块中):            audioop --- 处理原始音频数据.
                                                             (line   52)
* bidirectional() (在 unicodedata 模块中): unicodedata --- Unicode 数据库.
                                                             (line   45)
* bigaddrspacetest() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  675)
* BigEndianStructure (ctypes 中的类):    结构化数据类型.     (line   10)
* bigmemtest() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  659)
* bin() (內置函数):                      内置函数.           (line   90)
* Binary (msilib 中的类):                msilib --- Read and write Microsoft Installer files.
                                                             (line   89)
* Binary (xmlrpc.client 中的类):         Binary 对象.        (line    6)
* binary file – 二进制文件:              术语对照表.         (line  139)
* binary literal:                        数字字面值.         (line    6)
* binary mode:                           内置函数.           (line 1017)
* binary semaphores:                     _thread --- 底层多线程 API.
                                                             (line    6)
* binary; arithmetic; operation:         二元算术运算符.     (line    6)
* binary; bitwise; operation:            二元位运算.         (line    6)
* binary; literals:                      数字类型 --- int float complex.
                                                             (line   14)
* binaryfunc (C 类型):                   Slot Type typedefs. (line  111)
* BinaryIO (typing 中的类):              类 函数和修饰器.    (line  442)
* BINARY_ADD (opcode):                   Python字节码说明.   (line  149)
* BINARY_AND (opcode):                   Python字节码说明.   (line  169)
* BINARY_FLOOR_DIVIDE (opcode):          Python字节码说明.   (line  137)
* BINARY_LSHIFT (opcode):                Python字节码说明.   (line  161)
* BINARY_MATRIX_MULTIPLY (opcode):       Python字节码说明.   (line  131)
* BINARY_MODULO (opcode):                Python字节码说明.   (line  145)
* BINARY_MULTIPLY (opcode):              Python字节码说明.   (line  127)
* BINARY_OR (opcode):                    Python字节码说明.   (line  177)
* BINARY_POWER (opcode):                 Python字节码说明.   (line  123)
* BINARY_RSHIFT (opcode):                Python字节码说明.   (line  165)
* BINARY_SUBSCR (opcode):                Python字节码说明.   (line  157)
* BINARY_SUBTRACT (opcode):              Python字节码说明.   (line  153)
* BINARY_TRUE_DIVIDE (opcode):           Python字节码说明.   (line  141)
* BINARY_XOR (opcode):                   Python字节码说明.   (line  173)
* binascii (模块):                       binascii --- 二进制和 ASCII 码互转.
                                                             (line    6)
* bind (widgets):                        Bindings and Events.
                                                             (line    6)
* bind() (asyncore.dispatcher 方法):     asyncore --- 异步socket处理器.
                                                             (line  180)
* bind() (inspect.Signature 方法):       Introspecting callables with the Signature object.
                                                             (line   95)
* bind() (socket.socket 方法):           套接字对象.         (line   26)
* binding; name:                         名称的绑定.         (line    6)
* binding; name <1>:                     赋值语句.           (line    6)
* bindtextdomain() (在 gettext 模块中):  GNU gettext API.    (line   12)
* bindtextdomain() (在 locale 模块中):   Access to message catalogs.
                                                             (line   14)
* bind_partial() (inspect.Signature 方法): Introspecting callables with the Signature object.
                                                             (line  102)
* bind_port() (在 test.support 模块中):  test support --- Utilities for the Python test suite.
                                                             (line  803)
* bind_textdomain_codeset() (在 gettext 模块中): GNU gettext API.
                                                             (line   23)
* bind_unix_socket() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  820)
* binhex (模块):                         binhex --- 对binhex4文件进行编码和解码.
                                                             (line    6)
* binhex() (在 binhex 模块中):           binhex --- 对binhex4文件进行编码和解码.
                                                             (line   15)
* bisect (模块):                         bisect --- 数组二分查找算法.
                                                             (line    6)
* bisect() (在 bisect 模块中):           bisect --- 数组二分查找算法.
                                                             (line   28)
* bisect_left() (在 bisect 模块中):      bisect --- 数组二分查找算法.
                                                             (line   17)
* bisect_right() (在 bisect 模块中):     bisect --- 数组二分查找算法.
                                                             (line   28)
* bitmap() (msilib.Dialog 方法):         GUI classes.        (line   60)
* bitwise; and:                          二元位运算.         (line   12)
* bitwise; operations:                   整数类型的按位运算. (line    6)
* bitwise; or:                           二元位运算.         (line   16)
* bitwise; xor:                          二元位运算.         (line   14)
* bit_length() (int 方法):               整数类型的附加方法. (line    9)
* bk() (在 turtle 模块中):               海龟动作.           (line   23)
* bkgd() (curses.window 方法):           Window 对象.        (line   57)
* bkgdset() (curses.window 方法):        Window 对象.        (line   67)
* blake2b() (在 hashlib 模块中):         创建哈希对象.       (line    8)
* blake2b, blake2s:                      BLAKE2.             (line    6)
* blake2b.MAX_DIGEST_SIZE() (在 hashlib 模块中): 常量<5>.    (line   24)
* blake2b.MAX_KEY_SIZE() (在 hashlib 模块中): 常量<5>.       (line   18)
* blake2b.PERSON_SIZE() (在 hashlib 模块中): 常量<5>.        (line   12)
* blake2b.SALT_SIZE() (在 hashlib 模块中): 常量<5>.          (line    6)
* blake2s() (在 hashlib 模块中):         创建哈希对象.       (line   13)
* blake2s.MAX_DIGEST_SIZE() (在 hashlib 模块中): 常量<5>.    (line   26)
* blake2s.MAX_KEY_SIZE() (在 hashlib 模块中): 常量<5>.       (line   20)
* blake2s.PERSON_SIZE() (在 hashlib 模块中): 常量<5>.        (line   14)
* blake2s.SALT_SIZE() (在 hashlib 模块中): 常量<5>.          (line    8)
* blank line:                            空白行.             (line    6)
* block:                                 程序的结构.         (line    6)
* blocked_domains() (http.cookiejar.DefaultCookiePolicy 方法): DefaultCookiePolicy 对象.
                                                             (line   52)
* BlockingIOError:                       OS 异常.            (line    8)
* BlockingIOError <1>:                   高阶模块接口.       (line   34)
* blocksize (http.client.HTTPConnection 属性): HTTPConnection 对象.
                                                             (line   96)
* block_size (hmac.HMAC 属性):           hmac --- 基于密钥的消息验证.
                                                             (line   81)
* BNF:                                   标注.               (line    6)
* BNF <1>:                               表达式.             (line    6)
* body() (nntplib.NNTP 方法):            方法<3>.            (line  271)
* body_encode() (email.charset.Charset 方法): email charset 表示字符集.
                                                             (line  120)
* body_encoding (email.charset.Charset 属性): email charset 表示字符集.
                                                             (line   60)
* body_line_iterator() (在 email.iterators 模块中): email iterators 迭代器.
                                                             (line   13)
* BOM() (在 codecs 模块中):              codecs --- 编解码器注册和相关基类.
                                                             (line  200)
* BOM_BE() (在 codecs 模块中):           codecs --- 编解码器注册和相关基类.
                                                             (line  200)
* BOM_LE() (在 codecs 模块中):           codecs --- 编解码器注册和相关基类.
                                                             (line  200)
* BOM_UTF16() (在 codecs 模块中):        codecs --- 编解码器注册和相关基类.
                                                             (line  200)
* BOM_UTF16_BE() (在 codecs 模块中):     codecs --- 编解码器注册和相关基类.
                                                             (line  200)
* BOM_UTF16_LE() (在 codecs 模块中):     codecs --- 编解码器注册和相关基类.
                                                             (line  200)
* BOM_UTF32() (在 codecs 模块中):        codecs --- 编解码器注册和相关基类.
                                                             (line  200)
* BOM_UTF32_BE() (在 codecs 模块中):     codecs --- 编解码器注册和相关基类.
                                                             (line  200)
* BOM_UTF32_LE() (在 codecs 模块中):     codecs --- 编解码器注册和相关基类.
                                                             (line  200)
* BOM_UTF8() (在 codecs 模块中):         codecs --- 编解码器注册和相关基类.
                                                             (line  200)
* bool (內置类):                         内置函数.           (line  110)
* Boolean; operation:                    布尔运算.           (line    6)
* Boolean; operations:                   逻辑值检测.         (line    6)
* Boolean; operations <1>:               布尔运算 --- and or not.
                                                             (line    6)
* Boolean; type:                         内置函数.           (line  119)
* Boolean; values:                       布尔值.             (line   12)
* BOOLEAN_STATES (configparser.ConfigParser 属性): 定制解析器行为.
                                                             (line  213)
* bootstrap() (在 ensurepip 模块中):     Module API.         (line   13)
* border() (curses.window 方法):         Window 对象.        (line   74)
* bottom() (curses.panel.Panel 方法):    Panel 对象.         (line   20)
* bottom_panel() (在 curses.panel 模块中): 函数<4>.          (line    8)
* BoundArguments (inspect 中的类):       Introspecting callables with the Signature object.
                                                             (line  274)
* BoundaryError:                         email errors 异常和缺陷类.
                                                             (line   32)
* BoundedSemaphore (asyncio 中的类):     BoundedSemaphore.   (line    6)
* BoundedSemaphore (multiprocessing 中的类): 同步原语.       (line   17)
* BoundedSemaphore (threading 中的类):   信号量对象.         (line   60)
* BoundedSemaphore() (multiprocessing.managers.SyncManager 方法): 管理器.
                                                             (line  128)
* box() (curses.window 方法):            Window 对象.        (line  110)
* bpformat() (bdb.Breakpoint 方法):      bdb --- Debugger framework.
                                                             (line   55)
* bpprint() (bdb.Breakpoint 方法):       bdb --- Debugger framework.
                                                             (line   74)
* break (pdb command):                   调试器命令.         (line   56)
* Breakpoint (bdb 中的类):               bdb --- Debugger framework.
                                                             (line   22)
* breakpoint() (內置函数):               内置函数.           (line  121)
* breakpointhook() (在 sys 模块中):      sys --- 系统相关的参数和函数.
                                                             (line  153)
* breakpoints:                           帮助菜单（命令行和编辑器）.
                                                             (line   25)
* break_anywhere() (bdb.Bdb 方法):       bdb --- Debugger framework.
                                                             (line  203)
* break_here() (bdb.Bdb 方法):           bdb --- Debugger framework.
                                                             (line  196)
* break_long_words (textwrap.TextWrapper 属性): textwrap --- 文本自动换行与填充.
                                                             (line  209)
* break_on_hyphens (textwrap.TextWrapper 属性): textwrap --- 文本自动换行与填充.
                                                             (line  217)
* broadcast_address (ipaddress.IPv4Network 属性): Network objects.
                                                             (line   91)
* broadcast_address (ipaddress.IPv6Network 属性): Network objects.
                                                             (line  311)
* broken (threading.Barrier 属性):       栅栏对象.           (line   87)
* BrokenBarrierError:                    栅栏对象.           (line   91)
* BrokenExecutor:                        Exception类.        (line   14)
* BrokenPipeError:                       OS 异常.            (line   34)
* BrokenProcessPool:                     Exception类.        (line   34)
* BrokenThreadPool:                      Exception类.        (line   27)
* BROWSER:                               webbrowser --- 方便的Web浏览器控制器.
                                                             (line   17)
* BROWSER <1>:                           webbrowser --- 方便的Web浏览器控制器.
                                                             (line   79)
* BsdDbShelf (shelve 中的类):            限制.               (line   42)
* buf (multiprocessing.shared_memory.SharedMemory 属性): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   65)
* buffer (2to3 fixer):                   修复器.             (line   63)
* buffer (io.TextIOBase 属性):           文本 I/O<2>.        (line   28)
* buffer (unittest.TestResult 属性):     Loading and running tests.
                                                             (line  276)
* buffer interface; (see buffer protocol): 迭代器协议.       (line   43)
* buffer object; (see buffer protocol):  迭代器协议.         (line   42)
* buffer protocol:                       迭代器协议.         (line   43)
* buffer protocol; binary sequence types: printf 风格的字符串格式化.
                                                             (line  161)
* buffer protocol; str (built-in class): 文本序列类型 --- str.
                                                             (line   51)
* buffer size, I/O:                      内置函数.           (line 1017)
* BufferedIOBase (io 中的类):            I/O 基类.           (line  187)
* BufferedProtocol (asyncio 中的类):     基础协议.           (line   14)
* BufferedRandom (io 中的类):            缓冲流.             (line  116)
* BufferedReader (io 中的类):            缓冲流.             (line   51)
* BufferedRWPair (io 中的类):            缓冲流.             (line  129)
* BufferedWriter (io 中的类):            缓冲流.             (line   83)
* BufferError:                           基类.               (line   42)
* BufferingHandler (logging.handlers 中的类): MemoryHandler. (line   15)
* BufferTooShort:                        Process 和异常.     (line  179)
* buffer_info() (array.array 方法):      array --- 高效的数值数组.
                                                             (line  108)
* buffer_size (xml.parsers.expat.xmlparser 属性): XMLParser对象<2>.
                                                             (line   70)
* buffer_text (xml.parsers.expat.xmlparser 属性): XMLParser对象<2>.
                                                             (line   76)
* buffer_updated() (asyncio.BufferedProtocol 方法): 缓冲流协议.
                                                             (line   28)
* buffer_used (xml.parsers.expat.xmlparser 属性): XMLParser对象<2>.
                                                             (line   83)
* bufsize() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line  210)
* BUILD_CONST_KEY_MAP (opcode):          Python字节码说明.   (line  513)
* BUILD_LIST (opcode):                   Python字节码说明.   (line  497)
* BUILD_LIST_UNPACK (opcode):            Python字节码说明.   (line  540)
* BUILD_MAP (opcode):                    Python字节码说明.   (line  505)
* BUILD_MAP_UNPACK (opcode):             Python字节码说明.   (line  554)
* BUILD_MAP_UNPACK_WITH_CALL (opcode):   Python字节码说明.   (line  561)
* build_opener() (在 urllib.request 模块中): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  110)
* build_py (distutils.command.build_py 中的类): distutils command build_py --- Build the py/ pyc files of a package.
                                                             (line    6)
* build_py_2to3 (distutils.command.build_py 中的类): distutils command build_py --- Build the py/ pyc files of a package.
                                                             (line    8)
* BUILD_SET (opcode):                    Python字节码说明.   (line  501)
* BUILD_SET_UNPACK (opcode):             Python字节码说明.   (line  547)
* BUILD_SLICE (opcode):                  Python字节码说明.   (line  775)
* BUILD_STRING (opcode):                 Python字节码说明.   (line  520)
* BUILD_TUPLE (opcode):                  Python字节码说明.   (line  493)
* BUILD_TUPLE_UNPACK (opcode):           Python字节码说明.   (line  526)
* BUILD_TUPLE_UNPACK_WITH_CALL (opcode): Python字节码说明.   (line  533)
* built-in function; call:               调用.               (line  105)
* built-in method; call:                 调用.               (line  105)
* built-in; method:                      标准类型层级结构.   (line  379)
* built-in; types:                       内置类型.           (line    8)
* BuiltinFunctionType() (在 types 模块中): 标准解释器类型.   (line   71)
* BuiltinImporter (importlib.machinery 中的类): importlib machinery -- Importers and path hooks.
                                                             (line   64)
* BuiltinMethodType() (在 types 模块中): 标准解释器类型.     (line   71)
* builtins (模块):                       builtins --- 内建对象.
                                                             (line    6)
* builtin_module_names() (在 sys 模块中): sys --- 系统相关的参数和函数.
                                                             (line  117)
* ButtonBox (tkinter.tix 中的类):        Basic Widgets.      (line   13)
* bye() (在 turtle 模块中):              Screen 专有方法 而非继承自 TurtleScreen.
                                                             (line    6)
* byref() (在 ctypes 模块中):            工具函数.           (line   17)
* byte:                                  标准类型层级结构.   (line  138)
* bytearray:                             标准类型层级结构.   (line  159)
* bytearray (內置类):                    bytearray 对象.     (line    8)
* bytearray; formatting:                 printf 风格的字节串格式化.
                                                             (line    6)
* bytearray; interpolation:              printf 风格的字节串格式化.
                                                             (line    6)
* bytearray; methods:                    bytes 和 bytearray 操作.
                                                             (line    6)
* bytecode:                              标准类型层级结构.   (line  490)
* Bytecode (dis 中的类):                 字节码分析.         (line   11)
* bytecode – 字节码:                     术语对照表.         (line  163)
* Bytecode.codeobj() (在 dis 模块中):    字节码分析.         (line   33)
* Bytecode.first_line() (在 dis 模块中): 字节码分析.         (line   37)
* BYTECODE_SUFFIXES() (在 importlib.machinery 模块中): importlib machinery -- Importers and path hooks.
                                                             (line   38)
* byteorder() (在 sys 模块中):           sys --- 系统相关的参数和函数.
                                                             (line  112)
* bytes:                                 标准类型层级结构.   (line  138)
* bytes (uuid.UUID 属性):                uuid --- UUID objects according to RFC 4122.
                                                             (line   84)
* bytes (內置类):                        bytes 对象.         (line   10)
* bytes literal:                         字面值.             (line    8)
* bytes-like object – 字节类对象:        术语对照表.         (line  149)
* bytes; formatting:                     printf 风格的字节串格式化.
                                                             (line    6)
* bytes; interpolation:                  printf 风格的字节串格式化.
                                                             (line    6)
* bytes; methods:                        bytes 和 bytearray 操作.
                                                             (line    6)
* bytes; str (built-in class):           文本序列类型 --- str.
                                                             (line   51)
* BytesFeedParser (email.parser 中的类): FeedParser API.     (line   24)
* BytesGenerator (email.generator 中的类): email generator 生成 MIME 文档.
                                                             (line   33)
* BytesHeaderParser (email.parser 中的类): Parser API.       (line   59)
* BytesIO (io 中的类):                   缓冲流.             (line    8)
* BytesParser (email.parser 中的类):     Parser API.         (line   14)
* ByteString (collections.abc 中的类):   容器抽象基类.       (line  155)
* ByteString (typing 中的类):            类 函数和修饰器.    (line  223)
* byteswap() (array.array 方法):         array --- 高效的数值数组.
                                                             (line  121)
* byteswap() (在 audioop 模块中):        audioop --- 处理原始音频数据.
                                                             (line   57)
* BytesWarning:                          警告.               (line   49)
* bytes_le (uuid.UUID 属性):             uuid --- UUID objects according to RFC 4122.
                                                             (line   89)
* byte_compile() (在 distutils.util 模块中): distutils util --- Miscellaneous other utility functions.
                                                             (line  127)
* bz2 (模块):                            bz2 --- 对 bzip2 压缩算法的支持.
                                                             (line    6)
* BZ2Compressor (bz2 中的类):            增量压缩和解压.     (line    6)
* BZ2Decompressor (bz2 中的类):          增量压缩和解压.     (line   28)
* BZ2File (bz2 中的类):                  文件压缩和解压.     (line   37)
* C:                                     字符串和字节串字面值.
                                                             (line   62)
* C-contiguous:                          形状，步幅，子偏移量.
                                                             (line   25)
* C-contiguous <1>:                      术语对照表.         (line  222)
* C14NWriterTarget (xml.etree.ElementTree 中的类): TreeBuilder 对象.
                                                             (line   82)
* C; language:                           标准类型层级结构.   (line    6)
* C; language <1>:                       标准类型层级结构.   (line   79)
* C; language <2>:                       标准类型层级结构.   (line  369)
* C; language <3>:                       比较运算.           (line    6)
* C; language <4>:                       数字类型 --- int float complex.
                                                             (line    6)
* C; language <5>:                       数字类型 --- int float complex.
                                                             (line   92)
* C; structures:                         struct --- 将字节串解读为打包的二进制数据.
                                                             (line    8)
* CAB (msilib 中的类):                   CAB Objects.        (line    6)
* cached (importlib.machinery.ModuleSpec 属性): importlib machinery -- Importers and path hooks.
                                                             (line  396)
* cached_property() (在 functools 模块中): functools --- 高阶函数和可调用对象上的操作.
                                                             (line   15)
* CacheFTPHandler (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  357)
* cache_from_source() (在 imp 模块中):   imp --- Access the import internals.
                                                             (line  196)
* cache_from_source() (在 importlib.util 模块中): importlib util -- Utility code for importers.
                                                             (line   21)
* calcobjsize() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  530)
* calcsize() (在 struct 模块中):         函数和异常.         (line   48)
* calcvobjsize() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  535)
* Calendar (calendar 中的类):            calendar --- 日历相关函数.
                                                             (line   21)
* calendar (模块):                       calendar --- 日历相关函数.
                                                             (line    6)
* calendar() (在 calendar 模块中):       calendar --- 日历相关函数.
                                                             (line  305)
* call:                                  切片.               (line   30)
* call() (在 subprocess 模块中):         较旧的高阶 API.     (line    9)
* call() (在 unittest.mock 模块中):      call.               (line    6)
* call; instance:                        模拟可调用对象.     (line    8)
* Callable (collections.abc 中的类):     容器抽象基类.       (line  116)
* callable() (內置函数):                 内置函数.           (line  176)
* Callable() (在 typing 模块中):         类 函数和修饰器.    (line  793)
* CallableProxyType() (在 weakref 模块中): weakref --- 弱引用.
                                                             (line  239)
* callback (optparse.Option 属性):       Option attributes.  (line   60)
* callback – 回调:                       术语对照表.         (line  174)
* callback() (contextlib.ExitStack 方法): 工具.              (line  377)
* callbacks() (在 gc 模块中):            gc --- 垃圾回收器接口.
                                                             (line  189)
* callback_args (optparse.Option 属性):  Option attributes.  (line   66)
* callback_kwargs (optparse.Option 属性): Option attributes. (line   66)
* called (unittest.mock.Mock 属性):      Mock 类.            (line  276)
* CalledProcessError:                    使用 subprocess 模块.
                                                             (line  170)
* calloc():                              概述<16>.           (line   23)
* call_args (unittest.mock.Mock 属性):   Mock 类.            (line  395)
* call_args_list (unittest.mock.Mock 属性): Mock 类.         (line  439)
* call_at() (asyncio.loop 方法):         调度延迟回调.       (line   34)
* call_count (unittest.mock.Mock 属性):  Mock 类.            (line  288)
* call_exception_handler() (asyncio.loop 方法): 错误处理API. (line   34)
* CALL_FINALLY (opcode):                 Python字节码说明.   (line  641)
* CALL_FUNCTION (opcode):                Python字节码说明.   (line  702)
* CALL_FUNCTION_EX (opcode):             Python字节码说明.   (line  723)
* CALL_FUNCTION_KW (opcode):             Python字节码说明.   (line  711)
* call_later() (asyncio.loop 方法):      调度延迟回调.       (line    9)
* call_list() (unittest.mock.call 方法): call.               (line   20)
* CALL_METHOD (opcode):                  Python字节码说明.   (line  747)
* call_soon() (asyncio.loop 方法):       调度回调.           (line    6)
* call_soon_threadsafe() (asyncio.loop 方法): 调度回调.      (line   21)
* call_tracing() (在 sys 模块中):        sys --- 系统相关的参数和函数.
                                                             (line  123)
* cancel() (asyncio.Future 方法):        Future 对象<2>.     (line   99)
* cancel() (asyncio.Handle 方法):        回调处理.           (line   11)
* cancel() (asyncio.Task 方法):          Task 对象.          (line   46)
* cancel() (concurrent.futures.Future 方法): Future 对象.    (line   14)
* cancel() (sched.scheduler 方法):       调度器对象.         (line   36)
* cancel() (threading.Timer 方法):       定时器对象.         (line   31)
* cancelled() (asyncio.Future 方法):     Future 对象<2>.     (line   60)
* cancelled() (asyncio.Handle 方法):     回调处理.           (line   16)
* cancelled() (asyncio.Task 方法):       Task 对象.          (line   94)
* cancelled() (concurrent.futures.Future 方法): Future 对象. (line   20)
* CancelledError:                        Exception类.        (line    6)
* CancelledError <1>:                    异常<9>.            (line   16)
* cancel_dump_traceback_later() (在 faulthandler 模块中): Dumping the tracebacks after a timeout.
                                                             (line   29)
* cancel_join_thread() (multiprocessing.Queue 方法): 管道和队列.
                                                             (line  156)
* CannotSendHeader:                      http client --- HTTP 协议客户端.
                                                             (line  151)
* CannotSendRequest:                     http client --- HTTP 协议客户端.
                                                             (line  147)
* canonic() (bdb.Bdb 方法):              bdb --- Debugger framework.
                                                             (line   99)
* canonical() (decimal.Context 方法):    上下文对象.         (line  204)
* canonical() (decimal.Decimal 方法):    Decimal 对象.       (line  118)
* canonicalize() (在 xml.etree.ElementTree 模块中): 函数<6>. (line    6)
* CAN_BCM() (在 socket 模块中):          常量<8>.            (line  102)
* can_change_color() (在 curses 模块中): 函数<3>.            (line   27)
* can_fetch() (urllib.robotparser.RobotFileParser 方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   32)
* CAN_ISOTP() (在 socket 模块中):        常量<8>.            (line  128)
* CAN_RAW_FD_FRAMES() (在 socket 模块中): 常量<8>.           (line  116)
* can_symlink() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  545)
* can_write_eof() (asyncio.StreamWriter 方法): StreamWriter. (line   43)
* can_write_eof() (asyncio.WriteTransport 方法): 只写传输.   (line   12)
* can_xattr() (在 test.support 模块中):  test support --- Utilities for the Python test suite.
                                                             (line  549)
* capa() (poplib.POP3 方法):             POP3 对象.          (line   22)
* capitalize() (bytearray 方法):         bytes 和 bytearray 操作.
                                                             (line  335)
* capitalize() (bytes 方法):             bytes 和 bytearray 操作.
                                                             (line  335)
* capitalize() (str 方法):               字符串的方法<2>.    (line   18)
* captured_stderr() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  401)
* captured_stdin() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  401)
* captured_stdout() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  401)
* captureWarnings() (在 logging 模块中): 与警告模块集成.     (line    9)
* capwords() (在 string 模块中):         辅助函数.           (line    6)
* casefold() (str 方法):                 字符串的方法<2>.    (line   26)
* cast() (memoryview 方法):              内存视图.           (line  246)
* cast() (在 ctypes 模块中):             工具函数.           (line   29)
* cast() (在 typing 模块中):             类 函数和修饰器.    (line  573)
* cat() (在 nis 模块中):                 nis --- Sun 的 NIS 黄页 接口.
                                                             (line   26)
* catch_threading_exception() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  825)
* catch_unraisable_exception() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  860)
* catch_warnings (warnings 中的类):      Available Context Managers.
                                                             (line    6)
* category() (在 unicodedata 模块中):    unicodedata --- Unicode 数据库.
                                                             (line   41)
* cbreak() (在 curses 模块中):           函数<3>.            (line   31)
* CC:                                    新增，改进和弃用的模块<4>.
                                                             (line   58)
* ccc() (ftplib.FTP_TLS 方法):           FTP_TLS 对象.       (line   21)
* CCompiler (distutils.ccompiler 中的类): distutils ccompiler --- CCompiler基类.
                                                             (line   66)
* cdf() (statistics.NormalDist 方法):    NormalDist 对象.    (line   67)
* CDLL (ctypes 中的类):                  加载动态链接库.     (line    9)
* ceil() (in module math):               数字类型 --- int float complex.
                                                             (line   92)
* ceil() (在 math 模块中):               数论与表示函数.     (line    6)
* CellType() (在 types 模块中):          标准解释器类型.     (line   61)
* center() (bytearray 方法):             bytes 和 bytearray 操作.
                                                             (line  199)
* center() (bytes 方法):                 bytes 和 bytearray 操作.
                                                             (line  199)
* center() (str 方法):                   字符串的方法<2>.    (line   40)
* CertificateError:                      异常<12>.           (line   84)
* certificates:                          SSL 上下文.         (line  586)
* CERT_NONE() (在 ssl 模块中):           常量<9>.            (line   11)
* CERT_OPTIONAL() (在 ssl 模块中):       常量<9>.            (line   24)
* CERT_REQUIRED() (在 ssl 模块中):       常量<9>.            (line   39)
* cert_store_stats() (ssl.SSLContext 方法): SSL 上下文.      (line   63)
* cert_time_to_seconds() (在 ssl 模块中): 证书处理.          (line   42)
* CFLAGS:                                新增，改进和弃用的模块<4>.
                                                             (line   58)
* CFLAGS <1>:                            Tweaking compiler/linker flags.
                                                             (line   66)
* CFLAGS <2>:                            Tweaking compiler/linker flags.
                                                             (line   67)
* CFUNCTYPE() (在 ctypes 模块中):        函数原型.           (line   12)
* cgi (模块):                            cgi --- 通用网关接口支持.
                                                             (line    6)
* CGI; debugging:                        Debugging CGI scripts.
                                                             (line    6)
* CGI; exceptions:                       cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line    8)
* CGI; protocol:                         cgi --- 通用网关接口支持.
                                                             (line    8)
* CGI; security:                         Caring about security.
                                                             (line    6)
* CGI; tracebacks:                       cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line    8)
* CGIHandler (wsgiref.handlers 中的类):  wsgiref handlers -- server/gateway base classes.
                                                             (line   11)
* CGIHTTPRequestHandler (http.server 中的类): http server --- HTTP 服务器.
                                                             (line  434)
* cgitb (模块):                          cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line    6)
* CGIXMLRPCRequestHandler (xmlrpc.server 中的类): xmlrpc server --- 基本 XML-RPC 服务器.
                                                             (line   45)
* cgi_directories (http.server.CGIHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line  460)
* chain() (在 itertools 模块中):         Itertool函数.       (line   79)
* chaining; comparisons:                 比较运算.           (line   16)
* chaining; comparisons <1>:             比较运算<2>.        (line    6)
* ChainMap (collections 中的类):         ChainMap 对象.      (line   14)
* ChainMap (typing 中的类):              类 函数和修饰器.    (line  361)
* change_cwd() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  435)
* change_root() (在 distutils.util 模块中): distutils util --- Miscellaneous other utility functions.
                                                             (line   64)
* channels() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line  130)
* CHANNEL_BINDING_TYPES() (在 ssl 模块中): 常量<9>.          (line  392)
* channel_class (smtpd.SMTPServer 属性): SMTPServer 对象.    (line   79)
* character:                             标准类型层级结构.   (line  117)
* character <1>:                         抽取.               (line   28)
* character <2>:                         unicodedata --- Unicode 数据库.
                                                             (line    6)
* CharacterDataHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  200)
* characters() (xml.sax.handler.ContentHandler 方法): ContentHandler 对象.
                                                             (line  108)
* characters_written (BlockingIOError 属性): OS 异常.        (line   17)
* Charset (email.charset 中的类):        email charset 表示字符集.
                                                             (line   22)
* charset() (gettext.NullTranslations 方法): NullTranslations 类.
                                                             (line   71)
* CHAR_MAX() (在 locale 模块中):         locale --- 国际化服务.
                                                             (line  484)
* chdir() (在 os 模块中):                文件和目录.         (line   97)
* check (lzma.LZMADecompressor 属性):    在内存中压缩和解压缩数据.
                                                             (line  127)
* check() (imaplib.IMAP4 方法):          IMAP4 Objects.      (line   58)
* check() (在 tabnanny 模块中):          tabnanny --- 模糊缩进检测.
                                                             (line   16)
* checkbox() (msilib.Dialog 方法):       GUI classes.        (line   78)
* checkcache() (在 linecache 模块中):    linecache --- 随机读写文本行.
                                                             (line   36)
* CHECKED_HASH (py_compile.PycInvalidationMode 属性): py_compile --- 编译 Python 源文件.
                                                             (line   88)
* checkfuncname() (在 bdb 模块中):       bdb --- Debugger framework.
                                                             (line  384)
* CheckList (tkinter.tix 中的类):        Hierarchical ListBox.
                                                             (line   13)
* checksizeof() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  540)
* checksum; Cyclic Redundancy Check:     zlib --- 与 gzip 兼容的压缩.
                                                             (line   89)
* check_call() (在 subprocess 模块中):   较旧的高阶 API.     (line   32)
* check_environ() (在 distutils.util 模块中): distutils util --- Miscellaneous other utility functions.
                                                             (line   71)
* check_free_after_iterating() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  955)
* check_hostname (ssl.SSLContext 属性):  SSL 上下文.         (line  426)
* check_impl_detail() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  287)
* check_no_resource_warning() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  364)
* check_output() (doctest.OutputChecker 方法): OutputChecker 对象.
                                                             (line   17)
* check_output() (在 subprocess 模块中): 较旧的高阶 API.     (line   56)
* check_returncode() (subprocess.CompletedProcess 方法): 使用 subprocess 模块.
                                                             (line  108)
* check_syntax_error() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  685)
* check_syntax_warning() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  696)
* check_unused_args() (string.Formatter 方法): 自定义字符串格式化.
                                                             (line   73)
* check_warnings() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  296)
* check__all__() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  967)
* chflags() (在 os 模块中):              文件和目录.         (line  114)
* chgat() (curses.window 方法):          Window 对象.        (line  115)
* childNodes (xml.dom.Node 属性):        节点对象.           (line   41)
* ChildProcessError:                     OS 异常.            (line   22)
* children (pyclbr.Class 属性):          类对象<2>.          (line   31)
* children (pyclbr.Function 属性):       函数对象.           (line   30)
* chmod() (pathlib.Path 方法):           方法<2>.            (line   44)
* chmod() (在 os 模块中):                文件和目录.         (line  154)
* choice() (在 random 模块中):           序列用函数.         (line    6)
* choice() (在 secrets 模块中):          随机数.             (line   14)
* choices (optparse.Option 属性):        Option attributes.  (line   55)
* choices() (在 random 模块中):          序列用函数.         (line   11)
* chown() (在 os 模块中):                文件和目录.         (line  213)
* chown() (在 shutil 模块中):            目录和文件操作.     (line  296)
* chr() (內置函数):                      内置函数.           (line  187)
* chroot() (在 os 模块中):               文件和目录.         (line  235)
* Chunk (chunk 中的类):                  chunk --- 读取 IFF 分块数据.
                                                             (line   45)
* chunk (模块):                          chunk --- 读取 IFF 分块数据.
                                                             (line    6)
* cipher() (ssl.SSLSocket 方法):         SSL 套接字.         (line  182)
* cipher; DES:                           crypt --- Function to check Unix passwords.
                                                             (line    8)
* circle() (在 turtle 模块中):           海龟动作.           (line  169)
* CIRCUMFLEX() (在 token 模块中):        token --- 与Python解析树一起使用的常量.
                                                             (line  150)
* CIRCUMFLEXEQUAL() (在 token 模块中):   token --- 与Python解析树一起使用的常量.
                                                             (line  194)
* Clamped (decimal 中的类):              信号.               (line   17)
* Class (symtable 中的类):               Examining Symbol Tables.
                                                             (line   93)
* class – 类:                            术语对照表.         (line  178)
* Class browser:                         文件菜单 （命令行和编辑器）.
                                                             (line   22)
* class instance; attribute:             标准类型层级结构.   (line  454)
* class instance; attribute; assignment: 标准类型层级结构.   (line  464)
* class instance; call:                  调用.               (line  114)
* class object; call:                    标准类型层级结构.   (line  435)
* class object; call <1>:                标准类型层级结构.   (line  443)
* class object; call <2>:                调用.               (line  110)
* class variable – 类变量:               术语对照表.         (line  183)
* class; attribute:                      标准类型层级结构.   (line  435)
* class; attribute; assignment:          标准类型层级结构.   (line  441)
* class; body:                           执行类主体.         (line    6)
* class; constructor:                    基本定制.           (line   33)
* class; definition:                     return 语句.        (line    6)
* class; definition <1>:                 类定义.             (line    6)
* class; instance:                       标准类型层级结构.   (line  454)
* class; name:                           类定义.             (line    6)
* classmethod() (內置函数):              内置函数.           (line  196)
* ClassMethodDescriptorType() (在 types 模块中): 标准解释器类型.
                                                             (line   97)
* ClassVar() (在 typing 模块中):         类 函数和修饰器.    (line  828)
* clause:                                复合语句.           (line   15)
* CLD_CONTINUED() (在 os 模块中):        进程管理.           (line  645)
* CLD_DUMPED() (在 os 模块中):           进程管理.           (line  645)
* CLD_EXITED() (在 os 模块中):           进程管理.           (line  645)
* CLD_TRAPPED() (在 os 模块中):          进程管理.           (line  645)
* clean() (mailbox.Maildir 方法):        Maildir.            (line   69)
* cleandoc() (在 inspect 模块中):        Retrieving source code.
                                                             (line   65)
* CleanImport (test.support 中的类):     test support --- Utilities for the Python test suite.
                                                             (line 1059)
* cleanup functions:                     过程控制.           (line   26)
* clear (pdb command):                   调试器命令.         (line   75)
* Clear Breakpoint:                      帮助菜单（命令行和编辑器）.
                                                             (line   26)
* clear() (asyncio.Event 方法):          Event.              (line   56)
* clear() (collections.deque 方法):      deque 对象.         (line   35)
* clear() (curses.window 方法):          Window 对象.        (line  128)
* clear() (dict 方法):                   映射类型 --- dict.  (line  124)
* clear() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  563)
* clear() (frame 方法):                  标准类型层级结构.   (line  559)
* clear() (frozenset 方法):              集合类型 --- set frozenset.
                                                             (line  193)
* clear() (http.cookiejar.CookieJar 方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   77)
* clear() (mailbox.Mailbox 方法):        Mailbox 对象.       (line  166)
* clear() (sequence method):             可变序列类型.       (line   14)
* clear() (threading.Event 方法):        事件对象.           (line   31)
* clear() (xml.etree.ElementTree.Element 方法): 元素对象.    (line   48)
* clear() (在 turtle 模块中):            窗口控制.           (line   36)
* clearcache() (在 linecache 模块中):    linecache --- 随机读写文本行.
                                                             (line   31)
* ClearData() (msilib.Record 方法):      Record Objects.     (line   37)
* clearok() (curses.window 方法):        Window 对象.        (line  133)
* clearscreen() (在 turtle 模块中):      窗口控制.           (line   36)
* clearstamp() (在 turtle 模块中):       海龟动作.           (line  235)
* clearstamps() (在 turtle 模块中):      海龟动作.           (line  254)
* clear_all_breaks() (bdb.Bdb 方法):     bdb --- Debugger framework.
                                                             (line  303)
* clear_all_file_breaks() (bdb.Bdb 方法): bdb --- Debugger framework.
                                                             (line  298)
* clear_bpbynumber() (bdb.Bdb 方法):     bdb --- Debugger framework.
                                                             (line  292)
* clear_break() (bdb.Bdb 方法):          bdb --- Debugger framework.
                                                             (line  287)
* clear_cache() (在 filecmp 模块中):     filecmp --- 文件及目录的比较.
                                                             (line   47)
* clear_content() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  567)
* clear_flags() (decimal.Context 方法):  上下文对象.         (line  127)
* clear_frames() (在 traceback 模块中):  traceback --- 打印或检索堆栈回溯.
                                                             (line  148)
* clear_history() (在 readline 模块中):  历史列表.           (line    8)
* clear_session_cookies() (http.cookiejar.CookieJar 方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   89)
* clear_traces() (在 tracemalloc 模块中): 函数<9>.           (line    6)
* clear_traps() (decimal.Context 方法):  上下文对象.         (line  131)
* Client() (在 multiprocessing.connection 模块中): 监听器及客户端.
                                                             (line   32)
* client_address (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line   57)
* CLOCK_BOOTTIME() (在 time 模块中):     Clock ID 常量.      (line    9)
* clock_getres() (在 time 模块中):       函数<2>.            (line   35)
* clock_gettime() (在 time 模块中):      函数<2>.            (line   44)
* clock_gettime_ns() (在 time 模块中):   函数<2>.            (line   53)
* CLOCK_HIGHRES() (在 time 模块中):      Clock ID 常量.      (line   22)
* CLOCK_MONOTONIC() (在 time 模块中):    Clock ID 常量.      (line   31)
* CLOCK_MONOTONIC_RAW() (在 time 模块中): Clock ID 常量.     (line   39)
* CLOCK_PROCESS_CPUTIME_ID() (在 time 模块中): Clock ID 常量.
                                                             (line   49)
* CLOCK_PROF() (在 time 模块中):         Clock ID 常量.      (line   57)
* CLOCK_REALTIME() (在 time 模块中):     Clock ID 常量.      (line   93)
* clock_settime() (在 time 模块中):      函数<2>.            (line   61)
* clock_settime_ns() (在 time 模块中):   函数<2>.            (line   70)
* CLOCK_THREAD_CPUTIME_ID() (在 time 模块中): Clock ID 常量. (line   65)
* CLOCK_UPTIME() (在 time 模块中):       Clock ID 常量.      (line   73)
* CLOCK_UPTIME_RAW() (在 time 模块中):   Clock ID 常量.      (line   82)
* clone() (email.generator.BytesGenerator 方法): email generator 生成 MIME 文档.
                                                             (line   92)
* clone() (email.generator.Generator 方法): email generator 生成 MIME 文档.
                                                             (line  174)
* clone() (email.policy.Policy 方法):    email policy 策略对象.
                                                             (line  168)
* clone() (pipes.Template 方法):         模板对象.           (line   12)
* clone() (在 turtle 模块中):            特殊海龟方法.       (line   30)
* cloneNode() (xml.dom.Node 方法):       节点对象.           (line  127)
* close() (aifc.aifc 方法):              aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  101)
* close() (asyncio.AbstractChildWatcher 方法): 进程监视器.   (line   68)
* close() (asyncio.BaseTransport 方法):  基础传输.           (line    6)
* close() (asyncio.loop 方法):           运行和停止循环.     (line   40)
* close() (asyncio.Server 方法):         Server 对象.        (line   27)
* close() (asyncio.StreamWriter 方法):   StreamWriter.       (line   34)
* close() (asyncio.SubprocessTransport 方法): 子进程传输.    (line   54)
* close() (asyncore.dispatcher 方法):    asyncore --- 异步socket处理器.
                                                             (line  196)
* close() (chunk.Chunk 方法):            chunk --- 读取 IFF 分块数据.
                                                             (line   67)
* close() (contextlib.ExitStack 方法):   工具.               (line  409)
* close() (coroutine 方法):              协程对象.           (line   33)
* close() (dbm.dumb.dumbdbm 方法):       dbm dumb --- 便携式 DBM 实现.
                                                             (line   69)
* close() (dbm.gnu.gdbm 方法):           dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line   99)
* close() (dbm.ndbm.ndbm 方法):          dbm ndbm --- 基于 ndbm 的接口.
                                                             (line   54)
* close() (distutils.text_file.TextFile 方法): distutils text_file --- The TextFile class.
                                                             (line   96)
* close() (email.parser.BytesFeedParser 方法): FeedParser API.
                                                             (line   56)
* close() (ftplib.FTP 方法):             FTP 对象.           (line  211)
* close() (generator 方法):              生成器-迭代器的方法.
                                                             (line   38)
* close() (html.parser.HTMLParser 方法): HTMLParser 方法.    (line   14)
* close() (http.client.HTTPConnection 方法): HTTPConnection 对象.
                                                             (line   92)
* close() (imaplib.IMAP4 方法):          IMAP4 Objects.      (line   62)
* close() (in module os):                Sub-interpreter support.
                                                             (line   76)
* close() (io.IOBase 方法):              I/O 基类.           (line   39)
* close() (logging.FileHandler 方法):    FileHandler.        (line   22)
* close() (logging.Handler 方法):        处理器对象.         (line   65)
* close() (logging.handlers.MemoryHandler 方法): MemoryHandler.
                                                             (line   48)
* close() (logging.handlers.NTEventLogHandler 方法): NTEventLogHandler.
                                                             (line   23)
* close() (logging.handlers.SocketHandler 方法): SocketHandler.
                                                             (line   17)
* close() (logging.handlers.SysLogHandler 方法): SysLogHandler.
                                                             (line   34)
* close() (mailbox.Mailbox 方法):        Mailbox 对象.       (line  214)
* close() (mailbox.Maildir 方法):        Maildir.            (line   96)
* close() (mailbox.MH 方法):             MH.                 (line   93)
* close() (mmap.mmap 方法):              mmap --- 内存映射文件支持.
                                                             (line  142)
* Close() (msilib.Database 方法):        Database Objects.   (line   22)
* Close() (msilib.View 方法):            View Objects.       (line   35)
* close() (multiprocessing.connection.Connection 方法): 连接对象（Connection）<2>.
                                                             (line   32)
* close() (multiprocessing.connection.Listener 方法): 监听器及客户端.
                                                             (line   80)
* close() (multiprocessing.pool.Pool 方法): 进程池.          (line  138)
* close() (multiprocessing.Process 方法): Process 和异常.    (line  146)
* close() (multiprocessing.Queue 方法):  管道和队列.         (line  139)
* close() (multiprocessing.shared_memory.SharedMemory 方法): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   49)
* close() (os.scandir 方法):             文件和目录.         (line  686)
* close() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line   22)
* close() (ossaudiodev.oss_mixer_device 方法): Mixer Device Objects.
                                                             (line    8)
* close() (select.devpoll 方法):         /dev/poll 轮询对象. (line   12)
* close() (select.epoll 方法):           边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   63)
* close() (select.kqueue 方法):          Kqueue 对象.        (line    6)
* close() (selectors.BaseSelector 方法): 类<3>.              (line  119)
* close() (shelve.Shelf 方法):           shelve --- Python 对象持久化.
                                                             (line   58)
* close() (socket.socket 方法):          套接字对象.         (line   34)
* close() (sqlite3.Connection 方法):     连接对象（Connection）.
                                                             (line   41)
* close() (sqlite3.Cursor 方法):         Cursor 对象.        (line  156)
* close() (sunau.AU_read 方法):          AU_read 对象.       (line    9)
* close() (sunau.AU_write 方法):         AU_write 对象.      (line   57)
* close() (tarfile.TarFile 方法):        TarFile 对象.       (line  213)
* close() (telnetlib.Telnet 方法):       Telnet 对象.        (line   80)
* close() (urllib.request.BaseHandler 方法): BaseHandler 对象.
                                                             (line   13)
* close() (wave.Wave_read 方法):         Wave_read对象.      (line    8)
* close() (wave.Wave_write 方法):        Wave_write 对象.    (line   18)
* Close() (winreg.PyHKEY 方法):          Registry Handle Objects.
                                                             (line   34)
* close() (xml.etree.ElementTree.TreeBuilder 方法): TreeBuilder 对象.
                                                             (line   23)
* close() (xml.etree.ElementTree.XMLParser 方法): XMLParser对象.
                                                             (line   18)
* close() (xml.etree.ElementTree.XMLPullParser 方法): XMLPullParser对象.
                                                             (line   20)
* close() (xml.sax.xmlreader.IncrementalParser 方法): IncrementalParser 对象.
                                                             (line   12)
* close() (zipfile.ZipFile 方法):        ZipFile 对象.       (line   74)
* close() (在 fileinput 模块中):         fileinput --- 迭代来自多个输入流的行.
                                                             (line  104)
* close() (在 os 模块中):                文件描述符操作.     (line   17)
* close() (在 socket 模块中):            其他功能<2>.        (line    8)
* closed (http.client.HTTPResponse 属性): HTTPResponse 对象. (line   65)
* closed (io.IOBase 属性):               I/O 基类.           (line   47)
* closed (mmap.mmap 属性):               mmap --- 内存映射文件支持.
                                                             (line  147)
* closed (ossaudiodev.oss_audio_device 属性): Audio Device Objects.
                                                             (line  226)
* closed (select.devpoll 属性):          /dev/poll 轮询对象. (line   18)
* closed (select.epoll 属性):            边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   67)
* closed (select.kqueue 属性):           Kqueue 对象.        (line   10)
* CloseKey() (在 winreg 模块中):         函数<11>.           (line    8)
* closelog() (在 syslog 模块中):         Unix syslog 库例程. (line   52)
* closerange() (在 os 模块中):           文件描述符操作.     (line   27)
* close_connection (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line   65)
* close_when_done() (asynchat.async_chat 方法): asynchat --- 异步 socket 指令/响应 处理器.
                                                             (line   61)
* closing() (在 contextlib 模块中):      工具.               (line  106)
* clrtobot() (curses.window 方法):       Window 对象.        (line  138)
* clrtoeol() (curses.window 方法):       Window 对象.        (line  143)
* cmath (模块):                          cmath --- 关于复数的数学函数.
                                                             (line    6)
* Cmd (cmd 中的类):                      cmd --- 支持面向行的命令解释器.
                                                             (line   13)
* cmd (subprocess.CalledProcessError 属性): 使用 subprocess 模块.
                                                             (line  181)
* cmd (subprocess.TimeoutExpired 属性):  使用 subprocess 模块.
                                                             (line  144)
* cmd (模块):                            cmd --- 支持面向行的命令解释器.
                                                             (line    6)
* cmdloop() (cmd.Cmd 方法):              Cmd 对象.           (line    8)
* cmdqueue (cmd.Cmd 属性):               Cmd 对象.           (line  107)
* cmp() (在 filecmp 模块中):             filecmp --- 文件及目录的比较.
                                                             (line   16)
* cmpfiles() (在 filecmp 模块中):        filecmp --- 文件及目录的比较.
                                                             (line   30)
* cmp_op() (在 dis 模块中):              操作码集合.         (line   16)
* cmp_to_key() (在 functools 模块中):    functools --- 高阶函数和可调用对象上的操作.
                                                             (line   44)
* CMSG_LEN() (在 socket 模块中):         其他功能<2>.        (line  243)
* CMSG_SPACE() (在 socket 模块中):       其他功能<2>.        (line  255)
* code (SystemExit 属性):                具体异常.           (line  272)
* code (urllib.error.HTTPError 属性):    urllib error --- urllib request 引发的异常类.
                                                             (line   34)
* code (xml.etree.ElementTree.ParseError 属性): 异常<15>.    (line   12)
* code (xml.parsers.expat.ExpatError 属性): ExpatError 异常. (line    8)
* code (模块):                           code --- 解释器基类.
                                                             (line    6)
* code object:                           标准类型层级结构.   (line  490)
* code object <1>:                       方法.               (line   35)
* code object <2>:                       marshal --- 内部 Python 对象序列化.
                                                             (line   24)
* code object <3>:                       Cell 对象.          (line   45)
* code; block:                           执行模型.           (line    6)
* CodecInfo (codecs 中的类):             codecs --- 编解码器注册和相关基类.
                                                             (line   49)
* Codecs:                                codecs --- 编解码器注册和相关基类.
                                                             (line    8)
* codecs (模块):                         codecs --- 编解码器注册和相关基类.
                                                             (line    6)
* Codecs; decode:                        codecs --- 编解码器注册和相关基类.
                                                             (line    8)
* Codecs; encode:                        codecs --- 编解码器注册和相关基类.
                                                             (line    8)
* coded_value (http.cookies.Morsel 属性): Morsel 对象.       (line   56)
* codeop (模块):                         codeop --- 编译Python代码.
                                                             (line    6)
* codepoint2name() (在 html.entities 模块中): html entities --- HTML 一般实体的定义.
                                                             (line   30)
* codes() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   14)
* CODESET() (在 locale 模块中):          locale --- 国际化服务.
                                                             (line  166)
* CodeType (types 中的类):               标准解释器类型.     (line   44)
* code_info() (在 dis 模块中):           分析函数.           (line    9)
* coding; style:                         小插曲：编码风格.   (line    6)
* coercion – 强制类型转换:               术语对照表.         (line  188)
* collapse_addresses() (在 ipaddress 模块中): Other Module Level Functions.
                                                             (line   43)
* collapse_rfc2231_value() (在 email.utils 模块中): email utils 其他工具.
                                                             (line  159)
* collect() (在 gc 模块中):              gc --- 垃圾回收器接口.
                                                             (line   30)
* Collection (collections.abc 中的类):   容器抽象基类.       (line  130)
* Collection (typing 中的类):            类 函数和修饰器.    (line  189)
* collections (模块):                    collections --- 容器数据类型.
                                                             (line    6)
* collections.abc (模块):                collections abc --- 容器的抽象基类.
                                                             (line    6)
* collect_incoming_data() (asynchat.async_chat 方法): asynchat --- 异步 socket 指令/响应 处理器.
                                                             (line   66)
* colno (json.JSONDecodeError 属性):     异常<13>.           (line   26)
* colno (re.error 属性):                 模块内容.           (line  309)
* COLON() (在 token 模块中):             token --- 与Python解析树一起使用的常量.
                                                             (line   66)
* COLONEQUAL() (在 token 模块中):        token --- 与Python解析树一起使用的常量.
                                                             (line  234)
* color() (在 turtle 模块中):            颜色控制.           (line   94)
* colormode() (在 turtle 模块中):        设置与特殊方法.     (line   32)
* colorsys (模块):                       colorsys --- 颜色系统间的转换.
                                                             (line    6)
* color_content() (在 curses 模块中):    函数<3>.            (line   39)
* color_pair() (在 curses 模块中):       函数<3>.            (line   45)
* COLS:                                  curses<2>.          (line    7)
* COLS <1>:                              函数<3>.            (line  436)
* column() (tkinter.ttk.Treeview 方法):  ttk Treeview.       (line   35)
* COLUMNS:                               函数<3>.            (line  456)
* COLUMNS <1>:                           函数<3>.            (line  457)
* columns (os.terminal_size 属性):       查询终端的尺寸.     (line   27)
* col_offset (ast.AST 属性):             节点类.             (line   32)
* comb() (在 math 模块中):               数论与表示函数.     (line   12)
* combinations() (在 itertools 模块中):  Itertool函数.       (line  102)
* combinations_with_replacement() (在 itertools 模块中): Itertool函数.
                                                             (line  147)
* combine() (datetime.datetime 类方法):  datetime 对象.      (line  152)
* combining() (在 unicodedata 模块中):   unicodedata --- Unicode 数据库.
                                                             (line   50)
* ComboBox (tkinter.tix 中的类):         Basic Widgets.      (line   18)
* Combobox (tkinter.ttk 中的类):         ttk Combobox.       (line    6)
* comma:                                 带圆括号的形式.     (line   18)
* COMMA() (在 token 模块中):             token --- 与Python解析树一起使用的常量.
                                                             (line   70)
* Command (distutils.cmd 中的类):        distutils cmd --- Abstract base class for Distutils commands.
                                                             (line    8)
* Command (distutils.core 中的类):       distutils core --- 分发包功能的核心.
                                                             (line  291)
* command (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line   76)
* command line:                          完整的 Python 程序. (line   19)
* command line option; -?:               通用选项.           (line    6)
* command line option; -b:               其他选项.           (line    6)
* command line option; -B:               其他选项.           (line   14)
* command line option; -c <command>:     接口选项.           (line   31)
* command line option; –check-hash-based-pycs default|always|never: 其他选项.
                                                             (line   19)
* command line option; -d:               其他选项.           (line   30)
* command line option; -E:               其他选项.           (line   35)
* command line option; -h:               通用选项.           (line    6)
* command line option; –help:            通用选项.           (line    6)
* command line option; -i:               其他选项.           (line   40)
* command line option; -I:               其他选项.           (line   49)
* command line option; -J:               不应当使用的选项.   (line    6)
* command line option; -m <module-name>: 接口选项.           (line   43)
* command line option; -O:               其他选项.           (line   58)
* command line option; -OO:              其他选项.           (line   67)
* command line option; -q:               其他选项.           (line   75)
* command line option; -R:               其他选项.           (line   81)
* command line option; -s:               其他选项.           (line  101)
* command line option; -S:               其他选项.           (line  111)
* command line option; -u:               其他选项.           (line  117)
* command line option; -V:               通用选项.           (line   12)
* command line option; -v:               其他选项.           (line  125)
* command line option; –version:         通用选项.           (line   12)
* command line option; -W arg:           其他选项.           (line  131)
* command line option; -x:               其他选项.           (line  164)
* command line option; -X:               其他选项.           (line  169)
* CommandCompiler (codeop 中的类):       codeop --- 编译Python代码.
                                                             (line   56)
* commands (pdb command):                调试器命令.         (line  103)
* comment:                               注释.               (line    6)
* comment (http.cookiejar.Cookie 属性):  Cookie 对象<2>.     (line   58)
* comment (zipfile.ZipFile 属性):        ZipFile 对象.       (line  269)
* comment (zipfile.ZipInfo 属性):        ZipInfo 对象.       (line   81)
* comment() (xml.etree.ElementTree.TreeBuilder 方法): TreeBuilder 对象.
                                                             (line   42)
* COMMENT() (在 token 模块中):           token --- 与Python解析树一起使用的常量.
                                                             (line  257)
* Comment() (在 xml.etree.ElementTree 模块中): 函数<6>.      (line   65)
* commenters (shlex.shlex 属性):         shlex Objects.      (line   85)
* CommentHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  244)
* comment_url (http.cookiejar.Cookie 属性): Cookie 对象<2>.  (line   63)
* commit() (msilib.CAB 方法):            CAB Objects.        (line   24)
* Commit() (msilib.Database 方法):       Database Objects.   (line   11)
* commit() (sqlite3.Connection 方法):    连接对象（Connection）.
                                                             (line   29)
* common (filecmp.dircmp 属性):          dircmp 类.          (line   52)
* Common Gateway Interface:              cgi --- 通用网关接口支持.
                                                             (line    8)
* commonpath() (在 os.path 模块中):      os path --- 常用路径操作.
                                                             (line   63)
* commonprefix() (在 os.path 模块中):    os path --- 常用路径操作.
                                                             (line   76)
* common_dirs (filecmp.dircmp 属性):     dircmp 类.          (line   64)
* common_files (filecmp.dircmp 属性):    dircmp 类.          (line   68)
* common_funny (filecmp.dircmp 属性):    dircmp 类.          (line   72)
* common_types() (在 mimetypes 模块中):  mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line  122)
* communicate() (asyncio.asyncio.subprocess.Process 方法): 与子进程交互.
                                                             (line   44)
* communicate() (subprocess.Popen 方法): Popen 对象.         (line   30)
* compare() (decimal.Context 方法):      上下文对象.         (line  208)
* compare() (decimal.Decimal 方法):      Decimal 对象.       (line  123)
* compare() (difflib.Differ 方法):       Differ 对象.        (line   30)
* compare_digest() (在 hmac 模块中):     hmac --- 基于密钥的消息验证.
                                                             (line   95)
* compare_digest() (在 secrets 模块中):  其他功能.           (line    6)
* compare_networks() (ipaddress.IPv4Network 方法): Network objects.
                                                             (line  237)
* compare_networks() (ipaddress.IPv6Network 方法): Network objects.
                                                             (line  352)
* COMPARE_OP (opcode):                   Python字节码说明.   (line  575)
* compare_signal() (decimal.Context 方法): 上下文对象.       (line  212)
* compare_signal() (decimal.Decimal 方法): Decimal 对象.     (line  133)
* compare_to() (tracemalloc.Snapshot 方法): 快照.            (line   13)
* compare_total() (decimal.Context 方法): 上下文对象.        (line  216)
* compare_total() (decimal.Decimal 方法): Decimal 对象.      (line  139)
* compare_total_mag() (decimal.Context 方法): 上下文对象.    (line  220)
* compare_total_mag() (decimal.Decimal 方法): Decimal 对象.  (line  159)
* comparison:                            比较运算.           (line    6)
* comparisons:                           基本定制.           (line  149)
* COMPARISON_FLAGS() (在 doctest 模块中): Option Flags.      (line  115)
* Compat32 (email.policy 中的类):        email policy 策略对象.
                                                             (line  441)
* compat32() (在 email.policy 模块中):   email policy 策略对象.
                                                             (line  487)
* Compile (codeop 中的类):               codeop --- 编译Python代码.
                                                             (line   49)
* compile() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  266)
* compile() (parser.ST 方法):            ST 对象.            (line   17)
* compile() (內置函数):                  内置函数.           (line  219)
* compile() (在 py_compile 模块中):      py_compile --- 编译 Python 源文件.
                                                             (line   20)
* compile() (在 re 模块中):              模块内容.           (line   13)
* compileall (模块):                     compileall --- Byte-compile Python libraries.
                                                             (line    6)
* compileall command line option; -b:    Command-line use.   (line   52)
* compileall command line option; -d destdir: Command-line use.
                                                             (line   32)
* compileall command line option; -f:    Command-line use.   (line   22)
* compileall command line option; -i list: Command-line use. (line   46)
* compileall command line option; –invalidation-mode [timestamp|checked-hash|unchecked-hash]: Command-line use.
                                                             (line   73)
* compileall command line option; -j N:  Command-line use.   (line   67)
* compileall command line option; -l:    Command-line use.   (line   17)
* compileall command line option; -q:    Command-line use.   (line   26)
* compileall command line option; -r:    Command-line use.   (line   60)
* compileall command line option; -x regex: Command-line use.
                                                             (line   40)
* compileall command line option; directory ...: Command-line use.
                                                             (line    9)
* compileall command line option; file ...: Command-line use.
                                                             (line    9)
* compilest() (在 parser 模块中):        转换 ST 对象.       (line   43)
* compile_command() (在 code 模块中):    code --- 解释器基类.
                                                             (line   40)
* compile_command() (在 codeop 模块中):  codeop --- 编译Python代码.
                                                             (line   26)
* compile_dir() (在 compileall 模块中):  Public functions.   (line    6)
* compile_file() (在 compileall 模块中): Public functions.   (line   74)
* compile_path() (在 compileall 模块中): Public functions.   (line  120)
* complete() (rlcompleter.Completer 方法): Completer 对象.   (line    8)
* completedefault() (cmd.Cmd 方法):      Cmd 对象.           (line   62)
* CompletedProcess (subprocess 中的类):  使用 subprocess 模块.
                                                             (line   77)
* complete_statement() (在 sqlite3 模块中): 模块函数和常量.  (line  120)
* Complex (numbers 中的类):              数字的层次.         (line    6)
* complex (內置类):                      内置函数.           (line  283)
* complex literal:                       数字字面值.         (line    6)
* complex number – 复数:                 术语对照表.         (line  197)
* complex number; literals:              数字类型 --- int float complex.
                                                             (line   14)
* complex; number:                       标准类型层级结构.   (line   87)
* compound; statement:                   复合语句.           (line    6)
* comprehensions:                        列表、集合与字典的显示.
                                                             (line    6)
* compress() (bz2.BZ2Compressor 方法):   增量压缩和解压.     (line   14)
* compress() (lzma.LZMACompressor 方法): 在内存中压缩和解压缩数据.
                                                             (line   64)
* compress() (zlib.Compress 方法):       zlib --- 与 gzip 兼容的压缩.
                                                             (line  148)
* compress() (在 bz2 模块中):            一次性压缩或解压缩. (line    6)
* compress() (在 gzip 模块中):           gzip --- 对 gzip 格式的支持.
                                                             (line  142)
* compress() (在 itertools 模块中):      Itertool函数.       (line  192)
* compress() (在 lzma 模块中):           在内存中压缩和解压缩数据.
                                                             (line  149)
* compress() (在 zlib 模块中):           zlib --- 与 gzip 兼容的压缩.
                                                             (line   35)
* compressed (ipaddress.IPv4Address 属性): 地址对象.         (line   53)
* compressed (ipaddress.IPv4Network 属性): Network objects.  (line  107)
* compressed (ipaddress.IPv6Address 属性): 地址对象.         (line  149)
* compressed (ipaddress.IPv6Network 属性): Network objects.  (line  319)
* compression() (ssl.SSLSocket 方法):    SSL 套接字.         (line  197)
* CompressionError:                      tarfile --- 读写tar归档文件.
                                                             (line  170)
* compressobj() (在 zlib 模块中):        zlib --- 与 gzip 兼容的压缩.
                                                             (line   47)
* compress_size (zipfile.ZipInfo 属性):  ZipInfo 对象.       (line  130)
* compress_type (zipfile.ZipInfo 属性):  ZipInfo 对象.       (line   77)
* COMSPEC:                               进程管理.           (line  560)
* COMSPEC <1>:                           Popen 构造函数.     (line   74)
* concat() (在 operator 模块中):         operator --- 标准运算符替代函数.
                                                             (line  158)
* concatenation; operation:              通用序列操作.       (line   17)
* concurrent.futures (模块):             concurrent futures --- 启动并行任务.
                                                             (line    6)
* Condition (asyncio 中的类):            Condition.          (line    6)
* Condition (multiprocessing 中的类):    同步原语.           (line   27)
* condition (pdb command):               调试器命令.         (line   97)
* Condition (threading 中的类):          条件对象.           (line   60)
* condition() (msilib.Control 方法):     GUI classes.        (line   24)
* Condition() (multiprocessing.managers.SyncManager 方法): 管理器.
                                                             (line  133)
* Conditional; expression:               布尔运算.           (line    6)
* conditional; expression:               条件表达式.         (line    6)
* ConfigParser (configparser 中的类):    ConfigParser 对象.  (line    6)
* configparser (模块):                   configparser --- 配置文件解析器.
                                                             (line    6)
* configuration information:             sysconfig --- Provide access to Python's configuration information.
                                                             (line   10)
* configuration; file:                   configparser --- 配置文件解析器.
                                                             (line    8)
* configure() (tkinter.ttk.Style 方法):  Ttk Styling.        (line   24)
* configure_mock() (unittest.mock.Mock 方法): Mock 类.       (line  222)
* confstr() (在 os 模块中):              其他系统信息.       (line    6)
* confstr_names() (在 os 模块中):        其他系统信息.       (line   23)
* conjugate() (complex number method):   数字类型 --- int float complex.
                                                             (line   83)
* conjugate() (decimal.Decimal 方法):    Decimal 对象.       (line  170)
* conjugate() (numbers.Complex 方法):    数字的层次.         (line   22)
* conn (smtpd.SMTPChannel 属性):         SMTPChannel 对象.   (line   47)
* connect() (asyncore.dispatcher 方法):  asyncore --- 异步socket处理器.
                                                             (line  157)
* connect() (ftplib.FTP 方法):           FTP 对象.           (line   19)
* connect() (http.client.HTTPConnection 方法): HTTPConnection 对象.
                                                             (line   87)
* connect() (multiprocessing.managers.BaseManager 方法): 管理器.
                                                             (line   51)
* connect() (smtplib.SMTP 方法):         SMTP Objects.       (line   33)
* connect() (socket.socket 方法):        套接字对象.         (line   51)
* connect() (在 sqlite3 模块中):         模块函数和常量.     (line   44)
* Connection (multiprocessing.connection 中的类): 连接对象（Connection）<2>.
                                                             (line   12)
* Connection (sqlite3 中的类):           连接对象（Connection）.
                                                             (line    6)
* connection (sqlite3.Cursor 属性):      Cursor 对象.        (line  206)
* ConnectionAbortedError:                OS 异常.            (line   40)
* ConnectionError:                       OS 异常.            (line   26)
* ConnectionRefusedError:                OS 异常.            (line   45)
* ConnectionResetError:                  OS 异常.            (line   50)
* connection_lost() (asyncio.BaseProtocol 方法): 基础协议<2>.
                                                             (line   21)
* connection_made() (asyncio.BaseProtocol 方法): 基础协议<2>.
                                                             (line   14)
* ConnectRegistry() (在 winreg 模块中):  函数<11>.           (line   16)
* connect_accepted_socket() (asyncio.loop 方法): 创建网络服务.
                                                             (line  105)
* connect_ex() (socket.socket 方法):     套接字对象.         (line   70)
* connect_read_pipe() (asyncio.loop 方法): 使用管道.         (line    6)
* connect_write_pipe() (asyncio.loop 方法): 使用管道.        (line   22)
* const (optparse.Option 属性):          Option attributes.  (line   50)
* constant:                              字面值.             (line    6)
* constructor() (在 copyreg 模块中):     copyreg --- 注册配合 pickle 模块使用的函数.
                                                             (line   15)
* consumed (asyncio.LimitOverrunError 属性): 异常<9>.        (line   60)
* container:                             对象、值与类型.     (line   50)
* container <1>:                         标准类型层级结构.   (line  435)
* Container (collections.abc 中的类):    容器抽象基类.       (line  104)
* Container (typing 中的类):             类 函数和修饰器.    (line  177)
* container; iteration over:             迭代器类型.         (line    6)
* contains() (在 operator 模块中):       operator --- 标准运算符替代函数.
                                                             (line  163)
* ContentDispositionHeader (email.headerregistry 中的类): email headerregistry 自定义标头对象.
                                                             (line  230)
* ContentHandler (xml.sax.handler 中的类): xml sax handler --- SAX 处理程序的基类.
                                                             (line   15)
* ContentManager (email.contentmanager 中的类): email contentmanager 管理 MIME 内容.
                                                             (line   12)
* contents (ctypes._Pointer 属性):       数组与指针.         (line   43)
* contents() (importlib.abc.ResourceReader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  299)
* contents() (在 importlib.resources 模块中): importlib resources -- 资源.
                                                             (line  123)
* ContentTooShortError:                  urllib error --- urllib request 引发的异常类.
                                                             (line   50)
* ContentTransferEncoding (email.headerregistry 中的类): email headerregistry 自定义标头对象.
                                                             (line  239)
* ContentTypeHeader (email.headerregistry 中的类): email headerregistry 自定义标头对象.
                                                             (line  217)
* content_disposition (email.headerregistry.ContentDispositionHeader 属性): email headerregistry 自定义标头对象.
                                                             (line  235)
* content_manager (email.policy.EmailPolicy 属性): email policy 策略对象.
                                                             (line  324)
* content_type (email.headerregistry.ContentTypeHeader 属性): email headerregistry 自定义标头对象.
                                                             (line  222)
* Context (contextvars 中的类):          手动上下文管理.     (line   18)
* Context (decimal 中的类):              上下文对象.         (line   81)
* context (ssl.SSLSocket 属性):          SSL 套接字.         (line  274)
* context management protocol:           上下文管理器类型.   (line    6)
* context manager:                       with 语句上下文管理器.
                                                             (line   11)
* context manager <1>:                   上下文管理器类型.   (line    6)
* context manager – 上下文管理器:        术语对照表.         (line  206)
* context variable – 上下文变量:         术语对照表.         (line  212)
* ContextDecorator (contextlib 中的类):  工具.               (line  241)
* contextlib (模块):                     contextlib --- 为 with语句上下文提供的工具.
                                                             (line    6)
* ContextManager (typing 中的类):        类 函数和修饰器.    (line  313)
* contextmanager() (在 contextlib 模块中): 工具.             (line   28)
* ContextVar (contextvars 中的类):       上下文变量.         (line    6)
* contextvars (模块):                    contextvars 上下文变量.
                                                             (line    6)
* contextvars.Token (contextvars 中的类): 上下文变量.        (line   65)
* context_diff() (在 difflib 模块中):    difflib --- 计算差异的辅助工具.
                                                             (line  129)
* contiguous:                            形状，步幅，子偏移量.
                                                             (line   25)
* contiguous (memoryview 属性):          内存视图.           (line  444)
* contiguous – 连续:                     术语对照表.         (line  218)
* continue (pdb command):                调试器命令.         (line  157)
* Control (msilib 中的类):               GUI classes.        (line   11)
* Control (tkinter.tix 中的类):          Basic Widgets.      (line   24)
* control() (msilib.Dialog 方法):        GUI classes.        (line   47)
* control() (select.kqueue 方法):        Kqueue 对象.        (line   22)
* controlnames() (在 curses.ascii 模块中): curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  221)
* controls() (ossaudiodev.oss_mixer_device 方法): Mixer Device Objects.
                                                             (line   23)
* ConversionError:                       异常<6>.            (line   13)
* convert_arg_line_to_args() (argparse.ArgumentParser 方法): 自定义文件解析.
                                                             (line    6)
* convert_field() (string.Formatter 方法): 自定义字符串格式化.
                                                             (line   86)
* convert_path() (在 distutils.util 模块中): distutils util --- Miscellaneous other utility functions.
                                                             (line   54)
* Cookie (http.cookiejar 中的类):        http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   92)
* CookieError:                           http cookies --- HTTP状态管理.
                                                             (line   33)
* CookieJar (http.cookiejar 中的类):     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   38)
* cookiejar (urllib.request.HTTPCookieProcessor 属性): HTTPCookieProcessor 对象.
                                                             (line    8)
* CookiePolicy (http.cookiejar 中的类):  http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   60)
* Coordinated Universal Time:            time --- 时间的访问和转换.
                                                             (line   32)
* Copy:                                  帮助菜单（命令行和编辑器）.
                                                             (line   26)
* copy (模块):                           copy --- 浅层 shallow 和深层 deep 复制操作.
                                                             (line    6)
* copy() (collections.deque 方法):       deque 对象.         (line   39)
* copy() (contextvars.Context 方法):     手动上下文管理.     (line   64)
* copy() (decimal.Context 方法):         上下文对象.         (line  137)
* copy() (dict 方法):                    映射类型 --- dict.  (line  128)
* copy() (frozenset 方法):               集合类型 --- set frozenset.
                                                             (line  114)
* copy() (hashlib.hash 方法):            哈希算法.           (line  126)
* copy() (hmac.HMAC 方法):               hmac --- 基于密钥的消息验证.
                                                             (line   70)
* copy() (http.cookies.Morsel 方法):     Morsel 对象.        (line  102)
* copy() (imaplib.IMAP4 方法):           IMAP4 Objects.      (line   68)
* copy() (pipes.Template 方法):          模板对象.           (line   45)
* copy() (sequence method):              可变序列类型.       (line   14)
* copy() (types.MappingProxyType 方法):  标准解释器类型.     (line  215)
* copy() (zlib.Compress 方法):           zlib --- 与 gzip 兼容的压缩.
                                                             (line  164)
* copy() (zlib.Decompress 方法):         zlib --- 与 gzip 兼容的压缩.
                                                             (line  220)
* copy() (在 copy 模块中):               copy --- 浅层 shallow 和深层 deep 复制操作.
                                                             (line   17)
* copy() (在 multiprocessing.sharedctypes 模块中): multiprocessing sharedctypes 模块.
                                                             (line   70)
* copy() (在 shutil 模块中):             目录和文件操作.     (line  101)
* copy2() (在 shutil 模块中):            目录和文件操作.     (line  128)
* copy; protocol:                        封存类实例.         (line   78)
* copyfile() (在 shutil 模块中):         目录和文件操作.     (line   14)
* copyfileobj() (在 shutil 模块中):      目录和文件操作.     (line    6)
* copying files:                         shutil --- 高阶文件操作.
                                                             (line    8)
* copymode() (在 shutil 模块中):         目录和文件操作.     (line   49)
* copyreg (模块):                        copyreg --- 注册配合 pickle 模块使用的函数.
                                                             (line    6)
* copyright (in module sys):             Process-wide parameters.
                                                             (line  188)
* copyright (內置变量):                  由 site 模块添加的常量.
                                                             (line   17)
* copyright() (在 sys 模块中):           sys --- 系统相关的参数和函数.
                                                             (line  128)
* copysign() (在 math 模块中):           数论与表示函数.     (line   27)
* copystat() (在 shutil 模块中):         目录和文件操作.     (line   64)
* copytree() (在 shutil 模块中):         目录和文件操作.     (line  161)
* copy_abs() (decimal.Context 方法):     上下文对象.         (line  224)
* copy_abs() (decimal.Decimal 方法):     Decimal 对象.       (line  174)
* copy_context() (在 contextvars 模块中): 手动上下文管理.    (line    6)
* copy_decimal() (decimal.Context 方法): 上下文对象.         (line  141)
* copy_file() (在 distutils.file_util 模块中): distutils file_util --- Single file operations.
                                                             (line    9)
* copy_file_range() (在 os 模块中):      文件描述符操作.     (line   38)
* copy_location() (在 ast 模块中):       ast 中的辅助函数.   (line   92)
* copy_negate() (decimal.Context 方法):  上下文对象.         (line  228)
* copy_negate() (decimal.Decimal 方法):  Decimal 对象.       (line  179)
* copy_sign() (decimal.Context 方法):    上下文对象.         (line  232)
* copy_sign() (decimal.Decimal 方法):    Decimal 对象.       (line  184)
* copy_tree() (在 distutils.dir_util 模块中): distutils dir_util --- Directory tree operations.
                                                             (line   32)
* coroutine:                             特殊方法查找.       (line   67)
* coroutine <1>:                         yield 表达式.       (line   42)
* Coroutine (collections.abc 中的类):    容器抽象基类.       (line  204)
* Coroutine (typing 中的类):             类 函数和修饰器.    (line  286)
* coroutine – 协程:                      术语对照表.         (line  226)
* coroutine function – 协程函数:         术语对照表.         (line  232)
* coroutine() (在 asyncio 模块中):       基于生成器的协程.   (line   15)
* coroutine() (在 types 模块中):         协程工具函数.       (line    6)
* coroutine; function:                   标准类型层级结构.   (line  347)
* CoroutineType() (在 types 模块中):     标准解释器类型.     (line   30)
* cos() (在 cmath 模块中):               三角函数<2>.        (line   22)
* cos() (在 math 模块中):                三角函数.           (line   26)
* cosh() (在 cmath 模块中):              双曲函数<2>.        (line   22)
* cosh() (在 math 模块中):               双曲函数.           (line   20)
* count (tracemalloc.Statistic 属性):    统计.               (line   15)
* count (tracemalloc.StatisticDiff 属性): StatisticDiff.     (line   15)
* count() (array.array 方法):            array --- 高效的数值数组.
                                                             (line  127)
* count() (bytearray 方法):              bytes 和 bytearray 操作.
                                                             (line   30)
* count() (bytes 方法):                  bytes 和 bytearray 操作.
                                                             (line   30)
* count() (collections.deque 方法):      deque 对象.         (line   45)
* count() (multiprocessing.shared_memory.ShareableList 方法): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  226)
* count() (sequence method):             通用序列操作.       (line   17)
* count() (str 方法):                    字符串的方法<2>.    (line   46)
* count() (在 itertools 模块中):         Itertool函数.       (line  203)
* Counter (collections 中的类):          Counter 对象.       (line   22)
* Counter (typing 中的类):               类 函数和修饰器.    (line  353)
* countOf() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line  168)
* countTestCases() (unittest.TestCase 方法): 测试用例.       (line  705)
* countTestCases() (unittest.TestSuite 方法): Grouping tests.
                                                             (line   55)
* count_diff (tracemalloc.StatisticDiff 属性): StatisticDiff.
                                                             (line   20)
* CoverageResults (trace 中的类):        编程接口.           (line   47)
* co_argcount (code object attribute):   标准类型层级结构.   (line  499)
* CO_ASYNC_GENERATOR() (在 inspect 模块中): Code Objects Bit Flags.
                                                             (line   56)
* co_cellvars (code object attribute):   标准类型层级结构.   (line  499)
* co_code (code object attribute):       标准类型层级结构.   (line  499)
* co_consts (code object attribute):     标准类型层级结构.   (line  499)
* CO_COROUTINE() (在 inspect 模块中):    Code Objects Bit Flags.
                                                             (line   39)
* co_filename (code object attribute):   标准类型层级结构.   (line  499)
* co_firstlineno (code object attribute): 标准类型层级结构.  (line  499)
* co_flags (code object attribute):      标准类型层级结构.   (line  499)
* co_freevars (code object attribute):   标准类型层级结构.   (line  499)
* CO_FUTURE_DIVISION (C 变量):           The Very High Level Layer.
                                                             (line  420)
* CO_GENERATOR() (在 inspect 模块中):    Code Objects Bit Flags.
                                                             (line   30)
* CO_ITERABLE_COROUTINE() (在 inspect 模块中): Code Objects Bit Flags.
                                                             (line   47)
* co_kwonlyargcount (code object attribute): 标准类型层级结构.
                                                             (line  499)
* co_lnotab (code object attribute):     标准类型层级结构.   (line  499)
* co_name (code object attribute):       标准类型层级结构.   (line  499)
* co_names (code object attribute):      标准类型层级结构.   (line  499)
* CO_NESTED() (在 inspect 模块中):       Code Objects Bit Flags.
                                                             (line   26)
* CO_NEWLOCALS() (在 inspect 模块中):    Code Objects Bit Flags.
                                                             (line   13)
* co_nlocals (code object attribute):    标准类型层级结构.   (line  499)
* CO_NOFREE() (在 inspect 模块中):       Code Objects Bit Flags.
                                                             (line   35)
* CO_OPTIMIZED() (在 inspect 模块中):    Code Objects Bit Flags.
                                                             (line    9)
* co_posonlyargcount (code object attribute): 标准类型层级结构.
                                                             (line  499)
* co_stacksize (code object attribute):  标准类型层级结构.   (line  499)
* CO_VARARGS() (在 inspect 模块中):      Code Objects Bit Flags.
                                                             (line   18)
* CO_VARKEYWORDS() (在 inspect 模块中):  Code Objects Bit Flags.
                                                             (line   22)
* co_varnames (code object attribute):   标准类型层级结构.   (line  499)
* CPP:                                   新增，改进和弃用的模块<4>.
                                                             (line   59)
* CPPFLAGS:                              新增，改进和弃用的模块<4>.
                                                             (line   59)
* cProfile (模块):                       profile 和 cProfile 模块参考.
                                                             (line    6)
* CPU time:                              函数<2>.            (line  174)
* CPU time <1>:                          函数<2>.            (line  414)
* cpu_count() (在 multiprocessing 模块中): 杂项<3>.          (line   12)
* cpu_count() (在 os 模块中):            其他系统信息.       (line   31)
* CPython:                               术语对照表.         (line  239)
* cpython_only() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  632)
* crawl_delay() (urllib.robotparser.RobotFileParser 方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   46)
* CRC (zipfile.ZipInfo 属性):            ZipInfo 对象.       (line  126)
* crc32() (在 binascii 模块中):          binascii --- 二进制和 ASCII 码互转.
                                                             (line   96)
* crc32() (在 zlib 模块中):              zlib --- 与 gzip 兼容的压缩.
                                                             (line   87)
* crc_hqx() (在 binascii 模块中):        binascii --- 二进制和 ASCII 码互转.
                                                             (line   90)
* create() (imaplib.IMAP4 方法):         IMAP4 Objects.      (line   72)
* create() (venv.EnvBuilder 方法):       API<2>.             (line   45)
* create() (在 venv 模块中):             API<2>.             (line  133)
* createAttribute() (xml.dom.Document 方法): 文档对象.       (line   40)
* createAttributeNS() (xml.dom.Document 方法): 文档对象.     (line   46)
* createComment() (xml.dom.Document 方法): 文档对象.         (line   30)
* createDocument() (xml.dom.DOMImplementation 方法): DOMImplementation 对象.
                                                             (line   15)
* createDocumentType() (xml.dom.DOMImplementation 方法): DOMImplementation 对象.
                                                             (line   24)
* createElement() (xml.dom.Document 方法): 文档对象.         (line   13)
* createElementNS() (xml.dom.Document 方法): 文档对象.       (line   19)
* createfilehandler() (tkinter.Widget.tk 方法): File Handlers.
                                                             (line   27)
* CreateKey() (在 winreg 模块中):        函数<11>.           (line   34)
* CreateKeyEx() (在 winreg 模块中):      函数<11>.           (line   59)
* createLock() (logging.Handler 方法):   处理器对象.         (line   18)
* createLock() (logging.NullHandler 方法): NullHandler.      (line   23)
* createProcessingInstruction() (xml.dom.Document 方法): 文档对象.
                                                             (line   35)
* CreateRecord() (在 msilib 模块中):     msilib --- Read and write Microsoft Installer files.
                                                             (line   55)
* createSocket() (logging.handlers.SocketHandler 方法): SocketHandler.
                                                             (line   59)
* createTextNode() (xml.dom.Document 方法): 文档对象.        (line   25)
* create_aggregate() (sqlite3.Connection 方法): 连接对象（Connection）.
                                                             (line   98)
* create_archive() (在 zipapp 模块中):   Python API.         (line    8)
* create_autospec() (在 unittest.mock 模块中): create_autospec.
                                                             (line    6)
* CREATE_BREAKAWAY_FROM_JOB() (在 subprocess 模块中): Windows 常数.
                                                             (line  112)
* create_collation() (sqlite3.Connection 方法): 连接对象（Connection）.
                                                             (line  135)
* create_configuration() (venv.EnvBuilder 方法): API<2>.     (line   78)
* create_connection() (asyncio.loop 方法): 打开网络连接.     (line    6)
* create_connection() (在 socket 模块中): 创建套接字.        (line   69)
* create_datagram_endpoint() (asyncio.loop 方法): 打开网络连接.
                                                             (line  114)
* create_decimal() (decimal.Context 方法): 上下文对象.       (line  145)
* create_decimal_from_float() (decimal.Context 方法): 上下文对象.
                                                             (line  165)
* create_default_context() (在 ssl 模块中): 上下文创建.      (line    8)
* CREATE_DEFAULT_ERROR_MODE() (在 subprocess 模块中): Windows 常数.
                                                             (line  104)
* create_empty_file() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  237)
* create_function() (sqlite3.Connection 方法): 连接对象（Connection）.
                                                             (line   65)
* create_future() (asyncio.loop 方法):   创建 Futures 和 Tasks.
                                                             (line    6)
* create_module (C 函数):                Multi-phase initialization.
                                                             (line   67)
* create_module() (importlib.abc.Loader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  158)
* create_module() (importlib.machinery.ExtensionFileLoader 方法): importlib machinery -- Importers and path hooks.
                                                             (line  312)
* CREATE_NEW_CONSOLE() (在 subprocess 模块中): Windows 常数. (line   34)
* CREATE_NEW_PROCESS_GROUP() (在 subprocess 模块中): Windows 常数.
                                                             (line   38)
* CREATE_NO_WINDOW() (在 subprocess 模块中): Windows 常数.   (line   90)
* create_server() (asyncio.loop 方法):   创建网络服务.       (line    6)
* create_server() (在 socket 模块中):    创建套接字.         (line   90)
* create_shortcut() (內置函数):          The Postinstallation script.
                                                             (line   62)
* create_socket() (asyncore.dispatcher 方法): asyncore --- 异步socket处理器.
                                                             (line  149)
* create_static_lib() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  320)
* create_stats() (profile.Profile 方法): profile 和 cProfile 模块参考.
                                                             (line   85)
* create_string_buffer() (在 ctypes 模块中): 工具函数.       (line   35)
* create_subprocess_exec() (在 asyncio 模块中): 创建子进程.  (line    6)
* create_subprocess_shell() (在 asyncio 模块中): 创建子进程. (line   24)
* create_system (zipfile.ZipInfo 属性):  ZipInfo 对象.       (line   90)
* create_task() (asyncio.loop 方法):     创建 Futures 和 Tasks.
                                                             (line   15)
* create_task() (在 asyncio 模块中):     创建任务.           (line    6)
* create_tree() (在 distutils.dir_util 模块中): distutils dir_util --- Directory tree operations.
                                                             (line   21)
* create_unicode_buffer() (在 ctypes 模块中): 工具函数.      (line   50)
* create_unix_connection() (asyncio.loop 方法): 打开网络连接.
                                                             (line  180)
* create_unix_server() (asyncio.loop 方法): 创建网络服务.    (line   84)
* create_version (zipfile.ZipInfo 属性): ZipInfo 对象.       (line   94)
* credits (內置变量):                    由 site 模块添加的常量.
                                                             (line   17)
* critical() (logging.Logger 方法):      记录器对象.         (line  184)
* critical() (在 logging 模块中):        模块级别函数.       (line  115)
* CRNCYSTR() (在 locale 模块中):         locale --- 国际化服务.
                                                             (line  239)
* cross() (在 audioop 模块中):           audioop --- 处理原始音频数据.
                                                             (line   64)
* crypt (模块):                          crypt --- Function to check Unix passwords.
                                                             (line    6)
* crypt() (在 crypt 模块中):             模块函数<2>.        (line    8)
* crypt(3):                              crypt --- Function to check Unix passwords.
                                                             (line    8)
* crypt(3) <1>:                          crypt --- Function to check Unix passwords.
                                                             (line   16)
* crypt(3) <2>:                          模块函数<2>.        (line   32)
* cryptography:                          加密服务.           (line    6)
* cssclasses (calendar.HTMLCalendar 属性): calendar --- 日历相关函数.
                                                             (line  160)
* cssclasses_weekday_head (calendar.HTMLCalendar 属性): calendar --- 日历相关函数.
                                                             (line  178)
* cssclass_month (calendar.HTMLCalendar 属性): calendar --- 日历相关函数.
                                                             (line  192)
* cssclass_month_head (calendar.HTMLCalendar 属性): calendar --- 日历相关函数.
                                                             (line  185)
* cssclass_noday (calendar.HTMLCalendar 属性): calendar --- 日历相关函数.
                                                             (line  172)
* cssclass_year (calendar.HTMLCalendar 属性): calendar --- 日历相关函数.
                                                             (line  199)
* cssclass_year_head (calendar.HTMLCalendar 属性): calendar --- 日历相关函数.
                                                             (line  206)
* csv:                                   csv --- CSV 文件读写.
                                                             (line    8)
* csv (模块):                            csv --- CSV 文件读写.
                                                             (line    6)
* cte (email.headerregistry.ContentTransferEncoding 属性): email headerregistry 自定义标头对象.
                                                             (line  243)
* ctermid() (在 os 模块中):              进程参数.           (line    8)
* cte_type (email.policy.Policy 属性):   email policy 策略对象.
                                                             (line  126)
* ctime() (datetime.date 方法):          date 对象.          (line  231)
* ctime() (datetime.datetime 方法):      datetime 对象.      (line  614)
* ctime() (在 time 模块中):              函数<2>.            (line   78)
* ctrl() (在 curses.ascii 模块中):       curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  201)
* CTRL_BREAK_EVENT() (在 signal 模块中): 模块内容<5>.        (line  149)
* CTRL_C_EVENT() (在 signal 模块中):     模块内容<5>.        (line  140)
* ctypes (模块):                         ctypes --- Python 的外部函数库.
                                                             (line    6)
* curdir() (在 os 模块中):               其他系统信息.       (line   67)
* currency() (在 locale 模块中):         locale --- 国际化服务.
                                                             (line  400)
* current() (tkinter.ttk.Combobox 方法): ttk Combobox.       (line    8)
* CurrentByteIndex (xml.parsers.expat.xmlparser 属性): XMLParser对象<2>.
                                                             (line  129)
* CurrentColumnNumber (xml.parsers.expat.xmlparser 属性): XMLParser对象<2>.
                                                             (line  133)
* currentframe() (在 inspect 模块中):    The interpreter stack.
                                                             (line   72)
* CurrentLineNumber (xml.parsers.expat.xmlparser 属性): XMLParser对象<2>.
                                                             (line  137)
* current_process() (在 multiprocessing 模块中): 杂项<3>.    (line   26)
* current_task() (asyncio.Task 类方法):  Task 对象.          (line  217)
* current_task() (在 asyncio 模块中):    内省.               (line    6)
* current_thread() (在 threading 模块中): threading --- 基于线程的并行.
                                                             (line   32)
* curses (模块):                         curses --- 终端字符单元显示的处理.
                                                             (line    6)
* curses.ascii (模块):                   curses ascii --- 用于 ASCII 字符的工具.
                                                             (line    6)
* curses.panel (模块):                   curses panel --- curses 的 panel 栈扩展.
                                                             (line    6)
* curses.textpad (模块):                 curses textpad --- 用于 curses 程序的文本输入控件.
                                                             (line    6)
* Cursor (sqlite3 中的类):               Cursor 对象.        (line    6)
* cursor() (sqlite3.Connection 方法):    连接对象（Connection）.
                                                             (line   23)
* cursyncup() (curses.window 方法):      Window 对象.        (line  147)
* curs_set() (在 curses 模块中):         函数<3>.            (line   51)
* customize_compiler() (在 distutils.sysconfig 模块中): distutils sysconfig --- System configuration information.
                                                             (line   83)
* Cut:                                   帮助菜单（命令行和编辑器）.
                                                             (line   26)
* cwd() (ftplib.FTP 方法):               FTP 对象.           (line  182)
* cwd() (pathlib.Path 类方法):           方法<2>.            (line   15)
* cycle() (在 itertools 模块中):         Itertool函数.       (line  222)
* Cyclic Redundancy Check:               zlib --- 与 gzip 兼容的压缩.
                                                             (line   89)
* c_bool (ctypes 中的类):                基础数据类型<2>.    (line  179)
* C_BUILTIN() (在 imp 模块中):           imp --- Access the import internals.
                                                             (line  324)
* c_byte (ctypes 中的类):                基础数据类型<2>.    (line   36)
* c_char (ctypes 中的类):                基础数据类型<2>.    (line   41)
* c_char_p (ctypes 中的类):              基础数据类型<2>.    (line   46)
* c_contiguous (memoryview 属性):        内存视图.           (line  432)
* c_double (ctypes 中的类):              基础数据类型<2>.    (line   52)
* C_EXTENSION() (在 imp 模块中):         imp --- Access the import internals.
                                                             (line  312)
* c_float (ctypes 中的类):               基础数据类型<2>.    (line   62)
* c_int (ctypes 中的类):                 基础数据类型<2>.    (line   66)
* c_int16 (ctypes 中的类):               基础数据类型<2>.    (line   77)
* c_int32 (ctypes 中的类):               基础数据类型<2>.    (line   82)
* c_int64 (ctypes 中的类):               基础数据类型<2>.    (line   87)
* c_int8 (ctypes 中的类):                基础数据类型<2>.    (line   72)
* c_long (ctypes 中的类):                基础数据类型<2>.    (line   92)
* c_longdouble (ctypes 中的类):          基础数据类型<2>.    (line   56)
* c_longlong (ctypes 中的类):            基础数据类型<2>.    (line   97)
* c_short (ctypes 中的类):               基础数据类型<2>.    (line  102)
* c_size_t (ctypes 中的类):              基础数据类型<2>.    (line  107)
* c_ssize_t (ctypes 中的类):             基础数据类型<2>.    (line  111)
* c_ubyte (ctypes 中的类):               基础数据类型<2>.    (line  117)
* c_uint (ctypes 中的类):                基础数据类型<2>.    (line  122)
* c_uint16 (ctypes 中的类):              基础数据类型<2>.    (line  133)
* c_uint32 (ctypes 中的类):              基础数据类型<2>.    (line  138)
* c_uint64 (ctypes 中的类):              基础数据类型<2>.    (line  143)
* c_uint8 (ctypes 中的类):               基础数据类型<2>.    (line  128)
* c_ulong (ctypes 中的类):               基础数据类型<2>.    (line  148)
* c_ulonglong (ctypes 中的类):           基础数据类型<2>.    (line  153)
* c_ushort (ctypes 中的类):              基础数据类型<2>.    (line  158)
* c_void_p (ctypes 中的类):              基础数据类型<2>.    (line  163)
* c_wchar (ctypes 中的类):               基础数据类型<2>.    (line  168)
* c_wchar_p (ctypes 中的类):             基础数据类型<2>.    (line  174)
* daemon (multiprocessing.Process 属性): Process 和异常.     (line   73)
* daemon (threading.Thread 属性):        线程对象.           (line  154)
* dangling; else:                        复合语句.           (line   46)
* data:                                  对象、值与类型.     (line    6)
* data (collections.UserDict 属性):      UserDict 对象.      (line   19)
* data (collections.UserList 属性):      UserList 对象.      (line   22)
* data (collections.UserString 属性):    UserString 对象.    (line   20)
* Data (plistlib 中的类):                plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line  151)
* data (select.kevent 属性):             Kevent 对象.        (line  170)
* data (selectors.SelectorKey 属性):     类<3>.              (line   46)
* data (urllib.request.Request 属性):    Request 对象.       (line   36)
* data (xml.dom.Comment 属性):           注释对象.           (line    9)
* data (xml.dom.ProcessingInstruction 属性): ProcessingInstruction 对象.
                                                             (line   12)
* data (xml.dom.Text 属性):              Text 和 CDATASection 对象.
                                                             (line   12)
* data (xmlrpc.client.Binary 属性):      Binary 对象.        (line   12)
* data() (xml.etree.ElementTree.TreeBuilder 方法): TreeBuilder 对象.
                                                             (line   28)
* data; tabular:                         csv --- CSV 文件读写.
                                                             (line    8)
* data; type:                            标准类型层级结构.   (line    6)
* DatabaseError:                         异常<4>.            (line   14)
* databases:                             dbm dumb --- 便携式 DBM 实现.
                                                             (line    8)
* dataclass() (在 dataclasses 模块中):   模块级装饰器、类和函数.
                                                             (line    6)
* dataclasses (模块):                    dataclasses --- 数据类.
                                                             (line    6)
* DatagramHandler (logging.handlers 中的类): DatagramHandler.
                                                             (line    9)
* DatagramProtocol (asyncio 中的类):     基础协议.           (line   18)
* DatagramRequestHandler (socketserver 中的类): Request Handler Objects.
                                                             (line   42)
* DatagramTransport (asyncio 中的类):    传输层级.           (line   39)
* datagram_received() (asyncio.DatagramProtocol 方法): 数据报协议.
                                                             (line    9)
* DataHandler (urllib.request 中的类):   urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  347)
* data_open() (urllib.request.DataHandler 方法): DataHandler 对象.
                                                             (line    6)
* data_received() (asyncio.Protocol 方法): 流协议.           (line   13)
* date (datetime 中的类):                date 对象.          (line   12)
* date() (datetime.datetime 方法):       datetime 对象.      (line  356)
* date() (nntplib.NNTP 方法):            方法<3>.            (line  297)
* DateHeader (email.headerregistry 中的类): email headerregistry 自定义标头对象.
                                                             (line  110)
* datetime (datetime 中的类):            datetime 对象.      (line   15)
* datetime (email.headerregistry.DateHeader 属性): email headerregistry 自定义标头对象.
                                                             (line  118)
* DateTime (xmlrpc.client 中的类):       DateTime 对象.      (line    6)
* datetime (模块):                       datetime --- 基本的日期和时间类型.
                                                             (line    6)
* date_time (zipfile.ZipInfo 属性):      ZipInfo 对象.       (line   49)
* date_time_string() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  298)
* datum:                                 字典显示.           (line    6)
* day (datetime.date 属性):              date 对象.          (line  102)
* day (datetime.datetime 属性):          datetime 对象.      (line  250)
* Daylight Saving Time:                  time --- 时间的访问和转换.
                                                             (line   35)
* daylight() (在 time 模块中):           时区常量.           (line   12)
* day_abbr() (在 calendar 模块中):       calendar --- 日历相关函数.
                                                             (line  323)
* day_name() (在 calendar 模块中):       calendar --- 日历相关函数.
                                                             (line  319)
* DbfilenameShelf (shelve 中的类):       限制.               (line   53)
* dbm (模块):                            dbm --- Unix "数据库" 接口.
                                                             (line    6)
* dbm.dumb (模块):                       dbm dumb --- 便携式 DBM 实现.
                                                             (line    6)
* dbm.gnu (模块):                        dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line    6)
* dbm.ndbm (模块):                       dbm ndbm --- 基于 ndbm 的接口.
                                                             (line    6)
* dcgettext() (在 locale 模块中):        Access to message catalogs.
                                                             (line   10)
* deallocation, object:                  终结和内存释放.     (line    6)
* debug (imaplib.IMAP4 属性):            IMAP4 Objects.      (line  381)
* debug (pdb command):                   调试器命令.         (line  279)
* debug (shlex.shlex 属性):              shlex Objects.      (line  161)
* debug (zipfile.ZipFile 属性):          ZipFile 对象.       (line  264)
* debug() (logging.Logger 方法):         记录器对象.         (line   89)
* debug() (pipes.Template 方法):         模板对象.           (line   16)
* debug() (unittest.TestCase 方法):      测试用例.           (line  120)
* debug() (unittest.TestSuite 方法):     Grouping tests.     (line   48)
* debug() (在 doctest 模块中):           调试.               (line  124)
* debug() (在 logging 模块中):           模块级别函数.       (line   39)
* DEBUG() (在 re 模块中):                模块内容.           (line   48)
* debugger:                              调试菜单（仅 window 编辑器）.
                                                             (line   15)
* debugger <1>:                          sys --- 系统相关的参数和函数.
                                                             (line  630)
* debugger <2>:                          sys --- 系统相关的参数和函数.
                                                             (line 1113)
* debugger; configuration; file:         调试器命令.         (line   27)
* debugging:                             pdb --- Python的调试器.
                                                             (line    8)
* debugging; assertions:                 assert 语句.        (line    6)
* DebuggingServer (smtpd 中的类):        DebuggingServer 对象.
                                                             (line    6)
* debuglevel (http.client.HTTPResponse 属性): HTTPResponse 对象.
                                                             (line   59)
* DebugRunner (doctest 中的类):          调试.               (line  168)
* DEBUG_BYTECODE_SUFFIXES() (在 importlib.machinery 模块中): importlib machinery -- Importers and path hooks.
                                                             (line   20)
* DEBUG_COLLECTABLE() (在 gc 模块中):    gc --- 垃圾回收器接口.
                                                             (line  227)
* DEBUG_LEAK() (在 gc 模块中):           gc --- 垃圾回收器接口.
                                                             (line  244)
* debug_print() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  508)
* DEBUG_SAVEALL() (在 gc 模块中):        gc --- 垃圾回收器接口.
                                                             (line  239)
* debug_src() (在 doctest 模块中):       调试.               (line  147)
* DEBUG_STATS() (在 gc 模块中):          gc --- 垃圾回收器接口.
                                                             (line  222)
* DEBUG_UNCOLLECTABLE() (在 gc 模块中):  gc --- 垃圾回收器接口.
                                                             (line  231)
* Decimal (decimal 中的类):              Decimal 对象.       (line    6)
* decimal (模块):                        decimal --- 十进制定点和浮点运算.
                                                             (line    6)
* decimal literal:                       数字字面值.         (line    6)
* decimal() (在 unicodedata 模块中):     unicodedata --- Unicode 数据库.
                                                             (line   26)
* DecimalException (decimal 中的类):     信号.               (line   24)
* decode (codecs.CodecInfo 属性):        codecs --- 编解码器注册和相关基类.
                                                             (line   60)
* decode() (bytearray 方法):             bytes 和 bytearray 操作.
                                                             (line   41)
* decode() (bytes 方法):                 bytes 和 bytearray 操作.
                                                             (line   41)
* decode() (codecs.Codec 方法):          无状态的编码和解码. (line   24)
* decode() (codecs.IncrementalDecoder 方法): IncrementalDecoder 对象.
                                                             (line   24)
* decode() (json.JSONDecoder 方法):      编码器和解码器.     (line   78)
* decode() (xmlrpc.client.Binary 方法):  Binary 对象.        (line   20)
* decode() (xmlrpc.client.DateTime 方法): DateTime 对象.     (line   13)
* decode() (在 base64 模块中):           base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  180)
* decode() (在 codecs 模块中):           codecs --- 编解码器注册和相关基类.
                                                             (line   28)
* decode() (在 quopri 模块中):           quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   17)
* decode() (在 uu 模块中):               uu --- 对 uuencode 文件进行编码与解码.
                                                             (line   31)
* decodebytes() (在 base64 模块中):      base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  186)
* DecodedGenerator (email.generator 中的类): email generator 生成 MIME 文档.
                                                             (line  195)
* decodestring() (在 base64 模块中):     base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  193)
* decodestring() (在 quopri 模块中):     quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   35)
* decode_header() (在 email.header 模块中): email header 国际化标头.
                                                             (line  144)
* decode_header() (在 nntplib 模块中):   工具函数<2>.        (line    8)
* decode_params() (在 email.utils 模块中): email utils 其他工具.
                                                             (line  173)
* decode_rfc2231() (在 email.utils 模块中): email utils 其他工具.
                                                             (line  148)
* decode_source() (在 importlib.util 模块中): importlib util -- Utility code for importers.
                                                             (line   72)
* decomposition() (在 unicodedata 模块中): unicodedata --- Unicode 数据库.
                                                             (line   64)
* decompress() (bz2.BZ2Decompressor 方法): 增量压缩和解压.   (line   38)
* decompress() (lzma.LZMADecompressor 方法): 在内存中压缩和解压缩数据.
                                                             (line  104)
* decompress() (zlib.Decompress 方法):   zlib --- 与 gzip 兼容的压缩.
                                                             (line  196)
* decompress() (在 bz2 模块中):          一次性压缩或解压缩. (line   15)
* decompress() (在 gzip 模块中):         gzip --- 对 gzip 格式的支持.
                                                             (line  152)
* decompress() (在 lzma 模块中):         在内存中压缩和解压缩数据.
                                                             (line  158)
* decompress() (在 zlib 模块中):         zlib --- 与 gzip 兼容的压缩.
                                                             (line   97)
* decompressobj() (在 zlib 模块中):      zlib --- 与 gzip 兼容的压缩.
                                                             (line  130)
* decorator – 装饰器:                    术语对照表.         (line  244)
* DEDENT token:                          缩进.               (line   25)
* DEDENT token <1>:                      复合语句.           (line   46)
* dedent() (在 textwrap 模块中):         textwrap --- 文本自动换行与填充.
                                                             (line   59)
* DEDENT() (在 token 模块中):            token --- 与Python解析树一起使用的常量.
                                                             (line   48)
* deepcopy() (在 copy 模块中):           copy --- 浅层 shallow 和深层 deep 复制操作.
                                                             (line   21)
* default (inspect.Parameter 属性):      Introspecting callables with the Signature object.
                                                             (line  167)
* default (optparse.Option 属性):        Option attributes.  (line   36)
* default() (cmd.Cmd 方法):              Cmd 对象.           (line   57)
* default() (json.JSONEncoder 方法):     编码器和解码器.     (line  175)
* default() (在 email.policy 模块中):    email policy 策略对象.
                                                             (line  392)
* DEFAULT() (在 unittest.mock 模块中):   DEFAULT.            (line    6)
* default; parameter; value:             函数定义.           (line   46)
* DefaultContext (decimal 中的类):       上下文对象.         (line   61)
* DefaultCookiePolicy (http.cookiejar 中的类): http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   64)
* defaultdict (collections 中的类):      defaultdict 对象.   (line    6)
* DefaultDict (typing 中的类):           类 函数和修饰器.    (line  339)
* DefaultEventLoopPolicy (asyncio 中的类): 策略对象.         (line   50)
* DefaultHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  259)
* DefaultHandlerExpand() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  264)
* defaults() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line   65)
* DefaultSelector (selectors 中的类):    类<3>.              (line  140)
* defaultTestLoader() (在 unittest 模块中): Loading and running tests.
                                                             (line  429)
* defaultTestResult() (unittest.TestCase 方法): 测试用例.    (line  710)
* DEFAULT_BUFFER_SIZE() (在 io 模块中):  高阶模块接口.       (line    6)
* default_bufsize() (在 xml.dom.pulldom 模块中): xml dom pulldom --- 支持构建部分 DOM 树.
                                                             (line   92)
* default_exception_handler() (asyncio.loop 方法): 错误处理API.
                                                             (line   24)
* default_factory (collections.defaultdict 属性): defaultdict 对象.
                                                             (line   42)
* DEFAULT_FORMAT() (在 tarfile 模块中):  tarfile --- 读写tar归档文件.
                                                             (line  210)
* DEFAULT_IGNORES() (在 filecmp 模块中): dircmp 类.          (line   95)
* default_open() (urllib.request.BaseHandler 方法): BaseHandler 对象.
                                                             (line   28)
* DEFAULT_PROTOCOL() (在 pickle 模块中): 模块接口.           (line   19)
* default_timer() (在 timeit 模块中):    Python 接口.        (line   29)
* defects (email.headerregistry.BaseHeader 属性): email headerregistry 自定义标头对象.
                                                             (line   43)
* defects (email.message.EmailMessage 属性): email message 表示一封电子邮件信息.
                                                             (line  598)
* defects (email.message.Message 属性):  email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  608)
* define_macro() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  160)
* defpath() (在 os 模块中):              其他系统信息.       (line  100)
* DefragResult (urllib.parse 中的类):    结构化解析结果.     (line   40)
* DefragResultBytes (urllib.parse 中的类): 结构化解析结果.   (line   64)
* def_prog_mode() (在 curses 模块中):    函数<3>.            (line   58)
* def_shell_mode() (在 curses 模块中):   函数<3>.            (line   64)
* degrees() (在 math 模块中):            角度转换.           (line    6)
* degrees() (在 turtle 模块中):          度量单位设置.       (line    6)
* delattr() (內置函数):                  内置函数.           (line  308)
* delay() (在 turtle 模块中):            动画控制.           (line    6)
* delayload (http.cookiejar.FileCookieJar 属性): CookieJar 和 FileCookieJar 对象.
                                                             (line  158)
* delay_output() (在 curses 模块中):     函数<3>.            (line   70)
* delch() (curses.window 方法):          Window 对象.        (line  151)
* dele() (poplib.POP3 方法):             POP3 对象.          (line   61)
* delete() (ftplib.FTP 方法):            FTP 对象.           (line  176)
* delete() (imaplib.IMAP4 方法):         IMAP4 Objects.      (line   76)
* delete() (tkinter.ttk.Treeview 方法):  ttk Treeview.       (line   78)
* deleteacl() (imaplib.IMAP4 方法):      IMAP4 Objects.      (line   80)
* deletefilehandler() (tkinter.Widget.tk 方法): File Handlers.
                                                             (line   37)
* DeleteKey() (在 winreg 模块中):        函数<11>.           (line   93)
* DeleteKeyEx() (在 winreg 模块中):      函数<11>.           (line  113)
* deleteln() (curses.window 方法):       Window 对象.        (line  155)
* deleteMe() (bdb.Breakpoint 方法):      bdb --- Debugger framework.
                                                             (line   41)
* DeleteValue() (在 winreg 模块中):      函数<11>.           (line  149)
* DELETE_ATTR (opcode):                  Python字节码说明.   (line  473)
* DELETE_DEREF (opcode):                 Python字节码说明.   (line  683)
* DELETE_FAST (opcode):                  Python字节码说明.   (line  656)
* DELETE_GLOBAL (opcode):                Python字节码说明.   (line  481)
* DELETE_NAME (opcode):                  Python字节码说明.   (line  450)
* DELETE_SUBSCR (opcode):                Python字节码说明.   (line  245)
* deletion; target:                      del 语句<2>.        (line    6)
* deletion; target; list:                del 语句<2>.        (line    6)
* delimiter (csv.Dialect 属性):          变种与格式参数.     (line   16)
* delimiters:                            分隔符.             (line    6)
* delitem() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line  172)
* deliver_challenge() (在 multiprocessing.connection 模块中): 监听器及客户端.
                                                             (line   14)
* delocalize() (在 locale 模块中):       locale --- 国际化服务.
                                                             (line  421)
* del_param() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  318)
* del_param() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  452)
* demo_app() (在 wsgiref.simple_server 模块中): wsgiref simple_server -- a simple WSGI HTTP server.
                                                             (line   36)
* denominator (fractions.Fraction 属性): fractions --- 分数. (line   83)
* denominator (numbers.Rational 属性):   数字的层次.         (line   49)
* DeprecationWarning:                    警告.               (line   16)
* deque (collections 中的类):            deque 对象.         (line    6)
* Deque (typing 中的类):                 类 函数和修饰器.    (line  232)
* dequeue() (logging.handlers.QueueListener 方法): QueueListener.
                                                             (line   38)
* derwin() (curses.window 方法):         Window 对象.        (line  159)
* DER_cert_to_PEM_cert() (在 ssl 模块中): 证书处理.          (line   79)
* descrgetfunc (C 类型):                 Slot Type typedefs. (line   78)
* description (inspect.Parameter.kind 属性): Introspecting callables with the Signature object.
                                                             (line  232)
* description (sqlite3.Cursor 属性):     Cursor 对象.        (line  198)
* description() (nntplib.NNTP 方法):     方法<3>.            (line  148)
* descriptions() (nntplib.NNTP 方法):    方法<3>.            (line  134)
* descriptor – 描述器:                   术语对照表.         (line  263)
* descrsetfunc (C 类型):                 Slot Type typedefs. (line   83)
* dest (optparse.Option 属性):           Option attributes.  (line   27)
* destructor:                            基本定制.           (line   46)
* destructor <1>:                        赋值语句.           (line   59)
* destructor (C 类型):                   Slot Type typedefs. (line   24)
* detach() (io.BufferedIOBase 方法):     I/O 基类.           (line  217)
* detach() (io.TextIOBase 方法):         文本 I/O<2>.        (line   34)
* detach() (socket.socket 方法):         套接字对象.         (line   80)
* detach() (tkinter.ttk.Treeview 方法):  ttk Treeview.       (line   84)
* detach() (weakref.finalize 方法):      weakref --- 弱引用. (line  203)
* Detach() (winreg.PyHKEY 方法):         Registry Handle Objects.
                                                             (line   40)
* DETACHED_PROCESS() (在 subprocess 模块中): Windows 常数.   (line   97)
* detect_api_mismatch() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  929)
* detect_encoding() (在 tokenize 模块中): 对输入进行解析标记.
                                                             (line   76)
* detect_language() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  196)
* deterministic profiling:               profile分析器简介.  (line    6)
* device_encoding() (在 os 模块中):      文件描述符操作.     (line   58)
* devnull() (在 os 模块中):              其他系统信息.       (line  113)
* DEVNULL() (在 subprocess 模块中):      使用 subprocess 模块.
                                                             (line  115)
* devpoll() (在 select 模块中):          select --- 等待 I/O 完成.
                                                             (line   28)
* DevpollSelector (selectors 中的类):    类<3>.              (line  162)
* dgettext() (在 gettext 模块中):        GNU gettext API.    (line   42)
* dgettext() (在 locale 模块中):         Access to message catalogs.
                                                             (line    8)
* Dialect (csv 中的类):                  模块内容<3>.        (line  153)
* dialect (csv.csvreader 属性):          Reader 对象.        (line   18)
* dialect (csv.csvwriter 属性):          Writer 对象.        (line   27)
* Dialog (msilib 中的类):                GUI classes.        (line   40)
* dict (2to3 fixer):                     修复器.             (line   68)
* Dict (typing 中的类):                  类 函数和修饰器.    (line  329)
* dict (內置类):                         映射类型 --- dict.  (line   21)
* dict() (multiprocessing.managers.SyncManager 方法): 管理器.
                                                             (line  179)
* dictConfig() (在 logging.config 模块中): 配置函数.         (line   11)
* dictionary – 字典:                     术语对照表.         (line  275)
* dictionary comprehension – 字典推导式: 术语对照表.         (line  281)
* dictionary view – 字典视图:            术语对照表.         (line  288)
* dictionary; comprehensions:            字典显示.           (line    6)
* dictionary; display:                   字典显示.           (line    6)
* DictReader (csv 中的类):               模块内容<3>.        (line   88)
* DictWriter (csv 中的类):               模块内容<3>.        (line  124)
* Differ (difflib 中的类):               difflib --- 计算差异的辅助工具.
                                                             (line   39)
* difference() (frozenset 方法):         集合类型 --- set frozenset.
                                                             (line  100)
* difference_update() (frozenset 方法):  集合类型 --- set frozenset.
                                                             (line  163)
* difflib (模块):                        difflib --- 计算差异的辅助工具.
                                                             (line    6)
* diff_bytes() (在 difflib 模块中):      difflib --- 计算差异的辅助工具.
                                                             (line  294)
* diff_files (filecmp.dircmp 属性):      dircmp 类.          (line   81)
* digest() (hashlib.hash 方法):          哈希算法.           (line  114)
* digest() (hashlib.shake 方法):         SHAKE 可变长度摘要. (line   10)
* digest() (hmac.HMAC 方法):             hmac --- 基于密钥的消息验证.
                                                             (line   50)
* digest() (在 hmac 模块中):             hmac --- 基于密钥的消息验证.
                                                             (line   28)
* digest_size (hmac.HMAC 属性):          hmac --- 基于密钥的消息验证.
                                                             (line   77)
* digit() (在 unicodedata 模块中):       unicodedata --- Unicode 数据库.
                                                             (line   31)
* digits() (在 string 模块中):           字符串常量.         (line   23)
* dir() (ftplib.FTP 方法):               FTP 对象.           (line  161)
* dir() (內置函数):                      内置函数.           (line  326)
* dircmp (filecmp 中的类):               dircmp 类.          (line    6)
* directory (http.server.SimpleHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line  344)
* Directory (msilib 中的类):             Directory Objects.  (line    6)
* directory; changing:                   文件和目录.         (line   99)
* directory; creating:                   文件和目录.         (line  408)
* directory; deleting:                   目录和文件操作.     (line  215)
* directory; deleting <1>:               文件和目录.         (line  570)
* directory; traversal:                  文件和目录.         (line 1303)
* directory; traversal <1>:              文件和目录.         (line 1381)
* directory; walking:                    文件和目录.         (line 1303)
* directory; walking <1>:                文件和目录.         (line 1381)
* directory_created() (內置函数):        The Postinstallation script.
                                                             (line   23)
* DirEntry (os 中的类):                  文件和目录.         (line  718)
* DirList (tkinter.tix 中的类):          File Selectors.     (line    6)
* dirname() (在 os.path 模块中):         os path --- 常用路径操作.
                                                             (line   92)
* DirSelectBox (tkinter.tix 中的类):     File Selectors.     (line   26)
* DirSelectDialog (tkinter.tix 中的类):  File Selectors.     (line   20)
* DirsOnSysPath (test.support 中的类):   test support --- Utilities for the Python test suite.
                                                             (line 1068)
* DirTree (tkinter.tix 中的类):          File Selectors.     (line   13)
* dis (模块):                            dis --- Python 字节码反汇编器.
                                                             (line    6)
* dis() (dis.Bytecode 方法):             字节码分析.         (line   41)
* dis() (在 dis 模块中):                 分析函数.           (line   33)
* dis() (在 pickletools 模块中):         编程接口<2>.        (line    6)
* disable (pdb command):                 调试器命令.         (line   81)
* disable() (bdb.Breakpoint 方法):       bdb --- Debugger framework.
                                                             (line   51)
* disable() (profile.Profile 方法):      profile 和 cProfile 模块参考.
                                                             (line   81)
* disable() (在 faulthandler 模块中):    Fault handler state.
                                                             (line   22)
* disable() (在 gc 模块中):              gc --- 垃圾回收器接口.
                                                             (line   22)
* disable() (在 logging 模块中):         模块级别函数.       (line  139)
* DisableReflectionKey() (在 winreg 模块中): 函数<11>.       (line  465)
* disable_faulthandler() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  469)
* disable_gc() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  481)
* disable_interspersed_args() (optparse.OptionParser 方法): Querying and manipulating your option parser.
                                                             (line   10)
* disassemble() (在 dis 模块中):         分析函数.           (line   66)
* discard (http.cookiejar.Cookie 属性):  Cookie 对象<2>.     (line   54)
* discard() (frozenset 方法):            集合类型 --- set frozenset.
                                                             (line  184)
* discard() (mailbox.Mailbox 方法):      Mailbox 对象.       (line   58)
* discard() (mailbox.MH 方法):           MH.                 (line   68)
* discard_buffers() (asynchat.async_chat 方法): asynchat --- 异步 socket 指令/响应 处理器.
                                                             (line   71)
* disco() (在 dis 模块中):               分析函数.           (line   66)
* discover() (unittest.TestLoader 方法): Loading and running tests.
                                                             (line  117)
* disk_usage() (在 shutil 模块中):       目录和文件操作.     (line  284)
* dispatcher (asyncore 中的类):          asyncore --- 异步socket处理器.
                                                             (line   53)
* dispatcher_with_send (asyncore 中的类): asyncore --- 异步socket处理器.
                                                             (line  202)
* dispatch_call() (bdb.Bdb 方法):        bdb --- Debugger framework.
                                                             (line  156)
* dispatch_exception() (bdb.Bdb 方法):   bdb --- Debugger framework.
                                                             (line  176)
* dispatch_line() (bdb.Bdb 方法):        bdb --- Debugger framework.
                                                             (line  146)
* dispatch_return() (bdb.Bdb 方法):      bdb --- Debugger framework.
                                                             (line  166)
* dispatch_table (pickle.Pickler 属性):  模块接口.           (line  158)
* display (pdb command):                 调试器命令.         (line  215)
* displayhook() (在 sys 模块中):         sys --- 系统相关的参数和函数.
                                                             (line  201)
* display_name (email.headerregistry.Address 属性): email headerregistry 自定义标头对象.
                                                             (line  363)
* display_name (email.headerregistry.Group 属性): email headerregistry 自定义标头对象.
                                                             (line  400)
* dist() (在 math 模块中):               三角函数.           (line   30)
* distance() (在 turtle 模块中):         获取海龟的状态.     (line   64)
* distb() (在 dis 模块中):               分析函数.           (line   56)
* Distribution (distutils.core 中的类):  distutils core --- 分发包功能的核心.
                                                             (line  278)
* distutils (模块):                      distutils --- 构建和安装 Python 模块.
                                                             (line    6)
* distutils.archive_util (模块):         distutils archive_util --- Archiving utilities.
                                                             (line    6)
* distutils.bcppcompiler (模块):         distutils bcppcompiler --- Borland Compiler.
                                                             (line    6)
* distutils.ccompiler (模块):            distutils ccompiler --- CCompiler基类.
                                                             (line    6)
* distutils.cmd (模块):                  distutils cmd --- Abstract base class for Distutils commands.
                                                             (line    6)
* distutils.command (模块):              distutils command --- Individual Distutils commands.
                                                             (line    5)
* distutils.command.bdist (模块):        distutils command bdist --- Build a binary installer.
                                                             (line    5)
* distutils.command.bdist_dumb (模块):   distutils command bdist_dumb --- Build a "dumb" installer.
                                                             (line    5)
* distutils.command.bdist_msi (模块):    distutils command bdist_msi --- Build a Microsoft Installer binary package.
                                                             (line    6)
* distutils.command.bdist_packager (模块): distutils command bdist_packager --- Abstract base class for packagers.
                                                             (line    5)
* distutils.command.bdist_rpm (模块):    distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM.
                                                             (line    5)
* distutils.command.bdist_wininst (模块): distutils command bdist_wininst --- Build a Windows installer.
                                                             (line    6)
* distutils.command.build (模块):        distutils command build --- Build all files of a package.
                                                             (line    5)
* distutils.command.build_clib (模块):   distutils command build_clib --- Build any C libraries in a package.
                                                             (line    5)
* distutils.command.build_ext (模块):    distutils command build_ext --- Build any extensions in a package.
                                                             (line    5)
* distutils.command.build_py (模块):     distutils command build_py --- Build the py/ pyc files of a package.
                                                             (line    6)
* distutils.command.build_scripts (模块): distutils command build_scripts --- Build the scripts of a package.
                                                             (line    5)
* distutils.command.check (模块):        distutils command check --- Check the meta-data of a package.
                                                             (line    6)
* distutils.command.clean (模块):        distutils command clean --- Clean a package build area.
                                                             (line    6)
* distutils.command.config (模块):       distutils command config --- Perform package configuration.
                                                             (line    5)
* distutils.command.install (模块):      distutils command install --- Install a package.
                                                             (line    5)
* distutils.command.install_data (模块): distutils command install_data --- Install data files from a package.
                                                             (line    5)
* distutils.command.install_headers (模块): distutils command install_headers --- Install C/C++ header files from a package.
                                                             (line    5)
* distutils.command.install_lib (模块):  distutils command install_lib --- Install library files from a package.
                                                             (line    5)
* distutils.command.install_scripts (模块): distutils command install_scripts --- Install script files from a package.
                                                             (line    5)
* distutils.command.register (模块):     distutils command register --- Register a module with the Python Package Index.
                                                             (line    6)
* distutils.command.sdist (模块):        distutils command sdist --- Build a source distribution.
                                                             (line    5)
* distutils.core (模块):                 distutils core --- 分发包功能的核心.
                                                             (line    6)
* distutils.cygwinccompiler (模块):      distutils cygwincompiler --- Cygwin Compiler.
                                                             (line    6)
* distutils.debug (模块):                distutils debug --- Distutils debug mode.
                                                             (line    6)
* distutils.dep_util (模块):             distutils dep_util --- Dependency checking.
                                                             (line    6)
* distutils.dir_util (模块):             distutils dir_util --- Directory tree operations.
                                                             (line    6)
* distutils.dist (模块):                 distutils dist --- The Distribution class.
                                                             (line    6)
* distutils.errors (模块):               distutils errors --- Distutils exceptions.
                                                             (line    6)
* distutils.extension (模块):            distutils extension --- The Extension class.
                                                             (line    6)
* distutils.fancy_getopt (模块):         distutils fancy_getopt --- Wrapper around the standard getopt module.
                                                             (line    6)
* distutils.filelist (模块):             distutils filelist --- The FileList class.
                                                             (line    6)
* distutils.file_util (模块):            distutils file_util --- Single file operations.
                                                             (line    6)
* distutils.log (模块):                  distutils log --- Simple PEP 282-style logging.
                                                             (line    5)
* distutils.msvccompiler (模块):         distutils msvccompiler --- Microsoft Compiler.
                                                             (line    6)
* distutils.spawn (模块):                distutils spawn --- Spawn a sub-process.
                                                             (line    6)
* distutils.sysconfig (模块):            distutils sysconfig --- System configuration information.
                                                             (line    6)
* distutils.text_file (模块):            distutils text_file --- The TextFile class.
                                                             (line    6)
* distutils.unixccompiler (模块):        distutils unixccompiler --- Unix C Compiler.
                                                             (line    6)
* distutils.util (模块):                 distutils util --- Miscellaneous other utility functions.
                                                             (line    6)
* distutils.version (模块):              distutils version --- Version number classes.
                                                             (line    5)
* DISTUTILS_DEBUG:                       Debugging the setup script.
                                                             (line   19)
* divide() (decimal.Context 方法):       上下文对象.         (line  236)
* divide_int() (decimal.Context 方法):   上下文对象.         (line  240)
* division:                              二元算术运算符.     (line   25)
* DivisionByZero (decimal 中的类):       信号.               (line   28)
* divmod() (decimal.Context 方法):       上下文对象.         (line  244)
* divmod() (內置函数):                   内置函数.           (line  373)
* DllCanUnloadNow() (在 ctypes 模块中):  工具函数.           (line   65)
* DllGetClassObject() (在 ctypes 模块中): 工具函数.          (line   70)
* dllhandle() (在 sys 模块中):           sys --- 系统相关的参数和函数.
                                                             (line  195)
* dngettext() (在 gettext 模块中):       GNU gettext API.    (line   57)
* dnpgettext() (在 gettext 模块中):      GNU gettext API.    (line   68)
* doc (json.JSONDecodeError 属性):       异常<13>.           (line   14)
* DocCGIXMLRPCRequestHandler (xmlrpc.server 中的类): Documenting XMLRPC server.
                                                             (line   22)
* DocFileSuite() (在 doctest 模块中):    Unittest API.       (line   24)
* doClassCleanups() (unittest.TestCase 类方法): 测试用例.    (line  785)
* doCleanups() (unittest.TestCase 方法): 测试用例.           (line  753)
* docmd() (smtplib.SMTP 方法):           SMTP Objects.       (line   17)
* docstring:                             类定义.             (line    6)
* docstring (doctest.DocTest 属性):      DocTest 对象.       (line   49)
* docstring – 文档字符串:                术语对照表.         (line  296)
* docstrings:                            定义函数.           (line   20)
* docstrings <1>:                        文档字符串.         (line    6)
* DocTest (doctest 中的类):              DocTest 对象.       (line    6)
* doctest (模块):                        doctest --- 测试交互性的Python示例.
                                                             (line    6)
* DocTestFailure:                        调试.               (line  185)
* DocTestFinder (doctest 中的类):        DocTestFinder 对象. (line    6)
* DocTestParser (doctest 中的类):        DocTestParser 对象. (line    6)
* DocTestRunner (doctest 中的类):        DocTestRunner 对象. (line    6)
* DocTestSuite() (在 doctest 模块中):    Unittest API.       (line   99)
* doctype() (xml.etree.ElementTree.TreeBuilder 方法): TreeBuilder 对象.
                                                             (line   58)
* documentation string:                  标准类型层级结构.   (line  527)
* documentation strings:                 定义函数.           (line   20)
* documentation strings <1>:             文档字符串.         (line    6)
* documentation; generation:             pydoc --- 文档生成器和在线帮助系统.
                                                             (line    8)
* documentation; online:                 pydoc --- 文档生成器和在线帮助系统.
                                                             (line    8)
* documentElement (xml.dom.Document 属性): 文档对象.         (line    9)
* DocXMLRPCRequestHandler (xmlrpc.server 中的类): Documenting XMLRPC server.
                                                             (line   27)
* DocXMLRPCServer (xmlrpc.server 中的类): Documenting XMLRPC server.
                                                             (line   11)
* doc_header (cmd.Cmd 属性):             Cmd 对象.           (line  118)
* domain (email.headerregistry.Address 属性): email headerregistry 自定义标头对象.
                                                             (line  372)
* domain (tracemalloc.DomainFilter 属性): 域过滤器.          (line   20)
* domain (tracemalloc.Filter 属性):      过滤器.             (line   30)
* domain (tracemalloc.Trace 属性):       跟踪.               (line   15)
* DomainFilter (tracemalloc 中的类):     域过滤器.           (line    6)
* DomainLiberal (http.cookiejar.DefaultCookiePolicy 属性): DefaultCookiePolicy 对象.
                                                             (line  156)
* DomainRFC2965Match (http.cookiejar.DefaultCookiePolicy 属性): DefaultCookiePolicy 对象.
                                                             (line  149)
* DomainStrict (http.cookiejar.DefaultCookiePolicy 属性): DefaultCookiePolicy 对象.
                                                             (line  161)
* DomainStrictNoDots (http.cookiejar.DefaultCookiePolicy 属性): DefaultCookiePolicy 对象.
                                                             (line  136)
* DomainStrictNonDomain (http.cookiejar.DefaultCookiePolicy 属性): DefaultCookiePolicy 对象.
                                                             (line  142)
* domain_initial_dot (http.cookiejar.Cookie 属性): Cookie 对象<2>.
                                                             (line   86)
* domain_return_ok() (http.cookiejar.CookiePolicy 方法): CookiePolicy 对象.
                                                             (line   27)
* domain_specified (http.cookiejar.Cookie 属性): Cookie 对象<2>.
                                                             (line   82)
* DOMEventStream (xml.dom.pulldom 中的类): DOMEventStream 对象.
                                                             (line    6)
* DOMException:                          异常<16>.           (line   14)
* doModuleCleanups() (在 unittest 模块中): setUpModule and tearDownModule.
                                                             (line   35)
* DomstringSizeErr:                      异常<16>.           (line   18)
* done() (asyncio.Future 方法):          Future 对象<2>.     (line   52)
* done() (asyncio.Task 方法):            Task 对象.          (line  101)
* done() (concurrent.futures.Future 方法): Future 对象.      (line   28)
* done() (xdrlib.Unpacker 方法):         Unpacker 对象.      (line   25)
* done() (在 turtle 模块中):             使用屏幕事件.       (line   98)
* DONT_ACCEPT_BLANKLINE() (在 doctest 模块中): Option Flags. (line   30)
* DONT_ACCEPT_TRUE_FOR_1() (在 doctest 模块中): Option Flags.
                                                             (line   18)
* dont_write_bytecode() (在 sys 模块中): sys --- 系统相关的参数和函数.
                                                             (line  236)
* doRollover() (logging.handlers.RotatingFileHandler 方法): RotatingFileHandler.
                                                             (line   34)
* doRollover() (logging.handlers.TimedRotatingFileHandler 方法): TimedRotatingFileHandler.
                                                             (line   82)
* DOT() (在 token 模块中):               token --- 与Python解析树一起使用的常量.
                                                             (line  114)
* dot() (在 turtle 模块中):              海龟动作.           (line  205)
* DOTALL() (在 re 模块中):               模块内容.           (line   89)
* doublequote (csv.Dialect 属性):        变种与格式参数.     (line   20)
* DOUBLESLASH() (在 token 模块中):       token --- 与Python解析树一起使用的常量.
                                                             (line  210)
* DOUBLESLASHEQUAL() (在 token 模块中):  token --- 与Python解析树一起使用的常量.
                                                             (line  214)
* DOUBLESTAR() (在 token 模块中):        token --- 与Python解析树一起使用的常量.
                                                             (line  162)
* DOUBLESTAREQUAL() (在 token 模块中):   token --- 与Python解析树一起使用的常量.
                                                             (line  206)
* doupdate() (在 curses 模块中):         函数<3>.            (line   74)
* down (pdb command):                    调试器命令.         (line   46)
* down() (在 turtle 模块中):             绘图状态.           (line    6)
* do_clear() (bdb.Bdb 方法):             bdb --- Debugger framework.
                                                             (line  233)
* do_command() (curses.textpad.Textbox 方法): 文本框对象.    (line   25)
* do_GET() (http.server.SimpleHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  358)
* do_handshake() (ssl.SSLSocket 方法):   SSL 套接字.         (line  107)
* do_HEAD() (http.server.SimpleHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  351)
* do_POST() (http.server.CGIHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  468)
* dpgettext() (在 gettext 模块中):       GNU gettext API.    (line   64)
* drain() (asyncio.StreamWriter 方法):   StreamWriter.       (line   61)
* dropwhile() (在 itertools 模块中):     Itertool函数.       (line  239)
* drop_whitespace (textwrap.TextWrapper 属性): textwrap --- 文本自动换行与填充.
                                                             (line  171)
* dst() (datetime.datetime 方法):        datetime 对象.      (line  436)
* dst() (datetime.time 方法):            time 对象.          (line  209)
* dst() (datetime.timezone 方法):        timezone 对象.      (line   46)
* dst() (datetime.tzinfo 方法):          tzinfo 对象.        (line   55)
* DTDHandler (xml.sax.handler 中的类):   xml sax handler --- SAX 处理程序的基类.
                                                             (line   20)
* duck-typing – 鸭子类型:                术语对照表.         (line  302)
* DumbWriter (formatter 中的类):         Writer Implementations.
                                                             (line   22)
* dummy_threading (模块):                dummy_threading --- 可直接替代 threading 模块。.
                                                             (line    6)
* dump() (pickle.Pickler 方法):          模块接口.           (line  138)
* dump() (tracemalloc.Snapshot 方法):    快照.               (line   29)
* dump() (在 ast 模块中):                ast 中的辅助函数.   (line  190)
* dump() (在 json 模块中):               基本使用.           (line    6)
* dump() (在 marshal 模块中):            marshal --- 内部 Python 对象序列化.
                                                             (line   36)
* dump() (在 pickle 模块中):             模块接口.           (line   31)
* dump() (在 plistlib 模块中):           plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line   77)
* dump() (在 xml.etree.ElementTree 模块中): 函数<6>.         (line   75)
* dumps() (在 json 模块中):              基本使用.           (line   68)
* dumps() (在 marshal 模块中):           marshal --- 内部 Python 对象序列化.
                                                             (line   58)
* dumps() (在 pickle 模块中):            模块接口.           (line   42)
* dumps() (在 plistlib 模块中):          plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line  102)
* dumps() (在 xmlrpc.client 模块中):     Convenience Functions.
                                                             (line    6)
* dump_stats() (profile.Profile 方法):   profile 和 cProfile 模块参考.
                                                             (line   94)
* dump_stats() (pstats.Stats 方法):      Stats 类.           (line   59)
* dump_traceback() (在 faulthandler 模块中): Dumping the traceback.
                                                             (line    6)
* dump_traceback_later() (在 faulthandler 模块中): Dumping the tracebacks after a timeout.
                                                             (line    6)
* dup() (socket.socket 方法):            套接字对象.         (line   87)
* dup() (在 os 模块中):                  文件描述符操作.     (line   63)
* dup2() (在 os 模块中):                 文件描述符操作.     (line   73)
* DuplicateOptionError:                  异常<5>.            (line   22)
* DuplicateSectionError:                 异常<5>.            (line   14)
* DUP_TOP (opcode):                      Python字节码说明.   (line   75)
* DUP_TOP_TWO (opcode):                  Python字节码说明.   (line   81)
* dwFlags (subprocess.STARTUPINFO 属性): Windows Popen 助手. (line   17)
* DynamicClassAttribute() (在 types 模块中): 附加工具类和函数.
                                                             (line   36)
* D_FMT() (在 locale 模块中):            locale --- 国际化服务.
                                                             (line  177)
* D_T_FMT() (在 locale 模块中):          locale --- 国际化服务.
                                                             (line  171)
* e() (在 cmath 模块中):                 常量<3>.            (line   10)
* e() (在 math 模块中):                  常量<2>.            (line   10)
* E2BIG() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line   50)
* e; in numeric literal:                 整型数字面值.       (line   35)
* EACCES() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line   74)
* EADDRINUSE() (在 errno 模块中):        errno --- 标准 errno 系统符号.
                                                             (line  414)
* EADDRNOTAVAIL() (在 errno 模块中):     errno --- 标准 errno 系统符号.
                                                             (line  418)
* EADV() (在 errno 模块中):              errno --- 标准 errno 系统符号.
                                                             (line  294)
* EAFNOSUPPORT() (在 errno 模块中):      errno --- 标准 errno 系统符号.
                                                             (line  410)
* EAFP:                                  术语对照表.         (line  312)
* EAGAIN() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line   66)
* EALREADY() (在 errno 模块中):          errno --- 标准 errno 系统符号.
                                                             (line  478)
* east_asian_width() (在 unicodedata 模块中): unicodedata --- Unicode 数据库.
                                                             (line   55)
* EBADE() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line  230)
* EBADF() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line   58)
* EBADFD() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  330)
* EBADMSG() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  318)
* EBADR() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line  234)
* EBADRQC() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  246)
* EBADSLT() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  250)
* EBFONT() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  258)
* EBUSY() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line   86)
* ECHILD() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line   62)
* echo() (在 curses 模块中):             函数<3>.            (line   86)
* echochar() (curses.window 方法):       Window 对象.        (line  168)
* ECHRNG() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  198)
* ECOMM() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line  302)
* ECONNABORTED() (在 errno 模块中):      errno --- 标准 errno 系统符号.
                                                             (line  434)
* ECONNREFUSED() (在 errno 模块中):      errno --- 标准 errno 系统符号.
                                                             (line  466)
* ECONNRESET() (在 errno 模块中):        errno --- 标准 errno 系统符号.
                                                             (line  438)
* EDEADLK() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  162)
* EDEADLOCK() (在 errno 模块中):         errno --- 标准 errno 系统符号.
                                                             (line  254)
* EDESTADDRREQ() (在 errno 模块中):      errno --- 标准 errno 系统符号.
                                                             (line  378)
* edit() (curses.textpad.Textbox 方法):  文本框对象.         (line   17)
* EDOM() (在 errno 模块中):              errno --- 标准 errno 系统符号.
                                                             (line  154)
* EDOTDOT() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  314)
* EDQUOT() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  510)
* EEXIST() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line   90)
* EFAULT() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line   78)
* EFBIG() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line  130)
* effective() (在 bdb 模块中):           bdb --- Debugger framework.
                                                             (line  395)
* ehlo() (smtplib.SMTP 方法):            SMTP Objects.       (line   55)
* ehlo_or_helo_if_needed() (smtplib.SMTP 方法): SMTP Objects.
                                                             (line   68)
* EHOSTDOWN() (在 errno 模块中):         errno --- 标准 errno 系统符号.
                                                             (line  470)
* EHOSTUNREACH() (在 errno 模块中):      errno --- 标准 errno 系统符号.
                                                             (line  474)
* EIDRM() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line  194)
* EILSEQ() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  358)
* EINPROGRESS() (在 errno 模块中):       errno --- 标准 errno 系统符号.
                                                             (line  482)
* EINTR() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line   33)
* EINVAL() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  110)
* EIO() (在 errno 模块中):               errno --- 标准 errno 系统符号.
                                                             (line   42)
* EISCONN() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  446)
* EISDIR() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  106)
* EISNAM() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  502)
* EL2HLT() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  226)
* EL2NSYNC() (在 errno 模块中):          errno --- 标准 errno 系统符号.
                                                             (line  202)
* EL3HLT() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  206)
* EL3RST() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  210)
* Element (xml.etree.ElementTree 中的类): 元素对象.          (line    6)
* ElementDeclHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  168)
* elements() (collections.Counter 方法): Counter 对象.       (line   58)
* ElementTree (xml.etree.ElementTree 中的类): ElementTree 对象.
                                                             (line    6)
* element_create() (tkinter.ttk.Style 方法): Ttk Styling.    (line  131)
* element_names() (tkinter.ttk.Style 方法): Ttk Styling.     (line  183)
* element_options() (tkinter.ttk.Style 方法): Ttk Styling.   (line  187)
* ELIBACC() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  338)
* ELIBBAD() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  342)
* ELIBEXEC() (在 errno 模块中):          errno --- 标准 errno 系统符号.
                                                             (line  354)
* ELIBMAX() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  350)
* ELIBSCN() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  346)
* Ellinghouse, Lance:                    uu --- 对 uuencode 文件进行编码与解码.
                                                             (line   17)
* Ellipsis (內置变量):                   内置常量.           (line   47)
* ELLIPSIS() (在 doctest 模块中):        Option Flags.       (line   49)
* ELLIPSIS() (在 token 模块中):          token --- 与Python解析树一起使用的常量.
                                                             (line  230)
* ELNRNG() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  214)
* ELOOP() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line  182)
* else; conditional expression:          条件表达式.         (line    6)
* email (模块):                          email --- 电子邮件与 MIME 处理包.
                                                             (line    6)
* email.charset (模块):                  email charset 表示字符集.
                                                             (line    6)
* email.contentmanager (模块):           email contentmanager 管理 MIME 内容.
                                                             (line    6)
* email.encoders (模块):                 email encoders 编码器.
                                                             (line    6)
* email.errors (模块):                   email errors 异常和缺陷类.
                                                             (line    6)
* email.generator (模块):                email generator 生成 MIME 文档.
                                                             (line    6)
* email.header (模块):                   email header 国际化标头.
                                                             (line    6)
* email.headerregistry (模块):           email headerregistry 自定义标头对象.
                                                             (line    6)
* email.iterators (模块):                email iterators 迭代器.
                                                             (line    6)
* email.message (模块):                  email message 表示一封电子邮件信息.
                                                             (line    6)
* email.mime (模块):                     email mime 从头创建电子邮件和 MIME 对象.
                                                             (line    6)
* email.parser (模块):                   email parser 解析电子邮件信息.
                                                             (line    6)
* email.policy (模块):                   email policy 策略对象.
                                                             (line    6)
* email.utils (模块):                    email utils 其他工具.
                                                             (line    6)
* EmailMessage (email.message 中的类):   email message 表示一封电子邮件信息.
                                                             (line   40)
* EmailPolicy (email.policy 中的类):     email policy 策略对象.
                                                             (line  274)
* EMFILE() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  118)
* emit() (logging.FileHandler 方法):     FileHandler.        (line   26)
* emit() (logging.Handler 方法):         处理器对象.         (line   91)
* emit() (logging.handlers.BufferingHandler 方法): MemoryHandler.
                                                             (line   20)
* emit() (logging.handlers.DatagramHandler 方法): DatagramHandler.
                                                             (line   17)
* emit() (logging.handlers.HTTPHandler 方法): HTTPHandler.   (line   31)
* emit() (logging.handlers.NTEventLogHandler 方法): NTEventLogHandler.
                                                             (line   30)
* emit() (logging.handlers.QueueHandler 方法): QueueHandler. (line   26)
* emit() (logging.handlers.RotatingFileHandler 方法): RotatingFileHandler.
                                                             (line   38)
* emit() (logging.handlers.SMTPHandler 方法): SMTPHandler.   (line   28)
* emit() (logging.handlers.SocketHandler 方法): SocketHandler.
                                                             (line   21)
* emit() (logging.handlers.SysLogHandler 方法): SysLogHandler.
                                                             (line   38)
* emit() (logging.handlers.TimedRotatingFileHandler 方法): TimedRotatingFileHandler.
                                                             (line   86)
* emit() (logging.handlers.WatchedFileHandler 方法): WatchedFileHandler.
                                                             (line   40)
* emit() (logging.NullHandler 方法):     NullHandler.        (line   15)
* emit() (logging.StreamHandler 方法):   StreamHandler.      (line   15)
* EMLINK() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  146)
* Empty:                                 queue --- 一个同步的队列类.
                                                             (line   68)
* empty (inspect.Parameter 属性):        Introspecting callables with the Signature object.
                                                             (line  150)
* empty (inspect.Signature 属性):        Introspecting callables with the Signature object.
                                                             (line   73)
* empty() (asyncio.Queue 方法):          Queue.              (line   26)
* empty() (multiprocessing.Queue 方法):  管道和队列.         (line   92)
* empty() (multiprocessing.SimpleQueue 方法): 管道和队列.    (line  177)
* empty() (queue.Queue 方法):            Queue对象.          (line   14)
* empty() (queue.SimpleQueue 方法):      SimpleQueue 对象.   (line   12)
* empty() (sched.scheduler 方法):        调度器对象.         (line   41)
* empty; list:                           列表显示.           (line    6)
* empty; tuple:                          标准类型层级结构.   (line  130)
* empty; tuple <1>:                      带圆括号的形式.     (line   14)
* emptyline() (cmd.Cmd 方法):            Cmd 对象.           (line   52)
* EMPTY_NAMESPACE() (在 xml.dom 模块中): 模块内容<6>.        (line   29)
* EMSGSIZE() (在 errno 模块中):          errno --- 标准 errno 系统符号.
                                                             (line  382)
* EMULTIHOP() (在 errno 模块中):         errno --- 标准 errno 系统符号.
                                                             (line  310)
* enable (pdb command):                  调试器命令.         (line   87)
* enable() (bdb.Breakpoint 方法):        bdb --- Debugger framework.
                                                             (line   47)
* enable() (imaplib.IMAP4 方法):         IMAP4 Objects.      (line   84)
* enable() (profile.Profile 方法):       profile 和 cProfile 模块参考.
                                                             (line   77)
* enable() (在 cgitb 模块中):            cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line   25)
* enable() (在 faulthandler 模块中):     Fault handler state.
                                                             (line    6)
* enable() (在 gc 模块中):               gc --- 垃圾回收器接口.
                                                             (line   18)
* EnableReflectionKey() (在 winreg 模块中): 函数<11>.        (line  483)
* enable_callback_tracebacks() (在 sqlite3 模块中): 模块函数和常量.
                                                             (line  159)
* enable_interspersed_args() (optparse.OptionParser 方法): Querying and manipulating your option parser.
                                                             (line   31)
* enable_load_extension() (sqlite3.Connection 方法): 连接对象（Connection）.
                                                             (line  224)
* enable_traversal() (tkinter.ttk.Notebook 方法): ttk Notebook.
                                                             (line   75)
* ENABLE_USER_SITE() (在 site 模块中):   模块内容<7>.        (line   10)
* ENAMETOOLONG() (在 errno 模块中):      errno --- 标准 errno 系统符号.
                                                             (line  166)
* ENAVAIL() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  498)
* enclose() (curses.window 方法):        Window 对象.        (line  173)
* encode (codecs.CodecInfo 属性):        codecs --- 编解码器注册和相关基类.
                                                             (line   60)
* encode() (codecs.Codec 方法):          无状态的编码和解码. (line    9)
* encode() (codecs.IncrementalEncoder 方法): IncrementalEncoder 对象.
                                                             (line   24)
* encode() (email.header.Header 方法):   email header 国际化标头.
                                                             (line  101)
* encode() (json.JSONEncoder 方法):      编码器和解码器.     (line  192)
* encode() (str 方法):                   字符串的方法<2>.    (line   51)
* encode() (xmlrpc.client.Binary 方法):  Binary 对象.        (line   25)
* encode() (xmlrpc.client.DateTime 方法): DateTime 对象.     (line   17)
* encode() (在 base64 模块中):           base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  199)
* encode() (在 codecs 模块中):           codecs --- 编解码器注册和相关基类.
                                                             (line   19)
* encode() (在 quopri 模块中):           quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   26)
* encode() (在 uu 模块中):               uu --- 对 uuencode 文件进行编码与解码.
                                                             (line   21)
* encodebytes() (在 base64 模块中):      base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  207)
* EncodedFile() (在 codecs 模块中):      codecs --- 编解码器注册和相关基类.
                                                             (line  162)
* encodePriority() (logging.handlers.SysLogHandler 方法): SysLogHandler.
                                                             (line   63)
* encodestring() (在 base64 模块中):     base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  216)
* encodestring() (在 quopri 模块中):     quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   40)
* encode_7or8bit() (在 email.encoders 模块中): email encoders 编码器.
                                                             (line   49)
* encode_base64() (在 email.encoders 模块中): email encoders 编码器.
                                                             (line   42)
* encode_noop() (在 email.encoders 模块中): email encoders 编码器.
                                                             (line   54)
* encode_quopri() (在 email.encoders 模块中): email encoders 编码器.
                                                             (line   35)
* encode_rfc2231() (在 email.utils 模块中): email utils 其他工具.
                                                             (line  152)
* encoding (curses.window 属性):         Window 对象.        (line  179)
* encoding (io.TextIOBase 属性):         文本 I/O<2>.        (line   14)
* encoding (UnicodeError 属性):          具体异常.           (line  303)
* encoding declarations (source file):   编码声明.           (line    6)
* ENCODING() (在 tarfile 模块中):        tarfile --- 读写tar归档文件.
                                                             (line  190)
* ENCODING() (在 token 模块中):          token --- 与Python解析树一起使用的常量.
                                                             (line  267)
* encodings.idna (模块):                 encodings idna --- 应用程序中的国际化域名.
                                                             (line    6)
* encodings.mbcs (模块):                 encodings mbcs --- Windows ANSI代码页.
                                                             (line    6)
* encodings.utf_8_sig (模块):            encodings utf_8_sig --- 带BOM签名的UTF-8编解码器.
                                                             (line    6)
* encodings_map (mimetypes.MimeTypes 属性): MimeTypes 对象.  (line   26)
* encodings_map() (在 mimetypes 模块中): mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line  114)
* end (UnicodeError 属性):               具体异常.           (line  319)
* end() (re.Match 方法):                 匹配对象.           (line  112)
* end() (xml.etree.ElementTree.TreeBuilder 方法): TreeBuilder 对象.
                                                             (line   33)
* EndCdataSectionHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  255)
* EndDoctypeDeclHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  163)
* endDocument() (xml.sax.handler.ContentHandler 方法): ContentHandler 对象.
                                                             (line   33)
* endElement() (xml.sax.handler.ContentHandler 方法): ContentHandler 对象.
                                                             (line   79)
* EndElementHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  192)
* endElementNS() (xml.sax.handler.ContentHandler 方法): ContentHandler 对象.
                                                             (line  101)
* endheaders() (http.client.HTTPConnection 方法): HTTPConnection 对象.
                                                             (line  123)
* ENDMARKER() (在 token 模块中):         token --- 与Python解析树一起使用的常量.
                                                             (line   36)
* EndNamespaceDeclHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  236)
* endpos (re.Match 属性):                匹配对象.           (line  146)
* endPrefixMapping() (xml.sax.handler.ContentHandler 方法): ContentHandler 对象.
                                                             (line   61)
* endswith() (bytearray 方法):           bytes 和 bytearray 操作.
                                                             (line   58)
* endswith() (bytes 方法):               bytes 和 bytearray 操作.
                                                             (line   58)
* endswith() (str 方法):                 字符串的方法<2>.    (line   64)
* endwin() (在 curses 模块中):           函数<3>.            (line   91)
* END_ASYNC_FOR (opcode):                Python字节码说明.   (line  274)
* end_col_offset (ast.AST 属性):         节点类.             (line   32)
* end_fill() (在 turtle 模块中):         填充.               (line   20)
* END_FINALLY (opcode):                  Python字节码说明.   (line  386)
* end_headers() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  253)
* end_lineno (ast.AST 属性):             节点类.             (line   32)
* end_ns() (xml.etree.ElementTree.TreeBuilder 方法): TreeBuilder 对象.
                                                             (line   75)
* end_paragraph() (formatter.formatter 方法): The Formatter Interface.
                                                             (line   26)
* end_poly() (在 turtle 模块中):         特殊海龟方法.       (line   10)
* ENETDOWN() (在 errno 模块中):          errno --- 标准 errno 系统符号.
                                                             (line  422)
* ENETRESET() (在 errno 模块中):         errno --- 标准 errno 系统符号.
                                                             (line  430)
* ENETUNREACH() (在 errno 模块中):       errno --- 标准 errno 系统符号.
                                                             (line  426)
* ENFILE() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  114)
* ENOANO() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  242)
* ENOBUFS() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  442)
* ENOCSI() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  222)
* ENODATA() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  266)
* ENODEV() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line   98)
* ENOENT() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line   25)
* ENOEXEC() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line   54)
* ENOLCK() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  170)
* ENOLINK() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  290)
* ENOMEM() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line   70)
* ENOMSG() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  190)
* ENONET() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  278)
* ENOPKG() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  282)
* ENOPROTOOPT() (在 errno 模块中):       errno --- 标准 errno 系统符号.
                                                             (line  390)
* ENOSPC() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  134)
* ENOSR() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line  274)
* ENOSTR() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  262)
* ENOSYS() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  174)
* ENOTBLK() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line   82)
* ENOTCONN() (在 errno 模块中):          errno --- 标准 errno 系统符号.
                                                             (line  450)
* ENOTDIR() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  102)
* ENOTEMPTY() (在 errno 模块中):         errno --- 标准 errno 系统符号.
                                                             (line  178)
* ENOTNAM() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  494)
* ENOTSOCK() (在 errno 模块中):          errno --- 标准 errno 系统符号.
                                                             (line  374)
* ENOTTY() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  122)
* ENOTUNIQ() (在 errno 模块中):          errno --- 标准 errno 系统符号.
                                                             (line  326)
* enqueue() (logging.handlers.QueueHandler 方法): QueueHandler.
                                                             (line   44)
* enqueue_sentinel() (logging.handlers.QueueListener 方法): QueueListener.
                                                             (line   74)
* ensurepip (模块):                      ensurepip --- Bootstrapping the pip installer.
                                                             (line    6)
* ensure_directories() (venv.EnvBuilder 方法): API<2>.       (line   71)
* ensure_future() (在 asyncio 模块中):   Future 函数.        (line   18)
* enter() (sched.scheduler 方法):        调度器对象.         (line   26)
* enterabs() (sched.scheduler 方法):     调度器对象.         (line    8)
* enter_async_context() (contextlib.AsyncExitStack 方法): 工具.
                                                             (line  426)
* enter_context() (contextlib.ExitStack 方法): 工具.         (line  345)
* entities (xml.dom.DocumentType 属性):  文档类型对象.       (line   31)
* EntityDeclHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  214)
* entitydefs() (在 html.entities 模块中): html entities --- HTML 一般实体的定义.
                                                             (line   22)
* EntityResolver (xml.sax.handler 中的类): xml sax handler --- SAX 处理程序的基类.
                                                             (line   26)
* Enum (enum 中的类):                    模块内容<2>.        (line   11)
* enum (模块):                           enum --- 对枚举的支持.
                                                             (line    6)
* enumerate() (內置函数):                内置函数.           (line  382)
* enumerate() (在 threading 模块中):     threading --- 基于线程的并行.
                                                             (line   93)
* EnumKey() (在 winreg 模块中):          函数<11>.           (line  161)
* EnumValue() (在 winreg 模块中):        函数<11>.           (line  178)
* enum_certificates() (在 ssl 模块中):   证书处理.           (line  112)
* enum_crls() (在 ssl 模块中):           证书处理.           (line  133)
* EnvBuilder (venv 中的类):              API<2>.             (line   10)
* environ() (在 os 模块中):              进程参数.           (line   14)
* environ() (在 posix 模块中):           重要的模块内容.     (line    9)
* environb() (在 os 模块中):             进程参数.           (line   46)
* environment:                           名称的解析.         (line   11)
* environment variables; deleting:       进程参数.           (line  454)
* environment variables; setting:        进程参数.           (line  291)
* EnvironmentError:                      具体异常.           (line  351)
* Environments; virtual:                 venv --- 创建虚拟环境.
                                                             (line   10)
* EnvironmentVarGuard (test.support 中的类): test support --- Utilities for the Python test suite.
                                                             (line 1024)
* ENXIO() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line   46)
* eof (bz2.BZ2Decompressor 属性):        增量压缩和解压.     (line   61)
* eof (lzma.LZMADecompressor 属性):      在内存中压缩和解压缩数据.
                                                             (line  132)
* eof (shlex.shlex 属性):                shlex Objects.      (line  177)
* eof (ssl.MemoryBIO 属性):              内存 BIO 支持<2>.   (line  126)
* eof (zlib.Decompress 属性):            zlib --- 与 gzip 兼容的压缩.
                                                             (line  187)
* EOFError:                              具体异常.           (line   18)
* EOFError (built-in exception):         文件对象.           (line   36)
* eof_received() (asyncio.BufferedProtocol 方法): 缓冲流协议.
                                                             (line   34)
* eof_received() (asyncio.Protocol 方法): 流协议.            (line   26)
* EOPNOTSUPP() (在 errno 模块中):        errno --- 标准 errno 系统符号.
                                                             (line  402)
* EOVERFLOW() (在 errno 模块中):         errno --- 标准 errno 系统符号.
                                                             (line  322)
* EPERM() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line   21)
* EPFNOSUPPORT() (在 errno 模块中):      errno --- 标准 errno 系统符号.
                                                             (line  406)
* epilogue (email.message.EmailMessage 属性): email message 表示一封电子邮件信息.
                                                             (line  592)
* epilogue (email.message.Message 属性): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  600)
* EPIPE() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line  150)
* epoch:                                 time --- 时间的访问和转换.
                                                             (line   15)
* epoll() (在 select 模块中):            select --- 等待 I/O 完成.
                                                             (line   44)
* EpollSelector (selectors 中的类):      类<3>.              (line  153)
* EPROTO() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  306)
* EPROTONOSUPPORT() (在 errno 模块中):   errno --- 标准 errno 系统符号.
                                                             (line  394)
* EPROTOTYPE() (在 errno 模块中):        errno --- 标准 errno 系统符号.
                                                             (line  386)
* eq() (在 operator 模块中):             operator --- 标准运算符替代函数.
                                                             (line   19)
* EQEQUAL() (在 token 模块中):           token --- 与Python解析树一起使用的常量.
                                                             (line  130)
* EQUAL() (在 token 模块中):             token --- 与Python解析树一起使用的常量.
                                                             (line  110)
* ERA() (在 locale 模块中):              locale --- 国际化服务.
                                                             (line  246)
* ERANGE() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  158)
* erase() (curses.window 方法):          Window 对象.        (line  188)
* erasechar() (在 curses 模块中):        函数<3>.            (line   95)
* ERA_D_FMT() (在 locale 模块中):        locale --- 国际化服务.
                                                             (line  268)
* ERA_D_T_FMT() (在 locale 模块中):      locale --- 国际化服务.
                                                             (line  263)
* ERA_T_FMT() (在 locale 模块中):        locale --- 国际化服务.
                                                             (line  273)
* EREMCHG() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  334)
* EREMOTE() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  286)
* EREMOTEIO() (在 errno 模块中):         errno --- 标准 errno 系统符号.
                                                             (line  506)
* ERESTART() (在 errno 模块中):          errno --- 标准 errno 系统符号.
                                                             (line  362)
* erf() (在 math 模块中):                特殊函数.           (line    6)
* erfc() (在 math 模块中):               特殊函数.           (line   19)
* EROFS() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line  142)
* ERR() (在 curses 模块中):              常量<6>.            (line    8)
* errcheck (ctypes._FuncPtr 属性):       外部函数.           (line   46)
* errcode (xmlrpc.client.ProtocolError 属性): ProtocolError 对象.
                                                             (line   17)
* errmsg (xmlrpc.client.ProtocolError 属性): ProtocolError 对象.
                                                             (line   21)
* errno (OSError 属性):                  具体异常.           (line  113)
* errno (模块):                          errno --- 标准 errno 系统符号.
                                                             (line    6)
* error:                                 模块内容.           (line  286)
* error <1>:                             函数和异常.         (line    8)
* Error:                                 copy --- 浅层 shallow 和深层 deep 复制操作.
                                                             (line   25)
* Error <1>:                             目录和文件操作.     (line  338)
* error <2>:                             dbm --- Unix "数据库" 接口.
                                                             (line   15)
* error <3>:                             dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line   19)
* error <4>:                             dbm ndbm --- 基于 ndbm 的接口.
                                                             (line   17)
* error <5>:                             dbm dumb --- 便携式 DBM 实现.
                                                             (line   20)
* Error <2>:                             异常<4>.            (line   10)
* error <6>:                             zlib --- 与 gzip 兼容的压缩.
                                                             (line   20)
* Error <3>:                             模块内容<3>.        (line  228)
* Error <4>:                             异常<5>.            (line    6)
* Error <5>:                             异常<6>.            (line    8)
* error <7>:                             os --- 多种操作系统接口.
                                                             (line   36)
* error <8>:                             getopt --- C 风格的命令行选项解析器.
                                                             (line   63)
* error <9>:                             函数<3>.            (line    8)
* error <10>:                            _thread --- 底层多线程 API.
                                                             (line   17)
* error <11>:                            异常<11>.           (line    6)
* error <12>:                            select --- 等待 I/O 完成.
                                                             (line   21)
* Error <6>:                             异常<14>.           (line    8)
* Error <7>:                             binhex --- 对binhex4文件进行编码和解码.
                                                             (line   29)
* Error <8>:                             binascii --- 二进制和 ASCII 码互转.
                                                             (line  147)
* Error <9>:                             uu --- 对 uuencode 文件进行编码与解码.
                                                             (line   43)
* error <13>:                            xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line   27)
* Error <10>:                            webbrowser --- 方便的Web浏览器控制器.
                                                             (line   34)
* error <14>:                            audioop --- 处理原始音频数据.
                                                             (line   22)
* Error <11>:                            sunau --- 读写 Sun AU 文件.
                                                             (line   71)
* Error <12>:                            wave --- 读写WAV格式文件.
                                                             (line   49)
* Error <13>:                            locale --- 国际化服务.
                                                             (line   22)
* error <15>:                            resource --- Resource usage information.
                                                             (line   17)
* error <16>:                            nis --- Sun 的 NIS 黄页 接口.
                                                             (line   49)
* error handling:                        异常<2>.            (line    6)
* error() (argparse.ArgumentParser 方法): 退出方法.          (line   18)
* error() (logging.Logger 方法):         记录器对象.         (line  179)
* error() (urllib.request.OpenerDirector 方法): OpenerDirector 对象.
                                                             (line   52)
* error() (xml.sax.handler.ErrorHandler 方法): ErrorHandler 对象.
                                                             (line   13)
* error() (在 logging 模块中):           模块级别函数.       (line  110)
* ErrorByteIndex (xml.parsers.expat.xmlparser 属性): XMLParser对象<2>.
                                                             (line  107)
* ErrorCode (xml.parsers.expat.xmlparser 属性): XMLParser对象<2>.
                                                             (line  111)
* errorcode() (在 errno 模块中):         errno --- 标准 errno 系统符号.
                                                             (line   11)
* ErrorColumnNumber (xml.parsers.expat.xmlparser 属性): XMLParser对象<2>.
                                                             (line  116)
* ErrorHandler (xml.sax.handler 中的类): xml sax handler --- SAX 处理程序的基类.
                                                             (line   31)
* ErrorLineNumber (xml.parsers.expat.xmlparser 属性): XMLParser对象<2>.
                                                             (line  120)
* errors:                                异常<2>.            (line    6)
* errors (io.TextIOBase 属性):           文本 I/O<2>.        (line   19)
* errors (unittest.TestLoader 属性):     Loading and running tests.
                                                             (line   17)
* errors (unittest.TestResult 属性):     Loading and running tests.
                                                             (line  236)
* Errors; logging:                       logging --- Python 的日志记录工具.
                                                             (line    8)
* ErrorString() (在 xml.parsers.expat 模块中): xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line   37)
* ERRORTOKEN() (在 token 模块中):        token --- 与Python解析树一起使用的常量.
                                                             (line  248)
* error_body (wsgiref.handlers.BaseHandler 属性): wsgiref handlers -- server/gateway base classes.
                                                             (line  259)
* error_content_type (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line  139)
* error_headers (wsgiref.handlers.BaseHandler 属性): wsgiref handlers -- server/gateway base classes.
                                                             (line  252)
* error_leader() (shlex.shlex 方法):     shlex Objects.      (line   69)
* error_message_format (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line  131)
* error_output() (wsgiref.handlers.BaseHandler 方法): wsgiref handlers -- server/gateway base classes.
                                                             (line  224)
* error_perm:                            ftplib --- FTP 协议客户端.
                                                             (line  112)
* error_proto:                           ftplib --- FTP 协议客户端.
                                                             (line  117)
* error_proto <1>:                       poplib --- POP3 协议客户端.
                                                             (line   68)
* error_received() (asyncio.DatagramProtocol 方法): 数据报协议.
                                                             (line   14)
* error_reply:                           ftplib --- FTP 协议客户端.
                                                             (line  103)
* error_status (wsgiref.handlers.BaseHandler 属性): wsgiref handlers -- server/gateway base classes.
                                                             (line  246)
* error_temp:                            ftplib --- FTP 协议客户端.
                                                             (line  107)
* escape (shlex.shlex 属性):             shlex Objects.      (line  110)
* escape sequence:                       字符串和字节串字面值.
                                                             (line   62)
* escape() (在 glob 模块中):             glob --- Unix 风格路径名模式扩展.
                                                             (line   57)
* escape() (在 html 模块中):             html --- 超文本标记语言支持.
                                                             (line   12)
* escape() (在 re 模块中):               模块内容.           (line  252)
* escape() (在 xml.sax.saxutils 模块中): xml sax saxutils --- SAX 工具集.
                                                             (line   13)
* escapechar (csv.Dialect 属性):         变种与格式参数.     (line   29)
* escapedquotes (shlex.shlex 属性):      shlex Objects.      (line  122)
* ESHUTDOWN() (在 errno 模块中):         errno --- 标准 errno 系统符号.
                                                             (line  454)
* ESOCKTNOSUPPORT() (在 errno 模块中):   errno --- 标准 errno 系统符号.
                                                             (line  398)
* ESPIPE() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  138)
* ESRCH() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line   29)
* ESRMNT() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  298)
* ESTALE() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  486)
* ESTRPIPE() (在 errno 模块中):          errno --- 标准 errno 系统符号.
                                                             (line  366)
* ETIME() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line  270)
* ETIMEDOUT() (在 errno 模块中):         errno --- 标准 errno 系统符号.
                                                             (line  462)
* Etiny() (decimal.Context 方法):        上下文对象.         (line  182)
* ETOOMANYREFS() (在 errno 模块中):      errno --- 标准 errno 系统符号.
                                                             (line  458)
* Etop() (decimal.Context 方法):         上下文对象.         (line  187)
* ETXTBSY() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  126)
* EUCLEAN() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  490)
* EUNATCH() (在 errno 模块中):           errno --- 标准 errno 系统符号.
                                                             (line  218)
* EUSERS() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  370)
* eval() (內置函数):                     内置函数.           (line  403)
* evaluation; order:                     求值顺序.           (line    6)
* Event (asyncio 中的类):                Event.              (line    6)
* Event (multiprocessing 中的类):        同步原语.           (line   36)
* Event (threading 中的类):              事件对象.           (line   13)
* event scheduling:                      sched --- 事件调度器.
                                                             (line    8)
* event() (msilib.Control 方法):         GUI classes.        (line   16)
* Event() (multiprocessing.managers.SyncManager 方法): 管理器.
                                                             (line  143)
* events (selectors.SelectorKey 属性):   类<3>.              (line   42)
* events (widgets):                      Bindings and Events.
                                                             (line    6)
* EWOULDBLOCK() (在 errno 模块中):       errno --- 标准 errno 系统符号.
                                                             (line  186)
* Example (doctest 中的类):              Example Objects.    (line    6)
* example (doctest.DocTestFailure 属性): 调试.               (line  199)
* example (doctest.UnexpectedException 属性): 调试.          (line  220)
* examples (doctest.DocTest 属性):       DocTest 对象.       (line   17)
* excel (csv 中的类):                    模块内容<3>.        (line  158)
* excel_tab (csv 中的类):                模块内容<3>.        (line  163)
* except (2to3 fixer):                   修复器.             (line   79)
* excepthook() (in module sys):          cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line   28)
* excepthook() (在 sys 模块中):          sys --- 系统相关的参数和函数.
                                                             (line  260)
* excepthook() (在 threading 模块中):    threading --- 基于线程的并行.
                                                             (line   38)
* exception:                             异常<2>.            (line    6)
* exception <1>:                         raise 语句.         (line    6)
* Exception:                             基类.               (line   31)
* exception handler:                     异常<2>.            (line    6)
* exception() (asyncio.Future 方法):     Future 对象<2>.     (line  106)
* exception() (asyncio.Task 方法):       Task 对象.          (line  121)
* exception() (concurrent.futures.Future 方法): Future 对象. (line   45)
* exception() (logging.Logger 方法):     记录器对象.         (line  194)
* exception() (在 logging 模块中):       模块级别函数.       (line  120)
* EXCEPTION() (在 tkinter 模块中):       File Handlers.      (line   41)
* exception; chaining:                   raise 语句.         (line   25)
* exception; handler:                    标准类型层级结构.   (line  571)
* exceptions; in CGI scripts:            cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line    8)
* exclusive; or:                         二元位运算.         (line   14)
* exc_info (doctest.UnexpectedException 属性): 调试.         (line  224)
* exc_info (in module sys):              标准类型层级结构.   (line  571)
* exc_info() (in module sys):            异常<18>.           (line   43)
* exc_info() (在 sys 模块中):            sys --- 系统相关的参数和函数.
                                                             (line  294)
* exc_msg (doctest.Example 属性):        Example Objects.    (line   31)
* exc_type (traceback.TracebackException 属性): TracebackException Objects.
                                                             (line   38)
* EXDEV() (在 errno 模块中):             errno --- 标准 errno 系统符号.
                                                             (line   94)
* exec (2to3 fixer):                     修复器.             (line   83)
* exec() (內置函数):                     内置函数.           (line  439)
* execfile (2to3 fixer):                 修复器.             (line   87)
* execl() (在 os 模块中):                进程管理.           (line   45)
* execle() (在 os 模块中):               进程管理.           (line   45)
* execlp() (在 os 模块中):               进程管理.           (line   45)
* execlpe() (在 os 模块中):              进程管理.           (line   45)
* executable (in module sys):            Process-wide parameters.
                                                             (line  111)
* Executable Zip Files:                  zipapp --- Manage executable Python zip archives.
                                                             (line   10)
* executable() (在 sys 模块中):          sys --- 系统相关的参数和函数.
                                                             (line  322)
* executable_filename() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  448)
* execute() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  478)
* Execute() (msilib.View 方法):          View Objects.       (line    6)
* execute() (sqlite3.Connection 方法):   连接对象（Connection）.
                                                             (line   47)
* execute() (sqlite3.Cursor 方法):       Cursor 对象.        (line   10)
* execute() (在 distutils.util 模块中):  distutils util --- Miscellaneous other utility functions.
                                                             (line  109)
* executemany() (sqlite3.Connection 方法): 连接对象（Connection）.
                                                             (line   53)
* executemany() (sqlite3.Cursor 方法):   Cursor 对象.        (line   42)
* executescript() (sqlite3.Connection 方法): 连接对象（Connection）.
                                                             (line   59)
* executescript() (sqlite3.Cursor 方法): Cursor 对象.        (line   95)
* execution model:                       执行模型.           (line    6)
* execution; frame:                      程序的结构.         (line   14)
* execution; frame <1>:                  类定义.             (line    6)
* execution; stack:                      标准类型层级结构.   (line  571)
* ExecutionLoader (importlib.abc 中的类): importlib abc —— 关于导入的抽象基类.
                                                             (line  394)
* Executor (concurrent.futures 中的类):  Executor 对象.      (line    6)
* execv() (在 os 模块中):                进程管理.           (line   45)
* execve() (在 os 模块中):               进程管理.           (line   45)
* execvp() (在 os 模块中):               进程管理.           (line   45)
* execvpe() (在 os 模块中):              进程管理.           (line   45)
* exec_module (C 函数):                  Multi-phase initialization.
                                                             (line  102)
* exec_module() (importlib.abc.InspectLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  382)
* exec_module() (importlib.abc.Loader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  168)
* exec_module() (importlib.abc.SourceLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  507)
* exec_module() (importlib.machinery.ExtensionFileLoader 方法): importlib machinery -- Importers and path hooks.
                                                             (line  319)
* exec_prefix:                           与Python相关的路径和文件.
                                                             (line    6)
* exec_prefix <1>:                       包含文件.           (line   32)
* exec_prefix <2>:                       包含文件.           (line   40)
* EXEC_PREFIX() (在 distutils.sysconfig 模块中): distutils sysconfig --- System configuration information.
                                                             (line   23)
* exec_prefix() (在 sys 模块中):         sys --- 系统相关的参数和函数.
                                                             (line  308)
* ExFileSelectBox (tkinter.tix 中的类):  File Selectors.     (line   34)
* EXFULL() (在 errno 模块中):            errno --- 标准 errno 系统符号.
                                                             (line  238)
* exists() (pathlib.Path 方法):          方法<2>.            (line   55)
* exists() (tkinter.ttk.Treeview 方法):  ttk Treeview.       (line   94)
* exists() (zipfile.Path 方法):          Path 对象.          (line   44)
* exists() (在 os.path 模块中):          os path --- 常用路径操作.
                                                             (line   99)
* exit (內置变量):                       由 site 模块添加的常量.
                                                             (line   10)
* exit():                                过程控制.           (line   17)
* exit() (argparse.ArgumentParser 方法): 退出方法.           (line    6)
* exit() (在 sys 模块中):                sys --- 系统相关的参数和函数.
                                                             (line  328)
* exit() (在 _thread 模块中):            _thread --- 底层多线程 API.
                                                             (line   52)
* exitcode (multiprocessing.Process 属性): Process 和异常.   (line   94)
* exitfunc (2to3 fixer):                 修复器.             (line   92)
* exitonclick() (在 turtle 模块中):      Screen 专有方法 而非继承自 TurtleScreen.
                                                             (line   10)
* ExitStack (contextlib 中的类):         工具.               (line  314)
* exp() (decimal.Context 方法):          上下文对象.         (line  248)
* exp() (decimal.Decimal 方法):          Decimal 对象.       (line  196)
* exp() (在 cmath 模块中):               幂函数与对数函数<2>.
                                                             (line    6)
* exp() (在 math 模块中):                幂函数与对数函数.   (line    6)
* expand() (re.Match 方法):              匹配对象.           (line   16)
* ExpandEnvironmentStrings() (在 winreg 模块中): 函数<11>.   (line  212)
* expandNode() (xml.dom.pulldom.DOMEventStream 方法): DOMEventStream 对象.
                                                             (line   19)
* expandtabs() (bytearray 方法):         bytes 和 bytearray 操作.
                                                             (line  344)
* expandtabs() (bytes 方法):             bytes 和 bytearray 操作.
                                                             (line  344)
* expandtabs() (str 方法):               字符串的方法<2>.    (line   71)
* expanduser() (pathlib.Path 方法):      方法<2>.            (line   71)
* expanduser() (在 os.path 模块中):      os path --- 常用路径操作.
                                                             (line  119)
* expandvars() (在 os.path 模块中):      os path --- 常用路径操作.
                                                             (line  138)
* expand_tabs (textwrap.TextWrapper 属性): textwrap --- 文本自动换行与填充.
                                                             (line  142)
* Expat:                                 xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line   11)
* ExpatError:                            xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line   22)
* expect() (telnetlib.Telnet 方法):      Telnet 对象.        (line  111)
* expected (asyncio.IncompleteReadError 属性): 异常<9>.      (line   46)
* expectedFailure() (在 unittest 模块中): 跳过测试与预计的失败.
                                                             (line   94)
* expectedFailures (unittest.TestResult 属性): Loading and running tests.
                                                             (line  256)
* expires (http.cookiejar.Cookie 属性):  Cookie 对象<2>.     (line   49)
* exploded (ipaddress.IPv4Address 属性): 地址对象.           (line   55)
* exploded (ipaddress.IPv4Network 属性): Network objects.    (line  109)
* exploded (ipaddress.IPv6Address 属性): 地址对象.           (line  157)
* exploded (ipaddress.IPv6Network 属性): Network objects.    (line  321)
* expm1() (在 math 模块中):              幂函数与对数函数.   (line   11)
* expovariate() (在 random 模块中):      实值分布.           (line   32)
* expr() (在 parser 模块中):             创建 ST 对象.       (line   10)
* expression:                            表达式.             (line    6)
* expression – 表达式:                   术语对照表.         (line  319)
* expression; list:                      表达式列表.         (line    6)
* expression; list <1>:                  表达式语句.         (line    6)
* expression; list <2>:                  表达式语句.         (line    6)
* expression; statement:                 表达式语句.         (line    6)
* expunge() (imaplib.IMAP4 方法):        IMAP4 Objects.      (line   93)
* extend() (array.array 方法):           array --- 高效的数值数组.
                                                             (line  131)
* extend() (collections.deque 方法):     deque 对象.         (line   51)
* extend() (sequence method):            可变序列类型.       (line   14)
* extend() (xml.etree.ElementTree.Element 方法): 元素对象.   (line   80)
* ExtendedContext (decimal 中的类):      上下文对象.         (line   51)
* ExtendedInterpolation (configparser 中的类): 值的插值.     (line   35)
* EXTENDED_ARG (opcode):                 Python字节码说明.   (line  781)
* extendleft() (collections.deque 方法): deque 对象.         (line   55)
* extend_path() (在 pkgutil 模块中):     pkgutil --- 包扩展工具.
                                                             (line   18)
* Extension (distutils.core 中的类):     distutils core --- 分发包功能的核心.
                                                             (line  165)
* extension module – 扩展模块:           术语对照表.         (line  327)
* extension; module:                     标准类型层级结构.   (line    6)
* ExtensionFileLoader (importlib.machinery 中的类): importlib machinery -- Importers and path hooks.
                                                             (line  293)
* extensions_map (http.server.SimpleHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line  336)
* EXTENSION_SUFFIXES() (在 importlib.machinery 模块中): importlib machinery -- Importers and path hooks.
                                                             (line   47)
* External Data Representation:          数据流格式.         (line    6)
* External Data Representation <1>:      xdrlib --- 编码与解码 XDR 数据.
                                                             (line    8)
* ExternalClashError:                    异常<14>.           (line   23)
* ExternalEntityParserCreate() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line   36)
* ExternalEntityRefHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  277)
* external_attr (zipfile.ZipInfo 属性):  ZipInfo 对象.       (line  118)
* extra (zipfile.ZipInfo 属性):          ZipInfo 对象.       (line   85)
* extract() (tarfile.TarFile 方法):      TarFile 对象.       (line  140)
* extract() (traceback.StackSummary 类方法): StackSummary Objects.
                                                             (line   13)
* extract() (zipfile.ZipFile 方法):      ZipFile 对象.       (line  140)
* extractall() (tarfile.TarFile 方法):   TarFile 对象.       (line  118)
* extractall() (zipfile.ZipFile 方法):   ZipFile 对象.       (line  163)
* ExtractError:                          tarfile --- 读写tar归档文件.
                                                             (line  178)
* extractfile() (tarfile.TarFile 方法):  TarFile 对象.       (line  164)
* extract_cookies() (http.cookiejar.CookieJar 方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   30)
* extract_stack() (在 traceback 模块中): traceback --- 打印或检索堆栈回溯.
                                                             (line   94)
* extract_tb() (在 traceback 模块中):    traceback --- 打印或检索堆栈回溯.
                                                             (line   81)
* extract_version (zipfile.ZipInfo 属性): ZipInfo 对象.      (line   98)
* extsep() (在 os 模块中):               其他系统信息.       (line   90)
* EX_CANTCREAT() (在 os 模块中):         进程管理.           (line  171)
* EX_CONFIG() (在 os 模块中):            进程管理.           (line  202)
* EX_DATAERR() (在 os 模块中):           进程管理.           (line  123)
* EX_IOERR() (在 os 模块中):             进程管理.           (line  177)
* EX_NOHOST() (在 os 模块中):            进程管理.           (line  141)
* EX_NOINPUT() (在 os 模块中):           进程管理.           (line  129)
* EX_NOPERM() (在 os 模块中):            进程管理.           (line  196)
* EX_NOTFOUND() (在 os 模块中):          进程管理.           (line  208)
* EX_NOUSER() (在 os 模块中):            进程管理.           (line  135)
* EX_OK() (在 os 模块中):                进程管理.           (line  111)
* EX_OSERR() (在 os 模块中):             进程管理.           (line  159)
* EX_OSFILE() (在 os 模块中):            进程管理.           (line  165)
* EX_PROTOCOL() (在 os 模块中):          进程管理.           (line  190)
* EX_SOFTWARE() (在 os 模块中):          进程管理.           (line  153)
* EX_TEMPFAIL() (在 os 模块中):          进程管理.           (line  183)
* EX_UNAVAILABLE() (在 os 模块中):       进程管理.           (line  147)
* EX_USAGE() (在 os 模块中):             进程管理.           (line  117)
* f"; formatted string literal:          字符串和字节串字面值.
                                                             (line   54)
* f’; formatted string literal:          字符串和字节串字面值.
                                                             (line   54)
* f-string:                              字符串字面值拼接.   (line   20)
* f-string – f-字符串:                   术语对照表.         (line  332)
* fabs() (在 math 模块中):               数论与表示函数.     (line   32)
* factorial() (在 math 模块中):          数论与表示函数.     (line   36)
* factory() (importlib.util.LazyLoader 类方法): importlib util -- Utility code for importers.
                                                             (line  255)
* fail() (unittest.TestCase 方法):       测试用例.           (line  657)
* failfast (unittest.TestResult 属性):   Loading and running tests.
                                                             (line  287)
* failureException (unittest.TestCase 属性): 测试用例.       (line  662)
* failures (unittest.TestResult 属性):   Loading and running tests.
                                                             (line  242)
* FAIL_FAST() (在 doctest 模块中):       Option Flags.       (line  151)
* FakePath (test.support 中的类):        test support --- Utilities for the Python test suite.
                                                             (line 1111)
* False:                                 标准类型层级结构.   (line   69)
* false:                                 逻辑值检测.         (line    6)
* False <1>:                             逻辑值检测.         (line   19)
* False <2>:                             布尔值.             (line   12)
* False (Built-in object):               逻辑值检测.         (line   13)
* False (內置变量):                      内置常量.           (line    8)
* family (socket.socket 属性):           套接字对象.         (line  496)
* FancyGetopt (distutils.fancy_getopt 中的类): distutils fancy_getopt --- Wrapper around the standard getopt module.
                                                             (line   36)
* FancyURLopener (urllib.request 中的类): 已停用的接口.      (line  140)
* fancy_getopt() (在 distutils.fancy_getopt 模块中): distutils fancy_getopt --- Wrapper around the standard getopt module.
                                                             (line   20)
* fast (pickle.Pickler 属性):            模块接口.           (line  191)
* FastChildWatcher (asyncio 中的类):     进程监视器.         (line  114)
* fatalError() (xml.sax.handler.ErrorHandler 方法): ErrorHandler 对象.
                                                             (line   19)
* Fault (xmlrpc.client 中的类):          Fault 对象.         (line    6)
* faultCode (xmlrpc.client.Fault 属性):  Fault 对象.         (line   11)
* faulthandler (模块):                   faulthandler --- Dump the Python traceback.
                                                             (line    6)
* faultString (xmlrpc.client.Fault 属性): Fault 对象.        (line   15)
* fchdir() (在 os 模块中):               文件和目录.         (line  243)
* fchmod() (在 os 模块中):               文件描述符操作.     (line   83)
* fchown() (在 os 模块中):               文件描述符操作.     (line   94)
* FCICreate() (在 msilib 模块中):        msilib --- Read and write Microsoft Installer files.
                                                             (line   26)
* fcntl (模块):                          fcntl --- The fcntl and ioctl system calls.
                                                             (line    6)
* fcntl() (在 fcntl 模块中):             fcntl --- The fcntl and ioctl system calls.
                                                             (line   28)
* fd (selectors.SelectorKey 属性):       类<3>.              (line   38)
* fd() (在 turtle 模块中):               海龟动作.           (line    6)
* fdatasync() (在 os 模块中):            文件描述符操作.     (line  105)
* fdopen() (在 os 模块中):               创建文件对象.       (line    9)
* fd_count() (在 test.support 模块中):   test support --- Utilities for the Python test suite.
                                                             (line  242)
* Feature (msilib 中的类):               相关特性<3>.        (line    6)
* feature_external_ges() (在 xml.sax.handler 模块中): xml sax handler --- SAX 处理程序的基类.
                                                             (line   67)
* feature_external_pes() (在 xml.sax.handler 模块中): xml sax handler --- SAX 处理程序的基类.
                                                             (line   74)
* feature_namespaces() (在 xml.sax.handler 模块中): xml sax handler --- SAX 处理程序的基类.
                                                             (line   39)
* feature_namespace_prefixes() (在 xml.sax.handler 模块中): xml sax handler --- SAX 处理程序的基类.
                                                             (line   46)
* feature_string_interning() (在 xml.sax.handler 模块中): xml sax handler --- SAX 处理程序的基类.
                                                             (line   53)
* feature_validation() (在 xml.sax.handler 模块中): xml sax handler --- SAX 处理程序的基类.
                                                             (line   60)
* feed() (email.parser.BytesFeedParser 方法): FeedParser API.
                                                             (line   48)
* feed() (html.parser.HTMLParser 方法):  HTMLParser 方法.    (line    8)
* feed() (xml.etree.ElementTree.XMLParser 方法): XMLParser对象.
                                                             (line   23)
* feed() (xml.etree.ElementTree.XMLPullParser 方法): XMLPullParser对象.
                                                             (line   16)
* feed() (xml.sax.xmlreader.IncrementalParser 方法): IncrementalParser 对象.
                                                             (line    8)
* FeedParser (email.parser 中的类):      FeedParser API.     (line   61)
* fetch() (imaplib.IMAP4 方法):          IMAP4 Objects.      (line   99)
* Fetch() (msilib.View 方法):            View Objects.       (line   18)
* fetchall() (sqlite3.Cursor 方法):      Cursor 对象.        (line  150)
* fetchmany() (sqlite3.Cursor 方法):     Cursor 对象.        (line  135)
* fetchone() (sqlite3.Cursor 方法):      Cursor 对象.        (line  130)
* fflags (select.kevent 属性):           Kevent 对象.        (line   85)
* Field (dataclasses 中的类):            模块级装饰器、类和函数.
                                                             (line  195)
* field() (在 dataclasses 模块中):       模块级装饰器、类和函数.
                                                             (line  124)
* fieldnames (csv.csvreader 属性):       Reader 对象.        (line   29)
* fields (uuid.UUID 属性):               uuid --- UUID objects according to RFC 4122.
                                                             (line   94)
* fields() (在 dataclasses 模块中):      模块级装饰器、类和函数.
                                                             (line  211)
* field_size_limit() (在 csv 模块中):    模块内容<3>.        (line   81)
* file (pyclbr.Class 属性):              类对象<2>.          (line    9)
* file (pyclbr.Function 属性):           函数对象.           (line    8)
* file object – 文件对象:                术语对照表.         (line  337)
* file object; io module:                概述<8>.            (line    6)
* file object; open() built-in function: 内置函数.           (line  857)
* file-like object – 文件类对象:         术语对照表.         (line  350)
* file; byte-code:                       py_compile --- 编译 Python 源文件.
                                                             (line    8)
* file; byte-code <1>:                   imp --- Access the import internals.
                                                             (line   19)
* file; copying:                         shutil --- 高阶文件操作.
                                                             (line    8)
* file; large files:                     大文件支持.         (line    6)
* file; mime.types:                      mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line  105)
* file; modes:                           内置函数.           (line  876)
* filecmp (模块):                        filecmp --- 文件及目录的比较.
                                                             (line    6)
* fileConfig() (在 logging.config 模块中): 配置函数.         (line   52)
* FileCookieJar (http.cookiejar 中的类): http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   47)
* FileEntry (tkinter.tix 中的类):        File Selectors.     (line   50)
* FileExistsError:                       OS 异常.            (line   55)
* FileFinder (importlib.machinery 中的类): importlib machinery -- Importers and path hooks.
                                                             (line  153)
* FileHandler (logging 中的类):          FileHandler.        (line    9)
* FileHandler (urllib.request 中的类):   urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  343)
* FileInput (fileinput 中的类):          fileinput --- 迭代来自多个输入流的行.
                                                             (line  110)
* fileinput (模块):                      fileinput --- 迭代来自多个输入流的行.
                                                             (line    6)
* FileIO (io 中的类):                    原始文件 I/O.       (line    6)
* filelineno() (在 fileinput 模块中):    fileinput --- 迭代来自多个输入流的行.
                                                             (line   83)
* FileLoader (importlib.abc 中的类):     importlib abc —— 关于导入的抽象基类.
                                                             (line  410)
* filemode() (在 stat 模块中):           stat --- 解析 stat 结果.
                                                             (line  112)
* filename (doctest.DocTest 属性):       DocTest 对象.       (line   36)
* filename (http.cookiejar.FileCookieJar 属性): CookieJar 和 FileCookieJar 对象.
                                                             (line  153)
* filename (OSError 属性):               具体异常.           (line  133)
* filename (SyntaxError 属性):           具体异常.           (line  216)
* filename (traceback.TracebackException 属性): TracebackException Objects.
                                                             (line   42)
* filename (tracemalloc.Frame 属性):     Frame.              (line   13)
* filename (zipfile.ZipFile 属性):       ZipFile 对象.       (line  260)
* filename (zipfile.ZipInfo 属性):       ZipInfo 对象.       (line   45)
* filename() (在 fileinput 模块中):      fileinput --- 迭代来自多个输入流的行.
                                                             (line   69)
* filename2 (OSError 属性):              具体异常.           (line  133)
* filenames; pathname expansion:         glob --- Unix 风格路径名模式扩展.
                                                             (line    8)
* filenames; wildcard expansion:         fnmatch --- Unix 文件名模式匹配.
                                                             (line    8)
* filename_only() (在 tabnanny 模块中):  tabnanny --- 模糊缩进检测.
                                                             (line   28)
* filename_pattern (tracemalloc.Filter 属性): 过滤器.        (line   53)
* fileno() (http.client.HTTPResponse 方法): HTTPResponse 对象.
                                                             (line   36)
* fileno() (io.IOBase 方法):             I/O 基类.           (line   51)
* fileno() (multiprocessing.connection.Connection 方法): 连接对象（Connection）<2>.
                                                             (line   28)
* fileno() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line   28)
* fileno() (ossaudiodev.oss_mixer_device 方法): Mixer Device Objects.
                                                             (line   14)
* fileno() (select.devpoll 方法):        /dev/poll 轮询对象. (line   24)
* fileno() (select.epoll 方法):          边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   71)
* fileno() (select.kqueue 方法):         Kqueue 对象.        (line   14)
* fileno() (selectors.DevpollSelector 方法): 类<3>.          (line  166)
* fileno() (selectors.EpollSelector 方法): 类<3>.            (line  157)
* fileno() (selectors.KqueueSelector 方法): 类<3>.           (line  177)
* fileno() (socket.socket 方法):         套接字对象.         (line   95)
* fileno() (socketserver.BaseServer 方法): Server 对象<2>.   (line   14)
* fileno() (telnetlib.Telnet 方法):      Telnet 对象.        (line   88)
* fileno() (在 fileinput 模块中):        fileinput --- 迭代来自多个输入流的行.
                                                             (line   73)
* FileNotFoundError:                     OS 异常.            (line   60)
* fileobj (selectors.SelectorKey 属性):  类<3>.              (line   34)
* FileSelectBox (tkinter.tix 中的类):    File Selectors.     (line   42)
* FileType (argparse 中的类):            FileType 对象.      (line    6)
* FileWrapper (wsgiref.util 中的类):     wsgiref util -- WSGI environment utilities.
                                                             (line  114)
* FILE_ATTRIBUTE_ARCHIVE() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_COMPRESSED() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_DEVICE() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_DIRECTORY() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_ENCRYPTED() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_HIDDEN() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_INTEGRITY_STREAM() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_NORMAL() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_NOT_CONTENT_INDEXED() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_NO_SCRUB_DATA() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_OFFLINE() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_READONLY() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_REPARSE_POINT() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_SPARSE_FILE() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_SYSTEM() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_TEMPORARY() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* FILE_ATTRIBUTE_VIRTUAL() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  367)
* file_created() (內置函数):             The Postinstallation script.
                                                             (line   23)
* file_dispatcher (asyncore 中的类):     asyncore --- 异步socket处理器.
                                                             (line  207)
* file_open() (urllib.request.FileHandler 方法): FileHandler 对象.
                                                             (line    6)
* file_size (zipfile.ZipInfo 属性):      ZipInfo 对象.       (line  134)
* file_wrapper (asyncore 中的类):        asyncore --- 异步socket处理器.
                                                             (line  216)
* fill() (textwrap.TextWrapper 方法):    textwrap --- 文本自动换行与填充.
                                                             (line  249)
* fill() (在 textwrap 模块中):           textwrap --- 文本自动换行与填充.
                                                             (line   26)
* fillcolor() (在 turtle 模块中):        颜色控制.           (line   53)
* filling() (在 turtle 模块中):          填充.               (line    6)
* filter (2to3 fixer):                   修复器.             (line   96)
* Filter (logging 中的类):               Filter 对象.        (line   12)
* filter (select.kevent 属性):           Kevent 对象.        (line   14)
* Filter (tracemalloc 中的类):           过滤器.             (line    6)
* filter() (logging.Filter 方法):        Filter 对象.        (line   18)
* filter() (logging.Handler 方法):       处理器对象.         (line   54)
* filter() (logging.Logger 方法):        记录器对象.         (line  208)
* filter() (內置函数):                   内置函数.           (line  473)
* filter() (在 curses 模块中):           函数<3>.            (line  101)
* filter() (在 fnmatch 模块中):          fnmatch --- Unix 文件名模式匹配.
                                                             (line   61)
* filterfalse() (在 itertools 模块中):   Itertool函数.       (line  255)
* filterwarnings() (在 warnings 模块中): Available Functions.
                                                             (line   76)
* FILTER_DIR() (在 unittest.mock 模块中): FILTER_DIR.        (line    6)
* filter_traces() (tracemalloc.Snapshot 方法): 快照.         (line   35)
* final() (在 typing 模块中):            类 函数和修饰器.    (line  634)
* Final() (在 typing 模块中):            类 函数和修饰器.    (line  852)
* finalization, of objects:              终结和内存释放.     (line    6)
* finalize (weakref 中的类):             weakref --- 弱引用. (line  177)
* finalizer:                             基本定制.           (line   46)
* finalize_options() (distutils.cmd.Command 方法): Creating a new Distutils command.
                                                             (line   30)
* find() (bytearray 方法):               bytes 和 bytearray 操作.
                                                             (line   68)
* find() (bytes 方法):                   bytes 和 bytearray 操作.
                                                             (line   68)
* find() (doctest.DocTestFinder 方法):   DocTestFinder 对象. (line   32)
* find() (mmap.mmap 方法):               mmap --- 内存映射文件支持.
                                                             (line  153)
* find() (str 方法):                     字符串的方法<2>.    (line   87)
* find() (xml.etree.ElementTree.Element 方法): 元素对象.     (line   87)
* find() (xml.etree.ElementTree.ElementTree 方法): ElementTree 对象.
                                                             (line   19)
* find() (在 gettext 模块中):            基于类的 API.       (line   12)
* findall() (re.Pattern 方法):           正则表达式对象 （正则对象）.
                                                             (line   64)
* findall() (xml.etree.ElementTree.Element 方法): 元素对象.  (line   94)
* findall() (xml.etree.ElementTree.ElementTree 方法): ElementTree 对象.
                                                             (line   23)
* findall() (在 re 模块中):              模块内容.           (line  174)
* findCaller() (logging.Logger 方法):    记录器对象.         (line  223)
* finder:                                查找器和加载器.     (line    6)
* Finder (importlib.abc 中的类):         importlib abc —— 关于导入的抽象基类.
                                                             (line   28)
* finder – 查找器:                       术语对照表.         (line  354)
* finder; find_spec:                     元路径.             (line    6)
* findfactor() (在 audioop 模块中):      audioop --- 处理原始音频数据.
                                                             (line   68)
* findfile() (在 test.support 模块中):   test support --- Utilities for the Python test suite.
                                                             (line  228)
* findfit() (在 audioop 模块中):         audioop --- 处理原始音频数据.
                                                             (line   76)
* finditer() (re.Pattern 方法):          正则表达式对象 （正则对象）.
                                                             (line   69)
* finditer() (在 re 模块中):             模块内容.           (line  183)
* findlabels() (在 dis 模块中):          分析函数.           (line  116)
* findlinestarts() (在 dis 模块中):      分析函数.           (line  107)
* findmatch() (在 mailcap 模块中):       mailcap --- Mailcap 文件处理.
                                                             (line   21)
* findmax() (在 audioop 模块中):         audioop --- 处理原始音频数据.
                                                             (line   85)
* findtext() (xml.etree.ElementTree.Element 方法): 元素对象. (line  101)
* findtext() (xml.etree.ElementTree.ElementTree 方法): ElementTree 对象.
                                                             (line   27)
* find_class() (pickle protocol):        限制全局变量.       (line    6)
* find_class() (pickle.Unpickler 方法):  模块接口.           (line  249)
* find_library() (在 ctypes.util 模块中): 工具函数.          (line   76)
* find_library_file() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  202)
* find_loader() (importlib.abc.PathEntryFinder 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  114)
* find_loader() (importlib.machinery.FileFinder 方法): importlib machinery -- Importers and path hooks.
                                                             (line  190)
* find_loader() (在 importlib 模块中):   函数<10>.           (line   35)
* find_loader() (在 pkgutil 模块中):     pkgutil --- 包扩展工具.
                                                             (line   76)
* find_longest_match() (difflib.SequenceMatcher 方法): SequenceMatcher 对象.
                                                             (line   54)
* find_module() (imp.NullImporter 方法): imp --- Access the import internals.
                                                             (line  346)
* find_module() (importlib.abc.Finder 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line   35)
* find_module() (importlib.abc.MetaPathFinder 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line   66)
* find_module() (importlib.abc.PathEntryFinder 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  133)
* find_module() (importlib.machinery.PathFinder 类方法): importlib machinery -- Importers and path hooks.
                                                             (line  134)
* find_module() (zipimport.zipimporter 方法): zipimporter 对象.
                                                             (line   18)
* find_module() (在 imp 模块中):         imp --- Access the import internals.
                                                             (line   41)
* find_msvcrt() (在 ctypes.util 模块中): 工具函数.           (line   84)
* find_spec() (importlib.abc.MetaPathFinder 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line   51)
* find_spec() (importlib.abc.PathEntryFinder 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  101)
* find_spec() (importlib.machinery.FileFinder 方法): importlib machinery -- Importers and path hooks.
                                                             (line  183)
* find_spec() (importlib.machinery.PathFinder 类方法): importlib machinery -- Importers and path hooks.
                                                             (line  112)
* find_spec() (在 importlib.util 模块中): importlib util -- Utility code for importers.
                                                             (line   97)
* find_unused_port() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  887)
* find_user_password() (urllib.request.HTTPPasswordMgr 方法): HTTPPasswordMgr 对象.
                                                             (line   15)
* find_user_password() (urllib.request.HTTPPasswordMgrWithPriorAuth 方法): HTTPPasswordMgrWithPriorAuth 对象.
                                                             (line   17)
* finish() (socketserver.BaseRequestHandler 方法): Request Handler Objects.
                                                             (line   35)
* finish_request() (socketserver.BaseServer 方法): Server 对象<2>.
                                                             (line  125)
* firstChild (xml.dom.Node 属性):        节点对象.           (line   45)
* firstkey() (dbm.gnu.gdbm 方法):        dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line   71)
* firstweekday() (在 calendar 模块中):   calendar --- 日历相关函数.
                                                             (line  257)
* fix_missing_locations() (在 ast 模块中): ast 中的辅助函数. (line   77)
* fix_sentence_endings (textwrap.TextWrapper 属性): textwrap --- 文本自动换行与填充.
                                                             (line  188)
* Flag (enum 中的类):                    模块内容<2>.        (line   26)
* flags (re.Pattern 属性):               正则表达式对象 （正则对象）.
                                                             (line   82)
* flags (select.kevent 属性):            Kevent 对象.        (line   47)
* flags() (在 sys 模块中):               sys --- 系统相关的参数和函数.
                                                             (line  350)
* flag_bits (zipfile.ZipInfo 属性):      ZipInfo 对象.       (line  106)
* flash() (在 curses 模块中):            函数<3>.            (line  110)
* flatten() (email.generator.BytesGenerator 方法): email generator 生成 MIME 文档.
                                                             (line   66)
* flatten() (email.generator.Generator 方法): email generator 生成 MIME 文档.
                                                             (line  147)
* flattening; objects:                   pickle --- Python 对象序列化.
                                                             (line    8)
* float (內置类):                        内置函数.           (line  488)
* floating point literal:                数字字面值.         (line    6)
* floating point; literals:              数字类型 --- int float complex.
                                                             (line   14)
* floating point; number:                标准类型层级结构.   (line   79)
* FloatingPointError:                    具体异常.           (line   24)
* FloatOperation (decimal 中的类):       信号.               (line   91)
* float_info() (在 sys 模块中):          sys --- 系统相关的参数和函数.
                                                             (line  418)
* float_repr_style() (在 sys 模块中):    sys --- 系统相关的参数和函数.
                                                             (line  485)
* flock() (在 fcntl 模块中):             fcntl --- The fcntl and ioctl system calls.
                                                             (line  108)
* floor division – 向下取整除法:         术语对照表.         (line  364)
* floor() (in module math):              数字类型 --- int float complex.
                                                             (line   92)
* floor() (在 math 模块中):              数论与表示函数.     (line   41)
* floordiv() (在 operator 模块中):       operator --- 标准运算符替代函数.
                                                             (line   77)
* flush() (bz2.BZ2Compressor 方法):      增量压缩和解压.     (line   22)
* flush() (formatter.writer 方法):       The Writer Interface.
                                                             (line   13)
* flush() (io.BufferedWriter 方法):      缓冲流.             (line  105)
* flush() (io.IOBase 方法):              I/O 基类.           (line   56)
* flush() (logging.Handler 方法):        处理器对象.         (line   60)
* flush() (logging.handlers.BufferingHandler 方法): MemoryHandler.
                                                             (line   25)
* flush() (logging.handlers.MemoryHandler 方法): MemoryHandler.
                                                             (line   52)
* flush() (logging.StreamHandler 方法):  StreamHandler.      (line   23)
* flush() (lzma.LZMACompressor 方法):    在内存中压缩和解压缩数据.
                                                             (line   72)
* flush() (mailbox.Mailbox 方法):        Mailbox 对象.       (line  197)
* flush() (mailbox.Maildir 方法):        Maildir.            (line   85)
* flush() (mailbox.MH 方法):             MH.                 (line   88)
* flush() (mmap.mmap 方法):              mmap --- 内存映射文件支持.
                                                             (line  161)
* flush() (zlib.Compress 方法):          zlib --- 与 gzip 兼容的压缩.
                                                             (line  154)
* flush() (zlib.Decompress 方法):        zlib --- 与 gzip 兼容的压缩.
                                                             (line  212)
* flushinp() (在 curses 模块中):         函数<3>.            (line  116)
* FlushKey() (在 winreg 模块中):         函数<11>.           (line  223)
* flush_headers() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  262)
* flush_softspace() (formatter.formatter 方法): The Formatter Interface.
                                                             (line   83)
* fma() (decimal.Context 方法):          上下文对象.         (line  252)
* fma() (decimal.Decimal 方法):          Decimal 对象.       (line  229)
* fmean() (在 statistics 模块中):        函数细节.           (line   42)
* fmod() (在 math 模块中):               数论与表示函数.     (line   46)
* FMT_BINARY() (在 plistlib 模块中):     plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line  178)
* FMT_XML() (在 plistlib 模块中):        plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line  172)
* fnmatch (模块):                        fnmatch --- Unix 文件名模式匹配.
                                                             (line    6)
* fnmatch() (在 fnmatch 模块中):         fnmatch --- Unix 文件名模式匹配.
                                                             (line   38)
* fnmatchcase() (在 fnmatch 模块中):     fnmatch --- Unix 文件名模式匹配.
                                                             (line   55)
* focus() (tkinter.ttk.Treeview 方法):   ttk Treeview.       (line   98)
* fold (datetime.datetime 属性):         datetime 对象.      (line  275)
* fold (datetime.time 属性):             time 对象.          (line   67)
* fold() (email.headerregistry.BaseHeader 方法): email headerregistry 自定义标头对象.
                                                             (line   59)
* fold() (email.policy.Compat32 方法):   email policy 策略对象.
                                                             (line  472)
* fold() (email.policy.EmailPolicy 方法): email policy 策略对象.
                                                             (line  363)
* fold() (email.policy.Policy 方法):     email policy 策略对象.
                                                             (line  255)
* fold_binary() (email.policy.Compat32 方法): email policy 策略对象.
                                                             (line  478)
* fold_binary() (email.policy.EmailPolicy 方法): email policy 策略对象.
                                                             (line  378)
* fold_binary() (email.policy.Policy 方法): email policy 策略对象.
                                                             (line  266)
* for; in comprehensions:                列表、集合与字典的显示.
                                                             (line   13)
* forget() (tkinter.ttk.Notebook 方法):  ttk Notebook.       (line   18)
* forget() (在 test.support 模块中):     test support --- Utilities for the Python test suite.
                                                             (line  162)
* fork() (在 os 模块中):                 进程管理.           (line  214)
* fork() (在 pty 模块中):                pty --- 伪终端工具. (line   18)
* ForkingMixIn (socketserver 中的类):    Server Creation Notes.
                                                             (line   28)
* ForkingTCPServer (socketserver 中的类): Server Creation Notes.
                                                             (line   62)
* ForkingUDPServer (socketserver 中的类): Server Creation Notes.
                                                             (line   62)
* forkpty() (在 os 模块中):              进程管理.           (line  232)
* Form (tkinter.tix 中的类):             Form Geometry Manager.
                                                             (line    9)
* format (memoryview 属性):              内存视图.           (line  388)
* format (multiprocessing.shared_memory.ShareableList 属性): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  235)
* format (struct.Struct 属性):           类<2>.              (line   48)
* format() (built-in function); __str__() (object method): 基本定制.
                                                             (line  105)
* format() (logging.Formatter 方法):     格式器对象.         (line   40)
* format() (logging.Handler 方法):       处理器对象.         (line   86)
* format() (pprint.PrettyPrinter 方法):  PrettyPrinter 对象. (line   34)
* format() (str 方法):                   字符串的方法<2>.    (line  100)
* format() (string.Formatter 方法):      自定义字符串格式化. (line   15)
* format() (traceback.StackSummary 方法): StackSummary Objects.
                                                             (line   36)
* format() (traceback.TracebackException 方法): TracebackException Objects.
                                                             (line   73)
* format() (tracemalloc.Traceback 方法): 回溯<4>.            (line   25)
* format() (內置函数):                   内置函数.           (line  538)
* format() (在 locale 模块中):           locale --- 国际化服务.
                                                             (line  389)
* formataddr() (在 email.utils 模块中):  email utils 其他工具.
                                                             (line   54)
* formatargspec() (在 inspect 模块中):   类与函数<2>.        (line   92)
* formatargvalues() (在 inspect 模块中): 类与函数<2>.        (line  121)
* formatdate() (在 email.utils 模块中):  email utils 其他工具.
                                                             (line  117)
* FormatError:                           异常<14>.           (line   29)
* FormatError() (在 ctypes 模块中):      工具函数.           (line   92)
* formatException() (logging.Formatter 方法): 格式器对象.    (line   83)
* formatmonth() (calendar.HTMLCalendar 方法): calendar --- 日历相关函数.
                                                             (line  140)
* formatmonth() (calendar.TextCalendar 方法): calendar --- 日历相关函数.
                                                             (line  112)
* formatStack() (logging.Formatter 方法): 格式器对象.        (line   89)
* formatted string literal:              字符串字面值拼接.   (line   20)
* Formatter (logging 中的类):            格式器对象.         (line   21)
* Formatter (string 中的类):             自定义字符串格式化. (line   11)
* formatter (模块):                      formatter --- 通用格式化输出.
                                                             (line    6)
* formatTime() (logging.Formatter 方法): 格式器对象.         (line   56)
* formatting, string (%):                printf 风格的字符串格式化.
                                                             (line    6)
* formatting; bytearray (%):             printf 风格的字节串格式化.
                                                             (line    6)
* formatting; bytes (%):                 printf 风格的字节串格式化.
                                                             (line    6)
* formatwarning() (在 warnings 模块中):  Available Functions.
                                                             (line   67)
* formatyear() (calendar.HTMLCalendar 方法): calendar --- 日历相关函数.
                                                             (line  145)
* formatyear() (calendar.TextCalendar 方法): calendar --- 日历相关函数.
                                                             (line  123)
* formatyearpage() (calendar.HTMLCalendar 方法): calendar --- 日历相关函数.
                                                             (line  150)
* format_datetime() (在 email.utils 模块中): email utils 其他工具.
                                                             (line  137)
* format_exc() (在 traceback 模块中):    traceback --- 打印或检索堆栈回溯.
                                                             (line  135)
* format_exception() (在 traceback 模块中): traceback --- 打印或检索堆栈回溯.
                                                             (line  122)
* format_exception_only() (traceback.TracebackException 方法): TracebackException Objects.
                                                             (line   88)
* format_exception_only() (在 traceback 模块中): traceback --- 打印或检索堆栈回溯.
                                                             (line  111)
* format_field() (string.Formatter 方法): 自定义字符串格式化.
                                                             (line   81)
* format_help() (argparse.ArgumentParser 方法): 打印帮助.    (line   28)
* format_list() (在 traceback 模块中):   traceback --- 打印或检索堆栈回溯.
                                                             (line  101)
* format_map() (str 方法):               字符串的方法<2>.    (line  124)
* format_stack() (在 traceback 模块中):  traceback --- 打印或检索堆栈回溯.
                                                             (line  144)
* format_stack_entry() (bdb.Bdb 方法):   bdb --- Debugger framework.
                                                             (line  342)
* format_string() (在 locale 模块中):    locale --- 国际化服务.
                                                             (line  372)
* format_tb() (在 traceback 模块中):     traceback --- 打印或检索堆栈回溯.
                                                             (line  140)
* format_usage() (argparse.ArgumentParser 方法): 打印帮助.   (line   23)
* FORMAT_VALUE (opcode):                 Python字节码说明.   (line  787)
* Fortran contiguous:                    形状，步幅，子偏移量.
                                                             (line   24)
* Fortran contiguous <1>:                术语对照表.         (line  222)
* forward() (在 turtle 模块中):          海龟动作.           (line    6)
* ForwardRef (typing 中的类):            类 函数和修饰器.    (line  555)
* FOR_ITER (opcode):                     Python字节码说明.   (line  625)
* found_terminator() (asynchat.async_chat 方法): asynchat --- 异步 socket 指令/响应 处理器.
                                                             (line   76)
* fpathconf() (在 os 模块中):            文件描述符操作.     (line  113)
* fqdn (smtpd.SMTPChannel 属性):         SMTPChannel 对象.   (line   89)
* Fraction (fractions 中的类):           fractions --- 分数. (line   14)
* fractions (模块):                      fractions --- 分数. (line    6)
* frame (tkinter.scrolledtext.ScrolledText 属性): tkinter scrolledtext --- 滚动文字控件.
                                                             (line   20)
* Frame (tracemalloc 中的类):            Frame.              (line    6)
* FrameSummary (traceback 中的类):       FrameSummary Objects.
                                                             (line   11)
* FrameType() (在 types 模块中):         标准解释器类型.     (line  166)
* free():                                概述<16>.           (line   23)
* free; variable:                        名称的绑定.         (line   21)
* freefunc (C 类型):                     Slot Type typedefs. (line   37)
* freeze utility:                        导入模块<2>.        (line  259)
* freeze() (在 gc 模块中):               gc --- 垃圾回收器接口.
                                                             (line  148)
* freeze_support() (在 multiprocessing 模块中): 杂项<3>.     (line   40)
* frexp() (在 math 模块中):              数论与表示函数.     (line   58)
* from; import statement:                名称的绑定.         (line    8)
* from; import statement <1>:            import 语句.        (line   43)
* from; yield from expression:           yield 表达式.       (line   51)
* frombuf() (tarfile.TarInfo 类方法):    TarInfo 对象.       (line   17)
* frombytes() (array.array 方法):        array --- 高效的数值数组.
                                                             (line  138)
* fromfd() (select.epoll 方法):          边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   75)
* fromfd() (select.kqueue 方法):         Kqueue 对象.        (line   18)
* fromfd() (在 socket 模块中):           创建套接字.         (line  130)
* fromfile() (array.array 方法):         array --- 高效的数值数组.
                                                             (line  146)
* fromhex() (bytearray 类方法):          bytearray 对象.     (line   30)
* fromhex() (bytes 类方法):              bytes 对象.         (line   50)
* fromhex() (float 类方法):              浮点类型的附加方法. (line   33)
* fromisocalendar() (datetime.date 类方法): date 对象.       (line   71)
* fromisocalendar() (datetime.datetime 类方法): datetime 对象.
                                                             (line  201)
* fromisoformat() (datetime.date 类方法): date 对象.         (line   57)
* fromisoformat() (datetime.datetime 类方法): datetime 对象. (line  167)
* fromisoformat() (datetime.time 类方法): time 对象.         (line  100)
* fromkeys() (collections.Counter 方法): Counter 对象.       (line   94)
* fromkeys() (dict 类方法):              映射类型 --- dict.  (line  132)
* fromlist() (array.array 方法):         array --- 高效的数值数组.
                                                             (line  152)
* fromordinal() (datetime.date 类方法):  date 对象.          (line   48)
* fromordinal() (datetime.datetime 类方法): datetime 对象.   (line  144)
* fromshare() (在 socket 模块中):        创建套接字.         (line  144)
* fromstring() (array.array 方法):       array --- 高效的数值数组.
                                                             (line  157)
* fromstring() (在 xml.etree.ElementTree 模块中): 函数<6>.   (line   88)
* fromstringlist() (在 xml.etree.ElementTree 模块中): 函数<6>.
                                                             (line   95)
* fromtarfile() (tarfile.TarInfo 类方法): TarInfo 对象.      (line   23)
* fromtimestamp() (datetime.date 类方法): date 对象.         (line   32)
* fromtimestamp() (datetime.datetime 类方法): datetime 对象. (line   86)
* fromunicode() (array.array 方法):      array --- 高效的数值数组.
                                                             (line  163)
* fromutc() (datetime.timezone 方法):    timezone 对象.      (line   50)
* fromutc() (datetime.tzinfo 方法):      tzinfo 对象.        (line  139)
* from_address() (ctypes._CData 方法):   数据类型<2>.        (line   37)
* from_buffer() (ctypes._CData 方法):    数据类型<2>.        (line   17)
* from_buffer_copy() (ctypes._CData 方法): 数据类型<2>.      (line   27)
* from_bytes() (int 类方法):             整数类型的附加方法. (line   61)
* from_callable() (inspect.Signature 类方法): Introspecting callables with the Signature object.
                                                             (line  126)
* from_decimal() (fractions.Fraction 方法): fractions --- 分数.
                                                             (line  103)
* from_exception() (traceback.TracebackException 类方法): TracebackException Objects.
                                                             (line   63)
* from_file() (zipfile.ZipInfo 类方法):  ZipInfo 对象.       (line   12)
* from_float() (decimal.Decimal 方法):   Decimal 对象.       (line  206)
* from_float() (fractions.Fraction 方法): fractions --- 分数.
                                                             (line   94)
* from_iterable() (itertools.chain 类方法): Itertool函数.    (line   91)
* from_list() (traceback.StackSummary 类方法): StackSummary Objects.
                                                             (line   29)
* from_param() (ctypes._CData 方法):     数据类型<2>.        (line   45)
* from_samples() (statistics.NormalDist 类方法): NormalDist 对象.
                                                             (line   39)
* from_traceback() (dis.Bytecode 类方法): 字节码分析.        (line   28)
* FrozenImporter (importlib.machinery 中的类): importlib machinery -- Importers and path hooks.
                                                             (line   77)
* FrozenInstanceError:                   异常<17>.           (line    6)
* FrozenSet (typing 中的类):             类 函数和修饰器.    (line  260)
* frozenset (內置类):                    集合类型 --- set frozenset.
                                                             (line   28)
* fsdecode() (在 os 模块中):             进程参数.           (line   79)
* fsencode() (在 os 模块中):             进程参数.           (line   66)
* fspath() (在 os 模块中):               进程参数.           (line   92)
* fstat() (在 os 模块中):                文件描述符操作.     (line  130)
* fstatvfs() (在 os 模块中):             文件描述符操作.     (line  142)
* fstring:                               字符串字面值拼接.   (line   20)
* fsum() (在 math 模块中):               数论与表示函数.     (line   65)
* fsync() (在 os 模块中):                文件描述符操作.     (line  150)
* fs_is_case_insensitive() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  924)
* FS_NONASCII() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line   48)
* FTP:                                   urllib request Restrictions.
                                                             (line   37)
* FTP (ftplib 中的类):                   ftplib --- FTP 协议客户端.
                                                             (line   36)
* FTP; ftplib (standard module):         ftplib --- FTP 协议客户端.
                                                             (line    8)
* FTP; protocol:                         urllib request Restrictions.
                                                             (line    6)
* FTP; protocol <1>:                     ftplib --- FTP 协议客户端.
                                                             (line    8)
* FTPHandler (urllib.request 中的类):    urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  353)
* ftplib (模块):                         ftplib --- FTP 协议客户端.
                                                             (line    6)
* ftp_open() (urllib.request.FTPHandler 方法): FTPHandler 对象.
                                                             (line    6)
* FTP_TLS (ftplib 中的类):               ftplib --- FTP 协议客户端.
                                                             (line   67)
* ftruncate() (在 os 模块中):            文件描述符操作.     (line  161)
* Full:                                  queue --- 一个同步的队列类.
                                                             (line   73)
* full() (asyncio.Queue 方法):           Queue.              (line   30)
* full() (multiprocessing.Queue 方法):   管道和队列.         (line   97)
* full() (queue.Queue 方法):             Queue对象.          (line   20)
* fullmatch() (re.Pattern 方法):         正则表达式对象 （正则对象）.
                                                             (line   45)
* fullmatch() (在 re 模块中):            模块内容.           (line  130)
* full_url (urllib.request.Request 属性): Request 对象.      (line   10)
* func (functools.partial 属性):         partial 对象.       (line    9)
* funcattrs (2to3 fixer):                修复器.             (line  100)
* Function (symtable 中的类):            Examining Symbol Tables.
                                                             (line   66)
* function – 函数:                       术语对照表.         (line  371)
* function annotation – 函数标注:        术语对照表.         (line  377)
* function; annotations:                 函数标注.           (line    6)
* function; annotations <1>:             函数定义.           (line   77)
* function; argument:                    标准类型层级结构.   (line  224)
* function; call:                        标准类型层级结构.   (line  224)
* function; call <1>:                    调用.               (line   99)
* function; call <2>:                    调用.               (line  105)
* function; definition:                  return 语句.        (line    6)
* function; definition <1>:              函数定义.           (line    6)
* function; generator:                   yield 语句.         (line    6)
* function; name:                        函数定义.           (line    6)
* function; name <1>:                    函数定义.           (line    6)
* FunctionTestCase (unittest 中的类):    测试用例.           (line  888)
* FunctionType() (在 types 模块中):      标准解释器类型.     (line   17)
* functools (模块):                      functools --- 高阶函数和可调用对象上的操作.
                                                             (line    6)
* funny_files (filecmp.dircmp 属性):     dircmp 类.          (line   86)
* future (2to3 fixer):                   修复器.             (line  105)
* Future (asyncio 中的类):               Future 对象<2>.     (line    6)
* Future (concurrent.futures 中的类):    Future 对象.        (line    9)
* future; statement:                     future 语句.        (line    6)
* FutureWarning:                         警告.               (line   36)
* fwalk() (在 os 模块中):                文件和目录.         (line 1378)
* f_back (frame attribute):              标准类型层级结构.   (line  535)
* f_builtins (frame attribute):          标准类型层级结构.   (line  535)
* f_code (frame attribute):              标准类型层级结构.   (line  535)
* f_contiguous (memoryview 属性):        内存视图.           (line  438)
* f_globals (frame attribute):           标准类型层级结构.   (line  535)
* f_lasti (frame attribute):             标准类型层级结构.   (line  535)
* f_lineno (frame attribute):            标准类型层级结构.   (line  544)
* f_locals (frame attribute):            标准类型层级结构.   (line  535)
* F_LOCK() (在 os 模块中):               文件描述符操作.     (line  204)
* F_OK() (在 os 模块中):                 文件和目录.         (line   89)
* F_TEST() (在 os 模块中):               文件描述符操作.     (line  204)
* F_TLOCK() (在 os 模块中):              文件描述符操作.     (line  204)
* f_trace (frame attribute):             标准类型层级结构.   (line  544)
* f_trace_lines (frame attribute):       标准类型层级结构.   (line  544)
* f_trace_opcodes (frame attribute):     标准类型层级结构.   (line  544)
* F_ULOCK() (在 os 模块中):              文件描述符操作.     (line  204)
* G.722:                                 aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  140)
* gaierror:                              异常<11>.           (line   24)
* gamma() (在 math 模块中):              特殊函数.           (line   26)
* gammavariate() (在 random 模块中):     实值分布.           (line   39)
* garbage collection:                    对象、值与类型.     (line   29)
* garbage collection – 垃圾回收:         术语对照表.         (line  404)
* garbage() (在 gc 模块中):              gc --- 垃圾回收器接口.
                                                             (line  172)
* gather() (curses.textpad.Textbox 方法): 文本框对象.        (line   97)
* gather() (在 asyncio 模块中):          并发运行任务.       (line    6)
* gauss() (在 random 模块中):            实值分布.           (line   50)
* gc (模块):                             gc --- 垃圾回收器接口.
                                                             (line    6)
* gcd() (在 fractions 模块中):           fractions --- 分数. (line  155)
* gcd() (在 math 模块中):                数论与表示函数.     (line   81)
* gc_collect() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  473)
* ge() (在 operator 模块中):             operator --- 标准运算符替代函数.
                                                             (line   19)
* generate_help() (distutils.fancy_getopt.FancyGetopt 方法): distutils fancy_getopt --- Wrapper around the standard getopt module.
                                                             (line   68)
* generate_tokens() (在 tokenize 模块中): 对输入进行解析标记.
                                                             (line   37)
* generator:                             术语对照表.         (line  411)
* Generator (collections.abc 中的类):    容器抽象基类.       (line  147)
* Generator (email.generator 中的类):    email generator 生成 MIME 文档.
                                                             (line  116)
* Generator (typing 中的类):             类 函数和修饰器.    (line  369)
* generator – 生成器:                    术语对照表.         (line  411)
* generator expression:                  术语对照表.         (line  428)
* generator expression – 生成器表达式:   术语对照表.         (line  428)
* generator iterator – 生成器迭代器:     术语对照表.         (line  418)
* generator; expression:                 生成器表达式<2>.    (line    6)
* generator; function:                   标准类型层级结构.   (line  337)
* generator; function <1>:               yield 表达式.       (line    6)
* generator; function <2>:               yield 语句.         (line    6)
* generator; iterator:                   标准类型层级结构.   (line  337)
* generator; iterator <1>:               yield 语句.         (line    6)
* GeneratorExit:                         具体异常.           (line   28)
* GeneratorType() (在 types 模块中):     标准解释器类型.     (line   26)
* Generic (typing 中的类):               类 函数和修饰器.    (line   43)
* generic function – 泛型函数:           术语对照表.         (line  436)
* generic; special; attribute:           标准类型层级结构.   (line   10)
* generic_visit() (ast.NodeVisitor 方法): ast 中的辅助函数.  (line  132)
* genops() (在 pickletools 模块中):      编程接口<2>.        (line   19)
* gen_lib_options() (在 distutils.ccompiler 模块中): distutils ccompiler --- CCompiler基类.
                                                             (line   14)
* gen_preprocess_options() (在 distutils.ccompiler 模块中): distutils ccompiler --- CCompiler基类.
                                                             (line   24)
* gen_uuid() (在 msilib 模块中):         msilib --- Read and write Microsoft Installer files.
                                                             (line  109)
* geometric_mean() (在 statistics 模块中): 函数细节.         (line   55)
* get() (asyncio.Queue 方法):            Queue.              (line   37)
* get() (configparser.ConfigParser 方法): ConfigParser 对象. (line  164)
* get() (contextvars.Context 方法):      手动上下文管理.     (line   77)
* get() (contextvars.ContextVar 方法):   上下文变量.         (line   27)
* get() (dict 方法):                     映射类型 --- dict.  (line  141)
* get() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  200)
* get() (email.message.Message 方法):    email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  294)
* get() (mailbox.Mailbox 方法):          Mailbox 对象.       (line  114)
* get() (multiprocessing.pool.AsyncResult 方法): 进程池.     (line  162)
* get() (multiprocessing.Queue 方法):    管道和队列.         (line  119)
* get() (multiprocessing.SimpleQueue 方法): 管道和队列.      (line  181)
* get() (ossaudiodev.oss_mixer_device 方法): Mixer Device Objects.
                                                             (line   60)
* get() (queue.Queue 方法):              Queue对象.          (line   39)
* get() (queue.SimpleQueue 方法):        SimpleQueue 对象.   (line   35)
* get() (tkinter.ttk.Combobox 方法):     ttk Combobox.       (line   15)
* get() (tkinter.ttk.Spinbox 方法):      ttk Spinbox.        (line    8)
* get() (types.MappingProxyType 方法):   标准解释器类型.     (line  219)
* get() (xml.etree.ElementTree.Element 方法): 元素对象.      (line   53)
* get() (在 webbrowser 模块中):          webbrowser --- 方便的Web浏览器控制器.
                                                             (line   64)
* getacl() (imaplib.IMAP4 方法):         IMAP4 Objects.      (line  106)
* getaddresses() (在 email.utils 模块中): email utils 其他工具.
                                                             (line   66)
* getaddrinfo() (asyncio.loop 方法):     DNS.                (line    6)
* getaddrinfo() (在 socket 模块中):      其他功能<2>.        (line   16)
* getallocatedblocks() (在 sys 模块中):  sys --- 系统相关的参数和函数.
                                                             (line  496)
* getandroidapilevel() (在 sys 模块中):  sys --- 系统相关的参数和函数.
                                                             (line  508)
* getannotation() (imaplib.IMAP4 方法):  IMAP4 Objects.      (line  111)
* getargspec() (在 inspect 模块中):      类与函数<2>.        (line   17)
* getargvalues() (在 inspect 模块中):    类与函数<2>.        (line   81)
* getatime() (在 os.path 模块中):        os path --- 常用路径操作.
                                                             (line  148)
* getattr() (內置函数):                  内置函数.           (line  566)
* getattrfunc (C 类型):                  Slot Type typedefs. (line   53)
* getAttribute() (xml.dom.Element 方法): 元素对象<2>.        (line   30)
* getAttributeNode() (xml.dom.Element 方法): 元素对象<2>.    (line   35)
* getAttributeNodeNS() (xml.dom.Element 方法): 元素对象<2>.  (line   44)
* getAttributeNS() (xml.dom.Element 方法): 元素对象<2>.      (line   39)
* getattrofunc (C 类型):                 Slot Type typedefs. (line   63)
* getattr_static() (在 inspect 模块中):  Fetching attributes statically.
                                                             (line   16)
* GetBase() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line   26)
* getbegyx() (curses.window 方法):       Window 对象.        (line  192)
* getbkgd() (curses.window 方法):        Window 对象.        (line  196)
* getblocking() (socket.socket 方法):    套接字对象.         (line  130)
* getboolean() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line  194)
* getbuffer() (io.BytesIO 方法):         缓冲流.             (line   19)
* getbufferproc (C 类型):                Slot Type typedefs. (line  105)
* getByteStream() (xml.sax.xmlreader.InputSource 方法): InputSource 对象.
                                                             (line   46)
* getcallargs() (在 inspect 模块中):     类与函数<2>.        (line  140)
* getcanvas() (在 turtle 模块中):        设置与特殊方法.     (line   52)
* getcapabilities() (nntplib.NNTP 方法): 方法<3>.            (line   33)
* getcaps() (在 mailcap 模块中):         mailcap --- Mailcap 文件处理.
                                                             (line   47)
* getch() (curses.window 方法):          Window 对象.        (line  200)
* getch() (在 msvcrt 模块中):            控制台 I/O.         (line   10)
* getCharacterStream() (xml.sax.xmlreader.InputSource 方法): InputSource 对象.
                                                             (line   60)
* getche() (在 msvcrt 模块中):           控制台 I/O.         (line   21)
* getcheckinterval() (在 sys 模块中):    sys --- 系统相关的参数和函数.
                                                             (line  516)
* getChild() (logging.Logger 方法):      记录器对象.         (line   79)
* getchildren() (xml.etree.ElementTree.Element 方法): 元素对象.
                                                             (line  110)
* getclasstree() (在 inspect 模块中):    类与函数<2>.        (line    6)
* getclosurevars() (在 inspect 模块中):  类与函数<2>.        (line  170)
* GetColumnInfo() (msilib.View 方法):    View Objects.       (line   12)
* getColumnNumber() (xml.sax.xmlreader.Locator 方法): Locator 对象.
                                                             (line    8)
* getcomments() (在 inspect 模块中):     Retrieving source code.
                                                             (line   17)
* getcompname() (aifc.aifc 方法):        aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   62)
* getcompname() (sunau.AU_read 方法):    AU_read 对象.       (line   35)
* getcompname() (wave.Wave_read 方法):   Wave_read对象.      (line   33)
* getcomptype() (aifc.aifc 方法):        aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   57)
* getcomptype() (sunau.AU_read 方法):    AU_read 对象.       (line   30)
* getcomptype() (wave.Wave_read 方法):   Wave_read对象.      (line   29)
* getContentHandler() (xml.sax.xmlreader.XMLReader 方法): XMLReader 对象.
                                                             (line   20)
* getcontext() (在 decimal 模块中):      上下文对象.         (line   12)
* getcoroutinelocals() (在 inspect 模块中): Current State of Generators and Coroutines.
                                                             (line   73)
* getcoroutinestate() (在 inspect 模块中): Current State of Generators and Coroutines.
                                                             (line   28)
* getctime() (在 os.path 模块中):        os path --- 常用路径操作.
                                                             (line  162)
* getcwd() (在 os 模块中):               文件和目录.         (line  252)
* getcwdb() (在 os 模块中):              文件和目录.         (line  256)
* getcwdu (2to3 fixer):                  修复器.             (line  109)
* getdecoder() (在 codecs 模块中):       codecs --- 编解码器注册和相关基类.
                                                             (line   92)
* getdefaultencoding() (在 sys 模块中):  sys --- 系统相关的参数和函数.
                                                             (line  523)
* getdefaultlocale() (在 locale 模块中): locale --- 国际化服务.
                                                             (line  283)
* getdefaulttimeout() (在 socket 模块中): 其他功能<2>.       (line  270)
* getdlopenflags() (在 sys 模块中):      sys --- 系统相关的参数和函数.
                                                             (line  527)
* getdoc() (在 inspect 模块中):          Retrieving source code.
                                                             (line    6)
* getDOMImplementation() (在 xml.dom 模块中): 模块内容<6>.   (line   15)
* getDTDHandler() (xml.sax.xmlreader.XMLReader 方法): XMLReader 对象.
                                                             (line   29)
* getEffectiveLevel() (logging.Logger 方法): 记录器对象.     (line   72)
* getegid() (在 os 模块中):              进程参数.           (line  149)
* getElementsByTagName() (xml.dom.Document 方法): 文档对象.  (line   52)
* getElementsByTagName() (xml.dom.Element 方法): 元素对象<2>.
                                                             (line   13)
* getElementsByTagNameNS() (xml.dom.Document 方法): 文档对象.
                                                             (line   57)
* getElementsByTagNameNS() (xml.dom.Element 方法): 元素对象<2>.
                                                             (line   17)
* getencoder() (在 codecs 模块中):       codecs --- 编解码器注册和相关基类.
                                                             (line   86)
* getEncoding() (xml.sax.xmlreader.InputSource 方法): InputSource 对象.
                                                             (line   32)
* getEntityResolver() (xml.sax.xmlreader.XMLReader 方法): XMLReader 对象.
                                                             (line   38)
* getenv() (在 os 模块中):               进程参数.           (line  117)
* getenvb() (在 os 模块中):              进程参数.           (line  129)
* getErrorHandler() (xml.sax.xmlreader.XMLReader 方法): XMLReader 对象.
                                                             (line   48)
* geteuid() (在 os 模块中):              进程参数.           (line  155)
* getEvent() (xml.dom.pulldom.DOMEventStream 方法): DOMEventStream 对象.
                                                             (line   10)
* getEventCategory() (logging.handlers.NTEventLogHandler 方法): NTEventLogHandler.
                                                             (line   35)
* getEventType() (logging.handlers.NTEventLogHandler 方法): NTEventLogHandler.
                                                             (line   40)
* getException() (xml.sax.SAXException 方法): SAXException 对象.
                                                             (line   12)
* getFeature() (xml.sax.xmlreader.XMLReader 方法): XMLReader 对象.
                                                             (line   65)
* GetFieldCount() (msilib.Record 方法):  Record Objects.     (line    6)
* getfile() (在 inspect 模块中):         Retrieving source code.
                                                             (line   26)
* getfilesystemencodeerrors() (在 sys 模块中): sys --- 系统相关的参数和函数.
                                                             (line  567)
* getfilesystemencoding() (在 sys 模块中): sys --- 系统相关的参数和函数.
                                                             (line  535)
* getfirst() (cgi.FieldStorage 方法):    更高层级的接口.     (line   45)
* getfloat() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line  187)
* getfmts() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line   77)
* getfqdn() (在 socket 模块中):          其他功能<2>.        (line   61)
* getframeinfo() (在 inspect 模块中):    The interpreter stack.
                                                             (line   46)
* getframerate() (aifc.aifc 方法):       aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   49)
* getframerate() (sunau.AU_read 方法):   AU_read 对象.       (line   22)
* getframerate() (wave.Wave_read 方法):  Wave_read对象.      (line   21)
* getfullargspec() (在 inspect 模块中):  类与函数<2>.        (line   36)
* getgeneratorlocals() (在 inspect 模块中): Current State of Generators and Coroutines.
                                                             (line   53)
* getgeneratorstate() (在 inspect 模块中): Current State of Generators and Coroutines.
                                                             (line   12)
* getgid() (在 os 模块中):               进程参数.           (line  161)
* getgrall() (在 grp 模块中):            grp --- 组数据库.   (line   49)
* getgrgid() (在 grp 模块中):            grp --- 组数据库.   (line   36)
* getgrnam() (在 grp 模块中):            grp --- 组数据库.   (line   44)
* getgrouplist() (在 os 模块中):         进程参数.           (line  167)
* getgroups() (在 os 模块中):            进程参数.           (line  177)
* getheader() (http.client.HTTPResponse 方法): HTTPResponse 对象.
                                                             (line   24)
* getheaders() (http.client.HTTPResponse 方法): HTTPResponse 对象.
                                                             (line   32)
* gethostbyaddr() (in module socket):    进程参数.           (line  428)
* gethostbyaddr() (在 socket 模块中):    其他功能<2>.        (line  102)
* gethostbyname() (在 socket 模块中):    其他功能<2>.        (line   69)
* gethostbyname_ex() (在 socket 模块中): 其他功能<2>.        (line   80)
* gethostname() (in module socket):      进程参数.           (line  428)
* gethostname() (在 socket 模块中):      其他功能<2>.        (line   93)
* getincrementaldecoder() (在 codecs 模块中): codecs --- 编解码器注册和相关基类.
                                                             (line  105)
* getincrementalencoder() (在 codecs 模块中): codecs --- 编解码器注册和相关基类.
                                                             (line   98)
* getinfo() (zipfile.ZipFile 方法):      ZipFile 对象.       (line   79)
* getinnerframes() (在 inspect 模块中):  The interpreter stack.
                                                             (line   62)
* GetInputContext() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line   31)
* getint() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line  180)
* GetInteger() (msilib.Record 方法):     Record Objects.     (line   11)
* getitem() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line  177)
* getiterator() (xml.etree.ElementTree.Element 方法): 元素对象.
                                                             (line  115)
* getiterator() (xml.etree.ElementTree.ElementTree 方法): ElementTree 对象.
                                                             (line   31)
* getiterfunc (C 类型):                  Slot Type typedefs. (line   95)
* getitimer() (在 signal 模块中):        模块内容<5>.        (line  341)
* getkey() (curses.window 方法):         Window 对象.        (line  214)
* GetLastError() (在 ctypes 模块中):     工具函数.           (line   98)
* getLength() (xml.sax.xmlreader.Attributes 方法): Attributes 接口.
                                                             (line   10)
* getLevelName() (在 logging 模块中):    模块级别函数.       (line  168)
* getline() (在 linecache 模块中):       linecache --- 随机读写文本行.
                                                             (line   20)
* getLineNumber() (xml.sax.xmlreader.Locator 方法): Locator 对象.
                                                             (line   12)
* getlist() (cgi.FieldStorage 方法):     更高层级的接口.     (line   53)
* getloadavg() (在 os 模块中):           其他系统信息.       (line   40)
* getlocale() (在 locale 模块中):        locale --- 国际化服务.
                                                             (line  308)
* getLogger() (在 logging 模块中):       模块级别函数.       (line    8)
* getLoggerClass() (在 logging 模块中):  模块级别函数.       (line   18)
* getlogin() (在 os 模块中):             进程参数.           (line  196)
* getLogRecordFactory() (在 logging 模块中): 模块级别函数.   (line   28)
* getmark() (aifc.aifc 方法):            aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   79)
* getmark() (sunau.AU_read 方法):        AU_read 对象.       (line   76)
* getmark() (wave.Wave_read 方法):       Wave_read对象.      (line   58)
* getmarkers() (aifc.aifc 方法):         aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   73)
* getmarkers() (sunau.AU_read 方法):     AU_read 对象.       (line   72)
* getmarkers() (wave.Wave_read 方法):    Wave_read对象.      (line   54)
* getmaxyx() (curses.window 方法):       Window 对象.        (line  220)
* getmember() (tarfile.TarFile 方法):    TarFile 对象.       (line   85)
* getmembers() (tarfile.TarFile 方法):   TarFile 对象.       (line   93)
* getmembers() (在 inspect 模块中):      类型和成员.         (line  256)
* getMessage() (logging.LogRecord 方法): LogRecord 属性.     (line   45)
* getMessage() (xml.sax.SAXException 方法): SAXException 对象.
                                                             (line    8)
* getMessageID() (logging.handlers.NTEventLogHandler 方法): NTEventLogHandler.
                                                             (line   49)
* getmodule() (在 inspect 模块中):       Retrieving source code.
                                                             (line   32)
* getmodulename() (在 inspect 模块中):   类型和成员.         (line  269)
* getmouse() (在 curses 模块中):         函数<3>.            (line  121)
* getmro() (在 inspect 模块中):          类与函数<2>.        (line  132)
* getmtime() (在 os.path 模块中):        os path --- 常用路径操作.
                                                             (line  154)
* getname() (chunk.Chunk 方法):          chunk --- 读取 IFF 分块数据.
                                                             (line   59)
* getName() (threading.Thread 方法):     线程对象.           (line  118)
* getNameByQName() (xml.sax.xmlreader.AttributesNS 方法): AttributesNS 接口.
                                                             (line   15)
* getnameinfo() (asyncio.loop 方法):     DNS.                (line   11)
* getnameinfo() (在 socket 模块中):      其他功能<2>.        (line  114)
* getnames() (tarfile.TarFile 方法):     TarFile 对象.       (line   98)
* getNames() (xml.sax.xmlreader.Attributes 方法): Attributes 接口.
                                                             (line   14)
* getnchannels() (aifc.aifc 方法):       aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   41)
* getnchannels() (sunau.AU_read 方法):   AU_read 对象.       (line   14)
* getnchannels() (wave.Wave_read 方法):  Wave_read对象.      (line   13)
* getnframes() (aifc.aifc 方法):         aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   53)
* getnframes() (sunau.AU_read 方法):     AU_read 对象.       (line   26)
* getnframes() (wave.Wave_read 方法):    Wave_read对象.      (line   25)
* getnode:                               uuid --- UUID objects according to RFC 4122.
                                                             (line  177)
* getnode() (在 uuid 模块中):            uuid --- UUID objects according to RFC 4122.
                                                             (line  159)
* getopt (模块):                         getopt --- C 风格的命令行选项解析器.
                                                             (line    6)
* getopt() (distutils.fancy_getopt.FancyGetopt 方法): distutils fancy_getopt --- Wrapper around the standard getopt module.
                                                             (line   49)
* getopt() (在 getopt 模块中):           getopt --- C 风格的命令行选项解析器.
                                                             (line   21)
* GetoptError:                           getopt --- C 风格的命令行选项解析器.
                                                             (line   55)
* getouterframes() (在 inspect 模块中):  The interpreter stack.
                                                             (line   52)
* getoutput() (在 subprocess 模块中):    旧式的 Shell 发起函数.
                                                             (line   38)
* getpagesize() (在 resource 模块中):    Resource Usage.     (line  101)
* getparams() (aifc.aifc 方法):          aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   67)
* getparams() (sunau.AU_read 方法):      AU_read 对象.       (line   41)
* getparams() (wave.Wave_read 方法):     Wave_read对象.      (line   38)
* getparyx() (curses.window 方法):       Window 对象.        (line  224)
* getpass (模块):                        getpass --- 便携式密码输入工具.
                                                             (line    6)
* getpass() (在 getpass 模块中):         getpass --- 便携式密码输入工具.
                                                             (line   12)
* GetPassWarning:                        getpass --- 便携式密码输入工具.
                                                             (line   27)
* getpeercert() (ssl.SSLSocket 方法):    SSL 套接字.         (line  122)
* getpeername() (socket.socket 方法):    套接字对象.         (line  110)
* getpen() (在 turtle 模块中):           特殊海龟方法.       (line   37)
* getpgid() (在 os 模块中):              进程参数.           (line  205)
* getpgrp() (在 os 模块中):              进程参数.           (line  212)
* getpid() (在 os 模块中):               进程参数.           (line  218)
* getpos() (html.parser.HTMLParser 方法): HTMLParser 方法.   (line   25)
* getppid() (在 os 模块中):              进程参数.           (line  222)
* getpreferredencoding() (在 locale 模块中): locale --- 国际化服务.
                                                             (line  319)
* getpriority() (在 os 模块中):          进程参数.           (line  232)
* getprofile() (在 sys 模块中):          sys --- 系统相关的参数和函数.
                                                             (line  624)
* GetProperty() (msilib.SummaryInformation 方法): Summary Information Objects.
                                                             (line    6)
* getProperty() (xml.sax.xmlreader.XMLReader 方法): XMLReader 对象.
                                                             (line   77)
* GetPropertyCount() (msilib.SummaryInformation 方法): Summary Information Objects.
                                                             (line   17)
* getprotobyname() (在 socket 模块中):   其他功能<2>.        (line  128)
* getproxies() (在 urllib.request 模块中): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  139)
* getPublicId() (xml.sax.xmlreader.InputSource 方法): InputSource 对象.
                                                             (line   10)
* getPublicId() (xml.sax.xmlreader.Locator 方法): Locator 对象.
                                                             (line   16)
* getpwall() (在 pwd 模块中):            pwd --- 用户密码数据库.
                                                             (line   59)
* getpwnam() (在 pwd 模块中):            pwd --- 用户密码数据库.
                                                             (line   55)
* getpwuid() (在 pwd 模块中):            pwd --- 用户密码数据库.
                                                             (line   51)
* getQNameByName() (xml.sax.xmlreader.AttributesNS 方法): AttributesNS 接口.
                                                             (line   19)
* getQNames() (xml.sax.xmlreader.AttributesNS 方法): AttributesNS 接口.
                                                             (line   23)
* getquota() (imaplib.IMAP4 方法):       IMAP4 Objects.      (line  116)
* getquotaroot() (imaplib.IMAP4 方法):   IMAP4 Objects.      (line  121)
* getrandbits() (在 random 模块中):      簿记功能.           (line   35)
* getrandom() (在 os 模块中):            随机数<2>.          (line    6)
* getreader() (在 codecs 模块中):        codecs --- 编解码器注册和相关基类.
                                                             (line  112)
* getrecursionlimit() (在 sys 模块中):   sys --- 系统相关的参数和函数.
                                                             (line  583)
* getrefcount() (在 sys 模块中):         sys --- 系统相关的参数和函数.
                                                             (line  578)
* getresgid() (在 os 模块中):            进程参数.           (line  265)
* getresponse() (http.client.HTTPConnection 方法): HTTPConnection 对象.
                                                             (line   48)
* getresuid() (在 os 模块中):            进程参数.           (line  256)
* getrlimit() (在 resource 模块中):      Resource Limits.    (line   24)
* getroot() (xml.etree.ElementTree.ElementTree 方法): ElementTree 对象.
                                                             (line   36)
* getrusage() (在 resource 模块中):      Resource Usage.     (line    8)
* getsample() (在 audioop 模块中):       audioop --- 处理原始音频数据.
                                                             (line   94)
* getsampwidth() (aifc.aifc 方法):       aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   45)
* getsampwidth() (sunau.AU_read 方法):   AU_read 对象.       (line   18)
* getsampwidth() (wave.Wave_read 方法):  Wave_read对象.      (line   17)
* getscreen() (在 turtle 模块中):        特殊海龟方法.       (line   47)
* getservbyname() (在 socket 模块中):    其他功能<2>.        (line  135)
* getservbyport() (在 socket 模块中):    其他功能<2>.        (line  143)
* GetSetDescriptorType() (在 types 模块中): 标准解释器类型.  (line  173)
* getshapes() (在 turtle 模块中):        设置与特殊方法.     (line   61)
* getsid() (在 os 模块中):               进程参数.           (line  392)
* getsignal() (在 signal 模块中):        模块内容<5>.        (line  222)
* getsitepackages() (在 site 模块中):    模块内容<7>.        (line   50)
* getsize() (chunk.Chunk 方法):          chunk --- 读取 IFF 分块数据.
                                                             (line   63)
* getsize() (在 os.path 模块中):         os path --- 常用路径操作.
                                                             (line  171)
* getsizeof() (在 sys 模块中):           sys --- 系统相关的参数和函数.
                                                             (line  589)
* getsockname() (socket.socket 方法):    套接字对象.         (line  116)
* getsockopt() (socket.socket 方法):     套接字对象.         (line  121)
* getsource() (在 inspect 模块中):       Retrieving source code.
                                                             (line   55)
* getsourcefile() (在 inspect 模块中):   Retrieving source code.
                                                             (line   36)
* getsourcelines() (在 inspect 模块中):  Retrieving source code.
                                                             (line   42)
* getspall() (在 spwd 模块中):           spwd --- The shadow password database.
                                                             (line   66)
* getspnam() (在 spwd 模块中):           spwd --- The shadow password database.
                                                             (line   59)
* getstate() (codecs.IncrementalDecoder 方法): IncrementalDecoder 对象.
                                                             (line   37)
* getstate() (codecs.IncrementalEncoder 方法): IncrementalEncoder 对象.
                                                             (line   36)
* getstate() (在 random 模块中):         簿记功能.           (line   24)
* getstatusoutput() (在 subprocess 模块中): 旧式的 Shell 发起函数.
                                                             (line   10)
* getstr() (curses.window 方法):         Window 对象.        (line  229)
* GetString() (msilib.Record 方法):      Record Objects.     (line   16)
* getSubject() (logging.handlers.SMTPHandler 方法): SMTPHandler.
                                                             (line   32)
* GetSummaryInformation() (msilib.Database 方法): Database Objects.
                                                             (line   16)
* getswitchinterval() (在 sys 模块中):   sys --- 系统相关的参数和函数.
                                                             (line  606)
* getSystemId() (xml.sax.xmlreader.InputSource 方法): InputSource 对象.
                                                             (line   18)
* getSystemId() (xml.sax.xmlreader.Locator 方法): Locator 对象.
                                                             (line   20)
* getsyx() (在 curses 模块中):           函数<3>.            (line  133)
* gettarinfo() (tarfile.TarFile 方法):   TarFile 对象.       (line  196)
* gettempdir() (在 tempfile 模块中):     tempfile --- 生成临时文件和目录.
                                                             (line  190)
* gettempdirb() (在 tempfile 模块中):    tempfile --- 生成临时文件和目录.
                                                             (line  216)
* gettempprefix() (在 tempfile 模块中):  tempfile --- 生成临时文件和目录.
                                                             (line  222)
* gettempprefixb() (在 tempfile 模块中): tempfile --- 生成临时文件和目录.
                                                             (line  226)
* getTestCaseNames() (unittest.TestLoader 方法): Loading and running tests.
                                                             (line  111)
* gettext (模块):                        gettext --- 多语种国际化服务.
                                                             (line    6)
* gettext() (gettext.GNUTranslations 方法): GNUTranslations 类.
                                                             (line   32)
* gettext() (gettext.NullTranslations 方法): NullTranslations 类.
                                                             (line   29)
* gettext() (在 gettext 模块中):         GNU gettext API.    (line   37)
* gettext() (在 locale 模块中):          Access to message catalogs.
                                                             (line    6)
* gettimeout() (socket.socket 方法):     套接字对象.         (line  138)
* gettrace() (在 sys 模块中):            sys --- 系统相关的参数和函数.
                                                             (line  628)
* getturtle() (在 turtle 模块中):        特殊海龟方法.       (line   37)
* getType() (xml.sax.xmlreader.Attributes 方法): Attributes 接口.
                                                             (line   18)
* getuid() (在 os 模块中):               进程参数.           (line  274)
* geturl() (urllib.parse.urllib.parse.SplitResult 方法): 结构化解析结果.
                                                             (line   12)
* getuser() (在 getpass 模块中):         getpass --- 便携式密码输入工具.
                                                             (line   31)
* getuserbase() (在 site 模块中):        模块内容<7>.        (line   56)
* getusersitepackages() (在 site 模块中): 模块内容<7>.       (line   63)
* getvalue() (io.BytesIO 方法):          缓冲流.             (line   35)
* getvalue() (io.StringIO 方法):         文本 I/O<2>.        (line  182)
* getValue() (xml.sax.xmlreader.Attributes 方法): Attributes 接口.
                                                             (line   22)
* getValueByQName() (xml.sax.xmlreader.AttributesNS 方法): AttributesNS 接口.
                                                             (line   11)
* getwch() (在 msvcrt 模块中):           控制台 I/O.         (line   17)
* getwche() (在 msvcrt 模块中):          控制台 I/O.         (line   26)
* getweakrefcount() (在 weakref 模块中): weakref --- 弱引用. (line  111)
* getweakrefs() (在 weakref 模块中):     weakref --- 弱引用. (line  115)
* getwelcome() (ftplib.FTP 方法):        FTP 对象.           (line   34)
* getwelcome() (nntplib.NNTP 方法):      方法<3>.            (line   28)
* getwelcome() (poplib.POP3 方法):       POP3 对象.          (line   18)
* getwin() (在 curses 模块中):           函数<3>.            (line  138)
* getwindowsversion() (在 sys 模块中):   sys --- 系统相关的参数和函数.
                                                             (line  636)
* getwriter() (在 codecs 模块中):        codecs --- 编解码器注册和相关基类.
                                                             (line  119)
* getxattr() (在 os 模块中):             Linux 扩展属性.     (line   10)
* getyx() (curses.window 方法):          Window 对象.        (line  239)
* GET_AITER (opcode):                    Python字节码说明.   (line  259)
* get_all() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  208)
* get_all() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  302)
* get_all() (wsgiref.headers.Headers 方法): wsgiref headers -- WSGI response header tools.
                                                             (line   51)
* get_all_breaks() (bdb.Bdb 方法):       bdb --- Debugger framework.
                                                             (line  330)
* get_all_start_methods() (在 multiprocessing 模块中): 杂项<3>.
                                                             (line   67)
* GET_ANEXT (opcode):                    Python字节码说明.   (line  267)
* get_app() (wsgiref.simple_server.WSGIServer 方法): wsgiref simple_server -- a simple WSGI HTTP server.
                                                             (line   66)
* get_archive_formats() (在 shutil 模块中): 归档操作.        (line   54)
* get_args() (在 typing 模块中):         类 函数和修饰器.    (line  592)
* get_asyncgen_hooks() (在 sys 模块中):  sys --- 系统相关的参数和函数.
                                                             (line  681)
* get_attribute() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  798)
* GET_AWAITABLE (opcode):                Python字节码说明.   (line  251)
* get_begidx() (在 readline 模块中):     Completion.         (line   33)
* get_blocking() (在 os 模块中):         文件描述符操作.     (line  173)
* get_body() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  439)
* get_body_encoding() (email.charset.Charset 方法): email charset 表示字符集.
                                                             (line   85)
* get_boundary() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  335)
* get_boundary() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  483)
* get_bpbynumber() (bdb.Bdb 方法):       bdb --- Debugger framework.
                                                             (line  307)
* get_break() (bdb.Bdb 方法):            bdb --- Debugger framework.
                                                             (line  316)
* get_breaks() (bdb.Bdb 方法):           bdb --- Debugger framework.
                                                             (line  320)
* get_buffer() (asyncio.BufferedProtocol 方法): 缓冲流协议.  (line   18)
* get_buffer() (xdrlib.Packer 方法):     Packer 对象.        (line    8)
* get_buffer() (xdrlib.Unpacker 方法):   Unpacker 对象.      (line   21)
* get_bytes() (mailbox.Mailbox 方法):    Mailbox 对象.       (line  130)
* get_cache_token() (在 abc 模块中):     abc --- 抽象基类.   (line  284)
* get_ca_certs() (ssl.SSLContext 方法):  SSL 上下文.         (line  136)
* get_channel_binding() (ssl.SSLSocket 方法): SSL 套接字.    (line  207)
* get_charset() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  219)
* get_charsets() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  359)
* get_charsets() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  511)
* get_children() (symtable.SymbolTable 方法): Examining Symbol Tables.
                                                             (line   62)
* get_children() (tkinter.ttk.Treeview 方法): ttk Treeview.  (line   19)
* get_child_watcher() (asyncio.AbstractEventLoopPolicy 方法): 策略对象.
                                                             (line   33)
* get_child_watcher() (在 asyncio 模块中): 进程监视器.       (line   21)
* get_ciphers() (ssl.SSLContext 方法):   SSL 上下文.         (line  149)
* get_clock_info() (在 time 模块中):     函数<2>.            (line   88)
* get_close_matches() (在 difflib 模块中): difflib --- 计算差异的辅助工具.
                                                             (line  171)
* get_code() (importlib.abc.InspectLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  336)
* get_code() (importlib.abc.SourceLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  503)
* get_code() (importlib.machinery.ExtensionFileLoader 方法): importlib machinery -- Importers and path hooks.
                                                             (line  331)
* get_code() (importlib.machinery.SourcelessFileLoader 方法): importlib machinery -- Importers and path hooks.
                                                             (line  274)
* get_code() (zipimport.zipimporter 方法): zipimporter 对象. (line   25)
* get_completer() (在 readline 模块中):  Completion.         (line   24)
* get_completer_delims() (在 readline 模块中): Completion.   (line   40)
* get_completion_type() (在 readline 模块中): Completion.    (line   28)
* get_config_h_filename() (在 distutils.sysconfig 模块中): distutils sysconfig --- System configuration information.
                                                             (line   41)
* get_config_h_filename() (在 sysconfig 模块中): 其他功能<3>.
                                                             (line   67)
* get_config_var() (在 distutils.sysconfig 模块中): distutils sysconfig --- System configuration information.
                                                             (line   27)
* get_config_var() (在 sysconfig 模块中): 配置变量.          (line   26)
* get_config_vars() (在 distutils.sysconfig 模块中): distutils sysconfig --- System configuration information.
                                                             (line   32)
* get_config_vars() (在 sysconfig 模块中): 配置变量.         (line   16)
* get_content() (email.contentmanager.ContentManager 方法): email contentmanager 管理 MIME 内容.
                                                             (line   17)
* get_content() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  491)
* get_content() (在 email.contentmanager 模块中): 内容管理器实例.
                                                             (line   19)
* get_content_charset() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  354)
* get_content_charset() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  503)
* get_content_disposition() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  379)
* get_content_disposition() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  522)
* get_content_maintype() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  266)
* get_content_maintype() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  360)
* get_content_subtype() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  272)
* get_content_subtype() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  366)
* get_content_type() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  252)
* get_content_type() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  347)
* get_context() (在 multiprocessing 模块中): 杂项<3>.        (line   76)
* get_coro() (asyncio.Task 方法):        Task 对象.          (line  180)
* get_coroutine_origin_tracking_depth() (在 sys 模块中): sys --- 系统相关的参数和函数.
                                                             (line  692)
* get_count() (在 gc 模块中):            gc --- 垃圾回收器接口.
                                                             (line   90)
* get_current_history_length() (在 readline 模块中): 历史列表.
                                                             (line   13)
* get_data() (importlib.abc.FileLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  439)
* get_data() (importlib.abc.ResourceLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  320)
* get_data() (zipimport.zipimporter 方法): zipimporter 对象. (line   30)
* get_data() (在 pkgutil 模块中):        pkgutil --- 包扩展工具.
                                                             (line  200)
* get_date() (mailbox.MaildirMessage 方法): MaildirMessage.  (line   82)
* get_debug() (asyncio.loop 方法):       开启调试模式.       (line    6)
* get_debug() (在 gc 模块中):            gc --- 垃圾回收器接口.
                                                             (line   47)
* get_default() (argparse.ArgumentParser 方法): 解析器默认值.
                                                             (line   29)
* get_default_compiler() (在 distutils.ccompiler 模块中): distutils ccompiler --- CCompiler基类.
                                                             (line   36)
* get_default_domain() (在 nis 模块中):  nis --- Sun 的 NIS 黄页 接口.
                                                             (line   43)
* get_default_type() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  278)
* get_default_type() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  372)
* get_default_verify_paths() (在 ssl 模块中): 证书处理.      (line   89)
* get_dialect() (在 csv 模块中):         模块内容<3>.        (line   71)
* get_docstring() (在 ast 模块中):       ast 中的辅助函数.   (line   57)
* get_doctest() (doctest.DocTestParser 方法): DocTestParser 对象.
                                                             (line   13)
* get_endidx() (在 readline 模块中):     Completion.         (line   33)
* get_environ() (wsgiref.simple_server.WSGIRequestHandler 方法): wsgiref simple_server -- a simple WSGI HTTP server.
                                                             (line   88)
* get_errno() (在 ctypes 模块中):        工具函数.           (line  104)
* get_event_loop() (asyncio.AbstractEventLoopPolicy 方法): 策略对象.
                                                             (line   12)
* get_event_loop() (在 asyncio 模块中):  事件循环.           (line   34)
* get_event_loop_policy() (在 asyncio 模块中): 获取和设置策略.
                                                             (line    8)
* get_examples() (doctest.DocTestParser 方法): DocTestParser 对象.
                                                             (line   22)
* get_exception_handler() (asyncio.loop 方法): 错误处理API.  (line   18)
* get_exec_path() (在 os 模块中):        进程参数.           (line  141)
* get_extra_info() (asyncio.BaseTransport 方法): 基础传输.   (line   19)
* get_extra_info() (asyncio.StreamWriter 方法): StreamWriter.
                                                             (line   56)
* get_field() (string.Formatter 方法):   自定义字符串格式化. (line   44)
* get_file() (mailbox.Babyl 方法):       Babyl.              (line   39)
* get_file() (mailbox.Mailbox 方法):     Mailbox 对象.       (line  144)
* get_file() (mailbox.Maildir 方法):     Maildir.            (line  101)
* get_file() (mailbox.mbox 方法):        mbox.               (line   27)
* get_file() (mailbox.MH 方法):          MH.                 (line   83)
* get_file() (mailbox.MMDF 方法):        MMDF.               (line   24)
* get_filename() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  327)
* get_filename() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  475)
* get_filename() (importlib.abc.ExecutionLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  399)
* get_filename() (importlib.abc.FileLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  435)
* get_filename() (importlib.machinery.ExtensionFileLoader 方法): importlib machinery -- Importers and path hooks.
                                                             (line  339)
* get_filename() (zipimport.zipimporter 方法): zipimporter 对象.
                                                             (line   38)
* get_file_breaks() (bdb.Bdb 方法):      bdb --- Debugger framework.
                                                             (line  325)
* get_flags() (mailbox.MaildirMessage 方法): MaildirMessage. (line   59)
* get_flags() (mailbox.mboxMessage 方法): mboxMessage.       (line   56)
* get_flags() (mailbox.MMDFMessage 方法): MMDFMessage.       (line   55)
* get_folder() (mailbox.Maildir 方法):   Maildir.            (line   53)
* get_folder() (mailbox.MH 方法):        MH.                 (line   32)
* get_frees() (symtable.Function 方法):  Examining Symbol Tables.
                                                             (line   88)
* get_freeze_count() (在 gc 模块中):     gc --- 垃圾回收器接口.
                                                             (line  164)
* get_from() (mailbox.mboxMessage 方法): mboxMessage.        (line   43)
* get_from() (mailbox.MMDFMessage 方法): MMDFMessage.        (line   42)
* get_full_url() (urllib.request.Request 方法): Request 对象.
                                                             (line   93)
* get_globals() (symtable.Function 方法): Examining Symbol Tables.
                                                             (line   80)
* get_grouped_opcodes() (difflib.SequenceMatcher 方法): SequenceMatcher 对象.
                                                             (line  144)
* get_handle_inheritable() (在 os 模块中): 文件描述符的继承. (line   29)
* get_header() (urllib.request.Request 方法): Request 对象.  (line  106)
* get_history_item() (在 readline 模块中): 历史列表.         (line   18)
* get_history_length() (在 readline 模块中): 历史文件.       (line   27)
* get_id() (symtable.SymbolTable 方法):  Examining Symbol Tables.
                                                             (line   15)
* get_ident() (在 threading 模块中):     threading --- 基于线程的并行.
                                                             (line   74)
* get_ident() (在 _thread 模块中):       _thread --- 底层多线程 API.
                                                             (line   62)
* get_identifiers() (symtable.SymbolTable 方法): Examining Symbol Tables.
                                                             (line   48)
* get_importer() (在 pkgutil 模块中):    pkgutil --- 包扩展工具.
                                                             (line   91)
* get_info() (mailbox.MaildirMessage 方法): MaildirMessage.  (line   90)
* get_inheritable() (socket.socket 方法): 套接字对象.        (line  103)
* get_inheritable() (在 os 模块中):      文件描述符的继承.   (line   21)
* get_instructions() (在 dis 模块中):    分析函数.           (line   93)
* get_interpreter() (在 zipapp 模块中):  Python API.         (line   82)
* GET_ITER (opcode):                     Python字节码说明.   (line  107)
* get_key() (selectors.BaseSelector 方法): 类<3>.            (line  126)
* get_labels() (mailbox.Babyl 方法):     Babyl.              (line   28)
* get_labels() (mailbox.BabylMessage 方法): BabylMessage.    (line   44)
* get_last_error() (在 ctypes 模块中):   工具函数.           (line  111)
* get_lineno() (symtable.SymbolTable 方法): Examining Symbol Tables.
                                                             (line   26)
* get_line_buffer() (在 readline 模块中): 行缓冲区.          (line    8)
* get_loader() (在 pkgutil 模块中):      pkgutil --- 包扩展工具.
                                                             (line  105)
* get_locals() (symtable.Function 方法): Examining Symbol Tables.
                                                             (line   76)
* get_logger() (在 multiprocessing 模块中): 日志记录<2>.     (line   10)
* get_loop() (asyncio.Future 方法):      Future 对象<2>.     (line  119)
* get_loop() (asyncio.Server 方法):      Server 对象.        (line   37)
* get_magic() (在 imp 模块中):           imp --- Access the import internals.
                                                             (line   17)
* get_makefile_filename() (在 distutils.sysconfig 模块中): distutils sysconfig --- System configuration information.
                                                             (line   49)
* get_makefile_filename() (在 sysconfig 模块中): 其他功能<3>.
                                                             (line   71)
* get_map() (selectors.BaseSelector 方法): 类<3>.            (line  133)
* get_matching_blocks() (difflib.SequenceMatcher 方法): SequenceMatcher 对象.
                                                             (line   87)
* get_message() (mailbox.Mailbox 方法):  Mailbox 对象.       (line  124)
* get_method() (urllib.request.Request 方法): Request 对象.  (line   60)
* get_methods() (symtable.Class 方法):   Examining Symbol Tables.
                                                             (line   98)
* get_mixed_type_key() (在 ipaddress 模块中): Other Module Level Functions.
                                                             (line   56)
* get_name() (asyncio.Task 方法):        Task 对象.          (line  186)
* get_name() (symtable.Symbol 方法):     Examining Symbol Tables.
                                                             (line  108)
* get_name() (symtable.SymbolTable 方法): Examining Symbol Tables.
                                                             (line   19)
* get_namespace() (symtable.Symbol 方法): Examining Symbol Tables.
                                                             (line  179)
* get_namespaces() (symtable.Symbol 方法): Examining Symbol Tables.
                                                             (line  175)
* get_native_id() (在 threading 模块中): threading --- 基于线程的并行.
                                                             (line   82)
* get_native_id() (在 _thread 模块中):   _thread --- 底层多线程 API.
                                                             (line   68)
* get_nonlocals() (symtable.Function 方法): Examining Symbol Tables.
                                                             (line   84)
* get_nonstandard_attr() (http.cookiejar.Cookie 方法): Cookie 对象<2>.
                                                             (line   98)
* get_nowait() (asyncio.Queue 方法):     Queue.              (line   42)
* get_nowait() (multiprocessing.Queue 方法): 管道和队列.     (line  132)
* get_nowait() (queue.Queue 方法):       Queue对象.          (line   53)
* get_nowait() (queue.SimpleQueue 方法): SimpleQueue 对象.   (line   44)
* get_objects() (在 gc 模块中):          gc --- 垃圾回收器接口.
                                                             (line   51)
* get_object_traceback() (在 tracemalloc 模块中): 函数<9>.   (line   12)
* get_opcodes() (difflib.SequenceMatcher 方法): SequenceMatcher 对象.
                                                             (line  103)
* get_option() (optparse.OptionParser 方法): Querying and manipulating your option parser.
                                                             (line   37)
* get_option_group() (optparse.OptionParser 方法): Grouping Options.
                                                             (line  103)
* get_option_order() (distutils.fancy_getopt.FancyGetopt 方法): distutils fancy_getopt --- Wrapper around the standard getopt module.
                                                             (line   62)
* get_origin() (在 typing 模块中):       类 函数和修饰器.    (line  590)
* get_original_stdout() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  380)
* get_osfhandle() (在 msvcrt 模块中):    文件操作.           (line   50)
* get_output_charset() (email.charset.Charset 方法): email charset 表示字符集.
                                                             (line   98)
* get_param() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  399)
* get_parameters() (symtable.Function 方法): Examining Symbol Tables.
                                                             (line   71)
* get_params() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  384)
* get_path() (在 sysconfig 模块中):      安装路径.           (line   67)
* get_paths() (在 sysconfig 模块中):     安装路径.           (line   97)
* get_path_names() (在 sysconfig 模块中): 安装路径.          (line   62)
* get_payload() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  148)
* get_pid() (asyncio.SubprocessTransport 方法): 子进程传输.  (line    6)
* get_pipe_transport() (asyncio.SubprocessTransport 方法): 子进程传输.
                                                             (line   10)
* get_platform() (在 distutils.util 模块中): distutils util --- Miscellaneous other utility functions.
                                                             (line    9)
* get_platform() (在 sysconfig 模块中):  其他功能<3>.        (line   11)
* get_poly() (在 turtle 模块中):         特殊海龟方法.       (line   15)
* get_position() (xdrlib.Unpacker 方法): Unpacker 对象.      (line   12)
* get_protocol() (asyncio.BaseTransport 方法): 基础传输.     (line   79)
* get_python_inc() (在 distutils.sysconfig 模块中): distutils sysconfig --- System configuration information.
                                                             (line   57)
* get_python_lib() (在 distutils.sysconfig 模块中): distutils sysconfig --- System configuration information.
                                                             (line   67)
* get_python_version() (在 sysconfig 模块中): 其他功能<3>.   (line    6)
* get_recsrc() (ossaudiodev.oss_mixer_device 方法): Mixer Device Objects.
                                                             (line   84)
* get_referents() (在 gc 模块中):        gc --- 垃圾回收器接口.
                                                             (line  115)
* get_referrers() (在 gc 模块中):        gc --- 垃圾回收器接口.
                                                             (line   99)
* get_request() (socketserver.BaseServer 方法): Server 对象<2>.
                                                             (line  131)
* get_returncode() (asyncio.SubprocessTransport 方法): 子进程传输.
                                                             (line   26)
* get_running_loop() (在 asyncio 模块中): 事件循环.          (line   25)
* get_scheme() (wsgiref.handlers.BaseHandler 方法): wsgiref handlers -- server/gateway base classes.
                                                             (line  187)
* get_scheme_names() (在 sysconfig 模块中): 安装路径.        (line   57)
* get_sequences() (mailbox.MH 方法):     MH.                 (line   47)
* get_sequences() (mailbox.MHMessage 方法): MHMessage.       (line   30)
* get_server() (multiprocessing.managers.BaseManager 方法): 管理器.
                                                             (line   39)
* get_server_certificate() (在 ssl 模块中): 证书处理.        (line   64)
* get_shapepoly() (在 turtle 模块中):    外观.               (line  171)
* get_socket() (telnetlib.Telnet 方法):  Telnet 对象.        (line   84)
* get_source() (importlib.abc.InspectLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  347)
* get_source() (importlib.abc.SourceLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  519)
* get_source() (importlib.machinery.ExtensionFileLoader 方法): importlib machinery -- Importers and path hooks.
                                                             (line  335)
* get_source() (importlib.machinery.SourcelessFileLoader 方法): importlib machinery -- Importers and path hooks.
                                                             (line  279)
* get_source() (zipimport.zipimporter 方法): zipimporter 对象.
                                                             (line   45)
* get_source_segment() (在 ast 模块中):  ast 中的辅助函数.   (line   66)
* get_special_folder_path() (內置函数):  The Postinstallation script.
                                                             (line   32)
* get_stack() (asyncio.Task 方法):       Task 对象.          (line  152)
* get_stack() (bdb.Bdb 方法):            bdb --- Debugger framework.
                                                             (line  337)
* get_starttag_text() (html.parser.HTMLParser 方法): HTMLParser 方法.
                                                             (line   29)
* get_start_method() (在 multiprocessing 模块中): 杂项<3>.   (line   87)
* get_stats() (在 gc 模块中):            gc --- 垃圾回收器接口.
                                                             (line   61)
* get_stderr() (wsgiref.handlers.BaseHandler 方法): wsgiref handlers -- server/gateway base classes.
                                                             (line  127)
* get_stderr() (wsgiref.simple_server.WSGIRequestHandler 方法): wsgiref simple_server -- a simple WSGI HTTP server.
                                                             (line   98)
* get_stdin() (wsgiref.handlers.BaseHandler 方法): wsgiref handlers -- server/gateway base classes.
                                                             (line  122)
* get_string() (mailbox.Mailbox 方法):   Mailbox 对象.       (line  137)
* get_subdir() (mailbox.MaildirMessage 方法): MaildirMessage.
                                                             (line   43)
* get_suffixes() (在 imp 模块中):        imp --- Access the import internals.
                                                             (line   26)
* get_symbols() (symtable.SymbolTable 方法): Examining Symbol Tables.
                                                             (line   57)
* get_tag() (在 imp 模块中):             imp --- Access the import internals.
                                                             (line  235)
* get_task_factory() (asyncio.loop 方法): 创建 Futures 和 Tasks.
                                                             (line   36)
* get_terminal_size() (在 os 模块中):    查询终端的尺寸.     (line    8)
* get_terminal_size() (在 shutil 模块中): 查询输出终端的尺寸.
                                                             (line    6)
* get_terminator() (asynchat.async_chat 方法): asynchat --- 异步 socket 指令/响应 处理器.
                                                             (line   83)
* get_threshold() (在 gc 模块中):        gc --- 垃圾回收器接口.
                                                             (line   94)
* get_token() (shlex.shlex 方法):        shlex Objects.      (line    8)
* get_traceback_limit() (在 tracemalloc 模块中): 函数<9>.    (line   22)
* get_traced_memory() (在 tracemalloc 模块中): 函数<9>.      (line   32)
* get_tracemalloc_memory() (在 tracemalloc 模块中): 函数<9>. (line   38)
* get_type() (symtable.SymbolTable 方法): Examining Symbol Tables.
                                                             (line   10)
* get_type_hints() (在 typing 模块中):   类 函数和修饰器.    (line  580)
* get_unixfrom() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  121)
* get_unixfrom() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  133)
* get_unpack_formats() (在 shutil 模块中): 归档操作.         (line  136)
* get_usage() (optparse.OptionParser 方法): Other methods.   (line   22)
* get_value() (string.Formatter 方法):   自定义字符串格式化. (line   53)
* get_version() (optparse.OptionParser 方法): Printing a version string.
                                                             (line   34)
* get_visible() (mailbox.BabylMessage 方法): BabylMessage.   (line   60)
* get_wch() (curses.window 方法):        Window 对象.        (line  206)
* get_write_buffer_limits() (asyncio.WriteTransport 方法): 只写传输.
                                                             (line   21)
* get_write_buffer_size() (asyncio.WriteTransport 方法): 只写传输.
                                                             (line   17)
* GET_YIELD_FROM_ITER (opcode):          Python字节码说明.   (line  111)
* gid (tarfile.TarInfo 属性):            TarInfo 对象.       (line   71)
* GIL:                                   术语对照表.         (line  443)
* glob (模块):                           glob --- Unix 风格路径名模式扩展.
                                                             (line    6)
* glob() (msilib.Directory 方法):        Directory Objects.  (line   39)
* glob() (pathlib.Path 方法):            方法<2>.            (line   82)
* glob() (在 glob 模块中):               glob --- Unix 风格路径名模式扩展.
                                                             (line   27)
* global interpreter lock:               Thread State and the Global Interpreter Lock.
                                                             (line    6)
* global interpreter lock – 全局解释器锁: 术语对照表.        (line  447)
* global; name; binding:                 global 语句.        (line    6)
* global; namespace:                     标准类型层级结构.   (line  234)
* globals() (內置函数):                  内置函数.           (line  573)
* globs (doctest.DocTest 属性):          DocTest 对象.       (line   22)
* gmtime() (在 time 模块中):             函数<2>.            (line  117)
* gname (tarfile.TarInfo 属性):          TarInfo 对象.       (line   79)
* GNOME:                                 编目构造器.         (line    6)
* GNUTranslations (gettext 中的类):      GNUTranslations 类. (line   28)
* GNU_FORMAT() (在 tarfile 模块中):      tarfile --- 读写tar归档文件.
                                                             (line  202)
* gnu_getopt() (在 getopt 模块中):       getopt --- C 风格的命令行选项解析器.
                                                             (line   46)
* got (doctest.DocTestFailure 属性):     调试.               (line  203)
* goto() (在 turtle 模块中):             海龟动作.           (line   71)
* grammar:                               标注.               (line    6)
* Graphical User Interface:              Tk图形用户界面 GUI. (line    6)
* GREATER() (在 token 模块中):           token --- 与Python解析树一起使用的常量.
                                                             (line  106)
* GREATEREQUAL() (在 token 模块中):      token --- 与Python解析树一起使用的常量.
                                                             (line  142)
* Greenwich Mean Time:                   time --- 时间的访问和转换.
                                                             (line   32)
* GRND_NONBLOCK() (在 os 模块中):        随机数<2>.          (line   61)
* GRND_RANDOM() (在 os 模块中):          随机数<2>.          (line   73)
* Group (email.headerregistry 中的类):   email headerregistry 自定义标头对象.
                                                             (line  390)
* group() (nntplib.NNTP 方法):           方法<3>.            (line  157)
* group() (pathlib.Path 方法):           方法<2>.            (line  104)
* group() (re.Match 方法):               匹配对象.           (line   24)
* groupby() (在 itertools 模块中):       Itertool函数.       (line  269)
* groupdict() (re.Match 方法):           匹配对象.           (line  103)
* groupindex (re.Pattern 属性):          正则表达式对象 （正则对象）.
                                                             (line   91)
* grouping:                              缩进.               (line    6)
* groups (email.headerregistry.AddressHeader 属性): email headerregistry 自定义标头对象.
                                                             (line  153)
* groups (re.Pattern 属性):              正则表达式对象 （正则对象）.
                                                             (line   87)
* groups() (re.Match 方法):              匹配对象.           (line   83)
* grp (模块):                            grp --- 组数据库.   (line    6)
* gt() (在 operator 模块中):             operator --- 标准运算符替代函数.
                                                             (line   19)
* guess_all_extensions() (mimetypes.MimeTypes 方法): MimeTypes 对象.
                                                             (line   53)
* guess_all_extensions() (在 mimetypes 模块中): mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line   44)
* guess_extension() (mimetypes.MimeTypes 方法): MimeTypes 对象.
                                                             (line   43)
* guess_extension() (在 mimetypes 模块中): mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line   54)
* guess_scheme() (在 wsgiref.util 模块中): wsgiref util -- WSGI environment utilities.
                                                             (line   12)
* guess_type() (mimetypes.MimeTypes 方法): MimeTypes 对象.   (line   48)
* guess_type() (在 mimetypes 模块中):    mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line   21)
* GUI:                                   Tk图形用户界面 GUI. (line    6)
* gzip (模块):                           gzip --- 对 gzip 格式的支持.
                                                             (line    6)
* gzip command line option; –best:       命令行选项.         (line   14)
* gzip command line option; -d:          命令行选项.         (line   18)
* gzip command line option; –decompress: 命令行选项.         (line   18)
* gzip command line option; –fast:       命令行选项.         (line   10)
* gzip command line option; -h:          命令行选项.         (line   22)
* gzip command line option; –help:       命令行选项.         (line   22)
* gzip command line option; file:        命令行选项.         (line    6)
* GzipFile (gzip 中的类):                gzip --- 对 gzip 格式的支持.
                                                             (line   64)
* halfdelay() (在 curses 模块中):        函数<3>.            (line  163)
* Handle (asyncio 中的类):               回调处理.           (line    6)
* handle an exception:                   异常<2>.            (line    6)
* handle() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  172)
* handle() (logging.Handler 方法):       处理器对象.         (line   71)
* handle() (logging.handlers.QueueListener 方法): QueueListener.
                                                             (line   53)
* handle() (logging.Logger 方法):        记录器对象.         (line  234)
* handle() (logging.NullHandler 方法):   NullHandler.        (line   19)
* handle() (socketserver.BaseRequestHandler 方法): Request Handler Objects.
                                                             (line   20)
* handle() (wsgiref.simple_server.WSGIRequestHandler 方法): wsgiref simple_server -- a simple WSGI HTTP server.
                                                             (line  103)
* handleError() (logging.Handler 方法):  处理器对象.         (line   76)
* handleError() (logging.handlers.SocketHandler 方法): SocketHandler.
                                                             (line   28)
* Handler (logging 中的类):              处理器对象.         (line   10)
* handler() (在 cgitb 模块中):           cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line   52)
* handle_accept() (asyncore.dispatcher 方法): asyncore --- 异步socket处理器.
                                                             (line  117)
* handle_accepted() (asyncore.dispatcher 方法): asyncore --- 异步socket处理器.
                                                             (line  125)
* handle_charref() (html.parser.HTMLParser 方法): HTMLParser 方法.
                                                             (line   76)
* handle_close() (asyncore.dispatcher 方法): asyncore --- 异步socket处理器.
                                                             (line  108)
* handle_comment() (html.parser.HTMLParser 方法): HTMLParser 方法.
                                                             (line   83)
* handle_connect() (asyncore.dispatcher 方法): asyncore --- 异步socket处理器.
                                                             (line  103)
* handle_data() (html.parser.HTMLParser 方法): HTMLParser 方法.
                                                             (line   65)
* handle_decl() (html.parser.HTMLParser 方法): HTMLParser 方法.
                                                             (line   94)
* handle_defect() (email.policy.Policy 方法): email policy 策略对象.
                                                             (line  176)
* handle_endtag() (html.parser.HTMLParser 方法): HTMLParser 方法.
                                                             (line   52)
* handle_entityref() (html.parser.HTMLParser 方法): HTMLParser 方法.
                                                             (line   70)
* handle_error() (asyncore.dispatcher 方法): asyncore --- 异步socket处理器.
                                                             (line  112)
* handle_error() (socketserver.BaseServer 方法): Server 对象<2>.
                                                             (line  137)
* handle_expect_100() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  185)
* handle_expt() (asyncore.dispatcher 方法): asyncore --- 异步socket处理器.
                                                             (line   98)
* handle_one_request() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  179)
* handle_pi() (html.parser.HTMLParser 方法): HTMLParser 方法.
                                                             (line  101)
* handle_read() (asyncore.dispatcher 方法): asyncore --- 异步socket处理器.
                                                             (line   84)
* handle_request() (socketserver.BaseServer 方法): Server 对象<2>.
                                                             (line   21)
* handle_request() (xmlrpc.server.CGIXMLRPCRequestHandler 方法): CGIXMLRPCRequestHandler.
                                                             (line   50)
* handle_startendtag() (html.parser.HTMLParser 方法): HTMLParser 方法.
                                                             (line   58)
* handle_starttag() (html.parser.HTMLParser 方法): HTMLParser 方法.
                                                             (line   38)
* handle_timeout() (socketserver.BaseServer 方法): Server 对象<2>.
                                                             (line  147)
* handle_write() (asyncore.dispatcher 方法): asyncore --- 异步socket处理器.
                                                             (line   89)
* harmonic_mean() (在 statistics 模块中): 函数细节.          (line   72)
* hasattr() (內置函数):                  内置函数.           (line  578)
* hasAttribute() (xml.dom.Element 方法): 元素对象<2>.        (line   21)
* hasAttributeNS() (xml.dom.Element 方法): 元素对象<2>.      (line   25)
* hasAttributes() (xml.dom.Node 方法):   节点对象.           (line   81)
* hasChildNodes() (xml.dom.Node 方法):   节点对象.           (line   85)
* hascompare() (在 dis 模块中):          操作码集合.         (line   46)
* hasconst() (在 dis 模块中):            操作码集合.         (line   20)
* hasFeature() (xml.dom.DOMImplementation 方法): DOMImplementation 对象.
                                                             (line   10)
* hasfree() (在 dis 模块中):             操作码集合.         (line   24)
* hash character:                        注释.               (line    6)
* hash() (內置函数):                     内置函数.           (line  584)
* hash-based pyc – 基于哈希的 pyc:       术语对照表.         (line  462)
* hash.block_size() (在 hashlib 模块中): 哈希算法.           (line   89)
* hash.digest_size() (在 hashlib 模块中): 哈希算法.          (line   85)
* hashable:                              字典显示.           (line   29)
* Hashable (collections.abc 中的类):     容器抽象基类.       (line  108)
* Hashable (typing 中的类):              类 函数和修饰器.    (line  181)
* hashable – 可哈希:                     术语对照表.         (line  467)
* hasHandlers() (logging.Logger 方法):   记录器对象.         (line  247)
* hashfunc (C 类型):                     Slot Type typedefs. (line   87)
* hashlib (模块):                        hashlib --- 安全哈希与消息摘要.
                                                             (line    6)
* hash_info() (在 sys 模块中):           sys --- 系统相关的参数和函数.
                                                             (line  702)
* hasjabs() (在 dis 模块中):             操作码集合.         (line   38)
* hasjrel() (在 dis 模块中):             操作码集合.         (line   34)
* haslocal() (在 dis 模块中):            操作码集合.         (line   42)
* hasname() (在 dis 模块中):             操作码集合.         (line   30)
* HAS_ALPN() (在 ssl 模块中):            常量<9>.            (line  320)
* has_children() (symtable.SymbolTable 方法): Examining Symbol Tables.
                                                             (line   39)
* has_colors() (在 curses 模块中):       函数<3>.            (line  143)
* has_dualstack_ipv6() (在 socket 模块中): 创建套接字.       (line  123)
* HAS_ECDH() (在 ssl 模块中):            常量<9>.            (line  334)
* has_exec() (symtable.SymbolTable 方法): Examining Symbol Tables.
                                                             (line   44)
* has_extn() (smtplib.SMTP 方法):        SMTP Objects.       (line   78)
* has_function() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  210)
* has_header() (csv.Sniffer 方法):       模块内容<3>.        (line  188)
* has_header() (urllib.request.Request 方法): Request 对象.  (line   81)
* has_ic() (在 curses 模块中):           函数<3>.            (line  147)
* has_il() (在 curses 模块中):           函数<3>.            (line  152)
* has_ipv6() (在 socket 模块中):         常量<8>.            (line  206)
* has_key (2to3 fixer):                  修复器.             (line  113)
* has_key() (在 curses 模块中):          函数<3>.            (line  158)
* has_location (importlib.machinery.ModuleSpec 属性): importlib machinery -- Importers and path hooks.
                                                             (line  411)
* HAS_NEVER_CHECK_COMMON_NAME() (在 ssl 模块中): 常量<9>.    (line  327)
* has_nonstandard_attr() (http.cookiejar.Cookie 方法): Cookie 对象<2>.
                                                             (line   94)
* HAS_NPN() (在 ssl 模块中):             常量<9>.            (line  348)
* has_option() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line   91)
* has_option() (optparse.OptionParser 方法): Querying and manipulating your option parser.
                                                             (line   42)
* has_section() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line   82)
* HAS_SNI() (在 ssl 模块中):             常量<9>.            (line  341)
* HAS_SSLv2() (在 ssl 模块中):           常量<9>.            (line  356)
* HAS_SSLv3() (在 ssl 模块中):           常量<9>.            (line  362)
* has_ticket (ssl.SSLSession 属性):      SSL 会话.           (line   20)
* HAS_TLSv1() (在 ssl 模块中):           常量<9>.            (line  368)
* HAS_TLSv1_1() (在 ssl 模块中):         常量<9>.            (line  374)
* HAS_TLSv1_2() (在 ssl 模块中):         常量<9>.            (line  380)
* HAS_TLSv1_3() (在 ssl 模块中):         常量<9>.            (line  386)
* HAVE_ARGUMENT (opcode):                Python字节码说明.   (line  810)
* HAVE_CONTEXTVAR() (在 decimal 模块中): 常量<4>.            (line   30)
* HAVE_DOCSTRINGS() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  137)
* HAVE_THREADS() (在 decimal 模块中):    常量<4>.            (line   24)
* HCI_DATA_DIR() (在 socket 模块中):     常量<8>.            (line  217)
* HCI_FILTER() (在 socket 模块中):       常量<8>.            (line  217)
* HCI_TIME_STAMP() (在 socket 模块中):   常量<8>.            (line  217)
* head() (nntplib.NNTP 方法):            方法<3>.            (line  265)
* Header (email.header 中的类):          email header 国际化标头.
                                                             (line   49)
* HeaderError:                           tarfile --- 读写tar归档文件.
                                                             (line  183)
* HeaderParseError:                      email errors 异常和缺陷类.
                                                             (line   23)
* HeaderParser (email.parser 中的类):    Parser API.         (line   94)
* HeaderRegistry (email.headerregistry 中的类): email headerregistry 自定义标头对象.
                                                             (line  248)
* headers (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line   91)
* headers (urllib.error.HTTPError 属性): urllib error --- urllib request 引发的异常类.
                                                             (line   44)
* Headers (wsgiref.headers 中的类):      wsgiref headers -- WSGI response header tools.
                                                             (line    9)
* headers (xmlrpc.client.ProtocolError 属性): ProtocolError 对象.
                                                             (line   25)
* header_encode() (email.charset.Charset 方法): email charset 表示字符集.
                                                             (line  105)
* header_encode_lines() (email.charset.Charset 方法): email charset 表示字符集.
                                                             (line  112)
* header_encoding (email.charset.Charset 属性): email charset 表示字符集.
                                                             (line   52)
* header_factory (email.policy.EmailPolicy 属性): email policy 策略对象.
                                                             (line  315)
* header_fetch_parse() (email.policy.Compat32 方法): email policy 策略对象.
                                                             (line  466)
* header_fetch_parse() (email.policy.EmailPolicy 方法): email policy 策略对象.
                                                             (line  356)
* header_fetch_parse() (email.policy.Policy 方法): email policy 策略对象.
                                                             (line  242)
* header_items() (urllib.request.Request 方法): Request 对象.
                                                             (line  110)
* header_max_count() (email.policy.EmailPolicy 方法): email policy 策略对象.
                                                             (line  337)
* header_max_count() (email.policy.Policy 方法): email policy 策略对象.
                                                             (line  197)
* header_offset (zipfile.ZipInfo 属性):  ZipInfo 对象.       (line  122)
* header_source_parse() (email.policy.Compat32 方法): email policy 策略对象.
                                                             (line  456)
* header_source_parse() (email.policy.EmailPolicy 方法): email policy 策略对象.
                                                             (line  342)
* header_source_parse() (email.policy.Policy 方法): email policy 策略对象.
                                                             (line  213)
* header_store_parse() (email.policy.Compat32 方法): email policy 策略对象.
                                                             (line  462)
* header_store_parse() (email.policy.EmailPolicy 方法): email policy 策略对象.
                                                             (line  348)
* header_store_parse() (email.policy.Policy 方法): email policy 策略对象.
                                                             (line  229)
* heading() (tkinter.ttk.Treeview 方法): ttk Treeview.       (line  104)
* heading() (在 turtle 模块中):          获取海龟的状态.     (line   55)
* heapify() (在 heapq 模块中):           heapq --- 堆队列算法.
                                                             (line   47)
* heapmin() (在 msvcrt 模块中):          其他函数.           (line    6)
* heappop() (在 heapq 模块中):           heapq --- 堆队列算法.
                                                             (line   35)
* heappush() (在 heapq 模块中):          heapq --- 堆队列算法.
                                                             (line   31)
* heappushpop() (在 heapq 模块中):       heapq --- 堆队列算法.
                                                             (line   41)
* heapq (模块):                          heapq --- 堆队列算法.
                                                             (line    6)
* heapreplace() (在 heapq 模块中):       heapq --- 堆队列算法.
                                                             (line   51)
* helo() (smtplib.SMTP 方法):            SMTP Objects.       (line   44)
* help (optparse.Option 属性):           Option attributes.  (line   72)
* help (pdb command):                    调试器命令.         (line   34)
* help() (nntplib.NNTP 方法):            方法<3>.            (line  213)
* help() (內置函数):                     内置函数.           (line  594)
* help; online:                          pydoc --- 文档生成器和在线帮助系统.
                                                             (line    8)
* herror:                                异常<11>.           (line   13)
* hex (uuid.UUID 属性):                  uuid --- UUID objects according to RFC 4122.
                                                             (line  126)
* hex() (bytearray 方法):                bytearray 对象.     (line   45)
* hex() (bytes 方法):                    bytes 对象.         (line   64)
* hex() (float 方法):                    浮点类型的附加方法. (line   28)
* hex() (memoryview 方法):               内存视图.           (line  166)
* hex() (內置函数):                      内置函数.           (line  610)
* hexadecimal literal:                   数字字面值.         (line    6)
* hexadecimal; literals:                 数字类型 --- int float complex.
                                                             (line   14)
* hexbin() (在 binhex 模块中):           binhex --- 对binhex4文件进行编码和解码.
                                                             (line   21)
* hexdigest() (hashlib.hash 方法):       哈希算法.           (line  120)
* hexdigest() (hashlib.shake 方法):      SHAKE 可变长度摘要. (line   15)
* hexdigest() (hmac.HMAC 方法):          hmac --- 基于密钥的消息验证.
                                                             (line   60)
* hexdigits() (在 string 模块中):        字符串常量.         (line   27)
* hexlify() (在 binascii 模块中):        binascii --- 二进制和 ASCII 码互转.
                                                             (line  111)
* hexversion() (在 sys 模块中):          sys --- 系统相关的参数和函数.
                                                             (line  739)
* hidden() (curses.panel.Panel 方法):    Panel 对象.         (line   24)
* hide() (curses.panel.Panel 方法):      Panel 对象.         (line   28)
* hide() (tkinter.ttk.Notebook 方法):    ttk Notebook.       (line   23)
* hideturtle() (在 turtle 模块中):       可见性.             (line    6)
* hide_cookie2 (http.cookiejar.CookiePolicy 属性): CookiePolicy 对象.
                                                             (line   76)
* HierarchyRequestErr:                   异常<16>.           (line   23)
* HIGHEST_PROTOCOL() (在 pickle 模块中): 模块接口.           (line   13)
* HIGH_PRIORITY_CLASS() (在 subprocess 模块中): Windows 常数.
                                                             (line   59)
* HKEY_CLASSES_ROOT() (在 winreg 模块中): HKEY_* Constants.  (line    6)
* HKEY_CURRENT_CONFIG() (在 winreg 模块中): HKEY_* Constants.
                                                             (line   38)
* HKEY_CURRENT_USER() (在 winreg 模块中): HKEY_* Constants.  (line   12)
* HKEY_DYN_DATA() (在 winreg 模块中):    HKEY_* Constants.   (line   43)
* HKEY_LOCAL_MACHINE() (在 winreg 模块中): HKEY_* Constants. (line   19)
* HKEY_PERFORMANCE_DATA() (在 winreg 模块中): HKEY_* Constants.
                                                             (line   31)
* HKEY_USERS() (在 winreg 模块中):       HKEY_* Constants.   (line   25)
* hline() (curses.window 方法):          Window 对象.        (line  243)
* HList (tkinter.tix 中的类):            Hierarchical ListBox.
                                                             (line    6)
* hls_to_rgb() (在 colorsys 模块中):     colorsys --- 颜色系统间的转换.
                                                             (line   36)
* hmac (模块):                           hmac --- 基于密钥的消息验证.
                                                             (line    6)
* HOME:                                  os path.            (line   14)
* HOME <1>:                              Python API 的变化.  (line  103)
* HOME <2>:                              Windows<10>.        (line   13)
* HOME <3>:                              Windows<10>.        (line   16)
* HOME <4>:                              os path --- 常用路径操作.
                                                             (line  124)
* HOME <5>:                              os path --- 常用路径操作.
                                                             (line  136)
* HOME <6>:                              distutils util --- Miscellaneous other utility functions.
                                                             (line   77)
* HOME <7>:                              Location and names of config files.
                                                             (line   50)
* HOME <8>:                              Location and names of config files.
                                                             (line   67)
* home() (pathlib.Path 类方法):          方法<2>.            (line   23)
* home() (在 turtle 模块中):             海龟动作.           (line  154)
* HOMEDRIVE:                             os path --- 常用路径操作.
                                                             (line  129)
* HOMEDRIVE <1>:                         Location and names of config files.
                                                             (line   68)
* HOMEPATH:                              os path --- 常用路径操作.
                                                             (line  128)
* HOMEPATH <1>:                          Location and names of config files.
                                                             (line   68)
* hooks; import:                         导入钩子.           (line    6)
* hooks; meta:                           导入钩子.           (line    6)
* hooks; path:                           导入钩子.           (line    6)
* hook_compressed() (在 fileinput 模块中): fileinput --- 迭代来自多个输入流的行.
                                                             (line  155)
* hook_encoded() (在 fileinput 模块中):  fileinput --- 迭代来自多个输入流的行.
                                                             (line  165)
* host (urllib.request.Request 属性):    Request 对象.       (line   23)
* hostmask (ipaddress.IPv4Network 属性): Network objects.    (line   97)
* hostmask (ipaddress.IPv6Network 属性): Network objects.    (line  313)
* hostname_checks_common_name (ssl.SSLContext 属性): SSL 上下文.
                                                             (line  548)
* hosts (netrc.netrc 属性):              netrc 对象.         (line   22)
* hosts() (ipaddress.IPv4Network 方法):  Network objects.    (line  136)
* hosts() (ipaddress.IPv6Network 方法):  Network objects.    (line  331)
* hour (datetime.datetime 属性):         datetime 对象.      (line  254)
* hour (datetime.time 属性):             time 对象.          (line   46)
* HRESULT (ctypes 中的类):               基础数据类型<2>.    (line  184)
* hStdError (subprocess.STARTUPINFO 属性): Windows Popen 助手.
                                                             (line   38)
* hStdInput (subprocess.STARTUPINFO 属性): Windows Popen 助手.
                                                             (line   25)
* hStdOutput (subprocess.STARTUPINFO 属性): Windows Popen 助手.
                                                             (line   32)
* hsv_to_rgb() (在 colorsys 模块中):     colorsys --- 颜色系统间的转换.
                                                             (line   44)
* ht() (在 turtle 模块中):               可见性.             (line    6)
* HTML:                                  html parser --- 简单的 HTML 和 XHTML 解析器.
                                                             (line    8)
* HTML <1>:                              urllib request Restrictions.
                                                             (line   29)
* html (模块):                           html --- 超文本标记语言支持.
                                                             (line    6)
* html() (在 cgitb 模块中):              cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line   45)
* html.entities (模块):                  html entities --- HTML 一般实体的定义.
                                                             (line    6)
* html.parser (模块):                    html parser --- 简单的 HTML 和 XHTML 解析器.
                                                             (line    6)
* html5() (在 html.entities 模块中):     html entities --- HTML 一般实体的定义.
                                                             (line   13)
* HTMLCalendar (calendar 中的类):        calendar --- 日历相关函数.
                                                             (line  134)
* HtmlDiff (difflib 中的类):             difflib --- 计算差异的辅助工具.
                                                             (line   66)
* HTMLParser (html.parser 中的类):       html parser --- 简单的 HTML 和 XHTML 解析器.
                                                             (line   13)
* htonl() (在 socket 模块中):            其他功能<2>.        (line  165)
* htons() (在 socket 模块中):            其他功能<2>.        (line  170)
* http (模块):                           http --- HTTP 模块. (line    6)
* HTTP() (在 email.policy 模块中):       email policy 策略对象.
                                                             (line  409)
* http.client (模块):                    http client --- HTTP 协议客户端.
                                                             (line    6)
* http.cookiejar (模块):                 http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line    6)
* http.cookies (模块):                   http cookies --- HTTP状态管理.
                                                             (line    6)
* http.server (模块):                    http server --- HTTP 服务器.
                                                             (line    6)
* HTTP; http (standard module):          http --- HTTP 模块. (line    8)
* HTTP; http.client (standard module):   http client --- HTTP 协议客户端.
                                                             (line    8)
* HTTP; protocol:                        cgi --- 通用网关接口支持.
                                                             (line    8)
* HTTP; protocol <1>:                    urllib request Restrictions.
                                                             (line    6)
* HTTP; protocol <2>:                    urllib request Restrictions.
                                                             (line   29)
* HTTP; protocol <3>:                    http --- HTTP 模块. (line    8)
* HTTP; protocol <4>:                    http client --- HTTP 协议客户端.
                                                             (line    8)
* HTTP; protocol <5>:                    http server --- HTTP 服务器.
                                                             (line    8)
* HTTPBasicAuthHandler (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  293)
* HTTPConnection (http.client 中的类):   http client --- HTTP 协议客户端.
                                                             (line   23)
* HTTPCookieProcessor (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  238)
* httpd:                                 http server --- HTTP 服务器.
                                                             (line    8)
* HTTPDefaultErrorHandler (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  229)
* HTTPDigestAuthHandler (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  312)
* HTTPError:                             urllib error --- urllib request 引发的异常类.
                                                             (line   27)
* HTTPErrorProcessor (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  365)
* HTTPException:                         http client --- HTTP 协议客户端.
                                                             (line  114)
* HTTPHandler (logging.handlers 中的类): HTTPHandler.        (line    9)
* HTTPHandler (urllib.request 中的类):   urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  331)
* HTTPPasswordMgr (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  259)
* HTTPPasswordMgrWithDefaultRealm (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  263)
* HTTPPasswordMgrWithPriorAuth (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  268)
* HTTPRedirectHandler (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  234)
* HTTPResponse (http.client 中的类):     http client --- HTTP 协议客户端.
                                                             (line   84)
* HTTPSConnection (http.client 中的类):  http client --- HTTP 协议客户端.
                                                             (line   49)
* HTTPServer (http.server 中的类):       http server --- HTTP 服务器.
                                                             (line   24)
* HTTPSHandler (urllib.request 中的类):  urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  335)
* HTTPStatus (http 中的类):              http --- HTTP 模块. (line   26)
* https_open() (urllib.request.HTTPSHandler 方法): HTTPSHandler 对象.
                                                             (line    6)
* HTTPS_PORT() (在 http.client 模块中):  http client --- HTTP 协议客户端.
                                                             (line  184)
* https_response() (urllib.request.HTTPErrorProcessor 方法): HTTPErrorProcessor 对象.
                                                             (line   17)
* http_error_301() (urllib.request.HTTPRedirectHandler 方法): HTTPRedirectHandler 对象.
                                                             (line   28)
* http_error_302() (urllib.request.HTTPRedirectHandler 方法): HTTPRedirectHandler 对象.
                                                             (line   33)
* http_error_303() (urllib.request.HTTPRedirectHandler 方法): HTTPRedirectHandler 对象.
                                                             (line   38)
* http_error_307() (urllib.request.HTTPRedirectHandler 方法): HTTPRedirectHandler 对象.
                                                             (line   43)
* http_error_401() (urllib.request.HTTPBasicAuthHandler 方法): HTTPBasicAuthHandler 对象.
                                                             (line    6)
* http_error_401() (urllib.request.HTTPDigestAuthHandler 方法): HTTPDigestAuthHandler 对象.
                                                             (line    6)
* http_error_407() (urllib.request.ProxyBasicAuthHandler 方法): ProxyBasicAuthHandler 对象.
                                                             (line    6)
* http_error_407() (urllib.request.ProxyDigestAuthHandler 方法): ProxyDigestAuthHandler 对象.
                                                             (line    6)
* http_error_auth_reqed() (urllib.request.AbstractBasicAuthHandler 方法): AbstractBasicAuthHandler 对象.
                                                             (line    6)
* http_error_auth_reqed() (urllib.request.AbstractDigestAuthHandler 方法): AbstractDigestAuthHandler 对象.
                                                             (line    6)
* http_error_default() (urllib.request.BaseHandler 方法): BaseHandler 对象.
                                                             (line   58)
* http_open() (urllib.request.HTTPHandler 方法): HTTPHandler 对象.
                                                             (line    6)
* HTTP_PORT() (在 http.client 模块中):   http client --- HTTP 协议客户端.
                                                             (line  180)
* http_proxy:                            urllib request --- 用于打开 URL 的可扩展库.
                                                             (line   75)
* http_proxy <1>:                        例子<21>.           (line   89)
* http_proxy <2>:                        基本认证.           (line   57)
* http_response() (urllib.request.HTTPErrorProcessor 方法): HTTPErrorProcessor 对象.
                                                             (line    6)
* http_version (wsgiref.handlers.BaseHandler 属性): wsgiref handlers -- server/gateway base classes.
                                                             (line  299)
* hypot() (在 math 模块中):              三角函数.           (line   41)
* I() (在 re 模块中):                    模块内容.           (line   52)
* I/O control; buffering:                内置函数.           (line 1017)
* I/O control; buffering <1>:            套接字对象.         (line  171)
* iadd() (在 operator 模块中):           原地运算符.         (line   33)
* iand() (在 operator 模块中):           原地运算符.         (line   38)
* iconcat() (在 operator 模块中):        原地运算符.         (line   43)
* id (ssl.SSLSession 属性):              SSL 会话.           (line   12)
* id() (unittest.TestCase 方法):         测试用例.           (line  720)
* id() (內置函数):                       内置函数.           (line  639)
* idcok() (curses.window 方法):          Window 对象.        (line  249)
* ident (select.kevent 属性):            Kevent 对象.        (line    8)
* ident (threading.Thread 属性):         线程对象.           (line  124)
* identchars (cmd.Cmd 属性):             Cmd 对象.           (line   99)
* identifier:                            标识符和关键字.     (line    6)
* identifier <1>:                        标识符（名称）.     (line    6)
* identify() (tkinter.ttk.Notebook 方法): ttk Notebook.      (line   32)
* identify() (tkinter.ttk.Treeview 方法): ttk Treeview.      (line  142)
* identify() (tkinter.ttk.Widget 方法):  ttk Widget.         (line   11)
* identify_column() (tkinter.ttk.Treeview 方法): ttk Treeview.
                                                             (line  152)
* identify_element() (tkinter.ttk.Treeview 方法): ttk Treeview.
                                                             (line  181)
* identify_region() (tkinter.ttk.Treeview 方法): ttk Treeview.
                                                             (line  159)
* identify_row() (tkinter.ttk.Treeview 方法): ttk Treeview.  (line  148)
* identity of an object:                 对象、值与类型.     (line   10)
* identity; test:                        成员检测运算.       (line   32)
* idioms (2to3 fixer):                   修复器.             (line  117)
* IDLE:                                  IDLE<54>.           (line    8)
* IDLE <1>:                              术语对照表.         (line  483)
* IDLESTARTUP:                           IDLE<27>.           (line  174)
* IDLESTARTUP <1>:                       IDLE<31>.           (line    9)
* IDLESTARTUP <2>:                       IDLE<37>.           (line    9)
* IDLESTARTUP <3>:                       启动和代码执行.     (line    7)
* IDLE_PRIORITY_CLASS() (在 subprocess 模块中): Windows 常数.
                                                             (line   66)
* idlok() (curses.window 方法):          Window 对象.        (line  255)
* if; conditional expression:            条件表达式.         (line    6)
* if; in comprehensions:                 列表、集合与字典的显示.
                                                             (line   13)
* ifloordiv() (在 operator 模块中):      原地运算符.         (line   48)
* if_indextoname() (在 socket 模块中):   其他功能<2>.        (line  334)
* if_nameindex() (在 socket 模块中):     其他功能<2>.        (line  293)
* if_nametoindex() (在 socket 模块中):   其他功能<2>.        (line  318)
* iglob() (在 glob 模块中):              glob --- Unix 风格路径名模式扩展.
                                                             (line   49)
* ignorableWhitespace() (xml.sax.handler.ContentHandler 方法): ContentHandler 对象.
                                                             (line  126)
* ignore (pdb command):                  调试器命令.         (line   91)
* IGNORECASE() (在 re 模块中):           模块内容.           (line   52)
* ignore_errors() (在 codecs 模块中):    错误处理方案.       (line  116)
* IGNORE_EXCEPTION_DETAIL() (在 doctest 模块中): Option Flags.
                                                             (line   58)
* ignore_patterns() (在 shutil 模块中):  目录和文件操作.     (line  155)
* ihave() (nntplib.NNTP 方法):           方法<3>.            (line  290)
* IISCGIHandler (wsgiref.handlers 中的类): wsgiref handlers -- server/gateway base classes.
                                                             (line   24)
* ilshift() (在 operator 模块中):        原地运算符.         (line   53)
* imag (numbers.Complex 属性):           数字的层次.         (line   18)
* imaginary literal:                     数字字面值.         (line    6)
* imap() (multiprocessing.pool.Pool 方法): 进程池.           (line  100)
* IMAP4 (imaplib 中的类):                imaplib --- IMAP4 协议客户端.
                                                             (line   17)
* IMAP4.abort:                           imaplib --- IMAP4 协议客户端.
                                                             (line   45)
* IMAP4.error:                           imaplib --- IMAP4 协议客户端.
                                                             (line   40)
* IMAP4.readonly:                        imaplib --- IMAP4 协议客户端.
                                                             (line   52)
* IMAP4; protocol:                       imaplib --- IMAP4 协议客户端.
                                                             (line    8)
* IMAP4_SSL (imaplib 中的类):            imaplib --- IMAP4 协议客户端.
                                                             (line   61)
* IMAP4_SSL; protocol:                   imaplib --- IMAP4 协议客户端.
                                                             (line    8)
* IMAP4_stream (imaplib 中的类):         imaplib --- IMAP4 协议客户端.
                                                             (line   94)
* IMAP4_stream; protocol:                imaplib --- IMAP4 协议客户端.
                                                             (line    8)
* imaplib (模块):                        imaplib --- IMAP4 协议客户端.
                                                             (line    6)
* imap_unordered() (multiprocessing.pool.Pool 方法): 进程池. (line  113)
* imatmul() (在 operator 模块中):        原地运算符.         (line   68)
* imghdr (模块):                         imghdr --- 推测图像类型.
                                                             (line    6)
* immedok() (curses.window 方法):        Window 对象.        (line  260)
* immutable – 不可变:                    术语对照表.         (line  488)
* immutable object:                      对象、值与类型.     (line   10)
* immutable; data; type:                 字面值<2>.          (line   15)
* immutable; object:                     字面值<2>.          (line   15)
* immutable; object <1>:                 字典显示.           (line   29)
* immutable; sequence; types:            不可变序列类型.     (line    6)
* imod() (在 operator 模块中):           原地运算符.         (line   58)
* imp (模块):                            imp --- Access the import internals.
                                                             (line    6)
* ImpImporter (pkgutil 中的类):          pkgutil --- 包扩展工具.
                                                             (line   52)
* implementation() (在 sys 模块中):      sys --- 系统相关的参数和函数.
                                                             (line  759)
* ImpLoader (pkgutil 中的类):            pkgutil --- 包扩展工具.
                                                             (line   68)
* impl_detail() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  636)
* import (2to3 fixer):                   修复器.             (line  132)
* import hooks:                          导入钩子.           (line    6)
* import machinery:                      导入系统.           (line    6)
* import path – 导入路径:                术语对照表.         (line  494)
* importer – 导入器:                     术语对照表.         (line  506)
* ImportError:                           具体异常.           (line   35)
* importing – 导入:                      术语对照表.         (line  501)
* importlib (模块):                      importlib --- import 的实现.
                                                             (line    6)
* importlib.abc (模块):                  importlib abc —— 关于导入的抽象基类.
                                                             (line    6)
* importlib.machinery (模块):            importlib machinery -- Importers and path hooks.
                                                             (line    6)
* importlib.metadata (模块):             Using importlib metadata.
                                                             (line    6)
* importlib.resources (模块):            importlib resources -- 资源.
                                                             (line    6)
* importlib.util (模块):                 importlib util -- Utility code for importers.
                                                             (line    6)
* imports (2to3 fixer):                  修复器.             (line  136)
* imports2 (2to3 fixer):                 修复器.             (line  140)
* ImportWarning:                         警告.               (line   41)
* import_fresh_module() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  732)
* IMPORT_FROM (opcode):                  Python字节码说明.   (line  586)
* import_module() (在 importlib 模块中): 函数<10>.           (line   14)
* import_module() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  717)
* IMPORT_NAME (opcode):                  Python字节码说明.   (line  579)
* IMPORT_STAR (opcode):                  Python字节码说明.   (line  345)
* ImproperConnectionState:               http client --- HTTP 协议客户端.
                                                             (line  143)
* imul() (在 operator 模块中):           原地运算符.         (line   63)
* inch() (curses.window 方法):           Window 对象.        (line  266)
* inclusive (tracemalloc.DomainFilter 属性): 域过滤器.       (line   12)
* inclusive (tracemalloc.Filter 属性):   过滤器.             (line   38)
* inclusive; or:                         二元位运算.         (line   16)
* Incomplete:                            binascii --- 二进制和 ASCII 码互转.
                                                             (line  151)
* IncompleteRead:                        http client --- HTTP 协议客户端.
                                                             (line  139)
* IncompleteReadError:                   异常<9>.            (line   38)
* IncrementalDecoder (codecs 中的类):    IncrementalDecoder 对象.
                                                             (line   10)
* incrementaldecoder (codecs.CodecInfo 属性): codecs --- 编解码器注册和相关基类.
                                                             (line   68)
* IncrementalEncoder (codecs 中的类):    IncrementalEncoder 对象.
                                                             (line   10)
* incrementalencoder (codecs.CodecInfo 属性): codecs --- 编解码器注册和相关基类.
                                                             (line   68)
* IncrementalNewlineDecoder (io 中的类): 文本 I/O<2>.        (line  203)
* IncrementalParser (xml.sax.xmlreader 中的类): xml sax xmlreader --- 用于 XML 解析器的接口.
                                                             (line   18)
* increment_lineno() (在 ast 模块中):    ast 中的辅助函数.   (line   86)
* incr_item():                           异常<18>.           (line   76)
* incr_item() <1>:                       异常<18>.           (line  121)
* indent (doctest.Example 属性):         Example Objects.    (line   47)
* INDENT token:                          缩进.               (line   25)
* indent() (在 textwrap 模块中):         textwrap --- 文本自动换行与填充.
                                                             (line   82)
* INDENT() (在 token 模块中):            token --- 与Python解析树一起使用的常量.
                                                             (line   46)
* indentation:                           缩进.               (line    6)
* IndentationError:                      具体异常.           (line  234)
* index operation:                       标准类型层级结构.   (line   93)
* index() (array.array 方法):            array --- 高效的数值数组.
                                                             (line  170)
* index() (bytearray 方法):              bytes 和 bytearray 操作.
                                                             (line   87)
* index() (bytes 方法):                  bytes 和 bytearray 操作.
                                                             (line   87)
* index() (collections.deque 方法):      deque 对象.         (line   60)
* index() (multiprocessing.shared_memory.ShareableList 方法): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  230)
* index() (sequence method):             通用序列操作.       (line   17)
* index() (str 方法):                    字符串的方法<2>.    (line  139)
* index() (tkinter.ttk.Notebook 方法):   ttk Notebook.       (line   37)
* index() (tkinter.ttk.Treeview 方法):   ttk Treeview.       (line  187)
* index() (在 operator 模块中):          operator --- 标准运算符替代函数.
                                                             (line   82)
* IndexError:                            具体异常.           (line   53)
* indexOf() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line  182)
* IndexSizeErr:                          异常<16>.           (line   27)
* indices() (slice 方法):                标准类型层级结构.   (line  612)
* inet_aton() (在 socket 模块中):        其他功能<2>.        (line  179)
* inet_ntoa() (在 socket 模块中):        其他功能<2>.        (line  195)
* inet_ntop() (在 socket 模块中):        其他功能<2>.        (line  224)
* inet_pton() (在 socket 模块中):        其他功能<2>.        (line  208)
* Inexact (decimal 中的类):              信号.               (line   36)
* inf() (在 cmath 模块中):               常量<3>.            (line   20)
* inf() (在 math 模块中):                常量<2>.            (line   22)
* infile (shlex.shlex 属性):             shlex Objects.      (line  139)
* Infinity:                              内置函数.           (line  490)
* infj() (在 cmath 模块中):              常量<3>.            (line   26)
* info() (dis.Bytecode 方法):            字节码分析.         (line   46)
* info() (gettext.NullTranslations 方法): NullTranslations 类.
                                                             (line   66)
* info() (logging.Logger 方法):          记录器对象.         (line  166)
* info() (在 logging 模块中):            模块级别函数.       (line   97)
* infolist() (zipfile.ZipFile 方法):     ZipFile 对象.       (line   85)
* inheritance:                           类定义.             (line    6)
* ini file:                              configparser --- 配置文件解析器.
                                                             (line    8)
* init() (在 mimetypes 模块中):          mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line   66)
* inited() (在 mimetypes 模块中):        mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line   98)
* initgroups() (在 os 模块中):           进程参数.           (line  280)
* initialize_options() (distutils.cmd.Command 方法): Creating a new Distutils command.
                                                             (line   21)
* initial_indent (textwrap.TextWrapper 属性): textwrap --- 文本自动换行与填充.
                                                             (line  178)
* initproc (C 类型):                     Slot Type typedefs. (line   45)
* initscr() (在 curses 模块中):          函数<3>.            (line  188)
* init_color() (在 curses 模块中):       函数<3>.            (line  170)
* init_database() (在 msilib 模块中):    msilib --- Read and write Microsoft Installer files.
                                                             (line   60)
* init_pair() (在 curses 模块中):        函数<3>.            (line  179)
* inode() (os.DirEntry 方法):            文件和目录.         (line  762)
* INPLACE_ADD (opcode):                  Python字节码说明.   (line  213)
* INPLACE_AND (opcode):                  Python字节码说明.   (line  229)
* INPLACE_FLOOR_DIVIDE (opcode):         Python字节码说明.   (line  201)
* INPLACE_LSHIFT (opcode):               Python字节码说明.   (line  221)
* INPLACE_MATRIX_MULTIPLY (opcode):      Python字节码说明.   (line  195)
* INPLACE_MODULO (opcode):               Python字节码说明.   (line  209)
* INPLACE_MULTIPLY (opcode):             Python字节码说明.   (line  191)
* INPLACE_OR (opcode):                   Python字节码说明.   (line  237)
* INPLACE_POWER (opcode):                Python字节码说明.   (line  187)
* INPLACE_RSHIFT (opcode):               Python字节码说明.   (line  225)
* INPLACE_SUBTRACT (opcode):             Python字节码说明.   (line  217)
* INPLACE_TRUE_DIVIDE (opcode):          Python字节码说明.   (line  205)
* INPLACE_XOR (opcode):                  Python字节码说明.   (line  233)
* input:                                 表达式输入.         (line    6)
* input (2to3 fixer):                    修复器.             (line  145)
* input() (內置函数):                    内置函数.           (line  650)
* input() (在 fileinput 模块中):         fileinput --- 迭代来自多个输入流的行.
                                                             (line   46)
* InputOnly (tkinter.tix 中的类):        Miscellaneous Widgets.
                                                             (line    6)
* InputSource (xml.sax.xmlreader 中的类): xml sax xmlreader --- 用于 XML 解析器的接口.
                                                             (line   42)
* input_charset (email.charset.Charset 属性): email charset 表示字符集.
                                                             (line   46)
* input_codec (email.charset.Charset 属性): email charset 表示字符集.
                                                             (line   72)
* inquiry (C 类型):                      使对象类型支持循环垃圾回收.
                                                             (line  114)
* insch() (curses.window 方法):          Window 对象.        (line  271)
* insdelln() (curses.window 方法):       Window 对象.        (line  278)
* insert() (array.array 方法):           array --- 高效的数值数组.
                                                             (line  174)
* insert() (collections.deque 方法):     deque 对象.         (line   68)
* insert() (sequence method):            可变序列类型.       (line   14)
* insert() (tkinter.ttk.Notebook 方法):  ttk Notebook.       (line   42)
* insert() (tkinter.ttk.Treeview 方法):  ttk Treeview.       (line  192)
* insert() (xml.etree.ElementTree.Element 方法): 元素对象.   (line  120)
* insertBefore() (xml.dom.Node 方法):    节点对象.           (line  104)
* insertln() (curses.window 方法):       Window 对象.        (line  285)
* insert_text() (在 readline 模块中):    行缓冲区.           (line   12)
* insnstr() (curses.window 方法):        Window 对象.        (line  289)
* insort() (在 bisect 模块中):           bisect --- 数组二分查找算法.
                                                             (line   44)
* insort_left() (在 bisect 模块中):      bisect --- 数组二分查找算法.
                                                             (line   38)
* insort_right() (在 bisect 模块中):     bisect --- 数组二分查找算法.
                                                             (line   44)
* inspect (模块):                        inspect --- 检查对象.
                                                             (line    6)
* inspect command line option; –details: 命令行界面<8>.      (line   13)
* InspectLoader (importlib.abc 中的类):  importlib abc —— 关于导入的抽象基类.
                                                             (line  331)
* insstr() (curses.window 方法):         Window 对象.        (line  298)
* install() (gettext.NullTranslations 方法): NullTranslations 类.
                                                             (line   88)
* install() (在 gettext 模块中):         基于类的 API.       (line   60)
* installHandler() (在 unittest 模块中): 信号处理.           (line   29)
* install_opener() (在 urllib.request 模块中): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  102)
* install_scripts() (venv.EnvBuilder 方法): API<2>.          (line  109)
* instance; call:                        调用.               (line  119)
* instate() (tkinter.ttk.Widget 方法):   ttk Widget.         (line   18)
* instr() (curses.window 方法):          Window 对象.        (line  306)
* instream (shlex.shlex 属性):           shlex Objects.      (line  145)
* Instruction (dis 中的类):              Python字节码说明.   (line    9)
* Instruction.arg() (在 dis 模块中):     Python字节码说明.   (line   22)
* Instruction.argrepr() (在 dis 模块中): Python字节码说明.   (line   30)
* Instruction.argval() (在 dis 模块中):  Python字节码说明.   (line   26)
* Instruction.is_jump_target() (在 dis 模块中): Python字节码说明.
                                                             (line   42)
* Instruction.offset() (在 dis 模块中):  Python字节码说明.   (line   34)
* Instruction.opcode() (在 dis 模块中):  Python字节码说明.   (line   13)
* Instruction.opname() (在 dis 模块中):  Python字节码说明.   (line   18)
* Instruction.starts_line() (在 dis 模块中): Python字节码说明.
                                                             (line   38)
* int (uuid.UUID 属性):                  uuid --- UUID objects according to RFC 4122.
                                                             (line  130)
* int (內置类):                          内置函数.           (line  669)
* Int2AP() (在 imaplib 模块中):          imaplib --- IMAP4 协议客户端.
                                                             (line  108)
* integer:                               标准类型层级结构.   (line  117)
* integer literal:                       数字字面值.         (line    6)
* integer; literals:                     数字类型 --- int float complex.
                                                             (line   14)
* integer; representation:               标准类型层级结构.   (line   74)
* Integral (numbers 中的类):             数字的层次.         (line   53)
* Integrated Development Environment:    IDLE<54>.           (line    8)
* IntegrityError:                        异常<4>.            (line   18)
* Intel/DVI ADPCM:                       audioop --- 处理原始音频数据.
                                                             (line   15)
* IntEnum (enum 中的类):                 模块内容<2>.        (line   16)
* interact (pdb command):                调试器命令.         (line  229)
* interact() (code.InteractiveConsole 方法): 交互式控制台对象.
                                                             (line    9)
* interact() (telnetlib.Telnet 方法):    Telnet 对象.        (line  103)
* interact() (在 code 模块中):           code --- 解释器基类.
                                                             (line   27)
* interactive – 交互:                    术语对照表.         (line  511)
* interactive mode:                      完整的 Python 程序. (line   15)
* InteractiveConsole (code 中的类):      code --- 解释器基类.
                                                             (line   21)
* InteractiveInterpreter (code 中的类):  code --- 解释器基类.
                                                             (line   13)
* intern (2to3 fixer):                   修复器.             (line  149)
* intern() (在 sys 模块中):              sys --- 系统相关的参数和函数.
                                                             (line  824)
* internal type:                         标准类型层级结构.   (line  487)
* Internaldate2tuple() (在 imaplib 模块中): imaplib --- IMAP4 协议客户端.
                                                             (line  102)
* internalSubset (xml.dom.DocumentType 属性): 文档类型对象.  (line   22)
* internal_attr (zipfile.ZipInfo 属性):  ZipInfo 对象.       (line  114)
* Internet:                              互联网协议和支持.   (line    6)
* interpolated string literal:           字符串字面值拼接.   (line   20)
* interpolation, string (%):             printf 风格的字符串格式化.
                                                             (line    6)
* interpolation; bytearray (%):          printf 风格的字节串格式化.
                                                             (line    6)
* interpolation; bytes (%):              printf 风格的字节串格式化.
                                                             (line    6)
* InterpolationDepthError:               异常<5>.            (line   36)
* InterpolationError:                    异常<5>.            (line   32)
* InterpolationMissingOptionError:       异常<5>.            (line   41)
* InterpolationSyntaxError:              异常<5>.            (line   46)
* interpreted – 解释型:                  术语对照表.         (line  518)
* interpreter:                           最高层级组件.       (line    6)
* interpreter lock:                      Thread State and the Global Interpreter Lock.
                                                             (line    6)
* interpreter prompts:                   sys --- 系统相关的参数和函数.
                                                             (line 1010)
* interpreter shutdown – 解释器关闭:     术语对照表.         (line  526)
* interpreter_requires_environment() (在 test.support.script_helper 模块中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line    9)
* interrupt() (sqlite3.Connection 方法): 连接对象（Connection）.
                                                             (line  173)
* InterruptedError:                      OS 异常.            (line   64)
* interrupt_main() (在 _thread 模块中):  _thread --- 底层多线程 API.
                                                             (line   43)
* intersection() (frozenset 方法):       集合类型 --- set frozenset.
                                                             (line   93)
* intersection_update() (frozenset 方法): 集合类型 --- set frozenset.
                                                             (line  157)
* IntFlag (enum 中的类):                 模块内容<2>.        (line   20)
* intro (cmd.Cmd 属性):                  Cmd 对象.           (line  113)
* int_info() (在 sys 模块中):            sys --- 系统相关的参数和函数.
                                                             (line  794)
* InuseAttributeErr:                     异常<16>.           (line   31)
* inv() (在 operator 模块中):            operator --- 标准运算符替代函数.
                                                             (line   87)
* InvalidAccessErr:                      异常<16>.           (line   35)
* invalidate_caches() (importlib.abc.MetaPathFinder 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line   82)
* invalidate_caches() (importlib.abc.PathEntryFinder 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  140)
* invalidate_caches() (importlib.machinery.FileFinder 方法): importlib machinery -- Importers and path hooks.
                                                             (line  195)
* invalidate_caches() (importlib.machinery.PathFinder 类方法): importlib machinery -- Importers and path hooks.
                                                             (line  140)
* invalidate_caches() (在 importlib 模块中): 函数<10>.       (line   55)
* InvalidCharacterErr:                   异常<16>.           (line   39)
* InvalidModificationErr:                异常<16>.           (line   45)
* InvalidOperation (decimal 中的类):     信号.               (line   43)
* InvalidStateErr:                       异常<16>.           (line   49)
* InvalidStateError:                     Exception类.        (line   21)
* InvalidStateError <1>:                 异常<9>.            (line   26)
* InvalidURL:                            http client --- HTTP 协议客户端.
                                                             (line  122)
* inversion:                             一元算术和位运算.   (line   14)
* invert() (在 operator 模块中):         operator --- 标准运算符替代函数.
                                                             (line   87)
* invocation:                            标准类型层级结构.   (line  224)
* inv_cdf() (statistics.NormalDist 方法): NormalDist 对象.   (line   72)
* in_dll() (ctypes._CData 方法):         数据类型<2>.        (line   55)
* in_table_a1() (在 stringprep 模块中):  stringprep --- 因特网字符串预备.
                                                             (line   29)
* in_table_b1() (在 stringprep 模块中):  stringprep --- 因特网字符串预备.
                                                             (line   33)
* in_table_c11() (在 stringprep 模块中): stringprep --- 因特网字符串预备.
                                                             (line   47)
* in_table_c11_c12() (在 stringprep 模块中): stringprep --- 因特网字符串预备.
                                                             (line   55)
* in_table_c12() (在 stringprep 模块中): stringprep --- 因特网字符串预备.
                                                             (line   51)
* in_table_c21() (在 stringprep 模块中): stringprep --- 因特网字符串预备.
                                                             (line   59)
* in_table_c21_c22() (在 stringprep 模块中): stringprep --- 因特网字符串预备.
                                                             (line   67)
* in_table_c22() (在 stringprep 模块中): stringprep --- 因特网字符串预备.
                                                             (line   63)
* in_table_c3() (在 stringprep 模块中):  stringprep --- 因特网字符串预备.
                                                             (line   71)
* in_table_c4() (在 stringprep 模块中):  stringprep --- 因特网字符串预备.
                                                             (line   75)
* in_table_c5() (在 stringprep 模块中):  stringprep --- 因特网字符串预备.
                                                             (line   79)
* in_table_c6() (在 stringprep 模块中):  stringprep --- 因特网字符串预备.
                                                             (line   83)
* in_table_c7() (在 stringprep 模块中):  stringprep --- 因特网字符串预备.
                                                             (line   87)
* in_table_c8() (在 stringprep 模块中):  stringprep --- 因特网字符串预备.
                                                             (line   91)
* in_table_c9() (在 stringprep 模块中):  stringprep --- 因特网字符串预备.
                                                             (line   95)
* in_table_d1() (在 stringprep 模块中):  stringprep --- 因特网字符串预备.
                                                             (line   99)
* in_table_d2() (在 stringprep 模块中):  stringprep --- 因特网字符串预备.
                                                             (line  103)
* in_transaction (sqlite3.Connection 属性): 连接对象（Connection）.
                                                             (line   16)
* IO (typing 中的类):                    类 函数和修饰器.    (line  442)
* io (模块):                             io --- 处理流的核心工具.
                                                             (line    6)
* IOBase (io 中的类):                    I/O 基类.           (line    6)
* ioctl() (socket.socket 方法):          套接字对象.         (line  144)
* ioctl() (在 fcntl 模块中):             fcntl --- The fcntl and ioctl system calls.
                                                             (line   54)
* IOCTL_VM_SOCKETS_GET_LOCAL_CID() (在 socket 模块中): 常量<8>.
                                                             (line  187)
* IOError:                               具体异常.           (line  353)
* ior() (在 operator 模块中):            原地运算符.         (line   75)
* IO_REPARSE_TAG_APPEXECLINK() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  390)
* IO_REPARSE_TAG_MOUNT_POINT() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  390)
* IO_REPARSE_TAG_SYMLINK() (在 stat 模块中): stat --- 解析 stat 结果.
                                                             (line  390)
* ip (ipaddress.IPv4Interface 属性):     Interface objects.  (line   19)
* ip (ipaddress.IPv6Interface 属性):     Interface objects.  (line   74)
* ipaddress (模块):                      ipaddress --- IPv4/IPv6 操作库.
                                                             (line    6)
* ipow() (在 operator 模块中):           原地运算符.         (line   80)
* IPv4Address (ipaddress 中的类):        地址对象.           (line   11)
* IPv4Interface (ipaddress 中的类):      Interface objects.  (line    9)
* IPv4Network (ipaddress 中的类):        Network objects.    (line   13)
* ipv4_mapped (ipaddress.IPv6Address 属性): 地址对象.        (line  197)
* IPv6Address (ipaddress 中的类):        地址对象.           (line  126)
* IPv6Interface (ipaddress 中的类):      Interface objects.  (line   64)
* IPv6Network (ipaddress 中的类):        Network objects.    (line  253)
* IPV6_ENABLED() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line   83)
* ip_address() (在 ipaddress 模块中):    方便的工厂函数.     (line    9)
* ip_interface() (在 ipaddress 模块中):  方便的工厂函数.     (line   33)
* ip_network() (在 ipaddress 模块中):    方便的工厂函数.     (line   21)
* irshift() (在 operator 模块中):        原地运算符.         (line   85)
* isabs() (在 os.path 模块中):           os path --- 常用路径操作.
                                                             (line  178)
* isabstract() (在 inspect 模块中):      类型和成员.         (line  399)
* IsADirectoryError:                     OS 异常.            (line   73)
* isalnum() (bytearray 方法):            bytes 和 bytearray 操作.
                                                             (line  365)
* isalnum() (bytes 方法):                bytes 和 bytearray 操作.
                                                             (line  365)
* isalnum() (str 方法):                  字符串的方法<2>.    (line  144)
* isalnum() (在 curses.ascii 模块中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  127)
* isalpha() (bytearray 方法):            bytes 和 bytearray 操作.
                                                             (line  381)
* isalpha() (bytes 方法):                bytes 和 bytearray 操作.
                                                             (line  381)
* isalpha() (str 方法):                  字符串的方法<2>.    (line  152)
* isalpha() (在 curses.ascii 模块中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  131)
* isascii() (bytearray 方法):            bytes 和 bytearray 操作.
                                                             (line  396)
* isascii() (bytes 方法):                bytes 和 bytearray 操作.
                                                             (line  396)
* isascii() (str 方法):                  字符串的方法<2>.    (line  159)
* isascii() (在 curses.ascii 模块中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  135)
* isasyncgen() (在 inspect 模块中):      类型和成员.         (line  369)
* isasyncgenfunction() (在 inspect 模块中): 类型和成员.      (line  352)
* isatty() (chunk.Chunk 方法):           chunk --- 读取 IFF 分块数据.
                                                             (line   75)
* isatty() (io.IOBase 方法):             I/O 基类.           (line   60)
* isatty() (在 os 模块中):               文件描述符操作.     (line  185)
* isawaitable() (在 inspect 模块中):     类型和成员.         (line  333)
* isblank() (在 curses.ascii 模块中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  139)
* isblk() (tarfile.TarInfo 方法):        TarInfo 对象.       (line  113)
* isbuiltin() (在 inspect 模块中):       类型和成员.         (line  389)
* ischr() (tarfile.TarInfo 方法):        TarInfo 对象.       (line  109)
* isclass() (在 inspect 模块中):         类型和成员.         (line  289)
* isclose() (在 cmath 模块中):           分类函数.           (line   20)
* isclose() (在 math 模块中):            数论与表示函数.     (line   89)
* iscntrl() (在 curses.ascii 模块中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  143)
* iscode() (在 inspect 模块中):          类型和成员.         (line  385)
* iscoroutine() (在 asyncio 模块中):     基于生成器的协程.   (line   33)
* iscoroutine() (在 inspect 模块中):     类型和成员.         (line  326)
* iscoroutinefunction() (在 asyncio 模块中): 基于生成器的协程.
                                                             (line   40)
* iscoroutinefunction() (在 inspect 模块中): 类型和成员.     (line  315)
* isctrl() (在 curses.ascii 模块中):     curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  181)
* isDaemon() (threading.Thread 方法):    线程对象.           (line  164)
* isdatadescriptor() (在 inspect 模块中): 类型和成员.        (line  421)
* isdecimal() (str 方法):                字符串的方法<2>.    (line  166)
* isdev() (tarfile.TarInfo 方法):        TarInfo 对象.       (line  121)
* isdigit() (bytearray 方法):            bytes 和 bytearray 操作.
                                                             (line  404)
* isdigit() (bytes 方法):                bytes 和 bytearray 操作.
                                                             (line  404)
* isdigit() (str 方法):                  字符串的方法<2>.    (line  173)
* isdigit() (在 curses.ascii 模块中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  147)
* isdir() (tarfile.TarInfo 方法):        TarInfo 对象.       (line   97)
* isdir() (在 os.path 模块中):           os path --- 常用路径操作.
                                                             (line  194)
* isdisjoint() (frozenset 方法):         集合类型 --- set frozenset.
                                                             (line   59)
* isdown() (在 turtle 模块中):           绘图状态.           (line   82)
* iselement() (在 xml.etree.ElementTree 模块中): 函数<6>.    (line  104)
* isenabled() (在 gc 模块中):            gc --- 垃圾回收器接口.
                                                             (line   26)
* isEnabledFor() (logging.Logger 方法):  记录器对象.         (line   66)
* isendwin() (在 curses 模块中):         函数<3>.            (line  200)
* ISEOF() (在 token 模块中):             token --- 与Python解析树一起使用的常量.
                                                             (line   30)
* isexpr() (parser.ST 方法):             ST 对象.            (line   21)
* isexpr() (在 parser 模块中):           Queries on ST Objects.
                                                             (line   12)
* isfifo() (tarfile.TarInfo 方法):       TarInfo 对象.       (line  117)
* isfile() (tarfile.TarInfo 方法):       TarInfo 对象.       (line   89)
* isfile() (在 os.path 模块中):          os path --- 常用路径操作.
                                                             (line  186)
* isfinite() (在 cmath 模块中):          分类函数.           (line    6)
* isfinite() (在 math 模块中):           数论与表示函数.     (line  117)
* isfirstline() (在 fileinput 模块中):   fileinput --- 迭代来自多个输入流的行.
                                                             (line   88)
* isframe() (在 inspect 模块中):         类型和成员.         (line  381)
* isfunction() (在 inspect 模块中):      类型和成员.         (line  298)
* isfuture() (在 asyncio 模块中):        Future 函数.        (line    6)
* isgenerator() (在 inspect 模块中):     类型和成员.         (line  311)
* isgeneratorfunction() (在 inspect 模块中): 类型和成员.     (line  303)
* isgetsetdescriptor() (在 inspect 模块中): 类型和成员.      (line  434)
* isgraph() (在 curses.ascii 模块中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  152)
* isidentifier() (str 方法):             字符串的方法<2>.    (line  181)
* isinf() (在 cmath 模块中):             分类函数.           (line   12)
* isinf() (在 math 模块中):              数论与表示函数.     (line  124)
* isinstance (2to3 fixer):               修复器.             (line  153)
* isinstance() (內置函数):               内置函数.           (line  703)
* iskeyword() (在 keyword 模块中):       keyword --- 检验Python关键字.
                                                             (line   12)
* isleap() (在 calendar 模块中):         calendar --- 日历相关函数.
                                                             (line  261)
* islice() (在 itertools 模块中):        Itertool函数.       (line  321)
* islink() (在 os.path 模块中):          os path --- 常用路径操作.
                                                             (line  202)
* islnk() (tarfile.TarInfo 方法):        TarInfo 对象.       (line  105)
* islower() (bytearray 方法):            bytes 和 bytearray 操作.
                                                             (line  418)
* islower() (bytes 方法):                bytes 和 bytearray 操作.
                                                             (line  418)
* islower() (str 方法):                  字符串的方法<2>.    (line  198)
* islower() (在 curses.ascii 模块中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  156)
* ismemberdescriptor() (在 inspect 模块中): 类型和成员.      (line  443)
* ismeta() (在 curses.ascii 模块中):     curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  185)
* ismethod() (在 inspect 模块中):        类型和成员.         (line  294)
* ismethoddescriptor() (在 inspect 模块中): 类型和成员.      (line  403)
* ismodule() (在 inspect 模块中):        类型和成员.         (line  285)
* ismount() (在 os.path 模块中):         os path --- 常用路径操作.
                                                             (line  209)
* isnan() (在 cmath 模块中):             分类函数.           (line   16)
* isnan() (在 math 模块中):              数论与表示函数.     (line  128)
* ISNONTERMINAL() (在 token 模块中):     token --- 与Python解析树一起使用的常量.
                                                             (line   26)
* isnumeric() (str 方法):                字符串的方法<2>.    (line  203)
* isocalendar() (datetime.date 方法):    date 对象.          (line  197)
* isocalendar() (datetime.datetime 方法): datetime 对象.     (line  532)
* isoformat() (datetime.date 方法):      date 对象.          (line  217)
* isoformat() (datetime.datetime 方法):  datetime 对象.      (line  537)
* isoformat() (datetime.time 方法):      time 对象.          (line  135)
* IsolatedAsyncioTestCase (unittest 中的类): 测试用例.       (line  802)
* isolation_level (sqlite3.Connection 属性): 连接对象（Connection）.
                                                             (line   10)
* isoweekday() (datetime.date 方法):     date 对象.          (line  191)
* isoweekday() (datetime.datetime 方法): datetime 对象.      (line  526)
* isprint() (在 curses.ascii 模块中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  160)
* isprintable() (str 方法):              字符串的方法<2>.    (line  211)
* ispunct() (在 curses.ascii 模块中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  164)
* isqrt() (在 math 模块中):              数论与表示函数.     (line  132)
* isreadable() (pprint.PrettyPrinter 方法): PrettyPrinter 对象.
                                                             (line   20)
* isreadable() (在 pprint 模块中):       pprint --- 数据美化输出.
                                                             (line  113)
* isrecursive() (pprint.PrettyPrinter 方法): PrettyPrinter 对象.
                                                             (line   27)
* isrecursive() (在 pprint 模块中):      pprint --- 数据美化输出.
                                                             (line  121)
* isreg() (tarfile.TarInfo 方法):        TarInfo 对象.       (line   93)
* isReservedKey() (http.cookies.Morsel 方法): Morsel 对象.   (line   68)
* isroutine() (在 inspect 模块中):       类型和成员.         (line  394)
* isSameNode() (xml.dom.Node 方法):      节点对象.           (line   89)
* isspace() (bytearray 方法):            bytes 和 bytearray 操作.
                                                             (line  435)
* isspace() (bytes 方法):                bytes 和 bytearray 操作.
                                                             (line  435)
* isspace() (str 方法):                  字符串的方法<2>.    (line  220)
* isspace() (在 curses.ascii 模块中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  168)
* isstdin() (在 fileinput 模块中):       fileinput --- 迭代来自多个输入流的行.
                                                             (line   92)
* issubclass() (內置函数):               内置函数.           (line  712)
* issubset() (frozenset 方法):           集合类型 --- set frozenset.
                                                             (line   64)
* issuite() (parser.ST 方法):            ST 对象.            (line   25)
* issuite() (在 parser 模块中):          Queries on ST Objects.
                                                             (line   22)
* issuperset() (frozenset 方法):         集合类型 --- set frozenset.
                                                             (line   75)
* issym() (tarfile.TarInfo 方法):        TarInfo 对象.       (line  101)
* ISTERMINAL() (在 token 模块中):        token --- 与Python解析树一起使用的常量.
                                                             (line   22)
* istitle() (bytearray 方法):            bytes 和 bytearray 操作.
                                                             (line  442)
* istitle() (bytes 方法):                bytes 和 bytearray 操作.
                                                             (line  442)
* istitle() (str 方法):                  字符串的方法<2>.    (line  229)
* istraceback() (在 inspect 模块中):     类型和成员.         (line  377)
* isub() (在 operator 模块中):           原地运算符.         (line   90)
* isupper() (bytearray 方法):            bytes 和 bytearray 操作.
                                                             (line  456)
* isupper() (bytes 方法):                bytes 和 bytearray 操作.
                                                             (line  456)
* isupper() (str 方法):                  字符串的方法<2>.    (line  235)
* isupper() (在 curses.ascii 模块中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  173)
* isvisible() (在 turtle 模块中):        可见性.             (line   21)
* isxdigit() (在 curses.ascii 模块中):   curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  177)
* is_() (在 operator 模块中):            operator --- 标准运算符替代函数.
                                                             (line   52)
* is_absolute() (pathlib.PurePath 方法): 方法和特征属性.     (line  161)
* is_active() (asyncio.AbstractChildWatcher 方法): 进程监视器.
                                                             (line   59)
* is_alive() (multiprocessing.Process 方法): Process 和异常. (line   66)
* is_alive() (threading.Thread 方法):    线程对象.           (line  146)
* is_android() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line   40)
* is_annotated() (symtable.Symbol 方法): Examining Symbol Tables.
                                                             (line  142)
* is_assigned() (symtable.Symbol 方法):  Examining Symbol Tables.
                                                             (line  153)
* is_attachment() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  370)
* is_authenticated() (urllib.request.HTTPPasswordMgrWithPriorAuth 方法): HTTPPasswordMgrWithPriorAuth 对象.
                                                             (line   27)
* is_blocked() (http.cookiejar.DefaultCookiePolicy 方法): DefaultCookiePolicy 对象.
                                                             (line   60)
* is_block_device() (pathlib.Path 方法): 方法<2>.            (line  157)
* is_canonical() (decimal.Context 方法): 上下文对象.         (line  256)
* is_canonical() (decimal.Decimal 方法): Decimal 对象.       (line  237)
* IS_CHARACTER_JUNK() (在 difflib 模块中): difflib --- 计算差异的辅助工具.
                                                             (line  316)
* is_char_device() (pathlib.Path 方法):  方法<2>.            (line  165)
* is_check_supported() (在 lzma 模块中): 杂项<2>.            (line    6)
* is_closed() (asyncio.loop 方法):       运行和停止循环.     (line   36)
* is_closing() (asyncio.BaseTransport 方法): 基础传输.       (line   15)
* is_closing() (asyncio.StreamWriter 方法): StreamWriter.    (line   73)
* is_dataclass() (在 dataclasses 模块中): 模块级装饰器、类和函数.
                                                             (line  308)
* is_declared_global() (symtable.Symbol 方法): Examining Symbol Tables.
                                                             (line  133)
* is_dir() (os.DirEntry 方法):           文件和目录.         (line  773)
* is_dir() (pathlib.Path 方法):          方法<2>.            (line  109)
* is_dir() (zipfile.Path 方法):          Path 对象.          (line   36)
* is_dir() (zipfile.ZipInfo 方法):       ZipInfo 对象.       (line   37)
* is_enabled() (在 faulthandler 模块中): Fault handler state.
                                                             (line   27)
* is_expired() (http.cookiejar.Cookie 方法): Cookie 对象<2>. (line  109)
* is_fifo() (pathlib.Path 方法):         方法<2>.            (line  149)
* is_file() (os.DirEntry 方法):          文件和目录.         (line  797)
* is_file() (pathlib.Path 方法):         方法<2>.            (line  117)
* is_file() (zipfile.Path 方法):         Path 对象.          (line   40)
* is_finalizing() (在 sys 模块中):       sys --- 系统相关的参数和函数.
                                                             (line  835)
* is_finite() (decimal.Context 方法):    上下文对象.         (line  260)
* is_finite() (decimal.Decimal 方法):    Decimal 对象.       (line  243)
* is_free() (symtable.Symbol 方法):      Examining Symbol Tables.
                                                             (line  148)
* is_global (ipaddress.IPv4Address 属性): 地址对象.          (line   98)
* is_global (ipaddress.IPv6Address 属性): 地址对象.          (line  177)
* is_global() (symtable.Symbol 方法):    Examining Symbol Tables.
                                                             (line  125)
* is_hop_by_hop() (在 wsgiref.util 模块中): wsgiref util -- WSGI environment utilities.
                                                             (line  109)
* is_imported() (symtable.Symbol 方法):  Examining Symbol Tables.
                                                             (line  116)
* is_infinite() (decimal.Context 方法):  上下文对象.         (line  264)
* is_infinite() (decimal.Decimal 方法):  Decimal 对象.       (line  248)
* is_integer() (float 方法):             浮点类型的附加方法. (line   14)
* is_jython() (在 test.support 模块中):  test support --- Utilities for the Python test suite.
                                                             (line   36)
* is_linetouched() (curses.window 方法): Window 对象.        (line  314)
* IS_LINE_JUNK() (在 difflib 模块中):    difflib --- 计算差异的辅助工具.
                                                             (line  310)
* is_link_local (ipaddress.IPv4Address 属性): 地址对象.      (line  121)
* is_link_local (ipaddress.IPv4Network 属性): Network objects.
                                                             (line   80)
* is_link_local (ipaddress.IPv6Address 属性): 地址对象.      (line  185)
* is_link_local (ipaddress.IPv6Network 属性): Network objects.
                                                             (line  307)
* is_local() (symtable.Symbol 方法):     Examining Symbol Tables.
                                                             (line  138)
* is_loopback (ipaddress.IPv4Address 属性): 地址对象.        (line  116)
* is_loopback (ipaddress.IPv4Network 属性): Network objects. (line   78)
* is_loopback (ipaddress.IPv6Address 属性): 地址对象.        (line  183)
* is_loopback (ipaddress.IPv6Network 属性): Network objects. (line  305)
* is_mount() (pathlib.Path 方法):        方法<2>.            (line  125)
* is_multicast (ipaddress.IPv4Address 属性): 地址对象.       (line   87)
* is_multicast (ipaddress.IPv4Network 属性): Network objects.
                                                             (line   70)
* is_multicast (ipaddress.IPv6Address 属性): 地址对象.       (line  173)
* is_multicast (ipaddress.IPv6Network 属性): Network objects.
                                                             (line  297)
* is_multipart() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  105)
* is_multipart() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  119)
* is_namespace() (symtable.Symbol 方法): Examining Symbol Tables.
                                                             (line  157)
* is_nan() (decimal.Context 方法):       上下文对象.         (line  268)
* is_nan() (decimal.Decimal 方法):       Decimal 对象.       (line  253)
* is_nested() (symtable.SymbolTable 方法): Examining Symbol Tables.
                                                             (line   35)
* is_nonlocal() (symtable.Symbol 方法):  Examining Symbol Tables.
                                                             (line  129)
* is_normal() (decimal.Context 方法):    上下文对象.         (line  272)
* is_normal() (decimal.Decimal 方法):    Decimal 对象.       (line  258)
* is_normalized() (在 unicodedata 模块中): unicodedata --- Unicode 数据库.
                                                             (line   95)
* is_not() (在 operator 模块中):         operator --- 标准运算符替代函数.
                                                             (line   56)
* is_not_allowed() (http.cookiejar.DefaultCookiePolicy 方法): DefaultCookiePolicy 对象.
                                                             (line   74)
* is_optimized() (symtable.SymbolTable 方法): Examining Symbol Tables.
                                                             (line   31)
* is_package() (importlib.abc.InspectLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  357)
* is_package() (importlib.abc.SourceLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  523)
* is_package() (importlib.machinery.ExtensionFileLoader 方法): importlib machinery -- Importers and path hooks.
                                                             (line  326)
* is_package() (importlib.machinery.SourceFileLoader 方法): importlib machinery -- Importers and path hooks.
                                                             (line  225)
* is_package() (importlib.machinery.SourcelessFileLoader 方法): importlib machinery -- Importers and path hooks.
                                                             (line  269)
* is_package() (zipimport.zipimporter 方法): zipimporter 对象.
                                                             (line   51)
* is_parameter() (symtable.Symbol 方法): Examining Symbol Tables.
                                                             (line  121)
* is_private (ipaddress.IPv4Address 属性): 地址对象.         (line   92)
* is_private (ipaddress.IPv4Network 属性): Network objects.  (line   72)
* is_private (ipaddress.IPv6Address 属性): 地址对象.         (line  175)
* is_private (ipaddress.IPv6Network 属性): Network objects.  (line  299)
* is_python_build() (在 sysconfig 模块中): 其他功能<3>.      (line   49)
* is_qnan() (decimal.Context 方法):      上下文对象.         (line  276)
* is_qnan() (decimal.Decimal 方法):      Decimal 对象.       (line  263)
* is_reading() (asyncio.ReadTransport 方法): 只读传输.       (line    6)
* is_referenced() (symtable.Symbol 方法): Examining Symbol Tables.
                                                             (line  112)
* is_reserved (ipaddress.IPv4Address 属性): 地址对象.        (line  111)
* is_reserved (ipaddress.IPv4Network 属性): Network objects. (line   76)
* is_reserved (ipaddress.IPv6Address 属性): 地址对象.        (line  181)
* is_reserved (ipaddress.IPv6Network 属性): Network objects. (line  303)
* is_reserved() (pathlib.PurePath 方法): 方法和特征属性.     (line  180)
* is_resource() (importlib.abc.ResourceReader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  294)
* is_resource() (在 importlib.resources 模块中): importlib resources -- 资源.
                                                             (line  116)
* is_resource_enabled() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  197)
* is_running() (asyncio.loop 方法):      运行和停止循环.     (line   32)
* is_safe (uuid.UUID 属性):              uuid --- UUID objects according to RFC 4122.
                                                             (line  150)
* is_serving() (asyncio.Server 方法):    Server 对象.        (line   82)
* is_set() (asyncio.Event 方法):         Event.              (line   63)
* is_set() (threading.Event 方法):       事件对象.           (line   22)
* is_signed() (decimal.Context 方法):    上下文对象.         (line  280)
* is_signed() (decimal.Decimal 方法):    Decimal 对象.       (line  268)
* is_site_local (ipaddress.IPv6Address 属性): 地址对象.      (line  189)
* is_site_local (ipaddress.IPv6Network 属性): Network objects.
                                                             (line  357)
* is_snan() (decimal.Context 方法):      上下文对象.         (line  284)
* is_snan() (decimal.Decimal 方法):      Decimal 对象.       (line  273)
* is_socket() (pathlib.Path 方法):       方法<2>.            (line  141)
* is_subnormal() (decimal.Context 方法): 上下文对象.         (line  288)
* is_subnormal() (decimal.Decimal 方法): Decimal 对象.       (line  278)
* is_symlink() (os.DirEntry 方法):       文件和目录.         (line  810)
* is_symlink() (pathlib.Path 方法):      方法<2>.            (line  135)
* is_tarfile() (在 tarfile 模块中):      tarfile --- 读写tar归档文件.
                                                             (line  154)
* is_term_resized() (在 curses 模块中):  函数<3>.            (line  195)
* is_tracing() (在 tracemalloc 模块中):  函数<9>.            (line   43)
* is_tracked() (在 gc 模块中):           gc --- 垃圾回收器接口.
                                                             (line  126)
* is_unspecified (ipaddress.IPv4Address 属性): 地址对象.     (line  106)
* is_unspecified (ipaddress.IPv4Network 属性): Network objects.
                                                             (line   74)
* is_unspecified (ipaddress.IPv6Address 属性): 地址对象.     (line  179)
* is_unspecified (ipaddress.IPv6Network 属性): Network objects.
                                                             (line  301)
* is_wintouched() (curses.window 方法):  Window 对象.        (line  320)
* is_zero() (decimal.Context 方法):      上下文对象.         (line  292)
* is_zero() (decimal.Decimal 方法):      Decimal 对象.       (line  283)
* is_zipfile() (在 zipfile 模块中):      zipfile --- 使用ZIP存档.
                                                             (line   62)
* item selection:                        标准类型层级结构.   (line   93)
* item() (tkinter.ttk.Treeview 方法):    ttk Treeview.       (line  211)
* item() (xml.dom.NamedNodeMap 方法):    NamedNodeMap 对象.  (line   12)
* item() (xml.dom.NodeList 方法):        节点列表对象.       (line   13)
* itemgetter() (在 operator 模块中):     operator --- 标准运算符替代函数.
                                                             (line  237)
* items() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line  205)
* items() (contextvars.Context 方法):    手动上下文管理.     (line   98)
* items() (dict 方法):                   映射类型 --- dict.  (line  147)
* items() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  196)
* items() (email.message.Message 方法):  email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  290)
* items() (mailbox.Mailbox 方法):        Mailbox 对象.       (line  103)
* items() (types.MappingProxyType 方法): 标准解释器类型.     (line  225)
* items() (xml.etree.ElementTree.Element 方法): 元素对象.    (line   59)
* itemsize (array.array 属性):           array --- 高效的数值数组.
                                                             (line  100)
* itemsize (memoryview 属性):            内存视图.           (line  397)
* ItemsView (collections.abc 中的类):    容器抽象基类.       (line  180)
* ItemsView (typing 中的类):             类 函数和修饰器.    (line  272)
* iter() (xml.etree.ElementTree.Element 方法): 元素对象.     (line  125)
* iter() (xml.etree.ElementTree.ElementTree 方法): ElementTree 对象.
                                                             (line   40)
* iter() (內置函数):                     内置函数.           (line  719)
* Iterable (collections.abc 中的类):     容器抽象基类.       (line  120)
* Iterable (typing 中的类):              类 函数和修饰器.    (line  135)
* iterable – 可迭代对象:                 术语对照表.         (line  536)
* iterable; unpacking:                   表达式列表.         (line   14)
* Iterator (collections.abc 中的类):     容器抽象基类.       (line  136)
* Iterator (typing 中的类):              类 函数和修饰器.    (line  139)
* iterator – 迭代器:                     术语对照表.         (line  553)
* iterator protocol:                     迭代器类型.         (line    6)
* iterdecode() (在 codecs 模块中):       codecs --- 编解码器注册和相关基类.
                                                             (line  187)
* iterdir() (pathlib.Path 方法):         方法<2>.            (line  173)
* iterdir() (zipfile.Path 方法):         Path 对象.          (line   32)
* iterdump() (sqlite3.Connection 方法):  连接对象（Connection）.
                                                             (line  348)
* iterencode() (json.JSONEncoder 方法):  编码器和解码器.     (line  199)
* iterencode() (在 codecs 模块中):       codecs --- 编解码器注册和相关基类.
                                                             (line  177)
* iterfind() (xml.etree.ElementTree.Element 方法): 元素对象. (line  134)
* iterfind() (xml.etree.ElementTree.ElementTree 方法): ElementTree 对象.
                                                             (line   45)
* iteritems() (mailbox.Mailbox 方法):    Mailbox 对象.       (line  103)
* iterkeys() (mailbox.Mailbox 方法):     Mailbox 对象.       (line   83)
* itermonthdates() (calendar.Calendar 方法): calendar --- 日历相关函数.
                                                             (line   36)
* itermonthdays() (calendar.Calendar 方法): calendar --- 日历相关函数.
                                                             (line   42)
* itermonthdays2() (calendar.Calendar 方法): calendar --- 日历相关函数.
                                                             (line   49)
* itermonthdays3() (calendar.Calendar 方法): calendar --- 日历相关函数.
                                                             (line   56)
* itermonthdays4() (calendar.Calendar 方法): calendar --- 日历相关函数.
                                                             (line   64)
* iternextfunc (C 类型):                 Slot Type typedefs. (line   99)
* iterparse() (在 xml.etree.ElementTree 模块中): 函数<6>.    (line  109)
* itertext() (xml.etree.ElementTree.Element 方法): 元素对象. (line  142)
* itertools (2to3 fixer):                修复器.             (line  166)
* itertools (模块):                      itertools --- 为高效循环而创建迭代器的函数.
                                                             (line    6)
* itertools_imports (2to3 fixer):        修复器.             (line  160)
* itervalues() (mailbox.Mailbox 方法):   Mailbox 对象.       (line   89)
* iterweekdays() (calendar.Calendar 方法): calendar --- 日历相关函数.
                                                             (line   31)
* iter_attachments() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  473)
* iter_child_nodes() (在 ast 模块中):    ast 中的辅助函数.   (line  103)
* iter_fields() (在 ast 模块中):         ast 中的辅助函数.   (line   98)
* iter_importers() (在 pkgutil 模块中):  pkgutil --- 包扩展工具.
                                                             (line  122)
* iter_modules() (在 pkgutil 模块中):    pkgutil --- 包扩展工具.
                                                             (line  140)
* iter_parts() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  486)
* iter_unpack() (struct.Struct 方法):    类<2>.              (line   41)
* iter_unpack() (在 struct 模块中):      函数和异常.         (line   37)
* ItimerError:                           模块内容<5>.        (line  199)
* ITIMER_PROF() (在 signal 模块中):      模块内容<5>.        (line  170)
* ITIMER_REAL() (在 signal 模块中):      模块内容<5>.        (line  162)
* ITIMER_VIRTUAL() (在 signal 模块中):   模块内容<5>.        (line  166)
* itruediv() (在 operator 模块中):       原地运算符.         (line   95)
* ixor() (在 operator 模块中):           原地运算符.         (line  100)
* j; in numeric literal:                 浮点数字面值.       (line   24)
* Jansen, Jack:                          uu --- 对 uuencode 文件进行编码与解码.
                                                             (line   17)
* Java; language:                        标准类型层级结构.   (line   79)
* java_ver() (在 platform 模块中):       Java平台.           (line    6)
* join() (asyncio.Queue 方法):           Queue.              (line   47)
* join() (bytearray 方法):               bytes 和 bytearray 操作.
                                                             (line   98)
* join() (bytes 方法):                   bytes 和 bytearray 操作.
                                                             (line   98)
* join() (multiprocessing.JoinableQueue 方法): 管道和队列.   (line  207)
* join() (multiprocessing.pool.Pool 方法): 进程池.           (line  148)
* join() (multiprocessing.Process 方法): Process 和异常.     (line   43)
* join() (queue.Queue 方法):             Queue对象.          (line   73)
* join() (str 方法):                     字符串的方法<2>.    (line  240)
* join() (threading.Thread 方法):        线程对象.           (line   92)
* join() (在 os.path 模块中):            os path --- 常用路径操作.
                                                             (line  223)
* join() (在 shlex 模块中):              shlex --- Simple lexical analysis.
                                                             (line   30)
* JoinableQueue (multiprocessing 中的类): 管道和队列.        (line  189)
* joinpath() (pathlib.PurePath 方法):    方法和特征属性.     (line  194)
* join_thread() (multiprocessing.Queue 方法): 管道和队列.    (line  145)
* join_thread() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  786)
* json (模块):                           json --- JSON 编码和解码器.
                                                             (line    6)
* json.tool (模块):                      命令行界面<4>.      (line    6)
* json.tool command line option; -h:     命令行选项<4>.      (line   41)
* json.tool command line option; –help:  命令行选项<4>.      (line   41)
* json.tool command line option; –json-lines: 命令行选项<4>. (line   35)
* json.tool command line option; –sort-keys: 命令行选项<4>.  (line   29)
* json.tool command line option; infile: 命令行选项<4>.      (line    6)
* json.tool command line option; outfile: 命令行选项<4>.     (line   24)
* JSONDecodeError:                       异常<13>.           (line    6)
* JSONDecoder (json 中的类):             编码器和解码器.     (line    6)
* JSONEncoder (json 中的类):             编码器和解码器.     (line   94)
* js_output() (http.cookies.BaseCookie 方法): Cookie 对象.   (line   32)
* js_output() (http.cookies.Morsel 方法): Morsel 对象.       (line   79)
* jump (pdb command):                    调试器命令.         (line  161)
* JUMP_ABSOLUTE (opcode):                Python字节码说明.   (line  621)
* JUMP_FORWARD (opcode):                 Python字节码说明.   (line  591)
* JUMP_IF_FALSE_OR_POP (opcode):         Python字节码说明.   (line  614)
* JUMP_IF_TRUE_OR_POP (opcode):          Python字节码说明.   (line  607)
* kbhit() (在 msvcrt 模块中):            控制台 I/O.         (line    6)
* KDEDIR:                                webbrowser --- 方便的Web浏览器控制器.
                                                             (line  164)
* kevent() (在 select 模块中):           select --- 等待 I/O 完成.
                                                             (line   87)
* key:                                   字典显示.           (line    6)
* key (http.cookies.Morsel 属性):        Morsel 对象.        (line   60)
* key function – 键函数:                 术语对照表.         (line  569)
* key/datum pair:                        字典显示.           (line    6)
* KeyboardInterrupt:                     具体异常.           (line   62)
* KeyboardInterrupt (built-in exception): 信号处理<2>.       (line    8)
* KeyboardInterrupt (built-in exception) <1>: 信号处理<2>.   (line   20)
* KeyError:                              具体异常.           (line   58)
* keylog_filename (ssl.SSLContext 属性): SSL 上下文.         (line  459)
* keyname() (在 curses 模块中):          函数<3>.            (line  205)
* keypad() (curses.window 方法):         Window 对象.        (line  325)
* keyrefs() (weakref.WeakKeyDictionary 方法): weakref --- 弱引用.
                                                             (line  130)
* keys() (contextvars.Context 方法):     手动上下文管理.     (line   90)
* keys() (dict 方法):                    映射类型 --- dict.  (line  152)
* keys() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  188)
* keys() (email.message.Message 方法):   email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  282)
* keys() (mailbox.Mailbox 方法):         Mailbox 对象.       (line   83)
* keys() (sqlite3.Row 方法):             行对象.             (line   18)
* keys() (types.MappingProxyType 方法):  标准解释器类型.     (line  229)
* keys() (xml.etree.ElementTree.Element 方法): 元素对象.     (line   64)
* KeysView (collections.abc 中的类):     容器抽象基类.       (line  180)
* KeysView (typing 中的类):              类 函数和修饰器.    (line  268)
* keyword:                               关键字.             (line    6)
* keyword (模块):                        keyword --- 检验Python关键字.
                                                             (line    6)
* keyword argument – 关键字参数:         术语对照表.         (line  588)
* keywords (functools.partial 属性):     partial 对象.       (line   19)
* KEY_ALL_ACCESS() (在 winreg 模块中):   Access Rights.      (line    8)
* KEY_CREATE_LINK() (在 winreg 模块中):  Access Rights.      (line   51)
* KEY_CREATE_SUB_KEY() (在 winreg 模块中): Access Rights.    (line   38)
* KEY_ENUMERATE_SUB_KEYS() (在 winreg 模块中): Access Rights.
                                                             (line   42)
* KEY_EXECUTE() (在 winreg 模块中):      Access Rights.      (line   26)
* KEY_NOTIFY() (在 winreg 模块中):       Access Rights.      (line   46)
* KEY_QUERY_VALUE() (在 winreg 模块中):  Access Rights.      (line   30)
* KEY_READ() (在 winreg 模块中):         Access Rights.      (line   20)
* KEY_SET_VALUE() (在 winreg 模块中):    Access Rights.      (line   34)
* KEY_WOW64_32KEY() (在 winreg 模块中):  64-bit Specific.    (line   13)
* KEY_WOW64_64KEY() (在 winreg 模块中):  64-bit Specific.    (line    8)
* KEY_WRITE() (在 winreg 模块中):        Access Rights.      (line   15)
* kill() (asyncio.asyncio.subprocess.Process 方法): 与子进程交互.
                                                             (line   91)
* kill() (asyncio.SubprocessTransport 方法): 子进程传输.     (line   31)
* kill() (multiprocessing.Process 方法): Process 和异常.     (line  139)
* kill() (subprocess.Popen 方法):        Popen 对象.         (line   77)
* kill() (在 os 模块中):                 进程管理.           (line  247)
* killchar() (在 curses 模块中):         函数<3>.            (line  213)
* killpg() (在 os 模块中):               进程管理.           (line  264)
* kill_python() (在 test.support.script_helper 模块中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   66)
* kind (inspect.Parameter 属性):         Introspecting callables with the Signature object.
                                                             (line  179)
* knownfiles() (在 mimetypes 模块中):    mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line  103)
* kqueue() (在 select 模块中):           select --- 等待 I/O 完成.
                                                             (line   78)
* KqueueSelector (selectors 中的类):     类<3>.              (line  173)
* kwargs (inspect.BoundArguments 属性):  Introspecting callables with the Signature object.
                                                             (line  301)
* kwlist() (在 keyword 模块中):          keyword --- 检验Python关键字.
                                                             (line   16)
* L() (在 re 模块中):                    模块内容.           (line   67)
* LabelEntry (tkinter.tix 中的类):       Basic Widgets.      (line   30)
* LabelFrame (tkinter.tix 中的类):       Basic Widgets.      (line   36)
* lambda:                                术语对照表.         (line  592)
* lambda; expression:                    lambda 表达式.      (line    6)
* lambda; expression <1>:                函数定义.           (line   87)
* lambda; form:                          lambda 表达式.      (line    6)
* LambdaType() (在 types 模块中):        标准解释器类型.     (line   17)
* LANG:                                  GNU gettext API.    (line   18)
* LANG <1>:                              基于类的 API.       (line   22)
* LANG <2>:                              locale --- 国际化服务.
                                                             (line   49)
* LANG <3>:                              locale --- 国际化服务.
                                                             (line  292)
* LANG <4>:                              locale --- 国际化服务.
                                                             (line  296)
* LANGUAGE:                              GNU gettext API.    (line   17)
* LANGUAGE <1>:                          基于类的 API.       (line   21)
* large files:                           大文件支持.         (line    6)
* LARGEST() (在 test.support 模块中):    test support --- Utilities for the Python test suite.
                                                             (line  150)
* LargeZipFile:                          zipfile --- 使用ZIP存档.
                                                             (line   32)
* last() (nntplib.NNTP 方法):            方法<3>.            (line  236)
* lastChild (xml.dom.Node 属性):         节点对象.           (line   49)
* lastcmd (cmd.Cmd 属性):                Cmd 对象.           (line  103)
* lastgroup (re.Match 属性):             匹配对象.           (line  158)
* lastindex (re.Match 属性):             匹配对象.           (line  152)
* lastResort() (在 logging 模块中):      模块级属性.         (line    6)
* lastrowid (sqlite3.Cursor 属性):       Cursor 对象.        (line  180)
* last_accepted (multiprocessing.connection.Listener 属性): 监听器及客户端.
                                                             (line   91)
* last_traceback (in module sys):        标准类型层级结构.   (line  571)
* last_traceback() (在 sys 模块中):      sys --- 系统相关的参数和函数.
                                                             (line  842)
* last_type() (在 sys 模块中):           sys --- 系统相关的参数和函数.
                                                             (line  842)
* last_value() (在 sys 模块中):          sys --- 系统相关的参数和函数.
                                                             (line  842)
* layout() (tkinter.ttk.Style 方法):     Ttk Styling.        (line   96)
* lazycache() (在 linecache 模块中):     linecache --- 随机读写文本行.
                                                             (line   42)
* LazyLoader (importlib.util 中的类):    importlib util -- Utility code for importers.
                                                             (line  225)
* LBRACE() (在 token 模块中):            token --- 与Python解析树一起使用的常量.
                                                             (line  122)
* LBYL:                                  术语对照表.         (line  598)
* lchflags() (在 os 模块中):             文件和目录.         (line  264)
* lchmod() (pathlib.Path 方法):          方法<2>.            (line  192)
* lchmod() (在 os 模块中):               文件和目录.         (line  277)
* lchown() (在 os 模块中):               文件和目录.         (line  291)
* LC_ALL:                                GNU gettext API.    (line   17)
* LC_ALL <1>:                            基于类的 API.       (line   21)
* LC_ALL() (在 locale 模块中):           locale --- 国际化服务.
                                                             (line  475)
* LC_COLLATE() (在 locale 模块中):       locale --- 国际化服务.
                                                             (line  444)
* LC_CTYPE() (在 locale 模块中):         locale --- 国际化服务.
                                                             (line  438)
* LC_MESSAGES:                           GNU gettext API.    (line   18)
* LC_MESSAGES <1>:                       基于类的 API.       (line   21)
* LC_MESSAGES() (在 locale 模块中):      locale --- 国际化服务.
                                                             (line  460)
* LC_MONETARY() (在 locale 模块中):      locale --- 国际化服务.
                                                             (line  455)
* LC_NUMERIC() (在 locale 模块中):       locale --- 国际化服务.
                                                             (line  467)
* LC_TIME() (在 locale 模块中):          locale --- 国际化服务.
                                                             (line  450)
* LDCXXSHARED:                           构建和 C API 的改变<8>.
                                                             (line  153)
* ldexp() (在 math 模块中):              数论与表示函数.     (line  143)
* LDFLAGS:                               新增，改进和弃用的模块<4>.
                                                             (line   59)
* ldgettext() (在 gettext 模块中):       GNU gettext API.    (line   78)
* ldngettext() (在 gettext 模块中):      GNU gettext API.    (line   82)
* le() (在 operator 模块中):             operator --- 标准运算符替代函数.
                                                             (line   19)
* leading whitespace:                    缩进.               (line    6)
* leapdays() (在 calendar 模块中):       calendar --- 日历相关函数.
                                                             (line  266)
* leaveok() (curses.window 方法):        Window 对象.        (line  331)
* left (filecmp.dircmp 属性):            dircmp 类.          (line   36)
* left() (在 turtle 模块中):             海龟动作.           (line   55)
* LEFTSHIFT() (在 token 模块中):         token --- 与Python解析树一起使用的常量.
                                                             (line  154)
* LEFTSHIFTEQUAL() (在 token 模块中):    token --- 与Python解析树一起使用的常量.
                                                             (line  198)
* left_list (filecmp.dircmp 属性):       dircmp 类.          (line   44)
* left_only (filecmp.dircmp 属性):       dircmp 类.          (line   56)
* len() (內置函数):                      内置函数.           (line  741)
* lenfunc (C 类型):                      Slot Type typedefs. (line  103)
* length (xml.dom.NamedNodeMap 属性):    NamedNodeMap 对象.  (line    8)
* length (xml.dom.NodeList 属性):        节点列表对象.       (line   18)
* length_hint() (在 operator 模块中):    operator --- 标准运算符替代函数.
                                                             (line  191)
* LESS() (在 token 模块中):              token --- 与Python解析树一起使用的常量.
                                                             (line  102)
* LESSEQUAL() (在 token 模块中):         token --- 与Python解析树一起使用的常量.
                                                             (line  138)
* lexical analysis:                      词法分析.           (line    6)
* lexical definitions:                   标注.               (line   23)
* lexists() (在 os.path 模块中):         os path --- 常用路径操作.
                                                             (line  111)
* lgamma() (在 math 模块中):             特殊函数.           (line   32)
* lgettext() (gettext.GNUTranslations 方法): GNUTranslations 类.
                                                             (line   78)
* lgettext() (gettext.NullTranslations 方法): NullTranslations 类.
                                                             (line   53)
* lgettext() (在 gettext 模块中):        GNU gettext API.    (line   76)
* lib2to3 (模块):                        lib2to3 —— 2to3 支持库.
                                                             (line    6)
* libc_ver() (在 platform 模块中):       Unix 平台.          (line    6)
* library (ssl.SSLError 属性):           异常<12>.           (line   16)
* library() (在 dbm.ndbm 模块中):        dbm ndbm --- 基于 ndbm 的接口.
                                                             (line   22)
* LibraryLoader (ctypes 中的类):         加载动态链接库.     (line  130)
* library_dir_option() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  218)
* library_filename() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  456)
* library_option() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  223)
* license (內置变量):                    由 site 模块添加的常量.
                                                             (line   22)
* LifoQueue (asyncio 中的类):            后进先出队列.       (line    6)
* LifoQueue (queue 中的类):              queue --- 一个同步的队列类.
                                                             (line   35)
* light-weight processes:                _thread --- 底层多线程 API.
                                                             (line    6)
* LimitOverrunError:                     异常<9>.            (line   54)
* limit_denominator() (fractions.Fraction 方法): fractions --- 分数.
                                                             (line  111)
* lin2adpcm() (在 audioop 模块中):       audioop --- 处理原始音频数据.
                                                             (line   98)
* lin2alaw() (在 audioop 模块中):        audioop --- 处理原始音频数据.
                                                             (line  110)
* lin2lin() (在 audioop 模块中):         audioop --- 处理原始音频数据.
                                                             (line  116)
* lin2ulaw() (在 audioop 模块中):        audioop --- 处理原始音频数据.
                                                             (line  130)
* line continuation:                     显式的行拼接.       (line    6)
* line joining:                          逻辑行.             (line    6)
* line joining <1>:                      显式的行拼接.       (line    6)
* line structure:                        行结构.             (line    6)
* line() (msilib.Dialog 方法):           GUI classes.        (line   64)
* line-buffered I/O:                     内置函数.           (line 1017)
* linecache (模块):                      linecache --- 随机读写文本行.
                                                             (line    6)
* lineno (ast.AST 属性):                 节点类.             (line   32)
* lineno (doctest.DocTest 属性):         DocTest 对象.       (line   42)
* lineno (doctest.Example 属性):         Example Objects.    (line   41)
* lineno (json.JSONDecodeError 属性):    异常<13>.           (line   22)
* lineno (pyclbr.Class 属性):            类对象<2>.          (line   21)
* lineno (pyclbr.Function 属性):         函数对象.           (line   20)
* lineno (re.error 属性):                模块内容.           (line  305)
* lineno (shlex.shlex 属性):             shlex Objects.      (line  168)
* lineno (SyntaxError 属性):             具体异常.           (line  220)
* lineno (traceback.TracebackException 属性): TracebackException Objects.
                                                             (line   46)
* lineno (tracemalloc.Filter 属性):      过滤器.             (line   48)
* lineno (tracemalloc.Frame 属性):       Frame.              (line   17)
* lineno (xml.parsers.expat.ExpatError 属性): ExpatError 异常.
                                                             (line   24)
* lineno() (在 fileinput 模块中):        fileinput --- 迭代来自多个输入流的行.
                                                             (line   78)
* LINES:                                 curses<2>.          (line    6)
* LINES <1>:                             函数<3>.            (line  104)
* LINES <2>:                             函数<3>.            (line  436)
* LINES <3>:                             函数<3>.            (line  456)
* LINES <4>:                             函数<3>.            (line  457)
* lines (os.terminal_size 属性):         查询终端的尺寸.     (line   31)
* linesep (email.policy.Policy 属性):    email policy 策略对象.
                                                             (line  121)
* linesep() (在 os 模块中):              其他系统信息.       (line  106)
* lineterminator (csv.Dialect 属性):     变种与格式参数.     (line   36)
* LineTooLong:                           http client --- HTTP 协议客户端.
                                                             (line  164)
* line_buffering (io.TextIOWrapper 属性): 文本 I/O<2>.       (line  139)
* line_num (csv.csvreader 属性):         Reader 对象.        (line   22)
* link() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  346)
* link() (在 os 模块中):                 文件和目录.         (line  304)
* linkname (tarfile.TarInfo 属性):       TarInfo 对象.       (line   62)
* link_executable() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  398)
* link_shared_lib() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  408)
* link_shared_object() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  419)
* link_to() (pathlib.Path 方法):         方法<2>.            (line  373)
* list (pdb command):                    调试器命令.         (line  169)
* List (typing 中的类):                  类 函数和修饰器.    (line  240)
* list (內置类):                         列表<2>.            (line    9)
* list – 列表:                           术语对照表.         (line  609)
* list comprehension – 列表推导式:       术语对照表.         (line  614)
* list() (imaplib.IMAP4 方法):           IMAP4 Objects.      (line  126)
* list() (multiprocessing.managers.SyncManager 方法): 管理器.
                                                             (line  187)
* list() (nntplib.NNTP 方法):            方法<3>.            (line  103)
* list() (poplib.POP3 方法):             POP3 对象.          (line   51)
* list() (tarfile.TarFile 方法):         TarFile 对象.       (line  103)
* list; comprehensions:                  列表显示.           (line    6)
* list; display:                         列表显示.           (line    6)
* listdir() (在 os 模块中):              文件和目录.         (line  325)
* listen() (asyncore.dispatcher 方法):   asyncore --- 异步socket处理器.
                                                             (line  175)
* listen() (socket.socket 方法):         套接字对象.         (line  160)
* listen() (在 logging.config 模块中):   配置函数.           (line   88)
* listen() (在 turtle 模块中):           使用屏幕事件.       (line    6)
* Listener (multiprocessing.connection 中的类): 监听器及客户端.
                                                             (line   46)
* listMethods() (xmlrpc.client.ServerProxy.system 方法): ServerProxy 对象.
                                                             (line   17)
* ListNoteBook (tkinter.tix 中的类):     Manager Widgets.    (line   13)
* listxattr() (在 os 模块中):            Linux 扩展属性.     (line   25)
* LIST_APPEND (opcode):                  Python字节码说明.   (line  307)
* list_dialects() (在 csv 模块中):       模块内容<3>.        (line   77)
* list_folders() (mailbox.Maildir 方法): Maildir.            (line   49)
* list_folders() (mailbox.MH 方法):      MH.                 (line   28)
* literal:                               字面值.             (line    6)
* literal <1>:                           字面值<2>.          (line    6)
* Literal() (在 typing 模块中):          类 函数和修饰器.    (line  807)
* literal_eval() (在 ast 模块中):        ast 中的辅助函数.   (line   41)
* LittleEndianStructure (ctypes 中的类): 结构化数据类型.     (line   14)
* ljust() (bytearray 方法):              bytes 和 bytearray 操作.
                                                             (line  210)
* ljust() (bytes 方法):                  bytes 和 bytearray 操作.
                                                             (line  210)
* ljust() (str 方法):                    字符串的方法<2>.    (line  246)
* LK_LOCK() (在 msvcrt 模块中):          文件操作.           (line   17)
* LK_NBLCK() (在 msvcrt 模块中):         文件操作.           (line   24)
* LK_NBRLCK() (在 msvcrt 模块中):        文件操作.           (line   24)
* LK_RLCK() (在 msvcrt 模块中):          文件操作.           (line   17)
* LK_UNLCK() (在 msvcrt 模块中):         文件操作.           (line   30)
* ll (pdb command):                      调试器命令.         (line  182)
* LMTP (smtplib 中的类):                 smtplib ---SMTP协议客户端.
                                                             (line   84)
* ln() (decimal.Context 方法):           上下文对象.         (line  296)
* ln() (decimal.Decimal 方法):           Decimal 对象.       (line  288)
* LNAME:                                 getpass --- 便携式密码输入工具.
                                                             (line   35)
* lngettext() (gettext.GNUTranslations 方法): GNUTranslations 类.
                                                             (line   80)
* lngettext() (gettext.NullTranslations 方法): NullTranslations 类.
                                                             (line   55)
* lngettext() (在 gettext 模块中):       GNU gettext API.    (line   80)
* load() (http.cookiejar.FileCookieJar 方法): CookieJar 和 FileCookieJar 对象.
                                                             (line  125)
* load() (http.cookies.BaseCookie 方法): Cookie 对象.        (line   40)
* load() (pickle.Unpickler 方法):        模块接口.           (line  234)
* load() (tracemalloc.Snapshot 类方法):  快照.               (line   50)
* load() (在 json 模块中):               基本使用.           (line   81)
* load() (在 marshal 模块中):            marshal --- 内部 Python 对象序列化.
                                                             (line   47)
* load() (在 pickle 模块中):             模块接口.           (line   53)
* load() (在 plistlib 模块中):           plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line   42)
* loader:                                查找器和加载器.     (line    6)
* Loader (importlib.abc 中的类):         importlib abc —— 关于导入的抽象基类.
                                                             (line  146)
* loader (importlib.machinery.ModuleSpec 属性): importlib machinery -- Importers and path hooks.
                                                             (line  367)
* loader – 加载器:                       术语对照表.         (line  622)
* LoadError:                             http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   28)
* loader_state (importlib.machinery.ModuleSpec 属性): importlib machinery -- Importers and path hooks.
                                                             (line  391)
* LoadKey() (在 winreg 模块中):          函数<11>.           (line  242)
* LoadLibrary() (ctypes.LibraryLoader 方法): 加载动态链接库. (line  139)
* loads() (在 json 模块中):              基本使用.           (line  129)
* loads() (在 marshal 模块中):           marshal --- 内部 Python 对象序列化.
                                                             (line   66)
* loads() (在 pickle 模块中):            模块接口.           (line   68)
* loads() (在 plistlib 模块中):          plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line   69)
* loads() (在 xmlrpc.client 模块中):     Convenience Functions.
                                                             (line   19)
* loadTestsFromModule() (unittest.TestLoader 方法): Loading and running tests.
                                                             (line   41)
* loadTestsFromName() (unittest.TestLoader 方法): Loading and running tests.
                                                             (line   70)
* loadTestsFromNames() (unittest.TestLoader 方法): Loading and running tests.
                                                             (line  104)
* loadTestsFromTestCase() (unittest.TestLoader 方法): Loading and running tests.
                                                             (line   29)
* LOAD_ATTR (opcode):                    Python字节码说明.   (line  571)
* LOAD_BUILD_CLASS (opcode):             Python字节码说明.   (line  401)
* load_cert_chain() (ssl.SSLContext 方法): SSL 上下文.       (line   75)
* LOAD_CLASSDEREF (opcode):              Python字节码说明.   (line  671)
* LOAD_CLOSURE (opcode):                 Python字节码说明.   (line  660)
* LOAD_CONST (opcode):                   Python字节码说明.   (line  485)
* load_default_certs() (ssl.SSLContext 方法): SSL 上下文.    (line   98)
* LOAD_DEREF (opcode):                   Python字节码说明.   (line  666)
* load_dh_params() (ssl.SSLContext 方法): SSL 上下文.        (line  309)
* load_extension() (sqlite3.Connection 方法): 连接对象（Connection）.
                                                             (line  263)
* LOAD_FAST (opcode):                    Python字节码说明.   (line  648)
* LOAD_GLOBAL (opcode):                  Python字节码说明.   (line  632)
* LOAD_METHOD (opcode):                  Python字节码说明.   (line  737)
* load_module() (importlib.abc.FileLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  429)
* load_module() (importlib.abc.InspectLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  388)
* load_module() (importlib.abc.Loader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  179)
* load_module() (importlib.abc.SourceLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  513)
* load_module() (importlib.machinery.SourceFileLoader 方法): importlib machinery -- Importers and path hooks.
                                                             (line  240)
* load_module() (importlib.machinery.SourcelessFileLoader 方法): importlib machinery -- Importers and path hooks.
                                                             (line  284)
* load_module() (zipimport.zipimporter 方法): zipimporter 对象.
                                                             (line   56)
* load_module() (在 imp 模块中):         imp --- Access the import internals.
                                                             (line   90)
* LOAD_NAME (opcode):                    Python字节码说明.   (line  489)
* load_package_tests() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  909)
* load_verify_locations() (ssl.SSLContext 方法): SSL 上下文. (line  112)
* local (threading 中的类):              线程本地数据.       (line   14)
* localcontext() (在 decimal 模块中):    上下文对象.         (line   23)
* locale (模块):                         locale --- 国际化服务.
                                                             (line    6)
* LOCALE() (在 re 模块中):               模块内容.           (line   67)
* localeconv() (在 locale 模块中):       locale --- 国际化服务.
                                                             (line   53)
* LocaleHTMLCalendar (calendar 中的类):  calendar --- 日历相关函数.
                                                             (line  234)
* LocaleTextCalendar (calendar 中的类):  calendar --- 日历相关函数.
                                                             (line  228)
* localName (xml.dom.Attr 属性):         Attr 对象.          (line   12)
* localName (xml.dom.Node 属性):         节点对象.           (line   53)
* locals() (內置函数):                   内置函数.           (line  752)
* localtime() (在 email.utils 模块中):   email utils 其他工具.
                                                             (line   12)
* localtime() (在 time 模块中):          函数<2>.            (line  125)
* Locator (xml.sax.xmlreader 中的类):    xml sax xmlreader --- 用于 XML 解析器的接口.
                                                             (line   36)
* Lock (asyncio 中的类):                 Lock.               (line    6)
* Lock (multiprocessing 中的类):         同步原语.           (line   40)
* Lock (threading 中的类):               锁对象.             (line   26)
* lock() (mailbox.Babyl 方法):           Babyl.              (line   47)
* lock() (mailbox.Mailbox 方法):         Mailbox 对象.       (line  203)
* lock() (mailbox.Maildir 方法):         Maildir.            (line   90)
* lock() (mailbox.mbox 方法):            mbox.               (line   32)
* lock() (mailbox.MH 方法):              MH.                 (line   75)
* lock() (mailbox.MMDF 方法):            MMDF.               (line   29)
* Lock() (multiprocessing.managers.SyncManager 方法): 管理器.
                                                             (line  148)
* lock, interpreter:                     Thread State and the Global Interpreter Lock.
                                                             (line    6)
* locked() (asyncio.Condition 方法):     Condition.          (line   57)
* locked() (asyncio.Lock 方法):          Lock.               (line   54)
* locked() (asyncio.Semaphore 方法):     Semaphore.          (line   48)
* locked() (threading.Lock 方法):        锁对象.             (line   69)
* locked() (_thread.lock 方法):          _thread --- 底层多线程 API.
                                                             (line  126)
* lockf() (在 fcntl 模块中):             fcntl --- The fcntl and ioctl system calls.
                                                             (line  120)
* lockf() (在 os 模块中):                文件描述符操作.     (line  190)
* locking() (在 msvcrt 模块中):          文件操作.           (line    6)
* LockType() (在 _thread 模块中):        _thread --- 底层多线程 API.
                                                             (line   23)
* lock_held() (在 imp 模块中):           imp --- Access the import internals.
                                                             (line  248)
* log() (logging.Logger 方法):           记录器对象.         (line  189)
* log() (在 cmath 模块中):               幂函数与对数函数<2>.
                                                             (line   10)
* log() (在 logging 模块中):             模块级别函数.       (line  126)
* log() (在 math 模块中):                幂函数与对数函数.   (line   26)
* log10() (decimal.Context 方法):        上下文对象.         (line  300)
* log10() (decimal.Decimal 方法):        Decimal 对象.       (line  293)
* log10() (在 cmath 模块中):             幂函数与对数函数<2>.
                                                             (line   15)
* log10() (在 math 模块中):              幂函数与对数函数.   (line   50)
* log1p() (在 math 模块中):              幂函数与对数函数.   (line   33)
* log2() (在 math 模块中):               幂函数与对数函数.   (line   38)
* logb() (decimal.Context 方法):         上下文对象.         (line  304)
* logb() (decimal.Decimal 方法):         Decimal 对象.       (line  298)
* Logger (logging 中的类):               记录器对象.         (line   18)
* LoggerAdapter (logging 中的类):        LoggerAdapter 对象. (line   10)
* logging (模块):                        logging --- Python 的日志记录工具.
                                                             (line    6)
* logging.config (模块):                 logging config --- 日志记录配置.
                                                             (line    6)
* logging.handlers (模块):               logging handlers --- 日志处理.
                                                             (line    6)
* logical line:                          逻辑行.             (line    6)
* logical_and() (decimal.Context 方法):  上下文对象.         (line  308)
* logical_and() (decimal.Decimal 方法):  Decimal 对象.       (line  305)
* logical_invert() (decimal.Context 方法): 上下文对象.       (line  312)
* logical_invert() (decimal.Decimal 方法): Decimal 对象.     (line  311)
* logical_or() (decimal.Context 方法):   上下文对象.         (line  316)
* logical_or() (decimal.Decimal 方法):   Decimal 对象.       (line  316)
* logical_xor() (decimal.Context 方法):  上下文对象.         (line  320)
* logical_xor() (decimal.Decimal 方法):  Decimal 对象.       (line  322)
* login() (ftplib.FTP 方法):             FTP 对象.           (line   39)
* login() (imaplib.IMAP4 方法):          IMAP4 Objects.      (line  132)
* login() (nntplib.NNTP 方法):           方法<3>.            (line   47)
* login() (smtplib.SMTP 方法):           SMTP Objects.       (line   95)
* login_cram_md5() (imaplib.IMAP4 方法): IMAP4 Objects.      (line  137)
* LOGNAME:                               进程参数.           (line  199)
* LOGNAME <1>:                           getpass --- 便携式密码输入工具.
                                                             (line   35)
* lognormvariate() (在 random 模块中):   实值分布.           (line   55)
* logout() (imaplib.IMAP4 方法):         IMAP4 Objects.      (line  143)
* LogRecord (logging 中的类):            LogRecord 属性.     (line   10)
* log_date_time_string() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  307)
* log_error() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  276)
* log_exception() (wsgiref.handlers.BaseHandler 方法): wsgiref handlers -- server/gateway base classes.
                                                             (line  208)
* log_message() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  282)
* log_request() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  269)
* log_to_stderr() (在 multiprocessing 模块中): 日志记录<2>.  (line   21)
* long (2to3 fixer):                     修复器.             (line  173)
* longMessage (unittest.TestCase 属性):  测试用例.           (line  671)
* longname() (在 curses 模块中):         函数<3>.            (line  219)
* LONG_MAX:                              整数型对象.         (line   97)
* lookup() (symtable.SymbolTable 方法):  Examining Symbol Tables.
                                                             (line   52)
* lookup() (tkinter.ttk.Style 方法):     Ttk Styling.        (line   81)
* lookup() (在 codecs 模块中):           codecs --- 编解码器注册和相关基类.
                                                             (line   39)
* lookup() (在 unicodedata 模块中):      unicodedata --- Unicode 数据库.
                                                             (line   14)
* LookupError:                           基类.               (line   46)
* lookup_error() (在 codecs 模块中):     错误处理方案.       (line   97)
* loop control; target:                  break 语句.         (line   12)
* loop() (在 asyncore 模块中):           asyncore --- 异步socket处理器.
                                                             (line   39)
* loop; over mutable sequence:           for 语句<2>.        (line   38)
* loop; statement:                       break 语句.         (line    6)
* loop; statement <1>:                   continue 语句.      (line    6)
* loop; statement <2>:                   while 语句.         (line    6)
* loop; statement <3>:                   for 语句<2>.        (line    6)
* lower() (bytearray 方法):              bytes 和 bytearray 操作.
                                                             (line  473)
* lower() (bytes 方法):                  bytes 和 bytearray 操作.
                                                             (line  473)
* lower() (str 方法):                    字符串的方法<2>.    (line  252)
* LPAR() (在 token 模块中):              token --- 与Python解析树一起使用的常量.
                                                             (line   50)
* lpAttributeList (subprocess.STARTUPINFO 属性): Windows Popen 助手.
                                                             (line   53)
* lru_cache() (在 functools 模块中):     functools --- 高阶函数和可调用对象上的操作.
                                                             (line   65)
* lseek() (在 os 模块中):                文件描述符操作.     (line  215)
* lshift() (在 operator 模块中):         operator --- 标准运算符替代函数.
                                                             (line   94)
* LSQB() (在 token 模块中):              token --- 与Python解析树一起使用的常量.
                                                             (line   58)
* lstat() (pathlib.Path 方法):           方法<2>.            (line  197)
* lstat() (在 os 模块中):                文件和目录.         (line  356)
* lstrip() (bytearray 方法):             bytes 和 bytearray 操作.
                                                             (line  220)
* lstrip() (bytes 方法):                 bytes 和 bytearray 操作.
                                                             (line  220)
* lstrip() (str 方法):                   字符串的方法<2>.    (line  258)
* lsub() (imaplib.IMAP4 方法):           IMAP4 Objects.      (line  150)
* lt() (在 operator 模块中):             operator --- 标准运算符替代函数.
                                                             (line   19)
* lt() (在 turtle 模块中):               海龟动作.           (line   55)
* LWPCookieJar (http.cookiejar 中的类):  FileCookieJar subclasses and co-operation with web browsers.
                                                             (line   28)
* lzma (模块):                           lzma --- 用 LZMA 算法压缩.
                                                             (line    6)
* LZMACompressor (lzma 中的类):          在内存中压缩和解压缩数据.
                                                             (line    6)
* LZMADecompressor (lzma 中的类):        在内存中压缩和解压缩数据.
                                                             (line   79)
* LZMAError:                             lzma --- 用 LZMA 算法压缩.
                                                             (line   21)
* LZMAFile (lzma 中的类):                读写压缩文件.       (line   40)
* M() (在 re 模块中):                    模块内容.           (line   81)
* machine() (在 platform 模块中):        跨平台.             (line   32)
* macros (netrc.netrc 属性):             netrc 对象.         (line   27)
* mac_ver() (在 platform 模块中):        Mac OS平台.         (line    6)
* madvise() (mmap.mmap 方法):            mmap --- 内存映射文件支持.
                                                             (line  175)
* MADV_AUTOSYNC() (在 mmap 模块中):      MADV_* 常量.        (line    6)
* MADV_CORE() (在 mmap 模块中):          MADV_* 常量.        (line    6)
* MADV_DODUMP() (在 mmap 模块中):        MADV_* 常量.        (line    6)
* MADV_DOFORK() (在 mmap 模块中):        MADV_* 常量.        (line    6)
* MADV_DONTDUMP() (在 mmap 模块中):      MADV_* 常量.        (line    6)
* MADV_DONTFORK() (在 mmap 模块中):      MADV_* 常量.        (line    6)
* MADV_DONTNEED() (在 mmap 模块中):      MADV_* 常量.        (line    6)
* MADV_FREE() (在 mmap 模块中):          MADV_* 常量.        (line    6)
* MADV_HUGEPAGE() (在 mmap 模块中):      MADV_* 常量.        (line    6)
* MADV_HWPOISON() (在 mmap 模块中):      MADV_* 常量.        (line    6)
* MADV_MERGEABLE() (在 mmap 模块中):     MADV_* 常量.        (line    6)
* MADV_NOCORE() (在 mmap 模块中):        MADV_* 常量.        (line    6)
* MADV_NOHUGEPAGE() (在 mmap 模块中):    MADV_* 常量.        (line    6)
* MADV_NORMAL() (在 mmap 模块中):        MADV_* 常量.        (line    6)
* MADV_NOSYNC() (在 mmap 模块中):        MADV_* 常量.        (line    6)
* MADV_PROTECT() (在 mmap 模块中):       MADV_* 常量.        (line    6)
* MADV_RANDOM() (在 mmap 模块中):        MADV_* 常量.        (line    6)
* MADV_REMOVE() (在 mmap 模块中):        MADV_* 常量.        (line    6)
* MADV_SEQUENTIAL() (在 mmap 模块中):    MADV_* 常量.        (line    6)
* MADV_SOFT_OFFLINE() (在 mmap 模块中):  MADV_* 常量.        (line    6)
* MADV_UNMERGEABLE() (在 mmap 模块中):   MADV_* 常量.        (line    6)
* MADV_WILLNEED() (在 mmap 模块中):      MADV_* 常量.        (line    6)
* magic method – 魔术方法:               术语对照表.         (line  629)
* magic; method:                         术语对照表.         (line  632)
* MagicMock (unittest.mock 中的类):      Magic Mock.         (line    9)
* MAGIC_NUMBER() (在 importlib.util 模块中): importlib util -- Utility code for importers.
                                                             (line   13)
* Mailbox (mailbox 中的类):              Mailbox 对象.       (line    6)
* mailbox (模块):                        mailbox --- 操作多种格式的邮箱.
                                                             (line    6)
* mailcap (模块):                        mailcap --- Mailcap 文件处理.
                                                             (line    6)
* Maildir (mailbox 中的类):              Maildir.            (line    6)
* MaildirMessage (mailbox 中的类):       MaildirMessage.     (line    6)
* mailfrom (smtpd.SMTPChannel 属性):     SMTPChannel 对象.   (line   73)
* MailmanProxy (smtpd 中的类):           MailmanProxy 对象.  (line    6)
* main():                                Process-wide parameters.
                                                             (line    9)
* main() <1>:                            Process-wide parameters.
                                                             (line   36)
* main() <2>:                            Process-wide parameters.
                                                             (line  217)
* main() (在 py_compile 模块中):         py_compile --- 编译 Python 源文件.
                                                             (line  102)
* main() (在 site 模块中):               模块内容<7>.        (line   38)
* main() (在 unittest 模块中):           Loading and running tests.
                                                             (line  488)
* mainloop() (在 turtle 模块中):         使用屏幕事件.       (line   98)
* maintype (email.headerregistry.ContentTypeHeader 属性): email headerregistry 自定义标头对象.
                                                             (line  226)
* main_thread() (在 threading 模块中):   threading --- 基于线程的并行.
                                                             (line   99)
* major (email.headerregistry.MIMEVersionHeader 属性): email headerregistry 自定义标头对象.
                                                             (line  199)
* major() (在 os 模块中):                文件和目录.         (line  475)
* makedev() (在 os 模块中):              文件和目录.         (line  485)
* makedirs() (在 os 模块中):             文件和目录.         (line  406)
* makeelement() (xml.etree.ElementTree.Element 方法): 元素对象.
                                                             (line  149)
* makefile() (socket method):            标准类型层级结构.   (line  476)
* makefile() (socket.socket 方法):       套接字对象.         (line  168)
* makeLogRecord() (在 logging 模块中):   模块级别函数.       (line  192)
* makePickle() (logging.handlers.SocketHandler 方法): SocketHandler.
                                                             (line   38)
* makeRecord() (logging.Logger 方法):    记录器对象.         (line  241)
* makeSocket() (logging.handlers.DatagramHandler 方法): DatagramHandler.
                                                             (line   24)
* makeSocket() (logging.handlers.SocketHandler 方法): SocketHandler.
                                                             (line   33)
* maketrans() (bytearray 静态方法):      bytes 和 bytearray 操作.
                                                             (line  106)
* maketrans() (bytes 静态方法):          bytes 和 bytearray 操作.
                                                             (line  106)
* maketrans() (str 静态方法):            字符串的方法<2>.    (line  269)
* make_alternative() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  512)
* make_archive() (在 distutils.archive_util 模块中): distutils archive_util --- Archiving utilities.
                                                             (line    9)
* make_archive() (在 shutil 模块中):     归档操作.           (line   13)
* make_bad_fd() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  680)
* make_cookies() (http.cookiejar.CookieJar 方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   60)
* make_dataclass() (在 dataclasses 模块中): 模块级装饰器、类和函数.
                                                             (line  253)
* make_file() (difflib.HtmlDiff 方法):   difflib --- 计算差异的辅助工具.
                                                             (line   92)
* MAKE_FUNCTION (opcode):                Python字节码说明.   (line  757)
* make_header() (在 email.header 模块中): email header 国际化标头.
                                                             (line  158)
* make_legacy_pyc() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  190)
* make_mixed() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  520)
* make_msgid() (在 email.utils 模块中):  email utils 其他工具.
                                                             (line   23)
* make_parser() (在 xml.sax 模块中):     xml sax --- 支持 SAX2 解析器.
                                                             (line   24)
* make_pkg() (在 test.support.script_helper 模块中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   86)
* make_related() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  505)
* make_script() (在 test.support.script_helper 模块中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   71)
* make_server() (在 wsgiref.simple_server 模块中): wsgiref simple_server -- a simple WSGI HTTP server.
                                                             (line   14)
* make_table() (difflib.HtmlDiff 方法):  difflib --- 计算差异的辅助工具.
                                                             (line  117)
* make_tarball() (在 distutils.archive_util 模块中): distutils archive_util --- Archiving utilities.
                                                             (line   25)
* make_zipfile() (在 distutils.archive_util 模块中): distutils archive_util --- Archiving utilities.
                                                             (line   39)
* make_zip_pkg() (在 test.support.script_helper 模块中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   91)
* make_zip_script() (在 test.support.script_helper 模块中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   78)
* malloc():                              概述<16>.           (line   23)
* mangle_from_ (email.policy.Compat32 属性): email policy 策略对象.
                                                             (line  450)
* mangle_from_ (email.policy.Policy 属性): email policy 策略对象.
                                                             (line  150)
* map (2to3 fixer):                      修复器.             (line  177)
* map() (concurrent.futures.Executor 方法): Executor 对象.   (line   19)
* map() (multiprocessing.pool.Pool 方法): 进程池.            (line   71)
* map() (tkinter.ttk.Style 方法):        Ttk Styling.        (line   48)
* map() (內置函数):                      内置函数.           (line  761)
* mapLogRecord() (logging.handlers.HTTPHandler 方法): HTTPHandler.
                                                             (line   24)
* Mapping (collections.abc 中的类):      容器抽象基类.       (line  175)
* Mapping (typing 中的类):               类 函数和修饰器.    (line  203)
* mapping – 映射:                        术语对照表.         (line  632)
* mapping() (msilib.Control 方法):       GUI classes.        (line   20)
* MappingProxyType (types 中的类):       标准解释器类型.     (line  190)
* MappingView (collections.abc 中的类):  容器抽象基类.       (line  180)
* MappingView (typing 中的类):           类 函数和修饰器.    (line  264)
* mapPriority() (logging.handlers.SysLogHandler 方法): SysLogHandler.
                                                             (line  167)
* maps (collections.ChainMap 属性):      ChainMap 对象.      (line   32)
* maps() (在 nis 模块中):                nis --- Sun 的 NIS 黄页 接口.
                                                             (line   36)
* MAP_ADD (opcode):                      Python字节码说明.   (line  311)
* map_async() (multiprocessing.pool.Pool 方法): 进程池.      (line   84)
* map_table_b2() (在 stringprep 模块中): stringprep --- 因特网字符串预备.
                                                             (line   37)
* map_table_b3() (在 stringprep 模块中): stringprep --- 因特网字符串预备.
                                                             (line   42)
* map_to_type() (email.headerregistry.HeaderRegistry 方法): email headerregistry 自定义标头对象.
                                                             (line  323)
* marshal (模块):                        marshal --- 内部 Python 对象序列化.
                                                             (line    6)
* marshalling; objects:                  pickle --- Python 对象序列化.
                                                             (line    8)
* masking; operations:                   整数类型的按位运算. (line    6)
* Match (typing 中的类):                 类 函数和修饰器.    (line  450)
* match() (pathlib.PurePath 方法):       方法和特征属性.     (line  207)
* match() (re.Pattern 方法):             正则表达式对象 （正则对象）.
                                                             (line   29)
* match() (在 nis 模块中):               nis --- Sun 的 NIS 黄页 接口.
                                                             (line   15)
* match() (在 re 模块中):                模块内容.           (line  118)
* Matcher (test.support 中的类):         test support --- Utilities for the Python test suite.
                                                             (line 1085)
* matches() (test.support.Matcher 方法): test support --- Utilities for the Python test suite.
                                                             (line 1087)
* match_hostname() (在 ssl 模块中):      证书处理.           (line    6)
* match_test() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  246)
* match_value() (test.support.Matcher 方法): test support --- Utilities for the Python test suite.
                                                             (line 1091)
* math (模块):                           math --- 数学函数.  (line    6)
* matmul() (在 operator 模块中):         operator --- 标准运算符替代函数.
                                                             (line  109)
* matrix multiplication:                 二元算术运算符.     (line   20)
* max (datetime.date 属性):              date 对象.          (line   84)
* max (datetime.datetime 属性):          datetime 对象.      (line  230)
* max (datetime.time 属性):              time 对象.          (line   34)
* max (datetime.timedelta 属性):         timedelta 类对象.   (line   73)
* max() (decimal.Context 方法):          上下文对象.         (line  324)
* max() (decimal.Decimal 方法):          Decimal 对象.       (line  328)
* max() (內置函数):                      内置函数.           (line  769)
* max() (在 audioop 模块中):             audioop --- 处理原始音频数据.
                                                             (line  136)
* maxarray (reprlib.Repr 属性):          Repr 对象.          (line   13)
* maxdeque (reprlib.Repr 属性):          Repr 对象.          (line   13)
* maxdict (reprlib.Repr 属性):           Repr 对象.          (line   13)
* maxDiff (unittest.TestCase 属性):      测试用例.           (line  688)
* maxfrozenset (reprlib.Repr 属性):      Repr 对象.          (line   13)
* MAXIMUM_SUPPORTED (ssl.TLSVersion 属性): 常量<9>.          (line  479)
* maximum_version (ssl.SSLContext 属性): SSL 上下文.         (line  470)
* maxlen (collections.deque 属性):       deque 对象.         (line  108)
* maxlevel (reprlib.Repr 属性):          Repr 对象.          (line    9)
* maxlist (reprlib.Repr 属性):           Repr 对象.          (line   13)
* maxlong (reprlib.Repr 属性):           Repr 对象.          (line   24)
* maxother (reprlib.Repr 属性):          Repr 对象.          (line   34)
* maxpp() (在 audioop 模块中):           audioop --- 处理原始音频数据.
                                                             (line  140)
* maxset (reprlib.Repr 属性):            Repr 对象.          (line   13)
* maxsize (asyncio.Queue 属性):          Queue.              (line   22)
* maxsize() (在 sys 模块中):             sys --- 系统相关的参数和函数.
                                                             (line  854)
* maxstring (reprlib.Repr 属性):         Repr 对象.          (line   28)
* maxtuple (reprlib.Repr 属性):          Repr 对象.          (line   13)
* maxunicode() (在 sys 模块中):          sys --- 系统相关的参数和函数.
                                                             (line  859)
* MAXYEAR() (在 datetime 模块中):        常量.               (line   13)
* max_count (email.headerregistry.BaseHeader 属性): email headerregistry 自定义标头对象.
                                                             (line   50)
* MAX_EMAX() (在 decimal 模块中):        常量<4>.            (line   15)
* MAX_INTERPOLATION_DEPTH() (在 configparser 模块中): ConfigParser 对象.
                                                             (line  279)
* max_lines (textwrap.TextWrapper 属性): textwrap --- 文本自动换行与填充.
                                                             (line  225)
* max_line_length (email.policy.Policy 属性): email policy 策略对象.
                                                             (line  115)
* max_mag() (decimal.Context 方法):      上下文对象.         (line  328)
* max_mag() (decimal.Decimal 方法):      Decimal 对象.       (line  334)
* max_memuse() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  122)
* MAX_PREC() (在 decimal 模块中):        常量<4>.            (line   12)
* max_prefixlen (ipaddress.IPv4Address 属性): 地址对象.      (line   44)
* max_prefixlen (ipaddress.IPv4Network 属性): Network objects.
                                                             (line   65)
* max_prefixlen (ipaddress.IPv6Address 属性): 地址对象.      (line  171)
* max_prefixlen (ipaddress.IPv6Network 属性): Network objects.
                                                             (line  295)
* MAX_Py_ssize_t() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  118)
* mbox (mailbox 中的类):                 mbox.               (line    6)
* mboxMessage (mailbox 中的类):          mboxMessage.        (line    6)
* MB_ICONASTERISK() (在 winsound 模块中): winsound --- Sound-playing interface for Windows.
                                                             (line  128)
* MB_ICONEXCLAMATION() (在 winsound 模块中): winsound --- Sound-playing interface for Windows.
                                                             (line  132)
* MB_ICONHAND() (在 winsound 模块中):    winsound --- Sound-playing interface for Windows.
                                                             (line  136)
* MB_ICONQUESTION() (在 winsound 模块中): winsound --- Sound-playing interface for Windows.
                                                             (line  140)
* MB_OK() (在 winsound 模块中):          winsound --- Sound-playing interface for Windows.
                                                             (line  144)
* mean (statistics.NormalDist 属性):     NormalDist 对象.    (line   18)
* mean() (在 statistics 模块中):         函数细节.           (line    9)
* median (statistics.NormalDist 属性):   NormalDist 对象.    (line   22)
* median() (在 statistics 模块中):       函数细节.           (line  103)
* median_grouped() (在 statistics 模块中): 函数细节.         (line  159)
* median_high() (在 statistics 模块中):  函数细节.           (line  143)
* median_low() (在 statistics 模块中):   函数细节.           (line  127)
* MemberDescriptorType() (在 types 模块中): 标准解释器类型.  (line  180)
* membership; test:                      成员检测运算.       (line   30)
* memfd_create() (在 os 模块中):         文件和目录.         (line 1429)
* memmove() (在 ctypes 模块中):          工具函数.           (line  119)
* MemoryBIO (ssl 中的类):                内存 BIO 支持<2>.   (line  118)
* MemoryError:                           具体异常.           (line   69)
* MemoryHandler (logging.handlers 中的类): MemoryHandler.    (line   35)
* memoryview (內置类):                   内存视图.           (line    9)
* memset() (在 ctypes 模块中):           工具函数.           (line  124)
* merge() (在 heapq 模块中):             heapq --- 堆队列算法.
                                                             (line   66)
* Message (email.message 中的类):        email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line   38)
* Message (mailbox 中的类):              Message 对象.       (line    6)
* message digest, MD5:                   hashlib --- 安全哈希与消息摘要.
                                                             (line    8)
* MessageBeep() (在 winsound 模块中):    winsound --- Sound-playing interface for Windows.
                                                             (line   31)
* MessageClass (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line  153)
* MessageError:                          email errors 异常和缺陷类.
                                                             (line   12)
* MessageParseError:                     email errors 异常和缺陷类.
                                                             (line   17)
* messages() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   20)
* message_factory (email.policy.Policy 属性): email policy 策略对象.
                                                             (line  158)
* message_from_binary_file() (在 email 模块中): Parser API.  (line  114)
* message_from_bytes() (在 email 模块中): Parser API.        (line  103)
* message_from_file() (在 email 模块中): Parser API.         (line  134)
* message_from_string() (在 email 模块中): Parser API.       (line  125)
* meta hooks:                            导入钩子.           (line    6)
* meta path finder – 元路径查找器:       术语对照表.         (line  640)
* meta() (在 curses 模块中):             函数<3>.            (line  225)
* metaclass:                             元类.               (line    6)
* metaclass (2to3 fixer):                修复器.             (line  183)
* metaclass – 元类:                      术语对照表.         (line  648)
* metaclass hint:                        确定适当的元类.     (line    6)
* MetaPathFinder (importlib.abc 中的类): importlib abc —— 关于导入的抽象基类.
                                                             (line   44)
* metavar (optparse.Option 属性):        Option attributes.  (line   80)
* MetavarTypeHelpFormatter (argparse 中的类): formatter_class.
                                                             (line    9)
* meta_path() (在 sys 模块中):           sys --- 系统相关的参数和函数.
                                                             (line  868)
* Meter (tkinter.tix 中的类):            Basic Widgets.      (line   43)
* method (urllib.request.Request 属性):  Request 对象.       (line   47)
* method – 方法:                         术语对照表.         (line  659)
* method resolution order – 方法解析顺序: 术语对照表.        (line  665)
* method; call:                          调用.               (line  105)
* methodattrs (2to3 fixer):              修复器.             (line  188)
* methodcaller() (在 operator 模块中):   operator --- 标准运算符替代函数.
                                                             (line  285)
* MethodDescriptorType() (在 types 模块中): 标准解释器类型.  (line   91)
* methodHelp() (xmlrpc.client.ServerProxy.system 方法): ServerProxy 对象.
                                                             (line   43)
* methods (pyclbr.Class 属性):           类对象<2>.          (line   43)
* methods() (在 crypt 模块中):           Module Attributes.  (line    8)
* methodSignature() (xmlrpc.client.ServerProxy.system 方法): ServerProxy 对象.
                                                             (line   22)
* MethodType (in module types):          函数对象<3>.        (line   14)
* MethodType (in module types) <1>:      方法对象<2>.        (line   11)
* MethodType() (在 types 模块中):        标准解释器类型.     (line   67)
* MethodWrapperType() (在 types 模块中): 标准解释器类型.     (line   84)
* METHOD_BLOWFISH() (在 crypt 模块中):   Hashing Methods.    (line   22)
* method_calls (unittest.mock.Mock 属性): Mock 类.           (line  462)
* METHOD_CRYPT() (在 crypt 模块中):      Hashing Methods.    (line   34)
* METHOD_MD5() (在 crypt 模块中):        Hashing Methods.    (line   29)
* METHOD_SHA256() (在 crypt 模块中):     Hashing Methods.    (line   17)
* METHOD_SHA512() (在 crypt 模块中):     Hashing Methods.    (line   11)
* METH_CLASS (內置变量):                 公用对象的结构.     (line  221)
* METH_COEXIST (內置变量):               公用对象的结构.     (line  238)
* METH_FASTCALL (內置变量):              公用对象的结构.     (line  172)
* METH_NOARGS (內置变量):                公用对象的结构.     (line  199)
* METH_O (內置变量):                     公用对象的结构.     (line  208)
* METH_STATIC (內置变量):                公用对象的结构.     (line  228)
* METH_VARARGS (內置变量):               公用对象的结构.     (line  153)
* MFD_ALLOW_SEALING() (在 os 模块中):    文件和目录.         (line 1445)
* MFD_CLOEXEC() (在 os 模块中):          文件和目录.         (line 1445)
* MFD_HUGETLB() (在 os 模块中):          文件和目录.         (line 1445)
* MFD_HUGE_16GB() (在 os 模块中):        文件和目录.         (line 1445)
* MFD_HUGE_16MB() (在 os 模块中):        文件和目录.         (line 1445)
* MFD_HUGE_1GB() (在 os 模块中):         文件和目录.         (line 1445)
* MFD_HUGE_1MB() (在 os 模块中):         文件和目录.         (line 1445)
* MFD_HUGE_256MB() (在 os 模块中):       文件和目录.         (line 1445)
* MFD_HUGE_2GB() (在 os 模块中):         文件和目录.         (line 1445)
* MFD_HUGE_2MB() (在 os 模块中):         文件和目录.         (line 1445)
* MFD_HUGE_32MB() (在 os 模块中):        文件和目录.         (line 1445)
* MFD_HUGE_512KB() (在 os 模块中):       文件和目录.         (line 1445)
* MFD_HUGE_512MB() (在 os 模块中):       文件和目录.         (line 1445)
* MFD_HUGE_64KB() (在 os 模块中):        文件和目录.         (line 1445)
* MFD_HUGE_8MB() (在 os 模块中):         文件和目录.         (line 1445)
* MFD_HUGE_MASK() (在 os 模块中):        文件和目录.         (line 1445)
* MFD_HUGE_SHIFT() (在 os 模块中):       文件和目录.         (line 1445)
* MH (mailbox 中的类):                   MH.                 (line    6)
* MHMessage (mailbox 中的类):            MHMessage.          (line    6)
* microsecond (datetime.datetime 属性):  datetime 对象.      (line  266)
* microsecond (datetime.time 属性):      time 对象.          (line   58)
* MIME; base64 encoding:                 base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line    8)
* MIME; content type:                    mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line    8)
* MIME; headers:                         mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line   23)
* MIME; headers <1>:                     cgi --- 通用网关接口支持.
                                                             (line    8)
* MIME; quoted-printable encoding:       quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line    8)
* MIMEApplication (email.mime.application 中的类): email mime 从头创建电子邮件和 MIME 对象.
                                                             (line   82)
* MIMEAudio (email.mime.audio 中的类):   email mime 从头创建电子邮件和 MIME 对象.
                                                             (line  108)
* MIMEBase (email.mime.base 中的类):     email mime 从头创建电子邮件和 MIME 对象.
                                                             (line   26)
* MIMEImage (email.mime.image 中的类):   email mime 从头创建电子邮件和 MIME 对象.
                                                             (line  135)
* MIMEMessage (email.mime.message 中的类): email mime 从头创建电子邮件和 MIME 对象.
                                                             (line  162)
* MIMEMultipart (email.mime.multipart 中的类): email mime 从头创建电子邮件和 MIME 对象.
                                                             (line   58)
* MIMENonMultipart (email.mime.nonmultipart 中的类): email mime 从头创建电子邮件和 MIME 对象.
                                                             (line   49)
* MIMEPart (email.message 中的类):       email message 表示一封电子邮件信息.
                                                             (line  603)
* MIMEText (email.mime.text 中的类):     email mime 从头创建电子邮件和 MIME 对象.
                                                             (line  178)
* MimeTypes (mimetypes 中的类):          MimeTypes 对象.     (line    9)
* mimetypes (模块):                      mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line    6)
* MIMEVersionHeader (email.headerregistry 中的类): email headerregistry 自定义标头对象.
                                                             (line  189)
* min (datetime.date 属性):              date 对象.          (line   80)
* min (datetime.datetime 属性):          datetime 对象.      (line  225)
* min (datetime.time 属性):              time 对象.          (line   30)
* min (datetime.timedelta 属性):         timedelta 类对象.   (line   68)
* min() (decimal.Context 方法):          上下文对象.         (line  332)
* min() (decimal.Decimal 方法):          Decimal 对象.       (line  338)
* min() (內置函数):                      内置函数.           (line  797)
* MINEQUAL() (在 token 模块中):          token --- 与Python解析树一起使用的常量.
                                                             (line  170)
* MINIMUM_SUPPORTED (ssl.TLSVersion 属性): 常量<9>.          (line  477)
* minimum_version (ssl.SSLContext 属性): SSL 上下文.         (line  488)
* minmax() (在 audioop 模块中):          audioop --- 处理原始音频数据.
                                                             (line  144)
* minor (email.headerregistry.MIMEVersionHeader 属性): email headerregistry 自定义标头对象.
                                                             (line  203)
* minor() (在 os 模块中):                文件和目录.         (line  480)
* minus:                                 一元算术和位运算.   (line   10)
* minus() (decimal.Context 方法):        上下文对象.         (line  340)
* MINUS() (在 token 模块中):             token --- 与Python解析树一起使用的常量.
                                                             (line   82)
* minute (datetime.datetime 属性):       datetime 对象.      (line  258)
* minute (datetime.time 属性):           time 对象.          (line   50)
* MINYEAR() (在 datetime 模块中):        常量.               (line    8)
* MIN_EMIN() (在 decimal 模块中):        常量<4>.            (line   18)
* MIN_ETINY() (在 decimal 模块中):       常量<4>.            (line   21)
* min_mag() (decimal.Context 方法):      上下文对象.         (line  336)
* min_mag() (decimal.Decimal 方法):      Decimal 对象.       (line  344)
* mirrored() (在 unicodedata 模块中):    unicodedata --- Unicode 数据库.
                                                             (line   59)
* misc_header (cmd.Cmd 属性):            Cmd 对象.           (line  122)
* MISSING (contextvars.contextvars.Token.Token 属性): 上下文变量.
                                                             (line   81)
* MissingSectionHeaderError:             异常<5>.            (line   51)
* missing_compiler_executable() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  960)
* MISSING_C_DOCSTRINGS() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  132)
* MIXERDEV:                              ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line   71)
* mkd() (ftplib.FTP 方法):               FTP 对象.           (line  186)
* mkdir() (pathlib.Path 方法):           方法<2>.            (line  202)
* mkdir() (在 os 模块中):                文件和目录.         (line  384)
* mkdtemp() (在 tempfile 模块中):        tempfile --- 生成临时文件和目录.
                                                             (line  167)
* mkfifo() (在 os 模块中):               文件和目录.         (line  438)
* mknod() (在 os 模块中):                文件和目录.         (line  457)
* mkpath() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  490)
* mkpath() (在 distutils.dir_util 模块中): distutils dir_util --- Directory tree operations.
                                                             (line    9)
* mksalt() (在 crypt 模块中):            模块函数<2>.        (line   39)
* mkstemp() (在 tempfile 模块中):        tempfile --- 生成临时文件和目录.
                                                             (line  119)
* mktemp() (在 tempfile 模块中):         已弃用的函数和变量. (line   12)
* mktime() (在 time 模块中):             函数<2>.            (line  131)
* mktime_tz() (在 email.utils 模块中):   email utils 其他工具.
                                                             (line  111)
* mlsd() (ftplib.FTP 方法):              FTP 对象.           (line  141)
* mmap (mmap 中的类):                    mmap --- 内存映射文件支持.
                                                             (line   38)
* mmap (模块):                           mmap --- 内存映射文件支持.
                                                             (line    6)
* MMDF (mailbox 中的类):                 MMDF.               (line    6)
* MMDFMessage (mailbox 中的类):          MMDFMessage.        (line    6)
* Mock (unittest.mock 中的类):           Mock 类.            (line   19)
* mock_add_spec() (unittest.mock.Mock 方法): Mock 类.        (line  206)
* mock_calls (unittest.mock.Mock 属性):  Mock 类.            (line  480)
* mock_open() (在 unittest.mock 模块中): mock_open.          (line    6)
* mod() (在 operator 模块中):            operator --- 标准运算符替代函数.
                                                             (line   99)
* mode (io.FileIO 属性):                 原始文件 I/O.       (line   47)
* mode (ossaudiodev.oss_audio_device 属性): Audio Device Objects.
                                                             (line  234)
* mode (statistics.NormalDist 属性):     NormalDist 对象.    (line   26)
* mode (tarfile.TarInfo 属性):           TarInfo 对象.       (line   51)
* mode() (在 statistics 模块中):         函数细节.           (line  199)
* mode() (在 turtle 模块中):             设置与特殊方法.     (line    6)
* modf() (在 math 模块中):               数论与表示函数.     (line  147)
* modified() (urllib.robotparser.RobotFileParser 方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   42)
* Modify() (msilib.View 方法):           View Objects.       (line   23)
* modify() (select.devpoll 方法):        /dev/poll 轮询对象. (line   45)
* modify() (select.epoll 方法):          边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   83)
* modify() (select.poll 方法):           Poll 对象.          (line   51)
* modify() (selectors.BaseSelector 方法): 类<3>.             (line   85)
* module (pyclbr.Class 属性):            类对象<2>.          (line   13)
* module (pyclbr.Function 属性):         函数对象.           (line   12)
* module – 模块:                         术语对照表.         (line  671)
* module spec:                           查找器和加载器.     (line    6)
* module spec – 模块规格:                术语对照表.         (line  679)
* module; importing:                     import 语句.        (line    6)
* module; namespace:                     标准类型层级结构.   (line  409)
* module; search; path:                  模块搜索路径.       (line    6)
* module; search; path <1>:              linecache --- 随机读写文本行.
                                                             (line   25)
* module; search; path <2>:              sys --- 系统相关的参数和函数.
                                                             (line  901)
* module; search; path <3>:              site —— 站点专属的配置钩子.
                                                             (line   13)
* module; search; path <4>:              嵌入Python<2>.      (line   12)
* module; search; path <5>:              Initializing and finalizing the interpreter.
                                                             (line    8)
* module; search; path <6>:              Process-wide parameters.
                                                             (line  120)
* module; search; path <7>:              Process-wide parameters.
                                                             (line  133)
* ModuleFinder (modulefinder 中的类):    modulefinder --- 查找脚本使用的模块.
                                                             (line   22)
* modulefinder (模块):                   modulefinder --- 查找脚本使用的模块.
                                                             (line    6)
* ModuleInfo (pkgutil 中的类):           pkgutil --- 包扩展工具.
                                                             (line   12)
* ModuleNotFoundError:                   具体异常.           (line   45)
* modules (in module sys):               导入模块<2>.        (line    7)
* modules (in module sys) <1>:           Initializing and finalizing the interpreter.
                                                             (line    8)
* modules (modulefinder.ModuleFinder 属性): modulefinder --- 查找脚本使用的模块.
                                                             (line   41)
* modules() (在 sys 模块中):             sys --- 系统相关的参数和函数.
                                                             (line  893)
* ModuleSpec (importlib.machinery 中的类): importlib machinery -- Importers and path hooks.
                                                             (line  345)
* modules_cleanup() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  772)
* modules_setup() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  768)
* ModuleType (in module types):          模块对象.           (line    8)
* ModuleType (types 中的类):             标准解释器类型.     (line  104)
* module_for_loader() (在 importlib.util 模块中): importlib util -- Utility code for importers.
                                                             (line  133)
* module_from_spec() (在 importlib.util 模块中): importlib util -- Utility code for importers.
                                                             (line  117)
* module_repr() (importlib.abc.Loader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  246)
* modulo:                                二元算术运算符.     (line   30)
* monotonic() (在 time 模块中):          函数<2>.            (line  141)
* monotonic_ns() (在 time 模块中):       函数<2>.            (line  151)
* month (datetime.date 属性):            date 对象.          (line   98)
* month (datetime.datetime 属性):        datetime 对象.      (line  246)
* month() (在 calendar 模块中):          calendar --- 日历相关函数.
                                                             (line  296)
* monthcalendar() (在 calendar 模块中):  calendar --- 日历相关函数.
                                                             (line  286)
* monthdatescalendar() (calendar.Calendar 方法): calendar --- 日历相关函数.
                                                             (line   73)
* monthdays2calendar() (calendar.Calendar 方法): calendar --- 日历相关函数.
                                                             (line   78)
* monthdayscalendar() (calendar.Calendar 方法): calendar --- 日历相关函数.
                                                             (line   83)
* monthrange() (在 calendar 模块中):     calendar --- 日历相关函数.
                                                             (line  282)
* month_abbr() (在 calendar 模块中):     calendar --- 日历相关函数.
                                                             (line  332)
* month_name() (在 calendar 模块中):     calendar --- 日历相关函数.
                                                             (line  327)
* Morsel (http.cookies 中的类):          Morsel 对象.        (line    6)
* most_common() (collections.Counter 方法): Counter 对象.    (line   68)
* mouseinterval() (在 curses 模块中):    函数<3>.            (line  230)
* mousemask() (在 curses 模块中):        函数<3>.            (line  235)
* move() (curses.panel.Panel 方法):      Panel 对象.         (line   32)
* move() (curses.window 方法):           Window 对象.        (line  338)
* move() (mmap.mmap 方法):               mmap --- 内存映射文件支持.
                                                             (line  187)
* move() (tkinter.ttk.Treeview 方法):    ttk Treeview.       (line  220)
* move() (在 shutil 模块中):             目录和文件操作.     (line  252)
* move_file() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  495)
* move_file() (在 distutils.file_util 模块中): distutils file_util --- Single file operations.
                                                             (line   34)
* move_to_end() (collections.OrderedDict 方法): OrderedDict 对象.
                                                             (line   46)
* MozillaCookieJar (http.cookiejar 中的类): FileCookieJar subclasses and co-operation with web browsers.
                                                             (line    9)
* MRO:                                   术语对照表.         (line  684)
* mro() (class 方法):                    特殊属性.           (line   35)
* msg (http.client.HTTPResponse 属性):   HTTPResponse 对象.  (line   40)
* msg (json.JSONDecodeError 属性):       异常<13>.           (line   10)
* msg (re.error 属性):                   模块内容.           (line  293)
* msg (traceback.TracebackException 属性): TracebackException Objects.
                                                             (line   59)
* msg() (telnetlib.Telnet 方法):         Telnet 对象.        (line   71)
* msi:                                   msilib --- Read and write Microsoft Installer files.
                                                             (line    8)
* msilib (模块):                         msilib --- Read and write Microsoft Installer files.
                                                             (line    6)
* msvcrt (模块):                         msvcrt --- 来自 MS VC++ 运行时的有用例程.
                                                             (line    6)
* mtime (gzip.GzipFile 属性):            gzip --- 对 gzip 格式的支持.
                                                             (line  118)
* mtime (tarfile.TarInfo 属性):          TarInfo 对象.       (line   47)
* mtime() (urllib.robotparser.RobotFileParser 方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   37)
* mt_interact() (telnetlib.Telnet 方法): Telnet 对象.        (line  107)
* mul() (在 audioop 模块中):             audioop --- 处理原始音频数据.
                                                             (line  148)
* mul() (在 operator 模块中):            operator --- 标准运算符替代函数.
                                                             (line  104)
* MultiCall (xmlrpc.client 中的类):      MultiCall 对象.     (line    9)
* MULTILINE() (在 re 模块中):            模块内容.           (line   81)
* MultiLoopChildWatcher (asyncio 中的类): 进程监视器.        (line   87)
* multimode() (在 statistics 模块中):    函数细节.           (line  224)
* MultipartConversionError:              email errors 异常和缺陷类.
                                                             (line   36)
* multiplication:                        二元算术运算符.     (line   15)
* multiply() (decimal.Context 方法):     上下文对象.         (line  344)
* multiprocessing (模块):                multiprocessing --- 基于进程的并行.
                                                             (line    6)
* multiprocessing.connection (模块):     监听器及客户端.     (line    6)
* multiprocessing.dummy (模块):          multiprocessing dummy 模块.
                                                             (line    6)
* multiprocessing.Manager() (在 multiprocessing.sharedctypes 模块中): 管理器.
                                                             (line   10)
* multiprocessing.managers (模块):       管理器.             (line   15)
* multiprocessing.pool (模块):           进程池.             (line    6)
* multiprocessing.sharedctypes (模块):   multiprocessing sharedctypes 模块.
                                                             (line    6)
* multiprocessing.shared_memory (模块):  multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line    6)
* mutable – 可变:                        术语对照表.         (line  688)
* mutable object:                        对象、值与类型.     (line   10)
* mutable sequence; loop over:           for 语句<2>.        (line   38)
* mutable; sequence; types:              可变序列类型.       (line    6)
* MutableMapping (collections.abc 中的类): 容器抽象基类.     (line  175)
* MutableMapping (typing 中的类):        类 函数和修饰器.    (line  211)
* MutableSequence (collections.abc 中的类): 容器抽象基类.    (line  155)
* MutableSequence (typing 中的类):       类 函数和修饰器.    (line  219)
* MutableSet (collections.abc 中的类):   容器抽象基类.       (line  170)
* MutableSet (typing 中的类):            类 函数和修饰器.    (line  199)
* mvderwin() (curses.window 方法):       Window 对象.        (line  342)
* mvwin() (curses.window 方法):          Window 对象.        (line  347)
* myrights() (imaplib.IMAP4 方法):       IMAP4 Objects.      (line  157)
* name:                                  标识符和关键字.     (line    6)
* name <1>:                              名称的绑定.         (line    6)
* name <2>:                              标识符（名称）.     (line    6)
* name (codecs.CodecInfo 属性):          codecs --- 编解码器注册和相关基类.
                                                             (line   56)
* name (contextvars.ContextVar 属性):    上下文变量.         (line   21)
* name (doctest.DocTest 属性):           DocTest 对象.       (line   30)
* name (email.headerregistry.BaseHeader 属性): email headerregistry 自定义标头对象.
                                                             (line   37)
* name (hashlib.hash 属性):              哈希算法.           (line   95)
* name (hmac.HMAC 属性):                 hmac --- 基于密钥的消息验证.
                                                             (line   87)
* name (http.cookiejar.Cookie 属性):     Cookie 对象<2>.     (line   28)
* name (importlib.abc.FileLoader 属性):  importlib abc —— 关于导入的抽象基类.
                                                             (line  421)
* name (importlib.machinery.ExtensionFileLoader 属性): importlib machinery -- Importers and path hooks.
                                                             (line  304)
* name (importlib.machinery.ModuleSpec 属性): importlib machinery -- Importers and path hooks.
                                                             (line  361)
* name (importlib.machinery.SourceFileLoader 属性): importlib machinery -- Importers and path hooks.
                                                             (line  217)
* name (importlib.machinery.SourcelessFileLoader 属性): importlib machinery -- Importers and path hooks.
                                                             (line  261)
* name (inspect.Parameter 属性):         Introspecting callables with the Signature object.
                                                             (line  155)
* name (io.FileIO 属性):                 原始文件 I/O.       (line   51)
* name (multiprocessing.Process 属性):   Process 和异常.     (line   56)
* name (multiprocessing.shared_memory.SharedMemory 属性): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   69)
* name (os.DirEntry 属性):               文件和目录.         (line  740)
* name (ossaudiodev.oss_audio_device 属性): Audio Device Objects.
                                                             (line  230)
* name (pyclbr.Class 属性):              类对象<2>.          (line   17)
* name (pyclbr.Function 属性):           函数对象.           (line   16)
* name (tarfile.TarInfo 属性):           TarInfo 对象.       (line   39)
* name (threading.Thread 属性):          线程对象.           (line  113)
* name (xml.dom.Attr 属性):              Attr 对象.          (line    8)
* name (xml.dom.DocumentType 属性):      文档类型对象.       (line   27)
* name (zipfile.Path 属性):              Path 对象.          (line   19)
* name() (在 os 模块中):                 os --- 多种操作系统接口.
                                                             (line   40)
* NAME() (在 token 模块中):              token --- 与Python解析树一起使用的常量.
                                                             (line   38)
* name() (在 unicodedata 模块中):        unicodedata --- Unicode 数据库.
                                                             (line   21)
* name2codepoint() (在 html.entities 模块中): html entities --- HTML 一般实体的定义.
                                                             (line   26)
* name; binding:                         import 语句.        (line    6)
* name; binding <1>:                     import 语句.        (line   43)
* name; binding <2>:                     函数定义.           (line    6)
* name; binding <3>:                     函数定义.           (line    6)
* name; binding <4>:                     类定义.             (line    6)
* name; mangling:                        私有变量.           (line   11)
* name; mangling <1>:                    标识符（名称）.     (line   12)
* Named Shared Memory:                   multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   10)
* named tuple – 具名元组:                术语对照表.         (line  693)
* NamedTemporaryFile() (在 tempfile 模块中): tempfile --- 生成临时文件和目录.
                                                             (line   59)
* NamedTuple (typing 中的类):            类 函数和修饰器.    (line  458)
* namedtuple() (在 collections 模块中):  namedtuple 命名元组的工厂函数.
                                                             (line    9)
* NameError:                             具体异常.           (line   77)
* NameError (built-in exception):        名称的解析.         (line   14)
* namelist() (zipfile.ZipFile 方法):     ZipFile 对象.       (line   91)
* nameprep() (在 encodings.idna 模块中): encodings idna --- 应用程序中的国际化域名.
                                                             (line   38)
* namer (logging.handlers.BaseRotatingHandler 属性): BaseRotatingHandler.
                                                             (line   16)
* namereplace_errors() (在 codecs 模块中): 错误处理方案.     (line  131)
* namespace:                             命名与绑定.         (line    6)
* Namespace (argparse 中的类):           命名空间对象.       (line    6)
* Namespace (multiprocessing.managers 中的类): 管理器.       (line  197)
* namespace – 命名空间:                  术语对照表.         (line  715)
* namespace package – 命名空间包:        术语对照表.         (line  725)
* namespace() (imaplib.IMAP4 方法):      IMAP4 Objects.      (line  162)
* Namespace() (multiprocessing.managers.SyncManager 方法): 管理器.
                                                             (line  153)
* NamespaceErr:                          异常<16>.           (line   53)
* namespaceURI (xml.dom.Node 属性):      节点对象.           (line   63)
* NAMESPACE_DNS() (在 uuid 模块中):      uuid --- UUID objects according to RFC 4122.
                                                             (line  202)
* NAMESPACE_OID() (在 uuid 模块中):      uuid --- UUID objects according to RFC 4122.
                                                             (line  211)
* NAMESPACE_URL() (在 uuid 模块中):      uuid --- UUID objects according to RFC 4122.
                                                             (line  207)
* NAMESPACE_X500() (在 uuid 模块中):     uuid --- UUID objects according to RFC 4122.
                                                             (line  215)
* NaN:                                   内置函数.           (line  490)
* nan() (在 cmath 模块中):               常量<3>.            (line   32)
* nan() (在 math 模块中):                常量<2>.            (line   29)
* nanj() (在 cmath 模块中):              常量<3>.            (line   38)
* NannyNag:                              tabnanny --- 模糊缩进检测.
                                                             (line   33)
* napms() (在 curses 模块中):            函数<3>.            (line  242)
* nargs (optparse.Option 属性):          Option attributes.  (line   42)
* native_id (threading.Thread 属性):     线程对象.           (line  131)
* nbytes (memoryview 属性):              内存视图.           (line  348)
* ncurses_version() (在 curses 模块中):  常量<6>.            (line   22)
* ndiff() (在 difflib 模块中):           difflib --- 计算差异的辅助工具.
                                                             (line  197)
* ndim (memoryview 属性):                内存视图.           (line  410)
* ne (2to3 fixer):                       修复器.             (line  192)
* ne() (在 operator 模块中):             operator --- 标准运算符替代函数.
                                                             (line   19)
* needs_input (bz2.BZ2Decompressor 属性): 增量压缩和解压.    (line   73)
* needs_input (lzma.LZMADecompressor 属性): 在内存中压缩和解压缩数据.
                                                             (line  142)
* neg() (在 operator 模块中):            operator --- 标准运算符替代函数.
                                                             (line  116)
* negation:                              一元算术和位运算.   (line   10)
* nested scope – 嵌套作用域:             术语对照表.         (line  733)
* netmask (ipaddress.IPv4Network 属性):  Network objects.    (line  101)
* netmask (ipaddress.IPv6Network 属性):  Network objects.    (line  315)
* NetmaskValueError:                     Custom Exceptions.  (line   13)
* netrc (netrc 中的类):                  netrc --- netrc 文件处理.
                                                             (line   13)
* netrc (模块):                          netrc --- netrc 文件处理.
                                                             (line    6)
* NetrcParseError:                       netrc --- netrc 文件处理.
                                                             (line   31)
* netscape (http.cookiejar.CookiePolicy 属性): CookiePolicy 对象.
                                                             (line   68)
* network (ipaddress.IPv4Interface 属性): Interface objects. (line   28)
* network (ipaddress.IPv6Interface 属性): Interface objects. (line   76)
* Network News Transfer Protocol:        nntplib --- NNTP protocol client.
                                                             (line    8)
* network_address (ipaddress.IPv4Network 属性): Network objects.
                                                             (line   86)
* network_address (ipaddress.IPv6Network 属性): Network objects.
                                                             (line  309)
* new() (在 hashlib 模块中):             哈希算法.           (line   50)
* new() (在 hmac 模块中):                hmac --- 基于密钥的消息验证.
                                                             (line   12)
* new-style class – 新式类:              术语对照表.         (line  740)
* newer() (在 distutils.dep_util 模块中): distutils dep_util --- Dependency checking.
                                                             (line   10)
* newer_group() (在 distutils.dep_util 模块中): distutils dep_util --- Dependency checking.
                                                             (line   24)
* newer_pairwise() (在 distutils.dep_util 模块中): distutils dep_util --- Dependency checking.
                                                             (line   17)
* newfunc (C 类型):                      Slot Type typedefs. (line   41)
* newgroups() (nntplib.NNTP 方法):       方法<3>.            (line   79)
* NEWLINE token:                         逻辑行.             (line    6)
* NEWLINE token <1>:                     复合语句.           (line   46)
* NEWLINE() (在 token 模块中):           token --- 与Python解析树一起使用的常量.
                                                             (line   44)
* newlines (io.TextIOBase 属性):         文本 I/O<2>.        (line   23)
* newnews() (nntplib.NNTP 方法):         方法<3>.            (line   94)
* newpad() (在 curses 模块中):           函数<3>.            (line  246)
* NewType() (在 typing 模块中):          类 函数和修饰器.    (line  563)
* newwin() (在 curses 模块中):           函数<3>.            (line  260)
* new_alignment() (formatter.writer 方法): The Writer Interface.
                                                             (line   17)
* new_child() (collections.ChainMap 方法): ChainMap 对象.    (line   38)
* new_class() (在 types 模块中):         动态类型创建.       (line    6)
* new_compiler() (在 distutils.ccompiler 模块中): distutils ccompiler --- CCompiler基类.
                                                             (line   47)
* new_event_loop() (asyncio.AbstractEventLoopPolicy 方法): 策略对象.
                                                             (line   27)
* new_event_loop() (在 asyncio 模块中):  事件循环.           (line   53)
* new_font() (formatter.writer 方法):    The Writer Interface.
                                                             (line   25)
* new_margin() (formatter.writer 方法):  The Writer Interface.
                                                             (line   35)
* new_module() (在 imp 模块中):          imp --- Access the import internals.
                                                             (line  124)
* new_panel() (在 curses.panel 模块中):  函数<4>.            (line   12)
* new_spacing() (formatter.writer 方法): The Writer Interface.
                                                             (line   42)
* new_styles() (formatter.writer 方法):  The Writer Interface.
                                                             (line   46)
* next (2to3 fixer):                     修复器.             (line  196)
* next (pdb command):                    调试器命令.         (line  137)
* next() (nntplib.NNTP 方法):            方法<3>.            (line  232)
* next() (tarfile.TarFile 方法):         TarFile 对象.       (line  112)
* next() (tkinter.ttk.Treeview 方法):    ttk Treeview.       (line  231)
* next() (內置函数):                     内置函数.           (line  820)
* nextfile() (在 fileinput 模块中):      fileinput --- 迭代来自多个输入流的行.
                                                             (line   96)
* nextkey() (dbm.gnu.gdbm 方法):         dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line   77)
* nextSibling (xml.dom.Node 属性):       节点对象.           (line   35)
* next_minus() (decimal.Context 方法):   上下文对象.         (line  348)
* next_minus() (decimal.Decimal 方法):   Decimal 对象.       (line  348)
* next_plus() (decimal.Context 方法):    上下文对象.         (line  352)
* next_plus() (decimal.Decimal 方法):    Decimal 对象.       (line  353)
* next_toward() (decimal.Context 方法):  上下文对象.         (line  356)
* next_toward() (decimal.Decimal 方法):  Decimal 对象.       (line  358)
* ngettext() (gettext.GNUTranslations 方法): GNUTranslations 类.
                                                             (line   39)
* ngettext() (gettext.NullTranslations 方法): NullTranslations 类.
                                                             (line   34)
* ngettext() (在 gettext 模块中):        GNU gettext API.    (line   46)
* nice() (在 os 模块中):                 进程管理.           (line  272)
* nis (模块):                            nis --- Sun 的 NIS 黄页 接口.
                                                             (line    6)
* nl() (在 curses 模块中):               函数<3>.            (line  269)
* NL() (在 token 模块中):                token --- 与Python解析树一起使用的常量.
                                                             (line  261)
* nlargest() (在 heapq 模块中):          heapq --- 堆队列算法.
                                                             (line   86)
* nlst() (ftplib.FTP 方法):              FTP 对象.           (line  152)
* nl_langinfo() (在 locale 模块中):      locale --- 国际化服务.
                                                             (line  154)
* NNTP (nntplib 中的类):                 nntplib --- NNTP protocol client.
                                                             (line   54)
* NNTP; protocol:                        nntplib --- NNTP protocol client.
                                                             (line    8)
* NNTPDataError:                         nntplib --- NNTP protocol client.
                                                             (line  151)
* NNTPError:                             nntplib --- NNTP protocol client.
                                                             (line  121)
* nntplib (模块):                        nntplib --- NNTP protocol client.
                                                             (line    6)
* NNTPPermanentError:                    nntplib --- NNTP protocol client.
                                                             (line  141)
* NNTPProtocolError:                     nntplib --- NNTP protocol client.
                                                             (line  146)
* NNTPReplyError:                        nntplib --- NNTP protocol client.
                                                             (line  132)
* NNTPTemporaryError:                    nntplib --- NNTP protocol client.
                                                             (line  136)
* nntp_implementation (nntplib.NNTP 属性): Attributes.       (line   14)
* NNTP_SSL (nntplib 中的类):             nntplib --- NNTP protocol client.
                                                             (line   92)
* nntp_version (nntplib.NNTP 属性):      Attributes.         (line    6)
* nocbreak() (在 curses 模块中):         函数<3>.            (line  274)
* NoDataAllowedErr:                      异常<16>.           (line   68)
* node() (在 platform 模块中):           跨平台.             (line   37)
* nodelay() (curses.window 方法):        Window 对象.        (line  351)
* nodeName (xml.dom.Node 属性):          节点对象.           (line   68)
* NodeTransformer (ast 中的类):          ast 中的辅助函数.   (line  150)
* nodeType (xml.dom.Node 属性):          节点对象.           (line    8)
* nodeValue (xml.dom.Node 属性):         节点对象.           (line   75)
* NodeVisitor (ast 中的类):              ast 中的辅助函数.   (line  115)
* noecho() (在 curses 模块中):           函数<3>.            (line  278)
* NOEXPR() (在 locale 模块中):           locale --- 国际化服务.
                                                             (line  233)
* NoModificationAllowedErr:              异常<16>.           (line   72)
* nonblock() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line   72)
* NonCallableMagicMock (unittest.mock 中的类): Magic Mock.   (line   21)
* NonCallableMock (unittest.mock 中的类): Mock 类.           (line  538)
* None (Built-in object):                逻辑值检测.         (line   13)
* None (內置变量):                       内置常量.           (line   18)
* nonl() (在 curses 模块中):             函数<3>.            (line  282)
* nonzero (2to3 fixer):                  修复器.             (line  201)
* noop() (imaplib.IMAP4 方法):           IMAP4 Objects.      (line  166)
* noop() (poplib.POP3 方法):             POP3 对象.          (line   71)
* NoOptionError:                         异常<5>.            (line   28)
* NOP (opcode):                          Python字节码说明.   (line   52)
* noqiflush() (在 curses 模块中):        函数<3>.            (line  289)
* noraw() (在 curses 模块中):            函数<3>.            (line  296)
* NoReturn() (在 typing 模块中):         类 函数和修饰器.    (line  717)
* NormalDist (statistics 中的类):        NormalDist 对象.    (line   11)
* normalize() (decimal.Context 方法):    上下文对象.         (line  360)
* normalize() (decimal.Decimal 方法):    Decimal 对象.       (line  364)
* normalize() (xml.dom.Node 方法):       节点对象.           (line  122)
* normalize() (在 locale 模块中):        locale --- 国际化服务.
                                                             (line  338)
* normalize() (在 unicodedata 模块中):   unicodedata --- Unicode 数据库.
                                                             (line   69)
* NORMALIZE_WHITESPACE() (在 doctest 模块中): Option Flags.  (line   39)
* normalvariate() (在 random 模块中):    实值分布.           (line   61)
* NORMAL_PRIORITY_CLASS() (在 subprocess 模块中): Windows 常数.
                                                             (line   73)
* normcase() (在 os.path 模块中):        os path --- 常用路径操作.
                                                             (line  240)
* normpath() (在 os.path 模块中):        os path --- 常用路径操作.
                                                             (line  247)
* NoSectionError:                        异常<5>.            (line   10)
* NoSuchMailboxError:                    异常<14>.           (line   12)
* NotADirectoryError:                    OS 异常.            (line   78)
* notation:                              标注.               (line    6)
* notationDecl() (xml.sax.handler.DTDHandler 方法): DTDHandler 对象.
                                                             (line    8)
* NotationDeclHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  224)
* notations (xml.dom.DocumentType 属性): 文档类型对象.       (line   37)
* NotConnected:                          http client --- HTTP 协议客户端.
                                                             (line  118)
* NoteBook (tkinter.tix 中的类):         Manager Widgets.    (line   22)
* Notebook (tkinter.ttk 中的类):         ttk Notebook.       (line    6)
* NotEmptyError:                         异常<14>.           (line   18)
* NOTEQUAL() (在 token 模块中):          token --- 与Python解析树一起使用的常量.
                                                             (line  134)
* NotFoundErr:                           异常<16>.           (line   58)
* notify() (asyncio.Condition 方法):     Condition.          (line   49)
* notify() (threading.Condition 方法):   条件对象.           (line  124)
* notify_all() (asyncio.Condition 方法): Condition.          (line   61)
* notify_all() (threading.Condition 方法): 条件对象.         (line  140)
* notimeout() (curses.window 方法):      Window 对象.        (line  355)
* NotImplemented (內置变量):             内置常量.           (line   24)
* NotImplementedError:                   具体异常.           (line   82)
* NotStandaloneHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  269)
* NotSupportedErr:                       异常<16>.           (line   64)
* NotSupportedError:                     异常<4>.            (line   34)
* not_() (在 operator 模块中):           operator --- 标准运算符替代函数.
                                                             (line   40)
* noutrefresh() (curses.window 方法):    Window 对象.        (line  362)
* now() (datetime.datetime 类方法):      datetime 对象.      (line   57)
* no_proxy:                              urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  252)
* no_tracing() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  642)
* no_type_check() (在 typing 模块中):    类 函数和修饰器.    (line  657)
* no_type_check_decorator() (在 typing 模块中): 类 函数和修饰器.
                                                             (line  667)
* npgettext() (gettext.GNUTranslations 方法): GNUTranslations 类.
                                                             (line   67)
* npgettext() (gettext.NullTranslations 方法): NullTranslations 类.
                                                             (line   46)
* npgettext() (在 gettext 模块中):       GNU gettext API.    (line   66)
* NSIG() (在 signal 模块中):             模块内容<5>.        (line  158)
* nsmallest() (在 heapq 模块中):         heapq --- 堆队列算法.
                                                             (line   93)
* NTEventLogHandler (logging.handlers 中的类): NTEventLogHandler.
                                                             (line   10)
* ntohl() (在 socket 模块中):            其他功能<2>.        (line  151)
* ntohs() (在 socket 模块中):            其他功能<2>.        (line  156)
* ntransfercmd() (ftplib.FTP 方法):      FTP 对象.           (line  135)
* NT_OFFSET() (在 token 模块中):         token --- 与Python解析树一起使用的常量.
                                                             (line  252)
* null; operation:                       pass 语句<2>.       (line    6)
* null; operation <1>:                   pass 语句<2>.       (line    6)
* nullcontext() (在 contextlib 模块中):  工具.               (line  131)
* NullFormatter (formatter 中的类):      Formatter Implementations.
                                                             (line   10)
* NullHandler (logging 中的类):          NullHandler.        (line   11)
* NullImporter (imp 中的类):             imp --- Access the import internals.
                                                             (line  336)
* NullTranslations (gettext 中的类):     NullTranslations 类.
                                                             (line   11)
* NullWriter (formatter 中的类):         Writer Implementations.
                                                             (line   10)
* number:                                数字字面值.         (line    6)
* Number (numbers 中的类):               numbers --- 数字的抽象基类.
                                                             (line   13)
* NUMBER() (在 token 模块中):            token --- 与Python解析树一起使用的常量.
                                                             (line   40)
* numbers (模块):                        numbers --- 数字的抽象基类.
                                                             (line    6)
* number_class() (decimal.Context 方法): 上下文对象.         (line  364)
* number_class() (decimal.Decimal 方法): Decimal 对象.       (line  371)
* numerator (fractions.Fraction 属性):   fractions --- 分数. (line   79)
* numerator (numbers.Rational 属性):     数字的层次.         (line   45)
* numeric literal:                       数字字面值.         (line    6)
* numeric() (在 unicodedata 模块中):     unicodedata --- Unicode 数据库.
                                                             (line   36)
* numeric; conversions:                  数字类型 --- int float complex.
                                                             (line   92)
* numeric; literals:                     数字类型 --- int float complex.
                                                             (line   14)
* Numerical Python:                      内置函数.           (line 1258)
* numinput() (在 turtle 模块中):         输入方法.           (line   21)
* numliterals (2to3 fixer):              修复器.             (line  205)
* num_addresses (ipaddress.IPv4Network 属性): Network objects.
                                                             (line  128)
* num_addresses (ipaddress.IPv6Network 属性): Network objects.
                                                             (line  327)
* num_tickets (ssl.SSLContext 属性):     SSL 上下文.         (line  498)
* N_TOKENS() (在 token 模块中):          token --- 与Python解析树一起使用的常量.
                                                             (line  250)
* n_waiting (threading.Barrier 属性):    栅栏对象.           (line   83)
* obj (memoryview 属性):                 内存视图.           (line  337)
* object:                                对象、值与类型.     (line    6)
* object (UnicodeError 属性):            具体异常.           (line  311)
* object (內置类):                       内置函数.           (line  826)
* object – 对象:                         术语对照表.         (line  747)
* object.__slots__ (內置变量):           __slots__.          (line   13)
* object; code:                          标准类型层级结构.   (line  490)
* object; code <1>:                      方法.               (line   36)
* object; code <2>:                      marshal --- 内部 Python 对象序列化.
                                                             (line   24)
* object; code <3>:                      Cell 对象.          (line   46)
* object; deallocation:                  终结和内存释放.     (line    6)
* object; finalization:                  终结和内存释放.     (line    6)
* object; numeric:                       比较运算<2>.        (line   41)
* objects; comparing:                    比较运算<2>.        (line   41)
* object_filenames() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  464)
* objobjargproc (C 类型):                Slot Type typedefs. (line  122)
* objobjproc (C 类型):                   Slot Type typedefs. (line  120)
* obufcount() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line  214)
* obuffree() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line  219)
* oct() (內置函数):                      内置函数.           (line  834)
* octal literal:                         数字字面值.         (line    6)
* octal; literals:                       数字类型 --- int float complex.
                                                             (line   14)
* octdigits() (在 string 模块中):        字符串常量.         (line   31)
* offset (SyntaxError 属性):             具体异常.           (line  225)
* offset (traceback.TracebackException 属性): TracebackException Objects.
                                                             (line   54)
* offset (xml.parsers.expat.ExpatError 属性): ExpatError 异常.
                                                             (line   28)
* OK() (在 curses 模块中):               常量<6>.            (line   13)
* old_value (contextvars.contextvars.Token.Token 属性): 上下文变量.
                                                             (line   75)
* OleDLL (ctypes 中的类):                加载动态链接库.     (line   28)
* onclick() (在 turtle 模块中):          使用屏幕事件.       (line   51)
* ondrag() (在 turtle 模块中):           使用事件.           (line   52)
* onecmd() (cmd.Cmd 方法):               Cmd 对象.           (line   44)
* onkey() (在 turtle 模块中):            使用屏幕事件.       (line   11)
* onkeypress() (在 turtle 模块中):       使用屏幕事件.       (line   32)
* onkeyrelease() (在 turtle 模块中):     使用屏幕事件.       (line   11)
* onrelease() (在 turtle 模块中):        使用事件.           (line   27)
* onscreenclick() (在 turtle 模块中):    使用屏幕事件.       (line   51)
* ontimer() (在 turtle 模块中):          使用屏幕事件.       (line   78)
* OP() (在 token 模块中):                token --- 与Python解析树一起使用的常量.
                                                             (line  238)
* open() (distutils.text_file.TextFile 方法): distutils text_file --- The TextFile class.
                                                             (line   91)
* open() (imaplib.IMAP4 方法):           IMAP4 Objects.      (line  170)
* open() (pathlib.Path 方法):            方法<2>.            (line  224)
* open() (pipes.Template 方法):          模板对象.           (line   40)
* open() (tarfile.TarFile 类方法):       TarFile 对象.       (line   80)
* open() (telnetlib.Telnet 方法):        Telnet 对象.        (line   60)
* open() (urllib.request.OpenerDirector 方法): OpenerDirector 对象.
                                                             (line   43)
* open() (urllib.request.URLopener 方法): 已停用的接口.      (line   92)
* open() (webbrowser.controller 方法):   浏览器控制器对象.   (line    8)
* open() (zipfile.Path 方法):            Path 对象.          (line   23)
* open() (zipfile.ZipFile 方法):         ZipFile 对象.       (line   95)
* open() (內置函数):                     内置函数.           (line  857)
* open() (在 aifc 模块中):               aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   26)
* open() (在 bz2 模块中):                文件压缩和解压.     (line    6)
* open() (在 codecs 模块中):             codecs --- 编解码器注册和相关基类.
                                                             (line  141)
* open() (在 dbm 模块中):                dbm --- Unix "数据库" 接口.
                                                             (line   31)
* open() (在 dbm.dumb 模块中):           dbm dumb --- 便携式 DBM 实现.
                                                             (line   25)
* open() (在 dbm.gnu 模块中):            dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line   24)
* open() (在 dbm.ndbm 模块中):           dbm ndbm --- 基于 ndbm 的接口.
                                                             (line   26)
* open() (在 gzip 模块中):               gzip --- 对 gzip 格式的支持.
                                                             (line   25)
* open() (在 io 模块中):                 高阶模块接口.       (line   12)
* open() (在 lzma 模块中):               读写压缩文件.       (line    6)
* open() (在 os 模块中):                 文件描述符操作.     (line  232)
* open() (在 ossaudiodev 模块中):        ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line   39)
* open() (在 shelve 模块中):             shelve --- Python 对象持久化.
                                                             (line   15)
* open() (在 sunau 模块中):              sunau --- 读写 Sun AU 文件.
                                                             (line   45)
* open() (在 tarfile 模块中):            tarfile --- 读写tar归档文件.
                                                             (line   31)
* open() (在 tokenize 模块中):           对输入进行解析标记. (line   99)
* open() (在 wave 模块中):               wave --- 读写WAV格式文件.
                                                             (line   15)
* open() (在 webbrowser 模块中):         webbrowser --- 方便的Web浏览器控制器.
                                                             (line   40)
* OpenDatabase() (在 msilib 模块中):     msilib --- Read and write Microsoft Installer files.
                                                             (line   45)
* OpenerDirector (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  220)
* openfp() (在 sunau 模块中):            sunau --- 读写 Sun AU 文件.
                                                             (line   63)
* openfp() (在 wave 模块中):             wave --- 读写WAV格式文件.
                                                             (line   43)
* OpenKey() (在 winreg 模块中):          函数<11>.           (line  270)
* OpenKeyEx() (在 winreg 模块中):        函数<11>.           (line  270)
* openlog() (在 syslog 模块中):          Unix syslog 库例程. (line   33)
* openmixer() (在 ossaudiodev 模块中):   ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line   67)
* openpty() (在 os 模块中):              文件描述符操作.     (line  316)
* openpty() (在 pty 模块中):             pty --- 伪终端工具. (line   25)
* OpenSSL; (use in module hashlib):      哈希算法.           (line   18)
* OpenSSL; (use in module ssl):          ssl --- 套接字对象的TLS/SSL封装.
                                                             (line    8)
* OPENSSL_VERSION() (在 ssl 模块中):     常量<9>.            (line  399)
* OPENSSL_VERSION_INFO() (在 ssl 模块中): 常量<9>.           (line  408)
* OPENSSL_VERSION_NUMBER() (在 ssl 模块中): 常量<9>.         (line  417)
* OpenView() (msilib.Database 方法):     Database Objects.   (line    6)
* open_binary() (在 importlib.resources 模块中): importlib resources -- 资源.
                                                             (line   49)
* open_code() (在 io 模块中):            高阶模块接口.       (line   20)
* open_connection() (在 asyncio 模块中): 流.                 (line   40)
* open_new() (webbrowser.controller 方法): 浏览器控制器对象. (line   14)
* open_new() (在 webbrowser 模块中):     webbrowser --- 方便的Web浏览器控制器.
                                                             (line   54)
* open_new_tab() (webbrowser.controller 方法): 浏览器控制器对象.
                                                             (line   19)
* open_new_tab() (在 webbrowser 模块中): webbrowser --- 方便的Web浏览器控制器.
                                                             (line   59)
* open_osfhandle() (在 msvcrt 模块中):   文件操作.           (line   40)
* open_resource() (importlib.abc.ResourceReader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  280)
* open_text() (在 importlib.resources 模块中): importlib resources -- 资源.
                                                             (line   60)
* open_unix_connection() (在 asyncio 模块中): 流.            (line   90)
* open_unknown() (urllib.request.URLopener 方法): 已停用的接口.
                                                             (line  103)
* open_urlresource() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  713)
* OperationalError:                      异常<4>.            (line   28)
* operations on; dictionary; type:       映射类型 --- dict.  (line    6)
* operations on; integer; types:         整数类型的按位运算. (line    6)
* operations on; list; type:             可变序列类型.       (line   14)
* operations on; mapping; types:         映射类型 --- dict.  (line    6)
* operations on; numeric; types:         数字类型 --- int float complex.
                                                             (line   83)
* operations on; sequence; types:        通用序列操作.       (line   17)
* operations on; sequence; types <1>:    可变序列类型.       (line   14)
* operator (2to3 fixer):                 修复器.             (line  209)
* operator (模块):                       operator --- 标准运算符替代函数.
                                                             (line    6)
* operator; + (plus):                    一元算术和位运算.   (line   12)
* operator; + (plus) <1>:                二元算术运算符.     (line   47)
* operator; + (plus) <2>:                数字类型 --- int float complex.
                                                             (line   20)
* operator; - (minus):                   一元算术和位运算.   (line   10)
* operator; - (minus) <1>:               二元算术运算符.     (line   51)
* operator; - (minus) <2>:               数字类型 --- int float complex.
                                                             (line   20)
* operator; comparison:                  比较运算<2>.        (line    6)
* operator; overloading:                 特殊方法名称.       (line    6)
* operator; precedence:                  运算符优先级.       (line    6)
* operators:                             运算符.             (line    6)
* opmap() (在 dis 模块中):               操作码集合.         (line   12)
* opname() (在 dis 模块中):              操作码集合.         (line    8)
* optimize() (在 pickletools 模块中):    编程接口<2>.        (line   26)
* OPTIMIZED_BYTECODE_SUFFIXES() (在 importlib.machinery 模块中): importlib machinery -- Importers and path hooks.
                                                             (line   29)
* optim_args_from_interpreter_flags() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  396)
* Optional() (在 typing 模块中):         类 函数和修饰器.    (line  762)
* OptionGroup (optparse 中的类):         Grouping Options.   (line   12)
* OptionMenu (tkinter.tix 中的类):       Basic Widgets.      (line   48)
* OptionParser (optparse 中的类):        创建解析器.         (line    9)
* options (doctest.Example 属性):        Example Objects.    (line   53)
* Options (ssl 中的类):                  常量<9>.            (line  302)
* options (ssl.SSLContext 属性):         SSL 上下文.         (line  508)
* options() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line   87)
* optionxform() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line  243)
* optparse (模块):                       optparse --- 解析器的命令行选项.
                                                             (line    6)
* OP_ALL() (在 ssl 模块中):              常量<9>.            (line  187)
* OP_CIPHER_SERVER_PREFERENCE() (在 ssl 模块中): 常量<9>.    (line  264)
* OP_ENABLE_MIDDLEBOX_COMPAT() (在 ssl 模块中): 常量<9>.     (line  285)
* OP_IGNORE_UNEXPECTED_EOF() (在 ssl 模块中): 常量<9>.       (line  312)
* OP_NO_COMPRESSION() (在 ssl 模块中):   常量<9>.            (line  294)
* OP_NO_RENEGOTIATION() (在 ssl 模块中): 常量<9>.            (line  255)
* OP_NO_SSLv2() (在 ssl 模块中):         常量<9>.            (line  194)
* OP_NO_SSLv3() (在 ssl 模块中):         常量<9>.            (line  203)
* OP_NO_TICKET() (在 ssl 模块中):        常量<9>.            (line  306)
* OP_NO_TLSv1() (在 ssl 模块中):         常量<9>.            (line  212)
* OP_NO_TLSv1_1() (在 ssl 模块中):       常量<9>.            (line  223)
* OP_NO_TLSv1_2() (在 ssl 模块中):       常量<9>.            (line  233)
* OP_NO_TLSv1_3() (在 ssl 模块中):       常量<9>.            (line  243)
* OP_SINGLE_DH_USE() (在 ssl 模块中):    常量<9>.            (line  271)
* OP_SINGLE_ECDH_USE() (在 ssl 模块中):  常量<9>.            (line  278)
* ord() (內置函数):                      内置函数.           (line 1060)
* OrderedDict (collections 中的类):      OrderedDict 对象.   (line   33)
* OrderedDict (typing 中的类):           类 函数和修饰器.    (line  346)
* ordered_attributes (xml.parsers.expat.xmlparser 属性): XMLParser对象<2>.
                                                             (line   89)
* origin (importlib.machinery.ModuleSpec 属性): importlib machinery -- Importers and path hooks.
                                                             (line  374)
* origin_req_host (urllib.request.Request 属性): Request 对象.
                                                             (line   27)
* origin_server (wsgiref.handlers.BaseHandler 属性): wsgiref handlers -- server/gateway base classes.
                                                             (line  287)
* or_() (在 operator 模块中):            operator --- 标准运算符替代函数.
                                                             (line  121)
* os (模块):                             os --- 多种操作系统接口.
                                                             (line    6)
* os.path (模块):                        os path --- 常用路径操作.
                                                             (line    6)
* OSError:                               具体异常.           (line   96)
* ossaudiodev (模块):                    ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line    6)
* OSSAudioError:                         ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line   26)
* os_environ (wsgiref.handlers.BaseHandler 属性): wsgiref handlers -- server/gateway base classes.
                                                             (line  165)
* output:                                表达式语句.         (line   15)
* output (subprocess.CalledProcessError 属性): 使用 subprocess 模块.
                                                             (line  185)
* output (subprocess.TimeoutExpired 属性): 使用 subprocess 模块.
                                                             (line  152)
* output (unittest.TestCase 属性):       测试用例.           (line  431)
* output() (http.cookies.BaseCookie 方法): Cookie 对象.      (line   24)
* output() (http.cookies.Morsel 方法):   Morsel 对象.        (line   72)
* OutputChecker (doctest 中的类):        OutputChecker 对象. (line    6)
* OutputString() (http.cookies.Morsel 方法): Morsel 对象.    (line   87)
* output_charset (email.charset.Charset 属性): email charset 表示字符集.
                                                             (line   66)
* output_charset() (gettext.NullTranslations 方法): NullTranslations 类.
                                                             (line   75)
* output_codec (email.charset.Charset 属性): email charset 表示字符集.
                                                             (line   77)
* output_difference() (doctest.OutputChecker 方法): OutputChecker 对象.
                                                             (line   27)
* over() (nntplib.NNTP 方法):            方法<3>.            (line  166)
* Overflow (decimal 中的类):             信号.               (line   60)
* OverflowError:                         具体异常.           (line  151)
* OverflowError (built-in exception):    整数型对象.         (line   97)
* OverflowError (built-in exception) <1>: 整数型对象.        (line  131)
* OverflowError (built-in exception) <2>: 整数型对象.        (line  167)
* OverflowError (built-in exception) <3>: 整数型对象.        (line  177)
* OverflowError (built-in exception) <4>: 整数型对象.        (line  188)
* OverflowError (built-in exception) <5>: 整数型对象.        (line  200)
* overlap() (statistics.NormalDist 方法): NormalDist 对象.   (line   80)
* overlaps() (ipaddress.IPv4Network 方法): Network objects.  (line  155)
* overlaps() (ipaddress.IPv6Network 方法): Network objects.  (line  340)
* overlay() (curses.window 方法):        Window 对象.        (line  367)
* overload() (在 typing 模块中):         类 函数和修饰器.    (line  610)
* overwrite() (curses.window 方法):      Window 对象.        (line  378)
* owner() (pathlib.Path 方法):           方法<2>.            (line  235)
* O_APPEND() (在 os 模块中):             文件描述符操作.     (line  269)
* O_ASYNC() (在 os 模块中):              文件描述符操作.     (line  301)
* O_BINARY() (在 os 模块中):             文件描述符操作.     (line  291)
* O_CLOEXEC() (在 os 模块中):            文件描述符操作.     (line  279)
* O_CREAT() (在 os 模块中):              文件描述符操作.     (line  269)
* O_DIRECT() (在 os 模块中):             文件描述符操作.     (line  301)
* O_DIRECTORY() (在 os 模块中):          文件描述符操作.     (line  301)
* O_DSYNC() (在 os 模块中):              文件描述符操作.     (line  279)
* O_EXCL() (在 os 模块中):               文件描述符操作.     (line  269)
* O_EXLOCK() (在 os 模块中):             文件描述符操作.     (line  301)
* O_NDELAY() (在 os 模块中):             文件描述符操作.     (line  279)
* O_NOATIME() (在 os 模块中):            文件描述符操作.     (line  301)
* O_NOCTTY() (在 os 模块中):             文件描述符操作.     (line  279)
* O_NOFOLLOW() (在 os 模块中):           文件描述符操作.     (line  301)
* O_NOINHERIT() (在 os 模块中):          文件描述符操作.     (line  291)
* O_NONBLOCK() (在 os 模块中):           文件描述符操作.     (line  279)
* O_PATH() (在 os 模块中):               文件描述符操作.     (line  301)
* O_RANDOM() (在 os 模块中):             文件描述符操作.     (line  291)
* O_RDONLY() (在 os 模块中):             文件描述符操作.     (line  269)
* O_RDWR() (在 os 模块中):               文件描述符操作.     (line  269)
* O_RSYNC() (在 os 模块中):              文件描述符操作.     (line  279)
* O_SEQUENTIAL() (在 os 模块中):         文件描述符操作.     (line  291)
* O_SHLOCK() (在 os 模块中):             文件描述符操作.     (line  301)
* O_SHORT_LIVED() (在 os 模块中):        文件描述符操作.     (line  291)
* O_SYNC() (在 os 模块中):               文件描述符操作.     (line  279)
* O_TEMPORARY() (在 os 模块中):          文件描述符操作.     (line  291)
* O_TEXT() (在 os 模块中):               文件描述符操作.     (line  291)
* O_TMPFILE() (在 os 模块中):            文件描述符操作.     (line  301)
* O_TRUNC() (在 os 模块中):              文件描述符操作.     (line  269)
* O_WRONLY() (在 os 模块中):             文件描述符操作.     (line  269)
* p (pdb command):                       调试器命令.         (line  193)
* pack() (mailbox.MH 方法):              MH.                 (line   58)
* pack() (struct.Struct 方法):           类<2>.              (line   21)
* pack() (在 struct 模块中):             函数和异常.         (line   12)
* package:                               包<2>.              (line    6)
* package <1>:                           site —— 站点专属的配置钩子.
                                                             (line   50)
* package – 包:                          术语对照表.         (line  752)
* package variable; __all__:             导入模块<2>.        (line    7)
* Package() (在 importlib.resources 模块中): importlib resources -- 资源.
                                                             (line   33)
* package; namespace:                    命名空间包.         (line    6)
* package; portion:                      命名空间包.         (line    6)
* package; regular:                      常规包.             (line    6)
* packed (ipaddress.IPv4Address 属性):   地址对象.           (line   66)
* packed (ipaddress.IPv6Address 属性):   地址对象.           (line  165)
* Packer (xdrlib 中的类):                xdrlib --- 编码与解码 XDR 数据.
                                                             (line   17)
* packing (widgets):                     The Packer.         (line    6)
* packing; binary; data:                 struct --- 将字节串解读为打包的二进制数据.
                                                             (line    8)
* pack_array() (xdrlib.Packer 方法):     Packer 对象.        (line   75)
* pack_bytes() (xdrlib.Packer 方法):     Packer 对象.        (line   49)
* pack_double() (xdrlib.Packer 方法):    Packer 对象.        (line   25)
* pack_farray() (xdrlib.Packer 方法):    Packer 对象.        (line   68)
* pack_float() (xdrlib.Packer 方法):     Packer 对象.        (line   21)
* pack_fopaque() (xdrlib.Packer 方法):   Packer 对象.        (line   36)
* pack_fstring() (xdrlib.Packer 方法):   Packer 对象.        (line   31)
* pack_into() (struct.Struct 方法):      类<2>.              (line   26)
* pack_into() (在 struct 模块中):        函数和异常.         (line   17)
* pack_list() (xdrlib.Packer 方法):      Packer 对象.        (line   55)
* pack_opaque() (xdrlib.Packer 方法):    Packer 对象.        (line   45)
* pack_string() (xdrlib.Packer 方法):    Packer 对象.        (line   40)
* PAGER:                                 pydoc --- 文档生成器和在线帮助系统.
                                                             (line   38)
* pair_content() (在 curses 模块中):     函数<3>.            (line  300)
* pair_number() (在 curses 模块中):      函数<3>.            (line  305)
* PanedWindow (tkinter.tix 中的类):      Manager Widgets.    (line    6)
* Parameter (inspect 中的类):            Introspecting callables with the Signature object.
                                                             (line  141)
* parameter – 形参:                      术语对照表.         (line  760)
* parameter; call semantics:             调用.               (line   24)
* parameter; difference from argument:   如何将可选参数或关键字参数从一个函数传递到另一个函数？.
                                                             (line   15)
* parameter; function definition:        with 语句.          (line   91)
* ParameterizedMIMEHeader (email.headerregistry 中的类): email headerregistry 自定义标头对象.
                                                             (line  207)
* parameters (inspect.Signature 属性):   Introspecting callables with the Signature object.
                                                             (line   78)
* params (email.headerregistry.ParameterizedMIMEHeader 属性): email headerregistry 自定义标头对象.
                                                             (line  213)
* pardir() (在 os 模块中):               其他系统信息.       (line   72)
* paren (2to3 fixer):                    修复器.             (line  240)
* parent (importlib.machinery.ModuleSpec 属性): importlib machinery -- Importers and path hooks.
                                                             (line  402)
* parent (pyclbr.Class 属性):            类对象<2>.          (line   25)
* parent (pyclbr.Function 属性):         函数对象.           (line   24)
* parent (urllib.request.BaseHandler 属性): BaseHandler 对象.
                                                             (line   23)
* parent() (tkinter.ttk.Treeview 方法):  ttk Treeview.       (line  236)
* parenthesized form:                    带圆括号的形式.     (line    6)
* parentNode (xml.dom.Node 属性):        节点对象.           (line   16)
* parents (collections.ChainMap 属性):   ChainMap 对象.      (line   48)
* parent_process() (在 multiprocessing 模块中): 杂项<3>.     (line   32)
* paretovariate() (在 random 模块中):    实值分布.           (line   71)
* parse() (doctest.DocTestParser 方法):  DocTestParser 对象. (line   29)
* parse() (email.parser.BytesParser 方法): Parser API.       (line   29)
* parse() (email.parser.Parser 方法):    Parser API.         (line   75)
* parse() (string.Formatter 方法):       自定义字符串格式化. (line   32)
* parse() (urllib.robotparser.RobotFileParser 方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   28)
* parse() (xml.etree.ElementTree.ElementTree 方法): ElementTree 对象.
                                                             (line   51)
* Parse() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line    8)
* parse() (xml.sax.xmlreader.XMLReader 方法): XMLReader 对象.
                                                             (line    8)
* parse() (在 ast 模块中):               ast 中的辅助函数.   (line    8)
* parse() (在 cgi 模块中):               函数<8>.            (line    9)
* parse() (在 xml.dom.minidom 模块中):   xml dom minidom --- 最小化的 DOM 实现.
                                                             (line   33)
* parse() (在 xml.dom.pulldom 模块中):   xml dom pulldom --- 支持构建部分 DOM 树.
                                                             (line   77)
* parse() (在 xml.etree.ElementTree 模块中): 函数<6>.        (line  138)
* parse() (在 xml.sax 模块中):           xml sax --- 支持 SAX2 解析器.
                                                             (line   34)
* parseaddr() (在 email.utils 模块中):   email utils 其他工具.
                                                             (line   48)
* parsebytes() (email.parser.BytesParser 方法): Parser API.  (line   46)
* parsedate() (在 email.utils 模块中):   email utils 其他工具.
                                                             (line   80)
* parsedate_to_datetime() (在 email.utils 模块中): email utils 其他工具.
                                                             (line   99)
* parsedate_tz() (在 email.utils 模块中): email utils 其他工具.
                                                             (line   90)
* ParseError (xml.etree.ElementTree 中的类): 异常<15>.       (line    6)
* ParseFile() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line   14)
* ParseFlags() (在 imaplib 模块中):      imaplib --- IMAP4 协议客户端.
                                                             (line  113)
* parser:                                词法分析.           (line    6)
* Parser (email.parser 中的类):          Parser API.         (line   67)
* parser (模块):                         parser --- 访问 Python 解析树.
                                                             (line    6)
* ParserCreate() (在 xml.parsers.expat 模块中): xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line   41)
* ParserError:                           异常和错误处理.     (line   11)
* ParseResult (urllib.parse 中的类):     结构化解析结果.     (line   48)
* ParseResultBytes (urllib.parse 中的类): 结构化解析结果.    (line   72)
* parsestr() (email.parser.Parser 方法): Parser API.         (line   84)
* parseString() (在 xml.dom.minidom 模块中): xml dom minidom --- 最小化的 DOM 实现.
                                                             (line   43)
* parseString() (在 xml.dom.pulldom 模块中): xml dom pulldom --- 支持构建部分 DOM 树.
                                                             (line   88)
* parseString() (在 xml.sax 模块中):     xml sax --- 支持 SAX2 解析器.
                                                             (line   44)
* parse_and_bind() (在 readline 模块中): 初始化文件.         (line    8)
* parse_args() (argparse.ArgumentParser 方法): parse_args 方法.
                                                             (line    6)
* PARSE_COLNAMES() (在 sqlite3 模块中):  模块函数和常量.     (line   31)
* parse_config_h() (在 sysconfig 模块中): 其他功能<3>.       (line   56)
* PARSE_DECLTYPES() (在 sqlite3 模块中): 模块函数和常量.     (line   22)
* parse_header() (在 cgi 模块中):        函数<8>.            (line   40)
* parse_headers() (在 http.client 模块中): http client --- HTTP 协议客户端.
                                                             (line   94)
* parse_intermixed_args() (argparse.ArgumentParser 方法): 混合解析.
                                                             (line    6)
* parse_known_args() (argparse.ArgumentParser 方法): 部分解析.
                                                             (line    6)
* parse_known_intermixed_args() (argparse.ArgumentParser 方法): 混合解析.
                                                             (line    9)
* parse_multipart() (在 cgi 模块中):     函数<8>.            (line   19)
* parse_qs() (在 urllib.parse 模块中):   URL 解析.           (line  134)
* parse_qsl() (在 urllib.parse 模块中):  URL 解析.           (line  180)
* parsing; Python source code:           parser --- 访问 Python 解析树.
                                                             (line    6)
* ParsingError:                          异常<5>.            (line   55)
* partial (asyncio.IncompleteReadError 属性): 异常<9>.       (line   50)
* partial() (imaplib.IMAP4 方法):        IMAP4 Objects.      (line  182)
* partial() (在 functools 模块中):       functools --- 高阶函数和可调用对象上的操作.
                                                             (line  189)
* partialmethod (functools 中的类):      functools --- 高阶函数和可调用对象上的操作.
                                                             (line  216)
* parties (threading.Barrier 属性):      栅栏对象.           (line   79)
* partition() (bytearray 方法):          bytes 和 bytearray 操作.
                                                             (line  115)
* partition() (bytes 方法):              bytes 和 bytearray 操作.
                                                             (line  115)
* partition() (str 方法):                字符串的方法<2>.    (line  282)
* pass_() (poplib.POP3 方法):            POP3 对象.          (line   33)
* Paste:                                 帮助菜单（命令行和编辑器）.
                                                             (line   26)
* patch() (在 test.support 模块中):      test support --- Utilities for the Python test suite.
                                                             (line  942)
* patch() (在 unittest.mock 模块中):     patch.              (line   10)
* patch.dict() (在 unittest.mock 模块中): patch dict.        (line    6)
* patch.multiple() (在 unittest.mock 模块中): patch multiple.
                                                             (line    6)
* patch.object() (在 unittest.mock 模块中): patch object.    (line    6)
* patch.stopall() (在 unittest.mock 模块中): patch methods start and stop.
                                                             (line   70)
* PATH:                                  Python API 的变化.  (line  125)
* PATH <1>:                              'python' 命令行为的变化<2>.
                                                             (line    6)
* PATH <2>:                              'python' 命令行为的变化<2>.
                                                             (line   11)
* PATH <3>:                              'python' 命令行为的变化<2>.
                                                             (line   12)
* PATH <4>:                              安全<19>.           (line   16)
* PATH <5>:                              安全<19>.           (line   20)
* PATH <6>:                              模块搜索路径.       (line   12)
* PATH <7>:                              可执行的Python脚本. (line   11)
* PATH <8>:                              环境变量.           (line   22)
* PATH <9>:                              杂项.               (line   14)
* PATH <10>:                             安装步骤.           (line   26)
* PATH <11>:                             安装步骤.           (line   45)
* PATH <12>:                             无UI 安装.          (line   49)
* PATH <13>:                             附录：设置环境变量. (line   19)
* PATH <14>:                             附录：设置环境变量. (line   27)
* PATH <15>:                             查找Python可执行文件.
                                                             (line   12)
* PATH <16>:                             查找Python可执行文件.
                                                             (line   17)
* PATH <17>:                             查找Python可执行文件.
                                                             (line   18)
* PATH <18>:                             适用于Windows的Python启动器.
                                                             (line   12)
* PATH <19>:                             从命令行.           (line    8)
* PATH <20>:                             从命令行.           (line   33)
* PATH <21>:                             Shebang Lines.      (line   39)
* PATH <22>:                             Shebang Lines.      (line   40)
* PATH <23>:                             进程管理.           (line   39)
* PATH <24>:                             进程管理.           (line   69)
* PATH <25>:                             进程管理.           (line   71)
* PATH <26>:                             进程管理.           (line   73)
* PATH <27>:                             进程管理.           (line  386)
* PATH <28>:                             进程管理.           (line  458)
* PATH <29>:                             进程管理.           (line  459)
* PATH <30>:                             进程管理.           (line  461)
* PATH <31>:                             其他系统信息.       (line   97)
* PATH <32>:                             webbrowser --- 方便的Web浏览器控制器.
                                                             (line  192)
* PATH <33>:                             Installing your CGI script on a Unix system.
                                                             (line   29)
* PATH <34>:                             Common problems and solutions.
                                                             (line   23)
* PATH <35>:                             site —— 站点专属的配置钩子.
                                                             (line   45)
* PATH <36>:                             嵌入Python<2>.      (line   31)
* PATH <37>:                             嵌入Python<2>.      (line   37)
* PATH <38>:                             在 Unix 中怎样让 Python 脚本可执行？.
                                                             (line   19)
* PATH <39>:                             在 Unix 中怎样让 Python 脚本可执行？.
                                                             (line   24)
* path (http.cookiejar.Cookie 属性):     Cookie 对象<2>.     (line   41)
* path (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line   80)
* path (importlib.abc.FileLoader 属性):  importlib abc —— 关于导入的抽象基类.
                                                             (line  425)
* path (importlib.machinery.ExtensionFileLoader 属性): importlib machinery -- Importers and path hooks.
                                                             (line  308)
* path (importlib.machinery.FileFinder 属性): importlib machinery -- Importers and path hooks.
                                                             (line  179)
* path (importlib.machinery.SourceFileLoader 属性): importlib machinery -- Importers and path hooks.
                                                             (line  221)
* path (importlib.machinery.SourcelessFileLoader 属性): importlib machinery -- Importers and path hooks.
                                                             (line  265)
* path (in module sys):                  嵌入Python<2>.      (line   12)
* path (in module sys) <1>:              Initializing and finalizing the interpreter.
                                                             (line    8)
* path (in module sys) <2>:              Process-wide parameters.
                                                             (line  120)
* path (in module sys) <3>:              Process-wide parameters.
                                                             (line  133)
* path (os.DirEntry 属性):               文件和目录.         (line  749)
* Path (pathlib 中的类):                 具体路径.           (line    9)
* Path (zipfile 中的类):                 Path 对象.          (line    6)
* path based finder:                     基于路径的查找器.   (line    6)
* path based finder – 基于路径的查找器:  术语对照表.         (line  821)
* Path browser:                          文件菜单 （命令行和编辑器）.
                                                             (line   22)
* path entry – 路径入口:                 术语对照表.         (line  801)
* path entry finder – 路径入口查找器:    术语对照表.         (line  806)
* path entry hook – 路径入口钩子:        术语对照表.         (line  815)
* path hooks:                            导入钩子.           (line    6)
* path() (在 importlib.resources 模块中): importlib resources -- 资源.
                                                             (line  101)
* path() (在 sys 模块中):                sys --- 系统相关的参数和函数.
                                                             (line  899)
* path-like object – 路径类对象:         术语对照表.         (line  826)
* path; configuration; file:             site —— 站点专属的配置钩子.
                                                             (line   50)
* path; operations:                      pathlib --- 面向对象的文件系统路径.
                                                             (line   10)
* path; operations <1>:                  os path --- 常用路径操作.
                                                             (line    9)
* pathconf() (在 os 模块中):             文件和目录.         (line  489)
* pathconf_names() (在 os 模块中):       文件和目录.         (line  508)
* PathEntryFinder (importlib.abc 中的类): importlib abc —— 关于导入的抽象基类.
                                                             (line   92)
* PATHEXT:                               其他改进<2>.        (line   30)
* PATHEXT <1>:                           库<7>.              (line  116)
* PATHEXT <2>:                           无UI 安装.          (line   50)
* PathFinder (importlib.machinery 中的类): importlib machinery -- Importers and path hooks.
                                                             (line  103)
* pathlib (模块):                        pathlib --- 面向对象的文件系统路径.
                                                             (line    6)
* PathLike (os 中的类):                  进程参数.           (line  103)
* pathname2url() (在 urllib.request 模块中): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  129)
* pathsep() (在 os 模块中):              其他系统信息.       (line   95)
* path_hook() (importlib.machinery.FileFinder 类方法): importlib machinery -- Importers and path hooks.
                                                             (line  199)
* path_hooks() (在 sys 模块中):          sys --- 系统相关的参数和函数.
                                                             (line  919)
* path_importer_cache() (在 sys 模块中): sys --- 系统相关的参数和函数.
                                                             (line  927)
* path_mtime() (importlib.abc.SourceLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  480)
* path_return_ok() (http.cookiejar.CookiePolicy 方法): CookiePolicy 对象.
                                                             (line   56)
* path_stats() (importlib.abc.SourceLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  463)
* path_stats() (importlib.machinery.SourceFileLoader 方法): importlib machinery -- Importers and path hooks.
                                                             (line  230)
* pattern (re.error 属性):               模块内容.           (line  297)
* pattern (re.Pattern 属性):             正则表达式对象 （正则对象）.
                                                             (line   96)
* Pattern (typing 中的类):               类 函数和修饰器.    (line  450)
* pause() (在 signal 模块中):            模块内容<5>.        (line  245)
* pause_reading() (asyncio.ReadTransport 方法): 只读传输.    (line   12)
* pause_writing() (asyncio.BaseProtocol 方法): 基础协议<2>.  (line   35)
* PAX_FORMAT() (在 tarfile 模块中):      tarfile --- 读写tar归档文件.
                                                             (line  206)
* pax_headers (tarfile.TarFile 属性):    TarFile 对象.       (line  218)
* pax_headers (tarfile.TarInfo 属性):    TarInfo 对象.       (line   83)
* pbkdf2_hmac() (在 hashlib 模块中):     密钥派生.           (line   10)
* pd() (在 turtle 模块中):               绘图状态.           (line    6)
* Pdb (class in pdb):                    pdb --- Python的调试器.
                                                             (line   15)
* Pdb (pdb 中的类):                      pdb --- Python的调试器.
                                                             (line  123)
* pdb (模块):                            pdb --- Python的调试器.
                                                             (line    6)
* pdf() (statistics.NormalDist 方法):    NormalDist 对象.    (line   57)
* peek() (bz2.BZ2File 方法):             文件压缩和解压.     (line   67)
* peek() (gzip.GzipFile 方法):           gzip --- 对 gzip 格式的支持.
                                                             (line  106)
* peek() (io.BufferedReader 方法):       缓冲流.             (line   65)
* peek() (lzma.LZMAFile 方法):           读写压缩文件.       (line   74)
* peek() (weakref.finalize 方法):        weakref --- 弱引用. (line  209)
* peer (smtpd.SMTPChannel 属性):         SMTPChannel 对象.   (line   94)
* PEM_cert_to_DER_cert() (在 ssl 模块中): 证书处理.          (line   84)
* pen() (在 turtle 模块中):              绘图状态.           (line   32)
* pencolor() (在 turtle 模块中):         颜色控制.           (line    6)
* pending (ssl.MemoryBIO 属性):          内存 BIO 支持<2>.   (line  122)
* pending() (ssl.SSLSocket 方法):        SSL 套接字.         (line  270)
* PendingDeprecationWarning:             警告.               (line   21)
* pendown() (在 turtle 模块中):          绘图状态.           (line    6)
* pensize() (在 turtle 模块中):          绘图状态.           (line   18)
* penup() (在 turtle 模块中):            绘图状态.           (line   12)
* PEP:                                   术语对照表.         (line  837)
* PERCENT() (在 token 模块中):           token --- 与Python解析树一起使用的常量.
                                                             (line  118)
* PERCENTEQUAL() (在 token 模块中):      token --- 与Python解析树一起使用的常量.
                                                             (line  182)
* Performance:                           timeit --- 测量小代码片段的执行时间.
                                                             (line    8)
* perf_counter() (在 time 模块中):       函数<2>.            (line  157)
* perf_counter_ns() (在 time 模块中):    函数<2>.            (line  166)
* perm() (在 math 模块中):               数论与表示函数.     (line  151)
* PermissionError:                       OS 异常.            (line   83)
* permutations() (在 itertools 模块中):  Itertool函数.       (line  361)
* Persist() (msilib.SummaryInformation 方法): Summary Information Objects.
                                                             (line   29)
* persistence:                           pickle --- Python 对象序列化.
                                                             (line    8)
* persistent; objects:                   pickle --- Python 对象序列化.
                                                             (line    8)
* persistent_id (pickle protocol):       持久化外部对象.     (line    6)
* persistent_id() (pickle.Pickler 方法): 模块接口.           (line  143)
* persistent_load (pickle protocol):     持久化外部对象.     (line    6)
* persistent_load() (pickle.Unpickler 方法): 模块接口.       (line  239)
* pformat() (pprint.PrettyPrinter 方法): PrettyPrinter 对象. (line    8)
* pformat() (在 pprint 模块中):          pprint --- 数据美化输出.
                                                             (line   69)
* PF_CAN() (在 socket 模块中):           常量<8>.            (line   88)
* PF_PACKET() (在 socket 模块中):        常量<8>.            (line  137)
* PF_RDS() (在 socket 模块中):           常量<8>.            (line  147)
* pgettext() (gettext.GNUTranslations 方法): GNUTranslations 类.
                                                             (line   58)
* pgettext() (gettext.NullTranslations 方法): NullTranslations 类.
                                                             (line   39)
* pgettext() (在 gettext 模块中):        GNU gettext API.    (line   62)
* PGO() (在 test.support 模块中):        test support --- Utilities for the Python test suite.
                                                             (line   91)
* phase() (在 cmath 模块中):             到极坐标和从极坐标的转换.
                                                             (line   18)
* Philbrick, Geoff:                      给扩展函数的关键字参数.
                                                             (line   21)
* physical line:                         逻辑行.             (line    6)
* physical line <1>:                     显式的行拼接.       (line    6)
* physical line <2>:                     字符串和字节串字面值.
                                                             (line   62)
* pi() (xml.etree.ElementTree.TreeBuilder 方法): TreeBuilder 对象.
                                                             (line   49)
* pi() (在 cmath 模块中):                常量<3>.            (line    6)
* pi() (在 math 模块中):                 常量<2>.            (line    6)
* pickle (模块):                         pickle --- Python 对象序列化.
                                                             (line    6)
* pickle() (在 copyreg 模块中):          copyreg --- 注册配合 pickle 模块使用的函数.
                                                             (line   20)
* PickleBuffer (pickle 中的类):          模块接口.           (line  263)
* PickleError:                           模块接口.           (line   85)
* Pickler (pickle 中的类):               模块接口.           (line  107)
* pickletools (模块):                    pickletools --- pickle 开发者工具集.
                                                             (line    6)
* pickletools command line option; -a:   命令行选项<6>.      (line    6)
* pickletools command line option; –annotate: 命令行选项<6>. (line    6)
* pickletools command line option; –indentlevel=<num>: 命令行选项<6>.
                                                             (line   14)
* pickletools command line option; -l:   命令行选项<6>.      (line   14)
* pickletools command line option; -m:   命令行选项<6>.      (line   18)
* pickletools command line option; –memo: 命令行选项<6>.     (line   18)
* pickletools command line option; -o:   命令行选项<6>.      (line   10)
* pickletools command line option; –output=<file>: 命令行选项<6>.
                                                             (line   10)
* pickletools command line option; -p:   命令行选项<6>.      (line   22)
* pickletools command line option; –preamble=<preamble>: 命令行选项<6>.
                                                             (line   22)
* pickling; objects:                     pickle --- Python 对象序列化.
                                                             (line    8)
* PicklingError:                         模块接口.           (line   89)
* pid (asyncio.asyncio.subprocess.Process 属性): 与子进程交互.
                                                             (line  121)
* pid (multiprocessing.Process 属性):    Process 和异常.     (line   90)
* pid (subprocess.Popen 属性):           Popen 对象.         (line  119)
* Pipe() (在 multiprocessing 模块中):    管道和队列.         (line   62)
* pipe() (在 os 模块中):                 文件描述符操作.     (line  326)
* PIPE() (在 subprocess 模块中):         使用 subprocess 模块.
                                                             (line  122)
* pipe2() (在 os 模块中):                文件描述符操作.     (line  335)
* pipes (模块):                          pipes --- 终端管道接口.
                                                             (line    6)
* PIPE_BUF() (在 select 模块中):         select --- 等待 I/O 完成.
                                                             (line  129)
* pipe_connection_lost() (asyncio.SubprocessProtocol 方法): 子进程协议.
                                                             (line   17)
* pipe_data_received() (asyncio.SubprocessProtocol 方法): 子进程协议.
                                                             (line    9)
* PIPE_MAX_SIZE() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line   95)
* PIP_USER:                              Windows<16>.        (line    7)
* pkgutil (模块):                        pkgutil --- 包扩展工具.
                                                             (line    6)
* PKG_DIRECTORY() (在 imp 模块中):       imp --- Access the import internals.
                                                             (line  318)
* placeholder (textwrap.TextWrapper 属性): textwrap --- 文本自动换行与填充.
                                                             (line  232)
* PLAT:                                  distutils util --- Miscellaneous other utility functions.
                                                             (line   79)
* platform (in module sys):              Process-wide parameters.
                                                             (line  172)
* platform (模块):                       platform --- 获取底层平台的标识数据.
                                                             (line    6)
* platform() (在 platform 模块中):       跨平台.             (line   42)
* platform() (在 sys 模块中):            sys --- 系统相关的参数和函数.
                                                             (line  939)
* PlaySound() (在 winsound 模块中):      winsound --- Sound-playing interface for Windows.
                                                             (line   20)
* plist; file:                           plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line    8)
* plistlib (模块):                       plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line    6)
* plock() (在 os 模块中):                进程管理.           (line  278)
* plus:                                  一元算术和位运算.   (line   12)
* plus() (decimal.Context 方法):         上下文对象.         (line  368)
* PLUS() (在 token 模块中):              token --- 与Python解析树一起使用的常量.
                                                             (line   78)
* PLUSEQUAL() (在 token 模块中):         token --- 与Python解析树一起使用的常量.
                                                             (line  166)
* pm() (在 pdb 模块中):                  pdb --- Python的调试器.
                                                             (line  115)
* POINTER() (在 ctypes 模块中):          工具函数.           (line  129)
* pointer() (在 ctypes 模块中):          工具函数.           (line  135)
* polar() (在 cmath 模块中):             到极坐标和从极坐标的转换.
                                                             (line   34)
* Policy (email.policy 中的类):          email policy 策略对象.
                                                             (line  103)
* poll() (multiprocessing.connection.Connection 方法): 连接对象（Connection）<2>.
                                                             (line   38)
* poll() (select.devpoll 方法):          /dev/poll 轮询对象. (line   58)
* poll() (select.epoll 方法):            边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   91)
* poll() (select.poll 方法):             Poll 对象.          (line   65)
* poll() (subprocess.Popen 方法):        Popen 对象.         (line    8)
* poll() (在 select 模块中):             select --- 等待 I/O 完成.
                                                             (line   72)
* PollSelector (selectors 中的类):       类<3>.              (line  149)
* Pool (multiprocessing.pool 中的类):    进程池.             (line    8)
* pop() (array.array 方法):              array --- 高效的数值数组.
                                                             (line  179)
* pop() (collections.deque 方法):        deque 对象.         (line   77)
* pop() (dict 方法):                     映射类型 --- dict.  (line  156)
* pop() (frozenset 方法):                集合类型 --- set frozenset.
                                                             (line  188)
* pop() (mailbox.Mailbox 方法):          Mailbox 对象.       (line  170)
* pop() (sequence method):               可变序列类型.       (line   14)
* POP3 (poplib 中的类):                  poplib --- POP3 协议客户端.
                                                             (line   24)
* POP3; protocol:                        poplib --- POP3 协议客户端.
                                                             (line    8)
* POP3_SSL (poplib 中的类):              poplib --- POP3 协议客户端.
                                                             (line   37)
* Popen (subprocess 中的类):             Popen 构造函数.     (line    9)
* popen() (in module os):                标准类型层级结构.   (line  476)
* popen() (in module os) <1>:            select --- 等待 I/O 完成.
                                                             (line  114)
* popen() (在 os 模块中):                进程管理.           (line  285)
* popitem() (collections.OrderedDict 方法): OrderedDict 对象.
                                                             (line   40)
* popitem() (dict 方法):                 映射类型 --- dict.  (line  162)
* popitem() (mailbox.Mailbox 方法):      Mailbox 对象.       (line  177)
* popleft() (collections.deque 方法):    deque 对象.         (line   82)
* poplib (模块):                         poplib --- POP3 协议客户端.
                                                             (line    6)
* PopupMenu (tkinter.tix 中的类):        Basic Widgets.      (line   52)
* pop_alignment() (formatter.formatter 方法): The Formatter Interface.
                                                             (line   97)
* pop_all() (contextlib.ExitStack 方法): 工具.               (line  389)
* POP_BLOCK (opcode):                    Python字节码说明.   (line  350)
* POP_EXCEPT (opcode):                   Python字节码说明.   (line  355)
* POP_FINALLY (opcode):                  Python字节码说明.   (line  361)
* pop_font() (formatter.formatter 方法): The Formatter Interface.
                                                             (line  109)
* POP_JUMP_IF_FALSE (opcode):            Python字节码说明.   (line  601)
* POP_JUMP_IF_TRUE (opcode):             Python字节码说明.   (line  595)
* pop_margin() (formatter.formatter 方法): The Formatter Interface.
                                                             (line  121)
* pop_source() (shlex.shlex 方法):       shlex Objects.      (line   63)
* pop_style() (formatter.formatter 方法): The Formatter Interface.
                                                             (line  132)
* POP_TOP (opcode):                      Python字节码说明.   (line   56)
* port (http.cookiejar.Cookie 属性):     Cookie 对象<2>.     (line   36)
* portion – 部分:                        术语对照表.         (line  849)
* port_specified (http.cookiejar.Cookie 属性): Cookie 对象<2>.
                                                             (line   77)
* pos (json.JSONDecodeError 属性):       异常<13>.           (line   18)
* pos (re.error 属性):                   模块内容.           (line  301)
* pos (re.Match 属性):                   匹配对象.           (line  140)
* pos() (在 operator 模块中):            operator --- 标准运算符替代函数.
                                                             (line  126)
* pos() (在 turtle 模块中):              获取海龟的状态.     (line    6)
* position (xml.etree.ElementTree.ParseError 属性): 异常<15>.
                                                             (line   17)
* position() (在 turtle 模块中):         获取海龟的状态.     (line    6)
* positional argument – 位置参数:        术语对照表.         (line  854)
* posix (模块):                          posix --- 最常见的 POSIX 系统调用.
                                                             (line    6)
* POSIX Shared Memory:                   multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   10)
* POSIX; I/O control:                    termios --- POSIX 风格的 tty 控制.
                                                             (line    6)
* POSIXLY_CORRECT:                       getopt --- C 风格的命令行选项解析器.
                                                             (line   52)
* PosixPath (pathlib 中的类):            具体路径.           (line   19)
* posix_fadvise() (在 os 模块中):        文件描述符操作.     (line  354)
* POSIX_FADV_DONTNEED() (在 os 模块中):  文件描述符操作.     (line  367)
* POSIX_FADV_NOREUSE() (在 os 模块中):   文件描述符操作.     (line  367)
* POSIX_FADV_NORMAL() (在 os 模块中):    文件描述符操作.     (line  367)
* POSIX_FADV_RANDOM() (在 os 模块中):    文件描述符操作.     (line  367)
* POSIX_FADV_SEQUENTIAL() (在 os 模块中): 文件描述符操作.    (line  367)
* POSIX_FADV_WILLNEED() (在 os 模块中):  文件描述符操作.     (line  367)
* posix_fallocate() (在 os 模块中):      文件描述符操作.     (line  345)
* posix_spawn() (在 os 模块中):          进程管理.           (line  302)
* posix_spawnp() (在 os 模块中):         进程管理.           (line  380)
* POSIX_SPAWN_CLOSE() (在 os 模块中):    进程管理.           (line  328)
* POSIX_SPAWN_DUP2() (在 os 模块中):     进程管理.           (line  334)
* POSIX_SPAWN_OPEN() (在 os 模块中):     进程管理.           (line  322)
* post() (nntplib.NNTP 方法):            方法<3>.            (line  277)
* post() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line  175)
* postcmd() (cmd.Cmd 方法):              Cmd 对象.           (line   74)
* postloop() (cmd.Cmd 方法):             Cmd 对象.           (line   87)
* post_handshake_auth (ssl.SSLContext 属性): SSL 上下文.     (line  524)
* post_mortem() (在 pdb 模块中):         pdb --- Python的调试器.
                                                             (line  110)
* post_setup() (venv.EnvBuilder 方法):   API<2>.             (line   92)
* pow() (內置函数):                      内置函数.           (line 1066)
* pow() (在 math 模块中):                幂函数与对数函数.   (line   54)
* pow() (在 operator 模块中):            operator --- 标准运算符替代函数.
                                                             (line  131)
* power() (decimal.Context 方法):        上下文对象.         (line  373)
* power; operation:                      幂运算符.           (line    6)
* pp (pdb command):                      调试器命令.         (line  200)
* pp() (在 pprint 模块中):               pprint --- 数据美化输出.
                                                             (line   80)
* pprint (模块):                         pprint --- 数据美化输出.
                                                             (line    6)
* pprint() (pprint.PrettyPrinter 方法):  PrettyPrinter 对象. (line   13)
* pprint() (在 pprint 模块中):           pprint --- 数据美化输出.
                                                             (line   88)
* prcal() (在 calendar 模块中):          calendar --- 日历相关函数.
                                                             (line  301)
* pread() (在 os 模块中):                文件描述符操作.     (line  381)
* preadv() (在 os 模块中):               文件描述符操作.     (line  393)
* preamble (email.message.EmailMessage 属性): email message 表示一封电子邮件信息.
                                                             (line  574)
* preamble (email.message.Message 属性): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  582)
* precmd() (cmd.Cmd 方法):               Cmd 对象.           (line   67)
* prefix:                                与Python相关的路径和文件.
                                                             (line    6)
* prefix <1>:                            包含文件.           (line   32)
* prefix <2>:                            包含文件.           (line   35)
* prefix <3>:                            包含文件.           (line   39)
* prefix (xml.dom.Attr 属性):            Attr 对象.          (line   16)
* prefix (xml.dom.Node 属性):            节点对象.           (line   58)
* prefix (zipimport.zipimporter 属性):   zipimporter 对象.   (line   66)
* PREFIX() (在 distutils.sysconfig 模块中): distutils sysconfig --- System configuration information.
                                                             (line   19)
* prefix() (在 sys 模块中):              sys --- 系统相关的参数和函数.
                                                             (line  994)
* PREFIXES() (在 site 模块中):           模块内容<7>.        (line    6)
* prefixlen (ipaddress.IPv4Network 属性): Network objects.   (line  132)
* prefixlen (ipaddress.IPv6Network 属性): Network objects.   (line  329)
* preloop() (cmd.Cmd 方法):              Cmd 对象.           (line   82)
* prepare() (logging.handlers.QueueHandler 方法): QueueHandler.
                                                             (line   34)
* prepare() (logging.handlers.QueueListener 方法): QueueListener.
                                                             (line   45)
* prepare_class() (在 types 模块中):     动态类型创建.       (line   19)
* prepare_input_source() (在 xml.sax.saxutils 模块中): xml sax saxutils --- SAX 工具集.
                                                             (line   64)
* prepend() (pipes.Template 方法):       模板对象.           (line   35)
* preprocess() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  430)
* PrettyPrinter (pprint 中的类):         pprint --- 数据美化输出.
                                                             (line   23)
* prev() (tkinter.ttk.Treeview 方法):    ttk Treeview.       (line  241)
* previousSibling (xml.dom.Node 属性):   节点对象.           (line   28)
* primary:                               原型.               (line    6)
* print (2to3 fixer):                    修复器.             (line  245)
* print() (built-in function); __str__() (object method): 基本定制.
                                                             (line  105)
* print() (內置函数):                    内置函数.           (line 1096)
* printable() (在 string 模块中):        字符串常量.         (line   40)
* printdir() (zipfile.ZipFile 方法):     ZipFile 对象.       (line  180)
* printf-style formatting:               printf 风格的字符串格式化.
                                                             (line    6)
* printf-style formatting <1>:           printf 风格的字节串格式化.
                                                             (line    6)
* print_callees() (pstats.Stats 方法):   Stats 类.           (line  217)
* print_callers() (pstats.Stats 方法):   Stats 类.           (line  196)
* print_directory() (在 cgi 模块中):     函数<8>.            (line   59)
* print_environ() (在 cgi 模块中):       函数<8>.            (line   51)
* print_environ_usage() (在 cgi 模块中): 函数<8>.            (line   63)
* print_exc() (timeit.Timer 方法):       Python 接口.        (line  104)
* print_exc() (在 traceback 模块中):     traceback --- 打印或检索堆栈回溯.
                                                             (line   58)
* print_exception() (在 traceback 模块中): traceback --- 打印或检索堆栈回溯.
                                                             (line   32)
* PRINT_EXPR (opcode):                   Python字节码说明.   (line  298)
* print_form() (在 cgi 模块中):          函数<8>.            (line   55)
* print_help() (argparse.ArgumentParser 方法): 打印帮助.     (line   15)
* print_last() (在 traceback 模块中):    traceback --- 打印或检索堆栈回溯.
                                                             (line   63)
* print_stack() (asyncio.Task 方法):     Task 对象.          (line  168)
* print_stack() (在 traceback 模块中):   traceback --- 打印或检索堆栈回溯.
                                                             (line   70)
* print_stats() (profile.Profile 方法):  profile 和 cProfile 模块参考.
                                                             (line   89)
* print_stats() (pstats.Stats 方法):     Stats 类.           (line  164)
* print_tb() (在 traceback 模块中):      traceback --- 打印或检索堆栈回溯.
                                                             (line   20)
* print_usage() (argparse.ArgumentParser 方法): 打印帮助.    (line    9)
* print_usage() (optparse.OptionParser 方法): Other methods. (line   15)
* print_version() (optparse.OptionParser 方法): Printing a version string.
                                                             (line   26)
* PriorityQueue (asyncio 中的类):        优先级队列.         (line    6)
* PriorityQueue (queue 中的类):          queue --- 一个同步的队列类.
                                                             (line   41)
* PRIO_PGRP() (在 os 模块中):            进程参数.           (line  245)
* PRIO_PROCESS() (在 os 模块中):         进程参数.           (line  245)
* PRIO_USER() (在 os 模块中):            进程参数.           (line  245)
* private; names:                        标识符（名称）.     (line   12)
* prlimit() (在 resource 模块中):        Resource Limits.    (line   56)
* prmonth() (calendar.TextCalendar 方法): calendar --- 日历相关函数.
                                                             (line  119)
* prmonth() (在 calendar 模块中):        calendar --- 日历相关函数.
                                                             (line  292)
* ProactorEventLoop (asyncio 中的类):    事件循环实现.       (line   28)
* procedure; call:                       表达式语句.         (line   15)
* Process (multiprocessing 中的类):      Process 和异常.     (line    6)
* process() (logging.LoggerAdapter 方法): LoggerAdapter 对象.
                                                             (line   15)
* process; group:                        进程参数.           (line  163)
* process; group <1>:                    进程参数.           (line  214)
* process; id:                           进程参数.           (line  220)
* process; id of parent:                 进程参数.           (line  224)
* process; killing:                      进程管理.           (line  249)
* process; killing <1>:                  进程管理.           (line  266)
* process; scheduling priority:          进程参数.           (line  234)
* process; scheduling priority <1>:      进程参数.           (line  352)
* process; signalling:                   进程管理.           (line  249)
* process; signalling <1>:               进程管理.           (line  266)
* ProcessError:                          Process 和异常.     (line  175)
* processes, light-weight:               _thread --- 底层多线程 API.
                                                             (line    6)
* processingInstruction() (xml.sax.handler.ContentHandler 方法): ContentHandler 对象.
                                                             (line  138)
* ProcessingInstruction() (在 xml.etree.ElementTree 模块中): 函数<6>.
                                                             (line  145)
* ProcessingInstructionHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  196)
* ProcessLookupError:                    OS 异常.            (line   88)
* processor time:                        函数<2>.            (line  174)
* processor time <1>:                    函数<2>.            (line  414)
* processor() (在 platform 模块中):      跨平台.             (line   58)
* ProcessPoolExecutor (concurrent.futures 中的类): ProcessPoolExecutor.
                                                             (line   17)
* process_exited() (asyncio.SubprocessProtocol 方法): 子进程协议.
                                                             (line   23)
* process_message() (smtpd.SMTPServer 方法): SMTPServer 对象.
                                                             (line   41)
* process_request() (socketserver.BaseServer 方法): Server 对象<2>.
                                                             (line  156)
* process_time() (在 time 模块中):       函数<2>.            (line  172)
* process_time_ns() (在 time 模块中):    函数<2>.            (line  180)
* process_tokens() (在 tabnanny 模块中): tabnanny --- 模糊缩进检测.
                                                             (line   38)
* prod() (在 math 模块中):               数论与表示函数.     (line  164)
* product() (在 itertools 模块中):       Itertool函数.       (line  415)
* Profile (profile 中的类):              profile 和 cProfile 模块参考.
                                                             (line   34)
* profile (模块):                        profile 和 cProfile 模块参考.
                                                             (line    6)
* profile function:                      threading --- 基于线程的并行.
                                                             (line  114)
* profile function <1>:                  sys --- 系统相关的参数和函数.
                                                             (line  626)
* profile function <2>:                  sys --- 系统相关的参数和函数.
                                                             (line 1044)
* profiler:                              sys --- 系统相关的参数和函数.
                                                             (line  626)
* profiler <1>:                          sys --- 系统相关的参数和函数.
                                                             (line 1044)
* profiling, deterministic:              profile分析器简介.  (line    6)
* program:                               完整的 Python 程序. (line    6)
* ProgrammingError:                      异常<4>.            (line   23)
* Progressbar (tkinter.ttk 中的类):      ttk Progressbar.    (line    6)
* prompt (cmd.Cmd 属性):                 Cmd 对象.           (line   95)
* prompts, interpreter:                  sys --- 系统相关的参数和函数.
                                                             (line 1010)
* prompt_user_passwd() (urllib.request.FancyURLopener 方法): 已停用的接口.
                                                             (line  177)
* propagate (logging.Logger 属性):       记录器对象.         (line   20)
* property (內置类):                     内置函数.           (line 1118)
* property list:                         plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line    8)
* PropertyMock (unittest.mock 中的类):   Mock 类.            (line  607)
* property_declaration_handler() (在 xml.sax.handler 模块中): xml sax handler --- SAX 处理程序的基类.
                                                             (line   92)
* property_dom_node() (在 xml.sax.handler 模块中): xml sax handler --- SAX 处理程序的基类.
                                                             (line   99)
* property_lexical_handler() (在 xml.sax.handler 模块中): xml sax handler --- SAX 处理程序的基类.
                                                             (line   85)
* property_xml_string() (在 xml.sax.handler 模块中): xml sax handler --- SAX 处理程序的基类.
                                                             (line  106)
* proto (socket.socket 属性):            套接字对象.         (line  504)
* Protocol (asyncio 中的类):             基础协议.           (line   10)
* protocol (ssl.SSLContext 属性):        SSL 上下文.         (line  544)
* Protocol (typing 中的类):              类 函数和修饰器.    (line   66)
* protocol; context management:          上下文管理器类型.   (line    6)
* protocol; iterator:                    迭代器类型.         (line    6)
* protocol; Telnet:                      telnetlib -- Telnet 客户端.
                                                             (line    8)
* ProtocolError (xmlrpc.client 中的类):  ProtocolError 对象. (line    6)
* PROTOCOL_SSLv2() (在 ssl 模块中):      常量<9>.            (line  135)
* PROTOCOL_SSLv23() (在 ssl 模块中):     常量<9>.            (line  129)
* PROTOCOL_SSLv3() (在 ssl 模块中):      常量<9>.            (line  145)
* PROTOCOL_TLS() (在 ssl 模块中):        常量<9>.            (line  107)
* PROTOCOL_TLSv1() (在 ssl 模块中):      常量<9>.            (line  157)
* PROTOCOL_TLSv1_1() (在 ssl 模块中):    常量<9>.            (line  165)
* PROTOCOL_TLSv1_2() (在 ssl 模块中):    常量<9>.            (line  175)
* PROTOCOL_TLS_CLIENT() (在 ssl 模块中): 常量<9>.            (line  114)
* PROTOCOL_TLS_SERVER() (在 ssl 模块中): 常量<9>.            (line  122)
* protocol_version (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line  144)
* PROTOCOL_VERSION (imaplib.IMAP4 属性): IMAP4 Objects.      (line  376)
* prot_c() (ftplib.FTP_TLS 方法):        FTP_TLS 对象.       (line   32)
* prot_p() (ftplib.FTP_TLS 方法):        FTP_TLS 对象.       (line   28)
* provisional API – 暂定 API:            术语对照表.         (line  858)
* provisional package – 暂定包:          术语对照表.         (line  872)
* proxy() (在 weakref 模块中):           weakref --- 弱引用. (line   98)
* proxyauth() (imaplib.IMAP4 方法):      IMAP4 Objects.      (line  187)
* ProxyBasicAuthHandler (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  300)
* ProxyDigestAuthHandler (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  325)
* ProxyHandler (urllib.request 中的类):  urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  242)
* ProxyType() (在 weakref 模块中):       weakref --- 弱引用. (line  235)
* ProxyTypes() (在 weakref 模块中):      weakref --- 弱引用. (line  243)
* pryear() (calendar.TextCalendar 方法): calendar --- 日历相关函数.
                                                             (line  130)
* ps1() (在 sys 模块中):                 sys --- 系统相关的参数和函数.
                                                             (line 1007)
* ps2() (在 sys 模块中):                 sys --- 系统相关的参数和函数.
                                                             (line 1007)
* pstats (模块):                         Stats 类.           (line    7)
* pstdev() (在 statistics 模块中):       函数细节.           (line  237)
* pthreads:                              _thread --- 底层多线程 API.
                                                             (line   13)
* pthread_getcpuclockid() (在 time 模块中): 函数<2>.         (line   19)
* pthread_kill() (在 signal 模块中):     模块内容<5>.        (line  261)
* pthread_sigmask() (在 signal 模块中):  模块内容<5>.        (line  288)
* pty (模块):                            pty --- 伪终端工具. (line    6)
* pu() (在 turtle 模块中):               绘图状态.           (line   12)
* publicId (xml.dom.DocumentType 属性):  文档类型对象.       (line   13)
* PullDom (xml.dom.pulldom 中的类):      xml dom pulldom --- 支持构建部分 DOM 树.
                                                             (line   69)
* punctuation() (在 string 模块中):      字符串常量.         (line   35)
* punctuation_chars (shlex.shlex 属性):  shlex Objects.      (line  182)
* PurePath (pathlib 中的类):             纯路径.             (line    9)
* PurePath.anchor() (在 pathlib 模块中): 方法和特征属性.     (line   40)
* PurePath.drive() (在 pathlib 模块中):  方法和特征属性.     (line    8)
* PurePath.name() (在 pathlib 模块中):   方法和特征属性.     (line   92)
* PurePath.parent() (在 pathlib 模块中): 方法和特征属性.     (line   66)
* PurePath.parents() (在 pathlib 模块中): 方法和特征属性.    (line   53)
* PurePath.parts() (在 pathlib 模块中):  访问个别部分.       (line    8)
* PurePath.root() (在 pathlib 模块中):   方法和特征属性.     (line   24)
* PurePath.stem() (在 pathlib 模块中):   方法和特征属性.     (line  128)
* PurePath.suffix() (在 pathlib 模块中): 方法和特征属性.     (line  106)
* PurePath.suffixes() (在 pathlib 模块中): 方法和特征属性.   (line  117)
* PurePosixPath (pathlib 中的类):        纯路径.             (line   63)
* PureProxy (smtpd 中的类):              PureProxy对象.      (line    6)
* PureWindowsPath (pathlib 中的类):      纯路径.             (line   72)
* purge() (在 re 模块中):                模块内容.           (line  282)
* Purpose.CLIENT_AUTH() (在 ssl 模块中): 常量<9>.            (line  455)
* Purpose.SERVER_AUTH() (在 ssl 模块中): 常量<9>.            (line  447)
* push() (asynchat.async_chat 方法):     asynchat --- 异步 socket 指令/响应 处理器.
                                                             (line   87)
* push() (code.InteractiveConsole 方法): 交互式控制台对象.   (line   24)
* push() (contextlib.ExitStack 方法):    工具.               (line  356)
* pushbutton() (msilib.Dialog 方法):     GUI classes.        (line   68)
* push_alignment() (formatter.formatter 方法): The Formatter Interface.
                                                             (line   90)
* push_async_callback() (contextlib.AsyncExitStack 方法): 工具.
                                                             (line  436)
* push_async_exit() (contextlib.AsyncExitStack 方法): 工具.  (line  431)
* push_font() (formatter.formatter 方法): The Formatter Interface.
                                                             (line  101)
* push_margin() (formatter.formatter 方法): The Formatter Interface.
                                                             (line  113)
* push_source() (shlex.shlex 方法):      shlex Objects.      (line   56)
* push_style() (formatter.formatter 方法): The Formatter Interface.
                                                             (line  125)
* push_token() (shlex.shlex 方法):       shlex Objects.      (line   16)
* push_with_producer() (asynchat.async_chat 方法): asynchat --- 异步 socket 指令/响应 处理器.
                                                             (line   93)
* put() (asyncio.Queue 方法):            Queue.              (line   56)
* put() (multiprocessing.Queue 方法):    管道和队列.         (line  102)
* put() (multiprocessing.SimpleQueue 方法): 管道和队列.      (line  185)
* put() (queue.Queue 方法):              Queue对象.          (line   26)
* put() (queue.SimpleQueue 方法):        SimpleQueue 对象.   (line   17)
* putch() (在 msvcrt 模块中):            控制台 I/O.         (line   30)
* putenv() (在 os 模块中):               进程参数.           (line  289)
* putheader() (http.client.HTTPConnection 方法): HTTPConnection 对象.
                                                             (line  116)
* putp() (在 curses 模块中):             函数<3>.            (line  310)
* putrequest() (http.client.HTTPConnection 方法): HTTPConnection 对象.
                                                             (line  105)
* putwch() (在 msvcrt 模块中):           控制台 I/O.         (line   34)
* putwin() (curses.window 方法):         Window 对象.        (line  389)
* put_nowait() (asyncio.Queue 方法):     Queue.              (line   61)
* put_nowait() (multiprocessing.Queue 方法): 管道和队列.     (line  115)
* put_nowait() (queue.Queue 方法):       Queue对象.          (line   35)
* put_nowait() (queue.SimpleQueue 方法): SimpleQueue 对象.   (line   30)
* pvariance() (在 statistics 模块中):    函数细节.           (line  245)
* pwd (模块):                            pwd --- 用户密码数据库.
                                                             (line    6)
* pwd() (ftplib.FTP 方法):               FTP 对象.           (line  190)
* pwrite() (在 os 模块中):               文件描述符操作.     (line  443)
* pwritev() (在 os 模块中):              文件描述符操作.     (line  454)
* PyAnySet_Check (C 函数):               集合对象.           (line   49)
* PyAnySet_CheckExact (C 函数):          集合对象.           (line   54)
* PyArg_Parse (C 函数):                  API 函数.           (line   45)
* PyArg_ParseTuple (C 函数):             API 函数.           (line    6)
* PyArg_ParseTuple():                    提取扩展函数的参数. (line    6)
* PyArg_ParseTupleAndKeywords (C 函数):  API 函数.           (line   19)
* PyArg_ParseTupleAndKeywords():         给扩展函数的关键字参数.
                                                             (line    6)
* PyArg_UnpackTuple (C 函数):            API 函数.           (line   52)
* PyArg_ValidateKeywordArguments (C 函数): API 函数.         (line   37)
* PyArg_VaParse (C 函数):                API 函数.           (line   12)
* PyArg_VaParseTupleAndKeywords (C 函数): API 函数.          (line   30)
* PyASCIIObject (C 类型):                Unicode类型.        (line   29)
* PyAsyncMethods (C 类型):               Async Object Structures.
                                                             (line    8)
* PyAsyncMethods.am_aiter (C 成员):      Async Object Structures.
                                                             (line   34)
* PyAsyncMethods.am_anext (C 成员):      Async Object Structures.
                                                             (line   46)
* PyAsyncMethods.am_await (C 成员):      Async Object Structures.
                                                             (line   22)
* PyBool_Check (C 函数):                 布尔对象.           (line    9)
* PyBool_FromLong (C 函数):              布尔对象.           (line   31)
* PyBufferProcs:                         缓冲协议.           (line   17)
* PyBufferProcs (C 类型):                Buffer Object Structures.
                                                             (line    6)
* PyBufferProcs.bf_getbuffer (C 成员):   Buffer Object Structures.
                                                             (line   12)
* PyBufferProcs.bf_releasebuffer (C 成员): Buffer Object Structures.
                                                             (line   60)
* PyBuffer_FillContiguousStrides (C 函数): 缓冲区相关函数.   (line   78)
* PyBuffer_FillInfo (C 函数):            缓冲区相关函数.     (line   87)
* PyBuffer_FromContiguous (C 函数):      缓冲区相关函数.     (line   59)
* PyBuffer_GetPointer (C 函数):          缓冲区相关函数.     (line   53)
* PyBuffer_IsContiguous (C 函数):        缓冲区相关函数.     (line   46)
* PyBuffer_Release (C 函数):             缓冲区相关函数.     (line   32)
* PyBuffer_SizeFromFormat (C 函数):      缓冲区相关函数.     (line   41)
* PyBuffer_ToContiguous (C 函数):        缓冲区相关函数.     (line   67)
* PyBUF_ANY_CONTIGUOUS (C 宏):           连续性的请求.       (line   19)
* PyBUF_CONTIG (C 宏):                   复合请求.           (line   35)
* PyBUF_CONTIG_RO (C 宏):                复合请求.           (line   38)
* PyBUF_C_CONTIGUOUS (C 宏):             连续性的请求.       (line   13)
* PyBUF_FORMAT (C 宏):                   只读，格式.         (line   14)
* PyBUF_FULL (C 宏):                     复合请求.           (line   17)
* PyBUF_FULL_RO (C 宏):                  复合请求.           (line   20)
* PyBUF_F_CONTIGUOUS (C 宏):             连续性的请求.       (line   16)
* PyBUF_INDIRECT (C 宏):                 形状，步幅，子偏移量.
                                                             (line   13)
* PyBUF_ND (C 宏):                       形状，步幅，子偏移量.
                                                             (line   19)
* PyBUF_RECORDS (C 宏):                  复合请求.           (line   23)
* PyBUF_RECORDS_RO (C 宏):               复合请求.           (line   26)
* PyBUF_SIMPLE (C 宏):                   形状，步幅，子偏移量.
                                                             (line   22)
* PyBUF_STRIDED (C 宏):                  复合请求.           (line   29)
* PyBUF_STRIDED_RO (C 宏):               复合请求.           (line   32)
* PyBUF_STRIDES (C 宏):                  形状，步幅，子偏移量.
                                                             (line   16)
* PyBUF_WRITABLE (C 宏):                 只读，格式.         (line    6)
* PyByteArrayObject (C 类型):            字节数组对象.       (line    6)
* PyByteArray_AsString (C 函数):         直接 API 函数.      (line   23)
* PyByteArray_AS_STRING (C 函数):        宏.                 (line    8)
* PyByteArray_Check (C 函数):            类型检查宏.         (line    6)
* PyByteArray_CheckExact (C 函数):       类型检查宏.         (line   11)
* PyByteArray_Concat (C 函数):           直接 API 函数.      (line   15)
* PyByteArray_FromObject (C 函数):       直接 API 函数.      (line    6)
* PyByteArray_FromStringAndSize (C 函数): 直接 API 函数.     (line   10)
* PyByteArray_GET_SIZE (C 函数):         宏.                 (line   12)
* PyByteArray_Resize (C 函数):           直接 API 函数.      (line   28)
* PyByteArray_Size (C 函数):             直接 API 函数.      (line   19)
* PyByteArray_Type (C 变量):             字节数组对象.       (line   10)
* PyBytesObject (C 类型):                bytes 对象<2>.      (line    9)
* PyBytes_AsString (C 函数):             bytes 对象<2>.      (line  109)
* PyBytes_AsStringAndSize (C 函数):      bytes 对象<2>.      (line  122)
* PyBytes_AS_STRING (C 函数):            bytes 对象<2>.      (line  118)
* PyBytes_Check (C 函数):                bytes 对象<2>.      (line   18)
* PyBytes_CheckExact (C 函数):           bytes 对象<2>.      (line   22)
* PyBytes_Concat (C 函数):               bytes 对象<2>.      (line  142)
* PyBytes_ConcatAndDel (C 函数):         bytes 对象<2>.      (line  149)
* PyBytes_FromFormat (C 函数):           bytes 对象<2>.      (line   38)
* PyBytes_FromFormatV (C 函数):          bytes 对象<2>.      (line   92)
* PyBytes_FromObject (C 函数):           bytes 对象<2>.      (line   97)
* PyBytes_FromString (C 函数):           bytes 对象<2>.      (line   26)
* PyBytes_FromStringAndSize (C 函数):    bytes 对象<2>.      (line   31)
* PyBytes_GET_SIZE (C 函数):             bytes 对象<2>.      (line  105)
* PyBytes_Size (C 函数):                 bytes 对象<2>.      (line  101)
* PyBytes_Type (C 变量):                 bytes 对象<2>.      (line   13)
* pycache_prefix() (在 sys 模块中):      sys --- 系统相关的参数和函数.
                                                             (line  243)
* PyCallable_Check (C 函数):             对象协议.           (line  209)
* PyCallIter_Check (C 函数):             迭代器对象.         (line   28)
* PyCallIter_New (C 函数):               迭代器对象.         (line   32)
* PyCallIter_Type (C 变量):              迭代器对象.         (line   23)
* PyCapsule (C 类型):                    胶囊<2>.            (line   10)
* PyCapsule_CheckExact (C 函数):         胶囊<2>.            (line   26)
* PyCapsule_Destructor (C 类型):         胶囊<2>.            (line   17)
* PyCapsule_GetContext (C 函数):         胶囊<2>.            (line   69)
* PyCapsule_GetDestructor (C 函数):      胶囊<2>.            (line   59)
* PyCapsule_GetName (C 函数):            胶囊<2>.            (line   78)
* PyCapsule_GetPointer (C 函数):         胶囊<2>.            (line   49)
* PyCapsule_Import (C 函数):             胶囊<2>.            (line   87)
* PyCapsule_IsValid (C 函数):            胶囊<2>.            (line   99)
* PyCapsule_New (C 函数):                胶囊<2>.            (line   30)
* PyCapsule_SetContext (C 函数):         胶囊<2>.            (line  113)
* PyCapsule_SetDestructor (C 函数):      胶囊<2>.            (line  119)
* PyCapsule_SetName (C 函数):            胶囊<2>.            (line  127)
* PyCapsule_SetPointer (C 函数):         胶囊<2>.            (line  135)
* PyCellObject (C 类型):                 Cell 对象.          (line   13)
* PyCell_Check (C 函数):                 Cell 对象.          (line   21)
* PyCell_Get (C 函数):                   Cell 对象.          (line   29)
* PyCell_GET (C 函数):                   Cell 对象.          (line   32)
* PyCell_New (C 函数):                   Cell 对象.          (line   25)
* PyCell_Set (C 函数):                   Cell 对象.          (line   36)
* PyCell_SET (C 函数):                   Cell 对象.          (line   42)
* PyCell_Type (C 变量):                  Cell 对象.          (line   17)
* PyCFunction (C 类型):                  公用对象的结构.     (line   91)
* PyCFunctionWithKeywords (C 类型):      公用对象的结构.     (line  100)
* PycInvalidationMode (py_compile 中的类): py_compile --- 编译 Python 源文件.
                                                             (line   74)
* pyclbr (模块):                         pyclbr --- Python 模块浏览器支持.
                                                             (line    6)
* PyCodec_BackslashReplaceErrors (C 函数): 用于Unicode编码错误处理程序的注册表API.
                                                             (line   42)
* PyCodec_Decode (C 函数):               编解码器注册与支持功能.
                                                             (line   26)
* PyCodec_Decoder (C 函数):              Codec 查找API.      (line   14)
* PyCodec_Encode (C 函数):               编解码器注册与支持功能.
                                                             (line   18)
* PyCodec_Encoder (C 函数):              Codec 查找API.      (line   10)
* PyCodec_IgnoreErrors (C 函数):         用于Unicode编码错误处理程序的注册表API.
                                                             (line   31)
* PyCodec_IncrementalDecoder (C 函数):   Codec 查找API.      (line   23)
* PyCodec_IncrementalEncoder (C 函数):   Codec 查找API.      (line   18)
* PyCodec_KnownEncoding (C 函数):        编解码器注册与支持功能.
                                                             (line   13)
* PyCodec_LookupError (C 函数):          用于Unicode编码错误处理程序的注册表API.
                                                             (line   23)
* PyCodec_NameReplaceErrors (C 函数):    用于Unicode编码错误处理程序的注册表API.
                                                             (line   46)
* PyCodec_Register (C 函数):             编解码器注册与支持功能.
                                                             (line    6)
* PyCodec_RegisterError (C 函数):        用于Unicode编码错误处理程序的注册表API.
                                                             (line    6)
* PyCodec_ReplaceErrors (C 函数):        用于Unicode编码错误处理程序的注册表API.
                                                             (line   34)
* PyCodec_StreamReader (C 函数):         Codec 查找API.      (line   28)
* PyCodec_StreamWriter (C 函数):         Codec 查找API.      (line   34)
* PyCodec_StrictErrors (C 函数):         用于Unicode编码错误处理程序的注册表API.
                                                             (line   28)
* PyCodec_XMLCharRefReplaceErrors (C 函数): 用于Unicode编码错误处理程序的注册表API.
                                                             (line   38)
* PyCodeObject (C 类型):                 代码对象<2>.        (line    9)
* PyCode_Check (C 函数):                 代码对象<2>.        (line   18)
* PyCode_GetNumFree (C 函数):            代码对象<2>.        (line   22)
* PyCode_New (C 函数):                   代码对象<2>.        (line   26)
* PyCode_NewEmpty (C 函数):              代码对象<2>.        (line   53)
* PyCode_NewWithPosOnlyArgs (C 函数):    代码对象<2>.        (line   40)
* PyCode_Type (C 变量):                  代码对象<2>.        (line   13)
* PyCompactUnicodeObject (C 类型):       Unicode类型.        (line   29)
* PyCompileError:                        py_compile --- 编译 Python 源文件.
                                                             (line   16)
* PyCompilerFlags (C 类型):              The Very High Level Layer.
                                                             (line  394)
* PyCompilerFlags.cf_feature_version (C 成员): The Very High Level Layer.
                                                             (line  410)
* PyCompilerFlags.cf_flags (C 成员):     The Very High Level Layer.
                                                             (line  406)
* PyComplexObject (C 类型):              表示复数的Python对象.
                                                             (line    6)
* PyComplex_AsCComplex (C 函数):         表示复数的Python对象.
                                                             (line   41)
* PyComplex_Check (C 函数):              表示复数的Python对象.
                                                             (line   15)
* PyComplex_CheckExact (C 函数):         表示复数的Python对象.
                                                             (line   20)
* PyComplex_FromCComplex (C 函数):       表示复数的Python对象.
                                                             (line   25)
* PyComplex_FromDoubles (C 函数):        表示复数的Python对象.
                                                             (line   29)
* PyComplex_ImagAsDouble (C 函数):       表示复数的Python对象.
                                                             (line   37)
* PyComplex_RealAsDouble (C 函数):       表示复数的Python对象.
                                                             (line   33)
* PyComplex_Type (C 变量):               表示复数的Python对象.
                                                             (line   10)
* PyConfig (C 类型):                     PyConfig.           (line    6)
* PyConfig.argv (C 成员):                PyConfig.           (line   99)
* PyConfig.base_executable (C 成员):     PyConfig.           (line  111)
* PyConfig.base_exec_prefix (C 成员):    PyConfig.           (line  107)
* PyConfig.base_prefix (C 成员):         PyConfig.           (line  116)
* PyConfig.buffered_stdio (C 成员):      PyConfig.           (line  120)
* PyConfig.bytes_warning (C 成员):       PyConfig.           (line  127)
* PyConfig.check_hash_pycs_mode (C 成员): PyConfig.          (line  134)
* PyConfig.configure_c_stdio (C 成员):   PyConfig.           (line  144)
* PyConfig.dev_mode (C 成员):            PyConfig.           (line  150)
* PyConfig.dump_refs (C 成员):           PyConfig.           (line  154)
* PyConfig.executable (C 成员):          PyConfig.           (line  165)
* PyConfig.exec_prefix (C 成员):         PyConfig.           (line  161)
* PyConfig.faulthandler (C 成员):        PyConfig.           (line  169)
* PyConfig.filesystem_encoding (C 成员): PyConfig.           (line  174)
* PyConfig.filesystem_errors (C 成员):   PyConfig.           (line  178)
* PyConfig.hash_seed (C 成员):           PyConfig.           (line  183)
* PyConfig.home (C 成员):                PyConfig.           (line  193)
* PyConfig.import_time (C 成员):         PyConfig.           (line  200)
* PyConfig.inspect (C 成员):             PyConfig.           (line  204)
* PyConfig.install_signal_handlers (C 成员): PyConfig.       (line  208)
* PyConfig.interactive (C 成员):         PyConfig.           (line  212)
* PyConfig.isolated (C 成员):            PyConfig.           (line  216)
* PyConfig.legacy_windows_stdio (C 成员): PyConfig.          (line  230)
* PyConfig.malloc_stats (C 成员):        PyConfig.           (line  239)
* PyConfig.module_search_paths (C 成员): PyConfig.           (line  255)
* PyConfig.module_search_paths_set (C 成员): PyConfig.       (line  257)
* PyConfig.optimization_level (C 成员):  PyConfig.           (line  264)
* PyConfig.parser_debug (C 成员):        PyConfig.           (line  280)
* PyConfig.parse_argv (C 成员):          PyConfig.           (line  274)
* PyConfig.pathconfig_warnings (C 成员): PyConfig.           (line  285)
* PyConfig.prefix (C 成员):              PyConfig.           (line  291)
* PyConfig.program_name (C 成员):        PyConfig.           (line  295)
* PyConfig.pycache_prefix (C 成员):      PyConfig.           (line  300)
* PyConfig.pythonpath_env (C 成员):      PyConfig.           (line  247)
* PyConfig.quiet (C 成员):               PyConfig.           (line  306)
* PyConfig.run_command (C 成员):         PyConfig.           (line  311)
* PyConfig.run_filename (C 成员):        PyConfig.           (line  316)
* PyConfig.run_module (C 成员):          PyConfig.           (line  320)
* PyConfig.show_alloc_count (C 成员):    PyConfig.           (line  325)
* PyConfig.show_ref_count (C 成员):      PyConfig.           (line  333)
* PyConfig.site_import (C 成员):         PyConfig.           (line  342)
* PyConfig.skip_source_first_line (C 成员): PyConfig.        (line  346)
* PyConfig.stdio_encoding (C 成员):      PyConfig.           (line  350)
* PyConfig.stdio_errors (C 成员):        PyConfig.           (line  352)
* PyConfig.tracemalloc (C 成员):         PyConfig.           (line  357)
* PyConfig.user_site_directory (C 成员): PyConfig.           (line  365)
* PyConfig.use_environment (C 成员):     PyConfig.           (line  361)
* PyConfig.use_hash_seed (C 成员):       PyConfig.           (line  185)
* PyConfig.verbose (C 成员):             PyConfig.           (line  369)
* PyConfig.warnoptions (C 成员):         PyConfig.           (line  373)
* PyConfig.write_bytecode (C 成员):      PyConfig.           (line  384)
* PyConfig.xoptions (C 成员):            PyConfig.           (line  391)
* PyConfig_Clear (C 函数):               PyConfig.           (line   69)
* PyConfig_InitIsolatedConfig (C 函数):  PyConfig.           (line   17)
* PyConfig_InitPythonConfig (C 函数):    PyConfig.           (line   12)
* PyConfig_Read (C 函数):                PyConfig.           (line   61)
* PyConfig_SetArgv (C 函数):             PyConfig.           (line   37)
* PyConfig_SetBytesArgv (C 函数):        PyConfig.           (line   44)
* PyConfig_SetBytesString (C 函数):      PyConfig.           (line   29)
* PyConfig_SetString (C 函数):           PyConfig.           (line   22)
* PyConfig_SetWideStringList (C 函数):   PyConfig.           (line   52)
* PyContext (C 类型):                    上下文变量对象.     (line   23)
* PyContextToken (C 类型):               上下文变量对象.     (line   31)
* PyContextToken_CheckExact (C 函数):    上下文变量对象.     (line   59)
* PyContextToken_Type (C 变量):          上下文变量对象.     (line   43)
* PyContextVar (C 类型):                 上下文变量对象.     (line   27)
* PyContextVar_CheckExact (C 函数):      上下文变量对象.     (line   54)
* PyContextVar_Get (C 函数):             上下文变量对象.     (line  100)
* PyContextVar_New (C 函数):             上下文变量对象.     (line   95)
* PyContextVar_Reset (C 函数):           上下文变量对象.     (line  121)
* PyContextVar_Set (C 函数):             上下文变量对象.     (line  117)
* PyContextVar_Type (C 变量):            上下文变量对象.     (line   39)
* PyContext_CheckExact (C 函数):         上下文变量对象.     (line   49)
* PyContext_ClearFreeList (C 函数):      上下文变量对象.     (line   88)
* PyContext_Copy (C 函数):               上下文变量对象.     (line   70)
* PyContext_CopyCurrent (C 函数):        上下文变量对象.     (line   74)
* PyContext_Enter (C 函数):              上下文变量对象.     (line   78)
* PyContext_Exit (C 函数):               上下文变量对象.     (line   83)
* PyContext_New (C 函数):                上下文变量对象.     (line   66)
* PyContext_Type (C 变量):               上下文变量对象.     (line   35)
* PyCoroObject (C 类型):                 协程对象<2>.        (line   10)
* PyCoro_CheckExact (C 函数):            协程对象<2>.        (line   18)
* PyCoro_New (C 函数):                   协程对象<2>.        (line   23)
* PyCoro_Type (C 变量):                  协程对象<2>.        (line   14)
* PyDateTime_Check (C 函数):             DateTime 对象<2>.   (line   33)
* PyDateTime_CheckExact (C 函数):        DateTime 对象<2>.   (line   39)
* PyDateTime_DATE_GET_HOUR (C 函数):     DateTime 对象<2>.   (line  150)
* PyDateTime_DATE_GET_MICROSECOND (C 函数): DateTime 对象<2>.
                                                             (line  162)
* PyDateTime_DATE_GET_MINUTE (C 函数):   DateTime 对象<2>.   (line  154)
* PyDateTime_DATE_GET_SECOND (C 函数):   DateTime 对象<2>.   (line  158)
* PyDateTime_DELTA_GET_DAYS (C 函数):    DateTime 对象<2>.   (line  188)
* PyDateTime_DELTA_GET_MICROSECONDS (C 函数): DateTime 对象<2>.
                                                             (line  200)
* PyDateTime_DELTA_GET_SECONDS (C 函数): DateTime 对象<2>.   (line  194)
* PyDateTime_FromDateAndTime (C 函数):   DateTime 对象<2>.   (line   80)
* PyDateTime_FromDateAndTimeAndFold (C 函数): DateTime 对象<2>.
                                                             (line   87)
* PyDateTime_FromTimestamp (C 函数):     DateTime 对象<2>.   (line  208)
* PyDateTime_GET_DAY (C 函数):           DateTime 对象<2>.   (line  142)
* PyDateTime_GET_MONTH (C 函数):         DateTime 对象<2>.   (line  138)
* PyDateTime_GET_YEAR (C 函数):          DateTime 对象<2>.   (line  134)
* PyDateTime_TimeZone_UTC (C 变量):      DateTime 对象<2>.   (line   14)
* PyDateTime_TIME_GET_HOUR (C 函数):     DateTime 对象<2>.   (line  169)
* PyDateTime_TIME_GET_MICROSECOND (C 函数): DateTime 对象<2>.
                                                             (line  181)
* PyDateTime_TIME_GET_MINUTE (C 函数):   DateTime 对象<2>.   (line  173)
* PyDateTime_TIME_GET_SECOND (C 函数):   DateTime 对象<2>.   (line  177)
* PyDate_Check (C 函数):                 DateTime 对象<2>.   (line   23)
* PyDate_CheckExact (C 函数):            DateTime 对象<2>.   (line   28)
* PyDate_FromDate (C 函数):              DateTime 对象<2>.   (line   76)
* PyDate_FromTimestamp (C 函数):         DateTime 对象<2>.   (line  213)
* PyDelta_Check (C 函数):                DateTime 对象<2>.   (line   54)
* PyDelta_CheckExact (C 函数):           DateTime 对象<2>.   (line   59)
* PyDelta_FromDSU (C 函数):              DateTime 对象<2>.   (line  108)
* PyDescr_IsData (C 函数):               描述符对象.         (line   37)
* PyDescr_NewClassMethod (C 函数):       描述符对象.         (line   32)
* PyDescr_NewGetSet (C 函数):            描述符对象.         (line   12)
* PyDescr_NewMember (C 函数):            描述符对象.         (line   17)
* PyDescr_NewMethod (C 函数):            描述符对象.         (line   22)
* PyDescr_NewWrapper (C 函数):           描述符对象.         (line   27)
* PyDictObject (C 类型):                 字典对象.           (line    6)
* PyDictProxy_New (C 函数):              字典对象.           (line   27)
* PyDict_Check (C 函数):                 字典对象.           (line   15)
* PyDict_CheckExact (C 函数):            字典对象.           (line   19)
* PyDict_Clear (C 函数):                 字典对象.           (line   32)
* PyDict_ClearFreeList (C 函数):         字典对象.           (line  194)
* PyDict_Contains (C 函数):              字典对象.           (line   36)
* PyDict_Copy (C 函数):                  字典对象.           (line   42)
* PyDict_DelItem (C 函数):               字典对象.           (line   60)
* PyDict_DelItemString (C 函数):         字典对象.           (line   66)
* PyDict_GetItem (C 函数):               字典对象.           (line   72)
* PyDict_GetItemString (C 函数):         字典对象.           (line   86)
* PyDict_GetItemWithError (C 函数):      字典对象.           (line   80)
* PyDict_Items (C 函数):                 字典对象.           (line  107)
* PyDict_Keys (C 函数):                  字典对象.           (line  111)
* PyDict_Merge (C 函数):                 字典对象.           (line  165)
* PyDict_MergeFromSeq2 (C 函数):         字典对象.           (line  181)
* PyDict_New (C 函数):                   字典对象.           (line   23)
* PyDict_Next (C 函数):                  字典对象.           (line  123)
* PyDict_SetDefault (C 函数):            字典对象.           (line   96)
* PyDict_SetItem (C 函数):               字典对象.           (line   45)
* PyDict_SetItemString (C 函数):         字典对象.           (line   52)
* PyDict_Size (C 函数):                  字典对象.           (line  119)
* PyDict_Type (C 变量):                  字典对象.           (line   10)
* PyDict_Update (C 函数):                字典对象.           (line  174)
* PyDict_Values (C 函数):                字典对象.           (line  115)
* PyDLL (ctypes 中的类):                 加载动态链接库.     (line   52)
* pydoc (模块):                          pydoc --- 文档生成器和在线帮助系统.
                                                             (line    6)
* PyDoc_STR (C 宏):                      有用的宏.           (line   94)
* PyDoc_STRVAR (C 宏):                   有用的宏.           (line   76)
* PyErr_BadArgument (C 函数):            抛出异常<2>.        (line   38)
* PyErr_BadInternalCall (C 函数):        抛出异常<2>.        (line  172)
* PyErr_CheckSignals (C 函数):           信号处理<2>.        (line    6)
* PyErr_Clear (C 函数):                  打印和清理.         (line    6)
* PyErr_Clear():                         异常<18>.           (line   23)
* PyErr_Clear() <1>:                     异常<18>.           (line  121)
* PyErr_ExceptionMatches (C 函数):       查询错误指示器.     (line   20)
* PyErr_ExceptionMatches():              异常<18>.           (line  121)
* PyErr_Fetch (C 函数):                  查询错误指示器.     (line   35)
* PyErr_Fetch():                         终结和内存释放.     (line   19)
* PyErr_Format (C 函数):                 抛出异常<2>.        (line   20)
* PyErr_FormatV (C 函数):                抛出异常<2>.        (line   27)
* PyErr_GetExcInfo (C 函数):             查询错误指示器.     (line   96)
* PyErr_GivenExceptionMatches (C 函数):  查询错误指示器.     (line   26)
* PyErr_NewException (C 函数):           异常类.             (line    6)
* PyErr_NewExceptionWithDoc (C 函数):    异常类.             (line   23)
* PyErr_NoMemory (C 函数):               抛出异常<2>.        (line   43)
* PyErr_NormalizeException (C 函数):     查询错误指示器.     (line   77)
* PyErr_Occurred (C 函数):               查询错误指示器.     (line    6)
* PyErr_Occurred():                      异常<18>.           (line   10)
* PyErr_Print (C 函数):                  打印和清理.         (line   22)
* PyErr_PrintEx (C 函数):                打印和清理.         (line   10)
* PyErr_ResourceWarning (C 函数):        警告<3>.            (line   70)
* PyErr_Restore (C 函数):                查询错误指示器.     (line   58)
* PyErr_Restore():                       终结和内存释放.     (line   19)
* PyErr_SetExcFromWindowsErr (C 函数):   抛出异常<2>.        (line   95)
* PyErr_SetExcFromWindowsErrWithFilename (C 函数): 抛出异常<2>.
                                                             (line  132)
* PyErr_SetExcFromWindowsErrWithFilenameObject (C 函数): 抛出异常<2>.
                                                             (line  111)
* PyErr_SetExcFromWindowsErrWithFilenameObjects (C 函数): 抛出异常<2>.
                                                             (line  120)
* PyErr_SetExcInfo (C 函数):             查询错误指示器.     (line  114)
* PyErr_SetFromErrno (C 函数):           抛出异常<2>.        (line   48)
* PyErr_SetFromErrnoWithFilename (C 函数): 抛出异常<2>.      (line   76)
* PyErr_SetFromErrnoWithFilenameObject (C 函数): 抛出异常<2>.
                                                             (line   60)
* PyErr_SetFromErrnoWithFilenameObjects (C 函数): 抛出异常<2>.
                                                             (line   67)
* PyErr_SetFromWindowsErr (C 函数):      抛出异常<2>.        (line   83)
* PyErr_SetFromWindowsErrWithFilename (C 函数): 抛出异常<2>. (line  102)
* PyErr_SetImportError (C 函数):         抛出异常<2>.        (line  140)
* PyErr_SetImportErrorSubclass (C 函数): 警告<3>.            (line   33)
* PyErr_SetInterrupt (C 函数):           信号处理<2>.        (line   18)
* PyErr_SetNone (C 函数):                抛出异常<2>.        (line   34)
* PyErr_SetObject (C 函数):              抛出异常<2>.        (line   15)
* PyErr_SetString (C 函数):              抛出异常<2>.        (line    9)
* PyErr_SetString():                     异常<18>.           (line   23)
* PyErr_SyntaxLocation (C 函数):         抛出异常<2>.        (line  167)
* PyErr_SyntaxLocationEx (C 函数):       抛出异常<2>.        (line  158)
* PyErr_SyntaxLocationObject (C 函数):   抛出异常<2>.        (line  149)
* PyErr_WarnEx (C 函数):                 警告<3>.            (line   15)
* PyErr_WarnExplicit (C 函数):           警告<3>.            (line   53)
* PyErr_WarnExplicitObject (C 函数):     警告<3>.            (line   41)
* PyErr_WarnFormat (C 函数):             警告<3>.            (line   61)
* PyErr_WriteUnraisable (C 函数):        打印和清理.         (line   26)
* PyEval_AcquireLock (C 函数):           Low-level API.      (line  133)
* PyEval_AcquireThread (C 函数):         Low-level API.      (line  100)
* PyEval_AcquireThread():                高阶 API.           (line   29)
* PyEval_EvalCode (C 函数):              The Very High Level Layer.
                                                             (line  327)
* PyEval_EvalCodeEx (C 函数):            The Very High Level Layer.
                                                             (line  334)
* PyEval_EvalFrame (C 函数):             The Very High Level Layer.
                                                             (line  353)
* PyEval_EvalFrameEx (C 函数):           The Very High Level Layer.
                                                             (line  358)
* PyEval_GetBuiltins (C 函数):           反射.               (line    6)
* PyEval_GetFrame (C 函数):              反射.               (line   18)
* PyEval_GetFuncDesc (C 函数):           反射.               (line   31)
* PyEval_GetFuncName (C 函数):           反射.               (line   26)
* PyEval_GetGlobals (C 函数):            反射.               (line   14)
* PyEval_GetLocals (C 函数):             反射.               (line   10)
* PyEval_InitThreads (C 函数):           高阶 API.           (line   27)
* PyEval_InitThreads():                  Initializing and finalizing the interpreter.
                                                             (line    8)
* PyEval_MergeCompilerFlags (C 函数):    The Very High Level Layer.
                                                             (line  371)
* PyEval_ReleaseLock (C 函数):           Low-level API.      (line  155)
* PyEval_ReleaseThread (C 函数):         Low-level API.      (line  122)
* PyEval_ReleaseThread():                高阶 API.           (line   29)
* PyEval_RestoreThread (C 函数):         高阶 API.           (line   62)
* PyEval_RestoreThread():                Releasing the GIL from extension code.
                                                             (line   33)
* PyEval_RestoreThread() <1>:            高阶 API.           (line   29)
* PyEval_SaveThread (C 函数):            高阶 API.           (line   55)
* PyEval_SaveThread():                   Releasing the GIL from extension code.
                                                             (line   33)
* PyEval_SaveThread() <1>:               高阶 API.           (line   29)
* PyEval_SetProfile (C 函数):            分析和跟踪.         (line  116)
* PyEval_SetTrace (C 函数):              分析和跟踪.         (line  126)
* PyEval_ThreadsInitialized (C 函数):    高阶 API.           (line   45)
* PyException_GetCause (C 函数):         异常对象.           (line   29)
* PyException_GetContext (C 函数):       异常对象.           (line   16)
* PyException_GetTraceback (C 函数):     异常对象.           (line    6)
* PyException_SetCause (C 函数):         异常对象.           (line   35)
* PyException_SetContext (C 函数):       异常对象.           (line   23)
* PyException_SetTraceback (C 函数):     异常对象.           (line   12)
* PyExc_ArithmeticError:                 标准异常.           (line   11)
* PyExc_AssertionError:                  标准异常.           (line   11)
* PyExc_AttributeError:                  标准异常.           (line   11)
* PyExc_BaseException:                   标准异常.           (line   11)
* PyExc_BlockingIOError:                 标准异常.           (line   11)
* PyExc_BrokenPipeError:                 标准异常.           (line   11)
* PyExc_BufferError:                     标准异常.           (line   11)
* PyExc_BytesWarning:                    标准警告类别.       (line   11)
* PyExc_ChildProcessError:               标准异常.           (line   11)
* PyExc_ConnectionAbortedError:          标准异常.           (line   11)
* PyExc_ConnectionError:                 标准异常.           (line   11)
* PyExc_ConnectionRefusedError:          标准异常.           (line   11)
* PyExc_ConnectionResetError:            标准异常.           (line   11)
* PyExc_DeprecationWarning:              标准警告类别.       (line   11)
* PyExc_EnvironmentError:                标准异常.           (line  189)
* PyExc_EOFError:                        标准异常.           (line   11)
* PyExc_Exception:                       标准异常.           (line   11)
* PyExc_FileExistsError:                 标准异常.           (line   11)
* PyExc_FileNotFoundError:               标准异常.           (line   11)
* PyExc_FloatingPointError:              标准异常.           (line   11)
* PyExc_FutureWarning:                   标准警告类别.       (line   11)
* PyExc_GeneratorExit:                   标准异常.           (line   11)
* PyExc_ImportError:                     标准异常.           (line   11)
* PyExc_ImportWarning:                   标准警告类别.       (line   11)
* PyExc_IndentationError:                标准异常.           (line   11)
* PyExc_IndexError:                      标准异常.           (line   11)
* PyExc_InterruptedError:                标准异常.           (line   11)
* PyExc_IOError:                         标准异常.           (line  189)
* PyExc_IsADirectoryError:               标准异常.           (line   11)
* PyExc_KeyboardInterrupt:               标准异常.           (line   11)
* PyExc_KeyError:                        标准异常.           (line   11)
* PyExc_LookupError:                     标准异常.           (line   11)
* PyExc_MemoryError:                     标准异常.           (line   11)
* PyExc_ModuleNotFoundError:             标准异常.           (line   11)
* PyExc_NameError:                       标准异常.           (line   11)
* PyExc_NotADirectoryError:              标准异常.           (line   11)
* PyExc_NotImplementedError:             标准异常.           (line   11)
* PyExc_OSError:                         标准异常.           (line   11)
* PyExc_OverflowError:                   标准异常.           (line   11)
* PyExc_PendingDeprecationWarning:       标准警告类别.       (line   11)
* PyExc_PermissionError:                 标准异常.           (line   11)
* PyExc_ProcessLookupError:              标准异常.           (line   11)
* PyExc_RecursionError:                  标准异常.           (line   11)
* PyExc_ReferenceError:                  标准异常.           (line   11)
* PyExc_ResourceWarning:                 标准警告类别.       (line   11)
* PyExc_RuntimeError:                    标准异常.           (line   11)
* PyExc_RuntimeWarning:                  标准警告类别.       (line   11)
* PyExc_StopAsyncIteration:              标准异常.           (line   11)
* PyExc_StopIteration:                   标准异常.           (line   11)
* PyExc_SyntaxError:                     标准异常.           (line   11)
* PyExc_SyntaxWarning:                   标准警告类别.       (line   11)
* PyExc_SystemError:                     标准异常.           (line   11)
* PyExc_SystemExit:                      标准异常.           (line   11)
* PyExc_TabError:                        标准异常.           (line   11)
* PyExc_TimeoutError:                    标准异常.           (line   11)
* PyExc_TypeError:                       标准异常.           (line   11)
* PyExc_UnboundLocalError:               标准异常.           (line   11)
* PyExc_UnicodeDecodeError:              标准异常.           (line   11)
* PyExc_UnicodeEncodeError:              标准异常.           (line   11)
* PyExc_UnicodeError:                    标准异常.           (line   11)
* PyExc_UnicodeTranslateError:           标准异常.           (line   11)
* PyExc_UnicodeWarning:                  标准警告类别.       (line   11)
* PyExc_UserWarning:                     标准警告类别.       (line   11)
* PyExc_ValueError:                      标准异常.           (line   11)
* PyExc_Warning:                         标准警告类别.       (line   11)
* PyExc_WindowsError:                    标准异常.           (line  189)
* PyExc_ZeroDivisionError:               标准异常.           (line   11)
* PyFile_FromFd (C 函数):                文件对象.           (line   12)
* PyFile_GetLine (C 函数):               文件对象.           (line   35)
* PyFile_SetOpenCodeHook (C 函数):       文件对象.           (line   46)
* PyFile_WriteObject (C 函数):           文件对象.           (line   71)
* PyFile_WriteString (C 函数):           文件对象.           (line   79)
* PyFloatObject (C 类型):                浮点数对象.         (line    6)
* PyFloat_AsDouble (C 函数):             浮点数对象.         (line   33)
* PyFloat_AS_DOUBLE (C 函数):            浮点数对象.         (line   43)
* PyFloat_Check (C 函数):                浮点数对象.         (line   15)
* PyFloat_CheckExact (C 函数):           浮点数对象.         (line   20)
* PyFloat_ClearFreeList (C 函数):        浮点数对象.         (line   60)
* PyFloat_FromDouble (C 函数):           浮点数对象.         (line   29)
* PyFloat_FromString (C 函数):           浮点数对象.         (line   25)
* PyFloat_GetInfo (C 函数):              浮点数对象.         (line   47)
* PyFloat_GetMax (C 函数):               浮点数对象.         (line   52)
* PyFloat_GetMin (C 函数):               浮点数对象.         (line   56)
* PyFloat_Type (C 变量):                 浮点数对象.         (line   10)
* PyFrameObject (C 类型):                The Very High Level Layer.
                                                             (line  348)
* PyFrame_GetLineNumber (C 函数):        反射.               (line   22)
* PyFrozenSet_Check (C 函数):            集合对象.           (line   44)
* PyFrozenSet_CheckExact (C 函数):       集合对象.           (line   59)
* PyFrozenSet_New (C 函数):              集合对象.           (line   71)
* PyFrozenSet_Type (C 变量):             集合对象.           (line   31)
* PyFunctionObject (C 类型):             函数对象<3>.        (line    8)
* PyFunction_Check (C 函数):             函数对象<3>.        (line   17)
* PyFunction_GetAnnotations (C 函数):    函数对象<3>.        (line   76)
* PyFunction_GetClosure (C 函数):        函数对象<3>.        (line   65)
* PyFunction_GetCode (C 函数):           函数对象<3>.        (line   40)
* PyFunction_GetDefaults (C 函数):       函数对象<3>.        (line   53)
* PyFunction_GetGlobals (C 函数):        函数对象<3>.        (line   44)
* PyFunction_GetModule (C 函数):         函数对象<3>.        (line   48)
* PyFunction_New (C 函数):               函数对象<3>.        (line   22)
* PyFunction_NewWithQualName (C 函数):   函数对象<3>.        (line   30)
* PyFunction_SetAnnotations (C 函数):    函数对象<3>.        (line   80)
* PyFunction_SetClosure (C 函数):        函数对象<3>.        (line   69)
* PyFunction_SetDefaults (C 函数):       函数对象<3>.        (line   57)
* PyFunction_Type (C 变量):              函数对象<3>.        (line   12)
* PYFUNCTYPE() (在 ctypes 模块中):       函数原型.           (line   28)
* PyGenObject (C 类型):                  生成器对象.         (line   10)
* PyGen_Check (C 函数):                  生成器对象.         (line   18)
* PyGen_CheckExact (C 函数):             生成器对象.         (line   22)
* PyGen_New (C 函数):                    生成器对象.         (line   27)
* PyGen_NewWithQualName (C 函数):        生成器对象.         (line   32)
* PyGen_Type (C 变量):                   生成器对象.         (line   14)
* PyGetSetDef (C 类型):                  公用对象的结构.     (line  354)
* PyGILState_Check (C 函数):             高阶 API.           (line  141)
* PyGILState_Ensure (C 函数):            高阶 API.           (line   91)
* PyGILState_GetThisThreadState (C 函数): 高阶 API.          (line  133)
* PyGILState_Release (C 函数):           高阶 API.           (line  122)
* PyImport_AddModule (C 函数):           导入模块<2>.        (line  109)
* PyImport_AddModuleObject (C 函数):     导入模块<2>.        (line   93)
* PyImport_AppendInittab (C 函数):       导入模块<2>.        (line  276)
* PyImport_Cleanup (C 函数):             导入模块<2>.        (line  231)
* PyImport_ExecCodeModule (C 函数):      导入模块<2>.        (line  114)
* PyImport_ExecCodeModuleEx (C 函数):    导入模块<2>.        (line  150)
* PyImport_ExecCodeModuleObject (C 函数): 导入模块<2>.       (line  160)
* PyImport_ExecCodeModuleWithPathnames (C 函数): 导入模块<2>.
                                                             (line  171)
* PyImport_ExtendInittab (C 函数):       导入模块<2>.        (line  302)
* PyImport_FrozenModules (C 变量):       导入模块<2>.        (line  270)
* PyImport_GetImporter (C 函数):         导入模块<2>.        (line  216)
* PyImport_GetMagicNumber (C 函数):      导入模块<2>.        (line  185)
* PyImport_GetMagicTag (C 函数):         导入模块<2>.        (line  194)
* PyImport_GetModule (C 函数):           导入模块<2>.        (line  208)
* PyImport_GetModuleDict (C 函数):       导入模块<2>.        (line  203)
* PyImport_Import (C 函数):              导入模块<2>.        (line   78)
* PyImport_ImportFrozenModule (C 函数):  导入模块<2>.        (line  252)
* PyImport_ImportFrozenModuleObject (C 函数): 导入模块<2>.   (line  239)
* PyImport_ImportModule (C 函数):        导入模块<2>.        (line    6)
* PyImport_ImportModuleEx (C 函数):      导入模块<2>.        (line   34)
* PyImport_ImportModuleLevel (C 函数):   导入模块<2>.        (line   68)
* PyImport_ImportModuleLevelObject (C 函数): 导入模块<2>.    (line   51)
* PyImport_ImportModuleNoBlock (C 函数): 导入模块<2>.        (line   25)
* PyImport_ReloadModule (C 函数):        导入模块<2>.        (line   88)
* PyIndex_Check (C 函数):                数字协议.           (line  219)
* PyInit_modulename (C 函数):            构建C/C++扩展.      (line   14)
* PyInstanceMethod_Check (C 函数):       实例方法对象.       (line   15)
* PyInstanceMethod_Function (C 函数):    实例方法对象.       (line   24)
* PyInstanceMethod_GET_FUNCTION (C 函数): 实例方法对象.      (line   28)
* PyInstanceMethod_New (C 函数):         实例方法对象.       (line   20)
* PyInstanceMethod_Type (C 变量):        实例方法对象.       (line   10)
* PyInterpreterState (C 类型):           高阶 API.           (line    9)
* PyInterpreterState_Clear (C 函数):     Low-level API.      (line   21)
* PyInterpreterState_Delete (C 函数):    Low-level API.      (line   29)
* PyInterpreterState_GetDict (C 函数):   Low-level API.      (line   61)
* PyInterpreterState_GetID (C 函数):     Low-level API.      (line   53)
* PyInterpreterState_Head (C 函数):      高级调试器支持.     (line    9)
* PyInterpreterState_Main (C 函数):      高级调试器支持.     (line   14)
* PyInterpreterState_New (C 函数):       Low-level API.      (line   12)
* PyInterpreterState_Next (C 函数):      高级调试器支持.     (line   18)
* PyInterpreterState_ThreadHead (C 函数): 高级调试器支持.    (line   25)
* PyIter_Check (C 函数):                 迭代器协议.         (line    8)
* PyIter_Next (C 函数):                  迭代器协议.         (line   12)
* PyListObject (C 类型):                 列表对象.           (line    6)
* PyList_Append (C 函数):                列表对象.           (line   79)
* PyList_AsTuple (C 函数):               列表对象.           (line  110)
* PyList_Check (C 函数):                 列表对象.           (line   15)
* PyList_CheckExact (C 函数):            列表对象.           (line   19)
* PyList_ClearFreeList (C 函数):         列表对象.           (line  115)
* PyList_GetItem (C 函数):               列表对象.           (line   40)
* PyList_GetItem():                      引用计数细节.       (line  117)
* PyList_GetSlice (C 函数):              列表对象.           (line   84)
* PyList_GET_ITEM (C 函数):              列表对象.           (line   46)
* PyList_GET_SIZE (C 函数):              列表对象.           (line   36)
* PyList_Insert (C 函数):                列表对象.           (line   71)
* PyList_New (C 函数):                   列表对象.           (line   23)
* PyList_Reverse (C 函数):               列表对象.           (line  105)
* PyList_SetItem (C 函数):               列表对象.           (line   50)
* PyList_SetItem():                      引用计数细节.       (line   26)
* PyList_SetSlice (C 函数):              列表对象.           (line   91)
* PyList_SET_ITEM (C 函数):              列表对象.           (line   60)
* PyList_Size (C 函数):                  列表对象.           (line   32)
* PyList_Sort (C 函数):                  列表对象.           (line  100)
* PyList_Type (C 变量):                  列表对象.           (line   10)
* PyLongObject (C 类型):                 整数型对象.         (line   11)
* PyLong_AsDouble (C 函数):              整数型对象.         (line  247)
* PyLong_AsLong (C 函数):                整数型对象.         (line   95)
* PyLong_AsLongAndOverflow (C 函数):     整数型对象.         (line  111)
* PyLong_AsLongLong (C 函数):            整数型对象.         (line  129)
* PyLong_AsLongLongAndOverflow (C 函数): 整数型对象.         (line  144)
* PyLong_AsSize_t (C 函数):              整数型对象.         (line  186)
* PyLong_AsSsize_t (C 函数):             整数型对象.         (line  165)
* PyLong_AsUnsignedLong (C 函数):        整数型对象.         (line  175)
* PyLong_AsUnsignedLongLong (C 函数):    整数型对象.         (line  197)
* PyLong_AsUnsignedLongLongMask (C 函数): 整数型对象.        (line  229)
* PyLong_AsUnsignedLongMask (C 函数):    整数型对象.         (line  212)
* PyLong_AsVoidPtr (C 函数):             整数型对象.         (line  258)
* PyLong_Check (C 函数):                 整数型对象.         (line   20)
* PyLong_CheckExact (C 函数):            整数型对象.         (line   25)
* PyLong_FromDouble (C 函数):            整数型对象.         (line   60)
* PyLong_FromLong (C 函数):              整数型对象.         (line   30)
* PyLong_FromLongLong (C 函数):          整数型对象.         (line   52)
* PyLong_FromSize_t (C 函数):            整数型对象.         (line   48)
* PyLong_FromSsize_t (C 函数):           整数型对象.         (line   44)
* PyLong_FromString (C 函数):            整数型对象.         (line   64)
* PyLong_FromUnicode (C 函数):           整数型对象.         (line   76)
* PyLong_FromUnicodeObject (C 函数):     整数型对象.         (line   85)
* PyLong_FromUnsignedLong (C 函数):      整数型对象.         (line   40)
* PyLong_FromUnsignedLongLong (C 函数):  整数型对象.         (line   56)
* PyLong_FromVoidPtr (C 函数):           整数型对象.         (line   91)
* PyLong_Type (C 变量):                  整数型对象.         (line   15)
* PyMappingMethods (C 类型):             Mapping Object Structures.
                                                             (line    6)
* PyMappingMethods.mp_ass_subscript (C 成员): Mapping Object Structures.
                                                             (line   25)
* PyMappingMethods.mp_length (C 成员):   Mapping Object Structures.
                                                             (line   11)
* PyMappingMethods.mp_subscript (C 成员): Mapping Object Structures.
                                                             (line   17)
* PyMapping_Check (C 函数):              映射协议.           (line    9)
* PyMapping_DelItem (C 函数):            映射协议.           (line   35)
* PyMapping_DelItemString (C 函数):      映射协议.           (line   41)
* PyMapping_GetItemString (C 函数):      映射协议.           (line   21)
* PyMapping_HasKey (C 函数):             映射协议.           (line   46)
* PyMapping_HasKeyString (C 函数):       映射协议.           (line   54)
* PyMapping_Items (C 函数):              映射协议.           (line   74)
* PyMapping_Keys (C 函数):               映射协议.           (line   62)
* PyMapping_Length (C 函数):             映射协议.           (line   15)
* PyMapping_SetItemString (C 函数):      映射协议.           (line   27)
* PyMapping_Size (C 函数):               映射协议.           (line   15)
* PyMapping_Values (C 函数):             映射协议.           (line   68)
* PyMarshal_ReadLastObjectFromFile (C 函数): 数据 marshal 操作支持.
                                                             (line   58)
* PyMarshal_ReadLongFromFile (C 函数):   数据 marshal 操作支持.
                                                             (line   37)
* PyMarshal_ReadObjectFromFile (C 函数): 数据 marshal 操作支持.
                                                             (line   51)
* PyMarshal_ReadObjectFromString (C 函数): 数据 marshal 操作支持.
                                                             (line   69)
* PyMarshal_ReadShortFromFile (C 函数):  数据 marshal 操作支持.
                                                             (line   44)
* PyMarshal_WriteLongToFile (C 函数):    数据 marshal 操作支持.
                                                             (line   16)
* PyMarshal_WriteObjectToFile (C 函数):  数据 marshal 操作支持.
                                                             (line   23)
* PyMarshal_WriteObjectToString (C 函数): 数据 marshal 操作支持.
                                                             (line   29)
* PyMemAllocatorDomain (C 类型):         自定义内存分配器.   (line   34)
* PyMemAllocatorEx (C 类型):             自定义内存分配器.   (line    8)
* PyMemberDef (C 类型):                  公用对象的结构.     (line  251)
* PyMemoryView_Check (C 函数):           MemoryView 对象.    (line   34)
* PyMemoryView_FromBuffer (C 函数):      MemoryView 对象.    (line   22)
* PyMemoryView_FromMemory (C 函数):      MemoryView 对象.    (line   14)
* PyMemoryView_FromObject (C 函数):      MemoryView 对象.    (line    9)
* PyMemoryView_GetContiguous (C 函数):   MemoryView 对象.    (line   27)
* PyMemoryView_GET_BASE (C 函数):        MemoryView 对象.    (line   45)
* PyMemoryView_GET_BUFFER (C 函数):      MemoryView 对象.    (line   39)
* PyMem_Calloc (C 函数):                 内存接口.           (line   24)
* PyMem_Del (C 函数):                    内存接口.           (line   77)
* PYMEM_DOMAIN_MEM (C 宏):               自定义内存分配器.   (line   50)
* PYMEM_DOMAIN_OBJ (C 宏):               自定义内存分配器.   (line   62)
* PYMEM_DOMAIN_RAW (C 宏):               自定义内存分配器.   (line   38)
* PyMem_Free (C 函数):                   内存接口.           (line   51)
* PyMem_GetAllocator (C 函数):           自定义内存分配器.   (line   74)
* PyMem_Malloc (C 函数):                 内存接口.           (line   15)
* PyMem_New (C 函数):                    内存接口.           (line   62)
* PyMem_RawCalloc (C 函数):              原始内存接口.       (line   25)
* PyMem_RawFree (C 函数):                原始内存接口.       (line   52)
* PyMem_RawMalloc (C 函数):              原始内存接口.       (line   16)
* PyMem_RawRealloc (C 函数):             原始内存接口.       (line   37)
* PyMem_Realloc (C 函数):                内存接口.           (line   36)
* PyMem_Resize (C 函数):                 内存接口.           (line   68)
* PyMem_SetAllocator (C 函数):           自定义内存分配器.   (line   80)
* PyMem_SetupDebugHooks (C 函数):        自定义内存分配器.   (line   94)
* PyMethodDef (C 类型):                  公用对象的结构.     (line  115)
* PyMethod_Check (C 函数):               方法对象<2>.        (line   14)
* PyMethod_ClearFreeList (C 函数):       方法对象<2>.        (line   39)
* PyMethod_Function (C 函数):            方法对象<2>.        (line   24)
* PyMethod_GET_FUNCTION (C 函数):        方法对象<2>.        (line   28)
* PyMethod_GET_SELF (C 函数):            方法对象<2>.        (line   35)
* PyMethod_New (C 函数):                 方法对象<2>.        (line   19)
* PyMethod_Self (C 函数):                方法对象<2>.        (line   32)
* PyMethod_Type (C 变量):                方法对象<2>.        (line    9)
* PyModuleDef (C 类型):                  Initializing C modules.
                                                             (line   17)
* PyModuleDef.m_base (C 成员):           Initializing C modules.
                                                             (line   23)
* PyModuleDef.m_clear (C 成员):          Initializing C modules.
                                                             (line   82)
* PyModuleDef.m_doc (C 成员):            Initializing C modules.
                                                             (line   31)
* PyModuleDef.m_free (C 成员):           Initializing C modules.
                                                             (line   90)
* PyModuleDef.m_methods (C 成员):        Initializing C modules.
                                                             (line   57)
* PyModuleDef.m_name (C 成员):           Initializing C modules.
                                                             (line   27)
* PyModuleDef.m_reload (C 成员):         Initializing C modules.
                                                             (line   72)
* PyModuleDef.m_size (C 成员):           Initializing C modules.
                                                             (line   36)
* PyModuleDef.m_slots (C 成员):          Initializing C modules.
                                                             (line   63)
* PyModuleDef.m_traverse (C 成员):       Initializing C modules.
                                                             (line   74)
* PyModuleDef_Init (C 函数):             Multi-phase initialization.
                                                             (line   33)
* PyModuleDef_Slot (C 类型):             Multi-phase initialization.
                                                             (line   45)
* PyModuleDef_Slot.slot (C 成员):        Multi-phase initialization.
                                                             (line   47)
* PyModuleDef_Slot.value (C 成员):       Multi-phase initialization.
                                                             (line   51)
* PyModule_AddFunctions (C 函数):        Low-level module creation functions.
                                                             (line   52)
* PyModule_AddIntConstant (C 函数):      Support functions.  (line   35)
* PyModule_AddIntMacro (C 函数):         Support functions.  (line   51)
* PyModule_AddObject (C 函数):           Support functions.  (line   11)
* PyModule_AddStringConstant (C 函数):   Support functions.  (line   42)
* PyModule_AddStringMacro (C 函数):      Support functions.  (line   58)
* PyModule_Check (C 函数):               模块对象.           (line   12)
* PyModule_CheckExact (C 函数):          模块对象.           (line   17)
* PyModule_Create (C 函数):              Single-phase initialization.
                                                             (line   10)
* PyModule_Create2 (C 函数):             Single-phase initialization.
                                                             (line   16)
* PyModule_ExecDef (C 函数):             Low-level module creation functions.
                                                             (line   36)
* PyModule_FromDefAndSpec (C 函数):      Low-level module creation functions.
                                                             (line   11)
* PyModule_FromDefAndSpec2 (C 函数):     Low-level module creation functions.
                                                             (line   21)
* PyModule_GetDef (C 函数):              模块对象.           (line   74)
* PyModule_GetDict (C 函数):             模块对象.           (line   41)
* PyModule_GetFilename (C 函数):         模块对象.           (line   90)
* PyModule_GetFilenameObject (C 函数):   模块对象.           (line   80)
* PyModule_GetName (C 函数):             模块对象.           (line   63)
* PyModule_GetNameObject (C 函数):       模块对象.           (line   54)
* PyModule_GetState (C 函数):            模块对象.           (line   68)
* PyModule_New (C 函数):                 模块对象.           (line   36)
* PyModule_NewObject (C 函数):           模块对象.           (line   22)
* PyModule_SetDocString (C 函数):        Low-level module creation functions.
                                                             (line   43)
* PyModule_Type (C 变量):                模块对象.           (line    6)
* PyNumberMethods (C 类型):              Number Object Structures.
                                                             (line    6)
* PyNumberMethods.nb_absolute (C 成员):  Number Object Structures.
                                                             (line   85)
* PyNumberMethods.nb_add (C 成员):       Number Object Structures.
                                                             (line   69)
* PyNumberMethods.nb_and (C 成员):       Number Object Structures.
                                                             (line   95)
* PyNumberMethods.nb_bool (C 成员):      Number Object Structures.
                                                             (line   87)
* PyNumberMethods.nb_divmod (C 成员):    Number Object Structures.
                                                             (line   77)
* PyNumberMethods.nb_float (C 成员):     Number Object Structures.
                                                             (line  105)
* PyNumberMethods.nb_floor_divide (C 成员): Number Object Structures.
                                                             (line  127)
* PyNumberMethods.nb_index (C 成员):     Number Object Structures.
                                                             (line  135)
* PyNumberMethods.nb_inplace_add (C 成员): Number Object Structures.
                                                             (line  107)
* PyNumberMethods.nb_inplace_and (C 成员): Number Object Structures.
                                                             (line  121)
* PyNumberMethods.nb_inplace_floor_divide (C 成员): Number Object Structures.
                                                             (line  131)
* PyNumberMethods.nb_inplace_lshift (C 成员): Number Object Structures.
                                                             (line  117)
* PyNumberMethods.nb_inplace_matrix_multiply (C 成员): Number Object Structures.
                                                             (line  139)
* PyNumberMethods.nb_inplace_multiply (C 成员): Number Object Structures.
                                                             (line  111)
* PyNumberMethods.nb_inplace_or (C 成员): Number Object Structures.
                                                             (line  125)
* PyNumberMethods.nb_inplace_power (C 成员): Number Object Structures.
                                                             (line  115)
* PyNumberMethods.nb_inplace_remainder (C 成员): Number Object Structures.
                                                             (line  113)
* PyNumberMethods.nb_inplace_rshift (C 成员): Number Object Structures.
                                                             (line  119)
* PyNumberMethods.nb_inplace_subtract (C 成员): Number Object Structures.
                                                             (line  109)
* PyNumberMethods.nb_inplace_true_divide (C 成员): Number Object Structures.
                                                             (line  133)
* PyNumberMethods.nb_inplace_xor (C 成员): Number Object Structures.
                                                             (line  123)
* PyNumberMethods.nb_int (C 成员):       Number Object Structures.
                                                             (line  101)
* PyNumberMethods.nb_invert (C 成员):    Number Object Structures.
                                                             (line   89)
* PyNumberMethods.nb_lshift (C 成员):    Number Object Structures.
                                                             (line   91)
* PyNumberMethods.nb_matrix_multiply (C 成员): Number Object Structures.
                                                             (line  137)
* PyNumberMethods.nb_multiply (C 成员):  Number Object Structures.
                                                             (line   73)
* PyNumberMethods.nb_negative (C 成员):  Number Object Structures.
                                                             (line   81)
* PyNumberMethods.nb_or (C 成员):        Number Object Structures.
                                                             (line   99)
* PyNumberMethods.nb_positive (C 成员):  Number Object Structures.
                                                             (line   83)
* PyNumberMethods.nb_power (C 成员):     Number Object Structures.
                                                             (line   79)
* PyNumberMethods.nb_remainder (C 成员): Number Object Structures.
                                                             (line   75)
* PyNumberMethods.nb_reserved (C 成员):  Number Object Structures.
                                                             (line  103)
* PyNumberMethods.nb_rshift (C 成员):    Number Object Structures.
                                                             (line   93)
* PyNumberMethods.nb_subtract (C 成员):  Number Object Structures.
                                                             (line   71)
* PyNumberMethods.nb_true_divide (C 成员): Number Object Structures.
                                                             (line  129)
* PyNumberMethods.nb_xor (C 成员):       Number Object Structures.
                                                             (line   97)
* PyNumber_Absolute (C 函数):            数字协议.           (line   70)
* PyNumber_Add (C 函数):                 数字协议.           (line   13)
* PyNumber_And (C 函数):                 数字协议.           (line   88)
* PyNumber_AsSsize_t (C 函数):           数字协议.           (line  208)
* PyNumber_Check (C 函数):               数字协议.           (line    6)
* PyNumber_Divmod (C 函数):              数字协议.           (line   46)
* PyNumber_Float (C 函数):               数字协议.           (line  191)
* PyNumber_FloorDivide (C 函数):         数字协议.           (line   32)
* PyNumber_Index (C 函数):               数字协议.           (line  197)
* PyNumber_InPlaceAdd (C 函数):          数字协议.           (line  100)
* PyNumber_InPlaceAnd (C 函数):          数字协议.           (line  170)
* PyNumber_InPlaceFloorDivide (C 函数):  数字协议.           (line  127)
* PyNumber_InPlaceLshift (C 函数):       数字协议.           (line  158)
* PyNumber_InPlaceMatrixMultiply (C 函数): 数字协议.         (line  118)
* PyNumber_InPlaceMultiply (C 函数):     数字协议.           (line  111)
* PyNumber_InPlaceOr (C 函数):           数字协议.           (line  180)
* PyNumber_InPlacePower (C 函数):        数字协议.           (line  148)
* PyNumber_InPlaceRemainder (C 函数):    数字协议.           (line  142)
* PyNumber_InPlaceRshift (C 函数):       数字协议.           (line  164)
* PyNumber_InPlaceSubtract (C 函数):     数字协议.           (line  105)
* PyNumber_InPlaceTrueDivide (C 函数):   数字协议.           (line  134)
* PyNumber_InPlaceXor (C 函数):          数字协议.           (line  175)
* PyNumber_Invert (C 函数):              数字协议.           (line   76)
* PyNumber_Long (C 函数):                数字协议.           (line  185)
* PyNumber_Lshift (C 函数):              数字协议.           (line   80)
* PyNumber_MatrixMultiply (C 函数):      数字协议.           (line   25)
* PyNumber_Multiply (C 函数):            数字协议.           (line   21)
* PyNumber_Negative (C 函数):            数字协议.           (line   62)
* PyNumber_Or (C 函数):                  数字协议.           (line   96)
* PyNumber_Positive (C 函数):            数字协议.           (line   66)
* PyNumber_Power (C 函数):               数字协议.           (line   52)
* PyNumber_Remainder (C 函数):           数字协议.           (line   42)
* PyNumber_Rshift (C 函数):              数字协议.           (line   84)
* PyNumber_Subtract (C 函数):            数字协议.           (line   17)
* PyNumber_ToBase (C 函数):              数字协议.           (line  201)
* PyNumber_TrueDivide (C 函数):          数字协议.           (line   36)
* PyNumber_Xor (C 函数):                 数字协议.           (line   92)
* PyObject (C 类型):                     公用对象的结构.     (line   13)
* PyObject.ob_refcnt (C 成员):           PyObject Slots.     (line   30)
* PyObject.ob_type (C 成员):             PyObject Slots.     (line   43)
* PyObject._ob_next (C 成员):            PyObject Slots.     (line   13)
* PyObject._ob_prev (C 成员):            PyObject Slots.     (line   13)
* PyObjectArenaAllocator (C 类型):       自定义 pymalloc Arena 分配器.
                                                             (line    8)
* PyObject_AsCharBuffer (C 函数):        旧缓冲协议.         (line   18)
* PyObject_ASCII (C 函数):               对象协议.           (line  148)
* PyObject_AsFileDescriptor (C 函数):    文件对象.           (line   28)
* PyObject_AsReadBuffer (C 函数):        旧缓冲协议.         (line   26)
* PyObject_AsWriteBuffer (C 函数):       旧缓冲协议.         (line   43)
* PyObject_Bytes (C 函数):               对象协议.           (line  166)
* PyObject_Call (C 函数):                对象协议.           (line  214)
* PyObject_CallFunction (C 函数):        对象协议.           (line  239)
* PyObject_CallFunctionObjArgs (C 函数): 对象协议.           (line  279)
* PyObject_CallMethod (C 函数):          对象协议.           (line  258)
* PyObject_CallMethodObjArgs (C 函数):   对象协议.           (line  291)
* PyObject_CallObject (C 函数):          对象协议.           (line  228)
* PyObject_CallObject():                 在C中调用Python函数.
                                                             (line   51)
* PyObject_Calloc (C 函数):              对象分配器.         (line   22)
* PyObject_CheckBuffer (C 函数):         缓冲区相关函数.     (line    6)
* PyObject_CheckReadBuffer (C 函数):     旧缓冲协议.         (line   34)
* PyObject_Del (C 函数):                 在堆上分配对象.     (line   41)
* PyObject_DelAttr (C 函数):             对象协议.           (line   89)
* PyObject_DelAttrString (C 函数):       对象协议.           (line   94)
* PyObject_DelItem (C 函数):             对象协议.           (line  444)
* PyObject_Dir (C 函数):                 对象协议.           (line  449)
* PyObject_Free (C 函数):                对象分配器.         (line   49)
* PyObject_GC_Del (C 函数):              使对象类型支持循环垃圾回收.
                                                             (line   59)
* PyObject_GC_New (C 函数):              使对象类型支持循环垃圾回收.
                                                             (line   27)
* PyObject_GC_NewVar (C 函数):           使对象类型支持循环垃圾回收.
                                                             (line   32)
* PyObject_GC_Resize (C 函数):           使对象类型支持循环垃圾回收.
                                                             (line   39)
* PyObject_GC_Track (C 函数):            使对象类型支持循环垃圾回收.
                                                             (line   45)
* PyObject_GC_UnTrack (C 函数):          使对象类型支持循环垃圾回收.
                                                             (line   64)
* PyObject_GenericGetAttr (C 函数):      对象协议.           (line   52)
* PyObject_GenericGetDict (C 函数):      对象协议.           (line  100)
* PyObject_GenericSetAttr (C 函数):      对象协议.           (line   79)
* PyObject_GenericSetDict (C 函数):      对象协议.           (line  107)
* PyObject_GetArenaAllocator (C 函数):   自定义 pymalloc Arena 分配器.
                                                             (line   25)
* PyObject_GetAttr (C 函数):             对象协议.           (line   40)
* PyObject_GetAttrString (C 函数):       对象协议.           (line   46)
* PyObject_GetBuffer (C 函数):           缓冲区相关函数.     (line   13)
* PyObject_GetItem (C 函数):             对象协议.           (line  433)
* PyObject_GetIter (C 函数):             对象协议.           (line  456)
* PyObject_HasAttr (C 函数):             对象协议.           (line   21)
* PyObject_HasAttrString (C 函数):       对象协议.           (line   30)
* PyObject_Hash (C 函数):                对象协议.           (line  378)
* PyObject_HashNotImplemented (C 函数):  对象协议.           (line  386)
* PyObject_HEAD (C 宏):                  公用对象的结构.     (line   33)
* PyObject_HEAD_INIT (C 宏):             公用对象的结构.     (line   74)
* PyObject_Init (C 函数):                在堆上分配对象.     (line   14)
* PyObject_InitVar (C 函数):             在堆上分配对象.     (line   19)
* PyObject_IsInstance (C 函数):          对象协议.           (line  191)
* PyObject_IsSubclass (C 函数):          对象协议.           (line  174)
* PyObject_IsTrue (C 函数):              对象协议.           (line  392)
* PyObject_Length (C 函数):              对象协议.           (line  416)
* PyObject_LengthHint (C 函数):          对象协议.           (line  422)
* PyObject_Malloc (C 函数):              对象分配器.         (line   13)
* PyObject_New (C 函数):                 在堆上分配对象.     (line   25)
* PyObject_NewVar (C 函数):              在堆上分配对象.     (line   31)
* PyObject_Not (C 函数):                 对象协议.           (line  397)
* PyObject_Print (C 函数):               对象协议.           (line   15)
* PyObject_Realloc (C 函数):             对象分配器.         (line   34)
* PyObject_Repr (C 函数):                对象协议.           (line  138)
* PyObject_RichCompare (C 函数):         对象协议.           (line  115)
* PyObject_RichCompareBool (C 函数):     对象协议.           (line  124)
* PyObject_SetArenaAllocator (C 函数):   自定义 pymalloc Arena 分配器.
                                                             (line   30)
* PyObject_SetAttr (C 函数):             对象协议.           (line   60)
* PyObject_SetAttrString (C 函数):       对象协议.           (line   70)
* PyObject_SetItem (C 函数):             对象协议.           (line  437)
* PyObject_Size (C 函数):                对象协议.           (line  416)
* PyObject_Str (C 函数):                 对象协议.           (line  157)
* PyObject_Type (C 函数):                对象协议.           (line  402)
* PyObject_TypeCheck (C 函数):           对象协议.           (line  411)
* PyObject_VAR_HEAD (C 宏):              公用对象的结构.     (line   43)
* PyOS_AfterFork (C 函数):               操作系统实用程序.   (line   75)
* PyOS_AfterFork_Child (C 函数):         操作系统实用程序.   (line   53)
* PyOS_AfterFork_Parent (C 函数):        操作系统实用程序.   (line   39)
* PyOS_BeforeFork (C 函数):              操作系统实用程序.   (line   26)
* PyOS_CheckStack (C 函数):              操作系统实用程序.   (line   85)
* PyOS_double_to_string (C 函数):        字符串转换与格式化. (line   73)
* PyOS_FSPath (C 函数):                  操作系统实用程序.   (line    6)
* PyOS_getsig (C 函数):                  操作系统实用程序.   (line   93)
* PyOS_InputHook (C 变量):               The Very High Level Layer.
                                                             (line  161)
* PyOS_ReadlineFunctionPointer (C 变量): The Very High Level Layer.
                                                             (line  171)
* PyOS_setsig (C 函数):                  操作系统实用程序.   (line  100)
* PyOS_snprintf (C 函数):                字符串转换与格式化. (line    8)
* PyOS_stricmp (C 函数):                 字符串转换与格式化. (line  105)
* PyOS_string_to_double (C 函数):        字符串转换与格式化. (line   45)
* PyOS_strnicmp (C 函数):                字符串转换与格式化. (line  110)
* PyOS_vsnprintf (C 函数):               字符串转换与格式化. (line   14)
* PyParser_SimpleParseFile (C 函数):     The Very High Level Layer.
                                                             (line  217)
* PyParser_SimpleParseFileFlags (C 函数): The Very High Level Layer.
                                                             (line  225)
* PyParser_SimpleParseString (C 函数):   The Very High Level Layer.
                                                             (line  192)
* PyParser_SimpleParseStringFlags (C 函数): The Very High Level Layer.
                                                             (line  200)
* PyParser_SimpleParseStringFlagsFilename (C 函数): The Very High Level Layer.
                                                             (line  207)
* PyPI; (see Python Package Index (PyPI)): 安装相关工具.     (line   20)
* PyPreConfig (C 类型):                  PyPreConfig.        (line    6)
* PyPreConfig.allocator (C 成员):        PyPreConfig.        (line   32)
* PyPreConfig.coerce_c_locale (C 成员):  PyPreConfig.        (line   68)
* PyPreConfig.coerce_c_locale_warn (C 成员): PyPreConfig.    (line   73)
* PyPreConfig.configure_locale (C 成员): PyPreConfig.        (line   62)
* PyPreConfig.dev_mode (C 成员):         PyPreConfig.        (line   77)
* PyPreConfig.isolated (C 成员):         PyPreConfig.        (line   81)
* PyPreConfig.legacy_windows_fs_encoding (C 成员): PyPreConfig.
                                                             (line   85)
* PyPreConfig.parse_argv (C 成员):       PyPreConfig.        (line   94)
* PyPreConfig.use_environment (C 成员):  PyPreConfig.        (line  101)
* PyPreConfig.utf8_mode (C 成员):        PyPreConfig.        (line  105)
* PyPreConfig_InitIsolatedConfig (C 函数): PyPreConfig.      (line   24)
* PyPreConfig_InitPythonConfig (C 函数): PyPreConfig.        (line   18)
* PyProperty_Type (C 变量):              描述符对象.         (line    8)
* PyRun_AnyFile (C 函数):                The Very High Level Layer.
                                                             (line   48)
* PyRun_AnyFileEx (C 函数):              The Very High Level Layer.
                                                             (line   61)
* PyRun_AnyFileExFlags (C 函数):         The Very High Level Layer.
                                                             (line   67)
* PyRun_AnyFileFlags (C 函数):           The Very High Level Layer.
                                                             (line   54)
* PyRun_File (C 函数):                   The Very High Level Layer.
                                                             (line  252)
* PyRun_FileEx (C 函数):                 The Very High Level Layer.
                                                             (line  258)
* PyRun_FileExFlags (C 函数):            The Very High Level Layer.
                                                             (line  273)
* PyRun_FileFlags (C 函数):              The Very High Level Layer.
                                                             (line  264)
* PyRun_InteractiveLoop (C 函数):        The Very High Level Layer.
                                                             (line  146)
* PyRun_InteractiveLoopFlags (C 函数):   The Very High Level Layer.
                                                             (line  152)
* PyRun_InteractiveOne (C 函数):         The Very High Level Layer.
                                                             (line  125)
* PyRun_InteractiveOneFlags (C 函数):    The Very High Level Layer.
                                                             (line  131)
* PyRun_SimpleFile (C 函数):             The Very High Level Layer.
                                                             (line  100)
* PyRun_SimpleFileEx (C 函数):           The Very High Level Layer.
                                                             (line  105)
* PyRun_SimpleFileExFlags (C 函数):      The Very High Level Layer.
                                                             (line  111)
* PyRun_SimpleString (C 函数):           The Very High Level Layer.
                                                             (line   79)
* PyRun_SimpleStringFlags (C 函数):      The Very High Level Layer.
                                                             (line   85)
* PyRun_String (C 函数):                 The Very High Level Layer.
                                                             (line  232)
* PyRun_StringFlags (C 函数):            The Very High Level Layer.
                                                             (line  239)
* PySeqIter_Check (C 函数):              迭代器对象.         (line   15)
* PySeqIter_New (C 函数):                迭代器对象.         (line   19)
* PySeqIter_Type (C 变量):               迭代器对象.         (line   10)
* PySequenceMethods (C 类型):            Sequence Object Structures.
                                                             (line    6)
* PySequenceMethods.sq_ass_item (C 成员): Sequence Object Structures.
                                                             (line   45)
* PySequenceMethods.sq_concat (C 成员):  Sequence Object Structures.
                                                             (line   18)
* PySequenceMethods.sq_contains (C 成员): Sequence Object Structures.
                                                             (line   54)
* PySequenceMethods.sq_inplace_concat (C 成员): Sequence Object Structures.
                                                             (line   61)
* PySequenceMethods.sq_inplace_repeat (C 成员): Sequence Object Structures.
                                                             (line   71)
* PySequenceMethods.sq_item (C 成员):    Sequence Object Structures.
                                                             (line   31)
* PySequenceMethods.sq_length (C 成员):  Sequence Object Structures.
                                                             (line   11)
* PySequenceMethods.sq_repeat (C 成员):  Sequence Object Structures.
                                                             (line   24)
* PySequence_Check (C 函数):             序列协议.           (line    6)
* PySequence_Concat (C 函数):            序列协议.           (line   20)
* PySequence_Contains (C 函数):          序列协议.           (line   85)
* PySequence_Count (C 函数):             序列协议.           (line   80)
* PySequence_DelItem (C 函数):           序列协议.           (line   61)
* PySequence_DelSlice (C 函数):          序列协议.           (line   73)
* PySequence_Fast (C 函数):              序列协议.           (line  109)
* PySequence_Fast_GET_ITEM (C 函数):     序列协议.           (line  130)
* PySequence_Fast_GET_SIZE (C 函数):     序列协议.           (line  122)
* PySequence_Fast_ITEMS (C 函数):        序列协议.           (line  136)
* PySequence_GetItem (C 函数):           序列协议.           (line   41)
* PySequence_GetItem():                  引用计数细节.       (line  117)
* PySequence_GetSlice (C 函数):          序列协议.           (line   45)
* PySequence_Index (C 函数):             序列协议.           (line   91)
* PySequence_InPlaceConcat (C 函数):     序列协议.           (line   28)
* PySequence_InPlaceRepeat (C 函数):     序列协议.           (line   34)
* PySequence_ITEM (C 函数):              序列协议.           (line  144)
* PySequence_Length (C 函数):            序列协议.           (line   13)
* PySequence_List (C 函数):              序列协议.           (line   97)
* PySequence_Repeat (C 函数):            序列协议.           (line   24)
* PySequence_SetItem (C 函数):           序列协议.           (line   51)
* PySequence_SetSlice (C 函数):          序列协议.           (line   66)
* PySequence_Size (C 函数):              序列协议.           (line   13)
* PySequence_Tuple (C 函数):             序列协议.           (line  102)
* PySetObject (C 类型):                  集合对象.           (line   17)
* PySet_Add (C 函数):                    集合对象.           (line   98)
* PySet_Check (C 函数):                  集合对象.           (line   39)
* PySet_Clear (C 函数):                  集合对象.           (line  126)
* PySet_ClearFreeList (C 函数):          集合对象.           (line  130)
* PySet_Contains (C 函数):               集合对象.           (line   90)
* PySet_Discard (C 函数):                集合对象.           (line  111)
* PySet_GET_SIZE (C 函数):               集合对象.           (line   86)
* PySet_New (C 函数):                    集合对象.           (line   64)
* PySet_Pop (C 函数):                    集合对象.           (line  120)
* PySet_Size (C 函数):                   集合对象.           (line   80)
* PySet_Type (C 变量):                   集合对象.           (line   26)
* PySignal_SetWakeupFd (C 函数):         信号处理<2>.        (line   28)
* PySlice_AdjustIndices (C 函数):        切片对象.           (line   90)
* PySlice_Check (C 函数):                切片对象.           (line   11)
* PySlice_GetIndices (C 函数):           切片对象.           (line   23)
* PySlice_GetIndicesEx (C 函数):         切片对象.           (line   38)
* PySlice_New (C 函数):                  切片对象.           (line   15)
* PySlice_Type (C 变量):                 切片对象.           (line    6)
* PySlice_Unpack (C 函数):               切片对象.           (line   77)
* PyState_AddModule (C 函数):            Module lookup.      (line   23)
* PyState_FindModule (C 函数):           Module lookup.      (line   15)
* PyState_RemoveModule (C 函数):         Module lookup.      (line   44)
* PyStatus (C 类型):                     PyStatus.           (line    6)
* PyStatus.err_msg (C 成员):             PyStatus.           (line   20)
* PyStatus.exitcode (C 成员):            PyStatus.           (line   16)
* PyStatus.func (C 成员):                PyStatus.           (line   24)
* PyStatus_Error (C 函数):               PyStatus.           (line   34)
* PyStatus_Exception (C 函数):           PyStatus.           (line   48)
* PyStatus_Exit (C 函数):                PyStatus.           (line   42)
* PyStatus_IsError (C 函数):             PyStatus.           (line   54)
* PyStatus_IsExit (C 函数):              PyStatus.           (line   58)
* PyStatus_NoMemory (C 函数):            PyStatus.           (line   38)
* PyStatus_Ok (C 函数):                  PyStatus.           (line   30)
* PyStructSequence_Desc (C 类型):        结构序列对象.       (line   32)
* PyStructSequence_Field (C 类型):       结构序列对象.       (line   54)
* PyStructSequence_GetItem (C 函数):     结构序列对象.       (line   81)
* PyStructSequence_GET_ITEM (C 函数):    结构序列对象.       (line   86)
* PyStructSequence_InitType (C 函数):    结构序列对象.       (line   17)
* PyStructSequence_InitType2 (C 函数):   结构序列对象.       (line   23)
* PyStructSequence_New (C 函数):         结构序列对象.       (line   77)
* PyStructSequence_NewType (C 函数):     结构序列对象.       (line   10)
* PyStructSequence_SetItem (C 函数):     结构序列对象.       (line   92)
* PyStructSequence_SET_ITEM (C 函数):    结构序列对象.       (line  101)
* PyStructSequence_UnnamedField (C 变量): 结构序列对象.      (line   73)
* PySys_AddAuditHook (C 函数):           系统功能.           (line  127)
* PySys_AddWarnOption (C 函数):          系统功能.           (line   27)
* PySys_AddWarnOptionUnicode (C 函数):   系统功能.           (line   33)
* PySys_AddXOption (C 函数):             系统功能.           (line   87)
* PySys_Audit (C 函数):                  系统功能.           (line  103)
* PySys_FormatStderr (C 函数):           系统功能.           (line   80)
* PySys_FormatStdout (C 函数):           系统功能.           (line   72)
* PySys_GetObject (C 函数):              系统功能.           (line   11)
* PySys_GetXOptions (C 函数):            系统功能.           (line   96)
* PySys_ResetWarnOptions (C 函数):       系统功能.           (line   22)
* PySys_SetArgv (C 函数):                Process-wide parameters.
                                                             (line  255)
* PySys_SetArgv():                       Initializing and finalizing the interpreter.
                                                             (line    8)
* PySys_SetArgvEx (C 函数):              Process-wide parameters.
                                                             (line  214)
* PySys_SetArgvEx():                     嵌入Python<2>.      (line   17)
* PySys_SetArgvEx() <1>:                 Initializing and finalizing the interpreter.
                                                             (line    8)
* PySys_SetObject (C 函数):              系统功能.           (line   16)
* PySys_SetPath (C 函数):                系统功能.           (line   43)
* PySys_WriteStderr (C 函数):            系统功能.           (line   67)
* PySys_WriteStdout (C 函数):            系统功能.           (line   49)
* Python 3000:                           术语对照表.         (line  876)
* Python Editor:                         IDLE<54>.           (line    8)
* Python Package Index (PyPI):           安装相关工具.       (line   21)
* Python 提高建议; PEP 1:                新开发流程.         (line   67)
* Python 提高建议; PEP 1 <1>:            新开发流程.         (line   82)
* Python 提高建议; PEP 1 <2>:            术语对照表.         (line  849)
* Python 提高建议; PEP 100:              Unicode<2>.         (line   15)
* Python 提高建议; PEP 11:               PEP 538 传统 C 区域强制转换.
                                                             (line   16)
* Python 提高建议; PEP 11 <1>:           不支持的操作系统.   (line    6)
* Python 提高建议; PEP 11 <2>:           Library Changes.    (line   15)
* Python 提高建议; PEP 11 <3>:           构建<26>.           (line   14)
* Python 提高建议; PEP 11 <4>:           在Windows上使用 Python.
                                                             (line   15)
* Python 提高建议; PEP 11 <5>:           其他平台.           (line    7)
* Python 提高建议; PEP 201:              新开发流程.         (line   86)
* Python 提高建议; PEP 205:              PEP 205 Weak References.
                                                             (line   82)
* Python 提高建议; PEP 205 <1>:          weakref --- 弱引用. (line  251)
* Python 提高建议; PEP 207:              PEP 207 Rich Comparisons.
                                                             (line   71)
* Python 提高建议; PEP 207 <1>:          PEP 207 Rich Comparisons.
                                                             (line   77)
* Python 提高建议; PEP 208:              PEP 208 New Coercion Model.
                                                             (line   30)
* Python 提高建议; PEP 217:              PEP 217 Interactive Display Hook.
                                                             (line   27)
* Python 提高建议; PEP 218:              PEP 218 内置集合对象.
                                                             (line   50)
* Python 提高建议; PEP 218 <1>:          其他语言特性修改<12>.
                                                             (line   12)
* Python 提高建议; PEP 218 <2>:          PEP 218 A Standard Set Datatype.
                                                             (line   80)
* Python 提高建议; PEP 227:              PEP 227 Nested Scopes.
                                                             (line   96)
* Python 提高建议; PEP 227 <1>:          PEP 227 Nested Scopes<2>.
                                                             (line   96)
* Python 提高建议; PEP 227 <2>:          __future__ --- Future 语句定义.
                                                             (line   62)
* Python 提高建议; PEP 229:              PEP 229 New Build System.
                                                             (line   39)
* Python 提高建议; PEP 230:              PEP 230 Warning Framework.
                                                             (line   73)
* Python 提高建议; PEP 232:              PEP 232 Function Attributes.
                                                             (line   36)
* Python 提高建议; PEP 234:              PEP 234 Iterators.  (line  124)
* Python 提高建议; PEP 235:              概述<13>.           (line   31)
* Python 提高建议; PEP 236:              PEP 227 Nested Scopes<2>.
                                                             (line   87)
* Python 提高建议; PEP 236 <1>:          PEP 227 Nested Scopes<2>.
                                                             (line   88)
* Python 提高建议; PEP 236 <2>:          PEP 236 __future__ Directives.
                                                             (line   29)
* Python 提高建议; PEP 236 <3>:          future 语句.        (line   71)
* Python 提高建议; PEP 237:              整数.               (line    6)
* Python 提高建议; PEP 237 <1>:          PEP 237 统一长整数和整数.
                                                             (line   22)
* Python 提高建议; PEP 237 <2>:          其他语言特性修改<12>.
                                                             (line   18)
* Python 提高建议; PEP 237 <3>:          PEP 237 统一长整数和整数<2>.
                                                             (line   37)
* Python 提高建议; PEP 237 <4>:          printf 风格的字符串格式化.
                                                             (line  155)
* Python 提高建议; PEP 237 <5>:          printf 风格的字节串格式化.
                                                             (line  164)
* Python 提高建议; PEP 238:              整数.               (line   10)
* Python 提高建议; PEP 238 <1>:          PEP 238 Changing the Division Operator.
                                                             (line   21)
* Python 提高建议; PEP 238 <2>:          PEP 238 Changing the Division Operator.
                                                             (line   27)
* Python 提高建议; PEP 238 <3>:          PEP 238 Changing the Division Operator.
                                                             (line   68)
* Python 提高建议; PEP 238 <4>:          __future__ --- Future 语句定义.
                                                             (line   68)
* Python 提高建议; PEP 238 <5>:          The Very High Level Layer.
                                                             (line  423)
* Python 提高建议; PEP 238 <6>:          术语对照表.         (line  371)
* Python 提高建议; PEP 241:              PEP 241 Metadata in Python Packages.
                                                             (line   15)
* Python 提高建议; PEP 241 <1>:          PEP 241 Metadata in Python Packages.
                                                             (line   28)
* Python 提高建议; PEP 241 <2>:          PEP 241 Metadata in Python Packages.
                                                             (line   35)
* Python 提高建议; PEP 243:              PEP 241 Metadata in Python Packages.
                                                             (line   39)
* Python 提高建议; PEP 247:              hmac<2>.            (line   20)
* Python 提高建议; PEP 249:              sqlite3 包.         (line   16)
* Python 提高建议; PEP 249 <1>:          sqlite3 包.         (line  107)
* Python 提高建议; PEP 249 <2>:          sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块.
                                                             (line   16)
* Python 提高建议; PEP 249 <3>:          sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块.
                                                             (line  103)
* Python 提高建议; PEP 252:              Related Links.      (line   17)
* Python 提高建议; PEP 252 <1>:          Related Links.      (line   17)
* Python 提高建议; PEP 252 <2>:          实现描述器.         (line   20)
* Python 提高建议; PEP 253:              Old and New Classes.
                                                             (line   28)
* Python 提高建议; PEP 253 <1>:          Multiple Inheritance The Diamond Rule.
                                                             (line    8)
* Python 提高建议; PEP 253 <2>:          Related Links.      (line   17)
* Python 提高建议; PEP 253 <3>:          Related Links.      (line   19)
* Python 提高建议; PEP 253 <4>:          Related Links.      (line   21)
* Python 提高建议; PEP 255:              PEP 255 Simple Generators.
                                                             (line   45)
* Python 提高建议; PEP 255 <1>:          PEP 255 Simple Generators.
                                                             (line  131)
* Python 提高建议; PEP 255 <2>:          PEP 255 Simple Generators<2>.
                                                             (line   43)
* Python 提高建议; PEP 255 <3>:          PEP 255 Simple Generators<2>.
                                                             (line  129)
* Python 提高建议; PEP 255 <4>:          yield 表达式.       (line   71)
* Python 提高建议; PEP 255 <5>:          __future__ --- Future 语句定义.
                                                             (line   65)
* Python 提高建议; PEP 261:              Unicode Changes.    (line   18)
* Python 提高建议; PEP 261 <1>:          Unicode Changes.    (line   61)
* Python 提高建议; PEP 263:              其他语言特性修改<11>.
                                                             (line   98)
* Python 提高建议; PEP 263 <1>:          PEP 263 Source Code Encodings.
                                                             (line   29)
* Python 提高建议; PEP 263 <2>:          概述<13>.           (line   35)
* Python 提高建议; PEP 263 <3>:          对输入进行解析标记. (line   34)
* Python 提高建议; PEP 263 <4>:          对输入进行解析标记. (line   88)
* Python 提高建议; PEP 263 <5>:          Python 源代码中的 Unicode 文字.
                                                             (line   38)
* Python 提高建议; PEP 264:              Other Changes and Fixes<3>.
                                                             (line   55)
* Python 提高建议; PEP 273:              PEP 273 从ZIP压缩包导入模块.
                                                             (line   41)
* Python 提高建议; PEP 273 <1>:          PEP 273 从ZIP压缩包导入模块.
                                                             (line   44)
* Python 提高建议; PEP 273 <2>:          zipimport --- 从 Zip 存档中导入模块.
                                                             (line   34)
* Python 提高建议; PEP 273 <3>:          zipimport --- 从 Zip 存档中导入模块.
                                                             (line   36)
* Python 提高建议; PEP 274:              新语法.             (line   38)
* Python 提高建议; PEP 275:              为什么Python中没有switch或case语句？.
                                                             (line    8)
* Python 提高建议; PEP 277:              PEP 277 Unicode file name support for Windows NT.
                                                             (line   32)
* Python 提高建议; PEP 278:              PEP 278 通用换行支持.
                                                             (line   33)
* Python 提高建议; PEP 278 <1>:          术语对照表.         (line 1059)
* Python 提高建议; PEP 279:              PEP 279 enumerate.  (line   27)
* Python 提高建议; PEP 282:              PEP 282 logging 包. (line  101)
* Python 提高建议; PEP 282 <1>:          PEP 282 logging 包. (line  107)
* Python 提高建议; PEP 282 <2>:          归档操作.           (line   41)
* Python 提高建议; PEP 282 <3>:          与警告模块集成.     (line   33)
* Python 提高建议; PEP 282 <4>:          distutils log --- Simple PEP 282-style logging.
                                                             (line    6)
* Python 提高建议; PEP 285:              PEP 285 布尔类型.   (line   47)
* Python 提高建议; PEP 285 <1>:          PEP 285 布尔类型.   (line   70)
* Python 提高建议; PEP 288:              PEP 342 生成器的新特性.
                                                             (line  145)
* Python 提高建议; PEP 289:              PEP 289 生成器表达式.
                                                             (line   56)
* Python 提高建议; PEP 289 <1>:          其他语言特性修改<12>.
                                                             (line   15)
* Python 提高建议; PEP 289 <2>:          Python 文档.        (line   12)
* Python 提高建议; PEP 292:              PEP 292 Simpler String Substitutions.
                                                             (line   45)
* Python 提高建议; PEP 292 <1>:          模板字符串.         (line    6)
* Python 提高建议; PEP 293:              PEP 293 Codec Error Handling Callbacks.
                                                             (line   33)
* Python 提高建议; PEP 3000:             Python 3 0.         (line   43)
* Python 提高建议; PEP 301:              PEP 301 Distutils的软件包索引和元数据.
                                                             (line   45)
* Python 提高建议; PEP 301 <1>:          distutils command register --- Register a module with the Python Package Index.
                                                             (line    7)
* Python 提高建议; PEP 302:              Using importlib as the Implementation of Import.
                                                             (line   13)
* Python 提高建议; PEP 302 <1>:          Visible Changes.    (line   18)
* Python 提高建议; PEP 302 <2>:          Porting Python code.
                                                             (line   71)
* Python 提高建议; PEP 302 <3>:          新增，改进和弃用的模块<2>.
                                                             (line  106)
* Python 提高建议; PEP 302 <4>:          新增，改进和删除的模块.
                                                             (line  287)
* Python 提高建议; PEP 302 <5>:          PEP 273 从ZIP压缩包导入模块.
                                                             (line   46)
* Python 提高建议; PEP 302 <6>:          PEP 302 New Import Hooks.
                                                             (line   13)
* Python 提高建议; PEP 302 <7>:          PEP 302 New Import Hooks.
                                                             (line   38)
* Python 提高建议; PEP 302 <8>:          PEP 302 New Import Hooks.
                                                             (line   62)
* Python 提高建议; PEP 302 <9>:          导入系统.           (line   33)
* Python 提高建议; PEP 302 <10>:         参考文献.           (line    9)
* Python 提高建议; PEP 302 <11>:         内置函数.           (line 1503)
* Python 提高建议; PEP 302 <12>:         linecache --- 随机读写文本行.
                                                             (line   26)
* Python 提高建议; PEP 302 <13>:         sys --- 系统相关的参数和函数.
                                                             (line  925)
* Python 提高建议; PEP 302 <14>:         sys --- 系统相关的参数和函数.
                                                             (line  934)
* Python 提高建议; PEP 302 <15>:         zipimport --- 从 Zip 存档中导入模块.
                                                             (line   37)
* Python 提高建议; PEP 302 <16>:         zipimport --- 从 Zip 存档中导入模块.
                                                             (line   40)
* Python 提高建议; PEP 302 <17>:         pkgutil --- 包扩展工具.
                                                             (line   54)
* Python 提高建议; PEP 302 <18>:         pkgutil --- 包扩展工具.
                                                             (line   56)
* Python 提高建议; PEP 302 <19>:         pkgutil --- 包扩展工具.
                                                             (line   57)
* Python 提高建议; PEP 302 <20>:         pkgutil --- 包扩展工具.
                                                             (line   65)
* Python 提高建议; PEP 302 <21>:         pkgutil --- 包扩展工具.
                                                             (line   73)
* Python 提高建议; PEP 302 <22>:         pkgutil --- 包扩展工具.
                                                             (line   86)
* Python 提高建议; PEP 302 <23>:         pkgutil --- 包扩展工具.
                                                             (line  102)
* Python 提高建议; PEP 302 <24>:         pkgutil --- 包扩展工具.
                                                             (line  117)
* Python 提高建议; PEP 302 <25>:         pkgutil --- 包扩展工具.
                                                             (line  137)
* Python 提高建议; PEP 302 <26>:         pkgutil --- 包扩展工具.
                                                             (line  158)
* Python 提高建议; PEP 302 <27>:         pkgutil --- 包扩展工具.
                                                             (line  197)
* Python 提高建议; PEP 302 <28>:         runpy --- Locating and executing Python modules.
                                                             (line   32)
* Python 提高建议; PEP 302 <29>:         概述<13>.           (line   39)
* Python 提高建议; PEP 302 <30>:         importlib abc —— 关于导入的抽象基类.
                                                             (line   37)
* Python 提高建议; PEP 302 <31>:         importlib abc —— 关于导入的抽象基类.
                                                             (line  148)
* Python 提高建议; PEP 302 <32>:         importlib abc —— 关于导入的抽象基类.
                                                             (line  314)
* Python 提高建议; PEP 302 <33>:         importlib abc —— 关于导入的抽象基类.
                                                             (line  333)
* Python 提高建议; PEP 302 <34>:         importlib abc —— 关于导入的抽象基类.
                                                             (line  397)
* Python 提高建议; PEP 302 <35>:         imp --- Access the import internals.
                                                             (line  338)
* Python 提高建议; PEP 302 <36>:         术语对照表.         (line  364)
* Python 提高建议; PEP 302 <37>:         术语对照表.         (line  627)
* Python 提高建议; PEP 307:              PEP 307 Pickle Enhancements.
                                                             (line    8)
* Python 提高建议; PEP 307 <1>:          PEP 307 Pickle Enhancements.
                                                             (line   30)
* Python 提高建议; PEP 307 <2>:          PEP 307 Pickle Enhancements.
                                                             (line   42)
* Python 提高建议; PEP 307 <3>:          数据流格式.         (line   25)
* Python 提高建议; PEP 308:              PEP 308 条件表达式. (line   72)
* Python 提高建议; PEP 308 <1>:          PEP 308 条件表达式. (line   78)
* Python 提高建议; PEP 308 <2>:          条件表达式.         (line   15)
* Python 提高建议; PEP 309:              PEP 309 部分功能应用.
                                                             (line   73)
* Python 提高建议; PEP 3100:             Python 3 0.         (line   44)
* Python 提高建议; PEP 3101:             PEP 3101 A New Approach To String Formatting.
                                                             (line    6)
* Python 提高建议; PEP 3101 <1>:         PEP 3101 A New Approach To String Formatting.
                                                             (line    9)
* Python 提高建议; PEP 3101 <2>:         PEP 3101 高级字符串格式.
                                                             (line  159)
* Python 提高建议; PEP 3101 <3>:         自定义字符串格式化. (line    6)
* Python 提高建议; PEP 3101 <4>:         自定义字符串格式化. (line   48)
* Python 提高建议; PEP 3102:             新语法.             (line   13)
* Python 提高建议; PEP 3104:             新语法.             (line   24)
* Python 提高建议; PEP 3104 <1>:         nonlocal 语句.      (line   23)
* Python 提高建议; PEP 3105:             Print Is A Function.
                                                             (line    8)
* Python 提高建议; PEP 3105 <1>:         PEP 3105 print 改为函数.
                                                             (line   35)
* Python 提高建议; PEP 3105 <2>:         __future__ --- Future 语句定义.
                                                             (line   77)
* Python 提高建议; PEP 3106:             PEP 3106 Dictionary Views.
                                                             (line   58)
* Python 提高建议; PEP 3107:             PEP 563：延迟的标注求值.
                                                             (line    6)
* Python 提高建议; PEP 3107 <1>:         PEP 484 - 类型提示. (line    7)
* Python 提高建议; PEP 3107 <2>:         新语法.             (line    6)
* Python 提高建议; PEP 3107 <3>:         函数标注.           (line    7)
* Python 提高建议; PEP 3107 <4>:         函数定义.           (line  100)
* Python 提高建议; PEP 3108:             Library Changes.    (line    7)
* Python 提高建议; PEP 3108 <1>:         Library Changes.    (line   17)
* Python 提高建议; PEP 3108 <2>:         Library Changes.    (line   95)
* Python 提高建议; PEP 3109:             修改的语法.         (line    6)
* Python 提高建议; PEP 3109 <1>:         Changes To Exceptions.
                                                             (line   29)
* Python 提高建议; PEP 3110:             修改的语法.         (line   16)
* Python 提高建议; PEP 3110 <1>:         Changes To Exceptions.
                                                             (line   35)
* Python 提高建议; PEP 3110 <2>:         PEP 3110 异常处理的变更.
                                                             (line   48)
* Python 提高建议; PEP 3111:             Builtins.           (line   12)
* Python 提高建议; PEP 3112:             PEP 3112 字节字面值.
                                                             (line   75)
* Python 提高建议; PEP 3112 <1>:         __future__ --- Future 语句定义.
                                                             (line   80)
* Python 提高建议; PEP 3113:             移除的语法.         (line    6)
* Python 提高建议; PEP 3114:             Operators And Special Methods.
                                                             (line   19)
* Python 提高建议; PEP 3115:             types<4>.           (line   10)
* Python 提高建议; PEP 3115 <1>:         修改的语法.         (line   18)
* Python 提高建议; PEP 3115 <2>:         准备类命名空间.     (line   19)
* Python 提高建议; PEP 3115 <3>:         类定义.             (line   57)
* Python 提高建议; PEP 3115 <4>:         动态类型创建.       (line   44)
* Python 提高建议; PEP 3116:             性能优化<7>.        (line    8)
* Python 提高建议; PEP 3116 <1>:         PEP 3116 新 I/O 库. (line   69)
* Python 提高建议; PEP 3116 <2>:         术语对照表.         (line 1059)
* Python 提高建议; PEP 3118:             具有外部数据缓冲区的 pickle 协议 5.
                                                             (line   10)
* Python 提高建议; PEP 3118 <1>:         PEP 3118 新的内存视图实现和缓冲协议文档.
                                                             (line    6)
* Python 提高建议; PEP 3118 <2>:         API changes.        (line   29)
* Python 提高建议; PEP 3118 <3>:         构建和 C API 的改变<4>.
                                                             (line    8)
* Python 提高建议; PEP 3118 <4>:         构建和 C API 的改变<7>.
                                                             (line   12)
* Python 提高建议; PEP 3118 <5>:         PEP 3118 修改缓冲区协议.
                                                             (line   46)
* Python 提高建议; PEP 3118 <6>:         库<40>.             (line   99)
* Python 提高建议; PEP 3118 <7>:         库<45>.             (line   61)
* Python 提高建议; PEP 3118 <8>:         库<88>.             (line  955)
* Python 提高建议; PEP 3118 <9>:         内存视图.           (line  100)
* Python 提高建议; PEP 3119:             PEP 3119 抽象基类.  (line  139)
* Python 提高建议; PEP 3119 <1>:         自定义实例及子类检查.
                                                             (line   31)
* Python 提高建议; PEP 3119 <2>:         容器抽象基类.       (line  302)
* Python 提高建议; PEP 3119 <3>:         abc --- 抽象基类.   (line   10)
* Python 提高建议; PEP 3119 <4>:         对象协议.           (line  182)
* Python 提高建议; PEP 3119 <5>:         对象协议.           (line  200)
* Python 提高建议; PEP 3120:             Text Vs Data Instead Of Unicode Vs 8-bit.
                                                             (line  107)
* Python 提高建议; PEP 3120 <1>:         词法分析.           (line   11)
* Python 提高建议; PEP 3120 <2>:         概述<13>.           (line   71)
* Python 提高建议; PEP 3121:             构建和 C API 的改变<7>.
                                                             (line   14)
* Python 提高建议; PEP 3121 <1>:         Initializing C modules.
                                                             (line   55)
* Python 提高建议; PEP 3123:             构建和 C API 的改变<7>.
                                                             (line   16)
* Python 提高建议; PEP 3127:             PEP 3127 整型文字支持和语法.
                                                             (line   47)
* Python 提高建议; PEP 3129:             PEP 3129 类装饰器.  (line   24)
* Python 提高建议; PEP 3129 <1>:         类定义.             (line   62)
* Python 提高建议; PEP 3131:             Text Vs Data Instead Of Unicode Vs 8-bit.
                                                             (line  109)
* Python 提高建议; PEP 3131 <1>:         标识符和关键字.     (line    9)
* Python 提高建议; PEP 3131 <2>:         标识符和关键字.     (line   15)
* Python 提高建议; PEP 3132:             新语法.             (line   28)
* Python 提高建议; PEP 3132 <1>:         赋值语句.           (line  121)
* Python 提高建议; PEP 3134:             修改的语法.         (line    6)
* Python 提高建议; PEP 3134 <1>:         Changes To Exceptions.
                                                             (line   40)
* Python 提高建议; PEP 3134 <2>:         Changes To Exceptions.
                                                             (line   60)
* Python 提高建议; PEP 3135:             Builtins.           (line    6)
* Python 提高建议; PEP 3135 <1>:         创建类对象.         (line   43)
* Python 提高建议; PEP 3137:             PEP 3137 The memoryview Object.
                                                             (line   49)
* Python 提高建议; PEP 3138:             Text Vs Data Instead Of Unicode Vs 8-bit.
                                                             (line  103)
* Python 提高建议; PEP 314:              PEP 314 Python软件包的元数据 v1 1.
                                                             (line   42)
* Python 提高建议; PEP 314 <1>:          distutils core --- 分发包功能的核心.
                                                             (line   92)
* Python 提高建议; PEP 3141:             PEP 3141 A Type Hierarchy for Numbers.
                                                             (line   43)
* Python 提高建议; PEP 3141 <1>:         numbers --- 数字的抽象基类.
                                                             (line   10)
* Python 提高建议; PEP 3141 <2>:         abc --- 抽象基类.   (line   12)
* Python 提高建议; PEP 3147:             PEP 421 添加 sys implementation.
                                                             (line   21)
* Python 提高建议; PEP 3147 <1>:         PEP 3147 PYC 仓库目录.
                                                             (line   69)
* Python 提高建议; PEP 3147 <2>:         “编译过的”Python文件.
                                                             (line   34)
* Python 提高建议; PEP 3147 <3>:         导入相关的模块属性. (line   68)
* Python 提高建议; PEP 3147 <4>:         test support --- Utilities for the Python test suite.
                                                             (line  192)
* Python 提高建议; PEP 3147 <5>:         runpy --- Locating and executing Python modules.
                                                             (line   87)
* Python 提高建议; PEP 3147 <6>:         概述<13>.           (line   75)
* Python 提高建议; PEP 3147 <7>:         importlib util -- Utility code for importers.
                                                             (line   24)
* Python 提高建议; PEP 3147 <8>:         importlib util -- Utility code for importers.
                                                             (line   60)
* Python 提高建议; PEP 3147 <9>:         importlib util -- Utility code for importers.
                                                             (line   64)
* Python 提高建议; PEP 3147 <10>:        py_compile --- 编译 Python 源文件.
                                                             (line   25)
* Python 提高建议; PEP 3147 <11>:        py_compile --- 编译 Python 源文件.
                                                             (line   56)
* Python 提高建议; PEP 3147 <12>:        Command-line use.   (line   56)
* Python 提高建议; PEP 3147 <13>:        Public functions.   (line   36)
* Python 提高建议; PEP 3147 <14>:        Public functions.   (line   97)
* Python 提高建议; PEP 3147 <15>:        imp --- Access the import internals.
                                                             (line  191)
* Python 提高建议; PEP 3147 <16>:        imp --- Access the import internals.
                                                             (line  198)
* Python 提高建议; PEP 3147 <17>:        imp --- Access the import internals.
                                                             (line  221)
* Python 提高建议; PEP 3147 <18>:        imp --- Access the import internals.
                                                             (line  225)
* Python 提高建议; PEP 3147 <19>:        imp --- Access the import internals.
                                                             (line  237)
* Python 提高建议; PEP 3147 <20>:        导入模块<2>.        (line  196)
* Python 提高建议; PEP 3147 <21>:        如何创建 pyc 文件？.
                                                             (line   10)
* Python 提高建议; PEP 3147 <22>:        distutils util --- Miscellaneous other utility functions.
                                                             (line  132)
* Python 提高建议; PEP 3148:             PEP 3148 concurrent futures 模块.
                                                             (line   51)
* Python 提高建议; PEP 3148 <1>:         模块函数.           (line   50)
* Python 提高建议; PEP 3149:             PEP 3149 ABI Version Tagged so Files.
                                                             (line   33)
* Python 提高建议; PEP 3149 <1>:         核心与内置<71>.     (line    9)
* Python 提高建议; PEP 3149 <2>:         sys --- 系统相关的参数和函数.
                                                             (line   14)
* Python 提高建议; PEP 3151:             PEP 3151 重写 OS 和 IO 异常的层次结构.
                                                             (line   84)
* Python 提高建议; PEP 3151 <1>:         OS 异常.            (line  102)
* Python 提高建议; PEP 3151 <2>:         异常<11>.           (line   10)
* Python 提高建议; PEP 3151 <3>:         select --- 等待 I/O 完成.
                                                             (line   25)
* Python 提高建议; PEP 3151 <4>:         resource --- Resource usage information.
                                                             (line   21)
* Python 提高建议; PEP 3151 <5>:         标准异常.           (line  181)
* Python 提高建议; PEP 3154:             摘要 - 发布重点<5>. (line   57)
* Python 提高建议; PEP 3154 <1>:         pickle<4>.          (line   16)
* Python 提高建议; PEP 3154 <2>:         库<29>.             (line 1281)
* Python 提高建议; PEP 3154 <3>:         数据流格式.         (line   34)
* Python 提高建议; PEP 3155:             PEP 3155 类和函数的限定名称.
                                                             (line   62)
* Python 提高建议; PEP 3155 <1>:         术语对照表.         (line  902)
* Python 提高建议; PEP 3156:             摘要 - 发布重点<5>. (line   31)
* Python 提高建议; PEP 3156 <1>:         摘要 - 发布重点<5>. (line   44)
* Python 提高建议; PEP 3156 <2>:         asyncio<6>.         (line    6)
* Python 提高建议; PEP 3156 <3>:         asyncio<6>.         (line   17)
* Python 提高建议; PEP 3156 <4>:         selectors<2>.       (line    6)
* Python 提高建议; PEP 318:              PEP 318 Decorators for Functions and Methods.
                                                             (line  101)
* Python 提高建议; PEP 318 <1>:          PEP 318 Decorators for Functions and Methods.
                                                             (line  125)
* Python 提高建议; PEP 318 <2>:          其他语言特性修改<12>.
                                                             (line    9)
* Python 提高建议; PEP 318 <3>:          类定义.             (line   64)
* Python 提高建议; PEP 322:              PEP 322 反向迭代.   (line   35)
* Python 提高建议; PEP 322 <1>:          其他语言特性修改<12>.
                                                             (line   13)
* Python 提高建议; PEP 324:              PEP 324 新的子进程模块.
                                                             (line   86)
* Python 提高建议; PEP 324 <1>:          subprocess --- 子进程管理.
                                                             (line   22)
* Python 提高建议; PEP 325:              PEP 342 生成器的新特性.
                                                             (line  145)
* Python 提高建议; PEP 327:              Context 类型.       (line   56)
* Python 提高建议; PEP 328:              Porting Python code.
                                                             (line   36)
* Python 提高建议; PEP 328 <1>:          移除的语法.         (line   29)
* Python 提高建议; PEP 328 <2>:          PEP 328 绝对导入和相对导入.
                                                             (line    6)
* Python 提高建议; PEP 328 <3>:          PEP 328 绝对导入和相对导入.
                                                             (line   82)
* Python 提高建议; PEP 328 <4>:          PEP 328 多行导入.   (line   35)
* Python 提高建议; PEP 328 <5>:          其他语言特性修改<12>.
                                                             (line   21)
* Python 提高建议; PEP 328 <6>:          参考文献.           (line   17)
* Python 提高建议; PEP 328 <7>:          内置函数.           (line 1514)
* Python 提高建议; PEP 328 <8>:          __future__ --- Future 语句定义.
                                                             (line   71)
* Python 提高建议; PEP 328 <9>:          概述<13>.           (line   43)
* Python 提高建议; PEP 331:              PEP 331 Locale-Independent Float/String Conversions.
                                                             (line   38)
* Python 提高建议; PEP 333:              wsgiref 包.         (line    8)
* Python 提高建议; PEP 333 <1>:          wsgiref 包.         (line   31)
* Python 提高建议; PEP 3333:             PEP 3333 Python Web服务器网关接口v1 0 1.
                                                             (line   50)
* Python 提高建议; PEP 3333 <1>:         wsgiref --- WSGI Utilities and Reference Implementation.
                                                             (line   24)
* Python 提高建议; PEP 3333 <2>:         wsgiref util -- WSGI environment utilities.
                                                             (line    8)
* Python 提高建议; PEP 3333 <3>:         wsgiref util -- WSGI environment utilities.
                                                             (line   10)
* Python 提高建议; PEP 3333 <4>:         wsgiref util -- WSGI environment utilities.
                                                             (line   28)
* Python 提高建议; PEP 3333 <5>:         wsgiref util -- WSGI environment utilities.
                                                             (line   74)
* Python 提高建议; PEP 3333 <6>:         wsgiref headers -- WSGI response header tools.
                                                             (line   12)
* Python 提高建议; PEP 3333 <7>:         wsgiref simple_server -- a simple WSGI HTTP server.
                                                             (line   21)
* Python 提高建议; PEP 3333 <8>:         wsgiref simple_server -- a simple WSGI HTTP server.
                                                             (line   96)
* Python 提高建议; PEP 3333 <9>:         wsgiref validate --- WSGI conformance checker.
                                                             (line   13)
* Python 提高建议; PEP 3333 <10>:        wsgiref validate --- WSGI conformance checker.
                                                             (line   41)
* Python 提高建议; PEP 3333 <11>:        wsgiref handlers -- server/gateway base classes.
                                                             (line  233)
* Python 提高建议; PEP 3333 <12>:        wsgiref handlers -- server/gateway base classes.
                                                             (line  249)
* Python 提高建议; PEP 3333 <13>:        wsgiref handlers -- server/gateway base classes.
                                                             (line  256)
* Python 提高建议; PEP 3333 <14>:        wsgiref handlers -- server/gateway base classes.
                                                             (line  265)
* Python 提高建议; PEP 3333 <15>:        wsgiref handlers -- server/gateway base classes.
                                                             (line  307)
* Python 提高建议; PEP 338:              PEP 338 将模块作为脚本执行.
                                                             (line   21)
* Python 提高建议; PEP 338 <1>:          接口选项.           (line   84)
* Python 提高建议; PEP 338 <2>:          参考文献.           (line   20)
* Python 提高建议; PEP 338 <3>:          runpy --- Locating and executing Python modules.
                                                             (line  170)
* Python 提高建议; PEP 339:              构建和 C API 的改变<10>.
                                                             (line   45)
* Python 提高建议; PEP 341:              PEP 341 统一 try/except/finally.
                                                             (line   44)
* Python 提高建议; PEP 342:              PEP 342 生成器的新特性.
                                                             (line   42)
* Python 提高建议; PEP 342 <1>:          PEP 342 生成器的新特性.
                                                             (line  140)
* Python 提高建议; PEP 342 <2>:          移植到Python 2 5.   (line   15)
* Python 提高建议; PEP 342 <3>:          yield 表达式.       (line   75)
* Python 提高建议; PEP 342 <4>:          容器抽象基类.       (line  149)
* Python 提高建议; PEP 342 <5>:          向生成器传递值.     (line   20)
* Python 提高建议; PEP 342 <6>:          Python 文档.        (line   14)
* Python 提高建议; PEP 343:              contextlib 模块.    (line   64)
* Python 提高建议; PEP 343 <1>:          PEP 342 生成器的新特性.
                                                             (line  129)
* Python 提高建议; PEP 343 <2>:          contextlib 模块<2>. (line   64)
* Python 提高建议; PEP 343 <3>:          with 语句上下文管理器.
                                                             (line   35)
* Python 提高建议; PEP 343 <4>:          with 语句.          (line   87)
* Python 提高建议; PEP 343 <5>:          Using a context manager as a function decorator.
                                                             (line   51)
* Python 提高建议; PEP 343 <6>:          __future__ --- Future 语句定义.
                                                             (line   74)
* Python 提高建议; PEP 343 <7>:          术语对照表.         (line  211)
* Python 提高建议; PEP 347:              构建和 C API 的改变<10>.
                                                             (line   10)
* Python 提高建议; PEP 352:              Changes To Exceptions.
                                                             (line    9)
* Python 提高建议; PEP 352 <1>:          Deprecations and Removals.
                                                             (line    9)
* Python 提高建议; PEP 352 <2>:          PEP 352 异常作为新型的类.
                                                             (line   57)
* Python 提高建议; PEP 353:              PEP 353 使用ssize_t作为索引类型.
                                                             (line   48)
* Python 提高建议; PEP 353 <1>:          PEP 353 使用ssize_t作为索引类型.
                                                             (line   54)
* Python 提高建议; PEP 353 <2>:          构建和 C API 的改变<10>.
                                                             (line   20)
* Python 提高建议; PEP 356:              Python 2 5 有什么新变化.
                                                             (line   10)
* Python 提高建议; PEP 357:              PEP 357 '__index__' 方法.
                                                             (line   39)
* Python 提高建议; PEP 361:              Python 2 6 有什么新变化.
                                                             (line   10)
* Python 提高建议; PEP 362:              PEP 362 函数签名对象.
                                                             (line   19)
* Python 提高建议; PEP 362 <1>:          Introspecting callables with the Signature object.
                                                             (line  341)
* Python 提高建议; PEP 362 <2>:          术语对照表.         (line   78)
* Python 提高建议; PEP 362 <3>:          术语对照表.         (line  801)
* Python 提高建议; PEP 366:              Visible Changes.    (line   24)
* Python 提高建议; PEP 366 <1>:          导入相关的模块属性. (line   25)
* Python 提高建议; PEP 366 <2>:          导入相关的模块属性. (line   28)
* Python 提高建议; PEP 366 <3>:          参考文献.           (line   15)
* Python 提高建议; PEP 366 <4>:          参考文献.           (line   18)
* Python 提高建议; PEP 366 <5>:          runpy --- Locating and executing Python modules.
                                                             (line  174)
* Python 提高建议; PEP 366 <6>:          概述<13>.           (line   47)
* Python 提高建议; PEP 370:              PEP 370 分用户的 site-packages 目录.
                                                             (line   36)
* Python 提高建议; PEP 370 <1>:          其他选项.           (line  109)
* Python 提高建议; PEP 370 <2>:          环境变量.           (line  146)
* Python 提高建议; PEP 370 <3>:          环境变量.           (line  157)
* Python 提高建议; PEP 370 <4>:          命令行界面<9>.      (line   34)
* Python 提高建议; PEP 371:              PEP 371 多任务处理包.
                                                             (line  145)
* Python 提高建议; PEP 372:              PEP 372 有序字典.   (line   31)
* Python 提高建议; PEP 372 <1>:          PEP 372 Adding an Ordered Dictionary to collections.
                                                             (line   97)
* Python 提高建议; PEP 373:              Python 2 x的未来.   (line   17)
* Python 提高建议; PEP 378:              PEP 378 千位分隔符的格式说明符.
                                                             (line   32)
* Python 提高建议; PEP 378 <1>:          PEP 378 千位分隔符的格式说明符<2>.
                                                             (line   37)
* Python 提高建议; PEP 378 <2>:          格式规格迷你语言.   (line   83)
* Python 提高建议; PEP 380:              PEP 380 委托给子生成器的语法.
                                                             (line   66)
* Python 提高建议; PEP 380 <1>:          yield 表达式.       (line   79)
* Python 提高建议; PEP 383:              错误处理方案.       (line   50)
* Python 提高建议; PEP 383 <1>:          套接字协议族.       (line   13)
* Python 提高建议; PEP 383 <2>:          Locale Encoding.    (line   15)
* Python 提高建议; PEP 383 <3>:          Locale Encoding.    (line   53)
* Python 提高建议; PEP 383 <4>:          File System Encoding.
                                                             (line    9)
* Python 提高建议; PEP 384:              PEP 384 定义稳定的ABI.
                                                             (line   24)
* Python 提高建议; PEP 384 <1>:          稳定的应用程序二进制接口.
                                                             (line   28)
* Python 提高建议; PEP 385:              代码库.             (line   13)
* Python 提高建议; PEP 389:              PEP 389 Argparse 命令行解析模块.
                                                             (line   92)
* Python 提高建议; PEP 389 <1>:          PEP 389 The argparse Module for Parsing Command Lines.
                                                             (line  100)
* Python 提高建议; PEP 391:              PEP 391 基于字典的日志配置.
                                                             (line   52)
* Python 提高建议; PEP 391 <1>:          PEP 391 Dictionary-Based Configuration For Logging.
                                                             (line   94)
* Python 提高建议; PEP 392:              Python 3 2 有什么新变化.
                                                             (line   16)
* Python 提高建议; PEP 393:              PEP 393 灵活的字符串表示.
                                                             (line   16)
* Python 提高建议; PEP 393 <1>:          Functionality.      (line    6)
* Python 提高建议; PEP 393 <2>:          Performance and resource usage.
                                                             (line   29)
* Python 提高建议; PEP 393 <3>:          性能优化<5>.        (line    8)
* Python 提高建议; PEP 393 <4>:          构建和 C API 的改变<4>.
                                                             (line   12)
* Python 提高建议; PEP 393 <5>:          已弃用的 Python 模块、函数和方法<4>.
                                                             (line   10)
* Python 提高建议; PEP 393 <6>:          已弃用的 C API 函数和类型<3>.
                                                             (line    6)
* Python 提高建议; PEP 393 <7>:          Porting C code.     (line   17)
* Python 提高建议; PEP 393 <8>:          编码格式与 Unicode. (line    6)
* Python 提高建议; PEP 393 <9>:          sys --- 系统相关的参数和函数.
                                                             (line  864)
* Python 提高建议; PEP 393 <10>:         Deprecated Py_UNICODE APIs.
                                                             (line    8)
* Python 提高建议; PEP 395:              开放问题项.         (line   16)
* Python 提高建议; PEP 397:              PEP 486 Make the Python Launcher aware of virtual environments.
                                                             (line    6)
* Python 提高建议; PEP 397 <1>:          PEP 397 适用于Windows的Python启动器.
                                                             (line   31)
* Python 提高建议; PEP 397 <2>:          适用于Windows的Python启动器.
                                                             (line   15)
* Python 提高建议; PEP 397 <3>:          创建虚拟环境<2>.    (line  162)
* Python 提高建议; PEP 398:              Python 3 3 有什么新变化.
                                                             (line   12)
* Python 提高建议; PEP 4:                Library Changes.    (line   13)
* Python 提高建议; PEP 405:              PEP 405 虚拟环境.   (line   22)
* Python 提高建议; PEP 405 <1>:          venv --- 创建虚拟环境.
                                                             (line   17)
* Python 提高建议; PEP 409:              PEP 409 清除异常上下文.
                                                             (line   63)
* Python 提高建议; PEP 411:              sys --- 系统相关的参数和函数.
                                                             (line  690)
* Python 提高建议; PEP 411 <1>:          sys --- 系统相关的参数和函数.
                                                             (line  699)
* Python 提高建议; PEP 411 <2>:          sys --- 系统相关的参数和函数.
                                                             (line 1208)
* Python 提高建议; PEP 411 <3>:          sys --- 系统相关的参数和函数.
                                                             (line 1224)
* Python 提高建议; PEP 411 <4>:          术语对照表.         (line  872)
* Python 提高建议; PEP 412:              PEP 412 Key-Sharing Dictionary.
                                                             (line   15)
* Python 提高建议; PEP 414:              PEP 414 显式的Unicode文本.
                                                             (line   17)
* Python 提高建议; PEP 414 <1>:          字符串和字节串字面值.
                                                             (line   52)
* Python 提高建议; PEP 418:              time<5>.            (line    6)
* Python 提高建议; PEP 420:              PEP 420 隐式命名空间包.
                                                             (line    9)
* Python 提高建议; PEP 420 <1>:          PEP 420 隐式命名空间包.
                                                             (line   14)
* Python 提高建议; PEP 420 <2>:          核心与内置<56>.     (line   56)
* Python 提高建议; PEP 420 <3>:          核心与内置<61>.     (line  114)
* Python 提高建议; PEP 420 <4>:          导入系统.           (line   35)
* Python 提高建议; PEP 420 <5>:          命名空间包.         (line   20)
* Python 提高建议; PEP 420 <6>:          module __path__.    (line   16)
* Python 提高建议; PEP 420 <7>:          module __path__.    (line   17)
* Python 提高建议; PEP 420 <8>:          参考文献.           (line   10)
* Python 提高建议; PEP 420 <9>:          参考文献.           (line   12)
* Python 提高建议; PEP 420 <10>:         参考文献.           (line   12)
* Python 提高建议; PEP 420 <11>:         概述<13>.           (line   51)
* Python 提高建议; PEP 420 <12>:         术语对照表.         (line  364)
* Python 提高建议; PEP 420 <13>:         术语对照表.         (line  729)
* Python 提高建议; PEP 420 <14>:         术语对照表.         (line  854)
* Python 提高建议; PEP 421:              SimpleNamespace.    (line   16)
* Python 提高建议; PEP 421 <1>:          sys --- 系统相关的参数和函数.
                                                             (line  786)
* Python 提高建议; PEP 421 <2>:          sys --- 系统相关的参数和函数.
                                                             (line  791)
* Python 提高建议; PEP 424:              其他语言特性修改<5>.
                                                             (line   57)
* Python 提高建议; PEP 424 <1>:          operator<2>.        (line    8)
* Python 提高建议; PEP 427:              关键术语.           (line   27)
* Python 提高建议; PEP 428:              摘要 - 发布重点<5>. (line   39)
* Python 提高建议; PEP 428 <1>:          pathlib<5>.         (line   17)
* Python 提高建议; PEP 428 <2>:          pathlib --- 面向对象的文件系统路径.
                                                             (line   33)
* Python 提高建议; PEP 429:              Python 3 4 有什么新变化.
                                                             (line   16)
* Python 提高建议; PEP 432:              其他 CPython 实现的改变<2>.
                                                             (line    6)
* Python 提高建议; PEP 432 <1>:          核心与内置<39>.     (line  313)
* Python 提高建议; PEP 432 <2>:          Multi-Phase Initialization Private Provisional API.
                                                             (line    7)
* Python 提高建议; PEP 432 <3>:          Multi-Phase Initialization Private Provisional API.
                                                             (line   57)
* Python 提高建议; PEP 434:              PEP 434 IDLE Enhancement Exception for All Branches.
                                                             (line    6)
* Python 提高建议; PEP 435:              摘要 - 发布重点<5>. (line   36)
* Python 提高建议; PEP 435 <1>:          enum<5>.            (line    6)
* Python 提高建议; PEP 435 <2>:          enum<5>.            (line   15)
* Python 提高建议; PEP 436:              摘要 - 发布重点<5>. (line  120)
* Python 提高建议; PEP 436 <1>:          PEP 436 Argument Clinic.
                                                             (line    6)
* Python 提高建议; PEP 436 <2>:          PEP 436 Argument Clinic.
                                                             (line   28)
* Python 提高建议; PEP 441:              zipapp<2>.          (line    6)
* Python 提高建议; PEP 441 <1>:          zipapp<2>.          (line   24)
* Python 提高建议; PEP 442:              摘要 - 发布重点<5>. (line  113)
* Python 提高建议; PEP 442 <1>:          摘要 - 发布重点<5>. (line  115)
* Python 提高建议; PEP 442 <2>:          PEP 442 Safe Object Finalization.
                                                             (line    6)
* Python 提高建议; PEP 442 <3>:          PEP 442 Safe Object Finalization.
                                                             (line   21)
* Python 提高建议; PEP 442 <4>:          gc --- 垃圾回收器接口.
                                                             (line  186)
* Python 提高建议; PEP 442 <5>:          终结和内存释放.     (line   68)
* Python 提高建议; PEP 442 <6>:          PyTypeObject Slots. (line 1384)
* Python 提高建议; PEP 443:              摘要 - 发布重点<5>. (line   55)
* Python 提高建议; PEP 443 <1>:          functools<4>.       (line   22)
* Python 提高建议; PEP 443 <2>:          术语对照表.         (line  443)
* Python 提高建议; PEP 445:              摘要 - 发布重点<5>. (line  118)
* Python 提高建议; PEP 445 <1>:          PEP 445 Customization of CPython Memory Allocators.
                                                             (line    6)
* Python 提高建议; PEP 445 <2>:          PEP 445 Customization of CPython Memory Allocators.
                                                             (line   12)
* Python 提高建议; PEP 445 <3>:          其他改进<2>.        (line   63)
* Python 提高建议; PEP 446:              摘要 - 发布重点<5>. (line   14)
* Python 提高建议; PEP 446 <1>:          摘要 - 发布重点<5>. (line   78)
* Python 提高建议; PEP 446 <2>:          PEP 446 Newly Created File Descriptors Are Non-Inheritable.
                                                             (line    6)
* Python 提高建议; PEP 446 <3>:          PEP 446 Newly Created File Descriptors Are Non-Inheritable.
                                                             (line   26)
* Python 提高建议; PEP 448:              PEP 448 - Additional Unpacking Generalizations.
                                                             (line    6)
* Python 提高建议; PEP 448 <1>:          PEP 448 - Additional Unpacking Generalizations.
                                                             (line   38)
* Python 提高建议; PEP 448 <2>:          文档<45>.           (line   10)
* Python 提高建议; PEP 448 <3>:          文档<49>.           (line    9)
* Python 提高建议; PEP 448 <4>:          核心与内置<64>.     (line   12)
* Python 提高建议; PEP 448 <5>:          核心与内置<67>.     (line    9)
* Python 提高建议; PEP 448 <6>:          字典显示.           (line   23)
* Python 提高建议; PEP 448 <7>:          调用.               (line   90)
* Python 提高建议; PEP 448 <8>:          表达式列表.         (line   18)
* Python 提高建议; PEP 450:              摘要 - 发布重点<5>. (line   47)
* Python 提高建议; PEP 450 <1>:          statistics<3>.      (line    6)
* Python 提高建议; PEP 450 <2>:          statistics<3>.      (line   14)
* Python 提高建议; PEP 451:              PEP 489 Multi-phase extension module initialization.
                                                             (line    7)
* Python 提高建议; PEP 451 <1>:          摘要 - 发布重点<5>. (line   22)
* Python 提高建议; PEP 451 <2>:          PEP 451 A ModuleSpec Type for the Import System.
                                                             (line    6)
* Python 提高建议; PEP 451 <3>:          核心与内置<56>.     (line   76)
* Python 提高建议; PEP 451 <4>:          参考文献.           (line   22)
* Python 提高建议; PEP 451 <5>:          sys --- 系统相关的参数和函数.
                                                             (line  888)
* Python 提高建议; PEP 451 <6>:          pkgutil --- 包扩展工具.
                                                             (line   89)
* Python 提高建议; PEP 451 <7>:          pkgutil --- 包扩展工具.
                                                             (line  120)
* Python 提高建议; PEP 451 <8>:          runpy --- Locating and executing Python modules.
                                                             (line   91)
* Python 提高建议; PEP 451 <9>:          runpy --- Locating and executing Python modules.
                                                             (line  163)
* Python 提高建议; PEP 451 <10>:         runpy --- Locating and executing Python modules.
                                                             (line  178)
* Python 提高建议; PEP 451 <11>:         概述<13>.           (line   55)
* Python 提高建议; PEP 451 <12>:         Multi-phase initialization.
                                                             (line   71)
* Python 提高建议; PEP 451 <13>:         术语对照表.         (line  364)
* Python 提高建议; PEP 453:              摘要 - 发布重点<5>. (line   12)
* Python 提高建议; PEP 453 <1>:          摘要 - 发布重点<5>. (line   34)
* Python 提高建议; PEP 453 <2>:          Bootstrapping pip By Default.
                                                             (line    6)
* Python 提高建议; PEP 453 <3>:          文档更改.           (line   21)
* Python 提高建议; PEP 453 <4>:          ensurepip.          (line    7)
* Python 提高建议; PEP 453 <5>:          venv<4>.            (line   13)
* Python 提高建议; PEP 453 <6>:          其他改进<2>.        (line   73)
* Python 提高建议; PEP 453 <7>:          PEP 477 Backport ensurepip PEP 453 to Python 2 7.
                                                             (line    6)
* Python 提高建议; PEP 453 <8>:          Bootstrapping pip By Default<2>.
                                                             (line    6)
* Python 提高建议; PEP 453 <9>:          文档更改<2>.        (line   21)
* Python 提高建议; PEP 453 <10>:         ensurepip --- Bootstrapping the pip installer.
                                                             (line   33)
* Python 提高建议; PEP 454:              摘要 - 发布重点<5>. (line   50)
* Python 提高建议; PEP 454 <1>:          tracemalloc<3>.     (line    6)
* Python 提高建议; PEP 454 <2>:          tracemalloc<3>.     (line   22)
* Python 提高建议; PEP 456:              摘要 - 发布重点<5>. (line   75)
* Python 提高建议; PEP 456 <1>:          PEP 456 Secure and Interchangeable Hash Algorithm.
                                                             (line    6)
* Python 提高建议; PEP 461:              PEP 461 - percent formatting support for bytes and bytearray.
                                                             (line    6)
* Python 提高建议; PEP 461 <1>:          PEP 461 - percent formatting support for bytes and bytearray.
                                                             (line   41)
* Python 提高建议; PEP 461 <2>:          printf 风格的字节串格式化.
                                                             (line  172)
* Python 提高建议; PEP 465:              PEP 465 - 用于矩阵乘法的专用中缀运算符.
                                                             (line    6)
* Python 提高建议; PEP 465 <1>:          PEP 465 - 用于矩阵乘法的专用中缀运算符.
                                                             (line   44)
* Python 提高建议; PEP 465 <2>:          构建和 C API 的改变<3>.
                                                             (line   43)
* Python 提高建议; PEP 466:              PEP 466 Network Security Enhancements for Python 2 7.
                                                             (line    6)
* Python 提高建议; PEP 466 <1>:          PEP 466 Network Security Enhancements for Python 2 7.
                                                             (line   11)
* Python 提高建议; PEP 466 <2>:          PEP 466 Network Security Enhancements for Python 2 7.
                                                             (line   21)
* Python 提高建议; PEP 466 <3>:          PEP 466 Network Security Enhancements for Python 2 7.
                                                             (line   32)
* Python 提高建议; PEP 468:              PEP 468 保留关键字参数顺序.
                                                             (line   12)
* Python 提高建议; PEP 468 <1>:          库<48>.             (line   87)
* Python 提高建议; PEP 468 <2>:          OrderedDict 对象.   (line   73)
* Python 提高建议; PEP 471:              PEP 471 - os scandir function -- a better and faster directory iterator.
                                                             (line    6)
* Python 提高建议; PEP 471 <1>:          PEP 471 - os scandir function -- a better and faster directory iterator.
                                                             (line   29)
* Python 提高建议; PEP 471 <2>:          库<87>.             (line    6)
* Python 提高建议; PEP 475:              PEP 475 Retry system calls failing with EINTR.
                                                             (line   32)
* Python 提高建议; PEP 475 <1>:          PEP 475 Retry system calls failing with EINTR.
                                                             (line   75)
* Python 提高建议; PEP 475 <2>:          Python API 的变化<5>.
                                                             (line    6)
* Python 提高建议; PEP 475 <3>:          库<38>.             (line  229)
* Python 提高建议; PEP 475 <4>:          库<85>.             (line  143)
* Python 提高建议; PEP 475 <5>:          内置函数.           (line 1049)
* Python 提高建议; PEP 475 <6>:          OS 异常.            (line   70)
* Python 提高建议; PEP 475 <7>:          文件描述符操作.     (line  261)
* Python 提高建议; PEP 475 <8>:          文件描述符操作.     (line  513)
* Python 提高建议; PEP 475 <9>:          文件描述符操作.     (line  619)
* Python 提高建议; PEP 475 <10>:         进程管理.           (line  680)
* Python 提高建议; PEP 475 <11>:         函数<2>.            (line  194)
* Python 提高建议; PEP 475 <12>:         套接字对象.         (line   24)
* Python 提高建议; PEP 475 <13>:         套接字对象.         (line   67)
* Python 提高建议; PEP 475 <14>:         套接字对象.         (line  198)
* Python 提高建议; PEP 475 <15>:         套接字对象.         (line  209)
* Python 提高建议; PEP 475 <16>:         套接字对象.         (line  269)
* Python 提高建议; PEP 475 <17>:         套接字对象.         (line  329)
* Python 提高建议; PEP 475 <18>:         套接字对象.         (line  344)
* Python 提高建议; PEP 475 <19>:         套接字对象.         (line  360)
* Python 提高建议; PEP 475 <20>:         套接字对象.         (line  395)
* Python 提高建议; PEP 475 <21>:         select --- 等待 I/O 完成.
                                                             (line  127)
* Python 提高建议; PEP 475 <22>:         /dev/poll 轮询对象. (line   71)
* Python 提高建议; PEP 475 <23>:         边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   97)
* Python 提高建议; PEP 475 <24>:         Poll 对象.          (line   78)
* Python 提高建议; PEP 475 <25>:         Kqueue 对象.        (line   36)
* Python 提高建议; PEP 475 <26>:         类<3>.              (line  116)
* Python 提高建议; PEP 475 <27>:         模块内容<5>.        (line  463)
* Python 提高建议; PEP 475 <28>:         模块内容<5>.        (line  480)
* Python 提高建议; PEP 476:              PEP 476 Enabling certificate verification by default for stdlib http clients<2>.
                                                             (line    6)
* Python 提高建议; PEP 477:              PEP 477 Backport ensurepip PEP 453 to Python 2 7.
                                                             (line    6)
* Python 提高建议; PEP 478:              Python 3 5 有什么新变化.
                                                             (line   17)
* Python 提高建议; PEP 479:              Python 行为的更改.  (line   10)
* Python 提高建议; PEP 479 <1>:          PEP 479 Change StopIteration handling inside generators.
                                                             (line   12)
* Python 提高建议; PEP 479 <2>:          PEP 479 Change StopIteration handling inside generators.
                                                             (line   47)
* Python 提高建议; PEP 479 <3>:          库<29>.             (line 1269)
* Python 提高建议; PEP 479 <4>:          库<33>.             (line   52)
* Python 提高建议; PEP 479 <5>:          核心与内置<35>.     (line   34)
* Python 提高建议; PEP 479 <6>:          库<41>.             (line   95)
* Python 提高建议; PEP 479 <7>:          库<55>.             (line   80)
* Python 提高建议; PEP 479 <8>:          库<68>.             (line  326)
* Python 提高建议; PEP 479 <9>:          具体异常.           (line  196)
* Python 提高建议; PEP 479 <10>:         具体异常.           (line  198)
* Python 提高建议; PEP 479 <11>:         __future__ --- Future 语句定义.
                                                             (line   83)
* Python 提高建议; PEP 483:              PEP 484 - 类型提示. (line   47)
* Python 提高建议; PEP 483 <1>:          typing --- 类型标注支持.
                                                             (line   19)
* Python 提高建议; PEP 484:              ast.                (line   16)
* Python 提高建议; PEP 484 <1>:          ast.                (line   19)
* Python 提高建议; PEP 484 <2>:          PEP 560 对 typing 模块和泛型类型的核心支持.
                                                             (line    6)
* Python 提高建议; PEP 484 <3>:          PEP 526 变量注释的语法.
                                                             (line    6)
* Python 提高建议; PEP 484 <4>:          PEP 484 - 类型提示. (line   16)
* Python 提高建议; PEP 484 <5>:          PEP 484 - 类型提示. (line   41)
* Python 提高建议; PEP 484 <6>:          函数标注.           (line    7)
* Python 提高建议; PEP 484 <7>:          模拟泛型类型.       (line    6)
* Python 提高建议; PEP 484 <8>:          带标注的赋值语句.   (line   37)
* Python 提高建议; PEP 484 <9>:          函数定义.           (line  104)
* Python 提高建议; PEP 484 <10>:         typing --- 类型标注支持.
                                                             (line   15)
* Python 提高建议; PEP 484 <11>:         typing --- 类型标注支持.
                                                             (line   19)
* Python 提高建议; PEP 484 <12>:         NewType.            (line   60)
* Python 提高建议; PEP 484 <13>:         名义性子类型 区别于 结构性子类型.
                                                             (line    6)
* Python 提高建议; PEP 484 <14>:         名义性子类型 区别于 结构性子类型.
                                                             (line   11)
* Python 提高建议; PEP 484 <15>:         类 函数和修饰器.    (line   39)
* Python 提高建议; PEP 484 <16>:         类 函数和修饰器.    (line   41)
* Python 提高建议; PEP 484 <17>:         类 函数和修饰器.    (line  123)
* Python 提高建议; PEP 484 <18>:         类 函数和修饰器.    (line  632)
* Python 提高建议; PEP 484 <19>:         ast 中的辅助函数.   (line   15)
* Python 提高建议; PEP 484 <20>:         ast 中的辅助函数.   (line   25)
* Python 提高建议; PEP 484 <21>:         术语对照表.         (line   52)
* Python 提高建议; PEP 484 <22>:         术语对照表.         (line  391)
* Python 提高建议; PEP 484 <23>:         术语对照表.         (line 1040)
* Python 提高建议; PEP 484 <24>:         术语对照表.         (line 1053)
* Python 提高建议; PEP 484 <25>:         术语对照表.         (line 1078)
* Python 提高建议; PEP 485:              PEP 485 A function for testing approximate equality.
                                                             (line    6)
* Python 提高建议; PEP 485 <1>:          PEP 485 A function for testing approximate equality.
                                                             (line   36)
* Python 提高建议; PEP 485 <2>:          库<83>.             (line   10)
* Python 提高建议; PEP 485 <3>:          数论与表示函数.     (line  115)
* Python 提高建议; PEP 485 <4>:          分类函数.           (line   46)
* Python 提高建议; PEP 486:              PEP 486 Make the Python Launcher aware of virtual environments.
                                                             (line    6)
* Python 提高建议; PEP 486 <1>:          PEP 486 Make the Python Launcher aware of virtual environments.
                                                             (line   14)
* Python 提高建议; PEP 486 <2>:          Windows<51>.        (line    6)
* Python 提高建议; PEP 487:              PEP 487 自定义类创建.
                                                             (line   29)
* Python 提高建议; PEP 487 <1>:          PEP 487 描述器协议的增强.
                                                             (line    6)
* Python 提高建议; PEP 487 <2>:          PEP 487 描述器协议的增强.
                                                             (line   30)
* Python 提高建议; PEP 487 <3>:          Python API 的变化<4>.
                                                             (line  103)
* Python 提高建议; PEP 487 <4>:          文档<35>.           (line   52)
* Python 提高建议; PEP 487 <5>:          文档<42>.           (line    8)
* Python 提高建议; PEP 487 <6>:          核心与内置<53>.     (line   46)
* Python 提高建议; PEP 488:              PEP 488 Elimination of PYO files.
                                                             (line    6)
* Python 提高建议; PEP 488 <1>:          PEP 488 Elimination of PYO files.
                                                             (line   20)
* Python 提高建议; PEP 488 <2>:          Python API 的变化<5>.
                                                             (line   79)
* Python 提高建议; PEP 488 <3>:          核心与内置<71>.     (line   15)
* Python 提高建议; PEP 488 <4>:          其他选项.           (line   62)
* Python 提高建议; PEP 488 <5>:          其他选项.           (line   65)
* Python 提高建议; PEP 488 <6>:          其他选项.           (line   71)
* Python 提高建议; PEP 488 <7>:          其他选项.           (line   73)
* Python 提高建议; PEP 488 <8>:          test support --- Utilities for the Python test suite.
                                                             (line  192)
* Python 提高建议; PEP 488 <9>:          概述<13>.           (line   59)
* Python 提高建议; PEP 488 <10>:         importlib util -- Utility code for importers.
                                                             (line   24)
* Python 提高建议; PEP 488 <11>:         importlib util -- Utility code for importers.
                                                             (line   64)
* Python 提高建议; PEP 488 <12>:         py_compile --- 编译 Python 源文件.
                                                             (line   25)
* Python 提高建议; PEP 488 <13>:         distutils util --- Miscellaneous other utility functions.
                                                             (line  132)
* Python 提高建议; PEP 488 <14>:         distutils util --- Miscellaneous other utility functions.
                                                             (line  169)
* Python 提高建议; PEP 489:              PEP 489 Multi-phase extension module initialization.
                                                             (line    6)
* Python 提高建议; PEP 489 <1>:          PEP 489 Multi-phase extension module initialization.
                                                             (line   18)
* Python 提高建议; PEP 489 <2>:          构建和 C API 的改变<3>.
                                                             (line   37)
* Python 提高建议; PEP 489 <3>:          概述<13>.           (line   63)
* Python 提高建议; PEP 489 <4>:          importlib machinery -- Importers and path hooks.
                                                             (line   74)
* Python 提高建议; PEP 489 <5>:          importlib machinery -- Importers and path hooks.
                                                             (line  315)
* Python 提高建议; PEP 489 <6>:          importlib machinery -- Importers and path hooks.
                                                             (line  321)
* Python 提高建议; PEP 489 <7>:          模块方法表和初始化函数.
                                                             (line  114)
* Python 提高建议; PEP 489 <8>:          构建C/C++扩展.      (line   34)
* Python 提高建议; PEP 489 <9>:          Multi-phase initialization.
                                                             (line  107)
* Python 提高建议; PEP 492:              PEP 525 异步生成器. (line    6)
* Python 提高建议; PEP 492 <1>:          新关键字.           (line    7)
* Python 提高建议; PEP 492 <2>:          PEP 492 - 使用 async 和 await 语法实现协程.
                                                             (line    6)
* Python 提高建议; PEP 492 <3>:          PEP 492 - 使用 async 和 await 语法实现协程.
                                                             (line   97)
* Python 提高建议; PEP 492 <4>:          新关键字<2>.        (line    7)
* Python 提高建议; PEP 492 <5>:          C API 的变化<4>.    (line   25)
* Python 提高建议; PEP 492 <6>:          核心与内置<38>.     (line   99)
* Python 提高建议; PEP 492 <7>:          库<59>.             (line   36)
* Python 提高建议; PEP 492 <8>:          库<71>.             (line   16)
* Python 提高建议; PEP 492 <9>:          核心与内置<68>.     (line   14)
* Python 提高建议; PEP 492 <10>:         可等待对象.         (line   25)
* Python 提高建议; PEP 492 <11>:         yield 表达式.       (line   85)
* Python 提高建议; PEP 492 <12>:         async with 语句.    (line   43)
* Python 提高建议; PEP 492 <13>:         容器抽象基类.       (line  237)
* Python 提高建议; PEP 492 <14>:         Code Objects Bit Flags.
                                                             (line   42)
* Python 提高建议; PEP 492 <15>:         Code Objects Bit Flags.
                                                             (line   51)
* Python 提高建议; PEP 492 <16>:         术语对照表.         (line   83)
* Python 提高建议; PEP 492 <17>:         术语对照表.         (line  110)
* Python 提高建议; PEP 492 <18>:         术语对照表.         (line  116)
* Python 提高建议; PEP 492 <19>:         术语对照表.         (line  124)
* Python 提高建议; PEP 492 <20>:         术语对照表.         (line  134)
* Python 提高建议; PEP 492 <21>:         术语对照表.         (line  232)
* Python 提高建议; PEP 492 <22>:         术语对照表.         (line  238)
* Python 提高建议; PEP 493:              PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具.
                                                             (line    6)
* Python 提高建议; PEP 494:              Python 3 6 有什么新变化.
                                                             (line   16)
* Python 提高建议; PEP 495:              PEP 495 消除本地时间的歧义.
                                                             (line   13)
* Python 提高建议; PEP 495 <1>:          PEP 495 消除本地时间的歧义.
                                                             (line   36)
* Python 提高建议; PEP 495 <2>:          库<54>.             (line   96)
* Python 提高建议; PEP 498:              PEP 498 格式化的字符串文字.
                                                             (line    6)
* Python 提高建议; PEP 498 <1>:          PEP 498 格式化的字符串文字.
                                                             (line   25)
* Python 提高建议; PEP 498 <2>:          核心与内置<56>.     (line  284)
* Python 提高建议; PEP 498 <3>:          格式化字符串字面值. (line  119)
* Python 提高建议; PEP 498 <4>:          术语对照表.         (line  337)
* Python 提高建议; PEP 5:                PEP 230 Warning Framework.
                                                             (line   66)
* Python 提高建议; PEP 5 <1>:            提议对 Python 加入不兼容的更改是否合理？.
                                                             (line   11)
* Python 提高建议; PEP 506:              secrets.            (line   19)
* Python 提高建议; PEP 506 <1>:          库<61>.             (line   60)
* Python 提高建议; PEP 506 <2>:          secrets --- 生成安全随机数字用于管理密码.
                                                             (line   21)
* Python 提高建议; PEP 511:              Python API 的变化<4>.
                                                             (line   32)
* Python 提高建议; PEP 514:              Windows<41>.        (line    8)
* Python 提高建议; PEP 515:              PEP 515 数字文字中的下划线。.
                                                             (line    6)
* Python 提高建议; PEP 515 <1>:          PEP 515 数字文字中的下划线。.
                                                             (line   28)
* Python 提高建议; PEP 515 <2>:          核心与内置<52>.     (line   15)
* Python 提高建议; PEP 515 <3>:          核心与内置<52>.     (line   43)
* Python 提高建议; PEP 515 <4>:          格式规格迷你语言.   (line   89)
* Python 提高建议; PEP 519:              PEP 519 添加文件系统路径协议.
                                                             (line   62)
* Python 提高建议; PEP 519 <1>:          库<54>.             (line    6)
* Python 提高建议; PEP 519 <2>:          核心与内置<55>.     (line   19)
* Python 提高建议; PEP 519 <3>:          库<59>.             (line   16)
* Python 提高建议; PEP 519 <4>:          库<59>.             (line   27)
* Python 提高建议; PEP 519 <5>:          库<59>.             (line   29)
* Python 提高建议; PEP 519 <6>:          C API<32>.          (line    6)
* Python 提高建议; PEP 519 <7>:          术语对照表.         (line  836)
* Python 提高建议; PEP 520:              PEP 520 保留类属性定义顺序.
                                                             (line   17)
* Python 提高建议; PEP 523:              PEP 523 向CPython 添加框架评估API.
                                                             (line   12)
* Python 提高建议; PEP 523 <1>:          PEP 523 向CPython 添加框架评估API.
                                                             (line   26)
* Python 提高建议; PEP 523 <2>:          工具/示例<18>.      (line    7)
* Python 提高建议; PEP 523 <3>:          工具/示例<22>.      (line    7)
* Python 提高建议; PEP 523 <4>:          核心与内置<52>.     (line   83)
* Python 提高建议; PEP 524:              摘要 - 发布重点<3>. (line   66)
* Python 提高建议; PEP 524 <1>:          os<3>.              (line   20)
* Python 提高建议; PEP 524 <2>:          os<3>.              (line   24)
* Python 提高建议; PEP 524 <3>:          库<53>.             (line  150)
* Python 提高建议; PEP 524 <4>:          库<53>.             (line  154)
* Python 提高建议; PEP 524 <5>:          随机数<2>.          (line   35)
* Python 提高建议; PEP 525:              PEP 525 异步生成器. (line   22)
* Python 提高建议; PEP 525 <1>:          核心与内置<52>.     (line   49)
* Python 提高建议; PEP 525 <2>:          yield 表达式.       (line   83)
* Python 提高建议; PEP 525 <3>:          容器抽象基类.       (line  237)
* Python 提高建议; PEP 525 <4>:          sys --- 系统相关的参数和函数.
                                                             (line  688)
* Python 提高建议; PEP 525 <5>:          sys --- 系统相关的参数和函数.
                                                             (line 1204)
* Python 提高建议; PEP 525 <6>:          Code Objects Bit Flags.
                                                             (line   60)
* Python 提高建议; PEP 525 <7>:          术语对照表.         (line  110)
* Python 提高建议; PEP 526:              ast.                (line   17)
* Python 提高建议; PEP 526 <1>:          PEP 563：延迟的标注求值.
                                                             (line    6)
* Python 提高建议; PEP 526 <2>:          PEP 526 变量注释的语法.
                                                             (line   26)
* Python 提高建议; PEP 526 <3>:          typing<2>.          (line   23)
* Python 提高建议; PEP 526 <4>:          核心与内置<52>.     (line   51)
* Python 提高建议; PEP 526 <5>:          带标注的赋值语句.   (line   32)
* Python 提高建议; PEP 526 <6>:          函数定义.           (line  108)
* Python 提高建议; PEP 526 <7>:          typing --- 类型标注支持.
                                                             (line   15)
* Python 提高建议; PEP 526 <8>:          类 函数和修饰器.    (line  500)
* Python 提高建议; PEP 526 <9>:          类 函数和修饰器.    (line  534)
* Python 提高建议; PEP 526 <10>:         类 函数和修饰器.    (line  832)
* Python 提高建议; PEP 526 <11>:         dataclasses --- 数据类.
                                                             (line   14)
* Python 提高建议; PEP 526 <12>:         类变量.             (line    7)
* Python 提高建议; PEP 526 <13>:         ast 中的辅助函数.   (line   15)
* Python 提高建议; PEP 526 <14>:         术语对照表.         (line   52)
* Python 提高建议; PEP 526 <15>:         术语对照表.         (line 1078)
* Python 提高建议; PEP 528:              PEP 528 将Windows控制台编码更改为UTF-8.
                                                             (line   17)
* Python 提高建议; PEP 528 <1>:          UTF-8 模式.         (line   38)
* Python 提高建议; PEP 528 <2>:          全局配置变量.       (line  103)
* Python 提高建议; PEP 529:              Python API 的变化.  (line    7)
* Python 提高建议; PEP 529 <1>:          PEP 529 将Windows文件系统编码更改为UTF-8.
                                                             (line   22)
* Python 提高建议; PEP 529 <2>:          库<24>.             (line   22)
* Python 提高建议; PEP 529 <3>:          Windows<36>.        (line   14)
* Python 提高建议; PEP 529 <4>:          环境变量.           (line  270)
* Python 提高建议; PEP 529 <5>:          UTF-8 模式.         (line   40)
* Python 提高建议; PEP 529 <6>:          文件和目录.         (line  261)
* Python 提高建议; PEP 529 <7>:          sys --- 系统相关的参数和函数.
                                                             (line  562)
* Python 提高建议; PEP 529 <8>:          sys --- 系统相关的参数和函数.
                                                             (line 1237)
* Python 提高建议; PEP 529 <9>:          File System Encoding.
                                                             (line    9)
* Python 提高建议; PEP 529 <10>:         全局配置变量.       (line   91)
* Python 提高建议; PEP 530:              PEP 530 异步推导.   (line    6)
* Python 提高建议; PEP 530 <1>:          PEP 530 异步推导.   (line   18)
* Python 提高建议; PEP 530 <2>:          核心与内置<52>.     (line  145)
* Python 提高建议; PEP 530 <3>:          列表、集合与字典的显示.
                                                             (line   42)
* Python 提高建议; PEP 538:              PEP 538 传统 C 区域强制转换.
                                                             (line   10)
* Python 提高建议; PEP 538 <1>:          PEP 538 传统 C 区域强制转换.
                                                             (line   29)
* Python 提高建议; PEP 538 <2>:          PEP 538 传统 C 区域强制转换.
                                                             (line   38)
* Python 提高建议; PEP 538 <3>:          PEP 540 强制 UTF-8 运行时模式.
                                                             (line   22)
* Python 提高建议; PEP 538 <4>:          文档<25>.           (line   68)
* Python 提高建议; PEP 538 <5>:          文档<26>.           (line    6)
* Python 提高建议; PEP 538 <6>:          核心与内置<39>.     (line  135)
* Python 提高建议; PEP 538 <7>:          环境变量.           (line  326)
* Python 提高建议; PEP 538 <8>:          Python Configuration.
                                                             (line   13)
* Python 提高建议; PEP 539:              PEP 539 用于线程局部存储的新 C API.
                                                             (line   11)
* Python 提高建议; PEP 539 <1>:          PEP 539 用于线程局部存储的新 C API.
                                                             (line   25)
* Python 提高建议; PEP 539 <2>:          C API<21>.          (line   13)
* Python 提高建议; PEP 539 <3>:          Thread Specific Storage TSS API.
                                                             (line   15)
* Python 提高建议; PEP 540:              PEP 540 强制 UTF-8 运行时模式.
                                                             (line   16)
* Python 提高建议; PEP 540 <1>:          PEP 540 强制 UTF-8 运行时模式.
                                                             (line   29)
* Python 提高建议; PEP 540 <2>:          核心与内置<36>.     (line   63)
* Python 提高建议; PEP 540 <3>:          环境变量.           (line  385)
* Python 提高建议; PEP 540 <4>:          Python Configuration.
                                                             (line   13)
* Python 提高建议; PEP 544:              typing.             (line   29)
* Python 提高建议; PEP 544 <1>:          typing --- 类型标注支持.
                                                             (line   15)
* Python 提高建议; PEP 544 <2>:          名义性子类型 区别于 结构性子类型.
                                                             (line   20)
* Python 提高建议; PEP 544 <3>:          类 函数和修饰器.    (line   86)
* Python 提高建议; PEP 545:              PEP 545 Python 文档翻译.
                                                             (line    6)
* Python 提高建议; PEP 545 <1>:          PEP 545 Python 文档翻译.
                                                             (line   19)
* Python 提高建议; PEP 552:              PEP 552 基于哈希值的 pyc 文件.
                                                             (line   12)
* Python 提高建议; PEP 552 <1>:          PEP 552 基于哈希值的 pyc 文件.
                                                             (line   29)
* Python 提高建议; PEP 552 <2>:          库<29>.             (line  795)
* Python 提高建议; PEP 552 <3>:          核心与内置<36>.     (line   75)
* Python 提高建议; PEP 552 <4>:          概述<13>.           (line   67)
* Python 提高建议; PEP 552 <5>:          py_compile --- 编译 Python 源文件.
                                                             (line   65)
* Python 提高建议; PEP 552 <6>:          PyConfig.           (line  137)
* Python 提高建议; PEP 553:              PEP 553 内置的 breakpoint.
                                                             (line   19)
* Python 提高建议; PEP 553 <1>:          核心与内置<38>.     (line   73)
* Python 提高建议; PEP 557:              dataclasses.        (line   25)
* Python 提高建议; PEP 557 <1>:          dataclasses --- 数据类.
                                                             (line   12)
* Python 提高建议; PEP 560:              PEP 560 对 typing 模块和泛型类型的核心支持.
                                                             (line   17)
* Python 提高建议; PEP 560 <1>:          types.              (line   11)
* Python 提高建议; PEP 560 <2>:          核心与内置<36>.     (line   66)
* Python 提高建议; PEP 560 <3>:          解析 MRO 条目.      (line   14)
* Python 提高建议; PEP 560 <4>:          模拟泛型类型.       (line   19)
* Python 提高建议; PEP 560 <5>:          动态类型创建.       (line   50)
* Python 提高建议; PEP 560 <6>:          动态类型创建.       (line   63)
* Python 提高建议; PEP 562:              PEP 562 定制对模块属性的访问.
                                                             (line   15)
* Python 提高建议; PEP 562 <1>:          库<36>.             (line   63)
* Python 提高建议; PEP 562 <2>:          核心与内置<36>.     (line   69)
* Python 提高建议; PEP 562 <3>:          自定义模块属性访问. (line   44)
* Python 提高建议; PEP 563:              PEP 563：延迟的标注求值.
                                                             (line   43)
* Python 提高建议; PEP 563 <1>:          future 语句.        (line   30)
* Python 提高建议; PEP 563 <2>:          函数定义.           (line  112)
* Python 提高建议; PEP 563 <3>:          __future__ --- Future 语句定义.
                                                             (line   86)
* Python 提高建议; PEP 564:              PEP 564 具有纳秒级精度的新时间函数.
                                                             (line    7)
* Python 提高建议; PEP 564 <1>:          PEP 564 具有纳秒级精度的新时间函数.
                                                             (line   30)
* Python 提高建议; PEP 564 <2>:          time<2>.            (line    6)
* Python 提高建议; PEP 564 <3>:          库<38>.             (line  300)
* Python 提高建议; PEP 565:              PEP 565 在 __main__ 中显示 DeprecationWarning.
                                                             (line   35)
* Python 提高建议; PEP 566:              Using importlib metadata.
                                                             (line   24)
* Python 提高建议; PEP 566 <1>:          Distributions.      (line   28)
* Python 提高建议; PEP 567:              contextvars.        (line   17)
* Python 提高建议; PEP 567 <1>:          asyncio<2>.         (line   17)
* Python 提高建议; PEP 567 <2>:          文档<25>.           (line   86)
* Python 提高建议; PEP 567 <3>:          文档<27>.           (line    9)
* Python 提高建议; PEP 567 <4>:          核心与内置<35>.     (line   63)
* Python 提高建议; PEP 567 <5>:          contextvars 上下文变量.
                                                             (line   16)
* Python 提高建议; PEP 567 <6>:          调度回调.           (line   28)
* Python 提高建议; PEP 567 <7>:          调度延迟回调.       (line   28)
* Python 提高建议; PEP 567 <8>:          调度延迟回调.       (line   44)
* Python 提高建议; PEP 567 <9>:          Future 对象<2>.     (line   89)
* Python 提高建议; PEP 570:              仅限位置形参.       (line   61)
* Python 提高建议; PEP 570 <1>:          Python API 的变化.  (line  136)
* Python 提高建议; PEP 570 <2>:          核心与内置<26>.     (line   36)
* Python 提高建议; PEP 570 <3>:          函数定义.           (line   74)
* Python 提高建议; PEP 572:              赋值表达式.         (line   36)
* Python 提高建议; PEP 572 <1>:          CPython 字节码的改变.
                                                             (line   24)
* Python 提高建议; PEP 572 <2>:          文档<12>.           (line   13)
* Python 提高建议; PEP 572 <3>:          核心与内置<22>.     (line   18)
* Python 提高建议; PEP 572 <4>:          核心与内置<29>.     (line   90)
* Python 提高建议; PEP 572 <5>:          字典显示.           (line   35)
* Python 提高建议; PEP 572 <6>:          赋值表达式<2>.      (line   22)
* Python 提高建议; PEP 572 <7>:          为什么不能在表达式中赋值？.
                                                             (line   13)
* Python 提高建议; PEP 574:              具有外部数据缓冲区的 pickle 协议 5.
                                                             (line   13)
* Python 提高建议; PEP 574 <1>:          数据流格式.         (line   37)
* Python 提高建议; PEP 574 <2>:          示例<4>.            (line   60)
* Python 提高建议; PEP 578:              PEP 578 Python 运行时审核钩子.
                                                             (line   10)
* Python 提高建议; PEP 578 <1>:          审计事件表.         (line    8)
* Python 提高建议; PEP 578 <2>:          sys --- 系统相关的参数和函数.
                                                             (line   38)
* Python 提高建议; PEP 578 <3>:          系统功能.           (line  150)
* Python 提高建议; PEP 586:              typing.             (line   17)
* Python 提高建议; PEP 586 <1>:          typing --- 类型标注支持.
                                                             (line   15)
* Python 提高建议; PEP 586 <2>:          类 函数和修饰器.    (line  824)
* Python 提高建议; PEP 587:              PEP 587 Python 初始化配置.
                                                             (line    6)
* Python 提高建议; PEP 587 <1>:          PEP 587 Python 初始化配置.
                                                             (line   80)
* Python 提高建议; PEP 587 <2>:          核心与内置<21>.     (line   12)
* Python 提高建议; PEP 587 <3>:          C API<12>.          (line    6)
* Python 提高建议; PEP 587 <4>:          Python初始化配置.   (line   81)
* Python 提高建议; PEP 589:              typing.             (line    8)
* Python 提高建议; PEP 589 <1>:          typing --- 类型标注支持.
                                                             (line   16)
* Python 提高建议; PEP 589 <2>:          类 函数和修饰器.    (line  551)
* Python 提高建议; PEP 590:              Vectorcall 用于 CPython 的快速调用协议.
                                                             (line   11)
* Python 提高建议; PEP 590 <1>:          C API<12>.          (line   17)
* Python 提高建议; PEP 591:              typing.             (line   23)
* Python 提高建议; PEP 591 <1>:          typing --- 类型标注支持.
                                                             (line   16)
* Python 提高建议; PEP 591 <2>:          类 函数和修饰器.    (line  653)
* Python 提高建议; PEP 591 <3>:          类 函数和修饰器.    (line  866)
* Python 提高建议; PEP 6:                Python 版本的编号形式是怎样的？.
                                                             (line    8)
* Python 提高建议; PEP 602:              Python 有多稳定？.  (line    8)
* Python 提高建议; PEP 623:              文档<4>.            (line   19)
* Python 提高建议; PEP 623 <1>:          Unicode对象.        (line   31)
* Python 提高建议; PEP 628:              cmath.              (line    7)
* Python 提高建议; PEP 628 <1>:          math<3>.            (line    7)
* Python 提高建议; PEP 628 <2>:          库<54>.             (line   32)
* Python 提高建议; PEP 7:                构建和 C API 的改变<2>.
                                                             (line    9)
* Python 提高建议; PEP 7 <1>:            代码标准.           (line    6)
* Python 提高建议; PEP 7 <2>:            有用的宏.           (line   81)
* Python 提高建议; PEP 7 <3>:            有用的宏.           (line   99)
* Python 提高建议; PEP 8:                Library Changes.    (line   26)
* Python 提高建议; PEP 8 <1>:            库<38>.             (line  125)
* Python 提高建议; PEP 8 <2>:            IDLE<53>.           (line   81)
* Python 提高建议; PEP 8 <3>:            小插曲：编码风格.   (line   11)
* Python 提高建议; PEP 8 <4>:            编辑器和集成开发环境.
                                                             (line    7)
* Python 提高建议; PEP 8 <5>:            值比较.             (line   46)
* Python 提高建议; PEP 8 <6>:            Using real Argument Clinic converters instead of "legacy converters".
                                                             (line   50)
* Python 提高建议; PEP 8 <7>:            是否有 Python 程序规范代码标准或风格指南？.
                                                             (line    6)
* Python 提高建议; PEP 8 <8>:            如何让编辑器不要在我的 Python 源代码中插入 tab ？.
                                                             (line    6)
* PYTHON*:                               其他改进<2>.        (line    9)
* PYTHON* <1>:                           接口选项.           (line   66)
* PYTHON* <2>:                           接口选项.           (line  119)
* PYTHON* <3>:                           其他选项.           (line   37)
* PYTHON* <4>:                           其他选项.           (line   53)
* PYTHON* <5>:                           全局配置变量.       (line   54)
* PYTHONASYNCIODEBUG:                    开启调试模式.       (line   10)
* PYTHONASYNCIODEBUG <1>:                Debug 模式.         (line   11)
* PYTHONBREAKPOINT:                      PEP 553 内置的 breakpoint.
                                                             (line   12)
* PYTHONBREAKPOINT <1>:                  sys --- 系统相关的参数和函数.
                                                             (line  165)
* PYTHONBREAKPOINT <2>:                  sys --- 系统相关的参数和函数.
                                                             (line  175)
* PYTHONBREAKPOINT <3>:                  sys --- 系统相关的参数和函数.
                                                             (line  179)
* PYTHONCASEOK:                          PEP 235 Importing Modules on Case-Insensitive Platforms.
                                                             (line   17)
* PYTHONCOERCECLOCALE:                   PEP 538 传统 C 区域强制转换.
                                                             (line   11)
* PYTHONCOERCECLOCALE <1>:               环境变量.           (line  378)
* PYTHONCOERCECLOCALE <2>:               Python Configuration.
                                                             (line   15)
* PYTHONDEBUG:                           其他选项.           (line   32)
* PYTHONDEBUG <1>:                       全局配置变量.       (line   26)
* PYTHONDEVMODE:                         开发运行时模式 -X dev.
                                                             (line    6)
* PYTHONDEVMODE <1>:                     test support script_helper --- Utilities for the Python execution tests.
                                                             (line  102)
* PYTHONDOCS:                            pydoc --- 文档生成器和在线帮助系统.
                                                             (line   67)
* PYTHONDONTWRITEBYTECODE:               Interpreter Changes<2>.
                                                             (line   16)
* PYTHONDONTWRITEBYTECODE <1>:           新增和改进的模块<2>.
                                                             (line  624)
* PYTHONDONTWRITEBYTECODE <2>:           其他选项.           (line   17)
* PYTHONDONTWRITEBYTECODE <3>:           sys --- 系统相关的参数和函数.
                                                             (line  240)
* PYTHONDONTWRITEBYTECODE <4>:           全局配置变量.       (line   34)
* PYTHONDONTWRITEBYTECODE <5>:           如何创建 pyc 文件？.
                                                             (line   17)
* PYTHONDUMPREFS:                        调试构建使用与发布构建相同的 ABI.
                                                             (line   12)
* PYTHONDUMPREFS <1>:                    构建<15>.           (line   54)
* PYTHONDUMPREFS <2>:                    PyObject Slots.     (line   24)
* PYTHONFAULTHANDLER:                    faulthandler<3>.    (line   11)
* PYTHONFAULTHANDLER <1>:                faulthandler --- Dump the Python traceback.
                                                             (line   14)
* PYTHONHASHSEED:                        Builtin functions and types.
                                                             (line   17)
* PYTHONHASHSEED <1>:                    Porting Python code.
                                                             (line    6)
* PYTHONHASHSEED <2>:                    核心与内置<36>.     (line   30)
* PYTHONHASHSEED <3>:                    其他选项.           (line   83)
* PYTHONHASHSEED <4>:                    其他选项.           (line   95)
* PYTHONHASHSEED <5>:                    环境变量.           (line  111)
* PYTHONHASHSEED <6>:                    基本定制.           (line  238)
* PYTHONHASHSEED <7>:                    全局配置变量.       (line   46)
* PYTHONHASHSEED <8>:                    全局配置变量.       (line   49)
* PYTHONHOME:                            摘要 - 发布重点<3>. (line   90)
* PYTHONHOME <1>:                        其他选项.           (line   38)
* PYTHONHOME <2>:                        环境变量.           (line   16)
* PYTHONHOME <3>:                        环境变量.           (line   17)
* PYTHONHOME <4>:                        环境变量.           (line   31)
* PYTHONHOME <5>:                        查找模块.           (line   38)
* PYTHONHOME <6>:                        查找模块.           (line   52)
* PYTHONHOME <7>:                        查找模块.           (line   80)
* PYTHONHOME <8>:                        test support script_helper --- Utilities for the Python execution tests.
                                                             (line   24)
* PYTHONHOME <9>:                        嵌入Python<2>.      (line   38)
* PYTHONHOME <10>:                       嵌入Python<2>.      (line   44)
* PYTHONHOME <11>:                       全局配置变量.       (line   55)
* PYTHONHOME <12>:                       Process-wide parameters.
                                                             (line  269)
* PYTHONHOME <13>:                       Process-wide parameters.
                                                             (line  283)
* PYTHONHOME <14>:                       PyConfig.           (line  197)
* PYTHONHOME <15>:                       Modifying Python's Search Path.
                                                             (line   60)
* PYTHONHOME <16>:                       Modifying Python's Search Path.
                                                             (line   62)
* Pythonic:                              术语对照表.         (line  881)
* PYTHONINSPECT:                         Other Changes and Fixes<2>.
                                                             (line   13)
* PYTHONINSPECT <1>:                     其他选项.           (line   46)
* PYTHONINSPECT <2>:                     全局配置变量.       (line   66)
* PYTHONIOENCODING:                      其他改进<2>.        (line   75)
* PYTHONIOENCODING <1>:                  Interpreter Changes<2>.
                                                             (line   23)
* PYTHONIOENCODING <2>:                  环境变量.           (line  312)
* PYTHONIOENCODING <3>:                  环境变量.           (line  370)
* PYTHONIOENCODING <4>:                  sys --- 系统相关的参数和函数.
                                                             (line 1270)
* PYTHONIOENCODING <5>:                  Process-wide parameters.
                                                             (line   14)
* PYTHONIOENCODING <6>:                  Process-wide parameters.
                                                             (line   18)
* PYTHONLEGACYWINDOWSFSENCODING:         PEP 529 将Windows文件系统编码更改为UTF-8.
                                                             (line   18)
* PYTHONLEGACYWINDOWSFSENCODING <1>:     sys --- 系统相关的参数和函数.
                                                             (line 1232)
* PYTHONLEGACYWINDOWSFSENCODING <2>:     全局配置变量.       (line   88)
* PYTHONLEGACYWINDOWSSTDIO:              PEP 528 将Windows控制台编码更改为UTF-8.
                                                             (line   12)
* PYTHONLEGACYWINDOWSSTDIO <1>:          环境变量.           (line  135)
* PYTHONLEGACYWINDOWSSTDIO <2>:          sys --- 系统相关的参数和函数.
                                                             (line 1273)
* PYTHONLEGACYWINDOWSSTDIO <3>:          全局配置变量.       (line  100)
* PYTHONMALLOC:                          PYTHONMALLOC 环境变量.
                                                             (line    6)
* PYTHONMALLOC <1>:                      C API 的变化<3>.    (line    9)
* PYTHONMALLOC <2>:                      核心与内置<56>.     (line   91)
* PYTHONMALLOC <3>:                      环境变量.           (line  252)
* PYTHONMALLOC <4>:                      概述<16>.           (line   54)
* PYTHONMALLOC <5>:                      默认内存分配器.     (line   26)
* PYTHONMALLOC <6>:                      自定义内存分配器.   (line  121)
* PYTHONMALLOCSTATS:                     核心与内置<56>.     (line   97)
* PYTHONMALLOCSTATS <1>:                 概述<16>.           (line   57)
* PYTHONNOUSERSITE:                      PEP 370 分用户的 site-packages 目录.
                                                             (line   30)
* PYTHONNOUSERSITE <1>:                  模块内容<7>.        (line   14)
* PYTHONNOUSERSITE <2>:                  全局配置变量.       (line  120)
* PYTHONOPTIMIZE:                        其他选项.           (line   62)
* PYTHONOPTIMIZE <1>:                    全局配置变量.       (line  125)
* PYTHONPATH:                            'python' 命令行为的变化<2>.
                                                             (line    8)
* PYTHONPATH <1>:                        'python' 命令行为的变化<2>.
                                                             (line    9)
* PYTHONPATH <2>:                        模块搜索路径.       (line   12)
* PYTHONPATH <3>:                        标准模块.           (line   27)
* PYTHONPATH <4>:                        标准模块.           (line   27)
* PYTHONPATH <5>:                        其他选项.           (line   37)
* PYTHONPATH <6>:                        环境变量.           (line   26)
* PYTHONPATH <7>:                        环境变量.           (line   32)
* PYTHONPATH <8>:                        环境变量.           (line   34)
* PYTHONPATH <9>:                        附录：设置环境变量. (line   30)
* PYTHONPATH <10>:                       查找模块.           (line   27)
* PYTHONPATH <11>:                       查找模块.           (line   45)
* PYTHONPATH <12>:                       查找模块.           (line   79)
* PYTHONPATH <13>:                       配置.               (line    6)
* PYTHONPATH <14>:                       路径条目查找器.     (line    6)
* PYTHONPATH <15>:                       Installing your CGI script on a Unix system.
                                                             (line   29)
* PYTHONPATH <16>:                       test support script_helper --- Utilities for the Python execution tests.
                                                             (line   25)
* PYTHONPATH <17>:                       sys --- 系统相关的参数和函数.
                                                             (line  901)
* PYTHONPATH <18>:                       sys --- 系统相关的参数和函数.
                                                             (line  907)
* PYTHONPATH <19>:                       构建C/C++扩展.      (line    9)
* PYTHONPATH <20>:                       嵌入Python<2>.      (line   39)
* PYTHONPATH <21>:                       嵌入Python<2>.      (line   44)
* PYTHONPATH <22>:                       全局配置变量.       (line   54)
* PYTHONPATH <23>:                       PyConfig.           (line  252)
* PYTHONPATH <24>:                       Modifying Python's Search Path.
                                                             (line   67)
* PYTHONPATH <25>:                       Modifying Python's Search Path.
                                                             (line   68)
* PYTHONPROFILEIMPORTTIME:               其他语言特性修改<2>.
                                                             (line   44)
* PYTHONPROFILEIMPORTTIME <1>:           核心与内置<38>.     (line   67)
* PYTHONPROFILEIMPORTTIME <2>:           其他选项.           (line  191)
* PYTHONPYCACHEPREFIX:                   用于已编译字节码文件的并行文件系统缓存.
                                                             (line    6)
* PYTHONPYCACHEPREFIX <1>:               核心与内置<29>.     (line  396)
* PYTHONPYCACHEPREFIX <2>:               其他选项.           (line  218)
* PYTHONPYCACHEPREFIX <3>:               sys --- 系统相关的参数和函数.
                                                             (line  255)
* PYTHONSHOWALLOCCOUNT:                  Two new environment variables for debug mode.
                                                             (line   11)
* PYTHONSHOWREFCOUNT:                    Two new environment variables for debug mode.
                                                             (line    7)
* PYTHONSTARTUP:                         sys<6>.             (line   17)
* PYTHONSTARTUP <1>:                     sys<6>.             (line   21)
* PYTHONSTARTUP <2>:                     IDLE<27>.           (line  174)
* PYTHONSTARTUP <3>:                     IDLE<31>.           (line    9)
* PYTHONSTARTUP <4>:                     IDLE<37>.           (line    9)
* PYTHONSTARTUP <5>:                     交互式启动文件.     (line    7)
* PYTHONSTARTUP <6>:                     其他选项.           (line   44)
* PYTHONSTARTUP <7>:                     示例.               (line    8)
* PYTHONSTARTUP <8>:                     启动和代码执行.     (line    7)
* PYTHONSTARTUP <9>:                     sys --- 系统相关的参数和函数.
                                                             (line  815)
* PYTHONSTARTUP <10>:                    Readline（类库） 配置.
                                                             (line   10)
* PYTHONTRACEMALLOC:                     tracemalloc --- 跟踪内存分配.
                                                             (line   25)
* PYTHONTRACEMALLOC <1>:                 tracemalloc --- 跟踪内存分配.
                                                             (line   32)
* PYTHONTRACEMALLOC <2>:                 函数<9>.            (line   68)
* PYTHONUNBUFFERED:                      其他选项.           (line  121)
* PYTHONUNBUFFERED <1>:                  全局配置变量.       (line  140)
* PYTHONUSERBASE:                        PEP 370 分用户的 site-packages 目录.
                                                             (line   23)
* PYTHONUSERBASE <1>:                    模块内容<7>.        (line   35)
* PYTHONUSERBASE <2>:                    模块内容<7>.        (line   59)
* PYTHONUSERSITE:                        test support script_helper --- Utilities for the Python execution tests.
                                                             (line   25)
* PYTHONUTF8:                            PEP 540 强制 UTF-8 运行时模式.
                                                             (line    6)
* PYTHONUTF8 <1>:                        其他选项.           (line  215)
* PYTHONUTF8 <2>:                        环境变量.           (line  320)
* PYTHONUTF8 <3>:                        UTF-8 模式.         (line   16)
* PYTHONUTF8 <4>:                        sys --- 系统相关的参数和函数.
                                                             (line 1272)
* PYTHONUTF8 <5>:                        Python Configuration.
                                                             (line   14)
* PYTHONVERBOSE:                         其他选项.           (line  129)
* PYTHONVERBOSE <1>:                     全局配置变量.       (line  151)
* PYTHONWARNINGS:                        warnings.           (line   18)
* PYTHONWARNINGS <1>:                    其他语言特性修改<7>.
                                                             (line  158)
* PYTHONWARNINGS <2>:                    Changes to the Handling of Deprecation Warnings.
                                                             (line   25)
* PYTHONWARNINGS <3>:                    Interpreter Changes.
                                                             (line    6)
* PYTHONWARNINGS <4>:                    其他选项.           (line  145)
* PYTHONWARNINGS <5>:                    Describing Warning Filters.
                                                             (line    7)
* PYTHONWARNINGS <6>:                    Describing Warning Filters.
                                                             (line   21)
* PYTHONWARNINGS <7>:                    默认警告过滤器.     (line    7)
* python_branch() (在 platform 模块中):  跨平台.             (line   75)
* python_build() (在 platform 模块中):   跨平台.             (line   66)
* python_compiler() (在 platform 模块中): 跨平台.            (line   71)
* PYTHON_DOM:                            模块内容<6>.        (line   19)
* python_implementation() (在 platform 模块中): 跨平台.      (line   79)
* python_is_optimized() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  203)
* python_revision() (在 platform 模块中): 跨平台.            (line   84)
* python_version() (在 platform 模块中): 跨平台.             (line   88)
* python_version_tuple() (在 platform 模块中): 跨平台.       (line   95)
* PyThreadState:                         Thread State and the Global Interpreter Lock.
                                                             (line   23)
* PyThreadState <1>:                     Thread State and the Global Interpreter Lock.
                                                             (line   23)
* PyThreadState (C 类型):                高阶 API.           (line   21)
* PyThreadState_Clear (C 函数):          Low-level API.      (line   42)
* PyThreadState_Delete (C 函数):         Low-level API.      (line   47)
* PyThreadState_Get (C 函数):            高阶 API.           (line   76)
* PyThreadState_GetDict (C 函数):        Low-level API.      (line   75)
* PyThreadState_New (C 函数):            Low-level API.      (line   35)
* PyThreadState_Next (C 函数):           高级调试器支持.     (line   32)
* PyThreadState_SetAsyncExc (C 函数):    Low-level API.      (line   84)
* PyThreadState_Swap (C 函数):           高阶 API.           (line   82)
* PyThread_create_key (C 函数):          Thread Local Storage TLS API.
                                                             (line   17)
* PyThread_delete_key (C 函数):          Thread Local Storage TLS API.
                                                             (line   19)
* PyThread_delete_key_value (C 函数):    Thread Local Storage TLS API.
                                                             (line   25)
* PyThread_get_key_value (C 函数):       Thread Local Storage TLS API.
                                                             (line   23)
* PyThread_ReInitTLS (C 函数):           Thread Local Storage TLS API.
                                                             (line   27)
* PyThread_set_key_value (C 函数):       Thread Local Storage TLS API.
                                                             (line   21)
* PyThread_tss_alloc (C 函数):           Dynamic Allocation. (line   11)
* PyThread_tss_create (C 函数):          方法<4>.            (line   16)
* PyThread_tss_delete (C 函数):          方法<4>.            (line   24)
* PyThread_tss_free (C 函数):            Dynamic Allocation. (line   17)
* PyThread_tss_get (C 函数):             方法<4>.            (line   39)
* PyThread_tss_is_created (C 函数):      方法<4>.            (line   11)
* PyThread_tss_set (C 函数):             方法<4>.            (line   33)
* PyTimeZone_FromOffset (C 函数):        DateTime 对象<2>.   (line  114)
* PyTimeZone_FromOffsetAndName (C 函数): DateTime 对象<2>.   (line  121)
* PyTime_Check (C 函数):                 DateTime 对象<2>.   (line   44)
* PyTime_CheckExact (C 函数):            DateTime 对象<2>.   (line   49)
* PyTime_FromTime (C 函数):              DateTime 对象<2>.   (line   96)
* PyTime_FromTimeAndFold (C 函数):       DateTime 对象<2>.   (line  101)
* PyTraceMalloc_Track (C 函数):          tracemalloc C API.  (line    8)
* PyTraceMalloc_Untrack (C 函数):        tracemalloc C API.  (line   18)
* PyTrace_CALL (C 变量):                 分析和跟踪.         (line   61)
* PyTrace_C_CALL (C 变量):               分析和跟踪.         (line   93)
* PyTrace_C_EXCEPTION (C 变量):          分析和跟踪.         (line   98)
* PyTrace_C_RETURN (C 变量):             分析和跟踪.         (line  103)
* PyTrace_EXCEPTION (C 变量):            分析和跟踪.         (line   69)
* PyTrace_LINE (C 变量):                 分析和跟踪.         (line   81)
* PyTrace_OPCODE (C 变量):               分析和跟踪.         (line  108)
* PyTrace_RETURN (C 变量):               分析和跟踪.         (line   88)
* PyTupleObject (C 类型):                元组对象.           (line    6)
* PyTuple_Check (C 函数):                元组对象.           (line   15)
* PyTuple_CheckExact (C 函数):           元组对象.           (line   19)
* PyTuple_ClearFreeList (C 函数):        元组对象.           (line   92)
* PyTuple_GetItem (C 函数):              元组对象.           (line   42)
* PyTuple_GetSlice (C 函数):             元组对象.           (line   51)
* PyTuple_GET_ITEM (C 函数):             元组对象.           (line   47)
* PyTuple_GET_SIZE (C 函数):             元组对象.           (line   37)
* PyTuple_New (C 函数):                  元组对象.           (line   23)
* PyTuple_Pack (C 函数):                 元组对象.           (line   27)
* PyTuple_SetItem (C 函数):              元组对象.           (line   59)
* PyTuple_SetItem():                     引用计数细节.       (line   26)
* PyTuple_SET_ITEM (C 函数):             元组对象.           (line   69)
* PyTuple_Size (C 函数):                 元组对象.           (line   33)
* PyTuple_Type (C 变量):                 元组对象.           (line   10)
* PyTypeObject (C 类型):                 类型对象<2>.        (line    6)
* PyTypeObject.tp_alloc (C 成员):        PyTypeObject Slots. (line 1169)
* PyTypeObject.tp_allocs (C 成员):       PyTypeObject Slots. (line 1391)
* PyTypeObject.tp_as_async (C 成员):     PyTypeObject Slots. (line  239)
* PyTypeObject.tp_as_buffer (C 成员):    PyTypeObject Slots. (line  439)
* PyTypeObject.tp_as_mapping (C 成员):   PyTypeObject Slots. (line  301)
* PyTypeObject.tp_as_number (C 成员):    PyTypeObject Slots. (line  279)
* PyTypeObject.tp_as_sequence (C 成员):  PyTypeObject Slots. (line  290)
* PyTypeObject.tp_base (C 成员):         PyTypeObject Slots. (line  982)
* PyTypeObject.tp_bases (C 成员):        PyTypeObject Slots. (line 1280)
* PyTypeObject.tp_basicsize (C 成员):    PyTypeObject Slots. (line   47)
* PyTypeObject.tp_cache (C 成员):        PyTypeObject Slots. (line 1302)
* PyTypeObject.tp_call (C 成员):         PyTypeObject Slots. (line  349)
* PyTypeObject.tp_clear (C 成员):        PyTypeObject Slots. (line  720)
* PyTypeObject.tp_dealloc (C 成员):      PyTypeObject Slots. (line   99)
* PyTypeObject.tp_del (C 成员):          PyTypeObject Slots. (line 1327)
* PyTypeObject.tp_descr_get (C 成员):    PyTypeObject Slots. (line 1039)
* PyTypeObject.tp_descr_set (C 成员):    PyTypeObject Slots. (line 1051)
* PyTypeObject.tp_dict (C 成员):         PyTypeObject Slots. (line 1014)
* PyTypeObject.tp_dictoffset (C 成员):   PyTypeObject Slots. (line 1066)
* PyTypeObject.tp_doc (C 成员):          PyTypeObject Slots. (line  648)
* PyTypeObject.tp_finalize (C 成员):     PyTypeObject Slots. (line 1339)
* PyTypeObject.tp_flags (C 成员):        PyTypeObject Slots. (line  450)
* PyTypeObject.tp_free (C 成员):         PyTypeObject Slots. (line 1228)
* PyTypeObject.tp_frees (C 成员):        PyTypeObject Slots. (line 1395)
* PyTypeObject.tp_getattr (C 成员):      PyTypeObject Slots. (line  200)
* PyTypeObject.tp_getattro (C 成员):     PyTypeObject Slots. (line  387)
* PyTypeObject.tp_getset (C 成员):       PyTypeObject Slots. (line  967)
* PyTypeObject.tp_hash (C 成员):         PyTypeObject Slots. (line  312)
* PyTypeObject.tp_init (C 成员):         PyTypeObject Slots. (line 1132)
* PyTypeObject.tp_is_gc (C 成员):        PyTypeObject Slots. (line 1251)
* PyTypeObject.tp_itemsize (C 成员):     PyTypeObject Slots. (line   47)
* PyTypeObject.tp_iter (C 成员):         PyTypeObject Slots. (line  899)
* PyTypeObject.tp_iternext (C 成员):     PyTypeObject Slots. (line  915)
* PyTypeObject.tp_maxalloc (C 成员):     PyTypeObject Slots. (line 1399)
* PyTypeObject.tp_members (C 成员):      PyTypeObject Slots. (line  952)
* PyTypeObject.tp_methods (C 成员):      PyTypeObject Slots. (line  937)
* PyTypeObject.tp_mro (C 成员):          PyTypeObject Slots. (line 1291)
* PyTypeObject.tp_name (C 成员):         PyTypeObject Slots. (line   12)
* PyTypeObject.tp_new (C 成员):          PyTypeObject Slots. (line 1192)
* PyTypeObject.tp_next (C 成员):         PyTypeObject Slots. (line 1408)
* PyTypeObject.tp_prev (C 成员):         PyTypeObject Slots. (line 1403)
* PyTypeObject.tp_repr (C 成员):         PyTypeObject Slots. (line  253)
* PyTypeObject.tp_richcompare (C 成员):  PyTypeObject Slots. (line  789)
* PyTypeObject.tp_setattr (C 成员):      PyTypeObject Slots. (line  219)
* PyTypeObject.tp_setattro (C 成员):     PyTypeObject Slots. (line  412)
* PyTypeObject.tp_str (C 成员):          PyTypeObject Slots. (line  361)
* PyTypeObject.tp_subclasses (C 成员):   PyTypeObject Slots. (line 1310)
* PyTypeObject.tp_traverse (C 成员):     PyTypeObject Slots. (line  658)
* PyTypeObject.tp_vectorcall_offset (C 成员): PyTypeObject Slots.
                                                             (line  141)
* PyTypeObject.tp_version_tag (C 成员):  PyTypeObject Slots. (line 1331)
* PyTypeObject.tp_weaklist (C 成员):     PyTypeObject Slots. (line 1318)
* PyTypeObject.tp_weaklistoffset (C 成员): PyTypeObject Slots.
                                                             (line  863)
* PyType_Check (C 函数):                 类型对象<2>.        (line   15)
* PyType_CheckExact (C 函数):            类型对象<2>.        (line   20)
* PyType_ClearCache (C 函数):            类型对象<2>.        (line   25)
* PyType_FromSpec (C 函数):              Creating Heap-Allocated Types.
                                                             (line   26)
* PyType_FromSpecWithBases (C 函数):     Creating Heap-Allocated Types.
                                                             (line    9)
* PyType_GenericAlloc (C 函数):          类型对象<2>.        (line   67)
* PyType_GenericNew (C 函数):            类型对象<2>.        (line   75)
* PyType_GetFlags (C 函数):              类型对象<2>.        (line   29)
* PyType_GetSlot (C 函数):               类型对象<2>.        (line   88)
* PyType_HasFeature (C 函数):            类型对象<2>.        (line   48)
* PyType_IsSubtype (C 函数):             类型对象<2>.        (line   58)
* PyType_IS_GC (C 函数):                 类型对象<2>.        (line   53)
* PyType_Modified (C 函数):              类型对象<2>.        (line   42)
* PyType_Ready (C 函数):                 类型对象<2>.        (line   81)
* PyType_Slot (C 类型):                  Creating Heap-Allocated Types.
                                                             (line   59)
* PyType_Slot.PyType_Slot.pfunc (C 成员): Creating Heap-Allocated Types.
                                                             (line  109)
* PyType_Slot.PyType_Slot.slot (C 成员): Creating Heap-Allocated Types.
                                                             (line   64)
* PyType_Spec (C 类型):                  Creating Heap-Allocated Types.
                                                             (line   30)
* PyType_Spec.PyType_Spec.basicsize (C 成员): Creating Heap-Allocated Types.
                                                             (line   39)
* PyType_Spec.PyType_Spec.flags (C 成员): Creating Heap-Allocated Types.
                                                             (line   47)
* PyType_Spec.PyType_Spec.itemsize (C 成员): Creating Heap-Allocated Types.
                                                             (line   41)
* PyType_Spec.PyType_Spec.name (C 成员): Creating Heap-Allocated Types.
                                                             (line   34)
* PyType_Spec.PyType_Spec.slots (C 成员): Creating Heap-Allocated Types.
                                                             (line   54)
* PyType_Type (C 变量):                  类型对象<2>.        (line   10)
* PyTZInfo_Check (C 函数):               DateTime 对象<2>.   (line   64)
* PyTZInfo_CheckExact (C 函数):          DateTime 对象<2>.   (line   69)
* PyUnicodeDecodeError_Create (C 函数):  Unicode 异常对象.   (line    9)
* PyUnicodeDecodeError_GetEncoding (C 函数): Unicode 异常对象.
                                                             (line   45)
* PyUnicodeDecodeError_GetEnd (C 函数):  Unicode 异常对象.   (line   81)
* PyUnicodeDecodeError_GetObject (C 函数): Unicode 异常对象. (line   49)
* PyUnicodeDecodeError_GetReason (C 函数): Unicode 异常对象. (line  104)
* PyUnicodeDecodeError_GetStart (C 函数): Unicode 异常对象.  (line   54)
* PyUnicodeDecodeError_SetEnd (C 函数):  Unicode 异常对象.   (line   93)
* PyUnicodeDecodeError_SetReason (C 函数): Unicode 异常对象. (line  109)
* PyUnicodeDecodeError_SetStart (C 函数): Unicode 异常对象.  (line   68)
* PyUnicodeEncodeError_Create (C 函数):  Unicode 异常对象.   (line   18)
* PyUnicodeEncodeError_GetEncoding (C 函数): Unicode 异常对象.
                                                             (line   45)
* PyUnicodeEncodeError_GetEnd (C 函数):  Unicode 异常对象.   (line   81)
* PyUnicodeEncodeError_GetObject (C 函数): Unicode 异常对象. (line   49)
* PyUnicodeEncodeError_GetReason (C 函数): Unicode 异常对象. (line  104)
* PyUnicodeEncodeError_GetStart (C 函数): Unicode 异常对象.  (line   54)
* PyUnicodeEncodeError_SetEnd (C 函数):  Unicode 异常对象.   (line   93)
* PyUnicodeEncodeError_SetReason (C 函数): Unicode 异常对象. (line  109)
* PyUnicodeEncodeError_SetStart (C 函数): Unicode 异常对象.  (line   68)
* PyUnicodeObject (C 类型):              Unicode类型.        (line   29)
* PyUnicodeTranslateError_Create (C 函数): Unicode 异常对象. (line   31)
* PyUnicodeTranslateError_GetEnd (C 函数): Unicode 异常对象. (line   81)
* PyUnicodeTranslateError_GetObject (C 函数): Unicode 异常对象.
                                                             (line   49)
* PyUnicodeTranslateError_GetReason (C 函数): Unicode 异常对象.
                                                             (line  104)
* PyUnicodeTranslateError_GetStart (C 函数): Unicode 异常对象.
                                                             (line   54)
* PyUnicodeTranslateError_SetEnd (C 函数): Unicode 异常对象. (line   93)
* PyUnicodeTranslateError_SetReason (C 函数): Unicode 异常对象.
                                                             (line  109)
* PyUnicodeTranslateError_SetStart (C 函数): Unicode 异常对象.
                                                             (line   68)
* PyUnicode_1BYTE_DATA (C 函数):         Unicode类型.        (line   80)
* PyUnicode_1BYTE_KIND (C 宏):           Unicode类型.        (line   93)
* PyUnicode_2BYTE_DATA (C 函数):         Unicode类型.        (line   80)
* PyUnicode_2BYTE_KIND (C 宏):           Unicode类型.        (line   93)
* PyUnicode_4BYTE_DATA (C 函数):         Unicode类型.        (line   80)
* PyUnicode_4BYTE_KIND (C 宏):           Unicode类型.        (line   93)
* PyUnicode_AsASCIIString (C 函数):      ASCII Codecs.       (line   15)
* PyUnicode_AsCharmapString (C 函数):    Character Map Codecs.
                                                             (line   30)
* PyUnicode_AsEncodedString (C 函数):    Generic Codecs.     (line   17)
* PyUnicode_AsLatin1String (C 函数):     Latin-1 Codecs.     (line   16)
* PyUnicode_AsMBCSString (C 函数):       MBCS codecs for Windows.
                                                             (line   27)
* PyUnicode_AsRawUnicodeEscapeString (C 函数): Raw-Unicode-Escape Codecs.
                                                             (line   15)
* PyUnicode_AsUCS4 (C 函数):             Creating and accessing Unicode strings.
                                                             (line  242)
* PyUnicode_AsUCS4Copy (C 函数):         Creating and accessing Unicode strings.
                                                             (line  253)
* PyUnicode_AsUnicode (C 函数):          Deprecated Py_UNICODE APIs.
                                                             (line   35)
* PyUnicode_AsUnicodeAndSize (C 函数):   Deprecated Py_UNICODE APIs.
                                                             (line   64)
* PyUnicode_AsUnicodeCopy (C 函数):      Deprecated Py_UNICODE APIs.
                                                             (line   81)
* PyUnicode_AsUnicodeEscapeString (C 函数): Unicode-Escape Codecs.
                                                             (line   15)
* PyUnicode_AsUTF16String (C 函数):      UTF-16 Codecs.      (line   49)
* PyUnicode_AsUTF32String (C 函数):      UTF-32 Codecs.      (line   48)
* PyUnicode_AsUTF8 (C 函数):             UTF-8 Codecs.       (line   52)
* PyUnicode_AsUTF8AndSize (C 函数):      UTF-8 Codecs.       (line   29)
* PyUnicode_AsUTF8String (C 函数):       UTF-8 Codecs.       (line   24)
* PyUnicode_AsWideChar (C 函数):         wchar_t Support.    (line   16)
* PyUnicode_AsWideCharString (C 函数):   wchar_t Support.    (line   30)
* PyUnicode_AS_DATA (C 函数):            Unicode类型.        (line  184)
* PyUnicode_AS_UNICODE (C 函数):         Unicode类型.        (line  184)
* PyUnicode_Check (C 函数):              Unicode类型.        (line   48)
* PyUnicode_CheckExact (C 函数):         Unicode类型.        (line   53)
* PyUnicode_ClearFreeList (C 函数):      Unicode类型.        (line  160)
* PyUnicode_Compare (C 函数):            Methods and Slot Functions.
                                                             (line   86)
* PyUnicode_CompareWithASCIIString (C 函数): Methods and Slot Functions.
                                                             (line   94)
* PyUnicode_Concat (C 函数):             Methods and Slot Functions.
                                                             (line   12)
* PyUnicode_Contains (C 函数):           Methods and Slot Functions.
                                                             (line  125)
* PyUnicode_CopyCharacters (C 函数):     Creating and accessing Unicode strings.
                                                             (line  184)
* PyUnicode_Count (C 函数):              Methods and Slot Functions.
                                                             (line   73)
* PyUnicode_DATA (C 函数):               Unicode类型.        (line  114)
* PyUnicode_Decode (C 函数):             Generic Codecs.     (line    8)
* PyUnicode_DecodeASCII (C 函数):        ASCII Codecs.       (line    9)
* PyUnicode_DecodeCharmap (C 函数):      Character Map Codecs.
                                                             (line   15)
* PyUnicode_DecodeFSDefault (C 函数):    File System Encoding.
                                                             (line   66)
* PyUnicode_DecodeFSDefaultAndSize (C 函数): File System Encoding.
                                                             (line   43)
* PyUnicode_DecodeLatin1 (C 函数):       Latin-1 Codecs.     (line   10)
* PyUnicode_DecodeLocale (C 函数):       Locale Encoding.    (line   38)
* PyUnicode_DecodeLocaleAndSize (C 函数): Locale Encoding.   (line    9)
* PyUnicode_DecodeMBCS (C 函数):         MBCS codecs for Windows.
                                                             (line   12)
* PyUnicode_DecodeMBCSStateful (C 函数): MBCS codecs for Windows.
                                                             (line   18)
* PyUnicode_DecodeRawUnicodeEscape (C 函数): Raw-Unicode-Escape Codecs.
                                                             (line    8)
* PyUnicode_DecodeUnicodeEscape (C 函数): Unicode-Escape Codecs.
                                                             (line    8)
* PyUnicode_DecodeUTF16 (C 函数):        UTF-16 Codecs.      (line    8)
* PyUnicode_DecodeUTF16Stateful (C 函数): UTF-16 Codecs.     (line   36)
* PyUnicode_DecodeUTF32 (C 函数):        UTF-32 Codecs.      (line    8)
* PyUnicode_DecodeUTF32Stateful (C 函数): UTF-32 Codecs.     (line   35)
* PyUnicode_DecodeUTF7 (C 函数):         UTF-7 Codecs.       (line    8)
* PyUnicode_DecodeUTF7Stateful (C 函数): UTF-7 Codecs.       (line   14)
* PyUnicode_DecodeUTF8 (C 函数):         UTF-8 Codecs.       (line    8)
* PyUnicode_DecodeUTF8Stateful (C 函数): UTF-8 Codecs.       (line   14)
* PyUnicode_Encode (C 函数):             Generic Codecs.     (line   26)
* PyUnicode_EncodeASCII (C 函数):        ASCII Codecs.       (line   20)
* PyUnicode_EncodeCharmap (C 函数):      Character Map Codecs.
                                                             (line   44)
* PyUnicode_EncodeCodePage (C 函数):     MBCS codecs for Windows.
                                                             (line   32)
* PyUnicode_EncodeFSDefault (C 函数):    File System Encoding.
                                                             (line   80)
* PyUnicode_EncodeLatin1 (C 函数):       Latin-1 Codecs.     (line   22)
* PyUnicode_EncodeLocale (C 函数):       Locale Encoding.    (line   47)
* PyUnicode_EncodeMBCS (C 函数):         MBCS codecs for Windows.
                                                             (line   41)
* PyUnicode_EncodeRawUnicodeEscape (C 函数): Raw-Unicode-Escape Codecs.
                                                             (line   22)
* PyUnicode_EncodeUnicodeEscape (C 函数): Unicode-Escape Codecs.
                                                             (line   22)
* PyUnicode_EncodeUTF16 (C 函数):        UTF-16 Codecs.      (line   55)
* PyUnicode_EncodeUTF32 (C 函数):        UTF-32 Codecs.      (line   54)
* PyUnicode_EncodeUTF7 (C 函数):         UTF-7 Codecs.       (line   24)
* PyUnicode_EncodeUTF8 (C 函数):         UTF-8 Codecs.       (line   62)
* PyUnicode_Fill (C 函数):               Creating and accessing Unicode strings.
                                                             (line  197)
* PyUnicode_Find (C 函数):               Methods and Slot Functions.
                                                             (line   46)
* PyUnicode_FindChar (C 函数):           Methods and Slot Functions.
                                                             (line   57)
* PyUnicode_Format (C 函数):             Methods and Slot Functions.
                                                             (line  120)
* PyUnicode_FromEncodedObject (C 函数):  Creating and accessing Unicode strings.
                                                             (line  160)
* PyUnicode_FromFormat (C 函数):         Creating and accessing Unicode strings.
                                                             (line   48)
* PyUnicode_FromFormatV (C 函数):        Creating and accessing Unicode strings.
                                                             (line  153)
* PyUnicode_FromKindAndData (C 函数):    Creating and accessing Unicode strings.
                                                             (line   20)
* PyUnicode_FromObject (C 函数):         Deprecated Py_UNICODE APIs.
                                                             (line  106)
* PyUnicode_FromString (C 函数):         Creating and accessing Unicode strings.
                                                             (line   44)
* PyUnicode_FromString():                字典对象.           (line   56)
* PyUnicode_FromStringAndSize (C 函数):  Creating and accessing Unicode strings.
                                                             (line   30)
* PyUnicode_FromUnicode (C 函数):        Deprecated Py_UNICODE APIs.
                                                             (line   13)
* PyUnicode_FromWideChar (C 函数):       wchar_t Support.    (line    8)
* PyUnicode_FSConverter (C 函数):        File System Encoding.
                                                             (line   13)
* PyUnicode_FSDecoder (C 函数):          File System Encoding.
                                                             (line   30)
* PyUnicode_GetLength (C 函数):          Creating and accessing Unicode strings.
                                                             (line  178)
* PyUnicode_GetSize (C 函数):            Deprecated Py_UNICODE APIs.
                                                             (line   96)
* PyUnicode_GET_DATA_SIZE (C 函数):      Unicode类型.        (line  174)
* PyUnicode_GET_LENGTH (C 函数):         Unicode类型.        (line   72)
* PyUnicode_GET_SIZE (C 函数):           Unicode类型.        (line  164)
* PyUnicode_InternFromString (C 函数):   Methods and Slot Functions.
                                                             (line  147)
* PyUnicode_InternInPlace (C 函数):      Methods and Slot Functions.
                                                             (line  134)
* PyUnicode_Join (C 函数):               Methods and Slot Functions.
                                                             (line   32)
* PyUnicode_KIND (C 函数):               Unicode类型.        (line  105)
* PyUnicode_MAX_CHAR_VALUE (C 宏):       Unicode类型.        (line  151)
* PyUnicode_New (C 函数):                Creating and accessing Unicode strings.
                                                             (line    9)
* PyUnicode_READ (C 函数):               Unicode类型.        (line  134)
* PyUnicode_ReadChar (C 函数):           Creating and accessing Unicode strings.
                                                             (line  225)
* PyUnicode_READY (C 函数):              Unicode类型.        (line   58)
* PyUnicode_READ_CHAR (C 函数):          Unicode类型.        (line  143)
* PyUnicode_Replace (C 函数):            Methods and Slot Functions.
                                                             (line   79)
* PyUnicode_RichCompare (C 函数):        Methods and Slot Functions.
                                                             (line  106)
* PyUnicode_Split (C 函数):              Methods and Slot Functions.
                                                             (line   16)
* PyUnicode_Splitlines (C 函数):         Methods and Slot Functions.
                                                             (line   26)
* PyUnicode_Substring (C 函数):          Creating and accessing Unicode strings.
                                                             (line  234)
* PyUnicode_Tailmatch (C 函数):          Methods and Slot Functions.
                                                             (line   37)
* PyUnicode_TransformDecimalToASCII (C 函数): Deprecated Py_UNICODE APIs.
                                                             (line   52)
* PyUnicode_Translate (C 函数):          Character Map Codecs.
                                                             (line   59)
* PyUnicode_TranslateCharmap (C 函数):   Character Map Codecs.
                                                             (line   76)
* PyUnicode_Type (C 变量):               Unicode类型.        (line   40)
* PyUnicode_WCHAR_KIND (C 宏):           Unicode类型.        (line   93)
* PyUnicode_WRITE (C 函数):              Unicode类型.        (line  121)
* PyUnicode_WriteChar (C 函数):          Creating and accessing Unicode strings.
                                                             (line  211)
* PyVarObject (C 类型):                  公用对象的结构.     (line   24)
* PyVarObject.ob_size (C 成员):          PyVarObject Slots.  (line    6)
* PyVarObject_HEAD_INIT (C 宏):          公用对象的结构.     (line   82)
* PyVectorcall_Call (C 函数):            PyTypeObject Slots. (line  164)
* PyVectorcall_NARGS (C 函数):           对象协议.           (line  350)
* PyWeakref_Check (C 函数):              弱引用对象<2>.      (line    9)
* PyWeakref_CheckProxy (C 函数):         弱引用对象<2>.      (line   17)
* PyWeakref_CheckRef (C 函数):           弱引用对象<2>.      (line   13)
* PyWeakref_GetObject (C 函数):          弱引用对象<2>.      (line   41)
* PyWeakref_GET_OBJECT (C 函数):         弱引用对象<2>.      (line   49)
* PyWeakref_NewProxy (C 函数):           弱引用对象<2>.      (line   31)
* PyWeakref_NewRef (C 函数):             弱引用对象<2>.      (line   21)
* PyWideStringList (C 类型):             PyWideStringList.   (line    6)
* PyWideStringList.items (C 成员):       PyWideStringList.   (line   41)
* PyWideStringList.length (C 成员):      PyWideStringList.   (line   37)
* PyWideStringList_Append (C 函数):      PyWideStringList.   (line   15)
* PyWideStringList_Insert (C 函数):      PyWideStringList.   (line   22)
* PyWrapper_New (C 函数):                描述符对象.         (line   42)
* PyZipFile (zipfile 中的类):            PyZipFile 对象.     (line    9)
* Py_ABS (C 宏):                         有用的宏.           (line   19)
* Py_AddPendingCall (C 函数):            异步通知.           (line   10)
* Py_AddPendingCall():                   异步通知.           (line   12)
* Py_AtExit (C 函数):                    过程控制.           (line   24)
* Py_BEGIN_ALLOW_THREADS:                Releasing the GIL from extension code.
                                                             (line   21)
* Py_BEGIN_ALLOW_THREADS (C 宏):         高阶 API.           (line  157)
* Py_BLOCK_THREADS (C 宏):               高阶 API.           (line  171)
* Py_buffer (C 类型):                    缓冲区结构.         (line   19)
* Py_buffer.buf (C 成员):                缓冲区结构.         (line   21)
* Py_buffer.format (C 成员):             缓冲区结构.         (line   73)
* Py_buffer.internal (C 成员):           缓冲区结构.         (line  132)
* Py_buffer.itemsize (C 成员):           缓冲区结构.         (line   56)
* Py_buffer.len (C 成员):                缓冲区结构.         (line   40)
* Py_buffer.ndim (C 成员):               缓冲区结构.         (line   80)
* Py_buffer.obj (C 成员):                缓冲区结构.         (line   30)
* Py_buffer.readonly (C 成员):           缓冲区结构.         (line   51)
* Py_buffer.shape (C 成员):              缓冲区结构.         (line   90)
* Py_buffer.strides (C 成员):            缓冲区结构.         (line  102)
* Py_buffer.suboffsets (C 成员):         缓冲区结构.         (line  113)
* Py_BuildValue (C 函数):                创建变量.           (line    6)
* Py_BytesMain (C 函数):                 The Very High Level Layer.
                                                             (line   41)
* Py_BytesWarningFlag (C 变量):          全局配置变量.       (line   13)
* Py_CHARMASK (C 宏):                    有用的宏.           (line   49)
* Py_CLEAR (C 函数):                     引用计数<3>.        (line   39)
* py_compile (模块):                     py_compile --- 编译 Python 源文件.
                                                             (line    6)
* PY_COMPILED() (在 imp 模块中):         imp --- Access the import internals.
                                                             (line  306)
* Py_CompileString (C 函数):             The Very High Level Layer.
                                                             (line  284)
* Py_CompileString():                    The Very High Level Layer.
                                                             (line  378)
* Py_CompileString() <1>:                The Very High Level Layer.
                                                             (line  383)
* Py_CompileString() <2>:                The Very High Level Layer.
                                                             (line  390)
* Py_CompileStringExFlags (C 函数):      The Very High Level Layer.
                                                             (line  317)
* Py_CompileStringFlags (C 函数):        The Very High Level Layer.
                                                             (line  290)
* Py_CompileStringObject (C 函数):       The Very High Level Layer.
                                                             (line  297)
* Py_complex (C 类型):                   表示复数的C结构体.  (line    9)
* Py_DebugFlag (C 变量):                 全局配置变量.       (line   21)
* Py_DecodeLocale (C 函数):              操作系统实用程序.   (line  107)
* Py_DECREF (C 函数):                    引用计数<3>.        (line   18)
* Py_DECREF():                           引用计数<2>.        (line   13)
* Py_DEPRECATED (C 宏):                  有用的宏.           (line   66)
* Py_DontWriteBytecodeFlag (C 变量):     全局配置变量.       (line   29)
* Py_Ellipsis (C 变量):                  Ellipsis 对象.      (line    6)
* Py_EncodeLocale (C 函数):              操作系统实用程序.   (line  160)
* Py_EndInterpreter (C 函数):            Sub-interpreter support.
                                                             (line   76)
* Py_END_ALLOW_THREADS:                  Releasing the GIL from extension code.
                                                             (line   21)
* Py_END_ALLOW_THREADS (C 宏):           高阶 API.           (line  164)
* Py_EnterRecursiveCall (C 函数):        递归控制.           (line   11)
* Py_eval_input (C 变量):                The Very High Level Layer.
                                                             (line  376)
* Py_Exit (C 函数):                      过程控制.           (line   15)
* Py_ExitStatusException (C 函数):       PyStatus.           (line   62)
* Py_False (C 变量):                     布尔对象.           (line   13)
* Py_FatalError (C 函数):                过程控制.           (line    6)
* Py_FatalError():                       Process-wide parameters.
                                                             (line  217)
* Py_FdIsInteractive (C 函数):           操作系统实用程序.   (line   17)
* Py_file_input (C 变量):                The Very High Level Layer.
                                                             (line  381)
* Py_Finalize (C 函数):                  Initializing and finalizing the interpreter.
                                                             (line   78)
* Py_FinalizeEx (C 函数):                Initializing and finalizing the interpreter.
                                                             (line   39)
* Py_FinalizeEx():                       过程控制.           (line   17)
* Py_FinalizeEx() <1>:                   过程控制.           (line   26)
* Py_FinalizeEx() <2>:                   Initializing and finalizing the interpreter.
                                                             (line    8)
* Py_FinalizeEx() <3>:                   Sub-interpreter support.
                                                             (line   49)
* Py_FinalizeEx() <4>:                   Sub-interpreter support.
                                                             (line   78)
* PY_FROZEN() (在 imp 模块中):           imp --- Access the import internals.
                                                             (line  330)
* Py_FrozenFlag (C 变量):                全局配置变量.       (line   37)
* Py_GetBuildInfo (C 函数):              Process-wide parameters.
                                                             (line  203)
* Py_GetCompiler (C 函数):               Process-wide parameters.
                                                             (line  192)
* Py_GetCopyright (C 函数):              Process-wide parameters.
                                                             (line  181)
* Py_GETENV (C 宏):                      有用的宏.           (line   54)
* Py_GetExecPrefix (C 函数):             Process-wide parameters.
                                                             (line   71)
* Py_GetExecPrefix():                    嵌入Python<2>.      (line   42)
* Py_GetPath (C 函数):                   Process-wide parameters.
                                                             (line  118)
* Py_GetPath():                          嵌入Python<2>.      (line   42)
* Py_GetPath() <1>:                      Process-wide parameters.
                                                             (line   36)
* Py_GetPath() <2>:                      Process-wide parameters.
                                                             (line  133)
* Py_GetPlatform (C 函数):               Process-wide parameters.
                                                             (line  170)
* Py_GetPrefix (C 函数):                 Process-wide parameters.
                                                             (line   57)
* Py_GetPrefix():                        嵌入Python<2>.      (line   42)
* Py_GetProgramFullPath (C 函数):        Process-wide parameters.
                                                             (line  109)
* Py_GetProgramFullPath():               嵌入Python<2>.      (line   42)
* Py_GetProgramName (C 函数):            Process-wide parameters.
                                                             (line   51)
* Py_GetPythonHome (C 函数):             Process-wide parameters.
                                                             (line  280)
* Py_GetVersion (C 函数):                Process-wide parameters.
                                                             (line  157)
* Py_HashRandomizationFlag (C 变量):     全局配置变量.       (line   44)
* Py_IgnoreEnvironmentFlag (C 变量):     全局配置变量.       (line   52)
* Py_INCREF (C 函数):                    引用计数<3>.        (line    8)
* Py_INCREF():                           引用计数<2>.        (line   13)
* Py_Initialize (C 函数):                Initializing and finalizing the interpreter.
                                                             (line    6)
* Py_Initialize():                       嵌入Python<2>.      (line   12)
* Py_Initialize() <1>:                   Process-wide parameters.
                                                             (line    9)
* Py_Initialize() <2>:                   Process-wide parameters.
                                                             (line   36)
* Py_Initialize() <3>:                   Sub-interpreter support.
                                                             (line   49)
* Py_InitializeEx (C 函数):              Initializing and finalizing the interpreter.
                                                             (line   26)
* Py_InitializeFromConfig (C 函数):      Initialization with PyConfig.
                                                             (line    8)
* Py_InspectFlag (C 变量):               全局配置变量.       (line   59)
* Py_InteractiveFlag (C 变量):           全局配置变量.       (line   69)
* Py_IsInitialized (C 函数):             Initializing and finalizing the interpreter.
                                                             (line   32)
* Py_IsInitialized():                    嵌入Python<2>.      (line   51)
* Py_IsolatedFlag (C 变量):              全局配置变量.       (line   73)
* Py_LeaveRecursiveCall (C 函数):        递归控制.           (line   29)
* Py_LegacyWindowsFSEncodingFlag (C 变量): 全局配置变量.     (line   83)
* Py_LegacyWindowsStdioFlag (C 变量):    全局配置变量.       (line   95)
* Py_Main (C 函数):                      The Very High Level Layer.
                                                             (line   24)
* Py_MAX (C 宏):                         有用的宏.           (line   31)
* Py_MEMBER_SIZE (C 宏):                 有用的宏.           (line   43)
* Py_MIN (C 宏):                         有用的宏.           (line   25)
* Py_mod_create (C 宏):                  Multi-phase initialization.
                                                             (line   61)
* Py_mod_exec (C 宏):                    Multi-phase initialization.
                                                             (line   95)
* Py_NewInterpreter (C 函数):            Sub-interpreter support.
                                                             (line   24)
* Py_None (C 变量):                      None 对象.          (line   10)
* Py_NoSiteFlag (C 变量):                全局配置变量.       (line  107)
* Py_NotImplemented (C 变量):            对象协议.           (line    6)
* Py_NoUserSiteDirectory (C 变量):       全局配置变量.       (line  115)
* py_object (ctypes 中的类):             基础数据类型<2>.    (line  189)
* Py_OptimizeFlag (C 变量):              全局配置变量.       (line  123)
* Py_PreInitialize (C 函数):             Preinitialization with PyPreConfig.
                                                             (line    8)
* Py_PreInitializeFromArgs (C 函数):     Preinitialization with PyPreConfig.
                                                             (line   18)
* Py_PreInitializeFromBytesArgs (C 函数): Preinitialization with PyPreConfig.
                                                             (line   12)
* Py_PRINT_RAW:                          文件对象.           (line   74)
* PY_PYTHON:                             自定义默认的Python版本.
                                                             (line   13)
* Py_QuietFlag (C 变量):                 全局配置变量.       (line  128)
* Py_REFCNT (C 宏):                      公用对象的结构.     (line   60)
* Py_ReprEnter (C 函数):                 递归控制.           (line   41)
* Py_ReprLeave (C 函数):                 递归控制.           (line   59)
* Py_RETURN_FALSE (C 宏):                布尔对象.           (line   23)
* Py_RETURN_NONE (C 宏):                 None 对象.          (line   15)
* Py_RETURN_NOTIMPLEMENTED (C 宏):       对象协议.           (line   10)
* Py_RETURN_RICHCOMPARE (C 宏):          PyTypeObject Slots. (line  832)
* Py_RETURN_TRUE (C 宏):                 布尔对象.           (line   27)
* Py_RunMain (C 函数):                   Py_RunMain.         (line    6)
* Py_SetPath (C 函数):                   Process-wide parameters.
                                                             (line  131)
* Py_SetPath():                          Process-wide parameters.
                                                             (line  120)
* Py_SetProgramName (C 函数):            Process-wide parameters.
                                                             (line   34)
* Py_SetProgramName():                   嵌入Python<2>.      (line   42)
* Py_SetProgramName() <1>:               Initializing and finalizing the interpreter.
                                                             (line    8)
* Py_SetProgramName() <2>:               Process-wide parameters.
                                                             (line   53)
* Py_SetProgramName() <3>:               Process-wide parameters.
                                                             (line  111)
* Py_SetPythonHome (C 函数):             Process-wide parameters.
                                                             (line  266)
* Py_SetStandardStreamEncoding (C 函数): Process-wide parameters.
                                                             (line    6)
* Py_single_input (C 变量):              The Very High Level Layer.
                                                             (line  388)
* Py_SIZE (C 宏):                        公用对象的结构.     (line   67)
* PY_SOURCE() (在 imp 模块中):           imp --- Access the import internals.
                                                             (line  300)
* PY_SSIZE_T_MAX:                        整数型对象.         (line  167)
* Py_STRINGIFY (C 宏):                   有用的宏.           (line   37)
* Py_TPFLAGS_BASETYPE (內置变量):        PyTypeObject Slots. (line  505)
* Py_TPFLAGS_BASE_EXC_SUBCLASS (內置变量): PyTypeObject Slots.
                                                             (line  602)
* Py_TPFLAGS_BYTES_SUBCLASS (內置变量):  PyTypeObject Slots. (line  596)
* Py_TPFLAGS_DEFAULT (內置变量):         PyTypeObject Slots. (line  554)
* Py_TPFLAGS_DICT_SUBCLASS (內置变量):   PyTypeObject Slots. (line  600)
* Py_TPFLAGS_HAVE_FINALIZE (內置变量):   PyTypeObject Slots. (line  615)
* Py_TPFLAGS_HAVE_GC (內置变量):         PyTypeObject Slots. (line  533)
* Py_TPFLAGS_HEAPTYPE (內置变量):        PyTypeObject Slots. (line  490)
* Py_TPFLAGS_LIST_SUBCLASS (內置变量):   PyTypeObject Slots. (line  592)
* Py_TPFLAGS_LONG_SUBCLASS (內置变量):   PyTypeObject Slots. (line  590)
* Py_TPFLAGS_METHOD_DESCRIPTOR (內置变量): PyTypeObject Slots.
                                                             (line  566)
* Py_TPFLAGS_READY (內置变量):           PyTypeObject Slots. (line  515)
* Py_TPFLAGS_READYING (內置变量):        PyTypeObject Slots. (line  524)
* Py_TPFLAGS_TUPLE_SUBCLASS (內置变量):  PyTypeObject Slots. (line  594)
* Py_TPFLAGS_TYPE_SUBCLASS (內置变量):   PyTypeObject Slots. (line  604)
* Py_TPFLAGS_UNICODE_SUBCLASS (內置变量): PyTypeObject Slots.
                                                             (line  598)
* Py_tracefunc (C 类型):                 分析和跟踪.         (line   18)
* Py_True (C 变量):                      布尔对象.           (line   18)
* Py_tss_NEEDS_INIT (C 宏):              Thread Specific Storage TSS API.
                                                             (line   28)
* Py_tss_t (C 类型):                     Thread Specific Storage TSS API.
                                                             (line   17)
* Py_TYPE (C 宏):                        公用对象的结构.     (line   53)
* Py_UCS1 (C 类型):                      Unicode类型.        (line    9)
* Py_UCS2 (C 类型):                      Unicode类型.        (line    9)
* Py_UCS4 (C 类型):                      Unicode类型.        (line    9)
* Py_UNBLOCK_THREADS (C 宏):             高阶 API.           (line  177)
* Py_UnbufferedStdioFlag (C 变量):       全局配置变量.       (line  136)
* Py_UNICODE (C 类型):                   Unicode类型.        (line   20)
* Py_UNICODE_ISALNUM (C 函数):           Unicode字符属性.    (line   52)
* Py_UNICODE_ISALPHA (C 函数):           Unicode字符属性.    (line   47)
* Py_UNICODE_ISDECIMAL (C 函数):         Unicode字符属性.    (line   35)
* Py_UNICODE_ISDIGIT (C 函数):           Unicode字符属性.    (line   39)
* Py_UNICODE_ISLINEBREAK (C 函数):       Unicode字符属性.    (line   30)
* Py_UNICODE_ISLOWER (C 函数):           Unicode字符属性.    (line   15)
* Py_UNICODE_ISNUMERIC (C 函数):         Unicode字符属性.    (line   43)
* Py_UNICODE_ISPRINTABLE (C 函数):       Unicode字符属性.    (line   57)
* Py_UNICODE_ISSPACE (C 函数):           Unicode字符属性.    (line   10)
* Py_UNICODE_ISTITLE (C 函数):           Unicode字符属性.    (line   25)
* Py_UNICODE_ISUPPER (C 函数):           Unicode字符属性.    (line   20)
* Py_UNICODE_IS_HIGH_SURROGATE (C 宏):   Unicode字符属性.    (line  111)
* Py_UNICODE_IS_LOW_SURROGATE (C 宏):    Unicode字符属性.    (line  115)
* Py_UNICODE_IS_SURROGATE (C 宏):        Unicode字符属性.    (line  107)
* Py_UNICODE_JOIN_SURROGATES (C 宏):     Unicode字符属性.    (line  119)
* Py_UNICODE_TODECIMAL (C 函数):         Unicode字符属性.    (line   88)
* Py_UNICODE_TODIGIT (C 函数):           Unicode字符属性.    (line   94)
* Py_UNICODE_TOLOWER (C 函数):           Unicode字符属性.    (line   70)
* Py_UNICODE_TONUMERIC (C 函数):         Unicode字符属性.    (line  100)
* Py_UNICODE_TOTITLE (C 函数):           Unicode字符属性.    (line   82)
* Py_UNICODE_TOUPPER (C 函数):           Unicode字符属性.    (line   76)
* Py_UNREACHABLE (C 宏):                 有用的宏.           (line   10)
* Py_UNUSED (C 宏):                      有用的宏.           (line   59)
* Py_VaBuildValue (C 函数):              创建变量.           (line  187)
* PY_VECTORCALL_ARGUMENTS_OFFSET (C 宏): 对象协议.           (line  336)
* Py_VerboseFlag (C 变量):               全局配置变量.       (line  143)
* Py_VISIT (C 函数):                     使对象类型支持循环垃圾回收.
                                                             (line   97)
* Py_XDECREF (C 函数):                   引用计数<3>.        (line   33)
* Py_XDECREF():                          异常<18>.           (line  121)
* Py_XINCREF (C 函数):                   引用计数<3>.        (line   13)
* P_ALL() (在 os 模块中):                进程管理.           (line  623)
* P_DETACH() (在 os 模块中):             进程管理.           (line  509)
* P_NOWAIT() (在 os 模块中):             进程管理.           (line  492)
* P_NOWAITO() (在 os 模块中):            进程管理.           (line  492)
* P_OVERLAY() (在 os 模块中):            进程管理.           (line  509)
* P_PGID() (在 os 模块中):               进程管理.           (line  623)
* P_PID() (在 os 模块中):                进程管理.           (line  623)
* P_WAIT() (在 os 模块中):               进程管理.           (line  501)
* qiflush() (在 curses 模块中):          函数<3>.            (line  315)
* QName (xml.etree.ElementTree 中的类):  QName 对象.         (line    6)
* qsize() (asyncio.Queue 方法):          Queue.              (line   67)
* qsize() (multiprocessing.Queue 方法):  管道和队列.         (line   83)
* qsize() (queue.Queue 方法):            Queue对象.          (line    9)
* qsize() (queue.SimpleQueue 方法):      SimpleQueue 对象.   (line    8)
* qualified name – 限定名称:             术语对照表.         (line  898)
* quantiles() (statistics.NormalDist 方法): NormalDist 对象. (line   85)
* quantiles() (在 statistics 模块中):    函数细节.           (line  347)
* quantize() (decimal.Context 方法):     上下文对象.         (line  405)
* quantize() (decimal.Decimal 方法):     Decimal 对象.       (line  396)
* QueryInfoKey() (在 winreg 模块中):     函数<11>.           (line  302)
* QueryReflectionKey() (在 winreg 模块中): 函数<11>.         (line  499)
* QueryValue() (在 winreg 模块中):       函数<11>.           (line  331)
* QueryValueEx() (在 winreg 模块中):     函数<11>.           (line  351)
* Queue (asyncio 中的类):                Queue.              (line    6)
* Queue (multiprocessing 中的类):        管道和队列.         (line   71)
* Queue (queue 中的类):                  queue --- 一个同步的队列类.
                                                             (line   27)
* queue (sched.scheduler 属性):          调度器对象.         (line   63)
* queue (模块):                          queue --- 一个同步的队列类.
                                                             (line    6)
* Queue() (multiprocessing.managers.SyncManager 方法): 管理器.
                                                             (line  157)
* QueueEmpty:                            异常<8>.            (line    6)
* QueueFull:                             异常<8>.            (line   11)
* QueueHandler (logging.handlers 中的类): QueueHandler.      (line   18)
* QueueListener (logging.handlers 中的类): QueueListener.    (line   21)
* quick_ratio() (difflib.SequenceMatcher 方法): SequenceMatcher 对象.
                                                             (line  174)
* quit (pdb command):                    调试器命令.         (line  275)
* quit (內置变量):                       由 site 模块添加的常量.
                                                             (line   10)
* quit() (ftplib.FTP 方法):              FTP 对象.           (line  204)
* quit() (nntplib.NNTP 方法):            方法<3>.            (line   22)
* quit() (poplib.POP3 方法):             POP3 对象.          (line   75)
* quit() (smtplib.SMTP 方法):            SMTP Objects.       (line  325)
* quopri (模块):                         quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line    6)
* quote() (在 email.utils 模块中):       email utils 其他工具.
                                                             (line   37)
* quote() (在 shlex 模块中):             shlex --- Simple lexical analysis.
                                                             (line   44)
* quote() (在 urllib.parse 模块中):      URL Quoting.        (line   13)
* quoteattr() (在 xml.sax.saxutils 模块中): xml sax saxutils --- SAX 工具集.
                                                             (line   30)
* quotechar (csv.Dialect 属性):          变种与格式参数.     (line   43)
* quoted-printable; encoding:            quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line    8)
* quotes (shlex.shlex 属性):             shlex Objects.      (line  115)
* QUOTE_ALL() (在 csv 模块中):           模块内容<3>.        (line  203)
* quote_from_bytes() (在 urllib.parse 模块中): URL Quoting.  (line   52)
* QUOTE_MINIMAL() (在 csv 模块中):       模块内容<3>.        (line  207)
* QUOTE_NONE() (在 csv 模块中):          模块内容<3>.        (line  218)
* QUOTE_NONNUMERIC() (在 csv 模块中):    模块内容<3>.        (line  212)
* quote_plus() (在 urllib.parse 模块中): URL Quoting.        (line   41)
* quoting (csv.Dialect 属性):            变种与格式参数.     (line   48)
* r"; raw string literal:                字符串和字节串字面值.
                                                             (line   43)
* r’; raw string literal:                字符串和字节串字面值.
                                                             (line   43)
* radians() (在 math 模块中):            角度转换.           (line   10)
* radians() (在 turtle 模块中):          度量单位设置.       (line   27)
* RadioButtonGroup (msilib 中的类):      GUI classes.        (line   29)
* radiogroup() (msilib.Dialog 方法):     GUI classes.        (line   73)
* radix() (decimal.Context 方法):        上下文对象.         (line  409)
* radix() (decimal.Decimal 方法):        Decimal 对象.       (line  416)
* RADIXCHAR() (在 locale 模块中):        locale --- 国际化服务.
                                                             (line  214)
* raise (2to3 fixer):                    修复器.             (line  249)
* raise an exception:                    异常<2>.            (line    6)
* raise_on_defect (email.policy.Policy 属性): email policy 策略对象.
                                                             (line  144)
* raise_signal() (在 signal 模块中):     模块内容<5>.        (line  255)
* RAISE_VARARGS (opcode):                Python字节码说明.   (line  690)
* raising; exception:                    raise 语句.         (line    6)
* randbelow() (在 secrets 模块中):       随机数.             (line   18)
* randbits() (在 secrets 模块中):        随机数.             (line   22)
* randint() (在 random 模块中):          整数用函数.         (line   22)
* Random (random 中的类):                替代生成器.         (line    6)
* random (模块):                         random --- 生成伪随机数.
                                                             (line    6)
* random() (在 random 模块中):           实值分布.           (line    9)
* randrange() (在 random 模块中):        整数用函数.         (line    6)
* RAND_add() (在 ssl 模块中):            随机生成.           (line   56)
* RAND_bytes() (在 ssl 模块中):          随机生成.           (line    6)
* RAND_egd() (在 ssl 模块中):            随机生成.           (line   44)
* RAND_pseudo_bytes() (在 ssl 模块中):   随机生成.           (line   21)
* RAND_status() (在 ssl 模块中):         随机生成.           (line   38)
* range (內置类):                        range 对象.         (line    9)
* RARROW() (在 token 模块中):            token --- 与Python解析树一起使用的常量.
                                                             (line  226)
* ratecv() (在 audioop 模块中):          audioop --- 处理原始音频数据.
                                                             (line  153)
* ratio() (difflib.SequenceMatcher 方法): SequenceMatcher 对象.
                                                             (line  153)
* Rational (numbers 中的类):             数字的层次.         (line   39)
* raw (io.BufferedIOBase 属性):          I/O 基类.           (line  211)
* raw string:                            字符串和字节串字面值.
                                                             (line   34)
* raw() (pickle.PickleBuffer 方法):      模块接口.           (line  277)
* raw() (在 curses 模块中):              函数<3>.            (line  321)
* RawArray() (在 multiprocessing.sharedctypes 模块中): multiprocessing sharedctypes 模块.
                                                             (line   13)
* RawConfigParser (configparser 中的类): RawConfigParser 对象.
                                                             (line    6)
* RawDescriptionHelpFormatter (argparse 中的类): formatter_class.
                                                             (line    9)
* RawIOBase (io 中的类):                 I/O 基类.           (line  142)
* RawPen (turtle 中的类):                公共类.             (line    6)
* RawTextHelpFormatter (argparse 中的类): formatter_class.   (line    9)
* RawTurtle (turtle 中的类):             公共类.             (line    6)
* RawValue() (在 multiprocessing.sharedctypes 模块中): multiprocessing sharedctypes 模块.
                                                             (line   28)
* raw_data_manager() (在 email.contentmanager 模块中): 内容管理器实例.
                                                             (line   10)
* raw_decode() (json.JSONDecoder 方法):  编码器和解码器.     (line   85)
* raw_input (2to3 fixer):                修复器.             (line  255)
* raw_input() (code.InteractiveConsole 方法): 交互式控制台对象.
                                                             (line   37)
* RBRACE() (在 token 模块中):            token --- 与Python解析树一起使用的常量.
                                                             (line  126)
* rcpttos (smtpd.SMTPChannel 属性):      SMTPChannel 对象.   (line   78)
* re (re.Match 属性):                    匹配对象.           (line  162)
* re (模块):                             re --- 正则表达式操作.
                                                             (line    6)
* read() (asyncio.StreamReader 方法):    StreamReader.       (line   14)
* read() (chunk.Chunk 方法):             chunk --- 读取 IFF 分块数据.
                                                             (line   90)
* read() (codecs.StreamReader 方法):     StreamReader 对象.  (line   30)
* read() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line   97)
* read() (http.client.HTTPResponse 方法): HTTPResponse 对象. (line   13)
* read() (imaplib.IMAP4 方法):           IMAP4 Objects.      (line  192)
* read() (io.BufferedIOBase 方法):       I/O 基类.           (line  228)
* read() (io.BufferedReader 方法):       缓冲流.             (line   70)
* read() (io.RawIOBase 方法):            I/O 基类.           (line  154)
* read() (io.TextIOBase 方法):           文本 I/O<2>.        (line   47)
* read() (mimetypes.MimeTypes 方法):     MimeTypes 对象.     (line   58)
* read() (mmap.mmap 方法):               mmap --- 内存映射文件支持.
                                                             (line  193)
* read() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line   32)
* read() (ssl.MemoryBIO 方法):           内存 BIO 支持<2>.   (line  130)
* read() (ssl.SSLSocket 方法):           SSL 套接字.         (line   66)
* read() (urllib.robotparser.RobotFileParser 方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   24)
* read() (zipfile.ZipFile 方法):         ZipFile 对象.       (line  188)
* read() (在 os 模块中):                 文件描述符操作.     (line  498)
* read1() (io.BufferedIOBase 方法):      I/O 基类.           (line  241)
* read1() (io.BufferedReader 方法):      缓冲流.             (line   75)
* read1() (io.BytesIO 方法):             缓冲流.             (line   39)
* readable() (asyncore.dispatcher 方法): asyncore --- 异步socket处理器.
                                                             (line  134)
* readable() (io.IOBase 方法):           I/O 基类.           (line   64)
* READABLE() (在 tkinter 模块中):        File Handlers.      (line   41)
* readall() (io.RawIOBase 方法):         I/O 基类.           (line  167)
* reader() (在 csv 模块中):              模块内容<3>.        (line    8)
* ReadError:                             tarfile --- 读写tar归档文件.
                                                             (line  165)
* readexactly() (asyncio.StreamReader 方法): StreamReader.   (line   29)
* readfp() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line  260)
* readfp() (mimetypes.MimeTypes 方法):   MimeTypes 对象.     (line   66)
* readframes() (aifc.aifc 方法):         aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   84)
* readframes() (sunau.AU_read 方法):     AU_read 对象.       (line   47)
* readframes() (wave.Wave_read 方法):    Wave_read对象.      (line   44)
* readinto() (http.client.HTTPResponse 方法): HTTPResponse 对象.
                                                             (line   17)
* readinto() (io.BufferedIOBase 方法):   I/O 基类.           (line  251)
* readinto() (io.RawIOBase 方法):        I/O 基类.           (line  171)
* readinto1() (io.BufferedIOBase 方法):  I/O 基类.           (line  263)
* readinto1() (io.BytesIO 方法):         缓冲流.             (line   45)
* readline (模块):                       readline --- GNU readline 接口.
                                                             (line    6)
* readline() (asyncio.StreamReader 方法): StreamReader.      (line   21)
* readline() (codecs.StreamReader 方法): StreamReader 对象.  (line   49)
* readline() (distutils.text_file.TextFile 方法): distutils text_file --- The TextFile class.
                                                             (line  111)
* readline() (imaplib.IMAP4 方法):       IMAP4 Objects.      (line  197)
* readline() (io.IOBase 方法):           I/O 基类.           (line   69)
* readline() (io.TextIOBase 方法):       文本 I/O<2>.        (line   52)
* readline() (mmap.mmap 方法):           mmap --- 内存映射文件支持.
                                                             (line  206)
* readlines() (codecs.StreamReader 方法): StreamReader 对象. (line   58)
* readlines() (distutils.text_file.TextFile 方法): distutils text_file --- The TextFile class.
                                                             (line  124)
* readlines() (io.IOBase 方法):          I/O 基类.           (line   78)
* readlink() (在 os 模块中):             文件和目录.         (line  516)
* readmodule() (在 pyclbr 模块中):       pyclbr --- Python 模块浏览器支持.
                                                             (line   16)
* readmodule_ex() (在 pyclbr 模块中):    pyclbr --- Python 模块浏览器支持.
                                                             (line   25)
* READONLY:                              泛型属性管理.       (line   87)
* readonly (memoryview 属性):            内存视图.           (line  384)
* readPlist() (在 plistlib 模块中):      plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line  112)
* readPlistFromBytes() (在 plistlib 模块中): plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line  132)
* ReadTransport (asyncio 中的类):        传输层级.           (line   19)
* readuntil() (asyncio.StreamReader 方法): StreamReader.     (line   38)
* readv() (在 os 模块中):                文件描述符操作.     (line  569)
* ready() (multiprocessing.pool.AsyncResult 方法): 进程池.   (line  173)
* read_all() (telnetlib.Telnet 方法):    Telnet 对象.        (line   15)
* read_binary() (在 importlib.resources 模块中): importlib resources -- 资源.
                                                             (line   76)
* read_byte() (mmap.mmap 方法):          mmap --- 内存映射文件支持.
                                                             (line  202)
* read_bytes() (pathlib.Path 方法):      方法<2>.            (line  240)
* read_bytes() (zipfile.Path 方法):      Path 对象.          (line   53)
* read_dict() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line  150)
* read_eager() (telnetlib.Telnet 方法):  Telnet 对象.        (line   32)
* read_environ() (在 wsgiref.handlers 模块中): wsgiref handlers -- server/gateway base classes.
                                                             (line  305)
* read_events() (xml.etree.ElementTree.XMLPullParser 方法): XMLPullParser对象.
                                                             (line   26)
* read_file() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line  130)
* read_history_file() (在 readline 模块中): 历史文件.        (line    8)
* read_init_file() (在 readline 模块中): 初始化文件.         (line   13)
* read_lazy() (telnetlib.Telnet 方法):   Telnet 对象.        (line   40)
* read_mime_types() (在 mimetypes 模块中): mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line   82)
* READ_RESTRICTED:                       泛型属性管理.       (line   87)
* read_sb_data() (telnetlib.Telnet 方法): Telnet 对象.       (line   55)
* read_some() (telnetlib.Telnet 方法):   Telnet 对象.        (line   19)
* read_string() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line  140)
* read_text() (pathlib.Path 方法):       方法<2>.            (line  252)
* read_text() (zipfile.Path 方法):       Path 对象.          (line   48)
* read_text() (在 importlib.resources 模块中): importlib resources -- 资源.
                                                             (line   87)
* read_token() (shlex.shlex 方法):       shlex Objects.      (line   20)
* read_until() (telnetlib.Telnet 方法):  Telnet 对象.        (line    8)
* read_very_eager() (telnetlib.Telnet 方法): Telnet 对象.    (line   24)
* read_very_lazy() (telnetlib.Telnet 方法): Telnet 对象.     (line   48)
* read_windows_registry() (mimetypes.MimeTypes 方法): MimeTypes 对象.
                                                             (line   74)
* Real (numbers 中的类):                 数字的层次.         (line   26)
* real (numbers.Complex 属性):           数字的层次.         (line   14)
* Real Media File Format:                chunk --- 读取 IFF 分块数据.
                                                             (line    8)
* realloc():                             概述<16>.           (line   23)
* realpath() (在 os.path 模块中):        os path --- 常用路径操作.
                                                             (line  256)
* REALTIME_PRIORITY_CLASS() (在 subprocess 模块中): Windows 常数.
                                                             (line   80)
* real_max_memuse() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  127)
* real_quick_ratio() (difflib.SequenceMatcher 方法): SequenceMatcher 对象.
                                                             (line  178)
* reap_children() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  791)
* reap_threads() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  654)
* reason (http.client.HTTPResponse 属性): HTTPResponse 对象. (line   55)
* reason (ssl.SSLError 属性):            异常<12>.           (line   24)
* reason (UnicodeError 属性):            具体异常.           (line  307)
* reason (urllib.error.HTTPError 属性):  urllib error --- urllib request 引发的异常类.
                                                             (line   40)
* reason (urllib.error.URLError 属性):   urllib error --- urllib request 引发的异常类.
                                                             (line   20)
* reattach() (tkinter.ttk.Treeview 方法): ttk Treeview.      (line  246)
* rebinding; name:                       赋值语句.           (line    6)
* reccontrols() (ossaudiodev.oss_mixer_device 方法): Mixer Device Objects.
                                                             (line   54)
* received_data (smtpd.SMTPChannel 属性): SMTPChannel 对象.  (line   83)
* received_lines (smtpd.SMTPChannel 属性): SMTPChannel 对象. (line   56)
* recent() (imaplib.IMAP4 方法):         IMAP4 Objects.      (line  202)
* reconfigure() (io.TextIOWrapper 方法): 文本 I/O<2>.        (line  149)
* records (unittest.TestCase 属性):      测试用例.           (line  426)
* record_original_stdout() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  375)
* rect() (在 cmath 模块中):              到极坐标和从极坐标的转换.
                                                             (line   40)
* rectangle() (在 curses.textpad 模块中): curses textpad --- 用于 curses 程序的文本输入控件.
                                                             (line   13)
* RecursionError:                        具体异常.           (line  158)
* recursive_repr() (在 reprlib 模块中):  reprlib --- 另一种 repr 实现.
                                                             (line   34)
* recv() (asyncore.dispatcher 方法):     asyncore --- 异步socket处理器.
                                                             (line  166)
* recv() (multiprocessing.connection.Connection 方法): 连接对象（Connection）<2>.
                                                             (line   22)
* recv() (socket.socket 方法):           套接字对象.         (line  187)
* recvfrom() (socket.socket 方法):       套接字对象.         (line  200)
* recvfrom_into() (socket.socket 方法):  套接字对象.         (line  304)
* recvmsg() (socket.socket 方法):        套接字对象.         (line  215)
* recvmsg_into() (socket.socket 方法):   套接字对象.         (line  271)
* recv_bytes() (multiprocessing.connection.Connection 方法): 连接对象（Connection）<2>.
                                                             (line   59)
* recv_bytes_into() (multiprocessing.connection.Connection 方法): 连接对象（Connection）<2>.
                                                             (line   71)
* recv_into() (socket.socket 方法):      套接字对象.         (line  312)
* redirect_request() (urllib.request.HTTPRedirectHandler 方法): HTTPRedirectHandler 对象.
                                                             (line   13)
* redirect_stderr() (在 contextlib 模块中): 工具.            (line  232)
* redirect_stdout() (在 contextlib 模块中): 工具.            (line  196)
* redisplay() (在 readline 模块中):      行缓冲区.           (line   17)
* redrawln() (curses.window 方法):       Window 对象.        (line  394)
* redrawwin() (curses.window 方法):      Window 对象.        (line  399)
* reduce (2to3 fixer):                   修复器.             (line  259)
* reduce() (在 functools 模块中):        functools --- 高阶函数和可调用对象上的操作.
                                                             (line  256)
* reducer_override() (pickle.Pickler 方法): 模块接口.        (line  178)
* ref (weakref 中的类):                  weakref --- 弱引用. (line   65)
* refcount_test() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  647)
* reference count – 引用计数:            术语对照表.         (line  923)
* reference counting:                    对象、值与类型.     (line   29)
* ReferenceError:                        具体异常.           (line  165)
* ReferenceType() (在 weakref 模块中):   weakref --- 弱引用. (line  231)
* refold_source (email.policy.EmailPolicy 属性): email policy 策略对象.
                                                             (line  298)
* refresh() (curses.window 方法):        Window 对象.        (line  403)
* register() (abc.ABCMeta 方法):         abc --- 抽象基类.   (line   58)
* register() (multiprocessing.managers.BaseManager 方法): 管理器.
                                                             (line   66)
* register() (select.devpoll 方法):      /dev/poll 轮询对象. (line   30)
* register() (select.epoll 方法):        边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   79)
* register() (select.poll 方法):         Poll 对象.          (line   12)
* register() (selectors.BaseSelector 方法): 类<3>.           (line   61)
* register() (在 atexit 模块中):         atexit --- 退出处理器.
                                                             (line   19)
* register() (在 codecs 模块中):         codecs --- 编解码器注册和相关基类.
                                                             (line  128)
* register() (在 faulthandler 模块中):   Dumping the traceback on a user signal.
                                                             (line    6)
* register() (在 webbrowser 模块中):     webbrowser --- 方便的Web浏览器控制器.
                                                             (line   69)
* registerDOMImplementation() (在 xml.dom 模块中): 模块内容<6>.
                                                             (line    8)
* registerResult() (在 unittest 模块中): 信号处理.           (line   35)
* register_adapter() (在 sqlite3 模块中): 模块函数和常量.    (line  114)
* register_archive_format() (在 shutil 模块中): 归档操作.    (line   77)
* register_at_fork() (在 os 模块中):     进程管理.           (line  396)
* register_converter() (在 sqlite3 模块中): 模块函数和常量.  (line  106)
* register_defect() (email.policy.Policy 方法): email policy 策略对象.
                                                             (line  186)
* register_dialect() (在 csv 模块中):    模块内容<3>.        (line   58)
* register_error() (在 codecs 模块中):   错误处理方案.       (line   75)
* register_function() (xmlrpc.server.CGIXMLRPCRequestHandler 方法): CGIXMLRPCRequestHandler.
                                                             (line    9)
* register_function() (xmlrpc.server.SimpleXMLRPCServer 方法): SimpleXMLRPCServer Objects.
                                                             (line   10)
* register_instance() (xmlrpc.server.CGIXMLRPCRequestHandler 方法): CGIXMLRPCRequestHandler.
                                                             (line   26)
* register_instance() (xmlrpc.server.SimpleXMLRPCServer 方法): SimpleXMLRPCServer Objects.
                                                             (line   27)
* register_introspection_functions() (xmlrpc.server.CGIXMLRPCRequestHandler 方法): CGIXMLRPCRequestHandler.
                                                             (line   41)
* register_introspection_functions() (xmlrpc.server.SimpleXMLRPCServer 方法): SimpleXMLRPCServer Objects.
                                                             (line   55)
* register_multicall_functions() (xmlrpc.server.CGIXMLRPCRequestHandler 方法): CGIXMLRPCRequestHandler.
                                                             (line   46)
* register_multicall_functions() (xmlrpc.server.SimpleXMLRPCServer 方法): SimpleXMLRPCServer Objects.
                                                             (line   60)
* register_namespace() (在 xml.etree.ElementTree 模块中): 函数<6>.
                                                             (line  156)
* register_optionflag() (在 doctest 模块中): Option Flags.   (line  172)
* register_shape() (在 turtle 模块中):   设置与特殊方法.     (line   68)
* register_unpack_format() (在 shutil 模块中): 归档操作.     (line  117)
* regular package – 常规包:              术语对照表.         (line  930)
* REG_BINARY() (在 winreg 模块中):       Value Types.        (line    8)
* REG_DWORD() (在 winreg 模块中):        Value Types.        (line   12)
* REG_DWORD_BIG_ENDIAN() (在 winreg 模块中): Value Types.    (line   21)
* REG_DWORD_LITTLE_ENDIAN() (在 winreg 模块中): Value Types. (line   16)
* REG_EXPAND_SZ() (在 winreg 模块中):    Value Types.        (line   25)
* REG_FULL_RESOURCE_DESCRIPTOR() (在 winreg 模块中): Value Types.
                                                             (line   60)
* REG_LINK() (在 winreg 模块中):         Value Types.        (line   30)
* REG_MULTI_SZ() (在 winreg 模块中):     Value Types.        (line   34)
* REG_NONE() (在 winreg 模块中):         Value Types.        (line   39)
* REG_QWORD() (在 winreg 模块中):        Value Types.        (line   43)
* REG_QWORD_LITTLE_ENDIAN() (在 winreg 模块中): Value Types. (line   49)
* REG_RESOURCE_LIST() (在 winreg 模块中): Value Types.       (line   56)
* REG_RESOURCE_REQUIREMENTS_LIST() (在 winreg 模块中): Value Types.
                                                             (line   64)
* REG_SZ() (在 winreg 模块中):           Value Types.        (line   68)
* relative; import:                      import 语句.        (line   82)
* relative; URL:                         urllib parse 用于解析 URL.
                                                             (line    8)
* relative_to() (pathlib.PurePath 方法): 方法和特征属性.     (line  236)
* release() (asyncio.Condition 方法):    Condition.          (line   71)
* release() (asyncio.Lock 方法):         Lock.               (line   46)
* release() (asyncio.Semaphore 方法):    Semaphore.          (line   52)
* release() (logging.Handler 方法):      处理器对象.         (line   27)
* release() (memoryview 方法):           内存视图.           (line  215)
* release() (multiprocessing.Lock 方法): 同步原语.           (line   76)
* release() (multiprocessing.RLock 方法): 同步原语.          (line  117)
* release() (pickle.PickleBuffer 方法):  模块接口.           (line  284)
* release() (threading.Condition 方法):  条件对象.           (line   76)
* release() (threading.Lock 方法):       锁对象.             (line   58)
* release() (threading.RLock 方法):      递归锁对象.         (line   50)
* release() (threading.Semaphore 方法):  信号量对象.         (line   55)
* release() (_thread.lock 方法):         _thread --- 底层多线程 API.
                                                             (line  122)
* release() (在 platform 模块中):        跨平台.             (line  102)
* releasebufferproc (C 类型):            Slot Type typedefs. (line  107)
* release_lock() (在 imp 模块中):        imp --- Access the import internals.
                                                             (line  286)
* reload (2to3 fixer):                   修复器.             (line  263)
* reload() (在 imp 模块中):              imp --- Access the import internals.
                                                             (line  132)
* reload() (在 importlib 模块中):        函数<10>.           (line   64)
* relpath() (在 os.path 模块中):         os path --- 常用路径操作.
                                                             (line  269)
* remainder() (decimal.Context 方法):    上下文对象.         (line  413)
* remainder() (在 math 模块中):          数论与表示函数.     (line  173)
* remainder_near() (decimal.Context 方法): 上下文对象.       (line  419)
* remainder_near() (decimal.Decimal 方法): Decimal 对象.     (line  421)
* RemoteDisconnected:                    http client --- HTTP 协议客户端.
                                                             (line  169)
* remove() (array.array 方法):           array --- 高效的数值数组.
                                                             (line  184)
* remove() (collections.deque 方法):     deque 对象.         (line   87)
* remove() (frozenset 方法):             集合类型 --- set frozenset.
                                                             (line  179)
* remove() (mailbox.Mailbox 方法):       Mailbox 对象.       (line   58)
* remove() (mailbox.MH 方法):            MH.                 (line   68)
* remove() (sequence method):            可变序列类型.       (line   14)
* remove() (xml.etree.ElementTree.Element 方法): 元素对象.   (line  154)
* remove() (在 os 模块中):               文件和目录.         (line  547)
* removeAttribute() (xml.dom.Element 方法): 元素对象<2>.     (line   48)
* removeAttributeNode() (xml.dom.Element 方法): 元素对象<2>. (line   53)
* removeAttributeNS() (xml.dom.Element 方法): 元素对象<2>.   (line   58)
* removeChild() (xml.dom.Node 方法):     节点对象.           (line  111)
* removedirs() (在 os 模块中):           文件和目录.         (line  568)
* removeFilter() (logging.Handler 方法): 处理器对象.         (line   50)
* removeFilter() (logging.Logger 方法):  记录器对象.         (line  204)
* removeHandler() (logging.Logger 方法): 记录器对象.         (line  219)
* removeHandler() (在 unittest 模块中):  信号处理.           (line   52)
* removeResult() (在 unittest 模块中):   信号处理.           (line   46)
* removexattr() (在 os 模块中):          Linux 扩展属性.     (line   38)
* remove_child_handler() (asyncio.AbstractChildWatcher 方法): 进程监视器.
                                                             (line   44)
* remove_done_callback() (asyncio.Future 方法): Future 对象<2>.
                                                             (line   92)
* remove_done_callback() (asyncio.Task 方法): Task 对象.     (line  143)
* remove_flag() (mailbox.MaildirMessage 方法): MaildirMessage.
                                                             (line   76)
* remove_flag() (mailbox.mboxMessage 方法): mboxMessage.     (line   73)
* remove_flag() (mailbox.MMDFMessage 方法): MMDFMessage.     (line   72)
* remove_folder() (mailbox.Maildir 方法): Maildir.           (line   64)
* remove_folder() (mailbox.MH 方法):     MH.                 (line   42)
* remove_header() (urllib.request.Request 方法): Request 对象.
                                                             (line   86)
* remove_history_item() (在 readline 模块中): 历史列表.      (line   23)
* remove_label() (mailbox.BabylMessage 方法): BabylMessage.  (line   56)
* remove_option() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line  232)
* remove_option() (optparse.OptionParser 方法): Querying and manipulating your option parser.
                                                             (line   47)
* remove_pyc() (msilib.Directory 方法):  Directory Objects.  (line   45)
* remove_reader() (asyncio.loop 方法):   监控文件描述符.     (line   11)
* remove_section() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line  238)
* remove_sequence() (mailbox.MHMessage 方法): MHMessage.     (line   42)
* remove_signal_handler() (asyncio.loop 方法): Unix 信号.    (line   23)
* remove_tree() (在 distutils.dir_util 模块中): distutils dir_util --- Directory tree operations.
                                                             (line   60)
* remove_writer() (asyncio.loop 方法):   监控文件描述符.     (line   23)
* rename() (ftplib.FTP 方法):            FTP 对象.           (line  172)
* rename() (imaplib.IMAP4 方法):         IMAP4 Objects.      (line  207)
* rename() (pathlib.Path 方法):          方法<2>.            (line  266)
* rename() (在 os 模块中):               文件和目录.         (line  583)
* renames (2to3 fixer):                  修复器.             (line  267)
* renames() (在 os 模块中):              文件和目录.         (line  611)
* reopenIfNeeded() (logging.handlers.WatchedFileHandler 方法): WatchedFileHandler.
                                                             (line   33)
* reorganize() (dbm.gnu.gdbm 方法):      dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line   87)
* repeat() (timeit.Timer 方法):          Python 接口.        (line   87)
* repeat() (在 itertools 模块中):        Itertool函数.       (line  443)
* repeat() (在 timeit 模块中):           Python 接口.        (line   17)
* repetition; operation:                 通用序列操作.       (line   17)
* replace() (bytearray 方法):            bytes 和 bytearray 操作.
                                                             (line  125)
* replace() (bytes 方法):                bytes 和 bytearray 操作.
                                                             (line  125)
* replace() (curses.panel.Panel 方法):   Panel 对象.         (line   36)
* replace() (datetime.date 方法):        date 对象.          (line  153)
* replace() (datetime.datetime 方法):    datetime 对象.      (line  375)
* replace() (datetime.time 方法):        time 对象.          (line  124)
* replace() (inspect.Parameter 方法):    Introspecting callables with the Signature object.
                                                             (line  251)
* replace() (inspect.Signature 方法):    Introspecting callables with the Signature object.
                                                             (line  110)
* replace() (pathlib.Path 方法):         方法<2>.            (line  287)
* replace() (str 方法):                  字符串的方法<2>.    (line  288)
* replace() (types.CodeType 方法):       标准解释器类型.     (line   55)
* replace() (在 dataclasses 模块中):     模块级装饰器、类和函数.
                                                             (line  286)
* replace() (在 os 模块中):              文件和目录.         (line  625)
* replaceChild() (xml.dom.Node 方法):    节点对象.           (line  117)
* ReplacePackage() (在 modulefinder 模块中): modulefinder --- 查找脚本使用的模块.
                                                             (line   18)
* replace_errors() (在 codecs 模块中):   错误处理方案.       (line  110)
* replace_header() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  246)
* replace_header() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  341)
* replace_history_item() (在 readline 模块中): 历史列表.     (line   28)
* replace_whitespace (textwrap.TextWrapper 属性): textwrap --- 文本自动换行与填充.
                                                             (line  155)
* report() (filecmp.dircmp 方法):        dircmp 类.          (line   17)
* report() (modulefinder.ModuleFinder 方法): modulefinder --- 查找脚本使用的模块.
                                                             (line   32)
* REPORTING_FLAGS() (在 doctest 模块中): Option Flags.       (line  164)
* REPORT_CDIFF() (在 doctest 模块中):    Option Flags.       (line  126)
* report_failure() (doctest.DocTestRunner 方法): DocTestRunner 对象.
                                                             (line   70)
* report_full_closure() (filecmp.dircmp 方法): dircmp 类.    (line   26)
* REPORT_NDIFF() (在 doctest 模块中):    Option Flags.       (line  131)
* REPORT_ONLY_FIRST_FAILURE() (在 doctest 模块中): Option Flags.
                                                             (line  140)
* report_partial_closure() (filecmp.dircmp 方法): dircmp 类. (line   22)
* report_start() (doctest.DocTestRunner 方法): DocTestRunner 对象.
                                                             (line   48)
* report_success() (doctest.DocTestRunner 方法): DocTestRunner 对象.
                                                             (line   59)
* REPORT_UDIFF() (在 doctest 模块中):    Option Flags.       (line  121)
* report_unexpected_exception() (doctest.DocTestRunner 方法): DocTestRunner 对象.
                                                             (line   81)
* repr (2to3 fixer):                     修复器.             (line  271)
* Repr (reprlib 中的类):                 reprlib --- 另一种 repr 实现.
                                                             (line   15)
* repr() (built-in function); __repr__() (object method): 基本定制.
                                                             (line   92)
* repr() (reprlib.Repr 方法):            Repr 对象.          (line   40)
* repr() (內置函数):                     内置函数.           (line 1200)
* repr() (在 reprlib 模块中):            reprlib --- 另一种 repr 实现.
                                                             (line   26)
* repr1() (reprlib.Repr 方法):           Repr 对象.          (line   44)
* reprfunc (C 类型):                     Slot Type typedefs. (line   49)
* reprlib (模块):                        reprlib --- 另一种 repr 实现.
                                                             (line    6)
* Request (urllib.request 中的类):       urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  155)
* request() (http.client.HTTPConnection 方法): HTTPConnection 对象.
                                                             (line    8)
* RequestHandlerClass (socketserver.BaseServer 属性): Server 对象<2>.
                                                             (line   71)
* requestline (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line   70)
* request_queue_size (socketserver.BaseServer 属性): Server 对象<2>.
                                                             (line   98)
* request_rate() (urllib.robotparser.RobotFileParser 方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   54)
* request_uri() (在 wsgiref.util 模块中): wsgiref util -- WSGI environment utilities.
                                                             (line   25)
* request_version (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line   87)
* requires() (在 test.support 模块中):   test support --- Utilities for the Python test suite.
                                                             (line  211)
* requires_bz2() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  616)
* requires_docstrings() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  628)
* requires_freebsd_version() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  586)
* requires_gzip() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  612)
* requires_IEEE_754() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  604)
* requires_linux_version() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  592)
* requires_lzma() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  620)
* requires_mac_version() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  598)
* requires_resource() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  624)
* requires_zlib() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  608)
* reserved (zipfile.ZipInfo 属性):       ZipInfo 对象.       (line  102)
* reserved word:                         关键字.             (line    6)
* RESERVED_FUTURE() (在 uuid 模块中):    uuid --- UUID objects according to RFC 4122.
                                                             (line  235)
* RESERVED_MICROSOFT() (在 uuid 模块中): uuid --- UUID objects according to RFC 4122.
                                                             (line  231)
* RESERVED_NCS() (在 uuid 模块中):       uuid --- UUID objects according to RFC 4122.
                                                             (line  223)
* reset() (bdb.Bdb 方法):                bdb --- Debugger framework.
                                                             (line  106)
* reset() (codecs.IncrementalDecoder 方法): IncrementalDecoder 对象.
                                                             (line   33)
* reset() (codecs.IncrementalEncoder 方法): IncrementalEncoder 对象.
                                                             (line   30)
* reset() (codecs.StreamReader 方法):    StreamReader 对象.  (line   68)
* reset() (codecs.StreamWriter 方法):    StreamWriter 对象.  (line   36)
* reset() (contextvars.ContextVar 方法): 上下文变量.         (line   49)
* reset() (html.parser.HTMLParser 方法): HTMLParser 方法.    (line   21)
* reset() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line  168)
* reset() (pipes.Template 方法):         模板对象.           (line    8)
* reset() (threading.Barrier 方法):      栅栏对象.           (line   62)
* reset() (xdrlib.Packer 方法):          Packer 对象.        (line   12)
* reset() (xdrlib.Unpacker 方法):        Unpacker 对象.      (line    8)
* reset() (xml.dom.pulldom.DOMEventStream 方法): DOMEventStream 对象.
                                                             (line   35)
* reset() (xml.sax.xmlreader.IncrementalParser 方法): IncrementalParser 对象.
                                                             (line   17)
* reset() (在 turtle 模块中):            窗口控制.           (line   46)
* resetbuffer() (code.InteractiveConsole 方法): 交互式控制台对象.
                                                             (line   33)
* resetlocale() (在 locale 模块中):      locale --- 国际化服务.
                                                             (line  349)
* resetscreen() (在 turtle 模块中):      窗口控制.           (line   46)
* resetty() (在 curses 模块中):          函数<3>.            (line  336)
* resetwarnings() (在 warnings 模块中):  Available Functions.
                                                             (line   98)
* reset_mock() (unittest.mock.AsyncMock 方法): Mock 类.      (line  840)
* reset_mock() (unittest.mock.Mock 方法): Mock 类.           (line  178)
* reset_prog_mode() (在 curses 模块中):  函数<3>.            (line  326)
* reset_shell_mode() (在 curses 模块中): 函数<3>.            (line  331)
* resize() (curses.window 方法):         Window 对象.        (line  417)
* resize() (mmap.mmap 方法):             mmap --- 内存映射文件支持.
                                                             (line  211)
* resize() (在 ctypes 模块中):           工具函数.           (line  143)
* resizemode() (在 turtle 模块中):       外观.               (line   23)
* resizeterm() (在 curses 模块中):       函数<3>.            (line  348)
* resize_term() (在 curses 模块中):      函数<3>.            (line  340)
* resolution (datetime.date 属性):       date 对象.          (line   88)
* resolution (datetime.datetime 属性):   datetime 对象.      (line  235)
* resolution (datetime.time 属性):       time 对象.          (line   38)
* resolution (datetime.timedelta 属性):  timedelta 类对象.   (line   79)
* resolve() (pathlib.Path 方法):         方法<2>.            (line  298)
* resolveEntity() (xml.sax.handler.EntityResolver 方法): EntityResolver 对象.
                                                             (line    6)
* resolve_bases() (在 types 模块中):     动态类型创建.       (line   48)
* resolve_name() (在 importlib.util 模块中): importlib util -- Utility code for importers.
                                                             (line   80)
* resource (模块):                       resource --- Resource usage information.
                                                             (line    6)
* Resource() (在 importlib.resources 模块中): importlib resources -- 资源.
                                                             (line   41)
* ResourceDenied:                        test support --- Utilities for the Python test suite.
                                                             (line   22)
* ResourceLoader (importlib.abc 中的类): importlib abc —— 关于导入的抽象基类.
                                                             (line  312)
* ResourceReader (importlib.abc 中的类): importlib abc —— 关于导入的抽象基类.
                                                             (line  257)
* ResourceWarning:                       警告.               (line   53)
* resource_path() (importlib.abc.ResourceReader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  287)
* response (nntplib.NNTPError 属性):     nntplib --- NNTP protocol client.
                                                             (line  127)
* response() (imaplib.IMAP4 方法):       IMAP4 Objects.      (line  211)
* ResponseNotReady:                      http client --- HTTP 协议客户端.
                                                             (line  155)
* responses (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line  159)
* responses() (在 http.client 模块中):   http client --- HTTP 协议客户端.
                                                             (line  188)
* restart (pdb command):                 调试器命令.         (line  267)
* restore() (在 difflib 模块中):         difflib --- 计算差异的辅助工具.
                                                             (line  232)
* RESTRICTED:                            泛型属性管理.       (line   87)
* restricted; execution:                 内置命名空间和受限的执行.
                                                             (line    6)
* restype (ctypes._FuncPtr 属性):        外部函数.           (line   18)
* result() (asyncio.Future 方法):        Future 对象<2>.     (line   22)
* result() (asyncio.Task 方法):          Task 对象.          (line  108)
* result() (concurrent.futures.Future 方法): Future 对象.    (line   32)
* results() (trace.Trace 方法):          编程接口.           (line   40)
* resume_reading() (asyncio.ReadTransport 方法): 只读传输.   (line   19)
* resume_writing() (asyncio.BaseProtocol 方法): 基础协议<2>. (line   39)
* retr() (poplib.POP3 方法):             POP3 对象.          (line   56)
* retrbinary() (ftplib.FTP 方法):        FTP 对象.           (line   69)
* retrieve() (urllib.request.URLopener 方法): 已停用的接口.  (line  107)
* retrlines() (ftplib.FTP 方法):         FTP 对象.           (line   78)
* return (pdb command):                  调试器命令.         (line  153)
* returncode (asyncio.asyncio.subprocess.Process 属性): 与子进程交互.
                                                             (line  129)
* returncode (subprocess.CalledProcessError 属性): 使用 subprocess 模块.
                                                             (line  176)
* returncode (subprocess.CompletedProcess 属性): 使用 subprocess 模块.
                                                             (line   85)
* returncode (subprocess.Popen 属性):    Popen 对象.         (line  126)
* return_annotation (inspect.Signature 属性): Introspecting callables with the Signature object.
                                                             (line   89)
* return_ok() (http.cookiejar.CookiePolicy 方法): CookiePolicy 对象.
                                                             (line   18)
* RETURN_VALUE (opcode):                 Python字节码说明.   (line  323)
* return_value (unittest.mock.Mock 属性): Mock 类.           (line  301)
* retval (pdb command):                  调试器命令.         (line  284)
* reverse() (array.array 方法):          array --- 高效的数值数组.
                                                             (line  188)
* reverse() (collections.deque 方法):    deque 对象.         (line   92)
* reverse() (sequence method):           可变序列类型.       (line   14)
* reverse() (在 audioop 模块中):         audioop --- 处理原始音频数据.
                                                             (line  165)
* reversed() (內置函数):                 内置函数.           (line 1209)
* reverse_order() (pstats.Stats 方法):   Stats 类.           (line  157)
* reverse_pointer (ipaddress.IPv4Address 属性): 地址对象.    (line   72)
* reverse_pointer (ipaddress.IPv6Address 属性): 地址对象.    (line  167)
* Reversible (collections.abc 中的类):   容器抽象基类.       (line  141)
* Reversible (typing 中的类):            类 函数和修饰器.    (line  143)
* revert() (http.cookiejar.FileCookieJar 方法): CookieJar 和 FileCookieJar 对象.
                                                             (line  141)
* rewind() (aifc.aifc 方法):             aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   89)
* rewind() (sunau.AU_read 方法):         AU_read 对象.       (line   53)
* rewind() (wave.Wave_read 方法):        Wave_read对象.      (line   48)
* rfc2109 (http.cookiejar.Cookie 属性):  Cookie 对象<2>.     (line   68)
* rfc2109_as_netscape (http.cookiejar.DefaultCookiePolicy 属性): DefaultCookiePolicy 对象.
                                                             (line   83)
* rfc2965 (http.cookiejar.CookiePolicy 属性): CookiePolicy 对象.
                                                             (line   72)
* rfc822_escape() (在 distutils.util 模块中): distutils util --- Miscellaneous other utility functions.
                                                             (line  171)
* RFC; RFC 1014:                         xdrlib --- 编码与解码 XDR 数据.
                                                             (line   10)
* RFC; RFC 1014 <1>:                     xdrlib --- 编码与解码 XDR 数据.
                                                             (line   30)
* RFC; RFC 1123:                         函数<2>.            (line  533)
* RFC; RFC 1321:                         hashlib --- 安全哈希与消息摘要.
                                                             (line   12)
* RFC; RFC 1422:                         证书.               (line   26)
* RFC; RFC 1422 <1>:                     LibreSSL 支持.      (line   28)
* RFC; RFC 1521:                         base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  239)
* RFC; RFC 1521 <1>:                     quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   10)
* RFC; RFC 1521 <2>:                     quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   32)
* RFC; RFC 1522:                         binascii --- 二进制和 ASCII 码互转.
                                                             (line   62)
* RFC; RFC 1522 <1>:                     quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   22)
* RFC; RFC 1522 <2>:                     quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   33)
* RFC; RFC 1524:                         mailcap --- Mailcap 文件处理.
                                                             (line   17)
* RFC; RFC 1524 <1>:                     mailcap --- Mailcap 文件处理.
                                                             (line   31)
* RFC; RFC 1730:                         imaplib --- IMAP4 协议客户端.
                                                             (line   12)
* RFC; RFC 1738:                         URL Quoting.        (line  181)
* RFC; RFC 1750:                         随机生成.           (line   60)
* RFC; RFC 1766:                         locale --- 国际化服务.
                                                             (line  304)
* RFC; RFC 1766 <1>:                     locale --- 国际化服务.
                                                             (line  315)
* RFC; RFC 1808:                         urllib.             (line   23)
* RFC; RFC 1808 <1>:                     URL 解析.           (line   33)
* RFC; RFC 1808 <2>:                     URL Quoting.        (line  175)
* RFC; RFC 1832:                         xdrlib --- 编码与解码 XDR 数据.
                                                             (line   33)
* RFC; RFC 1832 <1>:                     xdrlib --- 编码与解码 XDR 数据.
                                                             (line   35)
* RFC; RFC 1869:                         smtplib ---SMTP协议客户端.
                                                             (line   12)
* RFC; RFC 1869 <1>:                     smtplib ---SMTP协议客户端.
                                                             (line  165)
* RFC; RFC 1870:                         smtpd<3>.           (line    7)
* RFC; RFC 1870 <1>:                     smtpd --- SMTP 服务器.
                                                             (line   26)
* RFC; RFC 1870 <2>:                     SMTPChannel 对象.   (line  124)
* RFC; RFC 1939:                         poplib --- POP3 协议客户端.
                                                             (line   11)
* RFC; RFC 1939 <1>:                     poplib --- POP3 协议客户端.
                                                             (line   11)
* RFC; RFC 2033:                         新增和改进的模块<2>.
                                                             (line  568)
* RFC; RFC 2045:                         email --- 电子邮件与 MIME 处理包.
                                                             (line   14)
* RFC; RFC 2045 <1>:                     email message 表示一封电子邮件信息.
                                                             (line  259)
* RFC; RFC 2045 <2>:                     email message 表示一封电子邮件信息.
                                                             (line  260)
* RFC; RFC 2045 <3>:                     email message 表示一封电子邮件信息.
                                                             (line  263)
* RFC; RFC 2045 <4>:                     email headerregistry 自定义标头对象.
                                                             (line  192)
* RFC; RFC 2045 <5>:                     email headerregistry 自定义标头对象.
                                                             (line  246)
* RFC; RFC 2045 <6>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  352)
* RFC; RFC 2045 <7>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  355)
* RFC; RFC 2045 <8>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  357)
* RFC; RFC 2045 <9>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  436)
* RFC; RFC 2045 <10>:                    email header 国际化标头.
                                                             (line   24)
* RFC; RFC 2045 <11>:                    base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line   24)
* RFC; RFC 2045 <12>:                    base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line   25)
* RFC; RFC 2045 <13>:                    base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  205)
* RFC; RFC 2045 <14>:                    base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line  211)
* RFC; RFC 2045#section-6.8:             Binary 对象.        (line   31)
* RFC; RFC 2046:                         email --- 电子邮件与 MIME 处理包.
                                                             (line   14)
* RFC; RFC 2046 <1>:                     内容管理器实例.     (line   72)
* RFC; RFC 2046 <2>:                     email header 国际化标头.
                                                             (line   24)
* RFC; RFC 2047:                         PEP 3333 Python Web服务器网关接口v1 0 1.
                                                             (line   21)
* RFC; RFC 2047 <1>:                     email<5>.           (line   27)
* RFC; RFC 2047 <2>:                     email --- 电子邮件与 MIME 处理包.
                                                             (line   14)
* RFC; RFC 2047 <3>:                     email policy 策略对象.
                                                             (line  277)
* RFC; RFC 2047 <4>:                     email policy 策略对象.
                                                             (line  280)
* RFC; RFC 2047 <5>:                     email headerregistry 自定义标头对象.
                                                             (line   64)
* RFC; RFC 2047 <6>:                     email headerregistry 自定义标头对象.
                                                             (line  101)
* RFC; RFC 2047 <7>:                     email headerregistry 自定义标头对象.
                                                             (line  103)
* RFC; RFC 2047 <8>:                     email header 国际化标头.
                                                             (line   25)
* RFC; RFC 2047 <9>:                     email header 国际化标头.
                                                             (line   44)
* RFC; RFC 2047 <10>:                    email header 国际化标头.
                                                             (line   94)
* RFC; RFC 2047 <11>:                    email header 国际化标头.
                                                             (line  113)
* RFC; RFC 2047 <12>:                    email utils 其他工具.
                                                             (line   60)
* RFC; RFC 2060:                         imaplib --- IMAP4 协议客户端.
                                                             (line   11)
* RFC; RFC 2060 <1>:                     IMAP4 Objects.      (line  310)
* RFC; RFC 2068:                         http cookies --- HTTP状态管理.
                                                             (line   16)
* RFC; RFC 2104:                         新增和改进的模块<3>.
                                                             (line   35)
* RFC; RFC 2104 <1>:                     hmac --- 基于密钥的消息验证.
                                                             (line   10)
* RFC; RFC 2109:                         http cookies --- HTTP状态管理.
                                                             (line   15)
* RFC; RFC 2109 <1>:                     http cookies --- HTTP状态管理.
                                                             (line   35)
* RFC; RFC 2109 <2>:                     http cookies --- HTTP状态管理.
                                                             (line   65)
* RFC; RFC 2109 <3>:                     Morsel 对象.        (line    8)
* RFC; RFC 2109 <4>:                     Morsel 对象.        (line   11)
* RFC; RFC 2109 <5>:                     Morsel 对象.        (line   98)
* RFC; RFC 2109 <6>:                     Morsel 对象.        (line  110)
* RFC; RFC 2109 <7>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   15)
* RFC; RFC 2109 <8>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   82)
* RFC; RFC 2109 <9>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   94)
* RFC; RFC 2109 <10>:                    http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line  121)
* RFC; RFC 2109 <11>:                    DefaultCookiePolicy 对象.
                                                             (line   86)
* RFC; RFC 2109 <12>:                    Cookie 对象<2>.     (line   11)
* RFC; RFC 2109 <13>:                    Cookie 对象<2>.     (line   23)
* RFC; RFC 2109 <14>:                    Cookie 对象<2>.     (line   70)
* RFC; RFC 2183:                         email --- 电子邮件与 MIME 处理包.
                                                             (line   14)
* RFC; RFC 2183 <1>:                     email message 表示一封电子邮件信息.
                                                             (line  382)
* RFC; RFC 2183 <2>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  525)
* RFC; RFC 2231:                         email --- 电子邮件与 MIME 处理包.
                                                             (line   15)
* RFC; RFC 2231 <1>:                     email message 表示一封电子邮件信息.
                                                             (line  230)
* RFC; RFC 2231 <2>:                     email message 表示一封电子邮件信息.
                                                             (line  302)
* RFC; RFC 2231 <3>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  319)
* RFC; RFC 2231 <4>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  321)
* RFC; RFC 2231 <5>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  410)
* RFC; RFC 2231 <6>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  416)
* RFC; RFC 2231 <7>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  443)
* RFC; RFC 2231 <8>:                     email header 国际化标头.
                                                             (line   25)
* RFC; RFC 2231 <9>:                     email utils 其他工具.
                                                             (line  150)
* RFC; RFC 2231 <10>:                    email utils 其他工具.
                                                             (line  154)
* RFC; RFC 2231 <11>:                    email utils 其他工具.
                                                             (line  162)
* RFC; RFC 2231 <12>:                    email utils 其他工具.
                                                             (line  167)
* RFC; RFC 2231 <13>:                    email utils 其他工具.
                                                             (line  175)
* RFC; RFC 2295:                         HTTP 状态码.        (line  181)
* RFC; RFC 2342:                         新增和改进的模块<3>.
                                                             (line   93)
* RFC; RFC 2342 <1>:                     IMAP4 Objects.      (line  164)
* RFC; RFC 2368:                         URL Quoting.        (line  171)
* RFC; RFC 2373:                         地址对象.           (line   90)
* RFC; RFC 2373 <1>:                     地址对象.           (line  109)
* RFC; RFC 2373 <2>:                     地址对象.           (line  119)
* RFC; RFC 2396:                         urllib parse<2>.    (line    6)
* RFC; RFC 2396 <1>:                     urllib.             (line   24)
* RFC; RFC 2396 <2>:                     URL 解析.           (line  239)
* RFC; RFC 2396 <3>:                     URL Quoting.        (line   24)
* RFC; RFC 2396 <4>:                     URL Quoting.        (line  166)
* RFC; RFC 2397:                         DataHandler 对象.   (line    8)
* RFC; RFC 2449:                         POP3 对象.          (line   24)
* RFC; RFC 2487:                         新增和改进的模块<3>.
                                                             (line   85)
* RFC; RFC 2595:                         poplib --- POP3 协议客户端.
                                                             (line   12)
* RFC; RFC 2595 <1>:                     POP3 对象.          (line  103)
* RFC; RFC 2616:                         PEP 3333 Python Web服务器网关接口v1 0 1.
                                                             (line   20)
* RFC; RFC 2616 <1>:                     wsgiref util -- WSGI environment utilities.
                                                             (line  112)
* RFC; RFC 2616 <2>:                     wsgiref validate --- WSGI conformance checker.
                                                             (line   27)
* RFC; RFC 2616 <3>:                     HTTPRedirectHandler 对象.
                                                             (line    7)
* RFC; RFC 2616 <4>:                     HTTPRedirectHandler 对象.
                                                             (line   23)
* RFC; RFC 2616 <5>:                     已停用的接口.       (line  157)
* RFC; RFC 2616 <6>:                     urllib error --- urllib request 引发的异常类.
                                                             (line   36)
* RFC; RFC 2616 <7>:                     概述<19>.           (line   28)
* RFC; RFC 2616 <8>:                     HTTPError.          (line   13)
* RFC; RFC 2616 <9>:                     错误代码.           (line   10)
* RFC; RFC 2732:                         urllib parse<3>.    (line   10)
* RFC; RFC 2732 <1>:                     新增和改进的模块.   (line  638)
* RFC; RFC 2732 <2>:                     URL Quoting.        (line  162)
* RFC; RFC 2818:                         ssl<9>.             (line   16)
* RFC; RFC 2818 <1>:                     证书处理.           (line    9)
* RFC; RFC 2821:                         email --- 电子邮件与 MIME 处理包.
                                                             (line   11)
* RFC; RFC 2822:                         新增和改进的模块<3>.
                                                             (line   97)
* RFC; RFC 2822 <1>:                     自带电池.           (line   13)
* RFC; RFC 2822 <2>:                     函数<2>.            (line  300)
* RFC; RFC 2822 <3>:                     函数<2>.            (line  533)
* RFC; RFC 2822 <4>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  226)
* RFC; RFC 2822 <5>:                     email header 国际化标头.
                                                             (line   17)
* RFC; RFC 2822 <6>:                     email header 国际化标头.
                                                             (line   18)
* RFC; RFC 2822 <7>:                     email header 国际化标头.
                                                             (line   24)
* RFC; RFC 2822 <8>:                     email header 国际化标头.
                                                             (line   71)
* RFC; RFC 2822 <9>:                     email header 国际化标头.
                                                             (line   94)
* RFC; RFC 2822 <10>:                    email header 国际化标头.
                                                             (line  108)
* RFC; RFC 2822 <11>:                    email utils 其他工具.
                                                             (line   25)
* RFC; RFC 2822 <12>:                    email utils 其他工具.
                                                             (line   82)
* RFC; RFC 2822 <13>:                    email utils 其他工具.
                                                             (line   85)
* RFC; RFC 2822 <14>:                    email utils 其他工具.
                                                             (line  194)
* RFC; RFC 2822 <15>:                    email utils 其他工具.
                                                             (line  120)
* RFC; RFC 2822 <16>:                    Message 对象.       (line   15)
* RFC; RFC 2822 <17>:                    http client --- HTTP 协议客户端.
                                                             (line   98)
* RFC; RFC 2822 <18>:                    http server --- HTTP 服务器.
                                                             (line   98)
* RFC; RFC 2964:                         http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line  134)
* RFC; RFC 2965:                         urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  190)
* RFC; RFC 2965 <1>:                     urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  196)
* RFC; RFC 2965 <2>:                     Request 对象.       (line   45)
* RFC; RFC 2965 <3>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   14)
* RFC; RFC 2965 <4>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   82)
* RFC; RFC 2965 <5>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   94)
* RFC; RFC 2965 <6>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line  123)
* RFC; RFC 2965 <7>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line  125)
* RFC; RFC 2965 <8>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line  132)
* RFC; RFC 2965 <9>:                     FileCookieJar subclasses and co-operation with web browsers.
                                                             (line   16)
* RFC; RFC 2965 <10>:                    CookiePolicy 对象.  (line   74)
* RFC; RFC 2965 <11>:                    CookiePolicy 对象.  (line   79)
* RFC; RFC 2965 <12>:                    DefaultCookiePolicy 对象.
                                                             (line    8)
* RFC; RFC 2965 <13>:                    DefaultCookiePolicy 对象.
                                                             (line   90)
* RFC; RFC 2965 <14>:                    DefaultCookiePolicy 对象.
                                                             (line  101)
* RFC; RFC 2965 <15>:                    DefaultCookiePolicy 对象.
                                                             (line  105)
* RFC; RFC 2965 <16>:                    DefaultCookiePolicy 对象.
                                                             (line  114)
* RFC; RFC 2965 <17>:                    DefaultCookiePolicy 对象.
                                                             (line  151)
* RFC; RFC 2965 <18>:                    Cookie 对象<2>.     (line   23)
* RFC; RFC 2965 <19>:                    例子<24>.           (line   25)
* RFC; RFC 2980:                         nntplib --- NNTP protocol client.
                                                             (line   13)
* RFC; RFC 2980 <1>:                     方法<3>.            (line  316)
* RFC; RFC 3056:                         地址对象.           (line  207)
* RFC; RFC 3171:                         地址对象.           (line   90)
* RFC; RFC 3207:                         新增和改进的模块<2>.
                                                             (line  573)
* RFC; RFC 3280:                         SSL 套接字.         (line  131)
* RFC; RFC 3330:                         地址对象.           (line  118)
* RFC; RFC 3339:                         在消息中显示日期/时间.
                                                             (line   16)
* RFC; RFC 3454:                         stringprep --- 因特网字符串预备.
                                                             (line   14)
* RFC; RFC 3454 <1>:                     stringprep --- 因特网字符串预备.
                                                             (line   20)
* RFC; RFC 3490:                         文字编码.           (line   14)
* RFC; RFC 3490 <1>:                     encodings idna --- 应用程序中的国际化域名.
                                                             (line    6)
* RFC; RFC 3490 <2>:                     encodings idna --- 应用程序中的国际化域名.
                                                             (line   45)
* RFC; RFC 3490 <3>:                     encodings idna --- 应用程序中的国际化域名.
                                                             (line   50)
* RFC; RFC 3490#section-3.1:             encodings idna --- 应用程序中的国际化域名.
                                                             (line   22)
* RFC; RFC 3492:                         文字编码.           (line   34)
* RFC; RFC 3492 <1>:                     encodings idna --- 应用程序中的国际化域名.
                                                             (line    6)
* RFC; RFC 3493:                         示例<8>.            (line  216)
* RFC; RFC 3501:                         IMAP4 Objects.      (line  321)
* RFC; RFC 3542:                         库<29>.             (line  350)
* RFC; RFC 3542 <1>:                     其他功能<2>.        (line  247)
* RFC; RFC 3548:                         新增，改进和弃用的模块<3>.
                                                             (line   16)
* RFC; RFC 3548 <1>:                     base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line   11)
* RFC; RFC 3548 <2>:                     base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line   14)
* RFC; RFC 3548 <3>:                     base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line   20)
* RFC; RFC 3548 <4>:                     base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line   97)
* RFC; RFC 3659:                         FTP 对象.           (line  143)
* RFC; RFC 3879:                         地址对象.           (line  192)
* RFC; RFC 3927:                         地址对象.           (line  123)
* RFC; RFC 3977:                         nntplib --- NNTP protocol client.
                                                             (line   13)
* RFC; RFC 3977 <1>:                     Attributes.         (line   10)
* RFC; RFC 3977 <2>:                     方法<3>.            (line   35)
* RFC; RFC 3977 <3>:                     方法<3>.            (line  137)
* RFC; RFC 3977 <4>:                     方法<3>.            (line  317)
* RFC; RFC 3986:                         urllib parse.       (line    6)
* RFC; RFC 3986 <1>:                     urllib parse<2>.    (line    6)
* RFC; RFC 3986 <2>:                     urllib.             (line   22)
* RFC; RFC 3986 <3>:                     新增和改进的模块.   (line  617)
* RFC; RFC 3986 <4>:                     移植到 Python 2 7.  (line   80)
* RFC; RFC 3986 <5>:                     URL 解析.           (line  125)
* RFC; RFC 3986 <6>:                     URL 解析.           (line  339)
* RFC; RFC 3986 <7>:                     URL Quoting.        (line   24)
* RFC; RFC 3986 <8>:                     URL Quoting.        (line  154)
* RFC; RFC 3986 <9>:                     http server --- HTTP 服务器.
                                                             (line   84)
* RFC; RFC 4086:                         LibreSSL 支持.      (line   32)
* RFC; RFC 4122:                         新增，改进和删除的模块.
                                                             (line  415)
* RFC; RFC 4122 <1>:                     新增，改进和删除的模块.
                                                             (line  420)
* RFC; RFC 4122 <2>:                     uuid --- UUID objects according to RFC 4122.
                                                             (line    6)
* RFC; RFC 4122 <3>:                     uuid --- UUID objects according to RFC 4122.
                                                             (line   12)
* RFC; RFC 4122 <4>:                     uuid --- UUID objects according to RFC 4122.
                                                             (line   71)
* RFC; RFC 4122 <5>:                     uuid --- UUID objects according to RFC 4122.
                                                             (line  136)
* RFC; RFC 4122 <6>:                     uuid --- UUID objects according to RFC 4122.
                                                             (line  165)
* RFC; RFC 4122 <7>:                     uuid --- UUID objects according to RFC 4122.
                                                             (line  229)
* RFC; RFC 4122 <8>:                     uuid --- UUID objects according to RFC 4122.
                                                             (line  242)
* RFC; RFC 4180:                         csv --- CSV 文件读写.
                                                             (line   11)
* RFC; RFC 4193:                         地址对象.           (line  194)
* RFC; RFC 4217:                         ftplib --- FTP 协议客户端.
                                                             (line   71)
* RFC; RFC 4291:                         地址对象.           (line  137)
* RFC; RFC 4380:                         地址对象.           (line  214)
* RFC; RFC 4627:                         json --- JSON 编码和解码器.
                                                             (line   10)
* RFC; RFC 4627 <1>:                     顶级非对象，非数组值.
                                                             (line    6)
* RFC; RFC 4642:                         nntplib --- NNTP protocol client.
                                                             (line  104)
* RFC; RFC 4954:                         SMTP Objects.       (line  128)
* RFC; RFC 4954 <1>:                     SMTP Objects.       (line  150)
* RFC; RFC 5161:                         imaplib.            (line   11)
* RFC; RFC 5161 <1>:                     IMAP4 Objects.      (line   86)
* RFC; RFC 5246:                         常量<9>.            (line  433)
* RFC; RFC 5246 <1>:                     LibreSSL 支持.      (line   40)
* RFC; RFC 5280:                         Other Changes.      (line   20)
* RFC; RFC 5280 <1>:                     Python API 的变化<5>.
                                                             (line   95)
* RFC; RFC 5280 <2>:                     证书处理.           (line    9)
* RFC; RFC 5280 <3>:                     证书处理.           (line   58)
* RFC; RFC 5280 <4>:                     LibreSSL 支持.      (line   36)
* RFC; RFC 5321:                         smtpd<3>.           (line    6)
* RFC; RFC 5321 <1>:                     email headerregistry 自定义标头对象.
                                                             (line  386)
* RFC; RFC 5321 <2>:                     smtpd --- SMTP 服务器.
                                                             (line   26)
* RFC; RFC 5321 <3>:                     SMTPServer 对象.    (line   49)
* RFC; RFC 5321 <4>:                     SMTPServer 对象.    (line   77)
* RFC; RFC 5322:                         email --- 电子邮件与 MIME 处理包.
                                                             (line   13)
* RFC; RFC 5322 <1>:                     email message 表示一封电子邮件信息.
                                                             (line   17)
* RFC; RFC 5322 <2>:                     email message 表示一封电子邮件信息.
                                                             (line   25)
* RFC; RFC 5322 <3>:                     Parser API.         (line   35)
* RFC; RFC 5322 <4>:                     email generator 生成 MIME 文档.
                                                             (line   82)
* RFC; RFC 5322 <5>:                     email generator 生成 MIME 文档.
                                                             (line  161)
* RFC; RFC 5322 <6>:                     email policy 策略对象.
                                                             (line  118)
* RFC; RFC 5322 <7>:                     email policy 策略对象.
                                                             (line  260)
* RFC; RFC 5322 <8>:                     email policy 策略对象.
                                                             (line  277)
* RFC; RFC 5322 <9>:                     email policy 策略对象.
                                                             (line  281)
* RFC; RFC 5322 <10>:                    email policy 策略对象.
                                                             (line  293)
* RFC; RFC 5322 <11>:                    email policy 策略对象.
                                                             (line  320)
* RFC; RFC 5322 <12>:                    email errors 异常和缺陷类.
                                                             (line   25)
* RFC; RFC 5322 <13>:                    email headerregistry 自定义标头对象.
                                                             (line   14)
* RFC; RFC 5322 <14>:                    email headerregistry 自定义标头对象.
                                                             (line   96)
* RFC; RFC 5322 <15>:                    email headerregistry 自定义标头对象.
                                                             (line  100)
* RFC; RFC 5322 <16>:                    email headerregistry 自定义标头对象.
                                                             (line  101)
* RFC; RFC 5322 <17>:                    email headerregistry 自定义标头对象.
                                                             (line  112)
* RFC; RFC 5322 <18>:                    email headerregistry 自定义标头对象.
                                                             (line  128)
* RFC; RFC 5322 <19>:                    email headerregistry 自定义标头对象.
                                                             (line  355)
* RFC; RFC 5322 <20>:                    email headerregistry 自定义标头对象.
                                                             (line  383)
* RFC; RFC 5322 <21>:                    email headerregistry 自定义标头对象.
                                                             (line  412)
* RFC; RFC 5322 <22>:                    email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line   17)
* RFC; RFC 5322 <23>:                    SMTP Objects.       (line  303)
* RFC; RFC 5424:                         SysLogHandler.      (line   46)
* RFC; RFC 5424 <1>:                     在发送给 SysLogHandler 的信息中插入一个 BOM。.
                                                             (line    6)
* RFC; RFC 5424 <2>:                     在发送给 SysLogHandler 的信息中插入一个 BOM。.
                                                             (line   15)
* RFC; RFC 5424 <3>:                     在发送给 SysLogHandler 的信息中插入一个 BOM。.
                                                             (line   34)
* RFC; RFC 5424#section-6:               在发送给 SysLogHandler 的信息中插入一个 BOM。.
                                                             (line    8)
* RFC; RFC 5735:                         地址对象.           (line  108)
* RFC; RFC 5891:                         encodings idna --- 应用程序中的国际化域名.
                                                             (line   10)
* RFC; RFC 5895:                         encodings idna --- 应用程序中的国际化域名.
                                                             (line   10)
* RFC; RFC 5929:                         SSL 套接字.         (line  213)
* RFC; RFC 6066:                         常量<9>.            (line  343)
* RFC; RFC 6066 <1>:                     SSL 上下文.         (line  260)
* RFC; RFC 6066 <2>:                     LibreSSL 支持.      (line   44)
* RFC; RFC 6125:                         证书处理.           (line   10)
* RFC; RFC 6125 <1>:                     证书处理.           (line   26)
* RFC; RFC 6152:                         smtpd.              (line   17)
* RFC; RFC 6152 <1>:                     SMTPServer 对象.    (line   35)
* RFC; RFC 6531:                         email<2>.           (line   19)
* RFC; RFC 6531 <1>:                     smtpd.              (line   23)
* RFC; RFC 6531 <2>:                     smtplib.            (line   15)
* RFC; RFC 6531 <3>:                     email message 表示一封电子邮件信息.
                                                             (line   80)
* RFC; RFC 6531 <4>:                     email policy 策略对象.
                                                             (line  296)
* RFC; RFC 6531 <5>:                     smtplib ---SMTP协议客户端.
                                                             (line   53)
* RFC; RFC 6531 <6>:                     smtpd --- SMTP 服务器.
                                                             (line   26)
* RFC; RFC 6531 <7>:                     SMTPServer 对象.    (line   26)
* RFC; RFC 6531 <8>:                     SMTPChannel 对象.   (line   20)
* RFC; RFC 6532:                         email<2>.           (line   18)
* RFC; RFC 6532 <1>:                     email --- 电子邮件与 MIME 处理包.
                                                             (line   13)
* RFC; RFC 6532 <2>:                     email message 表示一封电子邮件信息.
                                                             (line   18)
* RFC; RFC 6532 <3>:                     Parser API.         (line   36)
* RFC; RFC 6532 <4>:                     email policy 策略对象.
                                                             (line  294)
* RFC; RFC 6585:                         HTTP 状态码.        (line  194)
* RFC; RFC 6855:                         imaplib.            (line   12)
* RFC; RFC 6855 <1>:                     imaplib.            (line   14)
* RFC; RFC 6855 <2>:                     IMAP4 Objects.      (line   88)
* RFC; RFC 6855 <3>:                     IMAP4 Objects.      (line   90)
* RFC; RFC 6856:                         poplib.             (line    6)
* RFC; RFC 6856 <1>:                     POP3 对象.          (line   97)
* RFC; RFC 7159:                         json --- JSON 编码和解码器.
                                                             (line   10)
* RFC; RFC 7159 <1>:                     标准符合性和互操作性.
                                                             (line    6)
* RFC; RFC 7159 <2>:                     顶级非对象，非数组值.
                                                             (line    8)
* RFC; RFC 7230:                         urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  167)
* RFC; RFC 7230 <1>:                     HTTPConnection 对象.
                                                             (line  131)
* RFC; RFC 7231:                         HTTP 状态码.        (line   13)
* RFC; RFC 7231 <1>:                     HTTP 状态码.        (line   70)
* RFC; RFC 7231 <2>:                     HTTP 状态码.        (line  102)
* RFC; RFC 7238:                         HTTP 状态码.        (line   73)
* RFC; RFC 7301:                         Application-Layer Protocol Negotiation Support.
                                                             (line   10)
* RFC; RFC 7301 <1>:                     常量<9>.            (line  322)
* RFC; RFC 7301 <2>:                     SSL 上下文.         (line  229)
* RFC; RFC 7525:                         LibreSSL 支持.      (line   52)
* RFC; RFC 7540:                         HTTP 状态码.        (line  134)
* RFC; RFC 7693:                         BLAKE2.             (line    6)
* RFC; RFC 7725:                         HTTP 状态码.        (line  159)
* RFC; RFC 7914:                         密钥派生.           (line   42)
* RFC; RFC 821:                          smtplib ---SMTP协议客户端.
                                                             (line   12)
* RFC; RFC 821 <1>:                      smtplib ---SMTP协议客户端.
                                                             (line  160)
* RFC; RFC 822:                          新增和改进的模块<3>.
                                                             (line   97)
* RFC; RFC 822 <1>:                      函数<2>.            (line  529)
* RFC; RFC 822 <2>:                      函数<2>.            (line  531)
* RFC; RFC 822 <3>:                      email 示例.         (line   35)
* RFC; RFC 822 <4>:                      email header 国际化标头.
                                                             (line   17)
* RFC; RFC 822 <5>:                      HTTPConnection 对象.
                                                             (line  118)
* RFC; RFC 822 <6>:                      SMTP Objects.       (line   87)
* RFC; RFC 822 <7>:                      SMTP Objects.       (line  222)
* RFC; RFC 822 <8>:                      SMTP Objects.       (line  222)
* RFC; RFC 822 <9>:                      SMTP Example.       (line   10)
* RFC; RFC 822 <10>:                     GNUTranslations 类. (line   11)
* RFC; RFC 822 <11>:                     distutils util --- Miscellaneous other utility functions.
                                                             (line  173)
* RFC; RFC 8305:                         打开网络连接.       (line   65)
* RFC; RFC 8305 <1>:                     打开网络连接.       (line   72)
* RFC; RFC 854:                          telnetlib -- Telnet 客户端.
                                                             (line   11)
* RFC; RFC 854 <1>:                      telnetlib -- Telnet 客户端.
                                                             (line   48)
* RFC; RFC 959:                          ftplib --- FTP 协议客户端.
                                                             (line   13)
* RFC; RFC 959 <1>:                      FTP 对象.           (line  126)
* RFC; RFC 977:                          nntplib --- NNTP protocol client.
                                                             (line   13)
* RFC_4122() (在 uuid 模块中):           uuid --- UUID objects according to RFC 4122.
                                                             (line  227)
* rfile (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line  100)
* rfind() (bytearray 方法):              bytes 和 bytearray 操作.
                                                             (line  136)
* rfind() (bytes 方法):                  bytes 和 bytearray 操作.
                                                             (line  136)
* rfind() (mmap.mmap 方法):              mmap --- 内存映射文件支持.
                                                             (line  217)
* rfind() (str 方法):                    字符串的方法<2>.    (line  293)
* rgb_to_hls() (在 colorsys 模块中):     colorsys --- 颜色系统间的转换.
                                                             (line   32)
* rgb_to_hsv() (在 colorsys 模块中):     colorsys --- 颜色系统间的转换.
                                                             (line   40)
* rgb_to_yiq() (在 colorsys 模块中):     colorsys --- 颜色系统间的转换.
                                                             (line   24)
* rglob() (pathlib.Path 方法):           方法<2>.            (line  322)
* richcmpfunc (C 类型):                  Slot Type typedefs. (line   91)
* right (filecmp.dircmp 属性):           dircmp 类.          (line   40)
* right() (在 turtle 模块中):            海龟动作.           (line   39)
* RIGHTSHIFT() (在 token 模块中):        token --- 与Python解析树一起使用的常量.
                                                             (line  158)
* RIGHTSHIFTEQUAL() (在 token 模块中):   token --- 与Python解析树一起使用的常量.
                                                             (line  202)
* right_list (filecmp.dircmp 属性):      dircmp 类.          (line   48)
* right_only (filecmp.dircmp 属性):      dircmp 类.          (line   60)
* rindex() (bytearray 方法):             bytes 和 bytearray 操作.
                                                             (line  148)
* rindex() (bytes 方法):                 bytes 和 bytearray 操作.
                                                             (line  148)
* rindex() (str 方法):                   字符串的方法<2>.    (line  299)
* rjust() (bytearray 方法):              bytes 和 bytearray 操作.
                                                             (line  238)
* rjust() (bytes 方法):                  bytes 和 bytearray 操作.
                                                             (line  238)
* rjust() (str 方法):                    字符串的方法<2>.    (line  304)
* rlcompleter (模块):                    rlcompleter --- GNU readline 的补全函数.
                                                             (line    6)
* rlecode_hqx() (在 binascii 模块中):    binascii --- 二进制和 ASCII 码互转.
                                                             (line   81)
* rledecode_hqx() (在 binascii 模块中):  binascii --- 二进制和 ASCII 码互转.
                                                             (line   72)
* RLIMIT_AS() (在 resource 模块中):      Resource Limits.    (line  147)
* RLIMIT_CORE() (在 resource 模块中):    Resource Limits.    (line   92)
* RLIMIT_CPU() (在 resource 模块中):     Resource Limits.    (line   99)
* RLIMIT_DATA() (在 resource 模块中):    Resource Limits.    (line  111)
* RLIMIT_FSIZE() (在 resource 模块中):   Resource Limits.    (line  107)
* RLIMIT_MEMLOCK() (在 resource 模块中): Resource Limits.    (line  139)
* RLIMIT_MSGQUEUE() (在 resource 模块中): Resource Limits.   (line  152)
* RLIMIT_NICE() (在 resource 模块中):    Resource Limits.    (line  160)
* RLIMIT_NOFILE() (在 resource 模块中):  Resource Limits.    (line  130)
* RLIMIT_NPROC() (在 resource 模块中):   Resource Limits.    (line  126)
* RLIMIT_NPTS() (在 resource 模块中):    Resource Limits.    (line  215)
* RLIMIT_OFILE() (在 resource 模块中):   Resource Limits.    (line  135)
* RLIMIT_RSS() (在 resource 模块中):     Resource Limits.    (line  121)
* RLIMIT_RTPRIO() (在 resource 模块中):  Resource Limits.    (line  169)
* RLIMIT_RTTIME() (在 resource 模块中):  Resource Limits.    (line  177)
* RLIMIT_SBSIZE() (在 resource 模块中):  Resource Limits.    (line  194)
* RLIMIT_SIGPENDING() (在 resource 模块中): Resource Limits. (line  186)
* RLIMIT_STACK() (在 resource 模块中):   Resource Limits.    (line  115)
* RLIMIT_SWAP() (在 resource 模块中):    Resource Limits.    (line  204)
* RLIMIT_VMEM() (在 resource 模块中):    Resource Limits.    (line  143)
* RLIM_INFINITY() (在 resource 模块中):  Resource Limits.    (line   20)
* RLock (multiprocessing 中的类):        同步原语.           (line   84)
* RLock (threading 中的类):              递归锁对象.         (line   18)
* RLock() (multiprocessing.managers.SyncManager 方法): 管理器.
                                                             (line  161)
* rmd() (ftplib.FTP 方法):               FTP 对象.           (line  194)
* rmdir() (pathlib.Path 方法):           方法<2>.            (line  334)
* rmdir() (在 os 模块中):                文件和目录.         (line  643)
* rmdir() (在 test.support 模块中):      test support --- Utilities for the Python test suite.
                                                             (line  177)
* RMFF:                                  chunk --- 读取 IFF 分块数据.
                                                             (line    8)
* rms() (在 audioop 模块中):             audioop --- 处理原始音频数据.
                                                             (line  169)
* rmtree() (在 shutil 模块中):           目录和文件操作.     (line  213)
* rmtree() (在 test.support 模块中):     test support --- Utilities for the Python test suite.
                                                             (line  183)
* RobotFileParser (urllib.robotparser 中的类): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   15)
* robots.txt:                            urllib robotparser --- robots txt 语法分析程序.
                                                             (line    8)
* rollback() (sqlite3.Connection 方法):  连接对象（Connection）.
                                                             (line   36)
* rotate() (collections.deque 方法):     deque 对象.         (line   98)
* rotate() (decimal.Context 方法):       上下文对象.         (line  424)
* rotate() (decimal.Decimal 方法):       Decimal 对象.       (line  437)
* rotate() (logging.handlers.BaseRotatingHandler 方法): BaseRotatingHandler.
                                                             (line   51)
* RotatingFileHandler (logging.handlers 中的类): RotatingFileHandler.
                                                             (line    9)
* rotation_filename() (logging.handlers.BaseRotatingHandler 方法): BaseRotatingHandler.
                                                             (line   36)
* rotator (logging.handlers.BaseRotatingHandler 属性): BaseRotatingHandler.
                                                             (line   28)
* ROT_FOUR (opcode):                     Python字节码说明.   (line   68)
* ROT_THREE (opcode):                    Python字节码说明.   (line   64)
* ROT_TWO (opcode):                      Python字节码说明.   (line   60)
* round() (內置函数):                    内置函数.           (line 1216)
* Rounded (decimal 中的类):              信号.               (line   69)
* ROUND_05UP() (在 decimal 模块中):      舍入模式.           (line   34)
* ROUND_CEILING() (在 decimal 模块中):   舍入模式.           (line    6)
* ROUND_DOWN() (在 decimal 模块中):      舍入模式.           (line   10)
* ROUND_FLOOR() (在 decimal 模块中):     舍入模式.           (line   14)
* ROUND_HALF_DOWN() (在 decimal 模块中): 舍入模式.           (line   18)
* ROUND_HALF_EVEN() (在 decimal 模块中): 舍入模式.           (line   22)
* ROUND_HALF_UP() (在 decimal 模块中):   舍入模式.           (line   26)
* ROUND_UP() (在 decimal 模块中):        舍入模式.           (line   30)
* Row (sqlite3 中的类):                  行对象.             (line    6)
* rowcount (sqlite3.Cursor 属性):        Cursor 对象.        (line  163)
* row_factory (sqlite3.Connection 属性): 连接对象（Connection）.
                                                             (line  272)
* RPAR() (在 token 模块中):              token --- 与Python解析树一起使用的常量.
                                                             (line   54)
* rpartition() (bytearray 方法):         bytes 和 bytearray 操作.
                                                             (line  159)
* rpartition() (bytes 方法):             bytes 和 bytearray 操作.
                                                             (line  159)
* rpartition() (str 方法):               字符串的方法<2>.    (line  310)
* rpc_paths (xmlrpc.server.SimpleXMLRPCRequestHandler 属性): SimpleXMLRPCServer Objects.
                                                             (line   64)
* rpop() (poplib.POP3 方法):             POP3 对象.          (line   42)
* rset() (poplib.POP3 方法):             POP3 对象.          (line   67)
* rshift() (在 operator 模块中):         operator --- 标准运算符替代函数.
                                                             (line  136)
* rsplit() (bytearray 方法):             bytes 和 bytearray 操作.
                                                             (line  248)
* rsplit() (bytes 方法):                 bytes 和 bytearray 操作.
                                                             (line  248)
* rsplit() (str 方法):                   字符串的方法<2>.    (line  316)
* RSQB() (在 token 模块中):              token --- 与Python解析树一起使用的常量.
                                                             (line   62)
* rstrip() (bytearray 方法):             bytes 和 bytearray 操作.
                                                             (line  257)
* rstrip() (bytes 方法):                 bytes 和 bytearray 操作.
                                                             (line  257)
* rstrip() (str 方法):                   字符串的方法<2>.    (line  324)
* rt() (在 turtle 模块中):               海龟动作.           (line   39)
* RTLD_DEEPBIND() (在 os 模块中):        其他系统信息.       (line  118)
* RTLD_GLOBAL() (在 os 模块中):          其他系统信息.       (line  118)
* RTLD_LAZY() (在 os 模块中):            其他系统信息.       (line  118)
* RTLD_LOCAL() (在 os 模块中):           其他系统信息.       (line  118)
* RTLD_NODELETE() (在 os 模块中):        其他系统信息.       (line  118)
* RTLD_NOLOAD() (在 os 模块中):          其他系统信息.       (line  118)
* RTLD_NOW() (在 os 模块中):             其他系统信息.       (line  118)
* ruler (cmd.Cmd 属性):                  Cmd 对象.           (line  132)
* run (pdb command):                     调试器命令.         (line  267)
* Run script:                            格式菜单（仅 window 编辑器）.
                                                             (line   49)
* run() (bdb.Bdb 方法):                  bdb --- Debugger framework.
                                                             (line  361)
* run() (contextvars.Context 方法):      手动上下文管理.     (line   27)
* run() (distutils.cmd.Command 方法):    Creating a new Distutils command.
                                                             (line   40)
* run() (doctest.DocTestRunner 方法):    DocTestRunner 对象. (line   95)
* run() (multiprocessing.Process 方法):  Process 和异常.     (line   28)
* run() (pdb.Pdb 方法):                  pdb --- Python的调试器.
                                                             (line  156)
* run() (profile.Profile 方法):          profile 和 cProfile 模块参考.
                                                             (line   98)
* run() (sched.scheduler 方法):          调度器对象.         (line   45)
* run() (test.support.BasicTestRunner 方法): test support --- Utilities for the Python test suite.
                                                             (line 1103)
* run() (threading.Thread 方法):         线程对象.           (line   83)
* run() (trace.Trace 方法):              编程接口.           (line   22)
* run() (unittest.IsolatedAsyncioTestCase 方法): 测试用例.   (line  838)
* run() (unittest.TestCase 方法):        测试用例.           (line   83)
* run() (unittest.TestSuite 方法):       Grouping tests.     (line   41)
* run() (unittest.TextTestRunner 方法):  Loading and running tests.
                                                             (line  480)
* run() (wsgiref.handlers.BaseHandler 方法): wsgiref handlers -- server/gateway base classes.
                                                             (line   98)
* run() (在 asyncio 模块中):             运行 asyncio 程序.  (line    6)
* run() (在 pdb 模块中):                 pdb --- Python的调试器.
                                                             (line   80)
* run() (在 profile 模块中):             profile 和 cProfile 模块参考.
                                                             (line    8)
* run() (在 subprocess 模块中):          使用 subprocess 模块.
                                                             (line   12)
* runcall() (bdb.Bdb 方法):              bdb --- Debugger framework.
                                                             (line  378)
* runcall() (pdb.Pdb 方法):              pdb --- Python的调试器.
                                                             (line  156)
* runcall() (profile.Profile 方法):      profile 和 cProfile 模块参考.
                                                             (line  107)
* runcall() (在 pdb 模块中):             pdb --- Python的调试器.
                                                             (line   96)
* runcode() (code.InteractiveInterpreter 方法): 交互解释器对象.
                                                             (line   29)
* runctx() (bdb.Bdb 方法):               bdb --- Debugger framework.
                                                             (line  373)
* runctx() (profile.Profile 方法):       profile 和 cProfile 模块参考.
                                                             (line  102)
* runctx() (trace.Trace 方法):           编程接口.           (line   28)
* runctx() (在 profile 模块中):          profile 和 cProfile 模块参考.
                                                             (line   22)
* runeval() (bdb.Bdb 方法):              bdb --- Debugger framework.
                                                             (line  367)
* runeval() (pdb.Pdb 方法):              pdb --- Python的调试器.
                                                             (line  156)
* runeval() (在 pdb 模块中):             pdb --- Python的调试器.
                                                             (line   90)
* runfunc() (trace.Trace 方法):          编程接口.           (line   35)
* running() (concurrent.futures.Future 方法): Future 对象.   (line   24)
* runpy (模块):                          runpy --- Locating and executing Python modules.
                                                             (line    6)
* runsource() (code.InteractiveInterpreter 方法): 交互解释器对象.
                                                             (line    6)
* RuntimeError:                          具体异常.           (line  171)
* RuntimeWarning:                        警告.               (line   32)
* runtime_checkable() (在 typing 模块中): 类 函数和修饰器.   (line  690)
* runtime_library_dir_option() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  228)
* run_coroutine_threadsafe() (在 asyncio 模块中): 来自其他线程的日程安排.
                                                             (line    6)
* run_docstring_examples() (在 doctest 模块中): Basic API.   (line  128)
* run_doctest() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  270)
* run_forever() (asyncio.loop 方法):     运行和停止循环.     (line   15)
* run_in_executor() (asyncio.loop 方法): 在线程或者进程池中执行代码。.
                                                             (line    6)
* run_in_subinterp() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  950)
* run_module() (在 runpy 模块中):        runpy --- Locating and executing Python modules.
                                                             (line   27)
* run_path() (在 runpy 模块中):          runpy --- Locating and executing Python modules.
                                                             (line   95)
* run_python_until_end() (在 test.support.script_helper 模块中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   29)
* run_script() (modulefinder.ModuleFinder 方法): modulefinder --- 查找脚本使用的模块.
                                                             (line   37)
* run_setup() (在 distutils.core 模块中): distutils core --- 分发包功能的核心.
                                                             (line  110)
* run_unittest() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  254)
* run_until_complete() (asyncio.loop 方法): 运行和停止循环.  (line    6)
* run_with_locale() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  573)
* run_with_tz() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  581)
* RUSAGE_BOTH() (在 resource 模块中):    Resource Usage.     (line  122)
* RUSAGE_CHILDREN() (在 resource 模块中): Resource Usage.    (line  116)
* RUSAGE_SELF() (在 resource 模块中):    Resource Usage.     (line  110)
* RUSAGE_THREAD() (在 resource 模块中):  Resource Usage.     (line  128)
* RWF_DSYNC() (在 os 模块中):            文件描述符操作.     (line  480)
* RWF_HIPRI() (在 os 模块中):            文件描述符操作.     (line  431)
* RWF_NOWAIT() (在 os 模块中):           文件描述符操作.     (line  419)
* RWF_SYNC() (在 os 模块中):             文件描述符操作.     (line  489)
* R_OK() (在 os 模块中):                 文件和目录.         (line   89)
* S() (在 re 模块中):                    模块内容.           (line   89)
* safe (uuid.SafeUUID 属性):             uuid --- UUID objects according to RFC 4122.
                                                             (line   31)
* SafeChildWatcher (asyncio 中的类):     进程监视器.         (line  102)
* saferepr() (在 pprint 模块中):         pprint --- 数据美化输出.
                                                             (line  127)
* SafeUUID (uuid 中的类):                uuid --- UUID objects according to RFC 4122.
                                                             (line   27)
* safe_substitute() (string.Template 方法): 模板字符串.      (line   39)
* samefile() (pathlib.Path 方法):        方法<2>.            (line  338)
* samefile() (在 os.path 模块中):        os path --- 常用路径操作.
                                                             (line  282)
* SameFileError:                         目录和文件操作.     (line   43)
* sameopenfile() (在 os.path 模块中):    os path --- 常用路径操作.
                                                             (line  296)
* samestat() (在 os.path 模块中):        os path --- 常用路径操作.
                                                             (line  306)
* same_files (filecmp.dircmp 属性):      dircmp 类.          (line   77)
* same_quantum() (decimal.Context 方法): 上下文对象.         (line  428)
* same_quantum() (decimal.Decimal 方法): Decimal 对象.       (line  446)
* sample() (在 random 模块中):           序列用函数.         (line   55)
* samples() (statistics.NormalDist 方法): NormalDist 对象.   (line   49)
* save() (http.cookiejar.FileCookieJar 方法): CookieJar 和 FileCookieJar 对象.
                                                             (line  105)
* SAVEDCWD() (在 test.support 模块中):   test support --- Utilities for the Python test suite.
                                                             (line   87)
* SaveKey() (在 winreg 模块中):          函数<11>.           (line  378)
* SaveSignals (test.support 中的类):     test support --- Utilities for the Python test suite.
                                                             (line 1080)
* savetty() (在 curses 模块中):          函数<3>.            (line  353)
* SAX2DOM (xml.dom.pulldom 中的类):      xml dom pulldom --- 支持构建部分 DOM 树.
                                                             (line   73)
* SAXException:                          xml sax --- 支持 SAX2 解析器.
                                                             (line   72)
* SAXNotRecognizedException:             xml sax --- 支持 SAX2 解析器.
                                                             (line   93)
* SAXNotSupportedException:              xml sax --- 支持 SAX2 解析器.
                                                             (line   99)
* SAXParseException:                     xml sax --- 支持 SAX2 解析器.
                                                             (line   86)
* scaleb() (decimal.Context 方法):       上下文对象.         (line  432)
* scaleb() (decimal.Decimal 方法):       Decimal 对象.       (line  454)
* scandir() (在 os 模块中):              文件和目录.         (line  658)
* scanf():                               模拟 scanf.         (line    6)
* sched (模块):                          sched --- 事件调度器.
                                                             (line    6)
* scheduler (sched 中的类):              sched --- 事件调度器.
                                                             (line   12)
* SCHED_BATCH() (在 os 模块中):          调度器接口.         (line   17)
* SCHED_FIFO() (在 os 模块中):           调度器接口.         (line   30)
* sched_getaffinity() (在 os 模块中):    调度器接口.         (line   98)
* sched_getparam() (在 os 模块中):       调度器接口.         (line   79)
* sched_getscheduler() (在 os 模块中):   调度器接口.         (line   69)
* sched_get_priority_max() (在 os 模块中): 调度器接口.       (line   59)
* sched_get_priority_min() (在 os 模块中): 调度器接口.       (line   55)
* SCHED_IDLE() (在 os 模块中):           调度器接口.         (line   22)
* SCHED_OTHER() (在 os 模块中):          调度器接口.         (line   13)
* sched_param (os 中的类):               调度器接口.         (line   43)
* sched_priority (os.sched_param 属性):  调度器接口.         (line   51)
* SCHED_RESET_ON_FORK() (在 os 模块中):  调度器接口.         (line   38)
* SCHED_RR() (在 os 模块中):             调度器接口.         (line   34)
* sched_rr_get_interval() (在 os 模块中): 调度器接口.        (line   84)
* sched_setaffinity() (在 os 模块中):    调度器接口.         (line   93)
* sched_setparam() (在 os 模块中):       调度器接口.         (line   74)
* sched_setscheduler() (在 os 模块中):   调度器接口.         (line   63)
* SCHED_SPORADIC() (在 os 模块中):       调度器接口.         (line   26)
* sched_yield() (在 os 模块中):          调度器接口.         (line   89)
* schema() (在 msilib 模块中):           Precomputed tables. (line   10)
* scope:                                 命名与绑定.         (line    6)
* scope <1>:                             名称的解析.         (line    6)
* Screen (turtle 中的类):                公共类.             (line   28)
* screensize() (在 turtle 模块中):       窗口控制.           (line   55)
* script_from_examples() (在 doctest 模块中): 调试.          (line   72)
* scroll() (curses.window 方法):         Window 对象.        (line  423)
* ScrolledCanvas (turtle 中的类):        公共类.             (line   32)
* scrollok() (curses.window 方法):       Window 对象.        (line  427)
* scrypt() (在 hashlib 模块中):          密钥派生.           (line   39)
* seal() (在 unittest.mock 模块中):      Sealing mocks.      (line    6)
* search() (imaplib.IMAP4 方法):         IMAP4 Objects.      (line  216)
* search() (re.Pattern 方法):            正则表达式对象 （正则对象）.
                                                             (line    8)
* search() (在 re 模块中):               模块内容.           (line  112)
* second (datetime.datetime 属性):       datetime 对象.      (line  262)
* second (datetime.time 属性):           time 对象.          (line   54)
* seconds since the epoch:               time --- 时间的访问和转换.
                                                             (line   21)
* secrets (模块):                        secrets --- 生成安全随机数字用于管理密码.
                                                             (line    6)
* SECTCRE (configparser.ConfigParser 属性): 定制解析器行为.  (line  262)
* sections() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line   69)
* secure (http.cookiejar.Cookie 属性):   Cookie 对象<2>.     (line   45)
* secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512: hashlib --- 安全哈希与消息摘要.
                                                             (line    8)
* Secure Sockets Layer:                  ssl --- 套接字对象的TLS/SSL封装.
                                                             (line    8)
* see() (tkinter.ttk.Treeview 方法):     ttk Treeview.       (line  250)
* seed() (在 random 模块中):             簿记功能.           (line    6)
* seek() (chunk.Chunk 方法):             chunk --- 读取 IFF 分块数据.
                                                             (line   79)
* seek() (io.IOBase 方法):               I/O 基类.           (line   87)
* seek() (io.TextIOBase 方法):           文本 I/O<2>.        (line   59)
* seek() (mmap.mmap 方法):               mmap --- 内存映射文件支持.
                                                             (line  225)
* seekable() (io.IOBase 方法):           I/O 基类.           (line  108)
* SEEK_CUR() (在 os 模块中):             文件描述符操作.     (line  223)
* SEEK_END() (在 os 模块中):             文件描述符操作.     (line  223)
* SEEK_SET() (在 os 模块中):             文件描述符操作.     (line  223)
* seen_greeting (smtpd.SMTPChannel 属性): SMTPChannel 对象.  (line   68)
* Select (tkinter.tix 中的类):           Basic Widgets.      (line   58)
* select (模块):                         select --- 等待 I/O 完成.
                                                             (line    6)
* select() (imaplib.IMAP4 方法):         IMAP4 Objects.      (line  233)
* select() (selectors.BaseSelector 方法): 类<3>.             (line   97)
* select() (tkinter.ttk.Notebook 方法):  ttk Notebook.       (line   53)
* select() (在 select 模块中):           select --- 等待 I/O 完成.
                                                             (line   93)
* selected_alpn_protocol() (ssl.SSLSocket 方法): SSL 套接字. (line  219)
* selected_npn_protocol() (ssl.SSLSocket 方法): SSL 套接字.  (line  228)
* selection() (tkinter.ttk.Treeview 方法): ttk Treeview.     (line  258)
* selection_add() (tkinter.ttk.Treeview 方法): ttk Treeview. (line  273)
* selection_remove() (tkinter.ttk.Treeview 方法): ttk Treeview.
                                                             (line  280)
* selection_set() (tkinter.ttk.Treeview 方法): ttk Treeview. (line  266)
* selection_toggle() (tkinter.ttk.Treeview 方法): ttk Treeview.
                                                             (line  287)
* selector (urllib.request.Request 属性): Request 对象.      (line   31)
* SelectorEventLoop (asyncio 中的类):    事件循环实现.       (line   12)
* SelectorKey (selectors 中的类):        类<3>.              (line   28)
* selectors (模块):                      selectors --- 高级 I/O 复用库.
                                                             (line    6)
* SelectSelector (selectors 中的类):     类<3>.              (line  145)
* Semaphore (asyncio 中的类):            Semaphore.          (line    6)
* Semaphore (multiprocessing 中的类):    同步原语.           (line  131)
* Semaphore (threading 中的类):          信号量对象.         (line   17)
* Semaphore() (multiprocessing.managers.SyncManager 方法): 管理器.
                                                             (line  166)
* semaphores, binary:                    _thread --- 底层多线程 API.
                                                             (line    6)
* SEMI() (在 token 模块中):              token --- 与Python解析树一起使用的常量.
                                                             (line   74)
* send() (asyncore.dispatcher 方法):     asyncore --- 异步socket处理器.
                                                             (line  162)
* send() (coroutine 方法):               协程对象.           (line   17)
* send() (generator 方法):               生成器-迭代器的方法.
                                                             (line   23)
* send() (http.client.HTTPConnection 方法): HTTPConnection 对象.
                                                             (line  150)
* send() (imaplib.IMAP4 方法):           IMAP4 Objects.      (line  240)
* send() (logging.handlers.DatagramHandler 方法): DatagramHandler.
                                                             (line   29)
* send() (logging.handlers.SocketHandler 方法): SocketHandler.
                                                             (line   52)
* send() (multiprocessing.connection.Connection 方法): 连接对象（Connection）<2>.
                                                             (line   14)
* send() (socket.socket 方法):           套接字对象.         (line  319)
* sendall() (socket.socket 方法):        套接字对象.         (line  331)
* sendcmd() (ftplib.FTP 方法):           FTP 对象.           (line   53)
* sendfile() (asyncio.loop 方法):        传输文件.           (line    6)
* sendfile() (socket.socket 方法):       套接字对象.         (line  407)
* sendfile() (wsgiref.handlers.BaseHandler 方法): wsgiref handlers -- server/gateway base classes.
                                                             (line  274)
* sendfile() (在 os 模块中):             文件描述符操作.     (line  515)
* SendfileNotAvailableError:             异常<9>.            (line   32)
* sendmail() (smtplib.SMTP 方法):        SMTP Objects.       (line  219)
* sendmsg() (socket.socket 方法):        套接字对象.         (line  362)
* sendmsg_afalg() (socket.socket 方法):  套接字对象.         (line  397)
* sendto() (asyncio.DatagramTransport 方法): 数据报传输.     (line    6)
* sendto() (socket.socket 方法):         套接字对象.         (line  346)
* send_bytes() (multiprocessing.connection.Connection 方法): 连接对象（Connection）<2>.
                                                             (line   49)
* send_error() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  196)
* send_flowing_data() (formatter.writer 方法): The Writer Interface.
                                                             (line   76)
* send_header() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  231)
* send_hor_rule() (formatter.writer 方法): The Writer Interface.
                                                             (line   68)
* send_label_data() (formatter.writer 方法): The Writer Interface.
                                                             (line   92)
* send_line_break() (formatter.writer 方法): The Writer Interface.
                                                             (line   54)
* send_literal_data() (formatter.writer 方法): The Writer Interface.
                                                             (line   83)
* send_message() (smtplib.SMTP 方法):    SMTP Objects.       (line  294)
* send_paragraph() (formatter.writer 方法): The Writer Interface.
                                                             (line   58)
* send_response() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  216)
* send_response_only() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  243)
* send_signal() (asyncio.asyncio.subprocess.Process 方法): 与子进程交互.
                                                             (line   72)
* send_signal() (asyncio.SubprocessTransport 方法): 子进程传输.
                                                             (line   40)
* send_signal() (subprocess.Popen 方法): Popen 对象.         (line   63)
* sentinel (multiprocessing.Process 属性): Process 和异常.   (line  112)
* sentinel() (在 unittest.mock 模块中):  sentinel.           (line    6)
* sep() (在 os 模块中):                  其他系统信息.       (line   77)
* Sequence (collections.abc 中的类):     容器抽象基类.       (line  155)
* Sequence (typing 中的类):              类 函数和修饰器.    (line  215)
* sequence – 序列:                       术语对照表.         (line  943)
* sequence() (在 msilib 模块中):         Precomputed tables. (line   16)
* sequence2st() (在 parser 模块中):      创建 ST 对象.       (line   26)
* sequence; item:                        抽取.               (line    6)
* sequence; iteration:                   迭代器类型.         (line    6)
* SequenceMatcher (difflib 中的类):      SequenceMatcher 对象.
                                                             (line    8)
* serializing; objects:                  pickle --- Python 对象序列化.
                                                             (line    8)
* Server (asyncio 中的类):               Server 对象.        (line   12)
* server (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line   61)
* ServerProxy (xmlrpc.client 中的类):    xmlrpc client --- XML-RPC 客户端访问.
                                                             (line   22)
* server_activate() (socketserver.BaseServer 方法): Server 对象<2>.
                                                             (line  164)
* server_address (socketserver.BaseServer 属性): Server 对象<2>.
                                                             (line   76)
* server_bind() (socketserver.BaseServer 方法): Server 对象<2>.
                                                             (line  170)
* server_close() (socketserver.BaseServer 方法): Server 对象<2>.
                                                             (line   61)
* server_hostname (ssl.SSLSocket 属性):  SSL 套接字.         (line  290)
* server_side (ssl.SSLSocket 属性):      SSL 套接字.         (line  283)
* server_software (wsgiref.handlers.BaseHandler 属性): wsgiref handlers -- server/gateway base classes.
                                                             (line  175)
* server_version (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line  117)
* server_version (http.server.SimpleHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line  331)
* serve_forever() (asyncio.Server 方法): Server 对象.        (line   58)
* serve_forever() (socketserver.BaseServer 方法): Server 对象<2>.
                                                             (line   32)
* service_actions() (socketserver.BaseServer 方法): Server 对象<2>.
                                                             (line   45)
* session (ssl.SSLSocket 属性):          SSL 套接字.         (line  301)
* session_reused (ssl.SSLSocket 属性):   SSL 套接字.         (line  309)
* session_stats() (ssl.SSLContext 方法): SSL 上下文.         (line  416)
* Set (collections.abc 中的类):          容器抽象基类.       (line  170)
* Set (typing 中的类):                   类 函数和修饰器.    (line  255)
* set (內置类):                          集合类型 --- set frozenset.
                                                             (line   28)
* Set Breakpoint:                        帮助菜单（命令行和编辑器）.
                                                             (line   26)
* set comprehension – 集合推导式:        术语对照表.         (line  959)
* set() (asyncio.Event 方法):            Event.              (line   50)
* set() (configparser.ConfigParser 方法): ConfigParser 对象. (line  219)
* set() (configparser.RawConfigParser 方法): RawConfigParser 对象.
                                                             (line   32)
* set() (contextvars.ContextVar 方法):   上下文变量.         (line   40)
* set() (http.cookies.Morsel 方法):      Morsel 对象.        (line   64)
* set() (ossaudiodev.oss_mixer_device 方法): Mixer Device Objects.
                                                             (line   72)
* set() (test.support.EnvironmentVarGuard 方法): test support --- Utilities for the Python test suite.
                                                             (line 1035)
* set() (threading.Event 方法):          事件对象.           (line   26)
* set() (tkinter.ttk.Combobox 方法):     ttk Combobox.       (line   19)
* set() (tkinter.ttk.Spinbox 方法):      ttk Spinbox.        (line   12)
* set() (tkinter.ttk.Treeview 方法):     ttk Treeview.       (line  294)
* set() (xml.etree.ElementTree.Element 方法): 元素对象.      (line   68)
* set; comprehensions:                   集合显示.           (line    6)
* set; display:                          集合显示.           (line    6)
* setacl() (imaplib.IMAP4 方法):         IMAP4 Objects.      (line  247)
* setannotation() (imaplib.IMAP4 方法):  IMAP4 Objects.      (line  252)
* setattr() (內置函数):                  内置函数.           (line 1247)
* setattrfunc (C 类型):                  Slot Type typedefs. (line   57)
* setAttribute() (xml.dom.Element 方法): 元素对象<2>.        (line   63)
* setAttributeNode() (xml.dom.Element 方法): 元素对象<2>.    (line   67)
* setAttributeNodeNS() (xml.dom.Element 方法): 元素对象<2>.  (line   73)
* setAttributeNS() (xml.dom.Element 方法): 元素对象<2>.      (line   80)
* setattrofunc (C 类型):                 Slot Type typedefs. (line   69)
* SetBase() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line   19)
* setblocking() (socket.socket 方法):    套接字对象.         (line  426)
* setByteStream() (xml.sax.xmlreader.InputSource 方法): InputSource 对象.
                                                             (line   36)
* setcbreak() (在 tty 模块中):           tty --- 终端控制功能.
                                                             (line   21)
* setCharacterStream() (xml.sax.xmlreader.InputSource 方法): InputSource 对象.
                                                             (line   53)
* setcheckinterval() (在 sys 模块中):    sys --- 系统相关的参数和函数.
                                                             (line 1016)
* setcomptype() (aifc.aifc 方法):        aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  138)
* setcomptype() (sunau.AU_write 方法):   AU_write 对象.      (line   28)
* setcomptype() (wave.Wave_write 方法):  Wave_write 对象.    (line   43)
* setContentHandler() (xml.sax.xmlreader.XMLReader 方法): XMLReader 对象.
                                                             (line   24)
* setcontext() (在 decimal 模块中):      上下文对象.         (line   16)
* setDaemon() (threading.Thread 方法):   线程对象.           (line  164)
* setdefault() (dict 方法):              映射类型 --- dict.  (line  181)
* setdefault() (http.cookies.Morsel 方法): Morsel 对象.      (line  108)
* setdefaulttimeout() (在 socket 模块中): 其他功能<2>.       (line  275)
* setdlopenflags() (在 sys 模块中):      sys --- 系统相关的参数和函数.
                                                             (line 1031)
* setDocumentLocator() (xml.sax.handler.ContentHandler 方法): ContentHandler 对象.
                                                             (line    9)
* setDTDHandler() (xml.sax.xmlreader.XMLReader 方法): XMLReader 对象.
                                                             (line   33)
* setegid() (在 os 模块中):              进程参数.           (line  306)
* setEncoding() (xml.sax.xmlreader.InputSource 方法): InputSource 对象.
                                                             (line   22)
* setEntityResolver() (xml.sax.xmlreader.XMLReader 方法): XMLReader 对象.
                                                             (line   42)
* setErrorHandler() (xml.sax.xmlreader.XMLReader 方法): XMLReader 对象.
                                                             (line   52)
* seteuid() (在 os 模块中):              进程参数.           (line  312)
* setFeature() (xml.sax.xmlreader.XMLReader 方法): XMLReader 对象.
                                                             (line   71)
* setfirstweekday() (在 calendar 模块中): calendar --- 日历相关函数.
                                                             (line  248)
* setfmt() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line  122)
* setFormatter() (logging.Handler 方法): 处理器对象.         (line   42)
* setframerate() (aifc.aifc 方法):       aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  129)
* setframerate() (sunau.AU_write 方法):  AU_write 对象.      (line   19)
* setframerate() (wave.Wave_write 方法): Wave_write 对象.    (line   32)
* setgid() (在 os 模块中):               进程参数.           (line  318)
* setgroups() (在 os 模块中):            进程参数.           (line  324)
* seth() (在 turtle 模块中):             海龟动作.           (line  126)
* setheading() (在 turtle 模块中):       海龟动作.           (line  126)
* sethostname() (在 socket 模块中):      其他功能<2>.        (line  281)
* SetInteger() (msilib.Record 方法):     Record Objects.     (line   32)
* setitem() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line  186)
* setitimer() (在 signal 模块中):        模块内容<5>.        (line  321)
* setLevel() (logging.Handler 方法):     处理器对象.         (line   31)
* setLevel() (logging.Logger 方法):      记录器对象.         (line   39)
* setLocale() (xml.sax.xmlreader.XMLReader 方法): XMLReader 对象.
                                                             (line   57)
* setlocale() (在 locale 模块中):        locale --- 国际化服务.
                                                             (line   27)
* setLoggerClass() (在 logging 模块中):  模块级别函数.       (line  281)
* setlogmask() (在 syslog 模块中):       Unix syslog 库例程. (line   63)
* setLogRecordFactory() (在 logging 模块中): 模块级别函数.   (line  291)
* setmark() (aifc.aifc 方法):            aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  152)
* setMaxConns() (urllib.request.CacheFTPHandler 方法): CacheFTPHandler 对象.
                                                             (line   13)
* setmode() (在 msvcrt 模块中):          文件操作.           (line   34)
* setName() (threading.Thread 方法):     线程对象.           (line  118)
* setnchannels() (aifc.aifc 方法):       aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  121)
* setnchannels() (sunau.AU_write 方法):  AU_write 对象.      (line    9)
* setnchannels() (wave.Wave_write 方法): Wave_write 对象.    (line   24)
* setnframes() (aifc.aifc 方法):         aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  133)
* setnframes() (sunau.AU_write 方法):    AU_write 对象.      (line   23)
* setnframes() (wave.Wave_write 方法):   Wave_write 对象.    (line   38)
* SetParamEntityParsing() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line   44)
* setparameters() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line  185)
* setparams() (aifc.aifc 方法):          aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  145)
* setparams() (sunau.AU_write 方法):     AU_write 对象.      (line   33)
* setparams() (wave.Wave_write 方法):    Wave_write 对象.    (line   47)
* setpassword() (zipfile.ZipFile 方法):  ZipFile 对象.       (line  184)
* setpgid() (在 os 模块中):              进程参数.           (line  343)
* setpgrp() (在 os 模块中):              进程参数.           (line  336)
* setpos() (aifc.aifc 方法):             aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   93)
* setpos() (sunau.AU_read 方法):         AU_read 对象.       (line   59)
* setpos() (wave.Wave_read 方法):        Wave_read对象.      (line   64)
* setpos() (在 turtle 模块中):           海龟动作.           (line   71)
* setposition() (在 turtle 模块中):      海龟动作.           (line   71)
* setpriority() (在 os 模块中):          进程参数.           (line  350)
* setprofile() (在 sys 模块中):          sys --- 系统相关的参数和函数.
                                                             (line 1042)
* setprofile() (在 threading 模块中):    threading --- 基于线程的并行.
                                                             (line  112)
* SetProperty() (msilib.SummaryInformation 方法): Summary Information Objects.
                                                             (line   22)
* setProperty() (xml.sax.xmlreader.XMLReader 方法): XMLReader 对象.
                                                             (line   83)
* setPublicId() (xml.sax.xmlreader.InputSource 方法): InputSource 对象.
                                                             (line    6)
* setquota() (imaplib.IMAP4 方法):       IMAP4 Objects.      (line  257)
* setraw() (在 tty 模块中):              tty --- 终端控制功能.
                                                             (line   16)
* setrecursionlimit() (在 sys 模块中):   sys --- 系统相关的参数和函数.
                                                             (line 1087)
* setregid() (在 os 模块中):             进程参数.           (line  364)
* setresgid() (在 os 模块中):            进程参数.           (line  370)
* setresuid() (在 os 模块中):            进程参数.           (line  378)
* setreuid() (在 os 模块中):             进程参数.           (line  386)
* setrlimit() (在 resource 模块中):      Resource Limits.    (line   31)
* setsampwidth() (aifc.aifc 方法):       aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  125)
* setsampwidth() (sunau.AU_write 方法):  AU_write 对象.      (line   13)
* setsampwidth() (wave.Wave_write 方法): Wave_write 对象.    (line   28)
* setscrreg() (curses.window 方法):      Window 对象.        (line  435)
* setsid() (在 os 模块中):               进程参数.           (line  398)
* setsockopt() (socket.socket 方法):     套接字对象.         (line  453)
* setstate() (codecs.IncrementalDecoder 方法): IncrementalDecoder 对象.
                                                             (line   48)
* setstate() (codecs.IncrementalEncoder 方法): IncrementalEncoder 对象.
                                                             (line   42)
* setstate() (在 random 模块中):         簿记功能.           (line   29)
* setStream() (logging.StreamHandler 方法): StreamHandler.   (line   29)
* SetStream() (msilib.Record 方法):      Record Objects.     (line   26)
* SetString() (msilib.Record 方法):      Record Objects.     (line   21)
* setswitchinterval() (in module sys):   Thread State and the Global Interpreter Lock.
                                                             (line   15)
* setswitchinterval() (在 sys 模块中):   sys --- 系统相关的参数和函数.
                                                             (line 1102)
* setswitchinterval() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  281)
* setSystemId() (xml.sax.xmlreader.InputSource 方法): InputSource 对象.
                                                             (line   14)
* setsyx() (在 curses 模块中):           函数<3>.            (line  358)
* setTarget() (logging.handlers.MemoryHandler 方法): MemoryHandler.
                                                             (line   58)
* settiltangle() (在 turtle 模块中):     外观.               (line  108)
* settimeout() (socket.socket 方法):     套接字对象.         (line  440)
* setTimeout() (urllib.request.CacheFTPHandler 方法): CacheFTPHandler 对象.
                                                             (line    9)
* settrace() (在 sys 模块中):            sys --- 系统相关的参数和函数.
                                                             (line 1111)
* settrace() (在 threading 模块中):      threading --- 基于线程的并行.
                                                             (line  106)
* setuid() (在 os 模块中):               进程参数.           (line  404)
* setundobuffer() (在 turtle 模块中):    特殊海龟方法.       (line   57)
* setup() (socketserver.BaseRequestHandler 方法): Request Handler Objects.
                                                             (line   14)
* setUp() (unittest.TestCase 方法):      测试用例.           (line   33)
* setup() (在 distutils.core 模块中):    distutils core --- 分发包功能的核心.
                                                             (line   10)
* setup() (在 turtle 模块中):            Screen 专有方法 而非继承自 TurtleScreen.
                                                             (line   19)
* setUpClass() (unittest.TestCase 方法): 测试用例.           (line   55)
* setupterm() (在 curses 模块中):        函数<3>.            (line  363)
* SETUP_ANNOTATIONS (opcode):            Python字节码说明.   (line  337)
* SETUP_ASYNC_WITH (opcode):             Python字节码说明.   (line  290)
* setup_environ() (wsgiref.handlers.BaseHandler 方法): wsgiref handlers -- server/gateway base classes.
                                                             (line  195)
* SETUP_FINALLY (opcode):                Python字节码说明.   (line  636)
* setup_python() (venv.EnvBuilder 方法): API<2>.             (line   82)
* setup_scripts() (venv.EnvBuilder 方法): API<2>.            (line   88)
* setup_testing_defaults() (在 wsgiref.util 模块中): wsgiref util -- WSGI environment utilities.
                                                             (line   68)
* SETUP_WITH (opcode):                   Python字节码说明.   (line  406)
* SetValue() (在 winreg 模块中):         函数<11>.           (line  402)
* SetValueEx() (在 winreg 模块中):       函数<11>.           (line  433)
* setworldcoordinates() (在 turtle 模块中): 窗口控制.        (line   79)
* setx() (在 turtle 模块中):             海龟动作.           (line  100)
* setxattr() (在 os 模块中):             Linux 扩展属性.     (line   53)
* sety() (在 turtle 模块中):             海龟动作.           (line  113)
* SET_ADD (opcode):                      Python字节码说明.   (line  303)
* set_all():                             引用计数细节.       (line   98)
* set_allowed_domains() (http.cookiejar.DefaultCookiePolicy 方法): DefaultCookiePolicy 对象.
                                                             (line   70)
* set_alpn_protocols() (ssl.SSLContext 方法): SSL 上下文.    (line  225)
* set_app() (wsgiref.simple_server.WSGIServer 方法): wsgiref simple_server -- a simple WSGI HTTP server.
                                                             (line   61)
* set_asyncgen_hooks() (在 sys 模块中):  sys --- 系统相关的参数和函数.
                                                             (line 1189)
* set_authorizer() (sqlite3.Connection 方法): 连接对象（Connection）.
                                                             (line  179)
* set_auto_history() (在 readline 模块中): 历史列表.         (line   38)
* set_blocked_domains() (http.cookiejar.DefaultCookiePolicy 方法): DefaultCookiePolicy 对象.
                                                             (line   56)
* set_blocking() (在 os 模块中):         文件描述符操作.     (line  547)
* set_boundary() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  342)
* set_boundary() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  490)
* set_break() (bdb.Bdb 方法):            bdb --- Debugger framework.
                                                             (line  280)
* set_charset() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  195)
* set_children() (tkinter.ttk.Treeview 方法): ttk Treeview.  (line   25)
* set_child_watcher() (asyncio.AbstractEventLoopPolicy 方法): 策略对象.
                                                             (line   42)
* set_child_watcher() (在 asyncio 模块中): 进程监视器.       (line   25)
* set_ciphers() (ssl.SSLContext 方法):   SSL 上下文.         (line  213)
* set_completer() (在 readline 模块中):  Completion.         (line   12)
* set_completer_delims() (在 readline 模块中): Completion.   (line   40)
* set_completion_display_matches_hook() (在 readline 模块中): Completion.
                                                             (line   47)
* set_content() (email.contentmanager.ContentManager 方法): email contentmanager 管理 MIME 内容.
                                                             (line   34)
* set_content() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  498)
* set_content() (在 email.contentmanager 模块中): 内容管理器实例.
                                                             (line   29)
* set_continue() (bdb.Bdb 方法):         bdb --- Debugger framework.
                                                             (line  265)
* set_cookie() (http.cookiejar.CookieJar 方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   72)
* set_cookie_if_ok() (http.cookiejar.CookieJar 方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   68)
* set_coroutine_origin_tracking_depth() (在 sys 模块中): sys --- 系统相关的参数和函数.
                                                             (line 1210)
* set_current() (msilib.Feature 方法):   相关特性<3>.        (line   14)
* set_data() (importlib.abc.SourceLoader 方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  492)
* set_data() (importlib.machinery.SourceFileLoader 方法): importlib machinery -- Importers and path hooks.
                                                             (line  235)
* set_date() (mailbox.MaildirMessage 方法): MaildirMessage.  (line   86)
* set_debug() (asyncio.loop 方法):       开启调试模式.       (line   13)
* set_debug() (在 gc 模块中):            gc --- 垃圾回收器接口.
                                                             (line   41)
* set_debuglevel() (ftplib.FTP 方法):    FTP 对象.           (line   12)
* set_debuglevel() (http.client.HTTPConnection 方法): HTTPConnection 对象.
                                                             (line   59)
* set_debuglevel() (nntplib.NNTP 方法):  方法<3>.            (line  306)
* set_debuglevel() (poplib.POP3 方法):   POP3 对象.          (line   11)
* set_debuglevel() (smtplib.SMTP 方法):  SMTP Objects.       (line    8)
* set_debuglevel() (telnetlib.Telnet 方法): Telnet 对象.     (line   76)
* set_defaults() (argparse.ArgumentParser 方法): 解析器默认值.
                                                             (line    6)
* set_defaults() (optparse.OptionParser 方法): Other methods.
                                                             (line   27)
* set_default_executor() (asyncio.loop 方法): 在线程或者进程池中执行代码。.
                                                             (line   64)
* set_default_type() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  284)
* set_default_type() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  378)
* set_default_verify_paths() (ssl.SSLContext 方法): SSL 上下文.
                                                             (line  206)
* set_ecdh_curve() (ssl.SSLContext 方法): SSL 上下文.        (line  320)
* set_errno() (在 ctypes 模块中):        工具函数.           (line  149)
* set_event_loop() (asyncio.AbstractEventLoopPolicy 方法): 策略对象.
                                                             (line   23)
* set_event_loop() (在 asyncio 模块中):  事件循环.           (line   49)
* set_event_loop_policy() (在 asyncio 模块中): 获取和设置策略.
                                                             (line   12)
* set_exception() (asyncio.Future 方法): Future 对象<2>.     (line   45)
* set_exception() (concurrent.futures.Future 方法): Future 对象.
                                                             (line  103)
* set_exception_handler() (asyncio.loop 方法): 错误处理API.  (line    8)
* set_executable() (在 multiprocessing 模块中): 杂项<3>.     (line  101)
* set_executables() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  233)
* set_flags() (mailbox.MaildirMessage 方法): MaildirMessage. (line   66)
* set_flags() (mailbox.mboxMessage 方法): mboxMessage.       (line   62)
* set_flags() (mailbox.MMDFMessage 方法): MMDFMessage.       (line   61)
* set_from() (mailbox.mboxMessage 方法): mboxMessage.        (line   48)
* set_from() (mailbox.MMDFMessage 方法): MMDFMessage.        (line   47)
* set_handle_inheritable() (在 os 模块中): 文件描述符的继承. (line   35)
* set_history_length() (在 readline 模块中): 历史文件.       (line   27)
* set_include_dirs() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  101)
* set_info() (mailbox.MaildirMessage 方法): MaildirMessage.  (line   95)
* set_inheritable() (socket.socket 方法): 套接字对象.        (line  420)
* set_inheritable() (在 os 模块中):      文件描述符的继承.   (line   25)
* set_labels() (mailbox.BabylMessage 方法): BabylMessage.    (line   48)
* set_last_error() (在 ctypes 模块中):   工具函数.           (line  156)
* set_libraries() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  126)
* set_library_dirs() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  142)
* set_link_objects() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  185)
* set_literal (2to3 fixer):              修复器.             (line  275)
* set_loader() (在 importlib.util 模块中): importlib util -- Utility code for importers.
                                                             (line  168)
* set_match_tests() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  250)
* set_memlimit() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  370)
* set_name() (asyncio.Task 方法):        Task 对象.          (line  195)
* set_next() (bdb.Bdb 方法):             bdb --- Debugger framework.
                                                             (line  247)
* set_nonstandard_attr() (http.cookiejar.Cookie 方法): Cookie 对象<2>.
                                                             (line  103)
* set_npn_protocols() (ssl.SSLContext 方法): SSL 上下文.     (line  242)
* set_ok() (http.cookiejar.CookiePolicy 方法): CookiePolicy 对象.
                                                             (line    9)
* set_option_negotiation_callback() (telnetlib.Telnet 方法): Telnet 对象.
                                                             (line  129)
* set_output_charset() (gettext.NullTranslations 方法): NullTranslations 类.
                                                             (line   82)
* set_package() (在 importlib.util 模块中): importlib util -- Utility code for importers.
                                                             (line  183)
* set_param() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  292)
* set_param() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  431)
* set_pasv() (ftplib.FTP 方法):          FTP 对象.           (line   89)
* set_payload() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  186)
* set_policy() (http.cookiejar.CookieJar 方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   56)
* set_position() (xdrlib.Unpacker 方法): Unpacker 对象.      (line   16)
* set_pre_input_hook() (在 readline 模块中): 启动钩子.       (line   13)
* set_progress_handler() (sqlite3.Connection 方法): 连接对象（Connection）.
                                                             (line  197)
* set_protocol() (asyncio.BaseTransport 方法): 基础传输.     (line   73)
* set_proxy() (urllib.request.Request 方法): Request 对象.   (line  101)
* set_python_build() (在 distutils.sysconfig 模块中): distutils sysconfig --- System configuration information.
                                                             (line   98)
* set_quit() (bdb.Bdb 方法):             bdb --- Debugger framework.
                                                             (line  270)
* set_recsrc() (ossaudiodev.oss_mixer_device 方法): Mixer Device Objects.
                                                             (line   89)
* set_result() (asyncio.Future 方法):    Future 对象<2>.     (line   38)
* set_result() (concurrent.futures.Future 方法): Future 对象.
                                                             (line   93)
* set_return() (bdb.Bdb 方法):           bdb --- Debugger framework.
                                                             (line  251)
* set_running_or_notify_cancel() (concurrent.futures.Future 方法): Future 对象.
                                                             (line   74)
* set_runtime_library_dirs() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  153)
* set_seq1() (difflib.SequenceMatcher 方法): SequenceMatcher 对象.
                                                             (line   46)
* set_seq2() (difflib.SequenceMatcher 方法): SequenceMatcher 对象.
                                                             (line   50)
* set_seqs() (difflib.SequenceMatcher 方法): SequenceMatcher 对象.
                                                             (line   37)
* set_sequences() (mailbox.MH 方法):     MH.                 (line   52)
* set_sequences() (mailbox.MHMessage 方法): MHMessage.       (line   34)
* set_servername_callback (ssl.SSLContext 属性): SSL 上下文. (line  296)
* set_server_documentation() (xmlrpc.server.DocCGIXMLRPCRequestHandler 方法): DocCGIXMLRPCRequestHandler.
                                                             (line   24)
* set_server_documentation() (xmlrpc.server.DocXMLRPCServer 方法): DocXMLRPCServer Objects.
                                                             (line   24)
* set_server_name() (xmlrpc.server.DocCGIXMLRPCRequestHandler 方法): DocCGIXMLRPCRequestHandler.
                                                             (line   18)
* set_server_name() (xmlrpc.server.DocXMLRPCServer 方法): DocXMLRPCServer Objects.
                                                             (line   18)
* set_server_title() (xmlrpc.server.DocCGIXMLRPCRequestHandler 方法): DocCGIXMLRPCRequestHandler.
                                                             (line   13)
* set_server_title() (xmlrpc.server.DocXMLRPCServer 方法): DocXMLRPCServer Objects.
                                                             (line   13)
* set_spacing() (formatter.formatter 方法): The Formatter Interface.
                                                             (line  139)
* set_startup_hook() (在 readline 模块中): 启动钩子.         (line    6)
* set_start_method() (在 multiprocessing 模块中): 杂项<3>.   (line  113)
* set_step() (bdb.Bdb 方法):             bdb --- Debugger framework.
                                                             (line  243)
* set_subdir() (mailbox.MaildirMessage 方法): MaildirMessage.
                                                             (line   54)
* set_task_factory() (asyncio.loop 方法): 创建 Futures 和 Tasks.
                                                             (line   27)
* set_terminator() (asynchat.async_chat 方法): asynchat --- 异步 socket 指令/响应 处理器.
                                                             (line   99)
* set_threshold() (在 gc 模块中):        gc --- 垃圾回收器接口.
                                                             (line   76)
* set_trace() (bdb.Bdb 方法):            bdb --- Debugger framework.
                                                             (line  260)
* set_trace() (pdb.Pdb 方法):            pdb --- Python的调试器.
                                                             (line  156)
* set_trace() (在 bdb 模块中):           bdb --- Debugger framework.
                                                             (line  402)
* set_trace() (在 pdb 模块中):           pdb --- Python的调试器.
                                                             (line  102)
* set_trace_callback() (sqlite3.Connection 方法): 连接对象（Connection）.
                                                             (line  209)
* set_tunnel() (http.client.HTTPConnection 方法): HTTPConnection 对象.
                                                             (line   67)
* set_type() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  459)
* set_unittest_reportflags() (在 doctest 模块中): Unittest API.
                                                             (line  165)
* set_unixfrom() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  116)
* set_unixfrom() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  129)
* set_until() (bdb.Bdb 方法):            bdb --- Debugger framework.
                                                             (line  255)
* set_url() (urllib.robotparser.RobotFileParser 方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   20)
* set_usage() (optparse.OptionParser 方法): Other methods.   (line    8)
* set_userptr() (curses.panel.Panel 方法): Panel 对象.       (line   40)
* set_visible() (mailbox.BabylMessage 方法): BabylMessage.   (line   65)
* set_wakeup_fd() (在 signal 模块中):    模块内容<5>.        (line  347)
* set_write_buffer_limits() (asyncio.WriteTransport 方法): 只写传输.
                                                             (line   30)
* SF_APPEND() (在 stat 模块中):          stat --- 解析 stat 结果.
                                                             (line  349)
* SF_ARCHIVED() (在 stat 模块中):        stat --- 解析 stat 结果.
                                                             (line  341)
* SF_IMMUTABLE() (在 stat 模块中):       stat --- 解析 stat 结果.
                                                             (line  345)
* SF_MNOWAIT() (在 os 模块中):           文件描述符操作.     (line  559)
* SF_NODISKIO() (在 os 模块中):          文件描述符操作.     (line  559)
* SF_NOUNLINK() (在 stat 模块中):        stat --- 解析 stat 结果.
                                                             (line  353)
* SF_SNAPSHOT() (在 stat 模块中):        stat --- 解析 stat 结果.
                                                             (line  357)
* SF_SYNC() (在 os 模块中):              文件描述符操作.     (line  559)
* shape (memoryview 属性):               内存视图.           (line  414)
* Shape (turtle 中的类):                 公共类.             (line   41)
* shape() (在 turtle 模块中):            外观.               (line    6)
* shapesize() (在 turtle 模块中):        外观.               (line   47)
* shapetransform() (在 turtle 模块中):   外观.               (line  143)
* share() (socket.socket 方法):          套接字对象.         (line  478)
* ShareableList (multiprocessing.shared_memory 中的类): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  209)
* ShareableList() (multiprocessing.managers.SharedMemoryManager 方法): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  173)
* Shared Memory:                         multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   10)
* SharedMemory (multiprocessing.shared_memory 中的类): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   24)
* SharedMemory() (multiprocessing.managers.SharedMemoryManager 方法): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  168)
* SharedMemoryManager (multiprocessing.managers 中的类): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  147)
* shared_ciphers() (ssl.SSLSocket 方法): SSL 套接字.         (line  188)
* shared_object_filename() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  471)
* shearfactor() (在 turtle 模块中):      外观.               (line   76)
* Shelf (shelve 中的类):                 限制.               (line   18)
* shelve (模块):                         shelve --- Python 对象持久化.
                                                             (line    6)
* shield() (在 asyncio 模块中):          屏蔽取消操作.       (line    6)
* shift() (decimal.Context 方法):        上下文对象.         (line  436)
* shift() (decimal.Decimal 方法):        Decimal 对象.       (line  460)
* shifting; operation:                   移位运算.           (line    6)
* shifting; operations:                  整数类型的按位运算. (line    6)
* shift_path_info() (在 wsgiref.util 模块中): wsgiref util -- WSGI environment utilities.
                                                             (line   38)
* shlex (shlex 中的类):                  shlex --- Simple lexical analysis.
                                                             (line   82)
* shlex (模块):                          shlex --- Simple lexical analysis.
                                                             (line    6)
* shm (multiprocessing.shared_memory.ShareableList 属性): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  240)
* shortDescription() (unittest.TestCase 方法): 测试用例.     (line  726)
* shorten() (在 textwrap 模块中):        textwrap --- 文本自动换行与填充.
                                                             (line   36)
* shouldFlush() (logging.handlers.BufferingHandler 方法): MemoryHandler.
                                                             (line   30)
* shouldFlush() (logging.handlers.MemoryHandler 方法): MemoryHandler.
                                                             (line   62)
* shouldStop (unittest.TestResult 属性): Loading and running tests.
                                                             (line  267)
* show() (curses.panel.Panel 方法):      Panel 对象.         (line   45)
* showsyntaxerror() (code.InteractiveInterpreter 方法): 交互解释器对象.
                                                             (line   38)
* showtraceback() (code.InteractiveInterpreter 方法): 交互解释器对象.
                                                             (line   45)
* showturtle() (在 turtle 模块中):       可见性.             (line   14)
* showwarning() (在 warnings 模块中):    Available Functions.
                                                             (line   55)
* show_code() (在 dis 模块中):           分析函数.           (line   21)
* show_compilers() (在 distutils.ccompiler 模块中): distutils ccompiler --- CCompiler基类.
                                                             (line   61)
* shuffle() (在 random 模块中):          序列用函数.         (line   39)
* shutdown() (concurrent.futures.Executor 方法): Executor 对象.
                                                             (line   48)
* shutdown() (imaplib.IMAP4 方法):       IMAP4 Objects.      (line  262)
* shutdown() (multiprocessing.managers.BaseManager 方法): 管理器.
                                                             (line   59)
* shutdown() (socket.socket 方法):       套接字对象.         (line  472)
* shutdown() (socketserver.BaseServer 方法): Server 对象<2>. (line   54)
* shutdown() (在 logging 模块中):        模块级别函数.       (line  273)
* shutdown_asyncgens() (asyncio.loop 方法): 运行和停止循环.  (line   51)
* shutil (模块):                         shutil --- 高阶文件操作.
                                                             (line    6)
* side_effect (unittest.mock.Mock 属性): Mock 类.            (line  327)
* SIGABRT() (在 signal 模块中):          模块内容<5>.        (line   25)
* SIGALRM() (在 signal 模块中):          模块内容<5>.        (line   29)
* SIGBREAK() (在 signal 模块中):         模块内容<5>.        (line   35)
* SIGBUS() (在 signal 模块中):           模块内容<5>.        (line   41)
* SIGCHLD() (在 signal 模块中):          模块内容<5>.        (line   47)
* SIGCLD() (在 signal 模块中):           模块内容<5>.        (line   53)
* SIGCONT() (在 signal 模块中):          模块内容<5>.        (line   57)
* SIGFPE() (在 signal 模块中):           模块内容<5>.        (line   63)
* SIGHUP() (在 signal 模块中):           模块内容<5>.        (line   73)
* SIGILL() (在 signal 模块中):           模块内容<5>.        (line   79)
* SIGINT:                                信号处理<2>.        (line    8)
* SIGINT <1>:                            信号处理<2>.        (line   20)
* SIGINT() (在 signal 模块中):           模块内容<5>.        (line   83)
* siginterrupt() (在 signal 模块中):     模块内容<5>.        (line  382)
* SIGKILL() (在 signal 模块中):          模块内容<5>.        (line   89)
* signal (模块):                         signal --- 设置异步事件处理程序.
                                                             (line    6)
* signal() (在 signal 模块中):           模块内容<5>.        (line  394)
* Signature (inspect 中的类):            Introspecting callables with the Signature object.
                                                             (line   50)
* signature (inspect.BoundArguments 属性): Introspecting callables with the Signature object.
                                                             (line  306)
* signature() (在 inspect 模块中):       Introspecting callables with the Signature object.
                                                             (line   12)
* sigpending() (在 signal 模块中):       模块内容<5>.        (line  417)
* SIGPIPE() (在 signal 模块中):          模块内容<5>.        (line   97)
* SIGSEGV() (在 signal 模块中):          模块内容<5>.        (line  105)
* SIGTERM() (在 signal 模块中):          模块内容<5>.        (line  109)
* sigtimedwait() (在 signal 模块中):     模块内容<5>.        (line  465)
* SIGUSR1() (在 signal 模块中):          模块内容<5>.        (line  113)
* SIGUSR2() (在 signal 模块中):          模块内容<5>.        (line  119)
* sigwait() (在 signal 模块中):          模块内容<5>.        (line  429)
* sigwaitinfo() (在 signal 模块中):      模块内容<5>.        (line  442)
* SIGWINCH() (在 signal 模块中):         模块内容<5>.        (line  125)
* SIG_BLOCK() (在 signal 模块中):        模块内容<5>.        (line  176)
* SIG_DFL() (在 signal 模块中):          模块内容<5>.        (line   15)
* SIG_IGN() (在 signal 模块中):          模块内容<5>.        (line   21)
* SIG_SETMASK() (在 signal 模块中):      模块内容<5>.        (line  190)
* SIG_UNBLOCK() (在 signal 模块中):      模块内容<5>.        (line  183)
* Simple Mail Transfer Protocol:         smtplib ---SMTP协议客户端.
                                                             (line    8)
* simple; statement:                     简单语句.           (line    6)
* SimpleCookie (http.cookies 中的类):    http cookies --- HTTP状态管理.
                                                             (line   48)
* simplefilter() (在 warnings 模块中):   Available Functions.
                                                             (line   89)
* SimpleHandler (wsgiref.handlers 中的类): wsgiref handlers -- server/gateway base classes.
                                                             (line   70)
* SimpleHTTPRequestHandler (http.server 中的类): http server --- HTTP 服务器.
                                                             (line  319)
* SimpleNamespace (types 中的类):        附加工具类和函数.   (line    6)
* SimpleQueue (multiprocessing 中的类):  管道和队列.         (line  172)
* SimpleQueue (queue 中的类):            queue --- 一个同步的队列类.
                                                             (line   62)
* SimpleXMLRPCRequestHandler (xmlrpc.server 中的类): xmlrpc server --- 基本 XML-RPC 服务器.
                                                             (line   58)
* SimpleXMLRPCServer (xmlrpc.server 中的类): xmlrpc server --- 基本 XML-RPC 服务器.
                                                             (line   19)
* sin() (在 cmath 模块中):               三角函数<2>.        (line   26)
* sin() (在 math 模块中):                三角函数.           (line   51)
* single dispatch – 单分派:              术语对照表.         (line  965)
* SingleAddressHeader (email.headerregistry 中的类): email headerregistry 自定义标头对象.
                                                             (line  176)
* singledispatch() (在 functools 模块中): functools --- 高阶函数和可调用对象上的操作.
                                                             (line  281)
* singledispatchmethod (functools 中的类): functools --- 高阶函数和可调用对象上的操作.
                                                             (line  386)
* singleton; tuple:                      标准类型层级结构.   (line  130)
* sinh() (在 cmath 模块中):              双曲函数<2>.        (line   26)
* sinh() (在 math 模块中):               双曲函数.           (line   24)
* SIO_KEEPALIVE_VALS() (在 socket 模块中): 常量<8>.          (line  160)
* SIO_LOOPBACK_FAST_PATH() (在 socket 模块中): 常量<8>.      (line  160)
* SIO_RCVALL() (在 socket 模块中):       常量<8>.            (line  160)
* site (模块):                           site —— 站点专属的配置钩子.
                                                             (line    6)
* site command line option; –user-base:  命令行界面<9>.      (line   16)
* site command line option; –user-site:  命令行界面<9>.      (line   20)
* site-packages; directory:              site —— 站点专属的配置钩子.
                                                             (line   21)
* site_maps() (urllib.robotparser.RobotFileParser 方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   63)
* sixtofour (ipaddress.IPv6Address 属性): 地址对象.          (line  204)
* size (multiprocessing.shared_memory.SharedMemory 属性): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   73)
* size (struct.Struct 属性):             类<2>.              (line   55)
* size (tarfile.TarInfo 属性):           TarInfo 对象.       (line   43)
* size (tracemalloc.Statistic 属性):     统计.               (line   19)
* size (tracemalloc.StatisticDiff 属性): StatisticDiff.      (line   26)
* size (tracemalloc.Trace 属性):         跟踪.               (line   23)
* size() (ftplib.FTP 方法):              FTP 对象.           (line  198)
* size() (mmap.mmap 方法):               mmap --- 内存映射文件支持.
                                                             (line  232)
* Sized (collections.abc 中的类):        容器抽象基类.       (line  112)
* Sized (typing 中的类):                 类 函数和修饰器.    (line  185)
* sizeof() (在 ctypes 模块中):           工具函数.           (line  164)
* size_diff (tracemalloc.StatisticDiff 属性): StatisticDiff. (line   32)
* SIZE_MAX:                              整数型对象.         (line  188)
* skip() (chunk.Chunk 方法):             chunk --- 读取 IFF 分块数据.
                                                             (line   97)
* SKIP() (在 doctest 模块中):            Option Flags.       (line  103)
* skip() (在 unittest 模块中):           跳过测试与预计的失败.
                                                             (line   82)
* skipIf() (在 unittest 模块中):         跳过测试与预计的失败.
                                                             (line   86)
* skipinitialspace (csv.Dialect 属性):   变种与格式参数.     (line   54)
* skipped (unittest.TestResult 属性):    Loading and running tests.
                                                             (line  249)
* skippedEntity() (xml.sax.handler.ContentHandler 方法): ContentHandler 对象.
                                                             (line  148)
* SkipTest:                              跳过测试与预计的失败.
                                                             (line  100)
* skipTest() (unittest.TestCase 方法):   测试用例.           (line   97)
* skipUnless() (在 unittest 模块中):     跳过测试与预计的失败.
                                                             (line   90)
* skip_unless_bind_unix_socket() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  562)
* skip_unless_symlink() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  553)
* skip_unless_xattr() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  558)
* SLASH() (在 token 模块中):             token --- 与Python解析树一起使用的常量.
                                                             (line   90)
* SLASHEQUAL() (在 token 模块中):        token --- 与Python解析树一起使用的常量.
                                                             (line  178)
* slave() (nntplib.NNTP 方法):           方法<3>.            (line  302)
* sleep() (在 asyncio 模块中):           休眠.               (line    6)
* sleep() (在 time 模块中):              函数<2>.            (line  186)
* slice:                                 切片.               (line    6)
* slice (內置类):                        内置函数.           (line 1254)
* slice – 切片:                          术语对照表.         (line  970)
* slice; assignment:                     可变序列类型.       (line   14)
* slice; operation:                      通用序列操作.       (line   17)
* slicing:                               标准类型层级结构.   (line   97)
* slicing <1>:                           标准类型层级结构.   (line  146)
* slicing <2>:                           切片.               (line    6)
* slicing; assignment:                   赋值语句.           (line   98)
* SMALLEST() (在 test.support 模块中):   test support --- Utilities for the Python test suite.
                                                             (line  155)
* SMTP (smtplib 中的类):                 smtplib ---SMTP协议客户端.
                                                             (line   15)
* SMTP() (在 email.policy 模块中):       email policy 策略对象.
                                                             (line  397)
* SMTP; protocol:                        smtplib ---SMTP协议客户端.
                                                             (line    8)
* SMTPAuthenticationError:               smtplib ---SMTP协议客户端.
                                                             (line  152)
* SMTPChannel (smtpd 中的类):            SMTPChannel 对象.   (line    6)
* SMTPConnectError:                      smtplib ---SMTP协议客户端.
                                                             (line  137)
* smtpd (模块):                          smtpd --- SMTP 服务器.
                                                             (line    6)
* SMTPDataError:                         smtplib ---SMTP协议客户端.
                                                             (line  133)
* SMTPException:                         smtplib ---SMTP协议客户端.
                                                             (line   99)
* SMTPHandler (logging.handlers 中的类): SMTPHandler.        (line    9)
* SMTPHeloError:                         smtplib ---SMTP协议客户端.
                                                             (line  142)
* smtplib (模块):                        smtplib ---SMTP协议客户端.
                                                             (line    6)
* SMTPNotSupportedError:                 smtplib ---SMTP协议客户端.
                                                             (line  146)
* SMTPRecipientsRefused:                 smtplib ---SMTP协议客户端.
                                                             (line  126)
* SMTPResponseException:                 smtplib ---SMTP协议客户端.
                                                             (line  112)
* SMTPSenderRefused:                     smtplib ---SMTP协议客户端.
                                                             (line  120)
* SMTPServer (smtpd 中的类):             SMTPServer 对象.    (line    6)
* SMTPServerDisconnected:                smtplib ---SMTP协议客户端.
                                                             (line  106)
* SMTPUTF8() (在 email.policy 模块中):   email policy 策略对象.
                                                             (line  402)
* smtp_server (smtpd.SMTPChannel 属性):  SMTPChannel 对象.   (line   43)
* SMTP_SSL (smtplib 中的类):             smtplib ---SMTP协议客户端.
                                                             (line   56)
* smtp_state (smtpd.SMTPChannel 属性):   SMTPChannel 对象.   (line   62)
* Snapshot (tracemalloc 中的类):         快照.               (line    6)
* sndhdr (模块):                         sndhdr --- 推测声音文件的类型.
                                                             (line    6)
* SND_ALIAS() (在 winsound 模块中):      winsound --- Sound-playing interface for Windows.
                                                             (line   47)
* SND_ASYNC() (在 winsound 模块中):      winsound --- Sound-playing interface for Windows.
                                                             (line  109)
* SND_FILENAME() (在 winsound 模块中):   winsound --- Sound-playing interface for Windows.
                                                             (line   42)
* SND_LOOP() (在 winsound 模块中):       winsound --- Sound-playing interface for Windows.
                                                             (line   88)
* SND_MEMORY() (在 winsound 模块中):     winsound --- Sound-playing interface for Windows.
                                                             (line   94)
* SND_NODEFAULT() (在 winsound 模块中):  winsound --- Sound-playing interface for Windows.
                                                             (line  113)
* SND_NOSTOP() (在 winsound 模块中):     winsound --- Sound-playing interface for Windows.
                                                             (line  118)
* SND_NOWAIT() (在 winsound 模块中):     winsound --- Sound-playing interface for Windows.
                                                             (line  122)
* SND_PURGE() (在 winsound 模块中):      winsound --- Sound-playing interface for Windows.
                                                             (line  103)
* sniff() (csv.Sniffer 方法):            模块内容<3>.        (line  182)
* Sniffer (csv 中的类):                  模块内容<3>.        (line  176)
* sni_callback (ssl.SSLContext 属性):    SSL 上下文.         (line  256)
* socket (socketserver.BaseServer 属性): Server 对象<2>.     (line   85)
* socket (模块):                         socket --- 底层网络接口.
                                                             (line    6)
* socket() (imaplib.IMAP4 方法):         IMAP4 Objects.      (line  268)
* socket() (in module socket):           select --- 等待 I/O 完成.
                                                             (line  114)
* socket() (在 socket 模块中):           创建套接字.         (line    8)
* SocketHandler (logging.handlers 中的类): SocketHandler.    (line    9)
* socketpair() (在 socket 模块中):       创建套接字.         (line   53)
* sockets (asyncio.Server 属性):         Server 对象.        (line   92)
* socketserver (模块):                   socketserver --- A framework for network servers.
                                                             (line    6)
* SocketType() (在 socket 模块中):       创建套接字.         (line  153)
* socket_type (socketserver.BaseServer 属性): Server 对象<2>.
                                                             (line  108)
* sock_accept() (asyncio.loop 方法):     直接使用 socket 对象.
                                                             (line   68)
* SOCK_CLOEXEC() (在 socket 模块中):     常量<8>.            (line   29)
* sock_connect() (asyncio.loop 方法):    直接使用 socket 对象.
                                                             (line   50)
* SOCK_DGRAM() (在 socket 模块中):       常量<8>.            (line   19)
* SOCK_MAX_SIZE() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  100)
* SOCK_NONBLOCK() (在 socket 模块中):    常量<8>.            (line   29)
* SOCK_RAW() (在 socket 模块中):         常量<8>.            (line   19)
* SOCK_RDM() (在 socket 模块中):         常量<8>.            (line   19)
* sock_recv() (asyncio.loop 方法):       直接使用 socket 对象.
                                                             (line   11)
* sock_recv_into() (asyncio.loop 方法):  直接使用 socket 对象.
                                                             (line   24)
* sock_sendall() (asyncio.loop 方法):    直接使用 socket 对象.
                                                             (line   35)
* sock_sendfile() (asyncio.loop 方法):   直接使用 socket 对象.
                                                             (line   87)
* SOCK_SEQPACKET() (在 socket 模块中):   常量<8>.            (line   19)
* SOCK_STREAM() (在 socket 模块中):      常量<8>.            (line   19)
* SOL_ALG() (在 socket 模块中):          常量<8>.            (line  176)
* SOL_RDS() (在 socket 模块中):          常量<8>.            (line  147)
* SOMAXCONN() (在 socket 模块中):        常量<8>.            (line   45)
* sort() (imaplib.IMAP4 方法):           IMAP4 Objects.      (line  272)
* sort() (list 方法):                    列表<2>.            (line   33)
* sortdict() (在 test.support 模块中):   test support --- Utilities for the Python test suite.
                                                             (line  224)
* sorted() (內置函数):                   内置函数.           (line 1266)
* sortTestMethodsUsing (unittest.TestLoader 属性): Loading and running tests.
                                                             (line  185)
* sort_stats() (pstats.Stats 方法):      Stats 类.           (line   67)
* source (doctest.Example 属性):         Example Objects.    (line   17)
* source (pdb command):                  调试器命令.         (line  209)
* source (shlex.shlex 属性):             shlex Objects.      (line  150)
* source character set:                  编码声明.           (line    6)
* SourceFileLoader (importlib.machinery 中的类): importlib machinery -- Importers and path hooks.
                                                             (line  209)
* sourcehook() (shlex.shlex 方法):       shlex Objects.      (line   26)
* SourcelessFileLoader (importlib.machinery 中的类): importlib machinery -- Importers and path hooks.
                                                             (line  249)
* SourceLoader (importlib.abc 中的类):   importlib abc —— 关于导入的抽象基类.
                                                             (line  443)
* SOURCE_DATE_EPOCH:                     py_compile<2>.      (line    7)
* SOURCE_DATE_EPOCH <1>:                 库<29>.             (line  451)
* SOURCE_DATE_EPOCH <2>:                 构建<23>.           (line   15)
* SOURCE_DATE_EPOCH <3>:                 py_compile --- 编译 Python 源文件.
                                                             (line   51)
* SOURCE_DATE_EPOCH <4>:                 py_compile --- 编译 Python 源文件.
                                                             (line   66)
* SOURCE_DATE_EPOCH <5>:                 py_compile --- 编译 Python 源文件.
                                                             (line   69)
* SOURCE_DATE_EPOCH <6>:                 Command-line use.   (line   83)
* source_from_cache() (在 imp 模块中):   imp --- Access the import internals.
                                                             (line  219)
* source_from_cache() (在 importlib.util 模块中): importlib util -- Utility code for importers.
                                                             (line   58)
* source_hash() (在 importlib.util 模块中): importlib util -- Utility code for importers.
                                                             (line  217)
* SOURCE_SUFFIXES() (在 importlib.machinery 模块中): importlib machinery -- Importers and path hooks.
                                                             (line   13)
* source_to_code() (importlib.abc.InspectLoader 静态方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  366)
* space:                                 缩进.               (line    6)
* space; in printf-style formatting:     printf 风格的字符串格式化.
                                                             (line   53)
* space; in printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line   52)
* space; in string formatting:           格式规格迷你语言.   (line   59)
* span() (re.Match 方法):                匹配对象.           (line  134)
* spawn() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  485)
* spawn() (在 pty 模块中):               pty --- 伪终端工具. (line   31)
* spawnl() (在 os 模块中):               进程管理.           (line  426)
* spawnle() (在 os 模块中):              进程管理.           (line  426)
* spawnlp() (在 os 模块中):              进程管理.           (line  426)
* spawnlpe() (在 os 模块中):             进程管理.           (line  426)
* spawnv() (在 os 模块中):               进程管理.           (line  426)
* spawnve() (在 os 模块中):              进程管理.           (line  426)
* spawnvp() (在 os 模块中):              进程管理.           (line  426)
* spawnvpe() (在 os 模块中):             进程管理.           (line  426)
* spawn_python() (在 test.support.script_helper 模块中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   58)
* special method – 特殊方法:             术语对照表.         (line  977)
* special; attribute:                    标准类型层级结构.   (line   10)
* special; method:                       术语对照表.         (line  981)
* specified_attributes (xml.parsers.expat.xmlparser 属性): XMLParser对象<2>.
                                                             (line   96)
* spec_from_file_location() (在 importlib.util 模块中): importlib util -- Utility code for importers.
                                                             (line  205)
* spec_from_loader() (在 importlib.util 模块中): importlib util -- Utility code for importers.
                                                             (line  194)
* speed() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line  137)
* speed() (在 turtle 模块中):            海龟动作.           (line  288)
* Spinbox (tkinter.ttk 中的类):          ttk Spinbox.        (line    6)
* split() (bytearray 方法):              bytes 和 bytearray 操作.
                                                             (line  275)
* split() (bytes 方法):                  bytes 和 bytearray 操作.
                                                             (line  275)
* split() (re.Pattern 方法):             正则表达式对象 （正则对象）.
                                                             (line   60)
* split() (str 方法):                    字符串的方法<2>.    (line  335)
* split() (在 os.path 模块中):           os path --- 常用路径操作.
                                                             (line  319)
* split() (在 re 模块中):                模块内容.           (line  138)
* split() (在 shlex 模块中):             shlex --- Simple lexical analysis.
                                                             (line   17)
* splitdrive() (在 os.path 模块中):      os path --- 常用路径操作.
                                                             (line  332)
* splitext() (在 os.path 模块中):        os path --- 常用路径操作.
                                                             (line  349)
* splitlines() (bytearray 方法):         bytes 和 bytearray 操作.
                                                             (line  490)
* splitlines() (bytes 方法):             bytes 和 bytearray 操作.
                                                             (line  490)
* splitlines() (str 方法):               字符串的方法<2>.    (line  370)
* SplitResult (urllib.parse 中的类):     结构化解析结果.     (line   55)
* SplitResultBytes (urllib.parse 中的类): 结构化解析结果.    (line   81)
* split_quoted() (在 distutils.util 模块中): distutils util --- Miscellaneous other utility functions.
                                                             (line   98)
* SpooledTemporaryFile() (在 tempfile 模块中): tempfile --- 生成临时文件和目录.
                                                             (line   78)
* sprintf-style formatting:              printf 风格的字符串格式化.
                                                             (line    6)
* sprintf-style formatting <1>:          printf 风格的字节串格式化.
                                                             (line    6)
* spwd (模块):                           spwd --- The shadow password database.
                                                             (line    6)
* sqlite3 (模块):                        sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块.
                                                             (line    6)
* sqlite_version() (在 sqlite3 模块中):  模块函数和常量.     (line   14)
* sqlite_version_info() (在 sqlite3 模块中): 模块函数和常量. (line   18)
* sqrt() (decimal.Context 方法):         上下文对象.         (line  440)
* sqrt() (decimal.Decimal 方法):         Decimal 对象.       (line  468)
* sqrt() (在 cmath 模块中):              幂函数与对数函数<2>.
                                                             (line   20)
* sqrt() (在 math 模块中):               幂函数与对数函数.   (line   65)
* ssizeargfunc (C 类型):                 Slot Type typedefs. (line  116)
* ssizeobjargproc (C 类型):              Slot Type typedefs. (line  118)
* SSL:                                   ssl --- 套接字对象的TLS/SSL封装.
                                                             (line    8)
* ssl (模块):                            ssl --- 套接字对象的TLS/SSL封装.
                                                             (line    6)
* SSLCertVerificationError:              异常<12>.           (line   70)
* SSLContext (ssl 中的类):               SSL 上下文.         (line   12)
* SSLEOFError:                           异常<12>.           (line   63)
* SSLError:                              异常<12>.           (line    6)
* SSLErrorNumber (ssl 中的类):           常量<9>.            (line  463)
* SSLKEYLOGFILE:                         上下文创建.         (line   28)
* SSLKEYLOGFILE <1>:                     上下文创建.         (line   56)
* SSLObject (ssl 中的类):                内存 BIO 支持<2>.   (line   26)
* sslobject_class (ssl.SSLContext 属性): SSL 上下文.         (line  408)
* SSLSession (ssl 中的类):               SSL 会话.           (line    8)
* SSLSocket (ssl 中的类):                SSL 套接字.         (line    6)
* sslsocket_class (ssl.SSLContext 属性): SSL 上下文.         (line  385)
* SSLSyscallError:                       异常<12>.           (line   56)
* SSLv3 (ssl.TLSVersion 属性):           常量<9>.            (line  484)
* SSLWantReadError:                      异常<12>.           (line   40)
* SSLWantWriteError:                     异常<12>.           (line   48)
* SSLZeroReturnError:                    异常<12>.           (line   32)
* SSL_CERT_FILE:                         LibreSSL 支持.      (line   13)
* SSL_CERT_PATH:                         LibreSSL 支持.      (line   14)
* ssl_version (ftplib.FTP_TLS 属性):     FTP_TLS 对象.       (line    8)
* st() (在 turtle 模块中):               可见性.             (line   14)
* st2list() (在 parser 模块中):          转换 ST 对象.       (line   11)
* st2tuple() (在 parser 模块中):         转换 ST 对象.       (line   31)
* stack (traceback.TracebackException 属性): TracebackException Objects.
                                                             (line   34)
* stack viewer:                          调试菜单（仅 window 编辑器）.
                                                             (line   15)
* stack() (在 inspect 模块中):           The interpreter stack.
                                                             (line   82)
* stack; trace:                          标准类型层级结构.   (line  571)
* stackable; streams:                    codecs --- 编解码器注册和相关基类.
                                                             (line    8)
* StackSummary (traceback 中的类):       StackSummary Objects.
                                                             (line   11)
* stack_effect() (在 dis 模块中):        分析函数.           (line  121)
* stack_size() (在 threading 模块中):    threading --- 基于线程的并行.
                                                             (line  118)
* stack_size() (在 _thread 模块中):      _thread --- 底层多线程 API.
                                                             (line   79)
* stamp() (在 turtle 模块中):            海龟动作.           (line  225)
* Standard C:                            字符串和字节串字面值.
                                                             (line   62)
* standard input:                        完整的 Python 程序. (line   19)
* standard; output:                      表达式语句.         (line   15)
* standarderror (2to3 fixer):            修复器.             (line  280)
* standard_b64decode() (在 base64 模块中): base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line   67)
* standard_b64encode() (在 base64 模块中): base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line   62)
* standend() (curses.window 方法):       Window 对象.        (line  440)
* standout() (curses.window 方法):       Window 对象.        (line  444)
* STAR() (在 token 模块中):              token --- 与Python解析树一起使用的常量.
                                                             (line   86)
* STAREQUAL() (在 token 模块中):         token --- 与Python解析树一起使用的常量.
                                                             (line  174)
* starmap() (multiprocessing.pool.Pool 方法): 进程池.        (line  119)
* starmap() (在 itertools 模块中):       Itertool函数.       (line  466)
* starmap_async() (multiprocessing.pool.Pool 方法): 进程池.  (line  129)
* start (range 属性):                    range 对象.         (line   52)
* start (slice object attribute):        标准类型层级结构.   (line  607)
* start (slice object attribute) <1>:    切片.               (line   22)
* start (UnicodeError 属性):             具体异常.           (line  315)
* start() (logging.handlers.QueueListener 方法): QueueListener.
                                                             (line   60)
* start() (multiprocessing.managers.BaseManager 方法): 管理器.
                                                             (line   34)
* start() (multiprocessing.Process 方法): Process 和异常.    (line   36)
* start() (re.Match 方法):               匹配对象.           (line  112)
* start() (threading.Thread 方法):       线程对象.           (line   73)
* start() (tkinter.ttk.Progressbar 方法): ttk Progressbar.   (line    8)
* start() (xml.etree.ElementTree.TreeBuilder 方法): TreeBuilder 对象.
                                                             (line   37)
* start() (在 tracemalloc 模块中):       函数<9>.            (line   50)
* StartCdataSectionHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  249)
* StartDoctypeDeclHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  154)
* startDocument() (xml.sax.handler.ContentHandler 方法): ContentHandler 对象.
                                                             (line   25)
* startElement() (xml.sax.handler.ContentHandler 方法): ContentHandler 对象.
                                                             (line   69)
* StartElementHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  185)
* startElementNS() (xml.sax.handler.ContentHandler 方法): ContentHandler 对象.
                                                             (line   86)
* startfile() (在 os 模块中):            进程管理.           (line  519)
* STARTF_USESHOWWINDOW() (在 subprocess 模块中): Windows 常数.
                                                             (line   30)
* STARTF_USESTDHANDLES() (在 subprocess 模块中): Windows 常数.
                                                             (line   24)
* StartNamespaceDeclHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  231)
* startPrefixMapping() (xml.sax.handler.ContentHandler 方法): ContentHandler 对象.
                                                             (line   41)
* startswith() (bytearray 方法):         bytes 和 bytearray 操作.
                                                             (line  169)
* startswith() (bytes 方法):             bytes 和 bytearray 操作.
                                                             (line  169)
* startswith() (str 方法):               字符串的方法<2>.    (line  439)
* startTest() (unittest.TestResult 方法): Loading and running tests.
                                                             (line  330)
* startTestRun() (unittest.TestResult 方法): Loading and running tests.
                                                             (line  339)
* starttls() (imaplib.IMAP4 方法):       IMAP4 Objects.      (line  290)
* starttls() (nntplib.NNTP 方法):        方法<3>.            (line   61)
* starttls() (smtplib.SMTP 方法):        SMTP Objects.       (line  177)
* STARTUPINFO (subprocess 中的类):       Windows Popen 助手. (line    8)
* start_color() (在 curses 模块中):      函数<3>.            (line  370)
* start_component() (msilib.Directory 方法): Directory Objects.
                                                             (line   20)
* start_new_thread() (在 _thread 模块中): _thread --- 底层多线程 API.
                                                             (line   27)
* start_ns() (xml.etree.ElementTree.TreeBuilder 方法): TreeBuilder 对象.
                                                             (line   66)
* start_server() (在 asyncio 模块中):    流.                 (line   59)
* start_serving() (asyncio.Server 方法): Server 对象.        (line   43)
* start_threads() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  525)
* start_tls() (asyncio.loop 方法):       TLS 升级.           (line    6)
* start_unix_server() (在 asyncio 模块中): 流.               (line  106)
* stat (模块):                           stat --- 解析 stat 结果.
                                                             (line    6)
* stat() (nntplib.NNTP 方法):            方法<3>.            (line  218)
* stat() (os.DirEntry 方法):             文件和目录.         (line  826)
* stat() (pathlib.Path 方法):            方法<2>.            (line   33)
* stat() (poplib.POP3 方法):             POP3 对象.          (line   46)
* stat() (在 os 模块中):                 文件和目录.         (line  854)
* state() (tkinter.ttk.Widget 方法):     ttk Widget.         (line   25)
* statement – 语句:                      术语对照表.         (line  983)
* statement grouping:                    缩进.               (line    6)
* statement; assignment, annotated:      带标注的赋值语句.   (line    6)
* statement; assignment, augmented:      增强赋值语句.       (line    6)
* staticmethod() (內置函数):             内置函数.           (line 1288)
* Statistic (tracemalloc 中的类):        统计.               (line    6)
* StatisticDiff (tracemalloc 中的类):    StatisticDiff.      (line    6)
* statistics (模块):                     statistics --- 数学统计函数.
                                                             (line    6)
* statistics() (tracemalloc.Snapshot 方法): 快照.            (line   56)
* StatisticsError:                       异常<3>.            (line    8)
* Stats (pstats 中的类):                 Stats 类.           (line    9)
* status (http.client.HTTPResponse 属性): HTTPResponse 对象. (line   51)
* status() (imaplib.IMAP4 方法):         IMAP4 Objects.      (line  303)
* statvfs() (在 os 模块中):              文件和目录.         (line 1086)
* stat_result (os 中的类):               文件和目录.         (line  901)
* StdButtonBox (tkinter.tix 中的类):     Basic Widgets.      (line   64)
* stderr (asyncio.asyncio.subprocess.Process 属性): 与子进程交互.
                                                             (line  110)
* stderr (in module sys):                标准类型层级结构.   (line  476)
* stderr (in module sys) <1>:            Sub-interpreter support.
                                                             (line   26)
* stderr (subprocess.CalledProcessError 属性): 使用 subprocess 模块.
                                                             (line  194)
* stderr (subprocess.CompletedProcess 属性): 使用 subprocess 模块.
                                                             (line  102)
* stderr (subprocess.Popen 属性):        Popen 对象.         (line  107)
* stderr (subprocess.TimeoutExpired 属性): 使用 subprocess 模块.
                                                             (line  161)
* stderr() (在 sys 模块中):              sys --- 系统相关的参数和函数.
                                                             (line 1239)
* stdev (statistics.NormalDist 属性):    NormalDist 对象.    (line   30)
* stdev() (在 statistics 模块中):        函数细节.           (line  291)
* stdin (asyncio.asyncio.subprocess.Process 属性): 与子进程交互.
                                                             (line   99)
* stdin (in module sys):                 标准类型层级结构.   (line  476)
* stdin (in module sys) <1>:             Sub-interpreter support.
                                                             (line   26)
* stdin (subprocess.Popen 属性):         Popen 对象.         (line   92)
* stdin() (在 sys 模块中):               sys --- 系统相关的参数和函数.
                                                             (line 1239)
* stdin; stdout; sdterr:                 Process-wide parameters.
                                                             (line    9)
* stdio:                                 标准类型层级结构.   (line  476)
* stdout (asyncio.asyncio.subprocess.Process 属性): 与子进程交互.
                                                             (line  105)
* stdout (in module sys):                标准类型层级结构.   (line  476)
* stdout (in module sys) <1>:            Sub-interpreter support.
                                                             (line   26)
* stdout (subprocess.CalledProcessError 属性): 使用 subprocess 模块.
                                                             (line  190)
* stdout (subprocess.CompletedProcess 属性): 使用 subprocess 模块.
                                                             (line   92)
* stdout (subprocess.Popen 属性):        Popen 对象.         (line   99)
* stdout (subprocess.TimeoutExpired 属性): 使用 subprocess 模块.
                                                             (line  157)
* STDOUT() (在 subprocess 模块中):       使用 subprocess 模块.
                                                             (line  128)
* stdout() (在 sys 模块中):              sys --- 系统相关的参数和函数.
                                                             (line 1239)
* STD_ERROR_HANDLE() (在 subprocess 模块中): Windows 常数.   (line   16)
* STD_INPUT_HANDLE() (在 subprocess 模块中): Windows 常数.   (line    8)
* STD_OUTPUT_HANDLE() (在 subprocess 模块中): Windows 常数.  (line   12)
* step (pdb command):                    调试器命令.         (line  132)
* step (range 属性):                     range 对象.         (line   60)
* step (slice object attribute):         标准类型层级结构.   (line  607)
* step (slice object attribute) <1>:     切片.               (line   22)
* step() (tkinter.ttk.Progressbar 方法): ttk Progressbar.    (line   15)
* stereocontrols() (ossaudiodev.oss_mixer_device 方法): Mixer Device Objects.
                                                             (line   44)
* stls() (poplib.POP3 方法):             POP3 对象.          (line  101)
* stop (range 属性):                     range 对象.         (line   56)
* stop (slice object attribute):         标准类型层级结构.   (line  607)
* stop (slice object attribute) <1>:     切片.               (line   22)
* stop() (asyncio.loop 方法):            运行和停止循环.     (line   28)
* stop() (logging.handlers.QueueListener 方法): QueueListener.
                                                             (line   66)
* stop() (tkinter.ttk.Progressbar 方法): ttk Progressbar.    (line   21)
* stop() (unittest.TestResult 方法):     Loading and running tests.
                                                             (line  310)
* stop() (在 tracemalloc 模块中):        函数<9>.            (line   76)
* StopAsyncIteration:                    具体异常.           (line  201)
* StopIteration:                         具体异常.           (line  176)
* stopListening() (在 logging.config 模块中): 配置函数.      (line  131)
* stopTest() (unittest.TestResult 方法): Loading and running tests.
                                                             (line  334)
* stopTestRun() (unittest.TestResult 方法): Loading and running tests.
                                                             (line  345)
* stop_here() (bdb.Bdb 方法):            bdb --- Debugger framework.
                                                             (line  190)
* storbinary() (ftplib.FTP 方法):        FTP 对象.           (line   94)
* store() (imaplib.IMAP4 方法):          IMAP4 Objects.      (line  307)
* STORE_ACTIONS (optparse.Option 属性):  Adding new actions. (line   35)
* STORE_ATTR (opcode):                   Python字节码说明.   (line  468)
* STORE_DEREF (opcode):                  Python字节码说明.   (line  678)
* STORE_FAST (opcode):                   Python字节码说明.   (line  652)
* STORE_GLOBAL (opcode):                 Python字节码说明.   (line  477)
* STORE_NAME (opcode):                   Python字节码说明.   (line  444)
* STORE_SUBSCR (opcode):                 Python字节码说明.   (line  241)
* storlines() (ftplib.FTP 方法):         FTP 对象.           (line  106)
* str (built-in class); (see also string): range 对象.       (line  110)
* str (內置类):                          文本序列类型 --- str.
                                                             (line   37)
* str() (在 locale 模块中):              locale --- 国际化服务.
                                                             (line  415)
* strcoll() (在 locale 模块中):          locale --- 国际化服务.
                                                             (line  357)
* StreamError:                           tarfile --- 读写tar归档文件.
                                                             (line  174)
* StreamHandler (logging 中的类):        StreamHandler.      (line   10)
* StreamReader (asyncio 中的类):         StreamReader.       (line    6)
* StreamReader (codecs 中的类):          StreamReader 对象.  (line    9)
* streamreader (codecs.CodecInfo 属性):  codecs --- 编解码器注册和相关基类.
                                                             (line   76)
* StreamReaderWriter (codecs 中的类):    StreamReaderWriter 对象.
                                                             (line   12)
* StreamRecoder (codecs 中的类):         StreamRecoder 对象. (line   12)
* StreamRequestHandler (socketserver 中的类): Request Handler Objects.
                                                             (line   42)
* streams:                               codecs --- 编解码器注册和相关基类.
                                                             (line    8)
* StreamWriter (asyncio 中的类):         StreamWriter.       (line    6)
* StreamWriter (codecs 中的类):          StreamWriter 对象.  (line    9)
* streamwriter (codecs.CodecInfo 属性):  codecs --- 编解码器注册和相关基类.
                                                             (line   76)
* strerror (OSError 属性):               具体异常.           (line  128)
* strerror():                            抛出异常<2>.        (line   49)
* strerror() (在 os 模块中):             进程参数.           (line  410)
* strftime() (datetime.date 方法):       date 对象.          (line  246)
* strftime() (datetime.datetime 方法):   datetime 对象.      (line  631)
* strftime() (datetime.time 方法):       time 对象.          (line  189)
* strftime() (在 time 模块中):           函数<2>.            (line  196)
* strict (csv.Dialect 属性):             变种与格式参数.     (line   59)
* strict() (在 email.policy 模块中):     email policy 策略对象.
                                                             (line  414)
* strict_domain (http.cookiejar.DefaultCookiePolicy 属性): DefaultCookiePolicy 对象.
                                                             (line   95)
* strict_errors() (在 codecs 模块中):    错误处理方案.       (line  105)
* strict_ns_domain (http.cookiejar.DefaultCookiePolicy 属性): DefaultCookiePolicy 对象.
                                                             (line  117)
* strict_ns_set_initial_dollar (http.cookiejar.DefaultCookiePolicy 属性): DefaultCookiePolicy 对象.
                                                             (line  122)
* strict_ns_set_path (http.cookiejar.DefaultCookiePolicy 属性): DefaultCookiePolicy 对象.
                                                             (line  127)
* strict_ns_unverifiable (http.cookiejar.DefaultCookiePolicy 属性): DefaultCookiePolicy 对象.
                                                             (line  112)
* strict_rfc2965_unverifiable (http.cookiejar.DefaultCookiePolicy 属性): DefaultCookiePolicy 对象.
                                                             (line  103)
* strides (memoryview 属性):             内存视图.           (line  421)
* string (re.Match 属性):                匹配对象.           (line  167)
* string (模块):                         string --- 常见的字符串操作.
                                                             (line    6)
* string literal:                        字面值.             (line    8)
* STRING() (在 token 模块中):            token --- 与Python解析树一起使用的常量.
                                                             (line   42)
* string; conversion:                    基本定制.           (line  123)
* string; conversion <1>:                表达式语句.         (line   15)
* string; format() (built-in function):  内置函数.           (line  538)
* string; formatted literal:             字符串字面值拼接.   (line   20)
* string; formatting, printf:            printf 风格的字符串格式化.
                                                             (line    6)
* string; immutable sequences:           标准类型层级结构.   (line  115)
* string; interpolated literal:          字符串字面值拼接.   (line   20)
* string; interpolation, printf:         printf 风格的字符串格式化.
                                                             (line    6)
* string; item:                          抽取.               (line   28)
* string; methods:                       文本序列类型 --- str.
                                                             (line   73)
* string; object representation:         终结和内存释放.     (line   70)
* string; PyObject_Str (C function):     对象协议.           (line  157)
* string; str (built-in class):          文本序列类型 --- str.
                                                             (line   37)
* string; str() (built-in function):     内置函数.           (line 1317)
* string; text sequence type:            range 对象.         (line  110)
* string; __format__() (object method):  基本定制.           (line  123)
* string; __str__() (object method):     基本定制.           (line  105)
* StringIO (io 中的类):                  文本 I/O<2>.        (line  165)
* stringprep (模块):                     stringprep --- 因特网字符串预备.
                                                             (line    6)
* strings, documentation:                定义函数.           (line   20)
* strings, documentation <1>:            文档字符串.         (line    6)
* string_at() (在 ctypes 模块中):        工具函数.           (line  169)
* strip() (bytearray 方法):              bytes 和 bytearray 操作.
                                                             (line  313)
* strip() (bytes 方法):                  bytes 和 bytearray 操作.
                                                             (line  313)
* strip() (str 方法):                    字符串的方法<2>.    (line  446)
* stripspaces (curses.textpad.Textbox 属性): 文本框对象.     (line  102)
* strip_dirs() (pstats.Stats 方法):      Stats 类.           (line   34)
* strip_python_strerr() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  385)
* strptime() (datetime.datetime 类方法): datetime 对象.      (line  209)
* strptime() (在 time 模块中):           函数<2>.            (line  313)
* strsignal() (在 signal 模块中):        模块内容<5>.        (line  231)
* strtobool() (在 distutils.util 模块中): distutils util --- Miscellaneous other utility functions.
                                                             (line  119)
* Struct (struct 中的类):                类<2>.              (line    8)
* struct (模块):                         struct --- 将字节串解读为打包的二进制数据.
                                                             (line    6)
* Structure (ctypes 中的类):             结构化数据类型.     (line   21)
* struct_time (time 中的类):             函数<2>.            (line  340)
* strxfrm() (在 locale 模块中):          locale --- 国际化服务.
                                                             (line  364)
* STType() (在 parser 模块中):           ST 对象.            (line   10)
* Style (tkinter.ttk 中的类):            Ttk Styling.        (line   20)
* st_atime (os.stat_result 属性):        文件和目录.         (line  944)
* ST_ATIME() (在 stat 模块中):           stat --- 解析 stat 结果.
                                                             (line  152)
* st_atime_ns (os.stat_result 属性):     文件和目录.         (line  960)
* st_birthtime (os.stat_result 属性):    文件和目录.         (line 1017)
* st_blksize (os.stat_result 属性):      文件和目录.         (line  997)
* st_blocks (os.stat_result 属性):       文件和目录.         (line  992)
* st_creator (os.stat_result 属性):      文件和目录.         (line 1033)
* st_ctime (os.stat_result 属性):        文件和目录.         (line  952)
* ST_CTIME() (在 stat 模块中):           stat --- 解析 stat 结果.
                                                             (line  160)
* st_ctime_ns (os.stat_result 属性):     文件和目录.         (line  968)
* st_dev (os.stat_result 属性):          文件和目录.         (line  921)
* ST_DEV() (在 stat 模块中):             stat --- 解析 stat 结果.
                                                             (line  132)
* st_file_attributes (os.stat_result 属性): 文件和目录.      (line 1043)
* st_flags (os.stat_result 属性):        文件和目录.         (line 1006)
* st_fstype (os.stat_result 属性):       文件和目录.         (line 1023)
* st_gen (os.stat_result 属性):          文件和目录.         (line 1013)
* st_gid (os.stat_result 属性):          文件和目录.         (line  933)
* ST_GID() (在 stat 模块中):             stat --- 解析 stat 结果.
                                                             (line  144)
* st_ino (os.stat_result 属性):          文件和目录.         (line  912)
* ST_INO() (在 stat 模块中):             stat --- 解析 stat 结果.
                                                             (line  128)
* st_mode (os.stat_result 属性):         文件和目录.         (line  908)
* ST_MODE() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  124)
* st_mtime (os.stat_result 属性):        文件和目录.         (line  948)
* ST_MTIME() (在 stat 模块中):           stat --- 解析 stat 结果.
                                                             (line  156)
* st_mtime_ns (os.stat_result 属性):     文件和目录.         (line  964)
* st_nlink (os.stat_result 属性):        文件和目录.         (line  925)
* ST_NLINK() (在 stat 模块中):           stat --- 解析 stat 结果.
                                                             (line  136)
* st_rdev (os.stat_result 属性):         文件和目录.         (line 1002)
* st_reparse_tag (os.stat_result 属性):  文件和目录.         (line 1050)
* st_rsize (os.stat_result 属性):        文件和目录.         (line 1029)
* st_size (os.stat_result 属性):         文件和目录.         (line  937)
* ST_SIZE() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  148)
* st_type (os.stat_result 属性):         文件和目录.         (line 1037)
* st_uid (os.stat_result 属性):          文件和目录.         (line  929)
* ST_UID() (在 stat 模块中):             stat --- 解析 stat 结果.
                                                             (line  140)
* sub() (re.Pattern 方法):               正则表达式对象 （正则对象）.
                                                             (line   74)
* sub() (在 operator 模块中):            operator --- 标准运算符替代函数.
                                                             (line  141)
* sub() (在 re 模块中):                  模块内容.           (line  191)
* subclassing; immutable types:          基本定制.           (line    8)
* subdirs (filecmp.dircmp 属性):         dircmp 类.          (line   90)
* SubElement() (在 xml.etree.ElementTree 模块中): 函数<6>.   (line  165)
* submit() (concurrent.futures.Executor 方法): Executor 对象.
                                                             (line   10)
* submodule_search_locations (importlib.machinery.ModuleSpec 属性): importlib machinery -- Importers and path hooks.
                                                             (line  384)
* subn() (re.Pattern 方法):              正则表达式对象 （正则对象）.
                                                             (line   78)
* subn() (在 re 模块中):                 模块内容.           (line  243)
* subnets() (ipaddress.IPv4Network 方法): Network objects.   (line  173)
* subnets() (ipaddress.IPv6Network 方法): Network objects.   (line  344)
* subnet_of() (ipaddress.IPv4Network 方法): Network objects. (line  215)
* subnet_of() (ipaddress.IPv6Network 方法): Network objects. (line  348)
* Subnormal (decimal 中的类):            信号.               (line   77)
* suboffsets (memoryview 属性):          内存视图.           (line  428)
* subpad() (curses.window 方法):         Window 对象.        (line  448)
* subprocess (模块):                     subprocess --- 子进程管理.
                                                             (line    6)
* SubprocessError:                       使用 subprocess 模块.
                                                             (line  133)
* SubprocessProtocol (asyncio 中的类):   基础协议.           (line   22)
* SubprocessTransport (asyncio 中的类):  传输层级.           (line   46)
* subprocess_exec() (asyncio.loop 方法): 运行子进程.         (line   13)
* subprocess_shell() (asyncio.loop 方法): 运行子进程.        (line   93)
* subscribe() (imaplib.IMAP4 方法):      IMAP4 Objects.      (line  331)
* subscript; assignment:                 可变序列类型.       (line   14)
* subscript; operation:                  通用序列操作.       (line   17)
* subscription:                          标准类型层级结构.   (line   93)
* subscription <1>:                      标准类型层级结构.   (line  146)
* subscription <2>:                      标准类型层级结构.   (line  193)
* subscription <3>:                      抽取.               (line    6)
* subscription; assignment:              赋值语句.           (line   81)
* subsequent_indent (textwrap.TextWrapper 属性): textwrap --- 文本自动换行与填充.
                                                             (line  183)
* substitute() (string.Template 方法):   模板字符串.         (line   32)
* subst_vars() (在 distutils.util 模块中): distutils util --- Miscellaneous other utility functions.
                                                             (line   82)
* subTest() (unittest.TestCase 方法):    测试用例.           (line  105)
* subtract() (collections.Counter 方法): Counter 对象.       (line   78)
* subtract() (decimal.Context 方法):     上下文对象.         (line  444)
* subtraction:                           二元算术运算符.     (line   51)
* subtype (email.headerregistry.ContentTypeHeader 属性): email headerregistry 自定义标头对象.
                                                             (line  228)
* subwin() (curses.window 方法):         Window 对象.        (line  455)
* sub_commands (distutils.cmd.Command 属性): Creating a new Distutils command.
                                                             (line   49)
* successful() (multiprocessing.pool.AsyncResult 方法): 进程池.
                                                             (line  177)
* suffix_map (mimetypes.MimeTypes 属性): MimeTypes 对象.     (line   19)
* suffix_map() (在 mimetypes 模块中):    mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line  108)
* suite:                                 复合语句.           (line   15)
* suite() (在 parser 模块中):            创建 ST 对象.       (line   18)
* suiteClass (unittest.TestLoader 属性): Loading and running tests.
                                                             (line  191)
* sum() (內置函数):                      内置函数.           (line 1327)
* summarize() (doctest.DocTestRunner 方法): DocTestRunner 对象.
                                                             (line  115)
* summarize_address_range() (在 ipaddress 模块中): Other Module Level Functions.
                                                             (line   27)
* sum_list():                            引用计数细节.       (line  143)
* sum_sequence():                        引用计数细节.       (line  170)
* sum_sequence() <1>:                    异常<18>.           (line   63)
* sunau (模块):                          sunau --- 读写 Sun AU 文件.
                                                             (line    6)
* super (pyclbr.Class 属性):             类对象<2>.          (line   37)
* super() (內置函数):                    内置函数.           (line 1339)
* supernet() (ipaddress.IPv4Network 方法): Network objects.  (line  199)
* supernet() (ipaddress.IPv6Network 方法): Network objects.  (line  346)
* supernet_of() (ipaddress.IPv4Network 方法): Network objects.
                                                             (line  226)
* supernet_of() (ipaddress.IPv6Network 方法): Network objects.
                                                             (line  350)
* SupportsAbs (typing 中的类):           类 函数和修饰器.    (line  169)
* SupportsBytes (typing 中的类):         类 函数和修饰器.    (line  159)
* SupportsComplex (typing 中的类):       类 函数和修饰器.    (line  155)
* SupportsFloat (typing 中的类):         类 函数和修饰器.    (line  151)
* SupportsIndex (typing 中的类):         类 函数和修饰器.    (line  163)
* SupportsInt (typing 中的类):           类 函数和修饰器.    (line  147)
* SupportsRound (typing 中的类):         类 函数和修饰器.    (line  173)
* supports_bytes_environ() (在 os 模块中): 进程参数.         (line  415)
* supports_dir_fd() (在 os 模块中):      文件和目录.         (line 1121)
* supports_effective_ids() (在 os 模块中): 文件和目录.       (line 1141)
* supports_fd() (在 os 模块中):          文件和目录.         (line 1157)
* supports_follow_symlinks() (在 os 模块中): 文件和目录.     (line 1173)
* supports_unicode_filenames() (在 os.path 模块中): os path --- 常用路径操作.
                                                             (line  357)
* suppress() (在 contextlib 模块中):     工具.               (line  161)
* SuppressCrashReport (test.support 中的类): test support --- Utilities for the Python test suite.
                                                             (line 1044)
* swapcase() (bytearray 方法):           bytes 和 bytearray 操作.
                                                             (line  512)
* swapcase() (bytes 方法):               bytes 和 bytearray 操作.
                                                             (line  512)
* swapcase() (str 方法):                 字符串的方法<2>.    (line  466)
* swap_attr() (在 test.support 模块中):  test support --- Utilities for the Python test suite.
                                                             (line  486)
* swap_item() (在 test.support 模块中):  test support --- Utilities for the Python test suite.
                                                             (line  503)
* SW_HIDE() (在 subprocess 模块中):      Windows 常数.       (line   20)
* Symbol (symtable 中的类):              Examining Symbol Tables.
                                                             (line  103)
* symbol (模块):                         symbol --- 与 Python 解析树一起使用的常量.
                                                             (line    6)
* SymbolTable (symtable 中的类):         Examining Symbol Tables.
                                                             (line    6)
* symlink() (在 os 模块中):              文件和目录.         (line 1192)
* symlink_to() (pathlib.Path 方法):      方法<2>.            (line  355)
* symmetric_difference() (frozenset 方法): 集合类型 --- set frozenset.
                                                             (line  107)
* symmetric_difference_update() (frozenset 方法): 集合类型 --- set frozenset.
                                                             (line  169)
* symtable (模块):                       symtable --- Access to the compiler's symbol tables.
                                                             (line    6)
* symtable() (在 symtable 模块中):       Generating Symbol Tables.
                                                             (line    6)
* sym_name() (在 symbol 模块中):         symbol --- 与 Python 解析树一起使用的常量.
                                                             (line   17)
* sync() (dbm.dumb.dumbdbm 方法):        dbm dumb --- 便携式 DBM 实现.
                                                             (line   64)
* sync() (dbm.gnu.gdbm 方法):            dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line   94)
* sync() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line  161)
* sync() (shelve.Shelf 方法):            shelve --- Python 对象持久化.
                                                             (line   52)
* sync() (在 os 模块中):                 文件和目录.         (line 1227)
* syncdown() (curses.window 方法):       Window 对象.        (line  464)
* synchronized() (在 multiprocessing.sharedctypes 模块中): multiprocessing sharedctypes 模块.
                                                             (line   75)
* SyncManager (multiprocessing.managers 中的类): 管理器.     (line  113)
* syncok() (curses.window 方法):         Window 对象.        (line  469)
* syncup() (curses.window 方法):         Window 对象.        (line  474)
* syntax:                                标注.               (line    6)
* SyntaxErr:                             异常<16>.           (line   76)
* SyntaxError:                           具体异常.           (line  208)
* SyntaxWarning:                         警告.               (line   28)
* sys (模块):                            sys --- 系统相关的参数和函数.
                                                             (line    6)
* sys.exc_info:                          标准类型层级结构.   (line  571)
* sys.last_traceback:                    标准类型层级结构.   (line  571)
* sys.meta_path:                         元路径.             (line    6)
* sys.modules:                           模块缓存.           (line    6)
* sys.path:                              路径条目查找器.     (line    6)
* sys.path_hooks:                        路径条目查找器.     (line    6)
* sys.path_importer_cache:               路径条目查找器.     (line    6)
* sys.stderr:                            标准类型层级结构.   (line  476)
* sys.stdin:                             标准类型层级结构.   (line  476)
* sys.stdout:                            标准类型层级结构.   (line  476)
* sysconf() (在 os 模块中):              其他系统信息.       (line   47)
* sysconfig (模块):                      sysconfig --- Provide access to Python's configuration information.
                                                             (line    6)
* sysconf_names() (在 os 模块中):        其他系统信息.       (line   55)
* syslog (模块):                         Unix syslog 库例程. (line    6)
* syslog() (在 syslog 模块中):           Unix syslog 库例程. (line   17)
* SysLogHandler (logging.handlers 中的类): SysLogHandler.    (line    9)
* system() (在 os 模块中):               进程管理.           (line  548)
* system() (在 platform 模块中):         跨平台.             (line  107)
* SystemError:                           具体异常.           (line  244)
* SystemError (built-in exception):      模块对象.           (line   55)
* SystemError (built-in exception) <1>:  模块对象.           (line   81)
* SystemExit:                            具体异常.           (line  255)
* SystemExit (built-in exception):       异常<2>.            (line   20)
* systemId (xml.dom.DocumentType 属性):  文档类型对象.       (line   17)
* SystemRandom (random 中的类):          替代生成器.         (line   10)
* SystemRandom (secrets 中的类):         随机数.             (line    9)
* SystemRoot:                            Popen 构造函数.     (line  188)
* system_alias() (在 platform 模块中):   跨平台.             (line  112)
* system_must_validate_cert() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  219)
* sys_exc (2to3 fixer):                  修复器.             (line  284)
* sys_version (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line  124)
* S_ENFMT() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  293)
* S_IEXEC() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  307)
* S_IFBLK() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  189)
* S_IFCHR() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  197)
* S_IFDIR() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  193)
* S_IFDOOR() (在 stat 模块中):           stat --- 解析 stat 结果.
                                                             (line  205)
* S_IFIFO() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  201)
* S_IFLNK() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  181)
* S_IFMT() (在 stat 模块中):             stat --- 解析 stat 结果.
                                                             (line   73)
* S_IFPORT() (在 stat 模块中):           stat --- 解析 stat 结果.
                                                             (line  211)
* S_IFREG() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  185)
* S_IFSOCK() (在 stat 模块中):           stat --- 解析 stat 结果.
                                                             (line  177)
* S_IFWHT() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  217)
* S_IMODE() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line   67)
* S_IREAD() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  299)
* S_IRGRP() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  265)
* S_IROTH() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  281)
* S_IRUSR() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  249)
* S_IRWXG() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  261)
* S_IRWXO() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  277)
* S_IRWXU() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  245)
* S_ISBLK() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line   27)
* S_ISCHR() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line   23)
* S_ISDIR() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line   19)
* S_ISDOOR() (在 stat 模块中):           stat --- 解析 stat 结果.
                                                             (line   47)
* S_ISFIFO() (在 stat 模块中):           stat --- 解析 stat 结果.
                                                             (line   35)
* S_ISGID() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  232)
* S_ISLNK() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line   39)
* S_ISPORT() (在 stat 模块中):           stat --- 解析 stat 结果.
                                                             (line   53)
* S_ISREG() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line   31)
* S_ISSOCK() (在 stat 模块中):           stat --- 解析 stat 结果.
                                                             (line   43)
* S_ISUID() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  228)
* S_ISVTX() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  240)
* S_ISWHT() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line   59)
* S_IWGRP() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  269)
* S_IWOTH() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  285)
* S_IWRITE() (在 stat 模块中):           stat --- 解析 stat 结果.
                                                             (line  303)
* S_IWUSR() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  253)
* S_IXGRP() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  273)
* S_IXOTH() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  289)
* S_IXUSR() (在 stat 模块中):            stat --- 解析 stat 结果.
                                                             (line  257)
* tab:                                   缩进.               (line    6)
* tab() (tkinter.ttk.Notebook 方法):     ttk Notebook.       (line   62)
* TabError:                              具体异常.           (line  239)
* tabnanny (模块):                       tabnanny --- 模糊缩进检测.
                                                             (line    6)
* tabs() (tkinter.ttk.Notebook 方法):    ttk Notebook.       (line   71)
* tabsize (textwrap.TextWrapper 属性):   textwrap --- 文本自动换行与填充.
                                                             (line  147)
* tag (xml.etree.ElementTree.Element 属性): 元素对象.        (line   14)
* tagName (xml.dom.Element 属性):        元素对象<2>.        (line    8)
* tag_bind() (tkinter.ttk.Treeview 方法): ttk Treeview.      (line  302)
* tag_configure() (tkinter.ttk.Treeview 方法): ttk Treeview. (line  308)
* tag_has() (tkinter.ttk.Treeview 方法): ttk Treeview.       (line  318)
* tail (xml.etree.ElementTree.Element 属性): 元素对象.       (line   18)
* takewhile() (在 itertools 模块中):     Itertool函数.       (line  479)
* take_snapshot() (在 tracemalloc 模块中): 函数<9>.          (line   88)
* tan() (在 cmath 模块中):               三角函数<2>.        (line   30)
* tan() (在 math 模块中):                三角函数.           (line   55)
* tanh() (在 cmath 模块中):              双曲函数<2>.        (line   30)
* tanh() (在 math 模块中):               双曲函数.           (line   28)
* TarError:                              tarfile --- 读写tar归档文件.
                                                             (line  161)
* TarFile (tarfile 中的类):              TarFile 对象.       (line   18)
* tarfile (模块):                        tarfile --- 读写tar归档文件.
                                                             (line    6)
* tarfile command line option; -c <tarfile> <source1> ... <sourceN>: 命令行选项<3>.
                                                             (line   11)
* tarfile command line option; –create <tarfile> <source1> ... <sourceN>: 命令行选项<3>.
                                                             (line   11)
* tarfile command line option; -e <tarfile> [<output_dir>]: 命令行选项<3>.
                                                             (line   16)
* tarfile command line option; –extract <tarfile> [<output_dir>]: 命令行选项<3>.
                                                             (line   16)
* tarfile command line option; -l <tarfile>: 命令行选项<3>.  (line    6)
* tarfile command line option; –list <tarfile>: 命令行选项<3>.
                                                             (line    6)
* tarfile command line option; -t <tarfile>: 命令行选项<3>.  (line   21)
* tarfile command line option; –test <tarfile>: 命令行选项<3>.
                                                             (line   21)
* tarfile command line option; -v:       命令行选项<3>.      (line   26)
* tarfile command line option; –verbose: 命令行选项<3>.      (line   26)
* target:                                赋值语句.           (line   25)
* target (xml.dom.ProcessingInstruction 属性): ProcessingInstruction 对象.
                                                             (line    8)
* target; list:                          赋值语句.           (line   25)
* target; list <1>:                      for 语句<2>.        (line    6)
* target; list; assignment:              赋值语句.           (line   30)
* TarInfo (tarfile 中的类):              TarInfo 对象.       (line   13)
* Task (asyncio 中的类):                 Task 对象.          (line    6)
* task_done() (asyncio.Queue 方法):      Queue.              (line   71)
* task_done() (multiprocessing.JoinableQueue 方法): 管道和队列.
                                                             (line  194)
* task_done() (queue.Queue 方法):        Queue对象.          (line   60)
* tau() (在 cmath 模块中):               常量<3>.            (line   14)
* tau() (在 math 模块中):                常量<2>.            (line   14)
* tbreak (pdb command):                  调试器命令.         (line   70)
* tb_frame (traceback attribute):        标准类型层级结构.   (line  588)
* tb_lasti (traceback attribute):        标准类型层级结构.   (line  588)
* tb_lineno (traceback attribute):       标准类型层级结构.   (line  588)
* tb_locals (unittest.TestResult 属性):  Loading and running tests.
                                                             (line  294)
* tb_next (traceback attribute):         标准类型层级结构.   (line  596)
* tcdrain() (在 termios 模块中):         termios --- POSIX 风格的 tty 控制.
                                                             (line   44)
* tcflow() (在 termios 模块中):          termios --- POSIX 风格的 tty 控制.
                                                             (line   54)
* tcflush() (在 termios 模块中):         termios --- POSIX 风格的 tty 控制.
                                                             (line   48)
* tcgetattr() (在 termios 模块中):       termios --- POSIX 风格的 tty 控制.
                                                             (line   22)
* tcgetpgrp() (在 os 模块中):            文件描述符操作.     (line  584)
* Tcl() (在 tkinter 模块中):             Tkinter 模块.       (line   28)
* TCL_LIBRARY:                           我怎样“冻结”Tkinter程序？.
                                                             (line   10)
* TCPServer (socketserver 中的类):       socketserver --- A framework for network servers.
                                                             (line   15)
* tcsendbreak() (在 termios 模块中):     termios --- POSIX 风格的 tty 控制.
                                                             (line   39)
* tcsetattr() (在 termios 模块中):       termios --- POSIX 风格的 tty 控制.
                                                             (line   31)
* tcsetpgrp() (在 os 模块中):            文件描述符操作.     (line  591)
* tearDown() (unittest.TestCase 方法):   测试用例.           (line   41)
* tearDownClass() (unittest.TestCase 方法): 测试用例.        (line   69)
* tee() (在 itertools 模块中):           Itertool函数.       (line  492)
* tell() (aifc.aifc 方法):               aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   97)
* tell() (chunk.Chunk 方法):             chunk --- 读取 IFF 分块数据.
                                                             (line   86)
* tell() (io.IOBase 方法):               I/O 基类.           (line  114)
* tell() (io.TextIOBase 方法):           文本 I/O<2>.        (line   78)
* tell() (mmap.mmap 方法):               mmap --- 内存映射文件支持.
                                                             (line  236)
* tell() (sunau.AU_read 方法):           AU_read 对象.       (line   64)
* tell() (sunau.AU_write 方法):          AU_write 对象.      (line   39)
* tell() (wave.Wave_read 方法):          Wave_read对象.      (line   68)
* tell() (wave.Wave_write 方法):         Wave_write 对象.    (line   53)
* Telnet (telnetlib 中的类):             telnetlib -- Telnet 客户端.
                                                             (line   21)
* telnetlib (模块):                      telnetlib -- Telnet 客户端.
                                                             (line    6)
* TEMP:                                  tempfile --- 生成临时文件和目录.
                                                             (line  200)
* tempdir() (在 tempfile 模块中):        tempfile --- 生成临时文件和目录.
                                                             (line  237)
* tempfile (模块):                       tempfile --- 生成临时文件和目录.
                                                             (line    6)
* Template (pipes 中的类):               pipes --- 终端管道接口.
                                                             (line   18)
* Template (string 中的类):              模板字符串.         (line   28)
* template (string.Template 属性):       模板字符串.         (line   55)
* temporary; file:                       tempfile --- 生成临时文件和目录.
                                                             (line    8)
* temporary; file name:                  tempfile --- 生成临时文件和目录.
                                                             (line    8)
* TemporaryDirectory() (在 tempfile 模块中): tempfile --- 生成临时文件和目录.
                                                             (line  100)
* TemporaryFile() (在 tempfile 模块中):  tempfile --- 生成临时文件和目录.
                                                             (line   23)
* temp_cwd() (在 test.support 模块中):   test support --- Utilities for the Python test suite.
                                                             (line  444)
* temp_dir() (在 test.support 模块中):   test support --- Utilities for the Python test suite.
                                                             (line  425)
* temp_umask() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  458)
* teredo (ipaddress.IPv6Address 属性):   地址对象.           (line  211)
* TERM:                                  函数<3>.            (line  366)
* TERM <1>:                              函数<3>.            (line  387)
* termattrs() (在 curses 模块中):        函数<3>.            (line  380)
* terminal_size (os 中的类):             查询终端的尺寸.     (line   23)
* terminate() (asyncio.asyncio.subprocess.Process 方法): 与子进程交互.
                                                             (line   81)
* terminate() (asyncio.SubprocessTransport 方法): 子进程传输.
                                                             (line   45)
* terminate() (multiprocessing.pool.Pool 方法): 进程池.      (line  143)
* terminate() (multiprocessing.Process 方法): Process 和异常.
                                                             (line  127)
* terminate() (subprocess.Popen 方法):   Popen 对象.         (line   71)
* termination model:                     异常<2>.            (line   16)
* termios (模块):                        termios --- POSIX 风格的 tty 控制.
                                                             (line    6)
* termname() (在 curses 模块中):         函数<3>.            (line  385)
* ternary; operator:                     条件表达式.         (line    6)
* ternaryfunc (C 类型):                  Slot Type typedefs. (line  113)
* test (doctest.DocTestFailure 属性):    调试.               (line  194)
* test (doctest.UnexpectedException 属性): 调试.             (line  215)
* test (模块):                           test --- Python回归测试包.
                                                             (line    6)
* test() (在 cgi 模块中):                函数<8>.            (line   45)
* test.support (模块):                   test support --- Utilities for the Python test suite.
                                                             (line    6)
* test.support.script_helper (模块):     test support script_helper --- Utilities for the Python execution tests.
                                                             (line    6)
* TestCase (unittest 中的类):            测试用例.           (line    6)
* TestFailed:                            test support --- Utilities for the Python test suite.
                                                             (line   16)
* testfile() (在 doctest 模块中):        Basic API.          (line   12)
* TESTFN() (在 test.support 模块中):     test support --- Utilities for the Python test suite.
                                                             (line   52)
* TESTFN_ENCODING() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line   62)
* TESTFN_NONASCII() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line   78)
* TESTFN_UNDECODABLE() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line   72)
* TESTFN_UNENCODABLE() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line   66)
* TESTFN_UNICODE() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line   58)
* TestHandler (test.support 中的类):     test support --- Utilities for the Python test suite.
                                                             (line 1107)
* TestLoader (unittest 中的类):          Loading and running tests.
                                                             (line    6)
* testMethodPrefix (unittest.TestLoader 属性): Loading and running tests.
                                                             (line  177)
* testmod() (在 doctest 模块中):         Basic API.          (line   90)
* testNamePatterns (unittest.TestLoader 属性): Loading and running tests.
                                                             (line  199)
* TestResult (unittest 中的类):          Loading and running tests.
                                                             (line  216)
* tests() (在 imghdr 模块中):            imghdr --- 推测图像类型.
                                                             (line   72)
* testsource() (在 doctest 模块中):      调试.               (line  106)
* testsRun (unittest.TestResult 属性):   Loading and running tests.
                                                             (line  272)
* TestSuite (unittest 中的类):           Grouping tests.     (line    6)
* testzip() (zipfile.ZipFile 方法):      ZipFile 对象.       (line  203)
* TEST_DATA_DIR() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  114)
* TEST_HOME_DIR() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  110)
* TEST_HTTP_URL() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  141)
* TEST_SUPPORT_DIR() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  105)
* text (SyntaxError 属性):               具体异常.           (line  230)
* text (traceback.TracebackException 属性): TracebackException Objects.
                                                             (line   50)
* Text (typing 中的类):                  类 函数和修饰器.    (line  430)
* text (xml.etree.ElementTree.Element 属性): 元素对象.       (line   18)
* text encoding – 文本编码:              术语对照表.         (line  989)
* text file – 文本文件:                  术语对照表.         (line  993)
* text mode:                             内置函数.           (line 1017)
* text() (msilib.Dialog 方法):           GUI classes.        (line   56)
* text() (在 cgitb 模块中):              cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line   38)
* text() (在 msilib 模块中):             Precomputed tables. (line   23)
* Textbox (curses.textpad 中的类):       文本框对象.         (line    8)
* TextCalendar (calendar 中的类):        calendar --- 日历相关函数.
                                                             (line  106)
* textdomain() (在 gettext 模块中):      GNU gettext API.    (line   32)
* textdomain() (在 locale 模块中):       Access to message catalogs.
                                                             (line   12)
* TextFile (distutils.text_file 中的类): distutils text_file --- The TextFile class.
                                                             (line   10)
* textinput() (在 turtle 模块中):        输入方法.           (line    6)
* TextIO (typing 中的类):                类 函数和修饰器.    (line  442)
* TextIOBase (io 中的类):                文本 I/O<2>.        (line    6)
* TextIOWrapper (io 中的类):             文本 I/O<2>.        (line   87)
* TextTestResult (unittest 中的类):      Loading and running tests.
                                                             (line  421)
* TextTestRunner (unittest 中的类):      Loading and running tests.
                                                             (line  435)
* textwrap (模块):                       textwrap --- 文本自动换行与填充.
                                                             (line    6)
* TextWrapper (textwrap 中的类):         textwrap --- 文本自动换行与填充.
                                                             (line  118)
* text_factory (sqlite3.Connection 属性): 连接对象（Connection）.
                                                             (line  302)
* theme_create() (tkinter.ttk.Style 方法): Ttk Styling.      (line  191)
* theme_names() (tkinter.ttk.Style 方法): Ttk Styling.       (line  239)
* theme_settings() (tkinter.ttk.Style 方法): Ttk Styling.    (line  201)
* theme_use() (tkinter.ttk.Style 方法):  Ttk Styling.        (line  243)
* THOUSEP() (在 locale 模块中):          locale --- 国际化服务.
                                                             (line  218)
* Thread (threading 中的类):             线程对象.           (line   48)
* thread() (imaplib.IMAP4 方法):         IMAP4 Objects.      (line  335)
* ThreadedChildWatcher (asyncio 中的类): 进程监视器.         (line   74)
* threading (模块):                      threading --- 基于线程的并行.
                                                             (line    6)
* ThreadingHTTPServer (http.server 中的类): http server --- HTTP 服务器.
                                                             (line   30)
* ThreadingMixIn (socketserver 中的类):  Server Creation Notes.
                                                             (line   28)
* ThreadingTCPServer (socketserver 中的类): Server Creation Notes.
                                                             (line   62)
* ThreadingUDPServer (socketserver 中的类): Server Creation Notes.
                                                             (line   62)
* threading_cleanup() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  781)
* threading_setup() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  777)
* ThreadPool (multiprocessing.pool 中的类): multiprocessing dummy 模块.
                                                             (line   13)
* ThreadPoolExecutor (concurrent.futures 中的类): ThreadPoolExecutor.
                                                             (line   39)
* threads; POSIX:                        _thread --- 底层多线程 API.
                                                             (line   13)
* thread_info() (在 sys 模块中):         sys --- 系统相关的参数和函数.
                                                             (line 1306)
* thread_time() (在 time 模块中):        函数<2>.            (line  412)
* thread_time_ns() (在 time 模块中):     函数<2>.            (line  423)
* throw (2to3 fixer):                    修复器.             (line  289)
* throw() (coroutine 方法):              协程对象.           (line   25)
* throw() (generator 方法):              生成器-迭代器的方法.
                                                             (line   31)
* ticket_lifetime_hint (ssl.SSLSession 属性): SSL 会话.      (line   18)
* tigetflag() (在 curses 模块中):        函数<3>.            (line  389)
* tigetnum() (在 curses 模块中):         函数<3>.            (line  395)
* tigetstr() (在 curses 模块中):         函数<3>.            (line  401)
* TILDE() (在 token 模块中):             token --- 与Python解析树一起使用的常量.
                                                             (line  146)
* tilt() (在 turtle 模块中):             外观.               (line   92)
* tiltangle() (在 turtle 模块中):        外观.               (line  126)
* time (datetime 中的类):                time 对象.          (line    9)
* time (ssl.SSLSession 属性):            SSL 会话.           (line   14)
* time (模块):                           time --- 时间的访问和转换.
                                                             (line    6)
* time() (asyncio.loop 方法):            调度延迟回调.       (line   50)
* time() (datetime.datetime 方法):       datetime 对象.      (line  360)
* time() (在 time 模块中):               函数<2>.            (line  394)
* Time2Internaldate() (在 imaplib 模块中): imaplib --- IMAP4 协议客户端.
                                                             (line  117)
* timedelta (datetime 中的类):           timedelta 类对象.   (line    8)
* TimedRotatingFileHandler (logging.handlers 中的类): TimedRotatingFileHandler.
                                                             (line    9)
* timegm() (在 calendar 模块中):         calendar --- 日历相关函数.
                                                             (line  310)
* timeit (模块):                         timeit --- 测量小代码片段的执行时间.
                                                             (line    6)
* timeit command line option; -h:        命令行界面<6>.      (line   42)
* timeit command line option; –help:     命令行界面<6>.      (line   42)
* timeit command line option; -n N:      命令行界面<6>.      (line   12)
* timeit command line option; –number=N: 命令行界面<6>.      (line   12)
* timeit command line option; -p:        命令行界面<6>.      (line   24)
* timeit command line option; –process:  命令行界面<6>.      (line   24)
* timeit command line option; -r N:      命令行界面<6>.      (line   16)
* timeit command line option; –repeat=N: 命令行界面<6>.      (line   16)
* timeit command line option; -s S:      命令行界面<6>.      (line   20)
* timeit command line option; –setup=S:  命令行界面<6>.      (line   20)
* timeit command line option; -u:        命令行界面<6>.      (line   32)
* timeit command line option; –unit=U:   命令行界面<6>.      (line   32)
* timeit command line option; -v:        命令行界面<6>.      (line   38)
* timeit command line option; –verbose:  命令行界面<6>.      (line   38)
* timeit() (timeit.Timer 方法):          Python 接口.        (line   58)
* timeit() (在 timeit 模块中):           Python 接口.        (line    8)
* timeout:                               异常<11>.           (line   34)
* timeout (socketserver.BaseServer 属性): Server 对象<2>.    (line  114)
* timeout (ssl.SSLSession 属性):         SSL 会话.           (line   16)
* timeout (subprocess.TimeoutExpired 属性): 使用 subprocess 模块.
                                                             (line  148)
* timeout() (curses.window 方法):        Window 对象.        (line  478)
* TimeoutError:                          OS 异常.            (line   92)
* TimeoutError <1>:                      Process 和异常.     (line  191)
* TimeoutError <2>:                      Exception类.        (line   10)
* TimeoutError <3>:                      异常<9>.            (line   10)
* TimeoutExpired:                        使用 subprocess 模块.
                                                             (line  139)
* TIMEOUT_MAX() (在 threading 模块中):   threading --- 基于线程的并行.
                                                             (line  135)
* TIMEOUT_MAX() (在 _thread 模块中):     _thread --- 底层多线程 API.
                                                             (line   94)
* Timer (threading 中的类):              定时器对象.         (line   22)
* Timer (timeit 中的类):                 Python 接口.        (line   35)
* TimerHandle (asyncio 中的类):          回调处理.           (line   22)
* times() (在 os 模块中):                进程管理.           (line  573)
* TIMESTAMP (py_compile.PycInvalidationMode 属性): py_compile --- 编译 Python 源文件.
                                                             (line   83)
* timestamp() (datetime.datetime 方法):  datetime 对象.      (line  491)
* timetuple() (datetime.date 方法):      date 对象.          (line  165)
* timetuple() (datetime.datetime 方法):  datetime 对象.      (line  450)
* timetz() (datetime.datetime 方法):     datetime 对象.      (line  368)
* timezone (datetime 中的类):            timezone 对象.      (line   12)
* timezone() (在 time 模块中):           时区常量.           (line   16)
* time_ns() (在 time 模块中):            函数<2>.            (line  429)
* title() (bytearray 方法):              bytes 和 bytearray 操作.
                                                             (line  534)
* title() (bytes 方法):                  bytes 和 bytearray 操作.
                                                             (line  534)
* title() (str 方法):                    字符串的方法<2>.    (line  471)
* title() (在 turtle 模块中):            Screen 专有方法 而非继承自 TurtleScreen.
                                                             (line   45)
* Tix:                                   tkinter tix --- TK扩展包.
                                                             (line    8)
* tixCommand (tkinter.tix 中的类):       Tix Commands.       (line    6)
* tix_addbitmapdir() (tkinter.tix.tixCommand 方法): Tix Commands.
                                                             (line   47)
* tix_cget() (tkinter.tix.tixCommand 方法): Tix Commands.    (line   32)
* tix_configure() (tkinter.tix.tixCommand 方法): Tix Commands.
                                                             (line   20)
* tix_filedialog() (tkinter.tix.tixCommand 方法): Tix Commands.
                                                             (line   57)
* tix_getbitmap() (tkinter.tix.tixCommand 方法): Tix Commands.
                                                             (line   37)
* tix_getimage() (tkinter.tix.tixCommand 方法): Tix Commands.
                                                             (line   68)
* tix_option_get() (tkinter.tix.tixCommand 方法): Tix Commands.
                                                             (line   82)
* tix_resetoptions() (tkinter.tix.tixCommand 方法): Tix Commands.
                                                             (line   86)
* Tk:                                    Tk图形用户界面 GUI. (line    6)
* Tk (tkinter 中的类):                   Tkinter 模块.       (line   22)
* Tk (tkinter.tix 中的类):               Using Tix.          (line    6)
* Tk Option Data Types:                  Tk Option Data Types.
                                                             (line    6)
* Tkinter:                               Tk图形用户界面 GUI. (line    6)
* tkinter (模块):                        tkinter --- Tcl/Tk的Python接口.
                                                             (line    6)
* tkinter.scrolledtext (模块):           tkinter scrolledtext --- 滚动文字控件.
                                                             (line    6)
* tkinter.tix (模块):                    tkinter tix --- TK扩展包.
                                                             (line    6)
* tkinter.ttk (模块):                    tkinter ttk --- Tk主题小部件.
                                                             (line    6)
* TK_LIBRARY:                            我怎样“冻结”Tkinter程序？.
                                                             (line   11)
* TList (tkinter.tix 中的类):            Tabular ListBox.    (line    6)
* TLS:                                   ssl --- 套接字对象的TLS/SSL封装.
                                                             (line    8)
* TLSv1 (ssl.TLSVersion 属性):           常量<9>.            (line  486)
* TLSv1_1 (ssl.TLSVersion 属性):         常量<9>.            (line  488)
* TLSv1_2 (ssl.TLSVersion 属性):         常量<9>.            (line  490)
* TLSv1_3 (ssl.TLSVersion 属性):         常量<9>.            (line  492)
* TLSVersion (ssl 中的类):               常量<9>.            (line  469)
* TMP:                                   tempfile --- 生成临时文件和目录.
                                                             (line  202)
* TMPDIR:                                tempfile --- 生成临时文件和目录.
                                                             (line  198)
* ToASCII() (在 encodings.idna 模块中):  encodings idna --- 应用程序中的国际化域名.
                                                             (line   43)
* tobuf() (tarfile.TarInfo 方法):        TarInfo 对象.       (line   28)
* tobytes() (array.array 方法):          array --- 高效的数值数组.
                                                             (line  192)
* tobytes() (memoryview 方法):           内存视图.           (line  145)
* today() (datetime.date 类方法):        date 对象.          (line   26)
* today() (datetime.datetime 类方法):    datetime 对象.      (line   44)
* tofile() (array.array 方法):           array --- 高效的数值数组.
                                                             (line  200)
* token:                                 词法分析.           (line    6)
* token (shlex.shlex 属性):              shlex Objects.      (line  172)
* token (模块):                          token --- 与Python解析树一起使用的常量.
                                                             (line    6)
* TokenError:                            对输入进行解析标记. (line  106)
* tokenize (模块):                       tokenize --- 对 Python 代码使用的标记解析器.
                                                             (line    6)
* tokenize command line option; -e:      Command-Line Usage<2>.
                                                             (line   19)
* tokenize command line option; –exact:  Command-Line Usage<2>.
                                                             (line   19)
* tokenize command line option; -h:      Command-Line Usage<2>.
                                                             (line   15)
* tokenize command line option; –help:   Command-Line Usage<2>.
                                                             (line   15)
* tokenize() (在 tokenize 模块中):       对输入进行解析标记. (line    8)
* token_bytes() (在 secrets 模块中):     生成凭据.           (line    9)
* token_hex() (在 secrets 模块中):       生成凭据.           (line   17)
* token_urlsafe() (在 secrets 模块中):   生成凭据.           (line   26)
* tok_name() (在 token 模块中):          token --- 与Python解析树一起使用的常量.
                                                             (line   17)
* tolist() (array.array 方法):           array --- 高效的数值数组.
                                                             (line  204)
* tolist() (memoryview 方法):            内存视图.           (line  181)
* tolist() (parser.ST 方法):             ST 对象.            (line   29)
* tomono() (在 audioop 模块中):          audioop --- 处理原始音频数据.
                                                             (line  175)
* toordinal() (datetime.date 方法):      date 对象.          (line  179)
* toordinal() (datetime.datetime 方法):  datetime 对象.      (line  487)
* top() (curses.panel.Panel 方法):       Panel 对象.         (line   49)
* top() (poplib.POP3 方法):              POP3 对象.          (line   79)
* toprettyxml() (xml.dom.minidom.Node 方法): DOM 对象.       (line   48)
* top_panel() (在 curses.panel 模块中):  函数<4>.            (line   18)
* toreadonly() (memoryview 方法):        内存视图.           (line  196)
* tostereo() (在 audioop 模块中):        audioop --- 处理原始音频数据.
                                                             (line  180)
* tostring() (array.array 方法):         array --- 高效的数值数组.
                                                             (line  208)
* tostring() (在 xml.etree.ElementTree 模块中): 函数<6>.     (line  176)
* tostringlist() (在 xml.etree.ElementTree 模块中): 函数<6>. (line  195)
* total_changes (sqlite3.Connection 属性): 连接对象（Connection）.
                                                             (line  344)
* total_ordering() (在 functools 模块中): functools --- 高阶函数和可调用对象上的操作.
                                                             (line  152)
* total_seconds() (datetime.timedelta 方法): timedelta 类对象.
                                                             (line  225)
* totuple() (parser.ST 方法):            ST 对象.            (line   33)
* touch() (pathlib.Path 方法):           方法<2>.            (line  384)
* touchline() (curses.window 方法):      Window 对象.        (line  486)
* touchwin() (curses.window 方法):       Window 对象.        (line  492)
* tounicode() (array.array 方法):        array --- 高效的数值数组.
                                                             (line  214)
* ToUnicode() (在 encodings.idna 模块中): encodings idna --- 应用程序中的国际化域名.
                                                             (line   48)
* towards() (在 turtle 模块中):          获取海龟的状态.     (line   14)
* toxml() (xml.dom.minidom.Node 方法):   DOM 对象.           (line   36)
* to_bytes() (int 方法):                 整数类型的附加方法. (line   33)
* to_eng_string() (decimal.Context 方法): 上下文对象.        (line  448)
* to_eng_string() (decimal.Decimal 方法): Decimal 对象.      (line  472)
* to_integral() (decimal.Decimal 方法):  Decimal 对象.       (line  482)
* to_integral_exact() (decimal.Context 方法): 上下文对象.    (line  455)
* to_integral_exact() (decimal.Decimal 方法): Decimal 对象.  (line  487)
* to_integral_value() (decimal.Decimal 方法): Decimal 对象.  (line  494)
* to_sci_string() (decimal.Context 方法): 上下文对象.        (line  459)
* tparm() (在 curses 模块中):            函数<3>.            (line  407)
* Trace (trace 中的类):                  编程接口.           (line    6)
* Trace (tracemalloc 中的类):            跟踪.               (line    6)
* trace (模块):                          trace --- 跟踪Python语句的执行.
                                                             (line    6)
* trace command line option; -c:         Main options.       (line   12)
* trace command line option; -C:         Modifiers.          (line   11)
* trace command line option; –count:     Main options.       (line   12)
* trace command line option; –coverdir=<dir>: Modifiers.     (line   11)
* trace command line option; -f:         Modifiers.          (line    6)
* trace command line option; –file=<file>: Modifiers.        (line    6)
* trace command line option; -g:         Modifiers.          (line   33)
* trace command line option; –help:      Command-Line Usage. (line   15)
* trace command line option; –ignore-dir=<dir>: Filters.     (line   14)
* trace command line option; –ignore-module=<mod>: Filters.  (line    8)
* trace command line option; -l:         Main options.       (line   23)
* trace command line option; –listfuncs: Main options.       (line   23)
* trace command line option; -m:         Modifiers.          (line   17)
* trace command line option; –missing:   Modifiers.          (line   17)
* trace command line option; –no-report: Modifiers.          (line   27)
* trace command line option; -r:         Main options.       (line   27)
* trace command line option; -R:         Modifiers.          (line   27)
* trace command line option; –report:    Main options.       (line   27)
* trace command line option; -s:         Modifiers.          (line   22)
* trace command line option; –summary:   Modifiers.          (line   22)
* trace command line option; -t:         Main options.       (line   19)
* trace command line option; -T:         Main options.       (line   33)
* trace command line option; –timing:    Modifiers.          (line   33)
* trace command line option; –trace:     Main options.       (line   19)
* trace command line option; –trackcalls: Main options.      (line   33)
* trace command line option; –version:   Command-Line Usage. (line   19)
* trace function:                        threading --- 基于线程的并行.
                                                             (line  108)
* trace function <1>:                    sys --- 系统相关的参数和函数.
                                                             (line  630)
* trace function <2>:                    sys --- 系统相关的参数和函数.
                                                             (line 1113)
* trace() (在 inspect 模块中):           The interpreter stack.
                                                             (line   91)
* Traceback (tracemalloc 中的类):        回溯<4>.            (line    6)
* traceback (tracemalloc.Statistic 属性): 统计.              (line   23)
* traceback (tracemalloc.StatisticDiff 属性): StatisticDiff. (line   38)
* traceback (tracemalloc.Trace 属性):    跟踪.               (line   27)
* traceback (模块):                      traceback --- 打印或检索堆栈回溯.
                                                             (line    6)
* TracebackException (traceback 中的类): TracebackException Objects.
                                                             (line   11)
* tracebacklimit() (在 sys 模块中):      sys --- 系统相关的参数和函数.
                                                             (line 1338)
* tracebacks; in CGI scripts:            cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line    8)
* TracebackType (types 中的类):          标准解释器类型.     (line  159)
* traceback_limit (tracemalloc.Snapshot 属性): 快照.         (line   82)
* traceback_limit (wsgiref.handlers.BaseHandler 属性): wsgiref handlers -- server/gateway base classes.
                                                             (line  218)
* tracemalloc (模块):                    tracemalloc --- 跟踪内存分配.
                                                             (line    6)
* tracer() (在 turtle 模块中):           动画控制.           (line   22)
* traces (tracemalloc.Snapshot 属性):    快照.               (line   88)
* trace_dispatch() (bdb.Bdb 方法):       bdb --- Debugger framework.
                                                             (line  111)
* trailing; comma:                       表达式列表.         (line   20)
* transfercmd() (ftplib.FTP 方法):       FTP 对象.           (line  115)
* TransientResource (test.support 中的类): test support --- Utilities for the Python test suite.
                                                             (line 1015)
* transient_internet() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  462)
* translate() (bytearray 方法):          bytes 和 bytearray 操作.
                                                             (line  179)
* translate() (bytes 方法):              bytes 和 bytearray 操作.
                                                             (line  179)
* translate() (str 方法):                字符串的方法<2>.    (line  499)
* translate() (在 fnmatch 模块中):       fnmatch --- Unix 文件名模式匹配.
                                                             (line   66)
* translation() (在 gettext 模块中):     基于类的 API.       (line   35)
* Transport (asyncio 中的类):            传输层级.           (line   28)
* transport (asyncio.StreamWriter 属性): StreamWriter.       (line   52)
* Transport Layer Security:              ssl --- 套接字对象的TLS/SSL封装.
                                                             (line    8)
* traverseproc (C 类型):                 使对象类型支持循环垃圾回收.
                                                             (line   85)
* Tree (tkinter.tix 中的类):             Hierarchical ListBox.
                                                             (line   20)
* TreeBuilder (xml.etree.ElementTree 中的类): TreeBuilder 对象.
                                                             (line    6)
* Treeview (tkinter.ttk 中的类):         ttk Treeview.       (line    6)
* triangular() (在 random 模块中):       实值分布.           (line   21)
* triple-quoted string:                  字符串和字节串字面值.
                                                             (line   34)
* triple-quoted string – 三引号字符串:   术语对照表.         (line 1004)
* True:                                  标准类型层级结构.   (line   69)
* true:                                  逻辑值检测.         (line    9)
* True <1>:                              逻辑值检测.         (line   19)
* True <2>:                              布尔值.             (line   12)
* True (內置变量):                       内置常量.           (line   13)
* truediv() (在 operator 模块中):        operator --- 标准运算符替代函数.
                                                             (line  146)
* trunc() (in module math):              数字类型 --- int float complex.
                                                             (line   92)
* trunc() (在 math 模块中):              数论与表示函数.     (line  191)
* truncate() (io.IOBase 方法):           I/O 基类.           (line  118)
* truncate() (在 os 模块中):             文件和目录.         (line 1235)
* truth() (在 operator 模块中):          operator --- 标准运算符替代函数.
                                                             (line   47)
* truth; value:                          逻辑值检测.         (line    6)
* ttk:                                   tkinter ttk --- Tk主题小部件.
                                                             (line    8)
* tty (模块):                            tty --- 终端控制功能.
                                                             (line    6)
* tty; I/O control:                      termios --- POSIX 风格的 tty 控制.
                                                             (line    6)
* ttyname() (在 os 模块中):              文件描述符操作.     (line  598)
* tuple (內置类):                        元组.               (line   11)
* Tuple() (在 typing 模块中):            类 函数和修饰器.    (line  781)
* tuple2st() (在 parser 模块中):         创建 ST 对象.       (line   51)
* tuple_params (2to3 fixer):             修复器.             (line  293)
* Turtle (turtle 中的类):                公共类.             (line   16)
* turtle (模块):                         turtle --- 海龟绘图.
                                                             (line    6)
* turtledemo (模块):                     turtledemo --- 演示脚本集.
                                                             (line    6)
* turtles() (在 turtle 模块中):          设置与特殊方法.     (line   92)
* TurtleScreen (turtle 中的类):          公共类.             (line   21)
* turtlesize() (在 turtle 模块中):       外观.               (line   47)
* type:                                  标准类型层级结构.   (line    6)
* type (optparse.Option 属性):           Option attributes.  (line   19)
* type (socket.socket 属性):             套接字对象.         (line  500)
* type (tarfile.TarInfo 属性):           TarInfo 对象.       (line   55)
* Type (typing 中的类):                  类 函数和修饰器.    (line   98)
* type (urllib.request.Request 属性):    Request 对象.       (line   19)
* type (內置类):                         内置函数.           (line 1400)
* type – 类型:                           术语对照表.         (line 1011)
* type alias – 类型别名:                 术语对照表.         (line 1017)
* type hint – 类型提示:                  术语对照表.         (line 1040)
* type of an object:                     对象、值与类型.     (line   10)
* type; hierarchy:                       标准类型层级结构.   (line    6)
* typeahead() (在 curses 模块中):        函数<3>.            (line  413)
* typecode (array.array 属性):           array --- 高效的数值数组.
                                                             (line   96)
* typecodes() (在 array 模块中):         array --- 高效的数值数组.
                                                             (line   85)
* TypedDict (typing 中的类):             类 函数和修饰器.    (line  512)
* TYPED_ACTIONS (optparse.Option 属性):  Adding new actions. (line   39)
* typed_subpart_iterator() (在 email.iterators 模块中): email iterators 迭代器.
                                                             (line   22)
* TypeError:                             具体异常.           (line  276)
* types (2to3 fixer):                    修复器.             (line  297)
* TYPES (optparse.Option 属性):          Adding new types.   (line   11)
* types (模块):                          types --- 动态类型创建和内置类型名称.
                                                             (line    6)
* types, internal:                       标准类型层级结构.   (line  487)
* types_map (mimetypes.MimeTypes 属性):  MimeTypes 对象.     (line   31)
* types_map() (在 mimetypes 模块中):     mimetypes --- 映射文件夹到 MIME 类型.
                                                             (line  118)
* types_map_inv (mimetypes.MimeTypes 属性): MimeTypes 对象.  (line   37)
* TypeVar (typing 中的类):               类 函数和修饰器.    (line    8)
* TYPE_CHECKER (optparse.Option 属性):   Adding new types.   (line   16)
* TYPE_CHECKING() (在 typing 模块中):    类 函数和修饰器.    (line  884)
* type_check_only() (在 typing 模块中):  类 函数和修饰器.    (line  674)
* TYPE_COMMENT() (在 token 模块中):      token --- 与Python解析树一起使用的常量.
                                                             (line  246)
* TYPE_IGNORE() (在 token 模块中):       token --- 与Python解析树一起使用的常量.
                                                             (line  244)
* typing (模块):                         typing --- 类型标注支持.
                                                             (line    6)
* TZ:                                    函数<2>.            (line  438)
* TZ <1>:                                函数<2>.            (line  439)
* TZ <2>:                                函数<2>.            (line  446)
* TZ <3>:                                函数<2>.            (line  450)
* TZ <4>:                                函数<2>.            (line  452)
* TZ <5>:                                函数<2>.            (line  505)
* tzinfo (datetime 中的类):              tzinfo 对象.        (line    6)
* tzinfo (datetime.datetime 属性):       datetime 对象.      (line  270)
* tzinfo (datetime.time 属性):           time 对象.          (line   62)
* tzname() (datetime.datetime 方法):     datetime 对象.      (line  444)
* tzname() (datetime.time 方法):         time 对象.          (line  217)
* tzname() (datetime.timezone 方法):     timezone 对象.      (line   34)
* tzname() (datetime.tzinfo 方法):       tzinfo 对象.        (line  106)
* tzname() (在 time 模块中):             时区常量.           (line   21)
* tzset() (在 time 模块中):              函数<2>.            (line  436)
* T_FMT() (在 locale 模块中):            locale --- 国际化服务.
                                                             (line  183)
* T_FMT_AMPM() (在 locale 模块中):       locale --- 国际化服务.
                                                             (line  189)
* u"; string literal:                    字面值.             (line    8)
* u’; string literal:                    字面值.             (line    8)
* u-LAW:                                 audioop --- 处理原始音频数据.
                                                             (line   15)
* u-LAW <1>:                             aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  140)
* u-LAW <2>:                             sndhdr --- 推测声音文件的类型.
                                                             (line    8)
* ucd_3_2_0() (在 unicodedata 模块中):   unicodedata --- Unicode 数据库.
                                                             (line  108)
* udata (select.kevent 属性):            Kevent 对象.        (line  174)
* UDPServer (socketserver 中的类):       socketserver --- A framework for network servers.
                                                             (line   25)
* UF_APPEND() (在 stat 模块中):          stat --- 解析 stat 结果.
                                                             (line  321)
* UF_COMPRESSED() (在 stat 模块中):      stat --- 解析 stat 结果.
                                                             (line  333)
* UF_HIDDEN() (在 stat 模块中):          stat --- 解析 stat 结果.
                                                             (line  337)
* UF_IMMUTABLE() (在 stat 模块中):       stat --- 解析 stat 结果.
                                                             (line  317)
* UF_NODUMP() (在 stat 模块中):          stat --- 解析 stat 结果.
                                                             (line  313)
* UF_NOUNLINK() (在 stat 模块中):        stat --- 解析 stat 结果.
                                                             (line  329)
* UF_OPAQUE() (在 stat 模块中):          stat --- 解析 stat 结果.
                                                             (line  325)
* UID (plistlib 中的类):                 plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line  160)
* uid (tarfile.TarInfo 属性):            TarInfo 对象.       (line   67)
* uid() (imaplib.IMAP4 方法):            IMAP4 Objects.      (line  358)
* uidl() (poplib.POP3 方法):             POP3 对象.          (line   88)
* ulaw2lin() (在 audioop 模块中):        audioop --- 处理原始音频数据.
                                                             (line  185)
* ULONG_MAX:                             整数型对象.         (line  177)
* umask() (在 os 模块中):                进程参数.           (line  422)
* unalias (pdb command):                 调试器命令.         (line  254)
* uname (tarfile.TarInfo 属性):          TarInfo 对象.       (line   75)
* uname() (在 os 模块中):                进程参数.           (line  426)
* uname() (在 platform 模块中):          跨平台.             (line  122)
* unary; arithmetic; operation:          一元算术和位运算.   (line    6)
* unary; bitwise; operation:             一元算术和位运算.   (line    6)
* unaryfunc (C 类型):                    Slot Type typedefs. (line  109)
* UNARY_INVERT (opcode):                 Python字节码说明.   (line  103)
* UNARY_NEGATIVE (opcode):               Python字节码说明.   (line   95)
* UNARY_NOT (opcode):                    Python字节码说明.   (line   99)
* UNARY_POSITIVE (opcode):               Python字节码说明.   (line   91)
* unbinding; name:                       del 语句<2>.        (line   13)
* UnboundLocalError:                     名称的解析.         (line   14)
* UnboundLocalError <1>:                 具体异常.           (line  289)
* unbuffered I/O:                        内置函数.           (line 1017)
* UNC paths; and os.makedirs():          文件和目录.         (line  408)
* UNCHECKED_HASH (py_compile.PycInvalidationMode 属性): py_compile --- 编译 Python 源文件.
                                                             (line   93)
* unconsumed_tail (zlib.Decompress 属性): zlib --- 与 gzip 兼容的压缩.
                                                             (line  180)
* unctrl() (在 curses 模块中):           函数<3>.            (line  423)
* unctrl() (在 curses.ascii 模块中):     curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  213)
* undefine_macro() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  168)
* Underflow (decimal 中的类):            信号.               (line   84)
* undisplay (pdb command):               调试器命令.         (line  223)
* undo() (在 turtle 模块中):             海龟动作.           (line  277)
* undobufferentries() (在 turtle 模块中): 特殊海龟方法.      (line   68)
* undoc_header (cmd.Cmd 属性):           Cmd 对象.           (line  127)
* unescape() (在 html 模块中):           html --- 超文本标记语言支持.
                                                             (line   21)
* unescape() (在 xml.sax.saxutils 模块中): xml sax saxutils --- SAX 工具集.
                                                             (line   21)
* UnexpectedException:                   调试.               (line  207)
* unexpectedSuccesses (unittest.TestResult 属性): Loading and running tests.
                                                             (line  262)
* unfreeze() (在 gc 模块中):             gc --- 垃圾回收器接口.
                                                             (line  158)
* ungetch() (在 curses 模块中):          函数<3>.            (line  428)
* ungetch() (在 msvcrt 模块中):          控制台 I/O.         (line   38)
* ungetmouse() (在 curses 模块中):       函数<3>.            (line  448)
* ungetwch() (在 msvcrt 模块中):         控制台 I/O.         (line   43)
* unget_wch() (在 curses 模块中):        函数<3>.            (line  440)
* unhexlify() (在 binascii 模块中):      binascii --- 二进制和 ASCII 码互转.
                                                             (line  137)
* Unicode:                               标准类型层级结构.   (line  117)
* Unicode <1>:                           unicodedata --- Unicode 数据库.
                                                             (line    6)
* Unicode <2>:                           codecs --- 编解码器注册和相关基类.
                                                             (line    8)
* unicode (2to3 fixer):                  修复器.             (line  301)
* Unicode Consortium:                    字符串和字节串字面值.
                                                             (line   34)
* Unicode; database:                     unicodedata --- Unicode 数据库.
                                                             (line    6)
* unicodedata (模块):                    unicodedata --- Unicode 数据库.
                                                             (line    6)
* UnicodeDecodeError:                    具体异常.           (line  328)
* UnicodeEncodeError:                    具体异常.           (line  323)
* UnicodeError:                          具体异常.           (line  294)
* UnicodeTranslateError:                 具体异常.           (line  333)
* UnicodeWarning:                        警告.               (line   45)
* unidata_version() (在 unicodedata 模块中): unicodedata --- Unicode 数据库.
                                                             (line  104)
* unified_diff() (在 difflib 模块中):    difflib --- 计算差异的辅助工具.
                                                             (line  254)
* uniform() (在 random 模块中):          实值分布.           (line   13)
* UnimplementedFileMode:                 http client --- HTTP 协议客户端.
                                                             (line  135)
* Union (ctypes 中的类):                 结构化数据类型.     (line    6)
* union() (frozenset 方法):              集合类型 --- set frozenset.
                                                             (line   86)
* Union() (在 typing 模块中):            类 函数和修饰器.    (line  730)
* unique() (在 enum 模块中):             确保唯一的枚举值.   (line    9)
* unittest (模块):                       unittest --- 单元测试框架.
                                                             (line    6)
* unittest command line option; -b:      命令行选项<5>.      (line    8)
* unittest command line option; –buffer: 命令行选项<5>.      (line    8)
* unittest command line option; -c:      命令行选项<5>.      (line   14)
* unittest command line option; –catch:  命令行选项<5>.      (line   14)
* unittest command line option; -f:      命令行选项<5>.      (line   23)
* unittest command line option; –failfast: 命令行选项<5>.    (line   23)
* unittest command line option; -k:      命令行选项<5>.      (line   27)
* unittest command line option; –locals: 命令行选项<5>.      (line   41)
* unittest-discover command line option; -p: 探索性测试.     (line   33)
* unittest-discover command line option; –pattern pattern: 探索性测试.
                                                             (line   33)
* unittest-discover command line option; -s: 探索性测试.     (line   29)
* unittest-discover command line option; –start-directory directory: 探索性测试.
                                                             (line   29)
* unittest-discover command line option; -t: 探索性测试.     (line   37)
* unittest-discover command line option; –top-level-directory directory: 探索性测试.
                                                             (line   37)
* unittest-discover command line option; -v: 探索性测试.     (line   25)
* unittest-discover command line option; –verbose: 探索性测试.
                                                             (line   25)
* unittest.mock (模块):                  unittest mock --- 模拟对象库.
                                                             (line    6)
* universal newlines – 通用换行:         术语对照表.         (line 1053)
* universal newlines; bytearray.splitlines method: bytes 和 bytearray 操作.
                                                             (line  490)
* universal newlines; bytes.splitlines method: bytes 和 bytearray 操作.
                                                             (line  490)
* universal newlines; csv.reader function: 模块内容<3>.      (line    8)
* universal newlines; importlib.abc.InspectLoader.get_source method: importlib abc —— 关于导入的抽象基类.
                                                             (line  345)
* universal newlines; io.IncrementalNewlineDecoder class: 文本 I/O<2>.
                                                             (line  203)
* universal newlines; io.TextIOWrapper class: 文本 I/O<2>.   (line  106)
* universal newlines; open() built-in function: 内置函数.    (line  967)
* universal newlines; str.splitlines method: 字符串的方法<2>.
                                                             (line  370)
* universal newlines; subprocess module: 常用参数.           (line   25)
* universal newlines; What’s new:        PEP 3116 新 I/O 库. (line   42)
* universal newlines; What’s new <1>:    新增，改进和删除的模块.
                                                             (line  136)
* universal newlines; What’s new <2>:    PEP 324 新的子进程模块.
                                                             (line   36)
* universal newlines; What’s new <3>:    PEP 277 Unicode file name support for Windows NT.
                                                             (line   36)
* UNIX:                                  完整的 Python 程序. (line   19)
* UNIX; file control:                    fcntl --- The fcntl and ioctl system calls.
                                                             (line    6)
* UNIX; I/O control:                     fcntl --- The fcntl and ioctl system calls.
                                                             (line    6)
* UnixDatagramServer (socketserver 中的类): socketserver --- A framework for network servers.
                                                             (line   32)
* UnixStreamServer (socketserver 中的类): socketserver --- A framework for network servers.
                                                             (line   32)
* unix_dialect (csv 中的类):             模块内容<3>.        (line  168)
* unix_shell() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line   44)
* unknown (uuid.SafeUUID 属性):          uuid --- UUID objects according to RFC 4122.
                                                             (line   40)
* UnknownHandler (urllib.request 中的类): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  361)
* UnknownProtocol:                       http client --- HTTP 协议客户端.
                                                             (line  127)
* UnknownTransferEncoding:               http client --- HTTP 协议客户端.
                                                             (line  131)
* unknown_decl() (html.parser.HTMLParser 方法): HTMLParser 方法.
                                                             (line  111)
* unknown_open() (urllib.request.BaseHandler 方法): BaseHandler 对象.
                                                             (line   49)
* unknown_open() (urllib.request.UnknownHandler 方法): UnknownHandler 对象.
                                                             (line    6)
* unlink() (multiprocessing.shared_memory.SharedMemory 方法): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   55)
* unlink() (pathlib.Path 方法):          方法<2>.            (line  391)
* unlink() (xml.dom.minidom.Node 方法):  DOM 对象.           (line    9)
* unlink() (在 os 模块中):               文件和目录.         (line 1252)
* unlink() (在 test.support 模块中):     test support --- Utilities for the Python test suite.
                                                             (line  171)
* unload() (在 test.support 模块中):     test support --- Utilities for the Python test suite.
                                                             (line  167)
* unlock() (mailbox.Babyl 方法):         Babyl.              (line   47)
* unlock() (mailbox.Mailbox 方法):       Mailbox 对象.       (line  210)
* unlock() (mailbox.Maildir 方法):       Maildir.            (line   90)
* unlock() (mailbox.mbox 方法):          mbox.               (line   32)
* unlock() (mailbox.MH 方法):            MH.                 (line   75)
* unlock() (mailbox.MMDF 方法):          MMDF.               (line   29)
* unpack() (struct.Struct 方法):         类<2>.              (line   30)
* unpack() (在 struct 模块中):           函数和异常.         (line   23)
* Unpacker (xdrlib 中的类):              xdrlib --- 编码与解码 XDR 数据.
                                                             (line   22)
* unpacking; dictionary:                 字典显示.           (line   19)
* unpacking; in function calls:          调用.               (line   55)
* unpack_archive() (在 shutil 模块中):   归档操作.           (line   98)
* unpack_array() (xdrlib.Unpacker 方法): Unpacker 对象.      (line   81)
* unpack_bytes() (xdrlib.Unpacker 方法): Unpacker 对象.      (line   63)
* unpack_double() (xdrlib.Unpacker 方法): Unpacker 对象.     (line   38)
* UNPACK_EX (opcode):                    Python字节码说明.   (line  459)
* unpack_farray() (xdrlib.Unpacker 方法): Unpacker 对象.     (line   75)
* unpack_float() (xdrlib.Unpacker 方法): Unpacker 对象.      (line   34)
* unpack_fopaque() (xdrlib.Unpacker 方法): Unpacker 对象.    (line   49)
* unpack_from() (struct.Struct 方法):    类<2>.              (line   35)
* unpack_from() (在 struct 模块中):      函数和异常.         (line   30)
* unpack_fstring() (xdrlib.Unpacker 方法): Unpacker 对象.    (line   44)
* unpack_list() (xdrlib.Unpacker 方法):  Unpacker 对象.      (line   69)
* unpack_opaque() (xdrlib.Unpacker 方法): Unpacker 对象.     (line   58)
* UNPACK_SEQUENCE (opcode):              Python字节码说明.   (line  454)
* unpack_string() (xdrlib.Unpacker 方法): Unpacker 对象.     (line   53)
* unparsedEntityDecl() (xml.sax.handler.DTDHandler 方法): DTDHandler 对象.
                                                             (line   12)
* UnparsedEntityDeclHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  207)
* Unpickler (pickle 中的类):             模块接口.           (line  201)
* UnpicklingError:                       模块接口.           (line   96)
* unquote() (在 email.utils 模块中):     email utils 其他工具.
                                                             (line   42)
* unquote() (在 urllib.parse 模块中):    URL Quoting.        (line   60)
* unquote_plus() (在 urllib.parse 模块中): URL Quoting.      (line   76)
* unquote_to_bytes() (在 urllib.parse 模块中): URL Quoting.  (line   86)
* unraisablehook() (在 sys 模块中):      sys --- 系统相关的参数和函数.
                                                             (line 1344)
* unreachable object:                    对象、值与类型.     (line   29)
* unreadline() (distutils.text_file.TextFile 方法): distutils text_file --- The TextFile class.
                                                             (line  130)
* unrecognized escape sequence:          字符串和字节串字面值.
                                                             (line  140)
* unregister() (select.devpoll 方法):    /dev/poll 轮询对象. (line   50)
* unregister() (select.epoll 方法):      边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   87)
* unregister() (select.poll 方法):       Poll 对象.          (line   57)
* unregister() (selectors.BaseSelector 方法): 类<3>.         (line   73)
* unregister() (在 atexit 模块中):       atexit --- 退出处理器.
                                                             (line   35)
* unregister() (在 faulthandler 模块中): Dumping the traceback on a user signal.
                                                             (line   23)
* unregister_archive_format() (在 shutil 模块中): 归档操作.  (line   94)
* unregister_dialect() (在 csv 模块中):  模块内容<3>.        (line   66)
* unregister_unpack_format() (在 shutil 模块中): 归档操作.   (line  132)
* unsafe (uuid.SafeUUID 属性):           uuid --- UUID objects according to RFC 4122.
                                                             (line   36)
* unset() (test.support.EnvironmentVarGuard 方法): test support --- Utilities for the Python test suite.
                                                             (line 1040)
* unsetenv() (在 os 模块中):             进程参数.           (line  452)
* UnstructuredHeader (email.headerregistry 中的类): email headerregistry 自定义标头对象.
                                                             (line   94)
* unsubscribe() (imaplib.IMAP4 方法):    IMAP4 Objects.      (line  365)
* UnsupportedOperation:                  高阶模块接口.       (line   38)
* until (pdb command):                   调试器命令.         (line  144)
* untokenize() (在 tokenize 模块中):     对输入进行解析标记. (line   56)
* untouchwin() (curses.window 方法):     Window 对象.        (line  496)
* unused_data (bz2.BZ2Decompressor 属性): 增量压缩和解压.    (line   67)
* unused_data (lzma.LZMADecompressor 属性): 在内存中压缩和解压缩数据.
                                                             (line  136)
* unused_data (zlib.Decompress 属性):    zlib --- 与 gzip 兼容的压缩.
                                                             (line  174)
* unverifiable (urllib.request.Request 属性): Request 对象.  (line   43)
* unwrap() (ssl.SSLSocket 方法):         SSL 套接字.         (line  237)
* unwrap() (在 inspect 模块中):          类与函数<2>.        (line  186)
* unwrap() (在 urllib.parse 模块中):     URL 解析.           (line  368)
* up (pdb command):                      调试器命令.         (line   51)
* up() (在 turtle 模块中):               绘图状态.           (line   12)
* update() (collections.Counter 方法):   Counter 对象.       (line   98)
* update() (dict 方法):                  映射类型 --- dict.  (line  187)
* update() (frozenset 方法):             集合类型 --- set frozenset.
                                                             (line  151)
* update() (hashlib.hash 方法):          哈希算法.           (line  105)
* update() (hmac.HMAC 方法):             hmac --- 基于密钥的消息验证.
                                                             (line   42)
* update() (http.cookies.Morsel 方法):   Morsel 对象.        (line   94)
* update() (mailbox.Mailbox 方法):       Mailbox 对象.       (line  185)
* update() (mailbox.Maildir 方法):       Maildir.            (line   77)
* update() (trace.CoverageResults 方法): 编程接口.           (line   52)
* update() (在 turtle 模块中):           动画控制.           (line   43)
* update_authenticated() (urllib.request.HTTPPasswordMgrWithPriorAuth 方法): HTTPPasswordMgrWithPriorAuth 对象.
                                                             (line   22)
* update_lines_cols() (在 curses 模块中): 函数<3>.           (line  434)
* update_panels() (在 curses.panel 模块中): 函数<4>.         (line   22)
* update_visible() (mailbox.BabylMessage 方法): BabylMessage.
                                                             (line   72)
* update_wrapper() (在 functools 模块中): functools --- 高阶函数和可调用对象上的操作.
                                                             (line  433)
* upper() (bytearray 方法):              bytes 和 bytearray 操作.
                                                             (line  572)
* upper() (bytes 方法):                  bytes 和 bytearray 操作.
                                                             (line  572)
* upper() (str 方法):                    字符串的方法<2>.    (line  514)
* urandom() (在 os 模块中):              随机数<2>.          (line   26)
* URL:                                   cgi --- 通用网关接口支持.
                                                             (line    8)
* URL <1>:                               urllib parse 用于解析 URL.
                                                             (line    8)
* URL <2>:                               urllib robotparser --- robots txt 语法分析程序.
                                                             (line    8)
* URL <3>:                               http server --- HTTP 服务器.
                                                             (line    8)
* url (xmlrpc.client.ProtocolError 属性): ProtocolError 对象.
                                                             (line   13)
* url2pathname() (在 urllib.request 模块中): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  134)
* URL; parsing:                          urllib parse 用于解析 URL.
                                                             (line    8)
* urlcleanup() (在 urllib.request 模块中): 已停用的接口.     (line   56)
* urldefrag() (在 urllib.parse 模块中):  URL 解析.           (line  342)
* urlencode() (在 urllib.parse 模块中):  URL Quoting.        (line   98)
* URLError:                              urllib error --- urllib request 引发的异常类.
                                                             (line   15)
* urljoin() (在 urllib.parse 模块中):    URL 解析.           (line  312)
* urllib (2to3 fixer):                   修复器.             (line  305)
* urllib (模块):                         urllib --- URL 处理模块.
                                                             (line    6)
* urllib.error (模块):                   urllib error --- urllib request 引发的异常类.
                                                             (line    6)
* urllib.parse (模块):                   urllib parse 用于解析 URL.
                                                             (line    6)
* urllib.request (模块):                 urllib request --- 用于打开 URL 的可扩展库.
                                                             (line    6)
* urllib.response (模块):                urllib response --- urllib 使用的 Response 类.
                                                             (line    6)
* urllib.robotparser (模块):             urllib robotparser --- robots txt 语法分析程序.
                                                             (line    6)
* urlopen() (在 urllib.request 模块中):  urllib request --- 用于打开 URL 的可扩展库.
                                                             (line   20)
* URLopener (urllib.request 中的类):     已停用的接口.       (line   61)
* urlparse() (在 urllib.parse 模块中):   URL 解析.           (line    9)
* urlretrieve() (在 urllib.request 模块中): 已停用的接口.    (line    9)
* urlsafe_b64decode() (在 base64 模块中): base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line   78)
* urlsafe_b64encode() (在 base64 模块中): base64 --- Base16 Base32 Base64 Base85 数据编码.
                                                             (line   72)
* urlsplit() (在 urllib.parse 模块中):   URL 解析.           (line  232)
* urlunparse() (在 urllib.parse 模块中): URL 解析.           (line  224)
* urlunsplit() (在 urllib.parse 模块中): URL 解析.           (line  303)
* urn (uuid.UUID 属性):                  uuid --- UUID objects according to RFC 4122.
                                                             (line  134)
* UseForeignDTD() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line   51)
* USER:                                  getpass --- 便携式密码输入工具.
                                                             (line   35)
* user() (poplib.POP3 方法):             POP3 对象.          (line   29)
* user-defined; function:                标准类型层级结构.   (line  228)
* user-defined; function; call:          调用.               (line   99)
* user-defined; method:                  标准类型层级结构.   (line  298)
* user; effective id:                    进程参数.           (line  157)
* user; id:                              进程参数.           (line  276)
* user; id, setting:                     进程参数.           (line  406)
* UserDict (collections 中的类):         UserDict 对象.      (line   10)
* UserList (collections 中的类):         UserList 对象.      (line   13)
* USERNAME:                              进程参数.           (line  200)
* USERNAME <1>:                          getpass --- 便携式密码输入工具.
                                                             (line   35)
* username (email.headerregistry.Address 属性): email headerregistry 自定义标头对象.
                                                             (line  368)
* USERPROFILE:                           os path.            (line   13)
* USERPROFILE <1>:                       Python API 的变化.  (line  102)
* USERPROFILE <2>:                       Windows<10>.        (line   13)
* USERPROFILE <3>:                       os path --- 常用路径操作.
                                                             (line  128)
* USERPROFILE <4>:                       Location and names of config files.
                                                             (line   67)
* userptr() (curses.panel.Panel 方法):   Panel 对象.         (line   53)
* UserString (collections 中的类):       UserString 对象.    (line   10)
* UserWarning:                           警告.               (line   12)
* USER_BASE:                             新增和改进的模块.   (line  469)
* USER_BASE() (在 site 模块中):          模块内容<7>.        (line   28)
* user_call() (bdb.Bdb 方法):            bdb --- Debugger framework.
                                                             (line  211)
* user_exception() (bdb.Bdb 方法):       bdb --- Debugger framework.
                                                             (line  228)
* user_line() (bdb.Bdb 方法):            bdb --- Debugger framework.
                                                             (line  217)
* user_return() (bdb.Bdb 方法):          bdb --- Debugger framework.
                                                             (line  223)
* USER_SITE() (在 site 模块中):          模块内容<7>.        (line   18)
* use_default_colors() (在 curses 模块中): 函数<3>.          (line  460)
* use_env() (在 curses 模块中):          函数<3>.            (line  452)
* use_rawinput (cmd.Cmd 属性):           Cmd 对象.           (line  137)
* USTAR_FORMAT() (在 tarfile 模块中):    tarfile --- 读写tar归档文件.
                                                             (line  198)
* UTC:                                   time --- 时间的访问和转换.
                                                             (line   32)
* utc (datetime.timezone 属性):          timezone 对象.      (line   57)
* utcfromtimestamp() (datetime.datetime 类方法): datetime 对象.
                                                             (line  113)
* utcnow() (datetime.datetime 类方法):   datetime 对象.      (line   71)
* utcoffset() (datetime.datetime 方法):  datetime 对象.      (line  428)
* utcoffset() (datetime.time 方法):      time 对象.          (line  201)
* utcoffset() (datetime.timezone 方法):  timezone 对象.      (line   25)
* utcoffset() (datetime.tzinfo 方法):    tzinfo 对象.        (line   31)
* utctimetuple() (datetime.datetime 方法): datetime 对象.    (line  468)
* utf8 (email.policy.EmailPolicy 属性):  email policy 策略对象.
                                                             (line  291)
* utf8() (poplib.POP3 方法):             POP3 对象.          (line   94)
* utf8_enabled (imaplib.IMAP4 属性):     IMAP4 Objects.      (line  387)
* utime() (在 os 模块中):                文件和目录.         (line 1265)
* uu (模块):                             uu --- 对 uuencode 文件进行编码与解码.
                                                             (line    6)
* UUID (uuid 中的类):                    uuid --- UUID objects according to RFC 4122.
                                                             (line   45)
* uuid (模块):                           uuid --- UUID objects according to RFC 4122.
                                                             (line    6)
* uuid1:                                 uuid --- UUID objects according to RFC 4122.
                                                             (line  185)
* uuid1() (在 uuid 模块中):              uuid --- UUID objects according to RFC 4122.
                                                             (line  177)
* uuid3:                                 uuid --- UUID objects according to RFC 4122.
                                                             (line  190)
* uuid3() (在 uuid 模块中):              uuid --- UUID objects according to RFC 4122.
                                                             (line  185)
* uuid4:                                 uuid --- UUID objects according to RFC 4122.
                                                             (line  194)
* uuid4() (在 uuid 模块中):              uuid --- UUID objects according to RFC 4122.
                                                             (line  190)
* uuid5:                                 uuid --- UUID objects according to RFC 4122.
                                                             (line  199)
* uuid5() (在 uuid 模块中):              uuid --- UUID objects according to RFC 4122.
                                                             (line  194)
* UuidCreate() (在 msilib 模块中):       msilib --- Read and write Microsoft Installer files.
                                                             (line   39)
* v4_int_to_packed() (在 ipaddress 模块中): Other Module Level Functions.
                                                             (line    8)
* v6_int_to_packed() (在 ipaddress 模块中): Other Module Level Functions.
                                                             (line   20)
* validator() (在 wsgiref.validate 模块中): wsgiref validate --- WSGI conformance checker.
                                                             (line   22)
* valid_signals() (在 signal 模块中):    模块内容<5>.        (line  238)
* value (ctypes._SimpleCData 属性):      基础数据类型<2>.    (line   15)
* value (http.cookiejar.Cookie 属性):    Cookie 对象<2>.     (line   32)
* value (http.cookies.Morsel 属性):      Morsel 对象.        (line   52)
* value (xml.dom.Attr 属性):             Attr 对象.          (line   20)
* value of an object:                    对象、值与类型.     (line   10)
* Value() (multiprocessing.managers.SyncManager 方法): 管理器.
                                                             (line  175)
* Value() (在 multiprocessing 模块中):   共享 ctypes 对象.   (line    8)
* Value() (在 multiprocessing.sharedctypes 模块中): multiprocessing sharedctypes 模块.
                                                             (line   57)
* ValueError:                            具体异常.           (line  338)
* valuerefs() (weakref.WeakValueDictionary 方法): weakref --- 弱引用.
                                                             (line  141)
* values() (contextvars.Context 方法):   手动上下文管理.     (line   94)
* values() (dict 方法):                  映射类型 --- dict.  (line  197)
* values() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  192)
* values() (email.message.Message 方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  286)
* values() (mailbox.Mailbox 方法):       Mailbox 对象.       (line   89)
* values() (types.MappingProxyType 方法): 标准解释器类型.    (line  233)
* ValuesView (collections.abc 中的类):   容器抽象基类.       (line  180)
* ValuesView (typing 中的类):            类 函数和修饰器.    (line  276)
* value_decode() (http.cookies.BaseCookie 方法): Cookie 对象.
                                                             (line    6)
* value_encode() (http.cookies.BaseCookie 方法): Cookie 对象.
                                                             (line   13)
* var (contextvars.contextvars.Token.Token 属性): 上下文变量.
                                                             (line   71)
* variable annotation – 变量标注:        术语对照表.         (line 1060)
* variance (statistics.NormalDist 属性): NormalDist 对象.    (line   34)
* variance() (在 statistics 模块中):     函数细节.           (line  299)
* variant (uuid.UUID 属性):              uuid --- UUID objects according to RFC 4122.
                                                             (line  138)
* vars() (內置函数):                     内置函数.           (line 1434)
* vbar (tkinter.scrolledtext.ScrolledText 属性): tkinter scrolledtext --- 滚动文字控件.
                                                             (line   24)
* VBAR() (在 token 模块中):              token --- 与Python解析树一起使用的常量.
                                                             (line   94)
* VBAREQUAL() (在 token 模块中):         token --- 与Python解析树一起使用的常量.
                                                             (line  190)
* Vec2D (turtle 中的类):                 公共类.             (line   82)
* vectorcallfunc (C 类型):               Slot Type typedefs. (line   26)
* venv (模块):                           venv --- 创建虚拟环境.
                                                             (line    6)
* VERBOSE() (在 re 模块中):              模块内容.           (line   95)
* verbose() (在 tabnanny 模块中):        tabnanny --- 模糊缩进检测.
                                                             (line   23)
* verbose() (在 test.support 模块中):    test support --- Utilities for the Python test suite.
                                                             (line   30)
* verify() (smtplib.SMTP 方法):          SMTP Objects.       (line   84)
* VerifyFlags (ssl 中的类):              常量<9>.            (line  101)
* VerifyMode (ssl 中的类):               常量<9>.            (line   56)
* verify_client_post_handshake() (ssl.SSLSocket 方法): SSL 套接字.
                                                             (line  243)
* verify_code (ssl.SSLCertVerificationError 属性): 异常<12>. (line   76)
* VERIFY_CRL_CHECK_CHAIN() (在 ssl 模块中): 常量<9>.         (line   79)
* VERIFY_CRL_CHECK_LEAF() (在 ssl 模块中): 常量<9>.          (line   69)
* VERIFY_DEFAULT() (在 ssl 模块中):      常量<9>.            (line   62)
* verify_flags (ssl.SSLContext 属性):    SSL 上下文.         (line  560)
* verify_message (ssl.SSLCertVerificationError 属性): 异常<12>.
                                                             (line   80)
* verify_mode (ssl.SSLContext 属性):     SSL 上下文.         (line  574)
* verify_request() (socketserver.BaseServer 方法): Server 对象<2>.
                                                             (line  175)
* VERIFY_X509_STRICT() (在 ssl 模块中):  常量<9>.            (line   86)
* VERIFY_X509_TRUSTED_FIRST() (在 ssl 模块中): 常量<9>.      (line   93)
* version (email.headerregistry.MIMEVersionHeader 属性): email headerregistry 自定义标头对象.
                                                             (line  195)
* version (http.client.HTTPResponse 属性): HTTPResponse 对象.
                                                             (line   46)
* version (http.cookiejar.Cookie 属性):  Cookie 对象<2>.     (line   20)
* version (in module sys):               Process-wide parameters.
                                                             (line  164)
* version (in module sys) <1>:           Process-wide parameters.
                                                             (line  199)
* version (in module sys) <2>:           Process-wide parameters.
                                                             (line  210)
* version (ipaddress.IPv4Address 属性):  地址对象.           (line   40)
* version (ipaddress.IPv4Network 属性):  Network objects.    (line   63)
* version (ipaddress.IPv6Address 属性):  地址对象.           (line  169)
* version (ipaddress.IPv6Network 属性):  Network objects.    (line  293)
* version (urllib.request.URLopener 属性): 已停用的接口.     (line  132)
* version (uuid.UUID 属性):              uuid --- UUID objects according to RFC 4122.
                                                             (line  145)
* version() (ssl.SSLSocket 方法):        SSL 套接字.         (line  261)
* version() (在 curses 模块中):          常量<6>.            (line   18)
* version() (在 ensurepip 模块中):       Module API.         (line    8)
* version() (在 marshal 模块中):         marshal --- 内部 Python 对象序列化.
                                                             (line   74)
* version() (在 platform 模块中):        跨平台.             (line  117)
* version() (在 sqlite3 模块中):         模块函数和常量.     (line    6)
* version() (在 sys 模块中):             sys --- 系统相关的参数和函数.
                                                             (line 1385)
* version_info() (在 sqlite3 模块中):    模块函数和常量.     (line   10)
* version_info() (在 sys 模块中):        sys --- 系统相关的参数和函数.
                                                             (line 1397)
* version_string() (http.server.BaseHTTPRequestHandler 方法): http server --- HTTP 服务器.
                                                             (line  292)
* vformat() (string.Formatter 方法):     自定义字符串格式化. (line   22)
* virtual environment – 虚拟环境:        术语对照表.         (line 1079)
* virtual machine – 虚拟机:              术语对照表.         (line 1087)
* VIRTUAL_ENV:                           创建虚拟环境<2>.    (line  116)
* visit() (ast.NodeVisitor 方法):        ast 中的辅助函数.   (line  125)
* visitproc (C 类型):                    使对象类型支持循环垃圾回收.
                                                             (line   76)
* vline() (curses.window 方法):          Window 对象.        (line  501)
* voidcmd() (ftplib.FTP 方法):           FTP 对象.           (line   60)
* volume (zipfile.ZipInfo 属性):         ZipInfo 对象.       (line  110)
* vonmisesvariate() (在 random 模块中):  实值分布.           (line   65)
* wait() (asyncio.asyncio.subprocess.Process 方法): 与子进程交互.
                                                             (line   33)
* wait() (asyncio.Condition 方法):       Condition.          (line   77)
* wait() (asyncio.Event 方法):           Event.              (line   43)
* wait() (multiprocessing.pool.AsyncResult 方法): 进程池.    (line  169)
* wait() (subprocess.Popen 方法):        Popen 对象.         (line   13)
* wait() (threading.Barrier 方法):       栅栏对象.           (line   38)
* wait() (threading.Condition 方法):     条件对象.           (line   80)
* wait() (threading.Event 方法):         事件对象.           (line   37)
* wait() (在 asyncio 模块中):            简单等待.           (line    6)
* wait() (在 concurrent.futures 模块中): 模块函数.           (line    6)
* wait() (在 multiprocessing.connection 模块中): 监听器及客户端.
                                                             (line   99)
* wait() (在 os 模块中):                 进程管理.           (line  600)
* wait3() (在 os 模块中):                进程管理.           (line  682)
* wait4() (在 os 模块中):                进程管理.           (line  692)
* waitid() (在 os 模块中):               进程管理.           (line  608)
* waitpid() (在 os 模块中):              进程管理.           (line  656)
* wait_closed() (asyncio.Server 方法):   Server 对象.        (line   88)
* wait_closed() (asyncio.StreamWriter 方法): StreamWriter.   (line   79)
* wait_for() (asyncio.Condition 方法):   Condition.          (line   88)
* wait_for() (threading.Condition 方法): 条件对象.           (line  104)
* wait_for() (在 asyncio 模块中):        超时.               (line    6)
* wait_threads_exit() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  520)
* walk() (email.message.EmailMessage 方法): email message 表示一封电子邮件信息.
                                                             (line  390)
* walk() (email.message.Message 方法):   email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  531)
* walk() (在 ast 模块中):                ast 中的辅助函数.   (line  108)
* walk() (在 os 模块中):                 文件和目录.         (line 1301)
* walk_packages() (在 pkgutil 模块中):   pkgutil --- 包扩展工具.
                                                             (line  161)
* walk_stack() (在 traceback 模块中):    traceback --- 打印或检索堆栈回溯.
                                                             (line  155)
* walk_tb() (在 traceback 模块中):       traceback --- 打印或检索堆栈回溯.
                                                             (line  164)
* want (doctest.Example 属性):           Example Objects.    (line   23)
* warn() (distutils.ccompiler.CCompiler 方法): distutils ccompiler --- CCompiler基类.
                                                             (line  504)
* warn() (distutils.text_file.TextFile 方法): distutils text_file --- The TextFile class.
                                                             (line  101)
* warn() (在 warnings 模块中):           Available Functions.
                                                             (line    6)
* Warning:                               警告.               (line    8)
* Warning <1>:                           异常<4>.            (line    6)
* warning() (logging.Logger 方法):       记录器对象.         (line  171)
* warning() (xml.sax.handler.ErrorHandler 方法): ErrorHandler 对象.
                                                             (line   23)
* warning() (在 logging 模块中):         模块级别函数.       (line  102)
* warnings:                              warnings --- Warning control.
                                                             (line    8)
* warnings (模块):                       warnings --- Warning control.
                                                             (line    6)
* WarningsRecorder (test.support 中的类): test support --- Utilities for the Python test suite.
                                                             (line 1096)
* warnoptions() (在 sys 模块中):         sys --- 系统相关的参数和函数.
                                                             (line 1408)
* warn_explicit() (在 warnings 模块中):  Available Functions.
                                                             (line   32)
* wasSuccessful() (unittest.TestResult 方法): Loading and running tests.
                                                             (line  301)
* WatchedFileHandler (logging.handlers 中的类): WatchedFileHandler.
                                                             (line   20)
* wave (模块):                           wave --- 读写WAV格式文件.
                                                             (line    6)
* WCONTINUED() (在 os 模块中):           进程管理.           (line  708)
* WCOREDUMP() (在 os 模块中):            进程管理.           (line  726)
* WeakKeyDictionary (weakref 中的类):    weakref --- 弱引用. (line  119)
* WeakMethod (weakref 中的类):           weakref --- 弱引用. (line  150)
* weakref (模块):                        weakref --- 弱引用. (line    6)
* WeakSet (weakref 中的类):              weakref --- 弱引用. (line  145)
* WeakValueDictionary (weakref 中的类):  weakref --- 弱引用. (line  134)
* webbrowser (模块):                     webbrowser --- 方便的Web浏览器控制器.
                                                             (line    6)
* weekday() (datetime.date 方法):        date 对象.          (line  185)
* weekday() (datetime.datetime 方法):    datetime 对象.      (line  521)
* weekday() (在 calendar 模块中):        calendar --- 日历相关函数.
                                                             (line  273)
* weekheader() (在 calendar 模块中):     calendar --- 日历相关函数.
                                                             (line  278)
* weibullvariate() (在 random 模块中):   实值分布.           (line   75)
* WEXITED() (在 os 模块中):              进程管理.           (line  634)
* WEXITSTATUS() (在 os 模块中):          进程管理.           (line  766)
* wfile (http.server.BaseHTTPRequestHandler 属性): http server --- HTTP 服务器.
                                                             (line  105)
* what() (在 imghdr 模块中):             imghdr --- 推测图像类型.
                                                             (line   14)
* what() (在 sndhdr 模块中):             sndhdr --- 推测声音文件的类型.
                                                             (line   21)
* whathdr() (在 sndhdr 模块中):          sndhdr --- 推测声音文件的类型.
                                                             (line   28)
* whatis (pdb command):                  调试器命令.         (line  205)
* when() (asyncio.TimerHandle 方法):     回调处理.           (line   29)
* where (pdb command):                   调试器命令.         (line   41)
* which() (在 shutil 模块中):            目录和文件操作.     (line  312)
* whichdb() (在 dbm 模块中):             dbm --- Unix "数据库" 接口.
                                                             (line   21)
* whitespace (shlex.shlex 属性):         shlex Objects.      (line  104)
* whitespace() (在 string 模块中):       字符串常量.         (line   46)
* whitespace_split (shlex.shlex 属性):   shlex Objects.      (line  128)
* Widget (tkinter.ttk 中的类):           ttk Widget.         (line    9)
* width (textwrap.TextWrapper 属性):     textwrap --- 文本自动换行与填充.
                                                             (line  136)
* width() (在 turtle 模块中):            绘图状态.           (line   18)
* WIFCONTINUED() (在 os 模块中):         进程管理.           (line  734)
* WIFEXITED() (在 os 模块中):            进程管理.           (line  759)
* WIFSIGNALED() (在 os 模块中):          进程管理.           (line  753)
* WIFSTOPPED() (在 os 模块中):           进程管理.           (line  743)
* win32_edition() (在 platform 模块中):  Windows平台.        (line   17)
* win32_is_iot() (在 platform 模块中):   Windows平台.        (line   24)
* win32_ver() (在 platform 模块中):      Windows平台.        (line    6)
* WinDLL (ctypes 中的类):                加载动态链接库.     (line   39)
* window manager (widgets):              The Window Manager. (line    6)
* window() (curses.panel.Panel 方法):    Panel 对象.         (line   57)
* Windows:                               完整的 Python 程序. (line   19)
* Windows ini file:                      configparser --- 配置文件解析器.
                                                             (line    8)
* WindowsError:                          具体异常.           (line  355)
* WindowsPath (pathlib 中的类):          具体路径.           (line   29)
* WindowsProactorEventLoopPolicy (asyncio 中的类): 策略对象. (line   67)
* WindowsRegistryFinder (importlib.machinery 中的类): importlib machinery -- Importers and path hooks.
                                                             (line   89)
* WindowsSelectorEventLoopPolicy (asyncio 中的类): 策略对象. (line   60)
* window_height() (在 turtle 模块中):    设置与特殊方法.     (line   99)
* window_width() (在 turtle 模块中):     设置与特殊方法.     (line  106)
* winerror (OSError 属性):               具体异常.           (line  117)
* WinError() (在 ctypes 模块中):         工具函数.           (line  177)
* WINFUNCTYPE() (在 ctypes 模块中):      函数原型.           (line   20)
* winreg (模块):                         winreg --- Windows 注册表访问.
                                                             (line    6)
* WinSock:                               select --- 等待 I/O 完成.
                                                             (line  120)
* winsound (模块):                       winsound --- Sound-playing interface for Windows.
                                                             (line    6)
* winver() (在 sys 模块中):              sys --- 系统相关的参数和函数.
                                                             (line 1413)
* WITH_CLEANUP_FINISH (opcode):          Python字节码说明.   (line  431)
* WITH_CLEANUP_START (opcode):           Python字节码说明.   (line  418)
* with_hostmask (ipaddress.IPv4Interface 属性): Interface objects.
                                                             (line   55)
* with_hostmask (ipaddress.IPv4Network 属性): Network objects.
                                                             (line  123)
* with_hostmask (ipaddress.IPv6Interface 属性): Interface objects.
                                                             (line   82)
* with_hostmask (ipaddress.IPv6Network 属性): Network objects.
                                                             (line  325)
* with_name() (pathlib.PurePath 方法):   方法和特征属性.     (line  253)
* with_netmask (ipaddress.IPv4Interface 属性): Interface objects.
                                                             (line   46)
* with_netmask (ipaddress.IPv4Network 属性): Network objects.
                                                             (line  118)
* with_netmask (ipaddress.IPv6Interface 属性): Interface objects.
                                                             (line   80)
* with_netmask (ipaddress.IPv6Network 属性): Network objects.
                                                             (line  323)
* with_prefixlen (ipaddress.IPv4Interface 属性): Interface objects.
                                                             (line   37)
* with_prefixlen (ipaddress.IPv4Network 属性): Network objects.
                                                             (line  105)
* with_prefixlen (ipaddress.IPv6Interface 属性): Interface objects.
                                                             (line   78)
* with_prefixlen (ipaddress.IPv6Network 属性): Network objects.
                                                             (line  317)
* with_pymalloc() (在 test.support 模块中): test support --- Utilities for the Python test suite.
                                                             (line  207)
* with_suffix() (pathlib.PurePath 方法): 方法和特征属性.     (line  269)
* with_traceback() (BaseException 方法): 基类.               (line   20)
* WNOHANG() (在 os 模块中):              进程管理.           (line  701)
* WNOWAIT() (在 os 模块中):              进程管理.           (line  634)
* wordchars (shlex.shlex 属性):          shlex Objects.      (line   91)
* World Wide Web:                        互联网协议和支持.   (line    6)
* World Wide Web <1>:                    urllib parse 用于解析 URL.
                                                             (line    8)
* World Wide Web <2>:                    urllib robotparser --- robots txt 语法分析程序.
                                                             (line    8)
* wrap() (textwrap.TextWrapper 方法):    textwrap --- 文本自动换行与填充.
                                                             (line  241)
* wrap() (在 textwrap 模块中):           textwrap --- 文本自动换行与填充.
                                                             (line   15)
* wrapper() (在 curses 模块中):          函数<3>.            (line  467)
* WrapperDescriptorType() (在 types 模块中): 标准解释器类型. (line   77)
* wraps() (在 functools 模块中):         functools --- 高阶函数和可调用对象上的操作.
                                                             (line  467)
* wrap_bio() (ssl.SSLContext 方法):      SSL 上下文.         (line  393)
* wrap_future() (在 asyncio 模块中):     Future 函数.        (line   40)
* wrap_socket() (ssl.SSLContext 方法):   SSL 上下文.         (line  341)
* wrap_socket() (在 ssl 模块中):         证书处理.           (line  146)
* wrap_text() (在 distutils.fancy_getopt 模块中): distutils fancy_getopt --- Wrapper around the standard getopt module.
                                                             (line   32)
* writable() (asyncore.dispatcher 方法): asyncore --- 异步socket处理器.
                                                             (line  140)
* writable() (io.IOBase 方法):           I/O 基类.           (line  127)
* WRITABLE() (在 tkinter 模块中):        File Handlers.      (line   41)
* write() (asyncio.StreamWriter 方法):   StreamWriter.       (line   13)
* write() (asyncio.WriteTransport 方法): 只写传输.           (line   52)
* write() (code.InteractiveInterpreter 方法): 交互解释器对象.
                                                             (line   52)
* write() (codecs.StreamWriter 方法):    StreamWriter 对象.  (line   27)
* write() (configparser.ConfigParser 方法): ConfigParser 对象.
                                                             (line  225)
* write() (email.generator.BytesGenerator 方法): email generator 生成 MIME 文档.
                                                             (line   98)
* write() (email.generator.Generator 方法): email generator 生成 MIME 文档.
                                                             (line  179)
* write() (io.BufferedIOBase 方法):      I/O 基类.           (line  274)
* write() (io.BufferedWriter 方法):      缓冲流.             (line  110)
* write() (io.RawIOBase 方法):           I/O 基类.           (line  178)
* write() (io.TextIOBase 方法):          文本 I/O<2>.        (line   83)
* write() (mmap.mmap 方法):              mmap --- 内存映射文件支持.
                                                             (line  240)
* write() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line   39)
* write() (ssl.MemoryBIO 方法):          内存 BIO 支持<2>.   (line  135)
* write() (ssl.SSLSocket 方法):          SSL 套接字.         (line   83)
* write() (telnetlib.Telnet 方法):       Telnet 对象.        (line   92)
* write() (xml.etree.ElementTree.ElementTree 方法): ElementTree 对象.
                                                             (line   58)
* write() (zipfile.ZipFile 方法):        ZipFile 对象.       (line  212)
* write() (在 os 模块中):                文件描述符操作.     (line  605)
* write() (在 turtle 模块中):            更多绘图控制.       (line   27)
* writeall() (ossaudiodev.oss_audio_device 方法): Audio Device Objects.
                                                             (line   50)
* writeframes() (aifc.aifc 方法):        aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  162)
* writeframes() (sunau.AU_write 方法):   AU_write 对象.      (line   51)
* writeframes() (wave.Wave_write 方法):  Wave_write 对象.    (line   64)
* writeframesraw() (aifc.aifc 方法):     aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  168)
* writeframesraw() (sunau.AU_write 方法): AU_write 对象.     (line   45)
* writeframesraw() (wave.Wave_write 方法): Wave_write 对象.  (line   58)
* writeheader() (csv.DictWriter 方法):   Writer 对象.        (line   33)
* writelines() (asyncio.StreamWriter 方法): StreamWriter.    (line   23)
* writelines() (asyncio.WriteTransport 方法): 只写传输.      (line   58)
* writelines() (codecs.StreamWriter 方法): StreamWriter 对象.
                                                             (line   31)
* writelines() (io.IOBase 方法):         I/O 基类.           (line  132)
* writePlist() (在 plistlib 模块中):     plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line  125)
* writePlistToBytes() (在 plistlib 模块中): plistlib --- 生成与解析 Mac OS X plist 文件.
                                                             (line  143)
* writepy() (zipfile.PyZipFile 方法):    PyZipFile 对象.     (line   18)
* writer (formatter.formatter 属性):     The Formatter Interface.
                                                             (line   22)
* writer() (在 csv 模块中):              模块内容<3>.        (line   34)
* writerow() (csv.csvwriter 方法):       Writer 对象.        (line   13)
* writerows() (csv.csvwriter 方法):      Writer 对象.        (line   20)
* writestr() (zipfile.ZipFile 方法):     ZipFile 对象.       (line  231)
* WriteTransport (asyncio 中的类):       传输层级.           (line   10)
* writev() (在 os 模块中):               文件描述符操作.     (line  621)
* writexml() (xml.dom.minidom.Node 方法): DOM 对象.          (line   23)
* write_byte() (mmap.mmap 方法):         mmap --- 内存映射文件支持.
                                                             (line  252)
* write_bytes() (pathlib.Path 方法):     方法<2>.            (line  404)
* write_docstringdict() (在 turtle 模块中): 文档字符串翻译为不同的语言.
                                                             (line    9)
* write_eof() (asyncio.StreamWriter 方法): StreamWriter.     (line   48)
* write_eof() (asyncio.WriteTransport 方法): 只写传输.       (line   64)
* write_eof() (ssl.MemoryBIO 方法):      内存 BIO 支持<2>.   (line  142)
* write_file() (在 distutils.file_util 模块中): distutils file_util --- Single file operations.
                                                             (line   43)
* write_history_file() (在 readline 模块中): 历史文件.       (line   13)
* WRITE_RESTRICTED:                      泛型属性管理.       (line   87)
* write_results() (trace.CoverageResults 方法): 编程接口.    (line   57)
* write_text() (pathlib.Path 方法):      方法<2>.            (line  418)
* write_through (io.TextIOWrapper 属性): 文本 I/O<2>.        (line  143)
* writing; values:                       表达式语句.         (line   15)
* WrongDocumentErr:                      异常<16>.           (line   80)
* wsgiref (模块):                        wsgiref --- WSGI Utilities and Reference Implementation.
                                                             (line    6)
* wsgiref.handlers (模块):               wsgiref handlers -- server/gateway base classes.
                                                             (line    6)
* wsgiref.headers (模块):                wsgiref headers -- WSGI response header tools.
                                                             (line    6)
* wsgiref.simple_server (模块):          wsgiref simple_server -- a simple WSGI HTTP server.
                                                             (line    6)
* wsgiref.util (模块):                   wsgiref util -- WSGI environment utilities.
                                                             (line    6)
* wsgiref.validate (模块):               wsgiref validate --- WSGI conformance checker.
                                                             (line    6)
* WSGIRequestHandler (wsgiref.simple_server 中的类): wsgiref simple_server -- a simple WSGI HTTP server.
                                                             (line   75)
* WSGIServer (wsgiref.simple_server 中的类): wsgiref simple_server -- a simple WSGI HTTP server.
                                                             (line   45)
* wsgi_file_wrapper (wsgiref.handlers.BaseHandler 属性): wsgiref handlers -- server/gateway base classes.
                                                             (line  268)
* wsgi_multiprocess (wsgiref.handlers.BaseHandler 属性): wsgiref handlers -- server/gateway base classes.
                                                             (line  152)
* wsgi_multithread (wsgiref.handlers.BaseHandler 属性): wsgiref handlers -- server/gateway base classes.
                                                             (line  145)
* wsgi_run_once (wsgiref.handlers.BaseHandler 属性): wsgiref handlers -- server/gateway base classes.
                                                             (line  159)
* wShowWindow (subprocess.STARTUPINFO 属性): Windows Popen 助手.
                                                             (line   44)
* WSTOPPED() (在 os 模块中):             进程管理.           (line  634)
* WSTOPSIG() (在 os 模块中):             进程管理.           (line  774)
* wstring_at() (在 ctypes 模块中):       工具函数.           (line  186)
* ws_comma (2to3 fixer):                 修复器.             (line  309)
* WTERMSIG() (在 os 模块中):             进程管理.           (line  782)
* WUNTRACED() (在 os 模块中):            进程管理.           (line  715)
* WWW:                                   互联网协议和支持.   (line    6)
* WWW <1>:                               urllib parse 用于解析 URL.
                                                             (line    8)
* WWW <2>:                               urllib robotparser --- robots txt 语法分析程序.
                                                             (line    8)
* WWW; server:                           cgi --- 通用网关接口支持.
                                                             (line    8)
* WWW; server <1>:                       http server --- HTTP 服务器.
                                                             (line    8)
* W_OK() (在 os 模块中):                 文件和目录.         (line   89)
* X() (在 re 模块中):                    模块内容.           (line   95)
* X509 certificate:                      SSL 上下文.         (line  585)
* xatom() (imaplib.IMAP4 方法):          IMAP4 Objects.      (line  369)
* XATTR_CREATE() (在 os 模块中):         Linux 扩展属性.     (line   80)
* XATTR_REPLACE() (在 os 模块中):        Linux 扩展属性.     (line   85)
* XATTR_SIZE_MAX() (在 os 模块中):       Linux 扩展属性.     (line   76)
* xcor() (在 turtle 模块中):             获取海龟的状态.     (line   31)
* XDR:                                   xdrlib --- 编码与解码 XDR 数据.
                                                             (line    8)
* xdrlib (模块):                         xdrlib --- 编码与解码 XDR 数据.
                                                             (line    6)
* xhdr() (nntplib.NNTP 方法):            方法<3>.            (line  319)
* XHTML:                                 html parser --- 简单的 HTML 和 XHTML 解析器.
                                                             (line    8)
* XHTML_NAMESPACE() (在 xml.dom 模块中): 模块内容<6>.        (line   45)
* xml (模块):                            XML处理模块.        (line    6)
* XML() (在 xml.etree.ElementTree 模块中): 函数<6>.          (line  218)
* xml.dom (模块):                        xml dom --- 文档对象模型 API.
                                                             (line    6)
* xml.dom.minidom (模块):                xml dom minidom --- 最小化的 DOM 实现.
                                                             (line    6)
* xml.dom.pulldom (模块):                xml dom pulldom --- 支持构建部分 DOM 树.
                                                             (line    6)
* xml.etree.ElementInclude.default_loader() (在 xml.etree.ElementTree 模块中): 函数<7>.
                                                             (line    6)
* xml.etree.ElementInclude.include() (在 xml.etree.ElementTree 模块中): 函数<7>.
                                                             (line   16)
* xml.etree.ElementTree (模块):          xml etree ElementTree --- ElementTree XML API.
                                                             (line    6)
* xml.parsers.expat (模块):              xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line    6)
* xml.parsers.expat.errors (模块):       Expat 错误常量.     (line    6)
* xml.parsers.expat.model (模块):        内容模型描述.       (line    6)
* xml.sax (模块):                        xml sax --- 支持 SAX2 解析器.
                                                             (line    6)
* xml.sax.handler (模块):                xml sax handler --- SAX 处理程序的基类.
                                                             (line    6)
* xml.sax.saxutils (模块):               xml sax saxutils --- SAX 工具集.
                                                             (line    6)
* xml.sax.xmlreader (模块):              xml sax xmlreader --- 用于 XML 解析器的接口.
                                                             (line    6)
* xmlcharrefreplace_errors() (在 codecs 模块中): 错误处理方案.
                                                             (line  121)
* XmlDeclHandler() (xml.parsers.expat.xmlparser 方法): XMLParser对象<2>.
                                                             (line  146)
* XMLFilterBase (xml.sax.saxutils 中的类): xml sax saxutils --- SAX 工具集.
                                                             (line   57)
* XMLGenerator (xml.sax.saxutils 中的类): xml sax saxutils --- SAX 工具集.
                                                             (line   44)
* XMLID() (在 xml.etree.ElementTree 模块中): 函数<6>.        (line  225)
* XMLNS_NAMESPACE() (在 xml.dom 模块中): 模块内容<6>.        (line   40)
* XMLParser (xml.etree.ElementTree 中的类): XMLParser对象.   (line    6)
* XMLParserType() (在 xml.parsers.expat 模块中): xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line   31)
* XMLPullParser (xml.etree.ElementTree 中的类): XMLPullParser对象.
                                                             (line    6)
* XMLReader (xml.sax.xmlreader 中的类):  xml sax xmlreader --- 用于 XML 解析器的接口.
                                                             (line   14)
* xmlrpc.client (模块):                  xmlrpc client --- XML-RPC 客户端访问.
                                                             (line    6)
* xmlrpc.server (模块):                  xmlrpc server --- 基本 XML-RPC 服务器.
                                                             (line    6)
* XML_ERROR_ABORTED() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  161)
* XML_ERROR_ASYNC_ENTITY() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   26)
* XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   28)
* XML_ERROR_BAD_CHAR_REF() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   33)
* XML_ERROR_BINARY_ENTITY_REF() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   37)
* XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  122)
* XML_ERROR_DUPLICATE_ATTRIBUTE() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   41)
* XML_ERROR_ENTITY_DECLARED_IN_PE() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  114)
* XML_ERROR_EXTERNAL_ENTITY_HANDLING() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  105)
* XML_ERROR_FEATURE_REQUIRES_XML_DTD() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  116)
* XML_ERROR_FINISHED() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  165)
* XML_ERROR_INCOMPLETE_PE() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  136)
* XML_ERROR_INCORRECT_ENCODING() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   45)
* XML_ERROR_INVALID_TOKEN() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   47)
* XML_ERROR_JUNK_AFTER_DOC_ELEMENT() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   52)
* XML_ERROR_MISPLACED_XML_PI() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   56)
* XML_ERROR_NOT_STANDALONE() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  107)
* XML_ERROR_NOT_SUSPENDED() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  157)
* XML_ERROR_NO_ELEMENTS() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   60)
* XML_ERROR_NO_MEMORY() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   64)
* XML_ERROR_PARAM_ENTITY_REF() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   68)
* XML_ERROR_PARTIAL_CHAR() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   72)
* XML_ERROR_PUBLICID() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  148)
* XML_ERROR_RECURSIVE_ENTITY_REF() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   76)
* XML_ERROR_SUSPENDED() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  152)
* XML_ERROR_SUSPEND_PE() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  170)
* XML_ERROR_SYNTAX() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   81)
* XML_ERROR_TAG_MISMATCH() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   85)
* XML_ERROR_TEXT_DECL() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  144)
* XML_ERROR_UNBOUND_PREFIX() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  128)
* XML_ERROR_UNCLOSED_CDATA_SECTION() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  101)
* XML_ERROR_UNCLOSED_TOKEN() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   89)
* XML_ERROR_UNDECLARING_PREFIX() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  132)
* XML_ERROR_UNDEFINED_ENTITY() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   93)
* XML_ERROR_UNEXPECTED_STATE() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  112)
* XML_ERROR_UNKNOWN_ENCODING() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line   97)
* XML_ERROR_XML_DECL() (在 xml.parsers.expat.errors 模块中): Expat 错误常量.
                                                             (line  140)
* XML_NAMESPACE() (在 xml.dom 模块中):   模块内容<6>.        (line   35)
* xor() (在 operator 模块中):            operator --- 标准运算符替代函数.
                                                             (line  151)
* xover() (nntplib.NNTP 方法):           方法<3>.            (line  335)
* xpath() (nntplib.NNTP 方法):           方法<3>.            (line  343)
* xrange (2to3 fixer):                   修复器.             (line  313)
* xreadlines (2to3 fixer):               修复器.             (line  318)
* xview() (tkinter.ttk.Treeview 方法):   ttk Treeview.       (line  326)
* X_OK() (在 os 模块中):                 文件和目录.         (line   89)
* ycor() (在 turtle 模块中):             获取海龟的状态.     (line   43)
* year (datetime.date 属性):             date 对象.          (line   94)
* year (datetime.datetime 属性):         datetime 对象.      (line  242)
* Year 2038:                             time --- 时间的访问和转换.
                                                             (line   25)
* yeardatescalendar() (calendar.Calendar 方法): calendar --- 日历相关函数.
                                                             (line   87)
* yeardays2calendar() (calendar.Calendar 方法): calendar --- 日历相关函数.
                                                             (line   94)
* yeardayscalendar() (calendar.Calendar 方法): calendar --- 日历相关函数.
                                                             (line  100)
* YESEXPR() (在 locale 模块中):          locale --- 国际化服务.
                                                             (line  223)
* yield; examples:                       生成器-迭代器的方法.
                                                             (line   46)
* yield; expression:                     yield 表达式.       (line    6)
* yield; yield from (in What’s New):     PEP 3151 重写 OS 和 IO 异常的层次结构.
                                                             (line   87)
* YIELD_FROM (opcode):                   Python字节码说明.   (line  331)
* YIELD_VALUE (opcode):                  Python字节码说明.   (line  327)
* yiq_to_rgb() (在 colorsys 模块中):     colorsys --- 颜色系统间的转换.
                                                             (line   28)
* yview() (tkinter.ttk.Treeview 方法):   ttk Treeview.       (line  330)
* Zen of Python – Python 之禅:           术语对照表.         (line 1092)
* ZeroDivisionError:                     具体异常.           (line  343)
* zfill() (bytearray 方法):              bytes 和 bytearray 操作.
                                                             (line  589)
* zfill() (bytes 方法):                  bytes 和 bytearray 操作.
                                                             (line  589)
* zfill() (str 方法):                    字符串的方法<2>.    (line  523)
* zip (2to3 fixer):                      修复器.             (line  322)
* zip() (內置函数):                      内置函数.           (line 1451)
* zipapp (模块):                         zipapp --- Manage executable Python zip archives.
                                                             (line    6)
* zipapp command line option; -c:        命令行界面<7>.      (line   45)
* zipapp command line option; –compress: 命令行界面<7>.      (line   45)
* zipapp command line option; -h:        命令行界面<7>.      (line   61)
* zipapp command line option; –help:     命令行界面<7>.      (line   61)
* zipapp command line option; –info:     命令行界面<7>.      (line   55)
* zipapp command line option; -m <mainfn>: 命令行界面<7>.    (line   35)
* zipapp command line option; –main=<mainfn>: 命令行界面<7>. (line   35)
* zipapp command line option; -o <output>: 命令行界面<7>.    (line   18)
* zipapp command line option; –output=<output>: 命令行界面<7>.
                                                             (line   18)
* zipapp command line option; -p <interpreter>: 命令行界面<7>.
                                                             (line   29)
* zipapp command line option; –python=<interpreter>: 命令行界面<7>.
                                                             (line   29)
* ZipFile (zipfile 中的类):              ZipFile 对象.       (line    6)
* zipfile (模块):                        zipfile --- 使用ZIP存档.
                                                             (line    6)
* zipfile command line option; -c <zipfile> <source1> ... <sourceN>: 命令行选项<2>.
                                                             (line   11)
* zipfile command line option; –create <zipfile> <source1> ... <sourceN>: 命令行选项<2>.
                                                             (line   11)
* zipfile command line option; -e <zipfile> <output_dir>: 命令行选项<2>.
                                                             (line   16)
* zipfile command line option; –extract <zipfile> <output_dir>: 命令行选项<2>.
                                                             (line   16)
* zipfile command line option; -l <zipfile>: 命令行选项<2>.  (line    6)
* zipfile command line option; –list <zipfile>: 命令行选项<2>.
                                                             (line    6)
* zipfile command line option; -t <zipfile>: 命令行选项<2>.  (line   21)
* zipfile command line option; –test <zipfile>: 命令行选项<2>.
                                                             (line   21)
* zipimport (模块):                      zipimport --- 从 Zip 存档中导入模块.
                                                             (line    6)
* zipimporter (zipimport 中的类):        zipimporter 对象.   (line    8)
* ZipImportError:                        zipimport --- 从 Zip 存档中导入模块.
                                                             (line   46)
* ZipInfo (zipfile 中的类):              zipfile --- 使用ZIP存档.
                                                             (line   52)
* ZIP_BZIP2() (在 zipfile 模块中):       zipfile --- 使用ZIP存档.
                                                             (line   78)
* ZIP_DEFLATED() (在 zipfile 模块中):    zipfile --- 使用ZIP存档.
                                                             (line   74)
* zip_longest() (在 itertools 模块中):   Itertool函数.       (line  527)
* ZIP_LZMA() (在 zipfile 模块中):        zipfile --- 使用ZIP存档.
                                                             (line   84)
* ZIP_STORED() (在 zipfile 模块中):      zipfile --- 使用ZIP存档.
                                                             (line   70)
* zlib (模块):                           zlib --- 与 gzip 兼容的压缩.
                                                             (line    6)
* ZLIB_RUNTIME_VERSION() (在 zlib 模块中): zlib --- 与 gzip 兼容的压缩.
                                                             (line  236)
* ZLIB_VERSION() (在 zlib 模块中):       zlib --- 与 gzip 兼容的压缩.
                                                             (line  230)
* 例外; AssertionError:                  assert 语句.        (line   20)
* 例外; AttributeError:                  属性引用.           (line   10)
* 例外; GeneratorExit:                   生成器-迭代器的方法.
                                                             (line   38)
* 例外; GeneratorExit <1>:               异步生成器-迭代器方法.
                                                             (line   42)
* 例外; ImportError:                     import 语句.        (line    6)
* 例外; NameError:                       标识符（名称）.     (line    9)
* 例外; StopAsyncIteration:              异步生成器-迭代器方法.
                                                             (line    9)
* 例外; StopIteration:                   生成器-迭代器的方法.
                                                             (line   11)
* 例外; StopIteration <1>:               yield 语句.         (line    6)
* 例外; TypeError:                       一元算术和位运算.   (line   17)
* 例外; ValueError:                      移位运算.           (line   13)
* 例外; ZeroDivisionError:               二元算术运算符.     (line   25)
* 內置函数; abs:                         模拟数字类型.       (line  101)
* 內置函数; abs <1>:                     数字协议.           (line   71)
* 內置函数; ascii:                       对象协议.           (line  149)
* 內置函数; bytes:                       基本定制.           (line  120)
* 內置函数; bytes <1>:                   对象协议.           (line  167)
* 內置函数; chr:                         标准类型层级结构.   (line  117)
* 內置函数; classmethod:                 公用对象的结构.     (line  223)
* 內置函数; compile:                     global 语句.        (line   23)
* 內置函数; compile <1>:                 代码对象.           (line    6)
* 內置函数; compile <2>:                 标准解释器类型.     (line   46)
* 內置函数; compile <3>:                 Queries on ST Objects.
                                                             (line   14)
* 內置函数; compile <4>:                 导入模块<2>.        (line  117)
* 內置函数; complex:                     模拟数字类型.       (line  107)
* 內置函数; complex <1>:                 数字类型 --- int float complex.
                                                             (line   20)
* 內置函数; divmod:                      模拟数字类型.       (line   24)
* 內置函数; divmod <1>:                  模拟数字类型.       (line   51)
* 內置函数; divmod <2>:                  数字协议.           (line   47)
* 內置函数; eval:                        global 语句.        (line   23)
* 內置函数; eval <1>:                    表达式输入.         (line    6)
* 內置函数; eval <2>:                    代码对象.           (line   14)
* 內置函数; eval <3>:                    pprint --- 数据美化输出.
                                                             (line  115)
* 內置函数; eval <4>:                    PrettyPrinter 对象. (line   22)
* 內置函数; eval <5>:                    转换 ST 对象.       (line   45)
* 內置函数; exec:                        global 语句.        (line   23)
* 內置函数; exec <1>:                    内置函数.           (line  439)
* 內置函数; exec <2>:                    代码对象.           (line   14)
* 內置函数; exec <3>:                    转换 ST 对象.       (line   45)
* 內置函数; float:                       模拟数字类型.       (line  107)
* 內置函数; float <1>:                   数字类型 --- int float complex.
                                                             (line   20)
* 內置函数; float <2>:                   数字协议.           (line  192)
* 內置函数; hash:                        基本定制.           (line  181)
* 內置函数; hash <1>:                    不可变序列类型.     (line    6)
* 內置函数; hash <2>:                    对象协议.           (line  380)
* 內置函数; hash <3>:                    PyTypeObject Slots. (line  314)
* 內置函数; help:                        操作系统接口.       (line   19)
* 內置函数; id:                          对象、值与类型.     (line   10)
* 內置函数; int:                         模拟数字类型.       (line  107)
* 內置函数; int <1>:                     数字类型 --- int float complex.
                                                             (line   20)
* 內置函数; int <2>:                     数字协议.           (line  186)
* 內置函数; len:                         标准类型层级结构.   (line   93)
* 內置函数; len <1>:                     标准类型层级结构.   (line  169)
* 內置函数; len <2>:                     标准类型层级结构.   (line  193)
* 內置函数; len <3>:                     模拟容器类型.       (line   29)
* 內置函数; len <4>:                     通用序列操作.       (line   17)
* 內置函数; len <5>:                     映射类型 --- dict.  (line    6)
* 內置函数; len <6>:                     对象协议.           (line  419)
* 內置函数; len <7>:                     序列协议.           (line   16)
* 內置函数; len <8>:                     映射协议.           (line   18)
* 內置函数; len <9>:                     列表对象.           (line   34)
* 內置函数; len <10>:                    字典对象.           (line  121)
* 內置函数; len <11>:                    集合对象.           (line   82)
* 內置函数; max:                         通用序列操作.       (line   17)
* 內置函数; min:                         通用序列操作.       (line   17)
* 內置函数; open:                        读写文件.           (line    6)
* 內置函数; open <1>:                    标准类型层级结构.   (line  476)
* 內置函数; ord:                         标准类型层级结构.   (line  117)
* 內置函数; pow:                         模拟数字类型.       (line   24)
* 內置函数; pow <1>:                     模拟数字类型.       (line   24)
* 內置函数; pow <2>:                     模拟数字类型.       (line   51)
* 內置函数; pow <3>:                     模拟数字类型.       (line   59)
* 內置函数; pow <4>:                     数字协议.           (line   55)
* 內置函数; pow <5>:                     数字协议.           (line  150)
* 內置函数; print:                       基本定制.           (line  123)
* 內置函数; range:                       for 语句<2>.        (line   33)
* 內置函数; repr:                        表达式语句.         (line   15)
* 內置函数; repr <1>:                    终结和内存释放.     (line   69)
* 內置函数; repr <2>:                    对象协议.           (line  139)
* 內置函数; repr <3>:                    PyTypeObject Slots. (line  255)
* 內置函数; round:                       模拟数字类型.       (line  127)
* 內置函数; slice:                       标准类型层级结构.   (line  604)
* 內置函数; slice <1>:                   Python字节码说明.   (line  777)
* 內置函数; staticmethod:                公用对象的结构.     (line  230)
* 內置函数; tuple:                       序列协议.           (line  103)
* 內置函数; tuple <1>:                   列表对象.           (line  111)
* 內置函数; type:                        对象、值与类型.     (line   10)
* 內置函数; type <1>:                    元类.               (line    6)
* 內置函数; type <2>:                    类型对象.           (line    6)
* 內置函数; type <3>:                    对象协议.           (line  403)
* 內置函数; __import__:                  导入模块<2>.        (line   37)
* 关键字; as:                            import 语句.        (line    6)
* 关键字; as <1>:                        try 语句.           (line    6)
* 关键字; as <2>:                        with 语句.          (line    6)
* 关键字; async:                         协程函数定义.       (line    9)
* 关键字; await:                         调用.               (line  121)
* 关键字; await <1>:                     协程函数定义.       (line    9)
* 关键字; elif:                          if 语句<2>.         (line    6)
* 关键字; else:                          break 语句.         (line   12)
* 关键字; else <1>:                      if 语句<2>.         (line    6)
* 关键字; else <2>:                      while 语句.         (line    6)
* 关键字; else <3>:                      for 语句<2>.        (line    6)
* 关键字; else <4>:                      try 语句.           (line    6)
* 关键字; else <5>:                      try 语句.           (line   62)
* 关键字; except:                        try 语句.           (line    6)
* 关键字; finally:                       return 语句.        (line   16)
* 关键字; finally <1>:                   break 语句.         (line   17)
* 关键字; finally <2>:                   continue 语句.      (line    6)
* 关键字; finally <3>:                   try 语句.           (line    6)
* 关键字; finally <4>:                   try 语句.           (line   67)
* 关键字; from:                          yield 表达式.       (line    6)
* 关键字; from <1>:                      import 语句.        (line    6)
* 关键字; in:                            for 语句<2>.        (line    6)
* 关键字; yield:                         yield 表达式.       (line    6)
* 对象; asynchronous-generator:          异步生成器函数.     (line   41)
* 对象; Boolean:                         标准类型层级结构.   (line   69)
* 对象; Boolean <1>:                     数字类型 --- int float complex.
                                                             (line    6)
* 对象; built-in function:               标准类型层级结构.   (line  369)
* 对象; built-in function <1>:           调用.               (line  105)
* 对象; built-in method:                 标准类型层级结构.   (line  379)
* 对象; built-in method <1>:             调用.               (line  105)
* 对象; bytearray:                       可变序列类型.       (line    6)
* 对象; bytearray <1>:                   二进制序列类型 --- bytes bytearray memoryview.
                                                             (line    6)
* 对象; bytearray <2>:                   bytearray 对象.     (line    6)
* 对象; bytearray <3>:                   字节数组对象.       (line    6)
* 对象; bytes:                           二进制序列类型 --- bytes bytearray memoryview.
                                                             (line    6)
* 对象; bytes <1>:                       bytes 对象.         (line    6)
* 对象; bytes <2>:                       bytes 对象<2>.      (line    9)
* 对象; callable:                        标准类型层级结构.   (line  224)
* 对象; callable <1>:                    切片.               (line   30)
* 对象; Capsule:                         胶囊<2>.            (line    6)
* 对象; class:                           标准类型层级结构.   (line  435)
* 对象; class <1>:                       调用.               (line  110)
* 对象; class <2>:                       类定义.             (line    6)
* 对象; class instance:                  标准类型层级结构.   (line  435)
* 对象; class instance <1>:              标准类型层级结构.   (line  454)
* 对象; class instance <2>:              调用.               (line  114)
* 对象; complex:                         标准类型层级结构.   (line   87)
* 对象; complex number:                  数字类型 --- int float complex.
                                                             (line    6)
* 对象; complex number <1>:              复数对象.           (line    6)
* 对象; dictionary:                      标准类型层级结构.   (line  202)
* 对象; dictionary <1>:                  标准类型层级结构.   (line  435)
* 对象; dictionary <2>:                  基本定制.           (line  181)
* 对象; dictionary <3>:                  字典显示.           (line    6)
* 对象; dictionary <4>:                  抽取.               (line    6)
* 对象; dictionary <5>:                  赋值语句.           (line   90)
* 对象; dictionary <6>:                  映射类型 --- dict.  (line    6)
* 对象; dictionary <7>:                  字典对象.           (line    6)
* 对象; Ellipsis:                        标准类型层级结构.   (line   30)
* 对象; file:                            读写文件.           (line    6)
* 对象; file <1>:                        文件对象.           (line    6)
* 对象; floating point:                  标准类型层级结构.   (line   79)
* 对象; floating point <1>:              数字类型 --- int float complex.
                                                             (line    6)
* 对象; floating point <2>:              浮点数对象.         (line    6)
* 对象; frame:                           标准类型层级结构.   (line  532)
* 对象; frozenset:                       标准类型层级结构.   (line  187)
* 对象; frozenset <1>:                   集合对象.           (line    6)
* 对象; function:                        标准类型层级结构.   (line  228)
* 对象; function <1>:                    标准类型层级结构.   (line  369)
* 对象; function <2>:                    调用.               (line   99)
* 对象; function <3>:                    调用.               (line  105)
* 对象; function <4>:                    函数定义.           (line    6)
* 对象; function <5>:                    函数对象<3>.        (line    6)
* 对象; generator:                       标准类型层级结构.   (line  515)
* 对象; generator <1>:                   生成器表达式<2>.    (line    6)
* 对象; generator <2>:                   yield 表达式.       (line   87)
* 对象; immutable:                       标准类型层级结构.   (line  109)
* 对象; immutable sequence:              标准类型层级结构.   (line  109)
* 对象; instance:                        标准类型层级结构.   (line  435)
* 对象; instance <1>:                    标准类型层级结构.   (line  454)
* 对象; instance <2>:                    调用.               (line  114)
* 对象; instancemethod:                  实例方法对象.       (line    6)
* 对象; integer:                         标准类型层级结构.   (line   57)
* 对象; integer <1>:                     数字类型 --- int float complex.
                                                             (line    6)
* 对象; integer <2>:                     整数型对象.         (line    6)
* 对象; io.StringIO:                     文本序列类型 --- str.
                                                             (line   31)
* 对象; list:                            标准类型层级结构.   (line  153)
* 对象; list <1>:                        列表显示.           (line    6)
* 对象; list <2>:                        属性引用.           (line   10)
* 对象; list <3>:                        抽取.               (line    6)
* 对象; list <4>:                        切片.               (line    6)
* 对象; list <5>:                        赋值语句.           (line   85)
* 对象; list <6>:                        可变序列类型.       (line    6)
* 对象; list <7>:                        列表<2>.            (line    6)
* 对象; list <8>:                        列表对象.           (line    6)
* 对象; long integer:                    整数型对象.         (line    6)
* 对象; mapping:                         标准类型层级结构.   (line  193)
* 对象; mapping <1>:                     标准类型层级结构.   (line  468)
* 对象; mapping <2>:                     抽取.               (line    6)
* 对象; mapping <3>:                     赋值语句.           (line   90)
* 对象; mapping <4>:                     映射类型 --- dict.  (line    6)
* 对象; mapping <5>:                     容器对象.           (line    6)
* 对象; memoryview:                      二进制序列类型 --- bytes bytearray memoryview.
                                                             (line    6)
* 对象; memoryview <1>:                  Ellipsis 对象.      (line   10)
* 对象; method:                          实例对象.           (line   25)
* 对象; method <1>:                      标准类型层级结构.   (line  298)
* 对象; method <2>:                      标准类型层级结构.   (line  379)
* 对象; method <3>:                      调用.               (line  105)
* 对象; method <4>:                      方法.               (line    6)
* 对象; method <5>:                      方法对象<2>.        (line    6)
* 对象; module:                          标准类型层级结构.   (line  398)
* 对象; module <1>:                      属性引用.           (line   10)
* 对象; module <2>:                      模块对象.           (line    6)
* 对象; mutable:                         标准类型层级结构.   (line  146)
* 对象; mutable <1>:                     赋值语句.           (line    6)
* 对象; mutable <2>:                     赋值语句.           (line   81)
* 对象; mutable sequence:                标准类型层级结构.   (line  146)
* 对象; None:                            标准类型层级结构.   (line   15)
* 对象; None <1>:                        表达式语句.         (line   15)
* 对象; None <2>:                        None 对象.          (line    6)
* 对象; NotImplemented:                  标准类型层级结构.   (line   21)
* 对象; numeric:                         标准类型层级结构.   (line   35)
* 对象; numeric <1>:                     标准类型层级结构.   (line  468)
* 对象; numeric <2>:                     数字类型 --- int float complex.
                                                             (line    6)
* 对象; numeric <3>:                     数值对象.           (line    6)
* 对象; range:                           range 对象.         (line    6)
* 对象; sequence:                        标准类型层级结构.   (line   93)
* 对象; sequence <1>:                    标准类型层级结构.   (line  468)
* 对象; sequence <2>:                    抽取.               (line    6)
* 对象; sequence <3>:                    切片.               (line    6)
* 对象; sequence <4>:                    成员检测运算.       (line   30)
* 对象; sequence <5>:                    赋值语句.           (line   85)
* 对象; sequence <6>:                    for 语句<2>.        (line    6)
* 对象; sequence <7>:                    通用序列操作.       (line    6)
* 对象; sequence <8>:                    序列对象.           (line    6)
* 对象; set:                             标准类型层级结构.   (line  182)
* 对象; set <1>:                         集合显示.           (line    6)
* 对象; set <2>:                         集合类型 --- set frozenset.
                                                             (line    6)
* 对象; set <3>:                         集合对象.           (line    6)
* 对象; set type:                        标准类型层级结构.   (line  169)
* 对象; slice:                           模拟容器类型.       (line   50)
* 对象; socket:                          socket --- 底层网络接口.
                                                             (line   15)
* 对象; string:                          抽取.               (line    6)
* 对象; string <1>:                      切片.               (line    6)
* 对象; string <2>:                      range 对象.         (line  109)
* 对象; traceback:                       标准类型层级结构.   (line  571)
* 对象; traceback <1>:                   raise 语句.         (line   18)
* 对象; traceback <2>:                   try 语句.           (line   56)
* 对象; traceback <3>:                   sys --- 系统相关的参数和函数.
                                                             (line  302)
* 对象; traceback <4>:                   traceback --- 打印或检索堆栈回溯.
                                                             (line   14)
* 对象; tuple:                           标准类型层级结构.   (line  130)
* 对象; tuple <1>:                       抽取.               (line    6)
* 对象; tuple <2>:                       切片.               (line    6)
* 对象; tuple <3>:                       表达式列表.         (line   11)
* 对象; tuple <4>:                       不可变序列类型.     (line    6)
* 对象; tuple <5>:                       元组.               (line    6)
* 对象; tuple <6>:                       元组对象.           (line    6)
* 对象; type:                            内置函数.           (line 1404)
* 对象; type <1>:                        对象、类型和引用计数.
                                                             (line    6)
* 对象; type <2>:                        类型对象<2>.        (line    6)
* 对象; user-defined function:           标准类型层级结构.   (line  228)
* 对象; user-defined function <1>:       调用.               (line   99)
* 对象; user-defined function <2>:       函数定义.           (line    6)
* 对象; user-defined method:             标准类型层级结构.   (line  298)
* 模块; array:                           标准类型层级结构.   (line  164)
* 模块; array <1>:                       二进制序列类型 --- bytes bytearray memoryview.
                                                             (line    6)
* 模块; base64:                          binascii --- 二进制和 ASCII 码互转.
                                                             (line    6)
* 模块; bdb:                             pdb --- Python的调试器.
                                                             (line   15)
* 模块; binhex:                          binascii --- 二进制和 ASCII 码互转.
                                                             (line    6)
* 模块; builtins:                        dir 函数.           (line   41)
* 模块; builtins <1>:                    完整的 Python 程序. (line    6)
* 模块; builtins <2>:                    嵌入Python<2>.      (line   12)
* 模块; builtins <3>:                    Initializing and finalizing the interpreter.
                                                             (line    8)
* 模块; builtins <4>:                    Sub-interpreter support.
                                                             (line   26)
* 模块; cmd:                             pdb --- Python的调试器.
                                                             (line   15)
* 模块; copy:                            copyreg --- 注册配合 pickle 模块使用的函数.
                                                             (line    8)
* 模块; crypt:                           pwd --- 用户密码数据库.
                                                             (line   41)
* 模块; dbm.gnu:                         标准类型层级结构.   (line  215)
* 模块; dbm.gnu <1>:                     限制.               (line    6)
* 模块; dbm.ndbm:                        标准类型层级结构.   (line  215)
* 模块; dbm.ndbm <1>:                    限制.               (line    6)
* 模块; errno:                           具体异常.           (line  100)
* 模块; glob:                            fnmatch --- Unix 文件名模式匹配.
                                                             (line   33)
* 模块; imp:                             内置函数.           (line 1497)
* 模块; io:                              标准类型层级结构.   (line  476)
* 模块; json:                            使用 json 保存结构化数据.
                                                             (line    6)
* 模块; math:                            数字类型 --- int float complex.
                                                             (line   92)
* 模块; math <1>:                        常量<3>.            (line   44)
* 模块; os:                              posix --- 最常见的 POSIX 系统调用.
                                                             (line   11)
* 模块; pickle:                          copy --- 浅层 shallow 和深层 deep 复制操作.
                                                             (line   59)
* 模块; pickle <1>:                      copyreg --- 注册配合 pickle 模块使用的函数.
                                                             (line    8)
* 模块; pickle <2>:                      shelve --- Python 对象持久化.
                                                             (line    8)
* 模块; pickle <3>:                      marshal --- 内部 Python 对象序列化.
                                                             (line   13)
* 模块; pty:                             文件描述符操作.     (line  318)
* 模块; pwd:                             os path --- 常用路径操作.
                                                             (line  124)
* 模块; pyexpat:                         xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line   17)
* 模块; re:                              字符串的方法<2>.    (line    6)
* 模块; re <1>:                          fnmatch --- Unix 文件名模式匹配.
                                                             (line    8)
* 模块; shelve:                          marshal --- 内部 Python 对象序列化.
                                                             (line   13)
* 模块; signal:                          _thread --- 底层多线程 API.
                                                             (line  141)
* 模块; signal <1>:                      信号处理<2>.        (line    8)
* 模块; sitecustomize:                   site —— 站点专属的配置钩子.
                                                             (line   77)
* 模块; socket:                          互联网协议和支持.   (line    6)
* 模块; stat:                            文件和目录.         (line  875)
* 模块; string:                          locale --- 国际化服务.
                                                             (line  440)
* 模块; struct:                          套接字对象.         (line  459)
* 模块; sys:                             标准模块.           (line    6)
* 模块; sys <1>:                         try 语句.           (line   56)
* 模块; sys <2>:                         完整的 Python 程序. (line    6)
* 模块; sys <3>:                         内置函数.           (line 1017)
* 模块; sys <4>:                         嵌入Python<2>.      (line   12)
* 模块; sys <5>:                         Initializing and finalizing the interpreter.
                                                             (line    8)
* 模块; sys <6>:                         Sub-interpreter support.
                                                             (line   26)
* 模块; types:                           类型对象.           (line    6)
* 模块; urllib.request:                  http client --- HTTP 协议客户端.
                                                             (line    8)
* 模块; usercustomize:                   site —— 站点专属的配置钩子.
                                                             (line   85)
* 模块; uu:                              binascii --- 二进制和 ASCII 码互转.
                                                             (line    6)
* 模块; _locale:                         locale --- 国际化服务.
                                                             (line   16)
* 模块; _thread:                         高阶 API.           (line   45)
* 模块; __main__:                        名称的解析.         (line   40)
* 模块; __main__ <1>:                    完整的 Python 程序. (line    6)
* 模块; __main__ <2>:                    完整的 Python 程序. (line   15)
* 模块; __main__ <3>:                    runpy --- Locating and executing Python modules.
                                                             (line   30)
* 模块; __main__ <4>:                    runpy --- Locating and executing Python modules.
                                                             (line   97)
* 模块; __main__ <5>:                    嵌入Python<2>.      (line   12)
* 模块; __main__ <6>:                    Initializing and finalizing the interpreter.
                                                             (line    8)
* 模块; __main__ <7>:                    Sub-interpreter support.
                                                             (line   26)
* 环境变量; APPDATA:                     PEP 370 分用户的 site-packages 目录.
                                                             (line   26)
* 环境变量; AUDIODEV:                    ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line   51)
* 环境变量; BROWSER:                     webbrowser --- 方便的Web浏览器控制器.
                                                             (line   17)
* 环境变量; BROWSER <1>:                 webbrowser --- 方便的Web浏览器控制器.
                                                             (line   79)
* 环境变量; CC:                          新增，改进和弃用的模块<4>.
                                                             (line   58)
* 环境变量; CFLAGS:                      新增，改进和弃用的模块<4>.
                                                             (line   58)
* 环境变量; CFLAGS <1>:                  Tweaking compiler/linker flags.
                                                             (line   66)
* 环境变量; CFLAGS <2>:                  Tweaking compiler/linker flags.
                                                             (line   67)
* 环境变量; COLS:                        curses<2>.          (line    7)
* 环境变量; COLS <1>:                    函数<3>.            (line  436)
* 环境变量; COLUMNS:                     函数<3>.            (line  456)
* 环境变量; COLUMNS <1>:                 函数<3>.            (line  457)
* 环境变量; COMSPEC:                     进程管理.           (line  560)
* 环境变量; COMSPEC <1>:                 Popen 构造函数.     (line   74)
* 环境变量; CPP:                         新增，改进和弃用的模块<4>.
                                                             (line   59)
* 环境变量; CPPFLAGS:                    新增，改进和弃用的模块<4>.
                                                             (line   59)
* 环境变量; DISTUTILS_DEBUG:             Debugging the setup script.
                                                             (line   19)
* 环境变量; exec_prefix:                 与Python相关的路径和文件.
                                                             (line    6)
* 环境变量; exec_prefix <1>:             包含文件.           (line   32)
* 环境变量; exec_prefix <2>:             包含文件.           (line   40)
* 环境变量; HOME:                        os path.            (line   14)
* 环境变量; HOME <1>:                    Python API 的变化.  (line  103)
* 环境变量; HOME <2>:                    Windows<10>.        (line   13)
* 环境变量; HOME <3>:                    Windows<10>.        (line   16)
* 环境变量; HOME <4>:                    os path --- 常用路径操作.
                                                             (line  124)
* 环境变量; HOME <5>:                    os path --- 常用路径操作.
                                                             (line  136)
* 环境变量; HOME <6>:                    distutils util --- Miscellaneous other utility functions.
                                                             (line   77)
* 环境变量; HOME <7>:                    Location and names of config files.
                                                             (line   50)
* 环境变量; HOME <8>:                    Location and names of config files.
                                                             (line   67)
* 环境变量; HOMEDRIVE:                   os path --- 常用路径操作.
                                                             (line  129)
* 环境变量; HOMEDRIVE <1>:               Location and names of config files.
                                                             (line   68)
* 环境变量; HOMEPATH:                    os path --- 常用路径操作.
                                                             (line  128)
* 环境变量; HOMEPATH <1>:                Location and names of config files.
                                                             (line   68)
* 环境变量; http_proxy:                  urllib request --- 用于打开 URL 的可扩展库.
                                                             (line   75)
* 环境变量; http_proxy <1>:              例子<21>.           (line   89)
* 环境变量; http_proxy <2>:              基本认证.           (line   57)
* 环境变量; IDLESTARTUP:                 IDLE<27>.           (line  174)
* 环境变量; IDLESTARTUP <1>:             IDLE<31>.           (line    9)
* 环境变量; IDLESTARTUP <2>:             IDLE<37>.           (line    9)
* 环境变量; IDLESTARTUP <3>:             启动和代码执行.     (line    7)
* 环境变量; KDEDIR:                      webbrowser --- 方便的Web浏览器控制器.
                                                             (line  164)
* 环境变量; LANG:                        GNU gettext API.    (line   18)
* 环境变量; LANG <1>:                    基于类的 API.       (line   22)
* 环境变量; LANG <2>:                    locale --- 国际化服务.
                                                             (line   49)
* 环境变量; LANG <3>:                    locale --- 国际化服务.
                                                             (line  292)
* 环境变量; LANG <4>:                    locale --- 国际化服务.
                                                             (line  296)
* 环境变量; LANGUAGE:                    GNU gettext API.    (line   17)
* 环境变量; LANGUAGE <1>:                基于类的 API.       (line   21)
* 环境变量; LC_ALL:                      GNU gettext API.    (line   17)
* 环境变量; LC_ALL <1>:                  基于类的 API.       (line   21)
* 环境变量; LC_MESSAGES:                 GNU gettext API.    (line   18)
* 环境变量; LC_MESSAGES <1>:             基于类的 API.       (line   21)
* 环境变量; LDCXXSHARED:                 构建和 C API 的改变<8>.
                                                             (line  153)
* 环境变量; LDFLAGS:                     新增，改进和弃用的模块<4>.
                                                             (line   59)
* 环境变量; LINES:                       curses<2>.          (line    6)
* 环境变量; LINES <1>:                   函数<3>.            (line  104)
* 环境变量; LINES <2>:                   函数<3>.            (line  436)
* 环境变量; LINES <3>:                   函数<3>.            (line  456)
* 环境变量; LINES <4>:                   函数<3>.            (line  457)
* 环境变量; LNAME:                       getpass --- 便携式密码输入工具.
                                                             (line   35)
* 环境变量; LOGNAME:                     进程参数.           (line  199)
* 环境变量; LOGNAME <1>:                 getpass --- 便携式密码输入工具.
                                                             (line   35)
* 环境变量; MIXERDEV:                    ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line   71)
* 环境变量; no_proxy:                    urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  252)
* 环境变量; PAGER:                       pydoc --- 文档生成器和在线帮助系统.
                                                             (line   38)
* 环境变量; PATH:                        Python API 的变化.  (line  125)
* 环境变量; PATH <1>:                    'python' 命令行为的变化<2>.
                                                             (line    6)
* 环境变量; PATH <2>:                    'python' 命令行为的变化<2>.
                                                             (line   11)
* 环境变量; PATH <3>:                    'python' 命令行为的变化<2>.
                                                             (line   12)
* 环境变量; PATH <4>:                    安全<19>.           (line   16)
* 环境变量; PATH <5>:                    安全<19>.           (line   20)
* 环境变量; PATH <6>:                    模块搜索路径.       (line   12)
* 环境变量; PATH <7>:                    可执行的Python脚本. (line   11)
* 环境变量; PATH <8>:                    环境变量.           (line   22)
* 环境变量; PATH <9>:                    杂项.               (line   14)
* 环境变量; PATH <10>:                   安装步骤.           (line   26)
* 环境变量; PATH <11>:                   安装步骤.           (line   45)
* 环境变量; PATH <12>:                   无UI 安装.          (line   49)
* 环境变量; PATH <13>:                   附录：设置环境变量. (line   19)
* 环境变量; PATH <14>:                   附录：设置环境变量. (line   27)
* 环境变量; PATH <15>:                   查找Python可执行文件.
                                                             (line   12)
* 环境变量; PATH <16>:                   查找Python可执行文件.
                                                             (line   17)
* 环境变量; PATH <17>:                   查找Python可执行文件.
                                                             (line   18)
* 环境变量; PATH <18>:                   适用于Windows的Python启动器.
                                                             (line   12)
* 环境变量; PATH <19>:                   从命令行.           (line    8)
* 环境变量; PATH <20>:                   从命令行.           (line   33)
* 环境变量; PATH <21>:                   Shebang Lines.      (line   39)
* 环境变量; PATH <22>:                   Shebang Lines.      (line   40)
* 环境变量; PATH <23>:                   进程管理.           (line   39)
* 环境变量; PATH <24>:                   进程管理.           (line   69)
* 环境变量; PATH <25>:                   进程管理.           (line   71)
* 环境变量; PATH <26>:                   进程管理.           (line   73)
* 环境变量; PATH <27>:                   进程管理.           (line  386)
* 环境变量; PATH <28>:                   进程管理.           (line  458)
* 环境变量; PATH <29>:                   进程管理.           (line  459)
* 环境变量; PATH <30>:                   进程管理.           (line  461)
* 环境变量; PATH <31>:                   其他系统信息.       (line   97)
* 环境变量; PATH <32>:                   webbrowser --- 方便的Web浏览器控制器.
                                                             (line  192)
* 环境变量; PATH <33>:                   Installing your CGI script on a Unix system.
                                                             (line   29)
* 环境变量; PATH <34>:                   Common problems and solutions.
                                                             (line   23)
* 环境变量; PATH <35>:                   site —— 站点专属的配置钩子.
                                                             (line   45)
* 环境变量; PATH <36>:                   嵌入Python<2>.      (line   31)
* 环境变量; PATH <37>:                   嵌入Python<2>.      (line   37)
* 环境变量; PATH <38>:                   在 Unix 中怎样让 Python 脚本可执行？.
                                                             (line   19)
* 环境变量; PATH <39>:                   在 Unix 中怎样让 Python 脚本可执行？.
                                                             (line   24)
* 环境变量; PATHEXT:                     其他改进<2>.        (line   30)
* 环境变量; PATHEXT <1>:                 库<7>.              (line  116)
* 环境变量; PATHEXT <2>:                 无UI 安装.          (line   50)
* 环境变量; PIP_USER:                    Windows<16>.        (line    7)
* 环境变量; PLAT:                        distutils util --- Miscellaneous other utility functions.
                                                             (line   79)
* 环境变量; POSIXLY_CORRECT:             getopt --- C 风格的命令行选项解析器.
                                                             (line   52)
* 环境变量; prefix:                      与Python相关的路径和文件.
                                                             (line    6)
* 环境变量; prefix <1>:                  包含文件.           (line   32)
* 环境变量; prefix <2>:                  包含文件.           (line   35)
* 环境变量; prefix <3>:                  包含文件.           (line   39)
* 环境变量; PYTHON*:                     其他改进<2>.        (line    9)
* 环境变量; PYTHON* <1>:                 接口选项.           (line   66)
* 环境变量; PYTHON* <2>:                 接口选项.           (line  119)
* 环境变量; PYTHON* <3>:                 其他选项.           (line   37)
* 环境变量; PYTHON* <4>:                 其他选项.           (line   53)
* 环境变量; PYTHON* <5>:                 全局配置变量.       (line   54)
* 环境变量; PYTHONASYNCIODEBUG:          环境变量.           (line  208)
* 环境变量; PYTHONASYNCIODEBUG <1>:      开启调试模式.       (line   10)
* 环境变量; PYTHONASYNCIODEBUG <2>:      Debug 模式.         (line   11)
* 环境变量; PYTHONBREAKPOINT:            PEP 553 内置的 breakpoint.
                                                             (line   12)
* 环境变量; PYTHONBREAKPOINT <1>:        环境变量.           (line   54)
* 环境变量; PYTHONBREAKPOINT <2>:        sys --- 系统相关的参数和函数.
                                                             (line  165)
* 环境变量; PYTHONBREAKPOINT <3>:        sys --- 系统相关的参数和函数.
                                                             (line  175)
* 环境变量; PYTHONBREAKPOINT <4>:        sys --- 系统相关的参数和函数.
                                                             (line  179)
* 环境变量; PYTHONCASEOK:                PEP 235 Importing Modules on Case-Insensitive Platforms.
                                                             (line   17)
* 环境变量; PYTHONCASEOK <1>:            环境变量.           (line   88)
* 环境变量; PYTHONCOERCECLOCALE:         PEP 538 传统 C 区域强制转换.
                                                             (line   11)
* 环境变量; PYTHONCOERCECLOCALE <1>:     环境变量.           (line  284)
* 环境变量; PYTHONCOERCECLOCALE <2>:     环境变量.           (line  378)
* 环境变量; PYTHONCOERCECLOCALE <3>:     Python Configuration.
                                                             (line   15)
* 环境变量; PYTHONDEBUG:                 其他选项.           (line   32)
* 环境变量; PYTHONDEBUG <1>:             环境变量.           (line   65)
* 环境变量; PYTHONDEBUG <2>:             全局配置变量.       (line   26)
* 环境变量; PYTHONDEVMODE:               开发运行时模式 -X dev.
                                                             (line    6)
* 环境变量; PYTHONDEVMODE <1>:           环境变量.           (line  328)
* 环境变量; PYTHONDEVMODE <2>:           test support script_helper --- Utilities for the Python execution tests.
                                                             (line  102)
* 环境变量; PYTHONDOCS:                  pydoc --- 文档生成器和在线帮助系统.
                                                             (line   67)
* 环境变量; PYTHONDONTWRITEBYTECODE:     Interpreter Changes<2>.
                                                             (line   16)
* 环境变量; PYTHONDONTWRITEBYTECODE <1>: 新增和改进的模块<2>.
                                                             (line  624)
* 环境变量; PYTHONDONTWRITEBYTECODE <2>: 其他选项.           (line   17)
* 环境变量; PYTHONDONTWRITEBYTECODE <3>: 环境变量.           (line   93)
* 环境变量; PYTHONDONTWRITEBYTECODE <4>: sys --- 系统相关的参数和函数.
                                                             (line  240)
* 环境变量; PYTHONDONTWRITEBYTECODE <5>: 全局配置变量.       (line   34)
* 环境变量; PYTHONDONTWRITEBYTECODE <6>: 如何创建 pyc 文件？.
                                                             (line   17)
* 环境变量; PYTHONDUMPREFS:              调试构建使用与发布构建相同的 ABI.
                                                             (line   12)
* 环境变量; PYTHONDUMPREFS <1>:          构建<15>.           (line   54)
* 环境变量; PYTHONDUMPREFS <2>:          调试模式变量.       (line   14)
* 环境变量; PYTHONDUMPREFS <3>:          PyObject Slots.     (line   24)
* 环境变量; PYTHONEXECUTABLE:            环境变量.           (line  159)
* 环境变量; PYTHONFAULTHANDLER:          faulthandler<3>.    (line   11)
* 环境变量; PYTHONFAULTHANDLER <1>:      环境变量.           (line  183)
* 环境变量; PYTHONFAULTHANDLER <2>:      faulthandler --- Dump the Python traceback.
                                                             (line   14)
* 环境变量; PYTHONHASHSEED:              Builtin functions and types.
                                                             (line   17)
* 环境变量; PYTHONHASHSEED <1>:          Porting Python code.
                                                             (line    6)
* 环境变量; PYTHONHASHSEED <2>:          核心与内置<36>.     (line   30)
* 环境变量; PYTHONHASHSEED <3>:          其他选项.           (line   83)
* 环境变量; PYTHONHASHSEED <4>:          其他选项.           (line   95)
* 环境变量; PYTHONHASHSEED <5>:          环境变量.           (line  106)
* 环境变量; PYTHONHASHSEED <6>:          环境变量.           (line  111)
* 环境变量; PYTHONHASHSEED <7>:          基本定制.           (line  238)
* 环境变量; PYTHONHASHSEED <8>:          全局配置变量.       (line   46)
* 环境变量; PYTHONHASHSEED <9>:          全局配置变量.       (line   49)
* 环境变量; PYTHONHOME:                  摘要 - 发布重点<3>. (line   90)
* 环境变量; PYTHONHOME <1>:              其他选项.           (line   38)
* 环境变量; PYTHONHOME <2>:              环境变量.           (line    9)
* 环境变量; PYTHONHOME <3>:              环境变量.           (line   16)
* 环境变量; PYTHONHOME <4>:              环境变量.           (line   17)
* 环境变量; PYTHONHOME <5>:              环境变量.           (line   31)
* 环境变量; PYTHONHOME <6>:              查找模块.           (line   38)
* 环境变量; PYTHONHOME <7>:              查找模块.           (line   52)
* 环境变量; PYTHONHOME <8>:              查找模块.           (line   80)
* 环境变量; PYTHONHOME <9>:              test support script_helper --- Utilities for the Python execution tests.
                                                             (line   24)
* 环境变量; PYTHONHOME <10>:             嵌入Python<2>.      (line   38)
* 环境变量; PYTHONHOME <11>:             嵌入Python<2>.      (line   44)
* 环境变量; PYTHONHOME <12>:             全局配置变量.       (line   55)
* 环境变量; PYTHONHOME <13>:             Process-wide parameters.
                                                             (line  269)
* 环境变量; PYTHONHOME <14>:             Process-wide parameters.
                                                             (line  283)
* 环境变量; PYTHONHOME <15>:             PyConfig.           (line  197)
* 环境变量; PYTHONHOME <16>:             Modifying Python's Search Path.
                                                             (line   60)
* 环境变量; PYTHONHOME <17>:             Modifying Python's Search Path.
                                                             (line   62)
* 环境变量; PYTHONINSPECT:               Other Changes and Fixes<2>.
                                                             (line   13)
* 环境变量; PYTHONINSPECT <1>:           其他选项.           (line   46)
* 环境变量; PYTHONINSPECT <2>:           环境变量.           (line   70)
* 环境变量; PYTHONINSPECT <3>:           全局配置变量.       (line   66)
* 环境变量; PYTHONIOENCODING:            其他改进<2>.        (line   75)
* 环境变量; PYTHONIOENCODING <1>:        Interpreter Changes<2>.
                                                             (line   23)
* 环境变量; PYTHONIOENCODING <2>:        环境变量.           (line  122)
* 环境变量; PYTHONIOENCODING <3>:        环境变量.           (line  312)
* 环境变量; PYTHONIOENCODING <4>:        环境变量.           (line  370)
* 环境变量; PYTHONIOENCODING <5>:        sys --- 系统相关的参数和函数.
                                                             (line 1270)
* 环境变量; PYTHONIOENCODING <6>:        Process-wide parameters.
                                                             (line   14)
* 环境变量; PYTHONIOENCODING <7>:        Process-wide parameters.
                                                             (line   18)
* 环境变量; PYTHONLEGACYWINDOWSFSENCODING: PEP 529 将Windows文件系统编码更改为UTF-8.
                                                             (line   18)
* 环境变量; PYTHONLEGACYWINDOWSFSENCODING <1>: 环境变量.     (line  259)
* 环境变量; PYTHONLEGACYWINDOWSFSENCODING <2>: sys --- 系统相关的参数和函数.
                                                             (line 1232)
* 环境变量; PYTHONLEGACYWINDOWSFSENCODING <3>: 全局配置变量. (line   88)
* 环境变量; PYTHONLEGACYWINDOWSSTDIO:    PEP 528 将Windows控制台编码更改为UTF-8.
                                                             (line   12)
* 环境变量; PYTHONLEGACYWINDOWSSTDIO <1>: 环境变量.          (line  135)
* 环境变量; PYTHONLEGACYWINDOWSSTDIO <2>: 环境变量.          (line  272)
* 环境变量; PYTHONLEGACYWINDOWSSTDIO <3>: sys --- 系统相关的参数和函数.
                                                             (line 1273)
* 环境变量; PYTHONLEGACYWINDOWSSTDIO <4>: 全局配置变量.      (line  100)
* 环境变量; PYTHONMALLOC:                PYTHONMALLOC 环境变量.
                                                             (line    6)
* 环境变量; PYTHONMALLOC <1>:            C API 的变化<3>.    (line    9)
* 环境变量; PYTHONMALLOC <2>:            核心与内置<56>.     (line   91)
* 环境变量; PYTHONMALLOC <3>:            环境变量.           (line  215)
* 环境变量; PYTHONMALLOC <4>:            环境变量.           (line  252)
* 环境变量; PYTHONMALLOC <5>:            概述<16>.           (line   54)
* 环境变量; PYTHONMALLOC <6>:            默认内存分配器.     (line   26)
* 环境变量; PYTHONMALLOC <7>:            自定义内存分配器.   (line  121)
* 环境变量; PYTHONMALLOCSTATS:           核心与内置<56>.     (line   97)
* 环境变量; PYTHONMALLOCSTATS <1>:       环境变量.           (line  247)
* 环境变量; PYTHONMALLOCSTATS <2>:       概述<16>.           (line   57)
* 环境变量; PYTHONNOUSERSITE:            PEP 370 分用户的 site-packages 目录.
                                                             (line   30)
* 环境变量; PYTHONNOUSERSITE <1>:        环境变量.           (line  138)
* 环境变量; PYTHONNOUSERSITE <2>:        模块内容<7>.        (line   14)
* 环境变量; PYTHONNOUSERSITE <3>:        全局配置变量.       (line  120)
* 环境变量; PYTHONOPTIMIZE:              其他选项.           (line   62)
* 环境变量; PYTHONOPTIMIZE <1>:          环境变量.           (line   49)
* 环境变量; PYTHONOPTIMIZE <2>:          全局配置变量.       (line  125)
* 环境变量; PYTHONPATH:                  'python' 命令行为的变化<2>.
                                                             (line    8)
* 环境变量; PYTHONPATH <1>:              'python' 命令行为的变化<2>.
                                                             (line    9)
* 环境变量; PYTHONPATH <2>:              模块搜索路径.       (line   12)
* 环境变量; PYTHONPATH <3>:              标准模块.           (line   27)
* 环境变量; PYTHONPATH <4>:              标准模块.           (line   27)
* 环境变量; PYTHONPATH <5>:              其他选项.           (line   37)
* 环境变量; PYTHONPATH <6>:              环境变量.           (line   20)
* 环境变量; PYTHONPATH <7>:              环境变量.           (line   26)
* 环境变量; PYTHONPATH <8>:              环境变量.           (line   32)
* 环境变量; PYTHONPATH <9>:              环境变量.           (line   34)
* 环境变量; PYTHONPATH <10>:             附录：设置环境变量. (line   30)
* 环境变量; PYTHONPATH <11>:             查找模块.           (line   27)
* 环境变量; PYTHONPATH <12>:             查找模块.           (line   45)
* 环境变量; PYTHONPATH <13>:             查找模块.           (line   79)
* 环境变量; PYTHONPATH <14>:             配置.               (line    6)
* 环境变量; PYTHONPATH <15>:             Installing your CGI script on a Unix system.
                                                             (line   29)
* 环境变量; PYTHONPATH <16>:             test support script_helper --- Utilities for the Python execution tests.
                                                             (line   25)
* 环境变量; PYTHONPATH <17>:             sys --- 系统相关的参数和函数.
                                                             (line  901)
* 环境变量; PYTHONPATH <18>:             sys --- 系统相关的参数和函数.
                                                             (line  907)
* 环境变量; PYTHONPATH <19>:             构建C/C++扩展.      (line    9)
* 环境变量; PYTHONPATH <20>:             嵌入Python<2>.      (line   39)
* 环境变量; PYTHONPATH <21>:             嵌入Python<2>.      (line   44)
* 环境变量; PYTHONPATH <22>:             全局配置变量.       (line   54)
* 环境变量; PYTHONPATH <23>:             PyConfig.           (line  252)
* 环境变量; PYTHONPATH <24>:             Modifying Python's Search Path.
                                                             (line   67)
* 环境变量; PYTHONPATH <25>:             Modifying Python's Search Path.
                                                             (line   68)
* 环境变量; PYTHONPROFILEIMPORTTIME:     其他语言特性修改<2>.
                                                             (line   44)
* 环境变量; PYTHONPROFILEIMPORTTIME <1>: 核心与内置<38>.     (line   67)
* 环境变量; PYTHONPROFILEIMPORTTIME <2>: 其他选项.           (line  191)
* 环境变量; PYTHONPROFILEIMPORTTIME <3>: 环境变量.           (line  201)
* 环境变量; PYTHONPYCACHEPREFIX:         用于已编译字节码文件的并行文件系统缓存.
                                                             (line    6)
* 环境变量; PYTHONPYCACHEPREFIX <1>:     核心与内置<29>.     (line  396)
* 环境变量; PYTHONPYCACHEPREFIX <2>:     其他选项.           (line  218)
* 环境变量; PYTHONPYCACHEPREFIX <3>:     环境变量.           (line   98)
* 环境变量; PYTHONPYCACHEPREFIX <4>:     sys --- 系统相关的参数和函数.
                                                             (line  255)
* 环境变量; PYTHONSHOWALLOCCOUNT:        Two new environment variables for debug mode.
                                                             (line   11)
* 环境变量; PYTHONSHOWREFCOUNT:          Two new environment variables for debug mode.
                                                             (line    7)
* 环境变量; PYTHONSTARTUP:               sys<6>.             (line   17)
* 环境变量; PYTHONSTARTUP <1>:           sys<6>.             (line   21)
* 环境变量; PYTHONSTARTUP <2>:           IDLE<27>.           (line  174)
* 环境变量; PYTHONSTARTUP <3>:           IDLE<31>.           (line    9)
* 环境变量; PYTHONSTARTUP <4>:           IDLE<37>.           (line    9)
* 环境变量; PYTHONSTARTUP <5>:           交互式启动文件.     (line    7)
* 环境变量; PYTHONSTARTUP <6>:           其他选项.           (line   44)
* 环境变量; PYTHONSTARTUP <7>:           环境变量.           (line   38)
* 环境变量; PYTHONSTARTUP <8>:           示例.               (line    8)
* 环境变量; PYTHONSTARTUP <9>:           启动和代码执行.     (line    7)
* 环境变量; PYTHONSTARTUP <10>:          sys --- 系统相关的参数和函数.
                                                             (line  815)
* 环境变量; PYTHONSTARTUP <11>:          Readline（类库） 配置.
                                                             (line   10)
* 环境变量; PYTHONTHREADDEBUG:           调试模式变量.       (line    8)
* 环境变量; PYTHONTRACEMALLOC:           环境变量.           (line  192)
* 环境变量; PYTHONTRACEMALLOC <1>:       tracemalloc --- 跟踪内存分配.
                                                             (line   25)
* 环境变量; PYTHONTRACEMALLOC <2>:       tracemalloc --- 跟踪内存分配.
                                                             (line   32)
* 环境变量; PYTHONTRACEMALLOC <3>:       函数<9>.            (line   68)
* 环境变量; PYTHONUNBUFFERED:            其他选项.           (line  121)
* 环境变量; PYTHONUNBUFFERED <1>:        环境变量.           (line   78)
* 环境变量; PYTHONUNBUFFERED <2>:        全局配置变量.       (line  140)
* 环境变量; PYTHONUSERBASE:              PEP 370 分用户的 site-packages 目录.
                                                             (line   23)
* 环境变量; PYTHONUSERBASE <1>:          环境变量.           (line  148)
* 环境变量; PYTHONUSERBASE <2>:          模块内容<7>.        (line   35)
* 环境变量; PYTHONUSERBASE <3>:          模块内容<7>.        (line   59)
* 环境变量; PYTHONUSERSITE:              test support script_helper --- Utilities for the Python execution tests.
                                                             (line   25)
* 环境变量; PYTHONUTF8:                  PEP 540 强制 UTF-8 运行时模式.
                                                             (line    6)
* 环境变量; PYTHONUTF8 <1>:              其他选项.           (line  215)
* 环境变量; PYTHONUTF8 <2>:              环境变量.           (line  320)
* 环境变量; PYTHONUTF8 <3>:              环境变量.           (line  335)
* 环境变量; PYTHONUTF8 <4>:              UTF-8 模式.         (line   16)
* 环境变量; PYTHONUTF8 <5>:              sys --- 系统相关的参数和函数.
                                                             (line 1272)
* 环境变量; PYTHONUTF8 <6>:              Python Configuration.
                                                             (line   14)
* 环境变量; PYTHONVERBOSE:               其他选项.           (line  129)
* 环境变量; PYTHONVERBOSE <1>:           环境变量.           (line   83)
* 环境变量; PYTHONVERBOSE <2>:           全局配置变量.       (line  151)
* 环境变量; PYTHONWARNINGS:              warnings.           (line   18)
* 环境变量; PYTHONWARNINGS <1>:          其他语言特性修改<7>.
                                                             (line  158)
* 环境变量; PYTHONWARNINGS <2>:          Changes to the Handling of Deprecation Warnings.
                                                             (line   25)
* 环境变量; PYTHONWARNINGS <3>:          Interpreter Changes.
                                                             (line    6)
* 环境变量; PYTHONWARNINGS <4>:          其他选项.           (line  145)
* 环境变量; PYTHONWARNINGS <5>:          环境变量.           (line  164)
* 环境变量; PYTHONWARNINGS <6>:          Describing Warning Filters.
                                                             (line    7)
* 环境变量; PYTHONWARNINGS <7>:          Describing Warning Filters.
                                                             (line   21)
* 环境变量; PYTHONWARNINGS <8>:          默认警告过滤器.     (line    7)
* 环境变量; PYTHON_DOM:                  模块内容<6>.        (line   19)
* 环境变量; PY_PYTHON:                   自定义默认的Python版本.
                                                             (line   13)
* 环境变量; SOURCE_DATE_EPOCH:           py_compile<2>.      (line    7)
* 环境变量; SOURCE_DATE_EPOCH <1>:       库<29>.             (line  451)
* 环境变量; SOURCE_DATE_EPOCH <2>:       构建<23>.           (line   15)
* 环境变量; SOURCE_DATE_EPOCH <3>:       py_compile --- 编译 Python 源文件.
                                                             (line   51)
* 环境变量; SOURCE_DATE_EPOCH <4>:       py_compile --- 编译 Python 源文件.
                                                             (line   66)
* 环境变量; SOURCE_DATE_EPOCH <5>:       py_compile --- 编译 Python 源文件.
                                                             (line   69)
* 环境变量; SOURCE_DATE_EPOCH <6>:       Command-line use.   (line   83)
* 环境变量; SSLKEYLOGFILE:               上下文创建.         (line   28)
* 环境变量; SSLKEYLOGFILE <1>:           上下文创建.         (line   56)
* 环境变量; SSL_CERT_FILE:               LibreSSL 支持.      (line   13)
* 环境变量; SSL_CERT_PATH:               LibreSSL 支持.      (line   14)
* 环境变量; SystemRoot:                  Popen 构造函数.     (line  188)
* 环境变量; TCL_LIBRARY:                 我怎样“冻结”Tkinter程序？.
                                                             (line   10)
* 环境变量; TEMP:                        tempfile --- 生成临时文件和目录.
                                                             (line  200)
* 环境变量; TERM:                        函数<3>.            (line  366)
* 环境变量; TERM <1>:                    函数<3>.            (line  387)
* 环境变量; TK_LIBRARY:                  我怎样“冻结”Tkinter程序？.
                                                             (line   11)
* 环境变量; TMP:                         tempfile --- 生成临时文件和目录.
                                                             (line  202)
* 环境变量; TMPDIR:                      tempfile --- 生成临时文件和目录.
                                                             (line  198)
* 环境变量; TZ:                          函数<2>.            (line  438)
* 环境变量; TZ <1>:                      函数<2>.            (line  439)
* 环境变量; TZ <2>:                      函数<2>.            (line  446)
* 环境变量; TZ <3>:                      函数<2>.            (line  450)
* 环境变量; TZ <4>:                      函数<2>.            (line  452)
* 环境变量; TZ <5>:                      函数<2>.            (line  505)
* 环境变量; USER:                        getpass --- 便携式密码输入工具.
                                                             (line   35)
* 环境变量; USERNAME:                    进程参数.           (line  200)
* 环境变量; USERNAME <1>:                getpass --- 便携式密码输入工具.
                                                             (line   35)
* 环境变量; USERPROFILE:                 os path.            (line   13)
* 环境变量; USERPROFILE <1>:             Python API 的变化.  (line  102)
* 环境变量; USERPROFILE <2>:             Windows<10>.        (line   13)
* 环境变量; USERPROFILE <3>:             os path --- 常用路径操作.
                                                             (line  128)
* 环境变量; USERPROFILE <4>:             Location and names of config files.
                                                             (line   67)
* 环境变量; USER_BASE:                   新增和改进的模块.   (line  469)
* 环境变量; VIRTUAL_ENV:                 创建虚拟环境<2>.    (line  116)
* 语句; assert:                          assert 语句.        (line    6)
* 语句; assert <1>:                      具体异常.           (line   10)
* 语句; async def:                       协程<2>.            (line    8)
* 语句; async for:                       协程函数定义.       (line   24)
* 语句; async with:                      async for 语句.     (line   39)
* 语句; break:                           break 语句.         (line    6)
* 语句; break <1>:                       while 语句.         (line   15)
* 语句; break <2>:                       for 语句<2>.        (line   19)
* 语句; break <3>:                       try 语句.           (line   62)
* 语句; break <4>:                       try 语句.           (line   86)
* 语句; class:                           类定义.             (line    6)
* 语句; continue:                        continue 语句.      (line    6)
* 语句; continue <1>:                    while 语句.         (line   15)
* 语句; continue <2>:                    for 语句<2>.        (line   19)
* 语句; continue <3>:                    try 语句.           (line   62)
* 语句; continue <4>:                    try 语句.           (line   86)
* 语句; def:                             函数定义.           (line    6)
* 语句; del:                             基本定制.           (line   46)
* 语句; del <1>:                         del 语句<2>.        (line    6)
* 语句; del <2>:                         可变序列类型.       (line   14)
* 语句; del <3>:                         映射类型 --- dict.  (line    6)
* 语句; except:                          内置异常.           (line    6)
* 语句; for:                             for 语句.           (line    6)
* 语句; for <1>:                         break 语句.         (line    6)
* 语句; for <2>:                         continue 语句.      (line    6)
* 语句; for <3>:                         for 语句<2>.        (line    6)
* 语句; global:                          del 语句<2>.        (line   13)
* 语句; global <1>:                      global 语句.        (line    6)
* 语句; if:                              if 语句<2>.         (line    6)
* 语句; if <1>:                          逻辑值检测.         (line    6)
* 语句; import:                          标准类型层级结构.   (line  398)
* 语句; import <1>:                      import 语句.        (line    6)
* 语句; import <2>:                      内置函数.           (line 1497)
* 语句; import <3>:                      site —— 站点专属的配置钩子.
                                                             (line   37)
* 语句; import <4>:                      imp --- Access the import internals.
                                                             (line   11)
* 语句; nonlocal:                        nonlocal 语句.      (line    6)
* 语句; pass:                            pass 语句<2>.       (line    6)
* 语句; raise:                           raise 语句.         (line    6)
* 语句; raise <1>:                       内置异常.           (line   12)
* 语句; return:                          return 语句.        (line    6)
* 语句; return <1>:                      try 语句.           (line   62)
* 语句; return <2>:                      try 语句.           (line   86)
* 语句; try:                             标准类型层级结构.   (line  588)
* 语句; try <1>:                         try 语句.           (line    6)
* 语句; try <2>:                         内置异常.           (line    6)
* 语句; while:                           break 语句.         (line    6)
* 语句; while <1>:                       continue 语句.      (line    6)
* 语句; while <2>:                       while 语句.         (line    6)
* 语句; while <3>:                       逻辑值检测.         (line    6)
* 语句; with:                            with 语句上下文管理器.
                                                             (line   11)
* 语句; with <1>:                        with 语句.          (line    6)
* 语句; yield:                           yield 语句.         (line    6)
* 运算符; !=:                            比较运算.           (line    6)
* 运算符; != <1>:                        比较运算<2>.        (line    6)
* 运算符; % (percent):                   二元算术运算符.     (line   30)
* 运算符; % (percent) <1>:               数字类型 --- int float complex.
                                                             (line   20)
* 运算符; & (ampersand):                 二元位运算.         (line   12)
* 运算符; & (ampersand) <1>:             整数类型的按位运算. (line    6)
* 运算符; * (asterisk):                  二元算术运算符.     (line   15)
* 运算符; * (asterisk) <1>:              数字类型 --- int float complex.
                                                             (line   20)
* 运算符; **:                            幂运算符.           (line    6)
* 运算符; ** <1>:                        数字类型 --- int float complex.
                                                             (line   20)
* 运算符; / (slash):                     二元算术运算符.     (line   25)
* 运算符; / (slash) <1>:                 数字类型 --- int float complex.
                                                             (line   20)
* 运算符; //:                            二元算术运算符.     (line   25)
* 运算符; // <1>:                        数字类型 --- int float complex.
                                                             (line   20)
* 运算符; < (less):                      比较运算.           (line    6)
* 运算符; < (less) <1>:                  比较运算<2>.        (line    6)
* 运算符; <<:                            移位运算.           (line    6)
* 运算符; << <1>:                        整数类型的按位运算. (line    6)
* 运算符; <=:                            比较运算.           (line    6)
* 运算符; <= <1>:                        比较运算<2>.        (line    6)
* 运算符; ==:                            比较运算.           (line    6)
* 运算符; == <1>:                        比较运算<2>.        (line    6)
* 运算符; > (greater):                   比较运算.           (line    6)
* 运算符; > (greater) <1>:               比较运算<2>.        (line    6)
* 运算符; >=:                            比较运算.           (line    6)
* 运算符; >= <1>:                        比较运算<2>.        (line    6)
* 运算符; >>:                            移位运算.           (line    6)
* 运算符; >> <1>:                        整数类型的按位运算. (line    6)
* 运算符; @ (at):                        二元算术运算符.     (line   20)
* 运算符; and:                           布尔运算.           (line   17)
* 运算符; and <1>:                       逻辑值检测.         (line   19)
* 运算符; and <2>:                       布尔运算 --- and or not.
                                                             (line   22)
* 运算符; in:                            成员检测运算.       (line   30)
* 运算符; in <1>:                        比较运算<2>.        (line   58)
* 运算符; in <2>:                        通用序列操作.       (line   17)
* 运算符; is:                            成员检测运算.       (line   32)
* 运算符; is <1>:                        比较运算<2>.        (line    6)
* 运算符; is not:                        成员检测运算.       (line   32)
* 运算符; is not <1>:                    比较运算<2>.        (line    6)
* 运算符; not:                           布尔运算.           (line   15)
* 运算符; not <1>:                       布尔运算 --- and or not.
                                                             (line   22)
* 运算符; not in:                        成员检测运算.       (line   30)
* 运算符; not in <1>:                    比较运算<2>.        (line   58)
* 运算符; not in <2>:                    通用序列操作.       (line   17)
* 运算符; or:                            布尔运算.           (line   20)
* 运算符; or <1>:                        逻辑值检测.         (line   19)
* 运算符; or <2>:                        布尔运算 --- and or not.
                                                             (line   22)
* 运算符; ^ (caret):                     二元位运算.         (line   14)
* 运算符; ^ (caret) <1>:                 整数类型的按位运算. (line    6)
* 运算符; | (vertical bar):              二元位运算.         (line   16)
* 运算符; | (vertical bar) <1>:          整数类型的按位运算. (line    6)
* 运算符; ~ (tilde):                     一元算术和位运算.   (line   14)
* 运算符; ~ (tilde) <1>:                 整数类型的按位运算. (line    6)

                                                             
                                                             
                                                             
                                                             



Tag Table:
Node: Top342
Ref: contents doc537
Ref: 146537
Node: Python的新变化177003
Ref: whatsnew/index doc177095
Ref: 147177095
Ref: whatsnew/index python-documentation-contents177095
Ref: 148177095
Ref: whatsnew/index what-s-new-in-python177095
Ref: 149177095
Ref: whatsnew/index whatsnew-index177095
Ref: 14a177095
Node: Python 3 8 有什么新变化178447
Ref: whatsnew/3 8 doc178569
Ref: 14b178569
Ref: whatsnew/3 8 what-s-new-in-python-3-8178569
Ref: 14c178569
Node: 摘要 - 发布重点179618
Ref: whatsnew/3 8 summary-release-highlights179726
Ref: 14e179726
Node: 新的特性179777
Ref: whatsnew/3 8 new-features179918
Ref: 14f179918
Node: 赋值表达式180484
Ref: whatsnew/3 8 assignment-expressions180575
Ref: 150180575
Ref: 赋值表达式-Footnote-1181994
Ref: 赋值表达式-Footnote-2182091
Ref: 赋值表达式-Footnote-3182140
Node: 仅限位置形参182183
Ref: whatsnew/3 8 positional-only-parameters182340
Ref: 152182340
Ref: 仅限位置形参-Footnote-1184793
Ref: 仅限位置形参-Footnote-2184845
Ref: 仅限位置形参-Footnote-3184894
Node: 用于已编译字节码文件的并行文件系统缓存184937
Ref: whatsnew/3 8 parallel-filesystem-cache-for-compiled-bytecode-files185125
Ref: 154185125
Ref: 用于已编译字节码文件的并行文件系统缓存-Footnote-1185721
Node: 调试构建使用与发布构建相同的 ABI185764
Ref: whatsnew/3 8 debug-build-uses-the-same-abi-as-release-build185996
Ref: 159185996
Ref: 调试构建使用与发布构建相同的 ABI-Footnote-1188315
Ref: 调试构建使用与发布构建相同的 ABI-Footnote-2188358
Ref: 调试构建使用与发布构建相同的 ABI-Footnote-3188401
Ref: 调试构建使用与发布构建相同的 ABI-Footnote-4188444
Node: f-字符串支持 = 用于自动记录表达式和调试文档188487
Ref: whatsnew/3 8 f-strings-support-for-self-documenting-expressions-and-debugging188698
Ref: 15b188698
Ref: f-字符串支持 = 用于自动记录表达式和调试文档-Footnote-1189720
Node: PEP 578 Python 运行时审核钩子189763
Ref: whatsnew/3 8 pep-578-python-runtime-audit-hooks189958
Ref: 15e189958
Ref: PEP 578 Python 运行时审核钩子-Footnote-1190392
Node: PEP 587 Python 初始化配置190441
Ref: whatsnew/3 8 pep-587-python-initialization-configuration190621
Ref: 15f190621
Ref: PEP 587 Python 初始化配置-Footnote-1192537
Ref: PEP 587 Python 初始化配置-Footnote-2192586
Ref: PEP 587 Python 初始化配置-Footnote-3192635
Node: Vectorcall 用于 CPython 的快速调用协议192678
Ref: whatsnew/3 8 vectorcall-a-fast-calling-protocol-for-cpython192868
Ref: 17f192868
Ref: Vectorcall 用于 CPython 的快速调用协议-Footnote-1193389
Ref: Vectorcall 用于 CPython 的快速调用协议-Footnote-2193438
Node: 具有外部数据缓冲区的 pickle 协议 5193481
Ref: whatsnew/3 8 pickle-protocol-5-with-out-of-band-data-buffers193632
Ref: 180193632
Ref: 具有外部数据缓冲区的 pickle 协议 5-Footnote-1194303
Ref: 具有外部数据缓冲区的 pickle 协议 5-Footnote-2194352
Ref: 具有外部数据缓冲区的 pickle 协议 5-Footnote-3194401
Node: 其他语言特性修改194444
Ref: whatsnew/3 8 other-language-changes194576
Ref: 181194576
Ref: 其他语言特性修改-Footnote-1201614
Ref: 其他语言特性修改-Footnote-2201657
Ref: 其他语言特性修改-Footnote-3201700
Ref: 其他语言特性修改-Footnote-4201743
Ref: 其他语言特性修改-Footnote-5201786
Ref: 其他语言特性修改-Footnote-6201829
Ref: 其他语言特性修改-Footnote-7201872
Ref: 其他语言特性修改-Footnote-8201915
Ref: 其他语言特性修改-Footnote-9201958
Ref: 其他语言特性修改-Footnote-10202001
Ref: 其他语言特性修改-Footnote-11202045
Ref: 其他语言特性修改-Footnote-12202091
Ref: 其他语言特性修改-Footnote-13202135
Ref: 其他语言特性修改-Footnote-14202205
Ref: 其他语言特性修改-Footnote-15202265
Ref: 其他语言特性修改-Footnote-16202309
Ref: 其他语言特性修改-Footnote-17202353
Node: 新增模块202397
Ref: whatsnew/3 8 new-modules202532
Ref: 19e202532
Ref: 新增模块-Footnote-1203581
Node: 改进的模块203624
Ref: whatsnew/3 8 improved-modules203747
Ref: 19f203747
Node: ast204364
Ref: whatsnew/3 8 ast204435
Ref: 1a0204435
Ref: ast-Footnote-1205420
Ref: ast-Footnote-2205463
Ref: ast-Footnote-3205512
Ref: ast-Footnote-4205561
Ref: ast-Footnote-5205610
Node: asyncio205653
Ref: whatsnew/3 8 asyncio205741
Ref: 1a5205741
Ref: asyncio-Footnote-1208865
Ref: asyncio-Footnote-2208908
Ref: asyncio-Footnote-3208951
Ref: asyncio-Footnote-4208994
Ref: asyncio-Footnote-5209037
Ref: asyncio-Footnote-6209080
Ref: asyncio-Footnote-7209123
Ref: asyncio-Footnote-8209166
Ref: asyncio-Footnote-9209209
Ref: asyncio-Footnote-10209262
Node: builtins209306
Ref: whatsnew/3 8 builtins209402
Ref: 1b4209402
Ref: builtins-Footnote-1209872
Node: collections209915
Ref: whatsnew/3 8 collections210012
Ref: 1b6210012
Ref: collections-Footnote-1210539
Node: cProfile210582
Ref: whatsnew/3 8 cprofile210674
Ref: 1bb210674
Ref: cProfile-Footnote-1211039
Node: csv211082
Ref: whatsnew/3 8 csv211169
Ref: 1bd211169
Ref: csv-Footnote-1211477
Node: curses211520
Ref: whatsnew/3 8 curses211605
Ref: 1bf211605
Ref: curses-Footnote-1211835
Node: ctypes211878
Ref: whatsnew/3 8 ctypes211968
Ref: 1c1211968
Ref: ctypes-Footnote-1212450
Node: datetime212493
Ref: whatsnew/3 8 datetime212586
Ref: 1c4212586
Ref: datetime-Footnote-1213032
Node: functools213075
Ref: whatsnew/3 8 functools213164
Ref: 1c7213164
Ref: functools-Footnote-1214712
Ref: functools-Footnote-2214755
Ref: functools-Footnote-3214798
Node: gc214841
Ref: whatsnew/3 8 gc214929
Ref: 1cd214929
Ref: gc-Footnote-1215171
Node: gettext215214
Ref: whatsnew/3 8 gettext215297
Ref: 1cf215297
Ref: gettext-Footnote-1215510
Node: gzip215552
Ref: whatsnew/3 8 gzip215649
Ref: 1d1215649
Ref: gzip-Footnote-1216065
Ref: gzip-Footnote-2216108
Node: IDLE 与 idlelib216150
Ref: whatsnew/3 8 idle-and-idlelib216247
Ref: 1d5216247
Ref: IDLE 与 idlelib-Footnote-1218208
Ref: IDLE 与 idlelib-Footnote-2218253
Ref: IDLE 与 idlelib-Footnote-3218295
Ref: IDLE 与 idlelib-Footnote-4218338
Ref: IDLE 与 idlelib-Footnote-5218381
Ref: IDLE 与 idlelib-Footnote-6218424
Ref: IDLE 与 idlelib-Footnote-7218466
Ref: IDLE 与 idlelib-Footnote-8218509
Node: inspect218552
Ref: whatsnew/3 8 inspect218647
Ref: 1d6218647
Ref: inspect-Footnote-1219424
Node: io219467
Ref: whatsnew/3 8 io219555
Ref: 1db219555
Ref: io-Footnote-1219897
Node: itertools219940
Ref: whatsnew/3 8 itertools220030
Ref: 1dd220030
Ref: itertools-Footnote-1220409
Node: json tool220452
Ref: whatsnew/3 8 json-tool220547
Ref: 1df220547
Ref: json tool-Footnote-1220766
Node: logging220809
Ref: whatsnew/3 8 logging220899
Ref: 1e0220899
Ref: logging-Footnote-1221601
Node: math221644
Ref: whatsnew/3 8 math221729
Ref: 1e2221729
Ref: math-Footnote-1223437
Ref: math-Footnote-2223480
Ref: math-Footnote-3223523
Ref: math-Footnote-4223566
Ref: math-Footnote-5223609
Ref: math-Footnote-6223652
Ref: math-Footnote-7223695
Ref: math-Footnote-8223738
Node: mmap223781
Ref: whatsnew/3 8 mmap223874
Ref: 1ec223874
Ref: mmap-Footnote-1224111
Node: multiprocessing224154
Ref: whatsnew/3 8 multiprocessing224245
Ref: 1ef224245
Ref: multiprocessing-Footnote-1224581
Ref: multiprocessing-Footnote-2224624
Node: os224667
Ref: whatsnew/3 8 os224761
Ref: 1f0224761
Ref: os-Footnote-1226220
Ref: os-Footnote-2226263
Ref: os-Footnote-3226306
Node: os path226349
Ref: whatsnew/3 8 os-path226435
Ref: 1f6226435
Ref: os path-Footnote-1227447
Ref: os path-Footnote-2227490
Ref: os path-Footnote-3227533
Node: pathlib227576
Ref: whatsnew/3 8 pathlib227666
Ref: 201227666
Ref: pathlib-Footnote-1228406
Ref: pathlib-Footnote-2228449
Node: pickle228492
Ref: whatsnew/3 8 pickle228583
Ref: 20d228583
Ref: pickle-Footnote-1228907
Node: plistlib228950
Ref: whatsnew/3 8 plistlib229040
Ref: 210229040
Ref: plistlib-Footnote-1229298
Node: pprint229341
Ref: whatsnew/3 8 pprint229435
Ref: 212229435
Ref: pprint-Footnote-1230480
Node: py_compile230523
Ref: whatsnew/3 8 py-compile230614
Ref: 215230614
Ref: py_compile-Footnote-1230810
Node: shlex230853
Ref: whatsnew/3 8 shlex230944
Ref: 217230944
Ref: shlex-Footnote-1231153
Node: shutil231196
Ref: whatsnew/3 8 shutil231283
Ref: 21a231283
Ref: shutil-Footnote-1231930
Ref: shutil-Footnote-2231973
Ref: shutil-Footnote-3232016
Node: socket232059
Ref: whatsnew/3 8 socket232144
Ref: 21e232144
Ref: socket-Footnote-1232707
Ref: socket-Footnote-2232750
Node: ssl232793
Ref: whatsnew/3 8 ssl232882
Ref: 224232882
Ref: ssl-Footnote-1233145
Node: statistics233188
Ref: whatsnew/3 8 statistics233274
Ref: 227233274
Ref: statistics-Footnote-1235014
Ref: statistics-Footnote-2235057
Ref: statistics-Footnote-3235100
Ref: statistics-Footnote-4235143
Ref: statistics-Footnote-5235186
Node: sys235229
Ref: whatsnew/3 8 sys235319
Ref: 22d235319
Ref: sys-Footnote-1235736
Node: tarfile235779
Ref: whatsnew/3 8 tarfile235868
Ref: 230235868
Ref: tarfile-Footnote-1236256
Node: threading236299
Ref: whatsnew/3 8 threading236393
Ref: 231236393
Ref: threading-Footnote-1237101
Ref: threading-Footnote-2237146
Node: tokenize237189
Ref: whatsnew/3 8 tokenize237283
Ref: 237237283
Ref: tokenize-Footnote-1237594
Node: tkinter237637
Ref: whatsnew/3 8 tkinter237726
Ref: 238237726
Ref: tkinter-Footnote-1238285
Ref: tkinter-Footnote-2238328
Ref: tkinter-Footnote-3238371
Node: time238414
Ref: whatsnew/3 8 time238501
Ref: 239238501
Ref: time-Footnote-1238694
Node: typing238737
Ref: whatsnew/3 8 typing238828
Ref: 23b238828
Ref: typing-Footnote-1240255
Ref: typing-Footnote-2240304
Ref: typing-Footnote-3240353
Ref: typing-Footnote-4240402
Node: unicodedata240451
Ref: whatsnew/3 8 unicodedata240546
Ref: 246240546
Ref: unicodedata-Footnote-1240970
Ref: unicodedata-Footnote-2241031
Ref: unicodedata-Footnote-3241074
Node: unittest241117
Ref: whatsnew/3 8 unittest241210
Ref: 248241210
Ref: unittest-Footnote-1242498
Ref: unittest-Footnote-2242541
Ref: unittest-Footnote-3242584
Ref: unittest-Footnote-4242627
Node: venv242670
Ref: whatsnew/3 8 venv242759
Ref: 24f242759
Ref: venv-Footnote-1243014
Node: weakref243057
Ref: whatsnew/3 8 weakref243141
Ref: 250243141
Ref: weakref-Footnote-1243411
Node: xml243454
Ref: whatsnew/3 8 xml243540
Ref: 252243540
Ref: xml-Footnote-1244657
Ref: xml-Footnote-2244700
Ref: xml-Footnote-3244743
Ref: xml-Footnote-4244786
Ref: xml-Footnote-5244829
Node: xmlrpc244872
Ref: whatsnew/3 8 xmlrpc244942
Ref: 255244942
Ref: xmlrpc-Footnote-1245314
Node: 性能优化245357
Ref: whatsnew/3 8 optimizations245493
Ref: 257245493
Ref: 性能优化-Footnote-1249846
Ref: 性能优化-Footnote-2249889
Ref: 性能优化-Footnote-3249932
Ref: 性能优化-Footnote-4249975
Ref: 性能优化-Footnote-5250018
Ref: 性能优化-Footnote-6250061
Ref: 性能优化-Footnote-7250104
Ref: 性能优化-Footnote-8250147
Ref: 性能优化-Footnote-9250190
Ref: 性能优化-Footnote-10250233
Ref: 性能优化-Footnote-11250277
Ref: 性能优化-Footnote-12250321
Ref: 性能优化-Footnote-13250365
Node: 构建和 C API 的改变250409
Ref: whatsnew/3 8 build-and-c-api-changes250536
Ref: 264250536
Ref: 构建和 C API 的改变-Footnote-1255857
Ref: 构建和 C API 的改变-Footnote-2255900
Ref: 构建和 C API 的改变-Footnote-3255943
Ref: 构建和 C API 的改变-Footnote-4255986
Ref: 构建和 C API 的改变-Footnote-5256029
Ref: 构建和 C API 的改变-Footnote-6256072
Ref: 构建和 C API 的改变-Footnote-7256115
Ref: 构建和 C API 的改变-Footnote-8256158
Ref: 构建和 C API 的改变-Footnote-9256201
Ref: 构建和 C API 的改变-Footnote-10256244
Ref: 构建和 C API 的改变-Footnote-11256288
Ref: 构建和 C API 的改变-Footnote-12256332
Node: 弃用256376
Ref: whatsnew/3 8 deprecated256513
Ref: 278256513
Ref: 弃用-Footnote-1262176
Ref: 弃用-Footnote-2262219
Ref: 弃用-Footnote-3262262
Ref: 弃用-Footnote-4262305
Ref: 弃用-Footnote-5262347
Ref: 弃用-Footnote-6262390
Ref: 弃用-Footnote-7262433
Ref: 弃用-Footnote-8262476
Ref: 弃用-Footnote-9262519
Ref: 弃用-Footnote-10262562
Ref: 弃用-Footnote-11262606
Ref: 弃用-Footnote-12262650
Ref: 弃用-Footnote-13262694
Node: API 与特性的移除262738
Ref: whatsnew/3 8 api-and-feature-removals262870
Ref: 2a9262870
Ref: API 与特性的移除-Footnote-1265648
Ref: API 与特性的移除-Footnote-2265691
Ref: API 与特性的移除-Footnote-3265734
Ref: API 与特性的移除-Footnote-4265777
Ref: API 与特性的移除-Footnote-5265820
Ref: API 与特性的移除-Footnote-6265863
Ref: API 与特性的移除-Footnote-7265906
Ref: API 与特性的移除-Footnote-8265949
Ref: API 与特性的移除-Footnote-9265992
Ref: API 与特性的移除-Footnote-10266035
Ref: API 与特性的移除-Footnote-11266079
Node: 移植到 Python 3 8266123
Ref: whatsnew/3 8 porting-to-python-3-8266280
Ref: 2af266280
Node: Python 行为的改变266557
Ref: whatsnew/3 8 changes-in-python-behavior266665
Ref: 2b0266665
Ref: Python 行为的改变-Footnote-1268942
Ref: Python 行为的改变-Footnote-2268985
Ref: Python 行为的改变-Footnote-3269028
Ref: Python 行为的改变-Footnote-4269071
Ref: Python 行为的改变-Footnote-5269114
Ref: Python 行为的改变-Footnote-6269157
Node: Python API 的变化269200
Ref: whatsnew/3 8 changes-in-the-python-api269332
Ref: 2b8269332
Ref: whatsnew/3 8 bpo-36085-whatsnew276124
Ref: 2cb276124
Ref: Python API 的变化-Footnote-1277525
Ref: Python API 的变化-Footnote-2277574
Ref: Python API 的变化-Footnote-3277617
Ref: Python API 的变化-Footnote-4277660
Ref: Python API 的变化-Footnote-5277703
Ref: Python API 的变化-Footnote-6277746
Ref: Python API 的变化-Footnote-7277789
Ref: Python API 的变化-Footnote-8277832
Ref: Python API 的变化-Footnote-9277875
Ref: Python API 的变化-Footnote-10277918
Ref: Python API 的变化-Footnote-11277962
Ref: Python API 的变化-Footnote-12278006
Ref: Python API 的变化-Footnote-13278050
Ref: Python API 的变化-Footnote-14278094
Ref: Python API 的变化-Footnote-15278138
Ref: Python API 的变化-Footnote-16278182
Ref: Python API 的变化-Footnote-17278226
Ref: Python API 的变化-Footnote-18278269
Ref: Python API 的变化-Footnote-19278313
Ref: Python API 的变化-Footnote-20278357
Ref: Python API 的变化-Footnote-21278401
Ref: Python API 的变化-Footnote-22278445
Ref: Python API 的变化-Footnote-23278489
Ref: Python API 的变化-Footnote-24278533
Ref: Python API 的变化-Footnote-25278577
Ref: Python API 的变化-Footnote-26278621
Ref: Python API 的变化-Footnote-27278665
Node: C API 的变化278715
Ref: whatsnew/3 8 changes-in-the-c-api278851
Ref: 2cc278851
Ref: C API 的变化-Footnote-1284468
Ref: C API 的变化-Footnote-2284511
Ref: C API 的变化-Footnote-3284554
Ref: C API 的变化-Footnote-4284597
Ref: C API 的变化-Footnote-5284640
Ref: C API 的变化-Footnote-6284683
Ref: C API 的变化-Footnote-7284726
Ref: C API 的变化-Footnote-8284769
Node: CPython 字节码的改变284812
Ref: whatsnew/3 8 cpython-bytecode-changes284943
Ref: 2db284943
Ref: CPython 字节码的改变-Footnote-1286213
Ref: CPython 字节码的改变-Footnote-2286256
Ref: CPython 字节码的改变-Footnote-3286299
Ref: CPython 字节码的改变-Footnote-4286348
Node: 演示和工具286391
Ref: whatsnew/3 8 demos-and-tools286498
Ref: 2e6286498
Ref: 演示和工具-Footnote-1289795
Ref: 演示和工具-Footnote-2289838
Ref: 演示和工具-Footnote-3289966
Node: Python 3 8 1 中的重要变化290016
Ref: whatsnew/3 8 notable-changes-in-python-3-8-1290182
Ref: 2e7290182
Ref: Python 3 8 1 中的重要变化-Footnote-1290663
Node: Python 3 8 2 中的重要变化290706
Ref: whatsnew/3 8 notable-changes-in-python-3-8-2290883
Ref: 2e9290883
Ref: Python 3 8 2 中的重要变化-Footnote-1291210
Node: Python 3 8 3 中的重要变化291253
Ref: whatsnew/3 8 notable-changes-in-python-3-8-3291430
Ref: 2ea291430
Ref: Python 3 8 3 中的重要变化-Footnote-1291803
Node: Python 3 8 8 中的重要变化291846
Ref: whatsnew/3 8 notable-changes-in-python-3-8-8292023
Ref: 2eb292023
Ref: Python 3 8 8 中的重要变化-Footnote-1292718
Node: Python 3 8 9 中的重要变化292761
Ref: whatsnew/3 8 notable-changes-in-python-3-8-9292939
Ref: 2f0292939
Ref: Python 3 8 9 中的重要变化-Footnote-1293432
Node: Python 3 8 10 中的重要变化293475
Ref: whatsnew/3 8 notable-changes-in-python-3-8-10293657
Ref: 2f2293657
Node: macOS 11 0 Big Sur 与 Apple Silicon Mac 支持293844
Ref: whatsnew/3 8 macos-11-0-big-sur-and-apple-silicon-mac-support293960
Ref: 2f3293960
Ref: macOS 11 0 Big Sur 与 Apple Silicon Mac 支持-Footnote-1294929
Node: Python 3 8 10 中的重要变化<2>294972
Ref: whatsnew/3 8 id1295155
Ref: 2f4295155
Node: urllib parse295270
Ref: whatsnew/3 8 urllib-parse295354
Ref: 2f5295354
Ref: urllib parse-Footnote-1295847
Ref: urllib parse-Footnote-2295896
Node: Python 3 8 12 中的重要变化295939
Ref: whatsnew/3 8 notable-changes-in-python-3-8-12296081
Ref: 2f6296081
Node: Python API 的变化<2>296215
Ref: whatsnew/3 8 id2296307
Ref: 2f7296307
Ref: Python API 的变化<2>-Footnote-1296904
Node: Python 3 7 有什么新变化296947
Ref: whatsnew/3 7 doc297107
Ref: 2fa297107
Ref: whatsnew/3 7 what-s-new-in-python-3-7297107
Ref: 2fb297107
Node: 摘要 - 发布重点<2>298271
Ref: whatsnew/3 7 summary-release-highlights298385
Ref: 2fc298385
Ref: 摘要 - 发布重点<2>-Footnote-1300321
Ref: 摘要 - 发布重点<2>-Footnote-2300401
Ref: 摘要 - 发布重点<2>-Footnote-3300437
Ref: 摘要 - 发布重点<2>-Footnote-4300473
Node: 新的特性<2>300509
Ref: whatsnew/3 7 new-features300659
Ref: 311300659
Node: PEP 563：延迟的标注求值301668
Ref: whatsnew/3 7 pep-563-postponed-evaluation-of-annotations301795
Ref: 312301795
Ref: whatsnew/3 7 whatsnew37-pep563301795
Ref: 2fd301795
Ref: PEP 563：延迟的标注求值-Footnote-1303348
Ref: PEP 563：延迟的标注求值-Footnote-2303397
Ref: PEP 563：延迟的标注求值-Footnote-3303446
Node: PEP 538 传统 C 区域强制转换303495
Ref: whatsnew/3 7 pep-538-legacy-c-locale-coercion303667
Ref: 314303667
Ref: whatsnew/3 7 whatsnew37-pep538303667
Ref: 308303667
Ref: PEP 538 传统 C 区域强制转换-Footnote-1305908
Ref: PEP 538 传统 C 区域强制转换-Footnote-2305957
Ref: PEP 538 传统 C 区域强制转换-Footnote-3306006
Ref: PEP 538 传统 C 区域强制转换-Footnote-4306055
Node: PEP 540 强制 UTF-8 运行时模式306104
Ref: whatsnew/3 7 pep-540-forced-utf-8-runtime-mode306273
Ref: 319306273
Ref: whatsnew/3 7 whatsnew37-pep540306273
Ref: 309306273
Ref: PEP 540 强制 UTF-8 运行时模式-Footnote-1307706
Ref: PEP 540 强制 UTF-8 运行时模式-Footnote-2307755
Ref: PEP 540 强制 UTF-8 运行时模式-Footnote-3307804
Node: PEP 553 内置的 breakpoint307853
Ref: whatsnew/3 7 pep-553-built-in-breakpoint308031
Ref: 31b308031
Ref: whatsnew/3 7 whatsnew37-pep553308031
Ref: 301308031
Ref: PEP 553 内置的 breakpoint-Footnote-1308853
Node: PEP 539 用于线程局部存储的新 C API308902
Ref: whatsnew/3 7 pep-539-new-c-api-for-thread-local-storage309082
Ref: 31e309082
Ref: whatsnew/3 7 whatsnew37-pep539309082
Ref: 30d309082
Ref: PEP 539 用于线程局部存储的新 C API-Footnote-1310494
Ref: PEP 539 用于线程局部存储的新 C API-Footnote-2310543
Node: PEP 562 定制对模块属性的访问310592
Ref: whatsnew/3 7 pep-562-customization-of-access-to-module-attributes310791
Ref: 322310791
Ref: whatsnew/3 7 whatsnew37-pep562310791
Ref: 303310791
Ref: PEP 562 定制对模块属性的访问-Footnote-1311319
Node: PEP 564 具有纳秒级精度的新时间函数311368
Ref: whatsnew/3 7 pep-564-new-time-functions-with-nanosecond-resolution311572
Ref: 325311572
Ref: whatsnew/3 7 whatsnew37-pep564311572
Ref: 307311572
Ref: PEP 564 具有纳秒级精度的新时间函数-Footnote-1312529
Ref: PEP 564 具有纳秒级精度的新时间函数-Footnote-2312578
Ref: PEP 564 具有纳秒级精度的新时间函数-Footnote-3312663
Node: PEP 565 在 __main__ 中显示 DeprecationWarning312712
Ref: whatsnew/3 7 pep-565-show-deprecationwarning-in-main312933
Ref: 32d312933
Ref: whatsnew/3 7 whatsnew37-pep565312933
Ref: 30c312933
Ref: PEP 565 在 __main__ 中显示 DeprecationWarning-Footnote-1314747
Node: PEP 560 对 typing 模块和泛型类型的核心支持314796
Ref: whatsnew/3 7 pep-560-core-support-for-typing-module-and-generic-types315007
Ref: 32f315007
Ref: whatsnew/3 7 whatsnew37-pep560315007
Ref: 304315007
Ref: PEP 560 对 typing 模块和泛型类型的核心支持-Footnote-1315898
Ref: PEP 560 对 typing 模块和泛型类型的核心支持-Footnote-2315947
Node: PEP 552 基于哈希值的 pyc 文件315996
Ref: whatsnew/3 7 pep-552-hash-based-pyc-files316185
Ref: 331316185
Ref: whatsnew/3 7 whatsnew37-pep552316185
Ref: 30a316185
Ref: PEP 552 基于哈希值的 pyc 文件-Footnote-1317884
Ref: PEP 552 基于哈希值的 pyc 文件-Footnote-2317925
Ref: PEP 552 基于哈希值的 pyc 文件-Footnote-3317974
Node: PEP 545 Python 文档翻译318023
Ref: whatsnew/3 7 pep-545-python-documentation-translations318185
Ref: 333318185
Ref: whatsnew/3 7 whatsnew37-pep545318185
Ref: 30e318185
Ref: PEP 545 Python 文档翻译-Footnote-1318677
Ref: PEP 545 Python 文档翻译-Footnote-2318726
Node: 开发运行时模式 -X dev318775
Ref: whatsnew/3 7 development-runtime-mode-x-dev318891
Ref: 334318891
Ref: whatsnew/3 7 whatsnew37-devmode318891
Ref: 30b318891
Node: 其他语言特性修改<2>319297
Ref: whatsnew/3 7 other-language-changes319438
Ref: 336319438
Ref: 其他语言特性修改<2>-Footnote-1321736
Ref: 其他语言特性修改<2>-Footnote-2321779
Ref: 其他语言特性修改<2>-Footnote-3321822
Ref: 其他语言特性修改<2>-Footnote-4321865
Ref: 其他语言特性修改<2>-Footnote-5321908
Ref: 其他语言特性修改<2>-Footnote-6321951
Ref: 其他语言特性修改<2>-Footnote-7321994
Ref: 其他语言特性修改<2>-Footnote-8322037
Ref: 其他语言特性修改<2>-Footnote-9322080
Ref: 其他语言特性修改<2>-Footnote-10322123
Node: 新增模块<2>322167
Ref: whatsnew/3 7 new-modules322311
Ref: 342322311
Node: contextvars322432
Ref: whatsnew/3 7 contextvars322515
Ref: 343322515
Ref: whatsnew/3 7 whatsnew37-pep567322515
Ref: 2fe322515
Ref: contextvars-Footnote-1323179
Node: dataclasses323228
Ref: whatsnew/3 7 dataclasses323339
Ref: 345323339
Ref: whatsnew/3 7 whatsnew37-pep557323339
Ref: 2ff323339
Ref: dataclasses-Footnote-1323963
Node: importlib resources324012
Ref: whatsnew/3 7 importlib-resources324103
Ref: 34a324103
Ref: whatsnew/3 7 whatsnew37-importlib-resources324103
Ref: 300324103
Ref: importlib resources-Footnote-1324833
Ref: importlib resources-Footnote-2324876
Node: 改进的模块<2>324937
Ref: whatsnew/3 7 improved-modules325069
Ref: 34c325069
Node: argparse326216
Ref: whatsnew/3 7 argparse326298
Ref: 34d326298
Ref: argparse-Footnote-1326520
Node: asyncio<2>326563
Ref: whatsnew/3 7 asyncio326662
Ref: 34f326662
Ref: whatsnew/3 7 whatsnew37-asyncio326662
Ref: 306326662
Ref: asyncio<2>-Footnote-1332758
Ref: asyncio<2>-Footnote-2332801
Ref: asyncio<2>-Footnote-3332850
Ref: asyncio<2>-Footnote-4332893
Ref: asyncio<2>-Footnote-5332936
Ref: asyncio<2>-Footnote-6332979
Ref: asyncio<2>-Footnote-7333022
Ref: asyncio<2>-Footnote-8333065
Ref: asyncio<2>-Footnote-9333108
Ref: asyncio<2>-Footnote-10333151
Ref: asyncio<2>-Footnote-11333195
Ref: asyncio<2>-Footnote-12333239
Ref: asyncio<2>-Footnote-13333283
Ref: asyncio<2>-Footnote-14333327
Ref: asyncio<2>-Footnote-15333371
Ref: asyncio<2>-Footnote-16333415
Ref: asyncio<2>-Footnote-17333459
Ref: asyncio<2>-Footnote-18333503
Ref: asyncio<2>-Footnote-19333547
Ref: asyncio<2>-Footnote-20333591
Ref: asyncio<2>-Footnote-21333635
Ref: asyncio<2>-Footnote-22333679
Ref: asyncio<2>-Footnote-23333723
Ref: asyncio<2>-Footnote-24333767
Node: binascii333811
Ref: whatsnew/3 7 binascii333910
Ref: 375333910
Ref: binascii-Footnote-1334181
Node: calendar334224
Ref: whatsnew/3 7 calendar334327
Ref: 377334327
Ref: calendar-Footnote-1334560
Node: collections<2>334603
Ref: whatsnew/3 7 collections334708
Ref: 379334708
Ref: collections<2>-Footnote-1334900
Node: compileall334943
Ref: whatsnew/3 7 compileall335058
Ref: 37a335058
Ref: compileall-Footnote-1335441
Node: concurrent futures335484
Ref: whatsnew/3 7 concurrent-futures335595
Ref: 37c335595
Ref: concurrent futures-Footnote-1336041
Ref: concurrent futures-Footnote-2336084
Node: contextlib336127
Ref: whatsnew/3 7 contextlib336239
Ref: 37d336239
Ref: contextlib-Footnote-1336790
Ref: contextlib-Footnote-2336833
Ref: contextlib-Footnote-3336876
Ref: contextlib-Footnote-4336919
Node: cProfile<2>336962
Ref: whatsnew/3 7 cprofile337061
Ref: 383337061
Ref: cProfile<2>-Footnote-1337282
Node: crypt337325
Ref: whatsnew/3 7 crypt337425
Ref: 384337425
Ref: crypt-Footnote-1337739
Ref: crypt-Footnote-2337782
Node: datetime<2>337825
Ref: whatsnew/3 7 datetime337917
Ref: 386337917
Ref: datetime<2>-Footnote-1338337
Ref: datetime<2>-Footnote-2338380
Node: dbm338422
Ref: whatsnew/3 7 dbm338516
Ref: 389338516
Node: decimal338650
Ref: whatsnew/3 7 decimal338736
Ref: 38a338736
Ref: decimal-Footnote-1338964
Node: dis339007
Ref: whatsnew/3 7 dis339099
Ref: 38b339099
Ref: dis-Footnote-1339458
Node: distutils339501
Ref: whatsnew/3 7 distutils339590
Ref: 38d339590
Ref: distutils-Footnote-1339836
Node: enum339879
Ref: whatsnew/3 7 enum339977
Ref: 38e339977
Ref: enum-Footnote-1340620
Ref: enum-Footnote-2340663
Node: functools<2>340706
Ref: whatsnew/3 7 functools340800
Ref: 391340800
Ref: functools<2>-Footnote-1341018
Node: gc<2>341061
Ref: whatsnew/3 7 gc341155
Ref: 393341155
Ref: gc<2>-Footnote-1341662
Node: hmac341705
Ref: whatsnew/3 7 hmac341798
Ref: 397341798
Ref: hmac-Footnote-1342044
Node: http client342087
Ref: whatsnew/3 7 http-client342186
Ref: 399342186
Ref: http client-Footnote-1342442
Node: http server342485
Ref: whatsnew/3 7 http-server342596
Ref: 39c342596
Ref: http server-Footnote-1343457
Ref: http server-Footnote-2343500
Ref: http server-Footnote-3343543
Node: idlelib 与 IDLE343586
Ref: whatsnew/3 7 idlelib-and-idle343695
Ref: 39f343695
Ref: idlelib 与 IDLE-Footnote-1346702
Ref: idlelib 与 IDLE-Footnote-2346745
Ref: idlelib 与 IDLE-Footnote-3346790
Ref: idlelib 与 IDLE-Footnote-4346833
Ref: idlelib 与 IDLE-Footnote-5346876
Ref: idlelib 与 IDLE-Footnote-6346919
Ref: idlelib 与 IDLE-Footnote-7346962
Ref: idlelib 与 IDLE-Footnote-8347005
Ref: idlelib 与 IDLE-Footnote-9347048
Ref: idlelib 与 IDLE-Footnote-10347091
Ref: idlelib 与 IDLE-Footnote-11347137
Ref: idlelib 与 IDLE-Footnote-12347180
Ref: idlelib 与 IDLE-Footnote-13347224
Node: importlib347268
Ref: whatsnew/3 7 importlib347371
Ref: 3a0347371
Ref: importlib-Footnote-1348227
Ref: importlib-Footnote-2348270
Ref: importlib-Footnote-3348313
Node: io<2>348356
Ref: whatsnew/3 7 io348452
Ref: 3a4348452
Ref: io<2>-Footnote-1348711
Ref: io<2>-Footnote-2348754
Node: ipaddress348797
Ref: whatsnew/3 7 ipaddress348896
Ref: 3a6348896
Ref: ipaddress-Footnote-1349221
Node: itertools<2>349264
Ref: whatsnew/3 7 itertools349364
Ref: 3a9349364
Ref: itertools<2>-Footnote-1349604
Node: locale349647
Ref: whatsnew/3 7 locale349748
Ref: 3ab349748
Ref: locale-Footnote-1350139
Node: logging<2>350182
Ref: whatsnew/3 7 logging350278
Ref: 3ae350278
Ref: logging<2>-Footnote-1350790
Ref: logging<2>-Footnote-2350833
Ref: logging<2>-Footnote-3350876
Node: math<2>350919
Ref: whatsnew/3 7 math351018
Ref: 3b2351018
Ref: math<2>-Footnote-1351226
Node: mimetypes351269
Ref: whatsnew/3 7 mimetypes351364
Ref: 3b4351364
Ref: mimetypes-Footnote-1351569
Node: msilib351612
Ref: whatsnew/3 7 msilib351718
Ref: 3b5351718
Ref: msilib-Footnote-1351938
Node: multiprocessing<2>351981
Ref: whatsnew/3 7 multiprocessing352083
Ref: 3b7352083
Ref: multiprocessing<2>-Footnote-1352717
Ref: multiprocessing<2>-Footnote-2352760
Ref: multiprocessing<2>-Footnote-3352803
Node: os<2>352846
Ref: whatsnew/3 7 os352952
Ref: 3bb352952
Ref: os<2>-Footnote-1354231
Ref: os<2>-Footnote-2354274
Ref: os<2>-Footnote-3354317
Ref: os<2>-Footnote-4354360
Ref: os<2>-Footnote-5354403
Ref: os<2>-Footnote-6354446
Ref: os<2>-Footnote-7354489
Node: pathlib<2>354532
Ref: whatsnew/3 7 pathlib354623
Ref: 3c8354623
Ref: pathlib<2>-Footnote-1354869
Node: pdb354912
Ref: whatsnew/3 7 pdb355011
Ref: 3c9355011
Ref: pdb-Footnote-1355431
Ref: pdb-Footnote-2355474
Node: py_compile<2>355517
Ref: whatsnew/3 7 py-compile355611
Ref: 3cb355611
Ref: py_compile<2>-Footnote-1356054
Ref: py_compile<2>-Footnote-2356095
Node: pydoc356138
Ref: whatsnew/3 7 pydoc356234
Ref: 3cc356234
Ref: pydoc-Footnote-1356457
Node: queue356500
Ref: whatsnew/3 7 queue356585
Ref: 3cd356585
Ref: queue-Footnote-1356798
Node: re356841
Ref: whatsnew/3 7 re356927
Ref: 3cf356927
Ref: re-Footnote-1357994
Ref: re-Footnote-2358037
Ref: re-Footnote-3358080
Ref: re-Footnote-4358123
Ref: re-Footnote-5358166
Node: signal358209
Ref: whatsnew/3 7 signal358299
Ref: 3d5358299
Ref: signal-Footnote-1358600
Node: socket<2>358643
Ref: whatsnew/3 7 socket358743
Ref: 3d7358743
Ref: socket<2>-Footnote-1359846
Ref: socket<2>-Footnote-2359889
Ref: socket<2>-Footnote-3359932
Ref: socket<2>-Footnote-4359975
Ref: socket<2>-Footnote-5360018
Ref: socket<2>-Footnote-6360061
Node: socketserver360104
Ref: whatsnew/3 7 socketserver360205
Ref: 3dc360205
Node: sqlite3360668
Ref: whatsnew/3 7 sqlite3360766
Ref: 3df360766
Ref: sqlite3-Footnote-1361211
Ref: sqlite3-Footnote-2361254
Node: ssl<2>361297
Ref: whatsnew/3 7 ssl361389
Ref: 3e3361389
Ref: ssl<2>-Footnote-1364288
Ref: ssl<2>-Footnote-2364331
Ref: ssl<2>-Footnote-3364374
Ref: ssl<2>-Footnote-4364417
Ref: ssl<2>-Footnote-5364460
Ref: ssl<2>-Footnote-6364503
Ref: ssl<2>-Footnote-7364546
Ref: ssl<2>-Footnote-8364589
Ref: ssl<2>-Footnote-9364632
Ref: ssl<2>-Footnote-10364675
Ref: ssl<2>-Footnote-11364719
Ref: ssl<2>-Footnote-12364763
Ref: ssl<2>-Footnote-13364807
Node: string364851
Ref: whatsnew/3 7 string364946
Ref: 3f2364946
Ref: string-Footnote-1365230
Node: subprocess365275
Ref: whatsnew/3 7 subprocess365370
Ref: 3f4365370
Ref: subprocess-Footnote-1366652
Ref: subprocess-Footnote-2366695
Ref: subprocess-Footnote-3366738
Ref: subprocess-Footnote-4366781
Node: sys<2>366824
Ref: whatsnew/3 7 sys366920
Ref: 3f8366920
Ref: sys<2>-Footnote-1367667
Ref: sys<2>-Footnote-2367710
Ref: sys<2>-Footnote-3367753
Node: time<2>367796
Ref: whatsnew/3 7 time367892
Ref: 3fc367892
Ref: time<2>-Footnote-1369043
Ref: time<2>-Footnote-2369092
Node: tkinter<2>369135
Ref: whatsnew/3 7 tkinter369236
Ref: 404369236
Ref: tkinter<2>-Footnote-1369417
Node: tracemalloc369460
Ref: whatsnew/3 7 tracemalloc369559
Ref: 406369559
Ref: tracemalloc-Footnote-1370048
Node: types370091
Ref: whatsnew/3 7 types370194
Ref: 409370194
Ref: types-Footnote-1370712
Ref: types-Footnote-2370755
Ref: types-Footnote-3370798
Ref: types-Footnote-4370847
Node: unicodedata<2>370890
Ref: whatsnew/3 7 unicodedata370993
Ref: 40f370993
Ref: unicodedata<2>-Footnote-1371190
Node: unittest<2>371245
Ref: whatsnew/3 7 unittest371356
Ref: 410371356
Ref: unittest<2>-Footnote-1371785
Node: unittest mock371828
Ref: whatsnew/3 7 unittest-mock371940
Ref: 411371940
Ref: unittest mock-Footnote-1372437
Ref: unittest mock-Footnote-2372480
Node: urllib parse<2>372523
Ref: whatsnew/3 7 urllib-parse372626
Ref: 414372626
Ref: urllib parse<2>-Footnote-1372931
Ref: urllib parse<2>-Footnote-2372980
Ref: urllib parse<2>-Footnote-3373029
Node: uu373072
Ref: whatsnew/3 7 uu373166
Ref: 416373166
Ref: uu-Footnote-1373427
Node: uuid373470
Ref: whatsnew/3 7 uuid373557
Ref: 418373557
Ref: uuid-Footnote-1374152
Ref: uuid-Footnote-2374195
Node: warnings374238
Ref: whatsnew/3 7 warnings374332
Ref: 41c374332
Ref: warnings-Footnote-1375670
Ref: warnings-Footnote-2375713
Ref: warnings-Footnote-3375756
Ref: warnings-Footnote-4375799
Node: xml etree375842
Ref: whatsnew/3 7 xml-etree375945
Ref: 421375945
Ref: xml etree-Footnote-1376295
Node: xmlrpc server376338
Ref: whatsnew/3 7 xmlrpc-server376439
Ref: 423376439
Ref: xmlrpc server-Footnote-1376655
Node: zipapp376697
Ref: whatsnew/3 7 zipapp376796
Ref: 424376796
Ref: zipapp-Footnote-1377289
Ref: zipapp-Footnote-2377332
Node: zipfile377375
Ref: whatsnew/3 7 zipfile377452
Ref: 426377452
Ref: zipfile-Footnote-1377813
Ref: zipfile-Footnote-2377856
Node: C API 的改变377899
Ref: whatsnew/3 7 c-api-changes378031
Ref: 428378031
Ref: C API 的改变-Footnote-1382552
Ref: C API 的改变-Footnote-2382595
Ref: C API 的改变-Footnote-3382638
Ref: C API 的改变-Footnote-4382681
Ref: C API 的改变-Footnote-5382724
Ref: C API 的改变-Footnote-6382767
Ref: C API 的改变-Footnote-7382810
Ref: C API 的改变-Footnote-8382853
Ref: C API 的改变-Footnote-9382896
Ref: C API 的改变-Footnote-10382939
Ref: C API 的改变-Footnote-11382983
Ref: C API 的改变-Footnote-12383027
Ref: C API 的改变-Footnote-13383071
Ref: C API 的改变-Footnote-14383115
Ref: C API 的改变-Footnote-15383159
Ref: C API 的改变-Footnote-16383202
Ref: C API 的改变-Footnote-17383246
Ref: C API 的改变-Footnote-18383290
Ref: C API 的改变-Footnote-19383334
Ref: C API 的改变-Footnote-20383378
Node: 构建的改变383422
Ref: whatsnew/3 7 build-changes383551
Ref: 449383551
Ref: 构建的改变-Footnote-1384625
Ref: 构建的改变-Footnote-2384668
Ref: 构建的改变-Footnote-3384711
Node: 性能优化<2>384754
Ref: whatsnew/3 7 optimizations384898
Ref: 44a384898
Ref: whatsnew/3 7 whatsnew37-perf384898
Ref: 30f384898
Ref: whatsnew/3 7 whatsnew37-asyncio-perf385593
Ref: 350385593
Ref: 性能优化<2>-Footnote-1390181
Ref: 性能优化<2>-Footnote-2390224
Ref: 性能优化<2>-Footnote-3390267
Ref: 性能优化<2>-Footnote-4390310
Ref: 性能优化<2>-Footnote-5390353
Ref: 性能优化<2>-Footnote-6390396
Ref: 性能优化<2>-Footnote-7390439
Ref: 性能优化<2>-Footnote-8390482
Ref: 性能优化<2>-Footnote-9390525
Ref: 性能优化<2>-Footnote-10390568
Ref: 性能优化<2>-Footnote-11390612
Ref: 性能优化<2>-Footnote-12390656
Ref: 性能优化<2>-Footnote-13390700
Ref: 性能优化<2>-Footnote-14390744
Ref: 性能优化<2>-Footnote-15390788
Ref: 性能优化<2>-Footnote-16390832
Ref: 性能优化<2>-Footnote-17390876
Ref: 性能优化<2>-Footnote-18390920
Ref: 性能优化<2>-Footnote-19390964
Ref: 性能优化<2>-Footnote-20391008
Ref: 性能优化<2>-Footnote-21391052
Ref: 性能优化<2>-Footnote-22391096
Ref: 性能优化<2>-Footnote-23391140
Ref: 性能优化<2>-Footnote-24391184
Ref: 性能优化<2>-Footnote-25391228
Ref: 性能优化<2>-Footnote-26391272
Ref: 性能优化<2>-Footnote-27391316
Ref: 性能优化<2>-Footnote-28391360
Ref: 性能优化<2>-Footnote-29391404
Ref: 性能优化<2>-Footnote-30391448
Node: 其他 CPython 实现的改变391492
Ref: whatsnew/3 7 other-cpython-implementation-changes391647
Ref: 45c391647
Ref: 其他 CPython 实现的改变-Footnote-1392924
Ref: 其他 CPython 实现的改变-Footnote-2392967
Ref: 其他 CPython 实现的改变-Footnote-3393010
Ref: 其他 CPython 实现的改变-Footnote-4393053
Ref: 其他 CPython 实现的改变-Footnote-5393096
Node: 已弃用的 Python 行为393139
Ref: whatsnew/3 7 deprecated-python-behavior393323
Ref: 45e393323
Ref: 已弃用的 Python 行为-Footnote-1394413
Ref: 已弃用的 Python 行为-Footnote-2394456
Node: 已弃用的 Python 模块、函数和方法394499
Ref: whatsnew/3 7 deprecated-python-modules-functions-and-methods394687
Ref: 461394687
Node: aifc395065
Ref: whatsnew/3 7 aifc395169
Ref: 462395169
Ref: aifc-Footnote-1395391
Node: asyncio<3>395434
Ref: whatsnew/3 7 id2395561
Ref: 464395561
Ref: whatsnew/3 7 whatsnew37-asyncio-deprecated395561
Ref: 374395561
Ref: asyncio<3>-Footnote-1396027
Ref: asyncio<3>-Footnote-2396070
Node: collections<3>396113
Ref: whatsnew/3 7 id3396242
Ref: 465396242
Ref: collections<3>-Footnote-1396572
Node: dbm<2>396615
Ref: whatsnew/3 7 id4396741
Ref: 466396741
Ref: dbm<2>-Footnote-1397144
Node: enum<2>397187
Ref: whatsnew/3 7 id5397309
Ref: 467397309
Ref: enum<2>-Footnote-1397742
Node: gettext<2>397785
Ref: whatsnew/3 7 gettext397913
Ref: 468397913
Ref: gettext<2>-Footnote-1398158
Node: importlib<2>398201
Ref: whatsnew/3 7 id6398331
Ref: 469398331
Ref: importlib<2>-Footnote-1398868
Node: locale<2>398911
Ref: whatsnew/3 7 id7399038
Ref: 46f399038
Ref: locale<2>-Footnote-1399243
Node: macpath399286
Ref: whatsnew/3 7 macpath399413
Ref: 471399413
Ref: macpath-Footnote-1399604
Node: threading<2>399646
Ref: whatsnew/3 7 threading399773
Ref: 472399773
Ref: threading<2>-Footnote-1400058
Node: socket<3>400101
Ref: whatsnew/3 7 id8400227
Ref: 473400227
Ref: socket<3>-Footnote-1400551
Node: ssl<3>400594
Ref: whatsnew/3 7 id9400713
Ref: 476400713
Ref: ssl<3>-Footnote-1400933
Node: sunau400976
Ref: whatsnew/3 7 sunau401092
Ref: 478401092
Ref: sunau-Footnote-1401326
Node: sys<3>401369
Ref: whatsnew/3 7 id10401483
Ref: 47b401483
Ref: sys<3>-Footnote-1401795
Node: wave401838
Ref: whatsnew/3 7 wave401938
Ref: 47c401938
Ref: wave-Footnote-1402168
Node: 已弃用的 C API 函数和类型402211
Ref: whatsnew/3 7 deprecated-functions-and-types-of-the-c-api402394
Ref: 47f402394
Ref: 已弃用的 C API 函数和类型-Footnote-1403017
Ref: 已弃用的 C API 函数和类型-Footnote-2403060
Node: 平台支持的移除403103
Ref: whatsnew/3 7 id11403267
Ref: 481403267
Ref: whatsnew/3 7 platform-support-removals403267
Ref: 3e7403267
Ref: 平台支持的移除-Footnote-1404648
Ref: 平台支持的移除-Footnote-2404711
Node: API 与特性的移除<2>404790
Ref: whatsnew/3 7 api-and-feature-removals404935
Ref: 482404935
Ref: API 与特性的移除<2>-Footnote-1407701
Ref: API 与特性的移除<2>-Footnote-2407744
Ref: API 与特性的移除<2>-Footnote-3407787
Node: 移除的模块407830
Ref: whatsnew/3 7 module-removals407977
Ref: 48a407977
Ref: 移除的模块-Footnote-1408289
Node: Windows 专属的改变408332
Ref: whatsnew/3 7 windows-only-changes408474
Ref: 48b408474
Ref: Windows 专属的改变-Footnote-1409312
Ref: Windows 专属的改变-Footnote-2409355
Node: 移植到 Python 3 7409398
Ref: whatsnew/3 7 porting-to-python-3-7409556
Ref: 48c409556
Ref: whatsnew/3 7 porting-to-python-37409556
Ref: 310409556
Node: Python 行为的更改410010
Ref: whatsnew/3 7 changes-in-python-behavior410121
Ref: 48d410121
Ref: Python 行为的更改-Footnote-1411835
Ref: Python 行为的更改-Footnote-2411878
Ref: Python 行为的更改-Footnote-3411927
Ref: Python 行为的更改-Footnote-4411970
Ref: Python 行为的更改-Footnote-5412013
Ref: Python 行为的更改-Footnote-6412056
Node: Python API 的变化<3>412099
Ref: whatsnew/3 7 changes-in-the-python-api412237
Ref: 491412237
Ref: Python API 的变化<3>-Footnote-1421512
Ref: Python API 的变化<3>-Footnote-2421555
Ref: Python API 的变化<3>-Footnote-3421598
Ref: Python API 的变化<3>-Footnote-4421641
Ref: Python API 的变化<3>-Footnote-5421684
Ref: Python API 的变化<3>-Footnote-6421727
Ref: Python API 的变化<3>-Footnote-7421770
Ref: Python API 的变化<3>-Footnote-8421813
Ref: Python API 的变化<3>-Footnote-9421856
Ref: Python API 的变化<3>-Footnote-10421899
Ref: Python API 的变化<3>-Footnote-11421943
Ref: Python API 的变化<3>-Footnote-12421987
Ref: Python API 的变化<3>-Footnote-13422031
Ref: Python API 的变化<3>-Footnote-14422075
Ref: Python API 的变化<3>-Footnote-15422118
Ref: Python API 的变化<3>-Footnote-16422162
Ref: Python API 的变化<3>-Footnote-17422206
Ref: Python API 的变化<3>-Footnote-18422250
Ref: Python API 的变化<3>-Footnote-19422294
Ref: Python API 的变化<3>-Footnote-20422338
Ref: Python API 的变化<3>-Footnote-21422382
Ref: Python API 的变化<3>-Footnote-22422426
Ref: Python API 的变化<3>-Footnote-23422470
Ref: Python API 的变化<3>-Footnote-24422514
Ref: Python API 的变化<3>-Footnote-25422558
Ref: Python API 的变化<3>-Footnote-26422602
Ref: Python API 的变化<3>-Footnote-27422646
Ref: Python API 的变化<3>-Footnote-28422690
Ref: Python API 的变化<3>-Footnote-29422734
Ref: Python API 的变化<3>-Footnote-30422778
Node: C API 的变化<2>422822
Ref: whatsnew/3 7 changes-in-the-c-api422967
Ref: 4b3422967
Ref: C API 的变化<2>-Footnote-1423587
Node: CPython 字节码的改变<2>423630
Ref: whatsnew/3 7 cpython-bytecode-changes423778
Ref: 4b4423778
Ref: CPython 字节码的改变<2>-Footnote-1424138
Ref: CPython 字节码的改变<2>-Footnote-2424181
Node: Windows 专属的改变<2>424224
Ref: whatsnew/3 7 id12424387
Ref: 4b7424387
Ref: Windows 专属的改变<2>-Footnote-1424715
Node: 其他 CPython 实现的改变<2>424758
Ref: whatsnew/3 7 id13424883
Ref: 4b9424883
Ref: 其他 CPython 实现的改变<2>-Footnote-1426983
Ref: 其他 CPython 实现的改变<2>-Footnote-2427032
Ref: 其他 CPython 实现的改变<2>-Footnote-3427075
Node: Python 3 7 1 中的重要变化427118
Ref: whatsnew/3 7 notable-changes-in-python-3-7-1427284
Ref: 4be427284
Ref: Python 3 7 1 中的重要变化-Footnote-1428211
Ref: Python 3 7 1 中的重要变化-Footnote-2428254
Ref: Python 3 7 1 中的重要变化-Footnote-3428297
Node: Python 3 7 2 中的重要变化428340
Ref: whatsnew/3 7 notable-changes-in-python-3-7-2428517
Ref: 4c3428517
Node: Python 3 7 6 中的重要变化428990
Ref: whatsnew/3 7 notable-changes-in-python-3-7-6429168
Ref: 4c4429168
Ref: Python 3 7 6 中的重要变化-Footnote-1429649
Node: Python 3 7 10 中的重要变化429692
Ref: whatsnew/3 7 notable-changes-in-python-3-7-10429830
Ref: 4c5429830
Ref: Python 3 7 10 中的重要变化-Footnote-1430527
Node: Python 3 6 有什么新变化430570
Ref: whatsnew/3 6 doc430730
Ref: 4c6430730
Ref: whatsnew/3 6 what-s-new-in-python-3-6430730
Ref: 4c7430730
Ref: Python 3 6 有什么新变化-Footnote-1431939
Ref: Python 3 6 有什么新变化-Footnote-2431999
Node: 摘要 - 发布重点<3>432048
Ref: whatsnew/3 6 summary-release-highlights432162
Ref: 4c8432162
Ref: 摘要 - 发布重点<3>-Footnote-1435844
Ref: 摘要 - 发布重点<3>-Footnote-2435924
Ref: 摘要 - 发布重点<3>-Footnote-3436014
Node: 新的特性<3>436063
Ref: whatsnew/3 6 new-features436213
Ref: 4df436213
Ref: whatsnew/3 6 pypy-dict-implementation436213
Ref: 4e0436213
Node: PEP 498 格式化的字符串文字437413
Ref: whatsnew/3 6 pep-498-formatted-string-literals437538
Ref: 4e1437538
Ref: whatsnew/3 6 whatsnew36-pep498437538
Ref: 4c9437538
Ref: PEP 498 格式化的字符串文字-Footnote-1438481
Ref: PEP 498 格式化的字符串文字-Footnote-2438530
Node: PEP 526 变量注释的语法438579
Ref: whatsnew/3 6 pep-526-syntax-for-variable-annotations438751
Ref: 4e4438751
Ref: whatsnew/3 6 whatsnew36-pep526438751
Ref: 4cb438751
Ref: PEP 526 变量注释的语法-Footnote-1439807
Ref: PEP 526 变量注释的语法-Footnote-2439856
Ref: PEP 526 变量注释的语法-Footnote-3439905
Ref: PEP 526 变量注释的语法-Footnote-4439939
Node: PEP 515 数字文字中的下划线。439980
Ref: whatsnew/3 6 pep-515-underscores-in-numeric-literals440140
Ref: 4e5440140
Ref: whatsnew/3 6 whatsnew36-pep515440140
Ref: 4ca440140
Ref: PEP 515 数字文字中的下划线。-Footnote-1441097
Ref: PEP 515 数字文字中的下划线。-Footnote-2441146
Node: PEP 525 异步生成器441195
Ref: whatsnew/3 6 pep-525-asynchronous-generators441346
Ref: 4e7441346
Ref: whatsnew/3 6 whatsnew36-pep525441346
Ref: 4cc441346
Ref: PEP 525 异步生成器-Footnote-1442091
Ref: PEP 525 异步生成器-Footnote-2442140
Node: PEP 530 异步推导442189
Ref: whatsnew/3 6 pep-530-asynchronous-comprehensions442328
Ref: 4e8442328
Ref: whatsnew/3 6 whatsnew36-pep530442328
Ref: 4cd442328
Ref: PEP 530 异步推导-Footnote-1442822
Ref: PEP 530 异步推导-Footnote-2442871
Node: PEP 487 自定义类创建442920
Ref: whatsnew/3 6 pep-487-simpler-customization-of-class-creation443068
Ref: 4e9443068
Ref: whatsnew/3 6 whatsnew36-pep487443068
Ref: 4d0443068
Ref: PEP 487 自定义类创建-Footnote-1444010
Node: PEP 487 描述器协议的增强444059
Ref: whatsnew/3 6 pep-487-descriptor-protocol-enhancements444225
Ref: 4ee444225
Ref: whatsnew/3 6 whatsnew36-pep487-descriptors444225
Ref: 4ef444225
Ref: PEP 487 描述器协议的增强-Footnote-1445335
Ref: PEP 487 描述器协议的增强-Footnote-2445384
Node: PEP 519 添加文件系统路径协议445433
Ref: whatsnew/3 6 pep-519-adding-a-file-system-path-protocol445608
Ref: 4f2445608
Ref: whatsnew/3 6 whatsnew36-pep519445608
Ref: 4d5445608
Ref: PEP 519 添加文件系统路径协议-Footnote-1448411
Node: PEP 495 消除本地时间的歧义448460
Ref: whatsnew/3 6 pep-495-local-time-disambiguation448653
Ref: 4fa448653
Ref: whatsnew/3 6 whatsnew36-pep495448653
Ref: 4d6448653
Ref: PEP 495 消除本地时间的歧义-Footnote-1450053
Ref: PEP 495 消除本地时间的歧义-Footnote-2450102
Node: PEP 529 将Windows文件系统编码更改为UTF-8450151
Ref: whatsnew/3 6 pep-529-change-windows-filesystem-encoding-to-utf-8450353
Ref: 4fd450353
Ref: whatsnew/3 6 whatsnew36-pep529450353
Ref: 4dc450353
Ref: PEP 529 将Windows文件系统编码更改为UTF-8-Footnote-1451361
Node: PEP 528 将Windows控制台编码更改为UTF-8451410
Ref: whatsnew/3 6 pep-528-change-windows-console-encoding-to-utf-8451612
Ref: 501451612
Ref: whatsnew/3 6 whatsnew36-pep528451612
Ref: 4db451612
Ref: PEP 528 将Windows控制台编码更改为UTF-8-Footnote-1452292
Node: PEP 520 保留类属性定义顺序452341
Ref: whatsnew/3 6 pep-520-preserving-class-attribute-definition-order452528
Ref: 503452528
Ref: whatsnew/3 6 whatsnew36-pep520452528
Ref: 4d1452528
Ref: PEP 520 保留类属性定义顺序-Footnote-1453097
Node: PEP 468 保留关键字参数顺序453146
Ref: whatsnew/3 6 pep-468-preserving-keyword-argument-order453304
Ref: 506453304
Ref: whatsnew/3 6 whatsnew36-pep468453304
Ref: 4d2453304
Ref: PEP 468 保留关键字参数顺序-Footnote-1453624
Node: 新的 dict 实现453673
Ref: whatsnew/3 6 new-dict-implementation453836
Ref: 507453836
Ref: whatsnew/3 6 whatsnew36-compactdict453836
Ref: 4cf453836
Ref: 新的 dict 实现-Footnote-1454796
Ref: 新的 dict 实现-Footnote-2454876
Ref: 新的 dict 实现-Footnote-3454966
Ref: 新的 dict 实现-Footnote-4455009
Node: PEP 523 向CPython 添加框架评估API455089
Ref: whatsnew/3 6 pep-523-adding-a-frame-evaluation-api-to-cpython455242
Ref: 508455242
Ref: whatsnew/3 6 whatsnew36-pep523455242
Ref: 509455242
Ref: PEP 523 向CPython 添加框架评估API-Footnote-1456378
Ref: PEP 523 向CPython 添加框架评估API-Footnote-2456427
Node: PYTHONMALLOC 环境变量456476
Ref: whatsnew/3 6 pythonmalloc-environment-variable456644
Ref: 50a456644
Ref: whatsnew/3 6 whatsnew36-pythonmalloc456644
Ref: 4d4456644
Ref: PYTHONMALLOC 环境变量-Footnote-1459788
Ref: PYTHONMALLOC 环境变量-Footnote-2459831
Node: DTrace 和 SystemTap 探测支持459874
Ref: whatsnew/3 6 dtrace-and-systemtap-probing-support459993
Ref: 513459993
Ref: whatsnew/3 6 whatsnew36-tracing459993
Ref: 4d3459993
Ref: DTrace 和 SystemTap 探测支持-Footnote-1460800
Node: 其他语言特性修改<3>460843
Ref: whatsnew/3 6 other-language-changes460984
Ref: 515460984
Ref: 其他语言特性修改<3>-Footnote-1462347
Ref: 其他语言特性修改<3>-Footnote-2462390
Ref: 其他语言特性修改<3>-Footnote-3462433
Ref: 其他语言特性修改<3>-Footnote-4462476
Node: 新增模块<3>462519
Ref: whatsnew/3 6 new-modules462663
Ref: 519462663
Node: secrets462720
Ref: whatsnew/3 6 secrets462779
Ref: 51a462779
Ref: whatsnew/3 6 whatsnew36-pep506462779
Ref: 4ce462779
Ref: secrets-Footnote-1463440
Node: 改进的模块<3>463489
Ref: whatsnew/3 6 improved-modules463621
Ref: 51b463621
Node: array464992
Ref: whatsnew/3 6 array465067
Ref: 51c465067
Ref: array-Footnote-1465362
Node: ast<2>465405
Ref: whatsnew/3 6 ast465499
Ref: 51d465499
Ref: ast<2>-Footnote-1465744
Node: asyncio<4>465787
Ref: whatsnew/3 6 asyncio465887
Ref: 51e465887
Ref: asyncio<4>-Footnote-1469227
Ref: asyncio<4>-Footnote-2469270
Ref: asyncio<4>-Footnote-3469315
Ref: asyncio<4>-Footnote-4469358
Ref: asyncio<4>-Footnote-5469401
Ref: asyncio<4>-Footnote-6469444
Ref: asyncio<4>-Footnote-7469487
Ref: asyncio<4>-Footnote-8469530
Ref: asyncio<4>-Footnote-9469573
Ref: asyncio<4>-Footnote-10469616
Ref: asyncio<4>-Footnote-11469660
Ref: asyncio<4>-Footnote-12469704
Node: binascii<2>469748
Ref: whatsnew/3 6 binascii469847
Ref: 52a469847
Ref: binascii<2>-Footnote-1470132
Node: cmath470175
Ref: whatsnew/3 6 cmath470278
Ref: 52c470278
Ref: cmath-Footnote-1470749
Ref: cmath-Footnote-2470792
Ref: cmath-Footnote-3470841
Node: collections<4>470884
Ref: whatsnew/3 6 collections470997
Ref: 534470997
Ref: collections<4>-Footnote-1472098
Ref: collections<4>-Footnote-2472141
Ref: collections<4>-Footnote-3472184
Ref: collections<4>-Footnote-4472227
Ref: collections<4>-Footnote-5472270
Ref: collections<4>-Footnote-6472313
Node: concurrent futures<2>472356
Ref: whatsnew/3 6 concurrent-futures472477
Ref: 53a472477
Ref: concurrent futures<2>-Footnote-1472807
Node: contextlib<2>472850
Ref: whatsnew/3 6 contextlib472968
Ref: 53b472968
Ref: contextlib<2>-Footnote-1473464
Node: datetime<3>473507
Ref: whatsnew/3 6 datetime473614
Ref: 53e473614
Ref: datetime<3>-Footnote-1474631
Ref: datetime<3>-Footnote-2474674
Ref: datetime<3>-Footnote-3474717
Ref: datetime<3>-Footnote-4474760
Node: decimal<2>474803
Ref: whatsnew/3 6 decimal474909
Ref: 543474909
Ref: decimal<2>-Footnote-1475328
Node: distutils<2>475371
Ref: whatsnew/3 6 distutils475471
Ref: 545475471
Ref: distutils<2>-Footnote-1475845
Node: email475888
Ref: whatsnew/3 6 email475987
Ref: 546475987
Ref: email-Footnote-1476903
Ref: email-Footnote-2476946
Ref: email-Footnote-3476989
Node: encodings477032
Ref: whatsnew/3 6 encodings477126
Ref: 54c477126
Ref: encodings-Footnote-1477421
Node: enum<3>477464
Ref: whatsnew/3 6 enum477565
Ref: 54d477565
Ref: enum<3>-Footnote-1478313
Node: faulthandler478356
Ref: whatsnew/3 6 faulthandler478457
Ref: 550478457
Ref: faulthandler-Footnote-1478720
Node: fileinput478763
Ref: whatsnew/3 6 fileinput478864
Ref: 552478864
Ref: fileinput-Footnote-1479052
Node: hashlib479095
Ref: whatsnew/3 6 hashlib479198
Ref: 554479198
Ref: hashlib-Footnote-1480216
Ref: hashlib-Footnote-2480259
Ref: hashlib-Footnote-3480302
Ref: hashlib-Footnote-4480345
Node: http client<2>480388
Ref: whatsnew/3 6 http-client480501
Ref: 557480501
Ref: http client<2>-Footnote-1480761
Node: idlelib 与 IDLE<2>480804
Ref: whatsnew/3 6 idlelib-and-idle480922
Ref: 55a480922
Ref: idlelib 与 IDLE<2>-Footnote-1484399
Ref: idlelib 与 IDLE<2>-Footnote-2484442
Ref: idlelib 与 IDLE<2>-Footnote-3484485
Ref: idlelib 与 IDLE<2>-Footnote-4484530
Ref: idlelib 与 IDLE<2>-Footnote-5484573
Ref: idlelib 与 IDLE<2>-Footnote-6484616
Ref: idlelib 与 IDLE<2>-Footnote-7484659
Ref: idlelib 与 IDLE<2>-Footnote-8484702
Ref: idlelib 与 IDLE<2>-Footnote-9484745
Ref: idlelib 与 IDLE<2>-Footnote-10484788
Ref: idlelib 与 IDLE<2>-Footnote-11484832
Node: importlib<3>484878
Ref: whatsnew/3 6 importlib484992
Ref: 55b484992
Ref: importlib<3>-Footnote-1485819
Node: inspect<2>485862
Ref: whatsnew/3 6 inspect485961
Ref: 563485961
Ref: inspect<2>-Footnote-1486742
Ref: inspect<2>-Footnote-2486785
Node: json486828
Ref: whatsnew/3 6 json486925
Ref: 567486925
Ref: json-Footnote-1487197
Node: logging<3>487240
Ref: whatsnew/3 6 logging487334
Ref: 56a487334
Ref: logging<3>-Footnote-1487598
Node: math<3>487641
Ref: whatsnew/3 6 math487749
Ref: 56c487749
Ref: math<3>-Footnote-1487981
Ref: math<3>-Footnote-2488024
Node: multiprocessing<3>488073
Ref: whatsnew/3 6 multiprocessing488176
Ref: 56d488176
Ref: multiprocessing<3>-Footnote-1488399
Node: os<3>488441
Ref: whatsnew/3 6 os488547
Ref: 56f488547
Ref: os<3>-Footnote-1489535
Ref: os<3>-Footnote-2489578
Ref: os<3>-Footnote-3489627
Node: pathlib<3>489676
Ref: whatsnew/3 6 pathlib489770
Ref: 573489770
Ref: pathlib<3>-Footnote-1490004
Node: pdb<2>490047
Ref: whatsnew/3 6 pdb490145
Ref: 574490145
Node: pickle<2>490302
Ref: whatsnew/3 6 pickle490401
Ref: 576490401
Ref: pickle<2>-Footnote-1490718
Node: pickletools490761
Ref: whatsnew/3 6 pickletools490862
Ref: 578490862
Ref: pickletools-Footnote-1491090
Node: pydoc<2>491133
Ref: whatsnew/3 6 pydoc491231
Ref: 57a491231
Ref: pydoc<2>-Footnote-1491625
Ref: pydoc<2>-Footnote-2491667
Node: random491710
Ref: whatsnew/3 6 random491802
Ref: 57c491802
Ref: random-Footnote-1492057
Node: re<2>492100
Ref: whatsnew/3 6 re492192
Ref: 57e492192
Ref: re<2>-Footnote-1492897
Ref: re<2>-Footnote-2492941
Ref: re<2>-Footnote-3492984
Node: readline493027
Ref: whatsnew/3 6 readline493124
Ref: 57f493124
Ref: readline-Footnote-1493355
Node: rlcompleter493398
Ref: whatsnew/3 6 rlcompleter493498
Ref: 581493498
Ref: rlcompleter-Footnote-1493802
Ref: rlcompleter-Footnote-2493845
Node: shlex<2>493888
Ref: whatsnew/3 6 shlex493984
Ref: 582493984
Ref: shlex<2>-Footnote-1494274
Node: site494319
Ref: whatsnew/3 6 site494414
Ref: 585494414
Ref: site-Footnote-1494678
Node: sqlite3<2>494721
Ref: whatsnew/3 6 sqlite3494817
Ref: 586494817
Ref: sqlite3<2>-Footnote-1495020
Node: socket<4>495063
Ref: whatsnew/3 6 socket495170
Ref: 588495170
Ref: socket<4>-Footnote-1496132
Ref: socket<4>-Footnote-2496175
Ref: socket<4>-Footnote-3496218
Ref: socket<4>-Footnote-4496261
Node: socketserver<2>496304
Ref: whatsnew/3 6 socketserver496407
Ref: 58f496407
Ref: socketserver<2>-Footnote-1497036
Ref: socketserver<2>-Footnote-2497079
Node: ssl<4>497122
Ref: whatsnew/3 6 ssl497229
Ref: 593497229
Ref: ssl<4>-Footnote-1498425
Ref: ssl<4>-Footnote-2498468
Ref: ssl<4>-Footnote-3498511
Ref: ssl<4>-Footnote-4498554
Ref: ssl<4>-Footnote-5498597
Ref: ssl<4>-Footnote-6498640
Ref: ssl<4>-Footnote-7498683
Node: statistics<2>498726
Ref: whatsnew/3 6 statistics498824
Ref: 597498824
Ref: statistics<2>-Footnote-1499014
Node: struct499057
Ref: whatsnew/3 6 struct499162
Ref: 599499162
Ref: struct-Footnote-1499393
Node: subprocess<2>499436
Ref: whatsnew/3 6 subprocess499534
Ref: 59a499534
Ref: subprocess<2>-Footnote-1500227
Ref: subprocess<2>-Footnote-2500270
Node: sys<4>500312
Ref: whatsnew/3 6 sys500413
Ref: 59c500413
Ref: sys<4>-Footnote-1501014
Ref: sys<4>-Footnote-2501057
Node: telnetlib501100
Ref: whatsnew/3 6 telnetlib501195
Ref: 59f501195
Ref: telnetlib-Footnote-1501366
Node: time<3>501409
Ref: whatsnew/3 6 time501504
Ref: 5a1501504
Node: timeit501643
Ref: whatsnew/3 6 timeit501739
Ref: 5a3501739
Ref: timeit-Footnote-1502199
Ref: timeit-Footnote-2502241
Node: tkinter<3>502284
Ref: whatsnew/3 6 tkinter502379
Ref: 5a6502379
Ref: tkinter<3>-Footnote-1502805
Node: 回溯502848
Ref: whatsnew/3 6 traceback502951
Ref: 5a7502951
Ref: whatsnew/3 6 whatsnew36-traceback502951
Ref: 518502951
Ref: 回溯-Footnote-1503583
Node: tracemalloc<2>503626
Ref: whatsnew/3 6 tracemalloc503728
Ref: 5a8503728
Ref: tracemalloc<2>-Footnote-1504095
Node: typing<2>504138
Ref: whatsnew/3 6 typing504248
Ref: 5aa504248
Ref: whatsnew/3 6 whatsnew36-typing504248
Ref: 4d7504248
Ref: typing<2>-Footnote-1505900
Ref: typing<2>-Footnote-2505950
Ref: typing<2>-Footnote-3505993
Ref: typing<2>-Footnote-4506036
Ref: typing<2>-Footnote-5506085
Ref: typing<2>-Footnote-6506135
Ref: typing<2>-Footnote-7506187
Node: unicodedata<3>506239
Ref: whatsnew/3 6 unicodedata506351
Ref: 5af506351
Ref: unicodedata<3>-Footnote-1506539
Node: unittest mock<2>506589
Ref: whatsnew/3 6 unittest-mock506706
Ref: 5b0506706
Ref: unittest mock<2>-Footnote-1507223
Ref: unittest mock<2>-Footnote-2507266
Node: urllib request507309
Ref: whatsnew/3 6 urllib-request507430
Ref: 5b4507430
Ref: urllib request-Footnote-1507795
Node: urllib robotparser507838
Ref: whatsnew/3 6 urllib-robotparser507950
Ref: 5b5507950
Ref: urllib robotparser-Footnote-1508195
Node: venv<2>508238
Ref: whatsnew/3 6 venv508347
Ref: 5b7508347
Ref: venv<2>-Footnote-1508634
Node: warnings<2>508677
Ref: whatsnew/3 6 warnings508774
Ref: 5b8508774
Ref: warnings<2>-Footnote-1510045
Ref: warnings<2>-Footnote-2510088
Node: winreg510131
Ref: whatsnew/3 6 winreg510229
Ref: 5ba510229
Ref: winreg-Footnote-1510402
Node: winsound510445
Ref: whatsnew/3 6 winsound510545
Ref: 5bc510545
Ref: winsound-Footnote-1510744
Node: xmlrpc client510787
Ref: whatsnew/3 6 xmlrpc-client510891
Ref: 5c0510891
Ref: xmlrpc client-Footnote-1511184
Node: zipfile<2>511227
Ref: whatsnew/3 6 zipfile511327
Ref: 5c1511327
Ref: zipfile<2>-Footnote-1511861
Ref: zipfile<2>-Footnote-2511904
Node: zlib511947
Ref: whatsnew/3 6 zlib512025
Ref: 5c6512025
Ref: zlib-Footnote-1512281
Ref: zlib-Footnote-2512324
Node: 性能优化<3>512367
Ref: whatsnew/3 6 optimizations512512
Ref: 5c9512512
Ref: 性能优化<3>-Footnote-1516375
Ref: 性能优化<3>-Footnote-2516418
Ref: 性能优化<3>-Footnote-3516461
Ref: 性能优化<3>-Footnote-4516504
Ref: 性能优化<3>-Footnote-5516547
Ref: 性能优化<3>-Footnote-6516590
Ref: 性能优化<3>-Footnote-7516633
Ref: 性能优化<3>-Footnote-8516676
Ref: 性能优化<3>-Footnote-9516719
Ref: 性能优化<3>-Footnote-10516762
Ref: 性能优化<3>-Footnote-11516806
Ref: 性能优化<3>-Footnote-12516850
Ref: 性能优化<3>-Footnote-13516894
Ref: 性能优化<3>-Footnote-14516938
Ref: 性能优化<3>-Footnote-15516982
Ref: 性能优化<3>-Footnote-16517026
Ref: 性能优化<3>-Footnote-17517070
Ref: 性能优化<3>-Footnote-18517114
Ref: 性能优化<3>-Footnote-19517158
Ref: 性能优化<3>-Footnote-20517202
Ref: 性能优化<3>-Footnote-21517246
Node: 构建和 C API 的改变<2>517290
Ref: whatsnew/3 6 build-and-c-api-changes517429
Ref: 5d1517429
Ref: 构建和 C API 的改变<2>-Footnote-1519880
Ref: 构建和 C API 的改变<2>-Footnote-2519929
Ref: 构建和 C API 的改变<2>-Footnote-3519972
Ref: 构建和 C API 的改变<2>-Footnote-4520015
Ref: 构建和 C API 的改变<2>-Footnote-5520058
Ref: 构建和 C API 的改变<2>-Footnote-6520100
Ref: 构建和 C API 的改变<2>-Footnote-7520143
Ref: 构建和 C API 的改变<2>-Footnote-8520186
Ref: 构建和 C API 的改变<2>-Footnote-9520229
Ref: 构建和 C API 的改变<2>-Footnote-10520272
Node: 其他改进520316
Ref: whatsnew/3 6 other-improvements520449
Ref: 5d9520449
Node: 弃用<2>520804
Ref: whatsnew/3 6 deprecated520915
Ref: 5dd520915
Node: 新关键字521228
Ref: whatsnew/3 6 new-keywords521324
Ref: 5de521324
Ref: 新关键字-Footnote-1521713
Node: 已弃用的 Python 行为<2>521762
Ref: whatsnew/3 6 deprecated-python-behavior521914
Ref: 5df521914
Ref: 已弃用的 Python 行为<2>-Footnote-1523115
Ref: 已弃用的 Python 行为<2>-Footnote-2523158
Ref: 已弃用的 Python 行为<2>-Footnote-3523201
Node: 已弃用的 Python 模块、函数和方法<2>523244
Ref: whatsnew/3 6 deprecated-python-modules-functions-and-methods523421
Ref: 5e2523421
Node: asynchat523710
Ref: whatsnew/3 6 asynchat523819
Ref: 5e3523819
Ref: asynchat-Footnote-1524007
Node: asyncore524050
Ref: whatsnew/3 6 asyncore524174
Ref: 5e4524174
Ref: asyncore-Footnote-1524362
Node: dbm<3>524405
Ref: whatsnew/3 6 dbm524533
Ref: 5e5524533
Ref: dbm<3>-Footnote-1524893
Node: distutils<3>524936
Ref: whatsnew/3 6 id2525059
Ref: 5e6525059
Ref: distutils<3>-Footnote-1525379
Node: grp525422
Ref: whatsnew/3 6 grp525551
Ref: 5e7525551
Ref: grp-Footnote-1525749
Node: importlib<4>525792
Ref: whatsnew/3 6 id3525914
Ref: 5e9525914
Node: os<4>526568
Ref: whatsnew/3 6 id4526692
Ref: 5f0526692
Ref: os<4>-Footnote-1526986
Ref: os<4>-Footnote-2527029
Node: re<3>527072
Ref: whatsnew/3 6 id5527190
Ref: 5f2527190
Ref: re<3>-Footnote-1527516
Node: ssl<5>527559
Ref: whatsnew/3 6 id6527682
Ref: 5f3527682
Ref: ssl<5>-Footnote-1528477
Ref: ssl<5>-Footnote-2528520
Ref: ssl<5>-Footnote-3528563
Node: tkinter<4>528606
Ref: whatsnew/3 6 id7528731
Ref: 5f4528731
Node: venv<3>528892
Ref: whatsnew/3 6 id8529002
Ref: 5f5529002
Ref: venv<3>-Footnote-1529353
Node: 已弃用的 C API 函数和类型<2>529396
Ref: whatsnew/3 6 deprecated-functions-and-types-of-the-c-api529565
Ref: 5f6529565
Node: 弃用的构建选项529887
Ref: whatsnew/3 6 deprecated-build-options530000
Ref: 5f8530000
Node: 移除530428
Ref: whatsnew/3 6 removed530546
Ref: 5f9530546
Node: API 与特性的移除<3>530636
Ref: whatsnew/3 6 api-and-feature-removals530704
Ref: 5fa530704
Ref: API 与特性的移除<3>-Footnote-1532786
Ref: API 与特性的移除<3>-Footnote-2532829
Node: 移植到Python 3 6532902
Ref: whatsnew/3 6 porting-to-python-3-6533042
Ref: 5fe533042
Node: 'python' 命令行为的变化533378
Ref: whatsnew/3 6 changes-in-python-command-behavior533496
Ref: 5ff533496
Ref: 'python' 命令行为的变化-Footnote-1533957
Node: Python API 的变化<4>534000
Ref: whatsnew/3 6 changes-in-the-python-api534145
Ref: 600534145
Ref: Python API 的变化<4>-Footnote-1544238
Ref: Python API 的变化<4>-Footnote-2544280
Ref: Python API 的变化<4>-Footnote-3544329
Ref: Python API 的变化<4>-Footnote-4544372
Ref: Python API 的变化<4>-Footnote-5544415
Ref: Python API 的变化<4>-Footnote-6544458
Ref: Python API 的变化<4>-Footnote-7544501
Ref: Python API 的变化<4>-Footnote-8544544
Ref: Python API 的变化<4>-Footnote-9544587
Ref: Python API 的变化<4>-Footnote-10544630
Ref: Python API 的变化<4>-Footnote-11544674
Ref: Python API 的变化<4>-Footnote-12544724
Ref: Python API 的变化<4>-Footnote-13544768
Ref: Python API 的变化<4>-Footnote-14544812
Ref: Python API 的变化<4>-Footnote-15544856
Ref: Python API 的变化<4>-Footnote-16544900
Ref: Python API 的变化<4>-Footnote-17544943
Ref: Python API 的变化<4>-Footnote-18544987
Ref: Python API 的变化<4>-Footnote-19545031
Ref: Python API 的变化<4>-Footnote-20545075
Node: C API 的变化<3>545119
Ref: whatsnew/3 6 changes-in-the-c-api545263
Ref: 61a545263
Ref: C API 的变化<3>-Footnote-1545904
Ref: C API 的变化<3>-Footnote-2545947
Node: CPython 字节码的改变<3>545989
Ref: whatsnew/3 6 cpython-bytecode-changes546101
Ref: 61c546101
Ref: CPython 字节码的改变<3>-Footnote-1547755
Ref: CPython 字节码的改变<3>-Footnote-2547798
Ref: CPython 字节码的改变<3>-Footnote-3547841
Ref: CPython 字节码的改变<3>-Footnote-4547884
Ref: CPython 字节码的改变<3>-Footnote-5547927
Ref: CPython 字节码的改变<3>-Footnote-6547970
Ref: CPython 字节码的改变<3>-Footnote-7548013
Ref: CPython 字节码的改变<3>-Footnote-8548056
Ref: CPython 字节码的改变<3>-Footnote-9548099
Node: Python 3 6 2 中的重要变化548142
Ref: whatsnew/3 6 notable-changes-in-python-3-6-2548307
Ref: 629548307
Node: New make regen-all build target548465
Ref: whatsnew/3 6 new-make-regen-all-build-target548607
Ref: 62a548607
Ref: New make regen-all build target-Footnote-1549398
Ref: New make regen-all build target-Footnote-2549465
Node: Removal of make touch build target549508
Ref: whatsnew/3 6 removal-of-make-touch-build-target549650
Ref: 62b549650
Ref: Removal of make touch build target-Footnote-1550081
Node: Python 3 6 4 中的重要变化550124
Ref: whatsnew/3 6 notable-changes-in-python-3-6-4550301
Ref: 62c550301
Ref: Python 3 6 4 中的重要变化-Footnote-1550668
Ref: Python 3 6 4 中的重要变化-Footnote-2550711
Node: Python 3 6 5 中的重要变化550754
Ref: whatsnew/3 6 notable-changes-in-python-3-6-5550931
Ref: 62d550931
Ref: Python 3 6 5 中的重要变化-Footnote-1551228
Node: Python 3 6 7 中的重要变化551271
Ref: whatsnew/3 6 notable-changes-in-python-3-6-7551449
Ref: 62e551449
Ref: Python 3 6 7 中的重要变化-Footnote-1551820
Node: Python 3 6 10 中的重要变化551863
Ref: whatsnew/3 6 notable-changes-in-python-3-6-10552042
Ref: 62f552042
Ref: Python 3 6 10 中的重要变化-Footnote-1552525
Node: Notable changes in Python 3 6 13552568
Ref: whatsnew/3 6 notable-changes-in-python-3-6-13552707
Ref: 630552707
Ref: Notable changes in Python 3 6 13-Footnote-1553410
Node: Python 3 5 有什么新变化553453
Ref: whatsnew/3 5 doc553613
Ref: 631553613
Ref: whatsnew/3 5 what-s-new-in-python-3-5553613
Ref: 632553613
Ref: Python 3 5 有什么新变化-Footnote-1554506
Ref: Python 3 5 有什么新变化-Footnote-2554566
Node: 摘要 - 发布重点<4>554615
Ref: whatsnew/3 5 summary-release-highlights554729
Ref: 633554729
Ref: 摘要 - 发布重点<4>-Footnote-1558383
Ref: 摘要 - 发布重点<4>-Footnote-2558425
Ref: 摘要 - 发布重点<4>-Footnote-3558468
Ref: 摘要 - 发布重点<4>-Footnote-4558511
Ref: 摘要 - 发布重点<4>-Footnote-5558554
Ref: 摘要 - 发布重点<4>-Footnote-6558597
Ref: 摘要 - 发布重点<4>-Footnote-7558640
Node: 新的特性<4>558683
Ref: whatsnew/3 5 new-features558833
Ref: 646558833
Node: PEP 492 - 使用 async 和 await 语法实现协程559915
Ref: whatsnew/3 5 pep-492-coroutines-with-async-and-await-syntax560079
Ref: 647560079
Ref: whatsnew/3 5 whatsnew-pep-492560079
Ref: 634560079
Ref: PEP 492 - 使用 async 和 await 语法实现协程-Footnote-1563134
Ref: PEP 492 - 使用 async 和 await 语法实现协程-Footnote-2563183
Node: PEP 465 - 用于矩阵乘法的专用中缀运算符563232
Ref: whatsnew/3 5 pep-465-a-dedicated-infix-operator-for-matrix-multiplication563451
Ref: 650563451
Ref: whatsnew/3 5 whatsnew-pep-465563451
Ref: 635563451
Ref: PEP 465 - 用于矩阵乘法的专用中缀运算符-Footnote-1564771
Ref: PEP 465 - 用于矩阵乘法的专用中缀运算符-Footnote-2564820
Node: PEP 448 - Additional Unpacking Generalizations564869
Ref: whatsnew/3 5 pep-448-additional-unpacking-generalizations565097
Ref: 654565097
Ref: whatsnew/3 5 whatsnew-pep-448565097
Ref: 636565097
Ref: PEP 448 - Additional Unpacking Generalizations-Footnote-1566176
Ref: PEP 448 - Additional Unpacking Generalizations-Footnote-2566225
Node: PEP 461 - percent formatting support for bytes and bytearray566274
Ref: whatsnew/3 5 pep-461-percent-formatting-support-for-bytes-and-bytearray566472
Ref: 658566472
Ref: whatsnew/3 5 whatsnew-pep-461566472
Ref: 639566472
Ref: PEP 461 - percent formatting support for bytes and bytearray-Footnote-1568001
Ref: PEP 461 - percent formatting support for bytes and bytearray-Footnote-2568050
Node: PEP 484 - 类型提示568099
Ref: whatsnew/3 5 pep-484-type-hints568322
Ref: 65a568322
Ref: whatsnew/3 5 whatsnew-pep-484568322
Ref: 637568322
Ref: PEP 484 - 类型提示-Footnote-1569949
Ref: PEP 484 - 类型提示-Footnote-2569998
Ref: PEP 484 - 类型提示-Footnote-3570047
Ref: PEP 484 - 类型提示-Footnote-4570076
Ref: PEP 484 - 类型提示-Footnote-5570125
Node: PEP 471 - os scandir function -- a better and faster directory iterator570174
Ref: whatsnew/3 5 pep-471-os-scandir-function-a-better-and-faster-directory-iterator570382
Ref: 65c570382
Ref: whatsnew/3 5 whatsnew-pep-471570382
Ref: 642570382
Ref: PEP 471 - os scandir function -- a better and faster directory iterator-Footnote-1571718
Ref: PEP 471 - os scandir function -- a better and faster directory iterator-Footnote-2571767
Node: PEP 475 Retry system calls failing with EINTR571816
Ref: whatsnew/3 5 pep-475-retry-system-calls-failing-with-eintr572057
Ref: 65f572057
Ref: whatsnew/3 5 whatsnew-pep-475572057
Ref: 660572057
Ref: PEP 475 Retry system calls failing with EINTR-Footnote-1575075
Ref: PEP 475 Retry system calls failing with EINTR-Footnote-2575124
Node: PEP 479 Change StopIteration handling inside generators575173
Ref: whatsnew/3 5 pep-479-change-stopiteration-handling-inside-generators575394
Ref: 68a575394
Ref: whatsnew/3 5 whatsnew-pep-479575394
Ref: 5e0575394
Ref: PEP 479 Change StopIteration handling inside generators-Footnote-1577318
Ref: PEP 479 Change StopIteration handling inside generators-Footnote-2577367
Node: PEP 485 A function for testing approximate equality577416
Ref: whatsnew/3 5 pep-485-a-function-for-testing-approximate-equality577654
Ref: 68d577654
Ref: whatsnew/3 5 whatsnew-pep-485577654
Ref: 68e577654
Ref: PEP 485 A function for testing approximate equality-Footnote-1578814
Ref: PEP 485 A function for testing approximate equality-Footnote-2578863
Node: PEP 486 Make the Python Launcher aware of virtual environments578912
Ref: whatsnew/3 5 pep-486-make-the-python-launcher-aware-of-virtual-environments579127
Ref: 691579127
Ref: whatsnew/3 5 whatsnew-pep-486579127
Ref: 692579127
Ref: PEP 486 Make the Python Launcher aware of virtual environments-Footnote-1579687
Ref: PEP 486 Make the Python Launcher aware of virtual environments-Footnote-2579736
Ref: PEP 486 Make the Python Launcher aware of virtual environments-Footnote-3579785
Node: PEP 488 Elimination of PYO files579834
Ref: whatsnew/3 5 pep-488-elimination-of-pyo-files580049
Ref: 693580049
Ref: whatsnew/3 5 whatsnew-pep-488580049
Ref: 63e580049
Ref: PEP 488 Elimination of PYO files-Footnote-1580904
Ref: PEP 488 Elimination of PYO files-Footnote-2580953
Node: PEP 489 Multi-phase extension module initialization581002
Ref: whatsnew/3 5 pep-489-multi-phase-extension-module-initialization581146
Ref: 696581146
Ref: whatsnew/3 5 whatsnew-pep-489581146
Ref: 63f581146
Ref: PEP 489 Multi-phase extension module initialization-Footnote-1581902
Ref: PEP 489 Multi-phase extension module initialization-Footnote-2581951
Ref: PEP 489 Multi-phase extension module initialization-Footnote-3582000
Node: 其他语言特性修改<4>582049
Ref: whatsnew/3 5 other-language-changes582190
Ref: 697582190
Ref: 其他语言特性修改<4>-Footnote-1583169
Ref: 其他语言特性修改<4>-Footnote-2583212
Ref: 其他语言特性修改<4>-Footnote-3583255
Ref: 其他语言特性修改<4>-Footnote-4583298
Ref: 其他语言特性修改<4>-Footnote-5583341
Ref: 其他语言特性修改<4>-Footnote-6583384
Ref: 其他语言特性修改<4>-Footnote-7583427
Node: 新增模块<4>583470
Ref: whatsnew/3 5 new-modules583614
Ref: 699583614
Node: typing<3>583701
Ref: whatsnew/3 5 typing583780
Ref: 69a583780
Node: zipapp<2>583991
Ref: whatsnew/3 5 whatsnew-zipapp584070
Ref: 638584070
Ref: whatsnew/3 5 zipapp584070
Ref: 69b584070
Ref: zipapp<2>-Footnote-1584774
Ref: zipapp<2>-Footnote-2584823
Ref: zipapp<2>-Footnote-3584868
Ref: zipapp<2>-Footnote-4584911
Node: 改进的模块<4>584960
Ref: whatsnew/3 5 improved-modules585098
Ref: 69c585098
Node: argparse<2>586649
Ref: whatsnew/3 5 argparse586734
Ref: 69d586734
Ref: argparse<2>-Footnote-1587057
Node: asyncio<5>587100
Ref: whatsnew/3 5 asyncio587197
Ref: 6a1587197
Ref: asyncio<5>-Footnote-1590683
Ref: asyncio<5>-Footnote-2590726
Ref: asyncio<5>-Footnote-3590769
Node: bz2590814
Ref: whatsnew/3 5 bz2590903
Ref: 6ab590903
Ref: bz2-Footnote-1591158
Node: cgi591201
Ref: whatsnew/3 5 cgi591288
Ref: 6ad591288
Ref: cgi-Footnote-1591483
Node: cmath<2>591526
Ref: whatsnew/3 5 cmath591614
Ref: 6ae591614
Ref: cmath<2>-Footnote-1591828
Node: code591871
Ref: whatsnew/3 5 code591970
Ref: 6af591970
Ref: code-Footnote-1592221
Node: collections<5>592264
Ref: whatsnew/3 5 collections592370
Ref: 6b1592370
Ref: whatsnew/3 5 whatsnew-ordereddict592411
Ref: 640592411
Ref: collections<5>-Footnote-1593696
Ref: collections<5>-Footnote-2593739
Ref: collections<5>-Footnote-3593782
Ref: collections<5>-Footnote-4593825
Ref: collections<5>-Footnote-5593868
Node: collections abc593911
Ref: whatsnew/3 5 collections-abc594026
Ref: 6bd594026
Ref: collections abc-Footnote-1594696
Ref: collections abc-Footnote-2594739
Ref: collections abc-Footnote-3594782
Ref: collections abc-Footnote-4594825
Node: compileall<2>594872
Ref: whatsnew/3 5 compileall594994
Ref: 6c3594994
Ref: compileall<2>-Footnote-1595871
Ref: compileall<2>-Footnote-2595914
Ref: compileall<2>-Footnote-3595957
Node: concurrent futures<3>596000
Ref: whatsnew/3 5 concurrent-futures596119
Ref: 6c6596119
Ref: concurrent futures<3>-Footnote-1596621
Ref: concurrent futures<3>-Footnote-2596664
Node: configparser596707
Ref: whatsnew/3 5 configparser596826
Ref: 6c8596826
Ref: configparser-Footnote-1597782
Node: contextlib<3>597825
Ref: whatsnew/3 5 contextlib597929
Ref: 6c9597929
Ref: contextlib<3>-Footnote-1598545
Node: csv<2>598588
Ref: whatsnew/3 5 csv598689
Ref: 6cc598689
Ref: csv<2>-Footnote-1598893
Node: curses<2>598936
Ref: whatsnew/3 5 curses599030
Ref: 6ce599030
Ref: curses<2>-Footnote-1599311
Node: dbm<4>599353
Ref: whatsnew/3 5 dbm599448
Ref: 6d0599448
Ref: dbm<4>-Footnote-1599651
Node: difflib599694
Ref: whatsnew/3 5 difflib599792
Ref: 6d1599792
Ref: difflib-Footnote-1600328
Ref: difflib-Footnote-2600370
Node: distutils<4>600413
Ref: whatsnew/3 5 distutils600512
Ref: 6d4600512
Ref: distutils<4>-Footnote-1600967
Ref: distutils<4>-Footnote-2601009
Node: doctest601052
Ref: whatsnew/3 5 doctest601152
Ref: 6d5601152
Ref: doctest-Footnote-1601437
Node: email<2>601480
Ref: whatsnew/3 5 email601575
Ref: 6d8601575
Ref: email<2>-Footnote-1602686
Ref: email<2>-Footnote-2602729
Ref: email<2>-Footnote-3602772
Ref: email<2>-Footnote-4602821
Ref: email<2>-Footnote-5602870
Ref: email<2>-Footnote-6602913
Node: enum<4>602956
Ref: whatsnew/3 5 enum603059
Ref: 6de603059
Ref: enum<4>-Footnote-1603456
Node: faulthandler<2>603499
Ref: whatsnew/3 5 faulthandler603606
Ref: 6df603606
Ref: faulthandler<2>-Footnote-1603918
Node: functools<3>603961
Ref: whatsnew/3 5 functools604065
Ref: 6e3604065
Ref: whatsnew/3 5 whatsnew-lrucache604104
Ref: 643604104
Ref: functools<3>-Footnote-1604330
Node: glob604373
Ref: whatsnew/3 5 glob604469
Ref: 6e4604469
Ref: glob-Footnote-1604721
Node: gzip<2>604764
Ref: whatsnew/3 5 gzip604853
Ref: 6e5604853
Ref: gzip<2>-Footnote-1605078
Node: heapq605121
Ref: whatsnew/3 5 heapq605210
Ref: 6e7605210
Ref: heapq-Footnote-1605856
Node: http605899
Ref: whatsnew/3 5 http605995
Ref: 6ea605995
Ref: http-Footnote-1606241
Node: http client<3>606284
Ref: whatsnew/3 5 http-client606394
Ref: 6ec606394
Ref: http client<3>-Footnote-1607144
Node: idlelib 与 IDLE<3>607186
Ref: whatsnew/3 5 idlelib-and-idle607299
Ref: 6f0607299
Node: imaplib607692
Ref: whatsnew/3 5 imaplib607797
Ref: 6f1607797
Ref: imaplib-Footnote-1608676
Ref: imaplib-Footnote-2608718
Ref: imaplib-Footnote-3608767
Ref: imaplib-Footnote-4608816
Ref: imaplib-Footnote-5608865
Ref: imaplib-Footnote-6608908
Node: imghdr608951
Ref: whatsnew/3 5 imghdr609049
Ref: 6f5609049
Ref: imghdr-Footnote-1609343
Ref: imghdr-Footnote-2609374
Ref: imghdr-Footnote-3609417
Ref: imghdr-Footnote-4609460
Node: importlib<5>609503
Ref: whatsnew/3 5 importlib609604
Ref: 6f7609604
Ref: importlib<5>-Footnote-1610439
Ref: importlib<5>-Footnote-2610482
Ref: importlib<5>-Footnote-3610525
Node: inspect<3>610568
Ref: whatsnew/3 5 inspect610668
Ref: 6fb610668
Ref: inspect<3>-Footnote-1612231
Ref: inspect<3>-Footnote-2612274
Ref: inspect<3>-Footnote-3612317
Ref: inspect<3>-Footnote-4612360
Ref: inspect<3>-Footnote-5612403
Ref: inspect<3>-Footnote-6612446
Ref: inspect<3>-Footnote-7612489
Ref: inspect<3>-Footnote-8612532
Node: io<3>612575
Ref: whatsnew/3 5 io612675
Ref: 709612675
Ref: io<3>-Footnote-1612973
Node: ipaddress<2>613016
Ref: whatsnew/3 5 ipaddress613113
Ref: 70d613113
Ref: ipaddress<2>-Footnote-1614153
Ref: ipaddress<2>-Footnote-2614196
Node: json<2>614239
Ref: whatsnew/3 5 json614340
Ref: 70e614340
Ref: json<2>-Footnote-1614840
Ref: json<2>-Footnote-2614883
Node: linecache614926
Ref: whatsnew/3 5 linecache615024
Ref: 710615024
Ref: linecache-Footnote-1615434
Node: locale<3>615477
Ref: whatsnew/3 5 locale615578
Ref: 713615578
Ref: locale<3>-Footnote-1616149
Node: logging<4>616192
Ref: whatsnew/3 5 logging616288
Ref: 715616288
Ref: logging<4>-Footnote-1617264
Ref: logging<4>-Footnote-2617307
Node: lzma617350
Ref: whatsnew/3 5 lzma617444
Ref: 71c617444
Ref: lzma-Footnote-1617706
Node: math<4>617749
Ref: whatsnew/3 5 math617851
Ref: 71e617851
Ref: math<4>-Footnote-1618399
Ref: math<4>-Footnote-2618442
Ref: math<4>-Footnote-3618485
Node: multiprocessing<4>618528
Ref: whatsnew/3 5 multiprocessing618634
Ref: 721618634
Ref: multiprocessing<4>-Footnote-1618884
Node: operator618927
Ref: whatsnew/3 5 operator619031
Ref: 723619031
Ref: operator-Footnote-1619436
Ref: operator-Footnote-2619479
Node: os<5>619522
Ref: whatsnew/3 5 os619618
Ref: 728619618
Ref: os<5>-Footnote-1621472
Ref: os<5>-Footnote-2621515
Ref: os<5>-Footnote-3621558
Ref: os<5>-Footnote-4621601
Ref: os<5>-Footnote-5621644
Ref: os<5>-Footnote-6621687
Node: pathlib<4>621730
Ref: whatsnew/3 5 pathlib621827
Ref: 730621827
Ref: pathlib<4>-Footnote-1623310
Ref: pathlib<4>-Footnote-2623353
Ref: pathlib<4>-Footnote-3623396
Ref: pathlib<4>-Footnote-4623439
Ref: pathlib<4>-Footnote-5623482
Node: pickle<3>623525
Ref: whatsnew/3 5 pickle623623
Ref: 739623623
Ref: pickle<3>-Footnote-1623939
Node: poplib623982
Ref: whatsnew/3 5 poplib624075
Ref: 73a624075
Ref: poplib-Footnote-1624317
Ref: poplib-Footnote-2624366
Node: re<4>624409
Ref: whatsnew/3 5 re624504
Ref: 73c624504
Ref: re<4>-Footnote-1625752
Ref: re<4>-Footnote-2625794
Ref: re<4>-Footnote-3625837
Ref: re<4>-Footnote-4625882
Node: readline<2>625925
Ref: whatsnew/3 5 readline626023
Ref: 744626023
Ref: readline<2>-Footnote-1626286
Node: selectors626329
Ref: whatsnew/3 5 selectors626431
Ref: 746626431
Ref: selectors-Footnote-1626653
Node: shutil<2>626696
Ref: whatsnew/3 5 shutil626796
Ref: 747626796
Ref: shutil<2>-Footnote-1627275
Ref: shutil<2>-Footnote-2627318
Node: signal<2>627360
Ref: whatsnew/3 5 signal627456
Ref: 748627456
Ref: signal<2>-Footnote-1627919
Ref: signal<2>-Footnote-2627962
Node: smtpd628005
Ref: whatsnew/3 5 smtpd628099
Ref: 749628099
Ref: smtpd-Footnote-1629783
Ref: smtpd-Footnote-2629826
Ref: smtpd-Footnote-3629875
Ref: smtpd-Footnote-4629918
Ref: smtpd-Footnote-5629967
Ref: smtpd-Footnote-6630010
Node: smtplib630053
Ref: whatsnew/3 5 smtplib630144
Ref: 74a630144
Ref: smtplib-Footnote-1630765
Ref: smtplib-Footnote-2630808
Ref: smtplib-Footnote-3630851
Ref: smtplib-Footnote-4630900
Node: sndhdr630943
Ref: whatsnew/3 5 sndhdr631038
Ref: 74f631038
Ref: sndhdr-Footnote-1631253
Node: socket<5>631296
Ref: whatsnew/3 5 socket631390
Ref: 752631390
Ref: socket<5>-Footnote-1632361
Ref: socket<5>-Footnote-2632404
Ref: socket<5>-Footnote-3632447
Ref: socket<5>-Footnote-4632490
Node: ssl<6>632533
Ref: whatsnew/3 5 ssl632631
Ref: 756632631
Node: 内存 BIO 支持632759
Ref: whatsnew/3 5 memory-bio-support632874
Ref: 757632874
Ref: whatsnew/3 5 whatsnew-sslmemorybio632874
Ref: 641632874
Ref: 内存 BIO 支持-Footnote-1633753
Node: Application-Layer Protocol Negotiation Support633796
Ref: whatsnew/3 5 application-layer-protocol-negotiation-support633933
Ref: 759633933
Ref: Application-Layer Protocol Negotiation Support-Footnote-1634644
Ref: Application-Layer Protocol Negotiation Support-Footnote-2634687
Node: Other Changes634736
Ref: whatsnew/3 5 other-changes634847
Ref: 75d634847
Ref: Other Changes-Footnote-1636440
Ref: Other Changes-Footnote-2636483
Ref: Other Changes-Footnote-3636526
Ref: Other Changes-Footnote-4636569
Ref: Other Changes-Footnote-5636618
Ref: Other Changes-Footnote-6636661
Ref: Other Changes-Footnote-7636704
Ref: Other Changes-Footnote-8636747
Node: sqlite3<3>636790
Ref: whatsnew/3 5 sqlite3636892
Ref: 766636892
Ref: sqlite3<3>-Footnote-1637221
Ref: sqlite3<3>-Footnote-2637264
Node: subprocess<3>637307
Ref: whatsnew/3 5 subprocess637409
Ref: 768637409
Ref: whatsnew/3 5 whatsnew-subprocess637409
Ref: 644637409
Ref: subprocess<3>-Footnote-1638421
Node: sys<5>638464
Ref: whatsnew/3 5 sys638565
Ref: 76a638565
Ref: sys<5>-Footnote-1639215
Ref: sys<5>-Footnote-2639258
Node: sysconfig639301
Ref: whatsnew/3 5 sysconfig639399
Ref: 76d639399
Ref: sysconfig-Footnote-1639632
Node: tarfile<2>639675
Ref: whatsnew/3 5 tarfile639779
Ref: 76e639779
Ref: tarfile<2>-Footnote-1640690
Ref: tarfile<2>-Footnote-2640733
Ref: tarfile<2>-Footnote-3640776
Node: threading<3>640819
Ref: whatsnew/3 5 threading640921
Ref: 774640921
Ref: threading<3>-Footnote-1641173
Node: time<4>641216
Ref: whatsnew/3 5 time641317
Ref: 777641317
Ref: time<4>-Footnote-1641494
Node: timeit<2>641537
Ref: whatsnew/3 5 timeit641636
Ref: 779641636
Ref: timeit<2>-Footnote-1642103
Ref: timeit<2>-Footnote-2642146
Node: tkinter<5>642188
Ref: whatsnew/3 5 tkinter642289
Ref: 77b642289
Ref: tkinter<5>-Footnote-1642621
Node: 回溯<2>642664
Ref: whatsnew/3 5 traceback642764
Ref: 77c642764
Ref: whatsnew/3 5 whatsnew-traceback642764
Ref: 645642764
Ref: 回溯<2>-Footnote-1643339
Ref: 回溯<2>-Footnote-2643382
Ref: 回溯<2>-Footnote-3643425
Node: types<2>643468
Ref: whatsnew/3 5 types643572
Ref: 784643572
Ref: types<2>-Footnote-1644016
Ref: types<2>-Footnote-2644059
Node: unicodedata<4>644102
Ref: whatsnew/3 5 unicodedata644208
Ref: 787644208
Ref: unicodedata<4>-Footnote-1644360
Node: unittest<3>644410
Ref: whatsnew/3 5 unittest644524
Ref: 788644524
Ref: unittest<3>-Footnote-1645318
Ref: unittest<3>-Footnote-2645361
Ref: unittest<3>-Footnote-3645404
Node: unittest mock<3>645447
Ref: whatsnew/3 5 unittest-mock645553
Ref: 78c645553
Ref: unittest mock<3>-Footnote-1646494
Ref: unittest mock<3>-Footnote-2646537
Ref: unittest mock<3>-Footnote-3646580
Ref: unittest mock<3>-Footnote-4646623
Ref: unittest mock<3>-Footnote-5646666
Ref: unittest mock<3>-Footnote-6646709
Node: urllib646752
Ref: whatsnew/3 5 urllib646854
Ref: 792646854
Ref: urllib-Footnote-1648014
Ref: urllib-Footnote-2648057
Ref: urllib-Footnote-3648099
Ref: urllib-Footnote-4648142
Ref: urllib-Footnote-5648185
Ref: urllib-Footnote-6648234
Ref: urllib-Footnote-7648283
Ref: urllib-Footnote-8648332
Node: wsgiref648375
Ref: whatsnew/3 5 wsgiref648470
Ref: 797648470
Ref: wsgiref-Footnote-1648708
Node: xmlrpc<2>648750
Ref: whatsnew/3 5 xmlrpc648846
Ref: 799648846
Ref: xmlrpc<2>-Footnote-1649216
Ref: xmlrpc<2>-Footnote-2649259
Node: xml sax649302
Ref: whatsnew/3 5 xml-sax649401
Ref: 79a649401
Ref: xml sax-Footnote-1649734
Ref: xml sax-Footnote-2649776
Node: zipfile<3>649819
Ref: whatsnew/3 5 zipfile649900
Ref: 79d649900
Ref: zipfile<3>-Footnote-1650240
Ref: zipfile<3>-Footnote-2650283
Node: 其他模块级更改650326
Ref: whatsnew/3 5 other-module-level-changes650464
Ref: 79e650464
Ref: 其他模块级更改-Footnote-1650778
Node: 性能优化<4>650821
Ref: whatsnew/3 5 optimizations650969
Ref: 79f650969
Ref: 性能优化<4>-Footnote-1654020
Ref: 性能优化<4>-Footnote-2654063
Ref: 性能优化<4>-Footnote-3654106
Ref: 性能优化<4>-Footnote-4654149
Ref: 性能优化<4>-Footnote-5654192
Ref: 性能优化<4>-Footnote-6654235
Ref: 性能优化<4>-Footnote-7654278
Ref: 性能优化<4>-Footnote-8654321
Ref: 性能优化<4>-Footnote-9654364
Ref: 性能优化<4>-Footnote-10654407
Ref: 性能优化<4>-Footnote-11654451
Ref: 性能优化<4>-Footnote-12654495
Ref: 性能优化<4>-Footnote-13654539
Ref: 性能优化<4>-Footnote-14654583
Ref: 性能优化<4>-Footnote-15654627
Ref: 性能优化<4>-Footnote-16654671
Ref: 性能优化<4>-Footnote-17654715
Ref: 性能优化<4>-Footnote-18654759
Ref: 性能优化<4>-Footnote-19654803
Ref: 性能优化<4>-Footnote-20654847
Node: 构建和 C API 的改变<3>654891
Ref: whatsnew/3 5 build-and-c-api-changes655027
Ref: 7ad655027
Ref: 构建和 C API 的改变<3>-Footnote-1658559
Ref: 构建和 C API 的改变<3>-Footnote-2658602
Ref: 构建和 C API 的改变<3>-Footnote-3658645
Ref: 构建和 C API 的改变<3>-Footnote-4658688
Ref: 构建和 C API 的改变<3>-Footnote-5658731
Ref: 构建和 C API 的改变<3>-Footnote-6658774
Ref: 构建和 C API 的改变<3>-Footnote-7658823
Ref: 构建和 C API 的改变<3>-Footnote-8658866
Ref: 构建和 C API 的改变<3>-Footnote-9658909
Ref: 构建和 C API 的改变<3>-Footnote-10658958
Node: 弃用<3>658997
Ref: whatsnew/3 5 deprecated659127
Ref: 7b9659127
Node: 新关键字<2>659382
Ref: whatsnew/3 5 new-keywords659481
Ref: 7ba659481
Ref: 新关键字<2>-Footnote-1659751
Node: 已弃用的 Python 行为<3>659800
Ref: whatsnew/3 5 deprecated-python-behavior659932
Ref: 7bb659932
Node: 不支持的操作系统660341
Ref: whatsnew/3 5 unsupported-operating-systems660505
Ref: 7bc660505
Ref: 不支持的操作系统-Footnote-1660728
Node: 已弃用的 Python 模块、函数和方法<3>660777
Ref: whatsnew/3 5 deprecated-python-modules-functions-and-methods660903
Ref: 7bd660903
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-1663821
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-2663864
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-3663906
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-4663949
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-5663992
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-6664035
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-7664078
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-8664121
Node: 移除<2>664164
Ref: whatsnew/3 5 removed664285
Ref: 7c3664285
Node: API 与特性的移除<4>664375
Ref: whatsnew/3 5 api-and-feature-removals664446
Ref: 7c4664446
Ref: API 与特性的移除<4>-Footnote-1665293
Ref: API 与特性的移除<4>-Footnote-2665335
Node: 移植到Python 3 5665378
Ref: whatsnew/3 5 porting-to-python-3-5665518
Ref: 7c5665518
Node: Python 行为的改变<2>665811
Ref: whatsnew/3 5 changes-in-python-behavior665924
Ref: 7c6665924
Node: Python API 的变化<5>666304
Ref: whatsnew/3 5 changes-in-the-python-api666444
Ref: 7c7666444
Ref: Python API 的变化<5>-Footnote-1673345
Ref: Python API 的变化<5>-Footnote-2673394
Ref: Python API 的变化<5>-Footnote-3673437
Ref: Python API 的变化<5>-Footnote-4673480
Ref: Python API 的变化<5>-Footnote-5673523
Ref: Python API 的变化<5>-Footnote-6673566
Ref: Python API 的变化<5>-Footnote-7673609
Ref: Python API 的变化<5>-Footnote-8673652
Ref: Python API 的变化<5>-Footnote-9673695
Ref: Python API 的变化<5>-Footnote-10673738
Ref: Python API 的变化<5>-Footnote-11673782
Ref: Python API 的变化<5>-Footnote-12673826
Ref: Python API 的变化<5>-Footnote-13673869
Ref: Python API 的变化<5>-Footnote-14673919
Ref: Python API 的变化<5>-Footnote-15673969
Ref: Python API 的变化<5>-Footnote-16674013
Ref: Python API 的变化<5>-Footnote-17674057
Ref: Python API 的变化<5>-Footnote-18674101
Node: C API 的变化<4>674144
Ref: whatsnew/3 5 changes-in-the-c-api674250
Ref: 7d2674250
Ref: C API 的变化<4>-Footnote-1675504
Ref: C API 的变化<4>-Footnote-2675547
Ref: C API 的变化<4>-Footnote-3675590
Node: Python 3 5 4 的显著变化675639
Ref: whatsnew/3 5 notable-changes-in-python-3-5-4675761
Ref: 7d7675761
Node: New make regen-all build target<2>675987
Ref: whatsnew/3 5 new-make-regen-all-build-target676132
Ref: 7d8676132
Ref: New make regen-all build target<2>-Footnote-1676923
Ref: New make regen-all build target<2>-Footnote-2676990
Node: Removal of make touch build target<2>677033
Ref: whatsnew/3 5 removal-of-make-touch-build-target677178
Ref: 7d9677178
Ref: Removal of make touch build target<2>-Footnote-1677609
Node: Python 3 4 有什么新变化677652
Ref: whatsnew/3 4 doc677812
Ref: 7da677812
Ref: whatsnew/3 4 what-s-new-in-python-3-4677812
Ref: 7db677812
Ref: Python 3 4 有什么新变化-Footnote-1678506
Ref: Python 3 4 有什么新变化-Footnote-2678566
Node: 摘要 - 发布重点<5>678615
Ref: whatsnew/3 4 summary-release-highlights678729
Ref: 7dc678729
Ref: 摘要 - 发布重点<5>-Footnote-1682976
Ref: 摘要 - 发布重点<5>-Footnote-2683025
Ref: 摘要 - 发布重点<5>-Footnote-3683074
Ref: 摘要 - 发布重点<5>-Footnote-4683117
Ref: 摘要 - 发布重点<5>-Footnote-5683166
Ref: 摘要 - 发布重点<5>-Footnote-6683209
Ref: 摘要 - 发布重点<5>-Footnote-7683258
Ref: 摘要 - 发布重点<5>-Footnote-8683307
Ref: 摘要 - 发布重点<5>-Footnote-9683356
Ref: 摘要 - 发布重点<5>-Footnote-10683405
Ref: 摘要 - 发布重点<5>-Footnote-11683455
Ref: 摘要 - 发布重点<5>-Footnote-12683505
Ref: 摘要 - 发布重点<5>-Footnote-13683555
Ref: 摘要 - 发布重点<5>-Footnote-14683605
Ref: 摘要 - 发布重点<5>-Footnote-15683655
Ref: 摘要 - 发布重点<5>-Footnote-16683698
Ref: 摘要 - 发布重点<5>-Footnote-17683742
Ref: 摘要 - 发布重点<5>-Footnote-18683792
Ref: 摘要 - 发布重点<5>-Footnote-19683842
Ref: 摘要 - 发布重点<5>-Footnote-20683886
Ref: 摘要 - 发布重点<5>-Footnote-21683932
Ref: 摘要 - 发布重点<5>-Footnote-22683982
Ref: 摘要 - 发布重点<5>-Footnote-23684032
Ref: 摘要 - 发布重点<5>-Footnote-24684076
Ref: 摘要 - 发布重点<5>-Footnote-25684126
Node: 新的特性<5>684176
Ref: whatsnew/3 4 new-features684314
Ref: 7f8684314
Node: PEP 453 Explicit Bootstrapping of PIP in Python Installations684804
Ref: whatsnew/3 4 pep-453-explicit-bootstrapping-of-pip-in-python-installations684984
Ref: 7f9684984
Ref: whatsnew/3 4 whatsnew-pep-453684984
Ref: 7dd684984
Node: Bootstrapping pip By Default685187
Ref: whatsnew/3 4 bootstrapping-pip-by-default685334
Ref: 7fa685334
Ref: Bootstrapping pip By Default-Footnote-1688236
Ref: Bootstrapping pip By Default-Footnote-2688285
Node: 文档更改688380
Ref: whatsnew/3 4 documentation-changes688527
Ref: 7fd688527
Ref: 文档更改-Footnote-1689400
Ref: 文档更改-Footnote-2689437
Node: PEP 446 Newly Created File Descriptors Are Non-Inheritable689486
Ref: whatsnew/3 4 pep-446-newly-created-file-descriptors-are-non-inheritable689705
Ref: 802689705
Ref: whatsnew/3 4 whatsnew-pep-446689705
Ref: 7de689705
Ref: PEP 446 Newly Created File Descriptors Are Non-Inheritable-Footnote-1690712
Ref: PEP 446 Newly Created File Descriptors Are Non-Inheritable-Footnote-2690761
Node: Improvements to Codec Handling690810
Ref: whatsnew/3 4 codec-handling-improvements691015
Ref: 7e0691015
Ref: whatsnew/3 4 improvements-to-codec-handling691015
Ref: 80a691015
Ref: Improvements to Codec Handling-Footnote-1695216
Ref: Improvements to Codec Handling-Footnote-2695258
Ref: Improvements to Codec Handling-Footnote-3695301
Ref: Improvements to Codec Handling-Footnote-4695344
Node: PEP 451 A ModuleSpec Type for the Import System695387
Ref: whatsnew/3 4 pep-451-a-modulespec-type-for-the-import-system695561
Ref: 80f695561
Ref: whatsnew/3 4 whatsnew-pep-451695561
Ref: 7e1695561
Ref: PEP 451 A ModuleSpec Type for the Import System-Footnote-1696508
Ref: PEP 451 A ModuleSpec Type for the Import System-Footnote-2696557
Node: 其他语言特性修改<5>696637
Ref: whatsnew/3 4 other-language-changes696772
Ref: 811696772
Ref: 其他语言特性修改<5>-Footnote-1699390
Ref: 其他语言特性修改<5>-Footnote-2699433
Ref: 其他语言特性修改<5>-Footnote-3699476
Ref: 其他语言特性修改<5>-Footnote-4699519
Ref: 其他语言特性修改<5>-Footnote-5699564
Ref: 其他语言特性修改<5>-Footnote-6699607
Ref: 其他语言特性修改<5>-Footnote-7699650
Ref: 其他语言特性修改<5>-Footnote-8699693
Ref: 其他语言特性修改<5>-Footnote-9699736
Ref: 其他语言特性修改<5>-Footnote-10699779
Ref: 其他语言特性修改<5>-Footnote-11699823
Ref: 其他语言特性修改<5>-Footnote-12699873
Node: 新增模块<5>699917
Ref: whatsnew/3 4 new-modules700049
Ref: 816700049
Node: asyncio<6>700258
Ref: whatsnew/3 4 asyncio700338
Ref: 817700338
Ref: whatsnew/3 4 whatsnew-asyncio700338
Ref: 7e3700338
Ref: asyncio<6>-Footnote-1700920
Ref: asyncio<6>-Footnote-2700969
Node: ensurepip701018
Ref: whatsnew/3 4 ensurepip701114
Ref: 818701114
Ref: whatsnew/3 4 whatsnew-ensurepip701114
Ref: 7e4701114
Ref: ensurepip-Footnote-1702386
Node: enum<5>702435
Ref: whatsnew/3 4 enum702531
Ref: 819702531
Ref: whatsnew/3 4 whatsnew-enum702531
Ref: 7e5702531
Ref: enum<5>-Footnote-1703096
Ref: enum<5>-Footnote-2703145
Node: pathlib<5>703194
Ref: whatsnew/3 4 pathlib703293
Ref: 81a703293
Ref: whatsnew/3 4 whatsnew-pathlib703293
Ref: 7e6703293
Ref: pathlib<5>-Footnote-1703897
Node: selectors<2>703946
Ref: whatsnew/3 4 selectors704051
Ref: 81b704051
Ref: whatsnew/3 4 whatsnew-selectors704051
Ref: 7e7704051
Ref: selectors<2>-Footnote-1704309
Node: statistics<3>704358
Ref: whatsnew/3 4 statistics704467
Ref: 81c704467
Ref: whatsnew/3 4 whatsnew-statistics704467
Ref: 7e8704467
Ref: statistics<3>-Footnote-1704922
Ref: statistics<3>-Footnote-2704971
Node: tracemalloc<3>705020
Ref: whatsnew/3 4 tracemalloc705108
Ref: 81d705108
Ref: whatsnew/3 4 whatsnew-tracemalloc705108
Ref: 7e9705108
Ref: tracemalloc<3>-Footnote-1705760
Ref: tracemalloc<3>-Footnote-2705809
Node: 改进的模块<5>705858
Ref: whatsnew/3 4 improved-modules706005
Ref: 81e706005
Node: abc707304
Ref: whatsnew/3 4 abc707378
Ref: 81f707378
Ref: abc-Footnote-1707899
Ref: abc-Footnote-2707942
Node: aifc<2>707985
Ref: whatsnew/3 4 aifc708079
Ref: 823708079
Ref: aifc<2>-Footnote-1708717
Ref: aifc<2>-Footnote-2708760
Ref: aifc<2>-Footnote-3708803
Node: argparse<3>708845
Ref: whatsnew/3 4 argparse708943
Ref: 828708943
Ref: argparse<3>-Footnote-1709189
Node: audioop709232
Ref: whatsnew/3 4 audioop709329
Ref: 82a709329
Ref: audioop-Footnote-1709868
Ref: audioop-Footnote-2709911
Ref: audioop-Footnote-3709954
Node: base64709997
Ref: whatsnew/3 4 base64710097
Ref: 82c710097
Ref: base64-Footnote-1710928
Ref: base64-Footnote-2710971
Node: collections<6>711014
Ref: whatsnew/3 4 collections711115
Ref: 831711115
Ref: collections<6>-Footnote-1711445
Node: colorsys711488
Ref: whatsnew/3 4 colorsys711596
Ref: 833711596
Ref: colorsys-Footnote-1711964
Node: contextlib<4>712007
Ref: whatsnew/3 4 contextlib712107
Ref: 834712107
Ref: contextlib<4>-Footnote-1713292
Ref: contextlib<4>-Footnote-2713335
Ref: contextlib<4>-Footnote-3713378
Node: dbm<5>713421
Ref: whatsnew/3 4 dbm713519
Ref: 838713519
Ref: dbm<5>-Footnote-1713866
Node: dis<2>713909
Ref: whatsnew/3 4 dis714004
Ref: 83a714004
Ref: dis<2>-Footnote-1716603
Ref: dis<2>-Footnote-2716646
Ref: dis<2>-Footnote-3716689
Node: doctest<2>716732
Ref: whatsnew/3 4 doctest716829
Ref: 844716829
Ref: doctest<2>-Footnote-1717597
Ref: doctest<2>-Footnote-2717640
Ref: doctest<2>-Footnote-3717683
Node: email<3>717725
Ref: whatsnew/3 4 email717823
Ref: 847717823
Ref: whatsnew/3 4 whatsnew-email-contentmanager719071
Ref: 7ed719071
Ref: email<3>-Footnote-1719998
Ref: email<3>-Footnote-2720041
Ref: email<3>-Footnote-3720084
Ref: email<3>-Footnote-4720127
Node: filecmp720170
Ref: whatsnew/3 4 filecmp720270
Ref: 84f720270
Ref: filecmp-Footnote-1721016
Ref: filecmp-Footnote-2721059
Node: functools<4>721102
Ref: whatsnew/3 4 functools721199
Ref: 853721199
Ref: whatsnew/3 4 whatsnew-singledispatch721646
Ref: 7ea721646
Ref: functools<4>-Footnote-1722594
Ref: functools<4>-Footnote-2722636
Ref: functools<4>-Footnote-3722685
Ref: functools<4>-Footnote-4722728
Node: gc<3>722771
Ref: whatsnew/3 4 gc722868
Ref: 856722868
Ref: gc<3>-Footnote-1723134
Node: glob<2>723177
Ref: whatsnew/3 4 glob723272
Ref: 858723272
Ref: glob<2>-Footnote-1723576
Node: hashlib<2>723618
Ref: whatsnew/3 4 hashlib723715
Ref: 85a723715
Ref: hashlib<2>-Footnote-1724348
Ref: hashlib<2>-Footnote-2724393
Ref: hashlib<2>-Footnote-3724436
Node: hmac<2>724479
Ref: whatsnew/3 4 hmac724573
Ref: 85c724573
Ref: hmac<2>-Footnote-1725599
Ref: hmac<2>-Footnote-2725642
Ref: hmac<2>-Footnote-3725685
Ref: hmac<2>-Footnote-4725734
Node: html725777
Ref: whatsnew/3 4 html725868
Ref: 862725868
Ref: html-Footnote-1726625
Ref: html-Footnote-2726667
Ref: html-Footnote-3726710
Node: http<2>726753
Ref: whatsnew/3 4 http726856
Ref: 864726856
Ref: http<2>-Footnote-1727497
Ref: http<2>-Footnote-2727540
Node: idlelib 与 IDLE<4>727583
Ref: whatsnew/3 4 idlelib-and-idle727694
Ref: 867727694
Node: importlib<6>728087
Ref: whatsnew/3 4 importlib728201
Ref: 868728201
Ref: importlib<6>-Footnote-1730202
Ref: importlib<6>-Footnote-2730245
Ref: importlib<6>-Footnote-3730288
Ref: importlib<6>-Footnote-4730331
Ref: importlib<6>-Footnote-5730374
Ref: importlib<6>-Footnote-6730417
Ref: importlib<6>-Footnote-7730460
Node: inspect<4>730503
Ref: whatsnew/3 4 inspect730610
Ref: 870730610
Ref: inspect<4>-Footnote-1732324
Ref: inspect<4>-Footnote-2732367
Ref: inspect<4>-Footnote-3732410
Ref: inspect<4>-Footnote-4732453
Ref: inspect<4>-Footnote-5732496
Ref: inspect<4>-Footnote-6732539
Node: ipaddress<3>732582
Ref: whatsnew/3 4 ipaddress732687
Ref: 874732687
Ref: ipaddress<3>-Footnote-1733213
Node: logging<5>733256
Ref: whatsnew/3 4 logging733358
Ref: 876733358
Ref: logging<5>-Footnote-1734488
Ref: logging<5>-Footnote-2734530
Ref: logging<5>-Footnote-3734573
Node: marshal734616
Ref: whatsnew/3 4 marshal734713
Ref: 87c734713
Ref: whatsnew/3 4 whatsnew-marshal-3734713
Ref: 7e2734713
Ref: marshal-Footnote-1735388
Ref: marshal-Footnote-2735431
Node: mmap<2>735474
Ref: whatsnew/3 4 mmap735579
Ref: 87d735579
Ref: mmap<2>-Footnote-1735742
Node: multiprocessing<5>735784
Ref: whatsnew/3 4 multiprocessing735893
Ref: 87e735893
Ref: whatsnew/3 4 whatsnew-multiprocessing-no-fork735944
Ref: 7ec735944
Ref: multiprocessing<5>-Footnote-1737756
Ref: multiprocessing<5>-Footnote-2737798
Ref: multiprocessing<5>-Footnote-3737841
Ref: multiprocessing<5>-Footnote-4737883
Node: operator<2>737926
Ref: whatsnew/3 4 operator738033
Ref: 885738033
Ref: operator<2>-Footnote-1738584
Ref: operator<2>-Footnote-2738633
Ref: operator<2>-Footnote-3738676
Node: os<6>738719
Ref: whatsnew/3 4 os738814
Ref: 887738814
Ref: os<6>-Footnote-1740259
Ref: os<6>-Footnote-2740302
Ref: os<6>-Footnote-3740345
Ref: os<6>-Footnote-4740387
Node: pdb<3>740430
Ref: whatsnew/3 4 pdb740523
Ref: 88e740523
Ref: pdb<3>-Footnote-1741517
Ref: pdb<3>-Footnote-2741560
Node: pickle<4>741603
Ref: whatsnew/3 4 pickle741702
Ref: 891741702
Ref: whatsnew/3 4 whatsnew-protocol-4741702
Ref: 7eb741702
Ref: pickle<4>-Footnote-1742282
Node: plistlib<2>742331
Ref: whatsnew/3 4 plistlib742433
Ref: 893742433
Ref: plistlib<2>-Footnote-1742967
Node: poplib<2>743010
Ref: whatsnew/3 4 poplib743112
Ref: 89a743112
Ref: poplib<2>-Footnote-1743500
Node: pprint<2>743542
Ref: whatsnew/3 4 pprint743636
Ref: 89d743636
Ref: pprint<2>-Footnote-1744254
Ref: pprint<2>-Footnote-2744297
Node: pty744340
Ref: whatsnew/3 4 pty744433
Ref: 8a0744433
Node: pydoc<3>744624
Ref: whatsnew/3 4 pydoc744713
Ref: 8a2744713
Ref: pydoc<3>-Footnote-1745768
Ref: pydoc<3>-Footnote-2745811
Node: re<5>745854
Ref: whatsnew/3 4 re745948
Ref: 8a3745948
Ref: re<5>-Footnote-1746689
Ref: re<5>-Footnote-2746732
Ref: re<5>-Footnote-3746775
Node: resource746818
Ref: whatsnew/3 4 resource746910
Ref: 8a7746910
Ref: resource-Footnote-1747761
Ref: resource-Footnote-2747804
Ref: resource-Footnote-3747847
Node: select747890
Ref: whatsnew/3 4 select747983
Ref: 8b1747983
Ref: select-Footnote-1748490
Ref: select-Footnote-2748533
Node: shelve748576
Ref: whatsnew/3 4 shelve748670
Ref: 8b8748670
Ref: shelve-Footnote-1748940
Node: shutil<3>748983
Ref: whatsnew/3 4 shutil749079
Ref: 8ba749079
Ref: shutil<3>-Footnote-1749450
Node: smtpd<2>749495
Ref: whatsnew/3 4 smtpd749595
Ref: 8bd749595
Ref: smtpd<2>-Footnote-1749971
Node: smtplib<2>750014
Ref: whatsnew/3 4 smtplib750114
Ref: 8bf750114
Ref: smtplib<2>-Footnote-1750474
Node: socket<6>750516
Ref: whatsnew/3 4 socket750618
Ref: 8c1750618
Ref: socket<6>-Footnote-1751395
Ref: socket<6>-Footnote-2751438
Node: sqlite3<4>751480
Ref: whatsnew/3 4 sqlite3751578
Ref: 8c5751578
Ref: sqlite3<4>-Footnote-1751867
Ref: sqlite3<4>-Footnote-2751907
Node: ssl<7>751950
Ref: whatsnew/3 4 ssl752043
Ref: 8c6752043
Ref: whatsnew/3 4 whatsnew-tls-11-12752070
Ref: 7f0752070
Ref: whatsnew/3 4 whatsnew34-sslcontext752340
Ref: 7f3752340
Ref: whatsnew/3 4 whatsnew34-win-cert-store755010
Ref: 7f1755010
Ref: whatsnew/3 4 whatsnew34-sni755264
Ref: 7f2755264
Ref: ssl<7>-Footnote-1755713
Ref: ssl<7>-Footnote-2755756
Ref: ssl<7>-Footnote-3755799
Ref: ssl<7>-Footnote-4755842
Ref: ssl<7>-Footnote-5755885
Ref: ssl<7>-Footnote-6755928
Ref: ssl<7>-Footnote-7755970
Ref: ssl<7>-Footnote-8756013
Ref: ssl<7>-Footnote-9756056
Ref: ssl<7>-Footnote-10756098
Node: stat756142
Ref: whatsnew/3 4 stat756234
Ref: 8da756234
Ref: stat-Footnote-1756705
Ref: stat-Footnote-2756748
Node: struct<2>756791
Ref: whatsnew/3 4 struct756890
Ref: 8df756890
Ref: struct<2>-Footnote-1757220
Node: subprocess<4>757263
Ref: whatsnew/3 4 subprocess757366
Ref: 8e2757366
Ref: subprocess<4>-Footnote-1757810
Ref: subprocess<4>-Footnote-2757853
Node: sunau<2>757896
Ref: whatsnew/3 4 sunau757996
Ref: 8e5757996
Ref: sunau<2>-Footnote-1758801
Ref: sunau<2>-Footnote-2758844
Ref: sunau<2>-Footnote-3758887
Ref: sunau<2>-Footnote-4758930
Node: sys<6>758972
Ref: whatsnew/3 4 sys759069
Ref: 8e9759069
Ref: sys<6>-Footnote-1760347
Ref: sys<6>-Footnote-2760390
Node: tarfile<3>760432
Ref: whatsnew/3 4 tarfile760529
Ref: 8ef760529
Ref: tarfile<3>-Footnote-1760839
Node: textwrap760882
Ref: whatsnew/3 4 textwrap760985
Ref: 8f1760985
Ref: textwrap-Footnote-1761684
Ref: textwrap-Footnote-2761727
Node: threading<4>761770
Ref: whatsnew/3 4 threading761872
Ref: 8f6761872
Ref: threading<4>-Footnote-1762215
Node: 回溯<3>762258
Ref: whatsnew/3 4 traceback762360
Ref: 8f8762360
Ref: 回溯<3>-Footnote-1762665
Node: types<3>762710
Ref: whatsnew/3 4 types762809
Ref: 8fa762809
Ref: types<3>-Footnote-1763313
Node: urllib<2>763356
Ref: whatsnew/3 4 urllib763457
Ref: 8fc763457
Ref: urllib<2>-Footnote-1764771
Ref: urllib<2>-Footnote-2764814
Ref: urllib<2>-Footnote-3764857
Ref: urllib<2>-Footnote-4764900
Ref: urllib<2>-Footnote-5764943
Ref: urllib<2>-Footnote-6764986
Node: unittest<4>765029
Ref: whatsnew/3 4 unittest765129
Ref: 906765129
Ref: unittest<4>-Footnote-1768279
Ref: unittest<4>-Footnote-2768322
Ref: unittest<4>-Footnote-3768365
Ref: unittest<4>-Footnote-4768408
Ref: unittest<4>-Footnote-5768451
Ref: unittest<4>-Footnote-6768494
Ref: unittest<4>-Footnote-7768537
Ref: unittest<4>-Footnote-8768580
Ref: unittest<4>-Footnote-9768623
Node: venv<4>768666
Ref: whatsnew/3 4 venv768764
Ref: 90f768764
Ref: venv<4>-Footnote-1769320
Ref: venv<4>-Footnote-2769363
Ref: venv<4>-Footnote-3769406
Node: wave<2>769455
Ref: whatsnew/3 4 wave769552
Ref: 912769552
Ref: wave<2>-Footnote-1770187
Ref: wave<2>-Footnote-2770230
Ref: wave<2>-Footnote-3770273
Ref: wave<2>-Footnote-4770315
Node: weakref<2>770357
Ref: whatsnew/3 4 weakref770459
Ref: 916770459
Ref: weakref<2>-Footnote-1771078
Ref: weakref<2>-Footnote-2771121
Ref: weakref<2>-Footnote-3771164
Node: xml etree<2>771207
Ref: whatsnew/3 4 xml-etree771312
Ref: 91a771312
Ref: xml etree<2>-Footnote-1772045
Ref: xml etree<2>-Footnote-2772088
Node: zipfile<4>772131
Ref: whatsnew/3 4 zipfile772217
Ref: 921772217
Ref: zipfile<4>-Footnote-1772746
Ref: zipfile<4>-Footnote-2772789
Node: CPython Implementation Changes772832
Ref: whatsnew/3 4 cpython-implementation-changes772973
Ref: 924772973
Node: PEP 445 Customization of CPython Memory Allocators773491
Ref: whatsnew/3 4 pep-445-customization-of-cpython-memory-allocators773649
Ref: 925773649
Ref: whatsnew/3 4 whatsnew-pep-445773649
Ref: 7f6773649
Ref: PEP 445 Customization of CPython Memory Allocators-Footnote-1774033
Ref: PEP 445 Customization of CPython Memory Allocators-Footnote-2774082
Node: PEP 442 Safe Object Finalization774131
Ref: whatsnew/3 4 pep-442-safe-object-finalization774347
Ref: 926774347
Ref: whatsnew/3 4 whatsnew-pep-442774347
Ref: 7f5774347
Ref: PEP 442 Safe Object Finalization-Footnote-1775200
Ref: PEP 442 Safe Object Finalization-Footnote-2775249
Node: PEP 456 Secure and Interchangeable Hash Algorithm775298
Ref: whatsnew/3 4 pep-456-secure-and-interchangeable-hash-algorithm775487
Ref: 928775487
Ref: whatsnew/3 4 whatsnew-pep-456775487
Ref: 7ee775487
Ref: PEP 456 Secure and Interchangeable Hash Algorithm-Footnote-1776433
Ref: PEP 456 Secure and Interchangeable Hash Algorithm-Footnote-2776482
Node: PEP 436 Argument Clinic776525
Ref: whatsnew/3 4 pep-436-argument-clinic776711
Ref: 92a776711
Ref: whatsnew/3 4 whatsnew-pep-436776711
Ref: 7f7776711
Ref: PEP 436 Argument Clinic-Footnote-1777801
Ref: PEP 436 Argument Clinic-Footnote-2777850
Node: Other Build and C API Changes777899
Ref: whatsnew/3 4 other-build-and-c-api-changes778051
Ref: 92b778051
Ref: Other Build and C API Changes-Footnote-1780135
Ref: Other Build and C API Changes-Footnote-2780178
Ref: Other Build and C API Changes-Footnote-3780221
Ref: Other Build and C API Changes-Footnote-4780266
Ref: Other Build and C API Changes-Footnote-5780308
Ref: Other Build and C API Changes-Footnote-6780351
Ref: Other Build and C API Changes-Footnote-7780424
Ref: Other Build and C API Changes-Footnote-8780488
Ref: Other Build and C API Changes-Footnote-9780531
Node: 其他改进<2>780574
Ref: whatsnew/3 4 other-improvements780728
Ref: 931780728
Ref: whatsnew/3 4 other-improvements-3-4780728
Ref: 932780728
Ref: whatsnew/3 4 whatsnew-isolated-mode780767
Ref: 7df780767
Ref: 其他改进<2>-Footnote-1784888
Ref: 其他改进<2>-Footnote-2784931
Ref: 其他改进<2>-Footnote-3784973
Ref: 其他改进<2>-Footnote-4785016
Ref: 其他改进<2>-Footnote-5785059
Ref: 其他改进<2>-Footnote-6785102
Ref: 其他改进<2>-Footnote-7785145
Ref: 其他改进<2>-Footnote-8785240
Ref: 其他改进<2>-Footnote-9785293
Ref: 其他改进<2>-Footnote-10785336
Ref: 其他改进<2>-Footnote-11785380
Ref: 其他改进<2>-Footnote-12785424
Ref: 其他改进<2>-Footnote-13785474
Ref: 其他改进<2>-Footnote-14785518
Ref: 其他改进<2>-Footnote-15785562
Ref: 其他改进<2>-Footnote-16785606
Ref: 其他改进<2>-Footnote-17785650
Ref: 其他改进<2>-Footnote-18785700
Ref: 其他改进<2>-Footnote-19785744
Ref: 其他改进<2>-Footnote-20785788
Ref: 其他改进<2>-Footnote-21785832
Node: Significant Optimizations785876
Ref: whatsnew/3 4 significant-optimizations785992
Ref: 938785992
Ref: Significant Optimizations-Footnote-1788795
Ref: Significant Optimizations-Footnote-2788838
Ref: Significant Optimizations-Footnote-3788881
Ref: Significant Optimizations-Footnote-4788924
Ref: Significant Optimizations-Footnote-5788967
Ref: Significant Optimizations-Footnote-6789010
Ref: Significant Optimizations-Footnote-7789053
Ref: Significant Optimizations-Footnote-8789095
Ref: Significant Optimizations-Footnote-9789138
Ref: Significant Optimizations-Footnote-10789181
Ref: Significant Optimizations-Footnote-11789225
Ref: Significant Optimizations-Footnote-12789269
Ref: Significant Optimizations-Footnote-13789313
Node: 弃用<4>789357
Ref: whatsnew/3 4 deprecated789489
Ref: 93d789489
Ref: whatsnew/3 4 deprecated-3-4789489
Ref: 810789489
Node: Deprecations in the Python API789919
Ref: whatsnew/3 4 deprecations-in-the-python-api790023
Ref: 93e790023
Node: Deprecated Features793785
Ref: whatsnew/3 4 deprecated-features793889
Ref: 951793889
Ref: Deprecated Features-Footnote-1794268
Ref: Deprecated Features-Footnote-2794311
Node: 移除<3>794354
Ref: whatsnew/3 4 removed794476
Ref: 953794476
Node: 不再支持的操作系统794614
Ref: whatsnew/3 4 operating-systems-no-longer-supported794721
Ref: 954794721
Ref: 不再支持的操作系统-Footnote-1795098
Ref: 不再支持的操作系统-Footnote-2795141
Ref: 不再支持的操作系统-Footnote-3795184
Node: API 与特性的移除<5>795227
Ref: whatsnew/3 4 api-and-feature-removals795356
Ref: 955795356
Ref: API 与特性的移除<5>-Footnote-1797792
Ref: API 与特性的移除<5>-Footnote-2797828
Ref: API 与特性的移除<5>-Footnote-3797871
Ref: API 与特性的移除<5>-Footnote-4797914
Ref: API 与特性的移除<5>-Footnote-5797957
Ref: API 与特性的移除<5>-Footnote-6798000
Ref: API 与特性的移除<5>-Footnote-7798042
Node: Code Cleanups798085
Ref: whatsnew/3 4 code-cleanups798178
Ref: 958798178
Ref: Code Cleanups-Footnote-1798841
Node: 移植到 Python 3 4798884
Ref: whatsnew/3 4 porting-to-python-3-4799012
Ref: 959799012
Node: 'python' 命令行为的变化<2>799325
Ref: whatsnew/3 4 changes-in-python-command-behavior799447
Ref: 95a799447
Ref: 'python' 命令行为的变化<2>-Footnote-1800533
Node: Python API 的变化<6>800576
Ref: whatsnew/3 4 changes-in-the-python-api800725
Ref: 95c800725
Ref: Python API 的变化<6>-Footnote-1814094
Ref: Python API 的变化<6>-Footnote-2814137
Ref: Python API 的变化<6>-Footnote-3814180
Ref: Python API 的变化<6>-Footnote-4814223
Ref: Python API 的变化<6>-Footnote-5814266
Ref: Python API 的变化<6>-Footnote-6814309
Ref: Python API 的变化<6>-Footnote-7814352
Ref: Python API 的变化<6>-Footnote-8814395
Ref: Python API 的变化<6>-Footnote-9814437
Ref: Python API 的变化<6>-Footnote-10814480
Ref: Python API 的变化<6>-Footnote-11814524
Ref: Python API 的变化<6>-Footnote-12814568
Ref: Python API 的变化<6>-Footnote-13814612
Ref: Python API 的变化<6>-Footnote-14814656
Ref: Python API 的变化<6>-Footnote-15814700
Ref: Python API 的变化<6>-Footnote-16814744
Ref: Python API 的变化<6>-Footnote-17814788
Ref: Python API 的变化<6>-Footnote-18814832
Ref: Python API 的变化<6>-Footnote-19814876
Ref: Python API 的变化<6>-Footnote-20814920
Ref: Python API 的变化<6>-Footnote-21814964
Ref: Python API 的变化<6>-Footnote-22815008
Ref: Python API 的变化<6>-Footnote-23815052
Ref: Python API 的变化<6>-Footnote-24815095
Node: C API 的变化<5>815139
Ref: whatsnew/3 4 changes-in-the-c-api815246
Ref: 96e815246
Ref: C API 的变化<5>-Footnote-1816993
Ref: C API 的变化<5>-Footnote-2817036
Node: 3 4 3 的变化817079
Ref: whatsnew/3 4 changed-in-3-4-3817189
Ref: 97a817189
Node: PEP 476 Enabling certificate verification by default for stdlib http clients817400
Ref: whatsnew/3 4 pep-476817528
Ref: 97b817528
Ref: whatsnew/3 4 pep-476-enabling-certificate-verification-by-default-for-stdlib-http-clients817528
Ref: 97c817528
Node: Python 3 3 有什么新变化818527
Ref: whatsnew/3 3 doc818687
Ref: 97d818687
Ref: whatsnew/3 3 what-s-new-in-python-3-3818687
Ref: 97e818687
Ref: Python 3 3 有什么新变化-Footnote-1820432
Ref: Python 3 3 有什么新变化-Footnote-2820492
Node: 摘要 - 发布重点<6>820541
Ref: whatsnew/3 3 summary-release-highlights820660
Ref: 97f820660
Node: PEP 405 虚拟环境821921
Ref: whatsnew/3 3 pep-405822078
Ref: 981822078
Ref: whatsnew/3 3 pep-405-virtual-environments822078
Ref: 989822078
Ref: PEP 405 虚拟环境-Footnote-1823023
Node: PEP 420 隐式命名空间包823072
Ref: whatsnew/3 3 pep-420-implicit-namespace-packages823259
Ref: 98a823259
Ref: PEP 420 隐式命名空间包-Footnote-1823728
Ref: PEP 420 隐式命名空间包-Footnote-2823777
Node: PEP 3118 新的内存视图实现和缓冲协议文档823826
Ref: whatsnew/3 3 pep-3118-new-memoryview-implementation-and-buffer-protocol-documentation824025
Ref: 98b824025
Ref: whatsnew/3 3 pep-3118-update824025
Ref: 98c824025
Ref: PEP 3118 新的内存视图实现和缓冲协议文档-Footnote-1825108
Node: 相关特性825157
Ref: whatsnew/3 3 features825280
Ref: 98d825280
Ref: 相关特性-Footnote-1826084
Node: API changes826127
Ref: whatsnew/3 3 api-changes826250
Ref: 98e826250
Ref: API changes-Footnote-1827258
Ref: API changes-Footnote-2827301
Node: PEP 393 灵活的字符串表示827350
Ref: whatsnew/3 3 pep-393827562
Ref: 984827562
Ref: whatsnew/3 3 pep-393-flexible-string-representation827562
Ref: 991827562
Ref: PEP 393 灵活的字符串表示-Footnote-1828601
Node: Functionality828650
Ref: whatsnew/3 3 functionality828771
Ref: 992828771
Ref: Functionality-Footnote-1830218
Ref: Functionality-Footnote-2830267
Node: Performance and resource usage830310
Ref: whatsnew/3 3 performance-and-resource-usage830431
Ref: 994830431
Ref: Performance and resource usage-Footnote-1831646
Node: PEP 397 适用于Windows的Python启动器831695
Ref: whatsnew/3 3 pep-397831900
Ref: 995831900
Ref: whatsnew/3 3 pep-397-python-launcher-for-windows831900
Ref: 996831900
Ref: PEP 397 适用于Windows的Python启动器-Footnote-1833441
Ref: PEP 397 适用于Windows的Python启动器-Footnote-2833483
Node: PEP 3151 重写 OS 和 IO 异常的层次结构833532
Ref: whatsnew/3 3 pep-3151833743
Ref: 982833743
Ref: whatsnew/3 3 pep-3151-reworking-the-os-and-io-exception-hierarchy833743
Ref: 999833743
Ref: PEP 3151 重写 OS 和 IO 异常的层次结构-Footnote-1836274
Node: PEP 380 委托给子生成器的语法836323
Ref: whatsnew/3 3 pep-380836521
Ref: 980836521
Ref: whatsnew/3 3 pep-380-syntax-for-delegating-to-a-subgenerator836521
Ref: 9a9836521
Ref: PEP 380 委托给子生成器的语法-Footnote-1838912
Node: PEP 409 清除异常上下文838961
Ref: whatsnew/3 3 pep-409-suppressing-exception-context839142
Ref: 9ab839142
Ref: PEP 409 清除异常上下文-Footnote-1841188
Node: PEP 414 显式的Unicode文本841237
Ref: whatsnew/3 3 pep-414-explicit-unicode-literals841416
Ref: 9ac841416
Ref: PEP 414 显式的Unicode文本-Footnote-1842104
Node: PEP 3155 类和函数的限定名称842153
Ref: whatsnew/3 3 pep-3155-qualified-name-for-classes-and-functions842333
Ref: 9ad842333
Ref: PEP 3155 类和函数的限定名称-Footnote-1843859
Node: PEP 412 Key-Sharing Dictionary843908
Ref: whatsnew/3 3 pep-412844084
Ref: 985844084
Ref: whatsnew/3 3 pep-412-key-sharing-dictionary844084
Ref: 9ae844084
Ref: PEP 412 Key-Sharing Dictionary-Footnote-1844592
Node: PEP 362 函数签名对象844641
Ref: whatsnew/3 3 pep-362-function-signature-object844814
Ref: 9af844814
Ref: PEP 362 函数签名对象-Footnote-1845675
Node: PEP 421 添加 sys implementation845724
Ref: whatsnew/3 3 pep-421-adding-sys-implementation845914
Ref: 9b1845914
Ref: PEP 421 添加 sys implementation-Footnote-1847126
Node: SimpleNamespace847175
Ref: whatsnew/3 3 simplenamespace847260
Ref: 9b3847260
Ref: SimpleNamespace-Footnote-1847864
Node: Using importlib as the Implementation of Import847913
Ref: whatsnew/3 3 importlib848104
Ref: 983848104
Ref: whatsnew/3 3 using-importlib-as-the-implementation-of-import848104
Ref: 9b5848104
Ref: Using importlib as the Implementation of Import-Footnote-1849381
Ref: Using importlib as the Implementation of Import-Footnote-2849423
Ref: Using importlib as the Implementation of Import-Footnote-3849466
Ref: Using importlib as the Implementation of Import-Footnote-4849509
Ref: Using importlib as the Implementation of Import-Footnote-5849552
Node: New APIs849601
Ref: whatsnew/3 3 new-apis849717
Ref: 9b8849717
Node: Visible Changes851559
Ref: whatsnew/3 3 visible-changes851675
Ref: 9c2851675
Ref: Visible Changes-Footnote-1853529
Ref: Visible Changes-Footnote-2853578
Node: 其他语言特性修改<6>853627
Ref: whatsnew/3 3 other-language-changes853812
Ref: 9c4853812
Ref: 其他语言特性修改<6>-Footnote-1855779
Ref: 其他语言特性修改<6>-Footnote-2855822
Ref: 其他语言特性修改<6>-Footnote-3855865
Ref: 其他语言特性修改<6>-Footnote-4855908
Ref: 其他语言特性修改<6>-Footnote-5855951
Ref: 其他语言特性修改<6>-Footnote-6855994
Ref: 其他语言特性修改<6>-Footnote-7856037
Ref: 其他语言特性修改<6>-Footnote-8856080
Node: A Finer-Grained Import Lock856123
Ref: whatsnew/3 3 a-finer-grained-import-lock856288
Ref: 9c8856288
Ref: A Finer-Grained Import Lock-Footnote-1857037
Node: Builtin functions and types857079
Ref: whatsnew/3 3 builtin-functions-and-types857232
Ref: 9ca857232
Ref: Builtin functions and types-Footnote-1858465
Node: 新增模块<6>858507
Ref: whatsnew/3 3 new-modules858651
Ref: 9ce858651
Node: faulthandler<3>858775
Ref: whatsnew/3 3 faulthandler858863
Ref: 9cf858863
Node: ipaddress<4>859788
Ref: whatsnew/3 3 ipaddress859892
Ref: 9d1859892
Ref: ipaddress<4>-Footnote-1860242
Node: lzma<2>860284
Ref: whatsnew/3 3 lzma860364
Ref: 9d2860364
Ref: lzma<2>-Footnote-1860682
Node: 改进的模块<6>860724
Ref: whatsnew/3 3 improved-modules860856
Ref: 9d3860856
Node: abc<2>862119
Ref: whatsnew/3 3 abc862197
Ref: 9d4862197
Ref: abc<2>-Footnote-1863237
Ref: abc<2>-Footnote-2863280
Node: array<2>863323
Ref: whatsnew/3 3 array863419
Ref: 9da863419
Ref: array<2>-Footnote-1863663
Node: base64<2>863708
Ref: whatsnew/3 3 base64863809
Ref: 9db863809
Ref: base64<2>-Footnote-1864107
Node: binascii<3>864150
Ref: whatsnew/3 3 binascii864249
Ref: 9dc864249
Ref: binascii<3>-Footnote-1864503
Node: bz2<2>864546
Ref: whatsnew/3 3 bz2864645
Ref: 9dd864645
Ref: bz2<2>-Footnote-1865628
Ref: bz2<2>-Footnote-2865670
Node: 编码器865712
Ref: whatsnew/3 3 codecs865814
Ref: 9e0865814
Ref: 编码器-Footnote-1867137
Ref: 编码器-Footnote-2867180
Ref: 编码器-Footnote-3867223
Node: collections<7>867266
Ref: whatsnew/3 3 collections867375
Ref: 9e1867375
Ref: collections<7>-Footnote-1868140
Ref: collections<7>-Footnote-2868183
Ref: collections<7>-Footnote-3868226
Ref: collections<7>-Footnote-4868269
Node: contextlib<5>868312
Ref: whatsnew/3 3 contextlib868420
Ref: 9e3868420
Ref: contextlib<5>-Footnote-1869014
Node: crypt<2>869057
Ref: whatsnew/3 3 crypt869160
Ref: 9e4869160
Ref: crypt<2>-Footnote-1869373
Node: curses<3>869416
Ref: whatsnew/3 3 curses869517
Ref: 9e5869517
Ref: curses<3>-Footnote-1870381
Node: datetime<4>870423
Ref: whatsnew/3 3 datetime870526
Ref: 9e9870526
Ref: datetime<4>-Footnote-1871244
Node: decimal<3>871287
Ref: whatsnew/3 3 decimal871389
Ref: 9eb871389
Ref: whatsnew/3 3 new-decimal871389
Ref: 986871389
Ref: decimal<3>-Footnote-1873111
Node: 相关特性<2>873153
Ref: whatsnew/3 3 id1873238
Ref: 9ec873238
Node: API changes<2>873614
Ref: whatsnew/3 3 id2873699
Ref: 9ef873699
Node: email<4>876462
Ref: whatsnew/3 3 email876559
Ref: 9fa876559
Ref: whatsnew/3 3 new-email876559
Ref: 987876559
Node: Policy Framework876688
Ref: whatsnew/3 3 policy-framework876796
Ref: 9fb876796
Node: Provisional Policy with New Header API879804
Ref: whatsnew/3 3 provisional-policy-with-new-header-api879938
Ref: 9ff879938
Node: Other API Changes884574
Ref: whatsnew/3 3 other-api-changes884683
Ref: a03884683
Node: ftplib885574
Ref: whatsnew/3 3 ftplib885673
Ref: a0a885673
Ref: ftplib-Footnote-1886580
Ref: ftplib-Footnote-2886622
Ref: ftplib-Footnote-3886665
Node: functools<5>886708
Ref: whatsnew/3 3 functools886804
Ref: a10886804
Ref: functools<5>-Footnote-1887150
Node: gc<4>887193
Ref: whatsnew/3 3 gc887290
Ref: a11887290
Node: hmac<3>887462
Ref: whatsnew/3 3 hmac887554
Ref: a13887554
Ref: hmac<3>-Footnote-1887818
Node: http<3>887861
Ref: whatsnew/3 3 http887955
Ref: a15887955
Ref: http<3>-Footnote-1888633
Ref: http<3>-Footnote-2888675
Ref: http<3>-Footnote-3888718
Node: html<2>888761
Ref: whatsnew/3 3 html888858
Ref: a1c888858
Ref: html<2>-Footnote-1889856
Ref: html<2>-Footnote-2889899
Ref: html<2>-Footnote-3889942
Ref: html<2>-Footnote-4889985
Ref: html<2>-Footnote-5890028
Ref: html<2>-Footnote-6890071
Ref: html<2>-Footnote-7890116
Ref: html<2>-Footnote-8890160
Ref: html<2>-Footnote-9890203
Ref: html<2>-Footnote-10890246
Ref: html<2>-Footnote-11890292
Ref: html<2>-Footnote-12890337
Ref: html<2>-Footnote-13890381
Ref: html<2>-Footnote-14890425
Ref: html<2>-Footnote-15890468
Ref: html<2>-Footnote-16890512
Node: imaplib<2>890556
Ref: whatsnew/3 3 imaplib890656
Ref: a1e890656
Ref: imaplib<2>-Footnote-1890902
Node: inspect<5>890944
Ref: whatsnew/3 3 inspect891042
Ref: a20891042
Ref: inspect<5>-Footnote-1891764
Ref: inspect<5>-Footnote-2891807
Node: io<4>891850
Ref: whatsnew/3 3 io891950
Ref: a23891950
Ref: io<4>-Footnote-1892603
Node: itertools<3>892646
Ref: whatsnew/3 3 itertools892746
Ref: a24892746
Node: logging<6>892902
Ref: whatsnew/3 3 logging893004
Ref: a25893004
Node: math<5>893455
Ref: whatsnew/3 3 math893552
Ref: a27893552
Ref: math<5>-Footnote-1893775
Node: mmap<3>893818
Ref: whatsnew/3 3 mmap893923
Ref: a29893923
Ref: mmap<3>-Footnote-1894258
Node: multiprocessing<6>894301
Ref: whatsnew/3 3 multiprocessing894406
Ref: a2b894406
Ref: multiprocessing<6>-Footnote-1895556
Ref: multiprocessing<6>-Footnote-2895599
Ref: multiprocessing<6>-Footnote-3895641
Ref: multiprocessing<6>-Footnote-4895683
Node: nntplib895726
Ref: whatsnew/3 3 nntplib895829
Ref: a33895829
Ref: nntplib-Footnote-1896398
Node: os<7>896440
Ref: whatsnew/3 3 os896531
Ref: a35896531
Ref: os<7>-Footnote-1903901
Ref: os<7>-Footnote-2903944
Ref: os<7>-Footnote-3903986
Ref: os<7>-Footnote-4904029
Ref: os<7>-Footnote-5904072
Ref: os<7>-Footnote-6904115
Ref: os<7>-Footnote-7904157
Ref: os<7>-Footnote-8904200
Ref: os<7>-Footnote-9904243
Ref: os<7>-Footnote-10904286
Ref: os<7>-Footnote-11904329
Node: pdb<4>904373
Ref: whatsnew/3 3 pdb904466
Ref: a6f904466
Ref: pdb<4>-Footnote-1904751
Node: pickle<5>904794
Ref: whatsnew/3 3 pickle904890
Ref: a70904890
Ref: pickle<5>-Footnote-1905164
Node: pydoc<4>905207
Ref: whatsnew/3 3 pydoc905302
Ref: a72905302
Node: re<6>905499
Ref: whatsnew/3 3 re905590
Ref: a73905590
Ref: re<6>-Footnote-1905790
Node: sched905832
Ref: whatsnew/3 3 sched905924
Ref: a74905924
Ref: sched-Footnote-1907056
Ref: sched-Footnote-2907099
Ref: sched-Footnote-3907141
Ref: sched-Footnote-4907184
Ref: sched-Footnote-5907227
Node: select<2>907270
Ref: whatsnew/3 3 select907365
Ref: a79907365
Ref: select<2>-Footnote-1907628
Node: shlex<3>907670
Ref: whatsnew/3 3 shlex907769
Ref: a7a907769
Node: shutil<4>908080
Ref: whatsnew/3 3 shutil908179
Ref: a7c908179
Ref: shutil<4>-Footnote-1910046
Ref: shutil<4>-Footnote-2910089
Ref: shutil<4>-Footnote-3910132
Ref: shutil<4>-Footnote-4910175
Ref: shutil<4>-Footnote-5910218
Ref: shutil<4>-Footnote-6910261
Ref: shutil<4>-Footnote-7910304
Ref: shutil<4>-Footnote-8910346
Node: signal<3>910388
Ref: whatsnew/3 3 signal910487
Ref: a80910487
Ref: signal<3>-Footnote-1911552
Node: smtpd<3>911594
Ref: whatsnew/3 3 smtpd911694
Ref: a87911694
Ref: smtpd<3>-Footnote-1912180
Ref: smtpd<3>-Footnote-2912229
Ref: smtpd<3>-Footnote-3912278
Node: smtplib<3>912320
Ref: whatsnew/3 3 smtplib912420
Ref: a88912420
Ref: smtplib<3>-Footnote-1913171
Ref: smtplib<3>-Footnote-2913214
Ref: smtplib<3>-Footnote-3913257
Node: socket<7>913299
Ref: whatsnew/3 3 socket913406
Ref: a8d913406
Ref: socket<7>-Footnote-1914648
Ref: socket<7>-Footnote-2914690
Ref: socket<7>-Footnote-3914733
Ref: socket<7>-Footnote-4914776
Node: socketserver<3>914819
Ref: whatsnew/3 3 socketserver914926
Ref: a90914926
Ref: socketserver<3>-Footnote-1915299
Node: sqlite3<5>915342
Ref: whatsnew/3 3 sqlite3915446
Ref: a94915446
Ref: sqlite3<5>-Footnote-1915721
Node: ssl<8>915764
Ref: whatsnew/3 3 ssl915860
Ref: a96915860
Ref: ssl<8>-Footnote-1918083
Ref: ssl<8>-Footnote-2918126
Ref: ssl<8>-Footnote-3918169
Ref: ssl<8>-Footnote-4918212
Ref: ssl<8>-Footnote-5918255
Ref: ssl<8>-Footnote-6918298
Ref: ssl<8>-Footnote-7918341
Ref: ssl<8>-Footnote-8918384
Ref: ssl<8>-Footnote-9918427
Ref: ssl<8>-Footnote-10918470
Ref: ssl<8>-Footnote-11918514
Node: stat<2>918558
Ref: whatsnew/3 3 stat918653
Ref: aa4918653
Ref: stat<2>-Footnote-1918954
Node: struct<3>918997
Ref: whatsnew/3 3 struct919099
Ref: aa6919099
Ref: struct<3>-Footnote-1919346
Node: subprocess<5>919388
Ref: whatsnew/3 3 subprocess919489
Ref: aa7919489
Ref: subprocess<5>-Footnote-1919824
Ref: subprocess<5>-Footnote-2919866
Node: sys<7>919908
Ref: whatsnew/3 3 sys920010
Ref: aa9920010
Ref: sys<7>-Footnote-1920228
Node: tarfile<4>920271
Ref: whatsnew/3 3 tarfile920368
Ref: aac920368
Ref: tarfile<4>-Footnote-1920576
Node: tempfile920618
Ref: whatsnew/3 3 tempfile920720
Ref: aad920720
Ref: tempfile-Footnote-1920947
Node: textwrap<2>920989
Ref: whatsnew/3 3 textwrap921093
Ref: aaf921093
Ref: textwrap<2>-Footnote-1921338
Node: threading<5>921381
Ref: whatsnew/3 3 threading921484
Ref: ab1921484
Ref: threading<5>-Footnote-1922415
Ref: threading<5>-Footnote-2922458
Node: time<5>922500
Ref: whatsnew/3 3 time922600
Ref: ab8922600
Ref: time<5>-Footnote-1923567
Ref: time<5>-Footnote-2923616
Node: types<4>923659
Ref: whatsnew/3 3 types923758
Ref: abd923758
Ref: types<4>-Footnote-1924094
Ref: types<4>-Footnote-2924137
Ref: types<4>-Footnote-3924186
Node: unittest<5>924229
Ref: whatsnew/3 3 unittest924330
Ref: ac1924330
Ref: unittest<5>-Footnote-1924743
Node: urllib<3>924786
Ref: whatsnew/3 3 urllib924889
Ref: ac8924889
Ref: urllib<3>-Footnote-1925241
Node: webbrowser925286
Ref: whatsnew/3 3 webbrowser925399
Ref: aca925399
Ref: webbrowser-Footnote-1925937
Ref: webbrowser-Footnote-2925980
Node: xml etree ElementTree926023
Ref: whatsnew/3 3 xml-etree-elementtree926134
Ref: acb926134
Node: zlib<2>926653
Ref: whatsnew/3 3 zlib926745
Ref: acd926745
Ref: zlib<2>-Footnote-1927217
Ref: zlib<2>-Footnote-2927260
Node: 性能优化<5>927303
Ref: whatsnew/3 3 optimizations927448
Ref: ad0927448
Ref: 性能优化<5>-Footnote-1928253
Ref: 性能优化<5>-Footnote-2928302
Ref: 性能优化<5>-Footnote-3928345
Ref: 性能优化<5>-Footnote-4928388
Node: 构建和 C API 的改变<4>928431
Ref: whatsnew/3 3 build-and-c-api-changes928567
Ref: 98f928567
Ref: 构建和 C API 的改变<4>-Footnote-1930427
Ref: 构建和 C API 的改变<4>-Footnote-2930476
Ref: 构建和 C API 的改变<4>-Footnote-3930525
Node: 弃用<5>930568
Ref: whatsnew/3 3 deprecated930709
Ref: aef930709
Node: 不支持的操作系统<2>930997
Ref: whatsnew/3 3 unsupported-operating-systems931126
Ref: af0931126
Node: 已弃用的 Python 模块、函数和方法<4>931440
Ref: whatsnew/3 3 deprecated-python-modules-functions-and-methods931615
Ref: af1931615
Ref: 已弃用的 Python 模块、函数和方法<4>-Footnote-1933920
Ref: 已弃用的 Python 模块、函数和方法<4>-Footnote-2933962
Ref: 已弃用的 Python 模块、函数和方法<4>-Footnote-3934011
Ref: 已弃用的 Python 模块、函数和方法<4>-Footnote-4934054
Ref: 已弃用的 Python 模块、函数和方法<4>-Footnote-5934097
Node: 已弃用的 C API 函数和类型<3>934140
Ref: whatsnew/3 3 deprecated-functions-and-types-of-the-c-api934303
Ref: af5934303
Ref: 已弃用的 C API 函数和类型<3>-Footnote-1937481
Node: 弃用的功能937530
Ref: whatsnew/3 3 deprecated-features937637
Ref: b18937637
Node: 移植到 Python 3 3937847
Ref: whatsnew/3 3 porting-to-python-3-3937951
Ref: b19937951
Node: Porting Python code938206
Ref: whatsnew/3 3 porting-python-code938305
Ref: 9b7938305
Ref: whatsnew/3 3 portingpythoncode938305
Ref: b1a938305
Ref: Porting Python code-Footnote-1945333
Ref: Porting Python code-Footnote-2945376
Ref: Porting Python code-Footnote-3945419
Ref: Porting Python code-Footnote-4945462
Ref: Porting Python code-Footnote-5945511
Ref: Porting Python code-Footnote-6945560
Ref: Porting Python code-Footnote-7945602
Ref: Porting Python code-Footnote-8945647
Ref: Porting Python code-Footnote-9945690
Ref: Porting Python code-Footnote-10945732
Node: Porting C code945776
Ref: whatsnew/3 3 porting-c-code945905
Ref: 990945905
Ref: Porting C code-Footnote-1947397
Node: Building C extensions947446
Ref: whatsnew/3 3 building-c-extensions947583
Ref: b2a947583
Ref: Building C extensions-Footnote-1948181
Node: Command Line Switch Changes948224
Ref: whatsnew/3 3 command-line-switch-changes948338
Ref: b2b948338
Ref: Command Line Switch Changes-Footnote-1948906
Ref: Command Line Switch Changes-Footnote-2948949
Node: Python 3 2 有什么新变化948992
Ref: whatsnew/3 2 doc949152
Ref: b2d949152
Ref: whatsnew/3 2 what-s-new-in-python-3-2949152
Ref: b2e949152
Ref: Python 3 2 有什么新变化-Footnote-1950357
Ref: Python 3 2 有什么新变化-Footnote-2950456
Node: PEP 384 定义稳定的ABI950505
Ref: whatsnew/3 2 pep-384-defining-a-stable-abi950644
Ref: b2f950644
Ref: PEP 384 定义稳定的ABI-Footnote-1951714
Node: PEP 389 Argparse 命令行解析模块951763
Ref: whatsnew/3 2 pep-389-argparse-command-line-parsing-module951946
Ref: b30951946
Ref: PEP 389 Argparse 命令行解析模块-Footnote-1956041
Node: PEP 391 基于字典的日志配置956090
Ref: whatsnew/3 2 pep-391-dictionary-based-configuration-for-logging956281
Ref: b32956281
Ref: PEP 391 基于字典的日志配置-Footnote-1958511
Node: PEP 3148 concurrent futures 模块958560
Ref: whatsnew/3 2 pep-3148-the-concurrent-futures-module958738
Ref: b34958738
Ref: PEP 3148 concurrent futures 模块-Footnote-1961402
Node: PEP 3147 PYC 仓库目录961451
Ref: whatsnew/3 2 pep-3147-pyc-repository-directories961630
Ref: b39961630
Ref: PEP 3147 PYC 仓库目录-Footnote-1964635
Node: PEP 3149 ABI Version Tagged so Files964684
Ref: whatsnew/3 2 pep-3149-abi-version-tagged-so-files964875
Ref: b3c964875
Ref: PEP 3149 ABI Version Tagged so Files-Footnote-1966106
Node: PEP 3333 Python Web服务器网关接口v1 0 1966155
Ref: whatsnew/3 2 pep-3333-python-web-server-gateway-interface-v1-0-1966348
Ref: b3d966348
Ref: PEP 3333 Python Web服务器网关接口v1 0 1-Footnote-1968681
Ref: PEP 3333 Python Web服务器网关接口v1 0 1-Footnote-2968730
Ref: PEP 3333 Python Web服务器网关接口v1 0 1-Footnote-3968779
Node: 其他语言特性修改<7>968828
Ref: whatsnew/3 2 other-language-changes969018
Ref: b40969018
Ref: 其他语言特性修改<7>-Footnote-1978541
Ref: 其他语言特性修改<7>-Footnote-2978583
Ref: 其他语言特性修改<7>-Footnote-3978625
Ref: 其他语言特性修改<7>-Footnote-4978670
Ref: 其他语言特性修改<7>-Footnote-5978712
Ref: 其他语言特性修改<7>-Footnote-6978754
Ref: 其他语言特性修改<7>-Footnote-7978796
Ref: 其他语言特性修改<7>-Footnote-8978838
Ref: 其他语言特性修改<7>-Footnote-9978880
Ref: 其他语言特性修改<7>-Footnote-10978922
Ref: 其他语言特性修改<7>-Footnote-11978966
Ref: 其他语言特性修改<7>-Footnote-12979011
Ref: 其他语言特性修改<7>-Footnote-13979054
Ref: 其他语言特性修改<7>-Footnote-14979097
Ref: 其他语言特性修改<7>-Footnote-15979141
Ref: 其他语言特性修改<7>-Footnote-16979185
Node: 新增，改进和弃用的模块979228
Ref: whatsnew/3 2 new-improved-and-deprecated-modules979381
Ref: b4d979381
Node: email<5>981388
Ref: whatsnew/3 2 email981486
Ref: b4e981486
Ref: email<5>-Footnote-1983460
Ref: email<5>-Footnote-2983509
Ref: email<5>-Footnote-3983551
Node: elementtree983594
Ref: whatsnew/3 2 elementtree983713
Ref: b56983713
Ref: elementtree-Footnote-1985192
Ref: elementtree-Footnote-2985248
Node: functools<6>985290
Ref: whatsnew/3 2 functools985413
Ref: b5d985413
Ref: functools<6>-Footnote-1988872
Ref: functools<6>-Footnote-2988924
Ref: functools<6>-Footnote-3988976
Ref: functools<6>-Footnote-4989019
Ref: functools<6>-Footnote-5989062
Ref: functools<6>-Footnote-6989104
Ref: functools<6>-Footnote-7989146
Ref: functools<6>-Footnote-8989188
Node: itertools<4>989240
Ref: whatsnew/3 2 itertools989366
Ref: b5f989366
Node: collections<8>990056
Ref: whatsnew/3 2 collections990182
Ref: b61990182
Ref: collections<8>-Footnote-1992430
Ref: collections<8>-Footnote-2992490
Node: threading<6>992537
Ref: whatsnew/3 2 threading992668
Ref: b66992668
Ref: threading<6>-Footnote-1995429
Ref: threading<6>-Footnote-2995490
Ref: threading<6>-Footnote-3995588
Ref: threading<6>-Footnote-4995660
Node: datetime 和 time995702
Ref: whatsnew/3 2 datetime-and-time995826
Ref: b6a995826
Ref: datetime 和 time-Footnote-1998613
Ref: datetime 和 time-Footnote-2998658
Ref: datetime 和 time-Footnote-3998700
Ref: datetime 和 time-Footnote-4998742
Ref: datetime 和 time-Footnote-5998784
Ref: datetime 和 time-Footnote-6998829
Ref: datetime 和 time-Footnote-7998871
Node: math<6>998914
Ref: whatsnew/3 2 math999032
Ref: b6e999032
Ref: math<6>-Footnote-11000908
Node: abc<3>1000961
Ref: whatsnew/3 2 abc1001067
Ref: b731001067
Ref: abc<3>-Footnote-11001689
Node: io<5>1001731
Ref: whatsnew/3 2 io1001837
Ref: b741001837
Ref: io<5>-Footnote-11003008
Node: reprlib1003050
Ref: whatsnew/3 2 reprlib1003160
Ref: b761003160
Ref: reprlib-Footnote-11004151
Ref: reprlib-Footnote-21004193
Node: logging<7>1004235
Ref: whatsnew/3 2 logging1004346
Ref: b791004346
Node: csv<3>1006185
Ref: whatsnew/3 2 csv1006302
Ref: b801006302
Ref: csv<3>-Footnote-11007163
Ref: csv<3>-Footnote-21007205
Node: contextlib<6>1007250
Ref: whatsnew/3 2 contextlib1007378
Ref: b841007378
Ref: contextlib<6>-Footnote-11009597
Node: decimal and fractions1009639
Ref: whatsnew/3 2 decimal-and-fractions1009764
Ref: b871009764
Ref: decimal and fractions-Footnote-11012187
Ref: decimal and fractions-Footnote-21012229
Ref: decimal and fractions-Footnote-31012271
Ref: decimal and fractions-Footnote-41012313
Ref: decimal and fractions-Footnote-51012355
Ref: decimal and fractions-Footnote-61012397
Node: ftp1012439
Ref: whatsnew/3 2 ftp1012556
Ref: b8b1012556
Ref: ftp-Footnote-11013920
Ref: ftp-Footnote-21014009
Ref: ftp-Footnote-31014051
Node: popen1014093
Ref: whatsnew/3 2 popen1014198
Ref: b8c1014198
Ref: popen-Footnote-11014510
Ref: popen-Footnote-21014552
Node: select<3>1014595
Ref: whatsnew/3 2 select1014713
Ref: b8d1014713
Ref: select<3>-Footnote-11015144
Node: gzip 和 zipfile1015186
Ref: whatsnew/3 2 gzip-and-zipfile1015309
Ref: b8f1015309
Ref: gzip 和 zipfile-Footnote-11016880
Ref: gzip 和 zipfile-Footnote-21016922
Ref: gzip 和 zipfile-Footnote-31016964
Ref: gzip 和 zipfile-Footnote-41017009
Ref: gzip 和 zipfile-Footnote-51017051
Ref: gzip 和 zipfile-Footnote-61017093
Node: tarfile<5>1017135
Ref: whatsnew/3 2 tarfile1017259
Ref: b931017259
Ref: tarfile<5>-Footnote-11018830
Node: hashlib<3>1018872
Ref: whatsnew/3 2 hashlib1018986
Ref: b961018986
Ref: hashlib<3>-Footnote-11019749
Node: ast<3>1019791
Ref: whatsnew/3 2 ast1019900
Ref: b971019900
Node: os<8>1020838
Ref: whatsnew/3 2 os1020946
Ref: b991020946
Node: shutil<5>1021717
Ref: whatsnew/3 2 shutil1021829
Ref: b9d1021829
Node: sqlite3<6>1024000
Ref: whatsnew/3 2 sqlite31024114
Ref: ba01024114
Ref: sqlite3<6>-Footnote-11024767
Node: html<3>1024809
Ref: whatsnew/3 2 html1024923
Ref: ba31024923
Node: socket<8>1025209
Ref: whatsnew/3 2 socket1025319
Ref: ba41025319
Ref: socket<8>-Footnote-11025961
Ref: socket<8>-Footnote-21026003
Node: ssl<9>1026045
Ref: whatsnew/3 2 ssl1026152
Ref: ba71026152
Ref: ssl<9>-Footnote-11028251
Ref: ssl<9>-Footnote-21028300
Ref: ssl<9>-Footnote-31028385
Ref: ssl<9>-Footnote-41028427
Ref: ssl<9>-Footnote-51028469
Ref: ssl<9>-Footnote-61028511
Ref: ssl<9>-Footnote-71028553
Ref: ssl<9>-Footnote-81028595
Ref: ssl<9>-Footnote-91028637
Node: nntp1028679
Ref: whatsnew/3 2 nntp1028789
Ref: bac1028789
Ref: nntp-Footnote-11029378
Ref: nntp-Footnote-21029420
Node: certificates1029462
Ref: whatsnew/3 2 certificates1029576
Ref: baf1029576
Ref: certificates-Footnote-11029971
Node: imaplib<3>1030013
Ref: whatsnew/3 2 imaplib1030137
Ref: bb11030137
Ref: imaplib<3>-Footnote-11030416
Node: http client<4>1030458
Ref: whatsnew/3 2 http-client1030581
Ref: bb31030581
Ref: http client<4>-Footnote-11032003
Node: unittest<6>1032046
Ref: whatsnew/3 2 unittest1032168
Ref: bb61032168
Ref: unittest<6>-Footnote-11036956
Ref: unittest<6>-Footnote-21036999
Ref: unittest<6>-Footnote-31037041
Node: random<2>1037083
Ref: whatsnew/3 2 random1037200
Ref: bc21037200
Ref: random<2>-Footnote-11037870
Node: poplib<3>1037912
Ref: whatsnew/3 2 poplib1038029
Ref: bc81038029
Ref: poplib<3>-Footnote-11038389
Node: asyncore<2>1038431
Ref: whatsnew/3 2 asyncore1038550
Ref: bca1038550
Ref: asyncore<2>-Footnote-11039034
Node: tempfile<2>1039076
Ref: whatsnew/3 2 tempfile1039196
Ref: bcf1039196
Ref: tempfile<2>-Footnote-11039611
Node: inspect<6>1039653
Ref: whatsnew/3 2 inspect1039770
Ref: bd11039770
Ref: inspect<6>-Footnote-11041135
Node: pydoc<5>1041178
Ref: whatsnew/3 2 pydoc1041290
Ref: bd41041290
Ref: pydoc<5>-Footnote-11041615
Node: dis<3>1041657
Ref: whatsnew/3 2 dis1041765
Ref: bd51041765
Ref: dis<3>-Footnote-11043919
Node: dbm<6>1043961
Ref: whatsnew/3 2 dbm1044070
Ref: bd71044070
Ref: dbm<6>-Footnote-11044265
Node: ctypes<2>1044307
Ref: whatsnew/3 2 ctypes1044417
Ref: bd81044417
Node: site<2>1044533
Ref: whatsnew/3 2 site1044649
Ref: bda1044649
Ref: site<2>-Footnote-11045884
Node: sysconfig<2>1045926
Ref: whatsnew/3 2 sysconfig1046039
Ref: bde1046039
Node: pdb<5>1048251
Ref: whatsnew/3 2 pdb1048372
Ref: be21048372
Node: configparser<2>1049271
Ref: whatsnew/3 2 configparser1049395
Ref: be31049395
Node: urllib parse<3>1052259
Ref: whatsnew/3 2 urllib-parse1052384
Ref: be51052384
Ref: urllib parse<3>-Footnote-11054388
Ref: urllib parse<3>-Footnote-21054431
Ref: urllib parse<3>-Footnote-31054480
Ref: urllib parse<3>-Footnote-41054522
Ref: urllib parse<3>-Footnote-51054564
Node: mailbox1054606
Ref: whatsnew/3 2 mailbox1054726
Ref: be91054726
Ref: mailbox-Footnote-11056298
Node: turtledemo1056340
Ref: whatsnew/3 2 turtledemo1056436
Ref: bf01056436
Ref: turtledemo-Footnote-11056871
Node: 多线程1056914
Ref: whatsnew/3 2 multi-threading1057055
Ref: bf11057055
Ref: 多线程-Footnote-11058671
Ref: 多线程-Footnote-21058750
Ref: 多线程-Footnote-31058792
Ref: 多线程-Footnote-41058836
Node: 性能优化<6>1058878
Ref: whatsnew/3 2 optimizations1058993
Ref: bf51058993
Ref: 性能优化<6>-Footnote-11062448
Ref: 性能优化<6>-Footnote-21062490
Ref: 性能优化<6>-Footnote-31062532
Ref: 性能优化<6>-Footnote-41062574
Ref: 性能优化<6>-Footnote-51062620
Ref: 性能优化<6>-Footnote-61062662
Ref: 性能优化<6>-Footnote-71062704
Ref: 性能优化<6>-Footnote-81062747
Ref: 性能优化<6>-Footnote-91062789
Ref: 性能优化<6>-Footnote-101062831
Ref: 性能优化<6>-Footnote-111062874
Ref: 性能优化<6>-Footnote-121062917
Ref: 性能优化<6>-Footnote-131062960
Ref: 性能优化<6>-Footnote-141063006
Ref: 性能优化<6>-Footnote-151063049
Ref: 性能优化<6>-Footnote-161063093
Node: Unicode1063136
Ref: whatsnew/3 2 unicode1063254
Ref: bf81063254
Ref: Unicode-Footnote-11063804
Ref: Unicode-Footnote-21063854
Ref: Unicode-Footnote-31063898
Node: 编解码器1063969
Ref: whatsnew/3 2 codecs1064078
Ref: bf91064078
Ref: 编解码器-Footnote-11065015
Node: 文档1065060
Ref: whatsnew/3 2 documentation1065166
Ref: bfa1065166
Ref: 文档-Footnote-11066789
Ref: 文档-Footnote-21066857
Ref: 文档-Footnote-31066933
Ref: 文档-Footnote-41066975
Node: IDLE1067017
Ref: whatsnew/3 2 idle1067120
Ref: bfe1067120
Ref: IDLE-Footnote-11067520
Ref: IDLE-Footnote-21067562
Node: 代码库1067604
Ref: whatsnew/3 2 code-repository1067729
Ref: bff1067729
Ref: 代码库-Footnote-11068320
Ref: 代码库-Footnote-21068359
Ref: 代码库-Footnote-31068408
Ref: 代码库-Footnote-41068462
Node: 构建和 C API 的改变<5>1068506
Ref: whatsnew/3 2 build-and-c-api-changes1068647
Ref: c001068647
Ref: 构建和 C API 的改变<5>-Footnote-11072798
Ref: 构建和 C API 的改变<5>-Footnote-21072841
Ref: 构建和 C API 的改变<5>-Footnote-31072883
Ref: 构建和 C API 的改变<5>-Footnote-41072925
Ref: 构建和 C API 的改变<5>-Footnote-51072967
Ref: 构建和 C API 的改变<5>-Footnote-61073009
Ref: 构建和 C API 的改变<5>-Footnote-71073051
Ref: 构建和 C API 的改变<5>-Footnote-81073093
Ref: 构建和 C API 的改变<5>-Footnote-91073135
Ref: 构建和 C API 的改变<5>-Footnote-101073177
Ref: 构建和 C API 的改变<5>-Footnote-111073220
Ref: 构建和 C API 的改变<5>-Footnote-121073263
Ref: 构建和 C API 的改变<5>-Footnote-131073306
Ref: 构建和 C API 的改变<5>-Footnote-141073368
Ref: 构建和 C API 的改变<5>-Footnote-151073448
Node: 移植到 Python 3 21073505
Ref: whatsnew/3 2 porting-to-python-3-21073628
Ref: c091073628
Ref: 移植到 Python 3 2-Footnote-11080464
Ref: 移植到 Python 3 2-Footnote-21080506
Ref: 移植到 Python 3 2-Footnote-31080548
Ref: 移植到 Python 3 2-Footnote-41080593
Ref: 移植到 Python 3 2-Footnote-51080636
Ref: 移植到 Python 3 2-Footnote-61080679
Ref: 移植到 Python 3 2-Footnote-71080722
Node: Python 3 1 有什么新变化1080764
Ref: whatsnew/3 1 doc1080924
Ref: c1b1080924
Ref: whatsnew/3 1 what-s-new-in-python-3-11080924
Ref: c1c1080924
Node: PEP 372 有序字典1081520
Ref: whatsnew/3 1 pep-372-ordered-dictionaries1081656
Ref: c1d1081656
Ref: PEP 372 有序字典-Footnote-11083159
Ref: PEP 372 有序字典-Footnote-21083186
Node: PEP 378 千位分隔符的格式说明符1083235
Ref: whatsnew/3 1 pep-378-format-specifier-for-thousands-separator1083407
Ref: c1e1083407
Ref: PEP 378 千位分隔符的格式说明符-Footnote-11084605
Node: 其他语言特性修改<8>1084654
Ref: whatsnew/3 1 other-language-changes1084842
Ref: c1f1084842
Ref: 其他语言特性修改<8>-Footnote-11089638
Ref: 其他语言特性修改<8>-Footnote-21089683
Ref: 其他语言特性修改<8>-Footnote-31089725
Ref: 其他语言特性修改<8>-Footnote-41089767
Ref: 其他语言特性修改<8>-Footnote-51089809
Ref: 其他语言特性修改<8>-Footnote-61089854
Ref: 其他语言特性修改<8>-Footnote-71089896
Node: 新增，改进和弃用的模块<2>1089938
Ref: whatsnew/3 1 new-improved-and-deprecated-modules1090100
Ref: c201090100
Ref: 新增，改进和弃用的模块<2>-Footnote-11098692
Ref: 新增，改进和弃用的模块<2>-Footnote-21098737
Ref: 新增，改进和弃用的模块<2>-Footnote-31098779
Ref: 新增，改进和弃用的模块<2>-Footnote-41098821
Ref: 新增，改进和弃用的模块<2>-Footnote-51098863
Ref: 新增，改进和弃用的模块<2>-Footnote-61098905
Ref: 新增，改进和弃用的模块<2>-Footnote-71098954
Ref: 新增，改进和弃用的模块<2>-Footnote-81098996
Ref: 新增，改进和弃用的模块<2>-Footnote-91099038
Ref: 新增，改进和弃用的模块<2>-Footnote-101099080
Ref: 新增，改进和弃用的模块<2>-Footnote-111099123
Ref: 新增，改进和弃用的模块<2>-Footnote-121099166
Ref: 新增，改进和弃用的模块<2>-Footnote-131099209
Node: 性能优化<7>1099252
Ref: whatsnew/3 1 optimizations1099394
Ref: c261099394
Ref: 性能优化<7>-Footnote-11101583
Ref: 性能优化<7>-Footnote-21101632
Ref: 性能优化<7>-Footnote-31101674
Ref: 性能优化<7>-Footnote-41101716
Ref: 性能优化<7>-Footnote-51101758
Ref: 性能优化<7>-Footnote-61101783
Ref: 性能优化<7>-Footnote-71101825
Node: IDLE<2>1101867
Ref: whatsnew/3 1 idle1102001
Ref: c271102001
Ref: IDLE<2>-Footnote-11102224
Node: 构建和 C API 的改变<6>1102266
Ref: whatsnew/3 1 build-and-c-api-changes1102405
Ref: c281102405
Ref: 构建和 C API 的改变<6>-Footnote-11104648
Ref: 构建和 C API 的改变<6>-Footnote-21104690
Ref: 构建和 C API 的改变<6>-Footnote-31104732
Ref: 构建和 C API 的改变<6>-Footnote-41104774
Ref: 构建和 C API 的改变<6>-Footnote-51104816
Node: 移植到 Python 3 11104858
Ref: whatsnew/3 1 porting-to-python-3-11104981
Ref: c2c1104981
Node: Python 3 0 有什么新变化1106106
Ref: whatsnew/3 0 doc1106266
Ref: c2d1106266
Ref: whatsnew/3 0 what-s-new-in-python-3-01106266
Ref: c2e1106266
Node: 常见的绊脚石1108063
Ref: whatsnew/3 0 common-stumbling-blocks1108182
Ref: c2f1108182
Node: Print Is A Function1108532
Ref: whatsnew/3 0 print-is-a-function1108651
Ref: c301108651
Ref: Print Is A Function-Footnote-11110332
Node: Views And Iterators Instead Of Lists1110381
Ref: whatsnew/3 0 views-and-iterators-instead-of-lists1110529
Ref: c311110529
Node: Ordering Comparisons1112365
Ref: whatsnew/3 0 ordering-comparisons1112500
Ref: c3b1112500
Node: 整数1113947
Ref: whatsnew/3 0 integers1114086
Ref: c3d1114086
Ref: 整数-Footnote-11115298
Ref: 整数-Footnote-21115347
Node: Text Vs Data Instead Of Unicode Vs 8-bit1115396
Ref: whatsnew/3 0 text-vs-data-instead-of-unicode-vs-8-bit1115506
Ref: c3e1115506
Ref: Text Vs Data Instead Of Unicode Vs 8-bit-Footnote-11122087
Ref: Text Vs Data Instead Of Unicode Vs 8-bit-Footnote-21122136
Ref: Text Vs Data Instead Of Unicode Vs 8-bit-Footnote-31122185
Node: Overview Of Syntax Changes1122234
Ref: whatsnew/3 0 overview-of-syntax-changes1122399
Ref: c451122399
Node: 新语法1122610
Ref: whatsnew/3 0 new-syntax1122706
Ref: c461122706
Ref: 新语法-Footnote-11125247
Ref: 新语法-Footnote-21125296
Ref: 新语法-Footnote-31125345
Ref: 新语法-Footnote-41125394
Ref: 新语法-Footnote-51125443
Node: 修改的语法1125492
Ref: whatsnew/3 0 changed-syntax1125612
Ref: c491125612
Ref: 修改的语法-Footnote-11127302
Ref: 修改的语法-Footnote-21127351
Ref: 修改的语法-Footnote-31127400
Ref: 修改的语法-Footnote-41127449
Node: 移除的语法1127498
Ref: whatsnew/3 0 removed-syntax1127600
Ref: c4b1127600
Ref: 移除的语法-Footnote-11128787
Ref: 移除的语法-Footnote-21128836
Node: Changes Already Present In Python 2 61128885
Ref: whatsnew/3 0 changes-already-present-in-python-2-61129047
Ref: c4e1129047
Node: Library Changes1132807
Ref: whatsnew/3 0 library-changes1132987
Ref: c611132987
Ref: Library Changes-Footnote-11139215
Ref: Library Changes-Footnote-21139264
Ref: Library Changes-Footnote-31139313
Ref: Library Changes-Footnote-41139362
Ref: Library Changes-Footnote-51139411
Ref: Library Changes-Footnote-61139460
Node: PEP 3101 A New Approach To String Formatting1139509
Ref: whatsnew/3 0 pep-3101-a-new-approach-to-string-formatting1139673
Ref: c651139673
Ref: PEP 3101 A New Approach To String Formatting-Footnote-11140125
Node: Changes To Exceptions1140174
Ref: whatsnew/3 0 changes-to-exceptions1140350
Ref: c661140350
Ref: Changes To Exceptions-Footnote-11143854
Ref: Changes To Exceptions-Footnote-21143903
Ref: Changes To Exceptions-Footnote-31143952
Ref: Changes To Exceptions-Footnote-41144001
Ref: Changes To Exceptions-Footnote-51144050
Node: Miscellaneous Other Changes1144099
Ref: whatsnew/3 0 miscellaneous-other-changes1144259
Ref: c681144259
Node: Operators And Special Methods1144385
Ref: whatsnew/3 0 operators-and-special-methods1144495
Ref: c691144495
Ref: Operators And Special Methods-Footnote-11146131
Node: Builtins1146180
Ref: whatsnew/3 0 builtins1146290
Ref: c711146290
Ref: Builtins-Footnote-11148761
Ref: Builtins-Footnote-21148810
Node: 构建和 C API 的改变<7>1148859
Ref: whatsnew/3 0 build-and-c-api-changes1149004
Ref: c791149004
Ref: 构建和 C API 的改变<7>-Footnote-11150035
Ref: 构建和 C API 的改变<7>-Footnote-21150084
Ref: 构建和 C API 的改变<7>-Footnote-31150133
Node: 性能1150182
Ref: whatsnew/3 0 performance1150320
Ref: c7c1150320
Node: 移植到 Python 3 01150627
Ref: whatsnew/3 0 porting-to-python-3-01150728
Ref: c7d1150728
Node: Python 2 7 有什么新变化1152327
Ref: whatsnew/2 7 doc1152487
Ref: c801152487
Ref: whatsnew/2 7 what-s-new-in-python-2-71152487
Ref: c811152487
Node: Python 2 x的未来1154903
Ref: whatsnew/2 7 the-future-for-python-2-x1155044
Ref: c821155044
Ref: whatsnew/2 7 whatsnew27-python311155044
Ref: c831155044
Ref: Python 2 x的未来-Footnote-11157807
Ref: Python 2 x的未来-Footnote-21157856
Node: Changes to the Handling of Deprecation Warnings1157893
Ref: whatsnew/2 7 changes-to-the-handling-of-deprecation-warnings1158062
Ref: c861158062
Ref: Changes to the Handling of Deprecation Warnings-Footnote-11159637
Node: Python 3 1 Features1159679
Ref: whatsnew/2 7 python-3-1-features1159880
Ref: c871159880
Node: PEP 372 Adding an Ordered Dictionary to collections1161761
Ref: whatsnew/2 7 pep-03721161959
Ref: c881161959
Ref: whatsnew/2 7 pep-372-adding-an-ordered-dictionary-to-collections1161959
Ref: c8b1161959
Ref: PEP 372 Adding an Ordered Dictionary to collections-Footnote-11165546
Ref: PEP 372 Adding an Ordered Dictionary to collections-Footnote-21165573
Node: PEP 378 千位分隔符的格式说明符<2>1165622
Ref: whatsnew/2 7 pep-03781165854
Ref: c891165854
Ref: whatsnew/2 7 pep-378-format-specifier-for-thousands-separator1165854
Ref: c8d1165854
Ref: PEP 378 千位分隔符的格式说明符<2>-Footnote-11167321
Node: PEP 389 The argparse Module for Parsing Command Lines1167370
Ref: whatsnew/2 7 pep-389-the-argparse-module-for-parsing-command-lines1167601
Ref: c8e1167601
Ref: PEP 389 The argparse Module for Parsing Command Lines-Footnote-11171601
Node: PEP 391 Dictionary-Based Configuration For Logging1171650
Ref: whatsnew/2 7 pep-391-dictionary-based-configuration-for-logging1171862
Ref: c8f1171862
Ref: PEP 391 Dictionary-Based Configuration For Logging-Footnote-11175682
Node: PEP 3106 Dictionary Views1175731
Ref: whatsnew/2 7 pep-3106-dictionary-views1175920
Ref: c951175920
Ref: PEP 3106 Dictionary Views-Footnote-11178028
Ref: PEP 3106 Dictionary Views-Footnote-21178077
Node: PEP 3137 The memoryview Object1178119
Ref: whatsnew/2 7 pep-3137-the-memoryview-object1178285
Ref: c961178285
Ref: PEP 3137 The memoryview Object-Footnote-11179940
Ref: PEP 3137 The memoryview Object-Footnote-21179989
Node: 其他语言特性修改<9>1180031
Ref: whatsnew/2 7 other-language-changes1180196
Ref: c971180196
Ref: 其他语言特性修改<9>-Footnote-11190116
Ref: 其他语言特性修改<9>-Footnote-21190158
Ref: 其他语言特性修改<9>-Footnote-31190200
Ref: 其他语言特性修改<9>-Footnote-41190242
Ref: 其他语言特性修改<9>-Footnote-51190284
Ref: 其他语言特性修改<9>-Footnote-61190326
Ref: 其他语言特性修改<9>-Footnote-71190368
Ref: 其他语言特性修改<9>-Footnote-81190410
Ref: 其他语言特性修改<9>-Footnote-91190452
Ref: 其他语言特性修改<9>-Footnote-101190494
Ref: 其他语言特性修改<9>-Footnote-111190537
Ref: 其他语言特性修改<9>-Footnote-121190580
Ref: 其他语言特性修改<9>-Footnote-131190623
Ref: 其他语言特性修改<9>-Footnote-141190666
Ref: 其他语言特性修改<9>-Footnote-151190712
Ref: 其他语言特性修改<9>-Footnote-161190755
Ref: 其他语言特性修改<9>-Footnote-171190798
Ref: 其他语言特性修改<9>-Footnote-181190841
Ref: 其他语言特性修改<9>-Footnote-191190887
Ref: 其他语言特性修改<9>-Footnote-201190930
Ref: 其他语言特性修改<9>-Footnote-211190973
Ref: 其他语言特性修改<9>-Footnote-221191016
Ref: 其他语言特性修改<9>-Footnote-231191059
Ref: 其他语言特性修改<9>-Footnote-241191102
Node: Interpreter Changes1191145
Ref: whatsnew/2 7 interpreter-changes1191252
Ref: c9a1191252
Ref: whatsnew/2 7 new-27-interpreter1191252
Ref: c9b1191252
Ref: Interpreter Changes-Footnote-11191906
Node: 性能优化<8>1191948
Ref: whatsnew/2 7 optimizations1192055
Ref: c9c1192055
Ref: 性能优化<8>-Footnote-11196897
Ref: 性能优化<8>-Footnote-21196939
Ref: 性能优化<8>-Footnote-31196981
Ref: 性能优化<8>-Footnote-41197023
Ref: 性能优化<8>-Footnote-51197065
Ref: 性能优化<8>-Footnote-61197107
Ref: 性能优化<8>-Footnote-71197152
Ref: 性能优化<8>-Footnote-81197194
Ref: 性能优化<8>-Footnote-91197236
Ref: 性能优化<8>-Footnote-101197278
Ref: 性能优化<8>-Footnote-111197321
Ref: 性能优化<8>-Footnote-121197364
Ref: 性能优化<8>-Footnote-131197407
Node: 新增和改进的模块1197450
Ref: whatsnew/2 7 new-and-improved-modules1197613
Ref: c9f1197613
Ref: 新增和改进的模块-Footnote-11232721
Ref: 新增和改进的模块-Footnote-21232763
Ref: 新增和改进的模块-Footnote-31232805
Ref: 新增和改进的模块-Footnote-41232858
Ref: 新增和改进的模块-Footnote-51232900
Ref: 新增和改进的模块-Footnote-61232942
Ref: 新增和改进的模块-Footnote-71232987
Ref: 新增和改进的模块-Footnote-81233029
Ref: 新增和改进的模块-Footnote-91233071
Ref: 新增和改进的模块-Footnote-101233113
Ref: 新增和改进的模块-Footnote-111233156
Ref: 新增和改进的模块-Footnote-121233199
Ref: 新增和改进的模块-Footnote-131233242
Ref: 新增和改进的模块-Footnote-141233282
Ref: 新增和改进的模块-Footnote-151233325
Ref: 新增和改进的模块-Footnote-161233368
Ref: 新增和改进的模块-Footnote-171233411
Ref: 新增和改进的模块-Footnote-181233454
Ref: 新增和改进的模块-Footnote-191233497
Ref: 新增和改进的模块-Footnote-201233540
Ref: 新增和改进的模块-Footnote-211233583
Ref: 新增和改进的模块-Footnote-221233626
Ref: 新增和改进的模块-Footnote-231233669
Ref: 新增和改进的模块-Footnote-241233712
Ref: 新增和改进的模块-Footnote-251233755
Ref: 新增和改进的模块-Footnote-261233798
Ref: 新增和改进的模块-Footnote-271233844
Ref: 新增和改进的模块-Footnote-281233887
Ref: 新增和改进的模块-Footnote-291233930
Ref: 新增和改进的模块-Footnote-301233973
Ref: 新增和改进的模块-Footnote-311234016
Ref: 新增和改进的模块-Footnote-321234059
Ref: 新增和改进的模块-Footnote-331234102
Ref: 新增和改进的模块-Footnote-341234145
Ref: 新增和改进的模块-Footnote-351234188
Ref: 新增和改进的模块-Footnote-361234231
Ref: 新增和改进的模块-Footnote-371234274
Ref: 新增和改进的模块-Footnote-381234317
Ref: 新增和改进的模块-Footnote-391234360
Ref: 新增和改进的模块-Footnote-401234403
Ref: 新增和改进的模块-Footnote-411234446
Ref: 新增和改进的模块-Footnote-421234489
Ref: 新增和改进的模块-Footnote-431234532
Ref: 新增和改进的模块-Footnote-441234575
Ref: 新增和改进的模块-Footnote-451234618
Ref: 新增和改进的模块-Footnote-461234661
Ref: 新增和改进的模块-Footnote-471234704
Ref: 新增和改进的模块-Footnote-481234747
Ref: 新增和改进的模块-Footnote-491234793
Ref: 新增和改进的模块-Footnote-501234836
Ref: 新增和改进的模块-Footnote-511234879
Ref: 新增和改进的模块-Footnote-521234922
Ref: 新增和改进的模块-Footnote-531234965
Ref: 新增和改进的模块-Footnote-541235008
Ref: 新增和改进的模块-Footnote-551235051
Ref: 新增和改进的模块-Footnote-561235094
Ref: 新增和改进的模块-Footnote-571235137
Ref: 新增和改进的模块-Footnote-581235180
Ref: 新增和改进的模块-Footnote-591235223
Ref: 新增和改进的模块-Footnote-601235266
Ref: 新增和改进的模块-Footnote-611235309
Ref: 新增和改进的模块-Footnote-621235352
Ref: 新增和改进的模块-Footnote-631235395
Ref: 新增和改进的模块-Footnote-641235438
Ref: 新增和改进的模块-Footnote-651235481
Ref: 新增和改进的模块-Footnote-661235524
Ref: 新增和改进的模块-Footnote-671235567
Ref: 新增和改进的模块-Footnote-681235610
Ref: 新增和改进的模块-Footnote-691235653
Ref: 新增和改进的模块-Footnote-701235699
Ref: 新增和改进的模块-Footnote-711235742
Ref: 新增和改进的模块-Footnote-721235785
Ref: 新增和改进的模块-Footnote-731235871
Ref: 新增和改进的模块-Footnote-741235914
Ref: 新增和改进的模块-Footnote-751235957
Ref: 新增和改进的模块-Footnote-761236000
Ref: 新增和改进的模块-Footnote-771236043
Ref: 新增和改进的模块-Footnote-781236086
Ref: 新增和改进的模块-Footnote-791236132
Ref: 新增和改进的模块-Footnote-801236175
Ref: 新增和改进的模块-Footnote-811236218
Ref: 新增和改进的模块-Footnote-821236261
Ref: 新增和改进的模块-Footnote-831236304
Ref: 新增和改进的模块-Footnote-841236347
Ref: 新增和改进的模块-Footnote-851236390
Ref: 新增和改进的模块-Footnote-861236436
Ref: 新增和改进的模块-Footnote-871236482
Ref: 新增和改进的模块-Footnote-881236525
Ref: 新增和改进的模块-Footnote-891236575
Ref: 新增和改进的模块-Footnote-901236625
Ref: 新增和改进的模块-Footnote-911236668
Ref: 新增和改进的模块-Footnote-921236711
Ref: 新增和改进的模块-Footnote-931236754
Ref: 新增和改进的模块-Footnote-941236797
Ref: 新增和改进的模块-Footnote-951236840
Ref: 新增和改进的模块-Footnote-961236883
Ref: 新增和改进的模块-Footnote-971236926
Node: 新模块：importlib1236969
Ref: whatsnew/2 7 importlib-section1237081
Ref: c8a1237081
Ref: whatsnew/2 7 new-module-importlib1237081
Ref: cc41237081
Node: 新模块：sysconfig1238613
Ref: whatsnew/2 7 new-module-sysconfig1238759
Ref: cc51238759
Node: ttk Themed Widgets for Tk1240081
Ref: whatsnew/2 7 ttk-themed-widgets-for-tk1240232
Ref: cc81240232
Ref: ttk Themed Widgets for Tk-Footnote-11241300
Ref: ttk Themed Widgets for Tk-Footnote-21241342
Node: 更新的模块：unittest1241384
Ref: whatsnew/2 7 unittest-section1241547
Ref: cc91241547
Ref: whatsnew/2 7 updated-module-unittest1241547
Ref: cca1241547
Ref: 更新的模块：unittest-Footnote-11250394
Ref: 更新的模块：unittest-Footnote-21250420
Ref: 更新的模块：unittest-Footnote-31250457
Ref: 更新的模块：unittest-Footnote-41250499
Ref: 更新的模块：unittest-Footnote-51250541
Ref: 更新的模块：unittest-Footnote-61250586
Ref: 更新的模块：unittest-Footnote-71250628
Ref: 更新的模块：unittest-Footnote-81250670
Ref: 更新的模块：unittest-Footnote-91250712
Ref: 更新的模块：unittest-Footnote-101250754
Ref: 更新的模块：unittest-Footnote-111250797
Ref: 更新的模块：unittest-Footnote-121250840
Ref: 更新的模块：unittest-Footnote-131250883
Ref: 更新的模块：unittest-Footnote-141250926
Node: 更新的模块：ElementTree 1 31250969
Ref: whatsnew/2 7 elementtree-section1251098
Ref: ced1251098
Ref: whatsnew/2 7 updated-module-elementtree-1-31251098
Ref: cee1251098
Ref: 更新的模块：ElementTree 1 3-Footnote-11255039
Node: 构建和 C API 的改变<8>1255081
Ref: whatsnew/2 7 build-and-c-api-changes1255240
Ref: cf01255240
Ref: 构建和 C API 的改变<8>-Footnote-11263808
Ref: 构建和 C API 的改变<8>-Footnote-21263878
Ref: 构建和 C API 的改变<8>-Footnote-31263920
Ref: 构建和 C API 的改变<8>-Footnote-41263962
Ref: 构建和 C API 的改变<8>-Footnote-51264004
Ref: 构建和 C API 的改变<8>-Footnote-61264046
Ref: 构建和 C API 的改变<8>-Footnote-71264088
Ref: 构建和 C API 的改变<8>-Footnote-81264130
Ref: 构建和 C API 的改变<8>-Footnote-91264199
Ref: 构建和 C API 的改变<8>-Footnote-101264241
Ref: 构建和 C API 的改变<8>-Footnote-111264284
Ref: 构建和 C API 的改变<8>-Footnote-121264327
Ref: 构建和 C API 的改变<8>-Footnote-131264370
Ref: 构建和 C API 的改变<8>-Footnote-141264416
Ref: 构建和 C API 的改变<8>-Footnote-151264462
Ref: 构建和 C API 的改变<8>-Footnote-161264505
Ref: 构建和 C API 的改变<8>-Footnote-171264548
Ref: 构建和 C API 的改变<8>-Footnote-181264591
Ref: 构建和 C API 的改变<8>-Footnote-191264634
Ref: 构建和 C API 的改变<8>-Footnote-201264677
Ref: 构建和 C API 的改变<8>-Footnote-211264723
Ref: 构建和 C API 的改变<8>-Footnote-221264766
Node: 胶囊1264809
Ref: whatsnew/2 7 capsules1264919
Ref: cf61264919
Ref: whatsnew/2 7 whatsnew27-capsules1264919
Ref: cf71264919
Ref: 胶囊-Footnote-11266897
Node: 特定于 Windows 的更改：1266939
Ref: whatsnew/2 7 port-specific-changes-windows1267089
Ref: cfa1267089
Ref: 特定于 Windows 的更改：-Footnote-11268774
Ref: 特定于 Windows 的更改：-Footnote-21268816
Ref: 特定于 Windows 的更改：-Footnote-31268858
Ref: 特定于 Windows 的更改：-Footnote-41268900
Ref: 特定于 Windows 的更改：-Footnote-51268945
Ref: 特定于 Windows 的更改：-Footnote-61268987
Node: 特定于 Mac OS X 的更改：1269029
Ref: whatsnew/2 7 port-specific-changes-mac-os-x1269203
Ref: cfc1269203
Ref: 特定于 Mac OS X 的更改：-Footnote-11270235
Ref: 特定于 Mac OS X 的更改：-Footnote-21270277
Node: 特定于 FreeBSD 的更改：1270320
Ref: whatsnew/2 7 port-specific-changes-freebsd1270455
Ref: cfd1270455
Ref: 特定于 FreeBSD 的更改：-Footnote-11270808
Node: Other Changes and Fixes1270850
Ref: whatsnew/2 7 other-changes-and-fixes1271005
Ref: cfe1271005
Ref: Other Changes and Fixes-Footnote-11273193
Ref: Other Changes and Fixes-Footnote-21273235
Ref: Other Changes and Fixes-Footnote-31273280
Ref: Other Changes and Fixes-Footnote-41273322
Ref: Other Changes and Fixes-Footnote-51273364
Node: 移植到 Python 2 71273406
Ref: whatsnew/2 7 porting-to-python-2-71273586
Ref: cff1273586
Ref: 移植到 Python 2 7-Footnote-11279152
Ref: 移植到 Python 2 7-Footnote-21279194
Ref: 移植到 Python 2 7-Footnote-31279236
Ref: 移植到 Python 2 7-Footnote-41279278
Ref: 移植到 Python 2 7-Footnote-51279320
Ref: 移植到 Python 2 7-Footnote-61279362
Ref: 移植到 Python 2 7-Footnote-71279404
Ref: 移植到 Python 2 7-Footnote-81279446
Ref: 移植到 Python 2 7-Footnote-91279488
Ref: 移植到 Python 2 7-Footnote-101279530
Ref: 移植到 Python 2 7-Footnote-111279573
Ref: 移植到 Python 2 7-Footnote-121279616
Ref: 移植到 Python 2 7-Footnote-131279659
Ref: 移植到 Python 2 7-Footnote-141279709
Node: New Features Added to Python 2 7 Maintenance Releases1279752
Ref: whatsnew/2 7 new-features-added-to-python-2-7-maintenance-releases1279915
Ref: d001279915
Ref: whatsnew/2 7 py27-maintenance-enhancements1279915
Ref: c841279915
Node: Two new environment variables for debug mode1281381
Ref: whatsnew/2 7 two-new-environment-variables-for-debug-mode1281575
Ref: d011281575
Ref: Two new environment variables for debug mode-Footnote-11282252
Ref: Two new environment variables for debug mode-Footnote-21282295
Node: PEP 434 IDLE Enhancement Exception for All Branches1282338
Ref: whatsnew/2 7 pep-434-idle-enhancement-exception-for-all-branches1282593
Ref: d021282593
Ref: PEP 434 IDLE Enhancement Exception for All Branches-Footnote-11283113
Node: PEP 466 Network Security Enhancements for Python 2 71283162
Ref: whatsnew/2 7 pep-466-network-security-enhancements-for-python-2-71283421
Ref: d031283421
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-11285649
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-21285698
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-31285747
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-41285790
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-51285833
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-61285882
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-71285925
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-81285968
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-91286017
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-101286060
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-111286104
Node: PEP 477 Backport ensurepip PEP 453 to Python 2 71286148
Ref: whatsnew/2 7 pep-477-backport-ensurepip-pep-453-to-python-2-71286435
Ref: d061286435
Ref: PEP 477 Backport ensurepip PEP 453 to Python 2 7-Footnote-11286913
Ref: PEP 477 Backport ensurepip PEP 453 to Python 2 7-Footnote-21286962
Node: Bootstrapping pip By Default<2>1287011
Ref: whatsnew/2 7 bootstrapping-pip-by-default1287151
Ref: d071287151
Ref: Bootstrapping pip By Default<2>-Footnote-11288819
Ref: Bootstrapping pip By Default<2>-Footnote-21288868
Node: 文档更改<2>1288966
Ref: whatsnew/2 7 documentation-changes1289106
Ref: d081289106
Ref: whatsnew/2 7 id11289106
Ref: d091289106
Ref: 文档更改<2>-Footnote-11289983
Ref: 文档更改<2>-Footnote-21290019
Node: PEP 476 Enabling certificate verification by default for stdlib http clients<2>1290068
Ref: whatsnew/2 7 pep-476-enabling-certificate-verification-by-default-for-stdlib-http-clients1290361
Ref: d0a1290361
Ref: PEP 476 Enabling certificate verification by default for stdlib http clients<2>-Footnote-11291442
Node: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具1291491
Ref: whatsnew/2 7 pep-493-https-verification-migration-tools-for-python-2-71291770
Ref: d0b1291770
Ref: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具-Footnote-11292923
Node: New make regen-all build target<3>1292972
Ref: whatsnew/2 7 new-make-regen-all-build-target1293209
Ref: d0c1293209
Ref: New make regen-all build target<3>-Footnote-11294003
Ref: New make regen-all build target<3>-Footnote-21294070
Node: Removal of make touch build target<3>1294113
Ref: whatsnew/2 7 removal-of-make-touch-build-target1294283
Ref: d0d1294283
Ref: Removal of make touch build target<3>-Footnote-11294719
Node: 致谢1294762
Ref: whatsnew/2 7 acknowledgements1294896
Ref: d0e1294896
Ref: whatsnew/2 7 acks271294896
Ref: d0f1294896
Node: Python 2 6 有什么新变化1295090
Ref: whatsnew/2 6 doc1295250
Ref: d101295250
Ref: whatsnew/2 6 what-s-new-in-python-2-61295250
Ref: d111295250
Ref: whatsnew/2 6 whats-new-in-2-61295250
Ref: c4f1295250
Ref: Python 2 6 有什么新变化-Footnote-11298131
Node: Python 3 01298180
Ref: whatsnew/2 6 python-3-01298286
Ref: d121298286
Ref: Python 3 0-Footnote-11300394
Ref: Python 3 0-Footnote-21300443
Node: 开发过程的变化1300492
Ref: whatsnew/2 6 changes-to-the-development-process1300628
Ref: d131300628
Node: New Issue Tracker Roundup1301058
Ref: whatsnew/2 6 new-issue-tracker-roundup1301205
Ref: d141301205
Ref: New Issue Tracker Roundup-Footnote-11303231
Ref: New Issue Tracker Roundup-Footnote-21303280
Ref: New Issue Tracker Roundup-Footnote-31303311
Ref: New Issue Tracker Roundup-Footnote-41303351
Ref: New Issue Tracker Roundup-Footnote-51303386
Node: 新的文档格式：使用 Sphinx 的 reStructuredText1303427
Ref: whatsnew/2 6 new-documentation-format-restructuredtext-using-sphinx1303574
Ref: d151303574
Ref: 新的文档格式：使用 Sphinx 的 reStructuredText-Footnote-11305636
Ref: 新的文档格式：使用 Sphinx 的 reStructuredText-Footnote-21305695
Ref: 新的文档格式：使用 Sphinx 的 reStructuredText-Footnote-31305744
Ref: 新的文档格式：使用 Sphinx 的 reStructuredText-Footnote-41305775
Node: PEP 343 "with" 语句1305815
Ref: whatsnew/2 6 pep-03431305979
Ref: c501305979
Ref: whatsnew/2 6 pep-343-the-with-statement1305979
Ref: d161305979
Node: Writing Context Managers1309229
Ref: whatsnew/2 6 new-26-context-managers1309337
Ref: c511309337
Ref: whatsnew/2 6 writing-context-managers1309337
Ref: d171309337
Node: contextlib 模块1313846
Ref: whatsnew/2 6 new-module-contextlib1313954
Ref: c521313954
Ref: whatsnew/2 6 the-contextlib-module1313954
Ref: d181313954
Ref: contextlib 模块-Footnote-11316414
Node: PEP 366 从主模块显式相对导入1316463
Ref: whatsnew/2 6 pep-03661316647
Ref: c531316647
Ref: whatsnew/2 6 pep-366-explicit-relative-imports-from-a-main-module1316647
Ref: d191316647
Node: PEP 370 分用户的 site-packages 目录1317372
Ref: whatsnew/2 6 pep-03701317561
Ref: c541317561
Ref: whatsnew/2 6 pep-370-per-user-site-packages-directory1317561
Ref: d1b1317561
Ref: PEP 370 分用户的 site-packages 目录-Footnote-11318989
Node: PEP 371 多任务处理包1319038
Ref: whatsnew/2 6 pep-03711319219
Ref: c551319219
Ref: whatsnew/2 6 pep-371-the-multiprocessing-package1319219
Ref: d1f1319219
Ref: PEP 371 多任务处理包-Footnote-11324286
Node: PEP 3101 高级字符串格式1324335
Ref: whatsnew/2 6 pep-31011324502
Ref: c561324502
Ref: whatsnew/2 6 pep-3101-advanced-string-formatting1324502
Ref: d211324502
Ref: PEP 3101 高级字符串格式-Footnote-11330107
Node: PEP 3105 print 改为函数1330156
Ref: whatsnew/2 6 pep-31051330327
Ref: c571330327
Ref: whatsnew/2 6 pep-3105-print-as-a-function1330327
Ref: d231330327
Ref: PEP 3105 print 改为函数-Footnote-11331465
Node: PEP 3110 异常处理的变更1331514
Ref: whatsnew/2 6 pep-31101331679
Ref: c581331679
Ref: whatsnew/2 6 pep-3110-exception-handling-changes1331679
Ref: d241331679
Ref: PEP 3110 异常处理的变更-Footnote-11333230
Node: PEP 3112 字节字面值1333279
Ref: whatsnew/2 6 pep-31121333437
Ref: c591333437
Ref: whatsnew/2 6 pep-3112-byte-literals1333437
Ref: d251333437
Ref: PEP 3112 字节字面值-Footnote-11336447
Node: PEP 3116 新 I/O 库1336496
Ref: whatsnew/2 6 pep-31161336654
Ref: c5a1336654
Ref: whatsnew/2 6 pep-3116-new-i-o-library1336654
Ref: d2b1336654
Ref: PEP 3116 新 I/O 库-Footnote-11340264
Node: PEP 3118 修改缓冲区协议1340313
Ref: whatsnew/2 6 pep-31181340468
Ref: c5b1340468
Ref: whatsnew/2 6 pep-3118-revised-buffer-protocol1340468
Ref: d2c1340468
Ref: PEP 3118 修改缓冲区协议-Footnote-11342583
Node: PEP 3119 抽象基类1342632
Ref: whatsnew/2 6 pep-31191342803
Ref: c5c1342803
Ref: whatsnew/2 6 pep-3119-abstract-base-classes1342803
Ref: d2e1342803
Ref: PEP 3119 抽象基类-Footnote-11348125
Node: PEP 3127 整型文字支持和语法1348174
Ref: whatsnew/2 6 pep-31271348336
Ref: c5d1348336
Ref: whatsnew/2 6 pep-3127-integer-literal-support-and-syntax1348336
Ref: d311348336
Ref: PEP 3127 整型文字支持和语法-Footnote-11349633
Node: PEP 3129 类装饰器1349682
Ref: whatsnew/2 6 pep-31291349860
Ref: c5e1349860
Ref: whatsnew/2 6 pep-3129-class-decorators1349860
Ref: d321349860
Ref: PEP 3129 类装饰器-Footnote-11350228
Node: PEP 3141 A Type Hierarchy for Numbers1350277
Ref: whatsnew/2 6 pep-31411350447
Ref: c5f1350447
Ref: whatsnew/2 6 pep-3141-a-type-hierarchy-for-numbers1350447
Ref: d331350447
Ref: PEP 3141 A Type Hierarchy for Numbers-Footnote-11352637
Ref: PEP 3141 A Type Hierarchy for Numbers-Footnote-21352686
Ref: PEP 3141 A Type Hierarchy for Numbers-Footnote-31352784
Node: fractions 模块1352869
Ref: whatsnew/2 6 the-fractions-module1352959
Ref: d371352959
Node: 其他语言特性修改<10>1354556
Ref: whatsnew/2 6 other-language-changes1354732
Ref: d381354732
Ref: 其他语言特性修改<10>-Footnote-11363570
Ref: 其他语言特性修改<10>-Footnote-21363615
Ref: 其他语言特性修改<10>-Footnote-31363657
Ref: 其他语言特性修改<10>-Footnote-41363702
Ref: 其他语言特性修改<10>-Footnote-51363744
Ref: 其他语言特性修改<10>-Footnote-61363786
Ref: 其他语言特性修改<10>-Footnote-71363828
Ref: 其他语言特性修改<10>-Footnote-81363870
Ref: 其他语言特性修改<10>-Footnote-91363912
Ref: 其他语言特性修改<10>-Footnote-101363954
Ref: 其他语言特性修改<10>-Footnote-111363997
Ref: 其他语言特性修改<10>-Footnote-121364040
Ref: 其他语言特性修改<10>-Footnote-131364086
Ref: 其他语言特性修改<10>-Footnote-141364132
Ref: 其他语言特性修改<10>-Footnote-151364178
Ref: 其他语言特性修改<10>-Footnote-161364224
Node: 性能优化<9>1364270
Ref: whatsnew/2 6 optimizations1364381
Ref: d3c1364381
Ref: 性能优化<9>-Footnote-11367231
Ref: 性能优化<9>-Footnote-21367276
Ref: 性能优化<9>-Footnote-31367321
Ref: 性能优化<9>-Footnote-41367363
Node: Interpreter Changes<2>1367405
Ref: whatsnew/2 6 interpreter-changes1367516
Ref: d3d1367516
Ref: whatsnew/2 6 new-26-interpreter1367516
Ref: d3e1367516
Node: 新增和改进的模块<2>1369090
Ref: whatsnew/2 6 new-and-improved-modules1369254
Ref: d421369254
Ref: 新增和改进的模块<2>-Footnote-11411650
Ref: 新增和改进的模块<2>-Footnote-21411695
Ref: 新增和改进的模块<2>-Footnote-31411748
Ref: 新增和改进的模块<2>-Footnote-41411790
Ref: 新增和改进的模块<2>-Footnote-51411834
Ref: 新增和改进的模块<2>-Footnote-61411876
Ref: 新增和改进的模块<2>-Footnote-71411921
Ref: 新增和改进的模块<2>-Footnote-81411963
Ref: 新增和改进的模块<2>-Footnote-91412016
Ref: 新增和改进的模块<2>-Footnote-101412061
Ref: 新增和改进的模块<2>-Footnote-111412107
Ref: 新增和改进的模块<2>-Footnote-121412153
Ref: 新增和改进的模块<2>-Footnote-131412196
Ref: 新增和改进的模块<2>-Footnote-141412239
Ref: 新增和改进的模块<2>-Footnote-151412284
Ref: 新增和改进的模块<2>-Footnote-161412327
Ref: 新增和改进的模块<2>-Footnote-171412373
Ref: 新增和改进的模块<2>-Footnote-181412416
Ref: 新增和改进的模块<2>-Footnote-191412462
Ref: 新增和改进的模块<2>-Footnote-201412508
Ref: 新增和改进的模块<2>-Footnote-211412554
Ref: 新增和改进的模块<2>-Footnote-221412599
Ref: 新增和改进的模块<2>-Footnote-231412645
Ref: 新增和改进的模块<2>-Footnote-241412691
Ref: 新增和改进的模块<2>-Footnote-251412734
Ref: 新增和改进的模块<2>-Footnote-261412777
Ref: 新增和改进的模块<2>-Footnote-271412823
Ref: 新增和改进的模块<2>-Footnote-281412869
Ref: 新增和改进的模块<2>-Footnote-291412914
Ref: 新增和改进的模块<2>-Footnote-301412957
Ref: 新增和改进的模块<2>-Footnote-311413000
Ref: 新增和改进的模块<2>-Footnote-321413043
Ref: 新增和改进的模块<2>-Footnote-331413086
Ref: 新增和改进的模块<2>-Footnote-341413129
Ref: 新增和改进的模块<2>-Footnote-351413172
Ref: 新增和改进的模块<2>-Footnote-361413215
Ref: 新增和改进的模块<2>-Footnote-371413265
Ref: 新增和改进的模块<2>-Footnote-381413310
Ref: 新增和改进的模块<2>-Footnote-391413360
Ref: 新增和改进的模块<2>-Footnote-401413405
Ref: 新增和改进的模块<2>-Footnote-411413448
Ref: 新增和改进的模块<2>-Footnote-421413493
Ref: 新增和改进的模块<2>-Footnote-431413539
Ref: 新增和改进的模块<2>-Footnote-441413582
Ref: 新增和改进的模块<2>-Footnote-451413625
Ref: 新增和改进的模块<2>-Footnote-461413668
Ref: 新增和改进的模块<2>-Footnote-471413714
Ref: 新增和改进的模块<2>-Footnote-481413757
Ref: 新增和改进的模块<2>-Footnote-491413800
Ref: 新增和改进的模块<2>-Footnote-501413846
Ref: 新增和改进的模块<2>-Footnote-511413889
Ref: 新增和改进的模块<2>-Footnote-521413935
Ref: 新增和改进的模块<2>-Footnote-531413978
Ref: 新增和改进的模块<2>-Footnote-541414024
Ref: 新增和改进的模块<2>-Footnote-551414067
Ref: 新增和改进的模块<2>-Footnote-561414113
Ref: 新增和改进的模块<2>-Footnote-571414156
Ref: 新增和改进的模块<2>-Footnote-581414202
Ref: 新增和改进的模块<2>-Footnote-591414248
Ref: 新增和改进的模块<2>-Footnote-601414291
Ref: 新增和改进的模块<2>-Footnote-611414334
Ref: 新增和改进的模块<2>-Footnote-621414379
Ref: 新增和改进的模块<2>-Footnote-631414425
Node: ast 模块1414471
Ref: whatsnew/2 6 the-ast-module1414576
Ref: d521414576
Node: future_builtins 模块1417227
Ref: whatsnew/2 6 the-future-builtins-module1417383
Ref: d531417383
Node: The json module JavaScript Object Notation1418488
Ref: whatsnew/2 6 the-json-module-javascript-object-notation1418673
Ref: d551418673
Node: plistlib 模块：属性列表解析器1419685
Ref: whatsnew/2 6 the-plistlib-module-a-property-list-parser1419867
Ref: d561419867
Node: ctypes Enhancements1421220
Ref: whatsnew/2 6 ctypes-enhancements1421380
Ref: d571421380
Ref: ctypes Enhancements-Footnote-11423147
Ref: ctypes Enhancements-Footnote-21423192
Node: Improved SSL Support1423234
Ref: whatsnew/2 6 improved-ssl-support1423346
Ref: d581423346
Ref: Improved SSL Support-Footnote-11424278
Node: Deprecations and Removals1424311
Ref: whatsnew/2 6 deprecations-and-removals1424475
Ref: d591424475
Ref: Deprecations and Removals-Footnote-11426316
Node: 构建和 C API 的改变<9>1426365
Ref: whatsnew/2 6 build-and-c-api-changes1426521
Ref: d5b1426521
Ref: 构建和 C API 的改变<9>-Footnote-11432523
Ref: 构建和 C API 的改变<9>-Footnote-21432565
Ref: 构建和 C API 的改变<9>-Footnote-31432610
Ref: 构建和 C API 的改变<9>-Footnote-41432652
Ref: 构建和 C API 的改变<9>-Footnote-51432694
Node: 特定于 Windows 的更改：<2>1432739
Ref: whatsnew/2 6 port-specific-changes-windows1432880
Ref: d621432880
Ref: 特定于 Windows 的更改：<2>-Footnote-11435275
Ref: 特定于 Windows 的更改：<2>-Footnote-21435319
Ref: 特定于 Windows 的更改：<2>-Footnote-31435364
Node: 特定于 Mac OS X 的更改：<2>1435406
Ref: whatsnew/2 6 port-specific-changes-mac-os-x1435583
Ref: d631435583
Ref: 特定于 Mac OS X 的更改：<2>-Footnote-11436774
Node: 特定于 IRIX 的更改：1436819
Ref: whatsnew/2 6 port-specific-changes-irix1436954
Ref: d641436954
Node: 移植到Python 2 61437454
Ref: whatsnew/2 6 porting-to-python-2-61437594
Ref: d651437594
Ref: 移植到Python 2 6-Footnote-11441012
Ref: 移植到Python 2 6-Footnote-21441057
Ref: 移植到Python 2 6-Footnote-31441102
Node: 致谢<2>1441147
Ref: whatsnew/2 6 acknowledgements1441250
Ref: d681441250
Ref: whatsnew/2 6 acks1441250
Ref: d691441250
Node: Python 2 5 有什么新变化1441510
Ref: whatsnew/2 5 doc1441670
Ref: d6a1441670
Ref: whatsnew/2 5 what-s-new-in-python-2-51441670
Ref: d6b1441670
Ref: Python 2 5 有什么新变化-Footnote-11445087
Node: PEP 308 条件表达式1445136
Ref: whatsnew/2 5 pep-3081445260
Ref: d6c1445260
Ref: whatsnew/2 5 pep-308-conditional-expressions1445260
Ref: d711445260
Ref: PEP 308 条件表达式-Footnote-11448697
Ref: PEP 308 条件表达式-Footnote-21448746
Node: PEP 309 部分功能应用1448795
Ref: whatsnew/2 5 pep-3091448968
Ref: d721448968
Ref: whatsnew/2 5 pep-309-partial-function-application1448968
Ref: d731448968
Ref: PEP 309 部分功能应用-Footnote-11451773
Node: PEP 314 Python软件包的元数据 v1 11451822
Ref: whatsnew/2 5 pep-3141452007
Ref: d741452007
Ref: whatsnew/2 5 pep-314-metadata-for-python-software-packages-v1-11452007
Ref: d751452007
Ref: PEP 314 Python软件包的元数据 v1 1-Footnote-11453789
Node: PEP 328 绝对导入和相对导入1453838
Ref: whatsnew/2 5 pep-3281454032
Ref: d6f1454032
Ref: whatsnew/2 5 pep-328-absolute-and-relative-imports1454032
Ref: d761454032
Ref: PEP 328 绝对导入和相对导入-Footnote-11457820
Ref: PEP 328 绝对导入和相对导入-Footnote-21457869
Node: PEP 338 将模块作为脚本执行1457918
Ref: whatsnew/2 5 pep-3381458105
Ref: d771458105
Ref: whatsnew/2 5 pep-338-executing-modules-as-scripts1458105
Ref: d781458105
Ref: PEP 338 将模块作为脚本执行-Footnote-11458977
Node: PEP 341 统一 try/except/finally1459026
Ref: whatsnew/2 5 pep-3411459207
Ref: d701459207
Ref: whatsnew/2 5 pep-341-unified-try-except-finally1459207
Ref: d791459207
Ref: PEP 341 统一 try/except/finally-Footnote-11460958
Node: PEP 342 生成器的新特性1461007
Ref: whatsnew/2 5 pep-3421461177
Ref: d6e1461177
Ref: whatsnew/2 5 pep-342-new-generator-features1461177
Ref: d7b1461177
Ref: PEP 342 生成器的新特性-Footnote-11467765
Ref: PEP 342 生成器的新特性-Footnote-21467814
Ref: PEP 342 生成器的新特性-Footnote-31467863
Ref: PEP 342 生成器的新特性-Footnote-41467912
Ref: PEP 342 生成器的新特性-Footnote-51467961
Node: PEP 343 "with" 语句<2>1468010
Ref: whatsnew/2 5 pep-3431468179
Ref: d6d1468179
Ref: whatsnew/2 5 pep-343-the-with-statement1468179
Ref: d7c1468179
Node: Writing Context Managers<2>1471163
Ref: whatsnew/2 5 new-25-context-managers1471280
Ref: d7d1471280
Ref: whatsnew/2 5 writing-context-managers1471280
Ref: d7e1471280
Node: contextlib 模块<2>1475672
Ref: whatsnew/2 5 contextlibmod1475789
Ref: d7f1475789
Ref: whatsnew/2 5 the-contextlib-module1475789
Ref: d801475789
Ref: contextlib 模块<2>-Footnote-11478240
Node: PEP 352 异常作为新型的类1478289
Ref: whatsnew/2 5 pep-3521478468
Ref: d811478468
Ref: whatsnew/2 5 pep-352-exceptions-as-new-style-classes1478468
Ref: d821478468
Ref: PEP 352 异常作为新型的类-Footnote-11480900
Node: PEP 353 使用ssize_t作为索引类型1480949
Ref: whatsnew/2 5 pep-3531481130
Ref: d841481130
Ref: whatsnew/2 5 pep-353-using-ssize-t-as-the-index-type1481130
Ref: d851481130
Ref: PEP 353 使用ssize_t作为索引类型-Footnote-11484023
Ref: PEP 353 使用ssize_t作为索引类型-Footnote-21484072
Node: PEP 357 '__index__' 方法1484121
Ref: whatsnew/2 5 pep-3571484298
Ref: d871484298
Ref: whatsnew/2 5 pep-357-the-index-method1484298
Ref: d881484298
Ref: PEP 357 '__index__' 方法-Footnote-11485996
Node: 其他语言特性修改<11>1486045
Ref: whatsnew/2 5 other-lang1486216
Ref: d8a1486216
Ref: whatsnew/2 5 other-language-changes1486216
Ref: d8b1486216
Ref: 其他语言特性修改<11>-Footnote-11493158
Node: 交互解释器变更1493207
Ref: whatsnew/2 5 interactive1493318
Ref: d911493318
Ref: whatsnew/2 5 interactive-interpreter-changes1493318
Ref: d921493318
Node: 性能优化<10>1494071
Ref: whatsnew/2 5 optimizations1494182
Ref: d951494182
Ref: whatsnew/2 5 opts1494182
Ref: d961494182
Node: 新增，改进和删除的模块1497990
Ref: whatsnew/2 5 modules1498164
Ref: d971498164
Ref: whatsnew/2 5 new-improved-and-removed-modules1498164
Ref: d981498164
Ref: 新增，改进和删除的模块-Footnote-11522564
Ref: 新增，改进和删除的模块-Footnote-21522613
Ref: 新增，改进和删除的模块-Footnote-31522662
Node: ctypes 包1522711
Ref: whatsnew/2 5 module-ctypes1522815
Ref: da51522815
Ref: whatsnew/2 5 the-ctypes-package1522815
Ref: da61522815
Node: ElementTree 包1525998
Ref: whatsnew/2 5 module-etree1526122
Ref: da71526122
Ref: whatsnew/2 5 the-elementtree-package1526122
Ref: da81526122
Node: hashlib 包1531161
Ref: whatsnew/2 5 module-hashlib1531286
Ref: da91531286
Ref: whatsnew/2 5 the-hashlib-package1531286
Ref: daa1531286
Node: sqlite3 包1532833
Ref: whatsnew/2 5 module-sqlite1532954
Ref: dab1532954
Ref: whatsnew/2 5 the-sqlite3-package1532954
Ref: dac1532954
Ref: sqlite3 包-Footnote-11536893
Ref: sqlite3 包-Footnote-21536942
Node: wsgiref 包1536991
Ref: whatsnew/2 5 module-wsgiref1537092
Ref: dad1537092
Ref: whatsnew/2 5 the-wsgiref-package1537092
Ref: dae1537092
Ref: wsgiref 包-Footnote-11537973
Ref: wsgiref 包-Footnote-21538022
Node: 构建和 C API 的改变<10>1538071
Ref: whatsnew/2 5 build-and-c-api-changes1538236
Ref: daf1538236
Ref: whatsnew/2 5 build-api1538236
Ref: db01538236
Ref: 构建和 C API 的改变<10>-Footnote-11545253
Ref: 构建和 C API 的改变<10>-Footnote-21545302
Ref: 构建和 C API 的改变<10>-Footnote-31545351
Node: Port-Specific Changes1545400
Ref: whatsnew/2 5 port-specific-changes1545487
Ref: dba1545487
Ref: whatsnew/2 5 ports1545487
Ref: dbb1545487
Ref: Port-Specific Changes-Footnote-11546164
Node: 移植到Python 2 51546206
Ref: whatsnew/2 5 porting1546347
Ref: dbc1546347
Ref: whatsnew/2 5 porting-to-python-2-51546347
Ref: dbd1546347
Ref: 移植到Python 2 5-Footnote-11549162
Node: 致谢<3>1549211
Ref: whatsnew/2 5 acknowledgements1549314
Ref: dbe1549314
Node: Python 2 4 有什么新变化1549726
Ref: whatsnew/2 4 doc1549886
Ref: dbf1549886
Ref: whatsnew/2 4 what-s-new-in-python-2-41549886
Ref: dc01549886
Node: PEP 218 内置集合对象1551913
Ref: whatsnew/2 4 pep-218-built-in-set-objects1552046
Ref: dc11552046
Ref: PEP 218 内置集合对象-Footnote-11554240
Node: PEP 237 统一长整数和整数1554289
Ref: whatsnew/2 4 pep-237-unifying-long-integers-and-integers1554457
Ref: dc21554457
Ref: PEP 237 统一长整数和整数-Footnote-11555435
Node: PEP 289 生成器表达式1555484
Ref: whatsnew/2 4 pep-289-generator-expressions1555662
Ref: dc31555662
Ref: PEP 289 生成器表达式-Footnote-11557912
Node: PEP 292 Simpler String Substitutions1557961
Ref: whatsnew/2 4 pep-292-simpler-string-substitutions1558151
Ref: dc41558151
Ref: PEP 292 Simpler String Substitutions-Footnote-11559932
Node: PEP 318 Decorators for Functions and Methods1559981
Ref: whatsnew/2 4 pep-318-decorators-for-functions-and-methods1560165
Ref: dc51560165
Ref: PEP 318 Decorators for Functions and Methods-Footnote-11564664
Ref: PEP 318 Decorators for Functions and Methods-Footnote-21564713
Node: PEP 322 反向迭代1564762
Ref: whatsnew/2 4 pep-322-reverse-iteration1564939
Ref: dc71564939
Ref: PEP 322 反向迭代-Footnote-11565871
Node: PEP 324 新的子进程模块1565920
Ref: whatsnew/2 4 pep-324-new-subprocess-module1566082
Ref: dc81566082
Ref: PEP 324 新的子进程模块-Footnote-11569811
Node: PEP 327 十进制数据类型1569860
Ref: whatsnew/2 4 pep-327-decimal-data-type1570022
Ref: dca1570022
Node: 为什么需要十进制？1570602
Ref: whatsnew/2 4 why-is-decimal-needed1570718
Ref: dcb1570718
Node: Decimal 类型1573309
Ref: whatsnew/2 4 the-decimal-type1573448
Ref: dcc1573448
Node: Context 类型1576614
Ref: whatsnew/2 4 the-context-type1576717
Ref: dcd1576717
Ref: Context 类型-Footnote-11579309
Node: PEP 328 多行导入1579358
Ref: whatsnew/2 4 pep-328-multi-line-imports1579542
Ref: dce1579542
Ref: PEP 328 多行导入-Footnote-11580991
Node: PEP 331 Locale-Independent Float/String Conversions1581040
Ref: whatsnew/2 4 pep-331-locale-independent-float-string-conversions1581223
Ref: dcf1581223
Ref: PEP 331 Locale-Independent Float/String Conversions-Footnote-11582950
Node: 其他语言特性修改<12>1582999
Ref: whatsnew/2 4 other-language-changes1583198
Ref: dd01583198
Ref: 其他语言特性修改<12>-Footnote-11590178
Ref: 其他语言特性修改<12>-Footnote-21590227
Ref: 其他语言特性修改<12>-Footnote-31590276
Ref: 其他语言特性修改<12>-Footnote-41590325
Ref: 其他语言特性修改<12>-Footnote-51590374
Ref: 其他语言特性修改<12>-Footnote-61590423
Node: 性能优化<11>1590472
Ref: whatsnew/2 4 optimizations1590553
Ref: dd21590553
Node: 新增，改进和弃用的模块<3>1593302
Ref: whatsnew/2 4 new-improved-and-deprecated-modules1593479
Ref: dd41593479
Ref: 新增，改进和弃用的模块<3>-Footnote-11610728
Node: cookielib1610777
Ref: whatsnew/2 4 cookielib1610878
Ref: dd61610878
Node: doctest<3>1611788
Ref: whatsnew/2 4 doctest1611889
Ref: dd71611889
Node: 构建和 C API 的改变<11>1614623
Ref: whatsnew/2 4 build-and-c-api-changes1614792
Ref: ddd1614792
Node: Port-Specific Changes<2>1617412
Ref: whatsnew/2 4 port-specific-changes1617502
Ref: de41617502
Node: 移植到 Python 2 41617681
Ref: whatsnew/2 4 porting-to-python-2-41617823
Ref: de51617823
Node: 致谢<4>1619786
Ref: whatsnew/2 4 acknowledgements1619890
Ref: de71619890
Ref: whatsnew/2 4 acks1619890
Ref: de81619890
Node: Python 2 3 有什么新变化1620140
Ref: whatsnew/2 3 doc1620300
Ref: de91620300
Ref: whatsnew/2 3 what-s-new-in-python-2-31620300
Ref: dea1620300
Node: PEP 218 A Standard Set Datatype1623232
Ref: whatsnew/2 3 pep-218-a-standard-set-datatype1623363
Ref: dec1623363
Ref: PEP 218 A Standard Set Datatype-Footnote-11625843
Node: PEP 255 Simple Generators1625892
Ref: whatsnew/2 3 pep-255-simple-generators1626061
Ref: ded1626061
Ref: whatsnew/2 3 section-generators1626061
Ref: dee1626061
Ref: PEP 255 Simple Generators-Footnote-11632223
Ref: PEP 255 Simple Generators-Footnote-21632272
Node: PEP 263 Source Code Encodings1632321
Ref: whatsnew/2 3 pep-263-source-code-encodings1632494
Ref: df01632494
Ref: whatsnew/2 3 section-encodings1632494
Ref: df11632494
Ref: PEP 263 Source Code Encodings-Footnote-11633699
Node: PEP 273 从ZIP压缩包导入模块1633748
Ref: whatsnew/2 3 pep-273-importing-modules-from-zip-archives1633944
Ref: df21633944
Ref: PEP 273 从ZIP压缩包导入模块-Footnote-11635944
Ref: PEP 273 从ZIP压缩包导入模块-Footnote-21635993
Ref: PEP 273 从ZIP压缩包导入模块-Footnote-31636042
Node: PEP 277 Unicode file name support for Windows NT1636091
Ref: whatsnew/2 3 pep-277-unicode-file-name-support-for-windows-nt1636284
Ref: df41636284
Ref: PEP 277 Unicode file name support for Windows NT-Footnote-11637754
Node: PEP 278 通用换行支持1637803
Ref: whatsnew/2 3 pep-278-universal-newline-support1637978
Ref: df61637978
Ref: PEP 278 通用换行支持-Footnote-11639455
Node: PEP 279 enumerate1639504
Ref: whatsnew/2 3 pep-279-enumerate1639650
Ref: df71639650
Ref: whatsnew/2 3 section-enumerate1639650
Ref: df81639650
Ref: PEP 279 enumerate-Footnote-11640480
Node: PEP 282 logging 包1640529
Ref: whatsnew/2 3 pep-282-the-logging-package1640669
Ref: df91640669
Ref: PEP 282 logging 包-Footnote-11645337
Ref: PEP 282 logging 包-Footnote-21645386
Node: PEP 285 布尔类型1645435
Ref: whatsnew/2 3 pep-285-a-boolean-type1645596
Ref: dfa1645596
Ref: whatsnew/2 3 section-bool1645596
Ref: dfb1645596
Ref: PEP 285 布尔类型-Footnote-11648026
Ref: PEP 285 布尔类型-Footnote-21648075
Node: PEP 293 Codec Error Handling Callbacks1648124
Ref: whatsnew/2 3 pep-293-codec-error-handling-callbacks1648313
Ref: dfc1648313
Ref: PEP 293 Codec Error Handling Callbacks-Footnote-11649827
Node: PEP 301 Distutils的软件包索引和元数据1649876
Ref: whatsnew/2 3 pep-301-package-index-and-metadata-for-distutils1650069
Ref: dff1650069
Ref: whatsnew/2 3 section-pep3011650069
Ref: e001650069
Ref: PEP 301 Distutils的软件包索引和元数据-Footnote-11651690
Ref: PEP 301 Distutils的软件包索引和元数据-Footnote-21651726
Node: PEP 302 New Import Hooks1651775
Ref: whatsnew/2 3 pep-302-new-import-hooks1651956
Ref: e011651956
Ref: whatsnew/2 3 section-pep3021651956
Ref: df31651956
Ref: PEP 302 New Import Hooks-Footnote-11654546
Ref: PEP 302 New Import Hooks-Footnote-21654595
Ref: PEP 302 New Import Hooks-Footnote-31654644
Node: PEP 305 逗号分隔文件1654693
Ref: whatsnew/2 3 pep-305-comma-separated-files1654854
Ref: e021654854
Ref: whatsnew/2 3 section-pep3051654854
Ref: e031654854
Node: PEP 307 Pickle Enhancements1656329
Ref: whatsnew/2 3 pep-307-pickle-enhancements1656478
Ref: e051656478
Ref: whatsnew/2 3 section-pep3071656478
Ref: e061656478
Ref: PEP 307 Pickle Enhancements-Footnote-11658442
Ref: PEP 307 Pickle Enhancements-Footnote-21658491
Ref: PEP 307 Pickle Enhancements-Footnote-31658540
Node: 扩展切片1658589
Ref: whatsnew/2 3 extended-slices1658740
Ref: e0a1658740
Ref: whatsnew/2 3 section-slices1658740
Ref: e0b1658740
Node: 其他语言特性修改<13>1662114
Ref: whatsnew/2 3 other-language-changes1662274
Ref: e0d1662274
Ref: 其他语言特性修改<13>-Footnote-11670049
Ref: 其他语言特性修改<13>-Footnote-21670121
Node: String Changes1670175
Ref: whatsnew/2 3 string-changes1670279
Ref: e131670279
Node: 性能优化<12>1672734
Ref: whatsnew/2 3 optimizations1672838
Ref: e141672838
Node: 新增，改进和弃用的模块<4>1674279
Ref: whatsnew/2 3 new-improved-and-deprecated-modules1674466
Ref: e161674466
Ref: 新增，改进和弃用的模块<4>-Footnote-11699051
Node: Date/Time 类型1699090
Ref: whatsnew/2 3 date-time-type1699203
Ref: e1a1699203
Node: optparse 模块1701469
Ref: whatsnew/2 3 the-optparse-module1701582
Ref: e1b1701582
Node: Pymalloc A Specialized Object Allocator1703636
Ref: whatsnew/2 3 pymalloc-a-specialized-object-allocator1703824
Ref: e1c1703824
Ref: whatsnew/2 3 section-pymalloc1703824
Ref: e1d1703824
Node: 构建和 C API 的改变<12>1707704
Ref: whatsnew/2 3 build-and-c-api-changes1707882
Ref: e1f1707882
Node: Port-Specific Changes<3>1711302
Ref: whatsnew/2 3 port-specific-changes1711392
Ref: e241711392
Node: Other Changes and Fixes<2>1712627
Ref: whatsnew/2 3 other-changes-and-fixes1712786
Ref: e251712786
Ref: whatsnew/2 3 section-other1712786
Ref: e151712786
Node: 移植到 Python 2 31715260
Ref: whatsnew/2 3 porting-to-python-2-31715399
Ref: e281715399
Node: 致谢<5>1718202
Ref: whatsnew/2 3 acknowledgements1718306
Ref: e291718306
Ref: whatsnew/2 3 acks1718306
Ref: e2a1718306
Node: Python 2 2 有什么新变化1718845
Ref: whatsnew/2 2 doc1719005
Ref: e2b1719005
Ref: whatsnew/2 2 what-s-new-in-python-2-21719005
Ref: e2c1719005
Node: 概述1719694
Ref: whatsnew/2 2 introduction1719814
Ref: e2d1719814
Ref: 概述-Footnote-11720768
Ref: 概述-Footnote-21720817
Node: PEPs 252 and 253 Type and Class Changes1720866
Ref: whatsnew/2 2 peps-252-and-253-type-and-class-changes1721012
Ref: e2e1721012
Node: Old and New Classes1724440
Ref: whatsnew/2 2 old-and-new-classes1724555
Ref: e301724555
Ref: Old and New Classes-Footnote-11726960
Node: Descriptors1727009
Ref: whatsnew/2 2 descriptors1727170
Ref: e311727170
Node: Multiple Inheritance The Diamond Rule1731030
Ref: whatsnew/2 2 multiple-inheritance-the-diamond-rule1731188
Ref: e321731188
Ref: Multiple Inheritance The Diamond Rule-Footnote-11734073
Node: Attribute Access1734122
Ref: whatsnew/2 2 attribute-access1734282
Ref: e331734282
Node: Related Links1738099
Ref: whatsnew/2 2 related-links1738213
Ref: e361738213
Ref: whatsnew/2 2 sect-rellinks1738213
Ref: e2f1738213
Ref: Related Links-Footnote-11739706
Ref: Related Links-Footnote-21739755
Ref: Related Links-Footnote-31739804
Ref: Related Links-Footnote-41739853
Ref: Related Links-Footnote-51739902
Node: PEP 234 Iterators1739951
Ref: whatsnew/2 2 pep-234-iterators1740119
Ref: e371740119
Ref: PEP 234 Iterators-Footnote-11745001
Node: PEP 255 Simple Generators<2>1745050
Ref: whatsnew/2 2 pep-255-simple-generators1745214
Ref: e3a1745214
Ref: PEP 255 Simple Generators<2>-Footnote-11751254
Ref: PEP 255 Simple Generators<2>-Footnote-21751303
Node: PEP 237 统一长整数和整数<2>1751352
Ref: whatsnew/2 2 pep-237-unifying-long-integers-and-integers1751537
Ref: e3b1751537
Ref: PEP 237 统一长整数和整数<2>-Footnote-11753215
Node: PEP 238 Changing the Division Operator1753264
Ref: whatsnew/2 2 pep-238-changing-the-division-operator1753436
Ref: e3c1753436
Ref: PEP 238 Changing the Division Operator-Footnote-11757068
Ref: PEP 238 Changing the Division Operator-Footnote-21757117
Ref: PEP 238 Changing the Division Operator-Footnote-31757166
Node: Unicode Changes1757215
Ref: whatsnew/2 2 unicode-changes1757373
Ref: e3e1757373
Ref: Unicode Changes-Footnote-11759992
Ref: Unicode Changes-Footnote-21760041
Node: PEP 227 Nested Scopes1760090
Ref: whatsnew/2 2 pep-227-nested-scopes1760237
Ref: e401760237
Ref: PEP 227 Nested Scopes-Footnote-11764564
Node: 新增和改进的模块<3>1764613
Ref: whatsnew/2 2 new-and-improved-modules1764774
Ref: e411764774
Ref: 新增和改进的模块<3>-Footnote-11771384
Ref: 新增和改进的模块<3>-Footnote-21771433
Ref: 新增和改进的模块<3>-Footnote-31771482
Ref: 新增和改进的模块<3>-Footnote-41771531
Ref: 新增和改进的模块<3>-Footnote-51771580
Node: Interpreter Changes and Fixes1771628
Ref: whatsnew/2 2 interpreter-changes-and-fixes1771794
Ref: e421771794
Node: Other Changes and Fixes<3>1776551
Ref: whatsnew/2 2 other-changes-and-fixes1776699
Ref: e541776699
Ref: Other Changes and Fixes<3>-Footnote-11783353
Node: 致谢<6>1783402
Ref: whatsnew/2 2 acknowledgements1783512
Ref: e571783512
Node: Python 2 1 有什么新变化1784031
Ref: whatsnew/2 1 doc1784191
Ref: e581784191
Ref: whatsnew/2 1 what-s-new-in-python-2-11784191
Ref: e591784191
Node: 概述<2>1785166
Ref: whatsnew/2 1 introduction1785274
Ref: e5a1785274
Node: PEP 227 Nested Scopes<2>1786351
Ref: whatsnew/2 1 pep-227-nested-scopes1786497
Ref: e5b1786497
Ref: PEP 227 Nested Scopes<2>-Footnote-11790847
Ref: PEP 227 Nested Scopes<2>-Footnote-21790896
Ref: PEP 227 Nested Scopes<2>-Footnote-31790945
Node: PEP 236 __future__ Directives1790994
Ref: whatsnew/2 1 pep-236-future-directives1791155
Ref: e5c1791155
Ref: PEP 236 __future__ Directives-Footnote-11792377
Node: PEP 207 Rich Comparisons1792426
Ref: whatsnew/2 1 pep-207-rich-comparisons1792588
Ref: e5d1792588
Ref: PEP 207 Rich Comparisons-Footnote-11795980
Ref: PEP 207 Rich Comparisons-Footnote-21796029
Node: PEP 230 Warning Framework1796078
Ref: whatsnew/2 1 pep-230-warning-framework1796235
Ref: e5f1796235
Ref: PEP 230 Warning Framework-Footnote-11799504
Ref: PEP 230 Warning Framework-Footnote-21799553
Node: PEP 229 New Build System1799602
Ref: whatsnew/2 1 pep-229-new-build-system1799758
Ref: e611799758
Ref: PEP 229 New Build System-Footnote-11801667
Node: PEP 205 Weak References1801716
Ref: whatsnew/2 1 pep-205-weak-references1801874
Ref: e621801874
Ref: PEP 205 Weak References-Footnote-11804970
Node: PEP 232 Function Attributes1805019
Ref: whatsnew/2 1 pep-232-function-attributes1805208
Ref: e631805208
Ref: PEP 232 Function Attributes-Footnote-11806705
Node: PEP 235 Importing Modules on Case-Insensitive Platforms1806754
Ref: whatsnew/2 1 pep-235-importing-modules-on-case-insensitive-platforms1806952
Ref: e641806952
Node: PEP 217 Interactive Display Hook1807855
Ref: whatsnew/2 1 pep-217-interactive-display-hook1808052
Ref: e661808052
Ref: PEP 217 Interactive Display Hook-Footnote-11808966
Node: PEP 208 New Coercion Model1809015
Ref: whatsnew/2 1 pep-208-new-coercion-model1809192
Ref: e681809192
Ref: PEP 208 New Coercion Model-Footnote-11810808
Node: PEP 241 Metadata in Python Packages1810857
Ref: whatsnew/2 1 pep-241-metadata-in-python-packages1811029
Ref: e691811029
Ref: PEP 241 Metadata in Python Packages-Footnote-11813061
Ref: PEP 241 Metadata in Python Packages-Footnote-21813110
Ref: PEP 241 Metadata in Python Packages-Footnote-31813159
Ref: PEP 241 Metadata in Python Packages-Footnote-41813208
Node: 新增和改进的模块<4>1813257
Ref: whatsnew/2 1 new-and-improved-modules1813429
Ref: e6a1813429
Node: Other Changes and Fixes<4>1819253
Ref: whatsnew/2 1 other-changes-and-fixes1819399
Ref: e6d1819399
Node: 致谢<7>1825333
Ref: whatsnew/2 1 acknowledgements1825443
Ref: e6e1825443
Node: Python 2 0 有什么新变化1825664
Ref: whatsnew/2 0 doc1825807
Ref: e6f1825807
Ref: whatsnew/2 0 what-s-new-in-python-2-01825807
Ref: e701825807
Node: 概述<3>1826393
Ref: whatsnew/2 0 introduction1826499
Ref: e711826499
Node: What About Python 1 6?1827369
Ref: whatsnew/2 0 what-about-python-1-61827499
Ref: e721827499
Node: 新开发流程1828740
Ref: whatsnew/2 0 new-development-process1828871
Ref: e731828871
Ref: 新开发流程-Footnote-11833982
Ref: 新开发流程-Footnote-21834031
Ref: 新开发流程-Footnote-31834080
Node: Unicode<2>1834129
Ref: whatsnew/2 0 unicode1834253
Ref: e741834253
Ref: Unicode<2>-Footnote-11840423
Node: 列表推导式1840472
Ref: whatsnew/2 0 list-comprehensions1840601
Ref: e751840601
Node: Augmented Assignment1844319
Ref: whatsnew/2 0 augmented-assignment1844456
Ref: e761844456
Node: 字符串的方法1846002
Ref: whatsnew/2 0 string-methods1846152
Ref: e791846152
Node: Garbage Collection of Cycles1848007
Ref: whatsnew/2 0 garbage-collection-of-cycles1848155
Ref: e7a1848155
Node: 其他核心变化1851494
Ref: whatsnew/2 0 other-core-changes1851641
Ref: e7b1851641
Node: Minor Language Changes1851920
Ref: whatsnew/2 0 minor-language-changes1852035
Ref: e7c1852035
Node: Changes to Built-in Functions1857114
Ref: whatsnew/2 0 changes-to-built-in-functions1857229
Ref: e811857229
Node: 移植 Python 2 01859511
Ref: whatsnew/2 0 porting-to-2-01859649
Ref: e841859649
Node: 扩展/嵌入更改1864972
Ref: whatsnew/2 0 extending-embedding-changes1865125
Ref: e851865125
Node: Distutils：使模块易于安装1868925
Ref: whatsnew/2 0 distutils-making-modules-easy-to-install1869071
Ref: e861869071
Node: XML 模块1872395
Ref: whatsnew/2 0 xml-modules1872534
Ref: e871872534
Node: SAX2 Support1873429
Ref: whatsnew/2 0 sax2-support1873508
Ref: e881873508
Node: DOM Support1875146
Ref: whatsnew/2 0 dom-support1875255
Ref: e891875255
Node: Relationship to PyXML1878083
Ref: whatsnew/2 0 relationship-to-pyxml1878171
Ref: e8a1878171
Node: 模块更改1879461
Ref: whatsnew/2 0 module-changes1879582
Ref: e8b1879582
Node: 新增模块<7>1882046
Ref: whatsnew/2 0 new-modules1882168
Ref: e8c1882168
Node: IDLE 改进1886158
Ref: whatsnew/2 0 idle-improvements1886292
Ref: e8e1886292
Node: 删除和弃用的模块1887401
Ref: whatsnew/2 0 deleted-and-deprecated-modules1887529
Ref: e8f1887529
Node: 致谢<8>1888261
Ref: whatsnew/2 0 acknowledgements1888369
Ref: e901888369
Ref: 致谢<8>-Footnote-11888867
Ref: 致谢<8>-Footnote-21888930
Node: 更新日志1888969
Ref: whatsnew/changelog doc1889074
Ref: e911889074
Ref: whatsnew/changelog changelog1889074
Ref: 14d1889074
Ref: whatsnew/changelog id11889074
Ref: e921889074
Node: Python 3 8 12 final1893081
Ref: whatsnew/changelog python-3-8-12-final1893183
Ref: e931893183
Node: 安全1893358
Ref: whatsnew/changelog security1893444
Ref: e941893444
Ref: 安全-Footnote-11894562
Ref: 安全-Footnote-21894605
Ref: 安全-Footnote-31894648
Ref: 安全-Footnote-41894691
Node: 核心与内置1894734
Ref: whatsnew/changelog core-and-builtins1894832
Ref: e961894832
Ref: 核心与内置-Footnote-11895346
Ref: 核心与内置-Footnote-21895389
Ref: 核心与内置-Footnote-31895432
Node: 库1895475
Ref: whatsnew/changelog library1895576
Ref: e971895576
Ref: 库-Footnote-11895803
Node: 文档<2>1895846
Ref: whatsnew/changelog documentation1895939
Ref: e981895939
Ref: 文档<2>-Footnote-11896161
Node: Windows1896204
Ref: whatsnew/changelog windows1896299
Ref: e991896299
Ref: Windows-Footnote-11896432
Node: macOS1896475
Ref: whatsnew/changelog macos1896552
Ref: e9a1896552
Ref: macOS-Footnote-11897055
Ref: macOS-Footnote-21897098
Node: 最终版本Python 3 8 111897141
Ref: whatsnew/changelog python-3-8-11-final1897271
Ref: e9b1897271
Node: 安全<2>1897447
Ref: whatsnew/changelog id21897545
Ref: e9c1897545
Ref: 安全<2>-Footnote-11898183
Ref: 安全<2>-Footnote-21898226
Ref: 安全<2>-Footnote-31898269
Node: 核心与内置<2>1898312
Ref: whatsnew/changelog id31898425
Ref: e9d1898425
Ref: 核心与内置<2>-Footnote-11898645
Node: 库<2>1898688
Ref: whatsnew/changelog id41898783
Ref: e9e1898783
Node: Python 3 8 10 final1899000
Ref: whatsnew/changelog python-3-8-10-final1899129
Ref: e9f1899129
Node: 安全<3>1899398
Ref: whatsnew/changelog id51899490
Ref: ea01899490
Ref: 安全<3>-Footnote-11900401
Ref: 安全<3>-Footnote-21900444
Ref: 安全<3>-Footnote-31900487
Node: 核心与内置<3>1900530
Ref: whatsnew/changelog id61900637
Ref: ea31900637
Ref: 核心与内置<3>-Footnote-11901099
Ref: 核心与内置<3>-Footnote-21901142
Node: 库<3>1901185
Ref: whatsnew/changelog id71901292
Ref: ea41901292
Ref: 库<3>-Footnote-11904896
Ref: 库<3>-Footnote-21904939
Ref: 库<3>-Footnote-31904982
Ref: 库<3>-Footnote-41905025
Ref: 库<3>-Footnote-51905068
Ref: 库<3>-Footnote-61905111
Ref: 库<3>-Footnote-71905154
Ref: 库<3>-Footnote-81905197
Ref: 库<3>-Footnote-91905240
Ref: 库<3>-Footnote-101905283
Ref: 库<3>-Footnote-111905327
Ref: 库<3>-Footnote-121905371
Ref: 库<3>-Footnote-131905415
Ref: 库<3>-Footnote-141905459
Ref: 库<3>-Footnote-151905503
Ref: 库<3>-Footnote-161905547
Ref: 库<3>-Footnote-171905591
Ref: 库<3>-Footnote-181905635
Ref: 库<3>-Footnote-191905679
Ref: 库<3>-Footnote-201905723
Ref: 库<3>-Footnote-211905767
Ref: 库<3>-Footnote-221905811
Node: 文档<3>1905855
Ref: whatsnew/changelog id81905950
Ref: eaa1905950
Ref: 文档<3>-Footnote-11906384
Ref: 文档<3>-Footnote-21906427
Ref: 文档<3>-Footnote-31906470
Node: 测试1906513
Ref: whatsnew/changelog tests1906612
Ref: eab1906612
Ref: 测试-Footnote-11907173
Ref: 测试-Footnote-21907216
Ref: 测试-Footnote-31907259
Node: Windows<2>1907302
Ref: whatsnew/changelog id91907400
Ref: eac1907400
Ref: Windows<2>-Footnote-11908220
Ref: Windows<2>-Footnote-21908263
Ref: Windows<2>-Footnote-31908306
Ref: Windows<2>-Footnote-41908349
Ref: Windows<2>-Footnote-51908392
Node: macOS<2>1908435
Ref: whatsnew/changelog id101908534
Ref: eaf1908534
Ref: macOS<2>-Footnote-11909560
Ref: macOS<2>-Footnote-21909603
Ref: macOS<2>-Footnote-31909646
Node: IDLE<3>1909689
Ref: whatsnew/changelog idle1909783
Ref: eb01909783
Ref: IDLE<3>-Footnote-11909965
Node: C API1910008
Ref: whatsnew/changelog c-api1910085
Ref: eb11910085
Ref: C API-Footnote-11910490
Node: Python 3 8 9 final1910533
Ref: whatsnew/changelog python-3-8-9-final1910655
Ref: eb21910655
Node: 安全<4>1910910
Ref: whatsnew/changelog id111911001
Ref: eb31911001
Ref: 安全<4>-Footnote-11912074
Ref: 安全<4>-Footnote-21912117
Ref: 安全<4>-Footnote-31912160
Node: 核心与内置<4>1912203
Ref: whatsnew/changelog id121912309
Ref: eb61912309
Ref: 核心与内置<4>-Footnote-11913025
Ref: 核心与内置<4>-Footnote-21913068
Ref: 核心与内置<4>-Footnote-31913111
Node: 库<4>1913154
Ref: whatsnew/changelog id131913260
Ref: eb71913260
Ref: 库<4>-Footnote-11914751
Ref: 库<4>-Footnote-21914794
Ref: 库<4>-Footnote-31914837
Ref: 库<4>-Footnote-41914880
Ref: 库<4>-Footnote-51914923
Ref: 库<4>-Footnote-61914966
Ref: 库<4>-Footnote-71915009
Ref: 库<4>-Footnote-81915052
Ref: 库<4>-Footnote-91915095
Node: 文档<4>1915138
Ref: whatsnew/changelog id141915235
Ref: eb91915235
Ref: 文档<4>-Footnote-11915960
Ref: 文档<4>-Footnote-21916003
Ref: 文档<4>-Footnote-31916046
Ref: 文档<4>-Footnote-41916089
Ref: 文档<4>-Footnote-51916132
Node: 测试<2>1916181
Ref: whatsnew/changelog id151916278
Ref: eba1916278
Ref: 测试<2>-Footnote-11916581
Ref: 测试<2>-Footnote-21916624
Node: 构建1916667
Ref: whatsnew/changelog build1916763
Ref: ebb1916763
Ref: 构建-Footnote-11917029
Ref: 构建-Footnote-21917072
Node: macOS<3>1917115
Ref: whatsnew/changelog id161917209
Ref: ebc1917209
Ref: macOS<3>-Footnote-11917348
Node: IDLE<4>1917391
Ref: whatsnew/changelog id171917470
Ref: ebd1917470
Ref: IDLE<4>-Footnote-11917912
Ref: IDLE<4>-Footnote-21917955
Node: Python 3 8 8 final1917998
Ref: whatsnew/changelog python-3-8-8-final1918117
Ref: ebe1918117
Node: Python 3 8 8 rc11918240
Ref: whatsnew/changelog python-3-8-8-release-candidate-11918359
Ref: ebf1918359
Node: 安全<5>1918680
Ref: whatsnew/changelog id181918769
Ref: ec01918769
Ref: 安全<5>-Footnote-11919152
Ref: 安全<5>-Footnote-21919195
Node: 核心与内置<5>1919238
Ref: whatsnew/changelog id191919342
Ref: ec31919342
Ref: 核心与内置<5>-Footnote-11920051
Node: 库<5>1920094
Ref: whatsnew/changelog id201920198
Ref: ec41920198
Ref: 库<5>-Footnote-11922692
Ref: 库<5>-Footnote-21922735
Ref: 库<5>-Footnote-31922778
Ref: 库<5>-Footnote-41922821
Ref: 库<5>-Footnote-51922864
Ref: 库<5>-Footnote-61922907
Ref: 库<5>-Footnote-71922950
Ref: 库<5>-Footnote-81922993
Ref: 库<5>-Footnote-91923036
Ref: 库<5>-Footnote-101923079
Ref: 库<5>-Footnote-111923123
Ref: 库<5>-Footnote-121923167
Ref: 库<5>-Footnote-131923211
Ref: 库<5>-Footnote-141923255
Ref: 库<5>-Footnote-151923299
Ref: 库<5>-Footnote-161923343
Ref: 库<5>-Footnote-171923387
Node: 文档<5>1923431
Ref: whatsnew/changelog id211923526
Ref: ecc1923526
Ref: 文档<5>-Footnote-11923837
Ref: 文档<5>-Footnote-21923880
Node: 测试<3>1923923
Ref: whatsnew/changelog id221924021
Ref: ecd1924021
Ref: 测试<3>-Footnote-11924318
Ref: 测试<3>-Footnote-21924361
Node: 构建<2>1924404
Ref: whatsnew/changelog id231924503
Ref: ece1924503
Ref: 构建<2>-Footnote-11924633
Node: Windows<3>1924676
Ref: whatsnew/changelog id241924774
Ref: ecf1924774
Ref: Windows<3>-Footnote-11924985
Ref: Windows<3>-Footnote-21925028
Node: macOS<4>1925071
Ref: whatsnew/changelog id251925167
Ref: ed01925167
Ref: macOS<4>-Footnote-11925371
Ref: macOS<4>-Footnote-21925414
Node: IDLE<5>1925457
Ref: whatsnew/changelog id261925556
Ref: ed11925556
Ref: IDLE<5>-Footnote-11926301
Ref: IDLE<5>-Footnote-21926344
Ref: IDLE<5>-Footnote-31926387
Ref: IDLE<5>-Footnote-41926430
Ref: IDLE<5>-Footnote-51926473
Node: 工具/示例1926516
Ref: whatsnew/changelog tools-demos1926615
Ref: ed21926615
Ref: 工具/示例-Footnote-11926814
Node: C API<2>1926857
Ref: whatsnew/changelog id271926940
Ref: ed31926940
Ref: C API<2>-Footnote-11927308
Ref: C API<2>-Footnote-21927351
Node: Python 3 8 7 final1927394
Ref: whatsnew/changelog python-3-8-7-final1927527
Ref: ed51927527
Node: 核心与内置<6>1927749
Ref: whatsnew/changelog id281927837
Ref: ed61927837
Ref: 核心与内置<6>-Footnote-11928825
Ref: 核心与内置<6>-Footnote-21928868
Node: 库<6>1928911
Ref: whatsnew/changelog id291929017
Ref: eda1929017
Ref: 库<6>-Footnote-11930764
Ref: 库<6>-Footnote-21930807
Ref: 库<6>-Footnote-31930850
Ref: 库<6>-Footnote-41930893
Ref: 库<6>-Footnote-51930936
Ref: 库<6>-Footnote-61930979
Ref: 库<6>-Footnote-71931022
Ref: 库<6>-Footnote-81931065
Ref: 库<6>-Footnote-91931108
Ref: 库<6>-Footnote-101931151
Ref: 库<6>-Footnote-111931195
Node: 文档<6>1931239
Ref: whatsnew/changelog id301931336
Ref: edc1931336
Ref: 文档<6>-Footnote-11931505
Node: 构建<3>1931548
Ref: whatsnew/changelog id311931655
Ref: ede1931655
Ref: 构建<3>-Footnote-11932203
Ref: 构建<3>-Footnote-21932246
Node: 工具/示例<2>1932289
Ref: whatsnew/changelog id321932378
Ref: edf1932378
Ref: 工具/示例<2>-Footnote-11932582
Node: Python 3 8 7 release candidate 11932625
Ref: whatsnew/changelog python-3-8-7-release-candidate-11932760
Ref: ee01932760
Node: 安全<6>1933095
Ref: whatsnew/changelog id331933200
Ref: ee11933200
Ref: 安全<6>-Footnote-11933841
Ref: 安全<6>-Footnote-21933884
Ref: 安全<6>-Footnote-31933927
Node: 核心与内置<7>1933970
Ref: whatsnew/changelog id341934090
Ref: ee21934090
Ref: 核心与内置<7>-Footnote-11935149
Ref: 核心与内置<7>-Footnote-21935192
Ref: 核心与内置<7>-Footnote-31935235
Ref: 核心与内置<7>-Footnote-41935278
Ref: 核心与内置<7>-Footnote-51935321
Node: 库<7>1935364
Ref: whatsnew/changelog id351935484
Ref: ee41935484
Ref: 库<7>-Footnote-11941171
Ref: 库<7>-Footnote-21941214
Ref: 库<7>-Footnote-31941257
Ref: 库<7>-Footnote-41941300
Ref: 库<7>-Footnote-51941343
Ref: 库<7>-Footnote-61941386
Ref: 库<7>-Footnote-71941429
Ref: 库<7>-Footnote-81941472
Ref: 库<7>-Footnote-91941515
Ref: 库<7>-Footnote-101941558
Ref: 库<7>-Footnote-111941602
Ref: 库<7>-Footnote-121941646
Ref: 库<7>-Footnote-131941690
Ref: 库<7>-Footnote-141941734
Ref: 库<7>-Footnote-151941778
Ref: 库<7>-Footnote-161941822
Ref: 库<7>-Footnote-171941866
Ref: 库<7>-Footnote-181941910
Ref: 库<7>-Footnote-191941954
Ref: 库<7>-Footnote-201941998
Ref: 库<7>-Footnote-211942042
Ref: 库<7>-Footnote-221942114
Ref: 库<7>-Footnote-231942158
Ref: 库<7>-Footnote-241942202
Ref: 库<7>-Footnote-251942246
Ref: 库<7>-Footnote-261942290
Ref: 库<7>-Footnote-271942334
Ref: 库<7>-Footnote-281942378
Ref: 库<7>-Footnote-291942422
Ref: 库<7>-Footnote-301942466
Ref: 库<7>-Footnote-311942510
Ref: 库<7>-Footnote-321942554
Ref: 库<7>-Footnote-331942598
Ref: 库<7>-Footnote-341942642
Node: 文档<7>1942686
Ref: whatsnew/changelog id361942797
Ref: eec1942797
Ref: 文档<7>-Footnote-11943243
Ref: 文档<7>-Footnote-21943286
Ref: 文档<7>-Footnote-31943329
Ref: 文档<7>-Footnote-41943372
Node: 测试<4>1943415
Ref: whatsnew/changelog id371943529
Ref: eed1943529
Ref: 测试<4>-Footnote-11944810
Ref: 测试<4>-Footnote-21944853
Ref: 测试<4>-Footnote-31944896
Ref: 测试<4>-Footnote-41944939
Ref: 测试<4>-Footnote-51944982
Ref: 测试<4>-Footnote-61945025
Ref: 测试<4>-Footnote-71945068
Ref: 测试<4>-Footnote-81945111
Ref: 测试<4>-Footnote-91945154
Node: 构建<4>1945197
Ref: whatsnew/changelog id381945312
Ref: eee1945312
Ref: 构建<4>-Footnote-11945702
Node: Windows<4>1945745
Ref: whatsnew/changelog id391945859
Ref: eef1945859
Ref: Windows<4>-Footnote-11946272
Ref: Windows<4>-Footnote-21946315
Ref: Windows<4>-Footnote-31946358
Ref: Windows<4>-Footnote-41946401
Node: macOS<5>1946444
Ref: whatsnew/changelog id401946556
Ref: ef01946556
Ref: macOS<5>-Footnote-11946953
Ref: macOS<5>-Footnote-21946996
Ref: macOS<5>-Footnote-31947039
Node: IDLE<6>1947082
Ref: whatsnew/changelog id411947192
Ref: ef11947192
Ref: IDLE<6>-Footnote-11948023
Ref: IDLE<6>-Footnote-21948066
Ref: IDLE<6>-Footnote-31948109
Ref: IDLE<6>-Footnote-41948152
Ref: IDLE<6>-Footnote-51948195
Ref: IDLE<6>-Footnote-61948238
Node: C API<3>1948281
Ref: whatsnew/changelog id421948374
Ref: ef21948374
Ref: C API<3>-Footnote-11948565
Node: Python 3 8 6 final1948608
Ref: whatsnew/changelog python-3-8-6-final1948757
Ref: ef31948757
Node: 核心与内置<8>1948984
Ref: whatsnew/changelog id431949072
Ref: ef41949072
Ref: 核心与内置<8>-Footnote-11949249
Node: 库<8>1949292
Ref: whatsnew/changelog id441949398
Ref: ef51949398
Ref: 库<8>-Footnote-11950687
Ref: 库<8>-Footnote-21950730
Ref: 库<8>-Footnote-31950773
Ref: 库<8>-Footnote-41950816
Ref: 库<8>-Footnote-51950859
Ref: 库<8>-Footnote-61950902
Ref: 库<8>-Footnote-71950945
Ref: 库<8>-Footnote-81950988
Ref: 库<8>-Footnote-91951031
Node: 文档<8>1951074
Ref: whatsnew/changelog id451951171
Ref: ef61951171
Ref: 文档<8>-Footnote-11951561
Ref: 文档<8>-Footnote-21951604
Node: 测试<5>1951647
Ref: whatsnew/changelog id461951748
Ref: ef71951748
Ref: 测试<5>-Footnote-11951889
Node: Windows<5>1951932
Ref: whatsnew/changelog id471952031
Ref: ef81952031
Ref: Windows<5>-Footnote-11952194
Node: IDLE<7>1952237
Ref: whatsnew/changelog id481952318
Ref: ef91952318
Ref: IDLE<7>-Footnote-11952547
Ref: IDLE<7>-Footnote-21952590
Node: Python 3 8 6 release candidate 11952633
Ref: whatsnew/changelog python-3-8-6-release-candidate-11952768
Ref: efa1952768
Node: 核心与内置<9>1953023
Ref: whatsnew/changelog id491953125
Ref: efb1953125
Ref: 核心与内置<9>-Footnote-11953569
Ref: 核心与内置<9>-Footnote-21953612
Ref: 核心与内置<9>-Footnote-31953655
Node: 库<9>1953698
Ref: whatsnew/changelog id501953818
Ref: efd1953818
Ref: 库<9>-Footnote-11956281
Ref: 库<9>-Footnote-21956324
Ref: 库<9>-Footnote-31956367
Ref: 库<9>-Footnote-41956410
Ref: 库<9>-Footnote-51956453
Ref: 库<9>-Footnote-61956496
Ref: 库<9>-Footnote-71956539
Ref: 库<9>-Footnote-81956582
Ref: 库<9>-Footnote-91956625
Ref: 库<9>-Footnote-101956668
Ref: 库<9>-Footnote-111956712
Ref: 库<9>-Footnote-121956756
Ref: 库<9>-Footnote-131956800
Ref: 库<9>-Footnote-141956844
Ref: 库<9>-Footnote-151956888
Ref: 库<9>-Footnote-161956932
Ref: 库<9>-Footnote-171956976
Ref: 库<9>-Footnote-181957020
Ref: 库<9>-Footnote-191957064
Node: 文档<9>1957108
Ref: whatsnew/changelog id511957220
Ref: eff1957220
Ref: 文档<9>-Footnote-11957962
Ref: 文档<9>-Footnote-21958005
Ref: 文档<9>-Footnote-31958048
Ref: 文档<9>-Footnote-41958091
Ref: 文档<9>-Footnote-51958134
Node: Windows<6>1958177
Ref: whatsnew/changelog id521958290
Ref: f011958290
Ref: Windows<6>-Footnote-11958478
Ref: Windows<6>-Footnote-21958521
Node: IDLE<8>1958564
Ref: whatsnew/changelog id531958676
Ref: f021958676
Ref: IDLE<8>-Footnote-11959025
Ref: IDLE<8>-Footnote-21959068
Node: C API<4>1959111
Ref: whatsnew/changelog id541959204
Ref: f031959204
Ref: C API<4>-Footnote-11959398
Node: Python 3 8 5 final1959441
Ref: whatsnew/changelog python-3-8-5-final1959576
Ref: f041959576
Node: 安全<7>1959825
Ref: whatsnew/changelog id551959917
Ref: f051959917
Ref: 安全<7>-Footnote-11960235
Ref: 安全<7>-Footnote-21960278
Ref: 安全<7>-Footnote-31960321
Node: 核心与内置<10>1960364
Ref: whatsnew/changelog id561960472
Ref: f061960472
Ref: 核心与内置<10>-Footnote-11960794
Node: 库<10>1960837
Ref: whatsnew/changelog id571960946
Ref: f071960946
Ref: 库<10>-Footnote-11961274
Ref: 库<10>-Footnote-21961317
Node: 文档<10>1961360
Ref: whatsnew/changelog id581961459
Ref: f081961459
Ref: 文档<10>-Footnote-11961640
Node: 构建<5>1961683
Ref: whatsnew/changelog id591961783
Ref: f091961783
Ref: 构建<5>-Footnote-11961990
Node: macOS<6>1962033
Ref: whatsnew/changelog id601962130
Ref: f0a1962130
Ref: macOS<6>-Footnote-11962264
Node: IDLE<9>1962307
Ref: whatsnew/changelog id611962386
Ref: f0b1962386
Ref: IDLE<9>-Footnote-11962558
Node: Python 3 8 4 final1962601
Ref: whatsnew/changelog python-3-8-4-final1962736
Ref: f0c1962736
Node: 安全<8>1962924
Ref: whatsnew/changelog id621963016
Ref: f0d1963016
Ref: 安全<8>-Footnote-11963314
Ref: 安全<8>-Footnote-21963357
Node: 核心与内置<11>1963400
Ref: whatsnew/changelog id631963508
Ref: f0e1963508
Ref: 核心与内置<11>-Footnote-11964383
Ref: 核心与内置<11>-Footnote-21964426
Ref: 核心与内置<11>-Footnote-31964469
Ref: 核心与内置<11>-Footnote-41964512
Ref: 核心与内置<11>-Footnote-51964555
Node: 库<11>1964598
Ref: whatsnew/changelog id641964705
Ref: f0f1964705
Ref: 库<11>-Footnote-11965369
Ref: 库<11>-Footnote-21965412
Ref: 库<11>-Footnote-31965455
Ref: 库<11>-Footnote-41965498
Node: IDLE<10>1965541
Ref: whatsnew/changelog id651965620
Ref: f101965620
Ref: IDLE<10>-Footnote-11965912
Ref: IDLE<10>-Footnote-21965955
Node: Python 3 8 4 release candidate 11965998
Ref: whatsnew/changelog python-3-8-4-release-candidate-11966133
Ref: f111966133
Node: 安全<9>1966468
Ref: whatsnew/changelog id661966574
Ref: f121966574
Ref: 安全<9>-Footnote-11967113
Ref: 安全<9>-Footnote-21967156
Node: 核心与内置<12>1967199
Ref: whatsnew/changelog id671967321
Ref: f131967321
Ref: 核心与内置<12>-Footnote-11968802
Ref: 核心与内置<12>-Footnote-21968845
Ref: 核心与内置<12>-Footnote-31968888
Ref: 核心与内置<12>-Footnote-41968931
Ref: 核心与内置<12>-Footnote-51968974
Ref: 核心与内置<12>-Footnote-61969017
Ref: 核心与内置<12>-Footnote-71969060
Ref: 核心与内置<12>-Footnote-81969103
Node: 库<12>1969146
Ref: whatsnew/changelog id681969268
Ref: f171969268
Ref: 库<12>-Footnote-11973760
Ref: 库<12>-Footnote-21973803
Ref: 库<12>-Footnote-31973846
Ref: 库<12>-Footnote-41973889
Ref: 库<12>-Footnote-51973932
Ref: 库<12>-Footnote-61973975
Ref: 库<12>-Footnote-71974018
Ref: 库<12>-Footnote-81974061
Ref: 库<12>-Footnote-91974104
Ref: 库<12>-Footnote-101974147
Ref: 库<12>-Footnote-111974191
Ref: 库<12>-Footnote-121974235
Ref: 库<12>-Footnote-131974279
Ref: 库<12>-Footnote-141974323
Ref: 库<12>-Footnote-151974367
Ref: 库<12>-Footnote-161974411
Ref: 库<12>-Footnote-171974455
Ref: 库<12>-Footnote-181974499
Ref: 库<12>-Footnote-191974543
Ref: 库<12>-Footnote-201974587
Ref: 库<12>-Footnote-211974631
Ref: 库<12>-Footnote-221974675
Ref: 库<12>-Footnote-231974719
Ref: 库<12>-Footnote-241974763
Ref: 库<12>-Footnote-251974807
Ref: 库<12>-Footnote-261974851
Ref: 库<12>-Footnote-271974895
Ref: 库<12>-Footnote-281974939
Ref: 库<12>-Footnote-291974983
Node: 测试<6>1975027
Ref: whatsnew/changelog id691975139
Ref: f1b1975139
Ref: 测试<6>-Footnote-11976368
Ref: 测试<6>-Footnote-21976411
Ref: 测试<6>-Footnote-31976454
Ref: 测试<6>-Footnote-41976497
Ref: 测试<6>-Footnote-51976540
Ref: 测试<6>-Footnote-61976583
Ref: 测试<6>-Footnote-71976626
Node: 构建<6>1976669
Ref: whatsnew/changelog id701976784
Ref: f1d1976784
Ref: 构建<6>-Footnote-11977020
Ref: 构建<6>-Footnote-21977063
Node: Windows<7>1977106
Ref: whatsnew/changelog id711977220
Ref: f1e1977220
Ref: Windows<7>-Footnote-11978109
Ref: Windows<7>-Footnote-21978152
Ref: Windows<7>-Footnote-31978195
Ref: Windows<7>-Footnote-41978238
Ref: Windows<7>-Footnote-51978281
Ref: Windows<7>-Footnote-61978324
Node: macOS<7>1978367
Ref: whatsnew/changelog id721978480
Ref: f221978480
Ref: macOS<7>-Footnote-11979239
Ref: macOS<7>-Footnote-21979282
Ref: macOS<7>-Footnote-31979325
Ref: macOS<7>-Footnote-41979368
Node: IDLE<11>1979411
Ref: whatsnew/changelog id731979530
Ref: f231979530
Ref: IDLE<11>-Footnote-11979848
Ref: IDLE<11>-Footnote-21979891
Ref: IDLE<11>-Footnote-31979934
Node: 工具/示例<3>1979977
Ref: whatsnew/changelog id741980079
Ref: f241980079
Ref: 工具/示例<3>-Footnote-11980464
Ref: 工具/示例<3>-Footnote-21980507
Node: Python 3 8 3 final1980550
Ref: whatsnew/changelog python-3-8-3-final1980699
Ref: f251980699
Node: 核心与内置<13>1980912
Ref: whatsnew/changelog id751981002
Ref: f261981002
Ref: 核心与内置<13>-Footnote-11981579
Ref: 核心与内置<13>-Footnote-21981622
Ref: 核心与内置<13>-Footnote-31981665
Node: 库<13>1981708
Ref: whatsnew/changelog id761981817
Ref: f271981817
Ref: 库<13>-Footnote-11982448
Ref: 库<13>-Footnote-21982491
Ref: 库<13>-Footnote-31982534
Ref: 库<13>-Footnote-41982577
Node: 文档<11>1982620
Ref: whatsnew/changelog id771982720
Ref: f291982720
Ref: 文档<11>-Footnote-11982954
Ref: 文档<11>-Footnote-21982997
Node: Windows<8>1983040
Ref: whatsnew/changelog id781983141
Ref: f2a1983141
Ref: Windows<8>-Footnote-11983307
Node: C API<5>1983350
Ref: whatsnew/changelog id791983432
Ref: f2b1983432
Ref: C API<5>-Footnote-11983684
Node: Python 3 8 3 release candidate 11983727
Ref: whatsnew/changelog python-3-8-3-release-candidate-11983866
Ref: f2c1983866
Node: 安全<10>1984243
Ref: whatsnew/changelog id801984350
Ref: f2d1984350
Ref: 安全<10>-Footnote-11985061
Ref: 安全<10>-Footnote-21985104
Ref: 安全<10>-Footnote-31985147
Node: 核心与内置<14>1985190
Ref: whatsnew/changelog id811985313
Ref: f2e1985313
Ref: 核心与内置<14>-Footnote-11987151
Ref: 核心与内置<14>-Footnote-21987194
Ref: 核心与内置<14>-Footnote-31987237
Ref: 核心与内置<14>-Footnote-41987280
Ref: 核心与内置<14>-Footnote-51987323
Ref: 核心与内置<14>-Footnote-61987366
Ref: 核心与内置<14>-Footnote-71987409
Ref: 核心与内置<14>-Footnote-81987452
Ref: 核心与内置<14>-Footnote-91987495
Node: 库<14>1987538
Ref: whatsnew/changelog id821987661
Ref: f301987661
Ref: 库<14>-Footnote-11993572
Ref: 库<14>-Footnote-21993615
Ref: 库<14>-Footnote-31993658
Ref: 库<14>-Footnote-41993701
Ref: 库<14>-Footnote-51993744
Ref: 库<14>-Footnote-61993787
Ref: 库<14>-Footnote-71993830
Ref: 库<14>-Footnote-81993873
Ref: 库<14>-Footnote-91993916
Ref: 库<14>-Footnote-101993959
Ref: 库<14>-Footnote-111994003
Ref: 库<14>-Footnote-121994047
Ref: 库<14>-Footnote-131994091
Ref: 库<14>-Footnote-141994135
Ref: 库<14>-Footnote-151994179
Ref: 库<14>-Footnote-161994223
Ref: 库<14>-Footnote-171994267
Ref: 库<14>-Footnote-181994311
Ref: 库<14>-Footnote-191994355
Ref: 库<14>-Footnote-201994399
Ref: 库<14>-Footnote-211994443
Ref: 库<14>-Footnote-221994487
Ref: 库<14>-Footnote-231994531
Ref: 库<14>-Footnote-241994575
Ref: 库<14>-Footnote-251994619
Ref: 库<14>-Footnote-261994663
Ref: 库<14>-Footnote-271994707
Ref: 库<14>-Footnote-281994751
Ref: 库<14>-Footnote-291994795
Ref: 库<14>-Footnote-301994839
Ref: 库<14>-Footnote-311994883
Node: 文档<12>1994927
Ref: whatsnew/changelog id831995040
Ref: f3a1995040
Ref: 文档<12>-Footnote-11996056
Ref: 文档<12>-Footnote-21996099
Ref: 文档<12>-Footnote-31996142
Ref: 文档<12>-Footnote-41996185
Ref: 文档<12>-Footnote-51996234
Ref: 文档<12>-Footnote-61996277
Ref: 文档<12>-Footnote-71996320
Ref: 文档<12>-Footnote-81996363
Ref: 文档<12>-Footnote-91996406
Ref: 文档<12>-Footnote-101996449
Node: 测试<7>1996493
Ref: whatsnew/changelog id841996608
Ref: f3d1996608
Ref: 测试<7>-Footnote-11997930
Ref: 测试<7>-Footnote-21997973
Ref: 测试<7>-Footnote-31998016
Ref: 测试<7>-Footnote-41998059
Ref: 测试<7>-Footnote-51998102
Ref: 测试<7>-Footnote-61998145
Ref: 测试<7>-Footnote-71998188
Ref: 测试<7>-Footnote-81998230
Ref: 测试<7>-Footnote-91998273
Node: 构建<7>1998316
Ref: whatsnew/changelog id851998431
Ref: f401998431
Ref: 构建<7>-Footnote-11998915
Ref: 构建<7>-Footnote-21998958
Ref: 构建<7>-Footnote-31999001
Ref: 构建<7>-Footnote-41999044
Node: Windows<9>1999087
Ref: whatsnew/changelog id861999201
Ref: f411999201
Ref: Windows<9>-Footnote-12000143
Ref: Windows<9>-Footnote-22000186
Ref: Windows<9>-Footnote-32000229
Ref: Windows<9>-Footnote-42000272
Ref: Windows<9>-Footnote-52000315
Ref: Windows<9>-Footnote-62000358
Ref: Windows<9>-Footnote-72000401
Node: macOS<8>2000444
Ref: whatsnew/changelog id872000557
Ref: f422000557
Ref: macOS<8>-Footnote-12000760
Ref: macOS<8>-Footnote-22000803
Node: IDLE<12>2000846
Ref: whatsnew/changelog id882000965
Ref: f432000965
Ref: IDLE<12>-Footnote-12001800
Ref: IDLE<12>-Footnote-22001843
Ref: IDLE<12>-Footnote-32001886
Ref: IDLE<12>-Footnote-42001929
Ref: IDLE<12>-Footnote-52001972
Ref: IDLE<12>-Footnote-62002015
Node: 工具/示例<4>2002058
Ref: whatsnew/changelog id892002177
Ref: f442002177
Ref: 工具/示例<4>-Footnote-12002823
Ref: 工具/示例<4>-Footnote-22002866
Ref: 工具/示例<4>-Footnote-32002909
Node: C API<6>2002952
Ref: whatsnew/changelog id902003054
Ref: f452003054
Ref: C API<6>-Footnote-12003796
Ref: C API<6>-Footnote-22003839
Ref: C API<6>-Footnote-32003882
Ref: C API<6>-Footnote-42003925
Node: Python 3 8 2 正式版2003968
Ref: whatsnew/changelog python-3-8-2-final2004105
Ref: f492004105
Node: 核心与内置<15>2004299
Ref: whatsnew/changelog id912004393
Ref: f4a2004393
Ref: 核心与内置<15>-Footnote-12004844
Ref: 核心与内置<15>-Footnote-22004887
Node: 库<15>2004930
Ref: whatsnew/changelog id922005043
Ref: f4b2005043
Ref: 库<15>-Footnote-12005725
Ref: 库<15>-Footnote-22005768
Ref: 库<15>-Footnote-32005811
Ref: 库<15>-Footnote-42005854
Node: 文档<13>2005897
Ref: whatsnew/changelog id932005999
Ref: f4c2005999
Ref: 文档<13>-Footnote-12006423
Ref: 文档<13>-Footnote-22006466
Ref: 文档<13>-Footnote-32006509
Node: IDLE<13>2006552
Ref: whatsnew/changelog id942006638
Ref: f4d2006638
Ref: IDLE<13>-Footnote-12006772
Node: Python 3 8 2 rc22006815
Ref: whatsnew/changelog python-3-8-2-release-candidate-22006936
Ref: f4e2006936
Node: 安全<11>2007122
Ref: whatsnew/changelog id952007213
Ref: f4f2007213
Ref: 安全<11>-Footnote-12007473
Node: 核心与内置<16>2007516
Ref: whatsnew/changelog id962007623
Ref: f502007623
Ref: 核心与内置<16>-Footnote-12008231
Ref: 核心与内置<16>-Footnote-22008274
Ref: 核心与内置<16>-Footnote-32008317
Ref: 核心与内置<16>-Footnote-42008360
Ref: 核心与内置<16>-Footnote-52008403
Node: 库<16>2008446
Ref: whatsnew/changelog id972008551
Ref: f522008551
Ref: 库<16>-Footnote-12009588
Ref: 库<16>-Footnote-22009631
Ref: 库<16>-Footnote-32009674
Ref: 库<16>-Footnote-42009717
Ref: 库<16>-Footnote-52009760
Ref: 库<16>-Footnote-62009803
Node: IDLE<14>2009896
Ref: whatsnew/changelog id982009973
Ref: f532009973
Ref: IDLE<14>-Footnote-12010129
Node: Python 3 8 2 rc12010172
Ref: whatsnew/changelog python-3-8-2-release-candidate-12010293
Ref: f542010293
Node: 安全<12>2010567
Ref: whatsnew/changelog id992010658
Ref: f552010658
Ref: 安全<12>-Footnote-12010932
Ref: 安全<12>-Footnote-22010975
Node: 核心与内置<17>2011018
Ref: whatsnew/changelog id1002011125
Ref: f562011125
Ref: 核心与内置<17>-Footnote-12012621
Ref: 核心与内置<17>-Footnote-22012664
Ref: 核心与内置<17>-Footnote-32012707
Ref: 核心与内置<17>-Footnote-42012750
Ref: 核心与内置<17>-Footnote-52012793
Ref: 核心与内置<17>-Footnote-62012836
Ref: 核心与内置<17>-Footnote-72012879
Ref: 核心与内置<17>-Footnote-82012922
Ref: 核心与内置<17>-Footnote-92012965
Ref: 核心与内置<17>-Footnote-102013008
Ref: 核心与内置<17>-Footnote-112013052
Node: 库<17>2013096
Ref: whatsnew/changelog id1012013203
Ref: f582013203
Ref: 库<17>-Footnote-12017544
Ref: 库<17>-Footnote-22017587
Ref: 库<17>-Footnote-32017630
Ref: 库<17>-Footnote-42017673
Ref: 库<17>-Footnote-52017716
Ref: 库<17>-Footnote-62017759
Ref: 库<17>-Footnote-72017802
Ref: 库<17>-Footnote-82017845
Ref: 库<17>-Footnote-92017888
Ref: 库<17>-Footnote-102017931
Ref: 库<17>-Footnote-112017975
Ref: 库<17>-Footnote-122018019
Ref: 库<17>-Footnote-132018063
Ref: 库<17>-Footnote-142018107
Ref: 库<17>-Footnote-152018151
Ref: 库<17>-Footnote-162018195
Ref: 库<17>-Footnote-172018239
Ref: 库<17>-Footnote-182018283
Ref: 库<17>-Footnote-192018327
Ref: 库<17>-Footnote-202018371
Ref: 库<17>-Footnote-212018415
Ref: 库<17>-Footnote-222018459
Ref: 库<17>-Footnote-232018503
Ref: 库<17>-Footnote-242018547
Ref: 库<17>-Footnote-252018591
Ref: 库<17>-Footnote-262018635
Ref: 库<17>-Footnote-272018679
Node: 文档<14>2018723
Ref: whatsnew/changelog id1022018820
Ref: f5b2018820
Ref: 文档<14>-Footnote-12019659
Ref: 文档<14>-Footnote-22019702
Ref: 文档<14>-Footnote-32019745
Ref: 文档<14>-Footnote-42019788
Ref: 文档<14>-Footnote-52019831
Ref: 文档<14>-Footnote-62019904
Node: 测试<8>2019946
Ref: whatsnew/changelog id1032020045
Ref: f5c2020045
Ref: 测试<8>-Footnote-12020514
Ref: 测试<8>-Footnote-22020557
Node: 构建<8>2020600
Ref: whatsnew/changelog id1042020700
Ref: f5e2020700
Ref: 构建<8>-Footnote-12020899
Node: Windows<10>2020942
Ref: whatsnew/changelog id1052021041
Ref: f5f2021041
Ref: Windows<10>-Footnote-12021782
Ref: Windows<10>-Footnote-22021825
Ref: Windows<10>-Footnote-32021868
Ref: Windows<10>-Footnote-42021911
Ref: Windows<10>-Footnote-52021954
Node: IDLE<15>2021997
Ref: whatsnew/changelog id1062022078
Ref: f602022078
Ref: IDLE<15>-Footnote-12022823
Ref: IDLE<15>-Footnote-22022866
Ref: IDLE<15>-Footnote-32022909
Ref: IDLE<15>-Footnote-42022952
Ref: IDLE<15>-Footnote-52022995
Ref: IDLE<15>-Footnote-62023038
Node: Python 3 8 1 正式版2023081
Ref: whatsnew/changelog python-3-8-1-final2023202
Ref: f612023202
Node: 核心与内置<18>2023438
Ref: whatsnew/changelog id1072023532
Ref: f622023532
Ref: 核心与内置<18>-Footnote-12024228
Ref: 核心与内置<18>-Footnote-22024271
Ref: 核心与内置<18>-Footnote-32024314
Node: 库<18>2024357
Ref: whatsnew/changelog id1082024469
Ref: f632024469
Ref: 库<18>-Footnote-12024991
Ref: 库<18>-Footnote-22025034
Ref: 库<18>-Footnote-32025077
Node: 测试<9>2025120
Ref: whatsnew/changelog id1092025224
Ref: f642025224
Ref: 测试<9>-Footnote-12025422
Node: Windows<11>2025465
Ref: whatsnew/changelog id1102025570
Ref: f652025570
Ref: Windows<11>-Footnote-12025723
Node: macOS<9>2025766
Ref: whatsnew/changelog id1112025870
Ref: f662025870
Ref: macOS<9>-Footnote-12026040
Node: IDLE<16>2026083
Ref: whatsnew/changelog id1122026167
Ref: f672026167
Ref: IDLE<16>-Footnote-12026449
Ref: IDLE<16>-Footnote-22026492
Node: Python 3 8 1 rc12026535
Ref: whatsnew/changelog python-3-8-1-release-candidate-12026662
Ref: f682026662
Node: 安全<13>2026976
Ref: whatsnew/changelog id1132027067
Ref: f692027067
Ref: 安全<13>-Footnote-12028247
Ref: 安全<13>-Footnote-22028290
Ref: 安全<13>-Footnote-32028333
Ref: 安全<13>-Footnote-42028376
Ref: 安全<13>-Footnote-52028419
Ref: 安全<13>-Footnote-62028462
Ref: 安全<13>-Footnote-72028505
Node: 核心与内置<19>2028548
Ref: whatsnew/changelog id1142028655
Ref: f6a2028655
Ref: 核心与内置<19>-Footnote-12029985
Ref: 核心与内置<19>-Footnote-22030028
Ref: 核心与内置<19>-Footnote-32030071
Ref: 核心与内置<19>-Footnote-42030114
Ref: 核心与内置<19>-Footnote-52030157
Ref: 核心与内置<19>-Footnote-62030200
Ref: 核心与内置<19>-Footnote-72030243
Ref: 核心与内置<19>-Footnote-82030286
Ref: 核心与内置<19>-Footnote-92030329
Node: 库<19>2030372
Ref: whatsnew/changelog id1152030479
Ref: f6b2030479
Ref: 库<19>-Footnote-12035822
Ref: 库<19>-Footnote-22035865
Ref: 库<19>-Footnote-32035908
Ref: 库<19>-Footnote-42035951
Ref: 库<19>-Footnote-52035994
Ref: 库<19>-Footnote-62036037
Ref: 库<19>-Footnote-72036080
Ref: 库<19>-Footnote-82036123
Ref: 库<19>-Footnote-92036166
Ref: 库<19>-Footnote-102036209
Ref: 库<19>-Footnote-112036253
Ref: 库<19>-Footnote-122036297
Ref: 库<19>-Footnote-132036341
Ref: 库<19>-Footnote-142036385
Ref: 库<19>-Footnote-152036429
Ref: 库<19>-Footnote-162036473
Ref: 库<19>-Footnote-172036517
Ref: 库<19>-Footnote-182036561
Ref: 库<19>-Footnote-192036605
Ref: 库<19>-Footnote-202036649
Ref: 库<19>-Footnote-212036693
Ref: 库<19>-Footnote-222036737
Ref: 库<19>-Footnote-232036781
Ref: 库<19>-Footnote-242036825
Ref: 库<19>-Footnote-252036869
Ref: 库<19>-Footnote-262036913
Ref: 库<19>-Footnote-272036957
Ref: 库<19>-Footnote-282037001
Ref: 库<19>-Footnote-292037045
Ref: 库<19>-Footnote-302037089
Ref: 库<19>-Footnote-312037133
Ref: 库<19>-Footnote-322037177
Ref: 库<19>-Footnote-332037221
Node: 文档<15>2037265
Ref: whatsnew/changelog id1162037363
Ref: f6d2037363
Ref: 文档<15>-Footnote-12038007
Ref: 文档<15>-Footnote-22038050
Ref: 文档<15>-Footnote-32038093
Ref: 文档<15>-Footnote-42038136
Node: 测试<10>2038179
Ref: whatsnew/changelog id1172038279
Ref: f6e2038279
Ref: 测试<10>-Footnote-12039640
Ref: 测试<10>-Footnote-22039683
Ref: 测试<10>-Footnote-32039726
Ref: 测试<10>-Footnote-42039769
Ref: 测试<10>-Footnote-52039812
Ref: 测试<10>-Footnote-62039855
Ref: 测试<10>-Footnote-72039898
Node: 构建<9>2039941
Ref: whatsnew/changelog id1182040042
Ref: f702040042
Ref: 构建<9>-Footnote-12040652
Ref: 构建<9>-Footnote-22040695
Ref: 构建<9>-Footnote-32040738
Ref: 构建<9>-Footnote-42040781
Node: Windows<12>2040824
Ref: whatsnew/changelog id1192040924
Ref: f712040924
Ref: Windows<12>-Footnote-12041461
Ref: Windows<12>-Footnote-22041504
Ref: Windows<12>-Footnote-32041547
Ref: Windows<12>-Footnote-42041590
Ref: Windows<12>-Footnote-52041633
Node: macOS<10>2041676
Ref: whatsnew/changelog id1202041775
Ref: f722041775
Ref: macOS<10>-Footnote-12042083
Node: IDLE<17>2042126
Ref: whatsnew/changelog id1212042222
Ref: f732042222
Ref: IDLE<17>-Footnote-12042944
Ref: IDLE<17>-Footnote-22042987
Ref: IDLE<17>-Footnote-32043030
Ref: IDLE<17>-Footnote-42043073
Ref: IDLE<17>-Footnote-52043115
Node: C API<7>2043158
Ref: whatsnew/changelog id1222043236
Ref: f742043236
Ref: C API<7>-Footnote-12043823
Ref: C API<7>-Footnote-22043866
Ref: C API<7>-Footnote-32043909
Node: Python 3 8 0 正式版2043952
Ref: whatsnew/changelog python-3-8-0-final2044073
Ref: f762044073
Node: 核心与内置<20>2044367
Ref: whatsnew/changelog id1232044461
Ref: f772044461
Ref: 核心与内置<20>-Footnote-12045148
Ref: 核心与内置<20>-Footnote-22045191
Node: 库<20>2045234
Ref: whatsnew/changelog id1242045347
Ref: f782045347
Ref: 库<20>-Footnote-12046706
Ref: 库<20>-Footnote-22046749
Ref: 库<20>-Footnote-32046792
Ref: 库<20>-Footnote-42046835
Ref: 库<20>-Footnote-52046878
Ref: 库<20>-Footnote-62046921
Ref: 库<20>-Footnote-72046964
Node: 文档<16>2047007
Ref: whatsnew/changelog id1252047111
Ref: f7e2047111
Ref: 文档<16>-Footnote-12047269
Node: 测试<11>2047312
Ref: whatsnew/changelog id1262047420
Ref: f7f2047420
Ref: 测试<11>-Footnote-12047859
Node: Windows<13>2047902
Ref: whatsnew/changelog id1272048008
Ref: f802048008
Ref: Windows<13>-Footnote-12048301
Ref: Windows<13>-Footnote-22048344
Ref: Windows<13>-Footnote-32048387
Node: IDLE<18>2048430
Ref: whatsnew/changelog id1282048542
Ref: f812048542
Ref: IDLE<18>-Footnote-12048841
Node: 工具/示例<5>2048884
Ref: whatsnew/changelog id1292048993
Ref: f822048993
Ref: 工具/示例<5>-Footnote-12049349
Ref: 工具/示例<5>-Footnote-22049392
Node: C API<8>2049435
Ref: whatsnew/changelog id1302049527
Ref: f842049527
Ref: C API<8>-Footnote-12049855
Node: Python 3 8 0 rc12049898
Ref: whatsnew/changelog python-3-8-0-release-candidate-12050022
Ref: f852050022
Node: 安全<14>2050371
Ref: whatsnew/changelog id1312050462
Ref: f862050462
Ref: 安全<14>-Footnote-12051081
Ref: 安全<14>-Footnote-22051124
Ref: 安全<14>-Footnote-32051167
Ref: 安全<14>-Footnote-42051210
Node: 核心与内置<21>2051253
Ref: whatsnew/changelog id1322051360
Ref: f882051360
Ref: 核心与内置<21>-Footnote-12053894
Ref: 核心与内置<21>-Footnote-22053937
Ref: 核心与内置<21>-Footnote-32053980
Ref: 核心与内置<21>-Footnote-42054029
Ref: 核心与内置<21>-Footnote-52054072
Ref: 核心与内置<21>-Footnote-62054115
Ref: 核心与内置<21>-Footnote-72054158
Ref: 核心与内置<21>-Footnote-82054201
Ref: 核心与内置<21>-Footnote-92054244
Ref: 核心与内置<21>-Footnote-102054287
Ref: 核心与内置<21>-Footnote-112054331
Ref: 核心与内置<21>-Footnote-122054375
Ref: 核心与内置<21>-Footnote-132054419
Ref: 核心与内置<21>-Footnote-142054463
Ref: 核心与内置<21>-Footnote-152054507
Node: 库<21>2054551
Ref: whatsnew/changelog id1332054658
Ref: f892054658
Ref: 库<21>-Footnote-12063770
Ref: 库<21>-Footnote-22063813
Ref: 库<21>-Footnote-32063856
Ref: 库<21>-Footnote-42063899
Ref: 库<21>-Footnote-52063942
Ref: 库<21>-Footnote-62063985
Ref: 库<21>-Footnote-72064028
Ref: 库<21>-Footnote-82064071
Ref: 库<21>-Footnote-92064114
Ref: 库<21>-Footnote-102064157
Ref: 库<21>-Footnote-112064201
Ref: 库<21>-Footnote-122064245
Ref: 库<21>-Footnote-132064289
Ref: 库<21>-Footnote-142064333
Ref: 库<21>-Footnote-152064377
Ref: 库<21>-Footnote-162064421
Ref: 库<21>-Footnote-172064465
Ref: 库<21>-Footnote-182064509
Ref: 库<21>-Footnote-192064553
Ref: 库<21>-Footnote-202064597
Ref: 库<21>-Footnote-212064641
Ref: 库<21>-Footnote-222064685
Ref: 库<21>-Footnote-232064729
Ref: 库<21>-Footnote-242064773
Ref: 库<21>-Footnote-252064817
Ref: 库<21>-Footnote-262064861
Ref: 库<21>-Footnote-272064905
Ref: 库<21>-Footnote-282064949
Ref: 库<21>-Footnote-292064993
Ref: 库<21>-Footnote-302065037
Ref: 库<21>-Footnote-312065081
Ref: 库<21>-Footnote-322065189
Ref: 库<21>-Footnote-332065233
Ref: 库<21>-Footnote-342065277
Ref: 库<21>-Footnote-352065321
Ref: 库<21>-Footnote-362065365
Ref: 库<21>-Footnote-372065409
Ref: 库<21>-Footnote-382065453
Ref: 库<21>-Footnote-392065497
Ref: 库<21>-Footnote-402065541
Ref: 库<21>-Footnote-412065585
Ref: 库<21>-Footnote-422065629
Ref: 库<21>-Footnote-432065673
Ref: 库<21>-Footnote-442065717
Ref: 库<21>-Footnote-452065761
Ref: 库<21>-Footnote-462065805
Ref: 库<21>-Footnote-472065849
Ref: 库<21>-Footnote-482065893
Ref: 库<21>-Footnote-492065937
Ref: 库<21>-Footnote-502065981
Ref: 库<21>-Footnote-512066025
Ref: 库<21>-Footnote-522066069
Ref: 库<21>-Footnote-532066113
Ref: 库<21>-Footnote-542066157
Ref: 库<21>-Footnote-552066201
Ref: 库<21>-Footnote-562066245
Ref: 库<21>-Footnote-572066289
Ref: 库<21>-Footnote-582066333
Ref: 库<21>-Footnote-592066377
Node: 文档<17>2066421
Ref: whatsnew/changelog id1342066519
Ref: f8d2066519
Ref: 文档<17>-Footnote-12067780
Ref: 文档<17>-Footnote-22067823
Ref: 文档<17>-Footnote-32067866
Ref: 文档<17>-Footnote-42067909
Ref: 文档<17>-Footnote-52067952
Ref: 文档<17>-Footnote-62067995
Ref: 文档<17>-Footnote-72068038
Ref: 文档<17>-Footnote-82068081
Ref: 文档<17>-Footnote-92068124
Ref: 文档<17>-Footnote-102068167
Node: 测试<12>2068211
Ref: whatsnew/changelog id1352068312
Ref: f8f2068312
Ref: 测试<12>-Footnote-12070545
Ref: 测试<12>-Footnote-22070588
Ref: 测试<12>-Footnote-32070631
Ref: 测试<12>-Footnote-42070674
Ref: 测试<12>-Footnote-52070717
Ref: 测试<12>-Footnote-62070760
Ref: 测试<12>-Footnote-72070803
Ref: 测试<12>-Footnote-82070846
Ref: 测试<12>-Footnote-92070889
Ref: 测试<12>-Footnote-102070932
Ref: 测试<12>-Footnote-112070976
Ref: 测试<12>-Footnote-122071020
Ref: 测试<12>-Footnote-132071064
Node: 构建<10>2071108
Ref: whatsnew/changelog id1362071210
Ref: f912071210
Ref: 构建<10>-Footnote-12072494
Ref: 构建<10>-Footnote-22072537
Ref: 构建<10>-Footnote-32072580
Ref: 构建<10>-Footnote-42072623
Ref: 构建<10>-Footnote-52072666
Node: Windows<14>2072709
Ref: whatsnew/changelog id1372072810
Ref: f922072810
Ref: Windows<14>-Footnote-12074766
Ref: Windows<14>-Footnote-22074809
Ref: Windows<14>-Footnote-32074852
Ref: Windows<14>-Footnote-42074895
Ref: Windows<14>-Footnote-52074938
Ref: Windows<14>-Footnote-62074981
Ref: Windows<14>-Footnote-72075024
Ref: Windows<14>-Footnote-82075067
Ref: Windows<14>-Footnote-92075110
Ref: Windows<14>-Footnote-102075153
Ref: Windows<14>-Footnote-112075197
Ref: Windows<14>-Footnote-122075241
Ref: Windows<14>-Footnote-132075285
Ref: Windows<14>-Footnote-142075329
Ref: Windows<14>-Footnote-152075373
Ref: Windows<14>-Footnote-162075417
Ref: Windows<14>-Footnote-172075461
Node: macOS<11>2075505
Ref: whatsnew/changelog id1382075604
Ref: f942075604
Ref: macOS<11>-Footnote-12075843
Ref: macOS<11>-Footnote-22075886
Node: IDLE<19>2075929
Ref: whatsnew/changelog id1392076033
Ref: f952076033
Ref: IDLE<19>-Footnote-12077186
Ref: IDLE<19>-Footnote-22077229
Ref: IDLE<19>-Footnote-32077272
Ref: IDLE<19>-Footnote-42077315
Ref: IDLE<19>-Footnote-52077358
Ref: IDLE<19>-Footnote-62077401
Node: 工具/示例<6>2077444
Ref: whatsnew/changelog id1402077547
Ref: f962077547
Ref: 工具/示例<6>-Footnote-12077853
Ref: 工具/示例<6>-Footnote-22077896
Node: C API<9>2077939
Ref: whatsnew/changelog id1412078025
Ref: f972078025
Ref: C API<9>-Footnote-12078750
Ref: C API<9>-Footnote-22078793
Ref: C API<9>-Footnote-32078836
Ref: C API<9>-Footnote-42078879
Node: Python 3 8 0 beta 42078922
Ref: whatsnew/changelog python-3-8-0-beta-42079043
Ref: f9b2079043
Node: 安全<15>2079399
Ref: whatsnew/changelog id1422079493
Ref: f9c2079493
Ref: 安全<15>-Footnote-12079770
Node: 核心与内置<22>2079813
Ref: whatsnew/changelog id1432079923
Ref: f9d2079923
Ref: 核心与内置<22>-Footnote-12081345
Ref: 核心与内置<22>-Footnote-22081388
Ref: 核心与内置<22>-Footnote-32081431
Ref: 核心与内置<22>-Footnote-42081474
Ref: 核心与内置<22>-Footnote-52081517
Ref: 核心与内置<22>-Footnote-62081560
Ref: 核心与内置<22>-Footnote-72081609
Ref: 核心与内置<22>-Footnote-82081652
Ref: 核心与内置<22>-Footnote-92081695
Node: 库<22>2081738
Ref: whatsnew/changelog id1442081848
Ref: f9e2081848
Ref: 库<22>-Footnote-12087877
Ref: 库<22>-Footnote-22087920
Ref: 库<22>-Footnote-32087963
Ref: 库<22>-Footnote-42088006
Ref: 库<22>-Footnote-52088049
Ref: 库<22>-Footnote-62088092
Ref: 库<22>-Footnote-72088135
Ref: 库<22>-Footnote-82088178
Ref: 库<22>-Footnote-92088221
Ref: 库<22>-Footnote-102088264
Ref: 库<22>-Footnote-112088308
Ref: 库<22>-Footnote-122088352
Ref: 库<22>-Footnote-132088396
Ref: 库<22>-Footnote-142088440
Ref: 库<22>-Footnote-152088484
Ref: 库<22>-Footnote-162088528
Ref: 库<22>-Footnote-172088572
Ref: 库<22>-Footnote-182088616
Ref: 库<22>-Footnote-192088660
Ref: 库<22>-Footnote-202088704
Ref: 库<22>-Footnote-212088748
Ref: 库<22>-Footnote-222088792
Ref: 库<22>-Footnote-232088836
Ref: 库<22>-Footnote-242088880
Ref: 库<22>-Footnote-252088924
Ref: 库<22>-Footnote-262088968
Ref: 库<22>-Footnote-272089012
Ref: 库<22>-Footnote-282089056
Ref: 库<22>-Footnote-292089100
Ref: 库<22>-Footnote-302089144
Ref: 库<22>-Footnote-312089188
Ref: 库<22>-Footnote-322089232
Ref: 库<22>-Footnote-332089276
Ref: 库<22>-Footnote-342089320
Ref: 库<22>-Footnote-352089364
Ref: 库<22>-Footnote-362089408
Ref: 库<22>-Footnote-372089452
Ref: 库<22>-Footnote-382089496
Node: 文档<18>2089540
Ref: whatsnew/changelog id1452089641
Ref: fa02089641
Ref: 文档<18>-Footnote-12090400
Ref: 文档<18>-Footnote-22090443
Ref: 文档<18>-Footnote-32090486
Ref: 文档<18>-Footnote-42090529
Ref: 文档<18>-Footnote-52090572
Ref: 文档<18>-Footnote-62090615
Node: 测试<13>2090658
Ref: whatsnew/changelog id1462090762
Ref: fa12090762
Ref: 测试<13>-Footnote-12090924
Node: 构建<11>2090967
Ref: whatsnew/changelog id1472091072
Ref: fa22091072
Ref: 构建<11>-Footnote-12091355
Node: Windows<15>2091398
Ref: whatsnew/changelog id1482091502
Ref: fa32091502
Ref: Windows<15>-Footnote-12092984
Ref: Windows<15>-Footnote-22093027
Ref: Windows<15>-Footnote-32093069
Ref: Windows<15>-Footnote-42093111
Ref: Windows<15>-Footnote-52093154
Ref: Windows<15>-Footnote-62093197
Ref: Windows<15>-Footnote-72093240
Ref: Windows<15>-Footnote-82093283
Ref: Windows<15>-Footnote-92093326
Node: macOS<12>2093369
Ref: whatsnew/changelog id1492093471
Ref: fa52093471
Ref: macOS<12>-Footnote-12093735
Node: IDLE<20>2093778
Ref: whatsnew/changelog id1502093885
Ref: fa62093885
Ref: IDLE<20>-Footnote-12094450
Ref: IDLE<20>-Footnote-22094493
Ref: IDLE<20>-Footnote-32094536
Ref: IDLE<20>-Footnote-42094579
Ref: IDLE<20>-Footnote-52094622
Node: 工具/示例<7>2094665
Ref: whatsnew/changelog id1512094772
Ref: fa72094772
Ref: 工具/示例<7>-Footnote-12095094
Ref: 工具/示例<7>-Footnote-22095137
Node: C API<10>2095180
Ref: whatsnew/changelog id1522095270
Ref: fa82095270
Ref: C API<10>-Footnote-12095576
Ref: C API<10>-Footnote-22095619
Node: Python 3 8 0 beta 32095662
Ref: whatsnew/changelog python-3-8-0-beta-32095786
Ref: fa92095786
Node: 安全<16>2096102
Ref: whatsnew/changelog id1532096196
Ref: faa2096196
Ref: 安全<16>-Footnote-12096381
Node: 核心与内置<23>2096424
Ref: whatsnew/changelog id1542096534
Ref: fab2096534
Ref: 核心与内置<23>-Footnote-12096928
Ref: 核心与内置<23>-Footnote-22096971
Node: 库<23>2097014
Ref: whatsnew/changelog id1552097124
Ref: fac2097124
Ref: 库<23>-Footnote-12100087
Ref: 库<23>-Footnote-22100130
Ref: 库<23>-Footnote-32100204
Ref: 库<23>-Footnote-42100247
Ref: 库<23>-Footnote-52100290
Ref: 库<23>-Footnote-62100333
Ref: 库<23>-Footnote-72100376
Ref: 库<23>-Footnote-82100419
Ref: 库<23>-Footnote-92100462
Ref: 库<23>-Footnote-102100505
Ref: 库<23>-Footnote-112100549
Ref: 库<23>-Footnote-122100593
Ref: 库<23>-Footnote-132100637
Ref: 库<23>-Footnote-142100681
Ref: 库<23>-Footnote-152100725
Ref: 库<23>-Footnote-162100769
Node: 文档<19>2100813
Ref: whatsnew/changelog id1562100914
Ref: fb12100914
Ref: 文档<19>-Footnote-12102046
Ref: 文档<19>-Footnote-22102089
Ref: 文档<19>-Footnote-32102132
Ref: 文档<19>-Footnote-42102175
Ref: 文档<19>-Footnote-52102218
Ref: 文档<19>-Footnote-62102261
Ref: 文档<19>-Footnote-72102304
Ref: 文档<19>-Footnote-82102347
Node: 测试<14>2102390
Ref: whatsnew/changelog id1572102494
Ref: fb22102494
Ref: 测试<14>-Footnote-12103163
Ref: 测试<14>-Footnote-22103206
Ref: 测试<14>-Footnote-32103249
Ref: 测试<14>-Footnote-42103292
Node: 构建<12>2103335
Ref: whatsnew/changelog id1582103440
Ref: fb42103440
Ref: 构建<12>-Footnote-12104205
Node: Windows<16>2104248
Ref: whatsnew/changelog id1592104351
Ref: fb52104351
Ref: Windows<16>-Footnote-12104551
Node: IDLE<21>2104594
Ref: whatsnew/changelog id1602104703
Ref: fb62104703
Ref: IDLE<21>-Footnote-12106182
Ref: IDLE<21>-Footnote-22106225
Ref: IDLE<21>-Footnote-32106268
Ref: IDLE<21>-Footnote-42106311
Ref: IDLE<21>-Footnote-52106354
Ref: IDLE<21>-Footnote-62106397
Ref: IDLE<21>-Footnote-72106440
Ref: IDLE<21>-Footnote-82106483
Ref: IDLE<21>-Footnote-92106526
Node: 工具/示例<8>2106569
Ref: whatsnew/changelog id1612106658
Ref: fb72106658
Ref: 工具/示例<8>-Footnote-12106820
Node: Python 3 8 0 beta 22106863
Ref: whatsnew/changelog python-3-8-0-beta-22106987
Ref: fb82106987
Node: 安全<17>2107308
Ref: whatsnew/changelog id1622107402
Ref: fb92107402
Ref: 安全<17>-Footnote-12108502
Ref: 安全<17>-Footnote-22108545
Ref: 安全<17>-Footnote-32108588
Ref: 安全<17>-Footnote-42108631
Ref: 安全<17>-Footnote-52108674
Node: 核心与内置<24>2108717
Ref: whatsnew/changelog id1632108827
Ref: fbb2108827
Ref: 核心与内置<24>-Footnote-12110540
Ref: 核心与内置<24>-Footnote-22110583
Ref: 核心与内置<24>-Footnote-32110626
Ref: 核心与内置<24>-Footnote-42110669
Ref: 核心与内置<24>-Footnote-52110712
Ref: 核心与内置<24>-Footnote-62110755
Ref: 核心与内置<24>-Footnote-72110798
Ref: 核心与内置<24>-Footnote-82110841
Ref: 核心与内置<24>-Footnote-92110884
Ref: 核心与内置<24>-Footnote-102110927
Ref: 核心与内置<24>-Footnote-112110971
Ref: 核心与内置<24>-Footnote-122111015
Node: 库<24>2111059
Ref: whatsnew/changelog id1642111169
Ref: fbc2111169
Ref: 库<24>-Footnote-12116853
Ref: 库<24>-Footnote-22116896
Ref: 库<24>-Footnote-32116939
Ref: 库<24>-Footnote-42116982
Ref: 库<24>-Footnote-52117025
Ref: 库<24>-Footnote-62117068
Ref: 库<24>-Footnote-72117117
Ref: 库<24>-Footnote-82117160
Ref: 库<24>-Footnote-92117203
Ref: 库<24>-Footnote-102117246
Ref: 库<24>-Footnote-112117290
Ref: 库<24>-Footnote-122117334
Ref: 库<24>-Footnote-132117378
Ref: 库<24>-Footnote-142117422
Ref: 库<24>-Footnote-152117466
Ref: 库<24>-Footnote-162117510
Ref: 库<24>-Footnote-172117554
Ref: 库<24>-Footnote-182117598
Ref: 库<24>-Footnote-192117642
Ref: 库<24>-Footnote-202117686
Ref: 库<24>-Footnote-212117730
Ref: 库<24>-Footnote-222117774
Ref: 库<24>-Footnote-232117818
Ref: 库<24>-Footnote-242117862
Ref: 库<24>-Footnote-252117906
Ref: 库<24>-Footnote-262117950
Ref: 库<24>-Footnote-272117994
Ref: 库<24>-Footnote-282118038
Ref: 库<24>-Footnote-292118082
Ref: 库<24>-Footnote-302118126
Ref: 库<24>-Footnote-312118170
Ref: 库<24>-Footnote-322118214
Ref: 库<24>-Footnote-332118258
Ref: 库<24>-Footnote-342118302
Ref: 库<24>-Footnote-352118346
Ref: 库<24>-Footnote-362118390
Node: 文档<20>2118433
Ref: whatsnew/changelog id1652118534
Ref: fbe2118534
Ref: 文档<20>-Footnote-12118771
Node: 测试<15>2118814
Ref: whatsnew/changelog id1662118918
Ref: fc02118918
Ref: 测试<15>-Footnote-12121487
Ref: 测试<15>-Footnote-22121530
Ref: 测试<15>-Footnote-32121573
Ref: 测试<15>-Footnote-42121616
Ref: 测试<15>-Footnote-52121659
Ref: 测试<15>-Footnote-62121702
Ref: 测试<15>-Footnote-72121745
Ref: 测试<15>-Footnote-82121788
Ref: 测试<15>-Footnote-92121831
Ref: 测试<15>-Footnote-102121874
Ref: 测试<15>-Footnote-112121918
Ref: 测试<15>-Footnote-122121962
Ref: 测试<15>-Footnote-132122006
Ref: 测试<15>-Footnote-142122050
Ref: 测试<15>-Footnote-152122094
Ref: 测试<15>-Footnote-162122138
Ref: 测试<15>-Footnote-172122182
Node: 构建<13>2122226
Ref: whatsnew/changelog id1672122331
Ref: fc22122331
Ref: 构建<13>-Footnote-12122604
Node: Windows<17>2122647
Ref: whatsnew/changelog id1682122751
Ref: fc42122751
Ref: Windows<17>-Footnote-12123442
Ref: Windows<17>-Footnote-22123485
Ref: Windows<17>-Footnote-32123528
Ref: Windows<17>-Footnote-42123571
Ref: Windows<17>-Footnote-52123614
Ref: Windows<17>-Footnote-62123657
Node: macOS<13>2123700
Ref: whatsnew/changelog id1692123802
Ref: fc52123802
Ref: macOS<13>-Footnote-12124284
Ref: macOS<13>-Footnote-22124327
Ref: macOS<13>-Footnote-32124370
Node: IDLE<22>2124413
Ref: whatsnew/changelog id1702124513
Ref: fc62124513
Ref: IDLE<22>-Footnote-12125655
Ref: IDLE<22>-Footnote-22125698
Ref: IDLE<22>-Footnote-32125741
Ref: IDLE<22>-Footnote-42125784
Ref: IDLE<22>-Footnote-52125827
Ref: IDLE<22>-Footnote-62125870
Node: C API<11>2125912
Ref: whatsnew/changelog id1712125994
Ref: fc72125994
Ref: C API<11>-Footnote-12127170
Ref: C API<11>-Footnote-22127213
Ref: C API<11>-Footnote-32127256
Ref: C API<11>-Footnote-42127299
Ref: C API<11>-Footnote-52127342
Ref: C API<11>-Footnote-62127385
Ref: C API<11>-Footnote-72127428
Ref: C API<11>-Footnote-82127471
Node: Python 3 8 0 beta 12127514
Ref: whatsnew/changelog python-3-8-0-beta-12127639
Ref: fca2127639
Node: 安全<18>2127995
Ref: whatsnew/changelog id1722128089
Ref: fcb2128089
Ref: 安全<18>-Footnote-12128674
Ref: 安全<18>-Footnote-22128717
Ref: 安全<18>-Footnote-32128760
Node: 核心与内置<25>2128803
Ref: whatsnew/changelog id1732128913
Ref: fcc2128913
Ref: 核心与内置<25>-Footnote-12136969
Ref: 核心与内置<25>-Footnote-22137012
Ref: 核心与内置<25>-Footnote-32137055
Ref: 核心与内置<25>-Footnote-42137098
Ref: 核心与内置<25>-Footnote-52137141
Ref: 核心与内置<25>-Footnote-62137184
Ref: 核心与内置<25>-Footnote-72137227
Ref: 核心与内置<25>-Footnote-82137270
Ref: 核心与内置<25>-Footnote-92137313
Ref: 核心与内置<25>-Footnote-102137356
Ref: 核心与内置<25>-Footnote-112137400
Ref: 核心与内置<25>-Footnote-122137444
Ref: 核心与内置<25>-Footnote-132137488
Ref: 核心与内置<25>-Footnote-142137532
Ref: 核心与内置<25>-Footnote-152137576
Ref: 核心与内置<25>-Footnote-162137620
Ref: 核心与内置<25>-Footnote-172137664
Ref: 核心与内置<25>-Footnote-182137708
Ref: 核心与内置<25>-Footnote-192137751
Ref: 核心与内置<25>-Footnote-202137795
Ref: 核心与内置<25>-Footnote-212137839
Ref: 核心与内置<25>-Footnote-222137883
Ref: 核心与内置<25>-Footnote-232137926
Ref: 核心与内置<25>-Footnote-242137970
Ref: 核心与内置<25>-Footnote-252138014
Ref: 核心与内置<25>-Footnote-262138058
Ref: 核心与内置<25>-Footnote-272138102
Ref: 核心与内置<25>-Footnote-282138146
Ref: 核心与内置<25>-Footnote-292138190
Ref: 核心与内置<25>-Footnote-302138234
Ref: 核心与内置<25>-Footnote-312138278
Ref: 核心与内置<25>-Footnote-322138322
Ref: 核心与内置<25>-Footnote-332138366
Ref: 核心与内置<25>-Footnote-342138410
Ref: 核心与内置<25>-Footnote-352138454
Ref: 核心与内置<25>-Footnote-362138498
Ref: 核心与内置<25>-Footnote-372138542
Ref: 核心与内置<25>-Footnote-382138586
Ref: 核心与内置<25>-Footnote-392138630
Ref: 核心与内置<25>-Footnote-402138674
Ref: 核心与内置<25>-Footnote-412138718
Ref: 核心与内置<25>-Footnote-422138762
Ref: 核心与内置<25>-Footnote-432138806
Ref: 核心与内置<25>-Footnote-442138850
Node: 库<25>2138894
Ref: whatsnew/changelog id1742139004
Ref: fd22139004
Ref: 库<25>-Footnote-12157286
Ref: 库<25>-Footnote-22157329
Ref: 库<25>-Footnote-32157372
Ref: 库<25>-Footnote-42157415
Ref: 库<25>-Footnote-52157458
Ref: 库<25>-Footnote-62157501
Ref: 库<25>-Footnote-72157544
Ref: 库<25>-Footnote-82157587
Ref: 库<25>-Footnote-92157630
Ref: 库<25>-Footnote-102157673
Ref: 库<25>-Footnote-112157717
Ref: 库<25>-Footnote-122157761
Ref: 库<25>-Footnote-132157805
Ref: 库<25>-Footnote-142157849
Ref: 库<25>-Footnote-152157893
Ref: 库<25>-Footnote-162157937
Ref: 库<25>-Footnote-172157981
Ref: 库<25>-Footnote-182158025
Ref: 库<25>-Footnote-192158069
Ref: 库<25>-Footnote-202158113
Ref: 库<25>-Footnote-212158157
Ref: 库<25>-Footnote-222158201
Ref: 库<25>-Footnote-232158245
Ref: 库<25>-Footnote-242158289
Ref: 库<25>-Footnote-252158335
Ref: 库<25>-Footnote-262158379
Ref: 库<25>-Footnote-272158423
Ref: 库<25>-Footnote-282158467
Ref: 库<25>-Footnote-292158511
Ref: 库<25>-Footnote-302158555
Ref: 库<25>-Footnote-312158599
Ref: 库<25>-Footnote-322158643
Ref: 库<25>-Footnote-332158687
Ref: 库<25>-Footnote-342158731
Ref: 库<25>-Footnote-352158775
Ref: 库<25>-Footnote-362158819
Ref: 库<25>-Footnote-372158863
Ref: 库<25>-Footnote-382158907
Ref: 库<25>-Footnote-392158951
Ref: 库<25>-Footnote-402158995
Ref: 库<25>-Footnote-412159039
Ref: 库<25>-Footnote-422159083
Ref: 库<25>-Footnote-432159127
Ref: 库<25>-Footnote-442159171
Ref: 库<25>-Footnote-452159215
Ref: 库<25>-Footnote-462159259
Ref: 库<25>-Footnote-472159303
Ref: 库<25>-Footnote-482159347
Ref: 库<25>-Footnote-492159391
Ref: 库<25>-Footnote-502159435
Ref: 库<25>-Footnote-512159479
Ref: 库<25>-Footnote-522159523
Ref: 库<25>-Footnote-532159567
Ref: 库<25>-Footnote-542159611
Ref: 库<25>-Footnote-552159655
Ref: 库<25>-Footnote-562159699
Ref: 库<25>-Footnote-572159743
Ref: 库<25>-Footnote-582159787
Ref: 库<25>-Footnote-592159831
Ref: 库<25>-Footnote-602159875
Ref: 库<25>-Footnote-612159919
Ref: 库<25>-Footnote-622159963
Ref: 库<25>-Footnote-632160007
Ref: 库<25>-Footnote-642160051
Ref: 库<25>-Footnote-652160095
Ref: 库<25>-Footnote-662160139
Ref: 库<25>-Footnote-672160183
Ref: 库<25>-Footnote-682160227
Ref: 库<25>-Footnote-692160270
Ref: 库<25>-Footnote-702160314
Ref: 库<25>-Footnote-712160357
Ref: 库<25>-Footnote-722160401
Ref: 库<25>-Footnote-732160445
Ref: 库<25>-Footnote-742160489
Ref: 库<25>-Footnote-752160533
Ref: 库<25>-Footnote-762160577
Ref: 库<25>-Footnote-772160621
Ref: 库<25>-Footnote-782160665
Ref: 库<25>-Footnote-792160709
Ref: 库<25>-Footnote-802160753
Ref: 库<25>-Footnote-812160797
Ref: 库<25>-Footnote-822160841
Ref: 库<25>-Footnote-832160885
Ref: 库<25>-Footnote-842160929
Ref: 库<25>-Footnote-852160973
Ref: 库<25>-Footnote-862161017
Ref: 库<25>-Footnote-872161061
Ref: 库<25>-Footnote-882161105
Ref: 库<25>-Footnote-892161149
Ref: 库<25>-Footnote-902161193
Ref: 库<25>-Footnote-912161237
Ref: 库<25>-Footnote-922161281
Ref: 库<25>-Footnote-932161325
Ref: 库<25>-Footnote-942161369
Ref: 库<25>-Footnote-952161413
Ref: 库<25>-Footnote-962161457
Ref: 库<25>-Footnote-972161501
Ref: 库<25>-Footnote-982161545
Ref: 库<25>-Footnote-992161589
Ref: 库<25>-Footnote-1002161633
Ref: 库<25>-Footnote-1012161678
Ref: 库<25>-Footnote-1022161723
Ref: 库<25>-Footnote-1032161768
Ref: 库<25>-Footnote-1042161813
Ref: 库<25>-Footnote-1052161858
Ref: 库<25>-Footnote-1062161903
Ref: 库<25>-Footnote-1072161948
Node: 文档<21>2161993
Ref: whatsnew/changelog id1752162094
Ref: fe02162094
Ref: 文档<21>-Footnote-12164167
Ref: 文档<21>-Footnote-22164210
Ref: 文档<21>-Footnote-32164253
Ref: 文档<21>-Footnote-42164296
Ref: 文档<21>-Footnote-52164339
Ref: 文档<21>-Footnote-62164382
Ref: 文档<21>-Footnote-72164425
Ref: 文档<21>-Footnote-82164468
Ref: 文档<21>-Footnote-92164511
Ref: 文档<21>-Footnote-102164554
Ref: 文档<21>-Footnote-112164598
Ref: 文档<21>-Footnote-122164642
Ref: 文档<21>-Footnote-132164686
Ref: 文档<21>-Footnote-142164730
Node: 测试<16>2164774
Ref: whatsnew/changelog id1762164878
Ref: fe12164878
Ref: 测试<16>-Footnote-12166519
Ref: 测试<16>-Footnote-22166562
Ref: 测试<16>-Footnote-32166605
Ref: 测试<16>-Footnote-42166648
Ref: 测试<16>-Footnote-52166691
Ref: 测试<16>-Footnote-62166734
Ref: 测试<16>-Footnote-72166777
Ref: 测试<16>-Footnote-82166820
Ref: 测试<16>-Footnote-92166863
Ref: 测试<16>-Footnote-102166906
Node: 构建<14>2166950
Ref: whatsnew/changelog id1772167055
Ref: fe32167055
Ref: 构建<14>-Footnote-12168281
Ref: 构建<14>-Footnote-22168324
Node: Windows<18>2168367
Ref: whatsnew/changelog id1782168471
Ref: fe42168471
Ref: Windows<18>-Footnote-12168910
Ref: Windows<18>-Footnote-22168953
Ref: Windows<18>-Footnote-32168996
Ref: Windows<18>-Footnote-42169039
Node: macOS<14>2169082
Ref: whatsnew/changelog id1792169184
Ref: fe52169184
Ref: macOS<14>-Footnote-12169486
Node: IDLE<23>2169529
Ref: whatsnew/changelog id1802169636
Ref: fe62169636
Ref: IDLE<23>-Footnote-12170238
Ref: IDLE<23>-Footnote-22170281
Ref: IDLE<23>-Footnote-32170324
Ref: IDLE<23>-Footnote-42170367
Ref: IDLE<23>-Footnote-52170410
Ref: IDLE<23>-Footnote-62170453
Node: 工具/示例<9>2170496
Ref: whatsnew/changelog id1812170603
Ref: fe72170603
Ref: 工具/示例<9>-Footnote-12170802
Node: C API<12>2170845
Ref: whatsnew/changelog id1822170935
Ref: fe82170935
Ref: C API<12>-Footnote-12172270
Ref: C API<12>-Footnote-22172313
Ref: C API<12>-Footnote-32172362
Ref: C API<12>-Footnote-42172405
Ref: C API<12>-Footnote-52172448
Ref: C API<12>-Footnote-62172491
Ref: C API<12>-Footnote-72172540
Ref: C API<12>-Footnote-82172583
Ref: C API<12>-Footnote-92172626
Node: Python 3 8 0 alpha 42172669
Ref: whatsnew/changelog python-3-8-0-alpha-42172795
Ref: fea2172795
Node: 安全<19>2173154
Ref: whatsnew/changelog id1832173249
Ref: feb2173249
Ref: 安全<19>-Footnote-12174143
Ref: 安全<19>-Footnote-22174186
Ref: 安全<19>-Footnote-32174229
Node: 核心与内置<26>2174272
Ref: whatsnew/changelog id1842174383
Ref: fec2174383
Ref: 核心与内置<26>-Footnote-12177767
Ref: 核心与内置<26>-Footnote-22177810
Ref: 核心与内置<26>-Footnote-32177853
Ref: 核心与内置<26>-Footnote-42177896
Ref: 核心与内置<26>-Footnote-52177939
Ref: 核心与内置<26>-Footnote-62177982
Ref: 核心与内置<26>-Footnote-72178025
Ref: 核心与内置<26>-Footnote-82178068
Ref: 核心与内置<26>-Footnote-92178111
Ref: 核心与内置<26>-Footnote-102178160
Ref: 核心与内置<26>-Footnote-112178204
Ref: 核心与内置<26>-Footnote-122178248
Ref: 核心与内置<26>-Footnote-132178292
Ref: 核心与内置<26>-Footnote-142178336
Ref: 核心与内置<26>-Footnote-152178380
Ref: 核心与内置<26>-Footnote-162178424
Ref: 核心与内置<26>-Footnote-172178468
Ref: 核心与内置<26>-Footnote-182178512
Ref: 核心与内置<26>-Footnote-192178556
Ref: 核心与内置<26>-Footnote-202178600
Node: 库<26>2178644
Ref: whatsnew/changelog id1852178755
Ref: fed2178755
Ref: 库<26>-Footnote-12188051
Ref: 库<26>-Footnote-22188094
Ref: 库<26>-Footnote-32188137
Ref: 库<26>-Footnote-42188180
Ref: 库<26>-Footnote-52188225
Ref: 库<26>-Footnote-62188268
Ref: 库<26>-Footnote-72188311
Ref: 库<26>-Footnote-82188354
Ref: 库<26>-Footnote-92188397
Ref: 库<26>-Footnote-102188440
Ref: 库<26>-Footnote-112188484
Ref: 库<26>-Footnote-122188528
Ref: 库<26>-Footnote-132188572
Ref: 库<26>-Footnote-142188616
Ref: 库<26>-Footnote-152188660
Ref: 库<26>-Footnote-162188704
Ref: 库<26>-Footnote-172188748
Ref: 库<26>-Footnote-182188792
Ref: 库<26>-Footnote-192188836
Ref: 库<26>-Footnote-202188880
Ref: 库<26>-Footnote-212188924
Ref: 库<26>-Footnote-222188968
Ref: 库<26>-Footnote-232189012
Ref: 库<26>-Footnote-242189056
Ref: 库<26>-Footnote-252189100
Ref: 库<26>-Footnote-262189144
Ref: 库<26>-Footnote-272189188
Ref: 库<26>-Footnote-282189232
Ref: 库<26>-Footnote-292189276
Ref: 库<26>-Footnote-302189320
Ref: 库<26>-Footnote-312189364
Ref: 库<26>-Footnote-322189408
Ref: 库<26>-Footnote-332189452
Ref: 库<26>-Footnote-342189496
Ref: 库<26>-Footnote-352189540
Ref: 库<26>-Footnote-362189584
Ref: 库<26>-Footnote-372189628
Ref: 库<26>-Footnote-382189672
Ref: 库<26>-Footnote-392189716
Ref: 库<26>-Footnote-402189760
Ref: 库<26>-Footnote-412189804
Ref: 库<26>-Footnote-422189848
Ref: 库<26>-Footnote-432189892
Ref: 库<26>-Footnote-442189936
Ref: 库<26>-Footnote-452189980
Ref: 库<26>-Footnote-462190024
Ref: 库<26>-Footnote-472190068
Ref: 库<26>-Footnote-482190112
Ref: 库<26>-Footnote-492190156
Ref: 库<26>-Footnote-502190200
Ref: 库<26>-Footnote-512190244
Ref: 库<26>-Footnote-522190288
Ref: 库<26>-Footnote-532190332
Ref: 库<26>-Footnote-542190376
Node: 文档<22>2190420
Ref: whatsnew/changelog id1862190522
Ref: ff22190522
Ref: 文档<22>-Footnote-12191941
Ref: 文档<22>-Footnote-22191984
Ref: 文档<22>-Footnote-32192027
Ref: 文档<22>-Footnote-42192070
Ref: 文档<22>-Footnote-52192113
Ref: 文档<22>-Footnote-62192152
Ref: 文档<22>-Footnote-72192195
Ref: 文档<22>-Footnote-82192238
Ref: 文档<22>-Footnote-92192281
Ref: 文档<22>-Footnote-102192324
Ref: 文档<22>-Footnote-112192368
Ref: 文档<22>-Footnote-122192412
Node: 测试<17>2192456
Ref: whatsnew/changelog id1872192561
Ref: ff32192561
Ref: 测试<17>-Footnote-12194811
Ref: 测试<17>-Footnote-22194854
Ref: 测试<17>-Footnote-32194897
Ref: 测试<17>-Footnote-42194940
Ref: 测试<17>-Footnote-52194983
Ref: 测试<17>-Footnote-62195026
Ref: 测试<17>-Footnote-72195069
Ref: 测试<17>-Footnote-82195112
Ref: 测试<17>-Footnote-92195155
Ref: 测试<17>-Footnote-102195198
Ref: 测试<17>-Footnote-112195242
Ref: 测试<17>-Footnote-122195286
Ref: 测试<17>-Footnote-132195330
Ref: 测试<17>-Footnote-142195374
Ref: 测试<17>-Footnote-152195418
Node: 构建<15>2195462
Ref: whatsnew/changelog id1882195568
Ref: ff52195568
Ref: 构建<15>-Footnote-12198703
Ref: 构建<15>-Footnote-22198746
Ref: 构建<15>-Footnote-32198789
Ref: 构建<15>-Footnote-42198832
Ref: 构建<15>-Footnote-52198875
Ref: 构建<15>-Footnote-62198918
Ref: 构建<15>-Footnote-72198961
Ref: 构建<15>-Footnote-82199004
Ref: 构建<15>-Footnote-92199047
Ref: 构建<15>-Footnote-102199090
Ref: 构建<15>-Footnote-112199134
Ref: 构建<15>-Footnote-122199178
Ref: 构建<15>-Footnote-132199222
Node: Windows<19>2199266
Ref: whatsnew/changelog id1892199371
Ref: ff62199371
Ref: Windows<19>-Footnote-12202023
Ref: Windows<19>-Footnote-22202066
Ref: Windows<19>-Footnote-32202109
Ref: Windows<19>-Footnote-42202152
Ref: Windows<19>-Footnote-52202195
Ref: Windows<19>-Footnote-62202238
Ref: Windows<19>-Footnote-72202281
Ref: Windows<19>-Footnote-82202324
Ref: Windows<19>-Footnote-92202367
Ref: Windows<19>-Footnote-102202410
Ref: Windows<19>-Footnote-112202454
Ref: Windows<19>-Footnote-122202498
Node: macOS<15>2202542
Ref: whatsnew/changelog id1902202645
Ref: ff72202645
Ref: macOS<15>-Footnote-12202959
Ref: macOS<15>-Footnote-22203002
Node: IDLE<24>2203045
Ref: whatsnew/changelog id1912203154
Ref: ff82203154
Ref: IDLE<24>-Footnote-12203401
Node: 工具/示例<10>2203444
Ref: whatsnew/changelog id1922203553
Ref: ff92203553
Ref: 工具/示例<10>-Footnote-12203707
Node: C API<13>2203750
Ref: whatsnew/changelog id1932203842
Ref: ffa2203842
Ref: C API<13>-Footnote-12205842
Ref: C API<13>-Footnote-22205885
Ref: C API<13>-Footnote-32205928
Ref: C API<13>-Footnote-42205971
Ref: C API<13>-Footnote-52206014
Ref: C API<13>-Footnote-62206057
Node: Python 3 8 0 alpha 32206100
Ref: whatsnew/changelog python-3-8-0-alpha-32206227
Ref: ffc2206227
Node: 安全<20>2206568
Ref: whatsnew/changelog id1942206663
Ref: ffd2206663
Ref: 安全<20>-Footnote-12207220
Ref: 安全<20>-Footnote-22207263
Node: 核心与内置<27>2207306
Ref: whatsnew/changelog id1952207417
Ref: fff2207417
Ref: 核心与内置<27>-Footnote-12211016
Ref: 核心与内置<27>-Footnote-22211059
Ref: 核心与内置<27>-Footnote-32211102
Ref: 核心与内置<27>-Footnote-42211145
Ref: 核心与内置<27>-Footnote-52211188
Ref: 核心与内置<27>-Footnote-62211231
Ref: 核心与内置<27>-Footnote-72211274
Ref: 核心与内置<27>-Footnote-82211317
Ref: 核心与内置<27>-Footnote-92211360
Ref: 核心与内置<27>-Footnote-102211403
Ref: 核心与内置<27>-Footnote-112211447
Ref: 核心与内置<27>-Footnote-122211491
Ref: 核心与内置<27>-Footnote-132211535
Ref: 核心与内置<27>-Footnote-142211579
Ref: 核心与内置<27>-Footnote-152211623
Ref: 核心与内置<27>-Footnote-162211667
Ref: 核心与内置<27>-Footnote-172211711
Ref: 核心与内置<27>-Footnote-182211755
Ref: 核心与内置<27>-Footnote-192211799
Ref: 核心与内置<27>-Footnote-202211843
Ref: 核心与内置<27>-Footnote-212211887
Ref: 核心与内置<27>-Footnote-222211931
Node: 库<27>2211975
Ref: whatsnew/changelog id1962212086
Ref: 10012212086
Ref: 库<27>-Footnote-12217705
Ref: 库<27>-Footnote-22217748
Ref: 库<27>-Footnote-32217791
Ref: 库<27>-Footnote-42217834
Ref: 库<27>-Footnote-52217877
Ref: 库<27>-Footnote-62217920
Ref: 库<27>-Footnote-72217963
Ref: 库<27>-Footnote-82218006
Ref: 库<27>-Footnote-92218049
Ref: 库<27>-Footnote-102218092
Ref: 库<27>-Footnote-112218136
Ref: 库<27>-Footnote-122218180
Ref: 库<27>-Footnote-132218224
Ref: 库<27>-Footnote-142218268
Ref: 库<27>-Footnote-152218312
Ref: 库<27>-Footnote-162218356
Ref: 库<27>-Footnote-172218400
Ref: 库<27>-Footnote-182218444
Ref: 库<27>-Footnote-192218488
Ref: 库<27>-Footnote-202218532
Ref: 库<27>-Footnote-212218576
Ref: 库<27>-Footnote-222218620
Ref: 库<27>-Footnote-232218664
Ref: 库<27>-Footnote-242218708
Ref: 库<27>-Footnote-252218752
Ref: 库<27>-Footnote-262218796
Ref: 库<27>-Footnote-272218840
Ref: 库<27>-Footnote-282218884
Ref: 库<27>-Footnote-292218928
Ref: 库<27>-Footnote-302218972
Ref: 库<27>-Footnote-312219016
Ref: 库<27>-Footnote-322219060
Ref: 库<27>-Footnote-332219104
Ref: 库<27>-Footnote-342219148
Ref: 库<27>-Footnote-352219192
Ref: 库<27>-Footnote-362219236
Ref: 库<27>-Footnote-372219280
Node: 文档<23>2219324
Ref: whatsnew/changelog id1972219426
Ref: 10032219426
Ref: 文档<23>-Footnote-12219981
Ref: 文档<23>-Footnote-22220024
Ref: 文档<23>-Footnote-32220067
Node: 测试<18>2220110
Ref: whatsnew/changelog id1982220215
Ref: 10042220215
Ref: 测试<18>-Footnote-12220727
Ref: 测试<18>-Footnote-22220770
Ref: 测试<18>-Footnote-32220813
Node: 构建<16>2220856
Ref: whatsnew/changelog id1992220962
Ref: 10052220962
Ref: 构建<16>-Footnote-12221482
Ref: 构建<16>-Footnote-22221525
Ref: 构建<16>-Footnote-32221568
Ref: 构建<16>-Footnote-42221611
Node: Windows<20>2221654
Ref: whatsnew/changelog id2002221758
Ref: 10062221758
Ref: Windows<20>-Footnote-12222209
Ref: Windows<20>-Footnote-22222252
Ref: Windows<20>-Footnote-32222295
Node: IDLE<25>2222338
Ref: whatsnew/changelog id2012222449
Ref: 10072222449
Ref: IDLE<25>-Footnote-12223570
Ref: IDLE<25>-Footnote-22223613
Ref: IDLE<25>-Footnote-32223656
Ref: IDLE<25>-Footnote-42223699
Ref: IDLE<25>-Footnote-52223742
Ref: IDLE<25>-Footnote-62223785
Ref: IDLE<25>-Footnote-72223828
Ref: IDLE<25>-Footnote-82223871
Ref: IDLE<25>-Footnote-92223914
Node: 工具/示例<11>2223957
Ref: whatsnew/changelog id2022224066
Ref: 10082224066
Ref: 工具/示例<11>-Footnote-12224279
Ref: 工具/示例<11>-Footnote-22224322
Node: C API<14>2224365
Ref: whatsnew/changelog id2032224457
Ref: 10092224457
Ref: C API<14>-Footnote-12224849
Ref: C API<14>-Footnote-22224892
Node: Python 3 8 0 alpha 22224935
Ref: whatsnew/changelog python-3-8-0-alpha-22225062
Ref: 100a2225062
Node: 核心与内置<28>2225301
Ref: whatsnew/changelog id2042225393
Ref: 100b2225393
Ref: 核心与内置<28>-Footnote-12228529
Ref: 核心与内置<28>-Footnote-22228572
Ref: 核心与内置<28>-Footnote-32228615
Ref: 核心与内置<28>-Footnote-42228658
Ref: 核心与内置<28>-Footnote-52228701
Ref: 核心与内置<28>-Footnote-62228746
Ref: 核心与内置<28>-Footnote-72228789
Ref: 核心与内置<28>-Footnote-82228832
Ref: 核心与内置<28>-Footnote-92228875
Ref: 核心与内置<28>-Footnote-102228918
Ref: 核心与内置<28>-Footnote-112228962
Ref: 核心与内置<28>-Footnote-122229006
Ref: 核心与内置<28>-Footnote-132229050
Ref: 核心与内置<28>-Footnote-142229094
Ref: 核心与内置<28>-Footnote-152229138
Ref: 核心与内置<28>-Footnote-162229182
Ref: 核心与内置<28>-Footnote-172229226
Node: 库<28>2229270
Ref: whatsnew/changelog id2052229381
Ref: 100d2229381
Ref: 库<28>-Footnote-12233085
Ref: 库<28>-Footnote-22233128
Ref: 库<28>-Footnote-32233171
Ref: 库<28>-Footnote-42233214
Ref: 库<28>-Footnote-52233257
Ref: 库<28>-Footnote-62233300
Ref: 库<28>-Footnote-72233343
Ref: 库<28>-Footnote-82233386
Ref: 库<28>-Footnote-92233429
Ref: 库<28>-Footnote-102233472
Ref: 库<28>-Footnote-112233516
Ref: 库<28>-Footnote-122233560
Ref: 库<28>-Footnote-132233604
Ref: 库<28>-Footnote-142233648
Ref: 库<28>-Footnote-152233692
Ref: 库<28>-Footnote-162233736
Ref: 库<28>-Footnote-172233780
Node: 文档<24>2233824
Ref: whatsnew/changelog id2062233926
Ref: 10112233926
Ref: 文档<24>-Footnote-12234288
Ref: 文档<24>-Footnote-22234331
Ref: 文档<24>-Footnote-32234374
Node: 测试<19>2234417
Ref: whatsnew/changelog id2072234523
Ref: 10122234523
Ref: 测试<19>-Footnote-12235899
Ref: 测试<19>-Footnote-22235942
Ref: 测试<19>-Footnote-32235985
Ref: 测试<19>-Footnote-42236028
Ref: 测试<19>-Footnote-52236071
Ref: 测试<19>-Footnote-62236114
Ref: 测试<19>-Footnote-72236157
Ref: 测试<19>-Footnote-82236200
Node: Windows<21>2236243
Ref: whatsnew/changelog id2082236347
Ref: 10142236347
Ref: Windows<21>-Footnote-12236944
Ref: Windows<21>-Footnote-22236987
Ref: Windows<21>-Footnote-32237030
Ref: Windows<21>-Footnote-42237073
Ref: Windows<21>-Footnote-52237116
Node: IDLE<26>2237159
Ref: whatsnew/changelog id2092237244
Ref: 10152237244
Ref: IDLE<26>-Footnote-12237554
Ref: IDLE<26>-Footnote-22237597
Ref: IDLE<26>-Footnote-32237640
Node: Python 3 8 0 alpha 12237683
Ref: whatsnew/changelog python-3-8-0-alpha-12237812
Ref: 10162237812
Node: 安全<21>2238171
Ref: whatsnew/changelog id2102238266
Ref: 10172238266
Ref: 安全<21>-Footnote-12240584
Ref: 安全<21>-Footnote-22240627
Ref: 安全<21>-Footnote-32240670
Ref: 安全<21>-Footnote-42240713
Ref: 安全<21>-Footnote-52240756
Ref: 安全<21>-Footnote-62240799
Ref: 安全<21>-Footnote-72240842
Ref: 安全<21>-Footnote-82240885
Ref: 安全<21>-Footnote-92240928
Ref: 安全<21>-Footnote-102240971
Ref: 安全<21>-Footnote-112241015
Ref: 安全<21>-Footnote-122241059
Node: 核心与内置<29>2241103
Ref: whatsnew/changelog id2112241214
Ref: 101a2241214
Ref: 核心与内置<29>-Footnote-12267251
Ref: 核心与内置<29>-Footnote-22267294
Ref: 核心与内置<29>-Footnote-32267337
Ref: 核心与内置<29>-Footnote-42267380
Ref: 核心与内置<29>-Footnote-52267423
Ref: 核心与内置<29>-Footnote-62267466
Ref: 核心与内置<29>-Footnote-72267509
Ref: 核心与内置<29>-Footnote-82267552
Ref: 核心与内置<29>-Footnote-92267595
Ref: 核心与内置<29>-Footnote-102267638
Ref: 核心与内置<29>-Footnote-112267682
Ref: 核心与内置<29>-Footnote-122267726
Ref: 核心与内置<29>-Footnote-132267770
Ref: 核心与内置<29>-Footnote-142267814
Ref: 核心与内置<29>-Footnote-152267858
Ref: 核心与内置<29>-Footnote-162267902
Ref: 核心与内置<29>-Footnote-172267946
Ref: 核心与内置<29>-Footnote-182267990
Ref: 核心与内置<29>-Footnote-192268034
Ref: 核心与内置<29>-Footnote-202268078
Ref: 核心与内置<29>-Footnote-212268122
Ref: 核心与内置<29>-Footnote-222268166
Ref: 核心与内置<29>-Footnote-232268210
Ref: 核心与内置<29>-Footnote-242268254
Ref: 核心与内置<29>-Footnote-252268298
Ref: 核心与内置<29>-Footnote-262268348
Ref: 核心与内置<29>-Footnote-272268392
Ref: 核心与内置<29>-Footnote-282268436
Ref: 核心与内置<29>-Footnote-292268480
Ref: 核心与内置<29>-Footnote-302268524
Ref: 核心与内置<29>-Footnote-312268568
Ref: 核心与内置<29>-Footnote-322268612
Ref: 核心与内置<29>-Footnote-332268656
Ref: 核心与内置<29>-Footnote-342268700
Ref: 核心与内置<29>-Footnote-352268744
Ref: 核心与内置<29>-Footnote-362268788
Ref: 核心与内置<29>-Footnote-372268832
Ref: 核心与内置<29>-Footnote-382268876
Ref: 核心与内置<29>-Footnote-392268920
Ref: 核心与内置<29>-Footnote-402268964
Ref: 核心与内置<29>-Footnote-412269008
Ref: 核心与内置<29>-Footnote-422269052
Ref: 核心与内置<29>-Footnote-432269096
Ref: 核心与内置<29>-Footnote-442269140
Ref: 核心与内置<29>-Footnote-452269184
Ref: 核心与内置<29>-Footnote-462269228
Ref: 核心与内置<29>-Footnote-472269272
Ref: 核心与内置<29>-Footnote-482269316
Ref: 核心与内置<29>-Footnote-492269360
Ref: 核心与内置<29>-Footnote-502269404
Ref: 核心与内置<29>-Footnote-512269448
Ref: 核心与内置<29>-Footnote-522269492
Ref: 核心与内置<29>-Footnote-532269536
Ref: 核心与内置<29>-Footnote-542269580
Ref: 核心与内置<29>-Footnote-552269624
Ref: 核心与内置<29>-Footnote-562269668
Ref: 核心与内置<29>-Footnote-572269712
Ref: 核心与内置<29>-Footnote-582269756
Ref: 核心与内置<29>-Footnote-592269800
Ref: 核心与内置<29>-Footnote-602269843
Ref: 核心与内置<29>-Footnote-612269887
Ref: 核心与内置<29>-Footnote-622269931
Ref: 核心与内置<29>-Footnote-632269975
Ref: 核心与内置<29>-Footnote-642270019
Ref: 核心与内置<29>-Footnote-652270063
Ref: 核心与内置<29>-Footnote-662270107
Ref: 核心与内置<29>-Footnote-672270151
Ref: 核心与内置<29>-Footnote-682270195
Ref: 核心与内置<29>-Footnote-692270239
Ref: 核心与内置<29>-Footnote-702270283
Ref: 核心与内置<29>-Footnote-712270327
Ref: 核心与内置<29>-Footnote-722270371
Ref: 核心与内置<29>-Footnote-732270415
Ref: 核心与内置<29>-Footnote-742270459
Ref: 核心与内置<29>-Footnote-752270503
Ref: 核心与内置<29>-Footnote-762270547
Ref: 核心与内置<29>-Footnote-772270591
Ref: 核心与内置<29>-Footnote-782270635
Ref: 核心与内置<29>-Footnote-792270679
Ref: 核心与内置<29>-Footnote-802270723
Ref: 核心与内置<29>-Footnote-812270767
Ref: 核心与内置<29>-Footnote-822270811
Ref: 核心与内置<29>-Footnote-832270855
Ref: 核心与内置<29>-Footnote-842270899
Ref: 核心与内置<29>-Footnote-852270943
Ref: 核心与内置<29>-Footnote-862270987
Ref: 核心与内置<29>-Footnote-872271031
Ref: 核心与内置<29>-Footnote-882271075
Ref: 核心与内置<29>-Footnote-892271119
Ref: 核心与内置<29>-Footnote-902271163
Ref: 核心与内置<29>-Footnote-912271207
Ref: 核心与内置<29>-Footnote-922271251
Ref: 核心与内置<29>-Footnote-932271295
Ref: 核心与内置<29>-Footnote-942271339
Ref: 核心与内置<29>-Footnote-952271383
Ref: 核心与内置<29>-Footnote-962271427
Ref: 核心与内置<29>-Footnote-972271473
Ref: 核心与内置<29>-Footnote-982271517
Ref: 核心与内置<29>-Footnote-992271561
Ref: 核心与内置<29>-Footnote-1002271605
Ref: 核心与内置<29>-Footnote-1012271650
Ref: 核心与内置<29>-Footnote-1022271695
Ref: 核心与内置<29>-Footnote-1032271740
Ref: 核心与内置<29>-Footnote-1042271785
Ref: 核心与内置<29>-Footnote-1052271830
Ref: 核心与内置<29>-Footnote-1062271875
Ref: 核心与内置<29>-Footnote-1072271920
Ref: 核心与内置<29>-Footnote-1082271965
Ref: 核心与内置<29>-Footnote-1092272010
Ref: 核心与内置<29>-Footnote-1102272055
Ref: 核心与内置<29>-Footnote-1112272100
Ref: 核心与内置<29>-Footnote-1122272145
Ref: 核心与内置<29>-Footnote-1132272190
Ref: 核心与内置<29>-Footnote-1142272235
Ref: 核心与内置<29>-Footnote-1152272280
Ref: 核心与内置<29>-Footnote-1162272325
Ref: 核心与内置<29>-Footnote-1172272370
Ref: 核心与内置<29>-Footnote-1182272415
Ref: 核心与内置<29>-Footnote-1192272460
Ref: 核心与内置<29>-Footnote-1202272505
Ref: 核心与内置<29>-Footnote-1212272550
Ref: 核心与内置<29>-Footnote-1222272595
Ref: 核心与内置<29>-Footnote-1232272640
Ref: 核心与内置<29>-Footnote-1242272685
Ref: 核心与内置<29>-Footnote-1252272730
Ref: 核心与内置<29>-Footnote-1262272775
Ref: 核心与内置<29>-Footnote-1272272820
Ref: 核心与内置<29>-Footnote-1282272865
Ref: 核心与内置<29>-Footnote-1292272910
Ref: 核心与内置<29>-Footnote-1302272955
Ref: 核心与内置<29>-Footnote-1312273000
Ref: 核心与内置<29>-Footnote-1322273045
Ref: 核心与内置<29>-Footnote-1332273090
Ref: 核心与内置<29>-Footnote-1342273135
Ref: 核心与内置<29>-Footnote-1352273180
Ref: 核心与内置<29>-Footnote-1362273225
Ref: 核心与内置<29>-Footnote-1372273270
Ref: 核心与内置<29>-Footnote-1382273315
Ref: 核心与内置<29>-Footnote-1392273360
Ref: 核心与内置<29>-Footnote-1402273405
Ref: 核心与内置<29>-Footnote-1412273450
Ref: 核心与内置<29>-Footnote-1422273495
Ref: 核心与内置<29>-Footnote-1432273540
Ref: 核心与内置<29>-Footnote-1442273585
Ref: 核心与内置<29>-Footnote-1452273630
Ref: 核心与内置<29>-Footnote-1462273675
Ref: 核心与内置<29>-Footnote-1472273720
Ref: 核心与内置<29>-Footnote-1482273765
Ref: 核心与内置<29>-Footnote-1492273810
Ref: 核心与内置<29>-Footnote-1502273855
Ref: 核心与内置<29>-Footnote-1512273900
Ref: 核心与内置<29>-Footnote-1522273945
Ref: 核心与内置<29>-Footnote-1532273990
Ref: 核心与内置<29>-Footnote-1542274035
Ref: 核心与内置<29>-Footnote-1552274080
Ref: 核心与内置<29>-Footnote-1562274125
Ref: 核心与内置<29>-Footnote-1572274170
Ref: 核心与内置<29>-Footnote-1582274215
Ref: 核心与内置<29>-Footnote-1592274260
Ref: 核心与内置<29>-Footnote-1602274305
Ref: 核心与内置<29>-Footnote-1612274350
Ref: 核心与内置<29>-Footnote-1622274395
Node: 库<29>2274440
Ref: whatsnew/changelog id2122274551
Ref: 10242274551
Ref: 库<29>-Footnote-12345684
Ref: 库<29>-Footnote-22345727
Ref: 库<29>-Footnote-32345770
Ref: 库<29>-Footnote-42345813
Ref: 库<29>-Footnote-52345856
Ref: 库<29>-Footnote-62345899
Ref: 库<29>-Footnote-72345942
Ref: 库<29>-Footnote-82345985
Ref: 库<29>-Footnote-92346028
Ref: 库<29>-Footnote-102346071
Ref: 库<29>-Footnote-112346115
Ref: 库<29>-Footnote-122346159
Ref: 库<29>-Footnote-132346203
Ref: 库<29>-Footnote-142346247
Ref: 库<29>-Footnote-152346291
Ref: 库<29>-Footnote-162346335
Ref: 库<29>-Footnote-172346379
Ref: 库<29>-Footnote-182346423
Ref: 库<29>-Footnote-192346467
Ref: 库<29>-Footnote-202346511
Ref: 库<29>-Footnote-212346555
Ref: 库<29>-Footnote-222346599
Ref: 库<29>-Footnote-232346643
Ref: 库<29>-Footnote-242346687
Ref: 库<29>-Footnote-252346731
Ref: 库<29>-Footnote-262346775
Ref: 库<29>-Footnote-272346819
Ref: 库<29>-Footnote-282346863
Ref: 库<29>-Footnote-292346907
Ref: 库<29>-Footnote-302346951
Ref: 库<29>-Footnote-312346995
Ref: 库<29>-Footnote-322347039
Ref: 库<29>-Footnote-332347083
Ref: 库<29>-Footnote-342347127
Ref: 库<29>-Footnote-352347171
Ref: 库<29>-Footnote-362347215
Ref: 库<29>-Footnote-372347259
Ref: 库<29>-Footnote-382347303
Ref: 库<29>-Footnote-392347347
Ref: 库<29>-Footnote-402347391
Ref: 库<29>-Footnote-412347435
Ref: 库<29>-Footnote-422347479
Ref: 库<29>-Footnote-432347523
Ref: 库<29>-Footnote-442347567
Ref: 库<29>-Footnote-452347611
Ref: 库<29>-Footnote-462347655
Ref: 库<29>-Footnote-472347699
Ref: 库<29>-Footnote-482347743
Ref: 库<29>-Footnote-492347787
Ref: 库<29>-Footnote-502347831
Ref: 库<29>-Footnote-512347875
Ref: 库<29>-Footnote-522347919
Ref: 库<29>-Footnote-532347963
Ref: 库<29>-Footnote-542348007
Ref: 库<29>-Footnote-552348051
Ref: 库<29>-Footnote-562348095
Ref: 库<29>-Footnote-572348139
Ref: 库<29>-Footnote-582348183
Ref: 库<29>-Footnote-592348227
Ref: 库<29>-Footnote-602348271
Ref: 库<29>-Footnote-612348315
Ref: 库<29>-Footnote-622348359
Ref: 库<29>-Footnote-632348403
Ref: 库<29>-Footnote-642348447
Ref: 库<29>-Footnote-652348491
Ref: 库<29>-Footnote-662348535
Ref: 库<29>-Footnote-672348579
Ref: 库<29>-Footnote-682348623
Ref: 库<29>-Footnote-692348667
Ref: 库<29>-Footnote-702348711
Ref: 库<29>-Footnote-712348755
Ref: 库<29>-Footnote-722348799
Ref: 库<29>-Footnote-732348843
Ref: 库<29>-Footnote-742348887
Ref: 库<29>-Footnote-752348931
Ref: 库<29>-Footnote-762348975
Ref: 库<29>-Footnote-772349019
Ref: 库<29>-Footnote-782349063
Ref: 库<29>-Footnote-792349107
Ref: 库<29>-Footnote-802349151
Ref: 库<29>-Footnote-812349195
Ref: 库<29>-Footnote-822349239
Ref: 库<29>-Footnote-832349283
Ref: 库<29>-Footnote-842349327
Ref: 库<29>-Footnote-852349371
Ref: 库<29>-Footnote-862349415
Ref: 库<29>-Footnote-872349459
Ref: 库<29>-Footnote-882349503
Ref: 库<29>-Footnote-892349547
Ref: 库<29>-Footnote-902349591
Ref: 库<29>-Footnote-912349635
Ref: 库<29>-Footnote-922349679
Ref: 库<29>-Footnote-932349723
Ref: 库<29>-Footnote-942349773
Ref: 库<29>-Footnote-952349817
Ref: 库<29>-Footnote-962349861
Ref: 库<29>-Footnote-972349905
Ref: 库<29>-Footnote-982349949
Ref: 库<29>-Footnote-992349993
Ref: 库<29>-Footnote-1002350037
Ref: 库<29>-Footnote-1012350082
Ref: 库<29>-Footnote-1022350127
Ref: 库<29>-Footnote-1032350172
Ref: 库<29>-Footnote-1042350217
Ref: 库<29>-Footnote-1052350262
Ref: 库<29>-Footnote-1062350307
Ref: 库<29>-Footnote-1072350352
Ref: 库<29>-Footnote-1082350397
Ref: 库<29>-Footnote-1092350442
Ref: 库<29>-Footnote-1102350487
Ref: 库<29>-Footnote-1112350532
Ref: 库<29>-Footnote-1122350577
Ref: 库<29>-Footnote-1132350622
Ref: 库<29>-Footnote-1142350667
Ref: 库<29>-Footnote-1152350712
Ref: 库<29>-Footnote-1162350757
Ref: 库<29>-Footnote-1172350802
Ref: 库<29>-Footnote-1182350847
Ref: 库<29>-Footnote-1192350892
Ref: 库<29>-Footnote-1202350937
Ref: 库<29>-Footnote-1212350982
Ref: 库<29>-Footnote-1222351027
Ref: 库<29>-Footnote-1232351072
Ref: 库<29>-Footnote-1242351117
Ref: 库<29>-Footnote-1252351162
Ref: 库<29>-Footnote-1262351206
Ref: 库<29>-Footnote-1272351251
Ref: 库<29>-Footnote-1282351296
Ref: 库<29>-Footnote-1292351341
Ref: 库<29>-Footnote-1302351386
Ref: 库<29>-Footnote-1312351431
Ref: 库<29>-Footnote-1322351476
Ref: 库<29>-Footnote-1332351521
Ref: 库<29>-Footnote-1342351566
Ref: 库<29>-Footnote-1352351611
Ref: 库<29>-Footnote-1362351656
Ref: 库<29>-Footnote-1372351700
Ref: 库<29>-Footnote-1382351745
Ref: 库<29>-Footnote-1392351790
Ref: 库<29>-Footnote-1402351835
Ref: 库<29>-Footnote-1412351880
Ref: 库<29>-Footnote-1422351925
Ref: 库<29>-Footnote-1432351970
Ref: 库<29>-Footnote-1442352015
Ref: 库<29>-Footnote-1452352060
Ref: 库<29>-Footnote-1462352105
Ref: 库<29>-Footnote-1472352150
Ref: 库<29>-Footnote-1482352195
Ref: 库<29>-Footnote-1492352240
Ref: 库<29>-Footnote-1502352285
Ref: 库<29>-Footnote-1512352330
Ref: 库<29>-Footnote-1522352375
Ref: 库<29>-Footnote-1532352420
Ref: 库<29>-Footnote-1542352465
Ref: 库<29>-Footnote-1552352509
Ref: 库<29>-Footnote-1562352554
Ref: 库<29>-Footnote-1572352599
Ref: 库<29>-Footnote-1582352644
Ref: 库<29>-Footnote-1592352689
Ref: 库<29>-Footnote-1602352734
Ref: 库<29>-Footnote-1612352779
Ref: 库<29>-Footnote-1622352824
Ref: 库<29>-Footnote-1632352869
Ref: 库<29>-Footnote-1642352914
Ref: 库<29>-Footnote-1652352958
Ref: 库<29>-Footnote-1662353003
Ref: 库<29>-Footnote-1672353048
Ref: 库<29>-Footnote-1682353093
Ref: 库<29>-Footnote-1692353138
Ref: 库<29>-Footnote-1702353183
Ref: 库<29>-Footnote-1712353228
Ref: 库<29>-Footnote-1722353273
Ref: 库<29>-Footnote-1732353318
Ref: 库<29>-Footnote-1742353362
Ref: 库<29>-Footnote-1752353407
Ref: 库<29>-Footnote-1762353452
Ref: 库<29>-Footnote-1772353497
Ref: 库<29>-Footnote-1782353542
Ref: 库<29>-Footnote-1792353587
Ref: 库<29>-Footnote-1802353631
Ref: 库<29>-Footnote-1812353676
Ref: 库<29>-Footnote-1822353721
Ref: 库<29>-Footnote-1832353766
Ref: 库<29>-Footnote-1842353811
Ref: 库<29>-Footnote-1852353856
Ref: 库<29>-Footnote-1862353901
Ref: 库<29>-Footnote-1872353946
Ref: 库<29>-Footnote-1882353991
Ref: 库<29>-Footnote-1892354036
Ref: 库<29>-Footnote-1902354081
Ref: 库<29>-Footnote-1912354126
Ref: 库<29>-Footnote-1922354171
Ref: 库<29>-Footnote-1932354216
Ref: 库<29>-Footnote-1942354261
Ref: 库<29>-Footnote-1952354306
Ref: 库<29>-Footnote-1962354351
Ref: 库<29>-Footnote-1972354396
Ref: 库<29>-Footnote-1982354441
Ref: 库<29>-Footnote-1992354486
Ref: 库<29>-Footnote-2002354531
Ref: 库<29>-Footnote-2012354576
Ref: 库<29>-Footnote-2022354622
Ref: 库<29>-Footnote-2032354667
Ref: 库<29>-Footnote-2042354712
Ref: 库<29>-Footnote-2052354757
Ref: 库<29>-Footnote-2062354802
Ref: 库<29>-Footnote-2072354847
Ref: 库<29>-Footnote-2082354892
Ref: 库<29>-Footnote-2092354937
Ref: 库<29>-Footnote-2102354982
Ref: 库<29>-Footnote-2112355027
Ref: 库<29>-Footnote-2122355072
Ref: 库<29>-Footnote-2132355123
Ref: 库<29>-Footnote-2142355168
Ref: 库<29>-Footnote-2152355213
Ref: 库<29>-Footnote-2162355258
Ref: 库<29>-Footnote-2172355303
Ref: 库<29>-Footnote-2182355348
Ref: 库<29>-Footnote-2192355393
Ref: 库<29>-Footnote-2202355438
Ref: 库<29>-Footnote-2212355483
Ref: 库<29>-Footnote-2222355528
Ref: 库<29>-Footnote-2232355573
Ref: 库<29>-Footnote-2242355618
Ref: 库<29>-Footnote-2252355663
Ref: 库<29>-Footnote-2262355708
Ref: 库<29>-Footnote-2272355753
Ref: 库<29>-Footnote-2282355798
Ref: 库<29>-Footnote-2292355843
Ref: 库<29>-Footnote-2302355888
Ref: 库<29>-Footnote-2312355933
Ref: 库<29>-Footnote-2322355978
Ref: 库<29>-Footnote-2332356023
Ref: 库<29>-Footnote-2342356068
Ref: 库<29>-Footnote-2352356113
Ref: 库<29>-Footnote-2362356158
Ref: 库<29>-Footnote-2372356203
Ref: 库<29>-Footnote-2382356248
Ref: 库<29>-Footnote-2392356293
Ref: 库<29>-Footnote-2402356338
Ref: 库<29>-Footnote-2412356383
Ref: 库<29>-Footnote-2422356428
Ref: 库<29>-Footnote-2432356473
Ref: 库<29>-Footnote-2442356518
Ref: 库<29>-Footnote-2452356563
Ref: 库<29>-Footnote-2462356608
Ref: 库<29>-Footnote-2472356653
Ref: 库<29>-Footnote-2482356698
Ref: 库<29>-Footnote-2492356743
Ref: 库<29>-Footnote-2502356788
Ref: 库<29>-Footnote-2512356833
Ref: 库<29>-Footnote-2522356878
Ref: 库<29>-Footnote-2532356923
Ref: 库<29>-Footnote-2542356968
Ref: 库<29>-Footnote-2552357013
Ref: 库<29>-Footnote-2562357058
Ref: 库<29>-Footnote-2572357103
Ref: 库<29>-Footnote-2582357148
Ref: 库<29>-Footnote-2592357193
Ref: 库<29>-Footnote-2602357237
Ref: 库<29>-Footnote-2612357282
Ref: 库<29>-Footnote-2622357327
Ref: 库<29>-Footnote-2632357372
Ref: 库<29>-Footnote-2642357417
Ref: 库<29>-Footnote-2652357462
Ref: 库<29>-Footnote-2662357507
Ref: 库<29>-Footnote-2672357552
Ref: 库<29>-Footnote-2682357597
Ref: 库<29>-Footnote-2692357642
Ref: 库<29>-Footnote-2702357687
Ref: 库<29>-Footnote-2712357732
Ref: 库<29>-Footnote-2722357777
Ref: 库<29>-Footnote-2732357822
Ref: 库<29>-Footnote-2742357867
Ref: 库<29>-Footnote-2752357912
Ref: 库<29>-Footnote-2762357957
Ref: 库<29>-Footnote-2772358002
Ref: 库<29>-Footnote-2782358047
Ref: 库<29>-Footnote-2792358092
Ref: 库<29>-Footnote-2802358137
Ref: 库<29>-Footnote-2812358182
Ref: 库<29>-Footnote-2822358227
Ref: 库<29>-Footnote-2832358272
Ref: 库<29>-Footnote-2842358317
Ref: 库<29>-Footnote-2852358362
Ref: 库<29>-Footnote-2862358407
Ref: 库<29>-Footnote-2872358452
Ref: 库<29>-Footnote-2882358497
Ref: 库<29>-Footnote-2892358542
Ref: 库<29>-Footnote-2902358587
Ref: 库<29>-Footnote-2912358632
Ref: 库<29>-Footnote-2922358677
Ref: 库<29>-Footnote-2932358722
Ref: 库<29>-Footnote-2942358767
Ref: 库<29>-Footnote-2952358812
Ref: 库<29>-Footnote-2962358857
Ref: 库<29>-Footnote-2972358902
Ref: 库<29>-Footnote-2982358947
Ref: 库<29>-Footnote-2992358992
Ref: 库<29>-Footnote-3002359037
Ref: 库<29>-Footnote-3012359082
Ref: 库<29>-Footnote-3022359127
Ref: 库<29>-Footnote-3032359172
Ref: 库<29>-Footnote-3042359217
Ref: 库<29>-Footnote-3052359262
Ref: 库<29>-Footnote-3062359307
Ref: 库<29>-Footnote-3072359352
Ref: 库<29>-Footnote-3082359397
Ref: 库<29>-Footnote-3092359442
Ref: 库<29>-Footnote-3102359487
Ref: 库<29>-Footnote-3112359532
Ref: 库<29>-Footnote-3122359577
Ref: 库<29>-Footnote-3132359622
Ref: 库<29>-Footnote-3142359667
Ref: 库<29>-Footnote-3152359712
Ref: 库<29>-Footnote-3162359757
Ref: 库<29>-Footnote-3172359802
Ref: 库<29>-Footnote-3182359847
Ref: 库<29>-Footnote-3192359892
Ref: 库<29>-Footnote-3202359937
Ref: 库<29>-Footnote-3212359982
Ref: 库<29>-Footnote-3222360027
Ref: 库<29>-Footnote-3232360072
Ref: 库<29>-Footnote-3242360117
Ref: 库<29>-Footnote-3252360162
Ref: 库<29>-Footnote-3262360207
Ref: 库<29>-Footnote-3272360252
Ref: 库<29>-Footnote-3282360298
Ref: 库<29>-Footnote-3292360343
Ref: 库<29>-Footnote-3302360388
Ref: 库<29>-Footnote-3312360433
Ref: 库<29>-Footnote-3322360478
Ref: 库<29>-Footnote-3332360523
Ref: 库<29>-Footnote-3342360568
Ref: 库<29>-Footnote-3352360613
Ref: 库<29>-Footnote-3362360658
Ref: 库<29>-Footnote-3372360703
Ref: 库<29>-Footnote-3382360748
Ref: 库<29>-Footnote-3392360793
Ref: 库<29>-Footnote-3402360838
Ref: 库<29>-Footnote-3412360883
Ref: 库<29>-Footnote-3422360928
Ref: 库<29>-Footnote-3432360973
Ref: 库<29>-Footnote-3442361018
Ref: 库<29>-Footnote-3452361069
Ref: 库<29>-Footnote-3462361114
Ref: 库<29>-Footnote-3472361159
Ref: 库<29>-Footnote-3482361204
Ref: 库<29>-Footnote-3492361255
Ref: 库<29>-Footnote-3502361300
Ref: 库<29>-Footnote-3512361345
Ref: 库<29>-Footnote-3522361390
Ref: 库<29>-Footnote-3532361435
Ref: 库<29>-Footnote-3542361480
Ref: 库<29>-Footnote-3552361525
Ref: 库<29>-Footnote-3562361570
Ref: 库<29>-Footnote-3572361615
Ref: 库<29>-Footnote-3582361660
Ref: 库<29>-Footnote-3592361705
Ref: 库<29>-Footnote-3602361750
Ref: 库<29>-Footnote-3612361795
Ref: 库<29>-Footnote-3622361840
Ref: 库<29>-Footnote-3632361885
Ref: 库<29>-Footnote-3642361930
Ref: 库<29>-Footnote-3652361975
Ref: 库<29>-Footnote-3662362020
Ref: 库<29>-Footnote-3672362065
Ref: 库<29>-Footnote-3682362110
Ref: 库<29>-Footnote-3692362155
Ref: 库<29>-Footnote-3702362200
Ref: 库<29>-Footnote-3712362245
Ref: 库<29>-Footnote-3722362290
Ref: 库<29>-Footnote-3732362335
Ref: 库<29>-Footnote-3742362380
Ref: 库<29>-Footnote-3752362425
Ref: 库<29>-Footnote-3762362470
Ref: 库<29>-Footnote-3772362515
Ref: 库<29>-Footnote-3782362560
Ref: 库<29>-Footnote-3792362605
Ref: 库<29>-Footnote-3802362650
Ref: 库<29>-Footnote-3812362695
Ref: 库<29>-Footnote-3822362740
Ref: 库<29>-Footnote-3832362785
Ref: 库<29>-Footnote-3842362830
Ref: 库<29>-Footnote-3852362875
Ref: 库<29>-Footnote-3862362920
Ref: 库<29>-Footnote-3872362965
Ref: 库<29>-Footnote-3882363010
Ref: 库<29>-Footnote-3892363055
Ref: 库<29>-Footnote-3902363100
Ref: 库<29>-Footnote-3912363145
Ref: 库<29>-Footnote-3922363190
Ref: 库<29>-Footnote-3932363235
Ref: 库<29>-Footnote-3942363280
Ref: 库<29>-Footnote-3952363325
Ref: 库<29>-Footnote-3962363370
Ref: 库<29>-Footnote-3972363415
Ref: 库<29>-Footnote-3982363460
Ref: 库<29>-Footnote-3992363505
Ref: 库<29>-Footnote-4002363550
Ref: 库<29>-Footnote-4012363595
Ref: 库<29>-Footnote-4022363640
Ref: 库<29>-Footnote-4032363685
Ref: 库<29>-Footnote-4042363730
Ref: 库<29>-Footnote-4052363775
Ref: 库<29>-Footnote-4062363820
Ref: 库<29>-Footnote-4072363865
Ref: 库<29>-Footnote-4082363910
Ref: 库<29>-Footnote-4092363955
Ref: 库<29>-Footnote-4102364000
Ref: 库<29>-Footnote-4112364045
Ref: 库<29>-Footnote-4122364090
Ref: 库<29>-Footnote-4132364135
Ref: 库<29>-Footnote-4142364180
Ref: 库<29>-Footnote-4152364225
Ref: 库<29>-Footnote-4162364270
Ref: 库<29>-Footnote-4172364315
Ref: 库<29>-Footnote-4182364360
Ref: 库<29>-Footnote-4192364405
Ref: 库<29>-Footnote-4202364450
Ref: 库<29>-Footnote-4212364495
Ref: 库<29>-Footnote-4222364539
Ref: 库<29>-Footnote-4232364584
Ref: 库<29>-Footnote-4242364629
Ref: 库<29>-Footnote-4252364674
Ref: 库<29>-Footnote-4262364719
Ref: 库<29>-Footnote-4272364764
Ref: 库<29>-Footnote-4282364809
Ref: 库<29>-Footnote-4292364854
Ref: 库<29>-Footnote-4302364899
Ref: 库<29>-Footnote-4312364944
Ref: 库<29>-Footnote-4322364989
Ref: 库<29>-Footnote-4332365034
Ref: 库<29>-Footnote-4342365079
Ref: 库<29>-Footnote-4352365124
Ref: 库<29>-Footnote-4362365169
Node: 文档<25>2365214
Ref: whatsnew/changelog id2132365316
Ref: 104f2365316
Ref: 文档<25>-Footnote-12372012
Ref: 文档<25>-Footnote-22372055
Ref: 文档<25>-Footnote-32372098
Ref: 文档<25>-Footnote-42372141
Ref: 文档<25>-Footnote-52372184
Ref: 文档<25>-Footnote-62372227
Ref: 文档<25>-Footnote-72372270
Ref: 文档<25>-Footnote-82372313
Ref: 文档<25>-Footnote-92372356
Ref: 文档<25>-Footnote-102372399
Ref: 文档<25>-Footnote-112372443
Ref: 文档<25>-Footnote-122372487
Ref: 文档<25>-Footnote-132372531
Ref: 文档<25>-Footnote-142372575
Ref: 文档<25>-Footnote-152372619
Ref: 文档<25>-Footnote-162372663
Ref: 文档<25>-Footnote-172372707
Ref: 文档<25>-Footnote-182372751
Ref: 文档<25>-Footnote-192372795
Ref: 文档<25>-Footnote-202372839
Ref: 文档<25>-Footnote-212372883
Ref: 文档<25>-Footnote-222372927
Ref: 文档<25>-Footnote-232372971
Ref: 文档<25>-Footnote-242373021
Ref: 文档<25>-Footnote-252373065
Ref: 文档<25>-Footnote-262373109
Ref: 文档<25>-Footnote-272373153
Ref: 文档<25>-Footnote-282373197
Ref: 文档<25>-Footnote-292373241
Ref: 文档<25>-Footnote-302373291
Ref: 文档<25>-Footnote-312373335
Ref: 文档<25>-Footnote-322373379
Ref: 文档<25>-Footnote-332373423
Ref: 文档<25>-Footnote-342373467
Ref: 文档<25>-Footnote-352373511
Ref: 文档<25>-Footnote-362373555
Ref: 文档<25>-Footnote-372373599
Ref: 文档<25>-Footnote-382373643
Ref: 文档<25>-Footnote-392373687
Ref: 文档<25>-Footnote-402373731
Ref: 文档<25>-Footnote-412373775
Ref: 文档<25>-Footnote-422373819
Ref: 文档<25>-Footnote-432373863
Ref: 文档<25>-Footnote-442373907
Ref: 文档<25>-Footnote-452373951
Ref: 文档<25>-Footnote-462373995
Ref: 文档<25>-Footnote-472374039
Ref: 文档<25>-Footnote-482374083
Ref: 文档<25>-Footnote-492374127
Ref: 文档<25>-Footnote-502374171
Ref: 文档<25>-Footnote-512374214
Ref: 文档<25>-Footnote-522374258
Ref: 文档<25>-Footnote-532374302
Ref: 文档<25>-Footnote-542374346
Ref: 文档<25>-Footnote-552374390
Ref: 文档<25>-Footnote-562374434
Ref: 文档<25>-Footnote-572374477
Ref: 文档<25>-Footnote-582374521
Ref: 文档<25>-Footnote-592374565
Node: 测试<20>2374609
Ref: whatsnew/changelog id2142374714
Ref: 10522374714
Ref: 测试<20>-Footnote-12382303
Ref: 测试<20>-Footnote-22382346
Ref: 测试<20>-Footnote-32382389
Ref: 测试<20>-Footnote-42382432
Ref: 测试<20>-Footnote-52382475
Ref: 测试<20>-Footnote-62382518
Ref: 测试<20>-Footnote-72382561
Ref: 测试<20>-Footnote-82382604
Ref: 测试<20>-Footnote-92382647
Ref: 测试<20>-Footnote-102382690
Ref: 测试<20>-Footnote-112382734
Ref: 测试<20>-Footnote-122382778
Ref: 测试<20>-Footnote-132382822
Ref: 测试<20>-Footnote-142382866
Ref: 测试<20>-Footnote-152382910
Ref: 测试<20>-Footnote-162382954
Ref: 测试<20>-Footnote-172382998
Ref: 测试<20>-Footnote-182383042
Ref: 测试<20>-Footnote-192383086
Ref: 测试<20>-Footnote-202383130
Ref: 测试<20>-Footnote-212383174
Ref: 测试<20>-Footnote-222383218
Ref: 测试<20>-Footnote-232383262
Ref: 测试<20>-Footnote-242383306
Ref: 测试<20>-Footnote-252383350
Ref: 测试<20>-Footnote-262383394
Ref: 测试<20>-Footnote-272383438
Ref: 测试<20>-Footnote-282383482
Ref: 测试<20>-Footnote-292383526
Ref: 测试<20>-Footnote-302383570
Ref: 测试<20>-Footnote-312383614
Ref: 测试<20>-Footnote-322383658
Ref: 测试<20>-Footnote-332383702
Ref: 测试<20>-Footnote-342383746
Ref: 测试<20>-Footnote-352383790
Ref: 测试<20>-Footnote-362383834
Ref: 测试<20>-Footnote-372383878
Ref: 测试<20>-Footnote-382383922
Ref: 测试<20>-Footnote-392383966
Ref: 测试<20>-Footnote-402384010
Ref: 测试<20>-Footnote-412384054
Ref: 测试<20>-Footnote-422384098
Ref: 测试<20>-Footnote-432384142
Ref: 测试<20>-Footnote-442384186
Ref: 测试<20>-Footnote-452384230
Ref: 测试<20>-Footnote-462384274
Ref: 测试<20>-Footnote-472384318
Ref: 测试<20>-Footnote-482384362
Node: 构建<17>2384406
Ref: whatsnew/changelog id2152384512
Ref: 10542384512
Ref: 构建<17>-Footnote-12389625
Ref: 构建<17>-Footnote-22389668
Ref: 构建<17>-Footnote-32389711
Ref: 构建<17>-Footnote-42389754
Ref: 构建<17>-Footnote-52389797
Ref: 构建<17>-Footnote-62389840
Ref: 构建<17>-Footnote-72389883
Ref: 构建<17>-Footnote-82389926
Ref: 构建<17>-Footnote-92389969
Ref: 构建<17>-Footnote-102390012
Ref: 构建<17>-Footnote-112390056
Ref: 构建<17>-Footnote-122390100
Ref: 构建<17>-Footnote-132390144
Ref: 构建<17>-Footnote-142390188
Ref: 构建<17>-Footnote-152390232
Ref: 构建<17>-Footnote-162390276
Ref: 构建<17>-Footnote-172390320
Ref: 构建<17>-Footnote-182390364
Ref: 构建<17>-Footnote-192390408
Ref: 构建<17>-Footnote-202390452
Ref: 构建<17>-Footnote-212390496
Ref: 构建<17>-Footnote-222390540
Ref: 构建<17>-Footnote-232390584
Ref: 构建<17>-Footnote-242390627
Ref: 构建<17>-Footnote-252390671
Ref: 构建<17>-Footnote-262390715
Ref: 构建<17>-Footnote-272390759
Ref: 构建<17>-Footnote-282390803
Ref: 构建<17>-Footnote-292390847
Ref: 构建<17>-Footnote-302390891
Ref: 构建<17>-Footnote-312390935
Ref: 构建<17>-Footnote-322390979
Ref: 构建<17>-Footnote-332391023
Ref: 构建<17>-Footnote-342391067
Ref: 构建<17>-Footnote-352391111
Ref: 构建<17>-Footnote-362391155
Ref: 构建<17>-Footnote-372391199
Node: Windows<22>2391243
Ref: whatsnew/changelog id2162391348
Ref: 10552391348
Ref: Windows<22>-Footnote-12395784
Ref: Windows<22>-Footnote-22395827
Ref: Windows<22>-Footnote-32395870
Ref: Windows<22>-Footnote-42395913
Ref: Windows<22>-Footnote-52395956
Ref: Windows<22>-Footnote-62395999
Ref: Windows<22>-Footnote-72396042
Ref: Windows<22>-Footnote-82396085
Ref: Windows<22>-Footnote-92396128
Ref: Windows<22>-Footnote-102396171
Ref: Windows<22>-Footnote-112396215
Ref: Windows<22>-Footnote-122396259
Ref: Windows<22>-Footnote-132396303
Ref: Windows<22>-Footnote-142396347
Ref: Windows<22>-Footnote-152396391
Ref: Windows<22>-Footnote-162396435
Ref: Windows<22>-Footnote-172396479
Ref: Windows<22>-Footnote-182396523
Ref: Windows<22>-Footnote-192396567
Ref: Windows<22>-Footnote-202396611
Ref: Windows<22>-Footnote-212396655
Ref: Windows<22>-Footnote-222396699
Ref: Windows<22>-Footnote-232396743
Ref: Windows<22>-Footnote-242396787
Ref: Windows<22>-Footnote-252396831
Ref: Windows<22>-Footnote-262396875
Ref: Windows<22>-Footnote-272396919
Ref: Windows<22>-Footnote-282396963
Ref: Windows<22>-Footnote-292397007
Ref: Windows<22>-Footnote-302397051
Ref: Windows<22>-Footnote-312397095
Ref: Windows<22>-Footnote-322397139
Ref: Windows<22>-Footnote-332397183
Ref: Windows<22>-Footnote-342397227
Ref: Windows<22>-Footnote-352397271
Ref: Windows<22>-Footnote-362397315
Ref: Windows<22>-Footnote-372397359
Ref: Windows<22>-Footnote-382397403
Ref: Windows<22>-Footnote-392397447
Ref: Windows<22>-Footnote-402397491
Node: macOS<16>2397534
Ref: whatsnew/changelog id2172397637
Ref: 10562397637
Ref: macOS<16>-Footnote-12399250
Ref: macOS<16>-Footnote-22399293
Ref: macOS<16>-Footnote-32399336
Ref: macOS<16>-Footnote-42399379
Ref: macOS<16>-Footnote-52399422
Ref: macOS<16>-Footnote-62399465
Ref: macOS<16>-Footnote-72399508
Ref: macOS<16>-Footnote-82399551
Ref: macOS<16>-Footnote-92399594
Ref: macOS<16>-Footnote-102399637
Node: IDLE<27>2399681
Ref: whatsnew/changelog id2182399790
Ref: 10572399790
Ref: IDLE<27>-Footnote-12408197
Ref: IDLE<27>-Footnote-22408240
Ref: IDLE<27>-Footnote-32408283
Ref: IDLE<27>-Footnote-42408326
Ref: IDLE<27>-Footnote-52408369
Ref: IDLE<27>-Footnote-62408412
Ref: IDLE<27>-Footnote-72408455
Ref: IDLE<27>-Footnote-82408498
Ref: IDLE<27>-Footnote-92408541
Ref: IDLE<27>-Footnote-102408584
Ref: IDLE<27>-Footnote-112408628
Ref: IDLE<27>-Footnote-122408672
Ref: IDLE<27>-Footnote-132408716
Ref: IDLE<27>-Footnote-142408760
Ref: IDLE<27>-Footnote-152408804
Ref: IDLE<27>-Footnote-162408848
Ref: IDLE<27>-Footnote-172408892
Ref: IDLE<27>-Footnote-182408936
Ref: IDLE<27>-Footnote-192408980
Ref: IDLE<27>-Footnote-202409024
Ref: IDLE<27>-Footnote-212409068
Ref: IDLE<27>-Footnote-222409112
Ref: IDLE<27>-Footnote-232409156
Ref: IDLE<27>-Footnote-242409200
Ref: IDLE<27>-Footnote-252409244
Ref: IDLE<27>-Footnote-262409288
Ref: IDLE<27>-Footnote-272409332
Ref: IDLE<27>-Footnote-282409378
Ref: IDLE<27>-Footnote-292409422
Ref: IDLE<27>-Footnote-302409466
Ref: IDLE<27>-Footnote-312409510
Ref: IDLE<27>-Footnote-322409554
Ref: IDLE<27>-Footnote-332409598
Ref: IDLE<27>-Footnote-342409642
Ref: IDLE<27>-Footnote-352409686
Ref: IDLE<27>-Footnote-362409730
Ref: IDLE<27>-Footnote-372409774
Ref: IDLE<27>-Footnote-382409818
Ref: IDLE<27>-Footnote-392409862
Ref: IDLE<27>-Footnote-402409906
Ref: IDLE<27>-Footnote-412409950
Ref: IDLE<27>-Footnote-422409994
Ref: IDLE<27>-Footnote-432410038
Ref: IDLE<27>-Footnote-442410082
Ref: IDLE<27>-Footnote-452410126
Ref: IDLE<27>-Footnote-462410170
Ref: IDLE<27>-Footnote-472410214
Ref: IDLE<27>-Footnote-482410258
Ref: IDLE<27>-Footnote-492410302
Ref: IDLE<27>-Footnote-502410346
Ref: IDLE<27>-Footnote-512410390
Ref: IDLE<27>-Footnote-522410434
Ref: IDLE<27>-Footnote-532410478
Ref: IDLE<27>-Footnote-542410522
Ref: IDLE<27>-Footnote-552410566
Ref: IDLE<27>-Footnote-562410610
Ref: IDLE<27>-Footnote-572410654
Ref: IDLE<27>-Footnote-582410698
Ref: IDLE<27>-Footnote-592410742
Node: 工具/示例<12>2410786
Ref: whatsnew/changelog id2192410895
Ref: 10582410895
Ref: 工具/示例<12>-Footnote-12412544
Ref: 工具/示例<12>-Footnote-22412587
Ref: 工具/示例<12>-Footnote-32412630
Ref: 工具/示例<12>-Footnote-42412673
Ref: 工具/示例<12>-Footnote-52412716
Ref: 工具/示例<12>-Footnote-62412759
Ref: 工具/示例<12>-Footnote-72412802
Ref: 工具/示例<12>-Footnote-82412845
Ref: 工具/示例<12>-Footnote-92412888
Ref: 工具/示例<12>-Footnote-102412931
Ref: 工具/示例<12>-Footnote-112412975
Ref: 工具/示例<12>-Footnote-122413019
Node: C API<15>2413063
Ref: whatsnew/changelog id2202413155
Ref: 10592413155
Ref: C API<15>-Footnote-12416565
Ref: C API<15>-Footnote-22416608
Ref: C API<15>-Footnote-32416651
Ref: C API<15>-Footnote-42416694
Ref: C API<15>-Footnote-52416737
Ref: C API<15>-Footnote-62416780
Ref: C API<15>-Footnote-72416823
Ref: C API<15>-Footnote-82416866
Ref: C API<15>-Footnote-92416909
Ref: C API<15>-Footnote-102416952
Ref: C API<15>-Footnote-112416996
Ref: C API<15>-Footnote-122417040
Ref: C API<15>-Footnote-132417084
Ref: C API<15>-Footnote-142417128
Ref: C API<15>-Footnote-152417172
Ref: C API<15>-Footnote-162417216
Ref: C API<15>-Footnote-172417260
Ref: C API<15>-Footnote-182417304
Ref: C API<15>-Footnote-192417348
Ref: C API<15>-Footnote-202417392
Ref: C API<15>-Footnote-212417436
Ref: C API<15>-Footnote-222417480
Node: Python 3 7 0 正式版2417524
Ref: whatsnew/changelog python-3-7-0-final2417649
Ref: 10632417649
Node: 库<30>2417783
Ref: whatsnew/changelog id2212417867
Ref: 10642417867
Ref: 库<30>-Footnote-12418028
Node: C API<16>2418071
Ref: whatsnew/changelog id2222418155
Ref: 10662418155
Ref: C API<16>-Footnote-12418366
Node: Python 3 7 0 rc12418409
Ref: whatsnew/changelog python-3-7-0-release-candidate-12418533
Ref: 10672418533
Node: 核心与内置<30>2418764
Ref: whatsnew/changelog id2232418852
Ref: 10682418852
Ref: 核心与内置<30>-Footnote-12419487
Ref: 核心与内置<30>-Footnote-22419530
Ref: 核心与内置<30>-Footnote-32419573
Ref: 核心与内置<30>-Footnote-42419616
Node: 库<31>2419659
Ref: whatsnew/changelog id2242419766
Ref: 10692419766
Ref: 库<31>-Footnote-12421455
Ref: 库<31>-Footnote-22421498
Ref: 库<31>-Footnote-32421541
Ref: 库<31>-Footnote-42421584
Ref: 库<31>-Footnote-52421627
Ref: 库<31>-Footnote-62421670
Ref: 库<31>-Footnote-72421713
Ref: 库<31>-Footnote-82421756
Ref: 库<31>-Footnote-92421799
Ref: 库<31>-Footnote-102421842
Ref: 库<31>-Footnote-112421886
Ref: 库<31>-Footnote-122421930
Ref: 库<31>-Footnote-132421974
Node: 文档<26>2422018
Ref: whatsnew/changelog id2252422116
Ref: 106a2422116
Ref: 文档<26>-Footnote-12422607
Ref: 文档<26>-Footnote-22422650
Ref: 文档<26>-Footnote-32422699
Ref: 文档<26>-Footnote-42422742
Node: 构建<18>2422785
Ref: whatsnew/changelog id2262422887
Ref: 106b2422887
Ref: 构建<18>-Footnote-12423149
Node: Windows<23>2423191
Ref: whatsnew/changelog id2272423291
Ref: 106c2423291
Ref: Windows<23>-Footnote-12423448
Node: IDLE<28>2423491
Ref: whatsnew/changelog id2282423572
Ref: 106d2423572
Ref: IDLE<28>-Footnote-12424792
Ref: IDLE<28>-Footnote-22424835
Ref: IDLE<28>-Footnote-32424878
Ref: IDLE<28>-Footnote-42424921
Ref: IDLE<28>-Footnote-52424964
Ref: IDLE<28>-Footnote-62425007
Node: Python 3 7 0 beta 52425050
Ref: whatsnew/changelog python-3-7-0-beta-52425171
Ref: 106e2425171
Node: 核心与内置<31>2425426
Ref: whatsnew/changelog id2292425517
Ref: 106f2425517
Ref: 核心与内置<31>-Footnote-12427028
Ref: 核心与内置<31>-Footnote-22427071
Ref: 核心与内置<31>-Footnote-32427114
Ref: 核心与内置<31>-Footnote-42427157
Ref: 核心与内置<31>-Footnote-52427200
Ref: 核心与内置<31>-Footnote-62427243
Ref: 核心与内置<31>-Footnote-72427286
Ref: 核心与内置<31>-Footnote-82427329
Ref: 核心与内置<31>-Footnote-92427372
Node: 库<32>2427415
Ref: whatsnew/changelog id2302427525
Ref: 10702427525
Ref: 库<32>-Footnote-12433131
Ref: 库<32>-Footnote-22433174
Ref: 库<32>-Footnote-32433217
Ref: 库<32>-Footnote-42433260
Ref: 库<32>-Footnote-52433303
Ref: 库<32>-Footnote-62433346
Ref: 库<32>-Footnote-72433389
Ref: 库<32>-Footnote-82433432
Ref: 库<32>-Footnote-92433475
Ref: 库<32>-Footnote-102433518
Ref: 库<32>-Footnote-112433562
Ref: 库<32>-Footnote-122433606
Ref: 库<32>-Footnote-132433650
Ref: 库<32>-Footnote-142433694
Ref: 库<32>-Footnote-152433738
Ref: 库<32>-Footnote-162433782
Ref: 库<32>-Footnote-172433826
Ref: 库<32>-Footnote-182433870
Ref: 库<32>-Footnote-192433914
Ref: 库<32>-Footnote-202433958
Ref: 库<32>-Footnote-212434002
Ref: 库<32>-Footnote-222434046
Ref: 库<32>-Footnote-232434090
Ref: 库<32>-Footnote-242434134
Ref: 库<32>-Footnote-252434178
Ref: 库<32>-Footnote-262434222
Ref: 库<32>-Footnote-272434266
Ref: 库<32>-Footnote-282434310
Ref: 库<32>-Footnote-292434354
Ref: 库<32>-Footnote-302434398
Ref: 库<32>-Footnote-312434442
Ref: 库<32>-Footnote-322434486
Ref: 库<32>-Footnote-332434530
Ref: 库<32>-Footnote-342434574
Ref: 库<32>-Footnote-352434618
Ref: 库<32>-Footnote-362434662
Ref: 库<32>-Footnote-372434706
Ref: 库<32>-Footnote-382434750
Node: 文档<27>2434794
Ref: whatsnew/changelog id2312434895
Ref: 10712434895
Ref: 文档<27>-Footnote-12435357
Ref: 文档<27>-Footnote-22435400
Ref: 文档<27>-Footnote-32435443
Ref: 文档<27>-Footnote-42435492
Ref: 文档<27>-Footnote-52435535
Ref: 文档<27>-Footnote-62435578
Node: 测试<21>2435621
Ref: whatsnew/changelog id2322435725
Ref: 10722435725
Ref: 测试<21>-Footnote-12436038
Ref: 测试<21>-Footnote-22436081
Node: 构建<19>2436124
Ref: whatsnew/changelog id2332436227
Ref: 10732436227
Ref: 构建<19>-Footnote-12436706
Ref: 构建<19>-Footnote-22436749
Ref: 构建<19>-Footnote-32436792
Node: macOS<17>2436835
Ref: whatsnew/changelog id2342436936
Ref: 10742436936
Ref: macOS<17>-Footnote-12437178
Node: IDLE<29>2437221
Ref: whatsnew/changelog id2352437303
Ref: 10752437303
Ref: IDLE<29>-Footnote-12437582
Ref: IDLE<29>-Footnote-22437625
Ref: IDLE<29>-Footnote-32437668
Node: Python 3 7 0 beta 42437711
Ref: whatsnew/changelog python-3-7-0-beta-42437835
Ref: 10762437835
Node: 核心与内置<32>2438150
Ref: whatsnew/changelog id2362438241
Ref: 10772438241
Ref: 核心与内置<32>-Footnote-12439375
Ref: 核心与内置<32>-Footnote-22439418
Ref: 核心与内置<32>-Footnote-32439461
Ref: 核心与内置<32>-Footnote-42439504
Ref: 核心与内置<32>-Footnote-52439547
Ref: 核心与内置<32>-Footnote-62439590
Ref: 核心与内置<32>-Footnote-72439633
Node: 库<33>2439676
Ref: whatsnew/changelog id2372439786
Ref: 10782439786
Ref: 库<33>-Footnote-12442620
Ref: 库<33>-Footnote-22442663
Ref: 库<33>-Footnote-32442706
Ref: 库<33>-Footnote-42442749
Ref: 库<33>-Footnote-52442793
Ref: 库<33>-Footnote-62442836
Ref: 库<33>-Footnote-72442879
Ref: 库<33>-Footnote-82442922
Ref: 库<33>-Footnote-92442965
Ref: 库<33>-Footnote-102443008
Ref: 库<33>-Footnote-112443052
Ref: 库<33>-Footnote-122443096
Ref: 库<33>-Footnote-132443140
Ref: 库<33>-Footnote-142443184
Ref: 库<33>-Footnote-152443228
Ref: 库<33>-Footnote-162443272
Ref: 库<33>-Footnote-172443316
Ref: 库<33>-Footnote-182443366
Ref: 库<33>-Footnote-192443410
Ref: 库<33>-Footnote-202443454
Ref: 库<33>-Footnote-212443498
Ref: 库<33>-Footnote-222443542
Node: 文档<28>2443586
Ref: whatsnew/changelog id2382443687
Ref: 10792443687
Ref: 文档<28>-Footnote-12444422
Ref: 文档<28>-Footnote-22444465
Ref: 文档<28>-Footnote-32444508
Ref: 文档<28>-Footnote-42444551
Ref: 文档<28>-Footnote-52444594
Ref: 文档<28>-Footnote-62444636
Node: 测试<22>2444679
Ref: whatsnew/changelog id2392444783
Ref: 107a2444783
Ref: 测试<22>-Footnote-12444999
Node: 构建<20>2445042
Ref: whatsnew/changelog id2402445147
Ref: 107b2445147
Ref: 构建<20>-Footnote-12445837
Ref: 构建<20>-Footnote-22445880
Ref: 构建<20>-Footnote-32445923
Ref: 构建<20>-Footnote-42445966
Ref: 构建<20>-Footnote-52446009
Node: Windows<24>2446052
Ref: whatsnew/changelog id2412446156
Ref: 107c2446156
Ref: Windows<24>-Footnote-12446301
Node: macOS<18>2446344
Ref: whatsnew/changelog id2422446446
Ref: 107d2446446
Ref: macOS<18>-Footnote-12446587
Node: IDLE<30>2446630
Ref: whatsnew/changelog id2432446738
Ref: 107e2446738
Ref: IDLE<30>-Footnote-12447328
Ref: IDLE<30>-Footnote-22447371
Node: 工具/示例<13>2447414
Ref: whatsnew/changelog id2442447504
Ref: 107f2447504
Ref: 工具/示例<13>-Footnote-12448112
Ref: 工具/示例<13>-Footnote-22448155
Ref: 工具/示例<13>-Footnote-32448198
Ref: 工具/示例<13>-Footnote-42448241
Node: Python 3 7 0 beta 32448284
Ref: whatsnew/changelog python-3-7-0-beta-32448408
Ref: 10802448408
Node: 安全<22>2448765
Ref: whatsnew/changelog id2452448859
Ref: 10812448859
Ref: 安全<22>-Footnote-12449476
Ref: 安全<22>-Footnote-22449519
Ref: 安全<22>-Footnote-32449562
Node: 核心与内置<33>2449605
Ref: whatsnew/changelog id2462449715
Ref: 10822449715
Ref: 核心与内置<33>-Footnote-12450912
Ref: 核心与内置<33>-Footnote-22450955
Ref: 核心与内置<33>-Footnote-32450998
Ref: 核心与内置<33>-Footnote-42451041
Ref: 核心与内置<33>-Footnote-52451084
Ref: 核心与内置<33>-Footnote-62451127
Ref: 核心与内置<33>-Footnote-72451170
Node: 库<34>2451213
Ref: whatsnew/changelog id2472451323
Ref: 10832451323
Ref: 库<34>-Footnote-12455364
Ref: 库<34>-Footnote-22455407
Ref: 库<34>-Footnote-32455450
Ref: 库<34>-Footnote-42455493
Ref: 库<34>-Footnote-52455536
Ref: 库<34>-Footnote-62455579
Ref: 库<34>-Footnote-72455622
Ref: 库<34>-Footnote-82455665
Ref: 库<34>-Footnote-92455708
Ref: 库<34>-Footnote-102455751
Ref: 库<34>-Footnote-112455795
Ref: 库<34>-Footnote-122455839
Ref: 库<34>-Footnote-132455883
Ref: 库<34>-Footnote-142455927
Ref: 库<34>-Footnote-152455971
Ref: 库<34>-Footnote-162456015
Ref: 库<34>-Footnote-172456059
Ref: 库<34>-Footnote-182456103
Ref: 库<34>-Footnote-192456147
Ref: 库<34>-Footnote-202456191
Ref: 库<34>-Footnote-212456235
Ref: 库<34>-Footnote-222456279
Ref: 库<34>-Footnote-232456323
Ref: 库<34>-Footnote-242456367
Ref: 库<34>-Footnote-252456411
Ref: 库<34>-Footnote-262456455
Ref: 库<34>-Footnote-272456499
Node: 文档<29>2456543
Ref: whatsnew/changelog id2482456644
Ref: 10842456644
Ref: 文档<29>-Footnote-12457265
Ref: 文档<29>-Footnote-22457308
Ref: 文档<29>-Footnote-32457351
Ref: 文档<29>-Footnote-42457394
Ref: 文档<29>-Footnote-52457437
Node: 测试<23>2457480
Ref: whatsnew/changelog id2492457584
Ref: 10852457584
Ref: 测试<23>-Footnote-12457917
Ref: 测试<23>-Footnote-22457960
Ref: 测试<23>-Footnote-32458003
Node: 构建<21>2458046
Ref: whatsnew/changelog id2502458151
Ref: 10862458151
Ref: 构建<21>-Footnote-12458288
Node: Windows<25>2458331
Ref: whatsnew/changelog id2512458435
Ref: 10872458435
Ref: Windows<25>-Footnote-12458714
Ref: Windows<25>-Footnote-22458757
Node: macOS<19>2458800
Ref: whatsnew/changelog id2522458902
Ref: 10882458902
Ref: macOS<19>-Footnote-12459334
Node: IDLE<31>2459377
Ref: whatsnew/changelog id2532459485
Ref: 10892459485
Ref: IDLE<31>-Footnote-12460199
Ref: IDLE<31>-Footnote-22460242
Node: 工具/示例<14>2460285
Ref: whatsnew/changelog id2542460393
Ref: 108a2460393
Ref: 工具/示例<14>-Footnote-12460623
Node: C API<17>2460666
Ref: whatsnew/changelog id2552460757
Ref: 108b2460757
Ref: C API<17>-Footnote-12461141
Ref: C API<17>-Footnote-22461184
Node: Python 3 7 0 beta 22461227
Ref: whatsnew/changelog python-3-7-0-beta-22461351
Ref: 108c2461351
Node: 安全<23>2461688
Ref: whatsnew/changelog id2562461782
Ref: 108d2461782
Ref: 安全<23>-Footnote-12461961
Node: 核心与内置<34>2462004
Ref: whatsnew/changelog id2572462114
Ref: 108e2462114
Ref: 核心与内置<34>-Footnote-12462936
Ref: 核心与内置<34>-Footnote-22462979
Ref: 核心与内置<34>-Footnote-32463022
Ref: 核心与内置<34>-Footnote-42463065
Ref: 核心与内置<34>-Footnote-52463108
Ref: 核心与内置<34>-Footnote-62463151
Ref: 核心与内置<34>-Footnote-72463194
Node: 库<35>2463237
Ref: whatsnew/changelog id2582463347
Ref: 108f2463347
Ref: 库<35>-Footnote-12469721
Ref: 库<35>-Footnote-22469764
Ref: 库<35>-Footnote-32469807
Ref: 库<35>-Footnote-42469850
Ref: 库<35>-Footnote-52469893
Ref: 库<35>-Footnote-62469936
Ref: 库<35>-Footnote-72469979
Ref: 库<35>-Footnote-82470022
Ref: 库<35>-Footnote-92470065
Ref: 库<35>-Footnote-102470108
Ref: 库<35>-Footnote-112470152
Ref: 库<35>-Footnote-122470196
Ref: 库<35>-Footnote-132470240
Ref: 库<35>-Footnote-142470284
Ref: 库<35>-Footnote-152470328
Ref: 库<35>-Footnote-162470372
Ref: 库<35>-Footnote-172470416
Ref: 库<35>-Footnote-182470460
Ref: 库<35>-Footnote-192470504
Ref: 库<35>-Footnote-202470548
Ref: 库<35>-Footnote-212470592
Ref: 库<35>-Footnote-222470636
Ref: 库<35>-Footnote-232470680
Ref: 库<35>-Footnote-242470724
Ref: 库<35>-Footnote-252470768
Ref: 库<35>-Footnote-262470812
Ref: 库<35>-Footnote-272470856
Ref: 库<35>-Footnote-282470900
Ref: 库<35>-Footnote-292470944
Ref: 库<35>-Footnote-302470988
Ref: 库<35>-Footnote-312471032
Ref: 库<35>-Footnote-322471076
Ref: 库<35>-Footnote-332471120
Ref: 库<35>-Footnote-342471164
Node: 文档<30>2471208
Ref: whatsnew/changelog id2592471309
Ref: 10902471309
Ref: 文档<30>-Footnote-12472263
Ref: 文档<30>-Footnote-22472306
Ref: 文档<30>-Footnote-32472349
Ref: 文档<30>-Footnote-42472392
Ref: 文档<30>-Footnote-52472435
Ref: 文档<30>-Footnote-62472478
Ref: 文档<30>-Footnote-72472520
Ref: 文档<30>-Footnote-82472563
Node: 测试<24>2472606
Ref: whatsnew/changelog id2602472710
Ref: 10912472710
Ref: 测试<24>-Footnote-12472853
Node: 构建<22>2472896
Ref: whatsnew/changelog id2612473001
Ref: 10922473001
Ref: 构建<22>-Footnote-12473142
Node: Windows<26>2473185
Ref: whatsnew/changelog id2622473289
Ref: 10932473289
Ref: Windows<26>-Footnote-12474025
Ref: Windows<26>-Footnote-22474068
Ref: Windows<26>-Footnote-32474111
Ref: Windows<26>-Footnote-42474154
Ref: Windows<26>-Footnote-52474197
Ref: Windows<26>-Footnote-62474240
Node: macOS<20>2474283
Ref: whatsnew/changelog id2632474385
Ref: 10942474385
Ref: macOS<20>-Footnote-12474520
Node: IDLE<32>2474563
Ref: whatsnew/changelog id2642474671
Ref: 10952474671
Ref: IDLE<32>-Footnote-12475514
Ref: IDLE<32>-Footnote-22475557
Ref: IDLE<32>-Footnote-32475600
Ref: IDLE<32>-Footnote-42475643
Ref: IDLE<32>-Footnote-52475686
Ref: IDLE<32>-Footnote-62475729
Node: 工具/示例<15>2475772
Ref: whatsnew/changelog id2652475862
Ref: 10962475862
Ref: 工具/示例<15>-Footnote-12476081
Node: Python 3 7 0 beta 12476124
Ref: whatsnew/changelog python-3-7-0-beta-12476249
Ref: 10972476249
Node: 核心与内置<35>2476530
Ref: whatsnew/changelog id2662476621
Ref: 10982476621
Ref: 核心与内置<35>-Footnote-12480042
Ref: 核心与内置<35>-Footnote-22480085
Ref: 核心与内置<35>-Footnote-32480128
Ref: 核心与内置<35>-Footnote-42480171
Ref: 核心与内置<35>-Footnote-52480214
Ref: 核心与内置<35>-Footnote-62480257
Ref: 核心与内置<35>-Footnote-72480300
Ref: 核心与内置<35>-Footnote-82480343
Ref: 核心与内置<35>-Footnote-92480386
Ref: 核心与内置<35>-Footnote-102480435
Ref: 核心与内置<35>-Footnote-112480479
Ref: 核心与内置<35>-Footnote-122480523
Ref: 核心与内置<35>-Footnote-132480567
Ref: 核心与内置<35>-Footnote-142480611
Ref: 核心与内置<35>-Footnote-152480655
Ref: 核心与内置<35>-Footnote-162480699
Ref: 核心与内置<35>-Footnote-172480743
Ref: 核心与内置<35>-Footnote-182480787
Ref: 核心与内置<35>-Footnote-192480837
Ref: 核心与内置<35>-Footnote-202480881
Ref: 核心与内置<35>-Footnote-212480925
Ref: 核心与内置<35>-Footnote-222480969
Ref: 核心与内置<35>-Footnote-232481013
Node: 库<36>2481057
Ref: whatsnew/changelog id2672481167
Ref: 10992481167
Ref: 库<36>-Footnote-12488542
Ref: 库<36>-Footnote-22488585
Ref: 库<36>-Footnote-32488628
Ref: 库<36>-Footnote-42488671
Ref: 库<36>-Footnote-52488714
Ref: 库<36>-Footnote-62488757
Ref: 库<36>-Footnote-72488800
Ref: 库<36>-Footnote-82488843
Ref: 库<36>-Footnote-92488886
Ref: 库<36>-Footnote-102488929
Ref: 库<36>-Footnote-112488973
Ref: 库<36>-Footnote-122489017
Ref: 库<36>-Footnote-132489061
Ref: 库<36>-Footnote-142489105
Ref: 库<36>-Footnote-152489149
Ref: 库<36>-Footnote-162489193
Ref: 库<36>-Footnote-172489237
Ref: 库<36>-Footnote-182489281
Ref: 库<36>-Footnote-192489331
Ref: 库<36>-Footnote-202489375
Ref: 库<36>-Footnote-212489419
Ref: 库<36>-Footnote-222489463
Ref: 库<36>-Footnote-232489507
Ref: 库<36>-Footnote-242489551
Ref: 库<36>-Footnote-252489595
Ref: 库<36>-Footnote-262489639
Ref: 库<36>-Footnote-272489683
Ref: 库<36>-Footnote-282489727
Ref: 库<36>-Footnote-292489771
Ref: 库<36>-Footnote-302489815
Ref: 库<36>-Footnote-312489859
Ref: 库<36>-Footnote-322489903
Ref: 库<36>-Footnote-332489947
Ref: 库<36>-Footnote-342489991
Ref: 库<36>-Footnote-352490035
Ref: 库<36>-Footnote-362490079
Ref: 库<36>-Footnote-372490123
Ref: 库<36>-Footnote-382490167
Ref: 库<36>-Footnote-392490211
Ref: 库<36>-Footnote-402490255
Ref: 库<36>-Footnote-412490299
Ref: 库<36>-Footnote-422490343
Ref: 库<36>-Footnote-432490387
Ref: 库<36>-Footnote-442490431
Ref: 库<36>-Footnote-452490475
Ref: 库<36>-Footnote-462490519
Ref: 库<36>-Footnote-472490563
Node: 文档<31>2490607
Ref: whatsnew/changelog id2682490708
Ref: 109c2490708
Ref: 文档<31>-Footnote-12491233
Ref: 文档<31>-Footnote-22491276
Ref: 文档<31>-Footnote-32491319
Node: 测试<25>2491362
Ref: whatsnew/changelog id2692491466
Ref: 109d2491466
Ref: 测试<25>-Footnote-12492374
Ref: 测试<25>-Footnote-22492417
Ref: 测试<25>-Footnote-32492460
Ref: 测试<25>-Footnote-42492503
Ref: 测试<25>-Footnote-52492546
Ref: 测试<25>-Footnote-62492589
Node: 构建<23>2492632
Ref: whatsnew/changelog id2702492737
Ref: 109e2492737
Ref: 构建<23>-Footnote-12493351
Ref: 构建<23>-Footnote-22493394
Ref: 构建<23>-Footnote-32493437
Ref: 构建<23>-Footnote-42493480
Node: Windows<27>2493523
Ref: whatsnew/changelog id2712493627
Ref: 109f2493627
Ref: Windows<27>-Footnote-12494008
Ref: Windows<27>-Footnote-22494051
Ref: Windows<27>-Footnote-32494094
Node: macOS<21>2494137
Ref: whatsnew/changelog id2722494240
Ref: 10a02494240
Ref: macOS<21>-Footnote-12494762
Ref: macOS<21>-Footnote-22494805
Node: C API<18>2494848
Ref: whatsnew/changelog id2732494931
Ref: 10a12494931
Ref: C API<18>-Footnote-12495252
Ref: C API<18>-Footnote-22495295
Node: Python 3 7 0 alpha 42495338
Ref: whatsnew/changelog python-3-7-0-alpha-42495464
Ref: 10a22495464
Node: 核心与内置<36>2495741
Ref: whatsnew/changelog id2742495833
Ref: 10a32495833
Ref: 核心与内置<36>-Footnote-12499330
Ref: 核心与内置<36>-Footnote-22499373
Ref: 核心与内置<36>-Footnote-32499416
Ref: 核心与内置<36>-Footnote-42499459
Ref: 核心与内置<36>-Footnote-52499502
Ref: 核心与内置<36>-Footnote-62499545
Ref: 核心与内置<36>-Footnote-72499588
Ref: 核心与内置<36>-Footnote-82499631
Ref: 核心与内置<36>-Footnote-92499674
Ref: 核心与内置<36>-Footnote-102499717
Ref: 核心与内置<36>-Footnote-112499761
Ref: 核心与内置<36>-Footnote-122499805
Ref: 核心与内置<36>-Footnote-132499849
Ref: 核心与内置<36>-Footnote-142499893
Ref: 核心与内置<36>-Footnote-152499937
Ref: 核心与内置<36>-Footnote-162499981
Ref: 核心与内置<36>-Footnote-172500025
Ref: 核心与内置<36>-Footnote-182500069
Ref: 核心与内置<36>-Footnote-192500113
Ref: 核心与内置<36>-Footnote-202500163
Ref: 核心与内置<36>-Footnote-212500207
Ref: 核心与内置<36>-Footnote-222500257
Ref: 核心与内置<36>-Footnote-232500301
Ref: 核心与内置<36>-Footnote-242500351
Ref: 核心与内置<36>-Footnote-252500395
Ref: 核心与内置<36>-Footnote-262500439
Ref: 核心与内置<36>-Footnote-272500489
Node: 库<37>2500533
Ref: whatsnew/changelog id2752500644
Ref: 10a52500644
Ref: 库<37>-Footnote-12508647
Ref: 库<37>-Footnote-22508690
Ref: 库<37>-Footnote-32508733
Ref: 库<37>-Footnote-42508776
Ref: 库<37>-Footnote-52508819
Ref: 库<37>-Footnote-62508862
Ref: 库<37>-Footnote-72508905
Ref: 库<37>-Footnote-82508948
Ref: 库<37>-Footnote-92508991
Ref: 库<37>-Footnote-102509034
Ref: 库<37>-Footnote-112509078
Ref: 库<37>-Footnote-122509122
Ref: 库<37>-Footnote-132509166
Ref: 库<37>-Footnote-142509210
Ref: 库<37>-Footnote-152509254
Ref: 库<37>-Footnote-162509298
Ref: 库<37>-Footnote-172509342
Ref: 库<37>-Footnote-182509386
Ref: 库<37>-Footnote-192509430
Ref: 库<37>-Footnote-202509474
Ref: 库<37>-Footnote-212509518
Ref: 库<37>-Footnote-222509562
Ref: 库<37>-Footnote-232509606
Ref: 库<37>-Footnote-242509650
Ref: 库<37>-Footnote-252509694
Ref: 库<37>-Footnote-262509738
Ref: 库<37>-Footnote-272509782
Ref: 库<37>-Footnote-282509826
Ref: 库<37>-Footnote-292509870
Ref: 库<37>-Footnote-302509914
Ref: 库<37>-Footnote-312509958
Ref: 库<37>-Footnote-322510002
Ref: 库<37>-Footnote-332510046
Ref: 库<37>-Footnote-342510090
Ref: 库<37>-Footnote-352510134
Ref: 库<37>-Footnote-362510178
Ref: 库<37>-Footnote-372510222
Ref: 库<37>-Footnote-382510266
Ref: 库<37>-Footnote-392510310
Ref: 库<37>-Footnote-402510354
Ref: 库<37>-Footnote-412510398
Ref: 库<37>-Footnote-422510442
Ref: 库<37>-Footnote-432510486
Ref: 库<37>-Footnote-442510530
Ref: 库<37>-Footnote-452510574
Ref: 库<37>-Footnote-462510618
Ref: 库<37>-Footnote-472510662
Ref: 库<37>-Footnote-482510706
Ref: 库<37>-Footnote-492510750
Ref: 库<37>-Footnote-502510794
Ref: 库<37>-Footnote-512510838
Ref: 库<37>-Footnote-522510882
Ref: 库<37>-Footnote-532510926
Ref: 库<37>-Footnote-542510970
Node: 文档<32>2511014
Ref: whatsnew/changelog id2762511116
Ref: 10a82511116
Ref: 文档<32>-Footnote-12511270
Node: 测试<26>2511313
Ref: whatsnew/changelog id2772511419
Ref: 10a92511419
Ref: 测试<26>-Footnote-12511814
Ref: 测试<26>-Footnote-22511857
Node: Windows<28>2511900
Ref: whatsnew/changelog id2782512013
Ref: 10aa2512013
Ref: Windows<28>-Footnote-12512212
Node: 工具/示例<16>2512255
Ref: whatsnew/changelog id2792512367
Ref: 10ab2512367
Ref: 工具/示例<16>-Footnote-12512649
Node: C API<19>2512692
Ref: whatsnew/changelog id2802512784
Ref: 10ac2512784
Ref: C API<19>-Footnote-12513445
Ref: C API<19>-Footnote-22513488
Ref: C API<19>-Footnote-32513531
Ref: C API<19>-Footnote-42513574
Node: Python 3 7 0 alpha 32513617
Ref: whatsnew/changelog python-3-7-0-alpha-32513744
Ref: 10ad2513744
Node: 核心与内置<37>2514081
Ref: whatsnew/changelog id2812514173
Ref: 10ae2514173
Ref: 核心与内置<37>-Footnote-12519285
Ref: 核心与内置<37>-Footnote-22519328
Ref: 核心与内置<37>-Footnote-32519371
Ref: 核心与内置<37>-Footnote-42519414
Ref: 核心与内置<37>-Footnote-52519457
Ref: 核心与内置<37>-Footnote-62519500
Ref: 核心与内置<37>-Footnote-72519543
Ref: 核心与内置<37>-Footnote-82519586
Ref: 核心与内置<37>-Footnote-92519629
Ref: 核心与内置<37>-Footnote-102519672
Ref: 核心与内置<37>-Footnote-112519716
Ref: 核心与内置<37>-Footnote-122519760
Ref: 核心与内置<37>-Footnote-132519804
Ref: 核心与内置<37>-Footnote-142519848
Ref: 核心与内置<37>-Footnote-152519892
Ref: 核心与内置<37>-Footnote-162519936
Ref: 核心与内置<37>-Footnote-172519980
Ref: 核心与内置<37>-Footnote-182520024
Ref: 核心与内置<37>-Footnote-192520068
Ref: 核心与内置<37>-Footnote-202520112
Ref: 核心与内置<37>-Footnote-212520156
Ref: 核心与内置<37>-Footnote-222520200
Node: 库<38>2520244
Ref: whatsnew/changelog id2822520355
Ref: 10af2520355
Ref: 库<38>-Footnote-12536409
Ref: 库<38>-Footnote-22536452
Ref: 库<38>-Footnote-32536495
Ref: 库<38>-Footnote-42536538
Ref: 库<38>-Footnote-52536581
Ref: 库<38>-Footnote-62536624
Ref: 库<38>-Footnote-72536667
Ref: 库<38>-Footnote-82536710
Ref: 库<38>-Footnote-92536754
Ref: 库<38>-Footnote-102536797
Ref: 库<38>-Footnote-112536841
Ref: 库<38>-Footnote-122536885
Ref: 库<38>-Footnote-132536929
Ref: 库<38>-Footnote-142536973
Ref: 库<38>-Footnote-152537017
Ref: 库<38>-Footnote-162537061
Ref: 库<38>-Footnote-172537105
Ref: 库<38>-Footnote-182537149
Ref: 库<38>-Footnote-192537193
Ref: 库<38>-Footnote-202537237
Ref: 库<38>-Footnote-212537281
Ref: 库<38>-Footnote-222537325
Ref: 库<38>-Footnote-232537369
Ref: 库<38>-Footnote-242537413
Ref: 库<38>-Footnote-252537457
Ref: 库<38>-Footnote-262537503
Ref: 库<38>-Footnote-272537547
Ref: 库<38>-Footnote-282537591
Ref: 库<38>-Footnote-292537635
Ref: 库<38>-Footnote-302537679
Ref: 库<38>-Footnote-312537723
Ref: 库<38>-Footnote-322537767
Ref: 库<38>-Footnote-332537817
Ref: 库<38>-Footnote-342537861
Ref: 库<38>-Footnote-352537905
Ref: 库<38>-Footnote-362537949
Ref: 库<38>-Footnote-372537993
Ref: 库<38>-Footnote-382538037
Ref: 库<38>-Footnote-392538081
Ref: 库<38>-Footnote-402538125
Ref: 库<38>-Footnote-412538169
Ref: 库<38>-Footnote-422538213
Ref: 库<38>-Footnote-432538257
Ref: 库<38>-Footnote-442538301
Ref: 库<38>-Footnote-452538345
Ref: 库<38>-Footnote-462538389
Ref: 库<38>-Footnote-472538432
Ref: 库<38>-Footnote-482538476
Ref: 库<38>-Footnote-492538520
Ref: 库<38>-Footnote-502538564
Ref: 库<38>-Footnote-512538608
Ref: 库<38>-Footnote-522538652
Ref: 库<38>-Footnote-532538696
Ref: 库<38>-Footnote-542538740
Ref: 库<38>-Footnote-552538784
Ref: 库<38>-Footnote-562538828
Ref: 库<38>-Footnote-572538872
Ref: 库<38>-Footnote-582538916
Ref: 库<38>-Footnote-592538960
Ref: 库<38>-Footnote-602539004
Ref: 库<38>-Footnote-612539048
Ref: 库<38>-Footnote-622539092
Ref: 库<38>-Footnote-632539142
Ref: 库<38>-Footnote-642539186
Ref: 库<38>-Footnote-652539230
Ref: 库<38>-Footnote-662539274
Ref: 库<38>-Footnote-672539318
Ref: 库<38>-Footnote-682539362
Ref: 库<38>-Footnote-692539406
Ref: 库<38>-Footnote-702539450
Ref: 库<38>-Footnote-712539494
Ref: 库<38>-Footnote-722539538
Ref: 库<38>-Footnote-732539582
Ref: 库<38>-Footnote-742539626
Ref: 库<38>-Footnote-752539670
Ref: 库<38>-Footnote-762539714
Ref: 库<38>-Footnote-772539758
Ref: 库<38>-Footnote-782539802
Ref: 库<38>-Footnote-792539846
Ref: 库<38>-Footnote-802539890
Ref: 库<38>-Footnote-812539934
Ref: 库<38>-Footnote-822539978
Ref: 库<38>-Footnote-832540028
Ref: 库<38>-Footnote-842540072
Ref: 库<38>-Footnote-852540116
Ref: 库<38>-Footnote-862540160
Ref: 库<38>-Footnote-872540204
Ref: 库<38>-Footnote-882540248
Ref: 库<38>-Footnote-892540292
Ref: 库<38>-Footnote-902540336
Ref: 库<38>-Footnote-912540380
Ref: 库<38>-Footnote-922540424
Ref: 库<38>-Footnote-932540468
Ref: 库<38>-Footnote-942540512
Ref: 库<38>-Footnote-952540556
Ref: 库<38>-Footnote-962540600
Ref: 库<38>-Footnote-972540644
Ref: 库<38>-Footnote-982540688
Node: 文档<33>2540732
Ref: whatsnew/changelog id2832540834
Ref: 10b52540834
Ref: 文档<33>-Footnote-12541001
Node: 测试<27>2541044
Ref: whatsnew/changelog id2842541149
Ref: 10b62541149
Ref: 测试<27>-Footnote-12542359
Ref: 测试<27>-Footnote-22542402
Ref: 测试<27>-Footnote-32542445
Ref: 测试<27>-Footnote-42542488
Ref: 测试<27>-Footnote-52542531
Ref: 测试<27>-Footnote-62542574
Ref: 测试<27>-Footnote-72542617
Node: 构建<24>2542660
Ref: whatsnew/changelog id2852542766
Ref: 10b72542766
Ref: 构建<24>-Footnote-12543987
Ref: 构建<24>-Footnote-22544030
Ref: 构建<24>-Footnote-32544073
Ref: 构建<24>-Footnote-42544116
Ref: 构建<24>-Footnote-52544159
Ref: 构建<24>-Footnote-62544202
Ref: 构建<24>-Footnote-72544245
Ref: 构建<24>-Footnote-82544288
Ref: 构建<24>-Footnote-92544331
Ref: 构建<24>-Footnote-102544374
Ref: 构建<24>-Footnote-112544418
Ref: 构建<24>-Footnote-122544462
Node: Windows<29>2544506
Ref: whatsnew/changelog id2862544611
Ref: 10b82544611
Ref: Windows<29>-Footnote-12545144
Ref: Windows<29>-Footnote-22545186
Ref: Windows<29>-Footnote-32545229
Ref: Windows<29>-Footnote-42545272
Node: macOS<22>2545315
Ref: whatsnew/changelog id2872545418
Ref: 10b92545418
Ref: macOS<22>-Footnote-12545556
Node: IDLE<33>2545599
Ref: whatsnew/changelog id2882545708
Ref: 10ba2545708
Ref: IDLE<33>-Footnote-12547801
Ref: IDLE<33>-Footnote-22547844
Ref: IDLE<33>-Footnote-32547887
Ref: IDLE<33>-Footnote-42547930
Ref: IDLE<33>-Footnote-52547973
Ref: IDLE<33>-Footnote-62548016
Ref: IDLE<33>-Footnote-72548059
Ref: IDLE<33>-Footnote-82548102
Node: 工具/示例<17>2548145
Ref: whatsnew/changelog id2892548254
Ref: 10bb2548254
Ref: 工具/示例<17>-Footnote-12548786
Ref: 工具/示例<17>-Footnote-22548829
Node: C API<20>2548872
Ref: whatsnew/changelog id2902548964
Ref: 10bc2548964
Ref: C API<20>-Footnote-12550092
Ref: C API<20>-Footnote-22550135
Ref: C API<20>-Footnote-32550178
Ref: C API<20>-Footnote-42550221
Ref: C API<20>-Footnote-52550264
Ref: C API<20>-Footnote-62550307
Node: Python 3 7 0 alpha 22550350
Ref: whatsnew/changelog python-3-7-0-alpha-22550477
Ref: 10bd2550477
Node: 核心与内置<38>2550712
Ref: whatsnew/changelog id2912550804
Ref: 10be2550804
Ref: 核心与内置<38>-Footnote-12554991
Ref: 核心与内置<38>-Footnote-22555034
Ref: 核心与内置<38>-Footnote-32555077
Ref: 核心与内置<38>-Footnote-42555120
Ref: 核心与内置<38>-Footnote-52555163
Ref: 核心与内置<38>-Footnote-62555206
Ref: 核心与内置<38>-Footnote-72555249
Ref: 核心与内置<38>-Footnote-82555292
Ref: 核心与内置<38>-Footnote-92555335
Ref: 核心与内置<38>-Footnote-102555378
Ref: 核心与内置<38>-Footnote-112555422
Ref: 核心与内置<38>-Footnote-122555466
Ref: 核心与内置<38>-Footnote-132555510
Ref: 核心与内置<38>-Footnote-142555554
Ref: 核心与内置<38>-Footnote-152555598
Ref: 核心与内置<38>-Footnote-162555642
Ref: 核心与内置<38>-Footnote-172555686
Ref: 核心与内置<38>-Footnote-182555730
Ref: 核心与内置<38>-Footnote-192555774
Ref: 核心与内置<38>-Footnote-202555818
Ref: 核心与内置<38>-Footnote-212555868
Ref: 核心与内置<38>-Footnote-222555912
Ref: 核心与内置<38>-Footnote-232555956
Ref: 核心与内置<38>-Footnote-242556000
Ref: 核心与内置<38>-Footnote-252556044
Ref: 核心与内置<38>-Footnote-262556088
Ref: 核心与内置<38>-Footnote-272556132
Node: 库<39>2556182
Ref: whatsnew/changelog id2922556293
Ref: 10c12556293
Ref: 库<39>-Footnote-12560365
Ref: 库<39>-Footnote-22560408
Ref: 库<39>-Footnote-32560451
Ref: 库<39>-Footnote-42560494
Ref: 库<39>-Footnote-52560537
Ref: 库<39>-Footnote-62560580
Ref: 库<39>-Footnote-72560623
Ref: 库<39>-Footnote-82560666
Ref: 库<39>-Footnote-92560709
Ref: 库<39>-Footnote-102560752
Ref: 库<39>-Footnote-112560796
Ref: 库<39>-Footnote-122560840
Ref: 库<39>-Footnote-132560884
Ref: 库<39>-Footnote-142560928
Ref: 库<39>-Footnote-152560972
Ref: 库<39>-Footnote-162561016
Ref: 库<39>-Footnote-172561060
Ref: 库<39>-Footnote-182561104
Ref: 库<39>-Footnote-192561148
Ref: 库<39>-Footnote-202561192
Ref: 库<39>-Footnote-212561236
Ref: 库<39>-Footnote-222561280
Ref: 库<39>-Footnote-232561324
Ref: 库<39>-Footnote-242561368
Ref: 库<39>-Footnote-252561412
Ref: 库<39>-Footnote-262561456
Node: 文档<34>2561500
Ref: whatsnew/changelog id2932561602
Ref: 10c32561602
Ref: 文档<34>-Footnote-12561977
Ref: 文档<34>-Footnote-22562020
Node: 构建<25>2562063
Ref: whatsnew/changelog id2942562166
Ref: 10c42562166
Ref: 构建<25>-Footnote-12562796
Ref: 构建<25>-Footnote-22562839
Ref: 构建<25>-Footnote-32562882
Ref: 构建<25>-Footnote-42562925
Ref: 构建<25>-Footnote-52562968
Ref: 构建<25>-Footnote-62563011
Node: IDLE<34>2563054
Ref: whatsnew/changelog id2952563156
Ref: 10c52563156
Ref: IDLE<34>-Footnote-12564462
Ref: IDLE<34>-Footnote-22564505
Ref: IDLE<34>-Footnote-32564548
Ref: IDLE<34>-Footnote-42564591
Ref: IDLE<34>-Footnote-52564634
Ref: IDLE<34>-Footnote-62564677
Node: C API<21>2564722
Ref: whatsnew/changelog id2962564805
Ref: 10c62564805
Ref: C API<21>-Footnote-12565547
Ref: C API<21>-Footnote-22565590
Ref: C API<21>-Footnote-32565633
Ref: C API<21>-Footnote-42565676
Node: Python 3 7 0 alpha 12565725
Ref: whatsnew/changelog python-3-7-0-alpha-12565854
Ref: 10c72565854
Node: 安全<24>2566193
Ref: whatsnew/changelog id2972566288
Ref: 10c82566288
Ref: 安全<24>-Footnote-12567906
Ref: 安全<24>-Footnote-22567949
Ref: 安全<24>-Footnote-32567992
Ref: 安全<24>-Footnote-42568035
Ref: 安全<24>-Footnote-52568078
Ref: 安全<24>-Footnote-62568121
Ref: 安全<24>-Footnote-72568164
Node: 核心与内置<39>2568207
Ref: whatsnew/changelog id2982568318
Ref: 10c92568318
Ref: 核心与内置<39>-Footnote-12589202
Ref: 核心与内置<39>-Footnote-22589245
Ref: 核心与内置<39>-Footnote-32589288
Ref: 核心与内置<39>-Footnote-42589331
Ref: 核心与内置<39>-Footnote-52589374
Ref: 核心与内置<39>-Footnote-62589417
Ref: 核心与内置<39>-Footnote-72589460
Ref: 核心与内置<39>-Footnote-82589503
Ref: 核心与内置<39>-Footnote-92589546
Ref: 核心与内置<39>-Footnote-102589589
Ref: 核心与内置<39>-Footnote-112589633
Ref: 核心与内置<39>-Footnote-122589677
Ref: 核心与内置<39>-Footnote-132589721
Ref: 核心与内置<39>-Footnote-142589765
Ref: 核心与内置<39>-Footnote-152589809
Ref: 核心与内置<39>-Footnote-162589853
Ref: 核心与内置<39>-Footnote-172589897
Ref: 核心与内置<39>-Footnote-182589941
Ref: 核心与内置<39>-Footnote-192589985
Ref: 核心与内置<39>-Footnote-202590029
Ref: 核心与内置<39>-Footnote-212590073
Ref: 核心与内置<39>-Footnote-222590117
Ref: 核心与内置<39>-Footnote-232590161
Ref: 核心与内置<39>-Footnote-242590205
Ref: 核心与内置<39>-Footnote-252590249
Ref: 核心与内置<39>-Footnote-262590293
Ref: 核心与内置<39>-Footnote-272590337
Ref: 核心与内置<39>-Footnote-282590381
Ref: 核心与内置<39>-Footnote-292590425
Ref: 核心与内置<39>-Footnote-302590469
Ref: 核心与内置<39>-Footnote-312590513
Ref: 核心与内置<39>-Footnote-322590557
Ref: 核心与内置<39>-Footnote-332590601
Ref: 核心与内置<39>-Footnote-342590645
Ref: 核心与内置<39>-Footnote-352590689
Ref: 核心与内置<39>-Footnote-362590739
Ref: 核心与内置<39>-Footnote-372590783
Ref: 核心与内置<39>-Footnote-382590827
Ref: 核心与内置<39>-Footnote-392590871
Ref: 核心与内置<39>-Footnote-402590915
Ref: 核心与内置<39>-Footnote-412590959
Ref: 核心与内置<39>-Footnote-422591003
Ref: 核心与内置<39>-Footnote-432591047
Ref: 核心与内置<39>-Footnote-442591091
Ref: 核心与内置<39>-Footnote-452591135
Ref: 核心与内置<39>-Footnote-462591179
Ref: 核心与内置<39>-Footnote-472591223
Ref: 核心与内置<39>-Footnote-482591267
Ref: 核心与内置<39>-Footnote-492591311
Ref: 核心与内置<39>-Footnote-502591355
Ref: 核心与内置<39>-Footnote-512591399
Ref: 核心与内置<39>-Footnote-522591443
Ref: 核心与内置<39>-Footnote-532591487
Ref: 核心与内置<39>-Footnote-542591531
Ref: 核心与内置<39>-Footnote-552591575
Ref: 核心与内置<39>-Footnote-562591619
Ref: 核心与内置<39>-Footnote-572591663
Ref: 核心与内置<39>-Footnote-582591707
Ref: 核心与内置<39>-Footnote-592591751
Ref: 核心与内置<39>-Footnote-602591795
Ref: 核心与内置<39>-Footnote-612591839
Ref: 核心与内置<39>-Footnote-622591883
Ref: 核心与内置<39>-Footnote-632591927
Ref: 核心与内置<39>-Footnote-642591971
Ref: 核心与内置<39>-Footnote-652592015
Ref: 核心与内置<39>-Footnote-662592059
Ref: 核心与内置<39>-Footnote-672592103
Ref: 核心与内置<39>-Footnote-682592147
Ref: 核心与内置<39>-Footnote-692592191
Ref: 核心与内置<39>-Footnote-702592235
Ref: 核心与内置<39>-Footnote-712592279
Ref: 核心与内置<39>-Footnote-722592323
Ref: 核心与内置<39>-Footnote-732592367
Ref: 核心与内置<39>-Footnote-742592411
Ref: 核心与内置<39>-Footnote-752592455
Ref: 核心与内置<39>-Footnote-762592499
Ref: 核心与内置<39>-Footnote-772592543
Ref: 核心与内置<39>-Footnote-782592587
Ref: 核心与内置<39>-Footnote-792592631
Ref: 核心与内置<39>-Footnote-802592675
Ref: 核心与内置<39>-Footnote-812592719
Ref: 核心与内置<39>-Footnote-822592763
Ref: 核心与内置<39>-Footnote-832592807
Ref: 核心与内置<39>-Footnote-842592851
Ref: 核心与内置<39>-Footnote-852592895
Ref: 核心与内置<39>-Footnote-862592939
Ref: 核心与内置<39>-Footnote-872592983
Ref: 核心与内置<39>-Footnote-882593027
Ref: 核心与内置<39>-Footnote-892593071
Ref: 核心与内置<39>-Footnote-902593115
Ref: 核心与内置<39>-Footnote-912593165
Ref: 核心与内置<39>-Footnote-922593209
Ref: 核心与内置<39>-Footnote-932593253
Ref: 核心与内置<39>-Footnote-942593297
Ref: 核心与内置<39>-Footnote-952593341
Ref: 核心与内置<39>-Footnote-962593385
Ref: 核心与内置<39>-Footnote-972593429
Ref: 核心与内置<39>-Footnote-982593473
Ref: 核心与内置<39>-Footnote-992593517
Ref: 核心与内置<39>-Footnote-1002593561
Ref: 核心与内置<39>-Footnote-1012593606
Ref: 核心与内置<39>-Footnote-1022593651
Ref: 核心与内置<39>-Footnote-1032593696
Ref: 核心与内置<39>-Footnote-1042593741
Ref: 核心与内置<39>-Footnote-1052593786
Ref: 核心与内置<39>-Footnote-1062593831
Ref: 核心与内置<39>-Footnote-1072593876
Ref: 核心与内置<39>-Footnote-1082593921
Ref: 核心与内置<39>-Footnote-1092593966
Ref: 核心与内置<39>-Footnote-1102594011
Ref: 核心与内置<39>-Footnote-1112594056
Ref: 核心与内置<39>-Footnote-1122594101
Ref: 核心与内置<39>-Footnote-1132594146
Ref: 核心与内置<39>-Footnote-1142594191
Ref: 核心与内置<39>-Footnote-1152594236
Ref: 核心与内置<39>-Footnote-1162594281
Ref: 核心与内置<39>-Footnote-1172594326
Ref: 核心与内置<39>-Footnote-1182594371
Ref: 核心与内置<39>-Footnote-1192594416
Ref: 核心与内置<39>-Footnote-1202594461
Ref: 核心与内置<39>-Footnote-1212594506
Ref: 核心与内置<39>-Footnote-1222594551
Ref: 核心与内置<39>-Footnote-1232594596
Ref: 核心与内置<39>-Footnote-1242594641
Ref: 核心与内置<39>-Footnote-1252594686
Ref: 核心与内置<39>-Footnote-1262594731
Ref: 核心与内置<39>-Footnote-1272594776
Ref: 核心与内置<39>-Footnote-1282594821
Ref: 核心与内置<39>-Footnote-1292594866
Ref: 核心与内置<39>-Footnote-1302594911
Ref: 核心与内置<39>-Footnote-1312594956
Ref: 核心与内置<39>-Footnote-1322595001
Ref: 核心与内置<39>-Footnote-1332595046
Ref: 核心与内置<39>-Footnote-1342595091
Ref: 核心与内置<39>-Footnote-1352595136
Ref: 核心与内置<39>-Footnote-1362595181
Ref: 核心与内置<39>-Footnote-1372595226
Ref: 核心与内置<39>-Footnote-1382595271
Ref: 核心与内置<39>-Footnote-1392595316
Ref: 核心与内置<39>-Footnote-1402595361
Ref: 核心与内置<39>-Footnote-1412595406
Ref: 核心与内置<39>-Footnote-1422595451
Ref: 核心与内置<39>-Footnote-1432595496
Ref: 核心与内置<39>-Footnote-1442595541
Ref: 核心与内置<39>-Footnote-1452595586
Ref: 核心与内置<39>-Footnote-1462595631
Ref: 核心与内置<39>-Footnote-1472595676
Ref: 核心与内置<39>-Footnote-1482595721
Node: 库<40>2595766
Ref: whatsnew/changelog id2992595877
Ref: 10cb2595877
Ref: 库<40>-Footnote-12642483
Ref: 库<40>-Footnote-22642526
Ref: 库<40>-Footnote-32642569
Ref: 库<40>-Footnote-42642612
Ref: 库<40>-Footnote-52642655
Ref: 库<40>-Footnote-62642698
Ref: 库<40>-Footnote-72642741
Ref: 库<40>-Footnote-82642784
Ref: 库<40>-Footnote-92642827
Ref: 库<40>-Footnote-102642870
Ref: 库<40>-Footnote-112642914
Ref: 库<40>-Footnote-122642958
Ref: 库<40>-Footnote-132643002
Ref: 库<40>-Footnote-142643046
Ref: 库<40>-Footnote-152643090
Ref: 库<40>-Footnote-162643134
Ref: 库<40>-Footnote-172643178
Ref: 库<40>-Footnote-182643222
Ref: 库<40>-Footnote-192643266
Ref: 库<40>-Footnote-202643310
Ref: 库<40>-Footnote-212643354
Ref: 库<40>-Footnote-222643400
Ref: 库<40>-Footnote-232643444
Ref: 库<40>-Footnote-242643488
Ref: 库<40>-Footnote-252643532
Ref: 库<40>-Footnote-262643576
Ref: 库<40>-Footnote-272643626
Ref: 库<40>-Footnote-282643670
Ref: 库<40>-Footnote-292643714
Ref: 库<40>-Footnote-302643758
Ref: 库<40>-Footnote-312643802
Ref: 库<40>-Footnote-322643846
Ref: 库<40>-Footnote-332643890
Ref: 库<40>-Footnote-342643934
Ref: 库<40>-Footnote-352643977
Ref: 库<40>-Footnote-362644021
Ref: 库<40>-Footnote-372644065
Ref: 库<40>-Footnote-382644109
Ref: 库<40>-Footnote-392644153
Ref: 库<40>-Footnote-402644196
Ref: 库<40>-Footnote-412644240
Ref: 库<40>-Footnote-422644284
Ref: 库<40>-Footnote-432644328
Ref: 库<40>-Footnote-442644372
Ref: 库<40>-Footnote-452644416
Ref: 库<40>-Footnote-462644460
Ref: 库<40>-Footnote-472644504
Ref: 库<40>-Footnote-482644548
Ref: 库<40>-Footnote-492644592
Ref: 库<40>-Footnote-502644636
Ref: 库<40>-Footnote-512644680
Ref: 库<40>-Footnote-522644724
Ref: 库<40>-Footnote-532644767
Ref: 库<40>-Footnote-542644811
Ref: 库<40>-Footnote-552644855
Ref: 库<40>-Footnote-562644899
Ref: 库<40>-Footnote-572644943
Ref: 库<40>-Footnote-582644987
Ref: 库<40>-Footnote-592645031
Ref: 库<40>-Footnote-602645075
Ref: 库<40>-Footnote-612645119
Ref: 库<40>-Footnote-622645163
Ref: 库<40>-Footnote-632645207
Ref: 库<40>-Footnote-642645251
Ref: 库<40>-Footnote-652645295
Ref: 库<40>-Footnote-662645339
Ref: 库<40>-Footnote-672645383
Ref: 库<40>-Footnote-682645427
Ref: 库<40>-Footnote-692645471
Ref: 库<40>-Footnote-702645515
Ref: 库<40>-Footnote-712645559
Ref: 库<40>-Footnote-722645603
Ref: 库<40>-Footnote-732645646
Ref: 库<40>-Footnote-742645690
Ref: 库<40>-Footnote-752645734
Ref: 库<40>-Footnote-762645778
Ref: 库<40>-Footnote-772645822
Ref: 库<40>-Footnote-782645866
Ref: 库<40>-Footnote-792645910
Ref: 库<40>-Footnote-802645954
Ref: 库<40>-Footnote-812645998
Ref: 库<40>-Footnote-822646042
Ref: 库<40>-Footnote-832646086
Ref: 库<40>-Footnote-842646130
Ref: 库<40>-Footnote-852646174
Ref: 库<40>-Footnote-862646218
Ref: 库<40>-Footnote-872646262
Ref: 库<40>-Footnote-882646306
Ref: 库<40>-Footnote-892646350
Ref: 库<40>-Footnote-902646394
Ref: 库<40>-Footnote-912646438
Ref: 库<40>-Footnote-922646482
Ref: 库<40>-Footnote-932646526
Ref: 库<40>-Footnote-942646570
Ref: 库<40>-Footnote-952646614
Ref: 库<40>-Footnote-962646658
Ref: 库<40>-Footnote-972646702
Ref: 库<40>-Footnote-982646746
Ref: 库<40>-Footnote-992646790
Ref: 库<40>-Footnote-1002646834
Ref: 库<40>-Footnote-1012646879
Ref: 库<40>-Footnote-1022646924
Ref: 库<40>-Footnote-1032646969
Ref: 库<40>-Footnote-1042647014
Ref: 库<40>-Footnote-1052647059
Ref: 库<40>-Footnote-1062647104
Ref: 库<40>-Footnote-1072647149
Ref: 库<40>-Footnote-1082647194
Ref: 库<40>-Footnote-1092647239
Ref: 库<40>-Footnote-1102647284
Ref: 库<40>-Footnote-1112647329
Ref: 库<40>-Footnote-1122647374
Ref: 库<40>-Footnote-1132647419
Ref: 库<40>-Footnote-1142647464
Ref: 库<40>-Footnote-1152647509
Ref: 库<40>-Footnote-1162647554
Ref: 库<40>-Footnote-1172647598
Ref: 库<40>-Footnote-1182647643
Ref: 库<40>-Footnote-1192647688
Ref: 库<40>-Footnote-1202647733
Ref: 库<40>-Footnote-1212647778
Ref: 库<40>-Footnote-1222647823
Ref: 库<40>-Footnote-1232647868
Ref: 库<40>-Footnote-1242647913
Ref: 库<40>-Footnote-1252647958
Ref: 库<40>-Footnote-1262648003
Ref: 库<40>-Footnote-1272648048
Ref: 库<40>-Footnote-1282648093
Ref: 库<40>-Footnote-1292648138
Ref: 库<40>-Footnote-1302648183
Ref: 库<40>-Footnote-1312648228
Ref: 库<40>-Footnote-1322648273
Ref: 库<40>-Footnote-1332648318
Ref: 库<40>-Footnote-1342648363
Ref: 库<40>-Footnote-1352648408
Ref: 库<40>-Footnote-1362648453
Ref: 库<40>-Footnote-1372648498
Ref: 库<40>-Footnote-1382648543
Ref: 库<40>-Footnote-1392648588
Ref: 库<40>-Footnote-1402648633
Ref: 库<40>-Footnote-1412648678
Ref: 库<40>-Footnote-1422648723
Ref: 库<40>-Footnote-1432648768
Ref: 库<40>-Footnote-1442648813
Ref: 库<40>-Footnote-1452648858
Ref: 库<40>-Footnote-1462648903
Ref: 库<40>-Footnote-1472648947
Ref: 库<40>-Footnote-1482648992
Ref: 库<40>-Footnote-1492649037
Ref: 库<40>-Footnote-1502649082
Ref: 库<40>-Footnote-1512649127
Ref: 库<40>-Footnote-1522649172
Ref: 库<40>-Footnote-1532649217
Ref: 库<40>-Footnote-1542649262
Ref: 库<40>-Footnote-1552649307
Ref: 库<40>-Footnote-1562649352
Ref: 库<40>-Footnote-1572649397
Ref: 库<40>-Footnote-1582649442
Ref: 库<40>-Footnote-1592649487
Ref: 库<40>-Footnote-1602649532
Ref: 库<40>-Footnote-1612649577
Ref: 库<40>-Footnote-1622649622
Ref: 库<40>-Footnote-1632649667
Ref: 库<40>-Footnote-1642649712
Ref: 库<40>-Footnote-1652649757
Ref: 库<40>-Footnote-1662649802
Ref: 库<40>-Footnote-1672649847
Ref: 库<40>-Footnote-1682649892
Ref: 库<40>-Footnote-1692649937
Ref: 库<40>-Footnote-1702649981
Ref: 库<40>-Footnote-1712650026
Ref: 库<40>-Footnote-1722650071
Ref: 库<40>-Footnote-1732650116
Ref: 库<40>-Footnote-1742650161
Ref: 库<40>-Footnote-1752650206
Ref: 库<40>-Footnote-1762650251
Ref: 库<40>-Footnote-1772650296
Ref: 库<40>-Footnote-1782650341
Ref: 库<40>-Footnote-1792650386
Ref: 库<40>-Footnote-1802650431
Ref: 库<40>-Footnote-1812650475
Ref: 库<40>-Footnote-1822650520
Ref: 库<40>-Footnote-1832650565
Ref: 库<40>-Footnote-1842650610
Ref: 库<40>-Footnote-1852650655
Ref: 库<40>-Footnote-1862650700
Ref: 库<40>-Footnote-1872650744
Ref: 库<40>-Footnote-1882650789
Ref: 库<40>-Footnote-1892650834
Ref: 库<40>-Footnote-1902650879
Ref: 库<40>-Footnote-1912650924
Ref: 库<40>-Footnote-1922650969
Ref: 库<40>-Footnote-1932651014
Ref: 库<40>-Footnote-1942651059
Ref: 库<40>-Footnote-1952651104
Ref: 库<40>-Footnote-1962651149
Ref: 库<40>-Footnote-1972651194
Ref: 库<40>-Footnote-1982651239
Ref: 库<40>-Footnote-1992651284
Ref: 库<40>-Footnote-2002651329
Ref: 库<40>-Footnote-2012651374
Ref: 库<40>-Footnote-2022651419
Ref: 库<40>-Footnote-2032651464
Ref: 库<40>-Footnote-2042651509
Ref: 库<40>-Footnote-2052651554
Ref: 库<40>-Footnote-2062651599
Ref: 库<40>-Footnote-2072651644
Ref: 库<40>-Footnote-2082651689
Ref: 库<40>-Footnote-2092651734
Ref: 库<40>-Footnote-2102651779
Ref: 库<40>-Footnote-2112651824
Ref: 库<40>-Footnote-2122651869
Ref: 库<40>-Footnote-2132651914
Ref: 库<40>-Footnote-2142651959
Ref: 库<40>-Footnote-2152652004
Ref: 库<40>-Footnote-2162652049
Ref: 库<40>-Footnote-2172652094
Ref: 库<40>-Footnote-2182652139
Ref: 库<40>-Footnote-2192652184
Ref: 库<40>-Footnote-2202652229
Ref: 库<40>-Footnote-2212652274
Ref: 库<40>-Footnote-2222652319
Ref: 库<40>-Footnote-2232652364
Ref: 库<40>-Footnote-2242652409
Ref: 库<40>-Footnote-2252652453
Ref: 库<40>-Footnote-2262652498
Ref: 库<40>-Footnote-2272652543
Ref: 库<40>-Footnote-2282652588
Ref: 库<40>-Footnote-2292652633
Ref: 库<40>-Footnote-2302652678
Ref: 库<40>-Footnote-2312652723
Ref: 库<40>-Footnote-2322652768
Ref: 库<40>-Footnote-2332652813
Ref: 库<40>-Footnote-2342652858
Ref: 库<40>-Footnote-2352652903
Ref: 库<40>-Footnote-2362652948
Ref: 库<40>-Footnote-2372652993
Ref: 库<40>-Footnote-2382653038
Ref: 库<40>-Footnote-2392653083
Ref: 库<40>-Footnote-2402653128
Ref: 库<40>-Footnote-2412653173
Ref: 库<40>-Footnote-2422653218
Ref: 库<40>-Footnote-2432653263
Ref: 库<40>-Footnote-2442653308
Ref: 库<40>-Footnote-2452653353
Ref: 库<40>-Footnote-2462653398
Ref: 库<40>-Footnote-2472653443
Ref: 库<40>-Footnote-2482653488
Ref: 库<40>-Footnote-2492653533
Ref: 库<40>-Footnote-2502653578
Ref: 库<40>-Footnote-2512653623
Ref: 库<40>-Footnote-2522653668
Ref: 库<40>-Footnote-2532653713
Ref: 库<40>-Footnote-2542653758
Ref: 库<40>-Footnote-2552653803
Ref: 库<40>-Footnote-2562653848
Ref: 库<40>-Footnote-2572653893
Ref: 库<40>-Footnote-2582653938
Ref: 库<40>-Footnote-2592653983
Ref: 库<40>-Footnote-2602654028
Ref: 库<40>-Footnote-2612654073
Ref: 库<40>-Footnote-2622654118
Ref: 库<40>-Footnote-2632654163
Ref: 库<40>-Footnote-2642654208
Ref: 库<40>-Footnote-2652654253
Ref: 库<40>-Footnote-2662654298
Ref: 库<40>-Footnote-2672654343
Ref: 库<40>-Footnote-2682654388
Ref: 库<40>-Footnote-2692654433
Ref: 库<40>-Footnote-2702654478
Ref: 库<40>-Footnote-2712654523
Ref: 库<40>-Footnote-2722654568
Ref: 库<40>-Footnote-2732654624
Ref: 库<40>-Footnote-2742654669
Ref: 库<40>-Footnote-2752654714
Ref: 库<40>-Footnote-2762654759
Ref: 库<40>-Footnote-2772654804
Ref: 库<40>-Footnote-2782654849
Ref: 库<40>-Footnote-2792654894
Ref: 库<40>-Footnote-2802654939
Ref: 库<40>-Footnote-2812654984
Ref: 库<40>-Footnote-2822655029
Ref: 库<40>-Footnote-2832655074
Ref: 库<40>-Footnote-2842655119
Ref: 库<40>-Footnote-2852655164
Ref: 库<40>-Footnote-2862655209
Ref: 库<40>-Footnote-2872655254
Ref: 库<40>-Footnote-2882655299
Ref: 库<40>-Footnote-2892655344
Ref: 库<40>-Footnote-2902655389
Ref: 库<40>-Footnote-2912655434
Ref: 库<40>-Footnote-2922655479
Ref: 库<40>-Footnote-2932655524
Ref: 库<40>-Footnote-2942655569
Ref: 库<40>-Footnote-2952655614
Ref: 库<40>-Footnote-2962655659
Ref: 库<40>-Footnote-2972655704
Ref: 库<40>-Footnote-2982655749
Ref: 库<40>-Footnote-2992655794
Ref: 库<40>-Footnote-3002655839
Ref: 库<40>-Footnote-3012655884
Ref: 库<40>-Footnote-3022655929
Ref: 库<40>-Footnote-3032655974
Ref: 库<40>-Footnote-3042656019
Ref: 库<40>-Footnote-3052656064
Ref: 库<40>-Footnote-3062656109
Ref: 库<40>-Footnote-3072656154
Ref: 库<40>-Footnote-3082656199
Ref: 库<40>-Footnote-3092656244
Ref: 库<40>-Footnote-3102656289
Ref: 库<40>-Footnote-3112656334
Ref: 库<40>-Footnote-3122656379
Ref: 库<40>-Footnote-3132656424
Ref: 库<40>-Footnote-3142656469
Ref: 库<40>-Footnote-3152656514
Ref: 库<40>-Footnote-3162656559
Ref: 库<40>-Footnote-3172656604
Ref: 库<40>-Footnote-3182656649
Ref: 库<40>-Footnote-3192656694
Ref: 库<40>-Footnote-3202656739
Ref: 库<40>-Footnote-3212656784
Ref: 库<40>-Footnote-3222656829
Ref: 库<40>-Footnote-3232656874
Ref: 库<40>-Footnote-3242656919
Ref: 库<40>-Footnote-3252656964
Ref: 库<40>-Footnote-3262657009
Node: 文档<35>2657054
Ref: whatsnew/changelog id3002657156
Ref: 10cc2657156
Ref: 文档<35>-Footnote-12659306
Ref: 文档<35>-Footnote-22659349
Ref: 文档<35>-Footnote-32659392
Ref: 文档<35>-Footnote-42659435
Ref: 文档<35>-Footnote-52659478
Ref: 文档<35>-Footnote-62659521
Ref: 文档<35>-Footnote-72659564
Ref: 文档<35>-Footnote-82659607
Ref: 文档<35>-Footnote-92659650
Ref: 文档<35>-Footnote-102659693
Ref: 文档<35>-Footnote-112659737
Ref: 文档<35>-Footnote-122659781
Ref: 文档<35>-Footnote-132659825
Ref: 文档<35>-Footnote-142659869
Ref: 文档<35>-Footnote-152659913
Ref: 文档<35>-Footnote-162659957
Ref: 文档<35>-Footnote-172660007
Node: 测试<28>2660051
Ref: whatsnew/changelog id3012660156
Ref: 10cf2660156
Ref: 测试<28>-Footnote-12662906
Ref: 测试<28>-Footnote-22662949
Ref: 测试<28>-Footnote-32662992
Ref: 测试<28>-Footnote-42663035
Ref: 测试<28>-Footnote-52663078
Ref: 测试<28>-Footnote-62663121
Ref: 测试<28>-Footnote-72663164
Ref: 测试<28>-Footnote-82663207
Ref: 测试<28>-Footnote-92663250
Ref: 测试<28>-Footnote-102663293
Ref: 测试<28>-Footnote-112663337
Ref: 测试<28>-Footnote-122663381
Ref: 测试<28>-Footnote-132663425
Ref: 测试<28>-Footnote-142663469
Ref: 测试<28>-Footnote-152663513
Ref: 测试<28>-Footnote-162663557
Ref: 测试<28>-Footnote-172663601
Ref: 测试<28>-Footnote-182663645
Ref: 测试<28>-Footnote-192663689
Node: 构建<26>2663733
Ref: whatsnew/changelog id3022663839
Ref: 10d02663839
Ref: 构建<26>-Footnote-12668591
Ref: 构建<26>-Footnote-22668634
Ref: 构建<26>-Footnote-32668677
Ref: 构建<26>-Footnote-42668720
Ref: 构建<26>-Footnote-52668769
Ref: 构建<26>-Footnote-62668812
Ref: 构建<26>-Footnote-72668855
Ref: 构建<26>-Footnote-82668898
Ref: 构建<26>-Footnote-92668941
Ref: 构建<26>-Footnote-102668984
Ref: 构建<26>-Footnote-112669028
Ref: 构建<26>-Footnote-122669072
Ref: 构建<26>-Footnote-132669116
Ref: 构建<26>-Footnote-142669160
Ref: 构建<26>-Footnote-152669204
Ref: 构建<26>-Footnote-162669248
Ref: 构建<26>-Footnote-172669292
Ref: 构建<26>-Footnote-182669336
Ref: 构建<26>-Footnote-192669380
Ref: 构建<26>-Footnote-202669424
Ref: 构建<26>-Footnote-212669468
Ref: 构建<26>-Footnote-222669512
Ref: 构建<26>-Footnote-232669556
Ref: 构建<26>-Footnote-242669600
Ref: 构建<26>-Footnote-252669644
Ref: 构建<26>-Footnote-262669688
Ref: 构建<26>-Footnote-272669732
Ref: 构建<26>-Footnote-282669776
Ref: 构建<26>-Footnote-292669820
Ref: 构建<26>-Footnote-302669864
Ref: 构建<26>-Footnote-312669908
Ref: 构建<26>-Footnote-322669952
Ref: 构建<26>-Footnote-332669996
Ref: 构建<26>-Footnote-342670040
Ref: 构建<26>-Footnote-352670084
Ref: 构建<26>-Footnote-362670128
Ref: 构建<26>-Footnote-372670172
Node: Windows<30>2670216
Ref: whatsnew/changelog id3032670320
Ref: 10d12670320
Ref: Windows<30>-Footnote-12672807
Ref: Windows<30>-Footnote-22672850
Ref: Windows<30>-Footnote-32672893
Ref: Windows<30>-Footnote-42672936
Ref: Windows<30>-Footnote-52672979
Ref: Windows<30>-Footnote-62673022
Ref: Windows<30>-Footnote-72673065
Ref: Windows<30>-Footnote-82673108
Ref: Windows<30>-Footnote-92673151
Ref: Windows<30>-Footnote-102673194
Ref: Windows<30>-Footnote-112673238
Ref: Windows<30>-Footnote-122673282
Ref: Windows<30>-Footnote-132673326
Ref: Windows<30>-Footnote-142673370
Ref: Windows<30>-Footnote-152673414
Ref: Windows<30>-Footnote-162673458
Ref: Windows<30>-Footnote-172673502
Ref: Windows<30>-Footnote-182673546
Ref: Windows<30>-Footnote-192673590
Ref: Windows<30>-Footnote-202673634
Ref: Windows<30>-Footnote-212673678
Ref: Windows<30>-Footnote-222673722
Ref: Windows<30>-Footnote-232673766
Ref: Windows<30>-Footnote-242673810
Ref: Windows<30>-Footnote-252673854
Node: IDLE<35>2673898
Ref: whatsnew/changelog id3042674009
Ref: 10d22674009
Ref: IDLE<35>-Footnote-12684026
Ref: IDLE<35>-Footnote-22684069
Ref: IDLE<35>-Footnote-32684112
Ref: IDLE<35>-Footnote-42684155
Ref: IDLE<35>-Footnote-52684198
Ref: IDLE<35>-Footnote-62684241
Ref: IDLE<35>-Footnote-72684284
Ref: IDLE<35>-Footnote-82684327
Ref: IDLE<35>-Footnote-92684370
Ref: IDLE<35>-Footnote-102684413
Ref: IDLE<35>-Footnote-112684457
Ref: IDLE<35>-Footnote-122684501
Ref: IDLE<35>-Footnote-132684545
Ref: IDLE<35>-Footnote-142684589
Ref: IDLE<35>-Footnote-152684633
Ref: IDLE<35>-Footnote-162684677
Ref: IDLE<35>-Footnote-172684721
Ref: IDLE<35>-Footnote-182684765
Ref: IDLE<35>-Footnote-192684809
Ref: IDLE<35>-Footnote-202684853
Ref: IDLE<35>-Footnote-212684897
Ref: IDLE<35>-Footnote-222684941
Ref: IDLE<35>-Footnote-232684985
Ref: IDLE<35>-Footnote-242685029
Ref: IDLE<35>-Footnote-252685073
Ref: IDLE<35>-Footnote-262685117
Ref: IDLE<35>-Footnote-272685161
Ref: IDLE<35>-Footnote-282685205
Ref: IDLE<35>-Footnote-292685249
Ref: IDLE<35>-Footnote-302685293
Ref: IDLE<35>-Footnote-312685337
Ref: IDLE<35>-Footnote-322685381
Ref: IDLE<35>-Footnote-332685425
Ref: IDLE<35>-Footnote-342685469
Ref: IDLE<35>-Footnote-352685512
Ref: IDLE<35>-Footnote-362685556
Ref: IDLE<35>-Footnote-372685600
Ref: IDLE<35>-Footnote-382685644
Ref: IDLE<35>-Footnote-392685688
Ref: IDLE<35>-Footnote-402685732
Ref: IDLE<35>-Footnote-412685776
Ref: IDLE<35>-Footnote-422685820
Ref: IDLE<35>-Footnote-432685864
Ref: IDLE<35>-Footnote-442685907
Ref: IDLE<35>-Footnote-452685951
Ref: IDLE<35>-Footnote-462685995
Ref: IDLE<35>-Footnote-472686039
Ref: IDLE<35>-Footnote-482686083
Ref: IDLE<35>-Footnote-492686127
Ref: IDLE<35>-Footnote-502686171
Ref: IDLE<35>-Footnote-512686215
Node: 工具/示例<18>2686259
Ref: whatsnew/changelog id3052686368
Ref: 10d32686368
Ref: 工具/示例<18>-Footnote-12687863
Ref: 工具/示例<18>-Footnote-22687906
Ref: 工具/示例<18>-Footnote-32687955
Ref: 工具/示例<18>-Footnote-42687998
Ref: 工具/示例<18>-Footnote-52688041
Ref: 工具/示例<18>-Footnote-62688084
Ref: 工具/示例<18>-Footnote-72688127
Ref: 工具/示例<18>-Footnote-82688170
Node: C API<22>2688213
Ref: whatsnew/changelog id3062688305
Ref: 10d42688305
Ref: C API<22>-Footnote-12691361
Ref: C API<22>-Footnote-22691404
Ref: C API<22>-Footnote-32691447
Ref: C API<22>-Footnote-42691490
Ref: C API<22>-Footnote-52691533
Ref: C API<22>-Footnote-62691575
Ref: C API<22>-Footnote-72691618
Ref: C API<22>-Footnote-82691661
Ref: C API<22>-Footnote-92691704
Ref: C API<22>-Footnote-102691747
Ref: C API<22>-Footnote-112691791
Ref: C API<22>-Footnote-122691835
Ref: C API<22>-Footnote-132691879
Ref: C API<22>-Footnote-142691923
Ref: C API<22>-Footnote-152691967
Node: Python 3 6 6 正式版2692011
Ref: whatsnew/changelog python-3-6-6-final2692136
Ref: 10d52692136
Node: Python 3 6 6 rc12692266
Ref: whatsnew/changelog python-3-6-6-release-candidate-12692393
Ref: 10d62692393
Node: 核心与内置<40>2692722
Ref: whatsnew/changelog id3072692810
Ref: 10d72692810
Ref: 核心与内置<40>-Footnote-12694388
Ref: 核心与内置<40>-Footnote-22694431
Ref: 核心与内置<40>-Footnote-32694474
Ref: 核心与内置<40>-Footnote-42694517
Ref: 核心与内置<40>-Footnote-52694560
Ref: 核心与内置<40>-Footnote-62694603
Ref: 核心与内置<40>-Footnote-72694646
Ref: 核心与内置<40>-Footnote-82694689
Ref: 核心与内置<40>-Footnote-92694732
Ref: 核心与内置<40>-Footnote-102694775
Ref: 核心与内置<40>-Footnote-112694819
Ref: 核心与内置<40>-Footnote-122694863
Node: 库<41>2694907
Ref: whatsnew/changelog id3082695014
Ref: 10d82695014
Ref: 库<41>-Footnote-12700480
Ref: 库<41>-Footnote-22700523
Ref: 库<41>-Footnote-32700566
Ref: 库<41>-Footnote-42700609
Ref: 库<41>-Footnote-52700652
Ref: 库<41>-Footnote-62700695
Ref: 库<41>-Footnote-72700738
Ref: 库<41>-Footnote-82700781
Ref: 库<41>-Footnote-92700824
Ref: 库<41>-Footnote-102700867
Ref: 库<41>-Footnote-112700911
Ref: 库<41>-Footnote-122700955
Ref: 库<41>-Footnote-132700999
Ref: 库<41>-Footnote-142701043
Ref: 库<41>-Footnote-152701087
Ref: 库<41>-Footnote-162701131
Ref: 库<41>-Footnote-172701175
Ref: 库<41>-Footnote-182701219
Ref: 库<41>-Footnote-192701263
Ref: 库<41>-Footnote-202701307
Ref: 库<41>-Footnote-212701351
Ref: 库<41>-Footnote-222701396
Ref: 库<41>-Footnote-232701440
Ref: 库<41>-Footnote-242701484
Ref: 库<41>-Footnote-252701528
Ref: 库<41>-Footnote-262701572
Ref: 库<41>-Footnote-272701616
Ref: 库<41>-Footnote-282701660
Ref: 库<41>-Footnote-292701710
Ref: 库<41>-Footnote-302701754
Ref: 库<41>-Footnote-312701798
Ref: 库<41>-Footnote-322701842
Ref: 库<41>-Footnote-332701886
Ref: 库<41>-Footnote-342701930
Ref: 库<41>-Footnote-352701974
Ref: 库<41>-Footnote-362702018
Ref: 库<41>-Footnote-372702062
Ref: 库<41>-Footnote-382702106
Ref: 库<41>-Footnote-392702150
Node: 文档<36>2702194
Ref: whatsnew/changelog id3092702292
Ref: 10d92702292
Ref: 文档<36>-Footnote-12703769
Ref: 文档<36>-Footnote-22703812
Ref: 文档<36>-Footnote-32703855
Ref: 文档<36>-Footnote-42703898
Ref: 文档<36>-Footnote-52703941
Ref: 文档<36>-Footnote-62703984
Ref: 文档<36>-Footnote-72704027
Ref: 文档<36>-Footnote-82704070
Ref: 文档<36>-Footnote-92704113
Ref: 文档<36>-Footnote-102704156
Ref: 文档<36>-Footnote-112704200
Ref: 文档<36>-Footnote-122704244
Ref: 文档<36>-Footnote-132704287
Node: 测试<29>2704331
Ref: whatsnew/changelog id3102704432
Ref: 10da2704432
Ref: 测试<29>-Footnote-12704633
Ref: 测试<29>-Footnote-22704676
Node: 构建<27>2704719
Ref: whatsnew/changelog id3112704821
Ref: 10db2704821
Ref: 构建<27>-Footnote-12705618
Ref: 构建<27>-Footnote-22705660
Ref: 构建<27>-Footnote-32705703
Ref: 构建<27>-Footnote-42705746
Ref: 构建<27>-Footnote-52705789
Node: Windows<31>2705832
Ref: whatsnew/changelog id3122705933
Ref: 10dc2705933
Ref: Windows<31>-Footnote-12706071
Node: macOS<23>2706114
Ref: whatsnew/changelog id3132706213
Ref: 10dd2706213
Ref: macOS<23>-Footnote-12706351
Node: IDLE<36>2706394
Ref: whatsnew/changelog id3142706499
Ref: 10de2706499
Ref: IDLE<36>-Footnote-12708568
Ref: IDLE<36>-Footnote-22708611
Ref: IDLE<36>-Footnote-32708654
Ref: IDLE<36>-Footnote-42708697
Ref: IDLE<36>-Footnote-52708740
Ref: IDLE<36>-Footnote-62708783
Ref: IDLE<36>-Footnote-72708826
Ref: IDLE<36>-Footnote-82708869
Ref: IDLE<36>-Footnote-92708912
Ref: IDLE<36>-Footnote-102708955
Ref: IDLE<36>-Footnote-112708999
Ref: IDLE<36>-Footnote-122709043
Node: 工具/示例<19>2709087
Ref: whatsnew/changelog id3152709192
Ref: 10df2709192
Ref: 工具/示例<19>-Footnote-12709947
Ref: 工具/示例<19>-Footnote-22709990
Ref: 工具/示例<19>-Footnote-32710033
Ref: 工具/示例<19>-Footnote-42710076
Ref: 工具/示例<19>-Footnote-52710119
Node: C API<23>2710162
Ref: whatsnew/changelog id3162710250
Ref: 10e02710250
Ref: C API<23>-Footnote-12710463
Node: Python 3 6 5 正式版2710506
Ref: whatsnew/changelog python-3-6-5-final2710627
Ref: 10e12710627
Node: 测试<30>2710769
Ref: whatsnew/changelog id3172710857
Ref: 10e22710857
Ref: 测试<30>-Footnote-12711011
Node: 构建<28>2711054
Ref: whatsnew/changelog id3182711142
Ref: 10e32711142
Ref: 构建<28>-Footnote-12711279
Node: Python 3 6 5 rc12711322
Ref: whatsnew/changelog python-3-6-5-release-candidate-12711449
Ref: 10e42711449
Node: 安全<25>2711800
Ref: whatsnew/changelog id3192711891
Ref: 10e52711891
Ref: 安全<25>-Footnote-12712310
Ref: 安全<25>-Footnote-22712353
Node: 核心与内置<41>2712396
Ref: whatsnew/changelog id3202712503
Ref: 10e62712503
Ref: 核心与内置<41>-Footnote-12714664
Ref: 核心与内置<41>-Footnote-22714707
Ref: 核心与内置<41>-Footnote-32714750
Ref: 核心与内置<41>-Footnote-42714793
Ref: 核心与内置<41>-Footnote-52714836
Ref: 核心与内置<41>-Footnote-62714879
Ref: 核心与内置<41>-Footnote-72714922
Ref: 核心与内置<41>-Footnote-82714965
Ref: 核心与内置<41>-Footnote-92715008
Ref: 核心与内置<41>-Footnote-102715051
Ref: 核心与内置<41>-Footnote-112715095
Ref: 核心与内置<41>-Footnote-122715139
Ref: 核心与内置<41>-Footnote-132715183
Ref: 核心与内置<41>-Footnote-142715227
Node: 库<42>2715271
Ref: whatsnew/changelog id3212715378
Ref: 10e72715378
Ref: 库<42>-Footnote-12721299
Ref: 库<42>-Footnote-22721342
Ref: 库<42>-Footnote-32721385
Ref: 库<42>-Footnote-42721428
Ref: 库<42>-Footnote-52721471
Ref: 库<42>-Footnote-62721514
Ref: 库<42>-Footnote-72721557
Ref: 库<42>-Footnote-82721600
Ref: 库<42>-Footnote-92721643
Ref: 库<42>-Footnote-102721686
Ref: 库<42>-Footnote-112721730
Ref: 库<42>-Footnote-122721774
Ref: 库<42>-Footnote-132721818
Ref: 库<42>-Footnote-142721862
Ref: 库<42>-Footnote-152721906
Ref: 库<42>-Footnote-162721950
Ref: 库<42>-Footnote-172721994
Ref: 库<42>-Footnote-182722038
Ref: 库<42>-Footnote-192722082
Ref: 库<42>-Footnote-202722126
Ref: 库<42>-Footnote-212722170
Ref: 库<42>-Footnote-222722214
Ref: 库<42>-Footnote-232722258
Ref: 库<42>-Footnote-242722302
Ref: 库<42>-Footnote-252722346
Ref: 库<42>-Footnote-262722390
Ref: 库<42>-Footnote-272722434
Ref: 库<42>-Footnote-282722478
Ref: 库<42>-Footnote-292722522
Ref: 库<42>-Footnote-302722566
Ref: 库<42>-Footnote-312722610
Ref: 库<42>-Footnote-322722654
Ref: 库<42>-Footnote-332722698
Ref: 库<42>-Footnote-342722742
Ref: 库<42>-Footnote-352722786
Ref: 库<42>-Footnote-362722830
Ref: 库<42>-Footnote-372722874
Ref: 库<42>-Footnote-382722918
Ref: 库<42>-Footnote-392722962
Ref: 库<42>-Footnote-402723006
Node: 文档<37>2723050
Ref: whatsnew/changelog id3222723148
Ref: 10e82723148
Ref: 文档<37>-Footnote-12723986
Ref: 文档<37>-Footnote-22724029
Ref: 文档<37>-Footnote-32724072
Ref: 文档<37>-Footnote-42724114
Ref: 文档<37>-Footnote-52724157
Ref: 文档<37>-Footnote-62724200
Node: 测试<31>2724243
Ref: whatsnew/changelog id3232724344
Ref: 10e92724344
Ref: 测试<31>-Footnote-12725005
Ref: 测试<31>-Footnote-22725048
Ref: 测试<31>-Footnote-32725091
Ref: 测试<31>-Footnote-42725134
Node: 构建<29>2725177
Ref: whatsnew/changelog id3242725279
Ref: 10ea2725279
Ref: 构建<29>-Footnote-12725468
Node: Windows<32>2725511
Ref: whatsnew/changelog id3252725612
Ref: 10eb2725612
Ref: Windows<32>-Footnote-12726562
Ref: Windows<32>-Footnote-22726605
Ref: Windows<32>-Footnote-32726648
Ref: Windows<32>-Footnote-42726691
Ref: Windows<32>-Footnote-52726734
Ref: Windows<32>-Footnote-62726777
Ref: Windows<32>-Footnote-72726820
Ref: Windows<32>-Footnote-82726863
Node: macOS<24>2726906
Ref: whatsnew/changelog id3262727005
Ref: 10ec2727005
Ref: macOS<24>-Footnote-12727398
Node: IDLE<37>2727441
Ref: whatsnew/changelog id3272727546
Ref: 10ed2727546
Ref: IDLE<37>-Footnote-12729036
Ref: IDLE<37>-Footnote-22729079
Ref: IDLE<37>-Footnote-32729122
Ref: IDLE<37>-Footnote-42729165
Ref: IDLE<37>-Footnote-52729208
Ref: IDLE<37>-Footnote-62729251
Ref: IDLE<37>-Footnote-72729294
Ref: IDLE<37>-Footnote-82729337
Node: 工具/示例<20>2729380
Ref: whatsnew/changelog id3282729485
Ref: 10ee2729485
Ref: 工具/示例<20>-Footnote-12729905
Ref: 工具/示例<20>-Footnote-22729948
Node: C API<24>2729991
Ref: whatsnew/changelog id3292730079
Ref: 10ef2730079
Ref: C API<24>-Footnote-12730329
Node: Python 3 6 4 正式版2730372
Ref: whatsnew/changelog python-3-6-4-final2730493
Ref: 10f02730493
Node: Python 3 6 4 rc12730646
Ref: whatsnew/changelog python-3-6-4-release-candidate-12730773
Ref: 10f12730773
Node: 核心与内置<42>2731102
Ref: whatsnew/changelog id3302731190
Ref: 10f22731190
Ref: 核心与内置<42>-Footnote-12735924
Ref: 核心与内置<42>-Footnote-22735967
Ref: 核心与内置<42>-Footnote-32736010
Ref: 核心与内置<42>-Footnote-42736053
Ref: 核心与内置<42>-Footnote-52736096
Ref: 核心与内置<42>-Footnote-62736139
Ref: 核心与内置<42>-Footnote-72736182
Ref: 核心与内置<42>-Footnote-82736225
Ref: 核心与内置<42>-Footnote-92736268
Ref: 核心与内置<42>-Footnote-102736311
Ref: 核心与内置<42>-Footnote-112736355
Ref: 核心与内置<42>-Footnote-122736399
Ref: 核心与内置<42>-Footnote-132736443
Ref: 核心与内置<42>-Footnote-142736487
Ref: 核心与内置<42>-Footnote-152736531
Ref: 核心与内置<42>-Footnote-162736575
Ref: 核心与内置<42>-Footnote-172736619
Ref: 核心与内置<42>-Footnote-182736663
Ref: 核心与内置<42>-Footnote-192736707
Ref: 核心与内置<42>-Footnote-202736751
Ref: 核心与内置<42>-Footnote-212736795
Ref: 核心与内置<42>-Footnote-222736839
Ref: 核心与内置<42>-Footnote-232736883
Ref: 核心与内置<42>-Footnote-242736927
Node: 库<43>2736971
Ref: whatsnew/changelog id3312737078
Ref: 10f32737078
Ref: 库<43>-Footnote-12744404
Ref: 库<43>-Footnote-22744447
Ref: 库<43>-Footnote-32744490
Ref: 库<43>-Footnote-42744533
Ref: 库<43>-Footnote-52744576
Ref: 库<43>-Footnote-62744619
Ref: 库<43>-Footnote-72744662
Ref: 库<43>-Footnote-82744705
Ref: 库<43>-Footnote-92744748
Ref: 库<43>-Footnote-102744791
Ref: 库<43>-Footnote-112744835
Ref: 库<43>-Footnote-122744879
Ref: 库<43>-Footnote-132744923
Ref: 库<43>-Footnote-142744967
Ref: 库<43>-Footnote-152745011
Ref: 库<43>-Footnote-162745055
Ref: 库<43>-Footnote-172745098
Ref: 库<43>-Footnote-182745142
Ref: 库<43>-Footnote-192745186
Ref: 库<43>-Footnote-202745230
Ref: 库<43>-Footnote-212745274
Ref: 库<43>-Footnote-222745318
Ref: 库<43>-Footnote-232745362
Ref: 库<43>-Footnote-242745406
Ref: 库<43>-Footnote-252745450
Ref: 库<43>-Footnote-262745494
Ref: 库<43>-Footnote-272745538
Ref: 库<43>-Footnote-282745582
Ref: 库<43>-Footnote-292745626
Ref: 库<43>-Footnote-302745670
Ref: 库<43>-Footnote-312745714
Ref: 库<43>-Footnote-322745758
Ref: 库<43>-Footnote-332745802
Ref: 库<43>-Footnote-342745846
Ref: 库<43>-Footnote-352745890
Ref: 库<43>-Footnote-362745934
Ref: 库<43>-Footnote-372745978
Ref: 库<43>-Footnote-382746022
Ref: 库<43>-Footnote-392746066
Ref: 库<43>-Footnote-402746110
Ref: 库<43>-Footnote-412746154
Ref: 库<43>-Footnote-422746198
Ref: 库<43>-Footnote-432746242
Ref: 库<43>-Footnote-442746286
Ref: 库<43>-Footnote-452746330
Ref: 库<43>-Footnote-462746374
Ref: 库<43>-Footnote-472746418
Ref: 库<43>-Footnote-482746462
Ref: 库<43>-Footnote-492746506
Ref: 库<43>-Footnote-502746550
Ref: 库<43>-Footnote-512746594
Ref: 库<43>-Footnote-522746638
Node: 文档<38>2746682
Ref: whatsnew/changelog id3322746780
Ref: 10f42746780
Ref: 文档<38>-Footnote-12747253
Ref: 文档<38>-Footnote-22747296
Ref: 文档<38>-Footnote-32747339
Node: 测试<32>2747382
Ref: whatsnew/changelog id3332747483
Ref: 10f52747483
Ref: 测试<32>-Footnote-12748155
Ref: 测试<32>-Footnote-22748198
Ref: 测试<32>-Footnote-32748241
Ref: 测试<32>-Footnote-42748284
Node: 构建<30>2748327
Ref: whatsnew/changelog id3342748429
Ref: 10f62748429
Ref: 构建<30>-Footnote-12749340
Ref: 构建<30>-Footnote-22749383
Ref: 构建<30>-Footnote-32749426
Ref: 构建<30>-Footnote-42749469
Ref: 构建<30>-Footnote-52749512
Ref: 构建<30>-Footnote-62749555
Ref: 构建<30>-Footnote-72749598
Ref: 构建<30>-Footnote-82749641
Ref: 构建<30>-Footnote-92749684
Node: Windows<33>2749727
Ref: whatsnew/changelog id3352749828
Ref: 10f72749828
Ref: Windows<33>-Footnote-12750146
Ref: Windows<33>-Footnote-22750188
Node: macOS<25>2750231
Ref: whatsnew/changelog id3362750330
Ref: 10f82750330
Ref: macOS<25>-Footnote-12750468
Node: IDLE<38>2750511
Ref: whatsnew/changelog id3372750616
Ref: 10f92750616
Ref: IDLE<38>-Footnote-12753953
Ref: IDLE<38>-Footnote-22753996
Ref: IDLE<38>-Footnote-32754039
Ref: IDLE<38>-Footnote-42754082
Ref: IDLE<38>-Footnote-52754125
Ref: IDLE<38>-Footnote-62754168
Ref: IDLE<38>-Footnote-72754211
Ref: IDLE<38>-Footnote-82754254
Ref: IDLE<38>-Footnote-92754297
Ref: IDLE<38>-Footnote-102754340
Ref: IDLE<38>-Footnote-112754384
Ref: IDLE<38>-Footnote-122754428
Ref: IDLE<38>-Footnote-132754472
Ref: IDLE<38>-Footnote-142754516
Node: 工具/示例<21>2754562
Ref: whatsnew/changelog id3382754667
Ref: 10fa2754667
Ref: 工具/示例<21>-Footnote-12754957
Node: C API<25>2755000
Ref: whatsnew/changelog id3392755088
Ref: 10fb2755088
Ref: C API<25>-Footnote-12755816
Ref: C API<25>-Footnote-22755859
Ref: C API<25>-Footnote-32755902
Ref: C API<25>-Footnote-42755945
Node: Python 3 6 3 正式版2755988
Ref: whatsnew/changelog python-3-6-3-final2756109
Ref: 10fc2756109
Node: 库<44>2756245
Ref: whatsnew/changelog id3402756330
Ref: 10fd2756330
Ref: 库<44>-Footnote-12756534
Node: 构建<31>2756577
Ref: whatsnew/changelog id3412756662
Ref: 10ff2756662
Ref: 构建<31>-Footnote-12756953
Ref: 构建<31>-Footnote-22756996
Node: Python 3 6 3 rc12757039
Ref: whatsnew/changelog python-3-6-3-release-candidate-12757166
Ref: 11002757166
Node: 安全<26>2757477
Ref: whatsnew/changelog id3422757568
Ref: 11012757568
Ref: 安全<26>-Footnote-12757868
Ref: 安全<26>-Footnote-22757911
Node: 核心与内置<43>2757954
Ref: whatsnew/changelog id3432758061
Ref: 11022758061
Ref: 核心与内置<43>-Footnote-12761599
Ref: 核心与内置<43>-Footnote-22761642
Ref: 核心与内置<43>-Footnote-32761685
Ref: 核心与内置<43>-Footnote-42761728
Ref: 核心与内置<43>-Footnote-52761771
Ref: 核心与内置<43>-Footnote-62761814
Ref: 核心与内置<43>-Footnote-72761857
Ref: 核心与内置<43>-Footnote-82761900
Ref: 核心与内置<43>-Footnote-92761943
Ref: 核心与内置<43>-Footnote-102761986
Ref: 核心与内置<43>-Footnote-112762030
Ref: 核心与内置<43>-Footnote-122762074
Ref: 核心与内置<43>-Footnote-132762118
Ref: 核心与内置<43>-Footnote-142762162
Ref: 核心与内置<43>-Footnote-152762206
Ref: 核心与内置<43>-Footnote-162762250
Ref: 核心与内置<43>-Footnote-172762294
Ref: 核心与内置<43>-Footnote-182762338
Ref: 核心与内置<43>-Footnote-192762382
Ref: 核心与内置<43>-Footnote-202762426
Ref: 核心与内置<43>-Footnote-212762470
Ref: 核心与内置<43>-Footnote-222762514
Node: 库<45>2762558
Ref: whatsnew/changelog id3442762665
Ref: 11032762665
Ref: 库<45>-Footnote-12768654
Ref: 库<45>-Footnote-22768697
Ref: 库<45>-Footnote-32768740
Ref: 库<45>-Footnote-42768783
Ref: 库<45>-Footnote-52768826
Ref: 库<45>-Footnote-62768869
Ref: 库<45>-Footnote-72768912
Ref: 库<45>-Footnote-82768955
Ref: 库<45>-Footnote-92768998
Ref: 库<45>-Footnote-102769041
Ref: 库<45>-Footnote-112769085
Ref: 库<45>-Footnote-122769129
Ref: 库<45>-Footnote-132769173
Ref: 库<45>-Footnote-142769217
Ref: 库<45>-Footnote-152769261
Ref: 库<45>-Footnote-162769304
Ref: 库<45>-Footnote-172769348
Ref: 库<45>-Footnote-182769392
Ref: 库<45>-Footnote-192769442
Ref: 库<45>-Footnote-202769486
Ref: 库<45>-Footnote-212769530
Ref: 库<45>-Footnote-222769574
Ref: 库<45>-Footnote-232769618
Ref: 库<45>-Footnote-242769662
Ref: 库<45>-Footnote-252769706
Ref: 库<45>-Footnote-262769750
Ref: 库<45>-Footnote-272769794
Ref: 库<45>-Footnote-282769838
Ref: 库<45>-Footnote-292769882
Ref: 库<45>-Footnote-302769926
Ref: 库<45>-Footnote-312769970
Ref: 库<45>-Footnote-322770014
Ref: 库<45>-Footnote-332770058
Ref: 库<45>-Footnote-342770102
Ref: 库<45>-Footnote-352770146
Ref: 库<45>-Footnote-362770190
Ref: 库<45>-Footnote-372770234
Ref: 库<45>-Footnote-382770278
Ref: 库<45>-Footnote-392770322
Ref: 库<45>-Footnote-402770366
Ref: 库<45>-Footnote-412770410
Ref: 库<45>-Footnote-422770454
Node: 文档<39>2770498
Ref: whatsnew/changelog id3452770596
Ref: 11042770596
Ref: 文档<39>-Footnote-12771003
Ref: 文档<39>-Footnote-22771046
Ref: 文档<39>-Footnote-32771089
Node: 测试<33>2771132
Ref: whatsnew/changelog id3462771233
Ref: 11052771233
Ref: 测试<33>-Footnote-12771938
Ref: 测试<33>-Footnote-22771981
Ref: 测试<33>-Footnote-32772024
Ref: 测试<33>-Footnote-42772067
Node: 构建<32>2772110
Ref: whatsnew/changelog id3472772212
Ref: 11062772212
Ref: 构建<32>-Footnote-12772387
Node: Windows<34>2772430
Ref: whatsnew/changelog id3482772530
Ref: 11072772530
Ref: Windows<34>-Footnote-12773038
Ref: Windows<34>-Footnote-22773081
Ref: Windows<34>-Footnote-32773124
Ref: Windows<34>-Footnote-42773167
Node: IDLE<39>2773210
Ref: whatsnew/changelog id3492773317
Ref: 11082773317
Ref: IDLE<39>-Footnote-12782166
Ref: IDLE<39>-Footnote-22782209
Ref: IDLE<39>-Footnote-32782252
Ref: IDLE<39>-Footnote-42782295
Ref: IDLE<39>-Footnote-52782338
Ref: IDLE<39>-Footnote-62782381
Ref: IDLE<39>-Footnote-72782424
Ref: IDLE<39>-Footnote-82782467
Ref: IDLE<39>-Footnote-92782510
Ref: IDLE<39>-Footnote-102782553
Ref: IDLE<39>-Footnote-112782597
Ref: IDLE<39>-Footnote-122782641
Ref: IDLE<39>-Footnote-132782685
Ref: IDLE<39>-Footnote-142782729
Ref: IDLE<39>-Footnote-152782773
Ref: IDLE<39>-Footnote-162782817
Ref: IDLE<39>-Footnote-172782861
Ref: IDLE<39>-Footnote-182782905
Ref: IDLE<39>-Footnote-192782949
Ref: IDLE<39>-Footnote-202782993
Ref: IDLE<39>-Footnote-212783037
Ref: IDLE<39>-Footnote-222783081
Ref: IDLE<39>-Footnote-232783125
Ref: IDLE<39>-Footnote-242783169
Ref: IDLE<39>-Footnote-252783213
Ref: IDLE<39>-Footnote-262783257
Ref: IDLE<39>-Footnote-272783301
Ref: IDLE<39>-Footnote-282783345
Ref: IDLE<39>-Footnote-292783389
Ref: IDLE<39>-Footnote-302783433
Ref: IDLE<39>-Footnote-312783477
Ref: IDLE<39>-Footnote-322783521
Ref: IDLE<39>-Footnote-332783565
Ref: IDLE<39>-Footnote-342783609
Ref: IDLE<39>-Footnote-352783652
Ref: IDLE<39>-Footnote-362783696
Ref: IDLE<39>-Footnote-372783740
Ref: IDLE<39>-Footnote-382783784
Ref: IDLE<39>-Footnote-392783828
Ref: IDLE<39>-Footnote-402783872
Ref: IDLE<39>-Footnote-412783916
Ref: IDLE<39>-Footnote-422783960
Ref: IDLE<39>-Footnote-432784004
Node: 工具/示例<22>2784047
Ref: whatsnew/changelog id3502784134
Ref: 11092784134
Ref: 工具/示例<22>-Footnote-12784692
Ref: 工具/示例<22>-Footnote-22784735
Node: Python 3 6 2 正式版2784784
Ref: whatsnew/changelog python-3-6-2-final2784905
Ref: 110a2784905
Node: Python 3 6 2 rc22785016
Ref: whatsnew/changelog python-3-6-2-release-candidate-22785137
Ref: 110b2785137
Node: 安全<27>2785248
Ref: whatsnew/changelog id3512785311
Ref: 110c2785311
Ref: 安全<27>-Footnote-12786412
Ref: 安全<27>-Footnote-22786455
Ref: 安全<27>-Footnote-32786498
Node: Python 3 6 2 rc12786541
Ref: whatsnew/changelog python-3-6-2-release-candidate-12786662
Ref: 110d2786662
Node: 核心与内置<44>2787009
Ref: whatsnew/changelog id3522787097
Ref: 110e2787097
Ref: 核心与内置<44>-Footnote-12789081
Ref: 核心与内置<44>-Footnote-22789124
Ref: 核心与内置<44>-Footnote-32789167
Ref: 核心与内置<44>-Footnote-42789210
Ref: 核心与内置<44>-Footnote-52789253
Ref: 核心与内置<44>-Footnote-62789296
Ref: 核心与内置<44>-Footnote-72789339
Ref: 核心与内置<44>-Footnote-82789382
Ref: 核心与内置<44>-Footnote-92789425
Ref: 核心与内置<44>-Footnote-102789468
Ref: 核心与内置<44>-Footnote-112789512
Ref: 核心与内置<44>-Footnote-122789556
Ref: 核心与内置<44>-Footnote-132789600
Ref: 核心与内置<44>-Footnote-142789644
Ref: 核心与内置<44>-Footnote-152789688
Node: 库<46>2789732
Ref: whatsnew/changelog id3532789839
Ref: 110f2789839
Ref: 库<46>-Footnote-12790964
Ref: 库<46>-Footnote-22791007
Ref: 库<46>-Footnote-32791050
Ref: 库<46>-Footnote-42791093
Ref: 库<46>-Footnote-52791136
Ref: 库<46>-Footnote-62791179
Ref: 库<46>-Footnote-72791222
Ref: 库<46>-Footnote-82791265
Node: 安全<28>2791308
Ref: whatsnew/changelog id3542791403
Ref: 11102791403
Ref: 安全<28>-Footnote-12791664
Node: 库<47>2791707
Ref: whatsnew/changelog id3552791803
Ref: 11112791803
Ref: 库<47>-Footnote-12799143
Ref: 库<47>-Footnote-22799186
Ref: 库<47>-Footnote-32799229
Ref: 库<47>-Footnote-42799272
Ref: 库<47>-Footnote-52799315
Ref: 库<47>-Footnote-62799358
Ref: 库<47>-Footnote-72799401
Ref: 库<47>-Footnote-82799444
Ref: 库<47>-Footnote-92799487
Ref: 库<47>-Footnote-102799530
Ref: 库<47>-Footnote-112799574
Ref: 库<47>-Footnote-122799618
Ref: 库<47>-Footnote-132799662
Ref: 库<47>-Footnote-142799706
Ref: 库<47>-Footnote-152799750
Ref: 库<47>-Footnote-162799794
Ref: 库<47>-Footnote-172799838
Ref: 库<47>-Footnote-182799882
Ref: 库<47>-Footnote-192799926
Ref: 库<47>-Footnote-202799970
Ref: 库<47>-Footnote-212800014
Ref: 库<47>-Footnote-222800058
Ref: 库<47>-Footnote-232800102
Ref: 库<47>-Footnote-242800146
Ref: 库<47>-Footnote-252800190
Ref: 库<47>-Footnote-262800234
Ref: 库<47>-Footnote-272800278
Ref: 库<47>-Footnote-282800322
Ref: 库<47>-Footnote-292800366
Ref: 库<47>-Footnote-302800410
Ref: 库<47>-Footnote-312800454
Ref: 库<47>-Footnote-322800498
Ref: 库<47>-Footnote-332800542
Ref: 库<47>-Footnote-342800586
Ref: 库<47>-Footnote-352800630
Ref: 库<47>-Footnote-362800674
Ref: 库<47>-Footnote-372800718
Ref: 库<47>-Footnote-382800762
Ref: 库<47>-Footnote-392800806
Ref: 库<47>-Footnote-402800850
Ref: 库<47>-Footnote-412800894
Ref: 库<47>-Footnote-422800938
Ref: 库<47>-Footnote-432800982
Ref: 库<47>-Footnote-442801026
Ref: 库<47>-Footnote-452801070
Ref: 库<47>-Footnote-462801114
Ref: 库<47>-Footnote-472801158
Ref: 库<47>-Footnote-482801201
Ref: 库<47>-Footnote-492801245
Ref: 库<47>-Footnote-502801289
Ref: 库<47>-Footnote-512801333
Ref: 库<47>-Footnote-522801377
Node: IDLE<40>2801421
Ref: whatsnew/changelog id3562801516
Ref: 11122801516
Ref: IDLE<40>-Footnote-12802521
Ref: IDLE<40>-Footnote-22802564
Ref: IDLE<40>-Footnote-32802607
Ref: IDLE<40>-Footnote-42802650
Ref: IDLE<40>-Footnote-52802693
Ref: IDLE<40>-Footnote-62802736
Node: C API<26>2802779
Ref: whatsnew/changelog id3572802877
Ref: 11132802877
Ref: C API<26>-Footnote-12803065
Node: 构建<33>2803108
Ref: whatsnew/changelog id3582803208
Ref: 11142803208
Ref: 构建<33>-Footnote-12804017
Ref: 构建<33>-Footnote-22804060
Ref: 构建<33>-Footnote-32804103
Ref: 构建<33>-Footnote-42804146
Ref: 构建<33>-Footnote-52804189
Node: 文档<40>2804232
Ref: whatsnew/changelog id3592804340
Ref: 11152804340
Ref: 文档<40>-Footnote-12805053
Ref: 文档<40>-Footnote-22805096
Ref: 文档<40>-Footnote-32805139
Node: 工具/示例<23>2805182
Ref: whatsnew/changelog id3602805290
Ref: 11162805290
Ref: 工具/示例<23>-Footnote-12805480
Node: 测试<34>2805523
Ref: whatsnew/changelog id3612805632
Ref: 11172805632
Ref: 测试<34>-Footnote-12806291
Ref: 测试<34>-Footnote-22806334
Node: Windows<35>2806377
Ref: whatsnew/changelog id3622806460
Ref: 11182806460
Ref: Windows<35>-Footnote-12806904
Ref: Windows<35>-Footnote-22806947
Node: Python 3 6 1 正式版2806990
Ref: whatsnew/changelog python-3-6-1-final2807111
Ref: 11192807111
Node: 核心与内置<45>2807271
Ref: whatsnew/changelog id3632807368
Ref: 111a2807368
Ref: 核心与内置<45>-Footnote-12807978
Ref: 核心与内置<45>-Footnote-22808021
Node: 构建<34>2808064
Ref: whatsnew/changelog id3642808161
Ref: 111b2808161
Ref: 构建<34>-Footnote-12808343
Node: Python 3 6 1 rc12808386
Ref: whatsnew/changelog python-3-6-1-release-candidate-12808513
Ref: 111c2808513
Node: 核心与内置<46>2808786
Ref: whatsnew/changelog id3652808874
Ref: 111d2808874
Ref: 核心与内置<46>-Footnote-12811697
Ref: 核心与内置<46>-Footnote-22811740
Ref: 核心与内置<46>-Footnote-32811783
Ref: 核心与内置<46>-Footnote-42811826
Ref: 核心与内置<46>-Footnote-52811869
Ref: 核心与内置<46>-Footnote-62811912
Ref: 核心与内置<46>-Footnote-72811955
Ref: 核心与内置<46>-Footnote-82811998
Ref: 核心与内置<46>-Footnote-92812041
Ref: 核心与内置<46>-Footnote-102812084
Ref: 核心与内置<46>-Footnote-112812128
Ref: 核心与内置<46>-Footnote-122812172
Ref: 核心与内置<46>-Footnote-132812216
Ref: 核心与内置<46>-Footnote-142812260
Ref: 核心与内置<46>-Footnote-152812304
Ref: 核心与内置<46>-Footnote-162812348
Ref: 核心与内置<46>-Footnote-172812392
Ref: 核心与内置<46>-Footnote-182812436
Ref: 核心与内置<46>-Footnote-192812480
Ref: 核心与内置<46>-Footnote-202812524
Ref: 核心与内置<46>-Footnote-212812568
Ref: 核心与内置<46>-Footnote-222812612
Node: 库<48>2812656
Ref: whatsnew/changelog id3662812761
Ref: 111e2812761
Ref: 库<48>-Footnote-12818391
Ref: 库<48>-Footnote-22818434
Ref: 库<48>-Footnote-32818477
Ref: 库<48>-Footnote-42818520
Ref: 库<48>-Footnote-52818563
Ref: 库<48>-Footnote-62818606
Ref: 库<48>-Footnote-72818649
Ref: 库<48>-Footnote-82818692
Ref: 库<48>-Footnote-92818735
Ref: 库<48>-Footnote-102818778
Ref: 库<48>-Footnote-112818822
Ref: 库<48>-Footnote-122818866
Ref: 库<48>-Footnote-132818910
Ref: 库<48>-Footnote-142818954
Ref: 库<48>-Footnote-152818998
Ref: 库<48>-Footnote-162819042
Ref: 库<48>-Footnote-172819086
Ref: 库<48>-Footnote-182819130
Ref: 库<48>-Footnote-192819174
Ref: 库<48>-Footnote-202819218
Ref: 库<48>-Footnote-212819262
Ref: 库<48>-Footnote-222819306
Ref: 库<48>-Footnote-232819350
Ref: 库<48>-Footnote-242819394
Ref: 库<48>-Footnote-252819438
Ref: 库<48>-Footnote-262819482
Ref: 库<48>-Footnote-272819526
Ref: 库<48>-Footnote-282819576
Ref: 库<48>-Footnote-292819620
Ref: 库<48>-Footnote-302819664
Ref: 库<48>-Footnote-312819708
Ref: 库<48>-Footnote-322819752
Ref: 库<48>-Footnote-332819796
Ref: 库<48>-Footnote-342819840
Ref: 库<48>-Footnote-352819884
Ref: 库<48>-Footnote-362819927
Ref: 库<48>-Footnote-372819971
Ref: 库<48>-Footnote-382820015
Ref: 库<48>-Footnote-392820059
Ref: 库<48>-Footnote-402820103
Ref: 库<48>-Footnote-412820147
Ref: 库<48>-Footnote-422820191
Ref: 库<48>-Footnote-432820235
Ref: 库<48>-Footnote-442820279
Node: IDLE<41>2820323
Ref: whatsnew/changelog id3672820420
Ref: 111f2820420
Ref: IDLE<41>-Footnote-12820709
Ref: IDLE<41>-Footnote-22820752
Node: Windows<36>2820795
Ref: whatsnew/changelog id3682820894
Ref: 11202820894
Ref: Windows<36>-Footnote-12821541
Ref: Windows<36>-Footnote-22821584
Ref: Windows<36>-Footnote-32821627
Ref: Windows<36>-Footnote-42821670
Ref: Windows<36>-Footnote-52821713
Ref: Windows<36>-Footnote-62821762
Ref: Windows<36>-Footnote-72821805
Ref: Windows<36>-Footnote-82821848
Node: C API<27>2821891
Ref: whatsnew/changelog id3692821992
Ref: 11212821992
Ref: C API<27>-Footnote-12822818
Ref: C API<27>-Footnote-22822861
Ref: C API<27>-Footnote-32822904
Node: 文档<41>2822947
Ref: whatsnew/changelog id3702823047
Ref: 11222823047
Ref: 文档<41>-Footnote-12823568
Ref: 文档<41>-Footnote-22823611
Ref: 文档<41>-Footnote-32823654
Ref: 文档<41>-Footnote-42823697
Node: 测试<35>2823740
Ref: whatsnew/changelog id3712823841
Ref: 11232823841
Ref: 测试<35>-Footnote-12824826
Ref: 测试<35>-Footnote-22824869
Ref: 测试<35>-Footnote-32824912
Ref: 测试<35>-Footnote-42824955
Ref: 测试<35>-Footnote-52824998
Node: 构建<35>2825041
Ref: whatsnew/changelog id3722825123
Ref: 11242825123
Ref: 构建<35>-Footnote-12826381
Ref: 构建<35>-Footnote-22826424
Ref: 构建<35>-Footnote-32826467
Ref: 构建<35>-Footnote-42826510
Ref: 构建<35>-Footnote-52826553
Ref: 构建<35>-Footnote-62826596
Ref: 构建<35>-Footnote-72826639
Ref: 构建<35>-Footnote-82826682
Ref: 构建<35>-Footnote-92826725
Ref: 构建<35>-Footnote-102826768
Node: Python 3 6 0 正式版2826812
Ref: whatsnew/changelog python-3-6-0-final2826933
Ref: 11252826933
Node: Python 3 6 0 rc22827044
Ref: whatsnew/changelog python-3-6-0-release-candidate-22827165
Ref: 11262827165
Node: 核心与内置<47>2827376
Ref: whatsnew/changelog id3732827474
Ref: 11272827474
Ref: 核心与内置<47>-Footnote-12827850
Ref: 核心与内置<47>-Footnote-22827893
Node: 工具/示例<24>2827936
Ref: whatsnew/changelog id3742828054
Ref: 11282828054
Ref: 工具/示例<24>-Footnote-12828188
Node: Windows<37>2828231
Ref: whatsnew/changelog id3752828340
Ref: 11292828340
Ref: Windows<37>-Footnote-12828466
Node: 构建<36>2828509
Ref: whatsnew/changelog id3762828592
Ref: 112a2828592
Ref: 构建<36>-Footnote-12828747
Node: Python 3 6 0 rc12828790
Ref: whatsnew/changelog python-3-6-0-release-candidate-12828908
Ref: 112b2828908
Node: 核心与内置<48>2829131
Ref: whatsnew/changelog id3772829219
Ref: 112c2829219
Ref: 核心与内置<48>-Footnote-12830019
Ref: 核心与内置<48>-Footnote-22830062
Ref: 核心与内置<48>-Footnote-32830105
Ref: 核心与内置<48>-Footnote-42830148
Node: 库<49>2830191
Ref: whatsnew/changelog id3782830297
Ref: 112d2830297
Ref: 库<49>-Footnote-12831327
Ref: 库<49>-Footnote-22831370
Ref: 库<49>-Footnote-32831413
Ref: 库<49>-Footnote-42831456
Ref: 库<49>-Footnote-52831499
Ref: 库<49>-Footnote-62831542
Node: C API<28>2831585
Ref: whatsnew/changelog id3792831682
Ref: 112e2831682
Ref: C API<28>-Footnote-12831840
Node: 文档<42>2831883
Ref: whatsnew/changelog id3802831990
Ref: 112f2831990
Ref: 文档<42>-Footnote-12832314
Ref: 文档<42>-Footnote-22832357
Node: 工具/示例<25>2832406
Ref: whatsnew/changelog id3812832495
Ref: 11302832495
Ref: 工具/示例<25>-Footnote-12832661
Node: Python 3 6 0 beta 42832704
Ref: whatsnew/changelog python-3-6-0-beta-42832825
Ref: 11312832825
Node: 核心与内置<49>2833042
Ref: whatsnew/changelog id3822833133
Ref: 11322833133
Ref: 核心与内置<49>-Footnote-12834676
Ref: 核心与内置<49>-Footnote-22834719
Ref: 核心与内置<49>-Footnote-32834762
Ref: 核心与内置<49>-Footnote-42834805
Ref: 核心与内置<49>-Footnote-52834848
Ref: 核心与内置<49>-Footnote-62834891
Ref: 核心与内置<49>-Footnote-72834934
Ref: 核心与内置<49>-Footnote-82834977
Ref: 核心与内置<49>-Footnote-92835020
Ref: 核心与内置<49>-Footnote-102835063
Ref: 核心与内置<49>-Footnote-112835107
Node: 库<50>2835151
Ref: whatsnew/changelog id3832835261
Ref: 11332835261
Ref: 库<50>-Footnote-12837254
Ref: 库<50>-Footnote-22837297
Ref: 库<50>-Footnote-32837340
Ref: 库<50>-Footnote-42837383
Ref: 库<50>-Footnote-52837426
Ref: 库<50>-Footnote-62837469
Ref: 库<50>-Footnote-72837512
Ref: 库<50>-Footnote-82837555
Ref: 库<50>-Footnote-92837598
Ref: 库<50>-Footnote-102837641
Ref: 库<50>-Footnote-112837685
Ref: 库<50>-Footnote-122837729
Ref: 库<50>-Footnote-132837773
Ref: 库<50>-Footnote-142837817
Ref: 库<50>-Footnote-152837861
Ref: 库<50>-Footnote-162837905
Ref: 库<50>-Footnote-172837949
Ref: 库<50>-Footnote-182837993
Node: 文档<43>2838037
Ref: whatsnew/changelog id3842838138
Ref: 11342838138
Ref: 文档<43>-Footnote-12838273
Node: 测试<36>2838316
Ref: whatsnew/changelog id3852838420
Ref: 11352838420
Ref: 测试<36>-Footnote-12838682
Ref: 测试<36>-Footnote-22838725
Node: 构建<37>2838768
Ref: whatsnew/changelog id3862838853
Ref: 11362838853
Ref: 构建<37>-Footnote-12839216
Ref: 构建<37>-Footnote-22839259
Ref: 构建<37>-Footnote-32839302
Node: Python 3 6 0 beta 32839345
Ref: whatsnew/changelog python-3-6-0-beta-32839469
Ref: 11372839469
Node: 核心与内置<50>2839688
Ref: whatsnew/changelog id3872839779
Ref: 11382839779
Ref: 核心与内置<50>-Footnote-12840673
Ref: 核心与内置<50>-Footnote-22840716
Ref: 核心与内置<50>-Footnote-32840759
Ref: 核心与内置<50>-Footnote-42840802
Ref: 核心与内置<50>-Footnote-52840845
Ref: 核心与内置<50>-Footnote-62840888
Ref: 核心与内置<50>-Footnote-72840931
Node: 库<51>2840974
Ref: whatsnew/changelog id3882841085
Ref: 11392841085
Ref: 库<51>-Footnote-12844108
Ref: 库<51>-Footnote-22844151
Ref: 库<51>-Footnote-32844194
Ref: 库<51>-Footnote-42844237
Ref: 库<51>-Footnote-52844280
Ref: 库<51>-Footnote-62844323
Ref: 库<51>-Footnote-72844366
Ref: 库<51>-Footnote-82844409
Ref: 库<51>-Footnote-92844452
Ref: 库<51>-Footnote-102844495
Ref: 库<51>-Footnote-112844539
Ref: 库<51>-Footnote-122844583
Ref: 库<51>-Footnote-132844627
Ref: 库<51>-Footnote-142844671
Ref: 库<51>-Footnote-152844715
Ref: 库<51>-Footnote-162844759
Ref: 库<51>-Footnote-172844803
Ref: 库<51>-Footnote-182844847
Ref: 库<51>-Footnote-192844891
Ref: 库<51>-Footnote-202844935
Ref: 库<51>-Footnote-212844979
Ref: 库<51>-Footnote-222845023
Ref: 库<51>-Footnote-232845067
Ref: 库<51>-Footnote-242845111
Node: Windows<38>2845155
Ref: whatsnew/changelog id3892845257
Ref: 113a2845257
Ref: Windows<38>-Footnote-12845401
Node: 构建<38>2845444
Ref: whatsnew/changelog id3902845549
Ref: 113b2845549
Ref: 构建<38>-Footnote-12845859
Ref: 构建<38>-Footnote-22845902
Ref: 构建<38>-Footnote-32845945
Node: 测试<37>2845988
Ref: whatsnew/changelog id3912846073
Ref: 113c2846073
Ref: 测试<37>-Footnote-12846332
Ref: 测试<37>-Footnote-22846375
Node: Python 3 6 0 beta 22846418
Ref: whatsnew/changelog python-3-6-0-beta-22846542
Ref: 113d2846542
Node: 核心与内置<51>2846781
Ref: whatsnew/changelog id3922846872
Ref: 113e2846872
Ref: 核心与内置<51>-Footnote-12849603
Ref: 核心与内置<51>-Footnote-22849646
Ref: 核心与内置<51>-Footnote-32849689
Ref: 核心与内置<51>-Footnote-42849732
Ref: 核心与内置<51>-Footnote-52849775
Ref: 核心与内置<51>-Footnote-62849818
Ref: 核心与内置<51>-Footnote-72849861
Ref: 核心与内置<51>-Footnote-82849904
Ref: 核心与内置<51>-Footnote-92849947
Ref: 核心与内置<51>-Footnote-102849990
Ref: 核心与内置<51>-Footnote-112850034
Ref: 核心与内置<51>-Footnote-122850078
Ref: 核心与内置<51>-Footnote-132850122
Ref: 核心与内置<51>-Footnote-142850166
Ref: 核心与内置<51>-Footnote-152850210
Ref: 核心与内置<51>-Footnote-162850254
Ref: 核心与内置<51>-Footnote-172850298
Ref: 核心与内置<51>-Footnote-182850342
Ref: 核心与内置<51>-Footnote-192850386
Ref: 核心与内置<51>-Footnote-202850430
Ref: 核心与内置<51>-Footnote-212850474
Ref: 核心与内置<51>-Footnote-222850518
Ref: 核心与内置<51>-Footnote-232850562
Node: 库<52>2850606
Ref: whatsnew/changelog id3932850717
Ref: 113f2850717
Ref: 库<52>-Footnote-12856494
Ref: 库<52>-Footnote-22856537
Ref: 库<52>-Footnote-32856580
Ref: 库<52>-Footnote-42856623
Ref: 库<52>-Footnote-52856666
Ref: 库<52>-Footnote-62856709
Ref: 库<52>-Footnote-72856752
Ref: 库<52>-Footnote-82856795
Ref: 库<52>-Footnote-92856838
Ref: 库<52>-Footnote-102856881
Ref: 库<52>-Footnote-112856925
Ref: 库<52>-Footnote-122856969
Ref: 库<52>-Footnote-132857013
Ref: 库<52>-Footnote-142857057
Ref: 库<52>-Footnote-152857101
Ref: 库<52>-Footnote-162857145
Ref: 库<52>-Footnote-172857189
Ref: 库<52>-Footnote-182857233
Ref: 库<52>-Footnote-192857277
Ref: 库<52>-Footnote-202857321
Ref: 库<52>-Footnote-212857365
Ref: 库<52>-Footnote-222857409
Ref: 库<52>-Footnote-232857453
Ref: 库<52>-Footnote-242857497
Ref: 库<52>-Footnote-252857541
Ref: 库<52>-Footnote-262857585
Ref: 库<52>-Footnote-272857629
Ref: 库<52>-Footnote-282857673
Ref: 库<52>-Footnote-292857717
Ref: 库<52>-Footnote-302857761
Ref: 库<52>-Footnote-312857805
Ref: 库<52>-Footnote-322857849
Ref: 库<52>-Footnote-332857893
Ref: 库<52>-Footnote-342857937
Ref: 库<52>-Footnote-352857981
Ref: 库<52>-Footnote-362858025
Ref: 库<52>-Footnote-372858069
Ref: 库<52>-Footnote-382858113
Ref: 库<52>-Footnote-392858157
Ref: 库<52>-Footnote-402858201
Ref: 库<52>-Footnote-412858245
Ref: 库<52>-Footnote-422858289
Ref: 库<52>-Footnote-432858333
Ref: 库<52>-Footnote-442858377
Ref: 库<52>-Footnote-452858421
Ref: 库<52>-Footnote-462858465
Ref: 库<52>-Footnote-472858509
Ref: 库<52>-Footnote-482858553
Node: Windows<39>2858597
Ref: whatsnew/changelog id3942858698
Ref: 11402858698
Ref: Windows<39>-Footnote-12859509
Ref: Windows<39>-Footnote-22859552
Ref: Windows<39>-Footnote-32859595
Ref: Windows<39>-Footnote-42859638
Ref: Windows<39>-Footnote-52859681
Ref: Windows<39>-Footnote-62859724
Ref: Windows<39>-Footnote-72859767
Ref: Windows<39>-Footnote-82859810
Ref: Windows<39>-Footnote-92859853
Ref: Windows<39>-Footnote-102859896
Node: C API<29>2859940
Ref: whatsnew/changelog id3952860044
Ref: 11412860044
Ref: C API<29>-Footnote-12860298
Node: 构建<39>2860341
Ref: whatsnew/changelog id3962860444
Ref: 11422860444
Ref: 构建<39>-Footnote-12860870
Ref: 构建<39>-Footnote-22860913
Ref: 构建<39>-Footnote-32860956
Node: 测试<38>2860999
Ref: whatsnew/changelog id3972861084
Ref: 11432861084
Ref: 测试<38>-Footnote-12861221
Node: Python 3 6 0 beta 12861264
Ref: whatsnew/changelog python-3-6-0-beta-12861389
Ref: 11442861389
Node: 核心与内置<52>2861684
Ref: whatsnew/changelog id3982861775
Ref: 11452861775
Ref: 核心与内置<52>-Footnote-12867955
Ref: 核心与内置<52>-Footnote-22867998
Ref: 核心与内置<52>-Footnote-32868041
Ref: 核心与内置<52>-Footnote-42868084
Ref: 核心与内置<52>-Footnote-52868133
Ref: 核心与内置<52>-Footnote-62868176
Ref: 核心与内置<52>-Footnote-72868219
Ref: 核心与内置<52>-Footnote-82868262
Ref: 核心与内置<52>-Footnote-92868305
Ref: 核心与内置<52>-Footnote-102868348
Ref: 核心与内置<52>-Footnote-112868392
Ref: 核心与内置<52>-Footnote-122868436
Ref: 核心与内置<52>-Footnote-132868480
Ref: 核心与内置<52>-Footnote-142868530
Ref: 核心与内置<52>-Footnote-152868574
Ref: 核心与内置<52>-Footnote-162868618
Ref: 核心与内置<52>-Footnote-172868668
Ref: 核心与内置<52>-Footnote-182868712
Ref: 核心与内置<52>-Footnote-192868762
Ref: 核心与内置<52>-Footnote-202868806
Ref: 核心与内置<52>-Footnote-212868850
Ref: 核心与内置<52>-Footnote-222868894
Ref: 核心与内置<52>-Footnote-232868938
Ref: 核心与内置<52>-Footnote-242868982
Ref: 核心与内置<52>-Footnote-252869026
Ref: 核心与内置<52>-Footnote-262869070
Ref: 核心与内置<52>-Footnote-272869114
Ref: 核心与内置<52>-Footnote-282869164
Ref: 核心与内置<52>-Footnote-292869208
Ref: 核心与内置<52>-Footnote-302869252
Ref: 核心与内置<52>-Footnote-312869296
Ref: 核心与内置<52>-Footnote-322869340
Ref: 核心与内置<52>-Footnote-332869384
Ref: 核心与内置<52>-Footnote-342869428
Ref: 核心与内置<52>-Footnote-352869472
Ref: 核心与内置<52>-Footnote-362869516
Ref: 核心与内置<52>-Footnote-372869560
Ref: 核心与内置<52>-Footnote-382869604
Ref: 核心与内置<52>-Footnote-392869648
Ref: 核心与内置<52>-Footnote-402869692
Ref: 核心与内置<52>-Footnote-412869736
Ref: 核心与内置<52>-Footnote-422869780
Ref: 核心与内置<52>-Footnote-432869824
Ref: 核心与内置<52>-Footnote-442869868
Ref: 核心与内置<52>-Footnote-452869912
Ref: 核心与内置<52>-Footnote-462869956
Ref: 核心与内置<52>-Footnote-472870006
Node: 库<53>2870050
Ref: whatsnew/changelog id3992870158
Ref: 11462870158
Ref: 库<53>-Footnote-12881128
Ref: 库<53>-Footnote-22881171
Ref: 库<53>-Footnote-32881214
Ref: 库<53>-Footnote-42881257
Ref: 库<53>-Footnote-52881300
Ref: 库<53>-Footnote-62881343
Ref: 库<53>-Footnote-72881386
Ref: 库<53>-Footnote-82881429
Ref: 库<53>-Footnote-92881472
Ref: 库<53>-Footnote-102881515
Ref: 库<53>-Footnote-112881559
Ref: 库<53>-Footnote-122881603
Ref: 库<53>-Footnote-132881647
Ref: 库<53>-Footnote-142881691
Ref: 库<53>-Footnote-152881735
Ref: 库<53>-Footnote-162881779
Ref: 库<53>-Footnote-172881823
Ref: 库<53>-Footnote-182881869
Ref: 库<53>-Footnote-192881913
Ref: 库<53>-Footnote-202881957
Ref: 库<53>-Footnote-212882001
Ref: 库<53>-Footnote-222882045
Ref: 库<53>-Footnote-232882089
Ref: 库<53>-Footnote-242882133
Ref: 库<53>-Footnote-252882177
Ref: 库<53>-Footnote-262882222
Ref: 库<53>-Footnote-272882266
Ref: 库<53>-Footnote-282882310
Ref: 库<53>-Footnote-292882354
Ref: 库<53>-Footnote-302882398
Ref: 库<53>-Footnote-312882442
Ref: 库<53>-Footnote-322882486
Ref: 库<53>-Footnote-332882530
Ref: 库<53>-Footnote-342882574
Ref: 库<53>-Footnote-352882618
Ref: 库<53>-Footnote-362882662
Ref: 库<53>-Footnote-372882706
Ref: 库<53>-Footnote-382882750
Ref: 库<53>-Footnote-392882794
Ref: 库<53>-Footnote-402882838
Ref: 库<53>-Footnote-412882882
Ref: 库<53>-Footnote-422882926
Ref: 库<53>-Footnote-432882976
Ref: 库<53>-Footnote-442883020
Ref: 库<53>-Footnote-452883070
Ref: 库<53>-Footnote-462883114
Ref: 库<53>-Footnote-472883158
Ref: 库<53>-Footnote-482883202
Ref: 库<53>-Footnote-492883246
Ref: 库<53>-Footnote-502883290
Ref: 库<53>-Footnote-512883334
Ref: 库<53>-Footnote-522883378
Ref: 库<53>-Footnote-532883422
Ref: 库<53>-Footnote-542883466
Ref: 库<53>-Footnote-552883510
Ref: 库<53>-Footnote-562883554
Ref: 库<53>-Footnote-572883598
Ref: 库<53>-Footnote-582883642
Ref: 库<53>-Footnote-592883686
Ref: 库<53>-Footnote-602883730
Ref: 库<53>-Footnote-612883774
Ref: 库<53>-Footnote-622883818
Ref: 库<53>-Footnote-632883862
Ref: 库<53>-Footnote-642883906
Ref: 库<53>-Footnote-652883950
Ref: 库<53>-Footnote-662883994
Ref: 库<53>-Footnote-672884038
Ref: 库<53>-Footnote-682884082
Ref: 库<53>-Footnote-692884126
Ref: 库<53>-Footnote-702884170
Ref: 库<53>-Footnote-712884214
Ref: 库<53>-Footnote-722884258
Ref: 库<53>-Footnote-732884302
Ref: 库<53>-Footnote-742884346
Ref: 库<53>-Footnote-752884390
Ref: 库<53>-Footnote-762884433
Ref: 库<53>-Footnote-772884476
Ref: 库<53>-Footnote-782884520
Ref: 库<53>-Footnote-792884564
Ref: 库<53>-Footnote-802884607
Ref: 库<53>-Footnote-812884651
Node: IDLE<42>2884695
Ref: whatsnew/changelog id4002884793
Ref: 11472884793
Ref: IDLE<42>-Footnote-12885566
Ref: IDLE<42>-Footnote-22885609
Ref: IDLE<42>-Footnote-32885652
Ref: IDLE<42>-Footnote-42885695
Ref: IDLE<42>-Footnote-52885738
Ref: IDLE<42>-Footnote-62885781
Node: C API<30>2885824
Ref: whatsnew/changelog id4012885925
Ref: 11482885925
Ref: C API<30>-Footnote-12886197
Ref: C API<30>-Footnote-22886240
Node: 测试<39>2886283
Ref: whatsnew/changelog id4022886386
Ref: 11492886386
Ref: 测试<39>-Footnote-12886902
Ref: 测试<39>-Footnote-22886945
Ref: 测试<39>-Footnote-32886988
Ref: 测试<39>-Footnote-42887031
Node: 构建<40>2887074
Ref: whatsnew/changelog id4032887185
Ref: 114a2887185
Ref: 构建<40>-Footnote-12888579
Ref: 构建<40>-Footnote-22888622
Ref: 构建<40>-Footnote-32888665
Ref: 构建<40>-Footnote-42888708
Ref: 构建<40>-Footnote-52888751
Ref: 构建<40>-Footnote-62888794
Ref: 构建<40>-Footnote-72888837
Ref: 构建<40>-Footnote-82888880
Ref: 构建<40>-Footnote-92888923
Ref: 构建<40>-Footnote-102888966
Ref: 构建<40>-Footnote-112889010
Node: 工具/示例<26>2889054
Ref: whatsnew/changelog id4042889166
Ref: 114b2889166
Ref: 工具/示例<26>-Footnote-12889441
Node: Windows<40>2889484
Ref: whatsnew/changelog id4052889577
Ref: 114c2889577
Ref: Windows<40>-Footnote-12890548
Ref: Windows<40>-Footnote-22890591
Ref: Windows<40>-Footnote-32890634
Ref: Windows<40>-Footnote-42890676
Ref: Windows<40>-Footnote-52890719
Ref: Windows<40>-Footnote-62890762
Ref: Windows<40>-Footnote-72890804
Ref: Windows<40>-Footnote-82890847
Ref: Windows<40>-Footnote-92890890
Ref: Windows<40>-Footnote-102890933
Ref: Windows<40>-Footnote-112890977
Node: Python 3 6 0 alpha 42891021
Ref: whatsnew/changelog python-3-6-0-alpha-42891147
Ref: 114d2891147
Node: 核心与内置<53>2891386
Ref: whatsnew/changelog id4062891478
Ref: 114e2891478
Ref: 核心与内置<53>-Footnote-12893415
Ref: 核心与内置<53>-Footnote-22893458
Ref: 核心与内置<53>-Footnote-32893501
Ref: 核心与内置<53>-Footnote-42893544
Ref: 核心与内置<53>-Footnote-52893587
Ref: 核心与内置<53>-Footnote-62893630
Ref: 核心与内置<53>-Footnote-72893673
Ref: 核心与内置<53>-Footnote-82893716
Ref: 核心与内置<53>-Footnote-92893759
Ref: 核心与内置<53>-Footnote-102893801
Ref: 核心与内置<53>-Footnote-112893845
Ref: 核心与内置<53>-Footnote-122893889
Ref: 核心与内置<53>-Footnote-132893933
Ref: 核心与内置<53>-Footnote-142893977
Node: 库<54>2894027
Ref: whatsnew/changelog id4072894136
Ref: 114f2894136
Ref: 库<54>-Footnote-12898616
Ref: 库<54>-Footnote-22898659
Ref: 库<54>-Footnote-32898708
Ref: 库<54>-Footnote-42898751
Ref: 库<54>-Footnote-52898794
Ref: 库<54>-Footnote-62898837
Ref: 库<54>-Footnote-72898880
Ref: 库<54>-Footnote-82898923
Ref: 库<54>-Footnote-92898966
Ref: 库<54>-Footnote-102899009
Ref: 库<54>-Footnote-112899053
Ref: 库<54>-Footnote-122899103
Ref: 库<54>-Footnote-132899147
Ref: 库<54>-Footnote-142899191
Ref: 库<54>-Footnote-152899235
Ref: 库<54>-Footnote-162899279
Ref: 库<54>-Footnote-172899322
Ref: 库<54>-Footnote-182899366
Ref: 库<54>-Footnote-192899410
Ref: 库<54>-Footnote-202899454
Ref: 库<54>-Footnote-212899498
Ref: 库<54>-Footnote-222899542
Ref: 库<54>-Footnote-232899586
Ref: 库<54>-Footnote-242899630
Ref: 库<54>-Footnote-252899674
Ref: 库<54>-Footnote-262899718
Ref: 库<54>-Footnote-272899762
Ref: 库<54>-Footnote-282899806
Ref: 库<54>-Footnote-292899849
Ref: 库<54>-Footnote-302899893
Ref: 库<54>-Footnote-312899937
Ref: 库<54>-Footnote-322899981
Ref: 库<54>-Footnote-332900031
Ref: 库<54>-Footnote-342900075
Ref: 库<54>-Footnote-352900118
Ref: 库<54>-Footnote-362900162
Ref: 库<54>-Footnote-372900206
Ref: 库<54>-Footnote-382900250
Node: IDLE<43>2900294
Ref: whatsnew/changelog id4082900394
Ref: 11502900394
Ref: IDLE<43>-Footnote-12901718
Ref: IDLE<43>-Footnote-22901761
Ref: IDLE<43>-Footnote-32901804
Ref: IDLE<43>-Footnote-42901847
Ref: IDLE<43>-Footnote-52901890
Ref: IDLE<43>-Footnote-62901933
Ref: IDLE<43>-Footnote-72901976
Ref: IDLE<43>-Footnote-82902019
Node: 测试<40>2902062
Ref: whatsnew/changelog id4092902166
Ref: 11512902166
Ref: 测试<40>-Footnote-12902755
Ref: 测试<40>-Footnote-22902798
Ref: 测试<40>-Footnote-32902841
Ref: 测试<40>-Footnote-42902884
Node: Windows<41>2902927
Ref: whatsnew/changelog id4102903033
Ref: 11522903033
Ref: Windows<41>-Footnote-12903409
Ref: Windows<41>-Footnote-22903452
Ref: Windows<41>-Footnote-32903495
Ref: Windows<41>-Footnote-42903544
Ref: Windows<41>-Footnote-52903587
Node: 构建<41>2903630
Ref: whatsnew/changelog id4112903717
Ref: 11532903717
Ref: 构建<41>-Footnote-12904618
Ref: 构建<41>-Footnote-22904661
Ref: 构建<41>-Footnote-32904704
Ref: 构建<41>-Footnote-42904747
Ref: 构建<41>-Footnote-52904790
Ref: 构建<41>-Footnote-62904833
Node: Python 3 6 0 alpha 32904876
Ref: whatsnew/changelog python-3-6-0-alpha-32905003
Ref: 11542905003
Node: 核心与内置<54>2905372
Ref: whatsnew/changelog id4122905464
Ref: 11552905464
Ref: 核心与内置<54>-Footnote-12906202
Ref: 核心与内置<54>-Footnote-22906245
Ref: 核心与内置<54>-Footnote-32906288
Ref: 核心与内置<54>-Footnote-42906331
Node: 库<55>2906374
Ref: whatsnew/changelog id4132906485
Ref: 11562906485
Ref: 库<55>-Footnote-12909986
Ref: 库<55>-Footnote-22910029
Ref: 库<55>-Footnote-32910072
Ref: 库<55>-Footnote-42910115
Ref: 库<55>-Footnote-52910158
Ref: 库<55>-Footnote-62910201
Ref: 库<55>-Footnote-72910244
Ref: 库<55>-Footnote-82910287
Ref: 库<55>-Footnote-92910330
Ref: 库<55>-Footnote-102910373
Ref: 库<55>-Footnote-112910417
Ref: 库<55>-Footnote-122910461
Ref: 库<55>-Footnote-132910505
Ref: 库<55>-Footnote-142910549
Ref: 库<55>-Footnote-152910593
Ref: 库<55>-Footnote-162910637
Ref: 库<55>-Footnote-172910681
Ref: 库<55>-Footnote-182910725
Ref: 库<55>-Footnote-192910769
Ref: 库<55>-Footnote-202910813
Ref: 库<55>-Footnote-212910857
Node: 安全<29>2910907
Ref: whatsnew/changelog id4142911006
Ref: 11572911006
Ref: 安全<29>-Footnote-12911289
Node: 库<56>2911332
Ref: whatsnew/changelog id4152911434
Ref: 11582911434
Ref: 库<56>-Footnote-12911832
Ref: 库<56>-Footnote-22911875
Ref: 库<56>-Footnote-32911918
Node: 安全<30>2911960
Ref: whatsnew/changelog id4162912059
Ref: 11592912059
Ref: 安全<30>-Footnote-12912217
Node: 库<57>2912260
Ref: whatsnew/changelog id4172912360
Ref: 115a2912360
Ref: 库<57>-Footnote-12912680
Ref: 库<57>-Footnote-22912723
Node: IDLE<44>2912766
Ref: whatsnew/changelog id4182912865
Ref: 115b2912865
Ref: IDLE<44>-Footnote-12914527
Ref: IDLE<44>-Footnote-22914570
Ref: IDLE<44>-Footnote-32914613
Ref: IDLE<44>-Footnote-42914656
Ref: IDLE<44>-Footnote-52914699
Ref: IDLE<44>-Footnote-62914742
Ref: IDLE<44>-Footnote-72914785
Ref: IDLE<44>-Footnote-82914828
Ref: IDLE<44>-Footnote-92914871
Ref: IDLE<44>-Footnote-102914914
Node: C API<31>2914958
Ref: whatsnew/changelog id4192915060
Ref: 115c2915060
Ref: C API<31>-Footnote-12915300
Node: 构建<42>2915343
Ref: whatsnew/changelog id4202915454
Ref: 115d2915454
Ref: 构建<42>-Footnote-12916445
Ref: 构建<42>-Footnote-22916488
Ref: 构建<42>-Footnote-32916531
Ref: 构建<42>-Footnote-42916574
Ref: 构建<42>-Footnote-52916617
Node: 工具/示例<27>2916660
Ref: whatsnew/changelog id4212916772
Ref: 115e2916772
Ref: 工具/示例<27>-Footnote-12917058
Ref: 工具/示例<27>-Footnote-22917101
Node: 文档<44>2917144
Ref: whatsnew/changelog id4222917256
Ref: 115f2917256
Ref: 文档<44>-Footnote-12917619
Ref: 文档<44>-Footnote-22917662
Node: 测试<41>2917705
Ref: whatsnew/changelog id4232917791
Ref: 11602917791
Ref: 测试<41>-Footnote-12917961
Node: Python 3 6 0 alpha 22918004
Ref: whatsnew/changelog python-3-6-0-alpha-22918131
Ref: 11612918131
Node: 核心与内置<55>2918548
Ref: whatsnew/changelog id4242918640
Ref: 11622918640
Ref: 核心与内置<55>-Footnote-12920263
Ref: 核心与内置<55>-Footnote-22920306
Ref: 核心与内置<55>-Footnote-32920349
Ref: 核心与内置<55>-Footnote-42920392
Ref: 核心与内置<55>-Footnote-52920435
Ref: 核心与内置<55>-Footnote-62920478
Ref: 核心与内置<55>-Footnote-72920527
Ref: 核心与内置<55>-Footnote-82920570
Ref: 核心与内置<55>-Footnote-92920613
Ref: 核心与内置<55>-Footnote-102920656
Ref: 核心与内置<55>-Footnote-112920700
Ref: 核心与内置<55>-Footnote-122920744
Node: 库<58>2920788
Ref: whatsnew/changelog id4252920899
Ref: 11632920899
Ref: 库<58>-Footnote-12921532
Ref: 库<58>-Footnote-22921575
Ref: 库<58>-Footnote-32921618
Ref: 库<58>-Footnote-42921661
Node: 安全<31>2921704
Ref: whatsnew/changelog id4262921803
Ref: 11642921803
Ref: 安全<31>-Footnote-12922033
Node: 库<59>2922076
Ref: whatsnew/changelog id4272922178
Ref: 11652922178
Ref: 库<59>-Footnote-12924112
Ref: 库<59>-Footnote-22924155
Ref: 库<59>-Footnote-32924198
Ref: 库<59>-Footnote-42924241
Ref: 库<59>-Footnote-52924284
Ref: 库<59>-Footnote-62924333
Ref: 库<59>-Footnote-72924376
Ref: 库<59>-Footnote-82924419
Ref: 库<59>-Footnote-92924462
Ref: 库<59>-Footnote-102924511
Ref: 库<59>-Footnote-112924555
Ref: 库<59>-Footnote-122924605
Ref: 库<59>-Footnote-132924655
Ref: 库<59>-Footnote-142924699
Node: 安全<32>2924743
Ref: whatsnew/changelog id4282924842
Ref: 11662924842
Ref: 安全<32>-Footnote-12925160
Node: 库<60>2925203
Ref: whatsnew/changelog id4292925303
Ref: 11672925303
Ref: 库<60>-Footnote-12928049
Ref: 库<60>-Footnote-22928092
Ref: 库<60>-Footnote-32928135
Ref: 库<60>-Footnote-42928178
Ref: 库<60>-Footnote-52928221
Ref: 库<60>-Footnote-62928264
Ref: 库<60>-Footnote-72928307
Ref: 库<60>-Footnote-82928350
Ref: 库<60>-Footnote-92928393
Ref: 库<60>-Footnote-102928436
Ref: 库<60>-Footnote-112928480
Ref: 库<60>-Footnote-122928524
Ref: 库<60>-Footnote-132928568
Ref: 库<60>-Footnote-142928612
Ref: 库<60>-Footnote-152928656
Ref: 库<60>-Footnote-162928700
Ref: 库<60>-Footnote-172928744
Node: IDLE<45>2928788
Ref: whatsnew/changelog id4302928888
Ref: 11682928888
Ref: IDLE<45>-Footnote-12931541
Ref: IDLE<45>-Footnote-22931583
Ref: IDLE<45>-Footnote-32931626
Ref: IDLE<45>-Footnote-42931669
Ref: IDLE<45>-Footnote-52931712
Ref: IDLE<45>-Footnote-62931755
Ref: IDLE<45>-Footnote-72931798
Ref: IDLE<45>-Footnote-82931841
Ref: IDLE<45>-Footnote-92931884
Ref: IDLE<45>-Footnote-102931927
Ref: IDLE<45>-Footnote-112931971
Ref: IDLE<45>-Footnote-122932015
Ref: IDLE<45>-Footnote-132932059
Ref: IDLE<45>-Footnote-142932103
Ref: IDLE<45>-Footnote-152932147
Ref: IDLE<45>-Footnote-162932191
Ref: IDLE<45>-Footnote-172932235
Ref: IDLE<45>-Footnote-182932279
Ref: IDLE<45>-Footnote-192932323
Node: 文档<45>2932367
Ref: whatsnew/changelog id4312932470
Ref: 11692932470
Ref: 文档<45>-Footnote-12932897
Ref: 文档<45>-Footnote-22932940
Ref: 文档<45>-Footnote-32932983
Ref: 文档<45>-Footnote-42933032
Node: 测试<42>2933075
Ref: whatsnew/changelog id4322933181
Ref: 116a2933181
Ref: 测试<42>-Footnote-12933561
Ref: 测试<42>-Footnote-22933604
Node: Windows<42>2933647
Ref: whatsnew/changelog id4332933753
Ref: 116b2933753
Ref: Windows<42>-Footnote-12934037
Node: 构建<43>2934080
Ref: whatsnew/changelog id4342934187
Ref: 116c2934187
Ref: 构建<43>-Footnote-12934465
Ref: 构建<43>-Footnote-22934508
Node: Windows<43>2934551
Ref: whatsnew/changelog id4352934656
Ref: 116d2934656
Ref: Windows<43>-Footnote-12934859
Node: C API<32>2934902
Ref: whatsnew/changelog id4362935014
Ref: 116e2935014
Ref: C API<32>-Footnote-12935254
Ref: C API<32>-Footnote-22935297
Ref: C API<32>-Footnote-32935346
Node: 工具/示例<28>2935389
Ref: whatsnew/changelog id4372935481
Ref: 116f2935481
Ref: 工具/示例<28>-Footnote-12935679
Node: Python 3 6 0 alpha 12935722
Ref: whatsnew/changelog python-3-6-0-alpha-12935851
Ref: 11702935851
Node: 核心与内置<56>2936282
Ref: whatsnew/changelog id4382936374
Ref: 11712936374
Ref: 核心与内置<56>-Footnote-12949538
Ref: 核心与内置<56>-Footnote-22949581
Ref: 核心与内置<56>-Footnote-32949624
Ref: 核心与内置<56>-Footnote-42949667
Ref: 核心与内置<56>-Footnote-52949710
Ref: 核心与内置<56>-Footnote-62949753
Ref: 核心与内置<56>-Footnote-72949796
Ref: 核心与内置<56>-Footnote-82949839
Ref: 核心与内置<56>-Footnote-92949882
Ref: 核心与内置<56>-Footnote-102949925
Ref: 核心与内置<56>-Footnote-112949969
Ref: 核心与内置<56>-Footnote-122950013
Ref: 核心与内置<56>-Footnote-132950057
Ref: 核心与内置<56>-Footnote-142950101
Ref: 核心与内置<56>-Footnote-152950145
Ref: 核心与内置<56>-Footnote-162950189
Ref: 核心与内置<56>-Footnote-172950239
Ref: 核心与内置<56>-Footnote-182950283
Ref: 核心与内置<56>-Footnote-192950327
Ref: 核心与内置<56>-Footnote-202950371
Ref: 核心与内置<56>-Footnote-212950415
Ref: 核心与内置<56>-Footnote-222950459
Ref: 核心与内置<56>-Footnote-232950503
Ref: 核心与内置<56>-Footnote-242950553
Ref: 核心与内置<56>-Footnote-252950597
Ref: 核心与内置<56>-Footnote-262950641
Ref: 核心与内置<56>-Footnote-272950685
Ref: 核心与内置<56>-Footnote-282950729
Ref: 核心与内置<56>-Footnote-292950773
Ref: 核心与内置<56>-Footnote-302950817
Ref: 核心与内置<56>-Footnote-312950861
Ref: 核心与内置<56>-Footnote-322950905
Ref: 核心与内置<56>-Footnote-332950949
Ref: 核心与内置<56>-Footnote-342950993
Ref: 核心与内置<56>-Footnote-352951037
Ref: 核心与内置<56>-Footnote-362951081
Ref: 核心与内置<56>-Footnote-372951124
Ref: 核心与内置<56>-Footnote-382951168
Ref: 核心与内置<56>-Footnote-392951212
Ref: 核心与内置<56>-Footnote-402951256
Ref: 核心与内置<56>-Footnote-412951300
Ref: 核心与内置<56>-Footnote-422951344
Ref: 核心与内置<56>-Footnote-432951388
Ref: 核心与内置<56>-Footnote-442951432
Ref: 核心与内置<56>-Footnote-452951476
Ref: 核心与内置<56>-Footnote-462951520
Ref: 核心与内置<56>-Footnote-472951564
Ref: 核心与内置<56>-Footnote-482951608
Ref: 核心与内置<56>-Footnote-492951652
Ref: 核心与内置<56>-Footnote-502951696
Ref: 核心与内置<56>-Footnote-512951740
Ref: 核心与内置<56>-Footnote-522951784
Ref: 核心与内置<56>-Footnote-532951827
Ref: 核心与内置<56>-Footnote-542951871
Ref: 核心与内置<56>-Footnote-552951915
Ref: 核心与内置<56>-Footnote-562951959
Ref: 核心与内置<56>-Footnote-572952003
Ref: 核心与内置<56>-Footnote-582952047
Ref: 核心与内置<56>-Footnote-592952091
Ref: 核心与内置<56>-Footnote-602952135
Ref: 核心与内置<56>-Footnote-612952179
Ref: 核心与内置<56>-Footnote-622952223
Ref: 核心与内置<56>-Footnote-632952267
Ref: 核心与内置<56>-Footnote-642952311
Ref: 核心与内置<56>-Footnote-652952355
Ref: 核心与内置<56>-Footnote-662952399
Ref: 核心与内置<56>-Footnote-672952443
Ref: 核心与内置<56>-Footnote-682952487
Ref: 核心与内置<56>-Footnote-692952531
Ref: 核心与内置<56>-Footnote-702952575
Ref: 核心与内置<56>-Footnote-712952619
Ref: 核心与内置<56>-Footnote-722952663
Ref: 核心与内置<56>-Footnote-732952707
Ref: 核心与内置<56>-Footnote-742952751
Ref: 核心与内置<56>-Footnote-752952795
Ref: 核心与内置<56>-Footnote-762952839
Ref: 核心与内置<56>-Footnote-772952883
Ref: 核心与内置<56>-Footnote-782952927
Ref: 核心与内置<56>-Footnote-792952970
Ref: 核心与内置<56>-Footnote-802953014
Ref: 核心与内置<56>-Footnote-812953064
Ref: 核心与内置<56>-Footnote-822953108
Ref: 核心与内置<56>-Footnote-832953152
Ref: 核心与内置<56>-Footnote-842953196
Ref: 核心与内置<56>-Footnote-852953240
Ref: 核心与内置<56>-Footnote-862953284
Ref: 核心与内置<56>-Footnote-872953328
Node: 库<61>2953372
Ref: whatsnew/changelog id4392953483
Ref: 11732953483
Ref: 库<61>-Footnote-12958642
Ref: 库<61>-Footnote-22958685
Ref: 库<61>-Footnote-32958728
Ref: 库<61>-Footnote-42958771
Ref: 库<61>-Footnote-52958814
Ref: 库<61>-Footnote-62958857
Ref: 库<61>-Footnote-72958900
Ref: 库<61>-Footnote-82958943
Ref: 库<61>-Footnote-92958986
Ref: 库<61>-Footnote-102959029
Ref: 库<61>-Footnote-112959073
Ref: 库<61>-Footnote-122959117
Ref: 库<61>-Footnote-132959161
Ref: 库<61>-Footnote-142959205
Ref: 库<61>-Footnote-152959249
Ref: 库<61>-Footnote-162959293
Ref: 库<61>-Footnote-172959337
Ref: 库<61>-Footnote-182959381
Ref: 库<61>-Footnote-192959431
Ref: 库<61>-Footnote-202959475
Ref: 库<61>-Footnote-212959519
Ref: 库<61>-Footnote-222959563
Ref: 库<61>-Footnote-232959607
Ref: 库<61>-Footnote-242959651
Ref: 库<61>-Footnote-252959695
Ref: 库<61>-Footnote-262959739
Ref: 库<61>-Footnote-272959783
Ref: 库<61>-Footnote-282959827
Ref: 库<61>-Footnote-292959871
Ref: 库<61>-Footnote-302959915
Ref: 库<61>-Footnote-312959959
Ref: 库<61>-Footnote-322960003
Ref: 库<61>-Footnote-332960047
Ref: 库<61>-Footnote-342960091
Ref: 库<61>-Footnote-352960135
Ref: 库<61>-Footnote-362960179
Node: 安全<33>2960223
Ref: whatsnew/changelog id4402960322
Ref: 11742960322
Ref: 安全<33>-Footnote-12960604
Node: 库<62>2960647
Ref: whatsnew/changelog id4412960749
Ref: 11752960749
Ref: 库<62>-Footnote-12965454
Ref: 库<62>-Footnote-22965497
Ref: 库<62>-Footnote-32965540
Ref: 库<62>-Footnote-42965583
Ref: 库<62>-Footnote-52965626
Ref: 库<62>-Footnote-62965669
Ref: 库<62>-Footnote-72965712
Ref: 库<62>-Footnote-82965755
Ref: 库<62>-Footnote-92965798
Ref: 库<62>-Footnote-102965841
Ref: 库<62>-Footnote-112965885
Ref: 库<62>-Footnote-122965929
Ref: 库<62>-Footnote-132965973
Ref: 库<62>-Footnote-142966017
Ref: 库<62>-Footnote-152966061
Ref: 库<62>-Footnote-162966105
Ref: 库<62>-Footnote-172966149
Ref: 库<62>-Footnote-182966193
Ref: 库<62>-Footnote-192966237
Ref: 库<62>-Footnote-202966281
Ref: 库<62>-Footnote-212966325
Ref: 库<62>-Footnote-222966369
Ref: 库<62>-Footnote-232966413
Ref: 库<62>-Footnote-242966457
Ref: 库<62>-Footnote-252966501
Ref: 库<62>-Footnote-262966545
Ref: 库<62>-Footnote-272966589
Ref: 库<62>-Footnote-282966633
Ref: 库<62>-Footnote-292966677
Ref: 库<62>-Footnote-302966721
Ref: 库<62>-Footnote-312966765
Ref: 库<62>-Footnote-322966809
Node: 安全<34>2966853
Ref: whatsnew/changelog id4422966952
Ref: 11772966952
Ref: 安全<34>-Footnote-12967133
Node: 库<63>2967176
Ref: whatsnew/changelog id4432967278
Ref: 11782967278
Ref: 库<63>-Footnote-12970810
Ref: 库<63>-Footnote-22970853
Ref: 库<63>-Footnote-32970896
Ref: 库<63>-Footnote-42970939
Ref: 库<63>-Footnote-52970982
Ref: 库<63>-Footnote-62971025
Ref: 库<63>-Footnote-72971068
Ref: 库<63>-Footnote-82971111
Ref: 库<63>-Footnote-92971154
Ref: 库<63>-Footnote-102971197
Ref: 库<63>-Footnote-112971241
Ref: 库<63>-Footnote-122971285
Ref: 库<63>-Footnote-132971328
Ref: 库<63>-Footnote-142971372
Ref: 库<63>-Footnote-152971416
Ref: 库<63>-Footnote-162971460
Ref: 库<63>-Footnote-172971504
Ref: 库<63>-Footnote-182971548
Ref: 库<63>-Footnote-192971592
Ref: 库<63>-Footnote-202971636
Ref: 库<63>-Footnote-212971680
Ref: 库<63>-Footnote-222971724
Ref: 库<63>-Footnote-232971768
Ref: 库<63>-Footnote-242971812
Ref: 库<63>-Footnote-252971856
Node: 安全<35>2971900
Ref: whatsnew/changelog id4442971999
Ref: 117b2971999
Ref: 安全<35>-Footnote-12972159
Node: 库<64>2972202
Ref: whatsnew/changelog id4452972302
Ref: 117c2972302
Ref: 库<64>-Footnote-12989968
Ref: 库<64>-Footnote-22990011
Ref: 库<64>-Footnote-32990054
Ref: 库<64>-Footnote-42990097
Ref: 库<64>-Footnote-52990140
Ref: 库<64>-Footnote-62990183
Ref: 库<64>-Footnote-72990226
Ref: 库<64>-Footnote-82990269
Ref: 库<64>-Footnote-92990312
Ref: 库<64>-Footnote-102990355
Ref: 库<64>-Footnote-112990399
Ref: 库<64>-Footnote-122990443
Ref: 库<64>-Footnote-132990487
Ref: 库<64>-Footnote-142990531
Ref: 库<64>-Footnote-152990575
Ref: 库<64>-Footnote-162990619
Ref: 库<64>-Footnote-172990663
Ref: 库<64>-Footnote-182990707
Ref: 库<64>-Footnote-192990751
Ref: 库<64>-Footnote-202990795
Ref: 库<64>-Footnote-212990839
Ref: 库<64>-Footnote-222990883
Ref: 库<64>-Footnote-232990927
Ref: 库<64>-Footnote-242990971
Ref: 库<64>-Footnote-252991015
Ref: 库<64>-Footnote-262991059
Ref: 库<64>-Footnote-272991103
Ref: 库<64>-Footnote-282991147
Ref: 库<64>-Footnote-292991191
Ref: 库<64>-Footnote-302991235
Ref: 库<64>-Footnote-312991279
Ref: 库<64>-Footnote-322991323
Ref: 库<64>-Footnote-332991367
Ref: 库<64>-Footnote-342991411
Ref: 库<64>-Footnote-352991455
Ref: 库<64>-Footnote-362991499
Ref: 库<64>-Footnote-372991543
Ref: 库<64>-Footnote-382991587
Ref: 库<64>-Footnote-392991631
Ref: 库<64>-Footnote-402991675
Ref: 库<64>-Footnote-412991719
Ref: 库<64>-Footnote-422991763
Ref: 库<64>-Footnote-432991807
Ref: 库<64>-Footnote-442991851
Ref: 库<64>-Footnote-452991895
Ref: 库<64>-Footnote-462991939
Ref: 库<64>-Footnote-472991983
Ref: 库<64>-Footnote-482992027
Ref: 库<64>-Footnote-492992071
Ref: 库<64>-Footnote-502992115
Ref: 库<64>-Footnote-512992159
Ref: 库<64>-Footnote-522992202
Ref: 库<64>-Footnote-532992246
Ref: 库<64>-Footnote-542992290
Ref: 库<64>-Footnote-552992334
Ref: 库<64>-Footnote-562992378
Ref: 库<64>-Footnote-572992422
Ref: 库<64>-Footnote-582992465
Ref: 库<64>-Footnote-592992509
Ref: 库<64>-Footnote-602992553
Ref: 库<64>-Footnote-612992597
Ref: 库<64>-Footnote-622992641
Ref: 库<64>-Footnote-632992685
Ref: 库<64>-Footnote-642992729
Ref: 库<64>-Footnote-652992773
Ref: 库<64>-Footnote-662992817
Ref: 库<64>-Footnote-672992861
Ref: 库<64>-Footnote-682992904
Ref: 库<64>-Footnote-692992948
Ref: 库<64>-Footnote-702992992
Ref: 库<64>-Footnote-712993036
Ref: 库<64>-Footnote-722993080
Ref: 库<64>-Footnote-732993124
Ref: 库<64>-Footnote-742993168
Ref: 库<64>-Footnote-752993212
Ref: 库<64>-Footnote-762993256
Ref: 库<64>-Footnote-772993300
Ref: 库<64>-Footnote-782993344
Ref: 库<64>-Footnote-792993388
Ref: 库<64>-Footnote-802993432
Ref: 库<64>-Footnote-812993476
Ref: 库<64>-Footnote-822993520
Ref: 库<64>-Footnote-832993564
Ref: 库<64>-Footnote-842993608
Ref: 库<64>-Footnote-852993652
Ref: 库<64>-Footnote-862993696
Ref: 库<64>-Footnote-872993740
Ref: 库<64>-Footnote-882993784
Ref: 库<64>-Footnote-892993828
Ref: 库<64>-Footnote-902993872
Ref: 库<64>-Footnote-912993916
Ref: 库<64>-Footnote-922993960
Ref: 库<64>-Footnote-932994004
Ref: 库<64>-Footnote-942994048
Ref: 库<64>-Footnote-952994092
Ref: 库<64>-Footnote-962994136
Ref: 库<64>-Footnote-972994180
Ref: 库<64>-Footnote-982994224
Ref: 库<64>-Footnote-992994268
Ref: 库<64>-Footnote-1002994312
Ref: 库<64>-Footnote-1012994357
Ref: 库<64>-Footnote-1022994402
Ref: 库<64>-Footnote-1032994447
Ref: 库<64>-Footnote-1042994492
Ref: 库<64>-Footnote-1052994537
Ref: 库<64>-Footnote-1062994582
Ref: 库<64>-Footnote-1072994627
Ref: 库<64>-Footnote-1082994672
Ref: 库<64>-Footnote-1092994717
Ref: 库<64>-Footnote-1102994762
Ref: 库<64>-Footnote-1112994807
Ref: 库<64>-Footnote-1122994852
Ref: 库<64>-Footnote-1132994897
Ref: 库<64>-Footnote-1142994942
Ref: 库<64>-Footnote-1152994987
Ref: 库<64>-Footnote-1162995031
Ref: 库<64>-Footnote-1172995075
Ref: 库<64>-Footnote-1182995120
Ref: 库<64>-Footnote-1192995165
Ref: 库<64>-Footnote-1202995210
Ref: 库<64>-Footnote-1212995255
Ref: 库<64>-Footnote-1222995300
Ref: 库<64>-Footnote-1232995345
Ref: 库<64>-Footnote-1242995390
Ref: 库<64>-Footnote-1252995435
Ref: 库<64>-Footnote-1262995480
Ref: 库<64>-Footnote-1272995525
Ref: 库<64>-Footnote-1282995570
Ref: 库<64>-Footnote-1292995615
Ref: 库<64>-Footnote-1302995660
Ref: 库<64>-Footnote-1312995705
Node: IDLE<46>2995750
Ref: whatsnew/changelog id4462995850
Ref: 117d2995850
Ref: IDLE<46>-Footnote-13001431
Ref: IDLE<46>-Footnote-23001474
Ref: IDLE<46>-Footnote-33001517
Ref: IDLE<46>-Footnote-43001560
Ref: IDLE<46>-Footnote-53001603
Ref: IDLE<46>-Footnote-63001646
Ref: IDLE<46>-Footnote-73001689
Ref: IDLE<46>-Footnote-83001732
Ref: IDLE<46>-Footnote-93001775
Ref: IDLE<46>-Footnote-103001818
Ref: IDLE<46>-Footnote-113001862
Ref: IDLE<46>-Footnote-123001906
Ref: IDLE<46>-Footnote-133001950
Ref: IDLE<46>-Footnote-143001994
Ref: IDLE<46>-Footnote-153002038
Ref: IDLE<46>-Footnote-163002082
Ref: IDLE<46>-Footnote-173002126
Ref: IDLE<46>-Footnote-183002170
Ref: IDLE<46>-Footnote-193002214
Ref: IDLE<46>-Footnote-203002258
Ref: IDLE<46>-Footnote-213002302
Ref: IDLE<46>-Footnote-223002346
Ref: IDLE<46>-Footnote-233002390
Ref: IDLE<46>-Footnote-243002434
Ref: IDLE<46>-Footnote-253002478
Ref: IDLE<46>-Footnote-263002522
Ref: IDLE<46>-Footnote-273002566
Ref: IDLE<46>-Footnote-283002610
Node: 文档<46>3002654
Ref: whatsnew/changelog id4473002757
Ref: 117e3002757
Ref: 文档<46>-Footnote-13003527
Ref: 文档<46>-Footnote-23003570
Ref: 文档<46>-Footnote-33003612
Ref: 文档<46>-Footnote-43003655
Ref: 文档<46>-Footnote-53003698
Node: 测试<43>3003741
Ref: whatsnew/changelog id4483003846
Ref: 117f3003846
Ref: 测试<43>-Footnote-13005597
Ref: 测试<43>-Footnote-23005640
Ref: 测试<43>-Footnote-33005683
Ref: 测试<43>-Footnote-43005726
Ref: 测试<43>-Footnote-53005769
Ref: 测试<43>-Footnote-63005812
Ref: 测试<43>-Footnote-73005855
Ref: 测试<43>-Footnote-83005898
Ref: 测试<43>-Footnote-93005941
Ref: 测试<43>-Footnote-103005984
Ref: 测试<43>-Footnote-113006028
Ref: 测试<43>-Footnote-123006072
Ref: 测试<43>-Footnote-133006116
Node: 构建<44>3006160
Ref: whatsnew/changelog id4493006266
Ref: 11803006266
Ref: 构建<44>-Footnote-13008979
Ref: 构建<44>-Footnote-23009022
Ref: 构建<44>-Footnote-33009065
Ref: 构建<44>-Footnote-43009108
Ref: 构建<44>-Footnote-53009151
Ref: 构建<44>-Footnote-63009194
Ref: 构建<44>-Footnote-73009237
Ref: 构建<44>-Footnote-83009280
Ref: 构建<44>-Footnote-93009323
Ref: 构建<44>-Footnote-103009366
Ref: 构建<44>-Footnote-113009410
Ref: 构建<44>-Footnote-123009454
Ref: 构建<44>-Footnote-133009498
Ref: 构建<44>-Footnote-143009542
Ref: 构建<44>-Footnote-153009586
Ref: 构建<44>-Footnote-163009630
Ref: 构建<44>-Footnote-173009674
Ref: 构建<44>-Footnote-183009718
Ref: 构建<44>-Footnote-193009762
Node: Windows<44>3009806
Ref: whatsnew/changelog id4503009919
Ref: 11813009919
Ref: Windows<44>-Footnote-13010569
Ref: Windows<44>-Footnote-23010612
Ref: Windows<44>-Footnote-33010655
Ref: Windows<44>-Footnote-43010698
Ref: Windows<44>-Footnote-53010741
Ref: Windows<44>-Footnote-63010784
Node: 工具/示例<29>3010827
Ref: whatsnew/changelog id4513010939
Ref: 11823010939
Ref: 工具/示例<29>-Footnote-13011731
Ref: 工具/示例<29>-Footnote-23011774
Ref: 工具/示例<29>-Footnote-33011817
Ref: 工具/示例<29>-Footnote-43011860
Ref: 工具/示例<29>-Footnote-53011903
Ref: 工具/示例<29>-Footnote-63011946
Node: C API<33>3011989
Ref: whatsnew/changelog id4523012081
Ref: 11833012081
Ref: C API<33>-Footnote-13012570
Ref: C API<33>-Footnote-23012613
Node: Python 3 5 5 正式版3012656
Ref: whatsnew/changelog python-3-5-5-final3012781
Ref: 11843012781
Node: Python 3 5 5 rc13012912
Ref: whatsnew/changelog python-3-5-5-release-candidate-13013039
Ref: 11853013039
Node: 安全<36>3013206
Ref: whatsnew/changelog id4533013297
Ref: 11863013297
Ref: 安全<36>-Footnote-13014559
Ref: 安全<36>-Footnote-23014602
Ref: 安全<36>-Footnote-33014645
Ref: 安全<36>-Footnote-43014688
Ref: 安全<36>-Footnote-53014731
Node: 核心与内置<57>3014774
Ref: whatsnew/changelog id4543014881
Ref: 11873014881
Ref: 核心与内置<57>-Footnote-13015097
Node: 库<65>3015140
Ref: whatsnew/changelog id4553015228
Ref: 11883015228
Ref: 库<65>-Footnote-13015746
Ref: 库<65>-Footnote-23015789
Node: Python 3 5 4 正式版3015832
Ref: whatsnew/changelog python-3-5-4-final3015953
Ref: 11893015953
Node: 库<66>3016067
Ref: whatsnew/changelog id4563016133
Ref: 118a3016133
Ref: 库<66>-Footnote-13016323
Node: Python 3 5 4 rc13016366
Ref: whatsnew/changelog python-3-5-4-release-candidate-13016493
Ref: 118b3016493
Node: 安全<37>3016770
Ref: whatsnew/changelog id4573016861
Ref: 118c3016861
Ref: 安全<37>-Footnote-13018154
Ref: 安全<37>-Footnote-23018197
Ref: 安全<37>-Footnote-33018240
Ref: 安全<37>-Footnote-43018283
Node: 核心与内置<58>3018326
Ref: whatsnew/changelog id4583018433
Ref: 118d3018433
Ref: 核心与内置<58>-Footnote-13020679
Ref: 核心与内置<58>-Footnote-23020722
Ref: 核心与内置<58>-Footnote-33020765
Ref: 核心与内置<58>-Footnote-43020808
Ref: 核心与内置<58>-Footnote-53020851
Ref: 核心与内置<58>-Footnote-63020894
Ref: 核心与内置<58>-Footnote-73020937
Ref: 核心与内置<58>-Footnote-83020980
Ref: 核心与内置<58>-Footnote-93021023
Ref: 核心与内置<58>-Footnote-103021066
Ref: 核心与内置<58>-Footnote-113021110
Ref: 核心与内置<58>-Footnote-123021154
Ref: 核心与内置<58>-Footnote-133021198
Ref: 核心与内置<58>-Footnote-143021242
Ref: 核心与内置<58>-Footnote-153021286
Node: 库<67>3021330
Ref: whatsnew/changelog id4593021437
Ref: 118e3021437
Ref: 库<67>-Footnote-13031618
Ref: 库<67>-Footnote-23031661
Ref: 库<67>-Footnote-33031704
Ref: 库<67>-Footnote-43031747
Ref: 库<67>-Footnote-53031790
Ref: 库<67>-Footnote-63031833
Ref: 库<67>-Footnote-73031876
Ref: 库<67>-Footnote-83031919
Ref: 库<67>-Footnote-93031962
Ref: 库<67>-Footnote-103032005
Ref: 库<67>-Footnote-113032049
Ref: 库<67>-Footnote-123032093
Ref: 库<67>-Footnote-133032137
Ref: 库<67>-Footnote-143032181
Ref: 库<67>-Footnote-153032225
Ref: 库<67>-Footnote-163032269
Ref: 库<67>-Footnote-173032313
Ref: 库<67>-Footnote-183032357
Ref: 库<67>-Footnote-193032401
Ref: 库<67>-Footnote-203032445
Ref: 库<67>-Footnote-213032489
Ref: 库<67>-Footnote-223032533
Ref: 库<67>-Footnote-233032577
Ref: 库<67>-Footnote-243032621
Ref: 库<67>-Footnote-253032665
Ref: 库<67>-Footnote-263032709
Ref: 库<67>-Footnote-273032753
Ref: 库<67>-Footnote-283032797
Ref: 库<67>-Footnote-293032841
Ref: 库<67>-Footnote-303032885
Ref: 库<67>-Footnote-313032929
Ref: 库<67>-Footnote-323032973
Ref: 库<67>-Footnote-333033017
Ref: 库<67>-Footnote-343033061
Ref: 库<67>-Footnote-353033105
Ref: 库<67>-Footnote-363033149
Ref: 库<67>-Footnote-373033193
Ref: 库<67>-Footnote-383033237
Ref: 库<67>-Footnote-393033281
Ref: 库<67>-Footnote-403033325
Ref: 库<67>-Footnote-413033369
Ref: 库<67>-Footnote-423033413
Ref: 库<67>-Footnote-433033457
Ref: 库<67>-Footnote-443033501
Ref: 库<67>-Footnote-453033545
Ref: 库<67>-Footnote-463033589
Ref: 库<67>-Footnote-473033633
Ref: 库<67>-Footnote-483033677
Ref: 库<67>-Footnote-493033721
Ref: 库<67>-Footnote-503033765
Ref: 库<67>-Footnote-513033809
Ref: 库<67>-Footnote-523033853
Ref: 库<67>-Footnote-533033897
Ref: 库<67>-Footnote-543033941
Ref: 库<67>-Footnote-553033984
Ref: 库<67>-Footnote-563034028
Ref: 库<67>-Footnote-573034072
Ref: 库<67>-Footnote-583034116
Ref: 库<67>-Footnote-593034160
Ref: 库<67>-Footnote-603034204
Ref: 库<67>-Footnote-613034248
Ref: 库<67>-Footnote-623034292
Ref: 库<67>-Footnote-633034336
Ref: 库<67>-Footnote-643034380
Ref: 库<67>-Footnote-653034424
Ref: 库<67>-Footnote-663034468
Ref: 库<67>-Footnote-673034512
Ref: 库<67>-Footnote-683034556
Ref: 库<67>-Footnote-693034600
Ref: 库<67>-Footnote-703034644
Ref: 库<67>-Footnote-713034688
Ref: 库<67>-Footnote-723034732
Ref: 库<67>-Footnote-733034776
Ref: 库<67>-Footnote-743034820
Node: 文档<47>3034864
Ref: whatsnew/changelog id4603034962
Ref: 118f3034962
Ref: 文档<47>-Footnote-13035656
Ref: 文档<47>-Footnote-23035699
Ref: 文档<47>-Footnote-33035742
Ref: 文档<47>-Footnote-43035785
Ref: 文档<47>-Footnote-53035828
Ref: 文档<47>-Footnote-63035871
Node: 测试<44>3035914
Ref: whatsnew/changelog id4613036015
Ref: 11903036015
Ref: 测试<44>-Footnote-13038114
Ref: 测试<44>-Footnote-23038157
Ref: 测试<44>-Footnote-33038200
Ref: 测试<44>-Footnote-43038243
Ref: 测试<44>-Footnote-53038286
Ref: 测试<44>-Footnote-63038329
Ref: 测试<44>-Footnote-73038372
Ref: 测试<44>-Footnote-83038415
Ref: 测试<44>-Footnote-93038458
Node: 构建<45>3038501
Ref: whatsnew/changelog id4623038603
Ref: 11913038603
Ref: 构建<45>-Footnote-13039119
Ref: 构建<45>-Footnote-23039162
Ref: 构建<45>-Footnote-33039205
Node: Windows<45>3039248
Ref: whatsnew/changelog id4633039349
Ref: 11923039349
Ref: Windows<45>-Footnote-13039607
Ref: Windows<45>-Footnote-23039650
Node: C API<34>3039693
Ref: whatsnew/changelog id4643039775
Ref: 11933039775
Ref: C API<34>-Footnote-13040382
Ref: C API<34>-Footnote-23040425
Node: Python 3 5 3 正式版3040468
Ref: whatsnew/changelog python-3-5-3-final3040589
Ref: 11943040589
Node: Python 3 5 3 rc13040739
Ref: whatsnew/changelog python-3-5-3-release-candidate-13040866
Ref: 11953040866
Node: 核心与内置<59>3041251
Ref: whatsnew/changelog id4653041339
Ref: 11963041339
Ref: 核心与内置<59>-Footnote-13046772
Ref: 核心与内置<59>-Footnote-23046815
Ref: 核心与内置<59>-Footnote-33046858
Ref: 核心与内置<59>-Footnote-43046901
Ref: 核心与内置<59>-Footnote-53046944
Ref: 核心与内置<59>-Footnote-63046987
Ref: 核心与内置<59>-Footnote-73047030
Ref: 核心与内置<59>-Footnote-83047073
Ref: 核心与内置<59>-Footnote-93047116
Ref: 核心与内置<59>-Footnote-103047159
Ref: 核心与内置<59>-Footnote-113047203
Ref: 核心与内置<59>-Footnote-123047247
Ref: 核心与内置<59>-Footnote-133047291
Ref: 核心与内置<59>-Footnote-143047335
Ref: 核心与内置<59>-Footnote-153047379
Ref: 核心与内置<59>-Footnote-163047423
Ref: 核心与内置<59>-Footnote-173047467
Ref: 核心与内置<59>-Footnote-183047511
Ref: 核心与内置<59>-Footnote-193047555
Ref: 核心与内置<59>-Footnote-203047599
Ref: 核心与内置<59>-Footnote-213047643
Ref: 核心与内置<59>-Footnote-223047687
Ref: 核心与内置<59>-Footnote-233047731
Ref: 核心与内置<59>-Footnote-243047775
Ref: 核心与内置<59>-Footnote-253047819
Ref: 核心与内置<59>-Footnote-263047863
Ref: 核心与内置<59>-Footnote-273047907
Ref: 核心与内置<59>-Footnote-283047951
Ref: 核心与内置<59>-Footnote-293047995
Ref: 核心与内置<59>-Footnote-303048039
Ref: 核心与内置<59>-Footnote-313048083
Ref: 核心与内置<59>-Footnote-323048127
Ref: 核心与内置<59>-Footnote-333048171
Ref: 核心与内置<59>-Footnote-343048215
Ref: 核心与内置<59>-Footnote-353048259
Ref: 核心与内置<59>-Footnote-363048303
Ref: 核心与内置<59>-Footnote-373048347
Ref: 核心与内置<59>-Footnote-383048391
Ref: 核心与内置<59>-Footnote-393048435
Ref: 核心与内置<59>-Footnote-403048479
Ref: 核心与内置<59>-Footnote-413048523
Ref: 核心与内置<59>-Footnote-423048567
Ref: 核心与内置<59>-Footnote-433048611
Node: 库<68>3048655
Ref: whatsnew/changelog id4663048762
Ref: 11973048762
Ref: 库<68>-Footnote-13061757
Ref: 库<68>-Footnote-23061800
Ref: 库<68>-Footnote-33061843
Ref: 库<68>-Footnote-43061886
Ref: 库<68>-Footnote-53061929
Ref: 库<68>-Footnote-63061971
Ref: 库<68>-Footnote-73062014
Ref: 库<68>-Footnote-83062057
Ref: 库<68>-Footnote-93062100
Ref: 库<68>-Footnote-103062143
Ref: 库<68>-Footnote-113062187
Ref: 库<68>-Footnote-123062231
Ref: 库<68>-Footnote-133062275
Ref: 库<68>-Footnote-143062319
Ref: 库<68>-Footnote-153062363
Ref: 库<68>-Footnote-163062407
Ref: 库<68>-Footnote-173062451
Ref: 库<68>-Footnote-183062495
Ref: 库<68>-Footnote-193062539
Ref: 库<68>-Footnote-203062583
Ref: 库<68>-Footnote-213062627
Ref: 库<68>-Footnote-223062671
Ref: 库<68>-Footnote-233062715
Ref: 库<68>-Footnote-243062759
Ref: 库<68>-Footnote-253062803
Ref: 库<68>-Footnote-263062847
Ref: 库<68>-Footnote-273062891
Ref: 库<68>-Footnote-283062935
Ref: 库<68>-Footnote-293062979
Ref: 库<68>-Footnote-303063023
Ref: 库<68>-Footnote-313063067
Ref: 库<68>-Footnote-323063111
Ref: 库<68>-Footnote-333063157
Ref: 库<68>-Footnote-343063201
Ref: 库<68>-Footnote-353063245
Ref: 库<68>-Footnote-363063289
Ref: 库<68>-Footnote-373063333
Ref: 库<68>-Footnote-383063377
Ref: 库<68>-Footnote-393063421
Ref: 库<68>-Footnote-403063465
Ref: 库<68>-Footnote-413063509
Ref: 库<68>-Footnote-423063553
Ref: 库<68>-Footnote-433063597
Ref: 库<68>-Footnote-443063641
Ref: 库<68>-Footnote-453063685
Ref: 库<68>-Footnote-463063729
Ref: 库<68>-Footnote-473063773
Ref: 库<68>-Footnote-483063817
Ref: 库<68>-Footnote-493063861
Ref: 库<68>-Footnote-503063905
Ref: 库<68>-Footnote-513063949
Ref: 库<68>-Footnote-523063993
Ref: 库<68>-Footnote-533064037
Ref: 库<68>-Footnote-543064081
Ref: 库<68>-Footnote-553064125
Ref: 库<68>-Footnote-563064169
Ref: 库<68>-Footnote-573064213
Ref: 库<68>-Footnote-583064257
Ref: 库<68>-Footnote-593064301
Ref: 库<68>-Footnote-603064345
Ref: 库<68>-Footnote-613064389
Ref: 库<68>-Footnote-623064433
Ref: 库<68>-Footnote-633064477
Ref: 库<68>-Footnote-643064521
Ref: 库<68>-Footnote-653064565
Ref: 库<68>-Footnote-663064609
Ref: 库<68>-Footnote-673064653
Ref: 库<68>-Footnote-683064697
Ref: 库<68>-Footnote-693064741
Ref: 库<68>-Footnote-703064785
Ref: 库<68>-Footnote-713064829
Ref: 库<68>-Footnote-723064872
Ref: 库<68>-Footnote-733064916
Ref: 库<68>-Footnote-743064960
Ref: 库<68>-Footnote-753065004
Ref: 库<68>-Footnote-763065048
Ref: 库<68>-Footnote-773065092
Ref: 库<68>-Footnote-783065136
Ref: 库<68>-Footnote-793065180
Ref: 库<68>-Footnote-803065224
Ref: 库<68>-Footnote-813065268
Ref: 库<68>-Footnote-823065312
Ref: 库<68>-Footnote-833065356
Ref: 库<68>-Footnote-843065400
Ref: 库<68>-Footnote-853065444
Ref: 库<68>-Footnote-863065488
Ref: 库<68>-Footnote-873065532
Ref: 库<68>-Footnote-883065576
Ref: 库<68>-Footnote-893065620
Ref: 库<68>-Footnote-903065664
Ref: 库<68>-Footnote-913065708
Ref: 库<68>-Footnote-923065752
Ref: 库<68>-Footnote-933065796
Ref: 库<68>-Footnote-943065840
Ref: 库<68>-Footnote-953065884
Node: 安全<38>3065934
Ref: whatsnew/changelog id4673066029
Ref: 11983066029
Ref: 安全<38>-Footnote-13066312
Node: 库<69>3066355
Ref: whatsnew/changelog id4683066453
Ref: 11993066453
Ref: 库<69>-Footnote-13066618
Node: 安全<39>3066661
Ref: whatsnew/changelog id4693066756
Ref: 119a3066756
Ref: 安全<39>-Footnote-13066914
Node: 库<70>3066957
Ref: whatsnew/changelog id4703067053
Ref: 119b3067053
Ref: 库<70>-Footnote-13069924
Ref: 库<70>-Footnote-23069967
Ref: 库<70>-Footnote-33070010
Ref: 库<70>-Footnote-43070053
Ref: 库<70>-Footnote-53070096
Ref: 库<70>-Footnote-63070139
Ref: 库<70>-Footnote-73070182
Ref: 库<70>-Footnote-83070225
Ref: 库<70>-Footnote-93070268
Ref: 库<70>-Footnote-103070311
Ref: 库<70>-Footnote-113070355
Ref: 库<70>-Footnote-123070399
Ref: 库<70>-Footnote-133070443
Ref: 库<70>-Footnote-143070487
Ref: 库<70>-Footnote-153070531
Ref: 库<70>-Footnote-163070575
Ref: 库<70>-Footnote-173070619
Ref: 库<70>-Footnote-183070663
Ref: 库<70>-Footnote-193070707
Ref: 库<70>-Footnote-203070751
Ref: 库<70>-Footnote-213070795
Ref: 库<70>-Footnote-223070839
Ref: 库<70>-Footnote-233070883
Ref: 库<70>-Footnote-243070927
Ref: 库<70>-Footnote-253070971
Ref: 库<70>-Footnote-263071015
Ref: 库<70>-Footnote-273071059
Ref: 库<70>-Footnote-283071103
Node: IDLE<47>3071147
Ref: whatsnew/changelog id4713071242
Ref: 119c3071242
Ref: IDLE<47>-Footnote-13072498
Ref: IDLE<47>-Footnote-23072541
Ref: IDLE<47>-Footnote-33072584
Ref: IDLE<47>-Footnote-43072627
Ref: IDLE<47>-Footnote-53072670
Ref: IDLE<47>-Footnote-63072713
Ref: IDLE<47>-Footnote-73072756
Ref: IDLE<47>-Footnote-83072799
Node: C API<35>3072842
Ref: whatsnew/changelog id4723072940
Ref: 119d3072940
Ref: C API<35>-Footnote-13073270
Ref: C API<35>-Footnote-23073313
Node: 文档<48>3073356
Ref: whatsnew/changelog id4733073456
Ref: 119e3073456
Ref: 文档<48>-Footnote-13073591
Node: 测试<45>3073634
Ref: whatsnew/changelog id4743073742
Ref: 119f3073742
Ref: 测试<45>-Footnote-13074431
Ref: 测试<45>-Footnote-23074474
Ref: 测试<45>-Footnote-33074517
Ref: 测试<45>-Footnote-43074560
Ref: 测试<45>-Footnote-53074603
Ref: 测试<45>-Footnote-63074646
Node: 工具/示例<30>3074689
Ref: whatsnew/changelog id4753074798
Ref: 11a03074798
Ref: 工具/示例<30>-Footnote-13075278
Ref: 工具/示例<30>-Footnote-23075321
Ref: 工具/示例<30>-Footnote-33075364
Node: Windows<46>3075407
Ref: whatsnew/changelog id4763075516
Ref: 11a13075516
Ref: Windows<46>-Footnote-13076018
Ref: Windows<46>-Footnote-23076061
Ref: Windows<46>-Footnote-33076104
Ref: Windows<46>-Footnote-43076147
Ref: Windows<46>-Footnote-53076190
Node: 构建<46>3076233
Ref: whatsnew/changelog id4773076316
Ref: 11a23076316
Ref: 构建<46>-Footnote-13079018
Ref: 构建<46>-Footnote-23079061
Ref: 构建<46>-Footnote-33079104
Ref: 构建<46>-Footnote-43079147
Ref: 构建<46>-Footnote-53079190
Ref: 构建<46>-Footnote-63079233
Ref: 构建<46>-Footnote-73079276
Ref: 构建<46>-Footnote-83079319
Ref: 构建<46>-Footnote-93079362
Ref: 构建<46>-Footnote-103079405
Ref: 构建<46>-Footnote-113079449
Ref: 构建<46>-Footnote-123079493
Ref: 构建<46>-Footnote-133079537
Ref: 构建<46>-Footnote-143079581
Ref: 构建<46>-Footnote-153079625
Ref: 构建<46>-Footnote-163079669
Ref: 构建<46>-Footnote-173079713
Ref: 构建<46>-Footnote-183079757
Ref: 构建<46>-Footnote-193079801
Ref: 构建<46>-Footnote-203079845
Ref: 构建<46>-Footnote-213079889
Ref: 构建<46>-Footnote-223079933
Node: Python 3 5 2 正式版3079977
Ref: whatsnew/changelog python-3-5-2-final3080098
Ref: 11a33080098
Node: 核心与内置<60>3080276
Ref: whatsnew/changelog id4783080373
Ref: 11a43080373
Ref: 核心与内置<60>-Footnote-13080530
Node: 测试<46>3080573
Ref: whatsnew/changelog id4793080687
Ref: 11a53080687
Ref: 测试<46>-Footnote-13080847
Node: IDLE<48>3080890
Ref: whatsnew/changelog id4803080976
Ref: 11a63080976
Ref: IDLE<48>-Footnote-13081130
Node: Python 3 5 2 rc13081173
Ref: whatsnew/changelog python-3-5-2-release-candidate-13081300
Ref: 11a73081300
Node: 核心与内置<61>3081787
Ref: whatsnew/changelog id4813081878
Ref: 11a83081878
Ref: 核心与内置<61>-Footnote-13087716
Ref: 核心与内置<61>-Footnote-23087759
Ref: 核心与内置<61>-Footnote-33087802
Ref: 核心与内置<61>-Footnote-43087845
Ref: 核心与内置<61>-Footnote-53087888
Ref: 核心与内置<61>-Footnote-63087931
Ref: 核心与内置<61>-Footnote-73087974
Ref: 核心与内置<61>-Footnote-83088017
Ref: 核心与内置<61>-Footnote-93088060
Ref: 核心与内置<61>-Footnote-103088103
Ref: 核心与内置<61>-Footnote-113088147
Ref: 核心与内置<61>-Footnote-123088191
Ref: 核心与内置<61>-Footnote-133088235
Ref: 核心与内置<61>-Footnote-143088279
Ref: 核心与内置<61>-Footnote-153088323
Ref: 核心与内置<61>-Footnote-163088367
Ref: 核心与内置<61>-Footnote-173088411
Ref: 核心与内置<61>-Footnote-183088454
Ref: 核心与内置<61>-Footnote-193088498
Ref: 核心与内置<61>-Footnote-203088542
Ref: 核心与内置<61>-Footnote-213088586
Ref: 核心与内置<61>-Footnote-223088630
Ref: 核心与内置<61>-Footnote-233088674
Ref: 核心与内置<61>-Footnote-243088718
Ref: 核心与内置<61>-Footnote-253088762
Ref: 核心与内置<61>-Footnote-263088806
Ref: 核心与内置<61>-Footnote-273088850
Ref: 核心与内置<61>-Footnote-283088894
Ref: 核心与内置<61>-Footnote-293088938
Ref: 核心与内置<61>-Footnote-303088982
Ref: 核心与内置<61>-Footnote-313089026
Ref: 核心与内置<61>-Footnote-323089076
Ref: 核心与内置<61>-Footnote-333089120
Ref: 核心与内置<61>-Footnote-343089164
Ref: 核心与内置<61>-Footnote-353089208
Ref: 核心与内置<61>-Footnote-363089252
Ref: 核心与内置<61>-Footnote-373089296
Ref: 核心与内置<61>-Footnote-383089340
Node: 安全<40>3089384
Ref: whatsnew/changelog id4823089491
Ref: 11a93089491
Ref: 安全<40>-Footnote-13089720
Node: 库<71>3089763
Ref: whatsnew/changelog id4833089861
Ref: 11aa3089861
Ref: 库<71>-Footnote-13091028
Ref: 库<71>-Footnote-23091071
Ref: 库<71>-Footnote-33091114
Ref: 库<71>-Footnote-43091163
Ref: 库<71>-Footnote-53091206
Node: 安全<41>3091249
Ref: whatsnew/changelog id4843091344
Ref: 11ab3091344
Ref: 安全<41>-Footnote-13091662
Node: 库<72>3091705
Ref: whatsnew/changelog id4853091803
Ref: 11ac3091803
Ref: 库<72>-Footnote-13096518
Ref: 库<72>-Footnote-23096561
Ref: 库<72>-Footnote-33096604
Ref: 库<72>-Footnote-43096647
Ref: 库<72>-Footnote-53096690
Ref: 库<72>-Footnote-63096733
Ref: 库<72>-Footnote-73096776
Ref: 库<72>-Footnote-83096819
Ref: 库<72>-Footnote-93096862
Ref: 库<72>-Footnote-103096905
Ref: 库<72>-Footnote-113096949
Ref: 库<72>-Footnote-123096993
Ref: 库<72>-Footnote-133097037
Ref: 库<72>-Footnote-143097081
Ref: 库<72>-Footnote-153097125
Ref: 库<72>-Footnote-163097169
Ref: 库<72>-Footnote-173097213
Ref: 库<72>-Footnote-183097257
Ref: 库<72>-Footnote-193097301
Ref: 库<72>-Footnote-203097345
Ref: 库<72>-Footnote-213097389
Ref: 库<72>-Footnote-223097433
Ref: 库<72>-Footnote-233097477
Ref: 库<72>-Footnote-243097521
Ref: 库<72>-Footnote-253097565
Ref: 库<72>-Footnote-263097609
Ref: 库<72>-Footnote-273097653
Ref: 库<72>-Footnote-283097697
Ref: 库<72>-Footnote-293097741
Ref: 库<72>-Footnote-303097785
Ref: 库<72>-Footnote-313097829
Node: 安全<42>3097873
Ref: whatsnew/changelog id4863097968
Ref: 11ad3097968
Ref: 安全<42>-Footnote-13098250
Node: 库<73>3098293
Ref: whatsnew/changelog id4873098391
Ref: 11ae3098391
Ref: 库<73>-Footnote-13100455
Ref: 库<73>-Footnote-23100498
Ref: 库<73>-Footnote-33100541
Ref: 库<73>-Footnote-43100584
Ref: 库<73>-Footnote-53100627
Ref: 库<73>-Footnote-63100670
Ref: 库<73>-Footnote-73100713
Ref: 库<73>-Footnote-83100756
Ref: 库<73>-Footnote-93100799
Ref: 库<73>-Footnote-103100842
Ref: 库<73>-Footnote-113100886
Ref: 库<73>-Footnote-123100930
Ref: 库<73>-Footnote-133100974
Ref: 库<73>-Footnote-143101018
Ref: 库<73>-Footnote-153101062
Node: 安全<43>3101106
Ref: whatsnew/changelog id4883101201
Ref: 11af3101201
Ref: 安全<43>-Footnote-13101382
Node: 库<74>3101425
Ref: whatsnew/changelog id4893101523
Ref: 11b03101523
Ref: 库<74>-Footnote-13104067
Ref: 库<74>-Footnote-23104110
Ref: 库<74>-Footnote-33104153
Ref: 库<74>-Footnote-43104196
Ref: 库<74>-Footnote-53104239
Ref: 库<74>-Footnote-63104282
Ref: 库<74>-Footnote-73104325
Ref: 库<74>-Footnote-83104368
Ref: 库<74>-Footnote-93104411
Ref: 库<74>-Footnote-103104454
Ref: 库<74>-Footnote-113104497
Ref: 库<74>-Footnote-123104541
Ref: 库<74>-Footnote-133104585
Ref: 库<74>-Footnote-143104629
Ref: 库<74>-Footnote-153104673
Ref: 库<74>-Footnote-163104717
Ref: 库<74>-Footnote-173104761
Ref: 库<74>-Footnote-183104805
Ref: 库<74>-Footnote-193104849
Node: 安全<44>3104893
Ref: whatsnew/changelog id4903104988
Ref: 11b13104988
Ref: 安全<44>-Footnote-13105150
Node: 库<75>3105193
Ref: whatsnew/changelog id4913105289
Ref: 11b23105289
Ref: 库<75>-Footnote-13111772
Ref: 库<75>-Footnote-23111815
Ref: 库<75>-Footnote-33111858
Ref: 库<75>-Footnote-43111901
Ref: 库<75>-Footnote-53111944
Ref: 库<75>-Footnote-63111987
Ref: 库<75>-Footnote-73112030
Ref: 库<75>-Footnote-83112073
Ref: 库<75>-Footnote-93112116
Ref: 库<75>-Footnote-103112159
Ref: 库<75>-Footnote-113112203
Ref: 库<75>-Footnote-123112247
Ref: 库<75>-Footnote-133112291
Ref: 库<75>-Footnote-143112335
Ref: 库<75>-Footnote-153112379
Ref: 库<75>-Footnote-163112423
Ref: 库<75>-Footnote-173112467
Ref: 库<75>-Footnote-183112511
Ref: 库<75>-Footnote-193112555
Ref: 库<75>-Footnote-203112599
Ref: 库<75>-Footnote-213112643
Ref: 库<75>-Footnote-223112687
Ref: 库<75>-Footnote-233112731
Ref: 库<75>-Footnote-243112775
Ref: 库<75>-Footnote-253112819
Ref: 库<75>-Footnote-263112863
Ref: 库<75>-Footnote-273112907
Ref: 库<75>-Footnote-283112951
Ref: 库<75>-Footnote-293112995
Ref: 库<75>-Footnote-303113039
Ref: 库<75>-Footnote-313113083
Ref: 库<75>-Footnote-323113126
Ref: 库<75>-Footnote-333113170
Ref: 库<75>-Footnote-343113214
Ref: 库<75>-Footnote-353113258
Ref: 库<75>-Footnote-363113302
Ref: 库<75>-Footnote-373113346
Ref: 库<75>-Footnote-383113390
Ref: 库<75>-Footnote-393113434
Ref: 库<75>-Footnote-403113478
Ref: 库<75>-Footnote-413113522
Ref: 库<75>-Footnote-423113566
Ref: 库<75>-Footnote-433113610
Ref: 库<75>-Footnote-443113654
Ref: 库<75>-Footnote-453113698
Ref: 库<75>-Footnote-463113742
Ref: 库<75>-Footnote-473113786
Ref: 库<75>-Footnote-483113830
Ref: 库<75>-Footnote-493113874
Ref: 库<75>-Footnote-503113918
Node: IDLE<49>3113962
Ref: whatsnew/changelog id4923114058
Ref: 11b33114058
Ref: IDLE<49>-Footnote-13116421
Ref: IDLE<49>-Footnote-23116463
Ref: IDLE<49>-Footnote-33116506
Ref: IDLE<49>-Footnote-43116549
Ref: IDLE<49>-Footnote-53116592
Ref: IDLE<49>-Footnote-63116635
Ref: IDLE<49>-Footnote-73116678
Ref: IDLE<49>-Footnote-83116721
Ref: IDLE<49>-Footnote-93116764
Ref: IDLE<49>-Footnote-103116807
Ref: IDLE<49>-Footnote-113116851
Ref: IDLE<49>-Footnote-123116895
Ref: IDLE<49>-Footnote-133116939
Ref: IDLE<49>-Footnote-143116983
Ref: IDLE<49>-Footnote-153117027
Node: 文档<49>3117071
Ref: whatsnew/changelog id4933117170
Ref: 11b43117170
Ref: 文档<49>-Footnote-13118110
Ref: 文档<49>-Footnote-23118153
Ref: 文档<49>-Footnote-33118196
Ref: 文档<49>-Footnote-43118245
Ref: 文档<49>-Footnote-53118288
Ref: 文档<49>-Footnote-63118330
Ref: 文档<49>-Footnote-73118373
Ref: 文档<49>-Footnote-83118416
Node: 测试<47>3118459
Ref: whatsnew/changelog id4943118560
Ref: 11b53118560
Ref: 测试<47>-Footnote-13119435
Ref: 测试<47>-Footnote-23119478
Ref: 测试<47>-Footnote-33119521
Ref: 测试<47>-Footnote-43119564
Ref: 测试<47>-Footnote-53119607
Ref: 测试<47>-Footnote-63119650
Ref: 测试<47>-Footnote-73119693
Node: 构建<47>3119736
Ref: whatsnew/changelog id4953119838
Ref: 11b63119838
Ref: 构建<47>-Footnote-13122347
Ref: 构建<47>-Footnote-23122390
Ref: 构建<47>-Footnote-33122433
Ref: 构建<47>-Footnote-43122476
Ref: 构建<47>-Footnote-53122519
Ref: 构建<47>-Footnote-63122562
Ref: 构建<47>-Footnote-73122605
Ref: 构建<47>-Footnote-83122648
Ref: 构建<47>-Footnote-93122691
Ref: 构建<47>-Footnote-103122734
Ref: 构建<47>-Footnote-113122778
Ref: 构建<47>-Footnote-123122822
Ref: 构建<47>-Footnote-133122866
Ref: 构建<47>-Footnote-143122910
Ref: 构建<47>-Footnote-153122954
Ref: 构建<47>-Footnote-163122998
Ref: 构建<47>-Footnote-173123042
Node: Windows<47>3123086
Ref: whatsnew/changelog id4963123195
Ref: 11b73123195
Ref: Windows<47>-Footnote-13123777
Ref: Windows<47>-Footnote-23123820
Ref: Windows<47>-Footnote-33123863
Ref: Windows<47>-Footnote-43123906
Ref: Windows<47>-Footnote-53123949
Node: 工具/示例<31>3123992
Ref: whatsnew/changelog id4973124102
Ref: 11b83124102
Ref: 工具/示例<31>-Footnote-13124726
Ref: 工具/示例<31>-Footnote-23124769
Ref: 工具/示例<31>-Footnote-33124812
Ref: 工具/示例<31>-Footnote-43124855
Node: Windows<48>3124898
Ref: whatsnew/changelog id4983124988
Ref: 11b93124988
Ref: Windows<48>-Footnote-13125191
Node: Python 3 5 1 正式版3125234
Ref: whatsnew/changelog python-3-5-1-final3125355
Ref: 11ba3125355
Node: 核心与内置<62>3125517
Ref: whatsnew/changelog id4993125615
Ref: 11bb3125615
Ref: 核心与内置<62>-Footnote-13125790
Node: Windows<49>3125833
Ref: whatsnew/changelog id5003125931
Ref: 11bc3125931
Ref: Windows<49>-Footnote-13126121
Node: Python 3 5 1 rc13126164
Ref: whatsnew/changelog python-3-5-1-release-candidate-13126291
Ref: 11bd3126291
Node: 核心与内置<63>3126580
Ref: whatsnew/changelog id5013126668
Ref: 11be3126668
Ref: 核心与内置<63>-Footnote-13129791
Ref: 核心与内置<63>-Footnote-23129834
Ref: 核心与内置<63>-Footnote-33129877
Ref: 核心与内置<63>-Footnote-43129920
Ref: 核心与内置<63>-Footnote-53129963
Ref: 核心与内置<63>-Footnote-63130006
Ref: 核心与内置<63>-Footnote-73130049
Ref: 核心与内置<63>-Footnote-83130092
Ref: 核心与内置<63>-Footnote-93130135
Ref: 核心与内置<63>-Footnote-103130178
Ref: 核心与内置<63>-Footnote-113130222
Ref: 核心与内置<63>-Footnote-123130266
Ref: 核心与内置<63>-Footnote-133130310
Ref: 核心与内置<63>-Footnote-143130354
Ref: 核心与内置<63>-Footnote-153130398
Ref: 核心与内置<63>-Footnote-163130442
Ref: 核心与内置<63>-Footnote-173130486
Ref: 核心与内置<63>-Footnote-183130530
Ref: 核心与内置<63>-Footnote-193130574
Node: 库<76>3130618
Ref: whatsnew/changelog id5023130723
Ref: 11bf3130723
Ref: 库<76>-Footnote-13141080
Ref: 库<76>-Footnote-23141123
Ref: 库<76>-Footnote-33141166
Ref: 库<76>-Footnote-43141209
Ref: 库<76>-Footnote-53141251
Ref: 库<76>-Footnote-63141294
Ref: 库<76>-Footnote-73141337
Ref: 库<76>-Footnote-83141380
Ref: 库<76>-Footnote-93141423
Ref: 库<76>-Footnote-103141466
Ref: 库<76>-Footnote-113141510
Ref: 库<76>-Footnote-123141554
Ref: 库<76>-Footnote-133141598
Ref: 库<76>-Footnote-143141642
Ref: 库<76>-Footnote-153141686
Ref: 库<76>-Footnote-163141730
Ref: 库<76>-Footnote-173141774
Ref: 库<76>-Footnote-183141818
Ref: 库<76>-Footnote-193141862
Ref: 库<76>-Footnote-203141906
Ref: 库<76>-Footnote-213141950
Ref: 库<76>-Footnote-223141994
Ref: 库<76>-Footnote-233142038
Ref: 库<76>-Footnote-243142082
Ref: 库<76>-Footnote-253142126
Ref: 库<76>-Footnote-263142170
Ref: 库<76>-Footnote-273142214
Ref: 库<76>-Footnote-283142258
Ref: 库<76>-Footnote-293142302
Ref: 库<76>-Footnote-303142346
Ref: 库<76>-Footnote-313142390
Ref: 库<76>-Footnote-323142434
Ref: 库<76>-Footnote-333142478
Ref: 库<76>-Footnote-343142522
Ref: 库<76>-Footnote-353142566
Ref: 库<76>-Footnote-363142610
Ref: 库<76>-Footnote-373142654
Ref: 库<76>-Footnote-383142698
Ref: 库<76>-Footnote-393142742
Ref: 库<76>-Footnote-403142786
Ref: 库<76>-Footnote-413142830
Ref: 库<76>-Footnote-423142874
Ref: 库<76>-Footnote-433142918
Ref: 库<76>-Footnote-443142962
Ref: 库<76>-Footnote-453143006
Ref: 库<76>-Footnote-463143050
Ref: 库<76>-Footnote-473143094
Ref: 库<76>-Footnote-483143138
Ref: 库<76>-Footnote-493143182
Ref: 库<76>-Footnote-503143226
Ref: 库<76>-Footnote-513143270
Ref: 库<76>-Footnote-523143314
Ref: 库<76>-Footnote-533143358
Ref: 库<76>-Footnote-543143402
Ref: 库<76>-Footnote-553143446
Ref: 库<76>-Footnote-563143490
Ref: 库<76>-Footnote-573143534
Ref: 库<76>-Footnote-583143578
Ref: 库<76>-Footnote-593143622
Ref: 库<76>-Footnote-603143666
Ref: 库<76>-Footnote-613143710
Ref: 库<76>-Footnote-623143754
Ref: 库<76>-Footnote-633143798
Ref: 库<76>-Footnote-643143842
Ref: 库<76>-Footnote-653143886
Ref: 库<76>-Footnote-663143930
Ref: 库<76>-Footnote-673143974
Ref: 库<76>-Footnote-683144018
Ref: 库<76>-Footnote-693144062
Ref: 库<76>-Footnote-703144106
Node: IDLE<50>3144150
Ref: whatsnew/changelog id5033144246
Ref: 11c03144246
Ref: IDLE<50>-Footnote-13149199
Ref: IDLE<50>-Footnote-23149242
Ref: IDLE<50>-Footnote-33149285
Ref: IDLE<50>-Footnote-43149328
Ref: IDLE<50>-Footnote-53149371
Ref: IDLE<50>-Footnote-63149414
Ref: IDLE<50>-Footnote-73149457
Ref: IDLE<50>-Footnote-83149500
Ref: IDLE<50>-Footnote-93149543
Ref: IDLE<50>-Footnote-103149586
Ref: IDLE<50>-Footnote-113149630
Ref: IDLE<50>-Footnote-123149674
Ref: IDLE<50>-Footnote-133149718
Ref: IDLE<50>-Footnote-143149762
Ref: IDLE<50>-Footnote-153149806
Ref: IDLE<50>-Footnote-163149850
Ref: IDLE<50>-Footnote-173149894
Ref: IDLE<50>-Footnote-183149938
Ref: IDLE<50>-Footnote-193149982
Ref: IDLE<50>-Footnote-203150026
Ref: IDLE<50>-Footnote-213150070
Ref: IDLE<50>-Footnote-223150114
Ref: IDLE<50>-Footnote-233150158
Ref: IDLE<50>-Footnote-243150202
Ref: IDLE<50>-Footnote-253150246
Node: 文档<50>3150290
Ref: whatsnew/changelog id5043150389
Ref: 11c13150389
Ref: 文档<50>-Footnote-13151446
Ref: 文档<50>-Footnote-23151489
Ref: 文档<50>-Footnote-33151532
Ref: 文档<50>-Footnote-43151575
Ref: 文档<50>-Footnote-53151618
Ref: 文档<50>-Footnote-63151661
Node: 测试<48>3151704
Ref: whatsnew/changelog id5053151805
Ref: 11c23151805
Ref: 测试<48>-Footnote-13152312
Ref: 测试<48>-Footnote-23152355
Ref: 测试<48>-Footnote-33152398
Node: 构建<48>3152441
Ref: whatsnew/changelog id5063152543
Ref: 11c33152543
Ref: 构建<48>-Footnote-13152968
Ref: 构建<48>-Footnote-23153011
Ref: 构建<48>-Footnote-33153054
Node: Windows<50>3153097
Ref: whatsnew/changelog id5073153206
Ref: 11c43153206
Ref: Windows<50>-Footnote-13154479
Ref: Windows<50>-Footnote-23154522
Ref: Windows<50>-Footnote-33154565
Ref: Windows<50>-Footnote-43154608
Ref: Windows<50>-Footnote-53154651
Ref: Windows<50>-Footnote-63154694
Ref: Windows<50>-Footnote-73154737
Ref: Windows<50>-Footnote-83154780
Ref: Windows<50>-Footnote-93154823
Ref: Windows<50>-Footnote-103154866
Ref: Windows<50>-Footnote-113154910
Ref: Windows<50>-Footnote-123154954
Ref: Windows<50>-Footnote-133154998
Ref: Windows<50>-Footnote-143155042
Node: 工具/示例<32>3155086
Ref: whatsnew/changelog id5083155176
Ref: 11c53155176
Ref: 工具/示例<32>-Footnote-13155326
Node: Python 3 5 0 正式版3155369
Ref: whatsnew/changelog python-3-5-0-final3155490
Ref: 11c63155490
Node: 构建<49>3155610
Ref: whatsnew/changelog id5093155679
Ref: 11c73155679
Ref: 构建<49>-Footnote-13155855
Node: Python 3 5 0 rc43155898
Ref: whatsnew/changelog python-3-5-0-release-candidate-43156019
Ref: 11c83156019
Node: 库<77>3156146
Ref: whatsnew/changelog id5103156225
Ref: 11c93156225
Ref: 库<77>-Footnote-13156345
Node: 构建<50>3156388
Ref: whatsnew/changelog id5113156467
Ref: 11ca3156467
Ref: 构建<50>-Footnote-13156649
Node: Python 3 5 0 rc33156692
Ref: whatsnew/changelog python-3-5-0-release-candidate-33156807
Ref: 11cb3156807
Node: 核心与内置<64>3156952
Ref: whatsnew/changelog id5123157040
Ref: 11cc3157040
Ref: 核心与内置<64>-Footnote-13157399
Ref: 核心与内置<64>-Footnote-23157442
Ref: 核心与内置<64>-Footnote-33157485
Ref: 核心与内置<64>-Footnote-43157528
Node: 库<78>3157577
Ref: whatsnew/changelog id5133157665
Ref: 11cd3157665
Ref: 库<78>-Footnote-13158430
Ref: 库<78>-Footnote-23158473
Ref: 库<78>-Footnote-33158516
Ref: 库<78>-Footnote-43158559
Ref: 库<78>-Footnote-53158602
Node: Python 3 5 0 rc23158645
Ref: whatsnew/changelog python-3-5-0-release-candidate-23158760
Ref: 11ce3158760
Node: 核心与内置<65>3158905
Ref: whatsnew/changelog id5143158993
Ref: 11cf3158993
Ref: 核心与内置<65>-Footnote-13159524
Ref: 核心与内置<65>-Footnote-23159567
Ref: 核心与内置<65>-Footnote-33159610
Node: 库<79>3159653
Ref: whatsnew/changelog id5153159741
Ref: 11d03159741
Ref: 库<79>-Footnote-13160013
Ref: 库<79>-Footnote-23160056
Ref: 库<79>-Footnote-33160099
Node: Python 3 5 0 rc13160142
Ref: whatsnew/changelog python-3-5-0-release-candidate-13160260
Ref: 11d13160260
Node: 核心与内置<66>3160467
Ref: whatsnew/changelog id5163160555
Ref: 11d23160555
Ref: 核心与内置<66>-Footnote-13160724
Node: 库<80>3160767
Ref: whatsnew/changelog id5173160872
Ref: 11d33160872
Ref: 库<80>-Footnote-13162432
Ref: 库<80>-Footnote-23162475
Ref: 库<80>-Footnote-33162518
Ref: 库<80>-Footnote-43162561
Ref: 库<80>-Footnote-53162603
Ref: 库<80>-Footnote-63162646
Ref: 库<80>-Footnote-73162689
Ref: 库<80>-Footnote-83162732
Ref: 库<80>-Footnote-93162775
Ref: 库<80>-Footnote-103162818
Ref: 库<80>-Footnote-113162862
Ref: 库<80>-Footnote-123162906
Ref: 库<80>-Footnote-133162950
Ref: 库<80>-Footnote-143162994
Ref: 库<80>-Footnote-153163038
Node: IDLE<51>3163082
Ref: whatsnew/changelog id5183163178
Ref: 11d43163178
Ref: IDLE<51>-Footnote-13163923
Ref: IDLE<51>-Footnote-23163966
Ref: IDLE<51>-Footnote-33164009
Ref: IDLE<51>-Footnote-43164052
Node: 文档<51>3164095
Ref: whatsnew/changelog id5193164194
Ref: 11d53164194
Ref: 文档<51>-Footnote-13164838
Ref: 文档<51>-Footnote-23164881
Ref: 文档<51>-Footnote-33164924
Ref: 文档<51>-Footnote-43164967
Node: 测试<49>3165010
Ref: whatsnew/changelog id5203165092
Ref: 11d63165092
Ref: 测试<49>-Footnote-13165330
Node: Python 3 5 0 beta 43165373
Ref: whatsnew/changelog python-3-5-0-beta-43165494
Ref: 11d73165494
Node: 核心与内置<67>3165667
Ref: whatsnew/changelog id5213165758
Ref: 11d83165758
Ref: 核心与内置<67>-Footnote-13166553
Ref: 核心与内置<67>-Footnote-23166596
Ref: 核心与内置<67>-Footnote-33166639
Ref: 核心与内置<67>-Footnote-43166688
Ref: 核心与内置<67>-Footnote-53166731
Ref: 核心与内置<67>-Footnote-63166774
Ref: 核心与内置<67>-Footnote-73166817
Ref: 核心与内置<67>-Footnote-83166860
Node: 库<81>3166903
Ref: whatsnew/changelog id5223167013
Ref: 11d93167013
Ref: 库<81>-Footnote-13169291
Ref: 库<81>-Footnote-23169334
Ref: 库<81>-Footnote-33169377
Ref: 库<81>-Footnote-43169420
Ref: 库<81>-Footnote-53169463
Ref: 库<81>-Footnote-63169506
Ref: 库<81>-Footnote-73169549
Ref: 库<81>-Footnote-83169592
Ref: 库<81>-Footnote-93169635
Ref: 库<81>-Footnote-103169678
Ref: 库<81>-Footnote-113169722
Ref: 库<81>-Footnote-123169766
Ref: 库<81>-Footnote-133169810
Ref: 库<81>-Footnote-143169854
Ref: 库<81>-Footnote-153169898
Ref: 库<81>-Footnote-163169942
Ref: 库<81>-Footnote-173169986
Ref: 库<81>-Footnote-183170030
Ref: 库<81>-Footnote-193170074
Node: 构建<51>3170118
Ref: whatsnew/changelog id5233170200
Ref: 11da3170200
Ref: 构建<51>-Footnote-13170364
Node: Python 3 5 0 beta 33170407
Ref: whatsnew/changelog python-3-5-0-beta-33170531
Ref: 11db3170531
Node: 核心与内置<68>3170748
Ref: whatsnew/changelog id5243170839
Ref: 11dc3170839
Ref: 核心与内置<68>-Footnote-13172155
Ref: 核心与内置<68>-Footnote-23172198
Ref: 核心与内置<68>-Footnote-33172241
Ref: 核心与内置<68>-Footnote-43172284
Ref: 核心与内置<68>-Footnote-53172333
Ref: 核心与内置<68>-Footnote-63172376
Node: 库<82>3172419
Ref: whatsnew/changelog id5253172529
Ref: 11dd3172529
Ref: 库<82>-Footnote-13174472
Ref: 库<82>-Footnote-23174515
Ref: 库<82>-Footnote-33174558
Ref: 库<82>-Footnote-43174601
Ref: 库<82>-Footnote-53174644
Ref: 库<82>-Footnote-63174687
Ref: 库<82>-Footnote-73174730
Ref: 库<82>-Footnote-83174773
Ref: 库<82>-Footnote-93174816
Ref: 库<82>-Footnote-103174859
Ref: 库<82>-Footnote-113174903
Ref: 库<82>-Footnote-123174947
Ref: 库<82>-Footnote-133174991
Ref: 库<82>-Footnote-143175035
Ref: 库<82>-Footnote-153175079
Ref: 库<82>-Footnote-163175123
Ref: 库<82>-Footnote-173175167
Ref: 库<82>-Footnote-183175211
Node: 测试<50>3175255
Ref: whatsnew/changelog id5263175356
Ref: 11de3175356
Ref: 测试<50>-Footnote-13175636
Ref: 测试<50>-Footnote-23175679
Node: 文档<52>3175722
Ref: whatsnew/changelog id5273175826
Ref: 11df3175826
Ref: 文档<52>-Footnote-13176148
Ref: 文档<52>-Footnote-23176191
Node: 构建<52>3176234
Ref: whatsnew/changelog id5283176319
Ref: 11e03176319
Ref: 构建<52>-Footnote-13176483
Node: Python 3 5 0 beta 23176526
Ref: whatsnew/changelog python-3-5-0-beta-23176650
Ref: 11e13176650
Node: 核心与内置<69>3176801
Ref: whatsnew/changelog id5293176892
Ref: 11e23176892
Ref: 核心与内置<69>-Footnote-13177634
Ref: 核心与内置<69>-Footnote-23177677
Ref: 核心与内置<69>-Footnote-33177720
Ref: 核心与内置<69>-Footnote-43177763
Ref: 核心与内置<69>-Footnote-53177806
Node: 库<83>3177849
Ref: whatsnew/changelog id5303177940
Ref: 11e33177940
Ref: 库<83>-Footnote-13178636
Ref: 库<83>-Footnote-23178679
Ref: 库<83>-Footnote-33178722
Ref: 库<83>-Footnote-43178771
Ref: 库<83>-Footnote-53178813
Ref: 库<83>-Footnote-63178856
Ref: 库<83>-Footnote-73178899
Node: Python 3 5 0 beta 13178942
Ref: whatsnew/changelog python-3-5-0-beta-13179067
Ref: 11e43179067
Node: 核心与内置<70>3179316
Ref: whatsnew/changelog id5313179407
Ref: 11e53179407
Ref: 核心与内置<70>-Footnote-13181269
Ref: 核心与内置<70>-Footnote-23181312
Ref: 核心与内置<70>-Footnote-33181355
Ref: 核心与内置<70>-Footnote-43181398
Ref: 核心与内置<70>-Footnote-53181441
Ref: 核心与内置<70>-Footnote-63181484
Ref: 核心与内置<70>-Footnote-73181527
Ref: 核心与内置<70>-Footnote-83181570
Ref: 核心与内置<70>-Footnote-93181613
Ref: 核心与内置<70>-Footnote-103181656
Ref: 核心与内置<70>-Footnote-113181699
Ref: 核心与内置<70>-Footnote-123181743
Ref: 核心与内置<70>-Footnote-133181787
Ref: 核心与内置<70>-Footnote-143181831
Ref: 核心与内置<70>-Footnote-153181875
Ref: 核心与内置<70>-Footnote-163181919
Ref: 核心与内置<70>-Footnote-173181963
Ref: 核心与内置<70>-Footnote-183182006
Ref: 核心与内置<70>-Footnote-193182050
Node: 库<84>3182094
Ref: whatsnew/changelog id5323182202
Ref: 11e63182202
Ref: 库<84>-Footnote-13189849
Ref: 库<84>-Footnote-23189892
Ref: 库<84>-Footnote-33189935
Ref: 库<84>-Footnote-43189978
Ref: 库<84>-Footnote-53190021
Ref: 库<84>-Footnote-63190064
Ref: 库<84>-Footnote-73190107
Ref: 库<84>-Footnote-83190150
Ref: 库<84>-Footnote-93190193
Ref: 库<84>-Footnote-103190236
Ref: 库<84>-Footnote-113190279
Ref: 库<84>-Footnote-123190323
Ref: 库<84>-Footnote-133190367
Ref: 库<84>-Footnote-143190411
Ref: 库<84>-Footnote-153190454
Ref: 库<84>-Footnote-163190498
Ref: 库<84>-Footnote-173190542
Ref: 库<84>-Footnote-183190586
Ref: 库<84>-Footnote-193190630
Ref: 库<84>-Footnote-203190674
Ref: 库<84>-Footnote-213190718
Ref: 库<84>-Footnote-223190762
Ref: 库<84>-Footnote-233190806
Ref: 库<84>-Footnote-243190850
Ref: 库<84>-Footnote-253190894
Ref: 库<84>-Footnote-263190937
Ref: 库<84>-Footnote-273190981
Ref: 库<84>-Footnote-283191025
Ref: 库<84>-Footnote-293191069
Ref: 库<84>-Footnote-303191113
Ref: 库<84>-Footnote-313191157
Ref: 库<84>-Footnote-323191201
Ref: 库<84>-Footnote-333191245
Ref: 库<84>-Footnote-343191289
Ref: 库<84>-Footnote-353191333
Ref: 库<84>-Footnote-363191377
Ref: 库<84>-Footnote-373191421
Ref: 库<84>-Footnote-383191465
Ref: 库<84>-Footnote-393191509
Ref: 库<84>-Footnote-403191553
Ref: 库<84>-Footnote-413191597
Ref: 库<84>-Footnote-423191640
Ref: 库<84>-Footnote-433191684
Ref: 库<84>-Footnote-443191728
Ref: 库<84>-Footnote-453191772
Ref: 库<84>-Footnote-463191816
Ref: 库<84>-Footnote-473191860
Ref: 库<84>-Footnote-483191904
Ref: 库<84>-Footnote-493191948
Ref: 库<84>-Footnote-503191992
Ref: 库<84>-Footnote-513192036
Ref: 库<84>-Footnote-523192080
Ref: 库<84>-Footnote-533192124
Ref: 库<84>-Footnote-543192168
Ref: 库<84>-Footnote-553192212
Ref: 库<84>-Footnote-563192256
Node: IDLE<52>3192300
Ref: whatsnew/changelog id5333192399
Ref: 11e73192399
Ref: IDLE<52>-Footnote-13192566
Node: 测试<51>3192609
Ref: whatsnew/changelog id5343192711
Ref: 11e83192711
Ref: 测试<51>-Footnote-13193007
Ref: 测试<51>-Footnote-23193050
Node: 文档<53>3193092
Ref: whatsnew/changelog id5353193203
Ref: 11e93193203
Ref: 文档<53>-Footnote-13193592
Ref: 文档<53>-Footnote-23193635
Ref: 文档<53>-Footnote-33193678
Node: 工具/示例<33>3193721
Ref: whatsnew/changelog id5363193813
Ref: 11ea3193813
Ref: 工具/示例<33>-Footnote-13194326
Ref: 工具/示例<33>-Footnote-23194369
Ref: 工具/示例<33>-Footnote-33194412
Ref: 工具/示例<33>-Footnote-43194455
Node: Python 3 5 0 alpha 43194498
Ref: whatsnew/changelog python-3-5-0-alpha-43194624
Ref: 11eb3194624
Node: 核心与内置<71>3194877
Ref: whatsnew/changelog id5373194969
Ref: 11ec3194969
Ref: 核心与内置<71>-Footnote-13196327
Ref: 核心与内置<71>-Footnote-23196370
Ref: 核心与内置<71>-Footnote-33196419
Ref: 核心与内置<71>-Footnote-43196462
Ref: 核心与内置<71>-Footnote-53196505
Ref: 核心与内置<71>-Footnote-63196554
Ref: 核心与内置<71>-Footnote-73196597
Ref: 核心与内置<71>-Footnote-83196640
Ref: 核心与内置<71>-Footnote-93196683
Ref: 核心与内置<71>-Footnote-103196726
Ref: 核心与内置<71>-Footnote-113196770
Node: 库<85>3196814
Ref: whatsnew/changelog id5383196925
Ref: 11ed3196925
Ref: 库<85>-Footnote-13203627
Ref: 库<85>-Footnote-23203670
Ref: 库<85>-Footnote-33203713
Ref: 库<85>-Footnote-43203755
Ref: 库<85>-Footnote-53203798
Ref: 库<85>-Footnote-63203841
Ref: 库<85>-Footnote-73203883
Ref: 库<85>-Footnote-83203926
Ref: 库<85>-Footnote-93203969
Ref: 库<85>-Footnote-103204012
Ref: 库<85>-Footnote-113204056
Ref: 库<85>-Footnote-123204100
Ref: 库<85>-Footnote-133204144
Ref: 库<85>-Footnote-143204188
Ref: 库<85>-Footnote-153204232
Ref: 库<85>-Footnote-163204276
Ref: 库<85>-Footnote-173204320
Ref: 库<85>-Footnote-183204364
Ref: 库<85>-Footnote-193204408
Ref: 库<85>-Footnote-203204452
Ref: 库<85>-Footnote-213204496
Ref: 库<85>-Footnote-223204540
Ref: 库<85>-Footnote-233204584
Ref: 库<85>-Footnote-243204628
Ref: 库<85>-Footnote-253204672
Ref: 库<85>-Footnote-263204716
Ref: 库<85>-Footnote-273204760
Ref: 库<85>-Footnote-283204804
Ref: 库<85>-Footnote-293204848
Ref: 库<85>-Footnote-303204892
Ref: 库<85>-Footnote-313204935
Ref: 库<85>-Footnote-323204979
Ref: 库<85>-Footnote-333205023
Ref: 库<85>-Footnote-343205067
Ref: 库<85>-Footnote-353205111
Ref: 库<85>-Footnote-363205155
Ref: 库<85>-Footnote-373205199
Ref: 库<85>-Footnote-383205243
Ref: 库<85>-Footnote-393205287
Ref: 库<85>-Footnote-403205331
Ref: 库<85>-Footnote-413205375
Ref: 库<85>-Footnote-423205419
Ref: 库<85>-Footnote-433205469
Ref: 库<85>-Footnote-443205513
Ref: 库<85>-Footnote-453205557
Ref: 库<85>-Footnote-463205601
Ref: 库<85>-Footnote-473205645
Ref: 库<85>-Footnote-483205689
Node: 构建<53>3205733
Ref: whatsnew/changelog id5393205835
Ref: 11ee3205835
Ref: 构建<53>-Footnote-13206110
Ref: 构建<53>-Footnote-23206153
Node: 测试<52>3206196
Ref: whatsnew/changelog id5403206308
Ref: 11ef3206308
Ref: 测试<52>-Footnote-13206607
Ref: 测试<52>-Footnote-23206650
Node: 工具/示例<34>3206693
Ref: whatsnew/changelog id5413206804
Ref: 11f03206804
Ref: 工具/示例<34>-Footnote-13207832
Ref: 工具/示例<34>-Footnote-23207875
Ref: 工具/示例<34>-Footnote-33207918
Ref: 工具/示例<34>-Footnote-43207961
Ref: 工具/示例<34>-Footnote-53208004
Ref: 工具/示例<34>-Footnote-63208047
Node: C API<36>3208090
Ref: whatsnew/changelog id5423208182
Ref: 11f13208182
Ref: C API<36>-Footnote-13208335
Node: Python 3 5 0 alpha 33208378
Ref: whatsnew/changelog python-3-5-0-alpha-33208505
Ref: 11f23208505
Node: 核心与内置<72>3208738
Ref: whatsnew/changelog id5433208830
Ref: 11f33208830
Ref: 核心与内置<72>-Footnote-13209615
Ref: 核心与内置<72>-Footnote-23209658
Ref: 核心与内置<72>-Footnote-33209701
Ref: 核心与内置<72>-Footnote-43209744
Ref: 核心与内置<72>-Footnote-53209787
Ref: 核心与内置<72>-Footnote-63209830
Node: 库<86>3209873
Ref: whatsnew/changelog id5443209984
Ref: 11f43209984
Ref: 库<86>-Footnote-13216389
Ref: 库<86>-Footnote-23216432
Ref: 库<86>-Footnote-33216475
Ref: 库<86>-Footnote-43216518
Ref: 库<86>-Footnote-53216561
Ref: 库<86>-Footnote-63216604
Ref: 库<86>-Footnote-73216647
Ref: 库<86>-Footnote-83216690
Ref: 库<86>-Footnote-93216733
Ref: 库<86>-Footnote-103216776
Ref: 库<86>-Footnote-113216820
Ref: 库<86>-Footnote-123216864
Ref: 库<86>-Footnote-133216908
Ref: 库<86>-Footnote-143216952
Ref: 库<86>-Footnote-153216995
Ref: 库<86>-Footnote-163217039
Ref: 库<86>-Footnote-173217083
Ref: 库<86>-Footnote-183217127
Ref: 库<86>-Footnote-193217171
Ref: 库<86>-Footnote-203217215
Ref: 库<86>-Footnote-213217259
Ref: 库<86>-Footnote-223217303
Ref: 库<86>-Footnote-233217347
Ref: 库<86>-Footnote-243217391
Ref: 库<86>-Footnote-253217435
Ref: 库<86>-Footnote-263217479
Ref: 库<86>-Footnote-273217523
Ref: 库<86>-Footnote-283217567
Ref: 库<86>-Footnote-293217611
Ref: 库<86>-Footnote-303217655
Ref: 库<86>-Footnote-313217698
Ref: 库<86>-Footnote-323217742
Ref: 库<86>-Footnote-333217786
Ref: 库<86>-Footnote-343217830
Ref: 库<86>-Footnote-353217873
Ref: 库<86>-Footnote-363217917
Ref: 库<86>-Footnote-373217961
Ref: 库<86>-Footnote-383218005
Ref: 库<86>-Footnote-393218049
Ref: 库<86>-Footnote-403218093
Ref: 库<86>-Footnote-413218137
Ref: 库<86>-Footnote-423218181
Node: 构建<54>3218225
Ref: whatsnew/changelog id5453218327
Ref: 11f53218327
Ref: 构建<54>-Footnote-13218470
Node: 测试<53>3218513
Ref: whatsnew/changelog id5463218625
Ref: 11f63218625
Ref: 测试<53>-Footnote-13218848
Ref: 测试<53>-Footnote-23218891
Node: 工具/示例<35>3218934
Ref: whatsnew/changelog id5473219027
Ref: 11f73219027
Ref: 工具/示例<35>-Footnote-13219294
Node: Python 3 5 0 alpha 23219337
Ref: whatsnew/changelog python-3-5-0-alpha-23219464
Ref: 11f83219464
Node: 核心与内置<73>3219683
Ref: whatsnew/changelog id5483219775
Ref: 11f93219775
Ref: 核心与内置<73>-Footnote-13220062
Node: 库<87>3220105
Ref: whatsnew/changelog id5493220216
Ref: 11fa3220216
Ref: 库<87>-Footnote-13224518
Ref: 库<87>-Footnote-23224561
Ref: 库<87>-Footnote-33224610
Ref: 库<87>-Footnote-43224653
Ref: 库<87>-Footnote-53224696
Ref: 库<87>-Footnote-63224739
Ref: 库<87>-Footnote-73224782
Ref: 库<87>-Footnote-83224825
Ref: 库<87>-Footnote-93224868
Ref: 库<87>-Footnote-103224910
Ref: 库<87>-Footnote-113224954
Ref: 库<87>-Footnote-123224998
Ref: 库<87>-Footnote-133225042
Ref: 库<87>-Footnote-143225086
Ref: 库<87>-Footnote-153225130
Ref: 库<87>-Footnote-163225174
Ref: 库<87>-Footnote-173225217
Ref: 库<87>-Footnote-183225262
Ref: 库<87>-Footnote-193225305
Ref: 库<87>-Footnote-203225349
Ref: 库<87>-Footnote-213225392
Ref: 库<87>-Footnote-223225436
Ref: 库<87>-Footnote-233225480
Ref: 库<87>-Footnote-243225524
Ref: 库<87>-Footnote-253225568
Ref: 库<87>-Footnote-263225612
Ref: 库<87>-Footnote-273225656
Ref: 库<87>-Footnote-283225700
Ref: 库<87>-Footnote-293225744
Ref: 库<87>-Footnote-303225788
Ref: 库<87>-Footnote-313225832
Ref: 库<87>-Footnote-323225876
Ref: 库<87>-Footnote-333225920
Ref: 库<87>-Footnote-343225964
Ref: 库<87>-Footnote-353226008
Ref: 库<87>-Footnote-363226052
Ref: 库<87>-Footnote-373226096
Node: 构建<55>3226140
Ref: whatsnew/changelog id5503226241
Ref: 11fb3226241
Ref: 构建<55>-Footnote-13226498
Ref: 构建<55>-Footnote-23226541
Node: C API<37>3226584
Ref: whatsnew/changelog id5513226689
Ref: 11fc3226689
Ref: C API<37>-Footnote-13226869
Node: Windows<51>3226912
Ref: whatsnew/changelog id5523226998
Ref: 11fd3226998
Ref: Windows<51>-Footnote-13227293
Ref: Windows<51>-Footnote-23227336
Ref: Windows<51>-Footnote-33227385
Node: Python 3 5 0 alpha 13227428
Ref: whatsnew/changelog python-3-5-0-alpha-13227526
Ref: 11fe3227526
Node: 核心与内置<74>3227843
Ref: whatsnew/changelog id5533227935
Ref: 11ff3227935
Ref: 核心与内置<74>-Footnote-13237817
Ref: 核心与内置<74>-Footnote-23237860
Ref: 核心与内置<74>-Footnote-33237903
Ref: 核心与内置<74>-Footnote-43237946
Ref: 核心与内置<74>-Footnote-53237989
Ref: 核心与内置<74>-Footnote-63238032
Ref: 核心与内置<74>-Footnote-73238075
Ref: 核心与内置<74>-Footnote-83238118
Ref: 核心与内置<74>-Footnote-93238161
Ref: 核心与内置<74>-Footnote-103238204
Ref: 核心与内置<74>-Footnote-113238248
Ref: 核心与内置<74>-Footnote-123238292
Ref: 核心与内置<74>-Footnote-133238336
Ref: 核心与内置<74>-Footnote-143238380
Ref: 核心与内置<74>-Footnote-153238424
Ref: 核心与内置<74>-Footnote-163238468
Ref: 核心与内置<74>-Footnote-173238512
Ref: 核心与内置<74>-Footnote-183238556
Ref: 核心与内置<74>-Footnote-193238600
Ref: 核心与内置<74>-Footnote-203238644
Ref: 核心与内置<74>-Footnote-213238688
Ref: 核心与内置<74>-Footnote-223238732
Ref: 核心与内置<74>-Footnote-233238776
Ref: 核心与内置<74>-Footnote-243238820
Ref: 核心与内置<74>-Footnote-253238864
Ref: 核心与内置<74>-Footnote-263238908
Ref: 核心与内置<74>-Footnote-273238952
Ref: 核心与内置<74>-Footnote-283238996
Ref: 核心与内置<74>-Footnote-293239040
Ref: 核心与内置<74>-Footnote-303239084
Ref: 核心与内置<74>-Footnote-313239128
Ref: 核心与内置<74>-Footnote-323239172
Ref: 核心与内置<74>-Footnote-333239216
Ref: 核心与内置<74>-Footnote-343239262
Ref: 核心与内置<74>-Footnote-353239306
Ref: 核心与内置<74>-Footnote-363239350
Ref: 核心与内置<74>-Footnote-373239394
Ref: 核心与内置<74>-Footnote-383239438
Ref: 核心与内置<74>-Footnote-393239482
Ref: 核心与内置<74>-Footnote-403239526
Ref: 核心与内置<74>-Footnote-413239570
Ref: 核心与内置<74>-Footnote-423239614
Ref: 核心与内置<74>-Footnote-433239658
Ref: 核心与内置<74>-Footnote-443239702
Ref: 核心与内置<74>-Footnote-453239746
Ref: 核心与内置<74>-Footnote-463239790
Ref: 核心与内置<74>-Footnote-473239834
Ref: 核心与内置<74>-Footnote-483239878
Ref: 核心与内置<74>-Footnote-493239922
Ref: 核心与内置<74>-Footnote-503239966
Ref: 核心与内置<74>-Footnote-513240010
Ref: 核心与内置<74>-Footnote-523240054
Ref: 核心与内置<74>-Footnote-533240098
Ref: 核心与内置<74>-Footnote-543240142
Ref: 核心与内置<74>-Footnote-553240186
Ref: 核心与内置<74>-Footnote-563240230
Ref: 核心与内置<74>-Footnote-573240274
Ref: 核心与内置<74>-Footnote-583240318
Ref: 核心与内置<74>-Footnote-593240362
Ref: 核心与内置<74>-Footnote-603240406
Ref: 核心与内置<74>-Footnote-613240450
Ref: 核心与内置<74>-Footnote-623240494
Ref: 核心与内置<74>-Footnote-633240538
Ref: 核心与内置<74>-Footnote-643240582
Ref: 核心与内置<74>-Footnote-653240626
Ref: 核心与内置<74>-Footnote-663240670
Ref: 核心与内置<74>-Footnote-673240713
Ref: 核心与内置<74>-Footnote-683240757
Ref: 核心与内置<74>-Footnote-693240801
Ref: 核心与内置<74>-Footnote-703240845
Ref: 核心与内置<74>-Footnote-713240889
Ref: 核心与内置<74>-Footnote-723240933
Ref: 核心与内置<74>-Footnote-733240976
Node: 库<88>3241020
Ref: whatsnew/changelog id5543241129
Ref: 12003241129
Ref: 库<88>-Footnote-13293504
Ref: 库<88>-Footnote-23293547
Ref: 库<88>-Footnote-33293590
Ref: 库<88>-Footnote-43293633
Ref: 库<88>-Footnote-53293676
Ref: 库<88>-Footnote-63293719
Ref: 库<88>-Footnote-73293762
Ref: 库<88>-Footnote-83293805
Ref: 库<88>-Footnote-93293848
Ref: 库<88>-Footnote-103293891
Ref: 库<88>-Footnote-113293935
Ref: 库<88>-Footnote-123293979
Ref: 库<88>-Footnote-133294023
Ref: 库<88>-Footnote-143294067
Ref: 库<88>-Footnote-153294111
Ref: 库<88>-Footnote-163294155
Ref: 库<88>-Footnote-173294199
Ref: 库<88>-Footnote-183294243
Ref: 库<88>-Footnote-193294287
Ref: 库<88>-Footnote-203294331
Ref: 库<88>-Footnote-213294375
Ref: 库<88>-Footnote-223294419
Ref: 库<88>-Footnote-233294463
Ref: 库<88>-Footnote-243294507
Ref: 库<88>-Footnote-253294551
Ref: 库<88>-Footnote-263294595
Ref: 库<88>-Footnote-273294639
Ref: 库<88>-Footnote-283294683
Ref: 库<88>-Footnote-293294727
Ref: 库<88>-Footnote-303294771
Ref: 库<88>-Footnote-313294815
Ref: 库<88>-Footnote-323294859
Ref: 库<88>-Footnote-333294903
Ref: 库<88>-Footnote-343294947
Ref: 库<88>-Footnote-353294991
Ref: 库<88>-Footnote-363295035
Ref: 库<88>-Footnote-373295079
Ref: 库<88>-Footnote-383295123
Ref: 库<88>-Footnote-393295167
Ref: 库<88>-Footnote-403295211
Ref: 库<88>-Footnote-413295255
Ref: 库<88>-Footnote-423295299
Ref: 库<88>-Footnote-433295343
Ref: 库<88>-Footnote-443295387
Ref: 库<88>-Footnote-453295431
Ref: 库<88>-Footnote-463295475
Ref: 库<88>-Footnote-473295519
Ref: 库<88>-Footnote-483295563
Ref: 库<88>-Footnote-493295607
Ref: 库<88>-Footnote-503295651
Ref: 库<88>-Footnote-513295695
Ref: 库<88>-Footnote-523295739
Ref: 库<88>-Footnote-533295783
Ref: 库<88>-Footnote-543295827
Ref: 库<88>-Footnote-553295871
Ref: 库<88>-Footnote-563295917
Ref: 库<88>-Footnote-573295961
Ref: 库<88>-Footnote-583296005
Ref: 库<88>-Footnote-593296049
Ref: 库<88>-Footnote-603296093
Ref: 库<88>-Footnote-613296137
Ref: 库<88>-Footnote-623296181
Ref: 库<88>-Footnote-633296225
Ref: 库<88>-Footnote-643296269
Ref: 库<88>-Footnote-653296313
Ref: 库<88>-Footnote-663296357
Ref: 库<88>-Footnote-673296401
Ref: 库<88>-Footnote-683296445
Ref: 库<88>-Footnote-693296489
Ref: 库<88>-Footnote-703296533
Ref: 库<88>-Footnote-713296577
Ref: 库<88>-Footnote-723296621
Ref: 库<88>-Footnote-733296665
Ref: 库<88>-Footnote-743296709
Ref: 库<88>-Footnote-753296753
Ref: 库<88>-Footnote-763296797
Ref: 库<88>-Footnote-773296841
Ref: 库<88>-Footnote-783296885
Ref: 库<88>-Footnote-793296929
Ref: 库<88>-Footnote-803296973
Ref: 库<88>-Footnote-813297017
Ref: 库<88>-Footnote-823297061
Ref: 库<88>-Footnote-833297105
Ref: 库<88>-Footnote-843297149
Ref: 库<88>-Footnote-853297193
Ref: 库<88>-Footnote-863297237
Ref: 库<88>-Footnote-873297281
Ref: 库<88>-Footnote-883297325
Ref: 库<88>-Footnote-893297369
Ref: 库<88>-Footnote-903297413
Ref: 库<88>-Footnote-913297457
Ref: 库<88>-Footnote-923297501
Ref: 库<88>-Footnote-933297545
Ref: 库<88>-Footnote-943297589
Ref: 库<88>-Footnote-953297633
Ref: 库<88>-Footnote-963297676
Ref: 库<88>-Footnote-973297720
Ref: 库<88>-Footnote-983297764
Ref: 库<88>-Footnote-993297808
Ref: 库<88>-Footnote-1003297851
Ref: 库<88>-Footnote-1013297896
Ref: 库<88>-Footnote-1023297941
Ref: 库<88>-Footnote-1033297986
Ref: 库<88>-Footnote-1043298031
Ref: 库<88>-Footnote-1053298076
Ref: 库<88>-Footnote-1063298121
Ref: 库<88>-Footnote-1073298165
Ref: 库<88>-Footnote-1083298209
Ref: 库<88>-Footnote-1093298254
Ref: 库<88>-Footnote-1103298299
Ref: 库<88>-Footnote-1113298344
Ref: 库<88>-Footnote-1123298389
Ref: 库<88>-Footnote-1133298434
Ref: 库<88>-Footnote-1143298479
Ref: 库<88>-Footnote-1153298524
Ref: 库<88>-Footnote-1163298569
Ref: 库<88>-Footnote-1173298614
Ref: 库<88>-Footnote-1183298659
Ref: 库<88>-Footnote-1193298704
Ref: 库<88>-Footnote-1203298749
Ref: 库<88>-Footnote-1213298796
Ref: 库<88>-Footnote-1223298841
Ref: 库<88>-Footnote-1233298886
Ref: 库<88>-Footnote-1243298931
Ref: 库<88>-Footnote-1253298976
Ref: 库<88>-Footnote-1263299021
Ref: 库<88>-Footnote-1273299066
Ref: 库<88>-Footnote-1283299111
Ref: 库<88>-Footnote-1293299156
Ref: 库<88>-Footnote-1303299201
Ref: 库<88>-Footnote-1313299246
Ref: 库<88>-Footnote-1323299291
Ref: 库<88>-Footnote-1333299336
Ref: 库<88>-Footnote-1343299381
Ref: 库<88>-Footnote-1353299426
Ref: 库<88>-Footnote-1363299471
Ref: 库<88>-Footnote-1373299516
Ref: 库<88>-Footnote-1383299561
Ref: 库<88>-Footnote-1393299606
Ref: 库<88>-Footnote-1403299651
Ref: 库<88>-Footnote-1413299696
Ref: 库<88>-Footnote-1423299740
Ref: 库<88>-Footnote-1433299784
Ref: 库<88>-Footnote-1443299829
Ref: 库<88>-Footnote-1453299874
Ref: 库<88>-Footnote-1463299919
Ref: 库<88>-Footnote-1473299964
Ref: 库<88>-Footnote-1483300009
Ref: 库<88>-Footnote-1493300054
Ref: 库<88>-Footnote-1503300099
Ref: 库<88>-Footnote-1513300144
Ref: 库<88>-Footnote-1523300189
Ref: 库<88>-Footnote-1533300234
Ref: 库<88>-Footnote-1543300279
Ref: 库<88>-Footnote-1553300324
Ref: 库<88>-Footnote-1563300369
Ref: 库<88>-Footnote-1573300413
Ref: 库<88>-Footnote-1583300458
Ref: 库<88>-Footnote-1593300503
Ref: 库<88>-Footnote-1603300548
Ref: 库<88>-Footnote-1613300593
Ref: 库<88>-Footnote-1623300638
Ref: 库<88>-Footnote-1633300683
Ref: 库<88>-Footnote-1643300728
Ref: 库<88>-Footnote-1653300773
Ref: 库<88>-Footnote-1663300818
Ref: 库<88>-Footnote-1673300863
Ref: 库<88>-Footnote-1683300908
Ref: 库<88>-Footnote-1693300953
Ref: 库<88>-Footnote-1703300998
Ref: 库<88>-Footnote-1713301043
Ref: 库<88>-Footnote-1723301088
Ref: 库<88>-Footnote-1733301133
Ref: 库<88>-Footnote-1743301178
Ref: 库<88>-Footnote-1753301223
Ref: 库<88>-Footnote-1763301268
Ref: 库<88>-Footnote-1773301313
Ref: 库<88>-Footnote-1783301358
Ref: 库<88>-Footnote-1793301403
Ref: 库<88>-Footnote-1803301448
Ref: 库<88>-Footnote-1813301493
Ref: 库<88>-Footnote-1823301538
Ref: 库<88>-Footnote-1833301583
Ref: 库<88>-Footnote-1843301628
Ref: 库<88>-Footnote-1853301673
Ref: 库<88>-Footnote-1863301718
Ref: 库<88>-Footnote-1873301763
Ref: 库<88>-Footnote-1883301807
Ref: 库<88>-Footnote-1893301852
Ref: 库<88>-Footnote-1903301897
Ref: 库<88>-Footnote-1913301942
Ref: 库<88>-Footnote-1923301987
Ref: 库<88>-Footnote-1933302032
Ref: 库<88>-Footnote-1943302077
Ref: 库<88>-Footnote-1953302122
Ref: 库<88>-Footnote-1963302166
Ref: 库<88>-Footnote-1973302211
Ref: 库<88>-Footnote-1983302256
Ref: 库<88>-Footnote-1993302301
Ref: 库<88>-Footnote-2003302346
Ref: 库<88>-Footnote-2013302391
Ref: 库<88>-Footnote-2023302436
Ref: 库<88>-Footnote-2033302480
Ref: 库<88>-Footnote-2043302525
Ref: 库<88>-Footnote-2053302570
Ref: 库<88>-Footnote-2063302615
Ref: 库<88>-Footnote-2073302660
Ref: 库<88>-Footnote-2083302705
Ref: 库<88>-Footnote-2093302750
Ref: 库<88>-Footnote-2103302795
Ref: 库<88>-Footnote-2113302840
Ref: 库<88>-Footnote-2123302885
Ref: 库<88>-Footnote-2133302930
Ref: 库<88>-Footnote-2143302975
Ref: 库<88>-Footnote-2153303020
Ref: 库<88>-Footnote-2163303065
Ref: 库<88>-Footnote-2173303110
Ref: 库<88>-Footnote-2183303155
Ref: 库<88>-Footnote-2193303200
Ref: 库<88>-Footnote-2203303245
Ref: 库<88>-Footnote-2213303290
Ref: 库<88>-Footnote-2223303335
Ref: 库<88>-Footnote-2233303380
Ref: 库<88>-Footnote-2243303424
Ref: 库<88>-Footnote-2253303468
Ref: 库<88>-Footnote-2263303513
Ref: 库<88>-Footnote-2273303558
Ref: 库<88>-Footnote-2283303603
Ref: 库<88>-Footnote-2293303648
Ref: 库<88>-Footnote-2303303693
Ref: 库<88>-Footnote-2313303738
Ref: 库<88>-Footnote-2323303783
Ref: 库<88>-Footnote-2333303828
Ref: 库<88>-Footnote-2343303873
Ref: 库<88>-Footnote-2353303918
Ref: 库<88>-Footnote-2363303963
Ref: 库<88>-Footnote-2373304008
Ref: 库<88>-Footnote-2383304053
Ref: 库<88>-Footnote-2393304098
Ref: 库<88>-Footnote-2403304143
Ref: 库<88>-Footnote-2413304188
Ref: 库<88>-Footnote-2423304233
Ref: 库<88>-Footnote-2433304278
Ref: 库<88>-Footnote-2443304323
Ref: 库<88>-Footnote-2453304367
Ref: 库<88>-Footnote-2463304412
Ref: 库<88>-Footnote-2473304457
Ref: 库<88>-Footnote-2483304502
Ref: 库<88>-Footnote-2493304547
Ref: 库<88>-Footnote-2503304592
Ref: 库<88>-Footnote-2513304637
Ref: 库<88>-Footnote-2523304682
Ref: 库<88>-Footnote-2533304727
Ref: 库<88>-Footnote-2543304772
Ref: 库<88>-Footnote-2553304817
Ref: 库<88>-Footnote-2563304862
Ref: 库<88>-Footnote-2573304907
Ref: 库<88>-Footnote-2583304952
Ref: 库<88>-Footnote-2593304997
Ref: 库<88>-Footnote-2603305042
Ref: 库<88>-Footnote-2613305087
Ref: 库<88>-Footnote-2623305132
Ref: 库<88>-Footnote-2633305177
Ref: 库<88>-Footnote-2643305222
Ref: 库<88>-Footnote-2653305267
Ref: 库<88>-Footnote-2663305312
Ref: 库<88>-Footnote-2673305357
Ref: 库<88>-Footnote-2683305402
Ref: 库<88>-Footnote-2693305447
Ref: 库<88>-Footnote-2703305492
Ref: 库<88>-Footnote-2713305537
Ref: 库<88>-Footnote-2723305582
Ref: 库<88>-Footnote-2733305627
Ref: 库<88>-Footnote-2743305672
Ref: 库<88>-Footnote-2753305717
Ref: 库<88>-Footnote-2763305762
Ref: 库<88>-Footnote-2773305806
Ref: 库<88>-Footnote-2783305851
Ref: 库<88>-Footnote-2793305896
Ref: 库<88>-Footnote-2803305941
Ref: 库<88>-Footnote-2813305986
Ref: 库<88>-Footnote-2823306031
Ref: 库<88>-Footnote-2833306076
Ref: 库<88>-Footnote-2843306121
Ref: 库<88>-Footnote-2853306166
Ref: 库<88>-Footnote-2863306211
Ref: 库<88>-Footnote-2873306256
Ref: 库<88>-Footnote-2883306301
Ref: 库<88>-Footnote-2893306352
Ref: 库<88>-Footnote-2903306397
Ref: 库<88>-Footnote-2913306442
Ref: 库<88>-Footnote-2923306487
Ref: 库<88>-Footnote-2933306532
Ref: 库<88>-Footnote-2943306577
Ref: 库<88>-Footnote-2953306622
Ref: 库<88>-Footnote-2963306667
Ref: 库<88>-Footnote-2973306712
Ref: 库<88>-Footnote-2983306757
Ref: 库<88>-Footnote-2993306802
Ref: 库<88>-Footnote-3003306847
Ref: 库<88>-Footnote-3013306892
Ref: 库<88>-Footnote-3023306937
Ref: 库<88>-Footnote-3033306982
Ref: 库<88>-Footnote-3043307027
Ref: 库<88>-Footnote-3053307072
Ref: 库<88>-Footnote-3063307117
Ref: 库<88>-Footnote-3073307162
Ref: 库<88>-Footnote-3083307207
Ref: 库<88>-Footnote-3093307252
Ref: 库<88>-Footnote-3103307297
Ref: 库<88>-Footnote-3113307342
Ref: 库<88>-Footnote-3123307387
Ref: 库<88>-Footnote-3133307432
Ref: 库<88>-Footnote-3143307477
Ref: 库<88>-Footnote-3153307521
Ref: 库<88>-Footnote-3163307566
Ref: 库<88>-Footnote-3173307611
Ref: 库<88>-Footnote-3183307656
Ref: 库<88>-Footnote-3193307701
Ref: 库<88>-Footnote-3203307746
Ref: 库<88>-Footnote-3213307791
Ref: 库<88>-Footnote-3223307836
Ref: 库<88>-Footnote-3233307881
Ref: 库<88>-Footnote-3243307926
Ref: 库<88>-Footnote-3253307971
Ref: 库<88>-Footnote-3263308016
Ref: 库<88>-Footnote-3273308061
Ref: 库<88>-Footnote-3283308106
Ref: 库<88>-Footnote-3293308151
Ref: 库<88>-Footnote-3303308196
Ref: 库<88>-Footnote-3313308241
Ref: 库<88>-Footnote-3323308286
Ref: 库<88>-Footnote-3333308331
Ref: 库<88>-Footnote-3343308376
Ref: 库<88>-Footnote-3353308420
Ref: 库<88>-Footnote-3363308465
Ref: 库<88>-Footnote-3373308510
Ref: 库<88>-Footnote-3383308555
Ref: 库<88>-Footnote-3393308600
Ref: 库<88>-Footnote-3403308645
Ref: 库<88>-Footnote-3413308690
Ref: 库<88>-Footnote-3423308735
Ref: 库<88>-Footnote-3433308780
Ref: 库<88>-Footnote-3443308825
Ref: 库<88>-Footnote-3453308870
Ref: 库<88>-Footnote-3463308915
Ref: 库<88>-Footnote-3473308960
Ref: 库<88>-Footnote-3483309005
Ref: 库<88>-Footnote-3493309050
Ref: 库<88>-Footnote-3503309095
Ref: 库<88>-Footnote-3513309140
Ref: 库<88>-Footnote-3523309185
Ref: 库<88>-Footnote-3533309230
Ref: 库<88>-Footnote-3543309275
Ref: 库<88>-Footnote-3553309320
Ref: 库<88>-Footnote-3563309365
Ref: 库<88>-Footnote-3573309410
Ref: 库<88>-Footnote-3583309455
Ref: 库<88>-Footnote-3593309500
Ref: 库<88>-Footnote-3603309545
Ref: 库<88>-Footnote-3613309590
Ref: 库<88>-Footnote-3623309635
Ref: 库<88>-Footnote-3633309680
Ref: 库<88>-Footnote-3643309725
Ref: 库<88>-Footnote-3653309770
Ref: 库<88>-Footnote-3663309815
Ref: 库<88>-Footnote-3673309860
Ref: 库<88>-Footnote-3683309905
Ref: 库<88>-Footnote-3693309950
Ref: 库<88>-Footnote-3703309995
Ref: 库<88>-Footnote-3713310039
Ref: 库<88>-Footnote-3723310084
Ref: 库<88>-Footnote-3733310129
Ref: 库<88>-Footnote-3743310174
Ref: 库<88>-Footnote-3753310219
Ref: 库<88>-Footnote-3763310264
Ref: 库<88>-Footnote-3773310309
Ref: 库<88>-Footnote-3783310354
Ref: 库<88>-Footnote-3793310399
Ref: 库<88>-Footnote-3803310444
Ref: 库<88>-Footnote-3813310489
Ref: 库<88>-Footnote-3823310534
Ref: 库<88>-Footnote-3833310579
Ref: 库<88>-Footnote-3843310623
Ref: 库<88>-Footnote-3853310668
Ref: 库<88>-Footnote-3863310713
Ref: 库<88>-Footnote-3873310758
Ref: 库<88>-Footnote-3883310803
Ref: 库<88>-Footnote-3893310846
Ref: 库<88>-Footnote-3903310891
Ref: 库<88>-Footnote-3913310936
Ref: 库<88>-Footnote-3923310981
Ref: 库<88>-Footnote-3933311026
Ref: 库<88>-Footnote-3943311071
Ref: 库<88>-Footnote-3953311116
Ref: 库<88>-Footnote-3963311161
Node: IDLE<53>3311206
Ref: whatsnew/changelog id5553311306
Ref: 12013311306
Ref: IDLE<53>-Footnote-13314794
Ref: IDLE<53>-Footnote-23314837
Ref: IDLE<53>-Footnote-33314880
Ref: IDLE<53>-Footnote-43314922
Ref: IDLE<53>-Footnote-53314965
Ref: IDLE<53>-Footnote-63315007
Ref: IDLE<53>-Footnote-73315050
Ref: IDLE<53>-Footnote-83315093
Ref: IDLE<53>-Footnote-93315136
Ref: IDLE<53>-Footnote-103315179
Ref: IDLE<53>-Footnote-113315223
Ref: IDLE<53>-Footnote-123315267
Ref: IDLE<53>-Footnote-133315311
Ref: IDLE<53>-Footnote-143315355
Ref: IDLE<53>-Footnote-153315399
Ref: IDLE<53>-Footnote-163315443
Ref: IDLE<53>-Footnote-173315487
Ref: IDLE<53>-Footnote-183315531
Ref: IDLE<53>-Footnote-193315575
Ref: IDLE<53>-Footnote-203315619
Ref: IDLE<53>-Footnote-213315663
Ref: IDLE<53>-Footnote-223315707
Ref: IDLE<53>-Footnote-233315751
Ref: IDLE<53>-Footnote-243315801
Ref: IDLE<53>-Footnote-253315845
Ref: IDLE<53>-Footnote-263315889
Node: 构建<56>3315933
Ref: whatsnew/changelog id5563316035
Ref: 12023316035
Ref: 构建<56>-Footnote-13319430
Ref: 构建<56>-Footnote-23319473
Ref: 构建<56>-Footnote-33319516
Ref: 构建<56>-Footnote-43319559
Ref: 构建<56>-Footnote-53319602
Ref: 构建<56>-Footnote-63319645
Ref: 构建<56>-Footnote-73319688
Ref: 构建<56>-Footnote-83319731
Ref: 构建<56>-Footnote-93319774
Ref: 构建<56>-Footnote-103319817
Ref: 构建<56>-Footnote-113319861
Ref: 构建<56>-Footnote-123319905
Ref: 构建<56>-Footnote-133319949
Ref: 构建<56>-Footnote-143319993
Ref: 构建<56>-Footnote-153320037
Ref: 构建<56>-Footnote-163320081
Ref: 构建<56>-Footnote-173320125
Ref: 构建<56>-Footnote-183320169
Ref: 构建<56>-Footnote-193320213
Ref: 构建<56>-Footnote-203320257
Ref: 构建<56>-Footnote-213320301
Ref: 构建<56>-Footnote-223320345
Ref: 构建<56>-Footnote-233320389
Ref: 构建<56>-Footnote-243320433
Ref: 构建<56>-Footnote-253320477
Ref: 构建<56>-Footnote-263320521
Node: C API<38>3320565
Ref: whatsnew/changelog id5573320669
Ref: 12033320669
Ref: C API<38>-Footnote-13322034
Ref: C API<38>-Footnote-23322077
Ref: C API<38>-Footnote-33322120
Ref: C API<38>-Footnote-43322163
Ref: C API<38>-Footnote-53322206
Ref: C API<38>-Footnote-63322249
Ref: C API<38>-Footnote-73322292
Node: 文档<54>3322335
Ref: whatsnew/changelog id5583322439
Ref: 12043322439
Ref: 文档<54>-Footnote-13324230
Ref: 文档<54>-Footnote-23324273
Ref: 文档<54>-Footnote-33324316
Ref: 文档<54>-Footnote-43324359
Ref: 文档<54>-Footnote-53324402
Ref: 文档<54>-Footnote-63324444
Ref: 文档<54>-Footnote-73324487
Ref: 文档<54>-Footnote-83324530
Ref: 文档<54>-Footnote-93324573
Ref: 文档<54>-Footnote-103324616
Ref: 文档<54>-Footnote-113324660
Node: 测试<54>3324704
Ref: whatsnew/changelog id5593324816
Ref: 12053324816
Ref: 测试<54>-Footnote-13329034
Ref: 测试<54>-Footnote-23329077
Ref: 测试<54>-Footnote-33329120
Ref: 测试<54>-Footnote-43329163
Ref: 测试<54>-Footnote-53329206
Ref: 测试<54>-Footnote-63329249
Ref: 测试<54>-Footnote-73329292
Ref: 测试<54>-Footnote-83329335
Ref: 测试<54>-Footnote-93329378
Ref: 测试<54>-Footnote-103329421
Ref: 测试<54>-Footnote-113329465
Ref: 测试<54>-Footnote-123329509
Ref: 测试<54>-Footnote-133329553
Ref: 测试<54>-Footnote-143329597
Ref: 测试<54>-Footnote-153329640
Ref: 测试<54>-Footnote-163329684
Ref: 测试<54>-Footnote-173329728
Ref: 测试<54>-Footnote-183329772
Ref: 测试<54>-Footnote-193329816
Ref: 测试<54>-Footnote-203329860
Ref: 测试<54>-Footnote-213329904
Ref: 测试<54>-Footnote-223329948
Ref: 测试<54>-Footnote-233329992
Ref: 测试<54>-Footnote-243330036
Ref: 测试<54>-Footnote-253330080
Ref: 测试<54>-Footnote-263330124
Ref: 测试<54>-Footnote-273330168
Ref: 测试<54>-Footnote-283330212
Ref: 测试<54>-Footnote-293330256
Ref: 测试<54>-Footnote-303330300
Ref: 测试<54>-Footnote-313330344
Ref: 测试<54>-Footnote-323330388
Ref: 测试<54>-Footnote-333330432
Ref: 测试<54>-Footnote-343330476
Ref: 测试<54>-Footnote-353330520
Ref: 测试<54>-Footnote-363330564
Ref: 测试<54>-Footnote-373330608
Node: 工具/示例<36>3330652
Ref: whatsnew/changelog id5603330765
Ref: 12063330765
Ref: 工具/示例<36>-Footnote-13332428
Ref: 工具/示例<36>-Footnote-23332471
Ref: 工具/示例<36>-Footnote-33332514
Ref: 工具/示例<36>-Footnote-43332557
Ref: 工具/示例<36>-Footnote-53332600
Ref: 工具/示例<36>-Footnote-63332643
Ref: 工具/示例<36>-Footnote-73332686
Ref: 工具/示例<36>-Footnote-83332729
Ref: 工具/示例<36>-Footnote-93332772
Ref: 工具/示例<36>-Footnote-103332815
Ref: 工具/示例<36>-Footnote-113332859
Ref: 工具/示例<36>-Footnote-123332903
Node: Windows<52>3332947
Ref: whatsnew/changelog id5613333041
Ref: 12073333041
Ref: Windows<52>-Footnote-13334217
Ref: Windows<52>-Footnote-23334260
Ref: Windows<52>-Footnote-33334303
Ref: Windows<52>-Footnote-43334346
Ref: Windows<52>-Footnote-53334389
Ref: Windows<52>-Footnote-63334432
Ref: Windows<52>-Footnote-73334475
Node: Python 教程3334518
Ref: tutorial/index doc3334628
Ref: 12083334628
Ref: tutorial/index the-python-tutorial3334628
Ref: 12093334628
Ref: tutorial/index tutorial-index3334628
Ref: 120a3334628
Node: 课前甜点3336829
Ref: tutorial/appetite doc3336923
Ref: 12103336923
Ref: tutorial/appetite tut-intro3336923
Ref: 12113336923
Ref: tutorial/appetite whetting-your-appetite3336923
Ref: 12123336923
Node: 使用 Python 解释器3340947
Ref: tutorial/interpreter doc3341075
Ref: 12133341075
Ref: tutorial/interpreter tut-using3341075
Ref: 12143341075
Ref: tutorial/interpreter using-the-python-interpreter3341075
Ref: 12153341075
Node: 调用解释器3341186
Ref: tutorial/interpreter invoking-the-interpreter3341294
Ref: 12163341294
Ref: tutorial/interpreter tut-invoking3341294
Ref: 12173341294
Ref: 调用解释器-Footnote-13343981
Ref: 调用解释器-Footnote-23344142
Node: 传入参数3344203
Ref: tutorial/interpreter argument-passing3344288
Ref: 121c3344288
Ref: tutorial/interpreter tut-argpassing3344288
Ref: 121d3344288
Node: 交互模式3345111
Ref: tutorial/interpreter interactive-mode3345196
Ref: 121e3345196
Ref: tutorial/interpreter tut-interactive3345196
Ref: 8eb3345196
Node: 解释器的运行环境3346208
Ref: tutorial/interpreter the-interpreter-and-its-environment3346316
Ref: 12203346316
Ref: tutorial/interpreter tut-interp3346316
Ref: 12213346316
Node: 源文件的字符编码3346410
Ref: tutorial/interpreter source-code-encoding3346495
Ref: 12223346495
Ref: tutorial/interpreter tut-source-encoding3346495
Ref: 12233346495
Node: Python 的非正式介绍3347657
Ref: tutorial/introduction doc3347797
Ref: 12253347797
Ref: tutorial/introduction an-informal-introduction-to-python3347797
Ref: 12263347797
Ref: tutorial/introduction tut-informal3347797
Ref: 12273347797
Node: Python 作为计算器使用3349005
Ref: tutorial/introduction tut-calculator3349128
Ref: 122a3349128
Ref: tutorial/introduction using-python-as-a-calculator3349128
Ref: 122b3349128
Node: 数字3349384
Ref: tutorial/introduction numbers3349473
Ref: 122c3349473
Ref: tutorial/introduction tut-numbers3349473
Ref: 122d3349473
Ref: 数字-Footnote-13352338
Node: 字符串3352567
Ref: tutorial/introduction strings3352671
Ref: 12303352671
Ref: tutorial/introduction tut-strings3352671
Ref: 12313352671
Ref: 字符串-Footnote-13360059
Node: 列表3360365
Ref: tutorial/introduction lists3360454
Ref: 12363360454
Ref: tutorial/introduction tut-lists3360454
Ref: 12373360454
Node: 走向编程的第一步3362999
Ref: tutorial/introduction first-steps-towards-programming3363122
Ref: 123b3363122
Ref: tutorial/introduction tut-firststeps3363122
Ref: 123c3363122
Ref: 走向编程的第一步-Footnote-13366054
Node: 其他流程控制工具3366109
Ref: tutorial/controlflow doc3366238
Ref: 123e3366238
Ref: tutorial/controlflow more-control-flow-tools3366238
Ref: 123f3366238
Ref: tutorial/controlflow tut-morecontrol3366238
Ref: 12403366238
Node: if 语句3366661
Ref: tutorial/controlflow if-statements3366750
Ref: 12413366750
Ref: tutorial/controlflow tut-if3366750
Ref: 12423366750
Node: for 语句3367540
Ref: tutorial/controlflow for-statements3367650
Ref: 12453367650
Ref: tutorial/controlflow tut-for3367650
Ref: 12463367650
Node: range 函数3368827
Ref: tutorial/controlflow the-range-function3368986
Ref: 12473368986
Ref: tutorial/controlflow tut-range3368986
Ref: 12483368986
Node: break 和 continue 语句，以及循环中的 else 子句3371152
Ref: tutorial/controlflow break-and-continue-statements-and-else-clauses-on-loops3371312
Ref: 124b3371312
Ref: tutorial/controlflow tut-break3371312
Ref: 124c3371312
Node: pass 语句3373429
Ref: tutorial/controlflow pass-statements3373589
Ref: 124e3373589
Ref: tutorial/controlflow tut-pass3373589
Ref: 124f3373589
Node: 定义函数3374277
Ref: tutorial/controlflow defining-functions3374406
Ref: 12513374406
Ref: tutorial/controlflow tut-functions3374406
Ref: 12523374406
Ref: 定义函数-Footnote-13378879
Node: 函数定义的更多形式3379098
Ref: tutorial/controlflow more-on-defining-functions3379240
Ref: 12563379240
Ref: tutorial/controlflow tut-defining3379240
Ref: 12573379240
Node: 参数默认值3379578
Ref: tutorial/controlflow default-argument-values3379681
Ref: 12583379681
Ref: tutorial/controlflow tut-defaultargs3379681
Ref: 12593379681
Node: 关键字参数3381482
Ref: tutorial/controlflow keyword-arguments3381606
Ref: 125a3381606
Ref: tutorial/controlflow tut-keywordargs3381606
Ref: 125b3381606
Node: 特殊参数3385208
Ref: tutorial/controlflow special-parameters3385338
Ref: 125d3385338
Node: 位置或关键字参数3386407
Ref: tutorial/controlflow positional-or-keyword-arguments3386507
Ref: 125e3386507
Node: 仅限位置参数3386678
Ref: tutorial/controlflow positional-only-parameters3386808
Ref: 125f3386808
Node: 仅限关键字参数3387355
Ref: tutorial/controlflow keyword-only-arguments3387473
Ref: 12603387473
Node: 函数示例3387716
Ref: tutorial/controlflow function-examples3387822
Ref: 12613387822
Node: 概括3390657
Ref: tutorial/controlflow recap3390733
Ref: 12623390733
Node: 任意的参数列表3391517
Ref: tutorial/controlflow arbitrary-argument-lists3391650
Ref: 12633391650
Ref: tutorial/controlflow tut-arbitraryargs3391650
Ref: 12643391650
Node: 解包参数列表3392585
Ref: tutorial/controlflow tut-unpacking-arguments3392722
Ref: 12653392722
Ref: tutorial/controlflow unpacking-argument-lists3392722
Ref: 12663392722
Node: Lambda 表达式3393859
Ref: tutorial/controlflow lambda-expressions3393990
Ref: 12673393990
Ref: tutorial/controlflow tut-lambda3393990
Ref: 12683393990
Node: 文档字符串3394899
Ref: tutorial/controlflow documentation-strings3395024
Ref: 12693395024
Ref: tutorial/controlflow tut-docstrings3395024
Ref: 12533395024
Node: 函数标注3396658
Ref: tutorial/controlflow function-annotations3396758
Ref: 126a3396758
Ref: tutorial/controlflow tut-annotations3396758
Ref: 126b3396758
Ref: 函数标注-Footnote-13397913
Ref: 函数标注-Footnote-23397962
Node: 小插曲：编码风格3398011
Ref: tutorial/controlflow intermezzo-coding-style3398132
Ref: 126e3398132
Ref: tutorial/controlflow tut-codingstyle3398132
Ref: 126f3398132
Ref: 小插曲：编码风格-Footnote-13400215
Node: 数据结构3400264
Ref: tutorial/datastructures doc3400374
Ref: 12713400374
Ref: tutorial/datastructures data-structures3400374
Ref: 12723400374
Ref: tutorial/datastructures tut-structures3400374
Ref: 124a3400374
Node: 列表的更多特性3400662
Ref: tutorial/datastructures more-on-lists3400751
Ref: 12733400751
Ref: tutorial/datastructures tut-morelists3400751
Ref: 12743400751
Ref: 列表的更多特性-Footnote-13404272
Node: 列表作为栈使用3404418
Ref: tutorial/datastructures tut-lists-as-stacks3404530
Ref: 12753404530
Ref: tutorial/datastructures using-lists-as-stacks3404530
Ref: 12763404530
Node: 列表作为队列使用3405112
Ref: tutorial/datastructures tut-lists-as-queues3405251
Ref: 12773405251
Ref: tutorial/datastructures using-lists-as-queues3405251
Ref: 12783405251
Node: 列表推导式<2>3406260
Ref: tutorial/datastructures list-comprehensions3406402
Ref: 12793406402
Ref: tutorial/datastructures tut-listcomps3406402
Ref: 127a3406402
Node: 嵌套的列表推导式3409554
Ref: tutorial/datastructures nested-list-comprehensions3409663
Ref: 127b3409663
Node: del 语句3411196
Ref: tutorial/datastructures the-del-statement3411309
Ref: 127c3411309
Ref: tutorial/datastructures tut-del3411309
Ref: 127d3411309
Node: 元组和序列3412105
Ref: tutorial/datastructures tuples-and-sequences3412203
Ref: 127f3412203
Ref: tutorial/datastructures tut-tuples3412203
Ref: 125c3412203
Node: 集合3414992
Ref: tutorial/datastructures sets3415086
Ref: 12813415086
Ref: tutorial/datastructures tut-sets3415086
Ref: 12823415086
Node: 字典3416754
Ref: tutorial/datastructures dictionaries3416848
Ref: 12833416848
Ref: tutorial/datastructures tut-dictionaries3416848
Ref: 12843416848
Node: 循环的技巧3419441
Ref: tutorial/datastructures looping-techniques3419547
Ref: 12853419547
Ref: tutorial/datastructures tut-loopidioms3419547
Ref: 12493419547
Node: 深入条件控制3421608
Ref: tutorial/datastructures more-on-conditions3421735
Ref: 12863421735
Ref: tutorial/datastructures tut-conditions3421735
Ref: 12873421735
Node: 比较序列和其他类型3423616
Ref: tutorial/datastructures comparing-sequences-and-other-types3423719
Ref: 12893423719
Ref: tutorial/datastructures tut-comparing3423719
Ref: 128a3423719
Node: 模块3425208
Ref: tutorial/modules doc3425306
Ref: 128b3425306
Ref: tutorial/modules modules3425306
Ref: 128c3425306
Ref: tutorial/modules tut-modules3425306
Ref: 128d3425306
Node: 更多有关模块的信息3427652
Ref: tutorial/modules more-on-modules3427743
Ref: 128e3427743
Ref: tutorial/modules tut-moremodules3427743
Ref: 128f3427743
Ref: 更多有关模块的信息-Footnote-13430698
Node: 以脚本的方式执行模块3430856
Ref: tutorial/modules executing-modules-as-scripts3430977
Ref: 12903430977
Ref: tutorial/modules tut-modulesasscripts3430977
Ref: 12913430977
Node: 模块搜索路径3431878
Ref: tutorial/modules the-module-search-path3432038
Ref: 12923432038
Ref: tutorial/modules tut-searchpath3432038
Ref: 12933432038
Node: “编译过的”Python文件3433216
Ref: tutorial/modules compiled-python-files3433337
Ref: 12953433337
Ref: “编译过的”Python文件-Footnote-13435377
Node: 标准模块3435426
Ref: tutorial/modules standard-modules3435536
Ref: 12963435536
Ref: tutorial/modules tut-standardmodules3435536
Ref: 12943435536
Node: dir 函数3436817
Ref: tutorial/modules the-dir-function3436903
Ref: 12973436903
Ref: tutorial/modules tut-dir3436903
Ref: 12983436903
Node: 包3441013
Ref: tutorial/modules packages3441078
Ref: 12993441078
Ref: tutorial/modules tut-packages3441078
Ref: 129a3441078
Node: 从包中导入 *3444975
Ref: tutorial/modules importing-from-a-package3445053
Ref: 129b3445053
Ref: tutorial/modules tut-pkg-import-star3445053
Ref: 129c3445053
Node: 子包参考3447416
Ref: tutorial/modules intra-package-references3447524
Ref: 129d3447524
Node: 多个目录中的包3448392
Ref: tutorial/modules packages-in-multiple-directories3448474
Ref: 129e3448474
Node: 输入输出3448922
Ref: tutorial/inputoutput doc3449023
Ref: 12a03449023
Ref: tutorial/inputoutput input-and-output3449023
Ref: 12a13449023
Ref: tutorial/inputoutput tut-io3449023
Ref: 12a23449023
Node: 更漂亮的输出格式3449281
Ref: tutorial/inputoutput fancier-output-formatting3449375
Ref: 12a33449375
Ref: tutorial/inputoutput tut-formatting3449375
Ref: 12a43449375
Node: 格式化字符串文字3452753
Ref: tutorial/inputoutput formatted-string-literals3452873
Ref: 12a63452873
Ref: tutorial/inputoutput tut-f-strings3452873
Ref: 12a53452873
Node: 字符串的 format 方法3454304
Ref: tutorial/inputoutput the-string-format-method3454457
Ref: 12a73454457
Ref: tutorial/inputoutput tut-string-format3454457
Ref: 12a83454457
Node: 手动格式化字符串3456955
Ref: tutorial/inputoutput manual-string-formatting3457114
Ref: 12a93457114
Node: 旧的字符串格式化方法3458597
Ref: tutorial/inputoutput old-string-formatting3458721
Ref: 12ae3458721
Node: 读写文件3459241
Ref: tutorial/inputoutput reading-and-writing-files3459335
Ref: 12af3459335
Ref: tutorial/inputoutput tut-files3459335
Ref: 12b03459335
Node: 文件对象的方法3462076
Ref: tutorial/inputoutput methods-of-file-objects3462188
Ref: 12b13462188
Ref: tutorial/inputoutput tut-filemethods3462188
Ref: 12b23462188
Node: 使用 json 保存结构化数据3465682
Ref: tutorial/inputoutput saving-structured-data-with-json3465794
Ref: 12b33465794
Ref: tutorial/inputoutput tut-json3465794
Ref: 12b43465794
Ref: 使用 json 保存结构化数据-Footnote-13468249
Node: 错误和异常3468273
Ref: tutorial/errors doc3468371
Ref: 12b63468371
Ref: tutorial/errors errors-and-exceptions3468371
Ref: 12b73468371
Ref: tutorial/errors tut-errors3468371
Ref: 12b83468371
Node: 语法错误3468783
Ref: tutorial/errors syntax-errors3468862
Ref: 12b93468862
Ref: tutorial/errors tut-syntaxerrors3468862
Ref: 12ba3468862
Node: 异常3469626
Ref: tutorial/errors exceptions3469726
Ref: 12bb3469726
Ref: tutorial/errors tut-exceptions3469726
Ref: 12bc3469726
Node: 处理异常3471488
Ref: tutorial/errors handling-exceptions3471588
Ref: 12bf3471588
Ref: tutorial/errors tut-handling3471588
Ref: 124d3471588
Node: 抛出异常3477055
Ref: tutorial/errors raising-exceptions3477170
Ref: 12c03477170
Ref: tutorial/errors tut-raising3477170
Ref: 12c13477170
Node: 用户自定义异常3478194
Ref: tutorial/errors tut-userexceptions3478315
Ref: 12c23478315
Ref: tutorial/errors user-defined-exceptions3478315
Ref: 12c33478315
Node: 定义清理操作3480197
Ref: tutorial/errors defining-clean-up-actions3480330
Ref: 12c43480330
Ref: tutorial/errors tut-cleanup3480330
Ref: 12c53480330
Node: 预定义的清理操作3483262
Ref: tutorial/errors predefined-clean-up-actions3483365
Ref: 12c63483365
Ref: tutorial/errors tut-cleanup-with3483365
Ref: 12c73483365
Node: 类3484383
Ref: tutorial/classes doc3484484
Ref: 12c83484484
Ref: tutorial/classes classes3484484
Ref: 12c93484484
Ref: tutorial/classes tut-classes3484484
Ref: 12553484484
Node: 名称和对象3486422
Ref: tutorial/classes a-word-about-names-and-objects3486517
Ref: 12cb3486517
Ref: tutorial/classes tut-object3486517
Ref: 12cc3486517
Node: Python 作用域和命名空间3487313
Ref: tutorial/classes python-scopes-and-namespaces3487426
Ref: 12cd3487426
Ref: tutorial/classes tut-scopes3487426
Ref: 12ce3487426
Ref: Python 作用域和命名空间-Footnote-13493212
Node: 作用域和命名空间示例3493532
Ref: tutorial/classes scopes-and-namespaces-example3493630
Ref: 12d03493630
Ref: tutorial/classes tut-scopeexample3493630
Ref: 12d13493630
Node: 初探类3494923
Ref: tutorial/classes a-first-look-at-classes3495033
Ref: 12d23495033
Ref: tutorial/classes tut-firstclasses3495033
Ref: 12703495033
Node: 类定义语法3495238
Ref: tutorial/classes class-definition-syntax3495317
Ref: 12d33495317
Ref: tutorial/classes tut-classdefinition3495317
Ref: 12d43495317
Node: 类对象3496695
Ref: tutorial/classes class-objects3496795
Ref: 12d53496795
Ref: tutorial/classes tut-classobjects3496795
Ref: 12d63496795
Node: 实例对象3498828
Ref: tutorial/classes instance-objects3498925
Ref: 12d73498925
Ref: tutorial/classes tut-instanceobjects3498925
Ref: 12d83498925
Node: 方法对象3500441
Ref: tutorial/classes method-objects3500547
Ref: 12d93500547
Ref: tutorial/classes tut-methodobjects3500547
Ref: 12da3500547
Node: 类和实例变量3502307
Ref: tutorial/classes class-and-instance-variables3502392
Ref: 12db3502392
Ref: tutorial/classes tut-class-and-instance-variables3502392
Ref: 12dc3502392
Node: 补充说明3504309
Ref: tutorial/classes random-remarks3504394
Ref: 12dd3504394
Ref: tutorial/classes tut-remarks3504394
Ref: 12de3504394
Node: 继承3507955
Ref: tutorial/classes inheritance3508043
Ref: 12df3508043
Ref: tutorial/classes tut-inheritance3508043
Ref: 12e03508043
Node: 多重继承3510537
Ref: tutorial/classes multiple-inheritance3510592
Ref: 12e13510592
Ref: tutorial/classes tut-multiple3510592
Ref: 12e23510592
Node: 私有变量3512408
Ref: tutorial/classes private-variables3512496
Ref: 12e33512496
Ref: tutorial/classes tut-private3512496
Ref: 12ca3512496
Node: 杂项说明3514931
Ref: tutorial/classes odds-and-ends3515022
Ref: 12e43515022
Ref: tutorial/classes tut-odds3515022
Ref: 12e53515022
Node: 迭代器3515977
Ref: tutorial/classes iterators3516065
Ref: 12e63516065
Ref: tutorial/classes tut-iterators3516065
Ref: 12e73516065
Node: 生成器3518289
Ref: tutorial/classes generators3518383
Ref: 12e83518383
Ref: tutorial/classes tut-generators3518383
Ref: 12e93518383
Node: 生成器表达式3519714
Ref: tutorial/classes generator-expressions3519790
Ref: 12eb3519790
Ref: tutorial/classes tut-genexps3519790
Ref: 12ec3519790
Node: 标准库简介3520694
Ref: tutorial/stdlib doc3520815
Ref: 12ed3520815
Ref: tutorial/stdlib brief-tour-of-the-standard-library3520815
Ref: 12ee3520815
Ref: tutorial/stdlib tut-brieftour3520815
Ref: 12ef3520815
Node: 操作系统接口3521112
Ref: tutorial/stdlib operating-system-interface3521206
Ref: 12f03521206
Ref: tutorial/stdlib tut-os-interface3521206
Ref: 12f13521206
Node: 文件通配符3522390
Ref: tutorial/stdlib file-wildcards3522508
Ref: 12f23522508
Ref: tutorial/stdlib tut-file-wildcards3522508
Ref: 12f33522508
Node: 命令行参数3522743
Ref: tutorial/stdlib command-line-arguments3522879
Ref: 12f43522879
Ref: tutorial/stdlib tut-command-line-arguments3522879
Ref: 12f53522879
Node: 错误输出重定向和程序终止3523894
Ref: tutorial/stdlib error-output-redirection-and-program-termination3524036
Ref: 12f63524036
Ref: tutorial/stdlib tut-stderr3524036
Ref: 12f73524036
Node: 字符串模式匹配3524496
Ref: tutorial/stdlib string-pattern-matching3524629
Ref: 12f83524629
Ref: tutorial/stdlib tut-string-pattern-matching3524629
Ref: 12f93524629
Node: 数学3525208
Ref: tutorial/stdlib mathematics3525320
Ref: 12fa3525320
Ref: tutorial/stdlib tut-mathematics3525320
Ref: 12fb3525320
Node: 互联网访问3526380
Ref: tutorial/stdlib internet-access3526486
Ref: 12fc3526486
Ref: tutorial/stdlib tut-internet-access3526486
Ref: 12fd3526486
Node: 日期和时间3527491
Ref: tutorial/stdlib dates-and-times3527603
Ref: 12fe3527603
Ref: tutorial/stdlib tut-dates-and-times3527603
Ref: 12ff3527603
Node: 数据压缩3528348
Ref: tutorial/stdlib data-compression3528457
Ref: 13003528457
Ref: tutorial/stdlib tut-data-compression3528457
Ref: 13013528457
Node: 性能测量3528950
Ref: tutorial/stdlib performance-measurement3529056
Ref: 13023529056
Ref: tutorial/stdlib tut-performance-measurement3529056
Ref: 13033529056
Node: 质量控制3529797
Ref: tutorial/stdlib quality-control3529903
Ref: 13043529903
Ref: tutorial/stdlib tut-quality-control3529903
Ref: 13053529903
Node: 自带电池3531331
Ref: tutorial/stdlib batteries-included3531416
Ref: 13063531416
Ref: tutorial/stdlib tut-batteries-included3531416
Ref: 13073531416
Ref: 自带电池-Footnote-13532998
Node: 标准库简介 —— 第二部分3533047
Ref: tutorial/stdlib2 doc3533183
Ref: 13083533183
Ref: tutorial/stdlib2 brief-tour-of-the-standard-library-part-ii3533183
Ref: 13093533183
Ref: tutorial/stdlib2 tut-brieftourtwo3533183
Ref: 130a3533183
Node: 格式化输出3533555
Ref: tutorial/stdlib2 output-formatting3533657
Ref: 130b3533657
Ref: tutorial/stdlib2 tut-output-formatting3533657
Ref: 130c3533657
Node: 模板3535729
Ref: tutorial/stdlib2 templating3535873
Ref: 130d3535873
Ref: tutorial/stdlib2 tut-templating3535873
Ref: 130e3535873
Node: 使用二进制数据记录格式3538359
Ref: tutorial/stdlib2 tut-binary-formats3538500
Ref: 13113538500
Ref: tutorial/stdlib2 working-with-binary-data-record-layouts3538500
Ref: 13123538500
Node: 多线程<2>3539613
Ref: tutorial/stdlib2 multi-threading3539760
Ref: 13143539760
Ref: tutorial/stdlib2 tut-multi-threading3539760
Ref: 13153539760
Node: 日志记录3541567
Ref: tutorial/stdlib2 logging3541690
Ref: 13163541690
Ref: tutorial/stdlib2 tut-logging3541690
Ref: 13173541690
Node: 弱引用3542824
Ref: tutorial/stdlib2 tut-weak-references3542962
Ref: 13183542962
Ref: tutorial/stdlib2 weak-references3542962
Ref: 13193542962
Node: 用于操作列表的工具3544642
Ref: tutorial/stdlib2 tools-for-working-with-lists3544789
Ref: 131a3544789
Ref: tutorial/stdlib2 tut-list-tools3544789
Ref: 131b3544789
Node: 十进制浮点运算3547149
Ref: tutorial/stdlib2 decimal-floating-point-arithmetic3547278
Ref: 131c3547278
Ref: tutorial/stdlib2 tut-decimal-fp3547278
Ref: 131d3547278
Node: 虚拟环境和包3548893
Ref: tutorial/venv doc3549026
Ref: 131e3549026
Ref: tutorial/venv tut-venv3549026
Ref: 131f3549026
Ref: tutorial/venv virtual-environments-and-packages3549026
Ref: 13203549026
Node: 概述<4>3549146
Ref: tutorial/venv introduction3549237
Ref: 13213549237
Node: 创建虚拟环境3550286
Ref: tutorial/venv creating-virtual-environments3550404
Ref: 13233550404
Node: 使用pip管理包3552177
Ref: tutorial/venv managing-packages-with-pip3552277
Ref: 13243552277
Node: 接下来？3555877
Ref: tutorial/whatnow doc3556005
Ref: 13253556005
Ref: tutorial/whatnow tut-whatnow3556005
Ref: 13263556005
Ref: tutorial/whatnow what-now3556005
Ref: 13273556005
Ref: 接下来？-Footnote-13559026
Node: 交互式编辑和编辑历史3559185
Ref: tutorial/interactive doc3559325
Ref: 13293559325
Ref: tutorial/interactive interactive-input-editing-and-history-substitution3559325
Ref: 132a3559325
Ref: tutorial/interactive tut-interacting3559325
Ref: 121a3559325
Ref: 交互式编辑和编辑历史-Footnote-13559803
Node: Tab 补全和编辑历史3559864
Ref: tutorial/interactive tab-completion-and-history-editing3560001
Ref: 132b3560001
Ref: tutorial/interactive tut-keybindings3560001
Ref: 132c3560001
Node: 默认交互式解释器的替代品3560768
Ref: tutorial/interactive alternatives-to-the-interactive-interpreter3560905
Ref: 132d3560905
Ref: tutorial/interactive tut-commentary3560905
Ref: 132e3560905
Ref: 默认交互式解释器的替代品-Footnote-13561670
Ref: 默认交互式解释器的替代品-Footnote-23561699
Node: 浮点算术：争议和限制3561744
Ref: tutorial/floatingpoint doc3561878
Ref: 132f3561878
Ref: tutorial/floatingpoint bpython3561878
Ref: 13303561878
Ref: tutorial/floatingpoint floating-point-arithmetic-issues-and-limitations3561878
Ref: 13313561878
Ref: tutorial/floatingpoint tut-fp-issues3561878
Ref: 13323561878
Ref: 浮点算术：争议和限制-Footnote-13569436
Node: 表示性错误3569475
Ref: tutorial/floatingpoint representation-error3569557
Ref: 13353569557
Ref: tutorial/floatingpoint tut-fp-error3569557
Ref: 13363569557
Node: 附录3572687
Ref: tutorial/appendix doc3572782
Ref: 13373572782
Ref: tutorial/appendix appendix3572782
Ref: 13383572782
Ref: tutorial/appendix tut-appendix3572782
Ref: 13393572782
Node: 交互模式<2>3572848
Ref: tutorial/appendix interactive-mode3572906
Ref: 133a3572906
Ref: tutorial/appendix tut-interac3572906
Ref: 121f3572906
Node: 错误处理3573042
Ref: tutorial/appendix error-handling3573139
Ref: 133b3573139
Ref: tutorial/appendix tut-error3573139
Ref: 133c3573139
Ref: 错误处理-Footnote-13574028
Node: 可执行的Python脚本3574096
Ref: tutorial/appendix executable-python-scripts3574223
Ref: 133d3574223
Ref: tutorial/appendix tut-scripts3574223
Ref: 12243574223
Node: 交互式启动文件3575180
Ref: tutorial/appendix the-interactive-startup-file3575307
Ref: 133e3575307
Ref: tutorial/appendix tut-startup3575307
Ref: 133f3575307
Node: 定制模块3576662
Ref: tutorial/appendix the-customization-modules3576756
Ref: 13403576756
Ref: tutorial/appendix tut-customize3576756
Ref: 13413576756
Node: Python安装和使用3577585
Ref: using/index doc3577695
Ref: 13423577695
Ref: using/index python-setup-and-usage3577695
Ref: 13433577695
Ref: using/index using-index3577695
Ref: 13443577695
Node: 命令行与环境3578066
Ref: using/cmdline doc3578182
Ref: 13453578182
Ref: using/cmdline command-line-and-environment3578182
Ref: 13463578182
Ref: using/cmdline using-on-general3578182
Ref: fba3578182
Node: 命令行3578487
Ref: using/cmdline command-line3578572
Ref: 13483578572
Ref: using/cmdline using-on-cmdline3578572
Ref: 9333578572
Node: 接口选项3578936
Ref: using/cmdline interface-options3579015
Ref: 13493579015
Ref: using/cmdline using-on-interface-options3579015
Ref: 134a3579015
Ref: using/cmdline cmdoption-c3580362
Ref: 121b3580362
Ref: using/cmdline cmdoption-m3580911
Ref: 3403580911
Ref: using/cmdline cmdarg-dash3583075
Ref: 134c3583075
Ref: using/cmdline cmdarg-script3583458
Ref: 134d3583458
Ref: 接口选项-Footnote-13585207
Node: 通用选项3585256
Ref: using/cmdline generic-options3585356
Ref: 134e3585356
Ref: using/cmdline cmdoption3585395
Ref: d943585395
Ref: using/cmdline cmdoption-h3585416
Ref: 134f3585416
Ref: using/cmdline cmdoption-help3585437
Ref: d933585437
Ref: using/cmdline cmdoption-v3585515
Ref: 5db3585515
Ref: using/cmdline cmdoption-version3585536
Ref: 5da3585536
Node: 其他选项3585876
Ref: using/cmdline miscellaneous-options3585988
Ref: 13503585988
Ref: using/cmdline using-on-misc-options3585988
Ref: 9343585988
Ref: using/cmdline cmdoption-b3586027
Ref: 41d3586027
Ref: using/cmdline id13586355
Ref: d403586355
Ref: using/cmdline cmdoption-check-hash-based-pycs3586536
Ref: 13513586536
Ref: using/cmdline cmdoption-d3587232
Ref: 13523587232
Ref: using/cmdline cmdoption-e3587382
Ref: 10193587382
Ref: using/cmdline cmdoption-i3587535
Ref: e273587535
Ref: using/cmdline id23587964
Ref: 10183587964
Ref: using/cmdline cmdoption-o3588340
Ref: 6943588340
Ref: using/cmdline cmdoption-oo3588732
Ref: 6953588732
Ref: using/cmdline cmdoption-q3589046
Ref: 13553589046
Ref: using/cmdline cmdoption-r3589159
Ref: 10a43589159
Ref: using/cmdline cmdoption-s3590090
Ref: d1d3590090
Ref: using/cmdline id33590286
Ref: b2c3590286
Ref: using/cmdline cmdoption-u3590573
Ref: 13583590573
Ref: using/cmdline id43590818
Ref: d903590818
Ref: using/cmdline using-on-warnings3591170
Ref: 135b3591170
Ref: using/cmdline cmdoption-w3591170
Ref: 41f3591170
Ref: using/cmdline cmdoption-x3592703
Ref: 135e3592703
Ref: using/cmdline id53592852
Ref: 1563592852
Ref: 其他选项-Footnote-13596214
Ref: 其他选项-Footnote-23596263
Ref: 其他选项-Footnote-33596312
Ref: 其他选项-Footnote-43596361
Ref: 其他选项-Footnote-53596410
Node: 不应当使用的选项3596459
Ref: using/cmdline options-you-shouldn-t-use3596550
Ref: 13623596550
Ref: using/cmdline cmdoption-j3596609
Ref: d3f3596609
Ref: 不应当使用的选项-Footnote-13596703
Node: 环境变量3596734
Ref: using/cmdline environment-variables3596819
Ref: 13633596819
Ref: using/cmdline using-on-envvars3596819
Ref: 13643596819
Ref: using/cmdline envvar-PYTHONHOME3597056
Ref: 4de3597056
Ref: using/cmdline envvar-PYTHONPATH3597616
Ref: 95b3597616
Ref: using/cmdline envvar-PYTHONSTARTUP3598585
Ref: 8ed3598585
Ref: using/cmdline envvar-PYTHONOPTIMIZE3599196
Ref: 13543599196
Ref: using/cmdline envvar-PYTHONBREAKPOINT3599407
Ref: 31d3599407
Ref: using/cmdline envvar-PYTHONDEBUG3600000
Ref: 13533600000
Ref: using/cmdline envvar-PYTHONINSPECT3600216
Ref: e263600216
Ref: using/cmdline envvar-PYTHONUNBUFFERED3600482
Ref: 13593600482
Ref: using/cmdline envvar-PYTHONVERBOSE3600626
Ref: 135a3600626
Ref: using/cmdline envvar-PYTHONCASEOK3600842
Ref: e653600842
Ref: using/cmdline envvar-PYTHONDONTWRITEBYTECODE3601011
Ref: d413601011
Ref: using/cmdline envvar-PYTHONPYCACHEPREFIX3601228
Ref: 1553601228
Ref: using/cmdline envvar-PYTHONHASHSEED3601529
Ref: 9cd3601529
Ref: using/cmdline envvar-PYTHONIOENCODING3602173
Ref: 9373602173
Ref: using/cmdline envvar-PYTHONNOUSERSITE3602949
Ref: d1e3602949
Ref: using/cmdline envvar-PYTHONUSERBASE3603196
Ref: d1c3603196
Ref: using/cmdline envvar-PYTHONEXECUTABLE3603534
Ref: 136a3603534
Ref: using/cmdline envvar-PYTHONWARNINGS3603741
Ref: 4203603741
Ref: using/cmdline envvar-PYTHONFAULTHANDLER3604636
Ref: 9d03604636
Ref: using/cmdline envvar-PYTHONTRACEMALLOC3605042
Ref: 136b3605042
Ref: using/cmdline envvar-PYTHONPROFILEIMPORTTIME3605454
Ref: 3413605454
Ref: using/cmdline envvar-PYTHONASYNCIODEBUG3605703
Ref: 136c3605703
Ref: using/cmdline envvar-PYTHONMALLOC3605894
Ref: 50b3605894
Ref: using/cmdline envvar-PYTHONMALLOCSTATS3607086
Ref: 11723607086
Ref: using/cmdline envvar-PYTHONLEGACYWINDOWSFSENCODING3607677
Ref: 4ff3607677
Ref: using/cmdline envvar-PYTHONLEGACYWINDOWSSTDIO3608194
Ref: 5023608194
Ref: using/cmdline envvar-PYTHONCOERCECLOCALE3608629
Ref: 3153608629
Ref: using/cmdline envvar-PYTHONDEVMODE3611107
Ref: 3353611107
Ref: using/cmdline envvar-PYTHONUTF83611315
Ref: 31a3611315
Ref: 环境变量-Footnote-13613905
Ref: 环境变量-Footnote-23613954
Ref: 环境变量-Footnote-33614003
Ref: 环境变量-Footnote-43614052
Ref: 环境变量-Footnote-53614101
Node: 调试模式变量3614150
Ref: using/cmdline debug-mode-variables3614217
Ref: 13733614217
Ref: using/cmdline envvar-PYTHONTHREADDEBUG3614334
Ref: 13743614334
Ref: using/cmdline envvar-PYTHONDUMPREFS3614497
Ref: 15a3614497
Node: 在类Unix环境下使用Python3614705
Ref: using/unix doc3614856
Ref: 13753614856
Ref: using/unix using-on-unix3614856
Ref: 13763614856
Ref: using/unix using-python-on-unix-platforms3614856
Ref: 13773614856
Node: 获得并安装Python的最新版本3615039
Ref: using/unix getting-and-installing-the-latest-version-of-python3615164
Ref: 13783615164
Node: 在Linux中3615323
Ref: using/unix on-linux3615439
Ref: 13793615439
Node: 在FreeBSD和OpenBSD上3616306
Ref: using/unix on-freebsd-and-openbsd3616454
Ref: 137a3616454
Node: 在OpenSolaris系统上3616947
Ref: using/unix on-opensolaris3617075
Ref: 137b3617075
Ref: 在OpenSolaris系统上-Footnote-13617282
Node: 构建Python3617315
Ref: using/unix building-python3617482
Ref: 137c3617482
Ref: using/unix building-python-on-unix3617482
Ref: 7fc3617482
Ref: 构建Python-Footnote-13618227
Ref: 构建Python-Footnote-23618276
Ref: 构建Python-Footnote-33618343
Node: 与Python相关的路径和文件3618405
Ref: using/unix python-related-paths-and-files3618542
Ref: 137d3618542
Node: 杂项3619745
Ref: using/unix miscellaneous3619861
Ref: 137e3619861
Node: 在Windows上使用 Python3620372
Ref: using/windows doc3620536
Ref: 137f3620536
Ref: using/windows using-on-windows3620536
Ref: 2da3620536
Ref: using/windows using-python-on-windows3620536
Ref: 13803620536
Ref: 在Windows上使用 Python-Footnote-13622492
Ref: 在Windows上使用 Python-Footnote-23622542
Node: 完整安装程序3622591
Ref: using/windows the-full-installer3622699
Ref: 13843622699
Ref: using/windows windows-full3622699
Ref: 13813622699
Node: 安装步骤3622852
Ref: using/windows installation-steps3622950
Ref: 13853622950
Node: 删除 MAX_PATH 限制3624699
Ref: using/windows max-path3624818
Ref: 4dd3624818
Ref: using/windows removing-the-max-path-limitation3624818
Ref: 13873624818
Node: 无UI 安装3625544
Ref: using/windows install-quiet-option3625666
Ref: 13883625666
Ref: using/windows installing-without-ui3625666
Ref: 13893625666
Node: 免下载安装3634757
Ref: using/windows install-layout-option3634869
Ref: 13863634869
Ref: using/windows installing-without-downloading3634869
Ref: 138a3634869
Node: 修改安装3635727
Ref: using/windows modifying-an-install3635818
Ref: 138b3635818
Node: Microsoft Store包3636570
Ref: using/windows the-microsoft-store-package3636706
Ref: 138c3636706
Ref: using/windows windows-store3636706
Ref: 12183636706
Node: 已知的问题3638642
Ref: using/windows known-issues3638712
Ref: 138d3638712
Ref: 已知的问题-Footnote-13639254
Node: nuget org 安装包3639350
Ref: using/windows the-nuget-org-packages3639483
Ref: 138e3639483
Ref: using/windows windows-nuget3639483
Ref: 13823639483
Ref: nuget org 安装包-Footnote-13641420
Ref: nuget org 安装包-Footnote-23641451
Ref: nuget org 安装包-Footnote-33641497
Node: 可嵌入的包3641546
Ref: using/windows the-embeddable-package3641676
Ref: 138f3641676
Ref: using/windows windows-embeddable3641676
Ref: 13833641676
Ref: 可嵌入的包-Footnote-13643351
Node: Python应用程序3643422
Ref: using/windows python-application3643513
Ref: 13903643513
Node: 嵌入Python3644814
Ref: using/windows embedding-python3644905
Ref: 13913644905
Node: 替代捆绑包3645545
Ref: using/windows alternative-bundles3645668
Ref: 13923645668
Ref: 替代捆绑包-Footnote-13646396
Ref: 替代捆绑包-Footnote-23646446
Ref: 替代捆绑包-Footnote-33646489
Ref: 替代捆绑包-Footnote-43646539
Node: 配置Python3646576
Ref: using/windows configuring-python3646696
Ref: 13933646696
Node: 附录：设置环境变量3647144
Ref: using/windows excursus-setting-environment-variables3647256
Ref: 13943647256
Ref: using/windows setting-envvars3647256
Ref: 12193647256
Node: 查找Python可执行文件3649388
Ref: using/windows finding-the-python-executable3649500
Ref: 13953649500
Ref: using/windows windows-path-mod3649500
Ref: 9983649500
Node: UTF-8 模式3650628
Ref: using/windows utf-8-mode3650767
Ref: 13963650767
Ref: using/windows win-utf8-mode3650767
Ref: 13973650767
Ref: UTF-8 模式-Footnote-13652562
Ref: UTF-8 模式-Footnote-23652611
Node: 适用于Windows的Python启动器3652660
Ref: using/windows launcher3652799
Ref: 9973652799
Ref: using/windows python-launcher-for-windows3652799
Ref: 13983652799
Ref: 适用于Windows的Python启动器-Footnote-13653488
Node: 入门3653537
Ref: using/windows getting-started3653636
Ref: 13993653636
Node: 从命令行3653746
Ref: using/windows from-the-command-line3653825
Ref: 139a3653825
Node: 从虚拟环境3654893
Ref: using/windows virtual-environments3654990
Ref: 139b3654990
Node: 从脚本3655393
Ref: using/windows from-a-script3655493
Ref: 139c3655493
Node: 从文件关联3656421
Ref: using/windows from-file-associations3656497
Ref: 139d3656497
Node: Shebang Lines3656953
Ref: using/windows shebang-lines3657084
Ref: 139e3657084
Node: shebang lines 的参数3658908
Ref: using/windows arguments-in-shebang-lines3659042
Ref: 139f3659042
Node: 自定义3659295
Ref: using/windows customization3659422
Ref: 13a03659422
Node: 通过INI文件自定义3659530
Ref: using/windows customization-via-ini-files3659639
Ref: 13a13659639
Node: 自定义默认的Python版本3660321
Ref: using/windows customizing-default-python-versions3660430
Ref: 13a23660430
Node: 诊断3663731
Ref: using/windows diagnostics3663826
Ref: 13a33663826
Node: 查找模块3664170
Ref: using/windows finding-modules3664309
Ref: 4b83664309
Ref: using/windows id13664309
Ref: 13a43664309
Node: 附加模块3670150
Ref: using/windows additional-modules3670280
Ref: 13a53670280
Node: PyWin323670630
Ref: using/windows pywin323670704
Ref: 13a73670704
Ref: PyWin32-Footnote-13671259
Ref: PyWin32-Footnote-23671300
Ref: PyWin32-Footnote-33671400
Ref: PyWin32-Footnote-43671474
Ref: PyWin32-Footnote-53671568
Ref: PyWin32-Footnote-63671626
Node: cx_Freeze3671675
Ref: using/windows cx-freeze3671764
Ref: 13a83671764
Ref: cx_Freeze-Footnote-13672107
Node: WConio3672159
Ref: using/windows wconio3672232
Ref: 13aa3672232
Ref: WConio-Footnote-13672545
Node: 在Windows上编译Python3672605
Ref: using/windows compiling-python-on-windows3672735
Ref: 13ab3672735
Ref: 在Windows上编译Python-Footnote-13673634
Ref: 在Windows上编译Python-Footnote-23673683
Ref: 在Windows上编译Python-Footnote-33673750
Node: 其他平台3673798
Ref: using/windows other-platforms3673907
Ref: 13ad3673907
Ref: 其他平台-Footnote-13674411
Ref: 其他平台-Footnote-23674460
Ref: 其他平台-Footnote-33674501
Ref: 其他平台-Footnote-43674529
Ref: 其他平台-Footnote-53674617
Ref: 其他平台-Footnote-63674671
Node: 在苹果系统上使用 Python3674721
Ref: using/mac doc3674884
Ref: 13ae3674884
Ref: using/mac using-on-mac3674884
Ref: 13af3674884
Ref: using/mac using-python-on-a-macintosh3674884
Ref: 13b03674884
Node: 获取和安装 MacPython3675354
Ref: using/mac getting-and-installing-macpython3675459
Ref: 13b13675459
Ref: using/mac getting-osx3675459
Ref: 13b23675459
Node: 如何运行 Python 脚本3677250
Ref: using/mac how-to-run-a-python-script3677377
Ref: 13b33677377
Node: 运行有图形界面的脚本3678809
Ref: using/mac osx-gui-scripts3678951
Ref: 13b53678951
Ref: using/mac running-scripts-with-a-gui3678951
Ref: 13b63678951
Node: 配置3679361
Ref: using/mac configuration3679468
Ref: 13b73679468
Node: IDE3679984
Ref: using/mac ide3680124
Ref: 13b43680124
Ref: using/mac the-ide3680124
Ref: 13b93680124
Node: 安装额外的 Python 包3680311
Ref: using/mac installing-additional-python-packages3680454
Ref: 13ba3680454
Ref: using/mac mac-package-manager3680454
Ref: 13b83680454
Node: Mac 上的图形界面编程3680812
Ref: using/mac gui-programming-on-the-mac3680989
Ref: 13bb3680989
Node: 在 Mac 上分发 Python 应用程序3681948
Ref: using/mac distributing-python-applications-on-the-mac3682111
Ref: 13bc3682111
Node: 其他资源3682374
Ref: using/mac other-resources3682500
Ref: 13bd3682500
Node: 编辑器和集成开发环境3682785
Ref: using/editors doc3682913
Ref: 13be3682913
Ref: using/editors editors3682913
Ref: 13bf3682913
Ref: using/editors editors-and-ides3682913
Ref: 13c03682913
Ref: 编辑器和集成开发环境-Footnote-13683262
Ref: 编辑器和集成开发环境-Footnote-23683311
Ref: 编辑器和集成开发环境-Footnote-33683362
Node: Python语言参考3683433
Ref: reference/index doc3683546
Ref: 13c13683546
Ref: reference/index reference-index3683546
Ref: 120c3683546
Ref: reference/index the-python-language-reference3683546
Ref: 13c23683546
Node: 概述<5>3684327
Ref: reference/introduction doc3684412
Ref: 13c33684412
Ref: reference/introduction id13684412
Ref: 13c43684412
Ref: reference/introduction introduction3684412
Ref: 13c53684412
Node: 其他实现3685975
Ref: reference/introduction alternate-implementations3686048
Ref: 13c63686048
Ref: reference/introduction implementations3686048
Ref: 13473686048
Ref: 其他实现-Footnote-13687835
Ref: 其他实现-Footnote-23687866
Ref: 其他实现-Footnote-33687903
Ref: 其他实现-Footnote-43687934
Node: 标注3687959
Ref: reference/introduction id23688032
Ref: 13c73688032
Ref: reference/introduction notation3688032
Ref: 13c83688032
Ref: reference/introduction grammar-token-name3688158
Ref: 13c93688158
Ref: reference/introduction grammar-token-lc-letter3688206
Ref: 13ca3688206
Node: 词法分析3689895
Ref: reference/lexical_analysis doc3690001
Ref: 13cb3690001
Ref: reference/lexical_analysis lexical3690001
Ref: 13cc3690001
Ref: reference/lexical_analysis lexical-analysis3690001
Ref: 13cd3690001
Ref: 词法分析-Footnote-13690615
Node: 行结构3690664
Ref: reference/lexical_analysis id13690743
Ref: 13ce3690743
Ref: reference/lexical_analysis line-structure3690743
Ref: 13cf3690743
Node: 逻辑行3690988
Ref: reference/lexical_analysis id23691061
Ref: 13d03691061
Ref: reference/lexical_analysis logical-lines3691061
Ref: 13d13691061
Node: 物理行3691376
Ref: reference/lexical_analysis id33691464
Ref: 13d23691464
Ref: reference/lexical_analysis physical-lines3691464
Ref: 13d33691464
Node: 注释3692095
Ref: reference/lexical_analysis comments3692186
Ref: 13d43692186
Ref: reference/lexical_analysis id43692186
Ref: 13d53692186
Node: 编码声明3692451
Ref: reference/lexical_analysis encoding-declarations3692551
Ref: 13d63692551
Ref: reference/lexical_analysis encodings3692551
Ref: 13d73692551
Node: 显式的行拼接3693524
Ref: reference/lexical_analysis explicit-joining3693636
Ref: 13d83693636
Ref: reference/lexical_analysis explicit-line-joining3693636
Ref: 13d93693636
Node: 隐式的行拼接3694477
Ref: reference/lexical_analysis implicit-joining3694586
Ref: 13da3694586
Ref: reference/lexical_analysis implicit-line-joining3694586
Ref: 13db3694586
Node: 空白行3695323
Ref: reference/lexical_analysis blank-lines3695420
Ref: 13dc3695420
Ref: reference/lexical_analysis id53695420
Ref: 13dd3695420
Node: 缩进3695845
Ref: reference/lexical_analysis id63695945
Ref: 13de3695945
Ref: reference/lexical_analysis indentation3695945
Ref: 13df3695945
Node: 形符之间的空白3698844
Ref: reference/lexical_analysis whitespace3698926
Ref: 13e03698926
Ref: reference/lexical_analysis whitespace-between-tokens3698926
Ref: 13e13698926
Node: 其他形符3699269
Ref: reference/lexical_analysis id73699378
Ref: 13e23699378
Ref: reference/lexical_analysis other-tokens3699378
Ref: 13e33699378
Node: 标识符和关键字3699752
Ref: reference/lexical_analysis identifiers3699861
Ref: 13e43699861
Ref: reference/lexical_analysis identifiers-and-keywords3699861
Ref: 13e53699861
Ref: reference/lexical_analysis grammar-token-identifier3700598
Ref: 13e63700598
Ref: reference/lexical_analysis grammar-token-id-start3700644
Ref: 13e73700644
Ref: reference/lexical_analysis grammar-token-id-continue3700793
Ref: 13e83700793
Ref: reference/lexical_analysis grammar-token-xid-start3700941
Ref: 13e93700941
Ref: reference/lexical_analysis grammar-token-xid-continue3701048
Ref: 13ea3701048
Ref: 标识符和关键字-Footnote-13701958
Ref: 标识符和关键字-Footnote-23702007
Ref: 标识符和关键字-Footnote-33702056
Node: 关键字3702118
Ref: reference/lexical_analysis id83702215
Ref: 13eb3702215
Ref: reference/lexical_analysis keywords3702215
Ref: 13ec3702215
Node: 保留的标识符类3702788
Ref: reference/lexical_analysis id-classes3702885
Ref: 13ed3702885
Ref: reference/lexical_analysis reserved-classes-of-identifiers3702885
Ref: 13ee3702885
Node: 字面值3704261
Ref: reference/lexical_analysis id93704367
Ref: 13f03704367
Ref: reference/lexical_analysis literals3704367
Ref: 13f13704367
Node: 字符串和字节串字面值3704642
Ref: reference/lexical_analysis string-and-bytes-literals3704751
Ref: 13f23704751
Ref: reference/lexical_analysis strings3704751
Ref: 13f33704751
Ref: reference/lexical_analysis grammar-token-stringliteral3704874
Ref: 13f43704874
Ref: reference/lexical_analysis grammar-token-stringprefix3704940
Ref: 13f53704940
Ref: reference/lexical_analysis grammar-token-shortstring3705080
Ref: 13f63705080
Ref: reference/lexical_analysis grammar-token-longstring3705157
Ref: 13f73705157
Ref: reference/lexical_analysis grammar-token-shortstringitem3705240
Ref: 13f83705240
Ref: reference/lexical_analysis grammar-token-longstringitem3705299
Ref: 13f93705299
Ref: reference/lexical_analysis grammar-token-shortstringchar3705357
Ref: 13fa3705357
Ref: reference/lexical_analysis grammar-token-longstringchar3705440
Ref: 13fb3705440
Ref: reference/lexical_analysis grammar-token-stringescapeseq3705499
Ref: 13fc3705499
Ref: reference/lexical_analysis grammar-token-bytesliteral3705552
Ref: 13fd3705552
Ref: reference/lexical_analysis grammar-token-bytesprefix3705612
Ref: 13fe3705612
Ref: reference/lexical_analysis grammar-token-shortbytes3705702
Ref: 13ff3705702
Ref: reference/lexical_analysis grammar-token-longbytes3705776
Ref: 14003705776
Ref: reference/lexical_analysis grammar-token-shortbytesitem3705856
Ref: 14013705856
Ref: reference/lexical_analysis grammar-token-longbytesitem3705912
Ref: 14023705912
Ref: reference/lexical_analysis grammar-token-shortbyteschar3705967
Ref: 14033705967
Ref: reference/lexical_analysis grammar-token-longbyteschar3706048
Ref: 14043706048
Ref: reference/lexical_analysis grammar-token-bytesescapeseq3706105
Ref: 14053706105
Ref: 字符串和字节串字面值-Footnote-13713274
Ref: 字符串和字节串字面值-Footnote-23713323
Node: 字符串字面值拼接3713398
Ref: reference/lexical_analysis string-concatenation3713543
Ref: 14063713543
Ref: reference/lexical_analysis string-literal-concatenation3713543
Ref: 14073713543
Node: 格式化字符串字面值3714458
Ref: reference/lexical_analysis f-strings3714588
Ref: 15d3714588
Ref: reference/lexical_analysis formatted-string-literals3714588
Ref: 14083714588
Ref: reference/lexical_analysis grammar-token-f-string3715158
Ref: 14093715158
Ref: reference/lexical_analysis grammar-token-replacement-field3715235
Ref: 140a3715235
Ref: reference/lexical_analysis grammar-token-f-expression3715324
Ref: 140b3715324
Ref: reference/lexical_analysis grammar-token-conversion3715519
Ref: 140c3715519
Ref: reference/lexical_analysis grammar-token-format-spec3715562
Ref: 140d3715562
Ref: reference/lexical_analysis grammar-token-literal-char3715632
Ref: 140e3715632
Ref: 格式化字符串字面值-Footnote-13720443
Node: 数字字面值3720492
Ref: reference/lexical_analysis numbers3720616
Ref: 140f3720616
Ref: reference/lexical_analysis numeric-literals3720616
Ref: 14103720616
Node: 整型数字面值3720958
Ref: reference/lexical_analysis integer-literals3721073
Ref: 14113721073
Ref: reference/lexical_analysis integers3721073
Ref: 14123721073
Ref: reference/lexical_analysis grammar-token-integer3721176
Ref: 14133721176
Ref: reference/lexical_analysis grammar-token-decinteger3721248
Ref: 14143721248
Ref: reference/lexical_analysis grammar-token-bininteger3721318
Ref: 14153721318
Ref: reference/lexical_analysis grammar-token-octinteger3721374
Ref: 14163721374
Ref: reference/lexical_analysis grammar-token-hexinteger3721430
Ref: 14173721430
Ref: reference/lexical_analysis grammar-token-nonzerodigit3721486
Ref: 14183721486
Ref: reference/lexical_analysis grammar-token-digit3721518
Ref: 14193721518
Ref: reference/lexical_analysis grammar-token-bindigit3721550
Ref: 141a3721550
Ref: reference/lexical_analysis grammar-token-octdigit3721582
Ref: 141b3721582
Ref: reference/lexical_analysis grammar-token-hexdigit3721614
Ref: 141c3721614
Node: 浮点数字面值3722421
Ref: reference/lexical_analysis floating3722536
Ref: 141d3722536
Ref: reference/lexical_analysis floating-point-literals3722536
Ref: 141e3722536
Ref: reference/lexical_analysis grammar-token-floatnumber3722639
Ref: 141f3722639
Ref: reference/lexical_analysis grammar-token-pointfloat3722689
Ref: 14203722689
Ref: reference/lexical_analysis grammar-token-exponentfloat3722749
Ref: 14213722749
Ref: reference/lexical_analysis grammar-token-digitpart3722806
Ref: 14223722806
Ref: reference/lexical_analysis grammar-token-fraction3722850
Ref: 14233722850
Ref: reference/lexical_analysis grammar-token-exponent3722887
Ref: 14243722887
Node: 虚数字面值3723402
Ref: reference/lexical_analysis imaginary3723490
Ref: 14253723490
Ref: reference/lexical_analysis imaginary-literals3723490
Ref: 14263723490
Ref: reference/lexical_analysis grammar-token-imagnumber3723585
Ref: 14273723585
Node: 运算符3723980
Ref: reference/lexical_analysis id113724074
Ref: 14283724074
Ref: reference/lexical_analysis operators3724074
Ref: 14293724074
Node: 分隔符3724301
Ref: reference/lexical_analysis delimiters3724377
Ref: 142a3724377
Ref: reference/lexical_analysis id123724377
Ref: 142b3724377
Node: 数据模型3725226
Ref: reference/datamodel doc3725335
Ref: 142c3725335
Ref: reference/datamodel data-model3725335
Ref: 142d3725335
Ref: reference/datamodel datamodel3725335
Ref: f3b3725335
Node: 对象、值与类型3725465
Ref: reference/datamodel objects3725568
Ref: 142e3725568
Ref: reference/datamodel objects-values-and-types3725568
Ref: 142f3725568
Ref: 对象、值与类型-Footnote-13729888
Node: 标准类型层级结构3730081
Ref: reference/datamodel the-standard-type-hierarchy3730211
Ref: 14303730211
Ref: reference/datamodel types3730211
Ref: 14313730211
Ref: reference/datamodel frame-objects3760784
Ref: 14423760784
Ref: reference/datamodel frame clear3762443
Ref: 8143762443
Ref: reference/datamodel traceback-objects3762894
Ref: 33f3762894
Ref: reference/datamodel slice indices3765254
Ref: 9673765254
Node: 特殊方法名称3766718
Ref: reference/datamodel special-method-names3766833
Ref: 14433766833
Ref: reference/datamodel specialnames3766833
Ref: 5163766833
Ref: 特殊方法名称-Footnote-13768465
Node: 基本定制3768747
Ref: reference/datamodel basic-customization3768844
Ref: 14443768844
Ref: reference/datamodel customization3768844
Ref: 14453768844
Ref: reference/datamodel object __new__3768883
Ref: 8923768883
Ref: reference/datamodel object __init__3770262
Ref: d663770262
Ref: reference/datamodel object __del__3771026
Ref: 9273771026
Ref: reference/datamodel object __repr__3773676
Ref: 3473773676
Ref: reference/datamodel object __str__3774435
Ref: e3f3774435
Ref: reference/datamodel object __bytes__3775037
Ref: 14473775037
Ref: reference/datamodel object __format__3775210
Ref: 9563775210
Ref: reference/datamodel richcmpfuncs3776196
Ref: 14483776196
Ref: reference/datamodel object __lt__3776196
Ref: c3c3776196
Ref: reference/datamodel object __le__3776236
Ref: ca83776236
Ref: reference/datamodel object __eq__3776276
Ref: 3483776276
Ref: reference/datamodel object __ne__3776316
Ref: e5e3776316
Ref: reference/datamodel object __gt__3776356
Ref: ca93776356
Ref: reference/datamodel object __ge__3776396
Ref: caa3776396
Ref: reference/datamodel object __hash__3778612
Ref: 3493778612
Ref: reference/datamodel object __bool__3782503
Ref: c703782503
Node: 自定义属性访问3782940
Ref: reference/datamodel attribute-access3783064
Ref: 14493783064
Ref: reference/datamodel customizing-attribute-access3783064
Ref: 144a3783064
Ref: reference/datamodel object __getattr__3783243
Ref: 3233783243
Ref: reference/datamodel object __getattribute__3784450
Ref: 44f3784450
Ref: reference/datamodel object __setattr__3785408
Ref: e343785408
Ref: reference/datamodel object __delattr__3785962
Ref: 14403785962
Ref: reference/datamodel object __dir__3786289
Ref: 3243786289
Node: 自定义模块属性访问3786609
Ref: reference/datamodel customizing-module-attribute-access3786718
Ref: 144d3786718
Ref: 自定义模块属性访问-Footnote-13788694
Node: 实现描述器3788743
Ref: reference/datamodel descriptors3788876
Ref: 4f13788876
Ref: reference/datamodel implementing-descriptors3788876
Ref: 144e3788876
Ref: reference/datamodel object __get__3789264
Ref: 144b3789264
Ref: reference/datamodel object __set__3790073
Ref: 144f3790073
Ref: reference/datamodel object __delete__3790416
Ref: 14503790416
Ref: reference/datamodel object __set_name__3790549
Ref: 4f03790549
Ref: 实现描述器-Footnote-13791635
Node: 调用描述器3791684
Ref: reference/datamodel descriptor-invocation3791799
Ref: 14513791799
Ref: reference/datamodel invoking-descriptors3791799
Ref: 14523791799
Node: __slots__3794752
Ref: reference/datamodel id33794843
Ref: 14533794843
Ref: reference/datamodel slots3794843
Ref: 14543794843
Ref: reference/datamodel object __slots__3795190
Ref: e353795190
Node: 使用 __slots__ 的注意事项3795517
Ref: reference/datamodel notes-on-using-slots3795595
Ref: 14553795595
Node: 自定义类创建3798086
Ref: reference/datamodel class-customization3798228
Ref: 4ed3798228
Ref: reference/datamodel customizing-class-creation3798228
Ref: 14563798228
Ref: reference/datamodel object __init_subclass__3798601
Ref: 4ea3798601
Node: 元类3799930
Ref: reference/datamodel id43800017
Ref: 14573800017
Ref: reference/datamodel metaclasses3800017
Ref: 14583800017
Node: 解析 MRO 条目3800919
Ref: reference/datamodel resolving-mro-entries3801036
Ref: 14593801036
Ref: 解析 MRO 条目-Footnote-13801531
Node: 确定适当的元类3801580
Ref: reference/datamodel determining-the-appropriate-metaclass3801712
Ref: 145a3801712
Node: 准备类命名空间3802490
Ref: reference/datamodel prepare3802620
Ref: 5053802620
Ref: reference/datamodel preparing-the-class-namespace3802620
Ref: 145b3802620
Ref: 准备类命名空间-Footnote-13803457
Node: 执行类主体3803506
Ref: reference/datamodel executing-the-class-body3803630
Ref: 145c3803630
Node: 创建类对象3804268
Ref: reference/datamodel class-object-creation3804386
Ref: 4ec3804386
Ref: reference/datamodel creating-the-class-object3804386
Ref: 145d3804386
Ref: 创建类对象-Footnote-13806589
Node: 元类的作用3806638
Ref: reference/datamodel uses-for-metaclasses3806732
Ref: 145e3806732
Node: 自定义实例及子类检查3806977
Ref: reference/datamodel customizing-instance-and-subclass-checks3807116
Ref: 145f3807116
Ref: reference/datamodel class __instancecheck__3807509
Ref: 14603807509
Ref: reference/datamodel class __subclasscheck__3807757
Ref: 14613807757
Ref: 自定义实例及子类检查-Footnote-13808651
Node: 模拟泛型类型3808700
Ref: reference/datamodel emulating-generic-types3808842
Ref: 14623808842
Ref: reference/datamodel object __class_getitem__3809008
Ref: 3303809008
Ref: 模拟泛型类型-Footnote-13809488
Ref: 模拟泛型类型-Footnote-23809537
Node: 模拟可调用对象3809586
Ref: reference/datamodel callable-types3809716
Ref: 14633809716
Ref: reference/datamodel emulating-callable-objects3809716
Ref: 14643809716
Ref: reference/datamodel object __call__3809772
Ref: 143e3809772
Node: 模拟容器类型3810028
Ref: reference/datamodel emulating-container-types3810158
Ref: 14653810158
Ref: reference/datamodel sequence-types3810158
Ref: 14663810158
Ref: reference/datamodel object __len__3812081
Ref: dd33812081
Ref: reference/datamodel object __length_hint__3812789
Ref: 8153812789
Ref: reference/datamodel object __getitem__3813521
Ref: 2803813521
Ref: reference/datamodel object __setitem__3814326
Ref: c6a3814326
Ref: reference/datamodel object __delitem__3814731
Ref: c6b3814731
Ref: reference/datamodel object __missing__3815104
Ref: b433815104
Ref: reference/datamodel object __iter__3815295
Ref: 5173815295
Ref: reference/datamodel object __reversed__3815726
Ref: 5373815726
Ref: reference/datamodel object __contains__3816602
Ref: d303816602
Node: 模拟数字类型3817136
Ref: reference/datamodel emulating-numeric-types3817274
Ref: 146f3817274
Ref: reference/datamodel numeric-types3817274
Ref: 14703817274
Ref: reference/datamodel object __add__3817502
Ref: 14673817502
Ref: reference/datamodel object __sub__3817543
Ref: 14713817543
Ref: reference/datamodel object __mul__3817584
Ref: 14693817584
Ref: reference/datamodel object __matmul__3817625
Ref: 6513817625
Ref: reference/datamodel object __truediv__3817669
Ref: 78f3817669
Ref: reference/datamodel object __floordiv__3817714
Ref: e3d3817714
Ref: reference/datamodel object __mod__3817760
Ref: 14723817760
Ref: reference/datamodel object __divmod__3817801
Ref: 7903817801
Ref: reference/datamodel object __pow__3817845
Ref: 14733817845
Ref: reference/datamodel object __lshift__3817896
Ref: 14743817896
Ref: reference/datamodel object __rshift__3817940
Ref: 14753817940
Ref: reference/datamodel object __and__3817984
Ref: 14763817984
Ref: reference/datamodel object __xor__3818025
Ref: 14773818025
Ref: reference/datamodel object __or__3818066
Ref: 14783818066
Ref: reference/datamodel object __radd__3818949
Ref: 14683818949
Ref: reference/datamodel object __rsub__3818991
Ref: 14793818991
Ref: reference/datamodel object __rmul__3819033
Ref: 146a3819033
Ref: reference/datamodel object __rmatmul__3819075
Ref: 6523819075
Ref: reference/datamodel object __rtruediv__3819120
Ref: 147a3819120
Ref: reference/datamodel object __rfloordiv__3819166
Ref: 147b3819166
Ref: reference/datamodel object __rmod__3819213
Ref: 6b83819213
Ref: reference/datamodel object __rdivmod__3819255
Ref: 147c3819255
Ref: reference/datamodel object __rpow__3819300
Ref: 147d3819300
Ref: reference/datamodel object __rlshift__3819352
Ref: 147e3819352
Ref: reference/datamodel object __rrshift__3819397
Ref: 147f3819397
Ref: reference/datamodel object __rand__3819442
Ref: 14803819442
Ref: reference/datamodel object __rxor__3819484
Ref: 14813819484
Ref: reference/datamodel object __ror__3819526
Ref: 14823819526
Ref: reference/datamodel object __iadd__3820590
Ref: e773820590
Ref: reference/datamodel object __isub__3820632
Ref: e783820632
Ref: reference/datamodel object __imul__3820674
Ref: 146b3820674
Ref: reference/datamodel object __imatmul__3820716
Ref: 6533820716
Ref: reference/datamodel object __itruediv__3820761
Ref: 14833820761
Ref: reference/datamodel object __ifloordiv__3820807
Ref: 14843820807
Ref: reference/datamodel object __imod__3820854
Ref: 14853820854
Ref: reference/datamodel object __ipow__3820896
Ref: 14863820896
Ref: reference/datamodel object __ilshift__3820948
Ref: 14873820948
Ref: reference/datamodel object __irshift__3820993
Ref: 14883820993
Ref: reference/datamodel object __iand__3821038
Ref: 14893821038
Ref: reference/datamodel object __ixor__3821080
Ref: 148a3821080
Ref: reference/datamodel object __ior__3821122
Ref: 148b3821122
Ref: reference/datamodel object __neg__3822341
Ref: 148d3822341
Ref: reference/datamodel object __pos__3822375
Ref: 148e3822375
Ref: reference/datamodel object __abs__3822409
Ref: 148f3822409
Ref: reference/datamodel object __invert__3822443
Ref: 14903822443
Ref: reference/datamodel object __complex__3822584
Ref: 18e3822584
Ref: reference/datamodel object __int__3822622
Ref: 18c3822622
Ref: reference/datamodel object __float__3822656
Ref: 18d3822656
Ref: reference/datamodel object __index__3822850
Ref: 18b3822850
Ref: reference/datamodel object __round__3823464
Ref: 14923823464
Ref: reference/datamodel object __trunc__3823511
Ref: 14933823511
Ref: reference/datamodel object __floor__3823547
Ref: 14943823547
Ref: reference/datamodel object __ceil__3823583
Ref: 14953823583
Ref: 模拟数字类型-Footnote-13824126
Ref: 模拟数字类型-Footnote-23824389
Node: with 语句上下文管理器3824588
Ref: reference/datamodel context-managers3824726
Ref: 14963824726
Ref: reference/datamodel with-statement-context-managers3824726
Ref: 14973824726
Ref: reference/datamodel object __enter__3825373
Ref: c9d3825373
Ref: reference/datamodel object __exit__3825589
Ref: c9e3825589
Ref: with 语句上下文管理器-Footnote-13826322
Node: 特殊方法查找3826371
Ref: reference/datamodel special-lookup3826482
Ref: 144c3826482
Ref: reference/datamodel special-method-lookup3826482
Ref: 14993826482
Node: 协程3829020
Ref: reference/datamodel coroutines3829102
Ref: 149a3829102
Node: 可等待对象3829223
Ref: reference/datamodel awaitable-objects3829302
Ref: 149b3829302
Ref: reference/datamodel object __await__3829769
Ref: 64b3829769
Ref: 可等待对象-Footnote-13830148
Node: 协程对象3830197
Ref: reference/datamodel coroutine-objects3830300
Ref: 143d3830300
Ref: reference/datamodel id73830300
Ref: 149c3830300
Ref: reference/datamodel coroutine send3831051
Ref: 149e3831051
Ref: reference/datamodel coroutine throw3831532
Ref: 14a03831532
Ref: reference/datamodel coroutine close3832033
Ref: 14a23832033
Node: 异步迭代器3832535
Ref: reference/datamodel async-iterators3832647
Ref: 64f3832647
Ref: reference/datamodel asynchronous-iterators3832647
Ref: 14a43832647
Ref: reference/datamodel object __aiter__3832834
Ref: 48f3832834
Ref: reference/datamodel object __anext__3832924
Ref: 14a53832924
Node: 异步上下文管理器3833774
Ref: reference/datamodel async-context-managers3833865
Ref: 14a63833865
Ref: reference/datamodel asynchronous-context-managers3833865
Ref: 14a73833865
Ref: reference/datamodel object __aenter__3834141
Ref: 14a83834141
Ref: reference/datamodel object __aexit__3834299
Ref: 14a93834299
Node: 执行模型3834775
Ref: reference/executionmodel doc3834884
Ref: 14aa3834884
Ref: reference/executionmodel execmodel3834884
Ref: 14ab3834884
Ref: reference/executionmodel execution-model3834884
Ref: 14ac3834884
Node: 程序的结构3834986
Ref: reference/executionmodel prog-structure3835074
Ref: 14ad3835074
Ref: reference/executionmodel structure-of-a-program3835074
Ref: 14ae3835074
Node: 命名与绑定3835887
Ref: reference/executionmodel naming3835993
Ref: 14af3835993
Ref: reference/executionmodel naming-and-binding3835993
Ref: 14b03835993
Node: 名称的绑定3836153
Ref: reference/executionmodel bind-names3836244
Ref: 14b13836244
Ref: reference/executionmodel binding-of-names3836244
Ref: 14b23836244
Node: 名称的解析3837622
Ref: reference/executionmodel resolution-of-names3837758
Ref: 14b33837758
Ref: reference/executionmodel resolve-names3837758
Ref: 14b43837758
Node: 内置命名空间和受限的执行3841013
Ref: reference/executionmodel builtins-and-restricted-execution3841158
Ref: 14b53841158
Ref: reference/executionmodel restrict-exec3841158
Ref: 14b63841158
Node: 与动态特性的交互3841981
Ref: reference/executionmodel dynamic-features3842102
Ref: 14b73842102
Ref: reference/executionmodel interaction-with-dynamic-features3842102
Ref: 14b83842102
Ref: 与动态特性的交互-Footnote-13842823
Node: 异常<2>3842942
Ref: reference/executionmodel exceptions3843024
Ref: 14b93843024
Ref: reference/executionmodel id23843024
Ref: 14ba3843024
Node: 导入系统3844890
Ref: reference/import doc3844996
Ref: 14bb3844996
Ref: reference/import importsystem3844996
Ref: 143f3844996
Ref: reference/import the-import-system3844996
Ref: 14bc3844996
Ref: 导入系统-Footnote-13847394
Ref: 导入系统-Footnote-23847445
Ref: 导入系统-Footnote-33847494
Node: importlib<7>3847543
Ref: reference/import importlib3847619
Ref: 14bf3847619
Node: 包<2>3847970
Ref: reference/import packages3848061
Ref: 14c03848061
Node: 常规包3849355
Ref: reference/import regular-packages3849431
Ref: 14c13849431
Node: 命名空间包3850544
Ref: reference/import namespace-packages3850620
Ref: 14c43850620
Ref: 命名空间包-Footnote-13851857
Node: 搜索3851906
Ref: reference/import searching3851991
Ref: 14c63851991
Node: 模块缓存3852777
Ref: reference/import the-module-cache3852862
Ref: 14c73852862
Node: 查找器和加载器3854317
Ref: reference/import finders-and-loaders3854423
Ref: 14c83854423
Ref: reference/import id23854423
Ref: 14c93854423
Node: 导入钩子3856074
Ref: reference/import import-hooks3856177
Ref: 14ce3856177
Node: 元路径3856984
Ref: reference/import the-meta-path3857057
Ref: 14cf3857057
Node: 加载3859827
Ref: reference/import loading3859930
Ref: 14d13859930
Ref: 加载-Footnote-13863090
Node: 加载器3863431
Ref: reference/import loaders3863501
Ref: 14d33863501
Node: 子模块3866501
Ref: reference/import submodules3866598
Ref: 14d43866598
Node: 模块规格说明3867855
Ref: reference/import module-spec3867970
Ref: 14d53867970
Node: 导入相关的模块属性3868738
Ref: reference/import import-mod-attrs3868859
Ref: 14d23868859
Ref: reference/import import-related-module-attributes3868859
Ref: 14d73868859
Ref: reference/import __name__3869070
Ref: d1a3869070
Ref: reference/import __loader__3869232
Ref: 95e3869232
Ref: reference/import __package__3869488
Ref: 95d3869488
Ref: reference/import __spec__3870214
Ref: ec83870214
Ref: reference/import __path__3870789
Ref: 129f3870789
Ref: reference/import __file__3871291
Ref: ec73871291
Ref: reference/import __cached__3871313
Ref: b3a3871313
Ref: 导入相关的模块属性-Footnote-13872223
Ref: 导入相关的模块属性-Footnote-23872272
Ref: 导入相关的模块属性-Footnote-33872321
Node: module __path__3872370
Ref: reference/import module-path3872487
Ref: 14db3872487
Ref: reference/import package-path-rules3872487
Ref: 14da3872487
Ref: module __path__-Footnote-13873564
Ref: module __path__-Footnote-23873613
Node: 模块的 repr3873662
Ref: reference/import module-reprs3873779
Ref: 14dc3873779
Node: 已缓存字节码的失效3875314
Ref: reference/import cached-bytecode-invalidation3875407
Ref: 14dd3875407
Ref: reference/import pyc-invalidation3875407
Ref: 3323875407
Node: 基于路径的查找器3876755
Ref: reference/import the-path-based-finder3876876
Ref: 14de3876876
Node: 路径条目查找器3879209
Ref: reference/import path-entry-finders3879327
Ref: 14e03879327
Ref: 路径条目查找器-Footnote-13884155
Node: 路径条目查找器协议3884396
Ref: reference/import path-entry-finder-protocol3884514
Ref: 14e23884514
Node: 替换标准导入系统3886573
Ref: reference/import replacing-the-standard-import-system3886703
Ref: 14e33886703
Node: 包相对导入3887529
Ref: reference/import package-relative-imports3887666
Ref: 14e43887666
Ref: reference/import relativeimports3887666
Ref: 14e53887666
Node: 有关 __main__ 的特殊事项3888795
Ref: reference/import special-considerations-for-main3888923
Ref: 14e63888923
Node: __main__ __spec__3889490
Ref: reference/import id53889575
Ref: 14e73889575
Ref: reference/import main-spec3889575
Ref: 14d93889575
Node: 开放问题项3890926
Ref: reference/import open-issues3891051
Ref: 14e83891051
Ref: 开放问题项-Footnote-13891657
Node: 参考文献3891706
Ref: reference/import references3891791
Ref: 14e93891791
Ref: 参考文献-Footnote-13892898
Ref: 参考文献-Footnote-23892950
Ref: 参考文献-Footnote-33892999
Ref: 参考文献-Footnote-43893048
Ref: 参考文献-Footnote-53893097
Ref: 参考文献-Footnote-63893146
Ref: 参考文献-Footnote-73893195
Ref: 参考文献-Footnote-83893244
Ref: 参考文献-Footnote-93893293
Ref: 参考文献-Footnote-103893342
Node: 表达式3893392
Ref: reference/expressions doc3893498
Ref: 14ea3893498
Ref: reference/expressions expressions3893498
Ref: 14eb3893498
Ref: reference/expressions id13893498
Ref: 14ec3893498
Ref: reference/expressions grammar-token-name3893766
Ref: 14ed3893766
Node: 算术转换3894243
Ref: reference/expressions arithmetic-conversions3894316
Ref: 14ee3894316
Ref: reference/expressions conversions3894316
Ref: 14ef3894316
Node: 原子3894932
Ref: reference/expressions atoms3895020
Ref: 14f03895020
Ref: reference/expressions id23895020
Ref: 14f13895020
Ref: reference/expressions grammar-token-atom3895253
Ref: 14f23895253
Ref: reference/expressions grammar-token-enclosure3895305
Ref: 14f33895305
Node: 标识符（名称）3895680
Ref: reference/expressions atom-identifiers3895765
Ref: 13ef3895765
Ref: reference/expressions identifiers-names3895765
Ref: 14f43895765
Node: 字面值<2>3896902
Ref: reference/expressions atom-literals3897017
Ref: 14f53897017
Ref: reference/expressions literals3897017
Ref: 14f63897017
Ref: reference/expressions grammar-token-literal3897127
Ref: 14f73897127
Node: 带圆括号的形式3897750
Ref: reference/expressions parenthesized3897877
Ref: 14f83897877
Ref: reference/expressions parenthesized-forms3897877
Ref: 14f93897877
Ref: reference/expressions grammar-token-parenth-form3898005
Ref: 14fa3898005
Node: 列表、集合与字典的显示3898777
Ref: reference/expressions comprehensions3898904
Ref: 14fb3898904
Ref: reference/expressions displays-for-lists-sets-and-dictionaries3898904
Ref: 14fc3898904
Ref: reference/expressions grammar-token-comprehension3899273
Ref: 14fd3899273
Ref: reference/expressions grammar-token-comp-for3899327
Ref: 14fe3899327
Ref: reference/expressions grammar-token-comp-iter3899403
Ref: 14ff3899403
Ref: reference/expressions grammar-token-comp-if3899445
Ref: 15003899445
Ref: 列表、集合与字典的显示-Footnote-13901454
Node: 列表显示3901503
Ref: reference/expressions list-displays3901621
Ref: 15013901621
Ref: reference/expressions lists3901621
Ref: 15023901621
Ref: reference/expressions grammar-token-list-display3901738
Ref: 15033901738
Node: 集合显示3902131
Ref: reference/expressions set3902228
Ref: 15043902228
Ref: reference/expressions set-displays3902228
Ref: 15053902228
Ref: reference/expressions grammar-token-set-display3902369
Ref: 15063902369
Node: 字典显示3902845
Ref: reference/expressions dict3902951
Ref: 6573902951
Ref: reference/expressions dictionary-displays3902951
Ref: 15073902951
Ref: reference/expressions grammar-token-dict-display3903072
Ref: 15083903072
Ref: reference/expressions grammar-token-key-datum-list3903146
Ref: 15093903146
Ref: reference/expressions grammar-token-key-datum3903207
Ref: 150a3903207
Ref: reference/expressions grammar-token-dict-comprehension3903276
Ref: 150b3903276
Ref: 字典显示-Footnote-13904895
Ref: 字典显示-Footnote-23904944
Node: 生成器表达式<2>3904993
Ref: reference/expressions generator-expressions3905102
Ref: 150c3905102
Ref: reference/expressions genexpr3905102
Ref: 150d3905102
Ref: reference/expressions grammar-token-generator-expression3905228
Ref: 150e3905228
Node: yield 表达式3906981
Ref: reference/expressions yield-expressions3907069
Ref: 150f3907069
Ref: reference/expressions yieldexpr3907069
Ref: 15103907069
Ref: reference/expressions grammar-token-yield-atom3907115
Ref: 15113907115
Ref: reference/expressions grammar-token-yield-expression3907166
Ref: 15123907166
Ref: yield 表达式-Footnote-13911559
Ref: yield 表达式-Footnote-23911608
Ref: yield 表达式-Footnote-33911657
Ref: yield 表达式-Footnote-43911706
Ref: yield 表达式-Footnote-53911755
Node: 生成器-迭代器的方法3911804
Ref: reference/expressions generator-iterator-methods3911899
Ref: 15163911899
Ref: reference/expressions generator-methods3911899
Ref: 149d3911899
Ref: reference/expressions generator __next__3912185
Ref: 12ea3912185
Ref: reference/expressions generator send3912861
Ref: 149f3912861
Ref: reference/expressions generator throw3913369
Ref: 14a13913369
Ref: reference/expressions generator close3913789
Ref: 14a33913789
Node: 例子3914318
Ref: reference/expressions examples3914443
Ref: 15173914443
Node: 异步生成器函数3915480
Ref: reference/expressions asynchronous-generator-functions3915608
Ref: 15143915608
Ref: reference/expressions id33915608
Ref: 15183915608
Ref: 异步生成器函数-Footnote-13918354
Node: 异步生成器-迭代器方法3918433
Ref: reference/expressions asynchronous-generator-iterator-methods3918546
Ref: 151c3918546
Ref: reference/expressions asynchronous-generator-methods3918546
Ref: 151d3918546
Ref: reference/expressions agen __anext__3918733
Ref: 15193918733
Ref: reference/expressions agen asend3919575
Ref: 151a3919575
Ref: reference/expressions agen athrow3920342
Ref: 151e3920342
Ref: reference/expressions agen aclose3920957
Ref: 151b3920957
Node: 原型3921822
Ref: reference/expressions id43921913
Ref: 151f3921913
Ref: reference/expressions primaries3921913
Ref: 15203921913
Ref: reference/expressions grammar-token-primary3922017
Ref: 15213922017
Node: 属性引用3922147
Ref: reference/expressions attribute-references3922217
Ref: 15223922217
Ref: reference/expressions id53922217
Ref: 15233922217
Ref: reference/expressions grammar-token-attributeref3922322
Ref: 15243922322
Node: 抽取3922855
Ref: reference/expressions id63922940
Ref: 15253922940
Ref: reference/expressions subscriptions3922940
Ref: 15263922940
Ref: reference/expressions grammar-token-subscription3923068
Ref: 15273923068
Node: 切片3924358
Ref: reference/expressions id73924437
Ref: 15283924437
Ref: reference/expressions slicings3924437
Ref: 15293924437
Ref: reference/expressions grammar-token-slicing3924664
Ref: 152a3924664
Ref: reference/expressions grammar-token-slice-list3924713
Ref: 152b3924713
Ref: reference/expressions grammar-token-slice-item3924770
Ref: 152c3924770
Ref: reference/expressions grammar-token-proper-slice3924818
Ref: 152d3924818
Ref: reference/expressions grammar-token-lower-bound3924889
Ref: 152e3924889
Ref: reference/expressions grammar-token-upper-bound3924922
Ref: 152f3924922
Ref: reference/expressions grammar-token-stride3924955
Ref: 15303924955
Node: 调用3926024
Ref: reference/expressions calls3926088
Ref: 6553926088
Ref: reference/expressions id83926088
Ref: 15313926088
Ref: reference/expressions grammar-token-call3926250
Ref: 15343926250
Ref: reference/expressions grammar-token-argument-list3926334
Ref: 15353926334
Ref: reference/expressions grammar-token-positional-arguments3926598
Ref: 15363926598
Ref: reference/expressions grammar-token-positional-item3926667
Ref: 15373926667
Ref: reference/expressions grammar-token-starred-and-keywords3926736
Ref: 15383926736
Ref: reference/expressions grammar-token-keywords-arguments3926869
Ref: 15393926869
Ref: reference/expressions grammar-token-keyword-item3927004
Ref: 153a3927004
Ref: 调用-Footnote-13932421
Node: await 表达式3932470
Ref: reference/expressions await3932567
Ref: 1a43932567
Ref: reference/expressions await-expression3932567
Ref: 153c3932567
Ref: reference/expressions grammar-token-await-expr3932753
Ref: 153d3932753
Node: 幂运算符3932809
Ref: reference/expressions power3932924
Ref: 153e3932924
Ref: reference/expressions the-power-operator3932924
Ref: 153f3932924
Ref: reference/expressions grammar-token-power3933102
Ref: 15403933102
Node: 一元算术和位运算3934104
Ref: reference/expressions unary3934225
Ref: 15413934225
Ref: reference/expressions unary-arithmetic-and-bitwise-operations3934225
Ref: 15423934225
Ref: reference/expressions grammar-token-u-expr3934331
Ref: 15433934331
Node: 二元算术运算符3934797
Ref: reference/expressions binary3934918
Ref: 15443934918
Ref: reference/expressions binary-arithmetic-operations3934918
Ref: 15453934918
Ref: reference/expressions grammar-token-m-expr3935212
Ref: 15463935212
Ref: reference/expressions grammar-token-a-expr3935368
Ref: 15473935368
Ref: 二元算术运算符-Footnote-13937784
Ref: 二元算术运算符-Footnote-23938386
Node: 移位运算3938647
Ref: reference/expressions shifting3938759
Ref: 15493938759
Ref: reference/expressions shifting-operations3938759
Ref: 154a3938759
Ref: reference/expressions grammar-token-shift-expr3938839
Ref: 154b3938839
Node: 二元位运算3939132
Ref: reference/expressions binary-bitwise-operations3939235
Ref: 154c3939235
Ref: reference/expressions bitwise3939235
Ref: 154d3939235
Ref: reference/expressions grammar-token-and-expr3939323
Ref: 154e3939323
Ref: reference/expressions grammar-token-xor-expr3939378
Ref: 154f3939378
Ref: reference/expressions grammar-token-or-expr3939429
Ref: 15503939429
Node: 比较运算3939773
Ref: reference/expressions comparisons3939876
Ref: 15513939876
Ref: reference/expressions id113939876
Ref: 15523939876
Ref: reference/expressions grammar-token-comparison3940126
Ref: 15533940126
Ref: reference/expressions grammar-token-comp-operator3940182
Ref: 15543940182
Node: 值比较3941111
Ref: reference/expressions value-comparisons3941196
Ref: 15553941196
Ref: reference/expressions in3948074
Ref: 7ac3948074
Ref: reference/expressions not-in3948074
Ref: 146d3948074
Ref: 值比较-Footnote-13948112
Ref: 值比较-Footnote-23948161
Node: 成员检测运算3949151
Ref: reference/expressions membership-test-details3949260
Ref: 146e3949260
Ref: reference/expressions membership-test-operations3949260
Ref: 15563949260
Ref: reference/expressions is3951089
Ref: eca3951089
Node: 标识号比较3951089
Ref: reference/expressions identity-comparisons3951180
Ref: 15573951180
Ref: reference/expressions is-not3951180
Ref: 15583951180
Ref: reference/expressions booleans3951497
Ref: 15593951497
Ref: reference/expressions and3951497
Ref: 155a3951497
Ref: reference/expressions or3951497
Ref: 155b3951497
Ref: 标识号比较-Footnote-13951535
Node: 布尔运算3951850
Ref: reference/expressions boolean-operations3951956
Ref: 155c3951956
Ref: reference/expressions not3951956
Ref: 155d3951956
Ref: reference/expressions grammar-token-or-test3951993
Ref: 155e3951993
Ref: reference/expressions grammar-token-and-test3952044
Ref: 155f3952044
Ref: reference/expressions grammar-token-not-test3952097
Ref: 15603952097
Node: 赋值表达式<2>3953434
Ref: reference/expressions assignment-expressions3953543
Ref: 15613953543
Ref: reference/expressions grammar-token-assignment-expression3953585
Ref: 15623953585
Ref: 赋值表达式<2>-Footnote-13954224
Node: 条件表达式3954273
Ref: reference/expressions conditional-expressions3954386
Ref: 15643954386
Ref: reference/expressions if-expr3954386
Ref: 15653954386
Ref: reference/expressions grammar-token-conditional-expression3954428
Ref: 15663954428
Ref: reference/expressions grammar-token-expression3954501
Ref: 15633954501
Ref: reference/expressions grammar-token-expression-nocond3954570
Ref: 15673954570
Ref: reference/expressions lambdas3954973
Ref: 15683954973
Ref: 条件表达式-Footnote-13955011
Node: lambda 表达式3955060
Ref: reference/expressions id143955170
Ref: 15693955170
Ref: reference/expressions lambda3955170
Ref: c373955170
Ref: reference/expressions grammar-token-lambda-expr3955216
Ref: 156a3955216
Ref: reference/expressions grammar-token-lambda-expr-nocond3955285
Ref: 156b3955285
Node: 表达式列表3955800
Ref: reference/expressions expression-lists3955907
Ref: 156c3955907
Ref: reference/expressions exprlists3955907
Ref: 6563955907
Ref: reference/expressions grammar-token-expression-list3955949
Ref: 15153955949
Ref: reference/expressions grammar-token-starred-list3956012
Ref: 156d3956012
Ref: reference/expressions grammar-token-starred-expression3956079
Ref: 156e3956079
Ref: reference/expressions grammar-token-starred-item3956155
Ref: 156f3956155
Ref: 表达式列表-Footnote-13957088
Node: 求值顺序3957137
Ref: reference/expressions evalorder3957246
Ref: 15703957246
Ref: reference/expressions evaluation-order3957246
Ref: 15713957246
Node: 运算符优先级3957705
Ref: reference/expressions operator-precedence3957790
Ref: 15723957790
Ref: reference/expressions operator-summary3957790
Ref: 15733957790
Ref: 运算符优先级-Footnote-13962008
Ref: 运算符优先级-Footnote-23962117
Node: 简单语句3962269
Ref: reference/simple_stmts doc3962375
Ref: 15743962375
Ref: reference/simple_stmts simple3962375
Ref: 15753962375
Ref: reference/simple_stmts simple-statements3962375
Ref: 15763962375
Ref: reference/simple_stmts grammar-token-simple-stmt3962550
Ref: 15773962550
Node: 表达式语句3963411
Ref: reference/simple_stmts expression-statements3963496
Ref: 15783963496
Ref: reference/simple_stmts exprstmts3963496
Ref: 15793963496
Ref: reference/simple_stmts grammar-token-expression-stmt3963862
Ref: 157a3963862
Node: 赋值语句3964291
Ref: reference/simple_stmts assignment3964398
Ref: 157b3964398
Ref: reference/simple_stmts assignment-statements3964398
Ref: 157c3964398
Ref: reference/simple_stmts grammar-token-assignment-stmt3964538
Ref: 157d3964538
Ref: reference/simple_stmts grammar-token-target-list3964622
Ref: 157e3964622
Ref: reference/simple_stmts grammar-token-target3964674
Ref: 157f3964674
Ref: reference/simple_stmts attr-target-note3967855
Ref: 15803967855
Ref: 赋值语句-Footnote-13971290
Node: 增强赋值语句3971339
Ref: reference/simple_stmts augassign3971439
Ref: 15813971439
Ref: reference/simple_stmts augmented-assignment-statements3971439
Ref: 15823971439
Ref: reference/simple_stmts grammar-token-augmented-assignment-stmt3971575
Ref: 15833971575
Ref: reference/simple_stmts grammar-token-augtarget3971663
Ref: 15843971663
Ref: reference/simple_stmts grammar-token-augop3971749
Ref: 15853971749
Node: 带标注的赋值语句3973277
Ref: reference/simple_stmts annassign3973377
Ref: 15863973377
Ref: reference/simple_stmts annotated-assignment-statements3973377
Ref: 15873973377
Ref: reference/simple_stmts grammar-token-annotated-assignment-stmt3973549
Ref: 15883973549
Ref: 带标注的赋值语句-Footnote-13975316
Ref: 带标注的赋值语句-Footnote-23975365
Node: assert 语句3975414
Ref: reference/simple_stmts assert3975520
Ref: e0e3975520
Ref: reference/simple_stmts the-assert-statement3975520
Ref: 15893975520
Ref: reference/simple_stmts grammar-token-assert-stmt3975634
Ref: 158a3975634
Node: pass 语句<2>3976576
Ref: reference/simple_stmts pass3976683
Ref: 12503976683
Ref: reference/simple_stmts the-pass-statement3976683
Ref: 158b3976683
Ref: reference/simple_stmts grammar-token-pass-stmt3976726
Ref: 158c3976726
Node: del 语句<2>3977064
Ref: reference/simple_stmts del3977171
Ref: 127e3977171
Ref: reference/simple_stmts the-del-statement3977171
Ref: 158d3977171
Ref: reference/simple_stmts grammar-token-del-stmt3977212
Ref: 158e3977212
Node: return 语句3978075
Ref: reference/simple_stmts return3978180
Ref: 1913978180
Ref: reference/simple_stmts the-return-statement3978180
Ref: 158f3978180
Ref: reference/simple_stmts grammar-token-return-stmt3978227
Ref: 15903978227
Node: yield 语句3979305
Ref: reference/simple_stmts the-yield-statement3979409
Ref: 15913979409
Ref: reference/simple_stmts yield3979409
Ref: 1903979409
Ref: reference/simple_stmts grammar-token-yield-stmt3979454
Ref: 15923979454
Node: raise 语句3980159
Ref: reference/simple_stmts raise3980262
Ref: c4a3980262
Ref: reference/simple_stmts the-raise-statement3980262
Ref: 15933980262
Ref: reference/simple_stmts grammar-token-raise-stmt3980307
Ref: 15943980307
Node: break 语句3983591
Ref: reference/simple_stmts break3983697
Ref: 2dc3983697
Ref: reference/simple_stmts the-break-statement3983697
Ref: 15953983697
Ref: reference/simple_stmts grammar-token-break-stmt3983742
Ref: 15963983742
Node: continue 语句3984374
Ref: reference/simple_stmts continue3984481
Ref: 1823984481
Ref: reference/simple_stmts the-continue-statement3984481
Ref: 15973984481
Ref: reference/simple_stmts grammar-token-continue-stmt3984534
Ref: 15983984534
Ref: reference/simple_stmts import3985013
Ref: c253985013
Node: import 语句3985015
Ref: reference/simple_stmts from3985123
Ref: c4d3985123
Ref: reference/simple_stmts the-import-statement3985123
Ref: 15993985123
Ref: reference/simple_stmts grammar-token-import-stmt3985172
Ref: 159a3985172
Ref: reference/simple_stmts grammar-token-module3985629
Ref: 159b3985629
Ref: reference/simple_stmts grammar-token-relative-module3985683
Ref: 159c3985683
Node: future 语句3990525
Ref: reference/simple_stmts future3990588
Ref: 159d3990588
Ref: reference/simple_stmts future-statements3990588
Ref: 159e3990588
Ref: reference/simple_stmts grammar-token-future-stmt3991025
Ref: 159f3991025
Ref: reference/simple_stmts grammar-token-feature3991301
Ref: 15a03991301
Ref: future 语句-Footnote-13993836
Ref: future 语句-Footnote-23993885
Node: global 语句3993934
Ref: reference/simple_stmts global3994042
Ref: 12543994042
Ref: reference/simple_stmts the-global-statement3994042
Ref: 15a13994042
Ref: reference/simple_stmts grammar-token-global-stmt3994091
Ref: 15a23994091
Node: nonlocal 语句3995524
Ref: reference/simple_stmts nonlocal3995610
Ref: c473995610
Ref: reference/simple_stmts the-nonlocal-statement3995610
Ref: 15a33995610
Ref: reference/simple_stmts grammar-token-nonlocal-stmt3995663
Ref: 15a43995663
Ref: nonlocal 语句-Footnote-13996591
Node: 复合语句3996640
Ref: reference/compound_stmts doc3996755
Ref: 15a53996755
Ref: reference/compound_stmts compound3996755
Ref: 15a63996755
Ref: reference/compound_stmts compound-statements3996755
Ref: 15a73996755
Ref: reference/compound_stmts grammar-token-compound-stmt3998355
Ref: 15a83998355
Ref: reference/compound_stmts grammar-token-suite3998712
Ref: 15a93998712
Ref: reference/compound_stmts grammar-token-statement3998788
Ref: 15aa3998788
Ref: reference/compound_stmts grammar-token-stmt-list3998845
Ref: 15ab3998845
Ref: reference/compound_stmts if3999354
Ref: def3999354
Ref: reference/compound_stmts elif3999354
Ref: 12433999354
Node: if 语句<2>3999521
Ref: reference/compound_stmts else3999603
Ref: 12443999603
Ref: reference/compound_stmts the-if-statement3999603
Ref: 15ac3999603
Ref: reference/compound_stmts grammar-token-if-stmt3999690
Ref: 15ad3999690
Node: while 语句4000222
Ref: reference/compound_stmts the-while-statement4000326
Ref: 15ae4000326
Ref: reference/compound_stmts while4000326
Ref: 123d4000326
Ref: reference/compound_stmts grammar-token-while-stmt4000456
Ref: 15af4000456
Node: for 语句<2>4001028
Ref: reference/compound_stmts for4001130
Ref: c384001130
Ref: reference/compound_stmts the-for-statement4001130
Ref: 15b04001130
Ref: reference/compound_stmts grammar-token-for-stmt4001299
Ref: 15b14001299
Ref: reference/compound_stmts try4003864
Ref: d7a4003864
Ref: reference/compound_stmts except4003864
Ref: b464003864
Node: try 语句4003865
Ref: reference/compound_stmts finally4003966
Ref: 1834003966
Ref: reference/compound_stmts the-try-statement4003966
Ref: 15b24003966
Ref: reference/compound_stmts grammar-token-try-stmt4004090
Ref: 15b34004090
Ref: reference/compound_stmts grammar-token-try1-stmt4004131
Ref: 15b44004131
Ref: reference/compound_stmts grammar-token-try2-stmt4004317
Ref: 15b54004317
Ref: reference/compound_stmts with4009155
Ref: 6f24009155
Ref: try 语句-Footnote-14009191
Node: with 语句4009371
Ref: reference/compound_stmts as4009471
Ref: 15b64009471
Ref: reference/compound_stmts the-with-statement4009471
Ref: 15b74009471
Ref: reference/compound_stmts grammar-token-with-stmt4009806
Ref: 15b84009806
Ref: reference/compound_stmts grammar-token-with-item4009869
Ref: 15b94009869
Ref: reference/compound_stmts function4012482
Ref: 126c4012482
Ref: with 语句-Footnote-14012518
Node: 函数定义4012567
Ref: reference/compound_stmts def4012666
Ref: dc64012666
Ref: reference/compound_stmts function-definitions4012666
Ref: 15ba4012666
Ref: reference/compound_stmts grammar-token-funcdef4012813
Ref: 15bb4012813
Ref: reference/compound_stmts grammar-token-decorators4012964
Ref: 15bc4012964
Ref: reference/compound_stmts grammar-token-decorator4013010
Ref: 15bd4013010
Ref: reference/compound_stmts grammar-token-dotted-name4013101
Ref: 15be4013101
Ref: reference/compound_stmts grammar-token-parameter-list4013165
Ref: 15bf4013165
Ref: reference/compound_stmts grammar-token-parameter-list-no-posonly4013340
Ref: 15c04013340
Ref: reference/compound_stmts grammar-token-parameter-list-starargs4013501
Ref: 15c14013501
Ref: reference/compound_stmts grammar-token-parameter4013659
Ref: 15c24013659
Ref: reference/compound_stmts grammar-token-defparameter4013722
Ref: 15c34013722
Ref: reference/compound_stmts grammar-token-funcname4013784
Ref: 15c44013784
Ref: 函数定义-Footnote-14019079
Ref: 函数定义-Footnote-24019247
Ref: 函数定义-Footnote-34019296
Ref: 函数定义-Footnote-44019345
Ref: 函数定义-Footnote-54019394
Ref: 函数定义-Footnote-64019443
Node: 类定义4019492
Ref: reference/compound_stmts class4019589
Ref: c724019589
Ref: reference/compound_stmts class-definitions4019589
Ref: 15c64019589
Ref: reference/compound_stmts grammar-token-classdef4019712
Ref: 15c74019712
Ref: reference/compound_stmts grammar-token-inheritance4019788
Ref: 15c84019788
Ref: reference/compound_stmts grammar-token-classname4019833
Ref: 15c94019833
Ref: 类定义-Footnote-14022119
Ref: 类定义-Footnote-24022287
Ref: 类定义-Footnote-34022336
Ref: 类定义-Footnote-44022385
Node: 协程<2>4022434
Ref: reference/compound_stmts async4022510
Ref: 1a34022510
Ref: reference/compound_stmts coroutines4022510
Ref: 15ca4022510
Node: 协程函数定义4022630
Ref: reference/compound_stmts async-def4022719
Ref: 2854022719
Ref: reference/compound_stmts coroutine-function-definition4022719
Ref: 15cb4022719
Ref: reference/compound_stmts grammar-token-async-funcdef4022768
Ref: 15cc4022768
Node: async for 语句4023547
Ref: reference/compound_stmts async-for4023662
Ref: 2e44023662
Ref: reference/compound_stmts the-async-for-statement4023662
Ref: 15cd4023662
Ref: reference/compound_stmts grammar-token-async-for-stmt4023719
Ref: 15ce4023719
Node: async with 语句4024589
Ref: reference/compound_stmts async-with4024677
Ref: 64c4024677
Ref: reference/compound_stmts the-async-with-statement4024677
Ref: 15cf4024677
Ref: reference/compound_stmts grammar-token-async-with-stmt4024736
Ref: 15d04024736
Ref: async with 语句-Footnote-14025829
Node: 最高层级组件4025878
Ref: reference/toplevel_components doc4026002
Ref: 15d14026002
Ref: reference/toplevel_components top-level4026002
Ref: 15d24026002
Ref: reference/toplevel_components top-level-components4026002
Ref: 15d34026002
Node: 完整的 Python 程序4026363
Ref: reference/toplevel_components complete-python-programs4026462
Ref: 15d44026462
Ref: reference/toplevel_components programs4026462
Ref: 14d84026462
Node: 文件输入4027770
Ref: reference/toplevel_components file-input4027893
Ref: 15d54027893
Ref: reference/toplevel_components id14027893
Ref: 15d64027893
Ref: reference/toplevel_components grammar-token-file-input4027997
Ref: 15d74027997
Node: 交互式输入4028252
Ref: reference/toplevel_components interactive4028367
Ref: 15d84028367
Ref: reference/toplevel_components interactive-input4028367
Ref: 15d94028367
Ref: reference/toplevel_components grammar-token-interactive-input4028464
Ref: 15da4028464
Node: 表达式输入4028689
Ref: reference/toplevel_components expression-input4028783
Ref: 15db4028783
Ref: reference/toplevel_components id24028783
Ref: 15dc4028783
Ref: reference/toplevel_components grammar-token-eval-input4028975
Ref: 15dd4028975
Node: 完整的语法规范4029021
Ref: reference/grammar doc4029124
Ref: 15de4029124
Ref: reference/grammar full-grammar-specification4029124
Ref: 15df4029124
Node: Python 标准库4040099
Ref: library/index doc4040223
Ref: 15e04040223
Ref: library/index library-index4040223
Ref: 120b4040223
Ref: library/index the-python-standard-library4040223
Ref: 15e14040223
Ref: Python 标准库-Footnote-14042408
Node: 概述<6>4042433
Ref: library/intro doc4042516
Ref: 15e24042516
Ref: library/intro introduction4042516
Ref: 15e34042516
Ref: library/intro library-intro4042516
Ref: 15e44042516
Node: 可用性注释4044786
Ref: library/intro availability4044847
Ref: 136f4044847
Ref: library/intro notes-on-availability4044847
Ref: 15e54044847
Node: 内置函数4045195
Ref: library/functions doc4045299
Ref: 15e64045299
Ref: library/functions built-in-funcs4045299
Ref: bfb4045299
Ref: library/functions built-in-functions4045299
Ref: 15e74045299
Ref: library/functions abs4049823
Ref: 12cf4049823
Ref: library/functions all4050081
Ref: d8d4050081
Ref: library/functions any4050395
Ref: d8c4050395
Ref: library/functions ascii4050724
Ref: d544050724
Ref: library/functions bin4051080
Ref: c484051080
Ref: library/functions bool4051732
Ref: 1844051732
Ref: library/functions breakpoint4052292
Ref: 3024052292
Ref: library/functions func-bytearray4053074
Ref: 10ce4053074
Ref: library/functions func-bytes4054398
Ref: 10cd4054398
Ref: library/functions callable4055054
Ref: b4c4055054
Ref: library/functions chr4055607
Ref: 14384055607
Ref: library/functions classmethod4056011
Ref: 1d94056011
Ref: library/functions compile4056999
Ref: 1b54056999
Ref: library/functions complex4060700
Ref: 18a4060700
Ref: library/functions delattr4062097
Ref: 15e84062097
Ref: library/functions func-dict4062402
Ref: 15eb4062402
Ref: library/functions dir4062814
Ref: d3b4062814
Ref: library/functions divmod4065213
Ref: 1534065213
Ref: library/functions enumerate4065774
Ref: deb4065774
Ref: library/functions eval4066635
Ref: b984066635
Ref: library/functions exec4068653
Ref: c4c4068653
Ref: library/functions filter4070969
Ref: c364070969
Ref: library/functions float4071781
Ref: 1884071781
Ref: library/functions grammar-token-sign4072258
Ref: 15fd4072258
Ref: library/functions grammar-token-infinity4072297
Ref: 15fe4072297
Ref: library/functions grammar-token-nan4072345
Ref: 15ff4072345
Ref: library/functions grammar-token-numeric-value4072380
Ref: 16004072380
Ref: library/functions grammar-token-numeric-string4072438
Ref: 16014072438
Ref: library/functions format4073807
Ref: 4e34073807
Ref: library/functions func-frozenset4074754
Ref: 15ef4074754
Ref: library/functions getattr4075232
Ref: 4514075232
Ref: library/functions globals4075619
Ref: 15f24075619
Ref: library/functions hasattr4075815
Ref: 4504075815
Ref: library/functions hash4076135
Ref: 9cc4076135
Ref: library/functions help4076631
Ref: 57b4076631
Ref: library/functions hex4077548
Ref: c6e4077548
Ref: library/functions id4078569
Ref: d8e4078569
Ref: library/functions input4078986
Ref: c734078986
Ref: library/functions int4079773
Ref: 1854079773
Ref: library/functions isinstance4081747
Ref: 4574081747
Ref: library/functions issubclass4082351
Ref: 4584082351
Ref: library/functions iter4082739
Ref: d2f4082739
Ref: library/functions len4083997
Ref: 1514083997
Ref: library/functions func-list4084209
Ref: 15f04084209
Ref: library/functions locals4084422
Ref: 45d4084422
Ref: library/functions map4084852
Ref: c354084852
Ref: library/functions max4085365
Ref: 8134085365
Ref: library/functions func-memoryview4086444
Ref: 15e94086444
Ref: library/functions min4086599
Ref: 8124086599
Ref: library/functions next4087659
Ref: 68b4087659
Ref: library/functions object4087912
Ref: 2b14087912
Ref: library/functions oct4088262
Ref: c6d4088262
Ref: library/functions open4089013
Ref: 4f84089013
Ref: library/functions filemodes4090433
Ref: 16064090433
Ref: library/functions open-newline-parameter4095140
Ref: 16084095140
Ref: library/functions ord4099937
Ref: 14374099937
Ref: library/functions pow4100208
Ref: 19b4100208
Ref: library/functions print4101740
Ref: 88f4101740
Ref: library/functions property4102956
Ref: 1d84102956
Ref: library/functions func-range4105564
Ref: 15f14105564
Ref: library/functions repr4105844
Ref: 7d54105844
Ref: library/functions reversed4106395
Ref: 18f4106395
Ref: library/functions round4106715
Ref: c754106715
Ref: library/functions func-set4107942
Ref: 15ea4107942
Ref: library/functions setattr4108404
Ref: 15ec4108404
Ref: library/functions slice4108782
Ref: e0c4108782
Ref: library/functions sorted4109484
Ref: 44c4109484
Ref: library/functions staticmethod4110473
Ref: 1da4110473
Ref: library/functions func-str4111620
Ref: 15ed4111620
Ref: library/functions sum4111965
Ref: 1e64111965
Ref: library/functions super4112583
Ref: 4eb4112583
Ref: library/functions func-tuple4115970
Ref: 15ee4115970
Ref: library/functions type4116213
Ref: 6114116213
Ref: library/functions vars4117714
Ref: 10474117714
Ref: library/functions zip4118543
Ref: c3a4118543
Ref: library/functions __import__4120495
Ref: 6194120495
Ref: 内置函数-Footnote-14123400
Ref: 内置函数-Footnote-24123575
Ref: 内置函数-Footnote-34123624
Ref: 内置函数-Footnote-44123701
Ref: 内置函数-Footnote-54123750
Node: 内置常量4123799
Ref: library/constants doc4123906
Ref: 16194123906
Ref: library/constants built-in-constants4123906
Ref: 161a4123906
Ref: library/constants built-in-consts4123906
Ref: 161b4123906
Ref: library/constants False4124003
Ref: 3904124003
Ref: library/constants True4124143
Ref: 4a14124143
Ref: library/constants None4124281
Ref: 1584124281
Ref: library/constants NotImplemented4124513
Ref: 8554124513
Ref: library/constants Ellipsis4125681
Ref: 161c4125681
Ref: library/constants __debug__4125854
Ref: 100c4125854
Node: 由 site 模块添加的常量4126321
Ref: library/constants constants-added-by-the-site-module4126400
Ref: 161d4126400
Ref: library/constants quit4126705
Ref: 161e4126705
Ref: library/constants exit4126734
Ref: 161f4126734
Ref: library/constants copyright4126975
Ref: 16204126975
Ref: library/constants credits4126997
Ref: 16214126997
Ref: library/constants license4127088
Ref: 16224127088
Node: 内置类型4127326
Ref: library/stdtypes doc4127433
Ref: 16234127433
Ref: library/stdtypes bltin-types4127433
Ref: 16244127433
Ref: library/stdtypes built-in-types4127433
Ref: 16254127433
Node: 逻辑值检测4128748
Ref: library/stdtypes truth4128848
Ref: 15f34128848
Ref: library/stdtypes truth-value-testing4128848
Ref: 16264128848
Ref: 逻辑值检测-Footnote-14129897
Node: 布尔运算 --- and or not4130009
Ref: library/stdtypes boolean4130133
Ref: 16274130133
Ref: library/stdtypes boolean-operations-and-or-not4130133
Ref: 16284130133
Node: 比较运算<2>4131438
Ref: library/stdtypes comparisons4131581
Ref: 16294131581
Ref: library/stdtypes stdcomparisons4131581
Ref: 162a4131581
Node: 数字类型 --- int float complex4133858
Ref: library/stdtypes numeric-types-int-float-complex4133989
Ref: 162b4133989
Ref: library/stdtypes typesnumeric4133989
Ref: 122f4133989
Ref: 数字类型 --- int float complex-Footnote-14141627
Node: 整数类型的按位运算4141739
Ref: library/stdtypes bitstring-ops4141873
Ref: 162c4141873
Ref: library/stdtypes bitwise-operations-on-integer-types4141873
Ref: 162d4141873
Node: 整数类型的附加方法4144025
Ref: library/stdtypes additional-methods-on-integer-types4144195
Ref: 162e4144195
Ref: library/stdtypes int bit_length4144389
Ref: 162f4144389
Ref: library/stdtypes int to_bytes4145256
Ref: 16304145256
Ref: library/stdtypes int from_bytes4146547
Ref: 16324146547
Ref: library/stdtypes int as_integer_ratio4147657
Ref: 1874147657
Node: 浮点类型的附加方法4147887
Ref: library/stdtypes additional-methods-on-float4148057
Ref: 16334148057
Ref: library/stdtypes float as_integer_ratio4148242
Ref: 13334148242
Ref: library/stdtypes float is_integer4148463
Ref: 16344148463
Ref: library/stdtypes float hex4149046
Ref: 13344149046
Ref: library/stdtypes float fromhex4149255
Ref: 16354149255
Node: 数字类型的哈希运算4150751
Ref: library/stdtypes hashing-of-numeric-types4150885
Ref: 16364150885
Ref: library/stdtypes numeric-hash4150885
Ref: 16374150885
Node: 迭代器类型4155039
Ref: library/stdtypes iterator-types4155188
Ref: 16384155188
Ref: library/stdtypes typeiter4155188
Ref: 146c4155188
Ref: library/stdtypes container __iter__4155520
Ref: 16394155520
Ref: library/stdtypes iterator __iter__4156101
Ref: 163a4156101
Ref: library/stdtypes iterator __next__4156386
Ref: c6c4156386
Node: 生成器类型4157111
Ref: library/stdtypes generator-types4157178
Ref: 163b4157178
Ref: library/stdtypes id34157178
Ref: 163c4157178
Node: 序列类型 --- list tuple range4157639
Ref: library/stdtypes sequence-types-list-tuple-range4157780
Ref: 163d4157780
Ref: library/stdtypes typesseq4157780
Ref: 12804157780
Node: 通用序列操作4158220
Ref: library/stdtypes common-sequence-operations4158338
Ref: 163e4158338
Ref: library/stdtypes typesseq-common4158338
Ref: 163f4158338
Ref: 通用序列操作-Footnote-14166320
Node: 不可变序列类型4166408
Ref: library/stdtypes immutable-sequence-types4166553
Ref: 16444166553
Ref: library/stdtypes typesseq-immutable4166553
Ref: 16454166553
Node: 可变序列类型4167020
Ref: library/stdtypes mutable-sequence-types4167156
Ref: 16464167156
Ref: library/stdtypes typesseq-mutable4167156
Ref: 15f54167156
Node: 列表<2>4172507
Ref: library/stdtypes lists4172628
Ref: 16474172628
Ref: library/stdtypes typesseq-list4172628
Ref: 16044172628
Ref: library/stdtypes list4172783
Ref: 2634172783
Ref: library/stdtypes list sort4173862
Ref: 44d4173862
Node: 元组4175910
Ref: library/stdtypes tuples4176025
Ref: 16484176025
Ref: library/stdtypes typesseq-tuple4176025
Ref: 16174176025
Ref: library/stdtypes tuple4176344
Ref: 4864176344
Node: range 对象4177756
Ref: library/stdtypes ranges4177853
Ref: 16494177853
Ref: library/stdtypes typesseq-range4177853
Ref: 160f4177853
Ref: library/stdtypes range4178019
Ref: 9c64178019
Ref: library/stdtypes range start4179836
Ref: 164a4179836
Ref: library/stdtypes range stop4179933
Ref: 164b4179933
Ref: library/stdtypes range step4179987
Ref: 164c4179987
Ref: range 对象-Footnote-14181864
Node: 文本序列类型 --- str4181916
Ref: library/stdtypes text-sequence-type-str4182094
Ref: 164d4182094
Ref: library/stdtypes textseq4182094
Ref: 12334182094
Ref: library/stdtypes str4183755
Ref: 3394183755
Node: 字符串的方法<2>4185892
Ref: library/stdtypes id54186019
Ref: 164f4186019
Ref: library/stdtypes string-methods4186019
Ref: 12344186019
Ref: library/stdtypes str capitalize4186825
Ref: 16524186825
Ref: library/stdtypes str casefold4187141
Ref: 6b94187141
Ref: library/stdtypes str center4187761
Ref: 12ac4187761
Ref: library/stdtypes str count4188050
Ref: 16544188050
Ref: library/stdtypes str encode4188255
Ref: c3f4188255
Ref: library/stdtypes str endswith4188985
Ref: 7d04188985
Ref: library/stdtypes str expandtabs4189346
Ref: 16554189346
Ref: library/stdtypes str find4190362
Ref: 7a84190362
Ref: library/stdtypes str format4190879
Ref: 4e24190879
Ref: library/stdtypes str format_map4192302
Ref: 6ba4192302
Ref: library/stdtypes str index4192851
Ref: 16564192851
Ref: library/stdtypes str isalnum4192998
Ref: 16574192998
Ref: library/stdtypes str isalpha4193361
Ref: 16584193361
Ref: library/stdtypes str isascii4193781
Ref: 33c4193781
Ref: library/stdtypes str isdecimal4194010
Ref: 16594194010
Ref: library/stdtypes str isdigit4194407
Ref: 165a4194407
Ref: library/stdtypes str isidentifier4194851
Ref: 165b4194851
Ref: library/stdtypes str islower4195388
Ref: 165d4195388
Ref: library/stdtypes str isnumeric4195569
Ref: 165e4195569
Ref: library/stdtypes str isprintable4196036
Ref: 6bb4196036
Ref: library/stdtypes str isspace4196632
Ref: 165f4196632
Ref: library/stdtypes str istitle4196996
Ref: 16604196996
Ref: library/stdtypes str isupper4197248
Ref: 16614197248
Ref: library/stdtypes str join4197429
Ref: 16424197429
Ref: library/stdtypes str ljust4197726
Ref: 12ab4197726
Ref: library/stdtypes str lower4198010
Ref: 16534198010
Ref: library/stdtypes str lstrip4198211
Ref: 16624198211
Ref: library/stdtypes str maketrans4198683
Ref: 6bc4198683
Ref: library/stdtypes str partition4199405
Ref: 7ab4199405
Ref: library/stdtypes str replace4199717
Ref: 16644199717
Ref: library/stdtypes str rfind4199943
Ref: 7a94199943
Ref: library/stdtypes str rindex4200242
Ref: 16654200242
Ref: library/stdtypes str rjust4200404
Ref: 12aa4200404
Ref: library/stdtypes str rpartition4200688
Ref: 16664200688
Ref: library/stdtypes str rsplit4201010
Ref: 16674201010
Ref: library/stdtypes str rstrip4201478
Ref: 16684201478
Ref: library/stdtypes str split4201939
Ref: 7aa4201939
Ref: library/stdtypes str splitlines4203463
Ref: 16694203463
Ref: library/stdtypes str startswith4206023
Ref: 7cf4206023
Ref: library/stdtypes str strip4206389
Ref: 166a4206389
Ref: library/stdtypes str swapcase4207277
Ref: 166b4207277
Ref: library/stdtypes str title4207469
Ref: 166c4207469
Ref: library/stdtypes str translate4208462
Ref: 16634208462
Ref: library/stdtypes str upper4209312
Ref: 166e4209312
Ref: library/stdtypes str zfill4209754
Ref: 12ad4209754
Ref: 字符串的方法<2>-Footnote-14210230
Ref: 字符串的方法<2>-Footnote-24210400
Ref: 字符串的方法<2>-Footnote-34210570
Ref: 字符串的方法<2>-Footnote-44210740
Node: printf 风格的字符串格式化4210910
Ref: library/stdtypes old-string-formatting4211037
Ref: 12354211037
Ref: library/stdtypes printf-style-string-formatting4211037
Ref: 166f4211037
Ref: printf 风格的字符串格式化-Footnote-14219760
Ref: printf 风格的字符串格式化-Footnote-24219900
Node: 二进制序列类型 --- bytes bytearray memoryview4219949
Ref: library/stdtypes binary-sequence-types-bytes-bytearray-memoryview4220124
Ref: 16714220124
Ref: library/stdtypes binaryseq4220124
Ref: 15f84220124
Node: bytes 对象4220781
Ref: library/stdtypes bytes-objects4220907
Ref: 16724220907
Ref: library/stdtypes typebytes4220907
Ref: 15fa4220907
Ref: library/stdtypes bytes4221216
Ref: 33a4221216
Ref: library/stdtypes bytes fromhex4223313
Ref: 3374223313
Ref: library/stdtypes bytes hex4223901
Ref: 63a4223901
Node: bytearray 对象4226072
Ref: library/stdtypes bytearray-objects4226233
Ref: 16734226233
Ref: library/stdtypes typebytearray4226233
Ref: 15f94226233
Ref: library/stdtypes bytearray4226361
Ref: 33b4226361
Ref: library/stdtypes bytearray fromhex4227311
Ref: 3384227311
Ref: library/stdtypes bytearray hex4227931
Ref: 63b4227931
Node: bytes 和 bytearray 操作4229025
Ref: library/stdtypes bytes-and-bytearray-operations4229208
Ref: 16744229208
Ref: library/stdtypes bytes-methods4229208
Ref: 15f64229208
Ref: library/stdtypes bytes count4230356
Ref: 16754230356
Ref: library/stdtypes bytearray count4230402
Ref: 16764230402
Ref: library/stdtypes bytes decode4230809
Ref: c404230809
Ref: library/stdtypes bytearray decode4230870
Ref: 16774230870
Ref: library/stdtypes bytes endswith4231736
Ref: 16784231736
Ref: library/stdtypes bytearray endswith4231788
Ref: 16794231788
Ref: library/stdtypes bytes find4232238
Ref: 167a4232238
Ref: library/stdtypes bytearray find4232283
Ref: 167b4232283
Ref: library/stdtypes bytes index4233028
Ref: 167c4233028
Ref: library/stdtypes bytearray index4233074
Ref: 167d4233074
Ref: library/stdtypes bytes join4233430
Ref: 16434233430
Ref: library/stdtypes bytearray join4233464
Ref: 167e4233464
Ref: library/stdtypes bytes maketrans4233853
Ref: c114233853
Ref: library/stdtypes bytearray maketrans4233899
Ref: c124233899
Ref: library/stdtypes bytes partition4234249
Ref: 16804234249
Ref: library/stdtypes bytearray partition4234283
Ref: 16814234283
Ref: library/stdtypes bytes replace4234720
Ref: 16824234720
Ref: library/stdtypes bytearray replace4234766
Ref: 16834234766
Ref: library/stdtypes bytes rfind4235240
Ref: 16844235240
Ref: library/stdtypes bytearray rfind4235286
Ref: 16854235286
Ref: library/stdtypes bytes rindex4235784
Ref: 16864235784
Ref: library/stdtypes bytearray rindex4235831
Ref: 16874235831
Ref: library/stdtypes bytes rpartition4236196
Ref: 16884236196
Ref: library/stdtypes bytearray rpartition4236231
Ref: 16894236231
Ref: library/stdtypes bytes startswith4236683
Ref: 168a4236683
Ref: library/stdtypes bytearray startswith4236737
Ref: 168b4236737
Ref: library/stdtypes bytes translate4237189
Ref: 167f4237189
Ref: library/stdtypes bytearray translate4237240
Ref: c994237240
Ref: library/stdtypes bytes center4238157
Ref: 168c4238157
Ref: library/stdtypes bytearray center4238202
Ref: 168d4238202
Ref: library/stdtypes bytes ljust4238688
Ref: 168e4238688
Ref: library/stdtypes bytearray ljust4238732
Ref: 168f4238732
Ref: library/stdtypes bytes lstrip4239209
Ref: 16904239209
Ref: library/stdtypes bytearray lstrip4239244
Ref: 16914239244
Ref: library/stdtypes bytes rjust4240049
Ref: 16924240049
Ref: library/stdtypes bytearray rjust4240093
Ref: 16934240093
Ref: library/stdtypes bytes rsplit4240570
Ref: 16944240570
Ref: library/stdtypes bytearray rsplit4240619
Ref: 16954240619
Ref: library/stdtypes bytes rstrip4241115
Ref: 16974241115
Ref: library/stdtypes bytearray rstrip4241150
Ref: 16984241150
Ref: library/stdtypes bytes split4241944
Ref: 16994241944
Ref: library/stdtypes bytearray split4241992
Ref: 16964241992
Ref: library/stdtypes bytes strip4243701
Ref: 169a4243701
Ref: library/stdtypes bytearray strip4243735
Ref: 169b4243735
Ref: library/stdtypes bytes capitalize4244799
Ref: 169c4244799
Ref: library/stdtypes bytearray capitalize4244831
Ref: 169d4244831
Ref: library/stdtypes bytes expandtabs4245223
Ref: 169e4245223
Ref: library/stdtypes bytearray expandtabs4245264
Ref: 169f4245264
Ref: library/stdtypes bytes isalnum4246491
Ref: 16a04246491
Ref: library/stdtypes bytearray isalnum4246520
Ref: 16a14246520
Ref: library/stdtypes bytes isalpha4247069
Ref: 16a24247069
Ref: library/stdtypes bytearray isalpha4247098
Ref: 16a34247098
Ref: library/stdtypes bytes isascii4247528
Ref: 16a44247528
Ref: library/stdtypes bytearray isascii4247557
Ref: 16a54247557
Ref: library/stdtypes bytes isdigit4247781
Ref: 16a64247781
Ref: library/stdtypes bytearray isdigit4247810
Ref: 16a74247810
Ref: library/stdtypes bytes islower4248184
Ref: 16a84248184
Ref: library/stdtypes bytearray islower4248213
Ref: 16a94248213
Ref: library/stdtypes bytes isspace4248741
Ref: 16aa4248741
Ref: library/stdtypes bytearray isspace4248770
Ref: 16ab4248770
Ref: library/stdtypes bytes istitle4249081
Ref: 16ac4249081
Ref: library/stdtypes bytearray istitle4249110
Ref: 16ad4249110
Ref: library/stdtypes bytes isupper4249487
Ref: 16af4249487
Ref: library/stdtypes bytearray isupper4249516
Ref: 16b04249516
Ref: library/stdtypes bytes lower4250044
Ref: 16b14250044
Ref: library/stdtypes bytearray lower4250071
Ref: 16b24250071
Ref: library/stdtypes bytes splitlines4250650
Ref: 16b34250650
Ref: library/stdtypes bytearray splitlines4250696
Ref: 16b44250696
Ref: library/stdtypes bytes swapcase4251608
Ref: 16b54251608
Ref: library/stdtypes bytearray swapcase4251638
Ref: 16b64251638
Ref: library/stdtypes bytes title4252488
Ref: 16ae4252488
Ref: library/stdtypes bytearray title4252515
Ref: 16b74252515
Ref: library/stdtypes bytes upper4254089
Ref: 16b84254089
Ref: library/stdtypes bytearray upper4254116
Ref: 16b94254116
Ref: library/stdtypes bytes zfill4254695
Ref: 16ba4254695
Ref: library/stdtypes bytearray zfill4254727
Ref: 16bb4254727
Node: printf 风格的字节串格式化4255349
Ref: library/stdtypes bytes-formatting4255528
Ref: 6594255528
Ref: library/stdtypes printf-style-bytes-formatting4255528
Ref: 16bc4255528
Ref: printf 风格的字节串格式化-Footnote-14264641
Ref: printf 风格的字节串格式化-Footnote-24264781
Ref: printf 风格的字节串格式化-Footnote-34264830
Node: 内存视图4264879
Ref: library/stdtypes memory-views4265023
Ref: 16bd4265023
Ref: library/stdtypes typememoryview4265023
Ref: 16054265023
Ref: library/stdtypes memoryview4265225
Ref: 25d4265225
Ref: library/stdtypes memoryview __eq__4268826
Ref: 16c14268826
Ref: library/stdtypes memoryview tobytes4270764
Ref: 16c24270764
Ref: library/stdtypes memoryview hex4271802
Ref: 63c4271802
Ref: library/stdtypes memoryview tolist4272329
Ref: 16be4272329
Ref: library/stdtypes memoryview toreadonly4272861
Ref: 16c34272861
Ref: library/stdtypes memoryview release4273463
Ref: b454273463
Ref: library/stdtypes memoryview cast4274739
Ref: 16c44274739
Ref: library/stdtypes memoryview obj4277670
Ref: 16c64277670
Ref: library/stdtypes memoryview nbytes4277891
Ref: 16c74277891
Ref: library/stdtypes memoryview readonly4278953
Ref: 16c84278953
Ref: library/stdtypes memoryview format4279037
Ref: 16c04279037
Ref: library/stdtypes memoryview itemsize4279520
Ref: 16bf4279520
Ref: library/stdtypes memoryview ndim4279892
Ref: 16c94279892
Ref: library/stdtypes memoryview shape4280002
Ref: 16ca4280002
Ref: library/stdtypes memoryview strides4280242
Ref: 16cb4280242
Ref: library/stdtypes memoryview suboffsets4280521
Ref: 16cc4280521
Ref: library/stdtypes memoryview c_contiguous4280631
Ref: 16cd4280631
Ref: library/stdtypes memoryview f_contiguous4280772
Ref: 16ce4280772
Ref: library/stdtypes memoryview contiguous4280919
Ref: 16cf4280919
Ref: 内存视图-Footnote-14281092
Node: 集合类型 --- set frozenset4281141
Ref: library/stdtypes set-types-set-frozenset4281311
Ref: 16d04281311
Ref: library/stdtypes types-set4281311
Ref: 16024281311
Ref: library/stdtypes set4282803
Ref: b774282803
Ref: library/stdtypes frozenset4282829
Ref: bf64282829
Ref: library/stdtypes frozenset isdisjoint4283845
Ref: 16d14283845
Ref: library/stdtypes frozenset issubset4284055
Ref: 16d24284055
Ref: library/stdtypes frozenset issuperset4284332
Ref: 16d34284332
Ref: library/stdtypes frozenset union4284611
Ref: 16d44284611
Ref: library/stdtypes frozenset intersection4284805
Ref: 16d54284805
Ref: library/stdtypes frozenset difference4285006
Ref: 16d64285006
Ref: library/stdtypes frozenset symmetric_difference4285208
Ref: 16d74285208
Ref: library/stdtypes frozenset copy4285437
Ref: 16d84285437
Ref: library/stdtypes frozenset update4287616
Ref: 16d94287616
Ref: library/stdtypes frozenset intersection_update4287756
Ref: 16da4287756
Ref: library/stdtypes frozenset difference_update4287924
Ref: 16db4287924
Ref: library/stdtypes frozenset symmetric_difference_update4288081
Ref: 16dc4288081
Ref: library/stdtypes frozenset add4288256
Ref: 16dd4288256
Ref: library/stdtypes frozenset remove4288335
Ref: 16de4288335
Ref: library/stdtypes frozenset discard4288495
Ref: 16df4288495
Ref: library/stdtypes frozenset pop4288596
Ref: 16e04288596
Ref: library/stdtypes frozenset clear4288746
Ref: 16e14288746
Node: 映射类型 --- dict4289321
Ref: library/stdtypes mapping-types-dict4289463
Ref: 16e24289463
Ref: library/stdtypes typesmapping4289463
Ref: 3054289463
Ref: library/stdtypes dict4290588
Ref: 1b94290588
Ref: library/stdtypes dict clear4294724
Ref: 16e34294724
Ref: library/stdtypes dict copy4294796
Ref: 44e4294796
Ref: library/stdtypes dict fromkeys4294864
Ref: 16e44294864
Ref: library/stdtypes dict get4295353
Ref: 16e54295353
Ref: library/stdtypes dict items4295612
Ref: c334295612
Ref: library/stdtypes dict keys4295772
Ref: c324295772
Ref: library/stdtypes dict pop4295897
Ref: 16e74295897
Ref: library/stdtypes dict popitem4296155
Ref: 16e84296155
Ref: library/stdtypes dict setdefault4296894
Ref: 9c74296894
Ref: library/stdtypes dict update4297135
Ref: dd14297135
Ref: library/stdtypes dict values4297601
Ref: c344297601
Node: 字典视图对象4299590
Ref: library/stdtypes dict-views4299666
Ref: 16e64299666
Ref: library/stdtypes dictionary-view-objects4299666
Ref: 16e94299666
Node: 上下文管理器类型4302399
Ref: library/stdtypes context-manager-types4302529
Ref: 16eb4302529
Ref: library/stdtypes typecontextmanager4302529
Ref: 14984302529
Ref: library/stdtypes contextmanager __enter__4302895
Ref: 16ec4302895
Ref: library/stdtypes contextmanager __exit__4303814
Ref: 16ee4303814
Node: 其他内置类型4305872
Ref: library/stdtypes other-built-in-types4305993
Ref: 16ef4305993
Ref: library/stdtypes typesother4305993
Ref: 16f04305993
Node: 模块<2>4306325
Ref: library/stdtypes modules4306413
Ref: 16f14306413
Ref: library/stdtypes typesmodules4306413
Ref: 16f24306413
Node: 类与类实例4307443
Ref: library/stdtypes classes-and-class-instances4307546
Ref: 16f34307546
Ref: library/stdtypes typesobjects4307546
Ref: 16f44307546
Node: 函数4307685
Ref: library/stdtypes functions4307785
Ref: 16f54307785
Ref: library/stdtypes typesfunctions4307785
Ref: 16f64307785
Node: 方法4308178
Ref: library/stdtypes methods4308275
Ref: 16f74308275
Ref: library/stdtypes typesmethods4308275
Ref: 16f84308275
Node: 代码对象4309893
Ref: library/stdtypes bltin-code-objects4309996
Ref: 16f94309996
Ref: library/stdtypes code-objects4309996
Ref: 16fa4309996
Node: 类型对象4310742
Ref: library/stdtypes bltin-type-objects4310848
Ref: 16184310848
Ref: library/stdtypes type-objects4310848
Ref: 16fb4310848
Node: 空对象4311171
Ref: library/stdtypes bltin-null-object4311280
Ref: 16fc4311280
Ref: library/stdtypes the-null-object4311280
Ref: 16fd4311280
Node: 省略符对象4311560
Ref: library/stdtypes bltin-ellipsis-object4311672
Ref: 16fe4311672
Ref: library/stdtypes the-ellipsis-object4311672
Ref: 16ff4311672
Node: 未实现对象4312017
Ref: library/stdtypes bltin-notimplemented-object4312129
Ref: 17004312129
Ref: library/stdtypes the-notimplemented-object4312129
Ref: 17014312129
Node: 布尔值4312491
Ref: library/stdtypes bltin-boolean-values4312600
Ref: 15f44312600
Ref: library/stdtypes boolean-values4312600
Ref: 17024312600
Node: 内部对象4313162
Ref: library/stdtypes internal-objects4313247
Ref: 17034313247
Ref: library/stdtypes typesinternal4313247
Ref: 17044313247
Node: 特殊属性4313437
Ref: library/stdtypes special-attributes4313525
Ref: 17054313525
Ref: library/stdtypes specialattrs4313525
Ref: 17064313525
Ref: library/stdtypes object __dict__4313735
Ref: 5044313735
Ref: library/stdtypes instance __class__4313858
Ref: e124313858
Ref: library/stdtypes class __bases__4313921
Ref: e114313921
Ref: library/stdtypes definition __name__4313999
Ref: c6f4313999
Ref: library/stdtypes definition __qualname__4314102
Ref: 143a4314102
Ref: library/stdtypes class __mro__4314255
Ref: 16154314255
Ref: library/stdtypes class mro4314376
Ref: 17074314376
Ref: library/stdtypes class __subclasses__4314582
Ref: 17084314582
Node: 内置异常4314864
Ref: library/exceptions doc4314977
Ref: 17094314977
Ref: library/exceptions bltin-exceptions4314977
Ref: 12be4314977
Ref: library/exceptions built-in-exceptions4314977
Ref: 170a4314977
Node: 基类4317951
Ref: library/exceptions base-classes4318027
Ref: 170b4318027
Ref: library/exceptions BaseException4318105
Ref: 1a94318105
Ref: library/exceptions BaseException args4318411
Ref: 170c4318411
Ref: library/exceptions BaseException with_traceback4318705
Ref: 170d4318705
Ref: library/exceptions Exception4319087
Ref: 1aa4319087
Ref: library/exceptions ArithmeticError4319238
Ref: 170e4319238
Ref: library/exceptions BufferError4319449
Ref: 17104319449
Ref: library/exceptions LookupError4319556
Ref: 166d4319556
Node: 具体异常4319797
Ref: library/exceptions concrete-exceptions4319888
Ref: 17124319888
Ref: library/exceptions AssertionError4319970
Ref: 103e4319970
Ref: library/exceptions AttributeError4320058
Ref: 3a34320058
Ref: library/exceptions EOFError4320292
Ref: c744320292
Ref: library/exceptions FloatingPointError4320565
Ref: 170f4320565
Ref: library/exceptions GeneratorExit4320625
Ref: d3a4320625
Ref: library/exceptions ImportError4320967
Ref: 33d4320967
Ref: library/exceptions ModuleNotFoundError4321460
Ref: 3a24321460
Ref: library/exceptions IndexError4321713
Ref: e7d4321713
Ref: library/exceptions KeyError4321924
Ref: 2c84321924
Ref: library/exceptions KeyboardInterrupt4322034
Ref: 1984322034
Ref: library/exceptions MemoryError4322379
Ref: efc4322379
Ref: library/exceptions NameError4322887
Ref: d834322887
Ref: library/exceptions NotImplementedError4323087
Ref: 6174323087
Ref: library/exceptions OSError4323830
Ref: 1d44323830
Ref: library/exceptions OSError errno4324784
Ref: 17154324784
Ref: library/exceptions OSError winerror4324872
Ref: 17164324872
Ref: library/exceptions OSError strerror4325412
Ref: 17174325412
Ref: library/exceptions OSError filename4325621
Ref: 17184325621
Ref: library/exceptions OSError filename24325647
Ref: 17194325647
Ref: library/exceptions OverflowError4326545
Ref: 9684326545
Ref: library/exceptions RecursionError4326960
Ref: 63d4326960
Ref: library/exceptions ReferenceError4327240
Ref: e554327240
Ref: library/exceptions RuntimeError4327509
Ref: 2bb4327509
Ref: library/exceptions StopIteration4327693
Ref: 48e4327693
Ref: library/exceptions StopAsyncIteration4328888
Ref: 10224328888
Ref: library/exceptions SyntaxError4329080
Ref: 4604329080
Ref: library/exceptions SyntaxError filename4329433
Ref: 171a4329433
Ref: library/exceptions SyntaxError lineno4329508
Ref: 171b4329508
Ref: library/exceptions SyntaxError offset4329662
Ref: 171c4329662
Ref: library/exceptions SyntaxError text4329819
Ref: 171d4329819
Ref: library/exceptions IndentationError4329890
Ref: e804329890
Ref: library/exceptions TabError4330037
Ref: e7f4330037
Ref: library/exceptions SystemError4330201
Ref: 6044330201
Ref: library/exceptions SystemExit4330777
Ref: 6054330777
Ref: library/exceptions SystemExit code4331963
Ref: 171f4331963
Ref: library/exceptions TypeError4332075
Ref: 1934332075
Ref: library/exceptions UnboundLocalError4332809
Ref: e7e4332809
Ref: library/exceptions UnicodeError4333018
Ref: c434333018
Ref: library/exceptions UnicodeError encoding4333375
Ref: 17204333375
Ref: library/exceptions UnicodeError reason4333444
Ref: 17214333444
Ref: library/exceptions UnicodeError object4333526
Ref: 17224333526
Ref: library/exceptions UnicodeError start4333611
Ref: 17234333611
Ref: library/exceptions UnicodeError end4333705
Ref: 17244333705
Ref: library/exceptions UnicodeEncodeError4333809
Ref: 1fd4333809
Ref: library/exceptions UnicodeDecodeError4333982
Ref: 1fe4333982
Ref: library/exceptions UnicodeTranslateError4334155
Ref: 17254334155
Ref: library/exceptions ValueError4334328
Ref: 1fc4334328
Ref: library/exceptions ZeroDivisionError4334533
Ref: 12bd4334533
Ref: library/exceptions EnvironmentError4334838
Ref: 99b4334838
Ref: library/exceptions IOError4334868
Ref: 99a4334868
Ref: library/exceptions WindowsError4334889
Ref: 99c4334889
Ref: 具体异常-Footnote-14335009
Ref: 具体异常-Footnote-24335058
Node: OS 异常4335107
Ref: library/exceptions os-exceptions4335165
Ref: 17144335165
Ref: library/exceptions BlockingIOError4335298
Ref: 99f4335298
Ref: library/exceptions BlockingIOError characters_written4335661
Ref: 17264335661
Ref: library/exceptions ChildProcessError4335864
Ref: 9a04335864
Ref: library/exceptions ConnectionError4335994
Ref: 6ef4335994
Ref: library/exceptions BrokenPipeError4336230
Ref: 9a54336230
Ref: library/exceptions ConnectionAbortedError4336485
Ref: 9a64336485
Ref: library/exceptions ConnectionRefusedError4336666
Ref: 9a74336666
Ref: library/exceptions ConnectionResetError4336847
Ref: 9a84336847
Ref: library/exceptions FileExistsError4337018
Ref: 9604337018
Ref: library/exceptions FileNotFoundError4337163
Ref: 7c94337163
Ref: library/exceptions InterruptedError4337296
Ref: 6624337296
Ref: library/exceptions IsADirectoryError4337677
Ref: 9a14337677
Ref: library/exceptions NotADirectoryError4337850
Ref: 9a24337850
Ref: library/exceptions PermissionError4338037
Ref: 6084338037
Ref: library/exceptions ProcessLookupError4338255
Ref: 9a34338255
Ref: library/exceptions TimeoutError4338376
Ref: 9a44338376
Ref: OS 异常-Footnote-14338701
Ref: OS 异常-Footnote-24338750
Node: 警告4338799
Ref: library/exceptions warning-categories-as-exceptions4338902
Ref: 17274338902
Ref: library/exceptions warnings4338902
Ref: 17284338902
Ref: library/exceptions Warning4339022
Ref: 172a4339022
Ref: library/exceptions UserWarning4339074
Ref: 172b4339074
Ref: library/exceptions DeprecationWarning4339145
Ref: 2794339145
Ref: library/exceptions PendingDeprecationWarning4339309
Ref: 27a4339309
Ref: library/exceptions SyntaxWarning4339639
Ref: 1924339639
Ref: library/exceptions RuntimeWarning4339718
Ref: 2c14339718
Ref: library/exceptions FutureWarning4339807
Ref: 32e4339807
Ref: library/exceptions ImportWarning4339984
Ref: 5e14339984
Ref: library/exceptions UnicodeWarning4340081
Ref: d8f4340081
Ref: library/exceptions BytesWarning4340155
Ref: 4bd4340155
Ref: library/exceptions ResourceWarning4340263
Ref: 4d84340263
Node: 异常层次结构4340405
Ref: library/exceptions exception-hierarchy4340487
Ref: 172c4340487
Ref: library/text stringservices4342715
Ref: 164e4342715
Node: 文本处理服务4342716
Ref: library/text doc4342838
Ref: 172d4342838
Ref: library/text text-processing-services4342838
Ref: 172e4342838
Ref: library/text textservices4342838
Ref: 16514342838
Node: string --- 常见的字符串操作4343786
Ref: library/string doc4343913
Ref: 17304343913
Ref: library/string module-string4343913
Ref: f74343913
Ref: library/string string-common-string-operations4343913
Ref: 17314343913
Ref: string --- 常见的字符串操作-Footnote-14344345
Node: 字符串常量4344410
Ref: library/string string-constants4344533
Ref: 17324344533
Ref: library/string string ascii_letters4344612
Ref: c644344612
Ref: library/string string ascii_lowercase4344785
Ref: 17334344785
Ref: library/string string ascii_uppercase4344939
Ref: 17344344939
Ref: library/string string digits4345093
Ref: 17354345093
Ref: library/string string hexdigits4345158
Ref: 17364345158
Ref: library/string string octdigits4345238
Ref: 17374345238
Ref: library/string string punctuation4345304
Ref: 17384345304
Ref: library/string string printable4345477
Ref: 17394345477
Ref: library/string string whitespace4345707
Ref: 173a4345707
Node: 自定义字符串格式化4345888
Ref: library/string custom-string-formatting4346041
Ref: 173b4346041
Ref: library/string string-formatting4346041
Ref: 16504346041
Ref: library/string string Formatter4346436
Ref: 7be4346436
Ref: library/string string Formatter format4346522
Ref: 4944346522
Ref: library/string string Formatter vformat4346858
Ref: 173c4346858
Ref: library/string string Formatter parse4347451
Ref: 173d4347451
Ref: library/string string Formatter get_field4348142
Ref: 173e4348142
Ref: library/string string Formatter get_value4348672
Ref: 173f4348672
Ref: library/string string Formatter check_unused_args4349717
Ref: 17404349717
Ref: library/string string Formatter format_field4350237
Ref: 17414350237
Ref: library/string string Formatter convert_field4350451
Ref: 17424350451
Ref: 自定义字符串格式化-Footnote-14350808
Ref: 自定义字符串格式化-Footnote-24350857
Node: 格式字符串语法4350906
Ref: library/string format-string-syntax4351059
Ref: 17434351059
Ref: library/string formatstrings4351059
Ref: d224351059
Ref: library/string grammar-token-replacement-field4351785
Ref: 17444351785
Ref: library/string grammar-token-field-name4351873
Ref: 17454351873
Ref: library/string grammar-token-arg-name4351960
Ref: 17464351960
Ref: library/string grammar-token-attribute-name4352014
Ref: 17474352014
Ref: library/string grammar-token-element-index4352057
Ref: 17484352057
Ref: library/string grammar-token-index-string4352111
Ref: 17494352111
Ref: library/string grammar-token-conversion4352179
Ref: 174a4352179
Ref: library/string grammar-token-format-spec4352227
Ref: 174b4352227
Node: 格式规格迷你语言4355869
Ref: library/string format-specification-mini-language4355972
Ref: 174d4355972
Ref: library/string formatspec4355972
Ref: 4e64355972
Ref: library/string id14356708
Ref: 174e4356708
Ref: library/string grammar-token-fill4356801
Ref: 174f4356801
Ref: library/string grammar-token-align4356842
Ref: 17504356842
Ref: library/string grammar-token-sign4356889
Ref: 17514356889
Ref: library/string grammar-token-width4356930
Ref: 17524356930
Ref: library/string grammar-token-grouping-option4356962
Ref: 17534356962
Ref: library/string grammar-token-precision4356997
Ref: 17544356997
Ref: library/string grammar-token-type4357029
Ref: 17554357029
Ref: 格式规格迷你语言-Footnote-14368172
Ref: 格式规格迷你语言-Footnote-24368221
Node: 格式示例4368270
Ref: library/string format-examples4368373
Ref: 17564368373
Ref: library/string formatexamples4368373
Ref: 174c4368373
Node: 模板字符串4372760
Ref: library/string id24372898
Ref: 17574372898
Ref: library/string template-strings4372898
Ref: 16704372898
Ref: library/string string Template4374282
Ref: 3f34374282
Ref: library/string string Template substitute4374380
Ref: 130f4374380
Ref: library/string string Template safe_substitute4374800
Ref: 13104374800
Ref: library/string string Template template4375822
Ref: 17584375822
Ref: 模板字符串-Footnote-14379323
Ref: 模板字符串-Footnote-24379372
Node: 辅助函数4379423
Ref: library/string helper-functions4379531
Ref: 17594379531
Ref: library/string string capwords4379570
Ref: 175a4379570
Node: re --- 正则表达式操作4380051
Ref: library/re doc4380226
Ref: 175b4380226
Ref: library/re module-re4380226
Ref: de4380226
Ref: library/re re-regular-expression-operations4380226
Ref: 175c4380226
Ref: re --- 正则表达式操作-Footnote-14382634
Ref: re --- 正则表达式操作-Footnote-24382695
Node: 正则表达式语法4382735
Ref: library/re re-syntax4382842
Ref: 175d4382842
Ref: library/re regular-expression-syntax4382842
Ref: 175e4382842
Ref: 正则表达式语法-Footnote-14403856
Node: 模块内容4403898
Ref: library/re contents-of-module-re4404054
Ref: 17694404054
Ref: library/re module-contents4404054
Ref: 176a4404054
Ref: library/re re compile4404462
Ref: 4524404462
Ref: library/re re A4405427
Ref: 17634405427
Ref: library/re re ASCII4405444
Ref: 3d04405444
Ref: library/re re DEBUG4405998
Ref: 176e4405998
Ref: library/re re I4406080
Ref: 17644406080
Ref: library/re re IGNORECASE4406097
Ref: 176f4406097
Ref: library/re re L4406996
Ref: 17654406996
Ref: library/re re LOCALE4407013
Ref: 3d14407013
Ref: library/re re M4407769
Ref: 17664407769
Ref: library/re re MULTILINE4407786
Ref: 17624407786
Ref: library/re re S4408180
Ref: 17674408180
Ref: library/re re DOTALL4408197
Ref: 17614408197
Ref: library/re re X4408419
Ref: 17684408419
Ref: library/re re VERBOSE4408436
Ref: 17704408436
Ref: library/re re search4409185
Ref: bba4409185
Ref: library/re re match4409475
Ref: bbb4409475
Ref: library/re re fullmatch4410070
Ref: 8a44410070
Ref: library/re re split4410352
Ref: 3d24410352
Ref: library/re re findall4411994
Ref: 96b4411994
Ref: library/re re finditer4412478
Ref: 17724412478
Ref: library/re re sub4412863
Ref: 4834412863
Ref: library/re re subn4415702
Ref: 73d4415702
Ref: library/re re escape4415996
Ref: 49d4415996
Ref: library/re re purge4417390
Ref: 17734417390
Ref: library/re re error4417455
Ref: 73e4417455
Ref: library/re re error msg4417832
Ref: 73f4417832
Ref: library/re re error pattern4417896
Ref: 7404417896
Ref: library/re re error pos4417964
Ref: 7414417964
Ref: library/re re error lineno4418069
Ref: 7424418069
Ref: library/re re error colno4418154
Ref: 7434418154
Node: 正则表达式对象 （正则对象）4418291
Ref: library/re re-objects4418438
Ref: 8a54418438
Ref: library/re regular-expression-objects4418438
Ref: 17744418438
Ref: library/re re Pattern search4418589
Ref: 176d4418589
Ref: library/re re Pattern match4419779
Ref: 176c4419779
Ref: library/re re Pattern fullmatch4420576
Ref: 17754420576
Ref: library/re re Pattern split4421283
Ref: 17764421283
Ref: library/re re Pattern findall4421407
Ref: 17774421407
Ref: library/re re Pattern finditer4421645
Ref: 17784421645
Ref: library/re re Pattern sub4421877
Ref: 17794421877
Ref: library/re re Pattern subn4422000
Ref: 177a4422000
Ref: library/re re Pattern flags4422125
Ref: 177b4422125
Ref: library/re re Pattern groups4422321
Ref: 177c4422321
Ref: library/re re Pattern groupindex4422395
Ref: 177d4422395
Ref: library/re re Pattern pattern4422567
Ref: 177e4422567
Node: 匹配对象4422804
Ref: library/re id24422960
Ref: 177f4422960
Ref: library/re match-objects4422960
Ref: 8a64422960
Ref: library/re re Match expand4423330
Ref: 17804423330
Ref: library/re re Match group4423717
Ref: 17814423717
Ref: library/re re Match __getitem__4425714
Ref: 17824425714
Ref: library/re re Match groups4426154
Ref: 17834426154
Ref: library/re re Match groupdict4426914
Ref: 17844426914
Ref: library/re re Match start4427307
Ref: 17854427307
Ref: library/re re Match end4427341
Ref: 17864427341
Ref: library/re re Match span4428334
Ref: 17874428334
Ref: library/re re Match pos4428594
Ref: 17884428594
Ref: library/re re Match endpos4428825
Ref: 17894428825
Ref: library/re re Match lastindex4429062
Ref: 178a4429062
Ref: library/re re Match lastgroup4429391
Ref: 178b4429391
Ref: library/re re Match re4429517
Ref: 178c4429517
Ref: library/re re Match string4429708
Ref: 178d4429708
Node: 正则表达式例子4429954
Ref: library/re re-examples4430061
Ref: bfc4430061
Ref: library/re regular-expression-examples4430061
Ref: 178e4430061
Node: 检查对子4430374
Ref: library/re checking-for-a-pair4430465
Ref: 178f4430465
Node: 模拟 scanf4432397
Ref: library/re simulating-scanf4432512
Ref: 17904432512
Node: search vs match4434505
Ref: library/re id34434629
Ref: 17914434629
Ref: library/re search-vs-match4434629
Ref: 17714434629
Node: 制作一个电话本4435682
Ref: library/re making-a-phonebook4435806
Ref: 17924435806
Node: 文字整理4437884
Ref: library/re text-munging4438011
Ref: 17934438011
Node: 查找所有副词4438733
Ref: library/re finding-all-adverbs4438872
Ref: 17944438872
Node: 查找所有的副词及其位置4439305
Ref: library/re finding-all-adverbs-and-their-positions4439453
Ref: 17954439453
Node: 原始字符串标记4440074
Ref: library/re raw-string-notation4440228
Ref: 17964440228
Node: 写一个词法分析器4441035
Ref: library/re writing-a-tokenizer4441147
Ref: 17974441147
Ref: library/re frie094444467
Ref: 175f4444467
Ref: 写一个词法分析器-Footnote-14444707
Node: difflib --- 计算差异的辅助工具4444762
Ref: library/difflib doc4444942
Ref: 17984444942
Ref: library/difflib difflib-helpers-for-computing-deltas4444942
Ref: 17994444942
Ref: library/difflib module-difflib4444942
Ref: 374444942
Ref: library/difflib difflib Differ4447153
Ref: 179a4447153
Ref: library/difflib difflib HtmlDiff4448202
Ref: 179b4448202
Ref: library/difflib difflib HtmlDiff __init__4448505
Ref: 179c4448505
Ref: library/difflib difflib HtmlDiff make_file4449263
Ref: 6d24449263
Ref: library/difflib difflib HtmlDiff make_table4450783
Ref: 179e4450783
Ref: library/difflib difflib context_diff4451299
Ref: 179f4451299
Ref: library/difflib difflib get_close_matches4453141
Ref: 17a34453141
Ref: library/difflib difflib ndiff4454281
Ref: 179d4454281
Ref: library/difflib difflib restore4455856
Ref: 17a64455856
Ref: library/difflib difflib unified_diff4456580
Ref: 17a84456580
Ref: library/difflib difflib diff_bytes4458397
Ref: 6d34458397
Ref: library/difflib difflib IS_LINE_JUNK4459288
Ref: 17a44459288
Ref: library/difflib difflib IS_CHARACTER_JUNK4459594
Ref: 17a54459594
Ref: difflib --- 计算差异的辅助工具-Footnote-14460243
Ref: difflib --- 计算差异的辅助工具-Footnote-24460309
Ref: difflib --- 计算差异的辅助工具-Footnote-34460398
Node: SequenceMatcher 对象4460430
Ref: library/difflib sequence-matcher4460562
Ref: 17a94460562
Ref: library/difflib sequencematcher-objects4460562
Ref: 17aa4460562
Ref: library/difflib difflib SequenceMatcher4460683
Ref: 9574460683
Ref: library/difflib difflib SequenceMatcher set_seqs4462073
Ref: 17ab4462073
Ref: library/difflib difflib SequenceMatcher set_seq14462465
Ref: 17ad4462465
Ref: library/difflib difflib SequenceMatcher set_seq24462587
Ref: 17ac4462587
Ref: library/difflib difflib SequenceMatcher find_longest_match4462709
Ref: 17ae4462709
Ref: library/difflib difflib SequenceMatcher get_matching_blocks4464655
Ref: 17af4464655
Ref: library/difflib difflib SequenceMatcher get_opcodes4465538
Ref: 17b04465538
Ref: library/difflib difflib SequenceMatcher get_grouped_opcodes4467448
Ref: 17b14467448
Ref: library/difflib difflib SequenceMatcher ratio4467820
Ref: 17b24467820
Ref: library/difflib difflib SequenceMatcher quick_ratio4468770
Ref: 17b34468770
Ref: library/difflib difflib SequenceMatcher real_quick_ratio4468876
Ref: 17b44468876
Node: SequenceMatcher 的示例4469369
Ref: library/difflib id14469523
Ref: 17b54469523
Ref: library/difflib sequencematcher-examples4469523
Ref: 17b64469523
Ref: SequenceMatcher 的示例-Footnote-14471220
Node: Differ 对象4471273
Ref: library/difflib differ-objects4471418
Ref: 17b74471418
Ref: library/difflib id24471418
Ref: 17b84471418
Ref: library/difflib difflib Differ compare4472749
Ref: 17a74472749
Node: Differ 示例4473235
Ref: library/difflib differ-example4473381
Ref: 17b94473381
Ref: library/difflib differ-examples4473381
Ref: 17ba4473381
Node: difflib 的命令行接口4475648
Ref: library/difflib a-command-line-interface-to-difflib4475772
Ref: 17bb4475772
Ref: library/difflib difflib-interface4475772
Ref: 17a24475772
Node: textwrap --- 文本自动换行与填充4478523
Ref: library/textwrap doc4478708
Ref: 17bc4478708
Ref: library/textwrap module-textwrap4478708
Ref: 1094478708
Ref: library/textwrap textwrap-text-wrapping-and-filling4478708
Ref: 17bd4478708
Ref: library/textwrap textwrap wrap4479216
Ref: 17be4479216
Ref: library/textwrap textwrap fill4479702
Ref: 17c04479702
Ref: library/textwrap textwrap shorten4480085
Ref: 8f54480085
Ref: library/textwrap textwrap dedent4481132
Ref: 17c54481132
Ref: library/textwrap textwrap indent4481970
Ref: ab04481970
Ref: library/textwrap textwrap TextWrapper4483285
Ref: 8f24483285
Ref: library/textwrap textwrap TextWrapper width4483897
Ref: 17c74483897
Ref: library/textwrap textwrap TextWrapper expand_tabs4484170
Ref: 17c24484170
Ref: library/textwrap textwrap TextWrapper tabsize4484360
Ref: 17c14484360
Ref: library/textwrap textwrap TextWrapper replace_whitespace4484636
Ref: 17c44484636
Ref: library/textwrap textwrap TextWrapper drop_whitespace4485542
Ref: 17c34485542
Ref: library/textwrap textwrap TextWrapper initial_indent4485926
Ref: 17c84485926
Ref: library/textwrap textwrap TextWrapper subsequent_indent4486144
Ref: 17c94486144
Ref: library/textwrap textwrap TextWrapper fix_sentence_endings4486368
Ref: 17ca4486368
Ref: library/textwrap textwrap TextWrapper break_long_words4487419
Ref: 17c64487419
Ref: library/textwrap textwrap TextWrapper break_on_hyphens4487867
Ref: 17cb4487867
Ref: library/textwrap textwrap TextWrapper max_lines4488344
Ref: 8f34488344
Ref: library/textwrap textwrap TextWrapper placeholder4488573
Ref: 8f44488573
Ref: library/textwrap textwrap TextWrapper wrap4488841
Ref: 17bf4488841
Ref: library/textwrap textwrap TextWrapper fill4489257
Ref: 17cc4489257
Ref: textwrap --- 文本自动换行与填充-Footnote-14489444
Node: unicodedata --- Unicode 数据库4489511
Ref: library/unicodedata doc4489696
Ref: 17cd4489696
Ref: library/unicodedata module-unicodedata4489696
Ref: 11b4489696
Ref: library/unicodedata unicodedata-unicode-database4489696
Ref: 17ce4489696
Ref: library/unicodedata unicodedata lookup4490182
Ref: 9c54490182
Ref: library/unicodedata unicodedata name4490473
Ref: 17cf4490473
Ref: library/unicodedata unicodedata decimal4490697
Ref: 17d04490697
Ref: library/unicodedata unicodedata digit4490935
Ref: 17d14490935
Ref: library/unicodedata unicodedata numeric4491168
Ref: c014491168
Ref: library/unicodedata unicodedata category4491403
Ref: 17d24491403
Ref: library/unicodedata unicodedata bidirectional4491508
Ref: 17d34491508
Ref: library/unicodedata unicodedata combining4491675
Ref: 17d44491675
Ref: library/unicodedata unicodedata east_asian_width4491841
Ref: 17d54491841
Ref: library/unicodedata unicodedata mirrored4491957
Ref: 17d64491957
Ref: library/unicodedata unicodedata decomposition4492173
Ref: 17d74492173
Ref: library/unicodedata unicodedata normalize4492352
Ref: 10bf4492352
Ref: library/unicodedata unicodedata is_normalized4493932
Ref: 2474493932
Ref: library/unicodedata unicodedata unidata_version4494206
Ref: 17d84494206
Ref: library/unicodedata unicodedata ucd_3_2_04494305
Ref: da44494305
Ref: unicodedata --- Unicode 数据库-Footnote-14495068
Ref: unicodedata --- Unicode 数据库-Footnote-24495117
Ref: unicodedata --- Unicode 数据库-Footnote-34495163
Ref: unicodedata --- Unicode 数据库-Footnote-44495238
Node: stringprep --- 因特网字符串预备4495316
Ref: library/stringprep doc4495493
Ref: 17d94495493
Ref: library/stringprep module-stringprep4495493
Ref: f84495493
Ref: library/stringprep stringprep-internet-string-preparation4495493
Ref: 17da4495493
Ref: library/stringprep stringprep in_table_a14497165
Ref: 17db4497165
Ref: library/stringprep stringprep in_table_b14497289
Ref: 17dc4497289
Ref: library/stringprep stringprep map_table_b24497401
Ref: 17dd4497401
Ref: library/stringprep stringprep map_table_b34497551
Ref: 17de4497551
Ref: library/stringprep stringprep in_table_c114497701
Ref: 17df4497701
Ref: library/stringprep stringprep in_table_c124497813
Ref: 17e04497813
Ref: library/stringprep stringprep in_table_c11_c124497929
Ref: 17e14497929
Ref: library/stringprep stringprep in_table_c214498065
Ref: 17e24498065
Ref: library/stringprep stringprep in_table_c224498177
Ref: 17e34498177
Ref: library/stringprep stringprep in_table_c21_c224498293
Ref: 17e44498293
Ref: library/stringprep stringprep in_table_c34498429
Ref: 17e54498429
Ref: library/stringprep stringprep in_table_c44498532
Ref: 17e64498532
Ref: library/stringprep stringprep in_table_c54498638
Ref: 17e74498638
Ref: library/stringprep stringprep in_table_c64498738
Ref: 17e84498738
Ref: library/stringprep stringprep in_table_c74498850
Ref: 17e94498850
Ref: library/stringprep stringprep in_table_c84498965
Ref: 17ea4498965
Ref: library/stringprep stringprep in_table_c94499086
Ref: 17eb4499086
Ref: library/stringprep stringprep in_table_d14499189
Ref: 17ec4499189
Ref: library/stringprep stringprep in_table_d24499321
Ref: 17ed4499321
Ref: stringprep --- 因特网字符串预备-Footnote-14499480
Ref: stringprep --- 因特网字符串预备-Footnote-24499549
Ref: stringprep --- 因特网字符串预备-Footnote-34499598
Node: readline --- GNU readline 接口4499647
Ref: library/readline doc4499835
Ref: 17ee4499835
Ref: library/readline module-readline4499835
Ref: df4499835
Ref: library/readline readline-gnu-readline-interface4499835
Ref: 17ef4499835
Ref: readline --- GNU readline 接口-Footnote-14501579
Node: 初始化文件4501649
Ref: library/readline init-file4501754
Ref: 17f04501754
Ref: library/readline readline parse_and_bind4501854
Ref: 17f14501854
Ref: library/readline readline read_init_file4502027
Ref: 17f24502027
Node: 行缓冲区4502242
Ref: library/readline line-buffer4502368
Ref: 17f34502368
Ref: library/readline readline get_line_buffer4502451
Ref: 17f44502451
Ref: library/readline readline insert_text4502574
Ref: 17f54502574
Ref: library/readline readline redisplay4502767
Ref: 17f64502767
Node: 历史文件4502932
Ref: library/readline history-file4503055
Ref: 17f74503055
Ref: library/readline readline read_history_file4503138
Ref: 17f84503138
Ref: library/readline readline write_history_file4503370
Ref: 17f94503370
Ref: library/readline readline append_history_file4503610
Ref: 7454503610
Ref: library/readline readline get_history_length4503995
Ref: 17fa4503995
Ref: library/readline readline set_history_length4504038
Ref: 17fb4504038
Node: 历史列表4504350
Ref: library/readline history-list4504473
Ref: 17fc4504473
Ref: library/readline readline clear_history4504562
Ref: 17fd4504562
Ref: library/readline readline get_current_history_length4504783
Ref: 17fe4504783
Ref: library/readline readline get_history_item4505002
Ref: 17ff4505002
Ref: library/readline readline remove_history_item4505204
Ref: 18004505204
Ref: library/readline readline replace_history_item4505410
Ref: 18014505410
Ref: library/readline readline add_history4505625
Ref: 18024505625
Ref: library/readline readline set_auto_history4505810
Ref: 5804505810
Node: 启动钩子4506250
Ref: library/readline startup-hooks4506371
Ref: 18034506371
Ref: library/readline readline set_startup_hook4506410
Ref: 18044506410
Ref: library/readline readline set_pre_input_hook4506796
Ref: 18054506796
Node: Completion4507308
Ref: library/readline completion4507423
Ref: 18064507423
Ref: library/readline readline set_completer4507854
Ref: 18074507854
Ref: library/readline readline get_completer4508581
Ref: 18084508581
Ref: library/readline readline get_completion_type4508701
Ref: 18094508701
Ref: library/readline readline get_begidx4508884
Ref: 180a4508884
Ref: library/readline readline get_endidx4508919
Ref: 180b4508919
Ref: library/readline readline set_completer_delims4509135
Ref: 180c4509135
Ref: library/readline readline get_completer_delims4509186
Ref: 180d4509186
Ref: library/readline readline set_completion_display_matches_hook4509465
Ref: 180e4509465
Node: 示例4510002
Ref: library/readline example4510096
Ref: 180f4510096
Ref: library/readline readline-example4510096
Ref: 18104510096
Node: rlcompleter --- GNU readline 的补全函数4512632
Ref: library/rlcompleter doc4512772
Ref: 18124512772
Ref: library/rlcompleter module-rlcompleter4512772
Ref: e24512772
Ref: library/rlcompleter rlcompleter-completion-function-for-gnu-readline4512772
Ref: 18134512772
Ref: rlcompleter --- GNU readline 的补全函数-Footnote-14514154
Node: Completer 对象4514224
Ref: library/rlcompleter completer-objects4514321
Ref: 18144514321
Ref: library/rlcompleter id14514321
Ref: 18154514321
Ref: library/rlcompleter rlcompleter Completer complete4514409
Ref: 18164514409
Node: 二进制数据服务4515134
Ref: library/binary doc4515256
Ref: 18174515256
Ref: library/binary binary-data-services4515256
Ref: 18184515256
Ref: library/binary binaryservices4515256
Ref: 172f4515256
Node: struct --- 将字节串解读为打包的二进制数据4516059
Ref: library/struct doc4516226
Ref: 18194516226
Ref: library/struct module-struct4516226
Ref: f94516226
Ref: library/struct struct-interpret-bytes-as-packed-binary-data4516226
Ref: 181a4516226
Ref: struct --- 将字节串解读为打包的二进制数据-Footnote-14517882
Node: 函数和异常4517947
Ref: library/struct functions-and-exceptions4518079
Ref: 181e4518079
Ref: library/struct struct error4518167
Ref: cbc4518167
Ref: library/struct struct pack4518293
Ref: c134518293
Ref: library/struct struct pack_into4518518
Ref: 181f4518518
Ref: library/struct struct unpack4518792
Ref: 13134518792
Ref: library/struct struct unpack_from4519128
Ref: 18214519128
Ref: library/struct struct iter_unpack4519481
Ref: 8e04519481
Ref: library/struct struct calcsize4519941
Ref: 18204519941
Node: 格式字符串4520128
Ref: library/struct format-strings4520275
Ref: 18224520275
Ref: library/struct struct-format-strings4520275
Ref: 181b4520275
Node: 字节顺序，大小和对齐方式4520684
Ref: library/struct byte-order-size-and-alignment4520793
Ref: 18244520793
Ref: library/struct struct-alignment4520793
Ref: 181c4520793
Ref: 字节顺序，大小和对齐方式-Footnote-14523845
Node: 格式字符4523889
Ref: library/struct format-characters4524016
Ref: 18234524016
Ref: library/struct id14524016
Ref: 18264524016
Ref: 格式字符-Footnote-14534553
Ref: 格式字符-Footnote-24534625
Node: 例子<2>4534701
Ref: library/struct examples4534783
Ref: 18274534783
Ref: library/struct struct-examples4534783
Ref: 18254534783
Node: 类<2>4536447
Ref: library/struct classes4536570
Ref: 18284536570
Ref: library/struct struct-objects4536570
Ref: 18294536570
Ref: library/struct struct Struct4536647
Ref: 181d4536647
Ref: library/struct struct Struct pack4537297
Ref: 182a4537297
Ref: library/struct struct Struct pack_into4537475
Ref: 182c4537475
Ref: library/struct struct Struct unpack4537619
Ref: 182d4537619
Ref: library/struct struct Struct unpack_from4537805
Ref: 182e4537805
Ref: library/struct struct Struct iter_unpack4538049
Ref: 8e14538049
Ref: library/struct struct Struct format4538277
Ref: 49a4538277
Ref: library/struct struct Struct size4538485
Ref: 182b4538485
Node: codecs --- 编解码器注册和相关基类4538660
Ref: library/codecs doc4538827
Ref: 182f4538827
Ref: library/codecs codecs-codec-registry-and-base-classes4538827
Ref: 18304538827
Ref: library/codecs ietf-rfc-17004538827
Ref: 18314538827
Ref: library/codecs module-codecs4538827
Ref: 1c4538827
Ref: library/codecs codecs encode4539733
Ref: 80b4539733
Ref: library/codecs codecs decode4540238
Ref: 80c4540238
Ref: library/codecs codecs lookup4540808
Ref: 17114540808
Ref: library/codecs codecs CodecInfo4541294
Ref: 18334541294
Ref: library/codecs codecs CodecInfo name4541582
Ref: 18344541582
Ref: library/codecs codecs CodecInfo encode4541629
Ref: 18354541629
Ref: library/codecs codecs CodecInfo decode4541653
Ref: 18364541653
Ref: library/codecs codecs CodecInfo incrementalencoder4541974
Ref: 183a4541974
Ref: library/codecs codecs CodecInfo incrementaldecoder4542010
Ref: 183b4542010
Ref: library/codecs codecs CodecInfo streamwriter4542318
Ref: 183e4542318
Ref: library/codecs codecs CodecInfo streamreader4542348
Ref: 183f4542348
Ref: library/codecs codecs getencoder4542775
Ref: 18424542775
Ref: library/codecs codecs getdecoder4542955
Ref: 18434542955
Ref: library/codecs codecs getincrementalencoder4543135
Ref: 18444543135
Ref: library/codecs codecs getincrementaldecoder4543394
Ref: 18454543394
Ref: library/codecs codecs getreader4543653
Ref: 18464543653
Ref: library/codecs codecs getwriter4543868
Ref: 18474543868
Ref: library/codecs codecs register4544166
Ref: 18484544166
Ref: library/codecs codecs open4544894
Ref: 13724544894
Ref: library/codecs codecs EncodedFile4546022
Ref: 184a4546022
Ref: library/codecs codecs iterencode4546797
Ref: 184b4546797
Ref: library/codecs codecs iterdecode4547294
Ref: 184c4547294
Ref: library/codecs codecs BOM4547953
Ref: 184d4547953
Ref: library/codecs codecs BOM_BE4547976
Ref: 184e4547976
Ref: library/codecs codecs BOM_LE4548002
Ref: 184f4548002
Ref: library/codecs codecs BOM_UTF84548028
Ref: 18504548028
Ref: library/codecs codecs BOM_UTF164548056
Ref: 18514548056
Ref: library/codecs codecs BOM_UTF16_BE4548085
Ref: 18524548085
Ref: library/codecs codecs BOM_UTF16_LE4548117
Ref: 18534548117
Ref: library/codecs codecs BOM_UTF324548149
Ref: 18544548149
Ref: library/codecs codecs BOM_UTF32_BE4548178
Ref: 18554548178
Ref: library/codecs codecs BOM_UTF32_LE4548210
Ref: 18564548210
Ref: codecs --- 编解码器注册和相关基类-Footnote-14549344
Node: 编解码器基类4549409
Ref: library/codecs codec-base-classes4549540
Ref: 18324549540
Ref: library/codecs id14549540
Ref: 18574549540
Ref: library/codecs surrogateescape4550089
Ref: 18584550089
Node: 错误处理方案4550216
Ref: library/codecs error-handlers4550325
Ref: 13714550325
Ref: library/codecs id24550325
Ref: 18594550325
Ref: library/codecs codecs register_error4554139
Ref: dfd4554139
Ref: library/codecs codecs lookup_error4555594
Ref: dfe4555594
Ref: library/codecs codecs strict_errors4555863
Ref: 185a4555863
Ref: library/codecs codecs replace_errors4556031
Ref: 185c4556031
Ref: library/codecs codecs ignore_errors4556301
Ref: 185b4556301
Ref: library/codecs codecs xmlcharrefreplace_errors4556475
Ref: 185d4556475
Ref: library/codecs codecs backslashreplace_errors4556720
Ref: 185e4556720
Ref: library/codecs codecs namereplace_errors4556948
Ref: 185f4556948
Ref: 错误处理方案-Footnote-14557243
Node: 无状态的编码和解码4557292
Ref: library/codecs codec-objects4557437
Ref: 18394557437
Ref: library/codecs stateless-encoding-and-decoding4557437
Ref: 18604557437
Ref: library/codecs codecs Codec encode4557616
Ref: 18374557616
Ref: library/codecs codecs Codec decode4558315
Ref: 18384558315
Node: 增量式的编码和解码4559201
Ref: library/codecs incremental-encoding-and-decoding4559352
Ref: 18614559352
Node: IncrementalEncoder 对象4560097
Ref: library/codecs incremental-encoder-objects4560220
Ref: 18644560220
Ref: library/codecs incrementalencoder-objects4560220
Ref: 18654560220
Ref: library/codecs codecs IncrementalEncoder4560497
Ref: 183c4560497
Ref: library/codecs codecs IncrementalEncoder encode4561217
Ref: 18624561217
Ref: library/codecs codecs IncrementalEncoder reset4561494
Ref: 18664561494
Ref: library/codecs codecs IncrementalEncoder getstate4561739
Ref: 18674561739
Ref: library/codecs codecs IncrementalEncoder setstate4562070
Ref: 18684562070
Node: IncrementalDecoder 对象4562244
Ref: library/codecs incremental-decoder-objects4562367
Ref: 18694562367
Ref: library/codecs incrementaldecoder-objects4562367
Ref: 186a4562367
Ref: library/codecs codecs IncrementalDecoder4562644
Ref: 183d4562644
Ref: library/codecs codecs IncrementalDecoder decode4563364
Ref: 18634563364
Ref: library/codecs codecs IncrementalDecoder reset4563965
Ref: 186b4563965
Ref: library/codecs codecs IncrementalDecoder getstate4564040
Ref: 186c4564040
Ref: library/codecs codecs IncrementalDecoder setstate4564830
Ref: 186d4564830
Node: 流式的编码和解码4565004
Ref: library/codecs stream-encoding-and-decoding4565119
Ref: 186e4565119
Node: StreamWriter 对象4565527
Ref: library/codecs stream-writer-objects4565635
Ref: 186f4565635
Ref: library/codecs streamwriter-objects4565635
Ref: 18704565635
Ref: library/codecs codecs StreamWriter4565875
Ref: 18404565875
Ref: library/codecs codecs StreamWriter write4566770
Ref: 18714566770
Ref: library/codecs codecs StreamWriter writelines4566857
Ref: 18724566857
Ref: library/codecs codecs StreamWriter reset4567070
Ref: 18734567070
Node: StreamReader 对象4567464
Ref: library/codecs stream-reader-objects4567606
Ref: 18744567606
Ref: library/codecs streamreader-objects4567606
Ref: 18754567606
Ref: library/codecs codecs StreamReader4567846
Ref: 18414567846
Ref: library/codecs codecs StreamReader read4568844
Ref: 18764568844
Ref: library/codecs codecs StreamReader readline4569905
Ref: 18774569905
Ref: library/codecs codecs StreamReader readlines4570225
Ref: 18784570225
Ref: library/codecs codecs StreamReader reset4570652
Ref: 18794570652
Node: StreamReaderWriter 对象4570996
Ref: library/codecs stream-reader-writer4571139
Ref: 187a4571139
Ref: library/codecs streamreaderwriter-objects4571139
Ref: 187b4571139
Ref: library/codecs codecs StreamReaderWriter4571443
Ref: 18494571443
Node: StreamRecoder 对象4572066
Ref: library/codecs stream-recoder-objects4572181
Ref: 187c4572181
Ref: library/codecs streamrecoder-objects4572181
Ref: 187d4572181
Ref: library/codecs codecs StreamRecoder4572493
Ref: fdd4572493
Node: 编码格式与 Unicode4573527
Ref: library/codecs encodings-and-unicode4573679
Ref: 187e4573679
Ref: library/codecs encodings-overview4573679
Ref: 187f4573679
Ref: 编码格式与 Unicode-Footnote-14580255
Node: 标准编码4580304
Ref: library/codecs id34580466
Ref: 18804580466
Ref: library/codecs standard-encodings4580466
Ref: 6984580466
Node: Python 专属的编码格式4602254
Ref: library/codecs python-specific-encodings4602445
Ref: 18814602445
Node: 文字编码4602983
Ref: library/codecs text-encodings4603084
Ref: 18824603084
Ref: 文字编码-Footnote-14606176
Ref: 文字编码-Footnote-24606225
Node: 二进制转换4606274
Ref: library/codecs binary-transforms4606396
Ref: 80d4606396
Ref: library/codecs id44606396
Ref: 18834606396
Ref: 二进制转换-Footnote-14610120
Node: 文字转换4610254
Ref: library/codecs id64610355
Ref: 188c4610355
Ref: library/codecs text-transforms4610355
Ref: 80e4610355
Node: encodings idna --- 应用程序中的国际化域名4611023
Ref: library/codecs encodings-idna-internationalized-domain-names-in-applications4611242
Ref: 188d4611242
Ref: library/codecs module-encodings idna4611242
Ref: 774611242
Ref: library/codecs encodings idna nameprep4613661
Ref: 188e4613661
Ref: library/codecs encodings idna ToASCII4613851
Ref: 188f4613851
Ref: library/codecs encodings idna ToUnicode4614008
Ref: 18904614008
Ref: encodings idna --- 应用程序中的国际化域名-Footnote-14614156
Ref: encodings idna --- 应用程序中的国际化域名-Footnote-24614205
Ref: encodings idna --- 应用程序中的国际化域名-Footnote-34614254
Ref: encodings idna --- 应用程序中的国际化域名-Footnote-44614303
Ref: encodings idna --- 应用程序中的国际化域名-Footnote-54614352
Ref: encodings idna --- 应用程序中的国际化域名-Footnote-64614413
Ref: encodings idna --- 应用程序中的国际化域名-Footnote-74614462
Node: encodings mbcs --- Windows ANSI代码页4614511
Ref: library/codecs encodings-mbcs-windows-ansi-codepage4614758
Ref: 18914614758
Ref: library/codecs module-encodings mbcs4614758
Ref: 784614758
Node: encodings utf_8_sig --- 带BOM签名的UTF-8编解码器4615156
Ref: library/codecs encodings-utf-8-sig-utf-8-codec-with-bom-signature4615342
Ref: 18924615342
Ref: library/codecs module-encodings utf_8_sig4615342
Ref: 794615342
Node: 数据类型4615777
Ref: library/datatypes doc4615902
Ref: 18934615902
Ref: library/datatypes data-types4615902
Ref: 18944615902
Ref: library/datatypes datatypes4615902
Ref: 18954615902
Node: datetime --- 基本的日期和时间类型4617389
Ref: library/datetime doc4617521
Ref: 18964617521
Ref: library/datetime datetime-basic-date-and-time-types4617521
Ref: 18974617521
Ref: library/datetime module-datetime4617521
Ref: 314617521
Ref: datetime --- 基本的日期和时间类型-Footnote-14618451
Ref: datetime --- 基本的日期和时间类型-Footnote-24618518
Node: 感知型对象和简单型对象4618569
Ref: library/datetime aware-and-naive-objects4618697
Ref: 18984618697
Ref: library/datetime datetime-naive-aware4618697
Ref: 18994618697
Ref: 感知型对象和简单型对象-Footnote-14620468
Node: 常量4620532
Ref: library/datetime constants4620684
Ref: 189a4620684
Ref: library/datetime datetime MINYEAR4620778
Ref: 189b4620778
Ref: library/datetime datetime MAXYEAR4620940
Ref: 189c4620940
Node: 有效的类型4621100
Ref: library/datetime available-types4621238
Ref: 189d4621238
Node: 通用的特征属性4622901
Ref: library/datetime common-properties4623028
Ref: 18ae4623028
Node: 确定一个对象是感知型还是简单型4623424
Ref: library/datetime determining-if-an-object-is-aware-or-naive4623551
Ref: 18af4623551
Node: timedelta 类对象4624348
Ref: library/datetime datetime-timedelta4624491
Ref: 18b04624491
Ref: library/datetime timedelta-objects4624491
Ref: 18b14624491
Ref: library/datetime datetime timedelta4624631
Ref: 1964624631
Ref: library/datetime datetime timedelta min4626827
Ref: 18b24626827
Ref: library/datetime datetime timedelta max4626942
Ref: 18b34626942
Ref: library/datetime datetime timedelta resolution4627121
Ref: 18b44627121
Ref: library/datetime datetime timedelta total_seconds4634025
Ref: ca44634025
Node: class timedelta 用法示例4634537
Ref: library/datetime examples-of-usage-timedelta4634621
Ref: 18b54634621
Node: date 对象4635549
Ref: library/datetime date-objects4635692
Ref: 18b64635692
Ref: library/datetime datetime-date4635692
Ref: 18b74635692
Ref: library/datetime datetime date4635989
Ref: 1944635989
Ref: library/datetime datetime date today4636379
Ref: 18b84636379
Ref: library/datetime datetime date fromtimestamp4636515
Ref: 18b94636515
Ref: library/datetime datetime date fromordinal4637401
Ref: 18ba4637401
Ref: library/datetime datetime date fromisoformat4637745
Ref: 10a74637745
Ref: library/datetime datetime date fromisocalendar4638168
Ref: 1c54638168
Ref: library/datetime datetime date min4638424
Ref: 18bd4638424
Ref: library/datetime datetime date max4638498
Ref: 18be4638498
Ref: library/datetime datetime date resolution4638576
Ref: 18bf4638576
Ref: library/datetime datetime date year4638703
Ref: 189e4638703
Ref: library/datetime datetime date month4638807
Ref: 189f4638807
Ref: library/datetime datetime date day4638855
Ref: 18a04638855
Ref: library/datetime datetime date replace4641306
Ref: 18c04641306
Ref: library/datetime datetime date timetuple4641661
Ref: 18c14641661
Ref: library/datetime datetime date toordinal4642153
Ref: 18c24642153
Ref: library/datetime datetime date weekday4642383
Ref: 18c34642383
Ref: library/datetime datetime date isoweekday4642607
Ref: 18c44642607
Ref: library/datetime datetime date isocalendar4642852
Ref: 18bc4642852
Ref: library/datetime datetime date isoformat4643716
Ref: 18bb4643716
Ref: library/datetime datetime date __str__4644002
Ref: 18c54644002
Ref: library/datetime datetime date ctime4644108
Ref: 18c64644108
Ref: library/datetime datetime date strftime4644551
Ref: 5404644551
Ref: library/datetime datetime date __format__4644829
Ref: 18c94644829
Ref: date 对象-Footnote-14645319
Ref: date 对象-Footnote-24645613
Node: class date 用法示例4645802
Ref: library/datetime examples-of-usage-date4645873
Ref: 18ca4645873
Node: datetime 对象4647759
Ref: library/datetime datetime-datetime4647894
Ref: 18cb4647894
Ref: library/datetime datetime-objects4647894
Ref: 18cc4647894
Ref: library/datetime datetime datetime4648316
Ref: 1954648316
Ref: library/datetime datetime datetime today4649139
Ref: 18cd4649139
Ref: library/datetime datetime datetime now4649508
Ref: 10104649508
Ref: library/datetime datetime datetime utcnow4650181
Ref: 18ce4650181
Ref: library/datetime datetime datetime fromtimestamp4650945
Ref: 109b4650945
Ref: library/datetime datetime datetime utcfromtimestamp4652573
Ref: 18cf4652573
Ref: library/datetime datetime datetime fromordinal4654184
Ref: 18d04654184
Ref: library/datetime datetime datetime combine4654589
Ref: 5424654589
Ref: library/datetime datetime datetime fromisoformat4655336
Ref: 3874655336
Ref: library/datetime datetime datetime fromisocalendar4656829
Ref: 1c64656829
Ref: library/datetime datetime datetime strptime4657174
Ref: fbf4657174
Ref: library/datetime datetime datetime min4657740
Ref: 18d24657740
Ref: library/datetime datetime datetime max4657865
Ref: 18d34657865
Ref: library/datetime datetime datetime resolution4658012
Ref: 18d44658012
Ref: library/datetime datetime datetime year4658197
Ref: 18a64658197
Ref: library/datetime datetime datetime month4658305
Ref: 18a74658305
Ref: library/datetime datetime datetime day4658357
Ref: 18a84658357
Ref: library/datetime datetime datetime hour4658436
Ref: 18a94658436
Ref: library/datetime datetime datetime minute4658504
Ref: 18aa4658504
Ref: library/datetime datetime datetime second4658574
Ref: 18ab4658574
Ref: library/datetime datetime datetime microsecond4658644
Ref: 18ac4658644
Ref: library/datetime datetime datetime tzinfo4658724
Ref: 18ad4658724
Ref: library/datetime datetime datetime fold4658881
Ref: 4fc4658881
Ref: library/datetime datetime datetime date4663475
Ref: 18d54663475
Ref: library/datetime datetime datetime time4663584
Ref: 18d64663584
Ref: library/datetime datetime datetime timetz4663897
Ref: 18d74663897
Ref: library/datetime datetime datetime replace4664178
Ref: 18d84664178
Ref: library/datetime datetime datetime astimezone4664739
Ref: 1974664739
Ref: library/datetime datetime datetime utcoffset4667017
Ref: 18d94667017
Ref: library/datetime datetime datetime dst4667380
Ref: 18da4667380
Ref: library/datetime datetime datetime tzname4667731
Ref: 18dc4667731
Ref: library/datetime datetime datetime timetuple4667975
Ref: 18dd4667975
Ref: library/datetime datetime datetime utctimetuple4668858
Ref: 18de4668858
Ref: library/datetime datetime datetime toordinal4670015
Ref: 18df4670015
Ref: library/datetime datetime datetime timestamp4670146
Ref: 9ea4670146
Ref: library/datetime datetime datetime weekday4671525
Ref: 18e04671525
Ref: library/datetime datetime datetime isoweekday4671723
Ref: 18e14671723
Ref: library/datetime datetime datetime isocalendar4671956
Ref: 18d14671956
Ref: library/datetime datetime datetime isoformat4672117
Ref: 5414672117
Ref: library/datetime datetime datetime __str__4675044
Ref: 18e24675044
Ref: library/datetime datetime datetime ctime4675178
Ref: 18e34675178
Ref: library/datetime datetime datetime strftime4675759
Ref: 53f4675759
Ref: library/datetime datetime datetime __format__4676001
Ref: 18e44676001
Ref: datetime 对象-Footnote-14676505
Node: 用法示例 datetime4676593
Ref: library/datetime examples-of-usage-datetime4676666
Ref: 18e54676666
Node: time 对象4680969
Ref: library/datetime datetime-time4681106
Ref: 18e64681106
Ref: library/datetime time-objects4681106
Ref: 18e74681106
Ref: library/datetime datetime time4681307
Ref: 4fb4681307
Ref: library/datetime datetime time min4681964
Ref: 18e84681964
Ref: library/datetime datetime time max4682054
Ref: 18e94682054
Ref: library/datetime datetime time resolution4682152
Ref: 18ea4682152
Ref: library/datetime datetime time hour4682401
Ref: 18a14682401
Ref: library/datetime datetime time minute4682465
Ref: 18a24682465
Ref: library/datetime datetime time second4682531
Ref: 18a34682531
Ref: library/datetime datetime time microsecond4682597
Ref: 18a44682597
Ref: library/datetime datetime time tzinfo4682673
Ref: 18a54682673
Ref: library/datetime datetime time fold4682820
Ref: 18eb4682820
Ref: library/datetime datetime time fromisoformat4684688
Ref: 10a64684688
Ref: library/datetime datetime time replace4685551
Ref: 18ed4685551
Ref: library/datetime datetime time isoformat4686064
Ref: 18ec4686064
Ref: library/datetime datetime time __str__4688024
Ref: 18ef4688024
Ref: library/datetime datetime time strftime4688129
Ref: 18f04688129
Ref: library/datetime datetime time __format__4688354
Ref: 18f14688354
Ref: library/datetime datetime time utcoffset4688747
Ref: 18ee4688747
Ref: library/datetime datetime time dst4689105
Ref: 18f24689105
Ref: library/datetime datetime time tzname4689452
Ref: 18f34689452
Ref: time 对象-Footnote-14689779
Node: 用法示例 time4689822
Ref: library/datetime examples-of-usage-time4689887
Ref: 18f44689887
Node: tzinfo 对象4690744
Ref: library/datetime datetime-tzinfo4690881
Ref: 18f54690881
Ref: library/datetime tzinfo-objects4690881
Ref: 18f64690881
Ref: library/datetime datetime tzinfo4690934
Ref: 3884690934
Ref: library/datetime datetime tzinfo utcoffset4692438
Ref: 18f74692438
Ref: library/datetime datetime tzinfo dst4693647
Ref: 18f84693647
Ref: library/datetime datetime tzinfo tzname4696087
Ref: 18f94696087
Ref: library/datetime datetime tzinfo fromutc4698066
Ref: 18db4698066
Ref: tzinfo 对象-Footnote-14710355
Ref: tzinfo 对象-Footnote-24710413
Node: timezone 对象4710453
Ref: library/datetime datetime-timezone4710610
Ref: 18fb4710610
Ref: library/datetime timezone-objects4710610
Ref: 18fc4710610
Ref: library/datetime datetime timezone4710998
Ref: a094710998
Ref: library/datetime datetime timezone utcoffset4711553
Ref: 18fd4711553
Ref: library/datetime datetime timezone tzname4711882
Ref: 18fe4711882
Ref: library/datetime datetime timezone dst4712530
Ref: 18ff4712530
Ref: library/datetime datetime timezone fromutc4712594
Ref: 19004712594
Ref: library/datetime datetime timezone utc4712792
Ref: 18fa4712792
Node: strftime 和 strptime 的行为4712869
Ref: library/datetime strftime-and-strptime-behavior4713004
Ref: 19014713004
Ref: library/datetime strftime-strptime-behavior4713004
Ref: 18c84713004
Node: strftime 和 strptime Format Codes4715163
Ref: library/datetime strftime-and-strptime-format-codes4715286
Ref: 19024715286
Node: 技术细节4725377
Ref: library/datetime technical-detail4725500
Ref: 19034725500
Ref: 技术细节-Footnote-14730688
Node: calendar --- 日历相关函数4730802
Ref: library/calendar doc4730977
Ref: 19054730977
Ref: library/calendar calendar-general-calendar-related-functions4730977
Ref: 19064730977
Ref: library/calendar module-calendar4730977
Ref: 154730977
Ref: library/calendar calendar Calendar4732043
Ref: 19084732043
Ref: library/calendar calendar Calendar iterweekdays4732529
Ref: 19094732529
Ref: library/calendar calendar Calendar itermonthdates4732726
Ref: 4ae4732726
Ref: library/calendar calendar Calendar itermonthdays4733037
Ref: 190b4733037
Ref: library/calendar calendar Calendar itermonthdays24733410
Ref: 190c4733410
Ref: library/calendar calendar Calendar itermonthdays34733761
Ref: 4af4733761
Ref: library/calendar calendar Calendar itermonthdays44734106
Ref: 4b04734106
Ref: library/calendar calendar Calendar monthdatescalendar4734489
Ref: 190d4734489
Ref: library/calendar calendar Calendar monthdays2calendar4734667
Ref: 190e4734667
Ref: library/calendar calendar Calendar monthdayscalendar4734873
Ref: 190f4734873
Ref: library/calendar calendar Calendar yeardatescalendar4735028
Ref: 19104735028
Ref: library/calendar calendar Calendar yeardays2calendar4735395
Ref: 19114735395
Ref: library/calendar calendar Calendar yeardayscalendar4735700
Ref: 19124735700
Ref: library/calendar calendar TextCalendar4735959
Ref: 19134735959
Ref: library/calendar calendar TextCalendar formatmonth4736117
Ref: 19144736117
Ref: library/calendar calendar TextCalendar prmonth4736493
Ref: 19154736493
Ref: library/calendar calendar TextCalendar formatyear4736634
Ref: 19164736634
Ref: library/calendar calendar TextCalendar pryear4737080
Ref: 19174737080
Ref: library/calendar calendar HTMLCalendar4737219
Ref: 3784737219
Ref: library/calendar calendar HTMLCalendar formatmonth4737367
Ref: 19184737367
Ref: library/calendar calendar HTMLCalendar formatyear4737587
Ref: 19194737587
Ref: library/calendar calendar HTMLCalendar formatyearpage4737779
Ref: 191a4737779
Ref: library/calendar calendar HTMLCalendar cssclasses4738335
Ref: 191b4738335
Ref: library/calendar calendar HTMLCalendar cssclass_noday4738725
Ref: 191c4738725
Ref: library/calendar calendar HTMLCalendar cssclasses_weekday_head4738852
Ref: 191d4738852
Ref: library/calendar calendar HTMLCalendar cssclass_month_head4739048
Ref: 191e4739048
Ref: library/calendar calendar HTMLCalendar cssclass_month4739230
Ref: 191f4739230
Ref: library/calendar calendar HTMLCalendar cssclass_year4739420
Ref: 19204739420
Ref: library/calendar calendar HTMLCalendar cssclass_year_head4739604
Ref: 19214739604
Ref: library/calendar calendar LocaleTextCalendar4740458
Ref: 19224740458
Ref: library/calendar calendar LocaleHTMLCalendar4740821
Ref: 19234740821
Ref: library/calendar calendar setfirstweekday4741489
Ref: 19074741489
Ref: library/calendar calendar firstweekday4741912
Ref: 190a4741912
Ref: library/calendar calendar isleap4742011
Ref: 19244742011
Ref: library/calendar calendar leapdays4742143
Ref: 19254742143
Ref: library/calendar calendar weekday4742369
Ref: 19264742369
Ref: library/calendar calendar weekheader4742583
Ref: 19274742583
Ref: library/calendar calendar monthrange4742719
Ref: 19284742719
Ref: library/calendar calendar monthcalendar4742862
Ref: 19294742862
Ref: library/calendar calendar prmonth4743118
Ref: 192a4743118
Ref: library/calendar calendar month4743246
Ref: 192b4743246
Ref: library/calendar calendar prcal4743422
Ref: 192c4743422
Ref: library/calendar calendar calendar4743543
Ref: 192d4743543
Ref: library/calendar calendar timegm4743731
Ref: 192e4743731
Ref: library/calendar calendar day_name4744157
Ref: 192f4744157
Ref: library/calendar calendar day_abbr4744246
Ref: 19304744246
Ref: library/calendar calendar month_name4744341
Ref: 19314744341
Ref: library/calendar calendar month_abbr4744559
Ref: 19324744559
Ref: calendar --- 日历相关函数-Footnote-14745004
Node: collections --- 容器数据类型4745071
Ref: library/collections doc4745244
Ref: 19334745244
Ref: library/collections collections-container-datatypes4745244
Ref: 19344745244
Ref: library/collections module-collections4745244
Ref: 1e4745244
Ref: collections --- 容器数据类型-Footnote-14747390
Node: ChainMap 对象4747470
Ref: library/collections chainmap-objects4747579
Ref: 19384747579
Ref: library/collections collections ChainMap4747960
Ref: 4b14747960
Ref: library/collections collections ChainMap maps4748886
Ref: 19394748886
Ref: library/collections collections ChainMap new_child4749138
Ref: 8324749138
Ref: library/collections collections ChainMap parents4749720
Ref: 193a4749720
Ref: ChainMap 对象-Footnote-14751366
Ref: ChainMap 对象-Footnote-24751461
Ref: ChainMap 对象-Footnote-34751508
Ref: ChainMap 对象-Footnote-44751587
Ref: ChainMap 对象-Footnote-54751640
Node: ChainMap 例子和方法4751693
Ref: library/collections chainmap-examples-and-recipes4751769
Ref: 193b4751769
Node: Counter 对象4754655
Ref: library/collections counter-objects4754785
Ref: 193c4754785
Ref: library/collections collections Counter4755465
Ref: 9e24755465
Ref: library/collections collections Counter elements4757302
Ref: ca24757302
Ref: library/collections collections Counter most_common4757712
Ref: ca14757712
Ref: library/collections collections Counter subtract4758177
Ref: b624758177
Ref: library/collections collections Counter fromkeys4758788
Ref: 193d4758788
Ref: library/collections collections Counter update4758895
Ref: 193e4758895
Ref: Counter 对象-Footnote-14762606
Ref: Counter 对象-Footnote-24762685
Ref: Counter 对象-Footnote-34762732
Node: deque 对象4762825
Ref: library/collections deque-objects4762958
Ref: 193f4762958
Ref: library/collections collections deque4763007
Ref: 5394763007
Ref: library/collections collections deque append4764233
Ref: 19404764233
Ref: library/collections collections deque appendleft4764297
Ref: 19414764297
Ref: library/collections collections deque clear4764365
Ref: 19424764365
Ref: library/collections collections deque copy4764442
Ref: 6b44764442
Ref: library/collections collections deque count4764533
Ref: b644764533
Ref: library/collections collections deque extend4764647
Ref: 19434764647
Ref: library/collections collections deque extendleft4764759
Ref: 19444764759
Ref: library/collections collections deque index4764972
Ref: 6b24764972
Ref: library/collections collections deque insert4765246
Ref: 6b34765246
Ref: library/collections collections deque pop4765482
Ref: 19454765482
Ref: library/collections collections deque popleft4765662
Ref: 19464765662
Ref: library/collections collections deque remove4765840
Ref: 19474765840
Ref: library/collections collections deque reverse4765984
Ref: b654765984
Ref: library/collections collections deque rotate4766098
Ref: 19484766098
Ref: library/collections collections deque maxlen4766453
Ref: ca34766453
Node: deque 用法4769094
Ref: library/collections deque-recipes4769155
Ref: 19494769155
Ref: deque 用法-Footnote-14771443
Node: defaultdict 对象4771504
Ref: library/collections defaultdict-objects4771661
Ref: 194a4771661
Ref: library/collections collections defaultdict4771722
Ref: b424771722
Ref: library/collections collections defaultdict __missing__4772454
Ref: 194c4772454
Ref: library/collections collections defaultdict default_factory4773625
Ref: 194b4773625
Node: defaultdict 例子4773939
Ref: library/collections defaultdict-examples4774012
Ref: 194d4774012
Node: namedtuple 命名元组的工厂函数4776438
Ref: library/collections namedtuple-factory-function-for-tuples-with-named-fields4776601
Ref: 194e4776601
Ref: library/collections collections namedtuple4776897
Ref: 1b74776897
Ref: library/collections collections somenamedtuple _make4780427
Ref: 194f4780427
Ref: library/collections collections somenamedtuple _asdict4780642
Ref: 1b84780642
Ref: library/collections collections somenamedtuple _replace4781290
Ref: 19504781290
Ref: library/collections collections somenamedtuple _fields4781673
Ref: 19514781673
Ref: library/collections collections somenamedtuple _field_defaults4782138
Ref: 19524782138
Node: OrderedDict 对象4784755
Ref: library/collections ordereddict-objects4784915
Ref: 19534784915
Ref: library/collections collections OrderedDict4786165
Ref: 1ba4786165
Ref: library/collections collections OrderedDict popitem4786351
Ref: c8c4786351
Ref: library/collections collections OrderedDict move_to_end4786648
Ref: b634786648
Ref: OrderedDict 对象-Footnote-14788080
Ref: OrderedDict 对象-Footnote-24788165
Node: OrderedDict 例子和用法4788214
Ref: library/collections ordereddict-examples-and-recipes4788296
Ref: 19564788296
Node: UserDict 对象4789539
Ref: library/collections userdict-objects4789676
Ref: 19574789676
Ref: library/collections collections UserDict4789984
Ref: 19354789984
Ref: library/collections collections UserDict data4790460
Ref: 19584790460
Node: UserList 对象4790569
Ref: library/collections userlist-objects4790705
Ref: 19594790705
Ref: library/collections collections UserList4791183
Ref: 19364791183
Ref: library/collections collections UserList data4791669
Ref: 195a4791669
Node: UserString 对象4792246
Ref: library/collections userstring-objects4792358
Ref: 195b4792358
Ref: library/collections collections UserString4792676
Ref: 6b64792676
Ref: library/collections collections UserString data4793144
Ref: 195c4793144
Node: collections abc --- 容器的抽象基类4793432
Ref: library/collections abc doc4793599
Ref: 195d4793599
Ref: library/collections abc collections-abc-abstract-base-classes-for-containers4793599
Ref: 195e4793599
Ref: library/collections abc module-collections abc4793599
Ref: 1f4793599
Ref: collections abc --- 容器的抽象基类-Footnote-14794148
Node: 容器抽象基类4794224
Ref: library/collections abc collections-abstract-base-classes4794320
Ref: 19374794320
Ref: library/collections abc id14794320
Ref: 195f4794320
Ref: library/collections abc collections abc Container4803264
Ref: 19604803264
Ref: library/collections abc collections abc Hashable4803368
Ref: 19614803368
Ref: library/collections abc collections abc Sized4803467
Ref: 19644803467
Ref: library/collections abc collections abc Callable4803562
Ref: 19654803562
Ref: library/collections abc collections abc Iterable4803662
Ref: 19624803662
Ref: library/collections abc collections abc Collection4804142
Ref: 5354804142
Ref: library/collections abc collections abc Iterator4804260
Ref: 19634804260
Ref: library/collections abc collections abc Reversible4804434
Ref: 5364804434
Ref: library/collections abc collections abc Generator4804578
Ref: 6be4804578
Ref: library/collections abc collections abc Sequence4804869
Ref: 16404804869
Ref: library/collections abc collections abc MutableSequence4804903
Ref: 6b54804903
Ref: library/collections abc collections abc ByteString4804944
Ref: 19664804944
Ref: library/collections abc collections abc Set4805621
Ref: 16ea4805621
Ref: library/collections abc collections abc MutableSet4805650
Ref: 19674805650
Ref: library/collections abc collections abc Mapping4805736
Ref: 19544805736
Ref: library/collections abc collections abc MutableMapping4805769
Ref: 9f74805769
Ref: library/collections abc collections abc MappingView4805881
Ref: 19684805881
Ref: library/collections abc collections abc ItemsView4805918
Ref: 19694805918
Ref: library/collections abc collections abc KeysView4805953
Ref: 196a4805953
Ref: library/collections abc collections abc ValuesView4805987
Ref: 196b4805987
Ref: library/collections abc collections abc Awaitable4806099
Ref: 6bf4806099
Ref: library/collections abc collections abc Coroutine4806873
Ref: 6c04806873
Ref: library/collections abc collections abc AsyncIterable4807767
Ref: 6c24807767
Ref: library/collections abc collections abc AsyncIterator4807946
Ref: 6c14807946
Ref: library/collections abc collections abc AsyncGenerator4808145
Ref: 5384808145
Ref: 容器抽象基类-Footnote-14811215
Ref: 容器抽象基类-Footnote-24811264
Ref: 容器抽象基类-Footnote-34811313
Ref: 容器抽象基类-Footnote-44811362
Ref: 容器抽象基类-Footnote-54811415
Node: heapq --- 堆队列算法4811464
Ref: library/heapq doc4811632
Ref: 196c4811632
Ref: library/heapq heapq-heap-queue-algorithm4811632
Ref: 196d4811632
Ref: library/heapq module-heapq4811632
Ref: 8e4811632
Ref: library/heapq heapq heappush4813080
Ref: 196f4813080
Ref: library/heapq heapq heappop4813189
Ref: 19704813189
Ref: library/heapq heapq heappushpop4813432
Ref: 19714813432
Ref: library/heapq heapq heapify4813680
Ref: 196e4813680
Ref: library/heapq heapq heapreplace4813772
Ref: 19724813772
Ref: library/heapq heapq merge4814503
Ref: 6e84814503
Ref: library/heapq heapq nlargest4815568
Ref: 19734815568
Ref: library/heapq heapq nsmallest4815945
Ref: 19744815945
Ref: heapq --- 堆队列算法-Footnote-14816738
Node: 基本示例4816802
Ref: library/heapq basic-examples4816909
Ref: 19754816909
Ref: 基本示例-Footnote-14817823
Node: 优先队列实现说明4817870
Ref: library/heapq priority-queue-implementation-notes4817992
Ref: 19764817992
Ref: 优先队列实现说明-Footnote-14820776
Node: 理论4820829
Ref: library/heapq theory4820930
Ref: 19774820930
Ref: 理论-Footnote-14824971
Node: bisect --- 数组二分查找算法4825548
Ref: library/bisect doc4825706
Ref: 19784825706
Ref: library/bisect bisect-array-bisection-algorithm4825706
Ref: 19794825706
Ref: library/bisect module-bisect4825706
Ref: 124825706
Ref: library/bisect bisect bisect_left4826312
Ref: 197a4826312
Ref: library/bisect bisect bisect_right4826957
Ref: 197b4826957
Ref: library/bisect bisect bisect4827013
Ref: 197c4827013
Ref: library/bisect bisect insort_left4827381
Ref: 197d4827381
Ref: library/bisect bisect insort_right4827674
Ref: 197e4827674
Ref: library/bisect bisect insort4827730
Ref: 197f4827730
Ref: bisect --- 数组二分查找算法-Footnote-14828260
Ref: bisect --- 数组二分查找算法-Footnote-24828325
Node: 搜索有序列表4828395
Ref: library/bisect searching-sorted-lists4828506
Ref: 19804828506
Node: 其他示例4829683
Ref: library/bisect other-examples4829794
Ref: 19814829794
Ref: library/bisect bisect-example4829833
Ref: 19824829833
Node: array --- 高效的数值数组4831122
Ref: library/array doc4831276
Ref: 19834831276
Ref: library/array array-efficient-arrays-of-numeric-values4831276
Ref: 19844831276
Ref: library/array module-array4831276
Ref: 74831276
Ref: library/array array array4835681
Ref: 4594835681
Ref: library/array array typecodes4836415
Ref: 19894836415
Ref: library/array array array typecode4836878
Ref: 198a4836878
Ref: library/array array array itemsize4836952
Ref: 198b4836952
Ref: library/array array array append4837038
Ref: 198c4837038
Ref: library/array array array buffer_info4837125
Ref: 198d4837125
Ref: library/array array array byteswap4838002
Ref: 198e4838002
Ref: library/array array array count4838286
Ref: 198f4838286
Ref: library/array array array extend4838363
Ref: 19884838363
Ref: library/array array array frombytes4838731
Ref: 19864838731
Ref: library/array array array fromfile4839045
Ref: 19904839045
Ref: library/array array array fromlist4839298
Ref: 19854839298
Ref: library/array array array fromstring4839488
Ref: 19914839488
Ref: library/array array array fromunicode4839642
Ref: 19874839642
Ref: library/array array array index4839963
Ref: f1c4839963
Ref: library/array array array insert4840074
Ref: 19924840074
Ref: library/array array array pop4840230
Ref: 19934840230
Ref: library/array array array remove4840407
Ref: 19944840407
Ref: library/array array array reverse4840484
Ref: 19954840484
Ref: library/array array array tobytes4840554
Ref: 19964840554
Ref: library/array array array tofile4840865
Ref: 19974840865
Ref: library/array array array tolist4840975
Ref: 19994840975
Ref: library/array array array tostring4841062
Ref: 19984841062
Ref: library/array array array tounicode4841212
Ref: 199a4841212
Ref: array --- 高效的数值数组-Footnote-14842508
Node: weakref --- 弱引用4842544
Ref: library/weakref doc4842712
Ref: 199b4842712
Ref: library/weakref module-weakref4842712
Ref: 1294842712
Ref: library/weakref weakref-weak-references4842712
Ref: 199c4842712
Ref: library/weakref weakref ref4845996
Ref: 9184845996
Ref: library/weakref weakref ref __callback__4847558
Ref: 9194847558
Ref: library/weakref weakref proxy4847847
Ref: 2514847847
Ref: library/weakref weakref getweakrefcount4848618
Ref: 19a04848618
Ref: library/weakref weakref getweakrefs4848726
Ref: 19a14848726
Ref: library/weakref weakref WeakKeyDictionary4848845
Ref: 199d4848845
Ref: library/weakref weakref WeakKeyDictionary keyrefs4849529
Ref: 19a24849529
Ref: library/weakref weakref WeakValueDictionary4849629
Ref: 199e4849629
Ref: library/weakref weakref WeakValueDictionary valuerefs4849945
Ref: 19a34849945
Ref: library/weakref weakref WeakSet4850049
Ref: cc04850049
Ref: library/weakref weakref WeakMethod4850207
Ref: 9174850207
Ref: library/weakref weakref finalize4851086
Ref: 29e4851086
Ref: library/weakref weakref finalize __call__4852277
Ref: 19a44852277
Ref: library/weakref weakref finalize detach4852507
Ref: 19a54852507
Ref: library/weakref weakref finalize peek4852726
Ref: 19a64852726
Ref: library/weakref weakref finalize alive4852906
Ref: 19a74852906
Ref: library/weakref weakref finalize atexit4853020
Ref: 19a84853020
Ref: library/weakref weakref ReferenceType4853612
Ref: 19a94853612
Ref: library/weakref weakref ProxyType4853687
Ref: 19aa4853687
Ref: library/weakref weakref CallableProxyType4853770
Ref: 19ab4853770
Ref: library/weakref weakref ProxyTypes4853858
Ref: 19ac4853858
Ref: weakref --- 弱引用-Footnote-14854396
Ref: weakref --- 弱引用-Footnote-24854462
Node: 弱引用对象4854511
Ref: library/weakref weak-reference-objects4854602
Ref: 19ad4854602
Ref: library/weakref weakref-objects4854602
Ref: 19ae4854602
Node: 示例<2>4856879
Ref: library/weakref example4856994
Ref: 19af4856994
Ref: library/weakref weakref-example4856994
Ref: 19b04856994
Node: 终结器对象4857519
Ref: library/weakref finalize-examples4857652
Ref: 19b14857652
Ref: library/weakref finalizer-objects4857652
Ref: 19b24857652
Node: 比较终结器与 __del__ 方法4859431
Ref: library/weakref comparing-finalizers-with-del-methods4859546
Ref: 19b34859546
Node: types --- 动态类型创建和内置类型名称4862215
Ref: library/types doc4862403
Ref: 19b44862403
Ref: library/types module-types4862403
Ref: 1194862403
Ref: library/types types-dynamic-type-creation-and-names-for-built-in-types4862403
Ref: 19b54862403
Ref: types --- 动态类型创建和内置类型名称-Footnote-14863128
Node: 动态类型创建4863192
Ref: library/types dynamic-type-creation4863326
Ref: 19b64863326
Ref: library/types types new_class4863375
Ref: abf4863375
Ref: library/types types prepare_class4863955
Ref: ac04863955
Ref: library/types types resolve_bases4864932
Ref: 40e4864932
Ref: 动态类型创建-Footnote-14865584
Ref: 动态类型创建-Footnote-24865633
Ref: 动态类型创建-Footnote-34865682
Node: 标准解释器类型4865731
Ref: library/types standard-interpreter-types4865898
Ref: 19b74865898
Ref: library/types types FunctionType4866414
Ref: 19b84866414
Ref: library/types types LambdaType4866445
Ref: 19b94866445
Ref: library/types types GeneratorType4866770
Ref: 19ba4866770
Ref: library/types types CoroutineType4866886
Ref: 7864866886
Ref: library/types types AsyncGeneratorType4867037
Ref: 19bb4867037
Ref: library/types types CodeType4867208
Ref: 1994867208
Ref: library/types types CodeType replace4867750
Ref: 19bc4867750
Ref: library/types types CellType4867894
Ref: 143c4867894
Ref: library/types types MethodType4868031
Ref: 19bd4868031
Ref: library/types types BuiltinFunctionType4868110
Ref: 19be4868110
Ref: library/types types BuiltinMethodType4868148
Ref: 19bf4868148
Ref: library/types types WrapperDescriptorType4868362
Ref: 40a4868362
Ref: library/types types MethodWrapperType4868564
Ref: 40b4868564
Ref: library/types types MethodDescriptorType4868750
Ref: 40c4868750
Ref: library/types types ClassMethodDescriptorType4868894
Ref: 40d4868894
Ref: library/types types ModuleType4869073
Ref: 6fa4869073
Ref: library/types types ModuleType __doc__4869422
Ref: 19c04869422
Ref: library/types types ModuleType __loader__4869519
Ref: 19c14869519
Ref: library/types types ModuleType __name__4870164
Ref: 19c34870164
Ref: library/types types ModuleType __package__4870302
Ref: 19c54870302
Ref: library/types types ModuleType __spec__4871204
Ref: 19c74871204
Ref: library/types types TracebackType4871400
Ref: 33e4871400
Ref: library/types types FrameType4871680
Ref: 19c84871680
Ref: library/types types GetSetDescriptorType4871905
Ref: 19c94871905
Ref: library/types types MemberDescriptorType4872250
Ref: 19ca4872250
Ref: library/types types MappingProxyType4872744
Ref: abe4872744
Ref: library/types types MappingProxyType copy4873516
Ref: 19cb4873516
Ref: library/types types MappingProxyType get4873587
Ref: 19cc4873587
Ref: library/types types MappingProxyType items4873853
Ref: 19cd4873853
Ref: library/types types MappingProxyType keys4873970
Ref: 19ce4873970
Ref: library/types types MappingProxyType values4874062
Ref: 19cf4874062
Node: 附加工具类和函数4874156
Ref: library/types additional-utility-classes-and-functions4874323
Ref: 19d04874323
Ref: library/types types SimpleNamespace4874382
Ref: 9b44874382
Ref: library/types types DynamicClassAttribute4875616
Ref: 8fb4875616
Node: 协程工具函数4876207
Ref: library/types coroutine-utility-functions4876344
Ref: 19d14876344
Ref: library/types types coroutine4876393
Ref: 7854876393
Node: copy --- 浅层 shallow 和深层 deep 复制操作4877164
Ref: library/copy doc4877360
Ref: 19d24877360
Ref: library/copy copy-shallow-and-deep-copy-operations4877360
Ref: 19d34877360
Ref: library/copy module-copy4877360
Ref: 264877360
Ref: library/copy copy copy4877934
Ref: 3d34877934
Ref: library/copy copy deepcopy4877997
Ref: 3d44877997
Ref: library/copy copy Error4878072
Ref: 19d44878072
Ref: library/copy shallow-vs-deep-copy4878135
Ref: 12394878135
Ref: copy --- 浅层 shallow 和深层 deep 复制操作-Footnote-14880593
Node: pprint --- 数据美化输出4880656
Ref: library/pprint doc4880836
Ref: 19d54880836
Ref: library/pprint module-pprint4880836
Ref: d34880836
Ref: library/pprint pprint-data-pretty-printer4880836
Ref: 19d64880836
Ref: library/pprint pprint PrettyPrinter4881756
Ref: 89e4881756
Ref: library/pprint pprint pformat4884246
Ref: 89f4884246
Ref: library/pprint pprint pp4884669
Ref: 2134884669
Ref: library/pprint pprint pprint4885030
Ref: 2144885030
Ref: library/pprint pprint isreadable4886078
Ref: 19d74886078
Ref: library/pprint pprint isrecursive4886370
Ref: 19d84886370
Ref: library/pprint pprint saferepr4886502
Ref: 19d94886502
Ref: pprint --- 数据美化输出-Footnote-14887048
Node: PrettyPrinter 对象4887113
Ref: library/pprint id14887217
Ref: 19da4887217
Ref: library/pprint prettyprinter-objects4887217
Ref: 19db4887217
Ref: library/pprint pprint PrettyPrinter pformat4887334
Ref: 19dc4887334
Ref: library/pprint pprint PrettyPrinter pprint4887501
Ref: 19dd4887501
Ref: library/pprint pprint PrettyPrinter isreadable4887814
Ref: 19de4887814
Ref: library/pprint pprint PrettyPrinter isrecursive4888189
Ref: 19df4888189
Ref: library/pprint pprint PrettyPrinter format4888447
Ref: 19e04888447
Node: 示例<3>4889408
Ref: library/pprint example4889512
Ref: 19e14889512
Ref: library/pprint pprint-example4889512
Ref: 19e24889512
Ref: 示例<3>-Footnote-14896786
Node: reprlib --- 另一种 repr 实现4896811
Ref: library/reprlib doc4896967
Ref: 19e34896967
Ref: library/reprlib module-reprlib4896967
Ref: e04896967
Ref: library/reprlib reprlib-alternate-repr-implementation4896967
Ref: 19e44896967
Ref: library/reprlib reprlib Repr4897418
Ref: 19e54897418
Ref: library/reprlib reprlib aRepr4897637
Ref: 19e64897637
Ref: library/reprlib reprlib repr4897886
Ref: 19e74897886
Ref: library/reprlib reprlib recursive_repr4898271
Ref: b784898271
Ref: reprlib --- 另一种 repr 实现-Footnote-14899048
Node: Repr 对象4899114
Ref: library/reprlib id14899225
Ref: 19e94899225
Ref: library/reprlib repr-objects4899225
Ref: 19ea4899225
Ref: library/reprlib reprlib Repr maxlevel4899440
Ref: 19eb4899440
Ref: library/reprlib reprlib Repr maxdict4899537
Ref: 19ec4899537
Ref: library/reprlib reprlib Repr maxlist4899562
Ref: 19ed4899562
Ref: library/reprlib reprlib Repr maxtuple4899587
Ref: 19ee4899587
Ref: library/reprlib reprlib Repr maxset4899613
Ref: 19ef4899613
Ref: library/reprlib reprlib Repr maxfrozenset4899637
Ref: 19f04899637
Ref: library/reprlib reprlib Repr maxdeque4899667
Ref: 19f14899667
Ref: library/reprlib reprlib Repr maxarray4899693
Ref: 19f24899693
Ref: library/reprlib reprlib Repr maxlong4899908
Ref: 19f34899908
Ref: library/reprlib reprlib Repr maxstring4900033
Ref: 19f44900033
Ref: library/reprlib reprlib Repr maxother4900298
Ref: 19f54900298
Ref: library/reprlib reprlib Repr repr4900545
Ref: 19e84900545
Ref: library/reprlib reprlib Repr repr14900661
Ref: 19f64900661
Node: 子类化 Repr 对象4901433
Ref: library/reprlib subclassing-repr-objects4901544
Ref: 19f74901544
Ref: library/reprlib subclassing-reprs4901544
Ref: 19f84901544
Node: enum --- 对枚举的支持4902178
Ref: library/enum doc4902296
Ref: 19f94902296
Ref: library/enum enum-support-for-enumerations4902296
Ref: 19fa4902296
Ref: library/enum module-enum4902296
Ref: 7b4902296
Ref: enum --- 对枚举的支持-Footnote-14903408
Node: 模块内容<2>4903471
Ref: library/enum module-contents4903576
Ref: 19fb4903576
Ref: library/enum enum Enum4903887
Ref: 38f4903887
Ref: library/enum enum IntEnum4904043
Ref: 5964904043
Ref: library/enum enum IntFlag4904144
Ref: 176b4904144
Ref: library/enum enum Flag4904380
Ref: 54e4904380
Ref: library/enum enum auto4904658
Ref: 54f4904658
Node: 创建一个 Enum4904833
Ref: library/enum creating-an-enum4904992
Ref: 19fe4904992
Node: 对枚举成员及其属性的程序化访问4907341
Ref: library/enum programmatic-access-to-enumeration-members-and-their-attributes4907509
Ref: 1a004907509
Node: 复制枚举成员和值4908230
Ref: library/enum duplicating-enum-members-and-values4908405
Ref: 1a014908405
Node: 确保唯一的枚举值4909391
Ref: library/enum ensuring-unique-enumeration-values4909545
Ref: 1a024909545
Ref: library/enum enum unique4909797
Ref: 19fc4909797
Node: 使用自动设定的值4910352
Ref: library/enum using-automatic-values4910488
Ref: 1a034910488
Node: 迭代4911683
Ref: library/enum iteration4911810
Ref: 1a044911810
Node: 比较运算<3>4912585
Ref: library/enum comparisons4912718
Ref: 1a054912718
Node: 允许的枚举成员和属性4913584
Ref: library/enum allowed-members-and-attributes-of-enumerations4913735
Ref: 1a074913735
Node: 受限的 Enum 子类化4915409
Ref: library/enum restricted-enum-subclassing4915551
Ref: 1a094915551
Node: 封存4916623
Ref: library/enum pickling4916748
Ref: 1a0b4916748
Node: 功能性 API4917329
Ref: library/enum functional-api4917445
Ref: 19fd4917445
Node: 派生的枚举4920500
Ref: library/enum derived-enumerations4920643
Ref: 1a0d4920643
Node: IntEnum4920751
Ref: library/enum intenum4920826
Ref: 1a064920826
Node: IntFlag4921927
Ref: library/enum intflag4922015
Ref: 1a0e4922015
Node: Flag4923539
Ref: library/enum flag4923632
Ref: 1a0f4923632
Node: 其他事项4925636
Ref: library/enum others4925713
Ref: 1a104925713
Node: 何时使用 __new__ 与 __init__4927461
Ref: library/enum when-to-use-new-vs-init4927606
Ref: 1a114927606
Node: 有趣的示例4928684
Ref: library/enum interesting-examples4928841
Ref: 1a124928841
Node: 省略值4929253
Ref: library/enum omitting-values4929334
Ref: 1a134929334
Node: 使用 auto4930333
Ref: library/enum using-auto4930412
Ref: 1a144930412
Node: 使用 object4930667
Ref: library/enum using-object4930779
Ref: 1a154930779
Node: 使用描述性字符串4931046
Ref: library/enum using-a-descriptive-string4931173
Ref: 1a164931173
Node: 使用自定义的 __new__4931480
Ref: library/enum using-a-custom-new4931585
Ref: 1a174931585
Node: OrderedEnum4933274
Ref: library/enum orderedenum4933381
Ref: 1a0a4933381
Node: DuplicateFreeEnum4934549
Ref: library/enum duplicatefreeenum4934653
Ref: 1a184934653
Node: Planet4935689
Ref: library/enum planet4935792
Ref: 1a084935792
Node: TimePeriod4936843
Ref: library/enum timeperiod4936920
Ref: 1a194936920
Node: 各种枚举有何区别？4937536
Ref: library/enum how-are-enums-different4937651
Ref: 19ff4937651
Node: 枚举类4937899
Ref: library/enum enum-classes4938008
Ref: 1a1a4938008
Node: 枚举成员（即实例）4938518
Ref: library/enum enum-members-aka-instances4938648
Ref: 1a1b4938648
Node: 细节要点4939008
Ref: library/enum finer-points4939120
Ref: 1a1c4939120
Node: 支持的 __dunder__ 名称4939346
Ref: library/enum supported-dunder-names4939456
Ref: 1a1d4939456
Node: 支持的 _sunder_ 名称4939866
Ref: library/enum supported-sunder-names4940002
Ref: 1a1e4940002
Node: Enum 成员类型4941405
Ref: library/enum enum-member-type4941543
Ref: 1a1f4941543
Node: Enum 类和成员的布尔值4942243
Ref: library/enum boolean-value-of-enum-classes-and-members4942380
Ref: 1a204942380
Node: 带有方法的 Enum 类4942913
Ref: library/enum enum-classes-with-methods4943054
Ref: 1a214943054
Node: 组合 Flag 的成员4943618
Ref: library/enum combining-members-of-flag4943721
Ref: 1a224943721
Node: 数字和数学模块4944316
Ref: library/numeric doc4944441
Ref: 1a234944441
Ref: library/numeric numeric4944441
Ref: 1a244944441
Ref: library/numeric numeric-and-mathematical-modules4944441
Ref: 1a254944441
Node: numbers --- 数字的抽象基类4945313
Ref: library/numbers doc4945434
Ref: 1a264945434
Ref: library/numbers module-numbers4945434
Ref: c24945434
Ref: library/numbers numbers-numeric-abstract-base-classes4945434
Ref: 1a274945434
Ref: library/numbers numbers Number4945810
Ref: 14334945810
Ref: numbers --- 数字的抽象基类-Footnote-14946085
Ref: numbers --- 数字的抽象基类-Footnote-24946151
Node: 数字的层次4946200
Ref: library/numbers the-numeric-tower4946315
Ref: 1a284946315
Ref: library/numbers numbers Complex4946359
Ref: 14364946359
Ref: library/numbers numbers Complex real4946789
Ref: 1a294946789
Ref: library/numbers numbers Complex imag4946869
Ref: 1a2a4946869
Ref: library/numbers numbers Complex conjugate4946949
Ref: 1a2b4946949
Ref: library/numbers numbers Real4947084
Ref: 14354947084
Ref: library/numbers numbers Rational4947629
Ref: c604947629
Ref: library/numbers numbers Rational numerator4947874
Ref: 1a2c4947874
Ref: library/numbers numbers Rational denominator4947926
Ref: 1a2d4947926
Ref: library/numbers numbers Integral4947980
Ref: 14344947980
Node: 类型接口注释。4948318
Ref: library/numbers notes-for-type-implementors4948433
Ref: 1a2e4948433
Node: 加入更多数字的ABC4949218
Ref: library/numbers adding-more-numeric-abcs4949327
Ref: 1a2f4949327
Node: 实现算术运算4949634
Ref: library/numbers id14949743
Ref: 1a304949743
Ref: library/numbers implementing-the-arithmetic-operations4949743
Ref: 14324949743
Node: math --- 数学函数4954321
Ref: library/math doc4954488
Ref: 1a314954488
Ref: library/math math-mathematical-functions4954488
Ref: 1a324954488
Ref: library/math module-math4954488
Ref: b24954488
Node: 数论与表示函数4955358
Ref: library/math number-theoretic-and-representation-functions4955470
Ref: 1a334955470
Ref: library/math math ceil4955524
Ref: d354955524
Ref: library/math math comb4955749
Ref: 1e84955749
Ref: library/math math copysign4956267
Ref: d454956267
Ref: library/math math fabs4956457
Ref: 1a344956457
Ref: library/math math factorial4956517
Ref: 1eb4956517
Ref: library/math math floor4956676
Ref: d344956676
Ref: library/math math fmod4956887
Ref: 15484956887
Ref: library/math math frexp4957750
Ref: 1a354957750
Ref: library/math math fsum4958099
Ref: d464958099
Ref: library/math math gcd4958788
Ref: 71f4958788
Ref: library/math math isclose4959050
Ref: 68f4959050
Ref: library/math math isfinite4960205
Ref: b6f4960205
Ref: library/math math isinf4960420
Ref: d434960420
Ref: library/math math isnan4960542
Ref: d444960542
Ref: library/math math isqrt4960668
Ref: 1e94960668
Ref: library/math math ldexp4961141
Ref: 1a364961141
Ref: library/math math modf4961265
Ref: 1a374961265
Ref: library/math math perm4961393
Ref: 1e74961393
Ref: library/math math prod4961873
Ref: 1e54961873
Ref: library/math math remainder4962171
Ref: 3b34962171
Ref: library/math math trunc4963105
Ref: d364963105
Ref: 数论与表示函数-Footnote-14963902
Ref: 数论与表示函数-Footnote-24963955
Node: 幂函数与对数函数4964004
Ref: library/math power-and-logarithmic-functions4964137
Ref: 1a384964137
Ref: library/math math exp4964196
Ref: cb14964196
Ref: library/math math expm14964380
Ref: b704964380
Ref: library/math math log4964954
Ref: e194964954
Ref: library/math math log1p4965171
Ref: d4a4965171
Ref: library/math math log24965320
Ref: a284965320
Ref: library/math math log104965593
Ref: 1a394965593
Ref: library/math math pow4965701
Ref: 1a3a4965701
Ref: library/math math sqrt4966340
Ref: 1ea4966340
Ref: 幂函数与对数函数-Footnote-14966436
Node: 三角函数4966495
Ref: library/math trigonometric-functions4966619
Ref: 1a3b4966619
Ref: library/math math acos4966658
Ref: 1a3c4966658
Ref: library/math math asin4966739
Ref: 1a3d4966739
Ref: library/math math atan4966820
Ref: 1a3e4966820
Ref: library/math math atan24966901
Ref: 1a3f4966901
Ref: library/math math cos4967358
Ref: e184967358
Ref: library/math math dist4967423
Ref: 1e34967423
Ref: library/math math hypot4967736
Ref: 1e44967736
Ref: library/math math sin4968158
Ref: e174968158
Ref: library/math math tan4968223
Ref: 1a404968223
Node: 角度转换4968288
Ref: library/math angular-conversion4968400
Ref: 1a414968400
Ref: library/math math degrees4968439
Ref: 1a424968439
Ref: library/math math radians4968517
Ref: 1a434968517
Node: 双曲函数4968595
Ref: library/math hyperbolic-functions4968707
Ref: 1a444968707
Ref: library/math math acosh4968824
Ref: d474968824
Ref: library/math math asinh4968894
Ref: d484968894
Ref: library/math math atanh4968964
Ref: d494968964
Ref: library/math math cosh4969034
Ref: 1a454969034
Ref: library/math math sinh4969100
Ref: 1a464969100
Ref: library/math math tanh4969166
Ref: 1a474969166
Ref: 双曲函数-Footnote-14969268
Node: 特殊函数4969326
Ref: library/math special-functions4969435
Ref: 1a484969435
Ref: library/math math erf4969474
Ref: 45a4969474
Ref: library/math math erfc4969840
Ref: 45b4969840
Ref: library/math math gamma4970077
Ref: b714970077
Ref: library/math math lgamma4970176
Ref: b724970176
Ref: 特殊函数-Footnote-14970324
Ref: 特殊函数-Footnote-24970377
Ref: 特殊函数-Footnote-34970469
Ref: 特殊函数-Footnote-44970522
Ref: 特殊函数-Footnote-54970581
Node: 常量<2>4970634
Ref: library/math constants4970722
Ref: 1a494970722
Ref: library/math math pi4970751
Ref: 1a4a4970751
Ref: library/math math e4970837
Ref: 1a4b4970837
Ref: library/math math tau4970921
Ref: 1a4c4970921
Ref: library/math math inf4971241
Ref: 5304971241
Ref: library/math math nan4971415
Ref: 5314971415
Ref: 常量<2>-Footnote-14972564
Ref: 常量<2>-Footnote-24972616
Node: cmath --- 关于复数的数学函数4972644
Ref: library/cmath doc4972820
Ref: 1a4d4972820
Ref: library/cmath cmath-mathematical-functions-for-complex-numbers4972820
Ref: 1a4e4972820
Ref: library/cmath module-cmath4972820
Ref: 194972820
Node: 到极坐标和从极坐标的转换4973830
Ref: library/cmath conversions-to-and-from-polar-coordinates4973976
Ref: 1a4f4973976
Ref: library/cmath cmath phase4974646
Ref: 1a504974646
Ref: library/cmath cmath polar4975444
Ref: 1a514975444
Ref: library/cmath cmath rect4975676
Ref: 1a524975676
Node: 幂函数与对数函数<2>4975830
Ref: library/cmath power-and-logarithmic-functions4976000
Ref: 1a534976000
Ref: library/cmath cmath exp4976059
Ref: 1a544976059
Ref: library/cmath cmath log4976152
Ref: 1a554976152
Ref: library/cmath cmath log104976364
Ref: 1a564976364
Ref: library/cmath cmath sqrt4976498
Ref: 1a574976498
Node: 三角函数<2>4976613
Ref: library/cmath trigonometric-functions4976762
Ref: 1a584976762
Ref: library/cmath cmath acos4976801
Ref: 1a594976801
Ref: library/cmath cmath asin4977049
Ref: 1a5a4977049
Ref: library/cmath cmath atan4977161
Ref: 1a5b4977161
Ref: library/cmath cmath cos4977419
Ref: 1a5c4977419
Ref: library/cmath cmath sin4977476
Ref: 1a5d4977476
Ref: library/cmath cmath tan4977533
Ref: 1a5e4977533
Node: 双曲函数<2>4977590
Ref: library/cmath hyperbolic-functions4977724
Ref: 1a5f4977724
Ref: library/cmath cmath acosh4977763
Ref: 1a604977763
Ref: library/cmath cmath asinh4977924
Ref: 1a614977924
Ref: library/cmath cmath atanh4978162
Ref: 1a624978162
Ref: library/cmath cmath cosh4978428
Ref: 1a634978428
Ref: library/cmath cmath sinh4978495
Ref: 1a644978495
Ref: library/cmath cmath tanh4978562
Ref: 1a654978562
Node: 分类函数4978629
Ref: library/cmath classification-functions4978757
Ref: 1a664978757
Ref: library/cmath cmath isfinite4978796
Ref: 1a674978796
Ref: library/cmath cmath isinf4978956
Ref: 1a684978956
Ref: library/cmath cmath isnan4979092
Ref: 1a694979092
Ref: library/cmath cmath isclose4979221
Ref: 6904979221
Ref: 分类函数-Footnote-14980413
Node: 常量<3>4980462
Ref: library/cmath constants4980566
Ref: 1a6a4980566
Ref: library/cmath cmath pi4980595
Ref: 1a6b4980595
Ref: library/cmath cmath e4980669
Ref: 1a6c4980669
Ref: library/cmath cmath tau4980741
Ref: 52d4980741
Ref: library/cmath cmath inf4980840
Ref: 52e4980840
Ref: library/cmath cmath infj4980946
Ref: 5324980946
Ref: library/cmath cmath nan4981091
Ref: 52f4981091
Ref: library/cmath cmath nanj4981212
Ref: 5334981212
Node: decimal --- 十进制定点和浮点运算4982464
Ref: library/decimal doc4982639
Ref: 1a6d4982639
Ref: library/decimal decimal-decimal-fixed-point-and-floating-point-arithmetic4982639
Ref: 1a6e4982639
Ref: library/decimal module-decimal4982639
Ref: 364982639
Ref: decimal --- 十进制定点和浮点运算-Footnote-14987165
Ref: decimal --- 十进制定点和浮点运算-Footnote-24987231
Node: 快速入门教程4987284
Ref: library/decimal decimal-tutorial4987404
Ref: 1a7e4987404
Ref: library/decimal quick-start-tutorial4987404
Ref: 1a7f4987404
Node: Decimal 对象4994179
Ref: library/decimal decimal-decimal4994323
Ref: 1a824994323
Ref: library/decimal decimal-objects4994323
Ref: 1a834994323
Ref: library/decimal decimal Decimal4994368
Ref: 1894994368
Ref: library/decimal decimal Decimal adjusted4998948
Ref: 1a844998948
Ref: library/decimal decimal Decimal as_integer_ratio4999213
Ref: 5444999213
Ref: library/decimal decimal Decimal as_tuple4999623
Ref: 1a854999623
Ref: library/decimal decimal Decimal canonical4999776
Ref: 1a864999776
Ref: library/decimal decimal Decimal compare4999972
Ref: 1a874999972
Ref: library/decimal decimal Decimal compare_signal5000383
Ref: 1a885000383
Ref: library/decimal decimal Decimal compare_total5000671
Ref: 1a895000671
Ref: library/decimal decimal Decimal compare_total_mag5001814
Ref: 1a8a5001814
Ref: library/decimal decimal Decimal conjugate5002369
Ref: 1a8b5002369
Ref: library/decimal decimal Decimal copy_abs5002467
Ref: 1a8c5002467
Ref: library/decimal decimal Decimal copy_negate5002638
Ref: 1a8d5002638
Ref: library/decimal decimal Decimal copy_sign5002809
Ref: 1a8e5002809
Ref: library/decimal decimal Decimal exp5003300
Ref: 9f55003300
Ref: library/decimal decimal Decimal from_float5003690
Ref: b885003690
Ref: library/decimal decimal Decimal fma5004685
Ref: 1a8f5004685
Ref: library/decimal decimal Decimal is_canonical5004917
Ref: 1a905004917
Ref: library/decimal decimal Decimal is_finite5005179
Ref: 1a915005179
Ref: library/decimal decimal Decimal is_infinite5005370
Ref: 1a925005370
Ref: library/decimal decimal Decimal is_nan5005522
Ref: 1a935005522
Ref: library/decimal decimal Decimal is_normal5005684
Ref: 1a945005684
Ref: library/decimal decimal Decimal is_qnan5005906
Ref: 1a955005906
Ref: library/decimal decimal Decimal is_signed5006044
Ref: 1a965006044
Ref: library/decimal decimal Decimal is_snan5006229
Ref: 1a975006229
Ref: library/decimal decimal Decimal is_subnormal5006370
Ref: 1a985006370
Ref: library/decimal decimal Decimal is_zero5006530
Ref: 1a995006530
Ref: library/decimal decimal Decimal ln5006680
Ref: 9f65006680
Ref: library/decimal decimal Decimal log105006864
Ref: 1a9a5006864
Ref: library/decimal decimal Decimal logb5007042
Ref: 1a9b5007042
Ref: library/decimal decimal Decimal logical_and5007403
Ref: 1a9c5007403
Ref: library/decimal decimal Decimal logical_invert5007666
Ref: 1a9e5007666
Ref: library/decimal decimal Decimal logical_or5007827
Ref: 1a9f5007827
Ref: library/decimal decimal Decimal logical_xor5008091
Ref: 1aa05008091
Ref: library/decimal decimal Decimal max5008352
Ref: 1aa15008352
Ref: library/decimal decimal Decimal max_mag5008621
Ref: 1aa25008621
Ref: library/decimal decimal Decimal min5008764
Ref: 1aa35008764
Ref: library/decimal decimal Decimal min_mag5009033
Ref: 1aa45009033
Ref: library/decimal decimal Decimal next_minus5009176
Ref: 1aa55009176
Ref: library/decimal decimal Decimal next_plus5009405
Ref: 1aa65009405
Ref: library/decimal decimal Decimal next_toward5009633
Ref: 1aa75009633
Ref: library/decimal decimal Decimal normalize5009944
Ref: 1aa85009944
Ref: library/decimal decimal Decimal number_class5010321
Ref: 1aa95010321
Ref: library/decimal decimal Decimal quantize5011221
Ref: 9f95011221
Ref: library/decimal decimal Decimal radix5012265
Ref: 1aaa5012265
Ref: library/decimal decimal Decimal remainder_near5012481
Ref: 1aab5012481
Ref: library/decimal decimal Decimal rotate5013247
Ref: 1aac5013247
Ref: library/decimal decimal Decimal same_quantum5013826
Ref: 1aad5013826
Ref: library/decimal decimal Decimal scaleb5014191
Ref: 1aae5014191
Ref: library/decimal decimal Decimal shift5014459
Ref: 1aaf5014459
Ref: library/decimal decimal Decimal sqrt5014946
Ref: 1ab05014946
Ref: library/decimal decimal Decimal to_eng_string5015044
Ref: 1ab15015044
Ref: library/decimal decimal Decimal to_integral5015448
Ref: 1ab25015448
Ref: library/decimal decimal Decimal to_integral_exact5015644
Ref: 1ab45015644
Ref: library/decimal decimal Decimal to_integral_value5016076
Ref: 1ab35016076
Node: 逻辑操作数5016438
Ref: library/decimal logical-operands5016504
Ref: 1ab55016504
Ref: library/decimal logical-operands-label5016504
Ref: 1a9d5016504
Node: 上下文对象5016816
Ref: library/decimal context-objects5016951
Ref: 1ab65016951
Ref: library/decimal decimal-context5016951
Ref: 1ab75016951
Ref: library/decimal decimal getcontext5017286
Ref: 1a805017286
Ref: library/decimal decimal setcontext5017367
Ref: 1a815017367
Ref: library/decimal decimal localcontext5017572
Ref: 16ed5017572
Ref: library/decimal decimal BasicContext5018421
Ref: 9f15018421
Ref: library/decimal decimal ExtendedContext5018827
Ref: 9f25018827
Ref: library/decimal decimal DefaultContext5019344
Ref: 9f05019344
Ref: library/decimal decimal Context5020282
Ref: 9f85020282
Ref: library/decimal decimal Context clear_flags5022931
Ref: 1abc5022931
Ref: library/decimal decimal Context clear_traps5023011
Ref: 1abd5023011
Ref: library/decimal decimal Context copy5023123
Ref: 1abe5023123
Ref: library/decimal decimal Context copy_decimal5023194
Ref: 1abf5023194
Ref: library/decimal decimal Context create_decimal5023287
Ref: 9f45023287
Ref: library/decimal decimal Context create_decimal_from_float5024294
Ref: 1ac05024294
Ref: library/decimal decimal Context Etiny5025041
Ref: 1ac15025041
Ref: library/decimal decimal Context Etop5025248
Ref: 1ac25025248
Ref: library/decimal decimal Context abs5025690
Ref: 1ac35025690
Ref: library/decimal decimal Context add5025754
Ref: 1ac45025754
Ref: library/decimal decimal Context canonical5025823
Ref: ca55025823
Ref: library/decimal decimal Context compare5025904
Ref: 1ac55025904
Ref: library/decimal decimal Context compare_signal5025986
Ref: 1ac65025986
Ref: library/decimal decimal Context compare_total5026077
Ref: 1ac75026077
Ref: library/decimal decimal Context compare_total_mag5026182
Ref: 1ac85026182
Ref: library/decimal decimal Context copy_abs5026306
Ref: 1ac95026306
Ref: library/decimal decimal Context copy_negate5026389
Ref: 1aca5026389
Ref: library/decimal decimal Context copy_sign5026473
Ref: 1acb5026473
Ref: library/decimal decimal Context divide5026550
Ref: 1acc5026550
Ref: library/decimal decimal Context divide_int5026628
Ref: 1acd5026628
Ref: library/decimal decimal Context divmod5026728
Ref: 1ace5026728
Ref: library/decimal decimal Context exp5026823
Ref: 1acf5026823
Ref: library/decimal decimal Context fma5026883
Ref: 1ad05026883
Ref: library/decimal decimal Context is_canonical5026972
Ref: ca65026972
Ref: library/decimal decimal Context is_finite5027092
Ref: 1ad15027092
Ref: library/decimal decimal Context is_infinite5027214
Ref: 1ad25027214
Ref: library/decimal decimal Context is_nan5027333
Ref: 1ad35027333
Ref: library/decimal decimal Context is_normal5027453
Ref: 1ad45027453
Ref: library/decimal decimal Context is_qnan5027570
Ref: 1ad55027570
Ref: library/decimal decimal Context is_signed5027687
Ref: 1ad65027687
Ref: library/decimal decimal Context is_snan5027794
Ref: 1ad75027794
Ref: library/decimal decimal Context is_subnormal5027911
Ref: 1ad85027911
Ref: library/decimal decimal Context is_zero5028034
Ref: 1ad95028034
Ref: library/decimal decimal Context ln5028143
Ref: 1ada5028143
Ref: library/decimal decimal Context log105028227
Ref: 1adb5028227
Ref: library/decimal decimal Context logb5028306
Ref: 1adc5028306
Ref: library/decimal decimal Context logical_and5028386
Ref: 1add5028386
Ref: library/decimal decimal Context logical_invert5028492
Ref: 1ade5028492
Ref: library/decimal decimal Context logical_or5028573
Ref: 1adf5028573
Ref: library/decimal decimal Context logical_xor5028677
Ref: 1ae05028677
Ref: library/decimal decimal Context max5028783
Ref: 1ae15028783
Ref: library/decimal decimal Context max_mag5028884
Ref: 1ae25028884
Ref: library/decimal decimal Context min5028980
Ref: 1ae35028980
Ref: library/decimal decimal Context min_mag5029081
Ref: 1ae45029081
Ref: library/decimal decimal Context minus5029177
Ref: 1ae55029177
Ref: library/decimal decimal Context multiply5029288
Ref: 1ae65029288
Ref: library/decimal decimal Context next_minus5029362
Ref: 1ae75029362
Ref: library/decimal decimal Context next_plus5029454
Ref: 1ae85029454
Ref: library/decimal decimal Context next_toward5029545
Ref: 1ae95029545
Ref: library/decimal decimal Context normalize5029643
Ref: 1aea5029643
Ref: library/decimal decimal Context number_class5029719
Ref: 1aeb5029719
Ref: library/decimal decimal Context plus5029795
Ref: 1aec5029795
Ref: library/decimal decimal Context power5029996
Ref: 1aed5029996
Ref: library/decimal decimal Context quantize5031631
Ref: 1aee5031631
Ref: library/decimal decimal Context radix5031736
Ref: 1aef5031736
Ref: library/decimal decimal Context remainder5031823
Ref: 1af05031823
Ref: library/decimal decimal Context remainder_near5031987
Ref: 1af15031987
Ref: library/decimal decimal Context rotate5032191
Ref: 1af25032191
Ref: library/decimal decimal Context same_quantum5032272
Ref: 1af35032272
Ref: library/decimal decimal Context scaleb5032387
Ref: 1af45032387
Ref: library/decimal decimal Context shift5032497
Ref: 1af55032497
Ref: library/decimal decimal Context sqrt5032577
Ref: 1af65032577
Ref: library/decimal decimal Context subtract5032661
Ref: 1af75032661
Ref: library/decimal decimal Context to_eng_string5032735
Ref: 1af85032735
Ref: library/decimal decimal Context to_integral_exact5033020
Ref: 1af95033020
Ref: library/decimal decimal Context to_sci_string5033096
Ref: 1afa5033096
Node: 常量<4>5033201
Ref: library/decimal constants5033334
Ref: 1afb5033334
Ref: library/decimal decimal-rounding-modes5033334
Ref: 1afc5033334
Ref: library/decimal decimal MAX_PREC5033732
Ref: 1ab85033732
Ref: library/decimal decimal MAX_EMAX5033869
Ref: 1abb5033869
Ref: library/decimal decimal MIN_EMIN5034006
Ref: 1aba5034006
Ref: library/decimal decimal MIN_ETINY5034144
Ref: 1afd5034144
Ref: library/decimal decimal HAVE_THREADS5034272
Ref: 9ee5034272
Ref: library/decimal decimal HAVE_CONTEXTVAR5034412
Ref: 1afe5034412
Node: 舍入模式5034769
Ref: library/decimal rounding-modes5034893
Ref: 1ab95034893
Ref: library/decimal decimal ROUND_CEILING5034932
Ref: 1a6f5034932
Ref: library/decimal decimal ROUND_DOWN5035007
Ref: 1a705035007
Ref: library/decimal decimal ROUND_FLOOR5035067
Ref: 1a715035067
Ref: library/decimal decimal ROUND_HALF_DOWN5035141
Ref: 1a725035141
Ref: library/decimal decimal ROUND_HALF_EVEN5035248
Ref: 1a735035248
Ref: library/decimal decimal ROUND_HALF_UP5035364
Ref: 1a745035364
Ref: library/decimal decimal ROUND_UP5035475
Ref: 1a755035475
Ref: library/decimal decimal ROUND_05UP5035539
Ref: 1a765035539
Node: 信号5035695
Ref: library/decimal decimal-signals5035825
Ref: 1aff5035825
Ref: library/decimal signals5035825
Ref: 1b005035825
Ref: library/decimal decimal Clamped5036475
Ref: 1a775036475
Ref: library/decimal decimal DecimalException5036747
Ref: 1b015036747
Ref: library/decimal decimal DivisionByZero5036873
Ref: 1a785036873
Ref: library/decimal decimal Inexact5037167
Ref: 1a795037167
Ref: library/decimal decimal InvalidOperation5037407
Ref: 9f35037407
Ref: library/decimal decimal Overflow5037826
Ref: 1a7c5037826
Ref: library/decimal decimal Rounded5038201
Ref: 1a7a5038201
Ref: library/decimal decimal Subnormal5038537
Ref: 1a7b5038537
Ref: library/decimal decimal Underflow5038765
Ref: 1a7d5038765
Ref: library/decimal decimal FloatOperation5039009
Ref: 9ed5039009
Node: 浮点数说明5040248
Ref: library/decimal decimal-notes5040378
Ref: 1b025040378
Ref: library/decimal floating-point-notes5040378
Ref: 1b035040378
Node: 通过提升精度来解决舍入错误5040493
Ref: library/decimal mitigating-round-off-error-with-increased-precision5040605
Ref: 1b045040605
Node: 特殊的值5042092
Ref: library/decimal special-values5042204
Ref: 1b055042204
Node: 使用线程5045035
Ref: library/decimal decimal-threads5045165
Ref: 1b065045165
Ref: library/decimal working-with-threads5045165
Ref: 1b075045165
Node: 例程5046431
Ref: library/decimal decimal-recipes5046566
Ref: 1b085046566
Ref: library/decimal recipes5046566
Ref: 1b095046566
Node: Decimal 常见问题5051390
Ref: library/decimal decimal-faq5051504
Ref: 1b0a5051504
Ref: library/decimal id15051504
Ref: 1b0b5051504
Ref: Decimal 常见问题-Footnote-15057418
Ref: Decimal 常见问题-Footnote-25057485
Ref: Decimal 常见问题-Footnote-35057543
Node: fractions --- 分数5057646
Ref: library/fractions doc5057813
Ref: 1b0c5057813
Ref: library/fractions fractions-rational-numbers5057813
Ref: 1b0d5057813
Ref: library/fractions module-fractions5057813
Ref: 835057813
Ref: library/fractions fractions Fraction5058112
Ref: 1865058112
Ref: library/fractions fractions Fraction numerator5061089
Ref: 1b0f5061089
Ref: library/fractions fractions Fraction denominator5061159
Ref: 1b105061159
Ref: library/fractions fractions Fraction as_integer_ratio5061231
Ref: 1b115061231
Ref: library/fractions fractions Fraction from_float5061417
Ref: b895061417
Ref: library/fractions fractions Fraction from_decimal5061839
Ref: b8a5061839
Ref: library/fractions fractions Fraction limit_denominator5062202
Ref: 1b0e5062202
Ref: library/fractions fractions Fraction __floor__5063027
Ref: 1b125063027
Ref: library/fractions fractions Fraction __ceil__5063299
Ref: 1b135063299
Ref: library/fractions fractions Fraction __round__5063464
Ref: 1b145063464
Ref: library/fractions fractions gcd5063972
Ref: 7205063972
Ref: fractions --- 分数-Footnote-15064493
Node: random --- 生成伪随机数5064561
Ref: library/random doc5064719
Ref: 1b155064719
Ref: library/random module-random5064719
Ref: dd5064719
Ref: library/random random-generate-pseudo-random-numbers5064719
Ref: 1b165064719
Ref: random --- 生成伪随机数-Footnote-15067254
Ref: random --- 生成伪随机数-Footnote-25067319
Node: 簿记功能5067372
Ref: library/random bookkeeping-functions5067474
Ref: 1b1a5067474
Ref: library/random random seed5067513
Ref: c105067513
Ref: library/random random getstate5068321
Ref: 1b1b5068321
Ref: library/random random setstate5068487
Ref: 1b1c5068487
Ref: library/random random getrandbits5068726
Ref: 93b5068726
Node: 整数用函数5069081
Ref: library/random functions-for-integers5069207
Ref: 1b1d5069207
Ref: library/random random randrange5069251
Ref: bc35069251
Ref: library/random random randint5069898
Ref: bc45069898
Node: 序列用函数5070026
Ref: library/random functions-for-sequences5070152
Ref: 1b1e5070152
Ref: library/random random choice5070196
Ref: bc55070196
Ref: library/random random choices5070348
Ref: 57d5070348
Ref: library/random random shuffle5071961
Ref: bc65071961
Ref: library/random random sample5072663
Ref: bc75072663
Node: 实值分布5073567
Ref: library/random real-valued-distributions5073693
Ref: 1b1f5073693
Ref: library/random random random5073939
Ref: 1b175073939
Ref: library/random random uniform5074033
Ref: 1b205074033
Ref: library/random random triangular5074332
Ref: 1b215074332
Ref: library/random random betavariate5074628
Ref: 1b225074628
Ref: library/random random expovariate5074801
Ref: 1b235074801
Ref: library/random random gammavariate5075160
Ref: 1b245075160
Ref: library/random random gauss5075528
Ref: 1b255075528
Ref: library/random random lognormvariate5075704
Ref: 1b275075704
Ref: library/random random normalvariate5075968
Ref: 1b265075968
Ref: library/random random vonmisesvariate5076080
Ref: 1b285076080
Ref: library/random random paretovariate5076394
Ref: 1b295076394
Ref: library/random random weibullvariate5076488
Ref: 1b2a5076488
Node: 替代生成器5076614
Ref: library/random alternative-generator5076749
Ref: 1b2b5076749
Ref: library/random random Random5076793
Ref: 1b185076793
Ref: library/random random SystemRandom5076912
Ref: 1b195076912
Node: 关于再现性的说明5077341
Ref: library/random notes-on-reproducibility5077479
Ref: 1b2c5077479
Node: 例子和配方5078072
Ref: library/random examples-and-recipes5078186
Ref: 1b2d5078186
Ref: library/random random-examples5078186
Ref: b605078186
Ref: 例子和配方-Footnote-15083459
Ref: 例子和配方-Footnote-25083524
Ref: 例子和配方-Footnote-35083605
Ref: 例子和配方-Footnote-45083651
Ref: 例子和配方-Footnote-55083703
Ref: 例子和配方-Footnote-65083758
Ref: 例子和配方-Footnote-75083834
Ref: 例子和配方-Footnote-85083869
Ref: 例子和配方-Footnote-95083947
Node: statistics --- 数学统计函数5083982
Ref: library/statistics doc5084111
Ref: 1b2e5084111
Ref: library/statistics module-statistics5084111
Ref: f65084111
Ref: library/statistics statistics-mathematical-statistics-functions5084111
Ref: 1b2f5084111
Ref: statistics --- 数学统计函数-Footnote-15085257
Ref: statistics --- 数学统计函数-Footnote-25085326
Ref: statistics --- 数学统计函数-Footnote-35085352
Node: 平均值以及对中心位置的评估5085383
Ref: library/statistics averages-and-measures-of-central-location5085525
Ref: 1b305085525
Node: 对分散程度的评估5087056
Ref: library/statistics measures-of-spread5087219
Ref: 1b355087219
Node: 函数细节5087771
Ref: library/statistics function-details5087904
Ref: 1b3a5087904
Ref: library/statistics statistics mean5088096
Ref: 19a5088096
Ref: library/statistics statistics fmean5089468
Ref: 2285089468
Ref: library/statistics statistics geometric_mean5089890
Ref: 2295089890
Ref: library/statistics statistics harmonic_mean5090495
Ref: 5985090495
Ref: library/statistics statistics median5091831
Ref: 1b315091831
Ref: library/statistics statistics median_low5092763
Ref: 1b325092763
Ref: library/statistics statistics median_high5093378
Ref: 1b335093378
Ref: library/statistics statistics median_grouped5093990
Ref: 1b345093990
Ref: library/statistics statistics mode5095561
Ref: 2bc5095561
Ref: library/statistics statistics multimode5096671
Ref: 22a5096671
Ref: library/statistics statistics pstdev5097076
Ref: 1b365097076
Ref: library/statistics statistics pvariance5097340
Ref: 1b375097340
Ref: library/statistics statistics stdev5099447
Ref: 1b385099447
Ref: library/statistics statistics variance5099711
Ref: 1b395099711
Ref: library/statistics statistics quantiles5101849
Ref: 22b5101849
Ref: 函数细节-Footnote-15104482
Ref: 函数细节-Footnote-25104577
Node: 异常<3>5104657
Ref: library/statistics exceptions5104783
Ref: 1b3c5104783
Ref: library/statistics statistics StatisticsError5104841
Ref: 1b3b5104841
Node: NormalDist 对象5104953
Ref: library/statistics normaldist-objects5105058
Ref: 1b3d5105058
Ref: library/statistics statistics NormalDist5105387
Ref: 22c5105387
Ref: library/statistics statistics NormalDist mean5105639
Ref: 1b3e5105639
Ref: library/statistics statistics NormalDist median5105750
Ref: 1b3f5105750
Ref: library/statistics statistics NormalDist mode5105857
Ref: 1b405105857
Ref: library/statistics statistics NormalDist stdev5105959
Ref: 1b415105959
Ref: library/statistics statistics NormalDist variance5106065
Ref: 1b425106065
Ref: library/statistics statistics NormalDist from_samples5106210
Ref: 1b435106210
Ref: library/statistics statistics NormalDist samples5106751
Ref: 1b445106751
Ref: library/statistics statistics NormalDist pdf5107128
Ref: 1b455107128
Ref: library/statistics statistics NormalDist cdf5107651
Ref: 1b465107651
Ref: library/statistics statistics NormalDist inv_cdf5107842
Ref: 1b475107842
Ref: library/statistics statistics NormalDist overlap5108167
Ref: 1b485108167
Ref: library/statistics statistics NormalDist quantiles5108369
Ref: 1b495108369
Ref: NormalDist 对象-Footnote-15109875
Ref: NormalDist 对象-Footnote-25109939
Ref: NormalDist 对象-Footnote-35109999
Ref: NormalDist 对象-Footnote-45110053
Ref: NormalDist 对象-Footnote-55110110
Ref: NormalDist 对象-Footnote-65110164
Ref: NormalDist 对象-Footnote-75110209
Ref: NormalDist 对象-Footnote-85110265
Ref: NormalDist 对象-Footnote-95110322
Ref: NormalDist 对象-Footnote-105110369
Ref: NormalDist 对象-Footnote-115110437
Ref: NormalDist 对象-Footnote-125110509
Ref: NormalDist 对象-Footnote-135110566
Ref: NormalDist 对象-Footnote-145110658
Ref: NormalDist 对象-Footnote-155110705
Node: NormalDist 示例和用法5110790
Ref: library/statistics normaldist-examples-and-recipes5110870
Ref: 1b4a5110870
Ref: NormalDist 示例和用法-Footnote-15115225
Ref: NormalDist 示例和用法-Footnote-25115296
Ref: NormalDist 示例和用法-Footnote-35115343
Ref: NormalDist 示例和用法-Footnote-45115388
Ref: NormalDist 示例和用法-Footnote-55115445
Ref: NormalDist 示例和用法-Footnote-65115508
Ref: NormalDist 示例和用法-Footnote-75115589
Ref: NormalDist 示例和用法-Footnote-85115645
Node: 函数式编程模块5115715
Ref: library/functional doc5115849
Ref: 1b4b5115849
Ref: library/functional functional-programming-modules5115849
Ref: 1b4c5115849
Node: itertools --- 为高效循环而创建迭代器的函数5116378
Ref: library/itertools doc5116557
Ref: 1b4d5116557
Ref: library/itertools itertools-functions-creating-iterators-for-efficient-looping5116557
Ref: 1b4e5116557
Ref: library/itertools module-itertools5116557
Ref: a45116557
Node: Itertool函数5126784
Ref: library/itertools itertool-functions5126916
Ref: 1b555126916
Ref: library/itertools itertools-functions5126916
Ref: 1b565126916
Ref: library/itertools itertools accumulate5127125
Ref: 1de5127125
Ref: library/itertools itertools chain5130500
Ref: 16135130500
Ref: library/itertools itertools chain from_iterable5130998
Ref: 1b505130998
Ref: library/itertools itertools combinations5131453
Ref: cae5131453
Ref: library/itertools itertools combinations_with_replacement5133307
Ref: c215133307
Ref: library/itertools itertools compress5135136
Ref: c225135136
Ref: library/itertools itertools count5135552
Ref: c235135552
Ref: library/itertools itertools cycle5136289
Ref: 1b4f5136289
Ref: library/itertools itertools dropwhile5136962
Ref: 1b515136962
Ref: library/itertools itertools filterfalse5137633
Ref: 15fc5137633
Ref: library/itertools itertools groupby5138180
Ref: 1b525138180
Ref: library/itertools itertools islice5140808
Ref: 3aa5140808
Ref: library/itertools itertools permutations5142737
Ref: ed95142737
Ref: library/itertools itertools product5145045
Ref: caf5145045
Ref: library/itertools itertools repeat5146315
Ref: 10c25146315
Ref: library/itertools itertools starmap5147163
Ref: a305147163
Ref: library/itertools itertools takewhile5147812
Ref: 1b535147812
Ref: library/itertools itertools tee5148241
Ref: 1b545148241
Ref: library/itertools itertools zip_longest5149902
Ref: c395149902
Ref: Itertool函数-Footnote-15151302
Node: itertools 配方5151360
Ref: library/itertools id15151492
Ref: 1b585151492
Ref: library/itertools itertools-recipes5151492
Ref: bfd5151492
Ref: itertools 配方-Footnote-15160439
Node: functools --- 高阶函数和可调用对象上的操作5160488
Ref: library/functools doc5160716
Ref: 1b595160716
Ref: library/functools functools-higher-order-functions-and-operations-on-callable-objects5160716
Ref: 1b5a5160716
Ref: library/functools module-functools5160716
Ref: 855160716
Ref: library/functools functools cached_property5161168
Ref: 1c95161168
Ref: library/functools functools cmp_to_key5162423
Ref: b5e5162423
Ref: library/functools functools lru_cache5163416
Ref: 1c85163416
Ref: library/functools functools total_ordering5167322
Ref: 8545167322
Ref: library/functools functools partial5169086
Ref: 7d15169086
Ref: library/functools functools partialmethod5170394
Ref: 29d5170394
Ref: library/functools functools reduce5172091
Ref: c775172091
Ref: library/functools functools singledispatch5173249
Ref: 3925173249
Ref: library/functools functools singledispatchmethod5177173
Ref: 1ca5177173
Ref: library/functools functools update_wrapper5178773
Ref: 9625178773
Ref: library/functools functools wraps5180824
Ref: 8735180824
Ref: functools --- 高阶函数和可调用对象上的操作-Footnote-15182080
Ref: functools --- 高阶函数和可调用对象上的操作-Footnote-25182148
Ref: functools --- 高阶函数和可调用对象上的操作-Footnote-35182212
Ref: functools --- 高阶函数和可调用对象上的操作-Footnote-45182263
Ref: functools --- 高阶函数和可调用对象上的操作-Footnote-55182320
Node: partial 对象5182363
Ref: library/functools id15182470
Ref: 1b5c5182470
Ref: library/functools partial-objects5182470
Ref: 1b5b5182470
Ref: library/functools functools partial func5182644
Ref: 1b5d5182644
Ref: library/functools functools partial args5182825
Ref: 1b5e5182825
Ref: library/functools functools partial keywords5182966
Ref: 1b5f5182966
Node: operator --- 标准运算符替代函数5183492
Ref: library/operator doc5183655
Ref: 1b605183655
Ref: library/operator module-operator5183655
Ref: c35183655
Ref: library/operator operator-standard-operators-as-functions5183655
Ref: 1b615183655
Ref: library/operator operator lt5184423
Ref: 1b625184423
Ref: library/operator operator le5184454
Ref: 1b635184454
Ref: library/operator operator eq5184485
Ref: 1b645184485
Ref: library/operator operator ne5184516
Ref: 1b655184516
Ref: library/operator operator ge5184547
Ref: 1b665184547
Ref: library/operator operator gt5184578
Ref: 1b675184578
Ref: library/operator operator __lt__5184609
Ref: 1b685184609
Ref: library/operator operator __le__5184644
Ref: 1b695184644
Ref: library/operator operator __eq__5184679
Ref: 1b6a5184679
Ref: library/operator operator __ne__5184714
Ref: 1b6b5184714
Ref: library/operator operator __ge__5184749
Ref: 1b6c5184749
Ref: library/operator operator __gt__5184784
Ref: 1b6d5184784
Ref: library/operator operator not_5185393
Ref: 1b6e5185393
Ref: library/operator operator __not__5185425
Ref: 1b6f5185425
Ref: library/operator operator truth5185710
Ref: 1b705185710
Ref: library/operator operator is_5185889
Ref: 1b715185889
Ref: library/operator operator is_not5185973
Ref: 1b725185973
Ref: library/operator operator abs5186111
Ref: 1b735186111
Ref: library/operator operator __abs__5186142
Ref: 1b745186142
Ref: library/operator operator add5186213
Ref: 1b755186213
Ref: library/operator operator __add__5186245
Ref: 1b765186245
Ref: library/operator operator and_5186337
Ref: 1b775186337
Ref: library/operator operator __and__5186370
Ref: 1b785186370
Ref: library/operator operator floordiv5186454
Ref: 1b795186454
Ref: library/operator operator __floordiv__5186491
Ref: 1b7a5186491
Ref: library/operator operator index5186562
Ref: 14915186562
Ref: library/operator operator __index__5186593
Ref: 1b7b5186593
Ref: library/operator operator inv5186707
Ref: 1b7c5186707
Ref: library/operator operator invert5186738
Ref: 1b7d5186738
Ref: library/operator operator __inv__5186772
Ref: 1b7e5186772
Ref: library/operator operator __invert__5186807
Ref: 1b7f5186807
Ref: library/operator operator lshift5186923
Ref: 1b805186923
Ref: library/operator operator __lshift__5186958
Ref: 1b815186958
Ref: library/operator operator mod5187042
Ref: 1b825187042
Ref: library/operator operator __mod__5187074
Ref: 1b835187074
Ref: library/operator operator mul5187139
Ref: 1b575187139
Ref: library/operator operator __mul__5187171
Ref: 1b845187171
Ref: library/operator operator matmul5187263
Ref: 7265187263
Ref: library/operator operator __matmul__5187298
Ref: 1b855187298
Ref: library/operator operator neg5187390
Ref: 1b865187390
Ref: library/operator operator __neg__5187421
Ref: 1b875187421
Ref: library/operator operator or_5187508
Ref: 1b885187508
Ref: library/operator operator __or__5187540
Ref: 1b895187540
Ref: library/operator operator pos5187623
Ref: 1b8a5187623
Ref: library/operator operator __pos__5187654
Ref: 1b8b5187654
Ref: library/operator operator pow5187741
Ref: 1b8c5187741
Ref: library/operator operator __pow__5187773
Ref: 1b8d5187773
Ref: library/operator operator rshift5187866
Ref: 1b8e5187866
Ref: library/operator operator __rshift__5187901
Ref: 1b8f5187901
Ref: library/operator operator sub5187985
Ref: 1b905187985
Ref: library/operator operator __sub__5188017
Ref: 1b915188017
Ref: library/operator operator truediv5188082
Ref: 1b925188082
Ref: library/operator operator __truediv__5188118
Ref: 1b935188118
Ref: library/operator operator xor5188258
Ref: 1b945188258
Ref: library/operator operator __xor__5188290
Ref: 1b955188290
Ref: library/operator operator concat5188448
Ref: 1b965188448
Ref: library/operator operator __concat__5188483
Ref: 1b975188483
Ref: library/operator operator contains5188578
Ref: f145188578
Ref: library/operator operator __contains__5188615
Ref: 1b985188615
Ref: library/operator operator countOf5188736
Ref: f165188736
Ref: library/operator operator delitem5188820
Ref: 1b995188820
Ref: library/operator operator __delitem__5188856
Ref: 1b9a5188856
Ref: library/operator operator getitem5188944
Ref: 1b9b5188944
Ref: library/operator operator __getitem__5188980
Ref: 1b9c5188980
Ref: library/operator operator indexOf5189065
Ref: f155189065
Ref: library/operator operator setitem5189164
Ref: 1b9d5189164
Ref: library/operator operator __setitem__5189203
Ref: 1b9e5189203
Ref: library/operator operator length_hint5189301
Ref: 8865189301
Ref: library/operator operator attrgetter5189827
Ref: 7245189827
Ref: library/operator operator itemgetter5191111
Ref: 2625191111
Ref: library/operator operator methodcaller5192860
Ref: 7255192860
Ref: operator --- 标准运算符替代函数-Footnote-15193637
Node: 将运算符映射到函数5193704
Ref: library/operator mapping-operators-to-functions5193832
Ref: 1b9f5193832
Ref: library/operator operator-map5193832
Ref: 1ba05193832
Node: 原地运算符5201335
Ref: library/operator in-place-operators5201463
Ref: 1ba15201463
Ref: library/operator operator iadd5202607
Ref: 1ba35202607
Ref: library/operator operator __iadd__5202640
Ref: 1ba45202640
Ref: library/operator operator iand5202731
Ref: 1ba55202731
Ref: library/operator operator __iand__5202764
Ref: 1ba65202764
Ref: library/operator operator iconcat5202855
Ref: 1ba75202855
Ref: library/operator operator __iconcat__5202891
Ref: 1ba85202891
Ref: library/operator operator ifloordiv5203017
Ref: 1ba95203017
Ref: library/operator operator __ifloordiv__5203055
Ref: 1baa5203055
Ref: library/operator operator ilshift5203157
Ref: 1bab5203157
Ref: library/operator operator __ilshift__5203193
Ref: 1bac5203193
Ref: library/operator operator imod5203291
Ref: 1bad5203291
Ref: library/operator operator __imod__5203324
Ref: 1bae5203324
Ref: library/operator operator imul5203415
Ref: 1baf5203415
Ref: library/operator operator __imul__5203448
Ref: 1bb05203448
Ref: library/operator operator imatmul5203539
Ref: 7275203539
Ref: library/operator operator __imatmul__5203575
Ref: 1bb15203575
Ref: library/operator operator ior5203696
Ref: 1bb25203696
Ref: library/operator operator __ior__5203728
Ref: 1bb35203728
Ref: library/operator operator ipow5203817
Ref: 1bb45203817
Ref: library/operator operator __ipow__5203850
Ref: 1bb55203850
Ref: library/operator operator irshift5203942
Ref: 1bb65203942
Ref: library/operator operator __irshift__5203978
Ref: 1bb75203978
Ref: library/operator operator isub5204076
Ref: 1bb85204076
Ref: library/operator operator __isub__5204109
Ref: 1bb95204109
Ref: library/operator operator itruediv5204200
Ref: 1bba5204200
Ref: library/operator operator __itruediv__5204237
Ref: 1bbb5204237
Ref: library/operator operator ixor5204336
Ref: 1bbc5204336
Ref: library/operator operator __ixor__5204369
Ref: 1bbd5204369
Node: 文件和目录访问5204460
Ref: library/filesys doc5204588
Ref: 1bbe5204588
Ref: library/filesys file-and-directory-access5204588
Ref: 1bbf5204588
Ref: library/filesys filesys5204588
Ref: 1bc05204588
Node: pathlib --- 面向对象的文件系统路径5205613
Ref: library/pathlib doc5205755
Ref: 1bc15205755
Ref: library/pathlib module-pathlib5205755
Ref: c95205755
Ref: library/pathlib pathlib-object-oriented-filesystem-paths5205755
Ref: 1bc25205755
Ref: pathlib --- 面向对象的文件系统路径-Footnote-15207250
Ref: pathlib --- 面向对象的文件系统路径-Footnote-25207316
Node: 基础使用5207365
Ref: library/pathlib basic-use5207477
Ref: 1bc75207477
Node: 纯路径5208400
Ref: library/pathlib id15208533
Ref: 1bc85208533
Ref: library/pathlib pure-paths5208533
Ref: 1bc35208533
Ref: library/pathlib pathlib PurePath5208707
Ref: 10515208707
Ref: library/pathlib pathlib PurePosixPath5210780
Ref: 1bc95210780
Ref: library/pathlib pathlib PureWindowsPath5211060
Ref: 1bc65211060
Node: 通用性质5211596
Ref: library/pathlib general-properties5211675
Ref: 1bca5211675
Node: 运算符<2>5212497
Ref: library/pathlib operators5212603
Ref: 1bcb5212603
Node: 访问个别部分5213795
Ref: library/pathlib accessing-individual-parts5213910
Ref: 1bcc5213910
Ref: library/pathlib pathlib PurePath parts5214039
Ref: 1bcd5214039
Node: 方法和特征属性5214419
Ref: library/pathlib methods-and-properties5214513
Ref: 1bce5214513
Ref: library/pathlib pathlib PurePath drive5214616
Ref: 1bcf5214616
Ref: library/pathlib pathlib PurePath root5215039
Ref: 1bd05215039
Ref: library/pathlib pathlib PurePath anchor5215432
Ref: 1bd15215432
Ref: library/pathlib pathlib PurePath parents5215781
Ref: 1bd25215781
Ref: library/pathlib pathlib PurePath parent5216147
Ref: 1bd35216147
Ref: library/pathlib pathlib PurePath name5216905
Ref: 1bd55216905
Ref: library/pathlib pathlib PurePath suffix5217296
Ref: 1bd65217296
Ref: library/pathlib pathlib PurePath suffixes5217593
Ref: 1bd75217593
Ref: library/pathlib pathlib PurePath stem5217897
Ref: 1bd85217897
Ref: library/pathlib pathlib PurePath as_posix5218188
Ref: 1bd95218188
Ref: library/pathlib pathlib PurePath as_uri5218427
Ref: 1bda5218427
Ref: library/pathlib pathlib PurePath is_absolute5218774
Ref: 1bdb5218774
Ref: library/pathlib pathlib PurePath is_reserved5219375
Ref: 1bdc5219375
Ref: library/pathlib pathlib PurePath joinpath5219851
Ref: 1bdd5219851
Ref: library/pathlib pathlib PurePath match5220400
Ref: 1bde5220400
Ref: library/pathlib pathlib PurePath relative_to5221344
Ref: 1bdf5221344
Ref: library/pathlib pathlib PurePath with_name5221982
Ref: 1be05221982
Ref: library/pathlib pathlib PurePath with_suffix5222684
Ref: 10405222684
Node: 具体路径5223336
Ref: library/pathlib concrete-paths5223485
Ref: 1bc45223485
Ref: library/pathlib id25223485
Ref: 1be15223485
Ref: library/pathlib pathlib Path5223707
Ref: 2025223707
Ref: library/pathlib pathlib PosixPath5224055
Ref: 1be25224055
Ref: library/pathlib pathlib WindowsPath5224370
Ref: 1bc55224370
Node: 方法<2>5225322
Ref: library/pathlib methods5225380
Ref: 1be35225380
Ref: library/pathlib pathlib Path cwd5225931
Ref: 1be45225931
Ref: library/pathlib pathlib Path home5226153
Ref: 7345226153
Ref: library/pathlib pathlib Path stat5226431
Ref: 1be55226431
Ref: library/pathlib pathlib Path chmod5226783
Ref: 1be65226783
Ref: library/pathlib pathlib Path exists5227047
Ref: 2035227047
Ref: library/pathlib pathlib Path expanduser5227507
Ref: 7335227507
Ref: library/pathlib pathlib Path glob5227815
Ref: 1be75227815
Ref: library/pathlib pathlib Path group5228639
Ref: 1be85228639
Ref: library/pathlib pathlib Path is_dir5228805
Ref: 2045228805
Ref: library/pathlib pathlib Path is_file5229146
Ref: 2055229146
Ref: library/pathlib pathlib Path is_mount5229502
Ref: 2065229502
Ref: library/pathlib pathlib Path is_symlink5229993
Ref: 2075229993
Ref: library/pathlib pathlib Path is_socket5230207
Ref: 20b5230207
Ref: library/pathlib pathlib Path is_fifo5230571
Ref: 20a5230571
Ref: library/pathlib pathlib Path is_block_device5230926
Ref: 2085230926
Ref: library/pathlib pathlib Path is_char_device5231270
Ref: 2095231270
Ref: library/pathlib pathlib Path iterdir5231616
Ref: 1be95231616
Ref: library/pathlib pathlib Path lchmod5232318
Ref: 1bea5232318
Ref: library/pathlib pathlib Path lstat5232507
Ref: 1beb5232507
Ref: library/pathlib pathlib Path mkdir5232678
Ref: 7325232678
Ref: library/pathlib pathlib Path open5233736
Ref: 1bec5233736
Ref: library/pathlib pathlib Path owner5234082
Ref: 1bed5234082
Ref: library/pathlib pathlib Path read_bytes5234247
Ref: 7385234247
Ref: library/pathlib pathlib Path read_text5234551
Ref: 7365234551
Ref: library/pathlib pathlib Path rename5234962
Ref: 1bee5234962
Ref: library/pathlib pathlib Path replace5235781
Ref: 1bef5235781
Ref: library/pathlib pathlib Path resolve5236262
Ref: 1bd45236262
Ref: library/pathlib pathlib Path rglob5237160
Ref: 1bf05237160
Ref: library/pathlib pathlib Path rmdir5237535
Ref: 1bf15237535
Ref: library/pathlib pathlib Path samefile5237614
Ref: 7315237614
Ref: library/pathlib pathlib Path symlink_to5238129
Ref: 1bf25238129
Ref: library/pathlib pathlib Path link_to5238802
Ref: 20c5238802
Ref: library/pathlib pathlib Path touch5239180
Ref: 1bf35239180
Ref: library/pathlib pathlib Path unlink5239577
Ref: fde5239577
Ref: library/pathlib pathlib Path write_bytes5240067
Ref: 7375240067
Ref: library/pathlib pathlib Path write_text5240415
Ref: 7355240415
Node: 对应的 os 模块的工具5240834
Ref: library/pathlib correspondence-to-tools-in-the-os-module5240965
Ref: 1bf45240965
Node: os path --- 常用路径操作5245202
Ref: library/os path doc5245400
Ref: 1bfa5245400
Ref: library/os path module-os path5245400
Ref: c65245400
Ref: library/os path os-path-common-pathname-manipulations5245400
Ref: 1bfb5245400
Ref: library/os path os path abspath5247641
Ref: cb85247641
Ref: library/os path os path basename5247948
Ref: 1bf75247948
Ref: library/os path os path commonpath5248418
Ref: 72e5248418
Ref: library/os path os path commonprefix5248942
Ref: 72f5248942
Ref: library/os path os path dirname5249570
Ref: 1bf85249570
Ref: library/os path os path exists5249828
Ref: 1f75249828
Ref: library/os path os path lexists5250441
Ref: 1f85250441
Ref: library/os path os path expanduser5250763
Ref: 1ff5250763
Ref: library/os path os path expandvars5251699
Ref: d4c5251699
Ref: library/os path os path getatime5252170
Ref: 1bfd5252170
Ref: library/os path os path getmtime5252427
Ref: 1bfe5252427
Ref: library/os path os path getctime5252754
Ref: 1bff5252754
Ref: library/os path os path getsize5253230
Ref: 1c005253230
Ref: library/os path os path isabs5253477
Ref: 1bf65253477
Ref: library/os path os path isfile5253793
Ref: 1fa5253793
Ref: library/os path os path isdir5254129
Ref: 1f95254129
Ref: library/os path os path islink5254457
Ref: 1f55254457
Ref: library/os path os path ismount5254753
Ref: 1fb5254753
Ref: library/os path os path join5255591
Ref: f6c5255591
Ref: library/os path os path normcase5256572
Ref: 1c015256572
Ref: library/os path os path normpath5256863
Ref: cb75256863
Ref: library/os path os path realpath5257362
Ref: 2005257362
Ref: library/os path os path relpath5257858
Ref: 1bf55257858
Ref: library/os path os path samefile5258397
Ref: 88b5258397
Ref: library/os path os path sameopenfile5258905
Ref: 1c035258905
Ref: library/os path os path samestat5259215
Ref: 88a5259215
Ref: library/os path os path split5259765
Ref: 1bfc5259765
Ref: library/os path os path splitdrive5260560
Ref: 4855260560
Ref: library/os path os path splitext5261411
Ref: 1bf95261411
Ref: library/os path os path supports_unicode_filenames5261797
Ref: df55261797
Ref: os path --- 常用路径操作-Footnote-15262000
Ref: os path --- 常用路径操作-Footnote-25262068
Node: fileinput --- 迭代来自多个输入流的行5262133
Ref: library/fileinput doc5262313
Ref: 1c045262313
Ref: library/fileinput fileinput-iterate-over-lines-from-multiple-input-streams5262313
Ref: 1c055262313
Ref: library/fileinput module-fileinput5262313
Ref: 805262313
Ref: library/fileinput fileinput input5264407
Ref: 2ae5264407
Ref: library/fileinput fileinput filename5265439
Ref: 1c065265439
Ref: library/fileinput fileinput fileno5265568
Ref: 1c075265568
Ref: library/fileinput fileinput lineno5265753
Ref: 1c085265753
Ref: library/fileinput fileinput filelineno5265962
Ref: 1c095265962
Ref: library/fileinput fileinput isfirstline5266184
Ref: 1c0a5266184
Ref: library/fileinput fileinput isstdin5266330
Ref: 1c0b5266330
Ref: library/fileinput fileinput nextfile5266468
Ref: 1c0c5266468
Ref: library/fileinput fileinput close5266945
Ref: 1c0d5266945
Ref: library/fileinput fileinput FileInput5267079
Ref: 27f5267079
Ref: library/fileinput fileinput hook_compressed5269565
Ref: 1c0f5269565
Ref: library/fileinput fileinput hook_encoded5270051
Ref: 5535270051
Ref: fileinput --- 迭代来自多个输入流的行-Footnote-15270470
Node: stat --- 解析 stat 结果5270538
Ref: library/stat doc5270724
Ref: 1c105270724
Ref: library/stat module-stat5270724
Ref: f55270724
Ref: library/stat stat-interpreting-stat-results5270724
Ref: 1c115270724
Ref: library/stat stat S_ISDIR5271336
Ref: 1c125271336
Ref: library/stat stat S_ISCHR5271427
Ref: 1c135271427
Ref: library/stat stat S_ISBLK5271536
Ref: 1c145271536
Ref: library/stat stat S_ISREG5271642
Ref: 1c155271642
Ref: library/stat stat S_ISFIFO5271739
Ref: 1c165271739
Ref: library/stat stat S_ISLNK5271846
Ref: 1c175271846
Ref: library/stat stat S_ISSOCK5271943
Ref: 1c185271943
Ref: library/stat stat S_ISDOOR5272038
Ref: f7a5272038
Ref: library/stat stat S_ISPORT5272151
Ref: f7b5272151
Ref: library/stat stat S_ISWHT5272273
Ref: f7c5272273
Ref: library/stat stat S_IMODE5272471
Ref: 1c195272471
Ref: library/stat stat S_IFMT5272726
Ref: 1c1a5272726
Ref: library/stat stat filemode5274181
Ref: aa55274181
Ref: library/stat stat ST_MODE5274593
Ref: 8db5274593
Ref: library/stat stat ST_INO5274647
Ref: 1c1b5274647
Ref: library/stat stat ST_DEV5274688
Ref: 1c1c5274688
Ref: library/stat stat ST_NLINK5274744
Ref: 1c1d5274744
Ref: library/stat stat ST_UID5274808
Ref: 1c1e5274808
Ref: library/stat stat ST_GID5274864
Ref: 1c1f5274864
Ref: library/stat stat ST_SIZE5274922
Ref: 1c205274922
Ref: library/stat stat ST_ATIME5275051
Ref: 1c215275051
Ref: library/stat stat ST_MTIME5275109
Ref: 1c225275109
Ref: library/stat stat ST_CTIME5275167
Ref: 1c235275167
Ref: library/stat stat S_IFSOCK5276163
Ref: 1c245276163
Ref: library/stat stat S_IFLNK5276209
Ref: 1c255276209
Ref: library/stat stat S_IFREG5276257
Ref: 1c265276257
Ref: library/stat stat S_IFBLK5276305
Ref: 1c275276305
Ref: library/stat stat S_IFDIR5276350
Ref: 1c285276350
Ref: library/stat stat S_IFCHR5276392
Ref: 1c295276392
Ref: library/stat stat S_IFIFO5276440
Ref: 1c2a5276440
Ref: library/stat stat S_IFDOOR5276488
Ref: 8dc5276488
Ref: library/stat stat S_IFPORT5276552
Ref: 8dd5276552
Ref: library/stat stat S_IFWHT5276625
Ref: 8de5276625
Ref: library/stat stat S_ISUID5276923
Ref: 1c2b5276923
Ref: library/stat stat S_ISGID5276973
Ref: 1c2c5276973
Ref: library/stat stat S_ISVTX5277478
Ref: 1c2f5277478
Ref: library/stat stat S_IRWXU5277671
Ref: 1c305277671
Ref: library/stat stat S_IRUSR5277737
Ref: 1c315277737
Ref: library/stat stat S_IWUSR5277800
Ref: 1c325277800
Ref: library/stat stat S_IXUSR5277863
Ref: 1c335277863
Ref: library/stat stat S_IRWXG5277926
Ref: 1c345277926
Ref: library/stat stat S_IRGRP5277980
Ref: 1c355277980
Ref: library/stat stat S_IWGRP5278037
Ref: 1c365278037
Ref: library/stat stat S_IXGRP5278094
Ref: 1c2d5278094
Ref: library/stat stat S_IRWXO5278151
Ref: 1c375278151
Ref: library/stat stat S_IROTH5278229
Ref: 1c385278229
Ref: library/stat stat S_IWOTH5278292
Ref: 1c395278292
Ref: library/stat stat S_IXOTH5278355
Ref: 1c3a5278355
Ref: library/stat stat S_ENFMT5278418
Ref: 1c2e5278418
Ref: library/stat stat S_IREAD5278643
Ref: 1c3b5278643
Ref: library/stat stat S_IWRITE5278724
Ref: 1c3c5278724
Ref: library/stat stat S_IEXEC5278806
Ref: 1c3d5278806
Ref: library/stat stat UF_NODUMP5278966
Ref: 1c3e5278966
Ref: library/stat stat UF_IMMUTABLE5279022
Ref: 1c3f5279022
Ref: library/stat stat UF_APPEND5279084
Ref: 1c405279084
Ref: library/stat stat UF_OPAQUE5279143
Ref: 1c415279143
Ref: library/stat stat UF_NOUNLINK5279235
Ref: 1c425279235
Ref: library/stat stat UF_COMPRESSED5279305
Ref: 1c435279305
Ref: library/stat stat UF_HIDDEN5279391
Ref: 1c445279391
Ref: library/stat stat SF_ARCHIVED5279477
Ref: 1c455279477
Ref: library/stat stat SF_IMMUTABLE5279538
Ref: 1c465279538
Ref: library/stat stat SF_APPEND5279600
Ref: 1c475279600
Ref: library/stat stat SF_NOUNLINK5279659
Ref: 1c485279659
Ref: library/stat stat SF_SNAPSHOT5279729
Ref: 1c495279729
Ref: library/stat stat FILE_ATTRIBUTE_ARCHIVE5280090
Ref: 1c4a5280090
Ref: library/stat stat FILE_ATTRIBUTE_COMPRESSED5280130
Ref: 1c4b5280130
Ref: library/stat stat FILE_ATTRIBUTE_DEVICE5280173
Ref: 1c4c5280173
Ref: library/stat stat FILE_ATTRIBUTE_DIRECTORY5280212
Ref: 1c4d5280212
Ref: library/stat stat FILE_ATTRIBUTE_ENCRYPTED5280254
Ref: 1c4e5280254
Ref: library/stat stat FILE_ATTRIBUTE_HIDDEN5280296
Ref: 1c4f5280296
Ref: library/stat stat FILE_ATTRIBUTE_INTEGRITY_STREAM5280335
Ref: 1c505280335
Ref: library/stat stat FILE_ATTRIBUTE_NORMAL5280384
Ref: 1c515280384
Ref: library/stat stat FILE_ATTRIBUTE_NOT_CONTENT_INDEXED5280423
Ref: 1c525280423
Ref: library/stat stat FILE_ATTRIBUTE_NO_SCRUB_DATA5280475
Ref: 1c535280475
Ref: library/stat stat FILE_ATTRIBUTE_OFFLINE5280521
Ref: 1c545280521
Ref: library/stat stat FILE_ATTRIBUTE_READONLY5280561
Ref: 1c555280561
Ref: library/stat stat FILE_ATTRIBUTE_REPARSE_POINT5280602
Ref: 1c565280602
Ref: library/stat stat FILE_ATTRIBUTE_SPARSE_FILE5280648
Ref: 1c575280648
Ref: library/stat stat FILE_ATTRIBUTE_SYSTEM5280692
Ref: 1c585280692
Ref: library/stat stat FILE_ATTRIBUTE_TEMPORARY5280731
Ref: 1c595280731
Ref: library/stat stat FILE_ATTRIBUTE_VIRTUAL5280773
Ref: 1c5a5280773
Ref: library/stat stat IO_REPARSE_TAG_SYMLINK5281022
Ref: 1c5b5281022
Ref: library/stat stat IO_REPARSE_TAG_MOUNT_POINT5281062
Ref: 1c5c5281062
Ref: library/stat stat IO_REPARSE_TAG_APPEXECLINK5281106
Ref: 1c5d5281106
Ref: stat --- 解析 stat 结果-Footnote-15281211
Ref: stat --- 解析 stat 结果-Footnote-25281274
Node: filecmp --- 文件及目录的比较5281354
Ref: library/filecmp doc5281533
Ref: 1c5e5281533
Ref: library/filecmp filecmp-file-and-directory-comparisons5281533
Ref: 1c5f5281533
Ref: library/filecmp module-filecmp5281533
Ref: 7f5281533
Ref: library/filecmp filecmp cmp5281973
Ref: 1c605281973
Ref: library/filecmp filecmp cmpfiles5282628
Ref: 1c615282628
Ref: library/filecmp filecmp clear_cache5283546
Ref: 8505283546
Ref: filecmp --- 文件及目录的比较-Footnote-15283854
Node: dircmp 类5283920
Ref: library/filecmp dircmp-objects5284003
Ref: 1c625284003
Ref: library/filecmp the-dircmp-class5284003
Ref: 1c635284003
Ref: library/filecmp filecmp dircmp5284051
Ref: 8525284051
Ref: library/filecmp filecmp dircmp report5284557
Ref: 1c645284557
Ref: library/filecmp filecmp dircmp report_partial_closure5284687
Ref: 1c655284687
Ref: library/filecmp filecmp dircmp report_full_closure5284804
Ref: 1c665284804
Ref: library/filecmp filecmp dircmp left5285236
Ref: 1c675285236
Ref: library/filecmp filecmp dircmp right5285285
Ref: 1c685285285
Ref: library/filecmp filecmp dircmp left_list5285335
Ref: 1c695285335
Ref: library/filecmp filecmp dircmp right_list5285446
Ref: 1c6a5285446
Ref: library/filecmp filecmp dircmp common5285558
Ref: 1c6b5285558
Ref: library/filecmp filecmp dircmp left_only5285656
Ref: 1c6c5285656
Ref: library/filecmp filecmp dircmp right_only5285740
Ref: 1c6d5285740
Ref: library/filecmp filecmp dircmp common_dirs5285825
Ref: 1c6e5285825
Ref: library/filecmp filecmp dircmp common_files5285919
Ref: 1c6f5285919
Ref: library/filecmp filecmp dircmp common_funny5286011
Ref: 1c705286011
Ref: library/filecmp filecmp dircmp same_files5286172
Ref: 1c715286172
Ref: library/filecmp filecmp dircmp diff_files5286298
Ref: 1c725286298
Ref: library/filecmp filecmp dircmp funny_files5286441
Ref: 1c735286441
Ref: library/filecmp filecmp dircmp subdirs5286532
Ref: 1c745286532
Ref: library/filecmp filecmp DEFAULT_IGNORES5286671
Ref: 8515286671
Node: tempfile --- 生成临时文件和目录5287314
Ref: library/tempfile doc5287507
Ref: 1c755287507
Ref: library/tempfile module-tempfile5287507
Ref: 1045287507
Ref: library/tempfile tempfile-generate-temporary-files-and-directories5287507
Ref: 1c765287507
Ref: library/tempfile tempfile TemporaryFile5288525
Ref: 1c775288525
Ref: library/tempfile tempfile NamedTemporaryFile5290500
Ref: d515290500
Ref: library/tempfile tempfile SpooledTemporaryFile5291640
Ref: aae5291640
Ref: library/tempfile tempfile TemporaryDirectory5292823
Ref: bd05292823
Ref: library/tempfile tempfile mkstemp5293687
Ref: 1c785293687
Ref: library/tempfile tempfile mkdtemp5296501
Ref: 1c795296501
Ref: library/tempfile tempfile gettempdir5297494
Ref: 1c7f5297494
Ref: library/tempfile tempfile gettempdirb5298368
Ref: 1c815298368
Ref: library/tempfile tempfile gettempprefix5298505
Ref: 1c7d5298505
Ref: library/tempfile tempfile gettempprefixb5298629
Ref: 1c7e5298629
Ref: library/tempfile tempfile tempdir5299096
Ref: 1c805299096
Ref: tempfile --- 生成临时文件和目录-Footnote-15299568
Node: 例子<3>5299635
Ref: library/tempfile examples5299757
Ref: 1c825299757
Ref: library/tempfile tempfile-examples5299757
Ref: 1c7b5299757
Node: 已弃用的函数和变量5300659
Ref: library/tempfile deprecated-functions-and-variables5300781
Ref: 1c835300781
Ref: library/tempfile tempfile mktemp5301322
Ref: e955301322
Node: glob --- Unix 风格路径名模式扩展5302432
Ref: library/glob doc5302627
Ref: 1c845302627
Ref: library/glob glob-unix-style-pathname-pattern-expansion5302627
Ref: 1c855302627
Ref: library/glob module-glob5302627
Ref: 8a5302627
Ref: library/glob glob glob5303689
Ref: 5cf5303689
Ref: library/glob glob iglob5304877
Ref: 5d05304877
Ref: library/glob glob escape5305186
Ref: 8595305186
Ref: glob --- Unix 风格路径名模式扩展-Footnote-15306586
Node: fnmatch --- Unix 文件名模式匹配5306649
Ref: library/fnmatch doc5306839
Ref: 1c895306839
Ref: library/fnmatch fnmatch-unix-filename-pattern-matching5306839
Ref: 1c8a5306839
Ref: library/fnmatch module-fnmatch5306839
Ref: 815306839
Ref: library/fnmatch fnmatch fnmatch5308146
Ref: 1c865308146
Ref: library/fnmatch fnmatch fnmatchcase5308793
Ref: 1c8c5308793
Ref: library/fnmatch fnmatch filter5309040
Ref: 1c8b5309040
Ref: library/fnmatch fnmatch translate5309269
Ref: 104d5309269
Ref: fnmatch --- Unix 文件名模式匹配-Footnote-15309831
Node: linecache --- 随机读写文本行5309897
Ref: library/linecache doc5310075
Ref: 1c8d5310075
Ref: library/linecache linecache-random-access-to-text-lines5310075
Ref: 1c8e5310075
Ref: library/linecache module-linecache5310075
Ref: a95310075
Ref: library/linecache linecache getline5310809
Ref: 7125310809
Ref: library/linecache linecache clearcache5311559
Ref: 1c915311559
Ref: library/linecache linecache checkcache5311726
Ref: 1c925311726
Ref: library/linecache linecache lazycache5311997
Ref: 7115311997
Ref: linecache --- 随机读写文本行-Footnote-15312543
Ref: linecache --- 随机读写文本行-Footnote-25312611
Node: shutil --- 高阶文件操作5312660
Ref: library/shutil doc5312791
Ref: 1c935312791
Ref: library/shutil module-shutil5312791
Ref: ea5312791
Ref: library/shutil shutil-high-level-file-operations5312791
Ref: 1c945312791
Ref: shutil --- 高阶文件操作-Footnote-15313789
Node: 目录和文件操作5313854
Ref: library/shutil directory-and-files-operations5313962
Ref: 1c955313962
Ref: library/shutil file-operations5313962
Ref: 1c965313962
Ref: library/shutil shutil copyfileobj5314020
Ref: 25e5314020
Ref: library/shutil shutil copyfile5314531
Ref: 2595314531
Ref: library/shutil shutil SameFileError5316048
Ref: 8bc5316048
Ref: library/shutil shutil copymode5316200
Ref: 1c975316200
Ref: library/shutil shutil copystat5317052
Ref: a7f5317052
Ref: library/shutil shutil copy5319024
Ref: 25a5319024
Ref: library/shutil shutil copy25320403
Ref: 25b5320403
Ref: library/shutil shutil ignore_patterns5321832
Ref: 1c995321832
Ref: library/shutil shutil copytree5322124
Ref: 21b5322124
Ref: library/shutil shutil rmtree5325123
Ref: 21d5325123
Ref: library/shutil shutil rmtree avoids_symlink_attacks5326918
Ref: 1c9a5326918
Ref: library/shutil shutil move5327205
Ref: 25c5327205
Ref: library/shutil shutil disk_usage5329028
Ref: a7d5329028
Ref: library/shutil shutil chown5329498
Ref: a7e5329498
Ref: library/shutil shutil which5329975
Ref: eea5329975
Ref: library/shutil shutil Error5331273
Ref: 8bb5331273
Node: 依赖于具体平台的高效拷贝操作5331601
Ref: library/shutil platform-dependent-efficient-copy-operations5331725
Ref: 1c9b5331725
Ref: library/shutil shutil-platform-dependent-efficient-copy-operations5331725
Ref: 25f5331725
Ref: 依赖于具体平台的高效拷贝操作-Footnote-15332836
Ref: 依赖于具体平台的高效拷贝操作-Footnote-25332879
Node: copytree 示例5332927
Ref: library/shutil copytree-example5333073
Ref: 1c9c5333073
Ref: library/shutil shutil-copytree-example5333073
Ref: 1c9d5333073
Node: rmtree 示例5335112
Ref: library/shutil rmtree-example5335207
Ref: 1c9e5335207
Ref: library/shutil shutil-rmtree-example5335207
Ref: 1c9f5335207
Node: 归档操作5335749
Ref: library/shutil archiving-operations5335893
Ref: b9e5335893
Ref: library/shutil id15335893
Ref: 1ca05335893
Ref: library/shutil shutil make_archive5336171
Ref: 21c5336171
Ref: library/shutil shutil get_archive_formats5338164
Ref: 1ca25338164
Ref: library/shutil shutil register_archive_format5339017
Ref: 1ca35339017
Ref: library/shutil shutil unregister_archive_format5339866
Ref: 1ca45339866
Ref: library/shutil shutil unpack_archive5339975
Ref: b9f5339975
Ref: library/shutil shutil register_unpack_format5340918
Ref: 1ca55340918
Ref: library/shutil shutil unregister_unpack_format5341649
Ref: 1ca75341649
Ref: library/shutil shutil get_unpack_formats5341770
Ref: 1ca65341770
Ref: 归档操作-Footnote-15342703
Node: 归档程序示例5342752
Ref: library/shutil archiving-example5342865
Ref: 1ca85342865
Ref: library/shutil shutil-archiving-example5342865
Ref: 1ca95342865
Node: 使用 base_dir 的归档程序示例5343966
Ref: library/shutil archiving-example-with-base-dir5344079
Ref: 1caa5344079
Ref: library/shutil shutil-archiving-example-with-basedir5344079
Ref: 1ca15344079
Node: 查询输出终端的尺寸5345190
Ref: library/shutil querying-the-size-of-the-output-terminal5345304
Ref: 1cab5345304
Ref: library/shutil shutil get_terminal_size5345372
Ref: a525345372
Ref: 查询输出终端的尺寸-Footnote-15346755
Node: 数据持久化5346837
Ref: library/persistence doc5346965
Ref: 1cae5346965
Ref: library/persistence data-persistence5346965
Ref: 1caf5346965
Ref: library/persistence other-environment-variables5346965
Ref: 1cb05346965
Ref: library/persistence persistence5346965
Ref: 1cb15346965
Node: pickle --- Python 对象序列化5347908
Ref: library/pickle doc5348055
Ref: 1cb25348055
Ref: library/pickle module-pickle5348055
Ref: cb5348055
Ref: library/pickle pickle-python-object-serialization5348055
Ref: 1cb35348055
Ref: pickle --- Python 对象序列化-Footnote-15349690
Ref: pickle --- Python 对象序列化-Footnote-25349755
Node: 与其他 Python 模块间的关系5349818
Ref: library/pickle relationship-to-other-python-modules5349947
Ref: 1cb65349947
Node: 与 marshal 间的关系5350097
Ref: library/pickle comparison-with-marshal5350226
Ref: 1cb75350226
Node: 与 json 模块的比较5352097
Ref: library/pickle comparison-with-json5352226
Ref: 1cb55352226
Ref: library/pickle id25352226
Ref: 1cb85352226
Ref: 与 json 模块的比较-Footnote-15353334
Node: 数据流格式5353358
Ref: library/pickle data-stream-format5353508
Ref: 1cba5353508
Ref: library/pickle pickle-protocols5353508
Ref: 5775353508
Ref: 数据流格式-Footnote-15356157
Ref: 数据流格式-Footnote-25356206
Ref: 数据流格式-Footnote-35356255
Node: 模块接口5356304
Ref: library/pickle module-interface5356450
Ref: 1cbd5356450
Ref: library/pickle pickle HIGHEST_PROTOCOL5356863
Ref: e085356863
Ref: library/pickle pickle DEFAULT_PROTOCOL5357108
Ref: 1cc05357108
Ref: library/pickle pickle dump5357553
Ref: 1cbf5357553
Ref: library/pickle pickle dumps5358033
Ref: e075358033
Ref: library/pickle pickle load5358465
Ref: 5cb5358465
Ref: library/pickle pickle loads5359143
Ref: 5cc5359143
Ref: library/pickle pickle PickleError5359834
Ref: 1cc15359834
Ref: library/pickle pickle PicklingError5359952
Ref: 1cc25359952
Ref: library/pickle pickle UnpicklingError5360212
Ref: 1cc45360212
Ref: library/pickle pickle Pickler5360649
Ref: 20e5360649
Ref: library/pickle pickle Pickler dump5362289
Ref: 104c5362289
Ref: library/pickle pickle Pickler persistent_id5362450
Ref: 1cc75362450
Ref: library/pickle pickle Pickler dispatch_table5363291
Ref: a715363291
Ref: library/pickle pickle Pickler reducer_override5364335
Ref: 20f5364335
Ref: library/pickle pickle Pickler fast5364920
Ref: 1ccd5364920
Ref: library/pickle pickle Unpickler5365382
Ref: 1cbe5365382
Ref: library/pickle pickle Unpickler load5367417
Ref: 1ccf5367417
Ref: library/pickle pickle Unpickler persistent_load5367634
Ref: 1cc85367634
Ref: library/pickle pickle Unpickler find_class5368048
Ref: 1cd05368048
Ref: library/pickle pickle PickleBuffer5368735
Ref: 1cc55368735
Ref: library/pickle pickle PickleBuffer raw5369346
Ref: 1cd25369346
Ref: library/pickle pickle PickleBuffer release5369700
Ref: 1cd35369700
Node: 可以被封存/解封的对象5369791
Ref: library/pickle pickle-picklable5369937
Ref: 1cc35369937
Ref: library/pickle what-can-be-pickled-and-unpickled5369937
Ref: 1cd45369937
Ref: 可以被封存/解封的对象-Footnote-15372438
Ref: 可以被封存/解封的对象-Footnote-25372579
Node: 封存类实例5372704
Ref: library/pickle pickle-inst5372886
Ref: 1cb95372886
Ref: library/pickle pickling-class-instances5372886
Ref: 1cd55372886
Ref: library/pickle object __getnewargs_ex__5373693
Ref: 1cd65373693
Ref: library/pickle object __getnewargs__5374469
Ref: 6b75374469
Ref: library/pickle object __getstate__5375032
Ref: e095375032
Ref: library/pickle object __setstate__5375408
Ref: 19d5375408
Ref: library/pickle object __reduce__5377219
Ref: 19c5377219
Ref: library/pickle object __reduce_ex__5379720
Ref: 1a0c5379720
Ref: 封存类实例-Footnote-15380335
Node: 持久化外部对象5380443
Ref: library/pickle persistence-of-external-objects5380537
Ref: 1cd85380537
Ref: library/pickle pickle-persistent5380537
Ref: 1cc95380537
Ref: 持久化外部对象-Footnote-15385118
Node: Dispatch 表5385340
Ref: library/pickle dispatch-tables5385467
Ref: 1cd95385467
Ref: library/pickle pickle-dispatch5385467
Ref: 1ccb5385467
Node: 处理有状态的对象5386631
Ref: library/pickle handling-stateful-objects5386728
Ref: 1cda5386728
Ref: library/pickle pickle-state5386728
Ref: 1cd75386728
Node: 类型，函数和其他对象的自定义归约5388957
Ref: library/pickle custom-reduction-for-types-functions-and-other-objects5389123
Ref: 1cdb5389123
Ref: library/pickle reducer-override5389123
Ref: 1ccc5389123
Node: 外部缓冲区5391134
Ref: library/pickle out-of-band-buffers5391303
Ref: 1cdc5391303
Ref: library/pickle pickle-oob5391303
Ref: 1cc65391303
Node: 提供方 API5391963
Ref: library/pickle provider-api5392050
Ref: 1cdd5392050
Node: 使用方 API5392605
Ref: library/pickle consumer-api5392710
Ref: 1cde5392710
Node: 示例<4>5393905
Ref: library/pickle example5393988
Ref: 1cdf5393988
Ref: 示例<4>-Footnote-15396273
Node: 限制全局变量5396322
Ref: library/pickle pickle-restrict5396452
Ref: 1cd15396452
Ref: library/pickle restricting-globals5396452
Ref: 1ce05396452
Node: 性能<2>5399250
Ref: library/pickle performance5399374
Ref: 1ce15399374
Node: 例子<4>5399624
Ref: library/pickle examples5399721
Ref: 1ce25399721
Ref: library/pickle pickle-example5399721
Ref: 1ce35399721
Node: copyreg --- 注册配合 pickle 模块使用的函数5400971
Ref: library/copyreg doc5401160
Ref: 1ce45401160
Ref: library/copyreg copyreg-register-pickle-support-functions5401160
Ref: 1ce55401160
Ref: library/copyreg module-copyreg5401160
Ref: 275401160
Ref: library/copyreg copyreg constructor5401706
Ref: 1ce65401706
Ref: library/copyreg copyreg pickle5401924
Ref: 1cca5401924
Ref: copyreg --- 注册配合 pickle 模块使用的函数-Footnote-15402800
Node: 示例<5>5402866
Ref: library/copyreg example5402965
Ref: 1ce75402965
Node: shelve --- Python 对象持久化5403502
Ref: library/shelve doc5403699
Ref: 1ce85403699
Ref: library/shelve module-shelve5403699
Ref: e85403699
Ref: library/shelve shelve-python-object-persistence5403699
Ref: 1ce95403699
Ref: library/shelve shelve open5404238
Ref: 1cea5404238
Ref: library/shelve shelve Shelf sync5406324
Ref: 1cec5406324
Ref: library/shelve shelve Shelf close5406616
Ref: 1ced5406616
Ref: shelve --- Python 对象持久化-Footnote-15406959
Ref: shelve --- Python 对象持久化-Footnote-25407024
Node: 限制5407077
Ref: library/shelve restrictions5407171
Ref: 1cee5407171
Ref: library/shelve shelve Shelf5408084
Ref: 8b95408084
Ref: library/shelve shelve BsdDbShelf5409204
Ref: 1cef5409204
Ref: library/shelve shelve DbfilenameShelf5409870
Ref: 1cf05409870
Ref: 限制-Footnote-15410400
Node: 示例<6>5410453
Ref: library/shelve example5410547
Ref: 1cf15410547
Ref: library/shelve shelve-example5410547
Ref: 1ceb5410547
Node: marshal --- 内部 Python 对象序列化5412207
Ref: library/marshal doc5412382
Ref: 1cf25412382
Ref: library/marshal marshal-internal-python-object-serialization5412382
Ref: 1cf35412382
Ref: library/marshal module-marshal5412382
Ref: b15412382
Ref: library/marshal marshal dump5414537
Ref: 1cf45414537
Ref: library/marshal marshal load5415042
Ref: 10005415042
Ref: library/marshal marshal dumps5415584
Ref: 7a55415584
Ref: library/marshal marshal loads5415960
Ref: 1cf55415960
Ref: library/marshal marshal version5416262
Ref: 1cf65416262
Ref: marshal --- 内部 Python 对象序列化-Footnote-15416596
Node: dbm --- Unix "数据库" 接口5416921
Ref: library/dbm doc5417115
Ref: 1cf75417115
Ref: library/dbm dbm-interfaces-to-unix-databases5417115
Ref: 1cf85417115
Ref: library/dbm module-dbm5417115
Ref: 325417115
Ref: library/dbm dbm error5417609
Ref: 1cf95417609
Ref: library/dbm dbm whichdb5417861
Ref: 1cfa5417861
Ref: library/dbm dbm open5418385
Ref: 8395418385
Ref: dbm --- Unix "数据库" 接口-Footnote-15421668
Ref: dbm --- Unix "数据库" 接口-Footnote-25421739
Node: dbm gnu --- GNU 对 dbm 的重解析5421792
Ref: library/dbm dbm-gnu-gnu-s-reinterpretation-of-dbm5421939
Ref: 1cfb5421939
Ref: library/dbm module-dbm gnu5421939
Ref: 345421939
Ref: library/dbm dbm gnu error5422665
Ref: 2c65422665
Ref: library/dbm dbm gnu open5422859
Ref: 10415422859
Ref: library/dbm dbm gnu gdbm firstkey5424644
Ref: 1cfc5424644
Ref: library/dbm dbm gnu gdbm nextkey5424928
Ref: 1cfd5424928
Ref: library/dbm dbm gnu gdbm reorganize5425287
Ref: 1cfe5425287
Ref: library/dbm dbm gnu gdbm sync5425694
Ref: 1cff5425694
Ref: library/dbm dbm gnu gdbm close5425844
Ref: 1d005425844
Ref: dbm gnu --- GNU 对 dbm 的重解析-Footnote-15425954
Node: dbm ndbm --- 基于 ndbm 的接口5426020
Ref: library/dbm dbm-ndbm-interface-based-on-ndbm5426209
Ref: 1d015426209
Ref: library/dbm module-dbm ndbm5426209
Ref: 355426209
Ref: library/dbm dbm ndbm error5426880
Ref: 2c75426880
Ref: library/dbm dbm ndbm library5427076
Ref: 1d025427076
Ref: library/dbm dbm ndbm open5427158
Ref: 10425427158
Ref: library/dbm dbm ndbm ndbm close5428273
Ref: 1d035428273
Ref: dbm ndbm --- 基于 ndbm 的接口-Footnote-15428383
Node: dbm dumb --- 便携式 DBM 实现5428450
Ref: library/dbm dbm-dumb-portable-dbm-implementation5428594
Ref: 1d045428594
Ref: library/dbm module-dbm dumb5428594
Ref: 335428594
Ref: library/dbm dbm dumb error5429323
Ref: 2c55429323
Ref: library/dbm dbm dumb open5429513
Ref: 2c05429513
Ref: library/dbm dbm dumb dumbdbm sync5431255
Ref: 1d055431255
Ref: library/dbm dbm dumb dumbdbm close5431409
Ref: 1d065431409
Ref: dbm dumb --- 便携式 DBM 实现-Footnote-15431525
Node: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块5431592
Ref: library/sqlite3 doc5431736
Ref: 1d075431736
Ref: library/sqlite3 module-sqlite35431736
Ref: f35431736
Ref: library/sqlite3 sqlite3-db-api-2-0-interface-for-sqlite-databases5431736
Ref: 1d085431736
Ref: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块-Footnote-15435985
Ref: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块-Footnote-25436049
Ref: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块-Footnote-35436098
Node: 模块函数和常量5436147
Ref: library/sqlite3 module-functions-and-constants5436294
Ref: 1d0d5436294
Ref: library/sqlite3 sqlite3-module-contents5436294
Ref: 1d0e5436294
Ref: library/sqlite3 sqlite3 version5436350
Ref: 1d0f5436350
Ref: library/sqlite3 sqlite3 version_info5436466
Ref: 1d105436466
Ref: library/sqlite3 sqlite3 sqlite_version5436602
Ref: 1d115436602
Ref: library/sqlite3 sqlite3 sqlite_version_info5436704
Ref: 1d125436704
Ref: library/sqlite3 sqlite3 PARSE_DECLTYPES5436823
Ref: 1d135436823
Ref: library/sqlite3 sqlite3 PARSE_COLNAMES5437331
Ref: 1d145437331
Ref: library/sqlite3 sqlite3 connect5438174
Ref: 3e25438174
Ref: library/sqlite3 sqlite3 register_converter5441515
Ref: 1d175441515
Ref: library/sqlite3 sqlite3 register_adapter5441986
Ref: 1d195441986
Ref: library/sqlite3 sqlite3 complete_statement5442312
Ref: 1d1a5442312
Ref: library/sqlite3 sqlite3 enable_callback_tracebacks5443582
Ref: 1d1b5443582
Node: 连接对象（Connection）5443996
Ref: library/sqlite3 connection-objects5444165
Ref: 1d1c5444165
Ref: library/sqlite3 sqlite3-connection-objects5444165
Ref: 1d1d5444165
Ref: library/sqlite3 sqlite3 Connection5444236
Ref: 3e05444236
Ref: library/sqlite3 sqlite3 Connection isolation_level5444330
Ref: 1d165444330
Ref: library/sqlite3 sqlite3 Connection in_transaction5444601
Ref: 1d1f5444601
Ref: library/sqlite3 sqlite3 Connection cursor5444832
Ref: 1d205444832
Ref: library/sqlite3 sqlite3 Connection commit5445095
Ref: 1d215445095
Ref: library/sqlite3 sqlite3 Connection rollback5445450
Ref: 1d225445450
Ref: library/sqlite3 sqlite3 Connection close5445595
Ref: 1d235445595
Ref: library/sqlite3 sqlite3 Connection execute5445848
Ref: 1d245445848
Ref: library/sqlite3 sqlite3 Connection executemany5446166
Ref: 1d255446166
Ref: library/sqlite3 sqlite3 Connection executescript5446492
Ref: 1d275446492
Ref: library/sqlite3 sqlite3 Connection create_function5446815
Ref: fae5446815
Ref: library/sqlite3 sqlite3 Connection create_aggregate5448161
Ref: fad5448161
Ref: library/sqlite3 sqlite3 Connection create_collation5449492
Ref: 1d2a5449492
Ref: library/sqlite3 sqlite3 Connection interrupt5451098
Ref: 1d2b5451098
Ref: library/sqlite3 sqlite3 Connection set_authorizer5451377
Ref: faf5451377
Ref: library/sqlite3 sqlite3 Connection set_progress_handler5452592
Ref: fb05452592
Ref: library/sqlite3 sqlite3 Connection set_trace_callback5453158
Ref: a955453158
Ref: library/sqlite3 sqlite3 Connection enable_load_extension5453795
Ref: ba15453795
Ref: library/sqlite3 sqlite3 Connection load_extension5455519
Ref: ba25455519
Ref: library/sqlite3 sqlite3 Connection row_factory5455810
Ref: 1d2d5455810
Ref: library/sqlite3 sqlite3 Connection text_factory5457070
Ref: 1d2e5457070
Ref: library/sqlite3 sqlite3 Connection total_changes5458732
Ref: 1d2f5458732
Ref: library/sqlite3 sqlite3 Connection iterdump5458866
Ref: 1d305458866
Ref: library/sqlite3 sqlite3 Connection backup5459467
Ref: 3e15459467
Ref: 连接对象（Connection）-Footnote-15461670
Ref: 连接对象（Connection）-Footnote-25461716
Ref: 连接对象（Connection）-Footnote-35461998
Node: Cursor 对象5462280
Ref: library/sqlite3 cursor-objects5462437
Ref: 1d315462437
Ref: library/sqlite3 sqlite3-cursor-objects5462437
Ref: 1d325462437
Ref: library/sqlite3 sqlite3 Cursor5462482
Ref: 1d095462482
Ref: library/sqlite3 sqlite3 Cursor execute5462576
Ref: 1d0a5462576
Ref: library/sqlite3 sqlite3 Cursor executemany5463775
Ref: 1d265463775
Ref: library/sqlite3 sqlite3 Cursor executescript5465525
Ref: 1d285465525
Ref: library/sqlite3 sqlite3 Cursor fetchone5466621
Ref: 1d0b5466621
Ref: library/sqlite3 sqlite3 Cursor fetchmany5466805
Ref: 1d345466805
Ref: library/sqlite3 sqlite3 Cursor fetchall5467616
Ref: 1d0c5467616
Ref: library/sqlite3 sqlite3 Cursor close5467874
Ref: 1d355467874
Ref: library/sqlite3 sqlite3 Cursor rowcount5468154
Ref: 1d365468154
Ref: library/sqlite3 sqlite3 Cursor lastrowid5469038
Ref: 5875469038
Ref: library/sqlite3 sqlite3 Cursor arraysize5469641
Ref: 1d375469641
Ref: library/sqlite3 sqlite3 Cursor description5469841
Ref: 1d155469841
Ref: library/sqlite3 sqlite3 Cursor connection5470192
Ref: 1d385470192
Node: 行对象5470661
Ref: library/sqlite3 row-objects5470799
Ref: 1d395470799
Ref: library/sqlite3 sqlite3-row-objects5470799
Ref: 1d3a5470799
Ref: library/sqlite3 sqlite3 Row5470835
Ref: 7675470835
Ref: library/sqlite3 sqlite3 Row keys5471330
Ref: 1d3b5471330
Node: 异常<4>5472575
Ref: library/sqlite3 exceptions5472724
Ref: 1d3c5472724
Ref: library/sqlite3 sqlite3-exceptions5472724
Ref: 1d3d5472724
Ref: library/sqlite3 sqlite3 Warning5472755
Ref: 1d335472755
Ref: library/sqlite3 sqlite3 Error5472831
Ref: 1d3e5472831
Ref: library/sqlite3 sqlite3 DatabaseError5472949
Ref: 1d3f5472949
Ref: library/sqlite3 sqlite3 IntegrityError5473036
Ref: 1d405473036
Ref: library/sqlite3 sqlite3 ProgrammingError5473226
Ref: ee85473226
Ref: library/sqlite3 sqlite3 OperationalError5473451
Ref: 1d2c5473451
Ref: library/sqlite3 sqlite3 NotSupportedError5473731
Ref: 1d295473731
Node: SQLite 与 Python 类型5474021
Ref: library/sqlite3 sqlite-and-python-types5474173
Ref: 1d415474173
Ref: library/sqlite3 sqlite3-types5474173
Ref: 1d185474173
Node: 概述<7>5474429
Ref: library/sqlite3 introduction5474581
Ref: 1d425474581
Node: 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。5476456
Ref: library/sqlite3 using-adapters-to-store-additional-python-types-in-sqlite-databases5476661
Ref: 1d435476661
Node: 让对象自行适配5477231
Ref: library/sqlite3 letting-your-object-adapt-itself5477398
Ref: 1d445477398
Node: 注册可调用的适配器5478434
Ref: library/sqlite3 registering-an-adapter-callable5478601
Ref: 1d455478601
Node: 将SQLite 值转换为自定义Python 类型5479888
Ref: library/sqlite3 converting-sqlite-values-to-custom-python-types5480111
Ref: 1d465480111
Node: 默认适配器和转换器5482695
Ref: library/sqlite3 default-adapters-and-converters5482836
Ref: 1d475482836
Node: 控制事务5484336
Ref: library/sqlite3 controlling-transactions5484499
Ref: 1d485484499
Ref: library/sqlite3 sqlite3-controlling-transactions5484499
Ref: 1d1e5484499
Node: 有效使用 sqlite35486037
Ref: library/sqlite3 using-sqlite3-efficiently5486167
Ref: 1d495486167
Node: 使用快捷方式5486352
Ref: library/sqlite3 using-shortcut-methods5486475
Ref: 1d4a5486475
Node: 通过名称而不是索引访问索引5487677
Ref: library/sqlite3 accessing-columns-by-name-instead-of-by-index5487845
Ref: 1d4b5487845
Node: 使用连接作为上下文管理器5488524
Ref: library/sqlite3 using-the-connection-as-a-context-manager5488665
Ref: 1d4c5488665
Node: 数据压缩和存档5489727
Ref: library/archiving doc5489846
Ref: 1cbb5489846
Ref: library/archiving archiving5489846
Ref: 1d4d5489846
Ref: library/archiving data-compression-and-archiving5489846
Ref: 1d4e5489846
Node: zlib --- 与 gzip 兼容的压缩5490510
Ref: library/zlib doc5490643
Ref: 1d4f5490643
Ref: library/zlib module-zlib5490643
Ref: 1455490643
Ref: library/zlib zlib-compression-compatible-with-gzip5490643
Ref: 1d505490643
Ref: library/zlib zlib error5491477
Ref: 1d515491477
Ref: library/zlib zlib adler325491565
Ref: 1d525491565
Ref: library/zlib zlib compress5492258
Ref: 5c75492258
Ref: library/zlib zlib compressobj5492973
Ref: 1d535492973
Ref: library/zlib zlib crc325495295
Ref: 1d545495295
Ref: library/zlib zlib decompress5495903
Ref: 5c85495903
Ref: library/zlib decompress-wbits5496245
Ref: 1d555496245
Ref: library/zlib zlib decompressobj5497792
Ref: 1d565497792
Ref: library/zlib zlib Compress compress5498642
Ref: 1d575498642
Ref: library/zlib zlib Compress flush5498967
Ref: 1d585498967
Ref: library/zlib zlib Compress copy5499607
Ref: 1d595499607
Ref: library/zlib zlib Decompress unused_data5499913
Ref: 1d5a5499913
Ref: library/zlib zlib Decompress unconsumed_tail5500233
Ref: 1d5b5500233
Ref: library/zlib zlib Decompress eof5500592
Ref: ace5500592
Ref: library/zlib zlib Decompress decompress5500832
Ref: 1d5c5500832
Ref: library/zlib zlib Decompress flush5501760
Ref: 1d5d5501760
Ref: library/zlib zlib Decompress copy5502126
Ref: 1d5e5502126
Ref: library/zlib zlib ZLIB_VERSION5502528
Ref: 1d5f5502528
Ref: library/zlib zlib ZLIB_RUNTIME_VERSION5502771
Ref: acf5502771
Node: gzip --- 对 gzip 格式的支持5503146
Ref: library/gzip doc5503327
Ref: 1d605503327
Ref: library/gzip gzip-support-for-gzip-files5503327
Ref: 1d615503327
Ref: library/gzip module-gzip5503327
Ref: 8c5503327
Ref: library/gzip gzip open5504241
Ref: 1d625504241
Ref: library/gzip gzip BadGzipFile5505791
Ref: 1d35505791
Ref: library/gzip gzip GzipFile5506033
Ref: 6e65506033
Ref: library/gzip gzip GzipFile peek5508479
Ref: b905508479
Ref: library/gzip gzip GzipFile mtime5509003
Ref: 1d635509003
Ref: library/gzip gzip compress5510096
Ref: 1d25510096
Ref: library/gzip gzip decompress5510451
Ref: b915510451
Ref: gzip --- 对 gzip 格式的支持-Footnote-15510684
Node: 用法示例5510747
Ref: library/gzip examples-of-usage5510853
Ref: 1d685510853
Ref: library/gzip gzip-usage-examples5510853
Ref: 1d695510853
Node: 命令行界面5511678
Ref: library/gzip command-line-interface5511784
Ref: 1d6a5511784
Node: 命令行选项5512164
Ref: library/gzip command-line-options5512231
Ref: 1d6b5512231
Ref: library/gzip cmdoption-gzip-arg-file5512277
Ref: 1d6c5512277
Ref: library/gzip cmdoption-gzip-fast5512372
Ref: 1d6d5512372
Ref: library/gzip cmdoption-gzip-best5512459
Ref: 1d6e5512459
Ref: library/gzip cmdoption-gzip-d5512546
Ref: 1d6f5512546
Ref: library/gzip cmdoption-gzip-h5512616
Ref: 1d705512616
Node: bz2 --- 对 bzip2 压缩算法的支持5512674
Ref: library/bz2 doc5512852
Ref: 1d715512852
Ref: library/bz2 bz2-support-for-bzip2-compression5512852
Ref: 1d725512852
Ref: library/bz2 module-bz25512852
Ref: 145512852
Ref: bz2 --- 对 bzip2 压缩算法的支持-Footnote-15513717
Node: 文件压缩和解压5513779
Ref: library/bz2 de-compression-of-files5513906
Ref: 1d755513906
Ref: library/bz2 bz2 open5513962
Ref: 9de5513962
Ref: library/bz2 bz2 BZ2File5515399
Ref: 9395515399
Ref: library/bz2 bz2 BZ2File peek5516881
Ref: 1d765516881
Node: 增量压缩和解压5518196
Ref: library/bz2 incremental-de-compression5518359
Ref: 1d775518359
Ref: library/bz2 bz2 BZ2Compressor5518415
Ref: 1d735518415
Ref: library/bz2 bz2 BZ2Compressor compress5518745
Ref: 1d785518745
Ref: library/bz2 bz2 BZ2Compressor flush5519043
Ref: 1d795519043
Ref: library/bz2 bz2 BZ2Decompressor5519229
Ref: 1d745519229
Ref: library/bz2 bz2 BZ2Decompressor decompress5519768
Ref: 6ac5519768
Ref: library/bz2 bz2 BZ2Decompressor eof5521066
Ref: 1d7c5521066
Ref: library/bz2 bz2 BZ2Decompressor unused_data5521185
Ref: 1d7b5521185
Ref: library/bz2 bz2 BZ2Decompressor needs_input5521369
Ref: 1d7a5521369
Node: 一次性压缩或解压缩5521585
Ref: library/bz2 one-shot-de-compression5521742
Ref: 1d7d5521742
Ref: library/bz2 bz2 compress5521808
Ref: 18865521808
Ref: library/bz2 bz2 decompress5522115
Ref: 9df5522115
Node: 用法示例<2>5522443
Ref: library/bz2 bz2-usage-examples5522570
Ref: 1d7e5522570
Ref: library/bz2 examples-of-usage5522570
Ref: 1d7f5522570
Node: lzma --- 用 LZMA 算法压缩5525440
Ref: library/lzma doc5525612
Ref: 1d805525612
Ref: library/lzma lzma-compression-using-the-lzma-algorithm5525612
Ref: 1d815525612
Ref: library/lzma module-lzma5525612
Ref: ae5525612
Ref: library/lzma lzma LZMAError5526360
Ref: 1d825526360
Ref: lzma --- 用 LZMA 算法压缩-Footnote-15526712
Node: 读写压缩文件5526775
Ref: library/lzma reading-and-writing-compressed-files5526905
Ref: 1d835526905
Ref: library/lzma lzma open5526956
Ref: 1d845526956
Ref: library/lzma lzma LZMAFile5528729
Ref: 93a5528729
Ref: library/lzma lzma LZMAFile peek5530556
Ref: 1d875530556
Node: 在内存中压缩和解压缩数据5531353
Ref: library/lzma compressing-and-decompressing-data-in-memory5531501
Ref: 1d885531501
Ref: library/lzma lzma LZMACompressor5531582
Ref: 1d865531582
Ref: library/lzma lzma LZMACompressor compress5534354
Ref: 1d8b5534354
Ref: library/lzma lzma LZMACompressor flush5534802
Ref: 1d8c5534802
Ref: library/lzma lzma LZMADecompressor5535035
Ref: 1d855535035
Ref: library/lzma lzma LZMADecompressor decompress5536409
Ref: 71d5536409
Ref: library/lzma lzma LZMADecompressor check5537709
Ref: 1d905537709
Ref: library/lzma lzma LZMADecompressor eof5537913
Ref: 1d915537913
Ref: library/lzma lzma LZMADecompressor unused_data5538003
Ref: 1d8f5538003
Ref: library/lzma lzma LZMADecompressor needs_input5538169
Ref: 1d8e5538169
Ref: library/lzma lzma compress5538385
Ref: 1d895538385
Ref: library/lzma lzma decompress5538730
Ref: 1d8d5538730
Node: 杂项<2>5539204
Ref: library/lzma miscellaneous5539364
Ref: 1d925539364
Ref: library/lzma lzma is_check_supported5539395
Ref: 1d935539395
Node: 指定自定义的过滤器链5539733
Ref: library/lzma filter-chain-specs5539866
Ref: 1d8a5539866
Ref: library/lzma specifying-custom-filter-chains5539866
Ref: 1d945539866
Node: 例子<5>5542487
Ref: library/lzma examples5542602
Ref: 1d955542602
Node: zipfile --- 使用ZIP存档5543946
Ref: library/zipfile doc5544112
Ref: 1d965544112
Ref: library/zipfile module-zipfile5544112
Ref: 1435544112
Ref: library/zipfile zipfile-work-with-zip-archives5544112
Ref: 1d975544112
Ref: library/zipfile zipfile BadZipFile5544886
Ref: 1d985544886
Ref: library/zipfile zipfile BadZipfile5544990
Ref: 1d995544990
Ref: library/zipfile zipfile LargeZipFile5545130
Ref: 1d9a5545130
Ref: library/zipfile zipfile ZipInfo5545627
Ref: 5c35545627
Ref: library/zipfile zipfile is_zipfile5546213
Ref: cc25546213
Ref: library/zipfile zipfile ZIP_STORED5546519
Ref: 1da05546519
Ref: library/zipfile zipfile ZIP_DEFLATED5546603
Ref: 1da15546603
Ref: library/zipfile zipfile ZIP_BZIP25546721
Ref: 1da25546721
Ref: library/zipfile zipfile ZIP_LZMA5546850
Ref: 1da35546850
Ref: zipfile --- 使用ZIP存档-Footnote-15547731
Ref: zipfile --- 使用ZIP存档-Footnote-25547797
Ref: zipfile --- 使用ZIP存档-Footnote-35547865
Ref: zipfile --- 使用ZIP存档-Footnote-45547933
Node: ZipFile 对象5547966
Ref: library/zipfile id15548064
Ref: 1da45548064
Ref: library/zipfile zipfile-objects5548064
Ref: 1d9b5548064
Ref: library/zipfile zipfile ZipFile5548111
Ref: 4275548111
Ref: library/zipfile zipfile ZipFile close5551887
Ref: 1da55551887
Ref: library/zipfile zipfile ZipFile getinfo5552052
Ref: 1d9d5552052
Ref: library/zipfile zipfile ZipFile infolist5552316
Ref: 1d9e5552316
Ref: library/zipfile zipfile ZipFile namelist5552590
Ref: 1da65552590
Ref: library/zipfile zipfile ZipFile open5552675
Ref: 5c55552675
Ref: library/zipfile zipfile ZipFile extract5555027
Ref: 1daa5555027
Ref: library/zipfile zipfile ZipFile extractall5556399
Ref: 1dab5556399
Ref: library/zipfile zipfile ZipFile printdir5557367
Ref: 1dac5557367
Ref: library/zipfile zipfile ZipFile setpassword5557457
Ref: 1dad5557457
Ref: library/zipfile zipfile ZipFile read5557564
Ref: cc15557564
Ref: library/zipfile zipfile ZipFile testzip5558472
Ref: 1dae5558472
Ref: library/zipfile zipfile ZipFile write5558860
Ref: 6185558860
Ref: library/zipfile zipfile ZipFile writestr5559999
Ref: cc35559999
Ref: library/zipfile zipfile ZipFile filename5561622
Ref: 1daf5561622
Ref: library/zipfile zipfile ZipFile debug5561681
Ref: 1db05561681
Ref: library/zipfile zipfile ZipFile comment5561881
Ref: 1db15561881
Node: Path 对象5562181
Ref: library/zipfile id25562304
Ref: 1db25562304
Ref: library/zipfile path-objects5562304
Ref: 1d9c5562304
Ref: library/zipfile zipfile Path5562345
Ref: f1a5562345
Ref: library/zipfile zipfile Path name5562843
Ref: 1db35562843
Ref: library/zipfile zipfile Path open5562903
Ref: 1db45562903
Ref: library/zipfile zipfile Path iterdir5563288
Ref: 1db55563288
Ref: library/zipfile zipfile Path is_dir5563357
Ref: 1db65563357
Ref: library/zipfile zipfile Path is_file5563457
Ref: 1db75563457
Ref: library/zipfile zipfile Path exists5563558
Ref: 1db85563558
Ref: library/zipfile zipfile Path read_text5563684
Ref: 1db95563684
Ref: library/zipfile zipfile Path read_bytes5563892
Ref: 1dba5563892
Node: PyZipFile 对象5563964
Ref: library/zipfile id35564087
Ref: 1dbb5564087
Ref: library/zipfile pyzipfile-objects5564087
Ref: 1dbc5564087
Ref: library/zipfile zipfile PyZipFile5564270
Ref: 9235564270
Ref: library/zipfile zipfile PyZipFile writepy5564570
Ref: 9225564570
Node: ZipInfo 对象5567289
Ref: library/zipfile id45567419
Ref: 1dbd5567419
Ref: library/zipfile zipinfo-objects5567419
Ref: 1d9f5567419
Ref: library/zipfile zipfile ZipInfo from_file5567754
Ref: 5c25567754
Ref: library/zipfile zipfile ZipInfo is_dir5568745
Ref: 5c45568745
Ref: library/zipfile zipfile ZipInfo filename5568942
Ref: 1dbe5568942
Ref: library/zipfile zipfile ZipInfo date_time5569006
Ref: 1dbf5569006
Ref: library/zipfile zipfile ZipInfo compress_type5569757
Ref: 1dc05569757
Ref: library/zipfile zipfile ZipInfo comment5569829
Ref: 1dc15569829
Ref: library/zipfile zipfile ZipInfo extra5569928
Ref: 1dc25569928
Ref: library/zipfile zipfile ZipInfo create_system5570094
Ref: 1dc35570094
Ref: library/zipfile zipfile ZipInfo create_version5570171
Ref: 1dc45570171
Ref: library/zipfile zipfile ZipInfo extract_version5570256
Ref: 1dc55570256
Ref: library/zipfile zipfile ZipInfo reserved5570343
Ref: 1dc65570343
Ref: library/zipfile zipfile ZipInfo flag_bits5570395
Ref: 1dc75570395
Ref: library/zipfile zipfile ZipInfo volume5570449
Ref: 1dc85570449
Ref: library/zipfile zipfile ZipInfo internal_attr5570508
Ref: 1dc95570508
Ref: library/zipfile zipfile ZipInfo external_attr5570565
Ref: 1dca5570565
Ref: library/zipfile zipfile ZipInfo header_offset5570628
Ref: 1dcb5570628
Ref: library/zipfile zipfile ZipInfo CRC5570700
Ref: 1dcc5570700
Ref: library/zipfile zipfile ZipInfo compress_size5570760
Ref: 1dcd5570760
Ref: library/zipfile zipfile ZipInfo file_size5570829
Ref: 1da95570829
Ref: ZipInfo 对象-Footnote-15570930
Node: 命令行界面<2>5570998
Ref: library/zipfile command-line-interface5571130
Ref: 1dce5571130
Ref: library/zipfile zipfile-commandline5571130
Ref: 1dcf5571130
Node: 命令行选项<2>5571879
Ref: library/zipfile command-line-options5571952
Ref: 1dd35571952
Ref: library/zipfile cmdoption-zipfile-l5571998
Ref: 1dd25571998
Ref: library/zipfile cmdoption-zipfile-list5572029
Ref: 1dd45572029
Ref: library/zipfile cmdoption-zipfile-c5572111
Ref: 1dd05572111
Ref: library/zipfile cmdoption-zipfile-create5572166
Ref: 1dd55572166
Ref: library/zipfile cmdoption-zipfile-e5572267
Ref: 1dd15572267
Ref: library/zipfile cmdoption-zipfile-extract5572311
Ref: 1dd65572311
Ref: library/zipfile cmdoption-zipfile-t5572409
Ref: 1dd75572409
Ref: library/zipfile cmdoption-zipfile-test5572440
Ref: 1dd85572440
Node: 解压缩的障碍5572513
Ref: library/zipfile decompression-pitfalls5572622
Ref: 1dd95572622
Node: 由于文件本身5572862
Ref: library/zipfile from-file-itself5572962
Ref: 1dda5572962
Node: 文件系统限制5573135
Ref: library/zipfile file-system-limitations5573256
Ref: 1ddb5573256
Node: 资源限制5573512
Ref: library/zipfile resources-limitations5573621
Ref: 1ddc5573621
Ref: 资源限制-Footnote-15573864
Node: 中断5573911
Ref: library/zipfile interruption5574023
Ref: 1ddd5574023
Node: 提取的默认行为5574187
Ref: library/zipfile default-behaviors-of-extraction5574278
Ref: 1dde5574278
Node: tarfile --- 读写tar归档文件5574496
Ref: library/tarfile doc5574623
Ref: 1ddf5574623
Ref: library/tarfile module-tarfile5574623
Ref: 1025574623
Ref: library/tarfile pkzip-application-note5574623
Ref: 1de05574623
Ref: library/tarfile tarfile-read-and-write-tar-archive-files5574623
Ref: 1de15574623
Ref: library/tarfile tarfile open5575730
Ref: 76f5575730
Ref: library/tarfile tarfile is_tarfile5581739
Ref: 1de65581739
Ref: library/tarfile tarfile TarError5581949
Ref: 1de75581949
Ref: library/tarfile tarfile ReadError5582031
Ref: 1de35582031
Ref: library/tarfile tarfile CompressionError5582196
Ref: 1de45582196
Ref: library/tarfile tarfile StreamError5582328
Ref: 1de85582328
Ref: library/tarfile tarfile ExtractError5582443
Ref: 1de95582443
Ref: library/tarfile tarfile HeaderError5582623
Ref: 1dea5582623
Ref: library/tarfile tarfile ENCODING5582797
Ref: 1dec5582797
Ref: library/tarfile tarfile USTAR_FORMAT5583150
Ref: 1dee5583150
Ref: library/tarfile tarfile GNU_FORMAT5583221
Ref: 1def5583221
Ref: library/tarfile tarfile PAX_FORMAT5583277
Ref: 1df05583277
Ref: library/tarfile tarfile DEFAULT_FORMAT5583344
Ref: 1df15583344
Ref: tarfile --- 读写tar归档文件-Footnote-15584087
Ref: tarfile --- 读写tar归档文件-Footnote-25584153
Node: TarFile 对象5584225
Ref: library/tarfile id15584332
Ref: 1df25584332
Ref: library/tarfile tarfile-objects5584332
Ref: 1de25584332
Ref: library/tarfile tarfile TarFile5585144
Ref: b945585144
Ref: library/tarfile tarfile TarFile open5588444
Ref: 1df55588444
Ref: library/tarfile tarfile TarFile getmember5588607
Ref: 1df65588607
Ref: library/tarfile tarfile TarFile getmembers5588925
Ref: 7735588925
Ref: library/tarfile tarfile TarFile getnames5589094
Ref: 1df75589094
Ref: library/tarfile tarfile TarFile list5589254
Ref: 7725589254
Ref: library/tarfile tarfile TarFile next5589699
Ref: 1df85589699
Ref: library/tarfile tarfile TarFile extractall5589926
Ref: 7705589926
Ref: library/tarfile tarfile TarFile extract5591185
Ref: 7715591185
Ref: library/tarfile tarfile TarFile extractfile5592373
Ref: 1df95592373
Ref: library/tarfile tarfile TarFile add5592790
Ref: 4845592790
Ref: library/tarfile tarfile TarFile addfile5593670
Ref: 1dfa5593670
Ref: library/tarfile tarfile TarFile gettarinfo5594047
Ref: 1dfb5594047
Ref: library/tarfile tarfile TarFile close5595176
Ref: 1dff5595176
Ref: library/tarfile tarfile TarFile pax_headers5595324
Ref: 1e005595324
Node: TarInfo 对象5595417
Ref: library/tarfile id25595551
Ref: 1e015595551
Ref: library/tarfile tarinfo-objects5595551
Ref: 1df35595551
Ref: library/tarfile tarfile TarInfo5596030
Ref: b955596030
Ref: library/tarfile tarfile TarInfo frombuf5596115
Ref: 1deb5596115
Ref: library/tarfile tarfile TarInfo fromtarfile5596337
Ref: 1e025596337
Ref: library/tarfile tarfile TarInfo tobuf5596517
Ref: 1e035596517
Ref: library/tarfile tarfile TarInfo name5596925
Ref: 1dfe5596925
Ref: library/tarfile tarfile TarInfo size5596982
Ref: 1dfd5596982
Ref: library/tarfile tarfile TarInfo mtime5597042
Ref: 1e045597042
Ref: library/tarfile tarfile TarInfo mode5597100
Ref: 1e055597100
Ref: library/tarfile tarfile TarInfo type5597145
Ref: 1e065597145
Ref: library/tarfile tarfile TarInfo linkname5597513
Ref: 1e075597513
Ref: library/tarfile tarfile TarInfo uid5597681
Ref: 1e085597681
Ref: library/tarfile tarfile TarInfo gid5597758
Ref: 1e095597758
Ref: library/tarfile tarfile TarInfo uname5597835
Ref: 1e0a5597835
Ref: library/tarfile tarfile TarInfo gname5597881
Ref: 1e0b5597881
Ref: library/tarfile tarfile TarInfo pax_headers5597927
Ref: 1e0c5597927
Ref: library/tarfile tarfile TarInfo isfile5598097
Ref: 1e0d5598097
Ref: library/tarfile tarfile TarInfo isreg5598206
Ref: 1e0e5598206
Ref: library/tarfile tarfile TarInfo isdir5598278
Ref: 1e0f5598278
Ref: library/tarfile tarfile TarInfo issym5598359
Ref: 1e105598359
Ref: library/tarfile tarfile TarInfo islnk5598446
Ref: 1e115598446
Ref: library/tarfile tarfile TarInfo ischr5598530
Ref: 1e125598530
Ref: library/tarfile tarfile TarInfo isblk5598617
Ref: 1e135598617
Ref: library/tarfile tarfile TarInfo isfifo5598701
Ref: 1e145598701
Ref: library/tarfile tarfile TarInfo isdev5598784
Ref: 1e155598784
Node: 命令行界面<3>5598898
Ref: library/tarfile command-line-interface5599027
Ref: 1e165599027
Ref: library/tarfile tarfile-commandline5599027
Ref: 8f05599027
Node: 命令行选项<3>5599921
Ref: library/tarfile command-line-options5599994
Ref: 1e1a5599994
Ref: library/tarfile cmdoption-tarfile-l5600040
Ref: 1e195600040
Ref: library/tarfile cmdoption-tarfile-list5600071
Ref: 1e1b5600071
Ref: library/tarfile cmdoption-tarfile-c5600153
Ref: 1e175600153
Ref: library/tarfile cmdoption-tarfile-create5600208
Ref: 1e1c5600208
Ref: library/tarfile cmdoption-tarfile-e5600309
Ref: 1e185600309
Ref: library/tarfile cmdoption-tarfile-extract5600355
Ref: 1e1d5600355
Ref: library/tarfile cmdoption-tarfile-t5600487
Ref: 1e1e5600487
Ref: library/tarfile cmdoption-tarfile-test5600518
Ref: 1e1f5600518
Ref: library/tarfile cmdoption-tarfile-v5600591
Ref: 1e205600591
Node: 例子<6>5600658
Ref: library/tarfile examples5600796
Ref: 1e215600796
Ref: library/tarfile tar-examples5600796
Ref: 1de55600796
Node: 受支持的 tar 格式5602615
Ref: library/tarfile supported-tar-formats5602749
Ref: 1e225602749
Ref: library/tarfile tar-formats5602749
Ref: 1ded5602749
Node: Unicode 问题5604771
Ref: library/tarfile tar-unicode5604887
Ref: 1df45604887
Ref: library/tarfile unicode-issues5604887
Ref: 1e235604887
Node: 文件格式5606670
Ref: library/fileformats doc5606786
Ref: 1e255606786
Ref: library/fileformats file-formats5606786
Ref: 1e265606786
Ref: library/fileformats fileformats5606786
Ref: 1e275606786
Node: csv --- CSV 文件读写5607298
Ref: library/csv doc5607418
Ref: 1e285607418
Ref: library/csv csv-csv-file-reading-and-writing5607418
Ref: 1e295607418
Ref: library/csv module-csv5607418
Ref: 2a5607418
Ref: csv --- CSV 文件读写-Footnote-15609069
Ref: csv --- CSV 文件读写-Footnote-25609131
Node: 模块内容<3>5609180
Ref: library/csv csv-contents5609286
Ref: 1e2a5609286
Ref: library/csv module-contents5609286
Ref: 1e2b5609286
Ref: library/csv csv reader5609374
Ref: ecb5609374
Ref: library/csv csv writer5610899
Ref: e045610899
Ref: library/csv csv register_dialect5612488
Ref: 1e2f5612488
Ref: library/csv csv unregister_dialect5612951
Ref: 1e305612951
Ref: library/csv csv get_dialect5613145
Ref: 1e325613145
Ref: library/csv csv list_dialects5613379
Ref: 1e2d5613379
Ref: library/csv csv field_size_limit5613459
Ref: 1e335613459
Ref: library/csv csv DictReader5613687
Ref: 1be5613687
Ref: library/csv csv DictWriter5615204
Ref: b825615204
Ref: library/csv csv Dialect5616808
Ref: 1e2c5616808
Ref: library/csv csv excel5617006
Ref: 1e345617006
Ref: library/csv csv excel_tab5617168
Ref: 1e355617168
Ref: library/csv csv unix_dialect5617363
Ref: b815617363
Ref: library/csv csv Sniffer5617653
Ref: 1e365617653
Ref: library/csv csv Sniffer sniff5617796
Ref: 1e375617796
Ref: library/csv csv Sniffer has_header5618130
Ref: 1e385618130
Ref: library/csv csv QUOTE_ALL5618640
Ref: 1e395618640
Ref: library/csv csv QUOTE_MINIMAL5618736
Ref: 1e3a5618736
Ref: library/csv csv QUOTE_NONNUMERIC5618939
Ref: 1e3b5618939
Ref: library/csv csv QUOTE_NONE5619135
Ref: 1e3c5619135
Ref: library/csv csv Error5619562
Ref: 1e315619562
Ref: 模块内容<3>-Footnote-15619682
Ref: 模块内容<3>-Footnote-25620009
Node: 变种与格式参数5620336
Ref: library/csv csv-fmt-params5620464
Ref: 1e2e5620464
Ref: library/csv dialects-and-formatting-parameters5620464
Ref: 1e3d5620464
Ref: library/csv csv Dialect delimiter5621134
Ref: 1e3e5621134
Ref: library/csv csv Dialect doublequote5621233
Ref: 1e3f5621233
Ref: library/csv csv Dialect escapechar5621718
Ref: 1e405621718
Ref: library/csv csv Dialect lineterminator5622115
Ref: 1e415622115
Ref: library/csv csv Dialect quotechar5622417
Ref: 1e425622417
Ref: library/csv csv Dialect quoting5622605
Ref: 1e435622605
Ref: library/csv csv Dialect skipinitialspace5622857
Ref: 1e445622857
Ref: library/csv csv Dialect strict5623009
Ref: 1e455623009
Node: Reader 对象5623164
Ref: library/csv reader-objects5623290
Ref: 1e465623290
Ref: library/csv csv csvreader __next__5623459
Ref: 1e475623459
Ref: library/csv csv csvreader dialect5623836
Ref: 1e485623836
Ref: library/csv csv csvreader line_num5623919
Ref: 1e495623919
Ref: library/csv csv csvreader fieldnames5624115
Ref: 1e4a5624115
Node: Writer 对象5624306
Ref: library/csv writer-objects5624420
Ref: 1e4b5624420
Ref: library/csv csv csvwriter writerow5625018
Ref: 6cd5625018
Ref: library/csv csv csvwriter writerows5625305
Ref: 1e4c5625305
Ref: library/csv csv csvwriter dialect5625565
Ref: 1e4d5625565
Ref: library/csv csv DictWriter writeheader5625693
Ref: b835625693
Node: 例子<7>5626166
Ref: library/csv csv-examples5626258
Ref: 1e4e5626258
Ref: library/csv examples5626258
Ref: 1e4f5626258
Node: configparser --- 配置文件解析器5628173
Ref: library/configparser doc5628330
Ref: 1e505628330
Ref: library/configparser configparser-configuration-file-parser5628330
Ref: 1e515628330
Ref: library/configparser module-configparser5628330
Ref: 235628330
Ref: configparser --- 配置文件解析器-Footnote-15629459
Node: 快速起步5629530
Ref: library/configparser quick-start5629647
Ref: 1e525629647
Ref: 快速起步-Footnote-15632326
Ref: 快速起步-Footnote-25632498
Node: 支持的数据类型5632670
Ref: library/configparser supported-datatypes5632805
Ref: 1e565632805
Ref: 支持的数据类型-Footnote-15634121
Ref: 支持的数据类型-Footnote-25634293
Node: 回退值5634465
Ref: library/configparser fallback-values5634617
Ref: 1e5a5634617
Node: 受支持的 INI 文件结构5636026
Ref: library/configparser supported-ini-file-structure5636169
Ref: 1e535636169
Ref: 受支持的 INI 文件结构-Footnote-15638375
Ref: 受支持的 INI 文件结构-Footnote-25638547
Ref: 受支持的 INI 文件结构-Footnote-35638719
Ref: 受支持的 INI 文件结构-Footnote-45638891
Node: 值的插值5639063
Ref: library/configparser interpolation-of-values5639215
Ref: 1e5b5639215
Ref: library/configparser configparser BasicInterpolation5639402
Ref: 1e5c5639402
Ref: library/configparser configparser ExtendedInterpolation5640585
Ref: be45640585
Ref: 值的插值-Footnote-15641958
Node: 映射协议访问5642130
Ref: library/configparser mapping-protocol-access5642274
Ref: 1e545642274
Ref: 映射协议访问-Footnote-15644905
Node: 定制解析器行为5645077
Ref: library/configparser customizing-parser-behaviour5645226
Ref: 1e555645226
Ref: library/configparser configparser ConfigParser BOOLEAN_STATES5655217
Ref: 1e5e5655217
Ref: library/configparser configparser ConfigParser SECTCRE5657339
Ref: 1e5f5657339
Node: 旧式 API 示例5658521
Ref: library/configparser legacy-api-examples5658671
Ref: 1e605658671
Node: ConfigParser 对象5662420
Ref: library/configparser configparser-objects5662571
Ref: 1e615662571
Ref: library/configparser id115662571
Ref: 1e625662571
Ref: library/configparser configparser ConfigParser5662628
Ref: 4b25662628
Ref: library/configparser configparser ConfigParser defaults5666173
Ref: 1e655666173
Ref: library/configparser configparser ConfigParser sections5666263
Ref: 1e665666263
Ref: library/configparser configparser ConfigParser add_section5666377
Ref: c0c5666377
Ref: library/configparser configparser ConfigParser has_section5666845
Ref: 1e675666845
Ref: library/configparser configparser ConfigParser options5667003
Ref: 1e685667003
Ref: library/configparser configparser ConfigParser has_option5667101
Ref: 1e695667101
Ref: library/configparser configparser ConfigParser read5667394
Ref: 10b45667394
Ref: library/configparser configparser ConfigParser read_file5669078
Ref: 1e6a5669078
Ref: library/configparser configparser ConfigParser read_string5669547
Ref: 1e6c5669547
Ref: library/configparser configparser ConfigParser read_dict5669895
Ref: 1e645669895
Ref: library/configparser configparser ConfigParser get5670521
Ref: c0a5670521
Ref: library/configparser configparser ConfigParser getint5671412
Ref: 1e585671412
Ref: library/configparser configparser ConfigParser getfloat5671699
Ref: 1e595671699
Ref: library/configparser configparser ConfigParser getboolean5671990
Ref: 1e575671990
Ref: library/configparser configparser ConfigParser items5672691
Ref: 1e6d5672691
Ref: library/configparser configparser ConfigParser set5673311
Ref: c0b5673311
Ref: library/configparser configparser ConfigParser write5673614
Ref: 1e5d5673614
Ref: library/configparser configparser ConfigParser remove_option5674021
Ref: 1e6f5674021
Ref: library/configparser configparser ConfigParser remove_section5674341
Ref: 1e705674341
Ref: library/configparser configparser ConfigParser optionxform5674543
Ref: 1e635674543
Ref: library/configparser configparser ConfigParser readfp5675433
Ref: 1e6b5675433
Ref: library/configparser configparser MAX_INTERPOLATION_DEPTH5676177
Ref: 1e715676177
Node: RawConfigParser 对象5676383
Ref: library/configparser id135676526
Ref: 1e725676526
Ref: library/configparser rawconfigparser-objects5676526
Ref: 1e735676526
Ref: library/configparser configparser RawConfigParser5676591
Ref: 87a5676591
Ref: library/configparser configparser RawConfigParser add_section5677477
Ref: 1e745677477
Ref: library/configparser configparser RawConfigParser set5677914
Ref: 1e755677914
Node: 异常<5>5678670
Ref: library/configparser exceptions5678785
Ref: 1e765678785
Ref: library/configparser configparser Error5678818
Ref: 1e775678818
Ref: library/configparser configparser NoSectionError5678912
Ref: 1e6e5678912
Ref: library/configparser configparser DuplicateSectionError5679002
Ref: c0d5679002
Ref: library/configparser configparser DuplicateOptionError5679360
Ref: c0e5679360
Ref: library/configparser configparser NoOptionError5679676
Ref: 1e785679676
Ref: library/configparser configparser InterpolationError5679792
Ref: 1e795679792
Ref: library/configparser configparser InterpolationDepthError5679913
Ref: 1e7a5679913
Ref: library/configparser configparser InterpolationMissingOptionError5680141
Ref: 1e7b5680141
Ref: library/configparser configparser InterpolationSyntaxError5680323
Ref: 1e7c5680323
Ref: library/configparser configparser MissingSectionHeaderError5680513
Ref: 1e7d5680513
Ref: library/configparser configparser ParsingError5680638
Ref: 1e7e5680638
Node: netrc --- netrc 文件处理5680896
Ref: library/netrc doc5681066
Ref: 1e7f5681066
Ref: library/netrc module-netrc5681066
Ref: bf5681066
Ref: library/netrc netrc-netrc-file-processing5681066
Ref: 1e805681066
Ref: library/netrc netrc netrc5681365
Ref: 10b05681365
Ref: library/netrc netrc NetrcParseError5682517
Ref: 1e815682517
Ref: netrc --- netrc 文件处理-Footnote-15682891
Node: netrc 对象5682955
Ref: library/netrc id15683032
Ref: 1e825683032
Ref: library/netrc netrc-objects5683032
Ref: 1e835683032
Ref: library/netrc netrc netrc authenticators5683121
Ref: 1e845683121
Ref: library/netrc netrc netrc __repr__5683458
Ref: 1e855683458
Ref: library/netrc netrc netrc hosts5683682
Ref: 1e865683682
Ref: library/netrc netrc netrc macros5683874
Ref: 1e875683874
Node: xdrlib --- 编码与解码 XDR 数据5684230
Ref: library/xdrlib doc5684412
Ref: 1e885684412
Ref: library/xdrlib module-xdrlib5684412
Ref: 1335684412
Ref: library/xdrlib xdrlib-encode-and-decode-xdr-data5684412
Ref: 1e895684412
Ref: library/xdrlib xdrlib Packer5684989
Ref: 1e8a5684989
Ref: library/xdrlib xdrlib Unpacker5685152
Ref: 1e8b5685152
Ref: xdrlib --- 编码与解码 XDR 数据-Footnote-15685724
Ref: xdrlib --- 编码与解码 XDR 数据-Footnote-25685789
Ref: xdrlib --- 编码与解码 XDR 数据-Footnote-35685838
Ref: xdrlib --- 编码与解码 XDR 数据-Footnote-45685887
Ref: xdrlib --- 编码与解码 XDR 数据-Footnote-55685936
Node: Packer 对象5685985
Ref: library/xdrlib packer-objects5686096
Ref: 1e8c5686096
Ref: library/xdrlib xdr-packer-objects5686096
Ref: 1e8d5686096
Ref: library/xdrlib xdrlib Packer get_buffer5686188
Ref: 1e8e5686188
Ref: library/xdrlib xdrlib Packer reset5686283
Ref: 1e8f5686283
Ref: library/xdrlib xdrlib Packer pack_float5686716
Ref: 1e905686716
Ref: library/xdrlib xdrlib Packer pack_double5686797
Ref: 1e915686797
Ref: library/xdrlib xdrlib Packer pack_fstring5686950
Ref: 1e925686950
Ref: library/xdrlib xdrlib Packer pack_fopaque5687185
Ref: 1e935687185
Ref: library/xdrlib xdrlib Packer pack_string5687314
Ref: 1e945687314
Ref: library/xdrlib xdrlib Packer pack_opaque5687510
Ref: 1e955687510
Ref: library/xdrlib xdrlib Packer pack_bytes5687634
Ref: 1e965687634
Ref: library/xdrlib xdrlib Packer pack_list5687791
Ref: 1e975687791
Ref: library/xdrlib xdrlib Packer pack_farray5688413
Ref: 1e985688413
Ref: library/xdrlib xdrlib Packer pack_array5688770
Ref: 1e995688770
Node: Unpacker 对象5689003
Ref: library/xdrlib unpacker-objects5689132
Ref: 1e9a5689132
Ref: library/xdrlib xdr-unpacker-objects5689132
Ref: 1e9b5689132
Ref: library/xdrlib xdrlib Unpacker reset5689227
Ref: 1e9c5689227
Ref: library/xdrlib xdrlib Unpacker get_position5689319
Ref: 1e9d5689319
Ref: library/xdrlib xdrlib Unpacker set_position5689412
Ref: 1e9e5689412
Ref: library/xdrlib xdrlib Unpacker get_buffer5689608
Ref: 1e9f5689608
Ref: library/xdrlib xdrlib Unpacker done5689711
Ref: 1ea05689711
Ref: library/xdrlib xdrlib Unpacker unpack_float5690086
Ref: 1ea25690086
Ref: library/xdrlib xdrlib Unpacker unpack_double5690158
Ref: 1ea35690158
Ref: library/xdrlib xdrlib Unpacker unpack_fstring5690352
Ref: 1ea45690352
Ref: library/xdrlib xdrlib Unpacker unpack_fopaque5690535
Ref: 1ea55690535
Ref: library/xdrlib xdrlib Unpacker unpack_string5690664
Ref: 1ea65690664
Ref: library/xdrlib xdrlib Unpacker unpack_opaque5690870
Ref: 1ea75690870
Ref: library/xdrlib xdrlib Unpacker unpack_bytes5691010
Ref: 1ea85691010
Ref: library/xdrlib xdrlib Unpacker unpack_list5691177
Ref: 1ea95691177
Ref: library/xdrlib xdrlib Unpacker unpack_farray5691521
Ref: 1eaa5691521
Ref: library/xdrlib xdrlib Unpacker unpack_array5691799
Ref: 1eab5691799
Node: 异常<6>5692049
Ref: library/xdrlib exceptions5692156
Ref: 1eac5692156
Ref: library/xdrlib xdr-exceptions5692156
Ref: 1ead5692156
Ref: library/xdrlib xdrlib Error5692238
Ref: 1ea15692238
Ref: library/xdrlib xdrlib ConversionError5692385
Ref: 1eae5692385
Node: plistlib --- 生成与解析 Mac OS X plist 文件5692751
Ref: library/plistlib doc5692896
Ref: 1eaf5692896
Ref: library/plistlib module-plistlib5692896
Ref: d05692896
Ref: library/plistlib plistlib-generate-and-parse-mac-os-x-plist-files5692896
Ref: 1eb05692896
Ref: library/plistlib plistlib load5694279
Ref: 8945694279
Ref: library/plistlib plistlib loads5695349
Ref: 8965695349
Ref: library/plistlib plistlib dump5695587
Ref: 8955695587
Ref: library/plistlib plistlib dumps5696553
Ref: 8975696553
Ref: library/plistlib plistlib readPlist5696852
Ref: 4875696852
Ref: library/plistlib plistlib writePlist5697440
Ref: 94d5697440
Ref: library/plistlib plistlib readPlistFromBytes5697703
Ref: 4885697703
Ref: library/plistlib plistlib writePlistToBytes5698103
Ref: 94e5698103
Ref: library/plistlib plistlib Data5698324
Ref: 94f5698324
Ref: library/plistlib plistlib UID5698722
Ref: 2115698722
Ref: library/plistlib plistlib FMT_XML5699117
Ref: 8985699117
Ref: library/plistlib plistlib FMT_BINARY5699214
Ref: 8995699214
Ref: plistlib --- 生成与解析 Mac OS X plist 文件-Footnote-15699385
Ref: plistlib --- 生成与解析 Mac OS X plist 文件-Footnote-25699452
Node: 例子<8>5699551
Ref: library/plistlib examples5699647
Ref: 1eb15699647
Node: 加密服务5700386
Ref: library/crypto doc5700505
Ref: 1eb25700505
Ref: library/crypto crypto5700505
Ref: 1eb35700505
Ref: library/crypto cryptographic-services5700505
Ref: 1eb45700505
Node: hashlib --- 安全哈希与消息摘要5701008
Ref: library/hashlib doc5701141
Ref: 1eb55701141
Ref: library/hashlib hashlib-secure-hashes-and-message-digests5701141
Ref: 1eb65701141
Ref: library/hashlib module-hashlib5701141
Ref: 8d5701141
Ref: hashlib --- 安全哈希与消息摘要-Footnote-15702044
Ref: hashlib --- 安全哈希与消息摘要-Footnote-25702110
Node: 哈希算法5702159
Ref: library/hashlib hash-algorithms5702280
Ref: 1eb75702280
Ref: library/hashlib id15702280
Ref: 1eb85702280
Ref: library/hashlib hashlib new5704480
Ref: 1eb95704480
Ref: library/hashlib hashlib algorithms_guaranteed5705129
Ref: d045705129
Ref: library/hashlib hashlib algorithms_available5705459
Ref: d055705459
Ref: library/hashlib hashlib hash digest_size5705955
Ref: 1eba5705955
Ref: library/hashlib hashlib hash block_size5706040
Ref: 1ebb5706040
Ref: library/hashlib hashlib hash name5706161
Ref: 85b5706161
Ref: library/hashlib hashlib hash update5706559
Ref: 1ebc5706559
Ref: library/hashlib hashlib hash digest5706981
Ref: 1ebd5706981
Ref: library/hashlib hashlib hash hexdigest5707221
Ref: 1ebe5707221
Ref: library/hashlib hashlib hash copy5707490
Ref: 1ebf5707490
Node: SHAKE 可变长度摘要5707653
Ref: library/hashlib shake-variable-length-digests5707795
Ref: 1ec05707795
Ref: library/hashlib hashlib shake digest5708067
Ref: 10355708067
Ref: library/hashlib hashlib shake hexdigest5708283
Ref: 10365708283
Node: 密钥派生5708559
Ref: library/hashlib key-derivation5708695
Ref: 1ec15708695
Ref: library/hashlib hashlib pbkdf2_hmac5708965
Ref: 7ef5708965
Ref: library/hashlib hashlib scrypt5710315
Ref: 4da5710315
Ref: 密钥派生-Footnote-15711046
Ref: 密钥派生-Footnote-25711108
Node: BLAKE25711157
Ref: library/hashlib blake25711260
Ref: 1ec25711260
Ref: BLAKE2-Footnote-15711971
Ref: BLAKE2-Footnote-25711998
Ref: BLAKE2-Footnote-35712047
Node: 创建哈希对象5712125
Ref: library/hashlib creating-hash-objects5712204
Ref: 1ec35712204
Ref: library/hashlib hashlib blake2b5712312
Ref: 5555712312
Ref: library/hashlib hashlib blake2s5712514
Ref: 5565712514
Ref: 创建哈希对象-Footnote-15715521
Node: 常量<5>5715568
Ref: library/hashlib constants5715665
Ref: 1ec45715665
Ref: library/hashlib hashlib blake2b SALT_SIZE5715696
Ref: 1ec55715696
Ref: library/hashlib hashlib blake2s SALT_SIZE5715727
Ref: 1ec65715727
Ref: library/hashlib hashlib blake2b PERSON_SIZE5715814
Ref: 1ec75715814
Ref: library/hashlib hashlib blake2s PERSON_SIZE5715847
Ref: 1ec85715847
Ref: library/hashlib hashlib blake2b MAX_KEY_SIZE5715948
Ref: 1ec95715948
Ref: library/hashlib hashlib blake2s MAX_KEY_SIZE5715982
Ref: 1eca5715982
Ref: library/hashlib hashlib blake2b MAX_DIGEST_SIZE5716039
Ref: 1ecb5716039
Ref: library/hashlib hashlib blake2s MAX_DIGEST_SIZE5716076
Ref: 1ecc5716076
Node: 例子<9>5716160
Ref: library/hashlib examples5716251
Ref: 1ecd5716251
Node: 简单哈希5716406
Ref: library/hashlib simple-hashing5716500
Ref: 1ece5716500
Node: 使用不同的摘要大小5717928
Ref: library/hashlib using-different-digest-sizes5718043
Ref: 1ecf5718043
Node: 密钥哈希5719161
Ref: library/hashlib keyed-hashing5719276
Ref: 1ed05719276
Ref: 密钥哈希-Footnote-15721279
Node: 随机哈希5721357
Ref: library/hashlib randomized-hashing5721454
Ref: 1ed15721454
Ref: 随机哈希-Footnote-15723687
Ref: 随机哈希-Footnote-25723754
Node: 个性化5723785
Ref: library/hashlib personalization5723882
Ref: 1ed25723882
Ref: 个性化-Footnote-15725799
Node: 树形模式5725867
Ref: library/hashlib tree-mode5725943
Ref: 1ed35725943
Node: 开发人员5727191
Ref: library/hashlib credits5727264
Ref: 1ed45727264
Ref: 开发人员-Footnote-15729344
Ref: 开发人员-Footnote-25729371
Ref: 开发人员-Footnote-35729440
Ref: 开发人员-Footnote-45729474
Ref: 开发人员-Footnote-55729511
Ref: 开发人员-Footnote-65729554
Node: hmac --- 基于密钥的消息验证5729597
Ref: library/hmac doc5729793
Ref: 1ed55729793
Ref: library/hmac hmac-keyed-hashing-for-message-authentication5729793
Ref: 1ed65729793
Ref: library/hmac module-hmac5729793
Ref: 8f5729793
Ref: library/hmac hmac new5730047
Ref: 85d5730047
Ref: library/hmac hmac digest5730967
Ref: 3985730967
Ref: library/hmac hmac HMAC update5731553
Ref: 85e5731553
Ref: library/hmac hmac HMAC digest5731869
Ref: 1ed75731869
Ref: library/hmac hmac HMAC hexdigest5732410
Ref: 1ed85732410
Ref: library/hmac hmac HMAC copy5732938
Ref: 1ed95732938
Ref: library/hmac hmac HMAC digest_size5733132
Ref: 8615733132
Ref: library/hmac hmac HMAC block_size5733217
Ref: 85f5733217
Ref: library/hmac hmac HMAC name5733328
Ref: 8605733328
Ref: library/hmac hmac compare_digest5733498
Ref: a145733498
Ref: hmac --- 基于密钥的消息验证-Footnote-15734289
Ref: hmac --- 基于密钥的消息验证-Footnote-25734352
Node: secrets --- 生成安全随机数字用于管理密码5734401
Ref: library/secrets doc5734549
Ref: 1eda5734549
Ref: library/secrets module-secrets5734549
Ref: e55734549
Ref: library/secrets secrets-generate-secure-random-numbers-for-managing-secrets5734549
Ref: 1edb5734549
Ref: secrets --- 生成安全随机数字用于管理密码-Footnote-15735291
Ref: secrets --- 生成安全随机数字用于管理密码-Footnote-25735357
Node: 随机数5735406
Ref: library/secrets random-numbers5735527
Ref: 1edc5735527
Ref: library/secrets secrets SystemRandom5735673
Ref: 1edd5735673
Ref: library/secrets secrets choice5735853
Ref: 1ede5735853
Ref: library/secrets secrets randbelow5735953
Ref: 1edf5735953
Ref: library/secrets secrets randbits5736047
Ref: 1ee05736047
Node: 生成凭据5736141
Ref: library/secrets generating-tokens5736283
Ref: 1ee15736283
Ref: library/secrets secrets token_bytes5736471
Ref: 1ee25736471
Ref: library/secrets secrets token_hex5736764
Ref: 1ee35736764
Ref: library/secrets secrets token_urlsafe5737139
Ref: 1ee45737139
Node: 凭据应当使用多少个字节？5737586
Ref: library/secrets how-many-bytes-should-tokens-use5737671
Ref: 1ee55737671
Ref: 凭据应当使用多少个字节？-Footnote-15738657
Node: 其他功能5738714
Ref: library/secrets other-functions5738874
Ref: 1ee65738874
Ref: library/secrets secrets compare_digest5738915
Ref: 1ee75738915
Ref: 其他功能-Footnote-15739215
Node: 应用技巧与最佳实践5739272
Ref: library/secrets recipes-and-best-practices5739411
Ref: 1ee85739411
Ref: 应用技巧与最佳实践-Footnote-15741097
Ref: 应用技巧与最佳实践-Footnote-25741152
Node: 通用操作系统服务5741182
Ref: library/allos doc5741301
Ref: 1ee95741301
Ref: library/allos allos5741301
Ref: 1eea5741301
Ref: library/allos generic-operating-system-services5741301
Ref: 1eeb5741301
Node: os --- 多种操作系统接口5742978
Ref: library/os doc5743110
Ref: 1eec5743110
Ref: library/os module-os5743110
Ref: c55743110
Ref: library/os os-miscellaneous-operating-system-interfaces5743110
Ref: 1eed5743110
Ref: library/os os error5744766
Ref: 1eee5744766
Ref: library/os os name5744849
Ref: 1eef5744849
Ref: library/os os-filenames5745227
Ref: 1e245745227
Ref: os --- 多种操作系统接口-Footnote-15745502
Node: 文件名，命令行参数，以及环境变量。5745563
Ref: library/os file-names-command-line-arguments-and-environment-variables5745703
Ref: 1ef05745703
Ref: library/os filesystem-encoding5745703
Ref: 1ef15745703
Node: 进程参数5746621
Ref: library/os os-procinfo5746788
Ref: 1ef25746788
Ref: library/os process-parameters5746788
Ref: 1ef35746788
Ref: library/os os ctermid5746903
Ref: 1ef45746903
Ref: library/os os environ5747023
Ref: b3f5747023
Ref: library/os os environb5748754
Ref: b9c5748754
Ref: library/os os fsencode5749331
Ref: 4f75749331
Ref: library/os os fsdecode5749804
Ref: 4f65749804
Ref: library/os os fspath5750269
Ref: 4f55750269
Ref: library/os os PathLike5750702
Ref: 4f35750702
Ref: library/os os PathLike __fspath__5750909
Ref: 4f45750909
Ref: library/os os getenv5751169
Ref: 1ef75751169
Ref: library/os os getenvb5751657
Ref: b9b5751657
Ref: library/os os get_exec_path5752035
Ref: 1ef85752035
Ref: library/os os getegid5752372
Ref: 1ef95752372
Ref: library/os os geteuid5752528
Ref: 1efa5752528
Ref: library/os os getgid5752638
Ref: 1efb5752638
Ref: library/os os getgrouplist5752744
Ref: a635752744
Ref: library/os os getgroups5753086
Ref: 1efc5753086
Ref: library/os os getlogin5754219
Ref: 1efe5754219
Ref: library/os os getpgid5754620
Ref: 1f005754620
Ref: library/os os getpgrp5754817
Ref: 1f015754817
Ref: library/os os getpid5754915
Ref: 1f025754915
Ref: library/os os getppid5754968
Ref: 1f035754968
Ref: library/os os getpriority5755308
Ref: a4e5755308
Ref: library/os os PRIO_PROCESS5755881
Ref: 1f045755881
Ref: library/os os PRIO_PGRP5755909
Ref: 1f055755909
Ref: library/os os PRIO_USER5755934
Ref: 1f065755934
Ref: library/os os getresuid5756110
Ref: cb35756110
Ref: library/os os getresgid5756348
Ref: cb25756348
Ref: library/os os getuid5756577
Ref: 1f075756577
Ref: library/os os initgroups5756686
Ref: cb65756686
Ref: library/os os putenv5756921
Ref: 1ef55756921
Ref: library/os os setegid5757786
Ref: 1f095757786
Ref: library/os os seteuid5757897
Ref: 1f0a5757897
Ref: library/os os setgid5758011
Ref: 1f0b5758011
Ref: library/os os setgroups5758114
Ref: 1efd5758114
Ref: library/os os setpgrp5758674
Ref: 1f0c5758674
Ref: library/os os setpgid5758888
Ref: 1f0d5758888
Ref: library/os os setpriority5759100
Ref: a4f5759100
Ref: library/os os setregid5759785
Ref: 1f0e5759785
Ref: library/os os setresgid5759912
Ref: cb45759912
Ref: library/os os setresuid5760079
Ref: cb55760079
Ref: library/os os setreuid5760249
Ref: 1f0f5760249
Ref: library/os os getsid5760379
Ref: 1f105760379
Ref: library/os os setsid5760528
Ref: f3e5760528
Ref: library/os os setuid5760674
Ref: 1f115760674
Ref: library/os os strerror5760780
Ref: 1f125760780
Ref: library/os os supports_bytes_environ5760997
Ref: b9a5760997
Ref: library/os os umask5761182
Ref: 1f135761182
Ref: library/os os uname5761269
Ref: a655761269
Ref: library/os os unsetenv5762270
Ref: d4b5762270
Node: 创建文件对象5762944
Ref: library/os file-object-creation5763081
Ref: 1f155763081
Ref: library/os os-newstreams5763081
Ref: 1f165763081
Ref: library/os os fdopen5763268
Ref: 14415763268
Node: 文件描述符操作5763533
Ref: library/os file-descriptor-operations5763673
Ref: 1f175763673
Ref: library/os os-fd-ops5763673
Ref: 1f185763673
Ref: library/os os close5764413
Ref: 3da5764413
Ref: library/os os closerange5764838
Ref: 1f1b5764838
Ref: library/os os copy_file_range5765165
Ref: 1f1c5765165
Ref: library/os os device_encoding5766127
Ref: 1f1e5766127
Ref: library/os os dup5766286
Ref: fa45766286
Ref: library/os os dup25766652
Ref: 3c65766652
Ref: library/os os fchmod5767089
Ref: 6655767089
Ref: library/os os fchown5767482
Ref: 6665767482
Ref: library/os os fdatasync5767954
Ref: 6675767954
Ref: library/os os fpathconf5768168
Ref: 1f1f5768168
Ref: library/os os fstat5769116
Ref: 6685769116
Ref: library/os os fstatvfs5769366
Ref: 6695769366
Ref: library/os os fsync5769655
Ref: 66a5769655
Ref: library/os os ftruncate5770134
Ref: 66b5770134
Ref: library/os os get_blocking5770541
Ref: 72a5770541
Ref: library/os os isatty5770904
Ref: 1f215770904
Ref: library/os os lockf5771076
Ref: a625771076
Ref: library/os os F_LOCK5771617
Ref: 1f225771617
Ref: library/os os F_TLOCK5771639
Ref: 1f235771639
Ref: library/os os F_ULOCK5771662
Ref: 1f245771662
Ref: library/os os F_TEST5771685
Ref: 1f255771685
Ref: library/os os lseek5771846
Ref: a665771846
Ref: library/os os SEEK_SET5772312
Ref: d9c5772312
Ref: library/os os SEEK_CUR5772336
Ref: d9d5772336
Ref: library/os os SEEK_END5772360
Ref: d9e5772360
Ref: library/os os open5772589
Ref: 66e5772589
Ref: library/os os O_RDONLY5774510
Ref: 1f265774510
Ref: library/os os O_WRONLY5774534
Ref: 1f275774534
Ref: library/os os O_RDWR5774558
Ref: 1f295774558
Ref: library/os os O_APPEND5774580
Ref: 1f2a5774580
Ref: library/os os O_CREAT5774604
Ref: 1f2b5774604
Ref: library/os os O_EXCL5774627
Ref: 1c7c5774627
Ref: library/os os O_TRUNC5774649
Ref: 1f2c5774649
Ref: library/os os O_DSYNC5774728
Ref: 1f2d5774728
Ref: library/os os O_RSYNC5774751
Ref: 1f2e5774751
Ref: library/os os O_SYNC5774774
Ref: 1f2f5774774
Ref: library/os os O_NDELAY5774796
Ref: 1f305774796
Ref: library/os os O_NONBLOCK5774820
Ref: 72c5774820
Ref: library/os os O_NOCTTY5774846
Ref: 1f315774846
Ref: library/os os O_CLOEXEC5774870
Ref: 9cb5774870
Ref: library/os os O_BINARY5775009
Ref: 1f285775009
Ref: library/os os O_NOINHERIT5775033
Ref: 1f325775033
Ref: library/os os O_SHORT_LIVED5775060
Ref: 1f335775060
Ref: library/os os O_TEMPORARY5775089
Ref: 1f345775089
Ref: library/os os O_RANDOM5775116
Ref: 1f355775116
Ref: library/os os O_SEQUENTIAL5775140
Ref: 1f365775140
Ref: library/os os O_TEXT5775168
Ref: 1f375775168
Ref: library/os os O_ASYNC5775243
Ref: 1f385775243
Ref: library/os os O_DIRECT5775266
Ref: 1f395775266
Ref: library/os os O_DIRECTORY5775290
Ref: 1f3a5775290
Ref: library/os os O_NOFOLLOW5775317
Ref: 1f3b5775317
Ref: library/os os O_NOATIME5775343
Ref: 1f3c5775343
Ref: library/os os O_PATH5775368
Ref: 88c5775368
Ref: library/os os O_TMPFILE5775390
Ref: 88d5775390
Ref: library/os os O_SHLOCK5775415
Ref: d9f5775415
Ref: library/os os O_EXLOCK5775439
Ref: da05775439
Ref: library/os os openpty5775706
Ref: 1f3d5775706
Ref: library/os os pipe5776099
Ref: 1f1a5776099
Ref: library/os os pipe25776398
Ref: a365776398
Ref: library/os os posix_fallocate5776763
Ref: 6705776763
Ref: library/os os posix_fadvise5777015
Ref: 66f5777015
Ref: library/os os POSIX_FADV_NORMAL5777567
Ref: 1f3e5777567
Ref: library/os os POSIX_FADV_SEQUENTIAL5777600
Ref: 1f3f5777600
Ref: library/os os POSIX_FADV_RANDOM5777637
Ref: 1f405777637
Ref: library/os os POSIX_FADV_NOREUSE5777670
Ref: 1f415777670
Ref: library/os os POSIX_FADV_WILLNEED5777704
Ref: 1f425777704
Ref: library/os os POSIX_FADV_DONTNEED5777739
Ref: 1f435777739
Ref: library/os os pread5777955
Ref: 3c15777955
Ref: library/os os preadv5778336
Ref: 3bf5778336
Ref: library/os os RWF_NOWAIT5779411
Ref: 1f455779411
Ref: library/os os RWF_HIPRI5779884
Ref: 1f445779884
Ref: library/os os pwrite5780264
Ref: 3c45780264
Ref: library/os os pwritev5780546
Ref: 3c25780546
Ref: library/os os RWF_DSYNC5781581
Ref: 1f485781581
Ref: library/os os RWF_SYNC5781836
Ref: 1f495781836
Ref: library/os os read5782089
Ref: 6715782089
Ref: library/os os sendfile5782943
Ref: 3625782943
Ref: library/os os set_blocking5784243
Ref: 72b5784243
Ref: library/os os SF_NODISKIO5784624
Ref: 1f4a5784624
Ref: library/os os SF_MNOWAIT5784651
Ref: 1f4b5784651
Ref: library/os os SF_SYNC5784677
Ref: 1f4c5784677
Ref: library/os os readv5784853
Ref: 3c05784853
Ref: library/os os tcgetpgrp5785445
Ref: 1f4d5785445
Ref: library/os os tcsetpgrp5785656
Ref: 1f4e5785656
Ref: library/os os ttyname5785879
Ref: 1f4f5785879
Ref: library/os os write5786096
Ref: 6775786096
Ref: library/os os writev5786876
Ref: 3c35786876
Ref: 文件描述符操作-Footnote-15787541
Ref: 文件描述符操作-Footnote-25787590
Ref: 文件描述符操作-Footnote-35787653
Ref: 文件描述符操作-Footnote-45787702
Node: 查询终端的尺寸5787751
Ref: library/os querying-the-size-of-a-terminal5787863
Ref: 1f505787863
Ref: library/os terminal-size5787863
Ref: 1f515787863
Ref: library/os os get_terminal_size5787938
Ref: a515787938
Ref: library/os os terminal_size5788519
Ref: 1cad5788519
Ref: library/os os terminal_size columns5788621
Ref: 1f525788621
Ref: library/os os terminal_size lines5788701
Ref: 1f535788701
Node: 文件描述符的继承5788779
Ref: library/os fd-inheritance5788891
Ref: 8035788891
Ref: library/os inheritance-of-file-descriptors5788891
Ref: 1f545788891
Ref: library/os os get_inheritable5789824
Ref: 8045789824
Ref: library/os os set_inheritable5789943
Ref: 8055789943
Ref: library/os os get_handle_inheritable5790057
Ref: 8065790057
Ref: library/os os set_handle_inheritable5790219
Ref: 8075790219
Node: 文件和目录5790376
Ref: library/os files-and-directories5790510
Ref: 1f565790510
Ref: library/os os-file-dir5790510
Ref: 1ef65790510
Ref: library/os path-fd5790631
Ref: 3bd5790631
Ref: library/os dir-fd5791456
Ref: a375791456
Ref: library/os follow-symlinks5792141
Ref: a385792141
Ref: library/os os access5792677
Ref: a395792677
Ref: library/os os F_OK5795125
Ref: 1f575795125
Ref: library/os os R_OK5795145
Ref: 1f585795145
Ref: library/os os W_OK5795165
Ref: 1f595795165
Ref: library/os os X_OK5795185
Ref: 1f5a5795185
Ref: library/os os chdir5795353
Ref: a475795353
Ref: library/os os chflags5796026
Ref: a3a5796026
Ref: library/os os chmod5797082
Ref: a3b5797082
Ref: library/os os chown5798794
Ref: a3c5798794
Ref: library/os os chroot5799670
Ref: f515799670
Ref: library/os os fchdir5799861
Ref: 6645799861
Ref: library/os os getcwd5800200
Ref: fee5800200
Ref: library/os os getcwdb5800278
Ref: 2b95800278
Ref: library/os os lchflags5800580
Ref: 1f5c5800580
Ref: library/os os lchmod5801074
Ref: 10395801074
Ref: library/os os lchown5801641
Ref: 1f5d5801641
Ref: library/os os link5802145
Ref: a3d5802145
Ref: library/os os listdir5802933
Ref: a495802933
Ref: library/os os lstat5804302
Ref: 1f35804302
Ref: library/os os mkdir5805354
Ref: a3e5805354
Ref: library/os mkdir-modebits5805578
Ref: 1f5e5805578
Ref: library/os os makedirs5806384
Ref: 3c55806384
Ref: library/os os mkfifo5807902
Ref: 66c5807902
Ref: library/os os mknod5808780
Ref: 66d5808780
Ref: library/os os major5809646
Ref: 1f615809646
Ref: library/os os minor5809808
Ref: 1f625809808
Ref: library/os os makedev5809970
Ref: 1f605809970
Ref: library/os os pathconf5810073
Ref: a4a5810073
Ref: library/os os pathconf_names5811086
Ref: 1f635811086
Ref: library/os os readlink5811391
Ref: 1f45811391
Ref: library/os os remove5812766
Ref: a3f5812766
Ref: library/os os removedirs5813649
Ref: 1f645813649
Ref: library/os os rename5814471
Ref: a405814471
Ref: library/os os renames5815982
Ref: 1f655815982
Ref: library/os os replace5816630
Ref: a415816630
Ref: library/os os rmdir5817513
Ref: a425817513
Ref: library/os os scandir5818094
Ref: 2605818094
Ref: library/os os scandir close5819774
Ref: 5705819774
Ref: library/os os DirEntry5821177
Ref: 4f95821177
Ref: library/os os DirEntry name5822281
Ref: 1f685822281
Ref: library/os os DirEntry path5822674
Ref: 1f695822674
Ref: library/os os DirEntry inode5823403
Ref: 1f6a5823403
Ref: library/os os DirEntry is_dir5823793
Ref: 1f665823793
Ref: library/os os DirEntry is_file5825215
Ref: 65e5825215
Ref: library/os os DirEntry is_symlink5825930
Ref: 1f6b5825930
Ref: library/os os DirEntry stat5826758
Ref: 1f675826758
Ref: library/os os stat5828180
Ref: 1f25828180
Ref: library/os os stat_result5830532
Ref: 109a5830532
Ref: library/os os stat_result st_mode5830750
Ref: 1f6c5830750
Ref: library/os os stat_result st_ino5830860
Ref: 1f6d5830860
Ref: library/os os stat_result st_dev5831147
Ref: 1f6e5831147
Ref: library/os os stat_result st_nlink5831220
Ref: 1f6f5831220
Ref: library/os os stat_result st_uid5831280
Ref: 1f705831280
Ref: library/os os stat_result st_gid5831347
Ref: 1f715831347
Ref: library/os os stat_result st_size5831417
Ref: 1f725831417
Ref: library/os os stat_result st_atime5831653
Ref: 1f735831653
Ref: library/os os stat_result st_mtime5831734
Ref: 1d655831734
Ref: library/os os stat_result st_ctime5831815
Ref: 1f745831815
Ref: library/os os stat_result st_atime_ns5832011
Ref: 1f755832011
Ref: library/os os stat_result st_mtime_ns5832107
Ref: 1f765832107
Ref: library/os os stat_result st_ctime_ns5832203
Ref: 1f775832203
Ref: library/os os stat_result st_blocks5833471
Ref: 1f785833471
Ref: library/os os stat_result st_blksize5833645
Ref: 1f795833645
Ref: library/os os stat_result st_rdev5833843
Ref: 1f7a5833843
Ref: library/os os stat_result st_flags5833924
Ref: 1f7b5833924
Ref: library/os os stat_result st_gen5834131
Ref: 1f7c5834131
Ref: library/os os stat_result st_birthtime5834186
Ref: 1f7d5834186
Ref: library/os os stat_result st_fstype5834323
Ref: 3c75834323
Ref: library/os os stat_result st_rsize5834489
Ref: 1f7e5834489
Ref: library/os os stat_result st_creator5834552
Ref: 1f7f5834552
Ref: library/os os stat_result st_type5834614
Ref: 1f805834614
Ref: library/os os stat_result st_file_attributes5834722
Ref: 7295834722
Ref: library/os os stat_result st_reparse_tag5835029
Ref: 1f815835029
Ref: library/os os statvfs5836822
Ref: a4b5836822
Ref: library/os os supports_dir_fd5838767
Ref: a465838767
Ref: library/os os supports_effective_ids5839808
Ref: a4d5839808
Ref: library/os os supports_fd5840468
Ref: a4c5840468
Ref: library/os os supports_follow_symlinks5841223
Ref: 1c985841223
Ref: library/os os symlink5842255
Ref: a435842255
Ref: library/os os sync5843896
Ref: a615843896
Ref: library/os os truncate5844025
Ref: 72d5844025
Ref: library/os os unlink5844510
Ref: a445844510
Ref: library/os os utime5844994
Ref: a455844994
Ref: library/os os walk5846746
Ref: 65d5846746
Ref: library/os os fwalk5851346
Ref: 3bc5851346
Ref: library/os os memfd_create5853679
Ref: 1f15853679
Ref: library/os os MFD_CLOEXEC5854476
Ref: 1f825854476
Ref: library/os os MFD_ALLOW_SEALING5854503
Ref: 1f835854503
Ref: library/os os MFD_HUGETLB5854536
Ref: 1f845854536
Ref: library/os os MFD_HUGE_SHIFT5854563
Ref: 1f855854563
Ref: library/os os MFD_HUGE_MASK5854593
Ref: 1f865854593
Ref: library/os os MFD_HUGE_64KB5854622
Ref: 1f875854622
Ref: library/os os MFD_HUGE_512KB5854651
Ref: 1f885854651
Ref: library/os os MFD_HUGE_1MB5854681
Ref: 1f895854681
Ref: library/os os MFD_HUGE_2MB5854709
Ref: 1f8a5854709
Ref: library/os os MFD_HUGE_8MB5854737
Ref: 1f8b5854737
Ref: library/os os MFD_HUGE_16MB5854765
Ref: 1f8c5854765
Ref: library/os os MFD_HUGE_32MB5854794
Ref: 1f8d5854794
Ref: library/os os MFD_HUGE_256MB5854823
Ref: 1f8e5854823
Ref: library/os os MFD_HUGE_512MB5854853
Ref: 1f8f5854853
Ref: library/os os MFD_HUGE_1GB5854883
Ref: 1f905854883
Ref: library/os os MFD_HUGE_2GB5854911
Ref: 1f915854911
Ref: library/os os MFD_HUGE_16GB5854939
Ref: 1f925854939
Ref: 文件和目录-Footnote-15855293
Ref: 文件和目录-Footnote-25855342
Ref: 文件和目录-Footnote-35855385
Ref: 文件和目录-Footnote-45855464
Ref: 文件和目录-Footnote-55855545
Ref: 文件和目录-Footnote-65855634
Ref: 文件和目录-Footnote-75855723
Node: Linux 扩展属性5855781
Ref: library/os linux-extended-attributes5855851
Ref: 1f935855851
Ref: library/os os getxattr5855962
Ref: a535855962
Ref: library/os os listxattr5856611
Ref: a545856611
Ref: library/os os removexattr5857212
Ref: a555857212
Ref: library/os os setxattr5857863
Ref: a565857863
Ref: library/os os XATTR_SIZE_MAX5859039
Ref: 1f965859039
Ref: library/os os XATTR_CREATE5859154
Ref: 1f955859154
Ref: library/os os XATTR_REPLACE5859302
Ref: 1f945859302
Node: 进程管理5859451
Ref: library/os os-process5859579
Ref: 1f975859579
Ref: library/os process-management5859579
Ref: 1f985859579
Ref: library/os os abort5860121
Ref: 1f9a5860121
Ref: library/os os add_dll_directory5860506
Ref: 1c35860506
Ref: library/os os execl5861565
Ref: 1f995861565
Ref: library/os os execle5861610
Ref: 1f9b5861610
Ref: library/os os execlp5861661
Ref: 1f9c5861661
Ref: library/os os execlpe5861707
Ref: 1f9d5861707
Ref: library/os os execv5861759
Ref: 1f085861759
Ref: library/os os execve5861793
Ref: a485861793
Ref: library/os os execvp5861833
Ref: 1f9e5861833
Ref: library/os os execvpe5861868
Ref: 1f9f5861868
Ref: library/os os _exit5864590
Ref: 171e5864590
Ref: library/os os EX_OK5865288
Ref: 1fa05865288
Ref: library/os os EX_USAGE5865400
Ref: 1fa15865400
Ref: library/os os EX_DATAERR5865548
Ref: 1fa25865548
Ref: library/os os EX_NOINPUT5865665
Ref: 1fa35865665
Ref: library/os os EX_NOUSER5865800
Ref: 1fa45865800
Ref: library/os os EX_NOHOST5865919
Ref: 1fa55865919
Ref: library/os os EX_UNAVAILABLE5866038
Ref: 1fa65866038
Ref: library/os os EX_SOFTWARE5866162
Ref: 1fa75866162
Ref: library/os os EX_OSERR5866286
Ref: 1fa85866286
Ref: library/os os EX_OSFILE5866443
Ref: 1fa95866443
Ref: library/os os EX_CANTCREAT5866601
Ref: 1faa5866601
Ref: library/os os EX_IOERR5866738
Ref: 1fab5866738
Ref: library/os os EX_TEMPFAIL5866874
Ref: 1fac5866874
Ref: library/os os EX_PROTOCOL5867100
Ref: 1fad5867100
Ref: library/os os EX_NOPERM5867251
Ref: 1fae5867251
Ref: library/os os EX_CONFIG5867421
Ref: 1faf5867421
Ref: library/os os EX_NOTFOUND5867540
Ref: 1fb05867540
Ref: library/os os fork5867676
Ref: 9695867676
Ref: library/os os forkpty5868363
Ref: 1fb15868363
Ref: library/os os kill5869059
Ref: cfb5869059
Ref: library/os os killpg5869832
Ref: f3f5869832
Ref: library/os os nice5870057
Ref: a505870057
Ref: library/os os plock5870215
Ref: 1fb45870215
Ref: library/os os popen5870405
Ref: 2aa5870405
Ref: library/os os posix_spawn5871533
Ref: 2585871533
Ref: library/os os POSIX_SPAWN_OPEN5872529
Ref: 1fb55872529
Ref: library/os os POSIX_SPAWN_CLOSE5872704
Ref: 1fb65872704
Ref: library/os os POSIX_SPAWN_DUP25872829
Ref: 1fb75872829
Ref: library/os os posix_spawnp5875191
Ref: 10255875191
Ref: library/os os register_at_fork5875863
Ref: 3be5875863
Ref: library/os os spawnl5877180
Ref: 1f555877180
Ref: library/os os spawnle5877220
Ref: 1fb95877220
Ref: library/os os spawnlp5877266
Ref: 1fba5877266
Ref: library/os os spawnlpe5877307
Ref: 1fbb5877307
Ref: library/os os spawnv5877354
Ref: 1fbc5877354
Ref: library/os os spawnve5877395
Ref: 1fbd5877395
Ref: library/os os spawnvp5877442
Ref: 1fbe5877442
Ref: library/os os spawnvpe5877484
Ref: 1fbf5877484
Ref: library/os os P_NOWAIT5880822
Ref: 1fc05880822
Ref: library/os os P_NOWAITO5880846
Ref: 1fc25880846
Ref: library/os os P_WAIT5881135
Ref: 1fc15881135
Ref: library/os os P_DETACH5881473
Ref: 1fc35881473
Ref: library/os os P_OVERLAY5881497
Ref: 1fc45881497
Ref: library/os os startfile5881907
Ref: 1fc55881907
Ref: library/os os system5883476
Ref: dc95883476
Ref: library/os os times5884805
Ref: a645884805
Ref: library/os os wait5885826
Ref: 6745885826
Ref: library/os os waitid5886194
Ref: 6755886194
Ref: library/os os P_PID5886983
Ref: 1fc65886983
Ref: library/os os P_PGID5887004
Ref: 1fc75887004
Ref: library/os os P_ALL5887026
Ref: 1fc85887026
Ref: library/os os WEXITED5887214
Ref: 1fc95887214
Ref: library/os os WSTOPPED5887237
Ref: 1fca5887237
Ref: library/os os WNOWAIT5887261
Ref: 1fcd5887261
Ref: library/os os CLD_EXITED5887459
Ref: 1fce5887459
Ref: library/os os CLD_DUMPED5887485
Ref: 1fcf5887485
Ref: library/os os CLD_TRAPPED5887511
Ref: 1fd05887511
Ref: library/os os CLD_CONTINUED5887538
Ref: 1fd15887538
Ref: library/os os waitpid5887708
Ref: 6765887708
Ref: library/os os wait35889324
Ref: 6725889324
Ref: library/os os wait45889764
Ref: 6735889764
Ref: library/os os WNOHANG5890173
Ref: 1fcc5890173
Ref: library/os os WCONTINUED5890401
Ref: 1fcb5890401
Ref: library/os os WUNTRACED5890628
Ref: 1fd25890628
Ref: library/os os WCOREDUMP5891008
Ref: 1fd35891008
Ref: library/os os WIFCONTINUED5891254
Ref: 1fd55891254
Ref: library/os os WIFSTOPPED5891579
Ref: 1fd75891579
Ref: library/os os WIFSIGNALED5891982
Ref: 1fd45891982
Ref: library/os os WIFEXITED5892160
Ref: 1fd85892160
Ref: library/os os WEXITSTATUS5892436
Ref: 1fd95892436
Ref: library/os os WSTOPSIG5892620
Ref: 1fda5892620
Ref: library/os os WTERMSIG5892811
Ref: 1fdb5892811
Ref: 进程管理-Footnote-15893048
Ref: 进程管理-Footnote-25893120
Ref: 进程管理-Footnote-35893229
Node: 调度器接口5893278
Ref: library/os interface-to-the-scheduler5893409
Ref: 1fdc5893409
Ref: library/os os SCHED_OTHER5893716
Ref: 1fdd5893716
Ref: library/os os SCHED_BATCH5893772
Ref: 1fde5893772
Ref: library/os os SCHED_IDLE5893917
Ref: 1fdf5893917
Ref: library/os os SCHED_SPORADIC5894005
Ref: 1fe05894005
Ref: library/os os SCHED_FIFO5894088
Ref: 1fe15894088
Ref: library/os os SCHED_RR5894152
Ref: 1fe25894152
Ref: library/os os SCHED_RESET_ON_FORK5894211
Ref: 1fe35894211
Ref: library/os os sched_param5894430
Ref: 1fb85894430
Ref: library/os os sched_param sched_priority5894714
Ref: 1fe45894714
Ref: library/os os sched_get_priority_min5894798
Ref: a585894798
Ref: library/os os sched_get_priority_max5894942
Ref: a575894942
Ref: library/os os sched_setscheduler5895086
Ref: a5f5895086
Ref: library/os os sched_getscheduler5895353
Ref: a5b5895353
Ref: library/os os sched_setparam5895554
Ref: a5e5895554
Ref: library/os os sched_getparam5895765
Ref: a5a5895765
Ref: library/os os sched_rr_get_interval5895952
Ref: a5c5895952
Ref: library/os os sched_yield5896153
Ref: a605896153
Ref: library/os os sched_setaffinity5896210
Ref: a5d5896210
Ref: library/os os sched_getaffinity5896437
Ref: a595896437
Node: 其他系统信息5896575
Ref: library/os miscellaneous-system-information5896706
Ref: 1fe55896706
Ref: library/os os-path5896706
Ref: 1fe65896706
Ref: library/os os confstr5896759
Ref: 1fe75896759
Ref: library/os os confstr_names5897687
Ref: 1fe85897687
Ref: library/os os cpu_count5897963
Ref: 8885897963
Ref: library/os os getloadavg5898231
Ref: 1fe95898231
Ref: library/os os sysconf5898452
Ref: 1f465898452
Ref: library/os os sysconf_names5898786
Ref: 1fea5898786
Ref: library/os os curdir5899212
Ref: 1c025899212
Ref: library/os os pardir5899383
Ref: 1f5f5899383
Ref: library/os os sep5899552
Ref: 1c875899552
Ref: library/os os altsep5899907
Ref: 1c885899907
Ref: library/os os extsep5900176
Ref: 1feb5900176
Ref: library/os os pathsep5900329
Ref: 13655900329
Ref: library/os os defpath5900548
Ref: fef5900548
Ref: library/os os linesep5900758
Ref: 160c5900758
Ref: library/os os devnull5901152
Ref: 102a5901152
Ref: library/os os RTLD_LAZY5901319
Ref: a675901319
Ref: library/os os RTLD_NOW5901344
Ref: a685901344
Ref: library/os os RTLD_GLOBAL5901368
Ref: a695901368
Ref: library/os os RTLD_LOCAL5901395
Ref: a6a5901395
Ref: library/os os RTLD_NODELETE5901421
Ref: a6b5901421
Ref: library/os os RTLD_NOLOAD5901450
Ref: a6c5901450
Ref: library/os os RTLD_DEEPBIND5901477
Ref: a6d5901477
Node: 随机数<2>5901704
Ref: library/os random-numbers5901811
Ref: 1fec5901811
Ref: library/os os getrandom5901849
Ref: 5725901849
Ref: library/os os urandom5902640
Ref: 4d95902640
Ref: library/os os GRND_NONBLOCK5904428
Ref: 1fee5904428
Ref: library/os os GRND_RANDOM5904891
Ref: 1fed5904891
Ref: 随机数<2>-Footnote-15905111
Ref: 随机数<2>-Footnote-25905173
Node: io --- 处理流的核心工具5905222
Ref: library/io doc5905396
Ref: 1fef5905396
Ref: library/io io-core-tools-for-working-with-streams5905396
Ref: 1ff05905396
Ref: library/io module-io5905396
Ref: a25905396
Ref: io --- 处理流的核心工具-Footnote-15905702
Node: 概述<8>5905763
Ref: library/io io-overview5905867
Ref: 16075905867
Ref: library/io overview5905867
Ref: 1ff15905867
Node: 文本 I/O5907038
Ref: library/io text-i-o5907116
Ref: 1ff25907116
Node: 二进制 I/O5907733
Ref: library/io binary-i-o5907830
Ref: 1ff35907830
Node: 原始 I/O5908652
Ref: library/io raw-i-o5908730
Ref: 1ff45908730
Node: 高阶模块接口5909138
Ref: library/io high-level-module-interface5909269
Ref: 1ff55909269
Ref: library/io io DEFAULT_BUFFER_SIZE5909320
Ref: 16095909320
Ref: library/io io open5909549
Ref: 6635909549
Ref: library/io io open_code5909851
Ref: f325909851
Ref: library/io io BlockingIOError5910486
Ref: 1ff75910486
Ref: library/io io UnsupportedOperation5910596
Ref: 1ff85910596
Node: 类的层次结构5910891
Ref: library/io class-hierarchy5911022
Ref: 1ff95911022
Node: I/O 基类5915206
Ref: library/io i-o-base-classes5915296
Ref: 1ffb5915296
Ref: library/io io IOBase5915335
Ref: 1dc5915335
Ref: library/io io IOBase close5917028
Ref: 101e5917028
Ref: library/io io IOBase closed5917373
Ref: 101f5917373
Ref: library/io io IOBase fileno5917448
Ref: 1f195917448
Ref: library/io io IOBase flush5917641
Ref: 1ffc5917641
Ref: library/io io IOBase isatty5917770
Ref: 160a5917770
Ref: library/io io IOBase readable5917895
Ref: 1ffd5917895
Ref: library/io io IOBase readline5918077
Ref: 17135918077
Ref: library/io io IOBase readlines5918438
Ref: 17a05918438
Ref: library/io io IOBase seek5918872
Ref: 1da75918872
Ref: library/io io IOBase seekable5919753
Ref: 1ffe5919753
Ref: library/io io IOBase tell5919991
Ref: 1da85919991
Ref: library/io io IOBase truncate5920056
Ref: cad5920056
Ref: library/io io IOBase writable5920573
Ref: 1fff5920573
Ref: library/io io IOBase writelines5920768
Ref: 17a15920768
Ref: library/io io IOBase __del__5920946
Ref: 20005920946
Ref: library/io io RawIOBase5921142
Ref: a1b5921142
Ref: library/io io RawIOBase read5921599
Ref: 70b5921599
Ref: library/io io RawIOBase readall5922270
Ref: 20015922270
Ref: library/io io RawIOBase readinto5922402
Ref: 70c5922402
Ref: library/io io RawIOBase write5922732
Ref: 20025922732
Ref: library/io io BufferedIOBase5923282
Ref: 5915923282
Ref: library/io io BufferedIOBase raw5924469
Ref: 20045924469
Ref: library/io io BufferedIOBase detach5924708
Ref: 20055924708
Ref: library/io io BufferedIOBase read5925090
Ref: 1d675925090
Ref: library/io io BufferedIOBase read15925817
Ref: 1d665925817
Ref: library/io io BufferedIOBase readinto5926267
Ref: 20035926267
Ref: library/io io BufferedIOBase readinto15926762
Ref: 70a5926762
Ref: library/io io BufferedIOBase write5927215
Ref: 5925927215
Node: 原始文件 I/O5927933
Ref: library/io raw-file-i-o5928041
Ref: 20065928041
Ref: library/io io FileIO5928090
Ref: cac5928090
Ref: library/io io FileIO mode5930315
Ref: 20075930315
Ref: library/io io FileIO name5930383
Ref: 1dfc5930383
Node: 缓冲流5930505
Ref: library/io buffered-streams5930616
Ref: 20085930616
Ref: library/io io BytesIO5930737
Ref: 7a45930737
Ref: library/io io BytesIO getbuffer5931195
Ref: b755931195
Ref: library/io io BytesIO getvalue5931725
Ref: 1d645931725
Ref: library/io io BytesIO read15931824
Ref: 20095931824
Ref: library/io io BytesIO readinto15932000
Ref: 200a5932000
Ref: library/io io BufferedReader5932143
Ref: b925932143
Ref: library/io io BufferedReader peek5932899
Ref: 200b5932899
Ref: library/io io BufferedReader read5933109
Ref: 200c5933109
Ref: library/io io BufferedReader read15933307
Ref: 200d5933307
Ref: library/io io BufferedWriter5933635
Ref: 160d5933635
Ref: library/io io BufferedWriter flush5934660
Ref: 200e5934660
Ref: library/io io BufferedWriter write5934844
Ref: 200f5934844
Ref: library/io io BufferedRandom5935104
Ref: 160e5935104
Ref: library/io io BufferedRWPair5935698
Ref: 1ffa5935698
Node: 文本 I/O<2>5936601
Ref: library/io id15936687
Ref: 20105936687
Ref: library/io io TextIOBase5936728
Ref: c415936728
Ref: library/io io TextIOBase encoding5937031
Ref: 20115937031
Ref: library/io io TextIOBase errors5937183
Ref: 20125937183
Ref: library/io io TextIOBase newlines5937259
Ref: 20135937259
Ref: library/io io TextIOBase buffer5937483
Ref: c425937483
Ref: library/io io TextIOBase detach5937744
Ref: 20145937744
Ref: library/io io TextIOBase read5938208
Ref: 20155938208
Ref: library/io io TextIOBase readline5938409
Ref: 1c0e5938409
Ref: library/io io TextIOBase seek5938658
Ref: 20165938658
Ref: library/io io TextIOBase tell5939552
Ref: 20175939552
Ref: library/io io TextIOBase write5939725
Ref: 20185939725
Ref: library/io io TextIOWrapper5939824
Ref: 5fc5939824
Ref: library/io io TextIOWrapper line_buffering5943044
Ref: 201a5943044
Ref: library/io io TextIOWrapper write_through5943113
Ref: 201b5943113
Ref: library/io io TextIOWrapper reconfigure5943240
Ref: 3a55943240
Ref: library/io io StringIO5943960
Ref: 8365943960
Ref: library/io io StringIO getvalue5944834
Ref: 201c5944834
Ref: library/io io IncrementalNewlineDecoder5945472
Ref: 201d5945472
Node: 性能<3>5945668
Ref: library/io performance5945772
Ref: 201e5945772
Node: 二进制 I/O<2>5945978
Ref: library/io id25946062
Ref: 201f5946062
Node: 文本 I/O<3>5946654
Ref: library/io id35946759
Ref: 20205946759
Node: 多线程<3>5947278
Ref: library/io multi-threading5947379
Ref: 20215947379
Node: 可重入性5947877
Ref: library/io reentrancy5947956
Ref: 20225947956
Node: time --- 时间的访问和转换5948681
Ref: library/time doc5948882
Ref: 20235948882
Ref: library/time module-time5948882
Ref: 10b5948882
Ref: library/time time-time-access-and-conversions5948882
Ref: 20245948882
Ref: library/time epoch5949467
Ref: 20255949467
Ref: time --- 时间的访问和转换-Footnote-15953498
Node: 函数<2>5953548
Ref: library/time functions5953651
Ref: 20265953651
Ref: library/time time-functions5953651
Ref: 20275953651
Ref: library/time time asctime5953682
Ref: b6b5953682
Ref: library/time time pthread_getcpuclockid5954318
Ref: 4035954318
Ref: library/time time clock_getres5954895
Ref: aba5954895
Ref: library/time time clock_gettime5955147
Ref: abb5955147
Ref: library/time time clock_gettime_ns5955393
Ref: 3275955393
Ref: library/time time clock_settime5955581
Ref: library/time time clock_settime_ns5955825
Ref: 3285955825
Ref: library/time time ctime5956017
Ref: 18c75956017
Ref: library/time time get_clock_info5956574
Ref: ab95956574
Ref: library/time time gmtime5957632
Ref: b475957632
Ref: library/time time localtime5958098
Ref: f5d5958098
Ref: library/time time mktime5958383
Ref: b6c5958383
Ref: library/time time monotonic5958997
Ref: 7785958997
Ref: library/time time monotonic_ns5959402
Ref: 3295959402
Ref: library/time time perf_counter5959544
Ref: 2ab5959544
Ref: library/time time perf_counter_ns5959950
Ref: 32a5959950
Ref: library/time time process_time5960095
Ref: 2ac5960095
Ref: library/time time process_time_ns5960461
Ref: 32b5960461
Ref: library/time time sleep5960606
Ref: 6895960606
Ref: library/time time strftime5961200
Ref: b6d5961200
Ref: library/time time strptime5967895
Ref: d995967895
Ref: library/time time struct_time5969365
Ref: 5a25969365
Ref: library/time time time5972077
Ref: 3265972077
Ref: library/time time thread_time5973213
Ref: 4015973213
Ref: library/time time thread_time_ns5973688
Ref: 4025973688
Ref: library/time time time_ns5973825
Ref: 32c5973825
Ref: library/time time tzset5974018
Ref: 202b5974018
Ref: 函数<2>-Footnote-15977571
Ref: 函数<2>-Footnote-25977620
Ref: 函数<2>-Footnote-35977670
Ref: 函数<2>-Footnote-45977719
Ref: 函数<2>-Footnote-55978311
Ref: 函数<2>-Footnote-65978361
Node: Clock ID 常量5978409
Ref: library/time clock-id-constants5978533
Ref: 202c5978533
Ref: library/time time-clock-id-constants5978533
Ref: 20295978533
Ref: library/time time CLOCK_BOOTTIME5978675
Ref: 3fd5978675
Ref: library/time time CLOCK_HIGHRES5979118
Ref: 202d5979118
Ref: library/time time CLOCK_MONOTONIC5979411
Ref: 3fe5979411
Ref: library/time time CLOCK_MONOTONIC_RAW5979595
Ref: 202e5979595
Ref: library/time time CLOCK_PROCESS_CPUTIME_ID5979870
Ref: 202f5979870
Ref: library/time time CLOCK_PROF5980027
Ref: 3ff5980027
Ref: library/time time CLOCK_THREAD_CPUTIME_ID5980204
Ref: 20305980204
Ref: library/time time CLOCK_UPTIME5980345
Ref: 4005980345
Ref: library/time time CLOCK_UPTIME_RAW5980611
Ref: 23a5980611
Ref: library/time time CLOCK_REALTIME5980973
Ref: 202a5980973
Node: 时区常量5981145
Ref: library/time time-timezone-constants5981251
Ref: 20315981251
Ref: library/time timezone-constants5981251
Ref: 20325981251
Ref: library/time time altzone5981292
Ref: 20335981292
Ref: library/time time daylight5981568
Ref: 20345981568
Ref: library/time time timezone5981666
Ref: 20355981666
Ref: library/time time tzname5981851
Ref: 20365981851
Node: argparse --- 命令行选项、参数和子命令解析器5982928
Ref: library/argparse doc5983144
Ref: 20375983144
Ref: library/argparse argparse-parser-for-command-line-options-arguments-and-sub-commands5983144
Ref: 20385983144
Ref: library/argparse module-argparse5983144
Ref: 65983144
Ref: argparse --- 命令行选项、参数和子命令解析器-Footnote-15984109
Node: 示例<7>5984176
Ref: library/argparse example5984310
Ref: 203a5984310
Node: 创建一个解析器5985872
Ref: library/argparse creating-a-parser5985960
Ref: 203b5985960
Node: 添加参数5986297
Ref: library/argparse adding-arguments5986406
Ref: 203c5986406
Node: 解析参数5987465
Ref: library/argparse parsing-arguments5987544
Ref: 203f5987544
Node: ArgumentParser 对象5988185
Ref: library/argparse argumentparser-objects5988347
Ref: 20415988347
Ref: library/argparse argparse ArgumentParser5988408
Ref: 69e5988408
Node: prog5990786
Ref: library/argparse prog5990862
Ref: 20425990862
Node: usage5992670
Ref: library/argparse usage5992766
Ref: 20435992766
Node: description5993906
Ref: library/argparse description5994004
Ref: 20445994004
Node: epilog5994712
Ref: library/argparse epilog5994812
Ref: 20455994812
Node: parents5995562
Ref: library/argparse parents5995666
Ref: 20465995666
Node: formatter_class5997075
Ref: library/argparse formatter-class5997185
Ref: 20475997185
Ref: library/argparse argparse RawDescriptionHelpFormatter5997370
Ref: 204d5997370
Ref: library/argparse argparse RawTextHelpFormatter5997416
Ref: 204e5997416
Ref: library/argparse argparse ArgumentDefaultsHelpFormatter5997455
Ref: 204f5997455
Ref: library/argparse argparse MetavarTypeHelpFormatter5997503
Ref: 20505997503
Node: prefix_chars6000914
Ref: library/argparse prefix-chars6001038
Ref: 20486001038
Node: fromfile_prefix_chars6001708
Ref: library/argparse fromfile-prefix-chars6001833
Ref: 20496001833
Node: argument_default6002976
Ref: library/argparse argument-default6003101
Ref: 204a6003101
Node: allow_abbrev6003947
Ref: library/argparse allow-abbrev6004067
Ref: 6a06004067
Ref: library/argparse id16004067
Ref: 20556004067
Node: conflict_handler6004709
Ref: library/argparse conflict-handler6004821
Ref: 204b6004821
Node: add_help6006330
Ref: library/argparse add-help6006421
Ref: 204c6006421
Node: add_argument 方法6007929
Ref: library/argparse the-add-argument-method6008099
Ref: 20566008099
Ref: library/argparse argparse ArgumentParser add_argument6008162
Ref: 203d6008162
Node: name or flags6009721
Ref: library/argparse name-or-flags6009805
Ref: 20576009805
Node: action6010857
Ref: library/argparse action6010955
Ref: 20586010955
Node: nargs6016160
Ref: library/argparse nargs6016250
Ref: 20596016250
Ref: library/argparse argparse-remainder6019666
Ref: 20616019666
Node: const6020400
Ref: library/argparse const6020493
Ref: 205a6020493
Node: 默认值6021477
Ref: library/argparse default6021569
Ref: 205b6021569
Node: type6023296
Ref: library/argparse type6023390
Ref: 20516023390
Node: choices6025853
Ref: library/argparse choices6025946
Ref: 205c6025946
Node: required6027342
Ref: library/argparse required6027435
Ref: 205d6027435
Node: help6028402
Ref: library/argparse help6028495
Ref: 205e6028495
Node: metavar6030565
Ref: library/argparse metavar6030654
Ref: 205f6030654
Node: dest6032793
Ref: library/argparse dest6032888
Ref: 20526032888
Node: Action 类6034423
Ref: library/argparse action-classes6034502
Ref: 20626034502
Ref: library/argparse argparse Action6034786
Ref: 20606034786
Node: parse_args 方法6036455
Ref: library/argparse the-parse-args-method6036622
Ref: 20636036622
Ref: library/argparse argparse ArgumentParser parse_args6036681
Ref: 203e6036681
Node: 选项值语法6037486
Ref: library/argparse option-value-syntax6037579
Ref: 20666037579
Node: 无效的参数6038920
Ref: library/argparse invalid-arguments6039040
Ref: 20676039040
Node: 包含 - 的参数6039994
Ref: library/argparse arguments-containing6040129
Ref: 20686040129
Node: 参数缩写（前缀匹配）6041999
Ref: library/argparse argument-abbreviations-prefix-matching6042138
Ref: 20696042138
Ref: library/argparse prefix-matching6042138
Ref: 69f6042138
Node: 在 sys argv 以外6043002
Ref: library/argparse args6043141
Ref: 20646043141
Ref: library/argparse beyond-sys-argv6043141
Ref: 206a6043141
Node: 命名空间对象6044068
Ref: library/argparse namespace6044168
Ref: 20656044168
Ref: library/argparse the-namespace-object6044168
Ref: 206b6044168
Ref: library/argparse argparse Namespace6044221
Ref: 20406044221
Node: 其它实用工具6045216
Ref: library/argparse other-utilities6045386
Ref: 206c6045386
Node: 子命令6045625
Ref: library/argparse sub-commands6045713
Ref: 206d6045713
Ref: library/argparse argparse ArgumentParser add_subparsers6045751
Ref: 4ac6045751
Node: FileType 对象6054146
Ref: library/argparse filetype-objects6054252
Ref: 206e6054252
Ref: library/argparse argparse FileType6054303
Ref: 8296054303
Node: 参数组6055706
Ref: library/argparse argument-groups6055809
Ref: 206f6055809
Ref: library/argparse argparse ArgumentParser add_argument_group6055847
Ref: 20706055847
Node: 互斥6057841
Ref: library/argparse mutual-exclusion6057947
Ref: 20716057947
Ref: library/argparse argparse ArgumentParser add_mutually_exclusive_group6057980
Ref: 20726057980
Node: 解析器默认值6059443
Ref: library/argparse parser-defaults6059552
Ref: 20736059552
Ref: library/argparse argparse ArgumentParser set_defaults6059605
Ref: 20546059605
Ref: library/argparse argparse ArgumentParser get_default6060614
Ref: 20746060614
Node: 打印帮助6060971
Ref: library/argparse printing-help6061086
Ref: 20756061086
Ref: library/argparse argparse ArgumentParser print_usage6061298
Ref: 20766061298
Ref: library/argparse argparse ArgumentParser print_help6061542
Ref: 20776061542
Ref: library/argparse argparse ArgumentParser format_usage6061886
Ref: 20786061886
Ref: library/argparse argparse ArgumentParser format_help6062062
Ref: 20796062062
Node: 部分解析6062247
Ref: library/argparse partial-parsing6062365
Ref: 207a6062365
Ref: library/argparse argparse ArgumentParser parse_known_args6062408
Ref: 207b6062408
Node: 自定义文件解析6063419
Ref: library/argparse customizing-file-parsing6063537
Ref: 207c6063537
Ref: library/argparse argparse ArgumentParser convert_arg_line_to_args6063595
Ref: 20536063595
Node: 退出方法6064447
Ref: library/argparse exiting-methods6064565
Ref: 207d6064565
Ref: library/argparse argparse ArgumentParser exit6064608
Ref: 207e6064608
Ref: library/argparse argparse ArgumentParser error6065146
Ref: 207f6065146
Node: 混合解析6065304
Ref: library/argparse intermixed-parsing6065392
Ref: 20806065392
Ref: library/argparse argparse ArgumentParser parse_intermixed_args6065435
Ref: 34e6065435
Ref: library/argparse argparse ArgumentParser parse_known_intermixed_args6065523
Ref: 20816065523
Node: 升级 optparse 代码6067008
Ref: library/argparse id26067152
Ref: 20826067152
Ref: library/argparse upgrading-optparse-code6067152
Ref: b316067152
Node: getopt --- C 风格的命令行选项解析器6069478
Ref: library/getopt doc6069701
Ref: 20856069701
Ref: library/getopt getopt-c-style-parser-for-command-line-options6069701
Ref: 20866069701
Ref: library/getopt module-getopt6069701
Ref: 876069701
Ref: library/getopt getopt getopt6070576
Ref: 20876070576
Ref: library/getopt getopt gnu_getopt6072482
Ref: 20896072482
Ref: library/getopt getopt GetoptError6072990
Ref: 20886072990
Ref: library/getopt getopt error6073490
Ref: 208a6073490
Ref: getopt --- C 风格的命令行选项解析器-Footnote-16075869
Node: logging --- Python 的日志记录工具6075934
Ref: library/logging doc6076136
Ref: 208b6076136
Ref: library/logging logging-logging-facility-for-python6076136
Ref: 208c6076136
Ref: library/logging module-logging6076136
Ref: ab6076136
Ref: logging --- Python 的日志记录工具-Footnote-16077678
Node: 记录器对象6077754
Ref: library/logging logger6077867
Ref: 208d6077867
Ref: library/logging logger-objects6077867
Ref: 208e6077867
Ref: library/logging logging Logger6078833
Ref: 3af6078833
Ref: library/logging logging Logger propagate6078858
Ref: 20906078858
Ref: library/logging logging Logger setLevel6080066
Ref: 20916080066
Ref: library/logging logging Logger isEnabledFor6081659
Ref: 20946081659
Ref: library/logging logging Logger getEffectiveLevel6081962
Ref: 20936081962
Ref: library/logging logging Logger getChild6082379
Ref: c936082379
Ref: library/logging logging Logger debug6082815
Ref: 7196082815
Ref: library/logging logging Logger info6087278
Ref: 20976087278
Ref: library/logging logging Logger warning6087439
Ref: 20996087439
Ref: library/logging logging Logger error6087799
Ref: 209a6087799
Ref: library/logging logging Logger critical6087962
Ref: 7186087962
Ref: library/logging logging Logger log6088131
Ref: 7166088131
Ref: library/logging logging Logger exception6088310
Ref: 7176088310
Ref: library/logging logging Logger addFilter6088578
Ref: 209b6088578
Ref: library/logging logging Logger removeFilter6088682
Ref: 209c6088682
Ref: library/logging logging Logger filter6088788
Ref: 209d6088788
Ref: library/logging logging Logger addHandler6089181
Ref: 209e6089181
Ref: library/logging logging Logger removeHandler6089282
Ref: 209f6089282
Ref: library/logging logging Logger findCaller6089385
Ref: 20a06089385
Ref: library/logging logging Logger handle6090064
Ref: 20a16090064
Ref: library/logging logging Logger makeRecord6090416
Ref: 20a26090416
Ref: library/logging logging Logger hasHandlers6090674
Ref: 20a36090674
Node: 日志级别6091267
Ref: library/logging levels6091404
Ref: 20926091404
Ref: library/logging logging-levels6091404
Ref: 20a46091404
Node: 处理器对象6092229
Ref: library/logging handler6092366
Ref: 20a56092366
Ref: library/logging handler-objects6092366
Ref: 20a66092366
Ref: library/logging logging Handler6092647
Ref: 20966092647
Ref: library/logging logging Handler __init__6092673
Ref: 20a76092673
Ref: library/logging logging Handler createLock6092932
Ref: 20a86092932
Ref: library/logging logging Handler acquire6093113
Ref: 20a96093113
Ref: library/logging logging Handler release6093205
Ref: 20aa6093205
Ref: library/logging logging Handler setLevel6093297
Ref: 20ab6093297
Ref: library/logging logging Handler setFormatter6093790
Ref: 20ac6093790
Ref: library/logging logging Handler addFilter6093899
Ref: 20ad6093899
Ref: library/logging logging Handler removeFilter6094003
Ref: 20ae6094003
Ref: library/logging logging Handler filter6094110
Ref: 20af6094110
Ref: library/logging logging Handler flush6094445
Ref: 20b06094445
Ref: library/logging logging Handler close6094597
Ref: 20b16094597
Ref: library/logging logging Handler handle6094907
Ref: 20b36094907
Ref: library/logging logging Handler handleError6095120
Ref: 20b46095120
Ref: library/logging logging Handler format6095793
Ref: 20b66095793
Ref: library/logging logging Handler emit6095952
Ref: 20b56095952
Node: 格式器对象6096250
Ref: library/logging formatter-objects6096388
Ref: 20b76096388
Ref: library/logging id16096388
Ref: 20b86096388
Ref: library/logging logging Formatter6097382
Ref: 20956097382
Ref: library/logging logging Formatter format6098426
Ref: 20bc6098426
Ref: library/logging logging Formatter formatTime6099581
Ref: 20ba6099581
Ref: library/logging logging Formatter formatException6101571
Ref: 20bd6101571
Ref: library/logging logging Formatter formatStack6101867
Ref: 20be6101867
Node: Filter 对象6102129
Ref: library/logging filter6102268
Ref: 20c06102268
Ref: library/logging filter-objects6102268
Ref: 20c16102268
Ref: library/logging logging Filter6102788
Ref: b7f6102788
Ref: library/logging logging Filter filter6103088
Ref: 20c26103088
Node: LogRecord 属性6104973
Ref: library/logging log-record6105116
Ref: 20c56105116
Ref: library/logging logrecord-objects6105116
Ref: 20c66105116
Ref: library/logging logging LogRecord6105387
Ref: 90e6105387
Ref: library/logging logging LogRecord getMessage6106955
Ref: 20c86106955
Node: LogRecord 属性<2>6108325
Ref: library/logging id26108475
Ref: 20cb6108475
Ref: library/logging logrecord-attributes6108475
Ref: 20b96108475
Node: LoggerAdapter 对象6115674
Ref: library/logging logger-adapter6115820
Ref: 20cd6115820
Ref: library/logging loggeradapter-objects6115820
Ref: 20ce6115820
Ref: library/logging logging LoggerAdapter6116086
Ref: c946116086
Ref: library/logging logging LoggerAdapter process6116293
Ref: 20d06116293
Node: 线程安全6117438
Ref: library/logging thread-safety6117583
Ref: 20d16117583
Node: 模块级别函数6118192
Ref: library/logging module-level-functions6118332
Ref: 20d26118332
Ref: library/logging logging getLogger6118447
Ref: 208f6118447
Ref: library/logging logging getLoggerClass6119038
Ref: 20d36119038
Ref: library/logging logging getLogRecordFactory6119464
Ref: 20c96119464
Ref: library/logging logging debug6119907
Ref: 20986119907
Ref: library/logging logging info6123279
Ref: 20c36123279
Ref: library/logging logging warning6123446
Ref: 20d56123446
Ref: library/logging logging error6123810
Ref: 20d66123810
Ref: library/logging logging critical6123976
Ref: 20d76123976
Ref: library/logging logging exception6124151
Ref: 20d86124151
Ref: library/logging logging log6124428
Ref: 20d96124428
Ref: library/logging logging disable6125277
Ref: edb6125277
Ref: library/logging logging addLevelName6126394
Ref: 20da6126394
Ref: library/logging logging getLevelName6127008
Ref: 20dc6127008
Ref: library/logging logging makeLogRecord6128402
Ref: 20c76128402
Ref: library/logging logging basicConfig6128735
Ref: 1e16128735
Ref: library/logging logging shutdown6132652
Ref: 20b26132652
Ref: library/logging logging setLoggerClass6133052
Ref: 20d46133052
Ref: library/logging logging setLogRecordFactory6133675
Ref: 20ca6133675
Ref: 模块级别函数-Footnote-16134901
Node: 模块级属性6134944
Ref: library/logging module-level-attributes6135093
Ref: 20dd6135093
Ref: library/logging logging lastResort6135141
Ref: b7e6135141
Node: 与警告模块集成6135697
Ref: library/logging integration-with-the-warnings-module6135819
Ref: 20de6135819
Ref: library/logging logging captureWarnings6135988
Ref: 20df6135988
Ref: 与警告模块集成-Footnote-16137200
Ref: 与警告模块集成-Footnote-26137249
Node: logging config --- 日志记录配置6137302
Ref: library/logging config doc6137491
Ref: 20e06137491
Ref: library/logging config logging-config-logging-configuration6137491
Ref: 20e16137491
Ref: library/logging config module-logging config6137491
Ref: ac6137491
Ref: logging config --- 日志记录配置-Footnote-16138036
Node: 配置函数6138109
Ref: library/logging config configuration-functions6138222
Ref: 20e26138222
Ref: library/logging config logging-config-api6138222
Ref: c906138222
Ref: library/logging config logging config dictConfig6138603
Ref: b336138603
Ref: library/logging config logging config fileConfig6140466
Ref: 3b16140466
Ref: library/logging config logging config listen6142526
Ref: 87b6142526
Ref: library/logging config logging config stopListening6145634
Ref: 20e66145634
Node: 配置字典架构6145864
Ref: library/logging config configuration-dictionary-schema6146004
Ref: 20e76146004
Ref: library/logging config logging-config-dictschema6146004
Ref: 20e36146004
Node: 字典架构细节6146810
Ref: library/logging config dictionary-schema-details6146904
Ref: 20e96146904
Node: 增量配置6151392
Ref: library/logging config incremental-configuration6151507
Ref: 20ed6151507
Ref: library/logging config logging-config-dict-incremental6151507
Ref: 20ec6151507
Node: 对象连接6152789
Ref: library/logging config logging-config-dict-connections6152904
Ref: 20e86152904
Ref: library/logging config object-connections6152904
Ref: 20ee6152904
Node: 用户定义对象6155026
Ref: library/logging config logging-config-dict-userdef6155147
Ref: 20ea6155147
Ref: library/logging config user-defined-objects6155147
Ref: 20ef6155147
Node: 访问外部对象6158211
Ref: library/logging config access-to-external-objects6158338
Ref: 20f06158338
Ref: library/logging config logging-config-dict-externalobj6158338
Ref: 20f16158338
Node: 访问内部对象6159451
Ref: library/logging config access-to-internal-objects6159590
Ref: 20f26159590
Ref: library/logging config logging-config-dict-internalobj6159590
Ref: 20f36159590
Node: 导入解析与定制导入器6162704
Ref: library/logging config import-resolution-and-custom-importers6162816
Ref: 20f56162816
Ref: library/logging config logging-import-resolution6162816
Ref: 20f66162816
Node: 配置文件格式6163729
Ref: library/logging config configuration-file-format6163848
Ref: 20f76163848
Ref: library/logging config logging-config-fileformat6163848
Ref: 20e46163848
Node: logging handlers --- 日志处理6170933
Ref: library/logging handlers doc6171121
Ref: 20f86171121
Ref: library/logging handlers logging-handlers-logging-handlers6171121
Ref: 20f96171121
Ref: library/logging handlers module-logging handlers6171121
Ref: ad6171121
Ref: logging handlers --- 日志处理-Footnote-16172133
Node: StreamHandler6172209
Ref: library/logging handlers stream-handler6172312
Ref: 20fb6172312
Ref: library/logging handlers streamhandler6172312
Ref: 20fc6172312
Ref: library/logging handlers logging StreamHandler6172626
Ref: b7d6172626
Ref: library/logging handlers logging StreamHandler emit6172852
Ref: 20fd6172852
Ref: library/logging handlers logging StreamHandler flush6173185
Ref: 20fe6173185
Ref: library/logging handlers logging StreamHandler setStream6173458
Ref: 3b06173458
Node: FileHandler6174211
Ref: library/logging handlers file-handler6174334
Ref: 20ff6174334
Ref: library/logging handlers filehandler6174334
Ref: 21006174334
Ref: library/logging handlers logging FileHandler6174552
Ref: 20fa6174552
Ref: library/logging handlers logging FileHandler close6175179
Ref: 21026175179
Ref: library/logging handlers logging FileHandler emit6175233
Ref: 21016175233
Node: NullHandler6175304
Ref: library/logging handlers null-handler6175432
Ref: 21036175432
Ref: library/logging handlers nullhandler6175432
Ref: 21046175432
Ref: library/logging handlers logging NullHandler6175677
Ref: c246175677
Ref: library/logging handlers logging NullHandler emit6175769
Ref: 21056175769
Ref: library/logging handlers logging NullHandler handle6175846
Ref: 21066175846
Ref: library/logging handlers logging NullHandler createLock6175925
Ref: 21076175925
Node: WatchedFileHandler6176177
Ref: library/logging handlers watched-file-handler6176313
Ref: 21096176313
Ref: library/logging handlers watchedfilehandler6176313
Ref: 210a6176313
Ref: library/logging handlers logging handlers WatchedFileHandler6177327
Ref: 210b6177327
Ref: library/logging handlers logging handlers WatchedFileHandler reopenIfNeeded6177977
Ref: 56b6177977
Ref: library/logging handlers logging handlers WatchedFileHandler emit6178225
Ref: 210c6178225
Node: BaseRotatingHandler6178396
Ref: library/logging handlers base-rotating-handler6178540
Ref: 210d6178540
Ref: library/logging handlers baserotatinghandler6178540
Ref: 210e6178540
Ref: library/logging handlers logging handlers BaseRotatingHandler6178891
Ref: 210f6178891
Ref: library/logging handlers logging handlers BaseRotatingHandler namer6179060
Ref: 21106179060
Ref: library/logging handlers logging handlers BaseRotatingHandler rotator6179617
Ref: 21126179617
Ref: library/logging handlers logging handlers BaseRotatingHandler rotation_filename6179896
Ref: 21116179896
Ref: library/logging handlers logging handlers BaseRotatingHandler rotate6180423
Ref: 21136180423
Node: RotatingFileHandler6181675
Ref: library/logging handlers rotating-file-handler6181825
Ref: 21156181825
Ref: library/logging handlers rotatingfilehandler6181825
Ref: 21166181825
Ref: library/logging handlers logging handlers RotatingFileHandler6182006
Ref: 20eb6182006
Ref: library/logging handlers logging handlers RotatingFileHandler doRollover6183737
Ref: 21186183737
Ref: library/logging handlers logging handlers RotatingFileHandler emit6183814
Ref: 21176183814
Node: TimedRotatingFileHandler6183921
Ref: library/logging handlers timed-rotating-file-handler6184065
Ref: 21196184065
Ref: library/logging handlers timedrotatingfilehandler6184065
Ref: 211a6184065
Ref: library/logging handlers logging handlers TimedRotatingFileHandler6184283
Ref: 8776184283
Ref: library/logging handlers logging handlers TimedRotatingFileHandler doRollover6188888
Ref: 211c6188888
Ref: library/logging handlers logging handlers TimedRotatingFileHandler emit6188965
Ref: 211b6188965
Node: SocketHandler6189072
Ref: library/logging handlers socket-handler6189212
Ref: 211d6189212
Ref: library/logging handlers sockethandler6189212
Ref: 211e6189212
Ref: library/logging handlers logging handlers SocketHandler6189428
Ref: 8786189428
Ref: library/logging handlers logging handlers SocketHandler close6189836
Ref: 211f6189836
Ref: library/logging handlers logging handlers SocketHandler emit6189893
Ref: 21206189893
Ref: library/logging handlers logging handlers SocketHandler handleError6190279
Ref: 21216190279
Ref: library/logging handlers logging handlers SocketHandler makeSocket6190490
Ref: 21226190490
Ref: library/logging handlers logging handlers SocketHandler makePickle6190713
Ref: 21236190713
Ref: library/logging handlers logging handlers SocketHandler send6191421
Ref: 21246191421
Ref: library/logging handlers logging handlers SocketHandler createSocket6191696
Ref: 21256191696
Node: DatagramHandler6192713
Ref: library/logging handlers datagram-handler6192842
Ref: 21266192842
Ref: library/logging handlers datagramhandler6192842
Ref: 21276192842
Ref: library/logging handlers logging handlers DatagramHandler6193065
Ref: 8796193065
Ref: library/logging handlers logging handlers DatagramHandler emit6193477
Ref: 21286193477
Ref: library/logging handlers logging handlers DatagramHandler makeSocket6193805
Ref: 21296193805
Ref: library/logging handlers logging handlers DatagramHandler send6193982
Ref: 212a6193982
Node: SysLogHandler6194175
Ref: library/logging handlers syslog-handler6194308
Ref: 212b6194308
Ref: library/logging handlers sysloghandler6194308
Ref: 212c6194308
Ref: library/logging handlers logging handlers SysLogHandler6194502
Ref: a266194502
Ref: library/logging handlers logging handlers SysLogHandler close6196167
Ref: 212d6196167
Ref: library/logging handlers logging handlers SysLogHandler emit6196245
Ref: 212e6196245
Ref: library/logging handlers logging handlers SysLogHandler encodePriority6197940
Ref: 212f6197940
Ref: library/logging handlers logging handlers SysLogHandler mapPriority6201933
Ref: 21306201933
Ref: SysLogHandler-Footnote-16202412
Ref: SysLogHandler-Footnote-26202455
Ref: SysLogHandler-Footnote-36202504
Node: NTEventLogHandler6202547
Ref: library/logging handlers nt-eventlog-handler6202676
Ref: 21316202676
Ref: library/logging handlers nteventloghandler6202676
Ref: 21326202676
Ref: library/logging handlers logging handlers NTEventLogHandler6202996
Ref: 21336202996
Ref: library/logging handlers logging handlers NTEventLogHandler close6203947
Ref: 21346203947
Ref: library/logging handlers logging handlers NTEventLogHandler emit6204314
Ref: 21356204314
Ref: library/logging handlers logging handlers NTEventLogHandler getEventCategory6204463
Ref: 21366204463
Ref: library/logging handlers logging handlers NTEventLogHandler getEventType6204648
Ref: 21376204648
Ref: library/logging handlers logging handlers NTEventLogHandler getMessageID6205211
Ref: 21386205211
Node: SMTPHandler6205593
Ref: library/logging handlers smtp-handler6205722
Ref: 21396205722
Ref: library/logging handlers smtphandler6205722
Ref: 213a6205722
Ref: library/logging handlers logging handlers SMTPHandler6205920
Ref: 213b6205920
Ref: library/logging handlers logging handlers SMTPHandler emit6207088
Ref: 213c6207088
Ref: library/logging handlers logging handlers SMTPHandler getSubject6207192
Ref: 213d6207192
Node: MemoryHandler6207317
Ref: library/logging handlers memory-handler6207440
Ref: 213e6207440
Ref: library/logging handlers memoryhandler6207440
Ref: 213f6207440
Ref: library/logging handlers logging handlers BufferingHandler6208103
Ref: 21406208103
Ref: library/logging handlers logging handlers BufferingHandler emit6208282
Ref: 21416208282
Ref: library/logging handlers logging handlers BufferingHandler flush6208472
Ref: 21436208472
Ref: library/logging handlers logging handlers BufferingHandler shouldFlush6208619
Ref: 21426208619
Ref: library/logging handlers logging handlers MemoryHandler6208789
Ref: 20f46208789
Ref: library/logging handlers logging handlers MemoryHandler close6209571
Ref: 21456209571
Ref: library/logging handlers logging handlers MemoryHandler flush6209688
Ref: 21466209688
Ref: library/logging handlers logging handlers MemoryHandler setTarget6209961
Ref: 21446209961
Ref: library/logging handlers logging handlers MemoryHandler shouldFlush6210055
Ref: 21476210055
Node: HTTPHandler6210183
Ref: library/logging handlers http-handler6210307
Ref: 21486210307
Ref: library/logging handlers httphandler6210307
Ref: 21496210307
Ref: library/logging handlers logging handlers HTTPHandler6210520
Ref: 71a6210520
Ref: library/logging handlers logging handlers HTTPHandler mapLogRecord6211435
Ref: 214a6211435
Ref: library/logging handlers logging handlers HTTPHandler emit6211826
Ref: 214b6211826
Node: QueueHandler6212541
Ref: library/logging handlers queue-handler6212665
Ref: 214c6212665
Ref: library/logging handlers queuehandler6212665
Ref: 214d6212665
Ref: library/logging handlers logging handlers QueueHandler6213361
Ref: 214e6213361
Ref: library/logging handlers logging handlers QueueHandler emit6213808
Ref: 21506213808
Ref: library/logging handlers logging handlers QueueHandler prepare6214257
Ref: 21516214257
Ref: library/logging handlers logging handlers QueueHandler enqueue6214745
Ref: 214f6214745
Node: QueueListener6214976
Ref: library/logging handlers queue-listener6215080
Ref: 21526215080
Ref: library/logging handlers queuelistener6215080
Ref: 21536215080
Ref: library/logging handlers logging handlers QueueListener6216052
Ref: 71b6216052
Ref: library/logging handlers logging handlers QueueListener dequeue6217075
Ref: 21546217075
Ref: library/logging handlers logging handlers QueueListener prepare6217346
Ref: 21556217346
Ref: library/logging handlers logging handlers QueueListener handle6217652
Ref: 21566217652
Ref: library/logging handlers logging handlers QueueListener start6217908
Ref: 21576217908
Ref: library/logging handlers logging handlers QueueListener stop6218055
Ref: 21586218055
Ref: library/logging handlers logging handlers QueueListener enqueue_sentinel6218362
Ref: 21596218362
Node: getpass --- 便携式密码输入工具6218818
Ref: library/getpass doc6219013
Ref: 215a6219013
Ref: library/getpass getpass-portable-password-input6219013
Ref: 215b6219013
Ref: library/getpass module-getpass6219013
Ref: 886219013
Ref: library/getpass getpass getpass6219256
Ref: 215c6219256
Ref: library/getpass getpass GetPassWarning6220062
Ref: 215d6220062
Ref: library/getpass getpass getuser6220188
Ref: 1eff6220188
Ref: getpass --- 便携式密码输入工具-Footnote-16220709
Node: curses --- 终端字符单元显示的处理6220775
Ref: library/curses doc6220997
Ref: 215e6220997
Ref: library/curses curses-terminal-handling-for-character-cell-displays6220997
Ref: 215f6220997
Ref: library/curses module-curses6220997
Ref: 2c6220997
Ref: curses --- 终端字符单元显示的处理-Footnote-16223064
Node: 函数<3>6223127
Ref: library/curses curses-functions6223239
Ref: 21616223239
Ref: library/curses functions6223239
Ref: 21626223239
Ref: library/curses curses error6223322
Ref: 21636223322
Ref: library/curses curses baudrate6223657
Ref: 21646223657
Ref: library/curses curses beep6223977
Ref: 21656223977
Ref: library/curses curses can_change_color6224042
Ref: 21666224042
Ref: library/curses curses cbreak6224173
Ref: 21676224173
Ref: library/curses curses color_content6224639
Ref: 21696224639
Ref: library/curses curses color_pair6224989
Ref: 216a6224989
Ref: library/curses curses curs_set6225298
Ref: 216c6225298
Ref: library/curses curses def_prog_mode6225693
Ref: 216d6225693
Ref: library/curses curses def_shell_mode6225994
Ref: 216f6225994
Ref: library/curses curses delay_output6226294
Ref: 21716226294
Ref: library/curses curses doupdate6226381
Ref: 21726226381
Ref: library/curses curses echo6227106
Ref: 21766227106
Ref: library/curses curses endwin6227250
Ref: 21776227250
Ref: library/curses curses erasechar6227341
Ref: 21786227341
Ref: library/curses curses filter6227586
Ref: 21796227586
Ref: library/curses curses flash6228152
Ref: 217b6228152
Ref: library/curses curses flushinp6228394
Ref: 217c6228394
Ref: library/curses curses getmouse6228551
Ref: 217d6228551
Ref: library/curses curses getsyx6229326
Ref: 217f6229326
Ref: library/curses curses getwin6229518
Ref: 21816229518
Ref: library/curses curses has_colors6229747
Ref: 21826229747
Ref: library/curses curses has_ic6229865
Ref: 21836229865
Ref: library/curses curses has_il6230094
Ref: 21846230094
Ref: library/curses curses has_key6230380
Ref: 21856230380
Ref: library/curses curses halfdelay6230528
Ref: 21866230528
Ref: library/curses curses init_color6230930
Ref: 21886230930
Ref: library/curses curses init_pair6231526
Ref: 21896231526
Ref: library/curses curses initscr6232171
Ref: 217a6232171
Ref: library/curses curses is_term_resized6232405
Ref: 218c6232405
Ref: library/curses curses isendwin6232575
Ref: 218e6232575
Ref: library/curses curses keyname6232728
Ref: 218f6232728
Ref: library/curses curses killchar6233190
Ref: 21906233190
Ref: library/curses curses longname6233437
Ref: 21916233437
Ref: library/curses curses meta6233691
Ref: 21926233691
Ref: library/curses curses mouseinterval6233874
Ref: 21936233874
Ref: library/curses curses mousemask6234118
Ref: 21946234118
Ref: library/curses curses napms6234501
Ref: 21956234501
Ref: library/curses curses newpad6234560
Ref: 21966234560
Ref: library/curses curses newwin6235457
Ref: 21976235457
Ref: library/curses curses nl6235785
Ref: 21986235785
Ref: library/curses curses nocbreak6235991
Ref: 21876235991
Ref: library/curses curses noecho6236103
Ref: 21996236103
Ref: library/curses curses nonl6236192
Ref: 219a6236192
Ref: library/curses curses noqiflush6236625
Ref: 219b6236625
Ref: library/curses curses noraw6237006
Ref: 219c6237006
Ref: library/curses curses pair_content6237112
Ref: 219d6237112
Ref: library/curses curses pair_number6237312
Ref: 216b6237312
Ref: library/curses curses putp6237482
Ref: 219e6237482
Ref: library/curses curses qiflush6237686
Ref: 219f6237686
Ref: library/curses curses raw6237932
Ref: 21686237932
Ref: library/curses curses reset_prog_mode6238156
Ref: 216e6238156
Ref: library/curses curses reset_shell_mode6238308
Ref: 21706238308
Ref: library/curses curses resetty6238461
Ref: 21a06238461
Ref: library/curses curses resize_term6238580
Ref: 218d6238580
Ref: library/curses curses resizeterm6239075
Ref: 21a26239075
Ref: library/curses curses savetty6239315
Ref: 21a16239315
Ref: library/curses curses setsyx6239452
Ref: 21a36239452
Ref: library/curses curses setupterm6239626
Ref: 21a46239626
Ref: library/curses curses start_color6240002
Ref: 21a56240002
Ref: library/curses curses termattrs6240595
Ref: 21a66240595
Ref: library/curses curses termname6240789
Ref: 21a76240789
Ref: library/curses curses tigetflag6240916
Ref: 21a86240916
Ref: library/curses curses tigetnum6241195
Ref: 21a96241195
Ref: library/curses curses tigetstr6241474
Ref: 21aa6241474
Ref: library/curses curses tparm6241769
Ref: 21ab6241769
Ref: library/curses curses typeahead6242076
Ref: 21ac6242076
Ref: library/curses curses unctrl6242603
Ref: 21ad6242603
Ref: library/curses curses ungetch6242839
Ref: 21ae6242839
Ref: library/curses curses update_lines_cols6243028
Ref: 6cf6243028
Ref: library/curses curses unget_wch6243182
Ref: 9e86243182
Ref: library/curses curses ungetmouse6243400
Ref: 21af6243400
Ref: library/curses curses use_env6243555
Ref: 21b06243555
Ref: library/curses curses use_default_colors6244039
Ref: 218a6244039
Ref: library/curses curses wrapper6244431
Ref: 2a26244431
Node: Window 对象6245216
Ref: library/curses curses-window-objects6245346
Ref: 218b6245346
Ref: library/curses window-objects6245346
Ref: 21b16245346
Ref: library/curses curses window addch6245514
Ref: 21b26245514
Ref: library/curses curses window addnstr6246031
Ref: 21b36246031
Ref: library/curses curses window addstr6246274
Ref: 21736246274
Ref: library/curses curses window attroff6247190
Ref: 21b46247190
Ref: library/curses curses window attron6247310
Ref: 21b56247310
Ref: library/curses curses window attrset6247429
Ref: 21b66247429
Ref: library/curses curses window bkgd6247558
Ref: 21b76247558
Ref: library/curses curses window bkgdset6247957
Ref: 21b86247957
Ref: library/curses curses window border6248372
Ref: 21b96248372
Ref: library/curses curses window box6250242
Ref: 21ba6250242
Ref: library/curses curses window chgat6250448
Ref: 21bb6250448
Ref: library/curses curses window clear6251005
Ref: 21bd6251005
Ref: library/curses curses window clearok6251166
Ref: 21bf6251166
Ref: library/curses curses window clrtobot6251314
Ref: 21c06251314
Ref: library/curses curses window clrtoeol6251507
Ref: 21c16251507
Ref: library/curses curses window cursyncup6251588
Ref: 21c26251588
Ref: library/curses curses window delch6251718
Ref: 21c36251718
Ref: library/curses curses window deleteln6251804
Ref: 21c46251804
Ref: library/curses curses window derwin6251913
Ref: 21c56251913
Ref: library/curses curses window echochar6252293
Ref: 21c76252293
Ref: library/curses curses window enclose6252440
Ref: 21c86252440
Ref: library/curses curses window encoding6252702
Ref: 9e66252702
Ref: library/curses curses window erase6253069
Ref: 21be6253069
Ref: library/curses curses window getbegyx6253120
Ref: 21c96253120
Ref: library/curses curses window getbkgd6253205
Ref: 21ca6253205
Ref: library/curses curses window getch6253295
Ref: 217e6253295
Ref: library/curses curses window get_wch6253625
Ref: 9e76253625
Ref: library/curses curses window getkey6253917
Ref: 21cb6253917
Ref: library/curses curses window getmaxyx6254239
Ref: 21cc6254239
Ref: library/curses curses window getparyx6254330
Ref: 21cd6254330
Ref: library/curses curses window getstr6254513
Ref: 21ce6254513
Ref: library/curses curses window getyx6254724
Ref: 21cf6254724
Ref: library/curses curses window hline6254836
Ref: 21d06254836
Ref: library/curses curses window idcok6254996
Ref: 21d16254996
Ref: library/curses curses window idlok6255288
Ref: 21d26255288
Ref: library/curses curses window immedok6255462
Ref: 21d36255462
Ref: library/curses curses window inch6255765
Ref: 21d46255765
Ref: library/curses curses window insch6255930
Ref: 21d56255930
Ref: library/curses curses window insdelln6256143
Ref: 21d66256143
Ref: library/curses curses window insertln6256493
Ref: 21d76256493
Ref: library/curses curses window insnstr6256608
Ref: 21d86256608
Ref: library/curses curses window insstr6257058
Ref: 21d96257058
Ref: library/curses curses window instr6257411
Ref: 21da6257411
Ref: library/curses curses window is_linetouched6257770
Ref: 21db6257770
Ref: library/curses curses window is_wintouched6258047
Ref: 21dc6258047
Ref: library/curses curses window keypad6258224
Ref: 21dd6258224
Ref: library/curses curses window leaveok6258492
Ref: 21806258492
Ref: library/curses curses window move6258825
Ref: 21de6258825
Ref: library/curses curses window mvderwin6258911
Ref: 21df6258911
Ref: library/curses curses window mvwin6259124
Ref: 21e06259124
Ref: library/curses curses window nodelay6259232
Ref: 21e16259232
Ref: library/curses curses window notimeout6259351
Ref: 21e26259351
Ref: library/curses curses window noutrefresh6259606
Ref: 21746259606
Ref: library/curses curses window overlay6259839
Ref: 21e36259839
Ref: library/curses curses window overwrite6260413
Ref: 21e46260413
Ref: library/curses curses window putwin6260990
Ref: 21e56260990
Ref: library/curses curses window redrawln6261174
Ref: 21e66261174
Ref: library/curses curses window redrawwin6261354
Ref: 21e76261354
Ref: library/curses curses window refresh6261481
Ref: 21756261481
Ref: library/curses curses window resize6262334
Ref: 21e86262334
Ref: library/curses curses window scroll6262638
Ref: 21e96262638
Ref: library/curses curses window scrollok6262735
Ref: 21ea6262735
Ref: library/curses curses window setscrreg6263211
Ref: 21eb6263211
Ref: library/curses curses window standend6263367
Ref: 21ec6263367
Ref: library/curses curses window standout6263498
Ref: 21ed6263498
Ref: library/curses curses window subpad6263565
Ref: 21ee6263565
Ref: library/curses curses window subwin6263800
Ref: 21c66263800
Ref: library/curses curses window syncdown6264117
Ref: 21ef6264117
Ref: library/curses curses window syncok6264300
Ref: 21f06264300
Ref: library/curses curses window syncup6264461
Ref: 21f16264461
Ref: library/curses curses window timeout6264582
Ref: 21f26264582
Ref: library/curses curses window touchline6265058
Ref: 21bc6265058
Ref: library/curses curses window touchwin6265335
Ref: 21f36265335
Ref: library/curses curses window untouchwin6265440
Ref: 21f46265440
Ref: library/curses curses window vline6265577
Ref: 21f56265577
Ref: Window 对象-Footnote-16265773
Node: 常量<6>6265816
Ref: library/curses constants6265928
Ref: 21f66265928
Ref: library/curses curses ERR6266015
Ref: 21f76266015
Ref: library/curses curses OK6266161
Ref: 21f86266161
Ref: library/curses curses version6266305
Ref: 21f96266305
Ref: library/curses curses ncurses_version6266419
Ref: 1c06266419
Node: curses textpad --- 用于 curses 程序的文本输入控件6284434
Ref: library/curses curses-textpad-text-input-widget-for-curses-programs6284662
Ref: 21fa6284662
Ref: library/curses module-curses textpad6284662
Ref: 2f6284662
Ref: library/curses curses textpad rectangle6285216
Ref: 21fc6285216
Node: 文本框对象6285805
Ref: library/curses curses-textpad-objects6285917
Ref: 21fd6285917
Ref: library/curses textbox-objects6285917
Ref: 21fe6285917
Ref: library/curses curses textpad Textbox6286031
Ref: 21fb6286031
Ref: library/curses curses textpad Textbox edit6286442
Ref: 22006286442
Ref: library/curses curses textpad Textbox do_command6286936
Ref: 22016286936
Ref: library/curses curses textpad Textbox gather6290236
Ref: 22026290236
Ref: library/curses curses textpad Textbox stripspaces6290408
Ref: 21ff6290408
Node: curses ascii --- 用于 ASCII 字符的工具6290722
Ref: library/curses ascii doc6290949
Ref: 22036290949
Ref: library/curses ascii curses-ascii-utilities-for-ascii-characters6290949
Ref: 22046290949
Ref: library/curses ascii module-curses ascii6290949
Ref: 2d6290949
Ref: library/curses ascii curses ascii isalnum6294459
Ref: 22056294459
Ref: library/curses ascii curses ascii isalpha6294588
Ref: 22066294588
Ref: library/curses ascii curses ascii isascii6294710
Ref: 22076294710
Ref: library/curses ascii curses ascii isblank6294807
Ref: 22086294807
Ref: library/curses ascii curses ascii iscntrl6294913
Ref: 22096294913
Ref: library/curses ascii curses ascii isdigit6295028
Ref: 220a6295028
Ref: library/curses ascii curses ascii isgraph6295180
Ref: 220b6295180
Ref: library/curses ascii curses ascii islower6295283
Ref: 220c6295283
Ref: library/curses ascii curses ascii isprint6295362
Ref: 220d6295362
Ref: library/curses ascii curses ascii ispunct6295462
Ref: 220e6295462
Ref: library/curses ascii curses ascii isspace6295589
Ref: 220f6295589
Ref: library/curses ascii curses ascii isupper6295740
Ref: 22106295740
Ref: library/curses ascii curses ascii isxdigit6295819
Ref: 22116295819
Ref: library/curses ascii curses ascii isctrl6295943
Ref: 22126295943
Ref: library/curses ascii curses ascii ismeta6296039
Ref: 22136296039
Ref: library/curses ascii curses ascii ascii6296549
Ref: 22146296549
Ref: library/curses ascii curses ascii ctrl6296649
Ref: 22156296649
Ref: library/curses ascii curses ascii alt6296796
Ref: 22166296796
Ref: library/curses ascii curses ascii unctrl6297038
Ref: 22176297038
Ref: library/curses ascii curses ascii controlnames6297545
Ref: 22186297545
Node: curses panel --- curses 的 panel 栈扩展6297779
Ref: library/curses panel doc6297992
Ref: 22196297992
Ref: library/curses panel curses-panel-a-panel-stack-extension-for-curses6297992
Ref: 221a6297992
Ref: library/curses panel module-curses panel6297992
Ref: 2e6297992
Node: 函数<4>6298439
Ref: library/curses panel cursespanel-functions6298549
Ref: 221b6298549
Ref: library/curses panel functions6298549
Ref: 221c6298549
Ref: library/curses panel curses panel bottom_panel6298636
Ref: 221d6298636
Ref: library/curses panel curses panel new_panel6298721
Ref: 221e6298721
Ref: library/curses panel curses panel top_panel6298998
Ref: 221f6298998
Ref: library/curses panel curses panel update_panels6299080
Ref: 22206299080
Node: Panel 对象6299272
Ref: library/curses panel curses-panel-objects6299382
Ref: 22216299382
Ref: library/curses panel panel-objects6299382
Ref: 22226299382
Ref: library/curses panel curses panel Panel above6299686
Ref: 22236299686
Ref: library/curses panel curses panel Panel below6299757
Ref: 22246299757
Ref: library/curses panel curses panel Panel bottom6299828
Ref: 22256299828
Ref: library/curses panel curses panel Panel hidden6299891
Ref: 22266299891
Ref: library/curses panel curses panel Panel hide6300013
Ref: 22276300013
Ref: library/curses panel curses panel Panel move6300129
Ref: 22286300129
Ref: library/curses panel curses panel Panel replace6300210
Ref: 22296300210
Ref: library/curses panel curses panel Panel set_userptr6300301
Ref: 222a6300301
Ref: library/curses panel curses panel Panel show6300477
Ref: 222b6300477
Ref: library/curses panel curses panel Panel top6300556
Ref: 222c6300556
Ref: library/curses panel curses panel Panel userptr6300616
Ref: 222d6300616
Ref: library/curses panel curses panel Panel window6300719
Ref: 222e6300719
Node: platform --- 获取底层平台的标识数据6300797
Ref: library/platform doc6301000
Ref: 222f6301000
Ref: library/platform module-platform6301000
Ref: cf6301000
Ref: library/platform platform-access-to-underlying-platform-s-identifying-data6301000
Ref: 22306301000
Ref: platform --- 获取底层平台的标识数据-Footnote-16301425
Node: 跨平台6301492
Ref: library/platform cross-platform6301603
Ref: 22316301603
Ref: library/platform platform architecture6301641
Ref: 10266301641
Ref: library/platform platform machine6302865
Ref: 22326302865
Ref: library/platform platform node6303012
Ref: 22336303012
Ref: library/platform platform platform6303185
Ref: 102b6303185
Ref: library/platform platform processor6304010
Ref: 22356304010
Ref: library/platform platform python_build6304322
Ref: 22366304322
Ref: library/platform platform python_compiler6304474
Ref: 22376304474
Ref: library/platform platform python_branch6304590
Ref: 22386304590
Ref: library/platform platform python_implementation6304697
Ref: 22396304697
Ref: library/platform platform python_revision6304887
Ref: 223a6304887
Ref: library/platform platform python_version6304999
Ref: 223b6304999
Ref: library/platform platform python_version_tuple6305238
Ref: 223c6305238
Ref: library/platform platform release6305499
Ref: 223d6305499
Ref: library/platform platform system6305670
Ref: 223e6305670
Ref: library/platform platform system_alias6305875
Ref: 22346305875
Ref: library/platform platform version6306127
Ref: 223f6306127
Ref: library/platform platform uname6306296
Ref: 10296306296
Node: Java平台6306960
Ref: library/platform java-platform6307093
Ref: 22406307093
Ref: library/platform platform java_ver6307134
Ref: 22416307134
Node: Windows平台6307566
Ref: library/platform windows-platform6307702
Ref: 22426307702
Ref: library/platform platform win32_ver6307749
Ref: f286307749
Ref: library/platform platform win32_edition6308395
Ref: 22436308395
Ref: library/platform platform win32_is_iot6308640
Ref: 22446308640
Node: Mac OS平台6308818
Ref: library/platform mac-os-platform6308955
Ref: 22456308955
Ref: library/platform platform mac_ver6309000
Ref: 102c6309000
Node: Unix 平台6309375
Ref: library/platform unix-platforms6309490
Ref: 22466309490
Ref: library/platform platform libc_ver6309533
Ref: 10286309533
Node: errno --- 标准 errno 系统符号6310113
Ref: library/errno doc6310309
Ref: 22476310309
Ref: library/errno errno-standard-errno-system-symbols6310309
Ref: 22486310309
Ref: library/errno module-errno6310309
Ref: 7c6310309
Ref: library/errno errno errorcode6310654
Ref: 22496310654
Ref: library/errno errno EPERM6311128
Ref: 224a6311128
Ref: library/errno errno ENOENT6311178
Ref: 224b6311178
Ref: library/errno errno ESRCH6311232
Ref: 224c6311232
Ref: library/errno errno EINTR6311276
Ref: 6616311276
Ref: library/errno errno EIO6311418
Ref: 224d6311418
Ref: library/errno errno ENXIO6311458
Ref: 224e6311458
Ref: library/errno errno E2BIG6311511
Ref: 224f6311511
Ref: library/errno errno ENOEXEC6311561
Ref: 22506311561
Ref: library/errno errno EBADF6311613
Ref: 22516311613
Ref: library/errno errno ECHILD6311663
Ref: 22526311663
Ref: library/errno errno EAGAIN6311708
Ref: 1f476311708
Ref: library/errno errno ENOMEM6311747
Ref: 22536311747
Ref: library/errno errno EACCES6311792
Ref: 22546311792
Ref: library/errno errno EFAULT6311837
Ref: 22556311837
Ref: library/errno errno ENOTBLK6311885
Ref: 22566311885
Ref: library/errno errno EBUSY6311934
Ref: 22576311934
Ref: library/errno errno EEXIST6311984
Ref: 22586311984
Ref: library/errno errno EXDEV6312032
Ref: 1f1d6312032
Ref: library/errno errno ENODEV6312079
Ref: 22596312079
Ref: library/errno errno ENOTDIR6312124
Ref: 225a6312124
Ref: library/errno errno EISDIR6312170
Ref: 225b6312170
Ref: library/errno errno EINVAL6312212
Ref: fd96312212
Ref: library/errno errno ENFILE6312260
Ref: 225c6312260
Ref: library/errno errno EMFILE6312308
Ref: 225d6312308
Ref: library/errno errno ENOTTY6312362
Ref: 225e6312362
Ref: library/errno errno ETXTBSY6312410
Ref: 225f6312410
Ref: library/errno errno EFBIG6312459
Ref: 22606312459
Ref: library/errno errno ENOSPC6312503
Ref: 22616312503
Ref: library/errno errno ESPIPE6312560
Ref: 22626312560
Ref: library/errno errno EROFS6312605
Ref: 22636312605
Ref: library/errno errno EMLINK6312655
Ref: 22646312655
Ref: library/errno errno EPIPE6312700
Ref: 22656312700
Ref: library/errno errno EDOM6312747
Ref: 22666312747
Ref: library/errno errno ERANGE6312808
Ref: 22676312808
Ref: library/errno errno EDEADLK6312871
Ref: 22686312871
Ref: library/errno errno ENAMETOOLONG6312926
Ref: 22696312926
Ref: library/errno errno ENOLCK6312980
Ref: 226a6312980
Ref: library/errno errno ENOSYS6313037
Ref: 226b6313037
Ref: library/errno errno ENOTEMPTY6313085
Ref: 226c6313085
Ref: library/errno errno ELOOP6313133
Ref: 226d6313133
Ref: library/errno errno EWOULDBLOCK6313192
Ref: 226e6313192
Ref: library/errno errno ENOMSG6313245
Ref: 226f6313245
Ref: library/errno errno EIDRM6313305
Ref: 22706313305
Ref: library/errno errno ECHRNG6313355
Ref: 22716313355
Ref: library/errno errno EL2NSYNC6313412
Ref: 22726313412
Ref: library/errno errno EL3HLT6313465
Ref: 22736313465
Ref: library/errno errno EL3RST6313516
Ref: 22746313516
Ref: library/errno errno ELNRNG6313564
Ref: 22756313564
Ref: library/errno errno EUNATCH6313621
Ref: 22766313621
Ref: library/errno errno ENOCSI6313676
Ref: 22776313676
Ref: library/errno errno EL2HLT6313735
Ref: 22786313735
Ref: library/errno errno EBADE6313786
Ref: 22796313786
Ref: library/errno errno EBADR6313833
Ref: 227a6313833
Ref: library/errno errno EXFULL6313889
Ref: 227b6313889
Ref: library/errno errno ENOANO6313934
Ref: 227c6313934
Ref: library/errno errno EBADRQC6313979
Ref: 227d6313979
Ref: library/errno errno EBADSLT6314033
Ref: 227e6314033
Ref: library/errno errno EDEADLOCK6314082
Ref: 227f6314082
Ref: library/errno errno EBFONT6314142
Ref: 22806314142
Ref: library/errno errno ENOSTR6314202
Ref: 22816314202
Ref: library/errno errno ENODATA6314250
Ref: 22826314250
Ref: library/errno errno ETIME6314305
Ref: 22836314305
Ref: library/errno errno ENOSR6314355
Ref: 22846314355
Ref: library/errno errno ENONET6314402
Ref: 22856314402
Ref: library/errno errno ENOPKG6314456
Ref: 22866314456
Ref: library/errno errno EREMOTE6314501
Ref: 22876314501
Ref: library/errno errno ENOLINK6314553
Ref: 22886314553
Ref: library/errno errno EADV6314605
Ref: 22896314605
Ref: library/errno errno ESRMNT6314648
Ref: 228a6314648
Ref: library/errno errno ECOMM6314693
Ref: 228b6314693
Ref: library/errno errno EPROTO6314746
Ref: 228c6314746
Ref: library/errno errno EMULTIHOP6314791
Ref: 228d6314791
Ref: library/errno errno EDOTDOT6314842
Ref: 228e6314842
Ref: library/errno errno EBADMSG6314892
Ref: 228f6314892
Ref: library/errno errno EOVERFLOW6314941
Ref: 22906314941
Ref: library/errno errno ENOTUNIQ6315016
Ref: 22916315016
Ref: library/errno errno EBADFD6315078
Ref: 22926315078
Ref: library/errno errno EREMCHG6315144
Ref: 22936315144
Ref: library/errno errno ELIBACC6315199
Ref: 22946315199
Ref: library/errno errno ELIBBAD6315263
Ref: 22956315263
Ref: library/errno errno ELIBSCN6315324
Ref: 22966315324
Ref: library/errno errno ELIBMAX6315391
Ref: 22976315391
Ref: library/errno errno ELIBEXEC6315455
Ref: 22986315455
Ref: library/errno errno EILSEQ6315517
Ref: 22996315517
Ref: library/errno errno ERESTART6315568
Ref: 229a6315568
Ref: library/errno errno ESTRPIPE6315636
Ref: 229b6315636
Ref: library/errno errno EUSERS6315686
Ref: 229c6315686
Ref: library/errno errno ENOTSOCK6315731
Ref: 229d6315731
Ref: library/errno errno EDESTADDRREQ6315805
Ref: 229e6315805
Ref: library/errno errno EMSGSIZE6315862
Ref: 229f6315862
Ref: library/errno errno EPROTOTYPE6315909
Ref: 22a06315909
Ref: library/errno errno ENOPROTOOPT6315976
Ref: 22a16315976
Ref: library/errno errno EPROTONOSUPPORT6316029
Ref: 22a26316029
Ref: library/errno errno ESOCKTNOSUPPORT6316089
Ref: 22a36316089
Ref: library/errno errno EOPNOTSUPP6316158
Ref: 22a46316158
Ref: library/errno errno EPFNOSUPPORT6316231
Ref: 22a56316231
Ref: library/errno errno EAFNOSUPPORT6316291
Ref: 22a66316291
Ref: library/errno errno EADDRINUSE6316357
Ref: 22a76316357
Ref: library/errno errno EADDRNOTAVAIL6316412
Ref: 22a86316412
Ref: library/errno errno ENETDOWN6316479
Ref: 22a96316479
Ref: library/errno errno ENETUNREACH6316529
Ref: ff46316529
Ref: library/errno errno ENETRESET6316582
Ref: 22aa6316582
Ref: library/errno errno ECONNABORTED6316648
Ref: 22ab6316648
Ref: library/errno errno ECONNRESET6316711
Ref: 22ac6316711
Ref: library/errno errno ENOBUFS6316769
Ref: 22ad6316769
Ref: library/errno errno EISCONN6316833
Ref: 22ae6316833
Ref: library/errno errno ENOTCONN6316888
Ref: 22af6316888
Ref: library/errno errno ESHUTDOWN6316944
Ref: 22b06316944
Ref: library/errno errno ETOOMANYREFS6317013
Ref: 22b16317013
Ref: library/errno errno ETIMEDOUT6317079
Ref: 22b26317079
Ref: library/errno errno ECONNREFUSED6317127
Ref: 22b36317127
Ref: library/errno errno EHOSTDOWN6317178
Ref: 22b46317178
Ref: library/errno errno EHOSTUNREACH6317229
Ref: 22b56317229
Ref: library/errno errno EALREADY6317292
Ref: 22b66317292
Ref: library/errno errno EINPROGRESS6317345
Ref: 22b76317345
Ref: library/errno errno ESTALE6317401
Ref: 22b86317401
Ref: library/errno errno EUCLEAN6317460
Ref: 22b96317460
Ref: library/errno errno ENOTNAM6317512
Ref: 22ba6317512
Ref: library/errno errno ENAVAIL6317577
Ref: 22bb6317577
Ref: library/errno errno EISNAM6317639
Ref: 22bc6317639
Ref: library/errno errno EREMOTEIO6317693
Ref: 22bd6317693
Ref: library/errno errno EDQUOT6317746
Ref: 22be6317746
Node: ctypes --- Python 的外部函数库6317791
Ref: library/ctypes doc6317932
Ref: 22bf6317932
Ref: library/ctypes ctypes-a-foreign-function-library-for-python6317932
Ref: 22c06317932
Ref: library/ctypes module-ctypes6317932
Ref: 2b6317932
Node: ctypes 教程6318351
Ref: library/ctypes ctypes-ctypes-tutorial6318465
Ref: 22c16318465
Ref: library/ctypes ctypes-tutorial6318465
Ref: 22c26318465
Node: 载入动态连接库6319697
Ref: library/ctypes ctypes-loading-dynamic-link-libraries6319819
Ref: 22c56319819
Ref: library/ctypes loading-dynamic-link-libraries6319819
Ref: 22c66319819
Node: 操作导入的动态链接库中的函数6321732
Ref: library/ctypes accessing-functions-from-loaded-dlls6321875
Ref: 22c76321875
Ref: library/ctypes ctypes-accessing-functions-from-loaded-dlls6321875
Ref: 22c86321875
Node: 调用函数6324139
Ref: library/ctypes calling-functions6324279
Ref: 22c96324279
Ref: library/ctypes ctypes-calling-functions6324279
Ref: 22ca6324279
Node: 基础数据类型6326693
Ref: library/ctypes ctypes-fundamental-data-types6326812
Ref: 22cb6326812
Ref: library/ctypes fundamental-data-types6326812
Ref: 22cc6326812
Node: 调用函数，继续6334774
Ref: library/ctypes calling-functions-continued6334923
Ref: 22dd6334923
Ref: library/ctypes ctypes-calling-functions-continued6334923
Ref: 22de6334923
Node: 使用自定义的数据类型调用函数6336003
Ref: library/ctypes calling-functions-with-your-own-custom-data-types6336174
Ref: 22df6336174
Ref: library/ctypes ctypes-calling-functions-with-own-custom-data-types6336174
Ref: 22e06336174
Node: 指定必选参数的类型 函数原型6336915
Ref: library/ctypes ctypes-specifying-required-argument-types6337077
Ref: 22e16337077
Ref: library/ctypes specifying-the-required-argument-types-function-prototypes6337077
Ref: 22e26337077
Node: 返回类型6338740
Ref: library/ctypes ctypes-return-types6338891
Ref: 22e36338891
Ref: library/ctypes return-types6338891
Ref: 22e46338891
Node: 传递指针 或者传递引用6341436
Ref: library/ctypes ctypes-passing-pointers6341565
Ref: 22e66341565
Ref: library/ctypes passing-pointers-or-passing-parameters-by-reference6341565
Ref: 22e76341565
Node: 结构体和联合6342579
Ref: library/ctypes ctypes-structures-unions6342740
Ref: 22ea6342740
Ref: library/ctypes structures-and-unions6342740
Ref: 22eb6342740
Ref: library/ctypes ctypes-structureunion-alignment-byte-order6344709
Ref: 22ee6344709
Node: 结构体/联合 字段对齐及字节顺序6345006
Ref: library/ctypes structure-union-alignment-and-byte-order6345166
Ref: 22ef6345166
Node: 结构体和联合中的位域6345852
Ref: library/ctypes bit-fields-in-structures-and-unions6346000
Ref: 22f26346000
Ref: library/ctypes ctypes-bit-fields-in-structures-unions6346000
Ref: 22f36346000
Node: 数组6346520
Ref: library/ctypes arrays6346630
Ref: 22f46346630
Ref: library/ctypes ctypes-arrays6346630
Ref: 22f56346630
Node: 指针6347839
Ref: library/ctypes ctypes-pointers6347937
Ref: 22f66347937
Ref: library/ctypes pointers6347937
Ref: 22f76347937
Node: 类型强制转换6350471
Ref: library/ctypes ctypes-type-conversions6350578
Ref: 22fa6350578
Ref: library/ctypes type-conversions6350578
Ref: 22fb6350578
Node: 不完整类型6353027
Ref: library/ctypes ctypes-incomplete-types6353140
Ref: 22fc6353140
Ref: library/ctypes incomplete-types6353140
Ref: 22fd6353140
Node: 回调函数6354684
Ref: library/ctypes callback-functions6354805
Ref: 22fe6354805
Ref: library/ctypes ctypes-callback-functions6354805
Ref: 22ff6354805
Node: 访问 dll 中导出的值6358384
Ref: library/ctypes accessing-values-exported-from-dlls6358496
Ref: 23036358496
Ref: library/ctypes ctypes-accessing-values-exported-from-dlls6358496
Ref: 23046358496
Node: 意外6361103
Ref: library/ctypes ctypes-surprises6361221
Ref: 23076361221
Ref: library/ctypes surprises6361221
Ref: 23086361221
Node: 变长数据类型6363219
Ref: library/ctypes ctypes-variable-sized-data-types6363302
Ref: 23096363302
Ref: library/ctypes variable-sized-data-types6363302
Ref: 230a6363302
Node: ctypes 参考手册6364645
Ref: library/ctypes ctypes-ctypes-reference6364759
Ref: 230c6364759
Ref: library/ctypes ctypes-reference6364759
Ref: 230d6364759
Node: 寻找动态链接库6365055
Ref: library/ctypes ctypes-finding-shared-libraries6365162
Ref: 230e6365162
Ref: library/ctypes finding-shared-libraries6365162
Ref: 230f6365162
Node: 加载动态链接库6367488
Ref: library/ctypes ctypes-loading-shared-libraries6367616
Ref: 23106367616
Ref: library/ctypes loading-shared-libraries6367616
Ref: 23116367616
Ref: library/ctypes ctypes CDLL6367793
Ref: 1c26367793
Ref: library/ctypes ctypes OleDLL6368733
Ref: 23126368733
Ref: library/ctypes ctypes WinDLL6369318
Ref: 23146369318
Ref: library/ctypes ctypes PyDLL6369909
Ref: 23156369909
Ref: library/ctypes ctypes PyDLL _handle6373252
Ref: 231a6373252
Ref: library/ctypes ctypes PyDLL _name6373319
Ref: 231b6373319
Ref: library/ctypes ctypes LibraryLoader6373622
Ref: 231c6373622
Ref: library/ctypes ctypes LibraryLoader LoadLibrary6374065
Ref: 231d6374065
Ref: 加载动态链接库-Footnote-16375254
Node: 外部函数6375320
Ref: library/ctypes ctypes-foreign-functions6375439
Ref: 231e6375439
Ref: library/ctypes foreign-functions6375439
Ref: 231f6375439
Ref: library/ctypes ctypes _FuncPtr6375787
Ref: 23206375787
Ref: library/ctypes ctypes _FuncPtr restype6376028
Ref: 23216376028
Ref: library/ctypes ctypes _FuncPtr argtypes6376696
Ref: 23236376696
Ref: library/ctypes ctypes _FuncPtr errcheck6377769
Ref: 23226377769
Ref: library/ctypes ctypes ArgumentError6378599
Ref: 23246378599
Node: 函数原型6378911
Ref: library/ctypes ctypes-function-prototypes6379021
Ref: 23256379021
Ref: library/ctypes function-prototypes6379021
Ref: 23266379021
Ref: library/ctypes ctypes CFUNCTYPE6379534
Ref: 23006379534
Ref: library/ctypes ctypes WINFUNCTYPE6380001
Ref: 23016380001
Ref: library/ctypes ctypes PYFUNCTYPE6380427
Ref: 23276380427
Node: 工具函数6385473
Ref: library/ctypes ctypes-utility-functions6385586
Ref: 23286385586
Ref: library/ctypes utility-functions6385586
Ref: 23296385586
Ref: library/ctypes ctypes addressof6385631
Ref: 232a6385631
Ref: library/ctypes ctypes alignment6385862
Ref: 232b6385862
Ref: library/ctypes ctypes byref6386019
Ref: 22e86386019
Ref: library/ctypes ctypes cast6386485
Ref: 10236386485
Ref: library/ctypes ctypes create_string_buffer6386767
Ref: 22dc6386767
Ref: library/ctypes ctypes create_unicode_buffer6387519
Ref: fbd6387519
Ref: library/ctypes ctypes DllCanUnloadNow6388271
Ref: 232c6388271
Ref: library/ctypes ctypes DllGetClassObject6388493
Ref: 232d6388493
Ref: library/ctypes ctypes util find_library6388731
Ref: 6136388731
Ref: library/ctypes ctypes util find_msvcrt6389099
Ref: 232e6389099
Ref: library/ctypes ctypes FormatError6389487
Ref: 232f6389487
Ref: library/ctypes ctypes GetLastError6389757
Ref: 22e56389757
Ref: library/ctypes ctypes get_errno6390003
Ref: 23166390003
Ref: library/ctypes ctypes get_last_error6390232
Ref: 23186390232
Ref: library/ctypes ctypes memmove6390493
Ref: 23306390493
Ref: library/ctypes ctypes memset6390714
Ref: 23316390714
Ref: library/ctypes ctypes POINTER6390939
Ref: 22f96390939
Ref: library/ctypes ctypes pointer6391183
Ref: 22e96391183
Ref: library/ctypes ctypes resize6391481
Ref: 230b6391481
Ref: library/ctypes ctypes set_errno6391792
Ref: 23176391792
Ref: library/ctypes ctypes set_last_error6392060
Ref: 23196392060
Ref: library/ctypes ctypes sizeof6392361
Ref: 23326392361
Ref: library/ctypes ctypes string_at6392535
Ref: 23336392535
Ref: library/ctypes ctypes WinError6392889
Ref: 23346392889
Ref: library/ctypes ctypes wstring_at6393349
Ref: 23356393349
Node: 数据类型<2>6393740
Ref: library/ctypes ctypes-data-types6393862
Ref: 23366393862
Ref: library/ctypes data-types6393862
Ref: 23376393862
Ref: library/ctypes ctypes _CData6393907
Ref: 10c06393907
Ref: library/ctypes ctypes _CData from_buffer6394480
Ref: 233a6394480
Ref: library/ctypes ctypes _CData from_buffer_copy6394999
Ref: 233b6394999
Ref: library/ctypes ctypes _CData from_address6395513
Ref: 233c6395513
Ref: library/ctypes ctypes _CData from_param6395805
Ref: 233d6395805
Ref: library/ctypes ctypes _CData in_dll6396335
Ref: 233e6396335
Ref: library/ctypes ctypes _CData _b_base_6396584
Ref: 233f6396584
Ref: library/ctypes ctypes _CData _b_needsfree_6396846
Ref: 23406396846
Ref: library/ctypes ctypes _CData _objects6397002
Ref: 23386397002
Node: 基础数据类型<2>6397296
Ref: library/ctypes ctypes-fundamental-data-types-26397427
Ref: 23416397427
Ref: library/ctypes id16397427
Ref: 23426397427
Ref: library/ctypes ctypes _SimpleCData6397482
Ref: 23436397482
Ref: library/ctypes ctypes _SimpleCData value6397894
Ref: 23446397894
Ref: library/ctypes ctypes c_byte6399146
Ref: 22d06399146
Ref: library/ctypes ctypes c_char6399343
Ref: 22ce6399343
Ref: library/ctypes ctypes c_char_p6399554
Ref: 22da6399554
Ref: library/ctypes ctypes c_double6399858
Ref: ec16399858
Ref: library/ctypes ctypes c_longdouble6399986
Ref: ec26399986
Ref: library/ctypes ctypes c_float6400241
Ref: 22d96400241
Ref: library/ctypes ctypes c_int6400367
Ref: 22c36400367
Ref: library/ctypes ctypes c_int86400627
Ref: 23456400627
Ref: library/ctypes ctypes c_int166400760
Ref: 23466400760
Ref: library/ctypes ctypes c_int326400896
Ref: 23476400896
Ref: library/ctypes ctypes c_int646401030
Ref: 23486401030
Ref: library/ctypes ctypes c_long6401168
Ref: 22c46401168
Ref: library/ctypes ctypes c_longlong6401329
Ref: 22d66401329
Ref: library/ctypes ctypes c_short6401499
Ref: 22d26401499
Ref: library/ctypes ctypes c_size_t6401662
Ref: 22d86401662
Ref: library/ctypes ctypes c_ssize_t6401732
Ref: bd96401732
Ref: library/ctypes ctypes c_ubyte6401828
Ref: 22d16401828
Ref: library/ctypes ctypes c_uint6402028
Ref: 22d46402028
Ref: library/ctypes ctypes c_uint86402292
Ref: 23496402292
Ref: library/ctypes ctypes c_uint166402429
Ref: 234a6402429
Ref: library/ctypes ctypes c_uint326402568
Ref: 234b6402568
Ref: library/ctypes ctypes c_uint646402707
Ref: 234c6402707
Ref: library/ctypes ctypes c_ulong6402849
Ref: 22d56402849
Ref: library/ctypes ctypes c_ulonglong6403013
Ref: 22d76403013
Ref: library/ctypes ctypes c_ushort6403186
Ref: 22d36403186
Ref: library/ctypes ctypes c_void_p6403352
Ref: 22db6403352
Ref: library/ctypes ctypes c_wchar6403511
Ref: 22cf6403511
Ref: library/ctypes ctypes c_wchar_p6403756
Ref: ea96403756
Ref: library/ctypes ctypes c_bool6403960
Ref: 22cd6403960
Ref: library/ctypes ctypes HRESULT6404174
Ref: 23136404174
Ref: library/ctypes ctypes py_object6404325
Ref: 234d6404325
Node: 结构化数据类型6404710
Ref: library/ctypes ctypes-structured-data-types6404841
Ref: 234e6404841
Ref: library/ctypes structured-data-types6404841
Ref: 234f6404841
Ref: library/ctypes ctypes Union6404901
Ref: 22ed6404901
Ref: library/ctypes ctypes BigEndianStructure6404996
Ref: 22f06404996
Ref: library/ctypes ctypes LittleEndianStructure6405110
Ref: 22f16405110
Ref: library/ctypes ctypes Structure6405350
Ref: 22ec6405350
Ref: library/ctypes ctypes Structure _fields_6405750
Ref: 23506405750
Ref: library/ctypes ctypes Structure _pack_6407157
Ref: 23516407157
Ref: library/ctypes ctypes Structure _anonymous_6407408
Ref: 23526407408
Node: 数组与指针6409490
Ref: library/ctypes arrays-and-pointers6409591
Ref: 23536409591
Ref: library/ctypes ctypes-arrays-pointers6409591
Ref: 23546409591
Ref: library/ctypes ctypes Array6409641
Ref: 101c6409641
Ref: library/ctypes ctypes Array _length_6410105
Ref: 23556410105
Ref: library/ctypes ctypes Array _type_6410300
Ref: 23566410300
Ref: library/ctypes ctypes _Pointer6410461
Ref: 23576410461
Ref: library/ctypes ctypes _Pointer _type_6411085
Ref: 23586411085
Ref: library/ctypes ctypes _Pointer contents6411149
Ref: 22f86411149
Node: 并发执行6411296
Ref: library/concurrency doc6411427
Ref: 23596411427
Ref: library/concurrency concurrency6411427
Ref: 235a6411427
Ref: library/concurrency concurrent-execution6411427
Ref: 235b6411427
Node: threading --- 基于线程的并行6412604
Ref: library/threading doc6412738
Ref: 235c6412738
Ref: library/threading module-threading6412738
Ref: 10a6412738
Ref: library/threading threading-thread-based-parallelism6412738
Ref: 235d6412738
Ref: library/threading threading active_count6413863
Ref: 235e6413863
Ref: library/threading threading current_thread6414045
Ref: 23606414045
Ref: library/threading threading excepthook6414304
Ref: 2326414304
Ref: library/threading threading get_ident6415557
Ref: ab76415557
Ref: library/threading threading get_native_id6415902
Ref: 2346415902
Ref: library/threading threading enumerate6416316
Ref: 235f6416316
Ref: library/threading threading main_thread6416602
Ref: 8f76416602
Ref: library/threading threading settrace6416787
Ref: 23616416787
Ref: library/threading threading setprofile6417029
Ref: 23626417029
Ref: library/threading threading stack_size6417281
Ref: 23636417281
Ref: library/threading threading TIMEOUT_MAX6418377
Ref: 23646418377
Ref: threading --- 基于线程的并行-Footnote-16419496
Node: 线程本地数据6419564
Ref: library/threading thread-local-data6419675
Ref: 23666419675
Ref: library/threading threading local6420008
Ref: 23026420008
Node: 线程对象6420171
Ref: library/threading id16420300
Ref: 23676420300
Ref: library/threading thread-objects6420300
Ref: 23686420300
Ref: library/threading threading Thread6422826
Ref: 2356422826
Ref: library/threading threading Thread start6423962
Ref: 20e56423962
Ref: library/threading threading Thread run6424312
Ref: 2336424312
Ref: library/threading threading Thread join6424691
Ref: b686424691
Ref: library/threading threading Thread name6425835
Ref: 236a6425835
Ref: library/threading threading Thread getName6426008
Ref: 236c6426008
Ref: library/threading threading Thread setName6426036
Ref: 236d6426036
Ref: library/threading threading Thread ident6426181
Ref: 20286426181
Ref: library/threading threading Thread native_id6426532
Ref: 2366426532
Ref: library/threading threading Thread is_alive6427285
Ref: 23696427285
Ref: library/threading threading Thread daemon6427581
Ref: 236b6427581
Ref: library/threading threading Thread isDaemon6428069
Ref: 236e6428069
Ref: library/threading threading Thread setDaemon6428098
Ref: 236f6428098
Node: 锁对象6428247
Ref: library/threading id26428373
Ref: 23706428373
Ref: library/threading lock-objects6428373
Ref: 23716428373
Ref: library/threading threading Lock6429636
Ref: 23746429636
Ref: library/threading threading Lock acquire6429975
Ref: 7756429975
Ref: library/threading threading Lock release6431118
Ref: 23726431118
Ref: library/threading threading Lock locked6431538
Ref: 23756431538
Node: 递归锁对象6431614
Ref: library/threading id36431740
Ref: 23766431740
Ref: library/threading rlock-objects6431740
Ref: 23776431740
Ref: library/threading threading RLock6432532
Ref: bf76432532
Ref: library/threading threading RLock acquire6432927
Ref: 7766432927
Ref: library/threading threading RLock release6434234
Ref: 23786434234
Node: 条件对象6434812
Ref: library/threading condition-objects6434944
Ref: 23796434944
Ref: library/threading id46434944
Ref: 237a6434944
Ref: library/threading threading Condition6437893
Ref: ab26437893
Ref: library/threading threading Condition acquire6438384
Ref: 237b6438384
Ref: library/threading threading Condition release6438549
Ref: 237c6438549
Ref: library/threading threading Condition wait6438668
Ref: 23656438668
Ref: library/threading threading Condition wait_for6439956
Ref: 237f6439956
Ref: library/threading threading Condition notify6440809
Ref: 237d6440809
Ref: library/threading threading Condition notify_all6441637
Ref: 237e6441637
Node: 信号量对象6441983
Ref: library/threading id56442112
Ref: 23806442112
Ref: library/threading semaphore-objects6442112
Ref: 23816442112
Ref: library/threading threading Semaphore6442792
Ref: ab36442792
Ref: library/threading threading Semaphore acquire6443461
Ref: bf46443461
Ref: library/threading threading Semaphore release6444703
Ref: 23826444703
Ref: library/threading threading BoundedSemaphore6444923
Ref: ab46444923
Node: Semaphore 例子6445437
Ref: library/threading semaphore-example6445505
Ref: 23836445505
Ref: library/threading semaphore-examples6445505
Ref: 23846445505
Node: 事件对象6446254
Ref: library/threading event-objects6446386
Ref: 23856446386
Ref: library/threading id66446386
Ref: 23866446386
Ref: library/threading threading Event6446781
Ref: ab56446781
Ref: library/threading threading Event is_set6447168
Ref: 23896447168
Ref: library/threading threading Event set6447258
Ref: 23876447258
Ref: library/threading threading Event clear6447475
Ref: 23886447475
Ref: library/threading threading Event wait6447708
Ref: cbf6447708
Node: 定时器对象6448484
Ref: library/threading id76448613
Ref: 238a6448613
Ref: library/threading timer-objects6448613
Ref: 238b6448613
Ref: library/threading threading Timer6449286
Ref: ab66449286
Ref: library/threading threading Timer cancel6449730
Ref: 238c6449730
Node: 栅栏对象6449892
Ref: library/threading barrier-objects6450057
Ref: 238d6450057
Ref: library/threading threading Barrier6450918
Ref: b676450918
Ref: library/threading threading Barrier wait6451290
Ref: 238e6451290
Ref: library/threading threading Barrier reset6452432
Ref: 238f6452432
Ref: library/threading threading Barrier abort6452817
Ref: 23906452817
Ref: library/threading threading Barrier parties6453248
Ref: 23916453248
Ref: library/threading threading Barrier n_waiting6453325
Ref: 23926453325
Ref: library/threading threading Barrier broken6453416
Ref: 23936453416
Ref: library/threading threading BrokenBarrierError6453516
Ref: b696453516
Node: 在 with 语句中使用锁、条件和信号量6453728
Ref: library/threading using-locks-conditions-and-semaphores-in-the-with-statement6453869
Ref: 23946453869
Ref: library/threading with-locks6453869
Ref: 23736453869
Node: multiprocessing --- 基于进程的并行6454629
Ref: library/multiprocessing doc6454845
Ref: 23956454845
Ref: library/multiprocessing module-multiprocessing6454845
Ref: b86454845
Ref: library/multiprocessing multiprocessing-process-based-parallelism6454845
Ref: 23966454845
Ref: multiprocessing --- 基于进程的并行-Footnote-16455165
Node: 概述<9>6455237
Ref: library/multiprocessing introduction6455339
Ref: 23976455339
Node: Process 类6456677
Ref: library/multiprocessing the-process-class6456767
Ref: 23986456767
Node: 上下文和启动方法6457908
Ref: library/multiprocessing contexts-and-start-methods6458034
Ref: 239a6458034
Ref: library/multiprocessing multiprocessing-start-methods6458095
Ref: 87f6458095
Ref: 上下文和启动方法-Footnote-16462211
Node: 在进程之间交换对象6462254
Ref: library/multiprocessing exchanging-objects-between-processes6462384
Ref: 239d6462384
Node: 进程间同步6463976
Ref: library/multiprocessing synchronization-between-processes6464103
Ref: 23a06464103
Node: 进程间共享状态6464736
Ref: library/multiprocessing sharing-state-between-processes6464854
Ref: 23a16464854
Node: 使用工作进程6467757
Ref: library/multiprocessing using-a-pool-of-workers6467851
Ref: 23ac6467851
Node: 参考6470820
Ref: library/multiprocessing reference6470943
Ref: 23ad6470943
Node: Process 和异常6471423
Ref: library/multiprocessing process-and-exceptions6471507
Ref: 23ae6471507
Ref: library/multiprocessing multiprocessing Process6471567
Ref: 3ba6471567
Ref: library/multiprocessing multiprocessing Process run6472811
Ref: 239b6472811
Ref: library/multiprocessing multiprocessing Process start6473141
Ref: 23b16473141
Ref: library/multiprocessing multiprocessing Process join6473366
Ref: 23b26473366
Ref: library/multiprocessing multiprocessing Process name6473990
Ref: 23af6473990
Ref: library/multiprocessing multiprocessing Process is_alive6474407
Ref: 23b46474407
Ref: library/multiprocessing multiprocessing Process daemon6474617
Ref: 23b06474617
Ref: library/multiprocessing multiprocessing Process pid6475369
Ref: 23b56475369
Ref: library/multiprocessing multiprocessing Process exitcode6475471
Ref: 23b36475471
Ref: library/multiprocessing multiprocessing Process authkey6475648
Ref: 23b66475648
Ref: library/multiprocessing multiprocessing Process sentinel6476136
Ref: a2d6476136
Ref: library/multiprocessing multiprocessing Process terminate6476751
Ref: 23b86476751
Ref: library/multiprocessing multiprocessing Process kill6477404
Ref: 3b96477404
Ref: library/multiprocessing multiprocessing Process close6477563
Ref: 3b86477563
Ref: library/multiprocessing multiprocessing ProcessError6478728
Ref: 23b96478728
Ref: library/multiprocessing multiprocessing BufferTooShort6478829
Ref: 23ba6478829
Ref: library/multiprocessing multiprocessing AuthenticationError6479138
Ref: 23bb6479138
Ref: library/multiprocessing multiprocessing TimeoutError6479230
Ref: 23bc6479230
Node: 管道和队列6479315
Ref: library/multiprocessing pipes-and-queues6479417
Ref: 23bd6479417
Ref: library/multiprocessing multiprocessing Pipe6482731
Ref: 239f6482731
Ref: library/multiprocessing multiprocessing Queue6483134
Ref: 239e6483134
Ref: library/multiprocessing multiprocessing Queue qsize6483709
Ref: 23ca6483709
Ref: library/multiprocessing multiprocessing Queue empty6484068
Ref: 23c66484068
Ref: library/multiprocessing multiprocessing Queue full6484258
Ref: 23cb6484258
Ref: library/multiprocessing multiprocessing Queue put6484447
Ref: 103c6484447
Ref: library/multiprocessing multiprocessing Queue put_nowait6485217
Ref: 23cc6485217
Ref: library/multiprocessing multiprocessing Queue get6485298
Ref: 103d6485298
Ref: library/multiprocessing multiprocessing Queue get_nowait6486076
Ref: 23c76486076
Ref: library/multiprocessing multiprocessing Queue close6486321
Ref: 23cd6486321
Ref: library/multiprocessing multiprocessing Queue join_thread6486576
Ref: 23ce6486576
Ref: library/multiprocessing multiprocessing Queue cancel_join_thread6487138
Ref: 23c86487138
Ref: library/multiprocessing multiprocessing SimpleQueue6488072
Ref: 23be6488072
Ref: library/multiprocessing multiprocessing SimpleQueue empty6488215
Ref: 23cf6488215
Ref: library/multiprocessing multiprocessing SimpleQueue get6488321
Ref: 23d06488321
Ref: library/multiprocessing multiprocessing SimpleQueue put6488400
Ref: 23d16488400
Ref: library/multiprocessing multiprocessing JoinableQueue6488467
Ref: 23bf6488467
Ref: library/multiprocessing multiprocessing JoinableQueue task_done6488671
Ref: 23c26488671
Ref: library/multiprocessing multiprocessing JoinableQueue join6489365
Ref: 23d26489365
Ref: 管道和队列-Footnote-16489848
Node: 杂项<3>6489890
Ref: library/multiprocessing miscellaneous6490006
Ref: 23d36490006
Ref: library/multiprocessing multiprocessing active_children6490039
Ref: 23d46490039
Ref: library/multiprocessing multiprocessing cpu_count6490215
Ref: 8896490215
Ref: library/multiprocessing multiprocessing current_process6490549
Ref: 23d56490549
Ref: library/multiprocessing multiprocessing parent_process6490727
Ref: 23d66490727
Ref: library/multiprocessing multiprocessing freeze_support6491018
Ref: 23d76491018
Ref: library/multiprocessing multiprocessing get_all_start_methods6491988
Ref: 8806491988
Ref: library/multiprocessing multiprocessing get_context6492406
Ref: 8836492406
Ref: library/multiprocessing multiprocessing get_start_method6492852
Ref: 8816492852
Ref: library/multiprocessing multiprocessing set_executable6493456
Ref: 23d86493456
Ref: library/multiprocessing multiprocessing set_start_method6493898
Ref: 8826493898
Node: 连接对象（Connection）<2>6494549
Ref: library/multiprocessing connection-objects6494662
Ref: 23d96494662
Ref: library/multiprocessing multiprocessing connection Connection6494962
Ref: 23db6494962
Ref: library/multiprocessing multiprocessing connection Connection send6495010
Ref: 23dc6495010
Ref: library/multiprocessing multiprocessing connection Connection recv6495332
Ref: 23dd6495332
Ref: library/multiprocessing multiprocessing connection Connection fileno6495607
Ref: 23de6495607
Ref: library/multiprocessing multiprocessing connection Connection close6495701
Ref: 23df6495701
Ref: library/multiprocessing multiprocessing connection Connection poll6495824
Ref: 23e06495824
Ref: library/multiprocessing multiprocessing connection Connection send_bytes6496286
Ref: 23e16496286
Ref: library/multiprocessing multiprocessing connection Connection recv_bytes6496776
Ref: 23e26496776
Ref: library/multiprocessing multiprocessing connection Connection recv_bytes_into6497376
Ref: 23e36497376
Node: 同步原语6499657
Ref: library/multiprocessing synchronization-primitives6499781
Ref: 23e46499781
Ref: library/multiprocessing multiprocessing Barrier6500058
Ref: 23ab6500058
Ref: library/multiprocessing multiprocessing BoundedSemaphore6500209
Ref: 23a86500209
Ref: library/multiprocessing multiprocessing Condition6500664
Ref: 23a96500664
Ref: library/multiprocessing multiprocessing Event6500985
Ref: 23aa6500985
Ref: library/multiprocessing multiprocessing Lock6501062
Ref: 23a56501062
Ref: library/multiprocessing multiprocessing Lock acquire6501818
Ref: 23e56501818
Ref: library/multiprocessing multiprocessing Lock release6503149
Ref: 23e66503149
Ref: library/multiprocessing multiprocessing RLock6503466
Ref: 23a66503466
Ref: library/multiprocessing multiprocessing RLock acquire6504134
Ref: 23e76504134
Ref: library/multiprocessing multiprocessing RLock release6505418
Ref: 23e86505418
Ref: library/multiprocessing multiprocessing Semaphore6506368
Ref: 23a76506368
Ref: 同步原语-Footnote-16507654
Node: 共享 ctypes 对象6507696
Ref: library/multiprocessing shared-ctypes-objects6507798
Ref: 23e96507798
Ref: library/multiprocessing multiprocessing Value6507945
Ref: 23a26507945
Ref: library/multiprocessing multiprocessing Array6509437
Ref: 23a36509437
Node: multiprocessing sharedctypes 模块6510870
Ref: library/multiprocessing module-multiprocessing sharedctypes6510962
Ref: be6510962
Ref: library/multiprocessing the-multiprocessing-sharedctypes-module6510962
Ref: 23ea6510962
Ref: library/multiprocessing multiprocessing sharedctypes RawArray6511505
Ref: 23eb6511505
Ref: library/multiprocessing multiprocessing sharedctypes RawValue6512305
Ref: 23ed6512305
Ref: library/multiprocessing multiprocessing sharedctypes Array6513022
Ref: 23ec6513022
Ref: library/multiprocessing multiprocessing sharedctypes Value6513778
Ref: 23ee6513778
Ref: library/multiprocessing multiprocessing sharedctypes copy6514505
Ref: 23ef6514505
Ref: library/multiprocessing multiprocessing sharedctypes synchronized6514680
Ref: 7226514680
Node: 管理器6517622
Ref: library/multiprocessing managers6517724
Ref: 23f06517724
Ref: library/multiprocessing multiprocessing-managers6517724
Ref: 23c36517724
Ref: library/multiprocessing multiprocessing sharedctypes multiprocessing Manager6518025
Ref: 23f16518025
Ref: library/multiprocessing module-multiprocessing managers6518358
Ref: bb6518358
Ref: library/multiprocessing multiprocessing managers BaseManager6518513
Ref: 23f36518513
Ref: library/multiprocessing multiprocessing managers BaseManager start6519204
Ref: 23f46519204
Ref: library/multiprocessing multiprocessing managers BaseManager get_server6519422
Ref: 23f56519422
Ref: library/multiprocessing multiprocessing managers BaseManager connect6519936
Ref: 23f76519936
Ref: library/multiprocessing multiprocessing managers BaseManager shutdown6520219
Ref: 23f86520219
Ref: library/multiprocessing multiprocessing managers BaseManager register6520419
Ref: 23f96520419
Ref: library/multiprocessing multiprocessing managers BaseManager address6522485
Ref: 23f66522485
Ref: library/multiprocessing multiprocessing managers SyncManager6522978
Ref: 23f26522978
Ref: library/multiprocessing multiprocessing managers SyncManager Barrier6523356
Ref: 23fc6523356
Ref: library/multiprocessing multiprocessing managers SyncManager BoundedSemaphore6523547
Ref: 23fd6523547
Ref: library/multiprocessing multiprocessing managers SyncManager Condition6523706
Ref: 23fe6523706
Ref: library/multiprocessing multiprocessing managers SyncManager Event6524074
Ref: 23ff6524074
Ref: library/multiprocessing multiprocessing managers SyncManager Lock6524204
Ref: 24006524204
Ref: library/multiprocessing multiprocessing managers SyncManager Namespace6524333
Ref: 24016524333
Ref: library/multiprocessing multiprocessing managers SyncManager Queue6524451
Ref: 24026524451
Ref: library/multiprocessing multiprocessing managers SyncManager RLock6524575
Ref: 24036524575
Ref: library/multiprocessing multiprocessing managers SyncManager Semaphore6524705
Ref: 24046524705
Ref: library/multiprocessing multiprocessing managers SyncManager Array6524850
Ref: 24056524850
Ref: library/multiprocessing multiprocessing managers SyncManager Value6524949
Ref: 24066524949
Ref: library/multiprocessing multiprocessing managers SyncManager dict6525079
Ref: 24076525079
Ref: library/multiprocessing multiprocessing managers SyncManager list6525253
Ref: 24086525253
Ref: library/multiprocessing multiprocessing managers Namespace6525613
Ref: 23a46525613
Node: 自定义管理器6526396
Ref: library/multiprocessing customized-managers6526490
Ref: 24096526490
Node: 使用远程管理器6527273
Ref: library/multiprocessing using-a-remote-manager6527367
Ref: 240a6527367
Node: 代理对象6529494
Ref: library/multiprocessing multiprocessing-proxy-objects6529585
Ref: 56e6529585
Ref: library/multiprocessing proxy-objects6529585
Ref: 240b6529585
Ref: library/multiprocessing multiprocessing managers BaseProxy6532726
Ref: 23fa6532726
Ref: library/multiprocessing multiprocessing managers BaseProxy _callmethod6532838
Ref: 23fb6532838
Ref: library/multiprocessing multiprocessing managers BaseProxy _getvalue6534335
Ref: 240c6534335
Ref: library/multiprocessing multiprocessing managers BaseProxy __repr__6534489
Ref: 240d6534489
Ref: library/multiprocessing multiprocessing managers BaseProxy __str__6534576
Ref: 240e6534576
Node: 清理6534683
Ref: library/multiprocessing cleanup6534738
Ref: 240f6534738
Node: 进程池6534998
Ref: library/multiprocessing module-multiprocessing pool6535101
Ref: bc6535101
Ref: library/multiprocessing process-pools6535101
Ref: 24106535101
Ref: library/multiprocessing multiprocessing pool Pool6535234
Ref: 8846535234
Ref: library/multiprocessing multiprocessing pool Pool apply6537532
Ref: 24136537532
Ref: library/multiprocessing multiprocessing pool Pool apply_async6537851
Ref: 24146537851
Ref: library/multiprocessing multiprocessing pool Pool map6538627
Ref: a316538627
Ref: library/multiprocessing multiprocessing pool Pool map_async6539320
Ref: a326539320
Ref: library/multiprocessing multiprocessing pool Pool imap6540098
Ref: 24166540098
Ref: library/multiprocessing multiprocessing pool Pool imap_unordered6540778
Ref: 24176540778
Ref: library/multiprocessing multiprocessing pool Pool starmap6541066
Ref: a2e6541066
Ref: library/multiprocessing multiprocessing pool Pool starmap_async6541403
Ref: a2f6541403
Ref: library/multiprocessing multiprocessing pool Pool close6541755
Ref: 24116541755
Ref: library/multiprocessing multiprocessing pool Pool terminate6541901
Ref: 24126541901
Ref: library/multiprocessing multiprocessing pool Pool join6542099
Ref: 24186542099
Ref: library/multiprocessing multiprocessing pool AsyncResult6542523
Ref: 24156542523
Ref: library/multiprocessing multiprocessing pool AsyncResult get6542671
Ref: 24196542671
Ref: library/multiprocessing multiprocessing pool AsyncResult wait6543022
Ref: 241a6543022
Ref: library/multiprocessing multiprocessing pool AsyncResult ready6543131
Ref: 241b6543131
Ref: library/multiprocessing multiprocessing pool AsyncResult successful6543212
Ref: 241c6543212
Node: 监听器及客户端6544469
Ref: library/multiprocessing listeners-and-clients6544572
Ref: 241d6544572
Ref: library/multiprocessing module-multiprocessing connection6544572
Ref: b96544572
Ref: library/multiprocessing multiprocessing-listeners-clients6544572
Ref: 23da6544572
Ref: library/multiprocessing multiprocessing connection deliver_challenge6545072
Ref: 241e6545072
Ref: library/multiprocessing multiprocessing connection answer_challenge6545445
Ref: 241f6545445
Ref: library/multiprocessing multiprocessing connection Client6545743
Ref: 24206545743
Ref: library/multiprocessing multiprocessing connection Listener6546422
Ref: 24226546422
Ref: library/multiprocessing multiprocessing connection Listener accept6548069
Ref: 24236548069
Ref: library/multiprocessing multiprocessing connection Listener close6548367
Ref: 24246548367
Ref: library/multiprocessing multiprocessing connection Listener address6548629
Ref: 24256548629
Ref: library/multiprocessing multiprocessing connection Listener last_accepted6548700
Ref: 24266548700
Ref: library/multiprocessing multiprocessing connection wait6549070
Ref: a2c6549070
Node: 地址格式6553064
Ref: library/multiprocessing address-formats6553134
Ref: 24276553134
Ref: library/multiprocessing multiprocessing-address-formats6553134
Ref: 24216553134
Node: 认证密码6553787
Ref: library/multiprocessing authentication-keys6553896
Ref: 24286553896
Ref: library/multiprocessing multiprocessing-auth-keys6553896
Ref: 23b76553896
Node: 日志记录<2>6554921
Ref: library/multiprocessing logging6555037
Ref: 24296555037
Ref: library/multiprocessing multiprocessing get_logger6555338
Ref: 242a6555338
Ref: library/multiprocessing multiprocessing log_to_stderr6555794
Ref: 242b6555794
Node: multiprocessing dummy 模块6556788
Ref: library/multiprocessing module-multiprocessing dummy6556883
Ref: ba6556883
Ref: library/multiprocessing the-multiprocessing-dummy-module6556883
Ref: 242c6556883
Ref: library/multiprocessing multiprocessing pool ThreadPool6557376
Ref: edd6557376
Node: 编程指导6559057
Ref: library/multiprocessing multiprocessing-programming6559181
Ref: 23996559181
Ref: library/multiprocessing programming-guidelines6559181
Ref: 242d6559181
Node: 所有start方法6559381
Ref: library/multiprocessing all-start-methods6559489
Ref: 242e6559489
Ref: 所有start方法-Footnote-16565032
Ref: 所有start方法-Footnote-26565074
Ref: 所有start方法-Footnote-36565116
Node: spawn 和 forkserver 启动方式6565158
Ref: library/multiprocessing the-spawn-and-forkserver-start-methods6565266
Ref: 242f6565266
Node: 例子<10>6567129
Ref: library/multiprocessing examples6567238
Ref: 24306567238
Ref: library/multiprocessing multiprocessing-examples6567238
Ref: 23c96567238
Node: multiprocessing shared_memory --- 可从进程直接访问的共享内存6576107
Ref: library/multiprocessing shared_memory doc6576302
Ref: 24316576302
Ref: library/multiprocessing shared_memory module-multiprocessing shared_memory6576302
Ref: bd6576302
Ref: library/multiprocessing shared_memory multiprocessing-shared-memory-provides-shared-memory-for-direct-access-across-processes6576302
Ref: 24326576302
Ref: library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory6577565
Ref: 239c6577565
Ref: library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory close6579122
Ref: 24336579122
Ref: library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory unlink6579416
Ref: 24346579416
Ref: library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory buf6580059
Ref: 24356580059
Ref: library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory name6580132
Ref: 24366580132
Ref: library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory size6580215
Ref: 24376580215
Ref: library/multiprocessing shared_memory multiprocessing managers SharedMemoryManager6583293
Ref: 24386583293
Ref: library/multiprocessing shared_memory multiprocessing managers SharedMemoryManager SharedMemory6584510
Ref: 24396584510
Ref: library/multiprocessing shared_memory multiprocessing managers SharedMemoryManager ShareableList6584681
Ref: 243a6584681
Ref: library/multiprocessing shared_memory multiprocessing shared_memory ShareableList6586436
Ref: 243b6586436
Ref: library/multiprocessing shared_memory multiprocessing shared_memory ShareableList count6587533
Ref: 243c6587533
Ref: library/multiprocessing shared_memory multiprocessing shared_memory ShareableList index6587614
Ref: 243d6587614
Ref: library/multiprocessing shared_memory multiprocessing shared_memory ShareableList format6587783
Ref: 243e6587783
Ref: library/multiprocessing shared_memory multiprocessing shared_memory ShareableList shm6587922
Ref: 243f6587922
Ref: multiprocessing shared_memory --- 可从进程直接访问的共享内存-Footnote-16589538
Node: concurrent 包6589627
Ref: library/concurrent doc6589822
Ref: 24406589822
Ref: library/concurrent the-concurrent-package6589822
Ref: 24416589822
Node: concurrent futures --- 启动并行任务6589977
Ref: library/concurrent futures doc6590129
Ref: 24426590129
Ref: library/concurrent futures concurrent-futures-launching-parallel-tasks6590129
Ref: 24436590129
Ref: library/concurrent futures module-concurrent futures6590129
Ref: 226590129
Ref: concurrent futures --- 启动并行任务-Footnote-16590862
Ref: concurrent futures --- 启动并行任务-Footnote-26590947
Node: Executor 对象6591033
Ref: library/concurrent futures executor-objects6591153
Ref: 24456591153
Ref: library/concurrent futures concurrent futures Executor6591202
Ref: 24446591202
Ref: library/concurrent futures concurrent futures Executor submit6591343
Ref: 2a56591343
Ref: library/concurrent futures concurrent futures Executor map6591752
Ref: 6c76591752
Ref: library/concurrent futures concurrent futures Executor shutdown6593240
Ref: b366593240
Node: ThreadPoolExecutor6594717
Ref: library/concurrent futures threadpoolexecutor6594865
Ref: 24476594865
Ref: library/concurrent futures concurrent futures ThreadPoolExecutor6595915
Ref: 27b6595915
Node: ThreadPoolExecutor 例子6597573
Ref: library/concurrent futures id16597653
Ref: 24496597653
Ref: library/concurrent futures threadpoolexecutor-example6597653
Ref: b376597653
Node: ProcessPoolExecutor6598848
Ref: library/concurrent futures processpoolexecutor6598994
Ref: 244a6598994
Ref: library/concurrent futures concurrent futures ProcessPoolExecutor6599661
Ref: 2a46599661
Node: ProcessPoolExecutor 例子6601340
Ref: library/concurrent futures id26601422
Ref: 244c6601422
Ref: library/concurrent futures processpoolexecutor-example6601422
Ref: b386601422
Node: Future 对象6602324
Ref: library/concurrent futures future-objects6602464
Ref: 244d6602464
Ref: library/concurrent futures concurrent futures Future6602644
Ref: b356602644
Ref: library/concurrent futures concurrent futures Future cancel6602838
Ref: 244e6602838
Ref: library/concurrent futures concurrent futures Future cancelled6603096
Ref: 244f6603096
Ref: library/concurrent futures concurrent futures Future running6603193
Ref: 24506603193
Ref: library/concurrent futures concurrent futures Future done6603316
Ref: 24516603316
Ref: library/concurrent futures concurrent futures Future result6603429
Ref: 24526603429
Ref: library/concurrent futures concurrent futures Future exception6604091
Ref: 24536604091
Ref: library/concurrent futures concurrent futures Future add_done_callback6604734
Ref: 24546604734
Ref: library/concurrent futures concurrent futures Future set_running_or_notify_cancel6605543
Ref: 24556605543
Ref: library/concurrent futures concurrent futures Future set_result6606543
Ref: 24576606543
Ref: library/concurrent futures concurrent futures Future set_exception6606943
Ref: 24586606943
Node: 模块函数6607386
Ref: library/concurrent futures module-functions6607519
Ref: 245a6607519
Ref: library/concurrent futures concurrent futures wait6607560
Ref: 24566607560
Ref: library/concurrent futures concurrent futures as_completed6609279
Ref: 10fe6609279
Ref: 模块函数-Footnote-16610303
Node: Exception类6610352
Ref: library/concurrent futures exception-classes6610463
Ref: 245b6610463
Ref: library/concurrent futures concurrent futures CancelledError6610507
Ref: 1ab6610507
Ref: library/concurrent futures concurrent futures TimeoutError6610598
Ref: 24466610598
Ref: library/concurrent futures concurrent futures BrokenExecutor6610708
Ref: 245c6610708
Ref: library/concurrent futures concurrent futures InvalidStateError6610935
Ref: 24596610935
Ref: library/concurrent futures concurrent futures thread BrokenThreadPool6611102
Ref: 24486611102
Ref: library/concurrent futures concurrent futures process BrokenProcessPool6611330
Ref: 244b6611330
Node: subprocess --- 子进程管理6611628
Ref: library/subprocess doc6611791
Ref: 245d6611791
Ref: library/subprocess module-subprocess6611791
Ref: fa6611791
Ref: library/subprocess subprocess-subprocess-management6611791
Ref: 245e6611791
Ref: subprocess --- 子进程管理-Footnote-16612644
Ref: subprocess --- 子进程管理-Footnote-26612713
Node: 使用 subprocess 模块6612762
Ref: library/subprocess using-the-subprocess-module6612874
Ref: 245f6612874
Ref: library/subprocess subprocess run6613280
Ref: 3f56613280
Ref: library/subprocess subprocess CompletedProcess6616843
Ref: 7696616843
Ref: library/subprocess subprocess CompletedProcess args6616951
Ref: 24646616951
Ref: library/subprocess subprocess CompletedProcess returncode6617052
Ref: 24656617052
Ref: library/subprocess subprocess CompletedProcess stdout6617282
Ref: 24666617282
Ref: library/subprocess subprocess CompletedProcess stderr6617753
Ref: 24676617753
Ref: library/subprocess subprocess CompletedProcess check_returncode6618028
Ref: 24686618028
Ref: library/subprocess subprocess DEVNULL6618188
Ref: aa86618188
Ref: library/subprocess subprocess PIPE6618394
Ref: 3f66618394
Ref: library/subprocess subprocess STDOUT6618604
Ref: 24696618604
Ref: library/subprocess subprocess SubprocessError6618796
Ref: 246a6618796
Ref: library/subprocess subprocess TimeoutExpired6618903
Ref: 24636618903
Ref: library/subprocess subprocess TimeoutExpired cmd6619050
Ref: 246b6619050
Ref: library/subprocess subprocess TimeoutExpired timeout6619117
Ref: 246c6619117
Ref: library/subprocess subprocess TimeoutExpired output6619170
Ref: 246d6619170
Ref: library/subprocess subprocess TimeoutExpired stdout6619330
Ref: 246e6619330
Ref: library/subprocess subprocess TimeoutExpired stderr6619425
Ref: 246f6619425
Ref: library/subprocess subprocess CalledProcessError6619657
Ref: cbd6619657
Ref: library/subprocess subprocess CalledProcessError returncode6619892
Ref: 24716619892
Ref: library/subprocess subprocess CalledProcessError cmd6620049
Ref: 24726620049
Ref: library/subprocess subprocess CalledProcessError output6620116
Ref: 24736620116
Ref: library/subprocess subprocess CalledProcessError stdout6620276
Ref: 24746620276
Ref: library/subprocess subprocess CalledProcessError stderr6620371
Ref: 24756620371
Node: 常用参数6620650
Ref: library/subprocess frequently-used-arguments6620750
Ref: 24616620750
Ref: library/subprocess id16620750
Ref: 24766620750
Node: Popen 构造函数6624513
Ref: library/subprocess popen-constructor6624631
Ref: 247b6624631
Ref: library/subprocess subprocess Popen6624868
Ref: 2ba6624868
Ref: Popen 构造函数-Footnote-16637597
Node: 异常<7>6637657
Ref: library/subprocess exceptions6637754
Ref: 248b6637754
Node: 安全考量6638664
Ref: library/subprocess security-considerations6638797
Ref: 247a6638797
Ref: 安全考量-Footnote-16639434
Node: Popen 对象6639504
Ref: library/subprocess popen-objects6639633
Ref: 248c6639633
Ref: library/subprocess subprocess Popen poll6639729
Ref: 248d6639729
Ref: library/subprocess subprocess Popen wait6639880
Ref: 59b6639880
Ref: library/subprocess subprocess Popen communicate6640705
Ref: 24626640705
Ref: library/subprocess subprocess Popen send_signal6642370
Ref: 248e6642370
Ref: library/subprocess subprocess Popen terminate6642700
Ref: 248f6642700
Ref: library/subprocess subprocess Popen kill6642941
Ref: 24906642941
Ref: library/subprocess subprocess Popen args6643188
Ref: 24916643188
Ref: library/subprocess subprocess Popen stdin6643351
Ref: 24776643351
Ref: library/subprocess subprocess Popen stdout6643737
Ref: 24786643737
Ref: library/subprocess subprocess Popen stderr6644152
Ref: 24796644152
Ref: library/subprocess subprocess Popen pid6644813
Ref: 24926644813
Ref: library/subprocess subprocess Popen returncode6644979
Ref: 248a6644979
Node: Windows Popen 助手6645296
Ref: library/subprocess windows-popen-helpers6645432
Ref: 24936645432
Ref: library/subprocess subprocess STARTUPINFO6645560
Ref: 247d6645560
Ref: library/subprocess subprocess STARTUPINFO dwFlags6645923
Ref: 24946645923
Ref: library/subprocess subprocess STARTUPINFO hStdInput6646218
Ref: 24956646218
Ref: library/subprocess subprocess STARTUPINFO hStdOutput6646509
Ref: 24976646509
Ref: library/subprocess subprocess STARTUPINFO hStdError6646786
Ref: 24986646786
Ref: library/subprocess subprocess STARTUPINFO wShowWindow6647062
Ref: 24996647062
Ref: library/subprocess subprocess STARTUPINFO lpAttributeList6647484
Ref: 4a26647484
Ref: Windows Popen 助手-Footnote-16648594
Ref: Windows Popen 助手-Footnote-26648666
Ref: Windows Popen 助手-Footnote-36648738
Node: Windows 常数6648827
Ref: library/subprocess windows-constants6648898
Ref: 249c6648898
Ref: library/subprocess subprocess STD_INPUT_HANDLE6648996
Ref: 249d6648996
Ref: library/subprocess subprocess STD_OUTPUT_HANDLE6649111
Ref: 249e6649111
Ref: library/subprocess subprocess STD_ERROR_HANDLE6649243
Ref: 249f6649243
Ref: library/subprocess subprocess SW_HIDE6649374
Ref: 249b6649374
Ref: library/subprocess subprocess STARTF_USESTDHANDLES6649458
Ref: 24966649458
Ref: library/subprocess subprocess STARTF_USESHOWWINDOW6649667
Ref: 249a6649667
Ref: library/subprocess subprocess CREATE_NEW_CONSOLE6649793
Ref: 247e6649793
Ref: library/subprocess subprocess CREATE_NEW_PROCESS_GROUP6649930
Ref: 247f6649930
Ref: library/subprocess subprocess ABOVE_NORMAL_PRIORITY_CLASS6650250
Ref: 24806650250
Ref: library/subprocess subprocess BELOW_NORMAL_PRIORITY_CLASS6650446
Ref: 24816650446
Ref: library/subprocess subprocess HIGH_PRIORITY_CLASS6650642
Ref: 24826650642
Ref: library/subprocess subprocess IDLE_PRIORITY_CLASS6650821
Ref: 24836650821
Ref: library/subprocess subprocess NORMAL_PRIORITY_CLASS6651015
Ref: 24846651015
Ref: library/subprocess subprocess REALTIME_PRIORITY_CLASS6651211
Ref: 24856651211
Ref: library/subprocess subprocess CREATE_NO_WINDOW6651671
Ref: 24866651671
Ref: library/subprocess subprocess DETACHED_PROCESS6651842
Ref: 24876651842
Ref: library/subprocess subprocess CREATE_DEFAULT_ERROR_MODE6652075
Ref: 24886652075
Ref: library/subprocess subprocess CREATE_BREAKAWAY_FROM_JOB6652410
Ref: 24896652410
Node: 较旧的高阶 API6652590
Ref: library/subprocess call-function-trio6652753
Ref: 24606652753
Ref: library/subprocess older-high-level-api6652753
Ref: 24a06652753
Ref: library/subprocess subprocess call6652998
Ref: 3f76652998
Ref: library/subprocess subprocess check_call6653962
Ref: 24706653962
Ref: library/subprocess subprocess check_output6655064
Ref: 8e36655064
Node: 使用 subprocess 模块替换旧函数6657180
Ref: library/subprocess replacing-older-functions-with-the-subprocess-module6657351
Ref: 24a16657351
Ref: library/subprocess subprocess-replacements6657351
Ref: af26657351
Node: 替代 /bin/sh shell 命令替换6658372
Ref: library/subprocess replacing-bin-sh-shell-command-substitution6658509
Ref: 24a26658509
Node: 替代 shell 管道6658685
Ref: library/subprocess replacing-shell-pipeline6658847
Ref: 24a36658847
Node: 替代 os system6659481
Ref: library/subprocess replacing-os-system6659635
Ref: 24a46659635
Node: 替代 os spawn 函数族6660244
Ref: library/subprocess replacing-the-os-spawn-family6660414
Ref: 24a56660414
Node: 替代 os popen os popen2 os popen36661028
Ref: library/subprocess replacing-os-popen-os-popen2-os-popen36661217
Ref: 24a66661217
Node: 来自 popen2 模块的替代函数6662498
Ref: library/subprocess replacing-functions-from-the-popen2-module6662653
Ref: 24a76662653
Node: 旧式的 Shell 发起函数6663927
Ref: library/subprocess legacy-shell-invocation-functions6664088
Ref: 24a86664088
Ref: library/subprocess subprocess getstatusoutput6664387
Ref: 8e46664387
Ref: library/subprocess subprocess getoutput6665553
Ref: 24a96665553
Node: 注释<2>6665984
Ref: library/subprocess notes6666097
Ref: 24aa6666097
Node: 在 Windows 上将参数列表转换为一个字符串6666199
Ref: library/subprocess converting-an-argument-sequence-to-a-string-on-windows6666299
Ref: 24ab6666299
Ref: library/subprocess converting-argument-sequence6666299
Ref: 247c6666299
Node: sched --- 事件调度器6667283
Ref: library/sched doc6667439
Ref: 24ac6667439
Ref: library/sched module-sched6667439
Ref: e46667439
Ref: library/sched sched-event-scheduler6667439
Ref: 24ad6667439
Ref: library/sched sched scheduler6667683
Ref: a766667683
Ref: sched --- 事件调度器-Footnote-16669225
Node: 调度器对象6669289
Ref: library/sched id16669366
Ref: 24ae6669366
Ref: library/sched scheduler-objects6669366
Ref: 24af6669366
Ref: library/sched sched scheduler enterabs6669472
Ref: a786669472
Ref: library/sched sched scheduler enter6670261
Ref: a776670261
Ref: library/sched sched scheduler cancel6670614
Ref: 24b06670614
Ref: library/sched sched scheduler empty6670788
Ref: 24b16670788
Ref: library/sched sched scheduler run6670874
Ref: a756670874
Ref: library/sched sched scheduler queue6671828
Ref: 24b26671828
Node: queue --- 一个同步的队列类6672071
Ref: library/queue doc6672224
Ref: 24b36672224
Ref: library/queue module-queue6672224
Ref: db6672224
Ref: library/queue queue-a-synchronized-queue-class6672224
Ref: 24b46672224
Ref: library/queue queue Queue6673329
Ref: d206673329
Ref: library/queue queue LifoQueue6673691
Ref: 24b56673691
Ref: library/queue queue PriorityQueue6674009
Ref: 24b66674009
Ref: library/queue queue SimpleQueue6674897
Ref: 3ce6674897
Ref: library/queue queue Empty6675046
Ref: 23c46675046
Ref: library/queue queue Full6675213
Ref: 23c56675213
Ref: queue --- 一个同步的队列类-Footnote-16675464
Node: Queue对象6675528
Ref: library/queue queue-objects6675637
Ref: 24bb6675637
Ref: library/queue queueobjects6675637
Ref: 24bc6675637
Ref: library/queue queue Queue qsize6675806
Ref: 24bd6675806
Ref: library/queue queue Queue empty6675990
Ref: 24be6675990
Ref: library/queue queue Queue full6676285
Ref: 24bf6676285
Ref: library/queue queue Queue put6676572
Ref: 24b96676572
Ref: library/queue queue Queue put_nowait6677147
Ref: 24ba6677147
Ref: library/queue queue Queue get6677227
Ref: 24b76677227
Ref: library/queue queue Queue get_nowait6678106
Ref: 24b86678106
Ref: library/queue queue Queue task_done6678291
Ref: 23c06678291
Ref: library/queue queue Queue join6678895
Ref: 23c16678895
Node: SimpleQueue 对象6679926
Ref: library/queue simplequeue-objects6680035
Ref: 24c06680035
Ref: library/queue queue SimpleQueue qsize6680158
Ref: 24c16680158
Ref: library/queue queue SimpleQueue empty6680290
Ref: 24c26680290
Ref: library/queue queue SimpleQueue put6680489
Ref: 24c36680489
Ref: library/queue queue SimpleQueue put_nowait6681228
Ref: 24c46681228
Ref: library/queue queue SimpleQueue get6681379
Ref: 24c56681379
Ref: library/queue queue SimpleQueue get_nowait6681956
Ref: 24c66681956
Node: contextvars 上下文变量6682350
Ref: library/contextvars doc6682509
Ref: 24c76682509
Ref: library/contextvars contextvars-context-variables6682509
Ref: 24c86682509
Ref: library/contextvars module-contextvars6682509
Ref: 256682509
Ref: contextvars 上下文变量-Footnote-16683277
Node: 上下文变量6683326
Ref: library/contextvars context-variables6683435
Ref: 24cc6683435
Ref: library/contextvars contextvars ContextVar6683481
Ref: 24c96683481
Ref: library/contextvars contextvars ContextVar name6684103
Ref: 24ce6684103
Ref: library/contextvars contextvars ContextVar get6684211
Ref: 24cd6684211
Ref: library/contextvars contextvars ContextVar set6684655
Ref: 24cf6684655
Ref: library/contextvars contextvars ContextVar reset6684993
Ref: 24d16684993
Ref: library/contextvars contextvars contextvars Token6685483
Ref: 24d06685483
Ref: library/contextvars contextvars contextvars Token Token var6685713
Ref: 24d26685713
Ref: library/contextvars contextvars contextvars Token Token old_value6685827
Ref: 24d36685827
Ref: library/contextvars contextvars contextvars Token Token MISSING6686097
Ref: 24d46686097
Node: 手动上下文管理6686196
Ref: library/contextvars manual-context-management6686328
Ref: 24d56686328
Ref: library/contextvars contextvars copy_context6686384
Ref: 24ca6686384
Ref: library/contextvars contextvars Context6686830
Ref: 24cb6686830
Ref: library/contextvars contextvars Context run6687150
Ref: 24d66687150
Ref: library/contextvars contextvars Context copy6688517
Ref: 24d76688517
Ref: library/contextvars contextvars Context get6688927
Ref: 24d86688927
Ref: library/contextvars contextvars Context keys6689348
Ref: 24d96689348
Ref: library/contextvars contextvars Context values6689437
Ref: 24da6689437
Ref: library/contextvars contextvars Context items6689528
Ref: 24db6689528
Node: asyncio 支持6689642
Ref: library/contextvars asyncio-support6689750
Ref: 24dc6689750
Node: _thread --- 底层多线程 API6691276
Ref: library/_thread doc6691442
Ref: 24dd6691442
Ref: library/_thread module-_thread6691442
Ref: 36691442
Ref: library/_thread thread-low-level-threading-api6691442
Ref: 24de6691442
Ref: library/_thread _thread error6692069
Ref: 24df6692069
Ref: library/_thread _thread LockType6692224
Ref: 24e06692224
Ref: library/_thread _thread start_new_thread6692282
Ref: fd56692282
Ref: library/_thread _thread interrupt_main6693079
Ref: 24e16693079
Ref: library/_thread _thread exit6693435
Ref: 24e56693435
Ref: library/_thread _thread allocate_lock6693576
Ref: 24e66693576
Ref: library/_thread _thread get_ident6693729
Ref: 24e76693729
Ref: library/_thread _thread get_native_id6694048
Ref: 24e86694048
Ref: library/_thread _thread stack_size6694460
Ref: 24e96694460
Ref: library/_thread _thread TIMEOUT_MAX6695510
Ref: 24ea6695510
Ref: library/_thread _thread lock acquire6695755
Ref: 24eb6695755
Ref: library/_thread _thread lock release6696714
Ref: 24ec6696714
Ref: library/_thread _thread lock locked6696834
Ref: 24ed6696834
Node: _dummy_thread --- _thread 的替代模块6698112
Ref: library/_dummy_thread doc6698306
Ref: 24ee6698306
Ref: library/_dummy_thread dummy-thread-drop-in-replacement-for-the-thread-module6698306
Ref: 24ef6698306
Ref: library/_dummy_thread module-_dummy_thread6698306
Ref: 26698306
Ref: _dummy_thread --- _thread 的替代模块-Footnote-16699010
Node: dummy_threading --- 可直接替代 threading 模块。6699082
Ref: library/dummy_threading doc6699236
Ref: 24f06699236
Ref: library/dummy_threading dummy-threading-drop-in-replacement-for-the-threading-module6699236
Ref: 24f16699236
Ref: library/dummy_threading module-dummy_threading6699236
Ref: 686699236
Ref: dummy_threading --- 可直接替代 threading 模块。-Footnote-16699947
Node: 网络和进程间通信6700021
Ref: library/ipc doc6700149
Ref: 24f26700149
Ref: library/ipc ipc6700149
Ref: 24f36700149
Ref: library/ipc networking-and-interprocess-communication6700149
Ref: 24f46700149
Node: asyncio --- 异步 I/O6701148
Ref: library/asyncio doc6701269
Ref: 24f56701269
Ref: library/asyncio asyncio-asynchronous-i-o6701269
Ref: 24f66701269
Ref: library/asyncio module-asyncio6701269
Ref: a6701269
Node: 协程与任务6702926
Ref: library/asyncio-task doc6703012
Ref: 25006703012
Ref: library/asyncio-task coroutines-and-tasks6703012
Ref: 25016703012
Node: 协程<3>6703407
Ref: library/asyncio-task coroutine6703495
Ref: 24f76703495
Ref: library/asyncio-task coroutines6703495
Ref: 25026703495
Node: 可等待对象<2>6705775
Ref: library/asyncio-task asyncio-awaitables6705893
Ref: 25036705893
Ref: library/asyncio-task awaitables6705893
Ref: 25046705893
Node: 运行 asyncio 程序6708444
Ref: library/asyncio-task running-an-asyncio-program6708565
Ref: 25076708565
Ref: library/asyncio-task asyncio run6708624
Ref: 1a66708624
Ref: 运行 asyncio 程序-Footnote-16709507
Node: 创建任务6709581
Ref: library/asyncio-task creating-tasks6709690
Ref: 25086709690
Ref: library/asyncio-task asyncio create_task6709731
Ref: 1af6709731
Node: 休眠6710679
Ref: library/asyncio-task sleeping6710785
Ref: 25096710785
Ref: library/asyncio-task asyncio sleep6710816
Ref: 2866710816
Ref: library/asyncio-task asyncio-example-sleep6711182
Ref: 250a6711182
Node: 并发运行任务6711670
Ref: library/asyncio-task running-tasks-concurrently6711782
Ref: 250b6711782
Ref: library/asyncio-task asyncio gather6711833
Ref: 2876711833
Ref: library/asyncio-task asyncio-example-gather6713168
Ref: 250c6713168
Node: 屏蔽取消操作6714826
Ref: library/asyncio-task shielding-from-cancellation6714938
Ref: 250d6714938
Ref: library/asyncio-task asyncio shield6714989
Ref: 2886714989
Node: 超时6716106
Ref: library/asyncio-task timeouts6716212
Ref: 250f6716212
Ref: library/asyncio-task asyncio wait_for6716243
Ref: 2896716243
Ref: library/asyncio-task asyncio-example-waitfor6717097
Ref: 25116717097
Node: 简单等待6717751
Ref: library/asyncio-task waiting-primitives6717872
Ref: 25126717872
Ref: library/asyncio-task asyncio wait6717915
Ref: 28a6717915
Ref: library/asyncio-task asyncio-example-wait-coroutine6719995
Ref: 25136719995
Ref: library/asyncio-task asyncio as_completed6720858
Ref: 28b6720858
Node: 来自其他线程的日程安排6721496
Ref: library/asyncio-task scheduling-from-other-threads6721617
Ref: 25146721617
Ref: library/asyncio-task asyncio run_coroutine_threadsafe6721695
Ref: 5226721695
Node: 内省6723037
Ref: library/asyncio-task introspection6723157
Ref: 25166723157
Ref: library/asyncio-task asyncio current_task6723190
Ref: 3596723190
Ref: library/asyncio-task asyncio all_tasks6723489
Ref: 35a6723489
Node: Task 对象6723756
Ref: library/asyncio-task task-object6723867
Ref: 25176723867
Ref: library/asyncio-task asyncio Task6723910
Ref: 1ae6723910
Ref: library/asyncio-task asyncio Task cancel6725910
Ref: 250e6725910
Ref: library/asyncio-task asyncio-example-task-cancel6726490
Ref: 251c6726490
Ref: library/asyncio-task asyncio Task cancelled6727707
Ref: 25186727707
Ref: library/asyncio-task asyncio Task done6727980
Ref: 251d6727980
Ref: library/asyncio-task asyncio Task result6728218
Ref: 251e6728218
Ref: library/asyncio-task asyncio Task exception6728688
Ref: 25206728688
Ref: library/asyncio-task asyncio Task add_done_callback6729166
Ref: 25216729166
Ref: library/asyncio-task asyncio Task remove_done_callback6729489
Ref: 25226729489
Ref: library/asyncio-task asyncio Task get_stack6729776
Ref: 25246729776
Ref: library/asyncio-task asyncio Task print_stack6730528
Ref: 25256730528
Ref: library/asyncio-task asyncio Task get_coro6730956
Ref: 1ad6730956
Ref: library/asyncio-task asyncio Task get_name6731078
Ref: 1b26731078
Ref: library/asyncio-task asyncio Task set_name6731324
Ref: 1b16731324
Ref: library/asyncio-task asyncio Task all_tasks6731628
Ref: 35c6731628
Ref: library/asyncio-task asyncio Task current_task6732135
Ref: 35b6732135
Node: 基于生成器的协程6732578
Ref: library/asyncio-task asyncio-generator-based-coro6732674
Ref: 25056732674
Ref: library/asyncio-task generator-based-coroutines6732674
Ref: 25266732674
Ref: library/asyncio-task asyncio coroutine6733115
Ref: 2836733115
Ref: library/asyncio-task asyncio iscoroutine6733657
Ref: 25276733657
Ref: library/asyncio-task asyncio iscoroutinefunction6733897
Ref: 25286733897
Node: 流6734196
Ref: library/asyncio-stream doc6734306
Ref: 25296734306
Ref: library/asyncio-stream asyncio-streams6734306
Ref: 24f86734306
Ref: library/asyncio-stream streams6734306
Ref: 252a6734306
Ref: library/asyncio-stream asyncio-example-stream6734591
Ref: 252b6734591
Ref: library/asyncio-stream asyncio open_connection6735305
Ref: 36c6735305
Ref: library/asyncio-stream asyncio start_server6736124
Ref: 36d6736124
Ref: library/asyncio-stream asyncio open_unix_connection6737420
Ref: 252d6737420
Ref: library/asyncio-stream asyncio start_unix_server6738010
Ref: 252f6738010
Ref: 流-Footnote-16738733
Node: StreamReader6738807
Ref: library/asyncio-stream streamreader6738880
Ref: 25306738880
Ref: library/asyncio-stream asyncio StreamReader6738927
Ref: fda6738927
Ref: library/asyncio-stream asyncio StreamReader read6739216
Ref: 25316739216
Ref: library/asyncio-stream asyncio StreamReader readline6739494
Ref: 25326739494
Ref: library/asyncio-stream asyncio StreamReader readexactly6739816
Ref: 5276739816
Ref: library/asyncio-stream asyncio StreamReader readuntil6740191
Ref: 5266740191
Ref: library/asyncio-stream asyncio StreamReader at_eof6740966
Ref: 25356740966
Node: StreamWriter6741087
Ref: library/asyncio-stream streamwriter6741179
Ref: 25366741179
Ref: library/asyncio-stream asyncio StreamWriter6741226
Ref: fdb6741226
Ref: library/asyncio-stream asyncio StreamWriter write6741483
Ref: 25376741483
Ref: library/asyncio-stream asyncio StreamWriter writelines6741822
Ref: 25386741822
Ref: library/asyncio-stream asyncio StreamWriter close6742226
Ref: 25396742226
Ref: library/asyncio-stream asyncio StreamWriter can_write_eof6742453
Ref: 253a6742453
Ref: library/asyncio-stream asyncio StreamWriter write_eof6742625
Ref: 253b6742625
Ref: library/asyncio-stream asyncio StreamWriter transport6742731
Ref: 253c6742731
Ref: library/asyncio-stream asyncio StreamWriter get_extra_info6742804
Ref: 253d6742804
Ref: library/asyncio-stream asyncio StreamWriter drain6742968
Ref: 253e6742968
Ref: library/asyncio-stream asyncio StreamWriter is_closing6743480
Ref: 3606743480
Ref: library/asyncio-stream asyncio StreamWriter wait_closed6743615
Ref: 35f6743615
Node: 例子<11>6743840
Ref: library/asyncio-stream examples6743911
Ref: 252c6743911
Node: 使用流的 TCP 回显客户端6744113
Ref: library/asyncio-stream asyncio-tcp-echo-client-streams6744233
Ref: 253f6744233
Ref: library/asyncio-stream tcp-echo-client-using-streams6744233
Ref: 25406744233
Node: 使用流的 TCP 回显服务器6744945
Ref: library/asyncio-stream asyncio-tcp-echo-server-streams6745092
Ref: 25426745092
Ref: library/asyncio-stream tcp-echo-server-using-streams6745092
Ref: 25436745092
Node: 获取 HTTP 标头6746054
Ref: library/asyncio-stream get-http-headers6746226
Ref: 25456746226
Node: 注册一个打开的套接字以等待使用流的数据6747446
Ref: library/asyncio-stream asyncio-example-create-connection-streams6747577
Ref: 25466747577
Ref: library/asyncio-stream register-an-open-socket-to-wait-for-data-using-streams6747577
Ref: 25476747577
Node: 同步原语<2>6748938
Ref: library/asyncio-sync doc6749045
Ref: 254b6749045
Ref: library/asyncio-sync asyncio-sync6749045
Ref: 24fb6749045
Ref: library/asyncio-sync synchronization-primitives6749045
Ref: 254c6749045
Ref: 同步原语<2>-Footnote-16749950
Node: Lock6750022
Ref: library/asyncio-sync lock6750092
Ref: 254d6750092
Ref: library/asyncio-sync asyncio Lock6750123
Ref: 28c6750123
Ref: library/asyncio-sync asyncio Lock acquire6750794
Ref: 254e6750794
Ref: library/asyncio-sync asyncio Lock release6751218
Ref: 254f6751218
Ref: library/asyncio-sync asyncio Lock locked6751422
Ref: 25506751422
Node: Event6751507
Ref: library/asyncio-sync event6751595
Ref: 25516751595
Ref: library/asyncio-sync asyncio Event6751628
Ref: 28d6751628
Ref: library/asyncio-sync asyncio-example-sync-event6752194
Ref: 25556752194
Ref: library/asyncio-sync asyncio Event wait6752822
Ref: 25546752822
Ref: library/asyncio-sync asyncio Event set6753044
Ref: 25526753044
Ref: library/asyncio-sync asyncio Event clear6753165
Ref: 25536753165
Ref: library/asyncio-sync asyncio Event is_set6753373
Ref: 25566753373
Node: Condition6753460
Ref: library/asyncio-sync condition6753553
Ref: 25576753553
Ref: library/asyncio-sync asyncio Condition6753594
Ref: 28e6753594
Ref: library/asyncio-sync asyncio Condition acquire6754742
Ref: 25586754742
Ref: library/asyncio-sync asyncio Condition notify6754943
Ref: 25596754943
Ref: library/asyncio-sync asyncio Condition locked6755303
Ref: 255a6755303
Ref: library/asyncio-sync asyncio Condition notify_all6755396
Ref: 255b6755396
Ref: library/asyncio-sync asyncio Condition release6755776
Ref: 255c6755776
Ref: library/asyncio-sync asyncio Condition wait6755924
Ref: 255d6755924
Ref: library/asyncio-sync asyncio Condition wait_for6756379
Ref: 255e6756379
Node: Semaphore6756612
Ref: library/asyncio-sync semaphore6756716
Ref: 255f6756716
Ref: library/asyncio-sync asyncio Semaphore6756757
Ref: 28f6756757
Ref: library/asyncio-sync asyncio Semaphore acquire6757906
Ref: 25606757906
Ref: library/asyncio-sync asyncio Semaphore locked6758193
Ref: 25626758193
Ref: library/asyncio-sync asyncio Semaphore release6758298
Ref: 25616758298
Node: BoundedSemaphore6758633
Ref: library/asyncio-sync boundedsemaphore6758719
Ref: 25636758719
Ref: library/asyncio-sync asyncio BoundedSemaphore6758774
Ref: 2906758774
Node: 子进程集6759491
Ref: library/asyncio-subprocess doc6759604
Ref: 25646759604
Ref: library/asyncio-subprocess asyncio-subprocess6759604
Ref: 24f96759604
Ref: library/asyncio-subprocess subprocesses6759604
Ref: 25656759604
Ref: library/asyncio-subprocess asyncio-example-subprocess-shell6759877
Ref: 25666759877
Ref: 子进程集-Footnote-16761134
Ref: 子进程集-Footnote-26761212
Node: 创建子进程6761295
Ref: library/asyncio-subprocess creating-subprocesses6761377
Ref: 25686761377
Ref: library/asyncio-subprocess asyncio create_subprocess_exec6761425
Ref: 2926761425
Ref: library/asyncio-subprocess asyncio create_subprocess_shell6762080
Ref: 2936762080
Ref: 创建子进程-Footnote-16763530
Node: 常量<7>6763600
Ref: library/asyncio-subprocess constants6763709
Ref: 25706763709
Ref: library/asyncio-subprocess asyncio asyncio subprocess PIPE6763742
Ref: 25716763742
Ref: library/asyncio-subprocess asyncio asyncio subprocess STDOUT6764184
Ref: 25756764184
Ref: library/asyncio-subprocess asyncio asyncio subprocess DEVNULL6764333
Ref: 25766764333
Node: 与子进程交互6764553
Ref: library/asyncio-subprocess interacting-with-subprocesses6764638
Ref: 25776764638
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process6764909
Ref: 25696764909
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process wait6765814
Ref: 25796765814
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process communicate6766279
Ref: 25786766279
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process send_signal6767445
Ref: 257c6767445
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process terminate6767839
Ref: 257d6767839
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process kill6768115
Ref: 257f6768115
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process stdin6768327
Ref: 25726768327
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process stdout6768496
Ref: 25736768496
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process stderr6768661
Ref: 25746768661
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process pid6769140
Ref: 25806769140
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process returncode6769400
Ref: 257b6769400
Node: 子进程和线程6769671
Ref: library/asyncio-subprocess asyncio-subprocess-threads6769763
Ref: 257a6769763
Ref: library/asyncio-subprocess subprocess-and-threads6769763
Ref: 25816769763
Node: 例子<12>6770548
Ref: library/asyncio-subprocess examples6770640
Ref: 25676770640
Ref: library/asyncio-subprocess asyncio-example-create-subprocess-exec6770808
Ref: 25856770808
Node: 队列集6771608
Ref: library/asyncio-queue doc6771715
Ref: 25876771715
Ref: library/asyncio-queue asyncio-queues6771715
Ref: 24fa6771715
Ref: library/asyncio-queue queues6771715
Ref: 25886771715
Ref: 队列集-Footnote-16772343
Node: Queue6772416
Ref: library/asyncio-queue queue6772491
Ref: 258a6772491
Ref: library/asyncio-queue asyncio Queue6772524
Ref: 2916772524
Ref: library/asyncio-queue asyncio Queue maxsize6773161
Ref: 258d6773161
Ref: library/asyncio-queue asyncio Queue empty6773235
Ref: 258e6773235
Ref: library/asyncio-queue asyncio Queue full6773341
Ref: 258f6773341
Ref: library/asyncio-queue asyncio Queue get6773594
Ref: 258b6773594
Ref: library/asyncio-queue asyncio Queue get_nowait6773754
Ref: 25906773754
Ref: library/asyncio-queue asyncio Queue join6773917
Ref: 6a86773917
Ref: library/asyncio-queue asyncio Queue put6774375
Ref: 25926774375
Ref: library/asyncio-queue asyncio Queue put_nowait6774548
Ref: 25936774548
Ref: library/asyncio-queue asyncio Queue qsize6774725
Ref: 258c6774725
Ref: library/asyncio-queue asyncio Queue task_done6774797
Ref: 6a96774797
Node: 优先级队列6775476
Ref: library/asyncio-queue priority-queue6775578
Ref: 25956775578
Ref: library/asyncio-queue asyncio PriorityQueue6775626
Ref: 25966775626
Node: 后进先出队列6775820
Ref: library/asyncio-queue lifo-queue6775926
Ref: 25976775926
Ref: library/asyncio-queue asyncio LifoQueue6775979
Ref: 25986775979
Node: 异常<8>6776098
Ref: library/asyncio-queue exceptions6776199
Ref: 25996776199
Ref: library/asyncio-queue asyncio QueueEmpty6776232
Ref: 25916776232
Ref: library/asyncio-queue asyncio QueueFull6776367
Ref: 25946776367
Node: 例子<13>6776535
Ref: library/asyncio-queue examples6776609
Ref: 25896776609
Ref: library/asyncio-queue asyncio-example-queue-dist6776642
Ref: 259a6776642
Node: 异常<9>6778385
Ref: library/asyncio-exceptions doc6778492
Ref: 259b6778492
Ref: library/asyncio-exceptions asyncio-exceptions6778492
Ref: 259c6778492
Ref: library/asyncio-exceptions exceptions6778492
Ref: 259d6778492
Ref: library/asyncio-exceptions asyncio TimeoutError6778636
Ref: 25106778636
Ref: library/asyncio-exceptions asyncio CancelledError6778801
Ref: 1a86778801
Ref: library/asyncio-exceptions asyncio InvalidStateError6779117
Ref: 251f6779117
Ref: library/asyncio-exceptions asyncio SendfileNotAvailableError6779327
Ref: 259e6779327
Ref: library/asyncio-exceptions asyncio IncompleteReadError6779494
Ref: ee96779494
Ref: library/asyncio-exceptions asyncio IncompleteReadError expected6779684
Ref: 259f6779684
Ref: library/asyncio-exceptions asyncio IncompleteReadError partial6779770
Ref: 25336779770
Ref: library/asyncio-exceptions asyncio LimitOverrunError6779869
Ref: 25346779869
Ref: library/asyncio-exceptions asyncio LimitOverrunError consumed6780016
Ref: 25a06780016
Ref: 异常<9>-Footnote-16780118
Node: 事件循环6780196
Ref: library/asyncio-eventloop doc6780301
Ref: 25a16780301
Ref: library/asyncio-eventloop event-loop6780301
Ref: 25a26780301
Ref: library/asyncio-eventloop asyncio get_running_loop6781031
Ref: 35d6781031
Ref: library/asyncio-eventloop asyncio get_event_loop6781296
Ref: 35e6781296
Ref: library/asyncio-eventloop asyncio set_event_loop6781978
Ref: 25a36781978
Ref: library/asyncio-eventloop asyncio new_event_loop6782088
Ref: 25a46782088
Ref: 事件循环-Footnote-16783216
Ref: 事件循环-Footnote-26783289
Node: 事件循环方法集6783368
Ref: library/asyncio-eventloop asyncio-event-loop6783459
Ref: 64d6783459
Ref: library/asyncio-eventloop event-loop-methods6783459
Ref: 25a66783459
Node: 运行和停止循环6783948
Ref: library/asyncio-eventloop running-and-stopping-the-loop6784048
Ref: 25ac6784048
Ref: library/asyncio-eventloop asyncio loop run_until_complete6784106
Ref: 5206784106
Ref: library/asyncio-eventloop asyncio loop run_forever6784404
Ref: 25ad6784404
Ref: library/asyncio-eventloop asyncio loop stop6785129
Ref: 5286785129
Ref: library/asyncio-eventloop asyncio loop is_running6785183
Ref: 25ae6785183
Ref: library/asyncio-eventloop asyncio loop is_closed6785279
Ref: 6a46785279
Ref: library/asyncio-eventloop asyncio loop close6785374
Ref: 25af6785374
Ref: library/asyncio-eventloop asyncio loop shutdown_asyncgens6785745
Ref: 5296785745
Node: 调度回调6786404
Ref: library/asyncio-eventloop scheduling-callbacks6786531
Ref: 25b06786531
Ref: library/asyncio-eventloop asyncio loop call_soon6786574
Ref: 3526786574
Ref: library/asyncio-eventloop asyncio loop call_soon_threadsafe6787163
Ref: 3536787163
Ref: library/asyncio-eventloop asyncio-pass-keywords6787524
Ref: 25b26787524
Ref: 调度回调-Footnote-16787989
Node: 调度延迟回调6788038
Ref: library/asyncio-eventloop asyncio-delayed-calls6788168
Ref: 25b36788168
Ref: library/asyncio-eventloop scheduling-delayed-callbacks6788168
Ref: 25b46788168
Ref: library/asyncio-eventloop asyncio loop call_later6788347
Ref: 3546788347
Ref: library/asyncio-eventloop asyncio loop call_at6789410
Ref: 3556789410
Ref: library/asyncio-eventloop asyncio loop time6790103
Ref: 25b56790103
Ref: 调度延迟回调-Footnote-16790496
Ref: 调度延迟回调-Footnote-26790545
Node: 创建 Futures 和 Tasks6790594
Ref: library/asyncio-eventloop creating-futures-and-tasks6790730
Ref: 25b66790730
Ref: library/asyncio-eventloop asyncio loop create_future6790798
Ref: 5246790798
Ref: library/asyncio-eventloop asyncio loop create_task6791104
Ref: 1b06791104
Ref: library/asyncio-eventloop asyncio loop set_task_factory6791612
Ref: 6a66791612
Ref: library/asyncio-eventloop asyncio loop get_task_factory6792100
Ref: 6a76792100
Node: 打开网络连接6792225
Ref: library/asyncio-eventloop opening-network-connections6792361
Ref: 25b76792361
Ref: library/asyncio-eventloop asyncio loop create_connection6792414
Ref: 1b36792414
Ref: library/asyncio-eventloop asyncio loop create_datagram_endpoint6797793
Ref: 2e86797793
Ref: library/asyncio-eventloop asyncio loop create_unix_connection6801056
Ref: 252e6801056
Ref: 打开网络连接-Footnote-16801982
Ref: 打开网络连接-Footnote-26802031
Node: 创建网络服务6802080
Ref: library/asyncio-eventloop creating-network-servers6802204
Ref: 25c16802204
Ref: library/asyncio-eventloop asyncio loop create_server6802257
Ref: 3666802257
Ref: library/asyncio-eventloop asyncio loop create_unix_server6805725
Ref: 3676805725
Ref: library/asyncio-eventloop asyncio loop connect_accepted_socket6806539
Ref: 36e6806539
Node: 传输文件6807545
Ref: library/asyncio-eventloop transferring-files6807661
Ref: 25c26807661
Ref: library/asyncio-eventloop asyncio loop sendfile6807704
Ref: 25c36807704
Node: TLS 升级6808716
Ref: library/asyncio-eventloop tls-upgrade6808835
Ref: 25c46808835
Ref: library/asyncio-eventloop asyncio loop start_tls6808876
Ref: 3576808876
Node: 监控文件描述符6810023
Ref: library/asyncio-eventloop watching-file-descriptors6810156
Ref: 25c56810156
Ref: library/asyncio-eventloop asyncio loop add_reader6810214
Ref: 25496810214
Ref: library/asyncio-eventloop asyncio loop remove_reader6810413
Ref: 25c66810413
Ref: library/asyncio-eventloop asyncio loop add_writer6810514
Ref: 25c76810514
Ref: library/asyncio-eventloop asyncio loop remove_writer6810805
Ref: 25c86810805
Node: 直接使用 socket 对象6810989
Ref: library/asyncio-eventloop working-with-socket-objects-directly6811115
Ref: 25ca6811115
Ref: library/asyncio-eventloop asyncio loop sock_recv6811478
Ref: 4a66811478
Ref: library/asyncio-eventloop asyncio loop sock_recv_into6811955
Ref: 3586811955
Ref: library/asyncio-eventloop asyncio loop sock_sendall6812244
Ref: 4a76812244
Ref: library/asyncio-eventloop asyncio loop sock_connect6812973
Ref: 6aa6812973
Ref: library/asyncio-eventloop asyncio loop sock_accept6813580
Ref: 4a86813580
Ref: library/asyncio-eventloop asyncio loop sock_sendfile6814353
Ref: 3616814353
Node: DNS6815534
Ref: library/asyncio-eventloop dns6815651
Ref: 25cb6815651
Ref: library/asyncio-eventloop asyncio loop getaddrinfo6815680
Ref: 4a96815680
Ref: library/asyncio-eventloop asyncio loop getnameinfo6815839
Ref: 4aa6815839
Node: 使用管道6816183
Ref: library/asyncio-eventloop working-with-pipes6816285
Ref: 25ce6816285
Ref: library/asyncio-eventloop asyncio loop connect_read_pipe6816328
Ref: 256c6816328
Ref: library/asyncio-eventloop asyncio loop connect_write_pipe6816905
Ref: 256d6816905
Node: Unix 信号6817734
Ref: library/asyncio-eventloop unix-signals6817875
Ref: 25d16817875
Ref: library/asyncio-eventloop asyncio loop add_signal_handler6817918
Ref: 24fd6817918
Ref: library/asyncio-eventloop asyncio loop remove_signal_handler6818704
Ref: 25d26818704
Node: 在线程或者进程池中执行代码。6819012
Ref: library/asyncio-eventloop executing-code-in-thread-or-process-pools6819156
Ref: 25d36819156
Ref: library/asyncio-eventloop asyncio loop run_in_executor6819249
Ref: 25066819249
Ref: library/asyncio-eventloop asyncio loop set_default_executor6821358
Ref: 27c6821358
Node: 错误处理API6821871
Ref: library/asyncio-eventloop error-handling-api6822022
Ref: 25d46822022
Ref: library/asyncio-eventloop asyncio loop set_exception_handler6822127
Ref: 25d56822127
Ref: library/asyncio-eventloop asyncio loop get_exception_handler6822659
Ref: 5256822659
Ref: library/asyncio-eventloop asyncio loop default_exception_handler6822828
Ref: 25d76822828
Ref: library/asyncio-eventloop asyncio loop call_exception_handler6823217
Ref: 25d66823217
Node: 开启调试模式6824082
Ref: library/asyncio-eventloop enabling-debug-mode6824206
Ref: 25d86824206
Ref: library/asyncio-eventloop asyncio loop get_debug6824259
Ref: 6a36824259
Ref: library/asyncio-eventloop asyncio loop set_debug6824504
Ref: 6a26824504
Node: 运行子进程6824758
Ref: library/asyncio-eventloop running-subprocesses6824858
Ref: 25d96824858
Ref: library/asyncio-eventloop asyncio loop subprocess_exec6825274
Ref: 24fc6825274
Ref: library/asyncio-eventloop asyncio loop subprocess_shell6828772
Ref: 256a6828772
Ref: 运行子进程-Footnote-16829966
Node: 回调处理6830036
Ref: library/asyncio-eventloop callback-handles6830149
Ref: 25a76830149
Ref: library/asyncio-eventloop asyncio Handle6830192
Ref: 10b26830192
Ref: library/asyncio-eventloop asyncio Handle cancel6830338
Ref: 25dc6830338
Ref: library/asyncio-eventloop asyncio Handle cancelled6830483
Ref: 36f6830483
Ref: library/asyncio-eventloop asyncio TimerHandle6830605
Ref: 25a86830605
Ref: library/asyncio-eventloop asyncio TimerHandle when6830801
Ref: 36b6830801
Node: Server 对象6831082
Ref: library/asyncio-eventloop server-objects6831192
Ref: 25a96831192
Ref: library/asyncio-eventloop asyncio Server6831455
Ref: 3656831455
Ref: library/asyncio-eventloop asyncio Server close6831989
Ref: 25dd6831989
Ref: library/asyncio-eventloop asyncio Server get_loop6832341
Ref: 3646832341
Ref: library/asyncio-eventloop asyncio Server start_serving6832463
Ref: 3686832463
Ref: library/asyncio-eventloop asyncio Server serve_forever6833095
Ref: 3696833095
Ref: library/asyncio-eventloop asyncio Server is_serving6833946
Ref: 36a6833946
Ref: library/asyncio-eventloop asyncio Server wait_closed6834088
Ref: 25de6834088
Ref: library/asyncio-eventloop asyncio Server sockets6834192
Ref: 4ab6834192
Node: 事件循环实现6834471
Ref: library/asyncio-eventloop asyncio-event-loops6834579
Ref: 25df6834579
Ref: library/asyncio-eventloop event-loop-implementations6834579
Ref: 25aa6834579
Ref: library/asyncio-eventloop asyncio SelectorEventLoop6834895
Ref: 25826834895
Ref: library/asyncio-eventloop asyncio ProactorEventLoop6835346
Ref: 1ac6835346
Ref: library/asyncio-eventloop asyncio AbstractEventLoop6835579
Ref: 25e06835579
Ref: 事件循环实现-Footnote-16835831
Node: 例子<14>6835917
Ref: library/asyncio-eventloop examples6836003
Ref: 25ab6836003
Node: call_soon 的 Hello World 示例。6836616
Ref: library/asyncio-eventloop asyncio-example-lowlevel-helloworld6836749
Ref: 25e16836749
Ref: library/asyncio-eventloop hello-world-with-call-soon6836749
Ref: 25e26836749
Node: 使用 call_later 来展示当前的日期6837511
Ref: library/asyncio-eventloop asyncio-example-call-later6837692
Ref: 25e36837692
Ref: library/asyncio-eventloop display-the-current-date-with-call-later6837692
Ref: 25e46837692
Node: 监控一个文件描述符的读事件6838644
Ref: library/asyncio-eventloop asyncio-example-watch-fd6838830
Ref: 254a6838830
Ref: library/asyncio-eventloop watch-a-file-descriptor-for-read-events6838830
Ref: 25e56838830
Node: 为SIGINT和SIGTERM设置信号处理器6840124
Ref: library/asyncio-eventloop asyncio-example-unix-signals6840259
Ref: 25e66840259
Ref: library/asyncio-eventloop set-signal-handlers-for-sigint-and-sigterm6840259
Ref: 25e76840259
Node: Futures6841161
Ref: library/asyncio-future doc6841272
Ref: 25e86841272
Ref: library/asyncio-future asyncio-futures6841272
Ref: 24ff6841272
Ref: library/asyncio-future futures6841272
Ref: 25e96841272
Ref: Futures-Footnote-16841636
Ref: Futures-Footnote-26841710
Node: Future 函数6841790
Ref: library/asyncio-future future-functions6841872
Ref: 25ea6841872
Ref: library/asyncio-future asyncio isfuture6841919
Ref: 25eb6841919
Ref: library/asyncio-future asyncio ensure_future6842248
Ref: 51f6842248
Ref: library/asyncio-future asyncio wrap_future6843178
Ref: 25ec6843178
Node: Future 对象<2>6843349
Ref: library/asyncio-future future-object6843431
Ref: 25ed6843431
Ref: library/asyncio-future asyncio Future6843478
Ref: 44b6843478
Ref: library/asyncio-future asyncio Future result6844262
Ref: 25ee6844262
Ref: library/asyncio-future asyncio Future set_result6844862
Ref: 25196844862
Ref: library/asyncio-future asyncio Future set_exception6845068
Ref: 251a6845068
Ref: library/asyncio-future asyncio Future done6845286
Ref: 25ef6845286
Ref: library/asyncio-future asyncio Future cancelled6845574
Ref: 25f06845574
Ref: library/asyncio-future asyncio Future add_done_callback6845841
Ref: 3566845841
Ref: library/asyncio-future asyncio Future remove_done_callback6846780
Ref: 25236846780
Ref: library/asyncio-future asyncio Future cancel6847001
Ref: 251b6847001
Ref: library/asyncio-future asyncio Future exception6847256
Ref: 25f16847256
Ref: library/asyncio-future asyncio Future get_loop6847688
Ref: 3636847688
Ref: library/asyncio-future asyncio-example-future6847806
Ref: 25f26847806
Ref: Future 对象<2>-Footnote-16849726
Node: 传输和协议6849775
Ref: library/asyncio-protocol doc6849880
Ref: 25f36849880
Ref: library/asyncio-protocol asyncio-transports-protocols6849880
Ref: 24fe6849880
Ref: library/asyncio-protocol transports-and-protocols6849880
Ref: 25f46849880
Node: 传输6851841
Ref: library/asyncio-protocol asyncio-transport6851914
Ref: 25bb6851914
Ref: library/asyncio-protocol transports6851914
Ref: 25f56851914
Ref: 传输-Footnote-16852525
Node: 传输层级6852603
Ref: library/asyncio-protocol transports-hierarchy6852679
Ref: 25fe6852679
Ref: library/asyncio-protocol asyncio BaseTransport6852722
Ref: 25f76852722
Ref: library/asyncio-protocol asyncio WriteTransport6852829
Ref: 25d06852829
Ref: library/asyncio-protocol asyncio ReadTransport6853144
Ref: 25cf6853144
Ref: library/asyncio-protocol asyncio Transport6853456
Ref: 25f86853456
Ref: library/asyncio-protocol asyncio DatagramTransport6853969
Ref: 25f96853969
Ref: library/asyncio-protocol asyncio SubprocessTransport6854173
Ref: 25db6854173
Node: 基础传输6854444
Ref: library/asyncio-protocol base-transport6854541
Ref: 25ff6854541
Ref: library/asyncio-protocol asyncio BaseTransport close6854584
Ref: 26006854584
Ref: library/asyncio-protocol asyncio BaseTransport is_closing6854953
Ref: 5236854953
Ref: library/asyncio-protocol asyncio BaseTransport get_extra_info6855064
Ref: 2c96855064
Ref: library/asyncio-protocol asyncio BaseTransport set_protocol6856914
Ref: 26056856914
Ref: library/asyncio-protocol asyncio BaseTransport get_protocol6857069
Ref: 26066857069
Node: 只读传输6857140
Ref: library/asyncio-protocol read-only-transports6857237
Ref: 26076857237
Ref: library/asyncio-protocol asyncio ReadTransport is_reading6857280
Ref: 3706857280
Ref: library/asyncio-protocol asyncio ReadTransport pause_reading6857406
Ref: 3726857406
Ref: library/asyncio-protocol asyncio ReadTransport resume_reading6857710
Ref: 3716857710
Node: 只写传输6858001
Ref: library/asyncio-protocol write-only-transports6858101
Ref: 26096858101
Ref: library/asyncio-protocol asyncio WriteTransport abort6858144
Ref: 260a6858144
Ref: library/asyncio-protocol asyncio WriteTransport can_write_eof6858436
Ref: 260b6858436
Ref: library/asyncio-protocol asyncio WriteTransport get_write_buffer_size6858596
Ref: 260d6858596
Ref: library/asyncio-protocol asyncio WriteTransport get_write_buffer_limits6858707
Ref: 6a56858707
Ref: library/asyncio-protocol asyncio WriteTransport set_write_buffer_limits6858995
Ref: 260e6858995
Ref: library/asyncio-protocol asyncio WriteTransport write6860260
Ref: 26116860260
Ref: library/asyncio-protocol asyncio WriteTransport writelines6860431
Ref: 26126860431
Ref: library/asyncio-protocol asyncio WriteTransport write_eof6860706
Ref: 260c6860706
Node: 数据报传输6860968
Ref: library/asyncio-protocol datagram-transports6861071
Ref: 26136861071
Ref: library/asyncio-protocol asyncio DatagramTransport sendto6861119
Ref: 26146861119
Ref: library/asyncio-protocol asyncio DatagramTransport abort6861471
Ref: 26156861471
Node: 子进程传输6861773
Ref: library/asyncio-protocol asyncio-subprocess-transports6861855
Ref: 256e6861855
Ref: library/asyncio-protocol subprocess-transports6861855
Ref: 26166861855
Ref: library/asyncio-protocol asyncio SubprocessTransport get_pid6861903
Ref: 26176861903
Ref: library/asyncio-protocol asyncio SubprocessTransport get_pipe_transport6862003
Ref: 26186862003
Ref: library/asyncio-protocol asyncio SubprocessTransport get_returncode6862703
Ref: 26196862703
Ref: library/asyncio-protocol asyncio SubprocessTransport kill6862919
Ref: 261a6862919
Ref: library/asyncio-protocol asyncio SubprocessTransport send_signal6863187
Ref: 261c6863187
Ref: library/asyncio-protocol asyncio SubprocessTransport terminate6863347
Ref: 261b6863347
Ref: library/asyncio-protocol asyncio SubprocessTransport close6863650
Ref: 261d6863650
Node: 协议6863861
Ref: library/asyncio-protocol asyncio-protocol6863953
Ref: 25ba6863953
Ref: library/asyncio-protocol protocols6863953
Ref: 25f66863953
Ref: 协议-Footnote-16864650
Node: 基础协议6864727
Ref: library/asyncio-protocol base-protocols6864806
Ref: 261e6864806
Ref: library/asyncio-protocol asyncio BaseProtocol6864849
Ref: 25fa6864849
Ref: library/asyncio-protocol asyncio Protocol6864938
Ref: 25fb6864938
Ref: library/asyncio-protocol asyncio BufferedProtocol6865054
Ref: 2ca6865054
Ref: library/asyncio-protocol asyncio DatagramProtocol6865189
Ref: 25fc6865189
Ref: library/asyncio-protocol asyncio SubprocessProtocol6865294
Ref: 25da6865294
Node: 基础协议<2>6865422
Ref: library/asyncio-protocol base-protocol6865519
Ref: 261f6865519
Ref: library/asyncio-protocol asyncio BaseProtocol connection_made6865814
Ref: 25bc6865814
Ref: library/asyncio-protocol asyncio BaseProtocol connection_lost6866012
Ref: 26016866012
Ref: library/asyncio-protocol asyncio BaseProtocol pause_writing6866478
Ref: 260f6866478
Ref: library/asyncio-protocol asyncio BaseProtocol resume_writing6866582
Ref: 26106866582
Node: 流协议6867040
Ref: library/asyncio-protocol streaming-protocols6867140
Ref: 26206867140
Ref: library/asyncio-protocol asyncio Protocol data_received6867517
Ref: 26086867517
Ref: library/asyncio-protocol asyncio Protocol eof_received6868130
Ref: 26216868130
Node: 缓冲流协议6868919
Ref: library/asyncio-protocol buffered-streaming-protocols6869019
Ref: 26226869019
Ref: library/asyncio-protocol asyncio BufferedProtocol get_buffer6869749
Ref: 26236869749
Ref: library/asyncio-protocol asyncio BufferedProtocol buffer_updated6870200
Ref: 26246870200
Ref: library/asyncio-protocol asyncio BufferedProtocol eof_received6870367
Ref: 26256870367
Node: 数据报协议6870927
Ref: library/asyncio-protocol datagram-protocols6871033
Ref: 26266871033
Ref: library/asyncio-protocol asyncio DatagramProtocol datagram_received6871201
Ref: 26276871201
Ref: library/asyncio-protocol asyncio DatagramProtocol error_received6871443
Ref: 26286871443
Node: 子进程协议6872340
Ref: library/asyncio-protocol asyncio-subprocess-protocols6872422
Ref: 256f6872422
Ref: library/asyncio-protocol subprocess-protocols6872422
Ref: 26296872422
Ref: library/asyncio-protocol asyncio SubprocessProtocol pipe_data_received6872622
Ref: 262a6872622
Ref: library/asyncio-protocol asyncio SubprocessProtocol pipe_connection_lost6872883
Ref: 262b6872883
Ref: library/asyncio-protocol asyncio SubprocessProtocol process_exited6873070
Ref: 262c6873070
Node: 例子<15>6873157
Ref: library/asyncio-protocol examples6873234
Ref: 25fd6873234
Node: TCP回应服务器6873495
Ref: library/asyncio-protocol asyncio-example-tcp-echo-server-protocol6873587
Ref: 25446873587
Ref: library/asyncio-protocol tcp-echo-server6873587
Ref: 262d6873587
Node: TCP回应客户端6874861
Ref: library/asyncio-protocol asyncio-example-tcp-echo-client-protocol6874980
Ref: 25416874980
Ref: library/asyncio-protocol tcp-echo-client6874980
Ref: 262e6874980
Node: UDP回应服务器6876532
Ref: library/asyncio-protocol asyncio-udp-echo-server-protocol6876651
Ref: 25c06876651
Ref: library/asyncio-protocol udp-echo-server6876651
Ref: 262f6876651
Node: UDP回应客户端6877801
Ref: library/asyncio-protocol asyncio-udp-echo-client-protocol6877929
Ref: 25bf6877929
Ref: library/asyncio-protocol udp-echo-client6877929
Ref: 26306877929
Node: 链接已存在的套接字6879447
Ref: library/asyncio-protocol asyncio-example-create-connection6879600
Ref: 25486879600
Ref: library/asyncio-protocol connecting-existing-sockets6879600
Ref: 26316879600
Node: loop subprocess_exec 与 SubprocessProtocol6881490
Ref: library/asyncio-protocol asyncio-example-subprocess-proto6881616
Ref: 25866881616
Ref: library/asyncio-protocol loop-subprocess-exec-and-subprocessprotocol6881616
Ref: 26326881616
Node: 策略6883394
Ref: library/asyncio-policy doc6883504
Ref: 26336883504
Ref: library/asyncio-policy asyncio-policies6883504
Ref: 25a56883504
Ref: library/asyncio-policy policies6883504
Ref: 26346883504
Node: 获取和设置策略6884226
Ref: library/asyncio-policy getting-and-setting-the-policy6884311
Ref: 26366884311
Ref: library/asyncio-policy asyncio get_event_loop_policy6884432
Ref: 26376884432
Ref: library/asyncio-policy asyncio set_event_loop_policy6884518
Ref: 26386884518
Node: 策略对象6884688
Ref: library/asyncio-policy policy-objects6884797
Ref: 26396884797
Ref: library/asyncio-policy asyncio AbstractEventLoopPolicy6884885
Ref: 26356884885
Ref: library/asyncio-policy asyncio AbstractEventLoopPolicy get_event_loop6884964
Ref: 263a6884964
Ref: library/asyncio-policy asyncio AbstractEventLoopPolicy set_event_loop6885237
Ref: 263b6885237
Ref: library/asyncio-policy asyncio AbstractEventLoopPolicy new_event_loop6885342
Ref: 263c6885342
Ref: library/asyncio-policy asyncio AbstractEventLoopPolicy get_child_watcher6885491
Ref: 263d6885491
Ref: library/asyncio-policy asyncio AbstractEventLoopPolicy set_child_watcher6885715
Ref: 263f6885715
Ref: library/asyncio-policy asyncio DefaultEventLoopPolicy6885894
Ref: 26406885894
Ref: library/asyncio-policy asyncio WindowsSelectorEventLoopPolicy6886274
Ref: 26416886274
Ref: library/asyncio-policy asyncio WindowsProactorEventLoopPolicy6886469
Ref: 26426886469
Node: 进程监视器6886660
Ref: library/asyncio-policy asyncio-watchers6886763
Ref: 25836886763
Ref: library/asyncio-policy process-watchers6886763
Ref: 26436886763
Ref: library/asyncio-policy asyncio get_child_watcher6887513
Ref: 26476887513
Ref: library/asyncio-policy asyncio set_child_watcher6887604
Ref: 26486887604
Ref: library/asyncio-policy asyncio AbstractChildWatcher6887980
Ref: 263e6887980
Ref: library/asyncio-policy asyncio AbstractChildWatcher add_child_handler6888019
Ref: 26496888019
Ref: library/asyncio-policy asyncio AbstractChildWatcher remove_child_handler6888379
Ref: 264a6888379
Ref: library/asyncio-policy asyncio AbstractChildWatcher attach_loop6888591
Ref: 264b6888591
Ref: library/asyncio-policy asyncio AbstractChildWatcher is_active6888873
Ref: 264c6888873
Ref: library/asyncio-policy asyncio AbstractChildWatcher close6889115
Ref: 264d6889115
Ref: library/asyncio-policy asyncio ThreadedChildWatcher6889244
Ref: 25846889244
Ref: library/asyncio-policy asyncio MultiLoopChildWatcher6889694
Ref: 26446889694
Ref: library/asyncio-policy asyncio SafeChildWatcher6890296
Ref: 26456890296
Ref: library/asyncio-policy asyncio FastChildWatcher6890876
Ref: 26466890876
Node: 自定义策略6891297
Ref: library/asyncio-policy custom-policies6891379
Ref: 264e6891379
Node: 平台支持6891950
Ref: library/asyncio-platforms doc6892060
Ref: 264f6892060
Ref: library/asyncio-platforms asyncio-platform-support6892060
Ref: 25c96892060
Ref: library/asyncio-platforms platform-support6892060
Ref: 26506892060
Node: 所有平台6892313
Ref: library/asyncio-platforms all-platforms6892394
Ref: 26516892394
Node: Windows<53>6892548
Ref: library/asyncio-platforms windows6892647
Ref: 26526892647
Ref: Windows<53>-Footnote-16894355
Ref: Windows<53>-Footnote-26894438
Ref: Windows<53>-Footnote-36894520
Ref: Windows<53>-Footnote-46894601
Node: Windows的子进程支持6894664
Ref: library/asyncio-platforms asyncio-windows-subprocess6894737
Ref: 256b6894737
Ref: library/asyncio-platforms subprocess-support-on-windows6894737
Ref: 26546894737
Node: macOS<26>6895080
Ref: library/asyncio-platforms macos6895158
Ref: 26556895158
Node: 高级API索引6895768
Ref: library/asyncio-api-index doc6895887
Ref: 26576895887
Ref: library/asyncio-api-index high-level-api-index6895887
Ref: 26586895887
Node: 任务6896144
Ref: library/asyncio-api-index tasks6896223
Ref: 26596896223
Node: 队列集<2>6898972
Ref: library/asyncio-api-index queues6899075
Ref: 265a6899075
Node: 子进程集<2>6899862
Ref: library/asyncio-api-index subprocesses6899965
Ref: 265b6899965
Node: 流<2>6900521
Ref: library/asyncio-api-index streams6900618
Ref: 265c6900618
Node: 同步6901961
Ref: library/asyncio-api-index synchronization6902053
Ref: 265d6902053
Node: 异常<10>6903136
Ref: library/asyncio-api-index exceptions6903213
Ref: 265e6903213
Node: 底层API目录6904107
Ref: library/asyncio-llapi-index doc6904232
Ref: 265f6904232
Ref: library/asyncio-llapi-index low-level-api-index6904232
Ref: 26606904232
Node: 获取事件循环6904472
Ref: library/asyncio-llapi-index obtaining-the-event-loop6904575
Ref: 26616904575
Node: 事件循环方法集<2>6905516
Ref: library/asyncio-llapi-index event-loop-methods6905637
Ref: 26626905637
Node: 传输<2>6916676
Ref: library/asyncio-llapi-index transports6916788
Ref: 26636916788
Node: 协议<2>6922218
Ref: library/asyncio-llapi-index protocols6922324
Ref: 26646922324
Node: 事件循环策略6925367
Ref: library/asyncio-llapi-index event-loop-policies6925455
Ref: 26656925455
Node: 用 asyncio 开发6926226
Ref: library/asyncio-dev doc6926327
Ref: 26666926327
Ref: library/asyncio-dev asyncio-dev6926327
Ref: 26676926327
Ref: library/asyncio-dev developing-with-asyncio6926327
Ref: 26686926327
Node: Debug 模式6926688
Ref: library/asyncio-dev asyncio-debug-mode6926785
Ref: 13606926785
Ref: library/asyncio-dev debug-mode6926785
Ref: 26696926785
Node: 并发性和多线程6928293
Ref: library/asyncio-dev asyncio-multithreading6928420
Ref: 25156928420
Ref: library/asyncio-dev concurrency-and-multithreading6928420
Ref: 266c6928420
Node: 运行阻塞的代码6930620
Ref: library/asyncio-dev asyncio-handle-blocking6930750
Ref: 266d6930750
Ref: library/asyncio-dev running-blocking-code6930750
Ref: 266e6930750
Node: 日志记录<3>6931178
Ref: library/asyncio-dev asyncio-logger6931320
Ref: 266a6931320
Ref: library/asyncio-dev logging6931320
Ref: 266f6931320
Node: 检测 never-awaited 协同程序6931606
Ref: library/asyncio-dev asyncio-coroutine-not-scheduled6931751
Ref: 266b6931751
Ref: library/asyncio-dev detect-never-awaited-coroutines6931751
Ref: 26706931751
Node: 检测就再也没异常6932761
Ref: library/asyncio-dev detect-never-retrieved-exceptions6932882
Ref: 26716932882
Ref: 检测就再也没异常-Footnote-16934415
Node: socket --- 底层网络接口6934479
Ref: library/socket doc6934648
Ref: 26726934648
Ref: library/socket module-socket6934648
Ref: f06934648
Ref: library/socket socket-low-level-networking-interface6934648
Ref: 26736934648
Ref: socket --- 底层网络接口-Footnote-16935827
Node: 套接字协议族6935892
Ref: library/socket socket-families6936000
Ref: 26746936000
Ref: library/socket host-port6937093
Ref: 26756937093
Ref: 套接字协议族-Footnote-16944539
Node: 模块内容<4>6944588
Ref: library/socket module-contents6944720
Ref: 267b6944720
Node: 异常<11>6944882
Ref: library/socket exceptions6944962
Ref: 267c6944962
Ref: library/socket socket error6944993
Ref: 99d6944993
Ref: library/socket socket herror6945175
Ref: 267d6945175
Ref: library/socket socket gaierror6945717
Ref: 267e6945717
Ref: library/socket socket timeout6946221
Ref: c166946221
Ref: 异常<11>-Footnote-16946642
Node: 常量<8>6946691
Ref: library/socket constants6946789
Ref: 26806946789
Ref: library/socket socket AF_UNIX6946974
Ref: 25be6946974
Ref: library/socket socket AF_INET6947001
Ref: 25b86947001
Ref: library/socket socket AF_INET66947028
Ref: 25b96947028
Ref: library/socket socket SOCK_STREAM6947297
Ref: c926947297
Ref: library/socket socket SOCK_DGRAM6947328
Ref: c916947328
Ref: library/socket socket SOCK_RAW6947358
Ref: 26816947358
Ref: library/socket socket SOCK_RDM6947386
Ref: 26826947386
Ref: library/socket socket SOCK_SEQPACKET6947414
Ref: 26836947414
Ref: library/socket socket SOCK_CLOEXEC6947679
Ref: 49f6947679
Ref: library/socket socket SOCK_NONBLOCK6947711
Ref: 49e6947711
Ref: library/socket socket SOMAXCONN6948181
Ref: 7556948181
Ref: library/socket socket AF_CAN6949312
Ref: 26766949312
Ref: library/socket socket PF_CAN6949338
Ref: 26846949338
Ref: library/socket socket CAN_BCM6949594
Ref: 8c26949594
Ref: library/socket socket CAN_RAW_FD_FRAMES6950004
Ref: 7ce6950004
Ref: library/socket socket CAN_ISOTP6950378
Ref: 26776950378
Ref: library/socket socket AF_PACKET6950610
Ref: 26786950610
Ref: library/socket socket PF_PACKET6950639
Ref: 26856950639
Ref: library/socket socket AF_RDS6950851
Ref: 26866950851
Ref: library/socket socket PF_RDS6950877
Ref: 26876950877
Ref: library/socket socket SOL_RDS6950903
Ref: 26886950903
Ref: library/socket socket SIO_RCVALL6951137
Ref: 26896951137
Ref: library/socket socket SIO_KEEPALIVE_VALS6951167
Ref: 268a6951167
Ref: library/socket socket SIO_LOOPBACK_FAST_PATH6951205
Ref: 58a6951205
Ref: library/socket socket AF_ALG6951588
Ref: 58d6951588
Ref: library/socket socket SOL_ALG6951614
Ref: 268b6951614
Ref: library/socket socket AF_VSOCK6951786
Ref: 3db6951786
Ref: library/socket socket IOCTL_VM_SOCKETS_GET_LOCAL_CID6951814
Ref: 268c6951814
Ref: library/socket socket AF_LINK6952035
Ref: 8c36952035
Ref: library/socket socket has_ipv66952132
Ref: 268d6952132
Ref: library/socket socket BDADDR_ANY6952242
Ref: 268e6952242
Ref: library/socket socket BDADDR_LOCAL6952272
Ref: 268f6952272
Ref: library/socket socket HCI_FILTER6952520
Ref: 26906952520
Ref: library/socket socket HCI_TIME_STAMP6952550
Ref: 26916952550
Ref: library/socket socket HCI_DATA_DIR6952584
Ref: 26926952584
Ref: library/socket socket AF_QIPCRTR6952851
Ref: 26796952851
Ref: 常量<8>-Footnote-16953062
Node: 函数<5>6953113
Ref: library/socket functions6953192
Ref: 26936953192
Node: 创建套接字6953286
Ref: library/socket creating-sockets6953371
Ref: 26946953371
Ref: library/socket socket socket6953472
Ref: 67d6953472
Ref: library/socket socket socketpair6955845
Ref: 4896955845
Ref: library/socket socket create_connection6956553
Ref: ba66956553
Ref: library/socket socket create_server6957647
Ref: 21f6957647
Ref: library/socket socket has_dualstack_ipv66959260
Ref: 2206959260
Ref: library/socket socket fromfd6959441
Ref: 26966959441
Ref: library/socket socket fromshare6960286
Ref: 49c6960286
Ref: library/socket socket SocketType6960510
Ref: 26986960510
Node: 其他功能<2>6960660
Ref: library/socket other-functions6960745
Ref: 26996960745
Ref: library/socket socket close6960848
Ref: 3d96960848
Ref: library/socket socket getaddrinfo6961132
Ref: 25cc6961132
Ref: library/socket socket getfqdn6963699
Ref: 269a6963699
Ref: library/socket socket gethostbyname6964184
Ref: 269b6964184
Ref: library/socket socket gethostbyname_ex6964722
Ref: eae6964722
Ref: library/socket socket gethostname6965457
Ref: 1f146965457
Ref: library/socket socket gethostbyaddr6965814
Ref: ead6965814
Ref: library/socket socket getnameinfo6966468
Ref: 25cd6966468
Ref: library/socket socket getprotobyname6967155
Ref: 269c6967155
Ref: library/socket socket getservbyname6967567
Ref: 269d6967567
Ref: library/socket socket getservbyport6967965
Ref: 269e6967965
Ref: library/socket socket ntohl6968349
Ref: 269f6968349
Ref: library/socket socket ntohs6968588
Ref: 4756968588
Ref: library/socket socket htonl6969077
Ref: 26a06969077
Ref: library/socket socket htons6969316
Ref: 4746969316
Ref: library/socket socket inet_aton6969805
Ref: 2f86969805
Ref: library/socket socket inet_ntoa6970666
Ref: 26a16970666
Ref: library/socket socket inet_pton6971409
Ref: 2f96971409
Ref: library/socket socket inet_ntop6972183
Ref: 8c46972183
Ref: library/socket socket CMSG_LEN6973136
Ref: 10316973136
Ref: library/socket socket CMSG_SPACE6973730
Ref: 10306973730
Ref: library/socket socket getdefaulttimeout6974504
Ref: 26976974504
Ref: library/socket socket setdefaulttimeout6974751
Ref: 267f6974751
Ref: library/socket socket sethostname6975029
Ref: a8f6975029
Ref: library/socket socket if_nameindex6975338
Ref: 2216975338
Ref: library/socket socket if_nametoindex6976142
Ref: 2226976142
Ref: library/socket socket if_indextoname6976541
Ref: 2236976541
Ref: 其他功能<2>-Footnote-16976987
Node: 套接字对象6977036
Ref: library/socket id16977180
Ref: 26a26977180
Ref: library/socket socket-objects6977180
Ref: 26956977180
Ref: library/socket socket socket accept6977504
Ref: 67e6977504
Ref: library/socket socket socket bind6978186
Ref: 26a36978186
Ref: library/socket socket socket close6978475
Ref: 6096978475
Ref: library/socket socket socket connect6979336
Ref: 67f6979336
Ref: library/socket socket socket connect_ex6980312
Ref: 26a56980312
Ref: library/socket socket socket detach6980861
Ref: ba56980861
Ref: library/socket socket socket dup6981081
Ref: 26a66981081
Ref: library/socket socket socket fileno6981269
Ref: 26a76981269
Ref: library/socket socket socket get_inheritable6981606
Ref: 8086981606
Ref: library/socket socket socket getpeername6981845
Ref: 26026981845
Ref: library/socket socket socket getsockname6982117
Ref: 26036982117
Ref: library/socket socket socket getsockopt6982335
Ref: 58b6982335
Ref: library/socket socket socket getblocking6982974
Ref: 3d86982974
Ref: library/socket socket socket gettimeout6983191
Ref: 26a86983191
Ref: library/socket socket socket ioctl6983441
Ref: 5896983441
Ref: library/socket socket socket listen6984003
Ref: 7546984003
Ref: library/socket socket socket makefile6984364
Ref: b216984364
Ref: library/socket socket socket recv6985378
Ref: 6806985378
Ref: library/socket socket socket recvfrom6986034
Ref: 6816986034
Ref: library/socket socket socket recvmsg6986853
Ref: 6826986853
Ref: library/socket socket socket recvmsg_into6990370
Ref: a8e6990370
Ref: library/socket socket socket recvfrom_into6991935
Ref: cbb6991935
Ref: library/socket socket socket recv_into6992390
Ref: cba6992390
Ref: library/socket socket socket send6992791
Ref: 6836992791
Ref: library/socket socket socket sendall6993494
Ref: 6846993494
Ref: library/socket socket socket sendto6994360
Ref: 6866994360
Ref: library/socket socket socket sendmsg6995118
Ref: 6856995118
Ref: library/socket socket socket sendmsg_afalg6997132
Ref: 58e6997132
Ref: library/socket socket socket sendfile6997470
Ref: 7536997470
Ref: library/socket socket socket set_inheritable6998306
Ref: 8096998306
Ref: library/socket socket socket setblocking6998469
Ref: 1f206998469
Ref: library/socket socket socket settimeout6999000
Ref: 267a6999000
Ref: library/socket socket socket setsockopt6999664
Ref: 58c6999664
Ref: library/socket socket socket shutdown7000702
Ref: 26a47000702
Ref: library/socket socket socket share7000991
Ref: 49b7000991
Ref: library/socket socket socket family7001817
Ref: 26ac7001817
Ref: library/socket socket socket type7001875
Ref: 4a07001875
Ref: library/socket socket socket proto7001928
Ref: 26ad7001928
Ref: 套接字对象-Footnote-17002018
Ref: 套接字对象-Footnote-27002067
Ref: 套接字对象-Footnote-37002116
Ref: 套接字对象-Footnote-47002190
Ref: 套接字对象-Footnote-57002239
Ref: 套接字对象-Footnote-67002288
Ref: 套接字对象-Footnote-77002337
Ref: 套接字对象-Footnote-87002386
Ref: 套接字对象-Footnote-97002435
Ref: 套接字对象-Footnote-107002484
Node: 关于套接字超时的说明7002534
Ref: library/socket notes-on-socket-timeouts7002672
Ref: 26ae7002672
Ref: library/socket socket-timeouts7002672
Ref: 26ab7002672
Node: 超时与 connect 方法7004002
Ref: library/socket timeouts-and-the-connect-method7004125
Ref: 26af7004125
Node: 超时与 accept 方法7004530
Ref: library/socket timeouts-and-the-accept-method7004653
Ref: 26b07004653
Node: 示例<8>7005326
Ref: library/socket example7005440
Ref: 26b17005440
Ref: library/socket socket-example7005440
Ref: 26b27005440
Ref: 示例<8>-Footnote-17013075
Node: ssl --- 套接字对象的TLS/SSL封装7013124
Ref: library/ssl doc7013299
Ref: 26b37013299
Ref: library/ssl module-ssl7013299
Ref: f47013299
Ref: library/ssl ssl-tls-ssl-wrapper-for-socket-objects7013299
Ref: 26b47013299
Ref: ssl --- 套接字对象的TLS/SSL封装-Footnote-17015504
Node: 方法、常量和异常处理7015566
Ref: library/ssl functions-constants-and-exceptions7015694
Ref: 26b57015694
Node: 套接字创建7015892
Ref: library/ssl socket-creation7015998
Ref: 26b67015998
Node: 上下文创建7017741
Ref: library/ssl context-creation7017866
Ref: 26b77017866
Ref: library/ssl ssl create_default_context7018004
Ref: 8c97018004
Ref: 上下文创建-Footnote-17020684
Node: 异常<12>7020729
Ref: library/ssl exceptions7020851
Ref: 26bd7020851
Ref: library/ssl ssl SSLError7020882
Ref: c177020882
Ref: library/ssl ssl SSLError library7021357
Ref: aa07021357
Ref: library/ssl ssl SSLError reason7021627
Ref: aa17021627
Ref: library/ssl ssl SSLZeroReturnError7021879
Ref: 26be7021879
Ref: library/ssl ssl SSLWantReadError7022145
Ref: 75f7022145
Ref: library/ssl ssl SSLWantWriteError7022429
Ref: 7607022429
Ref: library/ssl ssl SSLSyscallError7022717
Ref: 26c07022717
Ref: library/ssl ssl SSLEOFError7022968
Ref: 26c17022968
Ref: library/ssl ssl SSLCertVerificationError7023187
Ref: 3e57023187
Ref: library/ssl ssl SSLCertVerificationError verify_code7023332
Ref: 26c27023332
Ref: library/ssl ssl SSLCertVerificationError verify_message7023437
Ref: 26c37023437
Ref: library/ssl ssl CertificateError7023536
Ref: 26c47023536
Node: 随机生成7023726
Ref: library/ssl random-generation7023845
Ref: 26c57023845
Ref: library/ssl ssl RAND_bytes7023886
Ref: a977023886
Ref: library/ssl ssl RAND_pseudo_bytes7024546
Ref: a987024546
Ref: library/ssl ssl RAND_status7025342
Ref: 26c67025342
Ref: library/ssl ssl RAND_egd7025641
Ref: 26c87025641
Ref: library/ssl ssl RAND_add7026274
Ref: 26c77026274
Ref: 随机生成-Footnote-17026679
Ref: 随机生成-Footnote-27026773
Node: 证书处理7026822
Ref: library/ssl certificate-handling7026940
Ref: 26c97026940
Ref: library/ssl ssl match_hostname7026981
Ref: 3e47026981
Ref: library/ssl ssl cert_time_to_seconds7028729
Ref: 7617028729
Ref: library/ssl ssl get_server_certificate7029620
Ref: aa27029620
Ref: library/ssl ssl DER_cert_to_PEM_cert7030549
Ref: 26cb7030549
Ref: library/ssl ssl PEM_cert_to_DER_cert7030720
Ref: 26cc7030720
Ref: library/ssl ssl get_default_verify_paths7030889
Ref: 8ca7030889
Ref: library/ssl ssl enum_certificates7031828
Ref: 8d67031828
Ref: library/ssl ssl enum_crls7032703
Ref: 8d77032703
Ref: library/ssl ssl wrap_socket7033246
Ref: 4777033246
Ref: 证书处理-Footnote-17034764
Ref: 证书处理-Footnote-27034813
Ref: 证书处理-Footnote-37034862
Ref: 证书处理-Footnote-47034911
Ref: 证书处理-Footnote-57034960
Node: 常量<9>7035009
Ref: library/ssl constants7035106
Ref: 26cf7035106
Ref: library/ssl ssl CERT_NONE7035274
Ref: 26d07035274
Ref: library/ssl ssl CERT_OPTIONAL7035896
Ref: 26d27035896
Ref: library/ssl ssl CERT_REQUIRED7036707
Ref: 26bb7036707
Ref: library/ssl ssl VerifyMode7037717
Ref: 26d47037717
Ref: library/ssl ssl VERIFY_DEFAULT7037827
Ref: 8cf7037827
Ref: library/ssl ssl VERIFY_CRL_CHECK_LEAF7038060
Ref: 8d07038060
Ref: library/ssl ssl VERIFY_CRL_CHECK_CHAIN7038485
Ref: 8d17038485
Ref: library/ssl ssl VERIFY_X509_STRICT7038684
Ref: 8d27038684
Ref: library/ssl ssl VERIFY_X509_TRUSTED_FIRST7038862
Ref: 26d57038862
Ref: library/ssl ssl VerifyFlags7039129
Ref: 26d67039129
Ref: library/ssl ssl PROTOCOL_TLS7039243
Ref: 26b87039243
Ref: library/ssl ssl PROTOCOL_TLS_CLIENT7039450
Ref: 26d17039450
Ref: library/ssl ssl PROTOCOL_TLS_SERVER7039744
Ref: 26d77039744
Ref: library/ssl ssl PROTOCOL_SSLv237039946
Ref: 26d87039946
Ref: library/ssl ssl PROTOCOL_SSLv27040090
Ref: 26d97040090
Ref: library/ssl ssl PROTOCOL_SSLv37040418
Ref: 26ca7040418
Ref: library/ssl ssl PROTOCOL_TLSv17040871
Ref: 26da7040871
Ref: library/ssl ssl PROTOCOL_TLSv1_17041156
Ref: 8c77041156
Ref: library/ssl ssl PROTOCOL_TLSv1_27041505
Ref: 8c87041505
Ref: library/ssl ssl OP_ALL7041977
Ref: 26db7041977
Ref: library/ssl ssl OP_NO_SSLv27042209
Ref: ba87042209
Ref: library/ssl ssl OP_NO_SSLv37042462
Ref: 26b97042462
Ref: library/ssl ssl OP_NO_TLSv17042712
Ref: 26dc7042712
Ref: library/ssl ssl OP_NO_TLSv1_17043099
Ref: 26dd7043099
Ref: library/ssl ssl OP_NO_TLSv1_27043426
Ref: 26de7043426
Ref: library/ssl ssl OP_NO_TLSv1_37043753
Ref: 26df7043753
Ref: library/ssl ssl OP_NO_RENEGOTIATION7044268
Ref: 26e07044268
Ref: library/ssl ssl OP_CIPHER_SERVER_PREFERENCE7044552
Ref: aa37044552
Ref: library/ssl ssl OP_SINGLE_DH_USE7044780
Ref: 26e17044780
Ref: library/ssl ssl OP_SINGLE_ECDH_USE7045015
Ref: 26e27045015
Ref: library/ssl ssl OP_ENABLE_MIDDLEBOX_COMPAT7045254
Ref: 26e37045254
Ref: library/ssl ssl OP_NO_COMPRESSION7045525
Ref: a9e7045525
Ref: library/ssl ssl Options7045751
Ref: 26e47045751
Ref: library/ssl ssl OP_NO_TICKET7045833
Ref: 26e57045833
Ref: library/ssl ssl OP_IGNORE_UNEXPECTED_EOF7045930
Ref: ea57045930
Ref: library/ssl ssl HAS_ALPN7046103
Ref: 75c7046103
Ref: library/ssl ssl HAS_NEVER_CHECK_COMMON_NAME7046270
Ref: 26e67046270
Ref: library/ssl ssl HAS_ECDH7046492
Ref: 26e77046492
Ref: library/ssl ssl HAS_SNI7046721
Ref: 26e87046721
Ref: library/ssl ssl HAS_NPN7046889
Ref: 26e97046889
Ref: library/ssl ssl HAS_SSLv27047189
Ref: 26ea7047189
Ref: library/ssl ssl HAS_SSLv37047306
Ref: 26eb7047306
Ref: library/ssl ssl HAS_TLSv17047423
Ref: 26ec7047423
Ref: library/ssl ssl HAS_TLSv1_17047540
Ref: 3f17047540
Ref: library/ssl ssl HAS_TLSv1_27047659
Ref: 26ed7047659
Ref: library/ssl ssl HAS_TLSv1_37047778
Ref: 26ee7047778
Ref: library/ssl ssl CHANNEL_BINDING_TYPES7047897
Ref: 26ef7047897
Ref: library/ssl ssl OPENSSL_VERSION7048125
Ref: ba97048125
Ref: library/ssl ssl OPENSSL_VERSION_INFO7048316
Ref: baa7048316
Ref: library/ssl ssl OPENSSL_VERSION_NUMBER7048520
Ref: bab7048520
Ref: library/ssl ssl ALERT_DESCRIPTION_HANDSHAKE_FAILURE7048776
Ref: 26f07048776
Ref: library/ssl ssl ALERT_DESCRIPTION_INTERNAL_ERROR7048828
Ref: 26f17048828
Ref: library/ssl ssl AlertDescription7049189
Ref: 26f27049189
Ref: library/ssl ssl Purpose SERVER_AUTH7049318
Ref: 8d47049318
Ref: library/ssl ssl Purpose CLIENT_AUTH7049613
Ref: 8d57049613
Ref: library/ssl ssl SSLErrorNumber7049911
Ref: 26f37049911
Ref: library/ssl ssl TLSVersion7050030
Ref: 26f47050030
Ref: library/ssl ssl TLSVersion MINIMUM_SUPPORTED7050244
Ref: 26f57050244
Ref: library/ssl ssl TLSVersion MAXIMUM_SUPPORTED7050286
Ref: 26f67050286
Ref: library/ssl ssl TLSVersion SSLv37050494
Ref: 26f77050494
Ref: library/ssl ssl TLSVersion TLSv17050524
Ref: 26f87050524
Ref: library/ssl ssl TLSVersion TLSv1_17050554
Ref: 26f97050554
Ref: library/ssl ssl TLSVersion TLSv1_27050586
Ref: 26fa7050586
Ref: library/ssl ssl TLSVersion TLSv1_37050618
Ref: 26fb7050618
Ref: 常量<9>-Footnote-17050715
Ref: 常量<9>-Footnote-27050764
Ref: 常量<9>-Footnote-37050813
Ref: 常量<9>-Footnote-47050891
Ref: 常量<9>-Footnote-57050940
Node: SSL 套接字7051033
Ref: library/ssl ssl-sockets7051183
Ref: 26fc7051183
Ref: library/ssl ssl SSLSocket7051227
Ref: 3ea7051227
Ref: library/ssl ssl SSLSocket read7053278
Ref: 7647053278
Ref: library/ssl ssl SSLSocket write7054095
Ref: 7657054095
Ref: library/ssl ssl SSLSocket do_handshake7055236
Ref: 7637055236
Ref: library/ssl ssl SSLSocket getpeercert7055939
Ref: 8d97055939
Ref: library/ssl ssl SSLSocket cipher7059224
Ref: 26047059224
Ref: library/ssl ssl SSLSocket shared_ciphers7059477
Ref: 7627059477
Ref: library/ssl ssl SSLSocket compression7059921
Ref: a9d7059921
Ref: library/ssl ssl SSLSocket get_channel_binding7060249
Ref: a9c7060249
Ref: library/ssl ssl SSLSocket selected_alpn_protocol7060811
Ref: 75b7060811
Ref: library/ssl ssl SSLSocket selected_npn_protocol7061172
Ref: 26ff7061172
Ref: library/ssl ssl SSLSocket unwrap7061549
Ref: 26fd7061549
Ref: library/ssl ssl SSLSocket verify_client_post_handshake7061886
Ref: 2267061886
Ref: library/ssl ssl SSLSocket version7062732
Ref: 75e7062732
Ref: library/ssl ssl SSLSocket pending7063138
Ref: 27007063138
Ref: library/ssl ssl SSLSocket context7063236
Ref: 26fe7063236
Ref: library/ssl ssl SSLSocket server_side7063579
Ref: 27017063579
Ref: library/ssl ssl SSLSocket server_hostname7063758
Ref: 3e87063758
Ref: library/ssl ssl SSLSocket session7064233
Ref: 27027064233
Ref: library/ssl ssl SSLSocket session_reused7064549
Ref: 27037064549
Ref: SSL 套接字-Footnote-17064647
Ref: SSL 套接字-Footnote-27064696
Node: SSL 上下文7064745
Ref: library/ssl ssl-contexts7064871
Ref: 27047064871
Ref: library/ssl ssl SSLContext7065154
Ref: 3ec7065154
Ref: library/ssl ssl SSLContext cert_store_stats7069047
Ref: 8cc7069047
Ref: library/ssl ssl SSLContext load_cert_chain7069437
Ref: a997069437
Ref: library/ssl ssl SSLContext load_default_certs7070828
Ref: 8d37070828
Ref: library/ssl ssl SSLContext load_verify_locations7071573
Ref: 7f47071573
Ref: library/ssl ssl SSLContext get_ca_certs7072739
Ref: 8cd7072739
Ref: library/ssl ssl SSLContext get_ciphers7073358
Ref: 5957073358
Ref: library/ssl ssl SSLContext set_default_verify_paths7075506
Ref: 8cb7075506
Ref: library/ssl ssl SSLContext set_ciphers7075933
Ref: 26ce7075933
Ref: library/ssl ssl SSLContext set_alpn_protocols7076556
Ref: 75a7076556
Ref: library/ssl ssl SSLContext set_npn_protocols7077378
Ref: a9f7077378
Ref: library/ssl ssl SSLContext sni_callback7078036
Ref: eb87078036
Ref: library/ssl ssl SSLContext set_servername_callback7080341
Ref: 8d87080341
Ref: library/ssl ssl SSLContext load_dh_params7080980
Ref: a9a7080980
Ref: library/ssl ssl SSLContext set_ecdh_curve7081477
Ref: a9b7081477
Ref: library/ssl ssl SSLContext wrap_socket7082179
Ref: 3ed7082179
Ref: library/ssl ssl SSLContext sslsocket_class7084743
Ref: 27067084743
Ref: library/ssl ssl SSLContext wrap_bio7085012
Ref: 3ee7085012
Ref: library/ssl ssl SSLContext sslobject_class7085703
Ref: 27077085703
Ref: library/ssl ssl SSLContext session_stats7085969
Ref: 27087085969
Ref: library/ssl ssl SSLContext check_hostname7086377
Ref: 26d37086377
Ref: library/ssl ssl SSLContext keylog_filename7087908
Ref: 26bc7087908
Ref: library/ssl ssl SSLContext maximum_version7088411
Ref: 3f07088411
Ref: library/ssl ssl SSLContext minimum_version7089339
Ref: 3ef7089339
Ref: library/ssl ssl SSLContext num_tickets7089688
Ref: 27097089688
Ref: library/ssl ssl SSLContext options7090013
Ref: 26cd7090013
Ref: library/ssl ssl SSLContext post_handshake_auth7090714
Ref: 2257090714
Ref: library/ssl ssl SSLContext protocol7091666
Ref: 270a7091666
Ref: library/ssl ssl SSLContext hostname_checks_common_name7091779
Ref: 3e67091779
Ref: library/ssl ssl SSLContext verify_flags7092252
Ref: 8ce7092252
Ref: library/ssl ssl SSLContext verify_mode7092808
Ref: 26ba7092808
Ref: SSL 上下文-Footnote-17093305
Ref: SSL 上下文-Footnote-27093451
Ref: SSL 上下文-Footnote-37093543
Ref: SSL 上下文-Footnote-47093636
Ref: SSL 上下文-Footnote-57093782
Ref: SSL 上下文-Footnote-67093874
Ref: SSL 上下文-Footnote-77093967
Ref: SSL 上下文-Footnote-87094055
Ref: SSL 上下文-Footnote-97094120
Ref: SSL 上下文-Footnote-107094169
Ref: SSL 上下文-Footnote-117094248
Ref: SSL 上下文-Footnote-127094298
Ref: SSL 上下文-Footnote-137094375
Node: 证书7094452
Ref: library/ssl certificates7094575
Ref: 270b7094575
Ref: library/ssl ssl-certificates7094575
Ref: 27057094575
Ref: 证书-Footnote-17096663
Node: 证书链7096712
Ref: library/ssl certificate-chains7096782
Ref: 270c7096782
Node: CA 证书7097885
Ref: library/ssl ca-certificates7097988
Ref: 270d7097988
Node: 合并的密钥和证书7098543
Ref: library/ssl combined-key-and-certificate7098652
Ref: 270e7098652
Node: 自签名证书7099229
Ref: library/ssl self-signed-certificates7099320
Ref: 270f7099320
Node: 例子<16>7100886
Ref: library/ssl examples7101029
Ref: 27107101029
Node: 检测 SSL 支持7101137
Ref: library/ssl testing-for-ssl-support7101225
Ref: 27117101225
Node: 客户端操作7101514
Ref: library/ssl client-side-operation7101629
Ref: 27127101629
Node: 服务器端操作7106214
Ref: library/ssl server-side-operation7106303
Ref: 27137106303
Node: 关于非阻塞套接字的说明7108282
Ref: library/ssl notes-on-non-blocking-sockets7108439
Ref: 27147108439
Ref: library/ssl ssl-nonblocking7108439
Ref: 26bf7108439
Node: 内存 BIO 支持<2>7111156
Ref: library/ssl memory-bio-support7111313
Ref: 27167111313
Ref: library/ssl ssl SSLObject7112382
Ref: 3eb7112382
Ref: library/ssl ssl MemoryBIO7115841
Ref: 7587115841
Ref: library/ssl ssl MemoryBIO pending7115960
Ref: 27177115960
Ref: library/ssl ssl MemoryBIO eof7116049
Ref: 27187116049
Ref: library/ssl ssl MemoryBIO read7116151
Ref: 27197116151
Ref: library/ssl ssl MemoryBIO write7116317
Ref: 271a7116317
Ref: library/ssl ssl MemoryBIO write_eof7116554
Ref: 271b7116554
Node: SSL 会话7116839
Ref: library/ssl ssl-session7116978
Ref: 271c7116978
Ref: library/ssl ssl SSLSession7117038
Ref: 5947117038
Ref: library/ssl ssl SSLSession id7117118
Ref: 271d7117118
Ref: library/ssl ssl SSLSession time7117139
Ref: 271e7117139
Ref: library/ssl ssl SSLSession timeout7117162
Ref: 271f7117162
Ref: library/ssl ssl SSLSession ticket_lifetime_hint7117188
Ref: 27207117188
Ref: library/ssl ssl SSLSession has_ticket7117227
Ref: 27217117227
Node: 安全考量<2>7117256
Ref: library/ssl security-considerations7117382
Ref: 27227117382
Ref: library/ssl ssl-security7117382
Ref: 25bd7117382
Node: 最佳默认值7117486
Ref: library/ssl best-defaults7117574
Ref: 27237117574
Node: 手动设置7118648
Ref: library/ssl manual-settings7118754
Ref: 27247118754
Node: 验证证书7118858
Ref: library/ssl verifying-certificates7118940
Ref: 27257118940
Node: 协议版本7120098
Ref: library/ssl protocol-versions7120201
Ref: 27267120201
Node: 密码选择7120949
Ref: library/ssl cipher-selection7121031
Ref: 27277121031
Ref: 密码选择-Footnote-17121642
Node: 多进程7121727
Ref: library/ssl multi-processing7121809
Ref: 27287121809
Node: TLS 1 37122318
Ref: library/ssl ssl-tlsv1-37122449
Ref: 3e97122449
Ref: library/ssl tls-1-37122449
Ref: 27297122449
Node: LibreSSL 支持7123539
Ref: library/ssl libressl-support7123646
Ref: 272a7123646
Ref: library/ssl ssl-libressl7123646
Ref: 272b7123646
Ref: LibreSSL 支持-Footnote-17125115
Ref: LibreSSL 支持-Footnote-27125181
Ref: LibreSSL 支持-Footnote-37125230
Ref: LibreSSL 支持-Footnote-47125279
Ref: LibreSSL 支持-Footnote-57125328
Ref: LibreSSL 支持-Footnote-67125377
Ref: LibreSSL 支持-Footnote-77125426
Ref: LibreSSL 支持-Footnote-87125502
Ref: LibreSSL 支持-Footnote-97125551
Node: select --- 等待 I/O 完成7125609
Ref: library/select doc7125789
Ref: 272c7125789
Ref: library/select module-select7125789
Ref: e67125789
Ref: library/select select-waiting-for-i-o-completion7125789
Ref: 272d7125789
Ref: library/select select error7126785
Ref: 99e7126785
Ref: library/select select devpoll7126967
Ref: 8b47126967
Ref: library/select select epoll7127637
Ref: 8b27127637
Ref: library/select select poll7129025
Ref: 27157129025
Ref: library/select select kqueue7129312
Ref: 27317129312
Ref: library/select select kevent7129626
Ref: 27337129626
Ref: library/select select select7129886
Ref: 67c7129886
Ref: library/select select PIPE_BUF7132006
Ref: b8e7132006
Ref: select --- 等待 I/O 完成-Footnote-17132639
Ref: select --- 等待 I/O 完成-Footnote-27132688
Node: /dev/poll 轮询对象7132737
Ref: library/select dev-poll-polling-objects7132882
Ref: 27357132882
Ref: library/select devpoll-objects7132882
Ref: 272e7132882
Ref: library/select select devpoll close7133242
Ref: 8b67133242
Ref: library/select select devpoll closed7133342
Ref: 8b77133342
Ref: library/select select devpoll fileno7133454
Ref: 8b57133454
Ref: library/select select devpoll register7133570
Ref: 27367133570
Ref: library/select select devpoll modify7134453
Ref: 27377134453
Ref: library/select select devpoll unregister7134643
Ref: 27387134643
Ref: library/select select devpoll poll7134990
Ref: 6787134990
Ref: /dev/poll 轮询对象-Footnote-17136045
Node: 边缘触发和水平触发的轮询 epoll 对象7136094
Ref: library/select edge-and-level-trigger-polling-epoll-objects7136259
Ref: 27397136259
Ref: library/select epoll-objects7136259
Ref: 272f7136259
Ref: library/select select epoll close7139039
Ref: 8b37139039
Ref: library/select select epoll closed7139126
Ref: 273a7139126
Ref: library/select select epoll fileno7139213
Ref: 273b7139213
Ref: library/select select epoll fromfd7139328
Ref: 273c7139328
Ref: library/select select epoll register7139418
Ref: 273d7139418
Ref: library/select select epoll modify7139520
Ref: 273e7139520
Ref: library/select select epoll unregister7139611
Ref: 273f7139611
Ref: library/select select epoll poll7139714
Ref: 6797139714
Ref: 边缘触发和水平触发的轮询 epoll 对象-Footnote-17140113
Node: Poll 对象7140162
Ref: library/select poll-objects7140318
Ref: 27307140318
Ref: library/select polling-objects7140318
Ref: 27407140318
Ref: library/select select poll register7140866
Ref: 27417140866
Ref: library/select select poll modify7142695
Ref: 27427142695
Ref: library/select select poll unregister7142944
Ref: 27437142944
Ref: library/select select poll poll7143304
Ref: 67b7143304
Ref: Poll 对象-Footnote-17144360
Node: Kqueue 对象7144409
Ref: library/select id17144529
Ref: 27447144529
Ref: library/select kqueue-objects7144529
Ref: 27327144529
Ref: library/select select kqueue close7144574
Ref: 27457144574
Ref: library/select select kqueue closed7144663
Ref: 27467144663
Ref: library/select select kqueue fileno7144752
Ref: 27477144752
Ref: library/select select kqueue fromfd7144868
Ref: 27487144868
Ref: library/select select kqueue control7144960
Ref: 67a7144960
Ref: Kqueue 对象-Footnote-17145630
Node: Kevent 对象7145679
Ref: library/select id27145779
Ref: 27497145779
Ref: library/select kevent-objects7145779
Ref: 27347145779
Ref: library/select select kevent ident7145890
Ref: 274a7145890
Ref: library/select select kevent filter7146163
Ref: 274b7146163
Ref: library/select select kevent flags7147710
Ref: 274c7147710
Ref: library/select select kevent fflags7149323
Ref: 274d7149323
Ref: library/select select kevent data7153020
Ref: 274e7153020
Ref: library/select select kevent udata7153073
Ref: 274f7153073
Node: selectors --- 高级 I/O 复用库7153127
Ref: library/selectors doc7153302
Ref: 27507153302
Ref: library/selectors module-selectors7153302
Ref: e77153302
Ref: library/selectors selectors-high-level-i-o-multiplexing7153302
Ref: 27517153302
Ref: selectors --- 高级 I/O 复用库-Footnote-17153611
Node: 概述<10>7153679
Ref: library/selectors introduction7153775
Ref: 27527153775
Node: 类<3>7154866
Ref: library/selectors classes7154981
Ref: 27557154981
Ref: library/selectors selectors SelectorKey7155706
Ref: 27567155706
Ref: library/selectors selectors SelectorKey fileobj7155973
Ref: 27577155973
Ref: library/selectors selectors SelectorKey fd7156038
Ref: 27587156038
Ref: library/selectors selectors SelectorKey events7156098
Ref: 27597156098
Ref: library/selectors selectors SelectorKey data7156183
Ref: 275a7156183
Ref: library/selectors selectors BaseSelector7156343
Ref: 27537156343
Ref: library/selectors selectors BaseSelector register7156928
Ref: 275b7156928
Ref: library/selectors selectors BaseSelector unregister7157565
Ref: 275c7157565
Ref: library/selectors selectors BaseSelector modify7158143
Ref: 4567158143
Ref: library/selectors selectors BaseSelector select7158708
Ref: 275d7158708
Ref: library/selectors selectors BaseSelector close7159909
Ref: 275e7159909
Ref: library/selectors selectors BaseSelector get_key7160092
Ref: 275f7160092
Ref: library/selectors selectors BaseSelector get_map7160351
Ref: 27607160351
Ref: library/selectors selectors DefaultSelector7160612
Ref: 27547160612
Ref: library/selectors selectors SelectSelector7160776
Ref: 26537160776
Ref: library/selectors selectors PollSelector7160868
Ref: 4547160868
Ref: library/selectors selectors EpollSelector7160957
Ref: 4537160957
Ref: library/selectors selectors EpollSelector fileno7161047
Ref: 27617161047
Ref: library/selectors selectors DevpollSelector7161189
Ref: 4557161189
Ref: library/selectors selectors DevpollSelector fileno7161283
Ref: 27627161283
Ref: library/selectors selectors KqueueSelector7161451
Ref: 26567161451
Ref: library/selectors selectors KqueueSelector fileno7161544
Ref: 27637161544
Ref: 类<3>-Footnote-17161724
Node: 例子<17>7161773
Ref: library/selectors examples7161869
Ref: 27647161869
Node: asyncore --- 异步socket处理器7162892
Ref: library/asyncore doc7163089
Ref: 27657163089
Ref: library/asyncore asyncore-asynchronous-socket-handler7163089
Ref: 27667163089
Ref: library/asyncore module-asyncore7163089
Ref: b7163089
Ref: library/asyncore asyncore loop7165153
Ref: 27677165153
Ref: library/asyncore asyncore dispatcher7166059
Ref: bcb7166059
Ref: library/asyncore asyncore dispatcher handle_read7167723
Ref: 276a7167723
Ref: library/asyncore asyncore dispatcher handle_write7167877
Ref: 276b7167877
Ref: library/asyncore asyncore dispatcher handle_expt7168231
Ref: 276c7168231
Ref: library/asyncore asyncore dispatcher handle_connect7168434
Ref: 276d7168434
Ref: library/asyncore asyncore dispatcher handle_close7168647
Ref: 276e7168647
Ref: library/asyncore asyncore dispatcher handle_error7168729
Ref: 276f7168729
Ref: library/asyncore asyncore dispatcher handle_accept7168901
Ref: bcd7168901
Ref: library/asyncore asyncore dispatcher handle_accepted7169227
Ref: bcc7169227
Ref: library/asyncore asyncore dispatcher readable7169647
Ref: 27687169647
Ref: library/asyncore asyncore dispatcher writable7169963
Ref: 27697169963
Ref: library/asyncore asyncore dispatcher create_socket7170422
Ref: 27717170422
Ref: library/asyncore asyncore dispatcher connect7170764
Ref: 27707170764
Ref: library/asyncore asyncore dispatcher send7170959
Ref: 27727170959
Ref: library/asyncore asyncore dispatcher recv7171048
Ref: 27737171048
Ref: library/asyncore asyncore dispatcher listen7171445
Ref: 27747171445
Ref: library/asyncore asyncore dispatcher bind7171659
Ref: 27757171659
Ref: library/asyncore asyncore dispatcher accept7172064
Ref: bce7172064
Ref: library/asyncore asyncore dispatcher close7172612
Ref: 27767172612
Ref: library/asyncore asyncore dispatcher_with_send7172883
Ref: 27777172883
Ref: library/asyncore asyncore file_dispatcher7173109
Ref: 27787173109
Ref: library/asyncore asyncore file_wrapper7173541
Ref: 27797173541
Ref: asyncore --- 异步socket处理器-Footnote-17174032
Node: asyncore 示例基本 HTTP 客户端7174099
Ref: library/asyncore asyncore-example-17174251
Ref: 277a7174251
Ref: library/asyncore asyncore-example-basic-http-client7174251
Ref: 277b7174251
Node: asyncore 示例基本回显服务器7175262
Ref: library/asyncore asyncore-example-27175414
Ref: 277c7175414
Ref: library/asyncore asyncore-example-basic-echo-server7175414
Ref: 277d7175414
Node: asynchat --- 异步 socket 指令/响应 处理器7176327
Ref: library/asynchat doc7176531
Ref: 277e7176531
Ref: library/asynchat asynchat-asynchronous-socket-command-response-handler7176531
Ref: 277f7176531
Ref: library/asynchat module-asynchat7176531
Ref: 97176531
Ref: library/asynchat asynchat async_chat7177650
Ref: 8be7177650
Ref: library/asynchat asynchat async_chat ac_in_buffer_size7178505
Ref: 27827178505
Ref: library/asynchat asynchat async_chat ac_out_buffer_size7178606
Ref: 27837178606
Ref: library/asynchat asynchat async_chat close_when_done7179740
Ref: 27857179740
Ref: library/asynchat asynchat async_chat collect_incoming_data7179899
Ref: 27807179899
Ref: library/asynchat asynchat async_chat discard_buffers7180123
Ref: 27867180123
Ref: library/asynchat asynchat async_chat found_terminator7180285
Ref: 27817180285
Ref: library/asynchat asynchat async_chat get_terminator7180608
Ref: 27877180608
Ref: library/asynchat asynchat async_chat push7180690
Ref: 27887180690
Ref: library/asynchat asynchat async_chat push_with_producer7180983
Ref: 27897180983
Ref: library/asynchat asynchat async_chat set_terminator7181308
Ref: 27847181308
Ref: asynchat --- 异步 socket 指令/响应 处理器-Footnote-17182289
Node: asynchat 示例7182356
Ref: library/asynchat asynchat-example7182458
Ref: 278a7182458
Ref: library/asynchat id17182458
Ref: 278b7182458
Node: signal --- 设置异步事件处理程序7184743
Ref: library/signal doc7184946
Ref: 278c7184946
Ref: library/signal module-signal7184946
Ref: eb7184946
Ref: library/signal signal-set-handlers-for-asynchronous-events7184946
Ref: 278d7184946
Node: 一般规则7185289
Ref: library/signal general-rules7185403
Ref: 278e7185403
Node: 执行 Python 信号处理程序7186114
Ref: library/signal execution-of-python-signal-handlers7186219
Ref: 27917186219
Node: 信号与线程7187225
Ref: library/signal id17187330
Ref: 27957187330
Ref: library/signal signals-and-threads7187330
Ref: 27967187330
Node: 模块内容<5>7187678
Ref: library/signal module-contents7187810
Ref: 27977187810
Ref: library/signal signal SIG_DFL7188333
Ref: 24e37188333
Ref: library/signal signal SIG_IGN7188630
Ref: 24e47188630
Ref: library/signal signal SIGABRT7188746
Ref: 279c7188746
Ref: library/signal signal SIGALRM7188821
Ref: 279d7188821
Ref: library/signal signal SIGBREAK7188937
Ref: 279e7188937
Ref: library/signal signal SIGBUS7189054
Ref: 279f7189054
Ref: library/signal signal SIGCHLD7189165
Ref: 27907189165
Ref: library/signal signal SIGCLD7189268
Ref: 27a07189268
Ref: library/signal signal SIGCONT7189335
Ref: 1fd67189335
Ref: library/signal signal SIGFPE7189453
Ref: 27937189453
Ref: library/signal signal SIGHUP7189651
Ref: 27a17189651
Ref: library/signal signal SIGILL7189783
Ref: 27a27189783
Ref: library/signal signal SIGINT7189832
Ref: 24e27189832
Ref: library/signal signal SIGKILL7189965
Ref: 27a37189965
Ref: library/signal signal SIGPIPE7190099
Ref: 278f7190099
Ref: library/signal signal SIGSEGV7190269
Ref: 27947190269
Ref: library/signal signal SIGTERM7190340
Ref: 257e7190340
Ref: library/signal signal SIGUSR17190390
Ref: 27a47190390
Ref: library/signal signal SIGUSR27190489
Ref: 27a57190489
Ref: library/signal signal SIGWINCH7190588
Ref: 27a67190588
Ref: library/signal signal CTRL_C_EVENT7191233
Ref: 1fb27191233
Ref: library/signal signal CTRL_BREAK_EVENT7191437
Ref: 1fb37191437
Ref: library/signal signal NSIG7191649
Ref: 27a77191649
Ref: library/signal signal ITIMER_REAL7191708
Ref: 27a87191708
Ref: library/signal signal ITIMER_VIRTUAL7191823
Ref: 27a97191823
Ref: library/signal signal ITIMER_PROF7191945
Ref: 27aa7191945
Ref: library/signal signal SIG_BLOCK7192237
Ref: 27987192237
Ref: library/signal signal SIG_UNBLOCK7192404
Ref: 27997192404
Ref: library/signal signal SIG_SETMASK7192576
Ref: 279a7192576
Ref: library/signal signal ItimerError7192799
Ref: 27ab7192799
Ref: library/signal signal alarm7193283
Ref: 27ae7193283
Ref: library/signal signal getsignal7193943
Ref: 279b7193943
Ref: library/signal signal strsignal7194456
Ref: 103f7194456
Ref: library/signal signal valid_signals7194684
Ref: 27af7194684
Ref: library/signal signal pause7194906
Ref: 27b07194906
Ref: library/signal signal raise_signal7195273
Ref: 27b17195273
Ref: library/signal signal pthread_kill7195401
Ref: a827195401
Ref: library/signal signal pthread_sigmask7196573
Ref: a817196573
Ref: library/signal signal setitimer7197887
Ref: 27ac7197887
Ref: library/signal signal getitimer7198899
Ref: 27ad7198899
Ref: library/signal signal set_wakeup_fd7199045
Ref: 3d67199045
Ref: library/signal signal siginterrupt7201124
Ref: a867201124
Ref: library/signal signal signal7201670
Ref: a857201670
Ref: library/signal signal sigpending7203066
Ref: a837203066
Ref: library/signal signal sigwait7203475
Ref: a847203475
Ref: library/signal signal sigwaitinfo7203996
Ref: 6887203996
Ref: library/signal signal sigtimedwait7205129
Ref: 6877205129
Ref: 模块内容<5>-Footnote-17205906
Ref: 模块内容<5>-Footnote-27205955
Node: 示例<9>7206004
Ref: library/signal example7206148
Ref: 27b27206148
Ref: library/signal signal-example7206148
Ref: 27b37206148
Node: 对于 SIGPIPE 的说明7207020
Ref: library/signal note-on-sigpipe7207140
Ref: 27b47207140
Node: mmap --- 内存映射文件支持7208523
Ref: library/mmap doc7208667
Ref: 27b57208667
Ref: library/mmap mmap-memory-mapped-file-support7208667
Ref: 27b67208667
Ref: library/mmap module-mmap7208667
Ref: b47208667
Ref: library/mmap mmap mmap7210929
Ref: 1ed7210929
Ref: library/mmap mmap mmap close7215590
Ref: 27b77215590
Ref: library/mmap mmap mmap closed7215770
Ref: 27b87215770
Ref: library/mmap mmap mmap find7215880
Ref: 27b97215880
Ref: library/mmap mmap mmap flush7216263
Ref: 2c47216263
Ref: library/mmap mmap mmap madvise7217051
Ref: 1ee7217051
Ref: library/mmap mmap mmap move7217585
Ref: 27bb7217585
Ref: library/mmap mmap mmap read7217850
Ref: a2a7217850
Ref: library/mmap mmap mmap read_byte7218275
Ref: 27bc7218275
Ref: library/mmap mmap mmap readline7218410
Ref: 27bd7218410
Ref: library/mmap mmap mmap resize7218550
Ref: 27be7218550
Ref: library/mmap mmap mmap rfind7218817
Ref: 27bf7218817
Ref: library/mmap mmap mmap seek7219201
Ref: 27c07219201
Ref: library/mmap mmap mmap size7219546
Ref: 27c17219546
Ref: library/mmap mmap mmap tell7219659
Ref: 27c27219659
Ref: library/mmap mmap mmap write7219733
Ref: 27c37219733
Ref: library/mmap mmap mmap write_byte7220336
Ref: 27c47220336
Node: MADV_* 常量7220631
Ref: library/mmap madv-constants7220714
Ref: 27c57220714
Ref: library/mmap madvise-constants7220714
Ref: 27ba7220714
Ref: library/mmap mmap MADV_NORMAL7220759
Ref: 27c67220759
Ref: library/mmap mmap MADV_RANDOM7220788
Ref: 27c77220788
Ref: library/mmap mmap MADV_SEQUENTIAL7220817
Ref: 27c87220817
Ref: library/mmap mmap MADV_WILLNEED7220850
Ref: 27c97220850
Ref: library/mmap mmap MADV_DONTNEED7220881
Ref: 27ca7220881
Ref: library/mmap mmap MADV_REMOVE7220912
Ref: 27cb7220912
Ref: library/mmap mmap MADV_DONTFORK7220941
Ref: 27cc7220941
Ref: library/mmap mmap MADV_DOFORK7220972
Ref: 27cd7220972
Ref: library/mmap mmap MADV_HWPOISON7221001
Ref: 27ce7221001
Ref: library/mmap mmap MADV_MERGEABLE7221032
Ref: 27cf7221032
Ref: library/mmap mmap MADV_UNMERGEABLE7221064
Ref: 27d07221064
Ref: library/mmap mmap MADV_SOFT_OFFLINE7221098
Ref: 27d17221098
Ref: library/mmap mmap MADV_HUGEPAGE7221133
Ref: 27d27221133
Ref: library/mmap mmap MADV_NOHUGEPAGE7221164
Ref: 27d37221164
Ref: library/mmap mmap MADV_DONTDUMP7221197
Ref: 27d47221197
Ref: library/mmap mmap MADV_DODUMP7221228
Ref: 27d57221228
Ref: library/mmap mmap MADV_FREE7221257
Ref: 27d67221257
Ref: library/mmap mmap MADV_NOSYNC7221284
Ref: 27d77221284
Ref: library/mmap mmap MADV_AUTOSYNC7221313
Ref: 27d87221313
Ref: library/mmap mmap MADV_NOCORE7221344
Ref: 27d97221344
Ref: library/mmap mmap MADV_CORE7221373
Ref: 27da7221373
Ref: library/mmap mmap MADV_PROTECT7221400
Ref: 27db7221400
Node: 互联网数据处理7221630
Ref: library/netdata doc7221773
Ref: 27dc7221773
Ref: library/netdata internet-data-handling7221773
Ref: 27dd7221773
Ref: library/netdata netdata7221773
Ref: 27de7221773
Node: email --- 电子邮件与 MIME 处理包7222797
Ref: library/email doc7222936
Ref: 27df7222936
Ref: library/email email-an-email-and-mime-handling-package7222936
Ref: 27e07222936
Ref: library/email module-email7222936
Ref: 697222936
Ref: email --- 电子邮件与 MIME 处理包-Footnote-17228979
Ref: email --- 电子邮件与 MIME 处理包-Footnote-27229052
Ref: email --- 电子邮件与 MIME 处理包-Footnote-37229101
Ref: email --- 电子邮件与 MIME 处理包-Footnote-47229150
Ref: email --- 电子邮件与 MIME 处理包-Footnote-57229199
Ref: email --- 电子邮件与 MIME 处理包-Footnote-67229248
Ref: email --- 电子邮件与 MIME 处理包-Footnote-77229297
Ref: email --- 电子邮件与 MIME 处理包-Footnote-87229346
Ref: email --- 电子邮件与 MIME 处理包-Footnote-97229395
Node: email message 表示一封电子邮件信息7229444
Ref: library/email message doc7229611
Ref: 27e17229611
Ref: library/email message email-message-representing-an-email-message7229611
Ref: 27e27229611
Ref: library/email message module-email message7229611
Ref: 727229611
Ref: library/email message email message EmailMessage7231913
Ref: 54b7231913
Ref: library/email message email message EmailMessage as_string7232404
Ref: 27e57232404
Ref: library/email message email message EmailMessage __str__7234119
Ref: 27e67234119
Ref: library/email message email message EmailMessage as_bytes7234542
Ref: 27e77234542
Ref: library/email message email message EmailMessage __bytes__7235640
Ref: 27e87235640
Ref: library/email message email message EmailMessage is_multipart7235821
Ref: 27e97235821
Ref: library/email message email message EmailMessage set_unixfrom7236550
Ref: 27ea7236550
Ref: library/email message email message EmailMessage get_unixfrom7236769
Ref: 27ec7236769
Ref: library/email message email message EmailMessage __len__7237867
Ref: 27ee7237867
Ref: library/email message email message EmailMessage __contains__7237962
Ref: 27ef7237962
Ref: library/email message email message EmailMessage __getitem__7238368
Ref: 27f07238368
Ref: library/email message email message EmailMessage __setitem__7238965
Ref: 27f37238965
Ref: library/email message email message EmailMessage __delitem__7240028
Ref: 27f47240028
Ref: library/email message email message EmailMessage keys7240228
Ref: 27ed7240228
Ref: library/email message email message EmailMessage values7240320
Ref: 27f57240320
Ref: library/email message email message EmailMessage items7240414
Ref: 27f67240414
Ref: library/email message email message EmailMessage get7240534
Ref: 27f77240534
Ref: library/email message email message EmailMessage get_all7240904
Ref: 27f17240904
Ref: library/email message email message EmailMessage add_header7241125
Ref: 27f87241125
Ref: library/email message email message EmailMessage replace_header7242931
Ref: 27f97242931
Ref: library/email message email message EmailMessage get_content_type7243246
Ref: 27fa7243246
Ref: library/email message email message EmailMessage get_content_maintype7244120
Ref: 27fc7244120
Ref: library/email message email message EmailMessage get_content_subtype7244393
Ref: 27fd7244393
Ref: library/email message email message EmailMessage get_default_type7244661
Ref: 27fb7244661
Ref: library/email message email message EmailMessage set_default_type7244955
Ref: 27fe7244955
Ref: library/email message email message EmailMessage set_param7245409
Ref: 27ff7245409
Ref: library/email message email message EmailMessage del_param7246924
Ref: 28007246924
Ref: library/email message email message EmailMessage get_filename7247347
Ref: 28017247347
Ref: library/email message email message EmailMessage get_boundary7247846
Ref: 28037247846
Ref: library/email message email message EmailMessage set_boundary7248210
Ref: 28047248210
Ref: library/email message email message EmailMessage get_content_charset7248932
Ref: 28067248932
Ref: library/email message email message EmailMessage get_charsets7249180
Ref: 28077249180
Ref: library/email message email message EmailMessage is_attachment7249832
Ref: 28087249832
Ref: library/email message email message EmailMessage get_content_disposition7250250
Ref: 280a7250250
Ref: library/email message email message EmailMessage walk7250715
Ref: 280b7250715
Ref: library/email message email message EmailMessage get_body7252722
Ref: 280c7252722
Ref: library/email message email message EmailMessage iter_attachments7254725
Ref: 280d7254725
Ref: library/email message email message EmailMessage iter_parts7255611
Ref: 280e7255611
Ref: library/email message email message EmailMessage get_content7255809
Ref: 280f7255809
Ref: library/email message email message EmailMessage set_content7256189
Ref: 28117256189
Ref: library/email message email message EmailMessage make_related7256563
Ref: 28137256563
Ref: library/email message email message EmailMessage make_alternative7256983
Ref: 28147256983
Ref: library/email message email message EmailMessage make_mixed7257437
Ref: 28157257437
Ref: library/email message email message EmailMessage add_related7257907
Ref: 28167257907
Ref: library/email message email message EmailMessage add_alternative7258675
Ref: 28187258675
Ref: library/email message email message EmailMessage add_attachment7259362
Ref: 28197259362
Ref: library/email message email message EmailMessage clear7260332
Ref: 281a7260332
Ref: library/email message email message EmailMessage clear_content7260407
Ref: 281b7260407
Ref: library/email message email message EmailMessage preamble7260631
Ref: 281c7260631
Ref: library/email message email message EmailMessage epilogue7261782
Ref: 281d7261782
Ref: library/email message email message EmailMessage defects7262074
Ref: 281e7262074
Ref: library/email message email message MIMEPart7262275
Ref: 84c7262275
Ref: email message 表示一封电子邮件信息-Footnote-17262655
Ref: email message 表示一封电子邮件信息-Footnote-27262727
Ref: email message 表示一封电子邮件信息-Footnote-37262921
Ref: email message 表示一封电子邮件信息-Footnote-47262970
Ref: email message 表示一封电子邮件信息-Footnote-57263019
Ref: email message 表示一封电子邮件信息-Footnote-67263068
Ref: email message 表示一封电子邮件信息-Footnote-77263117
Ref: email message 表示一封电子邮件信息-Footnote-87263166
Ref: email message 表示一封电子邮件信息-Footnote-97263215
Ref: email message 表示一封电子邮件信息-Footnote-107263264
Ref: email message 表示一封电子邮件信息-Footnote-117263314
Ref: email message 表示一封电子邮件信息-Footnote-127263364
Node: email parser 解析电子邮件信息7263414
Ref: library/email parser doc7263624
Ref: 281f7263624
Ref: library/email parser email-parser-parsing-email-messages7263624
Ref: 28207263624
Ref: library/email parser module-email parser7263624
Ref: 747263624
Ref: email parser 解析电子邮件信息-Footnote-17266018
Node: FeedParser API7266089
Ref: library/email parser feedparser-api7266196
Ref: 28227266196
Ref: library/email parser email parser BytesFeedParser7267491
Ref: b517267491
Ref: library/email parser email parser BytesFeedParser feed7268717
Ref: 28237268717
Ref: library/email parser email parser BytesFeedParser close7269192
Ref: 28247269192
Ref: library/email parser email parser FeedParser7269414
Ref: 28217269414
Node: Parser API7269887
Ref: library/email parser parser-api7270015
Ref: 28257270015
Ref: library/email parser email parser BytesParser7270679
Ref: b527270679
Ref: library/email parser email parser BytesParser parse7271293
Ref: 28267271293
Ref: library/email parser email parser BytesParser parsebytes7272248
Ref: 28277272248
Ref: library/email parser email parser BytesHeaderParser7272798
Ref: a047272798
Ref: library/email parser email parser Parser7273023
Ref: b207273023
Ref: library/email parser email parser Parser parse7273333
Ref: 28287273333
Ref: library/email parser email parser Parser parsestr7273759
Ref: 28297273759
Ref: library/email parser email parser HeaderParser7274232
Ref: a057274232
Ref: library/email parser email message_from_bytes7274627
Ref: b4f7274627
Ref: library/email parser email message_from_binary_file7275066
Ref: b507275066
Ref: library/email parser email message_from_string7275503
Ref: 282a7275503
Ref: library/email parser email message_from_file7275875
Ref: 282b7275875
Ref: Parser API-Footnote-17276568
Ref: Parser API-Footnote-27276617
Node: 附加说明7276666
Ref: library/email parser additional-notes7276771
Ref: 282c7276771
Node: email generator 生成 MIME 文档7278385
Ref: library/email generator doc7278576
Ref: 282d7278576
Ref: library/email generator email-generator-generating-mime-documents7278576
Ref: 282e7278576
Ref: library/email generator module-email generator7278576
Ref: 6e7278576
Ref: library/email generator email generator BytesGenerator7280537
Ref: b557280537
Ref: library/email generator email generator BytesGenerator flatten7282383
Ref: 282f7282383
Ref: library/email generator email generator BytesGenerator clone7284131
Ref: 28327284131
Ref: library/email generator email generator BytesGenerator write7284354
Ref: 28307284354
Ref: library/email generator email generator Generator7285364
Ref: b547285364
Ref: library/email generator email generator Generator flatten7287140
Ref: 28337287140
Ref: library/email generator email generator Generator clone7288823
Ref: 28357288823
Ref: library/email generator email generator Generator write7288996
Ref: 28347288996
Ref: library/email generator email generator DecodedGenerator7289833
Ref: 5477289833
Ref: email generator 生成 MIME 文档-Footnote-17291224
Ref: email generator 生成 MIME 文档-Footnote-27291298
Ref: email generator 生成 MIME 文档-Footnote-37291724
Ref: email generator 生成 MIME 文档-Footnote-47291776
Ref: email generator 生成 MIME 文档-Footnote-57291825
Ref: email generator 生成 MIME 文档-Footnote-67291877
Node: email policy 策略对象7291926
Ref: library/email policy doc7292111
Ref: 28367292111
Ref: library/email policy email-policy-policy-objects7292111
Ref: 28377292111
Ref: library/email policy module-email policy7292111
Ref: 757292111
Ref: library/email policy email policy Policy7297448
Ref: 9fc7297448
Ref: library/email policy email policy Policy max_line_length7298066
Ref: 28387298066
Ref: library/email policy email policy Policy linesep7298315
Ref: 28397298315
Ref: library/email policy email policy Policy cte_type7298530
Ref: 28317298530
Ref: library/email policy email policy Policy raise_on_defect7299559
Ref: 283b7299559
Ref: library/email policy email policy Policy mangle_from_7299801
Ref: 6d97299801
Ref: library/email policy email policy Policy message_factory7300138
Ref: 5487300138
Ref: library/email policy email policy Policy clone7300516
Ref: 9fe7300516
Ref: library/email policy email policy Policy handle_defect7300917
Ref: 283d7300917
Ref: library/email policy email policy Policy register_defect7301396
Ref: 283c7301396
Ref: library/email policy email policy Policy header_max_count7302028
Ref: 283e7302028
Ref: library/email policy email policy Policy header_source_parse7302899
Ref: 283f7302899
Ref: library/email policy email policy Policy header_store_parse7303782
Ref: 28407303782
Ref: library/email policy email policy Policy header_fetch_parse7304413
Ref: 28417304413
Ref: library/email policy email policy Policy fold7305087
Ref: 28427305087
Ref: library/email policy email policy Policy fold_binary7305718
Ref: 283a7305718
Ref: library/email policy email policy EmailPolicy7306051
Ref: a007306051
Ref: library/email policy email policy EmailPolicy utf87306758
Ref: 6db7306758
Ref: library/email policy email policy EmailPolicy refold_source7307145
Ref: 28437307145
Ref: library/email policy email policy EmailPolicy header_factory7307806
Ref: 28447307806
Ref: library/email policy email policy EmailPolicy content_manager7308356
Ref: 84d7308356
Ref: library/email policy email policy EmailPolicy header_max_count7308989
Ref: 28467308989
Ref: library/email policy email policy EmailPolicy header_source_parse7309152
Ref: 28487309152
Ref: library/email policy email policy EmailPolicy header_store_parse7309467
Ref: 28497309467
Ref: library/email policy email policy EmailPolicy header_fetch_parse7309933
Ref: 284a7309933
Ref: library/email policy email policy EmailPolicy fold7310310
Ref: 284b7310310
Ref: library/email policy email policy EmailPolicy fold_binary7311367
Ref: 284c7311367
Ref: library/email policy email policy default7312125
Ref: 27e47312125
Ref: library/email policy email policy SMTP7312320
Ref: 284d7312320
Ref: library/email policy email policy SMTPUTF87312515
Ref: 284e7312515
Ref: library/email policy email policy HTTP7312879
Ref: 284f7312879
Ref: library/email policy email policy strict7313062
Ref: 28507313062
Ref: library/email policy email policy Compat327314383
Ref: 9fd7314383
Ref: library/email policy email policy Compat32 mangle_from_7314800
Ref: 28517314800
Ref: library/email policy email policy Compat32 header_source_parse7314954
Ref: 28527314954
Ref: library/email policy email policy Compat32 header_store_parse7315269
Ref: 28537315269
Ref: library/email policy email policy Compat32 header_fetch_parse7315368
Ref: 28547315368
Ref: library/email policy email policy Compat32 fold7315622
Ref: 28567315622
Ref: library/email policy email policy Compat32 fold_binary7315936
Ref: 28577315936
Ref: library/email policy email policy compat327316485
Ref: 5497316485
Ref: email policy 策略对象-Footnote-17316679
Ref: email policy 策略对象-Footnote-27316750
Ref: email policy 策略对象-Footnote-37316799
Ref: email policy 策略对象-Footnote-47316848
Ref: email policy 策略对象-Footnote-57316897
Ref: email policy 策略对象-Footnote-67316946
Ref: email policy 策略对象-Footnote-77316995
Ref: email policy 策略对象-Footnote-87317044
Ref: email policy 策略对象-Footnote-97317115
Ref: email policy 策略对象-Footnote-107317164
Ref: email policy 策略对象-Footnote-117317214
Ref: email policy 策略对象-Footnote-127317264
Node: email errors 异常和缺陷类7317314
Ref: library/email errors doc7317507
Ref: 28587317507
Ref: library/email errors email-errors-exception-and-defect-classes7317507
Ref: 28597317507
Ref: library/email errors module-email errors7317507
Ref: 6d7317507
Ref: library/email errors email errors MessageError7317762
Ref: 285a7317762
Ref: library/email errors email errors MessageParseError7317966
Ref: 285b7317966
Ref: library/email errors email errors HeaderParseError7318203
Ref: 28057318203
Ref: library/email errors email errors BoundaryError7318746
Ref: 285c7318746
Ref: library/email errors email errors MultipartConversionError7318823
Ref: 285d7318823
Ref: email errors 异常和缺陷类-Footnote-17321954
Ref: email errors 异常和缺陷类-Footnote-27322025
Node: email headerregistry 自定义标头对象7322074
Ref: library/email headerregistry doc7322281
Ref: 28607322281
Ref: library/email headerregistry email-headerregistry-custom-header-objects7322281
Ref: 28617322281
Ref: library/email headerregistry module-email headerregistry7322281
Ref: 707322281
Ref: library/email headerregistry email headerregistry BaseHeader7323801
Ref: 27f27323801
Ref: library/email headerregistry email headerregistry BaseHeader name7324088
Ref: 28647324088
Ref: library/email headerregistry email headerregistry BaseHeader defects7324314
Ref: 28657324314
Ref: library/email headerregistry email headerregistry BaseHeader max_count7324653
Ref: 28477324653
Ref: library/email headerregistry email headerregistry BaseHeader fold7325045
Ref: 28667325045
Ref: library/email headerregistry email headerregistry UnstructuredHeader7327057
Ref: 28637327057
Ref: library/email headerregistry email headerregistry DateHeader7328014
Ref: 28677328014
Ref: library/email headerregistry email headerregistry DateHeader datetime7328331
Ref: 28687328331
Ref: library/email headerregistry email headerregistry AddressHeader7329713
Ref: 28697329713
Ref: library/email headerregistry email headerregistry AddressHeader groups7329961
Ref: 286a7329961
Ref: library/email headerregistry email headerregistry AddressHeader addresses7330227
Ref: 286d7330227
Ref: library/email headerregistry email headerregistry SingleAddressHeader7331235
Ref: 286f7331235
Ref: library/email headerregistry email headerregistry SingleAddressHeader address7331363
Ref: 28707331363
Ref: library/email headerregistry email headerregistry MIMEVersionHeader7331800
Ref: 28717331800
Ref: library/email headerregistry email headerregistry MIMEVersionHeader version7332139
Ref: 28727332139
Ref: library/email headerregistry email headerregistry MIMEVersionHeader major7332251
Ref: 28737332251
Ref: library/email headerregistry email headerregistry MIMEVersionHeader minor7332314
Ref: 28747332314
Ref: library/email headerregistry email headerregistry ParameterizedMIMEHeader7332377
Ref: 28757332377
Ref: library/email headerregistry email headerregistry ParameterizedMIMEHeader params7332712
Ref: 28767332712
Ref: library/email headerregistry email headerregistry ContentTypeHeader7332797
Ref: 28777332797
Ref: library/email headerregistry email headerregistry ContentTypeHeader content_type7332938
Ref: 28787332938
Ref: library/email headerregistry email headerregistry ContentTypeHeader maintype7333037
Ref: 28797333037
Ref: library/email headerregistry email headerregistry ContentTypeHeader subtype7333064
Ref: 287a7333064
Ref: library/email headerregistry email headerregistry ContentDispositionHeader7333090
Ref: 287b7333090
Ref: library/email headerregistry email headerregistry ContentDispositionHeader content_disposition7333244
Ref: 287c7333244
Ref: library/email headerregistry email headerregistry ContentTransferEncoding7333358
Ref: 287d7333358
Ref: library/email headerregistry email headerregistry ContentTransferEncoding cte7333468
Ref: 287e7333468
Ref: library/email headerregistry email headerregistry HeaderRegistry7333638
Ref: 28627333638
Ref: library/email headerregistry email headerregistry HeaderRegistry map_to_type7335306
Ref: 287f7335306
Ref: library/email headerregistry email headerregistry HeaderRegistry __getitem__7335589
Ref: 28807335589
Ref: library/email headerregistry email headerregistry HeaderRegistry __call__7335697
Ref: 28817335697
Ref: library/email headerregistry email headerregistry Address7336217
Ref: 286e7336217
Ref: library/email headerregistry email headerregistry Address display_name7337016
Ref: 28827337016
Ref: library/email headerregistry email headerregistry Address username7337212
Ref: 28837337212
Ref: library/email headerregistry email headerregistry Address domain7337309
Ref: 28847337309
Ref: library/email headerregistry email headerregistry Address addr_spec7337378
Ref: 28857337378
Ref: library/email headerregistry email headerregistry Address __str__7337579
Ref: 28867337579
Ref: library/email headerregistry email headerregistry Group7338002
Ref: 286b7338002
Ref: library/email headerregistry email headerregistry Group display_name7338445
Ref: 286c7338445
Ref: library/email headerregistry email headerregistry Group addresses7338677
Ref: 28877338677
Ref: library/email headerregistry email headerregistry Group __str__7338816
Ref: 28887338816
Ref: email headerregistry 自定义标头对象-Footnote-17339245
Ref: email headerregistry 自定义标头对象-Footnote-27339325
Ref: email headerregistry 自定义标头对象-Footnote-37339393
Ref: email headerregistry 自定义标头对象-Footnote-47339442
Ref: email headerregistry 自定义标头对象-Footnote-57339491
Ref: email headerregistry 自定义标头对象-Footnote-67339540
Ref: email headerregistry 自定义标头对象-Footnote-77339589
Ref: email headerregistry 自定义标头对象-Footnote-87339638
Ref: email headerregistry 自定义标头对象-Footnote-97339687
Ref: email headerregistry 自定义标头对象-Footnote-107339736
Ref: email headerregistry 自定义标头对象-Footnote-117339786
Ref: email headerregistry 自定义标头对象-Footnote-127339836
Ref: email headerregistry 自定义标头对象-Footnote-137339886
Ref: email headerregistry 自定义标头对象-Footnote-147339936
Ref: email headerregistry 自定义标头对象-Footnote-157339986
Ref: email headerregistry 自定义标头对象-Footnote-167340036
Ref: email headerregistry 自定义标头对象-Footnote-177340086
Node: email contentmanager 管理 MIME 内容7340136
Ref: library/email contentmanager doc7340324
Ref: 28897340324
Ref: library/email contentmanager email-contentmanager-managing-mime-content7340324
Ref: 288a7340324
Ref: library/email contentmanager module-email contentmanager7340324
Ref: 6b7340324
Ref: library/email contentmanager email contentmanager ContentManager7340567
Ref: 288b7340567
Ref: library/email contentmanager email contentmanager ContentManager get_content7340797
Ref: 28107340797
Ref: library/email contentmanager email contentmanager ContentManager set_content7341541
Ref: 28127341541
Ref: library/email contentmanager email contentmanager ContentManager add_get_handler7343067
Ref: 288d7343067
Ref: library/email contentmanager email contentmanager ContentManager add_set_handler7343261
Ref: 288f7343261
Ref: email contentmanager 管理 MIME 内容-Footnote-17343621
Ref: email contentmanager 管理 MIME 内容-Footnote-27343701
Node: 内容管理器实例7343769
Ref: library/email contentmanager content-manager-instances7343866
Ref: 28917343866
Ref: library/email contentmanager email contentmanager raw_data_manager7344177
Ref: 28457344177
Ref: library/email contentmanager email contentmanager get_content7344820
Ref: 288e7344820
Ref: library/email contentmanager email contentmanager set_content7345457
Ref: 28907345457
Ref: 内容管理器实例-Footnote-17349804
Node: email 示例7349853
Ref: library/email examples doc7350068
Ref: 28927350068
Ref: library/email examples email-examples7350068
Ref: 84e7350068
Ref: library/email examples id17350068
Ref: 28937350068
Ref: email 示例-Footnote-17364622
Ref: email 示例-Footnote-27364670
Node: email message Message 使用 compat32 API 来表示电子邮件消息7364744
Ref: library/email compat32-message doc7364970
Ref: 28947364970
Ref: library/email compat32-message compat32-message7364970
Ref: 27e37364970
Ref: library/email compat32-message email-message-message-representing-an-email-message-using-the-compat32-api7364970
Ref: 28957364970
Ref: library/email compat32-message email message Message7367222
Ref: 54a7367222
Ref: library/email compat32-message email message Message as_string7367690
Ref: 8487367690
Ref: library/email compat32-message email message Message __str__7369642
Ref: 28967369642
Ref: library/email compat32-message email message Message as_bytes7369808
Ref: 8497369808
Ref: library/email compat32-message email message Message __bytes__7371227
Ref: 84a7371227
Ref: library/email compat32-message email message Message is_multipart7371431
Ref: 28097371431
Ref: library/email compat32-message email message Message set_unixfrom7372071
Ref: 28977372071
Ref: library/email compat32-message email message Message get_unixfrom7372199
Ref: 28987372199
Ref: library/email compat32-message email message Message attach7372335
Ref: 28177372335
Ref: library/email compat32-message email message Message get_payload7372946
Ref: b537372946
Ref: library/email compat32-message email message Message set_payload7375482
Ref: 28997375482
Ref: library/email compat32-message email message Message set_charset7375915
Ref: 289a7375915
Ref: library/email compat32-message email message Message get_charset7377491
Ref: 289b7377491
Ref: library/email compat32-message email message Message __len__7378774
Ref: 289d7378774
Ref: library/email compat32-message email message Message __contains__7378869
Ref: 289e7378869
Ref: library/email compat32-message email message Message __getitem__7379241
Ref: 289f7379241
Ref: library/email compat32-message email message Message __setitem__7379730
Ref: 28a17379730
Ref: library/email compat32-message email message Message __delitem__7380276
Ref: 28a27380276
Ref: library/email compat32-message email message Message keys7380476
Ref: 289c7380476
Ref: library/email compat32-message email message Message values7380568
Ref: 28a37380568
Ref: library/email compat32-message email message Message items7380662
Ref: 28a47380662
Ref: library/email compat32-message email message Message get7380782
Ref: 28a57380782
Ref: library/email compat32-message email message Message get_all7381099
Ref: 28a07381099
Ref: library/email compat32-message email message Message add_header7381320
Ref: 28a67381320
Ref: library/email compat32-message email message Message replace_header7383132
Ref: 28a77383132
Ref: library/email compat32-message email message Message get_content_type7383421
Ref: 28a87383421
Ref: library/email compat32-message email message Message get_content_maintype7384219
Ref: 28aa7384219
Ref: library/email compat32-message email message Message get_content_subtype7384492
Ref: 28ab7384492
Ref: library/email compat32-message email message Message get_default_type7384760
Ref: 28a97384760
Ref: library/email compat32-message email message Message set_default_type7385054
Ref: 28ac7385054
Ref: library/email compat32-message email message Message get_params7385318
Ref: 28ad7385318
Ref: library/email compat32-message email message Message get_param7386185
Ref: 28ae7386185
Ref: library/email compat32-message email message Message set_param7388045
Ref: 84b7388045
Ref: library/email compat32-message email message Message del_param7389205
Ref: 28b07389205
Ref: library/email compat32-message email message Message set_type7389606
Ref: 28b17389606
Ref: library/email compat32-message email message Message get_filename7390426
Ref: 28b27390426
Ref: library/email compat32-message email message Message get_boundary7390925
Ref: 28b37390925
Ref: library/email compat32-message email message Message set_boundary7391289
Ref: 28b47391289
Ref: library/email compat32-message email message Message get_content_charset7392074
Ref: 28b57392074
Ref: library/email compat32-message email message Message get_charsets7392482
Ref: 28b67392482
Ref: library/email compat32-message email message Message get_content_disposition7393165
Ref: 6da7393165
Ref: library/email compat32-message email message Message walk7393557
Ref: 28b77393557
Ref: library/email compat32-message email message Message preamble7395641
Ref: 28b87395641
Ref: library/email compat32-message email message Message epilogue7396792
Ref: 28b97396792
Ref: library/email compat32-message email message Message defects7397122
Ref: 28ba7397122
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-17397359
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-27397408
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-37397457
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-47397506
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-57397555
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-67397604
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-77397653
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-87397702
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-97397751
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-107397800
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-117397850
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-127397900
Node: email mime 从头创建电子邮件和 MIME 对象7397950
Ref: library/email mime doc7398192
Ref: 28bb7398192
Ref: library/email mime email-mime-creating-email-and-mime-objects-from-scratch7398192
Ref: 28bc7398192
Ref: library/email mime module-email mime7398192
Ref: 737398192
Ref: library/email mime email mime base MIMEBase7399388
Ref: 28bd7399388
Ref: library/email mime email mime nonmultipart MIMENonMultipart7400474
Ref: 285e7400474
Ref: library/email mime email mime multipart MIMEMultipart7400913
Ref: 28be7400913
Ref: library/email mime email mime application MIMEApplication7402125
Ref: 28bf7402125
Ref: library/email mime email mime audio MIMEAudio7403405
Ref: 28c07403405
Ref: library/email mime email mime image MIMEImage7404903
Ref: 285f7404903
Ref: library/email mime email mime message MIMEMessage7406423
Ref: 28c17406423
Ref: library/email mime email mime text MIMEText7407074
Ref: 6dc7407074
Ref: email mime 从头创建电子邮件和 MIME 对象-Footnote-17408615
Node: email header 国际化标头7408682
Ref: library/email header doc7408884
Ref: 28c27408884
Ref: library/email header email-header-internationalized-headers7408884
Ref: 28c37408884
Ref: library/email header module-email header7408884
Ref: 6f7408884
Ref: library/email header email header Header7411372
Ref: 28557411372
Ref: library/email header email header Header append7413113
Ref: 28c47413113
Ref: library/email header email header Header encode7414368
Ref: 28c57414368
Ref: library/email header email header Header __str__7415795
Ref: 28c67415795
Ref: library/email header email header Header __eq__7416253
Ref: 28c77416253
Ref: library/email header email header Header __ne__7416376
Ref: 28c87416376
Ref: library/email header email header decode_header7416564
Ref: a017416564
Ref: library/email header email header make_header7417192
Ref: a027417192
Ref: email header 国际化标头-Footnote-17417868
Ref: email header 国际化标头-Footnote-27417939
Ref: email header 国际化标头-Footnote-37417988
Ref: email header 国际化标头-Footnote-47418036
Ref: email header 国际化标头-Footnote-57418085
Ref: email header 国际化标头-Footnote-67418134
Ref: email header 国际化标头-Footnote-77418183
Ref: email header 国际化标头-Footnote-87418232
Ref: email header 国际化标头-Footnote-97418281
Ref: email header 国际化标头-Footnote-107418330
Ref: email header 国际化标头-Footnote-117418380
Ref: email header 国际化标头-Footnote-127418430
Ref: email header 国际化标头-Footnote-137418480
Ref: email header 国际化标头-Footnote-147418530
Ref: email header 国际化标头-Footnote-157418580
Node: email charset 表示字符集7418630
Ref: library/email charset doc7418806
Ref: 28c97418806
Ref: library/email charset email-charset-representing-character-sets7418806
Ref: 28ca7418806
Ref: library/email charset module-email charset7418806
Ref: 6a7418806
Ref: library/email charset email charset Charset7419531
Ref: 6dd7419531
Ref: library/email charset email charset Charset input_charset7420926
Ref: 28cb7420926
Ref: library/email charset email charset Charset header_encoding7421179
Ref: 28cc7421179
Ref: library/email charset email charset Charset body_encoding7421594
Ref: 28cd7421594
Ref: library/email charset email charset Charset output_charset7421857
Ref: 28ce7421857
Ref: library/email charset email charset Charset input_codec7422160
Ref: 28cf7422160
Ref: library/email charset email charset Charset output_codec7422360
Ref: 28d07422360
Ref: library/email charset email charset Charset get_body_encoding7422648
Ref: 28d17422648
Ref: library/email charset email charset Charset get_output_charset7423325
Ref: 28d27423325
Ref: library/email charset email charset Charset header_encode7423523
Ref: 28d37423523
Ref: library/email charset email charset Charset header_encode_lines7423733
Ref: 28d47423733
Ref: library/email charset email charset Charset body_encode7424134
Ref: 28d57424134
Ref: library/email charset email charset Charset __str__7424436
Ref: 28d67424436
Ref: library/email charset email charset Charset __eq__7424618
Ref: 28d77424618
Ref: library/email charset email charset Charset __ne__7424741
Ref: 28d87424741
Ref: library/email charset email charset add_charset7424998
Ref: 28d97424998
Ref: library/email charset email charset add_alias7426288
Ref: 28db7426288
Ref: library/email charset email charset add_codec7426587
Ref: 28da7426587
Ref: email charset 表示字符集-Footnote-17426978
Node: email encoders 编码器7427050
Ref: library/email encoders doc7427222
Ref: 28dc7427222
Ref: library/email encoders email-encoders-encoders7427222
Ref: 28dd7427222
Ref: library/email encoders module-email encoders7427222
Ref: 6c7427222
Ref: library/email encoders email encoders encode_quopri7428809
Ref: 28de7428809
Ref: library/email encoders email encoders encode_base647429146
Ref: 28df7429146
Ref: library/email encoders email encoders encode_7or8bit7429537
Ref: 28e07429537
Ref: library/email encoders email encoders encode_noop7429762
Ref: 28e17429762
Ref: email encoders 编码器-Footnote-17429963
Ref: email encoders 编码器-Footnote-27430036
Node: email utils 其他工具7430170
Ref: library/email utils doc7430338
Ref: 28e27430338
Ref: library/email utils email-utils-miscellaneous-utilities7430338
Ref: 28e37430338
Ref: library/email utils module-email utils7430338
Ref: 767430338
Ref: library/email utils email utils localtime7430574
Ref: a087430574
Ref: library/email utils email utils make_msgid7431234
Ref: 28e47431234
Ref: library/email utils email utils quote7432061
Ref: 28e57432061
Ref: library/email utils email utils unquote7432244
Ref: 28027432244
Ref: library/email utils email utils parseaddr7432518
Ref: 28e67432518
Ref: library/email utils email utils formataddr7432845
Ref: b1d7432845
Ref: library/email utils email utils getaddresses7433506
Ref: 28e77433506
Ref: library/email utils email utils parsedate7434126
Ref: 28e87434126
Ref: library/email utils email utils parsedate_tz7434730
Ref: 28e97434730
Ref: library/email utils email utils parsedate_to_datetime7435279
Ref: a077435279
Ref: library/email utils email utils mktime_tz7435957
Ref: 28ea7435957
Ref: library/email utils email utils formatdate7436214
Ref: 28eb7436214
Ref: library/email utils email utils format_datetime7437187
Ref: a067437187
Ref: library/email utils email utils decode_rfc22317437863
Ref: 28ec7437863
Ref: library/email utils email utils encode_rfc22317437955
Ref: 28ed7437955
Ref: library/email utils email utils collapse_rfc2231_value7438388
Ref: 28af7438388
Ref: library/email utils email utils decode_params7439240
Ref: 28ee7439240
Ref: email utils 其他工具-Footnote-17439490
Ref: email utils 其他工具-Footnote-27439560
Ref: email utils 其他工具-Footnote-37439609
Ref: email utils 其他工具-Footnote-47439658
Ref: email utils 其他工具-Footnote-57439707
Ref: email utils 其他工具-Footnote-67439756
Ref: email utils 其他工具-Footnote-77439961
Ref: email utils 其他工具-Footnote-87440010
Ref: email utils 其他工具-Footnote-97440059
Ref: email utils 其他工具-Footnote-107440108
Ref: email utils 其他工具-Footnote-117440158
Ref: email utils 其他工具-Footnote-127440208
Node: email iterators 迭代器7440258
Ref: library/email iterators doc7440393
Ref: 28ef7440393
Ref: library/email iterators email-iterators-iterators7440393
Ref: 28f07440393
Ref: library/email iterators module-email iterators7440393
Ref: 717440393
Ref: library/email iterators email iterators body_line_iterator7440764
Ref: 28f17440764
Ref: library/email iterators email iterators typed_subpart_iterator7441287
Ref: 28f27441287
Ref: library/email iterators email iterators _structure7441992
Ref: 28f37441992
Ref: email iterators 迭代器-Footnote-17443504
Node: json --- JSON 编码和解码器7443578
Ref: library/json doc7443758
Ref: 28f47443758
Ref: library/json json-json-encoder-and-decoder7443758
Ref: 28f57443758
Ref: library/json module-json7443758
Ref: a57443758
Ref: json --- JSON 编码和解码器-Footnote-17447818
Ref: json --- JSON 编码和解码器-Footnote-27447890
Ref: json --- JSON 编码和解码器-Footnote-37447914
Ref: json --- JSON 编码和解码器-Footnote-47447963
Ref: json --- JSON 编码和解码器-Footnote-57448012
Ref: json --- JSON 编码和解码器-Footnote-67448091
Ref: json --- JSON 编码和解码器-Footnote-77448140
Ref: json --- JSON 编码和解码器-Footnote-87448413
Node: 基本使用7448438
Ref: library/json basic-usage7448549
Ref: 28f77448549
Ref: library/json json dump7448590
Ref: 60d7448590
Ref: library/json json dumps7452220
Ref: 60e7452220
Ref: library/json json load7452999
Ref: 5687452999
Ref: library/json json loads7455526
Ref: 5697455526
Ref: 基本使用-Footnote-17456407
Node: 编码器和解码器7456438
Ref: library/json encoders-and-decoders7456568
Ref: 28fa7456568
Ref: library/json json JSONDecoder7456624
Ref: 6107456624
Ref: library/json json-to-py-table7456865
Ref: 28f97456865
Ref: library/json json JSONDecoder decode7459693
Ref: 28fb7459693
Ref: library/json json JSONDecoder raw_decode7459925
Ref: 28fc7459925
Ref: library/json json JSONEncoder7460307
Ref: 60f7460307
Ref: library/json py-to-json-table7460591
Ref: 28f87460591
Ref: library/json json JSONEncoder default7464843
Ref: 28fd7464843
Ref: library/json json JSONEncoder encode7465486
Ref: 28fe7465486
Ref: library/json json JSONEncoder iterencode7465709
Ref: 28ff7465709
Node: 异常<13>7465947
Ref: library/json exceptions7466095
Ref: 29007466095
Ref: library/json json JSONDecodeError7466126
Ref: 70f7466126
Ref: library/json json JSONDecodeError msg7466246
Ref: 29017466246
Ref: library/json json JSONDecodeError doc7466310
Ref: 29027466310
Ref: library/json json JSONDecodeError pos7466374
Ref: 29037466374
Ref: library/json json JSONDecodeError lineno7466454
Ref: 29047466454
Ref: library/json json JSONDecodeError colno7466523
Ref: 29057466523
Node: 标准符合性和互操作性7466617
Ref: library/json standard-compliance-and-interoperability7466762
Ref: 29067466762
Ref: 标准符合性和互操作性-Footnote-17467678
Ref: 标准符合性和互操作性-Footnote-27467727
Node: 字符编码7467806
Ref: library/json character-encodings7467917
Ref: 29077467917
Node: Infinite 和 NaN 数值7469069
Ref: library/json infinite-and-nan-number-values7469213
Ref: 29087469213
Node: 对象中的重复名称7469943
Ref: library/json repeated-names-within-an-object7470105
Ref: 29097470105
Node: 顶级非对象，非数组值7470575
Ref: library/json top-level-non-object-non-array-values7470726
Ref: 290a7470726
Ref: 顶级非对象，非数组值-Footnote-17471279
Ref: 顶级非对象，非数组值-Footnote-27471328
Node: 实现限制7471377
Ref: library/json implementation-limitations7471495
Ref: 290b7471495
Node: 命令行界面<4>7472302
Ref: library/json command-line-interface7472428
Ref: 290c7472428
Ref: library/json json-commandline7472428
Ref: 28f67472428
Ref: library/json module-json tool7472428
Ref: a67472428
Ref: 命令行界面<4>-Footnote-17473288
Node: 命令行选项<4>7473356
Ref: library/json command-line-options7473429
Ref: 290e7473429
Ref: library/json cmdoption-json-tool-arg-infile7473477
Ref: 290f7473477
Ref: library/json cmdoption-json-tool-arg-outfile7473961
Ref: 29107473961
Ref: library/json cmdoption-json-tool-sort-keys7474104
Ref: 290d7474104
Ref: library/json cmdoption-json-tool-json-lines7474214
Ref: 29117474214
Ref: library/json cmdoption-json-tool-h7474328
Ref: 29127474328
Node: mailcap --- Mailcap 文件处理7474399
Ref: library/mailcap doc7474578
Ref: 29137474578
Ref: library/mailcap mailcap-mailcap-file-handling7474578
Ref: 29147474578
Ref: library/mailcap module-mailcap7474578
Ref: b07474578
Ref: library/mailcap mailcap findmatch7475509
Ref: 29157475509
Ref: library/mailcap mailcap getcaps7477358
Ref: 29167477358
Ref: mailcap --- Mailcap 文件处理-Footnote-17478109
Ref: mailcap --- Mailcap 文件处理-Footnote-27478175
Ref: mailcap --- Mailcap 文件处理-Footnote-37478224
Node: mailbox --- 操作多种格式的邮箱7478273
Ref: library/mailbox doc7478464
Ref: 29177478464
Ref: library/mailbox mailbox-manipulate-mailboxes-in-various-formats7478464
Ref: 29187478464
Ref: library/mailbox module-mailbox7478464
Ref: af7478464
Ref: mailbox --- 操作多种格式的邮箱-Footnote-17479282
Node: Mailbox 对象7479348
Ref: library/mailbox id17479461
Ref: 29197479461
Ref: library/mailbox mailbox-objects7479461
Ref: 291a7479461
Ref: library/mailbox mailbox Mailbox7479516
Ref: beb7479516
Ref: library/mailbox mailbox Mailbox add7481990
Ref: bea7481990
Ref: library/mailbox mailbox Mailbox remove7482719
Ref: 291b7482719
Ref: library/mailbox mailbox Mailbox __delitem__7482749
Ref: 29207482749
Ref: library/mailbox mailbox Mailbox discard7482784
Ref: 291c7482784
Ref: library/mailbox mailbox Mailbox __setitem__7483287
Ref: 29217483287
Ref: library/mailbox mailbox Mailbox iterkeys7484098
Ref: 29227484098
Ref: library/mailbox mailbox Mailbox keys7484127
Ref: 29237484127
Ref: library/mailbox mailbox Mailbox itervalues7484336
Ref: 29247484336
Ref: library/mailbox mailbox Mailbox __iter__7484367
Ref: 29257484367
Ref: library/mailbox mailbox Mailbox values7484396
Ref: 29267484396
Ref: library/mailbox mailbox Mailbox iteritems7485022
Ref: 29277485022
Ref: library/mailbox mailbox Mailbox items7485052
Ref: 29287485052
Ref: library/mailbox mailbox Mailbox get7485632
Ref: 29297485632
Ref: library/mailbox mailbox Mailbox __getitem__7485673
Ref: 292a7485673
Ref: library/mailbox mailbox Mailbox get_message7486192
Ref: 292b7486192
Ref: library/mailbox mailbox Mailbox get_bytes7486454
Ref: bed7486454
Ref: library/mailbox mailbox Mailbox get_string7486674
Ref: bee7486674
Ref: library/mailbox mailbox Mailbox get_file7486992
Ref: bec7486992
Ref: library/mailbox mailbox Mailbox __contains__7487823
Ref: 292c7487823
Ref: library/mailbox mailbox Mailbox __len__7487953
Ref: 292d7487953
Ref: library/mailbox mailbox Mailbox clear7488027
Ref: 292e7488027
Ref: library/mailbox mailbox Mailbox pop7488099
Ref: 292f7488099
Ref: library/mailbox mailbox Mailbox popitem7488480
Ref: 29307488480
Ref: library/mailbox mailbox Mailbox update7488937
Ref: 29317488937
Ref: library/mailbox mailbox Mailbox flush7489632
Ref: 29327489632
Ref: library/mailbox mailbox Mailbox lock7489919
Ref: 291d7489919
Ref: library/mailbox mailbox Mailbox unlock7490275
Ref: 291e7490275
Ref: library/mailbox mailbox Mailbox close7490360
Ref: 29347490360
Node: Maildir7490627
Ref: library/mailbox mailbox-maildir7490698
Ref: 29357490698
Ref: library/mailbox maildir7490698
Ref: 29367490698
Ref: library/mailbox mailbox Maildir7490741
Ref: cb07490741
Ref: library/mailbox mailbox Maildir list_folders7493362
Ref: 29387493362
Ref: library/mailbox mailbox Maildir get_folder7493447
Ref: 29397493447
Ref: library/mailbox mailbox Maildir add_folder7493673
Ref: 293b7493673
Ref: library/mailbox mailbox Maildir remove_folder7493821
Ref: 293c7493821
Ref: library/mailbox mailbox Maildir clean7494044
Ref: 293e7494044
Ref: library/mailbox mailbox Maildir add7494339
Ref: 293f7494339
Ref: library/mailbox mailbox Maildir __setitem__7494370
Ref: 29407494370
Ref: library/mailbox mailbox Maildir update7494414
Ref: 29417494414
Ref: library/mailbox mailbox Maildir flush7494744
Ref: 29427494744
Ref: library/mailbox mailbox Maildir lock7494893
Ref: 29437494893
Ref: library/mailbox mailbox Maildir unlock7494918
Ref: 29447494918
Ref: library/mailbox mailbox Maildir close7495064
Ref: 29457495064
Ref: library/mailbox mailbox Maildir get_file7495254
Ref: 29467495254
Ref: Maildir-Footnote-17495742
Ref: Maildir-Footnote-27495790
Node: mbox7495834
Ref: library/mailbox mailbox-mbox7495916
Ref: 29477495916
Ref: library/mailbox mbox7495916
Ref: 29487495916
Ref: library/mailbox mailbox mbox7495953
Ref: 291f7495953
Ref: library/mailbox mailbox mbox get_file7497195
Ref: 29497497195
Ref: library/mailbox mailbox mbox lock7497396
Ref: 294a7497396
Ref: library/mailbox mailbox mbox unlock7497421
Ref: 294b7497421
Ref: mbox-Footnote-17497971
Ref: mbox-Footnote-27498031
Ref: mbox-Footnote-37498083
Node: MH7498161
Ref: library/mailbox mailbox-mh7498241
Ref: 294c7498241
Ref: library/mailbox mh7498241
Ref: 294d7498241
Ref: library/mailbox mailbox MH7498274
Ref: 294e7498274
Ref: library/mailbox mailbox MH list_folders7499693
Ref: 29507499693
Ref: library/mailbox mailbox MH get_folder7499778
Ref: 29517499778
Ref: library/mailbox mailbox MH add_folder7499990
Ref: 29527499990
Ref: library/mailbox mailbox MH remove_folder7500135
Ref: 29537500135
Ref: library/mailbox mailbox MH get_sequences7500358
Ref: 29547500358
Ref: library/mailbox mailbox MH set_sequences7500516
Ref: 29557500516
Ref: library/mailbox mailbox MH pack7500763
Ref: 29567500763
Ref: library/mailbox mailbox MH remove7501129
Ref: 29577501129
Ref: library/mailbox mailbox MH __delitem__7501159
Ref: 29587501159
Ref: library/mailbox mailbox MH discard7501194
Ref: 29597501194
Ref: library/mailbox mailbox MH lock7501377
Ref: 295a7501377
Ref: library/mailbox mailbox MH unlock7501402
Ref: 295b7501402
Ref: library/mailbox mailbox MH get_file7501751
Ref: 295c7501751
Ref: library/mailbox mailbox MH flush7501912
Ref: 295d7501912
Ref: library/mailbox mailbox MH close7502056
Ref: 295e7502056
Ref: MH-Footnote-17502528
Ref: MH-Footnote-27502563
Node: Babyl7502608
Ref: library/mailbox babyl7502688
Ref: 295f7502688
Ref: library/mailbox mailbox-babyl7502688
Ref: 29607502688
Ref: library/mailbox mailbox Babyl7502727
Ref: 29617502727
Ref: library/mailbox mailbox Babyl get_labels7504148
Ref: 29637504148
Ref: library/mailbox mailbox Babyl get_file7504580
Ref: 29647504580
Ref: library/mailbox mailbox Babyl lock7505014
Ref: 29657505014
Ref: library/mailbox mailbox Babyl unlock7505039
Ref: 29667505039
Ref: Babyl-Footnote-17505424
Ref: Babyl-Footnote-27505468
Node: MMDF7505546
Ref: library/mailbox mailbox-mmdf7505615
Ref: 29677505615
Ref: library/mailbox mmdf7505615
Ref: 29687505615
Ref: library/mailbox mailbox MMDF7505652
Ref: 29697505652
Ref: library/mailbox mailbox MMDF get_file7506806
Ref: 296b7506806
Ref: library/mailbox mailbox MMDF lock7507007
Ref: 296c7507007
Ref: library/mailbox mailbox MMDF unlock7507032
Ref: 296d7507032
Ref: MMDF-Footnote-17507451
Ref: MMDF-Footnote-27507511
Node: Message 对象7507554
Ref: library/mailbox mailbox-message-objects7507686
Ref: 296e7507686
Ref: library/mailbox message-objects7507686
Ref: 296f7507686
Ref: library/mailbox mailbox Message7507741
Ref: bef7507741
Ref: Message 对象-Footnote-17509599
Node: MaildirMessage7509648
Ref: library/mailbox mailbox-maildirmessage7509733
Ref: 29707509733
Ref: library/mailbox maildirmessage7509733
Ref: 29717509733
Ref: library/mailbox mailbox MaildirMessage7509790
Ref: 29377509790
Ref: library/mailbox mailbox MaildirMessage get_subdir7511541
Ref: 29727511541
Ref: library/mailbox mailbox MaildirMessage set_subdir7512002
Ref: 29737512002
Ref: library/mailbox mailbox MaildirMessage get_flags7512152
Ref: 29747512152
Ref: library/mailbox mailbox MaildirMessage set_flags7512547
Ref: 29757512547
Ref: library/mailbox mailbox MaildirMessage add_flag7512661
Ref: 29767512661
Ref: library/mailbox mailbox MaildirMessage remove_flag7512972
Ref: 29777512972
Ref: library/mailbox mailbox MaildirMessage get_date7513291
Ref: 29787513291
Ref: library/mailbox mailbox MaildirMessage set_date7513408
Ref: 29797513408
Ref: library/mailbox mailbox MaildirMessage get_info7513539
Ref: 297a7513539
Ref: library/mailbox mailbox MaildirMessage set_info7513728
Ref: 297b7513728
Node: mboxMessage7516487
Ref: library/mailbox mailbox-mboxmessage7516590
Ref: 297c7516590
Ref: library/mailbox mboxmessage7516590
Ref: 297d7516590
Ref: library/mailbox mailbox mboxMessage7516641
Ref: 27eb7516641
Ref: library/mailbox mailbox mboxMessage get_from7518216
Ref: 297e7518216
Ref: library/mailbox mailbox mboxMessage set_from7518407
Ref: 297f7518407
Ref: library/mailbox mailbox mboxMessage get_flags7518894
Ref: 29807518894
Ref: library/mailbox mailbox mboxMessage set_flags7519168
Ref: 29817519168
Ref: library/mailbox mailbox mboxMessage add_flag7519441
Ref: 29827519441
Ref: library/mailbox mailbox mboxMessage remove_flag7519658
Ref: 29837519658
Node: MHMessage7522585
Ref: library/mailbox mailbox-mhmessage7522686
Ref: 29847522686
Ref: library/mailbox mhmessage7522686
Ref: 29857522686
Ref: library/mailbox mailbox MHMessage7522735
Ref: 294f7522735
Ref: library/mailbox mailbox MHMessage get_sequences7523606
Ref: 29867523606
Ref: library/mailbox mailbox MHMessage set_sequences7523710
Ref: 29877523710
Ref: library/mailbox mailbox MHMessage add_sequence7523808
Ref: 29887523808
Ref: library/mailbox mailbox MHMessage remove_sequence7523922
Ref: 29897523922
Node: BabylMessage7525726
Ref: library/mailbox babylmessage7525827
Ref: 298a7525827
Ref: library/mailbox mailbox-babylmessage7525827
Ref: 298b7525827
Ref: library/mailbox mailbox BabylMessage7525882
Ref: 29627525882
Ref: library/mailbox mailbox BabylMessage get_labels7527143
Ref: 298c7527143
Ref: library/mailbox mailbox BabylMessage set_labels7527220
Ref: 298d7527220
Ref: library/mailbox mailbox BabylMessage add_label7527319
Ref: 298e7527319
Ref: library/mailbox mailbox BabylMessage remove_label7527418
Ref: 298f7527418
Ref: library/mailbox mailbox BabylMessage get_visible7527517
Ref: 29907527517
Ref: library/mailbox mailbox BabylMessage set_visible7527672
Ref: 29917527672
Ref: library/mailbox mailbox BabylMessage update_visible7527992
Ref: 29927527992
Node: MMDFMessage7530282
Ref: library/mailbox mailbox-mmdfmessage7530365
Ref: 29937530365
Ref: library/mailbox mmdfmessage7530365
Ref: 29947530365
Ref: library/mailbox mailbox MMDFMessage7530418
Ref: 296a7530418
Ref: library/mailbox mailbox MMDFMessage get_from7531911
Ref: 29957531911
Ref: library/mailbox mailbox MMDFMessage set_from7532102
Ref: 29967532102
Ref: library/mailbox mailbox MMDFMessage get_flags7532589
Ref: 29977532589
Ref: library/mailbox mailbox MMDFMessage set_flags7532863
Ref: 29987532863
Ref: library/mailbox mailbox MMDFMessage add_flag7533136
Ref: 29997533136
Ref: library/mailbox mailbox MMDFMessage remove_flag7533353
Ref: 299a7533353
Node: 异常<14>7536283
Ref: library/mailbox exceptions7536411
Ref: 299b7536411
Ref: library/mailbox mailbox Error7536499
Ref: 299c7536499
Ref: library/mailbox mailbox NoSuchMailboxError7536575
Ref: 293a7536575
Ref: library/mailbox mailbox NotEmptyError7536860
Ref: 293d7536860
Ref: library/mailbox mailbox ExternalClashError7537013
Ref: 29337537013
Ref: library/mailbox mailbox FormatError7537279
Ref: 299d7537279
Node: 例子<18>7537477
Ref: library/mailbox examples7537582
Ref: 299e7537582
Ref: library/mailbox mailbox-examples7537582
Ref: 299f7537582
Node: mimetypes --- 映射文件夹到 MIME 类型7539773
Ref: library/mimetypes doc7539983
Ref: 29a07539983
Ref: library/mimetypes mimetypes-map-filenames-to-mime-types7539983
Ref: 29a17539983
Ref: library/mimetypes module-mimetypes7539983
Ref: b37539983
Ref: library/mimetypes mimetypes guess_type7540784
Ref: f797540784
Ref: library/mimetypes mimetypes guess_all_extensions7542070
Ref: 29a37542070
Ref: library/mimetypes mimetypes guess_extension7542555
Ref: 29a47542555
Ref: library/mimetypes mimetypes init7543170
Ref: 29a27543170
Ref: library/mimetypes mimetypes read_mime_types7544059
Ref: f187544059
Ref: library/mimetypes mimetypes add_type7544451
Ref: 29a67544451
Ref: library/mimetypes mimetypes inited7544855
Ref: 29a77544855
Ref: library/mimetypes mimetypes knownfiles7545006
Ref: 29a57545006
Ref: library/mimetypes mimetypes suffix_map7545195
Ref: 29a87545195
Ref: library/mimetypes mimetypes encodings_map7545503
Ref: 29a97545503
Ref: library/mimetypes mimetypes types_map7545595
Ref: 29aa7545595
Ref: library/mimetypes mimetypes common_types7545683
Ref: 29ab7545683
Ref: mimetypes --- 映射文件夹到 MIME 类型-Footnote-17546201
Ref: mimetypes --- 映射文件夹到 MIME 类型-Footnote-27546269
Node: MimeTypes 对象7546340
Ref: library/mimetypes id17546437
Ref: 29ac7546437
Ref: library/mimetypes mimetypes-objects7546437
Ref: 29ad7546437
Ref: library/mimetypes mimetypes MimeTypes7546659
Ref: 29ae7546659
Ref: library/mimetypes mimetypes MimeTypes suffix_map7547310
Ref: 29b17547310
Ref: library/mimetypes mimetypes MimeTypes encodings_map7547717
Ref: 29b27547717
Ref: library/mimetypes mimetypes MimeTypes types_map7547905
Ref: 29b37547905
Ref: library/mimetypes mimetypes MimeTypes types_map_inv7548195
Ref: 29b47548195
Ref: library/mimetypes mimetypes MimeTypes guess_extension7548495
Ref: 29b57548495
Ref: library/mimetypes mimetypes MimeTypes guess_type7548667
Ref: 10347548667
Ref: library/mimetypes mimetypes MimeTypes guess_all_extensions7548827
Ref: 29b67548827
Ref: library/mimetypes mimetypes MimeTypes read7549009
Ref: 29af7549009
Ref: library/mimetypes mimetypes MimeTypes readfp7549326
Ref: 29b07549326
Ref: library/mimetypes mimetypes MimeTypes read_windows_registry7549640
Ref: 29b77549640
Node: base64 --- Base16 Base32 Base64 Base85 数据编码7549966
Ref: library/base64 doc7550185
Ref: 29b87550185
Ref: library/base64 base64-base16-base32-base64-base85-data-encodings7550185
Ref: 29b97550185
Ref: library/base64 module-base647550185
Ref: e7550185
Ref: library/base64 base64 b64encode7551924
Ref: 29ba7551924
Ref: library/base64 base64 b64decode7552388
Ref: f5a7552388
Ref: library/base64 base64 standard_b64encode7553133
Ref: 29bb7553133
Ref: library/base64 base64 standard_b64decode7553303
Ref: 29bc7553303
Ref: library/base64 base64 urlsafe_b64encode7553492
Ref: 29bd7553492
Ref: library/base64 base64 urlsafe_b64decode7553802
Ref: 29be7553802
Ref: library/base64 base64 b32encode7554096
Ref: 29bf7554096
Ref: library/base64 base64 b32decode7554233
Ref: 9657554233
Ref: library/base64 base64 b16encode7555114
Ref: 29c07555114
Ref: library/base64 base64 b16decode7555251
Ref: 29c17555251
Ref: library/base64 base64 a85encode7555706
Ref: 82d7555706
Ref: library/base64 base64 a85decode7556525
Ref: 82e7556525
Ref: library/base64 base64 b85encode7557293
Ref: 82f7557293
Ref: library/base64 base64 b85decode7557640
Ref: 8307557640
Ref: library/base64 base64 decode7557900
Ref: 29c27557900
Ref: library/base64 base64 decodebytes7558187
Ref: 18857558187
Ref: library/base64 base64 decodestring7558406
Ref: 29c37558406
Ref: library/base64 base64 encode7558529
Ref: 29c47558529
Ref: library/base64 base64 encodebytes7559017
Ref: 18847559017
Ref: library/base64 base64 encodestring7559403
Ref: 29c57559403
Ref: base64 --- Base16 Base32 Base64 Base85 数据编码-Footnote-17560163
Ref: base64 --- Base16 Base32 Base64 Base85 数据编码-Footnote-27560228
Ref: base64 --- Base16 Base32 Base64 Base85 数据编码-Footnote-37560277
Ref: base64 --- Base16 Base32 Base64 Base85 数据编码-Footnote-47560326
Ref: base64 --- Base16 Base32 Base64 Base85 数据编码-Footnote-57560375
Ref: base64 --- Base16 Base32 Base64 Base85 数据编码-Footnote-67560424
Ref: base64 --- Base16 Base32 Base64 Base85 数据编码-Footnote-77560473
Ref: base64 --- Base16 Base32 Base64 Base85 数据编码-Footnote-87560522
Ref: base64 --- Base16 Base32 Base64 Base85 数据编码-Footnote-97560571
Ref: base64 --- Base16 Base32 Base64 Base85 数据编码-Footnote-107560620
Node: binhex --- 对binhex4文件进行编码和解码7560670
Ref: library/binhex doc7560886
Ref: 29c67560886
Ref: library/binhex binhex-encode-and-decode-binhex4-files7560886
Ref: 29c77560886
Ref: library/binhex module-binhex7560886
Ref: 117560886
Ref: library/binhex binhex binhex7561281
Ref: 29c87561281
Ref: library/binhex binhex hexbin7561534
Ref: 29c97561534
Ref: library/binhex binhex Error7561893
Ref: 29ca7561893
Ref: binhex --- 对binhex4文件进行编码和解码-Footnote-17562294
Node: 注释<3>7562359
Ref: library/binhex binhex-notes7562453
Ref: 29cb7562453
Ref: library/binhex notes7562453
Ref: 29cc7562453
Node: binascii --- 二进制和 ASCII 码互转7562735
Ref: library/binascii doc7562962
Ref: 29cd7562962
Ref: library/binascii binascii-convert-between-binary-and-ascii7562962
Ref: 29ce7562962
Ref: library/binascii module-binascii7562962
Ref: 107562962
Ref: library/binascii binascii a2b_uu7563925
Ref: 29cf7563925
Ref: library/binascii binascii b2a_uu7564163
Ref: 3767564163
Ref: library/binascii binascii a2b_base647564496
Ref: 29d07564496
Ref: library/binascii binascii b2a_base647564658
Ref: 52b7564658
Ref: library/binascii binascii a2b_qp7564995
Ref: 29d17564995
Ref: library/binascii binascii b2a_qp7565258
Ref: 29d27565258
Ref: library/binascii binascii a2b_hqx7565966
Ref: 29d37565966
Ref: library/binascii binascii rledecode_hqx7566227
Ref: 29d47566227
Ref: library/binascii binascii rlecode_hqx7566707
Ref: 29d67566707
Ref: library/binascii binascii b2a_hqx7566820
Ref: 29d77566820
Ref: library/binascii binascii crc_hqx7567045
Ref: 29d87567045
Ref: library/binascii binascii crc327567317
Ref: 29d97567317
Ref: library/binascii binascii b2a_hex7568035
Ref: 18877568035
Ref: library/binascii binascii hexlify7568097
Ref: fcd7568097
Ref: library/binascii binascii a2b_hex7569189
Ref: 18887569189
Ref: library/binascii binascii unhexlify7569227
Ref: 104e7569227
Ref: library/binascii binascii Error7569684
Ref: 9667569684
Ref: library/binascii binascii Incomplete7569764
Ref: 29d57569764
Ref: binascii --- 二进制和 ASCII 码互转-Footnote-17570364
Node: quopri --- 编码与解码经过 MIME 转码的可打印数据7570413
Ref: library/quopri doc7570639
Ref: 29da7570639
Ref: library/quopri module-quopri7570639
Ref: dc7570639
Ref: library/quopri quopri-encode-and-decode-mime-quoted-printable-data7570639
Ref: 29db7570639
Ref: library/quopri quopri decode7571357
Ref: 188a7571357
Ref: library/quopri quopri encode7571879
Ref: 18897571879
Ref: library/quopri quopri decodestring7572521
Ref: 29dc7572521
Ref: library/quopri quopri encodestring7572712
Ref: 29dd7572712
Ref: quopri --- 编码与解码经过 MIME 转码的可打印数据-Footnote-17573147
Ref: quopri --- 编码与解码经过 MIME 转码的可打印数据-Footnote-27573212
Ref: quopri --- 编码与解码经过 MIME 转码的可打印数据-Footnote-37573261
Ref: quopri --- 编码与解码经过 MIME 转码的可打印数据-Footnote-47573310
Ref: quopri --- 编码与解码经过 MIME 转码的可打印数据-Footnote-57573359
Node: uu --- 对 uuencode 文件进行编码与解码7573408
Ref: library/uu doc7573584
Ref: 29de7573584
Ref: library/uu module-uu7573584
Ref: 1247573584
Ref: library/uu uu-encode-and-decode-uuencode-files7573584
Ref: 29df7573584
Ref: library/uu uu encode7574443
Ref: 4177574443
Ref: library/uu uu decode7574951
Ref: 188b7574951
Ref: library/uu uu Error7575642
Ref: 29e07575642
Ref: uu --- 对 uuencode 文件进行编码与解码-Footnote-17576023
Node: 结构化标记处理工具7576084
Ref: library/markup doc7576227
Ref: 29e17576227
Ref: library/markup markup7576227
Ref: 29e27576227
Ref: library/markup structured-markup-processing-tools7576227
Ref: 29e37576227
Node: html --- 超文本标记语言支持7577607
Ref: library/html doc7577766
Ref: 29e47577766
Ref: library/html html-hypertext-markup-language-support7577766
Ref: 29e57577766
Ref: library/html module-html7577766
Ref: 907577766
Ref: library/html html escape7577999
Ref: 93c7577999
Ref: library/html html unescape7578451
Ref: 8637578451
Ref: html --- 超文本标记语言支持-Footnote-17579070
Node: html parser --- 简单的 HTML 和 XHTML 解析器7579142
Ref: library/html parser doc7579354
Ref: 29e67579354
Ref: library/html parser html-parser-simple-html-and-xhtml-parser7579354
Ref: 29e77579354
Ref: library/html parser module-html parser7579354
Ref: 927579354
Ref: library/html parser html parser HTMLParser7579714
Ref: 7c87579714
Ref: html parser --- 简单的 HTML 和 XHTML 解析器-Footnote-17580751
Node: HTML 解析器的示例程序7580821
Ref: library/html parser example-html-parser-application7580963
Ref: 29e87580963
Node: HTMLParser 方法7582157
Ref: library/html parser htmlparser-methods7582318
Ref: 29e97582318
Ref: library/html parser html parser HTMLParser feed7582428
Ref: 29ea7582428
Ref: library/html parser html parser HTMLParser close7582715
Ref: 29eb7582715
Ref: library/html parser html parser HTMLParser reset7583050
Ref: 29ec7583050
Ref: library/html parser html parser HTMLParser getpos7583174
Ref: 29ed7583174
Ref: library/html parser html parser HTMLParser get_starttag_text7583248
Ref: 29ee7583248
Ref: library/html parser html parser HTMLParser handle_starttag7583756
Ref: 29f07583756
Ref: library/html parser html parser HTMLParser handle_endtag7584449
Ref: 29f17584449
Ref: library/html parser html parser HTMLParser handle_startendtag7584620
Ref: 29ef7584620
Ref: library/html parser html parser HTMLParser handle_data7584990
Ref: 29f27584990
Ref: library/html parser html parser HTMLParser handle_entityref7585189
Ref: 29f37585189
Ref: library/html parser html parser HTMLParser handle_charref7585491
Ref: 29f47585491
Ref: library/html parser html parser HTMLParser handle_comment7585918
Ref: 29f57585918
Ref: library/html parser html parser HTMLParser handle_decl7586419
Ref: 29f67586419
Ref: library/html parser html parser HTMLParser handle_pi7586658
Ref: 29f77586658
Ref: library/html parser html parser HTMLParser unknown_decl7587200
Ref: 29f87587200
Node: 例子<19>7587473
Ref: library/html parser examples7587596
Ref: 29f97587596
Ref: library/html parser htmlparser-examples7587596
Ref: 29fa7587596
Node: html entities --- HTML 一般实体的定义7590961
Ref: library/html entities doc7591152
Ref: 29fb7591152
Ref: library/html entities html-entities-definitions-of-html-general-entities7591152
Ref: 29fc7591152
Ref: library/html entities module-html entities7591152
Ref: 917591152
Ref: library/html entities html entities html57591512
Ref: a1d7591512
Ref: library/html entities html entities entitydefs7591946
Ref: 29ff7591946
Ref: library/html entities html entities name2codepoint7592069
Ref: 29fd7592069
Ref: library/html entities html entities codepoint2name7592178
Ref: 29fe7592178
Ref: html entities --- HTML 一般实体的定义-Footnote-17592336
Ref: html entities --- HTML 一般实体的定义-Footnote-27592408
Node: XML处理模块7592500
Ref: library/xml doc7592686
Ref: 2a007592686
Ref: library/xml module-xml7592686
Ref: 1347592686
Ref: library/xml xml7592686
Ref: 2a017592686
Ref: library/xml xml-processing-modules7592686
Ref: 2a027592686
Ref: XML处理模块-Footnote-17593927
Node: XML 漏洞7593987
Ref: library/xml id17594072
Ref: 2a057594072
Ref: library/xml xml-vulnerabilities7594072
Ref: 2a037594072
Ref: XML 漏洞-Footnote-17598904
Ref: XML 漏洞-Footnote-27598967
Ref: XML 漏洞-Footnote-37599020
Ref: XML 漏洞-Footnote-47599073
Ref: XML 漏洞-Footnote-57599136
Ref: XML 漏洞-Footnote-67599183
Node: defusedxml 包7599228
Ref: library/xml defusedxml-package7599313
Ref: 2a047599313
Ref: library/xml the-defusedxml-package7599313
Ref: 2a067599313
Ref: defusedxml 包-Footnote-17599745
Node: xml etree ElementTree --- ElementTree XML API7599790
Ref: library/xml etree elementtree doc7599966
Ref: 2a077599966
Ref: library/xml etree elementtree dtd7599966
Ref: 2a087599966
Ref: library/xml etree elementtree module-xml etree ElementTree7599966
Ref: 1387599966
Ref: library/xml etree elementtree xml-etree-elementtree-the-elementtree-xml-api7599966
Ref: 2a097599966
Ref: xml etree ElementTree --- ElementTree XML API-Footnote-17600773
Node: 教程7600854
Ref: library/xml etree elementtree tutorial7600962
Ref: 2a0a7600962
Node: XML树和元素7601358
Ref: library/xml etree elementtree xml-tree-and-elements7601434
Ref: 2a0b7601434
Node: 解析XML7601895
Ref: library/xml etree elementtree elementtree-parsing-xml7602009
Ref: 2a0c7602009
Ref: library/xml etree elementtree parsing-xml7602009
Ref: 2a0d7602009
Node: Pull API进行非阻塞解析7604330
Ref: library/xml etree elementtree elementtree-pull-parsing7604453
Ref: 91c7604453
Ref: library/xml etree elementtree pull-api-for-non-blocking-parsing7604453
Ref: 2a0f7604453
Node: 查找感兴趣的元素7606164
Ref: library/xml etree elementtree finding-interesting-elements7606293
Ref: 2a127606293
Node: 修改XML文件7607461
Ref: library/xml etree elementtree modifying-an-xml-file7607576
Ref: 2a177607576
Node: 构建XML文档7610480
Ref: library/xml etree elementtree building-xml-documents7610598
Ref: 2a1b7610598
Node: 使用命名空间解析XML7610935
Ref: library/xml etree elementtree parsing-xml-with-namespaces7611053
Ref: 2a1d7611053
Ref: 使用命名空间解析XML-Footnote-17613341
Ref: 使用命名空间解析XML-Footnote-27613393
Node: 其他资源<2>7613445
Ref: library/xml etree elementtree additional-resources7613539
Ref: 2a1e7613539
Node: XPath支持7613679
Ref: library/xml etree elementtree elementtree-xpath7613805
Ref: 4227613805
Ref: library/xml etree elementtree xpath-support7613805
Ref: 2a1f7613805
Ref: XPath支持-Footnote-17614143
Node: 示例<10>7614179
Ref: library/xml etree elementtree example7614266
Ref: 2a207614266
Node: 支持的XPath语法7615263
Ref: library/xml etree elementtree supported-xpath-syntax7615350
Ref: 2a217615350
Node: 参考<2>7618673
Ref: library/xml etree elementtree reference7618808
Ref: 2a227618808
Node: 函数<6>7618872
Ref: library/xml etree elementtree elementtree-functions7618927
Ref: 2a237618927
Ref: library/xml etree elementtree functions7618927
Ref: 2a247618927
Ref: library/xml etree elementtree xml etree ElementTree canonicalize7618960
Ref: 2a257618960
Ref: library/xml etree elementtree xml etree ElementTree Comment7621273
Ref: 2a267621273
Ref: library/xml etree elementtree xml etree ElementTree dump7621880
Ref: 2a277621880
Ref: library/xml etree elementtree xml etree ElementTree fromstring7622316
Ref: 2a0e7622316
Ref: library/xml etree elementtree xml etree ElementTree fromstringlist7622673
Ref: b577622673
Ref: library/xml etree elementtree xml etree ElementTree iselement7623077
Ref: 2a297623077
Ref: library/xml etree elementtree xml etree ElementTree iterparse7623288
Ref: 9507623288
Ref: library/xml etree elementtree xml etree ElementTree parse7625007
Ref: 2a2a7625007
Ref: library/xml etree elementtree xml etree ElementTree ProcessingInstruction7625357
Ref: 2a2b7625357
Ref: library/xml etree elementtree xml etree ElementTree register_namespace7626003
Ref: b587626003
Ref: library/xml etree elementtree xml etree ElementTree SubElement7626436
Ref: 2a1c7626436
Ref: library/xml etree elementtree xml etree ElementTree tostring7626950
Ref: 91d7626950
Ref: library/xml etree elementtree xml etree ElementTree tostringlist7627974
Ref: 91e7627974
Ref: library/xml etree elementtree xml etree ElementTree XML7629155
Ref: 2a287629155
Ref: library/xml etree elementtree xml etree ElementTree XMLID7629557
Ref: 2a2c7629557
Ref: 函数<6>-Footnote-17630020
Ref: 函数<6>-Footnote-27630061
Ref: 函数<6>-Footnote-37630369
Node: XInclude 支持7630677
Ref: library/xml etree elementtree elementtree-xinclude7630810
Ref: 2a2d7630810
Ref: library/xml etree elementtree xinclude-support7630810
Ref: 2a2e7630810
Ref: XInclude 支持-Footnote-17631130
Node: 示例<11>7631170
Ref: library/xml etree elementtree id37631232
Ref: 2a2f7631232
Node: 参考<3>7632937
Ref: library/xml etree elementtree id47633052
Ref: 2a307633052
Node: 函数<7>7633262
Ref: library/xml etree elementtree elementinclude-functions7633338
Ref: 2a317633338
Ref: library/xml etree elementtree id57633338
Ref: 2a327633338
Ref: library/xml etree elementtree xml etree ElementTree xml etree ElementInclude default_loader7633371
Ref: 2a337633371
Ref: library/xml etree elementtree xml etree ElementTree xml etree ElementInclude include7633994
Ref: 2a347633994
Node: 元素对象7634596
Ref: library/xml etree elementtree element-objects7634699
Ref: 2a357634699
Ref: library/xml etree elementtree elementtree-element-objects7634699
Ref: 2a367634699
Ref: library/xml etree elementtree xml etree ElementTree Element7634742
Ref: acc7634742
Ref: library/xml etree elementtree xml etree ElementTree Element tag7635152
Ref: 2a377635152
Ref: library/xml etree elementtree xml etree ElementTree Element text7635272
Ref: 2a157635272
Ref: library/xml etree elementtree xml etree ElementTree Element tail7635294
Ref: 2a387635294
Ref: library/xml etree elementtree xml etree ElementTree Element attrib7636346
Ref: 2a397636346
Ref: library/xml etree elementtree xml etree ElementTree Element clear7636771
Ref: 2a3a7636771
Ref: library/xml etree elementtree xml etree ElementTree Element get7636946
Ref: 2a167636946
Ref: library/xml etree elementtree xml etree ElementTree Element items7637119
Ref: 2a3b7637119
Ref: library/xml etree elementtree xml etree ElementTree Element keys7637263
Ref: 2a3c7637263
Ref: library/xml etree elementtree xml etree ElementTree Element set7637383
Ref: 2a187637383
Ref: library/xml etree elementtree xml etree ElementTree Element append7637533
Ref: 2a197637533
Ref: library/xml etree elementtree xml etree ElementTree Element extend7637762
Ref: b597637762
Ref: library/xml etree elementtree xml etree ElementTree Element find7638010
Ref: 2a147638010
Ref: library/xml etree elementtree xml etree ElementTree Element findall7638437
Ref: 2a137638437
Ref: library/xml etree elementtree xml etree ElementTree Element findtext7638864
Ref: 2a3d7638864
Ref: library/xml etree elementtree xml etree ElementTree Element getchildren7639479
Ref: 2a3e7639479
Ref: library/xml etree elementtree xml etree ElementTree Element getiterator7639630
Ref: 2a3f7639630
Ref: library/xml etree elementtree xml etree ElementTree Element insert7639801
Ref: 2a407639801
Ref: library/xml etree elementtree xml etree ElementTree Element iter7640016
Ref: cef7640016
Ref: library/xml etree elementtree xml etree ElementTree Element iterfind7640454
Ref: b5a7640454
Ref: library/xml etree elementtree xml etree ElementTree Element itertext7640793
Ref: b5b7640793
Ref: library/xml etree elementtree xml etree ElementTree Element makeelement7641005
Ref: 2a417641005
Ref: library/xml etree elementtree xml etree ElementTree Element remove7641211
Ref: 2a1a7641211
Ref: 元素对象-Footnote-17643468
Node: ElementTree 对象7643511
Ref: library/xml etree elementtree elementtree-elementtree-objects7643617
Ref: 2a427643617
Ref: library/xml etree elementtree elementtree-objects7643617
Ref: 2a437643617
Ref: library/xml etree elementtree xml etree ElementTree ElementTree7643674
Ref: 91f7643674
Ref: library/xml etree elementtree xml etree ElementTree ElementTree _setroot7644006
Ref: 2a447644006
Ref: library/xml etree elementtree xml etree ElementTree ElementTree find7644232
Ref: 2a457644232
Ref: library/xml etree elementtree xml etree ElementTree ElementTree findall7644360
Ref: 2a467644360
Ref: library/xml etree elementtree xml etree ElementTree ElementTree findtext7644494
Ref: 2a477644494
Ref: library/xml etree elementtree xml etree ElementTree ElementTree getiterator7644644
Ref: 2a487644644
Ref: library/xml etree elementtree xml etree ElementTree ElementTree getroot7644820
Ref: 2a4a7644820
Ref: library/xml etree elementtree xml etree ElementTree ElementTree iter7644891
Ref: 2a497644891
Ref: library/xml etree elementtree xml etree ElementTree ElementTree iterfind7645118
Ref: 2a4b7645118
Ref: library/xml etree elementtree xml etree ElementTree ElementTree parse7645282
Ref: 2a4c7645282
Ref: library/xml etree elementtree xml etree ElementTree ElementTree write7645620
Ref: 9207645620
Ref: ElementTree 对象-Footnote-17648294
Node: QName 对象7648602
Ref: library/xml etree elementtree elementtree-qname-objects7648714
Ref: 2a4d7648714
Ref: library/xml etree elementtree qname-objects7648714
Ref: 2a4e7648714
Ref: library/xml etree elementtree xml etree ElementTree QName7648759
Ref: 2a4f7648759
Node: TreeBuilder 对象7649264
Ref: library/xml etree elementtree elementtree-treebuilder-objects7649373
Ref: 2a507649373
Ref: library/xml etree elementtree treebuilder-objects7649373
Ref: 2a517649373
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder7649430
Ref: 2547649430
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder close7650500
Ref: 2a527650500
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder data7650655
Ref: 2a537650655
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder end7650825
Ref: b5c7650825
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder start7650939
Ref: 2a547650939
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder comment7651115
Ref: 2a557651115
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder pi7651325
Ref: 2a567651325
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder doctype7651635
Ref: 2c27651635
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder start_ns7651924
Ref: 2a577651924
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder end_ns7652321
Ref: 2a587652321
Ref: library/xml etree elementtree xml etree ElementTree C14NWriterTarget7652538
Ref: 2a597652538
Ref: TreeBuilder 对象-Footnote-17653049
Node: XMLParser对象7653090
Ref: library/xml etree elementtree elementtree-xmlparser-objects7653206
Ref: 2a5a7653206
Ref: library/xml etree elementtree xmlparser-objects7653206
Ref: 2a5b7653206
Ref: library/xml etree elementtree xml etree ElementTree XMLParser7653257
Ref: 2537653257
Ref: library/xml etree elementtree xml etree ElementTree XMLParser close7653973
Ref: 2a5d7653973
Ref: library/xml etree elementtree xml etree ElementTree XMLParser feed7654195
Ref: 2a5c7654195
Ref: XMLParser对象-Footnote-17656078
Node: XMLPullParser对象7656386
Ref: library/xml etree elementtree elementtree-xmlpullparser-objects7656494
Ref: 2a5e7656494
Ref: library/xml etree elementtree xmlpullparser-objects7656494
Ref: 2a5f7656494
Ref: library/xml etree elementtree xml etree ElementTree XMLPullParser7656553
Ref: 91b7656553
Ref: library/xml etree elementtree xml etree ElementTree XMLPullParser feed7657184
Ref: 2a107657184
Ref: library/xml etree elementtree xml etree ElementTree XMLPullParser close7657268
Ref: 2a607657268
Ref: library/xml etree elementtree xml etree ElementTree XMLPullParser read_events7657556
Ref: 2a117657556
Node: 异常<15>7659089
Ref: library/xml etree elementtree exceptions7659173
Ref: 2a617659173
Ref: library/xml etree elementtree xml etree ElementTree ParseError7659206
Ref: c147659206
Ref: library/xml etree elementtree xml etree ElementTree ParseError code7659470
Ref: 2a627659470
Ref: library/xml etree elementtree xml etree ElementTree ParseError position7659655
Ref: 2a637659655
Node: xml dom --- 文档对象模型 API7659785
Ref: library/xml dom doc7659989
Ref: 2a647659989
Ref: library/xml dom module-xml dom7659989
Ref: 1357659989
Ref: library/xml dom xml-dom-the-document-object-model-api7659989
Ref: 2a657659989
Ref: xml dom --- 文档对象模型 API-Footnote-17663176
Ref: xml dom --- 文档对象模型 API-Footnote-27663252
Ref: xml dom --- 文档对象模型 API-Footnote-37663318
Ref: xml dom --- 文档对象模型 API-Footnote-47663365
Node: 模块内容<6>7663424
Ref: library/xml dom module-contents7663535
Ref: 2a687663535
Ref: library/xml dom xml dom registerDOMImplementation7663617
Ref: 2a697663617
Ref: library/xml dom xml dom getDOMImplementation7664010
Ref: 2a667664010
Ref: library/xml dom xml dom EMPTY_NAMESPACE7664836
Ref: 2a6a7664836
Ref: library/xml dom xml dom XML_NAMESPACE7665094
Ref: 2a6b7665094
Ref: library/xml dom xml dom XMLNS_NAMESPACE7665256
Ref: 2a6c7665256
Ref: library/xml dom xml dom XHTML_NAMESPACE7665439
Ref: 2a6d7665439
Ref: 模块内容<6>-Footnote-17666073
Ref: 模块内容<6>-Footnote-27666118
Ref: 模块内容<6>-Footnote-37666175
Node: DOM 中的对象7666213
Ref: library/xml dom dom-objects7666342
Ref: 2a6e7666342
Ref: library/xml dom objects-in-the-dom7666342
Ref: 2a6f7666342
Node: DOMImplementation 对象7670010
Ref: library/xml dom dom-implementation-objects7670108
Ref: 2a707670108
Ref: library/xml dom domimplementation-objects7670108
Ref: 2a7a7670108
Ref: library/xml dom xml dom DOMImplementation hasFeature7670433
Ref: 2a7b7670433
Ref: library/xml dom xml dom DOMImplementation createDocument7670602
Ref: 2a7c7670602
Ref: library/xml dom xml dom DOMImplementation createDocumentType7671112
Ref: 2a7d7671112
Node: 节点对象7671395
Ref: library/xml dom dom-node-objects7671520
Ref: 2a717671520
Ref: library/xml dom node-objects7671520
Ref: 2a7e7671520
Ref: library/xml dom xml dom Node nodeType7671624
Ref: 2a7f7671624
Ref: library/xml dom xml dom Node parentNode7672012
Ref: 2a807672012
Ref: library/xml dom xml dom Node attributes7672403
Ref: 2a817672403
Ref: library/xml dom xml dom Node previousSibling7672592
Ref: 2a827672592
Ref: library/xml dom xml dom Node nextSibling7673011
Ref: 2a837673011
Ref: library/xml dom xml dom Node childNodes7673270
Ref: 2a847673270
Ref: library/xml dom xml dom Node firstChild7673373
Ref: 2a857673373
Ref: library/xml dom xml dom Node lastChild7673502
Ref: 2a867673502
Ref: library/xml dom xml dom Node localName7673633
Ref: 2a877673633
Ref: library/xml dom xml dom Node prefix7673793
Ref: 2a887673793
Ref: library/xml dom xml dom Node namespaceURI7673968
Ref: 2a897673968
Ref: library/xml dom xml dom Node nodeName7674121
Ref: 2a8a7674121
Ref: library/xml dom xml dom Node nodeValue7674539
Ref: 2a8b7674539
Ref: library/xml dom xml dom Node hasAttributes7674776
Ref: 2a8c7674776
Ref: library/xml dom xml dom Node hasChildNodes7674874
Ref: 2a8d7674874
Ref: library/xml dom xml dom Node isSameNode7674975
Ref: 2a8e7674975
Ref: library/xml dom xml dom Node appendChild7675532
Ref: 2a8f7675532
Ref: library/xml dom xml dom Node insertBefore7675721
Ref: 2a907675721
Ref: library/xml dom xml dom Node removeChild7676093
Ref: 2a917676093
Ref: library/xml dom xml dom Node replaceChild7676403
Ref: 2a927676403
Ref: library/xml dom xml dom Node normalize7676630
Ref: 2a937676630
Ref: library/xml dom xml dom Node cloneNode7676833
Ref: 2a947676833
Node: 节点列表对象7676984
Ref: library/xml dom dom-nodelist-objects7677103
Ref: 2a727677103
Ref: library/xml dom nodelist-objects7677103
Ref: 2a957677103
Ref: library/xml dom xml dom NodeList item7677534
Ref: 2a967677534
Ref: library/xml dom xml dom NodeList length7677731
Ref: 2a977677731
Node: 文档类型对象7678306
Ref: library/xml dom documenttype-objects7678425
Ref: 2a987678425
Ref: library/xml dom dom-documenttype-objects7678425
Ref: 2a737678425
Ref: library/xml dom xml dom DocumentType publicId7678952
Ref: 2a997678952
Ref: library/xml dom xml dom DocumentType systemId7679093
Ref: 2a9a7679093
Ref: library/xml dom xml dom DocumentType internalSubset7679256
Ref: 2a9b7679256
Ref: library/xml dom xml dom DocumentType name7679466
Ref: 2a9c7679466
Ref: library/xml dom xml dom DocumentType entities7679572
Ref: 2a9d7679572
Ref: library/xml dom xml dom DocumentType notations7679899
Ref: 2a9e7679899
Node: 文档对象7680216
Ref: library/xml dom document-objects7680332
Ref: 2a9f7680332
Ref: library/xml dom dom-document-objects7680332
Ref: 2a747680332
Ref: library/xml dom xml dom Document documentElement7680538
Ref: 2aa07680538
Ref: library/xml dom xml dom Document createElement7680610
Ref: 2aa17680610
Ref: library/xml dom xml dom Document createElementNS7680879
Ref: 2aa27680879
Ref: library/xml dom xml dom Document createTextNode7681210
Ref: 2aa37681210
Ref: library/xml dom xml dom Document createComment7681415
Ref: 2aa47681415
Ref: library/xml dom xml dom Document createProcessingInstruction7681613
Ref: 2aa57681613
Ref: library/xml dom xml dom Document createAttribute7681860
Ref: 2aa67681860
Ref: library/xml dom xml dom Document createAttributeNS7682132
Ref: 2aa77682132
Ref: library/xml dom xml dom Document getElementsByTagName7682488
Ref: 2aa87682488
Ref: library/xml dom xml dom Document getElementsByTagNameNS7682656
Ref: 2aa97682656
Node: 元素对象<2>7682908
Ref: library/xml dom dom-element-objects7683017
Ref: 2a757683017
Ref: library/xml dom element-objects7683017
Ref: 2aaa7683017
Ref: library/xml dom xml dom Element tagName7683140
Ref: 2aab7683140
Ref: library/xml dom xml dom Element getElementsByTagName7683289
Ref: 2aac7683289
Ref: library/xml dom xml dom Element getElementsByTagNameNS7683397
Ref: 2aad7683397
Ref: library/xml dom xml dom Element hasAttribute7683523
Ref: 2aae7683523
Ref: library/xml dom xml dom Element hasAttributeNS7683638
Ref: 2aaf7683638
Ref: library/xml dom xml dom Element getAttribute7683803
Ref: 2ab07683803
Ref: library/xml dom xml dom Element getAttributeNode7684013
Ref: 2ab17684013
Ref: library/xml dom xml dom Element getAttributeNS7684135
Ref: 2ab27684135
Ref: library/xml dom xml dom Element getAttributeNodeNS7684390
Ref: 2ab37684390
Ref: library/xml dom xml dom Element removeAttribute7684540
Ref: 2ab47684540
Ref: library/xml dom xml dom Element removeAttributeNode7684697
Ref: 2ab67684697
Ref: library/xml dom xml dom Element removeAttributeNS7684906
Ref: 2ab77684906
Ref: library/xml dom xml dom Element setAttribute7685117
Ref: 2ab87685117
Ref: library/xml dom xml dom Element setAttributeNode7685211
Ref: 2ab97685211
Ref: library/xml dom xml dom Element setAttributeNodeNS7685532
Ref: 2abb7685532
Ref: library/xml dom xml dom Element setAttributeNS7685887
Ref: 2abc7685887
Node: Attr 对象7686106
Ref: library/xml dom attr-objects7686222
Ref: 2abd7686222
Ref: library/xml dom dom-attr-objects7686222
Ref: 2a767686222
Ref: library/xml dom xml dom Attr name7686332
Ref: 2abe7686332
Ref: library/xml dom xml dom Attr localName7686435
Ref: 2abf7686435
Ref: library/xml dom xml dom Attr prefix7686570
Ref: 2ac07686570
Ref: library/xml dom xml dom Attr value7686683
Ref: 2ac17686683
Node: NamedNodeMap 对象7686774
Ref: library/xml dom dom-attributelist-objects7686887
Ref: 2ac27686887
Ref: library/xml dom namednodemap-objects7686887
Ref: 2ac37686887
Ref: library/xml dom xml dom NamedNodeMap length7686999
Ref: 2ac47686999
Ref: library/xml dom xml dom NamedNodeMap item7687063
Ref: 2ac57687063
Node: 注释对象7687507
Ref: library/xml dom comment-objects7687637
Ref: 2ac67687637
Ref: library/xml dom dom-comment-objects7687637
Ref: 2a777687637
Ref: library/xml dom xml dom Comment data7687790
Ref: 2ac77687790
Node: Text 和 CDATASection 对象7687988
Ref: library/xml dom dom-text-objects7688127
Ref: 2a787688127
Ref: library/xml dom text-and-cdatasection-objects7688127
Ref: 2ac87688127
Ref: library/xml dom xml dom Text data7688560
Ref: 2ac97688560
Node: ProcessingInstruction 对象7688988
Ref: library/xml dom dom-pi-objects7689125
Ref: 2a797689125
Ref: library/xml dom processinginstruction-objects7689125
Ref: 2aca7689125
Ref: library/xml dom xml dom ProcessingInstruction target7689306
Ref: 2acb7689306
Ref: library/xml dom xml dom ProcessingInstruction data7689431
Ref: 2acc7689431
Node: 异常<16>7689529
Ref: library/xml dom dom-exceptions7689629
Ref: 2acd7689629
Ref: library/xml dom exceptions7689629
Ref: 2ace7689629
Ref: library/xml dom xml dom DOMException7690158
Ref: 2acf7690158
Ref: library/xml dom xml dom DomstringSizeErr7690289
Ref: 2ad07690289
Ref: library/xml dom xml dom HierarchyRequestErr7690513
Ref: 2ad17690513
Ref: library/xml dom xml dom IndexSizeErr7690633
Ref: 2ad27690633
Ref: library/xml dom xml dom InuseAttributeErr7690764
Ref: 2aba7690764
Ref: library/xml dom xml dom InvalidAccessErr7690906
Ref: 2ad37690906
Ref: library/xml dom xml dom InvalidCharacterErr7691020
Ref: 2ad47691020
Ref: library/xml dom xml dom InvalidModificationErr7691309
Ref: 2ad57691309
Ref: library/xml dom xml dom InvalidStateErr7691411
Ref: 2ad67691411
Ref: library/xml dom xml dom NamespaceErr7691521
Ref: 2ad77691521
Ref: library/xml dom xml dom NotFoundErr7691682
Ref: 2ab57691682
Ref: library/xml dom xml dom NotSupportedErr7691919
Ref: 2ad87691919
Ref: library/xml dom xml dom NoDataAllowedErr7692035
Ref: 2ad97692035
Ref: library/xml dom xml dom NoModificationAllowedErr7692144
Ref: 2ada7692144
Ref: library/xml dom xml dom SyntaxErr7692281
Ref: 2adb7692281
Ref: library/xml dom xml dom WrongDocumentErr7692373
Ref: 2adc7692373
Ref: 异常<16>-Footnote-17695339
Node: 一致性7695384
Ref: library/xml dom conformance7695489
Ref: 2add7695489
Ref: library/xml dom dom-conformance7695489
Ref: 2a677695489
Node: 类型映射7695692
Ref: library/xml dom dom-type-mapping7695774
Ref: 2ade7695774
Ref: library/xml dom type-mapping7695774
Ref: 2adf7695774
Node: 访问器方法7696572
Ref: library/xml dom accessor-methods7696654
Ref: 2ae07696654
Ref: library/xml dom dom-accessor-methods7696654
Ref: 2ae17696654
Node: xml dom minidom --- 最小化的 DOM 实现7698327
Ref: library/xml dom minidom doc7698532
Ref: 2ae27698532
Ref: library/xml dom minidom module-xml dom minidom7698532
Ref: 1367698532
Ref: library/xml dom minidom xml-dom-minidom-minimal-dom-implementation7698532
Ref: 2ae37698532
Ref: library/xml dom minidom xml dom minidom parse7699788
Ref: 2ae47699788
Ref: library/xml dom minidom xml dom minidom parseString7700350
Ref: 2ae57700350
Ref: xml dom minidom --- 最小化的 DOM 实现-Footnote-17702820
Ref: xml dom minidom --- 最小化的 DOM 实现-Footnote-27702894
Node: DOM 对象7702941
Ref: library/xml dom minidom dom-objects7703050
Ref: 2ae67703050
Ref: library/xml dom minidom minidom-objects7703050
Ref: 2ae77703050
Ref: library/xml dom minidom xml dom minidom Node unlink7703256
Ref: 2ae87703256
Ref: library/xml dom minidom xml dom minidom Node writexml7703985
Ref: 2ae97703985
Ref: library/xml dom minidom xml dom minidom Node toxml7704652
Ref: 2aea7704652
Ref: library/xml dom minidom xml dom minidom Node toprettyxml7705251
Ref: 2aeb7705251
Ref: DOM 对象-Footnote-17705720
Node: DOM 示例7706108
Ref: library/xml dom minidom dom-example7706248
Ref: 2aec7706248
Ref: library/xml dom minidom id27706248
Ref: 2aed7706248
Node: minidom 和 DOM 标准7708260
Ref: library/xml dom minidom minidom-and-dom7708381
Ref: 2aee7708381
Ref: library/xml dom minidom minidom-and-the-dom-standard7708381
Ref: 2aef7708381
Node: xml dom pulldom --- 支持构建部分 DOM 树7710727
Ref: library/xml dom pulldom doc7710931
Ref: 2af07710931
Ref: library/xml dom pulldom module-xml dom pulldom7710931
Ref: 1377710931
Ref: library/xml dom pulldom xml-dom-pulldom-support-for-building-partial-dom-trees7710931
Ref: 2af17710931
Ref: library/xml dom pulldom xml dom pulldom PullDom7713456
Ref: 2af37713456
Ref: library/xml dom pulldom xml dom pulldom SAX2DOM7713576
Ref: 2af57713576
Ref: library/xml dom pulldom xml dom pulldom parse7713696
Ref: 2af67713696
Ref: library/xml dom pulldom xml dom pulldom parseString7714282
Ref: 2af87714282
Ref: library/xml dom pulldom xml dom pulldom default_bufsize7714423
Ref: 2af97714423
Ref: xml dom pulldom --- 支持构建部分 DOM 树-Footnote-17714698
Node: DOMEventStream 对象7714772
Ref: library/xml dom pulldom domeventstream-objects7714876
Ref: 2afa7714876
Ref: library/xml dom pulldom id17714876
Ref: 2afb7714876
Ref: library/xml dom pulldom xml dom pulldom DOMEventStream7714937
Ref: 27d7714937
Ref: library/xml dom pulldom xml dom pulldom DOMEventStream getEvent7715085
Ref: 2afc7715085
Ref: library/xml dom pulldom xml dom pulldom DOMEventStream expandNode7715590
Ref: 2af27715590
Ref: library/xml dom pulldom xml dom pulldom DOMEventStream reset7716311
Ref: 2afd7716311
Node: xml sax --- 支持 SAX2 解析器7716338
Ref: library/xml sax doc7716544
Ref: 2afe7716544
Ref: library/xml sax module-xml sax7716544
Ref: 13c7716544
Ref: library/xml sax xml-sax-support-for-sax2-parsers7716544
Ref: 2aff7716544
Ref: library/xml sax xml sax make_parser7717548
Ref: 10387717548
Ref: library/xml sax xml sax parse7718090
Ref: ff17718090
Ref: library/xml sax xml sax parseString7718701
Ref: 79c7718701
Ref: library/xml sax xml sax SAXException7720516
Ref: 2b057720516
Ref: library/xml sax xml sax SAXParseException7721270
Ref: 2b037721270
Ref: library/xml sax xml sax SAXNotRecognizedException7721633
Ref: 2b067721633
Ref: library/xml sax xml sax SAXNotSupportedException7721912
Ref: 2b077721912
Ref: xml sax --- 支持 SAX2 解析器-Footnote-17722793
Ref: xml sax --- 支持 SAX2 解析器-Footnote-27722869
Node: SAXException 对象7722904
Ref: library/xml sax sax-exception-objects7722993
Ref: 2b087722993
Ref: library/xml sax saxexception-objects7722993
Ref: 2b097722993
Ref: library/xml sax xml sax SAXException getMessage7723106
Ref: 2b0a7723106
Ref: library/xml sax xml sax SAXException getException7723210
Ref: 2b0b7723210
Node: xml sax handler --- SAX 处理程序的基类7723312
Ref: library/xml sax handler doc7723506
Ref: 2b0c7723506
Ref: library/xml sax handler module-xml sax handler7723506
Ref: 13d7723506
Ref: library/xml sax handler xml-sax-handler-base-classes-for-sax-handlers7723506
Ref: 2b0d7723506
Ref: library/xml sax handler xml sax handler ContentHandler7724113
Ref: 2af47724113
Ref: library/xml sax handler xml sax handler DTDHandler7724320
Ref: 2b0e7724320
Ref: library/xml sax handler xml sax handler EntityResolver7724489
Ref: 2b0f7724489
Ref: library/xml sax handler xml sax handler ErrorHandler7724742
Ref: 2b027724742
Ref: library/xml sax handler xml sax handler feature_namespaces7725063
Ref: 2b107725063
Ref: library/xml sax handler xml sax handler feature_namespace_prefixes7725379
Ref: 2b117725379
Ref: library/xml sax handler xml sax handler feature_string_interning7725767
Ref: 2b127725767
Ref: library/xml sax handler xml sax handler feature_validation7726176
Ref: 2b137726176
Ref: library/xml sax handler xml sax handler feature_external_ges7726507
Ref: 2b017726507
Ref: library/xml sax handler xml sax handler feature_external_pes7726809
Ref: 2b147726809
Ref: library/xml sax handler xml sax handler all_features7727165
Ref: 2b157727165
Ref: library/xml sax handler xml sax handler property_lexical_handler7727235
Ref: 2b167727235
Ref: library/xml sax handler xml sax handler property_declaration_handler7727556
Ref: 2b177727556
Ref: library/xml sax handler xml sax handler property_dom_node7727909
Ref: 2b187727909
Ref: library/xml sax handler xml sax handler property_xml_string7728307
Ref: 2b197728307
Ref: library/xml sax handler xml sax handler all_properties7728548
Ref: 2b1a7728548
Ref: xml sax handler --- SAX 处理程序的基类-Footnote-17728770
Node: ContentHandler 对象7728844
Ref: library/xml sax handler content-handler-objects7728973
Ref: 2b1b7728973
Ref: library/xml sax handler contenthandler-objects7728973
Ref: 2b1c7728973
Ref: library/xml sax handler xml sax handler ContentHandler setDocumentLocator7729190
Ref: 2b1d7729190
Ref: library/xml sax handler xml sax handler ContentHandler startDocument7730098
Ref: 2b1e7730098
Ref: library/xml sax handler xml sax handler ContentHandler endDocument7730376
Ref: 2b1f7730376
Ref: library/xml sax handler xml sax handler ContentHandler startPrefixMapping7730714
Ref: 2b207730714
Ref: library/xml sax handler xml sax handler ContentHandler endPrefixMapping7731824
Ref: 2b217731824
Ref: library/xml sax handler xml sax handler ContentHandler startElement7732157
Ref: 2b227732157
Ref: library/xml sax handler xml sax handler ContentHandler endElement7732719
Ref: 2b237732719
Ref: library/xml sax handler xml sax handler ContentHandler startElementNS7732935
Ref: 2b257732935
Ref: library/xml sax handler xml sax handler ContentHandler endElementNS7733812
Ref: 2b277733812
Ref: library/xml sax handler xml sax handler ContentHandler characters7734068
Ref: 2b287734068
Ref: library/xml sax handler xml sax handler ContentHandler ignorableWhitespace7735043
Ref: 2b297735043
Ref: library/xml sax handler xml sax handler ContentHandler processingInstruction7735645
Ref: 2b2a7735645
Ref: library/xml sax handler xml sax handler ContentHandler skippedEntity7736053
Ref: 2b2b7736053
Node: DTDHandler 对象7736573
Ref: library/xml sax handler dtd-handler-objects7736732
Ref: 2b2c7736732
Ref: library/xml sax handler dtdhandler-objects7736732
Ref: 2b2d7736732
Ref: library/xml sax handler xml sax handler DTDHandler notationDecl7736841
Ref: 2b2e7736841
Ref: library/xml sax handler xml sax handler DTDHandler unparsedEntityDecl7736939
Ref: 2b2f7736939
Node: EntityResolver 对象7737072
Ref: library/xml sax handler entity-resolver-objects7737229
Ref: 2b307737229
Ref: library/xml sax handler entityresolver-objects7737229
Ref: 2b317737229
Ref: library/xml sax handler xml sax handler EntityResolver resolveEntity7737292
Ref: 2b327737292
Node: ErrorHandler 对象7737552
Ref: library/xml sax handler errorhandler-objects7737683
Ref: 2b337737683
Ref: library/xml sax handler sax-error-handler7737683
Ref: 2b347737683
Ref: library/xml sax handler xml sax handler ErrorHandler error7738298
Ref: 2b357738298
Ref: library/xml sax handler xml sax handler ErrorHandler fatalError7738615
Ref: 2b367738615
Ref: library/xml sax handler xml sax handler ErrorHandler warning7738770
Ref: 2b377738770
Node: xml sax saxutils --- SAX 工具集7739047
Ref: library/xml sax utils doc7739259
Ref: 2b387739259
Ref: library/xml sax utils module-xml sax saxutils7739259
Ref: 13e7739259
Ref: library/xml sax utils xml-sax-saxutils-sax-utilities7739259
Ref: 2b397739259
Ref: library/xml sax utils xml sax saxutils escape7739627
Ref: 2b3a7739627
Ref: library/xml sax utils xml sax saxutils unescape7740070
Ref: 2b3b7740070
Ref: library/xml sax utils xml sax saxutils quoteattr7740544
Ref: 2b3c7740544
Ref: library/xml sax utils xml sax saxutils XMLGenerator7741322
Ref: 2b3d7741322
Ref: library/xml sax utils xml sax saxutils XMLFilterBase7742132
Ref: 2b3e7742132
Ref: library/xml sax utils xml sax saxutils prepare_input_source7742515
Ref: 2b3f7742515
Ref: xml sax saxutils --- SAX 工具集-Footnote-17742974
Node: xml sax xmlreader --- 用于 XML 解析器的接口7743050
Ref: library/xml sax reader doc7743272
Ref: 2b407743272
Ref: library/xml sax reader module-xml sax xmlreader7743272
Ref: 13f7743272
Ref: library/xml sax reader xml-sax-xmlreader-interface-for-xml-parsers7743272
Ref: 2b417743272
Ref: library/xml sax reader xml sax xmlreader XMLReader7743775
Ref: 2af77743775
Ref: library/xml sax reader xml sax xmlreader IncrementalParser7743858
Ref: 2b427743858
Ref: library/xml sax reader xml sax xmlreader Locator7744860
Ref: 2b047744860
Ref: library/xml sax reader xml sax xmlreader InputSource7745186
Ref: 79b7745186
Ref: library/xml sax reader xml sax xmlreader AttributesImpl7745852
Ref: 2b447745852
Ref: library/xml sax reader xml sax xmlreader AttributesNSImpl7746325
Ref: 2b457746325
Ref: xml sax xmlreader --- 用于 XML 解析器的接口-Footnote-17747023
Node: XMLReader 对象7747100
Ref: library/xml sax reader id17747237
Ref: 2b467747237
Ref: library/xml sax reader xmlreader-objects7747237
Ref: 2b477747237
Ref: library/xml sax reader xml sax xmlreader XMLReader parse7747340
Ref: 2b437747340
Ref: library/xml sax reader xml sax xmlreader XMLReader getContentHandler7747896
Ref: 2b487747896
Ref: library/xml sax reader xml sax xmlreader XMLReader setContentHandler7747993
Ref: 2b497747993
Ref: library/xml sax reader xml sax xmlreader XMLReader getDTDHandler7748179
Ref: 2b4a7748179
Ref: library/xml sax reader xml sax xmlreader XMLReader setDTDHandler7748268
Ref: 2b4b7748268
Ref: library/xml sax reader xml sax xmlreader XMLReader getEntityResolver7748440
Ref: 2b4c7748440
Ref: library/xml sax reader xml sax xmlreader XMLReader setEntityResolver7748537
Ref: 2b4d7748537
Ref: library/xml sax reader xml sax xmlreader XMLReader getErrorHandler7748822
Ref: 2b4e7748822
Ref: library/xml sax reader xml sax xmlreader XMLReader setErrorHandler7748915
Ref: 2b4f7748915
Ref: library/xml sax reader xml sax xmlreader XMLReader setLocale7749121
Ref: 2b507749121
Ref: library/xml sax reader xml sax xmlreader XMLReader getFeature7749466
Ref: 2b517749466
Ref: library/xml sax reader xml sax xmlreader XMLReader setFeature7749730
Ref: 2b007749730
Ref: library/xml sax reader xml sax xmlreader XMLReader getProperty7750010
Ref: 2b527750010
Ref: library/xml sax reader xml sax xmlreader XMLReader setProperty7750277
Ref: 2b537750277
Node: IncrementalParser 对象7750560
Ref: library/xml sax reader incremental-parser-objects7750720
Ref: 2b547750720
Ref: library/xml sax reader incrementalparser-objects7750720
Ref: 2b557750720
Ref: library/xml sax reader xml sax xmlreader IncrementalParser feed7750859
Ref: 2b567750859
Ref: library/xml sax reader xml sax xmlreader IncrementalParser close7750941
Ref: 2b577750941
Ref: library/xml sax reader xml sax xmlreader IncrementalParser reset7751166
Ref: 2b587751166
Node: Locator 对象7751410
Ref: library/xml sax reader id27751572
Ref: 2b597751572
Ref: library/xml sax reader locator-objects7751572
Ref: 2b5a7751572
Ref: library/xml sax reader xml sax xmlreader Locator getColumnNumber7751675
Ref: 2b5b7751675
Ref: library/xml sax reader xml sax xmlreader Locator getLineNumber7751764
Ref: 2b5c7751764
Ref: library/xml sax reader xml sax xmlreader Locator getPublicId7751851
Ref: 2b5d7751851
Ref: library/xml sax reader xml sax xmlreader Locator getSystemId7751933
Ref: 2b5e7751933
Node: InputSource 对象7752015
Ref: library/xml sax reader input-source-objects7752170
Ref: 2b5f7752170
Ref: library/xml sax reader inputsource-objects7752170
Ref: 2b607752170
Ref: library/xml sax reader xml sax xmlreader InputSource setPublicId7752227
Ref: 2b617752227
Ref: library/xml sax reader xml sax xmlreader InputSource getPublicId7752331
Ref: 2b627752331
Ref: library/xml sax reader xml sax xmlreader InputSource setSystemId7752433
Ref: 2b637752433
Ref: library/xml sax reader xml sax xmlreader InputSource getSystemId7752537
Ref: 2b647752537
Ref: library/xml sax reader xml sax xmlreader InputSource setEncoding7752639
Ref: 2b657752639
Ref: library/xml sax reader xml sax xmlreader InputSource getEncoding7752997
Ref: 2b667752997
Ref: library/xml sax reader xml sax xmlreader InputSource setByteStream7753090
Ref: 2b677753090
Ref: library/xml sax reader xml sax xmlreader InputSource getByteStream7753498
Ref: 2b687753498
Ref: library/xml sax reader xml sax xmlreader InputSource setCharacterStream7753690
Ref: 2b697753690
Ref: library/xml sax reader xml sax xmlreader InputSource getCharacterStream7753972
Ref: 2b6a7753972
Node: Attributes 接口7754059
Ref: library/xml sax reader attributes-objects7754219
Ref: 2b247754219
Ref: library/xml sax reader the-attributes-interface7754219
Ref: 2b6b7754219
Ref: library/xml sax reader xml sax xmlreader Attributes getLength7754500
Ref: 2b6c7754500
Ref: library/xml sax reader xml sax xmlreader Attributes getNames7754568
Ref: 2b6d7754568
Ref: library/xml sax reader xml sax xmlreader Attributes getType7754635
Ref: 2b6e7754635
Ref: library/xml sax reader xml sax xmlreader Attributes getValue7754739
Ref: 2b6f7754739
Node: AttributesNS 接口7754815
Ref: library/xml sax reader attributes-ns-objects7754948
Ref: 2b267754948
Ref: library/xml sax reader the-attributesns-interface7754948
Ref: 2b707754948
Ref: library/xml sax reader xml sax xmlreader AttributesNS getValueByQName7755239
Ref: 2b717755239
Ref: library/xml sax reader xml sax xmlreader AttributesNS getNameByQName7755328
Ref: 2b727755328
Ref: library/xml sax reader xml sax xmlreader AttributesNS getQNameByName7755448
Ref: 2b737755448
Ref: library/xml sax reader xml sax xmlreader AttributesNS getQNames7755560
Ref: 2b747755560
Node: xml parsers expat --- 使用 Expat 的快速 XML 解析7755642
Ref: library/pyexpat doc7755821
Ref: 2b757755821
Ref: library/pyexpat module-xml parsers expat7755821
Ref: 1397755821
Ref: library/pyexpat xml-parsers-expat-fast-xml-parsing-using-expat7755821
Ref: 2b767755821
Ref: library/pyexpat xml parsers expat ExpatError7756844
Ref: c157756844
Ref: library/pyexpat xml parsers expat error7757038
Ref: 2b787757038
Ref: library/pyexpat xml parsers expat XMLParserType7757117
Ref: 2b797757117
Ref: library/pyexpat xml parsers expat ErrorString7757291
Ref: 2b7b7757291
Ref: library/pyexpat xml parsers expat ParserCreate7757403
Ref: 2b7a7757403
Ref: xml parsers expat --- 使用 Expat 的快速 XML 解析-Footnote-17759726
Ref: xml parsers expat --- 使用 Expat 的快速 XML 解析-Footnote-27760034
Node: XMLParser对象<2>7760067
Ref: library/pyexpat id27760203
Ref: 2b7c7760203
Ref: library/pyexpat xmlparser-objects7760203
Ref: 2b7d7760203
Ref: library/pyexpat xml parsers expat xmlparser Parse7760297
Ref: 2b7e7760297
Ref: library/pyexpat xml parsers expat xmlparser ParseFile7760649
Ref: 2b7f7760649
Ref: library/pyexpat xml parsers expat xmlparser SetBase7760850
Ref: 2b807760850
Ref: library/pyexpat xml parsers expat xmlparser GetBase7761217
Ref: 2b847761217
Ref: library/pyexpat xml parsers expat xmlparser GetInputContext7761419
Ref: 2b857761419
Ref: library/pyexpat xml parsers expat xmlparser ExternalEntityParserCreate7761667
Ref: 2b867761667
Ref: library/pyexpat xml parsers expat xmlparser SetParamEntityParsing7762131
Ref: 2b897762131
Ref: library/pyexpat xml parsers expat xmlparser UseForeignDTD7762466
Ref: 2b8a7762466
Ref: library/pyexpat xml parsers expat xmlparser buffer_size7763394
Ref: 2b8d7763394
Ref: library/pyexpat xml parsers expat xmlparser buffer_text7763659
Ref: 2b8e7763659
Ref: library/pyexpat xml parsers expat xmlparser buffer_used7764071
Ref: 2b907764071
Ref: library/pyexpat xml parsers expat xmlparser ordered_attributes7764333
Ref: 2b877764333
Ref: library/pyexpat xml parsers expat xmlparser specified_attributes7764755
Ref: 2b887764755
Ref: library/pyexpat xml parsers expat xmlparser ErrorByteIndex7765401
Ref: 2b917765401
Ref: library/pyexpat xml parsers expat xmlparser ErrorCode7765485
Ref: 2b927765485
Ref: library/pyexpat xml parsers expat xmlparser ErrorColumnNumber7765691
Ref: 2b937765691
Ref: library/pyexpat xml parsers expat xmlparser ErrorLineNumber7765769
Ref: 2b947765769
Ref: library/pyexpat xml parsers expat xmlparser CurrentByteIndex7766175
Ref: 2b957766175
Ref: library/pyexpat xml parsers expat xmlparser CurrentColumnNumber7766264
Ref: 2b967766264
Ref: library/pyexpat xml parsers expat xmlparser CurrentLineNumber7766347
Ref: 2b977766347
Ref: library/pyexpat xml parsers expat xmlparser XmlDeclHandler7766740
Ref: 2b987766740
Ref: library/pyexpat xml parsers expat xmlparser StartDoctypeDeclHandler7767268
Ref: 2b8b7767268
Ref: library/pyexpat xml parsers expat xmlparser EndDoctypeDeclHandler7767777
Ref: 2b8c7767777
Ref: library/pyexpat xml parsers expat xmlparser ElementDeclHandler7767932
Ref: 2b997767932
Ref: library/pyexpat xml parsers expat xmlparser AttlistDeclHandler7768120
Ref: 2b9a7768120
Ref: library/pyexpat xml parsers expat xmlparser StartElementHandler7768923
Ref: 2b9b7768923
Ref: library/pyexpat xml parsers expat xmlparser EndElementHandler7769301
Ref: 2b9c7769301
Ref: library/pyexpat xml parsers expat xmlparser ProcessingInstructionHandler7769392
Ref: 2b9d7769392
Ref: library/pyexpat xml parsers expat xmlparser CharacterDataHandler7769499
Ref: 2b8f7769499
Ref: library/pyexpat xml parsers expat xmlparser UnparsedEntityDeclHandler7769890
Ref: 2b837769890
Ref: library/pyexpat xml parsers expat xmlparser EntityDeclHandler7770247
Ref: 2ba07770247
Ref: library/pyexpat xml parsers expat xmlparser NotationDeclHandler7770899
Ref: 2b827770899
Ref: library/pyexpat xml parsers expat xmlparser StartNamespaceDeclHandler7771193
Ref: 2ba17771193
Ref: library/pyexpat xml parsers expat xmlparser EndNamespaceDeclHandler7771430
Ref: 2ba27771430
Ref: library/pyexpat xml parsers expat xmlparser CommentHandler7771884
Ref: 2ba37771884
Ref: library/pyexpat xml parsers expat xmlparser StartCdataSectionHandler7772066
Ref: 2b9e7772066
Ref: library/pyexpat xml parsers expat xmlparser EndCdataSectionHandler7772286
Ref: 2b9f7772286
Ref: library/pyexpat xml parsers expat xmlparser DefaultHandler7772382
Ref: 2ba47772382
Ref: library/pyexpat xml parsers expat xmlparser DefaultHandlerExpand7772614
Ref: 2ba57772614
Ref: library/pyexpat xml parsers expat xmlparser NotStandaloneHandler7772817
Ref: 2ba67772817
Ref: library/pyexpat xml parsers expat xmlparser ExternalEntityRefHandler7773310
Ref: 2b817773310
Node: ExpatError 异常7774338
Ref: library/pyexpat expaterror-exceptions7774493
Ref: 2ba77774493
Ref: library/pyexpat expaterror-objects7774493
Ref: 2b777774493
Ref: library/pyexpat xml parsers expat ExpatError code7774607
Ref: 2ba87774607
Ref: library/pyexpat xml parsers expat ExpatError lineno7775208
Ref: 2bab7775208
Ref: library/pyexpat xml parsers expat ExpatError offset7775309
Ref: 2bac7775309
Node: 示例<12>7775419
Ref: library/pyexpat example7775574
Ref: 2bad7775574
Ref: library/pyexpat expat-example7775574
Ref: 2bae7775574
Node: 内容模型描述7776668
Ref: library/pyexpat content-model-descriptions7776824
Ref: 2baf7776824
Ref: library/pyexpat expat-content-models7776824
Ref: 2bb07776824
Ref: library/pyexpat module-xml parsers expat model7776824
Ref: 13b7776824
Node: Expat 错误常量7778470
Ref: library/pyexpat expat-error-constants7778607
Ref: 2bb17778607
Ref: library/pyexpat expat-errors7778607
Ref: 2bb27778607
Ref: library/pyexpat module-xml parsers expat errors7778607
Ref: 13a7778607
Ref: library/pyexpat xml parsers expat errors codes7779135
Ref: 2baa7779135
Ref: library/pyexpat xml parsers expat errors messages7779264
Ref: 2ba97779264
Ref: library/pyexpat xml parsers expat errors XML_ERROR_ASYNC_ENTITY7779411
Ref: 2bb37779411
Ref: library/pyexpat xml parsers expat errors XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF7779472
Ref: 2bb47779472
Ref: library/pyexpat xml parsers expat errors XML_ERROR_BAD_CHAR_REF7779639
Ref: 2bb57779639
Ref: library/pyexpat xml parsers expat errors XML_ERROR_BINARY_ENTITY_REF7779810
Ref: 2bb67779810
Ref: library/pyexpat xml parsers expat errors XML_ERROR_DUPLICATE_ATTRIBUTE7779964
Ref: 2bb77779964
Ref: library/pyexpat xml parsers expat errors XML_ERROR_INCORRECT_ENCODING7780099
Ref: 2bb87780099
Ref: library/pyexpat xml parsers expat errors XML_ERROR_INVALID_TOKEN7780166
Ref: 2bb97780166
Ref: library/pyexpat xml parsers expat errors XML_ERROR_JUNK_AFTER_DOC_ELEMENT7780373
Ref: 2bba7780373
Ref: library/pyexpat xml parsers expat errors XML_ERROR_MISPLACED_XML_PI7780505
Ref: 2bbb7780505
Ref: library/pyexpat xml parsers expat errors XML_ERROR_NO_ELEMENTS7780639
Ref: 2bbc7780639
Ref: library/pyexpat xml parsers expat errors XML_ERROR_NO_MEMORY7780803
Ref: 2bbd7780803
Ref: library/pyexpat xml parsers expat errors XML_ERROR_PARAM_ENTITY_REF7780904
Ref: 2bbe7780904
Ref: library/pyexpat xml parsers expat errors XML_ERROR_PARTIAL_CHAR7781033
Ref: 2bbf7781033
Ref: library/pyexpat xml parsers expat errors XML_ERROR_RECURSIVE_ENTITY_REF7781146
Ref: 2bc07781146
Ref: library/pyexpat xml parsers expat errors XML_ERROR_SYNTAX7781354
Ref: 2bc17781354
Ref: library/pyexpat xml parsers expat errors XML_ERROR_TAG_MISMATCH7781458
Ref: 2bc27781458
Ref: library/pyexpat xml parsers expat errors XML_ERROR_UNCLOSED_TOKEN7781595
Ref: 2bc37781595
Ref: library/pyexpat xml parsers expat errors XML_ERROR_UNDEFINED_ENTITY7781758
Ref: 2bc47781758
Ref: library/pyexpat xml parsers expat errors XML_ERROR_UNKNOWN_ENCODING7781875
Ref: 2bc57781875
Ref: library/pyexpat xml parsers expat errors XML_ERROR_UNCLOSED_CDATA_SECTION7781990
Ref: 2bc67781990
Ref: library/pyexpat xml parsers expat errors XML_ERROR_EXTERNAL_ENTITY_HANDLING7782105
Ref: 2bc77782105
Ref: library/pyexpat xml parsers expat errors XML_ERROR_NOT_STANDALONE7782178
Ref: 2bc87782178
Ref: library/pyexpat xml parsers expat errors XML_ERROR_UNEXPECTED_STATE7782411
Ref: 2bc97782411
Ref: library/pyexpat xml parsers expat errors XML_ERROR_ENTITY_DECLARED_IN_PE7782476
Ref: 2bca7782476
Ref: library/pyexpat xml parsers expat errors XML_ERROR_FEATURE_REQUIRES_XML_DTD7782546
Ref: 2bcb7782546
Ref: library/pyexpat xml parsers expat errors XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING7782834
Ref: 2bcc7782834
Ref: library/pyexpat xml parsers expat errors XML_ERROR_UNBOUND_PREFIX7783088
Ref: 2bcd7783088
Ref: library/pyexpat xml parsers expat errors XML_ERROR_UNDECLARING_PREFIX7783224
Ref: 2bce7783224
Ref: library/pyexpat xml parsers expat errors XML_ERROR_INCOMPLETE_PE7783364
Ref: 2bcf7783364
Ref: library/pyexpat xml parsers expat errors XML_ERROR_XML_DECL7783478
Ref: 2bd07783478
Ref: library/pyexpat xml parsers expat errors XML_ERROR_TEXT_DECL7783584
Ref: 2bd17783584
Ref: library/pyexpat xml parsers expat errors XML_ERROR_PUBLICID7783709
Ref: 2bd27783709
Ref: library/pyexpat xml parsers expat errors XML_ERROR_SUSPENDED7783819
Ref: 2bd37783819
Ref: library/pyexpat xml parsers expat errors XML_ERROR_NOT_SUSPENDED7784014
Ref: 2bd47784014
Ref: library/pyexpat xml parsers expat errors XML_ERROR_ABORTED7784149
Ref: 2bd57784149
Ref: library/pyexpat xml parsers expat errors XML_ERROR_FINISHED7784265
Ref: 2bd67784265
Ref: library/pyexpat xml parsers expat errors XML_ERROR_SUSPEND_PE7784483
Ref: 2bd77784483
Node: 互联网协议和支持7784555
Ref: library/internet doc7784692
Ref: 2bd87784692
Ref: library/internet internet7784692
Ref: 2bd97784692
Ref: library/internet internet-protocols-and-support7784692
Ref: 2bda7784692
Node: webbrowser --- 方便的Web浏览器控制器7787191
Ref: library/webbrowser doc7787338
Ref: 2bdb7787338
Ref: library/webbrowser module-webbrowser7787338
Ref: 12a7787338
Ref: library/webbrowser webbrowser-convenient-web-browser-controller7787338
Ref: 2bdc7787338
Ref: library/webbrowser webbrowser Error7789059
Ref: 2bde7789059
Ref: library/webbrowser webbrowser open7789167
Ref: 2bdd7789167
Ref: library/webbrowser webbrowser open_new7789969
Ref: 2bdf7789969
Ref: library/webbrowser webbrowser open_new_tab7790138
Ref: 2be07790138
Ref: library/webbrowser webbrowser get7790316
Ref: 2be17790316
Ref: library/webbrowser webbrowser register7790529
Ref: 2be27790529
Ref: webbrowser --- 方便的Web浏览器控制器-Footnote-17796928
Ref: webbrowser --- 方便的Web浏览器控制器-Footnote-27796997
Node: 浏览器控制器对象7797119
Ref: library/webbrowser browser-controller-objects7797225
Ref: 2be37797225
Ref: library/webbrowser browser-controllers7797225
Ref: 2be47797225
Ref: library/webbrowser webbrowser controller open7797360
Ref: 2be57797360
Ref: library/webbrowser webbrowser controller open_new7797634
Ref: 2be67797634
Ref: library/webbrowser webbrowser controller open_new_tab7797854
Ref: 2be77797854
Node: cgi --- 通用网关接口支持7798061
Ref: library/cgi doc7798262
Ref: 2be87798262
Ref: library/cgi cgi-common-gateway-interface-support7798262
Ref: 2be97798262
Ref: library/cgi module-cgi7798262
Ref: 167798262
Ref: cgi --- 通用网关接口支持-Footnote-17798862
Node: 概述<11>7798924
Ref: library/cgi introduction7799030
Ref: 2bea7799030
Ref: library/cgi cgi-intro7799061
Ref: 2beb7799061
Node: 使用cgi模块。7800655
Ref: library/cgi id17800791
Ref: 2bec7800791
Ref: library/cgi using-the-cgi-module7800791
Ref: 2bed7800791
Node: 更高层级的接口7806322
Ref: library/cgi higher-level-interface7806457
Ref: 2bef7806457
Ref: library/cgi cgi FieldStorage getfirst7808568
Ref: 2bf07808568
Ref: library/cgi cgi FieldStorage getlist7809068
Ref: 2bee7809068
Ref: 更高层级的接口-Footnote-17809653
Node: 函数<8>7809911
Ref: library/cgi functions7810049
Ref: 2bf17810049
Ref: library/cgi functions-in-cgi-module7810049
Ref: 2bf27810049
Ref: library/cgi cgi parse7810223
Ref: 2ee7810223
Ref: library/cgi cgi parse_multipart7810648
Ref: 2ef7810648
Ref: library/cgi cgi parse_header7811609
Ref: 2bf37811609
Ref: library/cgi cgi test7811758
Ref: 2bf47811758
Ref: library/cgi cgi print_environ7811941
Ref: 2bf57811941
Ref: library/cgi cgi print_form7812019
Ref: 2bf67812019
Ref: library/cgi cgi print_directory7812083
Ref: 2bf77812083
Ref: library/cgi cgi print_environ_usage7812163
Ref: 2bf87812163
Node: Caring about security7812277
Ref: library/cgi caring-about-security7812437
Ref: 2bf97812437
Ref: library/cgi cgi-security7812437
Ref: 2bfa7812437
Node: Installing your CGI script on a Unix system7813222
Ref: library/cgi installing-your-cgi-script-on-a-unix-system7813396
Ref: 2bfb7813396
Node: Testing your CGI script7815410
Ref: library/cgi testing-your-cgi-script7815584
Ref: 2bfc7815584
Node: Debugging CGI scripts7816198
Ref: library/cgi debugging-cgi-scripts7816358
Ref: 2bfd7816358
Node: Common problems and solutions7819491
Ref: library/cgi common-problems-and-solutions7819619
Ref: 2bfe7819619
Node: cgitb --- 用于 CGI 脚本的回溯管理器7820974
Ref: library/cgitb doc7821185
Ref: 2bff7821185
Ref: library/cgitb cgitb-traceback-manager-for-cgi-scripts7821185
Ref: 2c007821185
Ref: library/cgitb module-cgitb7821185
Ref: 177821185
Ref: library/cgitb cgitb enable7822274
Ref: 2c017822274
Ref: library/cgitb cgitb text7823055
Ref: 2c027823055
Ref: library/cgitb cgitb html7823418
Ref: 2c037823418
Ref: library/cgitb cgitb handler7823781
Ref: 2c047823781
Ref: cgitb --- 用于 CGI 脚本的回溯管理器-Footnote-17824339
Node: wsgiref --- WSGI Utilities and Reference Implementation7824403
Ref: library/wsgiref doc7824609
Ref: 2c057824609
Ref: library/wsgiref module-wsgiref7824609
Ref: 12d7824609
Ref: library/wsgiref wsgiref-wsgi-utilities-and-reference-implementation7824609
Ref: 2c067824609
Ref: wsgiref --- WSGI Utilities and Reference Implementation-Footnote-17826426
Ref: wsgiref --- WSGI Utilities and Reference Implementation-Footnote-27826475
Node: wsgiref util -- WSGI environment utilities7826512
Ref: library/wsgiref module-wsgiref util7826700
Ref: 1317826700
Ref: library/wsgiref wsgiref-util-wsgi-environment-utilities7826700
Ref: 2c077826700
Ref: library/wsgiref wsgiref util guess_scheme7827157
Ref: 2c087827157
Ref: library/wsgiref wsgiref util request_uri7827779
Ref: 2c097827779
Ref: library/wsgiref wsgiref util application_uri7828099
Ref: 2c0a7828099
Ref: library/wsgiref wsgiref util shift_path_info7828363
Ref: 2c0b7828363
Ref: library/wsgiref wsgiref util setup_testing_defaults7830021
Ref: 2c0c7830021
Ref: library/wsgiref wsgiref util is_hop_by_hop7831704
Ref: 2c0d7831704
Ref: library/wsgiref wsgiref util FileWrapper7831871
Ref: 27e7831871
Ref: wsgiref util -- WSGI environment utilities-Footnote-17833126
Ref: wsgiref util -- WSGI environment utilities-Footnote-27833175
Ref: wsgiref util -- WSGI environment utilities-Footnote-37833224
Ref: wsgiref util -- WSGI environment utilities-Footnote-47833273
Ref: wsgiref util -- WSGI environment utilities-Footnote-57833322
Node: wsgiref headers -- WSGI response header tools7833371
Ref: library/wsgiref module-wsgiref headers7833618
Ref: 12f7833618
Ref: library/wsgiref wsgiref-headers-wsgi-response-header-tools7833618
Ref: 2c0e7833618
Ref: library/wsgiref wsgiref headers Headers7833880
Ref: 7987833880
Ref: library/wsgiref wsgiref headers Headers get_all7836143
Ref: 2c0f7836143
Ref: library/wsgiref wsgiref headers Headers add_header7836580
Ref: 2c107836580
Ref: wsgiref headers -- WSGI response header tools-Footnote-17837712
Node: wsgiref simple_server -- a simple WSGI HTTP server7837761
Ref: library/wsgiref module-wsgiref simple_server7838011
Ref: 1307838011
Ref: library/wsgiref wsgiref-simple-server-a-simple-wsgi-http-server7838011
Ref: 2c117838011
Ref: library/wsgiref wsgiref simple_server make_server7838605
Ref: 2c127838605
Ref: library/wsgiref wsgiref simple_server demo_app7839444
Ref: 2c137839444
Ref: library/wsgiref wsgiref simple_server WSGIServer7839879
Ref: 2c147839879
Ref: library/wsgiref wsgiref simple_server WSGIServer set_app7840630
Ref: 2c167840630
Ref: library/wsgiref wsgiref simple_server WSGIServer get_app7840775
Ref: 2c177840775
Ref: library/wsgiref wsgiref simple_server WSGIRequestHandler7841118
Ref: 2c187841118
Ref: library/wsgiref wsgiref simple_server WSGIRequestHandler get_environ7841732
Ref: 2c197841732
Ref: library/wsgiref wsgiref simple_server WSGIRequestHandler get_stderr7842238
Ref: 2c1a7842238
Ref: library/wsgiref wsgiref simple_server WSGIRequestHandler handle7842421
Ref: 2c1b7842421
Ref: wsgiref simple_server -- a simple WSGI HTTP server-Footnote-17842692
Ref: wsgiref simple_server -- a simple WSGI HTTP server-Footnote-27842741
Node: wsgiref validate --- WSGI conformance checker7842790
Ref: library/wsgiref module-wsgiref validate7843042
Ref: 1327843042
Ref: library/wsgiref wsgiref-validate-wsgi-conformance-checker7843042
Ref: 2c1c7843042
Ref: library/wsgiref wsgiref validate validator7843945
Ref: 2c1d7843945
Ref: wsgiref validate --- WSGI conformance checker-Footnote-17846163
Ref: wsgiref validate --- WSGI conformance checker-Footnote-27846212
Ref: wsgiref validate --- WSGI conformance checker-Footnote-37846261
Node: wsgiref handlers -- server/gateway base classes7846310
Ref: library/wsgiref module-wsgiref handlers7846522
Ref: 12e7846522
Ref: library/wsgiref wsgiref-handlers-server-gateway-base-classes7846522
Ref: 2c1e7846522
Ref: library/wsgiref wsgiref handlers CGIHandler7846913
Ref: 2c1f7846913
Ref: library/wsgiref wsgiref handlers IISCGIHandler7847560
Ref: 2c217847560
Ref: library/wsgiref wsgiref handlers BaseCGIHandler7848931
Ref: 2c207848931
Ref: library/wsgiref wsgiref handlers SimpleHandler7849792
Ref: 2c227849792
Ref: library/wsgiref wsgiref handlers BaseHandler7850706
Ref: fdc7850706
Ref: library/wsgiref wsgiref handlers BaseHandler run7851062
Ref: 2c237851062
Ref: library/wsgiref wsgiref handlers BaseHandler _write7851400
Ref: 2c247851400
Ref: library/wsgiref wsgiref handlers BaseHandler _flush7851745
Ref: 2c257851745
Ref: library/wsgiref wsgiref handlers BaseHandler get_stdin7851954
Ref: 2c267851954
Ref: library/wsgiref wsgiref handlers BaseHandler get_stderr7852119
Ref: 2c277852119
Ref: library/wsgiref wsgiref handlers BaseHandler add_cgi_vars7852287
Ref: 2c287852287
Ref: library/wsgiref wsgiref handlers BaseHandler wsgi_multithread7852833
Ref: 2c297852833
Ref: library/wsgiref wsgiref handlers BaseHandler wsgi_multiprocess7853120
Ref: 2c2a7853120
Ref: library/wsgiref wsgiref handlers BaseHandler wsgi_run_once7853409
Ref: 2c2b7853409
Ref: library/wsgiref wsgiref handlers BaseHandler os_environ7853648
Ref: 2c2c7853648
Ref: library/wsgiref wsgiref handlers BaseHandler server_software7854151
Ref: 2c2d7854151
Ref: library/wsgiref wsgiref handlers BaseHandler get_scheme7854727
Ref: 2c2f7854727
Ref: library/wsgiref wsgiref handlers BaseHandler setup_environ7855080
Ref: 2c307855080
Ref: library/wsgiref wsgiref handlers BaseHandler log_exception7855740
Ref: 2c327855740
Ref: library/wsgiref wsgiref handlers BaseHandler traceback_limit7856240
Ref: 2c337856240
Ref: library/wsgiref wsgiref handlers BaseHandler error_output7856459
Ref: 2c347856459
Ref: library/wsgiref wsgiref handlers BaseHandler error_status7857527
Ref: 2c357857527
Ref: library/wsgiref wsgiref handlers BaseHandler error_headers7857729
Ref: 2c367857729
Ref: library/wsgiref wsgiref handlers BaseHandler error_body7858018
Ref: 2c377858018
Ref: library/wsgiref wsgiref handlers BaseHandler wsgi_file_wrapper7858353
Ref: 2c317858353
Ref: library/wsgiref wsgiref handlers BaseHandler sendfile7858558
Ref: 2c387858558
Ref: library/wsgiref wsgiref handlers BaseHandler origin_server7859134
Ref: 2c2e7859134
Ref: library/wsgiref wsgiref handlers BaseHandler http_version7859657
Ref: 2c397859657
Ref: library/wsgiref wsgiref handlers read_environ7859876
Ref: b3e7859876
Ref: wsgiref handlers -- server/gateway base classes-Footnote-17860782
Ref: wsgiref handlers -- server/gateway base classes-Footnote-27860831
Ref: wsgiref handlers -- server/gateway base classes-Footnote-37860880
Ref: wsgiref handlers -- server/gateway base classes-Footnote-47860929
Ref: wsgiref handlers -- server/gateway base classes-Footnote-57860978
Node: 例子<20>7861027
Ref: library/wsgiref examples7861185
Ref: 2c3a7861185
Node: urllib --- URL 处理模块7863747
Ref: library/urllib doc7863959
Ref: 2c3b7863959
Ref: library/urllib module-urllib7863959
Ref: 11e7863959
Ref: library/urllib urllib-url-handling-modules7863959
Ref: 2c3c7863959
Ref: urllib --- URL 处理模块-Footnote-17864489
Node: urllib request --- 用于打开 URL 的可扩展库7864552
Ref: library/urllib request doc7864758
Ref: 2c3d7864758
Ref: library/urllib request module-urllib request7864758
Ref: 1217864758
Ref: library/urllib request urllib-request-extensible-library-for-opening-urls7864758
Ref: 2c3e7864758
Ref: library/urllib request urllib request urlopen7865323
Ref: 7957865323
Ref: library/urllib request urllib request install_opener7869387
Ref: 2c457869387
Ref: library/urllib request urllib request build_opener7869818
Ref: 2c467869818
Ref: library/urllib request urllib request pathname2url7870881
Ref: 2c4e7870881
Ref: library/urllib request urllib request url2pathname7871118
Ref: 2c4f7871118
Ref: library/urllib request urllib request getproxies7871347
Ref: 2c507871347
Ref: library/urllib request urllib request Request7872335
Ref: 8fe7872335
Ref: library/urllib request urllib request OpenerDirector7876347
Ref: 2c437876347
Ref: library/urllib request urllib request BaseHandler7876544
Ref: 2c477876544
Ref: library/urllib request urllib request HTTPDefaultErrorHandler7876663
Ref: 2c497876663
Ref: library/urllib request urllib request HTTPRedirectHandler7876827
Ref: 2c4a7876827
Ref: library/urllib request urllib request HTTPCookieProcessor7876915
Ref: 2c527876915
Ref: library/urllib request urllib request ProxyHandler7877025
Ref: f8b7877025
Ref: library/urllib request urllib request HTTPPasswordMgr7877960
Ref: 2c537877960
Ref: library/urllib request urllib request HTTPPasswordMgrWithDefaultRealm7878072
Ref: 2c547878072
Ref: library/urllib request urllib request HTTPPasswordMgrWithPriorAuth7878298
Ref: 7937878298
Ref: library/urllib request urllib request AbstractBasicAuthHandler7878636
Ref: ea27878636
Ref: library/urllib request urllib request HTTPBasicAuthHandler7879839
Ref: 2c577879839
Ref: library/urllib request urllib request ProxyBasicAuthHandler7880224
Ref: 2c587880224
Ref: library/urllib request urllib request AbstractDigestAuthHandler7880505
Ref: f377880505
Ref: library/urllib request urllib request HTTPDigestAuthHandler7880846
Ref: 2c597880846
Ref: library/urllib request urllib request ProxyDigestAuthHandler7881598
Ref: 2c5a7881598
Ref: library/urllib request urllib request HTTPHandler7881880
Ref: 2c487881880
Ref: library/urllib request urllib request HTTPSHandler7881964
Ref: bb07881964
Ref: library/urllib request urllib request FileHandler7882285
Ref: 2c4c7882285
Ref: library/urllib request urllib request DataHandler7882350
Ref: 8fd7882350
Ref: library/urllib request urllib request FTPHandler7882437
Ref: 2c4b7882437
Ref: library/urllib request urllib request CacheFTPHandler7882498
Ref: 2c5b7882498
Ref: library/urllib request urllib request UnknownHandler7882637
Ref: 2c447882637
Ref: library/urllib request urllib request HTTPErrorProcessor7882728
Ref: 2c4d7882728
Ref: urllib request --- 用于打开 URL 的可扩展库-Footnote-17883584
Ref: urllib request --- 用于打开 URL 的可扩展库-Footnote-27883657
Ref: urllib request --- 用于打开 URL 的可扩展库-Footnote-37883708
Ref: urllib request --- 用于打开 URL 的可扩展库-Footnote-47883745
Ref: urllib request --- 用于打开 URL 的可扩展库-Footnote-57883794
Ref: urllib request --- 用于打开 URL 的可扩展库-Footnote-67883843
Node: Request 对象7883892
Ref: library/urllib request id17884024
Ref: 2c5c7884024
Ref: library/urllib request request-objects7884024
Ref: 2c5d7884024
Ref: library/urllib request urllib request Request full_url7884282
Ref: 9007884282
Ref: library/urllib request urllib request Request type7884537
Ref: 2c5e7884537
Ref: library/urllib request urllib request Request host7884583
Ref: 2c5f7884583
Ref: library/urllib request urllib request Request origin_req_host7884701
Ref: 2c607884701
Ref: library/urllib request urllib request Request selector7884784
Ref: 2c617884784
Ref: library/urllib request urllib request Request data7884925
Ref: 9017884925
Ref: library/urllib request urllib request Request unverifiable7885168
Ref: 2c627885168
Ref: library/urllib request urllib request Request method7885282
Ref: 8ff7885282
Ref: library/urllib request urllib request Request get_method7885853
Ref: ac97885853
Ref: library/urllib request urllib request Request add_header7886254
Ref: 2c517886254
Ref: library/urllib request urllib request Request add_unredirected_header7886763
Ref: 2c637886763
Ref: library/urllib request urllib request Request has_header7886883
Ref: 2c647886883
Ref: library/urllib request urllib request Request remove_header7887039
Ref: 9037887039
Ref: library/urllib request urllib request Request get_full_url7887231
Ref: 2c657887231
Ref: library/urllib request urllib request Request set_proxy7887376
Ref: 2c667887376
Ref: library/urllib request urllib request Request get_header7887597
Ref: 2c677887597
Ref: library/urllib request urllib request Request header_items7887751
Ref: 2c687887751
Ref: Request 对象-Footnote-17888084
Node: OpenerDirector 对象7888133
Ref: library/urllib request opener-director-objects7888292
Ref: 2c697888292
Ref: library/urllib request openerdirector-objects7888292
Ref: 2c6a7888292
Ref: library/urllib request urllib request OpenerDirector add_handler7888407
Ref: 2c6b7888407
Ref: library/urllib request urllib request OpenerDirector open7889889
Ref: 9027889889
Ref: library/urllib request urllib request OpenerDirector error7890483
Ref: 2c707890483
Node: BaseHandler 对象7892008
Ref: library/urllib request base-handler-objects7892179
Ref: 2c717892179
Ref: library/urllib request basehandler-objects7892179
Ref: 2c727892179
Ref: library/urllib request urllib request BaseHandler add_parent7892397
Ref: 2c737892397
Ref: library/urllib request urllib request BaseHandler close7892484
Ref: 2c747892484
Ref: library/urllib request urllib request BaseHandler parent7892849
Ref: 2c757892849
Ref: library/urllib request urllib request BaseHandler default_open7892995
Ref: 2c767892995
Ref: library/urllib request protocol-open7893614
Ref: 2c6c7893614
Ref: library/urllib request urllib request BaseHandler unknown_open7893938
Ref: 2c777893938
Ref: library/urllib request urllib request BaseHandler http_error_default7894324
Ref: 2c787894324
Ref: library/urllib request http-error-nnn7895039
Ref: 2c6d7895039
Ref: library/urllib request protocol-request7895486
Ref: 2c6e7895486
Ref: library/urllib request protocol-response7895863
Ref: 2c6f7895863
Node: HTTPRedirectHandler 对象7896362
Ref: library/urllib request http-redirect-handler7896538
Ref: 2c797896538
Ref: library/urllib request httpredirecthandler-objects7896538
Ref: 2c7a7896538
Ref: library/urllib request urllib request HTTPRedirectHandler redirect_request7896965
Ref: 2c7b7896965
Ref: library/urllib request urllib request HTTPRedirectHandler http_error_3017897992
Ref: 2c7c7897992
Ref: library/urllib request urllib request HTTPRedirectHandler http_error_3027898243
Ref: 2c7d7898243
Ref: library/urllib request urllib request HTTPRedirectHandler http_error_3037898421
Ref: 2c7e7898421
Ref: library/urllib request urllib request HTTPRedirectHandler http_error_3077898603
Ref: 2c7f7898603
Ref: HTTPRedirectHandler 对象-Footnote-17898829
Ref: HTTPRedirectHandler 对象-Footnote-27898878
Node: HTTPCookieProcessor 对象7898927
Ref: library/urllib request http-cookie-processor7899104
Ref: 2c807899104
Ref: library/urllib request httpcookieprocessor-objects7899104
Ref: 2c817899104
Ref: library/urllib request urllib request HTTPCookieProcessor cookiejar7899240
Ref: 2c827899240
Node: ProxyHandler 对象7899351
Ref: library/urllib request proxy-handler7899524
Ref: 2c847899524
Ref: library/urllib request proxyhandler-objects7899524
Ref: 2c857899524
Node: HTTPPasswordMgr 对象7899998
Ref: library/urllib request http-password-mgr7900180
Ref: 2c557900180
Ref: library/urllib request httppasswordmgr-objects7900180
Ref: 2c867900180
Ref: library/urllib request urllib request HTTPPasswordMgr add_password7900357
Ref: 2c877900357
Ref: library/urllib request urllib request HTTPPasswordMgr find_user_password7900656
Ref: 2c887900656
Node: HTTPPasswordMgrWithPriorAuth 对象7901030
Ref: library/urllib request http-password-mgr-with-prior-auth7901224
Ref: 2c567901224
Ref: library/urllib request httppasswordmgrwithpriorauth-objects7901224
Ref: 2c897901224
Ref: library/urllib request urllib request HTTPPasswordMgrWithPriorAuth add_password7901448
Ref: 2c8a7901448
Ref: library/urllib request urllib request HTTPPasswordMgrWithPriorAuth find_user_password7901860
Ref: 2c8b7901860
Ref: library/urllib request urllib request HTTPPasswordMgrWithPriorAuth update_authenticated7902022
Ref: 2c8c7902022
Ref: library/urllib request urllib request HTTPPasswordMgrWithPriorAuth is_authenticated7902207
Ref: 2c8d7902207
Node: AbstractBasicAuthHandler 对象7902353
Ref: library/urllib request abstract-basic-auth-handler7902552
Ref: 2c8e7902552
Ref: library/urllib request abstractbasicauthhandler-objects7902552
Ref: 2c8f7902552
Ref: library/urllib request urllib request AbstractBasicAuthHandler http_error_auth_reqed7902633
Ref: 2c907902633
Node: HTTPBasicAuthHandler 对象7903437
Ref: library/urllib request http-basic-auth-handler7903629
Ref: 2c917903629
Ref: library/urllib request httpbasicauthhandler-objects7903629
Ref: 2c927903629
Ref: library/urllib request urllib request HTTPBasicAuthHandler http_error_4017903704
Ref: 2c937903704
Node: ProxyBasicAuthHandler 对象7903847
Ref: library/urllib request proxy-basic-auth-handler7904040
Ref: 2c947904040
Ref: library/urllib request proxybasicauthhandler-objects7904040
Ref: 2c957904040
Ref: library/urllib request urllib request ProxyBasicAuthHandler http_error_4077904117
Ref: 2c967904117
Node: AbstractDigestAuthHandler 对象7904271
Ref: library/urllib request abstract-digest-auth-handler7904465
Ref: 2c977904465
Ref: library/urllib request abstractdigestauthhandler-objects7904465
Ref: 2c987904465
Ref: library/urllib request urllib request AbstractDigestAuthHandler http_error_auth_reqed7904550
Ref: 2c997904550
Node: HTTPDigestAuthHandler 对象7904884
Ref: library/urllib request http-digest-auth-handler7905079
Ref: 2c9a7905079
Ref: library/urllib request httpdigestauthhandler-objects7905079
Ref: 2c9b7905079
Ref: library/urllib request urllib request HTTPDigestAuthHandler http_error_4017905156
Ref: 2c9c7905156
Node: ProxyDigestAuthHandler 对象7905310
Ref: library/urllib request proxy-digest-auth-handler7905491
Ref: 2c9d7905491
Ref: library/urllib request proxydigestauthhandler-objects7905491
Ref: 2c9e7905491
Ref: library/urllib request urllib request ProxyDigestAuthHandler http_error_4077905570
Ref: 2c9f7905570
Node: HTTPHandler 对象7905725
Ref: library/urllib request http-handler-objects7905897
Ref: 2ca07905897
Ref: library/urllib request httphandler-objects7905897
Ref: 2ca17905897
Ref: library/urllib request urllib request HTTPHandler http_open7905954
Ref: 2ca27905954
Node: HTTPSHandler 对象7906101
Ref: library/urllib request https-handler-objects7906262
Ref: 2ca37906262
Ref: library/urllib request httpshandler-objects7906262
Ref: 2ca47906262
Ref: library/urllib request urllib request HTTPSHandler https_open7906321
Ref: 2ca57906321
Node: FileHandler 对象7906471
Ref: library/urllib request file-handler-objects7906632
Ref: 2ca67906632
Ref: library/urllib request filehandler-objects7906632
Ref: 2ca77906632
Ref: library/urllib request urllib request FileHandler file_open7906689
Ref: 2ca87906689
Node: DataHandler 对象7906959
Ref: library/urllib request data-handler-objects7907118
Ref: 2ca97907118
Ref: library/urllib request datahandler-objects7907118
Ref: 2caa7907118
Ref: library/urllib request urllib request DataHandler data_open7907175
Ref: 2cab7907175
Ref: DataHandler 对象-Footnote-17907686
Node: FTPHandler 对象7907735
Ref: library/urllib request ftp-handler-objects7907898
Ref: 2cac7907898
Ref: library/urllib request ftphandler-objects7907898
Ref: 2cad7907898
Ref: library/urllib request urllib request FTPHandler ftp_open7907953
Ref: 2cae7907953
Node: CacheFTPHandler 对象7908083
Ref: library/urllib request cacheftp-handler-objects7908249
Ref: 2caf7908249
Ref: library/urllib request cacheftphandler-objects7908249
Ref: 2cb07908249
Ref: library/urllib request urllib request CacheFTPHandler setTimeout7908412
Ref: 2cb17908412
Ref: library/urllib request urllib request CacheFTPHandler setMaxConns7908495
Ref: 2cb27908495
Node: UnknownHandler 对象7908591
Ref: library/urllib request unknown-handler-objects7908765
Ref: 2cb37908765
Ref: library/urllib request unknownhandler-objects7908765
Ref: 2cb47908765
Ref: library/urllib request urllib request UnknownHandler unknown_open7908828
Ref: 2cb57908828
Node: HTTPErrorProcessor 对象7908918
Ref: library/urllib request http-error-processor-objects7909080
Ref: 2cb67909080
Ref: library/urllib request httperrorprocessor-objects7909080
Ref: 2cb77909080
Ref: library/urllib request urllib request HTTPErrorProcessor http_response7909151
Ref: 2cb87909151
Ref: library/urllib request urllib request HTTPErrorProcessor https_response7909592
Ref: 2cb97909592
Node: 例子<21>7909751
Ref: library/urllib request examples7909910
Ref: 2cba7909910
Ref: library/urllib request urllib-request-examples7909910
Ref: 2cbb7909910
Ref: library/urllib request urllib-examples7915270
Ref: 2cbd7915270
Node: 已停用的接口7916677
Ref: library/urllib request legacy-interface7916838
Ref: 2cbe7916838
Ref: library/urllib request urllib request urlretrieve7917032
Ref: 2cbf7917032
Ref: library/urllib request urllib request urlcleanup7919546
Ref: 2cc07919546
Ref: library/urllib request urllib request URLopener7919704
Ref: 2c407919704
Ref: library/urllib request urllib request URLopener open7921202
Ref: 2cc27921202
Ref: library/urllib request urllib request URLopener open_unknown7921705
Ref: 2cc37921705
Ref: library/urllib request urllib request URLopener retrieve7921817
Ref: fd87921817
Ref: library/urllib request urllib request URLopener version7923350
Ref: 2cc17923350
Ref: library/urllib request urllib request FancyURLopener7923668
Ref: 2c417923668
Ref: library/urllib request urllib request FancyURLopener prompt_user_passwd7925398
Ref: 2cc47925398
Ref: 已停用的接口-Footnote-17925938
Node: urllib request Restrictions7925987
Ref: library/urllib request urllib-request-restrictions7926129
Ref: 2cc57926129
Node: urllib response --- urllib 使用的 Response 类7928692
Ref: library/urllib request module-urllib response7928900
Ref: 1227928900
Ref: library/urllib request urllib-response-response-classes-used-by-urllib7928900
Ref: 2cc67928900
Node: urllib parse 用于解析 URL7929440
Ref: library/urllib parse doc7929647
Ref: 2cc77929647
Ref: library/urllib parse module-urllib parse7929647
Ref: 1207929647
Ref: library/urllib parse urllib-parse-parse-urls-into-components7929647
Ref: 2cc87929647
Ref: urllib parse 用于解析 URL-Footnote-17930808
Node: URL 解析7930879
Ref: library/urllib parse url-parsing7930987
Ref: 2cc97930987
Ref: library/urllib parse urllib parse urlparse7931140
Ref: 6037931140
Ref: library/urllib parse urllib parse parse_qs7938362
Ref: 2ec7938362
Ref: library/urllib parse urllib parse parse_qsl7940528
Ref: 2ed7940528
Ref: library/urllib parse urllib parse urlunparse7942544
Ref: 2ccb7942544
Ref: library/urllib parse urllib parse urlsplit7942944
Ref: 6027942944
Ref: library/urllib parse urllib parse urlunsplit7947204
Ref: 2ccc7947204
Ref: library/urllib parse urllib parse urljoin7947646
Ref: 7967947646
Ref: library/urllib parse urllib parse urldefrag7948943
Ref: be67948943
Ref: library/urllib parse urllib parse unwrap7950291
Ref: 2ccd7950291
Ref: URL 解析-Footnote-17950637
Ref: URL 解析-Footnote-27950686
Ref: URL 解析-Footnote-37950735
Ref: URL 解析-Footnote-47950784
Ref: URL 解析-Footnote-57950846
Node: 解析ASCII编码字节7950895
Ref: library/urllib parse id17951033
Ref: 2cce7951033
Ref: library/urllib parse parsing-ascii-encoded-bytes7951033
Ref: be87951033
Node: 结构化解析结果7953140
Ref: library/urllib parse structured-parse-results7953279
Ref: 2ccf7953279
Ref: library/urllib parse urlparse-result-object7953279
Ref: 2cca7953279
Ref: library/urllib parse urllib parse urllib parse SplitResult geturl7953682
Ref: 2cd07953682
Ref: library/urllib parse urllib parse DefragResult7954805
Ref: 2cd17954805
Ref: library/urllib parse urllib parse ParseResult7955059
Ref: 2cd37955059
Ref: library/urllib parse urllib parse SplitResult7955328
Ref: 2cd57955328
Ref: library/urllib parse urllib parse DefragResultBytes7955721
Ref: 2cd27955721
Ref: library/urllib parse urllib parse ParseResultBytes7955977
Ref: 2cd47955977
Ref: library/urllib parse urllib parse SplitResultBytes7956272
Ref: 2cd67956272
Node: URL Quoting7956559
Ref: library/urllib parse url-quoting7956666
Ref: 2cd77956666
Ref: library/urllib parse urllib parse quote7957069
Ref: 4157957069
Ref: library/urllib parse urllib parse quote_plus7958418
Ref: be77958418
Ref: library/urllib parse urllib parse quote_from_bytes7958907
Ref: 2cd87958907
Ref: library/urllib parse urllib parse unquote7959198
Ref: ee77959198
Ref: library/urllib parse urllib parse unquote_plus7959825
Ref: 2cd97959825
Ref: library/urllib parse urllib parse unquote_to_bytes7960160
Ref: 2cda7960160
Ref: library/urllib parse urllib parse urlencode7960576
Ref: 7947960576
Ref: URL Quoting-Footnote-17964352
Ref: URL Quoting-Footnote-27964401
Ref: URL Quoting-Footnote-37964450
Ref: URL Quoting-Footnote-47964487
Ref: URL Quoting-Footnote-57964536
Ref: URL Quoting-Footnote-67964585
Ref: URL Quoting-Footnote-77964634
Ref: URL Quoting-Footnote-87964683
Ref: URL Quoting-Footnote-97964732
Node: urllib error --- urllib request 引发的异常类7964781
Ref: library/urllib error doc7964991
Ref: 2cdb7964991
Ref: library/urllib error module-urllib error7964991
Ref: 11f7964991
Ref: library/urllib error urllib-error-exception-classes-raised-by-urllib-request7964991
Ref: 2cdc7964991
Ref: library/urllib error whatwg7964991
Ref: 2cdd7964991
Ref: library/urllib error urllib error URLError7965424
Ref: 2c427965424
Ref: library/urllib error urllib error URLError reason7965595
Ref: 2cde7965595
Ref: library/urllib error urllib error HTTPError7965843
Ref: 9047965843
Ref: library/urllib error urllib error HTTPError code7966174
Ref: 2cdf7966174
Ref: library/urllib error urllib error HTTPError reason7966410
Ref: 2ce17966410
Ref: library/urllib error urllib error HTTPError headers7966504
Ref: 9057966504
Ref: library/urllib error urllib error ContentTooShortError7966642
Ref: 2ce27966642
Ref: urllib error --- urllib request 引发的异常类-Footnote-17966988
Ref: urllib error --- urllib request 引发的异常类-Footnote-27967059
Node: urllib robotparser --- robots txt 语法分析程序7967108
Ref: library/urllib robotparser doc7967309
Ref: 2ce37967309
Ref: library/urllib robotparser module-urllib robotparser7967309
Ref: 1237967309
Ref: library/urllib robotparser urllib-robotparser-parser-for-robots-txt7967309
Ref: 2ce47967309
Ref: library/urllib robotparser urllib robotparser RobotFileParser7967845
Ref: 5b67967845
Ref: library/urllib robotparser urllib robotparser RobotFileParser set_url7968030
Ref: 2ce57968030
Ref: library/urllib robotparser urllib robotparser RobotFileParser read7968120
Ref: 2ce67968120
Ref: library/urllib robotparser urllib robotparser RobotFileParser parse7968213
Ref: 10b17968213
Ref: library/urllib robotparser urllib robotparser RobotFileParser can_fetch7968275
Ref: 2ce77968275
Ref: library/urllib robotparser urllib robotparser RobotFileParser mtime7968458
Ref: 2ce87968458
Ref: library/urllib robotparser urllib robotparser RobotFileParser modified7968671
Ref: 2ce97968671
Ref: library/urllib robotparser urllib robotparser RobotFileParser crawl_delay7968791
Ref: 2cea7968791
Ref: library/urllib robotparser urllib robotparser RobotFileParser request_rate7969122
Ref: 2ceb7969122
Ref: library/urllib robotparser urllib robotparser RobotFileParser site_maps7969525
Ref: 10467969525
Ref: urllib robotparser --- robots txt 语法分析程序-Footnote-17970396
Node: http --- HTTP 模块7970474
Ref: library/http doc7970661
Ref: 2cec7970661
Ref: library/http http-http-modules7970661
Ref: 2ced7970661
Ref: library/http module-http7970661
Ref: 937970661
Ref: library/http http HTTPStatus7971465
Ref: 6eb7971465
Ref: http --- HTTP 模块-Footnote-17972183
Node: HTTP 状态码7972255
Ref: library/http http-status-codes7972326
Ref: 2cee7972326
Ref: library/http id17972326
Ref: 2cef7972326
Ref: HTTP 状态码-Footnote-17985255
Ref: HTTP 状态码-Footnote-27985339
Ref: HTTP 状态码-Footnote-37985388
Ref: HTTP 状态码-Footnote-47985437
Ref: HTTP 状态码-Footnote-57985486
Ref: HTTP 状态码-Footnote-67985535
Ref: HTTP 状态码-Footnote-77985584
Ref: HTTP 状态码-Footnote-87985633
Ref: HTTP 状态码-Footnote-97985682
Node: http client --- HTTP 协议客户端7985731
Ref: library/http client doc7985896
Ref: 2cf07985896
Ref: library/http client http-client-http-protocol-client7985896
Ref: 2cf17985896
Ref: library/http client module-http client7985896
Ref: 947985896
Ref: library/http client http client HTTPConnection7986522
Ref: 39a7986522
Ref: library/http client http client HTTPSConnection7987990
Ref: 39b7987990
Ref: library/http client http client HTTPResponse7989678
Ref: a197989678
Ref: library/http client http client parse_headers7989998
Ref: 10507989998
Ref: library/http client http client HTTPException7990919
Ref: 2cf47990919
Ref: library/http client http client NotConnected7991049
Ref: 2cf57991049
Ref: library/http client http client InvalidURL7991139
Ref: 2cf67991139
Ref: library/http client http client UnknownProtocol7991302
Ref: 2cf77991302
Ref: library/http client http client UnknownTransferEncoding7991395
Ref: 2cf87991395
Ref: library/http client http client UnimplementedFileMode7991496
Ref: 2cf97991496
Ref: library/http client http client IncompleteRead7991595
Ref: 2cfa7991595
Ref: library/http client http client ImproperConnectionState7991687
Ref: 2cfb7991687
Ref: library/http client http client CannotSendRequest7991788
Ref: 2cfc7991788
Ref: library/http client http client CannotSendHeader7991893
Ref: 2cfd7991893
Ref: library/http client http client ResponseNotReady7991997
Ref: 2cfe7991997
Ref: library/http client http client BadStatusLine7992101
Ref: 2cff7992101
Ref: library/http client http client LineTooLong7992280
Ref: 2d007992280
Ref: library/http client http client RemoteDisconnected7992451
Ref: 6ee7992451
Ref: library/http client http client HTTP_PORT7992881
Ref: 2d017992881
Ref: library/http client http client HTTPS_PORT7992973
Ref: 2d027992973
Ref: library/http client http client responses7993068
Ref: 2d037993068
Ref: http client --- HTTP 协议客户端-Footnote-17993508
Ref: http client --- HTTP 协议客户端-Footnote-27993578
Ref: http client --- HTTP 协议客户端-Footnote-37993629
Node: HTTPConnection 对象7993678
Ref: library/http client httpconnection-objects7993800
Ref: 2d047993800
Ref: library/http client id17993800
Ref: 2d057993800
Ref: library/http client http client HTTPConnection request7993919
Ref: 5587993919
Ref: library/http client http client HTTPConnection getresponse7996572
Ref: 6ed7996572
Ref: library/http client http client HTTPConnection set_debuglevel7997037
Ref: 2d067997037
Ref: library/http client http client HTTPConnection set_tunnel7997398
Ref: bb57997398
Ref: library/http client http client HTTPConnection connect7998293
Ref: 2d077998293
Ref: library/http client http client HTTPConnection close7998499
Ref: 2d087998499
Ref: library/http client http client HTTPConnection blocksize7998573
Ref: 2d097998573
Ref: library/http client http client HTTPConnection putrequest7998833
Ref: 2d0a7998833
Ref: library/http client http client HTTPConnection putheader7999382
Ref: 2d0b7999382
Ref: library/http client http client HTTPConnection endheaders7999717
Ref: 5597999717
Ref: library/http client http client HTTPConnection send8001086
Ref: 2d0c8001086
Ref: HTTPConnection 对象-Footnote-18001344
Ref: HTTPConnection 对象-Footnote-28001392
Node: HTTPResponse 对象8001441
Ref: library/http client httpresponse-objects8001582
Ref: 2d0d8001582
Ref: library/http client id28001582
Ref: 2d0e8001582
Ref: library/http client http client HTTPResponse read8001987
Ref: 2d0f8001987
Ref: library/http client http client HTTPResponse readinto8002100
Ref: a1a8002100
Ref: library/http client http client HTTPResponse getheader8002285
Ref: 2d108002285
Ref: library/http client http client HTTPResponse getheaders8002676
Ref: 2d118002676
Ref: library/http client http client HTTPResponse fileno8002763
Ref: 2d128002763
Ref: library/http client http client HTTPResponse msg8002855
Ref: 2cf28002855
Ref: library/http client http client HTTPResponse version8003057
Ref: 2d138003057
Ref: library/http client http client HTTPResponse status8003175
Ref: 2d148003175
Ref: library/http client http client HTTPResponse reason8003248
Ref: 2c3f8003248
Ref: library/http client http client HTTPResponse debuglevel8003321
Ref: 2d158003321
Ref: library/http client http client HTTPResponse closed8003513
Ref: 2d168003513
Node: 例子<22>8003591
Ref: library/http client examples8003730
Ref: 2d178003730
Node: HTTPMessage Objects8006640
Ref: library/http client httpmessage-objects8006751
Ref: 2d188006751
Ref: library/http client id38006751
Ref: 2d198006751
Node: ftplib --- FTP 协议客户端8006966
Ref: library/ftplib doc8007142
Ref: 2d1a8007142
Ref: library/ftplib ftplib-ftp-protocol-client8007142
Ref: 2d1b8007142
Ref: library/ftplib module-ftplib8007142
Ref: 848007142
Ref: library/ftplib ftplib FTP8008604
Ref: 2f18008604
Ref: library/ftplib ftplib FTP_TLS8010061
Ref: a0b8010061
Ref: library/ftplib ftplib error_reply8012216
Ref: 2d1d8012216
Ref: library/ftplib ftplib error_temp8012312
Ref: 2d1e8012312
Ref: library/ftplib ftplib error_perm8012463
Ref: 2d1f8012463
Ref: library/ftplib ftplib error_proto8012617
Ref: 2d208012617
Ref: library/ftplib ftplib all_errors8012773
Ref: 2d218012773
Ref: ftplib --- FTP 协议客户端-Footnote-18013356
Ref: ftplib --- FTP 协议客户端-Footnote-28013421
Ref: ftplib --- FTP 协议客户端-Footnote-38013469
Node: FTP 对象8013518
Ref: library/ftplib ftp-objects8013618
Ref: 2d228013618
Ref: library/ftplib id18013618
Ref: 2d238013618
Ref: library/ftplib ftplib FTP set_debuglevel8013947
Ref: 2d248013947
Ref: library/ftplib ftplib FTP connect8014330
Ref: 2d258014330
Ref: library/ftplib ftplib FTP getwelcome8015188
Ref: 2d268015188
Ref: library/ftplib ftplib FTP login8015376
Ref: 2d278015376
Ref: library/ftplib ftplib FTP abort8016025
Ref: 2d288016025
Ref: library/ftplib ftplib FTP sendcmd8016142
Ref: 2d298016142
Ref: library/ftplib ftplib FTP voidcmd8016371
Ref: 2d2a8016371
Ref: library/ftplib ftplib FTP retrbinary8016754
Ref: 2d2b8016754
Ref: library/ftplib ftplib FTP retrlines8017373
Ref: 2d2d8017373
Ref: library/ftplib ftplib FTP set_pasv8017995
Ref: 2d2e8017995
Ref: library/ftplib ftplib FTP storbinary8018157
Ref: ca78018157
Ref: library/ftplib ftplib FTP storlines8018870
Ref: 2d2f8018870
Ref: library/ftplib ftplib FTP transfercmd8019335
Ref: 2d2c8019335
Ref: library/ftplib ftplib FTP ntransfercmd8020596
Ref: 2d308020596
Ref: library/ftplib ftplib FTP mlsd8020916
Ref: a0d8020916
Ref: library/ftplib ftplib FTP nlst8021530
Ref: a0e8021530
Ref: library/ftplib ftplib FTP dir8021940
Ref: a0f8021940
Ref: library/ftplib ftplib FTP rename8022576
Ref: 2d318022576
Ref: library/ftplib ftplib FTP delete8022686
Ref: 2d328022686
Ref: library/ftplib ftplib FTP cwd8022957
Ref: 2d338022957
Ref: library/ftplib ftplib FTP mkd8023032
Ref: 2d348023032
Ref: library/ftplib ftplib FTP pwd8023110
Ref: 2d358023110
Ref: library/ftplib ftplib FTP rmd8023183
Ref: 2d368023183
Ref: library/ftplib ftplib FTP size8023271
Ref: 2d378023271
Ref: library/ftplib ftplib FTP quit8023543
Ref: 2d388023543
Ref: library/ftplib ftplib FTP close8023923
Ref: 2d398023923
Ref: FTP 对象-Footnote-18024348
Ref: FTP 对象-Footnote-28024396
Node: FTP_TLS 对象8024445
Ref: library/ftplib ftp-tls-objects8024545
Ref: 2d3a8024545
Ref: library/ftplib ftplib FTP_TLS ssl_version8024680
Ref: 2d3b8024680
Ref: library/ftplib ftplib FTP_TLS auth8024794
Ref: 2d3c8024794
Ref: library/ftplib ftplib FTP_TLS ccc8025157
Ref: a0c8025157
Ref: library/ftplib ftplib FTP_TLS prot_p8025370
Ref: 2d1c8025370
Ref: library/ftplib ftplib FTP_TLS prot_c8025435
Ref: 2d3d8025435
Node: poplib --- POP3 协议客户端8025500
Ref: library/poplib doc8025673
Ref: 2d3e8025673
Ref: library/poplib module-poplib8025673
Ref: d18025673
Ref: library/poplib poplib-pop3-protocol-client8025673
Ref: 2d3f8025673
Ref: library/poplib poplib POP38026679
Ref: 2d408026679
Ref: library/poplib poplib POP3_SSL8027273
Ref: bc98027273
Ref: library/poplib poplib error_proto8028908
Ref: b1f8028908
Ref: poplib --- POP3 协议客户端-Footnote-18029534
Ref: poplib --- POP3 协议客户端-Footnote-28029599
Ref: poplib --- POP3 协议客户端-Footnote-38029648
Ref: poplib --- POP3 协议客户端-Footnote-48029697
Ref: poplib --- POP3 协议客户端-Footnote-58029746
Node: POP3 对象8029808
Ref: library/poplib id18029907
Ref: 2d418029907
Ref: library/poplib pop3-objects8029907
Ref: 2d428029907
Ref: library/poplib poplib POP3 set_debuglevel8030117
Ref: 2d438030117
Ref: library/poplib poplib POP3 getwelcome8030501
Ref: 2d448030501
Ref: library/poplib poplib POP3 capa8030591
Ref: 89b8030591
Ref: library/poplib poplib POP3 user8030789
Ref: 2d458030789
Ref: library/poplib poplib POP3 pass_8030899
Ref: 2d468030899
Ref: library/poplib poplib POP3 apop8031079
Ref: 2d478031079
Ref: library/poplib poplib POP3 rpop8031187
Ref: 2d488031187
Ref: library/poplib poplib POP3 stat8031304
Ref: 2d498031304
Ref: library/poplib poplib POP3 list8031440
Ref: 2d4a8031440
Ref: library/poplib poplib POP3 retr8031637
Ref: 2d4b8031637
Ref: library/poplib poplib POP3 dele8031813
Ref: 2d4c8031813
Ref: library/poplib poplib POP3 rset8032074
Ref: 2d4d8032074
Ref: library/poplib poplib POP3 noop8032149
Ref: 2d4e8032149
Ref: library/poplib poplib POP3 quit8032233
Ref: b1e8032233
Ref: library/poplib poplib POP3 top8032326
Ref: 2d4f8032326
Ref: library/poplib poplib POP3 uidl8032830
Ref: 2d508032830
Ref: library/poplib poplib POP3 utf88033130
Ref: 73b8033130
Ref: library/poplib poplib POP3 stls8033339
Ref: 89c8033339
Ref: POP3 对象-Footnote-18034079
Ref: POP3 对象-Footnote-28034128
Ref: POP3 对象-Footnote-38034177
Node: POP3 示例8034226
Ref: library/poplib id28034325
Ref: 2d518034325
Ref: library/poplib pop3-example8034325
Ref: 2d528034325
Node: imaplib --- IMAP4 协议客户端8034810
Ref: library/imaplib doc8034985
Ref: 2d538034985
Ref: library/imaplib imaplib-imap4-protocol-client8034985
Ref: 2d548034985
Ref: library/imaplib module-imaplib8034985
Ref: 988034985
Ref: library/imaplib imaplib IMAP48035595
Ref: 6148035595
Ref: library/imaplib imaplib IMAP4 error8036511
Ref: 2d568036511
Ref: library/imaplib imaplib IMAP4 abort8036651
Ref: 2d578036651
Ref: library/imaplib imaplib IMAP4 readonly8036910
Ref: 2d588036910
Ref: library/imaplib imaplib IMAP4_SSL8037264
Ref: a1f8037264
Ref: library/imaplib imaplib IMAP4_stream8038959
Ref: 2d558038959
Ref: library/imaplib imaplib Internaldate2tuple8039227
Ref: 2d598039227
Ref: library/imaplib imaplib Int2AP8039475
Ref: 2d5a8039475
Ref: library/imaplib imaplib ParseFlags8039621
Ref: 2d5b8039621
Ref: library/imaplib imaplib Time2Internaldate8039740
Ref: 2d5c8039740
Ref: imaplib --- IMAP4 协议客户端-Footnote-18041051
Ref: imaplib --- IMAP4 协议客户端-Footnote-28041117
Ref: imaplib --- IMAP4 协议客户端-Footnote-38041166
Node: IMAP4 Objects8041215
Ref: library/imaplib id18041320
Ref: 2d5d8041320
Ref: library/imaplib imap4-objects8041320
Ref: 2d5e8041320
Ref: library/imaplib imaplib IMAP4 append8042824
Ref: 2d5f8042824
Ref: library/imaplib imaplib IMAP4 authenticate8042928
Ref: 2d608042928
Ref: library/imaplib imaplib IMAP4 check8043759
Ref: 2d618043759
Ref: library/imaplib imaplib IMAP4 close8043823
Ref: 2d628043823
Ref: library/imaplib imaplib IMAP4 copy8044008
Ref: 2d638044008
Ref: library/imaplib imaplib IMAP4 create8044120
Ref: 2d648044120
Ref: library/imaplib imaplib IMAP4 delete8044198
Ref: 2d658044198
Ref: library/imaplib imaplib IMAP4 deleteacl8044276
Ref: 2d668044276
Ref: library/imaplib imaplib IMAP4 enable8044386
Ref: 6f38044386
Ref: library/imaplib imaplib IMAP4 expunge8044701
Ref: 2d678044701
Ref: library/imaplib imaplib IMAP4 fetch8044949
Ref: 2d688044949
Ref: library/imaplib imaplib IMAP4 getacl8045229
Ref: 2d698045229
Ref: library/imaplib imaplib IMAP4 getannotation8045383
Ref: 2d6a8045383
Ref: library/imaplib imaplib IMAP4 getquota8045584
Ref: 2d6b8045584
Ref: library/imaplib imaplib IMAP4 getquotaroot8045758
Ref: 2d6c8045758
Ref: library/imaplib imaplib IMAP4 list8045946
Ref: 2d6d8045946
Ref: library/imaplib imaplib IMAP4 login8046215
Ref: 2d6e8046215
Ref: library/imaplib imaplib IMAP4 login_cram_md58046348
Ref: 2d6f8046348
Ref: library/imaplib imaplib IMAP4 logout8046608
Ref: 2d708046608
Ref: library/imaplib imaplib IMAP4 lsub8046800
Ref: 2d718046800
Ref: library/imaplib imaplib IMAP4 myrights8047090
Ref: 2d728047090
Ref: library/imaplib imaplib IMAP4 namespace8047209
Ref: 2d738047209
Ref: library/imaplib imaplib IMAP4 noop8047298
Ref: 2d748047298
Ref: library/imaplib imaplib IMAP4 open8047358
Ref: 2d758047358
Ref: library/imaplib imaplib IMAP4 partial8047877
Ref: 2d7a8047877
Ref: library/imaplib imaplib IMAP4 proxyauth8048054
Ref: 2d7b8048054
Ref: library/imaplib imaplib IMAP4 read8048206
Ref: 2d768048206
Ref: library/imaplib imaplib IMAP4 readline8048322
Ref: 2d778048322
Ref: library/imaplib imaplib IMAP4 recent8048434
Ref: 2d7c8048434
Ref: library/imaplib imaplib IMAP4 rename8048589
Ref: 2d7d8048589
Ref: library/imaplib imaplib IMAP4 response8048697
Ref: 2d7e8048697
Ref: library/imaplib imaplib IMAP4 search8048855
Ref: 2d7f8048855
Ref: library/imaplib imaplib IMAP4 select8049529
Ref: 2d808049529
Ref: library/imaplib imaplib IMAP4 send8049824
Ref: 2d788049824
Ref: library/imaplib imaplib IMAP4 setacl8050037
Ref: 2d818050037
Ref: library/imaplib imaplib IMAP4 setannotation8050200
Ref: 2d828050200
Ref: library/imaplib imaplib IMAP4 setquota8050389
Ref: 2d838050389
Ref: library/imaplib imaplib IMAP4 shutdown8050563
Ref: 2d798050563
Ref: library/imaplib imaplib IMAP4 socket8050750
Ref: 2d848050750
Ref: library/imaplib imaplib IMAP4 sort8050836
Ref: 2d858050836
Ref: library/imaplib imaplib IMAP4 starttls8051780
Ref: bb28051780
Ref: library/imaplib imaplib IMAP4 status8052299
Ref: 2d868052299
Ref: library/imaplib imaplib IMAP4 store8052395
Ref: 2d878052395
Ref: library/imaplib imaplib IMAP4 subscribe8053584
Ref: 2d888053584
Ref: library/imaplib imaplib IMAP4 thread8053655
Ref: 2d898053655
Ref: library/imaplib imaplib IMAP4 uid8054782
Ref: 2d8a8054782
Ref: library/imaplib imaplib IMAP4 unsubscribe8055100
Ref: 2d8b8055100
Ref: library/imaplib imaplib IMAP4 xatom8055177
Ref: 2d8c8055177
Ref: library/imaplib imaplib IMAP4 PROTOCOL_VERSION8055381
Ref: 2d8d8055381
Ref: library/imaplib imaplib IMAP4 debug8055513
Ref: 2d8e8055513
Ref: library/imaplib imaplib IMAP4 utf8_enabled8055713
Ref: 6f48055713
Ref: IMAP4 Objects-Footnote-18055986
Ref: IMAP4 Objects-Footnote-28056035
Ref: IMAP4 Objects-Footnote-38056084
Ref: IMAP4 Objects-Footnote-48056133
Ref: IMAP4 Objects-Footnote-58056182
Ref: IMAP4 Objects-Footnote-68056231
Node: IMAP4 Example8056280
Ref: library/imaplib id28056385
Ref: 2d8f8056385
Ref: library/imaplib imap4-example8056385
Ref: 2d908056385
Node: nntplib --- NNTP protocol client8056873
Ref: library/nntplib doc8057047
Ref: 2d918057047
Ref: library/nntplib module-nntplib8057047
Ref: c18057047
Ref: library/nntplib nntplib-nntp-protocol-client8057047
Ref: 2d928057047
Ref: library/nntplib nntplib NNTP8058899
Ref: a348058899
Ref: library/nntplib nntplib NNTP_SSL8060863
Ref: bad8060863
Ref: library/nntplib nntplib NNTPError8062215
Ref: 2d948062215
Ref: library/nntplib nntplib NNTPError response8062458
Ref: 2d958062458
Ref: library/nntplib nntplib NNTPReplyError8062576
Ref: 2d968062576
Ref: library/nntplib nntplib NNTPTemporaryError8062676
Ref: 2d978062676
Ref: library/nntplib nntplib NNTPPermanentError8062801
Ref: 2d938062801
Ref: library/nntplib nntplib NNTPProtocolError8062926
Ref: 2d988062926
Ref: library/nntplib nntplib NNTPDataError8063087
Ref: 2d998063087
Ref: nntplib --- NNTP protocol client-Footnote-18063288
Ref: nntplib --- NNTP protocol client-Footnote-28063354
Ref: nntplib --- NNTP protocol client-Footnote-38063403
Ref: nntplib --- NNTP protocol client-Footnote-48063451
Ref: nntplib --- NNTP protocol client-Footnote-58063500
Node: NNTP Objects8063549
Ref: library/nntplib id18063654
Ref: 2d9a8063654
Ref: library/nntplib nntp-objects8063654
Ref: 2d9b8063654
Node: Attributes8063860
Ref: library/nntplib attributes8063937
Ref: 2d9c8063937
Ref: library/nntplib nntplib NNTP nntp_version8063980
Ref: 2d9d8063980
Ref: library/nntplib nntplib NNTP nntp_implementation8064241
Ref: 2d9e8064241
Ref: Attributes-Footnote-18064473
Node: 方法<3>8064522
Ref: library/nntplib methods8064599
Ref: 2d9f8064599
Ref: library/nntplib nntplib NNTP quit8065481
Ref: 2da08065481
Ref: library/nntplib nntplib NNTP getwelcome8065664
Ref: 2da18065664
Ref: library/nntplib nntplib NNTP getcapabilities8065853
Ref: 2da28065853
Ref: library/nntplib nntplib NNTP login8066312
Ref: 2da38066312
Ref: library/nntplib nntplib NNTP starttls8066928
Ref: bae8066928
Ref: library/nntplib nntplib NNTP newgroups8067720
Ref: 2da48067720
Ref: library/nntplib nntplib NNTP newnews8068387
Ref: 2da58068387
Ref: library/nntplib nntplib NNTP list8068758
Ref: 2da68068758
Ref: library/nntplib nntplib NNTP descriptions8070089
Ref: 2da78070089
Ref: library/nntplib nntplib NNTP description8070687
Ref: 2da88070687
Ref: library/nntplib nntplib NNTP group8071055
Ref: 2da98071055
Ref: library/nntplib nntplib NNTP over8071489
Ref: 2daa8071489
Ref: library/nntplib nntplib NNTP help8073649
Ref: 2dac8073649
Ref: library/nntplib nntplib NNTP stat8073803
Ref: 2dad8073803
Ref: library/nntplib nntplib NNTP next8074472
Ref: 2dae8074472
Ref: library/nntplib nntplib NNTP last8074566
Ref: 2daf8074566
Ref: library/nntplib nntplib NNTP article8074660
Ref: 2db08074660
Ref: library/nntplib nntplib NNTP head8075768
Ref: 2db18075768
Ref: library/nntplib nntplib NNTP body8076002
Ref: 2db28076002
Ref: library/nntplib nntplib NNTP post8076236
Ref: 2db38076236
Ref: library/nntplib nntplib NNTP ihave8076862
Ref: 2db48076862
Ref: library/nntplib nntplib NNTP date8077138
Ref: 2db58077138
Ref: library/nntplib nntplib NNTP slave8077306
Ref: 2db68077306
Ref: library/nntplib nntplib NNTP set_debuglevel8077402
Ref: 2db78077402
Ref: library/nntplib nntplib NNTP xhdr8078038
Ref: 2db88078038
Ref: library/nntplib nntplib NNTP xover8078976
Ref: 2db98078976
Ref: library/nntplib nntplib NNTP xpath8079352
Ref: 2dba8079352
Ref: 方法<3>-Footnote-18079688
Ref: 方法<3>-Footnote-28079737
Ref: 方法<3>-Footnote-38079786
Ref: 方法<3>-Footnote-48079835
Node: 工具函数<2>8079884
Ref: library/nntplib utility-functions8079989
Ref: 2dbb8079989
Ref: library/nntplib nntplib decode_header8080089
Ref: 2dab8080089
Node: smtplib ---SMTP协议客户端8080678
Ref: library/smtplib doc8080843
Ref: 2dbc8080843
Ref: library/smtplib module-smtplib8080843
Ref: ee8080843
Ref: library/smtplib smtplib-smtp-protocol-client8080843
Ref: 2dbd8080843
Ref: library/smtplib smtplib SMTP8081315
Ref: a898081315
Ref: library/smtplib smtplib SMTP_SSL8083530
Ref: a8a8083530
Ref: library/smtplib smtplib LMTP8085041
Ref: a8b8085041
Ref: library/smtplib smtplib SMTPException8085825
Ref: 8c08085825
Ref: library/smtplib smtplib SMTPServerDisconnected8086068
Ref: 2dc08086068
Ref: library/smtplib smtplib SMTPResponseException8086293
Ref: 2dc18086293
Ref: library/smtplib smtplib SMTPSenderRefused8086655
Ref: 2dc28086655
Ref: library/smtplib smtplib SMTPRecipientsRefused8086893
Ref: 2dc38086893
Ref: library/smtplib smtplib SMTPDataError8087163
Ref: 2dc48087163
Ref: library/smtplib smtplib SMTPConnectError8087256
Ref: 2dbe8087256
Ref: library/smtplib smtplib SMTPHeloError8087374
Ref: 2dc58087374
Ref: library/smtplib smtplib SMTPNotSupportedError8087458
Ref: f7d8087458
Ref: library/smtplib smtplib SMTPAuthenticationError8087595
Ref: 2dc68087595
Ref: smtplib ---SMTP协议客户端-Footnote-18088309
Ref: smtplib ---SMTP协议客户端-Footnote-28088375
Ref: smtplib ---SMTP协议客户端-Footnote-38088423
Ref: smtplib ---SMTP协议客户端-Footnote-48088472
Ref: smtplib ---SMTP协议客户端-Footnote-58088521
Ref: smtplib ---SMTP协议客户端-Footnote-68088569
Node: SMTP Objects8088618
Ref: library/smtplib id18088718
Ref: 2dc78088718
Ref: library/smtplib smtp-objects8088718
Ref: 2dc88088718
Ref: library/smtplib smtplib SMTP set_debuglevel8088822
Ref: 74c8088822
Ref: library/smtplib smtplib SMTP docmd8089168
Ref: 2dc98089168
Ref: library/smtplib smtplib SMTP connect8089818
Ref: eeb8089818
Ref: library/smtplib smtplib SMTP helo8090435
Ref: 2dca8090435
Ref: library/smtplib smtplib SMTP ehlo8090895
Ref: 2dcb8090895
Ref: library/smtplib smtplib SMTP ehlo_or_helo_if_needed8091691
Ref: 2dcd8091691
Ref: library/smtplib smtplib SMTP has_extn8092033
Ref: 2dcc8092033
Ref: library/smtplib smtplib SMTP verify8092228
Ref: 2dce8092228
Ref: library/smtplib smtplib SMTP login8092649
Ref: 2dcf8092649
Ref: library/smtplib smtplib SMTP auth8094223
Ref: 74b8094223
Ref: library/smtplib smtplib SMTP starttls8096450
Ref: a8c8096450
Ref: library/smtplib smtplib SMTP sendmail8098104
Ref: 74d8098104
Ref: library/smtplib smtplib SMTP send_message8101559
Ref: 74e8101559
Ref: library/smtplib smtplib SMTP quit8103561
Ref: 2dbf8103561
Ref: SMTP Objects-Footnote-18104024
Ref: SMTP Objects-Footnote-28104072
Ref: SMTP Objects-Footnote-38104121
Ref: SMTP Objects-Footnote-48104170
Ref: SMTP Objects-Footnote-58104218
Ref: SMTP Objects-Footnote-68104266
Node: SMTP Example8104315
Ref: library/smtplib id28104415
Ref: 2dd08104415
Ref: library/smtplib smtp-example8104415
Ref: 2dd18104415
Ref: SMTP Example-Footnote-18105848
Node: smtpd --- SMTP 服务器8105896
Ref: library/smtpd doc8106058
Ref: 2dd28106058
Ref: library/smtpd module-smtpd8106058
Ref: ed8106058
Ref: library/smtpd smtpd-smtp-server8106058
Ref: 2dd38106058
Ref: smtpd --- SMTP 服务器-Footnote-18107050
Ref: smtpd --- SMTP 服务器-Footnote-28107114
Ref: smtpd --- SMTP 服务器-Footnote-38107154
Ref: smtpd --- SMTP 服务器-Footnote-48107203
Ref: smtpd --- SMTP 服务器-Footnote-58107252
Node: SMTPServer 对象8107301
Ref: library/smtpd smtpserver-objects8107410
Ref: 2dd48107410
Ref: library/smtpd smtpd SMTPServer8107465
Ref: 60b8107465
Ref: library/smtpd smtpd SMTPServer process_message8109320
Ref: 60c8109320
Ref: library/smtpd smtpd SMTPServer channel_class8111181
Ref: 2dd58111181
Ref: SMTPServer 对象-Footnote-18111775
Ref: SMTPServer 对象-Footnote-28111824
Ref: SMTPServer 对象-Footnote-38111873
Ref: SMTPServer 对象-Footnote-48111922
Node: DebuggingServer 对象8111971
Ref: library/smtpd debuggingserver-objects8112104
Ref: 2dd68112104
Ref: library/smtpd smtpd DebuggingServer8112169
Ref: 2dd78112169
Node: PureProxy对象8112369
Ref: library/smtpd pureproxy-objects8112504
Ref: 2dd88112504
Ref: library/smtpd smtpd PureProxy8112555
Ref: 2dd98112555
Node: MailmanProxy 对象8112844
Ref: library/smtpd mailmanproxy-objects8112975
Ref: 2dda8112975
Ref: library/smtpd smtpd MailmanProxy8113034
Ref: 2ddb8113034
Node: SMTPChannel 对象8113442
Ref: library/smtpd smtpchannel-objects8113549
Ref: 2ddc8113549
Ref: library/smtpd smtpd SMTPChannel8113606
Ref: 60a8113606
Ref: library/smtpd smtpd SMTPChannel smtp_server8115079
Ref: 2ddd8115079
Ref: library/smtpd smtpd SMTPChannel conn8115180
Ref: 2dde8115180
Ref: library/smtpd smtpd SMTPChannel addr8115264
Ref: 2ddf8115264
Ref: library/smtpd smtpd SMTPChannel received_lines8115396
Ref: 2de08115396
Ref: library/smtpd smtpd SMTPChannel smtp_state8115614
Ref: 2de18115614
Ref: library/smtpd smtpd SMTPChannel seen_greeting8115817
Ref: 2de28115817
Ref: library/smtpd smtpd SMTPChannel mailfrom8115943
Ref: 2de38115943
Ref: library/smtpd smtpd SMTPChannel rcpttos8116082
Ref: 2de48116082
Ref: library/smtpd smtpd SMTPChannel received_data8116230
Ref: 2de58116230
Ref: library/smtpd smtpd SMTPChannel fqdn8116436
Ref: 2de68116436
Ref: library/smtpd smtpd SMTPChannel peer8116577
Ref: 2de78116577
Ref: SMTPChannel 对象-Footnote-18119022
Ref: SMTPChannel 对象-Footnote-28119071
Node: telnetlib -- Telnet 客户端8119120
Ref: library/telnetlib doc8119295
Ref: 2de88119295
Ref: library/telnetlib module-telnetlib8119295
Ref: 1038119295
Ref: library/telnetlib telnetlib-telnet-client8119295
Ref: 2de98119295
Ref: library/telnetlib telnetlib Telnet8120197
Ref: 5a08120197
Ref: telnetlib -- Telnet 客户端-Footnote-18121596
Ref: telnetlib -- Telnet 客户端-Footnote-28121664
Ref: telnetlib -- Telnet 客户端-Footnote-38121712
Node: Telnet 对象8121760
Ref: library/telnetlib id18121861
Ref: 2dec8121861
Ref: library/telnetlib telnet-objects8121861
Ref: 2ded8121861
Ref: library/telnetlib telnetlib Telnet read_until8121959
Ref: 2dee8121959
Ref: library/telnetlib telnetlib Telnet read_all8122271
Ref: 2def8122271
Ref: library/telnetlib telnetlib Telnet read_some8122380
Ref: 2df08122380
Ref: library/telnetlib telnetlib Telnet read_very_eager8122571
Ref: 2df18122571
Ref: library/telnetlib telnetlib Telnet read_eager8122898
Ref: 2df28122898
Ref: library/telnetlib telnetlib Telnet read_lazy8123176
Ref: 2df38123176
Ref: library/telnetlib telnetlib Telnet read_very_lazy8123493
Ref: 2df48123493
Ref: library/telnetlib telnetlib Telnet read_sb_data8123779
Ref: 2df58123779
Ref: library/telnetlib telnetlib Telnet open8124017
Ref: 2dea8124017
Ref: library/telnetlib telnetlib Telnet msg8124535
Ref: 2df68124535
Ref: library/telnetlib telnetlib Telnet set_debuglevel8124747
Ref: 2df78124747
Ref: library/telnetlib telnetlib Telnet close8124820
Ref: 2deb8124820
Ref: library/telnetlib telnetlib Telnet get_socket8124877
Ref: 2df88124877
Ref: library/telnetlib telnetlib Telnet fileno8124957
Ref: 2df98124957
Ref: library/telnetlib telnetlib Telnet write8125051
Ref: 2dfa8125051
Ref: library/telnetlib telnetlib Telnet interact8125512
Ref: 2dfb8125512
Ref: library/telnetlib telnetlib Telnet mt_interact8125613
Ref: 2dfc8125613
Ref: library/telnetlib telnetlib Telnet expect8125694
Ref: 2dfd8125694
Ref: library/telnetlib telnetlib Telnet set_option_negotiation_callback8126684
Ref: 2dfe8126684
Node: Telnet 示例8126997
Ref: library/telnetlib id28127098
Ref: 2dff8127098
Ref: library/telnetlib telnet-example8127098
Ref: 2e008127098
Node: uuid --- UUID objects according to RFC 41228127651
Ref: library/uuid doc8127850
Ref: 2e018127850
Ref: library/uuid module-uuid8127850
Ref: 1258127850
Ref: library/uuid uuid-uuid-objects-according-to-rfc-41228127850
Ref: 2e028127850
Ref: library/uuid uuid SafeUUID8128957
Ref: 2e068128957
Ref: library/uuid uuid SafeUUID safe8129005
Ref: 2e078129005
Ref: library/uuid uuid SafeUUID unsafe8129119
Ref: 2e088129119
Ref: library/uuid uuid SafeUUID unknown8129213
Ref: 2e098129213
Ref: library/uuid uuid UUID8129351
Ref: 2618129351
Ref: library/uuid uuid UUID bytes8131310
Ref: 2e0b8131310
Ref: library/uuid uuid UUID bytes_le8131436
Ref: 2e0c8131436
Ref: library/uuid uuid UUID fields8131585
Ref: 2e0d8131585
Ref: library/uuid uuid UUID hex8133049
Ref: 2e0e8133049
Ref: library/uuid uuid UUID int8133124
Ref: 2e0a8133124
Ref: library/uuid uuid UUID urn8133183
Ref: 2e0f8133183
Ref: library/uuid uuid UUID variant8133262
Ref: 2e108133262
Ref: library/uuid uuid UUID version8133523
Ref: 2e158133523
Ref: library/uuid uuid UUID is_safe8133658
Ref: 4198133658
Ref: library/uuid uuid getnode8133908
Ref: 41a8133908
Ref: library/uuid uuid uuid18134867
Ref: 41b8134867
Ref: library/uuid uuid uuid38135217
Ref: 2e038135217
Ref: library/uuid uuid uuid48135384
Ref: 2e048135384
Ref: library/uuid uuid uuid58135441
Ref: 2e058135441
Ref: library/uuid uuid NAMESPACE_DNS8135741
Ref: 2e168135741
Ref: library/uuid uuid NAMESPACE_URL8135870
Ref: 2e178135870
Ref: library/uuid uuid NAMESPACE_OID8135970
Ref: 2e188135970
Ref: library/uuid uuid NAMESPACE_X5008136075
Ref: 2e198136075
Ref: library/uuid uuid RESERVED_NCS8136335
Ref: 2e118136335
Ref: library/uuid uuid RFC_41228136404
Ref: 2e128136404
Ref: library/uuid uuid RESERVED_MICROSOFT8136485
Ref: 2e138136485
Ref: library/uuid uuid RESERVED_FUTURE8136559
Ref: 2e148136559
Ref: uuid --- UUID objects according to RFC 4122-Footnote-18136931
Ref: uuid --- UUID objects according to RFC 4122-Footnote-28136994
Ref: uuid --- UUID objects according to RFC 4122-Footnote-38137043
Ref: uuid --- UUID objects according to RFC 4122-Footnote-48137092
Ref: uuid --- UUID objects according to RFC 4122-Footnote-58137141
Ref: uuid --- UUID objects according to RFC 4122-Footnote-68137190
Ref: uuid --- UUID objects according to RFC 4122-Footnote-78137239
Node: 示例<13>8137288
Ref: library/uuid example8137378
Ref: 2e1a8137378
Ref: library/uuid uuid-example8137378
Ref: 2e1b8137378
Node: socketserver --- A framework for network servers8138633
Ref: library/socketserver doc8138833
Ref: 2e1c8138833
Ref: library/socketserver module-socketserver8138833
Ref: f18138833
Ref: library/socketserver socketserver-a-framework-for-network-servers8138833
Ref: 2e1d8138833
Ref: library/socketserver socketserver TCPServer8139192
Ref: 2e1e8139192
Ref: library/socketserver socketserver UDPServer8139661
Ref: 2e218139661
Ref: library/socketserver socketserver UnixStreamServer8139962
Ref: 2e228139962
Ref: library/socketserver socketserver UnixDatagramServer8140073
Ref: 2e238140073
Ref: socketserver --- A framework for network servers-Footnote-18142418
Node: Server Creation Notes8142489
Ref: library/socketserver server-creation-notes8142620
Ref: 2e288142620
Ref: library/socketserver socketserver ForkingMixIn8143454
Ref: 3dd8143454
Ref: library/socketserver socketserver ThreadingMixIn8143489
Ref: 3de8143489
Ref: library/socketserver socketserver ForkingTCPServer8144972
Ref: 2e2a8144972
Ref: library/socketserver socketserver ForkingUDPServer8145011
Ref: 2e2b8145011
Ref: library/socketserver socketserver ThreadingTCPServer8145050
Ref: 2e2c8145050
Ref: library/socketserver socketserver ThreadingUDPServer8145091
Ref: 2e298145091
Node: Server 对象<2>8147376
Ref: library/socketserver server-objects8147539
Ref: 2e2e8147539
Ref: library/socketserver socketserver BaseServer8147586
Ref: a918147586
Ref: library/socketserver socketserver BaseServer fileno8147983
Ref: 2e318147983
Ref: library/socketserver socketserver BaseServer handle_request8148256
Ref: 2e268148256
Ref: library/socketserver socketserver BaseServer serve_forever8148858
Ref: a938148858
Ref: library/socketserver socketserver BaseServer service_actions8149504
Ref: a928149504
Ref: library/socketserver socketserver BaseServer shutdown8149802
Ref: 102d8149802
Ref: library/socketserver socketserver BaseServer server_close8150082
Ref: 2e278150082
Ref: library/socketserver socketserver BaseServer address_family8150168
Ref: 2e378150168
Ref: library/socketserver socketserver BaseServer RequestHandlerClass8150376
Ref: 2e308150376
Ref: library/socketserver socketserver BaseServer server_address8150531
Ref: 2e2f8150531
Ref: library/socketserver socketserver BaseServer socket8150951
Ref: 2e388150951
Ref: library/socketserver socketserver BaseServer allow_reuse_address8151134
Ref: 2e398151134
Ref: library/socketserver socketserver BaseServer request_queue_size8151345
Ref: 2e3a8151345
Ref: library/socketserver socketserver BaseServer socket_type8151829
Ref: 2e3b8151829
Ref: library/socketserver socketserver BaseServer timeout8152017
Ref: 2e358152017
Ref: library/socketserver socketserver BaseServer finish_request8152520
Ref: 2e3c8152520
Ref: library/socketserver socketserver BaseServer get_request8152737
Ref: 2e328152737
Ref: library/socketserver socketserver BaseServer handle_error8152967
Ref: 6068152967
Ref: library/socketserver socketserver BaseServer handle_timeout8153414
Ref: 2e368153414
Ref: library/socketserver socketserver BaseServer process_request8153853
Ref: 2e348153853
Ref: library/socketserver socketserver BaseServer server_activate8154224
Ref: 2e208154224
Ref: library/socketserver socketserver BaseServer server_bind8154471
Ref: 2e1f8154471
Ref: library/socketserver socketserver BaseServer verify_request8154625
Ref: 2e338154625
Node: Request Handler Objects8155205
Ref: library/socketserver request-handler-objects8155357
Ref: 2e3d8155357
Ref: library/socketserver socketserver BaseRequestHandler8155426
Ref: 2e248155426
Ref: library/socketserver socketserver BaseRequestHandler setup8155778
Ref: 2e3e8155778
Ref: library/socketserver socketserver BaseRequestHandler handle8155973
Ref: 2e258155973
Ref: library/socketserver socketserver BaseRequestHandler finish8156677
Ref: 2e3f8156677
Ref: library/socketserver socketserver StreamRequestHandler8156956
Ref: 5908156956
Ref: library/socketserver socketserver DatagramRequestHandler8156999
Ref: 2e2d8156999
Node: 例子<23>8157756
Ref: library/socketserver examples8157883
Ref: 2e408157883
Node: socketserver TCPServer Example8158082
Ref: library/socketserver socketserver-tcpserver-example8158198
Ref: 2e418158198
Node: socketserver UDPServer Example8161354
Ref: library/socketserver socketserver-udpserver-example8161498
Ref: 2e428161498
Node: Asynchronous Mixins8163115
Ref: library/socketserver asynchronous-mixins8163220
Ref: 2e438163220
Node: http server --- HTTP 服务器8165566
Ref: library/http server doc8165756
Ref: 2e448165756
Ref: library/http server http-server-http-servers8165756
Ref: 2e458165756
Ref: library/http server module-http server8165756
Ref: 978165756
Ref: library/http server http server HTTPServer8166571
Ref: 2c158166571
Ref: library/http server http server ThreadingHTTPServer8166867
Ref: 39e8166867
Ref: library/http server http server BaseHTTPRequestHandler8167387
Ref: a168167387
Ref: library/http server http server BaseHTTPRequestHandler client_address8168233
Ref: 2e468168233
Ref: library/http server http server BaseHTTPRequestHandler server8168346
Ref: 2e478168346
Ref: library/http server http server BaseHTTPRequestHandler close_connection8168407
Ref: 2e488168407
Ref: library/http server http server BaseHTTPRequestHandler requestline8168608
Ref: 2e4a8168608
Ref: library/http server http server BaseHTTPRequestHandler command8168884
Ref: 2e4b8168884
Ref: library/http server http server BaseHTTPRequestHandler path8168986
Ref: 2e4c8168986
Ref: library/http server http server BaseHTTPRequestHandler request_version8169257
Ref: 2e4d8169257
Ref: library/http server http server BaseHTTPRequestHandler headers8169363
Ref: 2cf38169363
Ref: library/http server http server BaseHTTPRequestHandler rfile8169787
Ref: 2e4f8169787
Ref: library/http server http server BaseHTTPRequestHandler wfile8169936
Ref: 2e508169936
Ref: library/http server http server BaseHTTPRequestHandler server_version8170376
Ref: 2e518170376
Ref: library/http server http server BaseHTTPRequestHandler sys_version8170660
Ref: 2e528170660
Ref: library/http server http server BaseHTTPRequestHandler error_message_format8170912
Ref: 2e548170912
Ref: library/http server http server BaseHTTPRequestHandler error_content_type8171270
Ref: 2e558171270
Ref: library/http server http server BaseHTTPRequestHandler protocol_version8171447
Ref: 2e568171447
Ref: library/http server http server BaseHTTPRequestHandler MessageClass8171907
Ref: 2e4e8171907
Ref: library/http server http server BaseHTTPRequestHandler responses8172136
Ref: 2ce08172136
Ref: library/http server http server BaseHTTPRequestHandler handle8172698
Ref: 2e598172698
Ref: library/http server http server BaseHTTPRequestHandler handle_one_request8172998
Ref: 2e498172998
Ref: library/http server http server BaseHTTPRequestHandler handle_expect_1008173196
Ref: 2e5a8173196
Ref: library/http server http server BaseHTTPRequestHandler send_error8173700
Ref: 8658173700
Ref: library/http server http server BaseHTTPRequestHandler send_response8174823
Ref: 2e5b8174823
Ref: library/http server http server BaseHTTPRequestHandler send_header8175624
Ref: 2e578175624
Ref: library/http server http server BaseHTTPRequestHandler send_response_only8176189
Ref: 2e588176189
Ref: library/http server http server BaseHTTPRequestHandler end_headers8176607
Ref: a178176607
Ref: library/http server http server BaseHTTPRequestHandler flush_headers8176901
Ref: a188176901
Ref: library/http server http server BaseHTTPRequestHandler log_request8177071
Ref: 2e5d8177071
Ref: library/http server http server BaseHTTPRequestHandler log_error8177368
Ref: 2e5e8177368
Ref: library/http server http server BaseHTTPRequestHandler log_message8177613
Ref: 2e5f8177613
Ref: library/http server http server BaseHTTPRequestHandler version_string8178102
Ref: 2e538178102
Ref: library/http server http server BaseHTTPRequestHandler date_time_string8178316
Ref: 2e5c8178316
Ref: library/http server http server BaseHTTPRequestHandler log_date_time_string8178703
Ref: 2e608178703
Ref: library/http server http server BaseHTTPRequestHandler address_string8178808
Ref: 2e618178808
Ref: library/http server http server SimpleHTTPRequestHandler8179043
Ref: 39d8179043
Ref: library/http server http server SimpleHTTPRequestHandler server_version8179567
Ref: 2e648179567
Ref: library/http server http server SimpleHTTPRequestHandler extensions_map8179725
Ref: 2e658179725
Ref: library/http server http server SimpleHTTPRequestHandler directory8180044
Ref: 2e668180044
Ref: library/http server http server SimpleHTTPRequestHandler do_HEAD8180231
Ref: 2e638180231
Ref: library/http server http server SimpleHTTPRequestHandler do_GET8180519
Ref: 2e628180519
Ref: library/http server http-server-cli8182893
Ref: 8668182893
Ref: library/http server http server CGIHTTPRequestHandler8183898
Ref: 2e678183898
Ref: library/http server http server CGIHTTPRequestHandler cgi_directories8185089
Ref: 2e688185089
Ref: library/http server http server CGIHTTPRequestHandler do_POST8185332
Ref: 2e698185332
Ref: http server --- HTTP 服务器-Footnote-18185905
Ref: http server --- HTTP 服务器-Footnote-28185975
Ref: http server --- HTTP 服务器-Footnote-38186024
Node: http cookies --- HTTP状态管理8186073
Ref: library/http cookies doc8186268
Ref: 2e6a8186268
Ref: library/http cookies http-cookies-http-state-management8186268
Ref: 2e6b8186268
Ref: library/http cookies module-http cookies8186268
Ref: 968186268
Ref: library/http cookies http cookies CookieError8187611
Ref: 2e6c8187611
Ref: library/http cookies http cookies BaseCookie8187775
Ref: 2e6d8187775
Ref: library/http cookies http cookies SimpleCookie8188162
Ref: 10488188162
Ref: http cookies --- HTTP状态管理-Footnote-18188980
Ref: http cookies --- HTTP状态管理-Footnote-28189051
Ref: http cookies --- HTTP状态管理-Footnote-38189100
Ref: http cookies --- HTTP状态管理-Footnote-48189149
Ref: http cookies --- HTTP状态管理-Footnote-58189198
Node: Cookie 对象8189247
Ref: library/http cookies cookie-objects8189352
Ref: 2e6f8189352
Ref: library/http cookies id18189352
Ref: 2e708189352
Ref: library/http cookies http cookies BaseCookie value_decode8189399
Ref: 2e718189399
Ref: library/http cookies http cookies BaseCookie value_encode8189671
Ref: 2e728189671
Ref: library/http cookies http cookies BaseCookie output8190123
Ref: 2e738190123
Ref: library/http cookies http cookies BaseCookie js_output8190491
Ref: 2e748190491
Ref: library/http cookies http cookies BaseCookie load8190770
Ref: 2e6e8190770
Node: Morsel 对象8191052
Ref: library/http cookies id28191176
Ref: 2e758191176
Ref: library/http cookies morsel-objects8191176
Ref: 2e768191176
Ref: library/http cookies http cookies Morsel8191223
Ref: 4958191223
Ref: library/http cookies http cookies Morsel value8192550
Ref: 4978192550
Ref: library/http cookies http cookies Morsel coded_value8192598
Ref: 4988192598
Ref: library/http cookies http cookies Morsel key8192701
Ref: 4968192701
Ref: library/http cookies http cookies Morsel set8192755
Ref: 4998192755
Ref: library/http cookies http cookies Morsel isReservedKey8192864
Ref: 2e778192864
Ref: library/http cookies http cookies Morsel output8192975
Ref: 2e788192975
Ref: library/http cookies http cookies Morsel js_output8193315
Ref: 2e798193315
Ref: library/http cookies http cookies Morsel OutputString8193589
Ref: 2e7a8193589
Ref: library/http cookies http cookies Morsel update8193801
Ref: 7cd8193801
Ref: library/http cookies http cookies Morsel copy8194096
Ref: 7cc8194096
Ref: library/http cookies http cookies Morsel setdefault8194246
Ref: 2e7b8194246
Ref: Morsel 对象-Footnote-18194461
Ref: Morsel 对象-Footnote-28194510
Ref: Morsel 对象-Footnote-38194559
Ref: Morsel 对象-Footnote-48194608
Node: 示例<14>8194657
Ref: library/http cookies cookie-example8194759
Ref: 2e7c8194759
Ref: library/http cookies example8194759
Ref: 2e7d8194759
Node: http cookiejar —— HTTP 客户端的 Cookie 处理8196407
Ref: library/http cookiejar doc8196617
Ref: 2e7e8196617
Ref: library/http cookiejar http-cookiejar-cookie-handling-for-http-clients8196617
Ref: 2e7f8196617
Ref: library/http cookiejar module-http cookiejar8196617
Ref: 958196617
Ref: library/http cookiejar http cookiejar LoadError8197926
Ref: 2e808197926
Ref: library/http cookiejar http cookiejar CookieJar8198265
Ref: 2c838198265
Ref: library/http cookiejar http cookiejar FileCookieJar8198687
Ref: 2e818198687
Ref: library/http cookiejar http cookiejar CookiePolicy8199312
Ref: 2e828199312
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy8199446
Ref: ffe8199446
Ref: library/http cookiejar http cookiejar Cookie8201157
Ref: 2e878201157
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-18202840
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-28202913
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-38202962
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-48203011
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-58203060
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-68203109
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-78203158
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-88203207
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-98203256
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-108203305
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-118203355
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-128203405
Node: CookieJar 和 FileCookieJar 对象8203455
Ref: library/http cookiejar cookie-jar-objects8203647
Ref: 2e888203647
Ref: library/http cookiejar cookiejar-and-filecookiejar-objects8203647
Ref: 2e898203647
Ref: library/http cookiejar http cookiejar CookieJar add_cookie_header8203919
Ref: 2e8a8203919
Ref: library/http cookiejar http cookiejar CookieJar extract_cookies8204831
Ref: 2e8b8204831
Ref: library/http cookiejar http cookiejar CookieJar set_policy8206060
Ref: 2e8d8206060
Ref: library/http cookiejar http cookiejar CookieJar make_cookies8206164
Ref: 2e8e8206164
Ref: library/http cookiejar http cookiejar CookieJar set_cookie_if_ok8206451
Ref: 2e8f8206451
Ref: library/http cookiejar http cookiejar CookieJar set_cookie8206576
Ref: 2e908206576
Ref: library/http cookiejar http cookiejar CookieJar clear8206725
Ref: 2e918206725
Ref: library/http cookiejar http cookiejar CookieJar clear_session_cookies8207230
Ref: 2e928207230
Ref: library/http cookiejar http cookiejar FileCookieJar save8207873
Ref: 2e938207873
Ref: library/http cookiejar http cookiejar FileCookieJar load8208726
Ref: 2e838208726
Ref: library/http cookiejar http cookiejar FileCookieJar revert8209288
Ref: 2e848209288
Ref: library/http cookiejar http cookiejar FileCookieJar filename8209687
Ref: 2e948209687
Ref: library/http cookiejar http cookiejar FileCookieJar delayload8209821
Ref: 2e958209821
Node: FileCookieJar subclasses and co-operation with web browsers8210239
Ref: library/http cookiejar file-cookie-jar-classes8210459
Ref: 2e858210459
Ref: library/http cookiejar filecookiejar-subclasses-and-co-operation-with-web-browsers8210459
Ref: 2e968210459
Ref: library/http cookiejar http cookiejar MozillaCookieJar8210687
Ref: 2e978210687
Ref: library/http cookiejar http cookiejar LWPCookieJar8211483
Ref: 2e988211483
Ref: FileCookieJar subclasses and co-operation with web browsers-Footnote-18211940
Node: CookiePolicy 对象8211989
Ref: library/http cookiejar cookie-policy-objects8212201
Ref: 2e998212201
Ref: library/http cookiejar cookiepolicy-objects8212201
Ref: 2e9a8212201
Ref: library/http cookiejar http cookiejar CookiePolicy set_ok8212350
Ref: 2e8c8212350
Ref: library/http cookiejar http cookiejar CookiePolicy return_ok8212676
Ref: 2e9b8212676
Ref: library/http cookiejar http cookiejar CookiePolicy domain_return_ok8213005
Ref: 2e9c8213005
Ref: library/http cookiejar http cookiejar CookiePolicy path_return_ok8214383
Ref: 2e9d8214383
Ref: library/http cookiejar http cookiejar CookiePolicy netscape8214835
Ref: 2e9e8214835
Ref: library/http cookiejar http cookiejar CookiePolicy rfc29658214905
Ref: 2e9f8214905
Ref: library/http cookiejar http cookiejar CookiePolicy hide_cookie28214977
Ref: 2ea08214977
Ref: CookiePolicy 对象-Footnote-18215524
Ref: CookiePolicy 对象-Footnote-28215573
Node: DefaultCookiePolicy 对象8215622
Ref: library/http cookiejar default-cookie-policy-objects8215791
Ref: 2ea18215791
Ref: library/http cookiejar defaultcookiepolicy-objects8215791
Ref: 2ea28215791
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy blocked_domains8218104
Ref: 2ea38218104
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy set_blocked_domains8218215
Ref: 2ea48218215
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy is_blocked8218329
Ref: 2ea58218329
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy allowed_domains8218471
Ref: 2ea68218471
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy set_allowed_domains8218607
Ref: 2ea78218607
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy is_not_allowed8218741
Ref: 2ea88218741
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy rfc2109_as_netscape8219074
Ref: 2e868219074
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy strict_domain8219658
Ref: 2ea98219658
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy strict_rfc2965_unverifiable8219959
Ref: 2eaa8219959
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_unverifiable8220334
Ref: 2eab8220334
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_domain8220480
Ref: 2eac8220480
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_set_initial_dollar8220658
Ref: 2ead8220658
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_set_path8220810
Ref: 2eae8220810
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy DomainStrictNoDots8221131
Ref: 2eaf8221131
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy DomainStrictNonDomain8221373
Ref: 2eb08221373
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy DomainRFC2965Match8221718
Ref: 2eb18221718
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy DomainLiberal8221952
Ref: 2eb28221952
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy DomainStrict8222097
Ref: 2eb38222097
Ref: DefaultCookiePolicy 对象-Footnote-18222247
Ref: DefaultCookiePolicy 对象-Footnote-28222296
Ref: DefaultCookiePolicy 对象-Footnote-38222345
Ref: DefaultCookiePolicy 对象-Footnote-48222394
Ref: DefaultCookiePolicy 对象-Footnote-58222443
Ref: DefaultCookiePolicy 对象-Footnote-68222492
Ref: DefaultCookiePolicy 对象-Footnote-78222541
Node: Cookie 对象<2>8222590
Ref: library/http cookiejar cookie-objects8222750
Ref: 2eb48222750
Ref: library/http cookiejar http cookiejar Cookie version8223515
Ref: 2eb58223515
Ref: library/http cookiejar http cookiejar Cookie name8223870
Ref: 2eb68223870
Ref: library/http cookiejar http cookiejar Cookie value8223925
Ref: 2eb78223925
Ref: library/http cookiejar http cookiejar Cookie port8224002
Ref: 2eb88224002
Ref: library/http cookiejar http cookiejar Cookie path8224138
Ref: 2eb98224138
Ref: library/http cookiejar http cookiejar Cookie secure8224230
Ref: 2eba8224230
Ref: library/http cookiejar http cookiejar Cookie expires8224334
Ref: 2ebb8224334
Ref: library/http cookiejar http cookiejar Cookie discard8224484
Ref: 2ebd8224484
Ref: library/http cookiejar http cookiejar Cookie comment8224558
Ref: 2ebe8224558
Ref: library/http cookiejar http cookiejar Cookie comment_url8224688
Ref: 2ebf8224688
Ref: library/http cookiejar http cookiejar Cookie rfc21098224832
Ref: 2ec08224832
Ref: library/http cookiejar http cookiejar Cookie port_specified8225239
Ref: 2ec18225239
Ref: library/http cookiejar http cookiejar Cookie domain_specified8225415
Ref: 2ec28225415
Ref: library/http cookiejar http cookiejar Cookie domain_initial_dot8225521
Ref: 2ec38225521
Ref: library/http cookiejar http cookiejar Cookie has_nonstandard_attr8225774
Ref: 2ec48225774
Ref: library/http cookiejar http cookiejar Cookie get_nonstandard_attr8225888
Ref: 2ec58225888
Ref: library/http cookiejar http cookiejar Cookie set_nonstandard_attr8226050
Ref: 2ec68226050
Ref: library/http cookiejar http cookiejar Cookie is_expired8226222
Ref: 2ebc8226222
Ref: Cookie 对象<2>-Footnote-18226515
Ref: Cookie 对象<2>-Footnote-28226564
Ref: Cookie 对象<2>-Footnote-38226613
Ref: Cookie 对象<2>-Footnote-48226662
Node: 例子<24>8226711
Ref: library/http cookiejar examples8226836
Ref: 2ec78226836
Ref: 例子<24>-Footnote-18228282
Node: xmlrpc --- XMLRPC 服务端与客户端模块8228331
Ref: library/xmlrpc doc8228549
Ref: 2ec88228549
Ref: library/xmlrpc xmlrpc-xmlrpc-server-and-client-modules8228549
Ref: 2ec98228549
Node: xmlrpc client --- XML-RPC 客户端访问8229050
Ref: library/xmlrpc client doc8229257
Ref: 2eca8229257
Ref: library/xmlrpc client module-xmlrpc client8229257
Ref: 1408229257
Ref: library/xmlrpc client xmlrpc-client-xml-rpc-client-access8229257
Ref: 2ecb8229257
Ref: library/xmlrpc client xmlrpc client ServerProxy8230165
Ref: 2568230165
Ref: xmlrpc client --- XML-RPC 客户端访问-Footnote-18237882
Ref: xmlrpc client --- XML-RPC 客户端访问-Footnote-28237954
Ref: xmlrpc client --- XML-RPC 客户端访问-Footnote-38238048
Ref: xmlrpc client --- XML-RPC 客户端访问-Footnote-48238107
Ref: xmlrpc client --- XML-RPC 客户端访问-Footnote-58238166
Ref: xmlrpc client --- XML-RPC 客户端访问-Footnote-68238212
Node: ServerProxy 对象8238261
Ref: library/xmlrpc client id18238381
Ref: 2ed08238381
Ref: library/xmlrpc client serverproxy-objects8238381
Ref: 2ed18238381
Ref: library/xmlrpc client xmlrpc client ServerProxy system listMethods8239033
Ref: 2ed28239033
Ref: library/xmlrpc client xmlrpc client ServerProxy system methodSignature8239196
Ref: 2ed38239196
Ref: library/xmlrpc client xmlrpc client ServerProxy system methodHelp8240212
Ref: 2ed48240212
Node: DateTime 对象8241282
Ref: library/xmlrpc client datetime-objects8241424
Ref: 2ed58241424
Ref: library/xmlrpc client id28241424
Ref: 2ed68241424
Ref: library/xmlrpc client xmlrpc client DateTime8241475
Ref: 2ecc8241475
Ref: library/xmlrpc client xmlrpc client DateTime decode8241782
Ref: 2ed78241782
Ref: library/xmlrpc client xmlrpc client DateTime encode8241879
Ref: 2ed88241879
Node: Binary 对象8242951
Ref: library/xmlrpc client binary-objects8243087
Ref: 2ed98243087
Ref: library/xmlrpc client id38243087
Ref: 2eda8243087
Ref: library/xmlrpc client xmlrpc client Binary8243134
Ref: 2ecd8243134
Ref: library/xmlrpc client xmlrpc client Binary data8243349
Ref: 2edb8243349
Ref: library/xmlrpc client xmlrpc client Binary decode8243652
Ref: 2edc8243652
Ref: library/xmlrpc client xmlrpc client Binary encode8243791
Ref: 2edd8243791
Ref: Binary 对象-Footnote-18245034
Node: Fault 对象8245095
Ref: library/xmlrpc client fault-objects8245236
Ref: 2ede8245236
Ref: library/xmlrpc client id48245236
Ref: 2edf8245236
Ref: library/xmlrpc client xmlrpc client Fault8245281
Ref: 2ece8245281
Ref: library/xmlrpc client xmlrpc client Fault faultCode8245446
Ref: 2ee08245446
Ref: library/xmlrpc client xmlrpc client Fault faultString8245521
Ref: 2ee18245521
Node: ProtocolError 对象8246480
Ref: library/xmlrpc client protocol-error-objects8246624
Ref: 2ee28246624
Ref: library/xmlrpc client protocolerror-objects8246624
Ref: 2ee38246624
Ref: library/xmlrpc client xmlrpc client ProtocolError8246685
Ref: 2ecf8246685
Ref: library/xmlrpc client xmlrpc client ProtocolError url8246960
Ref: 2ee48246960
Ref: library/xmlrpc client xmlrpc client ProtocolError errcode8247034
Ref: 2ee58247034
Ref: library/xmlrpc client xmlrpc client ProtocolError errmsg8247087
Ref: 2ee68247087
Ref: library/xmlrpc client xmlrpc client ProtocolError headers8247163
Ref: 2ee78247163
Node: MultiCall 对象8247900
Ref: library/xmlrpc client multicall-objects8248053
Ref: 2ee88248053
Ref: library/xmlrpc client xmlrpc client MultiCall8248232
Ref: 2ee98248232
Ref: MultiCall 对象-Footnote-18249935
Node: Convenience Functions8250118
Ref: library/xmlrpc client convenience-functions8250274
Ref: 2eea8250274
Ref: library/xmlrpc client xmlrpc client dumps8250339
Ref: 2eeb8250339
Ref: library/xmlrpc client xmlrpc client loads8251050
Ref: 2eec8251050
Node: Example of Client Usage8251911
Ref: library/xmlrpc client example-of-client-usage8252085
Ref: 2eed8252085
Ref: library/xmlrpc client xmlrpc-client-example8252085
Ref: 2eee8252085
Node: Example of Client and Server Usage8253392
Ref: library/xmlrpc client example-of-client-and-server-usage8253536
Ref: 2eef8253536
Node: xmlrpc server --- 基本 XML-RPC 服务器8253685
Ref: library/xmlrpc server doc8253880
Ref: 2ef18253880
Ref: library/xmlrpc server module-xmlrpc server8253880
Ref: 1418253880
Ref: library/xmlrpc server xmlrpc-server-basic-xml-rpc-servers8253880
Ref: 2ef28253880
Ref: library/xmlrpc server xmlrpc server SimpleXMLRPCServer8254551
Ref: 2ef38254551
Ref: library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler8256068
Ref: 2ef48256068
Ref: library/xmlrpc server xmlrpc server SimpleXMLRPCRequestHandler8256712
Ref: 2ef58256712
Ref: xmlrpc server --- 基本 XML-RPC 服务器-Footnote-18257198
Node: SimpleXMLRPCServer Objects8257270
Ref: library/xmlrpc server simple-xmlrpc-servers8257407
Ref: 2ef68257407
Ref: library/xmlrpc server simplexmlrpcserver-objects8257407
Ref: 2ef78257407
Ref: library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_function8257643
Ref: 2ef88257643
Ref: library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_instance8258381
Ref: 2ef98258381
Ref: library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_introspection_functions8259996
Ref: 2efa8259996
Ref: library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_multicall_functions8260205
Ref: 2efb8260205
Ref: library/xmlrpc server xmlrpc server SimpleXMLRPCRequestHandler rpc_paths8260334
Ref: 2efc8260334
Node: SimpleXMLRPCServer Example8260747
Ref: library/xmlrpc server id18260836
Ref: 2efd8260836
Ref: library/xmlrpc server simplexmlrpcserver-example8260836
Ref: 2ef08260836
Node: CGIXMLRPCRequestHandler8265352
Ref: library/xmlrpc server cgixmlrpcrequesthandler8265523
Ref: 2efe8265523
Ref: library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_function8265707
Ref: 2eff8265707
Ref: library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_instance8266450
Ref: 2f008266450
Ref: library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_introspection_functions8267335
Ref: 2f018267335
Ref: library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_multicall_functions8267548
Ref: 2f028267548
Ref: library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler handle_request8267687
Ref: 2f038267687
Node: Documenting XMLRPC server8268273
Ref: library/xmlrpc server documenting-xmlrpc-server8268441
Ref: 2f048268441
Ref: library/xmlrpc server xmlrpc server DocXMLRPCServer8268768
Ref: f878268768
Ref: library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler8269239
Ref: 2f058269239
Ref: library/xmlrpc server xmlrpc server DocXMLRPCRequestHandler8269372
Ref: 2f068269372
Node: DocXMLRPCServer Objects8269688
Ref: library/xmlrpc server doc-xmlrpc-servers8269859
Ref: 2f078269859
Ref: library/xmlrpc server docxmlrpcserver-objects8269859
Ref: 2f088269859
Ref: library/xmlrpc server xmlrpc server DocXMLRPCServer set_server_title8270295
Ref: 2f098270295
Ref: library/xmlrpc server xmlrpc server DocXMLRPCServer set_server_name8270481
Ref: 2f0a8270481
Ref: library/xmlrpc server xmlrpc server DocXMLRPCServer set_server_documentation8270699
Ref: 2f0b8270699
Node: DocCGIXMLRPCRequestHandler8270955
Ref: library/xmlrpc server doccgixmlrpcrequesthandler8271092
Ref: 2f0c8271092
Ref: library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler set_server_title8271543
Ref: 2f0d8271543
Ref: library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler set_server_name8271740
Ref: 2f0e8271740
Ref: library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler set_server_documentation8271969
Ref: 2f0f8271969
Node: ipaddress --- IPv4/IPv6 操作库8272236
Ref: library/ipaddress doc8272381
Ref: 2f108272381
Ref: library/ipaddress ipaddress-ipv4-ipv6-manipulation-library8272381
Ref: 2f118272381
Ref: library/ipaddress module-ipaddress8272381
Ref: a38272381
Ref: ipaddress --- IPv4/IPv6 操作库-Footnote-18273229
Node: 方便的工厂函数8273297
Ref: library/ipaddress convenience-factory-functions8273406
Ref: 2f138273406
Ref: library/ipaddress ipaddress ip_address8273564
Ref: 2f148273564
Ref: library/ipaddress ipaddress ip_network8274098
Ref: 2f178274098
Ref: library/ipaddress ipaddress ip_interface8274766
Ref: 2f188274766
Node: IP 地址8275478
Ref: library/ipaddress ip-addresses8275613
Ref: 2f1b8275613
Node: 地址对象8275745
Ref: library/ipaddress address-objects8275846
Ref: 2f1c8275846
Ref: library/ipaddress ipaddress IPv4Address8276232
Ref: 2f158276232
Ref: library/ipaddress ipaddress IPv4Address version8277472
Ref: 2f1e8277472
Ref: library/ipaddress ipaddress IPv4Address max_prefixlen8277569
Ref: 2f1f8277569
Ref: library/ipaddress ipaddress IPv4Address compressed8277888
Ref: 2f208277888
Ref: library/ipaddress ipaddress IPv4Address exploded8277917
Ref: 2f218277917
Ref: library/ipaddress ipaddress IPv4Address packed8278403
Ref: 2f228278403
Ref: library/ipaddress ipaddress IPv4Address reverse_pointer8278637
Ref: 2f238278637
Ref: library/ipaddress ipaddress IPv4Address is_multicast8279177
Ref: 2f248279177
Ref: library/ipaddress ipaddress IPv4Address is_private8279379
Ref: 2f258279379
Ref: library/ipaddress ipaddress IPv4Address is_global8279633
Ref: 8758279633
Ref: library/ipaddress ipaddress IPv4Address is_unspecified8279915
Ref: 2f268279915
Ref: library/ipaddress ipaddress IPv4Address is_reserved8280066
Ref: 2f278280066
Ref: library/ipaddress ipaddress IPv4Address is_loopback8280228
Ref: 2f288280228
Ref: library/ipaddress ipaddress IPv4Address is_link_local8280417
Ref: 2f298280417
Ref: library/ipaddress ipaddress IPv6Address8280549
Ref: 2f168280549
Ref: library/ipaddress ipaddress IPv6Address compressed8281474
Ref: 2f2a8281474
Ref: library/ipaddress ipaddress IPv6Address exploded8281780
Ref: 2f2b8281780
Ref: library/ipaddress ipaddress IPv6Address packed8282054
Ref: 2f2c8282054
Ref: library/ipaddress ipaddress IPv6Address reverse_pointer8282079
Ref: 2f2d8282079
Ref: library/ipaddress ipaddress IPv6Address version8282113
Ref: 2f2e8282113
Ref: library/ipaddress ipaddress IPv6Address max_prefixlen8282139
Ref: 2f2f8282139
Ref: library/ipaddress ipaddress IPv6Address is_multicast8282171
Ref: 2f308282171
Ref: library/ipaddress ipaddress IPv6Address is_private8282202
Ref: 2f318282202
Ref: library/ipaddress ipaddress IPv6Address is_global8282231
Ref: 2f328282231
Ref: library/ipaddress ipaddress IPv6Address is_unspecified8282259
Ref: 2f338282259
Ref: library/ipaddress ipaddress IPv6Address is_reserved8282292
Ref: 2f348282292
Ref: library/ipaddress ipaddress IPv6Address is_loopback8282322
Ref: 2f358282322
Ref: library/ipaddress ipaddress IPv6Address is_link_local8282352
Ref: 2f368282352
Ref: library/ipaddress ipaddress IPv6Address is_site_local8282423
Ref: 2f378282423
Ref: library/ipaddress ipaddress IPv6Address ipv4_mapped8282766
Ref: 2f388282766
Ref: library/ipaddress ipaddress IPv6Address sixtofour8283035
Ref: 2f398283035
Ref: library/ipaddress ipaddress IPv6Address teredo8283322
Ref: 2f3a8283322
Ref: 地址对象-Footnote-18283669
Ref: 地址对象-Footnote-28283718
Ref: 地址对象-Footnote-38283767
Ref: 地址对象-Footnote-48283869
Ref: 地址对象-Footnote-58283971
Ref: 地址对象-Footnote-68284073
Ref: 地址对象-Footnote-78284175
Ref: 地址对象-Footnote-88284224
Ref: 地址对象-Footnote-98284273
Ref: 地址对象-Footnote-108284322
Ref: 地址对象-Footnote-118284372
Ref: 地址对象-Footnote-128284422
Ref: 地址对象-Footnote-138284472
Ref: 地址对象-Footnote-148284522
Ref: 地址对象-Footnote-158284572
Ref: 地址对象-Footnote-168284622
Node: Conversion to Strings and Integers8284672
Ref: library/ipaddress conversion-to-strings-and-integers8284794
Ref: 2f3b8284794
Node: 运算符<3>8285336
Ref: library/ipaddress operators8285437
Ref: 2f3c8285437
Node: 比较运算符8285689
Ref: library/ipaddress comparison-operators8285777
Ref: 2f3d8285777
Node: 算术运算符8286135
Ref: library/ipaddress arithmetic-operators8286223
Ref: 2f3e8286223
Node: IP网络的定义8286711
Ref: library/ipaddress ip-network-definitions8286842
Ref: 2f3f8286842
Node: Prefix net mask and host mask8287537
Ref: library/ipaddress prefix-net-mask-and-host-mask8287644
Ref: 2f408287644
Node: Network objects8288314
Ref: library/ipaddress network-objects8288442
Ref: 2f418288442
Ref: library/ipaddress ipaddress IPv4Network8288901
Ref: 3a88288901
Ref: library/ipaddress ipaddress IPv4Network version8291317
Ref: 2f438291317
Ref: library/ipaddress ipaddress IPv4Network max_prefixlen8291343
Ref: 2f448291343
Ref: library/ipaddress ipaddress IPv4Network is_multicast8291475
Ref: 2f458291475
Ref: library/ipaddress ipaddress IPv4Network is_private8291506
Ref: 2f468291506
Ref: library/ipaddress ipaddress IPv4Network is_unspecified8291535
Ref: 2f478291535
Ref: library/ipaddress ipaddress IPv4Network is_reserved8291568
Ref: 2f488291568
Ref: library/ipaddress ipaddress IPv4Network is_loopback8291598
Ref: 2f498291598
Ref: library/ipaddress ipaddress IPv4Network is_link_local8291628
Ref: 2f4a8291628
Ref: library/ipaddress ipaddress IPv4Network network_address8291817
Ref: 2f4b8291817
Ref: library/ipaddress ipaddress IPv4Network broadcast_address8291988
Ref: 2f4c8291988
Ref: library/ipaddress ipaddress IPv4Network hostmask8292182
Ref: 2f4d8292182
Ref: library/ipaddress ipaddress IPv4Network netmask8292274
Ref: 2f4e8292274
Ref: library/ipaddress ipaddress IPv4Network with_prefixlen8292364
Ref: 2f4f8292364
Ref: library/ipaddress ipaddress IPv4Network compressed8292397
Ref: 2f508292397
Ref: library/ipaddress ipaddress IPv4Network exploded8292426
Ref: 2f518292426
Ref: library/ipaddress ipaddress IPv4Network with_netmask8292724
Ref: 2f528292724
Ref: library/ipaddress ipaddress IPv4Network with_hostmask8292852
Ref: 2f538292852
Ref: library/ipaddress ipaddress IPv4Network num_addresses8292982
Ref: 2f548292982
Ref: library/ipaddress ipaddress IPv4Network prefixlen8293071
Ref: 2f558293071
Ref: library/ipaddress ipaddress IPv4Network hosts8293149
Ref: 2f568293149
Ref: library/ipaddress ipaddress IPv4Network overlaps8294146
Ref: 2f578294146
Ref: library/ipaddress ipaddress IPv4Network address_exclude8294318
Ref: 2f588294318
Ref: library/ipaddress ipaddress IPv4Network subnets8294924
Ref: 7a08294924
Ref: library/ipaddress ipaddress IPv4Network supernet8296472
Ref: 7a18296472
Ref: library/ipaddress ipaddress IPv4Network subnet_of8297278
Ref: 2f598297278
Ref: library/ipaddress ipaddress IPv4Network supernet_of8297573
Ref: 2f5a8297573
Ref: library/ipaddress ipaddress IPv4Network compare_networks8297874
Ref: 2f5b8297874
Ref: library/ipaddress ipaddress IPv6Network8298551
Ref: 3a78298551
Ref: library/ipaddress ipaddress IPv6Network version8300348
Ref: 2f5c8300348
Ref: library/ipaddress ipaddress IPv6Network max_prefixlen8300374
Ref: 2f5d8300374
Ref: library/ipaddress ipaddress IPv6Network is_multicast8300406
Ref: 2f5e8300406
Ref: library/ipaddress ipaddress IPv6Network is_private8300437
Ref: 2f5f8300437
Ref: library/ipaddress ipaddress IPv6Network is_unspecified8300466
Ref: 2f608300466
Ref: library/ipaddress ipaddress IPv6Network is_reserved8300499
Ref: 2f618300499
Ref: library/ipaddress ipaddress IPv6Network is_loopback8300529
Ref: 2f628300529
Ref: library/ipaddress ipaddress IPv6Network is_link_local8300559
Ref: 2f638300559
Ref: library/ipaddress ipaddress IPv6Network network_address8300591
Ref: 2f648300591
Ref: library/ipaddress ipaddress IPv6Network broadcast_address8300625
Ref: 2f658300625
Ref: library/ipaddress ipaddress IPv6Network hostmask8300661
Ref: 2f668300661
Ref: library/ipaddress ipaddress IPv6Network netmask8300688
Ref: 2f678300688
Ref: library/ipaddress ipaddress IPv6Network with_prefixlen8300714
Ref: 2f688300714
Ref: library/ipaddress ipaddress IPv6Network compressed8300747
Ref: 2f698300747
Ref: library/ipaddress ipaddress IPv6Network exploded8300776
Ref: 2f6a8300776
Ref: library/ipaddress ipaddress IPv6Network with_netmask8300803
Ref: 2f6b8300803
Ref: library/ipaddress ipaddress IPv6Network with_hostmask8300834
Ref: 2f6c8300834
Ref: library/ipaddress ipaddress IPv6Network num_addresses8300866
Ref: 2f6d8300866
Ref: library/ipaddress ipaddress IPv6Network prefixlen8300898
Ref: 2f6e8300898
Ref: library/ipaddress ipaddress IPv6Network hosts8300926
Ref: 2f6f8300926
Ref: library/ipaddress ipaddress IPv6Network overlaps8301376
Ref: 2f708301376
Ref: library/ipaddress ipaddress IPv6Network address_exclude8301411
Ref: 2f718301411
Ref: library/ipaddress ipaddress IPv6Network subnets8301455
Ref: 2f728301455
Ref: library/ipaddress ipaddress IPv6Network supernet8301517
Ref: 2f738301517
Ref: library/ipaddress ipaddress IPv6Network subnet_of8301580
Ref: 2f748301580
Ref: library/ipaddress ipaddress IPv6Network supernet_of8301616
Ref: 2f758301616
Ref: library/ipaddress ipaddress IPv6Network compare_networks8301654
Ref: 2f768301654
Ref: library/ipaddress ipaddress IPv6Network is_site_local8301796
Ref: 2f778301796
Node: 运算符<4>8301970
Ref: library/ipaddress id18302060
Ref: 2f788302060
Node: Logical operators8302357
Ref: library/ipaddress logical-operators8302441
Ref: 2f798302441
Node: 迭代<2>8302646
Ref: library/ipaddress iteration8302774
Ref: 2f7a8302774
Node: Networks as containers of addresses8303594
Ref: library/ipaddress networks-as-containers-of-addresses8303696
Ref: 2f7b8303696
Node: Interface objects8304154
Ref: library/ipaddress interface-objects8304304
Ref: 2f7c8304304
Ref: library/ipaddress ipaddress IPv4Interface8304453
Ref: 2f198304453
Ref: library/ipaddress ipaddress IPv4Interface ip8304868
Ref: 2f7d8304868
Ref: library/ipaddress ipaddress IPv4Interface network8305112
Ref: 2f7e8305112
Ref: library/ipaddress ipaddress IPv4Interface with_prefixlen8305366
Ref: 2f7f8305366
Ref: library/ipaddress ipaddress IPv4Interface with_netmask8305631
Ref: 2f808305631
Ref: library/ipaddress ipaddress IPv4Interface with_hostmask8305901
Ref: 2f818305901
Ref: library/ipaddress ipaddress IPv6Interface8306170
Ref: 2f1a8306170
Ref: library/ipaddress ipaddress IPv6Interface ip8306585
Ref: 2f828306585
Ref: library/ipaddress ipaddress IPv6Interface network8306606
Ref: 2f838306606
Ref: library/ipaddress ipaddress IPv6Interface with_prefixlen8306632
Ref: 2f848306632
Ref: library/ipaddress ipaddress IPv6Interface with_netmask8306665
Ref: 2f858306665
Ref: library/ipaddress ipaddress IPv6Interface with_hostmask8306696
Ref: 2f868306696
Node: 运算符<5>8306867
Ref: library/ipaddress id28306933
Ref: 2f878306933
Node: Logical operators<2>8307192
Ref: library/ipaddress id38307261
Ref: 2f888307261
Node: Other Module Level Functions8307918
Ref: library/ipaddress other-module-level-functions8308068
Ref: 2f898308068
Ref: library/ipaddress ipaddress v4_int_to_packed8308213
Ref: 2f8a8308213
Ref: library/ipaddress ipaddress v6_int_to_packed8308685
Ref: 2f8b8308685
Ref: library/ipaddress ipaddress summarize_address_range8308992
Ref: 7a28308992
Ref: library/ipaddress ipaddress collapse_addresses8309873
Ref: 7a38309873
Ref: library/ipaddress ipaddress get_mixed_type_key8310439
Ref: 2f8c8310439
Node: Custom Exceptions8311036
Ref: library/ipaddress custom-exceptions8311160
Ref: 2f8d8311160
Ref: library/ipaddress ipaddress AddressValueError8311331
Ref: 2f1d8311331
Ref: library/ipaddress ipaddress NetmaskValueError8311431
Ref: 2f428311431
Node: 多媒体服务8311532
Ref: library/mm doc8311651
Ref: 2f8e8311651
Ref: library/mm mmedia8311651
Ref: 2f8f8311651
Ref: library/mm multimedia-services8311651
Ref: 2f908311651
Node: audioop --- 处理原始音频数据8312493
Ref: library/audioop doc8312626
Ref: 2f918312626
Ref: library/audioop audioop-manipulate-raw-audio-data8312626
Ref: 2f928312626
Ref: library/audioop module-audioop8312626
Ref: d8312626
Ref: library/audioop audioop error8313477
Ref: 2f938313477
Ref: library/audioop audioop add8313586
Ref: 2f948313586
Ref: library/audioop audioop adpcm2lin8313931
Ref: 2f958313931
Ref: library/audioop audioop alaw2lin8314234
Ref: 2f978314234
Ref: library/audioop audioop avg8314465
Ref: 2f988314465
Ref: library/audioop audioop avgpp8314557
Ref: 2f998314557
Ref: library/audioop audioop bias8314729
Ref: 2f9a8314729
Ref: library/audioop audioop byteswap8314920
Ref: 82b8314920
Ref: library/audioop audioop cross8315140
Ref: 2f9b8315140
Ref: library/audioop audioop findfactor8315255
Ref: 2f9c8315255
Ref: library/audioop audioop findfit8315597
Ref: 2f9d8315597
Ref: library/audioop audioop findmax8316183
Ref: 2f9e8316183
Ref: library/audioop audioop getsample8316562
Ref: 2f9f8316562
Ref: library/audioop audioop lin2adpcm8316670
Ref: 2f968316670
Ref: library/audioop audioop lin2alaw8317383
Ref: 2fa08317383
Ref: library/audioop audioop lin2lin8317678
Ref: 2fa18317678
Ref: library/audioop audioop lin2ulaw8318291
Ref: 2fa28318291
Ref: library/audioop audioop max8318586
Ref: 2fa38318586
Ref: library/audioop audioop maxpp8318690
Ref: 2fa48318690
Ref: library/audioop audioop minmax8318784
Ref: 2fa58318784
Ref: library/audioop audioop mul8318915
Ref: 2fa68318915
Ref: library/audioop audioop ratecv8319121
Ref: 2fa78319121
Ref: library/audioop audioop reverse8319637
Ref: 2fa88319637
Ref: library/audioop audioop rms8319751
Ref: 2fa98319751
Ref: library/audioop audioop tomono8319899
Ref: 2faa8319899
Ref: library/audioop audioop tostereo8320124
Ref: 2fab8320124
Ref: library/audioop audioop ulaw2lin8320379
Ref: 2fac8320379
Node: aifc --- 读写 AIFF 和 AIFC 文件8322955
Ref: library/aifc doc8323127
Ref: 2fad8323127
Ref: library/aifc aifc-read-and-write-aiff-and-aifc-files8323127
Ref: 2fae8323127
Ref: library/aifc module-aifc8323127
Ref: 58323127
Ref: library/aifc aifc open8324345
Ref: 4638324345
Ref: library/aifc aifc aifc getnchannels8325338
Ref: 2faf8325338
Ref: library/aifc aifc aifc getsampwidth8325443
Ref: 2fb08325443
Ref: library/aifc aifc aifc getframerate8325532
Ref: 2fb18325532
Ref: library/aifc aifc aifc getnframes8325618
Ref: 2fb28325618
Ref: library/aifc aifc aifc getcomptype8325693
Ref: 2fb38325693
Ref: library/aifc aifc aifc getcompname8325878
Ref: 2fb48325878
Ref: library/aifc aifc aifc getparams8326098
Ref: 8248326098
Ref: library/aifc aifc aifc getmarkers8326297
Ref: 2fb58326297
Ref: library/aifc aifc aifc getmark8326609
Ref: 2fb68326609
Ref: library/aifc aifc aifc readframes8326752
Ref: 2fb78326752
Ref: library/aifc aifc aifc rewind8326947
Ref: 2fb88326947
Ref: library/aifc aifc aifc setpos8327057
Ref: 2fb98327057
Ref: library/aifc aifc aifc tell8327134
Ref: 2fba8327134
Ref: library/aifc aifc aifc close8327191
Ref: 8258327191
Ref: library/aifc aifc aifc aiff8327677
Ref: 2fbb8327677
Ref: library/aifc aifc aifc aifc8327859
Ref: 2fbc8327859
Ref: library/aifc aifc aifc setnchannels8328043
Ref: 2fbd8328043
Ref: library/aifc aifc aifc setsampwidth8328129
Ref: 2fbe8328129
Ref: library/aifc aifc aifc setframerate8328223
Ref: 2fbf8328223
Ref: library/aifc aifc aifc setnframes8328313
Ref: 2fc08328313
Ref: library/aifc aifc aifc setcomptype8328492
Ref: 2fc18328492
Ref: library/aifc aifc aifc setparams8328913
Ref: 2fc28328913
Ref: library/aifc aifc aifc setmark8329214
Ref: 2fc38329214
Ref: library/aifc aifc aifc writeframes8329564
Ref: 8278329564
Ref: library/aifc aifc aifc writeframesraw8329785
Ref: 8268329785
Ref: aifc --- 读写 AIFF 和 AIFC 文件-Footnote-18330235
Node: sunau --- 读写 Sun AU 文件8330298
Ref: library/sunau doc8330464
Ref: 2fc48330464
Ref: library/sunau module-sunau8330464
Ref: fb8330464
Ref: library/sunau sunau-read-and-write-sun-au-files8330464
Ref: 2fc58330464
Ref: library/sunau sunau open8331894
Ref: 47a8331894
Ref: library/sunau sunau openfp8332346
Ref: 4798332346
Ref: library/sunau sunau Error8332568
Ref: 2fc68332568
Ref: library/sunau sunau AUDIO_FILE_MAGIC8332766
Ref: 2fc78332766
Ref: library/sunau sunau AUDIO_FILE_ENCODING_MULAW_88332951
Ref: 2fc88332951
Ref: library/sunau sunau AUDIO_FILE_ENCODING_LINEAR_88332997
Ref: 2fc98332997
Ref: library/sunau sunau AUDIO_FILE_ENCODING_LINEAR_168333044
Ref: 2fca8333044
Ref: library/sunau sunau AUDIO_FILE_ENCODING_LINEAR_248333092
Ref: 2fcb8333092
Ref: library/sunau sunau AUDIO_FILE_ENCODING_LINEAR_328333140
Ref: 2fcc8333140
Ref: library/sunau sunau AUDIO_FILE_ENCODING_ALAW_88333188
Ref: 2fcd8333188
Ref: library/sunau sunau AUDIO_FILE_ENCODING_FLOAT8333329
Ref: 2fce8333329
Ref: library/sunau sunau AUDIO_FILE_ENCODING_DOUBLE8333373
Ref: 2fcf8333373
Ref: library/sunau sunau AUDIO_FILE_ENCODING_ADPCM_G7218333418
Ref: 2fd08333418
Ref: library/sunau sunau AUDIO_FILE_ENCODING_ADPCM_G7228333467
Ref: 2fd18333467
Ref: library/sunau sunau AUDIO_FILE_ENCODING_ADPCM_G723_38333516
Ref: 2fd28333516
Ref: library/sunau sunau AUDIO_FILE_ENCODING_ADPCM_G723_58333567
Ref: 2fd38333567
Ref: sunau --- 读写 Sun AU 文件-Footnote-18333825
Node: AU_read 对象8333889
Ref: library/sunau au-read-objects8333994
Ref: 2fd48333994
Ref: library/sunau id18333994
Ref: 2fd58333994
Ref: library/sunau sunau AU_read close8334128
Ref: 2fd68334128
Ref: library/sunau sunau AU_read getnchannels8334264
Ref: 2fd78334264
Ref: library/sunau sunau AU_read getsampwidth8334368
Ref: 2fd88334368
Ref: library/sunau sunau AU_read getframerate8334439
Ref: 2fd98334439
Ref: library/sunau sunau AU_read getnframes8334504
Ref: 2fda8334504
Ref: library/sunau sunau AU_read getcomptype8334570
Ref: 2fdb8334570
Ref: library/sunau sunau AU_read getcompname8334721
Ref: 2fdc8334721
Ref: library/sunau sunau AU_read getparams8334954
Ref: 2fdd8334954
Ref: library/sunau sunau AU_read readframes8335156
Ref: 2fde8335156
Ref: library/sunau sunau AU_read rewind8335395
Ref: 2fdf8335395
Ref: library/sunau sunau AU_read setpos8335538
Ref: 2fe08335538
Ref: library/sunau sunau AU_read tell8335704
Ref: 2fe18335704
Ref: library/sunau sunau AU_read getmarkers8335988
Ref: 2fe28335988
Ref: library/sunau sunau AU_read getmark8336050
Ref: 2fe38336050
Node: AU_write 对象8336112
Ref: library/sunau au-write-objects8336217
Ref: 2fe48336217
Ref: library/sunau id28336217
Ref: 2fe58336217
Ref: library/sunau sunau AU_write setnchannels8336354
Ref: 2fe68336354
Ref: library/sunau sunau AU_write setsampwidth8336418
Ref: 8e68336418
Ref: library/sunau sunau AU_write setframerate8336555
Ref: 2fe78336555
Ref: library/sunau sunau AU_write setnframes8336620
Ref: 2fe88336620
Ref: library/sunau sunau AU_write setcomptype8336759
Ref: 2fe98336759
Ref: library/sunau sunau AU_write setparams8336920
Ref: 2fea8336920
Ref: library/sunau sunau AU_write tell8337136
Ref: 2feb8337136
Ref: library/sunau sunau AU_write writeframesraw8337323
Ref: 8e78337323
Ref: library/sunau sunau AU_write writeframes8337497
Ref: 8e88337497
Ref: library/sunau sunau AU_write close8337665
Ref: 2fec8337665
Node: wave --- 读写WAV格式文件8337905
Ref: library/wave doc8338068
Ref: 2fed8338068
Ref: library/wave module-wave8338068
Ref: 1288338068
Ref: library/wave wave-read-and-write-wav-files8338068
Ref: 2fee8338068
Ref: library/wave wave open8338442
Ref: 47e8338442
Ref: library/wave wave openfp8339511
Ref: 47d8339511
Ref: library/wave wave Error8339670
Ref: 2ff18339670
Ref: wave --- 读写WAV格式文件-Footnote-18339846
Node: Wave_read对象8339909
Ref: library/wave id18340017
Ref: 2ff28340017
Ref: library/wave wave-read-objects8340017
Ref: 2ff38340017
Ref: library/wave wave Wave_read close8340142
Ref: 2fef8340142
Ref: library/wave wave Wave_read getnchannels8340289
Ref: 2ff48340289
Ref: library/wave wave Wave_read getsampwidth8340402
Ref: 2ff58340402
Ref: library/wave wave Wave_read getframerate8340475
Ref: 2ff68340475
Ref: library/wave wave Wave_read getnframes8340542
Ref: 2ff78340542
Ref: library/wave wave Wave_read getcomptype8340610
Ref: 2ff88340610
Ref: library/wave wave Wave_read getcompname8340708
Ref: 2ff98340708
Ref: library/wave wave Wave_read getparams8340855
Ref: 2ffa8340855
Ref: library/wave wave Wave_read readframes8341059
Ref: 2ffb8341059
Ref: library/wave wave Wave_read rewind8341179
Ref: 2ffc8341179
Ref: library/wave wave Wave_read getmarkers8341343
Ref: 2ffd8341343
Ref: library/wave wave Wave_read getmark8341407
Ref: 2ffe8341407
Ref: library/wave wave Wave_read setpos8341542
Ref: 2fff8341542
Ref: library/wave wave Wave_read tell8341621
Ref: 30008341621
Node: Wave_write 对象8341692
Ref: library/wave id28341800
Ref: 30018341800
Ref: library/wave wave-write-objects8341800
Ref: 9138341800
Ref: library/wave wave Wave_write close8342614
Ref: 2ff08342614
Ref: library/wave wave Wave_write setnchannels8342887
Ref: 30048342887
Ref: library/wave wave Wave_write setsampwidth8342953
Ref: 30058342953
Ref: library/wave wave Wave_write setframerate8343035
Ref: 30068343035
Ref: library/wave wave Wave_write setnframes8343203
Ref: 30028343203
Ref: library/wave wave Wave_write setcomptype8343417
Ref: 30078343417
Ref: library/wave wave Wave_write setparams8343542
Ref: 30038343542
Ref: library/wave wave Wave_write tell8343759
Ref: 30088343759
Ref: library/wave wave Wave_write writeframesraw8343933
Ref: 9148343933
Ref: library/wave wave Wave_write writeframes8344109
Ref: 9158344109
Node: chunk --- 读取 IFF 分块数据8344673
Ref: library/chunk doc8344843
Ref: 30098344843
Ref: library/chunk chunk-read-iff-chunked-data8344843
Ref: 300a8344843
Ref: library/chunk module-chunk8344843
Ref: 188344843
Ref: library/chunk chunk Chunk8346562
Ref: 300b8346562
Ref: library/chunk chunk Chunk getname8347535
Ref: 300c8347535
Ref: library/chunk chunk Chunk getsize8347642
Ref: 300d8347642
Ref: library/chunk chunk Chunk close8347707
Ref: 300e8347707
Ref: library/chunk chunk Chunk isatty8348043
Ref: 300f8348043
Ref: library/chunk chunk Chunk seek8348104
Ref: 30108348104
Ref: library/chunk chunk Chunk tell8348468
Ref: 30118348468
Ref: library/chunk chunk Chunk read8348539
Ref: 30128348539
Ref: library/chunk chunk Chunk skip8348904
Ref: 30138348904
Ref: chunk --- 读取 IFF 分块数据-Footnote-18349212
Ref: chunk --- 读取 IFF 分块数据-Footnote-28349276
Node: colorsys --- 颜色系统间的转换8349377
Ref: library/colorsys doc8349546
Ref: 30148349546
Ref: library/colorsys colorsys-conversions-between-color-systems8349546
Ref: 30158349546
Ref: library/colorsys module-colorsys8349546
Ref: 208349546
Ref: library/colorsys colorsys rgb_to_yiq8350435
Ref: 30168350435
Ref: library/colorsys colorsys yiq_to_rgb8350518
Ref: 30178350518
Ref: library/colorsys colorsys rgb_to_hls8350601
Ref: 30188350601
Ref: library/colorsys colorsys hls_to_rgb8350684
Ref: 30198350684
Ref: library/colorsys colorsys rgb_to_hsv8350767
Ref: 301a8350767
Ref: library/colorsys colorsys hsv_to_rgb8350850
Ref: 301b8350850
Ref: colorsys --- 颜色系统间的转换-Footnote-18351134
Node: imghdr --- 推测图像类型8351201
Ref: library/imghdr doc8351375
Ref: 301c8351375
Ref: library/imghdr imghdr-determine-the-type-of-an-image8351375
Ref: 301d8351375
Ref: library/imghdr module-imghdr8351375
Ref: 998351375
Ref: library/imghdr imghdr what8351672
Ref: 6f68351672
Ref: library/imghdr imghdr tests8353362
Ref: 301e8353362
Ref: imghdr --- 推测图像类型-Footnote-18353841
Node: sndhdr --- 推测声音文件的类型8353906
Ref: library/sndhdr doc8354089
Ref: 301f8354089
Ref: library/sndhdr module-sndhdr8354089
Ref: ef8354089
Ref: library/sndhdr sndhdr-determine-type-of-sound-file8354089
Ref: 30208354089
Ref: library/sndhdr sndhdr what8355226
Ref: 7508355226
Ref: library/sndhdr sndhdr whathdr8355503
Ref: 7518355503
Ref: sndhdr --- 推测声音文件的类型-Footnote-18355841
Node: ossaudiodev --- 访问兼容OSS的音频设备8355906
Ref: library/ossaudiodev doc8356051
Ref: 30218356051
Ref: library/ossaudiodev module-ossaudiodev8356051
Ref: c78356051
Ref: library/ossaudiodev ossaudiodev-access-to-oss-compatible-audio-devices8356051
Ref: 30228356051
Ref: library/ossaudiodev ossaudiodev OSSAudioError8356818
Ref: 30238356818
Ref: library/ossaudiodev ossaudiodev open8357334
Ref: 30248357334
Ref: library/ossaudiodev ossaudiodev openmixer8358729
Ref: 30258358729
Ref: ossaudiodev --- 访问兼容OSS的音频设备-Footnote-18359165
Node: Audio Device Objects8359213
Ref: library/ossaudiodev audio-device-objects8359345
Ref: 30268359345
Ref: library/ossaudiodev ossaudio-device-objects8359345
Ref: 30278359345
Ref: library/ossaudiodev ossaudiodev oss_audio_device close8359937
Ref: 30288359937
Ref: library/ossaudiodev ossaudiodev oss_audio_device fileno8360161
Ref: 30298360161
Ref: library/ossaudiodev ossaudiodev oss_audio_device read8360262
Ref: 302a8360262
Ref: library/ossaudiodev ossaudiodev oss_audio_device write8360570
Ref: 302b8360570
Ref: library/ossaudiodev ossaudiodev oss_audio_device writeall8361077
Ref: 302c8361077
Ref: library/ossaudiodev ossaudiodev oss_audio_device nonblock8362221
Ref: 302d8362221
Ref: library/ossaudiodev ossaudiodev oss_audio_device getfmts8362388
Ref: 302e8362388
Ref: library/ossaudiodev ossaudiodev oss_audio_device setfmt8364555
Ref: 302f8364555
Ref: library/ossaudiodev ossaudiodev oss_audio_device channels8364922
Ref: 30308364922
Ref: library/ossaudiodev ossaudiodev oss_audio_device speed8365250
Ref: 30318365250
Ref: library/ossaudiodev ossaudiodev oss_audio_device sync8365965
Ref: 30328365965
Ref: library/ossaudiodev ossaudiodev oss_audio_device reset8366248
Ref: 30338366248
Ref: library/ossaudiodev ossaudiodev oss_audio_device post8366512
Ref: 30348366512
Ref: library/ossaudiodev ossaudiodev oss_audio_device setparameters8366925
Ref: 30358366925
Ref: library/ossaudiodev ossaudiodev oss_audio_device bufsize8367988
Ref: 30368367988
Ref: library/ossaudiodev ossaudiodev oss_audio_device obufcount8368088
Ref: 30378368088
Ref: library/ossaudiodev ossaudiodev oss_audio_device obuffree8368222
Ref: 30388368222
Ref: library/ossaudiodev ossaudiodev oss_audio_device closed8368447
Ref: 30398368447
Ref: library/ossaudiodev ossaudiodev oss_audio_device name8368545
Ref: 303a8368545
Ref: library/ossaudiodev ossaudiodev oss_audio_device mode8368633
Ref: 303b8368633
Node: Mixer Device Objects8368745
Ref: library/ossaudiodev id18368877
Ref: 303c8368877
Ref: library/ossaudiodev mixer-device-objects8368877
Ref: 303d8368877
Ref: library/ossaudiodev ossaudiodev oss_mixer_device close8368988
Ref: 303e8368988
Ref: library/ossaudiodev ossaudiodev oss_mixer_device fileno8369189
Ref: 303f8369189
Ref: library/ossaudiodev ossaudiodev oss_mixer_device controls8369430
Ref: 30408369430
Ref: library/ossaudiodev ossaudiodev oss_mixer_device stereocontrols8370400
Ref: 30418370400
Ref: library/ossaudiodev ossaudiodev oss_mixer_device reccontrols8370845
Ref: 30428370845
Ref: library/ossaudiodev ossaudiodev oss_mixer_device get8371074
Ref: 30438371074
Ref: library/ossaudiodev ossaudiodev oss_mixer_device set8371569
Ref: 30448371569
Ref: library/ossaudiodev ossaudiodev oss_mixer_device get_recsrc8372132
Ref: 30458372132
Ref: library/ossaudiodev ossaudiodev oss_mixer_device set_recsrc8372293
Ref: 30468372293
Node: 国际化8372690
Ref: library/i18n doc8372797
Ref: 30478372797
Ref: library/i18n i18n8372797
Ref: 30488372797
Ref: library/i18n internationalization8372797
Ref: 30498372797
Node: gettext --- 多语种国际化服务8373196
Ref: library/gettext doc8373313
Ref: 304a8373313
Ref: library/gettext gettext-multilingual-internationalization-services8373313
Ref: 304b8373313
Ref: library/gettext module-gettext8373313
Ref: 898373313
Ref: gettext --- 多语种国际化服务-Footnote-18374216
Node: GNU gettext API8374282
Ref: library/gettext gnu-gettext-api8374395
Ref: 304c8374395
Ref: library/gettext gettext bindtextdomain8374887
Ref: 304d8374887
Ref: library/gettext gettext bind_textdomain_codeset8375446
Ref: 2988375446
Ref: library/gettext gettext textdomain8375854
Ref: 304f8375854
Ref: library/gettext gettext gettext8376081
Ref: dd58376081
Ref: library/gettext gettext dgettext8376317
Ref: 30508376317
Ref: library/gettext gettext ngettext8376452
Ref: 30518376452
Ref: library/gettext gettext dngettext8377115
Ref: 30528377115
Ref: library/gettext gettext pgettext8377270
Ref: 1d08377270
Ref: library/gettext gettext dpgettext8377319
Ref: 30538377319
Ref: library/gettext gettext npgettext8377377
Ref: 30548377377
Ref: library/gettext gettext dnpgettext8377439
Ref: 30558377439
Ref: library/gettext gettext lgettext8377751
Ref: 2948377751
Ref: library/gettext gettext ldgettext8377791
Ref: 2958377791
Ref: library/gettext gettext lngettext8377840
Ref: 2968377840
Ref: library/gettext gettext ldngettext8377893
Ref: 2978377893
Ref: GNU gettext API-Footnote-18379211
Ref: GNU gettext API-Footnote-28379689
Node: 基于类的 API8379754
Ref: library/gettext class-based-api8379912
Ref: 30568379912
Ref: library/gettext gettext find8380412
Ref: 30588380412
Ref: library/gettext gettext translation8381769
Ref: 29b8381769
Ref: library/gettext gettext install8383194
Ref: 29c8383194
Ref: 基于类的 API-Footnote-18384146
Node: NullTranslations 类8384214
Ref: library/gettext the-nulltranslations-class8384315
Ref: 305d8384315
Ref: library/gettext gettext NullTranslations8384692
Ref: 305b8384692
Ref: library/gettext gettext NullTranslations _parse8385099
Ref: 305f8385099
Ref: library/gettext gettext NullTranslations add_fallback8385387
Ref: 305e8385387
Ref: library/gettext gettext NullTranslations gettext8385600
Ref: 30608385600
Ref: library/gettext gettext NullTranslations ngettext8385774
Ref: 30618385774
Ref: library/gettext gettext NullTranslations pgettext8386008
Ref: 30628386008
Ref: library/gettext gettext NullTranslations npgettext8386235
Ref: 30638386235
Ref: library/gettext gettext NullTranslations lgettext8386477
Ref: 30598386477
Ref: library/gettext gettext NullTranslations lngettext8386514
Ref: 305a8386514
Ref: library/gettext gettext NullTranslations info8387039
Ref: 30648387039
Ref: library/gettext gettext NullTranslations charset8387219
Ref: 30658387219
Ref: library/gettext gettext NullTranslations output_charset8387296
Ref: 2998387296
Ref: library/gettext gettext NullTranslations set_output_charset8387519
Ref: 29a8387519
Ref: library/gettext gettext NullTranslations install8387688
Ref: 305c8387688
Node: GNUTranslations 类8388840
Ref: library/gettext the-gnutranslations-class8388976
Ref: 30668388976
Ref: library/gettext gettext GNUTranslations8390454
Ref: 30578390454
Ref: library/gettext gettext GNUTranslations gettext8390540
Ref: 30678390540
Ref: library/gettext gettext GNUTranslations ngettext8390889
Ref: 30688390889
Ref: library/gettext gettext GNUTranslations pgettext8391714
Ref: 30698391714
Ref: library/gettext gettext GNUTranslations npgettext8392128
Ref: 306a8392128
Ref: library/gettext gettext GNUTranslations lgettext8392646
Ref: 306b8392646
Ref: library/gettext gettext GNUTranslations lngettext8392683
Ref: 306c8392683
Ref: GNUTranslations 类-Footnote-18393217
Node: Solaris 消息编目支持8393265
Ref: library/gettext solaris-message-catalog-support8393396
Ref: 306d8393396
Node: 编目构造器8393611
Ref: library/gettext the-catalog-constructor8393714
Ref: 306e8393714
Node: 国际化 I18N 你的程序和模块8394314
Ref: library/gettext internationalizing-your-programs-and-modules8394466
Ref: 306f8394466
Ref: 国际化 I18N 你的程序和模块-Footnote-18397604
Ref: 国际化 I18N 你的程序和模块-Footnote-28397636
Node: 本地化你的模块8397679
Ref: library/gettext localizing-your-module8397809
Ref: 30708397809
Node: 本地化你的应用程序8398322
Ref: library/gettext localizing-your-application8398479
Ref: 30718398479
Node: 即时更改语言8399132
Ref: library/gettext changing-languages-on-the-fly8399280
Ref: 30728399280
Node: 延迟翻译8399905
Ref: library/gettext deferred-translations8400017
Ref: 30738400017
Node: 致谢<9>8402066
Ref: library/gettext acknowledgements8402193
Ref: 30748402193
Node: locale --- 国际化服务8402535
Ref: library/locale doc8402652
Ref: 30758402652
Ref: library/locale locale-internationalization-services8402652
Ref: 30768402652
Ref: library/locale module-locale8402652
Ref: aa8402652
Ref: library/locale locale Error8403347
Ref: 30778403347
Ref: library/locale locale setlocale8403471
Ref: 20198403471
Ref: library/locale locale localeconv8404656
Ref: 4928404656
Ref: library/locale locale nl_langinfo8411736
Ref: 307b8411736
Ref: library/locale locale CODESET8412255
Ref: 307c8412255
Ref: library/locale locale D_T_FMT8412391
Ref: 307d8412391
Ref: library/locale locale D_FMT8412589
Ref: 307e8412589
Ref: library/locale locale T_FMT8412778
Ref: 307f8412778
Ref: library/locale locale T_FMT_AMPM8412967
Ref: 30808412967
Ref: library/locale locale RADIXCHAR8413677
Ref: 30818413677
Ref: library/locale locale THOUSEP8413783
Ref: 30828413783
Ref: library/locale locale YESEXPR8413905
Ref: 30838413905
Ref: library/locale locale NOEXPR8414293
Ref: 30848414293
Ref: library/locale locale CRNCYSTR8414480
Ref: 30858414480
Ref: library/locale locale ERA8414749
Ref: 30868414749
Ref: library/locale locale ERA_D_T_FMT8415525
Ref: 30878415525
Ref: library/locale locale ERA_D_FMT8415698
Ref: 30888415698
Ref: library/locale locale ERA_T_FMT8415862
Ref: 30898415862
Ref: library/locale locale ALT_DIGITS8416026
Ref: 308a8416026
Ref: library/locale locale getdefaultlocale8416162
Ref: 13708416162
Ref: library/locale locale getlocale8417367
Ref: 19048417367
Ref: library/locale locale getpreferredencoding8417842
Ref: 3ad8417842
Ref: library/locale locale normalize8418703
Ref: 308d8418703
Ref: library/locale locale resetlocale8419123
Ref: 308e8419123
Ref: library/locale locale strcoll8419371
Ref: 308f8419371
Ref: library/locale locale strxfrm8419688
Ref: 30918419688
Ref: library/locale locale format_string8420030
Ref: 3ac8420030
Ref: library/locale locale format8420719
Ref: 4708420719
Ref: library/locale locale currency8421169
Ref: 30928421169
Ref: library/locale locale str8421797
Ref: 30938421797
Ref: library/locale locale delocalize8421984
Ref: 7148421984
Ref: library/locale locale atof8422158
Ref: 30948422158
Ref: library/locale locale atoi8422297
Ref: 30958422297
Ref: library/locale locale LC_CTYPE8422426
Ref: 308c8422426
Ref: library/locale locale LC_COLLATE8422650
Ref: 30908422650
Ref: library/locale locale LC_TIME8422845
Ref: 30968422845
Ref: library/locale locale LC_MONETARY8422997
Ref: 307a8422997
Ref: library/locale locale LC_MESSAGES8423172
Ref: 30978423172
Ref: library/locale locale LC_NUMERIC8423472
Ref: 30788423472
Ref: library/locale locale LC_ALL8423790
Ref: 308b8423790
Ref: library/locale locale CHAR_MAX8424217
Ref: 30798424217
Ref: locale --- 国际化服务-Footnote-18425069
Ref: locale --- 国际化服务-Footnote-28425134
Ref: locale --- 国际化服务-Footnote-38425183
Node: Background details hints tips and caveats8425232
Ref: library/locale background-details-hints-tips-and-caveats8425397
Ref: 30988425397
Node: For extension writers and programs that embed Python8427595
Ref: library/locale embedding-locale8427795
Ref: 30998427795
Ref: library/locale for-extension-writers-and-programs-that-embed-python8427795
Ref: 309a8427795
Node: Access to message catalogs8428593
Ref: library/locale access-to-message-catalogs8428743
Ref: 309b8428743
Ref: library/locale locale-gettext8428743
Ref: 309c8428743
Ref: library/locale locale gettext8428816
Ref: 309d8428816
Ref: library/locale locale dgettext8428850
Ref: 309e8428850
Ref: library/locale locale dcgettext8428893
Ref: 309f8428893
Ref: library/locale locale textdomain8428947
Ref: 30a08428947
Ref: library/locale locale bindtextdomain8428987
Ref: 30a18428987
Node: 程序框架8429917
Ref: library/frameworks doc8430033
Ref: 30a28430033
Ref: library/frameworks frameworks8430033
Ref: 30a38430033
Ref: library/frameworks program-frameworks8430033
Ref: 30a48430033
Node: turtle --- 海龟绘图8430459
Ref: library/turtle doc8430581
Ref: 30a58430581
Ref: library/turtle module-turtle8430581
Ref: 1178430581
Ref: library/turtle turtle-turtle-graphics8430581
Ref: 30a68430581
Ref: turtle --- 海龟绘图-Footnote-18431158
Node: 概述<12>8431223
Ref: library/turtle introduction8431342
Ref: 30a78431342
Node: 可用的 Turtle 和 Screen 方法概览8434673
Ref: library/turtle overview-of-available-turtle-and-screen-methods8434839
Ref: 30ae8434839
Node: Turtle 方法8434991
Ref: library/turtle turtle-methods8435116
Ref: 30af8435116
Node: TurtleScreen/Screen 方法8438902
Ref: library/turtle methods-of-turtlescreen-screen8439027
Ref: 30ff8439027
Node: RawTurtle/Turtle 方法和对应函数8440730
Ref: library/turtle methods-of-rawturtle-turtle-and-corresponding-functions8440927
Ref: 311e8440927
Node: 海龟动作8441276
Ref: library/turtle turtle-motion8441393
Ref: 311f8441393
Ref: library/turtle turtle forward8441434
Ref: 30b08441434
Ref: library/turtle turtle fd8441472
Ref: 30b18441472
Ref: library/turtle turtle back8441883
Ref: 30b48441883
Ref: library/turtle turtle bk8441918
Ref: 30b38441918
Ref: library/turtle turtle backward8441951
Ref: 30b28441951
Ref: library/turtle turtle right8442298
Ref: 30b58442298
Ref: library/turtle turtle rt8442331
Ref: 30b68442331
Ref: library/turtle turtle left8442782
Ref: 30b78442782
Ref: library/turtle turtle lt8442814
Ref: 30b88442814
Ref: library/turtle turtle goto8443263
Ref: 30b98443263
Ref: library/turtle turtle setpos8443299
Ref: 30ba8443299
Ref: library/turtle turtle setposition8443337
Ref: 30bb8443337
Ref: library/turtle turtle setx8444103
Ref: 30bc8444103
Ref: library/turtle turtle sety8444402
Ref: 30bd8444402
Ref: library/turtle turtle setheading8444700
Ref: 30be8444700
Ref: library/turtle turtle seth8444741
Ref: 30bf8444741
Ref: library/turtle turtle home8445549
Ref: 30c08445549
Ref: library/turtle turtle circle8445938
Ref: 30c18445938
Ref: library/turtle turtle dot8447244
Ref: 30c28447244
Ref: library/turtle turtle stamp8447815
Ref: 30c38447815
Ref: library/turtle turtle clearstamp8448105
Ref: 30c48448105
Ref: library/turtle turtle clearstamps8448614
Ref: 30c58448614
Ref: library/turtle turtle undo8449217
Ref: 30c68449217
Ref: library/turtle turtle speed8449540
Ref: 30c78449540
Node: 获取海龟的状态8450493
Ref: library/turtle tell-turtle-s-state8450637
Ref: 31218450637
Ref: library/turtle turtle position8450693
Ref: 30c88450693
Ref: library/turtle turtle pos8450724
Ref: 30c98450724
Ref: library/turtle turtle towards8450888
Ref: 30ca8450888
Ref: library/turtle turtle xcor8451414
Ref: 30cb8451414
Ref: library/turtle turtle ycor8451684
Ref: 30cc8451684
Ref: library/turtle turtle heading8451961
Ref: 30cd8451961
Ref: library/turtle turtle distance8452190
Ref: 30ce8452190
Node: 度量单位设置8452754
Ref: library/turtle settings-for-measurement8452898
Ref: 31228452898
Ref: library/turtle turtle degrees8452949
Ref: 30cf8452949
Ref: library/turtle turtle radians8453550
Ref: 30d08453550
Node: 画笔控制8453863
Ref: library/turtle pen-control8453998
Ref: 31238453998
Node: 绘图状态8454117
Ref: library/turtle drawing-state8454199
Ref: 31248454199
Ref: library/turtle turtle pendown8454242
Ref: 30d18454242
Ref: library/turtle turtle pd8454272
Ref: 30d28454272
Ref: library/turtle turtle down8454297
Ref: 30d38454297
Ref: library/turtle turtle penup8454370
Ref: 30d48454370
Ref: library/turtle turtle pu8454398
Ref: 30d58454398
Ref: library/turtle turtle up8454423
Ref: 30d68454423
Ref: library/turtle turtle pensize8454494
Ref: 30d78454494
Ref: library/turtle turtle width8454534
Ref: 30d88454534
Ref: library/turtle turtle pen8454976
Ref: 30d98454976
Ref: library/turtle turtle isdown8456728
Ref: 30da8456728
Node: 颜色控制8456994
Ref: library/turtle color-control8457091
Ref: 31258457091
Ref: library/turtle turtle pencolor8457134
Ref: 30dc8457134
Ref: library/turtle turtle fillcolor8458670
Ref: 30dd8458670
Ref: library/turtle turtle color8460083
Ref: 30db8460083
Node: 填充8461269
Ref: library/turtle filling8461372
Ref: 31268461372
Ref: library/turtle turtle filling8461405
Ref: 30de8461405
Ref: library/turtle turtle begin_fill8461676
Ref: 30df8461676
Ref: library/turtle turtle end_fill8461759
Ref: 30e08461759
Node: 更多绘图控制8462271
Ref: library/turtle more-drawing-control8462353
Ref: 31278462353
Ref: library/turtle turtle write8462996
Ref: 30e38462996
Node: 海龟状态8463721
Ref: library/turtle turtle-state8463850
Ref: 31288463850
Node: 可见性8463928
Ref: library/turtle visibility8464001
Ref: 31298464001
Ref: library/turtle turtle hideturtle8464039
Ref: 30e68464039
Ref: library/turtle turtle ht8464072
Ref: 30e78464072
Ref: library/turtle turtle showturtle8464263
Ref: 30e48464263
Ref: library/turtle turtle st8464296
Ref: 30e58464296
Ref: library/turtle turtle isvisible8464382
Ref: 30e88464382
Node: 外观8464665
Ref: library/turtle appearance8464738
Ref: 312a8464738
Ref: library/turtle turtle shape8464771
Ref: 30e98464771
Ref: library/turtle turtle resizemode8465401
Ref: 30ea8465401
Ref: library/turtle turtle shapesize8466235
Ref: 30eb8466235
Ref: library/turtle turtle turtlesize8466325
Ref: 30ec8466325
Ref: library/turtle turtle shearfactor8467211
Ref: 30ed8467211
Ref: library/turtle turtle tilt8467786
Ref: 30f08467786
Ref: library/turtle turtle settiltangle8468210
Ref: 30ee8468210
Ref: library/turtle turtle tiltangle8468700
Ref: 30ef8468700
Ref: library/turtle turtle shapetransform8469304
Ref: 30f18469304
Ref: library/turtle turtle get_shapepoly8470280
Ref: 30f28470280
Node: 使用事件8470650
Ref: library/turtle using-events8470785
Ref: 312b8470785
Ref: library/turtle turtle onrelease8471616
Ref: 30f48471616
Ref: library/turtle turtle ondrag8472583
Ref: 30f58472583
Node: 特殊海龟方法8473351
Ref: library/turtle special-turtle-methods8473486
Ref: 312c8473486
Ref: library/turtle turtle begin_poly8473539
Ref: 30f68473539
Ref: library/turtle turtle end_poly8473664
Ref: 30f78473664
Ref: library/turtle turtle get_poly8473829
Ref: 30f88473829
Ref: library/turtle turtle clone8474229
Ref: 30f98474229
Ref: library/turtle turtle getturtle8474413
Ref: 30fa8474413
Ref: library/turtle turtle getpen8474445
Ref: 30fb8474445
Ref: library/turtle turtle getscreen8474693
Ref: 30fc8474693
Ref: library/turtle turtle setundobuffer8474987
Ref: 30fd8474987
Ref: library/turtle turtle undobufferentries8475419
Ref: 30fe8475419
Node: 复合形状8475573
Ref: library/turtle compound-shapes8475687
Ref: 312d8475687
Ref: library/turtle compoundshapes8475687
Ref: 312e8475687
Node: TurtleScreen/Screen 方法及对应函数8476648
Ref: library/turtle methods-of-turtlescreen-screen-and-corresponding-functions8476814
Ref: 31308476814
Node: 窗口控制8477223
Ref: library/turtle window-control8477334
Ref: 31318477334
Ref: library/turtle turtle bgcolor8477377
Ref: 31008477377
Ref: library/turtle turtle bgpic8477806
Ref: 31018477806
Ref: library/turtle turtle clear8478374
Ref: 30e28478374
Ref: library/turtle turtle clearscreen8478402
Ref: 31028478402
Ref: library/turtle turtle reset8478798
Ref: 30e18478798
Ref: library/turtle turtle resetscreen8478826
Ref: 31038478826
Ref: library/turtle turtle screensize8479111
Ref: 31048479111
Ref: library/turtle turtle setworldcoordinates8479963
Ref: 31058479963
Node: 动画控制8480848
Ref: library/turtle animation-control8480986
Ref: 31328480986
Ref: library/turtle turtle delay8481029
Ref: 31068481029
Ref: library/turtle turtle tracer8481414
Ref: 31078481414
Ref: library/turtle turtle update8482066
Ref: 31088482066
Node: 使用屏幕事件8482224
Ref: library/turtle using-screen-events8482362
Ref: 31338482362
Ref: library/turtle turtle listen8482415
Ref: 31098482415
Ref: library/turtle turtle onkey8482627
Ref: 310a8482627
Ref: library/turtle turtle onkeyrelease8482663
Ref: 310b8482663
Ref: library/turtle turtle onkeypress8483273
Ref: 310c8483273
Ref: library/turtle turtle onclick8483843
Ref: 30f38483843
Ref: library/turtle turtle onscreenclick8483893
Ref: 310d8483893
Ref: library/turtle turtle ontimer8484982
Ref: 310e8484982
Ref: library/turtle turtle mainloop8485467
Ref: 310f8485467
Ref: library/turtle turtle done8485498
Ref: 31108485498
Node: 输入方法8485832
Ref: library/turtle input-methods8485979
Ref: 31348485979
Ref: library/turtle turtle textinput8486022
Ref: ea68486022
Ref: library/turtle turtle numinput8486477
Ref: ea78486477
Node: 设置与特殊方法8487354
Ref: library/turtle settings-and-special-methods8487531
Ref: 31358487531
Ref: library/turtle turtle mode8487589
Ref: 31118487589
Ref: library/turtle turtle colormode8488765
Ref: 31128488765
Ref: library/turtle turtle getcanvas8489394
Ref: 31138489394
Ref: library/turtle turtle getshapes8489649
Ref: 31148489649
Ref: library/turtle turtle register_shape8489825
Ref: 31158489825
Ref: library/turtle turtle addshape8489878
Ref: 31168489878
Ref: library/turtle turtle turtles8490777
Ref: 31178490777
Ref: library/turtle turtle window_height8490933
Ref: 31188490933
Ref: library/turtle turtle window_width8491060
Ref: 31198491060
Node: Screen 专有方法 而非继承自 TurtleScreen8491185
Ref: library/turtle methods-specific-to-screen-not-inherited-from-turtlescreen8491341
Ref: 31368491341
Ref: library/turtle screenspecific8491341
Ref: 31378491341
Ref: library/turtle turtle bye8491453
Ref: 311a8491453
Ref: library/turtle turtle exitonclick8491514
Ref: 311b8491514
Ref: library/turtle turtle setup8491948
Ref: 311c8491948
Ref: library/turtle turtle title8493246
Ref: 311d8493246
Node: 公共类8493512
Ref: library/turtle public-classes8493655
Ref: 31388493655
Ref: library/turtle turtle RawTurtle8493693
Ref: 30ab8493693
Ref: library/turtle turtle RawPen8493728
Ref: 30ac8493728
Ref: library/turtle turtle Turtle8494005
Ref: 30ad8494005
Ref: library/turtle turtle TurtleScreen8494183
Ref: 30a88494183
Ref: library/turtle turtle Screen8494363
Ref: 30aa8494363
Ref: library/turtle turtle ScrolledCanvas8494453
Ref: 30a98494453
Ref: library/turtle turtle Shape8494730
Ref: 312f8494730
Ref: library/turtle turtle Shape addcomponent8495471
Ref: 31398495471
Ref: library/turtle turtle Vec2D8496102
Ref: 31208496102
Node: 帮助与配置8496597
Ref: library/turtle help-and-configuration8496729
Ref: 313a8496729
Node: 如何使用帮助8496889
Ref: library/turtle how-to-use-help8497007
Ref: 313b8497007
Node: 文档字符串翻译为不同的语言8499251
Ref: library/turtle translation-of-docstrings-into-different-languages8499408
Ref: 313c8499408
Ref: library/turtle turtle write_docstringdict8499614
Ref: 313d8499614
Node: 如何配置 Screen 和 Turtle8500560
Ref: library/turtle how-to-configure-screen-and-turtles8500690
Ref: 313e8500690
Node: turtledemo --- 演示脚本集8503227
Ref: library/turtle module-turtledemo8503376
Ref: 1188503376
Ref: library/turtle turtledemo-demo-scripts8503376
Ref: 313f8503376
Node: Python 2 6 之后的变化8508800
Ref: library/turtle changes-since-python-2-68508960
Ref: 31408508960
Node: Python 3 0 之后的变化8509847
Ref: library/turtle changes-since-python-3-08509968
Ref: 31418509968
Node: cmd --- 支持面向行的命令解释器8511031
Ref: library/cmd doc8511195
Ref: 31428511195
Ref: library/cmd cmd-support-for-line-oriented-command-interpreters8511195
Ref: 31438511195
Ref: library/cmd module-cmd8511195
Ref: 1a8511195
Ref: library/cmd cmd Cmd8511586
Ref: 31448511586
Ref: cmd --- 支持面向行的命令解释器-Footnote-18512643
Node: Cmd 对象8512705
Ref: library/cmd cmd-objects8512812
Ref: 31468512812
Ref: library/cmd id18512812
Ref: 31478512812
Ref: library/cmd cmd Cmd cmdloop8512894
Ref: 31488512894
Ref: library/cmd cmd Cmd onecmd8515115
Ref: 314b8515115
Ref: library/cmd cmd Cmd emptyline8515623
Ref: 314e8515623
Ref: library/cmd cmd Cmd default8515789
Ref: 314d8515789
Ref: library/cmd cmd Cmd completedefault8515975
Ref: 314f8515975
Ref: library/cmd cmd Cmd precmd8516193
Ref: 314c8516193
Ref: library/cmd cmd Cmd postcmd8516598
Ref: 314a8516598
Ref: library/cmd cmd Cmd preloop8517106
Ref: 31508517106
Ref: library/cmd cmd Cmd postloop8517299
Ref: 31518517299
Ref: library/cmd cmd Cmd prompt8517582
Ref: 31528517582
Ref: library/cmd cmd Cmd identchars8517643
Ref: 31538517643
Ref: library/cmd cmd Cmd lastcmd8517711
Ref: 31548517711
Ref: library/cmd cmd Cmd cmdqueue8517782
Ref: 31558517782
Ref: library/cmd cmd Cmd intro8518032
Ref: 31498518032
Ref: library/cmd cmd Cmd doc_header8518186
Ref: 31568518186
Ref: library/cmd cmd Cmd misc_header8518290
Ref: 31578518290
Ref: library/cmd cmd Cmd undoc_header8518469
Ref: 31588518469
Ref: library/cmd cmd Cmd ruler8518649
Ref: 31598518649
Ref: library/cmd cmd Cmd use_rawinput8518822
Ref: 31458518822
Node: Cmd 例子8519294
Ref: library/cmd cmd-example8519401
Ref: 315a8519401
Ref: library/cmd id28519401
Ref: 315b8519401
Node: shlex --- Simple lexical analysis8524630
Ref: library/shlex doc8524762
Ref: 315c8524762
Ref: library/shlex module-shlex8524762
Ref: e98524762
Ref: library/shlex shlex-simple-lexical-analysis8524762
Ref: 315d8524762
Ref: library/shlex shlex split8525283
Ref: 2198525283
Ref: library/shlex shlex join8525938
Ref: 2188525938
Ref: library/shlex shlex quote8526390
Ref: a7b8526390
Ref: library/shlex shlex shlex8527688
Ref: 5838527688
Ref: shlex --- Simple lexical analysis-Footnote-18529912
Node: shlex Objects8529976
Ref: library/shlex id18530081
Ref: 31618530081
Ref: library/shlex shlex-objects8530081
Ref: 31628530081
Ref: library/shlex shlex shlex get_token8530185
Ref: 31638530185
Ref: library/shlex shlex shlex push_token8530548
Ref: 31648530548
Ref: library/shlex shlex shlex read_token8530630
Ref: 31668530630
Ref: library/shlex shlex shlex sourcehook8530869
Ref: 31678530869
Ref: library/shlex shlex shlex push_source8532409
Ref: 31698532409
Ref: library/shlex shlex shlex pop_source8532712
Ref: 316a8532712
Ref: library/shlex shlex shlex error_leader8532911
Ref: 316b8532911
Ref: library/shlex shlex shlex commenters8533640
Ref: 315e8533640
Ref: library/shlex shlex shlex wordchars8533859
Ref: 31608533859
Ref: library/shlex shlex shlex whitespace8534551
Ref: 316d8534551
Ref: library/shlex shlex shlex escape8534746
Ref: 316e8534746
Ref: library/shlex shlex shlex quotes8534908
Ref: 316f8534908
Ref: library/shlex shlex shlex escapedquotes8535190
Ref: 31708535190
Ref: library/shlex shlex shlex whitespace_split8535416
Ref: 316c8535416
Ref: library/shlex shlex shlex infile8535939
Ref: 315f8535939
Ref: library/shlex shlex shlex instream8536167
Ref: 31718536167
Ref: library/shlex shlex shlex source8536289
Ref: 31688536289
Ref: library/shlex shlex shlex debug8536876
Ref: 31728536876
Ref: library/shlex shlex shlex lineno8537137
Ref: 31738537137
Ref: library/shlex shlex shlex token8537230
Ref: 31748537230
Ref: library/shlex shlex shlex eof8537344
Ref: 31658537344
Ref: library/shlex shlex shlex punctuation_chars8537517
Ref: f8c8537517
Node: Parsing Rules8537921
Ref: library/shlex parsing-rules8538069
Ref: 31758538069
Ref: library/shlex shlex-parsing-rules8538069
Ref: 31768538069
Node: Improved Compatibility with Shells8540088
Ref: library/shlex improved-compatibility-with-shells8540214
Ref: 31778540214
Ref: library/shlex improved-shell-compatibility8540214
Ref: 5848540214
Node: Tk图形用户界面 GUI8543057
Ref: library/tk doc8543176
Ref: 31788543176
Ref: library/tk graphical-user-interfaces-with-tk8543176
Ref: 31798543176
Ref: library/tk tkinter8543176
Ref: 317a8543176
Node: tkinter --- Tcl/Tk的Python接口8544718
Ref: library/tkinter doc8544854
Ref: 317c8544854
Ref: library/tkinter module-tkinter8544854
Ref: 10d8544854
Ref: library/tkinter tkinter-python-interface-to-tcl-tk8544854
Ref: 317d8544854
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-18547227
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-28547303
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-38547348
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-48547379
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-58547419
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-68547458
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-78547509
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-88547595
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-98547664
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-108547721
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-118547754
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-128547778
Node: Tkinter 模块8547838
Ref: library/tkinter tkinter-modules8547953
Ref: 317e8547953
Ref: library/tkinter tkinter Tk8548726
Ref: 317f8548726
Ref: library/tkinter tkinter Tcl8549000
Ref: 31808549000
Node: Tkinter Life Preserver8550413
Ref: library/tkinter tkinter-life-preserver8550564
Ref: 31818550564
Node: How To Use This Section8551458
Ref: library/tkinter how-to-use-this-section8551577
Ref: 31828551577
Node: A Simple Hello World Program8553009
Ref: library/tkinter a-simple-hello-world-program8553128
Ref: 31838553128
Node: A Very Quick Look at Tcl/Tk8554000
Ref: library/tkinter a-very-quick-look-at-tcl-tk8554166
Ref: 31848554166
Node: Mapping Basic Tk into Tkinter8557510
Ref: library/tkinter mapping-basic-tk-into-tkinter8557684
Ref: 31868557684
Ref: library/tkinter tkinter-basic-mapping8557684
Ref: 31858557684
Node: How Tk and Tkinter are Related8559506
Ref: library/tkinter how-tk-and-tkinter-are-related8559668
Ref: 31888559668
Node: Handy Reference8560940
Ref: library/tkinter handy-reference8561086
Ref: 31898561086
Node: Setting Options8561338
Ref: library/tkinter setting-options8561424
Ref: 318a8561424
Ref: library/tkinter tkinter-setting-options8561424
Ref: 31878561424
Node: The Packer8564646
Ref: library/tkinter the-packer8564755
Ref: 318b8564755
Node: Packer Options8566401
Ref: library/tkinter packer-options8566520
Ref: 318c8566520
Node: Coupling Widget Variables8567220
Ref: library/tkinter coupling-widget-variables8567347
Ref: 318d8567347
Node: The Window Manager8569543
Ref: library/tkinter the-window-manager8569676
Ref: 318e8569676
Node: Tk Option Data Types8571070
Ref: library/tkinter tk-option-data-types8571197
Ref: 318f8571197
Node: Bindings and Events8574270
Ref: library/tkinter bindings-and-events8574398
Ref: 31908574398
Node: The index Parameter8577140
Ref: library/tkinter the-index-parameter8577254
Ref: 31918577254
Node: Images8579185
Ref: library/tkinter images8579271
Ref: 31928579271
Ref: Images-Footnote-18580199
Node: File Handlers8580233
Ref: library/tkinter file-handlers8580340
Ref: 31938580340
Ref: library/tkinter tkinter-file-handlers8580340
Ref: 31948580340
Ref: library/tkinter tkinter Widget tk createfilehandler8581282
Ref: 31958581282
Ref: library/tkinter tkinter Widget tk deletefilehandler8581717
Ref: 31968581717
Ref: library/tkinter tkinter READABLE8581799
Ref: 31978581799
Ref: library/tkinter tkinter WRITABLE8581828
Ref: 31988581828
Ref: library/tkinter tkinter EXCEPTION8581857
Ref: 31998581857
Node: tkinter ttk --- Tk主题小部件8581934
Ref: library/tkinter ttk doc8582106
Ref: 319a8582106
Ref: library/tkinter ttk module-tkinter ttk8582106
Ref: 1108582106
Ref: library/tkinter ttk tkinter-ttk-tk-themed-widgets8582106
Ref: 319b8582106
Ref: tkinter ttk --- Tk主题小部件-Footnote-18583147
Ref: tkinter ttk --- Tk主题小部件-Footnote-28583217
Node: 使用 Ttk8583270
Ref: library/tkinter ttk using-ttk8583369
Ref: 319c8583369
Ref: 使用 Ttk-Footnote-18584477
Node: Ttk 部件8584540
Ref: library/tkinter ttk ttk-widgets8584654
Ref: 319d8584654
Node: 控件8585763
Ref: library/tkinter ttk widget8585876
Ref: 31a48585876
Node: 标准选项8586148
Ref: library/tkinter ttk standard-options8586233
Ref: 31a58586233
Node: 可滚动控件选项8587583
Ref: library/tkinter ttk scrollable-widget-options8587689
Ref: 31a68587689
Node: 标签选项8588642
Ref: library/tkinter ttk label-options8588751
Ref: 31a78588751
Node: 兼容性选项8591215
Ref: library/tkinter ttk compatibility-options8591315
Ref: 31a88591315
Node: 控件状态8591821
Ref: library/tkinter ttk widget-states8591919
Ref: 31aa8591919
Node: ttk Widget8593560
Ref: library/tkinter ttk ttk-widget8593634
Ref: 31ab8593634
Ref: library/tkinter ttk tkinter ttk Widget8593821
Ref: 31a18593821
Ref: library/tkinter ttk tkinter ttk Widget identify8593850
Ref: 31ac8593850
Ref: library/tkinter ttk tkinter ttk Widget instate8594093
Ref: 31ad8594093
Ref: library/tkinter ttk tkinter ttk Widget state8594437
Ref: 31a98594437
Node: 组合框8594825
Ref: library/tkinter ttk combobox8594935
Ref: 31ae8594935
Node: 选项8595626
Ref: library/tkinter ttk options8595699
Ref: 31af8595699
Node: 虚拟事件8598171
Ref: library/tkinter ttk virtual-events8598265
Ref: 31b08598265
Node: ttk Combobox8598437
Ref: library/tkinter ttk ttk-combobox8598516
Ref: 31b18598516
Ref: library/tkinter ttk tkinter ttk Combobox8598563
Ref: 319e8598563
Ref: library/tkinter ttk tkinter ttk Combobox current8598594
Ref: 31b28598594
Ref: library/tkinter ttk tkinter ttk Combobox get8598870
Ref: 31b38598870
Ref: library/tkinter ttk tkinter ttk Combobox set8598949
Ref: 31b48598949
Node: Spinbox8599033
Ref: library/tkinter ttk spinbox8599146
Ref: 31b58599146
Node: 选项<2>8599900
Ref: library/tkinter ttk id18599977
Ref: 31b68599977
Node: 虚拟事件<2>8602359
Ref: library/tkinter ttk id28602456
Ref: 31b78602456
Node: ttk Spinbox8602656
Ref: library/tkinter ttk ttk-spinbox8602735
Ref: 31b88602735
Ref: library/tkinter ttk tkinter ttk Spinbox8602780
Ref: 4058602780
Ref: library/tkinter ttk tkinter ttk Spinbox get8602810
Ref: 31b98602810
Ref: library/tkinter ttk tkinter ttk Spinbox set8602869
Ref: 31ba8602869
Node: 笔记本8602941
Ref: library/tkinter ttk notebook8603056
Ref: 31bb8603056
Node: 选项<3>8603412
Ref: library/tkinter ttk id38603486
Ref: 31bc8603486
Node: Tab 选项8604656
Ref: library/tkinter ttk tab-options8604754
Ref: 31bd8604754
Node: Tab Identifiers8606795
Ref: library/tkinter ttk tab-identifiers8606898
Ref: 31bf8606898
Node: Virtual Events8607420
Ref: library/tkinter ttk id48607525
Ref: 31c18607525
Node: ttk Notebook8607669
Ref: library/tkinter ttk ttk-notebook8607750
Ref: 31c28607750
Ref: library/tkinter ttk tkinter ttk Notebook8607797
Ref: 319f8607797
Ref: library/tkinter ttk tkinter ttk Notebook add8607828
Ref: 31c38607828
Ref: library/tkinter ttk tkinter ttk Notebook forget8608113
Ref: 31c48608113
Ref: library/tkinter ttk tkinter ttk Notebook hide8608251
Ref: 31c58608251
Ref: library/tkinter ttk tkinter ttk Notebook identify8608561
Ref: 31c68608561
Ref: library/tkinter ttk tkinter ttk Notebook index8608703
Ref: 31c08608703
Ref: library/tkinter ttk tkinter ttk Notebook insert8608878
Ref: 31c78608878
Ref: library/tkinter ttk tkinter ttk Notebook select8609259
Ref: 31c88609259
Ref: library/tkinter ttk tkinter ttk Notebook tab8609573
Ref: 31c98609573
Ref: library/tkinter ttk tkinter ttk Notebook tabs8609919
Ref: 31ca8609919
Ref: library/tkinter ttk tkinter ttk Notebook enable_traversal8610007
Ref: 31be8610007
Node: Progressbar8610834
Ref: library/tkinter ttk progressbar8610951
Ref: 31cb8610951
Node: 选项<4>8611390
Ref: library/tkinter ttk id58611471
Ref: 31cc8611471
Node: ttk Progressbar8613314
Ref: library/tkinter ttk ttk-progressbar8613395
Ref: 31cd8613395
Ref: library/tkinter ttk tkinter ttk Progressbar8613448
Ref: 31a08613448
Ref: library/tkinter ttk tkinter ttk Progressbar start8613482
Ref: 31ce8613482
Ref: library/tkinter ttk tkinter ttk Progressbar step8613750
Ref: 31cf8613750
Ref: library/tkinter ttk tkinter ttk Progressbar stop8613897
Ref: 31d08613897
Node: Separator8614082
Ref: library/tkinter ttk separator8614198
Ref: 31d18614198
Node: 选项<5>8614426
Ref: library/tkinter ttk id68614481
Ref: 31d28614481
Node: Sizegrip8614855
Ref: library/tkinter ttk sizegrip8614968
Ref: 31d38614968
Node: Platform-specific notes8615318
Ref: library/tkinter ttk platform-specific-notes8615399
Ref: 31d48615399
Node: Bugs8615657
Ref: library/tkinter ttk bugs8615738
Ref: 31d58615738
Node: Treeview8616007
Ref: library/tkinter ttk treeview8616122
Ref: 31d68616122
Node: 选项<6>8617478
Ref: library/tkinter ttk id78617553
Ref: 31da8617553
Node: Item Options8620156
Ref: library/tkinter ttk item-options8620251
Ref: 31db8620251
Node: Tag Options8621429
Ref: library/tkinter ttk tag-options8621533
Ref: 31dc8621533
Node: Column Identifiers8622264
Ref: library/tkinter ttk column-identifiers8622373
Ref: 31d78622373
Node: Virtual Events<2>8623242
Ref: library/tkinter ttk id88623352
Ref: 31dd8623352
Node: ttk Treeview8624249
Ref: library/tkinter ttk ttk-treeview8624332
Ref: 31df8624332
Ref: library/tkinter ttk tkinter ttk Treeview8624379
Ref: 2bd8624379
Ref: library/tkinter ttk tkinter ttk Treeview bbox8624410
Ref: 31e08624410
Ref: library/tkinter ttk tkinter ttk Treeview get_children8624847
Ref: 31e18624847
Ref: library/tkinter ttk tkinter ttk Treeview set_children8625013
Ref: 31e28625013
Ref: library/tkinter ttk tkinter ttk Treeview column8625405
Ref: 31e38625405
Ref: library/tkinter ttk tkinter ttk Treeview delete8626790
Ref: 31e48626790
Ref: library/tkinter ttk tkinter ttk Treeview detach8626936
Ref: 31e58626936
Ref: library/tkinter ttk tkinter ttk Treeview exists8627247
Ref: 31e68627247
Ref: library/tkinter ttk tkinter ttk Treeview focus8627357
Ref: 31de8627357
Ref: library/tkinter ttk tkinter ttk Treeview heading8627550
Ref: 31e78627550
Ref: library/tkinter ttk tkinter ttk Treeview identify8628647
Ref: 31e88628647
Ref: library/tkinter ttk tkinter ttk Treeview identify_row8628884
Ref: 31e98628884
Ref: library/tkinter ttk tkinter ttk Treeview identify_column8628979
Ref: 31ea8628979
Ref: library/tkinter ttk tkinter ttk Treeview identify_region8629140
Ref: 31eb8629140
Ref: library/tkinter ttk tkinter ttk Treeview identify_element8629776
Ref: 31ec8629776
Ref: library/tkinter ttk tkinter ttk Treeview index8629904
Ref: 31ed8629904
Ref: library/tkinter ttk tkinter ttk Treeview insert8630032
Ref: 31ee8630032
Ref: library/tkinter ttk tkinter ttk Treeview item8630925
Ref: 31ef8630925
Ref: library/tkinter ttk tkinter ttk Treeview move8631303
Ref: 31f08631303
Ref: library/tkinter ttk tkinter ttk Treeview next8631741
Ref: 31f18631741
Ref: library/tkinter ttk tkinter ttk Treeview parent8631896
Ref: 31f28631896
Ref: library/tkinter ttk tkinter ttk Treeview prev8632047
Ref: 31f38632047
Ref: library/tkinter ttk tkinter ttk Treeview reattach8632207
Ref: 31f48632207
Ref: library/tkinter ttk tkinter ttk Treeview see8632309
Ref: 31f58632309
Ref: library/tkinter ttk tkinter ttk Treeview selection8632565
Ref: 2be8632565
Ref: library/tkinter ttk tkinter ttk Treeview selection_set8632808
Ref: 2bf8632808
Ref: library/tkinter ttk tkinter ttk Treeview selection_add8633008
Ref: 31f68633008
Ref: library/tkinter ttk tkinter ttk Treeview selection_remove8633203
Ref: 31f78633203
Ref: library/tkinter ttk tkinter ttk Treeview selection_toggle8633406
Ref: 31f88633406
Ref: library/tkinter ttk tkinter ttk Treeview set8633626
Ref: 31f98633626
Ref: library/tkinter ttk tkinter ttk Treeview tag_bind8633991
Ref: 31fa8633991
Ref: library/tkinter ttk tkinter ttk Treeview tag_configure8634261
Ref: 31fb8634261
Ref: library/tkinter ttk tkinter ttk Treeview tag_has8634690
Ref: 31fc8634690
Ref: library/tkinter ttk tkinter ttk Treeview xview8634975
Ref: 31d88634975
Ref: library/tkinter ttk tkinter ttk Treeview yview8635071
Ref: 31d98635071
Node: Ttk Styling8635165
Ref: library/tkinter ttk ttk-styling8635263
Ref: 31fd8635263
Ref: library/tkinter ttk ttkstyling8635263
Ref: 31a28635263
Ref: library/tkinter ttk tkinter ttk Style8635851
Ref: 31a38635851
Ref: library/tkinter ttk tkinter ttk Style configure8635938
Ref: 31fe8635938
Ref: library/tkinter ttk tkinter ttk Style map8636665
Ref: ee68636665
Ref: library/tkinter ttk tkinter ttk Style lookup8637930
Ref: 31ff8637930
Ref: library/tkinter ttk tkinter ttk Style layout8638451
Ref: 32008638451
Ref: library/tkinter ttk tkinter ttk Style element_create8639763
Ref: 32028639763
Ref: library/tkinter ttk tkinter ttk Style element_names8641849
Ref: 32038641849
Ref: library/tkinter ttk tkinter ttk Style element_options8641954
Ref: 32048641954
Ref: library/tkinter ttk tkinter ttk Style theme_create8642060
Ref: 32058642060
Ref: library/tkinter ttk tkinter ttk Style theme_settings8642473
Ref: 32068642473
Ref: library/tkinter ttk tkinter ttk Style theme_names8643949
Ref: 32078643949
Ref: library/tkinter ttk tkinter ttk Style theme_use8644029
Ref: 32088644029
Ref: Ttk Styling-Footnote-18644326
Node: Layouts8644387
Ref: library/tkinter ttk layouts8644442
Ref: 32018644442
Node: tkinter tix --- TK扩展包8645726
Ref: library/tkinter tix doc8645908
Ref: 32098645908
Ref: library/tkinter tix layout8645908
Ref: 320a8645908
Ref: library/tkinter tix layouts8645908
Ref: 320b8645908
Ref: library/tkinter tix module-tkinter tix8645908
Ref: 10f8645908
Ref: library/tkinter tix tkinter-tix-extension-widgets-for-tk8645908
Ref: 320c8645908
Ref: tkinter tix --- TK扩展包-Footnote-18647806
Ref: tkinter tix --- TK扩展包-Footnote-28647876
Ref: tkinter tix --- TK扩展包-Footnote-38647912
Ref: tkinter tix --- TK扩展包-Footnote-48647965
Ref: tkinter tix --- TK扩展包-Footnote-58648042
Node: Using Tix8648099
Ref: library/tkinter tix using-tix8648192
Ref: 32138648192
Ref: library/tkinter tix tkinter tix Tk8648231
Ref: 32148648231
Node: Tix Widgets8649192
Ref: library/tkinter tix tix-widgets8649306
Ref: 32158649306
Ref: Tix Widgets-Footnote-18649646
Node: Basic Widgets8649724
Ref: library/tkinter tix basic-widgets8649808
Ref: 32168649808
Ref: library/tkinter tix tkinter tix Balloon8649855
Ref: 32178649855
Ref: library/tkinter tix tkinter tix ButtonBox8650131
Ref: 32188650131
Ref: library/tkinter tix tkinter tix ComboBox8650270
Ref: 320e8650270
Ref: library/tkinter tix tkinter tix Control8650502
Ref: 320f8650502
Ref: library/tkinter tix tkinter tix LabelEntry8650748
Ref: 32198650748
Ref: library/tkinter tix tkinter tix LabelFrame8650957
Ref: 321a8650957
Ref: library/tkinter tix tkinter tix Meter8651257
Ref: 321b8651257
Ref: library/tkinter tix tkinter tix OptionMenu8651408
Ref: 321c8651408
Ref: library/tkinter tix tkinter tix PopupMenu8651499
Ref: 321d8651499
Ref: library/tkinter tix tkinter tix Select8651745
Ref: 321e8651745
Ref: library/tkinter tix tkinter tix StdButtonBox8651940
Ref: 321f8651940
Ref: Basic Widgets-Footnote-18652110
Ref: Basic Widgets-Footnote-28652190
Ref: Basic Widgets-Footnote-38652272
Ref: Basic Widgets-Footnote-48652353
Ref: Basic Widgets-Footnote-58652433
Ref: Basic Widgets-Footnote-68652516
Ref: Basic Widgets-Footnote-78652599
Ref: Basic Widgets-Footnote-88652677
Ref: Basic Widgets-Footnote-98652760
Ref: Basic Widgets-Footnote-108652842
Ref: Basic Widgets-Footnote-118652922
Node: File Selectors8653008
Ref: library/tkinter tix file-selectors8653121
Ref: 32208653121
Ref: library/tkinter tix tkinter tix DirList8653170
Ref: 32218653170
Ref: library/tkinter tix tkinter tix DirTree8653428
Ref: 32228653428
Ref: library/tkinter tix tkinter tix DirSelectDialog8653686
Ref: 32238653686
Ref: library/tkinter tix tkinter tix DirSelectBox8653940
Ref: 32248653940
Ref: library/tkinter tix tkinter tix ExFileSelectBox8654280
Ref: 32258654280
Ref: library/tkinter tix tkinter tix FileSelectBox8654609
Ref: 32268654609
Ref: library/tkinter tix tkinter tix FileEntry8654939
Ref: 32118654939
Ref: File Selectors-Footnote-18655257
Ref: File Selectors-Footnote-28655337
Ref: File Selectors-Footnote-38655417
Ref: File Selectors-Footnote-48655505
Ref: File Selectors-Footnote-58655593
Ref: File Selectors-Footnote-68655679
Node: Hierarchical ListBox8655761
Ref: library/tkinter tix hierarchical-listbox8655876
Ref: 32278655876
Ref: library/tkinter tix tkinter tix HList8655937
Ref: 320d8655937
Ref: library/tkinter tix tkinter tix CheckList8656220
Ref: 32288656220
Ref: library/tkinter tix tkinter tix Tree8656506
Ref: 32298656506
Ref: Hierarchical ListBox-Footnote-18656744
Ref: Hierarchical ListBox-Footnote-28656822
Ref: Hierarchical ListBox-Footnote-38656904
Node: Tabular ListBox8656981
Ref: library/tkinter tix tabular-listbox8657097
Ref: 322a8657097
Ref: library/tkinter tix tkinter tix TList8657148
Ref: 322b8657148
Ref: Tabular ListBox-Footnote-18657632
Node: Manager Widgets8657710
Ref: library/tkinter tix manager-widgets8657817
Ref: 322c8657817
Ref: library/tkinter tix tkinter tix PanedWindow8657868
Ref: 32128657868
Ref: library/tkinter tix tkinter tix ListNoteBook8658173
Ref: 322d8658173
Ref: library/tkinter tix tkinter tix NoteBook8658622
Ref: 32108658622
Ref: Manager Widgets-Footnote-18659027
Ref: Manager Widgets-Footnote-28659111
Ref: Manager Widgets-Footnote-38659196
Node: Image Types8659277
Ref: library/tkinter tix image-types8659390
Ref: 322e8659390
Ref: Image Types-Footnote-18660002
Ref: Image Types-Footnote-28660078
Node: Miscellaneous Widgets8660156
Ref: library/tkinter tix miscellaneous-widgets8660275
Ref: 322f8660275
Ref: library/tkinter tix tkinter tix InputOnly8660338
Ref: 32308660338
Ref: Miscellaneous Widgets-Footnote-18660537
Node: Form Geometry Manager8660619
Ref: library/tkinter tix form-geometry-manager8660718
Ref: 32318660718
Ref: library/tkinter tix tkinter tix Form8660864
Ref: 32328660864
Ref: Form Geometry Manager-Footnote-18661013
Node: Tix Commands8661090
Ref: library/tkinter tix tix-commands8661186
Ref: 32338661186
Ref: library/tkinter tix tkinter tix tixCommand8661233
Ref: 32348661233
Ref: library/tkinter tix tkinter tix tixCommand tix_configure8661737
Ref: 32358661737
Ref: library/tkinter tix tkinter tix tixCommand tix_cget8662422
Ref: 32368662422
Ref: library/tkinter tix tkinter tix tixCommand tix_getbitmap8662597
Ref: 32378662597
Ref: library/tkinter tix tkinter tix tixCommand tix_addbitmapdir8663148
Ref: 32388663148
Ref: library/tkinter tix tkinter tix tixCommand tix_filedialog8663682
Ref: 323a8663682
Ref: library/tkinter tix tkinter tix tixCommand tix_getimage8664262
Ref: 32398664262
Ref: library/tkinter tix tkinter tix tixCommand tix_option_get8665052
Ref: 323b8665052
Ref: library/tkinter tix tkinter tix tixCommand tix_resetoptions8665161
Ref: 323c8665161
Ref: Tix Commands-Footnote-18665994
Node: tkinter scrolledtext --- 滚动文字控件8666066
Ref: library/tkinter scrolledtext doc8666223
Ref: 323d8666223
Ref: library/tkinter scrolledtext module-tkinter scrolledtext8666223
Ref: 10e8666223
Ref: library/tkinter scrolledtext tkinter-scrolledtext-scrolled-text-widget8666223
Ref: 323e8666223
Ref: library/tkinter scrolledtext tkinter scrolledtext ScrolledText frame8667017
Ref: 323f8667017
Ref: library/tkinter scrolledtext tkinter scrolledtext ScrolledText vbar8667098
Ref: 32408667098
Ref: tkinter scrolledtext --- 滚动文字控件-Footnote-18667190
Node: IDLE<54>8667270
Ref: library/idle doc8667436
Ref: 32418667436
Ref: library/idle id18667436
Ref: 32428667436
Ref: library/idle idle8667436
Ref: 9528667436
Ref: IDLE<54>-Footnote-18668453
Node: 目录8668517
Ref: library/idle menus8668592
Ref: 32438668592
Node: 文件菜单 （命令行和编辑器）8669690
Ref: library/idle file-menu-shell-and-editor8669821
Ref: 32448669821
Node: 编辑菜单（命令行和编辑器）8671146
Ref: library/idle edit-menu-shell-and-editor8671324
Ref: 32458671324
Node: 格式菜单（仅 window 编辑器）8672954
Ref: library/idle format-menu8673130
Ref: 32488673130
Ref: library/idle format-menu-editor-window-only8673130
Ref: 32498673130
Node: 运行菜单（仅 window 编辑器）8674376
Ref: library/idle run-menu-editor-window-only8674551
Ref: 324a8674551
Ref: library/idle run-module8674638
Ref: 324b8674638
Ref: library/idle run-custom8675069
Ref: 324d8675069
Ref: library/idle check-module8675347
Ref: 324c8675347
Ref: library/idle python-shell8675695
Ref: 324e8675695
Node: Shell 菜单（仅 window 编辑器）8675753
Ref: library/idle shell-menu-shell-window-only8675928
Ref: 324f8675928
Node: 调试菜单（仅 window 编辑器）8676414
Ref: library/idle debug-menu-shell-window-only8676590
Ref: 32508676590
Node: 选项菜单（命令行和编辑器）8677510
Ref: library/idle options-menu-shell-and-editor8677688
Ref: 32518677688
Node: Window 菜单（命令行和编辑器）8679268
Ref: library/idle window-menu-shell-and-editor8679447
Ref: 32548679447
Node: 帮助菜单（命令行和编辑器）8679651
Ref: library/idle help-menu-shell-and-editor8679806
Ref: 32558679806
Node: 上下文菜单8680501
Ref: library/idle context-menus8680607
Ref: 32578680607
Node: 编辑和导航8681692
Ref: library/idle editing-and-navigation8681797
Ref: 32588681797
Ref: library/idle id28681797
Ref: 32598681797
Node: 编辑窗口8681989
Ref: library/idle editor-windows8682074
Ref: 325a8682074
Node: 按键绑定8682688
Ref: library/idle key-bindings8682794
Ref: 325b8682794
Node: 自动缩进8684127
Ref: library/idle automatic-indentation8684227
Ref: 325c8684227
Node: 完成8684785
Ref: library/idle completions8684879
Ref: 32468684879
Ref: library/idle id38684879
Ref: 325d8684879
Node: 提示8687514
Ref: library/idle calltips8687611
Ref: 32478687611
Ref: library/idle id48687611
Ref: 325e8687611
Node: 代码上下文8689227
Ref: library/idle code-context8689337
Ref: 32538689337
Ref: library/idle id58689337
Ref: 325f8689337
Node: Python Shell 窗口8690226
Ref: library/idle python-shell-window8690342
Ref: 32608690342
Node: 文本颜色8691453
Ref: library/idle text-colors8691545
Ref: 32618691545
Node: 启动和代码执行8692306
Ref: library/idle startup-and-code-execution8692420
Ref: 32628692420
Node: 命令行语法8693536
Ref: library/idle command-line-usage8693630
Ref: 32638693630
Node: 启动失败8694654
Ref: library/idle startup-failure8694775
Ref: 32648694775
Node: 运行用户代码8697952
Ref: library/idle running-user-code8698081
Ref: 32658698081
Node: Shell中的用户输出8700777
Ref: library/idle user-output-in-shell8700921
Ref: 32668700921
Node: 开发 tkinter 应用程序8704007
Ref: library/idle developing-tkinter-applications8704169
Ref: 32678704169
Node: 在没有子进程的情况下运行8705404
Ref: library/idle running-without-a-subprocess8705534
Ref: 32688705534
Node: 帮助和偏好8706911
Ref: library/idle help-and-preferences8707001
Ref: 32698707001
Node: 帮助源8707125
Ref: library/idle help-sources8707210
Ref: 32568707210
Ref: library/idle id68707210
Ref: 326a8707210
Node: 首选项设置8708063
Ref: library/idle preferences8708173
Ref: 32528708173
Ref: library/idle setting-preferences8708173
Ref: 326b8708173
Node: macOS 上的IDLE8709169
Ref: library/idle idle-on-macos8709276
Ref: 326c8709276
Node: 扩展8709539
Ref: library/idle extensions8709622
Ref: 326d8709622
Node: 其他图形用户界面（GUI）包8709963
Ref: library/othergui doc8710077
Ref: 326e8710077
Ref: library/othergui other-graphical-user-interface-packages8710077
Ref: 326f8710077
Ref: library/othergui other-gui-packages8710077
Ref: 317b8710077
Ref: 其他图形用户界面（GUI）包-Footnote-18712408
Ref: 其他图形用户界面（GUI）包-Footnote-28712458
Ref: 其他图形用户界面（GUI）包-Footnote-38712510
Ref: 其他图形用户界面（GUI）包-Footnote-48712539
Ref: 其他图形用户界面（GUI）包-Footnote-58712593
Ref: 其他图形用户界面（GUI）包-Footnote-68712623
Ref: 其他图形用户界面（GUI）包-Footnote-78712654
Ref: 其他图形用户界面（GUI）包-Footnote-88712709
Ref: 其他图形用户界面（GUI）包-Footnote-98712768
Ref: 其他图形用户界面（GUI）包-Footnote-108712807
Ref: 其他图形用户界面（GUI）包-Footnote-118712841
Ref: 其他图形用户界面（GUI）包-Footnote-128712877
Node: 开发工具8712930
Ref: library/development doc8713052
Ref: 32708713052
Ref: library/development development8713052
Ref: 32718713052
Ref: library/development development-tools8713052
Ref: 32728713052
Node: typing --- 类型标注支持8714367
Ref: library/typing doc8714500
Ref: 32738714500
Ref: library/typing module-typing8714500
Ref: 11a8714500
Ref: library/typing typing-support-for-type-hints8714500
Ref: 32748714500
Ref: typing --- 类型标注支持-Footnote-18715856
Ref: typing --- 类型标注支持-Footnote-28715921
Ref: typing --- 类型标注支持-Footnote-38715970
Ref: typing --- 类型标注支持-Footnote-48716019
Ref: typing --- 类型标注支持-Footnote-58716068
Ref: typing --- 类型标注支持-Footnote-68716117
Ref: typing --- 类型标注支持-Footnote-78716166
Ref: typing --- 类型标注支持-Footnote-88716215
Ref: typing --- 类型标注支持-Footnote-98716264
Node: 类型别名8716313
Ref: library/typing type-aliases8716407
Ref: 32788716407
Node: NewType8717551
Ref: library/typing distinct8717662
Ref: 32798717662
Ref: library/typing newtype8717662
Ref: 327a8717662
Ref: NewType-Footnote-18720305
Node: Callable8720354
Ref: library/typing callable8720467
Ref: 327b8720467
Node: 泛型 Generic8721060
Ref: library/typing generics8721193
Ref: 327c8721193
Ref: library/typing id18721193
Ref: 327d8721193
Node: 用户定义的泛型类型8721858
Ref: library/typing user-defined-generic-types8721993
Ref: 327e8721993
Node: Any 类型8725182
Ref: library/typing the-any-type8725350
Ref: 327f8725350
Node: 名义性子类型 区别于 结构性子类型8727879
Ref: library/typing nominal-vs-structural-subtyping8728042
Ref: 32808728042
Ref: 名义性子类型 区别于 结构性子类型-Footnote-18729621
Ref: 名义性子类型 区别于 结构性子类型-Footnote-28729670
Ref: 名义性子类型 区别于 结构性子类型-Footnote-38729719
Node: 类 函数和修饰器8729768
Ref: library/typing classes-functions-and-decorators8729912
Ref: 32818729912
Ref: library/typing typing TypeVar8730027
Ref: f318730027
Ref: library/typing typing Generic8731563
Ref: 32778731563
Ref: library/typing typing Protocol8732209
Ref: 2408732209
Ref: library/typing typing Type8733098
Ref: 32828733098
Ref: library/typing typing Iterable8734638
Ref: 32838734638
Ref: library/typing typing Iterator8734743
Ref: 32848734743
Ref: library/typing typing Reversible8734849
Ref: 32858734849
Ref: library/typing typing SupportsInt8734958
Ref: 2428734958
Ref: library/typing typing SupportsFloat8735042
Ref: 32868735042
Ref: library/typing typing SupportsComplex8735130
Ref: 32878735130
Ref: library/typing typing SupportsBytes8735222
Ref: 32888735222
Ref: library/typing typing SupportsIndex8735316
Ref: 2438735316
Ref: library/typing typing SupportsAbs8735428
Ref: 32898735428
Ref: library/typing typing SupportsRound8735554
Ref: 328a8735554
Ref: library/typing typing Container8735675
Ref: 328b8735675
Ref: library/typing typing Hashable8735782
Ref: 328c8735782
Ref: library/typing typing Sized8735865
Ref: 328d8735865
Ref: library/typing typing Collection8735942
Ref: 5ab8735942
Ref: library/typing typing AbstractSet8736101
Ref: 328e8736101
Ref: library/typing typing MutableSet8736214
Ref: 328f8736214
Ref: library/typing typing Mapping8736324
Ref: 32908736324
Ref: library/typing typing MutableMapping8736611
Ref: 32918736611
Ref: library/typing typing Sequence8736729
Ref: 32928736729
Ref: library/typing typing MutableSequence8736855
Ref: 32938736855
Ref: library/typing typing ByteString8736971
Ref: 32948736971
Ref: library/typing typing Deque8737299
Ref: 32958737299
Ref: library/typing typing List8737457
Ref: 32968737457
Ref: library/typing typing Set8737956
Ref: 32978737956
Ref: library/typing typing FrozenSet8738164
Ref: 32988738164
Ref: library/typing typing MappingView8738278
Ref: 32998738278
Ref: library/typing typing KeysView8738397
Ref: 329a8738397
Ref: library/typing typing ItemsView8738527
Ref: 329b8738527
Ref: library/typing typing ValuesView8738655
Ref: 329c8738655
Ref: library/typing typing Awaitable8738769
Ref: 329d8738769
Ref: library/typing typing Coroutine8738901
Ref: f008738901
Ref: library/typing typing AsyncIterable8739408
Ref: 329f8739408
Ref: library/typing typing AsyncIterator8739548
Ref: 32a08739548
Ref: library/typing typing ContextManager8739694
Ref: 53d8739694
Ref: library/typing typing AsyncContextManager8739865
Ref: 32a18739865
Ref: library/typing typing Dict8740046
Ref: 32a28740046
Ref: library/typing typing DefaultDict8740399
Ref: 32a38740399
Ref: library/typing typing OrderedDict8740575
Ref: 32a48740575
Ref: library/typing typing Counter8740751
Ref: 32a58740751
Ref: library/typing typing ChainMap8740921
Ref: 32a68740921
Ref: library/typing typing Generator8741104
Ref: 329e8741104
Ref: library/typing typing AsyncGenerator8742103
Ref: 32a78742103
Ref: library/typing typing Text8743295
Ref: 32a88743295
Ref: library/typing typing IO8743606
Ref: 32a98743606
Ref: library/typing typing TextIO8743625
Ref: 32aa8743625
Ref: library/typing typing BinaryIO8743648
Ref: 32ab8743648
Ref: library/typing typing Pattern8743860
Ref: 32ac8743860
Ref: library/typing typing Match8743884
Ref: 32ad8743884
Ref: library/typing typing NamedTuple8744213
Ref: 2818744213
Ref: library/typing typing TypedDict8745882
Ref: 23c8745882
Ref: library/typing typing ForwardRef8747608
Ref: 32ae8747608
Ref: library/typing typing NewType8747905
Ref: 5ae8747905
Ref: library/typing typing cast8748236
Ref: 32af8748236
Ref: library/typing typing get_type_hints8748502
Ref: 3138748502
Ref: library/typing typing get_origin8749111
Ref: 2448749111
Ref: library/typing typing get_args8749147
Ref: 2458749147
Ref: library/typing typing overload8749834
Ref: 32b08749834
Ref: library/typing typing final8750897
Ref: 23f8750897
Ref: library/typing typing no_type_check8751504
Ref: 32b18751504
Ref: library/typing typing no_type_check_decorator8751880
Ref: 32b28751880
Ref: library/typing typing type_check_only8752107
Ref: 32b38752107
Ref: library/typing typing runtime_checkable8752683
Ref: 2418752683
Ref: library/typing typing Any8753364
Ref: 65b8753364
Ref: library/typing typing NoReturn8753560
Ref: 32b48753560
Ref: library/typing typing Union8753826
Ref: 10448753826
Ref: library/typing typing Optional8754919
Ref: 32b58754919
Ref: library/typing typing Tuple8755542
Ref: 32758755542
Ref: library/typing typing Callable8756174
Ref: 32768756174
Ref: library/typing typing Literal8756934
Ref: 23d8756934
Ref: library/typing typing ClassVar8757744
Ref: 5ac8757744
Ref: library/typing typing Final8758776
Ref: 23e8758776
Ref: library/typing typing AnyStr8759296
Ref: 32b68759296
Ref: library/typing typing TYPE_CHECKING8759824
Ref: 5ad8759824
Ref: 类 函数和修饰器-Footnote-18760554
Ref: 类 函数和修饰器-Footnote-28760603
Ref: 类 函数和修饰器-Footnote-38760652
Ref: 类 函数和修饰器-Footnote-48760701
Ref: 类 函数和修饰器-Footnote-58760750
Ref: 类 函数和修饰器-Footnote-68760799
Ref: 类 函数和修饰器-Footnote-78760848
Ref: 类 函数和修饰器-Footnote-88760897
Ref: 类 函数和修饰器-Footnote-98760946
Ref: 类 函数和修饰器-Footnote-108760995
Ref: 类 函数和修饰器-Footnote-118761045
Ref: 类 函数和修饰器-Footnote-128761095
Node: pydoc --- 文档生成器和在线帮助系统8761145
Ref: library/pydoc doc8761329
Ref: 32b78761329
Ref: library/pydoc module-pydoc8761329
Ref: da8761329
Ref: library/pydoc pydoc-documentation-generator-and-online-help-system8761329
Ref: 32b88761329
Ref: pydoc --- 文档生成器和在线帮助系统-Footnote-18765806
Node: doctest --- 测试交互性的Python示例8765870
Ref: library/doctest doc8766056
Ref: 32ba8766056
Ref: library/doctest doctest-test-interactive-python-examples8766056
Ref: 32bb8766056
Ref: library/doctest module-doctest8766056
Ref: 678766056
Ref: doctest --- 测试交互性的Python示例-Footnote-18770067
Node: 简单用法：检查Docstrings中的示例8770133
Ref: library/doctest doctest-simple-testmod8770309
Ref: 32bc8770309
Ref: library/doctest simple-usage-checking-examples-in-docstrings8770309
Ref: 32bd8770309
Node: Simple Usage Checking Examples in a Text File8772064
Ref: library/doctest doctest-simple-testfile8772261
Ref: 32bf8772261
Ref: library/doctest simple-usage-checking-examples-in-a-text-file8772261
Ref: 32c08772261
Node: How It Works8774607
Ref: library/doctest doctest-how-it-works8774770
Ref: 32c28774770
Ref: library/doctest how-it-works8774770
Ref: 32c38774770
Node: Which Docstrings Are Examined?8775419
Ref: library/doctest doctest-which-docstrings8775545
Ref: 32c48775545
Ref: library/doctest which-docstrings-are-examined8775545
Ref: 32c58775545
Node: How are Docstring Examples Recognized?8776388
Ref: library/doctest doctest-finding-examples8776552
Ref: 32c68776552
Ref: library/doctest how-are-docstring-examples-recognized8776552
Ref: 32c78776552
Node: What's the Execution Context?8779640
Ref: library/doctest doctest-execution-context8779796
Ref: 32cb8779796
Ref: library/doctest what-s-the-execution-context8779796
Ref: 32cc8779796
Node: What About Exceptions?8780513
Ref: library/doctest doctest-exceptions8780643
Ref: 32cd8780643
Ref: library/doctest what-about-exceptions8780643
Ref: 32ce8780643
Ref: library/doctest option-flags-and-directives8785151
Ref: 32d08785151
Ref: What About Exceptions?-Footnote-18785188
Node: Option Flags8785392
Ref: library/doctest doctest-options8785503
Ref: 8458785503
Ref: library/doctest option-flags8785503
Ref: 32d18785503
Ref: library/doctest doctest DONT_ACCEPT_TRUE_FOR_18786119
Ref: 32d28786119
Ref: library/doctest doctest DONT_ACCEPT_BLANKLINE8786745
Ref: 32d38786745
Ref: library/doctest doctest NORMALIZE_WHITESPACE8787200
Ref: 32c88787200
Ref: library/doctest doctest ELLIPSIS8787692
Ref: dd98787692
Ref: library/doctest doctest IGNORE_EXCEPTION_DETAIL8788127
Ref: 32cf8788127
Ref: library/doctest doctest SKIP8790160
Ref: 32d48790160
Ref: library/doctest doctest COMPARISON_FLAGS8790672
Ref: 32d58790672
Ref: library/doctest doctest REPORT_UDIFF8790846
Ref: dda8790846
Ref: library/doctest doctest REPORT_CDIFF8791004
Ref: ddb8791004
Ref: library/doctest doctest REPORT_NDIFF8791166
Ref: ddc8791166
Ref: library/doctest doctest REPORT_ONLY_FIRST_FAILURE8791632
Ref: 32d68791632
Ref: library/doctest doctest FAIL_FAST8792213
Ref: 8468792213
Ref: library/doctest doctest REPORTING_FLAGS8792680
Ref: 32d78792680
Ref: library/doctest doctest register_optionflag8792939
Ref: 32d88792939
Node: Directives8793427
Ref: library/doctest directives8793525
Ref: 32db8793525
Ref: library/doctest doctest-directives8793525
Ref: 32c98793525
Ref: library/doctest grammar-token-directive8793750
Ref: 32dc8793750
Ref: library/doctest grammar-token-directive-options8793814
Ref: 32dd8793814
Ref: library/doctest grammar-token-directive-option8793887
Ref: 32de8793887
Ref: library/doctest grammar-token-on-or-off8793950
Ref: 32df8793950
Ref: library/doctest grammar-token-directive-option-name8793992
Ref: 32e08793992
Node: 警告<2>8795894
Ref: library/doctest doctest-warnings8795971
Ref: 32e18795971
Ref: library/doctest warnings8795971
Ref: 32e28795971
Node: Basic API8797856
Ref: library/doctest basic-api8797986
Ref: 32e38797986
Ref: library/doctest doctest-basic-api8797986
Ref: 32be8797986
Ref: library/doctest doctest testfile8798367
Ref: 32c18798367
Ref: library/doctest doctest testmod8802297
Ref: dd88802297
Ref: library/doctest doctest run_docstring_examples8804041
Ref: 32e58804041
Node: Unittest API8805017
Ref: library/doctest doctest-unittest-api8805147
Ref: 32e68805147
Ref: library/doctest unittest-api8805147
Ref: 32e78805147
Ref: library/doctest doctest DocFileSuite8805917
Ref: 32e88805917
Ref: library/doctest doctest DocTestSuite8809639
Ref: 6d68809639
Ref: library/doctest doctest set_unittest_reportflags8812782
Ref: 32ea8812782
Node: Advanced API8813972
Ref: library/doctest advanced-api8814099
Ref: 32eb8814099
Ref: library/doctest doctest-advanced-api8814099
Ref: 32ec8814099
Node: DocTest 对象8816235
Ref: library/doctest doctest-doctest8816322
Ref: 32ee8816322
Ref: library/doctest doctest-objects8816322
Ref: 32ef8816322
Ref: library/doctest doctest DocTest8816371
Ref: 32e98816371
Ref: library/doctest doctest DocTest examples8816785
Ref: 32f08816785
Ref: library/doctest doctest DocTest globs8816957
Ref: 32f18816957
Ref: library/doctest doctest DocTest name8817289
Ref: 32f28817289
Ref: library/doctest doctest DocTest filename8817479
Ref: 32f38817479
Ref: library/doctest doctest DocTest lineno8817713
Ref: 32f48817713
Ref: library/doctest doctest DocTest docstring8817988
Ref: 32f58817988
Node: Example Objects8818184
Ref: library/doctest doctest-example8818300
Ref: 32f68818300
Ref: library/doctest example-objects8818300
Ref: 32f78818300
Ref: library/doctest doctest Example8818353
Ref: 32ed8818353
Ref: library/doctest doctest Example source8818790
Ref: 32f88818790
Ref: library/doctest doctest Example want8819031
Ref: 32f98819031
Ref: library/doctest doctest Example exc_msg8819379
Ref: 32fa8819379
Ref: library/doctest doctest Example lineno8819861
Ref: 32fc8819861
Ref: library/doctest doctest Example indent8820089
Ref: 32fd8820089
Ref: library/doctest doctest Example options8820279
Ref: 32fe8820279
Node: DocTestFinder 对象8820672
Ref: library/doctest doctest-doctestfinder8820794
Ref: 32ff8820794
Ref: library/doctest doctestfinder-objects8820794
Ref: 33008820794
Ref: library/doctest doctest DocTestFinder8820855
Ref: 32e48820855
Ref: library/doctest doctest DocTestFinder find8821992
Ref: 33018821992
Node: DocTestParser 对象8824111
Ref: library/doctest doctest-doctestparser8824238
Ref: 33028824238
Ref: library/doctest doctestparser-objects8824238
Ref: 33038824238
Ref: library/doctest doctest DocTestParser8824299
Ref: 32ca8824299
Ref: library/doctest doctest DocTestParser get_doctest8824531
Ref: 33048824531
Ref: library/doctest doctest DocTestParser get_examples8824926
Ref: 33058824926
Ref: library/doctest doctest DocTestParser parse8825264
Ref: 33068825264
Node: DocTestRunner 对象8825660
Ref: library/doctest doctest-doctestrunner8825787
Ref: 33078825787
Ref: library/doctest doctestrunner-objects8825787
Ref: 33088825787
Ref: library/doctest doctest DocTestRunner8825848
Ref: 32da8825848
Ref: library/doctest doctest DocTestRunner report_start8827954
Ref: 33098827954
Ref: library/doctest doctest DocTestRunner report_success8828453
Ref: 330a8828453
Ref: library/doctest doctest DocTestRunner report_failure8828986
Ref: 330c8828986
Ref: library/doctest doctest DocTestRunner report_unexpected_exception8829509
Ref: 330b8829509
Ref: library/doctest doctest DocTestRunner run8830184
Ref: 330d8830184
Ref: library/doctest doctest DocTestRunner summarize8831185
Ref: 330e8831185
Node: OutputChecker 对象8831610
Ref: library/doctest doctest-outputchecker8831708
Ref: 330f8831708
Ref: library/doctest outputchecker-objects8831708
Ref: 33108831708
Ref: library/doctest doctest OutputChecker8831769
Ref: 32d98831769
Ref: library/doctest doctest OutputChecker check_output8832263
Ref: 33118832263
Ref: library/doctest doctest OutputChecker output_difference8832750
Ref: 33128832750
Node: 调试8833065
Ref: library/doctest debugging8833187
Ref: 33138833187
Ref: library/doctest doctest-debugging8833187
Ref: 33148833187
Ref: library/doctest doctest script_from_examples8835278
Ref: 33178835278
Ref: library/doctest doctest testsource8836263
Ref: 33188836263
Ref: library/doctest doctest debug8837058
Ref: 33168837058
Ref: library/doctest doctest debug_src8838146
Ref: 331a8838146
Ref: library/doctest doctest DebugRunner8839018
Ref: 33158839018
Ref: library/doctest doctest DocTestFailure8839783
Ref: 331c8839783
Ref: library/doctest doctest DocTestFailure test8840143
Ref: 331d8840143
Ref: library/doctest doctest DocTestFailure example8840263
Ref: 331e8840263
Ref: library/doctest doctest DocTestFailure got8840343
Ref: 331f8840343
Ref: library/doctest doctest UnexpectedException8840412
Ref: 331b8840412
Ref: library/doctest doctest UnexpectedException test8840762
Ref: 33208840762
Ref: library/doctest doctest UnexpectedException example8840887
Ref: 33218840887
Ref: library/doctest doctest UnexpectedException exc_info8840972
Ref: 33228840972
Node: Soapbox8841130
Ref: library/doctest doctest-soapbox8841231
Ref: 33238841231
Ref: library/doctest soapbox8841231
Ref: 33248841231
Node: unittest --- 单元测试框架8845084
Ref: library/unittest doc8845257
Ref: 33258845257
Ref: library/unittest module-unittest8845257
Ref: 11c8845257
Ref: library/unittest unittest-unit-testing-framework8845257
Ref: 33268845257
Ref: unittest --- 单元测试框架-Footnote-18848171
Ref: unittest --- 单元测试框架-Footnote-28848248
Ref: unittest --- 单元测试框架-Footnote-38848341
Ref: unittest --- 单元测试框架-Footnote-48848374
Ref: unittest --- 单元测试框架-Footnote-58848404
Ref: unittest --- 单元测试框架-Footnote-68848432
Node: 基本实例8848466
Ref: library/unittest basic-example8848573
Ref: 33288848573
Ref: library/unittest unittest-minimal-example8848573
Ref: 33298848573
Node: 命令行界面<5>8851256
Ref: library/unittest command-line-interface8851387
Ref: 332b8851387
Ref: library/unittest unittest-command-line-interface8851387
Ref: 332c8851387
Node: 命令行选项<5>8852623
Ref: library/unittest command-line-options8852696
Ref: 332e8852696
Ref: library/unittest cmdoption-unittest-b8852795
Ref: ccb8852795
Ref: library/unittest cmdoption-unittest-c8853077
Ref: ccc8853077
Ref: library/unittest cmdoption-unittest-f8853439
Ref: cce8853439
Ref: library/unittest cmdoption-unittest-k8853543
Ref: 33308853543
Ref: library/unittest cmdoption-unittest-locals8854144
Ref: 33318854144
Node: 探索性测试8854483
Ref: library/unittest test-discovery8854626
Ref: 33328854626
Ref: library/unittest unittest-test-discovery8854626
Ref: 332d8854626
Ref: library/unittest cmdoption-unittest-discover-v8855440
Ref: 33338855440
Ref: library/unittest cmdoption-unittest-discover-s8855507
Ref: 33348855507
Ref: library/unittest cmdoption-unittest-discover-p8855630
Ref: 33358855630
Ref: library/unittest cmdoption-unittest-discover-t8855745
Ref: 33368855745
Node: 组织你的测试代码8857309
Ref: library/unittest organizing-test-code8857461
Ref: 33388857461
Ref: library/unittest organizing-tests8857461
Ref: 332a8857461
Node: 复用已有的测试代码8861966
Ref: library/unittest legacy-unit-tests8862133
Ref: 333a8862133
Ref: library/unittest re-using-old-test-code8862133
Ref: 333b8862133
Node: 跳过测试与预计的失败8863510
Ref: library/unittest skipping-tests-and-expected-failures8863698
Ref: 333c8863698
Ref: library/unittest unittest-skipping8863698
Ref: 333d8863698
Ref: library/unittest unittest skip8866732
Ref: f908866732
Ref: library/unittest unittest skipIf8866855
Ref: 33408866855
Ref: library/unittest unittest skipUnless8866967
Ref: 33418866967
Ref: library/unittest unittest expectedFailure8867083
Ref: 333f8867083
Ref: library/unittest unittest SkipTest8867301
Ref: 90b8867301
Node: Distinguishing test iterations using subtests8867839
Ref: library/unittest distinguishing-test-iterations-using-subtests8868012
Ref: 33428868012
Ref: library/unittest subtests8868012
Ref: 9098868012
Node: 类与函数8870256
Ref: library/unittest classes-and-functions8870424
Ref: 33438870424
Ref: library/unittest unittest-contents8870424
Ref: 33448870424
Node: 测试用例8870596
Ref: library/unittest test-cases8870680
Ref: 33458870680
Ref: library/unittest testcase-objects8870680
Ref: 33468870680
Ref: library/unittest unittest TestCase8870723
Ref: 9078870723
Ref: library/unittest unittest TestCase setUp8872036
Ref: cd38872036
Ref: library/unittest unittest TestCase tearDown8872414
Ref: cd48872414
Ref: library/unittest unittest TestCase setUpClass8873188
Ref: 24d8873188
Ref: library/unittest unittest TestCase tearDownClass8873638
Ref: cd18873638
Ref: library/unittest unittest TestCase run8874097
Ref: ac68874097
Ref: library/unittest unittest TestCase skipTest8874719
Ref: 333e8874719
Ref: library/unittest unittest TestCase subTest8874967
Ref: 9088874967
Ref: library/unittest unittest TestCase debug8875529
Ref: 10378875529
Ref: library/unittest assert-methods8875764
Ref: 33278875764
Ref: library/unittest unittest TestCase assertEqual8879611
Ref: bbd8879611
Ref: library/unittest unittest TestCase assertNotEqual8880461
Ref: bbe8880461
Ref: library/unittest unittest TestCase assertTrue8880640
Ref: bbc8880640
Ref: library/unittest unittest TestCase assertFalse8880685
Ref: ccf8880685
Ref: library/unittest unittest TestCase assertIs8881186
Ref: cd78881186
Ref: library/unittest unittest TestCase assertIsNot8881238
Ref: cd88881238
Ref: library/unittest unittest TestCase assertIsNone8881409
Ref: cd58881409
Ref: library/unittest unittest TestCase assertIsNotNone8881456
Ref: cd68881456
Ref: library/unittest unittest TestCase assertIn8881591
Ref: ce08881591
Ref: library/unittest unittest TestCase assertNotIn8881647
Ref: ce18881647
Ref: library/unittest unittest TestCase assertIsInstance8881797
Ref: cd98881797
Ref: library/unittest unittest TestCase assertNotIsInstance8881852
Ref: cda8881852
Ref: library/unittest unittest TestCase assertRaises8884523
Ref: ac28884523
Ref: library/unittest unittest TestCase assertRaisesRegex8886235
Ref: ac38886235
Ref: library/unittest unittest TestCase assertWarns8887221
Ref: ac48887221
Ref: library/unittest unittest TestCase assertWarnsRegex8888925
Ref: ac58888925
Ref: library/unittest unittest TestCase assertLogs8889859
Ref: 90d8889859
Ref: library/unittest unittest TestCase records8890912
Ref: 334a8890912
Ref: library/unittest unittest TestCase output8891052
Ref: 334b8891052
Ref: library/unittest unittest TestCase assertAlmostEqual8894371
Ref: bbf8894371
Ref: library/unittest unittest TestCase assertNotAlmostEqual8894469
Ref: bc08894469
Ref: library/unittest unittest TestCase assertGreater8895525
Ref: cdb8895525
Ref: library/unittest unittest TestCase assertGreaterEqual8895582
Ref: cdc8895582
Ref: library/unittest unittest TestCase assertLess8895644
Ref: cdd8895644
Ref: library/unittest unittest TestCase assertLessEqual8895698
Ref: cde8895698
Ref: library/unittest unittest TestCase assertRegex8896061
Ref: bb98896061
Ref: library/unittest unittest TestCase assertNotRegex8896114
Ref: 334c8896114
Ref: library/unittest unittest TestCase assertCountEqual8896906
Ref: bb78896906
Ref: library/unittest type-specific-methods8897565
Ref: 33498897565
Ref: library/unittest unittest TestCase addTypeEqualityFunc8897883
Ref: ce98897883
Ref: library/unittest unittest TestCase assertMultiLineEqual8900588
Ref: cdf8900588
Ref: library/unittest unittest TestCase assertSequenceEqual8901001
Ref: ce58901001
Ref: library/unittest unittest TestCase assertListEqual8901624
Ref: ce38901624
Ref: library/unittest unittest TestCase assertTupleEqual8901683
Ref: ce48901683
Ref: library/unittest unittest TestCase assertSetEqual8902129
Ref: ce28902129
Ref: library/unittest unittest TestCase assertDictEqual8902579
Ref: ce68902579
Ref: library/unittest other-methods-and-attrs8902935
Ref: 334e8902935
Ref: library/unittest unittest TestCase fail8903026
Ref: 334f8903026
Ref: library/unittest unittest TestCase failureException8903169
Ref: 334d8903169
Ref: library/unittest unittest TestCase longMessage8903578
Ref: cd08903578
Ref: library/unittest unittest TestCase maxDiff8904311
Ref: bb88904311
Ref: library/unittest unittest TestCase countTestCases8904987
Ref: 33508904987
Ref: library/unittest unittest TestCase defaultTestResult8905169
Ref: 33488905169
Ref: library/unittest unittest TestCase id8905599
Ref: 33518905599
Ref: library/unittest unittest TestCase shortDescription8905794
Ref: 33528905794
Ref: library/unittest unittest TestCase addCleanup8906408
Ref: 2a38906408
Ref: library/unittest unittest TestCase doCleanups8907006
Ref: cd28907006
Ref: library/unittest unittest TestCase addClassCleanup8907642
Ref: 24c8907642
Ref: library/unittest unittest TestCase doClassCleanups8908312
Ref: 33548908312
Ref: library/unittest unittest IsolatedAsyncioTestCase8909012
Ref: 24e8909012
Ref: library/unittest unittest IsolatedAsyncioTestCase asyncSetUp8909219
Ref: 33558909219
Ref: library/unittest unittest IsolatedAsyncioTestCase asyncTearDown8909659
Ref: 33568909659
Ref: library/unittest unittest IsolatedAsyncioTestCase addAsyncCleanup8910505
Ref: 33578910505
Ref: library/unittest unittest IsolatedAsyncioTestCase run8910663
Ref: 33588910663
Ref: library/unittest unittest FunctionTestCase8912400
Ref: 33398912400
Node: Deprecated aliases8912909
Ref: library/unittest deprecated-aliases8912976
Ref: bc18912976
Ref: library/unittest id18912976
Ref: 33598912976
Node: Grouping tests8916072
Ref: library/unittest grouping-tests8916190
Ref: 335a8916190
Ref: library/unittest testsuite-objects8916190
Ref: 335b8916190
Ref: library/unittest unittest TestSuite8916241
Ref: 6d78916241
Ref: library/unittest unittest TestSuite addTest8917186
Ref: 335c8917186
Ref: library/unittest unittest TestSuite addTests8917306
Ref: 335d8917306
Ref: library/unittest unittest TestSuite run8917682
Ref: 335e8917682
Ref: library/unittest unittest TestSuite debug8917984
Ref: 335f8917984
Ref: library/unittest unittest TestSuite countTestCases8918257
Ref: 33608918257
Ref: library/unittest unittest TestSuite __iter__8918421
Ref: 96a8918421
Node: Loading and running tests8919867
Ref: library/unittest loading-and-running-tests8919964
Ref: 33618919964
Ref: library/unittest unittest TestLoader8920037
Ref: 78b8920037
Ref: library/unittest unittest TestLoader errors8920529
Ref: 78a8920529
Ref: library/unittest unittest TestLoader loadTestsFromTestCase8920993
Ref: 33638920993
Ref: library/unittest unittest TestLoader loadTestsFromModule8921544
Ref: 7898921544
Ref: library/unittest unittest TestLoader loadTestsFromName8923041
Ref: ce78923041
Ref: library/unittest unittest TestLoader loadTestsFromNames8924824
Ref: 33658924824
Ref: library/unittest unittest TestLoader getTestCaseNames8925109
Ref: 33648925109
Ref: library/unittest unittest TestLoader discover8925312
Ref: 90c8925312
Ref: library/unittest unittest TestLoader testMethodPrefix8928146
Ref: 33668928146
Ref: library/unittest unittest TestLoader sortTestMethodsUsing8928432
Ref: 33678928432
Ref: library/unittest unittest TestLoader suiteClass8928643
Ref: ce88928643
Ref: library/unittest unittest TestLoader testNamePatterns8928937
Ref: 33688928937
Ref: library/unittest unittest TestResult8929646
Ref: ac78929646
Ref: library/unittest unittest TestResult errors8930506
Ref: 33698930506
Ref: library/unittest unittest TestResult failures8930733
Ref: 336a8930733
Ref: library/unittest unittest TestResult skipped8931019
Ref: 336b8931019
Ref: library/unittest unittest TestResult expectedFailures8931210
Ref: 336c8931210
Ref: library/unittest unittest TestResult unexpectedSuccesses8931449
Ref: 336d8931449
Ref: library/unittest unittest TestResult shouldStop8931611
Ref: 336e8931611
Ref: library/unittest unittest TestResult testsRun8931742
Ref: 33708931742
Ref: library/unittest unittest TestResult buffer8931818
Ref: 33718931818
Ref: library/unittest unittest TestResult failfast8932262
Ref: 33748932262
Ref: library/unittest unittest TestResult tb_locals8932442
Ref: 33758932442
Ref: library/unittest unittest TestResult wasSuccessful8932585
Ref: 33768932585
Ref: library/unittest unittest TestResult stop8932917
Ref: 336f8932917
Ref: library/unittest unittest TestResult startTest8933876
Ref: 33728933876
Ref: library/unittest unittest TestResult stopTest8933975
Ref: 33738933975
Ref: library/unittest unittest TestResult startTestRun8934110
Ref: ceb8934110
Ref: library/unittest unittest TestResult stopTestRun8934227
Ref: cec8934227
Ref: library/unittest unittest TestResult addError8934342
Ref: 33788934342
Ref: library/unittest unittest TestResult addFailure8934809
Ref: 33798934809
Ref: library/unittest unittest TestResult addSuccess8935267
Ref: 337a8935267
Ref: library/unittest unittest TestResult addSkip8935409
Ref: 337b8935409
Ref: library/unittest unittest TestResult addExpectedFailure8935705
Ref: 337c8935705
Ref: library/unittest unittest TestResult addUnexpectedSuccess8936131
Ref: 337d8936131
Ref: library/unittest unittest TestResult addSubTest8936437
Ref: 337e8936437
Ref: library/unittest unittest TextTestResult8937107
Ref: 33538937107
Ref: library/unittest unittest defaultTestLoader8937419
Ref: 33628937419
Ref: library/unittest unittest TextTestRunner8937676
Ref: 33778937676
Ref: library/unittest unittest TextTestRunner _makeResult8939261
Ref: 33808939261
Ref: library/unittest unittest TextTestRunner run8939913
Ref: 33818939913
Ref: library/unittest unittest main8940274
Ref: 90a8940274
Node: load_tests Protocol8943127
Ref: library/unittest load-tests-protocol8943208
Ref: 33378943208
Node: Class and Module Fixtures8945873
Ref: library/unittest class-and-module-fixtures8946008
Ref: 33478946008
Node: setUpClass and tearDownClass8947896
Ref: library/unittest setupclass-and-teardownclass8948025
Ref: 33828948025
Node: setUpModule and tearDownModule8948939
Ref: library/unittest setupmodule-and-teardownmodule8949068
Ref: 33838949068
Ref: library/unittest unittest addModuleCleanup8949681
Ref: 24b8949681
Ref: library/unittest unittest doModuleCleanups8950255
Ref: 33848950255
Node: 信号处理8950864
Ref: library/unittest signal-handling8950978
Ref: 332f8950978
Ref: library/unittest unittest installHandler8952200
Ref: 33858952200
Ref: library/unittest unittest registerResult8952443
Ref: 33868952443
Ref: library/unittest unittest removeResult8952935
Ref: 33878952935
Ref: library/unittest unittest removeHandler8953155
Ref: ccd8953155
Node: unittest mock --- 模拟对象库8953543
Ref: library/unittest mock doc8953700
Ref: 33888953700
Ref: library/unittest mock module-unittest mock8953700
Ref: 11d8953700
Ref: library/unittest mock unittest-mock-mock-object-library8953700
Ref: 33898953700
Ref: unittest mock --- 模拟对象库-Footnote-18955149
Ref: unittest mock --- 模拟对象库-Footnote-28955221
Node: 快速上手8955259
Ref: library/unittest mock quick-guide8955358
Ref: 338a8955358
Node: Mock 类8960237
Ref: library/unittest mock the-mock-class8960357
Ref: 338e8960357
Ref: library/unittest mock unittest mock Mock8961221
Ref: 24a8961221
Ref: library/unittest mock unittest mock Mock assert_called8964250
Ref: 5b18964250
Ref: library/unittest mock unittest mock Mock assert_called_once8964534
Ref: 5b28964534
Ref: library/unittest mock unittest mock Mock assert_called_with8965110
Ref: 100f8965110
Ref: library/unittest mock unittest mock Mock assert_called_once_with8965464
Ref: 33958965464
Ref: library/unittest mock unittest mock Mock assert_any_call8966044
Ref: 33968966044
Ref: library/unittest mock unittest mock Mock assert_has_calls8966685
Ref: 33978966685
Ref: library/unittest mock unittest mock Mock assert_not_called8967530
Ref: 78d8967530
Ref: library/unittest mock unittest mock Mock reset_mock8967963
Ref: 5b38967963
Ref: library/unittest mock unittest mock Mock mock_add_spec8969096
Ref: 33998969096
Ref: library/unittest mock unittest mock Mock attach_mock8969421
Ref: 339a8969421
Ref: library/unittest mock unittest mock Mock configure_mock8969714
Ref: 33948969714
Ref: library/unittest mock unittest mock Mock __dir__8970948
Ref: 339c8970948
Ref: library/unittest mock unittest mock Mock _get_child_mock8971281
Ref: 339e8971281
Ref: library/unittest mock unittest mock Mock called8971681
Ref: 339f8971681
Ref: library/unittest mock unittest mock Mock call_count8971978
Ref: 33a08971978
Ref: library/unittest mock unittest mock Mock return_value8972306
Ref: 33938972306
Ref: library/unittest mock unittest mock Mock side_effect8973109
Ref: 33918973109
Ref: library/unittest mock unittest mock Mock call_args8975576
Ref: f348975576
Ref: library/unittest mock unittest mock Mock call_args_list8977393
Ref: 33a18977393
Ref: library/unittest mock unittest mock Mock method_calls8978431
Ref: 339b8978431
Ref: library/unittest mock unittest mock Mock mock_calls8979165
Ref: 33988979165
Ref: library/unittest mock unittest mock Mock __class__8980701
Ref: 33a38980701
Ref: library/unittest mock unittest mock NonCallableMock8981471
Ref: 338f8981471
Ref: library/unittest mock unittest mock PropertyMock8983992
Ref: 33a48983992
Ref: library/unittest mock unittest mock AsyncMock8985364
Ref: 2498985364
Ref: library/unittest mock unittest mock AsyncMock assert_awaited8988216
Ref: 33a58988216
Ref: library/unittest mock unittest mock AsyncMock assert_awaited_once8988951
Ref: 33a68988951
Ref: library/unittest mock unittest mock AsyncMock assert_awaited_with8989516
Ref: 33a78989516
Ref: library/unittest mock unittest mock AsyncMock assert_awaited_once_with8990185
Ref: 33a88990185
Ref: library/unittest mock unittest mock AsyncMock assert_any_await8990910
Ref: 33a98990910
Ref: library/unittest mock unittest mock AsyncMock assert_has_awaits8991553
Ref: 33aa8991553
Ref: library/unittest mock unittest mock AsyncMock assert_not_awaited8992646
Ref: 33ab8992646
Ref: library/unittest mock unittest mock AsyncMock reset_mock8992821
Ref: 33ac8992821
Ref: library/unittest mock unittest mock AsyncMock await_count8993051
Ref: 33ad8993051
Ref: library/unittest mock unittest mock AsyncMock await_args8993494
Ref: 33ae8993494
Ref: library/unittest mock unittest mock AsyncMock await_args_list8994109
Ref: f338994109
Ref: Mock 类-Footnote-18994972
Node: Calling8995398
Ref: library/unittest mock calling8995478
Ref: 33af8995478
Node: Deleting Attributes8998719
Ref: library/unittest mock deleting-attributes8998841
Ref: 33b08998841
Ref: library/unittest mock id28998841
Ref: 33b18998841
Node: Mock names and the name attribute8999614
Ref: library/unittest mock mock-names-and-the-name-attribute8999758
Ref: 33b28999758
Node: Attaching Mocks as Attributes9000336
Ref: library/unittest mock attaching-mocks-as-attributes9000452
Ref: 33b39000452
Node: The patchers9002308
Ref: library/unittest mock the-patchers9002450
Ref: 33b49002450
Node: patch9003065
Ref: library/unittest mock patch9003140
Ref: 33b59003140
Ref: library/unittest mock unittest mock patch9003342
Ref: 7919003342
Node: patch object9012165
Ref: library/unittest mock patch-object9012259
Ref: 33b79012259
Ref: library/unittest mock unittest mock patch object9012304
Ref: f6f9012304
Node: patch dict9013776
Ref: library/unittest mock patch-dict9013879
Ref: 33b89013879
Ref: library/unittest mock unittest mock patch dict9013922
Ref: fdf9013922
Node: patch multiple9018028
Ref: library/unittest mock patch-multiple9018147
Ref: 33ba9018147
Ref: library/unittest mock unittest mock patch multiple9018198
Ref: 33bb9018198
Node: patch methods start and stop9020904
Ref: library/unittest mock patch-methods-start-and-stop9021027
Ref: 33bc9021027
Ref: library/unittest mock start-and-stop9021027
Ref: 33bd9021027
Ref: library/unittest mock unittest mock patch stopall9023757
Ref: 33be9023757
Node: patch builtins9023864
Ref: library/unittest mock id49023984
Ref: 33bf9023984
Ref: library/unittest mock patch-builtins9023984
Ref: 33c09023984
Node: TEST_PREFIX9024305
Ref: library/unittest mock id59024421
Ref: 33c19024421
Ref: library/unittest mock test-prefix9024421
Ref: 33b99024421
Node: Nesting Patch Decorators9025304
Ref: library/unittest mock nesting-patch-decorators9025420
Ref: 33c29025420
Node: Where to patch9026337
Ref: library/unittest mock id69026480
Ref: 33b69026480
Ref: library/unittest mock where-to-patch9026480
Ref: 338b9026480
Node: Patching Descriptors and Proxy Objects9028246
Ref: library/unittest mock patching-descriptors-and-proxy-objects9028356
Ref: 33c39028356
Ref: Patching Descriptors and Proxy Objects-Footnote-19028797
Node: MagicMock and magic method support9028879
Ref: library/unittest mock magicmock-and-magic-method-support9029020
Ref: 33c49029020
Node: Mocking Magic Methods9029162
Ref: library/unittest mock magic-methods9029273
Ref: 338c9029273
Ref: library/unittest mock mocking-magic-methods9029273
Ref: 33c59029273
Ref: Mocking Magic Methods-Footnote-19033159
Ref: Mocking Magic Methods-Footnote-29033402
Node: Magic Mock9033527
Ref: library/unittest mock magic-mock9033638
Ref: 33c69033638
Ref: library/unittest mock unittest mock MagicMock9033782
Ref: 78e9033782
Ref: library/unittest mock unittest mock NonCallableMagicMock9034247
Ref: 33909034247
Node: Helpers9037610
Ref: library/unittest mock helpers9037730
Ref: 33c79037730
Node: sentinel9037903
Ref: library/unittest mock sentinel9037971
Ref: 33c89037971
Ref: library/unittest mock unittest mock sentinel9038010
Ref: 4129038010
Node: DEFAULT9039177
Ref: library/unittest mock default9039258
Ref: 33c99039258
Ref: library/unittest mock unittest mock DEFAULT9039295
Ref: 33929039295
Node: call9039550
Ref: library/unittest mock call9039638
Ref: 33ca9039638
Ref: library/unittest mock unittest mock call9039669
Ref: f8a9039669
Ref: library/unittest mock unittest mock call call_list9040205
Ref: 33cb9040205
Ref: library/unittest mock calls-as-tuples9041153
Ref: 33a29041153
Node: create_autospec9042773
Ref: library/unittest mock create-autospec9042857
Ref: 33cc9042857
Ref: library/unittest mock unittest mock create_autospec9042910
Ref: f599042910
Node: ANY9044200
Ref: library/unittest mock any9044290
Ref: 33cd9044290
Ref: library/unittest mock unittest mock ANY9044319
Ref: 33ce9044319
Node: FILTER_DIR9045202
Ref: library/unittest mock filter-dir9045286
Ref: 33cf9045286
Ref: library/unittest mock unittest mock FILTER_DIR9045329
Ref: 339d9045329
Node: mock_open9047384
Ref: library/unittest mock mock-open9047477
Ref: 33d09047477
Ref: library/unittest mock unittest mock mock_open9047518
Ref: fd79047518
Ref: mock_open-Footnote-19050318
Node: Autospeccing9050343
Ref: library/unittest mock auto-speccing9050439
Ref: 338d9050439
Ref: library/unittest mock autospeccing9050439
Ref: 33d19050439
Ref: Autospeccing-Footnote-19059938
Node: Sealing mocks9060183
Ref: library/unittest mock sealing-mocks9060261
Ref: 33d29060261
Ref: library/unittest mock unittest mock seal9060310
Ref: 4139060310
Node: unittest mock 上手指南9061118
Ref: library/unittest mock-examples doc9061298
Ref: 33d39061298
Ref: library/unittest mock-examples unittest-mock-getting-started9061298
Ref: 33d49061298
Ref: library/unittest mock-examples getting-started9061390
Ref: 33d59061390
Node: 使用 mock9061458
Ref: library/unittest mock-examples using-mock9061557
Ref: 33d69061557
Node: 模拟方法调用9061968
Ref: library/unittest mock-examples mock-patching-methods9062075
Ref: 33d79062075
Node: 对象上的方法调用的 mock9063618
Ref: library/unittest mock-examples mock-for-method-calls-on-an-object9063749
Ref: 33d89063749
Node: Mocking Classes9064837
Ref: library/unittest mock-examples mocking-classes9064967
Ref: 33d99064967
Node: Naming your mocks9065960
Ref: library/unittest mock-examples naming-your-mocks9066076
Ref: 33da9066076
Node: Tracking all Calls9066508
Ref: library/unittest mock-examples tracking-all-calls9066645
Ref: 33db9066645
Node: Setting Return Values and Attributes9068051
Ref: library/unittest mock-examples setting-return-values-and-attributes9068200
Ref: 33dc9068200
Node: Raising exceptions with mocks9069706
Ref: library/unittest mock-examples raising-exceptions-with-mocks9069872
Ref: 33dd9069872
Node: Side effect functions and iterables9070252
Ref: library/unittest mock-examples side-effect-functions-and-iterables9070412
Ref: 33de9070412
Node: Mocking asynchronous iterators9071452
Ref: library/unittest mock-examples mocking-asynchronous-iterators9071619
Ref: 33df9071619
Node: Mocking asynchronous context manager9072185
Ref: library/unittest mock-examples mocking-asynchronous-context-manager9072356
Ref: 33e09072356
Node: Creating a Mock from an Existing Object9073253
Ref: library/unittest mock-examples creating-a-mock-from-an-existing-object9073385
Ref: 33e19073385
Node: Patch Decorators9075195
Ref: library/unittest mock-examples patch-decorators9075319
Ref: 33e29075319
Node: Further Examples9080517
Ref: library/unittest mock-examples further-examples9080621
Ref: 33e39080621
Ref: library/unittest mock-examples id19080621
Ref: 33e49080621
Node: Mocking chained calls9081249
Ref: library/unittest mock-examples mocking-chained-calls9081347
Ref: 33e59081347
Node: Partial mocking9084458
Ref: library/unittest mock-examples partial-mocking9084591
Ref: 33e69084591
Ref: Partial mocking-Footnote-19086599
Node: Mocking a Generator Method9086700
Ref: library/unittest mock-examples mocking-a-generator-method9086856
Ref: 33e79086856
Ref: Mocking a Generator Method-Footnote-19087982
Node: Applying the same patch to every test method9088306
Ref: library/unittest mock-examples applying-the-same-patch-to-every-test-method9088470
Ref: 33e89088470
Node: Mocking Unbound Methods9090784
Ref: library/unittest mock-examples mocking-unbound-methods9090955
Ref: 33e99090955
Node: Checking multiple calls with mock9092723
Ref: library/unittest mock-examples checking-multiple-calls-with-mock9092879
Ref: 33ea9092879
Node: Coping with mutable arguments9094422
Ref: library/unittest mock-examples coping-with-mutable-arguments9094570
Ref: 33eb9094570
Node: Nesting Patches9098730
Ref: library/unittest mock-examples nesting-patches9098880
Ref: 33ec9098880
Node: Mocking a dictionary with MagicMock9100687
Ref: library/unittest mock-examples mocking-a-dictionary-with-magicmock9100844
Ref: 33ed9100844
Node: Mock subclasses and their attributes9103492
Ref: library/unittest mock-examples mock-subclasses-and-their-attributes9103665
Ref: 33ee9103665
Ref: Mock subclasses and their attributes-Footnote-19105797
Ref: Mock subclasses and their attributes-Footnote-29105970
Ref: Mock subclasses and their attributes-Footnote-39106028
Node: Mocking imports with patch dict9106115
Ref: library/unittest mock-examples mocking-imports-with-patch-dict9106309
Ref: 33ef9106309
Node: Tracking order of calls and less verbose call assertions9108949
Ref: library/unittest mock-examples tracking-order-of-calls-and-less-verbose-call-assertions9109137
Ref: 33f09109137
Node: More complex argument matching9112475
Ref: library/unittest mock-examples more-complex-argument-matching9112623
Ref: 33f19112623
Ref: More complex argument matching-Footnote-19115672
Ref: More complex argument matching-Footnote-29115715
Node: 2to3 - 自动将 Python 2 代码转为 Python 3 代码9115837
Ref: library/2to3 doc9116014
Ref: 33f29116014
Ref: library/2to3 to3-automated-python-2-to-3-code-translation9116014
Ref: 33f39116014
Ref: library/2to3 to3-reference9116014
Ref: c7e9116014
Node: 使用 2to39116677
Ref: library/2to3 to3-using9116797
Ref: 33f49116797
Ref: library/2to3 using-2to39116797
Ref: 33f59116797
Node: 修复器9121016
Ref: library/2to3 fixers9121174
Ref: 33f79121174
Ref: library/2to3 to3-fixers9121174
Ref: 33f69121174
Ref: library/2to3 2to3fixer-apply9121467
Ref: 33f89121467
Ref: library/2to3 2to3fixer-asserts9121641
Ref: 33f99121641
Ref: library/2to3 2to3fixer-basestring9123891
Ref: 33fa9123891
Ref: library/2to3 2to3fixer-buffer9123974
Ref: 33fb9123974
Ref: library/2to3 2to3fixer-dict9124175
Ref: 33fc9124175
Ref: library/2to3 2to3fixer-except9124801
Ref: 33fd9124801
Ref: library/2to3 2to3fixer-exec9124885
Ref: 33fe9124885
Ref: library/2to3 2to3fixer-execfile9124978
Ref: 10339124978
Ref: library/2to3 2to3fixer-exitfunc9125162
Ref: 33ff9125162
Ref: library/2to3 2to3fixer-filter9125274
Ref: 34009125274
Ref: library/2to3 2to3fixer-funcattrs9125371
Ref: 34019125371
Ref: library/2to3 2to3fixer-future9125535
Ref: 34029125535
Ref: library/2to3 2to3fixer-getcwdu9125622
Ref: 34039125622
Ref: library/2to3 2to3fixer-has_key9125715
Ref: 34049125715
Ref: library/2to3 2to3fixer-idioms9125804
Ref: 34059125804
Ref: library/2to3 2to3fixer-import9126361
Ref: 34069126361
Ref: library/2to3 2to3fixer-imports9126450
Ref: 34079126450
Ref: library/2to3 2to3fixer-imports29126517
Ref: 34089126517
Ref: library/2to3 2to3fixer-input9126694
Ref: 34099126694
Ref: library/2to3 2to3fixer-intern9126785
Ref: 340a9126785
Ref: library/2to3 2to3fixer-isinstance9126871
Ref: 340b9126871
Ref: library/2to3 2to3fixer-itertools_imports9127169
Ref: 340c9127169
Ref: library/2to3 2to3fixer-itertools9127422
Ref: 340d9127422
Ref: library/2to3 2to3fixer-long9127675
Ref: 340e9127675
Ref: library/2to3 2to3fixer-map9127749
Ref: 340f9127749
Ref: library/2to3 2to3fixer-metaclass9127965
Ref: 34109127965
Ref: library/2to3 2to3fixer-methodattrs9128122
Ref: 34119128122
Ref: library/2to3 2to3fixer-ne9128251
Ref: 34129128251
Ref: library/2to3 2to3fixer-next9128335
Ref: 34139128335
Ref: library/2to3 2to3fixer-nonzero9128517
Ref: 34149128517
Ref: library/2to3 2to3fixer-numliterals9128607
Ref: 34159128607
Ref: library/2to3 2to3fixer-operator9128684
Ref: 34169128684
Ref: library/2to3 2to3fixer-paren9130331
Ref: 34179130331
Ref: library/2to3 2to3fixer-print9130482
Ref: 34189130482
Ref: library/2to3 2to3fixer-raise9130572
Ref: 34199130572
Ref: library/2to3 2to3fixer-raw_input9130858
Ref: 341a9130858
Ref: library/2to3 2to3fixer-reduce9130945
Ref: 341b9130945
Ref: library/2to3 2to3fixer-reload9131037
Ref: 10439131037
Ref: library/2to3 2to3fixer-renames9131129
Ref: 341c9131129
Ref: library/2to3 2to3fixer-repr9131217
Ref: 341d9131217
Ref: library/2to3 2to3fixer-set_literal9131310
Ref: 341e9131310
Ref: library/2to3 2to3fixer-standarderror9131445
Ref: 341f9131445
Ref: library/2to3 2to3fixer-sys_exc9131543
Ref: 34209131543
Ref: library/2to3 2to3fixer-throw9131709
Ref: 34219131709
Ref: library/2to3 2to3fixer-tuple_params9131794
Ref: 34229131794
Ref: library/2to3 2to3fixer-types9131905
Ref: 34239131905
Ref: library/2to3 2to3fixer-unicode9132012
Ref: 34249132012
Ref: library/2to3 2to3fixer-urllib9132092
Ref: 34259132092
Ref: library/2to3 2to3fixer-ws_comma9132201
Ref: 34269132201
Ref: library/2to3 2to3fixer-xrange9132314
Ref: 34279132314
Ref: library/2to3 2to3fixer-xreadlines9132466
Ref: 34289132466
Ref: library/2to3 2to3fixer-zip9132569
Ref: 34299132569
Node: lib2to3 —— 2to3 支持库9132721
Ref: library/2to3 lib2to3-2to3-s-library9132859
Ref: 342a9132859
Ref: library/2to3 module-lib2to39132859
Ref: a89132859
Ref: lib2to3 —— 2to3 支持库-Footnote-19133161
Node: test --- Python回归测试包9133225
Ref: library/test doc9133428
Ref: 342b9133428
Ref: library/test module-test9133428
Ref: 1069133428
Ref: library/test test-regression-tests-package-for-python9133428
Ref: 342c9133428
Node: Writing Unit Tests for the test package9134828
Ref: library/test writing-tests9134989
Ref: 342d9134989
Ref: library/test writing-unit-tests-for-the-test-package9134989
Ref: 342e9134989
Node: Running tests using the command-line interface9139524
Ref: library/test regrtest9139685
Ref: 9359139685
Ref: library/test running-tests-using-the-command-line-interface9139685
Ref: 342f9139685
Node: test support --- Utilities for the Python test suite9141623
Ref: library/test module-test support9141843
Ref: 1079141843
Ref: library/test test-support-utilities-for-the-python-test-suite9141843
Ref: 34309141843
Ref: library/test test support TestFailed9142353
Ref: 34319142353
Ref: library/test test support ResourceDenied9142570
Ref: 34329142570
Ref: library/test test support verbose9142861
Ref: 34349142861
Ref: library/test test support is_jython9143079
Ref: 34359143079
Ref: library/test test support is_android9143170
Ref: 34369143170
Ref: library/test test support unix_shell9143250
Ref: 34379143250
Ref: library/test test support FS_NONASCII9143349
Ref: 34389143349
Ref: library/test test support TESTFN9143454
Ref: 34399143454
Ref: library/test test support TESTFN_UNICODE9143646
Ref: 343a9143646
Ref: library/test test support TESTFN_ENCODING9143739
Ref: 343b9143739
Ref: library/test test support TESTFN_UNENCODABLE9143834
Ref: 343c9143834
Ref: library/test test support TESTFN_UNDECODABLE9144076
Ref: 343d9144076
Ref: library/test test support TESTFN_NONASCII9144320
Ref: 343e9144320
Ref: library/test test support IPV6_ENABLED9144442
Ref: 343f9144442
Ref: library/test test support SAVEDCWD9144561
Ref: 34409144561
Ref: library/test test support PGO9144633
Ref: 34419144633
Ref: library/test test support PIPE_MAX_SIZE9144733
Ref: 34429144733
Ref: library/test test support SOCK_MAX_SIZE9144883
Ref: 34439144883
Ref: library/test test support TEST_SUPPORT_DIR9145035
Ref: 34449145035
Ref: library/test test support TEST_HOME_DIR9145159
Ref: 34459145159
Ref: library/test test support TEST_DATA_DIR9145258
Ref: 34469145258
Ref: library/test test support MAX_Py_ssize_t9145361
Ref: 34479145361
Ref: library/test test support max_memuse9145461
Ref: 34489145461
Ref: library/test test support real_max_memuse9145626
Ref: 344a9145626
Ref: library/test test support MISSING_C_DOCSTRINGS9145800
Ref: 344b9145800
Ref: library/test test support HAVE_DOCSTRINGS9145970
Ref: 344c9145970
Ref: library/test test support TEST_HTTP_URL9146052
Ref: 344d9146052
Ref: library/test test support ALWAYS_EQ9146163
Ref: 344e9146163
Ref: library/test test support LARGEST9146281
Ref: 344f9146281
Ref: library/test test support SMALLEST9146417
Ref: 34509146417
Ref: library/test test support forget9146621
Ref: 34519146621
Ref: library/test test support unload9146790
Ref: 34529146790
Ref: library/test test support unlink9146874
Ref: 34539146874
Ref: library/test test support rmdir9147077
Ref: 34549147077
Ref: library/test test support rmtree9147278
Ref: 34559147278
Ref: library/test test support make_legacy_pyc9147575
Ref: 34569147575
Ref: library/test test support is_resource_enabled9147908
Ref: 34579147908
Ref: library/test test support python_is_optimized9148133
Ref: 34589148133
Ref: library/test test support with_pymalloc9148259
Ref: 34599148259
Ref: library/test test support requires9148346
Ref: 34339148346
Ref: library/test test support system_must_validate_cert9148711
Ref: 345a9148711
Ref: library/test test support sortdict9148856
Ref: 345b9148856
Ref: library/test test support findfile9148946
Ref: 345c9148946
Ref: library/test test support create_empty_file9149316
Ref: 345d9149316
Ref: library/test test support fd_count9149456
Ref: 345e9149456
Ref: library/test test support match_test9149543
Ref: 345f9149543
Ref: library/test test support set_match_tests9149656
Ref: 34609149656
Ref: library/test test support run_unittest9149769
Ref: 10539149769
Ref: library/test test support run_doctest9150429
Ref: 34619150429
Ref: library/test test support setswitchinterval9150894
Ref: 34629150894
Ref: library/test test support check_impl_detail9151118
Ref: 34639151118
Ref: library/test test support check_warnings9151528
Ref: 34649151528
Ref: library/test test support check_no_resource_warning9154562
Ref: 34679154562
Ref: library/test test support set_memlimit9154824
Ref: 34499154824
Ref: library/test test support record_original_stdout9154980
Ref: 34689154980
Ref: library/test test support get_original_stdout9155144
Ref: 34699155144
Ref: library/test test support strip_python_strerr9155315
Ref: 346a9155315
Ref: library/test test support args_from_interpreter_flags9155570
Ref: 346b9155570
Ref: library/test test support optim_args_from_interpreter_flags9155757
Ref: 346c9155757
Ref: library/test test support captured_stdin9155937
Ref: 346d9155937
Ref: library/test test support captured_stdout9155980
Ref: 346e9155980
Ref: library/test test support captured_stderr9156024
Ref: fe29156024
Ref: library/test test support temp_dir9156747
Ref: 346f9156747
Ref: library/test test support change_cwd9157188
Ref: 34709157188
Ref: library/test test support temp_cwd9157545
Ref: 34719157545
Ref: library/test test support temp_umask9158181
Ref: 34729158181
Ref: library/test test support transient_internet9158291
Ref: 34739158291
Ref: library/test test support disable_faulthandler9158548
Ref: 34749158548
Ref: library/test test support gc_collect9158680
Ref: 34759158680
Ref: library/test test support disable_gc9159014
Ref: 34769159014
Ref: library/test test support swap_attr9159158
Ref: 34779159158
Ref: library/test test support swap_item9159739
Ref: 34789159739
Ref: library/test test support wait_threads_exit9160318
Ref: 34799160318
Ref: library/test test support start_threads9160472
Ref: 347a9160472
Ref: library/test test support calcobjsize9160626
Ref: 347b9160626
Ref: library/test test support calcvobjsize9160796
Ref: 347c9160796
Ref: library/test test support checksizeof9160969
Ref: 347d9160969
Ref: library/test test support can_symlink9161138
Ref: 347e9161138
Ref: library/test test support can_xattr9161261
Ref: 347f9161261
Ref: library/test test support skip_unless_symlink9161373
Ref: 34809161373
Ref: library/test test support skip_unless_xattr9161502
Ref: 34819161502
Ref: library/test test support skip_unless_bind_unix_socket9161615
Ref: 34829161615
Ref: library/test test support anticipate_failure9161763
Ref: 34839161763
Ref: library/test test support run_with_locale9162023
Ref: 34849162023
Ref: library/test test support run_with_tz9162381
Ref: 34859162381
Ref: library/test test support requires_freebsd_version9162541
Ref: 34869162541
Ref: library/test test support requires_linux_version9162773
Ref: 34879162773
Ref: library/test test support requires_mac_version9163000
Ref: 34889163000
Ref: library/test test support requires_IEEE_7549163230
Ref: 34899163230
Ref: library/test test support requires_zlib9163337
Ref: 348a9163337
Ref: library/test test support requires_gzip9163450
Ref: 348b9163450
Ref: library/test test support requires_bz29163562
Ref: 348c9163562
Ref: library/test test support requires_lzma9163672
Ref: 348d9163672
Ref: library/test test support requires_resource9163784
Ref: 348e9163784
Ref: library/test test support requires_docstrings9163907
Ref: 348f9163907
Ref: library/test test support cpython_only9164028
Ref: 34909164028
Ref: library/test test support impl_detail9164129
Ref: 34919164129
Ref: library/test test support no_tracing9164357
Ref: 34929164357
Ref: library/test test support refcount_test9164485
Ref: 34939164485
Ref: library/test test support reap_threads9164794
Ref: 34949164794
Ref: library/test test support bigmemtest9164923
Ref: 34959164923
Ref: library/test test support bigaddrspacetest9165668
Ref: 34969165668
Ref: library/test test support make_bad_fd9165806
Ref: 34979165806
Ref: library/test test support check_syntax_error9165963
Ref: 34989165963
Ref: library/test test support check_syntax_warning9166515
Ref: 10139166515
Ref: library/test test support open_urlresource9167312
Ref: 34999167312
Ref: library/test test support import_module9167439
Ref: 349a9167439
Ref: library/test test support import_fresh_module9168039
Ref: 349b9168039
Ref: library/test test support modules_setup9169636
Ref: 349c9169636
Ref: library/test test support modules_cleanup9169726
Ref: 349d9169726
Ref: library/test test support threading_setup9169888
Ref: 349e9169888
Ref: library/test test support threading_cleanup9169997
Ref: 349f9169997
Ref: library/test test support join_thread9170206
Ref: 34a09170206
Ref: library/test test support reap_children9170400
Ref: 34a19170400
Ref: library/test test support get_attribute9170672
Ref: 34a29170672
Ref: library/test test support bind_port9170832
Ref: 34a39170832
Ref: library/test test support bind_unix_socket9171760
Ref: 34a49171760
Ref: library/test test support catch_threading_exception9171927
Ref: fb39171927
Ref: library/test test support catch_unraisable_exception9172858
Ref: fc19172858
Ref: library/test test support find_unused_port9173741
Ref: 34a59173741
Ref: library/test test support load_package_tests9175047
Ref: 34a69175047
Ref: library/test test support fs_is_case_insensitive9175675
Ref: 34a79175675
Ref: library/test test support detect_api_mismatch9175821
Ref: 34a89175821
Ref: library/test test support patch9176286
Ref: 34a99176286
Ref: library/test test support run_in_subinterp9176620
Ref: 34aa9176620
Ref: library/test test support check_free_after_iterating9176787
Ref: 34ab9176787
Ref: library/test test support missing_compiler_executable9176934
Ref: 34ac9176934
Ref: library/test test support check__all__9177254
Ref: 34ad9177254
Ref: library/test test support TransientResource9179110
Ref: 34ae9179110
Ref: library/test test support EnvironmentVarGuard9179564
Ref: 34af9179564
Ref: library/test test support EnvironmentVarGuard set9180015
Ref: 34b09180015
Ref: library/test test support EnvironmentVarGuard unset9180162
Ref: 34b19180162
Ref: library/test test support SuppressCrashReport9180273
Ref: 34b29180273
Ref: library/test test support CleanImport9180773
Ref: 34b59180773
Ref: library/test test support DirsOnSysPath9181130
Ref: 34b69181130
Ref: library/test test support SaveSignals9181619
Ref: 34b79181619
Ref: library/test test support Matcher9181748
Ref: 34b89181748
Ref: library/test test support Matcher matches9181779
Ref: 34b99181779
Ref: library/test test support Matcher match_value9181892
Ref: 34ba9181892
Ref: library/test test support WarningsRecorder9182031
Ref: 34bb9182031
Ref: library/test test support BasicTestRunner9182204
Ref: 34bc9182204
Ref: library/test test support BasicTestRunner run9182243
Ref: 34bd9182243
Ref: library/test test support TestHandler9182317
Ref: 34be9182317
Ref: library/test test support FakePath9182421
Ref: 34bf9182421
Ref: test support --- Utilities for the Python test suite-Footnote-19182702
Ref: test support --- Utilities for the Python test suite-Footnote-29182751
Ref: test support --- Utilities for the Python test suite-Footnote-39182800
Node: test support script_helper --- Utilities for the Python execution tests9182880
Ref: library/test module-test support script_helper9183061
Ref: 1089183061
Ref: library/test test-support-script-helper-utilities-for-the-python-execution-tests9183061
Ref: 34c09183061
Ref: library/test test support script_helper interpreter_requires_environment9183335
Ref: 34c19183335
Ref: library/test test support script_helper run_python_until_end9184298
Ref: 34c29184298
Ref: library/test test support script_helper assert_python_ok9184582
Ref: 34c39184582
Ref: library/test test support script_helper assert_python_failure9185094
Ref: 34c49185094
Ref: library/test test support script_helper spawn_python9185434
Ref: 34c59185434
Ref: library/test test support script_helper kill_python9185745
Ref: 34c69185745
Ref: library/test test support script_helper make_script9185899
Ref: 34c79185899
Ref: library/test test support script_helper make_zip_script9186206
Ref: 34c89186206
Ref: library/test test support script_helper make_pkg9186573
Ref: 34c99186573
Ref: library/test test support script_helper make_zip_pkg9186764
Ref: 34ca9186764
Node: 调试和分析9187407
Ref: library/debug doc9187526
Ref: 34cb9187526
Ref: library/debug debugging-and-profiling9187526
Ref: 34cc9187526
Ref: library/audit_events audit-events9187933
Ref: 34cd9187933
Node: 审计事件表9188432
Ref: library/audit_events doc9188534
Ref: 34ce9188534
Ref: library/audit_events audit-events-table9188534
Ref: 34cf9188534
Ref: 审计事件表-Footnote-19241650
Node: bdb --- Debugger framework9241699
Ref: library/bdb doc9241852
Ref: 34f49241852
Ref: library/bdb bdb-debugger-framework9241852
Ref: 34f59241852
Ref: library/bdb module-bdb9241852
Ref: f9241852
Ref: library/bdb bdb BdbQuit9242176
Ref: 34f69242176
Ref: library/bdb bdb Breakpoint9242337
Ref: 34f79242337
Ref: library/bdb bdb Breakpoint deleteMe9243203
Ref: 34f89243203
Ref: library/bdb bdb Breakpoint enable9243419
Ref: 34f99243419
Ref: library/bdb bdb Breakpoint disable9243490
Ref: 34fa9243490
Ref: library/bdb bdb Breakpoint bpformat9243563
Ref: 34fb9243563
Ref: library/bdb bdb Breakpoint bpprint9243995
Ref: 34fc9243995
Ref: library/bdb bdb Bdb9244160
Ref: ca09244160
Ref: library/bdb bdb Bdb canonic9244937
Ref: 34fd9244937
Ref: library/bdb bdb Bdb reset9245195
Ref: 34fe9245195
Ref: library/bdb bdb Bdb trace_dispatch9245370
Ref: 34ff9245370
Ref: library/bdb bdb Bdb dispatch_line9246775
Ref: 35009246775
Ref: library/bdb bdb Bdb dispatch_call9247249
Ref: 35029247249
Ref: library/bdb bdb Bdb dispatch_return9247730
Ref: 35049247730
Ref: library/bdb bdb Bdb dispatch_exception9248219
Ref: 35069248219
Ref: library/bdb bdb Bdb stop_here9248875
Ref: 35089248875
Ref: library/bdb bdb Bdb break_here9249086
Ref: 35099249086
Ref: library/bdb bdb Bdb break_anywhere9249356
Ref: 350a9249356
Ref: library/bdb bdb Bdb user_call9249598
Ref: 35039249598
Ref: library/bdb bdb Bdb user_line9249835
Ref: 35019249835
Ref: library/bdb bdb Bdb user_return9250043
Ref: 35059250043
Ref: library/bdb bdb Bdb user_exception9250223
Ref: 35079250223
Ref: library/bdb bdb Bdb do_clear9250405
Ref: 350b9250405
Ref: library/bdb bdb Bdb set_step9250690
Ref: 350c9250690
Ref: library/bdb bdb Bdb set_next9250760
Ref: 350d9250760
Ref: library/bdb bdb Bdb set_return9250857
Ref: 350e9250857
Ref: library/bdb bdb Bdb set_until9250947
Ref: 350f9250947
Ref: library/bdb bdb Bdb set_trace9251118
Ref: 35109251118
Ref: library/bdb bdb Bdb set_continue9251277
Ref: 35119251277
Ref: library/bdb bdb Bdb set_quit9251450
Ref: 35129251450
Ref: library/bdb bdb Bdb set_break9251868
Ref: 35139251868
Ref: library/bdb bdb Bdb clear_break9252204
Ref: 35149252204
Ref: library/bdb bdb Bdb clear_bpbynumber9252374
Ref: 35159252374
Ref: library/bdb bdb Bdb clear_all_file_breaks9252597
Ref: 35169252597
Ref: library/bdb bdb Bdb clear_all_breaks9252756
Ref: 35179252756
Ref: library/bdb bdb Bdb get_bpbynumber9252838
Ref: 35189252838
Ref: library/bdb bdb Bdb get_break9253185
Ref: 35199253185
Ref: library/bdb bdb Bdb get_breaks9253302
Ref: 351a9253302
Ref: library/bdb bdb Bdb get_file_breaks9253456
Ref: 351b9253456
Ref: library/bdb bdb Bdb get_all_breaks9253594
Ref: 351c9253594
Ref: library/bdb bdb Bdb get_stack9253800
Ref: 351d9253800
Ref: library/bdb bdb Bdb format_stack_entry9253966
Ref: 351e9253966
Ref: library/bdb bdb Bdb run9254553
Ref: 351f9254553
Ref: library/bdb bdb Bdb runeval9254783
Ref: 35209254783
Ref: library/bdb bdb Bdb runctx9255011
Ref: 35219255011
Ref: library/bdb bdb Bdb runcall9255147
Ref: 2a09255147
Ref: library/bdb bdb checkfuncname9255313
Ref: 35229255313
Ref: library/bdb bdb effective9255749
Ref: 35239255749
Ref: library/bdb bdb set_trace9256066
Ref: 35249256066
Ref: bdb --- Debugger framework-Footnote-19256214
Node: faulthandler --- Dump the Python traceback9256276
Ref: library/faulthandler doc9256440
Ref: 35259256440
Ref: library/faulthandler faulthandler-dump-the-python-traceback9256440
Ref: 35269256440
Ref: library/faulthandler module-faulthandler9256440
Ref: 7d9256440
Node: Dumping the traceback9258478
Ref: library/faulthandler dumping-the-traceback9258606
Ref: 35279258606
Ref: library/faulthandler faulthandler dump_traceback9258669
Ref: 6e19258669
Node: Fault handler state9258969
Ref: library/faulthandler fault-handler-state9259144
Ref: 35289259144
Ref: library/faulthandler faulthandler enable9259203
Ref: 5519259203
Ref: library/faulthandler faulthandler disable9259881
Ref: 352a9259881
Ref: library/faulthandler faulthandler is_enabled9260020
Ref: 352b9260020
Node: Dumping the tracebacks after a timeout9260105
Ref: library/faulthandler dumping-the-tracebacks-after-a-timeout9260297
Ref: 352c9260297
Ref: library/faulthandler faulthandler dump_traceback_later9260394
Ref: 6e29260394
Ref: library/faulthandler faulthandler cancel_dump_traceback_later9261414
Ref: 352d9261414
Node: Dumping the traceback on a user signal9261536
Ref: library/faulthandler dumping-the-traceback-on-a-user-signal9261736
Ref: 352e9261736
Ref: library/faulthandler faulthandler register9261833
Ref: 6e09261833
Ref: library/faulthandler faulthandler unregister9262457
Ref: 352f9262457
Node: Issue with file descriptors9262730
Ref: library/faulthandler faulthandler-fd9262902
Ref: 35299262902
Ref: library/faulthandler issue-with-file-descriptors9262902
Ref: 35309262902
Node: 示例<15>9263370
Ref: library/faulthandler example9263495
Ref: 35319263495
Node: pdb --- Python的调试器9264037
Ref: library/pdb doc9264201
Ref: 35329264201
Ref: library/pdb debugger9264201
Ref: 35339264201
Ref: library/pdb module-pdb9264201
Ref: ca9264201
Ref: library/pdb pdb-the-python-debugger9264201
Ref: 35349264201
Ref: library/pdb pdb run9267195
Ref: 33199267195
Ref: library/pdb pdb runeval9267812
Ref: 35399267812
Ref: library/pdb pdb runcall9268109
Ref: 353a9268109
Ref: library/pdb pdb set_trace9268406
Ref: 3ca9268406
Ref: library/pdb pdb post_mortem9268765
Ref: d4d9268765
Ref: library/pdb pdb pm9268999
Ref: 353b9268999
Ref: library/pdb pdb Pdb9269307
Ref: 5759269307
Ref: library/pdb pdb Pdb run9270668
Ref: 353d9270668
Ref: library/pdb pdb Pdb runeval9270728
Ref: 353e9270728
Ref: library/pdb pdb Pdb runcall9270793
Ref: 353f9270793
Ref: library/pdb pdb Pdb set_trace9270844
Ref: 35409270844
Ref: pdb --- Python的调试器-Footnote-19270998
Ref: pdb --- Python的调试器-Footnote-29271060
Node: 调试器命令9271171
Ref: library/pdb debugger-commands9271249
Ref: 35359271249
Ref: library/pdb id29271249
Ref: 35419271249
Ref: library/pdb pdbcommand-help9273232
Ref: 35449273232
Ref: library/pdb pdbcommand-where9273591
Ref: 35459273591
Ref: library/pdb pdbcommand-down9273752
Ref: 35469273752
Ref: library/pdb pdbcommand-up9273899
Ref: 35479273899
Ref: library/pdb pdbcommand-break9274044
Ref: 35489274044
Ref: library/pdb pdbcommand-tbreak9274912
Ref: 35499274912
Ref: library/pdb pdbcommand-clear9275094
Ref: 354a9275094
Ref: library/pdb pdbcommand-disable9275401
Ref: 354b9275401
Ref: library/pdb pdbcommand-enable9275696
Ref: 354c9275696
Ref: library/pdb pdbcommand-ignore9275777
Ref: 354d9275777
Ref: library/pdb pdbcommand-condition9276127
Ref: 354e9276127
Ref: library/pdb pdbcommand-commands9276401
Ref: 354f9276401
Ref: library/pdb pdbcommand-step9277910
Ref: 35379277910
Ref: library/pdb pdbcommand-next9278064
Ref: 35389278064
Ref: library/pdb pdbcommand-until9278429
Ref: 35539278429
Ref: library/pdb pdbcommand-return9278758
Ref: 35509278758
Ref: library/pdb pdbcommand-continue9278833
Ref: 35369278833
Ref: library/pdb pdbcommand-jump9278915
Ref: 35519278915
Ref: library/pdb pdbcommand-list9279290
Ref: 35429279290
Ref: library/pdb pdbcommand-ll9279986
Ref: 35549279986
Ref: library/pdb pdbcommand-args9280148
Ref: 35559280148
Ref: library/pdb pdbcommand-p9280215
Ref: 8909280215
Ref: library/pdb pdbcommand-pp9280460
Ref: 35569280460
Ref: library/pdb pdbcommand-whatis9280604
Ref: 35579280604
Ref: library/pdb pdbcommand-source9280678
Ref: 35589280678
Ref: library/pdb pdbcommand-display9280798
Ref: 35599280798
Ref: library/pdb pdbcommand-undisplay9281021
Ref: 355a9281021
Ref: library/pdb pdbcommand-interact9281192
Ref: 355b9281192
Ref: library/pdb debugger-aliases9281413
Ref: 35439281413
Ref: library/pdb pdbcommand-alias9281413
Ref: 355c9281413
Ref: library/pdb pdbcommand-unalias9282433
Ref: 355d9282433
Ref: library/pdb pdbcommand-!9282494
Ref: 355e9282494
Ref: library/pdb pdbcommand-run9282882
Ref: 355f9282882
Ref: library/pdb pdbcommand-restart9282913
Ref: 35609282913
Ref: library/pdb pdbcommand-quit9283247
Ref: 35529283247
Ref: library/pdb pdbcommand-debug9283330
Ref: 35619283330
Ref: library/pdb pdbcommand-retval9283500
Ref: 35629283500
Node: Python Profilers 分析器9283589
Ref: library/profile doc9283758
Ref: 35639283758
Ref: library/profile profile9283758
Ref: 35649283758
Ref: library/profile the-python-profilers9283758
Ref: 35659283758
Ref: Python Profilers 分析器-Footnote-19284193
Ref: Python Profilers 分析器-Footnote-29284259
Node: profile分析器简介9284324
Ref: library/profile introduction-to-the-profilers9284436
Ref: 35669284436
Ref: library/profile profiler-introduction9284436
Ref: 35679284436
Node: 实时用户手册9285880
Ref: library/profile instant-user-s-manual9286034
Ref: 35689286034
Ref: library/profile profile-instant9286034
Ref: 35699286034
Node: profile 和 cProfile 模块参考9291927
Ref: library/profile module-cProfile9292068
Ref: 289292068
Ref: library/profile profile-and-cprofile-module-reference9292068
Ref: 356e9292068
Ref: library/profile module-profile9292166
Ref: d49292166
Ref: library/profile profile run9292241
Ref: 356f9292241
Ref: library/profile profile runctx9292874
Ref: 35709292874
Ref: library/profile profile Profile9293274
Ref: 1bc9293274
Ref: library/profile profile Profile enable9294844
Ref: 35719294844
Ref: library/profile profile Profile disable9294947
Ref: 35729294947
Ref: library/profile profile Profile create_stats9295051
Ref: 35739295051
Ref: library/profile profile Profile print_stats9295171
Ref: 35749295171
Ref: library/profile profile Profile dump_stats9295329
Ref: 35759295329
Ref: library/profile profile Profile run9295428
Ref: 35769295428
Ref: library/profile profile Profile runctx9295506
Ref: 35779295506
Ref: library/profile profile Profile runcall9295663
Ref: 29f9295663
Node: Stats 类9296004
Ref: library/profile profile-stats9296160
Ref: 35789296160
Ref: library/profile the-stats-class9296160
Ref: 35799296160
Ref: library/profile module-pstats9296279
Ref: d59296279
Ref: library/profile pstats Stats9296281
Ref: 356a9296281
Ref: library/profile pstats Stats strip_dirs9297525
Ref: 356c9297525
Ref: library/profile pstats Stats add9298343
Ref: 357a9298343
Ref: library/profile pstats Stats dump_stats9298836
Ref: 357b9298836
Ref: library/profile pstats Stats sort_stats9299217
Ref: 356b9299217
Ref: library/profile pstats Stats reverse_order9304574
Ref: 357c9304574
Ref: library/profile pstats Stats print_stats9304860
Ref: 356d9304860
Ref: library/profile pstats Stats print_callers9306304
Ref: 357d9306304
Ref: library/profile pstats Stats print_callees9307420
Ref: 357e9307420
Node: 什么是确定性性能分析？9307801
Ref: library/profile deterministic-profiling9307933
Ref: 357f9307933
Ref: library/profile what-is-deterministic-profiling9307933
Ref: 35809307933
Node: 局限性9309422
Ref: library/profile limitations9309557
Ref: 35819309557
Ref: library/profile profile-limitations9309557
Ref: 35829309557
Node: 准确估量9311074
Ref: library/profile calibration9311200
Ref: 35839311200
Ref: library/profile profile-calibration9311200
Ref: 35849311200
Node: 使用自定义计时器9312825
Ref: library/profile profile-timers9312933
Ref: 35859312933
Ref: library/profile using-a-custom-timer9312933
Ref: 35869312933
Node: timeit --- 测量小代码片段的执行时间9315384
Ref: library/timeit doc9315564
Ref: 35879315564
Ref: library/timeit module-timeit9315564
Ref: 10c9315564
Ref: library/timeit timeit-measure-execution-time-of-small-code-snippets9315564
Ref: 35889315564
Ref: timeit --- 测量小代码片段的执行时间-Footnote-19316246
Node: 基本示例<2>9316311
Ref: library/timeit basic-examples9316432
Ref: 358b9316432
Node: Python 接口9317621
Ref: library/timeit id19317769
Ref: 358d9317769
Ref: library/timeit python-interface9317769
Ref: 358a9317769
Ref: library/timeit timeit timeit9317873
Ref: 77a9317873
Ref: library/timeit timeit repeat9318285
Ref: 358f9318285
Ref: library/timeit timeit default_timer9318819
Ref: 35919318819
Ref: library/timeit timeit Timer9319011
Ref: 358e9319011
Ref: library/timeit timeit Timer timeit9320290
Ref: 5a59320290
Ref: library/timeit timeit Timer autorange9321147
Ref: 5a49321147
Ref: library/timeit timeit Timer repeat9321770
Ref: 35909321770
Ref: library/timeit timeit Timer print_exc9322769
Ref: 35929322769
Node: 命令行界面<6>9323293
Ref: library/timeit command-line-interface9323436
Ref: 35939323436
Ref: library/timeit timeit-command-line-interface9323436
Ref: 35899323436
Ref: library/timeit cmdoption-timeit-n9323634
Ref: 35949323634
Ref: library/timeit cmdoption-timeit-r9323706
Ref: 35959323706
Ref: library/timeit cmdoption-timeit-s9323789
Ref: 35969323789
Ref: library/timeit cmdoption-timeit-p9323888
Ref: 35979323888
Ref: library/timeit cmdoption-timeit-u9324112
Ref: 35989324112
Ref: library/timeit cmdoption-timeit-v9324251
Ref: 35999324251
Ref: library/timeit cmdoption-timeit-h9324342
Ref: 359a9324342
Node: 例子<25>9325417
Ref: library/timeit examples9325538
Ref: 359b9325538
Ref: library/timeit timeit-examples9325538
Ref: 358c9325538
Node: trace --- 跟踪Python语句的执行9328614
Ref: library/trace doc9328802
Ref: 359c9328802
Ref: library/trace module-trace9328802
Ref: 1139328802
Ref: library/trace trace-trace-or-track-python-statement-execution9328802
Ref: 359d9328802
Ref: trace --- 跟踪Python语句的执行-Footnote-19329479
Ref: trace --- 跟踪Python语句的执行-Footnote-29329543
Node: Command-Line Usage9329584
Ref: library/trace command-line-usage9329697
Ref: 359e9329697
Ref: library/trace trace-cli9329697
Ref: 359f9329697
Ref: library/trace cmdoption-trace-help9330051
Ref: 35a09330051
Ref: library/trace cmdoption-trace-version9330107
Ref: 35a19330107
Node: Main options9330327
Ref: library/trace main-options9330412
Ref: 35a29330412
Ref: library/trace cmdoption-trace-c9330802
Ref: 35a59330802
Ref: library/trace cmdoption-trace-t9331067
Ref: 35a49331067
Ref: library/trace cmdoption-trace-l9331140
Ref: 35a39331140
Ref: library/trace cmdoption-trace-r9331236
Ref: 35a99331236
Ref: library/trace cmdoption-trace-trackcalls9331440
Ref: 35aa9331440
Node: Modifiers9331548
Ref: library/trace modifiers9331649
Ref: 35ab9331649
Ref: library/trace cmdoption-trace-f9331688
Ref: 35a79331688
Ref: library/trace cmdoption-trace-coverdir9331853
Ref: 35a69331853
Ref: library/trace cmdoption-trace-m9332049
Ref: 35ac9332049
Ref: library/trace cmdoption-trace-s9332183
Ref: 35ad9332183
Ref: library/trace cmdoption-trace-no-report9332343
Ref: 35a89332343
Ref: library/trace cmdoption-trace-g9332572
Ref: 35ae9332572
Node: Filters9332699
Ref: library/trace filters9332779
Ref: 35af9332779
Ref: library/trace cmdoption-trace-ignore-module9332861
Ref: 35b09332861
Ref: library/trace cmdoption-trace-ignore-dir9333056
Ref: 35b19333056
Node: 编程接口9333265
Ref: library/trace programmatic-interface9333378
Ref: 35b29333378
Ref: library/trace trace-api9333378
Ref: 35b39333378
Ref: library/trace trace Trace9333419
Ref: 35b49333419
Ref: library/trace trace Trace run9334328
Ref: 35b59334328
Ref: library/trace trace Trace runctx9334570
Ref: 35b69334570
Ref: library/trace trace Trace runfunc9334884
Ref: 2a19334884
Ref: library/trace trace Trace results9335074
Ref: 35b79335074
Ref: library/trace trace CoverageResults9335383
Ref: 35b89335383
Ref: library/trace trace CoverageResults update9335545
Ref: 35b99335545
Ref: library/trace trace CoverageResults write_results9335663
Ref: 35ba9335663
Node: tracemalloc --- 跟踪内存分配9336693
Ref: library/tracemalloc doc9336825
Ref: 35bb9336825
Ref: library/tracemalloc module-tracemalloc9336825
Ref: 1159336825
Ref: library/tracemalloc tracemalloc-trace-memory-allocations9336825
Ref: 35bc9336825
Ref: tracemalloc --- 跟踪内存分配-Footnote-19338141
Node: 例子<26>9338211
Ref: library/tracemalloc examples9338304
Ref: 35bd9338304
Node: 显示前10项9338436
Ref: library/tracemalloc display-the-top-109338518
Ref: 35be9338518
Node: 计算差异9339976
Ref: library/tracemalloc compute-differences9340102
Ref: 35c09340102
Node: Get the traceback of a memory block9342263
Ref: library/tracemalloc get-the-traceback-of-a-memory-block9342385
Ref: 35c39342385
Node: Pretty top9345017
Ref: library/tracemalloc pretty-top9345118
Ref: 35c49345118
Node: API9347498
Ref: library/tracemalloc api9347591
Ref: 35c59347591
Node: 函数<9>9347762
Ref: library/tracemalloc functions9347832
Ref: 35c69347832
Ref: library/tracemalloc tracemalloc clear_traces9347863
Ref: 35c79347863
Ref: library/tracemalloc tracemalloc get_object_traceback9347996
Ref: 11769347996
Ref: library/tracemalloc tracemalloc get_traceback_limit9348401
Ref: 35ca9348401
Ref: library/tracemalloc tracemalloc get_traced_memory9348723
Ref: 35cb9348723
Ref: library/tracemalloc tracemalloc get_tracemalloc_memory9348927
Ref: 35cc9348927
Ref: library/tracemalloc tracemalloc is_tracing9349123
Ref: 35cd9349123
Ref: library/tracemalloc tracemalloc start9349354
Ref: 135f9349354
Ref: library/tracemalloc tracemalloc stop9350552
Ref: 35c89350552
Ref: library/tracemalloc tracemalloc take_snapshot9350984
Ref: 35cf9350984
Node: 域过滤器9351682
Ref: library/tracemalloc domainfilter9351770
Ref: 35d19351770
Ref: library/tracemalloc tracemalloc DomainFilter9351811
Ref: 5a99351811
Ref: library/tracemalloc tracemalloc DomainFilter inclusive9351971
Ref: 35d29351971
Ref: library/tracemalloc tracemalloc DomainFilter domain9352268
Ref: 35d39352268
Node: 过滤器9352370
Ref: library/tracemalloc filter9352454
Ref: 35d49352454
Ref: library/tracemalloc tracemalloc Filter9352490
Ref: 35d59352490
Ref: library/tracemalloc tracemalloc Filter domain9353327
Ref: 35d69353327
Ref: library/tracemalloc tracemalloc Filter inclusive9353595
Ref: 35d79353595
Ref: library/tracemalloc tracemalloc Filter lineno9354024
Ref: 35d99354024
Ref: library/tracemalloc tracemalloc Filter filename_pattern9354173
Ref: 35d89354173
Ref: library/tracemalloc tracemalloc Filter all_frames9354284
Ref: 35da9354284
Node: Frame9354688
Ref: library/tracemalloc frame9354766
Ref: 35dc9354766
Ref: library/tracemalloc tracemalloc Frame9354799
Ref: 35dd9354799
Ref: library/tracemalloc tracemalloc Frame filename9354945
Ref: 35de9354945
Ref: library/tracemalloc tracemalloc Frame lineno9355014
Ref: 35df9355014
Node: 快照9355075
Ref: library/tracemalloc snapshot9355150
Ref: 35e09355150
Ref: library/tracemalloc tracemalloc Snapshot9355183
Ref: 35d09355183
Ref: library/tracemalloc tracemalloc Snapshot compare_to9355359
Ref: 35ce9355359
Ref: library/tracemalloc tracemalloc Snapshot dump9356085
Ref: 35c19356085
Ref: library/tracemalloc tracemalloc Snapshot filter_traces9356206
Ref: 35e79356206
Ref: library/tracemalloc tracemalloc Snapshot load9356878
Ref: 35c29356878
Ref: library/tracemalloc tracemalloc Snapshot statistics9356998
Ref: 35bf9356998
Ref: library/tracemalloc tracemalloc Snapshot traceback_limit9358159
Ref: 35db9358159
Ref: library/tracemalloc tracemalloc Snapshot traces9358375
Ref: 35e89358375
Node: 统计9358667
Ref: library/tracemalloc statistic9358750
Ref: 35ed9358750
Ref: library/tracemalloc tracemalloc Statistic9358783
Ref: 35e99358783
Ref: library/tracemalloc tracemalloc Statistic count9358984
Ref: 35e59358984
Ref: library/tracemalloc tracemalloc Statistic size9359053
Ref: 35ea9359053
Ref: library/tracemalloc tracemalloc Statistic traceback9359137
Ref: 35eb9359137
Node: StatisticDiff9359266
Ref: library/tracemalloc statisticdiff9359349
Ref: 35ee9359349
Ref: library/tracemalloc tracemalloc StatisticDiff9359398
Ref: 35e19359398
Ref: library/tracemalloc tracemalloc StatisticDiff count9359696
Ref: 35ef9359696
Ref: library/tracemalloc tracemalloc StatisticDiff count_diff9359867
Ref: 35e49359867
Ref: library/tracemalloc tracemalloc StatisticDiff size9360086
Ref: 35e39360086
Ref: library/tracemalloc tracemalloc StatisticDiff size_diff9360279
Ref: 35e29360279
Ref: library/tracemalloc tracemalloc StatisticDiff traceback9360510
Ref: 35e69360510
Node: 跟踪9360641
Ref: library/tracemalloc trace9360727
Ref: 35f09360727
Ref: library/tracemalloc tracemalloc Trace9360760
Ref: 35ec9360760
Ref: library/tracemalloc tracemalloc Trace domain9360986
Ref: 35f19360986
Ref: library/tracemalloc tracemalloc Trace size9361261
Ref: 35f29361261
Ref: library/tracemalloc tracemalloc Trace traceback9361342
Ref: 35f39361342
Node: 回溯<4>9361471
Ref: library/tracemalloc traceback9361535
Ref: 35f49361535
Ref: library/tracemalloc tracemalloc Traceback9361568
Ref: 4079361568
Ref: library/tracemalloc tracemalloc Traceback format9362282
Ref: 4089362282
Node: 软件打包和分发9363364
Ref: library/distribution doc9363492
Ref: 35f69363492
Ref: library/distribution software-packaging-and-distribution9363492
Ref: 35f79363492
Node: distutils --- 构建和安装 Python 模块9364138
Ref: library/distutils doc9364293
Ref: 35f89364293
Ref: library/distutils distutils-building-and-installing-python-modules9364293
Ref: 35f99364293
Ref: library/distutils module-distutils9364293
Ref: 399364293
Ref: distutils --- 构建和安装 Python 模块-Footnote-19365911
Ref: distutils --- 构建和安装 Python 模块-Footnote-29365964
Ref: distutils --- 构建和安装 Python 模块-Footnote-39365993
Node: ensurepip --- Bootstrapping the pip installer9366030
Ref: library/ensurepip doc9366221
Ref: 35fa9366221
Ref: library/ensurepip ensurepip-bootstrapping-the-pip-installer9366221
Ref: 35fb9366221
Ref: library/ensurepip module-ensurepip9366221
Ref: 7a9366221
Ref: ensurepip --- Bootstrapping the pip installer-Footnote-19367615
Node: Command line interface9367664
Ref: library/ensurepip command-line-interface9367787
Ref: 35fc9367787
Node: Module API9369564
Ref: library/ensurepip module-api9369687
Ref: 35fd9369687
Ref: library/ensurepip ensurepip version9369794
Ref: 35fe9369794
Ref: library/ensurepip ensurepip bootstrap9369952
Ref: 34d69369952
Node: venv --- 创建虚拟环境9371729
Ref: library/venv doc9371925
Ref: 35ff9371925
Ref: library/venv module-venv9371925
Ref: 1269371925
Ref: library/venv venv-creation-of-virtual-environments9371925
Ref: 36009371925
Ref: venv --- 创建虚拟环境-Footnote-19372743
Ref: venv --- 创建虚拟环境-Footnote-29372804
Ref: venv --- 创建虚拟环境-Footnote-39372853
Node: 创建虚拟环境<2>9372976
Ref: library/venv creating-virtual-environments9373076
Ref: 36019373076
Ref: library/venv venv-def9379575
Ref: 36029379575
Ref: 创建虚拟环境<2>-Footnote-19381990
Ref: 创建虚拟环境<2>-Footnote-29382064
Ref: 创建虚拟环境<2>-Footnote-39382119
Ref: 创建虚拟环境<2>-Footnote-49382164
Ref: 创建虚拟环境<2>-Footnote-59382202
Node: API<2>9382251
Ref: library/venv api9382393
Ref: 36069382393
Ref: library/venv venv-api9382393
Ref: 7fb9382393
Ref: library/venv venv EnvBuilder9382630
Ref: 9109382630
Ref: library/venv venv EnvBuilder create9384215
Ref: 36079384215
Ref: library/venv venv EnvBuilder ensure_directories9385375
Ref: 36089385375
Ref: library/venv venv EnvBuilder create_configuration9385750
Ref: 36099385750
Ref: library/venv venv EnvBuilder setup_python9385862
Ref: 360a9385862
Ref: library/venv venv EnvBuilder setup_scripts9386200
Ref: 360b9386200
Ref: library/venv venv EnvBuilder post_setup9386314
Ref: 360c9386314
Ref: library/venv venv EnvBuilder install_scripts9387246
Ref: 360d9387246
Ref: library/venv venv create9388289
Ref: 9119388289
Node: 一个扩展 EnvBuilder 的例子9388700
Ref: library/venv an-example-of-extending-envbuilder9388812
Ref: 360e9388812
Ref: 一个扩展 EnvBuilder 的例子-Footnote-19399536
Node: zipapp --- Manage executable Python zip archives9399583
Ref: library/zipapp doc9399725
Ref: 360f9399725
Ref: library/zipapp module-zipapp9399725
Ref: 1429399725
Ref: library/zipapp pip9399725
Ref: 36109399725
Ref: library/zipapp zipapp-manage-executable-python-zip-archives9399725
Ref: 36119399725
Ref: zipapp --- Manage executable Python zip archives-Footnote-19400475
Node: Basic Example9400540
Ref: library/zipapp basic-example9400665
Ref: 36149400665
Node: 命令行界面<7>9401062
Ref: library/zipapp command-line-interface9401206
Ref: 36159401206
Ref: library/zipapp zipapp-command-line-interface9401206
Ref: 36129401206
Ref: library/zipapp cmdoption-zipapp-o9401683
Ref: 36169401683
Ref: library/zipapp cmdoption-zipapp-p9402186
Ref: 36179402186
Ref: library/zipapp cmdoption-zipapp-m9402468
Ref: 36189402468
Ref: library/zipapp cmdoption-zipapp-c9402893
Ref: 36199402893
Ref: library/zipapp cmdoption-zipapp-info9403174
Ref: 361a9403174
Ref: library/zipapp cmdoption-zipapp-h9403383
Ref: 361b9403383
Node: Python API9403457
Ref: library/zipapp python-api9403598
Ref: 361c9403598
Ref: library/zipapp zipapp-python-api9403598
Ref: 36139403598
Ref: library/zipapp zipapp create_archive9403686
Ref: 4259403686
Ref: library/zipapp zipapp get_interpreter9407453
Ref: 361d9407453
Node: 例子<27>9407808
Ref: library/zipapp examples9407957
Ref: 361e9407957
Ref: library/zipapp zipapp-examples9407957
Ref: 361f9407957
Node: Specifying the Interpreter9409316
Ref: library/zipapp specifying-the-interpreter9409499
Ref: 36209409499
Ref: library/zipapp zipapp-specifying-the-interpreter9409499
Ref: 36219409499
Node: Creating Standalone Applications with zipapp9410706
Ref: library/zipapp creating-standalone-applications-with-zipapp9410920
Ref: 36229410920
Node: Making a Windows executable9412958
Ref: library/zipapp making-a-windows-executable9413082
Ref: 36239413082
Node: Caveats9416197
Ref: library/zipapp caveats9416321
Ref: 36249416321
Node: The Python Zip Application Archive Format9418111
Ref: library/zipapp the-python-zip-application-archive-format9418290
Ref: 36259418290
Node: Python运行时服务9420181
Ref: library/python doc9420320
Ref: 36269420320
Ref: library/python python9420320
Ref: 36279420320
Ref: library/python python-runtime-services9420320
Ref: 36289420320
Node: sys --- 系统相关的参数和函数9421444
Ref: library/sys doc9421615
Ref: 36299421615
Ref: library/sys module-sys9421615
Ref: fe9421615
Ref: library/sys sys-system-specific-parameters-and-functions9421615
Ref: 362a9421615
Ref: library/sys sys abiflags9421946
Ref: 2659421946
Ref: library/sys sys addaudithook9422266
Ref: 34d09422266
Ref: library/sys sys argv9423816
Ref: c039423816
Ref: library/sys auditing9424685
Ref: ea19424685
Ref: library/sys sys audit9424685
Ref: f389424685
Ref: library/sys sys base_exec_prefix9425988
Ref: 36059425988
Ref: library/sys sys base_prefix9426561
Ref: 304e9426561
Ref: library/sys sys byteorder9427123
Ref: 16319427123
Ref: library/sys sys builtin_module_names9427347
Ref: 362b9427347
Ref: library/sys sys call_tracing9427608
Ref: 362c9427608
Ref: library/sys sys copyright9427842
Ref: 362d9427842
Ref: library/sys sys _clear_type_cache9427941
Ref: 362e9427941
Ref: library/sys sys _current_frames9428234
Ref: da39428234
Ref: library/sys sys breakpointhook9429011
Ref: 31c9429011
Ref: library/sys sys _debugmallocstats9430803
Ref: 362f9430803
Ref: library/sys sys dllhandle9431207
Ref: 36309431207
Ref: library/sys sys displayhook9431318
Ref: e679431318
Ref: library/sys sys dont_write_bytecode9432872
Ref: 36329432872
Ref: library/sys sys pycache_prefix9433250
Ref: 1579433250
Ref: library/sys sys excepthook9434172
Ref: e6b9434172
Ref: library/sys sys __breakpointhook__9435100
Ref: 36339435100
Ref: library/sys sys __displayhook__9435135
Ref: 36349435135
Ref: library/sys sys __excepthook__9435167
Ref: 36359435167
Ref: library/sys sys __unraisablehook__9435198
Ref: 36369435198
Ref: library/sys sys exc_info9435636
Ref: c679435636
Ref: library/sys sys exec_prefix9436622
Ref: 36049436622
Ref: library/sys sys executable9437442
Ref: 2759437442
Ref: library/sys sys exit9437741
Ref: cea9437741
Ref: library/sys sys flags9439171
Ref: b449439171
Ref: library/sys sys float_info9442118
Ref: fd19442118
Ref: library/sys sys float_repr_style9446394
Ref: c989446394
Ref: library/sys sys getallocatedblocks9446936
Ref: 8ea9446936
Ref: library/sys sys getandroidapilevel9447463
Ref: 3f99447463
Ref: library/sys sys getcheckinterval9447634
Ref: e109447634
Ref: library/sys sys getdefaultencoding9447836
Ref: 363a9447836
Ref: library/sys sys getdlopenflags9447951
Ref: e569447951
Ref: library/sys sys getfilesystemencoding9448247
Ref: 4fe9448247
Ref: library/sys sys getfilesystemencodeerrors9449565
Ref: 59d9449565
Ref: library/sys sys getrefcount9449980
Ref: 363b9449980
Ref: library/sys sys getrecursionlimit9450198
Ref: e829450198
Ref: library/sys sys getsizeof9450465
Ref: 35c99450465
Ref: library/sys sys getswitchinterval9451315
Ref: 36399451315
Ref: library/sys sys _getframe9451484
Ref: e6c9451484
Ref: library/sys sys getprofile9452049
Ref: d4f9452049
Ref: library/sys sys gettrace9452149
Ref: d509452149
Ref: library/sys sys getwindowsversion9452514
Ref: 59e9452514
Ref: library/sys sys get_asyncgen_hooks9454840
Ref: 363c9454840
Ref: library/sys sys get_coroutine_origin_tracking_depth9455357
Ref: 3fa9455357
Ref: library/sys sys hash_info9455682
Ref: 9299455682
Ref: library/sys sys hexversion9457235
Ref: 363e9457235
Ref: library/sys sys implementation9458066
Ref: 9b29458066
Ref: library/sys sys int_info9459912
Ref: c299459912
Ref: library/sys sys __interactivehook__9460656
Ref: 8ec9460656
Ref: library/sys sys intern9461161
Ref: c769461161
Ref: library/sys sys is_finalizing9461836
Ref: 76b9461836
Ref: library/sys sys last_type9462020
Ref: c629462020
Ref: library/sys sys last_value9462046
Ref: 36409462046
Ref: library/sys sys last_traceback9462073
Ref: 353c9462073
Ref: library/sys sys maxsize9462618
Ref: b4b9462618
Ref: library/sys sys maxunicode9462831
Ref: 9939462831
Ref: library/sys sys meta_path9463197
Ref: 5ef9463197
Ref: library/sys sys modules9464364
Ref: f369464364
Ref: library/sys sys path9464671
Ref: 4909464671
Ref: library/sys sys path_hooks9465631
Ref: 9649465631
Ref: library/sys sys path_importer_cache9465989
Ref: 4a59465989
Ref: library/sys sys platform9466506
Ref: 2b29466506
Ref: library/sys sys prefix9468734
Ref: 36039468734
Ref: library/sys sys ps19469506
Ref: 13669469506
Ref: library/sys sys ps29469526
Ref: 13679469526
Ref: library/sys sys setcheckinterval9469971
Ref: 36389469971
Ref: library/sys sys setdlopenflags9470740
Ref: a6e9470740
Ref: library/sys sys setprofile9471267
Ref: e459471267
Ref: library/sys sys setrecursionlimit9473420
Ref: e839473420
Ref: library/sys sys setswitchinterval9474092
Ref: bf39474092
Ref: library/sys sys settrace9474576
Ref: e469474576
Ref: library/sys sys set_asyncgen_hooks9478836
Ref: f399478836
Ref: library/sys sys set_coroutine_origin_tracking_depth9479849
Ref: 3fb9479849
Ref: library/sys sys _enablelegacywindowsfsencoding9480644
Ref: 5009480644
Ref: library/sys sys stdin9481088
Ref: 3169481088
Ref: library/sys sys stdout9481110
Ref: 3179481110
Ref: library/sys sys stderr9481133
Ref: 3189481133
Ref: library/sys sys __stdin__9483790
Ref: 36429483790
Ref: library/sys sys __stdout__9483816
Ref: 1cac9483816
Ref: library/sys sys __stderr__9483843
Ref: 36439483843
Ref: library/sys sys thread_info9484760
Ref: aaa9484760
Ref: library/sys sys tracebacklimit9486096
Ref: 36449486096
Ref: library/sys sys unraisablehook9486403
Ref: 22e9486403
Ref: library/sys sys version9488086
Ref: 5dc9488086
Ref: library/sys sys api_version9488430
Ref: 36459488430
Ref: library/sys sys version_info9488588
Ref: b229488588
Ref: library/sys sys warnoptions9489178
Ref: 41e9489178
Ref: library/sys sys winver9489360
Ref: 36469489360
Ref: library/sys sys _xoptions9489753
Ref: 13619489753
Ref: library/sys c999490503
Ref: 36379490503
Ref: sys --- 系统相关的参数和函数-Footnote-19490702
Ref: sys --- 系统相关的参数和函数-Footnote-29490751
Ref: sys --- 系统相关的参数和函数-Footnote-39490800
Ref: sys --- 系统相关的参数和函数-Footnote-49490849
Ref: sys --- 系统相关的参数和函数-Footnote-59490901
Ref: sys --- 系统相关的参数和函数-Footnote-69490950
Ref: sys --- 系统相关的参数和函数-Footnote-79490999
Ref: sys --- 系统相关的参数和函数-Footnote-89491048
Ref: sys --- 系统相关的参数和函数-Footnote-99491097
Ref: sys --- 系统相关的参数和函数-Footnote-109491146
Ref: sys --- 系统相关的参数和函数-Footnote-119491196
Ref: sys --- 系统相关的参数和函数-Footnote-129491246
Ref: sys --- 系统相关的参数和函数-Footnote-139491296
Ref: sys --- 系统相关的参数和函数-Footnote-149491346
Ref: sys --- 系统相关的参数和函数-Footnote-159491396
Ref: sys --- 系统相关的参数和函数-Footnote-169491476
Ref: sys --- 系统相关的参数和函数-Footnote-179491526
Ref: sys --- 系统相关的参数和函数-Footnote-189491576
Node: sysconfig --- Provide access to Python's configuration information9491626
Ref: library/sysconfig doc9491831
Ref: 36479491831
Ref: library/sysconfig module-sysconfig9491831
Ref: ff9491831
Ref: library/sysconfig sysconfig-provide-access-to-python-s-configuration-information9491831
Ref: 36489491831
Ref: sysconfig --- Provide access to Python's configuration information-Footnote-19492448
Node: 配置变量9492516
Ref: library/sysconfig configuration-variables9492652
Ref: 36499492652
Ref: library/sysconfig sysconfig get_config_vars9493119
Ref: 96d9493119
Ref: library/sysconfig sysconfig get_config_var9493488
Ref: 96c9493488
Node: 安装路径9493925
Ref: library/sysconfig installation-paths9494085
Ref: 364a9494085
Ref: library/sysconfig sysconfig get_scheme_names9496044
Ref: 364b9496044
Ref: library/sysconfig sysconfig get_path_names9496180
Ref: 364c9496180
Ref: library/sysconfig sysconfig get_path9496317
Ref: cc69496317
Ref: library/sysconfig sysconfig get_paths9497524
Ref: be19497524
Node: 其他功能<3>9498145
Ref: library/sysconfig other-functions9498320
Ref: 364d9498320
Ref: library/sysconfig sysconfig get_python_version9498361
Ref: be09498361
Ref: library/sysconfig sysconfig get_platform9498530
Ref: bdf9498530
Ref: library/sysconfig sysconfig is_python_build9499532
Ref: cc79499532
Ref: library/sysconfig sysconfig parse_config_h9499821
Ref: 364e9499821
Ref: library/sysconfig sysconfig get_config_h_filename9500213
Ref: 364f9500213
Ref: library/sysconfig sysconfig get_makefile_filename9500301
Ref: 36509500301
Node: Using sysconfig as a script9500387
Ref: library/sysconfig using-sysconfig-as-a-script9500541
Ref: 36519500541
Node: builtins --- 内建对象9501614
Ref: library/builtins doc9501812
Ref: 36529501812
Ref: library/builtins builtins-built-in-objects9501812
Ref: 36539501812
Ref: library/builtins module-builtins9501812
Ref: 139501812
Node: __main__ --- 顶层脚本环境9503164
Ref: library/__main__ doc9503324
Ref: 36549503324
Ref: library/__main__ main-top-level-script-environment9503324
Ref: 36559503324
Ref: library/__main__ module-__main__9503324
Ref: 19503324
Node: warnings --- Warning control9504145
Ref: library/warnings doc9504305
Ref: 36569504305
Ref: library/warnings module-warnings9504305
Ref: 1279504305
Ref: library/warnings warnings-warning-control9504305
Ref: 36579504305
Ref: warnings --- Warning control-Footnote-19506581
Node: 警告类别9506648
Ref: library/warnings id19506753
Ref: 365b9506753
Ref: library/warnings warning-categories9506753
Ref: 17299506753
Node: The Warnings Filter9510709
Ref: library/warnings the-warnings-filter9510841
Ref: 365c9510841
Ref: library/warnings warning-filter9510841
Ref: 135c9510841
Node: Describing Warning Filters9513387
Ref: library/warnings describing-warning-filters9513499
Ref: 135d9513499
Ref: library/warnings id29513499
Ref: 365d9513499
Node: 默认警告过滤器9515295
Ref: library/warnings default-warning-filter9515445
Ref: 365e9515445
Ref: library/warnings id39515445
Ref: 365f9515445
Node: Overriding the default filter9516508
Ref: library/warnings overriding-the-default-filter9516623
Ref: 36609516623
Ref: library/warnings warning-disable9516623
Ref: 36619516623
Node: 暂时禁止警告9518058
Ref: library/warnings temporarily-suppressing-warnings9518190
Ref: 36629518190
Ref: library/warnings warning-suppress9518190
Ref: 36639518190
Node: 测试警告9519174
Ref: library/warnings testing-warnings9519333
Ref: 36649519333
Ref: library/warnings warning-testing9519333
Ref: 36659519333
Node: Updating Code For New Versions of Dependencies9521385
Ref: library/warnings updating-code-for-new-versions-of-dependencies9521545
Ref: 36669521545
Ref: library/warnings warning-ignored9521545
Ref: 337f9521545
Node: Available Functions9522931
Ref: library/warnings available-functions9523105
Ref: 36679523105
Ref: library/warnings warning-functions9523105
Ref: 36689523105
Ref: library/warnings warnings warn9523164
Ref: e609523164
Ref: library/warnings warnings warn_explicit9524377
Ref: 5b99524377
Ref: library/warnings warnings showwarning9525548
Ref: 365a9525548
Ref: library/warnings warnings formatwarning9526184
Ref: 10029526184
Ref: library/warnings warnings filterwarnings9526614
Ref: e0f9526614
Ref: library/warnings warnings simplefilter9527289
Ref: 34669527289
Ref: library/warnings warnings resetwarnings9527723
Ref: 36599527723
Node: Available Context Managers9527989
Ref: library/warnings available-context-managers9528108
Ref: 36699528108
Ref: library/warnings warnings catch_warnings9528183
Ref: 34659528183
Node: dataclasses --- 数据类9529432
Ref: library/dataclasses doc9529614
Ref: 366a9529614
Ref: library/dataclasses dataclasses-data-classes9529614
Ref: 366b9529614
Ref: library/dataclasses module-dataclasses9529614
Ref: 309529614
Ref: dataclasses --- 数据类-Footnote-19531122
Ref: dataclasses --- 数据类-Footnote-29531192
Ref: dataclasses --- 数据类-Footnote-39531241
Node: 模块级装饰器、类和函数9531290
Ref: library/dataclasses module-level-decorators-classes-and-functions9531412
Ref: 366d9531412
Ref: library/dataclasses dataclasses dataclass9531488
Ref: 3469531488
Ref: library/dataclasses dataclasses field9537832
Ref: 100e9537832
Ref: library/dataclasses dataclasses Field9541603
Ref: 366e9541603
Ref: library/dataclasses dataclasses fields9542317
Ref: 366f9542317
Ref: library/dataclasses dataclasses asdict9542643
Ref: 36709542643
Ref: library/dataclasses dataclasses astuple9543399
Ref: 36719543399
Ref: library/dataclasses dataclasses make_dataclass9543886
Ref: 36729543886
Ref: library/dataclasses dataclasses replace9545380
Ref: ea89545380
Ref: library/dataclasses dataclasses is_dataclass9546683
Ref: 36739546683
Node: 初始化后处理9547127
Ref: library/dataclasses post-init-processing9547267
Ref: 36749547267
Node: 类变量9548240
Ref: library/dataclasses class-variables9548365
Ref: 36759548365
Ref: 类变量-Footnote-19548866
Node: 仅初始化变量9548915
Ref: library/dataclasses init-only-variables9549037
Ref: 36769549037
Node: 冻结的实例9550214
Ref: library/dataclasses frozen-instances9550336
Ref: 36779550336
Node: 继承<2>9550906
Ref: library/dataclasses inheritance9551028
Ref: 36799551028
Node: 默认工厂函数9552001
Ref: library/dataclasses default-factory-functions9552126
Ref: 367a9552126
Node: 可变的默认值9552762
Ref: library/dataclasses mutable-default-values9552888
Ref: 367b9552888
Node: 异常<17>9554677
Ref: library/dataclasses exceptions9554776
Ref: 367c9554776
Ref: library/dataclasses dataclasses FrozenInstanceError9554807
Ref: 36789554807
Node: contextlib --- 为 with语句上下文提供的工具9555062
Ref: library/contextlib doc9555236
Ref: 367d9555236
Ref: library/contextlib contextlib-utilities-for-with-statement-contexts9555236
Ref: 367e9555236
Ref: library/contextlib module-contextlib9555236
Ref: 249555236
Ref: contextlib --- 为 with语句上下文提供的工具-Footnote-19555863
Node: 工具9555932
Ref: library/contextlib utilities9556055
Ref: 367f9556055
Ref: library/contextlib contextlib AbstractContextManager9556112
Ref: 53c9556112
Ref: library/contextlib contextlib AbstractAsyncContextManager9556577
Ref: 3819556577
Ref: library/contextlib contextlib contextmanager9557047
Ref: b869557047
Ref: library/contextlib contextlib asynccontextmanager9559843
Ref: 3809559843
Ref: library/contextlib contextlib closing9560844
Ref: 36809560844
Ref: library/contextlib simplifying-support-for-single-optional-context-managers9561622
Ref: 36819561622
Ref: library/contextlib contextlib nullcontext9561622
Ref: 37e9561622
Ref: library/contextlib contextlib suppress9562722
Ref: 8359562722
Ref: library/contextlib contextlib redirect_stdout9563792
Ref: 6cb9563792
Ref: library/contextlib contextlib redirect_stderr9565129
Ref: 6ca9565129
Ref: library/contextlib contextlib ContextDecorator9565400
Ref: b859565400
Ref: library/contextlib contextlib ExitStack9567695
Ref: 37f9567695
Ref: library/contextlib contextlib ExitStack enter_context9569435
Ref: 36839569435
Ref: library/contextlib contextlib ExitStack push9569867
Ref: 36849569867
Ref: library/contextlib contextlib ExitStack callback9570755
Ref: 2a69570755
Ref: library/contextlib contextlib ExitStack pop_all9571208
Ref: 36859571208
Ref: library/contextlib contextlib ExitStack close9572256
Ref: 36869572256
Ref: library/contextlib contextlib AsyncExitStack9572544
Ref: 3829572544
Ref: library/contextlib contextlib AsyncExitStack enter_async_context9572903
Ref: 36889572903
Ref: library/contextlib contextlib AsyncExitStack push_async_exit9573045
Ref: 36899573045
Ref: library/contextlib contextlib AsyncExitStack push_async_callback9573207
Ref: 2a79573207
Ref: library/contextlib contextlib AsyncExitStack aclose9573344
Ref: 36879573344
Node: 例子和配方<2>9573916
Ref: library/contextlib examples-and-recipes9574098
Ref: 368a9574098
Node: Supporting a variable number of context managers9574531
Ref: library/contextlib supporting-a-variable-number-of-context-managers9574685
Ref: 368b9574685
Node: Catching exceptions from __enter__ methods9575727
Ref: library/contextlib catching-exceptions-from-enter-methods9575932
Ref: 368c9575932
Node: Cleaning up in an __enter__ implementation9577080
Ref: library/contextlib cleaning-up-in-an-enter-implementation9577288
Ref: 368d9577288
Node: Replacing any use of try-finally and flag variables9579191
Ref: library/contextlib replacing-any-use-of-try-finally-and-flag-variables9579404
Ref: 368e9579404
Node: Using a context manager as a function decorator9581919
Ref: library/contextlib using-a-context-manager-as-a-function-decorator9582081
Ref: 368f9582081
Ref: Using a context manager as a function decorator-Footnote-19583873
Node: Single use reusable and reentrant context managers9583922
Ref: library/contextlib single-use-reusable-and-reentrant-cms9584089
Ref: 8379584089
Ref: library/contextlib single-use-reusable-and-reentrant-context-managers9584089
Ref: 36909584089
Node: Reentrant context managers9585626
Ref: library/contextlib reentrant-cms9585773
Ref: 36829585773
Ref: library/contextlib reentrant-context-managers9585773
Ref: 36919585773
Node: Reusable context managers9587285
Ref: library/contextlib reusable-cms9587432
Ref: 36929587432
Ref: library/contextlib reusable-context-managers9587432
Ref: 36939587432
Node: abc --- 抽象基类9590102
Ref: library/abc doc9590277
Ref: 36949590277
Ref: library/abc abc-abstract-base-classes9590277
Ref: 36959590277
Ref: library/abc module-abc9590277
Ref: 49590277
Ref: library/abc abc ABC9591221
Ref: 8219591221
Ref: library/abc abc ABCMeta9591978
Ref: 8229591978
Ref: library/abc abc ABCMeta register9592695
Ref: 9d99592695
Ref: library/abc abc ABCMeta __subclasshook__9593326
Ref: 36969593326
Ref: library/abc abc abstractmethod9596071
Ref: 9d69596071
Ref: library/abc abc abstractclassmethod9598839
Ref: 9d79598839
Ref: library/abc abc abstractstaticmethod9599524
Ref: 9d89599524
Ref: library/abc abc abstractproperty9600207
Ref: 9d59600207
Ref: library/abc abc get_cache_token9601515
Ref: 8209601515
Ref: abc --- 抽象基类-Footnote-19601903
Ref: abc --- 抽象基类-Footnote-29601965
Ref: abc --- 抽象基类-Footnote-39602014
Ref: abc --- 抽象基类-Footnote-49602063
Node: atexit --- 退出处理器9602162
Ref: library/atexit doc9602325
Ref: 36979602325
Ref: library/atexit atexit-exit-handlers9602325
Ref: 36989602325
Ref: library/atexit module-atexit9602325
Ref: c9602325
Ref: library/atexit atexit register9603107
Ref: e8d9603107
Ref: library/atexit atexit unregister9604016
Ref: 36999604016
Node: atexit 示例9604534
Ref: library/atexit atexit-example9604610
Ref: 369a9604610
Ref: library/atexit id19604610
Ref: 369b9604610
Node: traceback --- 打印或检索堆栈回溯9605867
Ref: library/traceback doc9606044
Ref: 369c9606044
Ref: library/traceback module-traceback9606044
Ref: 1149606044
Ref: library/traceback traceback-print-or-retrieve-a-stack-traceback9606044
Ref: 369d9606044
Ref: library/traceback traceback print_tb9606767
Ref: 7829606767
Ref: library/traceback traceback print_exception9607404
Ref: 20bf9607404
Ref: library/traceback traceback print_exc9608549
Ref: 369e9608549
Ref: library/traceback traceback print_last9608713
Ref: 369f9608713
Ref: library/traceback traceback print_stack9609038
Ref: 7839609038
Ref: library/traceback traceback extract_tb9609584
Ref: 36a09609584
Ref: library/traceback traceback extract_stack9610315
Ref: 36a19610315
Ref: library/traceback traceback format_list9610616
Ref: 36a29610616
Ref: library/traceback traceback format_exception_only9611123
Ref: 32fb9611123
Ref: library/traceback traceback format_exception9611740
Ref: 36a39611740
Ref: library/traceback traceback format_exc9612342
Ref: 36a49612342
Ref: library/traceback traceback format_tb9612500
Ref: 35f59612500
Ref: library/traceback traceback format_stack9612614
Ref: 36a59612614
Ref: library/traceback traceback clear_frames9612737
Ref: 8f99612737
Ref: library/traceback traceback walk_stack9612942
Ref: 77d9612942
Ref: library/traceback traceback walk_tb9613248
Ref: 77e9613248
Ref: traceback --- 打印或检索堆栈回溯-Footnote-19613676
Node: TracebackException Objects9613744
Ref: library/traceback tracebackexception-objects9613877
Ref: 36a79613877
Ref: library/traceback traceback TracebackException9614115
Ref: 77f9614115
Ref: library/traceback traceback TracebackException __cause__9614498
Ref: 36a89614498
Ref: library/traceback traceback TracebackException __context__9614603
Ref: 36a99614603
Ref: library/traceback traceback TracebackException __suppress_context__9614722
Ref: 36aa9614722
Ref: library/traceback traceback TracebackException stack9614838
Ref: 36ab9614838
Ref: library/traceback traceback TracebackException exc_type9614928
Ref: 36ac9614928
Ref: library/traceback traceback TracebackException filename9615003
Ref: 36ad9615003
Ref: library/traceback traceback TracebackException lineno9615101
Ref: 36ae9615101
Ref: library/traceback traceback TracebackException text9615199
Ref: 36af9615199
Ref: library/traceback traceback TracebackException offset9615288
Ref: 36b09615288
Ref: library/traceback traceback TracebackException msg9615405
Ref: 36b19615405
Ref: library/traceback traceback TracebackException from_exception9615486
Ref: 36b29615486
Ref: library/traceback traceback TracebackException format9615869
Ref: 36b39615869
Ref: library/traceback traceback TracebackException format_exception_only9616417
Ref: 36b49616417
Node: StackSummary Objects9616964
Ref: library/traceback stacksummary-objects9617126
Ref: 36b59617126
Ref: library/traceback traceback StackSummary9617295
Ref: 7809617295
Ref: library/traceback traceback StackSummary extract9617328
Ref: 36a69617328
Ref: library/traceback traceback StackSummary from_list9618153
Ref: 36b69618153
Ref: library/traceback traceback StackSummary format9618456
Ref: 36b79618456
Node: FrameSummary Objects9619071
Ref: library/traceback framesummary-objects9619225
Ref: 36b89619225
Ref: library/traceback traceback FrameSummary9619390
Ref: 7819619390
Node: Traceback Examples9620133
Ref: library/traceback traceback-example9620258
Ref: 36b99620258
Ref: library/traceback traceback-examples9620258
Ref: 36ba9620258
Node: __future__ --- Future 语句定义9625654
Ref: library/__future__ doc9625833
Ref: 36bb9625833
Ref: library/__future__ future-future-statement-definitions9625833
Ref: 36bc9625833
Ref: library/__future__ module-__future__9625833
Ref: 09625833
Ref: __future__ --- Future 语句定义-Footnote-19630637
Ref: __future__ --- Future 语句定义-Footnote-29630706
Ref: __future__ --- Future 语句定义-Footnote-39630755
Ref: __future__ --- Future 语句定义-Footnote-49630804
Ref: __future__ --- Future 语句定义-Footnote-59630853
Ref: __future__ --- Future 语句定义-Footnote-69630902
Ref: __future__ --- Future 语句定义-Footnote-79630951
Ref: __future__ --- Future 语句定义-Footnote-89631000
Ref: __future__ --- Future 语句定义-Footnote-99631049
Ref: __future__ --- Future 语句定义-Footnote-109631098
Node: gc --- 垃圾回收器接口9631148
Ref: library/gc doc9631310
Ref: 36bd9631310
Ref: library/gc gc-garbage-collector-interface9631310
Ref: 36be9631310
Ref: library/gc module-gc9631310
Ref: 869631310
Ref: library/gc gc enable9632144
Ref: 36bf9632144
Ref: library/gc gc disable9632201
Ref: 36c09632201
Ref: library/gc gc isenabled9632259
Ref: 36c19632259
Ref: library/gc gc collect9632345
Ref: 22f9632345
Ref: library/gc gc set_debug9632950
Ref: 36c29632950
Ref: library/gc gc get_debug9633216
Ref: 36c39633216
Ref: library/gc gc get_objects9633282
Ref: 1ce9633282
Ref: library/gc gc get_stats9633679
Ref: 8579633679
Ref: library/gc gc set_threshold9634261
Ref: 36c49634261
Ref: library/gc gc get_count9635320
Ref: 36c59635320
Ref: library/gc gc get_threshold9635436
Ref: 36c69635436
Ref: library/gc gc get_referrers9635574
Ref: eb49635574
Ref: library/gc gc get_referents9636503
Ref: eb59636503
Ref: library/gc gc is_tracked9637236
Ref: cab9637236
Ref: library/gc gc freeze9637979
Ref: 3949637979
Ref: library/gc gc unfreeze9638474
Ref: 3959638474
Ref: library/gc gc get_freeze_count9638599
Ref: 3969638599
Ref: library/gc gc garbage9638791
Ref: b489638791
Ref: library/gc gc callbacks9639685
Ref: a129639685
Ref: library/gc gc DEBUG_STATS9640895
Ref: 36c99640895
Ref: library/gc gc DEBUG_COLLECTABLE9641038
Ref: 36ca9641038
Ref: library/gc gc DEBUG_UNCOLLECTABLE9641121
Ref: b499641121
Ref: library/gc gc DEBUG_SAVEALL9641503
Ref: 36c89641503
Ref: library/gc gc DEBUG_LEAK9641707
Ref: 36cb9641707
Ref: gc --- 垃圾回收器接口-Footnote-19641941
Ref: gc --- 垃圾回收器接口-Footnote-29642030
Node: inspect --- 检查对象9642079
Ref: library/inspect doc9642246
Ref: 36cc9642246
Ref: library/inspect inspect-inspect-live-objects9642246
Ref: 36cd9642246
Ref: library/inspect module-inspect9642246
Ref: a19642246
Ref: inspect --- 检查对象-Footnote-19643247
Node: 类型和成员9643313
Ref: library/inspect inspect-types9643420
Ref: 36ce9643420
Ref: library/inspect types-and-members9643420
Ref: 36cf9643420
Ref: library/inspect inspect getmembers9656077
Ref: 36d09656077
Ref: library/inspect inspect getmodulename9656689
Ref: 5fb9656689
Ref: library/inspect inspect ismodule9657359
Ref: 36d39657359
Ref: library/inspect inspect isclass9657449
Ref: 36d49657449
Ref: library/inspect inspect ismethod9657586
Ref: 36d59657586
Ref: library/inspect inspect isfunction9657700
Ref: 36d69657700
Ref: library/inspect inspect isgeneratorfunction9657876
Ref: 102e9657876
Ref: library/inspect inspect isgenerator9658162
Ref: 36d89658162
Ref: library/inspect inspect iscoroutinefunction9658258
Ref: 7019658258
Ref: library/inspect inspect iscoroutine9658640
Ref: 7009658640
Ref: library/inspect inspect isawaitable9658822
Ref: 7029658822
Ref: library/inspect inspect isasyncgenfunction9659268
Ref: 102f9659268
Ref: library/inspect inspect isasyncgen9659769
Ref: 36d99659769
Ref: library/inspect inspect istraceback9659993
Ref: 36da9659993
Ref: library/inspect inspect isframe9660089
Ref: 36db9660089
Ref: library/inspect inspect iscode9660177
Ref: 36dc9660177
Ref: library/inspect inspect isbuiltin9660263
Ref: 36dd9660263
Ref: library/inspect inspect isroutine9660397
Ref: 36de9660397
Ref: library/inspect inspect isabstract9660530
Ref: 36df9660530
Ref: library/inspect inspect ismethoddescriptor9660636
Ref: 36e09660636
Ref: library/inspect inspect isdatadescriptor9661517
Ref: 36e19661517
Ref: library/inspect inspect isgetsetdescriptor9662144
Ref: 36e29662144
Ref: library/inspect inspect ismemberdescriptor9662493
Ref: 36e39662493
Node: Retrieving source code9662853
Ref: library/inspect inspect-source9663018
Ref: 36e49663018
Ref: library/inspect retrieving-source-code9663018
Ref: 36e59663018
Ref: library/inspect inspect getdoc9663085
Ref: 1d79663085
Ref: library/inspect inspect getcomments9663511
Ref: 32b99663511
Ref: library/inspect inspect getfile9663933
Ref: 10b39663933
Ref: library/inspect inspect getmodule9664165
Ref: f359664165
Ref: library/inspect inspect getsourcefile9664263
Ref: 36e79664263
Ref: library/inspect inspect getsourcelines9664498
Ref: 36e89664498
Ref: library/inspect inspect getsource9665110
Ref: ee59665110
Ref: library/inspect inspect cleandoc9665553
Ref: 36e69665553
Node: Introspecting callables with the Signature object9665962
Ref: library/inspect inspect-signature-object9666127
Ref: 36e99666127
Ref: library/inspect introspecting-callables-with-the-signature-object9666127
Ref: 36ea9666127
Ref: library/inspect inspect signature9666442
Ref: 5649666442
Ref: library/inspect inspect Signature9667832
Ref: 6fc9667832
Ref: library/inspect inspect Signature empty9668847
Ref: 36ed9668847
Ref: library/inspect inspect Signature parameters9668964
Ref: 36eb9668964
Ref: library/inspect inspect Signature return_annotation9669451
Ref: 36ee9669451
Ref: library/inspect inspect Signature bind9669659
Ref: 36ef9669659
Ref: library/inspect inspect Signature bind_partial9669936
Ref: 36f09669936
Ref: library/inspect inspect Signature replace9670312
Ref: 36ec9670312
Ref: library/inspect inspect Signature from_callable9671015
Ref: 6ff9671015
Ref: library/inspect inspect Parameter9671595
Ref: 6fd9671595
Ref: library/inspect inspect Parameter empty9671938
Ref: 36f29671938
Ref: library/inspect inspect Parameter name9672066
Ref: 36f39672066
Ref: library/inspect inspect Parameter default9672522
Ref: 36f49672522
Ref: library/inspect inspect Parameter annotation9672710
Ref: 36f59672710
Ref: library/inspect inspect Parameter kind9672895
Ref: 36f69672895
Ref: library/inspect inspect Parameter kind description9675717
Ref: 36f79675717
Ref: library/inspect inspect Parameter replace9676247
Ref: 36f19676247
Ref: library/inspect inspect BoundArguments9677310
Ref: 9b09677310
Ref: library/inspect inspect BoundArguments arguments9677512
Ref: 36f89677512
Ref: library/inspect inspect BoundArguments args9678249
Ref: 36f99678249
Ref: library/inspect inspect BoundArguments kwargs9678398
Ref: 36fa9678398
Ref: library/inspect inspect BoundArguments signature9678545
Ref: 36fb9678545
Ref: library/inspect inspect BoundArguments apply_defaults9678640
Ref: 6fe9678640
Ref: Introspecting callables with the Signature object-Footnote-19679628
Node: 类与函数<2>9679677
Ref: library/inspect classes-and-functions9679841
Ref: 36fc9679841
Ref: library/inspect inspect-classes-functions9679841
Ref: 36fd9679841
Ref: library/inspect inspect getclasstree9679884
Ref: 36fe9679884
Ref: library/inspect inspect getargspec9680461
Ref: 5659680461
Ref: library/inspect inspect getfullargspec9681387
Ref: 5669681387
Ref: library/inspect inspect getargvalues9683744
Ref: 7c19683744
Ref: library/inspect inspect formatargspec9684249
Ref: 7c09684249
Ref: library/inspect inspect formatargvalues9685358
Ref: 7c29685358
Ref: library/inspect inspect getmro9685828
Ref: 36ff9685828
Ref: library/inspect inspect getcallargs9686190
Ref: 7bf9686190
Ref: library/inspect inspect getclosurevars9687526
Ref: a219687526
Ref: library/inspect inspect unwrap9688238
Ref: 8729688238
Node: The interpreter stack9688968
Ref: library/inspect inspect-stack9689113
Ref: 37009689113
Ref: library/inspect the-interpreter-stack9689113
Ref: 37019689113
Ref: library/inspect inspect getframeinfo9691106
Ref: 37029691106
Ref: library/inspect inspect getouterframes9691331
Ref: 7079691331
Ref: library/inspect inspect getinnerframes9691815
Ref: 7089691815
Ref: library/inspect inspect currentframe9692296
Ref: 37039692296
Ref: library/inspect inspect stack9692695
Ref: 7059692695
Ref: library/inspect inspect trace9693077
Ref: 7069693077
Node: Fetching attributes statically9693543
Ref: library/inspect fetching-attributes-statically9693715
Ref: 37049693715
Ref: library/inspect inspect getattr_static9694297
Ref: bd39694297
Node: Current State of Generators and Coroutines9696098
Ref: library/inspect current-state-of-generators-and-coroutines9696271
Ref: 37059696271
Ref: library/inspect inspect getgeneratorstate9696700
Ref: bd29696700
Ref: library/inspect inspect getcoroutinestate9697109
Ref: 7049697109
Ref: library/inspect inspect getgeneratorlocals9697940
Ref: a229697940
Ref: library/inspect inspect getcoroutinelocals9698810
Ref: 7039698810
Node: Code Objects Bit Flags9699041
Ref: library/inspect code-objects-bit-flags9699202
Ref: 37069699202
Ref: library/inspect inspect-module-co-flags9699202
Ref: 36d19699202
Ref: library/inspect inspect CO_OPTIMIZED9699365
Ref: 37079699365
Ref: library/inspect inspect CO_NEWLOCALS9699454
Ref: 37089699454
Ref: library/inspect inspect CO_VARARGS9699601
Ref: 37099699601
Ref: library/inspect inspect CO_VARKEYWORDS9699711
Ref: 370a9699711
Ref: library/inspect inspect CO_NESTED9699825
Ref: 370b9699825
Ref: library/inspect inspect CO_GENERATOR9699921
Ref: 370c9699921
Ref: library/inspect inspect CO_NOFREE9700098
Ref: 370d9700098
Ref: library/inspect inspect CO_COROUTINE9700191
Ref: 370e9700191
Ref: library/inspect inspect CO_ITERABLE_COROUTINE9700426
Ref: 370f9700426
Ref: library/inspect inspect CO_ASYNC_GENERATOR9700739
Ref: 37109700739
Ref: Code Objects Bit Flags-Footnote-19701386
Ref: Code Objects Bit Flags-Footnote-29701435
Ref: Code Objects Bit Flags-Footnote-39701484
Node: 命令行界面<8>9701533
Ref: library/inspect command-line-interface9701643
Ref: 37119701643
Ref: library/inspect inspect-module-cli9701643
Ref: 8719701643
Ref: library/inspect cmdoption-inspect-details9701999
Ref: 37129701999
Node: site —— 站点专属的配置钩子9702112
Ref: library/site doc9702242
Ref: 37139702242
Ref: library/site module-site9702242
Ref: ec9702242
Ref: library/site site-site-specific-configuration-hook9702242
Ref: 37149702242
Ref: site —— 站点专属的配置钩子-Footnote-19707652
Node: Readline（类库） 配置9707715
Ref: library/site readline-configuration9707842
Ref: 37169707842
Ref: library/site rlcompleter-config9707842
Ref: 8ee9707842
Node: 模块内容<7>9708474
Ref: library/site module-contents9708628
Ref: 37179708628
Ref: library/site site PREFIXES9708671
Ref: 37189708671
Ref: library/site site ENABLE_USER_SITE9708743
Ref: 37159708743
Ref: library/site site USER_SITE9709162
Ref: 13569709162
Ref: library/site site USER_BASE9709739
Ref: 13689709739
Ref: library/site site main9710311
Ref: 13579710311
Ref: library/site site addsitedir9710599
Ref: 37199710599
Ref: library/site site getsitepackages9710810
Ref: bdb9710810
Ref: library/site site getuserbase9710935
Ref: bdc9710935
Ref: library/site site getusersitepackages9711162
Ref: bdd9711162
Node: 命令行界面<9>9711540
Ref: library/site command-line-interface9711658
Ref: 371a9711658
Ref: library/site site-commandline9711658
Ref: 371b9711658
Ref: library/site cmdoption-site-user-base9712151
Ref: 371c9712151
Ref: library/site cmdoption-site-user-site9712219
Ref: 371d9712219
Ref: 命令行界面<9>-Footnote-19712853
Node: 自定义 Python 解释器9712902
Ref: library/custominterp doc9713032
Ref: 371e9713032
Ref: library/custominterp custom-python-interpreters9713032
Ref: 371f9713032
Ref: library/custominterp custominterp9713032
Ref: 37209713032
Node: code --- 解释器基类9713584
Ref: library/code doc9713709
Ref: 37219713709
Ref: library/code code-interpreter-base-classes9713709
Ref: 37229713709
Ref: library/code module-code9713709
Ref: 1b9713709
Ref: library/code code InteractiveInterpreter9714057
Ref: 37239714057
Ref: library/code code InteractiveConsole9714535
Ref: 18119714535
Ref: library/code code interact9714835
Ref: 37249714835
Ref: library/code code compile_command9715546
Ref: 37269715546
Ref: code --- 解释器基类-Footnote-19716669
Node: 交互解释器对象9716732
Ref: library/code interactive-interpreter-objects9716847
Ref: 37279716847
Ref: library/code interpreter-objects9716847
Ref: 37289716847
Ref: library/code code InteractiveInterpreter runsource9716903
Ref: 37299716903
Ref: library/code code InteractiveInterpreter runcode9718122
Ref: 372b9718122
Ref: library/code code InteractiveInterpreter showsyntaxerror9718557
Ref: 372a9718557
Ref: library/code code InteractiveInterpreter showtraceback9718983
Ref: 6b09718983
Ref: library/code code InteractiveInterpreter write9719294
Ref: 372c9719294
Node: 交互式控制台对象9719496
Ref: library/code console-objects9719611
Ref: 372d9719611
Ref: library/code interactive-console-objects9719611
Ref: 372e9719611
Ref: library/code code InteractiveConsole interact9719842
Ref: 372f9719842
Ref: library/code code InteractiveConsole push9720605
Ref: 37309720605
Ref: library/code code InteractiveConsole resetbuffer9721237
Ref: 37319721237
Ref: library/code code InteractiveConsole raw_input9721345
Ref: 37259721345
Node: codeop --- 编译Python代码9721645
Ref: library/codeop doc9721770
Ref: 37329721770
Ref: library/codeop codeop-compile-python-code9721770
Ref: 37339721770
Ref: library/codeop module-codeop9721770
Ref: 1d9721770
Ref: library/codeop codeop compile_command9722671
Ref: 37349722671
Ref: library/codeop codeop Compile9724059
Ref: 37359724059
Ref: library/codeop codeop CommandCompiler9724393
Ref: 37369724393
Ref: codeop --- 编译Python代码-Footnote-19724770
Node: 导入模块9724835
Ref: library/modules doc9724963
Ref: 37379724963
Ref: library/modules importing-modules9724963
Ref: 37389724963
Ref: library/modules modules9724963
Ref: 37399724963
Node: zipimport --- 从 Zip 存档中导入模块9725603
Ref: library/zipimport doc9725731
Ref: 373a9725731
Ref: library/zipimport module-zipimport9725731
Ref: 1449725731
Ref: library/zipimport zipimport-import-modules-from-zip-archives9725731
Ref: 373b9725731
Ref: library/zipimport zipimport ZipImportError9727602
Ref: 373c9727602
Ref: zipimport --- 从 Zip 存档中导入模块-Footnote-19727879
Ref: zipimport --- 从 Zip 存档中导入模块-Footnote-29727947
Ref: zipimport --- 从 Zip 存档中导入模块-Footnote-39728015
Ref: zipimport --- 从 Zip 存档中导入模块-Footnote-49728064
Ref: zipimport --- 从 Zip 存档中导入模块-Footnote-59728113
Ref: zipimport --- 从 Zip 存档中导入模块-Footnote-69728162
Node: zipimporter 对象9728211
Ref: library/zipimport id19728328
Ref: 373d9728328
Ref: library/zipimport zipimporter-objects9728328
Ref: 373e9728328
Ref: library/zipimport zipimport zipimporter9728445
Ref: 373f9728445
Ref: library/zipimport zipimport zipimporter find_module9728900
Ref: 37409728900
Ref: library/zipimport zipimport zipimporter get_code9729282
Ref: 37419729282
Ref: library/zipimport zipimport zipimporter get_data9729449
Ref: 10ca9729449
Ref: library/zipimport zipimport zipimporter get_filename9729727
Ref: 37429729727
Ref: library/zipimport zipimport zipimporter get_source9729974
Ref: 37439729974
Ref: library/zipimport zipimport zipimporter is_package9730219
Ref: 37449730219
Ref: library/zipimport zipimport zipimporter load_module9730425
Ref: 37459730425
Ref: library/zipimport zipimport zipimporter archive9730699
Ref: 37469730699
Ref: library/zipimport zipimport zipimporter prefix9730808
Ref: 37479730808
Node: 例子<28>9731160
Ref: library/zipimport examples9731277
Ref: 37489731277
Ref: library/zipimport zipimport-examples9731277
Ref: 37499731277
Node: pkgutil --- 包扩展工具9731942
Ref: library/pkgutil doc9732123
Ref: 374a9732123
Ref: library/pkgutil module-pkgutil9732123
Ref: ce9732123
Ref: library/pkgutil pkgutil-package-extension-utility9732123
Ref: 374b9732123
Ref: library/pkgutil pkgutil ModuleInfo9732369
Ref: 6169732369
Ref: library/pkgutil pkgutil extend_path9732515
Ref: 374c9732515
Ref: library/pkgutil pkgutil ImpImporter9734185
Ref: 374d9734185
Ref: library/pkgutil pkgutil ImpLoader9734869
Ref: 374e9734869
Ref: library/pkgutil pkgutil find_loader9735183
Ref: 374f9735183
Ref: library/pkgutil pkgutil get_importer9735748
Ref: 37509735748
Ref: library/pkgutil pkgutil get_loader9736256
Ref: 37519736256
Ref: library/pkgutil pkgutil iter_importers9736961
Ref: b1c9736961
Ref: library/pkgutil pkgutil iter_modules9737653
Ref: 6159737653
Ref: library/pkgutil pkgutil walk_packages9738494
Ref: 4939738494
Ref: library/pkgutil pkgutil get_data9740065
Ref: 37529740065
Ref: pkgutil --- 包扩展工具-Footnote-19741233
Ref: pkgutil --- 包扩展工具-Footnote-29741299
Ref: pkgutil --- 包扩展工具-Footnote-39741348
Ref: pkgutil --- 包扩展工具-Footnote-49741397
Ref: pkgutil --- 包扩展工具-Footnote-59741446
Ref: pkgutil --- 包扩展工具-Footnote-69741495
Ref: pkgutil --- 包扩展工具-Footnote-79741544
Ref: pkgutil --- 包扩展工具-Footnote-89741593
Ref: pkgutil --- 包扩展工具-Footnote-99741642
Ref: pkgutil --- 包扩展工具-Footnote-109741691
Ref: pkgutil --- 包扩展工具-Footnote-119741741
Ref: pkgutil --- 包扩展工具-Footnote-129741791
Ref: pkgutil --- 包扩展工具-Footnote-139741841
Ref: pkgutil --- 包扩展工具-Footnote-149741891
Node: modulefinder --- 查找脚本使用的模块9741941
Ref: library/modulefinder doc9742126
Ref: 37549742126
Ref: library/modulefinder module-modulefinder9742126
Ref: b59742126
Ref: library/modulefinder modulefinder-find-modules-used-by-a-script9742126
Ref: 37559742126
Ref: library/modulefinder modulefinder AddPackagePath9742573
Ref: 37569742573
Ref: library/modulefinder modulefinder ReplacePackage9742706
Ref: 37579742706
Ref: library/modulefinder modulefinder ModuleFinder9742849
Ref: ff09742849
Ref: library/modulefinder modulefinder ModuleFinder report9743442
Ref: 37599743442
Ref: library/modulefinder modulefinder ModuleFinder run_script9743607
Ref: 37589743607
Ref: library/modulefinder modulefinder ModuleFinder modules9743733
Ref: 375a9743733
Ref: modulefinder --- 查找脚本使用的模块-Footnote-19743963
Node: ModuleFinder 的示例用法9744034
Ref: library/modulefinder example-usage-of-modulefinder9744143
Ref: 375c9744143
Ref: library/modulefinder modulefinder-example9744143
Ref: 375b9744143
Node: runpy --- Locating and executing Python modules9745454
Ref: library/runpy doc9745642
Ref: 375d9745642
Ref: library/runpy module-runpy9745642
Ref: e39745642
Ref: library/runpy runpy-locating-and-executing-python-modules9745642
Ref: 375e9745642
Ref: library/runpy runpy run_module9746677
Ref: 134b9746677
Ref: library/runpy runpy run_path9749917
Ref: cb99749917
Ref: runpy --- Locating and executing Python modules-Footnote-19754147
Ref: runpy --- Locating and executing Python modules-Footnote-29754211
Ref: runpy --- Locating and executing Python modules-Footnote-39754260
Ref: runpy --- Locating and executing Python modules-Footnote-49754309
Ref: runpy --- Locating and executing Python modules-Footnote-59754358
Ref: runpy --- Locating and executing Python modules-Footnote-69754407
Ref: runpy --- Locating and executing Python modules-Footnote-79754456
Ref: runpy --- Locating and executing Python modules-Footnote-89754505
Node: importlib --- import 的实现9754554
Ref: library/importlib doc9754722
Ref: 375f9754722
Ref: library/importlib importlib-the-implementation-of-import9754722
Ref: 37609754722
Ref: library/importlib module-importlib9754722
Ref: 9b9754722
Ref: importlib --- import 的实现-Footnote-19755402
Node: 概述<13>9755480
Ref: library/importlib introduction9755576
Ref: 37619755576
Ref: 概述<13>-Footnote-19757152
Ref: 概述<13>-Footnote-29757204
Ref: 概述<13>-Footnote-39757253
Ref: 概述<13>-Footnote-49757302
Ref: 概述<13>-Footnote-59757351
Ref: 概述<13>-Footnote-69757400
Ref: 概述<13>-Footnote-79757449
Ref: 概述<13>-Footnote-89757498
Ref: 概述<13>-Footnote-99757547
Ref: 概述<13>-Footnote-109757596
Ref: 概述<13>-Footnote-119757646
Ref: 概述<13>-Footnote-129757696
Ref: 概述<13>-Footnote-139757746
Node: 函数<10>9757796
Ref: library/importlib functions9757949
Ref: 37629757949
Ref: library/importlib importlib __import__9757980
Ref: 9b69757980
Ref: library/importlib importlib import_module9758257
Ref: b1b9758257
Ref: library/importlib importlib find_loader9759486
Ref: 93f9759486
Ref: library/importlib importlib invalidate_caches9760523
Ref: 4a49760523
Ref: library/importlib importlib reload9760956
Ref: 3a19760956
Node: importlib abc —— 关于导入的抽象基类9764149
Ref: library/importlib importlib-abc-abstract-base-classes-related-to-import9764321
Ref: 37639764321
Ref: library/importlib module-importlib abc9764321
Ref: 9c9764321
Ref: library/importlib importlib abc Finder9765136
Ref: 9bd9765136
Ref: library/importlib importlib abc Finder find_module9765333
Ref: 37649765333
Ref: library/importlib importlib abc MetaPathFinder9765761
Ref: 9bb9765761
Ref: library/importlib importlib abc MetaPathFinder find_spec9765966
Ref: 46b9765966
Ref: library/importlib importlib abc MetaPathFinder find_module9766718
Ref: 46a9766718
Ref: library/importlib importlib abc MetaPathFinder invalidate_caches9767525
Ref: 37669767525
Ref: library/importlib importlib abc PathEntryFinder9768002
Ref: 9bc9768002
Ref: library/importlib importlib abc PathEntryFinder find_spec9768416
Ref: 46d9768416
Ref: library/importlib importlib abc PathEntryFinder find_loader9769052
Ref: 46c9769052
Ref: library/importlib importlib abc PathEntryFinder find_module9770190
Ref: 9439770190
Ref: library/importlib importlib abc PathEntryFinder invalidate_caches9770428
Ref: 37679770428
Ref: library/importlib importlib abc Loader9770727
Ref: 7cb9770727
Ref: library/importlib importlib abc Loader create_module9771124
Ref: 55d9771124
Ref: library/importlib importlib abc Loader exec_module9771551
Ref: 5ed9771551
Ref: library/importlib importlib abc Loader load_module9772013
Ref: 5ec9772013
Ref: library/importlib importlib abc Loader module_repr9775086
Ref: 9499775086
Ref: library/importlib importlib abc ResourceReader9775500
Ref: 34b9775500
Ref: library/importlib importlib abc ResourceReader open_resource9776895
Ref: 37689776895
Ref: library/importlib importlib abc ResourceReader resource_path9777151
Ref: 37699777151
Ref: library/importlib importlib abc ResourceReader is_resource9777381
Ref: 376a9777381
Ref: library/importlib importlib abc ResourceReader contents9777575
Ref: 104a9777575
Ref: library/importlib importlib abc ResourceLoader9778318
Ref: 46e9778318
Ref: library/importlib importlib abc ResourceLoader get_data9778645
Ref: 37539778645
Ref: library/importlib importlib abc InspectLoader9779266
Ref: 8699779266
Ref: library/importlib importlib abc InspectLoader get_code9779418
Ref: 86a9779418
Ref: library/importlib importlib abc InspectLoader get_source9779986
Ref: 86e9779986
Ref: library/importlib importlib abc InspectLoader is_package9780543
Ref: 376b9780543
Ref: library/importlib importlib abc InspectLoader source_to_code9780913
Ref: 6f89780913
Ref: library/importlib importlib abc InspectLoader exec_module9781549
Ref: 9479781549
Ref: library/importlib importlib abc InspectLoader load_module9781674
Ref: 9449781674
Ref: library/importlib importlib abc ExecutionLoader9781850
Ref: 376c9781850
Ref: library/importlib importlib abc ExecutionLoader get_filename9782078
Ref: 376d9782078
Ref: library/importlib importlib abc FileLoader9782553
Ref: 9bf9782553
Ref: library/importlib importlib abc FileLoader name9782973
Ref: 376e9782973
Ref: library/importlib importlib abc FileLoader path9783050
Ref: 376f9783050
Ref: library/importlib importlib abc FileLoader load_module9783106
Ref: 9459783106
Ref: library/importlib importlib abc FileLoader get_filename9783286
Ref: 37709783286
Ref: library/importlib importlib abc FileLoader get_data9783382
Ref: 37719783382
Ref: library/importlib importlib abc SourceLoader9783517
Ref: 37729783517
Ref: library/importlib importlib abc SourceLoader path_stats9784480
Ref: af49784480
Ref: library/importlib importlib abc SourceLoader path_mtime9785117
Ref: af39785117
Ref: library/importlib importlib abc SourceLoader set_data9785636
Ref: 37739785636
Ref: library/importlib importlib abc SourceLoader get_code9786100
Ref: 37749786100
Ref: library/importlib importlib abc SourceLoader exec_module9786205
Ref: 9489786205
Ref: library/importlib importlib abc SourceLoader load_module9786336
Ref: 9469786336
Ref: library/importlib importlib abc SourceLoader get_source9786526
Ref: 9619786526
Ref: library/importlib importlib abc SourceLoader is_package9786635
Ref: 37759786635
Ref: importlib abc —— 关于导入的抽象基类-Footnote-19787097
Ref: importlib abc —— 关于导入的抽象基类-Footnote-29787169
Ref: importlib abc —— 关于导入的抽象基类-Footnote-39787218
Ref: importlib abc —— 关于导入的抽象基类-Footnote-49787267
Ref: importlib abc —— 关于导入的抽象基类-Footnote-59787316
Ref: importlib abc —— 关于导入的抽象基类-Footnote-69787365
Node: importlib resources -- 资源9787414
Ref: library/importlib importlib-resources-resources9787623
Ref: 37769787623
Ref: library/importlib module-importlib resources9787623
Ref: 9f9787623
Ref: library/importlib importlib resources Package9788873
Ref: 37779788873
Ref: library/importlib importlib resources Resource9789230
Ref: 37789789230
Ref: library/importlib importlib resources open_binary9789469
Ref: 37799789469
Ref: library/importlib importlib resources open_text9789988
Ref: 377a9789988
Ref: library/importlib importlib resources read_binary9790699
Ref: 377b9790699
Ref: library/importlib importlib resources read_text9791219
Ref: 377c9791219
Ref: library/importlib importlib resources path9791920
Ref: ec59791920
Ref: library/importlib importlib resources is_resource9792635
Ref: 377d9792635
Ref: library/importlib importlib resources contents9792954
Ref: 10499792954
Ref: importlib resources -- 资源-Footnote-19793383
Ref: importlib resources -- 资源-Footnote-29793462
Ref: importlib resources -- 资源-Footnote-39793533
Ref: importlib resources -- 资源-Footnote-49793626
Ref: importlib resources -- 资源-Footnote-59793697
Node: importlib machinery -- Importers and path hooks9793773
Ref: library/importlib importlib-machinery-importers-and-path-hooks9793978
Ref: 377e9793978
Ref: library/importlib module-importlib machinery9793978
Ref: 9d9793978
Ref: library/importlib importlib machinery SOURCE_SUFFIXES9794309
Ref: 377f9794309
Ref: library/importlib importlib machinery DEBUG_BYTECODE_SUFFIXES9794473
Ref: 37809794473
Ref: library/importlib importlib machinery OPTIMIZED_BYTECODE_SUFFIXES9794721
Ref: 37829794721
Ref: library/importlib importlib machinery BYTECODE_SUFFIXES9794969
Ref: 37819794969
Ref: library/importlib importlib machinery EXTENSION_SUFFIXES9795243
Ref: 37839795243
Ref: library/importlib importlib machinery all_suffixes9795413
Ref: 36d29795413
Ref: library/importlib importlib machinery BuiltinImporter9795843
Ref: 55e9795843
Ref: library/importlib importlib machinery FrozenImporter9796401
Ref: 95f9796401
Ref: library/importlib importlib machinery WindowsRegistryFinder9796814
Ref: 5ee9796814
Ref: library/importlib importlib machinery PathFinder9797282
Ref: 9639797282
Ref: library/importlib importlib machinery PathFinder find_spec9797595
Ref: 9429797595
Ref: library/importlib importlib machinery PathFinder find_module9798750
Ref: 9419798750
Ref: library/importlib importlib machinery PathFinder invalidate_caches9798949
Ref: 4a39798949
Ref: library/importlib importlib machinery FileFinder9799546
Ref: 9be9799546
Ref: library/importlib importlib machinery FileFinder path9800847
Ref: 37849800847
Ref: library/importlib importlib machinery FileFinder find_spec9800917
Ref: 7ca9800917
Ref: library/importlib importlib machinery FileFinder find_loader9801090
Ref: 37859801090
Ref: library/importlib importlib machinery FileFinder invalidate_caches9801225
Ref: 37869801225
Ref: library/importlib importlib machinery FileFinder path_hook9801305
Ref: 37879801305
Ref: library/importlib importlib machinery SourceFileLoader9801751
Ref: 9c09801751
Ref: library/importlib importlib machinery SourceFileLoader name9802038
Ref: 37889802038
Ref: library/importlib importlib machinery SourceFileLoader path9802125
Ref: 37899802125
Ref: library/importlib importlib machinery SourceFileLoader is_package9802188
Ref: 378a9802188
Ref: library/importlib importlib machinery SourceFileLoader path_stats9802317
Ref: 378b9802317
Ref: library/importlib importlib machinery SourceFileLoader set_data9802453
Ref: 378c9802453
Ref: library/importlib importlib machinery SourceFileLoader load_module9802592
Ref: 5ea9802592
Ref: library/importlib importlib machinery SourcelessFileLoader9802902
Ref: 9c19802902
Ref: library/importlib importlib machinery SourcelessFileLoader name9803369
Ref: 378d9803369
Ref: library/importlib importlib machinery SourcelessFileLoader path9803450
Ref: 378e9803450
Ref: library/importlib importlib machinery SourcelessFileLoader is_package9803515
Ref: 378f9803515
Ref: library/importlib importlib machinery SourcelessFileLoader get_code9803641
Ref: 37909803641
Ref: library/importlib importlib machinery SourcelessFileLoader get_source9803777
Ref: 37919803777
Ref: library/importlib importlib machinery SourcelessFileLoader load_module9803916
Ref: 5eb9803916
Ref: library/importlib importlib machinery ExtensionFileLoader9804201
Ref: 55f9804201
Ref: library/importlib importlib machinery ExtensionFileLoader name9804564
Ref: 37929804564
Ref: library/importlib importlib machinery ExtensionFileLoader path9804638
Ref: 37939804638
Ref: library/importlib importlib machinery ExtensionFileLoader create_module9804702
Ref: 37949804702
Ref: library/importlib importlib machinery ExtensionFileLoader exec_module9804877
Ref: 37959804877
Ref: library/importlib importlib machinery ExtensionFileLoader is_package9805033
Ref: 37969805033
Ref: library/importlib importlib machinery ExtensionFileLoader get_code9805217
Ref: 37979805217
Ref: library/importlib importlib machinery ExtensionFileLoader get_source9805326
Ref: 37989805326
Ref: library/importlib importlib machinery ExtensionFileLoader get_filename9805442
Ref: 86f9805442
Ref: library/importlib importlib machinery ModuleSpec9805552
Ref: 14d69805552
Ref: library/importlib importlib machinery ModuleSpec name9806361
Ref: 19c49806361
Ref: library/importlib importlib machinery ModuleSpec loader9806466
Ref: 19c29806466
Ref: library/importlib importlib machinery ModuleSpec origin9806642
Ref: ec99806642
Ref: library/importlib importlib machinery ModuleSpec submodule_search_locations9806992
Ref: 37999806992
Ref: library/importlib importlib machinery ModuleSpec loader_state9807154
Ref: 379a9807154
Ref: library/importlib importlib machinery ModuleSpec cached9807276
Ref: 379b9807276
Ref: library/importlib importlib machinery ModuleSpec parent9807403
Ref: 19c69807403
Ref: library/importlib importlib machinery ModuleSpec has_location9807681
Ref: 379c9807681
Ref: importlib machinery -- Importers and path hooks-Footnote-19807858
Ref: importlib machinery -- Importers and path hooks-Footnote-29807937
Ref: importlib machinery -- Importers and path hooks-Footnote-39807986
Ref: importlib machinery -- Importers and path hooks-Footnote-49808035
Node: importlib util -- Utility code for importers9808084
Ref: library/importlib importlib-util-utility-code-for-importers9808270
Ref: 379d9808270
Ref: library/importlib module-importlib util9808270
Ref: a09808270
Ref: library/importlib importlib util MAGIC_NUMBER9808596
Ref: 86b9808596
Ref: library/importlib importlib util cache_from_source9808834
Ref: 5609808834
Ref: library/importlib importlib util source_from_cache9810735
Ref: 5619810735
Ref: library/importlib importlib util decode_source9811357
Ref: 86d9811357
Ref: library/importlib importlib util resolve_name9811623
Ref: 379e9811623
Ref: library/importlib importlib util find_spec9812323
Ref: 9409812323
Ref: library/importlib importlib util module_from_spec9813206
Ref: 6f99813206
Ref: library/importlib importlib util module_for_loader9813835
Ref: 94a9813835
Ref: library/importlib importlib util set_loader9815587
Ref: 94b9815587
Ref: library/importlib importlib util set_package9816197
Ref: 94c9816197
Ref: library/importlib importlib util spec_from_loader9816592
Ref: 37659816592
Ref: library/importlib importlib util spec_from_file_location9817034
Ref: 5629817034
Ref: library/importlib importlib util source_hash9817505
Ref: 379f9817505
Ref: library/importlib importlib util LazyLoader9817773
Ref: 55c9817773
Ref: library/importlib importlib util LazyLoader factory9819248
Ref: 37a19819248
Ref: importlib util -- Utility code for importers-Footnote-19819812
Ref: importlib util -- Utility code for importers-Footnote-29819885
Ref: importlib util -- Utility code for importers-Footnote-39819934
Ref: importlib util -- Utility code for importers-Footnote-49819983
Ref: importlib util -- Utility code for importers-Footnote-59820032
Ref: importlib util -- Utility code for importers-Footnote-69820081
Node: 例子<29>9820130
Ref: library/importlib examples9820260
Ref: 37a29820260
Ref: library/importlib importlib-examples9820260
Ref: 37a39820260
Node: Importing programmatically9820519
Ref: library/importlib importing-programmatically9820637
Ref: 37a49820637
Node: Checking if a module can be imported9820868
Ref: library/importlib checking-if-a-module-can-be-imported9821027
Ref: 37a59821027
Node: Importing a source file directly9821812
Ref: library/importlib importing-a-source-file-directly9821967
Ref: 37a69821967
Node: Setting up an importer9822526
Ref: library/importlib setting-up-an-importer9822682
Ref: 37a79822682
Node: Approximating importlib import_module9824256
Ref: library/importlib approximating-importlib-import-module9824371
Ref: 37a89824371
Node: Using importlib metadata9825968
Ref: library/importlib metadata doc9826080
Ref: 37a99826080
Ref: library/importlib metadata module-importlib metadata9826080
Ref: 9e9826080
Ref: library/importlib metadata using9826080
Ref: 37aa9826080
Ref: library/importlib metadata using-importlib-metadata9826080
Ref: 37ab9826080
Ref: Using importlib metadata-Footnote-19827480
Ref: Using importlib metadata-Footnote-29827558
Ref: Using importlib metadata-Footnote-39827643
Ref: Using importlib metadata-Footnote-49827728
Ref: Using importlib metadata-Footnote-59827800
Ref: Using importlib metadata-Footnote-69827838
Node: 概述<14>9827887
Ref: library/importlib metadata overview9827983
Ref: 37ac9827983
Node: 功能性 API<2>9829399
Ref: library/importlib metadata functional-api9829517
Ref: 37b29829517
Node: Entry points9829764
Ref: library/importlib metadata entry-points9829859
Ref: 37ad9829859
Ref: library/importlib metadata id19829859
Ref: 37b39829859
Ref: Entry points-Footnote-19830939
Node: Distribution metadata9831050
Ref: library/importlib metadata distribution-metadata9831175
Ref: 37b49831175
Ref: library/importlib metadata metadata9831175
Ref: 37ae9831175
Ref: Distribution metadata-Footnote-19831659
Node: Distribution versions9831939
Ref: library/importlib metadata distribution-versions9832070
Ref: 37b59832070
Ref: library/importlib metadata version9832070
Ref: 37af9832070
Node: Distribution files9832279
Ref: library/importlib metadata distribution-files9832414
Ref: 37b69832414
Ref: library/importlib metadata files9832414
Ref: 37b09832414
Ref: Distribution files-Footnote-19833804
Node: Distribution requirements9833901
Ref: library/importlib metadata distribution-requirements9834006
Ref: 37b79834006
Ref: library/importlib metadata requirements9834006
Ref: 37b19834006
Node: Distributions9834273
Ref: library/importlib metadata distributions9834411
Ref: 37b89834411
Ref: Distributions-Footnote-19835318
Node: Extending the search algorithm9835367
Ref: library/importlib metadata extending-the-search-algorithm9835480
Ref: 37b99835480
Node: Python 语言服务9837260
Ref: library/language doc9837374
Ref: 37ba9837374
Ref: library/language language9837374
Ref: 37bb9837374
Ref: library/language python-language-services9837374
Ref: 37bc9837374
Node: parser --- 访问 Python 解析树9838695
Ref: library/parser doc9838817
Ref: 37bd9838817
Ref: library/parser module-parser9838817
Ref: c89838817
Ref: library/parser parser-access-python-parse-trees9838817
Ref: 37be9838817
Node: 创建 ST 对象9843923
Ref: library/parser creating-st-objects9844035
Ref: 37c49844035
Ref: library/parser creating-sts9844035
Ref: 37c59844035
Ref: library/parser parser expr9844271
Ref: 37bf9844271
Ref: library/parser parser suite9844604
Ref: 37c09844604
Ref: library/parser parser sequence2st9844939
Ref: 37c19844939
Ref: library/parser parser tuple2st9846351
Ref: 37c89846351
Node: 转换 ST 对象9846518
Ref: library/parser converting-st-objects9846660
Ref: 37c99846660
Ref: library/parser converting-sts9846660
Ref: 37ca9846660
Ref: library/parser parser st2list9846960
Ref: 37c29846960
Ref: library/parser parser st2tuple9848032
Ref: 37c39848032
Ref: library/parser parser compilest9848574
Ref: 37c79848574
Node: Queries on ST Objects9849735
Ref: library/parser queries-on-st-objects9849882
Ref: 37cb9849882
Ref: library/parser querying-sts9849882
Ref: 37cc9849882
Ref: library/parser parser isexpr9850254
Ref: 37cd9850254
Ref: library/parser parser issuite9850735
Ref: 37ce9850735
Node: 异常和错误处理9851090
Ref: library/parser exceptions-and-error-handling9851230
Ref: 37cf9851230
Ref: library/parser st-errors9851230
Ref: 37d09851230
Ref: library/parser parser ParserError9851502
Ref: 37c69851502
Node: ST 对象9852660
Ref: library/parser id19852803
Ref: 37d19852803
Ref: library/parser st-objects9852803
Ref: 37d29852803
Ref: library/parser parser STType9852987
Ref: 37d39852987
Ref: library/parser parser ST compile9853163
Ref: 37d49853163
Ref: library/parser parser ST isexpr9853262
Ref: 37d59853262
Ref: library/parser parser ST issuite9853325
Ref: 37d69853325
Ref: library/parser parser ST tolist9853390
Ref: 37d79853390
Ref: library/parser parser ST totuple9853506
Ref: 37d89853506
Node: 示例 compile 的模拟9853624
Ref: library/parser example-emulation-of-compile9853737
Ref: 37d99853737
Node: ast --- 抽象语法树9854818
Ref: library/ast doc9855000
Ref: 37da9855000
Ref: library/ast ast-abstract-syntax-trees9855000
Ref: 37db9855000
Ref: library/ast module-ast9855000
Ref: 89855000
Ref: ast --- 抽象语法树-Footnote-19855856
Node: 节点类9855918
Ref: library/ast node-classes9856008
Ref: 37dd9856008
Ref: library/ast ast AST9856044
Ref: 37dc9856044
Ref: library/ast ast AST _fields9856776
Ref: 37df9856776
Ref: library/ast ast AST lineno9857483
Ref: 37e09857483
Ref: library/ast ast AST col_offset9857507
Ref: 37e19857507
Ref: library/ast ast AST end_lineno9857535
Ref: 37e29857535
Ref: library/ast ast AST end_col_offset9857563
Ref: 37e39857563
Node: 抽象文法9859743
Ref: library/ast abstract-grammar9859864
Ref: 37de9859864
Ref: library/ast id19859864
Ref: 37e49859864
Node: ast 中的辅助函数9865884
Ref: library/ast ast-helpers9865987
Ref: 37e59865987
Ref: library/ast ast parse9866156
Ref: 1a29866156
Ref: library/ast ast literal_eval9867908
Ref: 4ad9867908
Ref: library/ast ast get_docstring9868735
Ref: 10659868735
Ref: library/ast ast get_source_segment9869142
Ref: 1a19869142
Ref: library/ast ast fix_missing_locations9869588
Ref: 37e69869588
Ref: library/ast ast increment_lineno9870042
Ref: efe9870042
Ref: library/ast ast copy_location9870268
Ref: 37e79870268
Ref: library/ast ast iter_fields9870500
Ref: 37e89870500
Ref: library/ast ast iter_child_nodes9870653
Ref: 37e99870653
Ref: library/ast ast walk9870829
Ref: 37ea9870829
Ref: library/ast ast NodeVisitor9871093
Ref: 2829871093
Ref: library/ast ast NodeVisitor visit9871433
Ref: 37eb9871433
Ref: library/ast ast NodeVisitor generic_visit9871713
Ref: 37ec9871713
Ref: library/ast ast NodeTransformer9872539
Ref: 37ed9872539
Ref: library/ast ast dump9874199
Ref: f9f9874199
Ref: ast 中的辅助函数-Footnote-19875659
Ref: ast 中的辅助函数-Footnote-29875708
Ref: ast 中的辅助函数-Footnote-39875757
Ref: ast 中的辅助函数-Footnote-49875806
Ref: ast 中的辅助函数-Footnote-59875854
Ref: ast 中的辅助函数-Footnote-69875921
Ref: ast 中的辅助函数-Footnote-79875976
Ref: ast 中的辅助函数-Footnote-89876015
Node: symtable --- Access to the compiler's symbol tables9876052
Ref: library/symtable doc9876252
Ref: 37ee9876252
Ref: library/symtable module-symtable9876252
Ref: fd9876252
Ref: library/symtable symtable-access-to-the-compiler-s-symbol-tables9876252
Ref: 37ef9876252
Ref: symtable --- Access to the compiler's symbol tables-Footnote-19876834
Node: Generating Symbol Tables9876901
Ref: library/symtable generating-symbol-tables9877045
Ref: 37f09877045
Ref: library/symtable symtable symtable9877114
Ref: fd69877114
Node: Examining Symbol Tables9877392
Ref: library/symtable examining-symbol-tables9877536
Ref: 37f29877536
Ref: library/symtable symtable SymbolTable9877603
Ref: 37f19877603
Ref: library/symtable symtable SymbolTable get_type9877703
Ref: 37f39877703
Ref: library/symtable symtable SymbolTable get_id9877865
Ref: 37f49877865
Ref: library/symtable symtable SymbolTable get_name9877937
Ref: 37f59877937
Ref: library/symtable symtable SymbolTable get_lineno9878240
Ref: 37f69878240
Ref: library/symtable symtable SymbolTable is_optimized9878365
Ref: 37f79878365
Ref: library/symtable symtable SymbolTable is_nested9878474
Ref: 37f89878474
Ref: library/symtable symtable SymbolTable has_children9878578
Ref: 37f99878578
Ref: library/symtable symtable SymbolTable has_exec9878752
Ref: 37fb9878752
Ref: library/symtable symtable SymbolTable get_identifiers9878841
Ref: 37fc9878841
Ref: library/symtable symtable SymbolTable lookup9878938
Ref: 37fd9878938
Ref: library/symtable symtable SymbolTable get_symbols9879061
Ref: 37ff9879061
Ref: library/symtable symtable SymbolTable get_children9879186
Ref: 37fa9879186
Ref: library/symtable symtable Function9879274
Ref: 38009879274
Ref: library/symtable symtable Function get_parameters9879397
Ref: 38019879397
Ref: library/symtable symtable Function get_locals9879518
Ref: 38029879518
Ref: library/symtable symtable Function get_globals9879621
Ref: 38039879621
Ref: library/symtable symtable Function get_nonlocals9879726
Ref: 38049879726
Ref: library/symtable symtable Function get_frees9879835
Ref: 38059879835
Ref: library/symtable symtable Class9879955
Ref: 38069879955
Ref: library/symtable symtable Class get_methods9880061
Ref: 38079880061
Ref: library/symtable symtable Symbol9880185
Ref: 37fe9880185
Ref: library/symtable symtable Symbol get_name9880339
Ref: 38089880339
Ref: library/symtable symtable Symbol is_referenced9880408
Ref: 38099880408
Ref: library/symtable symtable Symbol is_imported9880508
Ref: 380a9880508
Ref: library/symtable symtable Symbol is_parameter9880631
Ref: 380b9880631
Ref: library/symtable symtable Symbol is_global9880724
Ref: 380c9880724
Ref: library/symtable symtable Symbol is_nonlocal9880809
Ref: 101d9880809
Ref: library/symtable symtable Symbol is_declared_global9880898
Ref: cbe9880898
Ref: library/symtable symtable Symbol is_local9881035
Ref: 380d9881035
Ref: library/symtable symtable Symbol is_annotated9881131
Ref: 380e9881131
Ref: library/symtable symtable Symbol is_free9881251
Ref: 380f9881251
Ref: library/symtable symtable Symbol is_assigned9881382
Ref: 38109881382
Ref: library/symtable symtable Symbol is_namespace9881487
Ref: 38119881487
Ref: library/symtable symtable Symbol get_namespaces9882123
Ref: 38129882123
Ref: library/symtable symtable Symbol get_namespace9882218
Ref: 38139882218
Node: symbol --- 与 Python 解析树一起使用的常量9882387
Ref: library/symbol doc9882613
Ref: 38149882613
Ref: library/symbol module-symbol9882613
Ref: fc9882613
Ref: library/symbol symbol-constants-used-with-python-parse-trees9882613
Ref: 38159882613
Ref: library/symbol symbol sym_name9883225
Ref: 38169883225
Ref: symbol --- 与 Python 解析树一起使用的常量-Footnote-19883429
Node: token --- 与Python解析树一起使用的常量9883494
Ref: library/token doc9883702
Ref: 38179883702
Ref: library/token module-token9883702
Ref: 1119883702
Ref: library/token token-constants-used-with-python-parse-trees9883702
Ref: 38189883702
Ref: library/token token tok_name9884310
Ref: 38199884310
Ref: library/token token ISTERMINAL9884477
Ref: 381a9884477
Ref: library/token token ISNONTERMINAL9884556
Ref: 381b9884556
Ref: library/token token ISEOF9884641
Ref: 381c9884641
Ref: library/token token ENDMARKER9884761
Ref: 381d9884761
Ref: library/token token NAME9884790
Ref: 381e9884790
Ref: library/token token NUMBER9884814
Ref: 381f9884814
Ref: library/token token STRING9884840
Ref: 38209884840
Ref: library/token token NEWLINE9884866
Ref: 38219884866
Ref: library/token token INDENT9884893
Ref: 38229884893
Ref: library/token token DEDENT9884919
Ref: 38239884919
Ref: library/token token LPAR9884945
Ref: 38249884945
Ref: library/token token RPAR9885001
Ref: 38259885001
Ref: library/token token LSQB9885057
Ref: 38269885057
Ref: library/token token RSQB9885113
Ref: 38279885113
Ref: library/token token COLON9885169
Ref: 38289885169
Ref: library/token token COMMA9885226
Ref: 38299885226
Ref: library/token token SEMI9885283
Ref: 382a9885283
Ref: library/token token PLUS9885339
Ref: 382b9885339
Ref: library/token token MINUS9885395
Ref: 382c9885395
Ref: library/token token STAR9885452
Ref: 382d9885452
Ref: library/token token SLASH9885508
Ref: 382e9885508
Ref: library/token token VBAR9885565
Ref: 382f9885565
Ref: library/token token AMPER9885621
Ref: 38309885621
Ref: library/token token LESS9885678
Ref: 38319885678
Ref: library/token token GREATER9885734
Ref: 38329885734
Ref: library/token token EQUAL9885793
Ref: 38339885793
Ref: library/token token DOT9885851
Ref: 38349885851
Ref: library/token token PERCENT9885907
Ref: 38359885907
Ref: library/token token LBRACE9885967
Ref: 38369885967
Ref: library/token token RBRACE9886026
Ref: 38379886026
Ref: library/token token EQEQUAL9886085
Ref: 38389886085
Ref: library/token token NOTEQUAL9886146
Ref: 38399886146
Ref: library/token token LESSEQUAL9886208
Ref: 383a9886208
Ref: library/token token GREATEREQUAL9886271
Ref: 383b9886271
Ref: library/token token TILDE9886337
Ref: 383c9886337
Ref: library/token token CIRCUMFLEX9886395
Ref: 383d9886395
Ref: library/token token LEFTSHIFT9886458
Ref: 383e9886458
Ref: library/token token RIGHTSHIFT9886521
Ref: 383f9886521
Ref: library/token token DOUBLESTAR9886585
Ref: 38409886585
Ref: library/token token PLUSEQUAL9886649
Ref: 38419886649
Ref: library/token token MINEQUAL9886712
Ref: 38429886712
Ref: library/token token STAREQUAL9886774
Ref: 38439886774
Ref: library/token token SLASHEQUAL9886837
Ref: 38449886837
Ref: library/token token PERCENTEQUAL9886901
Ref: 38459886901
Ref: library/token token AMPEREQUAL9886967
Ref: 38469886967
Ref: library/token token VBAREQUAL9887031
Ref: 38479887031
Ref: library/token token CIRCUMFLEXEQUAL9887094
Ref: 38489887094
Ref: library/token token LEFTSHIFTEQUAL9887163
Ref: 38499887163
Ref: library/token token RIGHTSHIFTEQUAL9887232
Ref: 384a9887232
Ref: library/token token DOUBLESTAREQUAL9887302
Ref: 384b9887302
Ref: library/token token DOUBLESLASH9887372
Ref: 384c9887372
Ref: library/token token DOUBLESLASHEQUAL9887437
Ref: 384d9887437
Ref: library/token token AT9887508
Ref: 384e9887508
Ref: library/token token ATEQUAL9887563
Ref: 384f9887563
Ref: library/token token RARROW9887624
Ref: 38509887624
Ref: library/token token ELLIPSIS9887684
Ref: 38519887684
Ref: library/token token COLONEQUAL9887747
Ref: 38529887747
Ref: library/token token OP9887811
Ref: 38539887811
Ref: library/token token AWAIT9887833
Ref: 38549887833
Ref: library/token token ASYNC9887858
Ref: 38559887858
Ref: library/token token TYPE_IGNORE9887883
Ref: 38569887883
Ref: library/token token TYPE_COMMENT9887914
Ref: 38579887914
Ref: library/token token ERRORTOKEN9887946
Ref: 38589887946
Ref: library/token token N_TOKENS9887976
Ref: 38599887976
Ref: library/token token NT_OFFSET9888004
Ref: 385a9888004
Ref: library/token token COMMENT9888147
Ref: 385b9888147
Ref: library/token token NL9888211
Ref: 385c9888211
Ref: library/token token ENCODING9888450
Ref: 385d9888450
Ref: token --- 与Python解析树一起使用的常量-Footnote-19889529
Node: keyword --- 检验Python关键字9889593
Ref: library/keyword doc9889803
Ref: 385e9889803
Ref: library/keyword keyword-testing-for-python-keywords9889803
Ref: 385f9889803
Ref: library/keyword module-keyword9889803
Ref: a79889803
Ref: library/keyword keyword iskeyword9890073
Ref: 165c9890073
Ref: library/keyword keyword kwlist9890189
Ref: 38609890189
Ref: keyword --- 检验Python关键字-Footnote-19890463
Node: tokenize --- 对 Python 代码使用的标记解析器9890529
Ref: library/tokenize doc9890721
Ref: 38619890721
Ref: library/tokenize module-tokenize9890721
Ref: 1129890721
Ref: library/tokenize tokenize-tokenizer-for-python-source9890721
Ref: 38629890721
Ref: tokenize --- 对 Python 代码使用的标记解析器-Footnote-19891683
Node: 对输入进行解析标记9891750
Ref: library/tokenize tokenizing-input9891898
Ref: 38639891898
Ref: library/tokenize tokenize tokenize9892013
Ref: c639892013
Ref: library/tokenize tokenize generate_tokens9893434
Ref: 10459893434
Ref: library/tokenize tokenize untokenize9894199
Ref: 38649894199
Ref: library/tokenize tokenize detect_encoding9895141
Ref: 1c909895141
Ref: library/tokenize tokenize open9896135
Ref: 1c8f9896135
Ref: library/tokenize tokenize TokenError9896300
Ref: 38659896300
Ref: 对输入进行解析标记-Footnote-19896792
Ref: 对输入进行解析标记-Footnote-29896841
Node: Command-Line Usage<2>9896890
Ref: library/tokenize command-line-usage9897057
Ref: 38669897057
Ref: library/tokenize tokenize-cli9897057
Ref: 38679897057
Ref: library/tokenize cmdoption-tokenize-h9897319
Ref: 38689897319
Ref: library/tokenize cmdoption-tokenize-e9897387
Ref: 38699897387
Node: 例子<30>9897585
Ref: library/tokenize examples9897716
Ref: 386a9897716
Node: tabnanny --- 模糊缩进检测9902211
Ref: library/tabnanny doc9902409
Ref: 386b9902409
Ref: library/tabnanny module-tabnanny9902409
Ref: 1019902409
Ref: library/tabnanny tabnanny-detection-of-ambiguous-indentation9902409
Ref: 386c9902409
Ref: library/tabnanny tabnanny check9902835
Ref: 386d9902835
Ref: library/tabnanny tabnanny verbose9903218
Ref: 386e9903218
Ref: library/tabnanny tabnanny filename_only9903368
Ref: 386f9903368
Ref: library/tabnanny tabnanny NannyNag9903563
Ref: 38709903563
Ref: library/tabnanny tabnanny process_tokens9903726
Ref: 38719903726
Ref: tabnanny --- 模糊缩进检测-Footnote-19904013
Node: pyclbr --- Python 模块浏览器支持9904080
Ref: library/pyclbr doc9904262
Ref: 38729904262
Ref: library/pyclbr module-pyclbr9904262
Ref: d99904262
Ref: library/pyclbr pyclbr-python-module-browser-support9904262
Ref: 38739904262
Ref: library/pyclbr pyclbr readmodule9904880
Ref: 11799904880
Ref: library/pyclbr pyclbr readmodule_ex9905414
Ref: 117a9905414
Ref: pyclbr --- Python 模块浏览器支持-Footnote-19906388
Node: 函数对象9906453
Ref: library/pyclbr function-objects9906562
Ref: 38749906562
Ref: library/pyclbr pyclbr-function-objects9906562
Ref: 38759906562
Ref: library/pyclbr pyclbr Function file9906702
Ref: 38769906702
Ref: library/pyclbr pyclbr Function module9906769
Ref: 38779906769
Ref: library/pyclbr pyclbr Function name9906844
Ref: 38789906844
Ref: library/pyclbr pyclbr Function lineno9906893
Ref: 38799906893
Ref: library/pyclbr pyclbr Function parent9906971
Ref: 387a9906971
Ref: library/pyclbr pyclbr Function children9907106
Ref: 387b9907106
Node: 类对象<2>9907225
Ref: library/pyclbr class-objects9907334
Ref: 387c9907334
Ref: library/pyclbr pyclbr-class-objects9907334
Ref: 387d9907334
Ref: library/pyclbr pyclbr Class file9907514
Ref: 387e9907514
Ref: library/pyclbr pyclbr Class module9907578
Ref: 387f9907578
Ref: library/pyclbr pyclbr Class name9907650
Ref: 38809907650
Ref: library/pyclbr pyclbr Class lineno9907693
Ref: 38819907693
Ref: library/pyclbr pyclbr Class parent9907768
Ref: 38829907768
Ref: library/pyclbr pyclbr Class children9907891
Ref: 38839907891
Ref: library/pyclbr pyclbr Class super9908007
Ref: 38849908007
Ref: library/pyclbr pyclbr Class methods9908264
Ref: 38859908264
Node: py_compile --- 编译 Python 源文件9908425
Ref: library/py_compile doc9908620
Ref: 38869908620
Ref: library/py_compile module-py_compile9908620
Ref: d89908620
Ref: library/py_compile py-compile-compile-python-source-files9908620
Ref: 38879908620
Ref: library/py_compile py_compile PyCompileError9909159
Ref: 38889909159
Ref: library/py_compile py_compile compile9909265
Ref: 2169909265
Ref: library/py_compile py_compile PycInvalidationMode9912721
Ref: 38899912721
Ref: library/py_compile py_compile PycInvalidationMode TIMESTAMP9913124
Ref: 388b9913124
Ref: library/py_compile py_compile PycInvalidationMode CHECKED_HASH9913349
Ref: 388a9913349
Ref: library/py_compile py_compile PycInvalidationMode UNCHECKED_HASH9913568
Ref: 388c9913568
Ref: library/py_compile py_compile main9913982
Ref: 388d9913982
Ref: py_compile --- 编译 Python 源文件-Footnote-19914788
Ref: py_compile --- 编译 Python 源文件-Footnote-29914857
Ref: py_compile --- 编译 Python 源文件-Footnote-39914906
Ref: py_compile --- 编译 Python 源文件-Footnote-49914955
Ref: py_compile --- 编译 Python 源文件-Footnote-59915004
Node: compileall --- Byte-compile Python libraries9915053
Ref: library/compileall doc9915245
Ref: 388e9915245
Ref: library/compileall compileall-byte-compile-python-libraries9915245
Ref: 388f9915245
Ref: library/compileall module-compileall9915245
Ref: 219915245
Ref: compileall --- Byte-compile Python libraries-Footnote-19915905
Node: Command-line use9915974
Ref: library/compileall command-line-use9916096
Ref: 38909916096
Ref: library/compileall cmdoption-compileall-arg-directory9916247
Ref: 38919916247
Ref: library/compileall cmdoption-compileall-arg-file9916279
Ref: 38929916279
Ref: library/compileall cmdoption-compileall-l9916533
Ref: 38939916533
Ref: library/compileall cmdoption-compileall-f9916689
Ref: 38949916689
Ref: library/compileall cmdoption-compileall-q9916766
Ref: 38959916766
Ref: library/compileall cmdoption-compileall-d9916956
Ref: 38969916956
Ref: library/compileall cmdoption-compileall-x9917315
Ref: 38979917315
Ref: library/compileall cmdoption-compileall-i9917494
Ref: 38989917494
Ref: library/compileall cmdoption-compileall-b9917702
Ref: 38999917702
Ref: library/compileall cmdoption-compileall-r9918034
Ref: 389a9918034
Ref: library/compileall cmdoption-compileall-j9918310
Ref: 389b9918310
Ref: library/compileall cmdoption-compileall-invalidation-mode9918495
Ref: 389c9918495
Ref: Command-line use-Footnote-19920167
Node: Public functions9920216
Ref: library/compileall public-functions9920338
Ref: 389d9920338
Ref: library/compileall compileall compile_dir9920393
Ref: 37b9920393
Ref: library/compileall compileall compile_file9923491
Ref: 6c49923491
Ref: library/compileall compileall compile_path9925602
Ref: 6c59925602
Ref: Public functions-Footnote-19927277
Ref: Public functions-Footnote-29927326
Node: dis --- Python 字节码反汇编器9927375
Ref: library/dis doc9927570
Ref: 389e9927570
Ref: library/dis dis-disassembler-for-python-bytecode9927570
Ref: 389f9927570
Ref: library/dis module-dis9927570
Ref: 389927570
Ref: dis --- Python 字节码反汇编器-Footnote-19928797
Node: 字节码分析9928859
Ref: library/dis bytecode-analysis9928968
Ref: 38a09928968
Ref: library/dis dis Bytecode9929181
Ref: 8409929181
Ref: library/dis dis Bytecode from_traceback9930077
Ref: 8429930077
Ref: library/dis dis Bytecode codeobj9930261
Ref: 38a19930261
Ref: library/dis dis Bytecode first_line9930326
Ref: 38a29930326
Ref: library/dis dis Bytecode dis9930421
Ref: 8419930421
Ref: library/dis dis Bytecode info9930588
Ref: 38a39930588
Node: 分析函数9931013
Ref: library/dis analysis-functions9931152
Ref: 38a49931152
Ref: library/dis dis code_info9931387
Ref: bd69931387
Ref: library/dis dis show_code9931866
Ref: 83b9931866
Ref: library/dis dis dis9932291
Ref: 38c9932291
Ref: library/dis dis distb9933546
Ref: 83c9933546
Ref: library/dis dis disassemble9933901
Ref: 83d9933901
Ref: library/dis dis disco9933960
Ref: 38a59933960
Ref: library/dis dis get_instructions9934694
Ref: 83f9934694
Ref: library/dis dis findlinestarts9935250
Ref: 38a69935250
Ref: library/dis dis findlabels9935676
Ref: 38a79935676
Ref: library/dis dis stack_effect9935852
Ref: 8439935852
Ref: 分析函数-Footnote-19936402
Node: Python字节码说明9936479
Ref: library/dis bytecodes9936618
Ref: 38a89936618
Ref: library/dis python-bytecode-instructions9936618
Ref: 38a99936618
Ref: library/dis dis Instruction9936819
Ref: 83e9936819
Ref: library/dis dis Instruction opcode9936882
Ref: 38aa9936882
Ref: library/dis dis Instruction opname9937043
Ref: 38ac9937043
Ref: library/dis dis Instruction arg9937107
Ref: 38ad9937107
Ref: library/dis dis Instruction argval9937206
Ref: 38ae9937206
Ref: library/dis dis Instruction argrepr9937304
Ref: 38af9937304
Ref: library/dis dis Instruction offset9937375
Ref: 38b09937375
Ref: library/dis dis Instruction starts_line9937451
Ref: 38b19937451
Ref: library/dis dis Instruction is_jump_target9937555
Ref: 38b29937555
Ref: library/dis opcode-NOP9937768
Ref: 38b39937768
Ref: library/dis opcode-POP_TOP9937850
Ref: 38b49937850
Ref: library/dis opcode-ROT_TWO9937911
Ref: 38b59937911
Ref: library/dis opcode-ROT_THREE9937975
Ref: 38b69937975
Ref: library/dis opcode-ROT_FOUR9938092
Ref: 2dd9938092
Ref: library/dis opcode-DUP_TOP9938259
Ref: 38b79938259
Ref: library/dis opcode-DUP_TOP_TWO9938341
Ref: 38b89938341
Ref: library/dis opcode-UNARY_POSITIVE9938565
Ref: 38b99938565
Ref: library/dis opcode-UNARY_NEGATIVE9938627
Ref: 38ba9938627
Ref: library/dis opcode-UNARY_NOT9938689
Ref: 38bb9938689
Ref: library/dis opcode-UNARY_INVERT9938749
Ref: 38bc9938749
Ref: library/dis opcode-GET_ITER9938809
Ref: 38bd9938809
Ref: library/dis opcode-GET_YIELD_FROM_ITER9938870
Ref: 38be9938870
Ref: library/dis opcode-BINARY_POWER9939247
Ref: 38bf9939247
Ref: library/dis opcode-BINARY_MULTIPLY9939314
Ref: 38c09939314
Ref: library/dis opcode-BINARY_MATRIX_MULTIPLY9939383
Ref: 38c19939383
Ref: library/dis opcode-BINARY_FLOOR_DIVIDE9939483
Ref: 38c29939483
Ref: library/dis opcode-BINARY_TRUE_DIVIDE9939556
Ref: 38c39939556
Ref: library/dis opcode-BINARY_MODULO9939628
Ref: 38c49939628
Ref: library/dis opcode-BINARY_ADD9939695
Ref: 38c59939695
Ref: library/dis opcode-BINARY_SUBTRACT9939759
Ref: 38c69939759
Ref: library/dis opcode-BINARY_SUBSCR9939828
Ref: 38c79939828
Ref: library/dis opcode-BINARY_LSHIFT9939894
Ref: 38c89939894
Ref: library/dis opcode-BINARY_RSHIFT9939962
Ref: 38c99939962
Ref: library/dis opcode-BINARY_AND9940030
Ref: 38ca9940030
Ref: library/dis opcode-BINARY_XOR9940094
Ref: 38cb9940094
Ref: library/dis opcode-BINARY_OR9940158
Ref: 38cc9940158
Ref: library/dis opcode-INPLACE_POWER9940452
Ref: 38cd9940452
Ref: library/dis opcode-INPLACE_MULTIPLY9940526
Ref: 38ce9940526
Ref: library/dis opcode-INPLACE_MATRIX_MULTIPLY9940602
Ref: 38cf9940602
Ref: library/dis opcode-INPLACE_FLOOR_DIVIDE9940709
Ref: 38d09940709
Ref: library/dis opcode-INPLACE_TRUE_DIVIDE9940790
Ref: 38d19940790
Ref: library/dis opcode-INPLACE_MODULO9940869
Ref: 38d29940869
Ref: library/dis opcode-INPLACE_ADD9940943
Ref: 38d39940943
Ref: library/dis opcode-INPLACE_SUBTRACT9941014
Ref: 38d49941014
Ref: library/dis opcode-INPLACE_LSHIFT9941090
Ref: 38d59941090
Ref: library/dis opcode-INPLACE_RSHIFT9941165
Ref: 38d69941165
Ref: library/dis opcode-INPLACE_AND9941240
Ref: 38d79941240
Ref: library/dis opcode-INPLACE_XOR9941311
Ref: 38d89941311
Ref: library/dis opcode-INPLACE_OR9941382
Ref: 38d99941382
Ref: library/dis opcode-STORE_SUBSCR9941452
Ref: 38da9941452
Ref: library/dis opcode-DELETE_SUBSCR9941518
Ref: 38db9941518
Ref: library/dis opcode-GET_AWAITABLE9941601
Ref: 38dc9941601
Ref: library/dis opcode-GET_AITER9941882
Ref: 38dd9941882
Ref: library/dis opcode-GET_ANEXT9942062
Ref: 38de9942062
Ref: library/dis opcode-END_ASYNC_FOR9942243
Ref: 2e39942243
Ref: library/dis opcode-BEFORE_ASYNC_WITH9942627
Ref: 38df9942627
Ref: library/dis opcode-SETUP_ASYNC_WITH9942823
Ref: 38e09942823
Ref: library/dis opcode-PRINT_EXPR9942933
Ref: 38e19942933
Ref: library/dis opcode-SET_ADD9943118
Ref: 38e29943118
Ref: library/dis opcode-LIST_APPEND9943217
Ref: 38e39943217
Ref: library/dis opcode-MAP_ADD9943326
Ref: 2e59943326
Ref: library/dis opcode-RETURN_VALUE9943777
Ref: 38e49943777
Ref: library/dis opcode-YIELD_VALUE9943845
Ref: 38e59943845
Ref: library/dis opcode-YIELD_FROM9943935
Ref: 38e69943935
Ref: library/dis opcode-SETUP_ANNOTATIONS9944069
Ref: 6279944069
Ref: library/dis opcode-IMPORT_STAR9944359
Ref: 38e79944359
Ref: library/dis opcode-POP_BLOCK9944582
Ref: 38e89944582
Ref: library/dis opcode-POP_EXCEPT9944716
Ref: 38e99944716
Ref: library/dis opcode-POP_FINALLY9944977
Ref: 2e09944977
Ref: library/dis opcode-BEGIN_FINALLY9945803
Ref: 2de9945803
Ref: library/dis opcode-END_FINALLY9946089
Ref: 2e19946089
Ref: library/dis opcode-LOAD_BUILD_CLASS9946803
Ref: 38eb9946803
Ref: library/dis opcode-SETUP_WITH9946968
Ref: 38ec9946968
Ref: library/dis opcode-WITH_CLEANUP_START9947605
Ref: 2e29947605
Ref: library/dis opcode-WITH_CLEANUP_FINISH9948294
Ref: 38ea9948294
Ref: library/dis opcode-STORE_NAME9948829
Ref: 38ee9948829
Ref: library/dis opcode-DELETE_NAME9949086
Ref: 38f19949086
Ref: library/dis opcode-UNPACK_SEQUENCE9949218
Ref: 38ef9949218
Ref: library/dis opcode-UNPACK_EX9949363
Ref: 38f29949363
Ref: library/dis opcode-STORE_ATTR9949796
Ref: 38f39949796
Ref: library/dis opcode-DELETE_ATTR9949933
Ref: 38f49949933
Ref: library/dis opcode-STORE_GLOBAL9950056
Ref: 38f09950056
Ref: library/dis opcode-DELETE_GLOBAL9950170
Ref: 38f59950170
Ref: library/dis opcode-LOAD_CONST9950280
Ref: 38f69950280
Ref: library/dis opcode-LOAD_NAME9950363
Ref: 38f79950363
Ref: library/dis opcode-BUILD_TUPLE9950460
Ref: 38f89950460
Ref: library/dis opcode-BUILD_LIST9950593
Ref: 38f99950593
Ref: library/dis opcode-BUILD_SET9950694
Ref: 38fa9950694
Ref: library/dis opcode-BUILD_MAP9950794
Ref: 38fb9950794
Ref: library/dis opcode-BUILD_CONST_KEY_MAP9951108
Ref: 6209951108
Ref: library/dis opcode-BUILD_STRING9951369
Ref: 61f9951369
Ref: library/dis opcode-BUILD_TUPLE_UNPACK9951509
Ref: 38fc9951509
Ref: library/dis opcode-BUILD_TUPLE_UNPACK_WITH_CALL9951756
Ref: 6269951756
Ref: library/dis opcode-BUILD_LIST_UNPACK9952019
Ref: 38fd9952019
Ref: library/dis opcode-BUILD_SET_UNPACK9952253
Ref: 38fe9952253
Ref: library/dis opcode-BUILD_MAP_UNPACK9952486
Ref: 38ff9952486
Ref: library/dis opcode-BUILD_MAP_UNPACK_WITH_CALL9952722
Ref: 6249952722
Ref: library/dis opcode-LOAD_ATTR9953132
Ref: 39009953132
Ref: library/dis opcode-COMPARE_OP9953226
Ref: 39019953226
Ref: library/dis opcode-IMPORT_NAME9953346
Ref: 39029953346
Ref: library/dis opcode-IMPORT_FROM9953709
Ref: 39039953709
Ref: library/dis opcode-JUMP_FORWARD9953919
Ref: 39049953919
Ref: library/dis opcode-POP_JUMP_IF_TRUE9954004
Ref: 39059954004
Ref: library/dis opcode-POP_JUMP_IF_FALSE9954165
Ref: 39069954165
Ref: library/dis opcode-JUMP_IF_TRUE_OR_POP9954327
Ref: 39079954327
Ref: library/dis opcode-JUMP_IF_FALSE_OR_POP9954553
Ref: 39089954553
Ref: library/dis opcode-JUMP_ABSOLUTE9954780
Ref: 39099954780
Ref: library/dis opcode-FOR_ITER9954868
Ref: 390a9954868
Ref: library/dis opcode-LOAD_GLOBAL9955197
Ref: 390b9955197
Ref: library/dis opcode-SETUP_FINALLY9955305
Ref: 390c9955305
Ref: library/dis opcode-CALL_FINALLY9955518
Ref: 2df9955518
Ref: library/dis opcode-LOAD_FAST9955738
Ref: 390d9955738
Ref: library/dis opcode-STORE_FAST9955851
Ref: 38ed9955851
Ref: library/dis opcode-DELETE_FAST9955951
Ref: 390e9955951
Ref: library/dis opcode-LOAD_CLOSURE9956041
Ref: 390f9956041
Ref: library/dis opcode-LOAD_DEREF9956342
Ref: 39109956342
Ref: library/dis opcode-LOAD_CLASSDEREF9956527
Ref: 9369956527
Ref: library/dis opcode-STORE_DEREF9956743
Ref: 39119956743
Ref: library/dis opcode-DELETE_DEREF9956882
Ref: 39129956882
Ref: library/dis opcode-RAISE_VARARGS9957068
Ref: 39139957068
Ref: library/dis opcode-CALL_FUNCTION9957484
Ref: 6229957484
Ref: library/dis opcode-CALL_FUNCTION_KW9958008
Ref: 6239958008
Ref: library/dis opcode-CALL_FUNCTION_EX9958786
Ref: 6259958786
Ref: library/dis opcode-LOAD_METHOD9959692
Ref: 4b59959692
Ref: library/dis opcode-CALL_METHOD9960176
Ref: 4b69960176
Ref: library/dis opcode-MAKE_FUNCTION9960701
Ref: 6219960701
Ref: library/dis opcode-BUILD_SLICE9961340
Ref: 39149961340
Ref: library/dis opcode-EXTENDED_ARG9961623
Ref: 39159961623
Ref: library/dis opcode-FORMAT_VALUE9961935
Ref: 61e9961935
Ref: library/dis opcode-HAVE_ARGUMENT9962789
Ref: 39169962789
Node: 操作码集合9963185
Ref: library/dis id19963303
Ref: 39179963303
Ref: library/dis opcode-collections9963303
Ref: 38ab9963303
Ref: library/dis dis opname9963410
Ref: 39189963410
Ref: library/dis dis opmap9963495
Ref: 39199963495
Ref: library/dis dis cmp_op9963564
Ref: 391a9963564
Ref: library/dis dis hasconst9963631
Ref: 391b9963631
Ref: library/dis dis hasfree9963697
Ref: 391c9963697
Ref: library/dis dis hasname9964003
Ref: 391d9964003
Ref: library/dis dis hasjrel9964077
Ref: 391e9964077
Ref: library/dis dis hasjabs9964154
Ref: 391f9964154
Ref: library/dis dis haslocal9964231
Ref: 39209964231
Ref: library/dis dis hascompare9964303
Ref: 39219964303
Node: pickletools --- pickle 开发者工具集9964371
Ref: library/pickletools doc9964513
Ref: 39229964513
Ref: library/pickletools module-pickletools9964513
Ref: cc9964513
Ref: library/pickletools pickletools-tools-for-pickle-developers9964513
Ref: 39239964513
Ref: pickletools --- pickle 开发者工具集-Footnote-19965214
Node: 命令行语法<2>9965284
Ref: library/pickletools command-line-usage9965404
Ref: 39249965404
Node: 命令行选项<6>9966310
Ref: library/pickletools command-line-options9966383
Ref: 39259966383
Ref: library/pickletools cmdoption-pickletools-a9966431
Ref: 39269966431
Ref: library/pickletools cmdoption-pickletools-o9966523
Ref: 39279966523
Ref: library/pickletools cmdoption-pickletools-l9966608
Ref: 39289966608
Ref: library/pickletools cmdoption-pickletools-m9966709
Ref: 39299966709
Ref: library/pickletools cmdoption-pickletools-p9966815
Ref: 392a9966815
Node: 编程接口<2>9966959
Ref: library/pickletools programmatic-interface9967079
Ref: 392b9967079
Ref: library/pickletools pickletools dis9967122
Ref: 5799967122
Ref: library/pickletools pickletools genops9967897
Ref: 392c9967897
Ref: library/pickletools pickletools optimize9968298
Ref: 1cce9968298
Node: 杂项服务9968580
Ref: library/misc doc9968707
Ref: 392d9968707
Ref: library/misc misc9968707
Ref: 392e9968707
Ref: library/misc miscellaneous-services9968707
Ref: 392f9968707
Node: formatter --- 通用格式化输出9968933
Ref: library/formatter doc9969017
Ref: 39309969017
Ref: library/formatter formatter-generic-output-formatting9969017
Ref: 39319969017
Ref: library/formatter module-formatter9969017
Ref: 829969017
Node: The Formatter Interface9970581
Ref: library/formatter formatter-interface9970710
Ref: 39329970710
Ref: library/formatter the-formatter-interface9970710
Ref: 39339970710
Ref: library/formatter formatter AS_IS9971038
Ref: 39349971038
Ref: library/formatter formatter formatter writer9971487
Ref: 39359971487
Ref: library/formatter formatter formatter end_paragraph9971579
Ref: 39369971579
Ref: library/formatter formatter formatter add_line_break9971726
Ref: 39379971726
Ref: library/formatter formatter formatter add_hor_rule9971875
Ref: 39389971875
Ref: library/formatter formatter formatter add_flowing_data9972188
Ref: 39399972188
Ref: library/formatter formatter formatter add_literal_data9972708
Ref: 393a9972708
Ref: library/formatter formatter formatter add_label_data9972927
Ref: 393b9972927
Ref: library/formatter formatter formatter flush_softspace9974354
Ref: 393c9974354
Ref: library/formatter formatter formatter push_alignment9974619
Ref: 393d9974619
Ref: library/formatter formatter formatter pop_alignment9974938
Ref: 393e9974938
Ref: library/formatter formatter formatter push_font9975016
Ref: 393f9975016
Ref: library/formatter formatter formatter pop_font9975397
Ref: 39409975397
Ref: library/formatter formatter formatter push_margin9975465
Ref: 39419975465
Ref: library/formatter formatter formatter pop_margin9975832
Ref: 39429975832
Ref: library/formatter formatter formatter push_style9975904
Ref: 39439975904
Ref: library/formatter formatter formatter pop_style9976207
Ref: 39449976207
Ref: library/formatter formatter formatter set_spacing9976474
Ref: 39459976474
Ref: library/formatter formatter formatter assert_line_data9976563
Ref: 39469976563
Node: Formatter Implementations9976921
Ref: library/formatter formatter-implementations9977079
Ref: 39479977079
Ref: library/formatter formatter-impls9977079
Ref: 39489977079
Ref: library/formatter formatter NullFormatter9977305
Ref: 39499977305
Ref: library/formatter formatter AbstractFormatter9977691
Ref: 394b9977691
Node: The Writer Interface9977976
Ref: library/formatter the-writer-interface9978133
Ref: 394c9978133
Ref: library/formatter writer-interface9978133
Ref: 394d9978133
Ref: library/formatter formatter writer flush9978554
Ref: 394e9978554
Ref: library/formatter formatter writer new_alignment9978641
Ref: 394f9978641
Ref: library/formatter formatter writer new_font9979001
Ref: 39509979001
Ref: library/formatter formatter writer new_margin9979527
Ref: 39519979527
Ref: library/formatter formatter writer new_spacing9979857
Ref: 39529979857
Ref: library/formatter formatter writer new_styles9979941
Ref: 39539979941
Ref: library/formatter formatter writer send_line_break9980275
Ref: 39549980275
Ref: library/formatter formatter writer send_paragraph9980344
Ref: 39559980344
Ref: library/formatter formatter writer send_hor_rule9980820
Ref: 39569980820
Ref: library/formatter formatter writer send_flowing_data9981171
Ref: 39579981171
Ref: library/formatter formatter writer send_literal_data9981471
Ref: 39589981471
Ref: library/formatter formatter writer send_label_data9981901
Ref: 39599981901
Node: Writer Implementations9982207
Ref: library/formatter writer-implementations9982330
Ref: 395a9982330
Ref: library/formatter writer-impls9982330
Ref: 395b9982330
Ref: library/formatter formatter NullWriter9982588
Ref: 394a9982588
Ref: library/formatter formatter AbstractWriter9982831
Ref: 395c9982831
Ref: library/formatter formatter DumbWriter9983045
Ref: 395d9983045
Node: Windows系统相关模块9983409
Ref: library/windows doc9983534
Ref: 395e9983534
Ref: library/windows ms-windows-specific-services9983534
Ref: 395f9983534
Ref: library/windows mswin-specific-services9983534
Ref: 13a69983534
Node: msilib --- Read and write Microsoft Installer files9984034
Ref: library/msilib doc9984206
Ref: 39609984206
Ref: library/msilib module-msilib9984206
Ref: b69984206
Ref: library/msilib msilib-read-and-write-microsoft-installer-files9984206
Ref: 39619984206
Ref: library/msilib msilib FCICreate9985276
Ref: 39629985276
Ref: library/msilib msilib UuidCreate9985775
Ref: 39639985775
Ref: library/msilib msilib OpenDatabase9985969
Ref: f1f9985969
Ref: library/msilib msilib CreateRecord9986519
Ref: 39649986519
Ref: library/msilib msilib init_database9986682
Ref: f209986682
Ref: library/msilib msilib add_data9987251
Ref: 39669987251
Ref: library/msilib msilib Binary9987823
Ref: 39679987823
Ref: library/msilib msilib add_tables9988017
Ref: 39689988017
Ref: library/msilib msilib add_stream9988356
Ref: 39699988356
Ref: library/msilib msilib gen_uuid9988514
Ref: 396a9988514
Ref: msilib --- Read and write Microsoft Installer files-Footnote-19988993
Ref: msilib --- Read and write Microsoft Installer files-Footnote-29989067
Ref: msilib --- Read and write Microsoft Installer files-Footnote-39989130
Ref: msilib --- Read and write Microsoft Installer files-Footnote-49989210
Node: Database Objects9989290
Ref: library/msilib database-objects9989415
Ref: 396b9989415
Ref: library/msilib id19989415
Ref: 396c9989415
Ref: library/msilib msilib Database OpenView9989468
Ref: f219989468
Ref: library/msilib msilib Database Commit9989618
Ref: 396d9989618
Ref: library/msilib msilib Database GetSummaryInformation9989754
Ref: 396e9989754
Ref: library/msilib msilib Database Close9989958
Ref: 3b69989958
Ref: Database Objects-Footnote-19990218
Ref: Database Objects-Footnote-29990298
Ref: Database Objects-Footnote-39990378
Ref: Database Objects-Footnote-49990458
Node: View Objects9990538
Ref: library/msilib id29990699
Ref: 396f9990699
Ref: library/msilib view-objects9990699
Ref: 39709990699
Ref: library/msilib msilib View Execute9990744
Ref: 39719990744
Ref: library/msilib msilib View GetColumnInfo9990972
Ref: 39729990972
Ref: library/msilib msilib View Fetch9991197
Ref: 39739991197
Ref: library/msilib msilib View Modify9991310
Ref: 39749991310
Ref: library/msilib msilib View Close9991861
Ref: 39759991861
Ref: View Objects-Footnote-19992081
Ref: View Objects-Footnote-29992161
Ref: View Objects-Footnote-39992241
Ref: View Objects-Footnote-49992321
Ref: View Objects-Footnote-59992401
Node: Summary Information Objects9992481
Ref: library/msilib summary-information-objects9992640
Ref: 39769992640
Ref: library/msilib summary-objects9992640
Ref: 39779992640
Ref: library/msilib msilib SummaryInformation GetProperty9992715
Ref: fd39992715
Ref: library/msilib msilib SummaryInformation GetPropertyCount9993306
Ref: 39789993306
Ref: library/msilib msilib SummaryInformation SetProperty9993458
Ref: 39799993458
Ref: library/msilib msilib SummaryInformation Persist9993750
Ref: 397a9993750
Ref: Summary Information Objects-Footnote-19994073
Ref: Summary Information Objects-Footnote-29994153
Ref: Summary Information Objects-Footnote-39994233
Ref: Summary Information Objects-Footnote-49994313
Node: Record Objects9994393
Ref: library/msilib id39994546
Ref: 397b9994546
Ref: library/msilib record-objects9994546
Ref: 397c9994546
Ref: library/msilib msilib Record GetFieldCount9994595
Ref: 397d9994595
Ref: library/msilib msilib Record GetInteger9994726
Ref: 397e9994726
Ref: library/msilib msilib Record GetString9994863
Ref: 397f9994863
Ref: library/msilib msilib Record SetString9994997
Ref: 39809994997
Ref: library/msilib msilib Record SetStream9995159
Ref: 39819995159
Ref: library/msilib msilib Record SetInteger9995358
Ref: 39829995358
Ref: library/msilib msilib Record ClearData9995521
Ref: 39839995521
Ref: Record Objects-Footnote-19995796
Ref: Record Objects-Footnote-29995876
Ref: Record Objects-Footnote-39995956
Ref: Record Objects-Footnote-49996036
Ref: Record Objects-Footnote-59996116
Node: Errors9996196
Ref: library/msilib errors9996333
Ref: 39849996333
Ref: library/msilib msi-errors9996333
Ref: 39859996333
Node: CAB Objects9996481
Ref: library/msilib cab9996621
Ref: 39869996621
Ref: library/msilib cab-objects9996621
Ref: 39879996621
Ref: library/msilib msilib CAB9996664
Ref: 39889996664
Ref: library/msilib msilib CAB append9997023
Ref: 39899997023
Ref: library/msilib msilib CAB commit9997372
Ref: 398a9997372
Node: Directory Objects9997576
Ref: library/msilib directory-objects9997725
Ref: 398b9997725
Ref: library/msilib msi-directory9997725
Ref: 398c9997725
Ref: library/msilib msilib Directory9997780
Ref: 398d9997780
Ref: library/msilib msilib Directory start_component9998546
Ref: fd49998546
Ref: library/msilib msilib Directory add_file9999087
Ref: 398e9999087
Ref: library/msilib msilib Directory glob9999584
Ref: 398f9999584
Ref: library/msilib msilib Directory remove_pyc9999798
Ref: 39909999798
Ref: Directory Objects-Footnote-110000008
Ref: Directory Objects-Footnote-210000088
Ref: Directory Objects-Footnote-310000168
Ref: Directory Objects-Footnote-410000248
Node: 相关特性<3>10000328
Ref: library/msilib features10000477
Ref: 399110000477
Ref: library/msilib id410000477
Ref: 399210000477
Ref: library/msilib msilib Feature10000518
Ref: 399310000518
Ref: library/msilib msilib Feature set_current10000914
Ref: 399410000914
Ref: 相关特性<3>-Footnote-110001209
Node: GUI classes10001289
Ref: library/msilib gui-classes10001439
Ref: 399510001439
Ref: library/msilib msi-gui10001439
Ref: 399610001439
Ref: library/msilib msilib Control10001720
Ref: 399710001720
Ref: library/msilib msilib Control event10001891
Ref: 399810001891
Ref: library/msilib msilib Control mapping10002038
Ref: 399910002038
Ref: library/msilib msilib Control condition10002160
Ref: 399a10002160
Ref: library/msilib msilib RadioButtonGroup10002299
Ref: 399b10002299
Ref: library/msilib msilib RadioButtonGroup add10002495
Ref: 399c10002495
Ref: library/msilib msilib Dialog10002765
Ref: 399d10002765
Ref: library/msilib msilib Dialog control10003068
Ref: 399e10003068
Ref: library/msilib msilib Dialog text10003431
Ref: 399f10003431
Ref: library/msilib msilib Dialog bitmap10003548
Ref: 39a010003548
Ref: library/msilib msilib Dialog line10003657
Ref: 39a110003657
Ref: library/msilib msilib Dialog pushbutton10003756
Ref: 39a210003756
Ref: library/msilib msilib Dialog radiogroup10003914
Ref: 39a310003914
Ref: library/msilib msilib Dialog checkbox10004088
Ref: 39a410004088
Ref: GUI classes-Footnote-110004443
Ref: GUI classes-Footnote-210004523
Ref: GUI classes-Footnote-310004603
Ref: GUI classes-Footnote-410004683
Ref: GUI classes-Footnote-510004763
Ref: GUI classes-Footnote-610004843
Ref: GUI classes-Footnote-710004923
Node: Precomputed tables10005003
Ref: library/msilib msi-tables10005129
Ref: 39a510005129
Ref: library/msilib precomputed-tables10005129
Ref: 39a610005129
Ref: library/msilib msilib schema10005342
Ref: 396510005342
Ref: library/msilib msilib sequence10005561
Ref: 39a710005561
Ref: library/msilib msilib text10005798
Ref: 39a810005798
Node: msvcrt --- 来自 MS VC++ 运行时的有用例程10005941
Ref: library/msvcrt doc10006156
Ref: 39a910006156
Ref: library/msvcrt module-msvcrt10006156
Ref: b710006156
Ref: library/msvcrt msvcrt-useful-routines-from-the-ms-vc-runtime10006156
Ref: 39aa10006156
Node: 文件操作10007019
Ref: library/msvcrt file-operations10007140
Ref: 39ab10007140
Ref: library/msvcrt msvcrt-files10007140
Ref: 39ac10007140
Ref: library/msvcrt msvcrt locking10007181
Ref: 34d910007181
Ref: library/msvcrt msvcrt LK_LOCK10007797
Ref: 39ad10007797
Ref: library/msvcrt msvcrt LK_RLCK10007824
Ref: 39ae10007824
Ref: library/msvcrt msvcrt LK_NBLCK10008070
Ref: 39af10008070
Ref: library/msvcrt msvcrt LK_NBRLCK10008098
Ref: 39b010008098
Ref: library/msvcrt msvcrt LK_UNLCK10008242
Ref: 39b110008242
Ref: library/msvcrt msvcrt setmode10008344
Ref: 39b210008344
Ref: library/msvcrt msvcrt open_osfhandle10008600
Ref: 34da10008600
Ref: library/msvcrt msvcrt get_osfhandle10009091
Ref: 34d810009091
Node: 控制台 I/O10009353
Ref: library/msvcrt console-i-o10009495
Ref: 39b310009495
Ref: library/msvcrt msvcrt-console10009495
Ref: 39b410009495
Ref: library/msvcrt msvcrt kbhit10009539
Ref: 39b510009539
Ref: library/msvcrt msvcrt getch10009640
Ref: 39b610009640
Ref: library/msvcrt msvcrt getwch10010086
Ref: 39b710010086
Ref: library/msvcrt msvcrt getche10010192
Ref: 39b810010192
Ref: library/msvcrt msvcrt getwche10010331
Ref: 39b910010331
Ref: library/msvcrt msvcrt putch10010439
Ref: 39ba10010439
Ref: library/msvcrt msvcrt putwch10010538
Ref: 39bb10010538
Ref: library/msvcrt msvcrt ungetch10010656
Ref: 39bc10010656
Ref: library/msvcrt msvcrt ungetwch10010846
Ref: 39bd10010846
Node: 其他函数10010968
Ref: library/msvcrt msvcrt-other10011089
Ref: 39be10011089
Ref: library/msvcrt other-functions10011089
Ref: 39bf10011089
Ref: library/msvcrt msvcrt heapmin10011130
Ref: 39c010011130
Node: winreg --- Windows 注册表访问10011304
Ref: library/winreg doc10011516
Ref: 39c110011516
Ref: library/winreg module-winreg10011516
Ref: 12b10011516
Ref: library/winreg winreg-windows-registry-access10011516
Ref: 39c210011516
Ref: library/winreg exception-changed10011909
Ref: 39c410011909
Node: 函数<11>10012136
Ref: library/winreg functions10012236
Ref: 39c510012236
Ref: library/winreg id110012236
Ref: 39c610012236
Ref: library/winreg winreg CloseKey10012302
Ref: 39c710012302
Ref: library/winreg winreg ConnectRegistry10012599
Ref: 34df10012599
Ref: library/winreg winreg CreateKey10013277
Ref: 34e010013277
Ref: library/winreg winreg CreateKeyEx10014207
Ref: 34e110014207
Ref: library/winreg winreg DeleteKey10015477
Ref: 34e210015477
Ref: library/winreg winreg DeleteKeyEx10016204
Ref: 34e310016204
Ref: library/winreg winreg DeleteValue10017594
Ref: 34e410017594
Ref: library/winreg winreg EnumKey10017970
Ref: 34e710017970
Ref: library/winreg winreg EnumValue10018618
Ref: 34e810018618
Ref: library/winreg winreg ExpandEnvironmentStrings10019836
Ref: 34e910019836
Ref: library/winreg winreg FlushKey10020189
Ref: 39cd10020189
Ref: library/winreg winreg LoadKey10021011
Ref: 34ea10021011
Ref: library/winreg winreg OpenKey10022204
Ref: 34eb10022204
Ref: library/winreg winreg OpenKeyEx10022275
Ref: 39d010022275
Ref: library/winreg winreg QueryInfoKey10023356
Ref: 34ed10023356
Ref: library/winreg winreg QueryValue10024257
Ref: 34ef10024257
Ref: library/winreg winreg QueryValueEx10025142
Ref: 34f010025142
Ref: library/winreg winreg SaveKey10026027
Ref: 34f110026027
Ref: library/winreg winreg SetValue10027081
Ref: 34f210027081
Ref: library/winreg winreg SetValueEx10028268
Ref: 34f310028268
Ref: library/winreg winreg DisableReflectionKey10029524
Ref: 34e510029524
Ref: library/winreg winreg EnableReflectionKey10030166
Ref: 34e610030166
Ref: library/winreg winreg QueryReflectionKey10030685
Ref: 34ee10030685
Ref: 函数<11>-Footnote-110031198
Ref: 函数<11>-Footnote-210031272
Ref: 函数<11>-Footnote-310031349
Node: 常量<10>10031426
Ref: library/winreg constants10031558
Ref: 39d510031558
Ref: library/winreg id210031558
Ref: 39d610031558
Node: HKEY_* Constants10031732
Ref: library/winreg hkey-constants10031817
Ref: 39c910031817
Ref: library/winreg id310031817
Ref: 39d710031817
Ref: library/winreg winreg HKEY_CLASSES_ROOT10031870
Ref: 39d810031870
Ref: library/winreg winreg HKEY_CURRENT_USER10032123
Ref: 39d910032123
Ref: library/winreg winreg HKEY_LOCAL_MACHINE10032428
Ref: 39cf10032428
Ref: library/winreg winreg HKEY_USERS10032654
Ref: 39ce10032654
Ref: library/winreg winreg HKEY_PERFORMANCE_DATA10032865
Ref: 39da10032865
Ref: library/winreg winreg HKEY_CURRENT_CONFIG10033134
Ref: 39db10033134
Ref: library/winreg winreg HKEY_DYN_DATA10033271
Ref: 39dc10033271
Node: Access Rights10033365
Ref: library/winreg access-rights10033470
Ref: 39cb10033470
Ref: library/winreg id410033470
Ref: 39dd10033470
Ref: library/winreg winreg KEY_ALL_ACCESS10033581
Ref: 39de10033581
Ref: library/winreg winreg KEY_WRITE10033872
Ref: 39ca10033872
Ref: library/winreg winreg KEY_READ10034027
Ref: 39d110034027
Ref: library/winreg winreg KEY_EXECUTE10034208
Ref: 39e410034208
Ref: library/winreg winreg KEY_QUERY_VALUE10034282
Ref: 39df10034282
Ref: library/winreg winreg KEY_SET_VALUE10034372
Ref: 39d310034372
Ref: library/winreg winreg KEY_CREATE_SUB_KEY10034465
Ref: 39e010034465
Ref: library/winreg winreg KEY_ENUMERATE_SUB_KEYS10034557
Ref: 39e110034557
Ref: library/winreg winreg KEY_NOTIFY10034659
Ref: 39e210034659
Ref: library/winreg winreg KEY_CREATE_LINK10034795
Ref: 39e310034795
Ref: Access Rights-Footnote-110034928
Node: 64-bit Specific10035005
Ref: library/winreg bit-access-rights10035070
Ref: 39e510035070
Ref: library/winreg bit-specific10035070
Ref: 39e610035070
Ref: library/winreg winreg KEY_WOW64_64KEY10035189
Ref: 39e710035189
Ref: library/winreg winreg KEY_WOW64_32KEY10035328
Ref: 39e810035328
Ref: 64-bit Specific-Footnote-110035503
Node: Value Types10035575
Ref: library/winreg id510035655
Ref: 39e910035655
Ref: library/winreg value-types10035655
Ref: 39d410035655
Ref: library/winreg winreg REG_BINARY10035750
Ref: 39ea10035750
Ref: library/winreg winreg REG_DWORD10035812
Ref: 39eb10035812
Ref: library/winreg winreg REG_DWORD_LITTLE_ENDIAN10035863
Ref: 39ec10035863
Ref: library/winreg winreg REG_DWORD_BIG_ENDIAN10035997
Ref: 39ed10035997
Ref: library/winreg winreg REG_EXPAND_SZ10036082
Ref: 39cc10036082
Ref: library/winreg winreg REG_LINK10036213
Ref: 39ee10036213
Ref: library/winreg winreg REG_MULTI_SZ10036273
Ref: f9310036273
Ref: library/winreg winreg REG_NONE10036441
Ref: 39ef10036441
Ref: library/winreg winreg REG_QWORD10036499
Ref: 5bb10036499
Ref: library/winreg winreg REG_QWORD_LITTLE_ENDIAN10036576
Ref: 39f010036576
Ref: library/winreg winreg REG_RESOURCE_LIST10036733
Ref: 39f110036733
Ref: library/winreg winreg REG_FULL_RESOURCE_DESCRIPTOR10036808
Ref: 39f210036808
Ref: library/winreg winreg REG_RESOURCE_REQUIREMENTS_LIST10036883
Ref: 39f310036883
Ref: library/winreg winreg REG_SZ10036966
Ref: 39d210036966
Ref: Value Types-Footnote-110037061
Node: Registry Handle Objects10037138
Ref: library/winreg handle-object10037251
Ref: 39c310037251
Ref: library/winreg registry-handle-objects10037251
Ref: 39f410037251
Ref: library/winreg winreg PyHKEY Close10038411
Ref: 39c810038411
Ref: library/winreg winreg PyHKEY Detach10038543
Ref: 34ec10038543
Ref: library/winreg winreg PyHKEY __enter__10039145
Ref: 39f510039145
Ref: library/winreg winreg PyHKEY __exit__10039177
Ref: 39f610039177
Node: winsound --- Sound-playing interface for Windows10039571
Ref: library/winsound doc10039724
Ref: 39f710039724
Ref: library/winsound module-winsound10039724
Ref: 12c10039724
Ref: library/winsound winsound-sound-playing-interface-for-windows10039724
Ref: 39f810039724
Ref: library/winsound winsound Beep10040074
Ref: 5bd10040074
Ref: library/winsound winsound PlaySound10040460
Ref: 5bf10040460
Ref: library/winsound winsound MessageBeep10041030
Ref: 5be10041030
Ref: library/winsound winsound SND_FILENAME10041633
Ref: 39f910041633
Ref: library/winsound winsound SND_ALIAS10041768
Ref: 39fa10041768
Ref: library/winsound winsound SND_LOOP10043382
Ref: 39fc10043382
Ref: library/winsound winsound SND_MEMORY10043571
Ref: 39fe10043571
Ref: library/winsound winsound SND_PURGE10043937
Ref: 39ff10043937
Ref: library/winsound winsound SND_ASYNC10044101
Ref: 39fd10044101
Ref: library/winsound winsound SND_NODEFAULT10044199
Ref: 39fb10044199
Ref: library/winsound winsound SND_NOSTOP10044324
Ref: 3a0010044324
Ref: library/winsound winsound SND_NOWAIT10044406
Ref: 3a0110044406
Ref: library/winsound winsound MB_ICONASTERISK10044568
Ref: 3a0210044568
Ref: library/winsound winsound MB_ICONEXCLAMATION10044648
Ref: 3a0310044648
Ref: library/winsound winsound MB_ICONHAND10044735
Ref: 3a0410044735
Ref: library/winsound winsound MB_ICONQUESTION10044808
Ref: 3a0510044808
Ref: library/winsound winsound MB_OK10044889
Ref: 3a0610044889
Node: Unix 专有服务10044959
Ref: library/unix doc10045090
Ref: 3a0710045090
Ref: library/unix unix10045090
Ref: 3a0810045090
Ref: library/unix unix-specific-services10045090
Ref: 3a0910045090
Node: posix --- 最常见的 POSIX 系统调用10046154
Ref: library/posix doc10046287
Ref: 3a0a10046287
Ref: library/posix module-posix10046287
Ref: d210046287
Ref: library/posix posix-the-most-common-posix-system-calls10046287
Ref: 3a0b10046287
Node: 大文件支持10047380
Ref: library/posix large-file-support10047503
Ref: 3a0c10047503
Ref: library/posix posix-large-files10047503
Ref: 3a0d10047503
Node: 重要的模块内容10048504
Ref: library/posix notable-module-contents10048627
Ref: 3a0e10048627
Ref: library/posix posix-contents10048627
Ref: 3a0f10048627
Ref: library/posix posix environ10048791
Ref: 3a1010048791
Node: pwd --- 用户密码数据库10049847
Ref: library/pwd doc10050026
Ref: 3a1110050026
Ref: library/pwd module-pwd10050026
Ref: d710050026
Ref: library/pwd pwd-the-password-database10050026
Ref: 3a1210050026
Ref: library/pwd pwd getpwuid10052122
Ref: 102710052122
Ref: library/pwd pwd getpwnam10052227
Ref: 103a10052227
Ref: library/pwd pwd getpwall10052324
Ref: 3a1310052324
Node: spwd --- The shadow password database10052623
Ref: library/spwd doc10052781
Ref: 3a1410052781
Ref: library/spwd module-spwd10052781
Ref: f210052781
Ref: library/spwd spwd-the-shadow-password-database10052781
Ref: 3a1510052781
Ref: library/spwd spwd getspnam10055065
Ref: 60710055065
Ref: library/spwd spwd getspall10055310
Ref: 3a1610055310
Node: grp --- 组数据库10055628
Ref: library/grp doc10055799
Ref: 3a1710055799
Ref: library/grp grp-the-group-database10055799
Ref: 3a1810055799
Ref: library/grp module-grp10055799
Ref: 8b10055799
Ref: library/grp grp getgrgid10057178
Ref: 5e810057178
Ref: library/grp grp getgrnam10057489
Ref: 103b10057489
Ref: library/grp grp getgrall10057653
Ref: 3a1910057653
Node: crypt --- Function to check Unix passwords10057919
Ref: library/crypt doc10058091
Ref: 3a1a10058091
Ref: library/crypt crypt-function-to-check-unix-passwords10058091
Ref: 3a1b10058091
Ref: library/crypt module-crypt10058091
Ref: 2910058091
Ref: crypt --- Function to check Unix passwords-Footnote-110059088
Node: Hashing Methods10059152
Ref: library/crypt hashing-methods10059272
Ref: 3a1c10059272
Ref: library/crypt crypt METHOD_SHA51210059457
Ref: 3a1d10059457
Ref: library/crypt crypt METHOD_SHA25610059648
Ref: 3a1e10059648
Ref: library/crypt crypt METHOD_BLOWFISH10059809
Ref: 3a1f10059809
Ref: library/crypt crypt METHOD_MD510059990
Ref: 3a2010059990
Ref: library/crypt crypt METHOD_CRYPT10060143
Ref: 61210060143
Node: Module Attributes10060289
Ref: library/crypt module-attributes10060433
Ref: 3a2110060433
Ref: library/crypt crypt methods10060507
Ref: 3a2210060507
Node: 模块函数<2>10060680
Ref: library/crypt module-functions10060819
Ref: 3a2310060819
Ref: library/crypt crypt crypt10060922
Ref: 3a2410060922
Ref: library/crypt crypt mksalt10062419
Ref: 38510062419
Node: 例子<31>10063263
Ref: library/crypt examples10063376
Ref: 3a2510063376
Node: termios --- POSIX 风格的 tty 控制10064511
Ref: library/termios doc10064689
Ref: 3a2610064689
Ref: library/termios module-termios10064689
Ref: 10510064689
Ref: library/termios termios-posix-style-tty-control10064689
Ref: 3a2710064689
Ref: library/termios termios tcgetattr10065652
Ref: 3a2810065652
Ref: library/termios termios tcsetattr10066191
Ref: 3a2910066191
Ref: library/termios termios tcsendbreak10066638
Ref: 3a2a10066638
Ref: library/termios termios tcdrain10066865
Ref: 3a2b10066865
Ref: library/termios termios tcflush10066990
Ref: 3a2c10066990
Ref: library/termios termios tcflow10067254
Ref: 3a2d10067254
Node: 示例<16>10067664
Ref: library/termios example10067749
Ref: 3a2e10067749
Ref: library/termios termios-example10067749
Ref: 3a2f10067749
Node: tty --- 终端控制功能10068493
Ref: library/tty doc10068652
Ref: 3a3010068652
Ref: library/tty module-tty10068652
Ref: 11610068652
Ref: library/tty tty-terminal-control-functions10068652
Ref: 3a3110068652
Ref: library/tty tty setraw10069028
Ref: 3a3210069028
Ref: library/tty tty setcbreak10069258
Ref: 3a3310069258
Ref: tty --- 终端控制功能-Footnote-110069611
Node: pty --- 伪终端工具10069673
Ref: library/pty doc10069836
Ref: 3a3410069836
Ref: library/pty module-pty10069836
Ref: d610069836
Ref: library/pty pty-pseudo-terminal-utilities10069836
Ref: 3a3510069836
Ref: library/pty pty fork10070370
Ref: 3a3610070370
Ref: library/pty pty openpty10070744
Ref: 3a3710070744
Ref: library/pty pty spawn10071004
Ref: 8a110071004
Ref: pty --- 伪终端工具-Footnote-110072838
Ref: pty --- 伪终端工具-Footnote-210072900
Node: 示例<17>10072943
Ref: library/pty example10073013
Ref: 3a3810073013
Node: fcntl --- The fcntl and ioctl system calls10074180
Ref: library/fcntl doc10074345
Ref: 3a3910074345
Ref: library/fcntl fcntl-the-fcntl-and-ioctl-system-calls10074345
Ref: 3a3a10074345
Ref: library/fcntl module-fcntl10074345
Ref: 7e10074345
Ref: library/fcntl fcntl fcntl10075444
Ref: 26a910075444
Ref: library/fcntl fcntl ioctl10076886
Ref: de610076886
Ref: library/fcntl fcntl flock10079218
Ref: 34d710079218
Ref: library/fcntl fcntl lockf10079723
Ref: d5a10079723
Node: pipes --- 终端管道接口10082437
Ref: library/pipes doc10082618
Ref: 3a3b10082618
Ref: library/pipes module-pipes10082618
Ref: cd10082618
Ref: library/pipes pipes-interface-to-shell-pipelines10082618
Ref: 3a3c10082618
Ref: library/pipes pipes Template10083130
Ref: 3a3d10083130
Ref: pipes --- 终端管道接口-Footnote-110083486
Node: 模板对象10083550
Ref: library/pipes id110083627
Ref: 3a3e10083627
Ref: library/pipes template-objects10083627
Ref: 3a3f10083627
Ref: library/pipes pipes Template reset10083700
Ref: 3a4010083700
Ref: library/pipes pipes Template clone10083783
Ref: 3a4110083783
Ref: library/pipes pipes Template debug10083863
Ref: 3a4210083863
Ref: library/pipes pipes Template append10084115
Ref: 3a4310084115
Ref: library/pipes pipes Template prepend10084800
Ref: 3a4410084800
Ref: library/pipes pipes Template open10084954
Ref: 3a4510084954
Ref: library/pipes pipes Template copy10085151
Ref: 3a4610085151
Node: resource --- Resource usage information10085250
Ref: library/resource doc10085422
Ref: 3a4710085422
Ref: library/resource module-resource10085422
Ref: e110085422
Ref: library/resource resource-resource-usage-information10085422
Ref: 3a4810085422
Ref: library/resource resource error10085907
Ref: 3a4910085907
Ref: resource --- Resource usage information-Footnote-110086176
Node: Resource Limits10086225
Ref: library/resource resource-limits10086339
Ref: 3a4a10086339
Ref: library/resource resource RLIM_INFINITY10087218
Ref: 3a4b10087218
Ref: library/resource resource getrlimit10087324
Ref: 3a4c10087324
Ref: library/resource resource setrlimit10087616
Ref: 34b310087616
Ref: library/resource resource prlimit10088772
Ref: 8a810088772
Ref: library/resource resource RLIMIT_CORE10090374
Ref: 34b410090374
Ref: library/resource resource RLIMIT_CPU10090637
Ref: 3a4e10090637
Ref: library/resource resource RLIMIT_FSIZE10090999
Ref: 3a4f10090999
Ref: library/resource resource RLIMIT_DATA10091097
Ref: 3a5010091097
Ref: library/resource resource RLIMIT_STACK10091190
Ref: 3a5110091190
Ref: library/resource resource RLIMIT_RSS10091389
Ref: 3a5210091389
Ref: library/resource resource RLIMIT_NPROC10091509
Ref: 3a5310091509
Ref: library/resource resource RLIMIT_NOFILE10091614
Ref: 3a4d10091614
Ref: library/resource resource RLIMIT_OFILE10091730
Ref: 3a5410091730
Ref: library/resource resource RLIMIT_MEMLOCK10091815
Ref: 3a5510091815
Ref: library/resource resource RLIMIT_VMEM10091915
Ref: 3a5610091915
Ref: library/resource resource RLIMIT_AS10092019
Ref: 3a5710092019
Ref: library/resource resource RLIMIT_MSGQUEUE10092142
Ref: 8a910092142
Ref: library/resource resource RLIMIT_NICE10092333
Ref: 8aa10092333
Ref: library/resource resource RLIMIT_RTPRIO10092532
Ref: 8ab10092532
Ref: library/resource resource RLIMIT_RTTIME10092693
Ref: 8ac10092693
Ref: library/resource resource RLIMIT_SIGPENDING10092952
Ref: 8ad10092952
Ref: library/resource resource RLIMIT_SBSIZE10093128
Ref: 8ae10093128
Ref: library/resource resource RLIMIT_SWAP10093433
Ref: 8af10093433
Ref: library/resource resource RLIMIT_NPTS10093820
Ref: 8b010093820
Ref: Resource Limits-Footnote-110094037
Node: Resource Usage10094104
Ref: library/resource resource-usage10094218
Ref: 3a5810094218
Ref: library/resource resource getrusage10094335
Ref: da110094335
Ref: library/resource resource getpagesize10098836
Ref: 3a5910098836
Ref: library/resource resource RUSAGE_SELF10099138
Ref: 3a5a10099138
Ref: library/resource resource RUSAGE_CHILDREN10099340
Ref: 3a5b10099340
Ref: library/resource resource RUSAGE_BOTH10099541
Ref: 3a5c10099541
Ref: library/resource resource RUSAGE_THREAD10099740
Ref: 3a5d10099740
Node: nis --- Sun 的 NIS 黄页 接口10099934
Ref: library/nis doc10100099
Ref: 3a5e10100099
Ref: library/nis module-nis10100099
Ref: c010100099
Ref: library/nis nis-interface-to-sun-s-nis-yellow-pages10100099
Ref: 3a5f10100099
Ref: library/nis nis match10100481
Ref: d9a10100481
Ref: library/nis nis cat10101015
Ref: 3a6110101015
Ref: library/nis nis maps10101442
Ref: d9b10101442
Ref: library/nis nis get_default_domain10101653
Ref: 3a6210101653
Ref: library/nis nis error10101778
Ref: 3a6010101778
Node: Unix syslog 库例程10101864
Ref: library/syslog doc10101981
Ref: 3a6310101981
Ref: library/syslog module-syslog10101981
Ref: 10010101981
Ref: library/syslog syslog-unix-syslog-library-routines10101981
Ref: 3a6410101981
Ref: library/syslog syslog syslog10102464
Ref: 34de10102464
Ref: library/syslog syslog openlog10103266
Ref: 34dc10103266
Ref: library/syslog syslog closelog10104323
Ref: 34db10104323
Ref: library/syslog syslog setlogmask10104811
Ref: 34dd10104811
Node: 例子<32>10106066
Ref: library/syslog examples10106134
Ref: 3a6510106134
Node: 简单示例10106194
Ref: library/syslog simple-example10106253
Ref: 3a6610106253
Node: 被取代的模块10106741
Ref: library/superseded doc10106871
Ref: 3a6710106871
Ref: library/superseded superseded10106871
Ref: 3a6810106871
Ref: library/superseded superseded-modules10106871
Ref: 3a6910106871
Node: optparse --- 解析器的命令行选项10107190
Ref: library/optparse doc10107329
Ref: 3a6a10107329
Ref: library/optparse module-optparse10107329
Ref: c410107329
Ref: library/optparse optparse-parser-for-command-line-options10107329
Ref: 3a6b10107329
Ref: optparse --- 解析器的命令行选项-Footnote-110110116
Node: 背景10110183
Ref: library/optparse background10110284
Ref: 3a6d10110284
Ref: library/optparse optparse-background10110284
Ref: 3a6e10110284
Node: 术语10110732
Ref: library/optparse optparse-terminology10110811
Ref: 3a6f10110811
Ref: library/optparse terminology10110811
Ref: 3a7010110811
Node: What are options for?10114626
Ref: library/optparse optparse-what-options-for10114726
Ref: 3a7110114726
Ref: library/optparse what-are-options-for10114726
Ref: 3a7210114726
Node: 位置位置10116407
Ref: library/optparse optparse-what-positional-arguments-for10116492
Ref: 3a7310116492
Ref: library/optparse what-are-positional-arguments-for10116492
Ref: 3a7410116492
Node: 教程<2>10117775
Ref: library/optparse optparse-tutorial10117897
Ref: 3a7510117897
Ref: library/optparse tutorial10117897
Ref: 3a7610117897
Node: Understanding option actions10120504
Ref: library/optparse optparse-understanding-option-actions10120603
Ref: 3a7b10120603
Ref: library/optparse understanding-option-actions10120603
Ref: 3a7c10120603
Node: The store action10121194
Ref: library/optparse optparse-store-action10121331
Ref: 3a7e10121331
Ref: library/optparse the-store-action10121331
Ref: 3a7f10121331
Node: Handling boolean flag options10123515
Ref: library/optparse handling-boolean-flag-options10123637
Ref: 3a8010123637
Ref: library/optparse optparse-handling-boolean-options10123637
Ref: 3a8110123637
Node: Other actions10124520
Ref: library/optparse optparse-other-actions10124638
Ref: 3a8210124638
Ref: library/optparse other-actions10124638
Ref: 3a8310124638
Node: 默认值<2>10125046
Ref: library/optparse default-values10125150
Ref: 3a8610125150
Ref: library/optparse optparse-default-values10125150
Ref: 3a8710125150
Node: Generating help10127022
Ref: library/optparse generating-help10127138
Ref: 3a8810127138
Ref: library/optparse optparse-generating-help10127138
Ref: 3a8910127138
Node: Grouping Options10131299
Ref: library/optparse grouping-options10131367
Ref: 3a8a10131367
Ref: library/optparse optparse OptionGroup10131698
Ref: 3a8b10131698
Ref: library/optparse optparse OptionParser get_option_group10135194
Ref: 3a8c10135194
Node: Printing a version string10135464
Ref: library/optparse optparse-printing-version-string10135595
Ref: 3a8d10135595
Ref: library/optparse printing-a-version-string10135595
Ref: 3a8e10135595
Ref: library/optparse optparse OptionParser print_version10136479
Ref: 3a8f10136479
Ref: library/optparse optparse OptionParser get_version10136853
Ref: 3a9110136853
Node: How optparse handles errors10136997
Ref: library/optparse how-optparse-handles-errors10137136
Ref: 3a9210137136
Ref: library/optparse optparse-how-optparse-handles-errors10137136
Ref: 3a9310137136
Node: Putting it all together10139219
Ref: library/optparse optparse-putting-it-all-together10139324
Ref: 3a9410139324
Ref: library/optparse putting-it-all-together10139324
Ref: 3a9510139324
Node: 参考指南10140242
Ref: library/optparse optparse-reference-guide10140374
Ref: 3a8410140374
Ref: library/optparse reference-guide10140374
Ref: 3a9610140374
Node: 创建解析器10140711
Ref: library/optparse creating-the-parser10140799
Ref: 3a9710140799
Ref: library/optparse optparse-creating-parser10140799
Ref: 3a9810140799
Ref: library/optparse optparse OptionParser10140931
Ref: 3a6c10140931
Node: 填充解析器10143927
Ref: library/optparse optparse-populating-parser10144036
Ref: 3a9a10144036
Ref: library/optparse populating-the-parser10144036
Ref: 3a9b10144036
Node: 定义选项10145303
Ref: library/optparse defining-options10145414
Ref: 3a9c10145414
Ref: library/optparse optparse-defining-options10145414
Ref: 3a9d10145414
Ref: library/optparse optparse OptionParser add_option10145811
Ref: 208310145811
Node: Option attributes10148631
Ref: library/optparse option-attributes10148750
Ref: 3a9f10148750
Ref: library/optparse optparse-option-attributes10148750
Ref: 3aa010148750
Ref: library/optparse optparse Option action10149086
Ref: 3a7710149086
Ref: library/optparse optparse Option type10149305
Ref: 3a7810149305
Ref: library/optparse optparse Option dest10149518
Ref: 3a7910149518
Ref: library/optparse optparse Option default10149860
Ref: 3aa210149860
Ref: library/optparse optparse Option nargs10150051
Ref: 3aa410150051
Ref: library/optparse optparse Option const10150280
Ref: 3aa510150280
Ref: library/optparse optparse Option choices10150387
Ref: 3aa610150387
Ref: library/optparse optparse Option callback10150508
Ref: 3aa710150508
Ref: library/optparse optparse Option callback_args10150737
Ref: 3aa810150737
Ref: library/optparse optparse Option callback_kwargs10150770
Ref: 3aa910150770
Ref: library/optparse optparse Option help10150931
Ref: 3a7a10150931
Ref: library/optparse optparse Option metavar10151276
Ref: 3aaa10151276
Node: Standard option actions10151476
Ref: library/optparse optparse-standard-option-actions10151604
Ref: 3a9e10151604
Ref: library/optparse standard-option-actions10151604
Ref: 3aab10151604
Node: Standard option types10159685
Ref: library/optparse optparse-standard-option-types10159811
Ref: 3aa110159811
Ref: library/optparse standard-option-types10159811
Ref: 3aac10159811
Node: 解析参数<2>10161282
Ref: library/optparse optparse-parsing-arguments10161429
Ref: 3aad10161429
Ref: library/optparse parsing-arguments10161429
Ref: 3aae10161429
Node: Querying and manipulating your option parser10162776
Ref: library/optparse optparse-querying-manipulating-option-parser10162927
Ref: 3aaf10162927
Ref: library/optparse querying-and-manipulating-your-option-parser10162927
Ref: 3ab010162927
Ref: library/optparse optparse OptionParser disable_interspersed_args10163236
Ref: 208410163236
Ref: library/optparse optparse OptionParser enable_interspersed_args10164026
Ref: 3ab110164026
Ref: library/optparse optparse OptionParser get_option10164232
Ref: 3ab210164232
Ref: library/optparse optparse OptionParser has_option10164405
Ref: 3ab310164405
Ref: library/optparse optparse OptionParser remove_option10164581
Ref: 3ab410164581
Node: Conflicts between options10164967
Ref: library/optparse conflicts-between-options10165112
Ref: 3ab510165112
Ref: library/optparse optparse-conflicts-between-options10165112
Ref: 3a9910165112
Node: 清理<2>10167575
Ref: library/optparse cleanup10167689
Ref: 3ab610167689
Ref: library/optparse optparse-cleanup10167689
Ref: 3ab710167689
Node: Other methods10168098
Ref: library/optparse optparse-other-methods10168178
Ref: 3ab810168178
Ref: library/optparse other-methods10168178
Ref: 3ab910168178
Ref: library/optparse optparse OptionParser set_usage10168280
Ref: 3aba10168280
Ref: library/optparse optparse OptionParser print_usage10168569
Ref: 3a9010168569
Ref: library/optparse optparse OptionParser get_usage10168905
Ref: 3abb10168905
Ref: library/optparse optparse OptionParser set_defaults10169043
Ref: 3aa310169043
Node: Option Callbacks10170207
Ref: library/optparse option-callbacks10170348
Ref: 3abc10170348
Ref: library/optparse optparse-option-callbacks10170348
Ref: 3a8510170348
Node: Defining a callback option10171565
Ref: library/optparse defining-a-callback-option10171677
Ref: 3abd10171677
Ref: library/optparse optparse-defining-callback-option10171677
Ref: 3abe10171677
Node: How callbacks are called10173902
Ref: library/optparse how-callbacks-are-called10174051
Ref: 3abf10174051
Ref: library/optparse optparse-how-callbacks-called10174051
Ref: 3ac010174051
Node: Raising errors in a callback10176661
Ref: library/optparse optparse-raising-errors-in-callback10176819
Ref: 3ac110176819
Ref: library/optparse raising-errors-in-a-callback10176819
Ref: 3ac210176819
Node: Callback example 1 trivial callback10177290
Ref: library/optparse callback-example-1-trivial-callback10177461
Ref: 3ac310177461
Ref: library/optparse optparse-callback-example-110177461
Ref: 3ac410177461
Node: Callback example 2 check option order10177909
Ref: library/optparse callback-example-2-check-option-order10178101
Ref: 3ac510178101
Ref: library/optparse optparse-callback-example-210178101
Ref: 3ac610178101
Node: Callback example 3 check option order generalized10178659
Ref: library/optparse callback-example-3-check-option-order-generalized10178860
Ref: 3ac710178860
Ref: library/optparse optparse-callback-example-310178860
Ref: 3ac810178860
Node: Callback example 4 check arbitrary condition10179634
Ref: library/optparse callback-example-4-check-arbitrary-condition10179832
Ref: 3ac910179832
Ref: library/optparse optparse-callback-example-410179832
Ref: 3aca10179832
Node: Callback example 5 fixed arguments10180627
Ref: library/optparse callback-example-5-fixed-arguments10180813
Ref: 3acb10180813
Ref: library/optparse optparse-callback-example-510180813
Ref: 3acc10180813
Node: Callback example 6 variable arguments10181887
Ref: library/optparse callback-example-6-variable-arguments10182020
Ref: 3acd10182020
Ref: library/optparse optparse-callback-example-610182020
Ref: 3ace10182020
Node: Extending optparse10184125
Ref: library/optparse extending-optparse10184245
Ref: 3acf10184245
Ref: library/optparse optparse-extending-optparse10184245
Ref: 3a7d10184245
Node: Adding new types10184582
Ref: library/optparse adding-new-types10184680
Ref: 3ad010184680
Ref: library/optparse optparse-adding-new-types10184680
Ref: 3ad110184680
Ref: library/optparse optparse Option TYPES10184969
Ref: 3ad210184969
Ref: library/optparse optparse Option TYPE_CHECKER10185125
Ref: 3ad310185125
Node: Adding new actions10188133
Ref: library/optparse adding-new-actions10188231
Ref: 3ad410188231
Ref: library/optparse optparse-adding-new-actions10188231
Ref: 3ad510188231
Ref: library/optparse optparse Option ACTIONS10189318
Ref: 3ad610189318
Ref: library/optparse optparse Option STORE_ACTIONS10189391
Ref: 3ad710189391
Ref: library/optparse optparse Option TYPED_ACTIONS10189477
Ref: 3ad810189477
Ref: library/optparse optparse Option ALWAYS_TYPED_ACTIONS10189563
Ref: 3ad910189563
Node: imp --- Access the import internals10192862
Ref: library/imp doc10193001
Ref: 3ada10193001
Ref: library/imp imp-access-the-import-internals10193001
Ref: 3adb10193001
Ref: library/imp module-imp10193001
Ref: 9a10193001
Ref: library/imp imp get_magic10193443
Ref: 86c10193443
Ref: library/imp imp get_suffixes10193723
Ref: 3adc10193723
Ref: library/imp imp find_module10194450
Ref: 3ae010194450
Ref: library/imp imp load_module10196950
Ref: 3ae410196950
Ref: library/imp imp new_module10198809
Ref: 3ae510198809
Ref: library/imp imp reload10199047
Ref: c7810199047
Ref: library/imp imp cache_from_source10202184
Ref: 3ae610202184
Ref: library/imp imp source_from_cache10203219
Ref: 3ae810203219
Ref: library/imp imp get_tag10203938
Ref: 3ae710203938
Ref: library/imp imp lock_held10204478
Ref: 3ae910204478
Ref: library/imp imp acquire_lock10205396
Ref: 3aea10205396
Ref: library/imp imp release_lock10206081
Ref: 3aeb10206081
Ref: library/imp imp PY_SOURCE10206601
Ref: 3add10206601
Ref: library/imp imp PY_COMPILED10206700
Ref: 3ade10206700
Ref: library/imp imp C_EXTENSION10206815
Ref: 3adf10206815
Ref: library/imp imp PKG_DIRECTORY10206938
Ref: 3ae310206938
Ref: library/imp imp C_BUILTIN10207047
Ref: 3ae110207047
Ref: library/imp imp PY_FROZEN10207150
Ref: 3ae210207150
Ref: library/imp imp NullImporter10207251
Ref: 9c310207251
Ref: library/imp imp NullImporter find_module10207643
Ref: 3aec10207643
Ref: imp --- Access the import internals-Footnote-110208110
Ref: imp --- Access the import internals-Footnote-210208172
Ref: imp --- Access the import internals-Footnote-310208221
Ref: imp --- Access the import internals-Footnote-410208270
Ref: imp --- Access the import internals-Footnote-510208319
Ref: imp --- Access the import internals-Footnote-610208368
Ref: imp --- Access the import internals-Footnote-710208417
Node: 例子<33>10208466
Ref: library/imp examples10208548
Ref: 3aed10208548
Ref: library/imp examples-imp10208548
Ref: 3aee10208548
Node: 未创建文档的模块10209548
Ref: library/undoc doc10209652
Ref: 3aef10209652
Ref: library/undoc undoc10209652
Ref: 3af010209652
Ref: library/undoc undocumented-modules10209652
Ref: 3af110209652
Node: 平台特定模块10210014
Ref: library/undoc platform-specific-modules10210093
Ref: 3af210210093
Node: 扩展和嵌入 Python 解释器10210415
Ref: extending/index doc10210546
Ref: 3af310210546
Ref: extending/index extending-and-embedding-the-python-interpreter10210546
Ref: 3af410210546
Ref: extending/index extending-index10210546
Ref: 120d10210546
Node: 推荐的第三方工具10211707
Ref: extending/index recommended-third-party-tools10211845
Ref: 3af510211845
Ref: 推荐的第三方工具-Footnote-110212423
Ref: 推荐的第三方工具-Footnote-210212450
Ref: 推荐的第三方工具-Footnote-310212486
Ref: 推荐的第三方工具-Footnote-410212514
Ref: 推荐的第三方工具-Footnote-510212548
Node: 不使用第三方工具创建扩展10212621
Ref: extending/index creating-extensions-without-third-party-tools10212819
Ref: 3af610212819
Node: 使用 C 或 C++ 扩展 Python10213271
Ref: extending/extending doc10213413
Ref: 3af710213413
Ref: extending/extending extending-intro10213413
Ref: 3af810213413
Ref: extending/extending extending-python-with-c-or-c10213413
Ref: 3af910213413
Ref: 使用 C 或 C++ 扩展 Python-Footnote-110214904
Node: 一个简单的例子10214941
Ref: extending/extending a-simple-example10215059
Ref: 3afa10215059
Ref: extending/extending extending-simpleexample10215059
Ref: 3afb10215059
Ref: 一个简单的例子-Footnote-110218367
Node: 关于错误和异常10218492
Ref: extending/extending extending-errors10218631
Ref: 3afd10218631
Ref: extending/extending intermezzo-errors-and-exceptions10218631
Ref: 3afe10218631
Node: 回到例子10224886
Ref: extending/extending back-to-the-example10225037
Ref: 3b0510225037
Ref: extending/extending backtoexample10225037
Ref: 3b0610225037
Node: 模块方法表和初始化函数10226605
Ref: extending/extending methodtable10226750
Ref: 3b0810226750
Ref: extending/extending the-module-s-method-table-and-initialization-function10226750
Ref: 3b0910226750
Ref: 模块方法表和初始化函数-Footnote-110231828
Node: 编译和链接10231877
Ref: extending/extending compilation10232035
Ref: 3b0c10232035
Ref: extending/extending compilation-and-linkage10232035
Ref: 3b0d10232035
Node: 在C中调用Python函数10233324
Ref: extending/extending calling-python-functions-from-c10233476
Ref: 3b0f10233476
Ref: extending/extending callingpython10233476
Ref: 3b1010233476
Node: 提取扩展函数的参数10239379
Ref: extending/extending extracting-parameters-in-extension-functions10239549
Ref: 3b1410239549
Ref: extending/extending parsetuple10239549
Ref: 3afc10239549
Node: 给扩展函数的关键字参数10241993
Ref: extending/extending keyword-parameters-for-extension-functions10242153
Ref: 3b1510242153
Ref: extending/extending parsetupleandkeywords10242153
Ref: 3b1610242153
Node: 构造任意值10244712
Ref: extending/extending building-arbitrary-values10244857
Ref: 3b1710244857
Ref: extending/extending buildvalue10244857
Ref: 3b1810244857
Node: 引用计数10246803
Ref: extending/extending refcounts10246936
Ref: 3b1110246936
Ref: extending/extending reference-counts10246936
Ref: 3b1910246936
Node: Python中的引用计数10250502
Ref: extending/extending refcountsinpython10250596
Ref: 3b1a10250596
Ref: extending/extending reference-counting-in-python10250596
Ref: 3b1b10250596
Ref: Python中的引用计数-Footnote-110252421
Ref: Python中的引用计数-Footnote-210252520
Node: 拥有规则10252668
Ref: extending/extending ownership-rules10252786
Ref: 3b1c10252786
Ref: extending/extending ownershiprules10252786
Ref: 3b1d10252786
Node: 危险的薄冰10254851
Ref: extending/extending thin-ice10254955
Ref: 3b2710254955
Ref: extending/extending thinice10254955
Ref: 3b2810254955
Node: NULL指针10257868
Ref: extending/extending null-pointers10257951
Ref: 3b2a10257951
Ref: extending/extending nullpointers10257951
Ref: 3b2b10257951
Ref: NULL指针-Footnote-110259453
Node: 在C++中编写扩展10259582
Ref: extending/extending cplusplus10259726
Ref: 3b2c10259726
Ref: extending/extending writing-extensions-in-c10259726
Ref: 3b2d10259726
Node: 给扩展模块提供C API10260353
Ref: extending/extending providing-a-c-api-for-an-extension-module10260476
Ref: 3b2e10260476
Ref: extending/extending using-capsules10260476
Ref: cf910260476
Node: 自定义扩展类型：教程10268045
Ref: extending/newtypes_tutorial doc10268232
Ref: 3b3210268232
Ref: extending/newtypes_tutorial defining-extension-types-tutorial10268232
Ref: 3b3310268232
Ref: extending/newtypes_tutorial defining-new-types10268232
Ref: 3b3410268232
Node: 基础10268789
Ref: extending/newtypes_tutorial dnt-basics10268915
Ref: 3b3510268915
Ref: extending/newtypes_tutorial the-basics10268915
Ref: 3b3610268915
Ref: 基础-Footnote-110277693
Node: Adding data and methods to the Basic example10277763
Ref: extending/newtypes_tutorial adding-data-and-methods-to-the-basic-example10277942
Ref: 3b4110277942
Ref: Adding data and methods to the Basic example-Footnote-110294194
Ref: Adding data and methods to the Basic example-Footnote-210294291
Node: Providing finer control over data attributes10294432
Ref: extending/newtypes_tutorial providing-finer-control-over-data-attributes10294641
Ref: 3b4c10294641
Ref: Providing finer control over data attributes-Footnote-110304544
Node: Supporting cyclic garbage collection10304928
Ref: extending/newtypes_tutorial supporting-cyclic-garbage-collection10305116
Ref: 3b4e10305116
Ref: Supporting cyclic garbage collection-Footnote-110315759
Node: Subclassing other types10315937
Ref: extending/newtypes_tutorial subclassing-other-types10316072
Ref: 3b5210316072
Node: 定义扩展类型：已分类主题10321334
Ref: extending/newtypes doc10321508
Ref: 3b5510321508
Ref: extending/newtypes defining-extension-types-assorted-topics10321508
Ref: 3b5610321508
Ref: extending/newtypes new-types-topics10321508
Ref: 3b5710321508
Ref: extending/newtypes dnt-type-methods10321583
Ref: 3b5810321583
Node: 终结和内存释放10325778
Ref: extending/newtypes finalization-and-de-allocation10325893
Ref: 3b5910325893
Ref: 终结和内存释放-Footnote-110328737
Node: 对象展示10328786
Ref: extending/newtypes object-presentation10328922
Ref: 3b5c10328922
Node: 属性管理10330504
Ref: extending/newtypes attribute-management10330636
Ref: 3b6010330636
Node: 泛型属性管理10332160
Ref: extending/newtypes generic-attribute-management10332270
Ref: 3b4810332270
Ref: extending/newtypes id110332270
Ref: 3b6110332270
Node: Type-specific Attribute Management10336387
Ref: extending/newtypes type-specific-attribute-management10336497
Ref: 3b6410336497
Node: Object Comparison10338255
Ref: extending/newtypes object-comparison10338400
Ref: 3b6710338400
Node: Abstract Protocol Support10340169
Ref: extending/newtypes abstract-protocol-support10340324
Ref: 3b6a10340324
Node: Weak Reference Support10345992
Ref: extending/newtypes weak-reference-support10346142
Ref: 3b7010346142
Ref: extending/newtypes weakref-support10346142
Ref: 199f10346142
Node: 更多建议10348052
Ref: extending/newtypes more-suggestions10348168
Ref: 3b7210348168
Node: 构建C/C++扩展10349094
Ref: extending/building doc10349273
Ref: 3b7410349273
Ref: extending/building building10349273
Ref: 3b0e10349273
Ref: extending/building building-c-and-c-extensions10349273
Ref: 3b7510349273
Ref: extending/building c PyInit_modulename10349704
Ref: 3b7610349704
Ref: 构建C/C++扩展-Footnote-110350959
Node: 使用distutils构建C和C++扩展10351008
Ref: extending/building building-c-and-c-extensions-with-distutils10351129
Ref: 3b7910351129
Node: 发布你的扩展模块10354687
Ref: extending/building distributing10354808
Ref: 3b7b10354808
Ref: extending/building distributing-your-extension-modules10354808
Ref: 3b7c10354808
Node: 在Windows平台编译C和C++扩展10355573
Ref: extending/windows doc10355707
Ref: 3b7e10355707
Ref: extending/windows building-c-and-c-extensions-on-windows10355707
Ref: 3b7f10355707
Ref: extending/windows building-on-windows10355707
Ref: 13ac10355707
Node: 菜谱式说明10356755
Ref: extending/windows a-cookbook-approach10356883
Ref: 3b8010356883
Ref: extending/windows win-cookbook10356883
Ref: 3b8110356883
Ref: 菜谱式说明-Footnote-110357403
Node: Unix 和 Windows 之间的差异10357480
Ref: extending/windows differences-between-unix-and-windows10357636
Ref: 3b8210357636
Ref: extending/windows dynamic-linking10357636
Ref: 3b8310357636
Node: DLL 的实际使用10360369
Ref: extending/windows using-dlls-in-practice10360501
Ref: 3b8410360501
Ref: extending/windows win-dlls10360501
Ref: 3b8510360501
Node: 在更大的应用程序中嵌入 CPython 运行时10362062
Ref: extending/index embedding-the-cpython-runtime-in-a-larger-application10362227
Ref: 3b8610362227
Node: 在其它应用程序嵌入 Python10362597
Ref: extending/embedding doc10362719
Ref: 3b8710362719
Ref: extending/embedding embedding10362719
Ref: 3b8810362719
Ref: extending/embedding embedding-python-in-another-application10362719
Ref: 3b8910362719
Node: Very High Level Embedding10365021
Ref: extending/embedding high-level-embedding10365170
Ref: 3b8c10365170
Ref: extending/embedding very-high-level-embedding10365170
Ref: 3b8d10365170
Node: Beyond Very High Level Embedding An overview10366933
Ref: extending/embedding beyond-very-high-level-embedding-an-overview10367100
Ref: 3b8e10367100
Ref: extending/embedding lower-level-embedding10367100
Ref: 3b8f10367100
Node: 纯嵌入10368809
Ref: extending/embedding id110368976
Ref: 3b9010368976
Ref: extending/embedding pure-embedding10368976
Ref: 3b9110368976
Node: Extending Embedded Python10373580
Ref: extending/embedding extending-embedded-python10373727
Ref: 3b9410373727
Ref: extending/embedding extending-with-embedding10373727
Ref: 3b9510373727
Node: 在 C++ 中嵌入 Python10375707
Ref: extending/embedding embedding-python-in-c10375881
Ref: 3b9610375881
Ref: extending/embedding embeddingincplusplus10375881
Ref: 3b9710375881
Node: 在类 Unix 系统中编译和链接10376251
Ref: extending/embedding compiling10376391
Ref: 3b9210376391
Ref: extending/embedding compiling-and-linking-under-unix-like-systems10376391
Ref: 3b9810376391
Node: Python/C API 参考手册10378543
Ref: c-api/index doc10378678
Ref: 3b9a10378678
Ref: c-api/index c-api-index10378678
Ref: 120e10378678
Ref: c-api/index python-c-api-reference-manual10378678
Ref: 3b9b10378678
Node: 概述<15>10379353
Ref: c-api/intro doc10379470
Ref: 3b9c10379470
Ref: c-api/intro api-intro10379470
Ref: 3b9d10379470
Ref: c-api/intro introduction10379470
Ref: 3b9e10379470
Node: 代码标准10380786
Ref: c-api/intro coding-standards10380866
Ref: 3b9f10380866
Ref: 代码标准-Footnote-110381268
Node: 包含文件10381317
Ref: c-api/intro api-includes10381418
Ref: 3ba010381418
Ref: c-api/intro include-files10381418
Ref: 3ba110381418
Node: 有用的宏10383782
Ref: c-api/intro useful-macros10383901
Ref: 3ba210383901
Ref: c-api/intro c Py_UNREACHABLE10384175
Ref: 42b10384175
Ref: c-api/intro c Py_ABS10384571
Ref: 3ba310384571
Ref: c-api/intro c Py_MIN10384655
Ref: 3ba410384655
Ref: c-api/intro c Py_MAX10384760
Ref: 3ba510384760
Ref: c-api/intro c Py_STRINGIFY10384865
Ref: 3ba610384865
Ref: c-api/intro c Py_MEMBER_SIZE10385013
Ref: 3ba710385013
Ref: c-api/intro c Py_CHARMASK10385155
Ref: 3ba810385155
Ref: c-api/intro c Py_GETENV10385338
Ref: 3ba910385338
Ref: c-api/intro c Py_UNUSED10385539
Ref: 3baa10385539
Ref: c-api/intro c Py_DEPRECATED10385742
Ref: 3bab10385742
Ref: c-api/intro c PyDoc_STRVAR10385971
Ref: f3c10385971
Ref: c-api/intro c PyDoc_STR10386589
Ref: 3bac10386589
Ref: 有用的宏-Footnote-110387181
Ref: 有用的宏-Footnote-210387230
Node: 对象、类型和引用计数10387279
Ref: c-api/intro api-objects10387396
Ref: 3bad10387396
Ref: c-api/intro objects-types-and-reference-counts10387396
Ref: 3bae10387396
Node: 引用计数<2>10388677
Ref: c-api/intro api-refcounts10388774
Ref: 3baf10388774
Ref: c-api/intro reference-counts10388774
Ref: 3bb010388774
Node: 引用计数细节10391858
Ref: c-api/intro api-refcountdetails10391928
Ref: 3bb110391928
Ref: c-api/intro reference-count-details10391928
Ref: 3bb210391928
Node: 类型10399112
Ref: c-api/intro api-types10399209
Ref: 3bb610399209
Ref: c-api/intro types10399209
Ref: 3bb710399209
Node: 异常<18>10399687
Ref: c-api/intro api-exceptions10399807
Ref: 3bb810399807
Ref: c-api/intro exceptions10399807
Ref: 3bb910399807
Node: 嵌入Python<2>10405876
Ref: c-api/intro api-embedding10405978
Ref: 3bbb10405978
Ref: c-api/intro embedding-python10405978
Ref: 3bbc10405978
Node: 调试构建10409155
Ref: c-api/intro api-debugging10409238
Ref: 3bc110409238
Ref: c-api/intro debugging-builds10409238
Ref: 3bc210409238
Node: 稳定的应用程序二进制接口10411518
Ref: c-api/stable doc10411669
Ref: 3bc310411669
Ref: c-api/stable stable10411669
Ref: 3bc410411669
Ref: c-api/stable stable-application-binary-interface10411669
Ref: 3bc510411669
Ref: 稳定的应用程序二进制接口-Footnote-110413396
Node: The Very High Level Layer10413445
Ref: c-api/veryhigh doc10413601
Ref: 3bc610413601
Ref: c-api/veryhigh the-very-high-level-layer10413601
Ref: 3bc710413601
Ref: c-api/veryhigh veryhigh10413601
Ref: 3bc810413601
Ref: c-api/veryhigh c Py_Main10414622
Ref: 4bf10414622
Ref: c-api/veryhigh c Py_BytesMain10415579
Ref: 17710415579
Ref: c-api/veryhigh c PyRun_AnyFile10415744
Ref: 3bc910415744
Ref: c-api/veryhigh c PyRun_AnyFileFlags10415967
Ref: 3bcb10415967
Ref: c-api/veryhigh c PyRun_AnyFileEx10416207
Ref: 3bcc10416207
Ref: c-api/veryhigh c PyRun_AnyFileExFlags10416434
Ref: 3bca10416434
Ref: c-api/veryhigh c PyRun_SimpleString10416999
Ref: 3b8a10416999
Ref: c-api/veryhigh c PyRun_SimpleStringFlags10417224
Ref: 3bce10417224
Ref: c-api/veryhigh c PyRun_SimpleFile10417905
Ref: 3b8b10417905
Ref: c-api/veryhigh c PyRun_SimpleFileEx10418128
Ref: 3bcf10418128
Ref: c-api/veryhigh c PyRun_SimpleFileExFlags10418347
Ref: ed710418347
Ref: c-api/veryhigh c PyRun_InteractiveOne10419039
Ref: 3bd010419039
Ref: c-api/veryhigh c PyRun_InteractiveOneFlags10419245
Ref: 3bd110419245
Ref: c-api/veryhigh c PyRun_InteractiveLoop10420005
Ref: 3bcd10420005
Ref: c-api/veryhigh c PyRun_InteractiveLoopFlags10420213
Ref: 3bd210420213
Ref: c-api/veryhigh c PyOS_InputHook10420671
Ref: 3bd310420671
Ref: c-api/veryhigh c PyOS_ReadlineFunctionPointer10421152
Ref: 97410421152
Ref: c-api/veryhigh c PyParser_SimpleParseString10422175
Ref: 3bd410422175
Ref: c-api/veryhigh c PyParser_SimpleParseStringFlags10422447
Ref: 3bd610422447
Ref: c-api/veryhigh c PyParser_SimpleParseStringFlagsFilename10422708
Ref: 3bd510422708
Ref: c-api/veryhigh c PyParser_SimpleParseFile10423225
Ref: 3bd710423225
Ref: c-api/veryhigh c PyParser_SimpleParseFileFlags10423467
Ref: 3bd810423467
Ref: c-api/veryhigh c PyRun_String10423750
Ref: fc310423750
Ref: c-api/veryhigh c PyRun_StringFlags10424020
Ref: 3bd910424020
Ref: c-api/veryhigh c PyRun_File10424679
Ref: 3bda10424679
Ref: c-api/veryhigh c PyRun_FileEx10424991
Ref: 3bdc10424991
Ref: c-api/veryhigh c PyRun_FileFlags10425289
Ref: 3bdd10425289
Ref: c-api/veryhigh c PyRun_FileExFlags10425610
Ref: 3bdb10425610
Ref: c-api/veryhigh c Py_CompileString10426195
Ref: 3bde10426195
Ref: c-api/veryhigh c Py_CompileStringFlags10426458
Ref: 3bdf10426458
Ref: c-api/veryhigh c Py_CompileStringObject10426750
Ref: 3be110426750
Ref: c-api/veryhigh c Py_CompileStringExFlags10427863
Ref: 3be010427863
Ref: c-api/veryhigh c PyEval_EvalCode10428233
Ref: 3be210428233
Ref: c-api/veryhigh c PyEval_EvalCodeEx10428553
Ref: 3be310428553
Ref: c-api/veryhigh c PyFrameObject10429228
Ref: 97910429228
Ref: c-api/veryhigh c PyEval_EvalFrame10429391
Ref: 3be410429391
Ref: c-api/veryhigh c PyEval_EvalFrameEx10429624
Ref: 96f10429624
Ref: c-api/veryhigh c PyEval_MergeCompilerFlags10430289
Ref: 3be510430289
Ref: c-api/veryhigh c Py_eval_input10430479
Ref: 3be610430479
Ref: c-api/veryhigh c Py_file_input10430635
Ref: 3be710430635
Ref: c-api/veryhigh c Py_single_input10430919
Ref: 3be810430919
Ref: c-api/veryhigh c PyCompilerFlags10431143
Ref: 2cd10431143
Ref: c-api/veryhigh c PyCompilerFlags cf_flags10431676
Ref: 3be910431676
Ref: c-api/veryhigh c PyCompilerFlags cf_feature_version10431736
Ref: 3bea10431736
Ref: c-api/veryhigh c CO_FUTURE_DIVISION10432089
Ref: 3beb10432089
Ref: The Very High Level Layer-Footnote-110432302
Node: 引用计数<3>10432351
Ref: c-api/refcounting doc10432483
Ref: 3bec10432483
Ref: c-api/refcounting countingrefs10432483
Ref: 3bed10432483
Ref: c-api/refcounting reference-counting10432483
Ref: 3bee10432483
Ref: c-api/refcounting c Py_INCREF10432581
Ref: 26610432581
Ref: c-api/refcounting c Py_XINCREF10432783
Ref: 26810432783
Ref: c-api/refcounting c Py_DECREF10432951
Ref: 26710432951
Ref: c-api/refcounting c Py_XDECREF10433964
Ref: 26910433964
Ref: c-api/refcounting c Py_CLEAR10434232
Ref: 3b5010434232
Node: 异常处理10435239
Ref: c-api/exceptions doc10435355
Ref: 3bef10435355
Ref: c-api/exceptions exception-handling10435355
Ref: 3bf010435355
Ref: c-api/exceptions exceptionhandling10435355
Ref: 365810435355
Node: 打印和清理10437409
Ref: c-api/exceptions printing-and-clearing10437497
Ref: 3bf110437497
Ref: c-api/exceptions c PyErr_Clear10437537
Ref: 97310437537
Ref: c-api/exceptions c PyErr_PrintEx10437660
Ref: 3bf210437660
Ref: c-api/exceptions c PyErr_Print10438285
Ref: f1910438285
Ref: c-api/exceptions c PyErr_WriteUnraisable10438362
Ref: fce10438362
Node: 抛出异常<2>10438964
Ref: c-api/exceptions raising-exceptions10439070
Ref: 3bf310439070
Ref: c-api/exceptions c PyErr_SetString10439275
Ref: 3aff10439275
Ref: c-api/exceptions c PyErr_SetObject10439619
Ref: 3b0110439619
Ref: c-api/exceptions c PyErr_Format10439825
Ref: 7b310439825
Ref: c-api/exceptions c PyErr_FormatV10440273
Ref: 7b210440273
Ref: c-api/exceptions c PyErr_SetNone10440568
Ref: 3bf410440568
Ref: c-api/exceptions c PyErr_BadArgument10440682
Ref: 3bf510440682
Ref: c-api/exceptions c PyErr_NoMemory10440896
Ref: 3b0310440896
Ref: c-api/exceptions c PyErr_SetFromErrno10441156
Ref: 3b0010441156
Ref: c-api/exceptions c PyErr_SetFromErrnoWithFilenameObject10441962
Ref: 3bf710441962
Ref: c-api/exceptions c PyErr_SetFromErrnoWithFilenameObjects10442423
Ref: 3bf810442423
Ref: c-api/exceptions c PyErr_SetFromErrnoWithFilename10442816
Ref: 3bf910442816
Ref: c-api/exceptions c PyErr_SetFromWindowsErr10443165
Ref: 3bfa10443165
Ref: c-api/exceptions c PyErr_SetExcFromWindowsErr10443855
Ref: 3bfb10443855
Ref: c-api/exceptions c PyErr_SetFromWindowsErrWithFilename10444125
Ref: 3bfc10444125
Ref: c-api/exceptions c PyErr_SetExcFromWindowsErrWithFilenameObject10444520
Ref: 3bfd10444520
Ref: c-api/exceptions c PyErr_SetExcFromWindowsErrWithFilenameObjects10444842
Ref: 3bfe10444842
Ref: c-api/exceptions c PyErr_SetExcFromWindowsErrWithFilename10445225
Ref: 3bff10445225
Ref: c-api/exceptions c PyErr_SetImportError10445544
Ref: 60110445544
Ref: c-api/exceptions c PyErr_SyntaxLocationObject10445967
Ref: 3c0010445967
Ref: c-api/exceptions c PyErr_SyntaxLocationEx10446313
Ref: 3c0110446313
Ref: c-api/exceptions c PyErr_SyntaxLocation10446625
Ref: 3c0210446625
Ref: c-api/exceptions c PyErr_BadInternalCall10446796
Ref: 3c0310446796
Node: 警告<3>10447057
Ref: c-api/exceptions issuing-warnings10447169
Ref: 3c0410447169
Ref: c-api/exceptions c PyErr_WarnEx10447915
Ref: db910447915
Ref: c-api/exceptions c PyErr_SetImportErrorSubclass10448896
Ref: 5d410448896
Ref: c-api/exceptions c PyErr_WarnExplicitObject10449229
Ref: 3c0610449229
Ref: c-api/exceptions c PyErr_WarnExplicit10449766
Ref: 3c0710449766
Ref: c-api/exceptions c PyErr_WarnFormat10450153
Ref: 3c0810450153
Ref: c-api/exceptions c PyErr_ResourceWarning10450467
Ref: 5d510450467
Node: 查询错误指示器10450783
Ref: c-api/exceptions querying-the-error-indicator10450895
Ref: 3c0910450895
Ref: c-api/exceptions c PyErr_Occurred10450945
Ref: 3b0210450945
Ref: c-api/exceptions c PyErr_ExceptionMatches10451741
Ref: 3bba10451741
Ref: c-api/exceptions c PyErr_GivenExceptionMatches10452019
Ref: 3c0a10452019
Ref: c-api/exceptions c PyErr_Fetch10452416
Ref: 97210452416
Ref: c-api/exceptions c PyErr_Restore10453336
Ref: 3b5a10453336
Ref: c-api/exceptions c PyErr_NormalizeException10454329
Ref: fcf10454329
Ref: c-api/exceptions c PyErr_GetExcInfo10455196
Ref: 3c0b10455196
Ref: c-api/exceptions c PyErr_SetExcInfo10455948
Ref: 3c0c10455948
Node: 信号处理<2>10456756
Ref: c-api/exceptions signal-handling10456868
Ref: 3c0d10456868
Ref: c-api/exceptions c PyErr_CheckSignals10456903
Ref: 3bf610456903
Ref: c-api/exceptions c PyErr_SetInterrupt10457567
Ref: 3c0e10457567
Ref: c-api/exceptions c PySignal_SetWakeupFd10457978
Ref: d4e10457978
Node: 异常类10458638
Ref: c-api/exceptions exception-classes10458741
Ref: 3c0f10458741
Ref: c-api/exceptions c PyErr_NewException10458771
Ref: c0810458771
Ref: c-api/exceptions c PyErr_NewExceptionWithDoc10459707
Ref: c0710459707
Node: 异常对象10460087
Ref: c-api/exceptions exception-objects10460195
Ref: 3c1010460195
Ref: c-api/exceptions c PyException_GetTraceback10460230
Ref: 3c1110460230
Ref: c-api/exceptions c PyException_SetTraceback10460536
Ref: fd010460536
Ref: c-api/exceptions c PyException_GetContext10460695
Ref: 3c1210460695
Ref: c-api/exceptions c PyException_SetContext10461065
Ref: 3c1310461065
Ref: c-api/exceptions c PyException_GetCause10461348
Ref: 3c1410461348
Ref: c-api/exceptions c PyException_SetCause10461663
Ref: 3c1510461663
Node: Unicode 异常对象10462069
Ref: c-api/exceptions unicode-exception-objects10462180
Ref: 3c1610462180
Ref: c-api/exceptions unicodeexceptions10462180
Ref: 3c1710462180
Ref: c-api/exceptions c PyUnicodeDecodeError_Create10462313
Ref: 3c1810462313
Ref: c-api/exceptions c PyUnicodeEncodeError_Create10462734
Ref: 3c1910462734
Ref: c-api/exceptions c PyUnicodeTranslateError_Create10463341
Ref: 3c1a10463341
Ref: c-api/exceptions c PyUnicodeDecodeError_GetEncoding10463908
Ref: 3c1b10463908
Ref: c-api/exceptions c PyUnicodeEncodeError_GetEncoding10463981
Ref: 3c1c10463981
Ref: c-api/exceptions c PyUnicodeDecodeError_GetObject10464137
Ref: 3c1d10464137
Ref: c-api/exceptions c PyUnicodeEncodeError_GetObject10464208
Ref: 3c1e10464208
Ref: c-api/exceptions c PyUnicodeTranslateError_GetObject10464279
Ref: 3c1f10464279
Ref: c-api/exceptions c PyUnicodeDecodeError_GetStart10464434
Ref: 3c2010464434
Ref: c-api/exceptions c PyUnicodeEncodeError_GetStart10464527
Ref: 3c2110464527
Ref: c-api/exceptions c PyUnicodeTranslateError_GetStart10464620
Ref: 3c2210464620
Ref: c-api/exceptions c PyUnicodeDecodeError_SetStart10464899
Ref: 3c2310464899
Ref: c-api/exceptions c PyUnicodeEncodeError_SetStart10464991
Ref: 3c2410464991
Ref: c-api/exceptions c PyUnicodeTranslateError_SetStart10465083
Ref: 3c2510465083
Ref: c-api/exceptions c PyUnicodeDecodeError_GetEnd10465306
Ref: 3c2610465306
Ref: c-api/exceptions c PyUnicodeEncodeError_GetEnd10465395
Ref: 3c2710465395
Ref: c-api/exceptions c PyUnicodeTranslateError_GetEnd10465484
Ref: 3c2810465484
Ref: c-api/exceptions c PyUnicodeDecodeError_SetEnd10465753
Ref: 3c2910465753
Ref: c-api/exceptions c PyUnicodeEncodeError_SetEnd10465841
Ref: 3c2a10465841
Ref: c-api/exceptions c PyUnicodeTranslateError_SetEnd10465929
Ref: 3c2b10465929
Ref: c-api/exceptions c PyUnicodeDecodeError_GetReason10466144
Ref: 3c2c10466144
Ref: c-api/exceptions c PyUnicodeEncodeError_GetReason10466215
Ref: 3c2d10466215
Ref: c-api/exceptions c PyUnicodeTranslateError_GetReason10466286
Ref: 3c2e10466286
Ref: c-api/exceptions c PyUnicodeDecodeError_SetReason10466441
Ref: 3c2f10466441
Ref: c-api/exceptions c PyUnicodeEncodeError_SetReason10466536
Ref: 3c3010466536
Ref: c-api/exceptions c PyUnicodeTranslateError_SetReason10466631
Ref: 3c3110466631
Node: 递归控制10466860
Ref: c-api/exceptions recursion-control10466971
Ref: 3c3210466971
Ref: c-api/exceptions c Py_EnterRecursiveCall10467261
Ref: 3c3310467261
Ref: c-api/exceptions c Py_LeaveRecursiveCall10468004
Ref: 3c3510468004
Ref: c-api/exceptions c Py_ReprEnter10468551
Ref: 3c3610468551
Ref: c-api/exceptions c Py_ReprLeave10469317
Ref: 3c3710469317
Node: 标准异常10469506
Ref: c-api/exceptions standard-exceptions10469615
Ref: 3c3810469615
Ref: c-api/exceptions standardexceptions10469615
Ref: 3c3910469615
Ref: 标准异常-Footnote-110482931
Node: 标准警告类别10482980
Ref: c-api/exceptions standard-warning-categories10483068
Ref: 3c3a10483068
Ref: c-api/exceptions standardwarningcategories10483068
Ref: 3c0510483068
Node: 工具<2>10486160
Ref: c-api/utilities doc10486276
Ref: 3c3b10486276
Ref: c-api/utilities id110486276
Ref: 3c3c10486276
Ref: c-api/utilities utilities10486276
Ref: 3c3d10486276
Node: 操作系统实用程序10486765
Ref: c-api/sys doc10486856
Ref: 3c3e10486856
Ref: c-api/sys operating-system-utilities10486856
Ref: 3c3f10486856
Ref: c-api/sys os10486856
Ref: 3c4010486856
Ref: c-api/sys c PyOS_FSPath10486911
Ref: 5d610486911
Ref: c-api/sys c Py_FdIsInteractive10487453
Ref: 3c4110487453
Ref: c-api/sys c PyOS_BeforeFork10487934
Ref: 43a10487934
Ref: c-api/sys c PyOS_AfterFork_Parent10488453
Ref: 43b10488453
Ref: c-api/sys c PyOS_AfterFork_Child10489065
Ref: 2ce10489065
Ref: c-api/sys c PyOS_AfterFork10489946
Ref: 43910489946
Ref: c-api/sys c PyOS_CheckStack10490352
Ref: 3c3410490352
Ref: c-api/sys c PyOS_getsig10490734
Ref: 3c4510490734
Ref: c-api/sys c PyOS_setsig10491041
Ref: 3c4610491041
Ref: c-api/sys c Py_DecodeLocale10491398
Ref: 44410491398
Ref: c-api/sys c Py_EncodeLocale10493427
Ref: 44510493427
Node: 系统功能10495207
Ref: c-api/sys system-functions10495319
Ref: 3c4a10495319
Ref: c-api/sys systemfunctions10495319
Ref: 3c4b10495319
Ref: c-api/sys c PySys_GetObject10495606
Ref: 3c4c10495606
Ref: c-api/sys c PySys_SetObject10495840
Ref: 3c4d10495840
Ref: c-api/sys c PySys_ResetWarnOptions10496096
Ref: 3c4e10496096
Ref: c-api/sys c PySys_AddWarnOption10496271
Ref: 4bb10496271
Ref: c-api/sys c PySys_AddWarnOptionUnicode10496500
Ref: 4ba10496500
Ref: c-api/sys c PySys_SetPath10496968
Ref: 3c4f10496968
Ref: c-api/sys c PySys_WriteStdout10497232
Ref: 3c5010497232
Ref: c-api/sys c PySys_WriteStderr10498094
Ref: 3c5110498094
Ref: c-api/sys c PySys_FormatStdout10498262
Ref: 3c5210498262
Ref: c-api/sys c PySys_FormatStderr10498530
Ref: 3c5410498530
Ref: c-api/sys c PySys_AddXOption10498724
Ref: 3c5510498724
Ref: c-api/sys c PySys_GetXOptions10499028
Ref: 3c5610499028
Ref: c-api/sys c PySys_Audit10499305
Ref: f4610499305
Ref: c-api/sys c PySys_AddAuditHook10500408
Ref: 34d110500408
Ref: 系统功能-Footnote-110501921
Node: 过程控制10501970
Ref: c-api/sys process-control10502073
Ref: 3c5810502073
Ref: c-api/sys processcontrol10502073
Ref: 3c5910502073
Ref: c-api/sys c Py_FatalError10502108
Ref: f9a10502108
Ref: c-api/sys c Py_Exit10502586
Ref: 61b10502586
Ref: c-api/sys c Py_AtExit10502933
Ref: 3c5a10502933
Node: 导入模块<2>10503581
Ref: c-api/import doc10503699
Ref: 3c5b10503699
Ref: c-api/import importing10503699
Ref: 3c5c10503699
Ref: c-api/import importing-modules10503699
Ref: 3c5d10503699
Ref: c-api/import c PyImport_ImportModule10503734
Ref: c7b10503734
Ref: c-api/import c PyImport_ImportModuleNoBlock10504761
Ref: 9c910504761
Ref: c-api/import c PyImport_ImportModuleEx10505236
Ref: b2910505236
Ref: c-api/import c PyImport_ImportModuleLevelObject10505962
Ref: 3c5e10505962
Ref: c-api/import c PyImport_ImportModuleLevel10506718
Ref: b2810506718
Ref: c-api/import c PyImport_Import10507128
Ref: d6710507128
Ref: c-api/import c PyImport_ReloadModule10507642
Ref: 3c5f10507642
Ref: c-api/import c PyImport_AddModuleObject10507902
Ref: 3c6010507902
Ref: c-api/import c PyImport_AddModule10508727
Ref: 3b2310508727
Ref: c-api/import c PyImport_ExecCodeModule10508961
Ref: 3c6110508961
Ref: c-api/import c PyImport_ExecCodeModuleEx10510735
Ref: 3c6210510735
Ref: c-api/import c PyImport_ExecCodeModuleObject10511121
Ref: 3c6410511121
Ref: c-api/import c PyImport_ExecCodeModuleWithPathnames10511553
Ref: 3c6310511553
Ref: c-api/import c PyImport_GetMagicNumber10512183
Ref: b2710512183
Ref: c-api/import c PyImport_GetMagicTag10512523
Ref: 3c6510512523
Ref: c-api/import c PyImport_GetModuleDict10512828
Ref: 3c6610512828
Ref: c-api/import c PyImport_GetModule10513064
Ref: 42910513064
Ref: c-api/import c PyImport_GetImporter10513409
Ref: 3c6710513409
Ref: c-api/import c _PyImport_Init10514069
Ref: 3c6810514069
Ref: c-api/import c PyImport_Cleanup10514170
Ref: 3c6910514170
Ref: c-api/import c _PyImport_Fini10514264
Ref: 3c6a10514264
Ref: c-api/import c PyImport_ImportFrozenModuleObject10514363
Ref: 3c6b10514363
Ref: c-api/import c PyImport_ImportFrozenModule10514958
Ref: 3c6c10514958
Ref: c-api/import c _frozen10515163
Ref: 3c6d10515163
Ref: c-api/import c PyImport_FrozenModules10515577
Ref: 230610515577
Ref: c-api/import c PyImport_AppendInittab10515897
Ref: 3b0b10515897
Ref: c-api/import c _inittab10516438
Ref: 3c6f10516438
Ref: c-api/import c PyImport_ExtendInittab10517095
Ref: 3c6e10517095
Ref: 导入模块<2>-Footnote-110517713
Node: 数据 marshal 操作支持10517762
Ref: c-api/marshal doc10517898
Ref: 3c7010517898
Ref: c-api/marshal data-marshalling-support10517898
Ref: 3c7110517898
Ref: c-api/marshal marshalling-utils10517898
Ref: 3c7210517898
Ref: c-api/marshal c PyMarshal_WriteLongToFile10518602
Ref: 3c7310518602
Ref: c-api/marshal c PyMarshal_WriteObjectToFile10518917
Ref: 3c7410518917
Ref: c-api/marshal c PyMarshal_WriteObjectToString10519138
Ref: 3c7510519138
Ref: c-api/marshal c PyMarshal_ReadLongFromFile10519458
Ref: 3c7610519458
Ref: c-api/marshal c PyMarshal_ReadShortFromFile10519800
Ref: 3c7710519800
Ref: c-api/marshal c PyMarshal_ReadObjectFromFile10520144
Ref: 3c7810520144
Ref: c-api/marshal c PyMarshal_ReadLastObjectFromFile10520488
Ref: 3c7910520488
Ref: c-api/marshal c PyMarshal_ReadObjectFromString10521211
Ref: 3c7a10521211
Node: 解析参数并构建值变量10521612
Ref: c-api/arg doc10521760
Ref: 3c7b10521760
Ref: c-api/arg arg-parsing10521760
Ref: 2d110521760
Ref: c-api/arg parsing-arguments-and-building-values10521760
Ref: 3c7c10521760
Node: 解析参数<3>10522330
Ref: c-api/arg parsing-arguments10522433
Ref: 3c7d10522433
Node: 字符串和缓存区10523069
Ref: c-api/arg strings-and-buffers10523160
Ref: 3c7e10523160
Node: 数字<2>10534754
Ref: c-api/arg numbers10534866
Ref: 3c8010534866
Node: 其他对象10537392
Ref: c-api/arg other-objects10537493
Ref: 3c8210537493
Ref: c-api/arg o-ampersand10538173
Ref: 3c8310538173
Node: API 函数10542291
Ref: c-api/arg api-functions10542374
Ref: 3c8410542374
Ref: c-api/arg c PyArg_ParseTuple10542411
Ref: 26b10542411
Ref: c-api/arg c PyArg_VaParse10542677
Ref: 3c8510542677
Ref: c-api/arg c PyArg_ParseTupleAndKeywords10542910
Ref: 5d310542910
Ref: c-api/arg c PyArg_VaParseTupleAndKeywords10543459
Ref: de210543459
Ref: c-api/arg c PyArg_ValidateKeywordArguments10543759
Ref: 3c8610543759
Ref: c-api/arg c PyArg_Parse10544051
Ref: f7510544051
Ref: c-api/arg c PyArg_UnpackTuple10544520
Ref: e4e10544520
Node: 创建变量10546247
Ref: c-api/arg building-values10546350
Ref: 3c8710546350
Ref: c-api/arg c Py_BuildValue10546389
Ref: 2cf10546389
Ref: c-api/arg c Py_VaBuildValue10553960
Ref: 3c8810553960
Node: 字符串转换与格式化10554212
Ref: c-api/conversion doc10554339
Ref: 3c8910554339
Ref: c-api/conversion string-conversion10554339
Ref: 3c8a10554339
Ref: c-api/conversion string-conversion-and-formatting10554339
Ref: 3c8b10554339
Ref: c-api/conversion c PyOS_snprintf10554455
Ref: e5110554455
Ref: c-api/conversion c PyOS_vsnprintf10554699
Ref: e5210554699
Ref: c-api/conversion c PyOS_string_to_double10556318
Ref: c2b10556318
Ref: c-api/conversion c PyOS_double_to_string10557963
Ref: 3c8c10557963
Ref: c-api/conversion c PyOS_stricmp10559445
Ref: 3c8d10559445
Ref: c-api/conversion c PyOS_strnicmp10559641
Ref: 3c8e10559641
Node: 反射10559867
Ref: c-api/reflection doc10559997
Ref: 3c8f10559997
Ref: c-api/reflection id110559997
Ref: 3c9010559997
Ref: c-api/reflection reflection10559997
Ref: 3c9110559997
Ref: c-api/reflection c PyEval_GetBuiltins10560022
Ref: 3c9210560022
Ref: c-api/reflection c PyEval_GetLocals10560237
Ref: 3c9310560237
Ref: c-api/reflection c PyEval_GetGlobals10560431
Ref: 3c9410560431
Ref: c-api/reflection c PyEval_GetFrame10560626
Ref: 3c9510560626
Ref: c-api/reflection c PyFrame_GetLineNumber10560809
Ref: cf310560809
Ref: c-api/reflection c PyEval_GetFuncName10560925
Ref: 3c9610560925
Ref: c-api/reflection c PyEval_GetFuncDesc10561113
Ref: 3c9710561113
Node: 编解码器注册与支持功能10561414
Ref: c-api/codec doc10561508
Ref: 3c9810561508
Ref: c-api/codec codec-registry10561508
Ref: 5f710561508
Ref: c-api/codec codec-registry-and-support-functions10561508
Ref: 3c9910561508
Ref: c-api/codec c PyCodec_Register10561578
Ref: 3c9a10561578
Ref: c-api/codec c PyCodec_KnownEncoding10561841
Ref: 3c9b10561841
Ref: c-api/codec c PyCodec_Encode10562037
Ref: 3c9c10562037
Ref: c-api/codec c PyCodec_Decode10562491
Ref: 3c9d10562491
Node: Codec 查找API10563038
Ref: c-api/codec codec-lookup-api10563184
Ref: 3c9e10563184
Ref: c-api/codec c PyCodec_Encoder10563490
Ref: 3c9f10563490
Ref: c-api/codec c PyCodec_Decoder10563651
Ref: 3ca010563651
Ref: c-api/codec c PyCodec_IncrementalEncoder10563812
Ref: 3ca110563812
Ref: c-api/codec c PyCodec_IncrementalDecoder10564037
Ref: 3ca210564037
Ref: c-api/codec c PyCodec_StreamReader10564262
Ref: 3ca310564262
Ref: c-api/codec c PyCodec_StreamWriter10564499
Ref: 3ca410564499
Node: 用于Unicode编码错误处理程序的注册表API10564736
Ref: c-api/codec registry-api-for-unicode-encoding-error-handlers10564882
Ref: 3ca510564882
Ref: c-api/codec c PyCodec_RegisterError10564991
Ref: 3ca610564991
Ref: c-api/codec c PyCodec_LookupError10566032
Ref: 3ca710566032
Ref: c-api/codec c PyCodec_StrictErrors10566316
Ref: 3ca810566316
Ref: c-api/codec c PyCodec_IgnoreErrors10566441
Ref: 3ca910566441
Ref: c-api/codec c PyCodec_ReplaceErrors10566588
Ref: 3caa10566588
Ref: c-api/codec c PyCodec_XMLCharRefReplaceErrors10566756
Ref: 3cab10566756
Ref: c-api/codec c PyCodec_BackslashReplaceErrors10566925
Ref: 3cac10566925
Ref: c-api/codec c PyCodec_NameReplaceErrors10567128
Ref: 7b110567128
Node: 抽象对象层10567322
Ref: c-api/abstract doc10567444
Ref: 3cad10567444
Ref: c-api/abstract abstract10567444
Ref: 3b6b10567444
Ref: c-api/abstract abstract-objects-layer10567444
Ref: 3cae10567444
Node: 对象协议10568045
Ref: c-api/object doc10568130
Ref: 3caf10568130
Ref: c-api/object object10568130
Ref: 3cb010568130
Ref: c-api/object object-protocol10568130
Ref: 3cb110568130
Ref: c-api/object c Py_NotImplemented10568165
Ref: 3cb210568165
Ref: c-api/object c Py_RETURN_NOTIMPLEMENTED10568311
Ref: 3cb310568311
Ref: c-api/object c PyObject_Print10568498
Ref: 105c10568498
Ref: c-api/object c PyObject_HasAttr10568848
Ref: 3cb410568848
Ref: c-api/object c PyObject_HasAttrString10569305
Ref: 3cb610569305
Ref: c-api/object c PyObject_GetAttr10569817
Ref: 3cb510569817
Ref: c-api/object c PyObject_GetAttrString10570110
Ref: 3b1e10570110
Ref: c-api/object c PyObject_GenericGetAttr10570418
Ref: 3cb710570418
Ref: c-api/object c PyObject_SetAttr10570955
Ref: 3cb810570955
Ref: c-api/object c PyObject_SetAttrString10571388
Ref: 3cb910571388
Ref: c-api/object c PyObject_GenericSetAttr10571832
Ref: 3cba10571832
Ref: c-api/object c PyObject_DelAttr10572380
Ref: 3cbb10572380
Ref: c-api/object c PyObject_DelAttrString10572592
Ref: 3cbc10572592
Ref: c-api/object c PyObject_GenericGetDict10572822
Ref: 3cbd10572822
Ref: c-api/object c PyObject_GenericSetDict10573068
Ref: 3cbe10573068
Ref: c-api/object c PyObject_RichCompare10573288
Ref: 3b6910573288
Ref: c-api/object c PyObject_RichCompareBool10573842
Ref: f5710573842
Ref: c-api/object c PyObject_Repr10574583
Ref: 97010574583
Ref: c-api/object c PyObject_ASCII10575003
Ref: 3cbf10575003
Ref: c-api/object c PyObject_Str10575456
Ref: 97110575456
Ref: c-api/object c PyObject_Bytes10575920
Ref: 3cc010575920
Ref: c-api/object c PyObject_IsSubclass10576326
Ref: 7a710576326
Ref: c-api/object c PyObject_IsInstance10577217
Ref: 7a610577217
Ref: c-api/object c PyCallable_Check10578096
Ref: 3cc110578096
Ref: c-api/object c PyObject_Call10578305
Ref: 3b1310578305
Ref: c-api/object c PyObject_CallObject10578940
Ref: 3b1210578940
Ref: c-api/object c PyObject_CallFunction10579393
Ref: 2d010579393
Ref: c-api/object c PyObject_CallMethod10580187
Ref: 3cc310580187
Ref: c-api/object c PyObject_CallFunctionObjArgs10581053
Ref: 3cc210581053
Ref: c-api/object c PyObject_CallMethodObjArgs10581572
Ref: fe910581572
Ref: c-api/object c _PyObject_Vectorcall10582115
Ref: 3cc410582115
Ref: c-api/object c PY_VECTORCALL_ARGUMENTS_OFFSET10583535
Ref: 3cc710583535
Ref: c-api/object c PyVectorcall_NARGS10584160
Ref: 3cc610584160
Ref: c-api/object c _PyObject_FastCallDict10584411
Ref: 3cc810584411
Ref: c-api/object c PyObject_Hash10585326
Ref: 3cc910585326
Ref: c-api/object c PyObject_HashNotImplemented10585635
Ref: d3910585635
Ref: c-api/object c PyObject_IsTrue10585945
Ref: 3cca10585945
Ref: c-api/object c PyObject_Not10586162
Ref: 3ccb10586162
Ref: c-api/object c PyObject_Type10586376
Ref: 3ccc10586376
Ref: c-api/object c PyObject_TypeCheck10586929
Ref: 3b7310586929
Ref: c-api/object c PyObject_Size10587125
Ref: 3ccd10587125
Ref: c-api/object c PyObject_Length10587178
Ref: 3cce10587178
Ref: c-api/object c PyObject_LengthHint10587421
Ref: 93010587421
Ref: c-api/object c PyObject_GetItem10587854
Ref: 3bb510587854
Ref: c-api/object c PyObject_SetItem10588090
Ref: 3bb310588090
Ref: c-api/object c PyObject_DelItem10588389
Ref: 3ccf10588389
Ref: c-api/object c PyObject_Dir10588588
Ref: 3cd010588588
Ref: c-api/object c PyObject_GetIter10589060
Ref: 3cd110589060
Ref: 对象协议-Footnote-110589448
Ref: 对象协议-Footnote-210589497
Node: 数字协议10589546
Ref: c-api/number doc10589652
Ref: 3cd210589652
Ref: c-api/number number10589652
Ref: 3cd310589652
Ref: c-api/number number-protocol10589652
Ref: 3cd410589652
Ref: c-api/number c PyNumber_Check10589687
Ref: 26c10589687
Ref: c-api/number c PyNumber_Add10589938
Ref: 3cd510589938
Ref: c-api/number c PyNumber_Subtract10590168
Ref: 3cd610590168
Ref: c-api/number c PyNumber_Multiply10590403
Ref: 3cd710590403
Ref: c-api/number c PyNumber_MatrixMultiply10590639
Ref: 7b710590639
Ref: c-api/number c PyNumber_FloorDivide10590923
Ref: 3cd810590923
Ref: c-api/number c PyNumber_TrueDivide10591169
Ref: 3cd910591169
Ref: c-api/number c PyNumber_Remainder10591565
Ref: 3cda10591565
Ref: c-api/number c PyNumber_Divmod10591805
Ref: 3cdb10591805
Ref: c-api/number c PyNumber_Power10592049
Ref: 3cdc10592049
Ref: c-api/number c PyNumber_Negative10592493
Ref: 3cdd10592493
Ref: c-api/number c PyNumber_Positive10592689
Ref: 3cde10592689
Ref: c-api/number c PyNumber_Absolute10592876
Ref: 3cdf10592876
Ref: c-api/number c PyNumber_Invert10593084
Ref: 3ce010593084
Ref: c-api/number c PyNumber_Lshift10593296
Ref: 3ce110593296
Ref: c-api/number c PyNumber_Rshift10593536
Ref: 3ce210593536
Ref: c-api/number c PyNumber_And10593777
Ref: 3ce310593777
Ref: c-api/number c PyNumber_Xor10594014
Ref: 3ce410594014
Ref: c-api/number c PyNumber_Or10594257
Ref: 3ce510594257
Ref: c-api/number c PyNumber_InPlaceAdd10594493
Ref: 3ce610594493
Ref: c-api/number c PyNumber_InPlaceSubtract10594786
Ref: 3ce710594786
Ref: c-api/number c PyNumber_InPlaceMultiply10595102
Ref: 3ce810595102
Ref: c-api/number c PyNumber_InPlaceMatrixMultiply10595423
Ref: 7b810595423
Ref: c-api/number c PyNumber_InPlaceFloorDivide10595780
Ref: 3ce910595780
Ref: c-api/number c PyNumber_InPlaceTrueDivide10596111
Ref: 3cea10596111
Ref: c-api/number c PyNumber_InPlaceRemainder10596583
Ref: 3ceb10596583
Ref: c-api/number c PyNumber_InPlacePower10596904
Ref: 3cec10596904
Ref: c-api/number c PyNumber_InPlaceLshift10597474
Ref: 3ced10597474
Ref: c-api/number c PyNumber_InPlaceRshift10597798
Ref: 3cee10597798
Ref: c-api/number c PyNumber_InPlaceAnd10598122
Ref: 3cef10598122
Ref: c-api/number c PyNumber_InPlaceXor10598429
Ref: 3cf010598429
Ref: c-api/number c PyNumber_InPlaceOr10598737
Ref: 3cf110598737
Ref: c-api/number c PyNumber_Long10599043
Ref: 26d10599043
Ref: c-api/number c PyNumber_Float10599269
Ref: 26e10599269
Ref: c-api/number c PyNumber_Index10599501
Ref: 3cf210599501
Ref: c-api/number c PyNumber_ToBase10599728
Ref: f4810599728
Ref: c-api/number c PyNumber_AsSsize_t10600222
Ref: 3cf310600222
Ref: c-api/number c PyIndex_Check10600879
Ref: 102110600879
Node: 序列协议10601108
Ref: c-api/sequence doc10601214
Ref: 3cf410601214
Ref: c-api/sequence sequence10601214
Ref: 3cf510601214
Ref: c-api/sequence sequence-protocol10601214
Ref: 3cf610601214
Ref: c-api/sequence c PySequence_Check10601249
Ref: 3cf710601249
Ref: c-api/sequence c PySequence_Size10601629
Ref: 105d10601629
Ref: c-api/sequence c PySequence_Length10601684
Ref: 3cf810601684
Ref: c-api/sequence c PySequence_Concat10601872
Ref: 3cf910601872
Ref: c-api/sequence c PySequence_Repeat10602105
Ref: 3cfa10602105
Ref: c-api/sequence c PySequence_InPlaceConcat10602354
Ref: 3cfb10602354
Ref: c-api/sequence c PySequence_InPlaceRepeat10602666
Ref: 3cfc10602666
Ref: c-api/sequence c PySequence_GetItem10603047
Ref: 105e10603047
Ref: c-api/sequence c PySequence_GetSlice10603272
Ref: 3cfd10603272
Ref: c-api/sequence c PySequence_SetItem10603544
Ref: 105f10603544
Ref: c-api/sequence c PySequence_DelItem10604005
Ref: 106010604005
Ref: c-api/sequence c PySequence_SetSlice10604197
Ref: 3cfe10604197
Ref: c-api/sequence c PySequence_DelSlice10604440
Ref: 3cff10604440
Ref: c-api/sequence c PySequence_Count10604679
Ref: 3d0010604679
Ref: c-api/sequence c PySequence_Contains10604948
Ref: 3d0110604948
Ref: c-api/sequence c PySequence_Index10605237
Ref: 3d0210605237
Ref: c-api/sequence c PySequence_List10605456
Ref: 3d0310605456
Ref: c-api/sequence c PySequence_Tuple10605756
Ref: 3d0410605756
Ref: c-api/sequence c PySequence_Fast10606140
Ref: 3d0510606140
Ref: c-api/sequence c PySequence_Fast_GET_SIZE10606829
Ref: 3d0710606829
Ref: c-api/sequence c PySequence_Fast_GET_ITEM10607225
Ref: 3d0810607225
Ref: c-api/sequence c PySequence_Fast_ITEMS10607516
Ref: 3d0910607516
Ref: c-api/sequence c PySequence_ITEM10607875
Ref: 3d0a10607875
Node: 映射协议10608235
Ref: c-api/mapping doc10608344
Ref: 3d0b10608344
Ref: c-api/mapping mapping10608344
Ref: 3d0c10608344
Ref: c-api/mapping mapping-protocol10608344
Ref: 3d0d10608344
Ref: c-api/mapping c PyMapping_Check10608492
Ref: 3d0e10608492
Ref: c-api/mapping c PyMapping_Size10608834
Ref: 106110608834
Ref: c-api/mapping c PyMapping_Length10608888
Ref: 3d0f10608888
Ref: c-api/mapping c PyMapping_GetItemString10609075
Ref: 3d1010609075
Ref: c-api/mapping c PyMapping_SetItemString10609399
Ref: 3d1110609399
Ref: c-api/mapping c PyMapping_DelItem10609738
Ref: 3d1210609738
Ref: c-api/mapping c PyMapping_DelItemString10610003
Ref: 3d1310610003
Ref: c-api/mapping c PyMapping_HasKey10610215
Ref: 3d1410610215
Ref: c-api/mapping c PyMapping_HasKeyString10610620
Ref: 3d1510610620
Ref: c-api/mapping c PyMapping_Keys10611040
Ref: 43410611040
Ref: c-api/mapping c PyMapping_Values10611305
Ref: 43510611305
Ref: c-api/mapping c PyMapping_Items10611572
Ref: 43610611572
Node: 迭代器协议10611893
Ref: c-api/iter doc10612002
Ref: 3d1610612002
Ref: c-api/iter iterator10612002
Ref: 3d1710612002
Ref: c-api/iter iterator-protocol10612002
Ref: 3d1810612002
Ref: c-api/iter c PyIter_Check10612071
Ref: 102010612071
Ref: c-api/iter c PyIter_Next10612188
Ref: 3d1910612188
Node: 缓冲协议10613097
Ref: c-api/buffer doc10613209
Ref: 3d1a10613209
Ref: c-api/buffer buffer-protocol10613209
Ref: 3d1b10613209
Ref: c-api/buffer bufferobjects10613209
Ref: 15f710613209
Node: 缓冲区结构10615563
Ref: c-api/buffer buffer-structure10615660
Ref: 3d1d10615660
Ref: c-api/buffer id110615660
Ref: 3d1e10615660
Ref: c-api/buffer c Py_buffer10616651
Ref: b2310616651
Ref: c-api/buffer c Py_buffer buf10616676
Ref: 3d2010616676
Ref: c-api/buffer c Py_buffer obj10617057
Ref: 3d2210617057
Ref: c-api/buffer c Py_buffer len10617565
Ref: 3d2510617565
Ref: c-api/buffer c Py_buffer readonly10618108
Ref: 3d2810618108
Ref: c-api/buffer c Py_buffer itemsize10618258
Ref: 3d2910618258
Ref: c-api/buffer c Py_buffer format10619125
Ref: 3d2a10619125
Ref: c-api/buffer c Py_buffer ndim10619417
Ref: 3d2d10619417
Ref: c-api/buffer c Py_buffer shape10619933
Ref: 3d2c10619933
Ref: c-api/buffer c Py_buffer strides10620453
Ref: 3d2110620453
Ref: c-api/buffer c Py_buffer suboffsets10620950
Ref: 3d2e10620950
Ref: c-api/buffer c Py_buffer internal10621817
Ref: 3d3010621817
Node: 缓冲区请求的类型10622192
Ref: c-api/buffer buffer-request-types10622310
Ref: 3d3110622310
Ref: c-api/buffer id210622310
Ref: 3d3210622310
Node: 与请求无关的字段10622861
Ref: c-api/buffer request-independent-fields10622970
Ref: 3d3310622970
Node: 只读，格式10623211
Ref: c-api/buffer readonly-format10623359
Ref: 3d3410623359
Ref: c-api/buffer c PyBUF_WRITABLE10623403
Ref: 3d2710623403
Ref: c-api/buffer c PyBUF_FORMAT10623734
Ref: 3d2b10623734
Node: 形状，步幅，子偏移量10624327
Ref: c-api/buffer shape-strides-suboffsets10624469
Ref: 3d3510624469
Ref: c-api/buffer c PyBUF_INDIRECT10624971
Ref: 3d3610624971
Ref: c-api/buffer c PyBUF_STRIDES10625174
Ref: 3d3710625174
Ref: c-api/buffer c PyBUF_ND10625359
Ref: 3d3810625359
Ref: c-api/buffer c PyBUF_SIMPLE10625552
Ref: 3d2610625552
Node: 连续性的请求10625657
Ref: c-api/buffer contiguity-requests10625796
Ref: 3d3910625796
Ref: c-api/buffer c PyBUF_C_CONTIGUOUS10626390
Ref: 3d3a10626390
Ref: c-api/buffer c PyBUF_F_CONTIGUOUS10626646
Ref: 3d3b10626646
Ref: c-api/buffer c PyBUF_ANY_CONTIGUOUS10626904
Ref: 3d3c10626904
Node: 复合请求10627306
Ref: c-api/buffer compound-requests10627406
Ref: 3d3d10627406
Ref: c-api/buffer c PyBUF_FULL10628240
Ref: 3d3f10628240
Ref: c-api/buffer c PyBUF_FULL_RO10628579
Ref: 3d4010628579
Ref: c-api/buffer c PyBUF_RECORDS10628916
Ref: 3d4110628916
Ref: c-api/buffer c PyBUF_RECORDS_RO10629249
Ref: 3d4210629249
Ref: c-api/buffer c PyBUF_STRIDED10629577
Ref: 3d4310629577
Ref: c-api/buffer c PyBUF_STRIDED_RO10629911
Ref: 3d4410629911
Ref: c-api/buffer c PyBUF_CONTIG10630239
Ref: 3d4510630239
Ref: c-api/buffer c PyBUF_CONTIG_RO10630572
Ref: 3d4610630572
Node: 复杂数组10630770
Ref: c-api/buffer complex-arrays10630894
Ref: 3d2f10630894
Node: NumPy-风格：形状和步幅10631026
Ref: c-api/buffer numpy-style-shape-and-strides10631157
Ref: 3d4710631157
Node: PIL-风格：形状，步幅和子偏移量10633029
Ref: c-api/buffer pil-style-shape-strides-and-suboffsets10633160
Ref: 3d4810633160
Node: 缓冲区相关函数10634324
Ref: c-api/buffer buffer-related-functions10634415
Ref: 3d4910634415
Ref: c-api/buffer c PyObject_CheckBuffer10634471
Ref: 3d4a10634471
Ref: c-api/buffer c PyObject_GetBuffer10634754
Ref: d2d10634754
Ref: c-api/buffer c PyBuffer_Release10635700
Ref: d5c10635700
Ref: c-api/buffer c PyBuffer_SizeFromFormat10636079
Ref: 3d4b10636079
Ref: c-api/buffer c PyBuffer_IsContiguous10636259
Ref: 3d3e10636259
Ref: c-api/buffer c PyBuffer_GetPointer10636596
Ref: 3d4c10636596
Ref: c-api/buffer c PyBuffer_FromContiguous10636833
Ref: 3d4d10636833
Ref: c-api/buffer c PyBuffer_ToContiguous10637139
Ref: 3d4e10637139
Ref: c-api/buffer c PyBuffer_FillContiguousStrides10637555
Ref: 3d4f10637555
Ref: c-api/buffer c PyBuffer_FillInfo10637941
Ref: 3d2410637941
Node: 旧缓冲协议10638915
Ref: c-api/objbuffer doc10639003
Ref: 3d5010639003
Ref: c-api/objbuffer old-buffer-protocol10639003
Ref: 3d5110639003
Ref: c-api/objbuffer c PyObject_AsCharBuffer10639685
Ref: 3d5210639685
Ref: c-api/objbuffer c PyObject_AsReadBuffer10640122
Ref: 3d5310640122
Ref: c-api/objbuffer c PyObject_CheckReadBuffer10640546
Ref: 3d5410640546
Ref: c-api/objbuffer c PyObject_AsWriteBuffer10640947
Ref: 3d5510640947
Node: 具体的对象层10641335
Ref: c-api/concrete doc10641475
Ref: 3d5610641475
Ref: c-api/concrete concrete10641475
Ref: 3d5710641475
Ref: c-api/concrete concrete-objects-layer10641475
Ref: 3d5810641475
Node: 基本对象10642321
Ref: c-api/concrete fundamental10642409
Ref: 3d5a10642409
Ref: c-api/concrete fundamental-objects10642409
Ref: 3d5b10642409
Node: 类型对象<2>10642568
Ref: c-api/type doc10642652
Ref: 3d5c10642652
Ref: c-api/type type-objects10642652
Ref: 3d5d10642652
Ref: c-api/type typeobjects10642652
Ref: 3d5e10642652
Ref: c-api/type c PyTypeObject10642691
Ref: 2d710642691
Ref: c-api/type c PyType_Type10642775
Ref: 3d5f10642775
Ref: c-api/type c PyType_Check10642928
Ref: 3d6010642928
Ref: c-api/type c PyType_CheckExact10643127
Ref: 3d6110643127
Ref: c-api/type c PyType_ClearCache10643325
Ref: 3d6210643325
Ref: c-api/type c PyType_GetFlags10643446
Ref: 3d6310643446
Ref: c-api/type c PyType_Modified10643931
Ref: 3d6510643931
Ref: c-api/type c PyType_HasFeature10644186
Ref: 3d6610644186
Ref: c-api/type c PyType_IS_GC10644375
Ref: 3d6710644375
Ref: c-api/type c PyType_IsSubtype10644565
Ref: 3d6810644565
Ref: c-api/type c PyType_GenericAlloc10644923
Ref: 27110644923
Ref: c-api/type c PyType_GenericNew10645265
Ref: 3b4010645265
Ref: c-api/type c PyType_Ready10645555
Ref: 3b4510645555
Ref: c-api/type c PyType_GetSlot10645892
Ref: 92c10645892
Node: Creating Heap-Allocated Types10646465
Ref: c-api/type creating-heap-allocated-types10646546
Ref: 3d6910646546
Ref: c-api/type c PyType_FromSpecWithBases10646703
Ref: 3d6b10646703
Ref: c-api/type c PyType_FromSpec10647358
Ref: 2d210647358
Ref: c-api/type c PyType_Spec10647519
Ref: 3d6d10647519
Ref: c-api/type c PyType_Spec PyType_Spec name10647592
Ref: 3d6e10647592
Ref: c-api/type c PyType_Spec PyType_Spec basicsize10647726
Ref: 3d6f10647726
Ref: c-api/type c PyType_Spec PyType_Spec itemsize10647772
Ref: 3d7010647772
Ref: c-api/type c PyType_Spec PyType_Spec flags10647972
Ref: 3d7110647972
Ref: c-api/type c PyType_Spec PyType_Spec slots10648218
Ref: 3d7210648218
Ref: c-api/type c PyType_Slot10648391
Ref: 3d7310648391
Ref: c-api/type c PyType_Slot PyType_Slot slot10648524
Ref: 3d7410648524
Ref: c-api/type c PyType_Slot PyType_Slot pfunc10649885
Ref: 3d7f10649885
Node: None 对象10650064
Ref: c-api/none doc10650148
Ref: 3d8010650148
Ref: c-api/none noneobject10650148
Ref: 3d8110650148
Ref: c-api/none the-none-object10650148
Ref: 3d8210650148
Ref: c-api/none c Py_None10650450
Ref: 3b0710650450
Ref: c-api/none c Py_RETURN_NONE10650627
Ref: dde10650627
Node: 数值对象10650794
Ref: c-api/concrete numeric-objects10650903
Ref: 3d8310650903
Ref: c-api/concrete numericobjects10650903
Ref: 3d8410650903
Node: 整数型对象10651022
Ref: c-api/long doc10651107
Ref: 3d8510651107
Ref: c-api/long integer-objects10651107
Ref: 3d8610651107
Ref: c-api/long longobjects10651107
Ref: 3d8710651107
Ref: c-api/long c PyLongObject10651391
Ref: 3d8810651391
Ref: c-api/long c PyLong_Type10651489
Ref: 3d8910651489
Ref: c-api/long c PyLong_Check10651659
Ref: 3d8a10651659
Ref: c-api/long c PyLong_CheckExact10651820
Ref: 3d8b10651820
Ref: c-api/long c PyLong_FromLong10651990
Ref: 3b0410651990
Ref: c-api/long c PyLong_FromUnsignedLong10652535
Ref: 3d8c10652535
Ref: c-api/long c PyLong_FromSsize_t10652761
Ref: 3d8d10652761
Ref: c-api/long c PyLong_FromSize_t10652985
Ref: 3d8e10652985
Ref: c-api/long c PyLong_FromLongLong10653194
Ref: 3d8f10653194
Ref: c-api/long c PyLong_FromUnsignedLongLong10653405
Ref: 3d9010653405
Ref: c-api/long c PyLong_FromDouble10653643
Ref: 3d9110653643
Ref: c-api/long c PyLong_FromString10653856
Ref: 3d9210653856
Ref: c-api/long c PyLong_FromUnicode10654672
Ref: 3d9310654672
Ref: c-api/long c PyLong_FromUnicodeObject10655055
Ref: 3d9410655055
Ref: c-api/long c PyLong_FromVoidPtr10655269
Ref: 3d9510655269
Ref: c-api/long c PyLong_AsLong10655475
Ref: 26a10655475
Ref: c-api/long c PyLong_AsLongAndOverflow10656113
Ref: c0510656113
Ref: c-api/long c PyLong_AsLongLong10656980
Ref: 3d9710656980
Ref: c-api/long c PyLong_AsLongLongAndOverflow10657612
Ref: c0410657612
Ref: c-api/long c PyLong_AsSsize_t10658536
Ref: 3d9810658536
Ref: c-api/long c PyLong_AsUnsignedLong10658925
Ref: 3d9910658925
Ref: c-api/long c PyLong_AsSize_t10659340
Ref: 3d9a10659340
Ref: c-api/long c PyLong_AsUnsignedLongLong10659721
Ref: c2a10659721
Ref: c-api/long c PyLong_AsUnsignedLongMask10660283
Ref: 3d9b10660283
Ref: c-api/long c PyLong_AsUnsignedLongLongMask10661002
Ref: fc910661002
Ref: c-api/long c PyLong_AsDouble10661759
Ref: 3d9c10661759
Ref: c-api/long c PyLong_AsVoidPtr10662134
Ref: 3d9610662134
Node: 布尔对象10662563
Ref: c-api/bool doc10662672
Ref: 3d9d10662672
Ref: c-api/bool boolean-objects10662672
Ref: 3d9e10662672
Ref: c-api/bool boolobjects10662672
Ref: 3d9f10662672
Ref: c-api/bool c PyBool_Check10662920
Ref: 3da010662920
Ref: c-api/bool c Py_False10663031
Ref: 3da110663031
Ref: c-api/bool c Py_True10663209
Ref: 3da210663209
Ref: c-api/bool c Py_RETURN_FALSE10663385
Ref: de010663385
Ref: c-api/bool c Py_RETURN_TRUE10663490
Ref: ddf10663490
Ref: c-api/bool c PyBool_FromLong10663593
Ref: 3da310663593
Node: 浮点数对象10663775
Ref: c-api/float doc10663881
Ref: 3da410663881
Ref: c-api/float floating-point-objects10663881
Ref: 3da510663881
Ref: c-api/float floatobjects10663881
Ref: 3da610663881
Ref: c-api/float c PyFloatObject10663925
Ref: 3da710663925
Ref: c-api/float c PyFloat_Type10664044
Ref: 3da810664044
Ref: c-api/float c PyFloat_Check10664249
Ref: 3da910664249
Ref: c-api/float c PyFloat_CheckExact10664441
Ref: 3daa10664441
Ref: c-api/float c PyFloat_FromString10664638
Ref: 3dab10664638
Ref: c-api/float c PyFloat_FromDouble10664839
Ref: 3dac10664839
Ref: c-api/float c PyFloat_AsDouble10665025
Ref: 26f10665025
Ref: c-api/float c PyFloat_AS_DOUBLE10665616
Ref: 3dad10665616
Ref: c-api/float c PyFloat_GetInfo10665764
Ref: d5f10665764
Ref: c-api/float c PyFloat_GetMax10666018
Ref: d5d10666018
Ref: c-api/float c PyFloat_GetMin10666137
Ref: d5e10666137
Ref: c-api/float c PyFloat_ClearFreeList10666259
Ref: 3dae10666259
Node: 复数对象10666374
Ref: c-api/complex doc10666459
Ref: 3daf10666459
Ref: c-api/complex complex-number-objects10666459
Ref: 3db010666459
Ref: c-api/complex complexobjects10666459
Ref: 3db110666459
Node: 表示复数的C结构体10666784
Ref: c-api/complex complex-numbers-as-c-structures10666894
Ref: 3db210666894
Ref: c-api/complex c Py_complex10667120
Ref: 3c8110667120
Ref: c-api/complex c _Py_c_sum10667450
Ref: 3db310667450
Ref: c-api/complex c _Py_c_diff10667602
Ref: 3db410667602
Ref: c-api/complex c _Py_c_neg10667755
Ref: 3db510667755
Ref: c-api/complex c _Py_c_prod10667900
Ref: 3db610667900
Ref: c-api/complex c _Py_c_quot10668056
Ref: 3db710668056
Ref: c-api/complex c _Py_c_pow10668318
Ref: 3db810668318
Node: 表示复数的Python对象10668591
Ref: c-api/complex complex-numbers-as-python-objects10668701
Ref: 3db910668701
Ref: c-api/complex c PyComplexObject10668767
Ref: 3dba10668767
Ref: c-api/complex c PyComplex_Type10668887
Ref: 3dbb10668887
Ref: c-api/complex c PyComplex_Check10669089
Ref: 3dbc10669089
Ref: c-api/complex c PyComplex_CheckExact10669287
Ref: 3dbd10669287
Ref: c-api/complex c PyComplex_FromCComplex10669490
Ref: 3dbe10669490
Ref: c-api/complex c PyComplex_FromDoubles10669679
Ref: 3dbf10669679
Ref: c-api/complex c PyComplex_RealAsDouble10669885
Ref: 3dc010669885
Ref: c-api/complex c PyComplex_ImagAsDouble10670000
Ref: 3dc110670000
Ref: c-api/complex c PyComplex_AsCComplex10670115
Ref: d6010670115
Node: 序列对象10670736
Ref: c-api/concrete sequence-objects10670845
Ref: 3dc210670845
Ref: c-api/concrete sequenceobjects10670845
Ref: 3dc310670845
Node: bytes 对象<2>10671157
Ref: c-api/bytes doc10671248
Ref: 3dc410671248
Ref: c-api/bytes bytes-objects10671248
Ref: 3dc510671248
Ref: c-api/bytes bytesobjects10671248
Ref: 3dc610671248
Ref: c-api/bytes c PyBytesObject10671418
Ref: d2610671418
Ref: c-api/bytes c PyBytes_Type10671529
Ref: 3dc710671529
Ref: c-api/bytes c PyBytes_Check10671714
Ref: d2710671714
Ref: c-api/bytes c PyBytes_CheckExact10671856
Ref: 3dc810671856
Ref: c-api/bytes c PyBytes_FromString10672009
Ref: 3dc910672009
Ref: c-api/bytes c PyBytes_FromStringAndSize10672280
Ref: d2810672280
Ref: c-api/bytes c PyBytes_FromFormat10672617
Ref: 101b10672617
Ref: c-api/bytes c PyBytes_FromFormatV10676050
Ref: 3dca10676050
Ref: c-api/bytes c PyBytes_FromObject10676266
Ref: 3dcb10676266
Ref: c-api/bytes c PyBytes_Size10676421
Ref: 3dcc10676421
Ref: c-api/bytes c PyBytes_GET_SIZE10676523
Ref: 3dcd10676523
Ref: c-api/bytes c PyBytes_AsString10676655
Ref: 3dce10676655
Ref: c-api/bytes c PyBytes_AS_STRING10677239
Ref: 3dcf10677239
Ref: c-api/bytes c PyBytes_AsStringAndSize10677376
Ref: 3dd010677376
Ref: c-api/bytes c PyBytes_Concat10678338
Ref: 3dd110678338
Ref: c-api/bytes c PyBytes_ConcatAndDel10678757
Ref: 3dd210678757
Ref: c-api/bytes c _PyBytes_Resize10679008
Ref: 105a10679008
Ref: bytes 对象<2>-Footnote-110679880
Ref: bytes 对象<2>-Footnote-210680006
Ref: bytes 对象<2>-Footnote-310680132
Ref: bytes 对象<2>-Footnote-410680258
Ref: bytes 对象<2>-Footnote-510680384
Ref: bytes 对象<2>-Footnote-610680510
Ref: bytes 对象<2>-Footnote-710680636
Ref: bytes 对象<2>-Footnote-810680762
Node: 字节数组对象10680888
Ref: c-api/bytearray doc10681019
Ref: 3dd310681019
Ref: c-api/bytearray byte-array-objects10681019
Ref: 3dd410681019
Ref: c-api/bytearray bytearrayobjects10681019
Ref: 3dd510681019
Ref: c-api/bytearray c PyByteArrayObject10681068
Ref: 3dd610681068
Ref: c-api/bytearray c PyByteArray_Type10681189
Ref: 3dd710681189
Node: 类型检查宏10681442
Ref: c-api/bytearray type-check-macros10681538
Ref: 3dd810681538
Ref: c-api/bytearray c PyByteArray_Check10681582
Ref: 3dd910681582
Ref: c-api/bytearray c PyByteArray_CheckExact10681756
Ref: 3dda10681756
Node: 直接 API 函数10681938
Ref: c-api/bytearray direct-api-functions10682046
Ref: 3ddb10682046
Ref: c-api/bytearray c PyByteArray_FromObject10682095
Ref: d2910682095
Ref: c-api/bytearray c PyByteArray_FromStringAndSize10682305
Ref: d2a10682305
Ref: c-api/bytearray c PyByteArray_Concat10682556
Ref: 3ddc10682556
Ref: c-api/bytearray c PyByteArray_Size10682752
Ref: 3ddd10682752
Ref: c-api/bytearray c PyByteArray_AsString10682885
Ref: 3dde10682885
Ref: c-api/bytearray c PyByteArray_Resize10683102
Ref: 3ddf10683102
Node: 宏10683246
Ref: c-api/bytearray macros10683330
Ref: 3de010683330
Ref: c-api/bytearray c PyByteArray_AS_STRING10683422
Ref: 3de110683422
Ref: c-api/bytearray c PyByteArray_GET_SIZE10683553
Ref: 3de210683553
Node: Unicode对象和编码解码器10683684
Ref: c-api/unicode doc10683812
Ref: b2410683812
Ref: c-api/unicode unicode-objects-and-codecs10683812
Ref: 3de310683812
Ref: c-api/unicode unicodeobjects10683812
Ref: 3de410683812
Node: Unicode对象10683964
Ref: c-api/unicode unicode-objects10684069
Ref: 3de510684069
Ref: Unicode对象-Footnote-110685676
Node: Unicode类型10685725
Ref: c-api/unicode unicode-type10685816
Ref: 3de610685816
Ref: c-api/unicode c Py_UCS410685948
Ref: adb10685948
Ref: c-api/unicode c Py_UCS210685970
Ref: ada10685970
Ref: c-api/unicode c Py_UCS110685992
Ref: ad910685992
Ref: c-api/unicode c Py_UNICODE10686261
Ref: af610686261
Ref: c-api/unicode c PyASCIIObject10686592
Ref: adc10686592
Ref: c-api/unicode c PyCompactUnicodeObject10686620
Ref: add10686620
Ref: c-api/unicode c PyUnicodeObject10686657
Ref: 3de710686657
Ref: c-api/unicode c PyUnicode_Type10686966
Ref: 3de810686966
Ref: c-api/unicode c PyUnicode_Check10687274
Ref: 3de910687274
Ref: c-api/unicode c PyUnicode_CheckExact10687421
Ref: 3dea10687421
Ref: c-api/unicode c PyUnicode_READY10687571
Ref: ade10687571
Ref: c-api/unicode c PyUnicode_GET_LENGTH10688081
Ref: ad410688081
Ref: c-api/unicode c PyUnicode_1BYTE_DATA10688320
Ref: ae310688320
Ref: c-api/unicode c PyUnicode_2BYTE_DATA10688378
Ref: ae410688378
Ref: c-api/unicode c PyUnicode_4BYTE_DATA10688436
Ref: ae510688436
Ref: c-api/unicode c PyUnicode_WCHAR_KIND10688897
Ref: ae710688897
Ref: c-api/unicode c PyUnicode_1BYTE_KIND10688929
Ref: ae810688929
Ref: c-api/unicode c PyUnicode_2BYTE_KIND10688961
Ref: ae910688961
Ref: c-api/unicode c PyUnicode_4BYTE_KIND10688993
Ref: aea10688993
Ref: c-api/unicode c PyUnicode_KIND10689230
Ref: ae610689230
Ref: c-api/unicode c PyUnicode_DATA10689546
Ref: ae210689546
Ref: c-api/unicode c PyUnicode_WRITE10689761
Ref: aed10689761
Ref: c-api/unicode c PyUnicode_READ10690324
Ref: aeb10690324
Ref: c-api/unicode c PyUnicode_READ_CHAR10690600
Ref: aec10690600
Ref: c-api/unicode c PyUnicode_MAX_CHAR_VALUE10690904
Ref: aee10690904
Ref: c-api/unicode c PyUnicode_ClearFreeList10691212
Ref: 3deb10691212
Ref: c-api/unicode c PyUnicode_GET_SIZE10691317
Ref: afd10691317
Ref: c-api/unicode c PyUnicode_GET_DATA_SIZE10691743
Ref: aff10691743
Ref: c-api/unicode c PyUnicode_AS_UNICODE10692125
Ref: af910692125
Ref: c-api/unicode c PyUnicode_AS_DATA10692186
Ref: afc10692186
Node: Unicode字符属性10693250
Ref: c-api/unicode unicode-character-properties10693388
Ref: 3dec10693388
Ref: c-api/unicode c Py_UNICODE_ISSPACE10693630
Ref: ed410693630
Ref: c-api/unicode c Py_UNICODE_ISLOWER10693774
Ref: 3ded10693774
Ref: c-api/unicode c Py_UNICODE_ISUPPER10693917
Ref: 3dee10693917
Ref: c-api/unicode c Py_UNICODE_ISTITLE10694061
Ref: 3def10694061
Ref: c-api/unicode c Py_UNICODE_ISLINEBREAK10694204
Ref: 3df010694204
Ref: c-api/unicode c Py_UNICODE_ISDECIMAL10694351
Ref: 3df110694351
Ref: c-api/unicode c Py_UNICODE_ISDIGIT10694489
Ref: 3df210694489
Ref: c-api/unicode c Py_UNICODE_ISNUMERIC10694623
Ref: 3df310694623
Ref: c-api/unicode c Py_UNICODE_ISALPHA10694761
Ref: 3df410694761
Ref: c-api/unicode c Py_UNICODE_ISALNUM10694906
Ref: 3df510694906
Ref: c-api/unicode c Py_UNICODE_ISPRINTABLE10695053
Ref: 3df610695053
Ref: c-api/unicode c Py_UNICODE_TOLOWER10695714
Ref: 3df710695714
Ref: c-api/unicode c Py_UNICODE_TOUPPER10695900
Ref: 3df810695900
Ref: c-api/unicode c Py_UNICODE_TOTITLE10696086
Ref: 3df910696086
Ref: c-api/unicode c Py_UNICODE_TODECIMAL10696272
Ref: 3dfa10696272
Ref: c-api/unicode c Py_UNICODE_TODIGIT10696491
Ref: 3dfb10696491
Ref: c-api/unicode c Py_UNICODE_TONUMERIC10696704
Ref: 3dfc10696704
Ref: c-api/unicode c Py_UNICODE_IS_SURROGATE10696955
Ref: 3dfd10696955
Ref: c-api/unicode c Py_UNICODE_IS_HIGH_SURROGATE10697063
Ref: 3dfe10697063
Ref: c-api/unicode c Py_UNICODE_IS_LOW_SURROGATE10697181
Ref: 3dff10697181
Ref: c-api/unicode c Py_UNICODE_JOIN_SURROGATES10697297
Ref: 3e0010697297
Node: Creating and accessing Unicode strings10697520
Ref: c-api/unicode creating-and-accessing-unicode-strings10697671
Ref: 3e0110697671
Ref: c-api/unicode c PyUnicode_New10697855
Ref: ad510697855
Ref: c-api/unicode c PyUnicode_FromKindAndData10698344
Ref: adf10698344
Ref: c-api/unicode c PyUnicode_FromStringAndSize10698799
Ref: 3e0210698799
Ref: c-api/unicode c PyUnicode_FromString10699466
Ref: 3b9310699466
Ref: c-api/unicode c PyUnicode_FromFormat10699648
Ref: 7d410699648
Ref: c-api/unicode c PyUnicode_FromFormatV10706605
Ref: 3c5310706605
Ref: c-api/unicode c PyUnicode_FromEncodedObject10706837
Ref: 3e0310706837
Ref: c-api/unicode c PyUnicode_GetLength10707597
Ref: ad310707597
Ref: c-api/unicode c PyUnicode_CopyCharacters10707750
Ref: ad210707750
Ref: c-api/unicode c PyUnicode_Fill10708223
Ref: b0310708223
Ref: c-api/unicode c PyUnicode_WriteChar10708698
Ref: ad810708698
Ref: c-api/unicode c PyUnicode_ReadChar10709257
Ref: ad710709257
Ref: c-api/unicode c PyUnicode_Substring10709579
Ref: ad610709579
Ref: c-api/unicode c PyUnicode_AsUCS410709898
Ref: ae010709898
Ref: c-api/unicode c PyUnicode_AsUCS4Copy10710325
Ref: ae110710325
Ref: Creating and accessing Unicode strings-Footnote-110710701
Ref: Creating and accessing Unicode strings-Footnote-210710854
Ref: Creating and accessing Unicode strings-Footnote-310711007
Ref: Creating and accessing Unicode strings-Footnote-410711160
Ref: Creating and accessing Unicode strings-Footnote-510711313
Ref: Creating and accessing Unicode strings-Footnote-610711466
Ref: Creating and accessing Unicode strings-Footnote-710711619
Ref: Creating and accessing Unicode strings-Footnote-810711772
Ref: Creating and accessing Unicode strings-Footnote-910711925
Ref: Creating and accessing Unicode strings-Footnote-1010712078
Ref: Creating and accessing Unicode strings-Footnote-1110712232
Ref: Creating and accessing Unicode strings-Footnote-1210712386
Ref: Creating and accessing Unicode strings-Footnote-1310712540
Node: Deprecated Py_UNICODE APIs10712694
Ref: c-api/unicode deprecated-py-unicode-apis10712841
Ref: 3e0510712841
Ref: c-api/unicode c PyUnicode_FromUnicode10713219
Ref: af710713219
Ref: c-api/unicode c PyUnicode_AsUnicode10714263
Ref: afa10714263
Ref: c-api/unicode c PyUnicode_TransformDecimalToASCII10715158
Ref: b1710715158
Ref: c-api/unicode c PyUnicode_AsUnicodeAndSize10715709
Ref: afb10715709
Ref: c-api/unicode c PyUnicode_AsUnicodeCopy10716441
Ref: b0010716441
Ref: c-api/unicode c PyUnicode_GetSize10717084
Ref: afe10717084
Ref: c-api/unicode c PyUnicode_FromObject10717468
Ref: 3e0610717468
Ref: Deprecated Py_UNICODE APIs-Footnote-110717896
Node: Locale Encoding10717945
Ref: c-api/unicode locale-encoding10718074
Ref: 3e0710718074
Ref: c-api/unicode c PyUnicode_DecodeLocaleAndSize10718208
Ref: 44610718208
Ref: c-api/unicode c PyUnicode_DecodeLocale10719372
Ref: 3e0810719372
Ref: c-api/unicode c PyUnicode_EncodeLocale10719646
Ref: 44710719646
Ref: Locale Encoding-Footnote-110720825
Ref: Locale Encoding-Footnote-210720874
Node: File System Encoding10720923
Ref: c-api/unicode file-system-encoding10721041
Ref: 3e0910721041
Ref: c-api/unicode c PyUnicode_FSConverter10721523
Ref: 5d710721523
Ref: c-api/unicode c PyUnicode_FSDecoder10722234
Ref: 5d810722234
Ref: c-api/unicode c PyUnicode_DecodeFSDefaultAndSize10722792
Ref: 3c4910722792
Ref: c-api/unicode c PyUnicode_DecodeFSDefault10723566
Ref: 3e0a10723566
Ref: c-api/unicode c PyUnicode_EncodeFSDefault10724092
Ref: 105b10724092
Ref: File System Encoding-Footnote-110725006
Ref: File System Encoding-Footnote-210725055
Node: wchar_t Support10725104
Ref: c-api/unicode wchar-t-support10725198
Ref: 3e0b10725198
Ref: c-api/unicode c PyUnicode_FromWideChar10725304
Ref: af810725304
Ref: c-api/unicode c PyUnicode_AsWideChar10725666
Ref: 106210725666
Ref: c-api/unicode c PyUnicode_AsWideCharString10726471
Ref: 44010726471
Node: Built-in Codecs10727536
Ref: c-api/unicode built-in-codecs10727676
Ref: 3e0c10727676
Ref: c-api/unicode builtincodecs10727676
Ref: 3e0410727676
Node: Generic Codecs10729100
Ref: c-api/unicode generic-codecs10729187
Ref: 3e0d10729187
Ref: c-api/unicode c PyUnicode_Decode10729271
Ref: f8310729271
Ref: c-api/unicode c PyUnicode_AsEncodedString10729790
Ref: 3e0e10729790
Ref: c-api/unicode c PyUnicode_Encode10730299
Ref: b0410730299
Node: UTF-8 Codecs10731039
Ref: c-api/unicode utf-8-codecs10731148
Ref: 3e0f10731148
Ref: c-api/unicode c PyUnicode_DecodeUTF810731226
Ref: 3e1010731226
Ref: c-api/unicode c PyUnicode_DecodeUTF8Stateful10731524
Ref: 3e1110731524
Ref: c-api/unicode c PyUnicode_AsUTF8String10732020
Ref: b0710732020
Ref: c-api/unicode c PyUnicode_AsUTF8AndSize10732306
Ref: 43210732306
Ref: c-api/unicode c PyUnicode_AsUTF810733230
Ref: 43310733230
Ref: c-api/unicode c PyUnicode_EncodeUTF810733495
Ref: b0610733495
Node: UTF-32 Codecs10734115
Ref: c-api/unicode utf-32-codecs10734223
Ref: 3e1210734223
Ref: c-api/unicode c PyUnicode_DecodeUTF3210734304
Ref: 3e1310734304
Ref: c-api/unicode c PyUnicode_DecodeUTF32Stateful10735448
Ref: 3e1410735448
Ref: c-api/unicode c PyUnicode_AsUTF32String10736068
Ref: 3e1510736068
Ref: c-api/unicode c PyUnicode_EncodeUTF3210736397
Ref: b0810736397
Node: UTF-16 Codecs10737443
Ref: c-api/unicode utf-16-codecs10737551
Ref: 3e1610737551
Ref: c-api/unicode c PyUnicode_DecodeUTF1610737632
Ref: 3e1710737632
Ref: c-api/unicode c PyUnicode_DecodeUTF16Stateful10738856
Ref: 3e1810738856
Ref: c-api/unicode c PyUnicode_AsUTF16String10739485
Ref: 3e1910739485
Ref: c-api/unicode c PyUnicode_EncodeUTF1610739814
Ref: b0910739814
Node: UTF-7 Codecs10740985
Ref: c-api/unicode utf-7-codecs10741101
Ref: 3e1a10741101
Ref: c-api/unicode c PyUnicode_DecodeUTF710741179
Ref: 3e1b10741179
Ref: c-api/unicode c PyUnicode_DecodeUTF7Stateful10741477
Ref: 3e1c10741477
Ref: c-api/unicode c PyUnicode_EncodeUTF710741975
Ref: b0510741975
Node: Unicode-Escape Codecs10742807
Ref: c-api/unicode unicode-escape-codecs10742935
Ref: 3e1d10742935
Ref: c-api/unicode c PyUnicode_DecodeUnicodeEscape10743042
Ref: 3e1e10743042
Ref: c-api/unicode c PyUnicode_AsUnicodeEscapeString10743358
Ref: b0b10743358
Ref: c-api/unicode c PyUnicode_EncodeUnicodeEscape10743672
Ref: b0a10743672
Node: Raw-Unicode-Escape Codecs10744191
Ref: c-api/unicode raw-unicode-escape-codecs10744321
Ref: 3e1f10744321
Ref: c-api/unicode c PyUnicode_DecodeRawUnicodeEscape10744440
Ref: 3e2010744440
Ref: c-api/unicode c PyUnicode_AsRawUnicodeEscapeString10744763
Ref: b0d10744763
Ref: c-api/unicode c PyUnicode_EncodeRawUnicodeEscape10745084
Ref: b0c10745084
Node: Latin-1 Codecs10745667
Ref: c-api/unicode latin-1-codecs10745788
Ref: 3e2110745788
Ref: c-api/unicode c PyUnicode_DecodeLatin110745985
Ref: 3e2210745985
Ref: c-api/unicode c PyUnicode_AsLatin1String10746287
Ref: b0f10746287
Ref: c-api/unicode c PyUnicode_EncodeLatin110746582
Ref: b0e10746582
Node: ASCII Codecs10747156
Ref: c-api/unicode ascii-codecs10747272
Ref: 3e2310747272
Ref: c-api/unicode c PyUnicode_DecodeASCII10747420
Ref: 3e2410747420
Ref: c-api/unicode c PyUnicode_AsASCIIString10747719
Ref: b1110747719
Ref: c-api/unicode c PyUnicode_EncodeASCII10748006
Ref: b1010748006
Node: Character Map Codecs10748576
Ref: c-api/unicode character-map-codecs10748701
Ref: 3e2510748701
Ref: c-api/unicode c PyUnicode_DecodeCharmap10749180
Ref: 3e2610749180
Ref: c-api/unicode c PyUnicode_AsCharmapString10750002
Ref: 3e2710750002
Ref: c-api/unicode c PyUnicode_EncodeCharmap10750652
Ref: b1210750652
Ref: c-api/unicode c PyUnicode_Translate10751348
Ref: 3e2810751348
Ref: c-api/unicode c PyUnicode_TranslateCharmap10752185
Ref: b1310752185
Node: MBCS codecs for Windows10752821
Ref: c-api/unicode mbcs-codecs-for-windows10752949
Ref: 3e2910752949
Ref: c-api/unicode c PyUnicode_DecodeMBCS10753309
Ref: 3e2a10753309
Ref: c-api/unicode c PyUnicode_DecodeMBCSStateful10753606
Ref: 3e2b10753606
Ref: c-api/unicode c PyUnicode_AsMBCSString10754069
Ref: b1510754069
Ref: c-api/unicode c PyUnicode_EncodeCodePage10754354
Ref: b1610754354
Ref: c-api/unicode c PyUnicode_EncodeMBCS10754748
Ref: b1410754748
Node: Methods & Slots10755358
Ref: c-api/unicode methods-slots10755457
Ref: 3e2c10755457
Node: Methods and Slot Functions10755508
Ref: c-api/unicode methods-and-slot-functions10755626
Ref: 3e2d10755626
Ref: c-api/unicode unicodemethodsandslots10755626
Ref: 3e2e10755626
Ref: c-api/unicode c PyUnicode_Concat10755949
Ref: b2510755949
Ref: c-api/unicode c PyUnicode_Split10756115
Ref: 3e2f10756115
Ref: c-api/unicode c PyUnicode_Splitlines10756578
Ref: 3e3010756578
Ref: c-api/unicode c PyUnicode_Join10756916
Ref: b2610756916
Ref: c-api/unicode c PyUnicode_Tailmatch10757141
Ref: b0210757141
Ref: c-api/unicode c PyUnicode_Find10757540
Ref: 3e3110757540
Ref: c-api/unicode c PyUnicode_FindChar10758076
Ref: 44810758076
Ref: c-api/unicode c PyUnicode_Count10758746
Ref: 3e3210758746
Ref: c-api/unicode c PyUnicode_Replace10759002
Ref: 3e3310759002
Ref: c-api/unicode c PyUnicode_Compare10759352
Ref: b0110759352
Ref: c-api/unicode c PyUnicode_CompareWithASCIIString10759672
Ref: c0610759672
Ref: c-api/unicode c PyUnicode_RichCompare10760126
Ref: 3e3410760126
Ref: c-api/unicode c PyUnicode_Format10760654
Ref: 3e3510760654
Ref: c-api/unicode c PyUnicode_Contains10760878
Ref: 3e3610760878
Ref: c-api/unicode c PyUnicode_InternInPlace10761181
Ref: 3e3710761181
Ref: c-api/unicode c PyUnicode_InternFromString10761954
Ref: 3e3810761954
Node: 元组对象10762331
Ref: c-api/tuple doc10762459
Ref: 3e3910762459
Ref: c-api/tuple tuple-objects10762459
Ref: 3e3a10762459
Ref: c-api/tuple tupleobjects10762459
Ref: 3e3b10762459
Ref: c-api/tuple c PyTupleObject10762500
Ref: 3c5710762500
Ref: c-api/tuple c PyTuple_Type10762614
Ref: 3e3c10762614
Ref: c-api/tuple c PyTuple_Check10762799
Ref: 3e3d10762799
Ref: c-api/tuple c PyTuple_CheckExact10762945
Ref: 3e3e10762945
Ref: c-api/tuple c PyTuple_New10763099
Ref: 3e3f10763099
Ref: c-api/tuple c PyTuple_Pack10763283
Ref: 3e4010763283
Ref: c-api/tuple c PyTuple_Size10763625
Ref: 3e4110763625
Ref: c-api/tuple c PyTuple_GET_SIZE10763751
Ref: 3e4210763751
Ref: c-api/tuple c PyTuple_GetItem10763927
Ref: 3b1f10763927
Ref: c-api/tuple c PyTuple_GET_ITEM10764211
Ref: 3e4310764211
Ref: c-api/tuple c PyTuple_GetSlice10764397
Ref: 3e4410764397
Ref: c-api/tuple c PyTuple_SetItem10764737
Ref: 3b2410764737
Ref: c-api/tuple c PyTuple_SET_ITEM10765167
Ref: 3e4510765167
Ref: c-api/tuple c _PyTuple_Resize10765645
Ref: e5310765645
Ref: c-api/tuple c PyTuple_ClearFreeList10766485
Ref: 3e4610766485
Node: 结构序列对象10766588
Ref: c-api/tuple struct-sequence-objects10766697
Ref: 3e4710766697
Ref: c-api/tuple c PyStructSequence_NewType10766962
Ref: 3e4810766962
Ref: c-api/tuple c PyStructSequence_InitType10767265
Ref: 92f10767265
Ref: c-api/tuple c PyStructSequence_InitType210767429
Ref: 92e10767429
Ref: c-api/tuple c PyStructSequence_Desc10767674
Ref: 43110767674
Ref: c-api/tuple c PyStructSequence_Field10769175
Ref: 43010769175
Ref: c-api/tuple c PyStructSequence_UnnamedField10770294
Ref: 3e4a10770294
Ref: c-api/tuple c PyStructSequence_New10770400
Ref: 3e4910770400
Ref: c-api/tuple c PyStructSequence_GetItem10770606
Ref: 3e4b10770606
Ref: c-api/tuple c PyStructSequence_GET_ITEM10770839
Ref: 3e4c10770839
Ref: c-api/tuple c PyStructSequence_SetItem10771033
Ref: 3e4d10771033
Ref: c-api/tuple c PyStructSequence_SET_ITEM10771372
Ref: 3e4e10771372
Node: 列表对象10771608
Ref: c-api/list doc10771696
Ref: 3e4f10771696
Ref: c-api/list list-objects10771696
Ref: 3e5010771696
Ref: c-api/list listobjects10771696
Ref: 3e5110771696
Ref: c-api/list c PyListObject10771737
Ref: 3d0610771737
Ref: c-api/list c PyList_Type10771852
Ref: 3b5410771852
Ref: c-api/list c PyList_Check10772048
Ref: 3e5210772048
Ref: c-api/list c PyList_CheckExact10772196
Ref: 3e5310772196
Ref: c-api/list c PyList_New10772346
Ref: 3bb410772346
Ref: c-api/list c PyList_Size10772854
Ref: d8610772854
Ref: c-api/list c PyList_GET_SIZE10773007
Ref: 3e5410773007
Ref: c-api/list c PyList_GetItem10773143
Ref: 3b2010773143
Ref: c-api/list c PyList_GET_ITEM10773522
Ref: 3e5510773522
Ref: c-api/list c PyList_SetItem10773715
Ref: 3b2510773715
Ref: c-api/list c PyList_SET_ITEM10774143
Ref: 3e5610774143
Ref: c-api/list c PyList_Insert10774641
Ref: 3e5710774641
Ref: c-api/list c PyList_Append10774964
Ref: 3e5810774964
Ref: c-api/list c PyList_GetSlice10775223
Ref: 3e5910775223
Ref: c-api/list c PyList_SetSlice10775594
Ref: 3e5a10775594
Ref: c-api/list c PyList_Sort10776045
Ref: 3e5b10776045
Ref: c-api/list c PyList_Reverse10776237
Ref: 3e5c10776237
Ref: c-api/list c PyList_AsTuple10776435
Ref: 3e5d10776435
Ref: c-api/list c PyList_ClearFreeList10776630
Ref: 3e5e10776630
Node: 容器对象10776756
Ref: c-api/concrete container-objects10776868
Ref: 3e5f10776868
Ref: c-api/concrete mapobjects10776868
Ref: 3e6010776868
Node: 字典对象10776947
Ref: c-api/dict doc10777029
Ref: 3e6110777029
Ref: c-api/dict dictionary-objects10777029
Ref: 3e6210777029
Ref: c-api/dict dictobjects10777029
Ref: 3e6310777029
Ref: c-api/dict c PyDictObject10777068
Ref: 3e6410777068
Ref: c-api/dict c PyDict_Type10777176
Ref: 3e6510777176
Ref: c-api/dict c PyDict_Check10777354
Ref: 3d5910777354
Ref: c-api/dict c PyDict_CheckExact10777490
Ref: 3e6610777490
Ref: c-api/dict c PyDict_New10777634
Ref: 3e6710777634
Ref: c-api/dict c PyDictProxy_New10777774
Ref: 3e6810777774
Ref: c-api/dict c PyDict_Clear10778048
Ref: 3e6910778048
Ref: c-api/dict c PyDict_Contains10778141
Ref: 3e6a10778141
Ref: c-api/dict c PyDict_Copy10778433
Ref: 3e6b10778433
Ref: c-api/dict c PyDict_SetItem10778571
Ref: 3b2610778571
Ref: c-api/dict c PyDict_SetItemString10778923
Ref: 3e6c10778923
Ref: c-api/dict c PyDict_DelItem10779294
Ref: 3e6d10779294
Ref: c-api/dict c PyDict_DelItemString10779624
Ref: 3e6e10779624
Ref: c-api/dict c PyDict_GetItem10779896
Ref: 3b2110779896
Ref: c-api/dict c PyDict_GetItemWithError10780347
Ref: 3e6f10780347
Ref: c-api/dict c PyDict_GetItemString10780701
Ref: 3b2210780701
Ref: c-api/dict c PyDict_SetDefault10781208
Ref: 3e7010781208
Ref: c-api/dict c PyDict_Items10781717
Ref: 3e7110781717
Ref: c-api/dict c PyDict_Keys10781885
Ref: 3e7210781885
Ref: c-api/dict c PyDict_Values10782052
Ref: 3e7310782052
Ref: c-api/dict c PyDict_Size10782223
Ref: 3e7410782223
Ref: c-api/dict c PyDict_Next10782354
Ref: 3e7510782354
Ref: c-api/dict c PyDict_Merge10784095
Ref: 3e7610784095
Ref: c-api/dict c PyDict_Update10784653
Ref: 3e7710784653
Ref: c-api/dict c PyDict_MergeFromSeq210785032
Ref: 3e7810785032
Ref: c-api/dict c PyDict_ClearFreeList10785665
Ref: 3e7910785665
Node: 集合对象10785791
Ref: c-api/set doc10785873
Ref: 3e7a10785873
Ref: c-api/set set-objects10785873
Ref: 3e7b10785873
Ref: c-api/set setobjects10785873
Ref: 3e7c10785873
Ref: c-api/set c PySetObject10786627
Ref: 3e7d10786627
Ref: c-api/set c PySet_Type10787238
Ref: 3e7e10787238
Ref: c-api/set c PyFrozenSet_Type10787375
Ref: 3e7f10787375
Ref: c-api/set c PySet_Check10787673
Ref: 3e8010787673
Ref: c-api/set c PyFrozenSet_Check10787822
Ref: 3e8110787822
Ref: c-api/set c PyAnySet_Check10787983
Ref: 3e8210787983
Ref: c-api/set c PyAnySet_CheckExact10788166
Ref: 3e8310788166
Ref: c-api/set c PyFrozenSet_CheckExact10788355
Ref: 3e8410788355
Ref: c-api/set c PySet_New10788521
Ref: db310788521
Ref: c-api/set c PyFrozenSet_New10788988
Ref: db410788988
Ref: c-api/set c PySet_Size10789528
Ref: db810789528
Ref: c-api/set c PySet_GET_SIZE10789824
Ref: 3e8510789824
Ref: c-api/set c PySet_Contains10789952
Ref: db710789952
Ref: c-api/set c PySet_Add10790478
Ref: db510790478
Ref: c-api/set c PySet_Discard10791225
Ref: db610791225
Ref: c-api/set c PySet_Pop10791798
Ref: 3e8610791798
Ref: c-api/set c PySet_Clear10792164
Ref: 3e8710792164
Ref: c-api/set c PySet_ClearFreeList10792257
Ref: 3e8810792257
Node: 函数对象<2>10792382
Ref: c-api/concrete function-objects10792497
Ref: 3e8910792497
Ref: c-api/concrete otherobjects10792497
Ref: 3e8a10792497
Node: 函数对象<3>10792680
Ref: c-api/function doc10792774
Ref: 3e8b10792774
Ref: c-api/function function-objects10792774
Ref: 3e8c10792774
Ref: c-api/function id110792774
Ref: 3e8d10792774
Ref: c-api/function c PyFunctionObject10792859
Ref: 3e8e10792859
Ref: c-api/function c PyFunction_Type10792928
Ref: 3e8f10792928
Ref: c-api/function c PyFunction_Check10793126
Ref: 3e9010793126
Ref: c-api/function c PyFunction_New10793308
Ref: 3e9110793308
Ref: c-api/function c PyFunction_NewWithQualName10793788
Ref: 3e9210793788
Ref: c-api/function c PyFunction_GetCode10794236
Ref: 3e9310794236
Ref: c-api/function c PyFunction_GetGlobals10794394
Ref: 3e9410794394
Ref: c-api/function c PyFunction_GetModule10794556
Ref: 3e9510794556
Ref: c-api/function c PyFunction_GetDefaults10794832
Ref: 3e9610794832
Ref: c-api/function c PyFunction_SetDefaults10795036
Ref: 3e9710795036
Ref: c-api/function c PyFunction_GetClosure10795310
Ref: 3e9810795310
Ref: c-api/function c PyFunction_SetClosure10795517
Ref: 3e9910795517
Ref: c-api/function c PyFunction_GetAnnotations10795786
Ref: 3e9a10795786
Ref: c-api/function c PyFunction_SetAnnotations10795984
Ref: 3e9b10795984
Node: 实例方法对象10796256
Ref: c-api/method doc10796374
Ref: 3e9c10796374
Ref: c-api/method instance-method-objects10796374
Ref: 3e9d10796374
Ref: c-api/method instancemethod-objects10796374
Ref: 3e9e10796374
Ref: c-api/method c PyInstanceMethod_Type10796622
Ref: 3e9f10796622
Ref: c-api/method c PyInstanceMethod_Check10796794
Ref: 3ea010796794
Ref: c-api/method c PyInstanceMethod_New10796993
Ref: 3ea110796993
Ref: c-api/method c PyInstanceMethod_Function10797236
Ref: 3ea210797236
Ref: c-api/method c PyInstanceMethod_GET_FUNCTION10797401
Ref: 3ea310797401
Node: 方法对象<2>10797598
Ref: c-api/method id110797712
Ref: 3ea410797712
Ref: c-api/method method-objects10797712
Ref: 3ea510797712
Ref: c-api/method c PyMethod_Type10797918
Ref: 3ea610797918
Ref: c-api/method c PyMethod_Check10798099
Ref: 3ea710798099
Ref: c-api/method c PyMethod_New10798277
Ref: 3ea810798277
Ref: c-api/method c PyMethod_Function10798598
Ref: 3ea910798598
Ref: c-api/method c PyMethod_GET_FUNCTION10798753
Ref: 3eaa10798753
Ref: c-api/method c PyMethod_Self10798936
Ref: 3eab10798936
Ref: c-api/method c PyMethod_GET_SELF10799075
Ref: 3eac10799075
Ref: c-api/method c PyMethod_ClearFreeList10799250
Ref: 3ead10799250
Node: Cell 对象10799354
Ref: c-api/cell doc10799465
Ref: 3eae10799465
Ref: c-api/cell cell-objects10799465
Ref: 3eaf10799465
Ref: c-api/cell id110799465
Ref: 3eb010799465
Ref: c-api/cell c PyCellObject10800049
Ref: 3eb110800049
Ref: c-api/cell c PyCell_Type10800116
Ref: 3eb210800116
Ref: c-api/cell c PyCell_Check10800208
Ref: 3eb310800208
Ref: c-api/cell c PyCell_New10800334
Ref: 3eb410800334
Ref: c-api/cell c PyCell_Get10800513
Ref: 3eb510800513
Ref: c-api/cell c PyCell_GET10800641
Ref: 3eb610800641
Ref: c-api/cell c PyCell_Set10800854
Ref: 3eb710800854
Ref: c-api/cell c PyCell_SET10801209
Ref: 3eb810801209
Ref: c-api/code codeobjects10801463
Ref: 3eb910801463
Node: 代码对象<2>10801464
Ref: c-api/code doc10801551
Ref: 3eba10801551
Ref: c-api/code code-objects10801551
Ref: 3ebb10801551
Ref: c-api/code c PyCodeObject10801705
Ref: 3ebc10801705
Ref: c-api/code c PyCode_Type10801822
Ref: 3ebd10801822
Ref: c-api/code c PyCode_Check10801965
Ref: 3ebe10801965
Ref: c-api/code c PyCode_GetNumFree10802080
Ref: 3ebf10802080
Ref: c-api/code c PyCode_New10802179
Ref: 27310802179
Ref: c-api/code c PyCode_NewWithPosOnlyArgs10802830
Ref: 27210802830
Ref: c-api/code c PyCode_NewEmpty10803386
Ref: cf210803386
Node: 其他对象<2>10803716
Ref: c-api/concrete other-objects10803810
Ref: 3ec010803810
Node: 文件对象10804166
Ref: c-api/file doc10804251
Ref: 3ec110804251
Ref: c-api/file file-objects10804251
Ref: 3ec210804251
Ref: c-api/file fileobjects10804251
Ref: 3ec310804251
Ref: c-api/file c PyFile_FromFd10804750
Ref: 3ec410804750
Ref: c-api/file c PyObject_AsFileDescriptor10805626
Ref: 3ec510805626
Ref: c-api/file c PyFile_GetLine10806018
Ref: 3ec610806018
Ref: c-api/file c PyFile_SetOpenCodeHook10806745
Ref: 1ff610806745
Ref: c-api/file c PyFile_WriteObject10807878
Ref: 3ec710807878
Ref: c-api/file c PyFile_WriteString10808250
Ref: 3ec810808250
Node: 模块对象10808445
Ref: c-api/module doc10808554
Ref: 3ec910808554
Ref: c-api/module module-objects10808554
Ref: 3eca10808554
Ref: c-api/module moduleobjects10808554
Ref: 3ecb10808554
Ref: c-api/module c PyModule_Type10808593
Ref: 3ecc10808593
Ref: c-api/module c PyModule_Check10808791
Ref: 3ecd10808791
Ref: c-api/module c PyModule_CheckExact10808922
Ref: 3ece10808922
Ref: c-api/module c PyModule_NewObject10809073
Ref: 3ecf10809073
Ref: c-api/module c PyModule_New10809662
Ref: 3ed010809662
Ref: c-api/module c PyModule_GetDict10809879
Ref: 3ed110809879
Ref: c-api/module c PyModule_GetNameObject10810466
Ref: 3ed210810466
Ref: c-api/module c PyModule_GetName10810782
Ref: 3ed310810782
Ref: c-api/module c PyModule_GetState10810951
Ref: 3ed410810951
Ref: c-api/module c PyModule_GetDef10811188
Ref: 3ed610811188
Ref: c-api/module c PyModule_GetFilenameObject10811422
Ref: 3ed710811422
Ref: c-api/module c PyModule_GetFilename10811846
Ref: 3ed810811846
Node: Initializing C modules10812266
Ref: c-api/module initializing-c-modules10812359
Ref: 3ed910812359
Ref: c-api/module initializing-modules10812359
Ref: 3b7710812359
Ref: c-api/module c PyModuleDef10812977
Ref: 3b4b10812977
Ref: c-api/module c PyModuleDef m_base10813201
Ref: 3eda10813201
Ref: c-api/module c PyModuleDef m_name10813318
Ref: 3edb10813318
Ref: c-api/module c PyModuleDef m_doc10813393
Ref: 3edc10813393
Ref: c-api/module c PyModuleDef m_size10813554
Ref: 3ed510813554
Ref: c-api/module c PyModuleDef m_methods10814498
Ref: 3edd10814498
Ref: c-api/module c PyModuleDef m_slots10814713
Ref: 3ede10814713
Ref: c-api/module c PyModuleDef m_reload10815085
Ref: 3edf10815085
Ref: c-api/module c PyModuleDef m_traverse10815132
Ref: 3ee010815132
Ref: c-api/module c PyModuleDef m_clear10815509
Ref: 3ee210815509
Ref: c-api/module c PyModuleDef m_free10815873
Ref: 3ee310815873
Ref: Initializing C modules-Footnote-110816403
Node: Single-phase initialization10816452
Ref: c-api/module single-phase-initialization10816573
Ref: 3ee410816573
Ref: c-api/module c PyModule_Create10816848
Ref: 3b0a10816848
Ref: c-api/module c PyModule_Create210817129
Ref: 3ee510817129
Node: Multi-phase initialization10817830
Ref: c-api/module id110817995
Ref: 3ee610817995
Ref: c-api/module multi-phase-initialization10817995
Ref: 3b7810817995
Ref: c-api/module c PyModuleDef_Init10819588
Ref: 3ee710819588
Ref: c-api/module c PyModuleDef_Slot10820035
Ref: 3ee810820035
Ref: c-api/module c PyModuleDef_Slot slot10820067
Ref: 3ee910820067
Ref: c-api/module c PyModuleDef_Slot value10820168
Ref: 3eea10820168
Ref: c-api/module c Py_mod_create10820384
Ref: 3eeb10820384
Ref: c-api/module c create_module10820575
Ref: 3eec10820575
Ref: c-api/module c Py_mod_exec10821992
Ref: 3ee110821992
Ref: c-api/module c exec_module10822262
Ref: 3eed10822262
Ref: Multi-phase initialization-Footnote-110822547
Ref: Multi-phase initialization-Footnote-210822596
Node: Low-level module creation functions10822645
Ref: c-api/module low-level-module-creation-functions10822800
Ref: 3eee10822800
Ref: c-api/module c PyModule_FromDefAndSpec10823179
Ref: 7b410823179
Ref: c-api/module c PyModule_FromDefAndSpec210823555
Ref: 7b510823555
Ref: c-api/module c PyModule_ExecDef10824176
Ref: 7b610824176
Ref: c-api/module c PyModule_SetDocString10824355
Ref: 3eef10824355
Ref: c-api/module c PyModule_AddFunctions10824690
Ref: 3ef010824690
Node: Support functions10825374
Ref: c-api/module support-functions10825494
Ref: 3ef110825494
Ref: c-api/module c PyModule_AddObject10825780
Ref: f8e10825780
Ref: c-api/module c PyModule_AddIntConstant10826695
Ref: 3ef210826695
Ref: c-api/module c PyModule_AddStringConstant10826990
Ref: 3ef310826990
Ref: c-api/module c PyModule_AddIntMacro10827349
Ref: 3ef410827349
Ref: c-api/module c PyModule_AddStringMacro10827694
Ref: d6110827694
Node: Module lookup10827804
Ref: c-api/module module-lookup10827897
Ref: 3ef510827897
Ref: c-api/module c PyState_FindModule10828316
Ref: 3ef610828316
Ref: c-api/module c PyState_AddModule10828798
Ref: 3ef710828798
Ref: c-api/module c PyState_RemoveModule10829694
Ref: 3ef810829694
Node: 迭代器对象10829900
Ref: c-api/iterator doc10830012
Ref: 3ef910830012
Ref: c-api/iterator id110830012
Ref: 3efa10830012
Ref: c-api/iterator iterator-objects10830012
Ref: 3efb10830012
Ref: c-api/iterator c PySeqIter_Type10830348
Ref: 3efc10830348
Ref: c-api/iterator c PySeqIter_Check10830543
Ref: 3efe10830543
Ref: c-api/iterator c PySeqIter_New10830660
Ref: 3efd10830660
Ref: c-api/iterator c PyCallIter_Type10830897
Ref: 3eff10830897
Ref: c-api/iterator c PyCallIter_Check10831086
Ref: 3f0110831086
Ref: c-api/iterator c PyCallIter_New10831205
Ref: 3f0010831205
Node: 描述符对象10831617
Ref: c-api/descriptor doc10831729
Ref: 3f0210831729
Ref: c-api/descriptor descriptor-objects10831729
Ref: 3f0310831729
Ref: c-api/descriptor id110831729
Ref: 3f0410831729
Ref: c-api/descriptor c PyProperty_Type10831876
Ref: 3f0510831876
Ref: c-api/descriptor c PyDescr_NewGetSet10831966
Ref: 3f0610831966
Ref: c-api/descriptor c PyDescr_NewMember10832104
Ref: 3f0710832104
Ref: c-api/descriptor c PyDescr_NewMethod10832240
Ref: f4710832240
Ref: c-api/descriptor c PyDescr_NewWrapper10832376
Ref: 3f0810832376
Ref: c-api/descriptor c PyDescr_NewClassMethod10832531
Ref: 3f0910832531
Ref: c-api/descriptor c PyDescr_IsData10832667
Ref: 3f0a10832667
Ref: c-api/descriptor c PyWrapper_New10832894
Ref: 3f0b10832894
Node: 切片对象10832994
Ref: c-api/slice doc10833106
Ref: 3f0c10833106
Ref: c-api/slice id110833106
Ref: 3f0d10833106
Ref: c-api/slice slice-objects10833106
Ref: 3f0e10833106
Ref: c-api/slice c PySlice_Type10833147
Ref: 3f0f10833147
Ref: c-api/slice c PySlice_Check10833295
Ref: 3f1010833295
Ref: c-api/slice c PySlice_New10833433
Ref: 3f1110833433
Ref: c-api/slice c PySlice_GetIndices10833896
Ref: 3f1210833896
Ref: c-api/slice c PySlice_GetIndicesEx10834567
Ref: 48010834567
Ref: c-api/slice c PySlice_Unpack10836431
Ref: 43710836431
Ref: c-api/slice c PySlice_AdjustIndices10837002
Ref: 43810837002
Node: Ellipsis 对象10837409
Ref: c-api/slice ellipsis-object10837523
Ref: 3f1310837523
Ref: c-api/slice c Py_Ellipsis10837572
Ref: 3f1410837572
Ref: c-api/memoryview memoryview-objects10837816
Ref: 3d1f10837816
Node: MemoryView 对象10837817
Ref: c-api/memoryview doc10837937
Ref: 3f1510837937
Ref: c-api/memoryview id110837937
Ref: 3f1610837937
Ref: c-api/memoryview c PyMemoryView_FromObject10838143
Ref: 3f1710838143
Ref: c-api/memoryview c PyMemoryView_FromMemory10838479
Ref: ad110838479
Ref: c-api/memoryview c PyMemoryView_FromBuffer10838785
Ref: 3d2310838785
Ref: c-api/memoryview c PyMemoryView_GetContiguous10839060
Ref: 3f1810839060
Ref: c-api/memoryview c PyMemoryView_Check10839498
Ref: 3f1910839498
Ref: c-api/memoryview c PyMemoryView_GET_BUFFER10839683
Ref: 3f1a10839683
Ref: c-api/memoryview c PyMemoryView_GET_BASE10839974
Ref: 3f1b10839974
Node: 弱引用对象<2>10840312
Ref: c-api/weakref doc10840426
Ref: 3f1c10840426
Ref: c-api/weakref weak-reference-objects10840426
Ref: 3f1d10840426
Ref: c-api/weakref weakrefobjects10840426
Ref: 3f1e10840426
Ref: c-api/weakref c PyWeakref_Check10840679
Ref: 3f1f10840679
Ref: c-api/weakref c PyWeakref_CheckRef10840801
Ref: 3f2010840801
Ref: c-api/weakref c PyWeakref_CheckProxy10840902
Ref: 3f2110840902
Ref: c-api/weakref c PyWeakref_NewRef10841011
Ref: 3f2210841011
Ref: c-api/weakref c PyWeakref_NewProxy10841759
Ref: 3f2310841759
Ref: c-api/weakref c PyWeakref_GetObject10842515
Ref: 3f2410842515
Ref: c-api/weakref c PyWeakref_GET_OBJECT10842983
Ref: 3f2510842983
Node: 胶囊<2>10843181
Ref: c-api/capsule doc10843293
Ref: 3f2610843293
Ref: c-api/capsule capsules10843293
Ref: 3b3110843293
Ref: c-api/capsule id110843293
Ref: 3f2710843293
Ref: c-api/capsule c PyCapsule10843435
Ref: c0f10843435
Ref: c-api/capsule c PyCapsule_Destructor10843859
Ref: 3f2810843859
Ref: c-api/capsule c PyCapsule_CheckExact10844130
Ref: 3f2910844130
Ref: c-api/capsule c PyCapsule_New10844249
Ref: 3b2f10844249
Ref: c-api/capsule c PyCapsule_GetPointer10845139
Ref: 3f2a10845139
Ref: c-api/capsule c PyCapsule_GetDestructor10845597
Ref: 3f2b10845597
Ref: c-api/capsule c PyCapsule_GetContext10846004
Ref: 3f2c10846004
Ref: c-api/capsule c PyCapsule_GetName10846391
Ref: 3f2d10846391
Ref: c-api/capsule c PyCapsule_Import10846775
Ref: 3b3010846775
Ref: c-api/capsule c PyCapsule_IsValid10847445
Ref: cf810847445
Ref: c-api/capsule c PyCapsule_SetContext10848217
Ref: 3f2e10848217
Ref: c-api/capsule c PyCapsule_SetDestructor10848438
Ref: 3f2f10848438
Ref: c-api/capsule c PyCapsule_SetName10848687
Ref: 3f3010848687
Ref: c-api/capsule c PyCapsule_SetPointer10849074
Ref: 3f3110849074
Node: 生成器对象10849319
Ref: c-api/gen doc10849428
Ref: 3f3210849428
Ref: c-api/gen gen-objects10849428
Ref: 3f3310849428
Ref: c-api/gen generator-objects10849428
Ref: 3f3410849428
Ref: c-api/gen c PyGenObject10849687
Ref: 3f3710849687
Ref: c-api/gen c PyGen_Type10849758
Ref: 3f3810849758
Ref: c-api/gen c PyGen_Check10849852
Ref: 3f3910849852
Ref: c-api/gen c PyGen_CheckExact10849990
Ref: 3f3a10849990
Ref: c-api/gen c PyGen_New10850152
Ref: 3f3510850152
Ref: c-api/gen c PyGen_NewWithQualName10850406
Ref: 3f3610850406
Node: 协程对象<2>10850808
Ref: c-api/coro doc10850929
Ref: 3f3b10850929
Ref: c-api/coro coro-objects10850929
Ref: 7d610850929
Ref: c-api/coro coroutine-objects10850929
Ref: 3f3c10850929
Ref: c-api/coro c PyCoroObject10851061
Ref: 3f3d10851061
Ref: c-api/coro c PyCoro_Type10851130
Ref: 3f3e10851130
Ref: c-api/coro c PyCoro_CheckExact10851222
Ref: 3f3f10851222
Ref: c-api/coro c PyCoro_New10851386
Ref: 3f4010851386
Node: 上下文变量对象10851774
Ref: c-api/contextvars doc10851898
Ref: 3f4110851898
Ref: c-api/contextvars context-variables-objects10851898
Ref: 3f4210851898
Ref: c-api/contextvars contextvarsobjects10851898
Ref: 34410851898
Ref: c-api/contextvars contextvarsobjects-pointertype-change10851954
Ref: 4c110851954
Ref: c-api/contextvars c PyContext10852487
Ref: 3f4310852487
Ref: c-api/contextvars c PyContextVar10852589
Ref: 3f4410852589
Ref: c-api/contextvars c PyContextToken10852697
Ref: 3f4510852697
Ref: c-api/contextvars c PyContext_Type10852795
Ref: 3f4610852795
Ref: c-api/contextvars c PyContextVar_Type10852886
Ref: 3f4710852886
Ref: c-api/contextvars c PyContextToken_Type10852989
Ref: 3f4810852989
Ref: c-api/contextvars c PyContext_CheckExact10853120
Ref: 3f4910853120
Ref: c-api/contextvars c PyContextVar_CheckExact10853322
Ref: 3f4a10853322
Ref: c-api/contextvars c PyContextToken_CheckExact10853530
Ref: 3f4b10853530
Ref: c-api/contextvars c PyContext_New10853771
Ref: 3f4c10853771
Ref: c-api/contextvars c PyContext_Copy10853941
Ref: 3f4d10853941
Ref: c-api/contextvars c PyContext_CopyCurrent10854137
Ref: 3f4e10854137
Ref: c-api/contextvars c PyContext_Enter10854318
Ref: 3f4f10854318
Ref: c-api/contextvars c PyContext_Exit10854484
Ref: 3f5010854484
Ref: c-api/contextvars c PyContext_ClearFreeList10854695
Ref: 3f5110854695
Ref: c-api/contextvars c PyContextVar_New10854882
Ref: 3f5210854882
Ref: c-api/contextvars c PyContextVar_Get10855249
Ref: 3f5310855249
Ref: c-api/contextvars c PyContextVar_Set10855894
Ref: 3f5410855894
Ref: c-api/contextvars c PyContextVar_Reset10856149
Ref: 3f5510856149
Node: DateTime 对象<2>10856428
Ref: c-api/datetime doc10856528
Ref: 3f5610856528
Ref: c-api/datetime datetime-objects10856528
Ref: 3f5710856528
Ref: c-api/datetime datetimeobjects10856528
Ref: 3f5810856528
Ref: c-api/datetime c PyDateTime_TimeZone_UTC10857057
Ref: 43e10857057
Ref: c-api/datetime c PyDate_Check10857255
Ref: 3f5910857255
Ref: c-api/datetime c PyDate_CheckExact10857458
Ref: 3f5a10857458
Ref: c-api/datetime c PyDateTime_Check10857617
Ref: 3f5b10857617
Ref: c-api/datetime c PyDateTime_CheckExact10857836
Ref: 3f5c10857836
Ref: c-api/datetime c PyTime_Check10858003
Ref: 3f5d10858003
Ref: c-api/datetime c PyTime_CheckExact10858208
Ref: 3f5e10858208
Ref: c-api/datetime c PyDelta_Check10858373
Ref: 3f5f10858373
Ref: c-api/datetime c PyDelta_CheckExact10858579
Ref: 3f6010858579
Ref: c-api/datetime c PyTZInfo_Check10858740
Ref: 3f6110858740
Ref: c-api/datetime c PyTZInfo_CheckExact10858951
Ref: 3f6210858951
Ref: c-api/datetime c PyDate_FromDate10859146
Ref: 3f6310859146
Ref: c-api/datetime c PyDateTime_FromDateAndTime10859326
Ref: 3f6410859326
Ref: c-api/datetime c PyDateTime_FromDateAndTimeAndFold10859636
Ref: 3f6510859636
Ref: c-api/datetime c PyTime_FromTime10860003
Ref: 3f6610860003
Ref: c-api/datetime c PyTime_FromTimeAndFold10860245
Ref: 3f6710860245
Ref: c-api/datetime c PyDelta_FromDSU10860534
Ref: 3f6810860534
Ref: c-api/datetime c PyTimeZone_FromOffset10860886
Ref: 43c10860886
Ref: c-api/datetime c PyTimeZone_FromOffsetAndName10861160
Ref: 43d10861160
Ref: c-api/datetime c PyDateTime_GET_YEAR10861693
Ref: 3f6910861693
Ref: c-api/datetime c PyDateTime_GET_MONTH10861799
Ref: 3f6a10861799
Ref: c-api/datetime c PyDateTime_GET_DAY10861900
Ref: 3f6b10861900
Ref: c-api/datetime c PyDateTime_DATE_GET_HOUR10862191
Ref: 3f6c10862191
Ref: c-api/datetime c PyDateTime_DATE_GET_MINUTE10862303
Ref: 3f6d10862303
Ref: c-api/datetime c PyDateTime_DATE_GET_SECOND10862417
Ref: 3f6e10862417
Ref: c-api/datetime c PyDateTime_DATE_GET_MICROSECOND10862528
Ref: 3f6f10862528
Ref: c-api/datetime c PyDateTime_TIME_GET_HOUR10862832
Ref: 3f7010862832
Ref: c-api/datetime c PyDateTime_TIME_GET_MINUTE10862940
Ref: 3f7110862940
Ref: c-api/datetime c PyDateTime_TIME_GET_SECOND10863050
Ref: 3f7210863050
Ref: c-api/datetime c PyDateTime_TIME_GET_MICROSECOND10863157
Ref: 3f7310863157
Ref: c-api/datetime c PyDateTime_DELTA_GET_DAYS10863462
Ref: 3f7410863462
Ref: c-api/datetime c PyDateTime_DELTA_GET_SECONDS10863612
Ref: 3f7510863612
Ref: c-api/datetime c PyDateTime_DELTA_GET_MICROSECONDS10863752
Ref: 3f7610863752
Ref: c-api/datetime c PyDateTime_FromTimestamp10863942
Ref: 3f7710863942
Ref: c-api/datetime c PyDate_FromTimestamp10864203
Ref: ffb10864203
Node: 初始化，终结和线程10864452
Ref: c-api/init doc10864598
Ref: 3f7810864598
Ref: c-api/init initialization10864598
Ref: 3f7910864598
Ref: c-api/init initialization-finalization-and-threads10864598
Ref: 3f7a10864598
Node: 在Python初始化之前10865015
Ref: c-api/init before-python-initialization10865130
Ref: 3f7b10865130
Ref: c-api/init pre-init-safe10865130
Ref: 44210865130
Node: 全局配置变量10867054
Ref: c-api/init global-conf-vars10867221
Ref: 3f7c10867221
Ref: c-api/init global-configuration-variables10867221
Ref: 3f8610867221
Ref: c-api/init c Py_BytesWarningFlag10867606
Ref: 4bc10867606
Ref: c-api/init c Py_DebugFlag10867887
Ref: 3f8710867887
Ref: c-api/init c Py_DontWriteBytecodeFlag10868115
Ref: 3f8810868115
Ref: c-api/init c Py_FrozenFlag10868378
Ref: 3f8910868378
Ref: c-api/init c Py_HashRandomizationFlag10868597
Ref: 3f8a10868597
Ref: c-api/init c Py_IgnoreEnvironmentFlag10868881
Ref: 4c010868881
Ref: c-api/init c Py_InspectFlag10869118
Ref: 3f8b10869118
Ref: c-api/init c Py_InteractiveFlag10869486
Ref: 3c4210869486
Ref: c-api/init c Py_IsolatedFlag10869565
Ref: 3f8c10869565
Ref: c-api/init c Py_LegacyWindowsFSEncodingFlag10869834
Ref: 3c4710869834
Ref: c-api/init c Py_LegacyWindowsStdioFlag10870231
Ref: 3f8d10870231
Ref: c-api/init c Py_NoSiteFlag10870628
Ref: 3f8e10870628
Ref: c-api/init c Py_NoUserSiteDirectory10870967
Ref: 3f8f10870967
Ref: c-api/init c Py_OptimizeFlag10871230
Ref: 230510871230
Ref: c-api/init c Py_QuietFlag10871367
Ref: 3f9010871367
Ref: c-api/init c Py_UnbufferedStdioFlag10871532
Ref: 3f9110871532
Ref: c-api/init c Py_VerboseFlag10871739
Ref: 3f9210871739
Ref: 全局配置变量-Footnote-110872226
Ref: 全局配置变量-Footnote-210872275
Node: Initializing and finalizing the interpreter10872324
Ref: c-api/init initializing-and-finalizing-the-interpreter10872490
Ref: 3f9310872490
Ref: c-api/init c Py_Initialize10872591
Ref: 44110872591
Ref: c-api/init c Py_InitializeEx10873562
Ref: 3f9410873562
Ref: c-api/init c Py_IsInitialized10873839
Ref: 3bc010873839
Ref: c-api/init c Py_FinalizeEx10874108
Ref: 5d210874108
Ref: c-api/init c Py_Finalize10876239
Ref: cf510876239
Node: Process-wide parameters10876389
Ref: c-api/init process-wide-parameters10876581
Ref: 3f9610876581
Ref: c-api/init c Py_SetStandardStreamEncoding10876642
Ref: 92d10876642
Ref: c-api/init c Py_SetProgramName10877755
Ref: f9910877755
Ref: c-api/init c Py_GetProgramName10878667
Ref: 27710878667
Ref: c-api/init c Py_GetPrefix10878896
Ref: 3bbe10878896
Ref: c-api/init c Py_GetExecPrefix10879667
Ref: 3bbf10879667
Ref: c-api/init c Py_GetProgramFullPath10881834
Ref: 27610881834
Ref: c-api/init c Py_GetPath10882269
Ref: 3bbd10882269
Ref: c-api/init c Py_SetPath10882977
Ref: 27410882977
Ref: c-api/init c Py_GetVersion10884190
Ref: 3f8410884190
Ref: c-api/init c Py_GetPlatform10884750
Ref: 3f8310884750
Ref: c-api/init c Py_GetCopyright10885337
Ref: 3f8210885337
Ref: c-api/init c Py_GetCompiler10885718
Ref: 3f8110885718
Ref: c-api/init c Py_GetBuildInfo10886099
Ref: da210886099
Ref: c-api/init c PySys_SetArgvEx10886507
Ref: c0210886507
Ref: c-api/init c PySys_SetArgv10888481
Ref: cf410888481
Ref: c-api/init c Py_SetPythonHome10888895
Ref: f9810888895
Ref: c-api/init c Py_GetPythonHome10889487
Ref: 3f8510889487
Ref: Process-wide parameters-Footnote-110889763
Node: Thread State and the Global Interpreter Lock10889832
Ref: c-api/init thread-state-and-the-global-interpreter-lock10890004
Ref: 3f9710890004
Ref: c-api/init threads10890004
Ref: 3f9810890004
Node: Releasing the GIL from extension code10891541
Ref: c-api/init releasing-the-gil-from-extension-code10891692
Ref: 3f9b10891692
Node: 非Python创建的线程10893569
Ref: c-api/init gilstate10893748
Ref: 3f9c10893748
Ref: c-api/init non-python-created-threads10893748
Ref: 3f9d10893748
Node: Cautions about fork10895496
Ref: c-api/init cautions-about-fork10895648
Ref: 3f9f10895648
Ref: c-api/init fork-and-threads10895648
Ref: 3c4310895648
Node: 高阶 API10897572
Ref: c-api/init high-level-api10897713
Ref: 3fa010897713
Ref: c-api/init c PyInterpreterState10897877
Ref: 2c310897877
Ref: c-api/init c PyThreadState10898446
Ref: 3f9910898446
Ref: c-api/init c PyEval_InitThreads10898684
Ref: c1a10898684
Ref: c-api/init c PyEval_ThreadsInitialized10899372
Ref: de110899372
Ref: c-api/init c PyEval_SaveThread10899763
Ref: c1910899763
Ref: c-api/init c PyEval_RestoreThread10900074
Ref: 2b510900074
Ref: c-api/init c PyThreadState_Get10900796
Ref: 3f9a10900796
Ref: c-api/init c PyThreadState_Swap10901064
Ref: 3fa110901064
Ref: c-api/init c PyGILState_Ensure10901422
Ref: 2b710901422
Ref: c-api/init c PyGILState_Release10903147
Ref: 3f9e10903147
Ref: c-api/init c PyGILState_GetThisThreadState10903633
Ref: 3fa210903633
Ref: c-api/init c PyGILState_Check10904020
Ref: 3fa310904020
Ref: c-api/init c Py_BEGIN_ALLOW_THREADS10904749
Ref: 3b2910904749
Ref: c-api/init c Py_END_ALLOW_THREADS10905053
Ref: 2b610905053
Ref: c-api/init c Py_BLOCK_THREADS10905334
Ref: 3fa410905334
Ref: c-api/init c Py_UNBLOCK_THREADS10905517
Ref: 3fa510905517
Node: Low-level API10905730
Ref: c-api/init low-level-api10905843
Ref: 3fa610905843
Ref: c-api/init c PyInterpreterState_New10906053
Ref: 34d310906053
Ref: c-api/init c PyInterpreterState_Clear10906392
Ref: 34d210906392
Ref: c-api/init c PyInterpreterState_Delete10906680
Ref: 3fa710906680
Ref: c-api/init c PyThreadState_New10906963
Ref: 3fa810906963
Ref: c-api/init c PyThreadState_Clear10907261
Ref: f2f10907261
Ref: c-api/init c PyThreadState_Delete10907427
Ref: 3fa910907427
Ref: c-api/init c PyInterpreterState_GetID10907683
Ref: 44310907683
Ref: c-api/init c PyInterpreterState_GetDict10907928
Ref: 3faa10907928
Ref: c-api/init c PyThreadState_GetDict10908433
Ref: 3fab10908433
Ref: c-api/init c PyThreadState_SetAsyncExc10908932
Ref: 43f10908932
Ref: c-api/init c PyEval_AcquireThread10909720
Ref: 2b410909720
Ref: c-api/init c PyEval_ReleaseThread10910822
Ref: 3fac10910822
Ref: c-api/init c PyEval_AcquireLock10911389
Ref: 2b310911389
Ref: c-api/init c PyEval_ReleaseLock10912429
Ref: c1810912429
Node: Sub-interpreter support10912746
Ref: c-api/init id110912907
Ref: 3fad10912907
Ref: c-api/init sub-interpreter-support10912907
Ref: 3c4410912907
Ref: c-api/init c Py_NewInterpreter10913834
Ref: 3f9510913834
Ref: c-api/init c Py_EndInterpreter10916844
Ref: 3fb010916844
Node: 错误和警告10917510
Ref: c-api/init bugs-and-caveats10917585
Ref: 3faf10917585
Node: 异步通知10919187
Ref: c-api/init asynchronous-notifications10919319
Ref: 3fb110919319
Ref: c-api/init c Py_AddPendingCall10919532
Ref: cf110919532
Node: 分析和跟踪10921186
Ref: c-api/init profiling10921316
Ref: 3fb210921316
Ref: c-api/init profiling-and-tracing10921316
Ref: 3fb310921316
Ref: c-api/init c Py_tracefunc10921978
Ref: 3fb410921978
Ref: c-api/init c PyTrace_CALL10924209
Ref: 3fb510924209
Ref: c-api/init c PyTrace_EXCEPTION10924597
Ref: 3fb610924597
Ref: c-api/init c PyTrace_LINE10925205
Ref: 3fb710925205
Ref: c-api/init c PyTrace_RETURN10925499
Ref: 3fb810925499
Ref: c-api/init c PyTrace_C_CALL10925650
Ref: 3fb910925650
Ref: c-api/init c PyTrace_C_EXCEPTION10925810
Ref: 3fba10925810
Ref: c-api/init c PyTrace_C_RETURN10925977
Ref: 3fbb10925977
Ref: c-api/init c PyTrace_OPCODE10926130
Ref: 3fbc10926130
Ref: c-api/init c PyEval_SetProfile10926462
Ref: e4310926462
Ref: c-api/init c PyEval_SetTrace10927014
Ref: e4410927014
Node: 高级调试器支持10927562
Ref: c-api/init advanced-debugger-support10927708
Ref: 3fbd10927708
Ref: c-api/init advanced-debugging10927708
Ref: 3fbe10927708
Ref: c-api/init c PyInterpreterState_Head10927833
Ref: e4710927833
Ref: c-api/init c PyInterpreterState_Main10927987
Ref: 3fae10927987
Ref: c-api/init c PyInterpreterState_Next10928097
Ref: e4810928097
Ref: c-api/init c PyInterpreterState_ThreadHead10928297
Ref: e4910928297
Ref: c-api/init c PyThreadState_Next10928539
Ref: e4a10928539
Node: Thread Local Storage Support10928774
Ref: c-api/init thread-local-storage10928896
Ref: 3fbf10928896
Ref: c-api/init thread-local-storage-support10928896
Ref: 3fc010928896
Node: Thread Specific Storage TSS API10930024
Ref: c-api/init thread-specific-storage-api10930157
Ref: 32010930157
Ref: c-api/init thread-specific-storage-tss-api10930157
Ref: 3fc110930157
Ref: c-api/init c Py_tss_t10930535
Ref: 32110930535
Ref: c-api/init c Py_tss_NEEDS_INIT10930977
Ref: 3fc210930977
Ref: Thread Specific Storage TSS API-Footnote-110931261
Node: Dynamic Allocation10931310
Ref: c-api/init dynamic-allocation10931414
Ref: 3fc310931414
Ref: c-api/init c PyThread_tss_alloc10931695
Ref: 3fc410931695
Ref: c-api/init c PyThread_tss_free10931913
Ref: 3fc510931913
Node: 方法<4>10932335
Ref: c-api/init methods10932439
Ref: 3fc710932439
Ref: c-api/init c PyThread_tss_is_created10932741
Ref: 3fcb10932741
Ref: c-api/init c PyThread_tss_create10932928
Ref: 3fca10932928
Ref: c-api/init c PyThread_tss_delete10933343
Ref: 3fc610933343
Ref: c-api/init c PyThread_tss_set10933773
Ref: 3fc810933773
Ref: c-api/init c PyThread_tss_get10934040
Ref: 3fc910934040
Node: Thread Local Storage TLS API10934275
Ref: c-api/init thread-local-storage-api10934408
Ref: 31f10934408
Ref: c-api/init thread-local-storage-tls-api10934408
Ref: 3fcc10934408
Ref: c-api/init c PyThread_create_key10935008
Ref: 3fcd10935008
Ref: c-api/init c PyThread_delete_key10935050
Ref: 3fce10935050
Ref: c-api/init c PyThread_set_key_value10935100
Ref: 97810935100
Ref: c-api/init c PyThread_get_key_value10935165
Ref: 3fcf10935165
Ref: c-api/init c PyThread_delete_key_value10935219
Ref: 3fd010935219
Ref: c-api/init c PyThread_ReInitTLS10935275
Ref: 3fd110935275
Node: Python初始化配置10935317
Ref: c-api/init_config doc10935457
Ref: 3fd210935457
Ref: c-api/init_config init-config10935457
Ref: 17e10935457
Ref: c-api/init_config python-initialization-configuration10935457
Ref: 3fd310935457
Ref: Python初始化配置-Footnote-110937349
Node: PyWideStringList10937398
Ref: c-api/init_config pywidestringlist10937489
Ref: 3fd510937489
Ref: c-api/init_config c PyWideStringList10937538
Ref: 16310937538
Ref: c-api/init_config c PyWideStringList_Append10937728
Ref: 17510937728
Ref: c-api/init_config c PyWideStringList_Insert10937942
Ref: 17610937942
Ref: c-api/init_config c PyWideStringList length10938381
Ref: 3fd610938381
Ref: c-api/init_config c PyWideStringList items10938445
Ref: 3fd710938445
Node: PyStatus10938508
Ref: c-api/init_config pystatus10938619
Ref: 3fd810938619
Ref: c-api/init_config c PyStatus10938652
Ref: 16210938652
Ref: c-api/init_config c PyStatus exitcode10938872
Ref: 3fd910938872
Ref: c-api/init_config c PyStatus err_msg10938961
Ref: 3fda10938961
Ref: c-api/init_config c PyStatus func10939025
Ref: 3fdb10939025
Ref: c-api/init_config c PyStatus_Ok10939173
Ref: 17410939173
Ref: c-api/init_config c PyStatus_Error10939242
Ref: 16e10939242
Ref: c-api/init_config c PyStatus_NoMemory10939356
Ref: 17310939356
Ref: c-api/init_config c PyStatus_Exit10939464
Ref: 17010939464
Ref: c-api/init_config c PyStatus_Exception10939610
Ref: 16f10939610
Ref: c-api/init_config c PyStatus_IsError10939839
Ref: 17110939839
Ref: c-api/init_config c PyStatus_IsExit10939928
Ref: 17210939928
Ref: c-api/init_config c Py_ExitStatusException10940019
Ref: 17810940019
Node: PyPreConfig10940959
Ref: c-api/init_config pypreconfig10941088
Ref: 3fdc10941088
Ref: c-api/init_config c PyPreConfig10941127
Ref: 16110941127
Ref: c-api/init_config c PyPreConfig_InitPythonConfig10941367
Ref: 16d10941367
Ref: c-api/init_config c PyPreConfig_InitIsolatedConfig10941553
Ref: 16c10941553
Ref: c-api/init_config c PyPreConfig allocator10941767
Ref: 3fdf10941767
Ref: c-api/init_config c PyPreConfig configure_locale10942864
Ref: 3fe110942864
Ref: c-api/init_config c PyPreConfig coerce_c_locale10943070
Ref: 3fe210943070
Ref: c-api/init_config c PyPreConfig coerce_c_locale_warn10943244
Ref: 3fe310943244
Ref: c-api/init_config c PyPreConfig dev_mode10943356
Ref: 3fe410943356
Ref: c-api/init_config c PyPreConfig isolated10943438
Ref: 3fe610943438
Ref: c-api/init_config c PyPreConfig legacy_windows_fs_encoding10943520
Ref: 3fe810943520
Ref: c-api/init_config c PyPreConfig parse_argv10943869
Ref: 3fe910943869
Ref: c-api/init_config c PyPreConfig use_environment10944179
Ref: 3fea10944179
Ref: c-api/init_config c PyPreConfig utf8_mode10944275
Ref: 3fec10944275
Node: Preinitialization with PyPreConfig10944356
Ref: c-api/init_config preinitialization-with-pypreconfig10944485
Ref: 3fed10944485
Ref: c-api/init_config c Py_PreInitialize10944606
Ref: 17a10944606
Ref: c-api/init_config c Py_PreInitializeFromBytesArgs10944740
Ref: 17c10944740
Ref: c-api/init_config c Py_PreInitializeFromArgs10944975
Ref: 17b10944975
Node: PyConfig10946744
Ref: c-api/init_config pyconfig10946890
Ref: 3fee10946890
Ref: c-api/init_config c PyConfig10946923
Ref: 16010946923
Ref: c-api/init_config c PyConfig_InitPythonConfig10947036
Ref: 16610947036
Ref: c-api/init_config c PyConfig_InitIsolatedConfig10947191
Ref: 16510947191
Ref: c-api/init_config c PyConfig_SetString10947350
Ref: 16b10947350
Ref: c-api/init_config c PyConfig_SetBytesString10947596
Ref: 16a10947596
Ref: c-api/init_config c PyConfig_SetArgv10947879
Ref: 16810947879
Ref: c-api/init_config c PyConfig_SetBytesArgv10948102
Ref: 16910948102
Ref: c-api/init_config c PyConfig_SetWideStringList10948358
Ref: 3fd410948358
Ref: c-api/init_config c PyConfig_Read10948638
Ref: 16710948638
Ref: c-api/init_config c PyConfig_Clear10948853
Ref: 16410948853
Ref: c-api/init_config c PyConfig argv10949897
Ref: 3ff010949897
Ref: c-api/init_config c PyConfig base_exec_prefix10950288
Ref: 3ff110950288
Ref: c-api/init_config c PyConfig base_executable10950379
Ref: 3ff210950379
Ref: c-api/init_config c PyConfig base_prefix10950571
Ref: 3ff410950571
Ref: c-api/init_config c PyConfig buffered_stdio10950652
Ref: 3ff510950652
Ref: c-api/init_config c PyConfig bytes_warning10950853
Ref: 3ff610950853
Ref: c-api/init_config c PyConfig check_hash_pycs_mode10951166
Ref: 3ff710951166
Ref: c-api/init_config c PyConfig configure_c_stdio10951503
Ref: 3ff810951503
Ref: c-api/init_config c PyConfig dev_mode10951720
Ref: 3fe510951720
Ref: c-api/init_config c PyConfig dump_refs10951805
Ref: 3ff910951805
Ref: c-api/init_config c PyConfig exec_prefix10952008
Ref: 3ffa10952008
Ref: c-api/init_config c PyConfig executable10952089
Ref: 3ff310952089
Ref: c-api/init_config c PyConfig faulthandler10952167
Ref: 3ffb10952167
Ref: c-api/init_config c PyConfig filesystem_encoding10952289
Ref: 3ffc10952289
Ref: c-api/init_config c PyConfig filesystem_errors10952410
Ref: 3ffd10952410
Ref: c-api/init_config c PyConfig hash_seed10952550
Ref: 3ffe10952550
Ref: c-api/init_config c PyConfig use_hash_seed10952594
Ref: 3fff10952594
Ref: c-api/init_config c PyConfig home10952827
Ref: 400010952827
Ref: c-api/init_config c PyConfig import_time10952995
Ref: 400110952995
Ref: c-api/init_config c PyConfig inspect10953076
Ref: 400210953076
Ref: c-api/init_config c PyConfig install_signal_handlers10953181
Ref: ee310953181
Ref: c-api/init_config c PyConfig interactive10953265
Ref: 400310953265
Ref: c-api/init_config c PyConfig isolated10953325
Ref: 3fe710953325
Ref: c-api/init_config c PyConfig legacy_windows_stdio10953869
Ref: 400510953869
Ref: c-api/init_config c PyConfig malloc_stats10954215
Ref: 400610954215
Ref: c-api/init_config c PyConfig pythonpath_env10954453
Ref: 400710954453
Ref: c-api/init_config c PyConfig module_search_paths10954700
Ref: 400810954700
Ref: c-api/init_config c PyConfig module_search_paths_set10954757
Ref: 400910954757
Ref: c-api/init_config c PyConfig optimization_level10955038
Ref: 400b10955038
Ref: c-api/init_config c PyConfig parse_argv10955314
Ref: 3fef10955314
Ref: c-api/init_config c PyConfig parser_debug10955563
Ref: 400c10955563
Ref: c-api/init_config c PyConfig pathconfig_warnings10955719
Ref: 400d10955719
Ref: c-api/init_config c PyConfig prefix10955979
Ref: 400e10955979
Ref: c-api/init_config c PyConfig program_name10956050
Ref: 400f10956050
Ref: c-api/init_config c PyConfig pycache_prefix10956200
Ref: 401010956200
Ref: c-api/init_config c PyConfig quiet10956391
Ref: 401110956391
Ref: c-api/init_config c PyConfig run_command10956540
Ref: 401210956540
Ref: c-api/init_config c PyConfig run_filename10956671
Ref: 401310956671
Ref: c-api/init_config c PyConfig run_module10956791
Ref: 401410956791
Ref: c-api/init_config c PyConfig show_alloc_count10956920
Ref: 401510956920
Ref: c-api/init_config c PyConfig show_ref_count10957156
Ref: 401610957156
Ref: c-api/init_config c PyConfig site_import10957408
Ref: 401710957408
Ref: c-api/init_config c PyConfig skip_source_first_line10957501
Ref: 401810957501
Ref: c-api/init_config c PyConfig stdio_encoding10957594
Ref: 401910957594
Ref: c-api/init_config c PyConfig stdio_errors10957638
Ref: 401a10957638
Ref: c-api/init_config c PyConfig tracemalloc10957805
Ref: 401b10957805
Ref: c-api/init_config c PyConfig use_environment10957915
Ref: 3feb10957915
Ref: c-api/init_config c PyConfig user_site_directory10958024
Ref: 400410958024
Ref: c-api/init_config c PyConfig verbose10958140
Ref: 401c10958140
Ref: c-api/init_config c PyConfig warnoptions10958217
Ref: 401d10958217
Ref: c-api/init_config c PyConfig write_bytecode10958692
Ref: 401e10958692
Ref: c-api/init_config c PyConfig xoptions10958905
Ref: 401f10958905
Ref: PyConfig-Footnote-110959332
Node: Initialization with PyConfig10959381
Ref: c-api/init_config initialization-with-pyconfig10959515
Ref: 402010959515
Ref: c-api/init_config c Py_InitializeFromConfig10959620
Ref: 17910959620
Node: Isolated Configuration10962322
Ref: c-api/init_config init-isolated-conf10962468
Ref: 3fde10962468
Ref: c-api/init_config isolated-configuration10962468
Ref: 402110962468
Node: Python Configuration10963259
Ref: c-api/init_config init-python-config10963389
Ref: 3fdd10963389
Ref: c-api/init_config python-configuration10963389
Ref: 402210963389
Ref: Python Configuration-Footnote-110964965
Ref: Python Configuration-Footnote-210965014
Node: 路径配置10965063
Ref: c-api/init_config init-path-config10965181
Ref: 400a10965181
Ref: c-api/init_config path-configuration10965181
Ref: 402310965181
Node: Py_RunMain10968580
Ref: c-api/init_config py-runmain10968728
Ref: 402410968728
Ref: c-api/init_config c Py_RunMain10968771
Ref: 17d10968771
Node: Multi-Phase Initialization Private Provisional API10969363
Ref: c-api/init_config multi-phase-initialization-private-provisional-api10969490
Ref: 402510969490
Ref: c-api/init_config c _Py_InitializeMain10970668
Ref: 402610970668
Ref: Multi-Phase Initialization Private Provisional API-Footnote-110972661
Ref: Multi-Phase Initialization Private Provisional API-Footnote-210972710
Node: 内存管理10972759
Ref: c-api/memory doc10972890
Ref: 402710972890
Ref: c-api/memory memory10972890
Ref: 3fe010972890
Ref: c-api/memory memory-management10972890
Ref: 402810972890
Node: 概述<16>10973137
Ref: c-api/memory memoryoverview10973223
Ref: 402910973223
Ref: c-api/memory overview10973223
Ref: 402a10973223
Node: 原始内存接口10976582
Ref: c-api/memory raw-memory-interface10976689
Ref: 402b10976689
Ref: c-api/memory c PyMem_RawMalloc10977072
Ref: 97510977072
Ref: c-api/memory c PyMem_RawCalloc10977443
Ref: 7ae10977443
Ref: c-api/memory c PyMem_RawRealloc10977893
Ref: 97610977893
Ref: c-api/memory c PyMem_RawFree10978624
Ref: 3c4810978624
Node: 内存接口10979077
Ref: c-api/memory memory-interface10979189
Ref: 402c10979189
Ref: c-api/memory memoryinterface10979189
Ref: 402d10979189
Ref: c-api/memory c PyMem_Malloc10979630
Ref: 50d10979630
Ref: c-api/memory c PyMem_Calloc10979995
Ref: 7af10979995
Ref: c-api/memory c PyMem_Realloc10980439
Ref: 97710980439
Ref: c-api/memory c PyMem_Free10981152
Ref: db110981152
Ref: c-api/memory c PyMem_New10981680
Ref: 402e10981680
Ref: c-api/memory c PyMem_Resize10981936
Ref: 402f10981936
Ref: c-api/memory c PyMem_Del10982410
Ref: 403010982410
Node: 对象分配器10982940
Ref: c-api/memory object-allocators10983055
Ref: 403110983055
Ref: c-api/memory c PyObject_Malloc10983406
Ref: 51010983406
Ref: c-api/memory c PyObject_Calloc10983777
Ref: 7b010983777
Ref: c-api/memory c PyObject_Realloc10984227
Ref: db210984227
Ref: c-api/memory c PyObject_Free10984958
Ref: 50c10984958
Node: 默认内存分配器10985411
Ref: c-api/memory default-memory-allocators10985538
Ref: 136d10985538
Ref: c-api/memory id110985538
Ref: 403210985538
Node: 自定义内存分配器10987809
Ref: c-api/memory customize-memory-allocators10987939
Ref: 403310987939
Ref: c-api/memory c PyMemAllocatorEx10988015
Ref: 7d310988015
Ref: c-api/memory c PyMemAllocatorDomain10989748
Ref: 403410989748
Ref: c-api/memory c PYMEM_DOMAIN_RAW10989839
Ref: 136e10989839
Ref: c-api/memory c PYMEM_DOMAIN_MEM10990075
Ref: 51110990075
Ref: c-api/memory c PYMEM_DOMAIN_OBJ10990298
Ref: 50f10990298
Ref: c-api/memory c PyMem_GetAllocator10990533
Ref: 3f7f10990533
Ref: c-api/memory c PyMem_SetAllocator10990687
Ref: 3f7d10990687
Ref: c-api/memory c PyMem_SetupDebugHooks10991282
Ref: 51210991282
Node: pymalloc 分配器10993317
Ref: c-api/memory pymalloc10993443
Ref: 5ca10993443
Ref: c-api/memory the-pymalloc-allocator10993443
Ref: 403510993443
Node: 自定义 pymalloc Arena 分配器10994253
Ref: c-api/memory customize-pymalloc-arena-allocator10994342
Ref: 403610994342
Ref: c-api/memory c PyObjectArenaAllocator10994444
Ref: 403710994444
Ref: c-api/memory c PyObject_GetArenaAllocator10995463
Ref: 3f8010995463
Ref: c-api/memory c PyObject_SetArenaAllocator10995585
Ref: 3f7e10995585
Node: tracemalloc C API10995707
Ref: c-api/memory tracemalloc-c-api10995819
Ref: 403810995819
Ref: c-api/memory c PyTraceMalloc_Track10995889
Ref: 42c10995889
Ref: c-api/memory c PyTraceMalloc_Untrack10996293
Ref: 42d10996293
Node: 例子<34>10996607
Ref: c-api/memory examples10996692
Ref: 403910996692
Ref: c-api/memory memoryexamples10996692
Ref: 403a10996692
Node: 对象实现支持10998520
Ref: c-api/objimpl doc10998654
Ref: 403b10998654
Ref: c-api/objimpl newtypes10998654
Ref: 403c10998654
Ref: c-api/objimpl object-implementation-support10998654
Ref: 403d10998654
Node: 在堆上分配对象10999105
Ref: c-api/allocation doc10999211
Ref: 403e10999211
Ref: c-api/allocation allocating-objects10999211
Ref: 403f10999211
Ref: c-api/allocation allocating-objects-on-the-heap10999211
Ref: 404010999211
Ref: c-api/allocation c _PyObject_New10999263
Ref: 404110999263
Ref: c-api/allocation c _PyObject_NewVar10999359
Ref: 404210999359
Ref: c-api/allocation c PyObject_Init10999488
Ref: 27010999488
Ref: c-api/allocation c PyObject_InitVar10999855
Ref: 404310999855
Ref: c-api/allocation c PyObject_New11000119
Ref: 2d311000119
Ref: c-api/allocation c PyObject_NewVar11000514
Ref: 2d411000514
Ref: c-api/allocation c PyObject_Del11001194
Ref: e1e11001194
Ref: c-api/allocation c _Py_NoneStruct11001588
Ref: 404411001588
Node: 公用对象的结构11001871
Ref: c-api/structures doc11002001
Ref: 404511002001
Ref: c-api/structures common-object-structures11002001
Ref: 404611002001
Ref: c-api/structures common-structs11002001
Ref: 404711002001
Ref: c-api/structures c PyObject11002464
Ref: 4c211002464
Ref: c-api/structures c PyVarObject11003046
Ref: 404811003046
Ref: c-api/structures c PyObject_HEAD11003428
Ref: c7a11003428
Ref: c-api/structures c PyObject_VAR_HEAD11003687
Ref: 404a11003687
Ref: c-api/structures c Py_TYPE11003988
Ref: 3b3911003988
Ref: c-api/structures c Py_REFCNT11004152
Ref: 3b3811004152
Ref: c-api/structures c Py_SIZE11004322
Ref: 404911004322
Ref: c-api/structures c PyObject_HEAD_INIT11004489
Ref: 404b11004489
Ref: c-api/structures c PyVarObject_HEAD_INIT11004705
Ref: 404c11004705
Ref: c-api/structures c PyCFunction11004980
Ref: de311004980
Ref: c-api/structures c PyCFunctionWithKeywords11005421
Ref: 404d11005421
Ref: c-api/structures c _PyCFunctionFast11005584
Ref: 404e11005584
Ref: c-api/structures c _PyCFunctionFastWithKeywords11005730
Ref: 404f11005730
Ref: c-api/structures c PyMethodDef11005899
Ref: e2311005899
Ref: c-api/structures METH_VARARGS11007855
Ref: e5011007855
Ref: c-api/structures METH_FASTCALL11008788
Ref: fc811008788
Ref: c-api/structures METH_NOARGS11009891
Ref: e2011009891
Ref: c-api/structures METH_O11010292
Ref: e4f11010292
Ref: c-api/structures METH_CLASS11010883
Ref: e2111010883
Ref: c-api/structures METH_STATIC11011158
Ref: e2211011158
Ref: c-api/structures METH_COEXIST11011545
Ref: 405011011545
Ref: c-api/structures c PyMemberDef11012213
Ref: 42e11012213
Ref: c-api/structures c PyGetSetDef11016349
Ref: 42f11016349
Node: 类型对象<3>11018489
Ref: c-api/typeobj doc11018622
Ref: 405111018622
Ref: c-api/typeobj type-objects11018622
Ref: 405211018622
Ref: c-api/typeobj type-structs11018622
Ref: 3b3a11018622
Node: 快速参考11019842
Ref: c-api/typeobj quick-reference11019938
Ref: 405411019938
Node: "tp 槽"11020034
Ref: c-api/typeobj tp-slots11020109
Ref: 405511020109
Ref: c-api/typeobj tp-slots-table11020109
Ref: 405611020109
Ref: "tp 槽"-Footnote-111033366
Ref: "tp 槽"-Footnote-211033631
Node: sub-slots11034402
Ref: c-api/typeobj id311034499
Ref: 407d11034499
Ref: c-api/typeobj sub-slots11034499
Ref: 405c11034499
Node: slot typedefs11044629
Ref: c-api/typeobj slot-typedefs11044709
Ref: 40b711044709
Ref: c-api/typeobj slot-typedefs-table11044709
Ref: 405711044709
Node: PyTypeObject Definition11052525
Ref: c-api/typeobj pytypeobject-definition11052644
Ref: 40ba11052644
Node: PyObject Slots11055469
Ref: c-api/typeobj pyobject-slots11055593
Ref: 40bb11055593
Ref: c-api/typeobj c PyObject _ob_next11056015
Ref: 40bc11056015
Ref: c-api/typeobj c PyObject _ob_prev11056057
Ref: 40bd11056057
Ref: c-api/typeobj c PyObject ob_refcnt11056807
Ref: 40be11056807
Ref: c-api/typeobj c PyObject ob_type11057300
Ref: 40bf11057300
Node: PyVarObject Slots11058387
Ref: c-api/typeobj pyvarobject-slots11058506
Ref: 40c011058506
Ref: c-api/typeobj c PyVarObject ob_size11058561
Ref: 40c111058561
Node: PyTypeObject Slots11058850
Ref: c-api/typeobj pytypeobject-slots11058965
Ref: 40c211058965
Ref: c-api/typeobj c PyTypeObject tp_name11059314
Ref: 3b5e11059314
Ref: c-api/typeobj c PyTypeObject tp_basicsize11061019
Ref: 3b3c11061019
Ref: c-api/typeobj c PyTypeObject tp_itemsize11061070
Ref: 3b3b11061070
Ref: c-api/typeobj c PyTypeObject tp_dealloc11063719
Ref: 3b4211063719
Ref: c-api/typeobj c PyTypeObject tp_vectorcall_offset11065771
Ref: 3cc511065771
Ref: c-api/typeobj c PyVectorcall_Call11066905
Ref: 40c511066905
Ref: c-api/typeobj c PyTypeObject tp_getattr11068524
Ref: 3b6511068524
Ref: c-api/typeobj c PyTypeObject tp_setattr11069245
Ref: 3b6611069245
Ref: c-api/typeobj c PyTypeObject tp_as_async11069986
Ref: 405b11069986
Ref: c-api/typeobj c PyTypeObject tp_repr11070521
Ref: 3b5d11070521
Ref: c-api/typeobj c PyTypeObject tp_as_number11071470
Ref: 405e11071470
Ref: c-api/typeobj c PyTypeObject tp_as_sequence11071871
Ref: 405f11071871
Ref: c-api/typeobj c PyTypeObject tp_as_mapping11072282
Ref: 406011072282
Ref: c-api/typeobj c PyTypeObject tp_hash11072688
Ref: 3b6e11072688
Ref: c-api/typeobj c PyTypeObject tp_call11074276
Ref: 3b6f11074276
Ref: c-api/typeobj c PyTypeObject tp_str11074676
Ref: 3b5f11074676
Ref: c-api/typeobj c PyTypeObject tp_getattro11075619
Ref: 3b6211075619
Ref: c-api/typeobj c PyTypeObject tp_setattro11076482
Ref: 3b6311076482
Ref: c-api/typeobj c PyTypeObject tp_as_buffer11077476
Ref: 406511077476
Ref: c-api/typeobj c PyTypeObject tp_flags11077876
Ref: 3d6411077876
Ref: c-api/typeobj Py_TPFLAGS_HEAPTYPE11079768
Ref: 3d6c11079768
Ref: c-api/typeobj Py_TPFLAGS_BASETYPE11080415
Ref: 3b4a11080415
Ref: c-api/typeobj Py_TPFLAGS_READY11080690
Ref: 40cb11080690
Ref: c-api/typeobj Py_TPFLAGS_READYING11080882
Ref: 40cc11080882
Ref: c-api/typeobj Py_TPFLAGS_HAVE_GC11081083
Ref: 3b5111081083
Ref: c-api/typeobj Py_TPFLAGS_DEFAULT11082069
Ref: 3b3d11082069
Ref: c-api/typeobj Py_TPFLAGS_METHOD_DESCRIPTOR11082451
Ref: 40ce11082451
Ref: c-api/typeobj Py_TPFLAGS_LONG_SUBCLASS11083312
Ref: 40cf11083312
Ref: c-api/typeobj Py_TPFLAGS_LIST_SUBCLASS11083355
Ref: 40d011083355
Ref: c-api/typeobj Py_TPFLAGS_TUPLE_SUBCLASS11083398
Ref: 40d111083398
Ref: c-api/typeobj Py_TPFLAGS_BYTES_SUBCLASS11083442
Ref: 40d211083442
Ref: c-api/typeobj Py_TPFLAGS_UNICODE_SUBCLASS11083486
Ref: 40d311083486
Ref: c-api/typeobj Py_TPFLAGS_DICT_SUBCLASS11083532
Ref: 40d411083532
Ref: c-api/typeobj Py_TPFLAGS_BASE_EXC_SUBCLASS11083575
Ref: 40d511083575
Ref: c-api/typeobj Py_TPFLAGS_TYPE_SUBCLASS11083622
Ref: 40d611083622
Ref: c-api/typeobj Py_TPFLAGS_HAVE_FINALIZE11084182
Ref: 2d911084182
Ref: c-api/typeobj _Py_TPFLAGS_HAVE_VECTORCALL11084553
Ref: 40c311084553
Ref: c-api/typeobj c PyTypeObject tp_doc11085453
Ref: 3b3e11085453
Ref: c-api/typeobj c PyTypeObject tp_traverse11085765
Ref: 36c711085765
Ref: c-api/typeobj c PyTypeObject tp_clear11088682
Ref: 3b5b11088682
Ref: c-api/typeobj c PyTypeObject tp_richcompare11092012
Ref: 3b6811092012
Ref: c-api/typeobj c Py_RETURN_RICHCOMPARE11093517
Ref: 42a11093517
Ref: c-api/typeobj c PyTypeObject tp_weaklistoffset11094748
Ref: 3b7111094748
Ref: c-api/typeobj c PyTypeObject tp_iter11096531
Ref: e3811096531
Ref: c-api/typeobj c PyTypeObject tp_iternext11097005
Ref: e3911097005
Ref: c-api/typeobj c PyTypeObject tp_methods11097797
Ref: 3b4911097797
Ref: c-api/typeobj c PyTypeObject tp_members11098293
Ref: 3b4711098293
Ref: c-api/typeobj c PyTypeObject tp_getset11098825
Ref: 3b4d11098825
Ref: c-api/typeobj c PyTypeObject tp_base11099349
Ref: 3b5311099349
Ref: c-api/typeobj c PyTypeObject tp_dict11100641
Ref: 3d7811100641
Ref: c-api/typeobj c PyTypeObject tp_descr_get11101618
Ref: 406c11101618
Ref: c-api/typeobj c PyTypeObject tp_descr_set11101910
Ref: 406e11101910
Ref: c-api/typeobj c PyTypeObject tp_dictoffset11102301
Ref: 3d7d11102301
Ref: c-api/typeobj c PyTypeObject tp_init11105559
Ref: 3b4611105559
Ref: c-api/typeobj c PyTypeObject tp_alloc11107015
Ref: 3b4411107015
Ref: c-api/typeobj c PyTypeObject tp_new11107700
Ref: 3b3f11107700
Ref: c-api/typeobj c PyTypeObject tp_free11109264
Ref: 3b4311109264
Ref: c-api/typeobj c PyTypeObject tp_is_gc11109948
Ref: 407411109948
Ref: c-api/typeobj c PyTypeObject tp_bases11111099
Ref: 407511111099
Ref: c-api/typeobj c PyTypeObject tp_mro11111347
Ref: 3d7911111347
Ref: c-api/typeobj c PyTypeObject tp_cache11111665
Ref: 3d7a11111665
Ref: c-api/typeobj c PyTypeObject tp_subclasses11111802
Ref: 3d7b11111802
Ref: c-api/typeobj c PyTypeObject tp_weaklist11111975
Ref: 3d7c11111975
Ref: c-api/typeobj c PyTypeObject tp_del11112194
Ref: 407611112194
Ref: c-api/typeobj c PyTypeObject tp_version_tag11112310
Ref: 407711112310
Ref: c-api/typeobj c PyTypeObject tp_finalize11112485
Ref: 2d811112485
Ref: c-api/typeobj c PyTypeObject tp_allocs11114197
Ref: 407811114197
Ref: c-api/typeobj c PyTypeObject tp_frees11114275
Ref: 407911114275
Ref: c-api/typeobj c PyTypeObject tp_maxalloc11114346
Ref: 407a11114346
Ref: c-api/typeobj c PyTypeObject tp_prev11114445
Ref: 407b11114445
Ref: c-api/typeobj c PyTypeObject tp_next11114588
Ref: 407c11114588
Ref: PyTypeObject Slots-Footnote-111115420
Node: Heap Types11115469
Ref: c-api/typeobj heap-types11115558
Ref: 3d6a11115558
Ref: c-api/typeobj id411115558
Ref: 40c611115558
Node: Number Object Structures11116722
Ref: c-api/typeobj number-object-structures11116859
Ref: 40d711116859
Ref: c-api/typeobj number-structs11116859
Ref: 40c811116859
Ref: c-api/typeobj c PyNumberMethods11116924
Ref: d8911116924
Ref: c-api/typeobj c PyNumberMethods nb_add11119353
Ref: 3d7611119353
Ref: c-api/typeobj c PyNumberMethods nb_subtract11119402
Ref: 408411119402
Ref: c-api/typeobj c PyNumberMethods nb_multiply11119456
Ref: 408611119456
Ref: c-api/typeobj c PyNumberMethods nb_remainder11119510
Ref: 408811119510
Ref: c-api/typeobj c PyNumberMethods nb_divmod11119565
Ref: 408a11119565
Ref: c-api/typeobj c PyNumberMethods nb_power11119617
Ref: 408b11119617
Ref: c-api/typeobj c PyNumberMethods nb_negative11119669
Ref: 408d11119669
Ref: c-api/typeobj c PyNumberMethods nb_positive11119722
Ref: 408e11119722
Ref: c-api/typeobj c PyNumberMethods nb_absolute11119775
Ref: 408f11119775
Ref: c-api/typeobj c PyNumberMethods nb_bool11119828
Ref: 409011119828
Ref: c-api/typeobj c PyNumberMethods nb_invert11119875
Ref: 409111119875
Ref: c-api/typeobj c PyNumberMethods nb_lshift11119926
Ref: 409211119926
Ref: c-api/typeobj c PyNumberMethods nb_rshift11119978
Ref: 409411119978
Ref: c-api/typeobj c PyNumberMethods nb_and11120030
Ref: 409611120030
Ref: c-api/typeobj c PyNumberMethods nb_xor11120079
Ref: 409811120079
Ref: c-api/typeobj c PyNumberMethods nb_or11120128
Ref: 409a11120128
Ref: c-api/typeobj c PyNumberMethods nb_int11120176
Ref: 409c11120176
Ref: c-api/typeobj c PyNumberMethods nb_reserved11120224
Ref: 409d11120224
Ref: c-api/typeobj c PyNumberMethods nb_float11120273
Ref: 409e11120273
Ref: c-api/typeobj c PyNumberMethods nb_inplace_add11120323
Ref: 408311120323
Ref: c-api/typeobj c PyNumberMethods nb_inplace_subtract11120380
Ref: 408511120380
Ref: c-api/typeobj c PyNumberMethods nb_inplace_multiply11120442
Ref: 408711120442
Ref: c-api/typeobj c PyNumberMethods nb_inplace_remainder11120504
Ref: 408911120504
Ref: c-api/typeobj c PyNumberMethods nb_inplace_power11120567
Ref: 408c11120567
Ref: c-api/typeobj c PyNumberMethods nb_inplace_lshift11120627
Ref: 409311120627
Ref: c-api/typeobj c PyNumberMethods nb_inplace_rshift11120687
Ref: 409511120687
Ref: c-api/typeobj c PyNumberMethods nb_inplace_and11120747
Ref: 409711120747
Ref: c-api/typeobj c PyNumberMethods nb_inplace_xor11120804
Ref: 409911120804
Ref: c-api/typeobj c PyNumberMethods nb_inplace_or11120861
Ref: 409b11120861
Ref: c-api/typeobj c PyNumberMethods nb_floor_divide11120917
Ref: 409f11120917
Ref: c-api/typeobj c PyNumberMethods nb_true_divide11120975
Ref: 40a111120975
Ref: c-api/typeobj c PyNumberMethods nb_inplace_floor_divide11121032
Ref: 40a011121032
Ref: c-api/typeobj c PyNumberMethods nb_inplace_true_divide11121098
Ref: 40a211121098
Ref: c-api/typeobj c PyNumberMethods nb_index11121163
Ref: 40a311121163
Ref: c-api/typeobj c PyNumberMethods nb_matrix_multiply11121213
Ref: 40a411121213
Ref: c-api/typeobj c PyNumberMethods nb_inplace_matrix_multiply11121274
Ref: 40a511121274
Node: Mapping Object Structures11121343
Ref: c-api/typeobj mapping-object-structures11121491
Ref: 40d811121491
Ref: c-api/typeobj mapping-structs11121491
Ref: 40ca11121491
Ref: c-api/typeobj c PyMappingMethods11121558
Ref: 3b6d11121558
Ref: c-api/typeobj c PyMappingMethods mp_length11121727
Ref: 40a611121727
Ref: c-api/typeobj c PyMappingMethods mp_subscript11121982
Ref: 40a811121982
Ref: c-api/typeobj c PyMappingMethods mp_ass_subscript11122341
Ref: 40a911122341
Node: Sequence Object Structures11122781
Ref: c-api/typeobj sequence-object-structures11122929
Ref: 40d911122929
Ref: c-api/typeobj sequence-structs11122929
Ref: 40c911122929
Ref: c-api/typeobj c PySequenceMethods11122998
Ref: 3b6c11122998
Ref: c-api/typeobj c PySequenceMethods sq_length11123146
Ref: 3d7711123146
Ref: c-api/typeobj c PySequenceMethods sq_concat11123451
Ref: 40ab11123451
Ref: c-api/typeobj c PySequenceMethods sq_repeat11123717
Ref: 40ac11123717
Ref: c-api/typeobj c PySequenceMethods sq_item11123997
Ref: 40ae11123997
Ref: c-api/typeobj c PySequenceMethods sq_ass_item11124703
Ref: 40af11124703
Ref: c-api/typeobj c PySequenceMethods sq_contains11125157
Ref: 40b111125157
Ref: c-api/typeobj c PySequenceMethods sq_inplace_concat11125459
Ref: 40b311125459
Ref: c-api/typeobj c PySequenceMethods sq_inplace_repeat11125973
Ref: 40b411125973
Node: Buffer Object Structures11126500
Ref: c-api/typeobj buffer-object-structures11126646
Ref: 40da11126646
Ref: c-api/typeobj buffer-structs11126646
Ref: 3d1c11126646
Ref: c-api/typeobj c PyBufferProcs11126711
Ref: 406611126711
Ref: c-api/typeobj c PyBufferProcs bf_getbuffer11126943
Ref: 3d7e11126943
Ref: c-api/typeobj c PyBufferProcs bf_releasebuffer11128835
Ref: 3c7f11128835
Node: Async Object Structures11129947
Ref: c-api/typeobj async-object-structures11130085
Ref: 40db11130085
Ref: c-api/typeobj async-structs11130085
Ref: 40c711130085
Ref: c-api/typeobj c PyAsyncMethods11130167
Ref: 3d7511130167
Ref: c-api/typeobj c PyAsyncMethods am_await11130549
Ref: 407e11130549
Ref: c-api/typeobj c PyAsyncMethods am_aiter11130891
Ref: 408011130891
Ref: c-api/typeobj c PyAsyncMethods am_anext11131238
Ref: 408111131238
Node: Slot Type typedefs11131511
Ref: c-api/typeobj id511131635
Ref: 40b911131635
Ref: c-api/typeobj slot-type-typedefs11131635
Ref: 40dc11131635
Ref: c-api/typeobj c allocfunc11131688
Ref: 407111131688
Ref: c-api/typeobj c destructor11132657
Ref: 405811132657
Ref: c-api/typeobj c vectorcallfunc11132704
Ref: 40c411132704
Ref: c-api/typeobj c freefunc11133004
Ref: 407311133004
Ref: c-api/typeobj c newfunc11133076
Ref: 407211133076
Ref: c-api/typeobj c initproc11133179
Ref: 407011133179
Ref: c-api/typeobj c reprfunc11133278
Ref: 405d11133278
Ref: c-api/typeobj c getattrfunc11133359
Ref: 405911133359
Ref: c-api/typeobj c setattrfunc11133490
Ref: 405a11133490
Ref: c-api/typeobj c getattrofunc11133710
Ref: 406311133710
Ref: c-api/typeobj c setattrofunc11133881
Ref: 406411133881
Ref: c-api/typeobj c descrgetfunc11134141
Ref: 406d11134141
Ref: c-api/typeobj c descrsetfunc11134258
Ref: 406f11134258
Ref: c-api/typeobj c hashfunc11134359
Ref: 406111134359
Ref: c-api/typeobj c richcmpfunc11134440
Ref: 406911134440
Ref: c-api/typeobj c getiterfunc11134548
Ref: 406a11134548
Ref: c-api/typeobj c iternextfunc11134631
Ref: 406b11134631
Ref: c-api/typeobj c lenfunc11134719
Ref: 40a711134719
Ref: c-api/typeobj c getbufferproc11134769
Ref: 40b511134769
Ref: c-api/typeobj c releasebufferproc11134836
Ref: 40b611134836
Ref: c-api/typeobj c unaryfunc11134903
Ref: 407f11134903
Ref: c-api/typeobj c binaryfunc11134954
Ref: 408211134954
Ref: c-api/typeobj c ternaryfunc11135018
Ref: 406211135018
Ref: c-api/typeobj c ssizeargfunc11135105
Ref: 40ad11135105
Ref: c-api/typeobj c ssizeobjargproc11135171
Ref: 40b011135171
Ref: c-api/typeobj c objobjproc11135234
Ref: 40b211135234
Ref: c-api/typeobj c objobjargproc11135292
Ref: 40aa11135292
Node: 例子<35>11135365
Ref: c-api/typeobj examples11135505
Ref: 40dd11135505
Ref: c-api/typeobj typedef-examples11135505
Ref: 405311135505
Node: 使对象类型支持循环垃圾回收11140827
Ref: c-api/gcsupport doc11140940
Ref: 40de11140940
Ref: c-api/gcsupport supporting-cycle-detection11140940
Ref: 40cd11140940
Ref: c-api/gcsupport supporting-cyclic-garbage-collection11140940
Ref: 40df11140940
Ref: c-api/gcsupport c PyObject_GC_New11142086
Ref: 2d511142086
Ref: c-api/gcsupport c PyObject_GC_NewVar11142277
Ref: 2d611142277
Ref: c-api/gcsupport c PyObject_GC_Resize11142501
Ref: 40e011142501
Ref: c-api/gcsupport c PyObject_GC_Track11142789
Ref: e4c11142789
Ref: c-api/gcsupport c PyObject_GC_Del11143423
Ref: e4b11143423
Ref: c-api/gcsupport c PyObject_GC_UnTrack11143613
Ref: e4d11143613
Ref: c-api/gcsupport c visitproc11144201
Ref: 40b811144201
Ref: c-api/gcsupport c traverseproc11144653
Ref: 406711144653
Ref: c-api/gcsupport c Py_VISIT11145302
Ref: 3b4f11145302
Ref: c-api/gcsupport c inquiry11145910
Ref: 406811145910
Node: API 和 ABI 版本管理11146325
Ref: c-api/apiabiversion doc11146438
Ref: 40e111146438
Ref: c-api/apiabiversion api-and-abi-versioning11146438
Ref: 40e211146438
Ref: c-api/apiabiversion apiabiversion11146438
Ref: 363f11146438
Ref: API 和 ABI 版本管理-Footnote-111148424
Node: 分发 Python 模块11148496
Ref: distributing/index doc11148619
Ref: 40e311148619
Ref: distributing/index distributing-index11148619
Ref: 7ff11148619
Ref: distributing/index distributing-python-modules11148619
Ref: 40e411148619
Node: 关键术语11149590
Ref: distributing/index key-terms11149689
Ref: 40e511149689
Ref: 关键术语-Footnote-111151378
Ref: 关键术语-Footnote-211151403
Ref: 关键术语-Footnote-311151432
Ref: 关键术语-Footnote-411151464
Ref: 关键术语-Footnote-511151500
Ref: 关键术语-Footnote-611151553
Ref: 关键术语-Footnote-711151591
Ref: 关键术语-Footnote-811151644
Node: 开源许可与协作11151693
Ref: distributing/index open-source-licensing-and-collaboration11151819
Ref: 40e611151819
Ref: distributing/index wheel11151819
Ref: 40e711151819
Node: 安装相关工具11152567
Ref: distributing/index installing-the-tools11152713
Ref: 40e811152713
Ref: 安装相关工具-Footnote-111153469
Node: 阅读 Python 打包用户指南11153567
Ref: distributing/index publishing-python-packages11153708
Ref: 40e911153708
Ref: distributing/index reading-the-python-packaging-user-guide11153708
Ref: 40ea11153708
Ref: 阅读 Python 打包用户指南-Footnote-111154049
Ref: 阅读 Python 打包用户指南-Footnote-211154119
Ref: 阅读 Python 打包用户指南-Footnote-311154213
Ref: 阅读 Python 打包用户指南-Footnote-411154315
Node: 我该如何 ？11154375
Ref: distributing/index how-do-i11154489
Ref: 40eb11154489
Ref: distributing/index the-pypirc-file11154489
Ref: 40ec11154489
Node: 为我的项目选择一个名字？11154756
Ref: distributing/index choose-a-name-for-my-project11154887
Ref: 40ed11154887
Node: 创建和分发二进制扩展？11155430
Ref: distributing/index create-and-distribute-binary-extensions11155561
Ref: 40ee11155561
Ref: 创建和分发二进制扩展？-Footnote-111155905
Node: 安装 Python 模块11155978
Ref: installing/index doc11156095
Ref: 40ef11156095
Ref: installing/index installing-index11156095
Ref: 7fe11156095
Ref: installing/index installing-python-modules11156095
Ref: 40f011156095
Node: 关键术语<2>11157056
Ref: installing/index key-terms11157152
Ref: 40f111157152
Ref: 关键术语<2>-Footnote-111158932
Ref: 关键术语<2>-Footnote-211158957
Ref: 关键术语<2>-Footnote-311158986
Ref: 关键术语<2>-Footnote-411159018
Ref: 关键术语<2>-Footnote-511159054
Node: 基本使用<2>11159134
Ref: installing/index basic-usage11159255
Ref: 40f211159255
Ref: 基本使用<2>-Footnote-111160687
Ref: 基本使用<2>-Footnote-211160724
Node: 我应如何 ？11160773
Ref: installing/index how-do-i11160900
Ref: 40f311160900
Node: 在 Python 3 4 之前的 Python 版本中安装 pip ？11161405
Ref: installing/index install-pip-in-versions-of-python-prior-to-python-3-411161558
Ref: 40f411161558
Ref: 在 Python 3 4 之前的 Python 版本中安装 pip ？-Footnote-111161976
Node: 只为当前用户安装软件包？11162063
Ref: installing/index install-packages-just-for-the-current-user11162266
Ref: 40f511162266
Node: 安装科学计算类 Python 软件包？11162482
Ref: installing/index install-scientific-python-packages11162674
Ref: 40f611162674
Ref: 安装科学计算类 Python 软件包？-Footnote-111163150
Ref: 安装科学计算类 Python 软件包？-Footnote-211163196
Node: 使用并行安装的多个 Python 版本？11163242
Ref: installing/index work-with-multiple-versions-of-python-installed-in-parallel11163389
Ref: 40f711163389
Node: 常见的安装问题11164302
Ref: installing/index common-installation-issues11164405
Ref: 40f811164405
Node: 在 Linux 的系统 Python 版本上安装11164558
Ref: installing/index installing-into-the-system-python-on-linux11164680
Ref: 40f911164680
Node: 未安装 pip11165182
Ref: installing/index pip-not-installed11165340
Ref: 40fa11165340
Ref: 未安装 pip-Footnote-111165570
Node: 安装二进制编译扩展11165672
Ref: installing/index installing-binary-extensions11165779
Ref: 40fb11165779
Ref: 安装二进制编译扩展-Footnote-111166608
Ref: 安装二进制编译扩展-Footnote-211166654
Node: Python 常用指引11166703
Ref: howto/index doc11166819
Ref: 40fc11166819
Ref: howto/index python-howtos11166819
Ref: 40fd11166819
Node: 将 Python 2 代码迁移到 Python 311167595
Ref: howto/pyporting doc11167730
Ref: 40fe11167730
Ref: howto/pyporting porting-python-2-code-to-python-311167730
Ref: 40ff11167730
Ref: howto/pyporting pyporting-howto11167730
Ref: c8511167730
Ref: 将 Python 2 代码迁移到 Python 3-Footnote-111168550
Ref: 将 Python 2 代码迁移到 Python 3-Footnote-211168654
Ref: 将 Python 2 代码迁移到 Python 3-Footnote-311168700
Node: 简要说明11168764
Ref: howto/pyporting the-short-explanation11168865
Ref: 410011168865
Ref: 简要说明-Footnote-111170024
Ref: 简要说明-Footnote-211170066
Ref: 简要说明-Footnote-311170125
Ref: 简要说明-Footnote-411170174
Ref: 简要说明-Footnote-511170214
Ref: 简要说明-Footnote-611170262
Ref: 简要说明-Footnote-711170299
Node: 详情11170329
Ref: howto/pyporting details11170430
Ref: 410111170430
Node: 删除对Python 2 6及更早版本的支持11171899
Ref: howto/pyporting drop-support-for-python-2-6-and-older11172064
Ref: 410211172064
Ref: 删除对Python 2 6及更早版本的支持-Footnote-111173390
Ref: 删除对Python 2 6及更早版本的支持-Footnote-211173427
Node: Make sure you specify the proper version support in your setup py file11173467
Ref: howto/pyporting make-sure-you-specify-the-proper-version-support-in-your-setup-py-file11173665
Ref: 410311173665
Ref: Make sure you specify the proper version support in your setup py file-Footnote-111174267
Node: 良好的测试覆盖率11174304
Ref: howto/pyporting have-good-test-coverage11174494
Ref: 410411174494
Ref: 良好的测试覆盖率-Footnote-111175174
Node: 了解Python 2 和 3之间的区别11175216
Ref: howto/pyporting learn-the-differences-between-python-2-311175348
Ref: 410511175348
Ref: 了解Python 2 和 3之间的区别-Footnote-111175987
Ref: 了解Python 2 和 3之间的区别-Footnote-211176022
Node: 更新代码11176078
Ref: howto/pyporting update-your-code11176219
Ref: 410611176219
Ref: 更新代码-Footnote-111178482
Ref: 更新代码-Footnote-211178541
Ref: 更新代码-Footnote-311178590
Ref: 更新代码-Footnote-411178649
Ref: 更新代码-Footnote-511178698
Node: 除法11178735
Ref: howto/pyporting division11178823
Ref: 410711178823
Node: 文本与二进制数据11179873
Ref: howto/pyporting text-versus-binary-data11180020
Ref: 410811180020
Ref: 文本与二进制数据-Footnote-111186538
Node: Use feature detection instead of version detection11186575
Ref: howto/pyporting use-feature-detection-instead-of-version-detection11186707
Ref: 410911186707
Ref: Use feature detection instead of version detection-Footnote-111188410
Node: Prevent compatibility regressions11188454
Ref: howto/pyporting prevent-compatibility-regressions11188606
Ref: 410a11188606
Ref: Prevent compatibility regressions-Footnote-111189948
Ref: Prevent compatibility regressions-Footnote-211189988
Ref: Prevent compatibility regressions-Footnote-311190037
Node: Check which dependencies block your transition11190096
Ref: howto/pyporting check-which-dependencies-block-your-transition11190294
Ref: 410b11190294
Ref: Check which dependencies block your transition-Footnote-111191156
Node: Update your setup py file to denote Python 3 compatibility11191204
Ref: howto/pyporting update-your-setup-py-file-to-denote-python-3-compatibility11191414
Ref: 410c11191414
Node: Use continuous integration to stay compatible11191928
Ref: howto/pyporting use-continuous-integration-to-stay-compatible11192131
Ref: 410d11192131
Ref: Use continuous integration to stay compatible-Footnote-111193443
Node: 考虑使用可选的静态类型检查11193480
Ref: howto/pyporting consider-using-optional-static-type-checking11193616
Ref: 410e11193616
Ref: 考虑使用可选的静态类型检查-Footnote-111194374
Ref: 考虑使用可选的静态类型检查-Footnote-211194404
Node: 将扩展模块移植到 Python 311194445
Ref: howto/cporting doc11194620
Ref: 410f11194620
Ref: howto/cporting cporting-howto11194620
Ref: c7f11194620
Ref: howto/cporting porting-extension-modules-to-python-311194620
Ref: 411011194620
Ref: howto/cporting why-python-3-exists11194620
Ref: 411111194620
Ref: 将扩展模块移植到 Python 3-Footnote-111195327
Ref: 将扩展模块移植到 Python 3-Footnote-211195378
Ref: 将扩展模块移植到 Python 3-Footnote-311195435
Ref: 将扩展模块移植到 Python 3-Footnote-411195462
Node: 用 Python 进行 Curses 编程11195509
Ref: howto/curses doc11195668
Ref: 411211195668
Ref: howto/curses cffi11195668
Ref: 411311195668
Ref: howto/curses curses-howto11195668
Ref: 216011195668
Ref: howto/curses curses-programming-with-python11195668
Ref: 411411195668
Node: curses 是什么？11196052
Ref: howto/curses what-is-curses11196181
Ref: 411511196181
Ref: curses 是什么？-Footnote-111198430
Ref: curses 是什么？-Footnote-211198470
Ref: curses 是什么？-Footnote-311198513
Node: Python 的 curses 模块11198562
Ref: howto/curses the-python-curses-module11198642
Ref: 411611198642
Node: 开始和结束curses应用程序11199452
Ref: howto/curses starting-and-ending-a-curses-application11199605
Ref: 411711199605
Node: 窗口和面板11202627
Ref: howto/curses windows-and-pads11202773
Ref: 411811202773
Node: 显示文字11206809
Ref: howto/curses displaying-text11206934
Ref: 411911206934
Node: 属性和颜色11210339
Ref: howto/curses attributes-and-color11210403
Ref: 411a11210403
Node: 用户输入11214710
Ref: howto/curses user-input11214835
Ref: 411b11214835
Ref: 用户输入-Footnote-111218411
Node: 更多的信息11218451
Ref: howto/curses for-more-information11218555
Ref: 411c11218555
Ref: 更多的信息-Footnote-111220055
Ref: 更多的信息-Footnote-211220092
Ref: 更多的信息-Footnote-311220155
Ref: 更多的信息-Footnote-411220207
Node: 描述器使用指南11220281
Ref: howto/descriptor doc11220428
Ref: 411d11220428
Ref: howto/descriptor descriptor-howto-guide11220428
Ref: 411e11220428
Node: 摘要11220724
Ref: howto/descriptor abstract11220812
Ref: 411f11220812
Node: 定义和简介11221287
Ref: howto/descriptor definition-and-introduction11221399
Ref: 412011221399
Node: 描述器协议11222672
Ref: howto/descriptor descriptor-protocol11222796
Ref: 412111222796
Node: 调用描述器<2>11223946
Ref: howto/descriptor invoking-descriptors11224070
Ref: 412211224070
Ref: 调用描述器<2>-Footnote-111226889
Ref: 调用描述器<2>-Footnote-211226957
Ref: 调用描述器<2>-Footnote-311227029
Node: 描述器示例11227109
Ref: howto/descriptor descriptor-example11227224
Ref: 412311227224
Node: 属性11228569
Ref: howto/descriptor properties11228681
Ref: 412411228681
Node: 函数和方法11231291
Ref: howto/descriptor functions-and-methods11231412
Ref: 412511231412
Node: 静态方法和类方法11233532
Ref: howto/descriptor static-methods-and-class-methods11233638
Ref: 412611233638
Node: 函数式编程指引11237848
Ref: howto/functional doc11237982
Ref: 412711237982
Ref: howto/functional functional-programming-howto11237982
Ref: 412811237982
Node: 概述<17>11238655
Ref: howto/functional introduction11238744
Ref: 412911238744
Node: 形式证明11242726
Ref: howto/functional formal-provability11242803
Ref: 412b11242803
Node: 模块化11244434
Ref: howto/functional modularity11244541
Ref: 412c11244541
Node: 易于调试和测试11244844
Ref: howto/functional ease-of-debugging-and-testing11244948
Ref: 412d11244948
Node: 组合性11245548
Ref: howto/functional composability11245634
Ref: 412e11245634
Node: 迭代器<2>11246248
Ref: howto/functional functional-howto-iterators11246382
Ref: 412a11246382
Ref: howto/functional iterators11246382
Ref: 412f11246382
Node: 支持迭代器的数据类型11249543
Ref: howto/functional data-types-that-support-iterators11249622
Ref: 413011249622
Node: 生成器表达式和列表推导式11251370
Ref: howto/functional generator-expressions-and-list-comprehensions11251506
Ref: 413111251506
Node: 生成器<2>11255557
Ref: howto/functional generators11255696
Ref: 413211255696
Ref: 生成器<2>-Footnote-111259167
Node: 向生成器传递值11259247
Ref: howto/functional passing-values-into-a-generator11259317
Ref: 413311259317
Ref: 向生成器传递值-Footnote-111262908
Node: 内置函数<2>11262957
Ref: howto/functional built-in-functions11263076
Ref: 413411263076
Ref: 内置函数<2>-Footnote-111266913
Node: itertools 模块11266967
Ref: howto/functional the-itertools-module11267090
Ref: 413511267090
Node: 创建新的迭代器11267667
Ref: howto/functional creating-new-iterators11267771
Ref: 413611267771
Node: 对元素使用函数11270437
Ref: howto/functional calling-functions-on-elements11270562
Ref: 413711270562
Node: 选择元素11271340
Ref: howto/functional selecting-elements11271456
Ref: 413811271456
Node: 组合函数11272860
Ref: howto/functional combinatoric-functions11272970
Ref: 413911272970
Node: 为元素分组11275194
Ref: howto/functional grouping-elements11275283
Ref: 413a11275283
Node: functools 模块11276795
Ref: howto/functional the-functools-module11276932
Ref: 413b11276932
Node: operator 模块11280413
Ref: howto/functional the-operator-module11280481
Ref: 413c11280481
Node: 小函数和 lambda 表达式11281273
Ref: howto/functional small-functions-and-the-lambda-expression11281415
Ref: 413d11281415
Node: 修订记录和致谢11284115
Ref: howto/functional revision-history-and-acknowledgements11284256
Ref: 413e11284256
Node: 参考文献<2>11284985
Ref: howto/functional references11285088
Ref: 413f11285088
Node: 通用文献11285190
Ref: howto/functional general11285276
Ref: 414011285276
Node: Python 相关11286146
Ref: howto/functional python-specific11286254
Ref: 414111286254
Ref: Python 相关-Footnote-111286691
Ref: Python 相关-Footnote-211286742
Ref: Python 相关-Footnote-311286795
Node: Python 文档11286848
Ref: howto/functional python-documentation11286935
Ref: 414211286935
Ref: Python 文档-Footnote-111287268
Ref: Python 文档-Footnote-211287317
Node: 日志常用指引11287366
Ref: howto/logging doc11287497
Ref: 414311287497
Ref: howto/logging logging-howto11287497
Ref: 414411287497
Node: 日志基础教程11287792
Ref: howto/logging basic-logging-tutorial11287892
Ref: 414511287892
Ref: howto/logging logging-basic-tutorial11287892
Ref: b7a11287892
Node: 什么时候使用日志11288576
Ref: howto/logging when-to-use-logging11288688
Ref: 414611288688
Node: 一个简单的例子<2>11292081
Ref: howto/logging a-simple-example11292223
Ref: 414711292223
Ref: howto/logging howto-minimal-example11292223
Ref: 414811292223
Node: 记录日志到文件11292932
Ref: howto/logging logging-to-a-file11293077
Ref: 414911293077
Node: 从多个模块记录日志11295325
Ref: howto/logging logging-from-multiple-modules11295464
Ref: 414a11295464
Node: 记录变量数据11296548
Ref: howto/logging logging-variable-data11296693
Ref: 414b11296693
Node: 更改显示消息的格式11297448
Ref: howto/logging changing-the-format-of-displayed-messages11297597
Ref: 414c11297597
Node: 在消息中显示日期/时间11298468
Ref: howto/logging displaying-the-date-time-in-messages11298611
Ref: 414d11298611
Ref: 在消息中显示日期/时间-Footnote-111299595
Node: 后续步骤11299644
Ref: howto/logging next-steps11299751
Ref: 414e11299751
Node: 进阶日志教程11300606
Ref: howto/logging advanced-logging-tutorial11300730
Ref: 414f11300730
Ref: howto/logging logging-advanced-tutorial11300730
Ref: b7b11300730
Node: 记录流程11303919
Ref: howto/logging logging-flow11304004
Ref: 415011304004
Node: 记录器11304149
Ref: howto/logging loggers11304255
Ref: 415111304255
Node: 处理程序11308158
Ref: howto/logging handler-basic11308267
Ref: 415211308267
Ref: howto/logging handlers11308267
Ref: 415311308267
Node: 格式化程序11310143
Ref: howto/logging formatters11310261
Ref: 415511310261
Ref: howto/logging logging logging Formatter __init__11310683
Ref: 415611310683
Node: 配置日志记录11312242
Ref: howto/logging configuring-logging11312387
Ref: 415711312387
Node: 如果没有提供配置会发生什么11318486
Ref: howto/logging what-happens-if-no-configuration-is-provided11318640
Ref: 415811318640
Node: 配置库的日志记录11319923
Ref: howto/logging configuring-logging-for-a-library11320050
Ref: 415911320050
Ref: howto/logging library-config11320050
Ref: 210811320050
Node: 日志级别<2>11322228
Ref: howto/logging logging-levels11322355
Ref: 415a11322355
Node: 自定义级别11324938
Ref: howto/logging custom-levels11325005
Ref: 20db11325005
Ref: howto/logging id111325005
Ref: 415b11325005
Node: 有用的处理程序11325598
Ref: howto/logging id211325737
Ref: 415c11325737
Ref: howto/logging useful-handlers11325737
Ref: 415411325737
Node: 记录日志中引发的异常11329518
Ref: howto/logging exceptions-raised-during-logging11329672
Ref: 415d11329672
Ref: howto/logging logging-exceptions11329672
Ref: 415e11329672
Node: 使用任意对象作为消息11330671
Ref: howto/logging arbitrary-object-messages11330810
Ref: 20cc11330810
Ref: howto/logging using-arbitrary-objects-as-messages11330810
Ref: 415f11330810
Node: 优化11331321
Ref: howto/logging optimization11331421
Ref: 416011331421
Node: 日志操作手册11334790
Ref: howto/logging-cookbook doc11334920
Ref: 416111334920
Ref: howto/logging-cookbook id111334920
Ref: 416211334920
Ref: howto/logging-cookbook logging-cookbook11334920
Ref: b7c11334920
Node: 在多个模块中记录日志11336404
Ref: howto/logging-cookbook using-logging-in-multiple-modules11336528
Ref: 416311336528
Node: 在多个线程中记录日志11340032
Ref: howto/logging-cookbook logging-from-multiple-threads11340210
Ref: 416411340210
Node: 多个日志处理器以及多种格式化器11341909
Ref: howto/logging-cookbook multiple-handlers-and-formatters11342084
Ref: 416511342084
Node: 在多个地方记录日志11344241
Ref: howto/logging-cookbook logging-to-multiple-destinations11344413
Ref: 416611344413
Ref: howto/logging-cookbook multiple-destinations11344413
Ref: 416711344413
Node: 日志服务器配置示例11347265
Ref: howto/logging-cookbook configuration-server-example11347422
Ref: 416811347422
Node: 处理日志处理器的阻塞11348967
Ref: howto/logging-cookbook dealing-with-handlers-that-block11349130
Ref: 416911349130
Node: 通过网络发送和接收日志11352409
Ref: howto/logging-cookbook network-logging11352584
Ref: 416a11352584
Ref: howto/logging-cookbook sending-and-receiving-logging-events-across-a-network11352584
Ref: 416b11352584
Node: 在日志记录中添加上下文信息11357903
Ref: howto/logging-cookbook adding-contextual-information-to-your-logging-output11358084
Ref: 416c11358084
Ref: howto/logging-cookbook context-info11358084
Ref: 20cf11358084
Node: 使用日志适配器传递上下文信息11358968
Ref: howto/logging-cookbook using-loggeradapters-to-impart-contextual-information11359131
Ref: 416d11359131
Node: 使用除字典之外的其它对象传递上下文信息11361893
Ref: howto/logging-cookbook using-objects-other-than-dicts-to-pass-contextual-information11362029
Ref: 416e11362029
Node: 使用过滤器传递上下文信息11362430
Ref: howto/logging-cookbook filters-contextual11362593
Ref: 20c411362593
Ref: howto/logging-cookbook using-filters-to-impart-contextual-information11362593
Ref: 416f11362593
Node: 从多个进程记录至单个文件11366324
Ref: howto/logging-cookbook logging-to-a-single-file-from-multiple-processes11366490
Ref: 417011366490
Ref: howto/logging-cookbook multiple-processes11366490
Ref: 417111366490
Node: concurrent futures ProcessPoolExecutor 的用法11376673
Ref: howto/logging-cookbook using-concurrent-futures-processpoolexecutor11376794
Ref: 417211376794
Node: 轮换日志文件11377765
Ref: howto/logging-cookbook using-file-rotation11377925
Ref: 417311377925
Node: 使用其他日志格式化方式11379795
Ref: howto/logging-cookbook format-styles11379938
Ref: 417411379938
Ref: howto/logging-cookbook use-of-alternative-formatting-styles11379938
Ref: 417511379938
Node: 自定义 LogRecord11386395
Ref: howto/logging-cookbook custom-logrecord11386558
Ref: 417611386558
Ref: howto/logging-cookbook customizing-logrecord11386558
Ref: 417711386558
Node: 子类化 QueueHandler - ZeroMQ 示例11390039
Ref: howto/logging-cookbook subclassing-queuehandler-a-zeromq-example11390213
Ref: 417811390213
Ref: howto/logging-cookbook zeromq-handlers11390213
Ref: 417911390213
Node: 子类化 QueueListener —— ZeroMQ 示例11391485
Ref: howto/logging-cookbook subclassing-queuelistener-a-zeromq-example11391679
Ref: 417a11391679
Node: 基于字典进行日志配置的示例11392771
Ref: howto/logging-cookbook an-example-dictionary-based-configuration11392979
Ref: 417b11392979
Ref: 基于字典进行日志配置的示例-Footnote-111394995
Node: 利用 rotator 和 namer 自定义日志轮换操作11395081
Ref: howto/logging-cookbook cookbook-rotator-namer11395278
Ref: 211411395278
Ref: howto/logging-cookbook using-a-rotator-and-namer-to-customize-log-rotation-processing11395278
Ref: 417c11395278
Node: 更加详细的多道处理示例11396077
Ref: howto/logging-cookbook a-more-elaborate-multiprocessing-example11396293
Ref: 417d11396293
Node: 在发送给 SysLogHandler 的信息中插入一个 BOM。11405774
Ref: howto/logging-cookbook inserting-a-bom-into-messages-sent-to-a-sysloghandler11405968
Ref: 417e11405968
Ref: 在发送给 SysLogHandler 的信息中插入一个 BOM。-Footnote-111407886
Ref: 在发送给 SysLogHandler 的信息中插入一个 BOM。-Footnote-211407935
Ref: 在发送给 SysLogHandler 的信息中插入一个 BOM。-Footnote-311407994
Ref: 在发送给 SysLogHandler 的信息中插入一个 BOM。-Footnote-411408043
Node: 结构化日志的实现代码11408092
Ref: howto/logging-cookbook implementing-structured-logging11408288
Ref: 417f11408288
Node: 利用 dictConfig 自定义 handler11410851
Ref: howto/logging-cookbook custom-handlers11411034
Ref: 418011411034
Ref: howto/logging-cookbook customizing-handlers-with-dictconfig11411034
Ref: 418111411034
Node: 生效于整个应用程序的格式化样式11415967
Ref: howto/logging-cookbook formatting-styles11416153
Ref: 20bb11416153
Ref: howto/logging-cookbook using-particular-formatting-styles-throughout-your-application11416153
Ref: 418211416153
Node: LogRecord 工厂的用法11417797
Ref: howto/logging-cookbook using-logrecord-factories11417943
Ref: 418311417943
Node: 自定义信息对象的使用11418844
Ref: howto/logging-cookbook using-custom-message-objects11418990
Ref: 418411418990
Node: 利用 dictConfig 定义过滤器11421389
Ref: howto/logging-cookbook configuring-filters-with-dictconfig11421573
Ref: 418511421573
Ref: howto/logging-cookbook filters-dictconfig11421573
Ref: 418611421573
Node: 异常信息的自定义格式化11424323
Ref: howto/logging-cookbook custom-format-exception11424486
Ref: 418711424486
Ref: howto/logging-cookbook customized-exception-formatting11424486
Ref: 418811424486
Node: 语音播报日志信息11426474
Ref: howto/logging-cookbook speaking-logging-messages11426649
Ref: 418911426649
Ref: howto/logging-cookbook spoken-messages11426649
Ref: 418a11426649
Node: 缓冲日志消息并有条件地输出它们11428433
Ref: howto/logging-cookbook buffered-logging11428616
Ref: 418b11428616
Ref: howto/logging-cookbook buffering-logging-messages-and-outputting-them-conditionally11428616
Ref: 418c11428616
Node: 通过配置使用UTC GMT 格式化时间11433953
Ref: howto/logging-cookbook formatting-times-using-utc-gmt-via-configuration11434160
Ref: 418d11434160
Ref: howto/logging-cookbook utc-formatting11434160
Ref: 418e11434160
Node: 使用上下文管理器的可选的日志记录11436078
Ref: howto/logging-cookbook context-manager11436267
Ref: 418f11436267
Ref: howto/logging-cookbook using-a-context-manager-for-selective-logging11436267
Ref: 419011436267
Node: 命令行日志应用起步11441054
Ref: howto/logging-cookbook a-cli-application-starter-template11441221
Ref: 419111441221
Ref: howto/logging-cookbook starter-template11441221
Ref: 419211441221
Node: Qt GUI 日志示例11446984
Ref: howto/logging-cookbook a-qt-gui-for-logging11447094
Ref: 419311447094
Ref: howto/logging-cookbook qt-gui11447094
Ref: 419411447094
Ref: Qt GUI 日志示例-Footnote-111456321
Ref: Qt GUI 日志示例-Footnote-211456348
Ref: Qt GUI 日志示例-Footnote-311456390
Node: 正则表达式HOWTO11456430
Ref: howto/regex doc11456563
Ref: 419511456563
Ref: howto/regex regex-howto11456563
Ref: 176011456563
Ref: howto/regex regular-expression-howto11456563
Ref: 419611456563
Node: 概述<18>11456975
Ref: howto/regex introduction11457063
Ref: 419711457063
Node: 简单模式11458404
Ref: howto/regex simple-patterns11458522
Ref: 419811458522
Node: 匹配字符11458934
Ref: howto/regex matching-characters11459010
Ref: 419911459010
Node: 重复11463023
Ref: howto/regex repeating-things11463099
Ref: 419a11463099
Node: 使用正则表达式11467367
Ref: howto/regex using-regular-expressions11467493
Ref: 419b11467493
Node: 编译正则表达式11467916
Ref: howto/regex compiling-regular-expressions11468019
Ref: 419c11468019
Node: 反斜杠灾难11469079
Ref: howto/regex id111469203
Ref: 419d11469203
Ref: howto/regex the-backslash-plague11469203
Ref: 419e11469203
Node: 应用匹配11471884
Ref: howto/regex performing-matches11472008
Ref: 419f11472008
Ref: 应用匹配-Footnote-111477465
Node: 模块级别函数<2>11477537
Ref: howto/regex module-level-functions11477658
Ref: 41a011477658
Node: 编译标志11478742
Ref: howto/regex compilation-flags11478842
Ref: 41a111478842
Node: 更多模式能力11485250
Ref: howto/regex more-pattern-power11485379
Ref: 41a311485379
Node: 更多元字符11485694
Ref: howto/regex id211485779
Ref: 41a411485779
Ref: howto/regex more-metacharacters11485779
Ref: 41a211485779
Node: 分组11489946
Ref: howto/regex grouping11490061
Ref: 41a511490061
Node: 非捕获和命名组11493113
Ref: howto/regex non-capturing-and-named-groups11493225
Ref: 41a611493225
Node: 前向断言11497615
Ref: howto/regex lookahead-assertions11497712
Ref: 41a711497712
Node: 修改字符串11500858
Ref: howto/regex modifying-strings11500978
Ref: 41a811500978
Node: 分割字符串11501858
Ref: howto/regex splitting-strings11501949
Ref: 41a911501949
Node: 搜索和替换11504116
Ref: howto/regex search-and-replace11504207
Ref: 41aa11504207
Node: 常见问题11508308
Ref: howto/regex common-problems11508416
Ref: 41ab11508416
Node: 使用字符串方法11508815
Ref: howto/regex use-string-methods11508910
Ref: 41ac11508910
Node: match 和 search11510468
Ref: howto/regex match-versus-search11510590
Ref: 41ad11510590
Node: 贪婪与非贪婪11512095
Ref: howto/regex greedy-versus-non-greedy11512213
Ref: 41ae11512213
Node: 使用 re VERBOSE11513969
Ref: howto/regex using-re-verbose11514062
Ref: 41af11514062
Node: 反馈11515472
Ref: howto/regex feedback11515556
Ref: 41b011515556
Node: 套接字编程指南11516229
Ref: howto/sockets doc11516356
Ref: 41b111516356
Ref: howto/sockets socket-howto11516356
Ref: 26aa11516356
Ref: howto/sockets socket-programming-howto11516356
Ref: 41b211516356
Node: 套接字11516942
Ref: howto/sockets sockets11517036
Ref: 41b311517036
Node: 历史11518183
Ref: howto/sockets history11518235
Ref: 41b411518235
Node: 创建套接字<2>11518782
Ref: howto/sockets creating-a-socket11518906
Ref: 41b511518906
Node: 进程间通信11522123
Ref: howto/sockets ipc11522193
Ref: 41b611522193
Node: 使用一个套接字11522696
Ref: howto/sockets using-a-socket11522823
Ref: 41b711522823
Node: 二进制数据11528621
Ref: howto/sockets binary-data11528694
Ref: 41b811528694
Node: 断开连接11529685
Ref: howto/sockets disconnecting11529815
Ref: 41b911529815
Node: 套接字何时销毁11531206
Ref: howto/sockets when-sockets-die11531276
Ref: 41ba11531276
Node: 非阻塞的套接字11532009
Ref: howto/sockets non-blocking-sockets11532109
Ref: 41bb11532109
Node: 排序指南11535919
Ref: howto/sorting doc11536040
Ref: 41bc11536040
Ref: howto/sorting sorting-how-to11536040
Ref: 41bd11536040
Ref: howto/sorting sortinghowto11536040
Ref: 161111536040
Node: 基本排序11536650
Ref: howto/sorting sorting-basics11536732
Ref: 41be11536732
Node: 关键函数11537508
Ref: howto/sorting key-functions11537620
Ref: 41bf11537620
Node: Operator 模块函数11539240
Ref: howto/sorting operator-module-functions11539355
Ref: 41c011539355
Node: 升序和降序11540366
Ref: howto/sorting ascending-and-descending11540502
Ref: 41c111540502
Node: 排序稳定性和排序复杂度11540985
Ref: howto/sorting sort-stability-and-complex-sorts11541141
Ref: 41c211541141
Ref: 排序稳定性和排序复杂度-Footnote-111542723
Ref: 排序稳定性和排序复杂度-Footnote-211542789
Node: 使用装饰-排序-去装饰的旧方法11542835
Ref: howto/sorting the-old-way-using-decorate-sort-undecorate11543005
Ref: 41c311543005
Ref: 使用装饰-排序-去装饰的旧方法-Footnote-111544459
Node: 使用 cmp 参数的旧方法11544519
Ref: howto/sorting the-old-way-using-the-cmp-parameter11544662
Ref: 41c411544662
Node: 其它11546974
Ref: howto/sorting odd-and-ends11547067
Ref: 41c511547067
Node: Unicode 指南11548702
Ref: howto/unicode doc11548843
Ref: 41c611548843
Ref: howto/unicode id111548843
Ref: 41c711548843
Ref: howto/unicode unicode-howto11548843
Ref: c4411548843
Node: Unicode 概述11549166
Ref: howto/unicode introduction-to-unicode11549265
Ref: 41c811549265
Node: 定义11549375
Ref: howto/unicode definitions11549447
Ref: 41c911549447
Node: 编码11552094
Ref: howto/unicode encodings11552190
Ref: 41ca11552190
Node: 参考文献<3>11555353
Ref: howto/unicode references11555434
Ref: 41cb11555434
Ref: 参考文献<3>-Footnote-111556476
Ref: 参考文献<3>-Footnote-211556507
Ref: 参考文献<3>-Footnote-311556547
Ref: 参考文献<3>-Footnote-411556604
Node: Python对Unicode的支持11556648
Ref: howto/unicode python-s-unicode-support11556779
Ref: 41cc11556779
Node: 字符串类型11557129
Ref: howto/unicode the-string-type11557230
Ref: 41cd11557230
Node: 转换为字节11560194
Ref: howto/unicode converting-to-bytes11560341
Ref: 41ce11560341
Node: Python 源代码中的 Unicode 文字11562046
Ref: howto/unicode unicode-literals-in-python-source-code11562191
Ref: 41cf11562191
Ref: Python 源代码中的 Unicode 文字-Footnote-111564093
Node: Unicode属性11564142
Ref: howto/unicode unicode-properties11564287
Ref: 41d011564287
Node: 字符串比较11565841
Ref: howto/unicode comparing-strings11565972
Ref: 41d111565972
Node: Unicode 正则表达式11568634
Ref: howto/unicode unicode-regular-expressions11568767
Ref: 41d211568767
Node: 参考文献<4>11569826
Ref: howto/unicode id211569935
Ref: 41d311569935
Ref: 参考文献<4>-Footnote-111570761
Ref: 参考文献<4>-Footnote-211570856
Node: Unicode 数据的读写11570908
Ref: howto/unicode reading-and-writing-unicode-data11571035
Ref: 41d411571035
Node: Unicode 文件名11574265
Ref: howto/unicode unicode-filenames11574381
Ref: 41d511574381
Node: 识别 Unicode 的编程技巧11576524
Ref: howto/unicode tips-for-writing-unicode-aware-programs11576664
Ref: 41d611576664
Node: 在文件编码格式之间进行转换11577905
Ref: howto/unicode converting-between-file-encodings11578047
Ref: 41d711578047
Node: 编码格式未知的文件11578790
Ref: howto/unicode files-in-an-unknown-encoding11578932
Ref: 41d811578932
Node: 参考文献<5>11579749
Ref: howto/unicode id311579863
Ref: 41d911579863
Ref: 参考文献<5>-Footnote-111580436
Ref: 参考文献<5>-Footnote-211580508
Ref: 参考文献<5>-Footnote-311580613
Node: 致谢<10>11580681
Ref: howto/unicode acknowledgements11580774
Ref: 41da11580774
Node: HOWTO 使用 urllib 包获取网络资源11581222
Ref: howto/urllib2 doc11581366
Ref: 41db11581366
Ref: howto/urllib2 howto-fetch-internet-resources-using-the-urllib-package11581366
Ref: 41dc11581366
Ref: howto/urllib2 urllib-howto11581366
Ref: 2cbc11581366
Ref: HOWTO 使用 urllib 包获取网络资源-Footnote-111581833
Ref: HOWTO 使用 urllib 包获取网络资源-Footnote-211581888
Node: 概述<19>11581964
Ref: howto/urllib2 introduction11582070
Ref: 41dd11582070
Ref: 概述<19>-Footnote-111583582
Ref: 概述<19>-Footnote-211583655
Node: 提取URL11583704
Ref: howto/urllib2 fetching-urls11583834
Ref: 41de11583834
Node: 数据11585884
Ref: howto/urllib2 data11585962
Ref: 41df11585962
Ref: 数据-Footnote-111588424
Node: HTTP 头部信息11588493
Ref: howto/urllib2 headers11588571
Ref: 41e011588571
Ref: HTTP 头部信息-Footnote-111590081
Ref: HTTP 头部信息-Footnote-211590110
Ref: HTTP 头部信息-Footnote-311590346
Ref: HTTP 头部信息-Footnote-411590473
Node: 处理异常<2>11590585
Ref: howto/urllib2 handling-exceptions11590720
Ref: 41e311590720
Node: URLError11591163
Ref: howto/urllib2 urlerror11591241
Ref: 41e411591241
Node: HTTPError11591804
Ref: howto/urllib2 httperror11591903
Ref: 41e511591903
Ref: HTTPError-Footnote-111592763
Node: 错误代码11592812
Ref: howto/urllib2 error-codes11592870
Ref: 41e611592870
Ref: 错误代码-Footnote-111597585
Node: 包装起来11597634
Ref: howto/urllib2 wrapping-it-up11597716
Ref: 41e711597716
Node: 数字111597922
Ref: howto/urllib2 number-111598002
Ref: 41e811598002
Node: 第二种方案11598626
Ref: howto/urllib2 number-211598706
Ref: 41e911598706
Node: info and geturl11599249
Ref: howto/urllib2 info-and-geturl11599393
Ref: 41e211599393
Ref: info and geturl-Footnote-111600290
Node: Opener 和 Handler11600327
Ref: howto/urllib2 openers-and-handlers11600468
Ref: 41ea11600468
Node: 基本认证11602018
Ref: howto/urllib2 id511602150
Ref: 41eb11602150
Ref: 基本认证-Footnote-111605486
Node: 代理11605559
Ref: howto/urllib2 proxies11605691
Ref: 41ec11605691
Ref: 代理-Footnote-111606638
Ref: 代理-Footnote-211606928
Node: 套接字与分层11607066
Ref: howto/urllib2 sockets-and-layers11607192
Ref: 41ee11607192
Node: 备注11608165
Ref: howto/urllib2 footnotes11608276
Ref: 41ef11608276
Node: Argparse 教程11608341
Ref: howto/argparse doc11608492
Ref: 41f011608492
Ref: howto/argparse argparse-tutorial11608492
Ref: 41f111608492
Ref: howto/argparse id111608566
Ref: 203911608566
Node: 概念11609165
Ref: howto/argparse concepts11609241
Ref: 41f211609241
Node: 基础<2>11611331
Ref: howto/argparse the-basics11611434
Ref: 41f311611434
Node: 位置参数介绍11612610
Ref: howto/argparse introducing-positional-arguments11612725
Ref: 41f411612725
Node: 可选参数介绍11615985
Ref: howto/argparse introducing-optional-arguments11616124
Ref: 41f511616124
Node: 短选项11619058
Ref: howto/argparse short-options11619122
Ref: 41f611619122
Node: 结合位置参数和可选参数11619879
Ref: howto/argparse combining-positional-and-optional-arguments11620027
Ref: 41f711620027
Node: 进行一些小小的改进11628148
Ref: howto/argparse getting-a-little-more-advanced11628284
Ref: 41f811628284
Node: 矛盾的选项11630278
Ref: howto/argparse conflicting-options11630357
Ref: 41f911630357
Node: 后记11633444
Ref: howto/argparse conclusion11633538
Ref: 41fa11633538
Node: ipaddress模块介绍11633784
Ref: howto/ipaddress doc11633916
Ref: 41fb11633916
Ref: howto/ipaddress an-introduction-to-the-ipaddress-module11633916
Ref: 41fc11633916
Ref: howto/ipaddress ipaddress-howto11633916
Ref: 2f1211633916
Node: 创建 Address/Network/Interface 对象11634514
Ref: howto/ipaddress creating-address-network-interface-objects11634659
Ref: 41fd11634659
Node: 关于IP版本的说明11635052
Ref: howto/ipaddress a-note-on-ip-versions11635174
Ref: 41fe11635174
Node: IP主机地址11635734
Ref: howto/ipaddress ip-host-addresses11635877
Ref: 41ff11635877
Node: 定义网络11636892
Ref: howto/ipaddress defining-networks11637024
Ref: 420011637024
Node: 主机接口11639051
Ref: howto/ipaddress host-interfaces11639160
Ref: 420111639160
Node: 审查 Address/Network/Interface 对象11639993
Ref: howto/ipaddress inspecting-address-network-interface-objects11640176
Ref: 420211640176
Node: Network 作为 Address 列表11642329
Ref: howto/ipaddress networks-as-lists-of-addresses11642488
Ref: 420311642488
Node: 比较运算<4>11643216
Ref: howto/ipaddress comparisons11643374
Ref: 420411643374
Node: 将IP地址与其他模块一起使用11643706
Ref: howto/ipaddress using-ip-addresses-with-other-modules11643880
Ref: 420511643880
Node: 实例创建失败时获取更多详细信息11644288
Ref: howto/ipaddress getting-more-detail-when-instance-creation-fails11644438
Ref: 420611644438
Node: Argument Clinic How-To11646258
Ref: howto/clinic doc11646416
Ref: 420711646416
Ref: howto/clinic argument-clinic-how-to11646416
Ref: 420811646416
Node: The Goals Of Argument Clinic11647443
Ref: howto/clinic the-goals-of-argument-clinic11647563
Ref: 420911647563
Node: Basic Concepts And Usage11649921
Ref: howto/clinic basic-concepts-and-usage11650080
Ref: 420a11650080
Node: Converting Your First Function11652511
Ref: howto/clinic converting-your-first-function11652657
Ref: 420b11652657
Node: Advanced Topics11668758
Ref: howto/clinic advanced-topics11668871
Ref: 420d11668871
Node: Symbolic default values11669837
Ref: howto/clinic symbolic-default-values11669988
Ref: 420e11669988
Node: Renaming the C functions and variables generated by Argument Clinic11670617
Ref: howto/clinic renaming-the-c-functions-and-variables-generated-by-argument-clinic11670821
Ref: 420f11670821
Node: Converting functions using PyArg_UnpackTuple11672484
Ref: howto/clinic converting-functions-using-pyarg-unpacktuple11672680
Ref: 421011672680
Node: Optional Groups11673225
Ref: howto/clinic optional-groups11673422
Ref: 421111673422
Node: Using real Argument Clinic converters instead of "legacy converters"11677474
Ref: howto/clinic using-real-argument-clinic-converters-instead-of-legacy-converters11677636
Ref: 421211677636
Ref: Using real Argument Clinic converters instead of "legacy converters"-Footnote-111686494
Node: Py_buffer11686543
Ref: howto/clinic py-buffer11686709
Ref: 421311686709
Node: Advanced converters11687025
Ref: howto/clinic advanced-converters11687147
Ref: 421411687147
Node: Parameter default values11688848
Ref: howto/clinic default-values11688983
Ref: 420c11688983
Ref: howto/clinic parameter-default-values11688983
Ref: 421511688983
Node: The NULL default value11689512
Ref: howto/clinic the-null-default-value11689667
Ref: 421611689667
Node: Expressions specified as default values11690141
Ref: howto/clinic expressions-specified-as-default-values11690296
Ref: 421711690296
Node: Using a return converter11692687
Ref: howto/clinic using-a-return-converter11692846
Ref: 421811692846
Node: Cloning existing functions11695487
Ref: howto/clinic cloning-existing-functions11695626
Ref: 421911695626
Node: Calling Python code11696946
Ref: howto/clinic calling-python-code11697085
Ref: 421a11697085
Node: Using a "self converter"11698000
Ref: howto/clinic using-a-self-converter11698139
Ref: 421b11698139
Node: Writing a custom converter11699873
Ref: howto/clinic writing-a-custom-converter11700026
Ref: 421c11700026
Node: Writing a custom return converter11703719
Ref: howto/clinic writing-a-custom-return-converter11703870
Ref: 421d11703870
Node: METH_O and METH_NOARGS11704449
Ref: howto/clinic meth-o-and-meth-noargs11704602
Ref: 421e11704602
Node: tp_new and tp_init functions11705173
Ref: howto/clinic tp-new-and-tp-init-functions11705333
Ref: 421f11705333
Node: Changing and redirecting Clinic's output11706278
Ref: howto/clinic changing-and-redirecting-clinic-s-output11706432
Ref: 422011706432
Node: The #ifdef trick11717686
Ref: howto/clinic the-ifdef-trick11717849
Ref: 422111717849
Node: Using Argument Clinic in Python files11720623
Ref: howto/clinic using-argument-clinic-in-python-files11720737
Ref: 422211720737
Node: 使用 DTrace 和 SystemTap 检测CPython11721433
Ref: howto/instrumentation doc11721561
Ref: 422311721561
Ref: howto/instrumentation instrumentation11721561
Ref: 51411721561
Ref: howto/instrumentation instrumenting-cpython-with-dtrace-and-systemtap11721561
Ref: 422411721561
Node: 启用静态标记11722611
Ref: howto/instrumentation enabling-the-static-markers11722734
Ref: 422511722734
Node: 静态DTrace探针11726762
Ref: howto/instrumentation static-dtrace-probes11726915
Ref: 422611726915
Node: 静态SystemTap标记11729303
Ref: howto/instrumentation static-systemtap-markers11729459
Ref: 422711729459
Node: 可用的静态标记11731401
Ref: howto/instrumentation available-static-markers11731556
Ref: 422811731556
Node: SystemTap Tapsets11733843
Ref: howto/instrumentation systemtap-tapsets11733987
Ref: 422911733987
Node: 例子<36>11735548
Ref: howto/instrumentation examples11735662
Ref: 422a11735662
Node: Python 常见问题11736928
Ref: faq/index doc11737039
Ref: 422b11737039
Ref: faq/index faq-index11737039
Ref: 132811737039
Ref: faq/index python-frequently-asked-questions11737039
Ref: 422c11737039
Node: Python常见问题11737365
Ref: faq/general doc11737466
Ref: 422d11737466
Ref: faq/general general-python-faq11737466
Ref: 422e11737466
Node: 一般信息11737568
Ref: faq/general general-information11737669
Ref: 422f11737669
Node: 什么是 Python？11738629
Ref: faq/general what-is-python11738741
Ref: 423011738741
Ref: 什么是 Python？-Footnote-111739625
Node: 什么是 Python 软件基金会？11739677
Ref: faq/general what-is-the-python-software-foundation11739839
Ref: 423111739839
Ref: 什么是 Python 软件基金会？-Footnote-111740422
Node: 使用 Python 是否存在版权限制？11740468
Ref: faq/general are-there-copyright-restrictions-on-the-use-of-python11740652
Ref: 423211740652
Ref: 使用 Python 是否存在版权限制？-Footnote-111741427
Ref: 使用 Python 是否存在版权限制？-Footnote-211741471
Node: 创造 Python 的最初理由是什么？11741518
Ref: faq/general why-was-python-created-in-the-first-place11741692
Ref: 423311741692
Node: Python 适合做什么？11743935
Ref: faq/general what-is-python-good-for11744111
Ref: 423411744111
Ref: Python 适合做什么？-Footnote-111744905
Node: Python 版本的编号形式是怎样的？11744930
Ref: faq/general how-does-the-python-version-numbering-scheme-work11745118
Ref: 423511745118
Ref: Python 版本的编号形式是怎样的？-Footnote-111747025
Node: 我应如何获取一份 Python 源代码的副本？11747074
Ref: faq/general how-do-i-obtain-a-copy-of-the-python-source11747275
Ref: 423611747275
Ref: 我应如何获取一份 Python 源代码的副本？-Footnote-111748029
Node: 我应如何获取 Python 的文档？11748072
Ref: faq/general how-do-i-get-documentation-on-python11748293
Ref: 423711748293
Ref: 我应如何获取 Python 的文档？-Footnote-111748791
Node: 我之前从未接触过编程。 哪里有 Python 的教程？11748822
Ref: faq/general i-ve-never-programmed-before-is-there-a-python-tutorial11749049
Ref: 423811749049
Ref: 我之前从未接触过编程。 哪里有 Python 的教程？-Footnote-111749415
Node: 是否有专门针对 Python 的新闻组或邮件列表？11749467
Ref: faq/general is-there-a-newsgroup-or-mailing-list-devoted-to-python11749706
Ref: 423911749706
Ref: 是否有专门针对 Python 的新闻组或邮件列表？-Footnote-111750552
Ref: 是否有专门针对 Python 的新闻组或邮件列表？-Footnote-211750613
Node: 我应如何获取 Python 的公开测试版本？11750683
Ref: faq/general how-do-i-get-a-beta-test-version-of-python11750912
Ref: 423a11750912
Ref: 我应如何获取 Python 的公开测试版本？-Footnote-111751435
Node: 我应如何为 Python 提交错误报告和补丁？11751472
Ref: faq/general how-do-i-submit-bug-reports-and-patches-for-python11751719
Ref: 423b11751719
Ref: 我应如何为 Python 提交错误报告和补丁？-Footnote-111752409
Ref: 我应如何为 Python 提交错误报告和补丁？-Footnote-211752466
Node: 是否有任何公开发表的 Python 相关文章可以供我参考引用？11752503
Ref: faq/general are-there-any-published-articles-about-python-that-i-can-reference11752741
Ref: 423c11752741
Node: 是否有任何 Python 相关的书籍？11753281
Ref: faq/general are-there-any-books-on-python11753520
Ref: 423d11753520
Node: www python org 具体位于世界上的哪个地点？11753923
Ref: faq/general where-in-the-world-is-www-python-org-located11754110
Ref: 423e11754110
Ref: www python org 具体位于世界上的哪个地点？-Footnote-111754392
Node: 为何命名为 Python？11754420
Ref: faq/general why-is-it-called-python11754622
Ref: 423f11754622
Ref: 为何命名为 Python？-Footnote-111755061
Node: 我必须喜欢 "Monty Python 的飞行马戏团" 吗？11755112
Ref: faq/general do-i-have-to-like-monty-python-s-flying-circus11755251
Ref: 424011755251
Node: 现实世界中的 Python11755417
Ref: faq/general python-in-the-real-world11755518
Ref: 424111755518
Node: Python 有多稳定？11755886
Ref: faq/general how-stable-is-python11756010
Ref: 424211756010
Ref: Python 有多稳定？-Footnote-111757031
Ref: Python 有多稳定？-Footnote-211757080
Ref: Python 有多稳定？-Footnote-311757122
Node: 有多少人在使用 Python？11757172
Ref: faq/general how-many-people-are-using-python11757355
Ref: 424311757355
Node: 有哪些重要的项目是用 Python 开发的？11757856
Ref: faq/general have-any-significant-projects-been-done-in-python11758070
Ref: 424411758070
Ref: 有哪些重要的项目是用 Python 开发的？-Footnote-111758740
Ref: 有哪些重要的项目是用 Python 开发的？-Footnote-211758792
Ref: 有哪些重要的项目是用 Python 开发的？-Footnote-311758820
Ref: 有哪些重要的项目是用 Python 开发的？-Footnote-411758848
Node: 在未来可以期待 Python 将有什么新进展？11758879
Ref: faq/general what-new-developments-are-expected-for-python-in-the-future11759118
Ref: 424511759118
Ref: 在未来可以期待 Python 将有什么新进展？-Footnote-111759682
Node: 提议对 Python 加入不兼容的更改是否合理？11759743
Ref: faq/general is-it-reasonable-to-propose-incompatible-changes-to-python11759987
Ref: 424611759987
Ref: 提议对 Python 加入不兼容的更改是否合理？-Footnote-111760737
Node: Python 是一种对编程初学者友好的语言吗？11760786
Ref: faq/general is-python-a-good-language-for-beginning-programmers11760968
Ref: 424711760968
Ref: Python 是一种对编程初学者友好的语言吗？-Footnote-111764620
Ref: Python 是一种对编程初学者友好的语言吗？-Footnote-211764671
Node: 编程常见问题11764733
Ref: faq/programming doc11764870
Ref: 424811764870
Ref: faq/programming programming-faq11764870
Ref: 424911764870
Node: 一般问题11765063
Ref: faq/programming general-questions11765151
Ref: 424a11765151
Node: Python 有没有提供断点与单步调试等功能的，源码层次的调试器？11765511
Ref: faq/programming is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc11765717
Ref: 424b11765717
Ref: Python 有没有提供断点与单步调试等功能的，源码层次的调试器？-Footnote-111767068
Ref: Python 有没有提供断点与单步调试等功能的，源码层次的调试器？-Footnote-211767112
Ref: Python 有没有提供断点与单步调试等功能的，源码层次的调试器？-Footnote-311767165
Ref: Python 有没有提供断点与单步调试等功能的，源码层次的调试器？-Footnote-411767210
Ref: Python 有没有提供断点与单步调试等功能的，源码层次的调试器？-Footnote-511767259
Ref: Python 有没有提供断点与单步调试等功能的，源码层次的调试器？-Footnote-611767298
Ref: Python 有没有提供断点与单步调试等功能的，源码层次的调试器？-Footnote-711767328
Ref: Python 有没有提供断点与单步调试等功能的，源码层次的调试器？-Footnote-811767385
Node: 是否有能帮助寻找漏洞或执行静态分析的工具？11767428
Ref: faq/programming are-there-tools-to-help-find-bugs-or-perform-static-analysis11767729
Ref: 424c11767729
Ref: 是否有能帮助寻找漏洞或执行静态分析的工具？-Footnote-111768100
Ref: 是否有能帮助寻找漏洞或执行静态分析的工具？-Footnote-211768132
Ref: 是否有能帮助寻找漏洞或执行静态分析的工具？-Footnote-311768174
Ref: 是否有能帮助寻找漏洞或执行静态分析的工具？-Footnote-411768204
Ref: 是否有能帮助寻找漏洞或执行静态分析的工具？-Footnote-511768236
Node: 我如何能够通过一个 Python 脚本创建一个独立运行的二进制文件？11768277
Ref: faq/programming how-can-i-create-a-stand-alone-binary-from-a-python-script11768552
Ref: 424d11768552
Ref: 我如何能够通过一个 Python 脚本创建一个独立运行的二进制文件？-Footnote-111770168
Ref: 我如何能够通过一个 Python 脚本创建一个独立运行的二进制文件？-Footnote-211770199
Ref: 我如何能够通过一个 Python 脚本创建一个独立运行的二进制文件？-Footnote-311770248
Node: 是否有 Python 程序规范代码标准或风格指南？11770300
Ref: faq/programming are-there-coding-standards-or-a-style-guide-for-python-programs11770503
Ref: 424e11770503
Ref: 是否有 Python 程序规范代码标准或风格指南？-Footnote-111770746
Node: 核心语言11770795
Ref: faq/programming core-language11770910
Ref: 424f11770910
Node: 当变量有值时，为什么会出现UnboundLocalError？11772019
Ref: faq/programming why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value11772193
Ref: 425011772193
Node: Python中的局部变量和全局变量有哪些规则？11773952
Ref: faq/programming what-are-the-rules-for-local-and-global-variables-in-python11774217
Ref: 425111774217
Node: 为什么在具有不同值的循环中定义的lambdas都返回相同的结果？11774961
Ref: faq/programming why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result11775203
Ref: 425211775203
Node: 如何跨模块共享全局变量？11777054
Ref: faq/programming how-do-i-share-global-variables-across-modules11777284
Ref: 425311777284
Node: 导入模块的“最佳实践”是什么？11777994
Ref: faq/programming what-are-the-best-practices-for-using-import-in-a-module11778184
Ref: 425411778184
Node: 为什么对象之间会共享默认值？11780653
Ref: faq/programming why-are-default-values-shared-between-objects11780888
Ref: 425511780888
Node: 如何将可选参数或关键字参数从一个函数传递到另一个函数？11783140
Ref: faq/programming how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another11783369
Ref: 425611783369
Node: 形参和实参之间有什么区别？11783888
Ref: faq/programming faq-argument-vs-parameter11784126
Ref: 425711784126
Ref: faq/programming what-is-the-difference-between-arguments-and-parameters11784126
Ref: 425811784126
Node: 为什么更改列表 'y' 也会更改列表 'x'？11784707
Ref: faq/programming why-did-changing-list-y-also-change-list-x11784927
Ref: 425911784927
Node: 如何编写带输出参数的函数（通过引用调用）？11788225
Ref: faq/programming how-do-i-write-a-function-with-output-parameters-call-by-reference11788445
Ref: 425a11788445
Node: 如何在Python中创建高阶函数？11790803
Ref: faq/programming how-do-you-make-a-higher-order-function-in-python11791005
Ref: 425b11791005
Node: 如何在Python中复制对象？11792500
Ref: faq/programming how-do-i-copy-an-object-in-python11792678
Ref: 425c11792678
Node: 如何找到对象的方法或属性？11793092
Ref: faq/programming how-can-i-find-the-methods-or-attributes-of-an-object11793279
Ref: 425d11793279
Node: 我的代码如何才能发现对象的名称？11793538
Ref: faq/programming how-can-my-code-discover-the-name-of-an-object11793731
Ref: 425e11793731
Node: 逗号运算符的优先级是什么？11795288
Ref: faq/programming what-s-up-with-the-comma-operator-s-precedence11795499
Ref: 425f11795499
Node: 是否有与 C 的 "? " 三目运算符等价的东西？11796002
Ref: faq/programming is-there-an-equivalent-of-c-s-ternary-operator11796214
Ref: 426011796214
Node: 是否可以用Python编写混淆的单行程序?11796767
Ref: faq/programming is-it-possible-to-write-obfuscated-one-liners-in-python11796995
Ref: 426111796995
Node: 函数参数列表中的斜杠（/）是什么意思？11798457
Ref: faq/programming faq-positional-only-arguments11798619
Ref: 160311798619
Ref: faq/programming what-does-the-slash-in-the-parameter-list-of-a-function-mean11798619
Ref: 426211798619
Node: 数字和字符串11799566
Ref: faq/programming numbers-and-strings11799678
Ref: 426311799678
Node: 如何指定十六进制和八进制整数？11800333
Ref: faq/programming how-do-i-specify-hexadecimal-and-octal-integers11800471
Ref: 426411800471
Node: 为什么-22 // 10返回-3？11801093
Ref: faq/programming why-does-22-10-return-311801276
Ref: 426511801276
Node: 如何将字符串转换为数字？11802063
Ref: faq/programming how-do-i-convert-a-string-to-a-number11802237
Ref: 426611802237
Node: 如何将数字转换为字符串？11803477
Ref: faq/programming how-do-i-convert-a-number-to-a-string11803646
Ref: 426711803646
Node: 如何修改字符串？11804190
Ref: faq/programming how-do-i-modify-a-string-in-place11804366
Ref: 426811804366
Node: 如何使用字符串调用函数/方法？11805175
Ref: faq/programming how-do-i-use-strings-to-call-functions-methods11805404
Ref: 426911805404
Node: 是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？11806892
Ref: faq/programming is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings11807139
Ref: 426a11807139
Node: 是否有 scanf 或 sscanf 的对应物？11807809
Ref: faq/programming is-there-a-scanf-or-sscanf-equivalent11808083
Ref: 426b11808083
Node: 'UnicodeDecodeError' 或 'UnicodeEncodeError' 错误是什么意思？11808711
Ref: faq/programming what-does-unicodedecodeerror-or-unicodeencodeerror-error-mean11808887
Ref: 426c11808887
Node: 性能<4>11809079
Ref: faq/programming performance11809204
Ref: 426d11809204
Node: 我的程序太慢了。该如何加快速度？11809362
Ref: faq/programming my-program-is-too-slow-how-do-i-speed-it-up11809528
Ref: 426e11809528
Ref: 我的程序太慢了。该如何加快速度？-Footnote-111811984
Ref: 我的程序太慢了。该如何加快速度？-Footnote-211812010
Node: 将多个字符串连接在一起的最有效方法是什么？11812075
Ref: faq/programming efficient-string-concatenation11812241
Ref: 426f11812241
Ref: faq/programming what-is-the-most-efficient-way-to-concatenate-many-strings-together11812241
Ref: 427011812241
Node: 序列（元组/列表）11813136
Ref: faq/programming sequences-tuples-lists11813249
Ref: 427111813249
Node: 如何在元组和列表之间进行转换？11813864
Ref: faq/programming how-do-i-convert-between-tuples-and-lists11814004
Ref: 427211814004
Node: 什么是负数序号？11814862
Ref: faq/programming what-s-a-negative-index11815050
Ref: 427311815050
Node: 如何以相反的顺序迭代序列？11815591
Ref: faq/programming how-do-i-iterate-over-a-sequence-in-reverse-order11815770
Ref: 427411815770
Node: 如何从列表中删除重复项？11816074
Ref: faq/programming how-do-you-remove-duplicates-from-a-list11816265
Ref: 427511816265
Node: 如何从列表中删除多个项？11817080
Ref: faq/programming how-do-you-remove-multiple-items-from-a-list11817265
Ref: 427611817265
Node: 如何在Python中创建数组？11817773
Ref: faq/programming how-do-you-make-an-array-in-python11817949
Ref: 427711817949
Node: 如何创建多维列表？11818828
Ref: faq/programming faq-multidimensional-list11819010
Ref: 164111819010
Ref: faq/programming how-do-i-create-a-multidimensional-list11819010
Ref: 427811819010
Ref: 如何创建多维列表？-Footnote-111820194
Node: 如何将方法应用于一系列对象？11820224
Ref: faq/programming how-do-i-apply-a-method-to-a-sequence-of-objects11820442
Ref: 427911820442
Node: 为什么 a_tuple[i] += ['item'] 会在执行加法时引发异常？11820613
Ref: faq/programming faq-augmented-assignment-tuple-error11820884
Ref: 148c11820884
Ref: faq/programming why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works11820884
Ref: 427a11820884
Node: 我想做一个复杂的排序：你能用Python做一个Schwartzian变换吗？11823874
Ref: faq/programming i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python11824163
Ref: 427b11824163
Node: 如何按其他列表中的值对一个列表进行排序？11824631
Ref: faq/programming how-can-i-sort-one-list-by-values-from-another-list11824842
Ref: 427c11824842
Node: 对象11826035
Ref: faq/programming objects11826148
Ref: 427d11826148
Node: 什么是类？11826898
Ref: faq/programming what-is-a-class11826983
Ref: 427e11826983
Node: 什么是方法？11827605
Ref: faq/programming what-is-a-method11827717
Ref: 427f11827717
Node: 什么是 self ？11827997
Ref: faq/programming what-is-self11828160
Ref: 428011828160
Node: 如何检查对象是否为给定类或其子类的一个实例？11828576
Ref: faq/programming how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it11828739
Ref: 428211828739
Node: 什么是委托？11830124
Ref: faq/programming what-is-delegation11830333
Ref: 428311830333
Node: 如何从覆盖基类的派生类调用基类中定义的方法?11832045
Ref: faq/programming how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it11832227
Ref: 428411832227
Node: 如何组织代码以便更改基类？11832875
Ref: faq/programming how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class11833087
Ref: 428511833087
Node: 如何创建静态类数据和静态类方法？11833636
Ref: faq/programming how-do-i-create-static-class-data-and-static-class-methods11833838
Ref: 428611833838
Node: 如何在Python中重载构造函数（或方法）？11835348
Ref: faq/programming how-can-i-overload-constructors-or-methods-in-python11835601
Ref: 428711835601
Node: 我尝试使用 __spam ，但是得到一个关于 _SomeClassName__spam 的错误信息。11836464
Ref: faq/programming i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam11836738
Ref: 428811836738
Node: 类定义了 __del__ 方法，但是删除对象时没有调用它。11837489
Ref: faq/programming my-class-defines-del-but-it-is-not-called-when-i-delete-the-object11837757
Ref: 428911837757
Node: 如何获取给定类的所有实例的列表？11839542
Ref: faq/programming how-do-i-get-a-list-of-all-instances-of-a-given-class11839769
Ref: 428a11839769
Node: 为什么 id 的结果看起来不是唯一的？11840046
Ref: faq/programming why-does-the-result-of-id-appear-to-be-not-unique11840195
Ref: 428b11840195
Node: 模块<3>11840971
Ref: faq/programming modules11841050
Ref: 428c11841050
Node: 如何创建 pyc 文件？11841458
Ref: faq/programming how-do-i-create-a-pyc-file11841572
Ref: 428d11841572
Ref: 如何创建 pyc 文件？-Footnote-111844048
Node: 如何找到当前模块名称？11844097
Ref: faq/programming how-do-i-find-the-current-module-name11844250
Ref: 428e11844250
Node: 如何让模块相互导入？11844753
Ref: faq/programming how-can-i-have-modules-that-mutually-import-each-other11844934
Ref: 428f11844934
Node: __import__ 'x y z' 返回 <module 'x'>; 如何获取z?11846530
Ref: faq/programming import-x-y-z-returns-module-x-how-do-i-get-z11846789
Ref: 429011846789
Node: 当我编辑了导入过的模块并重新导入它时，这些变化没有显示出来。为什么会这样？11847045
Ref: faq/programming when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen11847265
Ref: 429111847265
Node: 设计和历史常见问题11848576
Ref: faq/design doc11848717
Ref: 429211848717
Ref: faq/design design-and-history-faq11848717
Ref: 429311848717
Node: 为什么Python使用缩进来分组语句？11850592
Ref: faq/design why-does-python-use-indentation-for-grouping-of-statements11850764
Ref: 429411850764
Node: 为什么简单的算术运算得到奇怪的结果？11852244
Ref: faq/design why-am-i-getting-strange-results-with-simple-arithmetic-operations11852458
Ref: 429511852458
Node: 为什么浮点计算不准确？11852591
Ref: faq/design why-are-floating-point-calculations-so-inaccurate11852802
Ref: 429611852802
Node: 为什么Python字符串是不可变的？11854170
Ref: faq/design why-are-python-strings-immutable11854394
Ref: 429711854394
Node: 为什么必须在方法定义和调用中显式使用“self”？11854918
Ref: faq/design why-must-self-be-used-explicitly-in-method-definitions-and-calls11855148
Ref: 429811855148
Ref: faq/design why-self11855148
Ref: 428111855148
Node: 为什么不能在表达式中赋值？11857242
Ref: faq/design id211857564
Ref: 429911857564
Ref: faq/design why-can-t-i-use-an-assignment-in-an-expression11857564
Ref: 128811857564
Ref: 为什么不能在表达式中赋值？-Footnote-111857899
Node: 为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？11857948
Ref: faq/design why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list11858275
Ref: 429a11858275
Node: 为什么 join 是一个字符串方法而不是列表或元组方法？11859446
Ref: faq/design why-is-join-a-string-method-instead-of-a-list-or-tuple-method11859752
Ref: 429b11859752
Node: 异常有多快？11861415
Ref: faq/design how-fast-are-exceptions11861633
Ref: 429c11861633
Node: 为什么Python中没有switch或case语句？11862417
Ref: faq/design why-isn-t-there-a-switch-or-case-statement-in-python11862662
Ref: 429d11862662
Ref: 为什么Python中没有switch或case语句？-Footnote-111863916
Node: 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？11863965
Ref: faq/design can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation11864237
Ref: 429e11864237
Ref: 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？-Footnote-111864776
Node: 为什么lambda表达式不能包含语句？11864832
Ref: faq/design why-can-t-lambda-expressions-contain-statements11865119
Ref: 429f11865119
Node: 可以将Python编译为机器代码，C或其他语言吗？11865838
Ref: faq/design can-python-be-compiled-to-machine-code-c-or-some-other-language11866053
Ref: 42a011866053
Ref: 可以将Python编译为机器代码，C或其他语言吗？-Footnote-111866438
Ref: 可以将Python编译为机器代码，C或其他语言吗？-Footnote-211866465
Ref: 可以将Python编译为机器代码，C或其他语言吗？-Footnote-311866496
Node: Python如何管理内存？11866531
Ref: faq/design how-does-python-manage-memory11866759
Ref: 42a111866759
Ref: Python如何管理内存？-Footnote-111868222
Ref: Python如何管理内存？-Footnote-211868252
Node: 为什么CPython不使用更传统的垃圾回收方案？11868280
Ref: faq/design why-doesn-t-cpython-use-a-more-traditional-garbage-collection-scheme11868496
Ref: 42a211868496
Node: CPython退出时为什么不释放所有内存？11869239
Ref: faq/design why-isn-t-all-memory-freed-when-cpython-exits11869479
Ref: 42a311869479
Node: 为什么有单独的元组和列表数据类型？11870058
Ref: faq/design why-are-there-separate-tuple-and-list-data-types11870280
Ref: 42a411870280
Node: 列表是如何在CPython中实现的？11871346
Ref: faq/design how-are-lists-implemented-in-cpython11871559
Ref: 42a511871559
Node: 字典是如何在CPython中实现的？11872207
Ref: faq/design how-are-dictionaries-implemented-in-cpython11872411
Ref: 42a611872411
Node: 为什么字典key必须是不可变的？11873195
Ref: faq/design why-must-dictionary-keys-be-immutable11873406
Ref: 42a711873406
Node: 为什么 list sort 没有返回排序列表？11877169
Ref: faq/design why-doesn-t-list-sort-return-the-sorted-list11877388
Ref: 42a811877388
Node: 如何在Python中指定和实施接口规范？11878144
Ref: faq/design how-do-you-specify-and-enforce-an-interface-spec-in-python11878343
Ref: 42a911878343
Node: 为什么没有goto？11880313
Ref: faq/design why-is-there-no-goto11880531
Ref: 42aa11880531
Node: 为什么原始字符串（r-strings）不能以反斜杠结尾？11881536
Ref: faq/design why-can-t-raw-strings-r-strings-end-with-a-backslash11881761
Ref: 42ab11881761
Node: 为什么Python没有属性赋值的“with”语句？11882787
Ref: faq/design why-doesn-t-python-have-a-with-statement-for-attribute-assignments11883039
Ref: 42ac11883039
Node: 为什么 if/while/def/class语句需要冒号？11884894
Ref: faq/design why-are-colons-required-for-the-if-while-def-class-statements11885143
Ref: 42ad11885143
Node: 为什么Python在列表和元组的末尾允许使用逗号？11885773
Ref: faq/design why-does-python-allow-commas-at-the-end-of-lists-and-tuples11885958
Ref: 42ae11885958
Node: 代码库和插件 FAQ11886909
Ref: faq/library doc11887057
Ref: 42af11887057
Ref: faq/library library-and-extension-faq11887057
Ref: 42b011887057
Node: 通用的代码库问题11887277
Ref: faq/library general-library-questions11887381
Ref: 42b111887381
Node: 如何找到可以用来做 XXX 的模块或应用？11887898
Ref: faq/library how-do-i-find-a-module-or-application-to-perform-task-x11888079
Ref: 42b211888079
Ref: 如何找到可以用来做 XXX 的模块或应用？-Footnote-111888565
Ref: 如何找到可以用来做 XXX 的模块或应用？-Footnote-211888590
Node: math py（socket py，regex py 等）的源文件在哪？11888621
Ref: faq/library where-is-the-math-py-socket-py-regex-py-etc-source-file11888858
Ref: 42b311888858
Node: 在 Unix 中怎样让 Python 脚本可执行？11889604
Ref: faq/library how-do-i-make-a-python-script-executable-on-unix11889826
Ref: 42b411889826
Node: Python 中有 curses/termcap 包吗？11891222
Ref: faq/library is-there-a-curses-termcap-package-for-python11891443
Ref: 42b511891443
Ref: Python 中有 curses/termcap 包吗？-Footnote-111892184
Ref: Python 中有 curses/termcap 包吗？-Footnote-211892243
Node: Python 中存在类似 C 的 onexit 函数的东西吗？11892292
Ref: faq/library is-there-an-equivalent-to-c-s-onexit-in-python11892514
Ref: 42b611892514
Node: 为什么我的信号处理函数不能工作？11892735
Ref: faq/library why-don-t-my-signal-handlers-work11892910
Ref: 42b711892910
Node: 通用任务11893226
Ref: faq/library common-tasks11893351
Ref: 42b811893351
Node: 怎样测试 Python 程序或组件？11893522
Ref: faq/library how-do-i-test-a-python-program-or-component11893653
Ref: 42b911893653
Node: 怎样用 docstring 创建文档？11895340
Ref: faq/library how-do-i-create-documentation-from-doc-strings11895516
Ref: 42ba11895516
Ref: 怎样用 docstring 创建文档？-Footnote-111895840
Ref: 怎样用 docstring 创建文档？-Footnote-211895879
Node: 怎样一次只获取一个按键？11895909
Ref: faq/library how-do-i-get-a-single-keypress-at-a-time11896038
Ref: 42bb11896038
Node: 线程相关11896245
Ref: faq/library threads11896361
Ref: 42bc11896361
Node: 程序中怎样使用线程？11896631
Ref: faq/library how-do-i-program-using-threads11896761
Ref: 42bd11896761
Node: 我的线程都没有运行，为什么？11897159
Ref: faq/library none-of-my-threads-seem-to-run-why11897343
Ref: 42be11897343
Node: 如何将任务分配给多个工作线程？11898843
Ref: faq/library how-do-i-parcel-out-work-among-a-bunch-of-worker-threads11899042
Ref: 42bf11899042
Node: 怎样修改全局变量是线程安全的？11901528
Ref: faq/library what-kinds-of-global-value-mutation-are-thread-safe11901721
Ref: 42c011901721
Node: 不能删除全局解释器锁吗？11903064
Ref: faq/library can-t-we-get-rid-of-the-global-interpreter-lock11903203
Ref: 42c111903203
Ref: 不能删除全局解释器锁吗？-Footnote-111905467
Node: 输入输出<2>11905527
Ref: faq/library input-and-output11905655
Ref: 42c211905655
Node: 怎样删除文件？（以及其他文件相关的问题……）11906193
Ref: faq/library how-do-i-delete-a-file-and-other-file-questions11906341
Ref: 42c311906341
Node: 怎样复制文件？11907595
Ref: faq/library how-do-i-copy-a-file11907797
Ref: 42c411907797
Node: 怎样读取（或写入）二进制数据？11907987
Ref: faq/library how-do-i-read-or-write-binary-data11908196
Ref: 42c511908196
Node: 似乎 os popen 创建的管道不能使用 os read ，这是为什么？11909392
Ref: faq/library i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why11909612
Ref: 42c611909612
Node: 怎样访问（RS232）串口？11910152
Ref: faq/library how-do-i-access-the-serial-rs232-port11910400
Ref: 42c711910400
Node: 为什么关闭 sys stdout（stdin，stderr）并不会真正关掉它？11910704
Ref: faq/library why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it11910870
Ref: 42c811910870
Node: 网络 / Internet 编程11912003
Ref: faq/library network-internet-programming11912128
Ref: 42c911912128
Node: Python 中的 WWW 工具是什么？11912484
Ref: faq/library what-www-tools-are-there-for-python11912639
Ref: 42ca11912639
Node: 怎样模拟发送 CGI 表单（METHOD=POST）？11913190
Ref: faq/library how-can-i-mimic-cgi-form-submission-method-post11913393
Ref: 42cb11913393
Node: 生成 HTML 需要使用什么模块？11914445
Ref: faq/library what-module-should-i-use-to-help-with-generating-html11914653
Ref: 42cc11914653
Ref: 生成 HTML 需要使用什么模块？-Footnote-111914848
Node: 怎样使用 Python 脚本发送邮件？11914900
Ref: faq/library how-do-i-send-mail-from-a-python-script11915105
Ref: 42cd11915105
Node: socket 的 connect 方法怎样避免阻塞？11916420
Ref: faq/library how-do-i-avoid-blocking-in-the-connect-method-of-a-socket11916577
Ref: 42ce11916577
Ref: socket 的 connect 方法怎样避免阻塞？-Footnote-111917656
Node: 数据库11917696
Ref: faq/library databases11917821
Ref: 42cf11917821
Node: Python 中有数据库包的接口吗？11917957
Ref: faq/library are-there-any-interfaces-to-database-packages-in-python11918096
Ref: 42d011918096
Ref: Python 中有数据库包的接口吗？-Footnote-111918560
Node: 在 Python 中如何实现持久化对象？11918617
Ref: faq/library how-do-you-implement-persistent-objects-in-python11918756
Ref: 42d111918756
Node: 数学和数字11919146
Ref: faq/library mathematics-and-numerics11919238
Ref: 42d211919238
Node: Python 中怎样生成随机数？11919329
Ref: faq/library how-do-i-generate-random-numbers-in-python11919415
Ref: 42d311919415
Node: 扩展/嵌入常见问题11920290
Ref: faq/extending doc11920445
Ref: 42d411920445
Ref: faq/extending extending-embedding-faq11920445
Ref: 42d511920445
Node: 可以使用 C 语言创建自己的函数吗？11921690
Ref: faq/extending can-i-create-my-own-functions-in-c11921859
Ref: 42d611921859
Node: 可以使用 C++ 语言创建自己的函数吗？11922189
Ref: faq/extending id211922404
Ref: 42d711922404
Node: C很难写，有没有其他选择？11922781
Ref: faq/extending c-wrapper-software11922992
Ref: 42d811922992
Ref: faq/extending writing-c-is-hard-are-there-any-alternatives11922992
Ref: 42d911922992
Ref: C很难写，有没有其他选择？-Footnote-111923590
Ref: C很难写，有没有其他选择？-Footnote-211923616
Ref: C很难写，有没有其他选择？-Footnote-311923683
Ref: C很难写，有没有其他选择？-Footnote-411923711
Ref: C很难写，有没有其他选择？-Footnote-511923769
Ref: C很难写，有没有其他选择？-Footnote-611923805
Ref: C很难写，有没有其他选择？-Footnote-711923861
Node: 如何在 C 中执行任意 Python 语句？11923900
Ref: faq/extending how-can-i-execute-arbitrary-python-statements-from-c11924111
Ref: 42da11924111
Node: 如何在 C 中对任意 Python 表达式求值？11924635
Ref: faq/extending how-can-i-evaluate-an-arbitrary-python-expression-from-c11924849
Ref: 42db11924849
Node: 如何从Python对象中提取C的值？11925136
Ref: faq/extending how-do-i-extract-c-values-from-a-python-object11925362
Ref: 42dc11925362
Node: 如何使用Py_BuildValue 创建任意长度的元组？11926568
Ref: faq/extending how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length11926778
Ref: 42dd11926778
Node: 如何从C调用对象的方法？11926953
Ref: faq/extending how-do-i-call-an-object-s-method-from-c11927207
Ref: 42de11927207
Node: 如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？11928379
Ref: faq/extending how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr11928620
Ref: 42df11928620
Node: 如何从C访问用Python编写的模块？11929830
Ref: faq/extending how-do-i-access-a-module-written-in-python-from-c11930078
Ref: 42e011930078
Node: 如何在 Python 中对接 C ++ 对象？11930877
Ref: faq/extending how-do-i-interface-to-c-objects-from-python11931110
Ref: 42e111931110
Node: 我使用Setup文件添加了一个模块，为什么make失败了？11931622
Ref: faq/extending i-added-a-module-using-the-setup-file-and-the-make-fails-why11931833
Ref: 42e211931833
Node: 如何调试扩展？11932185
Ref: faq/extending how-do-i-debug-an-extension11932442
Ref: 42e311932442
Node: 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?11932956
Ref: faq/extending i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why11933201
Ref: 42e411933201
Node: 如何区分“输入不完整”和“输入无效”？11933643
Ref: faq/extending how-do-i-tell-incomplete-input-from-invalid-input11933933
Ref: 42e511933933
Node: 如何找到未定义的g++符号__builtin_new或__pure_virtual？11939901
Ref: faq/extending how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual11940228
Ref: 42e611940228
Node: 能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？11940589
Ref: faq/extending can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance11940850
Ref: 42e711940850
Node: Python在Windows上的常见问题11941378
Ref: faq/windows doc11941550
Ref: 42e811941550
Ref: faq/windows python-on-windows-faq11941550
Ref: 42e911941550
Ref: faq/windows windows-faq11941550
Ref: 42ea11941550
Node: 我怎样在Windows下运行一个Python程序？11942103
Ref: faq/windows faq-run-program-under-windows11942270
Ref: 42eb11942270
Ref: faq/windows how-do-i-run-a-python-program-under-windows11942270
Ref: 42ec11942270
Node: 我怎么让 Python 脚本可执行？11945394
Ref: faq/windows how-do-i-make-python-scripts-executable11945620
Ref: 42ed11945620
Node: 为什么有时候 Python 程序会启动缓慢？11946145
Ref: faq/windows why-does-python-sometimes-take-so-long-to-start11946375
Ref: 42ee11946375
Node: 我怎样使用 Python 脚本制作可执行文件？11947137
Ref: faq/windows how-do-i-make-an-executable-from-a-python-script11947367
Ref: 42ef11947367
Ref: 我怎样使用 Python 脚本制作可执行文件？-Footnote-111947655
Ref: 我怎样使用 Python 脚本制作可执行文件？-Footnote-211947707
Node: * pyd 文件和 DLL 文件相同吗？11947738
Ref: faq/windows is-a-pyd-file-the-same-as-a-dll11947968
Ref: 42f011947968
Node: 我怎样将 Python 嵌入一个 Windows 程序？11948912
Ref: faq/windows how-can-i-embed-python-into-a-windows-application11949156
Ref: 42f111949156
Node: 如何让编辑器不要在我的 Python 源代码中插入 tab ？11953272
Ref: faq/windows how-do-i-keep-editors-from-inserting-tabs-into-my-python-source11953523
Ref: 42f211953523
Ref: 如何让编辑器不要在我的 Python 源代码中插入 tab ？-Footnote-111954389
Node: 如何在不阻塞的情况下检查按键？11954438
Ref: faq/windows how-do-i-check-for-a-keypress-without-blocking11954630
Ref: 42f311954630
Node: 图形用户界面（GUI）常见问题11954971
Ref: faq/gui doc11955168
Ref: 42f411955168
Ref: faq/gui graphic-user-interface-faq11955168
Ref: 42f511955168
Node: 图形界面常见问题11955432
Ref: faq/gui general-gui-questions11955596
Ref: 42f611955596
Node: Python 是否有平台无关的图形界面工具包？11955653
Ref: faq/gui what-platform-independent-gui-toolkits-exist-for-python11955880
Ref: 42f711955880
Node: Tkinter11956293
Ref: faq/gui tkinter11956410
Ref: 42f811956410
Ref: Tkinter-Footnote-111956891
Ref: Tkinter-Footnote-211956933
Node: wxWidgets11956960
Ref: faq/gui wxwidgets11957088
Ref: 42fa11957088
Ref: wxWidgets-Footnote-111957979
Node: Qt11958012
Ref: faq/gui qt11958137
Ref: 42f911958137
Ref: Qt-Footnote-111958598
Ref: Qt-Footnote-211958657
Ref: Qt-Footnote-311958691
Ref: Qt-Footnote-411958755
Ref: Qt-Footnote-511958821
Node: Gtk+11958858
Ref: faq/gui gtk11958978
Ref: 42fb11958978
Ref: Gtk+-Footnote-111959306
Ref: Gtk+-Footnote-211959356
Ref: Gtk+-Footnote-311959409
Node: Kivy11959437
Ref: faq/gui kivy11959559
Ref: 42fc11959559
Ref: Kivy-Footnote-111959917
Node: FLTK11959943
Ref: faq/gui fltk11960067
Ref: 42fd11960067
Ref: FLTK-Footnote-111960286
Ref: FLTK-Footnote-211960314
Node: OpenGL11960352
Ref: faq/gui opengl11960463
Ref: 42fe11960463
Ref: OpenGL-Footnote-111960579
Node: 有哪些Python的GUI工具是某个平台专用的？11960619
Ref: faq/gui what-platform-specific-gui-toolkits-exist-for-python11960844
Ref: 42ff11960844
Ref: 有哪些Python的GUI工具是某个平台专用的？-Footnote-111961241
Node: 有关Tkinter的问题11961282
Ref: faq/gui tkinter-questions11961443
Ref: 430011961443
Node: 我怎样“冻结”Tkinter程序？11961658
Ref: faq/gui how-do-i-freeze-tkinter-applications11961814
Ref: 430111961814
Node: 在等待 I/O 操作时能够处理 Tk 事件吗？11962761
Ref: faq/gui can-i-have-tk-events-handled-while-waiting-for-i-o11962972
Ref: 430211962972
Node: 在Tkinter中键绑定不工作：为什么？11963453
Ref: faq/gui i-can-t-get-key-bindings-to-work-in-tkinter-why11963618
Ref: 430311963618
Node: “为什么我的电脑上安装了 Python ？”11964129
Ref: faq/installed doc11964283
Ref: 430411964283
Ref: faq/installed why-is-python-installed-on-my-computer-faq11964283
Ref: 430511964283
Node: 什么是 Python？<2>11964517
Ref: faq/installed what-is-python11964679
Ref: 430611964679
Ref: 什么是 Python？<2>-Footnote-111965049
Node: 为什么我的电脑上安装了 Python ？11965101
Ref: faq/installed why-is-python-installed-on-my-machine11965298
Ref: 430711965298
Node: 我能删除 Python 吗？11966222
Ref: faq/installed can-i-delete-python11966388
Ref: 430811966388
Node: 术语对照表11967140
Ref: glossary doc11967244
Ref: 430911967244
Ref: glossary glossary11967244
Ref: 120f11967244
Ref: glossary id111967244
Ref: 430a11967244
Ref: glossary term-011967278
Ref: 122811967278
Ref: glossary term-111967428
Ref: 122911967428
Ref: glossary term-2to311967763
Ref: 103211967763
Ref: glossary term-abstract-base-class11968152
Ref: b3b11968152
Ref: glossary term-annotation11969007
Ref: 430c11969007
Ref: glossary term-argument11969495
Ref: 153211969495
Ref: glossary term-asynchronous-context-manager11970757
Ref: 64a11970757
Ref: glossary term-asynchronous-generator11971006
Ref: 151311971006
Ref: glossary term-asynchronous-generator-iterator11971681
Ref: 363d11971681
Ref: glossary term-asynchronous-iterable11972380
Ref: 64911972380
Ref: glossary term-asynchronous-iterator11972628
Ref: 64e11972628
Ref: glossary term-attribute11973046
Ref: 430f11973046
Ref: glossary term-awaitable11973256
Ref: 52111973256
Ref: glossary term-bdfl11973462
Ref: 431011973462
Ref: glossary term-binary-file11973574
Ref: 1cb411973574
Ref: glossary term-bytes-like-object11974036
Ref: 5f111974036
Ref: glossary term-bytecode11974937
Ref: 61d11974937
Ref: glossary term-callback11975559
Ref: 25b111975559
Ref: glossary term-class11975677
Ref: 161211975677
Ref: glossary term-class-variable11975816
Ref: 431111975816
Ref: glossary term-coercion11975961
Ref: 431211975961
Ref: glossary term-complex-number11976547
Ref: 431311976547
Ref: glossary term-context-manager11977192
Ref: 57111977192
Ref: glossary term-context-variable11977408
Ref: 431411977408
Ref: glossary term-contiguous11977832
Ref: 16c511977832
Ref: glossary term-coroutine11978303
Ref: 1a711978303
Ref: glossary term-coroutine-function11978586
Ref: 64811978586
Ref: glossary term-cpython11978900
Ref: 144611978900
Ref: glossary term-decorator11979092
Ref: 28411979092
Ref: glossary term-descriptor11979733
Ref: 161611979733
Ref: glossary term-dictionary11980488
Ref: 431511980488
Ref: glossary term-dictionary-comprehension11980718
Ref: 431611980718
Ref: glossary term-dictionary-view11981067
Ref: 195511981067
Ref: glossary term-docstring11981488
Ref: 15c511981488
Ref: glossary term-duck-typing11981825
Ref: 430b11981825
Ref: glossary term-eafp11982474
Ref: 1f5b11982474
Ref: glossary term-expression11982863
Ref: 363111982863
Ref: glossary term-extension-module11983329
Ref: 431811983329
Ref: glossary term-f-string11983484
Ref: 15c11983484
Ref: glossary term-file-object11983689
Ref: b4a11983689
Ref: glossary term-file-like-object11984437
Ref: 1c7a11984437
Ref: glossary term-finder11984521
Ref: 14ca11984521
Ref: glossary term-floor-division11984915
Ref: 122e11984915
Ref: glossary term-function11985325
Ref: 153311985325
Ref: glossary term-function-annotation11985596
Ref: 126d11985596
Ref: glossary term-future11986120
Ref: 68c11986120
Ref: glossary term-garbage-collection11986527
Ref: ed811986527
Ref: glossary term-generator11986812
Ref: 9aa11986812
Ref: glossary term-generator-iterator11987269
Ref: 45f11987269
Ref: glossary term-generator-expression11987660
Ref: 431911987660
Ref: glossary term-generic-function11988061
Ref: 1cc11988061
Ref: glossary term-gil11988386
Ref: bf211988386
Ref: glossary term-global-interpreter-lock11988443
Ref: 50e11988443
Ref: glossary term-hash-based-pyc11989416
Ref: 431a11989416
Ref: glossary term-hashable11989624
Ref: 143911989624
Ref: glossary term-idle11990560
Ref: 431b11990560
Ref: glossary term-immutable11990718
Ref: 123211990718
Ref: glossary term-import-path11991032
Ref: 14cd11991032
Ref: glossary term-importing11991366
Ref: 14be11991366
Ref: glossary term-importer11991498
Ref: 14cc11991498
Ref: glossary term-interactive11991638
Ref: 431c11991638
Ref: glossary term-interpreted11992058
Ref: 431d11992058
Ref: glossary term-interpreter-shutdown11992495
Ref: 76c11992495
Ref: glossary term-iterable11993116
Ref: bb411993116
Ref: glossary term-iterator11994246
Ref: 104b11994246
Ref: glossary term-key-function11995385
Ref: 6e911995385
Ref: glossary term-keyword-argument11996482
Ref: 5cd11996482
Ref: glossary term-lambda11996558
Ref: 36d711996558
Ref: glossary term-lbyl11996760
Ref: 431711996760
Ref: glossary term-list11997361
Ref: 431e11997361
Ref: glossary term-list-comprehension11997566
Ref: 431f11997566
Ref: glossary term-loader11998001
Ref: 14cb11998001
Ref: glossary term-magic-method11998291
Ref: 432011998291
Ref: glossary term-mapping11998381
Ref: b4111998381
Ref: glossary term-meta-path-finder11998741
Ref: 9b911998741
Ref: glossary term-metaclass11999057
Ref: 233911999057
Ref: glossary term-method11999681
Ref: 430e11999681
Ref: glossary term-method-resolution-order11999966
Ref: 161411999966
Ref: glossary term-module12000227
Ref: 14bd12000227
Ref: glossary term-module-spec12000492
Ref: 364112000492
Ref: glossary term-mro12000669
Ref: 288c12000669
Ref: glossary term-mutable12000727
Ref: 123a12000727
Ref: glossary term-named-tuple12000882
Ref: aab12000882
Ref: glossary term-namespace12001956
Ref: 432112001956
Ref: glossary term-namespace-package12002612
Ref: 14c312002612
Ref: glossary term-nested-scope12002942
Ref: 15fb12002942
Ref: glossary term-new-style-class12003383
Ref: 1cbc12003383
Ref: glossary term-object12003719
Ref: 432212003719
Ref: glossary term-package12003905
Ref: ec612003905
Ref: glossary term-parameter12004176
Ref: 153b12004176
Ref: glossary positional-only-parameter12004711
Ref: 2a812004711
Ref: glossary keyword-only-parameter12005057
Ref: 2ad12005057
Ref: glossary term-path-entry12006372
Ref: 14df12006372
Ref: glossary term-path-entry-finder12006536
Ref: 9ba12006536
Ref: glossary term-path-entry-hook12006906
Ref: 14e112006906
Ref: glossary term-path-based-finder12007148
Ref: 14d012007148
Ref: glossary term-path-like-object12007313
Ref: 37312007313
Ref: glossary term-pep12007965
Ref: 432312007965
Ref: glossary term-portion12008531
Ref: 14c512008531
Ref: glossary term-positional-argument12008698
Ref: 5ce12008698
Ref: glossary term-provisional-api12008774
Ref: 35112008774
Ref: glossary term-provisional-package12009631
Ref: 98812009631
Ref: glossary term-python-300012009710
Ref: 432412009710
Ref: glossary term-pythonic12009883
Ref: 432512009883
Ref: glossary term-qualified-name12010497
Ref: 143b12010497
Ref: glossary term-reference-count12011354
Ref: 3b3712011354
Ref: glossary term-regular-package12011780
Ref: 14c212011780
Ref: glossary term-slots12011967
Ref: 37a012011967
Ref: glossary term-sequence12012285
Ref: 123812012285
Ref: glossary term-set-comprehension12013237
Ref: 432612013237
Ref: glossary term-single-dispatch12013556
Ref: 1cb12013556
Ref: glossary term-slice12013705
Ref: 161012013705
Ref: glossary term-special-method12014026
Ref: 366c12014026
Ref: glossary term-statement12014290
Ref: 1ba212014290
Ref: glossary term-text-encoding12014546
Ref: 160b12014546
Ref: glossary term-text-file12014643
Ref: 12b512014643
Ref: glossary term-triple-quoted-string12015179
Ref: 432712015179
Ref: glossary term-type12015604
Ref: 432812015604
Ref: glossary term-type-alias12015846
Ref: 432912015846
Ref: glossary term-type-hint12016514
Ref: 430d12016514
Ref: glossary term-universal-newlines12017058
Ref: 5fd12017058
Ref: glossary term-variable-annotation12017415
Ref: 62812017415
Ref: glossary term-virtual-environment12017999
Ref: 132212017999
Ref: glossary term-virtual-machine12018290
Ref: 279212018290
Ref: glossary term-zen-of-python12018458
Ref: 432a12018458
Ref: 术语对照表-Footnote-112018702
Ref: 术语对照表-Footnote-212018751
Ref: 术语对照表-Footnote-312018800
Ref: 术语对照表-Footnote-412018849
Ref: 术语对照表-Footnote-512018898
Ref: 术语对照表-Footnote-612018947
Ref: 术语对照表-Footnote-712018996
Ref: 术语对照表-Footnote-812019045
Ref: 术语对照表-Footnote-912019094
Ref: 术语对照表-Footnote-1012019143
Ref: 术语对照表-Footnote-1112019182
Ref: 术语对照表-Footnote-1212019232
Ref: 术语对照表-Footnote-1312019282
Ref: 术语对照表-Footnote-1412019332
Ref: 术语对照表-Footnote-1512019364
Ref: 术语对照表-Footnote-1612019414
Ref: 术语对照表-Footnote-1712019464
Ref: 术语对照表-Footnote-1812019514
Ref: 术语对照表-Footnote-1912019564
Ref: 术语对照表-Footnote-2012019614
Ref: 术语对照表-Footnote-2112019664
Ref: 术语对照表-Footnote-2212019714
Ref: 术语对照表-Footnote-2312019764
Ref: 术语对照表-Footnote-2412019823
Ref: 术语对照表-Footnote-2512019873
Ref: 术语对照表-Footnote-2612019923
Ref: 术语对照表-Footnote-2712019973
Ref: 术语对照表-Footnote-2812020023
Ref: 术语对照表-Footnote-2912020073
Ref: 术语对照表-Footnote-3012020123
Ref: 术语对照表-Footnote-3112020173
Ref: 术语对照表-Footnote-3212020223
Ref: 术语对照表-Footnote-3312020273
Ref: 术语对照表-Footnote-3412020323
Ref: 术语对照表-Footnote-3512020373
Ref: 术语对照表-Footnote-3612020423
Node: 文档说明12020473
Ref: about doc12020570
Ref: 432b12020570
Ref: about about-these-documents12020570
Ref: 432c12020570
Ref: 文档说明-Footnote-112021365
Ref: 文档说明-Footnote-212021396
Ref: 文档说明-Footnote-312021445
Ref: 文档说明-Footnote-412021486
Node: Python 文档的贡献者12021527
Ref: about contributors-to-the-python-documentation12021601
Ref: 432d12021601
Ref: Python 文档的贡献者-Footnote-112021961
Node: 处理错误12022022
Ref: bugs doc12022116
Ref: 432e12022116
Ref: bugs dealing-with-bugs12022116
Ref: 432f12022116
Ref: bugs reporting-bugs12022116
Ref: 3b9912022116
Node: 文档 Bug12022582
Ref: bugs documentation-bugs12022685
Ref: 433112022685
Ref: 文档 Bug-Footnote-112023729
Ref: 文档 Bug-Footnote-212023874
Ref: 文档 Bug-Footnote-312023919
Node: 使用 Python 的问题追踪系统12023995
Ref: bugs using-the-python-issue-tracker12024142
Ref: 433312024142
Ref: bugs using-the-tracker12024142
Ref: 433212024142
Ref: 使用 Python 的问题追踪系统-Footnote-112026381
Ref: 使用 Python 的问题追踪系统-Footnote-212026444
Node: 开始为 Python 贡献您的知识12026528
Ref: bugs contributing-to-python12026656
Ref: 433012026656
Ref: bugs getting-started-contributing-to-python-yourself12026656
Ref: 433412026656
Ref: 开始为 Python 贡献您的知识-Footnote-112027097
Ref: 开始为 Python 贡献您的知识-Footnote-212027134
Node: 版权所有12027210
Ref: copyright doc12027310
Ref: 433512027310
Ref: copyright copyright12027310
Ref: 433612027310
Ref: copyright core-mentorship-mailing-list12027310
Ref: 433712027310
Node: 历史和许可证12027831
Ref: license doc12027957
Ref: 433912027957
Ref: license history-and-license12027957
Ref: 433812027957
Ref: license id112027957
Ref: 433a12027957
Node: 该软件的历史12028125
Ref: license history-of-the-software12028263
Ref: 433b12028263
Node: 获取或以其他方式使用 Python 的条款和条件12032645
Ref: license terms-and-conditions-for-accessing-or-otherwise-using-python12032822
Ref: 433c12032822
Node: 用于 PYTHON 3 8 12 的 PSF 许可协议12033926
Ref: license psf-license12034114
Ref: 433d12034114
Ref: license psf-license-agreement-for-python-release12034114
Ref: 434012034114
Node: 用于 PYTHON 2 0 的 BEOPEN COM 许可协议12036792
Ref: license beopen-com-license-agreement-for-python-2-012037030
Ref: 434112037030
Node: 用于 PYTHON 1 6 1 的 CNRI 许可协议12039723
Ref: license cnri-license-agreement-for-python-1-6-112039968
Ref: 434212039968
Node: 用于 PYTHON 0 9 0 至 1 2 的 CWI 许可协议12044143
Ref: license cwi-license-agreement-for-python-0-9-0-through-1-212044410
Ref: 434312044410
Node: ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3 8 12 DOCUMENTATION12045668
Ref: license bsd012045885
Ref: 433e12045885
Ref: license zero-clause-bsd-license-for-code-in-the-python-release-documentation12045885
Ref: 434412045885
Node: 收录软件的许可与鸣谢12046689
Ref: license licenses-and-acknowledgements-for-incorporated-software12046839
Ref: 434512046839
Ref: license otherlicenses12046839
Ref: 433f12046839
Node: Mersenne Twister12047372
Ref: license mersenne-twister12047476
Ref: 434612047476
Node: 套接字<2>12049724
Ref: license sockets12049858
Ref: 434712049858
Node: 异步套接字服务12051682
Ref: license asynchronous-socket-services12051813
Ref: 434812051813
Node: Cookie 管理12052996
Ref: license cookie-management12053127
Ref: 434912053127
Node: 执行追踪12054318
Ref: license execution-tracing12054456
Ref: 434a12054456
Node: UUencode 与 UUdecode 函数12055686
Ref: license uuencode-and-uudecode-functions12055833
Ref: 434b12055833
Node: XML 远程过程调用12057390
Ref: license xml-remote-procedure-calls12057535
Ref: 434c12057535
Node: test_epoll12059030
Ref: license test-epoll12059160
Ref: 434d12059160
Node: Select kqueue12060404
Ref: license select-kqueue12060521
Ref: 434e12060521
Node: SipHash2412062057
Ref: license siphash2412062179
Ref: 434f12062179
Node: strtod 和 dtoa12063339
Ref: license strtod-and-dtoa12063455
Ref: 435012063455
Node: OpenSSL12064766
Ref: license openssl12064878
Ref: 435112064878
Node: expat12072385
Ref: license expat12072488
Ref: 435212072488
Node: libffi12073877
Ref: license libffi12073980
Ref: 435312073980
Node: zlib<3>12075309
Ref: license zlib12075414
Ref: 435412075414
Node: cfuhash12076625
Ref: license cfuhash12076732
Ref: 435512076732
Node: libmpdec12078516
Ref: license libmpdec12078637
Ref: 435612078637
Node: W3C C14N 测试套件12080197
Ref: license w3c-c14n-test-suite12080302
Ref: 435712080302
Node: 分发 Python 模块（遗留版本）12082218
Ref: distutils/index doc12082362
Ref: 435812082362
Ref: distutils/index distributing-python-modules-legacy-version12082362
Ref: 435912082362
Ref: distutils/index distutils-index12082362
Ref: 80112082362
Ref: 分发 Python 模块（遗留版本）-Footnote-112083634
Node: Distutils 模块介绍12083700
Ref: distutils/introduction doc12083824
Ref: 435a12083824
Ref: distutils/introduction an-introduction-to-distutils12083824
Ref: 435b12083824
Ref: distutils/introduction distutils-intro12083824
Ref: 435c12083824
Node: 概念和术语12084482
Ref: distutils/introduction concepts-terminology12084589
Ref: 435d12084589
Ref: distutils/introduction distutils-concepts12084589
Ref: 435e12084589
Node: 一个简单的例子<3>12085778
Ref: distutils/introduction a-simple-example12085917
Ref: 435f12085917
Ref: distutils/introduction distutils-simple-example12085917
Ref: 436012085917
Node: 通用的 Python 术语12089781
Ref: distutils/introduction general-python-terminology12089930
Ref: 436212089930
Ref: distutils/introduction python-terms12089930
Ref: 436312089930
Node: Distutils 特定的术语12091934
Ref: distutils/introduction distutils-specific-terminology12092050
Ref: 436412092050
Ref: distutils/introduction distutils-term12092050
Ref: 436512092050
Node: 编写安装脚本12093184
Ref: distutils/setupscript doc12093350
Ref: 436612093350
Ref: distutils/setupscript setup-script12093350
Ref: 436112093350
Ref: distutils/setupscript writing-the-setup-script12093350
Ref: 436712093350
Node: Listing whole packages12096696
Ref: distutils/setupscript listing-packages12096808
Ref: 436912096808
Ref: distutils/setupscript listing-whole-packages12096808
Ref: 436a12096808
Node: Listing individual modules12099264
Ref: distutils/setupscript listing-individual-modules12099413
Ref: 436b12099413
Ref: distutils/setupscript listing-modules12099413
Ref: 436c12099413
Node: Describing extension modules12100219
Ref: distutils/setupscript describing-extension-modules12100394
Ref: 436d12100394
Ref: distutils/setupscript describing-extensions12100394
Ref: 436e12100394
Node: 扩展名和软件包12102141
Ref: distutils/setupscript extension-names-and-packages12102258
Ref: 437012102258
Node: Extension source files12103336
Ref: distutils/setupscript extension-source-files12103482
Ref: 437112103482
Node: Preprocessor options12104878
Ref: distutils/setupscript preprocessor-options12105018
Ref: 437212105018
Node: Library options12108030
Ref: distutils/setupscript library-options12108163
Ref: 437312108163
Node: 其他选项<2>12109141
Ref: distutils/setupscript other-options12109245
Ref: 437412109245
Node: Relationships between Distributions and Packages12110394
Ref: distutils/setupscript relationships-between-distributions-and-packages12110561
Ref: 437512110561
Node: Installing Scripts12113929
Ref: distutils/setupscript distutils-installing-scripts12114091
Ref: 437612114091
Ref: distutils/setupscript installing-scripts12114091
Ref: 437712114091
Node: Installing Package Data12115189
Ref: distutils/setupscript distutils-installing-package-data12115330
Ref: 437812115330
Ref: distutils/setupscript installing-package-data12115330
Ref: 437912115330
Node: Installing Additional Files12117032
Ref: distutils/setupscript distutils-additional-files12117175
Ref: 437a12117175
Ref: distutils/setupscript installing-additional-files12117175
Ref: 437b12117175
Node: Additional meta-data12119059
Ref: distutils/setupscript additional-meta-data12119205
Ref: 437c12119205
Ref: distutils/setupscript meta-data12119205
Ref: 436812119205
Ref: Additional meta-data-Footnote-112126534
Node: Debugging the setup script12126571
Ref: distutils/setupscript debug-setup-script12126681
Ref: 437d12126681
Ref: distutils/setupscript debugging-the-setup-script12126681
Ref: 437e12126681
Node: 编写设置脚本的配置文件12127756
Ref: distutils/configfile doc12127930
Ref: 437f12127930
Ref: distutils/configfile setup-config12127930
Ref: 438012127930
Ref: distutils/configfile writing-the-setup-configuration-file12127930
Ref: 438112127930
Ref: distutils/configfile distutils-build-ext-inplace12130838
Ref: 438212130838
Ref: 编写设置脚本的配置文件-Footnote-112133068
Node: Creating a Source Distribution12133167
Ref: distutils/sourcedist doc12133341
Ref: 438412133341
Ref: distutils/sourcedist creating-a-source-distribution12133341
Ref: 438512133341
Ref: distutils/sourcedist source-dist12133341
Ref: 438612133341
Node: Specifying the files to distribute12136133
Ref: distutils/sourcedist manifest12136267
Ref: 3b7d12136267
Ref: distutils/sourcedist specifying-the-files-to-distribute12136267
Ref: 438712136267
Node: Manifest-related options12142198
Ref: distutils/sourcedist manifest-options12142332
Ref: 438912142332
Ref: distutils/sourcedist manifest-related-options12142332
Ref: 438a12142332
Node: 创建构建分布12143427
Ref: distutils/builtdist doc12143584
Ref: 438b12143584
Ref: distutils/builtdist built-dist12143584
Ref: 438c12143584
Ref: distutils/builtdist creating-built-distributions12143584
Ref: 438d12143584
Node: 创建RPM软件包12151076
Ref: distutils/builtdist creating-rpm-packages12151185
Ref: 438e12151185
Ref: distutils/builtdist creating-rpms12151185
Ref: 438f12151185
Node: Creating Windows Installers12158800
Ref: distutils/builtdist creating-windows-installers12158944
Ref: 439012158944
Ref: distutils/builtdist creating-wininst12158944
Ref: 439112158944
Node: Cross-compiling on Windows12161170
Ref: distutils/builtdist cross-compile-windows12161325
Ref: 439212161325
Ref: distutils/builtdist cross-compiling-on-windows12161325
Ref: 439312161325
Node: The Postinstallation script12163007
Ref: distutils/builtdist postinstallation-script12163097
Ref: 439412163097
Ref: distutils/builtdist the-postinstallation-script12163097
Ref: 439512163097
Ref: distutils/builtdist directory_created12164002
Ref: 439612164002
Ref: distutils/builtdist file_created12164039
Ref: 439712164039
Ref: distutils/builtdist get_special_folder_path12164388
Ref: 439812164388
Ref: distutils/builtdist create_shortcut12165280
Ref: 439912165280
Node: Vista User Access Control UAC12165995
Ref: distutils/builtdist vista-user-access-control-uac12166114
Ref: 439a12166114
Node: Distutils 示例12166572
Ref: distutils/examples doc12166715
Ref: 439b12166715
Ref: distutils/examples distutils-examples12166715
Ref: 439c12166715
Ref: distutils/examples id112166715
Ref: 439d12166715
Ref: Distutils 示例-Footnote-112167417
Node: 纯 Python 分发（通过 module）12167473
Ref: distutils/examples pure-mod12167604
Ref: 439e12167604
Ref: distutils/examples pure-python-distribution-by-module12167604
Ref: 439f12167604
Node: 纯 Python 分发（通过 包）12169132
Ref: distutils/examples pure-pkg12169290
Ref: 43a012169290
Ref: distutils/examples pure-python-distribution-by-package12169290
Ref: 43a112169290
Node: 单个扩展模块12172746
Ref: distutils/examples single-ext12172883
Ref: 43a212172883
Ref: distutils/examples single-extension-module12172883
Ref: 43a312172883
Node: 检查一个包12173871
Ref: distutils/examples checking-a-package12173990
Ref: 43a412173990
Ref: 检查一个包-Footnote-112175535
Node: 读取元数据12175575
Ref: distutils/examples reading-the-metadata12175667
Ref: 43a512175667
Node: 扩展 Distutils12177156
Ref: distutils/extending doc12177293
Ref: 43a612177293
Ref: distutils/extending docutils12177293
Ref: 43a712177293
Ref: distutils/extending extending-distutils12177293
Ref: 13a912177293
Ref: distutils/extending id112177293
Ref: 43a812177293
Node: 集成新的命令12178400
Ref: distutils/extending integrating-new-commands12178504
Ref: 43aa12178504
Node: 添加新的发布类型12181024
Ref: distutils/extending adding-new-distribution-types12181128
Ref: 43ab12181128
Node: 命令参考12181552
Ref: distutils/commandref doc12181688
Ref: 43ac12181688
Ref: distutils/commandref command-reference12181688
Ref: 43ad12181688
Ref: distutils/commandref reference12181688
Ref: 43ae12181688
Node: 安装模块 install 命令族12182091
Ref: distutils/commandref install-cmd12182213
Ref: 43af12182213
Ref: distutils/commandref installing-modules-the-install-command-family12182213
Ref: 43b012182213
Node: install_data12182481
Ref: distutils/commandref install-data12182584
Ref: 43b112182584
Ref: distutils/commandref install-data-cmd12182584
Ref: 43b212182584
Node: install_scripts12182705
Ref: distutils/commandref install-scripts12182808
Ref: 43b312182808
Ref: distutils/commandref install-scripts-cmd12182808
Ref: 43b412182808
Node: 创建源码发行包 sdist 命令12182929
Ref: distutils/commandref creating-a-source-distribution-the-sdist-command12183051
Ref: 43b512183051
Ref: distutils/commandref sdist-cmd12183051
Ref: 438812183051
Node: API参考引用12185410
Ref: distutils/apiref doc12185521
Ref: 43b612185521
Ref: distutils/apiref api-reference12185521
Ref: 43b712185521
Ref: distutils/apiref id112185521
Ref: 43b812185521
Ref: API参考引用-Footnote-112191222
Node: distutils core --- 分发包功能的核心12191322
Ref: distutils/apiref distutils-core-core-distutils-functionality12191465
Ref: 43b912191465
Ref: distutils/apiref module-distutils core12191465
Ref: 5412191465
Ref: distutils/apiref distutils core setup12191827
Ref: 3b7a12191827
Ref: distutils/apiref distutils core run_setup12198592
Ref: 43bc12198592
Ref: distutils/apiref distutils core Extension12201006
Ref: 436f12201006
Ref: distutils/apiref distutils core Distribution12208241
Ref: 43ba12208241
Ref: distutils/apiref distutils core Command12208751
Ref: 43bb12208751
Ref: distutils core --- 分发包功能的核心-Footnote-112208948
Ref: distutils core --- 分发包功能的核心-Footnote-212208985
Node: distutils ccompiler --- CCompiler基类12209034
Ref: distutils/apiref distutils-ccompiler-ccompiler-base-class12209229
Ref: 43bd12209229
Ref: distutils/apiref module-distutils ccompiler12209229
Ref: 3c12209229
Ref: distutils/apiref distutils ccompiler gen_lib_options12209710
Ref: 43bf12209710
Ref: distutils/apiref distutils ccompiler gen_preprocess_options12210194
Ref: 43c012210194
Ref: distutils/apiref distutils ccompiler get_default_compiler12210858
Ref: 43c112210858
Ref: distutils/apiref distutils ccompiler new_compiler12211315
Ref: 43c212211315
Ref: distutils/apiref distutils ccompiler show_compilers12212109
Ref: 43c312212109
Ref: distutils/apiref distutils ccompiler CCompiler12212300
Ref: 43be12212300
Ref: distutils/apiref distutils ccompiler CCompiler add_include_dir12213725
Ref: 43c412213725
Ref: distutils/apiref distutils ccompiler CCompiler set_include_dirs12214027
Ref: 43c512214027
Ref: distutils/apiref distutils ccompiler CCompiler add_library12214500
Ref: 43c612214500
Ref: distutils/apiref distutils ccompiler CCompiler set_libraries12215287
Ref: 43c712215287
Ref: distutils/apiref distutils ccompiler CCompiler add_library_dir12215582
Ref: 43c812215582
Ref: distutils/apiref distutils ccompiler CCompiler set_library_dirs12215988
Ref: 43c912215988
Ref: distutils/apiref distutils ccompiler CCompiler add_runtime_library_dir12216229
Ref: 43ca12216229
Ref: distutils/apiref distutils ccompiler CCompiler set_runtime_library_dirs12216390
Ref: 43cb12216390
Ref: distutils/apiref distutils ccompiler CCompiler define_macro12216676
Ref: 43cc12216676
Ref: distutils/apiref distutils ccompiler CCompiler undefine_macro12217044
Ref: 43cd12217044
Ref: distutils/apiref distutils ccompiler CCompiler add_link_object12217567
Ref: 43ce12217567
Ref: distutils/apiref distutils ccompiler CCompiler set_link_objects12217846
Ref: 43cf12217846
Ref: distutils/apiref distutils ccompiler CCompiler detect_language12218289
Ref: 43d012218289
Ref: distutils/apiref distutils ccompiler CCompiler find_library_file12218533
Ref: 43d112218533
Ref: distutils/apiref distutils ccompiler CCompiler has_function12218942
Ref: 43d212218942
Ref: distutils/apiref distutils ccompiler CCompiler library_dir_option12219344
Ref: 43d312219344
Ref: distutils/apiref distutils ccompiler CCompiler library_option12219499
Ref: 43d412219499
Ref: distutils/apiref distutils ccompiler CCompiler runtime_library_dir_option12219670
Ref: 43d512219670
Ref: distutils/apiref distutils ccompiler CCompiler set_executables12219841
Ref: 43d612219841
Ref: distutils/apiref distutils ccompiler CCompiler compile12221301
Ref: 43d812221301
Ref: distutils/apiref distutils ccompiler CCompiler create_static_lib12224083
Ref: 43d912224083
Ref: distutils/apiref distutils ccompiler CCompiler link12225363
Ref: 43da12225363
Ref: distutils/apiref distutils ccompiler CCompiler link_executable12228019
Ref: 43db12228019
Ref: distutils/apiref distutils ccompiler CCompiler link_shared_lib12228509
Ref: 43dc12228509
Ref: distutils/apiref distutils ccompiler CCompiler link_shared_object12229051
Ref: 43dd12229051
Ref: distutils/apiref distutils ccompiler CCompiler preprocess12229617
Ref: 43de12229617
Ref: distutils/apiref distutils ccompiler CCompiler executable_filename12230504
Ref: 43df12230504
Ref: distutils/apiref distutils ccompiler CCompiler library_filename12230808
Ref: 43e012230808
Ref: distutils/apiref distutils ccompiler CCompiler object_filenames12231213
Ref: 43e112231213
Ref: distutils/apiref distutils ccompiler CCompiler shared_object_filename12231449
Ref: 43e212231449
Ref: distutils/apiref distutils ccompiler CCompiler execute12231644
Ref: 43e312231644
Ref: distutils/apiref distutils ccompiler CCompiler spawn12231928
Ref: 43e512231928
Ref: distutils/apiref distutils ccompiler CCompiler mkpath12232077
Ref: 43e612232077
Ref: distutils/apiref distutils ccompiler CCompiler move_file12232255
Ref: 43e812232255
Ref: distutils/apiref distutils ccompiler CCompiler announce12232393
Ref: 43ea12232393
Ref: distutils/apiref distutils ccompiler CCompiler warn12232499
Ref: 43eb12232499
Ref: distutils/apiref distutils ccompiler CCompiler debug_print12232588
Ref: 43ec12232588
Node: distutils unixccompiler --- Unix C Compiler12232777
Ref: distutils/apiref distutils-unixccompiler-unix-c-compiler12232974
Ref: 43ed12232974
Ref: distutils/apiref module-distutils unixccompiler12232974
Ref: 6412232974
Node: distutils msvccompiler --- Microsoft Compiler12233741
Ref: distutils/apiref distutils-msvccompiler-microsoft-compiler12233942
Ref: 43ee12233942
Ref: distutils/apiref module-distutils msvccompiler12233942
Ref: 6012233942
Node: distutils bcppcompiler --- Borland Compiler12234930
Ref: distutils/apiref distutils-bcppcompiler-borland-compiler12235132
Ref: 43ef12235132
Ref: distutils/apiref module-distutils bcppcompiler12235132
Ref: 3b12235132
Node: distutils cygwincompiler --- Cygwin Compiler12235366
Ref: distutils/apiref distutils-cygwincompiler-cygwin-compiler12235569
Ref: 43f012235569
Ref: distutils/apiref module-distutils cygwinccompiler12235569
Ref: 5512235569
Node: distutils archive_util --- Archiving utilities12235951
Ref: distutils/apiref distutils-archive-util-archiving-utilities12236153
Ref: 43f112236153
Ref: distutils/apiref module-distutils archive_util12236153
Ref: 3a12236153
Ref: distutils/apiref distutils archive_util make_archive12236364
Ref: 43f212236364
Ref: distutils/apiref distutils archive_util make_tarball12237268
Ref: 43f312237268
Ref: distutils/apiref distutils archive_util make_zipfile12238049
Ref: 43f412238049
Node: distutils dep_util --- Dependency checking12238561
Ref: distutils/apiref distutils-dep-util-dependency-checking12238767
Ref: 43f512238767
Ref: distutils/apiref module-distutils dep_util12238767
Ref: 5712238767
Ref: distutils/apiref distutils dep_util newer12239056
Ref: 43f612239056
Ref: distutils/apiref distutils dep_util newer_pairwise12239394
Ref: 43f712239394
Ref: distutils/apiref distutils dep_util newer_group12239714
Ref: 43f812239714
Node: distutils dir_util --- Directory tree operations12240609
Ref: distutils/apiref distutils-dir-util-directory-tree-operations12240815
Ref: 43f912240815
Ref: distutils/apiref module-distutils dir_util12240815
Ref: 5812240815
Ref: distutils/apiref distutils dir_util mkpath12241021
Ref: 43e712241021
Ref: distutils/apiref distutils dir_util create_tree12241628
Ref: 43fa12241628
Ref: distutils/apiref distutils dir_util copy_tree12242187
Ref: 43fb12242187
Ref: distutils/apiref distutils dir_util remove_tree12243659
Ref: 43fd12243659
Ref: distutils dir_util --- Directory tree operations-Footnote-112243971
Node: distutils file_util --- Single file operations12244017
Ref: distutils/apiref distutils-file-util-single-file-operations12244237
Ref: 43fe12244237
Ref: distutils/apiref module-distutils file_util12244237
Ref: 5d12244237
Ref: distutils/apiref distutils file_util copy_file12244434
Ref: 43fc12244434
Ref: distutils/apiref distutils file_util move_file12245852
Ref: 43e912245852
Ref: distutils/apiref distutils file_util write_file12246250
Ref: 43ff12246250
Node: distutils util --- Miscellaneous other utility functions12246435
Ref: distutils/apiref distutils-util-miscellaneous-other-utility-functions12246648
Ref: 440012246648
Ref: distutils/apiref module-distutils util12246648
Ref: 6512246648
Ref: distutils/apiref distutils util get_platform12246886
Ref: 440112246886
Ref: distutils/apiref distutils util convert_path12248585
Ref: 440212248585
Ref: distutils/apiref distutils util change_root12249128
Ref: 440312249128
Ref: distutils/apiref distutils util check_environ12249451
Ref: 440412249451
Ref: distutils/apiref distutils util subst_vars12249868
Ref: 440512249868
Ref: distutils/apiref distutils util split_quoted12250682
Ref: 43d712250682
Ref: distutils/apiref distutils util execute12251255
Ref: 43e412251255
Ref: distutils/apiref distutils util strtobool12251769
Ref: 440612251769
Ref: distutils/apiref distutils util byte_compile12252120
Ref: 440712252120
Ref: distutils/apiref distutils util rfc822_escape12254131
Ref: 440812254131
Ref: distutils util --- Miscellaneous other utility functions-Footnote-112254422
Ref: distutils util --- Miscellaneous other utility functions-Footnote-212254471
Ref: distutils util --- Miscellaneous other utility functions-Footnote-312254520
Ref: distutils util --- Miscellaneous other utility functions-Footnote-412254569
Node: distutils dist --- The Distribution class12254617
Ref: distutils/apiref distutils-dist-the-distribution-class12254827
Ref: 440912254827
Ref: distutils/apiref module-distutils dist12254827
Ref: 5912254827
Node: distutils extension --- The Extension class12255069
Ref: distutils/apiref distutils-extension-the-extension-class12255263
Ref: 440a12255263
Ref: distutils/apiref module-distutils extension12255263
Ref: 5b12255263
Node: distutils debug --- Distutils debug mode12255482
Ref: distutils/apiref distutils-debug-distutils-debug-mode12255676
Ref: 440b12255676
Ref: distutils/apiref module-distutils debug12255676
Ref: 5612255676
Node: distutils errors --- Distutils exceptions12255812
Ref: distutils/apiref distutils-errors-distutils-exceptions12256031
Ref: 440c12256031
Ref: distutils/apiref module-distutils errors12256031
Ref: 5a12256031
Node: distutils fancy_getopt --- Wrapper around the standard getopt module12256531
Ref: distutils/apiref distutils-fancy-getopt-wrapper-around-the-standard-getopt-module12256751
Ref: 440d12256751
Ref: distutils/apiref module-distutils fancy_getopt12256751
Ref: 5c12256751
Ref: distutils/apiref distutils fancy_getopt fancy_getopt12257449
Ref: 440e12257449
Ref: distutils/apiref distutils fancy_getopt wrap_text12258105
Ref: 441012258105
Ref: distutils/apiref distutils fancy_getopt FancyGetopt12258211
Ref: 440f12258211
Ref: distutils/apiref distutils fancy_getopt FancyGetopt getopt12258774
Ref: 441112258774
Ref: distutils/apiref distutils fancy_getopt FancyGetopt get_option_order12259376
Ref: 441212259376
Ref: distutils/apiref distutils fancy_getopt FancyGetopt generate_help12259620
Ref: 441312259620
Node: distutils filelist --- The FileList class12259900
Ref: distutils/apiref distutils-filelist-the-filelist-class12260125
Ref: 441412260125
Ref: distutils/apiref module-distutils filelist12260125
Ref: 5e12260125
Node: distutils log --- Simple PEP 282-style logging12260346
Ref: distutils/apiref distutils-log-simple-pep-282-style-logging12260542
Ref: 441512260542
Ref: distutils/apiref module-distutils log12260542
Ref: 5f12260542
Node: distutils spawn --- Spawn a sub-process12260663
Ref: distutils/apiref distutils-spawn-spawn-a-sub-process12260874
Ref: 441612260874
Ref: distutils/apiref module-distutils spawn12260874
Ref: 6112260874
Node: distutils sysconfig --- System configuration information12261213
Ref: distutils/apiref distutils-sysconfig-system-configuration-information12261420
Ref: 441712261420
Ref: distutils/apiref module-distutils sysconfig12261420
Ref: 6212261420
Ref: distutils/apiref distutils sysconfig PREFIX12262263
Ref: 441812262263
Ref: distutils/apiref distutils sysconfig EXEC_PREFIX12262359
Ref: 441912262359
Ref: distutils/apiref distutils sysconfig get_config_var12262465
Ref: 441a12262465
Ref: distutils/apiref distutils sysconfig get_config_vars12262628
Ref: 441b12262628
Ref: distutils/apiref distutils sysconfig get_config_h_filename12263080
Ref: 441c12263080
Ref: distutils/apiref distutils sysconfig get_makefile_filename12263438
Ref: 441d12263438
Ref: distutils/apiref distutils sysconfig get_python_inc12263814
Ref: 441e12263814
Ref: distutils/apiref distutils sysconfig get_python_lib12264333
Ref: 441f12264333
Ref: distutils/apiref distutils sysconfig customize_compiler12265136
Ref: 442012265136
Ref: distutils/apiref distutils sysconfig set_python_build12265804
Ref: 442112265804
Node: distutils text_file --- The TextFile class12266125
Ref: distutils/apiref distutils-text-file-the-textfile-class12266337
Ref: 442212266337
Ref: distutils/apiref module-distutils text_file12266337
Ref: 6312266337
Ref: distutils/apiref distutils text_file TextFile12266650
Ref: 442312266650
Ref: distutils/apiref distutils text_file TextFile open12271174
Ref: 442712271174
Ref: distutils/apiref distutils text_file TextFile close12271321
Ref: 442612271321
Ref: distutils/apiref distutils text_file TextFile warn12271485
Ref: 442412271485
Ref: distutils/apiref distutils text_file TextFile readline12271995
Ref: 442812271995
Ref: distutils/apiref distutils text_file TextFile readlines12272673
Ref: 442912272673
Ref: distutils/apiref distutils text_file TextFile unreadline12272880
Ref: 442512272880
Node: distutils version --- Version number classes12273505
Ref: distutils/apiref distutils-version-version-number-classes12273721
Ref: 442a12273721
Ref: distutils/apiref module-distutils version12273721
Ref: 6612273721
Node: distutils cmd --- Abstract base class for Distutils commands12273834
Ref: distutils/apiref distutils-cmd-abstract-base-class-for-distutils-commands12274040
Ref: 442b12274040
Ref: distutils/apiref module-distutils cmd12274040
Ref: 3d12274040
Ref: distutils/apiref distutils cmd Command12274252
Ref: 43a912274252
Node: Creating a new Distutils command12275324
Ref: distutils/apiref creating-a-new-distutils-command12275537
Ref: 442f12275537
Ref: distutils/apiref distutils cmd Command initialize_options12276406
Ref: 442c12276406
Ref: distutils/apiref distutils cmd Command finalize_options12276854
Ref: 442d12276854
Ref: distutils/apiref distutils cmd Command run12277350
Ref: 442e12277350
Ref: distutils/apiref distutils cmd Command sub_commands12277776
Ref: 443012277776
Node: distutils command --- Individual Distutils commands12278760
Ref: distutils/apiref distutils-command-individual-distutils-commands12278965
Ref: 443112278965
Ref: distutils/apiref module-distutils command12278965
Ref: 3e12278965
Node: distutils command bdist --- Build a binary installer12279092
Ref: distutils/apiref distutils-command-bdist-build-a-binary-installer12279335
Ref: 443212279335
Ref: distutils/apiref module-distutils command bdist12279335
Ref: 3f12279335
Node: distutils command bdist_packager --- Abstract base class for packagers12279464
Ref: distutils/apiref distutils-command-bdist-packager-abstract-base-class-for-packagers12279713
Ref: 443312279713
Ref: distutils/apiref module-distutils command bdist_packager12279713
Ref: 4212279713
Node: distutils command bdist_dumb --- Build a "dumb" installer12279878
Ref: distutils/apiref distutils-command-bdist-dumb-build-a-dumb-installer12280149
Ref: 443412280149
Ref: distutils/apiref module-distutils command bdist_dumb12280149
Ref: 4012280149
Node: distutils command bdist_msi --- Build a Microsoft Installer binary package12280288
Ref: distutils/apiref distutils-command-bdist-msi-build-a-microsoft-installer-binary-package12280573
Ref: 443512280573
Ref: distutils/apiref module-distutils command bdist_msi12280573
Ref: 4112280573
Ref: distutils/apiref distutils command bdist_msi bdist_msi12280746
Ref: 443612280746
Ref: distutils command bdist_msi --- Build a Microsoft Installer binary package-Footnote-112281187
Node: distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM12281257
Ref: distutils/apiref distutils-command-bdist-rpm-build-a-binary-distribution-as-a-redhat-rpm-and-srpm12281546
Ref: 443712281546
Ref: distutils/apiref module-distutils command bdist_rpm12281546
Ref: 4312281546
Node: distutils command bdist_wininst --- Build a Windows installer12281739
Ref: distutils/apiref distutils-command-bdist-wininst-build-a-windows-installer12282009
Ref: 443812282009
Ref: distutils/apiref module-distutils command bdist_wininst12282009
Ref: 4412282009
Node: distutils command sdist --- Build a source distribution12282220
Ref: distutils/apiref distutils-command-sdist-build-a-source-distribution12282462
Ref: 443912282462
Ref: distutils/apiref module-distutils command sdist12282462
Ref: 5312282462
Node: distutils command build --- Build all files of a package12282597
Ref: distutils/apiref distutils-command-build-build-all-files-of-a-package12282845
Ref: 443a12282845
Ref: distutils/apiref module-distutils command build12282845
Ref: 4512282845
Node: distutils command build_clib --- Build any C libraries in a package12282982
Ref: distutils/apiref distutils-command-build-clib-build-any-c-libraries-in-a-package12283240
Ref: 443b12283240
Ref: distutils/apiref module-distutils command build_clib12283240
Ref: 4612283240
Node: distutils command build_ext --- Build any extensions in a package12283399
Ref: distutils/apiref distutils-command-build-ext-build-any-extensions-in-a-package12283668
Ref: 443c12283668
Ref: distutils/apiref module-distutils command build_ext12283668
Ref: 4712283668
Node: distutils command build_py --- Build the py/ pyc files of a package12283823
Ref: distutils/apiref distutils-command-build-py-build-the-py-pyc-files-of-a-package12284091
Ref: 443d12284091
Ref: distutils/apiref module-distutils command build_py12284091
Ref: 4812284091
Ref: distutils/apiref distutils command build_py build_py12284252
Ref: 443e12284252
Ref: distutils/apiref distutils command build_py build_py_2to312284298
Ref: 443f12284298
Node: distutils command build_scripts --- Build the scripts of a package12284913
Ref: distutils/apiref distutils-command-build-scripts-build-the-scripts-of-a-package12285170
Ref: 444012285170
Ref: distutils/apiref module-distutils command build_scripts12285170
Ref: 4912285170
Node: distutils command clean --- Clean a package build area12285327
Ref: distutils/apiref distutils-command-clean-clean-a-package-build-area12285575
Ref: 444112285575
Ref: distutils/apiref module-distutils command clean12285575
Ref: 4b12285575
Node: distutils command config --- Perform package configuration12286019
Ref: distutils/apiref distutils-command-config-perform-package-configuration12286248
Ref: 444212286248
Ref: distutils/apiref module-distutils command config12286248
Ref: 4c12286248
Node: distutils command install --- Install a package12286389
Ref: distutils/apiref distutils-command-install-install-a-package12286632
Ref: 444312286632
Ref: distutils/apiref module-distutils command install12286632
Ref: 4d12286632
Node: distutils command install_data --- Install data files from a package12286751
Ref: distutils/apiref distutils-command-install-data-install-data-files-from-a-package12287015
Ref: 444412287015
Ref: distutils/apiref module-distutils command install_data12287015
Ref: 4e12287015
Node: distutils command install_headers --- Install C/C++ header files from a package12287176
Ref: distutils/apiref distutils-command-install-headers-install-c-c-header-files-from-a-package12287463
Ref: 444512287463
Ref: distutils/apiref module-distutils command install_headers12287463
Ref: 4f12287463
Node: distutils command install_lib --- Install library files from a package12287646
Ref: distutils/apiref distutils-command-install-lib-install-library-files-from-a-package12287938
Ref: 444612287938
Ref: distutils/apiref module-distutils command install_lib12287938
Ref: 5012287938
Node: distutils command install_scripts --- Install script files from a package12288103
Ref: distutils/apiref distutils-command-install-scripts-install-script-files-from-a-package12288394
Ref: 444712288394
Ref: distutils/apiref module-distutils command install_scripts12288394
Ref: 5112288394
Node: distutils command register --- Register a module with the Python Package Index12288565
Ref: distutils/apiref distutils-command-register-register-a-module-with-the-python-package-index12288846
Ref: 444812288846
Ref: distutils/apiref module-distutils command register12288846
Ref: 5212288846
Ref: distutils command register --- Register a module with the Python Package Index-Footnote-112289193
Node: distutils command check --- Check the meta-data of a package12289242
Ref: distutils/apiref distutils-command-check-check-the-meta-data-of-a-package12289441
Ref: 444912289441
Ref: distutils/apiref module-distutils command check12289441
Ref: 4a12289441
Node: 安装Python模块（旧版）12289783
Ref: install/index doc12289928
Ref: 444a12289928
Ref: install/index install-index12289928
Ref: 80012289928
Ref: install/index installing-python-modules-legacy-version12289928
Ref: 444b12289928
Ref: 安装Python模块（旧版）-Footnote-112290948
Node: 概述<20>12291014
Ref: install/index inst-intro12291126
Ref: 444c12291126
Ref: install/index introduction12291126
Ref: 444d12291126
Node: 基于分布式系统的源代码分发12291973
Ref: install/index distutils-based-source-distributions12292059
Ref: 444e12292059
Ref: install/index inst-new-standard12292059
Ref: 444f12292059
Node: Standard Build and Install12293326
Ref: install/index inst-standard-install12293469
Ref: 445012293469
Ref: install/index standard-build-and-install12293469
Ref: 445112293469
Node: Platform variations12293871
Ref: install/index inst-platform-variations12293982
Ref: 445212293982
Ref: install/index platform-variations12293982
Ref: 445312293982
Node: Splitting the job up12294897
Ref: install/index inst-splitting-up12295035
Ref: 445412295035
Ref: install/index splitting-the-job-up12295035
Ref: 445512295035
Node: How building works12296339
Ref: install/index how-building-works12296480
Ref: 445612296480
Ref: install/index inst-how-build-works12296480
Ref: 445712296480
Node: How installation works12298205
Ref: install/index how-installation-works12298317
Ref: 445912298317
Ref: install/index inst-how-install-works12298317
Ref: 445a12298317
Node: Alternate Installation12303127
Ref: install/index alternate-installation12303275
Ref: 445d12303275
Ref: install/index inst-alt-install12303275
Ref: 445b12303275
Node: Alternate installation the user scheme12304963
Ref: install/index alternate-installation-the-user-scheme12305107
Ref: 445e12305107
Ref: install/index inst-alt-install-user12305107
Ref: 136912305107
Node: Alternate installation the home scheme12307506
Ref: install/index alternate-installation-the-home-scheme12307704
Ref: 445f12307704
Ref: install/index inst-alt-install-home12307704
Ref: 446012307704
Node: Alternate installation Unix the prefix scheme12309500
Ref: install/index alternate-installation-unix-the-prefix-scheme12309708
Ref: 446212309708
Ref: install/index inst-alt-install-prefix-unix12309708
Ref: 446312309708
Node: Alternate installation Windows the prefix scheme12313742
Ref: install/index alternate-installation-windows-the-prefix-scheme12313903
Ref: 446412313903
Ref: install/index inst-alt-install-prefix-windows12313903
Ref: 446512313903
Node: 自定义安装12315173
Ref: install/index custom-installation12315324
Ref: 446612315324
Ref: install/index inst-custom-install12315324
Ref: 445c12315324
Node: Modifying Python's Search Path12322315
Ref: install/index inst-search-path12322397
Ref: 446112322397
Ref: install/index modifying-python-s-search-path12322397
Ref: 446712322397
Node: Distutils Configuration Files12326119
Ref: install/index distutils-configuration-files12326283
Ref: 446812326283
Ref: install/index inst-config-files12326283
Ref: 445812326283
Node: Location and names of config files12326986
Ref: install/index inst-config-filenames12327117
Ref: 446912327117
Ref: install/index location-and-names-of-config-files12327117
Ref: 446a12327117
Node: Syntax of config files12331060
Ref: install/index inst-config-syntax12331191
Ref: 438312331191
Ref: install/index syntax-of-config-files12331191
Ref: 446b12331191
Node: Building Extensions Tips and Tricks12333105
Ref: install/index building-extensions-tips-and-tricks12333245
Ref: 446c12333245
Ref: install/index inst-building-ext12333245
Ref: 446d12333245
Node: Tweaking compiler/linker flags12333851
Ref: install/index inst-tweak-flags12334002
Ref: 446e12334002
Ref: install/index tweaking-compiler-linker-flags12334002
Ref: 446f12334002
Node: Using non-Microsoft compilers on Windows12337071
Ref: install/index inst-non-ms-compilers12337222
Ref: 447012337222
Ref: install/index using-non-microsoft-compilers-on-windows12337222
Ref: 447112337222
Node: Borland/CodeGear C++12337381
Ref: install/index borland-codegear-c12337509
Ref: 447212337509
Ref: Borland/CodeGear C++-Footnote-112339460
Ref: Borland/CodeGear C++-Footnote-212339571
Ref: Borland/CodeGear C++-Footnote-312339616
Node: GNU C / Cygwin / MinGW12339670
Ref: install/index gnu-c-cygwin-mingw12339798
Ref: 447312339798
Ref: GNU C / Cygwin / MinGW-Footnote-112340806
Ref: GNU C / Cygwin / MinGW-Footnote-212340886
Node: Older Versions of Python and MinGW12340987
Ref: install/index older-versions-of-python-and-mingw12341080
Ref: 447412341080
Ref: Older Versions of Python and MinGW-Footnote-112342739
Node: Python 模块索引12342804
Node: 索引12365384
Ref: 34d513931831
Ref: 41e113931861
Ref: using/cmdline audit_event_cpython_run_file_013931892
Ref: 34d413931923
Ref: howto/urllib2 basic-authentication13931954
Ref: using/cmdline audit_event_cpython_run_stdin_013931985
Ref: howto/urllib2 quick-reference-to-http-headers13932016
Ref: 41ed13932047

End Tag Table


Local Variables:
coding: utf-8
End:
